text
stringlengths 8
6.88M
|
|---|
#include "decifrar.hpp"
#include <iostream>
#include <cassert>
int main(int argc, char* argv[]) {
decifrar* decif = new decifrar();
assert(decif->decipher("FC HQWZP LPU JOMUFU HK TBFXIT TXJGPHFZH", "181246").compare("EU GOSTO DOS FILMES DE STEVEN SPIELBERG") == 0);
std::cout << "Everything good on decifrar class" << std::endl;
return 0;
}
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "noises.h"
using namespace std;
#define B 0x100
#define BM 0xff
#define N 0x1000
#define NP 12 /* 2^N */
#define NM 0xfff
static int p[B + B + 2];
static float g3[B + B + 2][3];
static float g2[B + B + 2][2];
static float g1[B + B + 2];
static int strt = 1;
#define s_curve(t) ( t * t * (3. - 2. * t) )
#define lerp(t, a, b) ( a + t * (b - a) )
#define setup(i,b0,b1,r0,r1)\
t = vec[i] + N;\
b0 = ((int)t) & BM;\
b1 = (b0+1) & BM;\
r0 = t - (int)t;\
r1 = r0 - 1.;
float noiseFunction(float *vec)
{
int bx0, bx1, by0, by1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v;
register int i, j;
if (strt) {
strt = 0;
initialiaze();
}
setup(0, bx0,bx1, rx0,rx1);
setup(1, by0,by1, ry0,ry1);
i = p[ bx0 ];
j = p[ bx1 ];
b00 = p[ i + by0 ];
b10 = p[ j + by0 ];
b01 = p[ i + by1 ];
b11 = p[ j + by1 ];
sx = s_curve(rx0);
sy = s_curve(ry0);
#define at2(rx,ry) ( rx * q[0] + ry * q[1] )
q = g2[ b00 ] ; u = at2(rx0,ry0);
q = g2[ b10 ] ; v = at2(rx1,ry0);
a = lerp(sx, u, v);
q = g2[ b01 ] ; u = at2(rx0,ry1);
q = g2[ b11 ] ; v = at2(rx1,ry1);
b = lerp(sx, u, v);
return lerp(sy, a, b);
}
static void normalize2(float v[2])
{
float s;
s = sqrt(v[0] * v[0] + v[1] * v[1]);
v[0] = v[0] / s;
v[1] = v[1] / s;
}
static void normalize3(float v[3])
{
float s;
s = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
v[0] = v[0] / s;
v[1] = v[1] / s;
v[2] = v[2] / s;
}
static void initialiaze(void)
{
int i, j, k;
for (i = 0 ; i < B ; i++) {
p[i] = i;
g1[i] = (float)((rand() % (B + B)) - B) / B;
for (j = 0 ; j < 2 ; j++)
g2[i][j] = (float)((rand() % (B + B)) - B) / B;
normalize2(g2[i]);
for (j = 0 ; j < 3 ; j++)
g3[i][j] = (float)((rand() % (B + B)) - B) / B;
normalize3(g3[i]);
}
while (--i) {
k = p[i];
p[i] = p[j = rand() % B];
p[j] = k;
}
for (i = 0 ; i < B + 2 ; i++) {
p[B + i] = p[i];
g1[B + i] = g1[i];
for (j = 0 ; j < 2 ; j++)
g2[B + i][j] = g2[i][j];
for (j = 0 ; j < 3 ; j++)
g3[B + i][j] = g3[i][j];
}
}
|
/*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY
- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*====================================================================*/
/*
* libversions.c
*
* Image library version number
* char *getImagelibVersions()
*/
#include "allheaders.h"
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif /* HAVE_CONFIG_H */
#if HAVE_LIBGIF
#include "gif_lib.h"
#endif
#if HAVE_LIBJPEG
/* jpeglib.h includes jconfig.h, which makes the error of setting
* #define HAVE_STDLIB_H
* which conflicts with config_auto.h (where it is set to 1) and results
* for some gcc compiler versions in a warning. The conflict is harmless
* but we suppress it by undefining the variable. */
#undef HAVE_STDLIB_H
#include "jpeglib.h"
#include "jerror.h"
#endif
#if HAVE_LIBPNG
#include "png.h"
#endif
#if HAVE_LIBTIFF
#include "tiffio.h"
#endif
#if HAVE_LIBZ
#include "zlib.h"
#endif
#if HAVE_LIBWEBP
#include "webp/encode.h"
#endif
#if HAVE_LIBJP2K /* assuming it's 2.1 */
#include "openjpeg-2.1/openjpeg.h"
#endif
#define stringJoinInPlace(s1, s2) \
{ tempStrP = stringJoin((s1),(s2)); FREE(s1); (s1) = tempStrP; }
/*---------------------------------------------------------------------*
* Image Library Version number *
*---------------------------------------------------------------------*/
/*!
* getImagelibVersions()
*
* Return: string of version numbers; e.g.,
* libgif 5.0.3
* libjpeg 8b
* libpng 1.4.3
* libtiff 3.9.5
* zlib 1.2.5
* libwebp 0.3.0
* libopenjp2 2.1.0
*
* Notes:
* (1) The caller has responsibility to free the memory.
*/
char *
getImagelibVersions()
{
char buf[128];
l_int32 first = TRUE;
#if HAVE_LIBJPEG
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr err;
char buffer[JMSG_LENGTH_MAX];
#endif
char *tempStrP;
char *versionNumP;
char *nextTokenP;
char *versionStrP = stringNew("");
#if HAVE_LIBGIF
first = FALSE;
stringJoinInPlace(versionStrP, "libgif ");
#ifdef GIFLIB_MAJOR
snprintf(buf, sizeof(buf), "%d.%d.%d", GIFLIB_MAJOR, GIFLIB_MINOR,
GIFLIB_RELEASE);
#else
stringCopy(buf, "4.1.6(?)", sizeof(buf));
#endif
stringJoinInPlace(versionStrP, buf);
#endif
#if HAVE_LIBJPEG
cinfo.err = jpeg_std_error(&err);
err.msg_code = JMSG_VERSION;
(*err.format_message) ((j_common_ptr ) &cinfo, buffer);
if (!first)
{
stringJoinInPlace(versionStrP, " : ");
}
first = FALSE;
stringJoinInPlace(versionStrP, "libjpeg ");
versionNumP = strtokSafe(buffer, " ", &nextTokenP);
stringJoinInPlace(versionStrP, versionNumP);
FREE(versionNumP);
#endif
#if HAVE_LIBPNG
if (!first)
{
stringJoinInPlace(versionStrP, " : ");
}
first = FALSE;
stringJoinInPlace(versionStrP, "libpng ");
stringJoinInPlace(versionStrP, png_get_libpng_ver(NULL));
#endif
#if HAVE_LIBTIFF
if (!first)
{
stringJoinInPlace(versionStrP, " : ");
}
first = FALSE;
stringJoinInPlace(versionStrP, "libtiff ");
versionNumP = strtokSafe((char *)TIFFGetVersion(), " \n", &nextTokenP);
FREE(versionNumP);
versionNumP = strtokSafe(NULL, " \n", &nextTokenP);
FREE(versionNumP);
versionNumP = strtokSafe(NULL, " \n", &nextTokenP);
stringJoinInPlace(versionStrP, versionNumP);
FREE(versionNumP);
#endif
#if HAVE_LIBZ
if (!first)
{
stringJoinInPlace(versionStrP, " : ");
}
first = FALSE;
stringJoinInPlace(versionStrP, "zlib ");
stringJoinInPlace(versionStrP, zlibVersion());
#endif
#if HAVE_LIBWEBP
{
l_int32 val;
char buf[32];
if (!first)
{
stringJoinInPlace(versionStrP, " : ");
}
first = FALSE;
stringJoinInPlace(versionStrP, "libwebp ");
val = WebPGetEncoderVersion();
snprintf(buf, sizeof(buf), "%d.%d.%d", val >> 16, (val >> 8) & 0xff,
val & 0xff);
stringJoinInPlace(versionStrP, buf);
}
#endif
#if HAVE_LIBJP2K
{
const char *version;
if (!first)
{
stringJoinInPlace(versionStrP, " : ");
}
first = FALSE;
stringJoinInPlace(versionStrP, "libopenjp2 ");
version = opj_version();
stringJoinInPlace(versionStrP, version);
}
#endif
stringJoinInPlace(versionStrP, "\n");
return versionStrP;
}
|
/*!
* \file
* \author David Saxon
* \brief Inline definitions for UTF-8 implementations of the
* byte_to_symbol_index function.
*
* \copyright Copyright (c) 2018, The Arcane Initiative
* All rights reserved.
*
* \license BSD 3-Clause License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DEUS_UNICODEVIEWIMPL_UTF8COMPUTESYMBOLLENGTH_INL_
#define DEUS_UNICODEVIEWIMPL_UTF8COMPUTESYMBOLLENGTH_INL_
#include <codecvt>
#include <locale>
#include "deus/Exceptions.hpp"
namespace deus
{
DEUS_VERSION_NS_BEGIN
namespace utf8_inl
{
DEUS_FORCE_INLINE void compute_symbol_length_naive(
const char* in_data,
std::size_t in_byte_length,
std::size_t& out_symbol_length)
{
out_symbol_length = 0;
std::size_t next_check = 0;
for(std::size_t i = 0; i < in_byte_length - 1; ++i)
{
const char* c = in_data + i;
// determine UTF-8 symbols
if(next_check <= 0)
{
// single character byte
if((*c & 0x80) == 0)
{
next_check = 0;
}
// 2 byte character
else if((*c & 0xE0) == 0xC0)
{
next_check = 1;
}
// 3 byte character
else if((*c & 0xF0) == 0xE0)
{
next_check = 2;
}
// 4 byte character
else if((*c & 0xF8) == 0xF0)
{
next_check = 3;
}
else
{
deus::UnicodeView character(c, 1, deus::Encoding::kASCII);
throw deus::UTF8Error(
"Invalid leading byte in UTF-8 string: '" + character +
": <" + character.bytes_as_hex().front() + ">"
);
}
++out_symbol_length;
}
else
{
--next_check;
}
}
}
DEUS_FORCE_INLINE void compute_symbol_length_wstring_convert(
const char* in_data,
std::size_t in_byte_length,
std::size_t& out_symbol_length)
{
out_symbol_length = 0;
// null data?
if(in_data == nullptr)
{
return;
}
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> convert;
std::string str(in_data, in_byte_length - 1);
std::wstring wstr = convert.from_bytes(str);
out_symbol_length = wstr.length();
}
DEUS_FORCE_INLINE void compute_symbol_length_byte_jump(
const char* in_data,
std::size_t in_byte_length,
std::size_t& out_symbol_length)
{
out_symbol_length = 0;
for(std::size_t i = 0; i < in_byte_length - 1;)
{
const char* byte_ptr = in_data + i;
// use the jump table to determine how many bytes we should jump to the
// next symbol
const char jump_index = ((*byte_ptr) >> 4) & 0x0F;
const std::size_t jump =
static_cast<std::size_t>(utf8_inl::g_jump_table[jump_index]);
i += jump;
++out_symbol_length;
}
}
DEUS_FORCE_INLINE void compute_symbol_length_word_batching(
const char* in_data,
std::size_t in_byte_length,
std::size_t& out_symbol_length)
{
out_symbol_length = 0;
std::size_t start_addr = (std::size_t) in_data;
constexpr std::size_t word_size = sizeof(std::size_t);
// determine the point of word alignment
std::size_t align_at = word_size - (start_addr % word_size);
// naive check the first bits until we're word aligned
std::size_t iterate_to = align_at;
if(in_byte_length - 1 < align_at)
{
iterate_to = in_byte_length - 1;
}
std::size_t i = 0;
while(i < iterate_to)
{
const char* byte_ptr = in_data + i;
// use the jump table to determine how many bytes we should jump to the
// next symbol
const char jump_index = ((*byte_ptr) >> 4) & 0x0F;
const std::size_t jump =
static_cast<std::size_t>(utf8_inl::g_jump_table[jump_index]);
i += jump;
++out_symbol_length;
}
i = iterate_to;
// complete
if(i >= in_byte_length - 1)
{
return;
}
// magic numbers
constexpr std::size_t magic_1 =
(word_size > 4)
?
0x8080808080808080L
:
0x80808080UL;
constexpr std::size_t magic_2 =
(word_size > 4)
?
0x0101010101010101L
:
0x01010101UL;
constexpr std::size_t magic_3 =
(word_size > 4)
?
0x4040404040404040L
:
0x40404040UL;
// TODO: should replace literal 8s for word size
// calculate when the final iteration will occur
std::size_t final_iteration = (in_byte_length - i) / word_size;
final_iteration = i + (final_iteration * word_size) - 8;
// calculate how many bytes need masking on the final iterator -- at least
// one byte (the null terminator) always needs masking on the final
// iteration
std::size_t mask_size = (std::size_t) (in_data + in_byte_length);
mask_size = ((mask_size - 1) % word_size) * 8;
// TODO: word size?
const std::size_t end_or_mask =
0x8080808080808080UL & (0xFFFFFFFFFFFFFFFF << mask_size);
std::size_t and_shift = 0xFFFFFFFFFFFFFFFF >> (64 - mask_size);
// compiler bug? 0xFFFFFFFFFFFFFFFF >> (64 - 0) does not equal
// 0x0000000000000000 (but 0xFFFFFFFFFFFFFFFF >> 64 does...)
if(mask_size == 0)
{
and_shift = 0;
}
std::size_t end_and_mask = 0x8080808080808080UL | and_shift;
// read word-aligned - even though we may have "read" the first few bytes it
// it won't affect the following algorithm since the read bytes have the
// format 10xxxxxx
for(; i < in_byte_length; i += word_size)
{
std::size_t word = *((std::size_t*) (in_data + i));
// apply the final iteration mask?
if(in_byte_length - i <= word_size)
{
word |= end_or_mask;
word &= end_and_mask;
}
// bias for ascii strings
std::size_t symbol_counter = word & magic_1;
if(symbol_counter == 0)
{
out_symbol_length += word_size;
continue;
}
// count all the symbols that don't have the format 10xxxxxx, since
// these are supplementary bytes
symbol_counter = symbol_counter & (((~word) & magic_3) << 1);
symbol_counter = ~symbol_counter;
symbol_counter = (symbol_counter >> 7) & magic_2;
const char* h_add = (const char*) (&symbol_counter);
out_symbol_length +=
h_add[0] + h_add[1] + h_add[2] + h_add[3];
if(word_size > 4)
{
out_symbol_length +=
h_add[4] + h_add[5] + h_add[6] + h_add[7];
}
}
}
} // namespace utf8_inl
DEUS_VERSION_NS_END
} // namespace deus
#endif
|
#include <string>
#ifndef IO_H
#define IO_H
char getch();
char getche();
void reset();
void clean_stdin();
std::string color(const std::string text, const std::string color);
std::string underline(const std::string text, const std::string color);
#endif
|
#ifndef GENERIC_MEX_IO
#define GENERIC_MEX_IO
#include <matrix.h>
#include <mex.h>
#undef printf
#include <cstdarg>
#include <vector>
#include <unordered_map>
#include <functional>
#include <cstdio>
#include <string.h>
#include "MexMem.hpp"
#include "LambdaToFunction.hpp"
#include "MexTypeTraits.hpp"
#ifdef _MSC_VER
# define STRCMPI_FUNC _strcmpi
#elif defined __GNUC__
# if (__GNUC__ > 5) || (__GNUC__ == 5)
# define STRCMPI_FUNC strcasecmp
# endif
#endif
typedef std::unordered_map<std::string, std::pair<void*, size_t> > StructArgTable;
//////////////////////////////////////////////////////////////////
///////////////////// BASIC HELPER FUNCTIONS /////////////////////
//////////////////////////////////////////////////////////////////
inline void vWriteOutput(const char *Format, std::va_list Args) {
char buffertemp[256], bufferFinal[256];
vsnprintf(buffertemp, 256, Format, Args);
char* tempIter = buffertemp;
char* FinalIter = bufferFinal;
for (; *tempIter != 0; ++tempIter, ++FinalIter) {
if (*tempIter == '%') {
*FinalIter = '%';
++FinalIter;
*FinalIter = '%';
}
else {
*FinalIter = *tempIter;
}
}
*FinalIter = 0;
#ifdef MEX_LIB
mexPrintf(bufferFinal);
mexEvalString("drawnow();");
#elif defined MEX_EXE
std::printf(bufferFinal);
std::fflush(stdout);
#endif
}
inline void WriteOutput(const char *Format, ...) {
std::va_list Args;
va_start(Args, Format);
vWriteOutput(Format, Args);
va_end(Args);
}
template <typename ExType>
inline void WriteException(ExType Exception, const char *Format, ...) {
std::va_list Args;
va_start(Args, Format);
vWriteOutput(Format, Args);
va_end(Args);
throw Exception;
}
inline void StringSplit(const char* InputString, const char* DelimString, std::vector<std::string> &SplitStringVect,
bool includeBlanks = false){
std::string tempInputString(InputString);
SplitStringVect.resize(0);
do{
size_t DelimPos = tempInputString.find_first_of(DelimString);
std::string currentSubString;
if (DelimPos != std::string::npos){
currentSubString = tempInputString.substr(0, DelimPos);
tempInputString = tempInputString.substr(DelimPos + 1);
}
else{
currentSubString = tempInputString;
tempInputString = "";
}
if (includeBlanks || currentSubString != ""){
SplitStringVect.push_back(currentSubString);
}
} while (tempInputString.length() != 0);
}
inline mxArrayPtr assignmxStruct(const std::initializer_list<const char*> &FieldNames,
const std::initializer_list<mxArrayPtr> &FieldmxArrays) {
// This creates an Mex Struct with the given parameters
// Validate Size equality of FieldNames and FieldmxArrays
if (FieldNames.size() != FieldmxArrays.size()) {
WriteException(ExOps::EXCEPTION_INVALID_INPUT,
"The Size of FieldNames (%d) must be equal to the size of FieldmxArrays (%d)",
FieldNames.size(), FieldmxArrays.size());
}
size_t Size[] = {1, 1};
mxArrayPtr ReturnStruct = mxCreateStructArray(2, Size, 0, nullptr);
auto NInputs = FieldNames.size();
for(size_t i=0; i < NInputs; ++i) {
mxAddField(ReturnStruct, FieldNames.begin()[i]);
mxSetField(ReturnStruct, 0, FieldNames.begin()[i], FieldmxArrays.begin()[i]);
}
return ReturnStruct;
}
//////////////////////////////////////////////////////////////////
//////////////////////// OUTPUT FUNCTIONS ////////////////////////
//////////////////////////////////////////////////////////////////
template<typename TypeDest, typename T> inline mxArrayPtr assignmxArray(T &ScalarOut){
mxClassID ClassID = GetMexType<TypeDest>::typeVal;
mxArrayPtr ReturnPointer;
if (std::is_arithmetic<T>::value){
ReturnPointer = mxCreateNumericMatrix_730(1, 1, ClassID, mxREAL);
*reinterpret_cast<TypeDest *>(mxGetData(ReturnPointer)) = (TypeDest)ScalarOut;
}
else{
ReturnPointer = mxCreateNumericMatrix_730(0, 0, ClassID, mxREAL);
}
return ReturnPointer;
}
template<typename T, class Al, class B=typename std::enable_if<std::is_same<Al, mxAllocator>::value>::type>
inline mxArrayPtr assignmxArray(MexMatrix<T, Al> &MatrixOut){
mxClassID ClassID = GetMexType<T>::typeVal;
mxArrayPtr ReturnPointer = mxCreateNumericMatrix_730(0, 0, ClassID, mxREAL);
MatrixOut.trim();
if (MatrixOut.ncols() && MatrixOut.nrows()){
mxSetM(ReturnPointer, MatrixOut.ncols());
mxSetN(ReturnPointer, MatrixOut.nrows());
mxSetData(ReturnPointer, MatrixOut.releaseArray());
}
return ReturnPointer;
}
template<typename T, class Al, class B=typename std::enable_if<std::is_same<Al, mxAllocator>::value>::type>
inline mxArrayPtr assignmxArray(MexVector<T, Al> &VectorOut){
mxClassID ClassID = GetMexType<T>::typeVal;
mxArrayPtr ReturnPointer = mxCreateNumericMatrix_730(0, 0, ClassID, mxREAL);
VectorOut.trim();
if (VectorOut.size()){
mxSetM(ReturnPointer, VectorOut.size());
mxSetN(ReturnPointer, 1);
mxSetData(ReturnPointer, VectorOut.releaseArray());
}
return ReturnPointer;
}
template<typename T, class Al, class AlSub>
inline mxArrayPtr assignmxArray(MexVector<MexVector<T, Al>, AlSub> &VectorOut){
mxClassID ClassID = GetMexType<T>::typeVal;
mxArrayPtr ReturnPointer;
VectorOut.trim();
if (VectorOut.size()){
ReturnPointer = mxCreateCellMatrix(VectorOut.size(), 1);
size_t VectVectSize = VectorOut.size();
for (int i = 0; i < VectVectSize; ++i){
mxSetCell(ReturnPointer, i, assignmxArray(VectorOut[i]));
}
}
else{
ReturnPointer = mxCreateCellMatrix_730(0, 0);
}
return ReturnPointer;
}
struct MexMemInputOps{
bool IS_REQUIRED;
bool IS_NONEMPTY;
bool NO_EXCEPT;
bool QUIET;
int REQUIRED_SIZE;
MexMemInputOps(){
IS_REQUIRED = false;
IS_NONEMPTY = false;
NO_EXCEPT = false;
QUIET = false;
REQUIRED_SIZE = -1;
}
MexMemInputOps(
bool IS_REQUIRED_,
bool IS_NONEMPTY_ = false,
int REQUIRED_SIZE_ = -1,
bool NO_EXCEPT_ = false,
bool QUIET_ = false
){
IS_REQUIRED = IS_REQUIRED_;
IS_NONEMPTY = IS_NONEMPTY_;
NO_EXCEPT = NO_EXCEPT_;
QUIET = QUIET_;
REQUIRED_SIZE = REQUIRED_SIZE_;
}
};
//////////////////////////////////////////////////////////////////
//////////////// GENERAL PURPOSE HELPER FUNCTIONS ////////////////
//////////////////////////////////////////////////////////////////
inline MexMemInputOps getInputOps_v(int nOptions, va_list Options) {
MexMemInputOps InputOps;
for (int i = 0; i < nOptions; ++i) {
char *CurrOption = va_arg(Options, char*);
if (!STRCMPI_FUNC("IS_REQUIRED", CurrOption)) {
InputOps.IS_REQUIRED = true;
}
else if (!STRCMPI_FUNC("IS_NONEMPTY", CurrOption)) {
InputOps.IS_NONEMPTY = true;
}
else if (!STRCMPI_FUNC("QUIET", CurrOption)) {
InputOps.QUIET = true;
}
else if (!STRCMPI_FUNC("NO_EXCEPT", CurrOption)) {
InputOps.NO_EXCEPT = true;
}
else if (!STRCMPI_FUNC("REQUIRED_SIZE", CurrOption)) {
InputOps.REQUIRED_SIZE = va_arg(Options, int);
}
}
return InputOps;
}
inline MexMemInputOps getInputOps(int nOptions = 0, ...) {
MexMemInputOps ReturnOps;
va_list OptionArray;
va_start(OptionArray, nOptions);
ReturnOps = getInputOps_v(nOptions, OptionArray);
va_end(OptionArray);
return ReturnOps;
}
template <typename FieldCppType = void>
static const mxArray* getValidStructField(const mxArray* InputStruct, const char * FieldName, const MexMemInputOps & InputOps = MexMemInputOps()){
// Processing Struct Name Heirarchy
std::vector<std::string> NameHeirarchyVect;
const mxArray* InputStructField = InputStruct;
StringSplit(FieldName, ".", NameHeirarchyVect);
// Validating wether InputStruct is not nullptr
if (InputStruct == nullptr)
return nullptr;
int NameHeirarchyDepth = NameHeirarchyVect.size();
for (int i = 0; i < NameHeirarchyDepth - 1; ++i){
InputStructField = mxGetField(InputStructField, 0, NameHeirarchyVect[i].data());
if (InputStructField == nullptr || mxIsEmpty(InputStructField) || mxGetClassID(InputStructField) != mxSTRUCT_CLASS){
// If it is an invalid struct class
if (InputOps.IS_REQUIRED){
if (!InputOps.QUIET)
WriteOutput("The required field '%s' is either empty or non-existant.\n", FieldName);
if (!InputOps.NO_EXCEPT)
throw ExOps::EXCEPTION_INVALID_INPUT;
}
return nullptr;
}
}
// Extracting Final Vector
InputStructField = mxGetField(InputStructField, 0, NameHeirarchyVect.back().data());
// Validate Type of Field
if (!FieldInfo<FieldCppType>::CheckType(InputStructField)) {
if (!InputOps.QUIET)
WriteOutput("The Field '%s' does not match the type required.\n", FieldName);
if (!InputOps.NO_EXCEPT)
throw ExOps::EXCEPTION_INVALID_INPUT;
}
// Calculate Number of elements
size_t NumElems = FieldInfo<FieldCppType>::getSize(InputStructField);
// If Field exists with non-empty data
if (InputStructField != nullptr) {
if (InputOps.REQUIRED_SIZE != -1 && NumElems > 0 && InputOps.REQUIRED_SIZE != NumElems) {
if (!InputOps.QUIET)
WriteOutput("The size of %s is required to be %d, it is currenty %d\n", FieldName, InputOps.REQUIRED_SIZE, NumElems);
if (!InputOps.NO_EXCEPT)
throw ExOps::EXCEPTION_INVALID_INPUT;
return nullptr;
}
else if(NumElems == 0 && InputOps.IS_NONEMPTY) {
if (!InputOps.QUIET)
WriteOutput("The field %s is required to be non-empty\n", FieldName);
if (!InputOps.NO_EXCEPT)
throw ExOps::EXCEPTION_INVALID_INPUT;
return nullptr;
}
else {
return InputStructField;
}
}
// If no data was found
else if (InputOps.IS_REQUIRED) {
if (!InputOps.QUIET)
WriteOutput("The required field '%s' is either empty or non-existant.\n", FieldName);
if (!InputOps.NO_EXCEPT)
throw ExOps::EXCEPTION_INVALID_INPUT;
return nullptr;
}
return nullptr;
}
template<typename TypeRHS, typename TypeLHS>
inline typename MexVector<TypeLHS>::iterator MexTransform(
typename MexVector<TypeRHS>::iterator const RHSVectorBeg,
typename MexVector<TypeRHS>::iterator const RHSVectorEnd,
typename MexVector<TypeLHS>::iterator const LHSVectorBeg,
std::function<void(TypeLHS &, TypeRHS &)> transform_func){
auto RHSIter = RHSVectorBeg;
auto LHSIter = LHSVectorBeg;
for (; RHSIter != RHSVectorEnd; ++RHSIter, ++LHSIter){
transform_func(*LHSIter , *RHSIter);
}
return LHSIter;
}
template<typename TypeRHS, typename TypeLHS>
inline typename MexVector<TypeLHS>::iterator MexTransform(
typename MexVector<TypeRHS>::iterator RHSVectorBeg,
typename MexVector<TypeRHS>::iterator RHSVectorEnd,
typename MexVector<TypeLHS>::iterator LHSVectorBeg,
typename std::function<TypeLHS(TypeRHS &)> transform_func){
auto RHSIter = RHSVectorBeg;
auto LHSIter = LHSVectorBeg;
for (; RHSIter != RHSVectorEnd; ++RHSIter, ++LHSIter){
*LHSIter = transform_func(*RHSIter);
}
return LHSIter;
}
//////////////////////////////////////////////////////////////////
////////////////////////// SCALAR INPUT //////////////////////////
//////////////////////////////////////////////////////////////////
// -------- From mxArray -------- //
template <typename TypeSrc, typename TypeDest>
inline void getInputfrommxArray(const mxArray* InputArray, TypeDest &ScalarIn){
if (InputArray != nullptr && !mxIsEmpty(InputArray))
ScalarIn = (TypeDest)(*reinterpret_cast<TypeSrc *>(mxGetData(InputArray)));
}
template <typename TypeSrc, typename TypeDest>
inline void getInputfrommxArray(const mxArray* InputArray, TypeDest &ScalarIn,
TypeDest(*casting_func)(TypeSrc &SrcElem)) {
if (InputArray != nullptr && !mxIsEmpty(InputArray))
ScalarIn = casting_func(*reinterpret_cast<TypeSrc *>(mxGetData(InputArray)));
}
template <typename TypeSrc, typename TypeDest>
inline void getInputfrommxArray(const mxArray* InputArray, TypeDest &ScalarIn,
std::function<TypeDest(TypeSrc &)> &casting_func){
if (InputArray != nullptr && !mxIsEmpty(InputArray))
ScalarIn = casting_func(*reinterpret_cast<TypeSrc *>(mxGetData(InputArray)));
}
// -------- From Structure Field -------- //
template <typename TypeSrc, typename TypeDest>
inline int getInputfromStruct(const mxArray* InputStruct, const char* FieldName, TypeDest &ScalarIn,
MexMemInputOps InputOps = MexMemInputOps()) {
InputOps.REQUIRED_SIZE = -1;
const mxArray* StructFieldPtr = getValidStructField<TypeSrc>(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<TypeSrc>(StructFieldPtr, ScalarIn);
return 0;
}
else {
return 1;
}
}
template <typename TypeSrc, typename TypeDest>
inline int getInputfromStruct(const mxArray* InputStruct, const char* FieldName, TypeDest &ScalarIn,
TypeDest(*casting_func)(TypeSrc &SrcElem),
MexMemInputOps InputOps = MexMemInputOps()) {
InputOps.REQUIRED_SIZE = -1;
const mxArray* StructFieldPtr = getValidStructField<TypeSrc>(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<TypeSrc>(StructFieldPtr, ScalarIn, casting_func);
return 0;
}
else {
return 1;
}
}
template <typename TypeSrc, typename TypeDest>
inline int getInputfromStruct(const mxArray* InputStruct, const char* FieldName, TypeDest &ScalarIn,
std::function<TypeDest(TypeSrc &)> &casting_func,
MexMemInputOps InputOps = MexMemInputOps()) {
InputOps.REQUIRED_SIZE = -1;
const mxArray* StructFieldPtr = getValidStructField<TypeSrc>(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<TypeSrc>(StructFieldPtr, ScalarIn, casting_func);
return 0;
}
else {
return 1;
}
}
//////////////////////////////////////////////////////////////////
////////////////////////// VECTOR INPUT //////////////////////////
//////////////////////////////////////////////////////////////////
// -------- From mxArray -------- //
template <typename TypeSrc, typename TypeDest, class AlDest>
inline void getInputfrommxArray(
const mxArray* InputArray,
MexVector<TypeDest, AlDest> &VectorIn) {
if (InputArray != nullptr && !mxIsEmpty(InputArray)) {
size_t NumElems = mxGetNumberOfElements(InputArray);
TypeSrc* tempArrayPtr = reinterpret_cast<TypeSrc*>(mxGetData(InputArray));
VectorIn.resize(NumElems); // This will not erase old data
for (int i = 0; i < NumElems; ++i) {
VectorIn[i] = (TypeDest)tempArrayPtr[i];
}
}
}
template <typename TypeSrc, typename TypeDest, class AlDest>
inline void getInputfrommxArray(
const mxArray* InputArray,
MexVector<TypeDest, AlDest> &VectorIn,
void(*casting_func)(TypeSrc &SrcElem, TypeDest &DestElem)) {
if (InputArray != nullptr && !mxIsEmpty(InputArray)) {
size_t NumElems = mxGetNumberOfElements(InputArray);
TypeSrc* tempArrayPtr = reinterpret_cast<TypeSrc*>(mxGetData(InputArray));
VectorIn.resize(NumElems);
for (int i = 0; i < NumElems; ++i) {
casting_func(tempArrayPtr[i], VectorIn[i]);
}
}
}
template <typename TypeSrc, typename TypeDest, class AlDest>
inline void getInputfrommxArray(
const mxArray* InputArray,
MexVector<TypeDest, AlDest> &VectorIn,
std::function<void(TypeSrc &, TypeDest &)> &casting_func) {
if (InputArray != nullptr && !mxIsEmpty(InputArray)) {
size_t NumElems = mxGetNumberOfElements(InputArray);
TypeSrc* tempArrayPtr = reinterpret_cast<TypeSrc*>(mxGetData(InputArray));
VectorIn.resize(NumElems);
for (int i = 0; i < NumElems; ++i) {
casting_func(tempArrayPtr[i], VectorIn[i]);
}
}
}
// -------- From Structure Field -------- //
template <typename TypeSrc, typename TypeDest, class AlDest>
inline int getInputfromStruct(
const mxArray* InputStruct, const char* FieldName,
MexVector<TypeDest, AlDest> &VectorIn,
MexMemInputOps InputOps = MexMemInputOps()) {
// Processing Data
const mxArray* StructFieldPtr = getValidStructField<MexVector<TypeSrc> >(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<TypeSrc, TypeDest>(StructFieldPtr, VectorIn);
return 0;
}
else {
return 1;
}
}
template <typename TypeSrc, typename TypeDest, class AlDest>
inline int getInputfromStruct(
const mxArray* InputStruct, const char* FieldName,
MexVector<TypeDest, AlDest> &VectorIn,
void(*casting_func)(TypeSrc &SrcElem, TypeDest &DestElem),
MexMemInputOps InputOps = MexMemInputOps()) {
// Processing Data
const mxArray* StructFieldPtr = getValidStructField<MexVector<TypeSrc> >(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<TypeSrc, TypeDest>(StructFieldPtr, VectorIn, casting_func);
return 0;
}
else {
return 1;
}
}
template <typename TypeSrc, typename TypeDest, class AlDest>
inline int getInputfromStruct(
const mxArray* InputStruct, const char* FieldName,
MexVector<TypeDest, AlDest> &VectorIn,
std::function<void(TypeSrc &, TypeDest &)> &casting_func,
MexMemInputOps InputOps = MexMemInputOps()) {
// Processing Data
const mxArray* StructFieldPtr = getValidStructField<MexVector<TypeSrc> >(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<TypeSrc, TypeDest>(StructFieldPtr, VectorIn, casting_func);
return 0;
}
else {
return 1;
}
}
//////////////////////////////////////////////////////////////////
////////////////////////// MATRIX INPUT //////////////////////////
//////////////////////////////////////////////////////////////////
// -------- From mxArray -------- //
template <typename TypeSrc, typename TypeDest, class AlDest>
inline void getInputfrommxArray(
const mxArray* InputArray,
MexMatrix<TypeDest, AlDest> &MatrixIn) {
if (InputArray != nullptr && !mxIsEmpty(InputArray)) {
size_t NDim0 = FieldInfo<decltype(MatrixIn)>::getSize(InputArray, 0);
size_t NDim1 = FieldInfo<decltype(MatrixIn)>::getSize(InputArray, 1);
TypeSrc* tempArrayPtr = reinterpret_cast<TypeSrc*>(mxGetData(InputArray));
MatrixIn.resize(NDim1, NDim0); // This will not erase old data
for (int i=0; i<NDim1; ++i) {
for (int j=0; j<NDim0; ++j) {
MatrixIn(i,j) = (TypeDest)tempArrayPtr[NDim0*i + j];
}
}
}
}
template <typename TypeSrcDest>
inline void getROInputfrommxArray(
const mxArray* InputArray,
MexMatrix<TypeSrcDest, mxAllocator> &MatrixIn) {
if (InputArray != nullptr && !mxIsEmpty(InputArray)) {
size_t NDim0 = FieldInfo<decltype(MatrixIn)>::getSize(InputArray, 0);
size_t NDim1 = FieldInfo<decltype(MatrixIn)>::getSize(InputArray, 1);
TypeSrcDest* tempArrayPtr = reinterpret_cast<TypeSrcDest*>(mxGetData(InputArray));
MatrixIn.assign(NDim1, NDim0, tempArrayPtr, false);
}
}
template <typename TypeSrc, typename TypeDest, class AlDest>
inline void getInputfrommxArray(
const mxArray* InputArray,
MexMatrix<TypeDest, AlDest> &MatrixIn,
void(*casting_func)(TypeSrc &SrcElem, TypeDest &DestElem)) {
if (InputArray != nullptr && !mxIsEmpty(InputArray)) {
size_t NDim0 = FieldInfo<decltype(MatrixIn)>::getSize(InputArray, 0);
size_t NDim1 = FieldInfo<decltype(MatrixIn)>::getSize(InputArray, 1);
TypeSrc* tempArrayPtr = reinterpret_cast<TypeSrc*>(mxGetData(InputArray));
MatrixIn.resize(NDim1, NDim0); // This will not erase old data
for (int i=0; i<NDim1; ++i) {
for (int j=0; j<NDim0; ++j) {
casting_func(tempArrayPtr[NDim0*i + j], MatrixIn(i,j));
}
}
}
}
template <typename TypeSrc, typename TypeDest, class AlDest>
inline void getInputfrommxArray(
const mxArray* InputArray,
MexMatrix<TypeDest, AlDest> &MatrixIn,
std::function<void(TypeSrc &, TypeDest &)> &casting_func) {
if (InputArray != nullptr && !mxIsEmpty(InputArray)) {
size_t NDim0 = FieldInfo<decltype(MatrixIn)>::getSize(InputArray, 0);
size_t NDim1 = FieldInfo<decltype(MatrixIn)>::getSize(InputArray, 1);
TypeSrc* tempArrayPtr = reinterpret_cast<TypeSrc*>(mxGetData(InputArray));
MatrixIn.resize(NDim1, NDim0); // This will not erase old data
for (int i=0; i<NDim1; ++i) {
for (int j=0; j<NDim0; ++j) {
casting_func(tempArrayPtr[NDim0*i + j], MatrixIn(i,j));
}
}
}
}
// -------- From Structure Field -------- //
template <typename TypeSrc, typename TypeDest, class AlDest>
inline int getInputfromStruct(
const mxArray* InputStruct, const char* FieldName,
MexMatrix<TypeDest, AlDest> &MatrixIn,
MexMemInputOps InputOps = MexMemInputOps()) {
// Processing Data
const mxArray* StructFieldPtr = getValidStructField<MexMatrix<TypeSrc> >(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<TypeSrc, TypeDest>(StructFieldPtr, MatrixIn);
return 0;
}
else {
return 1;
}
}
template <typename TypeSrcDest>
inline int getROInputfromStruct(
const mxArray* InputStruct, const char* FieldName,
MexMatrix<TypeSrcDest, mxAllocator> &MatrixIn,
MexMemInputOps InputOps = MexMemInputOps()) {
// Processing Data
const mxArray* StructFieldPtr = getValidStructField<MexMatrix<TypeSrcDest> >(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<TypeSrcDest>(StructFieldPtr, MatrixIn);
return 0;
}
else {
return 1;
}
}
template <typename TypeSrc, typename TypeDest, class AlDest>
inline int getInputfromStruct(
const mxArray* InputStruct, const char* FieldName,
MexMatrix<TypeDest, AlDest> &MatrixIn,
void(*casting_func)(TypeSrc &SrcElem, TypeDest &DestElem),
MexMemInputOps InputOps = MexMemInputOps()) {
// Processing Data
const mxArray* StructFieldPtr = getValidStructField<MexMatrix<TypeSrc> >(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<TypeSrc, TypeDest>(StructFieldPtr, MatrixIn, casting_func);
return 0;
}
else {
return 1;
}
}
template <typename TypeSrc, typename TypeDest, class AlDest>
inline int getInputfromStruct(
const mxArray* InputStruct, const char* FieldName,
MexMatrix<TypeDest, AlDest> &MatrixIn,
std::function<void(TypeSrc &, TypeDest &)> &casting_func,
MexMemInputOps InputOps = MexMemInputOps()) {
// Processing Data
const mxArray* StructFieldPtr = getValidStructField<MexMatrix<TypeSrc> >(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<TypeSrc, TypeDest>(StructFieldPtr, MatrixIn, casting_func);
return 0;
}
else {
return 1;
}
}
//////////////////////////////////////////////////////////////////
///////////////////////// VECTVECT INPUT /////////////////////////
//////////////////////////////////////////////////////////////////
// -------- From mxArray -------- //
template <typename T, class AlSub, class Al>
inline void getInputfrommxArray(const mxArray* InputArray, MexVector<MexVector<T, AlSub>, Al> &VectorIn){
if (InputArray != nullptr && !mxIsEmpty(InputArray) && mxGetClassID(InputArray) == mxCELL_CLASS){
size_t NumElems = mxGetNumberOfElements(InputArray);
mxArrayPtr* tempArrayPtr = reinterpret_cast<mxArrayPtr*>(mxGetData(InputArray));
VectorIn = MexVector<MexVector<T> >(NumElems, MexVector<T>(0));
for (int i = 0; i < NumElems; ++i){
getInputfrommxArray<T>(tempArrayPtr[i], VectorIn[i]);
}
}
}
// -------- From Structure Field -------- //
template <typename T, class AlSub, class Al>
inline int getInputfromStruct(
const mxArray* InputStruct, const char* FieldName,
MexVector<MexVector<T, AlSub>, Al> &VectorIn,
MexMemInputOps InputOps = MexMemInputOps()) {
// Processing Data
const mxArray * StructFieldPtr = getValidStructField<MexVector<MexVector<T> > >(InputStruct, FieldName, InputOps);
if (StructFieldPtr != nullptr) {
getInputfrommxArray<T>(StructFieldPtr, VectorIn);
return 0;
}
else {
return 1;
}
}
//////////////////////////////////////////////////////////////////
////////////////////////// STRUCT INPUT //////////////////////////
//////////////////////////////////////////////////////////////////
// This function is slightly less secure as strict type compliance is not ensured
template <typename T, class Al>
inline int getInputfromStruct(
const mxArray* InputStruct, const char* FieldName,
MexVector<T, Al> &VectorIn,
void(*struct_inp_fun)(StructArgTable &ArgumentVects, T &DestElem),
MexMemInputOps InputOps = MexMemInputOps()){
// Processing Data
// converting Field Name into array of field names by splitting at '-'
std::vector<std::string> FieldNamesVect(0);
StructArgTable StructFieldmxArrays;
// Split the string into its components by delimeters ' -/,'
StringSplit(FieldName, " -/,", FieldNamesVect);
// For each valid field name stored in vector, add entry in map
size_t PrevNumElems = 0; // used to enforce condition that all are of equal size
for (int i = 0; i < FieldNamesVect.size(); ++i){
const mxArray * StructFieldPtr;
// Size constraints are imposed based on wether
// a) A prerequisite size has been specified
// b) We have another reference size to impose size equality
// c) We have nothing (in which case no size constraints)
if (InputOps.REQUIRED_SIZE != -1){
StructFieldPtr = getValidStructField(InputStruct, FieldNamesVect[i].data(), InputOps);
}
else if(PrevNumElems != 0){
MexMemInputOps tempInputOps = InputOps;
tempInputOps.REQUIRED_SIZE = PrevNumElems;
StructFieldPtr = getValidStructField(InputStruct, FieldNamesVect[i].data(), tempInputOps);
}
else{
MexMemInputOps tempInputOps = InputOps;
StructFieldPtr = getValidStructField(InputStruct, FieldNamesVect[i].data(), tempInputOps);
}
// Storing the element conditionally depending on whether or not it exists
size_t NumElems = (StructFieldPtr != nullptr) ? mxGetNumberOfElements(StructFieldPtr) : 0;
if (StructFieldPtr != NULL){
// Store the pointer and data size for current field
int ElemSize = mxGetElementSize(StructFieldPtr);
StructFieldmxArrays.insert(
std::pair<std::string, std::pair<void*, size_t> >(
FieldNamesVect[i],
std::pair<void*, size_t>(mxGetData(StructFieldPtr), ElemSize)
));
PrevNumElems = NumElems;
}
else{
// Store the null pointer and 0 size for current field
StructFieldmxArrays.insert(
std::pair<std::string, std::pair<void*, size_t> >(
FieldNamesVect[i],
std::pair<void*, size_t>(nullptr, 0)
));
}
}
// At this point PrevNumElems represents the number of elements in the arrays listed
VectorIn.resize(PrevNumElems);
for (int i = 0; i < PrevNumElems; ++i){
struct_inp_fun(StructFieldmxArrays, VectorIn[i]);
// updating pointers to the next element
for (auto Elem : StructFieldmxArrays){
auto &CurrElem = StructFieldmxArrays[Elem.first];
if (CurrElem.first != nullptr)
CurrElem.first = (char *)CurrElem.first + CurrElem.second;
}
}
return 0;
}
// Taking structure as input (functors)
// This function is slightly less secure as strict type compliance is not ensured
template <typename T, class Al>
inline int getInputfromStruct(
const mxArray* InputStruct, const char* FieldName,
MexVector<T, Al> &VectorIn,
const std::function<void(StructArgTable &ArgumentVects, T &DestElem)> &struct_inp_fun,
MexMemInputOps InputOps = MexMemInputOps()){
// Processing Data
// converting Field Name into array of field names by splitting at '-'
std::vector<std::string> FieldNamesVect(0);
StructArgTable StructFieldmxArrays;
// Split the string into its components by delimeters ' -/,'
StringSplit(FieldName, " -/,", FieldNamesVect);
// For each valid field name stored in vector, add entry in map
size_t PrevNumElems = 0; // used to enforce condition that all are of equal size
for (int i = 0; i < FieldNamesVect.size(); ++i){
const mxArray * StructFieldPtr;
// Size constraints are imposed based on wether
// a) A prerequisite size has been specified
// b) We have another reference size to impose size equality
// c) We have nothing (in which case no size constraints)
if (InputOps.REQUIRED_SIZE != -1){
StructFieldPtr = getValidStructField(InputStruct, FieldNamesVect[i].data(), InputOps);
}
else if (PrevNumElems != 0){
MexMemInputOps tempInputOps = InputOps;
tempInputOps.REQUIRED_SIZE = PrevNumElems;
StructFieldPtr = getValidStructField(InputStruct, FieldNamesVect[i].data(), tempInputOps);
}
else{
MexMemInputOps tempInputOps = InputOps;
StructFieldPtr = getValidStructField(InputStruct, FieldNamesVect[i].data(), tempInputOps);
}
// Storing the element conditionally depending on whether or not it exists
size_t NumElems = (StructFieldPtr != nullptr) ? mxGetNumberOfElements(StructFieldPtr) : 0;
if (StructFieldPtr != NULL){
// Store the pointer and data size for current field
int ElemSize = mxGetElementSize(StructFieldPtr);
StructFieldmxArrays.insert(
std::pair<std::string, std::pair<void*, size_t> >(
FieldNamesVect[i],
std::pair<void*, size_t>(mxGetData(StructFieldPtr), ElemSize)
));
PrevNumElems = NumElems;
}
else{
// Store the null pointer and 0 size for current field
StructFieldmxArrays.insert(
std::pair<std::string, std::pair<void*, size_t> >(
FieldNamesVect[i],
std::pair<void*, size_t>(nullptr, 0)
));
}
}
// At this point PrevNumElems represents the number of elements in the arrays listed
VectorIn.resize(PrevNumElems); // Does not Delete Previous Elements
for (int i = 0; i < PrevNumElems; ++i){
struct_inp_fun(StructFieldmxArrays, VectorIn[i]);
// updating pointers to the next element
for (auto Elem : StructFieldmxArrays){
auto &CurrElem = StructFieldmxArrays[Elem.first];
if (CurrElem.first != nullptr)
CurrElem.first = (char *)CurrElem.first + CurrElem.second;
}
}
return 0;
}
#endif
|
// This file has been generated by Py++.
#ifndef StateImageryMap_hpp__pyplusplus_wrapper
#define StateImageryMap_hpp__pyplusplus_wrapper
void register_StateImageryMap_class();
#endif//StateImageryMap_hpp__pyplusplus_wrapper
|
// max occuring character in a string
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "kndkfkjdjlfdlkslfk";
int freq[26] = {0};
for(int i=0;i<s.size();i++){
freq[s[i]-'a']++;
}
char ans;
int maxF = 0;
for(int i=0; i<26;i++){
if(freq[i]>maxF){
maxF = freq[i];
ans = i+'a';
}
}
cout<<ans<<" - "<<maxF;
return 0;
}
|
/******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Game.cpp *
* Copyright 2016 PlanetChili.net <http://www.planetchili.net> *
* *
* This file is part of The Chili DirectX Framework. *
* *
* The Chili DirectX Framework is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* The Chili DirectX Framework is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with The Chili DirectX Framework. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************************/
#include "MainWindow.h"
#include "Game.h"
#include "Vec2.h"
Game::Game(MainWindow& wnd)
:
wnd(wnd),
gfx(wnd),
space(sprites2),
storyline("Data/Story.txt", sprites2.smallChars, Colors::Green, RectI(20, 780, 20, 580)),
ending("Data/Ending.txt", sprites2.smallChars, Colors::Green, RectI(20, 780, 20, 580)),
highscores(sprites2.largeChars)
{
}
void Game::Go()
{
gfx.BeginFrame();
float elapsedTime = ft.Mark();
while (elapsedTime > 0.0f)
{
float dt = std::min(0.15f, elapsedTime);
elapsedTime -= dt;
timer.addTime(dt);
UpdateModel(dt);
}
ComposeFrame();
gfx.EndFrame();
}
void Game::ComposeFrame()
{
switch (gameStatus)
{
case Status::introShowing:
storyline.draw(gfx);
break;
case Status::pause:
{
space.draw(gfx);
std::string pauseText;
if (currentLevel < maxLevel)
{
pauseText = " Stage " + std::to_string(currentLevel) + "\n\nGet Ready!";
}
else
{
pauseText = "Final Stage \n\n Get Ready!";
}
sprites2.largeChars.printText(pauseText, Vei2(320.0f, 286.0f), gfx, Colors::Green);
break;
}
case Status::levelRunning:
space.draw(gfx);
break;
case Status::levelEnding:
{
std::string endingText = "Leaving Sector...";
space.draw(gfx);
sprites2.largeChars.printText(endingText, Vei2(264.0f, 286.0f), gfx, Colors::Green);
break;
}
case Status::lost:
{
std::string lostText = "Game Over!";
space.draw(gfx);
sprites2.largeChars.printText(lostText, Vei2(320.0f, 286.0f), gfx, Colors::Green);
break;
}
case Status::endingShowing:
ending.draw(gfx);
break;
case Status::highscores_enter:
{
space.draw(gfx);
highscores.display(gfx);
}
case Status::highscores_show:
{
space.draw(gfx);
highscores.display(gfx);
}
}
}
void Game::UpdateModel(float dt)
{
switch (gameStatus)
{
case Status::introShowing:
storyline.update(dt);
if (wnd.kbd.KeyIsPressed(VK_SPACE))
{
gameStatus = Status::pause;
timer.init(&pauseMode, 2);
}
break;
case Status::pause:
if (!pauseMode)
{
gameStatus = Status::levelRunning;
}
break;
case Status::levelRunning:
space.update(wnd.kbd, dt, timer);
if (space.rocketDestroyed())
{
gameStatus = Status::lost;
timer.init(&lostTimerOver, 3);
space.gameOver = true;
}
else if (space.levelComplete(timer))
{
gameStatus = Status::levelEnding;
}
break;
case Status::levelEnding:
if (space.endSequenceComplete(dt, timer))
{
++currentLevel;
if (currentLevel > maxLevel)
{
space.gameOver = true;
gameStatus = Status::endingShowing;
}
else
{
gameStatus = Status::pause;
space.initLevel(currentLevel, timer);
pauseMode = true;
timer.init(&pauseMode, 2);
}
}
break;
case Status::lost:
space.update(wnd.kbd, dt, timer);
if (lostTimerOver)
{
if (highscores.checkNew(space.getScore()))
{
gameStatus = Status::highscores_enter;
highscores.add(currentLevel, space.getScore());
wnd.kbd.FlushChar();
}
else
{
gameStatus = Status::highscores_show;
}
}
break;
case Status::endingShowing:
ending.update(dt);
if (wnd.kbd.KeyIsPressed(VK_SPACE))
{
if (highscores.checkNew(space.getScore()))
{
gameStatus = Status::highscores_enter;
highscores.add(currentLevel, space.getScore());
wnd.kbd.FlushChar();
}
else
{
gameStatus = Status::highscores_show;
}
}
break;
case Status::highscores_enter:
space.update(dt, timer);
if (highscores.addNametoNew(wnd.kbd.ReadChar()))
{
highscores.save();
gameStatus = Status::highscores_show;
}
break;
case Status::highscores_show:
space.update(dt, timer);
break;
}
}
|
#include "../inc.h"
class Solution {
public:
//O(N * logN)
int longestConsecutive1(vector<int> &num) {
if(num.size() < 2)
return num.size();
sort(num.begin(), num.end());
int r = 1, c = 1;
for(size_t i = 1;i < num.size();++i){
if(num[i - 1] == num[i])
continue;
if(num[i - 1] + 1 == num[i]){
if(++c > r)
r = c;
}else
c = 1;
}
return r;
}
//O(N)
int longestConsecutive2(vector<int> &num) {
if(num.size() < 2)
return num.size();
unordered_map<int, bool> m; //num -> used
for(size_t i = 0;i < num.size();++i)
m[num[i]] = false;
int r = 0;
for(unordered_map<int, bool>::iterator it = m.begin();it != m.end();++it){
if(it->second)
continue;
it->second = true; //used
int r1 = 1;
for(;;++r1){
cout<<"r1: "<<(it->first - r1)<<endl;
unordered_map<int, bool>::iterator wh = m.find(it->first - r1);
if(wh == m.end())
break;
wh->second = true;
}
int r2 = 1;
for(;;++r2){
cout<<"r2: "<<(it->first + r2)<<endl;
unordered_map<int, bool>::iterator wh = m.find(it->first + r2);
if(wh == m.end())
break;
wh->second = true;
}
r1 += r2 - 1;
if(r1 > r)
r = r1;
}
return r;
}
};
int main()
{
vector<int> n;
n.push_back(0);
n.push_back(-1);
cout<<Solution().longestConsecutive2(n)<<endl;
}
|
#pragma once
#include "easytf/base.h"
#include "easytf/entity.h"
#include "easytf/param.h"
namespace easytf
{
class Operator
{
public:
//init param
virtual void init(const Param& param) = 0;
//forward
virtual void forward(const std::map<std::string, std::shared_ptr<Entity>>& bottom, std::map<std::string, std::shared_ptr<Entity>>& top) = 0;
};
}
|
#include<iostream>
using namespace std;
int gcd(int a,int b)
{
int i,j;
for(i=1; i<=a || i<=b; ++i)
{
if(a%i==0 && b%i==0)
j=i;
}
return (a*b)/j;
}
int main()
{
int j;
float fraction,i=2,x,y,a,b,c;
cin>>x>>y;
c=x/y;
while(c>0)
{
j=gcd(y,i);
a=(j/y)*x;
b=(j/i)*1;
if(a>=b)
{
x=a-b;
y=j;
cout<<1<<"/"<<i<<" ";
i++;
c=x/y;
}
else
i++;
}
}
|
/*
File Name: BinarySearchTree.h
Author: Geun-Hyung Kim
Description:
연결 리스트를 활용한 이진탐색트리 생성
*/
#ifndef _BINARY_SEARCH_TREE_
#define _BINARY_SEARCH_TREE_
#include <iostream>
#include <queue>
using namespace std;
template <typename T>
class Node{
T data; // 데이터 저장을 위한 변수
Node<T> *left; // 트리 노드의 왼쪽 자식노드의 주소 저장을 위한 변수
Node<T> *right; // 트리 노드의 오른쪽 자식노드의 주소 저장을 위한 변수
public:
Node(T d = 0, Node<T>* l = NULL, Node<T>* r = NULL) : data(d), left(NULL), right(NULL){}
~Node(){}
T getData(); // 특정 트리 노드의 데이터 값 가져오기
void setData(T& data); // 특정 트리 노드의 데이터 값 대입하기
Node<T>* getLeftNode(); // 특정 트리 노드의 왼쪽 자식노드의 주소 값 반환
Node<T>* getRightNode(); // 특정 트리 노드의 오른쪽 자식노드의 주소 값 반환
void setLeftNode(Node<T> *node); //왼쪽 자식노드에 트리 노드 추가
void setRightNode(Node<T> *node); // 오른쪽 자식노드에 트리 노드 추가
bool levelFind(int type); // type : 반환값을 설정
};
template<typename T>
class BinarySearchTree{
Node<T> *root;
int size; // 현재 트리의 노드 개수
public:
BinarySearchTree(): size(0), root(NULL){};
~BinarySearchTree();
// 특정 트리에서 데이터를 찾아서 존재하면 true, 존재하지 않으면 false를 반환
bool searchData(T& data);
// 트리에 입력한 데이터의 노드 추가 (이미 데이터가 있으면 false, 반환 데이터가 추가되면 true 반환)
bool insertData(T& data);
// 트리에서 입력한 데이터의 노드 삭제 (트리에 없는 데이터를 삭제하고자 하면 false, 데이터 삭제가 성공하면 true 반환)
bool removeData(T& data);
// 트리의 root에서 부터 레벨 오더로 데이터 값을 출력
void levelOrderPrint();
};
// NODE 클래스 함수 구현
template <typename T>
T Node<T>::getData() {
return this->data;
}
template <typename T>
void Node<T>::setData(T& data) {
this->data = data.data;
}
template <typename T>
Node<T>* Node<T>::getLeftNode() {
if (this->left == NULL) {
return NULL;
}
return this->left;
}
template <typename T>
Node<T>* Node<T>::getRightNode() {
if (this->right == NULL) {
return NULL;
}
return this->right;
}
template <typename T>
void Node<T>::setLeftNode(Node<T>* node) {
this->left = node;
}
template <typename T>
void Node<T>::setRightNode(Node<T>* node) {
this->right = node;
}
// BinarySearchTree 클래스 함수 구현
template <typename T>
bool BinarySearchTree<T>::searchData(T& data) {
queue<Node<T>*> dataSet;
Node<T>* find = root;
while (true) {
if (find->getData() == data) return true;
if (find->getLeftNode() != NULL) dataSet.push(find->getLeftNode());
if (find->getRightNode() != NULL) dataSet.push(find->getRightNode());
if (find->getLeftNode() == NULL &&
find->getRightNode() == NULL &&
dataSet.size() == 0) return false;
find = dataSet.front();
dataSet.pop();
}
}
// Q. 데이터 삽입의 반환형이 왜 Bool인가요?
template <typename T>
bool BinarySearchTree<T>::insertData(T& data) {
// 데이터가 없을 경우
if (root == NULL) {
root = new Node<T>(data); return true;
}
else if(searchData(data)){
return false;
}
else {
Node<T>* find = root;
for (;;) {
// 오른쪽으로 삽입
if (find->getData() < data) {
// 오른쪽 노드가 비어있다면?
if (find->getRightNode() == NULL) {
find->setRightNode(data);
size++; return true;
}
find = find->getRightNode();
}
if (find->getData() >= data) {
// 왼쪽 노드가 비어있다면?
if (find->getLeftNode() == NULL) {
find->setRightNode(data);
size++; return true;
}
find = find->getLeftNode();
}
}
}
}
template <typename T>
bool BinarySearchTree<T>::removeData(T& data) {
// 트리에 데이터가 없을 경우
if (root == NULL || !searchData(data)) {
return false;
}
else {
Node<T>* find = root;
Node<T>* deleteNode = NULL;
queue<Node<T>*> dataSet;
int direction = -1; // 1 : 왼쪽 , 0 : 오른쪽
// 첫노드는 따로 체크하기
if (root->getData() == data) {
direction == 1;
}
while (true) {
// 같은 데이터를 찾은 경우
if (find->getLeftNode() != NULL) {
if (find->getLeftNode()->getData() == data) { deleteNode = find; direction = 1; break; }
dataSet.push(find->getLeftNode());
}
if (find->getRightNode() != NULL) {
if (find->getRightNode()->getData() == data) { deleteNode = find; direction = 0; break; }
dataSet.push(find->getRightNode());
}
if (find->getLeftNode() == NULL &&
find->getRightNode() == NULL &&
dataSet.size() == 0) return false;
find = dataSet.front();
dataSet.pop();
}
Node<T>* search = NULL;
if (direction == 1) {
// 실제 삭제될 노드
search = deleteNode->getLeftNode();
// 우측 노드가 없는 경우
if (search->getRightNode() == NULL) {
deleteNode->setLeftNode(search->getLeftNode());
size--; return true;
}
// 최 우측 노드 탐색
for (; deleteNode->getRightNode()->getRightNode() != NULL; deleteNode = deleteNode->getRightNode();) {}
// 삭제노드의 값을 최우측 노드의 값으로 설정
deleteNode->setLeftNode(search->getRightNode()->getRightNode());
// 최우측 노드 부모의 오른쪽값 NULL 설정
search->getRightNode()->setRightNode(NULL);
size--; return true;
}
else if (direction == 0) {
// 실제 삭제될 노드
search = deleteNode->getRightNode();
// 좌측 노드가 없는 경우
if (search->getLeftNode() == NULL) {
deleteNode->setRightNode(search->getRgihtNode());
size--; return true;
}
// 최 좌측 노드 탐색
for (; deleteNode->getLeftNode()->getLeftNode() != NULL; deleteNode = deleteNode->getLeftNode();) {}
// 삭제노드의 값을 최좌측 노드의 값으로 설정
deleteNode->setRightNode(search->getLeftNode()->getLeftNode());
// 최우측 노드 부모의 오른쪽값 NULL 설정
search->getLeftNode()->setLeftNode(NULL);
size--; return true;
}
}
}
template <typename T>
void BinarySearchTree<T>::levelOrderPrint() {
queue<Node<T>*> dataSet;
Node<T>* find = root;
while (true) {
cout << find->getData() << "\t";
if (find->getLeftNode() != NULL) dataSet.push(find->getLeftNode());
if (find->getRightNode() != NULL) dataSet.push(find->getRightNode());
if (find->getLeftNode() == NULL &&
find->getRightNode() == NULL &&
dataSet.size() == 0) return;
find = dataSet.front();
dataSet.pop();
}
}
#endif
|
#include "rayon.h"
#include <QDebug>
Rayon::Rayon()
{
id_3=0;
type_2="";
etat=0;
materiels="";
}
Rayon::Rayon(int id_3,QString type_2,int etat,QString materiels)
{
this->id_3=id_3;
this->type_2=type_2;
this->etat=etat;
this->materiels=materiels;
}
QString Rayon::get_type_2(){return type_2;}
int Rayon::get_etat(){return etat;}
QString Rayon::get_materiels(){return materiels;}
int Rayon::get_id_3(){return id_3;}
bool Rayon::ajouter_2()
{
QSqlQuery query;
QString res= QString::number(id_3);
query.prepare("INSERT INTO rayon (ID_3, TYPE_2, ETAT, MATERIELS) "
"VALUES (:id_3, :type_2, :etat, :materiels )");
query.bindValue(":id_3", res);
query.bindValue(":type_2", type_2);
query.bindValue(":etat", etat);
query.bindValue(":materiels", materiels);
return query.exec();
}
QSqlQueryModel * Rayon::afficher()
{QSqlQueryModel * model= new QSqlQueryModel();
model->setQuery("select * from rayon");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("Type "));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("Etat "));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("Materiels "));
return model;
}
bool Rayon::supprimer_2(int idd)
{
QSqlQuery query;
QString res= QString::number(idd);
query.prepare("Delete from rayon where ID_3 = :id_3 ");
query.bindValue(":id_3", res);
return query.exec();
}
bool Rayon::modifier_2(int idd)
{
QSqlQuery query;
QString res= QString::number(idd);
query.prepare("UPDATE rayon SET TYPE_2=:type_2, ETAT=:etat, MATERIELS=:materiels WHERE ID_3=:id_3");
query.bindValue(":id_3", res);
query.bindValue(":type_2", type_2);
query.bindValue(":etat", etat);
query.bindValue(":materiels", materiels);
return query.exec();
}
QSqlQueryModel * Rayon::recherche_2(const QString &id_3)
{
QSqlQueryModel * model = new QSqlQueryModel();
model->setQuery("select * from rayon where(ID_3 LIKE '"+id_3+"')");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID_3"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("Type_2 "));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("ETAT"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("MATERIELS "));
return model;
}
QSqlQueryModel * Rayon:: afficher_trier()
{
QSqlQueryModel * model = new QSqlQueryModel();
model->setQuery("select * from rayon ORDER BY ID_3");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID_3"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("Type_2 "));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("ETAT"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("MATERIELS "));
return model;
}
|
/*************************************************************
* > File Name : P2278.cpp
* > Author : Tony
* > Created Time : 2019/08/26 15:59:39
* > Algorithm : [DataStructure]priority_queue
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int 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;
}
int Time;
struct Node {
int id, st, dt, p;
bool operator < (const Node& a) const {
if (p == a.p) return st > a.st;
else return p < a.p;
}
}in;
int main() {
priority_queue<Node> q;
while (scanf("%d %d %d %d", &in.id, &in.st, &in.dt, &in.p)!= EOF) {
while (!q.empty() && Time + q.top().dt <= in.st) {
Node out = q.top(); q.pop(); Time += out.dt;
printf("%d %d\n", out.id, Time);
}
if (!q.empty()) {
Node top = q.top(); q.pop();
top.dt = top.dt - in.st + Time;
q.push(top);
}
q.push(in);
Time = in.st;
}
while (!q.empty()) {
Node out = q.top(); q.pop();
Time += out.dt;
printf("%d %d\n", out.id, Time);
}
return 0;
}
|
#ifndef WAVPCMFILE_H
#define WAVPCMFILE_H
#include <QFile>
#include <QAudioFormat>
class WavPcmFile : public QFile {
public:
WavPcmFile(const QString & name, const QAudioFormat & format, QObject *parent = 0);
bool open();
void close();
private:
void writeHeader();
bool hasSupportedFormat();
QAudioFormat format;
};
#endif // WAVPCMFILE_H
|
/* Copyright (c) 2008 NVIDIA CORPORATION
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//For feedback and latest version see http://dynamica.googlecode.com
#ifndef MAX_NODE_H
#define MAX_NODE_H
#include <max.h>
#include <list>
#include <map>
#include <iterator>
//#include "SimpleMesh.h"
#include "MxUtils.h"
class ccMaxNode;
struct ccPrimaryShapePara
{
NxReal Radius; // for NxSphereShape and NxCapsuleShape
NxReal Height; // for NxCapsuleShape
NxVec3 BoxDimension; // for NxBoxShape
};
/*
ccMaxNode holds the information of the Max node. It converts mesh to PxSimpleMesh for further unified usage.
*/
class ccMaxNode {
friend class ccMaxWorld;
private:
ccMaxNode(INode* node);
virtual ~ccMaxNode();
public:
void SetNode(INode* node);
Matrix3 GetCurrentTM(); // get current pose TM, unit changed
void SyncFromMaxMesh();
inline INode* GetMaxNode() { return MaxINode; }
inline ULONG GetMaxHandle() { if(MaxINode) return MaxINode->GetHandle(); return NULL; }
void SetSimulatedPose(Matrix3& pose, bool useScaleTM = true); // use simulation result to update node pose; for RB, useScaleRM = true, for Cloth, false
void RestorePose(); // restore original pose
PxSimpleMesh SimpleMesh;
NxShapeType ShapeType;
ccPrimaryShapePara PrimaryShapePara;
Matrix3 PhysicsNodePoseTM; // pose TM
Matrix3 PhysicsNodePoseTMInv; // pose TM's inverse
Point3 NodePosInPhysics; // object's position in physics world, != poseTM.GetRow(3)
protected:
INode* MaxINode; // store the Max Node pointer
bool ScaledIsUnified; // true, if the mesh is not scaled or the mesh is scaled equally at x/y/z
private:
Matrix3 PhysicsNodeScaleTM; // scale TM
Matrix3 MaxNodeObjectTM; // Max Node's object TM
Matrix3 MaxPivotTM; // node object TM
Matrix3 MaxNodeTM; // pose TM
};
#endif
|
#pragma once
void sort_file(const std::string & in_path, const std::string & output_path, const std::string & tmp_path = "tmp.dat", size_t num_threads = 2);
void sort_file(const char* in_path, const char* output_path, const char* tmp_path = "tmp.dat", size_t num_threads = 2);
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
string first_name;
first_name = "Gulnaz";
cout <<first_name;
cout<<"\n";
first_name = "Nici";
cout <<first_name;
cout<<"\n";
int age;
age = 45;
cout <<age;
cout<<"\n";
age = 15 + 20;
cout<<age;
cout<<"\n";
int books_amount;
cout <<books_amount;
cout <<"\n";
char seat_sector;
seat_sector = 'A' + 7;
cout << seat_sector;
cout << "\n";
}
|
#include <iostream>
using namespace std;
int main()
{
cout << "first num: "
double n1, n2;
cin >> n1;
cout << "second num: "
cin >> n2;
cout << "sum:" << n1 + n2 << endl;
return 0;
}
|
/*
ID: sarthak16
PROG: namenum
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
char a[10][3] = {
{'0', '0', '0'},
{'1', '1', '1'},
{'A', 'B', 'C'},
{'D', 'E', 'F'},
{'G', 'H', 'I'},
{'J', 'K', 'L'},
{'M', 'N', 'O'},
{'P', 'R', 'S'},
{'T', 'U', 'V'},
{'W', 'X', 'Y'},
};
int validName(string, string);
int main()
{
ifstream fin ("namenum.in");
ifstream tin ("dict.txt");
freopen("namenum.out", "w", stdout);
string num;
fin>>num;
int atl = 0;
for(int i=0; i<4617; i++)
{
string name;
tin>>name;
if(validName(num, name))
{
cout<<name<<endl;
atl = 1;
}
}
if(!atl) cout<<"NONE"<<endl;
return 0;
}
int validName(string num, string name)
{
if(num.length()!=name.length()) return 0;
for(int i=0; i<num.length(); i++)
{
int index = (int)(num[i]-'0');
if(a[index][0]!=name[i] && a[index][1]!=name[i] && a[index][2]!=name[i]) return 0;
}
return 1;
}
|
/*************************************************************************
> File Name: time.cpp
> Author: Jason
> Mail: jie-email@jie-trancender.org
> Created Time: 2017年03月29日 星期三 13时34分42秒
************************************************************************/
#include "time.h"
#include <muduo/net/EventLoop.h>
#include <muduo/base/Logging.h>
#include <functional>
using namespace std::placeholders;
using namespace muduo;
using namespace muduo::net;
TimeServer::TimeServer(EventLoop* loop, const InetAddress& listenAdder)
:loop_(loop), server_(loop, listenAdder, "TimeServer")
{
server_.setConnectionCallback(std::bind(&TimeServer::onConnection, this, _1));
}
void TimeServer::onConnection(const TcpConnectionPtr& conn)
{
LOG_INFO << "TimeServer - " << conn->peerAddress().toIpPort() << " -> "
<< conn->localAddress().toIpPort() << " is " << (conn->connected() ? "UP" : "DOWN");
if (conn->connected())
{
time_t now = ::time(NULL);
int32_t be32 = sockets::hostToNetwork32(static_cast<int32_t>(now));
conn->send(&be32, sizeof be32);
conn->shutdown();
}
}
void TimeServer::start()
{
server_.start();
}
|
#include "Camera.hpp"
using namespace Render;
using namespace Math;
Camera::Camera(float sceneAspectRatio) : m_fov(120.0f), m_aspectRatio(sceneAspectRatio), m_zNear(0.01f), m_zFar(6000.f), m_cameraInitPos({1000.0, 600.0, -800.0}), m_targetInitPos({0.0, 0.0, 0.0})
{
reset();
}
void Camera::reset()
{
m_cameraPos = m_cameraInitPos;
m_targetPos = m_targetInitPos;
updateProjMat();
updateProjViewMat();
}
void Camera::rotate(float angleX, float angleY)
{
float3 vecTargetCamera(m_cameraPos - m_targetPos);
auto rot = float4x4::RotationY(angleY) * float4x4::RotationX(angleX);
const auto matWorldToCam = m_viewMat.RemoveTranslation();
rot = matWorldToCam * rot * matWorldToCam.Transpose();
vecTargetCamera = vecTargetCamera * rot;
m_cameraPos = m_targetPos + vecTargetCamera;
updateProjViewMat();
}
void Camera::translate(float dispX, float dispY)
{
auto trans = float4x4::Translation(dispX, dispY, 0.0f);
const auto matWorldToCam = m_viewMat.RemoveTranslation();
trans = matWorldToCam * trans * matWorldToCam.Transpose();
m_cameraPos = float4(m_cameraPos, 1.0) * trans;
m_targetPos = float4(m_targetPos, 1.0) * trans;
updateProjViewMat();
}
void Camera::zoom(float delta)
{
float zoomRatio = 1.f + delta / 10.f;
float3 vecTargetCamera(m_cameraPos - m_targetPos);
m_cameraPos = m_targetPos + vecTargetCamera * zoomRatio;
updateProjViewMat();
}
void Camera::updateProjMat()
{
m_projMat = float4x4::Projection(m_fov, m_aspectRatio, m_zNear, m_zFar, true);
}
void Camera::updateProjViewMat()
{
// Classic lookAt function
float3 refX, refY, refZ;
refZ = - (m_cameraPos - m_targetPos);
refZ = normalize(refZ);
refY = { 0.0f, 1.0f, 0.0f };
refX = cross(refY, refZ);
refY = cross(refZ, refX);
refX = normalize(refX);
refY = normalize(refY);
float dotRefXEye = -dot(refX, m_cameraPos);
float dotRefYEye = -dot(refY, m_cameraPos);
float dotRefZEye = -dot(refZ, m_cameraPos);
m_viewMat =
{
refX.x , refY.x , refZ.x , 0.0f,
refX.y , refY.y , refZ.y , 0.0f,
refX.z , refY.z , refZ.z , 0.0f,
dotRefXEye, dotRefYEye, dotRefZEye, 1.0f
};
m_projViewMat = float4x4::Mul(m_viewMat, m_projMat);
}
|
#ifndef __F_BULLET__
#define __F_BULLET__
#include "Bullet.h"
#include "../../FrameWork/Animation.h"
#define F_BULLET_SPEED 200.0f
#define ROUND_RADIUS 600.0f
#define ROUND_FREQUENCE 3.5f
class FBullet : public Bullet
{
public:
FBullet(GVector2 startPosition, float degree);
~FBullet();
void init() override;
void update(float deltatime) override;
void draw(LPD3DXSPRITE, Viewport*) override;
void release() override;
private:
Animation* _animations;
float initRadian();
};
#endif // !__F_BULLET__
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** This program is free software; you can redistribute it and/or
//** modify it under the terms of the GNU General Public License
//** as published by the Free Software Foundation; either version 3
//** of the License, or (at your option) any later version.
//**
//** This program is distributed in the hope that it will be useful,
//** but WITHOUT ANY WARRANTY; without even the implied warranty of
//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
//**
//** Portable code to mix sounds for snd_dma.cpp
//**
//**************************************************************************
#include "local.h"
#include "../client_main.h"
#include "../../common/Common.h"
#include "../../common/common_defs.h"
#include "../../common/strings.h"
#include "../../common/command_buffer.h"
#define TALK_FUTURE_SEC 0.25 // go this far into the future (seconds)
unsigned char s_entityTalkAmplitude[ MAX_CLIENTS_WS ];
portable_samplepair_t paintbuffer[ PAINTBUFFER_SIZE ];
extern "C"
{
int* snd_p;
int snd_linear_count;
short* snd_out;
}
static int snd_vol;
#if id386 && defined _MSC_VER
static __declspec( naked ) void S_WriteLinearBlastStereo16() {
__asm
{
push edi
push ebx
mov ecx,ds : dword ptr[snd_linear_count]
mov ebx,ds : dword ptr[snd_p]
mov edi,ds : dword ptr[snd_out]
LWLBLoopTop :
mov eax,ds : dword ptr[-8 + ebx + ecx * 4]
sar eax,8
cmp eax,07FFFh
jg LClampHigh
cmp eax,0FFFF8000h
jnl LClampDone
mov eax,0FFFF8000h
jmp LClampDone
LClampHigh :
mov eax,07FFFh
LClampDone :
mov edx,ds : dword ptr[-4 + ebx + ecx * 4]
sar edx,8
cmp edx,07FFFh
jg LClampHigh2
cmp edx,0FFFF8000h
jnl LClampDone2
mov edx,0FFFF8000h
jmp LClampDone2
LClampHigh2 :
mov edx,07FFFh
LClampDone2 :
shl edx,16
and eax,0FFFFh
or edx,eax
mov ds : dword ptr[-4 + edi + ecx * 2],edx
sub ecx,2
jnz LWLBLoopTop
pop ebx
pop edi
ret
}
}
#elif id386 && defined __GNUC__
// forward declare, implementation somewhere else
extern "C" void S_WriteLinearBlastStereo16();
#else
static void S_WriteLinearBlastStereo16() {
for ( int i = 0; i < snd_linear_count; i += 2 ) {
int val = snd_p[ i ] >> 8;
if ( val > 0x7fff ) {
snd_out[ i ] = 0x7fff;
} else if ( val < -32768 ) {
snd_out[ i ] = -32768;
} else {
snd_out[ i ] = val;
}
val = snd_p[ i + 1 ] >> 8;
if ( val > 0x7fff ) {
snd_out[ i + 1 ] = 0x7fff;
} else if ( val < -32768 ) {
snd_out[ i + 1 ] = -32768;
} else {
snd_out[ i + 1 ] = val;
}
}
}
#endif
static void S_TransferStereo16( int endtime ) {
snd_p = ( int* )paintbuffer;
int lpaintedtime = s_paintedtime;
while ( lpaintedtime < endtime ) {
// handle recirculating buffer issues
int lpos = lpaintedtime & ( ( dma.samples >> 1 ) - 1 );
snd_out = ( short* )dma.buffer + ( lpos << 1 );
snd_linear_count = ( dma.samples >> 1 ) - lpos;
if ( lpaintedtime + snd_linear_count > endtime ) {
snd_linear_count = endtime - lpaintedtime;
}
snd_linear_count <<= 1;
// write a linear blast of samples
S_WriteLinearBlastStereo16();
snd_p += snd_linear_count;
lpaintedtime += ( snd_linear_count >> 1 );
}
}
static void S_TransferPaintBuffer( int endtime ) {
if ( !dma.buffer ) {
return;
}
if ( s_testsound->integer ) {
// write a fixed sine wave
int count = endtime - s_paintedtime;
for ( int i = 0; i < count; i++ ) {
paintbuffer[ i ].left = paintbuffer[ i ].right =
sin( ( s_paintedtime + i ) * 0.1 ) * 20000 * 256;
}
}
if ( dma.samplebits == 16 && dma.channels == 2 ) {
// optimized case
S_TransferStereo16( endtime );
} else {
// general case
int* p = ( int* )paintbuffer;
int count = ( endtime - s_paintedtime ) * dma.channels;
int out_mask = dma.samples - 1;
int out_idx = s_paintedtime * dma.channels & out_mask;
int step = 3 - dma.channels;
if ( dma.samplebits == 16 ) {
short* out = ( short* )dma.buffer;
while ( count-- ) {
int val = *p >> 8;
p += step;
if ( val > 0x7fff ) {
val = 0x7fff;
} else if ( val < -32768 ) {
val = -32768;
}
out[ out_idx ] = val;
out_idx = ( out_idx + 1 ) & out_mask;
}
} else if ( dma.samplebits == 8 ) {
byte* out = dma.buffer;
while ( count-- ) {
int val = *p >> 8;
p += step;
if ( val > 0x7fff ) {
val = 0x7fff;
} else if ( val < -32768 ) {
val = -32768;
}
out[ out_idx ] = ( val >> 8 ) + 128;
out_idx = ( out_idx + 1 ) & out_mask;
}
}
}
}
//**************************************************************************
//
// LIP SYNCING
//
//**************************************************************************
static void S_SetVoiceAmplitudeFrom16( const sfx_t* sc, int sampleOffset, int count, int entnum ) {
if ( count <= 0 ) {
return; // must have gone ahead of the end of the sound
}
int sfx_count = 0;
short* samples = sc->Data;
for ( int i = 0; i < count; i++ ) {
int data = samples[ sampleOffset++ ];
if ( abs( data ) > 5000 ) {
sfx_count += ( data * 255 ) >> 8;
}
}
// adjust the sfx_count according to the frametime (scale down for longer frametimes)
sfx_count = abs( sfx_count );
sfx_count = ( int )( ( float )sfx_count / ( 2.0 * ( float )count ) );
if ( sfx_count > 255 ) {
sfx_count = 255;
}
if ( sfx_count < 25 ) {
sfx_count = 0;
}
// update the amplitude for this entity
s_entityTalkAmplitude[ entnum ] = ( unsigned char )sfx_count;
}
int S_GetVoiceAmplitude( int entityNum ) {
if ( !( GGameType & ( GAME_WolfSP | GAME_ET ) ) ) {
return 0;
}
if ( entityNum >= ( GGameType & GAME_ET ? MAX_CLIENTS_ET : MAX_CLIENTS_WS ) ) {
common->Printf( "Error: S_GetVoiceAmplitude() called for a non-client\n" );
return 0;
}
return ( int )s_entityTalkAmplitude[ entityNum ];
}
//**************************************************************************
//
// Wave file saving functions
//
//**************************************************************************
struct wav_hdr_t {
unsigned int ChunkID; // big endian
unsigned int ChunkSize; // little endian
unsigned int Format; // big endian
unsigned int Subchunk1ID; // big endian
unsigned int Subchunk1Size; // little endian
unsigned short AudioFormat; // little endian
unsigned short NumChannels; // little endian
unsigned int SampleRate; // little endian
unsigned int ByteRate; // little endian
unsigned short BlockAlign; // little endian
unsigned short BitsPerSample; // little endian
unsigned int Subchunk2ID; // big endian
unsigned int Subchunk2Size; // little indian ;)
unsigned int NumSamples;
};
static wav_hdr_t hdr;
static portable_samplepair_t wavbuffer[ PAINTBUFFER_SIZE ];
static void CL_WavFilename( int number, char* fileName ) {
if ( number < 0 || number > 9999 ) {
String::Sprintf( fileName, MAX_QPATH, "wav9999" ); // fretn - removed .tga
return;
}
String::Sprintf( fileName, MAX_QPATH, "wav%04i", number );
}
static void CL_WriteWaveHeader() {
memset( &hdr, 0, sizeof ( hdr ) );
hdr.ChunkID = 0x46464952; // "RIFF"
hdr.ChunkSize = 0; // total filesize - 8 bytes
hdr.Format = 0x45564157; // "WAVE"
hdr.Subchunk1ID = 0x20746d66; // "fmt "
hdr.Subchunk1Size = 16; // 16 = pcm
hdr.AudioFormat = 1; // 1 = linear quantization
hdr.NumChannels = 2; // 2 = stereo
hdr.SampleRate = dma.speed;
hdr.BitsPerSample = 16; // 16bits
// SampleRate * NumChannels * BitsPerSample/8
hdr.ByteRate = hdr.SampleRate * hdr.NumChannels * ( hdr.BitsPerSample / 8 );
// NumChannels * BitsPerSample/8
hdr.BlockAlign = hdr.NumChannels * ( hdr.BitsPerSample / 8 );
hdr.Subchunk2ID = 0x61746164; // "data"
hdr.Subchunk2Size = 0; // NumSamples * NumChannels * BitsPerSample/8
// ...
FS_Write( &hdr.ChunkID, 44, clc.wm_wavefile );
}
void CL_WriteWaveOpen() {
if ( Cmd_Argc() > 2 ) {
common->Printf( "wav_record <wavname>\n" );
return;
}
if ( clc.wm_waverecording ) {
common->Printf( "Already recording a wav file\n" );
return;
}
char wavName[ MAX_QPATH ];
char name[ MAX_QPATH ];
if ( Cmd_Argc() == 2 ) {
const char* s = Cmd_Argv( 1 );
String::NCpyZ( wavName, s, sizeof ( wavName ) );
String::Sprintf( name, sizeof ( name ), "wav/%s.wav", wavName );
} else {
for ( int number = 0; number <= 9999; number++ ) {
char wavName[ MAX_QPATH ];
CL_WavFilename( number, wavName );
String::Sprintf( name, sizeof ( name ), "wav/%s.wav", wavName );
int len = FS_FileExists( name );
if ( len <= 0 ) {
break; // file doesn't exist
}
}
}
common->Printf( "recording to %s.\n", name );
clc.wm_wavefile = FS_FOpenFileWrite( name );
if ( !clc.wm_wavefile ) {
common->Printf( "ERROR: couldn't open %s for writing.\n", name );
return;
}
CL_WriteWaveHeader();
clc.wm_wavetime = -1;
clc.wm_waverecording = true;
if ( GGameType & GAME_ET ) {
Cvar_Set( "cl_waverecording", "1" );
Cvar_Set( "cl_wavefilename", wavName );
Cvar_Set( "cl_waveoffset", "0" );
}
}
void CL_WriteWaveClose() {
common->Printf( "Stopped recording\n" );
hdr.Subchunk2Size = hdr.NumSamples * hdr.NumChannels * ( hdr.BitsPerSample / 8 );
hdr.ChunkSize = 36 + hdr.Subchunk2Size;
FS_Seek( clc.wm_wavefile, 4, FS_SEEK_SET );
FS_Write( &hdr.ChunkSize, 4, clc.wm_wavefile );
FS_Seek( clc.wm_wavefile, 40, FS_SEEK_SET );
FS_Write( &hdr.Subchunk2Size, 4, clc.wm_wavefile );
// and we're outta here
FS_FCloseFile( clc.wm_wavefile );
clc.wm_wavefile = 0;
}
void CL_WriteWaveFilePacket( int endtime ) {
if ( !clc.wm_waverecording || !clc.wm_wavefile ) {
return;
}
if ( clc.wm_wavetime == -1 ) {
clc.wm_wavetime = s_soundtime;
memcpy( wavbuffer, paintbuffer, sizeof ( wavbuffer ) );
return;
}
if ( s_soundtime <= clc.wm_wavetime ) {
return;
}
int total = s_soundtime - clc.wm_wavetime;
if ( total < 1 ) {
return;
}
clc.wm_wavetime = s_soundtime;
for ( int i = 0; i < total; i++ ) {
int parm;
short out;
parm = ( wavbuffer[ i ].left ) >> 8;
if ( parm > 32767 ) {
parm = 32767;
}
if ( parm < -32768 ) {
parm = -32768;
}
out = parm;
FS_Write( &out, 2, clc.wm_wavefile );
parm = ( wavbuffer[ i ].right ) >> 8;
if ( parm > 32767 ) {
parm = 32767;
}
if ( parm < -32768 ) {
parm = -32768;
}
out = parm;
FS_Write( &out, 2, clc.wm_wavefile );
hdr.NumSamples++;
}
memcpy( wavbuffer, paintbuffer, sizeof ( wavbuffer ) );
if ( GGameType & GAME_ET ) {
Cvar_Set( "cl_waveoffset", va( "%d", FS_FTell( clc.wm_wavefile ) ) );
}
}
//**************************************************************************
//
// CHANNEL MIXING
//
//**************************************************************************
static void S_PaintChannelFrom16( channel_t* ch, const sfx_t* sc, int count,
int sampleOffset, int bufferOffset ) {
portable_samplepair_t* samp = &paintbuffer[ bufferOffset ];
if ( !ch->doppler || ch->dopplerScale == 1.0f ) {
int leftvol = ch->leftvol * snd_vol;
int rightvol = ch->rightvol * snd_vol;
short* samples = sc->Data;
for ( int i = 0; i < count; i++ ) {
int data = samples[ sampleOffset++ ];
samp[ i ].left += ( data * leftvol ) >> 8;
samp[ i ].right += ( data * rightvol ) >> 8;
}
} else {
sampleOffset = sampleOffset * ch->oldDopplerScale;
float fleftvol = ch->leftvol * snd_vol;
float frightvol = ch->rightvol * snd_vol;
float ooff = sampleOffset;
short* samples = sc->Data;
for ( int i = 0; i < count; i++ ) {
int aoff = ooff;
ooff = ooff + ch->dopplerScale;
int boff = ooff;
float fdata = 0;
for ( int j = aoff; j < boff; j++ ) {
fdata += samples[ j ];
}
float fdiv = 256 * ( boff - aoff );
samp[ i ].left += ( fdata * fleftvol ) / fdiv;
samp[ i ].right += ( fdata * frightvol ) / fdiv;
}
}
}
void S_PaintChannels( int endtime ) {
int i, si;
int end;
channel_t* ch;
sfx_t* sc;
int ltime, count;
int sampleOffset;
streamingSound_t* ss;
bool firstPass = true;
if ( s_mute->value ) {
snd_vol = 0;
} else {
snd_vol = s_volume->value * 255;
}
if ( s_volCurrent < 1 ) {
// only when fading (at map start/end)
snd_vol = ( int )( ( float )snd_vol * s_volCurrent );
}
while ( s_paintedtime < endtime ) {
// if paintbuffer is smaller than DMA buffer
// we may need to fill it multiple times
end = endtime;
if ( endtime - s_paintedtime > PAINTBUFFER_SIZE ) {
end = s_paintedtime + PAINTBUFFER_SIZE;
}
// start any playsounds
while ( 1 ) {
playsound_t* ps = s_pendingplays.next;
if ( ps == &s_pendingplays ) {
break; // no more pending sounds
}
if ( ps->begin <= s_paintedtime ) {
S_IssuePlaysound( ps );
continue;
}
if ( ps->begin < end ) {
end = ps->begin; // stop here
}
break;
}
// clear pain buffer for the current time
Com_Memset( paintbuffer, 0, ( end - s_paintedtime ) * sizeof ( portable_samplepair_t ) );
// mix all streaming sounds into paint buffer
for ( si = 0, ss = streamingSounds; si < MAX_STREAMING_SOUNDS; si++, ss++ ) {
// if this streaming sound is still playing
if ( s_rawend[ si ] >= s_paintedtime ) {
// copy from the streaming sound source
int s;
int stop;
stop = ( end < s_rawend[ si ] ) ? end : s_rawend[ si ];
for ( i = s_paintedtime; i < stop; i++ ) {
s = i & ( MAX_RAW_SAMPLES - 1 );
paintbuffer[ i - s_paintedtime ].left += ( s_rawsamples[ si ][ s ].left * s_rawVolume[ si ].left ) >> 8;
paintbuffer[ i - s_paintedtime ].right += ( s_rawsamples[ si ][ s ].right * s_rawVolume[ si ].right ) >> 8;
}
// rain - the announcer is ent -1, so make sure we're >= 0
if ( ( GGameType & ( GAME_WolfSP | GAME_ET ) ) && firstPass && ss->channel == Q3CHAN_VOICE &&
ss->entnum >= 0 && ss->entnum < ( GGameType & GAME_ET ? MAX_CLIENTS_ET : MAX_CLIENTS_WS ) ) {
int talktime;
int sfx_count, vstop;
int data;
// we need to go into the future, since the interpolated behaviour of the facial
// animation creates lag in the time it takes to display the current facial frame
talktime = s_paintedtime + ( int )( TALK_FUTURE_SEC * ( float )s_khz->integer * 1000 );
vstop = ( talktime + 100 < s_rawend[ si ] ) ? talktime + 100 : s_rawend[ si ];
sfx_count = 0;
for ( i = talktime; i < vstop; i++ ) {
s = i & ( MAX_RAW_SAMPLES - 1 );
data = abs( ( s_rawsamples[ si ][ s ].left ) / 8000 );
if ( data > sfx_count ) {
sfx_count = data;
}
}
if ( sfx_count > 255 ) {
sfx_count = 255;
}
if ( sfx_count < 25 ) {
sfx_count = 0;
}
// update the amplitude for this entity
s_entityTalkAmplitude[ ss->entnum ] = ( unsigned char )sfx_count;
}
}
}
// paint in the channels.
ch = s_channels;
for ( i = 0; i < MAX_CHANNELS; i++, ch++ ) {
if ( ch->startSample == START_SAMPLE_IMMEDIATE || !ch->sfx ||
( !ch->leftvol && !ch->rightvol ) ) {
//(ch->leftvol < 0.25 && ch->rightvol < 0.25))
continue;
}
ltime = s_paintedtime;
sc = ch->sfx;
while ( ltime < end ) {
sampleOffset = ltime - ch->startSample;
count = end - ltime;
if ( sampleOffset + count > sc->Length ) {
count = sc->Length - sampleOffset;
}
if ( count > 0 ) {
// Talking animations
// TODO: check that this entity has talking animations enabled!
if ( ( GGameType & ( GAME_WolfSP | GAME_ET ) ) && firstPass && ch->entchannel == Q3CHAN_VOICE &&
ch->entnum < ( GGameType & GAME_ET ? MAX_CLIENTS_ET : MAX_CLIENTS_WS ) ) {
int talkofs, talkcnt, talktime;
// we need to go into the future, since the interpolated behaviour of the facial
// animation creates lag in the time it takes to display the current facial frame
talktime = ltime + ( int )( TALK_FUTURE_SEC * ( float )s_khz->integer * 1000 );
talkofs = talktime - ch->startSample;
talkcnt = 100;
if ( talkofs + talkcnt < sc->Length ) {
S_SetVoiceAmplitudeFrom16( sc, talkofs, talkcnt, ch->entnum );
}
}
S_PaintChannelFrom16( ch, sc, count, sampleOffset, ltime - s_paintedtime );
ltime += count;
}
// if at end of loop, restart
if ( ltime >= ch->startSample + ch->sfx->Length ) {
if ( ch->sfx->LoopStart >= 0 ) {
ch->startSample = ltime - ch->sfx->LoopStart;
} else {
// channel just stopped
if ( !( GGameType & GAME_Tech3 ) ) {
ch->sfx = NULL;
}
break;
}
}
}
}
// paint in the looped channels.
ch = loop_channels;
for ( i = 0; i < numLoopChannels; i++, ch++ ) {
if ( !ch->sfx || ( !ch->leftvol && !ch->rightvol ) ) {
continue;
}
ltime = s_paintedtime;
sc = ch->sfx;
if ( sc->Data == NULL || sc->Length == 0 ) {
continue;
}
// we might have to make two passes if it
// is a looping sound effect and the end of
// the sample is hit
do {
sampleOffset = ( ltime % sc->Length );
count = end - ltime;
if ( sampleOffset + count > sc->Length ) {
count = sc->Length - sampleOffset;
}
if ( count > 0 ) {
// Ridah, talking animations
// TODO: check that this entity has talking animations enabled!
if ( ( GGameType & ( GAME_WolfSP | GAME_ET ) ) && firstPass && ch->entchannel == Q3CHAN_VOICE &&
ch->entnum < ( GGameType & GAME_ET ? MAX_CLIENTS_ET : MAX_CLIENTS_WS ) ) {
int talkofs, talkcnt, talktime;
// we need to go into the future, since the interpolated behaviour of the facial
// animation creates lag in the time it takes to display the current facial frame
talktime = ltime + ( int )( TALK_FUTURE_SEC * ( float )s_khz->integer * 1000 );
talkofs = talktime % sc->Length;
talkcnt = 100;
if ( talkofs + talkcnt < sc->Length ) {
S_SetVoiceAmplitudeFrom16( sc, talkofs, talkcnt, ch->entnum );
}
}
S_PaintChannelFrom16( ch, sc, count, sampleOffset, ltime - s_paintedtime );
ltime += count;
}
} while ( ltime < end );
}
// transfer out according to DMA format
S_TransferPaintBuffer( end );
CL_WriteWaveFilePacket( end );
s_paintedtime = end;
firstPass = false;
}
}
|
#ifndef BinaryNode_hpp
#define BinaryNode_hpp
#include <iostream>
namespace compressor
{
class bitset;
class BinaryNode
{
public:
explicit BinaryNode() = default;
explicit BinaryNode(BinaryNode& node) = default;
explicit BinaryNode(BinaryNode&& node) = default;
virtual ~BinaryNode() = default;
virtual BinaryNode& operator=(BinaryNode& node) = default;
virtual BinaryNode& operator=(BinaryNode&& node) = default;
virtual std::shared_ptr<BinaryNode> left() const;
virtual void setLeft(std::shared_ptr<BinaryNode> left);
virtual std::shared_ptr<BinaryNode> right() const;
virtual void setRight(std::shared_ptr<BinaryNode> right);
virtual std::weak_ptr<BinaryNode> parent() const;
virtual void setParent(std::weak_ptr<BinaryNode> parent);
virtual bool hasParent() const;
virtual void setTag(std::shared_ptr<compressor::bitset> tag);
virtual std::shared_ptr<compressor::bitset> tag() const;
bool operator==(const BinaryNode& rhs);
bool operator!=(const BinaryNode& rhs);
protected:
std::shared_ptr<BinaryNode> _left;
std::shared_ptr<BinaryNode> _right;
std::weak_ptr<BinaryNode> _parent;
std::shared_ptr<compressor::bitset> _tag;
};
}
#endif /* BinaryNode_hpp */
|
/***************************************************************************
dialogocolores.h - description
-------------------
begin : jue abr 1 2004
copyright : (C) 2004 by Oscar G. Duarte
email : ogduarte@ing.unal.edu.co
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef DIALOGOCOLORES_H
#define DIALOGOCOLORES_H
#include <wx/wx.h>
#include "listacolores.h"
/**Dialogo para mostrar los Colores de la Pantalla
*@author Oscar G. Duarte
*/
class DialogoColores : public wxDialog {
public:
DialogoColores(ListaColores col,
wxWindow* parent,const wxString& title);
~DialogoColores();
void OnPaint(wxPaintEvent&);
ListaColores Colores;
DECLARE_EVENT_TABLE()
};
#endif
|
#include <ros/ros.h>
#include <OGRE/OgreMatrix3.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreVector3.h>
#include "WeightedPoseWithCovarianceArray/WeightedPoseWithCovarianceArrayVisual.h"
namespace tuw_geometry_rviz
{
WeightedPoseWithCovarianceArrayVisual::WeightedPoseWithCovarianceArrayVisual(Ogre::SceneManager *scene_manager,
Ogre::SceneNode *parent_node)
{
scene_manager_ = scene_manager;
// Ogre::SceneNode s form a tree, with each node storing the
// transform (position and orientation) of itself relative to its
// parent. Ogre does the math of combining those transforms when it
// is time to render.
//
// Here we create a node to store the pose of the MarkerDetection's header
// frame
// relative to the RViz fixed frame.
frame_node_ = parent_node->createChildSceneNode();
count_ = 0;
}
WeightedPoseWithCovarianceArrayVisual::~WeightedPoseWithCovarianceArrayVisual()
{
// Destroy the frame node since we don't need it anymore.
scene_manager_->destroySceneNode(frame_node_);
}
Ogre::ColourValue WeightedPoseWithCovarianceArrayVisual::colorFromWeight(Ogre::ColourValue low, Ogre::ColourValue high,
double weight)
{
Ogre::ColourValue result;
result[0] = weight * high[0] + (1 - weight) * low[0];
result[1] = weight * high[1] + (1 - weight) * low[1];
result[2] = weight * high[2] + (1 - weight) * low[2];
result[3] = 0.2 + 0.8 * weight;
return result;
}
void WeightedPoseWithCovarianceArrayVisual::setMessage(
const tuw_geometry_msgs::WeightedPoseWithCovarianceArray::ConstPtr &msg)
{
unsigned int i;
if (count_ != msg->poses.size())
{
poses_.resize(msg->poses.size());
variances_.resize(msg->poses.size());
for (i = 0; i < msg->poses.size(); i++)
{
// We create the visual objects within the frame node so that we can
// set thier position and direction relative to their header frame.
poses_[i].reset(new rviz::Arrow(scene_manager_, frame_node_));
variances_[i].reset(new rviz::Shape(rviz::Shape::Sphere, scene_manager_, frame_node_));
}
}
count_ = msg->poses.size();
double maxWeight = -DBL_MAX;
for (i = 0; i < msg->poses.size(); i++)
{
double pw = msg->poses[i].weight;
if (pw > 1)
{
ROS_WARN("[WeightedPoseWithCovarianceArrayVisual setMessage] Invalid "
"weight: %f > 1",
pw);
pw = 0;
}
if (pw < 0)
{
ROS_WARN("[WeightedPoseWithCovarianceArrayVisual setMessage] Invalid "
"weight: %f < 0",
pw);
pw = 0;
}
if (pw > maxWeight)
{
maxWeight = pw;
}
}
for (i = 0; i < msg->poses.size(); i++)
{
tuw_geometry_msgs::WeightedPoseWithCovariance pose = msg->poses[i];
double weight = pose.weight;
weight = maxWeight > 0 ? weight / maxWeight : 0;
Ogre::Vector3 position = Ogre::Vector3(pose.pose.position.x, pose.pose.position.y, pose.pose.position.z);
Ogre::Quaternion orientation = Ogre::Quaternion(pose.pose.orientation.x, pose.pose.orientation.y,
pose.pose.orientation.z, pose.pose.orientation.w);
// Arrow points in -Z direction, so rotate the orientation before display.
// TODO: is it safe to change Arrow to point in +X direction?
Ogre::Quaternion rotation1 = Ogre::Quaternion(Ogre::Degree(-90), Ogre::Vector3::UNIT_Y);
Ogre::Quaternion rotation2 = Ogre::Quaternion(Ogre::Degree(-180), Ogre::Vector3::UNIT_X);
orientation = rotation2 * rotation1 * orientation;
poses_[i]->setPosition(position);
poses_[i]->setOrientation(orientation);
poses_[i]->setColor(colorFromWeight(color_pose_low_, color_pose_high_, weight));
Ogre::Matrix3 C = Ogre::Matrix3(pose.covariance[6 * 0 + 0], pose.covariance[6 * 0 + 1], pose.covariance[6 * 0 + 5],
pose.covariance[6 * 1 + 0], pose.covariance[6 * 1 + 1], pose.covariance[6 * 1 + 5],
pose.covariance[6 * 5 + 0], pose.covariance[6 * 5 + 1], pose.covariance[6 * 5 + 5]);
Ogre::Real eigenvalues[3];
Ogre::Vector3 eigenvectors[3];
C.EigenSolveSymmetric(eigenvalues, eigenvectors);
if (eigenvalues[0] < 0)
{
ROS_WARN("[WeightedPoseWithCovarianceArrayVisual setMessage] "
"eigenvalue[0]: %f < 0 ",
eigenvalues[0]);
eigenvalues[0] = 0;
}
if (eigenvalues[1] < 0)
{
ROS_WARN("[WeightedPoseWithCovarianceArrayVisual setMessage] "
"eigenvalue[1]: %f < 0 ",
eigenvalues[1]);
eigenvalues[1] = 0;
}
if (eigenvalues[2] < 0)
{
ROS_WARN("[WeightedPoseWithCovarianceArrayVisual setMessage] "
"eigenvalue[2]: %f < 0 ",
eigenvalues[2]);
eigenvalues[2] = 0;
}
variances_[i]->setColor(colorFromWeight(color_variance_, color_variance_, weight));
variances_[i]->setPosition(position);
variances_[i]->setOrientation(Ogre::Quaternion(eigenvectors[0], eigenvectors[1], eigenvectors[2]));
variances_[i]->setScale(
Ogre::Vector3(2 * sqrt(eigenvalues[0]), 2 * sqrt(eigenvalues[1]), 2 * sqrt(eigenvalues[2])));
}
}
// Position is passed through to the SceneNode.
void WeightedPoseWithCovarianceArrayVisual::setFramePosition(const Ogre::Vector3 &position)
{
frame_node_->setPosition(position);
}
// Orientation is passed through to the SceneNode.
void WeightedPoseWithCovarianceArrayVisual::setFrameOrientation(const Ogre::Quaternion &orientation)
{
frame_node_->setOrientation(orientation);
}
// Scale is passed through to the pose Shape object.
void WeightedPoseWithCovarianceArrayVisual::setScalePose(float scale)
{
scale_pose_ = scale;
}
// Color is passed through to the pose Shape object.
void WeightedPoseWithCovarianceArrayVisual::setColorPose(Ogre::ColourValue low, Ogre::ColourValue high)
{
color_pose_low_ = low;
color_pose_high_ = high;
}
// Color is passed through to the variance Shape object.
void WeightedPoseWithCovarianceArrayVisual::setColorVariance(Ogre::ColourValue color)
{
color_variance_ = color;
}
} // end namespace marker_rviz
|
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define ok() puts(ok?"Yes":"No");
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef set<int> si;
typedef map<string, int> msi;
typedef greater<int> gt;
typedef priority_queue<int, vector<int>, gt> minq;
typedef long long ll;
typedef pair<ll,ll> pll;
const ll LINF = 1e18L + 1;
const int INF = 1e9 + 1;
//clang++ -std=c++11 -stdlib=libc++
const int mod = 1000000007;
// const int mod = 998244353;
struct mint {
ll x; // typedef long long ll;
mint(ll x=0):x((x%mod+mod)%mod){}
mint operator-() const { return mint(-x);}
mint& operator+=(const mint a) {
if ((x += a.x) >= mod) x -= mod;
return *this;
}
mint& operator-=(const mint a) {
if ((x += mod-a.x) >= mod) x -= mod;
return *this;
}
mint& operator*=(const mint a) { (x *= a.x) %= mod; return *this;}
mint operator+(const mint a) const { return mint(*this) += a;}
mint operator-(const mint a) const { return mint(*this) -= a;}
mint operator*(const mint a) const { return mint(*this) *= a;}
mint pow(ll t) const {
if (!t) return 1;
mint a = pow(t>>1);
a *= a;
if (t&1) a *= *this;
return a;
}
// for prime mod
mint inv() const { return pow(mod-2);}
mint& operator/=(const mint a) { return *this *= a.inv();}
mint operator/(const mint a) const { return mint(*this) /= a;}
};
istream& operator>>(istream& is, const mint& a) { return is >> a.x;}
ostream& operator<<(ostream& os, const mint& a) { return os << a.x;}
struct combination {
vector<mint> fact, ifact;
combination(int n):fact(n+1),ifact(n+1) {
assert(n < mod);
fact[0] = 1;
for (int i = 1; i <= n; ++i) fact[i] = fact[i-1]*i;
ifact[n] = fact[n].inv();
for (int i = n; i >= 1; --i) ifact[i-1] = ifact[i]*i;
}
mint operator()(int n, int k) {
if (k < 0 || k > n) return 0;
return fact[n]*ifact[k]*ifact[n-k];
}
};
int n, k;
int main() {
cin >> n >> k;
combination c(n);
k = min(k, n);
mint ans = 0;
rep(i, k+1) {
ans += c(n,i) * c(n-1, i);
}
cout << ans.x << endl;
return 0;
}
|
#include <Control/vddispatcher.h>
VDDispatcher::VDDispatcher(QObject *parent) : QObject(parent)
{
/* ide jon majd a settings osztaly peldanya, amely alapjan a vdcontrol es a gui funkcioit
osszekapcsoljuk. (billentyuparancs es egyeb marhasagok pld.
Scriptelesnel ez az osztaly jo lehet event-kezelesre is.
*/
//this->setParent(parent);
//TODO: megtalálni miért nem a VDFileControl ennek a faterja.
}
void VDDispatcher::VDFileItemReadyToDisplay(VDFileItem *item){
qDebug() << "ReadyToDisplay: " << item;
}
void VDDispatcher::PanelItemDoubleClicked(QString standardUrl,int panel){
// ide kerülhet a duplaklikk kiertekelesere keszulo kod
emit ExecutionRequest(standardUrl,panel);
}
|
#ifndef CODEGENERATOR_H
#define CODEGENERATOR_H
#include "../syntaxtree/aggregates.h"
/**
* Abstract interface to which every code generator for tiny should adhere
*/
class CodeGenerator {
public:
/**
* Generate code for all given identifiers (variables, arrays and functions)
* The passed variables and arrays are globals.
*/
virtual void generateCode(Identifiers& ids) = 0;
/**
* Virtual destructor.
*/
virtual ~CodeGenerator() { }
};
#endif
|
#include <iostream>
#include "world.h"
int main() {
World& world = World::instance();
Country* scotland = world.getCountry("Scotland");
Country* catalonia = world.getCountry("Catalonia");
Country* england = world.getCountry("England");
Country* spain = world.getCountry("Spain");
Union* eu = world.getUnion("European Union");
spain->detachCountry(catalonia);
england->detachCountry(scotland);
eu->attachCountry(catalonia);
eu->attachCountry(scotland);
std::cout << world.giveSupport() << std::endl;
return 0;
}
|
//
// DataFile.h
// Homework6
//
// Created by HeeCheol Kim on 2018. 10. 12..
// Copyright © 2018년 HeeCheol Kim. All rights reserved.
//
#pragma once
#include <string.h>
using namespace std;
class DataFile {
public:
DataFile() {
this->filename = "";
}
~DataFile() {}
inline void setFile(string filename) { this->filename = filename; }
inline string getFile() { return this->filename; }
private:
string filename;
};
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <queue>
#include <sstream>
using namespace std;
/*
位运算方法,二进制表示下,某一位a与b不同才能得到1(0+1或者1+0),某一位a与b相同能得到0(0+0或者1+1进位)
我们再保留进位 (a&b)<<1,如果进位为0时加法完成
*/
class Solution {
public:
int Add(int a, int b)
{
int t;
while(b){
t = a^b;
b = (a&b)<<1;
a = t;
} return a;
}
};
int main(){
return 0;
}
|
/**
*
* @file TCP.hpp
* @brief TCP communication class
* @auther Naoki Takahashi
*
**/
#pragma once
#include <memory>
#include <string>
#include <boost/asio.hpp>
namespace IO {
namespace Communicator {
class TCP {
public :
TCP(const short &port);
TCP(const TCP &) = delete;
~TCP();
boost::system::error_code &server_v4(),
&server_v6();
std::string read();
boost::system::error_code &read(std::string &read_string);
boost::system::error_code &client(const std::string &address);
boost::system::error_code &write(const std::string &buffer);
private :
std::unique_ptr<short> port;
std::unique_ptr<boost::asio::io_service> io_service;
std::unique_ptr<boost::system::error_code> error_code;
std::unique_ptr<boost::asio::ip::tcp::socket> socket;
std::unique_ptr<boost::asio::ip::tcp::endpoint> endpoint;
std::unique_ptr<boost::asio::ip::tcp::acceptor> acceptor;
boost::system::error_code &accept(),
&connect();
};
}
}
|
#ifndef METROMAP_MAP_MAP_H
#define METROMAP_MAP_MAP_H
#include <QHash>
#include <QList>
#include <QSharedPointer>
class QString;
namespace metro {
class Station;
class Map
{
public:
typedef QHash<quint32, QSharedPointer<Station> >::const_iterator StationIterator;
QList<quint32> stationsId() const;
QList<quint32> linesId() const;
bool containsStation(quint32 id) const;
const Station& stationById(quint32 id) const;
void insertStation(const Station& station);
void removeStation(const Station& station);
void removeStation(quint32 id);
void loadFromFile(const QString& fileName);
void saveToFile(const QString& fileName) const;
QList<quint32> findTimeOptimizedPath(quint32 from, quint32 to) const;
QList<quint32> findCrossOverOptimizedPath(quint32 from, quint32 to) const;
QList<quint32> findPath(quint32 from, quint32 to, qint32 crossoverPenalty) const;
QString debugString() const;
private:
void updateLinks(const Station& station);
void removeLinks(const Station& station);
void rebuildStationsGraph();
QList<StationIterator> findDijkstraPath(const StationIterator& from,
const StationIterator& to,
qint32 crossoverPenalty = 0) const;
private:
QHash<quint32, QSharedPointer<Station> > m_stations;
QHash<StationIterator, QList<StationIterator> > m_graph;
};
} // metro
inline uint qHash(const QHash<quint32, QSharedPointer<metro::Station> >::const_iterator& key)
{
return qHash(key.key());
}
#endif // METROMAP_MAP_MAP_H
|
#include "EditorInputHandler.h"
EditorInputHandler::EditorInputHandler(
HINSTANCE handleInstance,
HWND handle,
Camera* camera,
int w,
int h)
{
this->m_Width = w;
this->m_Height = h;
HRESULT hr = DirectInput8Create(
handleInstance,
DIRECTINPUT_VERSION,
IID_IDirectInput8,
(void**)&m_directInput,
NULL);
//hr = m_directInput->CreateDevice(GUID_SysKeyboard,
// &DIKeyboard,
// NULL);
hr = m_directInput->CreateDevice(GUID_SysMouse,
&DIMouse,
NULL);
//hr = DIKeyboard->SetDataFormat(&c_dfDIKeyboard);
//hr = DIKeyboard->SetCooperativeLevel(handle, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
hr = DIMouse->SetDataFormat(&c_dfDIMouse);
hr = DIMouse->SetCooperativeLevel(handle, DISCL_EXCLUSIVE | DISCL_NOWINKEY | DISCL_FOREGROUND);
//this->m_hwnd = handle;
this->m_Camera = camera;
this->m_PreviousPos = camera->GetCameraPos();
for (size_t i = 0; i < NUMBOOLS; i++)
{
this->m_KeysHeld[i] = false;
}
DIMouse->Acquire();
}
EditorInputHandler::~EditorInputHandler()
{
}
void EditorInputHandler::KeyboardMovement(double dT)
{
float speed = 4.0f * dT;
float translateCameraX = 0, translateCameraY = 0, translateCameraZ = 0;
if (m_KeysHeld[Bools::SHIFT] == true)
{
if (this->m_KeysHeld[Bools::W] == true)
translateCameraZ += speed;
if (this->m_KeysHeld[Bools::A] == true)
translateCameraX -= speed;
if (this->m_KeysHeld[Bools::S] == true)
translateCameraZ -= speed;
if (this->m_KeysHeld[Bools::D] == true)
translateCameraX += speed;
if (this->m_KeysHeld[Bools::C] == true)
translateCameraY -= speed;
if (this->m_KeysHeld[Bools::SPACE] == true)
translateCameraY += speed;
MouseZoom(dT);
}
else {
if (this->m_KeysHeld[Bools::SPACE] == true)
translateCameraY += speed;
}
if (this->m_KeysHeld[ALT] == true)
MouseMovement(dT);
if ((translateCameraY || translateCameraZ || translateCameraX))
{
DirectX::XMFLOAT3 posTranslation =
DirectX::XMFLOAT3(
float(translateCameraX),
float(translateCameraY),
float(translateCameraZ)
);
this->m_PreviousPos = this->m_Camera->GetCameraPos();
this->m_Camera->ApplyLocalTranslation(
float(translateCameraX),
float(translateCameraY),
float(translateCameraZ)
);
this->m_Camera->UpdateView();
}
}
void EditorInputHandler::MouseMovement(double dT)
{
DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &m_mouse.currentState);
float pitch = 0;
float yaw = 0;
float rotationAmount = (DirectX::XM_PI / 8) / 2;
if (m_mouse.currentState.rgbButtons[0])
{
if ((m_mouse.currentState.lX != m_mouse.lastState.lX) || (m_mouse.currentState.lY != m_mouse.lastState.lY))
{
pitch += m_mouse.currentState.lX * 0.01f;
yaw += m_mouse.currentState.lY * 0.01f;
// Ensure the mouse location doesn't exceed the screen width or height.
if (this->m_mouse.x < 0) { this->m_mouse.x = 0; }
if (this->m_mouse.y < 0) { this->m_mouse.y = 0; }
if (this->m_mouse.x > m_Width) { this->m_mouse.x = m_Width; }
if (this->m_mouse.y > m_Height) { this->m_mouse.y = m_Height; }
m_mouse.lastState = m_mouse.currentState;
}
}
DirectX::XMFLOAT4 camUpFloat;
DirectX::XMFLOAT3 camPosFloat;
DirectX::XMFLOAT3 camTargetFloat;
this->m_Camera->GetCameraUp(camUpFloat);
camPosFloat = this->m_Camera->GetCameraPos();
camTargetFloat = this->m_Camera->GetLookAt();
DirectX::XMVECTOR rotationVector;
DirectX::XMVECTOR camUpVec = { 0.0f, 1.0f,0.0f,0.0f };//DirectX::XMLoadFloat4(&camUpFloat);
DirectX::XMVECTOR camPosVec = DirectX::XMLoadFloat3(&camPosFloat);
DirectX::XMVECTOR camTargetVec = DirectX::XMLoadFloat3(&camTargetFloat);
DirectX::XMVECTOR camDir = DirectX::XMVector3Normalize(DirectX::XMVectorSubtract(camTargetVec, camPosVec));
DirectX::XMVECTOR camRight = DirectX::XMVector3Normalize(DirectX::XMVector3Cross(camDir, camUpVec));
camRight.m128_f32[3] = rotationAmount * -yaw;
camUpVec.m128_f32[3] = rotationAmount * pitch;
if (pitch||yaw)
{
this->m_Camera->RotateCamera(camRight);
this->m_Camera->RotateCamera(camUpVec);
};
this->m_Camera->UpdateView();
}
void EditorInputHandler::MouseZoom(double dT)
{
DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &m_mouse.currentState);
float speedrot = 2.5f * dT;
float translateCameraZ = 0;
if (m_mouse.currentState.rgbButtons[0])
{
if (m_mouse.currentState.lY < 0)
{
translateCameraZ += speedrot;
}
if (m_mouse.currentState.lY > 0)
{
translateCameraZ -= speedrot;
}
}
if (translateCameraZ)
{
DirectX::XMFLOAT3 posTranslation =
DirectX::XMFLOAT3(
0.0f,
0.0f,
float(translateCameraZ)
);
this->m_PreviousPos = this->m_Camera->GetCameraPos();
this->m_Camera->ApplyLocalTranslation(
0.0f,
0.0f,
float(translateCameraZ)
);
this->m_Camera->UpdateView();
}
}
void EditorInputHandler::CameraReset()
{
this->m_Camera->Initialize(this->m_Width / this->m_Height);
this->m_Camera->SetLookAt(DirectX::XMVECTOR{ 0.0f, 0.0f, 0.0f, 1.0f });
this->m_Camera->SetCameraPos(DirectX::XMVECTOR{ 0.0f, 0.0f, -1.0f, 1.0f });
this->m_Camera->UpdateView();
}
void EditorInputHandler::UpdateMouse()
{
DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &m_mouse.currentState);
this->m_mouse.x = this->m_point.x();
this->m_mouse.y = this->m_point.y();
if (this->m_mouse.x > this->m_Width)
this->m_mouse.x = this->m_Width;
else if (this->m_mouse.x < 0)
this->m_mouse.x = 0;
if (this->m_mouse.y > this->m_Height)
this->m_mouse.y = this->m_Height;
else if (this->m_mouse.y < 0)
this->m_mouse.y = 0;
if (this->m_mouse.leftHeld)
{
SelectionHandler::GetInstance()->ProjectRay(m_mouse.x, m_mouse.y);
SelectionHandler::GetInstance()->MoveObject(m_KeysHeld[Bools::CONTROL]);
}
}
void EditorInputHandler::mouseButtonDown(QMouseEvent * evt)
{
if (evt->button() == Qt::LeftButton && !this->m_KeysHeld[ALT])
{
////*MOUSEPICKING*//
SelectionHandler::GetInstance()->ProjectRay(m_mouse.x, m_mouse.y);
bool object = false;
bool widget = false;
if (SelectionHandler::GetInstance()->HasSelection() )
{
widget = SelectionHandler::GetInstance()->PickTransformWidget();
}
if (!widget)
object = SelectionHandler::GetInstance()->PickObjectSelection();
if (object || widget)
{
SelectionHandler::GetInstance()->SetSelection(true);
}
else if(!this->m_KeysHeld[ALT])
{
SelectionHandler::GetInstance()->SetSelection(false);
}
this->m_mouse.leftHeld = true;
}
}
void EditorInputHandler::mouseButtonRelease(QMouseEvent * evt)
{
if (evt->button() == Qt::LeftButton)
{
this->m_mouse.leftHeld = false;
SelectionHandler::GetInstance()->SetActiveAxis(TransformWidget::NONE);
}
}
void EditorInputHandler::keyReleased(QKeyEvent * evt)
{
switch (evt->key())
{
case Qt::Key_Shift:
m_KeysHeld[Bools::SHIFT] = false;
break;
case Qt::Key_Alt:
m_KeysHeld[Bools::ALT] = false;
break;
case Qt::Key_Control:
m_KeysHeld[Bools::CONTROL] = false;
m_ableToDuplicate = true;
break;
case Qt::Key_W:
m_KeysHeld[Bools::W] = false;
break;
case Qt::Key_A:
m_KeysHeld[Bools::A] = false;
break;
case Qt::Key_S:
m_KeysHeld[Bools::S] = false;
break;
case Qt::Key_D:
m_KeysHeld[Bools::D] = false;
break;
case Qt::Key_C:
m_KeysHeld[Bools::C] = false;
break;
case Qt::Key_Space:
m_KeysHeld[Bools::SPACE] = false;
break;
default:
break;
}
}
void EditorInputHandler::ViewPortChanged(float height, float width)
{
this->m_Height = height;
this->m_Width = width;
SelectionHandler::GetInstance()->updateWindowSize(height, width);
}
void EditorInputHandler::deleteModel()
{
if (SelectionHandler::GetInstance()->HasSelection())
{
LevelHandler::GetInstance()->GetCurrentLevel()->RemoveModel
(SelectionHandler::GetInstance()->GetModelID(), SelectionHandler::GetInstance()->GetInstanceID());
SelectionHandler::GetInstance()->SetSelection(false);
}
}
void EditorInputHandler::detectInput(double dT, QKeyEvent* evt)
{
switch (evt->key())
{
case Qt::Key_Shift:
m_KeysHeld[Bools::SHIFT] = true;
break;
case Qt::Key_Alt:
m_KeysHeld[Bools::ALT] = true;
break;
case Qt::Key_Control:
m_KeysHeld[Bools::CONTROL] = true;
break;
case Qt::Key_W:
m_KeysHeld[Bools::W] = true;
break;
case Qt::Key_A:
m_KeysHeld[Bools::A] = true;
break;
case Qt::Key_S:
m_KeysHeld[Bools::S] = true;
break;
case Qt::Key_D:
if (m_ableToDuplicate)
{
if (this->m_KeysHeld[Bools::CONTROL] == true)
{
if (SelectionHandler::GetInstance()->HasSelection())
{
Container* temp = SelectionHandler::GetInstance()->GetSelected();
Container* newEntity = nullptr;
Resources::Status st = LevelHandler::GetInstance()->GetCurrentLevel()->DuplicateEntity(temp, newEntity);
if (st == Resources::Status::ST_OK)
SelectionHandler::GetInstance()->SetSelectedContainer(newEntity);
}
m_ableToDuplicate = false;
}
}
m_KeysHeld[Bools::D] = true;
break;
case Qt::Key_C:
m_KeysHeld[Bools::C] = true;
break;
case Qt::Key_Space:
m_KeysHeld[Bools::SPACE] = true;
break;
case Qt::Key_R:
CameraReset();
break;
case Qt::Key_Delete:
deleteModel();
break;
case (Qt::Key_0):
case (Qt::Key_Up) :
case (Qt::Key_Down) :
case (Qt::Key_Left) :
case (Qt::Key_Right) :
SelectionHandler::GetInstance()->RotateObject(evt->key());
break;
default:
break;
}
/*switch (evt->key())
{
case Qt::Key_R:
CameraReset();
break;
case (Qt::Key_Up):
case (Qt::Key_Down):
case (Qt::Key_Left):
case (Qt::Key_Right):
SelectionHandler::GetInstance()->RotateObject(evt->key());
break;
default:
break;
}*/
}
|
#include <iostream>
using namespace std;
int money[100];
int answer[10001];
int main(){
/*모든 answer 배열의 원소값을 매우 큰 값으로 초기화*/
for(int i = 0; i < 10001; i++){
answer[i] = 10001;
}
int n, m, x;
cin >> n >> m;
/*단위 화폐의 최소한의 지불 화폐 수는 1*/
for(int a = 0; a < n; a++){
cin >> x;
answer[x] = 1;
money[a] = x;
}
/*점화식: a[i] = (모든 a[i - x] + 1들 중 최솟값)
x 는 처음 입력한 단위 화폐들*/
for(int a = 1; a <= m; a++){
for(int b = 0; b < n; b++){
if(a-money[b] > 0){
answer[a] = min(answer[a], answer[a-money[b]] + 1);
}
}
}
if(answer[m] == 10001) cout << "-1" << endl;
else cout << answer[m] << endl;
return 0;
}
|
include "MORClass.h"
|
#include "LinkedList.h"
// default constructor (creates empty list)
LinkedList::LinkedList() {
head = NULL;
tail = NULL;
length = 0;
}
// constructor creates list when given head node (can be head of another list)
LinkedList::LinkedList(Node* h) {
head = h;
length = 0;
Node* curr = head;
Node* prev = curr;
while(curr != NULL) {
length++;
prev = curr;
curr = curr->next;
}
tail = prev;
}
// default destructor
LinkedList::~LinkedList() {
if (head != NULL) {
delete head;
}
}
// add a node to the linked list (nodes are added in assending order, smallest value at head)
Node* LinkedList::add(int data) {
Node* n = new Node(data);
length++;
// case of an empty list
if (head == NULL) {
n->next = NULL;
n->prev = NULL;
head = n;
tail = n;
return(head);
}
// case where we add to the head of the list
if (n->data <= head->data) {
n->next = head;
n->prev = NULL;
head = n;
return(head);
}
Node* prev = head;
Node* curr = head;
// move to the location for the data to be added
while ((curr != NULL) && (n->data > curr->data)) {
prev = curr;
curr = curr->next;
}
// case where we add to the middle of the list
if (curr != NULL) {
n->next = curr;
n->prev = prev;
prev->next = n;
curr->prev = n;
return(head);
}
// case where node is added to the end of the list
n->next = NULL;
n->prev = prev;
prev->next = n;
tail = n;
return(head);
}
// add a node to the linked list (nodes are added in assending order, smallest value at head)
Node* LinkedList::add(Node* n) {
length++;
// case of an empty list
if (head == NULL) {
n->next = NULL;
n->prev = NULL;
head = n;
tail = n;
return(head);
}
// case where we add to the head of the list
if (n->data <= head->data) {
n->next = head;
n->prev = NULL;
head = n;
return(head);
}
Node* prev = head;
Node* curr = head;
// move to the location for the data to be added
while ((curr != NULL) && (n->data > curr->data)) {
prev = curr;
curr = curr->next;
}
// case where we add to the middle of the list
if (curr != NULL) {
n->next = curr;
n->prev = prev;
prev->next = n;
curr->prev = n;
return(head);
}
void LinkedList::print() {
Node* temp = head;
cout << "Contents of Linked List: " << endl;
while (temp != NULL) {
cout << temp->data << endl;
temp = temp->next;
}
return;
}
|
#pragma once
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
#include "regressor.h"
using namespace std;
using namespace cv;
class FaceX
{
public:
// Construct the object and load model from file.
//
// filename: The file name of the model file.
//
// Throw runtime_error if the model file cannot be opened.
FaceX(const string &filename);
// Do face alignment.
//
// image: The image which contains face. Must be 8 bits gray image.
// face_rect: Where the face locates.
//
// Return the landmarks. The number and positions of landmarks depends on
// the model.
vector<Point2d> Alignment(Mat image, Rect face_rect) const;
// Return how many landmarks the model provides for a face.
int landmarks_count() const
{
return mean_shape_.size();
}
private:
vector<Point2d> mean_shape_;
vector<vector<Point2d>> test_init_shapes_;
vector<Regressor> stage_regressors_;
};
|
/***********************************************************************
created: 18/8/2011
author: Martin Preisler
purpose: Implements the Element class
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2011 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "CEGUI/Element.h"
#include "CEGUI/CoordConverter.h"
#include "CEGUI/System.h" // FIXME: only for root container size - display size
#include "CEGUI/Renderer.h" // FIXME: only for root container size - display size
#include "CEGUI/Logger.h"
#include <algorithm>
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4355) // 'this' is used to init unclipped rects
#endif
namespace CEGUI
{
const String Element::EventNamespace("Element");
const String Element::EventSized("Sized");
const String Element::EventMoved("Moved");
const String Element::EventHorizontalAlignmentChanged("HorizontalAlignmentChanged");
const String Element::EventVerticalAlignmentChanged("VerticalAlignmentChanged");
const String Element::EventRotated("Rotated");
const String Element::EventChildAdded("ChildAdded");
const String Element::EventChildRemoved("ChildRemoved");
const String Element::EventChildOrderChanged("ChildOrderChanged");
const String Element::EventZOrderChanged("ZOrderChanged");
const String Element::EventNonClientChanged("NonClientChanged");
const String Element::EventIsSizeAdjustedToContentChanged("IsSizeAdjustedToContentChanged");
//----------------------------------------------------------------------------//
// NB: we promised not to change incoming elements, but we don't want to prevent users from changing return values
std::pair<Element*, Element*> Element::getSiblingsInCommonAncestor(const Element* e1, const Element* e2)
{
if (!e1 || !e2)
return { nullptr, nullptr };
if (e1 == e2)
return { const_cast<Element*>(e1), const_cast<Element*>(e1) };
// Calculate depth of e1 and check if e2 is its ancestor
size_t depth1 = 0;
auto curr = e1;
do
{
++depth1;
curr = curr->getParentElement();
if (curr == e2)
return { const_cast<Element*>(e2), const_cast<Element*>(e2) };
}
while (curr);
// Calculate depth of e2 and check if e1 is its ancestor
size_t depth2 = 0;
curr = e2;
do
{
++depth2;
curr = curr->getParentElement();
if (curr == e1)
return { const_cast<Element*>(e1), const_cast<Element*>(e1) };
}
while (curr);
// Common ancestor is inherently at the same level in both branches.
// Prepare to search by moving both branches to the shallowest level.
while (depth2 > depth1)
{
e2 = e2->getParentElement();
--depth2;
}
while (depth1 > depth2)
{
e1 = e1->getParentElement();
--depth1;
}
// Now compare branches at the same level, starting from parents because
// we already know that e1 and e2 are not parents of each other.
while (depth1)
{
if (e1->getParentElement() == e2->getParentElement())
return { const_cast<Element*>(e1), const_cast<Element*>(e2) };
e1 = e1->getParentElement();
e2 = e2->getParentElement();
--depth1;
}
return { nullptr, nullptr };
}
//----------------------------------------------------------------------------//
Element::Element():
d_area(cegui_reldim(0), cegui_reldim(0), cegui_reldim(0), cegui_reldim(0)),
d_minSize(cegui_reldim(0), cegui_reldim(0)),
d_maxSize(cegui_reldim(0), cegui_reldim(0)),
d_pixelSize(0.0f, 0.0f),
d_rotation(1.f, 0.f, 0.f, 0.f), // <-- IDENTITY
d_pivot(UVector3(cegui_reldim(0.5f), cegui_reldim(0.5f), cegui_reldim(0.5f))),
d_unclippedOuterRect(this, &Element::getUnclippedOuterRect_impl),
d_unclippedInnerRect(this, &Element::getUnclippedInnerRect_impl)
{
addElementProperties();
}
//----------------------------------------------------------------------------//
void Element::setArea(const UVector2& pos, const USize& size, bool adjust_size_to_content)
{
// TODO: early exit if equal? or return false from notifyScreenAreaChanged if unchanged?
d_area.setPositionAndSize(pos, size);
notifyScreenAreaChanged(adjust_size_to_content);
}
//----------------------------------------------------------------------------//
void Element::notifyScreenAreaChanged(bool adjust_size_to_content)
{
// Update pixel size and detect resizing
const Sizef oldSize = d_pixelSize;
d_pixelSize = calculatePixelSize();
const bool sized = (d_pixelSize != oldSize);
// Update outer rect to detect moving
// NB: pixel size must be already updated
const glm::vec2 oldPos = d_unclippedOuterRect.getCurrent().d_min;
d_unclippedOuterRect.invalidateCache();
const glm::vec2 newPos = d_unclippedOuterRect.get().d_min;
const bool movedOnScreen = (newPos != oldPos);
// Check movement inside a parent
bool movedInParent = movedOnScreen;
if (d_parent)
{
const glm::vec2 newOffsetInParent = d_parent->d_unclippedOuterRect.get().d_min;
movedInParent = ((newPos - newOffsetInParent) != (oldPos - d_offsetInParent));
d_offsetInParent = newOffsetInParent;
}
// Handle outer rect changes and check if child content rects changed
const uint8_t flags = handleAreaChanges(movedOnScreen, movedInParent, sized);
if (!d_children.empty())
{
const bool needClientLayout = (flags & ClientSized);
const bool needNonClientLayout = (flags & NonClientSized);
if (needClientLayout || needNonClientLayout)
{
// We need full layouting when child area size changed or when explicitly requested
performChildLayout(needClientLayout, needNonClientLayout);
}
else if (flags)
{
// Lightweight code path for not resized widgets
const bool client = flags & (ClientMoved | ClientClippingChanged);
const bool nonClient = flags & (NonClientMoved | NonClientClippingChanged);
const bool clientMoved = flags & ClientMoved;
const bool nonClientMoved = flags & NonClientMoved;
for (Element* child : d_children)
if (child->isNonClient() ? nonClient : client)
child->handleAreaChangesRecursively(child->isNonClient() ? nonClientMoved : clientMoved);
}
}
if (movedInParent)
{
ElementEventArgs eventArgs(this);
onMoved(eventArgs);
}
if (sized)
{
ElementEventArgs eventArgs(this);
onSized(eventArgs);
if (adjust_size_to_content)
adjustSizeToContent();
}
}
//----------------------------------------------------------------------------//
uint8_t Element::handleAreaChanges(bool movedOnScreen, bool /*movedInParent*/, bool sized)
{
// Element has inner == outer, so all children are affected by outer rect changes
const uint8_t flags =
(movedOnScreen ? (NonClientMoved | ClientMoved) : 0) |
(sized ? (NonClientSized | ClientSized) : 0);
if (flags)
d_unclippedInnerRect.invalidateCache();
return flags;
}
//----------------------------------------------------------------------------//
// Lightweight version of notifyScreenAreaChanged
// TODO: can somehow merge with notifyScreenAreaChanged or at least rename consistently?
void Element::handleAreaChangesRecursively(bool movedOnScreen)
{
d_unclippedOuterRect.invalidateCache();
// There are guarantees:
// - our size didn't change because the parent size didn't
// - our offset in the parent didn't change because our area and its size didn't
const uint8_t flags = handleAreaChanges(movedOnScreen, false, false);
if (flags)
{
const bool client = flags & (ClientMoved | ClientClippingChanged);
const bool nonClient = flags & (NonClientMoved | NonClientClippingChanged);
const bool clientMoved = flags & ClientMoved;
const bool nonClientMoved = flags & NonClientMoved;
for (Element* child : d_children)
if (child->isNonClient() ? nonClient : client)
child->handleAreaChangesRecursively(child->isNonClient() ? nonClientMoved : clientMoved);
}
}
//----------------------------------------------------------------------------//
void Element::performChildLayout(bool client, bool nonClient)
{
if (client || nonClient)
for (Element* child : d_children)
if (child->isNonClient() ? nonClient : client)
child->notifyScreenAreaChanged();
}
//----------------------------------------------------------------------------//
void Element::setHorizontalAlignment(const HorizontalAlignment alignment)
{
if (d_horizontalAlignment == alignment)
return;
d_horizontalAlignment = alignment;
ElementEventArgs args(this);
onHorizontalAlignmentChanged(args);
}
//----------------------------------------------------------------------------//
void Element::setVerticalAlignment(const VerticalAlignment alignment)
{
if (d_verticalAlignment == alignment)
return;
d_verticalAlignment = alignment;
ElementEventArgs args(this);
onVerticalAlignmentChanged(args);
}
//----------------------------------------------------------------------------//
void Element::setMinSize(const USize& size)
{
d_minSize = size;
notifyScreenAreaChanged();
}
//----------------------------------------------------------------------------//
void Element::setMaxSize(const USize& size)
{
d_maxSize = size;
notifyScreenAreaChanged();
}
//----------------------------------------------------------------------------//
void Element::setAspectMode(AspectMode mode)
{
if (d_aspectMode == mode)
return;
d_aspectMode = mode;
// TODO: We want an Event and more smart rect update handling
// Ensure the area is calculated with the new aspect mode
// TODO: This potentially wastes effort, we should just mark it as dirty
// and postpone the calculation for as long as possible
notifyScreenAreaChanged();
}
//----------------------------------------------------------------------------//
void Element::setAspectRatio(float ratio)
{
if (d_aspectRatio == ratio)
return;
d_aspectRatio = ratio;
// TODO: We want an Event and more smart rect update handling
// Ensure the area is calculated with the new aspect ratio
// TODO: This potentially wastes effort, we should just mark it as dirty
// and postpone the calculation for as long as possible
notifyScreenAreaChanged();
}
//----------------------------------------------------------------------------//
void Element::setPixelAligned(const bool setting)
{
if (d_pixelAligned == setting)
return;
d_pixelAligned = setting;
// TODO: We want an Event and more smart rect update handling
// Ensure the area is calculated with the new pixel aligned setting
// TODO: This potentially wastes effort, we should just mark it as dirty
// and postpone the calculation for as long as possible
notifyScreenAreaChanged();
}
//----------------------------------------------------------------------------//
Sizef Element::calculatePixelSize(bool skipAllPixelAlignment) const
{
// calculate pixel sizes for everything, so we have a common format for
// comparisons.
const Sizef rootSize = getRootContainerSize();
Sizef absMin(CoordConverter::asAbsolute(d_minSize, rootSize, false));
const Sizef absMax(CoordConverter::asAbsolute(d_maxSize, rootSize, false));
Sizef ret = CoordConverter::asAbsolute(getSize(), getBasePixelSize(skipAllPixelAlignment), false);
// in case absMin components are larger than absMax ones,
// max size takes precedence
if (absMax.d_width != 0.0f && absMin.d_width > absMax.d_width)
{
absMin.d_width = absMax.d_width;
CEGUI_LOGINSANE("MinSize resulted in an absolute pixel size with "
"width larger than what MaxSize resulted in");
}
if (absMax.d_height != 0.0f && absMin.d_height > absMax.d_height)
{
absMin.d_height = absMax.d_height;
CEGUI_LOGINSANE("MinSize resulted in an absolute pixel size with "
"height larger than what MaxSize resulted in");
}
// limit new pixel size to: minSize <= newSize <= maxSize
if (ret.d_width < absMin.d_width)
ret.d_width = absMin.d_width;
else if (absMax.d_width != 0.0f && ret.d_width > absMax.d_width)
ret.d_width = absMax.d_width;
if (ret.d_height < absMin.d_height)
ret.d_height = absMin.d_height;
else if (absMax.d_height != 0.0f && ret.d_height > absMax.d_height)
ret.d_height = absMax.d_height;
if (d_aspectMode != AspectMode::Ignore)
{
// make sure we respect current aspect mode and ratio
ret.scaleToAspect(d_aspectMode, d_aspectRatio);
/* Make sure we haven't blown any of the hard limits. Still maintain the
aspect when we do this.
NOTE: When the hard min max limits are unsatisfiable with the aspect
lock mode, the result won't be limited by both limits! */
if (ret.d_width < absMin.d_width)
{
ret.d_height *= absMin.d_width / ret.d_width;
ret.d_width = absMin.d_width;
}
else if (ret.d_height < absMin.d_height)
{
ret.d_width *= absMin.d_height / ret.d_height;
ret.d_height = absMin.d_height;
}
else if (absMax.d_width != 0.f && ret.d_width > absMax.d_width)
{
ret.d_height *= absMax.d_width / ret.d_width;
ret.d_width = absMax.d_width;
}
else if (absMax.d_height != 0.f && ret.d_height > absMax.d_height)
{
ret.d_width *= absMax.d_height / ret.d_height;
ret.d_height = absMax.d_height;
}
}
if (d_pixelAligned)
{
ret.d_width = CoordConverter::alignToPixels(ret.d_width);
ret.d_height = CoordConverter::alignToPixels(ret.d_height);
}
return ret;
}
//----------------------------------------------------------------------------//
Sizef Element::getParentPixelSize(bool skipAllPixelAlignment) const
{
if (d_parent)
{
return skipAllPixelAlignment ?
d_parent->calculatePixelSize(true) : d_parent->getPixelSize();
}
else
{
return getRootContainerSize();
}
}
//----------------------------------------------------------------------------//
Sizef Element::getBasePixelSize(bool skipAllPixelAlignment) const
{
if (skipAllPixelAlignment)
{
return Sizef((d_parent && !d_nonClient) ?
d_parent->getUnclippedInnerRect().getFresh(true).getSize() :
getParentPixelSize(true));
}
else
{
return Sizef((d_parent && !d_nonClient) ?
d_parent->getUnclippedInnerRect().get().getSize() :
getParentPixelSize());
}
}
//----------------------------------------------------------------------------//
Sizef Element::getRootContainerSize() const
{
return System::getSingleton().getRenderer()->getDisplaySize();
}
//----------------------------------------------------------------------------//
void Element::adjustSizeToContent()
{
adjustSizeToContent_direct();
}
//----------------------------------------------------------------------------//
Sizef Element::getContentSize() const
{
throw InvalidRequestException("This function isn't implemented for this type of element.");
}
//----------------------------------------------------------------------------//
UDim Element::getWidthOfAreaReservedForContentLowerBoundAsFuncOfElementWidth() const
{
throw InvalidRequestException("This function isn't implemented for this type of element.");
}
//----------------------------------------------------------------------------//
UDim Element::getHeightOfAreaReservedForContentLowerBoundAsFuncOfElementHeight() const
{
throw InvalidRequestException("This function isn't implemented for this type of element.");
}
/*----------------------------------------------------------------------------//
By definition of
"getWidthOfAreaReservedForContentLowerBoundAsFuncOfElementWidth" (see its
doc), if we let "t" be the width of the area of the element which is
reserved for content and "n" be the element width, then the following holds
true:
t >= inverse.d_scale*m + inverse.d_offset (1)
Therefore, for every non-negative number "c", if we want "t >= c" to be
true, it's sufficient to require that:
inverse.d_scale*m + inverse.d_offset >= c
Assume "inverse.d_scale > 0". Then that's equivalent to:
m >= (c - inverse.d_offset) / inverse.d_scale
If we let "a = 1/inverse.d_scale" and
"b = -inverse.d_offset / inverse.d_scale" then that's equivalent to:
m >= a*c +b
So we have the following: for every non-negative number "c", if
"m >= a*c +b" then "t >= c". Therefore, by the definition of
"getElementWidthLowerBoundAsFuncOfWidthOfAreaReservedForContent" (see its
doc), we can return:
UDim(a, b) = UDim(1.f /inverse.d_scale, -inverse.d_offset /inverse.d_scale)
Now, if "inverse.d_scale = 0" obviously all the above doesn't work.f In this
case we have, from (1):
t >= inverse.d_scale*m + inverse.d_offset = inverse.d_offset
Which means the width of the area of the element which is reserved for
content that we can guarantee is constant and doesn't depend on the element
width. Therefore, no matter what "a" and "b" we choose, we can't guarantee
that for every non-negative number "c", if "m >= a*c +b" then "t >= c"
(because all we know is t >= inverse.d_offset). Therefore in such a case we
throw an exception.
------------------------------------------------------------------------------*/
UDim Element::getElementWidthLowerBoundAsFuncOfWidthOfAreaReservedForContent() const
{
UDim inverse(getWidthOfAreaReservedForContentLowerBoundAsFuncOfElementWidth());
if (inverse.d_scale == 0.f)
throw InvalidRequestException("Content width doesn't depend on the element width.");
return UDim(1.f /inverse.d_scale, -inverse.d_offset /inverse.d_scale);
}
/*----------------------------------------------------------------------------//
The implementation of this method is equivalent to that of
"getElementWidthLowerBoundAsFuncOfWidthOfAreaReservedForContent". See the
comment before the definition of that method for more details.
------------------------------------------------------------------------------*/
UDim Element::getElementHeightLowerBoundAsFuncOfHeightOfAreaReservedForContent() const
{
UDim inverse(getHeightOfAreaReservedForContentLowerBoundAsFuncOfElementHeight());
if (inverse.d_scale == 0.f)
throw InvalidRequestException("Content height doesn't depend on the element height.");
return UDim(1.f /inverse.d_scale, -inverse.d_offset /inverse.d_scale);
}
//----------------------------------------------------------------------------//
void Element::adjustSizeToContent_direct()
{
if (!isSizeAdjustedToContent())
return;
const float epsilon = adjustSizeToContent_getEpsilon();
USize size_func(UDim(-1.f, -1.f), UDim(-1.f, -1.f));
Sizef new_pixel_size(getPixelSize());
const Sizef contentSize = getContentSize();
if (isWidthAdjustedToContent())
{
size_func.d_width = getElementWidthLowerBoundAsFuncOfWidthOfAreaReservedForContent();
new_pixel_size.d_width = std::ceil(
(contentSize.d_width + epsilon) * size_func.d_width.d_scale + size_func.d_width.d_offset);
}
if (isHeightAdjustedToContent())
{
size_func.d_height = getElementHeightLowerBoundAsFuncOfHeightOfAreaReservedForContent();
new_pixel_size.d_height = std::ceil(
(contentSize.d_height + epsilon) * size_func.d_height.d_scale + size_func.d_height.d_offset);
}
if (getAspectMode() != AspectMode::Ignore)
{
if (isWidthAdjustedToContent())
{
if (isHeightAdjustedToContent())
new_pixel_size.scaleToAspect(AspectMode::Expand, getAspectRatio());
else
new_pixel_size.scaleToAspect(AspectMode::AdjustHeight, getAspectRatio());
}
else
{
if (isHeightAdjustedToContent())
new_pixel_size.scaleToAspect(AspectMode::AdjustWidth, getAspectRatio());
}
}
USize new_size(getSize());
if (isWidthAdjustedToContent() || (getAspectMode() != AspectMode::Ignore))
new_size.d_width = UDim(0.f, new_pixel_size.d_width);
if (isHeightAdjustedToContent() || (getAspectMode() != AspectMode::Ignore))
new_size.d_height = UDim(0.f, new_pixel_size.d_height);
setSize(new_size, false);
}
//----------------------------------------------------------------------------//
float Element::adjustSizeToContent_getEpsilon() const
{
return 1.f / 64.f;
}
/*----------------------------------------------------------------------------//
Return the lowest power of 2 (with non-negative integer exponent) which is
greater than or equal to "value".
------------------------------------------------------------------------------*/
static unsigned int powOf2Supremum(unsigned int value)
{
unsigned int num_of_digits = 0;
if (value != 0)
{
--value;
while (value != 0)
{
++num_of_digits;
value >>= 1;
}
}
return 1u << num_of_digits;
}
//----------------------------------------------------------------------------//
Sizef Element::getSizeAdjustedToContent_bisection(const USize& size_func, float domain_min, float domain_max) const
{
int domain_min_int(static_cast<int>(std::floor(domain_min)));
int domain_max_int(static_cast<int>(std::ceil(domain_max)));
if (domain_min_int >= domain_max_int)
throw InvalidRequestException("Length of domain is 0.");
/* First, enlarge the domain so that it's a power of 2 (with non-negative
integer exponent). This makes the bisection use only integer
parameters. */
int domain_size(domain_max_int - domain_min_int);
int domain_size_pow_of_2(static_cast<int>(powOf2Supremum(domain_size)));
domain_min_int -= domain_size_pow_of_2 - domain_size;
Sizef element_size(0.f, 0.f);
while (true)
{
int param((domain_min_int+domain_max_int+1) / 2);
float param_float(static_cast<float>(param));
element_size = Sizef(size_func.d_width.d_scale*param_float + size_func.d_width.d_offset,
size_func.d_height.d_scale*param_float + size_func.d_height.d_offset);
if (domain_max_int <= domain_min_int+1)
break;
if (param_float <= domain_min)
domain_min_int = param;
else if (param_float >= domain_max ||
((element_size.d_width >= 0) &&
(element_size.d_height >= 0) &&
contentFitsForSpecifiedElementSize(element_size)))
domain_max_int = param;
else
domain_min_int = param;
}
return element_size;
}
//----------------------------------------------------------------------------//
bool Element::contentFitsForSpecifiedElementSize(const Sizef& element_size) const
{
return contentFitsForSpecifiedElementSize_tryByResizing(element_size);
}
//----------------------------------------------------------------------------//
bool Element::contentFitsForSpecifiedElementSize_tryByResizing(const Sizef& element_size) const
{
const USize current_size(getSize());
const_cast<Element*>(this)->setSize(
USize(UDim(0.f, element_size.d_width), UDim(0.f, element_size.d_height)), false);
const bool ret = contentFits();
const_cast<Element*>(this)->setSize(current_size, false);
return ret;
}
//----------------------------------------------------------------------------//
bool Element::contentFits() const
{
throw InvalidRequestException("This function isn't implemented for this type of element.");
}
//----------------------------------------------------------------------------//
void Element::setRotation(const glm::quat& rotation)
{
if (d_rotation == rotation)
return;
d_rotation = rotation;
ElementEventArgs args(this);
onRotated(args);
}
//----------------------------------------------------------------------------//
void Element::setPivot(const UVector3& pivot)
{
if (d_pivot == pivot)
return;
d_pivot = pivot;
ElementEventArgs args(this);
onRotated(args);
}
//----------------------------------------------------------------------------//
void Element::addChild(Element* element)
{
if (!element)
throw InvalidRequestException("Can't add NULL to Element as a child!");
if (element == this)
throw InvalidRequestException("Can't make element its own child - "
"this->addChild(this); is forbidden.");
// if the element is already a child of this Element, this is a NOOP
if (isChild(element))
return;
addChild_impl(element);
ElementEventArgs args(element);
onChildAdded(args);
}
//----------------------------------------------------------------------------//
void Element::removeChild(Element* element)
{
if (!element)
throw InvalidRequestException("NULL can't be a child of any Element, "
"it makes little sense to ask for its "
"removal");
removeChild_impl(element);
ElementEventArgs args(element);
onChildRemoved(args);
}
//----------------------------------------------------------------------------//
void Element::addChildAtIndex(Element* element, size_t index)
{
addChild(element);
moveChildToIndex(element, index);
}
//----------------------------------------------------------------------------//
void Element::removeChildAtIndex(size_t index)
{
removeChild(getChildElementAtIndex(index));
}
//----------------------------------------------------------------------------//
void Element::moveChildToIndex(size_t indexFrom, size_t indexTo)
{
indexTo = std::min(indexTo, d_children.size());
if (indexFrom == indexTo || indexFrom >= d_children.size())
{
return;
}
// we get the iterator of the old position
std::vector<Element*>::iterator it = d_children.begin();
std::advance(it, indexFrom);
Element* child = *it;
// erase the child from it's old position
d_children.erase(it);
// if the window comes before the point we want to insert to,
// we have to decrement the position
if (indexFrom < indexTo)
{
--indexTo;
}
// find iterator of the new position
it = d_children.begin();
std::advance(it, indexTo);
// and insert the window there
d_children.insert(it, child);
ElementEventArgs args(this);
onChildOrderChanged(args);
}
//----------------------------------------------------------------------------//
void Element::moveChildToIndex(Element* child, size_t index)
{
moveChildToIndex(getChildIndex(child), index);
}
//----------------------------------------------------------------------------//
void Element::moveChildByDelta(Element* child, int delta)
{
const size_t oldIndex = getChildIndex(child);
const size_t newIndex =
static_cast<size_t>(std::max(0, static_cast<int>(oldIndex) + delta));
moveChildToIndex(oldIndex, newIndex);
}
//----------------------------------------------------------------------------//
void Element::swapChildren(size_t index1, size_t index2)
{
if (index1 < d_children.size() &&
index2 < d_children.size() &&
index1 != index2)
{
std::swap(d_children[index1], d_children[index2]);
ElementEventArgs args(this);
onChildOrderChanged(args);
}
}
//----------------------------------------------------------------------------//
void Element::swapChildren(Element* child1, Element* child2)
{
if (child1 != child2)
swapChildren(getChildIndex(child1), getChildIndex(child2));
}
//----------------------------------------------------------------------------//
size_t Element::getChildIndex(const Element* child) const
{
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
if (d_children[i] == child)
return i;
// Any value >= getChildCount() must be treated as invalid
return std::numeric_limits<size_t>().max();
}
//----------------------------------------------------------------------------//
bool Element::isChild(const Element* element) const
{
return std::find(d_children.begin(), d_children.end(), element) != d_children.end();
}
//----------------------------------------------------------------------------//
bool Element::isDescendantOf(const Element* element) const
{
const Element* current = d_parent;
while (current)
{
if (current == element)
return true;
current = current->d_parent;
}
return false;
}
//----------------------------------------------------------------------------//
bool Element::isInChain(const Element* mostNested, const Element* leastNested) const
{
const Element* current = mostNested;
while (current && current != leastNested)
{
if (current == this)
return true;
current = current->d_parent;
}
return (this == leastNested);
}
//----------------------------------------------------------------------------//
void Element::setNonClient(const bool setting)
{
if (setting == d_nonClient)
return;
d_nonClient = setting;
ElementEventArgs args(this);
onNonClientChanged(args);
}
//----------------------------------------------------------------------------//
void Element::setAdjustWidthToContent(bool value)
{
if (d_isWidthAdjustedToContent == value)
return;
d_isWidthAdjustedToContent = value;
ElementEventArgs args(this);
onIsSizeAdjustedToContentChanged(args);
}
//----------------------------------------------------------------------------//
void Element::setAdjustHeightToContent(bool value)
{
if (d_isHeightAdjustedToContent == value)
return;
d_isHeightAdjustedToContent = value;
ElementEventArgs args(this);
onIsSizeAdjustedToContentChanged(args);
}
//----------------------------------------------------------------------------//
void Element::onIsSizeAdjustedToContentChanged(ElementEventArgs& e)
{
adjustSizeToContent();
fireEvent(EventIsSizeAdjustedToContentChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Element::addElementProperties()
{
const String propertyOrigin("Element");
CEGUI_DEFINE_PROPERTY(Element, URect,
"Area", "Property to get/set the unified area rectangle. Value is a \"URect\".",
&Element::setArea, &Element::getArea, URect(UDim(0, 0), UDim(0, 0), UDim(0, 0), UDim(0, 0))
);
CEGUI_DEFINE_PROPERTY_NO_XML(Element, UVector2,
"Position", "Property to get/set the unified position. Value is a \"UVector2\".",
&Element::setPosition, &Element::getPosition, UVector2(UDim(0, 0), UDim(0, 0))
);
CEGUI_DEFINE_PROPERTY(Element, VerticalAlignment,
"VerticalAlignment", "Property to get/set the vertical alignment. Value is one of \"Top\", \"Centre\" or \"Bottom\".",
&Element::setVerticalAlignment, &Element::getVerticalAlignment, VerticalAlignment::Top
);
CEGUI_DEFINE_PROPERTY(Element, HorizontalAlignment,
"HorizontalAlignment", "Property to get/set the horizontal alignment. Value is one of \"Left\", \"Centre\" or \"Right\".",
&Element::setHorizontalAlignment, &Element::getHorizontalAlignment, HorizontalAlignment::Left
);
CEGUI_DEFINE_PROPERTY_NO_XML(Element, USize,
"Size", "Property to get/set the unified size. Value is a \"USize\".",
&Element::setSize, &Element::getSize, USize(UDim(0, 0), UDim(0, 0))
);
CEGUI_DEFINE_PROPERTY(Element, USize,
"MinSize", "Property to get/set the unified minimum size. Value is a \"USize\".",
&Element::setMinSize, &Element::getMinSize, USize(UDim(0, 0), UDim(0, 0))
);
CEGUI_DEFINE_PROPERTY(Element, USize, "MaxSize",
"Property to get/set the unified maximum size. Value is a \"USize\". "
"Note that zero means no maximum size.",
&Element::setMaxSize, &Element::getMaxSize, USize(UDim(0, 0), UDim(0, 0))
);
CEGUI_DEFINE_PROPERTY(Element, AspectMode,
"AspectMode", "Property to get/set the 'aspect mode' setting. Value is either \"Ignore\", \"Shrink\", "
"\"Expand\", \"AdjustHeight\" or \"AdjustWidth\".",
&Element::setAspectMode, &Element::getAspectMode, AspectMode::Ignore
);
CEGUI_DEFINE_PROPERTY(Element, float,
"AspectRatio", "Property to get/set the aspect ratio. Only applies when aspect mode is not \"Ignore\".",
&Element::setAspectRatio, &Element::getAspectRatio, 1.0 / 1.0
);
CEGUI_DEFINE_PROPERTY(Element, bool,
"PixelAligned", "Property to get/set whether the Element's size and position should be pixel aligned. "
"Value is either \"true\" or \"false\".",
&Element::setPixelAligned, &Element::isPixelAligned, true
);
CEGUI_DEFINE_PROPERTY(Element, glm::quat,
"Rotation", "Property to get/set the Element's rotation. Value is a quaternion (glm::quat): "
"\"w:[w_float] x:[x_float] y:[y_float] z:[z_float]\""
"or \"x:[x_float] y:[y_float] z:[z_float]\" to convert from Euler angles (in degrees).",
&Element::setRotation, &Element::getRotation, glm::quat(1.0, 0.0, 0.0, 0.0)
);
CEGUI_DEFINE_PROPERTY(Element, UVector3,
"Pivot", "Property to get/set the Element's rotation's pivot point.",
&Element::setPivot, &Element::getPivot,
UVector3(cegui_reldim(1./2), cegui_reldim(1./2), cegui_reldim(1./2))
);
CEGUI_DEFINE_PROPERTY(Element, bool,
"NonClient", "Property to get/set whether the Element is 'non-client'. "
"Value is either \"true\" or \"false\".",
&Element::setNonClient, &Element::isNonClient, false
);
CEGUI_DEFINE_PROPERTY(Element, bool, "AdjustWidthToContent",
"Property to get/set whether to " "automatically adjust the element's " "width to the element's content. "
"Value is either \"true\" or \"false\".",
&Element::setAdjustWidthToContent, &Element::isWidthAdjustedToContent, false
);
CEGUI_DEFINE_PROPERTY(Element, bool, "AdjustHeightToContent",
"Property to get/set whether to " "automatically adjust the element's height to the element's content. "
"Value is either \"true\" or \"false\".",
&Element::setAdjustHeightToContent, &Element::isHeightAdjustedToContent, false
);
}
//----------------------------------------------------------------------------//
void Element::addChild_impl(Element* element)
{
// if element is attached elsewhere, detach it first (will fire normal events)
if (Element* const oldParent = element->d_parent)
oldParent->removeChild(element);
// add element to child list
if (std::find(d_children.cbegin(), d_children.cend(), element) == d_children.cend())
d_children.push_back(element);
element->d_parent = this;
}
//----------------------------------------------------------------------------//
void Element::removeChild_impl(Element* element)
{
// NB: it is intentionally valid to remove an element that is not in the list
auto it = std::find(d_children.begin(), d_children.end(), element);
if (it != d_children.end())
d_children.erase(it);
// reset element's parent so it's no longer this element
if (element->d_parent == this)
element->d_parent = nullptr;
}
//----------------------------------------------------------------------------//
Rectf Element::getUnclippedOuterRect_impl(bool skipAllPixelAlignment) const
{
const Rectf parent_rect = (!d_parent) ?
Rectf(glm::vec2(0, 0), getRootContainerSize()) :
skipAllPixelAlignment ?
d_parent->getChildContentArea(d_nonClient).getFresh(true) :
d_parent->getChildContentArea(d_nonClient).get();
const Sizef parent_size = parent_rect.getSize();
const Sizef pixel_size = skipAllPixelAlignment ? calculatePixelSize(true) : getPixelSize();
glm::vec2 offset = parent_rect.d_min + CoordConverter::asAbsolute(d_area.d_min, parent_size, false);
if (d_horizontalAlignment == HorizontalAlignment::Centre)
offset.x += (parent_size.d_width - pixel_size.d_width) * 0.5f;
else if (d_horizontalAlignment == HorizontalAlignment::Right)
offset.x += parent_size.d_width - pixel_size.d_width;
if (d_verticalAlignment == VerticalAlignment::Centre)
offset.y += (parent_size.d_height - pixel_size.d_height) * 0.5f;
else if (d_verticalAlignment == VerticalAlignment::Bottom)
offset.y += parent_size.d_height - pixel_size.d_height;
if (d_pixelAligned && !skipAllPixelAlignment)
{
offset.x = CoordConverter::alignToPixels(offset.x);
offset.y = CoordConverter::alignToPixels(offset.y);
}
return Rectf(offset, pixel_size);
}
//----------------------------------------------------------------------------//
Rectf Element::getUnclippedInnerRect_impl(bool skipAllPixelAlignment) const
{
return skipAllPixelAlignment ? d_unclippedOuterRect.getFresh(true) : d_unclippedOuterRect.get();
}
//----------------------------------------------------------------------------//
void Element::onSized(ElementEventArgs& e)
{
fireEvent(EventSized, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Element::onMoved(ElementEventArgs& e)
{
fireEvent(EventMoved, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Element::onHorizontalAlignmentChanged(ElementEventArgs& e)
{
notifyScreenAreaChanged();
fireEvent(EventHorizontalAlignmentChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Element::onVerticalAlignmentChanged(ElementEventArgs& e)
{
notifyScreenAreaChanged();
fireEvent(EventVerticalAlignmentChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Element::onRotated(ElementEventArgs& e)
{
fireEvent(EventRotated, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Element::onChildAdded(ElementEventArgs& e)
{
fireEvent(EventChildAdded, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Element::onChildRemoved(ElementEventArgs& e)
{
fireEvent(EventChildRemoved, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Element::onChildOrderChanged(ElementEventArgs& e)
{
fireEvent(EventChildOrderChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Element::onNonClientChanged(ElementEventArgs& e)
{
notifyScreenAreaChanged();
fireEvent(EventNonClientChanged, e, EventNamespace);
}
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
} // End of CEGUI namespace section
|
#ifndef LTUI_INPUT_H
#define LTUI_INPUT_H
#include <iostream>
#include <optional>
#include <sstream>
#include <string>
namespace ltui::input {
template <class parsed_t>
std::optional<parsed_t> read(const std::string &prompt) {
parsed_t tmp;
do {
std::cin.clear();
std::cout << prompt;
std::cin >> tmp;
} while (!std::cin);
return tmp;
}
template <> inline std::optional<std::string> read(const std::string &prompt) {
std::cin.clear();
constexpr auto bytes_to_ignore = 8;
std::cin.ignore(bytes_to_ignore, '\n');
std::cout << prompt;
std::string s;
std::getline(std::cin, s);
if (s.empty()) {
return std::nullopt;
}
return s;
}
} // namespace ltui
#endif
|
//
// Created by yulichao on 2020/11/9.
//
#include "head.h"
#include <string>
#include <iostream>
#include <unistd.h>
#include <list>
using namespace std;
class master {
private:
list<notifier *> pNotifierlist;
public:
master() = default;
void doWork() {
cout << "master work : " << endl;
for (int i = 0; i < 100; ++i) {
cout << "do working !" << endl;
for (auto item : pNotifierlist)
item->notify(i + 1);
sleep(1);
}
cout << "finish !" << endl;
}
void addObserver(notifier * p) {
pNotifierlist.push_back(p);
}
void removeObserver(notifier *p) {
pNotifierlist.remove(p);
}
};
|
#pragma once
// Forward Declarations
class SimpleVertexShader;
class SimplePixelShader;
struct ID3D11ShaderResourceView;
struct ID3D11SamplerState;
class Material
{
public:
// Parameterised Constructor for Material
Material(SimpleVertexShader* t_vertex_shader, SimplePixelShader* t_pixel_shader, ID3D11ShaderResourceView* t_diffused_srv, ID3D11ShaderResourceView* t_normal_srv, ID3D11SamplerState* t_sampler);
// Destructor for Material
~Material();
// Get Vertex Shader of the Material
SimpleVertexShader* getVertexShader() const;
// Get Pixel Shader of the Material
SimplePixelShader* getPixelShader() const;
// Get this material's diffused texture SRV
ID3D11ShaderResourceView* getdiffusedSRV() const;
// Get this material's normal map SRV
ID3D11ShaderResourceView* getNormalSRV() const;
// Get Pixel Shader of the Material
ID3D11SamplerState* getSamplerState() const;
private:
SimpleVertexShader* vertexShader = nullptr;
SimplePixelShader* pixelShader = nullptr;
ID3D11ShaderResourceView* diffused_srv = nullptr;
ID3D11ShaderResourceView* normal_srv = nullptr;
ID3D11SamplerState* sampler = nullptr;
};
|
#ifndef WBACTIONUISHOWYESNODIALOG_H
#define WBACTIONUISHOWYESNODIALOG_H
#include "wbaction.h"
#include "simplestring.h"
class WBActionUIShowYesNoDialog : public WBAction
{
public:
WBActionUIShowYesNoDialog();
virtual ~WBActionUIShowYesNoDialog();
DEFINE_WBACTION_FACTORY( UIShowYesNoDialog );
virtual void InitializeFromDefinition( const SimpleString& DefinitionName );
virtual void Execute();
private:
SimpleString m_YesNoString; // Config
Array<WBAction*> m_YesActions; // Config
};
#endif // WBACTIONUISHOWYESNODIALOG_H
|
#include "videofactory.h"
VideoFactory::VideoFactory()
{
}
QString VideoFactory::getNewId()
{
QString ajout="video@";
return ajout+NoteFactory::getNewId();
}
Note* VideoFactory::buildNote(const QString& id, const QString& titre, const QString &path, const QString &desc){
Video* v=new Video(id, titre,path, desc);
return v;
}
Note* VideoFactory::buildNewNote(const QString& titre, const QString &path){
QString id;
id=getNewId();
return buildNote(id, titre,path);
}
Note* VideoFactory::chargerNote(const QString& id, const QString& chemin){
QFile fichier(chemin+"/"+id+".txt");
QString desc;
if(fichier.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream flux(&fichier);
QString titre(flux.readLine());
QString path(flux.readLine());
while(!flux.atEnd()) desc += flux.readLine()+"\n";
Note* n= buildNote(id, titre, path,desc);
n->setInTheFile(true);
return n;
}
else {
qDebug()<<"note pas charger";
return 0;}
}
|
#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <set>
#include <regex>
//REFERENCE: http://www.cplusplus.com/forum/general/182654/
namespace html_generator
{
//USAGE: USE replace_all TO REPLACE ALL HYPERLINK AND SRC in a html text by appending prefix to the old_href
std::string replace_all(std::string html_text, std::string prefix);
std::string replace_old_src(std::string html_text, std::string prefix);
std::string replace_old_href(std::string html_text, std::string prefix);
//These functions are all helper functions
std::string replace_single_href(std::string text, std::string old_href, std::string new_href);
std::string file_to_string( std::string file_name );
std::set<std::string> extract_hyperlinks( std::string text );
} // namespace html_generator
|
/* @brief processes.h
* Intermediate tasks
*/
#ifndef PROCESSES_H
#define PROCESSES_H
#include <bits/stdc++.h>
using namespace std;
void mapeoAlphabet( string *alphabet );
void negativeNumbMod( int *modifyModule, int sizeAlphabet );
int verifyAffineKey( int sizeAlphabet, int a );
void generateKeyVigenere( string *key, string *message, string *alphabet );
void generateKeyAffine( string *key, string *alphabet );
void extendedEuclid( int valueofA, int valueofN, int *s, int *t, int *gcdResult );
#endif
|
#include "Tiles.h"
Tiles::Tiles(int w, int h)
{
//ctor
tileWidth = w;
tileHeight = h;
}
Tiles::~Tiles()
{
//dtor
}
void Tiles::Initialize()
{
}
int Tiles::GetTileWidth()
{
return tileWidth;
}
int Tiles::GetTileHeight()
{
return tileHeight;
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <queue>
#include <sstream>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
void SerializeHelper(TreeNode *r, string& str){
str += ',';
if(r == NULL) str += '$';
else {
//str += i2s(r->val);
str += i2s_v2(r->val);
SerializeHelper(r->left, str);
SerializeHelper(r->right, str);
}
cout << str << endl;
}
char* Serialize(TreeNode *root) {
string str;
SerializeHelper(root, str);
/*
char* res = new char[str.size()+1];
strcpy(res, str.c_str());
++res; // escape one ','
*/
//*
char* res = new char[str.size()];
char *dst = res;
const char *src = (str.c_str())+1; // escape one ','
while ((*dst++=*src++)!='\0');
//*/
return res;
}
TreeNode* DeserializeHelper(TreeNode* p, char*& str) {
if(*str == '\0') return NULL;
if(*str == '$'){
if(*(++str) == ','){
++str; // 0, 1,2,$,$,$,$'\0'
}
return NULL;
}
p = new TreeNode(s2i(str));
p->left = DeserializeHelper(p->left, str);
p->right = DeserializeHelper(p->right, str);
return p;
}
TreeNode* Deserialize(char *str) {
return DeserializeHelper(NULL, str);
}
private:
string i2s(long long x){
if(x == 0) return "0";
string str;
bool negative = false;
if(x<0){
negative = true;
x = -x;
}
while(x != 0){
str += char(x%10 + '0');
x /= 10;
} if(negative) str += '-';
std::reverse(str.begin(), str.end());
return str;
}
string i2s_v2(int x){
stringstream ss;
ss << x;
string res;
ss >> res;
return res;
}
int s2i(char*& s){
int res = 0;
bool negative = false;
if(*s == '-'){
negative = true;
++s;
} while(*s != ',' && *s != '\0'){
res = res*10 + (*s++ - '0');
} if(negative) res = -res;
if(*s == ',') ++s;
return res;
}
};
TreeNode* constructTree(int& v, int x){
if(v>x) return NULL;
TreeNode* r = new TreeNode(v++);
r->left = constructTree(v, x);
r->right = constructTree(v, x);
return r;
}
void printTreeNode(TreeNode* r){
if(r){
cout << r->val << endl;
printTreeNode(r->left);
printTreeNode(r->right);
}
}
int main(){
Solution solution = Solution();
int cur_v = 0;
//cout << solution.i2s(-1234) << endl;
//cout << solution.s2i("-123") << endl;
TreeNode* r = constructTree(cur_v, 100);
printTreeNode(r);
char* str_tree = Solution().Serialize(r);
cout << endl;
cout << endl;
cout << str_tree << endl;
//cout << endl;
//printTreeNode(solution.Deserialize(str_tree));
return 0;
}
|
#ifndef __CTILE_H_
#define __CTILE_H_
#include "CommonHeader.h"
//타일 상태 (갈 수 있는 곳인지, 없는 곳인지)
enum class ETileType : USHORT const
{
Non = 0,
Block = 1
};
//주위 타일 방향 판단 쉽게 하려고 선언
enum class EDirection : unsigned char const
{
NW = 0,
N = 1,
NE = 2,
E = 3,
SE = 4,
S = 5,
SW = 6,
W = 7
};
/*
타일 클래스
길찾기 관련, 몬스터 스폰 위치 포함
*/
class CTile
{
private:
USHORT m_x;
USHORT m_y;
ETileType m_tileType;
USHORT m_nSpawnMonsterIndex;
int m_goal;
int m_heuristic;
int m_fitness;
bool m_bIsClose;
bool m_bIsOpen;
CTile* m_pNeighborTile[8];
CTile* m_pParentTile;
public:
CTile(USHORT _x = 0, USHORT _y = 0, ETileType _tileType = ETileType::Non, USHORT _monsterIndex = 0) :
m_x(_x), m_y(_y), m_tileType(_tileType), m_nSpawnMonsterIndex(_monsterIndex)
{
m_goal = m_heuristic = m_fitness = 0;
m_bIsClose = m_bIsOpen = false;
m_pParentTile = nullptr;
for (int i = 0; i < 8; i++)
m_pNeighborTile[i] = nullptr;
}
~CTile() = default;
public:
void SetCoordinate(USHORT _x = 0, USHORT _y = 0, ETileType _tileType = ETileType::Non, USHORT _monsterIndex = 0);
void SetNeighborTile(EDirection _direction, CTile* _tile);
void SetNeighborParent(list<CTile*>* _openList, CTile* _finishTile);
void Clear(void);
void SetOpen(bool _open);
void SetClose(bool _close);
void SetParent(CTile* _grid, list<CTile*>* _openList, CTile* _finishTile);
void PathScoring(CTile* _grid, CTile* _finishGrid);
bool operator<(CTile* _other)
{
return m_fitness < _other->GetFitness();
}
public:
bool IsOpen(void);
bool IsClose(void);
USHORT GetSpawnMonsterIndex(void);
int GetFitness(void);
CTile* GetParent(void);
int GetX(void);
int GetY(void);
};
#endif
|
/*Ще не остаточна версія Ітема*/
#include "graphnode.h"
#include <QPainter>
#include <QDebug>
GraphNode::GraphNode(int id) : GrawItem(id)
{
}
QRectF GraphNode::boundingRect() const
{
if (_ModeView==0)
return QRectF(-4, -4, 8, 8);
}
void GraphNode::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/,
QWidget */*widget*/)
{
if (_ModeView!=0)
return;
if (isSelected())
paintSelected(painter);
else
paintNotSelected(painter);
}
void GraphNode::paintSelected(QPainter *painter)
{
painter->setPen(QPen(Qt::blue, 1));
painter->setBrush(Qt::SolidPattern);
painter->drawEllipse(QRect(-4, -4, 8, 8));
}
void GraphNode::paintNotSelected(QPainter *painter)
{
painter->setPen(QPen(Qt::cyan, 1));
painter->setBrush(Qt::SolidPattern);
painter->drawEllipse(QRect(-4, -4, 8, 8));
}
void GraphNode::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
ptX=x();
ptY=y();
emit signalParent();
QGraphicsItem::mouseReleaseEvent(event);
}
void GraphNode::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mouseMoveEvent(event);
if (_fixX>=0)
setX(_fixX);
if (_fixY>=0)
setY(_fixY);
}
ComponentType GraphNode::componentType() const
{
return ComponentType::GraphNode;
}
/*void GraphNode::setDeltaX(qreal iDeltaX)
{
if (!parentItem()){
deltaX = iDeltaX;
}else{
deltaX = 0;
}
setX(ptX+deltaX);
}*/
/*
В чому різниця між setDelta і setPt функціями? Чи не можна було в клієнтському коді порахувати потрібні
зміщення і передати результат стандартним методам setX, setY?
consty qreal deltaForX = calculateDeltaForX();
consty qreal deltaForY = calculateDeltaForY();
item->setX(deltaForX);
item->setY(deltaForY);
*/
/*void GraphNode::setDeltaY(qreal iDeltaY)
{
if (!parentItem()){
deltaY = iDeltaY;
}else{
deltaY = 0;
}
setY(ptY+deltaY);
}
void GraphNode::setPtX(qreal iptX)
{
ptX = iptX;
setX(ptX+deltaX);
}
void GraphNode::setPtY(qreal iptY)
{
ptY = iptY;
setY(ptY+deltaY);
}*/
/*
Цей метод вертає точку на що, на середину фігури чи її низ(верх)???
Що має думати клієнгт при такому виклику:
circle->getPoint(); ???
*/
QPointF GraphNode::getPoint() const
{
//qDebug() << "GraphNode::getPoint() 111";
return QPointF(ptX, ptY);
}
void GraphNode::setFixY(int iFixY)
{
_fixY = iFixY;
}
void GraphNode::setFixX(int iFixX)
{
_fixX = iFixX;
}
|
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <bits/stdc++.h>
#include <dirent.h>
#include <netinet/tcp.h>
#include "base/server.h"
using std::cout;
using std::endl;
#define SEND_SIZE 1024
int serverFileDescriptor;
int clientFileDescriptor;
void socket_pair(){
serverFileDescriptor = socket(AF_INET, SOCK_STREAM, 0);
if(serverFileDescriptor<0){
cout<<"Couldn't create socket\n";
return;
}
int port = 8080;
//server Address information
struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
// serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); //binds only to localhost
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); //binds to all available interfaces
serverAddress.sin_port = htons(port);
//Assign socket address to declared socket
int fails=bind(serverFileDescriptor, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
if(fails){
fprintf(stderr,"Couldn't bind to the port: %d\n",port);
return;
}
//Start listening on the port, maximum allowed clients is 5
fails=listen(serverFileDescriptor,5);
if(!fails){
cout<<"Listening...\n";
}
clientFileDescriptor = accept(serverFileDescriptor,NULL,NULL);
cout<<"Client connected\n";
}
void client_wait(){
int socketFileDescriptor = socket(AF_INET, SOCK_STREAM, 0);
FILE* socketRead = fdopen(socketFileDescriptor,"r+");
if(socketFileDescriptor<0){
cout<<"Couldn't create socket\n";
return;
}
int port = 8080;
//Server address information
struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddress.sin_port = htons(port);
// Connect to server
int status= connect(socketFileDescriptor, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
cout<<"Connected to server\n";
}
void send_initial_values(){
cout<<"serverFileDescriptor: "<<serverFileDescriptor<<" clientFileDescriptor: " <<
clientFileDescriptor <<endl;
// int data_sent = send(clientFileDescriptor,recv_initial_values,SEND_SIZE,0);
// cout<<"Data sent:"<<data_sent<<endl;
}
void recv_initial_values(){
}
|
#pragma once
#include "Config.h"
#include <string>
#include <iostream>
#include <map>
#include <list>
#include <vector>
#include <sstream>
#include <fstream>
#include <memory>
#include <SOIL.h>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <roguelikelib/randomness.h>
#include <roguelikelib/mapgenerators.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#pragma comment(lib, "SOIL.lib")
#pragma comment(lib, "glew32s.lib")
#pragma comment(lib, "OpenGL32.lib")
#pragma comment(lib, "glfw3.lib")
#pragma comment(lib, "freetype.lib")
|
//
// Created by dn on 12/31/17.
//
#include <iostream>
#include "game_logic.h"
Deck deck;
void Match()
{
std::string match_result {"Tourament Complete\nYou finished this tourament with "};
// Deck deck;
deck.shuffleDeck();
int mount_money = 5000;
while (mount_money > 0) {
mount_money += round();
}
std::cout << match_result<< mount_money<<'\n';
}
int round()
{
int value_of_bet = ChooseBettingValue();
// int roundResult = 0;
int player_total = 0;
int splited_player = 0;
int dealer_total = 0;
bool spliting = Frist2CardsAndSpliting(player_total, dealer_total, deck);
if (BlackJack(player_total, dealer_total, value_of_bet)) {
//if there is blackjack we ignore ther rest of the round
// and return the betting value
return value_of_bet;
}
// int player_choise = GetPlayerChoice(spliting);
while (GetPlayerChoice(spliting) == 1 and player_total < 21) {
switch (GetPlayerChoice(spliting)) {
case 1: {
Hit(player_total);
break;
}
case 2: {
Stand();
break;
}
case 3: {
DoubleDown(player_total);
break;
}
case 4: {
Split(player_total, splited_player);
break;
}
default:
break;
}
}
PremiumPlayer(player_total, splited_player);
DealerTurn(player_total, dealer_total);
return RoundWinning(value_of_bet, player_total , dealer_total);
}
void PremiumPlayer(int &premium_player, int &splited_player)
{
if (splited_player > premium_player and splited_player <= 21) {
int temp = premium_player;
premium_player = splited_player;
splited_player = temp;
}
}
int ChooseBettingValue()
{
std::cout << "Choose beting Value of these values :-\n\t10\t25\t100\t250\tMaxVlue" << '\n';
int choice;
do {
std::cin >> choice;
}
while (
choice != 10 &&
choice != 25 &&
choice != 100 &&
choice != 250 &&
choice != 500
);
return choice;
}
bool Frist2CardsAndSpliting(int &player_total, int &dealer_total, Deck &deck)
{
Card hit_card = deck.dealCard();
int frist_card = hit_card.getCardValue();
std::string player_frist_card = hit_card.printCard();
dealer_total += deck.dealCard().getCardValue();
hit_card = deck.dealCard();
int secont_card = hit_card.getCardValue();
std::string player_second_card = hit_card.printCard();
hit_card = deck.dealCard();
std::string dealer_card = hit_card.printCard();
dealer_total += hit_card.getCardValue();
std::string player_card_printing = "You have: " + player_frist_card + " and " + player_second_card + "\n";
std::string dealer_card_printing = "The dealer is showing: " + dealer_card + "\n";
player_total = frist_card + secont_card;
return player_frist_card == player_second_card;
}
bool BlackJack(int &player_total, int &dealer_total, int &value_of_bet)
{
if (player_total == 21 or dealer_total == 21) {
if (player_total == 21) {
value_of_bet += (value_of_bet / 2);
std::cout << "***BlackJack***\n";
}
else if (dealer_total == 21) {
value_of_bet = (value_of_bet + value_of_bet / 2) * -1;
std::cout << "DEALER WON\n";
}
return 1;
}
return 0;
}
int GetPlayerChoice(bool split)
{
// 1- Hit.
// 2- Stand.
// 3-Double down.
// 4- Splite.
if (split) {
int choice;
while (1) {
std::cout << "Enter the numper of you choise :\n1- Hit.\n2- Stand.\n3- Double down.\n4- Splite.\n";
std::cin >> choice;
if (choice > 0 and choice < 5) {
break;
}
else {
for (int i = 0; i < 15; ++i) {
std::cout << '\n';
}
}
}
return choice;
}
else {
int choice;
while (1) {
std::cout << "Enter the numper of you choise :\n1- Hit.\n2- Stand.\n3- Double down.\n";
std::cin >> choice;
if (choice > 0 and choice < 4) {
break;
}
else {
for (int i = 0; i < 15; ++i) {
std::cout << '\n';
}
}
}
return choice;
}
}
void Split(int &player_total, int &splited_player)
{
splited_player = player_total / 2;
while (GetPlayerChoice(0) == 1 and splited_player < 21) {
switch (GetPlayerChoice(0)) {
case 1: {
Hit(splited_player);
break;
}
case 2: {
Stand();
break;
}
case 3: {
DoubleDown(splited_player);
break;
}
//should be deleted coz unneeded case
// case 4: {
// Split();
// break;
// }
default:
break;
}
}
}
void Hit(int &total)
{
// return Deck::dealCard().getCardValue();
total += deck.dealCard().getCardValue();
//check crossing 21
}
void Stand()
{
//nothing to do just for the beauty of the program :D
}
void DoubleDown(int &player_total)
{
Hit(player_total);
}
void DealerTurn(int &player_total, int &dealer_total)
{
while (dealer_total < player_total) {
Hit(dealer_total);
}
}
int RoundWinning(int &bet_value, int &player, int &dealer)
{
if (player > dealer) {
std::cout << "YOU WIN!" << '\n';
std::cout << '+' << bet_value << '\n';
return bet_value;
}
else if (player < dealer) {
std::cout << "DEALER WON" << '\n';
std::cout << '-' << bet_value << '\n';
return -1 * bet_value;
}
else {
std::cout << "PUSH" << '\n';
return 0;
}
}
|
#include<bits/stdc++.h>
using namespace std;
int n;
vector<string>v;
void solve(string s,int pos,string ans)
{
if(pos==n)
{
v.push_back(ans);return;
}
solve(s,pos+1,ans+'+'+s[pos]);
solve(s,pos+1,ans+s[pos]);
}
int main()
{
string s;
cin>>s;
n=s.size();
string x="";
x+=s[0];
solve(s,1,x);
long long ans=0;
for(string s:v)
{
string x="";
for(int i=0;i<s.size();i++)
{
if(s[i]=='+')
{
ans+=stoll(x);x.clear();
}
else
x+=s[i];
}
ans+=stoll(x);
x.clear();
}
cout<<ans<<"\n";
}
|
#pragma once
#include <SFML/Graphics.hpp>
#include <random>
#include <ctime>
#include <iostream>
#include "Snake.h"
#include "Level.h"
#define LOOP(n)for(size_t i = 0;i<n;i++)
#define LOOPX(n)for(size_t x = 0;x<n;x++)
#define LOOPY(n)for(size_t y = 0;y<n;y++)
#define MAP_OFFSET_X 0
#define MAP_OFFSET_Y 0
#define MAP_SIZE_X 800
#define MAP_SIZE_Y 800
#define NUM_OF_TREATS 5
#define SIZE_OF_MAP 10
#define TILE (*_map[pos.y][pos.y])
using namespace sf;
typedef std::uniform_int_distribution<unsigned> randomU;
class Snake;
class Map{
public:
enum TILE_TYPE {ERROR,AIR,SNAKE_HEAD,SNAKE_BODYI,SNAKE_BODYL,SNAKE_BODYLO,SNAKE_BODYO,SNAKE_BODYIL,SNAKE_TAIL,TREAT,OBSTACLE,FINISH};
struct Tile {
Tile(const Vector2f &size, const Vector2f &pos);
Tile(){ this->_type = ERROR; }
void updateSnakeParts(const unsigned short &type);
void updateNoSnake();
void update();
inline void draw(RenderWindow &window) {window.draw(_body);}
void setType(const TILE_TYPE &type) { _type = type; }
TILE_TYPE getType() { return _type; }
void rotate(const float &angle){ _angle = angle; _body.setRotation(angle); }
void setRandomTreat();
void setRandomAngle() { rotate(randomAngle(randomGenerator)); }
inline void reset();
inline void setStyle(const unsigned short &s) { _style = s; }
unsigned short getAngle() { return _angle; }
static Texture _texture;
static unsigned short _animation;
private:
static std::uniform_int_distribution<unsigned> randomTreat;
static std::uniform_int_distribution<unsigned> randomAngle;
const Vector2f _pos;
const Vector2f _size;
RectangleShape _body;
unsigned short _angle = 0;
size_t s_c = 40;
unsigned _treatID = 0;
unsigned short _style = 0;
TILE_TYPE _type = AIR;
};
Map(const size_t &, const Vector2u &vm ,Color = Color::White);
Map(Level* level, const Vector2u& vm);
~Map();
void update();
void draw(RenderWindow &window);
Tile ***getMap() { return _map; }
void setTileType(const Vector2u &,const TILE_TYPE &);
void updateSnakeTile(const Vector2u &pos,const unsigned short &type);
void updateNoSnakeTile(const Vector2u& pos);
bool checkTile(const Vector2u &, const TILE_TYPE &);
void rotateTile(const Vector2u &, const float &);
void updateNoSnake();
void spawnSnake(Snake* snake);
void resetTile(const Vector2u &);
void clear();
void spawnTreat();
void openExit();
void updateExit();
//debug funkce
#ifdef DEBUG
void showBitmap() {
LOOPY(_size) {
LOOPX(_size) {
std::cout << std::setw(3) << _map[y][x]->getType() << " ";
}
std::cout << std::endl <<std::endl;
}
}
#endif
size_t getSize() { return _size; }
static std::default_random_engine randomGenerator;
private:
Tile ***_map = nullptr;
Level* _level = nullptr;
Vector2u _snake_head_spawn_pos;
Vector2u _snake_tail_spawn_pos;
Vector2u _exit_pos;
size_t _size;
RectangleShape _background;
bool _exitOpen = false;
};
|
#include <iostream>
using namespace std;
struct Rectangle
{
int length; //4 bytes
int breadth; // 4 bytes
};
//Rectangle object will take 4+4= 8 bytes of memory
int main()
{
struct Rectangle rec = {20,15};
// rec.length = 20;
// rec.breadth = 15;
cout<< rec.length<<endl;
cout<< rec.breadth;
return 0;
}
|
/**
* Binary serialization basic sinks
*/
#ifndef FISHY_SERIALIZER_BASESINKS_H
#define FISHY_SERIALIZER_BASESINKS_H
#include <cstring>
namespace core {
namespace base {
/**
* Sink that is usable to just size a given serialization.
*/
class FakeSink : public iBinarySerializerSink {
public:
FakeSink() : m_size(0) {}
virtual size_t write(const ::core::memory::ConstBlob &b) {
m_size += b.size();
return b.size();
}
virtual size_t read(::core::memory::Blob &) {
CHECK_INVALID_OPERATION();
return 0;
}
virtual void seek(const size_t dist) { m_size += dist; }
virtual size_t avail() { return 0; }
/**
* Return the currently serialized size in bytes.
*/
size_t size() const { return m_size; }
private:
size_t m_size;
};
/**
* Sink that provides a limited range over a parent sink.
*/
class RangeSink : public iBinarySerializerSink {
public:
RangeSink(iBinarySerializerSink &sink, size_t size)
: m_sink(sink), m_size(size) {}
virtual size_t write(const ::core::memory::ConstBlob &b) {
const size_t sz = cap(b.size());
return m_sink.write(::core::memory::ConstBlob(b.data(), sz));
}
virtual size_t read(::core::memory::Blob &b) {
const size_t sz = cap(b.size());
::core::memory::Blob tmp(b.data(), sz);
return m_sink.read(tmp);
}
virtual void seek(const size_t dist) {
const size_t sz = cap(dist);
m_sink.seek(sz);
}
virtual size_t avail() { return m_size; }
private:
iBinarySerializerSink &m_sink;
size_t m_size;
size_t cap(const size_t in) {
const size_t ret = std::min(in, m_size);
m_size -= ret;
return ret;
}
};
/**
* Sink over a writeable {@link Blob}.
*/
class BlobSink : public iBinarySerializerSink {
public:
BlobSink(core::memory::Blob &sink) : m_sink(sink), m_pos(0) {}
virtual size_t write(const ::core::memory::ConstBlob &b) {
size_t writeable = std::min(b.size(), m_sink.size() - m_pos);
memcpy(m_sink.data() + m_pos, b.data(), writeable);
m_pos += writeable;
return writeable;
}
virtual size_t read(::core::memory::Blob &b) {
size_t readable = std::min(b.size(), m_sink.size() - m_pos);
memcpy(b.data(), m_sink.data() + m_pos, readable);
m_pos += readable;
return readable;
}
virtual void seek(const size_t dist) {
if (m_sink.size() - m_pos < dist) {
m_pos = m_sink.size();
} else {
m_pos = m_pos + dist;
}
}
virtual size_t avail() { return m_sink.size() - m_pos; }
void reset() { m_pos = 0; }
/**
* Return the currently serialized size in bytes.
*/
size_t size() const { return m_pos; }
private:
core::memory::Blob &m_sink;
size_t m_pos;
};
/**
* Sink over a read-only {@link ConstBlob}.
*/
class ConstBlobSink : public iBinarySerializerSink {
public:
ConstBlobSink(const core::memory::ConstBlob &sink) : m_sink(sink), m_pos(0) {}
virtual size_t write(const ::core::memory::ConstBlob &b) {
(void) b;
CHECK_INVALID_OPERATION();
return 0;
}
virtual size_t read(::core::memory::Blob &b) {
size_t readable = std::min(b.size(), m_sink.size() - m_pos);
memcpy(b.data(), m_sink.data() + m_pos, readable);
m_pos += readable;
return readable;
}
virtual void seek(const size_t dist) {
if (m_sink.size() - m_pos < dist) {
m_pos = m_sink.size();
} else {
m_pos = m_pos + dist;
}
}
virtual size_t avail() { return m_sink.size() - m_pos; }
void reset() { m_pos = 0; }
private:
const core::memory::ConstBlob &m_sink;
size_t m_pos;
};
} // namespace base
} // namespace core
#endif
|
#include<cstdio>
#include<iostream>
#include<stack>
using namespace std;
int main()
{
int n;
char s1[20],s2[20];
while(~scanf("%d %s %s",&n,s1,s2))
{
stack <char> s;
int flag[100]={0};
int j=0,k=0;
for(int i=0; i < n; i++)
{
s.push(s1[i]);
flag[k++] = 1;
while(!s.empty() && s.top() == s2[j])
{
flag[k++] = -1;
s.pop();
j++;
}
}
if(j == n)
{
printf("Yes.\n");
for(int i = 0; i < k; i++)
{
if(flag[i] == 1)
printf("in\n");
else if(flag[i] == -1)
printf("out\n");
}
}
else
printf("No.\n");
printf("FINISH\n");
}
return 0;
}
|
/*
* File: Console.h
* Author: gmena
*
* Created on 06 de septiembre de 2014, 09:00 AM
*/
#include <string>
#include <iostream>
#include "Util.h"
using namespace std;
#ifndef CONSOLE_H
#define CONSOLE_H
class Console {
public:
static void success(string log);
static void error(string log);
static void warning(string log);
static void header(string log);
static void date();
private:
};
#endif /* CONSOLE_H */
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
#ifndef POOMA_EVALUATOR_REDUCTIONEVALUATOR_H
#define POOMA_EVALUATOR_REDUCTIONEVALUATOR_H
//-----------------------------------------------------------------------------
// Class:
// ReductionEvaluator<InlineKernelTag>
// ReductionEvaluator<CompressibleKernelTag>
// CompressibleReduce<T, Op>
//-----------------------------------------------------------------------------
/** @file
* @ingroup Evaluator
* @brief
* ReductionEvaluator<InlineKernelTag> reduces expressions by inlining a
* simple loop. ReductionEvaluator<CompressibleKernelTag> can optionally take
* advantage of compression.
*/
//-----------------------------------------------------------------------------
// Includes:
//-----------------------------------------------------------------------------
#include "Engine/EngineFunctor.h"
#include "Evaluator/CompressibleEngines.h"
#include "Evaluator/KernelTags.h"
#include "PETE/OperatorTags.h"
#include "Pooma/PoomaOperatorTags.h"
#include "Utilities/WrappedInt.h"
#include "Utilities/PAssert.h"
#include <limits>
#ifdef _OPENMP
#include <omp.h>
#endif
/**
* Traits class defining identity element for type T under
* operation Op. Needs to be specialized for Op and possibly T.
*/
template<class Op, class T>
struct ReductionTraits {
};
template<class T>
struct ReductionTraits<OpAddAssign, T> {
static inline T identity() { return T(0); }
};
template<class T>
struct ReductionTraits<OpMultiplyAssign, T> {
static inline T identity() { return T(1); }
};
template<class T>
struct ReductionTraits<FnMinAssign, T> {
static inline T identity() { return std::numeric_limits<T>::max(); }
};
template<class T>
struct ReductionTraits<FnMaxAssign, T> {
static inline T identity() { return std::numeric_limits<T>::min(); }
};
template<class T>
struct ReductionTraits<FnOrAssign, T> {
static inline T identity() { return T(false); }
};
template<class T>
struct ReductionTraits<FnAndAssign, T> {
static inline T identity() { return T(true); }
};
template<class T>
struct ReductionTraits<OpBitwiseOrAssign, T> {
static inline T identity() { return T(); }
};
template<class T>
struct ReductionTraits<OpBitwiseAndAssign, T> {
static inline T identity() { return ~T(); }
};
/**
* Class to hold static array for partial reduction results
* and routine for final reduction. Two versions, one dummy
* for non-OpenMP, one for OpenMP operation.
*/
#ifndef _OPENMP
template<class T>
struct PartialReduction {
static inline void init() {}
inline void storePartialResult(const T& result)
{
answer = result;
}
template <class Op>
inline void reduce(T& ret, const Op&)
{
ret = answer;
}
T answer;
};
#else
template<class T>
struct PartialReduction {
static inline void init()
{
if (!answer)
answer = new T[omp_get_max_threads()];
}
inline void storePartialResult(const T& result)
{
int n = omp_get_thread_num();
answer[n] = result;
if (n == 0)
num_threads = omp_get_num_threads();
}
template <class Op>
inline void reduce(T& ret, const Op& op)
{
T res = answer[0];
for (int i = 1; i<num_threads; ++i)
op(res, answer[i]);
ret = res;
}
int num_threads;
static T *answer;
};
template <class T>
T *PartialReduction<T>::answer = NULL;
#endif
//-----------------------------------------------------------------------------
// Forward Declarations:
//-----------------------------------------------------------------------------
template<class KernelTag>
struct ReductionEvaluator;
/**
* The point of this class is to input an expression with the
* 'evaluate' member function and reduce it by looping over the
* whole domain.
*
* This is the simplest possible reduction. It makes the simplifying
* assumption that expression passed in can handle random access to
* all of its elements efficiently.
*/
template<>
struct ReductionEvaluator<InlineKernelTag>
{
//---------------------------------------------------------------------------
// Input an expression and cause it to be evaluated.
// All this template function does is extract the domain
// from the expression and call evaluate on that.
template<class T, class Op, class Expr>
static void evaluate(T &ret, const Op &op, const Expr &e)
{
typedef typename Expr::Domain_t Domain_t;
// The reduction evaluators assume unit-stride zero-based domains.
CTAssert(Domain_t::unitStride);
for (int i=0; i<Domain_t::dimensions; ++i)
PAssert(e.domain()[i].first() == 0);
PartialReduction<T>::init();
evaluate(ret, op, e, e.domain(),
WrappedInt<Domain_t::dimensions>());
}
//---------------------------------------------------------------------------
// This is the function both of the above functions call.
// It adds a third argument which is a tag class templated on
// the dimension of the domain.
//
// This parameter lets us specialize the function based on
// that dimension.
//
// Some day, we will figure out how to specialize template
// member functions outside the class declaration...
//
// These functions are all inline for efficiency. That means that if
// they are being used at the user level we will get the optimization
// of recognizing multiple uses of a single Array on the right hand
// side.
//
// There are seven specializations here, for dimension 1 through 7.
// Rather than use template metaprograms for these seven cases we
// simply enumerate them explicitly. This is done to reduce the
// burden on the compiler, which would otherwise have to jump through
// a bunch of hoops to get the code that is here.
//
// For each of the specializations it builds a nested loop for each
// dimension. Each loop is constructed last() from the
// appropriate dimension of the zero-based domain.
//
// NOTE: These loops assume that the domain passed in is a unit-stride
// domain starting at 0. Assertions are made to make sure this is true
// in the dispatching evaluate.
template<class T, class Op, class Expr, class Domain>
inline static void evaluate(T &ret, const Op &op, const Expr &e,
const Domain &domain, WrappedInt<1>)
{
Expr localExpr(e);
int e0 = domain[0].length();
PartialReduction<T> reduction;
#pragma omp parallel if (e0 > 512)
{
T answer = ReductionTraits<Op, T>::identity();
#pragma omp for nowait
for (int i0 = 0; i0 < e0; ++i0)
op(answer, localExpr.read(i0));
reduction.storePartialResult(answer);
}
reduction.reduce(ret, op);
}
template<class T, class Op, class Expr, class Domain>
inline static void evaluate(T &ret, const Op &op, const Expr &e,
const Domain &domain, WrappedInt<2>)
{
Expr localExpr(e);
int e0 = domain[0].length();
int e1 = domain[1].length();
PartialReduction<T> reduction;
#pragma omp parallel
{
T answer = ReductionTraits<Op, T>::identity();
#pragma omp for nowait
for (int i1 = 0; i1 < e1; ++i1)
for (int i0 = 0; i0 < e0; ++i0)
op(answer, localExpr.read(i0, i1));
reduction.storePartialResult(answer);
}
reduction.reduce(ret, op);
}
template<class T, class Op, class Expr, class Domain>
inline static void evaluate(T &ret, const Op &op, const Expr &e,
const Domain &domain, WrappedInt<3>)
{
Expr localExpr(e);
int e0 = domain[0].length();
int e1 = domain[1].length();
int e2 = domain[2].length();
PartialReduction<T> reduction;
#pragma omp parallel
{
T answer = ReductionTraits<Op, T>::identity();
#pragma omp for nowait
for (int i2 = 0; i2 < e2; ++i2)
for (int i1 = 0; i1 < e1; ++i1)
for (int i0 = 0; i0 < e0; ++i0)
op(answer, localExpr.read(i0, i1, i2));
reduction.storePartialResult(answer);
}
reduction.reduce(ret, op);
}
template<class T, class Op, class Expr, class Domain>
inline static void evaluate(T &ret, const Op &op, const Expr &e,
const Domain &domain, WrappedInt<4>)
{
Expr localExpr(e);
int e0 = domain[0].length();
int e1 = domain[1].length();
int e2 = domain[2].length();
int e3 = domain[3].length();
PartialReduction<T> reduction;
#pragma omp parallel
{
T answer = ReductionTraits<Op, T>::identity();
#pragma omp for nowait
for (int i3 = 0; i3 < e3; ++i3)
for (int i2 = 0; i2 < e2; ++i2)
for (int i1 = 0; i1 < e1; ++i1)
for (int i0 = 0; i0 < e0; ++i0)
op(answer, localExpr.read(i0, i1, i2, i3));
reduction.storePartialResult(answer);
}
reduction.reduce(ret, op);
}
template<class T, class Op, class Expr, class Domain>
inline static void evaluate(T &ret, const Op &op, const Expr &e,
const Domain &domain, WrappedInt<5>)
{
Expr localExpr(e);
int e0 = domain[0].length();
int e1 = domain[1].length();
int e2 = domain[2].length();
int e3 = domain[3].length();
int e4 = domain[4].length();
PartialReduction<T> reduction;
#pragma omp parallel
{
T answer = ReductionTraits<Op, T>::identity();
#pragma omp for nowait
for (int i4 = 0; i4 < e4; ++i4)
for (int i3 = 0; i3 < e3; ++i3)
for (int i2 = 0; i2 < e2; ++i2)
for (int i1 = 0; i1 < e1; ++i1)
for (int i0 = 0; i0 < e0; ++i0)
op(answer, localExpr.read(i0, i1, i2, i3, i4));
reduction.storePartialResult(answer);
}
reduction.reduce(ret, op);
}
template<class T, class Op, class Expr, class Domain>
inline static void evaluate(T &ret, const Op &op, const Expr &e,
const Domain &domain, WrappedInt<6>)
{
Expr localExpr(e);
int e0 = domain[0].length();
int e1 = domain[1].length();
int e2 = domain[2].length();
int e3 = domain[3].length();
int e4 = domain[4].length();
int e5 = domain[5].length();
PartialReduction<T> reduction;
#pragma omp parallel
{
T answer = ReductionTraits<Op, T>::identity();
#pragma omp for nowait
for (int i5 = 0; i5 < e5; ++i5)
for (int i4 = 0; i4 < e4; ++i4)
for (int i3 = 0; i3 < e3; ++i3)
for (int i2 = 0; i2 < e2; ++i2)
for (int i1 = 0; i1 < e1; ++i1)
for (int i0 = 0; i0 < e0; ++i0)
op(answer, localExpr.read(i0, i1, i2, i3, i4, i5));
reduction.storePartialResult(answer);
}
reduction.reduce(ret, op);
}
template<class T, class Op, class Expr, class Domain>
inline static void evaluate(T &ret, const Op &op, const Expr &e,
const Domain &domain, WrappedInt<7>)
{
Expr localExpr(e);
int e0 = domain[0].length();
int e1 = domain[1].length();
int e2 = domain[2].length();
int e3 = domain[3].length();
int e4 = domain[4].length();
int e5 = domain[5].length();
int e6 = domain[6].length();
PartialReduction<T> reduction;
#pragma omp parallel
{
T answer = ReductionTraits<Op, T>::identity();
#pragma omp for nowait
for (int i6 = 0; i6 < e6; ++i6)
for (int i5 = 0; i5 < e5; ++i5)
for (int i4 = 0; i4 < e4; ++i4)
for (int i3 = 0; i3 < e3; ++i3)
for (int i2 = 0; i2 < e2; ++i2)
for (int i1 = 0; i1 < e1; ++i1)
for (int i0 = 0; i0 < e0; ++i0)
op(answer, localExpr.read(i0, i1, i2, i3, i4, i5, i6));
reduction.storePartialResult(answer);
}
reduction.reduce(ret, op);
}
};
//-----------------------------------------------------------------------------
// This class handles the evaluation of a reduction from a single compressed
// value. The current possibilies are:
// o sum: N * val
// o prod: val^N
// o min: val
// o max: val
// o any: val
// o all: val
// o bitOr: val
// o bitAnd: val
//-----------------------------------------------------------------------------
template<class T, class Op>
struct CompressibleReduce
{
template<class T1>
inline static void evaluate(T &ret, const Op &, const T1 &val, int)
{
ret = static_cast<T>(val);
}
};
template<class T>
struct CompressibleReduce<T, OpAddAssign>
{
template<class T1>
inline static void evaluate(T &ret, const OpAddAssign &, const T1 &val,
int n)
{
ret = static_cast<T>(n * val);
}
};
template<class T>
struct CompressibleReduce<T, OpMultiplyAssign>
{
template<class T1>
inline static void evaluate(T &ret, const OpMultiplyAssign &, const T1 &val,
int n)
{
ret = static_cast<T>(val);
while (--n > 0)
ret *= static_cast<T>(val);
}
};
//-----------------------------------------------------------------------------
// The point of this class is to input an expression with the
// 'evaluate' member function and reduce it, optionally taking advantage of
// compression.
//-----------------------------------------------------------------------------
template<>
struct ReductionEvaluator<CompressibleKernelTag>
{
//---------------------------------------------------------------------------
// Input an expression and cause it to be reduced.
// This class relies on another class, CompressibleReduce<T, Op> to
// perform the correct reduction based on the operator if the expression
// is compressed. If it is not, we simply use
// ReductionEvaluator<InlineKernelTag>.
template<class T, class Op, class Expr>
inline static void evaluate(T &ret, const Op &op, const Expr &e)
{
if (engineFunctor(e, Compressed()))
{
CompressibleReduce<T, Op>::
evaluate(ret, op, engineFunctor(e, CompressedRead()),
e.domain().size());
}
else
{
ReductionEvaluator<InlineKernelTag>::evaluate(ret, op, e);
}
}
};
#endif // POOMA_EVALUATOR_REDUCTIONEVALUATOR_H
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: ReductionEvaluator.h,v $ $Author: richi $
// $Revision: 1.12 $ $Date: 2004/11/04 20:07:26 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
//my solution
//70+ ms
//I cannot understand the requirements as a foreigner even with Google!!
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size()!=t.size()) return false;
unordered_map<char,int> mymap;
for(int i=0;i<s.size();i++){
mymap[s[i]] = 0;
}
for(int i=0;i<s.size();i++){
mymap[s[i]]++;
}
//the showup times of the char is limited
for(int i=0;i<t.size();i++){
if(mymap.find(t[i]) == mymap.end()) return false;
--mymap[t[i]];
if(mymap[t[i]]<0) return false;
}
return true;
}
};
//much better solution
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int m[26] = {0};
for (int i = 0; i < s.size(); ++i) ++m[s[i] - 'a'];
for (int i = 0; i < t.size(); ++i) {
if (--m[t[i] - 'a'] < 0) return false;
}
return true;
}
};
|
#include <iostream>
#include "LangLexer.hpp"
#include "LangParser.hpp"
#include "LangWalker.hpp"
int main()
{
ANTLR_USING_NAMESPACE(std)
ANTLR_USING_NAMESPACE(antlr)
try {
LangLexer lexer(cin);
LangParser parser(lexer);
parser.block();
// antlr.CommonAST a = (antlr.CommonAST)parser.getAST();
RefAST a = parser.getAST();
cout << a->toStringList() << endl;
LangWalker walker;
walker.block(a); // walk tree
cout << "done walking" << endl;
} catch(exception& e) {
cout << "exception: "<< e.what() << endl;
}
}
|
#include<bits/stdc++.h>
#define M 1000000007
using namespace std;
long solve(int n,int k,int x)
{
long onecount = 1;
long nononecount = 0;
for(int i=1;i<n;i++)
{
long temp = onecount;
onecount = ((nononecount)*(k-1))%M;
nononecount = (temp + ((nononecount)*(k-2))%M)%M;
}
if(x == 1)
{
return onecount;
}
return nononecount;
}
int main()
{
int n,k;
cin >> n >> k;
cout << solve(n,k,1) << endl;
cout << solve(n,k,2) << endl;
return 0;
}
|
#include "simulation.h"
#include "point.h"
#include "vehicule.h"
#include "vehiculecontroller.h"
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QGeoCoordinate>
simulation::simulation()
{
}
void simulation::remplir_vehicules(Point itineraires[100][24])
{
Vehicule voiture;
Point position;
Point itineraire[24];
for(int i=0; i<100;i++)
{
for(int j=0; j<24;j++)
{
itineraire[j]=itineraires[i][j];
}
position = *new Point(2,3);
voiture= *new Vehicule(position);
voiture.setPositionInfo(itineraire);
d_vehicules[i]=voiture;
}
}
void simulation::deplacement_vehicule()
{
VehiculeController vehiculeCntrl;
vehiculeCntrl.setCenter(QGeoCoordinate(47.732828,7.352456));
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("VehiculeController", &vehiculeCntrl);
}
void simulation::start()
{
Point itineraires[100][24];
//en fonction des routes
remplir_vehicules(itineraires);
}
|
/*
* 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.
*
*/
#ifdef __linux
#include <sys/types.h>
#include <sys/socket.h> // socket, sendmsg, recvmsg
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <errno.h>
#else
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <net/route.h>
#include <errno.h>
#endif
#include <unistd.h> // getpid
#ifdef __linux
#include <flux/File>
#include <flux/LineSource>
#endif
#include <flux/exceptions>
#include <flux/net/NetworkInterface>
namespace flux {
namespace net {
NetworkInterface::NetworkInterface():
index_(-1),
type_(0),
flags_(0),
hardwareAddress_(0),
mtu_(0),
addressList_(SocketAddressList::create())
{}
#ifdef __linux
Ref<NetworkInterfaceList> NetworkInterface::queryAll(int family)
{
Ref<NetworkInterfaceList> list = NetworkInterfaceList::create();
getLink(list);
int families[2];
families[0] = ((family == AF_UNSPEC) || (family == AF_INET6)) ? AF_INET6 : -1;
families[1] = ((family == AF_UNSPEC) || (family == AF_INET)) ? AF_INET : -1;
for (int j = 0; j < 2; ++j)
{
if (families[j] == -1) continue;
family = families[j];
int fd = ::socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (fd == -1) FLUX_SYSTEM_DEBUG_ERROR(errno);
int seq = 0;
struct sockaddr_nl src;
memclr(&src, sizeof(src));
src.nl_family = AF_NETLINK;
src.nl_pid = ::getpid();
if (::bind(fd, (struct sockaddr *)&src, (socklen_t)sizeof(src)) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
// send request
{
size_t msgLen = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
struct nlmsghdr *msg = (struct nlmsghdr *)flux::malloc(msgLen);
if (!msg) FLUX_SYSTEM_DEBUG_ERROR(errno);
memclr(msg, msgLen);
msg->nlmsg_type = RTM_GETADDR;
msg->nlmsg_len = msgLen;
msg->nlmsg_flags = NLM_F_REQUEST|NLM_F_ROOT;
msg->nlmsg_pid = src.nl_pid;
msg->nlmsg_seq = seq++;
struct ifaddrmsg *data = (struct ifaddrmsg *)NLMSG_DATA(msg);
data->ifa_family = family;
struct sockaddr_nl dst;
memclr(&dst, sizeof(dst));
dst.nl_family = AF_NETLINK;
struct msghdr hdr;
memclr(&hdr, sizeof(hdr));
struct iovec iov = { msg, msgLen };
hdr.msg_iov = &iov;
hdr.msg_iovlen = 1;
hdr.msg_name = (void *)&dst;
hdr.msg_namelen = sizeof(dst);
if (::sendmsg(fd, &hdr, 0/*flags*/) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
flux::free(msg);
}
// process reply
{
struct msghdr hdr;
memclr(&hdr, sizeof(hdr));
ssize_t bufSize = ::recvmsg(fd, &hdr, MSG_PEEK|MSG_TRUNC);
if (bufSize < 0) FLUX_SYSTEM_DEBUG_ERROR(errno);
void *buf = flux::malloc(bufSize);
if (!buf) FLUX_SYSTEM_DEBUG_ERROR(errno);
struct iovec iov = { buf, (size_t)bufSize };
hdr.msg_iov = &iov;
hdr.msg_iovlen = 1;
ssize_t bufFill = ::recvmsg(fd, &hdr, 0/*flags*/);
if (::close(fd) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
struct nlmsghdr *msg = (struct nlmsghdr *)buf;
for (;NLMSG_OK(msg, unsigned(bufFill)); msg = NLMSG_NEXT(msg, bufFill))
{
unsigned msgType = msg->nlmsg_type;
// unsigned msgFlags = msg->nlmsg_flags;
if (msgType == RTM_NEWADDR)
{
struct ifaddrmsg *data = (struct ifaddrmsg *)NLMSG_DATA(msg);
struct rtattr *attr = (struct rtattr *)IFA_RTA(data);
int attrFill = NLMSG_PAYLOAD(msg, sizeof(struct ifaddrmsg));
Ref<SocketAddress> label;
Ref<NetworkInterface> interface = 0;
for (int i = 0; i < list->count(); ++i) {
if (unsigned(list->at(i)->index_) == data->ifa_index) {
interface = list->at(i);
break;
}
}
if (!interface) {
if (!getLink(list, data->ifa_index))
continue;
interface = list->at(list->count() - 1);
}
for (;RTA_OK(attr, attrFill); attr = RTA_NEXT(attr, attrFill))
{
unsigned attrType = attr->rta_type;
// unsigned attrLen = RTA_PAYLOAD(attr);
if ( (attrType == IFA_ADDRESS) ||
(attrType == IFA_LOCAL) ||
(attrType == IFA_BROADCAST) ||
(attrType == IFA_ANYCAST)
)
{
Ref<SocketAddress> address;
struct sockaddr_in addr4;
struct sockaddr_in6 addr6;
if (data->ifa_family == AF_INET) {
memclr(&addr4, sizeof(addr4));
// addr.sin_len = sizeof(addr);
*(uint8_t *)&addr4 = sizeof(addr4); // uggly, but safe HACK, for BSD4.4
addr4.sin_family = AF_INET;
addr4.sin_addr = *(struct in_addr *)RTA_DATA(attr);
if (attrType != IFA_ADDRESS)
address = SocketAddress::create(&addr4);
}
else if (data->ifa_family == AF_INET6) {
memclr(&addr6, sizeof(addr6));
#ifdef SIN6_LEN
addr.sin6_len = sizeof(addr6);
#endif
addr6.sin6_family = AF_INET6;
addr6.sin6_addr = *(struct in6_addr *)RTA_DATA(attr);
addr6.sin6_scope_id = data->ifa_scope;
if (attrType != IFA_ADDRESS)
address = SocketAddress::create(&addr6);
}
if (attrType == IFA_ADDRESS) {
if (data->ifa_family == AF_INET)
label = SocketAddressEntry::create(&addr4, data->ifa_prefixlen);
else if (data->ifa_family == AF_INET6)
label = SocketAddress::create(&addr6);
interface->addressList_->append(label);
}
if ((label) && (data->ifa_family == AF_INET)) {
SocketAddressEntry *entry = cast<SocketAddressEntry>(label.get());
if (attrType == IFA_LOCAL)
entry->localAddress_ = address;
else if (attrType == IFA_BROADCAST)
entry->broadcastAddress_ = address;
else if (attrType == IFA_ANYCAST)
entry->anycastAddress_ = address;
}
}
}
}
else if (msgType == NLMSG_DONE) { // paranoid HACK
break;
}
}
free(buf);
}
}
if (list->count() == 0)
list = queryAllIoctl(family);
return list;
}
Ref<NetworkInterface> NetworkInterface::getLink(NetworkInterfaceList *list, int index)
{
Ref<NetworkInterface> firstFound = 0;
{
int fd = ::socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (fd == -1) FLUX_SYSTEM_DEBUG_ERROR(errno);
int seq = 0;
struct sockaddr_nl src;
memclr(&src, sizeof(src));
src.nl_family = AF_NETLINK;
src.nl_pid = ::getpid();
if (::bind(fd, (struct sockaddr *)&src, (socklen_t)sizeof(src)) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
// send request
{
size_t msgLen = NLMSG_LENGTH(sizeof(struct ifinfomsg));
struct nlmsghdr *msg = (struct nlmsghdr *)flux::malloc(msgLen);
if (!msg) FLUX_SYSTEM_DEBUG_ERROR(errno);
memclr(msg, msgLen);
msg->nlmsg_type = RTM_GETLINK;
msg->nlmsg_len = msgLen;
msg->nlmsg_flags = NLM_F_REQUEST|(NLM_F_ROOT * (index == -1));
msg->nlmsg_pid = src.nl_pid;
msg->nlmsg_seq = seq++;
struct ifinfomsg *data = (struct ifinfomsg *)NLMSG_DATA(msg);
data->ifi_family = AF_UNSPEC;
data->ifi_change = 0xFFFFFFFF;
data->ifi_index = index;
struct sockaddr_nl dst;
memclr(&dst, sizeof(dst));
dst.nl_family = AF_NETLINK;
struct msghdr hdr;
memclr(&hdr, sizeof(hdr));
struct iovec iov = { msg, msgLen };
hdr.msg_iov = &iov;
hdr.msg_iovlen = 1;
hdr.msg_name = (void *)&dst;
hdr.msg_namelen = sizeof(dst);
if (::sendmsg(fd, &hdr, 0/*flags*/) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
flux::free(msg);
}
// process reply
{
struct msghdr hdr;
memclr(&hdr, sizeof(hdr));
ssize_t bufSize = ::recvmsg(fd, &hdr, MSG_PEEK|MSG_TRUNC);
if (bufSize < 0) FLUX_SYSTEM_DEBUG_ERROR(errno);
void *buf = flux::malloc(bufSize);
if (!buf) FLUX_SYSTEM_DEBUG_ERROR(errno);
struct iovec iov = { buf, (size_t)bufSize };
hdr.msg_iov = &iov;
hdr.msg_iovlen = 1;
ssize_t bufFill = ::recvmsg(fd, &hdr, 0/*flags*/);
struct nlmsghdr *msg = (struct nlmsghdr *)buf;
for (;NLMSG_OK(msg, unsigned(bufFill)); msg = NLMSG_NEXT(msg, bufFill))
{
unsigned msgType = msg->nlmsg_type;
// unsigned msgFlags = msg->nlmsg_flags;
if (msgType == RTM_NEWLINK)
{
struct ifinfomsg *data = (struct ifinfomsg *)NLMSG_DATA(msg);
struct rtattr *attr = (struct rtattr *)IFLA_RTA(data);
int attrFill = NLMSG_PAYLOAD(msg, sizeof(struct ifinfomsg));
Ref<NetworkInterface> interface = NetworkInterface::create();
interface->index_ = data->ifi_index;
interface->type_ = data->ifi_type;
interface->flags_ = data->ifi_flags;
for (;RTA_OK(attr, attrFill); attr = RTA_NEXT(attr, attrFill))
{
unsigned attrType = attr->rta_type;
unsigned attrLen = RTA_PAYLOAD(attr);
if ((attrType == IFLA_ADDRESS) || (attrType == IFLA_BROADCAST)) {
// strange fact: hardware address always stored in little endian
unsigned char *value = (unsigned char *)RTA_DATA(attr);
uint64_t h = 0;
for (unsigned i = 0; i < attrLen; ++i) {
h <<= 8;
h |= value[i];
}
if (attrType == IFLA_ADDRESS)
interface->hardwareAddress_= h;
//else if (attrType == IFLA_BROADCAST)
// interface->broadcastAddress_ = h;
}
else if (attrType == IFLA_IFNAME) {
interface->name_ = (char *)RTA_DATA(attr);
}
else if (attrType == IFLA_MTU) {
if (attrLen == 4)
interface->mtu_ = *(uint32_t *)RTA_DATA(attr);
}
}
if (!firstFound) firstFound = interface;
if (list) list->append(interface);
else break;
}
}
flux::free(buf);
}
if (::close(fd) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
}
return firstFound;
}
Ref<NetworkInterfaceList> NetworkInterface::queryAllIoctl(int family)
{
Ref<NetworkInterfaceList> list = NetworkInterfaceList::create();
int fd = ::socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) FLUX_SYSTEM_DEBUG_ERROR(errno);
Ref<LineSource> source = LineSource::open(File::open("/proc/net/dev"));
for (String line; source->read(&line);) {
if (line->contains(':')) {
Ref<NetworkInterface> interface = NetworkInterface::create();
list->append(interface);
Ref<StringList> parts = line->split(":");
String name = parts->at(0)->trim();
interface->name_ = name;
{
struct ifreq ifr;
memclr(&ifr, sizeof(ifr));
for (int i = 0, n = name->count(); i < n; ++i)
ifr.ifr_name[i] = name->at(i);
if (::ioctl(fd, SIOCGIFHWADDR, &ifr) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
interface->hardwareAddress_ = 0;
for (int i = 0, n = 6; i < n; ++i) // quick HACK, 6 is just a safe bet
interface->hardwareAddress_ = (interface->hardwareAddress_ << 8) | ((unsigned char *)ifr.ifr_hwaddr.sa_data)[i];
if (::ioctl(fd, SIOCGIFFLAGS, &ifr) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
interface->flags_ = ifr.ifr_flags;
if (::ioctl(fd, SIOCGIFMTU, &ifr) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
interface->mtu_ = ifr.ifr_mtu;
}
}
}
{
struct ifconf ifc;
int capa = 32 * sizeof(struct ifreq);
ifc.ifc_len = capa;
ifc.ifc_req = (struct ifreq *)flux::malloc(capa);
while (true) {
if (::ioctl(fd, SIOCGIFCONF, &ifc) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
if (ifc.ifc_len == capa) {
flux::free(ifc.ifc_req);
capa *= 2;
ifc.ifc_len = capa;
ifc.ifc_req = (struct ifreq *)flux::malloc(capa);
continue;
}
break;
}
for (int i = 0; i < int(ifc.ifc_len / sizeof(struct ifreq)); ++i)
{
struct ifreq *ifr = ifc.ifc_req + i;
if ((family != AF_UNSPEC) && (family != ifr->ifr_addr.sa_family))
continue;
for (int k = 0; k < list->count(); ++k)
{
NetworkInterface *interface = list->at(k);
if (interface->name_ == ifr->ifr_name) {
struct sockaddr *addr = &ifr->ifr_addr;
struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
Ref<SocketAddress> label;
if (addr->sa_family == AF_INET)
label = SocketAddressEntry::create(addr4);
else if (addr->sa_family == AF_INET6)
label = SocketAddress::create(addr6);
interface->addressList_->append(label);
if ((label) && (addr->sa_family == AF_INET)) {
SocketAddressEntry *entry = cast<SocketAddressEntry>(label.get());
if (interface->flags_ & IFF_BROADCAST) {
struct ifreq ifr2 = *ifr;
if (::ioctl(fd, SIOCGIFBRDADDR, &ifr2) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
entry->broadcastAddress_ = SocketAddress::create((struct sockaddr_in *)&ifr2.ifr_broadaddr);
}
if (interface->flags_ & IFF_POINTOPOINT) {
struct ifreq ifr2 = *ifr;
if (::ioctl(fd, SIOCGIFDSTADDR, &ifr2) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
entry->broadcastAddress_ = SocketAddress::create((struct sockaddr_in *)&ifr2.ifr_dstaddr);
}
}
}
}
}
flux::free(ifc.ifc_req);
}
return list;
}
#else
#ifdef __APPLE__
#define SALIGN (sizeof(int32_t) - 1)
#else
#define SALIGN (sizeof(long) - 1)
#endif
#define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : (SALIGN + 1))
Ref<NetworkInterfaceList> NetworkInterface::queryAll(int family)
{
Ref<NetworkInterfaceList> list = NetworkInterfaceList::create();
int mib[6];
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0 /*protocol*/;
mib[3] = (family == -1) ? AF_UNSPEC : family;
mib[4] = NET_RT_IFLIST;
mib[5] = 0 /*flags*/;
size_t bufSize = 0;
if (::sysctl(mib, 6, NULL, &bufSize, NULL, 0) == -1)
FLUX_SYSTEM_DEBUG_ERROR(errno);
// race against changing address configuration
char *buf = 0;
while (true) {
buf = (char *)flux::malloc(bufSize);
if (!buf) FLUX_SYSTEM_DEBUG_ERROR(errno);
if (::sysctl(mib, 6, (void *)buf, &bufSize, NULL, 0) == -1) {
if (errno == ENOMEM) {
flux::free(buf);
bufSize *= 2; // arbitrary, but safe choice
buf = (char *)flux::malloc(bufSize);
continue;
}
FLUX_SYSTEM_DEBUG_ERROR(errno);
}
else
break;
}
for (
struct if_msghdr *msg = (struct if_msghdr *)buf;
(char *)msg < buf + bufSize;
msg = (struct if_msghdr *)((char *)msg + msg->ifm_msglen)
)
{
int msgType = msg->ifm_type;
int msgAddrs = msg->ifm_addrs;
if (msgType == RTM_IFINFO) {
Ref<NetworkInterface> interface = NetworkInterface::create();
interface->index_ = msg->ifm_index;
interface->flags_ = msg->ifm_flags;
interface->mtu_ = msg->ifm_data.ifi_mtu;
if (msgAddrs & RTA_IFP) {
list->append(interface);
struct sockaddr_dl *addr = (struct sockaddr_dl *)(msg + 1);
if (addr->sdl_family == AF_LINK) { // paranoid check
interface->type_ = addr->sdl_type;
if (addr->sdl_nlen > 0)
interface->name_ = String(addr->sdl_data, addr->sdl_nlen);
if (addr->sdl_alen > 0) {
// strange fact: hardware address always stored in little endian
unsigned char *value = (unsigned char *)addr->sdl_data + addr->sdl_nlen;
uint64_t h = 0;
for (int i = 0, n = addr->sdl_alen; i < n; ++i) {
h <<= 8;
h |= value[i];
}
interface->hardwareAddress_ = h;
}
}
}
}
else if ((msgType == RTM_NEWADDR) && (family != -1)) {
struct ifa_msghdr *msga = (struct ifa_msghdr *)msg;
char *attr = (char *)(msga + 1);
FLUX_ASSERT(list->count() > 0);
NetworkInterface *interface = list->at(list->count() - 1);
// FLUX_ASSERT(interface->index_ == msga->ifam_index); // HACK, OpenBSD can fullfill
Ref<SocketAddress> label;
for (int i = 0; i < RTAX_MAX; ++i) {
if (msga->ifam_addrs & (1 << i)) {
struct sockaddr *addr = (struct sockaddr *) attr;
Ref<SocketAddress> address;
int len = SA_RLEN(addr);
if (i == RTAX_IFA) {
if (addr->sa_family == AF_INET)
label = SocketAddressEntry::create((struct sockaddr_in *)addr);
else if (addr->sa_family == AF_INET6)
label = SocketAddress::create((struct sockaddr_in6 *)addr);
interface->addressList_->append(label);
if (addr->sa_family == AF_INET) {
SocketAddressEntry *entry = cast<SocketAddressEntry>(label);
if (i == RTAX_NETMASK) {
uint32_t x = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
uint32_t y = ~(uint32_t)0;
int m = 32;
for(; m > 0; --m, y <<= 1)
if (x == y) break;
entry->networkMask_ = m;
}
else if (i == RTAX_BRD) {
if (addr->sa_family == AF_INET)
entry->broadcastAddress_ = SocketAddress::create((struct sockaddr_in *)addr);
}
}
}
attr += len;
}
}
}
}
flux::free(buf);
return list;
}
#endif
}} // namespace flux::net
|
#include "device.h"
#ifndef FONT_H
#define FONT_H
class Font
{
const uint8_t * font;
uint8_t width;
uint8_t height;
uint8_t shift;
public:
Font (const uint8_t *f);
void setWidth (uint8_t);
void setHeight (uint8_t);
void setShift (uint8_t);
uint8_t & getWidth ();
uint8_t & getHeight ();
uint8_t & getShift ();
const uint8_t * getFont ();
const uint8_t * getFont (uint16_t);
};
#endif
|
//
// BankAccount_Graphic_Panel.cpp
// BankAccount
//
// Created by ace on 2016. 6. 18..
// Copyright © 2016년 origin. All rights reserved.
//
#include "BankAccount_Graphic_Panel.hpp"
|
/* Rishabh Arora
IIIT-Hyderabad */
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> II;
typedef vector<int> VI;
typedef vector<II> VII;
typedef long long int LL;
typedef unsigned long long int ULL;
#define rep(i, a, b) for(i = a; i < b; i++)
#define rev(i, a, b) for(i = a; i > b; i--)
#define INF INT_MAX
#define PB push_back
#define MP make_pair
#define F first
#define S second
#define SET(a,b) memset(a, b, sizeof(a))
const int N = 1e5+10;
const int mod = 1e9+7;
const int LOGN = 20;
int n, m;
int R[N], M[N], depth[N], par[N], P[N][LOGN];
II a[N];
vector<VI> g;
struct node {
int count;
node *left, *right;
node() {}
node(int count, node * left, node * right) :
count(count), left(left), right(right) {}
node *insert(int l, int r, int w);
};
node *root[N];
node *null = new node(0, NULL, NULL);
node* node::insert(int low, int high, int w) {
if(low == high && low == w) {
return new node(this->count+1, null, null);
}
else if( (high < w) || (low > w) ) {
return this;
}
int mid = (low + high) >> 1;
return new node(this->count+1, this->left->insert(low, mid, w), this->right->insert(mid+1, high, w));
}
int query(node* a, int low, int high, int l, int r) {
if( (low > high) || (low > r) || (high < l)) {
return 0;
}
else if( l <= low && high <= r) {
return this->count;
}
int mid = (low + high) >> 1;
return query(a->left, low, mid, l, r) + query(a->right, mid+1, high, l, r);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int i;
cin >> n >> m;
g.resize(n+1);
rep(i, 1, n+1) {
cin >> a[i].F ;
a[i].S = i;
X[a[i].F] = i;
}
sort(a + 1, a + n + 1);
rep(i, 1, n+1) {
M[a[i].S] = i;
R[i] = a[i].F;
V[X[a[i].S]].PB()
}
null->left=null->right=null;
root[0] = null;
while(m--) {
int u, v, k;
cin >> u >> v >> k;
int l = lca(u, v);
int p = par[l];
if (p == -1) p = 0;
cout << R[query(root[u], root[v], root[l], root[p], 1, n, k)] << '\n';
}
return 0;
}
|
#include <iostream>
#define length 100
using namespace std;
//prototipo funcao maior
double* maior (double *vetor, int tamanho);
int main ()
{
double numero [length], n;
double *pnumero;
double *enderecomaior;
cout<<"Digite a quantidade de numeros desejados:"<<endl;
cin>>n;
if (n<=length)
{
for (int i=0; i<n; i++)
{
cout<<"Digite o numero real desejado: "<<endl;
cin>>numero[i];
}
}
else
cout<<"Digite um numero menor ou igual a 100!"<<endl;
pnumero = numero;
enderecomaior = maior (pnumero, n);
cout<<"O maior numero: "<<*enderecomaior<<endl;
return 0;
}
//implementacao da funcao maior
double* maior (double *vetor, int tamanho)
{
double *maior;
for (int i=0; i<tamanho; i++, vetor++)
{
if (*vetor>(*(vetor+1)))
maior = vetor;
}
return maior;
}
|
//
// Created by 梁栋 on 2019-03-18.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
void combinationSum2Base(const vector<int>& candidates, int start, int target, vector<int > record, vector<vector<int> >& res){
if(target == 0){
res.push_back(record);
return ;
}
bool find_flag = false;
for(int i=start;i<candidates.size() && target >= candidates[i];i++){
if(record.empty() && (i >= 1 && candidates[i] == candidates[i-1]))
continue;
if(find_flag && candidates[i] == candidates[i-1])
continue;
if(find_flag && candidates[i] != candidates[i-1])
find_flag = false;
record.push_back(candidates[i]);
int original_size = res.size();
combinationSum2Base(candidates, i+1, target - candidates[i], record, res);
int after_size = res.size();
if(after_size > original_size){
find_flag = true;
}
record.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
// for(int i=0;i<candidates.size();i++){
// cout<<candidates[i]<<", ";
// }
cout<<endl;
vector<vector<int> > res;
vector<int > record;
combinationSum2Base(candidates, 0, target, record, res);
return res;
}
};
class CombinationSum{
public:
static void test(){
Solution solution;
vector<int> data = {1,2,2,2,5};
vector<vector<int> > res = solution.combinationSum2(data, 5);
for (auto &re : res) {
for (int j : re) {
cout<< j <<", ";
}
cout<<endl;
}
}
};
|
//
// Created by Changmin Kim on 2017. 5. 7..
//
#ifndef OBJECT_TRACKER_OBJECTTRACKER_H
#define OBJECT_TRACKER_OBJECTTRACKER_H
#include <iostream>
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
using namespace std;
#define TPL_DIR "/Users/changmin/Projects/object_tracker/markerTpl.png"
//callback함수 맴버가 콜백으로 바로 들어가지 않으므로 이 함수를 거쳐서 맴버를 호출하게한다.
void onMouse(int event, int x, int y, int, void* obj);
class objectTracker{
private:
Mat image; //추적할 이미지
int trackObjectState; //추적여부
Rect trackWindow; // 추적된 타겟 영역 윈도.
bool isSelectObject; //마우스로 선택여부
Point origin; // 템플레이트의 왼쪽 상단 지점. 이 부분부터 드래그하여 영역을 선택한다.
Rect selection; // 템플레이트 영역. 사각형. 이 부분은 역상으로 표현된다.
int vmin, vmax; // value 값의 경계
int smin; // 최소 채도 값. smin~255까지의 채도 값을 갖는 화소가 검출 대상이다.
//원본영상을 hsv로 바꾸고 hue부분만 추출하고, SV부분 마스크를 얻고, 히스토그램을 구해서 backprojection한다.
Mat hsv, hue, mask, hist, backproj;
//히스토그램을 위한 값들
int hsize;// hue의 bin의 개수.
float hranges[2];//2채널만 사용
const float* phranges;
Rect firstSel;//처음 박스로 클릭한 부분
/*
// objectPos; 오브젝트의 위치를 나타냄
L:Left
R:Right
F:Far
B:Near(Back해야함)
M:missing(정지)
I:initial
*/
char objectPos;
public:
objectTracker();
~objectTracker(){
}
void getImage(const Mat& image){
image.copyTo(this->image);
}
void getTemplateHist();
void trackObject();
void showWindow();
void initWindow(int mode = 0);//0이외의 숫자가 나오면 v값의 범위를 나타낼수 있음
void onMouseEvent(int event, int x, int y);
friend void onMouse(int event, int x, int y, int, void* obj);
char getObjectPos();
void setTracking(int mode){
trackObjectState = mode;
trackWindow = Rect(1,1,image.rows,image.cols);
}
void trackCamShift();
//템플릿으로 추적 - 임의의 파일
void getTemplateHistTpl();//연구중
void trackObjectTpl();
};
#endif //OBJECT_TRACKER_OBJECTTRACKER_H
|
/*
* Copyright (C) 2014-2016 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 COLLISION_BENCHMARK_TEST_COLLIDINGSHAPESCONFIGURATION_H
#define COLLISION_BENCHMARK_TEST_COLLIDINGSHAPESCONFIGURATION_H
#include <collision_benchmark/BasicTypes.hh>
#include <memory>
#include <vector>
#include <string>
namespace collision_benchmark
{
namespace test
{
/**
* \brief Details of one saved configuration for CollideShapesTestFramework test
* \author Jennifer Buehler
* \date May 2017
*/
class CollidingShapesConfiguration
{
// helper struct to allow external boost serialization
public: struct access;
public: typedef std::shared_ptr<CollidingShapesConfiguration> Ptr;
public: typedef std::shared_ptr<const CollidingShapesConfiguration> ConstPtr;
public: CollidingShapesConfiguration() {}
public: CollidingShapesConfiguration(const std::vector<std::string>& _models,
const std::vector<std::string>& _shapes,
const collision_benchmark::BasicState &_modelState1 =
collision_benchmark::BasicState(),
const collision_benchmark::BasicState &_modelState2 =
collision_benchmark::BasicState()):
models(_models),
shapes(_shapes),
modelState1(_modelState1),
modelState2(_modelState2) {}
public: CollidingShapesConfiguration(const CollidingShapesConfiguration &o):
models(o.models),
shapes(o.shapes),
modelState1(o.modelState1),
modelState2(o.modelState2) {}
public: std::vector<std::string> models;
public: std::vector<std::string> shapes;
public: collision_benchmark::BasicState modelState1, modelState2;
};
} // namespace test
} // namespace collision_benchmark
#endif // COLLISION_BENCHMARK_TEST_COLLIDINGSHAPESCONFIGURATION_H
|
#include <iostream>
using namespace std;
class Counter
{
private:
unsigned int m_counter;
public:
Counter() : m_counter(0) {}
unsigned int get() { return m_counter; }
void operator++() { m_counter++; }
void operator--() { m_counter--; }
};
template<class T>
class SharedPointer
{
private:
T* m_ptr;
Counter* m_counter;
public:
SharedPointer(T* ptr = nullptr)
{
m_ptr = ptr;
m_counter = new Counter();
if (ptr)
{
++(*m_counter);
}
}
SharedPointer(SharedPointer<T>& sp)
{
m_ptr = sp.m_ptr;
m_counter = sp.m_ptr;
++(*m_counter);
}
~SharedPointer()
{
--(*m_counter);
if (m_counter->get() == 0)
{
delete m_ptr;
delete m_counter;
}
}
unsigned int use_count() { return m_counter->get(); }
T* get() { return m_ptr; }
T& operator*() { return *m_ptr; }
T* operator->() { return m_ptr; }
};
|
#include "Object.hpp"
class Tile : public Object {
private:
std::string type;
//grass top
//grass fill
//grass slope
//grass steep slope
//? block
//flippy thing
//moving platform
};
|
#include <fstream>
#include <gtest/gtest.h>
#include <cereal/archives/portable_binary.hpp>
#include "hs_test_utility/test_toolkit/test_serialization.hpp"
#include "hs_sfm/sfm_utility/match_type.hpp"
namespace
{
TEST(TestMatchType, SerializationTest)
{
typedef hs::sfm::ImagePair ImagePair;
typedef hs::sfm::KeyPair KeyPair;
typedef hs::sfm::MatchContainer MatchContainer;
typedef hs::sfm::Track Track;
typedef hs::sfm::TrackContainer TrackContainer;
typedef hs::sfm::ObjectIndexMap ObjectIndexMap;
typedef hs::sfm::ViewInfoIndexer ViewInfoIndexer;
MatchContainer matches;
matches[ImagePair(0, 1)].push_back(KeyPair(0, 1));
matches[ImagePair(0, 1)].push_back(KeyPair(0, 2));
matches[ImagePair(0, 1)].push_back(KeyPair(0, 3));
matches[ImagePair(0, 1)].push_back(KeyPair(1, 2));
matches[ImagePair(0, 1)].push_back(KeyPair(1, 3));
matches[ImagePair(1, 2)].push_back(KeyPair(0, 1));
matches[ImagePair(1, 2)].push_back(KeyPair(0, 2));
matches[ImagePair(1, 2)].push_back(KeyPair(0, 3));
hs::test::TestLocalSerialization<MatchContainer> matches_tester;
ASSERT_EQ(true, matches_tester(matches, "matches.bin"));
TrackContainer tracks(100);
for (size_t i = 0; i < 100; i++)
{
for (size_t j = 0; j < 9; j++)
{
tracks[i].push_back(std::pair<size_t, size_t>(2, 3));
}
}
hs::test::TestLocalSerialization<TrackContainer> tracks_tester;
ASSERT_EQ(true, tracks_tester(tracks, "tracks.bin"));
ObjectIndexMap object_index_map(100);
for (size_t i = 0; i < 88; i++)
{
object_index_map[i + 12] = i;
}
hs::test::TestLocalSerialization<ObjectIndexMap> object_index_map_tester;
ASSERT_EQ(true, object_index_map_tester(object_index_map,
"object_index_map.bin"));
ViewInfoIndexer view_info_indexer;
view_info_indexer.SetViewInfoByTracks(tracks);
hs::test::TestLocalSerialization<ViewInfoIndexer> view_info_indexer_tester;
ASSERT_EQ(true, view_info_indexer_tester(view_info_indexer,
"view_info_indexer.bin"));
}
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m,q;
cin>>n>>m;
vector<string>s(n);
vector<string>t(m);
for(int i=0; i<n;i++)
cin>>s[i];
for(int i=0; i<m;i++)
cin>>t[i];
cin>>q;
long y;
while(q--){
cin>>y;
int x = y%n;
int z = y%m;
if(x==0){
cout<<s[n-1];
}else{
cout<<s[x-1];
}
if(z==0){
cout<<t[m-1];
}else{
cout<<t[z-1];
}
cout<<"\n";
}
return 0;
}
|
#include "BCD.h"
BCD::BCDStore BCD::BCDStore::OpenStore( LPCWSTR lpStoreName /*= L""*/, BOOL *pStatus /*= NULL*/ )
{
WMIServices services(L"root\\WMI");
if (!services.Valid())
{
if (pStatus) *pStatus = FALSE;
return BCDStore();
}
WMIObject storeClass = services.GetObject(L"BCDStore");
if (!storeClass.Valid())
{
if (pStatus) *pStatus = FALSE;
return BCDStore();
}
CComVariant res, objStore;
BOOL Bxx = storeClass.ExecMethod(L"OpenStore", &res, &objStore, L"File", L"");
if (!Bxx)
{
if (pStatus) *pStatus = FALSE;
return BCDStore();
}
if ((objStore.vt != VT_UNKNOWN) || !objStore.punkVal)
{
if (pStatus) *pStatus = FALSE;
return BCDStore();
}
if (pStatus) *pStatus = TRUE;
return BCDStore(objStore.punkVal, services);
}
BOOL BCD::BCDStore::ProvideBcdObjects()
{
if (!m_BcdObjects.empty())
return TRUE;
CComVariant res, objects;
BOOL bxx = ExecMethod(L"EnumerateObjects", &res, &objects, L"Type", CComVariant(0, VT_I4));
if (!bxx)
return FALSE;
if (objects.vt != (VT_ARRAY | VT_UNKNOWN))
return FALSE;
m_BcdObjects.clear();
size_t nElements = objects.parray->rgsabound[0].cElements;
m_BcdObjects.reserve(nElements);
for (ULONG i = 0; i < nElements; i++)
{
IUnknown *pUnknown = ((IUnknown **)objects.parray->pvData)[i];
CComPtr<IWbemClassObject> pBcdObject;
BCDObject obj(pUnknown, m_pServices);
if (!obj.Valid())
return FALSE;
m_BcdObjects.push_back(obj);
}
return TRUE;
}
BCD::BCDObject BCD::BCDStore::CopyObject( const BCDObject &Obj, BOOL *pStatus )
{
if (!Obj.Valid())
{
if (pStatus) *pStatus = FALSE;
return BCDObject();
}
wstring objID = Obj.GetID();
if (objID.empty())
{
if (pStatus) *pStatus = FALSE;
return BCDObject();
}
CComVariant res, newobj;
BOOL bxx = ExecMethod(L"CopyObject", &res, &newobj, L"SourceStoreFile", L"", L"SourceId", objID.c_str(), L"Flags", 1);
if (!bxx)
{
if (pStatus) *pStatus = FALSE;
return BCDObject();
}
if ((newobj.vt != VT_UNKNOWN) || !newobj.punkVal)
{
if (pStatus) *pStatus = FALSE;
return BCDObject();
}
if (pStatus) *pStatus = TRUE;
return BCDObject(newobj.punkVal, m_pServices);
}
BCD::BCDElement BCD::BCDObject::GetElement( BCDElementType type )
{
if (!Valid())
return BCDElement();
CComVariant res, bcdElement;
BOOL bxx = ExecMethod(L"GetElement", &res, &bcdElement, L"Type", (long)type);
if (!bxx)
return BCDElement();
if ((bcdElement.vt != VT_UNKNOWN) || !bcdElement.punkVal)
return BCDElement();
return BCDElement(bcdElement.punkVal, m_pServices, *this, type);
}
BOOL BCD::BCDObject::SetElementHelper( BCDElementType type, LPCWSTR pFunctionName, LPCWSTR pParamName, const CComVariant &Value )
{
assert(pFunctionName && pParamName);
if (!Valid())
return FALSE;
CComVariant res;
if (!ExecMethod(pFunctionName, &res, L"Type", (long)type, pParamName, Value))
return FALSE;
if ((res.vt != VT_BOOL) && (res.boolVal != TRUE))
return FALSE;
return TRUE;
}
BOOL BCD::BCDObjectList::ApplyChanges()
{
if (!Valid())
return FALSE;
SAFEARRAY *pArray = SafeArrayCreateVector(VT_BSTR, 0, (ULONG)m_Ids.size());
if (!pArray)
return FALSE;
for (size_t i = 0; i < m_Ids.size(); i++)
((BSTR *)pArray->pvData)[i] = SysAllocString(m_Ids[i].c_str());
CComVariant objList(pArray);
SafeArrayDestroy(pArray);
return m_Element.SetElementHelper(L"SetObjectListElement", L"Ids", objList);
}
|
#include <bits/stdc++.h>
using namespace std ;
#define ll long long
const int MAX_N = 2e5 + 10 ;
int n ;
ll sum , b[MAX_N] , c[MAX_N] ;
bool check(int x) {
for (int i = 0 ; i < x ; ++i) b[i] = 0 ;
for (int i = x ; i <= n ; ++i) b[0] += c[i] ;
for (int i = 0 ; i < x ; ++i) b[i] += c[i] ;
ll ned = 1 ;
for (int i = x - 1 ; i >= 0 ; --i) {
if (ned > sum) return 0 ;
if (ned < b[i]) b[0] += b[i] - ned ;
else ned = ned + ned - b[i] ;
}
if (ned <= b[0]) return 1 ;
else return 0 ;
}
int main() {
sum = 0 ;
scanf("%d" , &n) ;
for (int i = 0 ; i < n ; ++i) scanf("%lld" , &c[i]) , sum += c[i] ;
if(sum == 1)
{
if(c[0] == 1) cout << 1 << endl;
else for (int i = 0 ; i < n ; ++i) if(c[i] == 1) cout << i << endl;
return 0;
}
///
int L = 0 , R = n + 100 ;
for (; L + 1 < R ;) {
int mid = (L + R) >> 1 ;
if (check(mid)) L = mid ;
else R = mid ;
}
printf("%d\n" , L) ;
return 0 ;
}
|
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
int n,m,a=1;
while(true)
{
scanf("%d %d",&n,&m);
if(!n && !m)break;
int ara[n+2],x;
for(int i=0;i<n;i++)scanf("%d",&ara[i]);
for(int i=0;i<m;i++)scanf("%d",&x);
printf("Case %d: ",a);
sort(ara,ara+n,greater<int>());
if(m>=n)printf("0\n");
else
{
int ok=n-m;
printf("%d %d\n",ok,ara[n-1]);
}
a++;
}
return 0;
}
|
//--------------------------------------------------------------
// Student Name: < Ivan Hernandez , Linhson Bui>
// Date: <12/13/2018>
//
// Space Ship Spotted - CS134 Final Project
// In this game you are exploring an unknown land
// as an alien in a flying saucer
// You want to find and abduct any cows you can find
// Unforunately for you, there is no source of water in this land
// That means no form of life, that includes cows
//
// We are using octrees to determine an intersection
// and phyics to resolve the collision
// Cameras are set up to track the ship, see a bottom view from the ship
// see a side view from the ship, and a free view of the ship
//
// Use the arrows keys to move around
// keys 1-5 change the camera angles
// p toggles the points of collision we are testing for intersection
// c enables movement of the camera
// w toggles the wireframe of the terrain
//
//
//
#include "ofApp.h"
#include "Util.h"
//--------------------------------------------------------------
// setup scene, lighting, state and load geometry
//
void ofApp::setup(){
bWireframe = false;
bDisplayPoints = false;
bAltKeyDown = false;
bCtrlKeyDown = false;
bRoverLoaded = false;
bTerrainSelected = true;
// ofSetWindowShape(1024, 768);
cam.setDistance(30);
cam.setNearClip(.1);
cam.setFov(65.5); // approx equivalent to 28mm in 35mm format
ofSetVerticalSync(true);
cam.disableMouseInput();
ofEnableSmoothing();
ofEnableDepthTest();
theCam = &cam;
// setup rudimentary lighting
//
initLightingAndMaterials();
//Ivan Hernandez - Created the alien terrain in Maya
mars.loadModel("geo/terrain_v2.obj");
mars.setScaleNormalization(false);
boundingBox = meshBounds(mars.getMesh(0));
altitude = 0;
// Ivan Hernandez - Worked on the Octree Implementation
// Create the Octree by passing in the mesh and the amount of levels
octree.create(mars.getMesh(0), 8);
// To appropriate the rotation of the mesh
mars.setRotation(0, 180, 0, 0, 1);
// Rover setup
// load BG image
//
bBackgroundLoaded = backgroundImage.load("images/starry_bg.jpg");
backgroundImage.resize(ofGetWidth(), ofGetHeight());
// Ivan Hernandez - Created the spaceship in Maya
// load lander model
if (lander.loadModel("geo/spaceShip.obj")) {
lander.setScaleNormalization(false);
lander.setScale(.25, .25, .25);
lander.setRotation(0, -180, 1, 0, 0);
lander.setPosition(0,0,0);
bLanderLoaded = true;
}
else {
cout << "Error: Can't load model" << "geo/spaceShip.obj" << endl;
ofExit(0);
}
trackingCam.setFov(90);
trackingCam.setPosition(30, 10, 0);
sideCam.setFov(90);
downCam.setFov(90);
downCam.lookAt(glm::vec3(0, 0, 0));
// particle System with 1 particle
prover.add(par);
//turbulence force
turbForce = new TurbulenceForce(ofVec3f(-0.7,-0.7,-0.7),ofVec3f(0.7,0.7,0.7));
// setting up the vectors that move the particle
thrust = new Thruster(ofVec3f(0,0,0));
// exhaust particles
turb2 = new TurbulenceForce(ofVec3f(-2,-2,-2),ofVec3f(2,2,2));
gravF = new GravityForce(ofVec3f(0,-.09,0));
radF = new ImpulseRadialForce(100.0);
resForce = new ImpulseForce();
exhaustForce = new ImpulseRadialForce(50);
exhaust.sys->addForce(exhaustForce);
//set the emitter's variables
exhaust.setVelocity(ofVec3f(0,-4,0));
exhaust.setEmitterType(DiskEmitter);
exhaust.setGroupSize(2);
exhaust.setLifespan(.8);
exhaust.setParticleRadius(.01);
exhaust.setRate(35);
prover.addForce(turbForce);
prover.addForce(thrust);
prover.addForce(resForce);
prover.addForce(gravF);
shipBox = Box(Vector3(-1,-1,-1),Vector3(1,1,1));
prover.particles[0].position = ofVec3f(-20,5,0);
cam.setPosition(ofVec3f(-20,0,0));
//setup for ufo audio
if(ufo.load("ufo.mp3"))
soundSet = true;
//setup for theme audio
if(theme.load("space_theme.mp3"))
tmSet = true;
if(tmSet){
theme.setVolume(.5);
theme.play();
}
//Ivan Hernandez - light setup
keyLight.setup();
keyLight.enable();
keyLight.setAreaLight(1, 1);
keyLight.setAmbientColor(ofFloatColor(1, 1, 1));
keyLight.setDiffuseColor(ofFloatColor(1, 1, 1));
keyLight.setSpecularColor(ofFloatColor(1, 1, 1));
keyLight.rotate(45, ofVec3f(0, 1, 0));
keyLight.rotate(45, ofVec3f(1, 0, 0));
keyLight.setPosition(glm::vec3(0, 200, 0));
keyLight.lookAt(glm::vec3(0, 0, 0));
}
//--------------------------------------------------------------
// incrementally update scene (animation)
void ofApp::update() {
prover.update();
exhaust.setPosition(ofVec3f(prover.particles[0].position.x, prover.particles[0].position.y + .25, prover.particles[0].position.z));
exhaust.update();
assigner = prover.particles[0].position;
lander.setPosition(assigner.x , assigner.y , assigner.z);
altRayDistance();
//Ivan Hernandez - Worked on the code for the different types of Cameras
//Tracking Camera
trackingCam.setPosition(glm::vec3(lander.getPosition().x + 10, lander.getPosition().y + 2, lander.getPosition().z + 10));
trackingCam.lookAt(glm::vec3(lander.getPosition().x, lander.getPosition().y + 2, lander.getPosition().z));
//side view camera
sideCam.setPosition(glm::vec3(lander.getPosition().x - 1, lander.getPosition().y + 4, lander.getPosition().z));
sideCam.lookAt(glm::vec3(glm::vec3(lander.getPosition().x + .30, lander.getPosition().y + 4, lander.getPosition().z)));
//ground view camera
downCam.setPosition(glm::vec3(lander.getPosition().x, lander.getPosition().y + 5, lander.getPosition().z));
downCam.lookAt(glm::vec3(glm::vec3(prover.particles[0].position.x, -1*(prover.particles[0].position.y + .30), prover.particles[0].position.z)));
// updates the collision box of the space ship
shipBox.parameters[0] = Vector3(assigner.x , assigner.y , assigner.z) + Vector3(-1.7,0,-1.7);
shipBox.parameters[1] =Vector3(assigner.x , assigner.y , assigner.z) + Vector3(1.7,1.75,1.7);
// dimension of our shipBox is 3.4 x 1.75. 3.4
// dont know how to get dimensions from model directly so box is hard coded
// looks for collisions every frame
collisionDect();
// if there is a collision, turn off the turbulence force
if (colDetected == true){
turbForce->set(ofVec3f(0,0,0), ofVec3f(0,0,0));
resCollision();
}
}
//--------------------------------------------------------------
void ofApp::draw(){
// draws the background if one is loaded
if (bBackgroundLoaded) {
ofPushMatrix();
ofDisableDepthTest();
backgroundImage.draw(0, 0);
ofEnableDepthTest();
ofPopMatrix();
}
cam.begin();
theCam->begin();
ofPushMatrix();
if (bWireframe) { // wireframe mode (include axis)
ofDisableLighting();
ofSetColor(ofColor::slateGray);
mars.drawWireframe();
if (bRoverLoaded) {
rover.drawWireframe();
if (!bTerrainSelected) drawAxis(rover.getPosition());
}
if (bTerrainSelected) drawAxis(ofVec3f(0, 0, 0));
}
else {
ofEnableLighting(); // shaded mode
mars.drawFaces();
if (bRoverLoaded) {
rover.drawFaces();
if (!bTerrainSelected) drawAxis(rover.getPosition());
}
if (bTerrainSelected) drawAxis(ofVec3f(0, 0, 0));
}
if (bDisplayPoints) { // display points as an option
glPointSize(3);
ofSetColor(ofColor::green);
mars.drawVertices();
}
// highlight selected point (draw sphere around selected point)
//
if (bPointSelected) {
ofSetColor(ofColor::blue);
ofDrawSphere(selectedPoint, .1);
}
ofNoFill();
ofSetColor(ofColor::white);
if (intPtsToggle == true){
for(int i = 0; i <6; i++)
ofDrawSphere(boxPts[i].x(),boxPts[i].y(),boxPts[i].z(),.05);
}
//keyLight.draw();
lander.drawFaces();
exhaust.draw();
ofPopMatrix();
cam.end();
theCam->end();
string str;
str += "Frame Rate: " + std::to_string(ofGetFrameRate());
ofSetColor(ofColor::white);
ofDrawBitmapString(str, ofGetWindowWidth() - 170, 15);
string altistr;
altistr += "Altitude: " + std::to_string(altitude);
ofSetColor(ofColor::white);
ofDrawBitmapString(altistr, 15, 15);
}
//
// Draw an XYZ axis in RGB at world (0,0,0) for reference.
//
void ofApp::drawAxis(ofVec3f location) {
ofPushMatrix();
ofTranslate(location);
ofSetLineWidth(1.0);
// X Axis
ofSetColor(ofColor(255, 0, 0));
ofDrawLine(ofPoint(0, 0, 0), ofPoint(1, 0, 0));
// Y Axis
ofSetColor(ofColor(0, 255, 0));
ofDrawLine(ofPoint(0, 0, 0), ofPoint(0, 1, 0));
// Z Axis
ofSetColor(ofColor(0, 0, 255));
ofDrawLine(ofPoint(0, 0, 0), ofPoint(0, 0, 1));
ofPopMatrix();
}
void ofApp::keyPressed(int key) {
switch (key) {
case '1':
theCam = &cam;
break;
case '2':
theCam = &trackingCam;
break;
case '3':
theCam = &sideCam;
break;
case '4':
theCam = &downCam;
break;
case '5':
theCam = &cam;
theCam->setPosition(glm::vec3(lander.getPosition().x + 10, lander.getPosition().y + 2, lander.getPosition().z + 10));
theCam->lookAt(glm::vec3(lander.getPosition().x, lander.getPosition().y + 2, lander.getPosition().z));
break;
case '6':
direc = lander.getPosition() - theCam->getPosition();
theCam->setPosition(theCam->getPosition() + (direc.getNormalized() * -.2));
break;
case 'C':
case 'c':
if (cam.getMouseInputEnabled()) cam.disableMouseInput();
else cam.enableMouseInput();
break;
case 'F':
case 'f':
ofToggleFullscreen();
break;
case 'H':
case 'h':
break;
case 'i':
{
// used for testing collisions
ofVec3f vel = prover.particles[0].velocity;
resForce->apply(-ofGetFrameRate()*vel);
break;
}
case 'p':
intPtsToggle = !intPtsToggle;
break;
case 'r':
cam.reset();
break;
case 's':
savePicture();
break;
case 't':
setCameraTarget();
break;
case 'u':
theme.stop();
break;
case 'v':
togglePointsDisplay();
break;
case 'V':
break;
case 'w':
toggleWireframeMode();
break;
case OF_KEY_ALT:
cam.enableMouseInput();
bAltKeyDown = true;
break;
case OF_KEY_CONTROL:
bCtrlKeyDown = true;
break;
case OF_KEY_SHIFT:
break;
case OF_KEY_DEL:
break;
case OF_KEY_UP:
// Using alt key to determine whether we change z or x
if (!bAltKeyDown){
prover.reset();
thrust->set(ofVec3f(0,SPD,0));
exhaust.sys->reset();
exhaust.start();
ufo.play();
}
else{
prover.reset();
thrust->set(ofVec3f(0,0,SPD));
}
break;
case OF_KEY_DOWN:
if(!bAltKeyDown){
prover.reset();
thrust->set(ofVec3f(0,-SPD,0));
}
else{
prover.reset();
thrust->set(ofVec3f(0,0,-SPD));
}
break;
case OF_KEY_LEFT:
prover.reset();
thrust->set(ofVec3f(-SPD,0,0));
break;
case OF_KEY_RIGHT:
prover.reset();
thrust->set(ofVec3f(SPD,0,0));
break;
default:
break;
}
}
void ofApp::toggleWireframeMode() {
bWireframe = !bWireframe;
}
void ofApp::toggleSelectTerrain() {
bTerrainSelected = !bTerrainSelected;
}
void ofApp::togglePointsDisplay() {
bDisplayPoints = !bDisplayPoints;
}
void ofApp::keyReleased(int key) {
switch (key) {
case OF_KEY_ALT:
cam.disableMouseInput();
bAltKeyDown = false;
break;
case OF_KEY_CONTROL:
bCtrlKeyDown = false;
break;
case OF_KEY_SHIFT:
break;
case OF_KEY_UP:
exhaust.sys->reset();
ufo.stop();
exhaust.stop();
case OF_KEY_RIGHT:
case OF_KEY_LEFT:
case OF_KEY_DOWN:
prover.reset();
thrust->set(ofVec3f(0,0,0));
break;
default:
break;
}
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button) {
}
//draw a box from a "Box" class
//
void ofApp::drawBox(const Box &box) {
Vector3 min = box.parameters[0];
Vector3 max = box.parameters[1];
Vector3 size = max - min;
Vector3 center = size / 2 + min;
ofVec3f p = ofVec3f(center.x(), center.y(), center.z());
float w = size.x();
float h = size.y();
float d = size.z();
ofDrawBox(p, w, h, d);
}
// return a Mesh Bounding Box for the entire Mesh
//
Box ofApp::meshBounds(const ofMesh & mesh) {
int n = mesh.getNumVertices();
ofVec3f v = mesh.getVertex(0);
ofVec3f max = v;
ofVec3f min = v;
for (int i = 1; i < n; i++) {
ofVec3f v = mesh.getVertex(i);
if (v.x > max.x) max.x = v.x;
else if (v.x < min.x) min.x = v.x;
if (v.y > max.y) max.y = v.y;
else if (v.y < min.y) min.y = v.y;
if (v.z > max.z) max.z = v.z;
else if (v.z < min.z) min.z = v.z;
}
return Box(Vector3(min.x, min.y, min.z), Vector3(max.x, max.y, max.z));
}
// Subdivide a Box into eight(8) equal size boxes, return them in boxList;
//
void ofApp::subDivideBox8(const Box &box, vector<Box> & boxList) {
Vector3 min = box.parameters[0];
Vector3 max = box.parameters[1];
Vector3 size = max - min;
Vector3 center = size / 2 + min;
float xdist = (max.x() - min.x()) / 2;
float ydist = (max.y() - min.y()) / 2;
float zdist = (max.z() - min.z()) / 2;
Vector3 h = Vector3(0, ydist, 0);
// generate ground floor
//
Box b[8];
b[0] = Box(min, center);
b[1] = Box(b[0].min() + Vector3(xdist, 0, 0), b[0].max() + Vector3(xdist, 0, 0));
b[2] = Box(b[1].min() + Vector3(0, 0, zdist), b[1].max() + Vector3(0, 0, zdist));
b[3] = Box(b[2].min() + Vector3(-xdist, 0, 0), b[2].max() + Vector3(-xdist, 0, 0));
boxList.clear();
for (int i = 0; i < 4; i++)
boxList.push_back(b[i]);
// generate second story
//
for (int i = 4; i < 8; i++) {
b[i] = Box(b[i - 4].min() + h, b[i - 4].max() + h);
boxList.push_back(b[i]);
}
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button) {
}
bool ofApp::doPointSelection() {
}
// Set the camera to use the selected point as it's new target
//
void ofApp::setCameraTarget() {
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
// setup basic ambient lighting in GL (for now, enable just 1 light)
//
void ofApp::initLightingAndMaterials() {
static float ambient[] =
{ .5f, .5f, .5, 1.0f };
static float diffuse[] =
{ 1.0f, 1.0f, 1.0f, 1.0f };
static float position[] =
{5.0, 5.0, 5.0, 0.0 };
static float lmodel_ambient[] =
{ 1.0f, 1.0f, 1.0f, 1.0f };
static float lmodel_twoside[] =
{ GL_TRUE };
glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, position);
glLightfv(GL_LIGHT1, GL_AMBIENT, ambient);
glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse);
glLightfv(GL_LIGHT1, GL_POSITION, position);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// glEnable(GL_LIGHT1);
glShadeModel(GL_SMOOTH);
}
void ofApp::savePicture() {
ofImage picture;
picture.grabScreen(0, 0, ofGetWidth(), ofGetHeight());
picture.save("screenshot.png");
cout << "picture saved" << endl;
}
//--------------------------------------------------------------
//
// support drag-and-drop of model (.obj) file loading. when
// model is dropped in viewport, place origin under cursor
//
void ofApp::dragEvent(ofDragInfo dragInfo) {
ofVec3f point;
mouseIntersectPlane(ofVec3f(0, 0, 0), cam.getZAxis(), point);
if (rover.loadModel(dragInfo.files[0])) {
rover.setScaleNormalization(false);
rover.setScale(.005, .005, .005);
rover.setPosition(point.x, point.y, point.z);
bRoverLoaded = true;
}
else cout << "Error: Can't load model" << dragInfo.files[0] << endl;
}
bool ofApp::mouseIntersectPlane(ofVec3f planePoint, ofVec3f planeNorm, ofVec3f &point) {
glm::vec3 mouse(mouseX, mouseY, 0);
ofVec3f rayPoint = cam.screenToWorld(mouse);
ofVec3f rayDir = rayPoint - cam.getPosition();
rayDir.normalize();
return (rayIntersectPlane(rayPoint, rayDir, planePoint, planeNorm, point));
}
// Linhson Bui
// Casts a ray downwards from the ship until it collides with the terrain
// Calculates the distance and displays that on screen
//
void ofApp::altRayDistance(){
// Create a ray where the point is the position of the spaceship
// and the direction is striaght down
ofVec3f rayPoint = prover.particles[0].position;
ofVec3f rayDir = ofVec3f(0,-1,0);
Ray ray = Ray(Vector3(rayPoint.x, rayPoint.y, rayPoint.z),
Vector3(rayDir.x, rayDir.y, rayDir.z));
TreeNode selectionNode;
octree.intersect(ray, octree.root, selectionNode);
// If the oct intersection returns a Node with a point
// set the altitude to the difference of the Ship position and that returned node point
if (selectionNode.points.size() > 0) {
altPoint = mars.getMesh(0).getVertex(selectionNode.points[0]);
ofVec3f resRay = rayPoint - altPoint;
altitude = resRay.y;
}
}
// Linhson Bui
// Detects collision using the center of each face of the bound box of the ship
//
void ofApp::collisionDect(){
if(colDetected == false){
// gets the center of each box face and puts thm
// into an array
boxPts[0] = shipBox.max() + Vector3(-shipW/2,0,-shipL/2);
boxPts[1] = shipBox.min() + Vector3(0,shipH/2,shipL/2);
boxPts[2] = shipBox.min() + Vector3(shipW/2,shipH/2,0);
boxPts[3] = shipBox.max() + Vector3(0,-shipH/2,-shipL/2);
boxPts[4] = shipBox.max() + Vector3(-shipW/2, -shipH/2,0);
boxPts[5] = shipBox.min() + Vector3(shipW/2,0,shipL/2);
// return of the ship is moving upwards
// we have no ceilings in this terrain
ofVec3f vel = prover.particles[0].velocity;
if (vel.y > 0) return;
int i = 0;
TreeNode selectionNode;
// we traverse through that array
// seeing if they intersect with the terrain octree
// once 1 is found set colDetected to true
while( i < 8 && colDetected == false){
octree.intersect(boxPts[i], octree.root, selectionNode);
if(selectionNode.points.size() > 0){
// cout << "Collision Detected" << endl;
colDetected = true;
}
else i++;
}
}
}
// Linhson Bui
// Applies the resolution force to the ship if there is a collision
//
void ofApp::resCollision(){
// stops checking for collision of the ship stops moving in the y direction
ofVec3f vel = prover.particles[0].velocity;
if (vel.y == 0){
return;
}
// applying the formula from the lecture
ofVec3f n = vel;
n.normalize();
float dot = (-vel.x * n.x) + (-vel.y * n.y) + (-vel.z * n.z);
ofVec3f resVec = 1.2 * dot * n;
resForce->apply(ofGetFrameRate()*resVec);
//cout << "ResForce applied" << endl;
colDetected = false;
}
|
#include <iostream>
#include <fstream>
int main(int argc, char **argv)
{
if (argc != 2) {
return 1;
}
std::ifstream f(argv[1], std::ios::binary);
f.seekg(0, std::ios::end);
std::cout << f.tellg();
return 0;
}
|
//@@author A0112218W
#include "Command_Edit.h"
EditCommand::EditCommand(CommandTokens::SecondaryCommandType type2, size_t index) : Command(CommandTokens::PrimaryCommandType::Edit) {
_type2 = type2;
_index = index;
}
bool EditCommand::canUndo() {
return true;
}
EditNameCommand::EditNameCommand(size_t index, std::string newTaskText):EditCommand(CommandTokens::SecondaryCommandType::Name, index) {
_newTaskText = newTaskText;
}
UIFeedback EditNameCommand::execute(RunTimeStorage* runTimeStorage) {
checkIsValidForExecute(runTimeStorage);
std::string feedbackMessage;
assert (!_newTaskText.empty());
try {
Task& taskToEdit = runTimeStorage -> find(_index);
_editIndex = runTimeStorage -> find(taskToEdit);
_oldTaskText = taskToEdit.getTaskText();
//Task object used to check for duplication after edit.
Task testTask = taskToEdit;
testTask.changeTaskText(_newTaskText);
if (runTimeStorage->isDuplicate(testTask)) {
throw COMMAND_EXECUTION_EXCEPTION(MESSAGE_EDIT_DUPLICATE);
}
taskToEdit.changeTaskText(_newTaskText);
char buffer[255];
sprintf_s(buffer, MESSAGE_EDIT_NAME_SUCCESS.c_str(), _oldTaskText.c_str(), _newTaskText.c_str());
feedbackMessage = std::string(buffer);
postExecutionAction(runTimeStorage);
return UIFeedback(runTimeStorage->refreshTasksToDisplay(), feedbackMessage);
} catch (INDEX_NOT_FOUND_EXCEPTION e){
throw COMMAND_EXECUTION_EXCEPTION(e.what());
} catch (COMMAND_EXECUTION_EXCEPTION e){
throw e;
}
}
UIFeedback EditNameCommand::undo() {
checkIsValidForUndo();
Task& taskToEdit = _runTimeStorageExecuted->getEntry(_editIndex);
taskToEdit.changeTaskText(_oldTaskText);
std::vector<Task> taskToDisplay = _runTimeStorageExecuted->refreshTasksToDisplay();
postUndoAction();
return UIFeedback(taskToDisplay, MESSAGE_EDIT_UNDO);
}
EditStartCommand::EditStartCommand(size_t index, ptime newStart) : EditCommand(CommandTokens::SecondaryCommandType::Start, index) {
_newStart = newStart;
}
UIFeedback EditStartCommand::execute(RunTimeStorage* runTimeStorage) {
checkIsValidForExecute(runTimeStorage);
std::string feedbackMessage;
try {
Task& taskToEdit = runTimeStorage -> find(_index);
_editIndex = runTimeStorage -> find(taskToEdit);
_oldStart = taskToEdit.getStartDateTime();
//Task object used to check for duplication after edit.
Task testTask = taskToEdit;
testTask.changeStartDateTime(_newStart);
if (runTimeStorage->isDuplicate(testTask)) {
throw COMMAND_EXECUTION_EXCEPTION(MESSAGE_EDIT_DUPLICATE);
}
taskToEdit.changeStartDateTime(_newStart);
char buffer[255];
std::string newStartString = boost::posix_time::to_simple_string(_newStart);
sprintf_s(buffer, MESSAGE_EDIT_START_SUCCESS.c_str(), taskToEdit.getTaskText().c_str(), newStartString.c_str());
feedbackMessage = std::string(buffer);
postExecutionAction(runTimeStorage);
return UIFeedback(runTimeStorage->refreshTasksToDisplay(), feedbackMessage);
} catch (INDEX_NOT_FOUND_EXCEPTION e) {
throw COMMAND_EXECUTION_EXCEPTION(e.what());
} catch (TASK_EXCEPTION e) {
throw COMMAND_EXECUTION_EXCEPTION(e.what());
} catch (COMMAND_EXECUTION_EXCEPTION e){
throw e;
}
}
UIFeedback EditStartCommand::undo() {
checkIsValidForUndo();
Task& taskToEdit = _runTimeStorageExecuted->getEntry(_editIndex);
taskToEdit.changeStartDateTime(_oldStart);
std::vector<Task> taskToDisplay = _runTimeStorageExecuted->refreshTasksToDisplay();
postUndoAction();
return UIFeedback(taskToDisplay, MESSAGE_EDIT_UNDO);
}
EditEndCommand::EditEndCommand(size_t index, ptime newEnd) : EditCommand(CommandTokens::SecondaryCommandType::End, index) {
_newEnd = newEnd;
}
UIFeedback EditEndCommand::execute(RunTimeStorage* runTimeStorage) {
checkIsValidForExecute(runTimeStorage);
std::string feedbackMessage;
try {
Task& taskToEdit = runTimeStorage -> find(_index);
_editIndex = runTimeStorage -> find(taskToEdit);
_oldEnd = taskToEdit.getEndDateTime();
//Task object used to check for duplication after edit.
Task testTask = taskToEdit;
testTask.changeEndDateTime(_newEnd);
if (runTimeStorage->isDuplicate(testTask)) {
throw COMMAND_EXECUTION_EXCEPTION(MESSAGE_EDIT_DUPLICATE);
}
taskToEdit.changeEndDateTime(_newEnd);
char buffer[255];
std::string newEndString = boost::posix_time::to_simple_string(_newEnd);
sprintf_s(buffer, MESSAGE_EDIT_END_SUCCESS.c_str(), taskToEdit.getTaskText().c_str(), newEndString.c_str());
feedbackMessage = std::string(buffer);
postExecutionAction(runTimeStorage);
return UIFeedback(runTimeStorage->refreshTasksToDisplay(), feedbackMessage);
} catch(INDEX_NOT_FOUND_EXCEPTION e) {
throw COMMAND_EXECUTION_EXCEPTION(e.what());
} catch(TASK_EXCEPTION e) {
throw COMMAND_EXECUTION_EXCEPTION(e.what());
} catch (COMMAND_EXECUTION_EXCEPTION e){
throw e;
}
}
UIFeedback EditEndCommand::undo() {
checkIsValidForUndo();
Task& taskToEdit = _runTimeStorageExecuted->getEntry(_editIndex);
taskToEdit.changeEndDateTime(_oldEnd);
std::vector<Task> taskToDisplay = _runTimeStorageExecuted->refreshTasksToDisplay();
postUndoAction();
return UIFeedback(taskToDisplay, MESSAGE_EDIT_UNDO);
}
|
//
// Created by nickolay on 09.06.2020.
//
#include <opencv2/imgcodecs.hpp>
//#include <opencv2/imgcodecs/imgcodecs_c.h>
#include <iostream>
#include <opencv2/imgproc.hpp>
#include "DroneImage.h"
#include "opencv2/highgui.hpp"
DroneImage::DroneImage()
{
data = cv::imread("../../testim.jpg", cv::IMREAD_COLOR);//CV_LOAD_IMAGE_COLOR);
cv::resize(data, data, cv::Size(320, 240), 0, 0, cv::INTER_CUBIC);
setImage(data.size(),data.data);
}
void DroneImage::setImage(std::shared_ptr<cv::Mat> im)
{
mutex.lock();
image = std::shared_ptr<cv::Mat>(new cv::Mat( im->size(), CV_8UC3, im->data));
mutex.unlock();
}
void DroneImage::setGrayImage(std::shared_ptr<cv::Mat> im)
{
mutex.lock();
image = std::shared_ptr<cv::Mat>(new cv::Mat( im->size(), CV_8UC1, im->data));
mutex.unlock();
}
void DroneImage::setImage(cv::Size size, uchar* dataArray)
{
mutex.lock();
cv::Mat d = cv::Mat(size, CV_8UC3, dataArray);
data = d.clone();
image = std::shared_ptr<cv::Mat>(new cv::Mat(data));
mutex.unlock();
}
void DroneImage::setGrayImage(cv::Size size, uchar* dataArray)
{
mutex.lock();
cv::Mat d = cv::Mat(size, CV_8UC1, dataArray);
data = d.clone();
image = std::shared_ptr<cv::Mat>(new cv::Mat(data));
mutex.unlock();
}
void DroneImage::saveToTestDir()
{
mutex.lock();
std::cout<<"trying to save"<<std::endl;
cv::imwrite("../../testOut.jpg",*image.get());
std::cout<<"saved"<<std::endl;
mutex.unlock();
}
std::shared_ptr<cv::Mat> DroneImage::getImage()
{
mutex.lock();
std::shared_ptr<cv::Mat> result = image;
mutex.unlock();
return result;
}
|
#include<SerialFlash.h>
#define FLASH_PIN (0)
void setup() {
//open serial and wait for it to complete
Serial.begin(9600);
while(!Serial)
{
delay(100);
}
//try and access the chip
bool serialOpen = SerialFlash.begin(FLASH_PIN);
if(serialOpen)
{
//erase the chip
Serial.println("Erasing the chip...");
SerialFlash.eraseAll();
while(SerialFlash.ready() == false)
{
//wait for chip to be ready (30s to 2 mins)
}
Serial.println("Chip erased");
}
else
{
//error message
Serial.println("Unable to access Chip");
}
}
void loop() {
// put your main code here, to run repeatedly:
}
|
#include "MontonCartas.h"
using namespace std;
MontonCartas::MontonCartas()
{
p = 0;
deleted = 0;
}
MontonCartas::MontonCartas(int todas)
{
char pal [] = {'O','C','B','E'};
deleted = 0;
Carta *aux;
bool primeraCarta = true;
for(int i=0; i<4; i++)
{
char a = pal[3-i];
for(int j=0; j<12; j++)
{
aux = new Carta;
(*aux).palo = a;
(*aux).num = 12-j;
if(primeraCarta)
{
(*aux).sig = 0;
primeraCarta = false;
}else
(*aux).sig = p;
p = aux;
}
}
delete aux;
}
MontonCartas::~MontonCartas()
{
recursiveDelete(p);
recursiveDelete(deleted);
}
MontonCartas& MontonCartas::operator= (const MontonCartas& orig)
{
if(&orig != this)
{
if(this->p != 0)
{
Carta *Claus;
Claus=this->p;
while(Claus != 0)
{
Claus = (*Claus).sig;
delete p;
p = Claus;
}
}
Carta *aux, *aux2;
aux = this->p;
aux2 = orig.p;
bool primeraCarta = true;
while(aux2 != 0)
{
aux = new Carta;
if(primeraCarta)
{
(*aux).sig = 0;
primeraCarta = false;
}else
(*aux).sig = p;
p = aux;
aux2 = (*aux2).sig;
}
// data copy
aux = this->p;
aux2 = orig.p;
while(aux2 != 0)
{
(*aux).num = (*aux2).num;
(*aux).palo = (*aux2).palo;
aux = (*aux).sig;
aux2 = (*aux2).sig;
}
}
return *this;
}
void MontonCartas::recursiveDelete(Carta* &pointer)
{
if(pointer != 0)
{
if(pointer->sig == 0)
{
delete pointer;
}else{
recursiveDelete(pointer->sig);
}
}
}
void MontonCartas::intercambiar(int pos1, int pos2)
{
Carta* aux1;
Carta* aux2 ;
aux1 = p;
aux2 = p;
for(int i=0; i<pos1; ++i)
aux1 = (*aux1).sig;
for(int i=0; i<pos2; ++i)
aux2 = (*aux2).sig;
int numAux = (*aux1).num ;
char paloAux = aux1->palo ;
aux1->num = aux2->num;
aux1->palo = aux2->palo;
aux2->num = numAux;
aux2->palo = paloAux;
}
Carta* MontonCartas::getCarta(int pos)
{
Carta* laCarta = p;
for(int i=0; i<pos; i++)
laCarta = (*laCarta).sig;
return laCarta;
}
int MontonCartas::getNumeroCarta (int pos) const
{
Carta *aux = p;
for(int i=0; i<pos; i++)
aux = (*aux).sig;
return (*aux).num;
}
char MontonCartas::getPaloCarta (int pos) const
{
Carta *aux;
aux = p;
for(int i=0; i<pos; i++)
aux = (*aux).sig;
return (*aux).palo;
}
int MontonCartas::sizeMonton()
{
int tam=0;
Carta *aux;
aux = p;
for(tam; aux != 0; tam++){
aux = (*aux).sig;
}
return tam;
}
void MontonCartas::eliminarCarta (int pos)
{
int tam = sizeMonton();
Carta* aux ;
aux = p;
if(pos == 0)
{
p = p->sig;
aux->sig = 0;
}
else if(pos == tam-1)
{
Carta* aux2 ;
aux2 = p;
for(int i=0; i<pos; ++i)
aux = aux->sig;
for(int i=0; i<pos-1; ++i)
aux2 = aux2->sig;
aux2->sig = 0;
}
else
{
Carta* aux2 ;
aux2 = p;
for(int i=0; i<pos; ++i)
aux = aux->sig;
for(int i=0; i<pos-1; ++i)
aux2 = aux2->sig;
aux2->sig = aux->sig;
aux->sig = 0;
}
// now we have to add the deleted card to the deleted pointer
if(this->deleted == 0)
{
deleted = aux;
}
else
{
Carta* auxDeleted ;
auxDeleted = deleted;
while(auxDeleted->sig != 0)
{
auxDeleted = auxDeleted->sig;
}
auxDeleted->sig = aux;
}
}
void MontonCartas::insertarCarta (int n, char tipo)
{
//we have to search for the same and existing card
bool encontrada = false;
Carta *aux;
aux = p;
while(aux!=0 && !encontrada)
{
if((*aux).num == n && (*aux).palo == tipo)
encontrada = true;
aux = (*aux).sig;
}
if(!encontrada) // if that's true, now we have to add it to the end
{
aux = p;
//move aux to the end
while((*aux).sig != 0)
{
aux = (*aux).sig;
}
//create a new card
Carta *aux2 = new Carta;
(*aux2).sig = 0;
(*aux2).num = n;
(*aux2).palo = tipo;
(*aux).sig = aux2;
}else
cout<<"This card already exist."<<endl;
}
void MontonCartas::mezclar()
{
int tam = sizeMonton();
srand(time(0));
for(int i=0; i<tam; i++)
{
int pos1 = rand()%tam;
int pos2 = rand()%tam;
intercambiar(pos1,pos2);
}
}
Carta* MontonCartas::sacarCarta(int pos)
{
Carta * laCarta = getCarta(pos);
eliminarCarta(pos);
return laCarta;
}
void MontonCartas::printMonton()
{
Carta * aux = p;
int veces = 0;
while(aux != 0)
{
cout << aux->num << aux->palo << " " ;
aux = aux->sig;
veces ++;
if(veces == 12)
{
cout << endl;
veces = 0;
}
}
}
|
// Zach_Hunter_HW4.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
double deposit = 0.0;
double intrate = 0.0;
double balance = 0.0;
int months = 0;
int asternum = 0;
string asterisk1;
int monthcount = 1;
double astercalc = 0.0;
cout << "Enter a deposit amount between $100 and $10000." << endl << "$";
cin >> deposit;
while (deposit < 100 || deposit > 10000 || cin.fail()) { //loop for validation checking on deposit
cin.clear(); //nifty trick I found to use cin.fail in validation check to throw out anything that isnt a number
cin.ignore(1000000, '\n');
cout << "Please enter a valid deposit between $100 and $10,000." << endl << "$";
cin >> deposit;
}
cout << endl << "Enter the number of months. (Between 12 and 60)" << endl;
cin >> months;
while (months < 12 || months > 60 || cin.fail()) { //loop for validation checking on months
cin.clear();
cin.ignore(1000000, '\n');
cout << "Please enter a valid number of months. (Between 12 and 60)" << endl;
cin >> months;
}
cout << endl << "Enter an interest rate between 2.0 and 8.0 percent." << endl;
cin >> intrate;
while (intrate < 2 || intrate > 8 || cin.fail()) { //loop for validation checking on interest rate
cin.clear();
cin.ignore(1000000, '\n');
cout << "Please enter a valid interest rate between 2.0 and 8.0 percent." << endl;
cin >> intrate;
}
ofstream savingsfile; //beginning common outputs
savingsfile.open("savings.txt");
cout << "Thank you for banking at TheBigVault" << endl; //line 1
savingsfile << "Thank you for banking at TheBigVault" << endl;
cout << left << setw(21) << "Deposit" << "$" << right << setw(13) << fixed << setprecision(2) << deposit << endl; //line 2
savingsfile << left << setw(21) << "Deposit" << "$" << right << setw(13) << fixed << setprecision(2) << deposit << endl;
cout << left << setw(21) << "Interest Rate" << " " << right << setw(13) << intrate << "%" << endl; //line 3
savingsfile << left << setw(21) << "Interest Rate" << " " << right << setw(13) << intrate << "%" << endl;
cout << left << setw(21) << "Month" << " " << right << setw(13) << "Balance" << endl; //line 4
savingsfile << left << setw(21) << "Month" << " " << right << setw(13) << "Balance" << endl;
cout << "------------------------------------" << endl; //line 5
savingsfile << "------------------------------------" << endl;
intrate = intrate / 100; //convert intrate to usable number after it has been displayed
for (monthcount = 1, asterisk1 = ""; monthcount <= 12 ; monthcount++) { //loop for console display, limited to 12 months
astercalc = deposit * 0.1;
balance = deposit*pow((1.0 + (intrate / 12)), monthcount); //balance formula
asternum = balance / astercalc; //bonus 1, calculates how many asterisks are needed
for (int astercount = asternum; astercount > 0; astercount--) { //adds asterisks to string depending on how many it needs
asterisk1 = asterisk1 + "*";
}
cout << left << setw(21) << monthcount << "$" << right << setw(13) << balance << " " << asterisk1 << endl;
asterisk1 = "";
}
cout << endl << "Full readout available in savings.txt" << endl << "5 year (60 month) projection available in balance.txt" << endl;
for (monthcount = 1, asterisk1 = ""; monthcount <= months; monthcount++) { //loop for file display equal to number of months
astercalc = deposit * 0.1;
balance = deposit*pow((1.0 + (intrate / 12)), monthcount);
asternum = balance / astercalc;
for (int astercount = asternum; astercount > 0; astercount--) {
asterisk1 = asterisk1 + "*";
}
savingsfile << left << setw(21) << monthcount << "$" << right << setw(13) << balance << " " << asterisk1 << endl;
asterisk1 = "";
}
savingsfile.close();
ofstream balancefile; //bonus 2, outputs all 60 months of data
balancefile.open("balance.txt");
balancefile << "5 Year (60 Month) Balance Projection" << endl << left << setw(17) << "Month" << right << setw(18) << "Balance" << endl << "-----------------------------------" << endl;
for (monthcount = 1, asterisk1 = ""; monthcount <= 60; monthcount++) { //loop for file display, always continues for 60 months
astercalc = deposit * 0.1;
balance = deposit*pow((1.0 + (intrate / 12)), monthcount);
asternum = balance / astercalc;
for (int astercount = asternum; astercount > 0; astercount--) {
asterisk1 = asterisk1 + "*";
}
balancefile << left << setw(21) << monthcount << "$" << right << setw(13) << fixed << setprecision(2) << balance << " " << asterisk1 << endl;
asterisk1 = "";
}
balancefile.close();
system("pause");
return 0;
}
|
/***************************************************************************
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.
***************************************************************************/
#pragma once
namespace sci
{
// STL doesn't have a memory stream (other than stringstream), so we'll implement our own
// simple one.
class ostream
{
public:
ostream();
ostream(const ostream &src) = delete;
ostream& operator=(const ostream &src) = delete;
void WriteWord(uint16_t w);
void WriteByte(uint8_t b);
void WriteBytes(const uint8_t *pData, int cCount);
void FillByte(uint8_t value, int cCount);
void reset();
uint32_t tellp() const { return _cbSizeValid; }
void seekp(uint32_t newPosition);
void seekp(int32_t offset, std::ios_base::seekdir way);
// Use with caution!
uint8_t *GetInternalPointer() { return _pData.get(); }
const uint8_t *GetInternalPointer() const { return _pData.get(); }
template<class _T>
ostream &operator<< (const _T &t)
{
WriteBytes(reinterpret_cast<const uint8_t*>(&t), sizeof(t));
return *this;
}
ostream &operator<< (const std::string aString)
{
WriteBytes(reinterpret_cast<const uint8_t*>(aString.c_str()), (int)aString.length() + 1);
return *this;
}
uint32_t GetDataSize() const { return _cbSizeValid; }
void EnsureCapacity(uint32_t size);
private:
void _Grow(uint32_t cbGrowMin);
std::unique_ptr<uint8_t[]> _pData; // Our data
uint32_t _iIndex; // Current index into it.
uint32_t _cbReserved; // The size in bytes of pData
uint32_t _cbSizeValid; // Size that contains valid data.
std::ios_base::iostate _state;
};
//
// Class used to read/write data from a resource
// It's a bit messy now with whom owns the internal byte stream. This needs some work.
//
class istream
{
public:
istream(const uint8_t *pData, uint32_t cbSize);
istream(const sci::istream &original, uint32_t absoluteOffset);
istream();
istream(const sci::istream &original) = default;
istream &operator=(const sci::istream &original) = default;
uint32_t GetDataSize() const { return _cbSizeValid; }
// New api
bool good() { return (_state & (std::ios_base::failbit | std::ios_base::eofbit)) == 0; }
bool has_more_data() { return tellg() < GetDataSize(); }
istream &operator>> (uint16_t &w);
istream &operator>> (uint8_t &b);
istream &operator>> (std::string &str);
void getRLE(std::string &str);
void read_data(uint8_t *pBuffer, uint32_t cbBytes)
{
if (!_Read(pBuffer, cbBytes))
{
_state = std::ios_base::eofbit | std::ios_base::failbit;
}
}
template<class _T>
istream &operator>> (typename _T &t)
{
uint32_t dwSave = tellg();
if (!_Read(reinterpret_cast<uint8_t*>(&t), sizeof(t)))
{
seekg(dwSave);
memset(&t, 0, sizeof(t));
_state = std::ios_base::eofbit | std::ios_base::failbit;
}
return *this;
}
void seekg(uint32_t dwIndex);
void seekg(int32_t offset, std::ios_base::seekdir way);
uint32_t tellg() { return _iIndex; }
uint32_t getBytesRemaining() { return (_cbSizeValid > _iIndex) ? (_cbSizeValid - _iIndex) : 0; }
void skip(uint32_t cBytes);
bool peek(uint8_t &b);
bool peek(uint16_t &w);
uint8_t peek();
void setThrowExceptions(bool shouldThrow) { _throwExceptions = shouldThrow; }
// Use with caution!
const uint8_t *GetInternalPointer() const { return _pDataReadOnly; }
private:
bool _ReadWord(uint16_t *pw) { return _Read((uint8_t*)pw, 2); }
bool _Read(uint8_t *pData, uint32_t cCount);
bool _ReadByte(uint8_t *pb) { return _Read(pb, 1); }
void _OnReadPastEnd();
uint32_t _iIndex;
uint32_t _cbSizeValid;
const uint8_t *_pDataReadOnly;
bool _throwExceptions;
std::ios_base::iostate _state;
};
istream istream_from_ostream(ostream &src);
class streamOwner
{
public:
streamOwner(const uint8_t *data, uint32_t size);
streamOwner(HANDLE hFile, DWORD lengthToInclude = 0);
streamOwner(const std::string &filename); // Memory mapped
~streamOwner();
istream getReader();
uint32_t GetDataSize();
private:
std::unique_ptr<uint8_t[]> _pData; // Our data
uint32_t _cbSizeValid;
const uint8_t *_dataMemoryMapped;
HANDLE _hFile;
HANDLE _hMap;
};
void transfer(istream from, ostream &to, uint32_t count);
}
|
/**
*
* @file main.cpp
* @brief Test main function
* @author Naoki Takahashi
*
**/
#include <exception>
#include <iostream>
#include <string>
#include <bitset>
#include <chrono>
#include <thread>
#include <boost/asio.hpp>
#include "Constant.hpp"
#include "Converter/Endian.hpp"
#include "CommandLineArgumentReader.hpp"
#include "Byte.hpp"
#include "Log/Logger.hpp"
#include "Math/Differential/Function.hpp"
#include "Math/Matrix.hpp"
#include "Math/Unit/SI.hpp"
#include "Math/Unit/UnofficialSI.hpp"
#include "Math/Unit/Value.hpp"
#include "Math/MatrixOperation.hpp"
#include "Math/MathLiterals.hpp"
int main(int argc, char **argv) {
try {
std::vector<double> log_vec;
Tools::Log::Logger logger(argc, argv);
if(Tools::Converter::Endian::is_big_endian()) {
logger.message(Tools::Log::MessageLevels::info, "This computer is big endian");
}
else if(Tools::Converter::Endian::is_little_endian()) {
logger.message(Tools::Log::MessageLevels::info, "This computer is little endian");
}
else {
logger.message(Tools::Log::MessageLevels::info, "This computer is unknown endian");
}
auto start_p = std::chrono::high_resolution_clock::now();
auto end_p = std::chrono::high_resolution_clock::now();
start_p = std::chrono::high_resolution_clock::now();
end_p = std::chrono::high_resolution_clock::now();
logger.message(Tools::Log::MessageLevels::debug, "Milliseconds of ");
logger.message(Tools::Log::MessageLevels::debug, std::chrono::duration<double, std::ratio<1, 1000>>(end_p - start_p).count());
auto message_level_test = "Test: Message level";
logger.message(Tools::Log::MessageLevels::trace, message_level_test);
logger.message(Tools::Log::MessageLevels::debug, message_level_test);
logger.message(Tools::Log::MessageLevels::info, message_level_test);
logger.message(Tools::Log::MessageLevels::warning, message_level_test);
logger.message(Tools::Log::MessageLevels::error, message_level_test);
logger.message(Tools::Log::MessageLevels::fatal, message_level_test);
logger.start_loger_thread();
log_vec.push_back(1.2);
log_vec.push_back(1.2);
log_vec.push_back(1.2);
log_vec.push_back(1.2);
Tools::Math::Vector<float, 3> v;
Tools::Math::Matrix<float, 3, 3> m;
v << 1, 2, 1;
m = v.asDiagonal();
logger.message(Tools::Log::MessageLevels::debug, "Test: message matrix");
logger.message(Tools::Log::MessageLevels::debug, v);
logger.message(Tools::Log::MessageLevels::debug, m);
start_p = std::chrono::high_resolution_clock::now();
logger.message(Tools::Log::MessageLevels::debug, "Test: STL vector");
logger.message(Tools::Log::MessageLevels::debug, log_vec);
logger.message(Tools::Log::MessageLevels::debug, "");
end_p = std::chrono::high_resolution_clock::now();
logger.message(Tools::Log::MessageLevels::debug, "Milliseconds of ");
logger.message(Tools::Log::MessageLevels::debug, std::chrono::duration<double, std::ratio<1, 1000>>(end_p - start_p).count());
auto dfunc = std::make_unique<Tools::Math::Differential::Function<float>>();
Tools::Math::Unit::Value<float, Tools::Math::Unit::SI::metre> have_unit_value(0.1);
short value_for_byte_debug = 360;
std::string print_message;
logger.message(Tools::Log::MessageLevels::trace, "Byte operation test");
print_message = "Original data is " + std::to_string(value_for_byte_debug);
logger.message(Tools::Log::MessageLevels::trace, print_message);
auto low_byte = static_cast<uint8_t>(Tools::Byte::low_byte(value_for_byte_debug));
print_message = "Low byte is " + std::to_string(low_byte);
logger.message(Tools::Log::MessageLevels::trace, print_message);
auto high_byte = static_cast<uint8_t>(Tools::Byte::high_byte(value_for_byte_debug));
print_message = "High byte is " + std::to_string(high_byte);
logger.message(Tools::Log::MessageLevels::trace, print_message);
auto original_byte = Tools::Byte::union_byte(static_cast<short>(high_byte), static_cast<short>(low_byte));
print_message = "Original byte is " + std::to_string(original_byte);
logger.message(Tools::Log::MessageLevels::trace, print_message);
logger.close_loger_thread();
}
catch(const std::exception &error) {
std::cerr << error.what() << std::endl;
}
return 0;
}
|
#pragma once
#include <experimental/coroutine>
#include <variant>
#include <optional>
#include <system_error>
namespace ncoro
{
namespace stde = std::experimental;
namespace details
{
template<typename T, typename E, typename ExceptionHandler>
class result
{
public:
using value_type = std::remove_cvref_t<T>;
using error_type = std::remove_cvref_t<E>;
using exception_handler = std::remove_cvref_t<ExceptionHandler>;
result(const value_type& t);
result(value_type&& t);
result(const error_type& e);
result(error_type&& e);
result(const result& r);
result(result&& r);
result& operator=(const value_type& v);
result& operator=(value_type&& v);
result& operator=(const error_type& v);
result& operator=(error_type&& v);
result& operator=(result&& r);
result& operator=(result const& r);
bool has_value() const;
bool has_error() const;
operator bool() const;
value_type& operator->();
const value_type& operator->() const;
value_type& operator*();
const value_type& operator*() const;
value_type& value();
const value_type& value() const;
value_type& value_or(value_type& alt);
const value_type& value_or(const value_type& alt) const;
error_type& error();
const error_type& error() const;
bool operator==(result const& y) const;
bool operator!=(result const& y) const;
bool operator==(const value_type&) const;
bool operator!=(const value_type&) const;
friend bool operator==(const value_type&, const result&);
friend bool operator!=(const value_type&, const result&);
bool operator==(const error_type&) const;
bool operator!=(const error_type&) const;
friend bool operator==(const error_type&, const result&);
friend bool operator!=(const error_type&, const result&);
struct promise_type;
template <class Promise>
struct result_awaiter {
using value_type = typename Promise::result_type::value_type;
using exception_handler = typename Promise::result_type::exception_handler;
result<value_type, error_type, exception_handler>&& res;
result_awaiter(result<value_type, error_type, exception_handler>&& r)
: res(std::move(r))
{}
value_type&& await_resume() noexcept {
return std::move(res.value());
}
bool await_ready() noexcept {
return res.has_value();
}
void await_suspend(std::experimental::coroutine_handle<promise_type> const& handle) noexcept {
handle.promise().var() = res.error();
}
};
struct promise_type
{
using result_type = result;
stde::suspend_never initial_suspend() { return {}; }
stde::suspend_never final_suspend() noexcept { return {}; }
result get_return_object() {
return stde::coroutine_handle<promise_type>::from_promise(*this);
}
void return_value(value_type&& v) noexcept {
var() = std::move(v);
}
void return_value(value_type const& v) {
var() = v;
}
void return_value(error_type&& e) noexcept {
var() = std::move(e);
}
void return_value(error_type const& e) noexcept {
var() = e;
}
void unhandled_exception() {
var() = ExceptionHandler{}.unhandled_exception();
}
template <class TT, class H>
auto await_transform(result<TT, error_type, H>&& res) noexcept {
return result_awaiter<result<TT, error_type, H>::promise_type>(std::move(res));
}
std::variant<value_type, error_type>& var()
{
return mRes->mVar;
}
result_type* mRes;
};
private:
using coro_handle = std::experimental::coroutine_handle<promise_type>;
std::variant<value_type, error_type> mVar;
std::variant<value_type, error_type>& var() {
return mVar;
};
const std::variant<value_type, error_type>& var() const {
return mVar;
};
result(coro_handle handle)
{
handle.promise().mRes = this;
}
};
template<typename T, typename E, typename H>
result<T, E, H>::result(const value_type& t)
:mVar(t)
{}
template<typename T, typename E, typename H>
result<T, E, H>::result(value_type&& t)
: mVar(std::forward<value_type>(t))
{}
template<typename T, typename E, typename H>
result<T, E, H>::result(const error_type& e)
: mVar(e)
{}
template<typename T, typename E, typename H>
result<T, E, H>::result(error_type&& e)
: mVar(std::forward<error_type>(e))
{}
template<typename T, typename E, typename H>
result<T, E, H>::result(result const& r)
: mVar(r.mVar)
{}
template<typename T, typename E, typename H>
result<T, E, H>::result(result&& r)
: mVar(std::move(r.mVar))
{}
template<typename T, typename E, typename H>
result<T, E, H>& result<T, E, H>::operator=(const value_type& v) { var() = v; return *this; }
template<typename T, typename E, typename H>
result<T, E, H>& result<T, E, H>::operator=(value_type&& v) { var() = std::move(v); return *this; }
template<typename T, typename E, typename H>
result<T, E, H>& result<T, E, H>::operator=(const error_type& v) { var() = v; return *this; }
template<typename T, typename E, typename H>
result<T, E, H>& result<T, E, H>::operator=(error_type&& v) { var() = std::move(v); return *this; }
template<typename T, typename E, typename H>
result<T, E, H>& result<T, E, H>::operator=(result&& r) { var() = std::move(r.var()); return *this; }
template<typename T, typename E, typename H>
result<T, E, H>& result<T, E, H>::operator=(result const& r) { var() = r.var(); return *this; }
template<typename T, typename E, typename H>
bool result<T, E, H>::has_value() const { return std::holds_alternative<value_type>(var()); }
template<typename T, typename E, typename H>
bool result<T, E, H>::has_error() const { return !has_value(); }
template<typename T, typename E, typename H>
result<T, E, H>::operator bool() const { return has_value(); }
template<typename T, typename E, typename H>
typename result<T, E, H>::value_type& result<T, E, H>::operator->() { return value(); }
template<typename T, typename E, typename H>
const typename result<T, E, H>::value_type& result<T, E, H>::operator->() const { return value(); }
template<typename T, typename E, typename H>
typename result<T, E, H>::value_type& result<T, E, H>::operator*() { return value(); }
template<typename T, typename E, typename H>
const typename result<T, E, H>::value_type& result<T, E, H>::operator*() const { return value(); }
template<typename T, typename E, typename H>
typename result<T, E, H>::value_type& result<T, E, H>::value() {
if (has_error())
exception_handler{}.throwErrorType(error());
return std::get<value_type>(var());
}
template<typename T, typename E, typename H>
const typename result<T, E, H>::value_type& result<T, E, H>::value() const {
if (has_error())
exception_handler{}.throwErrorType(error());
return std::get<value_type>(var());
}
template<typename T, typename E, typename H>
typename result<T, E, H>::value_type& result<T, E, H>::value_or(value_type& alt) {
if (has_error())
return alt;
return std::get<value_type>(var());
}
template<typename T, typename E, typename H>
const typename result<T, E, H>::value_type& result<T, E, H>::value_or(const value_type& alt) const {
if (has_error())
return alt;
return std::get<value_type>(var());
}
class bad_result_access
: public std::exception
{
public:
bad_result_access(char const* const msg)
: std::exception(msg)
{ }
};
template<typename T, typename E, typename H>
typename result<T, E, H>::error_type& result<T, E, H>::error() {
if (has_value())
throw bad_result_access("error() was called on a Result<T,E> which stores an value_type");
return std::get<error_type>(var());
}
template<typename T, typename E, typename H>
const typename result<T, E, H>::error_type& result<T, E, H>::error() const {
if (has_value())
throw bad_result_access("error() was called on a Result<T,E> which stores an value_type");
return std::get<error_type>(var());
}
template<typename T, typename E, typename H>
bool result<T, E, H>::operator==(result const& y) const {
return var() == y.var();
}
template<typename T, typename E, typename H>
bool result<T, E, H>::operator!=(result const& y) const {
return var() != y.var();
}
template<typename T, typename E, typename H>
bool result<T, E, H>::operator==(const value_type& v) const {
return var() == v;
}
template<typename T, typename E, typename H>
bool result<T, E, H>::operator!=(const value_type& v) const {
return var() != v;
}
template<typename T, typename E, typename H>
bool operator==(const T& v, const result<T, E, H>& r) {
return r.var() == v;
}
template<typename T, typename E, typename H>
bool operator!=(const T& v, const result<T, E, H>& r) {
return r.var() != v;
}
template<typename T, typename E, typename H>
bool result<T, E, H>::operator==(const error_type& v) const {
return var() == v;
}
template<typename T, typename E, typename H>
bool result<T, E, H>::operator!=(const error_type& v) const {
return var() != v;
}
template<typename T, typename E, typename H>
bool operator==(const E& v, const result<T, E, H>& r) {
return r.var() == v;
}
template<typename T, typename E, typename H>
bool operator!=(const E& v, const result<T, E, H>& r) {
return r.var() != v;
}
//template<typename T, typename E, typename EX>
//std::ostream& operator<<(std::ostream& out, const result<T, E, EX>& r) {
// if (r.has_value())
// out << "{" << r.value() << "}";
// else
// out << "<" << r.error().message() << ">" << std::endl;
// return out;
//}
}
enum class Errc
{
success = 0,
uncaught_exception
};
using error_code = std::error_code;
error_code make_error_code(Errc e);
}
namespace std {
template <>
struct is_error_code_enum<ncoro::Errc> : true_type {};
}
namespace ncoro {
template<typename T, typename E>
struct RethrowExceptionHandler
{
std::variant<T, E> unhandled_exception() {
throw;
}
void throwErrorType(E& e) {
throw e;
}
};
template<typename T, typename E>
class NothrowExceptionHandler;
template<typename T>
class NothrowExceptionHandler<T, std::error_code>
{
public:
std::variant<T, std::error_code> unhandled_exception() {
try {
throw;
}
catch (std::error_code e) {
return e;
}
catch (...) {
return Errc::uncaught_exception;
}
std::terminate();
}
void throwErrorType(std::error_code e) {
throw e;
}
};
template<typename T>
class NothrowExceptionHandler<T, std::exception_ptr>
{
public:
std::variant<T, std::exception_ptr> unhandled_exception() {
return std::current_exception();
}
void throwErrorType(std::exception_ptr e) {
std::rethrow_exception(e);
}
};
template<typename T, typename E>
class NothrowExceptionHandler
{
public:
std::variant<T, E> unhandled_exception() {
try {
throw;
}
catch (E & e) {
return e;
}
catch (...) {
return E{};
}
std::terminate();
}
void throwErrorType(E const& e) {
throw e;
}
};
template<typename T, typename Error = std::error_code, typename ExceptionHandler = NothrowExceptionHandler<T, Error>>
using result = details::result<T, Error, ExceptionHandler>;
}
int resultMain();
|
///////////////////////////////////////////////////////////////////
//Copyright 2019-2020 Perekupenko Stanislav. All Rights Reserved.//
//@Author Perekupenko Stanislav (stanislavperekupenko@gmail.com) //
///////////////////////////////////////////////////////////////////
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "CPPW_SaveButton.generated.h"
class UCPPW_Save;
UCLASS()
class SACPP_API UCPPW_SaveButton : public UUserWidget
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Components", meta = (BindWidget)) class UButton* ButtonDelete;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Components", meta = (BindWidget)) class UButton* ButtonResave;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Components", meta = (BindWidget)) class UButton* ButtonLoad;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Components", meta = (BindWidget)) class UTextBlock* TextBlockName;
virtual void NativeConstruct() override;
void SetUp(FString _saveName, UCPPW_Save* _parent);
private:
FString SaveName;
UCPPW_Save* ParentSaveWidget;
UFUNCTION(BlueprintCallable, Category = "Input") void ButtonDeleteOnClicked();
UFUNCTION(BlueprintCallable, Category = "Input") void ButtonResaveOnClicked();
UFUNCTION(BlueprintCallable, Category = "Input") void ButtonLoadOnClicked();
};
|
/*
* SKETCH:
* DWIO.ino
*
* (c) 2016, Michael Gries
* Creation: 2016-06-28 (based on SimpleTestDweetIO.ino)
* Modified: 2016-06-28 (function DweetIOmessaging added)
* Modified: 2016-07-04 (ESP.getFreeHeap() added to Dweet)
*
* PREREQUISITES:
* uses predefined local WiFi network
*
* LINKS:
* see https://dweet.io/ (home page of service provider)
* see https://dweet.io/follow/af104-D1mini (this application)
* see https://dweet.io/follow/af104-test (NodeMCU Lua project test data for reference)
*
* ISSUES:
* none
*
*/
#include <ESP8266WiFi.h>
#include <TimeLib.h> // by Paul Stoffregen, not included in the Arduino IDE !!!
#define DWEET_IO_THING_NAME "af104-D1mini" // IoT test device name
//// DECLARATIONS
const char* host = "dweet.io";
void DweetIOmessaging(){
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.print(__func__); Serial.println(": TCP connection failed (port 80)");
return;
}
Serial.print(__func__); Serial.print(": TCP: port 80 connected, HTTP: sent data to "); Serial.println(host);
char TimeStamp[20];
sprintf(TimeStamp, "%04d-%02d-%02d_%02d:%02d:%02d", year(), month(), day(), hour(), minute(), second() );
//Serial.println(TimeStamp);
//
// send the request to the server https://dweet.io/follow/af104-D1mini
//
client.print(String("GET /dweet/for/af104-D1mini")
+ "?"
+ "RSSI=" + WiFi.RSSI()
+ "&"
+ "Millis=" + millis()
+ "&"
+ "TimeStamp=" + TimeStamp
+ "&"
+ "FreeHeap=" + ESP.getFreeHeap()
+ "&"
+ "ToolVersion=" + __VERSION__
+ " "
+ "HTTP/1.1\r\n"
+ "Host: " + host + "\r\n"
+ "Connection: close\r\n\r\n"
);
delay(10);
// Read all the lines of the reply from server and print them to Serial
String httpStatusLine;
bool onlyfirstLine = true;
while(client.available()){
String line = client.readStringUntil('\r');
if (onlyfirstLine) {
httpStatusLine = line;
onlyfirstLine = false;
}
// Serial.print(__func__); Serial.print(line); // only for debug purposes
}
Serial.print(__func__); Serial.print(": HTTP: received "); Serial.println(httpStatusLine);
}
|
#include "dweetESP8266.h"
#include <ArduinoJson.h>
/**
* Constructor.
*/
dweet::dweet(){
// _thing_name = thing_name;
maxValues = 5;
currentValue = 0;
val = (Value *)malloc(maxValues*sizeof(Value));
}
/**
* This function is to get value from the dweet.io API
* @arg key the key where you will get the data
* @return value the data that you get from the dweet.io API
*/
String dweet::getDweet(char* thing_name, char* key){
String value;
String response;
uint8_t bodyPosinit;
uint8_t bodyPosend;
String dweetKey ="\"";
dweetKey += key;
dweetKey += "\":";
int length = dweetKey.length();
if (_client.connect(SERVER, PORT)){
//Serial.println(F("geting your variable"));
Serial.println(F("\n\nrequesting value of given key ...")); // M. Gries, 2016-06-05
// Make a HTTP request:
_client.print(F("GET /get/latest/dweet/for/"));
_client.print(thing_name);
_client.println(F(" HTTP/1.1"));
_client.println(F("Host: dweet.io"));
_client.println(F("User-Agent: ESP8266-WiFi/1.0"));
_client.println(F("Connection: close"));
_client.println();
}
while (!_client.available());
while (_client.available()){
response = _client.readString();
}
//Serial.write(c);
Serial.println(response);
bodyPosinit =4+ response.indexOf("\r\n\r\n");
response = response.substring(bodyPosinit);
// Serial.println(response); // M,Gries
bodyPosinit =10+ response.indexOf("\"content\"");
bodyPosend = response.indexOf("}]}");
response = response.substring(bodyPosinit,bodyPosend);
// Serial.println(response); M. Gries
if (response.indexOf(dweetKey) == -1) {
value = "Key not found";
} else {
//StaticJsonBuffer<200> jsonBuffer; //M. Gries, 2016-06-05
StaticJsonBuffer<500> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(response);
if (!root.success()){
Serial.println("parseObject() failed");
value = "parse error.";
} else {
const char* val = root[key];
value = String(val);
}
}
_client.flush();
_client.stop();
return value;
}
/**
* Add a value of variable to save
* @arg key variable key to save in a struct
* @arg value variable value to save in a struct
*/
void dweet::add(char *key, String value){
if(currentValue == maxValues){
Serial.println(F("You are sending more than 5 consecutives variables, you just could send 5 variables. Then other variables will be deleted!"));
//currentValue = maxValues;
} else {
(val+currentValue)->id = key;
(val+currentValue)->value_id = value;
currentValue++;
}
}
/**
* Send all data of all variables that you saved
* @reutrn true upon success, false upon error.
*/
bool dweet::sendAll(char* thing_name){
int i;
String all;
String str;
for(i=0; i<currentValue;){
str = (val+i)->value_id;
all += String((val + i)->id);
all += "=";
all += str;
i++;
if(i<currentValue){
all += "&";
}
}
//i = all.length();
if (_client.connect(SERVER, PORT)){
Serial.println(F("Posting your variables"));
_client.print(F("POST /dweet/for/"));
_client.print(thing_name);
_client.print(F("?"));
_client.print(all);
_client.println(F(" HTTP/1.1"));
_client.println(F("Host: dweet.io"));
_client.println(F("User-Agent: ESP8266-WiFi/1.0"));
_client.println(F("Connection: close"));
_client.println();
}
while(!_client.available());
while (_client.available()){
char c = _client.read();
Serial.write(c);
}
currentValue = 0;
_client.stop();
return true;
}
bool dweet::wifiConnection(char* ssid, char* pass){
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
|
/**
* \file NumberCrush.cxx
* \author Brice Maussang, Gaëtan Perrot, Peio Rigaux, Jérémy Topalian
* \date 16 Decembre 2014
* \brief Jeu NumberCrush
* \version 1.0
*/
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <limits>
#include <cstdlib>
#include <ctime>
using namespace std;
/** \namespace nsNumberCrush
*
* \brief namespace grouping tools components game's gameplay
*
*/
namespace nsNumberCrush
{
typedef vector <string> CVString; /*!< \brief a type representing a matrix of string */
typedef vector <unsigned> CVUInt;/*!< \brief a type representing a vector of unsigned */
typedef vector <char> CVLine;/*!< \brief a type representing a row of the matrix */
typedef vector <CVLine> CMat;/*!< \brief a type representing the matrix */
typedef pair <unsigned, unsigned> CPosition;/*!< \brief a type representing a position in the matrix */
typedef vector <CPosition> CVPair;/*!< \brief a type representing a matrix of position */
//Colors
const string KReset = "0"; /*!< \brief a type to return to the original color */
const string KBlack = "30";/*!< \brief a type to set a string in black */
const string KRed = "31";/*!< \brief a type to set a string in red */
const string KGreen = "32";/*!< \brief a type to set a string in green */
const string KYellow = "33";/*!< \brief a type to set a string in yellow */
const string KBlue = "34";/*!< \brief a type to set a string in blue */
const string KMagenta = "35";/*!< \brief a type to set a string in magenta */
const string KCyan = "36";/*!< \brief a type to set a string in cyan */
//Files Name
const string KConfigFileName = ("config.cfg");/*!< \brief a type to name the config file */
const string KHeaderFileName = ("header.txt");/*!< \brief a type to name the header file */
const string KMenuFileName = ("menu.txt");/*!< \brief a type to name the menu file */
const string KRulesFileName = ("rules.txt");/*!< \brief a type to name the rules file */
const string KHelpFileName = ("instructions.txt");/*!< \brief a type to name the help file */
const string KCreditsFileName = ("credit.txt");/*!< \brief a type to name the credit file */
const unsigned KSquareValue = 10; /*!< \brief a type representing the score of a cell */
const char KImpossible = '0';/*!< \brief a type representing an empty cell */
/**
* \fn ClearScreen ()
* \brief function to clear the display.
*/
void ClearScreen () //clear the screen
{
cout << "\033[H\033[2J";
}// ClearScreen ()
/**
* \fn Color (const string & Col)
* \brief function to change the color of the display.
*
*\param Col : Colors
*/
void Color (const string& Col) //add color to text
{
cout << "\033[" << Col << "m";
}// Color ()
/**
* \fn ClearBuffer()
* \brief function to clear only the buffer.
*/
void ClearBuffer () //clear the buffer
{
cin.clear ();
cin.seekg (0, ios::end);
if (!cin.fail ())
cin.ignore (numeric_limits <streamsize>::max ());
else
cin.clear ();
}// ClearBuffer ()
/**
* \fn Pause()
* \brief function to set the program on pause.
*/
void Pause () //set the program on pause
{
cout << "Appuyez sur \"ENTRER\" pour continuer";
cin.ignore ();
cin.ignore ();
}// Pause ()
template <typename T>
/**
* \fn bool : IsOfType(const string& Str)
* \brief function to determine the type.
*\param Str : a string
*/
bool IsOfType (const string& Str)
{
istringstream iss (Str);
T tmp;
return (iss >> tmp) && (iss.eof ());
}// IsOfType ()
template <typename T>
/**
* \fn bool : IsBetween(const T& Val, const T Min, const T Max)
* \brief function to determine a value between Min and Max.
*\param Val : Value
*\param Min : Minimum
*\param Max : Maximum
*/
bool IsBetween (const T& Val, const T Min, const T Max)
{
if ((Val <= Max) && (Val >= Min))
return true;
return false;
}// IsBetween ()
template <typename T>
/**
* \fn T ConvertStr (const string& Str)
* \brief function to convert in a string type.
*\param Str : a string
*/
T ConvertStr (const string& Str)
{
istringstream iss (Str);
T tmp;
iss >> tmp;
return tmp;
}// ConvertStr ()
/**
* \fn bool : IsReadable (const string& FileName)
* \brief function to determine if a file exist.
*\param FileName : the name of the file
*/
bool IsReadable (const string& FileName) //test if a file exist
{
ifstream TestFile (FileName.c_str());
return !TestFile.fail ();
}// IsReadable ()
/**
* \fn DisplayFileContents (const string& FileName)
* \brief function to show the file on screen.
*\param FileName : the name of the file
*/
void DisplayFileContents (const string& FileName) //show a file on screen
{
if (IsReadable)
{
ifstream File (FileName.c_str ());
string Line;
while (getline (File, Line))
cout << Line << endl;
}
else
cerr << "Erreur d'ouverture du fichier '" << FileName << "'" << endl;
}// DisplayFileContents ()
/**
* \fn DisplayScore (const unsigned& Score, const unsigned& TurnScore, const unsigned& Multiplier)
* \brief function to show the score on screen.
*\param Score : score of the player
*\param TurnScore : turn of the score
*\param Multiplier : score multiplier
*/
void DisplayScore (const unsigned& Score,
const unsigned& TurnScore,
const unsigned& Multiplier) //show score on screen
{
cout << "Score : " << Score << endl;
cout << "+" << TurnScore << endl;
cout << "x" << Multiplier << endl
<< endl;
}// ShowScore ()
/**
* \fn DisplayGrid (const CMat& Grid)
* \brief function to show the matrix on screen.
*\param Grid : name of the matrix
*/
void DisplayGrid (const CMat& Grid) //show matrix on screen
{
Color (KReset);
for (unsigned i (1); i < Grid [0].size () - 1; ++i)
cout << " " << i << " ";
cout << endl;
for (unsigned i (0); i < Grid [0].size () - 2; ++i)
cout << "____";
cout << endl;
for (unsigned i (1); i < Grid.size () - 1; ++i)
{
for (unsigned j (0); j < Grid [i].size () - 2; ++j)
cout << "| ";
cout << "|" << endl;
cout << "| ";
for (unsigned j (1); j < Grid [i].size () - 1; ++j)
{
(KImpossible != Grid [i][j]) ? cout << Grid [i][j]
: cout << " ";
cout << " | ";
}
cout << setw (3) << i << endl;
for (unsigned j (0); j < Grid [i].size () - 2; ++j)
cout << "|___";
cout << "|" << endl;
}
}// DisplayGrid ()
/**
* \fn InitGrid (CMat& Grid, const unsigned& Width, const unsigned& Heigth)
* \brief function to create the square matrix.
*
*\param Grid : Matrix
*\param Width : Width of the matrix
*\param Heigth : Heigth of the matrix
*/
void InitGrid (CMat& Grid,
const unsigned& Width,
const unsigned& Heigth) //Initialize a square matrix
{
Grid.resize (Heigth);
for (unsigned i (0); i < Grid.size (); ++i)
Grid [i].resize (Width);
for (unsigned i (0); i < Grid.size (); ++i)
for (unsigned j (0); j < Grid [i].size (); ++j)
Grid [i][j] = KImpossible;
}// InitGrid ()
/**
* \fn FillGrid (CMat& Grid, const CVLine& Vect)
* \brief function to replace 'KImpossibe' values in a matrix by random characters from a vector.
*
*\param Grid : Matrix
*\param Vect : Vector
*/
void FillGrid (CMat& Grid, const CVLine& Vect) //replace 'KImpossibe' values in a matrix by random characters from a vector
{
for (unsigned i (1); i < Grid.size () - 1; ++i)
for (unsigned j (1); j < Grid [i].size () - 1; ++j)
{
if (Grid [i][j] != KImpossible) continue;
unsigned RandNb = rand () % Vect.size ();
Grid [i][j] = Vect [RandNb];
}
}// FillGrid ()
/**
* \fn CatchInput (string& Input)
* \brief function to catch a string.
*
*\param Input : Input of the player
*/
void CatchInput (string& Input) //catch a string
{
for (getline (cin, Input); cin.eof (); getline (cin, Input))
ClearBuffer ();
}// CatchInput ()
/**
* \fn bool : IsValueInGrid (const CMat& Grid, const char& Value)
* \brief function to test if a value is in a matrix.
*\param Grid : Matrix
*\param Value : Value of a cell
*/
bool IsValueInGrid (const CMat& Grid, const char& Value) //test if a value is in a matrix
{
unsigned i (1);
for ( ; i < Grid.size () - 1; )
{
unsigned j (1);
for ( ; j < Grid [i].size () - 1; )
{
if (Grid [i][j] == Value) return true;
++j;
}
++i;
}
return false;
}// IsValueInVect ()
/**
* \fn string : TakeValueInVectStr (const string& Label, const CVString& Vect)
* \brief function to catch a value in a vector of string.
*\param Label : Value
*\param Vect : Vector of string
*/
string TakeValueInVectStr (const string& Label, const CVString& Vect) //Catch a value in a vector of string
{
string Parser = "=";
for(unsigned i (0); i < Vect.size (); ++i)
{
if(Label == Vect [i].substr (0, Vect [i].find (Parser)))
return Vect [i].substr ((Vect [i].find (Parser) + Parser.length ()), Vect [i].length ());
}
}// TakeValueInVectStr ()
/**
* \fn FileToVectStr (CVString& Vect, const string& FileName)
* \brief function to translate a file into a vector of string.
*\param Vect : Vector of string
*\param FileName : the name of the file
*/
void FileToVectStr (CVString& Vect, const string& FileName) //Translate a file into a vector of string
{
ifstream File (FileName.c_str ());
if (File)
{
string Line;
while (getline (File, Line))
Vect.push_back (Line);
}
}// FileToVectStr ()
/**
* \fn CreateConfigFile ()
* \brief function to create a config file with default values.
*/
void CreateConfigFile () //create config file with default values
{
ofstream ConfigCreated;
ConfigCreated.open (KConfigFileName.c_str());
ConfigCreated << "MatrixWidth=10" << endl;
ConfigCreated << "MatrixHeigth=10" << endl;
ConfigCreated << "NbCandies=5" << endl;
ConfigCreated << "NbMaxTimes=20" << endl;
ConfigCreated.close ();
}// CreateConfig ()
/**
* \fn ChangeValueInFile (const string& Label, const string& FileName, const string& Value)
* \brief function to change the value in a file.
*\param Label : Label
*\param FileName : the name of the file
*\param Value : Value
*/
void ChangeValueInFile (const string& Label, const string& FileName, const string& Value)
{
string Parser = "=";
CVString VToGetConfig;
FileToVectStr (VToGetConfig, FileName);
for (unsigned i (0); i < VToGetConfig.size (); ++i)
{
if (Label == VToGetConfig [i].substr (0, VToGetConfig [i].find (Parser)))
VToGetConfig [i] = (VToGetConfig [i].substr (0, (VToGetConfig [i].find (Parser) + Parser.length ())) + Value);
}
ofstream Config (FileName.c_str (), ios_base::out | ios_base::trunc);
string str;
if (Config)
{
for (unsigned i (0); i < VToGetConfig.size (); ++i)
Config << VToGetConfig [i] << endl;
}
Config.close();
}
/**
* \fn CutInputStr (const string& InputStr, CPosition& Pos, char& C)
* \brief function to cut the input in a position and a direction.
*\param InputStr : input to cut
*\param Pos : position
*\param C : direction
*/
void CutInputStr (const string& InputStr, CPosition& Pos, char& C)
{
istringstream iss (InputStr);
string Str;
iss >> Str;
if (IsOfType <unsigned> (Str))
Pos.first = ConvertStr <unsigned> (Str);
iss >> Str;
if (IsOfType <unsigned> (Str))
Pos.second = ConvertStr <unsigned> (Str);
iss >> Str;
C = char (toupper (ConvertStr <char> (Str)));
}// CutInputStr ()
/**
* \fn Test_CutInputStr ()
* \brief test function @see CutInputStr.
*/
void Test_CutInputStr ()
{
string str = "11 12 z";
CPosition pos;
char c;
CutInputStr (str, pos, c);
cout << pos.first << "/" << pos.second << "/" << c << endl;
str = "9 42 a";
CutInputStr (str, pos, c);
cout << pos.first << "/" << pos.second << "/" << c << endl;
}// Test_CutInputStr ()
/**
* \fn MakeAMove (CMat& Grid, const CPosition& Pos, const char& Direction)
* \brief function to move the current number according to the character in the 3rd parameter.
*
*\param Grid : Matrix
*\param Pos : the number's position before the move
*\param Direction : the key pressed by the player
*/
void MakeAMove (CMat& Grid,
const CPosition& Pos,
const char& Direction) //swap two values depending on a direction
{
switch (Direction)
{
case 'Z':
swap (Grid [Pos.first][Pos.second],
Grid [Pos.first - 1][Pos.second]);
break;
case 'S':
swap (Grid [Pos.first][Pos.second],
Grid [Pos.first + 1][Pos.second]);
break;
case 'Q':
swap (Grid [Pos.first][Pos.second],
Grid [Pos.first][Pos.second - 1]);
break;
case 'D':
swap (Grid [Pos.first][Pos.second],
Grid [Pos.first][Pos.second + 1]);
break;
default:
cerr << "Direction Invalide" << endl;
}
}// MakeAMove ()
/**
* \fn bool AtLeastThreeInColumn (const CMat& Grid, CPosition& Pos, unsigned& HowMany)
* \brief function to test if there is at least 3 consecutive numbers in the same column.
*
*\param Grid : Matrix
*\param Pos : the position from which we find the sequence
*\param HowMany : how many consecutive numbers we have from the position Position
*/
bool AtLeastThreeInColumn (const CMat& Grid,
CPosition& Pos,
unsigned& HowMany) //find a sequence of at least three same numbers in a matrix column
{
for (unsigned i = Pos.first; i < Grid.size () - 2; ++i)
for (unsigned j = Pos.second; j < Grid [i].size () - 1; ++j)
{
if (KImpossible == Grid [i][j]) continue;
HowMany = 1;
for ( ; Grid [i + HowMany][j] == Grid [i][j]; )
++HowMany;
if (3 <= HowMany)
{
Pos.first = i;
Pos.second = j;
return true;
}
}
return false;
}// AtLeastThreeInColumn ()
/**
* \fn bool AtLeastThreeInARow (const CMat& Grid, CPosition& Pos, unsigned& HowMany)
* \brief function to test if there is at least 3 consecutive numbers in the same row.
*
*\param Grid : Matrix
*\param Pos : the position from which we find the sequence
*\param HowMany : how many consecutive numbers we have from the position Position
*/
bool AtLeastThreeInARow (const CMat& Grid,
CPosition & Pos,
unsigned& HowMany) //find a sequence of at least three same numbers in a matrix line
{
for (unsigned i = Pos.first; i < Grid.size () - 1; ++i)
for (unsigned j = Pos.second; j < Grid [i].size () - 2; ++j)
{
if (KImpossible == Grid [i][j]) continue;
HowMany = 1;
for ( ; Grid [i][j + HowMany] == Grid [i][j]; )
++HowMany;
if (3 <= HowMany)
{
Pos.first = i;
Pos.second = j;
return true;
}
}
return false;
}// AtLeastThreeInARow ()
/**
* \fn RemovalInColumn (CMat& Grid, const CPosition& Pos, const unsigned& HowMany)
* \brief function to remove a sequence of numbers in a matrix column.
*
*\param Grid : Matrix
*\param Pos : the position from which we find the sequence
*\param HowMany : how many consecutive numbers we have from the position Position
*/
void RemovalInColumn (CMat& Grid,
const CPosition& Pos,
const unsigned& HowMany) //remove a sequence of numbers in a matrix column
{
for (unsigned i (0); i < HowMany; ++i)
Grid [Pos.first + i][Pos.second] = KImpossible;
}// RemovalInColumn ()
/**
* \fn RemovalInRow (CMat& Grid, const CPosition& Pos, const unsigned& HowMany)
* \brief function to remove a sequence of numbers in a matrix line.
*
*\param Grid : Matrix
*\param Pos : the position from which we find the sequence
*\param HowMany : how many consecutive numbers we have from the position Position
*/
void RemovalInRow (CMat& Grid,
const CPosition& Pos,
const unsigned& HowMany) //remove a sequence of numbers in a matrix line
{
for (unsigned i (0); i < HowMany; ++i)
Grid [Pos.first][Pos.second + i] = KImpossible;
}// RemovalInRow ()
/**
* \fn MoveNumbersDown (CMat& Grid)
* \brief function to move all the matrix down.
*
*\param Grid : Matrix
*/
void MoveNumbersDown (CMat& Grid) //move all the matrix caracters down
{
for (unsigned i = Grid.size () - 2; i > 0; --i)
for (unsigned j = Grid.size () - 2; j > 0; --j)
{
if (Grid [j][i] != KImpossible) continue;
unsigned k = j - 1;
for ( ;0 < k && Grid [k][i] == KImpossible; )
--k;
swap (Grid [k][i], Grid [j][i]);
}
}// MoveNumbersDown ()
/**
* \fn HandleGrid (CMat& Grid, CVPair& VPosColumn, CVPair& VPosRow, CVUInt& VHowManyCol, CVUInt& VHowManyRow)
* \brief function to find then remove a sequence of numbers in a matrix line.
*
*\param Grid : Matrix
*\param VPosColumn : the position from which we find the sequence in column
*\param VPosRow : the position from which we find the sequence in row
*\param VHowManyCol : how many consecutive numbers we have from the position VPosColumn
*\param VHowManyRow : how many consecutive numbers we have from the position VPosRow
*/
void HandleGrid (CMat& Grid,
CVPair& VPosColumn,
CVPair& VPosRow,
CVUInt& VHowManyCol,
CVUInt& VHowManyRow)
{
unsigned HowMany;
CPosition Pos;
//find all sequences of at least three numbers in column
for ( ; AtLeastThreeInColumn (Grid, Pos, HowMany); )
{
VPosColumn.push_back (Pos);
VHowManyCol.push_back (HowMany);
++Pos.second;
}
//find all sequences of at least three numbers in a row
Pos.first = Pos.second = 0;
for ( ; AtLeastThreeInARow (Grid, Pos, HowMany); )
{
VPosRow.push_back (Pos);
VHowManyRow.push_back (HowMany);
++Pos.second;
}
//remove sequences
for (unsigned i (0); i < VPosColumn.size (); ++i)
RemovalInColumn (Grid, VPosColumn [i], VHowManyCol [i]);
for (unsigned i (0); i < VPosRow.size (); ++i)
RemovalInRow (Grid, VPosRow [i], VHowManyRow [i]);
}// HandleGrid ()
/**
* \fn PlayScoreMod ()
* \brief function to play score mod.
*
*/
void PlayScoreMod () //play score mod
{
//init variables with config file
CVString VConfig;
FileToVectStr (VConfig, KConfigFileName);
const unsigned MatHeigth = ConvertStr <unsigned> (TakeValueInVectStr ("MatrixHeigth", VConfig)) + 2;
const unsigned MatWidth = ConvertStr <unsigned> (TakeValueInVectStr ("MatrixWidth", VConfig)) + 2;
const unsigned NbCandies = ConvertStr <unsigned> (TakeValueInVectStr ("NbCandies", VConfig));
unsigned NbMaxTimes = ConvertStr <unsigned> (TakeValueInVectStr ("NbMaxTimes", VConfig));
unsigned TotalScore (0);
unsigned TurnScore (0);
unsigned Multiplier (0);
//init VCandies
CVLine VCandies (NbCandies);
for (unsigned i = (0); i < VCandies.size (); ++i)
VCandies [i] = char ('0' + i + 1);
//init board
CMat Matrix;
InitGrid (Matrix, MatWidth, MatHeigth);
for ( ; IsValueInGrid (Matrix, KImpossible); )
{
CVPair VPosCol, VPosRow;
CVUInt VHowManyCol, VHowManyRow;
FillGrid (Matrix, VCandies);
HandleGrid (Matrix, VPosCol, VPosRow, VHowManyCol, VHowManyRow);
MoveNumbersDown (Matrix);
}
//start game
for ( ; 0 != NbMaxTimes; )
{
//display board
ClearScreen ();
DisplayScore (TotalScore, TurnScore, Multiplier);
DisplayGrid (Matrix);
cout << "Nombre de coups restant : " << NbMaxTimes << endl << endl;
DisplayFileContents (KHelpFileName);
cout << endl << "Entrez une commande : ";
//input interpreter
string Input;
CMat M = Matrix;
for ( ; M == Matrix; )
{
CPosition InputPos;
char InputDir;
CatchInput (Input);
CutInputStr (Input, InputPos, InputDir);
if (IsBetween (InputPos.first, 1u, MatHeigth - 2) && IsBetween (InputPos.second, 1u, MatWidth - 2))
MakeAMove (Matrix, InputPos, InputDir);
else
cout << "Commande invalide" << endl;
if (IsValueInGrid (Matrix, KImpossible))
MakeAMove (Matrix, InputPos, InputDir);
}
//manipulate matrix and increase score
TurnScore = Multiplier = 0;
unsigned Score;
do
{
Score = TurnScore;
CVPair VPosCol, VPosRow;
CVUInt VHowManyCol, VHowManyRow;
HandleGrid (Matrix, VPosCol, VPosRow, VHowManyCol, VHowManyRow);
MoveNumbersDown (Matrix);
FillGrid (Matrix, VCandies);
for (unsigned i : VHowManyCol)
TurnScore += i * KSquareValue;
for (unsigned i : VHowManyRow)
TurnScore += i * KSquareValue;
Multiplier += VHowManyCol.size () + VHowManyRow.size ();
}while (Score != TurnScore);
TotalScore += TurnScore * Multiplier;
--NbMaxTimes;
}
//show final score
ClearScreen ();
cout << "Votre score : " << TotalScore << endl;
Pause ();
}// PlayScoreMode ()
/**
* \fn ChangeSettings ()
* \brief function to change settings of the game.
*
*/
void ChangeSettings ()
{
ClearScreen ();
string Input;
for ( ; Input != "Q"; )
{
CVString VConfig;
FileToVectStr (VConfig, KConfigFileName);
cout << "hauteur" << " = " << TakeValueInVectStr ("MatrixWidth", VConfig) << endl;
cout << "largeur" << " = " << TakeValueInVectStr ("MatrixHeigth", VConfig) << endl;
cout << "nombres" << " = " << TakeValueInVectStr ("NbCandies", VConfig) << endl << endl;
cout << "Entrez le nom du paramètre suivi de la valeur que vous souhaitez lui attribuer." << endl
<< "Tapez 'Q' pour quitter." << endl
<< "ex: \"hauteur 15\"" << endl << endl;
CatchInput (Input);
istringstream iss (Input);
string tmp, Value, Label;
iss >> tmp;
iss >> Value;
unsigned Min, Max;
if (tmp == "hauteur")
{
Label = "MatrixWidth";
Min = 5;
Max = 15;
}
else if (tmp == "largeur")
{
Label = "MatrixHeigth";
Min = 5;
Max = 20;
}
else if (tmp == "nombres")
{
Label = "NbCandies";
Min = 3;
Max = 7;
}
else
cout << "Commande invalide" << endl;
if (IsOfType <unsigned> (Value) && IsBetween (ConvertStr <unsigned> (Value), Min, Max))
ChangeValueInFile (Label, KConfigFileName, Value);
else
cout << "Valeur invalide" << endl;
}
ClearScreen ();
}
/**
* \fn MainMenu ()
* \brief function used to display the menu.
*
*/
void MainMenu ()
{
string Str;
for ( ; Str != "4"; )
{
//display menu
ClearScreen ();
DisplayFileContents (KHeaderFileName);
DisplayFileContents (KMenuFileName);
CatchInput (Str);
switch (ConvertStr <char> (Str))
{
case '1':
PlayScoreMod (); //play score mod
break;
case '2':
DisplayFileContents (KRulesFileName); //display rules
Pause ();
break;
case '3':
ChangeSettings (); //change settings
break;
case '4':
ClearScreen ();
cout << "developped by" << endl;
DisplayFileContents (KCreditsFileName); //display credits
Pause ();
break;
default :
cerr << "Champ invalide" << endl;
}
}
}// MainMenu ()
}// namespace
/**
* \fn int main()
* \brief Program main menu.
*
*/
int main ()
{
srand (time (NULL));
if (!nsNumberCrush::IsReadable (nsNumberCrush::KConfigFileName))
nsNumberCrush::CreateConfigFile ();
nsNumberCrush::MainMenu ();
return EXIT_SUCESS;
}// main ()
|
/***************************************************************************
Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD
FileName: HTTPRequest.h
Description: A object to receive, parse and respond to client using HTTP protocol.
Comment: copy from Darwin Streaming Server 5.5.5
Author: taoyunxing@dadimedia.com
Version: v1.0.0.1
CreateDate: 2010-08-16
LastUpdate: 2010-08-16
****************************************************************************/
#ifndef __HTTPREQUEST_H__
#define __HTTPREQUEST_H__
#include "HTTPProtocol.h"
#include "StrPtrLen.h"
#include "StringParser.h"
#include "ResizeableStringFormatter.h"
#include "OSHeaders.h"
#include "QTSS.h"
class HTTPRequest
{
public:
// Constructor
HTTPRequest(StrPtrLen* serverHeader, StrPtrLen* requestPtr);
// This cosntructor is used when the request has been parsed and thrown away
// and the response has to be created
HTTPRequest(StrPtrLen* serverHeader);
// Destructor
virtual ~HTTPRequest();
// Should be called before accessing anything in the request header
// Calls ParseRequestLine and ParseHeaders
QTSS_Error Parse();
// Basic access methods for the HTTP method, the absolute request URI,
// the host name from URI, the relative request URI, the request file path,
// the HTTP version, the Status code, the keep-alive tag.
HTTPMethod GetMethod(){ return fMethod; }
StrPtrLen* GetRequestLine(){ return &fRequestLine; }
StrPtrLen* GetRequestAbsoluteURI(){ return &fAbsoluteURI; }
StrPtrLen* GetSchemefromAbsoluteURI(){ return &fAbsoluteURIScheme; }
StrPtrLen* GetHostfromAbsoluteURI(){ return &fHostHeader; }
StrPtrLen* GetRequestRelativeURI(){ return &fRelativeURI; }
char* GetRequestPath(){ return fRequestPath; }
HTTPVersion GetVersion(){ return fVersion; }
HTTPStatusCode GetStatusCode(){ return fStatusCode; }
Bool16 IsRequestKeepAlive(){ return fRequestKeepAlive; }
// If header field exists in the request, it will be found in the dictionary
// and the value returned. Otherwise, NULL is returned.
StrPtrLen* GetHeaderValue(HTTPHeader inHeader);
// Creates a header with the corresponding version and status code
void CreateResponseHeader(HTTPVersion version, HTTPStatusCode statusCode);
// To append response header fields as appropriate
void AppendResponseHeader(HTTPHeader inHeader, StrPtrLen* inValue);
void AppendDateAndExpiresFields();
void AppendDateField();
void AppendConnectionCloseHeader();
void AppendConnectionKeepAliveHeader();
void AppendContentLengthHeader(UInt64 length_64bit);
void AppendContentLengthHeader(UInt32 length_32bit);
// Returns the completed response header by appending CRLF to the end of the header fields buffer
StrPtrLen* GetCompleteResponseHeader();
// Parse if-modified-since header
time_t ParseIfModSinceHeader();
private:
enum { kMinHeaderSizeInBytes = 512 };
// Gets the method, version and calls ParseURI
QTSS_Error ParseRequestLine(StringParser* parser);
// Parses the URI to get absolute and relative URIs, the host name and the file path
QTSS_Error ParseURI(StringParser* parser);
// Parses the headers and adds them into a dictionary
// Also calls SetKeepAlive with the Connection header field's value if it exists
QTSS_Error ParseHeaders(StringParser* parser);
// Sets fRequestKeepAlive
void SetKeepAlive(StrPtrLen* keepAliveValue);
// Used in initialize and CreateResponseHeader
void PutStatusLine(StringFormatter* putStream, HTTPStatusCode status, HTTPVersion version);
// For writing into the premade headers
StrPtrLen* GetServerHeader(){ return &fSvrHeader; }
// Complete request and response headers
StrPtrLen fRequestHeader;
ResizeableStringFormatter* fResponseFormatter;
StrPtrLen* fResponseHeader;
// Private members
HTTPMethod fMethod;
HTTPVersion fVersion;
HTTPStatusCode fStatusCode;
StrPtrLen fRequestLine;
// For the URI (fAbsoluteURI and fRelativeURI are the same if the URI is of the form "/path")
// If it is an absolute URI, these fields will be filled in "http://foo.bar.com/path"
// => fAbsoluteURIScheme = "http", fHostHeader = "foo.bar.com", fRequestPath = "path"
StrPtrLen fAbsoluteURI; // If it is of the form "http://foo.bar.com/path"
StrPtrLen fRelativeURI; // If it is of the form "/path"
StrPtrLen fAbsoluteURIScheme;
StrPtrLen fHostHeader; // If the full url is given in the request line
char* fRequestPath; // Also contains the query string
Bool16 fRequestKeepAlive; // Keep-alive information in the client request
StrPtrLen fFieldValues[httpNumHeaders]; // Array of header field values parsed from the request
StrPtrLen fSvrHeader; // Server header set up at initialization
static StrPtrLen sColonSpace;
static UInt8 sURLStopConditions[];
};
#endif // __HTTPREQUEST_H__
|
#ifndef CPP_LINQ_TEST_UTILS_H
#define CPP_LINQ_TEST_UTILS_H
#include "CppLinq.h"
template<typename R, typename T, unsigned N, typename F>
void IsEqualArray(R dst, T(&ans)[N], F func)
{
for (size_t i = 0; i < N; ++i)
{
EXPECT_EQ(func(ans[i]), func(dst.NextObject()));
}
EXPECT_THROW(dst.NextObject(), CppLinq::EnumeratorEndException);
}
template<typename R, typename T, unsigned N>
void IsEqualArray(R dst, T(&ans)[N])
{
for (size_t i = 0; i < N; ++i)
{
EXPECT_EQ(ans[i], dst.NextObject());
}
EXPECT_THROW(dst.NextObject(), CppLinq::EnumeratorEndException);
}
#endif
|
#include <omp.h>
#include <assert.h>
#include <string.h>
#include "matrix.h"
#include "memory.h"
void fun3d::Matrix::ilu_YousefSaad()
{
memset(iw, 0, nrows * sizeof(unsigned int));
for(unsigned int i = 0; i < nrows; i++)
{
const unsigned int j0 = A->i[i];
const unsigned int j1 = A->i[i+1];
for(unsigned int j = j0; j < j1; j++) iw[A->j[j]] = j;
for(unsigned int j = j0; j < j1; j++)
{
const unsigned int k = A->j[j];
if(k < i)
{
double T[bs2];
dgemm(A->a + bidx2(j), A->a + bidx2(A->d[k]), T);
memcpy(A->a + bidx2(j), T, bs2 * sizeof(double));
for(unsigned int jj = A->d[k] + 1; jj < A->i[k+1]; jj++)
{
const unsigned int jw = iw[A->j[jj]];
if(jw != 0)
{
double TT[bs2];
dgemm(T, A->a + bidx2(jj), TT);
axpy2(-1.f, TT, A->a + bidx2(jw));
}
}
}
else break;
}
inv(A->a + bidx2(A->d[i]));
for(unsigned int j = j0; j < j1; j++) iw[A->j[j]] = 0;
}
}
void fun3d::Matrix::ilu_Edmond()
{
unsigned int sweep = 0;
do {
#pragma omp parallel for
for(unsigned int i = 0; i < nrows; i++)
{
const unsigned int jstart = A->i[i];
const unsigned int jend = A->i[i+1];
for(unsigned int j = jstart; j < jend; j++)
{
const unsigned int k = A->j[j];
unsigned int il = L->i[i];
unsigned int iu = Ut->i[k];
double a[bs2];
memcpy(a, A->a + bidx2(j), bs2 * sizeof(double));
double d[bs2];
memset(d, 0, bs2 * sizeof(double));
while(il < L->i[i+1] && iu < Ut->i[k+1])
{
const unsigned int jl = L->j[il];
const unsigned int ju = Ut->j[iu];
if(jl == ju)
{
dgemm(L->a + bidx2(il), Ut->a + bidx2(iu), d);
axpy2(-1.f, d, a);
}
if(jl <= ju) il++;
if(jl >= ju) iu++;
}
axpy2(1.f, d, a);
if(i > k)
{
double T[bs2];
inv(Ut->a + bidx2(Ut->i[k+1]-1), T);
dgemm(a, T, L->a + bidx2(il-1));
}
else memcpy(Ut->a + bidx2(iu-1), a, bs2 * sizeof(double));
}
}
} while(++sweep < ilu_sweeps);
#if 0
#pragma omp parallel for
for(unsigned int i = 0; i < nrows; i++)
{
const unsigned int jstart = Ut->i[i];
const unsigned int jend = Ut->i[i+1];
for(unsigned int j = jstart; j < jend; j++)
memcpy(U->a + bidx2(U_index[j]), Ut->a + bidx2(j), bs2 * sizeof(double));
inv(U->a + bidx2(U->d[i]));
}
#else
#pragma omp parallel for
for(unsigned int i = 0; i < nrows; i++)
{
const unsigned int jstart = A->i[i];
const unsigned int jend = A->i[i+1];
unsigned int idxL = L->i[i];
for(unsigned int j = jstart; j < jend; j++)
{
if(A->j[j] < i)
{
memcpy(A->a + bidx2(j), L->a + bidx2(idxL++), bs2 * sizeof(double));
}
if(A->j[j] >= i)
{
memcpy(A->a + bidx2(j), Ut->a + bidx2(Ut_index[j]), bs2 * sizeof(double));
}
}
inv(A->a + bidx2(A->d[i]));
}
#endif
}
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef IGLOBALCONTROLUNIT_H_
#define IGLOBALCONTROLUNIT_H_
#include "Coord.h"
#include <map>
#define GCU_IGCU_MAP std::map<int, IGlobalControlUnit*>
class IGlobalControlUnit {
public:
IGlobalControlUnit(){
}
virtual ~IGlobalControlUnit() {
}
public:
inline bool operator< (IGlobalControlUnit& rhs){
return this->getCurrentPostion().x<rhs.getCurrentPostion().x;
}
public:
virtual int getAddr() = 0;
virtual void setCurrentPostion(Coord pos) = 0;
virtual Coord getCurrentPostion() = 0;
virtual void setCurrentSpeed(Coord speed) = 0;
virtual Coord getCurrentSpeed() = 0;
virtual void setSpeed(Coord speed) = 0;
virtual Coord getSpeed() = 0;
virtual void handleMsgFromNetwLayer(cMessage* msg) = 0;
virtual void connectToGCU(IGlobalControlUnit* gcu) = 0;
virtual void disconnectFromGCU(IGlobalControlUnit* gcu) = 0;
virtual void disconnectAll() = 0;
virtual void connectToAP(int apid) = 0;
virtual void disconnectFromAP(int apid) = 0;
virtual bool isAp() = 0;
virtual void isAp(bool isAp) = 0;
virtual bool isConnectedTo(IGlobalControlUnit* gcu) = 0;
virtual bool isInRange(IGlobalControlUnit* gcu) = 0;
virtual double getDistFrom(IGlobalControlUnit* gcu) = 0;
virtual bool hasAp() = 0;
virtual int getApid() = 0;
virtual void setApid(int apid) = 0;
virtual GCU_IGCU_MAP* getNeighbors() = 0;
virtual double getReceivePower() const = 0;
virtual void setReceivePower(double receivePower) = 0;
virtual double getSendPower() const = 0;
virtual void setSendPower(double sendPower) = 0;
};
#endif /* IGLOBALCONTROLUNIT_H_ */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.