text
stringlengths 8
6.88M
|
|---|
#include <cinttypes>
#include <cstdio>
#include <iostream>
#define MAX 93
uint64_t fib(uint64_t n)
{
static uint64_t f1 = 1, f2 = 1;
if (n <= 2)
return f2;
if (n >= MAX)
{
std::cerr << "Cannot computer for n > 93";
return 0;
}
uint64_t temp = f2;
f2 += f1;
f1 = temp;
return f2;
}
/** Main function */
int main()
{
// Main Function
for (uint64_t i = 1; i < 93; i++)
{
std::cout << i << " th fibonacci number is " << fib(i) << std::endl;
}
return 0;
}
|
#include "systemc.h"
#include "tester.h"
#include <iostream>
#include <fstream>
void tester::tester_func(){
unsigned int t_data1,t_data2,t_control;
while(1){
if (infile >> t_data1 >> t_data2 >> t_control)
{
out1.write(t_data1);
out2.write(t_data2);
ctrl.write(t_control);
wait();
}
else
break;
}
sc_stop();
}
|
//
// KSymtable.hpp <Keepi>
//
// Made by Julien Fortin
// contact <julien.fortin.it@gmail.com>
//
#ifndef __KSYMTABLE_HPP__
#define __KSYMTABLE_HPP__
#include <map>
#include <iostream>
#include "KObject.hpp"
class KSymtable
{
private:
std::map<std::string, KObject*> __symtable;
KSymtable(const KSymtable&);
KSymtable operator=(const KSymtable&);
protected:
public:
KSymtable();
~KSymtable();
void print() const;
void add(const std::string&, KObject* value);
/*
template <typename T>
T resolveIdentifier(const char* name) const
{
std::string key = name;
KeepiSymMap::const_iterator it = this->_symtable.find(key);
if (it != this->_symtable.cend())
{
try
{
KNumber<T>* number = reinterpret_cast<KNumber<T>*>(it->second);
if (number)
return number->getValue();
else
key = "\"" + key + "\": null pointer";
}
catch(std::exception const &e)
{
std::cerr << e.what() << std::endl;
}
}
throw KUndefinedIdentifierException(key);
};
*/
};
#endif
|
/*
===========================================================================
Copyright (C) 2017 waYne (CAM)
===========================================================================
*/
#pragma once
#ifndef ELYSIUM_CORE_DATA_IDBCOMMAND
#define ELYSIUM_CORE_DATA_IDBCOMMAND
#ifndef ELYSIUM_CORE_OBJECT
#include "../Elysium.Core/Object.hpp"
#endif
#ifndef ELYSIUM_CORE_DATA_ISOLATIONLEVEL
#include "IsolationLevel.hpp"
#endif
#ifndef _XSTRING_
#include <xstring>
#endif
#ifndef ELYSIUM_CORE_DATA_COMMANDTYPE
#include "CommandType.hpp"
#endif
#ifndef ELYSIUM_CORE_DATA_COMMANDBEHAVIOUR
#include "CommandBehavior.hpp"
#endif
#ifndef ELYSIUM_CORE_DATA_IDBCONNECTION
#include "IDbConnection.hpp"
#endif
#ifndef ELYSIUM_CORE_DATA_IDBTRANSACTION
#include "IDbTransaction.hpp"
#endif
#ifndef ELYSIUM_CORE_DATA_IDATAREADER
#include "IDataReader.hpp"
#endif
namespace Elysium
{
namespace Core
{
namespace Data
{
class EXPORT IDbCommand : public Object
{
public:
/// <summary>
/// Destroy the object using the virtual destructor
/// </summary>
virtual ~IDbCommand() {}
virtual const std::wstring GetCommandText() const = 0;
virtual const int& GetConnectionTimeout() const = 0;
virtual const CommandType& GetCommandType() const = 0;
virtual const IDbConnection* GetConnection() const = 0;
//virtual const IDataParameterCollection* GetParameters() const = 0;
virtual const IDbTransaction* GetTransaction() const = 0;
//virtual const UpdateRowSource* GetUpdateRowSource() const = 0;
virtual void SetCommandText(std::wstring CommandText) = 0;
virtual void SetConnectionTimeout(int Timeout) = 0;
virtual void SetCommandType(CommandType Type) = 0;
//virtual void SetConnection(IDbConnection* Connection) = 0;
//virtual void SetTransaction(IDbTransaction* Transaction) = 0;
//virtual void SetUpdateRowSource(UpdateRowSource* UpdateRowSource) = 0;
//virtual void Cancel() = 0;
//virtual IDbDataParameter CreateParameter() = 0;
virtual int ExecuteNonQuery() = 0;
virtual void ExecuteReader(IDataReader* Reader) = 0;
//virtual IDataReader ExecuteReader(CommandBehaviour Behaviour) = 0;
//virtual object ExecuteScalar() = 0;
//virtual void Prepare() = 0;
};
}
}
}
#endif
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef XPNUMERICEXPR_H
#define XPNUMERICEXPR_H
#include "modules/xpath/src/xpexpr.h"
/** Implements the *, /, %, + and - operators. */
class XPath_NumericExpression
: public XPath_NumberExpression
{
private:
XPath_NumberExpression *lhs, *rhs;
XPath_ExpressionType type;
unsigned state_index, lhs_number_index;
XPath_NumericExpression (XPath_Parser *parser, XPath_NumberExpression *lhs, XPath_NumberExpression *rhs, XPath_ExpressionType type);
public:
static XPath_NumberExpression *MakeL (XPath_Parser *parser, XPath_Expression *lhs, XPath_Expression *rhs, XPath_ExpressionType type);
virtual ~XPath_NumericExpression ();
virtual unsigned GetResultType ();
virtual unsigned GetExpressionFlags ();
virtual double EvaluateToNumberL (XPath_Context *context, BOOL initial);
};
/** Implements the ! operator. */
class XPath_NegateExpression
: public XPath_NumberExpression
{
private:
XPath_NumberExpression *base;
XPath_NegateExpression (XPath_Parser *parser, XPath_NumberExpression *base);
public:
static XPath_NumberExpression *MakeL (XPath_Parser *parser, XPath_Expression *base);
virtual ~XPath_NegateExpression ();
virtual unsigned GetResultType ();
virtual unsigned GetExpressionFlags ();
virtual double EvaluateToNumberL (XPath_Context *context, BOOL initial);
};
#endif // XPNUMERICEXPR_H
|
// CryptWindows.h: interface for the CCryptWindows class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CRYPTWINDOWS_H__6BECC471_57F7_11D4_B7F5_0050DA34A2BA__INCLUDED_)
#define AFX_CRYPTWINDOWS_H__6BECC471_57F7_11D4_B7F5_0050DA34A2BA__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Crypt.h"
class CCryptWindows
{
public:
CCryptWindows();
virtual ~CCryptWindows();
BOOL Encrypt(BYTE*& pByte, DWORD& dwSize, LPCTSTR lpszPassword, const CCrypt::Algorithm& eAlgorithm);
BOOL Decrypt(BYTE*& pByte, DWORD& dwSize, LPCTSTR lpszPassword, const CCrypt::Algorithm& eAlgorithm);
protected:
BOOL Init();
BOOL m_bInit;
};
#endif // !defined(AFX_CRYPTWINDOWS_H__6BECC471_57F7_11D4_B7F5_0050DA34A2BA__INCLUDED_)
|
// Q 22
#include "stdio.h"
#include "conio.h"
void main(void)
{
int a,b,fact,n;
clrscr();
printf("Put the value = ");
scanf("%d",&a);
fact=1;
for(b=a; b>=1; b--)
{
fact=fact*b;
}
printf("%d is %d\n",a,fact);
getch();
}
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "P2pConnectionProxy.h"
#include "LevinProtocol.h"
#include "P2pContext.h"
#include "P2pNode.h"
#include <System/InterruptedException.h>
using namespace platform_system;
namespace cn {
P2pConnectionProxy::P2pConnectionProxy(P2pContextOwner&& ctx, IP2pNodeInternal& node)
: m_contextOwner(std::move(ctx)), m_context(m_contextOwner.get()), m_node(node) {}
P2pConnectionProxy::~P2pConnectionProxy() {
m_context.stop();
}
bool P2pConnectionProxy::processIncomingHandshake() {
LevinProtocol::Command cmd;
if (!m_context.readCommand(cmd)) {
throw std::runtime_error("Connection unexpectedly closed");
}
if (cmd.command == COMMAND_HANDSHAKE::ID) {
handleHandshakeRequest(cmd);
return true;
}
if (cmd.command == COMMAND_PING::ID) {
COMMAND_PING::response resp{ PING_OK_RESPONSE_STATUS_TEXT, m_node.getPeerId() };
m_context.writeMessage(makeReply(COMMAND_PING::ID, LevinProtocol::encode(resp), LEVIN_PROTOCOL_RETCODE_SUCCESS));
return false;
}
throw std::runtime_error("Unexpected command: " + std::to_string(cmd.command));
}
void P2pConnectionProxy::read(P2pMessage& message) {
if (!m_readQueue.empty()) {
message = std::move(m_readQueue.front());
m_readQueue.pop();
return;
}
for (;;) {
LevinProtocol::Command cmd;
if (!m_context.readCommand(cmd)) {
throw InterruptedException();
}
message.type = cmd.command;
if (cmd.command == COMMAND_HANDSHAKE::ID) {
handleHandshakeResponse(cmd, message);
break;
} else if (cmd.command == COMMAND_TIMED_SYNC::ID) {
handleTimedSync(cmd);
} else {
message.data = std::move(cmd.buf);
break;
}
}
}
void P2pConnectionProxy::write(const P2pMessage &message) {
if (message.type == COMMAND_HANDSHAKE::ID) {
writeHandshake(message);
} else {
m_context.writeMessage(P2pContext::Message(P2pMessage(message), P2pContext::Message::NOTIFY));
}
}
void P2pConnectionProxy::ban() {
// not implemented
}
void P2pConnectionProxy::stop() {
m_context.stop();
}
void P2pConnectionProxy::writeHandshake(const P2pMessage &message) {
CORE_SYNC_DATA coreSync;
LevinProtocol::decode(message.data, coreSync);
if (m_context.isIncoming()) {
// response
COMMAND_HANDSHAKE::response res;
res.node_data = m_node.getNodeData();
res.payload_data = coreSync;
res.local_peerlist = m_node.getLocalPeerList();
m_context.writeMessage(makeReply(COMMAND_HANDSHAKE::ID, LevinProtocol::encode(res), LEVIN_PROTOCOL_RETCODE_SUCCESS));
m_node.tryPing(m_context);
} else {
// request
COMMAND_HANDSHAKE::request req;
req.node_data = m_node.getNodeData();
req.payload_data = coreSync;
m_context.writeMessage(makeRequest(COMMAND_HANDSHAKE::ID, LevinProtocol::encode(req)));
}
}
void P2pConnectionProxy::handleHandshakeRequest(const LevinProtocol::Command& cmd) {
COMMAND_HANDSHAKE::request req;
if (!LevinProtocol::decode<COMMAND_HANDSHAKE::request>(cmd.buf, req)) {
throw std::runtime_error("Failed to decode COMMAND_HANDSHAKE request");
}
m_node.handleNodeData(req.node_data, m_context);
m_readQueue.push(P2pMessage{
cmd.command, LevinProtocol::encode(req.payload_data) }); // enqueue payload info
}
void P2pConnectionProxy::handleHandshakeResponse(const LevinProtocol::Command& cmd, P2pMessage& message) {
if (m_context.isIncoming()) {
// handshake should be already received by P2pNode
throw std::runtime_error("Unexpected COMMAND_HANDSHAKE from incoming connection");
}
COMMAND_HANDSHAKE::response res;
if (!LevinProtocol::decode(cmd.buf, res)) {
throw std::runtime_error("Invalid handshake message format");
}
m_node.handleNodeData(res.node_data, m_context);
m_node.handleRemotePeerList(res.local_peerlist, res.node_data.local_time);
message.data = LevinProtocol::encode(res.payload_data);
}
void P2pConnectionProxy::handleTimedSync(const LevinProtocol::Command& cmd) {
if (cmd.isResponse) {
COMMAND_TIMED_SYNC::response res;
LevinProtocol::decode(cmd.buf, res);
m_node.handleRemotePeerList(res.local_peerlist, res.local_time);
} else {
// we ignore information from the request
// COMMAND_TIMED_SYNC::request req;
// LevinProtocol::decode(cmd.buf, req);
COMMAND_TIMED_SYNC::response res;
res.local_time = time(nullptr);
res.local_peerlist = m_node.getLocalPeerList();
res.payload_data = m_node.getGenesisPayload();
m_context.writeMessage(makeReply(COMMAND_TIMED_SYNC::ID, LevinProtocol::encode(res), LEVIN_PROTOCOL_RETCODE_SUCCESS));
}
}
}
|
// Scintilla source code edit control
/** @file LexVB.cxx
** Lexer for Visual Basic (include VB6) and VBScript.
** Changes by Zufu Liu <zufuliu@gmail.com> 2011/08
** - Updated ColouriseVBDoc, updated number format checking, added preprocessor handling
** - rewrited FoldVBDoc fucntion, fixed folding bugs, added some properties.
**/
// Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
using namespace Scintilla;
// Internal state, highlighted as number
#define SCE_B_FILENUMBER SCE_B_DEFAULT+100
#define LexCharAt(pos) styler.SafeGetCharAt(pos, '\0')
static inline bool IsTypeCharacter(int ch) {
return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$';
}
static bool IsVBNumber(int ch, int chPrev) {
return (ch < 0x80) && (isxdigit(ch)
|| (ch == '.' && chPrev != '.')
|| ((ch == '+' || ch == '_') && (chPrev == 'E' || chPrev == 'e'))
|| ((ch == 'S' || ch == 'I' || ch == 'L' || ch == 's' || ch == 'i' || ch == 'l')
&& (chPrev < 0x80) && (isdigit(chPrev) || chPrev == 'U' || chPrev == 'u'))
|| ((ch == 'R' || ch == 'r' || ch == '%' || ch == '@' || ch == '!' || ch == '#')
&& (chPrev < 0x80) && isdigit(chPrev))
|| (ch == '&' && (chPrev < 0x80) && isxdigit(chPrev)));
}
/*static const char * const vbWordListDesc[] = {
"Keyword",
"Type keyword"
"Unused keyword",
"Preprocessor",
"Attribute",
"Constant"
0
};*/
static inline bool IsSpaceEquiv(int state) {
// including SCE_B_DEFAULT, SCE_B_COMMENT
return (state <= SCE_B_COMMENT);
}
static void ColouriseVBDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList keywordLists, Accessor &styler, bool vbScriptSyntax) {
const WordList &keywords = *keywordLists[0];
const WordList &keywords2 = *keywordLists[1];
const WordList &keywords3 = *keywordLists[2];
const WordList &keywords4 = *keywordLists[3];
const WordList &keywords5 = *keywordLists[4];
const WordList &keywords6 = *keywordLists[5];
int fileNbDigits = 0;
int visibleChars = 0;
bool isIfThenPreprocessor = false;
bool isEndPreprocessor = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart) {
isIfThenPreprocessor = false;
isEndPreprocessor = false;
visibleChars = 0;
}
if (sc.state == SCE_B_OPERATOR) {
sc.SetState(SCE_B_DEFAULT);
} else if (sc.state == SCE_B_IDENTIFIER) {
_label_identifier:
if (!(iswordstart(sc.ch))) {
// In Basic (except VBScript), a variable name or a function name
// can end with a special character indicating the type of the value
// held or returned.
bool skipType = false;
if (!vbScriptSyntax && IsTypeCharacter(sc.ch)) {
sc.Forward(); // Skip it
skipType = true;
}
if (sc.ch == ']') { // bracketed [keyword] identifier
sc.Forward();
}
char s[128];
Sci_Position len = sc.GetCurrentLowered(s, sizeof(s));
if (skipType) {
s[len - 1] = '\0';
}
if (visibleChars == len && LexGetNextChar(sc.currentPos, styler) == ':') {
sc.ChangeState(SCE_B_LABEL);
sc.SetState(SCE_B_DEFAULT);
} else
if (strcmp(s, "rem") == 0) {
sc.ChangeState(SCE_B_COMMENT);
} else {
if ((isIfThenPreprocessor && strcmp(s, "then") == 0) || (isEndPreprocessor
&& (strcmp(s, "if") == 0 || strcmp(s, "region") == 0 || strcmp(s, "externalsource") == 0))) {
sc.ChangeState(SCE_B_PREPROCESSOR);
} else if (keywords.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD3);
} else if (!vbScriptSyntax && s[0] == '#' && keywords4.InList(&s[1])) {
sc.ChangeState(SCE_B_PREPROCESSOR);
isIfThenPreprocessor = strcmp(s, "#if") == 0 || strcmp(s, "#elseif") == 0;
isEndPreprocessor = strcmp(s, "#end") == 0;
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD4);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_B_CONSTANT);
}
sc.SetState(SCE_B_DEFAULT);
}
}
} else if (sc.state == SCE_B_NUMBER) {
if (!IsVBNumber(sc.ch, sc.chPrev)) {
sc.SetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_STRING) {
// VB doubles quotes to preserve them, so just end this string
// state now as a following quote will start again
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
if (tolower(sc.chNext) == 'c' || sc.chNext == '$') {
sc.Forward();
}
sc.ForwardSetState(SCE_B_DEFAULT);
}
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_B_STRINGEOL);
sc.ForwardSetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_COMMENT) {
if (sc.atLineStart) {
sc.SetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_FILENUMBER) {
if (IsADigit(sc.ch)) {
fileNbDigits++;
if (fileNbDigits > 3) {
sc.ChangeState(SCE_B_DATE);
}
} else if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ',') {
// Regular uses: Close #1; Put #1, ...; Get #1, ... etc.
// Too bad if date is format #27, Oct, 2003# or something like that...
// Use regular number state
sc.ChangeState(SCE_B_NUMBER);
sc.SetState(SCE_B_DEFAULT);
} else if (sc.ch == '#') {
sc.ChangeState(SCE_B_DATE);
sc.ForwardSetState(SCE_B_DEFAULT);
} else {
sc.ChangeState(SCE_B_DATE);
}
if (sc.state != SCE_B_FILENUMBER) {
fileNbDigits = 0;
}
} else if (sc.state == SCE_B_DATE) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_B_STRINGEOL);
sc.ForwardSetState(SCE_B_DEFAULT);
} else if (sc.ch == '#') {
sc.ForwardSetState(SCE_B_DEFAULT);
}
}
if (sc.state == SCE_B_DEFAULT) {
if (sc.ch == '\'') {
sc.SetState(SCE_B_COMMENT);
} else if (sc.ch == '\"') {
sc.SetState(SCE_B_STRING);
} else if (sc.ch == '#') {
char chNUp = static_cast<char>(MakeUpperCase(sc.chNext));
if (chNUp == 'E' || chNUp == 'I' || chNUp == 'R' || chNUp == 'C')
sc.SetState(SCE_B_IDENTIFIER);
else
sc.SetState(SCE_B_FILENUMBER);
} else if (sc.ch == '&' && (sc.chNext == 'h' || sc.chNext == 'H')) { // Hexadecimal number
sc.SetState(SCE_B_NUMBER);
sc.Forward();
} else if (sc.ch == '&' && (sc.chNext == 'o' || sc.chNext == 'O')) { // Octal number
sc.SetState(SCE_B_NUMBER);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_B_NUMBER);
} else if (sc.ch == '_' && isspace(sc.chNext)) {
sc.SetState(SCE_B_OPERATOR);
} else if (iswordstart(sc.ch) || sc.ch == '[') { // bracketed [keyword] identifier
sc.SetState(SCE_B_IDENTIFIER);
} else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\')) { // Integer division
sc.SetState(SCE_B_OPERATOR);
}
}
if (!(isspacechar(sc.ch) || IsSpaceEquiv(sc.state))) {
visibleChars++;
}
}
if (sc.state == SCE_B_IDENTIFIER)
goto _label_identifier;
sc.Complete();
}
static bool VBLineStartsWith(Sci_Position line, Accessor &styler, const char* word) {
Sci_Position pos = LexLineSkipSpaceTab(line, styler);
return (styler.StyleAt(pos) == SCE_B_KEYWORD) && (LexMatchIgnoreCase(pos, styler, word));
}
static bool VBMatchNextWord(Sci_Position startPos, Sci_Position endPos, Accessor &styler, const char *word) {
Sci_Position pos = LexSkipSpaceTab(startPos, endPos, styler);
return isspace(LexCharAt(pos + static_cast<int>(strlen(word))))
&& LexMatchIgnoreCase(pos, styler, word);
}
static bool IsVBProperty(Sci_Position line, Sci_Position startPos, Accessor &styler) {
Sci_Position endPos = styler.LineStart(line+1) - 1;
for (Sci_Position i = startPos; i < endPos; i++) {
if (styler.StyleAt(i) == SCE_B_OPERATOR && LexCharAt(i) == '(')
return true;
}
return false;
}
static bool IsVBSome(Sci_Position line, int kind, Accessor &styler) {
Sci_Position startPos = styler.LineStart(line);
Sci_Position endPos = styler.LineStart(line+1) - 1;
Sci_Position pos = LexSkipSpaceTab(startPos, endPos, styler);
int stl = styler.StyleAt(pos);
if (stl == SCE_B_KEYWORD) {
if (LexMatchIgnoreCase(pos, styler, "public")) {
pos += 6;
} else if (LexMatchIgnoreCase(pos, styler, "private")) {
pos += 7;
} else if (LexMatchIgnoreCase(pos, styler, "protected")) {
pos += 9;
pos = LexSkipSpaceTab(endPos, pos, styler);
}
if (LexMatchIgnoreCase(pos, styler, "friend"))
pos += 6;
pos = LexSkipSpaceTab(pos, endPos, styler);
stl = styler.StyleAt(pos);
if (stl == SCE_B_KEYWORD) {
return (kind == 1 && isspace(LexCharAt(pos+4)) && LexMatchIgnoreCase(pos, styler, "type"))
|| (kind == 2 && isspace(LexCharAt(pos+5)) && LexMatchIgnoreCase(pos, styler, "const"));
}
}
return false;
}
#define VBMatch(word) LexMatchIgnoreCase(i, styler, word)
#define VBMatchNext(pos, word) VBMatchNextWord(pos, endPos, styler, word)
#define IsCommentLine(line) IsLexCommentLine(line, styler, SCE_B_COMMENT)
#define IsDimLine(line) VBLineStartsWith(line, styler, "dim")
#define IsConstLine(line) IsVBSome(line, 2, styler)
#define IsVB6Type(line) IsVBSome(line, 1, styler)
static void FoldVBDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList, Accessor &styler) {
if (styler.GetPropertyInt("fold") == 0)
return;
const bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
const bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
const bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
Sci_PositionU endPos = startPos + length;
int visibleChars = 0;
Sci_Position lineCurrent = styler.GetLine(startPos);
int levelCurrent = SC_FOLDLEVELBASE;
if (lineCurrent > 0)
levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
int levelNext = levelCurrent;
char ch = '\0';
char chNext = styler[startPos];
int style = initStyle;
int styleNext = styler.StyleAt(startPos);
int numBegin = 0; // nested Begin ... End, found in VB6 Form
bool isEnd = false; // End {Function Sub}{If}{Class Module Structure Interface Operator Enum}{Property Event}{Type}
bool isInterface = false;// {Property Function Sub Event Interface Class Structure }
bool isProperty = false;// Property: Get Set
bool isCustom = false; // Custom Event
bool isExit = false; // Exit {Function Sub Property}
bool isDeclare = false; // Declare, Delegate {Function Sub}
bool isIf = false; // If ... Then \r\n ... \r\n End If
static Sci_Position lineIf = 0, lineThen = 0;
for (Sci_PositionU i = startPos; i < endPos; i++) {
char chPrev = ch;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
bool atLineBegin = (visibleChars == 0) && !atEOL;
if (foldComment && atEOL && IsCommentLine(lineCurrent)) {
if (!IsCommentLine(lineCurrent - 1) && IsCommentLine(lineCurrent + 1))
levelNext++;
else if (IsCommentLine(lineCurrent - 1) && !IsCommentLine(lineCurrent + 1))
levelNext--;
}
if (atEOL && IsDimLine(lineCurrent)) {
if (!IsDimLine(lineCurrent - 1) && IsDimLine(lineCurrent + 1))
levelNext++;
else if (IsDimLine(lineCurrent - 1) && !IsDimLine(lineCurrent + 1))
levelNext--;
}
if (atEOL && IsConstLine(lineCurrent)) {
if (!IsConstLine(lineCurrent - 1) && IsConstLine(lineCurrent + 1))
levelNext++;
else if (IsConstLine(lineCurrent - 1) && !IsConstLine(lineCurrent + 1))
levelNext--;
}
if (style == SCE_B_KEYWORD && stylePrev != SCE_B_KEYWORD
&& !(chPrev == '.' || chPrev == '[')) { // not a member, not bracketed [keyword] identifier
if (atLineBegin && (VBMatch("for") || (VBMatch("do") && isspace(LexCharAt(i+2))) // not Double
|| VBMatch("while") || (VBMatch("try") && isspace(LexCharAt(i+3))) // not TryCast
|| (VBMatch("select") && VBMatchNext(i+6, "case")) // Select Case
|| (VBMatch("with") && isspace(LexCharAt(i+4))) // not WithEvents, not With {...}
|| VBMatch("namespace") || VBMatch("synclock") || VBMatch("using")
|| (isProperty && (VBMatch("set") || (VBMatch("get") && isspace(LexCharAt(i+3))))) // not GetType
|| (isCustom && (VBMatch("raiseevent") || VBMatch("addhandler") || VBMatch("removehandler")))
)) {
levelNext++;
} else if (atLineBegin && (VBMatch("next") || VBMatch("loop") || VBMatch("wend"))) {
levelNext--;
} else if (VBMatch("exit") && (VBMatchNext(i+4, "function") || VBMatchNext(i+4, "sub")
|| VBMatchNext(i+4, "property")
)) {
isExit = true;
} else if (VBMatch("begin")) {
levelNext++;
if (isspace(LexCharAt(i+5)))
numBegin++;
} else if (VBMatch("end")) {
levelNext--;
char chEnd = LexCharAt(i+3);
if (chEnd == ' ' || chEnd == '\t') {
Sci_Position pos = LexSkipSpaceTab(i+3, endPos, styler);
chEnd = LexCharAt(pos);
// check if End is used to terminate statement
if (isalpha(chEnd) && (VBMatchNext(pos, "function") || VBMatchNext(pos, "sub")
|| VBMatchNext(pos, "if") || VBMatchNext(pos, "class") || VBMatchNext(pos, "structure")
|| VBMatchNext(pos, "module") || VBMatchNext(pos, "enum") || VBMatchNext(pos, "interface")
|| VBMatchNext(pos, "operator") || VBMatchNext(pos, "property") || VBMatchNext(pos, "event")
|| VBMatchNext(pos,"type") // VB6
)) {
isEnd = true;
}
}
if (chEnd == '\r' || chEnd == '\n' || chEnd == '\'') {
isEnd = false;
if (numBegin == 0) levelNext++;// End can be placed anywhere, but not used to terminate statement
if (numBegin > 0) numBegin--;
}
if (VBMatch("endif")) // same as End If
isIf = false;
// one line: If ... Then ... End If
if (lineCurrent == lineIf && lineCurrent == lineThen)
levelNext++;
} else if (VBMatch("if")) {
isIf = true;
lineIf = lineCurrent;
if (isEnd) {isEnd = false; isIf = false;}
else levelNext++;
} else if (VBMatch("then")) {
if (isIf) {
isIf = false;
Sci_Position pos = LexSkipSpaceTab(i+4, endPos, styler);
char chEnd = LexCharAt(pos);
if (!(chEnd == '\r' || chEnd == '\n' || chEnd == '\''))
levelNext--;
}
lineThen = lineCurrent;
} else if ((!isInterface && (VBMatch("class") || VBMatch("structure")))
|| VBMatch("module") || VBMatch("enum") || VBMatch("operator")
) {
if (isEnd) isEnd = false;
else levelNext++;
} else if (VBMatch("interface")) {
if (!(isEnd || isInterface))
levelNext++;
isInterface = true;
if (isEnd) {isEnd = false; isInterface = false;}
} else if (VBMatch("declare") || VBMatch("delegate")) {
isDeclare = true;
} else if (!isInterface && (VBMatch("sub") || VBMatch("function"))) {
if (!(isEnd || isExit || isDeclare))
levelNext++;
if (isEnd) isEnd = false;
if (isExit) isExit = false;
if (isDeclare) isDeclare = false;
} else if (!isInterface && VBMatch("property")) {
isProperty = true;
if (!(isEnd || isExit)) {
levelNext++;
if (!IsVBProperty(lineCurrent, i+8, styler)) {
isProperty = false;
levelNext--;
}
}
if (isEnd) {isEnd = false; isProperty = false;}
if (isExit) isExit = false;
} else if (VBMatch("custom")) {
isCustom = true;
} else if (!isInterface && isCustom && VBMatch("event")) {
if (isEnd) {isEnd = false; isCustom = false;}
else levelNext++;
} else if (VBMatch("type") && isspace(LexCharAt(i+4))) { // not TypeOf, VB6: [...] Type ... End Type
if (!isEnd && IsVB6Type(lineCurrent))
levelNext++;
if (isEnd) isEnd = false;
}
}
if (foldPreprocessor && style == SCE_B_PREPROCESSOR) {
if (VBMatch("#if") || VBMatch("#region") || VBMatch("#externalsource"))
levelNext++;
else if (VBMatch("#end"))
levelNext--;
}
if (style == SCE_B_OPERATOR) {
// Anonymous With { ... }
if (ch == '{')
levelNext++;
else if (ch == '}')
levelNext--;
}
if (!isspacechar(ch))
visibleChars++;
if (atEOL || (i == endPos-1)) {
int levelUse = levelCurrent;
int lev = levelUse | levelNext << 16;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if (levelUse < levelNext)
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelCurrent = levelNext;
visibleChars = 0;
}
}
}
static void ColouriseVBNetDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList keywordLists, Accessor &styler) {
ColouriseVBDoc(startPos, length, initStyle, keywordLists, styler, false);
}
static void ColouriseVBScriptDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList keywordLists, Accessor &styler) {
ColouriseVBDoc(startPos, length, initStyle, keywordLists, styler, true);
}
LexerModule lmVB(SCLEX_VB, ColouriseVBNetDoc, "vb", FoldVBDoc);
LexerModule lmVBScript(SCLEX_VBSCRIPT, ColouriseVBScriptDoc, "vbscript", FoldVBDoc);
|
#include <iostream>
#include <array>
int main() {
using type = float;
std::array<type, 7> v, L;
v[0] = 282.029877;
v[1] = 102.204384;
v[2] = 31.318350;
v[3] = 23.661867;
v[4] = 17.634819;
v[5] = 4.794288;
v[6] = 4.236803;
L[0] = -0.066980;
L[1] = -0.042629;
L[2] = 0.356164;
L[3] = 0.024159;
L[4] = 0.138100;
L[5] = -0.395324;
L[6] = 0.068205;
type sum = 0;
auto const atb = -10.372528;
auto const l_7_7 = 0.002658;
for (int i=0; i<7; i++)
sum += L[i] * v[i];
auto const value = (atb - sum) / l_7_7;
std::cout << "value = " << value << std::endl;
}
|
#include "Game.h"
#include "InputHandler.h"
#include <Windows.h>
#include <sstream>
InputHandler* InputHandler::s_pInstance = nullptr;
InputHandler::InputHandler()
{
m_mousePosition = new Vector2D(0, 0);
for (int i = 0; i < 3; i++)
{
m_mouseButtonStates.push_back(false);
}
}
void InputHandler::clean()
{
}
bool InputHandler::AllKeyOff()
{
if (KeyCount<=0)
{
return true;
}
return false;
}
void InputHandler::update()
{
SDL_Event p_event;
if (SDL_PollEvent(&p_event))
{
switch (p_event.type)
{
case SDL_QUIT:
TheGame::Instance()->setRunning(false);
TheGame::Instance()->clean();
break;
case SDL_MOUSEMOTION:
onMouseMove(p_event);
break;
case SDL_MOUSEBUTTONDOWN:
onMouseButtonDown(p_event);
break;
case SDL_MOUSEBUTTONUP:
onMouseButtonUp(p_event);
break;
case SDL_KEYDOWN:
onKeyDown();
break;
case SDL_KEYUP:
onKeyUp();
break;
default:
break;
}
}
}
void InputHandler::onKeyDown()
{
m_keystates = SDL_GetKeyboardState(0);
}
void InputHandler::onKeyUp()
{
m_keystates = SDL_GetKeyboardState(0);
}
void InputHandler::onMouseMove(SDL_Event& evt)
{
if (evt.type == SDL_MOUSEMOTION)
{
m_mousePosition->setX(evt.motion.x);
m_mousePosition->setY(evt.motion.y);
}
}
void InputHandler::onMouseButtonDown(SDL_Event& evt)
{
if (evt.type == SDL_MOUSEBUTTONDOWN)
{
if (evt.button.button == SDL_BUTTON_LEFT)
{
m_mouseButtonStates[LEFT] = true;
}
if (evt.button.button == SDL_BUTTON_MIDDLE)
{
m_mouseButtonStates[MIDDLE] = true;
}
if (evt.button.button == SDL_BUTTON_RIGHT)
{
m_mouseButtonStates[RIGHT] = true;
}
}
}
void InputHandler::onMouseButtonUp(SDL_Event& evt)
{
if (evt.type == SDL_MOUSEBUTTONUP)
{
if (evt.button.button == SDL_BUTTON_LEFT)
{
m_mouseButtonStates[LEFT] = false;
}
if (evt.button.button == SDL_BUTTON_MIDDLE)
{
m_mouseButtonStates[MIDDLE] = false;
}
if (evt.button.button == SDL_BUTTON_RIGHT)
{
m_mouseButtonStates[RIGHT] = false;
}
}
}
bool InputHandler::isKeyDown(SDL_Scancode key)
{
if (m_keystates != 0)
{
if (m_keystates[key] == 1)
{
return true;
}
else return false;
}
return false;
}
bool InputHandler::getMouseButtonState(int buttonNumber)
{
return m_mouseButtonStates[buttonNumber];
}
Vector2D* InputHandler::getMousePosition()
{
return m_mousePosition;
}
|
// Visual Micro is in vMicro>General>Tutorial Mode
//
/*
Name: GardenConrtonSensor1.ino
Created: 10.06.2021 10:57:35
Author: Bartosz Gumula
*/
// Define User Types below here or use a .h file
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <ArduinoJson.hpp>
#include <WebSocketsClient.h>
#include <Wire.h>
#include <DHT12.h>
#include <String.h>
#include <Adafruit_BMP280.h>
#include <Hash.h>
//
#define USE_SERIAL Serial
#define H HIGH
#define L LOW
#define Led 2
#define slow 2000;
#define fast 280;
//
IPAddress ip(192, 168, 1, 10);
IPAddress gate(192, 168, 1, 1);
IPAddress sub(255,255,255,0);
char ssid[] = "SensorsWiFi";
char pass[] = "658B9D5B***";
WebSocketsClient webSocket;
DHT12 dht;
//globalVar
unsigned long readingTime;
unsigned long blinkTime;
float temp, hum;
uint8_t ledStatus = LOW;
void blink(uint8_t mode = 0) {
switch (mode) {
case 0: { // LED ON - OK;
digitalWrite(Led, HIGH);
ledStatus = HIGH;
}break;
case 1: { //slow blink - WiWi not connected
if (millis() >= blinkTime) {
ledStatus = !ledStatus;
digitalWrite(Led, ledStatus);
blinkTime = millis() + slow;
}
}break;
case 2: { //fast blink - sensor not avaliable
if (millis() >= blinkTime) {
ledStatus = !ledStatus;
digitalWrite(Led, ledStatus);
blinkTime = millis() + fast;
}
}break;
}
}
// The setup() function runs once each time the micro-controller starts
void setup()
{
delay(2000);
//Basic
Serial.begin(115200);
Serial.setDebugOutput(true);
Wire.begin();
//WiFi
//WiFi.config(ip, gate, sub);
delay(100);
if (WiFi.begin(ssid, pass) == WL_CONNECTED){
Serial.println("Connected");
}
//websockets
webSocket.begin("192.168.1.1", 81, "/");
webSocket.onEvent(webSocketEvent);
webSocket.setReconnectInterval(5000);
webSocket.enableHeartbeat(15000, 3000, 2);
pinMode(16, OUTPUT);
pinMode(Led, OUTPUT);
//time
readingTime = millis() + (1000 * 60);
blinkTime = millis();
}
void loop()
{
if (WiFi.status() == WL_CONNECTED) {
if (millis() <= readingTime) {
if (dht.readStatus()){
blink(0);
delay(10);
temp = dht.readTemperature();
hum = dht.readHumidity();
int ilosc = 2;
DynamicJsonDocument dane(256);
dane["type"] = "sensorData";
dane["ilosc"] = ilosc;
dane["val1"]["name"] = "TunelTemp";
dane["val1"]["val"] = temp;
dane["val2"]["name"] = "TunelHum";
dane["val2"]["val"] = hum;
dane["globalName"] = "TUNEL";
String x;
serializeJson(dane, x);
webSocket.sendTXT(x);
delay(500);
Serial.println("SLEEP");
delay(5000);
ESP.deepSleep(20e7);
}
else {
Serial.println("DHT wrong status");
blink(2);
}
}
webSocket.loop();
}
else {
Serial.println("Not connected");
blink(1);
}
delay(300);
}
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
switch (type) {
case WStype_DISCONNECTED:
USE_SERIAL.printf("[WSc] Disconnected!\n");
break;
case WStype_CONNECTED: {
USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
// send message to server when Connected
webSocket.sendTXT("Connected");
}
break;
case WStype_TEXT:
USE_SERIAL.printf("[WSc] get text: %s\n", payload);
// send message to server
// webSocket.sendTXT("message here");
break;
case WStype_BIN:
USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
hexdump(payload, length);
// send data to server
// webSocket.sendBIN(payload, length);
break;
case WStype_PING:
// pong will be send automatically
USE_SERIAL.printf("[WSc] get ping\n");
break;
case WStype_PONG:
// answer to a ping we send
USE_SERIAL.printf("[WSc] get pong\n");
break;
}
}
|
#pragma once
#include "SSSPipeline.h"
#include "AppFrameWork2.h"
#include <sstream>
using namespace std;
class App_SSS :public App{
public:
bool shutdown = false;
bool use_huawei_head = false;
int head_index = 0;
float modelscale = 0.003;
Vector3 modelTranslate = Vector3(-1.6,0.5,-1.6);
vector<SceneNode*> lightpoint= vector<SceneNode*>(5,nullptr);
void Init() {
w = 1280;
h = 720;
if (use_huawei_head) {
if (head_index == 0) {
w = 800;
h = 920;
}
if (head_index == 1) {
w = 540;
h = 960;
}
if (head_index == 2) {
w = 1000;
h = 600;
}
if (head_index == 3) {
w = 420;
h = 360;
}
if (head_index == 4) {
w = 280;
h = 440;
}
if (head_index == 5 ) {
w = 380;
h = 520;
}
}
render = new EGLRenderSystem;
render->SetWandH(w, h);
render->Initialize();
InitDevice();
InitPipeline();
CreateScene();
}
void LoadModel(string path) {
SceneManager* scene = SceneContainer::getInstance().get("scene1");
SceneNode* root = scene->GetSceneRoot();
SceneNode* s;
s = LoadMeshtoSceneNode(path, path);
if (s == NULL) {
cout << "cant load model:" + path << endl; return;
}
s->setScale(Vector3(modelscale));
s->setTranslation(modelTranslate);
if (s != NULL)
root->attachNode(s);
auto b = root->getBoundingBox();
auto v=b.getHalfSize();
cout<<v.x;
}
void RemoveAllNodes() {
SceneManager* scene = SceneContainer::getInstance().get("scene1");
SceneNode* root = scene->GetSceneRoot();
root->detachAllNodes();
}
void InitPipeline()
{
auto mpipeline = new SSSPipeline;
mpipeline->use_huawei_head = use_huawei_head;
mpipeline->head_index = head_index;
mpipeline->Init();
pipeline = mpipeline;
}
void Render() {
UpdateGUI();
pipeline->Render();
}
void SetCameraPers() {
camera->setProjectionType(Camera::PT_PERSPECTIVE);
camera->lookAt(Vector3(0, 0, 1.5), Vector3(0, 0, 0), Vector3(0, 1, 0));
camera->setPerspective(45, float(w) / float(h), 0.01, 50);
}
void SetCameraOrth() {
float width = w *modelscale, height = h *modelscale;
float x = 1.2, y = -1.2;
//x = 0; y = 0;
camera->lookAt(Vector3(x, y, 1000 * modelscale), Vector3(x, y, 0), Vector3(0, 1, 0));
camera->setProjectionType(Camera::PT_ORTHOGONAL);
camera->setFrustum(-width / 2, width / 2, -height / 2, height / 2, 0.1, 3000*modelscale);
}
void UpdateGUI() {
GUI::NewFrame();
{
ImGui::Begin("Params");
ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
auto p = (SSSPipeline*)pipeline;
ImGui::DragFloat("bumpiness",&p->bumpiness,0.002, 0.0, 1.0);
ImGui::DragFloat("specularIntensity", &p->specularIntensity, 0.002, 0.0, 10.0);
ImGui::DragFloat("specularRoughness", &p->specularRoughness, 0.002, 0.0, 1.0);
ImGui::DragFloat("specularFresnel", &p->specularFresnel, 0.002, 0.0, 1.0);
ImGui::DragFloat("translucency", &p->translucency, 0.002, 0.0, 1.0);
ImGui::DragFloat("sssBlurWidth", &p->sssWidth, 0.0001, 0.0, 0.1);
//ImGui::DragFloat("environment", &p->environment, 0.002, 0.0, 1.0);
static bool f=false;
ImGui::Checkbox("Transmittance Enable", &f); p->sssEnabled = f ? 1 : 0;
static char file[100]="model/RelightingData/0.obj";
ImGui::InputText("Model Path", file, 100);
string tmp(file);
if (ImGui::Button("Load")) LoadModel(tmp);
if (ImGui::Button("RemoveAll")) RemoveAllNodes();
ImGui::DragFloat("Load model scale", &modelscale, 0.001, 0.003, 1.0);
static bool f2 = false;
ImGui::Checkbox("Use Normal map", &f2); p->normalenable = f2 ? 1 : 0;
if(ImGui::Button("PersCamera")) SetCameraPers();
if (ImGui::Button("OrthCamera")) SetCameraOrth();
ImGui::Combo("Shading mode", &p->mode, "shading\0shadowMap0\0shadowMap1\0shadowMap2\0shadowFactor0\0shadowFactor1\0shadowFactor2\0");
static int cameraid = 0;
if (ImGui::Button("Go to Light Camera")) {
auto s= &p->e_shadowmap.cameras[cameraid];
camera->setProjectionType(Camera::PT_PERSPECTIVE);
camera->lookAt(s->getPosition(), s->getDirection(), Vector3(0, 1, 0));
camera->setPerspective(45, float(w) / float(h), s->getNear(), s->getFar());
}
ImGui::InputInt("Light ID (0-3)", &cameraid);
ImGui::DragFloat3("CameraPos", &camera->m_Position[0]);
static bool showlightwindow = 1;
if (ImGui::Button("Light Window")) showlightwindow = !showlightwindow;
if (showlightwindow) {
ImGui::Begin("Light");
ImGui::DragFloat3("Light Center", &p->LightCenter[0]);
ImGui::DragFloat("Light Near", &p->lightnear,0.01,0.01);
ImGui::DragFloat("Light Far", &p->lightfar,0.01);
ImGui::DragFloat("ambient light", &p->ambient, 0.002, 0.0, 1.0);
ImGui::Text("hard shadowmap");
ImGui::DragFloat3("Light0 position", &p->lights[0].positon[0], 0.1);
ImGui::DragFloat3("Light0 color", &p->lights[0].color[0], 0.01);
ImGui::DragFloat("ShadowCameraWidth0", &p->sw[0]);
ImGui::DragFloat3("Light1 position", &p->lights[1].positon[0], 0.1);
ImGui::DragFloat3("Light1 color", &p->lights[1].color[0], 0.01);
ImGui::DragFloat("ShadowCameraWidth1", &p->sw[1]);
ImGui::Text("soft shadowmap");
ImGui::DragFloat("Blur radius", &p->vsm.blureffect.radius, 0.001, 0.003, 3.0);
ImGui::DragFloat("ReduceBleeding", &p->vsm.ReduceBleeding, 0.001, 0.003, 1.0);
ImGui::DragFloat3("Light2 position", &p->lights[2].positon[0], 0.1);
ImGui::DragFloat3("Light2 color", &p->lights[2].color[0], 0.01);
ImGui::DragFloat("ShadowCameraWidth2", &p->sw[2]);
for (int i = 0; i < 4; i++) {
auto dir = p->LightCenter - p->lights[i].positon;
dir.normalize();
p->lights[i].direction = dir;
if (lightpoint[i] != nullptr)
lightpoint[i]->setTranslation(p->lights[i].positon);
}
if (ImGui::Button("LoadPreset")) p->LoadConfigs();
ImGui::End();
}
//static int f3 = 1;
//ImGui::Combo("Camera Mode", &f3, "orth\0pers\0");
//if (f3 == 0) SetCameraOrth(); else SetCameraPers();
ImGui::End();
}
}
void CreateScene() {
scene = new OctreeSceneManager("scene1", render);
SceneContainer::getInstance().add(scene);
SceneNode* pRoot = scene->GetSceneRoot();
camera = scene->CreateCamera("main");
camera->lookAt(Vector3(0, 0, 1.5), Vector3(0, 0, 0), Vector3(0, 1, 0));
camera->setPerspective(45, float(w) / float(h), 0.01, 50);
//scene1 light
{
Light * sunLight;
sunLight = scene->CreateLight("light1", Light::LT_SPOT);
sunLight->setDirection(Vector3(1.0, -1.0, -1.0));
sunLight->setPosition(Vector3(-1, 2, 6));
sunLight->SetMaxDistance(9);
sunLight->Exponent = 3;
sunLight->Cutoff = 0.8;
sunLight->setCastShadow(true);
sunLight->Diffuse = Vector3(1.0, 1.0, 1.0);
scene->setActiveLightVector(sunLight, 0);
}
//FrameListener * camera_op = new FrameListenerDebug(camera, pRoot, scene, h, w, sysentry->m_pipeline);
//framelistener_list.push_back(camera_op);
loadModels();
}
void loadModels() {
SceneManager* scene = SceneContainer::getInstance().get("scene1");
SceneNode* root = scene->GetSceneRoot();
SceneNode* s;
for (int i = 0; i < 3; i++) {
s = LoadMeshtoSceneNode("model/pbr_test/sphere7d.obj", "light point" + to_string(i));
s->scale(0.03, 0.03, 0.03);
lightpoint[i] = s;
root->attachNode(s);
}
if (!use_huawei_head) {
s = LoadMeshtoSceneNode("model/head/head5.obj", "Head");
s->scale(3, 3, 3);
}
//else
//{
// float scale = 300;
// float width = w / scale, height = h / scale;
// stringstream mesh_name;
// mesh_name << "model/head/huawei/" << head_index << ".obj";
// s = LoadMeshtoSceneNode(mesh_name.str(), "Head");
// s->translate(-width / 2 - 0.5 / scale, height / 2 - 0.5 / scale, 0);
// //camera->lookAt(Vector3(0, 0, 1000 / scale), Vector3(0, 0, 0), Vector3(0, 1, 0));
// //camera->setProjectionType(Camera::PT_ORTHOGONAL);
// //camera->setFrustum(-width / 2, width / 2, -height / 2, height / 2, 0.1, 3000 / scale);
// s->scale(1 / scale, 1 / scale, 1 / scale);
//}
root->attachNode(s);
}
};
|
/**今年暑假不AC */
//“今年暑假不AC?”
//“是的。”
//“那你干什么呢?”
//“看世界杯呀,笨蛋!”
//“@#$%^&*%...”
//
//确实如此,世界杯来了,球迷的节日也来了,估计很多ACMer也会抛开电脑,奔向电视了。
//作为球迷,一定想看尽量多的完整的比赛,当然,作为新时代的好青年,你一定还会看一些其它的节目,
//比如新闻联播(永远不要忘记关心国家大事)、非常6+7、超级女生,以及王小丫的《开心辞典》等等,
//假设你已经知道了所有你喜欢看的电视节目的转播时间表,你会合理安排吗?(目标是能看尽量多的完整节目)
///**Input*/
//输入数据包含多个测试实例,每个测试实例的第一行只有一个整数n(n<=100),表示你喜欢看的节目的总数,
//然后是n行数据,每行包括两个数据Ti_s,Ti_e (1<=i<=n),分别表示第i个节目的开始和结束时间,为了简化问题,每个时间都用一个正整数表示。n=0表示输入结束,不做处理。
///**Output*/
//对于每个测试实例,输出能完整看到的电视节目的个数,每个测试实例的输出占一行。
#include <iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node
{
int st;
int ed;
};
bool cmp(node node1,node node2)
{
return node1.ed<node2.ed;
}
int main()
{
int i,j,num,ans,now=0;
struct node nodes[105];
while(scanf("%d",&num)&&num)
{
for(i=0; i<num; i++)
{
scanf("%d%d",&nodes[i].st,&nodes[i].ed);
// cin>>nodes[i].st>>nodes[i].ed;
}
sort(nodes,nodes+num,cmp);
now = nodes[0].ed;
ans = 1;
for(j=1; j<num; j++)
{
if(nodes[j].st>=now)
{
now = nodes[j].ed;
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
//
// Copyright (C) 2003-2007 Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Julien Picalausa
//
#include "core/pch.h"
#include "WindowsOpCommandLineArgumentHandler.h"
#include "adjunct/desktop_util/boot/DesktopBootstrap.h"
#include "platforms/windows/pi/WindowsOpSystemInfo.h"
#include "platforms/windows/installer/OperaInstaller.h"
extern void MakeDefaultBrowser(BOOL force_HKLM = FALSE);
extern void MakeDefaultMailClient(BOOL force_HKLM = FALSE);
OP_STATUS CommandLineArgumentHandler::Create(CommandLineArgumentHandler** handler)
{
if ((*handler = new WindowsOpCommandLineArgumentHandler()) != 0)
return OpStatus::OK;
else
return OpStatus::ERR_NO_MEMORY;
}
OP_STATUS WindowsOpCommandLineArgumentHandler::CheckArgPlatform(CommandLineManager::CLArgument arg_name, const char *arg)
{
if ((arg_name == CommandLineManager::Settings
#ifdef _DEBUG
|| arg_name == CommandLineManager::DebugSettings
#endif
) && !PathFileExistsA(arg))
return OpStatus::ERR;
return OpStatus::OK;
}
OP_STATUS WindowsOpCommandLineArgumentHandler::HandlePlatform(CommandLineManager::CLArgument arg_name, CommandLineArgument *arg_value)
{
switch (arg_name)
{
case CommandLineManager::ScreenHeight:
case CommandLineManager::ScreenWidth:
#ifdef _DEBUG
case CommandLineManager::DebugSettings:
#endif
case CommandLineManager::MediaCenter:
case CommandLineManager::Settings:
case CommandLineManager::Fullscreen:
case CommandLineManager::DelayShutdown:
case CommandLineManager::ReinstallBrowser:
case CommandLineManager::ReinstallMailer:
case CommandLineManager::ReinstallNewsReader:
case CommandLineManager::PersonalDirectory:
//We use these later on
break;
case CommandLineManager::HideIconsCommand:
//TODO: implement what is needed to remove Opera from view
exit(0);
case CommandLineManager::ShowIconsCommand:
//TODO: implement what is needed to put Opera back in start menu,...
exit(0);
case CommandLineManager::NewWindow:
return OpStatus::OK;
break;
case CommandLineManager::AddFirewallException:
{
uni_char exe_path[MAX_PATH];
if(!GetModuleFileName(NULL, exe_path, MAX_PATH))
break;
OpStringC path_string(exe_path);
OpStringC opera_string(UNI_L("Opera Internet Browser"));
WindowsOpSystemInfo::AddToWindowsFirewallException(path_string, opera_string);
exit(0);
}
case CommandLineManager::CrashLog:
g_desktop_bootstrap->DisableHWAcceleration();
break;
case CommandLineManager::OWIInstall:
case CommandLineManager::OWIUninstall:
case CommandLineManager::OWIAutoupdate:
g_desktop_bootstrap->DisableHWAcceleration();
// Fall through.
case CommandLineManager::OWISilent:
case CommandLineManager::OWIInstallFolder:
case CommandLineManager::OWILanguage:
case CommandLineManager::OWICopyOnly:
case CommandLineManager::OWIAllUsers:
case CommandLineManager::OWISingleProfile:
case CommandLineManager::OWISetDefaultPref:
case CommandLineManager::OWISetFixedPref:
case CommandLineManager::OWISetDefaultBrowser:
case CommandLineManager::OWIStartMenuShortcut:
case CommandLineManager::OWIDesktopShortcut:
case CommandLineManager::OWIQuickLaunchShortcut:
case CommandLineManager::OWIPinToTaskbar:
case CommandLineManager::OWILaunchOpera:
case CommandLineManager::OWIGiveFolderWriteAccess:
case CommandLineManager::OWIGiveWriteAccessTo:
case CommandLineManager::OWIUpdateCountryCode:
case CommandLineManager::OWICountryCode:
#if defined(_DEBUG) && defined(MEMORY_ELECTRIC_FENCE)
case CommandLineManager::Fence:
#endif // MEMORY_ELECTRIC_FENCE
//We use these later on
break;
default:
return OpStatus::ERR;
}
return OpStatus::OK;
}
BOOL WindowsOpCommandLineArgumentHandler::HideHelp(CommandLineManager::CLArgument arg_name)
{
switch (arg_name)
{
case CommandLineManager::WatirTest:
case CommandLineManager::DebugProxy:
case CommandLineManager::DelayShutdown:
#ifdef _DEBUG
case CommandLineManager::DebugSettings:
#endif
case CommandLineManager::HideIconsCommand:
case CommandLineManager::ShowIconsCommand:
case CommandLineManager::ReinstallBrowser:
case CommandLineManager::ReinstallMailer:
case CommandLineManager::ReinstallNewsReader:
case CommandLineManager::OWIInstall:
case CommandLineManager::OWIUninstall:
case CommandLineManager::OWIAutoupdate:
case CommandLineManager::OWISilent:
case CommandLineManager::OWIInstallFolder:
case CommandLineManager::OWILanguage:
case CommandLineManager::OWICopyOnly:
case CommandLineManager::OWIAllUsers:
case CommandLineManager::OWISingleProfile:
case CommandLineManager::OWISetDefaultPref:
case CommandLineManager::OWISetFixedPref:
case CommandLineManager::OWISetDefaultBrowser:
case CommandLineManager::OWIStartMenuShortcut:
case CommandLineManager::OWIDesktopShortcut:
case CommandLineManager::OWIQuickLaunchShortcut:
case CommandLineManager::OWIPinToTaskbar:
case CommandLineManager::OWILaunchOpera:
case CommandLineManager::OWIUpdateCountryCode:
case CommandLineManager::OWICountryCode:
return TRUE;
default:
return FALSE;
}
}
|
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
int main(int argc, char *argv[])
{
cv::VideoCapture cap;
cap.open(0);
if (!cap.isOpened()) {
std::cerr << "err openning camera" << std::endl;
return -1;
}
cv::namedWindow("camera capture");
while (1) {
cv::Mat stream;
cap >> stream;
cv::imshow("camera capture", stream);
if (cv::waitKey(20) == 'n')
break;
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifndef NO_CARBON
#ifdef MACGOGI
#include "platforms/macgogi/pi/MacOpMultimediaPlayer.h"
#include "platforms/macgogi/util/OpFileUtils.h"
#include "platforms/macgogi/util/utils.h"
#else
#include "platforms/mac/pi/MacOpMultimediaPlayer.h"
#include "platforms/mac/File/FileUtils_Mac.h"
#endif
// #define SYNCHRONOUS_MOVIE_PLAY
#define FILE_CLEANUP
OP_STATUS OpMultimediaPlayer::Create(OpMultimediaPlayer **newObj)
{
*newObj = new MacOpMultimediaPlayer;
return *newObj ? OpStatus::OK : OpStatus::ERR_NO_MEMORY;
}
MacOpMultimediaPlayer::MacOpMultimediaPlayer()
: movie(NULL)
{
EnterMovies();
}
MacOpMultimediaPlayer::~MacOpMultimediaPlayer()
{
ExitMovies();
if(movie)
{
DisposeMovie(movie);
}
}
void MacOpMultimediaPlayer::Stop(UINT32 id)
{
if (movie)
{
DisposeMovie(movie);
}
movie = NULL;
}
void MacOpMultimediaPlayer::StopAll()
{
if (movie)
{
DisposeMovie(movie);
}
movie = NULL;
}
OP_STATUS MacOpMultimediaPlayer::LoadMedia(const uni_char* filename)
{
return OpStatus::ERR;
}
OP_STATUS MacOpMultimediaPlayer::PlayMedia()
{
return OpStatus::ERR;
}
OP_STATUS MacOpMultimediaPlayer::PauseMedia()
{
return OpStatus::ERR;
}
OP_STATUS MacOpMultimediaPlayer::StopMedia()
{
return OpStatus::ERR;
}
void MacOpMultimediaPlayer::SetMultimediaListener(OpMultimediaListener* listener)
{
}
#endif // NO_CARBON
|
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> v;
v.push_back(9);
v.push_back(8);
v.insert(v.begin(),10);
for(vector<int>::iterator it = v.begin(); it!=v.end(); ++it){
cout<<*it<<endl;
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<int>pos, neg;
main()
{
ll n;
while(cin>>n)
{
ll i, x, sum_pos=0, sum_neg=0, lst_pos, lst_neg;
for(i=0; i<n; i++)
{
cin>>x;
if(x>0)
{
lst_pos = i;
sum_pos+=x;
pos.push_back(x);
}
else
{
lst_neg = i;
x=abs(x);
sum_neg+=x;
neg.push_back(x);
}
}
if(sum_pos>sum_neg)printf("first\n");
else if(sum_neg>sum_pos)printf("second\n");
else
{
for(i=0; i<min(pos.size(), neg.size()); i++)
{
if(pos[i]>neg[i])
{
printf("first\n");
return 0;
}
else if(neg[i]>pos[i])
{
printf("second\n");
return 0;
}
}
if(pos.size()>neg.size())printf("first\n");
else if(pos.size()<neg.size())printf("second\n");
else
{
if(lst_pos>lst_neg)printf("first\n");
else
printf("second\n");
}
}
}
return 0;
}
|
/*
* Copyright 2019 LogMeIn
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <future>
#include <iostream>
#include <thread>
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <benchmark/benchmark.h>
#include <asyncly/executor/ThreadPoolExecutorController.h>
namespace asyncly {
namespace {
const uint64_t counter_increment = 10000;
std::atomic<bool> keepRunning{ true };
std::atomic<uint64_t> result{ 0 };
thread_local uint64_t counter{ 0 };
static void
send(std::shared_ptr<IExecutor> executorToCallIn, std::shared_ptr<IExecutor> executorToCallBack)
{
if (!keepRunning.load()) {
return;
}
auto task
= [executorToCallIn, executorToCallBack]() { send(executorToCallBack, executorToCallIn); };
executorToCallIn->post(task);
counter++;
if (counter % counter_increment == 0) {
result.fetch_add(counter_increment, std::memory_order_relaxed);
}
}
}
}
using namespace asyncly;
static void threadPoolPerformanceTest(benchmark::State& state)
{
keepRunning = true;
auto range = static_cast<size_t>(state.range(0));
auto executorControlA = ThreadPoolExecutorController::create(range);
auto executorA = executorControlA->get_executor();
auto executorControlB = ThreadPoolExecutorController::create(range);
auto executorB = executorControlB->get_executor();
auto lastTs = std::chrono::steady_clock::now();
for (unsigned i = 0; i < 10 * range; i++) {
send(executorB, executorA);
}
bool allowedToRun = true;
uint64_t lastResult = 0;
while (allowedToRun) {
uint64_t currentResult = result;
while (lastResult == currentResult) {
boost::this_thread::sleep_for(boost::chrono::microseconds(5));
currentResult = result;
}
const auto afterTs = std::chrono::steady_clock::now();
auto incrementCount = (currentResult - lastResult);
const auto iterationTime
= std::chrono::duration_cast<std::chrono::duration<double>>(afterTs - lastTs).count()
/ incrementCount;
for (size_t i = 0; allowedToRun && i < incrementCount; ++i) {
allowedToRun = state.KeepRunning();
state.SetIterationTime(iterationTime);
}
lastTs = afterTs;
lastResult = currentResult;
}
keepRunning = false;
state.SetItemsProcessed(result.exchange(0));
std::promise<void> doneA;
executorA->post([&doneA]() { doneA.set_value(); });
std::promise<void> doneB;
executorB->post([&doneB]() { doneB.set_value(); });
doneA.get_future().wait();
doneB.get_future().wait();
}
BENCHMARK(threadPoolPerformanceTest)
->Arg(1)
->Arg(2)
->Arg(std::thread::hardware_concurrency() / 2)
->UseManualTime();
|
#include "../command.hpp"
void scale(const double depth, const double breadth) {
response::vacuous();
}
|
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int N;
cin >> N;
int current_block = 1;
while(current_block <= N)
{
if(current_block != 1)
cout << endl;
int case_c = 1;
int n, m;
while(cin >> n >> m)
{
int cnt = 0;
if(n == 0 && m == 0)
break;
for(int a = 1; a < n; a++)
for(int b = a+1; b < n; b++)
if(((a*a+ b*b + m) %(a*b)) == 0)
cnt++;
cout << "Case " << case_c << ": " << cnt << endl;
case_c++;
}
current_block++;
}
return 0;
}
|
#include <iostream>
#include <string>
template<typename T>
struct X {
int m1 = 7;
T m2;
X(T const& x) : m2{x} {}
void mf1() {}
void mf2();
};
template<typename T>
void X<T>::mf2() {}
template<typename T>
struct Vector_iter {};
template<typename T>
class Vector {
public:
using value_type = T;
using iterator = Vector_iter<T>;
};
struct Point { int x, y; };
template<typename T>
struct XX {
static constexpr Point p {100, 250};
static const int m1 = 7;
// error: non-const static data member must be initialized out of line
// static int m2 = 8; // error: not const
static int m3;
static void f1() {}
static void f2();
};
//error: redefinition of 'm1' with a different type: 'int' vs 'const int'
//template<typename T> int XX<T>::m1 = 88;
template<typename T> int XX<T>::m3 = 99;
template<typename T> void XX<T>::f2() {}
int main() {
X<int> xi{9};
X<std::string> xs{"grwegrw"};
}
|
// Created on: 1995-10-25
// Created by: Christian CAILLET
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IFSelect_SelectSent_HeaderFile
#define _IFSelect_SelectSent_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Integer.hxx>
#include <IFSelect_SelectExtract.hxx>
class Interface_EntityIterator;
class Interface_Graph;
class Standard_Transient;
class Interface_InterfaceModel;
class TCollection_AsciiString;
class IFSelect_SelectSent;
DEFINE_STANDARD_HANDLE(IFSelect_SelectSent, IFSelect_SelectExtract)
//! This class returns entities according sending to a file
//! Once a model has been loaded, further sendings are recorded
//! as status in the graph (for each value, a count of sendings)
//!
//! Hence, it is possible to query entities : sent ones (at least
//! once), non-sent (i.e. remaining) ones, duplicated ones, etc...
//!
//! This selection performs this query
class IFSelect_SelectSent : public IFSelect_SelectExtract
{
public:
//! Creates a SelectSent :
//! sentcount = 0 -> remaining (non-sent) entities
//! sentcount = 1, atleast = True (D) -> sent (at least once)
//! sentcount = 2, atleast = True -> duplicated (sent least twice)
//! etc...
//! sentcount = 1, atleast = False -> sent just once (non-dupl.d)
//! sentcount = 2, atleast = False -> sent just twice
//! etc...
Standard_EXPORT IFSelect_SelectSent(const Standard_Integer sentcount = 1, const Standard_Boolean atleast = Standard_True);
//! Returns the queried count of sending
Standard_EXPORT Standard_Integer SentCount() const;
//! Returns the <atleast> status, True for sending at least the
//! sending count, False for sending exactly the sending count
//! Remark : if SentCount is 0, AtLeast is ignored
Standard_EXPORT Standard_Boolean AtLeast() const;
//! Returns the list of selected entities. It is redefined to
//! work on the graph itself (not queried by sort)
//!
//! An entity is selected if its count complies to the query in
//! Direct Mode, rejected in Reversed Mode
//!
//! Query works on the sending count recorded as status in Graph
Standard_EXPORT virtual Interface_EntityIterator RootResult (const Interface_Graph& G) const Standard_OVERRIDE;
//! Returns always False because RootResult has done the work
Standard_EXPORT Standard_Boolean Sort (const Standard_Integer rank, const Handle(Standard_Transient)& ent, const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE;
//! Returns a text defining the criterium : query :
//! SentCount = 0 -> "Remaining (non-sent) entities"
//! SentCount = 1, AtLeast = True -> "Sent entities"
//! SentCount = 1, AtLeast = False -> "Sent once (no duplicated)"
//! SentCount = 2, AtLeast = True -> "Sent several times entities"
//! SentCount = 2, AtLeast = False -> "Sent twice entities"
//! SentCount > 2, AtLeast = True -> "Sent at least <count> times entities"
//! SentCount > 2, AtLeast = False -> "Sent <count> times entities"
Standard_EXPORT TCollection_AsciiString ExtractLabel() const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IFSelect_SelectSent,IFSelect_SelectExtract)
protected:
private:
Standard_Integer thecnt;
Standard_Boolean thelst;
};
#endif // _IFSelect_SelectSent_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#ifdef GEOLOCATION_SUPPORT
#include "modules/geolocation/src/geo_network_request.h"
#include "modules/geolocation/geolocation.h"
#include "modules/geolocation/src/geo_tools.h"
#include "modules/pi/OpGeolocation.h"
#include "modules/pi/OpSystemInfo.h"
// The responses are usually several hundred characters long.
#define RESPONSE_CHARS_LIMIT 32768
/* static */ OP_STATUS
OpGeolocationNetworkRequest::Create(OpGeolocationNetworkRequest *&new_obj, OpGeolocationNetworkApi *network_api, GeoWifiData *wifi_data, GeoRadioData *radio_data, GeoGpsData *gps_data)
{
OpGeolocationNetworkRequest *obj = OP_NEW(OpGeolocationNetworkRequest, (network_api));
if (!obj)
return OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsError(obj->Construct(wifi_data, radio_data, gps_data)))
{
OP_DELETE(obj);
return OpStatus::ERR_NO_MEMORY;
}
new_obj = obj;
return OpStatus::OK;
}
OP_STATUS
OpGeolocationNetworkRequest::Construct(GeoWifiData *wifi_data, GeoRadioData *radio_data, GeoGpsData *gps_data)
{
m_mh = g_main_message_handler;
URL request_url;
RETURN_IF_ERROR(m_network_api->MakeRequestUrl(request_url, wifi_data, radio_data, gps_data));
m_request_url = request_url;
CommState state = m_request_url.Load(m_mh, URL(), TRUE, TRUE, FALSE, TRUE);
if (state != COMM_LOADING)
return OpStatus::ERR;
RETURN_IF_ERROR(SetCallbacks());
return OpStatus::OK;
}
OpGeolocationNetworkRequest::OpGeolocationNetworkRequest(OpGeolocationNetworkApi *network_api)
: m_listener(NULL)
, m_network_api(network_api)
, m_mh(NULL)
, m_finished(FALSE)
{
}
OpGeolocationNetworkRequest::~OpGeolocationNetworkRequest()
{
Out();
UnsetCallbacks();
}
void
OpGeolocationNetworkRequest::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
switch (msg)
{
case MSG_URL_MOVED:
{
UnsetCallbacks();
m_request_url = m_request_url.GetAttribute(URL::KMovedToURL); // TODO? Update m_url_str with new target?
SetCallbacks();
return;
}
case MSG_URL_LOADING_FAILED:
{
HandleError(OpGeolocation::Error::PROVIDER_ERROR);
OP_DELETE(this);
return;
}
case MSG_URL_DATA_LOADED:
{
if (m_request_url.Status(TRUE) == URL_LOADED)
{
HandleFinished();
OP_DELETE(this);
}
return;
}
}
OP_ASSERT(!"You shouldn't be here, are we sending messages to ourselves that we do not handle?");
HandleError(OpGeolocation::Error::PROVIDER_ERROR);
}
OP_STATUS
OpGeolocationNetworkRequest::SetCallbacks()
{
URL_ID id = m_request_url.Id();
RETURN_IF_ERROR(m_mh->SetCallBack(this, MSG_URL_DATA_LOADED, id));
RETURN_IF_ERROR(m_mh->SetCallBack(this, MSG_URL_LOADING_FAILED, id));
RETURN_IF_ERROR(m_mh->SetCallBack(this, MSG_URL_MOVED, id));
return OpStatus::OK;
}
void
OpGeolocationNetworkRequest::UnsetCallbacks()
{
if (m_mh)
m_mh->UnsetCallBacks(this);
}
void
OpGeolocationNetworkRequest::HandleFinished()
{
m_finished = TRUE;
UnsetCallbacks();
int response = m_request_url.GetAttribute(URL::KHTTP_Response_Code);
if (response == HTTP_OK || m_request_url.Type() == URL_DATA)
{
OpGeolocation::Position position;
op_memset(&position, 0, sizeof(position));
position.type = OpGeolocation::WIFI|OpGeolocation::RADIO;
OP_STATUS err = HandleResponse(position);
if (m_listener)
{
if (OpStatus::IsSuccess(err))
m_listener->OnNetworkPositionAvailable(position);
else
m_listener->OnNetworkPositionError(OpGeolocation::Error(OpGeolocation::Error::POSITION_NOT_FOUND, OpGeolocation::WIFI|OpGeolocation::RADIO));
}
}
else
{
#ifdef OPERA_CONSOLE
GeoTools::PostConsoleMessage(OpConsoleEngine::Error, UNI_L("Location provider responded with error code."), GeoTools::CustomProviderNote());
#endif // OPERA_CONSOLE
if (m_listener)
m_listener->OnNetworkPositionError(OpGeolocation::Error(OpGeolocation::Error::PROVIDER_ERROR, OpGeolocation::WIFI|OpGeolocation::RADIO));
}
}
void
OpGeolocationNetworkRequest::HandleError(OpGeolocation::Error::ErrorCode error)
{
m_finished = TRUE;
UnsetCallbacks();
if (m_listener)
m_listener->OnNetworkPositionError(OpGeolocation::Error(error, OpGeolocation::WIFI|OpGeolocation::RADIO));
}
OP_STATUS
OpGeolocationNetworkRequest::HandleResponse(OpGeolocation::Position &pos)
{
OpAutoPtr<URL_DataDescriptor> url_dd(m_request_url.GetDescriptor(m_mh, TRUE, FALSE, TRUE, NULL, URL_TEXT_CONTENT));
if (!url_dd.get())
return OpStatus::ERR;
BOOL more;
unsigned long bytes_read = url_dd->RetrieveData(more);
unsigned int chars_read = bytes_read / 2;
unsigned int total_chars_read = 0;
uni_char *buffer;
TempBuffer temp_buffer;
if (more)
{
do
{
temp_buffer.Append((uni_char*) url_dd->GetBuffer(), chars_read);
total_chars_read += chars_read;
url_dd->ConsumeData(chars_read * 2);
bytes_read = url_dd->RetrieveData(more);
chars_read = bytes_read / 2;
} while(chars_read > 0 && total_chars_read < RESPONSE_CHARS_LIMIT);
buffer = temp_buffer.GetStorage();
}
else
{
buffer = (uni_char*) url_dd->GetBuffer();
total_chars_read = chars_read;
}
return m_network_api->ProcessResponse(buffer, total_chars_read, pos);
}
#endif // GEOLOCATION_SUPPORT
|
#include <simplecpp>
main_program{
initCanvas();
Turtle t1, t2, t3;
t2.left(120);
t3.left(240);
repeat(8){
t1.forward(100);
t2.forward(100);
t3.forward(100);
t1.left(360.0/8);
t2.left(360.0/8);
t3.left(360.0/8);
}
wait(5);
}
|
/*
* controller.cpp
* Control the game, move pieces, etc.
*
* @author Yoan DUMAS
* @versionn 1.0
* @date 20/12/2013
*/
#include <iostream>
#include <stdlib.h>
#include "controller.h"
#include "factory.h"
#include "draughtpiece.h"
#include "clickablelabel.h"
Controller::Controller(QWidget * parent) :
QMainWindow(parent),
next_(WHITE),
squareSelected_((position_t){-1,-1})
{
initDraughtboard();
ClickableLabel ** labelTable = db_.getLabelTable();
for(int i = 0 ; i < DB_LENGTH * DB_LENGTH ; ++i) {
connect(labelTable[i], SIGNAL(clicked(position_t)), this, SLOT(getClicked(position_t)));
}
// Set the properties of the window
setWindowTitle("Checkers");
setMinimumSize(600, 600);
setCentralWidget(db_.draw());
}
Controller::~Controller() {
for(std::map<int, Piece *>::iterator it = whitePieces_.begin() ; it != whitePieces_.end() ; ++it) {
delete (*it).second;
}
for(std::map<int, Piece *>::iterator it = blackPieces_.begin() ; it != blackPieces_.end() ; ++it) {
delete (*it).second;
}
}
void Controller::initDraughtboard() {
Factory<Piece> fac;
fac.record("WhiteDraught", new DraughtPiece((position_t){-1, -1}, WHITE, NORMAL));
fac.record("BlackDraught", new DraughtPiece((position_t){-1, -1}, BLACK, NORMAL));
Piece * p;
// Create and place black pieces
for(int i = 0 ; i < 12 ; ++i) {
p = fac.create("BlackDraught");
p->setPosition((position_t){(i < 4 || i > 7) ? 2 * (i % 4) + 1 : 2 * (i % 4), i / 4});
db_.addPiece(*p);
blackPieces_[p->getID()] = p;
}
// Same thing for the white pieces
for(int i = 0 ; i < 12 ; ++i) {
p = fac.create("WhiteDraught");
p->setPosition((position_t){(i >= 4 && i <= 7) ? 2 * (i % 4) + 1: 2 * (i % 4), i / 4 + 5});
db_.addPiece(*p);
whitePieces_[p->getID()] = p;
}
}
void Controller::move(const position_t & inSrc, const position_t & inDst) throw(SquareNotEmpty, SquareEmpty, std::out_of_range, WrongPlayer, NotReachableSquare, IllegalMove) {
bool throwError = false;
position_t pieceToEat;
// Verify that the destination is reachable by the Piece
if(pieceCanReachPosition(*db_.getPiece(inSrc), inDst)) {
db_.move(inSrc, inDst);
} else {
// The position is perhaps reachable by eating an ennemy piece.
position_t diff = {inDst.i - inSrc.i, inDst.j - inSrc.j};
if(abs(diff.i) == 2) {
pieceToEat.i = inSrc.i + diff.i / 2;
if(((DraughtPiece*)db_.getPiece(inSrc))->getState() == SUPER) {
if(abs(diff.j) == 2) {
pieceToEat.j = inSrc.j + diff.j / 2;
} else {
throwError = true;
}
} else if( db_.getPiece(inSrc)->getColor() == WHITE) {
if(diff.j == -2) {
pieceToEat.j = inSrc.j - 1;
} else {
throwError = true;
}
} else {
// The Piece is black
if(diff.j == 2) {
pieceToEat.j = inSrc.j + 1;
} else {
throwError = true;
}
}
} else {
throwError = true;
}
if(throwError) {
throw NotReachableSquare("The square is not reachable by the Piece.");
}
if(db_.isFree(pieceToEat)) {
throw IllegalMove("You cannot reach this square.");
}
if(db_.getPiece(pieceToEat)->getColor() == db_.getPiece(inSrc)->getColor()) {
throw IllegalMove("You cannot eat a Piece of the same color.");
}
// Delete the eaten Piece and make the move
int id = db_.getPiece(pieceToEat)->getID();
if(db_.getPiece(pieceToEat)->getColor() == WHITE) {
delete whitePieces_[id];
whitePieces_.erase(id);
} else {
delete blackPieces_[id];
blackPieces_.erase(id);
}
db_.deletePiece(pieceToEat);
db_.move(inSrc, inDst);
}
// Check the state of the Piece
if((inDst.j == 0 || inDst.j == DB_LENGTH - 1) && ((DraughtPiece *)db_.getPiece(inDst))->getState() == NORMAL) {
((DraughtPiece *)db_.getPiece(inDst))->setState(SUPER);
}
// Change player
next_ = !next_;
}
bool Controller::pieceCanReachPosition(const Piece & inPiece, const position_t & inPos) const {
std::vector<position_t> reachablePositions = inPiece.getReachablePosition();
bool find = false;
for(std::vector<position_t>::const_iterator it = reachablePositions.begin() ; it != reachablePositions.end() && !find ; ++it) {
if(it->i == inPos.i && it->j == inPos.j) {
find = true;
}
}
return find;
}
/*void Controller::display() {
setCentralWidget(db_.draw());
}*/
bool Controller::isEnd() const {
return blackPieces_.size() == 0 || whitePieces_.size() == 0;
}
int Controller::getBlackPiecesNumber() const {
return blackPieces_.size();
}
int Controller::getWhitePiecesNumber() const {
return whitePieces_.size();
}
void Controller::getClicked(position_t pos){
try {
treatGUIEvent(pos);
} catch(const SquareEmpty & sqee) {
QMessageBox::about(this, "Error", sqee.what());
squareSelected_ = (position_t){-1, -1};
} catch(const WrongPlayer & wpe) {
QMessageBox::about(this, "Error", wpe.what());
squareSelected_ = (position_t){-1, -1};
} catch(const SquareNotEmpty & sqnee){
QMessageBox::about(this, "Error", sqnee.what());
squareSelected_ = (position_t){-1, -1};
}
if(isEnd()) {
if(getBlackPiecesNumber() == 0) {
QMessageBox::about(this, "Congratulations", "White player win the game !");
} else {
QMessageBox::about(this, "Congratulations", "Black player win the game !");
}
// Close the window
close();
}
}
void Controller::treatGUIEvent(position_t pos) throw(SquareEmpty, WrongPlayer, SquareNotEmpty) {
if(isPieceSelected()) {
if(!db_.isFree(pos)) {
throw SquareNotEmpty("The destination square must be unoccuped.");
}
// Do the move
try {
move(squareSelected_, pos);
} catch(const NotReachableSquare & nrsqe) {
QMessageBox::about(this, "Error", nrsqe.what());
squareSelected_ = (position_t) {-1, -1};
} catch(const IllegalMove & ime) {
QMessageBox::about(this, "Error", ime.what());
squareSelected_ = (position_t) {-1, -1};
}
// Unselect square
squareSelected_ = (position_t){-1, -1};
} else {
// Verify that the source position contains a Piece
if(db_.isFree(pos)) {
std::string tmp = "You must select a " + (std::string)((next_ == WHITE)? "white" : "black") + " piece to move.";
throw SquareEmpty(tmp.c_str());
}
// Verify that the source position contains a Piece which can move this turn
if(db_.getPiece(pos)->getColor() != next_) {
std::string tmp = "It is not your turn to play, you must move a " + (std::string)((next_ == WHITE)? "white" : "black") + " piece.";
throw WrongPlayer(tmp.c_str());
}
squareSelected_ = pos;
}
// Update GUI
setCentralWidget(db_.draw());
}
bool Controller::isPieceSelected() const {
return squareSelected_.i != - 1 && squareSelected_.j != -1;
}
|
#include "Cube.h"
// public
Cube::Cube()
{
mVertexData.clear();
mIndexData.clear();
}
Cube::~Cube()
{
mIndexData.clear();
mVertexData.clear();
}
void Cube::Initialize()
{
mInstanced = false;
mTessellated = false;
mInputLayoutSize = sizeof(IL_PosTexNor);
InitializeData();
InitializeBuffer();
}
void Cube::SetBuffer()
{
SetWorldBuffer();
}
// private
void Cube::InitializeData()
{
GetInputLayoutFromFile(L"Cube");
mVertexData.resize(mVertexCount);
mIndexData.resize(mIndexCount);
for (UINT i = 0; i < mVertexCount; i++)
{
mVertexData[i] = mTempData[i];
mIndexData[i] = i;
}
}
void Cube::InitializeBuffer()
{
CreateBuffer
(
D3D.GetDevice(),
D3D11_BIND_VERTEX_BUFFER,
sizeof(IL_PosTexNor) * mVertexCount,
D3D11_USAGE_IMMUTABLE,
&mVertexData[0],
&mVertexBuffer
);
CreateBuffer
(
D3D.GetDevice(),
D3D11_BIND_INDEX_BUFFER,
sizeof(UINT) * mIndexCount,
D3D11_USAGE_IMMUTABLE,
&mIndexData[0],
&mIndexBuffer
);
}
|
#include <iostream>
using namespace std;
#include <stdlib.h>
#include<conio.h>
double avg=0;//统计总分和加平均分权
const int mathp=4;//数学学分
const int cppp=5;//C++学分
const int sum=70;//设置总学分
class Student
{
private:
int num;
char *name;
char *sex;
char *phone;
char *rphone;
double math;
double cpp;
Student* next;
public:
Student()
{next=NULL;}
~Student();
void Push(Student **refhead,int num,char *name,char *sex,char *phone,char *rphone,double math,double cpp);
void Delete(Student *head,int data);
Student* Find(Student* head,int data);
void Display(Student* head);
int Length(Student* head);
void Math(Student* head,int data);
void Update(Student* head,int data);
void Insert();
};
Student* head=new Student;//带头结点的头指针
void Student::Push(Student **refhead,int num,char *name,char *sex,char *phone,char *rphone,double math,double cpp)
{
Student* newnode=new Student;//新增加结点
newnode->num=num;
newnode->name=name;
newnode->sex=sex;
newnode->phone=phone;
newnode->rphone=rphone;
newnode->math=math;
newnode->cpp=cpp;
newnode->next=*refhead;
*refhead=newnode;//重置表头
}
//遍历
void Student::Display(Student* head)
{
Student* temp;
temp=head;
if(temp->next==NULL)//判断空表
cout<<"没有学生!";
else
{while(temp!=NULL)//
{
cout<<"学号:"<<temp->num<<"姓名:"<<temp->name<<"性别:"<<temp->sex<<"手机:"<<temp->phone<<"宿舍电话:"<<temp->rphone<<"数学成绩:"<<temp->math<<"C++成绩:"<<temp->cpp<<endl;
temp=temp->next;
}
}
return;
}
//人数
int Student::Length(Student* head)
{
Student* cur;
cur=head;
int count=0;
while(cur!=NULL)
{
count++;//通过累加统计人数
cur=cur->next;
}
return count;
}
//查找
Student* Student::Find(Student* head,int data)
{
Student* cur=head;
bool bo=false;
while(cur!=NULL)
{
if(cur->num=data)
{
bo=true;//如果找到则改变bo的值
cout<<"学号:"<<cur->num<<"姓名:"<<cur->name<<"性别:"<<cur->sex<<"手机:"<<cur->phone<<"宿舍电话:"<<cur->rphone<<"数学成绩:"<<cur->math<<"C++成绩:"<<cur->cpp<<endl;
break;
}
cur=cur->next;
}
if(bo==false)//通过判断bo的值判断找到与否
cout<<"没有这个人!"<<endl;
return cur;
}
//删除
void Student::Delete(Student* head,int data)
{
Student *bef,*cur;
bef=cur=head;
while(cur!=NULL)
{
if(cur->num==data)
break;
else
{bef=cur;cur=cur->next;}
}
if(cur==head)//如果是头结点则删除头结点
{
head=cur->next;
delete cur;
}
else
{
bef->next=cur->next;
delete cur;
}
}
//修改
void Student::Update(Student* head,int data)
{
Student* cur=head;
bool bo=false;
while(cur!=NULL)
{
if(cur->num==data)
{
bo=true;
int a,b;
char *c;
double d;
for(;;) //找到后提供各字段的修改
{ cout<<"1修改学号|2修改姓名|3修改性别|4修改手机号|5修改宿舍电话号|6修改数学成绩|7修改C++成绩|8退出\n";
cin>>a;
switch(a)
{
case 1:cout<<"输入新学号:";
cin>>b;
cur->num=a;
break;
case 2:cout<<"输入新姓名:";
cin>>c;
cur->name=c;
break;
case 3:cout<<"输入新性别:";
cin>>c;
cur->sex=c;
break;
case 4:cout<<"输入新手机号:";
cin>>c;
cur->phone=c;
break;
case 5:cout<<"输入新宿舍电话号:";
cin>>c;
cur->rphone=c;
break;
case 6:cout<<"输入新数学成绩:";
cin>>d;
cur->math=d;
break;
case 7:cout<<"输入C++成绩:";
cin>>d;
cur->cpp=d;
break;
case 8:exit(1);
break;
default:cout<<"操作错误";
break;
}
}
break;
}
}
if(bo==false)
cout<<"没有这个人!"<<endl;
return;
}
//统计
void Student::Math(Student* head,int data)
{
Student* cur=head;
bool bo=false;
while(cur!=NULL)
{
if(cur->num=data)
{
bo=true;
avg=cur->math*(mathp/sum)+cur->cpp*(cppp/sum);//计算总分和加平均分权的公式
break;
}
cur=cur->next;
}
if(bo==false){
cout<<"没有这个人!"<<endl;
return;
}
cout<<"该生的总分和加平均分权="<<avg<<endl;
return;
}
//录入
void Student::Insert()
{
head=NULL;
int num;
char name[8];
char sex[4];
char phone[11];
char rphone[7];
double math;
double cpp;
cout<<"请输入基本信息:\n";
cout<<"学号:";
cin>>num;
cout<<"姓名:";
cin>>name;
cout<<"性别:";
cin>>sex;
cout<<"手机号:";
cin>>phone;
cout<<"宿舍电话:";
cin>>rphone;
cout<<"数学成绩:";
cin>>math;
cout<<"C++成绩:";
cin>>cpp;
Push(&head,num,name,sex,phone,rphone,math,cpp);//调用函数Push建立有序链表
}
//用释构函数逐个释放空间
Student::~Student()
{
while(head!=NULL)
{
delete head;
head=head->next;
}
}
//程序主入口
int main()
{
for(;;)
{
head=NULL;
Student s;
int x;
int data;
cout<<"|1录入|2查找|3删除|4修改|5统计|6退出|\n";
cout<<"请作选择:\n";
cin>>x;
switch(x)
{
case 1:
start:
s.Insert();
cout<<"继续吗?[Y/N]";
char ch;
cin>>ch;
if(ch=='y' || ch=='Y')
goto start;
s.Display(head);
int l;
l=s.Length(head);
cout<<"一共有"<<l<<"个学生。"<<endl;
break;
case 2:
cout<<"请输入你要查找的学生的学号:";
cin>>data;
s.Find(head,data);
break;
case 3:
cout<<"请输入你要删除的学生的学号:";
cin>>data;
s.Delete(head,data);
break;
case 4:
cout<<"请输入你要修改的学生的学号:";
cin>>data;
s.Update(head,data);
break;
case 5:
cout<<"请输入你要统计的学生的学号:";
cin>>data;
s.Math(head,data);
break;
case 6:
exit(1);
break;
default:cout<<"操作错误!"<<endl;
break;
}
}
getch();
}
|
#pragma once
#include <string>
class UDPReceiver
{
public:
UDPReceiver(uint16_t port, const std::string& networkInterface="", const std::string& multicastGroup="" , int timeout = 1000 );
virtual ~UDPReceiver();
virtual int receive(uint8_t *buffer, uint32_t bufferSize);
private:
int _timeout;
int _fd;
uint16_t _port;
std::string _address;
std::string _networkInterface;
protected:
};
|
#pragma once
#include "qwidget.h"
class CHisto : public QWidget
{
Q_OBJECT
public:
CHisto(QWidget *parent);
~CHisto();
private:
//Pour ne pas commencer a tracer en 0,0
QPoint m_commencer;
int * m_nTab;
int m_nMaxi ;
int m_nCoul ; // 0 = Noir, 1= Red, 2 = Green, 3= Bleu
public:
void setHisto( int * Tab, int Maxi, int Coul) ;
protected:
void paintEvent(QPaintEvent * evt) ;
};
|
class LandRover_CZ_EP1;
class LandRover_CZ_EP1_DZE: LandRover_CZ_EP1 {
scope = 2;
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_DESERT";
vehicleClass = "DayZ Epoch Vehicles";
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
class Turrets {};
transportMaxWeapons = 15;
transportMaxMagazines = 70;
transportmaxbackpacks = 4;
class HitPoints;
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
class HitGlass2;
class HitGlass3;
supplyRadius = 1.2;
class Upgrades {
ItemORP[] = {"LandRover_CZ_EP1_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",2},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class LandRover_CZ_EP1_DZE1: LandRover_CZ_EP1_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_DESERT+";
original = "LandRover_CZ_EP1_DZE";
maxspeed = 160;
terrainCoef = 1.5;
class Upgrades {
ItemAVE[] = {"LandRover_CZ_EP1_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",6},{"ItemScrews",4}}};
};
};
class LandRover_CZ_EP1_DZE2: LandRover_CZ_EP1_DZE1 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_DESERT++";
armor = 60;
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.65;
};
class HitLBWheel: HitLBWheel {
armor = 0.65;
};
class HitRFWheel: HitRFWheel {
armor = 0.65;
};
class HitRBWheel: HitRBWheel {
armor = 0.65;
};
class HitFuel: HitFuel {
armor = 1.5;
};
class HitEngine: HitEngine {
armor = 2.5;
};
class HitGlass1: HitGlass1 {
armor = 0.25;
};
};
class Upgrades {
ItemLRK[] = {"LandRover_CZ_EP1_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class LandRover_CZ_EP1_DZE3: LandRover_CZ_EP1_DZE2 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_DESERT+++";
transportMaxWeapons = 30;
transportMaxMagazines = 140;
transportmaxbackpacks = 8;
class Upgrades {
ItemTNK[] = {"LandRover_CZ_EP1_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
};
};
class LandRover_CZ_EP1_DZE4: LandRover_CZ_EP1_DZE3 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_DESERT++++";
fuelCapacity = 250;
};
class LandRover_TK_CIV_EP1_DZE: LandRover_CZ_EP1_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_RED";
hiddenSelections[] = {"Camo1"};
hiddenSelectionsTextures[] = {"\ca\wheeled_E\LR\Data\LR_Base_red_CO.paa"};
class HitPoints;
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
class HitGlass2;
class HitGlass3;
class Upgrades {
ItemORP[] = {"LandRover_TK_CIV_EP1_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",2},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class LandRover_TK_CIV_EP1_DZE1: LandRover_TK_CIV_EP1_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_RED+";
original = "LandRover_TK_CIV_EP1_DZE";
maxspeed = 160;
terrainCoef = 1.5;
class Upgrades {
ItemAVE[] = {"LandRover_TK_CIV_EP1_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",6},{"ItemScrews",4}}};
};
};
class LandRover_TK_CIV_EP1_DZE2: LandRover_TK_CIV_EP1_DZE1 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_RED++";
armor = 60;
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.65;
};
class HitLBWheel: HitLBWheel {
armor = 0.65;
};
class HitRFWheel: HitRFWheel {
armor = 0.65;
};
class HitRBWheel: HitRBWheel {
armor = 0.65;
};
class HitFuel: HitFuel {
armor = 1.5;
};
class HitEngine: HitEngine {
armor = 2.5;
};
class HitGlass1: HitGlass1 {
armor = 0.25;
};
};
class Upgrades {
ItemLRK[] = {"LandRover_TK_CIV_EP1_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class LandRover_TK_CIV_EP1_DZE3: LandRover_TK_CIV_EP1_DZE2 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_RED+++";
transportMaxWeapons = 30;
transportMaxMagazines = 140;
transportmaxbackpacks = 8;
class Upgrades {
ItemTNK[] = {"LandRover_TK_CIV_EP1_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
};
};
class LandRover_TK_CIV_EP1_DZE4: LandRover_TK_CIV_EP1_DZE3 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_RED++++";
fuelCapacity = 250;
};
class LandRover_ACR_DZE: LandRover_CZ_EP1_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_WOODLAND";
model = "\Ca\Wheeled_ACR\LR\LR_ACR.p3d";
class HitPoints;
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
class HitGlass2;
class HitGlass3;
class Upgrades {
ItemORP[] = {"LandRover_ACR_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",2},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class LandRover_ACR_DZE1: LandRover_ACR_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_WOODLAND+";
original = "LandRover_ACR_DZE";
maxspeed = 160;
terrainCoef = 1.5;
class Upgrades {
ItemAVE[] = {"LandRover_ACR_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",6},{"ItemScrews",4}}};
};
};
class LandRover_ACR_DZE2: LandRover_ACR_DZE1 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_WOODLAND++";
armor = 60;
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.65;
};
class HitLBWheel: HitLBWheel {
armor = 0.65;
};
class HitRFWheel: HitRFWheel {
armor = 0.65;
};
class HitRBWheel: HitRBWheel {
armor = 0.65;
};
class HitFuel: HitFuel {
armor = 1.5;
};
class HitEngine: HitEngine {
armor = 2.5;
};
class HitGlass1: HitGlass1 {
armor = 0.25;
};
};
class Upgrades {
ItemLRK[] = {"LandRover_ACR_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class LandRover_ACR_DZE3: LandRover_ACR_DZE2 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_WOODLAND+++";
transportMaxWeapons = 30;
transportMaxMagazines = 140;
transportmaxbackpacks = 8;
class Upgrades {
ItemTNK[] = {"LandRover_ACR_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
};
};
class LandRover_ACR_DZE4: LandRover_ACR_DZE3 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_WOODLAND++++";
fuelCapacity = 250;
};
class LandRover_Ambulance_ACR_DZE: LandRover_ACR_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_MEDIC_WOODLAND";
model = "\Ca\Wheeled_ACR\LR\LR_AMB_ACR";
hiddenSelections[] = {"camo2"};
hiddenSelectionsTextures[] = {"\ca\wheeled_acr\lr\data\lr_amb_ext_co.paa"};
attendant = 0;
class Damage
{
tex[] = {};
mat[] = {"ca\wheeled_acr\lr\data\lr_amb_ext.rvmat","ca\wheeled_acr\lr\data\lr_amb_ext_damage.rvmat","ca\wheeled_acr\lr\data\lr_amb_ext_destruct.rvmat","ca\wheeled_E\LR\Data\LR_base.rvmat","ca\wheeled_E\LR\Data\LR_base_damage.rvmat","ca\wheeled_E\LR\Data\LR_base_destruct.rvmat","ca\wheeled_E\LR\Data\LR_glass.rvmat","ca\wheeled_E\LR\Data\LR_glass_damage.rvmat","ca\wheeled_E\LR\Data\LR_glass_destruct.rvmat","ca\wheeled_E\LR\Data\LR_Special.rvmat","ca\wheeled_E\LR\Data\LR_Special_damage.rvmat","ca\wheeled_E\LR\Data\LR_Special_destruct.rvmat","Ca\Ca_E\data\default.rvmat","Ca\Ca_E\data\default.rvmat","Ca\Ca_E\data\default_destruct.rvmat"};
};
class Upgrades {
ItemORP[] = {"LandRover_Ambulance_ACR_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",2},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class LandRover_Ambulance_ACR_DZE1: LandRover_Ambulance_ACR_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_MEDIC_WOODLAND+";
original = "LandRover_Ambulance_ACR_DZE";
maxspeed = 160;
terrainCoef = 1.5;
class Upgrades {
ItemAVE[] = {"LandRover_Ambulance_ACR_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",6},{"ItemScrews",4}}};
};
};
class LandRover_Ambulance_ACR_DZE2: LandRover_Ambulance_ACR_DZE1 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_MEDIC_WOODLAND++";
armor = 60;
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.65;
};
class HitLBWheel: HitLBWheel {
armor = 0.65;
};
class HitRFWheel: HitRFWheel {
armor = 0.65;
};
class HitRBWheel: HitRBWheel {
armor = 0.65;
};
class HitFuel: HitFuel {
armor = 1.5;
};
class HitEngine: HitEngine {
armor = 2.5;
};
class HitGlass1: HitGlass1 {
armor = 0.25;
};
};
class Upgrades {
ItemLRK[] = {"LandRover_Ambulance_ACR_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class LandRover_Ambulance_ACR_DZE3: LandRover_Ambulance_ACR_DZE2 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_MEDIC_WOODLAND+++";
transportMaxWeapons = 30;
transportMaxMagazines = 140;
transportmaxbackpacks = 8;
class Upgrades {
ItemTNK[] = {"LandRover_Ambulance_ACR_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
};
};
class LandRover_Ambulance_ACR_DZE4: LandRover_Ambulance_ACR_DZE3 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_MEDIC_WOODLAND++++";
fuelCapacity = 250;
};
class LandRover_Ambulance_Des_ACR_DZE: LandRover_Ambulance_ACR_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_MEDIC_DESERT";
hiddenSelectionsTextures[] = {"\ca\wheeled_acr\lr\data\lr_amb_ext_desert_co.paa"};
class Upgrades {
ItemORP[] = {"LandRover_Ambulance_Des_ACR_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",2},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class LandRover_Ambulance_Des_ACR_DZE1: LandRover_Ambulance_Des_ACR_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_MEDIC_DESERT+";
original = "LandRover_Ambulance_Des_ACR_DZE";
maxspeed = 160;
terrainCoef = 1.5;
class Upgrades {
ItemAVE[] = {"LandRover_Ambulance_Des_ACR_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",6},{"ItemScrews",4}}};
};
};
class LandRover_Ambulance_Des_ACR_DZE2: LandRover_Ambulance_Des_ACR_DZE1 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_MEDIC_DESERT++";
armor = 60;
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.65;
};
class HitLBWheel: HitLBWheel {
armor = 0.65;
};
class HitRFWheel: HitRFWheel {
armor = 0.65;
};
class HitRBWheel: HitRBWheel {
armor = 0.65;
};
class HitFuel: HitFuel {
armor = 1.5;
};
class HitEngine: HitEngine {
armor = 2.5;
};
class HitGlass1: HitGlass1 {
armor = 0.25;
};
};
class Upgrades {
ItemLRK[] = {"LandRover_Ambulance_Des_ACR_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class LandRover_Ambulance_Des_ACR_DZE3: LandRover_Ambulance_Des_ACR_DZE2 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_MEDIC_DESERT+++";
transportMaxWeapons = 30;
transportMaxMagazines = 140;
transportmaxbackpacks = 8;
class Upgrades {
ItemTNK[] = {"LandRover_Ambulance_Des_ACR_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
};
};
class LandRover_Ambulance_Des_ACR_DZE4: LandRover_Ambulance_Des_ACR_DZE3 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_MEDIC_DESERT++++";
fuelCapacity = 250;
};
class BAF_Offroad_D_DZE: LandRover_CZ_EP1_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_DESERT";
model = "ca\wheeled_d_baf\LR_covered_soft_BAF";
transportMaxWeapons = 15;
transportMaxMagazines = 70;
transportmaxbackpacks = 4;
class HitPoints;
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
class HitGlass2;
class HitGlass3;
class Damage
{
tex[] = {};
mat[] = {"ca\wheeled_d_baf\Data\LR_base_baf.rvmat","ca\wheeled_d_baf\Data\LR_base_baf_damage.rvmat","ca\wheeled_d_baf\Data\LR_base_baf_destruct.rvmat","ca\wheeled_d_baf\Data\LR_glass_baf.rvmat","ca\wheeled_d_baf\Data\LR_glass_baf_damage.rvmat","ca\wheeled_d_baf\Data\LR_glass_baf_destruct.rvmat","ca\wheeled_d_baf\Data\LR_Special_baf.rvmat","ca\wheeled_d_baf\Data\LR_Special_baf_damage.rvmat","ca\wheeled_d_baf\Data\LR_Special_baf_destruct.rvmat"};
};
class Upgrades {
ItemORP[] = {"BAF_Offroad_D_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",2},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class BAF_Offroad_D_DZE1: BAF_Offroad_D_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_DESERT+";
original = "BAF_Offroad_D_DZE";
maxspeed = 160;
terrainCoef = 1.5;
class Upgrades {
ItemAVE[] = {"BAF_Offroad_D_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",6},{"ItemScrews",4}}};
};
};
class BAF_Offroad_D_DZE2: BAF_Offroad_D_DZE1 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_DESERT++";
armor = 60;
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.65;
};
class HitLBWheel: HitLBWheel {
armor = 0.65;
};
class HitRFWheel: HitRFWheel {
armor = 0.65;
};
class HitRBWheel: HitRBWheel {
armor = 0.65;
};
class HitFuel: HitFuel {
armor = 1.5;
};
class HitEngine: HitEngine {
armor = 2.5;
};
class HitGlass1: HitGlass1 {
armor = 0.25;
};
};
class Upgrades {
ItemLRK[] = {"BAF_Offroad_D_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class BAF_Offroad_D_DZE3: BAF_Offroad_D_DZE2 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_DESERT+++";
transportMaxWeapons = 30;
transportMaxMagazines = 140;
transportmaxbackpacks = 8;
class Upgrades {
ItemTNK[] = {"BAF_Offroad_D_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
};
};
class BAF_Offroad_D_DZE4: BAF_Offroad_D_DZE3 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_DESERT++++";
fuelCapacity = 250;
};
class BAF_Offroad_W_DZE: BAF_Offroad_D_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_WOODLAND";
model = "ca\wheeled_w_baf\LR_covered_soft_W_BAF";
class HitPoints;
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
class HitGlass2;
class HitGlass3;
class Upgrades {
ItemORP[] = {"BAF_Offroad_W_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",2},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class BAF_Offroad_W_DZE1: BAF_Offroad_W_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_WOODLAND+";
original = "BAF_Offroad_W_DZE";
maxspeed = 160;
terrainCoef = 1.5;
class Upgrades {
ItemAVE[] = {"BAF_Offroad_W_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",6},{"ItemScrews",4}}};
};
};
class BAF_Offroad_W_DZE2: BAF_Offroad_W_DZE1 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_WOODLAND++";
armor = 60;
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.65;
};
class HitLBWheel: HitLBWheel {
armor = 0.65;
};
class HitRFWheel: HitRFWheel {
armor = 0.65;
};
class HitRBWheel: HitRBWheel {
armor = 0.65;
};
class HitFuel: HitFuel {
armor = 1.5;
};
class HitEngine: HitEngine {
armor = 2.5;
};
class HitGlass1: HitGlass1 {
armor = 0.25;
};
};
class Upgrades {
ItemLRK[] = {"BAF_Offroad_W_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class BAF_Offroad_W_DZE3: BAF_Offroad_W_DZE2 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_WOODLAND+++";
transportMaxWeapons = 30;
transportMaxMagazines = 140;
transportmaxbackpacks = 8;
class Upgrades {
ItemTNK[] = {"BAF_Offroad_W_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
};
};
class BAF_Offroad_W_DZE4: BAF_Offroad_W_DZE3 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_WOODLAND++++";
fuelCapacity = 250;
};
class LandRover_Special_CZ_EP1;
class LandRover_Special_CZ_EP1_DZ: LandRover_Special_CZ_EP1
{
scope = 2;
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_SPECIAL";
vehicleClass = "DayZ Epoch Vehicles";
class Turrets;
class MainTurret;
class AGS30_Turret;
class PK_Turret;
class ViewOptics;
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
transportMaxWeapons = 15;
transportMaxMagazines = 70;
transportmaxbackpacks = 4;
class HitPoints;
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
supplyRadius = 1.2;
};
class LandRover_Special_CZ_EP1_DZE: LandRover_Special_CZ_EP1_DZ
{
class Turrets: Turrets
{
class AGS30_Turret: MainTurret
{
discreteDistance[] = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300};
discreteDistanceInitIndex = 2;
turretInfoType = "RscWeaponZeroing";
body = "mainTurret";
gun = "mainGun";
gunnerForceOptics = 0;
gunnerOutOpticsShowCursor = 0;
weapons[] = {"AGS30"};
magazines[] = {};
soundServo[] = {"\ca\sounds\vehicles\servos\turret-1",0.0316228,1,15};
gunnerAction = "LR_Gunner01_EP1";
gunnerInAction = "LR_Gunner01_EP1";
ejectDeadGunner = 1;
gunnerOpticsModel = "\ca\weapons\optika_AGS30";
stabilizedInAxes = "StabilizedInAxesNone";
minElev = -18;
class ViewOptics : ViewOptics
{
initFov = 0.1;
maxFov = 0.1;
minFov = 0.1;
};
};
class PK_Turret: MainTurret
{
discreteDistance[] = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500};
discreteDistanceInitIndex = 2;
gunnerName = "$STR_POSITION_COMMANDER";
primaryGunner = 0;
primaryObserver = 1;
commanding = 2;
body = "mainTurret_2";
gun = "mainGun_2";
animationSourceBody = "mainTurret_2";
animationSourceGun = "mainGun_2";
proxyIndex = 2;
gunBeg = "usti hlavne_2";
gunEnd = "konec hlavne_2";
memoryPointGunnerOptics = "gunnerview_2";
minElev = -18;
maxElev = 40;
minTurn = -45;
maxTurn = 45;
initTurn = 0;
gunnerOpticsModel = "\ca\Weapons\optika_empty";
gunnerForceOptics = 0;
turretInfoType = "RscWeaponZeroing";
weapons[] = {"PKTBC"};
magazines[] = {};
soundServo[] = {};
gunnerAction = "LR_Gunner02_EP1";
gunnerInAction = "LR_Gunner02_EP1";
ejectDeadGunner = 1;
stabilizedInAxes = "StabilizedInAxesNone";
memoryPointsGetInGunner = "pos codriver";
memoryPointsGetInGunnerDir = "pos codriver dir";
};
};
class Upgrades {
ItemORP[] = {"LandRover_Special_CZ_EP1_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",2},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class LandRover_Special_CZ_EP1_DZE1: LandRover_Special_CZ_EP1_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_SPECIAL+";
original = "LandRover_Special_CZ_EP1_DZE";
maxspeed = 160;
terrainCoef = 1.5;
class Upgrades {
ItemAVE[] = {"LandRover_Special_CZ_EP1_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",6},{"ItemScrews",4}}};
};
};
class LandRover_Special_CZ_EP1_DZE2: LandRover_Special_CZ_EP1_DZE1 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_SPECIAL++";
armor = 60;
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.65;
};
class HitLBWheel: HitLBWheel {
armor = 0.65;
};
class HitRFWheel: HitRFWheel {
armor = 0.65;
};
class HitRBWheel: HitRBWheel {
armor = 0.65;
};
class HitFuel: HitFuel {
armor = 1.5;
};
class HitEngine: HitEngine {
armor = 2.5;
};
class HitGlass1: HitGlass1 {
armor = 0.25;
};
};
class Upgrades {
ItemLRK[] = {"LandRover_Special_CZ_EP1_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class LandRover_Special_CZ_EP1_DZE3: LandRover_Special_CZ_EP1_DZE2 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_SPECIAL+++";
transportMaxWeapons = 30;
transportMaxMagazines = 140;
transportmaxbackpacks = 8;
class Upgrades {
ItemTNK[] = {"LandRover_Special_CZ_EP1_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
};
};
class LandRover_Special_CZ_EP1_DZE4: LandRover_Special_CZ_EP1_DZE3 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_SPECIAL++++";
fuelCapacity = 250;
};
class LandRover_MG_TK_EP1;
class LandRover_MG_TK_EP1_DZ: LandRover_MG_TK_EP1
{
scope = 2;
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_M2";
vehicleClass = "DayZ Epoch Vehicles";
class Turrets;
class MainTurret;
transportMaxWeapons = 15;
transportMaxMagazines = 70;
transportmaxbackpacks = 4;
class HitPoints;
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
supplyRadius = 1.2;
};
class LandRover_MG_TK_EP1_DZE: LandRover_MG_TK_EP1_DZ
{
class Turrets: Turrets
{
class MainTurret: MainTurret
{
magazines[] = {};
};
};
class Upgrades {
ItemORP[] = {"LandRover_MG_TK_EP1_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",2},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class LandRover_MG_TK_EP1_DZE1: LandRover_MG_TK_EP1_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_M2+";
original = "LandRover_MG_TK_EP1_DZE";
maxspeed = 160;
terrainCoef = 1.5;
class Upgrades {
ItemAVE[] = {"LandRover_MG_TK_EP1_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",6},{"ItemScrews",4}}};
};
};
class LandRover_MG_TK_EP1_DZE2: LandRover_MG_TK_EP1_DZE1 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_M2++";
armor = 60;
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.65;
};
class HitLBWheel: HitLBWheel {
armor = 0.65;
};
class HitRFWheel: HitRFWheel {
armor = 0.65;
};
class HitRBWheel: HitRBWheel {
armor = 0.65;
};
class HitFuel: HitFuel {
armor = 1.5;
};
class HitEngine: HitEngine {
armor = 2.5;
};
class HitGlass1: HitGlass1 {
armor = 0.25;
};
};
class Upgrades {
ItemLRK[] = {"LandRover_MG_TK_EP1_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class LandRover_MG_TK_EP1_DZE3: LandRover_MG_TK_EP1_DZE2 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_M2+++";
transportMaxWeapons = 30;
transportMaxMagazines = 140;
transportmaxbackpacks = 8;
class Upgrades {
ItemTNK[] = {"LandRover_MG_TK_EP1_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
};
};
class LandRover_MG_TK_EP1_DZE4: LandRover_MG_TK_EP1_DZE3 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_M2++++";
fuelCapacity = 250;
};
class LandRover_SPG9_TK_EP1;
class LandRover_SPG9_TK_EP1_DZ: LandRover_SPG9_TK_EP1
{
scope = 2;
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_SPG9";
vehicleClass = "DayZ Epoch Vehicles";
class Turrets;
class MainTurret;
transportMaxWeapons = 15;
transportMaxMagazines = 70;
transportmaxbackpacks = 4;
class HitPoints;
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
supplyRadius = 1.2;
};
class LandRover_SPG9_TK_EP1_DZE: LandRover_SPG9_TK_EP1_DZ
{
class Turrets: Turrets
{
class MainTurret: MainTurret
{
magazines[] = {};
};
};
class Upgrades {
ItemORP[] = {"LandRover_SPG9_TK_EP1_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",2},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class LandRover_SPG9_TK_EP1_DZE1: LandRover_SPG9_TK_EP1_DZE {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_SPG9+";
original = "LandRover_SPG9_TK_EP1_DZE";
maxspeed = 160;
terrainCoef = 1.5;
class Upgrades {
ItemAVE[] = {"LandRover_SPG9_TK_EP1_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",6},{"ItemScrews",4}}};
};
};
class LandRover_SPG9_TK_EP1_DZE2: LandRover_SPG9_TK_EP1_DZE1 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_SPG9++";
armor = 60;
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.65;
};
class HitLBWheel: HitLBWheel {
armor = 0.65;
};
class HitRFWheel: HitRFWheel {
armor = 0.65;
};
class HitRBWheel: HitRBWheel {
armor = 0.65;
};
class HitFuel: HitFuel {
armor = 1.5;
};
class HitEngine: HitEngine {
armor = 2.5;
};
class HitGlass1: HitGlass1 {
armor = 0.25;
};
};
class Upgrades {
ItemLRK[] = {"LandRover_SPG9_TK_EP1_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class LandRover_SPG9_TK_EP1_DZE3: LandRover_SPG9_TK_EP1_DZE2 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_SPG9+++";
transportMaxWeapons = 30;
transportMaxMagazines = 140;
transportmaxbackpacks = 8;
class Upgrades {
ItemTNK[] = {"LandRover_SPG9_TK_EP1_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
};
};
class LandRover_SPG9_TK_EP1_DZE4: LandRover_SPG9_TK_EP1_DZE3 {
displayname = "$STR_VEH_NAME_MILITARY_OFFROAD_SPG9++++";
fuelCapacity = 250;
};
|
#pragma once
#include <QAbstractListModel>
#include "Entities/Statistics/PassedTest/PassedTest.h"
class PassedTestModel : public QAbstractListModel {
Q_OBJECT
public:
explicit PassedTestModel(const PassedTest &passedTest, QObject *parent = nullptr);
// :: QAbstractListModel ::
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
// :: Accessors ::
const PassedTest &getPassedTest() const;
void setPassedTest(const PassedTest &passedTest);
int getTestId() const;
QString getPassedTestName() const;
uint getNumberOfPasses() const;
ScaleStatistics getScaleStatistics(const QModelIndex &index) const;
private:
PassedTest m_passedTest;
};
|
#include <iostream>
#include <queue>
using namespace std;
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
#define int long long int
#define ld long double
#define F first
#define S second
#define P pair<int,int>
#define pb push_back
#define endl '\n'
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
const int N = 9;
//int Graph[N][N];
int dis[N][N];
const int inf = 1e18;
#define node pair<int,P>
int row[] = { -2, 2, -1, 1, -1, 1, -2, 2};
int col[] = {1, 1, 2, 2, -2, -2, -1, -1};
bool is_valid(int i, int j) {
return (i >= 0 && i < 8 && j >= 0 && j < 8);
}
void dijkstra(int sx, int sy, int ex, int ey) {
priority_queue<node, vector<node>, greater<node>> q;
q.push({0, {sx, sy}});
dis[sx][sy] = 0;
while (!q.empty()) {
node temp = q.top();
q.pop();
int p_c = temp.F;
int tx = temp.S.F;
int ty = temp.S.S;
if (p_c > dis[tx][ty])
continue;
if (tx == ex && ty == ey)
break;
for (int i = 0; i < 8; i++) {
int r = tx + row[i];
int c = ty + col[i];
int cur_cost = r * tx + c * ty;
if (is_valid(r, c) && dis[r][c] > p_c + cur_cost) {
dis[r][c] = p_c + cur_cost;
q.push({dis[r][c], {r, c}});
}
}
}
}
void solve() {
int x1, x2, y1, y2;
while (cin >> x1 >> y1 >> x2 >> y2) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
dis[i][j] = inf;
}
}
dijkstra(x1, y1, x2, y2);
if (dis[x2][y2] != inf)
cout << dis[x2][y2] << endl;
else
cout << -1 << endl;
}
return ;
}
int32_t main() {
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
//int t;cin>>t;while(t--)
solve();
return 0;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: web_client_main.cpp
* Author: ssridhar
*
* Created on October 11, 2017, 1:06 PM
*/
#include "namespace.h"
#include "Job.h"
#include "JobFactory.h"
#include "QueueFactory.h"
#include "SchedulerFactory.h"
#include "StateFactory.h"
#include "ThreadFactory.h"
#include "stdin_cb.h"
#include <signal.h>
unsigned char time_to_exit = 0;
/**
* is_webclient_alive Informs whether the current process is alive or not.
* @return
*/
int webclient::is_webclient_alive() {
return !time_to_exit;
}
/**
* INThandler catch SIGINT and shut down the process.
* @param dummy
*/
void INThandler(int dummy) {
LOG_ERROR("INThandler: Exiting...\n");
time_to_exit = 1;
}
/**
* hostname_to_ip Helper function to convert a hostname to IP address.
* @param hostname
* @param service
* @param ip
* @param ip_len
* @return ipv4 address.
*/
int hostname_to_ip(const char *hostname, char *service, char *ip, uint32_t ip_len) {
//int sockfd;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_in *h;
struct sockaddr_in6 *h6;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(hostname, service, &hints, &servinfo)) != 0) {
LOG_ERROR("getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
if (p->ai_family == AF_INET) {
h = (struct sockaddr_in *) p->ai_addr;
inet_ntop(p->ai_family, (const void *) &(h->sin_addr.s_addr), ip, (socklen_t) ip_len);
LOG_ERROR("Hostname %s Resolved to %s\n", hostname, ip);
break;
} else if (p->ai_family == AF_INET6) {
h6 = (struct sockaddr_in6 *) p->ai_addr;
inet_ntop(p->ai_family, (const void *) &(h6->sin6_addr.s6_addr[0]), ip, (socklen_t) ip_len);
LOG_ERROR("Hostname %s Resolved to %s\n", hostname, ip);
break;
} else {
LOG_ERROR("Invalid address family\n");
}
}
freeaddrinfo(servinfo); // all done with this structure, free 'er up
return 0;
}
#define DOMAIN_NAME_ADDRESS_MAX 256
/**
* convert_domain_name_to_ip_address This converts a domain name to IP address.
* @param p_IPAddr
* @return
*/
uint32_t convert_domain_name_to_ip_address(char *p_IPAddr) {
char nIPAddr[256];
int hname_lkup_rc = 0;
uint32_t ipaddress = -1;
if (strlen(p_IPAddr) < DOMAIN_NAME_ADDRESS_MAX) {
hname_lkup_rc = hostname_to_ip(p_IPAddr, NULL, nIPAddr, sizeof (nIPAddr));
if (hname_lkup_rc != 0) {
LOG_ERROR("IP name resolution failure... exiting\n");
exit(2);
}
int s = inet_pton(AF_INET, nIPAddr, &ipaddress);
if (s <= 0) {
if (s == 0)
LOG_ERROR("%s:%d ipv4 addr not in presentation format\n", __FILE__, __LINE__);
else
perror("inet_pton v4\n");
}
}
return ipaddress;
}
#define STARTING_PORT 1025
#define ENDING_PORT 64000
#define LOCAL_IP 0xfefefefe
#define REMOTE_IP 0xfefe1234
#define MAX_REMOTE_ADDRESS_LEN 200
int main(int argc, char **argv) {
// signal(SIGINT, INThandler);
initializeLogParameters("WEBCLIENT");
char threadName[10] = "MAIN";
pthread_setname_np(pthread_self(), threadName);
uint16_t local_starting_port = STARTING_PORT;
uint16_t local_ending_port = ENDING_PORT;
uint32_t local_ip_address = LOCAL_IP;
uint32_t remote_ip_address = REMOTE_IP;
char remote_address[MAX_REMOTE_ADDRESS_LEN];
char c = '\0';
while ((c = getopt(argc, argv, "d:s:e:l:r:t:")) != -1) {
switch (c) {
case 'd':
switch (atoi(optarg)) {
case 0:
setLogLevel("DEBUG");
break;
case 1:
setLogLevel("INFO");
break;
case 2:
setLogLevel("NOTICE");
break;
case 3:
setLogLevel("ERROR");
break;
default:
setLogLevel("NOTICE");
break;
}
break;
case 's':
local_starting_port = (unsigned short) atoi(optarg);
break;
case 'e':
local_ending_port = (unsigned short) atoi(optarg);
break;
case 'l':
local_ip_address = convert_domain_name_to_ip_address(optarg);
break;
case 'r':
{
char *p_IPAddr = (char *) optarg;
if (p_IPAddr && strlen(p_IPAddr) < MAX_REMOTE_ADDRESS_LEN) {
memset(remote_address, 0, MAX_REMOTE_ADDRESS_LEN);
memcpy(remote_address, p_IPAddr, strlen(p_IPAddr));
remote_ip_address = convert_domain_name_to_ip_address(optarg);
}
}
break;
case 'h':
default:
LOG_ERROR("options: [-d <dbglvl 0-DEBUG,1-INFO,2-NOTICE,3-ERROR>] [-s <starting port>] [-e <ending port>] [-l <local ipaddr>] [-r <remote ip or domain name>]\n");
exit(EXIT_FAILURE);
break;
}
}
pthread_t pthread_var;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(
&pthread_var,
&attr,
&stdin_cb_fn,
NULL);
printf("local_starting_port=%d,local_ending_port=%d,local_ip_address=%08x,remote_ip_address=%08x,remote_address=%s",
local_starting_port,
local_ending_port,
local_ip_address,
remote_ip_address,
remote_address);
webclient::Scheduler_Factory::Instance()->initialize(
local_starting_port,
local_ending_port,
local_ip_address,
remote_ip_address,
remote_address);
#if 0
webclient::Job *p_job = (webclient::Job *) calloc(1, sizeof (webclient::Job));
webclient::uint32_t length = 0;
webclient::Queue_Factory::Instance()->dequeue(webclient::State_Factory::get_init_state(),
(void **) &p_job, &length);
printf("%s:%s:%d pmsg=%p,length=%d\n", __FILE__, __FUNCTION__, __LINE__,
p_job, length);
webclient::Scheduler_Factory::Instance()->Process_this_Job(p_job);
webclient::Scheduler_Factory::Instance()->Process_this_Job(p_job);
webclient::Scheduler_Factory::Instance()->Process_this_Job(p_job);
webclient::Scheduler_Factory::Instance()->Process_this_Job(p_job);
webclient::Scheduler_Factory::Instance()->Process_this_Job(p_job);
webclient::Scheduler_Factory::Instance()->Process_this_Job(p_job);
webclient::Scheduler_Factory::Instance()->Process_this_Job(p_job);
webclient::Scheduler_Factory::Instance()->Process_this_Job(p_job);
#endif
sleep(1);
webclient::Scheduler_Factory::Instance()->run();
return 1;
}
|
#pragma once
#include "Viruss.h"
#include <list>
#include "FluViruss.h"
#include "DengueViruss.h"
using namespace std;
class Patient
{
private:
int m_resistance;
list <Viruss*> m_virusList;
int m_state;
public:
Patient();
Patient(int, list <Viruss *>, int);
~Patient();
void InitResistance();
void DoStart();
void TakeMedicine(int medicine_resistance);
void DoDie();
int GetState();
};
|
#include "stdafx.h"
#include "TypeInQuestion.h"
BOOST_AUTO_TEST_SUITE(TypeInQuestionSuite)
using namespace qp;
using namespace std;
BOOST_AUTO_TEST_CASE(Construction)
{
set<string> answers = { "First answer", "Second answer" };
CTypeInQuestion quest("Question description", answers);
BOOST_REQUIRE_EQUAL(quest.GetDescription(), "Question description");
BOOST_REQUIRE_CLOSE(quest.GetScore(), 0.0, 0.0001);
}
BOOST_AUTO_TEST_CASE(QuestionHasCorrectAnswers)
{
set<string> answers = { "First answer", "Second answer" };
CTypeInQuestion quest("Question description", answers);
set<string> const& gotAnswers = quest.GetAnswers();
BOOST_REQUIRE(answers == gotAnswers);
}
BOOST_AUTO_TEST_CASE(QuestionHasNoEmptyAnswer)
{
set<string> answers;
BOOST_REQUIRE_THROW(CTypeInQuestion quest("Question description", answers), invalid_argument);
}
BOOST_AUTO_TEST_CASE(RemoveExtraSpacesInAnswers)
{
set<string> answers1 = {" Answer with extra spaces "};
CTypeInQuestion quest1("Question description", answers1);
set<string> const& gotAnswers = quest1.GetAnswers();
set<string> const& rightAnswers = {"Answer with extra spaces"};
BOOST_REQUIRE(rightAnswers == gotAnswers);
set<string> answers2 = {" ", "Answer"};
BOOST_REQUIRE_THROW(CTypeInQuestion quest2("Question description", answers2), invalid_argument);
}
BOOST_AUTO_TEST_SUITE_END()
|
//
// Created by arnito on 4/06/17.
//
#ifndef BEAT_THE_BEAT_QUOTE1ACTOR_HPP
#define BEAT_THE_BEAT_QUOTE1ACTOR_HPP
#include "../Actor.h"
#include "../entities/Quote.h"
class Scene;
class Quote1Actor : public Actor{
public:
Quote1Actor(int playerId,Quote &q, Scene &s);
~Quote1Actor();
void update(const sf::Time& deltatime);
void action(Inputs::Key key);
private:
Quote *_quote;
};
#endif //BEAT_THE_BEAT_QUOTE1ACTOR_HPP
|
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
const char* MySSID = "ssid"; // Local Network SSID
const char* MyPASSWORD = "password"; // Local Network Password
const String PART_ID = "3";
/*****************************************************/
const char* WIFI_SSID = "MyWiFi";
const char* WIFI_PASSWORD = "MyPassword";
/*****************************************************/
const char* host = "api.thingspeak.com";
const char* privateKey = "thingspeak write key";
const int WIFI_CHANNEL = 4;
const int SERVER_PORT = 8080;
IPAddress local_IP(192,168,1,1);
IPAddress gateway(192,168,0,1);
IPAddress subnet(255,255,255,0) ;
WiFiServer WiFi_Server(SERVER_PORT);
WiFiClient WiFi_Client;
//WiFiClient client;
String data1, data2;
float c;
String Lat="-33.772875";
String Long="150.908145";
void setup()
{
Serial.begin(9600);
Serial.println();
/* Setup ESP8266 in soft-AP mode*/
WiFi.mode(WIFI_AP_STA);
Serial.println();
Serial.print("Setting soft-AP configuration ... ");
Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");
Serial.print("Setting soft-AP ... ");
Serial.println(WiFi.softAP(WIFI_SSID,WIFI_PASSWORD,WIFI_CHANNEL) ? "Ready" : "Failed!");
Serial.print("Soft-AP IP address = ");
Serial.println(WiFi.softAPIP());
/* Starting the Server */
WiFi_Server.begin();
Serial.println("Server online.");
delay(1000);
Serial.println();
//Station
// WiFi.hostname("ESP8266");
WiFi.begin(MySSID, MyPASSWORD);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("WiFi connected");
Serial.println("Local IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
}
void loop()
{
WiFi_Client = WiFi_Server.available();
if (WiFi_Client.available() > 0)
{
data1 =WiFi_Client.readStringUntil('\r');
Serial.println(data1);
c = data1.toFloat();
if (c >= 0.01){
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
const int httpPort = 80;
if (!WiFi_Client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/update";
url += "?api_key=";
url += privateKey;
url += "&field1=";
url += PART_ID;
url += "&field2=";
url += data1;
url += "&field3=";
url += Lat;
url += "&field4=";
url += Long;
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
WiFi_Client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
// Read all the lines of the reply from server and print them to Serial
while(WiFi_Client.available()){
String line = WiFi_Client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
delay(1000);
}
}
else{
Serial.println("No Data Received From Tag");
delay(1000);
}
data1 = "";
}
|
#include <cmath>
#include "trm/binary.h"
/**
* Returns main-sequence radius given a mass. Completely crude
* at the moment just uses R = M in solar units. Needs to be updated
* for anything critical.
* \param m mass of star (solar masses)
* \return Radius of star (solar radii)
*/
double Binary::mr_main_sequence(double m){
return m;
}
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution1 {
public:
int permuteUnique(vector<int>& nums) {
int res=1;
for(int i=1;i<=nums.size();i++)
res*=i;
sort(nums.begin(),nums.end());
int cnt=1,sum=1;
for(int i=1;i<nums.size();i++)
{
if(nums[i]==nums[i-1])
{
cnt++;
sum*=cnt;
}
else
{
res/=sum;
sum=1;
cnt=1;
}
}
res/=sum;
return res;
}
};
class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> permuteUnique(vector<int>& nums) {
//基本思想:递归回溯法,递归回溯找寻所有可能结果保存到res
//因为nums里有重复元素,要想组合cur不出现重复,对相同重复元素下标顺序固定,不允许出现逆序,也就是遇到一个nums元素,看当前组合cur中是否有元素相同,如果相同,当前元素下标必须大于相同元素下标,这样保证了res中没有重复
//cur保存当前某一种可能的下标组合情况,cnt计数cur中元素个数,当等于nums.size(),将当前的一种下标组合cur对应元素保存到res
vector<int> cur;
Recursion(nums, cur, 0);
return res;
}
void Recursion(vector<int> nums, vector<int> cur, int cnt)
{
//cnt计数cur中元素个数,当等于nums.size(),将当前的一种下标组合cur对应元素保存到res
if (cnt == nums.size())
{
vector<int> temp;
for (auto& r : cur)
temp.push_back(nums[r]);
res.push_back(temp);
return;
}
//循环遍历nums所有元素
for (int i = 0; i < nums.size(); i++)
{
int flag = 0;
//看当前nums中的下标i是否存在cur中,若存在cur中或者看当前组合下标cur中对应元素与nums[i]相同当前元素下标i必须大于相同元素下标r,则flag=1否则继续循环看nums下一个元素
for (auto& r : cur)
{
if (r == i || (nums[r] == nums[i] && i < r))
{
flag = 1;
break;
}
}
//若flag=0,当前下标i加入下标组合cur并且cnt+1,递归找下一个元素
if (flag == 0)
{
cur.push_back(i);
Recursion(nums, cur, cnt + 1);
//回溯弹出刚刚加入的下标i
cur.pop_back();
}
}
return;
}
};
int main()
{
Solution solute;
vector<vector<int>> res;
vector<int> nums = { 1,1,0,0,1,-1,-1,1 };
res = solute.permuteUnique(nums);
for (int i = 0; i < res.size(); i++)
{
for (int j = 0; j < res[i].size(); j++)
cout << res[i][j] << " ";
cout << endl;
}
cout << res.size() << endl;
return 0;
}
|
/* leetcode 125
*
*
*
*/
#include <string>
#include <unordered_set>
#include <algorithm>
using namespace std;
class Solution {
public:
bool isPalindrome(string s) {
if(s.size() == 0) {
return true;
}
for (int l = 0, r = s.size() - 1; l < r; l++, r--) {
if (!isalnum(s[l])) {
r++;
continue;
} else if (!isalnum(s[r])) {
l--;
continue;
}
if(tolower(s[l]) != tolower(s[r])) {
return false;
}
}
return true;
}
};
/************************** run solution **************************/
int _solution_run(string s)
{
Solution leetcode_125;
int ans = leetcode_125.isPalindrome(s);
return ans;
}
#ifdef USE_SOLUTION_CUSTOM
string _solution_custom(TestCases &tc)
{
}
#endif
/************************** get testcase **************************/
#ifdef USE_GET_TEST_CASES_IN_CPP
vector<string> _get_test_cases_string()
{
return {};
}
#endif
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
LL a[100100];
int id[100100];
int main() {
int n,k;
scanf("%d%d",&n,&k);
LL ans = 0,sum = 0;
for (int i = 1;i <= n; i++) {
scanf("%I64d",&a[i]);
ans += a[i-1]*a[i];
sum += a[i];
}
a[0] = a[n];a[n+1] = a[1];
ans += a[1]*a[n];
for (int i = 1;i <= k; i++) scanf("%d",&id[i]);
sort(id+1,id+k+1);id[0] = n;
for (int i = 1;i <= k; i++) {
sum -= a[id[i]];
if (id[i-1] == id[i]-1) ans += a[id[i]]*(sum - a[id[i]+1]);
else ans += a[id[i]]*(sum - a[id[i]-1] -a[id[i]+1]);
}
if (id[k] == n && id[1] == 1) ans += a[n]*a[1];
printf("%I64d",ans);
return 0;
}
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/bgsegm.hpp"
#include <vector>
#include <opencv2/viz.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/core.hpp>
#include <opencv2/calib3d.hpp>
#define PENGZHANG 1
#define THETA_X (30*3.141592653589/180)
#define THETA_Y 0
#define THETA_Z 3.141592653589
#define CAPINDEX 1
using namespace cv;
using namespace std;
//const char* params
// = "{ help h | | Print usage }"
// "{ input | /media/lijiayi/OS/Users/69067/Pictures/Camera Roll/WIN_20190121_20_19_00_Pro.mp4 | Path to a video or a sequence of image }"
// "{ algo | 1MOG2 | Background subtraction method (KNN, MOG2) }";
class myImgPoint : public Point2f
{
public:
float angle_with_center;
float length_to_next_point;
myImgPoint(float x,float y): Point2f(x,y){ }
bool operator < (const myImgPoint& myImgPoint1) const
{
return angle_with_center<myImgPoint1.angle_with_center;
}
bool operator > (const myImgPoint& myImgPoint1) const
{
return angle_with_center>myImgPoint1.angle_with_center;
}
};
float dist_btn_pts(Point2f p1,Point2f p2)
{
return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2) * 1.0);
}
int main(int argc, char* argv[]) {
// CommandLineParser parser(argc, argv, params);
// parser.about("This program shows how to use d provided by "
// " OpenCV. You can process both videos and images.\n");
// if (parser.has("help")) {
// //print help information
// parser.printMessage();
// }
String algo="MOG";
//相机参数
Mat cameraMatrix;
cameraMatrix = Mat::zeros(3, 3, CV_64F);
const vector<double> distCoeffs{0.03819613038058793, -0.06112508916119349, -5.515361356058103e-05,
0.003470678820019871, 0};
cameraMatrix.at<double>(0, 0) = 411.1663471332097;
cameraMatrix.at<double>(0, 2) = 331.9546551659722;
cameraMatrix.at<double>(1, 1) = 411.4132376251969;
cameraMatrix.at<double>(1, 2) = 268.2985302141446;
cameraMatrix.at<double>(2, 2) = 1;
//! [create]
//create Background Subtractor objects
Ptr<BackgroundSubtractor> pBackSub;
if (algo == "MOG2")
pBackSub = createBackgroundSubtractorMOG2();
else if(algo == "KNN")
pBackSub = createBackgroundSubtractorKNN();
else if(algo == "MOG")
pBackSub = bgsegm::createBackgroundSubtractorMOG(); //MOG approach
//! [create]
//! [capture]
VideoCapture capture(CAPINDEX);
capture.set(CAP_PROP_AUTO_EXPOSURE,0.25);
capture.set(CAP_PROP_EXPOSURE, 0.00001);
if (!capture.isOpened()) {
//error in opening the video input
cerr << "Unable to open: " << CAPINDEX << endl;
return 0;
}
//! [capture]
//region 3D virtualization
viz::Viz3d myWindow("Coordinate Frame");
myWindow.showWidget("Coordinate Widget", viz::WCoordinateSystem());
viz::WCube cube_widget1(Point3f(-0.0663, -0.03966, -0.01), Point3f(0.0663, 0, 0.01), false, viz::Color::blue());
viz::WCube cube_widget2(Point3f(-0.03135, 0, -0.01), Point3f(0.03135, 0.06132, 0.01), false, viz::Color::blue());
myWindow.showWidget("Cube Widget1", cube_widget1);
myWindow.showWidget("Cube Widget2", cube_widget2);
viz::WLine line_widget(Point3d(0, 0, 3), Point3d(0, 0, 0), viz::Color::red());
myWindow.showWidget("line", line_widget);
line_widget.setRenderingProperty(viz::LINE_WIDTH, 1);
myWindow.spinOnce(1, true);
//endregion
//region camera position transform
// Vec3d rvec1 = Vec3d(rvec.at<double>(0,0),rvec.at<double>(1,0),rvec.at<double>(2,0));
// Vec3d tvec1 = Vec3d(tvec.at<double>(0,0),tvec.at<double>(1,0),tvec.at<double>(2,0));
// Affine3f pose(rvec1,tvec1);
// cout << pose.matrix << endl;
//endregion
Mat frame, fgMask, frame_masked, binImg, hsvImg, img, valueImg, result;
img = Mat::zeros(480, 640, CV_8UC3);
valueImg = Mat::zeros(480, 640, CV_8UC1);
result = Mat::zeros(1000, 1000, CV_8UC1);
ofstream myfile;
myfile.open("/home/lijiayi/newdisk/cameraresult.csv");
int n = 0;
while (true) {
capture >> frame;
if (frame.empty())
break;
undistort(frame, img, cameraMatrix, distCoeffs);
imshow("undistorted", img);
cvtColor(img, hsvImg, CV_BGR2HSV);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
const int hi = i * img.cols * 3 + j * 3,
gi = i * img.cols + j;
valueImg.data[gi] = hsvImg.data[hi + 2];
}
}
//! [apply]
//update the background model
pBackSub->apply(img, fgMask);
//! [apply]
frame_masked = Mat::zeros(frame.size(), frame.type());
binImg = frame_masked.clone();
valueImg.copyTo(frame_masked, fgMask);
threshold(frame_masked, binImg, 200, 255, THRESH_BINARY);
//! [show]
//show the current frame and the fg masks
// imshow("Frame", frame);
// imshow("FG Mask", fgMask);
imshow("frame_masked", frame_masked);
// imshow("bin",binImg);
//! [show]
//region 膨胀
Mat dilatedImg;
if (PENGZHANG) {
int structElementSize = 1;
Mat structElement = getStructuringElement(MORPH_ELLIPSE,
Size(2 * structElementSize + 1, 2 * structElementSize + 1),
Point(structElementSize, structElementSize));
dilate(binImg, dilatedImg, structElement);
} else {
dilatedImg = binImg.clone();
}
// imshow("Dilated", dilatedImg);
//endregion
//region 寻找轮廓
vector<vector<Point>> contours, contours_org;
vector<Vec4i> hierarchy;
findContours(dilatedImg, contours_org, hierarchy, RETR_CCOMP, CHAIN_APPROX_NONE);
//region find max_Area
double maxArea;
vector<Point> temp;
for (auto i = contours_org.begin(); i != contours_org.end(); i++) {
maxArea = contourArea(*i);
for (auto j = i + 1; j != contours_org.end(); j++) {
if (contourArea(*j) > maxArea) {
maxArea = contourArea(*j);
temp = *i;
(*i) = (*j);
(*j) = temp;
}
}
}
if (contours_org.size() >= 4)
for (int i = 0; i < 4; i++) contours.push_back(contours_org[i]);
//endregion
Mat contoursImg = Mat::zeros(img.size(), CV_8UC1);
// rectImg = img.clone();
// drawContours(contoursImg, contours, -1, Scalar(255), 3, 8, hierarchy);
//endregion
vector<myImgPoint> imgPts;
vector<Point2f> imgPts2;
for (auto itContour = contours.begin(); itContour != contours.end(); itContour++) {
// if(contourArea(*itContour)<40)
// {
// continue;
// }
Moments m;
m = moments(*itContour, true);
myImgPoint p = myImgPoint((m.m10 / m.m00), (m.m01 / m.m00));
imgPts.push_back(p);
for (auto itContourPt = (*itContour).begin(); itContourPt != (*itContour).end(); itContourPt++) {
contoursImg.at<uchar>(Point((*itContourPt).x, (*itContourPt).y)) = 255;
}
contoursImg.at<uchar>(p) = 255;
}
imshow("contours", contoursImg);
if (imgPts.size() == 4) {
Point2f centerP;
imgPts2.clear();
imgPts2.assign(4, myImgPoint(0, 0));
centerP = Point2f(((imgPts[0].x + imgPts[1].x + imgPts[2].x + imgPts[3].x) / 4),
((imgPts[0].y + imgPts[1].y + imgPts[2].y + imgPts[3].y) / 4));
//与中心点形成的角度
for (int i=0;i<4;i++)
{
imgPts[i].angle_with_center=atan2(imgPts[i].y-centerP.y,imgPts[i].x-centerP.x);
}
//sort according to angle with center Point
sort(imgPts.begin(),imgPts.end());
imgPts[0].length_to_next_point=dist_btn_pts(imgPts[0],imgPts[1]);
imgPts[1].length_to_next_point=dist_btn_pts(imgPts[1],imgPts[2]);
imgPts[2].length_to_next_point=dist_btn_pts(imgPts[2],imgPts[3]);
imgPts[3].length_to_next_point=dist_btn_pts(imgPts[3],imgPts[0]);
int Index_maxL=0;
for(int i=1;i<4;i++)
{
if(imgPts[i].length_to_next_point>imgPts[Index_maxL].length_to_next_point)
Index_maxL=i;
}
imgPts2[1]=imgPts[Index_maxL];
imgPts2[0]=imgPts[(Index_maxL+1)%4];
imgPts2[3]=imgPts[(Index_maxL+2)%4];
imgPts2[2]=imgPts[(Index_maxL+3)%4];
// for (auto itPt = imgPts.begin(); itPt != imgPts.end(); itPt++) {
// if ((*itPt).x <= centerP.x && (*itPt).y <= centerP.y)
// imgPts2[0] = Point2f((*itPt));
// else if ((*itPt).x > centerP.x && (*itPt).y <= centerP.y)
// imgPts2[1] = Point2f((*itPt));
// else if ((*itPt).x > centerP.x && (*itPt).y > centerP.y)
// imgPts2[2] = Point2f((*itPt));
// else if ((*itPt).x <= centerP.x && (*itPt).y > centerP.y)
// imgPts2[3] = Point2f((*itPt));
// }
vector<Point3f> objectPts;
objectPts.emplace_back(-0.0663, -0.03966, 0);
objectPts.emplace_back(0.06526, -0.03966, 0);
objectPts.emplace_back(0.03135, 0.06132, 0);
objectPts.emplace_back(-0.03135, 0.06132, 0);
// objectPts.emplace_back(-0.0663,0.03966,0);
// objectPts.emplace_back(0.06526,0.03966,0);
// objectPts.emplace_back(0.03135,-0.06132,0);
// objectPts.emplace_back(-0.03135,-0.06132,0);
Mat rvec, tvec;
solvePnP(objectPts, imgPts2, cameraMatrix, distCoeffs, rvec, tvec);
// cout << "=========================" << endl;
// cout << "trans" << tvec << endl;
//// cout << "rotate" << rvec << endl;
// cout << "=========================" << endl;
Point ppp;
ppp = Point(int(tvec.at<double>(0, 0) * 50 + 300), int(tvec.at<double>(0, 1) * 50 + 300));
if (ppp.x >= 0 && ppp.x <= result.size().width && ppp.y >= 0 && ppp.y <= result.size().height)
result.at<uchar>(ppp) = 255;
// imshow("results", result);
// Mat rot_mat;
// Rodrigues(Vec3f(rvec.at<double>(0,0),rvec.at<double>(1,0),rvec.at<double>(2,0)), rot_mat);
// cout << rvec << " ||||||||" << endl;
// cout << Vec3f(rvec.at<double>(0,0),rvec.at<double>(1,0),rvec.at<double>(2,0)) << endl;
Vec3d rvec1 = Vec3d(rvec.at<double>(0, 0), rvec.at<double>(1, 0), rvec.at<double>(2, 0));
Vec3d tvec1 = Vec3d(tvec.at<double>(0, 0), tvec.at<double>(1, 0), tvec.at<double>(2, 0));
Affine3f pose(rvec1, tvec1);
// cout << pose.matrix << endl;
// myWindow.setWidgetPose("Cube Widget1", pose);
// myWindow.setWidgetPose("Cube Widget2", pose);
//相机坐标系修正
// 1.00412352941177 0.614449098039216 0.299829411764706
// -0.523598775598299 -0.0349065850398866 1.53588974175501
Matx33f R_x(1, 0, 0,
0, cos(THETA_X), -sin(THETA_X),
0, sin(THETA_X), cos(THETA_X));
Matx33f R_y(cos(THETA_Y), 0, sin(THETA_Y),
0, 1, 0,
-sin(THETA_Y), 0, cos(THETA_Y));
Matx33f R_z(cos(THETA_Z), -sin(THETA_Z), 0,
sin(THETA_Z), cos(THETA_Z), 0,
0, 0, 1);
Matx33f R = R_z * R_x;
Vec3f tvec_cam = {0, -1, 0.3};
// Vec3f tvec_cam = {0,0,0};
Affine3f pose_cam(R, tvec_cam);
// cout << pose.matrix << endl;
Affine3f ppposee = pose.concatenate(pose_cam.inv());
myWindow.setWidgetPose("Cube Widget1", ppposee);
myWindow.setWidgetPose("Cube Widget2", ppposee);
myWindow.spinOnce(1, true);
myfile << tvec1[0] << "," << tvec1[1] << "," << tvec1[2] << "," << tvec1[0] << "," << tvec1[1] << ","
<< tvec1[2] << "," << endl;
cout << n << endl;
// if (n==150)
// std::getchar();
}
// if (n==frames-1)
// {
// capture.set(CV_CAP_PROP_POS_FRAMES,1);
// }
n++;
//get the input from the keyboard
int keyboard = waitKey(50);
if (keyboard == 'q' || keyboard == 27)
break;
}
myfile.close();
return 0;
}
|
#include <Command.h>
/*
Testing the command class for serial control
*/
const char trigPin = 3;
const char echoPin = 2;
Command startTrig = Command('i', trigPin, 'o');
Command startEcho = Command('i', echoPin, 'i');
Command trigLow = Command('w', trigPin, 'l');
Command trigHigh = Command('w', trigPin, 'h');
Command readEcho = Command('p', echoPin, 'h');
void setup()
{
Serial.begin(9600);
startTrig.run();
startEcho.run();
}
void loop()
{
trigLow.run();
delayMicroseconds(2);
trigHigh.run();
delayMicroseconds(10);
trigLow.run();
readEcho.run();
Serial.println(int(readEcho.getResponse()));
delay(50);
}
|
#ifndef AS64_STD_DYNAMICAL_MOVEMENT_PRIMITIVE_H
#define AS64_STD_DYNAMICAL_MOVEMENT_PRIMITIVE_H
#include <dmp_lib/DMP/DMP_.h>
#include <dmp_lib/GatingFunction/SigmoidGatingFunction.h>
namespace as64_
{
namespace dmp_
{
class DMP : public DMP_
{
public:
DMP(int N_kernels, double a_z, double b_z,
std::shared_ptr<CanonicalClock> can_clock_ptr=std::shared_ptr<CanonicalClock>(new CanonicalClock()),
std::shared_ptr<GatingFunction> shape_attr_gating_ptr=std::shared_ptr<GatingFunction>(new SigmoidGatingFunction(1.0, 0.5)));
DMP *deepCopy() const;
void exportToFile(std::ostream &out) const;
static std::shared_ptr<DMP_> importFromFile(std::istream &in);
protected:
double shapeAttractor(double x, double g) const;
double forcingTermScaling(double g) const;
double calcFd(double x, double y, double dy, double ddy, double g) const;
double calcLearnedFd(double x, double g) const;
}; // class DMP
} // namespace dmp_
} // namespace as64_
#endif // AS64_STD_DYNAMICAL_MOVEMENT_PRIMITIVE_H
|
#ifndef HTML5ELEMENT_H
#define HTML5ELEMENT_H
class HTML5Element
{
public:
#include "modules/logdoc/src/html5/elementtypes.h"
#include "modules/logdoc/src/html5/attrtypes.h"
enum Ns
{
HTML,
MATH,
SVG,
XLINK,
XML,
XMLNS,
WML
};
private:
};
#endif // HTML5ELEMENT_H
|
#include "TranscoderManager.h"
#include "MessageManager.h"
#include <iostream>
#include <string>
#include <vector>
#define LENGTH_OF_LISTEN_QUEUE 20
using namespace std;
int threadNum=0;
unsigned int _stdcall handleMessage(void *params) {
InfoNode *node = (InfoNode *)params;
MessageList *list = node->messageList;
SOCKET *socketID = node->socketID;
subMessageList *pRCL=list->pRCL;
MessageNode *present=pRCL->present;
int size=present->size;
INT8 *CString=present->CString;
printf("enter the son thread\n");
int readSize;
char sendBuffer[2000];
memset(sendBuffer,0,2000);
memcpy(sendBuffer,CString,size);
sendBuffer[size]= '\0'; //strlen
char recvBuffer[2000]={0};
while ((readSize = recv(*socketID, recvBuffer, 2000, 0)) > 0) {
recvBuffer[readSize] = '\0';
puts(recvBuffer);
////////////////////////////////// parse the recv
std::vector<char*> splits;
char delims[] = "|";
char *result = NULL;
result = strtok( recvBuffer, delims );
while( result != NULL ) {
printf( "result is %s\n", result );
splits.push_back(result);
result = strtok( NULL, delims );
}
printf("%d\n",splits.at(0));
UINT8 typeof;UINT32 lengthof;UINT8 encNumof;
typeof=(UINT8)strtol (splits.at(0),NULL,16);
lengthof=(UINT32)strtol(splits.at(1),NULL,16);
printf("type is %d\n",typeof);
if (typeof == 0x01) {
UINT8 encNum = (UINT8)strtol(splits.at(2), NULL, 16);
printf("encNum is %d\n", encNum);
int offset = 0;
int index = 3;
for (int i = 1; i <= encNum; i++) {
UINT8 paramNum = (UINT8)strtol(splits.at(index), NULL, 16);
printf("\tparamNum is %d\n", paramNum);
for (int j = 1; j <= paramNum; j++) {
UINT8 paramType = (UINT8)strtol(splits.at(index + 2*j-1), NULL, 16);
UINT32 valueof = (UINT32)strtol(splits.at(index + j * 2), NULL, 16);
printf("\t\tparamType is %x, ", paramType);
printf("value is %x\n", valueof);
}
offset = paramNum;
index = index + offset*2 + 1;
}
} else if (typeof == 0x41) {
} else if (typeof == 0x02) {
} else if (typeof == 0x42) {
} else if (typeof == 0x43) {
UINT8 outputStreamIndex=(UINT8)strtol(splits.at(2),NULL,16);
UINT64 pts=(UINT64)strtol(splits.at(3),NULL,16);
UINT8 averageFrameRate=(UINT8)strtol(splits.at(4),NULL,16);
UINT8 instantFrameRate=(UINT8)strtol(splits.at(5),NULL,16);
} else if (typeof == 0x04) {
}
else{
printf("This is not TLV information\n");
}
memset(recvBuffer,0,2000);
if(send(*socketID , sendBuffer , strlen(sendBuffer)+1 , 0)<0) { //plus 1 makes the last 0 could be sent to client
printf("Send failed:%d",WSAGetLastError());
return -1;
}
printf("Send message successfully.\n");
}
closesocket(*socketID);
printf("Will return from %s\n",__FUNCTION__);
return 0;
}
//************************************
// Method: 利用端口信息,初始化transcoderManager线程,线程suspend
// FullName: init_transcoderManager
// Access: public
// Returns: int -1失败 0成功
// Qualifier:
// Parameter: pthread_t * transcoderManager
// Parameter: SOCKET * socketID 主控PC和转码节点间TCP/IP连接链路
// Parameter: MessageList * pList 需要更新其中的码控反馈信息和编码信息进度列表
// Parameter: void * private 线程私有空间
//************************************
int init_transcoderManager( HANDLE *transcoderManager, SOCKET *socketID,MessageList *pList,void *privateSpace ) {
InfoNode *info = new InfoNode();
info->messageList = pList;
info->socketID = socketID;
SOCKET new_socket;
int length;
if((*socketID = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(7747);
if( bind(*socketID ,(struct sockaddr *)&server , sizeof(server))==SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
return -1;
}
if (listen(*socketID, LENGTH_OF_LISTEN_QUEUE))
{
printf("Server Listen Failed : %d\n" , WSAGetLastError());
return -1;
}
printf("Welcome ,intial success\n");
length= sizeof(struct sockaddr_in);
timeval timeout = {600, 0};
fd_set fds;
FD_ZERO(&fds);
FD_SET(*socketID, &fds);
int b=select(*socketID+1, &fds, NULL, NULL, &timeout);
if(select(*socketID+1, &fds, NULL, NULL, &timeout)==SOCKET_ERROR){
printf("select failed with error code : %d" , WSAGetLastError());
return -1;
};
printf("You have %d handle\n",b);
if (FD_ISSET(*socketID, &fds))
{
while(1){
new_socket = accept(*socketID , (struct sockaddr *)&client, &length);
if (new_socket <0)
{
printf("accept failed with error code : %d" , WSAGetLastError());
return -1;
}
threadNum++;
puts("Connection accepted");
info->socketID=&new_socket; //very important
printf("accept is:%d\n",new_socket);
transcoderManager = (HANDLE *)malloc(sizeof(HANDLE));
*transcoderManager = (HANDLE)_beginthreadex(NULL, 0, handleMessage, (void *)info,0, NULL);
if(*transcoderManager==0){
printf("CreateThread failed (%d)\n", GetLastError());
return -1;
}
printf("Create %d Thread Successfully:%s.\n",a,__FUNCTION__);
}
}
closesocket(*socketID);
delete(info);
info=NULL;
printf("Will return from %s\n", __FUNCTION__);
return 0;
}
//************************************
// Method: 线程从挂起状态唤醒
// FullName: activate_transcoderManager
// Access: public
// Returns: int -1失败 0成功
// Qualifier:
// Parameter: pthread_t * transcoderManager 线程NULL指针
// Parameter: SOCKET * socketID 主控PC和转码节点间TCP/IP连接链路
// Parameter: MessageList * pList 需要更新其中的码控反馈信息和编码信息进度列表
// Parameter: void * private 线程私有空间
//************************************
int activate_transcoderManager(HANDLE *transcoderManager, SOCKET *socketID, MessageList *pList, void *privateSpace) {
if(ResumeThread(*transcoderManager)==-1){
return -1;
};
return 0;
}
//************************************
// Method: 线程销毁
// FullName: destroy_transcoderManager
// Access: public
// Returns: int -1失败 0成功
// Qualifier:
// Parameter: pthread_t * transcoderManager 线程句柄
// Parameter: void * private
//************************************
int destroy_transcoderManager( HANDLE *transcoderManager,void *privateSpace ) {
if(CloseHandle(*transcoderManager)==0){
return -1;
};
WSACleanup();
return 0;
}
|
#include "thm_string.h"
#include <iostream>
using namespace std;
thm_string::thm_string()
{
cout << "Thm_String: Default Constructor called" << endl;
l = {};
}
thm_string::thm_string(char *str)
{
cout << "Thm_String: Constructor called with char *" << endl;
l = {};
for(int i = 0; str[i] != '\0'; i++){
// add chars to list
l.push_back(str[i]);
}
for (list<char>::iterator it = l.begin(); it != l.end(); ++it)
std::cout << *it;
}
char thm_string::charAt(int pos){
auto it = l.begin();
advance(it, pos);
cout << *it << endl;
return *it;
}
ostream& operator<<(ostream& os, thm_string str)
{
for (list<char>::iterator it = str.l.begin(); it != str.l.end(); ++it)
os << *it;
return os;
}
/*
int example()
{
// Create a list containing integers
std::list<int> l = { 7, 5, 16, 8 };
// Add an integer to the front of the list
l.push_front(25);
// Add an integer to the back of the list
l.push_back(13);
// Insert an integer before 16 by searching
auto it = std::find(l.begin(), l.end(), 16);
if (it != l.end()) {
l.insert(it, 42);
}
// Iterate and print values of the list
for (int n : l) {
std::cout << n << '\n';
}
}
*/
|
#include "sea_lion.h"
using namespace std;
SeaLion::SeaLion(){
age = 0;
cost = 700;
offspring_size = 1;
base_food_cost = 80;
revenue = 140;
}
|
using namespace std;
#include <vector>
#include <unordered_map>
class CrackWalls
{
public:
CrackWalls();
~CrackWalls();
void findWays(int);
long long findPoses(int);
private:
vector<string> ways;
void getWays(int, char *, int);
unordered_map<int, vector<int>> poses;
unordered_map<string, long long> cache;
bool(*interPoses)[3500] = new bool[3500][3500];
long long getLayers(int, int);
};
|
#include "utils.hpp"
double toDouble(const json &node)
{
string str = node.dump();
return stod(str.substr(1, str.size() - 2));
}
|
#include<iostream>
int main () {
int year = 0;
char space;
int month = 0;
char dash;
int day = 0;
std::cout << "Input Winnie's Birthday (ex. 2018 09-01) : ";
std::cin >> year >> space >> day >> dash >> month;
if ( year != 2018 ) {
std::cout << " You should enter 2018 " << std::endl;
std::cin >> year >> space >> day >> dash >> month;
}
if ( day < 0 || day > 31 ) {
std::cout << " You should enter from 1 to 31 " << std::endl;
std::cin >> year >> space >> day >> dash >> month;
}
if ( month < 1 || month > 12 ) {
std::cout << " You should enter from 1 to 12 " << std::endl;
}
int rMonth = day % 10 * 10 + ( day - day % 10 ) / 10;
int rDay = month % 10 * 10 + ( month - month % 10 ) /10;
if ( rMonth > 12 ) {
std::cout << " The Aliens will not come on Winnie's Birthday " << std::endl;
} else if ( rMonth > month || ( rMonth == month && rDay > day ) ) {
std::cout << " The Aliens will be late " << std::endl;
} else if ( rMonth == month && rDay == day ) {
std::cout << " The Aliens will be in time " << std::endl;
} else {
std::cout << " The Aliens will come early " << std::endl;
}
return 0;
}
|
/**
* Copyright 2015 ViajeFacil
* @author Hugo Ferrando Seage
* @author David Jiménez Cuevas
* @author Estefanía Ortego García
*
* Los negos: una compañía crea negos, son los encargados de gestionar
* los paquetes y billetes aéreos, que le darán a los owners y estos
* a las oficinas correspondientes.
*/
#ifndef dialogNego_H
#define dialogNego_H
#include <QDialog>
#include "./pelVector.hpp"
#include "./nego.hpp"
#include "./owner.hpp"
namespace Ui {
class dialogNego;
}
/**
* @brief Dialogo de Negos
*/
class dialogNego : public QDialog {
Q_OBJECT
public:
explicit dialogNego(QWidget *parent = 0);
~dialogNego();
/**
* @brief Carga los comboBox
* Recorre el Vector de Owners y rellena el comboBox
*/
void cargar(pel::Vector<Owner>* own);
/**
* @brief Edita el Nego
* Edita el Nego que ha sido pasado por referencia
*/
void setNegoAEditar(Nego *neg);
/**
* @brief Crea un Nego
* Crea un nuevo Nego y se lo devuelve a mainWindow,
* el cual lo mete en su Vector correspondiente
*/
Nego crear();
/**
* @brief Owner seleccionado
* Devuelve el nivel del comboBox. Este nivel indica que Owner
* ha sido seleccionado. Se pasa al mainWindow para que sepa
* en que Owner tiene que insertar el Nego
*/
int nivel();
private slots: // NOLINT - https://github.com/google/styleguide/issues/30
void on_buttonOkCancel_accepted();
private:
bool editando = false;
Nego *negoAEditar;
Ui::dialogNego *ui;
};
#endif // dialogNego_H
|
#include "dialog.h"
#include <QBitmap>
#include <QDebug>
#include <QKeyEvent>
#include <QDateTime>
#include <QValidator>
#include "ui_dialog.h"
#include "Hardware/Motion/Motion.h"
#include "thread/rx_thread.h"
#include "Hardware/NRF24L01/NRF24L01.h"
#include "inputpara.h"
#include "singl_motion.h"
extern u8 buf[32];
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
QValidator *validator = new QIntValidator(0,255,this);
ui->lineEdit->setValidator(validator);
ui->lineEdit_2->setValidator(validator);
ui->lineEdit_3->setValidator(validator);
ui->lineEdit_4->setValidator(validator);
ui->radioButton->setChecked(true);
this->setWindowFlags(this->windowFlags()|Qt::FramelessWindowHint);
Rx_thread *Reciver = new Rx_thread(this);
QTimer *timer = new QTimer(this);
timer->start(1000);
connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdate()));
connect(Reciver,SIGNAL(Rx_flag(QString)),this,SLOT(Disp_Rx_value(QString)),Qt::QueuedConnection);
connect(Reciver,SIGNAL(Rx_flag(QString)),this,SLOT(on_pushButton_f2_clicked()),Qt::QueuedConnection);
connect(Reciver,SIGNAL(Motion_stop()),this,SLOT(on_pushButton_cancel_clicked()),Qt::QueuedConnection);
connect(this, SIGNAL(Keyvalue(QString)), this, SLOT(Update_number(QString)));
connect(ui->pushButton_0,SIGNAL(clicked()),this,SLOT(Getkeyvalue()));
connect(ui->pushButton_1,SIGNAL(clicked()),this,SLOT(Getkeyvalue()));
connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(Getkeyvalue()));
connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(Getkeyvalue()));
connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(Getkeyvalue()));
connect(ui->pushButton_5,SIGNAL(clicked()),this,SLOT(Getkeyvalue()));
connect(ui->pushButton_6,SIGNAL(clicked()),this,SLOT(Getkeyvalue()));
connect(ui->pushButton_7,SIGNAL(clicked()),this,SLOT(Getkeyvalue()));
connect(ui->pushButton_8,SIGNAL(clicked()),this,SLOT(Getkeyvalue()));
connect(ui->pushButton_9,SIGNAL(clicked()),this,SLOT(Getkeyvalue()));
GPIO_Configure("80","out");
NRF24L01_Init();
if(NRF24L01_check())
{
QPixmap pix;
pix.load(":/images/image/wifi.bmp");
QBitmap mask = pix.createMaskFromColor(QColor(255,255,255),Qt::MaskInColor);
pix.setMask(mask);
ui->label_4->setAutoFillBackground(true);
pix = pix.scaled(ui->label_4->size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
ui->label_4->setPixmap(pix);
}
Reciver->start();
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void Dialog::Update_number(QString value)
{
QWidget *current_focus_w = this->focusWidget(); //获取当前具有焦点的部件
if(current_focus_w->inherits("QLineEdit"))
{
QLineEdit * display = qobject_cast<QLineEdit*>(current_focus_w);
if(value == "backspace")
{
display->backspace();
}
else
{
display->setText(display->text()+value);
}
}
}
void Dialog::Getkeyvalue()
{
QString value = ((QPushButton * )sender())->text();//获取按键值
emit Keyvalue(value);
}
void Dialog::on_pushButton_yes_clicked()
{
buf[4] = (u8)ui->lineEdit->text().toInt();
buf[5] = (u8)ui->lineEdit_2->text().toInt();
buf[6] = (u8)ui->lineEdit_3->text().toInt();
buf[7] = (u8)ui->lineEdit_4->text().toInt();
NRF24L01_TX_Mode();
NRF24L01_TxPacket(buf);
}
void Dialog::on_pushButton_no_clicked()
{
emit Keyvalue("backspace");
}
void Dialog::Disp_Rx_value(QString str)
{
char tmp[10];
if(str=="success")
{
sprintf(tmp,"%u",buf[4]);
ui->lineEdit->setText(tmp);
sprintf(tmp,"%u",buf[5]);
ui->lineEdit_2->setText(tmp);
sprintf(tmp,"%u",buf[6]);
ui->lineEdit_3->setText(tmp);
sprintf(tmp,"%u",buf[7]);
ui->lineEdit_4->setText(tmp);
}
}
void Dialog::on_pushButton_cancel_clicked()
{
killTimer(time);
Motion_gpio("80","0");
}
void Dialog::timerEvent(QTimerEvent *event)
{
static char flag = 0;
if(event->timerId() == time)
{
flag = ~ flag;
if(flag == 0)
Motion_gpio("80","0");
else
Motion_gpio("80","1");
}
}
void Dialog::timerUpdate()
{
QDateTime sys_time = QDateTime::currentDateTime();
QString str_sys_time = sys_time.toString("yyyy-MM-dd hh:mm:ss dddd");
ui->label_time->setText(str_sys_time);
}
void Dialog::on_pushButton_f2_clicked()
{
QString str_time = ui->lineEdit->text();
time = startTimer(str_time.toInt());
}
void Dialog::on_pushButton_10_clicked()
{
Singl_Motion *Singl_Motion_dialog = new Singl_Motion(this);
Singl_Motion_dialog->setModal(true);
Singl_Motion_dialog->show();
}
void Dialog::on_pushButton_11_clicked()
{
InputPara *inputPara_dialog = new InputPara(this);
inputPara_dialog->setModal(true);
inputPara_dialog->show();
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
scanf("%d",&t);
int h,m,s;
s=t%60;
m=((t-s)/60)%60;
h=(t-s-m*60)/3600;
printf("%d:%d:%d",h,m,s);
return 0;
}
|
#include <iostream>
#include <vector>
#include <stack>
#include <cstring>
#define MAX 20001
int n, m, ID[MAX], ID_idx, GROUP[MAX], GROUP_idx;
bool finished[MAX];
std::vector<int> link[MAX];
std::stack<int> stk;
void push_link(int x, int y)
{
if(x < 0)
{
x = -x + m;
}
if(y < 0)
{
y = -y + m;
}
link[x].push_back(y);
}
int Make_SSC(int idx)
{
ID[idx] = ++ID_idx;
stk.push(idx);
int parent = ID[idx];
for(int next : link[idx])
{
if(ID[next] == 0)
{
parent = std::min(parent, Make_SSC(next));
}
else if(!finished[next])
{
parent = std::min(parent, ID[next]);
}
}
if(parent == ID[idx])
{
GROUP_idx++;
while(!stk.empty())
{
int top = stk.top();
stk.pop();
finished[top] = true;
GROUP[top] = GROUP_idx;
if(top == idx)
{
break;
}
}
}
return parent;
}
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
std::cin >> n >> m;
for(int i = 0; i < n; i++)
{
int x, y;
std::cin >> x >> y;
push_link(-x, y);
push_link(-y, x);
}
for(int i = 1; i <= m * 2; i++)
{
if(ID[i] == 0)
{
Make_SSC(i);
}
}
bool FLAG = false;
for(int i = 1; i <= m; i++)
{
if(GROUP[i] == GROUP[i + m])
{
FLAG = true;
break;
}
}
std::cout << (FLAG ? "OTL\n" : "^_^\n");
return 0;
}
|
#include <iostream>
#include "ListaST.h"
#include "Hora.h"
#include <stdlib.h>
using namespace std;
int main()
{
ListaST<Hora> A,B;
Hora horaUsuario;
int n;
cout << "Numero de horas a guardar: ";
cin >> n;
for(int i = 0;i<n;i++){
Hora H;
H.pideleAlUsuarioTusDatos();
A.inserta(H);
}
cout << endl << "Ingresa la hora limite:" << endl;
horaUsuario.pideleAlUsuarioTusDatos();
system("cls");
cout << "Hora limite:" << endl;
horaUsuario.muestraTusDatos();
cout << endl << "Lista Original:" << endl;
A.muestraTusDatos();
A.compara(horaUsuario, B);
cout << endl << "Lista resultante:" << endl;
B.muestraTusDatos();
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MODULES_OTL_PAIR_H
#define MODULES_OTL_PAIR_H
/// A simple, lightweight pair template, not unlike std::pair.
template<typename T1, typename T2>
struct OtlPair
{
T1 first;
T2 second;
OtlPair()
: first(T1())
, second(T2())
{}
OtlPair(const T1& x, const T2& y)
: first(x)
, second(y)
{}
template <class U1, class U2>
OtlPair(const OtlPair<U1, U2>& other)
: first(other.first)
, second(other.second)
{}
}; // OtlPair
template<typename T1, typename T2>
OtlPair<T1, T2> OtlMakePair(T1 x, T2 y)
{
return OtlPair<T1, T2>(x, y);
}
#endif // MODULES_OTL_PAIR_H
|
// Pong.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "pong.hpp"
#include "menu.hpp"
#include "main.h"
int windowWidth;
int windowHeight;
sf::Font font;
int main(int argc, char** argv)
{
windowWidth = 800;
windowHeight = 600;
font.loadFromFile("arial.ttf");
//Applications variables
//Window creation
sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "Pong");
//Mouse cursor no more visible
//App.setMouseCursorVisible(false);
//Main loop
int returnCode = OPTION_MENU;
while (returnCode != OPTION_EXIT)
{
switch (returnCode) {
case OPTION_MENU :
returnCode = start(window);
break;
case OPTION_PLAY :
returnCode = play(window);
break;
}
}
window.close();
return 0;
}
|
#include "Config.h"
#include <vector>
#include <iostream>
using namespace std;
bool interpolateD(const Config& config, const char * path,
float p, double& out){
float start, end;
Setting& setting = config.lookup(path);
if(setting.lookupValue("from",start)
&& setting.lookupValue("to",end))
{
out =start+(end-start)*p;
return true;
}
return false;
}
bool interpolateI(const Config& config, const char* path,
float p, unsigned char& out){
int start, end;
Setting& setting = config.lookup(path);
if(setting.lookupValue("from",start)
&& setting.lookupValue("to",end))
{
out = (unsigned char)(start+(end-start)*p);
return true;
}
return false;
}
bool loadRenderConfig(Config& config, RendererConfig& rendConfig, double p){
if(!config.lookupValue("iterations",rendConfig.iterations))
return false;
if(!config.lookupValue("points",rendConfig.points))
return false;
int width, height;
if(config.lookupValue("width",width)
&& config.lookupValue("height",height)){
rendConfig.image =new Image(width, height);
}
else
return false;
interpolateD(config,"variations.identity",p, rendConfig.weights.identity);
interpolateD(config,"variations.spherical",p, rendConfig.weights.spherical);
interpolateD(config,"variations.sinusoidal",p, rendConfig.weights.sinusoidal);
interpolateD(config,"variations.swirl",p, rendConfig.weights.swirl);
int functionCount = config.lookup("functions").getLength();
if(functionCount == 0)
return false;
rendConfig.F = new vector<FlameParameters*>();
int i;
char path[50];
for(i=0; i < functionCount ; i++){
FlameParameters * fp = new FlameParameters();
//Weight
sprintf(path,"functions.[%i].weight",i);
interpolateD(config,path,p,fp->p);
//Color
sprintf(path,"functions.[%i].color.red",i);
interpolateI(config,path,p,fp->color.R);
sprintf(path,"functions.[%i].color.green",i);
interpolateI(config,path,p,fp->color.G);
sprintf(path,"functions.[%i].color.blue",i);
interpolateI(config,path,p,fp->color.B);
//Coefs
sprintf(path,"functions.[%i].coefs.a",i);
interpolateD(config,path,p,fp->a);
sprintf(path,"functions.[%i].coefs.b",i);
interpolateD(config,path,p,fp->b);
sprintf(path,"functions.[%i].coefs.c",i);
interpolateD(config,path,p,fp->c);
sprintf(path,"functions.[%i].coefs.d",i);
interpolateD(config,path,p,fp->d);
sprintf(path,"functions.[%i].coefs.e",i);
interpolateD(config,path,p,fp->e);
sprintf(path,"functions.[%i].coefs.f",i);
interpolateD(config,path,p,fp->f);
rendConfig.F->push_back(fp);
}
return true;
}
|
/**********************************************************************************
head.h
This file contains the class definition, attributes, and methods of the Head.
The Head consists of all the mechanical systems as well as all the sensors and
electronics (excluding the LCD user interface). The functions incorporate all
the different features and have them interact with one another. The different
tests for various LOC levels, different pulses, and the functions that are defined
to interact with the UI are defined here. Several functions can be expanded on to
improve and complete the interaction between HAL and the user.
Last Edited by Ethan Lauer on 4/8/21
*********************************************************************************/
#include <Arduino.h>
// Mechanical System Header Files
#include "Eyes.h"
#include "Brows.h"
#include "Lids.h"
#include "jaw.h"
#include "neck.h"
// Sensors and Electronics Header Files
#include "forceSensor.h"
#include "microphone.h"
#include "camera.h"
#include "pulse.h"
#include "voice.h"
class Head {
private:
// ********************************************PRIVATE**************************************
// Overall LOC State Variable
// 0 = Alert, 1 = Verbal Response, 2 = Painful Response, 3 = Unresponsive
// initialize to arbitrary 7 when running full code - will be easier to see that it is an error
int stateLOC = 0; // This value is changed when the user provides input
// State Variables for the switch cases for the different LOC tests based on the stateLOC value
int alertLOCState = 0; // state machine for alert actions for LOC test
int verbalLOCState = 0; // state machine for verbal actions for LOC test
int painLOCState = 0; // state machine for pain actions for LOC test
int uLOCState = 0; // state machine for unresponsive actions for LOC test - note: not used in this version of the code.
// Circulation Variable
int pulseNum = 120; //used for exact pulse BPM - initialize to default 120 BPM
// Listening Variables
int micState = 0; // state variale if listening or responding or checking till done talking
const int micRange = 20; //any value outside the range of -micRange to micRange is means the person is talking
const int micOffset = 560; // offest used to filter out the unneccessary data from the mic - Note: Mic Potentiometer may need to be adjusted before each use
int timesResponded = 0; // the number of times the head responded to the person - keeps track of script and when to execute certain actions.
boolean finishedDialogue = false; // track if the person is done talking
// Camera Hand Tracking Variables
int lastTime; // store the number of frames hand was tracked
int count; // count how long the hand has been at the same location
//Airway Variables for UI interaction
boolean isNormAir; //true if normal airway
boolean isLockJaw; //true if have lock jaw problem
boolean isIrrBreath; //true if have irregular breathing
boolean isStriBreath; // true if have stridor breathing
boolean isAgGasp; // true if have agonal gasps
// Sensor pins
const int foreheadSensorPin = A14;
const int neckSensorPin = A15;
const int chinSensorPin = A16;
const int jawRightSensorPin = A17;
const int jawLeftSensorPin = A18;
const int micPin = A20;
// General state variable for testing functions
int headState = 0;
public:
// ********************************************PUBLIC**************************************
// Having all of the features public will let you access certain facial
// feautres on their own and their own functions without having to rewrite them as a "getter" function.
// Tt might be possible to have these in private after final testing is complete.
// Variables to check if all the settigns are set
// must be public unless want to use getter for lcd beginning
// Have the settings been given a value?
boolean isLOCSet = false;
boolean isAirSet = false;
boolean isPulseSet = false;
// NOTE: Not used in this code. Was unable to get to this part of the testing.
boolean isLOCTestDone = false; // true if finished LOC Test
boolean isAirTestDone = false; // true if finished air Test
boolean isPulseTestDone = false; // true if finished air Test
//MECHANICAL SYSTEMS
Eyeballs eyeBalls = Eyeballs();
Eyebrows eyeBrows = Eyebrows();
Eyelids eyeLids = Eyelids();
Neck neck = Neck();
Jaw jaw = Jaw();
// SENSORS
ForceSensor foreheadSensor = ForceSensor(foreheadSensorPin); // Large FSR
ForceSensor neckSensor = ForceSensor(neckSensorPin); // Large FSR
ForceSensor chinSensor = ForceSensor(chinSensorPin); // Small FSR
ForceSensor jawRightSensor = ForceSensor(jawRightSensorPin); // Small FSR
ForceSensor jawLeftSensor = ForceSensor(jawLeftSensorPin); // Small FSR
Microphone mic = Microphone(micPin);
Camera camera = Camera();
// OTHER ELECTRONICS
Pulse pulse = Pulse();
Voice voice = Voice();
//**************************************************************************************************INITIALIZE*********************************************************
// Define Head
Head() {
}
/*
setUp - Run the setup function for each of the mechanical systems and all the electronics.
Run this in the void setup() function in the main .ino file.
*/
void setUp() {
// Mechanical Systems
eyeLids.setUp();
eyeBalls.setUp();
eyeBrows.setUp();
neck.setUp();
jaw.setUp();
// Sensors and Electronics
foreheadSensor.setUp(foreheadSensorPin);
neckSensor.setUp(neckSensorPin);
chinSensor.setUp(chinSensorPin);
jawRightSensor.setUp(jawRightSensorPin);
jawLeftSensor.setUp(jawLeftSensorPin);
camera.setUp(); // uncomment once you are testing with camera
mic.setUp(micPin);
pulse.setUp();
voice.setUp(); // uncomment once you are testing with voice
}
//*********************************************************************SET PARAMETERS/FEATURES - FOR UI INTERACTION*******************************************************************
/*
setLOC - Set the LOC state variable to the desired input
Set the respective boolean indicating the LOC is now set.
int LOCSetting - integer indicating the level where
0 = Alert, 1 = Verbal Response, 2 = Painful Response, 3 = Unresponsive
*/
void setLOC(int LOCSetting) {
stateLOC = LOCSetting;
isLOCSet = true;
}
/*
setAir - Set the airway conditions to conditions that were passed into the function
Set the respective boolean indicating the airway is now set
boolean *airCondition - array of booleans where each index represents the following
airCondition[0] - true if normal airway, false if there is something wrong
airCondition[1] - true if lock jaw problem, false otherwise
airCondition[2] - true if have irregular breathing, false otherwise
airCondition[3] - true if have stridor breathing, false otherwise
airCondition[4] - true if have agonal gasps, false otherwise
*/
void setAir(boolean *airCondition) {
isNormAir = airCondition[0];
if (!isNormAir) {
isLockJaw = airCondition[1];
isIrrBreath = airCondition[2];
isStriBreath = airCondition[3];
if (!isIrrBreath && !isStriBreath) { // agonal gasps cannot occur at the same time as irregular breathing or stridor breathing
isAgGasp = airCondition[4];
}
}
isAirSet = true; // indicate airway is set now
Serial.print("Normal airway condition"); Serial.println(isNormAir); // for debuggin
}
/*
setPulseBPM - Set the Pulse BPM to the value that is inputted.
Set the respective boolean indicating the pulse/circulation is now set
int pulseBPM - integer of the exact BPM the pulse is set to
*/
void setPulseBPM(int pulseBPM) {
pulseNum = pulseBPM;
Serial.print("SET PULSE TO = "); Serial.println(pulseNum);
isPulseSet = true;
}
/*
setPulseRange - Set the Pulse range to the desired input
Set the respective boolean indicating the pulse/circulation is now set
int pulseRange - integer from 0-2 where:
0 = normal pulse range
1 = fast pulse range
2 = slow pulse range
*/
void setPulseRange(int pulseRange) {
if (pulseRange == 0) { // obtain a pulse value withing the normal, fast, or slow ranges (see pulse.h for details)
pulseNum = pulse.normalPulse();
} else if (pulseRange == 1) {
pulseNum = pulse.fastPulse();
} else if (pulseRange == 2) {
pulseNum = pulse.slowPulse();
} else {
Serial.println("ERROR SETTING PULSE FROM RANGE");
}
isPulseSet = true; //indicate the pulse is now set
}
/*
isAllSet - checks to see if all of the settings for the head are set
return boolean - true if all the different settings have been assigned a value, false otherwise
*/
boolean isAllSet() {
return (isLOCSet && isAirSet && isPulseSet);
}
//************************************************************************************** LOC TESTS **********************************************************************
/*
LOCTEST - Switch case that calls the different LOC tests depending on the state
that was set from the user. See each LOCTest() for details.
*/
void LOCTEST() {
switch (stateLOC) {
case 0: // alert
alertLOCTest();
break;
case 1: // verbal
verbalLOCTest();
break;
case 2: // pain
painLOCTest();
break;
case 3: // unresponsive
unresponsive();
break;
}
}
/*
alertLOCTest - This is the fully alert LOC Test called by the LOCTEST(). The pulse that was inputted
by the user runs continuously during this test. This test assumes the user is folowing a standard
script the entire time. The responses should be fairly quick and realsitic.
State 0 = First, HAL listens to the user and responds accordingly (see listenAndRespond() for details),
State 1 = Once he is done responding, he then tracks the person's glove until it is out of the frame for
more than 40 iterations
State 2 = Then Hal moves to an general idling state.
NOTE: State 3 is included and can be switched to for future work. Any futher interaction with Hal can occur here.
The test can be concluded by adding and exit case at the end once the test is complete.
If statements are used in this function due to an odd bug in the switch case that only occured occasionally.
If this bug can be fixed, a switch case would be better than if statements.
*/
void alertLOCTest() {
// Serial.print("ALERT LOC STATE = "); Serial.println(alertLOCState); // for debugging
pulse.pulseByBPM(pulseNum); // run the pulse constantly
//***************** State is equal to 0****************
if (alertLOCState == 0) {
if (finishedDialogue) { // if the person is done speaking back and forth, switch states
alertLOCState = 1;
}
eyeLids.blinkEyes(); // can be changed to an idleBlink for more realism
listenAndRespond(); // use mic to listen to user and respond appropriately
}
//***************** State is equal to 1****************
if (alertLOCState == 1) {
int *blockAge = camera.getBlockInfo(4); // use the camera to detect objects
int framesTracked = blockAge[0]; // how long has the object been tracked
Serial.print("AGE OF BLOCK = "); Serial.println(framesTracked);
followHand(); // move the eyeballs to follow the detected hand
if (framesTracked > 0 && framesTracked == lastTime) { // if the object is no longer detected or being tracked
if (count > 40) { // if it doesnt comeback into the frame within the given time, switch states
alertLOCState = 2;
Serial.println ("Set to second state");
delay(2000);
} else { //increment the count
count++;
Serial.print(" count = "); Serial.println(count);
}
} else {
lastTime = framesTracked; // update the variable that stores the previous value of how long it is tracked
}
}
//***************** State is equal to 2****************
if (alertLOCState == 2) { // complete generic movements as a place holder
// Serial.println("IN THE SECOND CASE");
eyeBalls.neutralBoth();
eyeLids.blinkEyes();
// alertLOCState = 3; // commented out for now for testing
}
//****************** State is equal to 3****************
if (alertLOCState == 3) { // final test case
Serial.println("IN THE THIRD CASE");
delay(2000);
alertLOCState = 2;
}
}
/*
verbalLOCTest - This is the verbal LOC Test called by the LOCTEST(). The pulse that was inputted
by the user runs continuously during this test. This test assumes the user is folowing a standard
script the entire time. The responses should be more dazed and slow. The system should
respond to verbal stimuli but slower than alert levels.
State 0 = First, HAL listens to the user and responds accordingly (see listenAndRespond() for details),
State 1 = Once he is done responding, he then tracks the person's glove until it is out of the frame for
more than 40 iterations. The neck should also move to follow the hand as well.
State 2 = Then Hal moves to an general idling state.
NOTE: The test can be concluded by adding and exit case at the end once the test is complete.
If statements are used in this function due to an odd bug in the switch case that only occured occasionally.
If this bug can be fixed, a switch case would be better than if statements.
*/
void verbalLOCTest() {
// Serial.print("VERBAL LOC STATE = "); Serial.println(verbalLOCState); // for debugging
pulse.pulseByBPM(pulseNum); // pulse runs continuously
//***************** State is equal to 0****************
if (verbalLOCState == 0) { // first speak with the person. after 2 responses then change state
if (finishedDialogue) {// if the person is done speaking back and forth, switch states
verbalLOCState = 1;
}
eyeBalls.stepEyesUpandDownVerySlow(); // can be replaced with a more condensed function of the "dazed" movements
listenAndRespond(); // use mic to listen to user and respond appropriately
}
//***************** State is equal to 1****************
if (verbalLOCState == 1) { // next follow the persons finger with eyes.
int *blockAge = camera.getBlockInfo(4);// use the camera to detect objects
int framesTracked = blockAge[0]; // how long has the object been tracked
Serial.print("AGE OF BLOCK = "); Serial.println(framesTracked);
followHand(); // move the eyeballs to follow the detected hand
if (framesTracked > 0 && framesTracked == lastTime) { // if the object is no longer detected or being tracked
if (count > 40) {// if it doesnt comeback into the frame within the given time, switch states
verbalLOCState = 2;
Serial.println("Set to second state");
delay(1000);
} else {
Serial.print("count = "); Serial.println(count);
count++; // increment the count
}
} else {
lastTime = framesTracked; // update the variable that stores the previous value of how long it is tracked
}
}
//***************** State is equal to 2****************
if (verbalLOCState == 2) { // complete generic movements as a place holder, then complete the test
Serial.println("IN SECOND CASE OF VERBAL LOC TEST");
// eyeBalls.neutralBoth();
eyeLids.blinkEyes();
eyeBalls.stepEyesUpandDownSlow();
}
}
/*
painLOCTest - This is the pail LOC Test called by the LOCTEST(). A default random pulse
runs continuously during this test but can be changed to a poor pulse in future iterations.
This test assumes the user is folowing a standard script the entire time. The system
should only respond to physical stimuli and does not listen to the user at all. The movements
should be more dazed. This function soley relies on the neck sensor to change reactions
but the other 4 FSRs can be incorporated into this test in future iterations.
The switch cases changes states based on the level of force applied to the neck sesnor.
Uncomment/comment different lines to have different reactions based on the degree of force applied.
*/
void painLOCTest() {
pulse.randPulse(); // random/irregular pulse
headState = neckSensor.forceRange(neckSensorPin); // read force sensor and divide into a specific range
switch (headState) {
case 0: // act dazed or tired while no force is applied
// alertActions();
eyeBrows.raiseAndSlightRaise();
eyeLids.stepLidsSleepy();
// eyeLids.stepLidsVerySlow();
eyeBalls.stepEyesUpandDownVerySlow();
neck.neutral();
break;
case 1:
// eyeBalls.glanceRight();
break;
case 2: // when a light force is applied, move to set points (also helps when from large force back to no force, mechanical systems have a midpoint to move back to)
eyeBrows.slightRaiseBoth();
eyeBalls.neutralBoth();
eyeLids.openPercentBoth(50);
break;
case 3:
// eyeBalls.lookLeftandRight();
break;
case 4: // a big force is applied, complete the preset pain actions (can be replaced with specific actions if using other force sensors in the future)
// eyeBalls.stepEyesDown();
painActions();
break;
}
}
//************************************************************************************** LOC FUNCTIONS **********************************************************************
/*
listenAndRespond - The system listens to the user and responds twice with mechanical and audio feedback. This is a modified verstion of micTest().
State 0 = The microphone is read, filtered, and if it is outside of the normal range,
State 1 = the person is talking so the microphone waits to see if the audio goes back to normal at which point
State 2 = The system responds with an audio response and a mechanical responds that lasts until the audio is complete.
This process is repeated twice (ie. user speaks, Hal responds, user speaks, Hal Responds).
The timesResponded limit can be changed based on the script that is followed. The 3.5 second wait after the person has finished
talking can be adjusted to a different time if it proves to be too slow.
*/
void listenAndRespond() {
int anVal; // store raw analog value
int trimmedVal; // store filtered value
switch (micState) {
case 0: // The head is listening
// if the head has responded two times already, then stop and say that the dialogue is finished
if (timesResponded == 2) {
timesResponded = 0;
finishedDialogue = true;
// return finishedDialogue; // this line can be removed since finishedDialogue is global. Just have not tested at this point
break;
}
// check the microphone to see if its has heard anything out of the ordinary range
anVal = analogRead(micPin);
trimmedVal = anVal - micOffset;
Serial.print(" Analog Value = "); Serial.println(trimmedVal, DEC);
// if the mic heard anything out of the ordinary range, then switch to next case
if (trimmedVal > micRange || trimmedVal < -micRange) {
micState = 1;
timeNow = millis(); // reset timer for next case
}
break;
case 1: // The head is waiting for user to finish speaking
anVal = analogRead(micPin);
trimmedVal = anVal - micOffset;
Serial.println("You are talking ");
Serial.print(" Analog Value = "); Serial.println(trimmedVal, DEC);
// if the mic has picked up values back in the normal range and has waits for 3.5 seconds of "no talking", then move to the next state
if ((trimmedVal < micRange || trimmedVal > -micRange) && (millis() > timeNow + 3500)) {
micState = 2;
timeNow = millis(); // reset timer for next case
}
break;
case 2: // Head is responding to dialogue
stateVoiceLOCResponses(); // completes certain responses depending on LOC state
anVal = analogRead(micPin);
trimmedVal = anVal - micOffset; // NOTE: future work could include having HAL continue to listen as he responds and stop/change his reaction if the user interrupts him
Serial.println("responding ");
Serial.print(" Analog Value = "); Serial.println(trimmedVal, DEC);
while (voice.stillPlaying()) { // if the audio is still playing
stateMechLOCResponses(); // completes the corresponding responses that match the audio
}
timesResponded++; // increment the times responded and go back to listening
micState = 0;
break;
}
}
/*
followHand - This function obtains camera info and the pixel coordinates, converts these values to servo values for both the
left and right eyeballs, and drives servos to these positions. If the LOC is a verbal response, the neck should
rotate to follow the pixel moving in the X(horizontal) direction.
NOTE: in future work, the head can be tilted so it can follow the Y(vertical) position.
*/
void followHand() {
eyeLids.openBoth(); // keep eyelids open the entire time - can be replaced with an idle blink or different blink functions based on LOC
int *pixCoords;
pixCoords = camera.getBlockInfo(0); // get the x and y coordinates of the detected block
// Serial.print("Pix X = "); Serial.println(pixCoords[0]);
// Serial.print("Pix Y = "); Serial.println(pixCoords[1]);
int xPix = pixCoords[0];
int yPix = pixCoords[1];
// Get the pixel coordinates for the edges of the camera frame
int pixMaxLeft = camera.pixMaxLeft;
int pixMaxRight = camera.pixMaxRight;
int pixMaxUp = camera.pixMaxUp;
int pixMaxDown = camera.pixMaxDown;
// Serial.print("LEft Eye Up Max = "); Serial.println(leftUpVertEye);
// Serial.print("Right Eye Up Max = "); Serial.println(rightUpVertEye);
//
// Convert pixels to eye servo positions - note: currently using global variables for eye positions. Change this to a public attribute in the eyes (not tested yet)
// I have tried to use a separate function outside of this to condense the "map" function but the data transfer between
// functions failed. Used volatiles, etc. Possibly try it again or another way if at all possible but this works with minimal delay.
int horLeftEyeCoord = map(xPix, pixMaxLeft, pixMaxRight, leftLeftHorEye, leftRightHorEye);
int horRightEyeCoord = map(xPix, pixMaxLeft, pixMaxRight, rightLeftHorEye, rightRightHorEye);
int vertLeftEyeCoord = map(yPix, pixMaxUp, pixMaxDown, leftUpVertEye, leftDownVertEye);
int vertRightEyeCoord = map(yPix, pixMaxUp, pixMaxDown, rightUpVertEye, rightDownVertEye);
// Serial.print(pixMaxUp); Serial.print(","); Serial.print(pixMaxDown); Serial.print(","); Serial.print(leftUpVertEye); Serial.print(","); Serial.println(leftDownVertEye);
// printing for debugging
// Serial.println("in head");
// Serial.print("Head Left X = "); Serial.println(horLeftEyeCoord);
// Serial.print("Head Left Y = "); Serial.println(vertLeftEyeCoord);
// Serial.print("Head Right X = "); Serial.println(horRightEyeCoord);
// Serial.print("Head Right Y = "); Serial.println(vertRightEyeCoord);
//Move eyes or neck to appropriate positions
if (stateLOC == 0) {
eyeBalls.moveHorEyesTo(horLeftEyeCoord, horRightEyeCoord);
eyeBalls.moveVertEyesTo(vertLeftEyeCoord, vertRightEyeCoord);
} else if (stateLOC == 1) {
eyeBalls.moveHorEyesTo(horLeftEyeCoord + 5, horRightEyeCoord + 5); // add an arbitrary offset (5) of the eyeball positions since the LOC is lower than alert
eyeBalls.moveVertEyesTo(vertLeftEyeCoord + 5, vertRightEyeCoord + 5);
int neckRotCoord = map(xPix, pixMaxLeft, pixMaxRight, neck.rotLeftMax, neck.rotRightMin); // convert pixels to neck rotation position
neck.rotToDeg(neckRotCoord, 3); // rotate the neck to follow the hand
}
}
//*********************************************RESPONSES for the LISTEN AND RESPOND FUNCTION*********************************************
/*
stateMechLOCResponses - This funtion uses a switch case that calls the various mechanical responses
in the LOC test (see listenAndRespond()) based on the LOC set by the user.
This function enables the listenAndRespond() function to be cleaner.
*/
void stateMechLOCResponses() {
switch (stateLOC) {
case 0:
alertResponses();
break;
case 1:
verbalResponses();
break;
case 2:
painResponses();
break;
case 3:
unresponsive();
break;
}
}
/*
stateVoiceLOCResponses - This funtion uses a switch case that calls the various audio responses
used in the LOC test (see listenAndRespond()) based on the LOC set by the user.
This function enables the listenAndRespond() function to be cleaner.
*/
void stateVoiceLOCResponses() {
switch (stateLOC) {
case 0:
alertVoiceRespond();
break;
case 1:
verbalVoiceRespond();
break;
case 2:
painVoiceRespond();
break;
case 3:
unresponsive();
break;
}
}
/*
alertVoiceRespond - Based on the times the system has responded to the user, (the number of back
and forths of the conversation) the Voice plays different .wav files that correspond with the alert LOC. To avoid
using a loop to play the file, an if statement is called with each iteration to
check if the voice is playing the audio file (see listenAndRespond() for more
details of implementation).
NOTE: These files should be replaced with new recordings so they are more accurate
and professional. More cases can be added if the system is set up to respond more than twice.
*/
void alertVoiceRespond() {
switch (timesResponded) {
case 0:
if (voice.stillPlaying()) { //first dialogue: respond with a greeting and a brief description of medical problem
} else {
voice.playFile("HIBUS.WAV");
}
break;
case 1:
if (voice.stillPlaying()) { //second dialogue: agree to follow the hand
} else {
voice.playFile("YESFOLOW.WAV");
}
break;
}
}
/*
alertResponses - Based on the times the system has responded to the user, (the number of back
and forths of the conversation) the mechanical componenets of the head move
in sync with the audio file that was called (see cooresponding case in alertVoiceRespond()).
These movements shoud be similar to average human movement that is a reasonable, natural speed.
NOTE: The mechanical movements should be changed to be in sync with the audio file.
Currently, the mechanical movements are just place holders. Once the audio
file is defined, the respective mechancial components (particularly the jaw)
should be programmed to move in sync. Functions for each response should be
created in each respective class. More cases can be added if the system is
set up to respond more than twice.
*/
void alertResponses() {
switch (timesResponded) {
case 0:// first mechanical response - saying hello
eyeLids.winkLeft();
jaw.helloJaw();
break;
case 1:// second mechanical response - agreeing to follow the hand.
eyeLids.winkRight();
jaw.helloJawSlow();
neck.nodTimes(3, 250);
break;
}
}
/*
verbalVoiceRespond - Based on the times the system has responded to the user, (the number of back
and forths of the conversation) the Voice plays different .wav files that correspond with the verbal LOC state. To avoid
using a loop to play the file, an if statement is called with each iteration to
check if the voice is playing the audio file (see listenAndRespond() for more
details of implementation).
NOTE: These files should be replaced with new recordings so they are more accurate
and professional. The current files are place holders and DO NOT represent the
LOC state right now. More cases can be added if the system is set up to respond more than twice.
*/
void verbalVoiceRespond() {
switch (timesResponded) {
case 0:
if (voice.stillPlaying()) { //first dialogue: respond with a dazed greeting and a poor description of medical problem
} else {
voice.playFile("AHHH.WAV");
}
break;
case 1:
if (voice.stillPlaying()) { //second dialogue: agree to follow the hand but delayed
} else {
voice.playFile("YESFOLOW.WAV");
}
break;
}
}
/*
verbalResponses - Based on the times the system has responded to the user, (the number of back
and forths of the conversation) the mechanical componenets of the head move
in sync with the audio file that was called (see cooresponding case in verbalVoiceRespond()).
These movements shoud slower than average human movement or could be faster to
illustrate the person is nervous.
NOTE: The mechanical movements should be changed to be in sync with the audio file.
Currently, the mechanical movements are just place holders. Once the audio
file is defined, the respective mechancial components (particularly the jaw)
should be programmed to move in sync. Functions for each response should be
created in each respective class. More cases can be added if the system is
set up to respond more than twice.
*/
void verbalResponses() {
switch (timesResponded) {
case 0:
eyeBrows.raiseLeftFurrowRight(); //first dialogue- currently placeholder (replace)
break;
case 1:
eyeBalls.lookLeftandRight();//second dialogue- currently placeholder (replace)
// add neck rotation here
neck.tilt();
break;
}
}
/*
painVoiceRespond - This function should hold any pain audio responses the system can provide if the patient is able to.
In the pain LOC, the system should not respond to any audio stimuli but should instead only respond
to physical response.
NOTE: These files should be replaced with new recordings so they are more accurate
and professional. The current files are place holders (or defaults)and DO NOT represent the
LOC state right now. More cases can be added if the system is set up to respond more than twice.
The switch case can be adjusted to change based on a variable that keeps track of the physical
responses rather than the audio responses.
*/
void painVoiceRespond() {
switch (timesResponded) {
case 0:
if (voice.stillPlaying()) {
} else {
voice.playFile("SDTEST1.WAV"); // default sample .wav file from Teensy website
}
break;
case 1:
if (voice.stillPlaying()) {
} else {
voice.playFile("AHHH.WAV"); // placeholder pain yell
}
break;
}
}
/*
painResponses - This function should hold any pain mechanical responses the system can provide if the patient is able to.
In the pain LOC, the system should not respond to any audio stimuli but should instead only respond
to physical response.
NOTE: These files should be replaced with mechanical movements so they are more accurate
and professional. The current movements place holders (or defaults)and DO NOT represent the
LOC state right now. More cases can be added if the system is set up to respond more than twice.
The switch case can be adjusted to change based on a variable that keeps track of the physical
responses rather than the audio responses.
*/
void painResponses() {
switch (timesResponded) {
case 0:
eyeBrows.raiseAndFurrow();
break;
case 1:
eyeLids.longClose();
neck.wince(true); // wincing to the left or right depending on the FSR pressd
break;
}
}
//*********************************************GENERAL LOC ACTIONS*********************************************
//******* These functions are currently used to have a standard LOC actions for testing. New functions can be
//******* created that combine all the different response functions for each mechanical components. For example,
//******* a function called "alertGreetAction()" could include a jaw.alertGreet(), eyeLids.idleBlink(), and other
//******* actions that can be synchronized with the audio file called in case 0 of alertVoiceRespond().
//******* Note: painActions() is currently used in the painLOC with the voice included in the response. Audio files
//******* can also be included in these functions to make the code more condensed as well.
/*
stateMechLOCActions - This includes a switch case that calls the different standard actions based on the LOC state.
This is used to make the code cleaner and easer to read when implemented in other parts of the code.
NOTE: This can be changed or new functions could be added so a variety of actions can be called
for each LOC state.
*/
void stateMechLOCActions() {
switch (stateLOC) {
case 0:
alertActions();
break;
case 1:
verbalActions();
break;
case 2:
painActions();
break;
case 3:
unresponsive();
break;
}
}
/*
alertActions - The head conducts generalized alert actions wehre the eyelids blink,
the eyes glance to the left every so often, and the eyebrows raise and furrow.
NOTE: The other mechanical systems were not set at the time this function was
created but the jaw and neck can be included in these actions.
*/
void alertActions() {
eyeLids.blinkEyes();
eyeBalls.glanceLeft();
eyeBrows.raiseAndFurrow();
}
/*
verbalActions - The head conducts generalized verbal actions wehre the eyelids blink normally,
the eyeballs slowly move uup and down, and the eyebrows raise and furrow.
NOTE: The other mechanical systems were not set at the time this function was
created but the jaw and neck can be included in these actions.
*/
void verbalActions() {
eyeBalls.stepEyesUpandDownVerySlow();
eyeBrows.raiseAndFurrow();
eyeLids.blinkEyes();
}
/*
painActions - The head conducts generalized pain actions in reaction high pressure applied to the left neck FSR where the voice
yells "aahhhh", the eyeballs look left, the eyelids wince to the left, and the left eyebrow furrows.
*/
void painActions() {
if (voice.stillPlaying()) {
} else {
voice.playFile("AHHH.WAV");
}
eyeBrows.raiseRightFurrowLeft();
eyeLids.winceLeft();
eyeBalls.leftBoth();
neck.wince(true);
}
/*
unresponsive - The head completes very dazed movements constantly regardless of any stimuli.
*/
void unresponsive() {
eyeLids.lazyBlinkEyes();
eyeBrows.slightRaiseBoth();
eyeBalls.neutralBoth();
}
//************************************************************** TESTING FUNCTIONS **********************************************************************
//****** These functions are used for testing different features and capabilities on their own and slowly integrating it with the rest of the code*******
/*
micTest - Tests the microphone and if the head can respond to an input that is louder than other parts.
State 0: The microphone waits to get input that is out of the normal range (listening),
State 1: waits until the value goes back into the normal range (waits until the person is done speaking),
State 2: then performs the arbitrary actions for arbitrary amount of time (responding).
*/
void micTest() {
int anVal; // stores raw analog input value
int trimmedVal; // stores the value after the offset is subtracted
switch (micState) {
case 0:
anVal = analogRead(micPin); // get raw input
trimmedVal = anVal - micOffset; // subtract the excess data
Serial.print(" Analog Value = "); Serial.println(trimmedVal, DEC); // for debugging
if (trimmedVal > micRange || trimmedVal < -micRange) { // switch states if the mic picked up a value outside of the normal range
micState = 1;
timeNow = millis(); // reset timer for next state
}
break;
case 1:
anVal = analogRead(micPin); // continue to read input
trimmedVal = anVal - micOffset; // subtract excess data
Serial.println("You are talking "); // for debugging
Serial.print(" Analog Value = "); Serial.println(trimmedVal, DEC);
if ((trimmedVal < micRange || trimmedVal > -micRange) && (millis() > timeNow + 3500)) { // when the input goes back to the normal range and at least 3.5 seconds have passed within this range
micState = 2; // switch states
timeNow = millis(); // reset timere
}
break;
case 2:
alertActions(); // complete generic reactions
anVal = analogRead(micPin); // continue to read input and filter in case other actions need to be taken
trimmedVal = anVal - micOffset; // NOTE: future work could include having HAL continue to listen as he responds and stop/change his reaction if the user interrupts him
Serial.println("responding "); // for debugging
Serial.print(" Analog Value = "); Serial.println(trimmedVal, DEC);
if (millis() > timeNow + 10000) { //respond for 10 seconds until returning to listening.
micState = 0;
}
break;
}
}
/*
fsrTest - This function tests to see if all 5 force sensors can actuate differnt parts
of the head at the same time.
*/
void fsrTest() {
if (neckSensor.forceRange(neckSensorPin) == 0) {
eyeLids.blinkEyes();
}
if (foreheadSensor.forceRange(foreheadSensorPin) == 4) {
eyeBalls.glanceLeft();
}
if (chinSensor.forceRange(chinSensorPin) == 4) {
eyeBrows.raiseAndFurrow();
}
if (jawRightSensor.forceRange(jawRightSensorPin) == 4) {
jaw.regOpenAndClose();
}else{
jaw.neutralMouth();
}
if (jawLeftSensor.forceRange(jawLeftSensorPin) == 4) {
jaw.thrustJawPercent(100);
}else{
jaw.neutralMouth();
}
}
/*
neckTest - General function for testing different neck movements and setpoints.
The commented code can be commented/uncommented in order to test different parts.
See neck.h for details.
*/
void neckTest() {
// neck.tiltTimes(3, 250);
// neck.nodTimes(3, 140);
// neck.neutral();
// neck.moveToDeg(120,2);
// neck.calibration(0,270,A13);
// neck.nod();
// neck.tilt();
switch (headState) { // iterate through different setpoints
case 0:
if ( neck.rotToDeg(35, 2)) { // rotate to the center point
Serial.println("COMMANDED Rotating to 35");
headState = 1;
delay(2000);
}
break;
case 1:
if ( neck.rotToDeg(80, 2)) { // rotate to the left
Serial.println("COMMANDED Rotating to 80");
headState = 2;
delay(2000);
}
break;
case 2:
if ( neck.rotToDeg(0, 2)) { // rotate to the right
Serial.println("COMMANDED Rotating to 0");
headState = 3;
delay(2000);
}
break;
case 3:
if ( neck.rotToDeg(35, 2)) { // rotate to the center
headState = 4;
delay(1000);
}
break;
case 4:
if ( neck.wince(true)) {
headState = 5;
// delay(1000);
}
break;
case 5:
if ( neck.neutral()) {
headState = 6;
delay(1000);
}
break;
case 6:
if (neck.wince(false)) {
headState = 7;
// delay(1000);
}
break;
case 7:
if (neck.neutral()) {
headState = 0;
delay(1000);
}
break;
}
}
/*
pulseTest - General function used to test the regular and irregular pulse
to ensure the BPM calaculation is accurate and the randomizer is indeed random.
See pulse.h for details.
*/
void pulseTest() {
pulse.pulseByBPM(60);
// pulse.randPulse();
}
/*
voiceTest - General function to test the capabilities of the speaker. See voice.h for details
*/
void voiceTest() {
voice.playFile("HELLO.WAV");
Serial.print("Bool === "); Serial.println(voice.stillPlaying());
while (voice.stillPlaying()) {
Serial.println("Still Playing file");
delay(500);
}
}
/*
jawTest - General function to test the capabilities of the jaw movements. See jaw.h for details.
*/
void jawTest() {
// jaw.stepVertOpenClose(3, 3);
// jaw.regOpenAndClose();
jaw.openJawPercent(100);
Serial.println("open jaw all the way");
delay(1000);
jaw.openJawPercent(0);
Serial.println("close jaw all the way");
delay(1000);
jaw.openJawPercent(50);
Serial.println("open jaw Halfway");
delay(1000);
jaw.thrustJawPercent(100);
Serial.println("thrust jaw all the way");
delay(1000);
jaw.thrustJawPercent(0);
Serial.println("retract jaw all the way");
delay(1000);
jaw.thrustJawPercent(50);
Serial.println("thrust jaw Halfway");
delay(1000);
}
/*
headLoop - General testing function for testing different head actions that are called depending
on how much force is applied ot the neck sensor.The commented code can be commented/uncommented
in order to test different parts. See the respective header files for the function descriptions.
*/
void headLoop() {
// pulse.pulseByBPM(pulseNum);
headState = neckSensor.forceRange(neckSensorPin);
switch (headState) {
case 0:
// alertActions();
// neck.moveToDeg(270);
// pulse.pulseByBPM(100);
neck.neutral();
// eyeLids.stepLidsSleepy();
eyeLids.idleBlink();
// eyeBalls.stepEyesLeftandRightSlow();
// eyeBalls.rollEyes();
eyeBalls.idleEyes(0);
// jaw.stepVertOpenClose(3, 3);
break;
case 1:
break;
case 2:
// eyeBrows.raiseAndSlightRaise();
break;
case 3:
// eyeBalls.lookLeftandRight();
eyeBalls.neutralBoth();
break;
case 4:
eyeLids.winkLeft();
// eyeBalls.lookLeftandRight();
eyeBalls.crossEyed();
neck.wince(true);
jaw.regOpenAndClose();
// neck.nodTimes(3, 250);
// neck.moveToDeg(0);
// eyeLids.longClose();
// painActions();
// pulse.pulseByBPM(160);
break;
}
}
};
|
/*
* File: Reader.h
* Author: ovoloshchuk
*
* Created on March 9, 2011, 12:36 PM
*/
#ifndef _READER_H
#define _READER_H
#include "Object.h"
#include "DataContainer.h"
#include <fstream>
#include <map>
#include <string>
class Reader {
public:
Reader(char *filename);
Reader(const Reader& orig);
void fill(DataContainer &container);
virtual ~Reader();
static Object* parseObject(string data, int &id);
private:
static float getNumber(char **data, int &length, char delimiter = ';');
std::ifstream _dataFile;
std::string _filename;
};
#endif /* _READER_H */
|
#include <Unixfunc.h>
#include <iostream>
using namespace std;
int sendFd(int sfd, int fd)
{
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
struct iovec iov[2];
char buf1[10] = "hello";
char buf2[10] = "world";
iov[0].iov_base = buf1;
iov[0].iov_len = 5;
iov[1].iov_base = buf2;
iov[1].iov_len = 5;
msg.msg_iov = iov;
msg.msg_iovlen = 2;
struct cmsghdr *cmsg;
int len = CMSG_LEN(sizeof(int));
cmsg = (struct cmsghdr *)calloc(1, len);
cmsg->cmsg_len = len;
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
*(int *)CMSG_DATA(cmsg) = fd;
msg.msg_control = cmsg;
msg.msg_controllen = len;
int ret;
ret = sendmsg(sfd, &msg, 0);
ERROR_CHECK(ret, -1, "sendmsg");
return 0;
}
int recvFd(int sfd, int *fd)
{
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
struct iovec iov[2];
char buf1[10];
char buf2[10];
iov[0].iov_base = buf1;
iov[0].iov_len = 5;
iov[1].iov_base = buf2;
iov[1].iov_len = 5;
msg.msg_iov = iov;
msg.msg_iovlen = 2;
struct cmsghdr *cmsg;
int len = CMSG_LEN(sizeof(int));
cmsg = (struct cmsghdr *)calloc(1, len);
cmsg->cmsg_len = len;
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
msg.msg_control = cmsg;
msg.msg_controllen = len;
int ret;
ret = recvmsg(sfd, &msg, 0);
ERROR_CHECK(ret, -1, "sendmsg");
*fd = *(int *)CMSG_DATA(cmsg);
return 0;
}
/*
前言
亲属进程之间传递文件描述符:
文件描述符间的传递,并不是简单的值之间的传递,而是要将文件描述符引用的文件一并传递,并且再将文件的引用计数+1,看似简单,实际关联了内核,较为困难
对于这两个函数,需要注意的有以下几点:
1.进程间传递文件描述符相当于是dup, 需要将文件的引用计数+1 ,而不是简单的赋值操作
2.recvFd在sendFd存在的情况下会阻塞等待,如果sendFd不存在,那么recvFd会变为非阻塞模式
父进程打开一个file文件句柄,写入helloWorld, 并将文件句柄传送给子进程, 子进程读出helloWorld
*/
int main()
{
int fds[2];
int ret = socketpair(AF_LOCAL, SOCK_STREAM, 0, fds);//全双工管道
ERROR_CHECK(ret, -1, "socketpair");
cout << "fds[0] = " << fds[0] << " , fsd[1] = " << fds[1] << endl;
if (fork() == 0)
{
close(fds[1]);
int fd;
recvFd(fds[0], &fd);
cout << "child process get fd:" << fd << endl;
char buf[100] = {0};
read(fd, buf, sizeof(buf));
cout << "child process read:" << buf << endl;
close(fds[0]);
exit(0);
}
else
{
close(fds[0]);
int fd = open("file", O_RDWR | O_CREAT, 0755);
ERROR_CHECK(fd, -1, "open");
cout << "father process get fd:" << fd << endl;
write(fd, "helloWorld", 10);
lseek(fd, 0, SEEK_SET);//注意此时文件指针已经读取到了末尾,所以要进行指针偏移,父子进程在文件指针的操作上同步
sendFd(fds[1], fd);
cout << "father process has send fd" << endl;
close(fds[0]);
wait(NULL);
exit(0);
}
return 0;
}
|
/*
* syslog.cpp
*
* Created on: Dec 12, 2012
* Author: suntus
*/
#include "syslog.h"
SysLog::SysLog() {
}
SysLog::~SysLog() {
}
|
//
// Created by 송지원 on 2019-11-13.
//
#include "iostream"
using namespace std;
const int DIV_NUM = 10007;
long long D[1001][11];
int main () {
long long result = 0;
int i, j, k, N;
for (j=0; j<=9; j++) {
D[1][j] = 1;
}
cin >> N;
for (i=2; i<=N; i++) {
for (j=0; j<=9; j++) {
// D[i][j] = D[i-1][j] * (10-j);
// D[i][j] %= DIV_NUM;
for (k=0; k<=j; k++) {
D[i][j] += D[i-1][k];
D[i][j] %= DIV_NUM;
}
}
}
for (j=0; j<=9; j++) {
result += D[N][j];
result %= DIV_NUM;
}
cout << result % DIV_NUM << endl;
}
|
#ifndef TP_PPROJECT_EMPLOYEEOPTIONS_H
#define TP_PPROJECT_EMPLOYEEOPTIONS_H
#include <iostream>
#include "BaseUserOptions.h"
class EmployeeOptions : public BaseUserOptions {
public:
~EmployeeOptions() override = default;
// Get log
void getLog(const LogUpdates& logUpdates, int globalId,
const std::shared_ptr<BaseCallback> callback,
std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override;
// Registration new user
void registration(const UserInfo& authInfo, int globalId,
const std::shared_ptr<BaseCallback> callback,
std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override;
};
#endif
|
/*
Name : Aman Jain
Date : 11-07-2020
Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s.
Time Complexity :O(logn)
*/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll binaryStrings(ll n, ll dp[]){
if(n<1)
return 0;
if(n==1)
return 2;
if(n==2)
return 3;
if(dp[n]!=0)
return dp[n];
dp[n]=binaryStrings(n-1,dp)+ binaryStrings(n-2,dp);
return dp[n];
}
int main(){
int t;
cin>>t;
while(t--){
ll n;
cin>>n;
ll dp[1000]={0};
cout<<binaryStrings(n,dp)<<endl;
}
}
|
#include "corridor_navigation/corridor_navigation_ros.h"
#include <ros/console.h>
int main(int argc, char **argv)
{
if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug))
{
ros::console::notifyLoggerLevelsChanged();
}
ROS_DEBUG("Starting corridor navigation node");
ros::init(argc, argv, "corridor_navigation_node");
ros::NodeHandle nh("~");
CorridorNavigationROS corridor_navigation_ros(nh);
corridor_navigation_ros.run();
ros::spin();
return 0;
}
|
//
// Created by griha on 09.12.17.
//
#pragma once
#ifndef MIKRONSST_HSM_ENCODING_HPP
#define MIKRONSST_HSM_ENCODING_HPP
#include <stdlib.h>
#include <string>
namespace griha { namespace hsm {
inline std::wstring to_wstr(const std::string &src) {
std::wstring ret(src.size(), L' ');
ret.resize(std::mbstowcs(&ret[0], src.c_str(), src.size()));
return ret;
}
inline std::string from_wstr(const std::wstring &src) {
std::string ret(src.size() * sizeof(wchar_t), ' ');
ret.resize(std::wcstombs(&ret[0], src.c_str(), ret.size()));
return ret;
}
}} // namespace griha::hsm
#endif //MIKRONSST_HSM_ENCODING_HPP
|
#pragma once
#include "utils/time_utils.hpp"
#include "utils/exception.hpp"
#include <chrono>
#include <mutex>
using namespace std;
using namespace chrono;
namespace nora {
enum class gid_type {
ROLE,
NOTICE,
MAIL,
LEAGUE,
GLADIATOR,
ARENA_CHALLENGE_RECORD,
RECHARGE_ORDER,
MANSION_FURNITURE,
MANSION_QUEST,
CHILD,
CONFLICT_BATTLE_RECORD,
GUANPIN_CHANGED_RECORD,
MIRROR_ROLE,
};
#pragma pack(push)
#pragma pack(1)
struct gid_template {
uint8_t type_: 5;
uint16_t server_id_: 11;
uint32_t time_;
uint16_t serial_;
};
#pragma pack(pop)
class gid {
public:
static gid& instance() {
static gid inst;
return inst;
}
void set_server_id(int server_id);
uint64_t new_gid(gid_type type);
gid_type get_type(uint64_t gid);
uint64_t change_type(uint64_t gid, gid_type type);
int get_server_id(uint64_t gid);
private:
mutable mutex mutex_;
uint32_t serial_time_;
map<gid_type, uint32_t> serial_;
int server_id_;
};
}
|
#include "Particle.h"
Particle::Particle() = default;
Particle::Particle(const int id) : life(0), id(id), temperature(0)
{
isBurning = false;
solid = false;
color = sf::Color::Black;
}
|
// Wed Aug 24 15:46:50 EDT 2016
// Evan S Weinberg
// Include file for CR-M
// WARNING!!!
// MULTISHIFT CR IS A PARTICULARLY UNSTABLE ALGORITHM.
// TECHNICALLY, ONE SHOULD MONITOR CONVERGENCE BY LOOKING FOR \zeta_n < 1.
// On a more mathematical level, CR appears to generate a Krylov space in
// Ab, instead of in b (which is what CG does). This follows from noting
// the solution is A-orthogonal to the Krylov space K(A, b), as opposed to
// just orthogonal.
// Under a shift, a Krylov space in Ab -> a shift in (A+\sigma)b.
// Thus, the shifted operator doesn't generate the same Krylov space
// as the original operator!
#ifndef ESW_INVERTER_CR_M
#define ESW_INVERTER_CR_M
#include <string>
#include <complex>
using std::complex;
#include "inverter_struct.h"
#include "verbosity.h"
// Multishift CR defined in http://arxiv.org/pdf/hep-lat/9612014.pdf
inversion_info minv_vector_cr_m(double **phi, double *phi0, int n_shift, int size, int resid_freq_check, int max_iter, double eps, double* shifts, void (*matrix_vector)(double*,double*,void*), void* extra_info, bool worst_first = false, inversion_verbose_struct* verbosity = 0);
inversion_info minv_vector_cr_m(complex<double> **phi, complex<double> *phi0, int n_shift, int size, int resid_freq_check, int max_iter, double eps, double* shifts, void (*matrix_vector)(complex<double>*,complex<double>*,void*), void* extra_info, bool worst_first = false, inversion_verbose_struct* verbosity = 0);
// multishift CR starts with 0 initial guess, so a restarted version wouldn't work.
#endif
|
// #include "base.h"
// Graph::Graph(){
// int n = LENGTH(chars);
// ch2int = new map<char, int>();
// int2ch = new map<int, char>();
// for(int i=0; i<n; i++){
// ch2int->insert(pair<char, int>(chars[i], i));
// int2ch->insert(pair<int, char>(i, chars[i]));
// }
// }
// Graph::Graph(vector<char> &vertexs){
// int n = LENGTH(vertexs);
// ch2int = new map<char, int>();
// int2ch = new map<int, char>();
// for(int i=0; i<n; i++){
// ch2int->insert(pair<char, int>(vertexs[i], i));
// int2ch->insert(pair<int, char>(i, vertexs[i]));
// }
// }
// Graph::~Graph(){
// if(ch2int)
// delete ch2int;
// if(int2ch)
// delete int2ch;
// }
// /* ------------------------------------ 图矩阵 ------------------------------------------ */
// void Graph::createGraphMatrx(const vector<vector<char>> &letters, const vector<int> &weights, const bool &ori,
// vector<vector<GMNode*>> &matrix){
// /**
// * @letters: {{'A', 'B'}, {'B', 'C'}, ...}
// * @weights: { 1, 2, ...}
// * @ori: 创建的图是否为有向图
// */
// // 初始化
// map<char, int>::iterator it1, it2;
// for(int i=0; i<letters.size(); i++)
// {
// it1 = ch2int->find(letters[i][0]), it2 = ch2int->find(letters[i][1]);
// GMNode* mNode = new GMNode(i, weights[i], it1->second, it2->second);
// matrix[it1->second][it2->second] = mNode;
// if (ori)
// matrix[it2->second][it1->second] = mNode;
// }
// }
// void Graph::printMatrix(const vector<vector<GMNode*>> &matrix){
// for(int i=0; i < matrix.size(); i++){
// for(int j=0; j<matrix[i].size(); j++)
// if (matrix[i][j] != nullptr)
// cout << matrix[i][j]->weight << ' ';
// else
// cout << 0 << ' ';
// cout << endl;
// }
// }
// void Graph::testMatrix(){
// vector<char> vertexs = {'A', 'B', 'C', 'D', 'E', 'F'};
// vector<vector<char>> arcs = {{'A', 'B'}, {'A', 'C'}, {'B', 'F'}, {'C', 'D'}, {'D', 'E'}};
// vector<int> weights = {1, 3, 5, 2, 4};
// bool ori = true;
// int nVertexs = vertexs.size();
// // cout << sizeof(vertexs) << ' ' << sizeof(int) << ' ' << nVertexs << endl;
// vector<vector<GMNode*>> matrix(nVertexs, vector<GMNode*>(nVertexs, 0));
// createGraphMatrx(arcs, weights, ori, matrix);
// printMatrix(matrix);
// }
// /* ------------------------------------ 图链表 ------------------------------------------ */
// void Graph::createGraphTable(const vector<vector<char>> &letters, const vector<int> &weights, const bool &ori, vector<GTNode*> &table){
// map<char, int>* heads = new map<char, int>(); // 存储表头,用于判断是否需要重新创建表头
// map<char, int>::iterator it;
// int headId=0;
// for(int i=0; i<letters.size(); i++)
// {
// it = heads->find(letters[i][0]); // 查找找到的表头
// if(it == heads->end()) // 创建新的表头
// {
// GTNode* n2 = new GTNode(letters[i][1], weights[i], nullptr);
// GTNode* n1 = new GTNode(letters[i][0], 0, n2);
// heads->insert(pair<char, int>(letters[i][0], headId++));
// table.push_back(n1);
// }
// else
// {
// GTNode* head = table[it->second];
// while(head->next)
// head = head->next;
// head->next = new GTNode(letters[i][1], weights[i], nullptr);
// }
// if (ori == false){ // 无向图,需要创建反向链接
// it = heads->find(letters[i][1]); // 查找找到的表头
// if(it == heads->end()) // 创建新的表头
// {
// GTNode* n2 = new GTNode(letters[i][0], weights[i], nullptr);
// GTNode* n1 = new GTNode(letters[i][1], 0, n2);
// heads->insert(pair<char, int>(letters[i][1], headId++));
// table.push_back(n1);
// }
// else
// {
// GTNode* head = table[it->second];
// while(head->next)
// head = head->next;
// head->next = new GTNode(letters[i][0], weights[i], nullptr);
// }
// }
// }
// }
// void Graph::printTable(const vector<GTNode*> &table)
// {
// for(int i=0; i<table.size(); i++){
// GTNode* n = table[i];
// cout << n->name;
// while(n->next){
// cout << " -" << n->next->weight << "-> " << n->next->name;
// n = n->next;
// }
// cout << endl;
// }
// }
// void Graph::testTable()
// {
// vector<char> vertexs = {'A', 'B', 'C', 'D', 'E', 'F'};
// vector<vector<char>> arcs = {{'A', 'B'}, {'A', 'C'}, {'B', 'F'}, {'C', 'D'}, {'D', 'E'}};
// vector<int> weights = {1, 3, 5, 2, 4};
// bool ori = false;
// vector<GTNode*> table;
// createGraphTable(arcs, weights, ori, table);
// cout << table.size() << endl; // bug: empty table
// printTable(table);
// }
|
#include "NextDate.h"
#include "gtest/gtest.h"
class NextDateTest : public testing::Test{
protected:
//virtual void Setup();
//virtual void TearDown();
};
TEST_F(NextDateTest, BoundaryValueTesting)
{
EXPECT_EQ(TellNextDate(1812,1,1),"1812/1/2");
EXPECT_EQ(TellNextDate(1812,1,15),"1812/1/16");
EXPECT_EQ(TellNextDate(2012,1,30),"2012/1/31");
EXPECT_EQ(TellNextDate(1813,1,31),"1813/2/1");
}
TEST_F(NextDateTest, EquivalenceClassTesting)
{
//month =>30,31,February
//day -> 1~28,29,30,31
//year = 2000, common year, non-century leap year
EXPECT_EQ(TellNextDate(2000,6,14),"2000/6/15");
EXPECT_EQ(TellNextDate(1996,7,29),"1996/7/30");
EXPECT_EQ(TellNextDate(2002,2,30),"Invalid Input");
EXPECT_EQ(TellNextDate(2000,6,31),"Invalid Input");
}
TEST_F(NextDateTest, EdgeTesting)
{
EXPECT_EQ(TellNextDate(1813,1,1),"1813/1/2");
EXPECT_EQ(TellNextDate(1813,1,31),"1813/2/1");
EXPECT_EQ(TellNextDate(2000,2,29),"2000/3/1");
EXPECT_EQ(TellNextDate(1813,1,25),"1813/1/26");
EXPECT_EQ(TellNextDate(1991,9,31),"Invalid Input");
}
TEST_F(NextDateTest, DecisionTableTest)
{
EXPECT_EQ(TellNextDate(2001,4,15),"2001/4/16");
EXPECT_EQ(TellNextDate(2001,4,30),"2001/5/1");
EXPECT_EQ(TellNextDate(2001,4,31),"Invalid Input");
EXPECT_EQ(TellNextDate(2001,2,29),"Invalid Input");
EXPECT_EQ(TellNextDate(2001,2,30),"Invalid Input");
EXPECT_EQ(TellNextDate(2004,2,29),"2004/3/1");
}
TEST_F(NextDateTest, C0Test)
{
EXPECT_EQ("Invalid Input",TellNextDate(1996,1,0));
EXPECT_EQ("1996/2/1",TellNextDate(1996,1,31));
EXPECT_EQ("1996/1/2",TellNextDate(1996,1,1));
EXPECT_EQ("Invalid Input",TellNextDate(1996,4,0));
EXPECT_EQ("1996/5/1",TellNextDate(1996,4,30));
EXPECT_EQ("1996/4/6",TellNextDate(1996,4,5));
EXPECT_EQ("1996/12/2",TellNextDate(1996,12,1));
EXPECT_EQ("1997/1/1",TellNextDate(1996,12,31));
EXPECT_EQ("Invalid Input",TellNextDate(1996,12,32));
EXPECT_EQ("1996/2/28",TellNextDate(1996,2,27));
EXPECT_EQ("Invalid Input",TellNextDate(1996,2,0));
EXPECT_EQ("1996/2/29",TellNextDate(1996,2,28));
EXPECT_EQ("1997/3/1",TellNextDate(1997,2,28));
EXPECT_EQ("1996/3/1",TellNextDate(1996,2,29));
EXPECT_EQ("Invalid Input",TellNextDate(1997,2,29));
}
TEST_F(NextDateTest, C1Test)
{
//1,2,3
EXPECT_EQ("1996/2/1",TellNextDate(1996,1,31));
//1,4,5
EXPECT_EQ("Invalid Input",TellNextDate(1996,4,31));
//1,6
EXPECT_EQ("1996/12/31",TellNextDate(1996,12,30));
//1,6,7
EXPECT_EQ("1997/1/1",TellNextDate(1996,12,31));
//1,8
EXPECT_EQ("1996/2/28",TellNextDate(1996,2,27));
//1,8,9,10,12
EXPECT_EQ("1996/3/1",TellNextDate(1996,2,29));
//1,8,9,11
EXPECT_EQ("1996/2/29",TellNextDate(1996,2,28));
}
TEST_F(NextDateTest, MCDCTest)
{
//day<31 day>0(case1)
EXPECT_EQ("1996/1/31",TellNextDate(1996,1,30));
EXPECT_EQ("1996/2/1",TellNextDate(1996,1,31));
//day<30 day>0(case2)
EXPECT_EQ("1996/4/2",TellNextDate(1996,4,1));
EXPECT_EQ("Invalid Input",TellNextDate(1996,4,31));
//day<31 day>0(case3)
EXPECT_EQ("1996/12/31",TellNextDate(1996,12,30));
EXPECT_EQ("1997/1/1",TellNextDate(1996,12,31));
//day<28 day>0(case4)
EXPECT_EQ("1996/2/16",TellNextDate(1996,2,15));
EXPECT_EQ("1996/3/1",TellNextDate(1996,2,29));
//year%4==0 year%100!=0 year%400==0
EXPECT_EQ("1996/2/29",TellNextDate(1996,2,28));
EXPECT_EQ("1997/3/1",TellNextDate(1997,2,28));
}
|
#include "basis.hpp"
#include "hierarchical_basis.hpp"
#include "orthonormal_basis.hpp"
#include "three_point_basis.hpp"
namespace Time {
bool Element1D::Refine() {
if (is_full()) return false;
make_child(/* parent */ this, /* left_child */ true);
make_child(/* parent */ this, /* left_child */ false);
return true;
}
const std::array<ContLinearScalingFn *, 2> &Element1D::RefineContLinear() {
if (!phi_cont_lin_[0] || !phi_cont_lin_[1]) {
auto phi_parents = parent()->RefineContLinear();
// Check whether we are the left child element.
if (index_ % 2 == 0) {
phi_parents[0]->RefineMiddle();
phi_parents[0]->RefineRight();
} else {
phi_parents[1]->RefineLeft();
phi_parents[1]->RefineMiddle();
}
assert(phi_cont_lin_[0] && phi_cont_lin_[1]);
}
return phi_cont_lin_;
}
const std::array<OrthonormalWaveletFn *, 2> &Element1D::RefinePsiOrthonormal() {
if (!psi_ortho_[0] || !psi_ortho_[1]) {
assert(level() > 0);
const auto &psi_parent = parent()->RefinePsiOrthonormal();
psi_parent[0]->Refine();
assert(psi_ortho_[0] && psi_ortho_[1]);
}
return psi_ortho_;
}
HierarchicalWaveletFn *Element1D::RefinePsiHierarchical() {
assert(this->level_ != 0);
if (!psi_hierarch_) {
// There are two HierarchicalWavelets on level 0, so need to do
// a trick.
if (this->level_ == 1) {
assert(parent()->parent()->psi_hierarch_);
parent()->parent()->psi_hierarch_->children().at(0)->Refine();
} else {
parent()->RefinePsiHierarchical()->Refine();
}
}
assert(psi_hierarch_);
return psi_hierarch_;
}
std::pair<double, double> Element1D::Interval() const {
assert(!is_metaroot());
double h = 1.0 / (1LL << level_);
return {h * index_, h * (index_ + 1)};
}
double Element1D::GlobalCoordinates(double bary2) const {
assert(0 <= bary2 && bary2 <= 1);
auto [a, b] = Interval();
return a + bary2 * (b - a);
}
} // namespace Time
|
#pragma once
#include <cstdint>
namespace OpenFlight
{
//------------------------------------------------------------------------------
struct Color3f
{
Color3f() : mRed(0.0), mGreen(0.0), mBlue(0.0) {}
Color3f(float iR, float iG, float iB) : mRed(iR), mGreen(iG), mBlue(iB) {}
float mRed;
float mGreen;
float mBlue;
};
//------------------------------------------------------------------------------
struct Color4f
{
Color4f() : mRed(0.0), mGreen(0.0), mBlue(0.0), mAlpha(0.0) {}
Color4f(float iR, float iG, float iB, float iA) : mRed(iR), mGreen(iG), mBlue(iB), mAlpha(iA) {}
float mRed;
float mGreen;
float mBlue;
float mAlpha;
};
//------------------------------------------------------------------------------
//unsigned byte
struct Color4ub
{
Color4ub() : mRed(0), mGreen(0), mBlue(0), mAlpha(0) {}
Color4ub(int iC) : mRed( (iC >> 24) & 0x000000ff), mGreen( (iC >> 16) & 0x000000ff), mBlue( (iC >> 8) & 0x000000ff), mAlpha(iC & 0x000000ff) {}
unsigned char mRed;
unsigned char mGreen;
unsigned char mBlue;
unsigned char mAlpha;
};
//------------------------------------------------------------------------------
struct Matrix4f
{
Matrix4f(); //identity matrix
enum internalStorage{isRowMajor = 0, isColumnMajor};
float mData[4][4];
internalStorage mInternalStorage;
};
//------------------------------------------------------------------------------
struct Vector2f
{
Vector2f() : mX(0.0f), mY(0.0f){}
~Vector2f(){}
float mX;
float mY;
};
//------------------------------------------------------------------------------
struct Vector2i
{
Vector2i() : mX(0), mY(0){}
~Vector2i(){}
int mX;
int mY;
};
//------------------------------------------------------------------------------
struct Vector3f
{
Vector3f() : mX(0.0f), mY(0.0f), mZ(0.0f) {}
~Vector3f(){}
float mX;
float mY;
float mZ;
};
//------------------------------------------------------------------------------
struct Vector3d
{
Vector3d() : mX(0.0), mY(0.0), mZ(0.0) {}
~Vector3d(){}
double mX;
double mY;
double mZ;
};
//------------------------------------------------------------------------------
// maps the data for records:
// ocVertexWithColor = 68 , //“Vertex with Color Record”
// ocVertexWithColorAndNormal = 69 , //“Vertex with Color and Normal Record”
// ocVertexWithColorNormalAndUv = 70 , //“Vertex with Color, Normal and UV Record”
// ocVertexWithColorAndUv = 71 , //“Vertex with Color and UV Record”
//
// Notes:
// The mFlags is somehow tricky over here. As stated in the documentation
// Flags (bits, from left to right)
// 0 = Start hard edge
// 1 = Normal frozen
// 2 = No color
// 3 = Packed color
// 4-15 = Spare
//
// By left to right, it appears they mean most significant to least significant
//
struct Vertex
{
Vertex() : mColorNameIndex(0), mFlags(0), mCoordinate(), mNormal(),
mTextureCoordinate(), mPackedColor(), mColorIndex(0) {}
~Vertex() {}
enum flag{ fStartHardEdge = 1 << (15-0), fNormalFrozen = 1 << (15-1),
fNoColor = 1 << (15-2), fPackedColor = 1 << (15-3)};
bool hasFlag(flag iFlag) const;
uint16_t mColorNameIndex;
uint16_t mFlags;
Vector3d mCoordinate;
Vector3f mNormal;
Vector2f mTextureCoordinate;
Color4ub mPackedColor;
uint32_t mColorIndex;
};
}
|
class ACE_Module;
class ACE_ModuleInteraction;
class CfgVehicles {
class Man;
class CAManBase: Man {
class ACE_Actions {
class ACE_MainActions {
displayName = CSTRING(MainAction);
distance = 4;
condition = QUOTE(true);
statement = "";
icon = "\a3\ui_f\data\IGUI\Cfg\Actions\eject_ca.paa";
selection = "pelvis";
class ACE_GetDown {
displayName = CSTRING(GetDown);
condition = "false";
statement = QUOTE([ARR_2(_player,_target)] call DFUNC(getDown));
showDisabled = 0;
priority = 2.2;
};
class ACE_SendAway {
displayName = CSTRING(SendAway);
condition = "false";
statement = QUOTE([ARR_2(_player,_target)] call DFUNC(sendAway));
showDisabled = 0;
priority = 2.0;
};
class ACE_ApplyHandcuffs {
displayName = CSTRING(SetCaptive);
selection = "righthand";
distance = 2;
condition = "false";
statement = QUOTE([ARR_2(_player, _target)] call FUNC(doApplyHandcuffs));
exceptions[] = {};
icon = QUOTE(PATHTOF(UI\handcuff_ca.paa));
};
};
};
};
class LandVehicle;
class Car: LandVehicle {
class ACE_Actions {
class ACE_MainActions {
displayName = "ADINT ACTION";
selection = "motor";
distance = 10;
condition = "true";
class ACE_Passengers
{
displayName = "Durchsuchen";
condition = "true";
statement = "";
};
class ACE_LampTurnOn
{
displayName = "ADINT 2";
condition = "true";
statement = "";
selection = "";
distance = 10;
};
class ACE_LampTurnOff
{
displayName = "ADINT 3";
condition = "";
statement = "";
selection = "";
distance = 10;
};
};
};
};
};
|
#ifndef SCROLLING_BG_H
#define SCROLLING_BG_H
#include "game.hpp"
#include <sgfx/image.hpp>
#include <sgfx/primitives.hpp>
#include <chrono>
#include <memory>
#include <string>
class scrolling_bg final : public game_object {
public:
scrolling_bg(game_proxy proxy, std::string const& image) : img_{sgfx::load_rle(image)} {}
game_object::status update(game_proxy proxy, std::chrono::milliseconds delta) override
{
pos_.y = (pos_.y + scroll_speed_) % img_.height();
return game_object::status::alive;
}
void draw(sgfx::canvas_view target) const override
{
sgfx::draw(target, img_, pos_);
sgfx::draw(target, img_, pos_ - sgfx::vec{0, img_.height()});
}
private:
sgfx::rle_image img_;
sgfx::point pos_{0, 0};
int const scroll_speed_{2};
};
#endif
|
//: C12:OverloadingUnaryOperators.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
#include <iostream>
using namespace std;
// Funkcje niebedace funkcjami skladowymi:
class Integer {
long i;
Integer* This() { return this; }
public:
Integer(long ll = 0) : i(ll) {}
// Brak skutkow ubocznych - argumenty sa
// referencjami do stalych:
friend const Integer&
operator+(const Integer& a);
friend const Integer
operator-(const Integer& a);
friend const Integer
operator~(const Integer& a);
friend Integer*
operator&(Integer& a);
friend int
operator!(const Integer& a);
// Wystepuja skutki uboczne - argumenty nie sa
// referencjami do stalych:
// Operator przedrostkowy:
friend const Integer&
operator++(Integer& a);
// Operator przyrostkowy:
friend const Integer
operator++(Integer& a, int);
// Operator przedrostkowy:
friend const Integer&
operator--(Integer& a);
// Operator przyrostkowy:
friend const Integer
operator--(Integer& a, int);
};
// Operatory globalne:
const Integer& operator+(const Integer& a) {
cout << "+Integer\n";
return a; // Jednoargumentowy operator + nic nie robi
}
const Integer operator-(const Integer& a) {
cout << "-Integer\n";
return Integer(-a.i);
}
const Integer operator~(const Integer& a) {
cout << "~Integer\n";
return Integer(~a.i);
}
Integer* operator&(Integer& a) {
cout << "&Integer\n";
return a.This(); // &a jest rekurencyjne!
}
int operator!(const Integer& a) {
cout << "!Integer\n";
return !a.i;
}
// Operator przedrostkowy - zwraca wartosc po inkrementacji:
const Integer& operator++(Integer& a) {
cout << "++Integer\n";
a.i++;
return a;
}
// Operator przyrostkowy - zwraca wartosc przed inkrementacja:
const Integer operator++(Integer& a, int) {
cout << "Integer++\n";
Integer before(a.i);
a.i++;
return before;
}
// Operator przedrostkowy - zwraca wartosc po dekrementacji:
const Integer& operator--(Integer& a) {
cout << "--Integer\n";
a.i--;
return a;
}
// Operator przyrostkowy - zwraca wartosc przed dekrementacja:
const Integer operator--(Integer& a, int) {
cout << "Integer--\n";
Integer before(a.i);
a.i--;
return before;
}
// Prezentacja dzialania przeciazanych operatorow:
void f(Integer a) {
+a;
-a;
~a;
Integer* ip = &a;
!a;
++a;
a++;
--a;
a--;
}
// Funkcje skladowe (niejawny argument "this"):
class Byte {
unsigned char b;
public:
Byte(unsigned char bb = 0) : b(bb) {}
// Brak skutkow ubocznych - stale funkcje skladowe:
const Byte& operator+() const {
cout << "+Byte\n";
return *this;
}
const Byte operator-() const {
cout << "-Byte\n";
return Byte(-b);
}
const Byte operator~() const {
cout << "~Byte\n";
return Byte(~b);
}
Byte operator!() const {
cout << "!Byte\n";
return Byte(!b);
}
Byte* operator&() {
cout << "&Byte\n";
return this;
}
// Wystepuja skutki uboczne - funkcje skladowe
// nie bedace stalymi:
const Byte& operator++() { // Przedrostek
cout << "++Byte\n";
b++;
return *this;
}
const Byte operator++(int) { // Przyrostek
cout << "Byte++\n";
Byte before(b);
b++;
return before;
}
const Byte& operator--() { // Przedrostek
cout << "--Byte\n";
--b;
return *this;
}
const Byte operator--(int) { // Przyrostek
cout << "Byte--\n";
Byte before(b);
--b;
return before;
}
};
void g(Byte b) {
+b;
-b;
~b;
Byte* bp = &b;
!b;
++b;
b++;
--b;
b--;
}
int main() {
Integer a;
f(a);
Byte b;
g(b);
} ///:~
|
#include "Resource.h"
Resource::Resource(String name) {
_name = name;
_amount = 0;
}
Resource::Resource(String name, int initialAmount) {
_name = name;
_amount = initialAmount;
}
int Resource::add(int amount) {
_amount += amount;
return _amount;
}
int Resource::getAmount() {
return _amount;
}
|
#include "gb_dbg.h"
#include "gb_memory.h"
#include "gb_util.h"
#include <iostream>
void Debug::run(void) {
// check events
stopped |= check_breakpoints();
stopped |= check_watchpoints();
stopped |= step_resume;
step_resume = false;
// drop into debugger prompt for break/watch/step
while (stopped) {
print_prompt();
// read command line input
std::string cmd_text = gb_util::get_console_line();
// tokenize and execute
std::vector<std::string> argv = gb_util::split(cmd_text, ' ');
// execute command handler
exec_dbg_command(argv);
}
// append new serial data to buffer
if (mem->serial_tx_initd) {
serial_data.push_back(mem->serial_tx_data);
mem->serial_tx_initd = false;
}
}
void Debug::init(GB_Sys *gb_sys) {
cpu = gb_sys->cpu;
mem = gb_sys->mem;
// add commands
add_command("help", &Debug::execute_help_cmd, "prints help message");
add_command("break", &Debug::execute_break_cmd, "sets breakpoint at address");
// add_command("watch", &Debug::execute_watch_cmd, "sets memory watchpoint at address");
add_command("continue", &Debug::execute_continue_cmd, "continue emulator execution");
add_command("step", &Debug::execute_step_cmd, "execute a single instruction");
add_command("examine", &Debug::execute_examine_cmd, "display memory contents");
//add_command("info", &Debug::execute_info_cmd, "prints name and values of registers");
//add_command("reset", execute_reset_cmd,"reset emulator.");
add_command("quit", &Debug::execute_quit_cmd, "quits emulator");
}
bool Debug::check_breakpoints(void) {
if (breakpoints.count(cpu->registers.pc)) {
if (breakpoints.at(cpu->registers.pc).enabled ) {
print_cpu_state();
return true;
}
}
return false;
}
bool Debug::check_watchpoints(void) {
for (auto &w : watchpoints) {
if (!w.second.enabled) {
continue;
}
if (mem->read_byte(w.second.addr) != w.second.prev_val) {
print_cpu_state();
return true;
}
}
return false;
}
void Debug::print_cpu_state(void) {
auto opcode = mem->read_byte(cpu->registers.pc);
// output : 0xADDR | Instruction Disassembly
std::cout << "0x" << hex << setfill('0') << setw(4)
<< cpu->registers.pc
<< " | "
<< cpu->instrs[opcode].disassembly << "\n";
// output for each reg: name 0xBEEF
std::cout << "Registers: " << "\n";
std::cout
<< "af 0x" << hex << setfill('0') << setw(4)
<< unsigned(cpu->registers.af) << "\n"
<< "bc 0x" << hex << setfill('0') << setw(4)
<< unsigned(cpu->registers.bc) << "\n"
<< "de 0x" << hex << setfill('0') << setw(4)
<< unsigned(cpu->registers.de) << "\n"
<< "hl 0x" << hex << setfill('0') << setw(4)
<< unsigned(cpu->registers.hl) << "\n"
<< "sp 0x" << hex << setfill('0') << setw(4)
<< unsigned(cpu->registers.sp) << "\n"
<< "pc 0x" << hex << setfill('0') << setw(4)
<< unsigned(cpu->registers.pc) << "\n";
}
void Debug::print_prompt(void) {
std::cout << "> ";
}
// TODO(connor): Add a typedef for func arguement
void Debug::add_command(std::string name,
void (Debug::*func)(CmdArgs &),
std::string desc) {
CommandDef cmd = {name, std::bind(func, this, std::placeholders::_1), desc};
commands.push_back(cmd);
}
void Debug::exec_dbg_command(std::vector<std::string> &argv) {
// search commands
for (auto &c : commands) {
if (argv[0] == c.name || argv[0][0] == c.name[0]) {
try {
c.handler(argv);
} catch (std::out_of_range) {
std::cout << "Error: Arg out of range"
<< "\n";
} catch (std::invalid_argument) {
std::cout << "Error: Invalid arguement"
<< "\n";
}
}
}
}
void Debug::execute_help_cmd(CmdArgs &argv) {
std::cout << "Debugger commands:" << "\n";
for (auto &c : commands) {
std::cout << std::left << std::setfill(' ')
<< std::setw(PrintWidth) << c.name
<< std::setw(PrintWidth) << "--"
<< std::setw(PrintWidth) << c.desc << "\n";
}
}
void Debug::execute_break_cmd(std::vector<std::string> &argv) {
// insert breakpoint if it doesn't already exist
auto addr = gb_util::stous(argv[1], nullptr, 0);
if (breakpoints.count(addr)) {
std::cout << "breakpoint exists\n";
} else {
breakpoints.insert({addr, Breakpoint{.enabled = true}});
cout << "breakpoint set\n";
}
}
void Debug::execute_watch_cmd(std::vector<std::string> &argv) {
// insert watchpoint if it doesn't already exist
auto addr = gb_util::stous(argv[1], nullptr, 0);
if (watchpoints.count(addr)) {
std::cout << "watchpoint exists\n";
} else {
watchpoints.insert({addr, Watchpoint{.addr=addr, .prev_val=0x00, .enabled = true}});
cout << "watchpoint set\n";
}
}
void Debug::execute_continue_cmd(std::vector<std::string> &argv) {
stopped = false;
}
void Debug::execute_step_cmd(std::vector<std::string> &argv) {
print_cpu_state();
stopped = false;
step_resume = true;
}
void Debug::execute_examine_cmd(std::vector<std::string> &argv) {
unsigned short addr = std::stoul(argv[1], nullptr, 0);
unsigned short blocks;
// check if num blocks arg specified
if (argv.size() == 3) {
blocks = std::stoul(argv[2], nullptr, 0);
} else {
blocks = 1;
}
mem->print_memory_range(addr, blocks);
}
// TODO(connor): info command with lcd, cpu, and mem modifiers
//void Debug::execute_info_cmd(std::vector<std::string> &argv) {}
// TODO
//void Debug::execute_reset_cmd(std::vector<std::string> &argv) {}
void Debug::execute_quit_cmd(std::vector<std::string> &argv) {
std::cout << "exiting\n";
cpu->stop = true;
stopped = false;
}
void Debug::write_serial_log_file(std::string filepath) {
std::ofstream out(filepath, std::ofstream::out | std::ofstream::trunc);
for (const auto &c : serial_data ) out << char(c);
out << "\0";
}
|
// Created on: 1995-04-26
// Created by: Modelistation
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _ChFi3d_ChBuilder_HeaderFile
#define _ChFi3d_ChBuilder_HeaderFile
#include <BRepAdaptor_Surface.hxx>
#include <ChFi3d_Builder.hxx>
#include <ChFiDS_ChamfMethod.hxx>
#include <ChFiDS_ChamfMode.hxx>
#include <ChFiDS_SecHArray1.hxx>
#include <ChFiDS_ListOfStripe.hxx>
#include <ChFiDS_SequenceOfSurfData.hxx>
#include <ChFiDS_ElSpine.hxx>
#include <math_Vector.hxx>
#include <TopAbs_Orientation.hxx>
#include <TopAbs_State.hxx>
class TopoDS_Shape;
class TopoDS_Edge;
class TopoDS_Face;
class ChFiDS_SurfData;
class ChFiDS_Spine;
class Adaptor3d_TopolTool;
class TopoDS_Vertex;
class ChFiDS_Stripe;
//! construction tool for 3D chamfers on edges (on a solid).
class ChFi3d_ChBuilder : public ChFi3d_Builder
{
public:
DEFINE_STANDARD_ALLOC
//! initializes the Builder with the Shape <S> for the
//! computation of chamfers
Standard_EXPORT ChFi3d_ChBuilder(const TopoDS_Shape& S, const Standard_Real Ta = 1.0e-2);
//! initializes a contour with the edge <E> as first
//! (the next are found by propagation ).
//! The two distances (parameters of the chamfer) must
//! be set after.
//! if the edge <E> has more than 2 adjacent faces
Standard_EXPORT void Add (const TopoDS_Edge& E);
//! initializes a new contour with the edge <E> as first
//! (the next are found by propagation ), and the
//! distance <Dis>
//! if the edge <E> has more than 2 adjacent faces
Standard_EXPORT void Add (const Standard_Real Dis, const TopoDS_Edge& E);
//! set the distance <Dis> of the fillet
//! contour of index <IC> in the DS with <Dis> on <F>.
//! if the face <F> is not one of common faces
//! of an edge of the contour <IC>
Standard_EXPORT void SetDist (const Standard_Real Dis,
const Standard_Integer IC,
const TopoDS_Face& F);
//! gives the distances <Dis> of the fillet
//! contour of index <IC> in the DS
Standard_EXPORT void GetDist (const Standard_Integer IC, Standard_Real& Dis) const;
//! initializes a new contour with the edge <E> as first
//! (the next are found by propagation ), and the
//! distance <Dis1> and <Dis2>
//! if the edge <E> has more than 2 adjacent faces
Standard_EXPORT void Add (const Standard_Real Dis1,
const Standard_Real Dis2,
const TopoDS_Edge& E,
const TopoDS_Face& F);
//! set the distances <Dis1> and <Dis2> of the fillet
//! contour of index <IC> in the DS with <Dis1> on <F>.
//! if the face <F> is not one of common faces
//! of an edge of the contour <IC>
Standard_EXPORT void SetDists (const Standard_Real Dis1,
const Standard_Real Dis2,
const Standard_Integer IC,
const TopoDS_Face& F);
//! gives the distances <Dis1> and <Dis2> of the fillet
//! contour of index <IC> in the DS
Standard_EXPORT void Dists (const Standard_Integer IC,
Standard_Real& Dis1,
Standard_Real& Dis2) const;
//! initializes a new contour with the edge <E> as first
//! (the next are found by propagation ), and the
//! distance <Dis1> and <Angle>
//! if the edge <E> has more than 2 adjacent faces
Standard_EXPORT void AddDA (const Standard_Real Dis,
const Standard_Real Angle,
const TopoDS_Edge& E,
const TopoDS_Face& F);
//! set the distance <Dis> and <Angle> of the fillet
//! contour of index <IC> in the DS with <Dis> on <F>.
//! if the face <F> is not one of common faces
//! of an edge of the contour <IC>
Standard_EXPORT void SetDistAngle (const Standard_Real Dis,
const Standard_Real Angle,
const Standard_Integer IC,
const TopoDS_Face& F);
//! gives the distances <Dis> and <Angle> of the fillet
//! contour of index <IC> in the DS
Standard_EXPORT void GetDistAngle (const Standard_Integer IC,
Standard_Real& Dis,
Standard_Real& Angle) const;
//! set the mode of shamfer
Standard_EXPORT void SetMode (const ChFiDS_ChamfMode theMode);
//! renvoi la methode des chanfreins utilisee
Standard_EXPORT ChFiDS_ChamfMethod IsChamfer (const Standard_Integer IC) const;
//! returns the mode of chamfer used
Standard_EXPORT ChFiDS_ChamfMode Mode () const;
//! Reset tous rayons du contour IC.
Standard_EXPORT void ResetContour (const Standard_Integer IC);
Standard_EXPORT void Simulate (const Standard_Integer IC);
Standard_EXPORT Standard_Integer NbSurf (const Standard_Integer IC) const;
Standard_EXPORT Handle(ChFiDS_SecHArray1) Sect (const Standard_Integer IC,
const Standard_Integer IS) const;
Standard_EXPORT virtual void SimulSurf (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Curve2d)& PC1,
const Handle(BRepAdaptor_Surface)& Sref1,
const Handle(BRepAdaptor_Curve2d)& PCref1,
Standard_Boolean& Decroch1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const TopAbs_Orientation Or2,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP,
const Standard_Boolean RecS,
const Standard_Boolean RecRst,
const math_Vector& Soldep) Standard_OVERRIDE;
Standard_EXPORT virtual void SimulSurf (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const TopAbs_Orientation Or1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Handle(BRepAdaptor_Curve2d)& PC2,
const Handle(BRepAdaptor_Surface)& Sref2,
const Handle(BRepAdaptor_Curve2d)& PCref2,
Standard_Boolean& Decroch2,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP,
const Standard_Boolean RecS,
const Standard_Boolean RecRst,
const math_Vector& Soldep) Standard_OVERRIDE;
Standard_EXPORT virtual void SimulSurf (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Curve2d)& PC1,
const Handle(BRepAdaptor_Surface)& Sref1,
const Handle(BRepAdaptor_Curve2d)& PCref1,
Standard_Boolean& Decroch1,
const TopAbs_Orientation Or1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Handle(BRepAdaptor_Curve2d)& PC2,
const Handle(BRepAdaptor_Surface)& Sref2,
const Handle(BRepAdaptor_Curve2d)& PCref2,
Standard_Boolean& Decroch2,
const TopAbs_Orientation Or2,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP1,
const Standard_Boolean RecRst1,
const Standard_Boolean RecP2,
const Standard_Boolean RecRst2,
const math_Vector& Soldep) Standard_OVERRIDE;
//! Methode, implemented in inheritants, calculates
//! the elements of construction of the surface (fillet
//! or chamfer).
Standard_EXPORT virtual Standard_Boolean PerformSurf (ChFiDS_SequenceOfSurfData& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecOnS1,
const Standard_Boolean RecOnS2,
const math_Vector& Soldep,
Standard_Integer& Intf,
Standard_Integer& Intl) Standard_OVERRIDE;
//! Method, implemented in the inheritants, calculates
//! the elements of construction of the surface (fillet
//! or chamfer) contact edge/face.
Standard_EXPORT virtual void PerformSurf (ChFiDS_SequenceOfSurfData& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Curve2d)& PC1,
const Handle(BRepAdaptor_Surface)& Sref1,
const Handle(BRepAdaptor_Curve2d)& PCref1,
Standard_Boolean& Decroch1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const TopAbs_Orientation Or2,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP,
const Standard_Boolean RecS,
const Standard_Boolean RecRst,
const math_Vector& Soldep) Standard_OVERRIDE;
//! Method, implemented in inheritants, calculates
//! the elements of construction of the surface (fillet
//! or chamfer) contact edge/face.
Standard_EXPORT virtual void PerformSurf (ChFiDS_SequenceOfSurfData& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const TopAbs_Orientation Or1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Handle(BRepAdaptor_Curve2d)& PC2,
const Handle(BRepAdaptor_Surface)& Sref2,
const Handle(BRepAdaptor_Curve2d)& PCref2,
Standard_Boolean& Decroch2,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP,
const Standard_Boolean RecS,
const Standard_Boolean RecRst,
const math_Vector& Soldep) Standard_OVERRIDE;
//! Method, implemented in inheritants, calculates
//! the elements of construction of the surface (fillet
//! or chamfer) contact edge/edge.
Standard_EXPORT virtual void PerformSurf (ChFiDS_SequenceOfSurfData& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Curve2d)& PC1,
const Handle(BRepAdaptor_Surface)& Sref1,
const Handle(BRepAdaptor_Curve2d)& PCref1,
Standard_Boolean& Decroch1,
const TopAbs_Orientation Or1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Handle(BRepAdaptor_Curve2d)& PC2,
const Handle(BRepAdaptor_Surface)& Sref2,
const Handle(BRepAdaptor_Curve2d)& PCref2,
Standard_Boolean& Decroch2,
const TopAbs_Orientation Or2,
const Standard_Real MaxStep,
const Standard_Real Fleche,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecP1,
const Standard_Boolean RecRst1,
const Standard_Boolean RecP2,
const Standard_Boolean RecRst2,
const math_Vector& Soldep) Standard_OVERRIDE;
protected:
Standard_EXPORT void SimulKPart (const Handle(ChFiDS_SurfData)& SD) const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean SimulSurf (Handle(ChFiDS_SurfData)& Data,
const Handle(ChFiDS_ElSpine)& Guide,
const Handle(ChFiDS_Spine)& Spine,
const Standard_Integer Choix,
const Handle(BRepAdaptor_Surface)& S1,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I2,
const Standard_Real TolGuide,
Standard_Real& First,
Standard_Real& Last,
const Standard_Boolean Inside,
const Standard_Boolean Appro,
const Standard_Boolean Forward,
const Standard_Boolean RecOnS1,
const Standard_Boolean RecOnS2,
const math_Vector& Soldep,
Standard_Integer& Intf,
Standard_Integer& Intl) Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean PerformFirstSection (const Handle(ChFiDS_Spine)& S,
const Handle(ChFiDS_ElSpine)& HGuide,
const Standard_Integer Choix,
Handle(BRepAdaptor_Surface)& S1,
Handle(BRepAdaptor_Surface)& S2,
const Handle(Adaptor3d_TopolTool)& I1,
const Handle(Adaptor3d_TopolTool)& I2,
const Standard_Real Par,
math_Vector& SolDep,
TopAbs_State& Pos1,
TopAbs_State& Pos2) const Standard_OVERRIDE;
//! computes the intersection of two chamfers on
//! the vertex of index <Index> in myVDataMap.
Standard_EXPORT void PerformTwoCorner (const Standard_Integer Index) Standard_OVERRIDE;
//! computes the intersection of three chamfers on
//! the vertex of index <Index> in myVDataMap.
Standard_EXPORT void PerformThreeCorner (const Standard_Integer Index) Standard_OVERRIDE;
//! extends the spine of the Stripe <S> at the
//! extremity of the vertex <V>.
Standard_EXPORT void ExtentOneCorner (const TopoDS_Vertex& V,
const Handle(ChFiDS_Stripe)& S) Standard_OVERRIDE;
//! extends the spine of the 2 stripes of <LS> at the
//! extremity of the vertex <V>
Standard_EXPORT void ExtentTwoCorner (const TopoDS_Vertex& V,
const ChFiDS_ListOfStripe& LS) Standard_OVERRIDE;
//! extends the spine of the 2 stripes of <LS> at the
//! extremity of the vertex <V>
Standard_EXPORT void ExtentThreeCorner (const TopoDS_Vertex& V,
const ChFiDS_ListOfStripe& LS) Standard_OVERRIDE;
//! set the regularities
Standard_EXPORT void SetRegul() Standard_OVERRIDE;
private:
Standard_EXPORT void ConexFaces (const Handle(ChFiDS_Spine)& Sp,
const Standard_Integer IEdge,
TopoDS_Face& F1,
TopoDS_Face& F2) const;
ChFiDS_ChamfMode myMode;
};
#endif // _ChFi3d_ChBuilder_HeaderFile
|
#pragma once
#include "render_component.h"
#include "..\\external\SDL2-2.0.10\include\SDL.h"
class Texture;
class SpriteAnimationComponent : public RenderComponent {
public:
SpriteAnimationComponent() {}
bool Create(const Name& name, Entity* owner, const Name& texture_name, const vector2& origin = vector2::zero);
void Destroy() override;
bool Load(const rapidjson::Value& value) override;
SpriteAnimationComponent* Clone() override { return new SpriteAnimationComponent(*this); }
void Initialize() override;
void Update() override;
void Draw() override;
void Reset();
private:
Texture* texture_ = nullptr;
Name texture_name_;
vector2 origin_;
SDL_Rect rect_;
int frame_count_ = 1;
int frames_per_col_ = 1;
int frames_per_row_ = 1;
int current_frame_ = 0;
float frame_timer_ = 0.0f;
float frame_rate_ = 1.0f / 30.0f; // 1 second divided by 30 frames - 30fps
bool completed_animation_ = false;
};
|
// Hero's Inventory 3.0
// Demonstrates iterators
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void weapons()
{
vector<string>::iterator myIterator;
vector<string>::const_iterator iter;
vector<string> weapons;
weapons.push_back("longsword");
weapons.push_back("shortsword");
weapons.push_back("dagger");
weapons.push_back("dagger");
weapons.push_back("light crossbow");
cout << "Your Weapons:\n\n";
for (iter = weapons.begin(); iter != weapons.end(); ++iter)
{
cout << *iter << endl;
}
}
void armor()
{
vector<string>::iterator myIterator;
vector<string>::const_iterator iter;
vector<string> armor;
armor.push_back("chainmail");
armor.push_back("wooden shield");
armor.push_back("helmet");
armor.push_back("bracers");
cout << "\n\nYour Armor:\n\n";
for (iter = armor.begin(); iter != armor.end(); ++iter)
{
cout << *iter << endl;
}
}
void items()
{
vector<string>::iterator myIterator;
vector<string>::const_iterator iter;
vector<string> items;
items.push_back("potion");
items.push_back("potion");
items.push_back("caltrops");
items.push_back("torch");
items.push_back("rope");
items.push_back("winter fur");
items.push_back("sharpening stone");
cout << "\n\nYour Items:\n\n";
for (iter = items.begin(); iter != items.end(); ++iter)
{
cout << *iter << endl;
}
}
void itemList()
{
cout << "What would you like to see?" << endl;
cout << "1. Weapons\n";
cout << "2. Armor\n";
cout << "3. Items\n";
cout << "4. All\n";
char menu;
cin >> menu;
switch(menu)
{
case 1:
weapons();
break;
case 2:
armor();
break;
case 3:
items();
break;
default:
cout << "Please select 1-3." << endl;
}
}
int main()
{
cout << "Welcome to Hero Inventory 1.0!\n";
cout << "Created by David Zammit\n\n";
cout << "This application is designed to help you keep track of your characters inventory by allowing you to navigate using type. You will be able to add items and remove items as well as manage your money.\n" << endl;
cout << "Would you like to begin?" << endl;
char ans;
cin >> ans;
switch(ans)
{
case 'y':
cout << "Loading...\n\n" << endl;
itemList();
break;
case 'n':
cout << "Thank You!" << endl;
return 0;
break;
default:
cout << "Please select 'y' or 'n' to continue." << endl;
}
return 0;
}
|
/*
@project: @@PROJECT@@
@repo: https://github.com/Alexandra-Miller/@@PROJECT@@
@creator: Alexandra Marie Miller
@description
@description
@dependencies: bash
*/
/* =================== CONSTANTS ========================================== */
/* =================== FUNCTIONS ========================================== */
|
/********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.8.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QListWidget>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_mainWindow
{
public:
QAction *actionNote;
QAction *actionTache;
QAction *actionImage;
QAction *actionAudio;
QAction *actionVideo;
QAction *nouvelleRelationAction;
QAction *actionafficher;
QAction *actioncorbeille;
QAction *actionde_merde;
QAction *actionclose;
QWidget *centralwidget;
QWidget *verticalLayoutWidget_3;
QVBoxLayout *centralLayout;
QVBoxLayout *titre;
QLabel *label;
QVBoxLayout *partiePrincipale;
QSpacerItem *verticalSpacer;
QLabel *label_2;
QPushButton *pushButtonArticle;
QPushButton *pushButtonTask;
QPushButton *pushButtonImage;
QPushButton *pushButtonVideo;
QPushButton *pushButtonAudio;
QSpacerItem *verticalSpacer_2;
QWidget *verticalLayoutWidget;
QVBoxLayout *listRelationLayout;
QLabel *relationLabel;
QListWidget *listRelation;
QWidget *verticalLayoutWidget_2;
QVBoxLayout *partieGauche;
QLabel *notesLabel;
QListWidget *listWidgetNotesActives;
QLabel *taskLabel;
QListWidget *listWidgetTasksActives;
QLabel *archivesLabel;
QListWidget *listWidgetArchive;
QMenuBar *menubar;
QMenu *menuNote;
QMenu *menunouvelle_note;
QMenu *menuRelations;
QMenu *menuCorbeille;
QMenu *menuparam_tres;
QMenu *menuApp;
QStatusBar *statusbar;
void setupUi(QMainWindow *mainWindow)
{
if (mainWindow->objectName().isEmpty())
mainWindow->setObjectName(QStringLiteral("mainWindow"));
mainWindow->resize(800, 600);
actionNote = new QAction(mainWindow);
actionNote->setObjectName(QStringLiteral("actionNote"));
actionTache = new QAction(mainWindow);
actionTache->setObjectName(QStringLiteral("actionTache"));
actionImage = new QAction(mainWindow);
actionImage->setObjectName(QStringLiteral("actionImage"));
actionAudio = new QAction(mainWindow);
actionAudio->setObjectName(QStringLiteral("actionAudio"));
actionVideo = new QAction(mainWindow);
actionVideo->setObjectName(QStringLiteral("actionVideo"));
nouvelleRelationAction = new QAction(mainWindow);
nouvelleRelationAction->setObjectName(QStringLiteral("nouvelleRelationAction"));
actionafficher = new QAction(mainWindow);
actionafficher->setObjectName(QStringLiteral("actionafficher"));
actioncorbeille = new QAction(mainWindow);
actioncorbeille->setObjectName(QStringLiteral("actioncorbeille"));
actionde_merde = new QAction(mainWindow);
actionde_merde->setObjectName(QStringLiteral("actionde_merde"));
actionclose = new QAction(mainWindow);
actionclose->setObjectName(QStringLiteral("actionclose"));
centralwidget = new QWidget(mainWindow);
centralwidget->setObjectName(QStringLiteral("centralwidget"));
verticalLayoutWidget_3 = new QWidget(centralwidget);
verticalLayoutWidget_3->setObjectName(QStringLiteral("verticalLayoutWidget_3"));
verticalLayoutWidget_3->setGeometry(QRect(260, 0, 331, 561));
centralLayout = new QVBoxLayout(verticalLayoutWidget_3);
centralLayout->setObjectName(QStringLiteral("centralLayout"));
centralLayout->setSizeConstraint(QLayout::SetDefaultConstraint);
centralLayout->setContentsMargins(0, 0, 0, 0);
titre = new QVBoxLayout();
titre->setObjectName(QStringLiteral("titre"));
titre->setSizeConstraint(QLayout::SetFixedSize);
label = new QLabel(verticalLayoutWidget_3);
label->setObjectName(QStringLiteral("label"));
QFont font;
font.setFamily(QStringLiteral("Webdings"));
font.setPointSize(36);
label->setFont(font);
label->setAlignment(Qt::AlignCenter);
titre->addWidget(label);
centralLayout->addLayout(titre);
partiePrincipale = new QVBoxLayout();
partiePrincipale->setObjectName(QStringLiteral("partiePrincipale"));
partiePrincipale->setSizeConstraint(QLayout::SetMinimumSize);
partiePrincipale->setContentsMargins(-1, 0, -1, -1);
verticalSpacer = new QSpacerItem(20, 60, QSizePolicy::Minimum, QSizePolicy::Fixed);
partiePrincipale->addItem(verticalSpacer);
label_2 = new QLabel(verticalLayoutWidget_3);
label_2->setObjectName(QStringLiteral("label_2"));
QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Maximum);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(label_2->sizePolicy().hasHeightForWidth());
label_2->setSizePolicy(sizePolicy);
QFont font1;
font1.setPointSize(18);
label_2->setFont(font1);
label_2->setAlignment(Qt::AlignCenter);
partiePrincipale->addWidget(label_2);
pushButtonArticle = new QPushButton(verticalLayoutWidget_3);
pushButtonArticle->setObjectName(QStringLiteral("pushButtonArticle"));
partiePrincipale->addWidget(pushButtonArticle);
pushButtonTask = new QPushButton(verticalLayoutWidget_3);
pushButtonTask->setObjectName(QStringLiteral("pushButtonTask"));
partiePrincipale->addWidget(pushButtonTask);
pushButtonImage = new QPushButton(verticalLayoutWidget_3);
pushButtonImage->setObjectName(QStringLiteral("pushButtonImage"));
partiePrincipale->addWidget(pushButtonImage);
pushButtonVideo = new QPushButton(verticalLayoutWidget_3);
pushButtonVideo->setObjectName(QStringLiteral("pushButtonVideo"));
partiePrincipale->addWidget(pushButtonVideo);
pushButtonAudio = new QPushButton(verticalLayoutWidget_3);
pushButtonAudio->setObjectName(QStringLiteral("pushButtonAudio"));
partiePrincipale->addWidget(pushButtonAudio);
verticalSpacer_2 = new QSpacerItem(20, 150, QSizePolicy::Minimum, QSizePolicy::Fixed);
partiePrincipale->addItem(verticalSpacer_2);
centralLayout->addLayout(partiePrincipale);
verticalLayoutWidget = new QWidget(centralwidget);
verticalLayoutWidget->setObjectName(QStringLiteral("verticalLayoutWidget"));
verticalLayoutWidget->setGeometry(QRect(590, 289, 211, 271));
listRelationLayout = new QVBoxLayout(verticalLayoutWidget);
listRelationLayout->setObjectName(QStringLiteral("listRelationLayout"));
listRelationLayout->setContentsMargins(0, 0, 0, 0);
relationLabel = new QLabel(verticalLayoutWidget);
relationLabel->setObjectName(QStringLiteral("relationLabel"));
listRelationLayout->addWidget(relationLabel);
listRelation = new QListWidget(verticalLayoutWidget);
listRelation->setObjectName(QStringLiteral("listRelation"));
listRelationLayout->addWidget(listRelation);
verticalLayoutWidget_2 = new QWidget(centralwidget);
verticalLayoutWidget_2->setObjectName(QStringLiteral("verticalLayoutWidget_2"));
verticalLayoutWidget_2->setGeometry(QRect(-1, 0, 261, 561));
partieGauche = new QVBoxLayout(verticalLayoutWidget_2);
partieGauche->setObjectName(QStringLiteral("partieGauche"));
partieGauche->setContentsMargins(0, 0, 0, 0);
notesLabel = new QLabel(verticalLayoutWidget_2);
notesLabel->setObjectName(QStringLiteral("notesLabel"));
partieGauche->addWidget(notesLabel);
listWidgetNotesActives = new QListWidget(verticalLayoutWidget_2);
listWidgetNotesActives->setObjectName(QStringLiteral("listWidgetNotesActives"));
partieGauche->addWidget(listWidgetNotesActives);
taskLabel = new QLabel(verticalLayoutWidget_2);
taskLabel->setObjectName(QStringLiteral("taskLabel"));
partieGauche->addWidget(taskLabel);
listWidgetTasksActives = new QListWidget(verticalLayoutWidget_2);
listWidgetTasksActives->setObjectName(QStringLiteral("listWidgetTasksActives"));
partieGauche->addWidget(listWidgetTasksActives);
archivesLabel = new QLabel(verticalLayoutWidget_2);
archivesLabel->setObjectName(QStringLiteral("archivesLabel"));
partieGauche->addWidget(archivesLabel);
listWidgetArchive = new QListWidget(verticalLayoutWidget_2);
listWidgetArchive->setObjectName(QStringLiteral("listWidgetArchive"));
partieGauche->addWidget(listWidgetArchive);
mainWindow->setCentralWidget(centralwidget);
menubar = new QMenuBar(mainWindow);
menubar->setObjectName(QStringLiteral("menubar"));
menubar->setGeometry(QRect(0, 0, 800, 22));
menuNote = new QMenu(menubar);
menuNote->setObjectName(QStringLiteral("menuNote"));
menunouvelle_note = new QMenu(menuNote);
menunouvelle_note->setObjectName(QStringLiteral("menunouvelle_note"));
menuRelations = new QMenu(menubar);
menuRelations->setObjectName(QStringLiteral("menuRelations"));
menuCorbeille = new QMenu(menubar);
menuCorbeille->setObjectName(QStringLiteral("menuCorbeille"));
menuparam_tres = new QMenu(menubar);
menuparam_tres->setObjectName(QStringLiteral("menuparam_tres"));
menuApp = new QMenu(menubar);
menuApp->setObjectName(QStringLiteral("menuApp"));
mainWindow->setMenuBar(menubar);
statusbar = new QStatusBar(mainWindow);
statusbar->setObjectName(QStringLiteral("statusbar"));
mainWindow->setStatusBar(statusbar);
menubar->addAction(menuNote->menuAction());
menubar->addAction(menuRelations->menuAction());
menubar->addAction(menuCorbeille->menuAction());
menubar->addAction(menuparam_tres->menuAction());
menubar->addAction(menuApp->menuAction());
menuNote->addAction(menunouvelle_note->menuAction());
menunouvelle_note->addAction(actionNote);
menunouvelle_note->addAction(actionTache);
menunouvelle_note->addAction(actionImage);
menunouvelle_note->addAction(actionAudio);
menunouvelle_note->addAction(actionVideo);
menuRelations->addAction(nouvelleRelationAction);
menuCorbeille->addAction(actionafficher);
menuparam_tres->addAction(actioncorbeille);
menuApp->addAction(actionclose);
retranslateUi(mainWindow);
QMetaObject::connectSlotsByName(mainWindow);
} // setupUi
void retranslateUi(QMainWindow *mainWindow)
{
mainWindow->setWindowTitle(QApplication::translate("mainWindow", "MainWindow", Q_NULLPTR));
actionNote->setText(QApplication::translate("mainWindow", "Article", Q_NULLPTR));
actionTache->setText(QApplication::translate("mainWindow", "Tache", Q_NULLPTR));
actionImage->setText(QApplication::translate("mainWindow", "Image", Q_NULLPTR));
actionAudio->setText(QApplication::translate("mainWindow", "Audio", Q_NULLPTR));
actionVideo->setText(QApplication::translate("mainWindow", "Video", Q_NULLPTR));
nouvelleRelationAction->setText(QApplication::translate("mainWindow", "nouvelle relation", Q_NULLPTR));
actionafficher->setText(QApplication::translate("mainWindow", "afficher", Q_NULLPTR));
actioncorbeille->setText(QApplication::translate("mainWindow", "corbeille", Q_NULLPTR));
actionde_merde->setText(QApplication::translate("mainWindow", "de merde", Q_NULLPTR));
actionclose->setText(QApplication::translate("mainWindow", "close", Q_NULLPTR));
label->setText(QApplication::translate("mainWindow", "PluriNotes", Q_NULLPTR));
label_2->setText(QApplication::translate("mainWindow", "Cr\303\251er une nouvelle note :", Q_NULLPTR));
pushButtonArticle->setText(QApplication::translate("mainWindow", "Article", Q_NULLPTR));
pushButtonTask->setText(QApplication::translate("mainWindow", "T\303\242che", Q_NULLPTR));
pushButtonImage->setText(QApplication::translate("mainWindow", "Image", Q_NULLPTR));
pushButtonVideo->setText(QApplication::translate("mainWindow", "Vid\303\251o", Q_NULLPTR));
pushButtonAudio->setText(QApplication::translate("mainWindow", "Audio", Q_NULLPTR));
relationLabel->setText(QApplication::translate("mainWindow", "Relations :", Q_NULLPTR));
notesLabel->setText(QApplication::translate("mainWindow", "Notes :", Q_NULLPTR));
taskLabel->setText(QApplication::translate("mainWindow", "T\303\242ches : ", Q_NULLPTR));
archivesLabel->setText(QApplication::translate("mainWindow", "Notes archiv\303\251es :", Q_NULLPTR));
menuNote->setTitle(QApplication::translate("mainWindow", "Notes", Q_NULLPTR));
menunouvelle_note->setTitle(QApplication::translate("mainWindow", "nouvelle note", Q_NULLPTR));
menuRelations->setTitle(QApplication::translate("mainWindow", "Relations", Q_NULLPTR));
menuCorbeille->setTitle(QApplication::translate("mainWindow", "Corbeille", Q_NULLPTR));
menuparam_tres->setTitle(QApplication::translate("mainWindow", "param\303\250tres", Q_NULLPTR));
menuApp->setTitle(QApplication::translate("mainWindow", "App", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class mainWindow: public Ui_mainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
|
#include "TrustchainBuilder.hpp"
#include <Tanker/Entry.hpp>
#include <Tanker/Errors/AssertionError.hpp>
#include <Tanker/Groups/GroupEncryptedKey.hpp>
#include <Tanker/Groups/Manager.hpp>
#include <Tanker/Identity/Delegation.hpp>
#include <Tanker/Serialization/Serialization.hpp>
#include <Tanker/Share.hpp>
#include <Tanker/Trustchain/Actions/DeviceRevocation.hpp>
#include <Tanker/Trustchain/GroupId.hpp>
#include <Tanker/Trustchain/TrustchainId.hpp>
#include <Tanker/Types/SUserId.hpp>
#include <Helpers/Await.hpp>
#include <algorithm>
#include <cstring>
using namespace Tanker::Trustchain::Actions;
using namespace Tanker::Trustchain;
using namespace Tanker;
TrustchainBuilder::TrustchainBuilder()
: _trustchainKeyPair(Tanker::Crypto::makeSignatureKeyPair())
{
Block block{};
block.nature = Nature::TrustchainCreation;
block.payload = Serialization::serialize(
TrustchainCreation{_trustchainKeyPair.publicKey});
block.trustchainId = TrustchainId(block.hash());
_trustchainId = block.trustchainId;
block.index = _entries.size() + 1;
_entries.push_back(blockToServerEntry(block));
}
namespace
{
TrustchainBuilder::Device createDevice()
{
return TrustchainBuilder::Device{
{
Tanker::Crypto::makeSignatureKeyPair(),
Tanker::Crypto::makeEncryptionKeyPair(),
},
{}, // deviceId will be filled in later
{}, // delegation will be filled in later
{} // blockIndex will be filled in later
};
}
}
Tanker::Device TrustchainBuilder::Device::asTankerDevice() const
{
return Tanker::Device{id,
blockIndex,
std::nullopt,
keys.signatureKeyPair.publicKey,
keys.encryptionKeyPair.publicKey,
false};
}
Tanker::User TrustchainBuilder::User::asTankerUser() const
{
Tanker::User tankerUser{
userId,
userKeys.empty() ?
std::optional<Tanker::Crypto::PublicEncryptionKey>() :
userKeys.back().keyPair.publicKey,
std::vector<Tanker::Device>(devices.size())};
std::transform(devices.begin(),
devices.end(),
tankerUser.devices.begin(),
[](auto const& device) { return device.asTankerDevice(); });
return tankerUser;
}
Tanker::ExternalGroup TrustchainBuilder::InternalGroup::asExternalGroup() const
{
Tanker::ExternalGroup extGroup{
tankerGroup.id,
tankerGroup.signatureKeyPair.publicKey,
encryptedPrivateSignatureKey,
tankerGroup.encryptionKeyPair.publicKey,
tankerGroup.lastBlockHash,
tankerGroup.lastBlockIndex,
};
return extGroup;
}
TrustchainId const& TrustchainBuilder::trustchainId() const
{
return _trustchainId;
}
Crypto::PrivateSignatureKey const& TrustchainBuilder::trustchainPrivateKey()
const
{
return _trustchainKeyPair.privateKey;
}
auto TrustchainBuilder::makeUser(std::string const& suserId) -> ResultUser
{
return makeUser3(suserId);
}
auto TrustchainBuilder::makeUser1(std::string const& suserId) -> ResultUser
{
if (findUser(suserId))
throw Errors::AssertionError(fmt::format("{} already exists", suserId));
auto device = createDevice();
auto const daUserId = SUserId{suserId};
User user{
daUserId,
obfuscateUserId(daUserId, _trustchainId),
{device},
{},
_entries.size() + 1,
};
auto const delegation =
Identity::makeDelegation(user.userId, _trustchainKeyPair.privateKey);
auto const preserializedBlock =
BlockGenerator(_trustchainId, trustchainPrivateKey(), {})
.addUser1(delegation,
device.keys.signatureKeyPair.publicKey,
device.keys.encryptionKeyPair.publicKey);
auto block = Serialization::deserialize<Block>(preserializedBlock);
block.index = _entries.size() + 1;
user.devices[0].delegation = delegation;
user.devices[0].id = DeviceId(block.hash());
user.devices[0].blockIndex = block.index;
_users.push_back(user);
auto const entry = blockToServerEntry(block);
_entries.push_back(entry);
return {user, entry};
}
auto TrustchainBuilder::makeUser3(std::string const& suserId) -> ResultUser
{
if (findUser(suserId))
throw Errors::AssertionError(fmt::format("{} already exists", suserId));
auto device = createDevice();
auto const daUserId = SUserId{suserId};
User user{
daUserId,
Tanker::obfuscateUserId(daUserId, _trustchainId),
{device},
{{Tanker::Crypto::makeEncryptionKeyPair(), _entries.size() + 1}},
_entries.size() + 1,
};
auto const delegation =
Identity::makeDelegation(user.userId, _trustchainKeyPair.privateKey);
auto const preserializedBlock =
BlockGenerator(_trustchainId, trustchainPrivateKey(), {})
.addUser3(delegation,
device.keys.signatureKeyPair.publicKey,
device.keys.encryptionKeyPair.publicKey,
user.userKeys.back().keyPair);
auto block = Serialization::deserialize<Block>(preserializedBlock);
block.index = _entries.size() + 1;
user.devices[0].id = DeviceId(block.hash());
user.devices[0].delegation = delegation;
user.devices[0].blockIndex = block.index;
_users.push_back(user);
auto const entry = blockToServerEntry(block);
_entries.push_back(entry);
return {user, entry};
}
auto TrustchainBuilder::makeDevice(std::string const& suserId,
int validatorDeviceIndex) -> ResultDevice
{
return makeDevice3(suserId, validatorDeviceIndex);
}
auto TrustchainBuilder::makeDevice1(std::string const& p,
int validatorDeviceIndex) -> ResultDevice
{
auto const suserId = SUserId{p};
auto user = findMutableUser(suserId);
auto device = createDevice();
// the device that will validate this device
auto const& validatorDevice = user->devices.at(validatorDeviceIndex);
auto const delegation = Identity::makeDelegation(
user->userId, validatorDevice.keys.signatureKeyPair.privateKey);
auto const preserializedBlock =
BlockGenerator(_trustchainId,
validatorDevice.keys.signatureKeyPair.privateKey,
validatorDevice.id)
.addDevice1(delegation,
device.keys.signatureKeyPair.publicKey,
device.keys.encryptionKeyPair.publicKey);
auto block = Serialization::deserialize<Block>(preserializedBlock);
block.index = _entries.size() + 1;
device.id = DeviceId(block.hash());
device.delegation = delegation;
device.blockIndex = block.index;
user->devices.push_back(device);
auto const tankerUser = user->asTankerUser();
auto const entry = blockToServerEntry(block);
_entries.push_back(entry);
return {device, tankerUser, entry};
}
auto TrustchainBuilder::makeDevice3(std::string const& p,
int validatorDeviceIndex) -> ResultDevice
{
auto const suserId = SUserId{p};
auto user = findMutableUser(suserId);
if (user->userKeys.empty()) // upgrading the user
{
user->userKeys.push_back(
{Tanker::Crypto::makeEncryptionKeyPair(), _entries.size() + 1});
}
auto device = createDevice();
// the device that will validate this device
auto const& validatorDevice = user->devices.at(validatorDeviceIndex);
auto const delegation = Identity::makeDelegation(
user->userId, validatorDevice.keys.signatureKeyPair.privateKey);
auto const preserializedBlock =
BlockGenerator(_trustchainId,
validatorDevice.keys.signatureKeyPair.privateKey,
validatorDevice.id)
.addDevice3(delegation,
device.keys.signatureKeyPair.publicKey,
device.keys.encryptionKeyPair.publicKey,
user->userKeys.back().keyPair);
auto block = Serialization::deserialize<Block>(preserializedBlock);
block.index = _entries.size() + 1;
device.id = DeviceId(block.hash());
device.delegation = delegation;
device.blockIndex = block.index;
user->devices.push_back(device);
auto const tankerUser = user->asTankerUser();
auto const entry = blockToServerEntry(block);
_entries.push_back(entry);
return {device, tankerUser, entry};
}
TrustchainBuilder::ProvisionalUser TrustchainBuilder::makeProvisionalUser(
std::string const& email)
{
auto const secretProvisionalUser = SecretProvisionalUser{
Tanker::Identity::TargetType::Email,
email,
Crypto::makeEncryptionKeyPair(),
Crypto::makeEncryptionKeyPair(),
Crypto::makeSignatureKeyPair(),
Crypto::makeSignatureKeyPair(),
};
auto const publicProvisionalUser = PublicProvisionalUser{
secretProvisionalUser.appSignatureKeyPair.publicKey,
secretProvisionalUser.appEncryptionKeyPair.publicKey,
secretProvisionalUser.tankerSignatureKeyPair.publicKey,
secretProvisionalUser.tankerEncryptionKeyPair.publicKey,
};
auto const publicProvisionalIdentity = Identity::PublicProvisionalIdentity{
_trustchainId,
secretProvisionalUser.target,
secretProvisionalUser.value,
secretProvisionalUser.appSignatureKeyPair.publicKey,
secretProvisionalUser.appEncryptionKeyPair.publicKey,
};
return ProvisionalUser{
secretProvisionalUser,
publicProvisionalUser,
SPublicIdentity(to_string(publicProvisionalIdentity)),
};
}
ServerEntry TrustchainBuilder::claimProvisionalIdentity(
std::string const& suserId,
Tanker::SecretProvisionalUser const& provisionalUser,
int authorDeviceIndex)
{
auto const user = findUser(suserId).value();
auto const& authorDevice = user.devices.at(authorDeviceIndex);
auto const preserializedBlock =
BlockGenerator(_trustchainId,
authorDevice.keys.signatureKeyPair.privateKey,
authorDevice.id)
.provisionalIdentityClaim(
user.userId, provisionalUser, user.userKeys.back().keyPair);
auto block = Serialization::deserialize<Block>(preserializedBlock);
block.index = _entries.size() + 1;
auto const entry = blockToServerEntry(block);
_entries.push_back(entry);
return entry;
}
TrustchainBuilder::ResultGroup TrustchainBuilder::makeGroup(
Device const& author,
std::vector<User> const& users,
std::vector<Tanker::PublicProvisionalUser> const& provisionalUsers)
{
return makeGroup2(author, users, provisionalUsers);
}
namespace
{
UserGroupCreation::v1::SealedPrivateEncryptionKeysForUsers
generateGroupKeysForUsers(
Crypto::PrivateEncryptionKey const& groupPrivateEncryptionKey,
std::vector<TrustchainBuilder::User> const& users)
{
UserGroupCreation::v1::SealedPrivateEncryptionKeysForUsers keysForUsers;
for (auto const& user : users)
{
if (user.userKeys.empty())
throw std::runtime_error(
"TrustchainBuilder: can't add a user without user key to a group");
keysForUsers.emplace_back(
user.userKeys.back().keyPair.publicKey,
Crypto::sealEncrypt(groupPrivateEncryptionKey,
user.userKeys.back().keyPair.publicKey));
}
return keysForUsers;
}
std::vector<TrustchainBuilder::User> getOnlyNewMembers(
std::vector<SUserId> oldMembers, std::vector<TrustchainBuilder::User> toAdd)
{
std::vector<TrustchainBuilder::User> newUsers;
newUsers.reserve(toAdd.size());
std::remove_copy_if(toAdd.begin(),
toAdd.end(),
std::back_inserter(newUsers),
[&](auto const& user) {
return std::find(oldMembers.begin(),
oldMembers.end(),
user.suserId) != oldMembers.end();
});
auto const comparator = [](auto const& a, auto const& b) {
return a.suserId < b.suserId;
};
std::sort(newUsers.begin(), newUsers.end(), comparator);
newUsers.erase(std::unique(newUsers.begin(), newUsers.end(), comparator),
newUsers.end());
return newUsers;
}
}
TrustchainBuilder::ResultGroup TrustchainBuilder::makeGroup1(
Device const& author, std::vector<User> const& users)
{
auto const signatureKeyPair = Crypto::makeSignatureKeyPair();
auto const encryptionKeyPair = Crypto::makeEncryptionKeyPair();
auto const keysForUsers =
generateGroupKeysForUsers(encryptionKeyPair.privateKey, users);
auto const preserializedBlock =
BlockGenerator(
_trustchainId, author.keys.signatureKeyPair.privateKey, author.id)
.userGroupCreation(
signatureKeyPair, encryptionKeyPair.publicKey, keysForUsers);
auto block = Serialization::deserialize<Block>(preserializedBlock);
block.index = _entries.size() + 1;
auto const entry = blockToServerEntry(block);
_entries.push_back(entry);
Tanker::InternalGroup tgroup{
GroupId{signatureKeyPair.publicKey},
signatureKeyPair,
encryptionKeyPair,
entry.hash(),
block.index,
};
std::vector<SUserId> members;
for (auto const& user : users)
members.push_back(user.suserId);
auto const encryptedPrivateSignatureKey = entry.action()
.get<UserGroupCreation>()
.get<UserGroupCreation::v1>()
.sealedPrivateSignatureKey();
InternalGroup group{tgroup, encryptedPrivateSignatureKey, members, {}};
_groups.insert(group);
return {group, entry};
}
TrustchainBuilder::ResultGroup TrustchainBuilder::makeGroup2(
Device const& author,
std::vector<User> const& users,
std::vector<Tanker::PublicProvisionalUser> const& provisionalUsers)
{
auto const signatureKeyPair = Crypto::makeSignatureKeyPair();
auto const encryptionKeyPair = Crypto::makeEncryptionKeyPair();
auto const blockGenerator = BlockGenerator(
_trustchainId, author.keys.signatureKeyPair.privateKey, author.id);
std::vector<Tanker::User> tusers;
for (auto const& user : users)
tusers.push_back(user.asTankerUser());
auto const preserializedBlock =
Groups::Manager::generateCreateGroupBlock(tusers,
provisionalUsers,
blockGenerator,
signatureKeyPair,
encryptionKeyPair);
auto block = Serialization::deserialize<Block>(preserializedBlock);
block.index = _entries.size() + 1;
auto const entry = blockToServerEntry(block);
_entries.push_back(entry);
Tanker::InternalGroup tgroup{
GroupId{signatureKeyPair.publicKey},
signatureKeyPair,
encryptionKeyPair,
entry.hash(),
block.index,
};
std::vector<SUserId> members;
for (auto const& user : users)
members.push_back(user.suserId);
auto const encryptedPrivateSignatureKey = entry.action()
.get<UserGroupCreation>()
.get<UserGroupCreation::v2>()
.sealedPrivateSignatureKey();
auto const provisionalMembers = entry.action()
.get<UserGroupCreation>()
.get<UserGroupCreation::v2>()
.provisionalMembers();
InternalGroup group{
tgroup, encryptedPrivateSignatureKey, members, provisionalMembers};
_groups.insert(group);
return {group, entry};
}
TrustchainBuilder::ResultGroup TrustchainBuilder::addUserToGroup(
Device const& author, InternalGroup group, std::vector<User> const& users)
{
auto const newUsers = getOnlyNewMembers(group.members, users);
auto const keysForUsers = generateGroupKeysForUsers(
group.tankerGroup.encryptionKeyPair.privateKey, newUsers);
auto const preserializedBlock =
BlockGenerator(
_trustchainId, author.keys.signatureKeyPair.privateKey, author.id)
.userGroupAddition(group.tankerGroup.signatureKeyPair,
group.tankerGroup.lastBlockHash,
keysForUsers);
auto block = Serialization::deserialize<Block>(preserializedBlock);
block.index = _entries.size() + 1;
auto const entry = blockToServerEntry(block);
_entries.push_back(entry);
group.tankerGroup.lastBlockHash = entry.hash();
group.tankerGroup.lastBlockIndex = entry.index();
std::transform(newUsers.begin(),
newUsers.end(),
std::back_inserter(group.members),
[](auto const& user) { return user.suserId; });
// replace group in _groups
_groups.erase(group);
_groups.insert(group);
return {group, entry};
}
TrustchainBuilder::ResultGroup TrustchainBuilder::addUserToGroup2(
Device const& author,
InternalGroup group,
std::vector<User> const& users,
std::vector<Tanker::PublicProvisionalUser> const& provisionalUsers)
{
auto const newUsers = getOnlyNewMembers(group.members, users);
std::vector<Tanker::User> tusers;
for (auto const& user : newUsers)
tusers.push_back(user.asTankerUser());
auto const blockGenerator = BlockGenerator(
_trustchainId, author.keys.signatureKeyPair.privateKey, author.id);
auto const preserializedBlock = Groups::Manager::generateAddUserToGroupBlock(
tusers, provisionalUsers, blockGenerator, group.tankerGroup);
auto block = Serialization::deserialize<Block>(preserializedBlock);
block.index = _entries.size() + 1;
auto const entry = blockToServerEntry(block);
_entries.push_back(entry);
auto const newProvisionalMembers = entry.action()
.get<UserGroupAddition>()
.get<UserGroupAddition::v2>()
.provisionalMembers();
group.provisionalMembers.insert(group.provisionalMembers.end(),
newProvisionalMembers.begin(),
newProvisionalMembers.end());
group.tankerGroup.lastBlockHash = entry.hash();
group.tankerGroup.lastBlockIndex = entry.index();
std::transform(newUsers.begin(),
newUsers.end(),
std::back_inserter(group.members),
[](auto const& user) { return user.suserId; });
// replace group in _groups
_groups.erase(group);
_groups.insert(group);
return {group, entry};
}
std::vector<Block> TrustchainBuilder::shareToDevice(
Device const& sender,
User const& receiver,
ResourceId const& resourceId,
Crypto::SymmetricKey const& key)
{
if (!receiver.userKeys.empty())
throw std::runtime_error("can't shareToDevice if the user has a user key");
std::vector<Block> result;
for (auto const& receiverDevice : receiver.devices)
{
auto const encryptedKey =
Crypto::asymEncrypt<Crypto::EncryptedSymmetricKey>(
key,
sender.keys.encryptionKeyPair.privateKey,
receiverDevice.keys.encryptionKeyPair.publicKey);
auto const block =
BlockGenerator(
_trustchainId, sender.keys.signatureKeyPair.privateKey, sender.id)
.keyPublish(encryptedKey, resourceId, receiverDevice.id);
auto deserializedBlock = Serialization::deserialize<Block>(block);
deserializedBlock.index = _entries.size() + 1;
_entries.push_back(blockToServerEntry(deserializedBlock));
result.push_back(deserializedBlock);
}
return result;
}
Block TrustchainBuilder::shareToUser(Device const& sender,
User const& receiver,
ResourceId const& resourceId,
Crypto::SymmetricKey const& key)
{
if (receiver.userKeys.empty())
throw std::runtime_error("can't shareToUser if the user has no user key");
auto const receiverPublicKey = receiver.userKeys.back().keyPair.publicKey;
auto const block = Share::makeKeyPublishToUser(
BlockGenerator(
_trustchainId, sender.keys.signatureKeyPair.privateKey, sender.id),
receiverPublicKey,
resourceId,
key);
auto deserializedBlock = Serialization::deserialize<Block>(block);
deserializedBlock.index = _entries.size() + 1;
_entries.push_back(blockToServerEntry(deserializedBlock));
return deserializedBlock;
}
Block TrustchainBuilder::shareToUserGroup(Device const& sender,
InternalGroup const& receiver,
ResourceId const& resourceId,
Crypto::SymmetricKey const& key)
{
auto const receiverPublicKey =
receiver.tankerGroup.encryptionKeyPair.publicKey;
auto const encryptedKey = Crypto::sealEncrypt(key, receiverPublicKey);
KeyPublishToUserGroup keyPublish{receiverPublicKey, resourceId, encryptedKey};
Block block;
block.trustchainId = _trustchainId;
block.author = Crypto::Hash{sender.id};
block.nature = Nature::KeyPublishToUserGroup;
block.payload = Serialization::serialize(keyPublish);
block.signature =
Crypto::sign(block.hash(), sender.keys.signatureKeyPair.privateKey);
block.index = _entries.size() + 1;
_entries.push_back(blockToServerEntry(block));
return block;
}
Block TrustchainBuilder::shareToProvisionalUser(
Device const& sender,
PublicProvisionalUser const& receiver,
ResourceId const& resourceId,
Crypto::SymmetricKey const& key)
{
auto const encryptedKeyOnce =
Crypto::sealEncrypt(key, receiver.appEncryptionPublicKey);
auto const encryptedKeyTwice =
Crypto::sealEncrypt(encryptedKeyOnce, receiver.tankerEncryptionPublicKey);
KeyPublishToProvisionalUser keyPublish{receiver.appSignaturePublicKey,
resourceId,
receiver.tankerSignaturePublicKey,
encryptedKeyTwice};
Block block;
block.trustchainId = _trustchainId;
block.author = Crypto::Hash{sender.id};
block.nature = Nature::KeyPublishToProvisionalUser;
block.payload = Serialization::serialize(keyPublish);
block.signature =
Crypto::sign(block.hash(), sender.keys.signatureKeyPair.privateKey);
block.index = _entries.size() + 1;
_entries.push_back(blockToServerEntry(block));
return block;
}
Block TrustchainBuilder::revokeDevice1(Device const& sender,
Device const& target,
bool unsafe)
{
auto const foundUser = std::find_if(
_users.begin(), _users.end(), [sender, target](auto const user) {
return std::find_if(user.devices.begin(),
user.devices.end(),
[sender](Device const& device) {
return device.asTankerDevice() ==
sender.asTankerDevice();
}) != user.devices.end() &&
std::find_if(user.devices.begin(),
user.devices.end(),
[target](Device const& device) {
return device.asTankerDevice() ==
target.asTankerDevice();
}) != user.devices.end();
});
if (foundUser == _users.end() && !unsafe)
{
throw std::runtime_error(
"TrustchainBuilder: cannot revoke a device from another user");
}
auto const revocation = DeviceRevocation1{target.id};
Block block;
block.trustchainId = _trustchainId;
block.author = Crypto::Hash{sender.id};
block.nature = Nature::DeviceRevocation;
block.payload = Serialization::serialize(revocation);
block.signature =
Crypto::sign(block.hash(), sender.keys.signatureKeyPair.privateKey);
block.index = _entries.size() + 1;
_entries.push_back(blockToServerEntry(block));
return block;
}
Block TrustchainBuilder::revokeDevice2(Device const& sender,
Device const& target,
User const& user,
bool unsafe)
{
auto const userHasDevices =
std::find_if(user.devices.begin(),
user.devices.end(),
[sender](Device const& device) {
return device.asTankerDevice() == sender.asTankerDevice();
}) != user.devices.end() &&
std::find_if(user.devices.begin(),
user.devices.end(),
[target](Device const& device) {
return device.asTankerDevice() == target.asTankerDevice();
}) != user.devices.end();
if (!userHasDevices && !unsafe)
{
throw std::runtime_error(
"TrustchainBuilder: cannot revoke a device from another user");
}
auto const newEncryptionKey = Crypto::makeEncryptionKeyPair();
auto const tankerUser = user.asTankerUser();
auto oldPublicEncryptionKey = Crypto::PublicEncryptionKey{};
auto encryptedKeyForPreviousUserKey = Crypto::SealedPrivateEncryptionKey{};
if (tankerUser.userKey)
{
oldPublicEncryptionKey = *tankerUser.userKey;
encryptedKeyForPreviousUserKey = Crypto::sealEncrypt(
user.userKeys.back().keyPair.privateKey, newEncryptionKey.publicKey);
}
DeviceRevocation::v2::SealedKeysForDevices userKeys;
for (auto const& device : user.devices)
{
if (device.id != target.id)
{
Crypto::SealedPrivateEncryptionKey sealedEncryptedKey{
Crypto::sealEncrypt(newEncryptionKey.privateKey,
device.keys.encryptionKeyPair.publicKey)};
userKeys.emplace_back(device.id, sealedEncryptedKey);
}
}
DeviceRevocation2 const revocation{target.id,
newEncryptionKey.publicKey,
encryptedKeyForPreviousUserKey,
oldPublicEncryptionKey,
userKeys};
Block block;
block.trustchainId = _trustchainId;
block.author = Crypto::Hash{sender.id};
block.nature = Nature::DeviceRevocation2;
block.payload = Serialization::serialize(revocation);
block.signature =
Crypto::sign(block.hash(), sender.keys.signatureKeyPair.privateKey);
block.index = _entries.size() + 1;
_entries.push_back(blockToServerEntry(block));
return block;
}
std::optional<TrustchainBuilder::User> TrustchainBuilder::findUser(
std::string const& suserId) const
{
auto user =
const_cast<TrustchainBuilder*>(this)->findMutableUser(SUserId{suserId});
if (user)
return *user;
return std::nullopt;
}
TrustchainBuilder::User* TrustchainBuilder::findMutableUser(
SUserId const& suserId)
{
auto const it =
std::find_if(_users.begin(), _users.end(), [&](auto const& user) {
return user.suserId == suserId;
});
if (it == _users.end())
return nullptr;
return std::addressof(*it);
}
BlockGenerator TrustchainBuilder::makeBlockGenerator(
TrustchainBuilder::Device const& device) const
{
return BlockGenerator(
_trustchainId, device.keys.signatureKeyPair.privateKey, device.id);
}
std::unique_ptr<Tanker::UserKeyStore> TrustchainBuilder::makeUserKeyStore(
User const& user, Tanker::DataStore::ADatabase* conn) const
{
auto result = std::make_unique<Tanker::UserKeyStore>(conn);
for (auto const& userKey : user.userKeys)
AWAIT_VOID(result->putPrivateKey(userKey.keyPair.publicKey,
userKey.keyPair.privateKey));
return result;
}
std::unique_ptr<Tanker::ContactStore> TrustchainBuilder::makeContactStoreWith(
std::vector<std::string> const& suserIds,
Tanker::DataStore::ADatabase* conn) const
{
auto contactStore = std::make_unique<Tanker::ContactStore>(conn);
for (auto const& suserId : suserIds)
{
auto const optUser = findUser(suserId);
if (!optUser)
{
throw Errors::AssertionError("makeContactStoreWith: no user named " +
suserId);
}
AWAIT_VOID(contactStore->putUser(optUser->asTankerUser()));
}
return contactStore;
}
std::unique_ptr<Tanker::ProvisionalUserKeysStore>
TrustchainBuilder::makeProvisionalUserKeysStoreWith(
std::vector<ProvisionalUser> const& provisionalUsers,
Tanker::DataStore::ADatabase* conn) const
{
auto provisionalUserKeysStore =
std::make_unique<Tanker::ProvisionalUserKeysStore>(conn);
for (auto const& provisionalUser : provisionalUsers)
{
AWAIT_VOID(provisionalUserKeysStore->putProvisionalUserKeys(
provisionalUser.secretProvisionalUser.appSignatureKeyPair.publicKey,
provisionalUser.secretProvisionalUser.tankerSignatureKeyPair.publicKey,
{
provisionalUser.secretProvisionalUser.appEncryptionKeyPair,
provisionalUser.secretProvisionalUser.tankerEncryptionKeyPair,
}));
}
return provisionalUserKeysStore;
}
std::vector<Group> TrustchainBuilder::getGroupsOfUser(
TrustchainBuilder::User const& user) const
{
std::vector<Group> result;
for (auto const& group : _groups)
{
if (std::find(group.members.begin(), group.members.end(), user.suserId) !=
group.members.end())
result.push_back(group.tankerGroup);
else
result.push_back(group.asExternalGroup());
}
return result;
}
std::unique_ptr<Tanker::GroupStore> TrustchainBuilder::makeGroupStore(
TrustchainBuilder::User const& user,
Tanker::DataStore::ADatabase* conn) const
{
auto result = std::make_unique<Tanker::GroupStore>(conn);
for (auto const& group : getGroupsOfUser(user))
AWAIT_VOID(result->put(group));
return result;
}
std::unique_ptr<Tanker::GroupStore> TrustchainBuilder::makeGroupStore(
std::vector<Trustchain::GroupId> const& groups,
Tanker::DataStore::ADatabase* conn) const
{
auto result = std::make_unique<Tanker::GroupStore>(conn);
for (auto const& groupId : groups)
{
auto const groupIt =
std::find_if(_groups.begin(), _groups.end(), [&](auto const& g) {
return g.tankerGroup.id == groupId;
});
if (groupIt == _groups.end())
throw std::runtime_error(
"TrustchainBuilder: unknown group in makeGroupStore");
AWAIT_VOID(result->put(groupIt->asExternalGroup()));
}
return result;
}
std::vector<ServerEntry> const& TrustchainBuilder::entries() const
{
return _entries;
}
std::vector<TrustchainBuilder::InternalGroup> TrustchainBuilder::groups() const
{
return std::vector<InternalGroup>(_groups.begin(), _groups.end());
}
std::vector<TrustchainBuilder::User> const& TrustchainBuilder::users() const
{
return _users;
}
|
#pragma once
#ifndef _MOUSE_STATE_H
#define _MOUSE_STATE_H
#include "Keys.h"
#include "../maths/MathCore.h"
class MouseState
{
private:
bool mouseLButton;
bool mouseRButton;
bool m_keepMouseOnScreen;
bool m_wrapMouseAroundScreen;
POINT pt;
bool m_init;
Vector2 m_mousePosition;
Vector2 m_prevMousePosition;
public:
MouseState(void);
~MouseState(void);
void Update();
bool IsButtonDown(Mouse::MousePad mouse);
bool IsButtonUp(Mouse::MousePad mouse);
const Vector2& getMousePosition();
const Vector2& getPrevMousePosition();
void MouseEventLDown();
void MouseEventLUp();
void MouseEventRDown();
void MouseEventRUp();
void SetMouseOnScreen(bool mouseOnScreen, bool wrapArroundScreen);
};
#endif
|
// SettingWnd.h: interface for the CSettingWnd class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SETTINGWND_H__DE96A50E_45B2_4D1F_85E6_9570518EC1CE__INCLUDED_)
#define AFX_SETTINGWND_H__DE96A50E_45B2_4D1F_85E6_9570518EC1CE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "guicontrolbar.h"
class CSettingWnd : public CGuiControlBar
{
public:
CSettingWnd();
virtual ~CSettingWnd();
DECLARE_MESSAGE_MAP()
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
private:
// Attributes
};
#endif // !defined(AFX_SETTINGWND_H__DE96A50E_45B2_4D1F_85E6_9570518EC1CE__INCLUDED_)
|
#pragma once
#include "Vector4.h"
#include "BasicLogicDefinitions.h"
class StaticObjectModel
{
public:
typedef struct {
float left,top,
right,bottom;
} Rect;
enum StaticObjectState {
STATIC_OBJECT_CANNOT_BE_COLLECTED,
STATIC_OBJECT_TO_BE_COLLECTED,
STATIC_OBJECT_COLLECTED
};
//The below is a simplification. We do not create separate classes for static objects
//It is ok to do so for the time being since there are few objects and not much
//complexity/logic attached to them
enum StaticObjectType {
STATIC_OBJECT_TYPE_COINS,
STATIC_OBJECT_TYPE_SHIELD,
STATIC_OBJECT_TYPE_GEM,
STATIC_OBJECT_TYPE_BOOTS,
STATIC_OBJECT_TYPE_LIFE_POTION,
STATIC_OBJECT_TYPE_DECORATION
};
public:
StaticObjectModel(StaticObjectType type);
virtual ~StaticObjectModel();
public:
void setTerrainPosition(const Vector4& terrainPosition) { m_terrainPosition = terrainPosition; }
const Vector4& getTerrainPosition() const { return m_terrainPosition; }
const Vector4 getScreenPosition() const { return m_terrainPosition*PIXELS_PER_METER; }
void setScreenPosition(const Vector4& screenPosition) { m_terrainPosition = screenPosition * (float)(1/ (float)PIXELS_PER_METER); }
void setRect(const Rect rect){ m_rect = rect; }
const Rect getRect(){return m_rect;}
void setStaticObjectState(StaticObjectState state){m_staticObjectState = state;}
const StaticObjectState getStaticObjectState(){return m_staticObjectState;}
const StaticObjectType getStaticObjectType(){return m_staticObjectType;}
void setPixelWidth(int width){ m_pixelWidth = width; }
const int getPixelWidth(){return m_pixelWidth;}
void setPixelHeight(int height){ m_pixelHeight = height; }
const int getPixelHeight(){return m_pixelHeight;}
protected:
StaticObjectType m_staticObjectType;
StaticObjectState m_staticObjectState;
Rect m_rect;
Vector4 m_terrainPosition;
int m_pixelWidth;
int m_pixelHeight;
};
|
/**********************************************************
//
// Wih (Wireless Interface Hockey)
//
// puck.cpp (パッククラス)
//
// Copyright (C) 2007,
// Masayuki Morita, Kazuki Hamada, Tatsuya Mori,
// All Rights Reserved.
**********************************************************/
#include "puck.h"
//方向から速度ベクトルを更新
void CPuck::set_direction(int direct){
direct_=direct;
switch(direct){
case 0:
break;
case 1:
v_.x_= step_;
v_.y_= -step_;
break;
case 2:
v_.x_= step_;
v_.y_= step_;
break;
case 3:
v_.x_= -step_;
v_.y_= step_;
break;
case 4:
v_.x_= -step_;
v_.y_= -step_;
break;
default:
v_.x_= 0;
v_.y_= 0;
break;
}
}
void CPuck::draw(HDC hdc) const{
//HBRUSH hBrush=CreateSolidBrush(RGB(225,225,255));
//HBRUSH hBrushOld=(HBRUSH)SelectObject(hdc,hBrush);
HBRUSH hBrushOld = (HBRUSH)SelectObject(hdc, (HBRUSH)GetStockObject(WHITE_BRUSH));
Ellipse(hdc,pos_.x_-radius_,pos_.y_-radius_,pos_.x_+radius_,pos_.y_+radius_);
SelectObject(hdc, hBrushOld);
//DeleteObject(hBrush);
}
|
// Created on: 1995-03-08
// Created by: Bruno DUMORTIER
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepPrimAPI_MakeHalfSpace_HeaderFile
#define _BRepPrimAPI_MakeHalfSpace_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <TopoDS_Solid.hxx>
#include <BRepBuilderAPI_MakeShape.hxx>
class TopoDS_Face;
class gp_Pnt;
class TopoDS_Shell;
//! Describes functions to build half-spaces.
//! A half-space is an infinite solid, limited by a surface. It
//! is built from a face or a shell, which bounds it, and with
//! a reference point, which specifies the side of the
//! surface where the matter of the half-space is located.
//! A half-space is a tool commonly used in topological
//! operations to cut another shape.
//! A MakeHalfSpace object provides a framework for:
//! - defining and implementing the construction of a half-space, and
//! - consulting the result.
class BRepPrimAPI_MakeHalfSpace : public BRepBuilderAPI_MakeShape
{
public:
DEFINE_STANDARD_ALLOC
//! Make a HalfSpace defined with a Face and a Point.
Standard_EXPORT BRepPrimAPI_MakeHalfSpace(const TopoDS_Face& Face, const gp_Pnt& RefPnt);
//! Make a HalfSpace defined with a Shell and a Point.
Standard_EXPORT BRepPrimAPI_MakeHalfSpace(const TopoDS_Shell& Shell, const gp_Pnt& RefPnt);
//! Returns the constructed half-space as a solid.
Standard_EXPORT const TopoDS_Solid& Solid() const;
Standard_EXPORT operator TopoDS_Solid() const;
protected:
private:
TopoDS_Solid mySolid;
};
#endif // _BRepPrimAPI_MakeHalfSpace_HeaderFile
|
/****************************************************************
* TianGong RenderLab *
* Copyright (c) Gaiyitp9. All rights reserved. *
* This code is licensed under the MIT License (MIT). *
*****************************************************************/
#pragma once
#include <chrono>
namespace TG
{
// 高精度计时器
class Chronometer
{
public:
Chronometer();
Chronometer(const Chronometer&) = delete;
Chronometer(Chronometer&&) = delete;
Chronometer& operator=(const Chronometer&) = delete;
Chronometer& operator=(Chronometer&&) = delete;
~Chronometer();
static std::wstring Date(); // 当前时区的日期和时间
[[nodiscard]] float DeltaTime() const;
[[nodiscard]] float TotalTime() const;
void Reset();
void Pause();
void Start();
void Tick();
private:
double m_deltaTime = 0.0; // 单位毫秒(ms)
bool m_stopped = false;
std::chrono::steady_clock::time_point m_base; // 开始运行的时间点
std::chrono::steady_clock::time_point m_last; // 上一帧的时间点
std::chrono::steady_clock::time_point m_stop; // 暂停的时间点
std::chrono::duration<double, std::milli> m_paused{}; // 已暂停的时间
};
}
|
#ifndef __VIVADO_SYNTH__
#include <fstream>
using namespace std;
// Debug utility
ofstream* global_debug_handle;
#endif //__VIVADO_SYNTH__
#include "bxy_ur_4_opt_compute_units.h"
#include "hw_classes.h"
struct blurx_blurx_update_0_write0_merged_banks_3_cache {
// RAM Box: {[0, 1920], [0, 1079]}
// Capacity: 2
// # of read delays: 2
hw_uint<16> f0;
hw_uint<16> f2;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct blurx_blurx_update_0_write1_merged_banks_3_cache {
// RAM Box: {[1, 1921], [0, 1079]}
// Capacity: 2
// # of read delays: 2
hw_uint<16> f0;
hw_uint<16> f2;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct blurx_blurx_update_0_write2_merged_banks_3_cache {
// RAM Box: {[2, 1922], [0, 1079]}
// Capacity: 2
// # of read delays: 2
hw_uint<16> f0;
hw_uint<16> f2;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct blurx_blurx_update_0_write3_merged_banks_3_cache {
// RAM Box: {[3, 1923], [0, 1079]}
// Capacity: 2
// # of read delays: 2
hw_uint<16> f0;
hw_uint<16> f2;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct blurx_cache {
blurx_blurx_update_0_write0_merged_banks_3_cache blurx_blurx_update_0_write0_merged_banks_3;
blurx_blurx_update_0_write1_merged_banks_3_cache blurx_blurx_update_0_write1_merged_banks_3;
blurx_blurx_update_0_write2_merged_banks_3_cache blurx_blurx_update_0_write2_merged_banks_3;
blurx_blurx_update_0_write3_merged_banks_3_cache blurx_blurx_update_0_write3_merged_banks_3;
};
inline void blurx_blurx_update_0_write0_write(hw_uint<16>& blurx_blurx_update_0_write0, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write0_merged_banks_3.push(blurx_blurx_update_0_write0);
}
inline void blurx_blurx_update_0_write1_write(hw_uint<16>& blurx_blurx_update_0_write1, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write1_merged_banks_3.push(blurx_blurx_update_0_write1);
}
inline void blurx_blurx_update_0_write2_write(hw_uint<16>& blurx_blurx_update_0_write2, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write2_merged_banks_3.push(blurx_blurx_update_0_write2);
}
inline void blurx_blurx_update_0_write3_write(hw_uint<16>& blurx_blurx_update_0_write3, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write3_merged_banks_3.push(blurx_blurx_update_0_write3);
}
inline hw_uint<16> bxy_ur_4_rd0_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd0 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { bxy_ur_4_update_0[d0, d1] -> 1 : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write0 = blurx.blurx_blurx_update_0_write0_merged_banks_3.peek_1();
return value_blurx_blurx_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd1_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd1 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[1 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { bxy_ur_4_update_0[d0, d1] -> 1 : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write1 = blurx.blurx_blurx_update_0_write1_merged_banks_3.peek_1();
return value_blurx_blurx_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd10_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd10 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[4 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { }
auto value_blurx_blurx_update_0_write0 = blurx.blurx_blurx_update_0_write0_merged_banks_3.peek_0();
return value_blurx_blurx_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd11_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd11 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[5 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { }
auto value_blurx_blurx_update_0_write1 = blurx.blurx_blurx_update_0_write1_merged_banks_3.peek_0();
return value_blurx_blurx_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd2_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd2 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[2 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { bxy_ur_4_update_0[d0, d1] -> 1 : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write2 = blurx.blurx_blurx_update_0_write2_merged_banks_3.peek_1();
return value_blurx_blurx_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd3_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd3 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[1 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { bxy_ur_4_update_0[d0, d1] -> 1 : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write1 = blurx.blurx_blurx_update_0_write1_merged_banks_3.peek_1();
return value_blurx_blurx_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd4_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd4 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[2 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { bxy_ur_4_update_0[d0, d1] -> 1 : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write2 = blurx.blurx_blurx_update_0_write2_merged_banks_3.peek_1();
return value_blurx_blurx_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd5_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd5 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[3 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { bxy_ur_4_update_0[d0, d1] -> 1 : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write3 = blurx.blurx_blurx_update_0_write3_merged_banks_3.peek_1();
return value_blurx_blurx_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd6_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd6 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[2 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { bxy_ur_4_update_0[d0, d1] -> 1 : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write2 = blurx.blurx_blurx_update_0_write2_merged_banks_3.peek_1();
return value_blurx_blurx_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd7_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd7 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[3 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { bxy_ur_4_update_0[d0, d1] -> 1 : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write3 = blurx.blurx_blurx_update_0_write3_merged_banks_3.peek_1();
return value_blurx_blurx_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd8_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd8 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[4 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { }
auto value_blurx_blurx_update_0_write0 = blurx.blurx_blurx_update_0_write0_merged_banks_3.peek_0();
return value_blurx_blurx_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> bxy_ur_4_rd9_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// bxy_ur_4_rd9 read pattern: { bxy_ur_4_update_0[d0, d1] -> blurx[3 + 4d0, d1] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Read schedule : { bxy_ur_4_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// DD fold: { bxy_ur_4_update_0[d0, d1] -> 1 : 0 <= d0 <= 479 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write3 = blurx.blurx_blurx_update_0_write3_merged_banks_3.peek_1();
return value_blurx_blurx_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// blurx_update_0_write
// blurx_blurx_update_0_write0
// blurx_blurx_update_0_write1
// blurx_blurx_update_0_write2
// blurx_blurx_update_0_write3
inline void blurx_blurx_update_0_write_bundle_write(hw_uint<64>& blurx_update_0_write, blurx_cache& blurx, int d0, int d1) {
hw_uint<16> blurx_blurx_update_0_write0_res = blurx_update_0_write.extract<0, 15>();
blurx_blurx_update_0_write0_write(blurx_blurx_update_0_write0_res, blurx, d0, d1);
hw_uint<16> blurx_blurx_update_0_write1_res = blurx_update_0_write.extract<16, 31>();
blurx_blurx_update_0_write1_write(blurx_blurx_update_0_write1_res, blurx, d0, d1);
hw_uint<16> blurx_blurx_update_0_write2_res = blurx_update_0_write.extract<32, 47>();
blurx_blurx_update_0_write2_write(blurx_blurx_update_0_write2_res, blurx, d0, d1);
hw_uint<16> blurx_blurx_update_0_write3_res = blurx_update_0_write.extract<48, 63>();
blurx_blurx_update_0_write3_write(blurx_blurx_update_0_write3_res, blurx, d0, d1);
}
// bxy_ur_4_update_0_read
// bxy_ur_4_rd0
// bxy_ur_4_rd1
// bxy_ur_4_rd2
// bxy_ur_4_rd3
// bxy_ur_4_rd4
// bxy_ur_4_rd5
// bxy_ur_4_rd6
// bxy_ur_4_rd7
// bxy_ur_4_rd8
// bxy_ur_4_rd9
// bxy_ur_4_rd10
// bxy_ur_4_rd11
inline hw_uint<192> blurx_bxy_ur_4_update_0_read_bundle_read(blurx_cache& blurx, int d0, int d1) {
// # of ports in bundle: 12
// bxy_ur_4_rd0
// bxy_ur_4_rd1
// bxy_ur_4_rd2
// bxy_ur_4_rd3
// bxy_ur_4_rd4
// bxy_ur_4_rd5
// bxy_ur_4_rd6
// bxy_ur_4_rd7
// bxy_ur_4_rd8
// bxy_ur_4_rd9
// bxy_ur_4_rd10
// bxy_ur_4_rd11
hw_uint<192> result;
hw_uint<16> bxy_ur_4_rd0_res = bxy_ur_4_rd0_select(blurx, d0, d1);
set_at<0, 192>(result, bxy_ur_4_rd0_res);
hw_uint<16> bxy_ur_4_rd1_res = bxy_ur_4_rd1_select(blurx, d0, d1);
set_at<16, 192>(result, bxy_ur_4_rd1_res);
hw_uint<16> bxy_ur_4_rd2_res = bxy_ur_4_rd2_select(blurx, d0, d1);
set_at<32, 192>(result, bxy_ur_4_rd2_res);
hw_uint<16> bxy_ur_4_rd3_res = bxy_ur_4_rd3_select(blurx, d0, d1);
set_at<48, 192>(result, bxy_ur_4_rd3_res);
hw_uint<16> bxy_ur_4_rd4_res = bxy_ur_4_rd4_select(blurx, d0, d1);
set_at<64, 192>(result, bxy_ur_4_rd4_res);
hw_uint<16> bxy_ur_4_rd5_res = bxy_ur_4_rd5_select(blurx, d0, d1);
set_at<80, 192>(result, bxy_ur_4_rd5_res);
hw_uint<16> bxy_ur_4_rd6_res = bxy_ur_4_rd6_select(blurx, d0, d1);
set_at<96, 192>(result, bxy_ur_4_rd6_res);
hw_uint<16> bxy_ur_4_rd7_res = bxy_ur_4_rd7_select(blurx, d0, d1);
set_at<112, 192>(result, bxy_ur_4_rd7_res);
hw_uint<16> bxy_ur_4_rd8_res = bxy_ur_4_rd8_select(blurx, d0, d1);
set_at<128, 192>(result, bxy_ur_4_rd8_res);
hw_uint<16> bxy_ur_4_rd9_res = bxy_ur_4_rd9_select(blurx, d0, d1);
set_at<144, 192>(result, bxy_ur_4_rd9_res);
hw_uint<16> bxy_ur_4_rd10_res = bxy_ur_4_rd10_select(blurx, d0, d1);
set_at<160, 192>(result, bxy_ur_4_rd10_res);
hw_uint<16> bxy_ur_4_rd11_res = bxy_ur_4_rd11_select(blurx, d0, d1);
set_at<176, 192>(result, bxy_ur_4_rd11_res);
return result;
}
#include "hw_classes.h"
struct input_input_update_0_write0_merged_banks_3_cache {
// RAM Box: {[0, 1920], [0, 1081]}
// Capacity: 963
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 480> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 480> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_480() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_481() {
return f2;
}
inline hw_uint<16> peek_961() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_962() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 480
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 480 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 480
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 480 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_input_update_0_write1_merged_banks_3_cache {
// RAM Box: {[1, 1921], [0, 1081]}
// Capacity: 963
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 480> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 480> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_480() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_481() {
return f2;
}
inline hw_uint<16> peek_961() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_962() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 480
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 480 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 480
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 480 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_input_update_0_write2_merged_banks_3_cache {
// RAM Box: {[2, 1922], [0, 1081]}
// Capacity: 963
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 480> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 480> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_480() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_481() {
return f2;
}
inline hw_uint<16> peek_961() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_962() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 480
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 480 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 480
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 480 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_input_update_0_write3_merged_banks_3_cache {
// RAM Box: {[3, 1923], [0, 1081]}
// Capacity: 963
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 480> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 480> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_480() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_481() {
return f2;
}
inline hw_uint<16> peek_961() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_962() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 480
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 480 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 480
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 480 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_cache {
input_input_update_0_write0_merged_banks_3_cache input_input_update_0_write0_merged_banks_3;
input_input_update_0_write1_merged_banks_3_cache input_input_update_0_write1_merged_banks_3;
input_input_update_0_write2_merged_banks_3_cache input_input_update_0_write2_merged_banks_3;
input_input_update_0_write3_merged_banks_3_cache input_input_update_0_write3_merged_banks_3;
};
inline void input_input_update_0_write0_write(hw_uint<16>& input_input_update_0_write0, input_cache& input, int d0, int d1) {
input.input_input_update_0_write0_merged_banks_3.push(input_input_update_0_write0);
}
inline void input_input_update_0_write1_write(hw_uint<16>& input_input_update_0_write1, input_cache& input, int d0, int d1) {
input.input_input_update_0_write1_merged_banks_3.push(input_input_update_0_write1);
}
inline void input_input_update_0_write2_write(hw_uint<16>& input_input_update_0_write2, input_cache& input, int d0, int d1) {
input.input_input_update_0_write2_merged_banks_3.push(input_input_update_0_write2);
}
inline void input_input_update_0_write3_write(hw_uint<16>& input_input_update_0_write3, input_cache& input, int d0, int d1) {
input.input_input_update_0_write3_merged_banks_3.push(input_input_update_0_write3);
}
inline hw_uint<16> blurx_rd0_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd0 read pattern: { blurx_update_0[d0, d1] -> input[4d0, d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 962 : 0 < d0 <= 479 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (482 + d0) : d0 = 480 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 962 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write0 = input.input_input_update_0_write0_merged_banks_3.peek_962();
return value_input_input_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd1_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd1 read pattern: { blurx_update_0[d0, d1] -> input[4d0, 1 + d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 481 : 0 < d0 <= 479 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 480 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 481 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write0 = input.input_input_update_0_write0_merged_banks_3.peek_481();
return value_input_input_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd10_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd10 read pattern: { blurx_update_0[d0, d1] -> input[3 + 4d0, 1 + d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 481 : 0 < d0 <= 479 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 480 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 481 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write3 = input.input_input_update_0_write3_merged_banks_3.peek_481();
return value_input_input_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd11_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd11 read pattern: { blurx_update_0[d0, d1] -> input[3 + 4d0, 2 + d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write3 = input.input_input_update_0_write3_merged_banks_3.peek_0();
return value_input_input_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd2_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd2 read pattern: { blurx_update_0[d0, d1] -> input[4d0, 2 + d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write0 = input.input_input_update_0_write0_merged_banks_3.peek_0();
return value_input_input_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd3_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd3 read pattern: { blurx_update_0[d0, d1] -> input[1 + 4d0, d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 962 : 0 < d0 <= 479 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (482 + d0) : d0 = 480 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 962 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write1 = input.input_input_update_0_write1_merged_banks_3.peek_962();
return value_input_input_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd4_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd4 read pattern: { blurx_update_0[d0, d1] -> input[1 + 4d0, 1 + d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 481 : 0 < d0 <= 479 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 480 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 481 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write1 = input.input_input_update_0_write1_merged_banks_3.peek_481();
return value_input_input_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd5_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd5 read pattern: { blurx_update_0[d0, d1] -> input[1 + 4d0, 2 + d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write1 = input.input_input_update_0_write1_merged_banks_3.peek_0();
return value_input_input_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd6_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd6 read pattern: { blurx_update_0[d0, d1] -> input[2 + 4d0, d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 962 : 0 < d0 <= 479 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (482 + d0) : d0 = 480 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 962 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write2 = input.input_input_update_0_write2_merged_banks_3.peek_962();
return value_input_input_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd7_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd7 read pattern: { blurx_update_0[d0, d1] -> input[2 + 4d0, 1 + d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 481 : 0 < d0 <= 479 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 480 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 481 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write2 = input.input_input_update_0_write2_merged_banks_3.peek_481();
return value_input_input_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd8_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd8 read pattern: { blurx_update_0[d0, d1] -> input[2 + 4d0, 2 + d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write2 = input.input_input_update_0_write2_merged_banks_3.peek_0();
return value_input_input_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd9_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd9 read pattern: { blurx_update_0[d0, d1] -> input[3 + 4d0, d1] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 480 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 480 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 962 : 0 < d0 <= 479 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (482 + d0) : d0 = 480 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 962 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write3 = input.input_input_update_0_write3_merged_banks_3.peek_962();
return value_input_input_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// blurx_update_0_read
// blurx_rd0
// blurx_rd1
// blurx_rd2
// blurx_rd3
// blurx_rd4
// blurx_rd5
// blurx_rd6
// blurx_rd7
// blurx_rd8
// blurx_rd9
// blurx_rd10
// blurx_rd11
inline hw_uint<192> input_blurx_update_0_read_bundle_read(input_cache& input, int d0, int d1) {
// # of ports in bundle: 12
// blurx_rd0
// blurx_rd1
// blurx_rd2
// blurx_rd3
// blurx_rd4
// blurx_rd5
// blurx_rd6
// blurx_rd7
// blurx_rd8
// blurx_rd9
// blurx_rd10
// blurx_rd11
hw_uint<192> result;
hw_uint<16> blurx_rd0_res = blurx_rd0_select(input, d0, d1);
set_at<0, 192>(result, blurx_rd0_res);
hw_uint<16> blurx_rd1_res = blurx_rd1_select(input, d0, d1);
set_at<16, 192>(result, blurx_rd1_res);
hw_uint<16> blurx_rd2_res = blurx_rd2_select(input, d0, d1);
set_at<32, 192>(result, blurx_rd2_res);
hw_uint<16> blurx_rd3_res = blurx_rd3_select(input, d0, d1);
set_at<48, 192>(result, blurx_rd3_res);
hw_uint<16> blurx_rd4_res = blurx_rd4_select(input, d0, d1);
set_at<64, 192>(result, blurx_rd4_res);
hw_uint<16> blurx_rd5_res = blurx_rd5_select(input, d0, d1);
set_at<80, 192>(result, blurx_rd5_res);
hw_uint<16> blurx_rd6_res = blurx_rd6_select(input, d0, d1);
set_at<96, 192>(result, blurx_rd6_res);
hw_uint<16> blurx_rd7_res = blurx_rd7_select(input, d0, d1);
set_at<112, 192>(result, blurx_rd7_res);
hw_uint<16> blurx_rd8_res = blurx_rd8_select(input, d0, d1);
set_at<128, 192>(result, blurx_rd8_res);
hw_uint<16> blurx_rd9_res = blurx_rd9_select(input, d0, d1);
set_at<144, 192>(result, blurx_rd9_res);
hw_uint<16> blurx_rd10_res = blurx_rd10_select(input, d0, d1);
set_at<160, 192>(result, blurx_rd10_res);
hw_uint<16> blurx_rd11_res = blurx_rd11_select(input, d0, d1);
set_at<176, 192>(result, blurx_rd11_res);
return result;
}
// input_update_0_write
// input_input_update_0_write0
// input_input_update_0_write1
// input_input_update_0_write2
// input_input_update_0_write3
inline void input_input_update_0_write_bundle_write(hw_uint<64>& input_update_0_write, input_cache& input, int d0, int d1) {
hw_uint<16> input_input_update_0_write0_res = input_update_0_write.extract<0, 15>();
input_input_update_0_write0_write(input_input_update_0_write0_res, input, d0, d1);
hw_uint<16> input_input_update_0_write1_res = input_update_0_write.extract<16, 31>();
input_input_update_0_write1_write(input_input_update_0_write1_res, input, d0, d1);
hw_uint<16> input_input_update_0_write2_res = input_update_0_write.extract<32, 47>();
input_input_update_0_write2_write(input_input_update_0_write2_res, input, d0, d1);
hw_uint<16> input_input_update_0_write3_res = input_update_0_write.extract<48, 63>();
input_input_update_0_write3_write(input_input_update_0_write3_res, input, d0, d1);
}
// Operation logic
inline void bxy_ur_4_update_0(blurx_cache& blurx, HWStream<hw_uint<64> >& /* buffer_args num ports = 4 */bxy_ur_4, int d0, int d1) {
// Consume: blurx
auto blurx_0_c__0_value = blurx_bxy_ur_4_update_0_read_bundle_read(blurx/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
*global_debug_handle << "bxy_ur_4_update_0_blurx," << d0<< "," << d1<< "," << blurx_0_c__0_value << endl;
#endif //__VIVADO_SYNTH__
auto compute_result = bxy_ur_4_generated_compute_unrolled_4(blurx_0_c__0_value);
// Produce: bxy_ur_4
bxy_ur_4.write(compute_result);
#ifndef __VIVADO_SYNTH__
hw_uint<64> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
hw_uint<16> debug_compute_result_lane_1;
set_at<0, 16, 16>(debug_compute_result_lane_1, debug_compute_result.extract<16, 31>());
hw_uint<16> debug_compute_result_lane_2;
set_at<0, 16, 16>(debug_compute_result_lane_2, debug_compute_result.extract<32, 47>());
hw_uint<16> debug_compute_result_lane_3;
set_at<0, 16, 16>(debug_compute_result_lane_3, debug_compute_result.extract<48, 63>());
*global_debug_handle << "bxy_ur_4_update_0," << (4*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
*global_debug_handle << "bxy_ur_4_update_0," << (4*d0 + 1) << ", " << d1<< "," << debug_compute_result_lane_1 << endl;
*global_debug_handle << "bxy_ur_4_update_0," << (4*d0 + 2) << ", " << d1<< "," << debug_compute_result_lane_2 << endl;
*global_debug_handle << "bxy_ur_4_update_0," << (4*d0 + 3) << ", " << d1<< "," << debug_compute_result_lane_3 << endl;
#endif //__VIVADO_SYNTH__
}
inline void blurx_update_0(input_cache& input, blurx_cache& blurx, int d0, int d1) {
// Consume: input
auto input_0_c__0_value = input_blurx_update_0_read_bundle_read(input/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
*global_debug_handle << "blurx_update_0_input," << d0<< "," << d1<< "," << input_0_c__0_value << endl;
#endif //__VIVADO_SYNTH__
auto compute_result = blurx_generated_compute_unrolled_4(input_0_c__0_value);
// Produce: blurx
blurx_blurx_update_0_write_bundle_write(compute_result, blurx, d0, d1);
#ifndef __VIVADO_SYNTH__
hw_uint<64> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
hw_uint<16> debug_compute_result_lane_1;
set_at<0, 16, 16>(debug_compute_result_lane_1, debug_compute_result.extract<16, 31>());
hw_uint<16> debug_compute_result_lane_2;
set_at<0, 16, 16>(debug_compute_result_lane_2, debug_compute_result.extract<32, 47>());
hw_uint<16> debug_compute_result_lane_3;
set_at<0, 16, 16>(debug_compute_result_lane_3, debug_compute_result.extract<48, 63>());
*global_debug_handle << "blurx_update_0," << (4*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
*global_debug_handle << "blurx_update_0," << (4*d0 + 1) << ", " << d1<< "," << debug_compute_result_lane_1 << endl;
*global_debug_handle << "blurx_update_0," << (4*d0 + 2) << ", " << d1<< "," << debug_compute_result_lane_2 << endl;
*global_debug_handle << "blurx_update_0," << (4*d0 + 3) << ", " << d1<< "," << debug_compute_result_lane_3 << endl;
#endif //__VIVADO_SYNTH__
}
inline void input_update_0(HWStream<hw_uint<64> >& /* buffer_args num ports = 4 */input_arg, input_cache& input, int d0, int d1) {
// Consume: input_arg
auto input_arg_0_c__0_value = input_arg.read();
auto compute_result = input_generated_compute_unrolled_4(input_arg_0_c__0_value);
// Produce: input
input_input_update_0_write_bundle_write(compute_result, input, d0, d1);
#ifndef __VIVADO_SYNTH__
hw_uint<64> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
hw_uint<16> debug_compute_result_lane_1;
set_at<0, 16, 16>(debug_compute_result_lane_1, debug_compute_result.extract<16, 31>());
hw_uint<16> debug_compute_result_lane_2;
set_at<0, 16, 16>(debug_compute_result_lane_2, debug_compute_result.extract<32, 47>());
hw_uint<16> debug_compute_result_lane_3;
set_at<0, 16, 16>(debug_compute_result_lane_3, debug_compute_result.extract<48, 63>());
*global_debug_handle << "input_update_0," << (4*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
*global_debug_handle << "input_update_0," << (4*d0 + 1) << ", " << d1<< "," << debug_compute_result_lane_1 << endl;
*global_debug_handle << "input_update_0," << (4*d0 + 2) << ", " << d1<< "," << debug_compute_result_lane_2 << endl;
*global_debug_handle << "input_update_0," << (4*d0 + 3) << ", " << d1<< "," << debug_compute_result_lane_3 << endl;
#endif //__VIVADO_SYNTH__
}
// Driver function
void bxy_ur_4_opt(HWStream<hw_uint<64> >& /* get_args num ports = 4 */input_arg, HWStream<hw_uint<64> >& /* get_args num ports = 4 */bxy_ur_4, int num_epochs) {
#ifndef __VIVADO_SYNTH__
ofstream debug_file("bxy_ur_4_opt_debug.csv");
global_debug_handle = &debug_file;
#endif //__VIVADO_SYNTH__
blurx_cache blurx;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
input_cache input;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
#ifdef __VIVADO_SYNTH__
#pragma HLS inline recursive
#endif // __VIVADO_SYNTH__
for (int epoch = 0; epoch < num_epochs; epoch++) {
// Schedules...
// blurx_update_0 -> [1*d1*1*1 + 1*2,1*d0*1*1 + 1*0,1*2]
// bxy_ur_4_update_0 -> [1*d1*1*1 + 1*2,1*d0*1*1 + 1*1,1*3]
// input_arg_update_0 -> [1*d1*1*1 + 1*0,1*d0*1*1 + 1*0,1*0]
// input_update_0 -> [1*d1*1*1 + 1*0,1*d0*1*1 + 1*0,1*1]
for (int c0 = 0; c0 <= 1081; c0++) {
for (int c1 = 0; c1 <= 480; c1++) {
#ifdef __VIVADO_SYNTH__
#pragma HLS pipeline II=1
#endif // __VIVADO_SYNTH__
if ((0 <= c1 && c1 <= 480) && ((c1 - 0) % 1 == 0) && (0 <= c0 && c0 <= 1081) && ((c0 - 0) % 1 == 0)) {
input_update_0(input_arg, input, (c1 - 0) / 1, (c0 - 0) / 1);
}
if ((0 <= c1 && c1 <= 480) && ((c1 - 0) % 1 == 0) && (2 <= c0 && c0 <= 1081) && ((c0 - 2) % 1 == 0)) {
blurx_update_0(input, blurx, (c1 - 0) / 1, (c0 - 2) / 1);
}
if ((1 <= c1 && c1 <= 480) && ((c1 - 1) % 1 == 0) && (2 <= c0 && c0 <= 1081) && ((c0 - 2) % 1 == 0)) {
bxy_ur_4_update_0(blurx, bxy_ur_4, (c1 - 1) / 1, (c0 - 2) / 1);
}
}
}
}
#ifndef __VIVADO_SYNTH__
debug_file.close();
#endif //__VIVADO_SYNTH__
}
void bxy_ur_4_opt(HWStream<hw_uint<64> >& /* get_args num ports = 4 */input_arg, HWStream<hw_uint<64> >& /* get_args num ports = 4 */bxy_ur_4) {
bxy_ur_4_opt(input_arg, bxy_ur_4, 1);
}
#ifdef __VIVADO_SYNTH__
#include "bxy_ur_4_opt.h"
const int bxy_ur_4_update_0_write_num_transfers = 518400;
const int input_update_0_read_num_transfers = 520442;
extern "C" {
static void read_input_update_0_read(hw_uint<64>* input, HWStream<hw_uint<64> >& v, const int size) {
hw_uint<64> burst_reg;
int num_transfers = input_update_0_read_num_transfers*size;
for (int i = 0; i < num_transfers; i++) {
#pragma HLS pipeline II=1
burst_reg = input[i];
v.write(burst_reg);
}
}
static void write_bxy_ur_4_update_0_write(hw_uint<64>* output, HWStream<hw_uint<64> >& v, const int size) {
hw_uint<64> burst_reg;
int num_transfers = bxy_ur_4_update_0_write_num_transfers*size;
for (int i = 0; i < num_transfers; i++) {
#pragma HLS pipeline II=1
burst_reg = v.read();
output[i] = burst_reg;
}
}
void bxy_ur_4_opt_accel(hw_uint<64>* input_update_0_read, hw_uint<64>* bxy_ur_4_update_0_write, const int size) {
#pragma HLS dataflow
#pragma HLS INTERFACE m_axi port = input_update_0_read offset = slave depth = 65536 bundle = gmem0
#pragma HLS INTERFACE m_axi port = bxy_ur_4_update_0_write offset = slave depth = 65536 bundle = gmem1
#pragma HLS INTERFACE s_axilite port = input_update_0_read bundle = control
#pragma HLS INTERFACE s_axilite port = bxy_ur_4_update_0_write bundle = control
#pragma HLS INTERFACE s_axilite port = size bundle = control
#pragma HLS INTERFACE s_axilite port = return bundle = control
static HWStream<hw_uint<64> > input_update_0_read_channel;
static HWStream<hw_uint<64> > bxy_ur_4_update_0_write_channel;
read_input_update_0_read(input_update_0_read, input_update_0_read_channel, size);
bxy_ur_4_opt(input_update_0_read_channel, bxy_ur_4_update_0_write_channel, size);
write_bxy_ur_4_update_0_write(bxy_ur_4_update_0_write, bxy_ur_4_update_0_write_channel, size);
}
}
#endif //__VIVADO_SYNTH__
|
#include <iostream>
#include <vector>
#define MAX 10001
#define MOD (long long)1e12
typedef long long ll;
std::vector<ll> dp[MAX];
ll Get(int i, int j)
{
if(dp[i].size() <= j)
{
return 0;
}
return dp[i][j];
}
int main()
{
dp[0].push_back(0);
dp[1].push_back(1);
for(int i = 2; i < MAX; i++)
{
int len = std::max(dp[i - 1].size(), dp[i - 2].size());
ll up = 0;
for(int j = 0; j < len; j++)
{
ll a = Get(i - 1, j);
ll b = Get(i - 2, j);
ll M = (a + b + up) / MOD;
ll N = (a + b + up) % MOD;
dp[i].push_back(N);
up = M;
}
if(up > 0)
{
dp[i].push_back(up);
}
}
int n;
scanf("%d", &n);
for(auto idx = dp[n].rbegin(); idx != dp[n].rend(); idx++)
{
if(idx == dp[n].rbegin())
{
printf("%lld", *idx);
}
else
{
printf("%012lld", *idx);
}
}
return 0;
}
|
#pragma once
#include <atomic>
inline namespace arba
{
namespace evnt
{
class event_info
{
inline static std::size_t generate_type_index_()
{
static std::atomic_size_t index = 0;
return index++;
}
public:
template <class event_type>
inline static std::size_t type_index()
{
static const std::size_t index = generate_type_index_();
return index;
}
};
}
}
|
#include <Servo.h>
Servo myservo; // create servo object to control a servo
Servo myservo2;
int potpin0 = 0; // address analog pin to read data from the potentiometer
int potpin1 = 1; // potentiometer address
//int heartbeat = 2; // replace potpin2 with heartbeat if you want to add a heart beat sensor
int val0; // variable to read the value from the analog pin (looking for 1-5Volts)
int val1;
void setup() {
myservo.attach(8); // attaches the servo on pin 9 to the servo object
myservo2.attach(12);
Serial.begin(9600);
}
void loop() {
val0 = analogRead(potpin0); // reads the value of the voltage of the potentiometer (value between 0 and 1023)
val0 = map(val0, 0, 1023, 0, 90); // 0-1023 is what we're reading and we scale it to use it with the servo (value between 0 and 180)
val1 = analogRead(potpin1);
val1 = map(val1, 0, 1023, 0, 90);
myservo.write(val0); // sets the servo position according to the scaled value
myservo2.write(val1);
//debug
Serial.println(val0);
Serial.println(val1);
delay(15); // waits for the servo to get there
}
|
#ifndef NESTED_INTEGRATION_STD_LIST_ITERATE_HPP
#define NESTED_INTEGRATION_STD_LIST_ITERATE_HPP
#include <list>
#include "nested/integration/std/detail/iterate.hpp"
#include "nested/integration/iterate.hpp"
namespace nested
{
namespace integrate
{
namespace iterate
{
template<typename State, typename Functor, typename T>
inline void iterate(std::list<T>& l, Functor& f)
{
detail::iterate<State>(l.begin(), l.end(), f);
}
template<typename State, typename Functor, typename T>
inline void iterate(std::list<T> const& l, Functor& f)
{
detail::iterate<State>(l.begin(), l.end(), f);
}
} // namespace iterate
} // namespace integrate
} // namespace nested
#endif // #ifndef NESTED_INTEGRATION_STD_LIST_ITERATE_HPP
|
// Created on: 1995-07-24
// Created by: Modelistation
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StdPrs_WFPoleSurface_HeaderFile
#define _StdPrs_WFPoleSurface_HeaderFile
#include <Prs3d_Root.hxx>
#include <Prs3d_Drawer.hxx>
class Adaptor3d_Surface;
//! Computes the presentation of surfaces by drawing a
//! double network of lines linking the poles of the surface
//! in the two parametric direction.
//! The number of lines to be drawn is controlled
//! by the NetworkNumber of the given Drawer.
class StdPrs_WFPoleSurface : public Prs3d_Root
{
public:
DEFINE_STANDARD_ALLOC
//! Adds the surface aSurface to the presentation object aPresentation.
//! The shape's display attributes are set in the attribute manager aDrawer.
//! The surface aSurface is a surface object from
//! Adaptor3d, and provides data from a Geom surface.
//! This makes it possible to use the surface in a geometric algorithm.
Standard_EXPORT static void Add (const Handle(Prs3d_Presentation)& aPresentation, const Adaptor3d_Surface& aSurface, const Handle(Prs3d_Drawer)& aDrawer);
protected:
private:
};
#endif // _StdPrs_WFPoleSurface_HeaderFile
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.