blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fe476b5bb9638e5eb5a0a91cb4cfa8175ba58487 | 1f9ff37c2383ea01758a486eeb9d46185c28520f | /Solved Problems/Trees/Partitions the Tree.cpp | f2e6e5e25b84ae69a27240ec8ce66fd584cc19ac | [] | no_license | Manii-M/InterviewBit | 992a9fbca290052d2386536443e57f62818bdc12 | b5d735d9c22edebfbcbd2ee06532cba28f18f64d | refs/heads/master | 2022-12-15T10:31:55.391785 | 2020-09-07T13:56:44 | 2020-09-07T13:56:44 | 263,404,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,709 | cpp | Partitions the Tree.cpp | /**
* Equal Tree Partition
Problem Description
Given a binary tree A. Check whether it is possible to partition the tree to two trees which have equal sum of values after removing exactly one edge on the original tree.
Problem Constraints
1 <= size of tree <= 100000
-109 <= value of node <= 109
Input Format
First and only argument is head of tree A.
Output Format
Return 1 if the tree can be partitioned into two trees of equal sum else return 0.
Example Input
Input 1:
5
/ \
3 7
/ \ / \
4 6 5 6
Input 2:
1
/ \
2 10
/ \
20 2
Example Output
Output 1:
1
Output 2:
0
Example Explanation
Explanation 1:
Remove edge between 5(root node) and 7:
Tree 1 = Tree 2 =
5 7
/ / \
3 5 6
/ \
4 6
Sum of Tree 1 = Sum of Tree 2 = 18
Explanation 2:
The given Tree cannot be partitioned.
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int canPartitioned(TreeNode *A, map<int, TreeNode *> &m, TreeNode *root)
{
if (A == NULL)
return 0;
int left = canPartitioned(A->left, m, root);
int right = canPartitioned(A->right, m, root);
int sum = left + right + A->val;
if (A != root)
m[sum] = A;
return sum;
}
int Solution::solve(TreeNode *A)
{
TreeNode *root = A;
map<int, TreeNode *> m;
int sum = canPartitioned(A, m, root);
if (sum % 2 == 0 && m.find(sum / 2) != m.end())
return 1;
return 0;
}
/**
Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}; */
int dfs(TreeNode *root, unordered_map<int, int> &m)
{
if (!root)
return 0;
int cur = root->val + dfs(root->left, m) + dfs(root->right, m);
++m[cur];
return cur;
}
int checkEqualPartition(TreeNode *root)
{
unordered_map<int, int> m;
int sum = dfs(root, m);
if (sum == 0)
{
if (m[0] > 1)
return 1;
return 0;
}
if (sum % 2)
return 0;
if (m.count(sum / 2))
return 1;
return 0;
}
int Solution::solve(TreeNode *A) { return checkEqualPartition(A); } |
9e77ae57c1f084d5cb61d47a74bdd03dc9bbbbf1 | bd008507ccb324c289983317b91c79940b4b9780 | /cpp/av或bv号互转.cpp | 2c752fef3de0b2630aeaa413636801051d6c01b4 | [] | no_license | xiaoqiumc1234/xiaoqiumc1234.github.io | 6a4de5970ec9565f055b1234922170ee323b46a6 | b9880cce196e33ccb6880d4fc99eb4df5a610cff | refs/heads/master | 2022-11-06T15:36:07.299256 | 2020-06-20T13:02:10 | 2020-06-20T13:02:10 | 262,002,458 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,458 | cpp | av或bv号互转.cpp | #include <math.h>
#include <iostream>
#include <cstdlib>
#include <clocale>
using namespace std;
char table[] = "fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF";
int tr[58] = { 0 };
int s[] = { 11, 10, 3, 8, 4, 6 };
long long _xor = 177451812;
long long _add = 8728348608;
long long dec(string x)
{
for (int i = 0; i < 58; i++)
tr[(int)table[i]] = i;
long long r = 0;
for (int i = 0; i < 6; i++)
r += tr[x[s[i]]] * (long long)pow(58,i);
return (r - _add)^_xor;
}
string enc(long long x)
{
x = (x^_xor)+_add;
string r = "BV1 4 1 7 ";
for (int i = 0; i < 6; i++)
r[s[i]] = table[(int)(x / (long long)pow(58, i) % 58)];
return r;
}
string pretoupper(string x){
int len = x.length();
for(int i = 0; i < 2; i++){
if(islower(x[i])) x[i] = toupper(x[i]);
}
return x;
}
int main()
{
string str;
system("title av号与bv号互转") ;
cout << "请输入一个av号或bv号:";
cin >> str;
if(str.length() <= 2) goto inputerr;
str = pretoupper(str);
if(str[0] == 'A' && str[1] == 'V'){//av
string sub = str.substr(2);
long long num = _atoi64(sub.c_str());
cout << "对应的bv号为:" << enc(num) << endl;
}
else if(str[0] == 'B' && str[1] == 'V'){
cout << "对应的av号为:av" << dec(str) << endl;
} //bv
else
inputerr:
cout << "输入不合法!请输入av或bv开头的合法字符串!" << endl;//illegal input
cout << "请按[enter]键继续..." << endl;
getchar();
getchar();
}
|
0d4bce0a0ba97b1ec5fb8bb246761ba4b33ad247 | 758e58030f8493db12d3e2b346a5543f578c6132 | /soft/remote_ctrl/luamcuctrl/src/luamcuctrl.cpp | 7571dc5480bf99bc4c9587ce88785b4d60e41df9 | [] | no_license | notezen/IPM | 9e5191f48c0f006374aac7757723269ee70fc927 | 5f742b6fb055dbc1037a04f9257f7feb0c125351 | refs/heads/master | 2021-01-20T09:07:07.853253 | 2015-04-24T19:00:43 | 2015-04-24T19:00:43 | 27,236,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,228 | cpp | luamcuctrl.cpp |
#include "luamcuctrl.h"
#include "mcu_ctrl.h"
static const char META[] = "LUA_MCUCTRL_META";
static const char LIB_NAME[] = "luamcuctrl";
static int create( lua_State * L )
{
int cnt = lua_gettop( L );
McuCtrl * io = new McuCtrl();
McuCtrl * * p = reinterpret_cast< McuCtrl * * >( lua_newuserdata( L, sizeof( McuCtrl * ) ) );
*p = dynamic_cast<McuCtrl *>( io );
luaL_getmetatable( L, META );
lua_setmetatable( L, -2 );
return 1;
}
static int gc( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
if ( io )
delete io;
return 0;
}
static int self( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
lua_pushlightuserdata( L, reinterpret_cast< void * >(io) );
return 1;
}
static int open( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
bool res;
if ( ( lua_gettop( L ) > 1 ) && ( lua_type( L, 2 ) == LUA_TSTRING ) )
{
std::string arg = lua_tostring( L, 2 );
res = io->open( arg );
}
else
res = io->open();
lua_pushboolean( L, ( res ) ? 1 : 0 );
return 1;
}
static int close( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
io->close();
return 0;
}
static int isOpen( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
bool res = io->isOpen();
lua_pushboolean( L, ( res ) ? 1 : 0 );
return 1;
}
static int write( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
std::string stri = lua_tostring( L, 2 );
int res = io->write( stri );
lua_pushnumber( L, static_cast<lua_Number>( res ) );
return 1;
}
static int read( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
std::string stri;
int res = io->read( stri );
if ( res > 0 )
lua_pushstring( L, stri.c_str() );
else
lua_pushnil( L );
return 1;
}
static int setOutputs( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
int cnt = lua_gettop( L );
std::basic_string<unsigned long> args;
args.resize( cnt - 1 );
for ( int i=2; i<=cnt; i++ )
args[i-2] = static_cast<unsigned long>( lua_tonumber( L, i ) );
bool res = io->setOutputs( const_cast<unsigned long *>( args.data() ), static_cast<int>( args.size() ) );
lua_pushboolean( L, res ? 1 : 0 );
return 1;
}
static int inputs( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
int cnt;
if ( lua_gettop( L ) > 1 )
cnt = static_cast<int>( lua_tonumber( L, 2 ) );
else
cnt = 3;
std::basic_string<unsigned long> args;
args.resize( cnt );
bool res = io->inputs( const_cast<unsigned long *>( args.data() ), cnt );
if ( res )
{
for ( int i=0; i<cnt; i++ )
lua_pushnumber( L, static_cast<lua_Number>( args[i] ) );
return cnt;
}
return 0;
}
static int accInit( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
bool res = io->accInit();
lua_pushboolean( L, res ? 1 : 0 );
return 1;
}
static int accAcc( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
int x, y, z;
bool res = io->accAcc( x, y, z );
lua_pushboolean( L, res ? 1 : 0 );
if ( !res )
return 1;
lua_pushnumber( L, static_cast<lua_Number>( x ) );
lua_pushnumber( L, static_cast<lua_Number>( y ) );
lua_pushnumber( L, static_cast<lua_Number>( z ) );
return 4;
}
static int accMag( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
int x, y, z;
bool res = io->accMag( x, y, z );
lua_pushboolean( L, res ? 1 : 0 );
if ( !res )
return 1;
lua_pushnumber( L, static_cast<lua_Number>( x ) );
lua_pushnumber( L, static_cast<lua_Number>( y ) );
lua_pushnumber( L, static_cast<lua_Number>( z ) );
return 4;
}
static int accTemp( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
int t;
bool res = io->accTemp( t );
lua_pushboolean( L, res ? 1 : 0 );
if ( !res )
return 1;
lua_pushnumber( L, static_cast<lua_Number>( t ) );
return 2;
}
static int i2cSetAddr( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
int addr = static_cast<int>( lua_tonumber( L, 2 ) );
bool res = io->i2cSetAddr( addr );
lua_pushboolean( L, res ? 1 : 0 );
return 1;
}
static int i2cSetBuf( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
int start = static_cast<int>( lua_tonumber( L, 2 ) );
int cnt = lua_gettop( L );
for ( int i=3; i<=cnt; i++ )
{
unsigned char val = static_cast<unsigned char>( lua_tonumber( L, i ) );
bool res = io->i2cSetBuf( start, &val, 1 );
start++;
if ( !res )
{
lua_pushboolean( L, 0 );
return 1;
}
}
lua_pushboolean( L, 1 );
return 1;
}
static int i2cIo( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
int txCnt = static_cast<int>( lua_tonumber( L, 2 ) );
int rxCnt = static_cast<int>( lua_tonumber( L, 2 ) );
bool res = io->i2cIo( txCnt, rxCnt );
lua_pushboolean( L, res ? 1 : 0 );
return 1;
}
static int i2cStatus( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
int status;
bool res = io->i2cStatus( status );
lua_pushboolean( L, res ? 1 : 0 );
if ( res )
lua_pushnumber( L, static_cast<lua_Number>( status ) );
else
lua_pushnumber( L, static_cast<lua_Number>( -1 ) );
return 2;
}
static int i2cBuffer( lua_State * L )
{
McuCtrl * io = *reinterpret_cast<McuCtrl * *>( lua_touserdata( L, 1 ) );
int cnt = static_cast<int>( lua_tonumber( L, 2 ) );
std::basic_string<unsigned char> vals;
vals.resize( cnt );
bool res = io->i2cBuffer( cnt, const_cast<unsigned char *>( vals.data() ) );
if ( !res )
return 0;
for ( int i=0; i<cnt; i++ )
lua_pushnumber( L, static_cast<lua_Number>( vals[i] ) );
return cnt;
}
static const struct luaL_reg META_FUNCTIONS[] = {
{ "__gc", gc },
{ "pointer", self },
// Open/close routines
{ "open", open },
{ "close", close },
{ "isOpen", isOpen },
// The lowest possible level
{ "write", write },
{ "read", read },
{ "setOutputs", setOutputs },
{ "inputs", inputs },
{ "accInit", accInit },
{ "accAcc", accAcc },
{ "accMag", accMag },
{ "accTemp", accTemp },
{ "i2cSetAddr", i2cSetAddr },
{ "i2cSetBuf", i2cSetBuf },
{ "i2cIo", i2cIo },
{ "i2cStatus", i2cStatus },
{ "i2cBuffer", i2cBuffer },
{ NULL, NULL },
};
static void createMeta( lua_State * L )
{
int top = lua_gettop( L );
luaL_newmetatable( L, META ); // create new metatable for file handles
// file methods
lua_pushliteral( L, "__index" );
lua_pushvalue( L, -2 ); // push metatable
lua_rawset( L, -3 ); // metatable.__index = metatable
luaL_register( L, NULL, META_FUNCTIONS );
lua_settop( L, top );
}
static const struct luaL_reg FUNCTIONS[] = {
{ "create", create },
{ NULL, NULL },
};
static void registerFunctions( lua_State * L )
{
luaL_register( L, LIB_NAME, FUNCTIONS );
}
extern "C" int DECLSPEC luaopen_luamcuctrl( lua_State * L )
{
createMeta( L );
registerFunctions( L );
return 0;
}
|
69dcc27f5846b813574153721283a48ce4849531 | 91a5721215434f4e41e8fa1008f3baa68302d8dd | /Game/ConsoleQuestion5.h | 1dce8425c468c72ca225c6c36218019b772ba350 | [] | no_license | potion0522/WhiteRoom | 44bfb1f3cf2a66da696fd964fcf3f4b02a278bb8 | 6ddcdd2edbd0d5d5c47e0117ddc7c64d151be631 | refs/heads/master | 2020-04-15T01:56:13.770500 | 2019-04-04T12:44:28 | 2019-04-04T12:44:28 | 164,297,091 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 783 | h | ConsoleQuestion5.h | #pragma once
#include "ConsoleQuestion.h"
#include <vector>
/*********************************************
コンソールの6Pの問題(Question5)
*********************************************/
PTR( ConsoleQuestion5 );
PTR( Image );
class ConsoleQuestion5 : public ConsoleQuestion {
public:
ConsoleQuestion5( std::function< void( ) > callback, QuestionManagerPtr question_manager );
virtual ~ConsoleQuestion5( );
public:
void draw( int x, int y ) const;
private:
void actOnNone( );
void actOnPush( );
void actOnPushUp( );
void actOnAnswer( );
int getMouseOnNum( ) const;
private:
const int ERROR = 0xff;
private:
unsigned char _selecting_num;
std::vector< unsigned char > _select_nums;
ImagePtr _nums_image;
ImagePtr _arrow_image;
ImagePtr _frame_image;
};
|
1a5a75d9193bbbcc04e391a8e9662372bf17e6cd | 06ce3f409299c2ff53a2a4e63b842acfcec9c188 | /src/WireFormatTest.cc | 2a3e1a41548c77c60bae559f41dee938e8f0615d | [
"ISC"
] | permissive | SMatsushi/RAMCloud | 44ba99f87bbd48cdcc434ffad23f1d39c299a3e5 | e66752b8096bd57c19da7de6553f72fa2e5fc980 | refs/heads/master | 2021-01-22T07:31:51.916876 | 2016-09-15T13:57:04 | 2016-09-15T13:57:04 | 38,463,852 | 2 | 0 | null | 2016-09-15T13:57:04 | 2015-07-03T00:44:06 | C++ | UTF-8 | C++ | false | false | 3,152 | cc | WireFormatTest.cc | /* Copyright (c) 2010-2015 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright
* notice and this permission notice appear in all copies.lie
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
* CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <string.h>
#include "TestUtil.h"
#include "WireFormat.h"
namespace RAMCloud {
class WireFormatTest : public ::testing::Test {
public:
WireFormatTest() { }
private:
DISALLOW_COPY_AND_ASSIGN(WireFormatTest);
};
TEST_F(WireFormatTest, serviceTypeSymbol) {
EXPECT_STREQ("MASTER_SERVICE",
WireFormat::serviceTypeSymbol(WireFormat::MASTER_SERVICE));
EXPECT_STREQ("BACKUP_SERVICE",
WireFormat::serviceTypeSymbol(WireFormat::BACKUP_SERVICE));
EXPECT_STREQ("INVALID_SERVICE",
WireFormat::serviceTypeSymbol(WireFormat::INVALID_SERVICE));
// Test out-of-range values.
EXPECT_STREQ("INVALID_SERVICE",
WireFormat::serviceTypeSymbol(static_cast<WireFormat::ServiceType>
(WireFormat::INVALID_SERVICE + 1)));
}
TEST_F(WireFormatTest, getStatus) {
Buffer buffer;
EXPECT_EQ(STATUS_RESPONSE_FORMAT_ERROR, WireFormat::getStatus(&buffer));
WireFormat::ResponseCommon* header =
buffer.emplaceAppend<WireFormat::ResponseCommon>();
header->status = STATUS_WRONG_VERSION;
EXPECT_EQ(STATUS_WRONG_VERSION, WireFormat::getStatus(&buffer));
}
TEST_F(WireFormatTest, opcodeSymbol_integer) {
// Sample a few opcode values.
EXPECT_STREQ("PING", WireFormat::opcodeSymbol(WireFormat::PING));
EXPECT_STREQ("GET_TABLE_CONFIG", WireFormat::opcodeSymbol(
WireFormat::GET_TABLE_CONFIG));
EXPECT_STREQ("ILLEGAL_RPC_TYPE", WireFormat::opcodeSymbol(
WireFormat::ILLEGAL_RPC_TYPE));
// Test out-of-range values.
EXPECT_STREQ("unknown(81)", WireFormat::opcodeSymbol(
WireFormat::ILLEGAL_RPC_TYPE+1));
// Make sure the next-to-last value is defined (this will fail if
// someone adds a new opcode and doesn't update opcodeSymbol).
EXPECT_EQ(string(WireFormat::opcodeSymbol(
WireFormat::ILLEGAL_RPC_TYPE-1)).find("unknown"), string::npos);
}
TEST_F(WireFormatTest, opcodeSymbol_buffer) {
// First, try an empty buffer with a valid header.
Buffer b;
EXPECT_STREQ("null", WireFormat::opcodeSymbol(&b));
// Now try a buffer with a valid header.
WireFormat::RequestCommon* header =
b.emplaceAppend<WireFormat::RequestCommon>();
header->opcode = WireFormat::PING;
EXPECT_STREQ("PING", WireFormat::opcodeSymbol(&b));
}
} // namespace RAMCloud
|
729a040966eb9df0e5969185ed4e694a6eef5276 | 96914ec576bc16f4c85af101eb371739dcf41336 | /代码/stu_info.h | 8a0a0a360f6e28be58e7a8cc65d04d0f9b9210b5 | [] | no_license | yiwen9586/RehabCareRecord-DBMS | a59e823d112764c9d5201d15edda97d526272f98 | e3f9d9ddb688393b3a111e0e8c034041e90fb3f2 | refs/heads/master | 2020-03-31T07:13:02.522523 | 2019-02-12T23:45:21 | 2019-02-12T23:45:21 | 152,012,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | h | stu_info.h | #ifndef STU_INFO_H
#define STU_INFO_H
#include <QMainWindow>
#pragma execution_character_set("utf-8")
namespace Ui {
class stu_info;
}
class stu_info : public QMainWindow
{
Q_OBJECT
public:
explicit stu_info(QWidget *parent = 0);
~stu_info();
bool createConnection();
void closeEvent (QCloseEvent *event );
private slots:
void on_pushButton_clicked();
private:
Ui::stu_info *ui;
};
#endif // STU_INFO_H
|
4a3ac26a6b18184472af6f2ae98c215ebe0ce034 | 8c2585f92fedd6064d3fe2a4425f7da8697d74fc | /Animation/Camera.cpp | 7d9154aa1b8da7230acd02d328b0789d3424a007 | [] | no_license | djadeja/sdl_tutorials | 29c78e4c4073c049e50017557d0942cb95f7d80b | 7320542fd2cc2301f34e9b120bbe1483a1f0b46d | refs/heads/master | 2022-12-24T01:01:09.864355 | 2020-09-21T17:20:36 | 2020-09-21T17:20:36 | 289,952,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 711 | cpp | Camera.cpp | #include "Camera.h"
Camera Camera::cameraControl;
Camera::Camera() : targetX(NULL), targetY(NULL), x(0), y(0), targetMode(TargetMode::NORMAL) {
}
int Camera::getX() {
if (targetX != NULL) {
if (targetMode == TargetMode::CENTER) {
return *targetX - (WIN_WIDTH / 2);
}
return *targetX;
}
return x;
}
int Camera::getY() {
if(targetY != NULL) {
if(targetMode == TargetMode::CENTER) {
return *targetY - (WIN_HEIGHT / 2);
}
return *targetY;
}
return y;
}
void Camera::setPos(int x, int y) {
this->x = x;
this->y = y;
}
void Camera::setTarget(float *x, float *y) {
targetX = x;
targetY = y;
} |
b112d980802d89357d5092f3e83738fb0a9bb4f2 | 5f5d34bb43247d5e771c50e9a47882120a56351b | /include/util/util.hpp | 6eac3beb2ca1fe8672ab1508d6cd0e55956d53dc | [
"MIT"
] | permissive | qaskai/MLCMST | dc2693306114594999488c6c8d810edd07791ce6 | 0fa0529347eb6a44f45cf52dff477291c6fad433 | refs/heads/master | 2022-12-10T17:03:44.793041 | 2020-09-13T13:50:23 | 2020-09-13T13:50:23 | 248,966,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,043 | hpp | util.hpp | #pragma once
#include <algorithm>
#include <string>
#include <istream>
#include <vector>
#include <unordered_map>
namespace MLCMST::util {
std::string read_stream(std::istream& stream);
std::vector<int> firstN(unsigned int N);
long clockMilliseconds();
double mean(const std::vector<double> &v);
double stdev(const std::vector<double>& v);
template <typename T>
void erase(std::vector<T>& v, T val);
template <typename T>
std::vector<std::vector<T>> break_up(unsigned int N, std::vector<T> vec);
template <typename T>
std::unordered_map<T, int> valueToIndex(const std::vector<T>& v);
template <typename V>
std::unordered_map<V, std::vector<int> > groupIndexesByValue(const std::vector<V>& v);
template <typename T>
std::vector<T> concat(const std::vector<std::vector<T>>& vectors);
template <typename T>
void erase(std::vector<T>& v, T val)
{
v.erase(std::find(v.begin(), v.end(), val));
}
// template function implementation
template <typename T>
std::vector<std::vector<T>> break_up(unsigned int N, std::vector<T> vec)
{
std::vector<std::vector<T>> out;
unsigned int idx = 0;
while (idx < vec.size()) {
out.emplace_back();
for (unsigned int i = 0; i < N && idx < vec.size(); i++) {
out.back().push_back(vec[idx++]);
}
}
return out;
}
template <typename T>
std::unordered_map<T, int> valueToIndex(const std::vector<T>& v)
{
std::unordered_map<T, int> mapping;
for (int i=0; i<v.size(); i++) {
mapping[v[i]] = i;
}
return mapping;
}
template <typename V>
std::unordered_map<V, std::vector<int> > groupIndexesByValue(const std::vector<V>& v)
{
std::unordered_map<V, std::vector<int> > groups;
for (int i=0; i < v.size(); i++) {
groups[v[i]].push_back(i);
}
return groups;
}
template <typename T>
std::vector<T> concat(const std::vector<std::vector<T>>& vectors)
{
std::vector<T> result;
for (const std::vector<T>& v : vectors) {
result.insert(result.end(), v.begin(), v.end());
}
return result;
}
}
|
471360b8e88f9f0f1c9a46580049707ee0d91c51 | cc2a953fc0a4f42f796a89d90dfb2d7703ecdb09 | /Contest & Online Judge/wcipeg/ioi0722.cpp | bdc4488212c84cfe2893710738ab3fee30e83013 | [] | no_license | 210183/CP | 107af662a3ab759760b14c6ed31fb21dc7c274e4 | bd0b74aa2a90e12c5e5f45ac251de9d6cf69a7c6 | refs/heads/master | 2020-08-05T05:41:36.075888 | 2019-07-07T02:23:05 | 2019-07-07T02:23:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,206 | cpp | ioi0722.cpp | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <bitset>
#include <cassert>
#define makmu using
#define ndasmu namespace
#define gundulmu std
makmu ndasmu gundulmu;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> pii;
typedef pair<double,double> pdd;
typedef pair<string,string> pss;
typedef pair<int,double> pid;
typedef pair<int,LL> pil;
typedef pair<LL,LL> pll;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define SYNC ios_base::sync_with_stdio(false)
#define TIE cin.tie(0)
#define INF 1000000000
#define INFLL 4000000000000000000LL
#define EPS 1e-9
#define MOD 1000000007LL
#define DEBUG puts("DEBUG")
#ifdef _WIN32
#define getchar_unlocked getchar
#endif
#define g getchar_unlocked
int dx8[8]={-1,-1,0,1,1,1,0,-1},dx4[4]={-1,0,1,0};
int dy8[8]={0,-1,-1,-1,0,1,1,1},dy4[4]={0,-1,0,1};
inline void open(string name){
freopen((name+".in").c_str(),"r",stdin);
freopen((name+".out").c_str(),"w",stdout);
}
inline void close(){
fclose(stdin);
fclose(stdout);
}
inline int io(){
register char c;
while(1){
c=g();
if(c!='\n' && c!=' ') break;
}
int res=0,sign=1;
if(c=='-') sign=-1;
else res=c-'0';
while(1){
c=g();
if(c==' ' || c=='\n' || c==EOF) break;
res=(res<<3)+(res<<1)+c-'0';
}
return res*sign;
}
///////////////////////////////////////////////////
////// End of Template /////
/////////////////////////////////////////////////
const int MAXN = 100005;
const int MAX2 = 150000;
const int MAX3 = 225;
int arr[MAXN];
pii arr2[MAXN];
pair<pii,pii> arr3[MAXN];
int BIT2[MAX2+5];
int BIT3[MAX3+5][MAX3+5][MAX3+5];
int n,d,m,op;
void Update2(int x,int val){
for( ; x <= MAX2 ; x += x & -x)
BIT2[x] += val;
}
int Query2(int x){
int ret = 0;
for( ; x ; x -= x & -x)
ret += BIT2[x];
return ret;
}
void Update3(int x,int y,int z,int val){
for(int i = x ; i <= MAX3 ; i += i & -i)
for(int j = y ; j <= MAX3 ; j += j & -j)
for(int k = z ; k <= MAX3 ; k += k & -k)
BIT3[i][j][k] += val;
}
int Query3(int x,int y,int z){
int ret = 0;
for(int i = x ; i ; i -= i & -i)
for(int j = y ; j ; j -= j & -j)
for(int k = z ; k ; k -= k & -k)
ret += BIT3[i][j][k];
return ret;
}
void Answer1(){
for(int i = 0 ; i < n ; i++)
scanf("%d",&arr[i]);
sort(arr,arr + n);
LL ans = 0;
int it = 0;
for(int i = 0 ; i < n ; i++){
while(arr[i] - arr[it] > d) it++;
ans += (i - it);
}
printf("%lld\n",ans);
}
void Answer2(){
int a,b;
for(int i = 0 ; i < n ; i++){
scanf("%d %d",&a,&b);
arr2[i] = mp(a + b, a - b + 75000);
}
sort(arr2,arr2 + n);
LL ans = 0;
int it = 0;
for(int i = 0 ; i < n ; i++){
while(arr2[i].fi - arr2[it].fi > d){
Update2(arr2[it].se, -1);
it++;
}
b = min(MAX2, arr2[i].se + d);
a = max(1, arr2[i].se - d);
int tmp = Query2(b) - Query2(a - 1);
ans += tmp;
Update2(arr2[i].se,1);
}
printf("%lld\n",ans);
}
void Answer3(){
int a,b,c;
for(int i = 0 ; i < n ; i++){
scanf("%d %d %d",&a,&b,&c);
arr3[i].fi = mp(a + b + c, a + b - c + 75);
arr3[i].se = mp(a - b + c + 75, a - b - c + 150);
}
//DEBUG;
sort(arr3,arr3 + n);
LL ans = 0;
int it = 0;
for(int i = 0 ; i < n ; i++){
//printf("%d\n",i);
while(arr3[i].fi.fi - arr3[it].fi.fi > d){
Update3(arr3[it].fi.se, arr3[it].se.fi, arr3[it].se.se, -1);
it++;
}
int xb = min(MAX3,arr3[i].fi.se + d);
int xa = max(1,arr3[i].fi.se - d);
int yb = min(MAX3,arr3[i].se.fi + d);
int ya = max(1,arr3[i].se.fi - d);
int zb = min(MAX3,arr3[i].se.se + d);
int za = max(1,arr3[i].se.se - d);
int tmp = Query3(xb,yb,zb);
tmp -= (Query3(xa-1,yb,zb) + Query3(xb,ya-1,zb) + Query3(xb,yb,za-1));
tmp += (Query3(xa-1,ya-1,zb) + Query3(xa-1,yb,za-1) + Query3(xb,ya-1,za-1));
tmp -= Query3(xa-1,ya-1,za-1);
ans += tmp;
Update3(arr3[i].fi.se, arr3[i].se.fi, arr3[i].se.se, 1);
}
printf("%lld\n",ans);
}
int main(){
scanf("%d %d %d %d",&op,&n,&d,&m);
if(op == 1) Answer1();
else if(op == 2) Answer2();
else Answer3();
//puts("ganteng");
return 0;
}
|
9e1f34731d24817c842f66cc2ead0aa714f6a6bf | 33496338a35c4f76eadec13dc56c7831b1896113 | /Plugins/MadaraLibrary/Source/ThirdParty/madara/utility/ThreadSafeVector.h | 93740c277572b49880ec911fdddf6013208f4545 | [
"BSD-2-Clause"
] | permissive | jredmondson/GamsPlugins | 1ce0c2301cf84b6398ae1a2a6cdef9a4d0c1992c | d133f86c263997a55f11b3b3d3344faeee60d726 | refs/heads/master | 2021-07-08T23:40:48.423530 | 2020-10-01T05:31:26 | 2020-10-01T05:31:26 | 196,622,579 | 3 | 1 | BSD-2-Clause | 2020-03-17T04:23:21 | 2019-07-12T17:54:49 | C++ | UTF-8 | C++ | false | false | 3,084 | h | ThreadSafeVector.h | /* -*- C++ -*- */
#ifndef _MADARA_UTILITY_THREADSAFE_VECTOR_H_
#define _MADARA_UTILITY_THREADSAFE_VECTOR_H_
#include <vector>
#include "madara/LockType.h"
namespace madara
{
namespace utility
{
/**
* @class ThreadSafeVector
* @brief Manages a thread safe STL vector
*/
template<typename T>
class ThreadSafeVector
{
public:
/**
* Constructor
**/
ThreadSafeVector(void);
/**
* Copy constructor
* @param rhs the vector to copy
**/
ThreadSafeVector(const ThreadSafeVector& rhs);
/**
* Copy constructor
* @param rhs the vector to copy
**/
ThreadSafeVector(const std::vector<T>& rhs);
/**
* Destructor
**/
virtual ~ThreadSafeVector(void);
/**
* Assignment operator
* @param rhs a vector to copy
**/
void operator=(const ThreadSafeVector& rhs);
/**
* Assignment operator
* @param rhs a vector to copy
**/
void operator=(const std::vector<T>& rhs);
/**
* Accesses an element of the vector
* @param index index to access
* @return the element at the index
**/
inline T& operator[](size_t index);
/**
* Accesses an element of the vector
* @param index index to access
* @return the element at the index
**/
inline const T& operator[](size_t index) const;
/**
* Erases an element
* @param index index of element to erase
* @return the new size of the vector
**/
inline size_t erase(size_t index);
/**
* Pushes a value onto the end of the vector
* @param value a value to add to the end of the vector
**/
inline void push_back(T& value);
/**
* Returns the last element of the vector
* @return the last element of the vector
**/
inline const T& back(void) const;
/**
* Returns the last element of the vector
* @return the last element of the vector
**/
inline T& back(void);
/**
* Returns the last element before removing it
* @return the deleted element of the vector
**/
inline T pop_back(void);
/**
* Reserves a number of elements the vector
* @param new_size the new size
**/
inline void reserve(size_t new_size) const;
/**
* Resizes the vector
* @param new_size the new size
**/
inline void resize(size_t new_size) const;
/**
* returns the current size of the vector
* @return the current size
**/
inline size_t size(void) const;
/**
* returns the max size of the vector
* @return the max size
**/
inline size_t max_size(void) const;
/**
* Clears the vector
**/
inline void clear(void);
/**
* Locks the mutex
**/
inline void lock(void) const;
/**
* Unlocks the mutex
**/
inline void unlock(void) const;
/**
* Locks the mutex
**/
inline void acquire(void) const;
/**
* Unlocks the mutex
**/
inline void release(void) const;
private:
/// mutex for updating refcount_
mutable MADARA_LOCK_TYPE mutex_;
/// the encapsulated vector
std::vector<T> vector_;
};
}
}
#include "madara/utility/ThreadSafeVector.cpp"
#endif /* _MADARA_UTILITY_THREADSAFE_VECTOR_H_ */
|
c8fd791a2b4da82cfe2c0eefec5b32f2e8250def | 72852e07bb30adbee608275d6048b2121a5b9d82 | /algorithms/problem_1832/solution.cpp | ad92f301b53542d70f453f4725034d457b5b88be | [] | no_license | drlongle/leetcode | e172ae29ea63911ccc3afb815f6dbff041609939 | 8e61ddf06fb3a4fb4a4e3d8466f3367ee1f27e13 | refs/heads/master | 2023-01-08T16:26:12.370098 | 2023-01-03T09:08:24 | 2023-01-03T09:08:24 | 81,335,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,433 | cpp | solution.cpp | /*
1832. Check if the Sentence Is Pangram
Easy
A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string sentence containing only lowercase English letters,
return true if sentence is a pangram, or false otherwise.
Example 1:
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.
Example 2:
Input: sentence = "leetcode"
Output: false
Constraints:
1 <= sentence.length <= 1000
sentence consists of lowercase English letters.
*/
#include <algorithm>
#include <atomic>
#include <bitset>
#include <cassert>
#include <climits>
#include <cmath>
#include <condition_variable>
#include <functional>
#include <future>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <random>
#include <regex>
#include <set>
#include <sstream>
#include <stack>
#include <string_view>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "common/ListNode.h"
#include "common/TreeNode.h"
using namespace std;
class Solution {
public:
bool checkIfPangram(string sentence) {
unordered_set<char> cnt;
for (char c: sentence)
cnt.insert(c);
return cnt.size() == 26;
}
};
int main() {
Solution sol;
return 0;
}
|
907ebb8117d3ebaa1d48954149b3ba77e16d5307 | 56f431ac8061ddb4c45b32457b0f948d1029d98f | /MonoNative.Tests/mscorlib/System/Globalization/mscorlib_System_Globalization_StringInfo_Fixture.cpp | ec5ecfa4943557e995598e61a550468f9642c2d5 | [
"BSD-2-Clause"
] | permissive | brunolauze/MonoNative | 886d2a346a959d86e7e0ff68661be1b6767c5ce6 | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | refs/heads/master | 2016-09-15T17:32:26.626998 | 2016-03-01T17:55:27 | 2016-03-01T17:55:27 | 22,582,991 | 12 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,690 | cpp | mscorlib_System_Globalization_StringInfo_Fixture.cpp | // Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Globalization
// Name: StringInfo
// C++ Typed Name: mscorlib::System::Globalization::StringInfo
#include <gtest/gtest.h>
#include <mscorlib/System/Globalization/mscorlib_System_Globalization_StringInfo.h>
#include <mscorlib/System/mscorlib_System_Type.h>
#include <mscorlib/System/Globalization/mscorlib_System_Globalization_TextElementEnumerator.h>
namespace mscorlib
{
namespace System
{
namespace Globalization
{
//Constructors Tests
//StringInfo()
TEST(mscorlib_System_Globalization_StringInfo_Fixture,DefaultConstructor)
{
mscorlib::System::Globalization::StringInfo *value = new mscorlib::System::Globalization::StringInfo();
EXPECT_NE(NULL, value->GetNativeObject());
}
//StringInfo(mscorlib::System::String value)
TEST(mscorlib_System_Globalization_StringInfo_Fixture,Constructor_2)
{
mscorlib::System::Globalization::StringInfo *value = new mscorlib::System::Globalization::StringInfo();
EXPECT_NE(NULL, value->GetNativeObject());
}
//Public Methods Tests
// Method Equals
// Signature: mscorlib::System::Object value
TEST(mscorlib_System_Globalization_StringInfo_Fixture,Equals_Test)
{
}
// Method GetHashCode
// Signature:
TEST(mscorlib_System_Globalization_StringInfo_Fixture,GetHashCode_Test)
{
}
// Method SubstringByTextElements
// Signature: mscorlib::System::Int32 startingTextElement
TEST(mscorlib_System_Globalization_StringInfo_Fixture,SubstringByTextElements_1_Test)
{
}
// Method SubstringByTextElements
// Signature: mscorlib::System::Int32 startingTextElement, mscorlib::System::Int32 lengthInTextElements
TEST(mscorlib_System_Globalization_StringInfo_Fixture,SubstringByTextElements_2_Test)
{
}
//Public Static Methods Tests
// Method GetNextTextElement
// Signature: mscorlib::System::String str
TEST(mscorlib_System_Globalization_StringInfo_Fixture,GetNextTextElement_1_StaticTest)
{
}
// Method GetNextTextElement
// Signature: mscorlib::System::String str, mscorlib::System::Int32 index
TEST(mscorlib_System_Globalization_StringInfo_Fixture,GetNextTextElement_2_StaticTest)
{
}
// Method GetTextElementEnumerator
// Signature: mscorlib::System::String str
TEST(mscorlib_System_Globalization_StringInfo_Fixture,GetTextElementEnumerator_1_StaticTest)
{
}
// Method GetTextElementEnumerator
// Signature: mscorlib::System::String str, mscorlib::System::Int32 index
TEST(mscorlib_System_Globalization_StringInfo_Fixture,GetTextElementEnumerator_2_StaticTest)
{
}
// Method ParseCombiningCharacters
// Signature: mscorlib::System::String str
TEST(mscorlib_System_Globalization_StringInfo_Fixture,ParseCombiningCharacters_StaticTest)
{
}
//Public Properties Tests
// Property LengthInTextElements
// Return Type: mscorlib::System::Int32
// Property Get Method
TEST(mscorlib_System_Globalization_StringInfo_Fixture,get_LengthInTextElements_Test)
{
}
// Property String
// Return Type: mscorlib::System::String
// Property Get Method
TEST(mscorlib_System_Globalization_StringInfo_Fixture,get_String_Test)
{
}
// Property String
// Return Type: mscorlib::System::String
// Property Set Method
TEST(mscorlib_System_Globalization_StringInfo_Fixture,set_String_Test)
{
}
}
}
}
|
39de7e639ec90f1295c94cd9eee081c3747776c7 | aec41e793d61159771ec01295a511eb5d021f458 | /leetcode/328-odd-even-linked-list.cpp | 924fca409f80673fe9382fff85cbd8a454d32c0c | [] | no_license | FootprintGL/algo | ef043d89549685d72400275f7f4ce769028c48c8 | 1109c20921a6c573212ac9170c2aafeb5ca1da0f | refs/heads/master | 2023-04-09T02:59:00.510380 | 2021-04-16T12:59:03 | 2021-04-16T12:59:03 | 272,113,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,016 | cpp | 328-odd-even-linked-list.cpp |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
/* 链表节点数小于3个 */
if (head == nullptr || head->next == nullptr || head->next->next == nullptr)
return head;
ListNode *h1 = head, *h2 = head->next;
ListNode *p = h1, *q = h2;
bool flag = true;
/* 节点next指向下下个元素 */
while (q->next) {
p->next = q->next;
p = q;
q = p->next;
flag = !flag;
}
if (!flag) {
/* 奇数个节点 */
p->next = nullptr;
q->next = h2;
} else {
/* 偶数个节点 */
p->next = h2;
}
return head;
}
};
|
6d58cabd8ba4300769b9fda22e6bcb83d3291ab7 | 98e417b95479af6ff6d3f19aa77a719b7f05a1e1 | /Leetcode/数据结构/数组与矩阵/leetcode1_sumOfTwoNum.cpp | eb0566f7c5481541cbf836af8d57c6b40ec31097 | [] | no_license | peaceminusones/ZYL-Leetcode | d7bc67ae284d3ee3a2c195010da89bfadc754e61 | 05d0fbe9bc35ff887cd826bfb6c3bf8d56d87efb | refs/heads/master | 2023-02-01T15:54:43.380805 | 2020-12-17T03:09:16 | 2020-12-17T03:09:16 | 279,570,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 666 | cpp | leetcode1_sumOfTwoNum.cpp | #include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target)
{
vector<int> res;
unordered_map<int, int> map; // 存储nums[i]和target的差,和相应的位置
for (int i = 0; i < nums.size(); i++)
{
int diff = target - nums[i];
if (map.find(diff) == map.end()) // 如果nums[i]和target的差没有出现过
map[nums[i]] = i;
else // 出现过,则得到了结果
res = {map[diff], i};
}
return res;
}
};
int main()
{
return 0;
} |
612a2627fc370e1e743fef2232cace1065a49243 | 1095cfe2e29ddf4e4c5e12d713bd12f45c9b6f7d | /src/cpu/pred/simple_indirect.cc | f09cdeef55fe4e26f856b19a4ccef7243db36967 | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"MIT"
] | permissive | gem5/gem5 | 9ec715ae036c2e08807b5919f114e1d38d189bce | 48a40cf2f5182a82de360b7efa497d82e06b1631 | refs/heads/stable | 2023-09-03T15:56:25.819189 | 2023-08-31T05:53:03 | 2023-08-31T05:53:03 | 27,425,638 | 1,185 | 1,177 | BSD-3-Clause | 2023-09-14T08:29:31 | 2014-12-02T09:46:00 | C++ | UTF-8 | C++ | false | false | 8,174 | cc | simple_indirect.cc | /*
* Copyright (c) 2014 ARM Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cpu/pred/simple_indirect.hh"
#include "base/intmath.hh"
#include "debug/Indirect.hh"
namespace gem5
{
namespace branch_prediction
{
SimpleIndirectPredictor::SimpleIndirectPredictor(
const SimpleIndirectPredictorParams ¶ms)
: IndirectPredictor(params),
hashGHR(params.indirectHashGHR),
hashTargets(params.indirectHashTargets),
numSets(params.indirectSets),
numWays(params.indirectWays),
tagBits(params.indirectTagSize),
pathLength(params.indirectPathLength),
instShift(params.instShiftAmt),
ghrNumBits(params.indirectGHRBits),
ghrMask((1 << params.indirectGHRBits)-1)
{
if (!isPowerOf2(numSets)) {
panic("Indirect predictor requires power of 2 number of sets");
}
threadInfo.resize(params.numThreads);
targetCache.resize(numSets);
for (unsigned i = 0; i < numSets; i++) {
targetCache[i].resize(numWays);
}
fatal_if(ghrNumBits > (sizeof(ThreadInfo::ghr)*8), "ghr_size is too big");
}
void
SimpleIndirectPredictor::genIndirectInfo(ThreadID tid,
void* & indirect_history)
{
// record the GHR as it was before this prediction
// It will be used to recover the history in case this prediction is
// wrong or belongs to bad path
indirect_history = new unsigned(threadInfo[tid].ghr);
}
void
SimpleIndirectPredictor::updateDirectionInfo(
ThreadID tid, bool actually_taken)
{
threadInfo[tid].ghr <<= 1;
threadInfo[tid].ghr |= actually_taken;
threadInfo[tid].ghr &= ghrMask;
}
void
SimpleIndirectPredictor::changeDirectionPrediction(ThreadID tid,
void * indirect_history, bool actually_taken)
{
unsigned * previousGhr = static_cast<unsigned *>(indirect_history);
threadInfo[tid].ghr = ((*previousGhr) << 1) + actually_taken;
threadInfo[tid].ghr &= ghrMask;
}
bool
SimpleIndirectPredictor::lookup(Addr br_addr, PCStateBase& target,
ThreadID tid)
{
Addr set_index = getSetIndex(br_addr, threadInfo[tid].ghr, tid);
Addr tag = getTag(br_addr);
assert(set_index < numSets);
DPRINTF(Indirect, "Looking up %x (set:%d)\n", br_addr, set_index);
const auto &iset = targetCache[set_index];
for (auto way = iset.begin(); way != iset.end(); ++way) {
// tag may be 0 and match the default in way->tag, so we also have to
// check that way->target has been initialized.
if (way->tag == tag && way->target) {
DPRINTF(Indirect, "Hit %x (target:%s)\n", br_addr, *way->target);
set(target, *way->target);
return true;
}
}
DPRINTF(Indirect, "Miss %x\n", br_addr);
return false;
}
void
SimpleIndirectPredictor::recordIndirect(Addr br_addr, Addr tgt_addr,
InstSeqNum seq_num, ThreadID tid)
{
DPRINTF(Indirect, "Recording %x seq:%d\n", br_addr, seq_num);
HistoryEntry entry(br_addr, tgt_addr, seq_num);
threadInfo[tid].pathHist.push_back(entry);
}
void
SimpleIndirectPredictor::commit(InstSeqNum seq_num, ThreadID tid,
void * indirect_history)
{
DPRINTF(Indirect, "Committing seq:%d\n", seq_num);
ThreadInfo &t_info = threadInfo[tid];
// we do not need to recover the GHR, so delete the information
unsigned * previousGhr = static_cast<unsigned *>(indirect_history);
delete previousGhr;
if (t_info.pathHist.empty()) return;
if (t_info.headHistEntry < t_info.pathHist.size() &&
t_info.pathHist[t_info.headHistEntry].seqNum <= seq_num) {
if (t_info.headHistEntry >= pathLength) {
t_info.pathHist.pop_front();
} else {
++t_info.headHistEntry;
}
}
}
void
SimpleIndirectPredictor::squash(InstSeqNum seq_num, ThreadID tid)
{
DPRINTF(Indirect, "Squashing seq:%d\n", seq_num);
ThreadInfo &t_info = threadInfo[tid];
auto squash_itr = t_info.pathHist.begin();
while (squash_itr != t_info.pathHist.end()) {
if (squash_itr->seqNum > seq_num) {
break;
}
++squash_itr;
}
if (squash_itr != t_info.pathHist.end()) {
DPRINTF(Indirect, "Squashing series starting with sn:%d\n",
squash_itr->seqNum);
}
t_info.pathHist.erase(squash_itr, t_info.pathHist.end());
}
void
SimpleIndirectPredictor::deleteIndirectInfo(ThreadID tid,
void * indirect_history)
{
unsigned * previousGhr = static_cast<unsigned *>(indirect_history);
threadInfo[tid].ghr = *previousGhr;
delete previousGhr;
}
void
SimpleIndirectPredictor::recordTarget(
InstSeqNum seq_num, void * indirect_history, const PCStateBase& target,
ThreadID tid)
{
ThreadInfo &t_info = threadInfo[tid];
unsigned * ghr = static_cast<unsigned *>(indirect_history);
// Should have just squashed so this branch should be the oldest
auto hist_entry = *(t_info.pathHist.rbegin());
// Temporarily pop it off the history so we can calculate the set
t_info.pathHist.pop_back();
Addr set_index = getSetIndex(hist_entry.pcAddr, *ghr, tid);
Addr tag = getTag(hist_entry.pcAddr);
hist_entry.targetAddr = target.instAddr();
t_info.pathHist.push_back(hist_entry);
assert(set_index < numSets);
auto &iset = targetCache[set_index];
for (auto way = iset.begin(); way != iset.end(); ++way) {
if (way->tag == tag) {
DPRINTF(Indirect, "Updating Target (seq: %d br:%x set:%d target:"
"%s)\n", seq_num, hist_entry.pcAddr, set_index, target);
set(way->target, target);
return;
}
}
DPRINTF(Indirect, "Allocating Target (seq: %d br:%x set:%d target:%s)\n",
seq_num, hist_entry.pcAddr, set_index, target);
// Did not find entry, random replacement
auto &way = iset[rand() % numWays];
way.tag = tag;
set(way.target, target);
}
inline Addr
SimpleIndirectPredictor::getSetIndex(Addr br_addr, unsigned ghr, ThreadID tid)
{
ThreadInfo &t_info = threadInfo[tid];
Addr hash = br_addr >> instShift;
if (hashGHR) {
hash ^= ghr;
}
if (hashTargets) {
unsigned hash_shift = floorLog2(numSets) / pathLength;
for (int i = t_info.pathHist.size()-1, p = 0;
i >= 0 && p < pathLength; i--, p++) {
hash ^= (t_info.pathHist[i].targetAddr >>
(instShift + p*hash_shift));
}
}
return hash & (numSets-1);
}
inline Addr
SimpleIndirectPredictor::getTag(Addr br_addr)
{
return (br_addr >> instShift) & ((0x1<<tagBits)-1);
}
} // namespace branch_prediction
} // namespace gem5
|
719d71f1756f9f3d39c2c5145d8230823228c48c | f8fb1bb814f2a2313f04f2f48129deb7d744803c | /third_party/fmt-9.1.0/test/core-test.cc | c76dc161775d3e7d69a07528c541fa1a09272fdc | [
"Python-2.0",
"LicenseRef-scancode-free-unknown",
"MIT",
"LicenseRef-scancode-object-form-exception-to-mit",
"BSD-2-Clause"
] | permissive | Project-OSRM/osrm-backend | 403583d537b770139e9fa0faa114224af7060ff5 | d234c7246c1d5334cbd0f86038ad7008aea7bc11 | refs/heads/master | 2023-08-28T15:43:54.442947 | 2023-08-20T09:17:30 | 2023-08-20T09:17:30 | 2,436,255 | 5,359 | 3,526 | BSD-2-Clause | 2023-09-13T20:01:37 | 2011-09-22T10:05:08 | C++ | UTF-8 | C++ | false | false | 32,179 | cc | core-test.cc | // Formatting library for C++ - core tests
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
// clang-format off
#include "test-assert.h"
// clang-format on
#define I 42 // simulate https://en.cppreference.com/w/c/numeric/complex/I
#include "fmt/core.h"
#undef I
#include <algorithm> // std::copy_n
#include <climits> // INT_MAX
#include <cstring> // std::strlen
#include <functional> // std::equal_to
#include <iterator> // std::back_insert_iterator
#include <limits> // std::numeric_limits
#include <string> // std::string
#include <type_traits> // std::is_same
#include "gmock/gmock.h"
using fmt::string_view;
using fmt::detail::buffer;
using testing::_;
using testing::Invoke;
using testing::Return;
#ifdef FMT_FORMAT_H_
# error core-test includes format.h
#endif
TEST(string_view_test, value_type) {
static_assert(std::is_same<string_view::value_type, char>::value, "");
}
TEST(string_view_test, ctor) {
EXPECT_STREQ("abc", fmt::string_view("abc").data());
EXPECT_EQ(3u, fmt::string_view("abc").size());
EXPECT_STREQ("defg", fmt::string_view(std::string("defg")).data());
EXPECT_EQ(4u, fmt::string_view(std::string("defg")).size());
}
TEST(string_view_test, length) {
// Test that string_view::size() returns string length, not buffer size.
char str[100] = "some string";
EXPECT_EQ(std::strlen(str), string_view(str).size());
EXPECT_LT(std::strlen(str), sizeof(str));
}
// Check string_view's comparison operator.
template <template <typename> class Op> void check_op() {
const char* inputs[] = {"foo", "fop", "fo"};
size_t num_inputs = sizeof(inputs) / sizeof(*inputs);
for (size_t i = 0; i < num_inputs; ++i) {
for (size_t j = 0; j < num_inputs; ++j) {
string_view lhs(inputs[i]), rhs(inputs[j]);
EXPECT_EQ(Op<int>()(lhs.compare(rhs), 0), Op<string_view>()(lhs, rhs));
}
}
}
TEST(string_view_test, compare) {
EXPECT_EQ(string_view("foo").compare(string_view("foo")), 0);
EXPECT_GT(string_view("fop").compare(string_view("foo")), 0);
EXPECT_LT(string_view("foo").compare(string_view("fop")), 0);
EXPECT_GT(string_view("foo").compare(string_view("fo")), 0);
EXPECT_LT(string_view("fo").compare(string_view("foo")), 0);
check_op<std::equal_to>();
check_op<std::not_equal_to>();
check_op<std::less>();
check_op<std::less_equal>();
check_op<std::greater>();
check_op<std::greater_equal>();
}
namespace test_ns {
template <typename Char> class test_string {
private:
std::basic_string<Char> s_;
public:
test_string(const Char* s) : s_(s) {}
const Char* data() const { return s_.data(); }
size_t length() const { return s_.size(); }
operator const Char*() const { return s_.c_str(); }
};
template <typename Char>
fmt::basic_string_view<Char> to_string_view(const test_string<Char>& s) {
return {s.data(), s.length()};
}
} // namespace test_ns
TEST(core_test, is_output_iterator) {
EXPECT_TRUE((fmt::detail::is_output_iterator<char*, char>::value));
EXPECT_FALSE((fmt::detail::is_output_iterator<const char*, char>::value));
EXPECT_FALSE((fmt::detail::is_output_iterator<std::string, char>::value));
EXPECT_TRUE(
(fmt::detail::is_output_iterator<std::back_insert_iterator<std::string>,
char>::value));
EXPECT_TRUE(
(fmt::detail::is_output_iterator<std::string::iterator, char>::value));
EXPECT_FALSE((fmt::detail::is_output_iterator<std::string::const_iterator,
char>::value));
}
TEST(core_test, buffer_appender) {
// back_insert_iterator is not default-constructible before C++20, so
// buffer_appender can only be default-constructible when back_insert_iterator
// is.
static_assert(
std::is_default_constructible<
std::back_insert_iterator<fmt::detail::buffer<char>>>::value ==
std::is_default_constructible<
fmt::detail::buffer_appender<char>>::value,
"");
#ifdef __cpp_lib_ranges
static_assert(std::output_iterator<fmt::detail::buffer_appender<char>, char>);
#endif
}
#if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 470
TEST(buffer_test, noncopyable) {
EXPECT_FALSE(std::is_copy_constructible<buffer<char>>::value);
# if !FMT_MSC_VERSION
// std::is_copy_assignable is broken in MSVC2013.
EXPECT_FALSE(std::is_copy_assignable<buffer<char>>::value);
# endif
}
TEST(buffer_test, nonmoveable) {
EXPECT_FALSE(std::is_move_constructible<buffer<char>>::value);
# if !FMT_MSC_VERSION
// std::is_move_assignable is broken in MSVC2013.
EXPECT_FALSE(std::is_move_assignable<buffer<char>>::value);
# endif
}
#endif
TEST(buffer_test, indestructible) {
static_assert(!std::is_destructible<fmt::detail::buffer<int>>(),
"buffer's destructor is protected");
}
template <typename T> struct mock_buffer final : buffer<T> {
MOCK_METHOD1(do_grow, size_t(size_t capacity));
void grow(size_t capacity) override {
this->set(this->data(), do_grow(capacity));
}
mock_buffer(T* data = nullptr, size_t buf_capacity = 0) {
this->set(data, buf_capacity);
ON_CALL(*this, do_grow(_)).WillByDefault(Invoke([](size_t capacity) {
return capacity;
}));
}
};
TEST(buffer_test, ctor) {
{
mock_buffer<int> buffer;
EXPECT_EQ(nullptr, buffer.data());
EXPECT_EQ(static_cast<size_t>(0), buffer.size());
EXPECT_EQ(static_cast<size_t>(0), buffer.capacity());
}
{
int dummy;
mock_buffer<int> buffer(&dummy);
EXPECT_EQ(&dummy, &buffer[0]);
EXPECT_EQ(static_cast<size_t>(0), buffer.size());
EXPECT_EQ(static_cast<size_t>(0), buffer.capacity());
}
{
int dummy;
size_t capacity = std::numeric_limits<size_t>::max();
mock_buffer<int> buffer(&dummy, capacity);
EXPECT_EQ(&dummy, &buffer[0]);
EXPECT_EQ(static_cast<size_t>(0), buffer.size());
EXPECT_EQ(capacity, buffer.capacity());
}
}
TEST(buffer_test, access) {
char data[10];
mock_buffer<char> buffer(data, sizeof(data));
buffer[0] = 11;
EXPECT_EQ(11, buffer[0]);
buffer[3] = 42;
EXPECT_EQ(42, *(&buffer[0] + 3));
const fmt::detail::buffer<char>& const_buffer = buffer;
EXPECT_EQ(42, const_buffer[3]);
}
TEST(buffer_test, try_resize) {
char data[123];
mock_buffer<char> buffer(data, sizeof(data));
buffer[10] = 42;
EXPECT_EQ(42, buffer[10]);
buffer.try_resize(20);
EXPECT_EQ(20u, buffer.size());
EXPECT_EQ(123u, buffer.capacity());
EXPECT_EQ(42, buffer[10]);
buffer.try_resize(5);
EXPECT_EQ(5u, buffer.size());
EXPECT_EQ(123u, buffer.capacity());
EXPECT_EQ(42, buffer[10]);
// Check if try_resize calls grow.
EXPECT_CALL(buffer, do_grow(124));
buffer.try_resize(124);
EXPECT_CALL(buffer, do_grow(200));
buffer.try_resize(200);
}
TEST(buffer_test, try_resize_partial) {
char data[10];
mock_buffer<char> buffer(data, sizeof(data));
EXPECT_CALL(buffer, do_grow(20)).WillOnce(Return(15));
buffer.try_resize(20);
EXPECT_EQ(buffer.capacity(), 15);
EXPECT_EQ(buffer.size(), 15);
}
TEST(buffer_test, clear) {
mock_buffer<char> buffer;
EXPECT_CALL(buffer, do_grow(20));
buffer.try_resize(20);
buffer.try_resize(0);
EXPECT_EQ(static_cast<size_t>(0), buffer.size());
EXPECT_EQ(20u, buffer.capacity());
}
TEST(buffer_test, append) {
char data[15];
mock_buffer<char> buffer(data, 10);
auto test = "test";
buffer.append(test, test + 5);
EXPECT_STREQ(test, &buffer[0]);
EXPECT_EQ(5u, buffer.size());
buffer.try_resize(10);
EXPECT_CALL(buffer, do_grow(12));
buffer.append(test, test + 2);
EXPECT_EQ('t', buffer[10]);
EXPECT_EQ('e', buffer[11]);
EXPECT_EQ(12u, buffer.size());
}
TEST(buffer_test, append_partial) {
char data[10];
mock_buffer<char> buffer(data, sizeof(data));
testing::InSequence seq;
EXPECT_CALL(buffer, do_grow(15)).WillOnce(Return(10));
EXPECT_CALL(buffer, do_grow(15)).WillOnce(Invoke([&buffer](size_t) {
EXPECT_EQ(fmt::string_view(buffer.data(), buffer.size()), "0123456789");
buffer.clear();
return 10;
}));
auto test = "0123456789abcde";
buffer.append(test, test + 15);
}
TEST(buffer_test, append_allocates_enough_storage) {
char data[19];
mock_buffer<char> buffer(data, 10);
auto test = "abcdefgh";
buffer.try_resize(10);
EXPECT_CALL(buffer, do_grow(19));
buffer.append(test, test + 9);
}
struct custom_context {
using char_type = char;
using parse_context_type = fmt::format_parse_context;
bool called = false;
template <typename T> struct formatter_type {
auto parse(fmt::format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
const char* format(const T&, custom_context& ctx) {
ctx.called = true;
return nullptr;
}
};
void advance_to(const char*) {}
};
struct test_struct {};
FMT_BEGIN_NAMESPACE
template <typename Char> struct formatter<test_struct, Char> {
auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
auto format(test_struct, format_context& ctx) -> decltype(ctx.out()) {
auto test = string_view("test");
return std::copy_n(test.data(), test.size(), ctx.out());
}
};
FMT_END_NAMESPACE
TEST(arg_test, format_args) {
auto args = fmt::format_args();
EXPECT_FALSE(args.get(1));
}
TEST(arg_test, make_value_with_custom_context) {
auto t = test_struct();
fmt::detail::value<custom_context> arg(
fmt::detail::arg_mapper<custom_context>().map(t));
auto ctx = custom_context();
auto parse_ctx = fmt::format_parse_context("");
arg.custom.format(&t, parse_ctx, ctx);
EXPECT_TRUE(ctx.called);
}
// Use a unique result type to make sure that there are no undesirable
// conversions.
struct test_result {};
template <typename T> struct mock_visitor {
template <typename U> struct result { using type = test_result; };
mock_visitor() {
ON_CALL(*this, visit(_)).WillByDefault(Return(test_result()));
}
MOCK_METHOD1_T(visit, test_result(T value));
MOCK_METHOD0_T(unexpected, void());
test_result operator()(T value) { return visit(value); }
template <typename U> test_result operator()(U) {
unexpected();
return test_result();
}
};
template <typename T> struct visit_type { using type = T; };
#define VISIT_TYPE(type_, visit_type_) \
template <> struct visit_type<type_> { using type = visit_type_; }
VISIT_TYPE(signed char, int);
VISIT_TYPE(unsigned char, unsigned);
VISIT_TYPE(short, int);
VISIT_TYPE(unsigned short, unsigned);
#if LONG_MAX == INT_MAX
VISIT_TYPE(long, int);
VISIT_TYPE(unsigned long, unsigned);
#else
VISIT_TYPE(long, long long);
VISIT_TYPE(unsigned long, unsigned long long);
#endif
#define CHECK_ARG(Char, expected, value) \
{ \
testing::StrictMock<mock_visitor<decltype(expected)>> visitor; \
EXPECT_CALL(visitor, visit(expected)); \
using iterator = std::back_insert_iterator<buffer<Char>>; \
fmt::visit_format_arg( \
visitor, \
fmt::detail::make_arg<fmt::basic_format_context<iterator, Char>>( \
value)); \
}
#define CHECK_ARG_SIMPLE(value) \
{ \
using value_type = decltype(value); \
typename visit_type<value_type>::type expected = value; \
CHECK_ARG(char, expected, value) \
CHECK_ARG(wchar_t, expected, value) \
}
template <typename T> class numeric_arg_test : public testing::Test {};
using test_types =
testing::Types<bool, signed char, unsigned char, short, unsigned short, int,
unsigned, long, unsigned long, long long, unsigned long long,
float, double, long double>;
TYPED_TEST_SUITE(numeric_arg_test, test_types);
template <typename T, fmt::enable_if_t<std::is_integral<T>::value, int> = 0>
T test_value() {
return static_cast<T>(42);
}
template <typename T,
fmt::enable_if_t<std::is_floating_point<T>::value, int> = 0>
T test_value() {
return static_cast<T>(4.2);
}
TYPED_TEST(numeric_arg_test, make_and_visit) {
CHECK_ARG_SIMPLE(test_value<TypeParam>());
CHECK_ARG_SIMPLE(std::numeric_limits<TypeParam>::min());
CHECK_ARG_SIMPLE(std::numeric_limits<TypeParam>::max());
}
TEST(arg_test, char_arg) { CHECK_ARG(char, 'a', 'a'); }
TEST(arg_test, string_arg) {
char str_data[] = "test";
char* str = str_data;
const char* cstr = str;
CHECK_ARG(char, cstr, str);
auto sv = fmt::string_view(str);
CHECK_ARG(char, sv, std::string(str));
}
TEST(arg_test, wstring_arg) {
wchar_t str_data[] = L"test";
wchar_t* str = str_data;
const wchar_t* cstr = str;
auto sv = fmt::basic_string_view<wchar_t>(str);
CHECK_ARG(wchar_t, cstr, str);
CHECK_ARG(wchar_t, cstr, cstr);
CHECK_ARG(wchar_t, sv, std::wstring(str));
CHECK_ARG(wchar_t, sv, fmt::basic_string_view<wchar_t>(str));
}
TEST(arg_test, pointer_arg) {
void* p = nullptr;
const void* cp = nullptr;
CHECK_ARG(char, cp, p);
CHECK_ARG(wchar_t, cp, p);
CHECK_ARG_SIMPLE(cp);
}
struct check_custom {
test_result operator()(
fmt::basic_format_arg<fmt::format_context>::handle h) const {
struct test_buffer final : fmt::detail::buffer<char> {
char data[10];
test_buffer() : fmt::detail::buffer<char>(data, 0, 10) {}
void grow(size_t) override {}
} buffer;
auto parse_ctx = fmt::format_parse_context("");
auto ctx = fmt::format_context(fmt::detail::buffer_appender<char>(buffer),
fmt::format_args());
h.format(parse_ctx, ctx);
EXPECT_EQ("test", std::string(buffer.data, buffer.size()));
return test_result();
}
};
TEST(arg_test, custom_arg) {
auto test = test_struct();
using visitor =
mock_visitor<fmt::basic_format_arg<fmt::format_context>::handle>;
testing::StrictMock<visitor> v;
EXPECT_CALL(v, visit(_)).WillOnce(Invoke(check_custom()));
fmt::visit_format_arg(v, fmt::detail::make_arg<fmt::format_context>(test));
}
TEST(arg_test, visit_invalid_arg) {
testing::StrictMock<mock_visitor<fmt::monostate>> visitor;
EXPECT_CALL(visitor, visit(_));
auto arg = fmt::basic_format_arg<fmt::format_context>();
fmt::visit_format_arg(visitor, arg);
}
#if FMT_USE_CONSTEXPR
enum class arg_id_result { none, empty, index, name, error };
struct test_arg_id_handler {
arg_id_result res = arg_id_result::none;
int index = 0;
string_view name;
constexpr void operator()() { res = arg_id_result::empty; }
constexpr void operator()(int i) {
res = arg_id_result::index;
index = i;
}
constexpr void operator()(string_view n) {
res = arg_id_result::name;
name = n;
}
constexpr void on_error(const char*) { res = arg_id_result::error; }
};
template <size_t N>
constexpr test_arg_id_handler parse_arg_id(const char (&s)[N]) {
test_arg_id_handler h;
fmt::detail::parse_arg_id(s, s + N, h);
return h;
}
TEST(format_test, constexpr_parse_arg_id) {
static_assert(parse_arg_id(":").res == arg_id_result::empty, "");
static_assert(parse_arg_id("}").res == arg_id_result::empty, "");
static_assert(parse_arg_id("42:").res == arg_id_result::index, "");
static_assert(parse_arg_id("42:").index == 42, "");
static_assert(parse_arg_id("foo:").res == arg_id_result::name, "");
static_assert(parse_arg_id("foo:").name.size() == 3, "");
static_assert(parse_arg_id("!").res == arg_id_result::error, "");
}
struct test_format_specs_handler {
enum result { none, hash, zero, loc, error };
result res = none;
fmt::align_t alignment = fmt::align::none;
fmt::sign_t sign = fmt::sign::none;
char fill = 0;
int width = 0;
fmt::detail::arg_ref<char> width_ref;
int precision = 0;
fmt::detail::arg_ref<char> precision_ref;
fmt::presentation_type type = fmt::presentation_type::none;
// Workaround for MSVC2017 bug that results in "expression did not evaluate
// to a constant" with compiler-generated copy ctor.
constexpr test_format_specs_handler() {}
constexpr test_format_specs_handler(const test_format_specs_handler& other) =
default;
constexpr void on_align(fmt::align_t a) { alignment = a; }
constexpr void on_fill(fmt::string_view f) { fill = f[0]; }
constexpr void on_sign(fmt::sign_t s) { sign = s; }
constexpr void on_hash() { res = hash; }
constexpr void on_zero() { res = zero; }
constexpr void on_localized() { res = loc; }
constexpr void on_width(int w) { width = w; }
constexpr void on_dynamic_width(fmt::detail::auto_id) {}
constexpr void on_dynamic_width(int index) { width_ref = index; }
constexpr void on_dynamic_width(string_view) {}
constexpr void on_precision(int p) { precision = p; }
constexpr void on_dynamic_precision(fmt::detail::auto_id) {}
constexpr void on_dynamic_precision(int index) { precision_ref = index; }
constexpr void on_dynamic_precision(string_view) {}
constexpr void end_precision() {}
constexpr void on_type(fmt::presentation_type t) { type = t; }
constexpr void on_error(const char*) { res = error; }
};
template <size_t N>
constexpr test_format_specs_handler parse_test_specs(const char (&s)[N]) {
auto h = test_format_specs_handler();
fmt::detail::parse_format_specs(s, s + N - 1, h);
return h;
}
TEST(core_test, constexpr_parse_format_specs) {
using handler = test_format_specs_handler;
static_assert(parse_test_specs("<").alignment == fmt::align::left, "");
static_assert(parse_test_specs("*^").fill == '*', "");
static_assert(parse_test_specs("+").sign == fmt::sign::plus, "");
static_assert(parse_test_specs("-").sign == fmt::sign::minus, "");
static_assert(parse_test_specs(" ").sign == fmt::sign::space, "");
static_assert(parse_test_specs("#").res == handler::hash, "");
static_assert(parse_test_specs("0").res == handler::zero, "");
static_assert(parse_test_specs("L").res == handler::loc, "");
static_assert(parse_test_specs("42").width == 42, "");
static_assert(parse_test_specs("{42}").width_ref.val.index == 42, "");
static_assert(parse_test_specs(".42").precision == 42, "");
static_assert(parse_test_specs(".{42}").precision_ref.val.index == 42, "");
static_assert(parse_test_specs("d").type == fmt::presentation_type::dec, "");
static_assert(parse_test_specs("{<").res == handler::error, "");
}
struct test_parse_context {
using char_type = char;
constexpr int next_arg_id() { return 11; }
template <typename Id> FMT_CONSTEXPR void check_arg_id(Id) {}
FMT_CONSTEXPR void check_dynamic_spec(int) {}
constexpr const char* begin() { return nullptr; }
constexpr const char* end() { return nullptr; }
void on_error(const char*) {}
};
template <size_t N>
constexpr fmt::detail::dynamic_format_specs<char> parse_dynamic_specs(
const char (&s)[N]) {
auto specs = fmt::detail::dynamic_format_specs<char>();
auto ctx = test_parse_context();
auto h = fmt::detail::dynamic_specs_handler<test_parse_context>(specs, ctx);
parse_format_specs(s, s + N - 1, h);
return specs;
}
TEST(format_test, constexpr_dynamic_specs_handler) {
static_assert(parse_dynamic_specs("<").align == fmt::align::left, "");
static_assert(parse_dynamic_specs("*^").fill[0] == '*', "");
static_assert(parse_dynamic_specs("+").sign == fmt::sign::plus, "");
static_assert(parse_dynamic_specs("-").sign == fmt::sign::minus, "");
static_assert(parse_dynamic_specs(" ").sign == fmt::sign::space, "");
static_assert(parse_dynamic_specs("#").alt, "");
static_assert(parse_dynamic_specs("0").align == fmt::align::numeric, "");
static_assert(parse_dynamic_specs("42").width == 42, "");
static_assert(parse_dynamic_specs("{}").width_ref.val.index == 11, "");
static_assert(parse_dynamic_specs("{42}").width_ref.val.index == 42, "");
static_assert(parse_dynamic_specs(".42").precision == 42, "");
static_assert(parse_dynamic_specs(".{}").precision_ref.val.index == 11, "");
static_assert(parse_dynamic_specs(".{42}").precision_ref.val.index == 42, "");
static_assert(parse_dynamic_specs("d").type == fmt::presentation_type::dec,
"");
}
template <size_t N>
constexpr test_format_specs_handler check_specs(const char (&s)[N]) {
fmt::detail::specs_checker<test_format_specs_handler> checker(
test_format_specs_handler(), fmt::detail::type::double_type);
parse_format_specs(s, s + N - 1, checker);
return checker;
}
TEST(format_test, constexpr_specs_checker) {
using handler = test_format_specs_handler;
static_assert(check_specs("<").alignment == fmt::align::left, "");
static_assert(check_specs("*^").fill == '*', "");
static_assert(check_specs("+").sign == fmt::sign::plus, "");
static_assert(check_specs("-").sign == fmt::sign::minus, "");
static_assert(check_specs(" ").sign == fmt::sign::space, "");
static_assert(check_specs("#").res == handler::hash, "");
static_assert(check_specs("0").res == handler::zero, "");
static_assert(check_specs("42").width == 42, "");
static_assert(check_specs("{42}").width_ref.val.index == 42, "");
static_assert(check_specs(".42").precision == 42, "");
static_assert(check_specs(".{42}").precision_ref.val.index == 42, "");
static_assert(check_specs("d").type == fmt::presentation_type::dec, "");
static_assert(check_specs("{<").res == handler::error, "");
}
struct test_format_string_handler {
constexpr void on_text(const char*, const char*) {}
constexpr int on_arg_id() { return 0; }
template <typename T> constexpr int on_arg_id(T) { return 0; }
constexpr void on_replacement_field(int, const char*) {}
constexpr const char* on_format_specs(int, const char* begin, const char*) {
return begin;
}
constexpr void on_error(const char*) { error = true; }
bool error = false;
};
template <size_t N> constexpr bool parse_string(const char (&s)[N]) {
auto h = test_format_string_handler();
fmt::detail::parse_format_string<true>(fmt::string_view(s, N - 1), h);
return !h.error;
}
TEST(format_test, constexpr_parse_format_string) {
static_assert(parse_string("foo"), "");
static_assert(!parse_string("}"), "");
static_assert(parse_string("{}"), "");
static_assert(parse_string("{42}"), "");
static_assert(parse_string("{foo}"), "");
static_assert(parse_string("{:}"), "");
}
#endif // FMT_USE_CONSTEXPR
struct enabled_formatter {};
struct enabled_ptr_formatter {};
struct disabled_formatter {};
struct disabled_formatter_convertible {
operator int() const { return 42; }
};
FMT_BEGIN_NAMESPACE
template <> struct formatter<enabled_formatter> {
auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
auto format(enabled_formatter, format_context& ctx) -> decltype(ctx.out()) {
return ctx.out();
}
};
template <> struct formatter<enabled_ptr_formatter*> {
auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
auto format(enabled_ptr_formatter*, format_context& ctx)
-> decltype(ctx.out()) {
return ctx.out();
}
};
FMT_END_NAMESPACE
TEST(core_test, has_formatter) {
using fmt::has_formatter;
using context = fmt::format_context;
static_assert(has_formatter<enabled_formatter, context>::value, "");
static_assert(!has_formatter<disabled_formatter, context>::value, "");
static_assert(!has_formatter<disabled_formatter_convertible, context>::value,
"");
}
struct const_formattable {};
struct nonconst_formattable {};
FMT_BEGIN_NAMESPACE
template <> struct formatter<const_formattable> {
auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
auto format(const const_formattable&, format_context& ctx)
-> decltype(ctx.out()) {
auto test = string_view("test");
return std::copy_n(test.data(), test.size(), ctx.out());
}
};
template <> struct formatter<nonconst_formattable> {
auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
auto format(nonconst_formattable&, format_context& ctx)
-> decltype(ctx.out()) {
auto test = string_view("test");
return std::copy_n(test.data(), test.size(), ctx.out());
}
};
FMT_END_NAMESPACE
struct convertible_to_pointer {
operator const int*() const { return nullptr; }
};
struct convertible_to_pointer_formattable {
operator const int*() const { return nullptr; }
};
FMT_BEGIN_NAMESPACE
template <> struct formatter<convertible_to_pointer_formattable> {
auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
auto format(convertible_to_pointer_formattable, format_context& ctx) const
-> decltype(ctx.out()) {
auto test = string_view("test");
return std::copy_n(test.data(), test.size(), ctx.out());
}
};
FMT_END_NAMESPACE
enum class unformattable_scoped_enum {};
namespace test {
enum class formattable_scoped_enum {};
auto format_as(formattable_scoped_enum) -> int { return 42; }
struct convertible_to_enum {
operator formattable_scoped_enum() const { return {}; }
};
} // namespace test
TEST(core_test, is_formattable) {
#if 0
// This should be enabled once corresponding map overloads are gone.
static_assert(fmt::is_formattable<signed char*>::value, "");
static_assert(fmt::is_formattable<unsigned char*>::value, "");
static_assert(fmt::is_formattable<const signed char*>::value, "");
static_assert(fmt::is_formattable<const unsigned char*>::value, "");
#endif
static_assert(!fmt::is_formattable<wchar_t>::value, "");
#ifdef __cpp_char8_t
static_assert(!fmt::is_formattable<char8_t>::value, "");
#endif
static_assert(!fmt::is_formattable<char16_t>::value, "");
static_assert(!fmt::is_formattable<char32_t>::value, "");
static_assert(!fmt::is_formattable<const wchar_t*>::value, "");
static_assert(!fmt::is_formattable<const wchar_t[3]>::value, "");
static_assert(!fmt::is_formattable<fmt::basic_string_view<wchar_t>>::value,
"");
static_assert(fmt::is_formattable<enabled_formatter>::value, "");
static_assert(!fmt::is_formattable<enabled_ptr_formatter*>::value, "");
static_assert(!fmt::is_formattable<disabled_formatter>::value, "");
static_assert(fmt::is_formattable<disabled_formatter_convertible>::value, "");
static_assert(fmt::is_formattable<const_formattable&>::value, "");
static_assert(fmt::is_formattable<const const_formattable&>::value, "");
static_assert(fmt::is_formattable<nonconst_formattable&>::value, "");
#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1910
static_assert(!fmt::is_formattable<const nonconst_formattable&>::value, "");
#endif
static_assert(!fmt::is_formattable<convertible_to_pointer>::value, "");
const auto f = convertible_to_pointer_formattable();
EXPECT_EQ(fmt::format("{}", f), "test");
static_assert(!fmt::is_formattable<void (*)()>::value, "");
struct s;
static_assert(!fmt::is_formattable<int(s::*)>::value, "");
static_assert(!fmt::is_formattable<int (s::*)()>::value, "");
static_assert(!fmt::is_formattable<unformattable_scoped_enum>::value, "");
static_assert(fmt::is_formattable<test::formattable_scoped_enum>::value, "");
static_assert(!fmt::is_formattable<test::convertible_to_enum>::value, "");
}
TEST(core_test, format) { EXPECT_EQ(fmt::format("{}", 42), "42"); }
TEST(core_test, format_to) {
std::string s;
fmt::format_to(std::back_inserter(s), "{}", 42);
EXPECT_EQ(s, "42");
}
TEST(core_test, format_as) {
EXPECT_EQ(fmt::format("{}", test::formattable_scoped_enum()), "42");
}
struct convertible_to_int {
operator int() const { return 42; }
};
struct convertible_to_c_string {
operator const char*() const { return "foo"; }
};
FMT_BEGIN_NAMESPACE
template <> struct formatter<convertible_to_int> {
auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
auto format(convertible_to_int, format_context& ctx) -> decltype(ctx.out()) {
return std::copy_n("foo", 3, ctx.out());
}
};
template <> struct formatter<convertible_to_c_string> {
FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
auto format(convertible_to_c_string, format_context& ctx)
-> decltype(ctx.out()) {
return std::copy_n("bar", 3, ctx.out());
}
};
FMT_END_NAMESPACE
TEST(core_test, formatter_overrides_implicit_conversion) {
EXPECT_EQ(fmt::format("{}", convertible_to_int()), "foo");
EXPECT_EQ(fmt::format("{}", convertible_to_c_string()), "bar");
}
// Test that check is not found by ADL.
template <typename T> void check(T);
TEST(core_test, adl_check) {
EXPECT_EQ(fmt::format("{}", test_struct()), "test");
}
TEST(core_test, to_string_view_foreign_strings) {
using namespace test_ns;
EXPECT_EQ(to_string_view(test_string<char>("42")), "42");
fmt::detail::type type =
fmt::detail::mapped_type_constant<test_string<char>,
fmt::format_context>::value;
EXPECT_EQ(type, fmt::detail::type::string_type);
}
struct implicitly_convertible_to_string {
operator std::string() const { return "foo"; }
};
struct implicitly_convertible_to_string_view {
operator fmt::string_view() const { return "foo"; }
};
TEST(core_test, format_implicitly_convertible_to_string_view) {
EXPECT_EQ("foo", fmt::format("{}", implicitly_convertible_to_string_view()));
}
// std::is_constructible is broken in MSVC until version 2015.
#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1900
struct explicitly_convertible_to_string_view {
explicit operator fmt::string_view() const { return "foo"; }
};
TEST(core_test, format_explicitly_convertible_to_string_view) {
// Types explicitly convertible to string_view are not formattable by
// default because it may introduce ODR violations.
static_assert(
!fmt::is_formattable<explicitly_convertible_to_string_view>::value, "");
}
# ifdef FMT_USE_STRING_VIEW
struct explicitly_convertible_to_std_string_view {
explicit operator std::string_view() const { return "foo"; }
};
TEST(core_test, format_explicitly_convertible_to_std_string_view) {
// Types explicitly convertible to string_view are not formattable by
// default because it may introduce ODR violations.
static_assert(
!fmt::is_formattable<explicitly_convertible_to_std_string_view>::value,
"");
}
# endif
#endif
struct convertible_to_long_long {
operator long long() const { return 1LL << 32; }
};
TEST(format_test, format_convertible_to_long_long) {
EXPECT_EQ("100000000", fmt::format("{:x}", convertible_to_long_long()));
}
struct disabled_rvalue_conversion {
operator const char*() const& { return "foo"; }
operator const char*() & { return "foo"; }
operator const char*() const&& = delete;
operator const char*() && = delete;
};
TEST(core_test, disabled_rvalue_conversion) {
EXPECT_EQ("foo", fmt::format("{}", disabled_rvalue_conversion()));
}
namespace adl_test {
template <typename... T> void make_format_args(const T&...) = delete;
struct string : std::string {};
} // namespace adl_test
// Test that formatting functions compile when make_format_args is found by ADL.
TEST(core_test, adl) {
// Only check compilation and don't run the code to avoid polluting the output
// and since the output is tested elsewhere.
if (fmt::detail::const_check(true)) return;
auto s = adl_test::string();
char buf[10];
(void)fmt::format("{}", s);
fmt::format_to(buf, "{}", s);
fmt::format_to_n(buf, 10, "{}", s);
(void)fmt::formatted_size("{}", s);
fmt::print("{}", s);
fmt::print(stdout, "{}", s);
}
TEST(core_test, has_const_formatter) {
EXPECT_TRUE((fmt::detail::has_const_formatter<const_formattable,
fmt::format_context>()));
EXPECT_FALSE((fmt::detail::has_const_formatter<nonconst_formattable,
fmt::format_context>()));
}
TEST(core_test, format_nonconst) {
EXPECT_EQ(fmt::format("{}", nonconst_formattable()), "test");
}
|
3fd27f57598d1733d05d9eb34be7a1bf53c40e06 | ddabf2282a3262cf71e0bee15589e96f7bc51ab4 | /blaze_tensor/math/views/dilatedsubtensor/Dense.h | 971e9810e98c2bf9dacb858ba37a6132ec50870f | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | STEllAR-GROUP/blaze_tensor | 538067a8ead9f551349e486a3a5d965feaad5b75 | 4b6ec2c6b20b46de36ac4374deea03d2fc4b3753 | refs/heads/master | 2021-06-27T10:36:53.061011 | 2020-10-01T15:59:23 | 2020-10-01T15:59:23 | 157,039,072 | 35 | 7 | NOASSERTION | 2020-09-30T18:18:43 | 2018-11-11T02:03:03 | C++ | UTF-8 | C++ | false | false | 105,904 | h | Dense.h | //=================================================================================================
/*!
// \file blaze_tensor/math/views/DilatedSubtensor/Dense.h
// \brief DilatedSubtensor specialization for dense matrices
//
// Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved
// Copyright (C) 2018-2019 Hartmut Kaiser - All Rights Reserved
// Copyright (C) 2019 Bita Hasheminezhad - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZE_TENSOR_MATH_VIEWS_DILATEDSUBTENSOR_DENSE_H_
#define _BLAZE_TENSOR_MATH_VIEWS_DILATEDSUBTENSOR_DENSE_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <algorithm>
#include <iterator>
#include <blaze/math/Aliases.h>
#include <blaze/math/constraints/Computation.h>
#include <blaze/math/constraints/RequiresEvaluation.h>
#include <blaze/math/constraints/Symmetric.h>
#include <blaze/math/constraints/TransExpr.h>
#include <blaze/math/constraints/UniTriangular.h>
#include <blaze/math/Exception.h>
#include <blaze/math/expressions/View.h>
#include <blaze/math/InitializerList.h>
#include <blaze/math/shims/Clear.h>
#include <blaze/math/shims/IsDefault.h>
#include <blaze/math/shims/Reset.h>
#include <blaze/math/SIMD.h>
#include <blaze/math/StorageOrder.h>
#include <blaze/math/traits/AddTrait.h>
#include <blaze/math/traits/SchurTrait.h>
#include <blaze/math/traits/SubTrait.h>
#include <blaze/math/typetraits/HasMutableDataAccess.h>
#include <blaze/math/typetraits/HasSIMDAdd.h>
#include <blaze/math/typetraits/HasSIMDMult.h>
#include <blaze/math/typetraits/HasSIMDSub.h>
#include <blaze/math/typetraits/IsContiguous.h>
#include <blaze/math/typetraits/IsDiagonal.h>
#include <blaze/math/typetraits/IsExpression.h>
#include <blaze/math/typetraits/IsHermitian.h>
#include <blaze/math/typetraits/IsLower.h>
#include <blaze/math/typetraits/IsRestricted.h>
#include <blaze/math/typetraits/IsSIMDCombinable.h>
#include <blaze/math/typetraits/IsStrictlyLower.h>
#include <blaze/math/typetraits/IsStrictlyUpper.h>
#include <blaze/math/typetraits/IsSymmetric.h>
#include <blaze/math/typetraits/IsTriangular.h>
#include <blaze/math/typetraits/IsUniLower.h>
#include <blaze/math/typetraits/IsUniUpper.h>
#include <blaze/math/typetraits/IsUpper.h>
#include <blaze/math/typetraits/RequiresEvaluation.h>
#include <blaze/math/views/Check.h>
#include <blaze/system/Blocking.h>
#include <blaze/system/CacheSize.h>
#include <blaze/system/Inline.h>
#include <blaze/system/Optimizations.h>
#include <blaze/system/Thresholds.h>
#include <blaze/util/algorithms/Max.h>
#include <blaze/util/algorithms/Min.h>
#include <blaze/util/AlignmentCheck.h>
#include <blaze/util/Assert.h>
#include <blaze/util/constraints/Pointer.h>
#include <blaze/util/constraints/Reference.h>
#include <blaze/util/constraints/Vectorizable.h>
#include <blaze/util/EnableIf.h>
#include <blaze/util/MaybeUnused.h>
#include <blaze/util/mpl/If.h>
#include <blaze/util/TypeList.h>
#include <blaze/util/Types.h>
#include <blaze/util/typetraits/IsConst.h>
#include <blaze/util/typetraits/IsReference.h>
#include <blaze_tensor/math/constraints/DenseTensor.h>
#include <blaze_tensor/math/constraints/DilatedSubtensor.h>
#include <blaze_tensor/math/constraints/RowMajorTensor.h>
#include <blaze_tensor/math/dense/InitializerTensor.h>
#include <blaze_tensor/math/expressions/DenseTensor.h>
#include <blaze_tensor/math/traits/DilatedSubtensorTrait.h>
#include <blaze_tensor/math/views/dilatedsubtensor/BaseTemplate.h>
#include <blaze_tensor/math/views/dilatedsubtensor/DilatedSubtensorData.h>
#include <blaze_tensor/system/Thresholds.h>
namespace blaze {
//=================================================================================================
//
// CLASS TEMPLATE SPECIALIZATION FOR UNALIGNED ROW-MAJOR DENSE DILATEDSUBMATRICES
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Specialization of DilatedSubtensor for unaligned row-major dense dilatedsubmatrices.
// \ingroup DilatedSubtensor
//
// This Specialization of DilatedSubtensor adapts the class template to the requirements of unaligned
// row-major dense dilatedsubmatrices.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
class DilatedSubtensor<TT,true,CSAs...>
: public View< DenseTensor< DilatedSubtensor<TT,true,CSAs...> > >
, private DilatedSubtensorData<CSAs...>
{
private:
//**Type definitions****************************************************************************
using DataType = DilatedSubtensorData<CSAs...>; //!< The type of the DilatedSubtensorData base class.
using Operand = If_t< IsExpression_v<TT>, TT, TT& >; //!< Composite data type of the tensor expression.
//**********************************************************************************************
//**********************************************************************************************
//! Helper variable template for the explicit application of the SFINAE principle.
template< typename TT1, typename TT2 >
static constexpr bool EnforceEvaluation_v =
( IsRestricted_v<TT1> && RequiresEvaluation_v<TT2> );
//**********************************************************************************************
public:
//**Type definitions****************************************************************************
//! Type of this DilatedSubtensor instance.
using This = DilatedSubtensor<TT,true,CSAs...>;
using BaseType = DenseTensor<This>; //!< Base type of this DilatedSubtensor instance.
using ViewedType = TT; //!< The type viewed by this DilatedSubtensor instance.
using ResultType = DilatedSubtensorTrait_t<TT,CSAs...>; //!< Result type for expression template evaluations.
using OppositeType = OppositeType_t<ResultType>; //!< Result type with opposite storage order for expression template evaluations.
using TransposeType = TransposeType_t<ResultType>; //!< Transpose type for expression template evaluations.
using ElementType = ElementType_t<TT>; //!< Type of the DilatedSubtensor elements.
using SIMDType = SIMDTrait_t<ElementType>; //!< SIMD type of the DilatedSubtensor elements.
using ReturnType = ReturnType_t<TT>; //!< Return type for expression template evaluations
using CompositeType = const DilatedSubtensor&; //!< Data type for composite expression templates.
//! Reference to a constant dilatedsubtensor value.
using ConstReference = ConstReference_t<TT>;
//! Reference to a non-constant dilatedsubtensor value.
using Reference = If_t< IsConst_v<TT>, ConstReference, Reference_t<TT> >;
//! Pointer to a constant dilatedsubtensor value.
using ConstPointer = ConstPointer_t<TT>;
//! Pointer to a non-constant dilatedsubtensor value.
using Pointer = If_t< IsConst_v<TT> || !HasMutableDataAccess_v<TT>, ConstPointer, Pointer_t<TT> >;
////**********************************************************************************************
//**DilatedSubtensorIterator class definition****************************************************
/*!\brief Iterator over the elements of the sparse DilatedSubtensor.
*/
template< typename IteratorType > // Type of the dense tensor iterator
class DilatedSubtensorIterator
{
public:
//**Type definitions*************************************************************************
//! The iterator category.
using IteratorCategory = typename std::iterator_traits<IteratorType>::iterator_category;
//! Type of the underlying elements.
using ValueType = typename std::iterator_traits<IteratorType>::value_type;
//! Pointer return type.
using PointerType = typename std::iterator_traits<IteratorType>::pointer;
//! Reference return type.
using ReferenceType = typename std::iterator_traits<IteratorType>::reference;
//! Difference between two iterators.
using DifferenceType = typename std::iterator_traits<IteratorType>::difference_type;
// STL iterator requirements
using iterator_category = IteratorCategory; //!< The iterator category.
using value_type = ValueType; //!< Type of the underlying elements.
using pointer = PointerType; //!< Pointer return type.
using reference = ReferenceType; //!< Reference return type.
using difference_type = DifferenceType; //!< Difference between two iterators.
//*******************************************************************************************
//**Constructor******************************************************************************
/*!\brief Default constructor of the DilatedSubtensorIterator class.
*/
inline DilatedSubtensorIterator()
: iterator_ ( ) // Iterator to the current DilatedSubtensor element
, pagedilation_ ( 1 ) // page step-size of the underlying dilated subtensor
, rowdilation_ ( 1 ) // row step-size of the underlying dilated subtensor
, columndilation_ ( 1 ) // column step-size of the underlying dilated subtensor
{}
//*******************************************************************************************
//**Constructor******************************************************************************
/*!\brief Constructor of the DilatedSubtensorIterator class.
//
// \param iterator Iterator to the initial element.
// \param isMemoryAligned Memory alignment flag.
*/
inline DilatedSubtensorIterator( IteratorType iterator, size_t pagedilation, size_t rowdilation, size_t columndilation)
: iterator_ ( iterator ) // Iterator to the current DilatedSubtensor element
, pagedilation_ ( pagedilation ) // page step-size of the underlying dilated subtensor
, rowdilation_ ( rowdilation ) // row step-size of the underlying dilated subtensor
, columndilation_ ( columndilation ) // column step-size of the underlying dilated subtensor
{}
//*******************************************************************************************
//**Constructor******************************************************************************
/*!\brief Conversion constructor from different DilatedSubtensorIterator instances.
//
// \param it The DilatedSubtensor iterator to be copied.
*/
template< typename IteratorType2 >
inline DilatedSubtensorIterator( const DilatedSubtensorIterator<IteratorType2>& it )
: iterator_ ( it.base() ) // Iterator to the current DilatedSubtensor element
, pagedilation_ ( it.pagedilation() ) // page step-size of the underlying dilated subtensor
, rowdilation_ ( it.rowdilation() ) // row step-size of the underlying dilated subtensor
, columndilation_ ( it.columndilation() ) // column step-size of the underlying dilated subtensor
{}
//*******************************************************************************************
//**Addition assignment operator*************************************************************
/*!\brief Addition assignment operator.
//
// \param inc The increment of the iterator.
// \return The incremented iterator.
*/
inline DilatedSubtensorIterator& operator+=( size_t inc ) {
iterator_ += inc * columndilation_;
return *this;
}
//*******************************************************************************************
//**Subtraction assignment operator**********************************************************
/*!\brief Subtraction assignment operator.
//
// \param dec The decrement of the iterator.
// \return The decremented iterator.
*/
inline DilatedSubtensorIterator& operator-=( size_t dec ) {
iterator_ -= dec * columndilation_;
return *this;
}
//*******************************************************************************************
//**Prefix increment operator****************************************************************
/*!\brief Pre-increment operator.
//
// \return Reference to the incremented iterator.
*/
inline DilatedSubtensorIterator& operator++() {
iterator_+= columndilation_;
return *this;
}
//*******************************************************************************************
//**Postfix increment operator***************************************************************
/*!\brief Post-increment operator.
//
// \return The previous position of the iterator.
*/
inline const DilatedSubtensorIterator operator++( int ) {
return DilatedSubtensorIterator( iterator_+=columndilation_, pagedilation_, rowdilation_, columndilation_ );
}
//*******************************************************************************************
//**Prefix decrement operator****************************************************************
/*!\brief Pre-decrement operator.
//
// \return Reference to the decremented iterator.
*/
inline DilatedSubtensorIterator& operator--() {
iterator_-= columndilation_;
return *this;
}
//*******************************************************************************************
//**Postfix decrement operator***************************************************************
/*!\brief Post-decrement operator.
//
// \return The previous position of the iterator.
*/
inline const DilatedSubtensorIterator operator--( int ) {
return DilatedSubtensorIterator( iterator_-=columndilation_, pagedilation_, rowdilation_, columndilation_ );
}
//*******************************************************************************************
//**Element access operator******************************************************************
/*!\brief Direct access to the element at the current iterator position.
//
// \return The resulting value.
*/
inline ReferenceType operator*() const {
return *iterator_;
}
//*******************************************************************************************
//**Element access operator******************************************************************
/*!\brief Direct access to the element at the current iterator position.
//
// \return Pointer to the element at the current iterator position.
*/
inline IteratorType operator->() const {
return iterator_;
}
//*******************************************************************************************
//**Equality operator************************************************************************
/*!\brief Equality comparison between two DilatedSubtensorIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the iterators refer to the same element, \a false if not.
*/
inline bool operator==( const DilatedSubtensorIterator& rhs ) const {
return iterator_ == rhs.iterator_ && pagedilation_ == rhs.pagedilation_ && rowdilation_ == rhs.rowdilation_ &&
columndilation_ == rhs.columndilation_;
}
//*******************************************************************************************
//**Inequality operator**********************************************************************
/*!\brief Inequality comparison between two DilatedSubtensorIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the iterators don't refer to the same element, \a false if they do.
*/
inline bool operator!=( const DilatedSubtensorIterator& rhs ) const {
return iterator_ != rhs.iterator_ || pagedilation_ != rhs.pagedilation_ || rowdilation_ != rhs.rowdilation_ ||
columndilation_ != rhs.columndilation_;
}
//*******************************************************************************************
//**Less-than operator***********************************************************************
/*!\brief Less-than comparison between two DilatedSubtensorIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the left-hand side iterator is smaller, \a false if not.
*/
inline bool operator<( const DilatedSubtensorIterator& rhs ) const {
return iterator_ < rhs.iterator_;
}
//*******************************************************************************************
//**Greater-than operator********************************************************************
/*!\brief Greater-than comparison between two DilatedSubtensorIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the left-hand side iterator is greater, \a false if not.
*/
inline bool operator>( const DilatedSubtensorIterator& rhs ) const {
return iterator_ > rhs.iterator_;
}
//*******************************************************************************************
//**Less-or-equal-than operator**************************************************************
/*!\brief Less-than comparison between two DilatedSubtensorIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the left-hand side iterator is smaller or equal, \a false if not.
*/
inline bool operator<=( const DilatedSubtensorIterator& rhs ) const {
return iterator_ <= rhs.iterator_;
}
//*******************************************************************************************
//**Greater-or-equal-than operator***********************************************************
/*!\brief Greater-than comparison between two DilatedSubtensorIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the left-hand side iterator is greater or equal, \a false if not.
*/
inline bool operator>=( const DilatedSubtensorIterator& rhs ) const {
return iterator_ >= rhs.iterator_;
}
//*******************************************************************************************
//**Subtraction operator*********************************************************************
/*!\brief Calculating the number of elements between two iterators.
//
// \param rhs The right-hand side iterator.
// \return The number of elements between the two iterators.
*/
inline DifferenceType operator-( const DilatedSubtensorIterator& rhs ) const {
return (iterator_ - rhs.iterator_)/ptrdiff_t(columndilation_);
}
//*******************************************************************************************
//**Addition operator************************************************************************
/*!\brief Addition between a DilatedSubtensorIterator and an integral value.
//
// \param it The iterator to be incremented.
// \param inc The number of elements the iterator is incremented.
// \return The incremented iterator.
*/
friend inline const DilatedSubtensorIterator operator+( const DilatedSubtensorIterator& it, size_t inc ) {
return DilatedSubtensorIterator( it.iterator_ + inc*it.columndilation_, it.pagedilation_, it.rowdilation_, it.columndilation_ );
}
//*******************************************************************************************
//**Addition operator************************************************************************
/*!\brief Addition between an integral value and a DilatedSubtensorIterator.
//
// \param inc The number of elements the iterator is incremented.
// \param it The iterator to be incremented.
// \return The incremented iterator.
*/
friend inline const DilatedSubtensorIterator operator+( size_t inc, const DilatedSubtensorIterator& it ) {
return DilatedSubtensorIterator( it.iterator_ + inc*it.columndilation_, it.pagedilation_, it.rowdilation_, it.columndilation_ );
}
//*******************************************************************************************
//**Subtraction operator*********************************************************************
/*!\brief Subtraction between a DilatedSubtensorIterator and an integral value.
//
// \param it The iterator to be decremented.
// \param dec The number of elements the iterator is decremented.
// \return The decremented iterator.
*/
friend inline const DilatedSubtensorIterator operator-( const DilatedSubtensorIterator& it, size_t dec ) {
return DilatedSubtensorIterator( it.iterator_ - dec*it.columndilation_, it.pagedilation_, it.rowdilation_, it.columndilation_ );
}
//*******************************************************************************************
//**Base function****************************************************************************
/*!\brief Access to the current position of the DilatedSubtensor iterator.
//
// \return The current position of the DilatedSubtensor iterator.
*/
inline IteratorType base() const {
return iterator_;
}
//*******************************************************************************************
//**PageDilation function********************************************************************
/*!\briefAccess to the current rowdilation of the dilatedsubtensor iterator.
//
// \return The page dilation of the dilatedsubtensor iterator.
*/
inline size_t pagedilation() const noexcept {
return pagedilation_;
}
//*******************************************************************************************
//**RowDilation function*********************************************************************
/*!\briefAccess to the current rowdilation of the dilatedsubtensor iterator.
//
// \return The row dilation of the dilatedsubtensor iterator.
*/
inline size_t rowdilation() const noexcept {
return rowdilation_;
}
//*******************************************************************************************
//**ColumnDilation function******************************************************************
/*!\brief Access to the current columndilation of the dilatedsubtensor iterator.
//
// \return The row dilation of the dilatedsubtensor iterator.
*/
inline size_t columndilation() const noexcept {
return columndilation_;
}
//*******************************************************************************************
private:
//**Member variables*************************************************************************
IteratorType iterator_; //!< Iterator to the current DilatedSubtensor element.
size_t pagedilation_; //!< Row step-size of the underlying dilated subtensor
size_t rowdilation_; //!< Row step-size of the underlying dilated subtensor
size_t columndilation_; //!< Column step-size of the underlying dilated subtensor
//*******************************************************************************************
};
//**********************************************************************************************
//**Type definitions****************************************************************************
//! Iterator over constant elements.
using ConstIterator = DilatedSubtensorIterator< ConstIterator_t<TT> >;
//! Iterator over non-constant elements.
using Iterator = If_t< IsConst_v<TT>, ConstIterator, DilatedSubtensorIterator< Iterator_t<TT> > >;
//**********************************************************************************************
//**Compilation flags***************************************************************************
//! Compilation switch for the expression template evaluation strategy.
static constexpr bool simdEnabled = false;
//! Compilation switch for the expression template assignment strategy.
static constexpr bool smpAssignable = TT::smpAssignable;
//**********************************************************************************************
//**Constructors********************************************************************************
/*!\name Constructors */
//@{
template< typename... RSAs >
explicit inline DilatedSubtensor( TT& tensor, RSAs... args );
DilatedSubtensor( const DilatedSubtensor& ) = default;
//@}
//**********************************************************************************************
//**Destructor**********************************************************************************
/*!\name Destructor */
//@{
~DilatedSubtensor() = default;
//@}
//**********************************************************************************************
//**Data access functions***********************************************************************
/*!\name Data access functions */
//@{
inline Reference operator()( size_t k, size_t i, size_t j );
inline ConstReference operator()( size_t k, size_t i, size_t j ) const;
inline Reference at( size_t k, size_t i, size_t j );
inline ConstReference at( size_t k, size_t i, size_t j ) const;
inline Pointer data () noexcept;
inline ConstPointer data () const noexcept;
inline Pointer data ( size_t i, size_t k ) noexcept;
inline ConstPointer data ( size_t i, size_t k ) const noexcept;
inline Iterator begin ( size_t i, size_t k );
inline ConstIterator begin ( size_t i, size_t k ) const;
inline ConstIterator cbegin( size_t i, size_t k ) const;
inline Iterator end ( size_t i, size_t k );
inline ConstIterator end ( size_t i, size_t k ) const;
inline ConstIterator cend ( size_t i, size_t k ) const;
//@}
//**********************************************************************************************
//**Assignment operators************************************************************************
/*!\name Assignment operators */
//@{
inline DilatedSubtensor& operator=( const ElementType& rhs );
inline DilatedSubtensor& operator=( initializer_list< initializer_list< initializer_list<ElementType> > > list );
inline DilatedSubtensor& operator=( const DilatedSubtensor& rhs );
template< typename TT2 >
inline DilatedSubtensor& operator=( const Tensor<TT2>& rhs );
template< typename TT2 >
inline auto operator+=( const Tensor<TT2>& rhs )
-> EnableIf_t< !EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >;
template< typename TT2 >
inline auto operator+=( const Tensor<TT2>& rhs )
-> EnableIf_t< EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >;
template< typename TT2 >
inline auto operator-=( const Tensor<TT2>& rhs )
-> EnableIf_t< !EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >;
template< typename TT2 >
inline auto operator-=( const Tensor<TT2>& rhs )
-> EnableIf_t< EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >;
template< typename TT2 >
inline auto operator%=( const Tensor<TT2>& rhs )
-> EnableIf_t< !EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >;
template< typename TT2 >
inline auto operator%=( const Tensor<TT2>& rhs )
-> EnableIf_t< EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >;
//@}
//**********************************************************************************************
//**Utility functions***************************************************************************
/*!\name Utility functions */
//@{
using DataType::page;
using DataType::row;
using DataType::column;
using DataType::pages;
using DataType::rows;
using DataType::columns;
using DataType::pagedilation;
using DataType::rowdilation;
using DataType::columndilation;
inline TT& operand() noexcept;
inline const TT& operand() const noexcept;
inline size_t spacing() const noexcept;
inline size_t capacity() const noexcept;
inline size_t capacity( size_t i, size_t k ) const noexcept;
inline size_t nonZeros() const;
inline size_t nonZeros( size_t i, size_t k ) const;
inline void reset();
inline void reset( size_t i, size_t k );
//@}
//**********************************************************************************************
//**Numeric functions***************************************************************************
/*!\name Numeric functions */
//@{
inline DilatedSubtensor& transpose();
inline DilatedSubtensor& ctranspose();
template< typename Other > inline DilatedSubtensor& scale( const Other& scalar );
//@}
//**********************************************************************************************
public:
//**Expression template evaluation functions****************************************************
/*!\name Expression template evaluation functions */
//@{
template< typename Other >
inline bool canAlias( const Other* alias ) const noexcept;
template< typename TT2, size_t... CSAs2 >
inline bool canAlias( const DilatedSubtensor<TT2,true,CSAs2...>* alias ) const noexcept;
template< typename Other >
inline bool isAliased( const Other* alias ) const noexcept;
template< typename TT2, size_t... CSAs2 >
inline bool isAliased( const DilatedSubtensor<TT2,true,CSAs2...>* alias ) const noexcept;
inline bool isAligned() const noexcept { return false; }
inline bool canSMPAssign() const noexcept;
template< typename TT2 > inline auto assign( const DenseTensor<TT2>& rhs );
template< typename TT2 > inline auto addAssign( const DenseTensor<TT2>& rhs );
template< typename TT2 > inline auto subAssign( const DenseTensor<TT2>& rhs );
template< typename TT2 > inline auto schurAssign( const DenseTensor<TT2>& rhs );
//@}
//**********************************************************************************************
private:
//**Utility functions***************************************************************************
/*!\name Utility functions */
//@{
inline bool hasOverlap() const noexcept;
//@}
//**********************************************************************************************
//**Member variables****************************************************************************
/*!\name Member variables */
//@{
Operand tensor_; //!< The tensor containing the DilatedSubtensor.
//@}
//**********************************************************************************************
//**Friend declarations*************************************************************************
template< typename TT2, bool DF2, size_t... CSAs2 > friend class DilatedSubtensor;
//**********************************************************************************************
//**Compile time checks*************************************************************************
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( TT );
BLAZE_CONSTRAINT_MUST_NOT_BE_COMPUTATION_TYPE ( TT );
BLAZE_CONSTRAINT_MUST_NOT_BE_TRANSEXPR_TYPE ( TT );
//BLAZE_CONSTRAINT_MUST_NOT_BE_SUBTENSOR_TYPE ( TT );
//BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_TENSOR_TYPE( TT );
BLAZE_CONSTRAINT_MUST_NOT_BE_POINTER_TYPE ( TT );
BLAZE_CONSTRAINT_MUST_NOT_BE_REFERENCE_TYPE ( TT );
//**********************************************************************************************
};
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// CONSTRUCTORS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Constructor for unaligned row-major dense submatrices.
//
// \param tensor The dense tensor containing the DilatedSubtensor.
// \param args The runtime DilatedSubtensor arguments.
// \exception std::invalid_argument Invalid DilatedSubtensor specification.
//
// By default, the provided DilatedSubtensor arguments are checked at runtime. In case the DilatedSubtensor is
// not properly specified (i.e. if the specified DilatedSubtensor is not contained in the given dense
// tensor) a \a std::invalid_argument exception is thrown. The checks can be skipped by providing
// the optional \a blaze::unchecked argument.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename... RSAs > // Runtime DilatedSubtensor arguments
inline DilatedSubtensor<TT,true,CSAs...>::DilatedSubtensor( TT& tensor, RSAs... args )
: DataType ( args... ) // Base class initialization
, tensor_ ( tensor ) // The tensor containing the DilatedSubtensor
{
if( !Contains_v< TypeList<RSAs...>, Unchecked > ) {
if(( page() + ( pages() - 1 ) * pagedilation() + 1 > tensor_.pages() ) ||
( row() + ( rows() - 1 ) * rowdilation() + 1 > tensor_.rows() ) ||
( column() + ( columns() - 1 ) * columndilation() + 1 > tensor_.columns() ) )
{
BLAZE_THROW_INVALID_ARGUMENT( "Invalid dilatedsubtensor specification" );
}
}
else {
BLAZE_USER_ASSERT(
page() + ( pages() - 1 ) * pagedilation() + 1 <= tensor_.pages(),
"Invalid dilatedsubtensor specification" );
BLAZE_USER_ASSERT( row() + ( rows() - 1 ) * rowdilation() + 1 <= tensor_.rows(),
"Invalid dilatedsubtensor specification" );
BLAZE_USER_ASSERT( column() + ( columns() - 1 ) * columndilation() + 1 <= tensor_.columns(),
"Invalid dilatedsubtensor specification" );
}
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// DATA ACCESS FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief 2D-access to the dense DilatedSubtensor elements.
//
// \param i Access index for the row. The index has to be in the range \f$[0..M-1]\f$.
// \param j Access index for the column. The index has to be in the range \f$[0..N-1]\f$.
// \return Reference to the accessed value.
//
// This function only performs an index check in case BLAZE_USER_ASSERT() is active. In contrast,
// the at() function is guaranteed to perform a check of the given access indices.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::Reference
DilatedSubtensor<TT,true,CSAs...>::operator()( size_t k, size_t i, size_t j )
{
BLAZE_USER_ASSERT( k < pages(), "Invalid page access index" );
BLAZE_USER_ASSERT( i < rows() , "Invalid row access index" );
BLAZE_USER_ASSERT( j < columns(), "Invalid column access index" );
return tensor_( page() + k * pagedilation(), row() + i * rowdilation(), column() + j * columndilation() );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief 3D-access to the dense DilatedSubtensor elements.
//
// \param i Access index for the row. The index has to be in the range \f$[0..M-1]\f$.
// \param j Access index for the column. The index has to be in the range \f$[0..N-1]\f$.
// \return Reference to the accessed value.
//
// This function only performs an index check in case BLAZE_USER_ASSERT() is active. In contrast,
// the at() function is guaranteed to perform a check of the given access indices.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::ConstReference
DilatedSubtensor<TT,true,CSAs...>::operator()( size_t k, size_t i, size_t j ) const
{
BLAZE_USER_ASSERT( k < pages(), "Invalid page access index" );
BLAZE_USER_ASSERT( i < rows() , "Invalid row access index" );
BLAZE_USER_ASSERT( j < columns(), "Invalid column access index" );
return const_cast< const TT& >( tensor_ )( page() + k * pagedilation(), row() + i * rowdilation(), column() + j * columndilation() );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Checked access to the DilatedSubtensor elements.
//
// \param i Access index for the row. The index has to be in the range \f$[0..M-1]\f$.
// \param j Access index for the column. The index has to be in the range \f$[0..N-1]\f$.
// \return Reference to the accessed value.
// \exception std::out_of_range Invalid tensor access index.
//
// In contrast to the function call operator this function always performs a check of the given
// access indices.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::Reference
DilatedSubtensor<TT,true,CSAs...>::at( size_t k, size_t i, size_t j )
{
if( k >= pages() ) {
BLAZE_THROW_OUT_OF_RANGE( "Invalid page access index" );
}
if( i >= rows() ) {
BLAZE_THROW_OUT_OF_RANGE( "Invalid row access index" );
}
if( j >= columns() ) {
BLAZE_THROW_OUT_OF_RANGE( "Invalid column access index" );
}
return (*this)(k,i,j);
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Checked access to the DilatedSubtensor elements.
//
// \param i Access index for the row. The index has to be in the range \f$[0..M-1]\f$.
// \param j Access index for the column. The index has to be in the range \f$[0..N-1]\f$.
// \return Reference to the accessed value.
// \exception std::out_of_range Invalid tensor access index.
//
// In contrast to the function call operator this function always performs a check of the given
// access indices.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::ConstReference
DilatedSubtensor<TT,true,CSAs...>::at( size_t k, size_t i, size_t j ) const
{
if( k >= pages() ) {
BLAZE_THROW_OUT_OF_RANGE( "Invalid page access index" );
}
if( i >= rows() ) {
BLAZE_THROW_OUT_OF_RANGE( "Invalid row access index" );
}
if( j >= columns() ) {
BLAZE_THROW_OUT_OF_RANGE( "Invalid column access index" );
}
return (*this)(k,i,j);
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Low-level data access to the DilatedSubtensor elements.
//
// \return Pointer to the internal element storage.
//
// This function returns a pointer to the internal storage of the dense DilatedSubtensor. Note that
// you can NOT assume that all tensor elements lie adjacent to each other! The dense DilatedSubtensor
// may use techniques such as padding to improve the alignment of the data.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::Pointer
DilatedSubtensor<TT,true,CSAs...>::data() noexcept
{
return tensor_.data() + ( page()*tensor_.rows() + row() ) * spacing() + column();
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Low-level data access to the DilatedSubtensor elements.
//
// \return Pointer to the internal element storage.
//
// This function returns a pointer to the internal storage of the dense DilatedSubtensor. Note that
// you can NOT assume that all tensor elements lie adjacent to each other! The dense DilatedSubtensor
// may use techniques such as padding to improve the alignment of the data.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::ConstPointer
DilatedSubtensor<TT,true,CSAs...>::data() const noexcept
{
return tensor_.data() + ( page()*tensor_.rows() + row() ) * spacing() + column();
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Low-level data access to the subtensor elements of row/column \a i.
//
// \param i The row/column index.
// \return Pointer to the internal element storage.
//
// This function returns a pointer to the internal storage for the elements in row/column \a i.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time subtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::Pointer
DilatedSubtensor<TT,true,CSAs...>::data( size_t i, size_t k ) noexcept
{
return tensor_.data() + ( ( page()+k ) * tensor_.rows() + ( row()+i ) ) * spacing() + column();
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Low-level data access to the subtensor elements of row/column \a i.
//
// \param i The row/column index.
// \return Pointer to the internal element storage.
//
// This function returns a pointer to the internal storage for the elements in row/column \a i.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time subtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::ConstPointer
DilatedSubtensor<TT,true,CSAs...>::data( size_t i, size_t k ) const noexcept
{
return tensor_.data() + ( ( page()+k ) * tensor_.rows() + ( row()+i ) ) * spacing() + column();
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns an iterator to the first non-zero element of row/column \a i.
//
// \param i The row/column index.
// \return Iterator to the first non-zero element of row/column \a i.
//
// This function returns a row/column iterator to the first non-zero element of row/column \a i.
// In case the storage order is set to \a rowMajor the function returns an iterator to the first
// non-zero element of row \a i, in case the storage flag is set to \a columnMajor the function
// returns an iterator to the first non-zero element of column \a i.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::Iterator
DilatedSubtensor<TT,true,CSAs...>::begin( size_t i, size_t k )
{
BLAZE_USER_ASSERT( k < pages(), "Invalid dense dilatedsubtensor page access index" );
BLAZE_USER_ASSERT( i < rows(), "Invalid dense dilatedsubtensor row access index" );
return Iterator( tensor_.begin( row() + i * rowdilation() , page() + k * pagedilation() ) + column(),
pagedilation(), rowdilation(), columndilation() );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns an iterator to the first non-zero element of row/column \a i.
//
// \param i The row/column index.
// \return Iterator to the first non-zero element of row/column \a i.
//
// This function returns a row/column iterator to the first non-zero element of row/column \a i.
// In case the storage order is set to \a rowMajor the function returns an iterator to the first
// non-zero element of row \a i, in case the storage flag is set to \a columnMajor the function
// returns an iterator to the first non-zero element of column \a i.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::ConstIterator
DilatedSubtensor<TT,true,CSAs...>::begin( size_t i, size_t k ) const
{
BLAZE_USER_ASSERT( k < pages(),"Invalid dense dilatedsubtensor page access index" );
BLAZE_USER_ASSERT( i < rows(), "Invalid dense dilatedsubtensor row access index" );
return ConstIterator( tensor_.cbegin( row() + i * rowdilation() , page() + k * pagedilation() ) + column(),
pagedilation(), rowdilation(), columndilation() );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns an iterator to the first non-zero element of row/column \a i.
//
// \param i The row/column index.
// \return Iterator to the first non-zero element of row/column \a i.
//
// This function returns a row/column iterator to the first non-zero element of row/column \a i.
// In case the storage order is set to \a rowMajor the function returns an iterator to the first
// non-zero element of row \a i, in case the storage flag is set to \a columnMajor the function
// returns an iterator to the first non-zero element of column \a i.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::ConstIterator
DilatedSubtensor<TT,true,CSAs...>::cbegin( size_t i, size_t k ) const
{
BLAZE_USER_ASSERT( k < pages(),"Invalid dense dilatedsubtensor page access index" );
BLAZE_USER_ASSERT( i < rows(), "Invalid dense dilatedsubtensor row access index" );
return ConstIterator( tensor_.cbegin( row() + i * rowdilation() , page() + k * pagedilation()) + column(),
pagedilation(), rowdilation(), columndilation() );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns an iterator just past the last non-zero element of row/column \a i.
//
// \param i The row/column index.
// \return Iterator just past the last non-zero element of row/column \a i.
//
// This function returns an row/column iterator just past the last non-zero element of row/column
// \a i. In case the storage order is set to \a rowMajor the function returns an iterator just
// past the last non-zero element of row \a i, in case the storage flag is set to \a columnMajor
// the function returns an iterator just past the last non-zero element of column \a i.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::Iterator
DilatedSubtensor<TT,true,CSAs...>::end( size_t i, size_t k )
{
BLAZE_USER_ASSERT( k < pages(),"Invalid dense dilatedsubtensor page access index" );
BLAZE_USER_ASSERT( i < rows(), "Invalid dense dilatedsubtensor row access index" );
return Iterator( tensor_.begin( row() + i * rowdilation() , page() + k * pagedilation() ) + column() + columns() * columndilation(),
pagedilation(), rowdilation(), columndilation() );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns an iterator just past the last non-zero element of row/column \a i.
//
// \param i The row/column index.
// \return Iterator just past the last non-zero element of row/column \a i.
//
// This function returns an row/column iterator just past the last non-zero element of row/column
// \a i. In case the storage order is set to \a rowMajor the function returns an iterator just
// past the last non-zero element of row \a i, in case the storage flag is set to \a columnMajor
// the function returns an iterator just past the last non-zero element of column \a i.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::ConstIterator
DilatedSubtensor<TT,true,CSAs...>::end( size_t i, size_t k ) const
{
BLAZE_USER_ASSERT( k < pages(),"Invalid dense dilatedsubtensor page access index" );
BLAZE_USER_ASSERT( i < rows(), "Invalid dense dilatedsubtensor row access index" );
return ConstIterator( tensor_.cbegin( row() + i * rowdilation() , page() + k * pagedilation() ) + column() + columns() * columndilation(),
pagedilation(), rowdilation(), columndilation() );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns an iterator just past the last non-zero element of row/column \a i.
//
// \param i The row/column index.
// \return Iterator just past the last non-zero element of row/column \a i.
//
// This function returns an row/column iterator just past the last non-zero element of row/column
// \a i. In case the storage order is set to \a rowMajor the function returns an iterator just
// past the last non-zero element of row \a i, in case the storage flag is set to \a columnMajor
// the function returns an iterator just past the last non-zero element of column \a i.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline typename DilatedSubtensor<TT,true,CSAs...>::ConstIterator
DilatedSubtensor<TT,true,CSAs...>::cend( size_t i, size_t k ) const
{
BLAZE_USER_ASSERT( k < pages(),"Invalid dense dilatedsubtensor page access index" );
BLAZE_USER_ASSERT( i < rows(), "Invalid dense dilatedsubtensor row access index" );
return ConstIterator( tensor_.cbegin( row() + i * rowdilation() , page() + k * pagedilation() ) + column() + columns() * columndilation(),
pagedilation(), rowdilation(), columndilation() );;
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// ASSIGNMENT OPERATORS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Homogenous assignment to all DilatedSubtensor elements.
//
// \param rhs Scalar value to be assigned to all DilatedSubtensor elements.
// \return Reference to the assigned DilatedSubtensor.
//
// This function homogeneously assigns the given value to all dense tensor elements. Note that in
// case the underlying dense tensor is a lower/upper tensor only lower/upper and diagonal elements
// of the underlying tensor are modified.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline DilatedSubtensor<TT,true,CSAs...>&
DilatedSubtensor<TT,true,CSAs...>::operator=( const ElementType& rhs )
{
decltype(auto) left( derestrict( tensor_ ) );
const size_t kend( page() + pages() * pagedilation() );
for( size_t k=page(); k<kend; k += pagedilation() )
{
const size_t iend( row() + rows() * rowdilation() );
for( size_t i=row(); i<iend; i += rowdilation() )
{
const size_t jbegin( column() );
const size_t jend ( column() + columns() * columndilation() );
for( size_t j=jbegin; j<jend; j += columndilation() ) {
if( !IsRestricted_v<TT> || IsTriangular_v<TT> || trySet( tensor_, i, j, k, rhs ) )
left(k,i,j) = rhs;
}
}
}
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief List assignment to all DilatedSubtensor elements.
//
// \param list The initializer list.
// \exception std::invalid_argument Invalid initializer list dimension.
// \exception std::invalid_argument Invalid assignment to restricted tensor.
//
// This assignment operator offers the option to directly assign to all elements of the DilatedSubtensor
// by means of an initializer list. The DilatedSubtensor elements are assigned the values from the given
// initializer list. Missing values are initialized as default. Note that in case the size of the
// top-level initializer list does not match the number of rows of the DilatedSubtensor or the size of
// any nested list exceeds the number of columns, a \a std::invalid_argument exception is thrown.
// Also, if the underlying tensor \a TT is restricted and the assignment would violate an
// invariant of the tensor, a \a std::invalid_argument exception is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline DilatedSubtensor<TT,true,CSAs...>&
DilatedSubtensor<TT,true,CSAs...>::operator=( initializer_list< initializer_list<initializer_list<ElementType> > > list )
{
if( list.size() != pages() ) {
BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to dilatedsubtensor" );
}
if( IsRestricted_v<TT> ) {
const InitializerTensor<ElementType> tmp( list, rows(), columns() );
if( !tryAssign( tensor_, tmp, row(), column(), page() ) ) {
BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to restricted tensor" );
}
}
decltype(auto) left( derestrict( *this ) );
size_t k( 0UL );
for( const auto& colList : list ) {
size_t i( 0UL );
for( const auto& rowList : colList ) {
std::fill( std::copy( rowList.begin(), rowList.end(), left.begin(i, k) ), left.end(i, k), ElementType() );
++i;
}
++k;
}
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Copy assignment operator for DilatedSubtensor.
//
// \param rhs Dense DilatedSubtensor to be copied.
// \return Reference to the assigned DilatedSubtensor.
// \exception std::invalid_argument DilatedSubtensor sizes do not match.
// \exception std::invalid_argument Invalid assignment to restricted tensor.
//
// The dense DilatedSubtensor is initialized as a copy of the given dense DilatedSubtensor. In case the current
// sizes of the two submatrices don't match, a \a std::invalid_argument exception is thrown. Also,
// if the underlying tensor \a TT is a lower triangular, upper triangular, or symmetric tensor
// and the assignment would violate its lower, upper, or symmetry property, respectively, a
// \a std::invalid_argument exception is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline DilatedSubtensor<TT,true,CSAs...>&
DilatedSubtensor<TT,true,CSAs...>::operator=( const DilatedSubtensor& rhs )
{
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
if( this == &rhs || ( &tensor_ == &rhs.tensor_ && page() == rhs.page() && row() == rhs.row() && column() == rhs.column() &&
pagedilation() == rhs.pagedilation() && rowdilation() == rhs.rowdilation() && columndilation() == rhs.columndilation() ) )
return *this;
if( pages() != rhs.pages() || rows() != rhs.rows() || columns() != rhs.columns() ) {
BLAZE_THROW_INVALID_ARGUMENT( "DilatedSubtensor sizes do not match" );
}
if( !tryAssign( tensor_, rhs, row(), column(), page() ) ) {
BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to restricted tensor" );
}
decltype(auto) left( derestrict( *this ) );
if( rhs.canAlias( &tensor_ ) ) {
const ResultType tmp( rhs );
smpAssign( left, tmp );
}
else {
smpAssign( left, rhs );
}
BLAZE_INTERNAL_ASSERT( isIntact( tensor_ ), "Invariant violation detected" );
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Assignment operator for different matrices.
//
// \param rhs Tensor to be assigned.
// \return Reference to the assigned DilatedSubtensor.
// \exception std::invalid_argument Tensor sizes do not match.
// \exception std::invalid_argument Invalid assignment to restricted tensor.
//
// The dense DilatedSubtensor is initialized as a copy of the given tensor. In case the current sizes
// of the two matrices don't match, a \a std::invalid_argument exception is thrown. Also, if
// the underlying tensor \a TT is a lower triangular, upper triangular, or symmetric tensor
// and the assignment would violate its lower, upper, or symmetry property, respectively, a
// \a std::invalid_argument exception is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side tensor
inline DilatedSubtensor<TT,true,CSAs...>&
DilatedSubtensor<TT,true,CSAs...>::operator=( const Tensor<TT2>& rhs )
{
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType_t<TT2> );
if( pages() != (*rhs).pages() || rows() != (*rhs).rows() || columns() != (*rhs).columns() ) {
BLAZE_THROW_INVALID_ARGUMENT( "Tensor sizes do not match" );
}
using Right = If_t< IsRestricted_v<TT>, CompositeType_t<TT2>, const TT2& >;
Right right( *rhs );
if( !tryAssign( tensor_, right, row(), column(), page() ) ) {
BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to restricted tensor" );
}
decltype(auto) left( derestrict( *this ) );
if( IsReference_v<Right> && right.canAlias( &tensor_ ) ) {
const ResultType_t<TT2> tmp( right );
smpAssign( left, tmp );
}
else {
smpAssign( left, right );
}
BLAZE_INTERNAL_ASSERT( isIntact( tensor_ ), "Invariant violation detected" );
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Addition assignment operator for the addition of a tensor (\f$ A+=B \f$).
//
// \param rhs The right-hand side tensor to be added to the DilatedSubtensor.
// \return Reference to the dense DilatedSubtensor.
// \exception std::invalid_argument Tensor sizes do not match.
// \exception std::invalid_argument Invalid assignment to restricted tensor.
//
// In case the current sizes of the two matrices don't match, a \a std::invalid_argument exception
// is thrown. Also, if the underlying tensor \a TT is a lower triangular, upper triangular, or
// symmetric tensor and the assignment would violate its lower, upper, or symmetry property,
// respectively, a \a std::invalid_argument exception is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side tensor
inline auto DilatedSubtensor<TT,true,CSAs...>::operator+=( const Tensor<TT2>& rhs )
-> EnableIf_t< !EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >
{
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType_t<TT2> );
using AddType = AddTrait_t< ResultType, ResultType_t<TT2> >;
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( AddType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( AddType );
if( pages() != (*rhs).pages() || rows() != (*rhs).rows() || columns() != (*rhs).columns() ) {
BLAZE_THROW_INVALID_ARGUMENT( "Tensor sizes do not match" );
}
if( !tryAddAssign( tensor_, *rhs, row(), column(), page() ) ) {
BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to restricted tensor" );
}
decltype(auto) left( derestrict( *this ) );
if( (*rhs).canAlias( &tensor_ ) ) {
const AddType tmp( *this + (*rhs) );
smpAssign( left, tmp );
}
else {
smpAddAssign( left, *rhs );
}
BLAZE_INTERNAL_ASSERT( isIntact( tensor_ ), "Invariant violation detected" );
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Addition assignment operator for the addition of a tensor (\f$ A+=B \f$).
//
// \param rhs The right-hand side tensor to be added to the DilatedSubtensor.
// \return Reference to the dense DilatedSubtensor.
// \exception std::invalid_argument Tensor sizes do not match.
// \exception std::invalid_argument Invalid assignment to restricted tensor.
//
// In case the current sizes of the two matrices don't match, a \a std::invalid_argument exception
// is thrown. Also, if the underlying tensor \a TT is a lower triangular, upper triangular, or
// symmetric tensor and the assignment would violate its lower, upper, or symmetry property,
// respectively, a \a std::invalid_argument exception is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side tensor
inline auto DilatedSubtensor<TT,true,CSAs...>::operator+=( const Tensor<TT2>& rhs )
-> EnableIf_t< EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >
{
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType_t<TT2> );
using AddType = AddTrait_t< ResultType, ResultType_t<TT2> >;
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( AddType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( AddType );
if( pages() != (*rhs).pages() || rows() != (*rhs).rows() || columns() != (*rhs).columns() ) {
BLAZE_THROW_INVALID_ARGUMENT( "Tensor sizes do not match" );
}
const AddType tmp( *this + (*rhs) );
if( !tryAssign( tensor_, tmp, row(), column(), page() ) ) {
BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to restricted tensor" );
}
decltype(auto) left( derestrict( *this ) );
smpAssign( left, tmp );
BLAZE_INTERNAL_ASSERT( isIntact( tensor_ ), "Invariant violation detected" );
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Subtraction assignment operator for the subtraction of a tensor (\f$ A-=B \f$).
//
// \param rhs The right-hand side tensor to be subtracted from the DilatedSubtensor.
// \return Reference to the dense DilatedSubtensor.
// \exception std::invalid_argument Tensor sizes do not match.
// \exception std::invalid_argument Invalid assignment to restricted tensor.
//
// In case the current sizes of the two matrices don't match, a \a std::invalid_argument exception
// is thrown. Also, if the underlying tensor \a TT is a lower triangular, upper triangular, or
// symmetric tensor and the assignment would violate its lower, upper, or symmetry property,
// respectively, a \a std::invalid_argument exception is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side tensor
inline auto DilatedSubtensor<TT,true,CSAs...>::operator-=( const Tensor<TT2>& rhs )
-> EnableIf_t< !EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >
{
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType_t<TT2> );
using SubType = SubTrait_t< ResultType, ResultType_t<TT2> >;
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( SubType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( SubType );
if( pages() != (*rhs).pages() || rows() != (*rhs).rows() || columns() != (*rhs).columns() ) {
BLAZE_THROW_INVALID_ARGUMENT( "Tensor sizes do not match" );
}
if( !trySubAssign( tensor_, *rhs, row(), column(), page() ) ) {
BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to restricted tensor" );
}
decltype(auto) left( derestrict( *this ) );
if( (*rhs).canAlias( &tensor_ ) ) {
const SubType tmp( *this - (*rhs ) );
smpAssign( left, tmp );
}
else {
smpSubAssign( left, *rhs );
}
BLAZE_INTERNAL_ASSERT( isIntact( tensor_ ), "Invariant violation detected" );
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Subtraction assignment operator for the subtraction of a tensor (\f$ A-=B \f$).
//
// \param rhs The right-hand side tensor to be subtracted from the DilatedSubtensor.
// \return Reference to the dense DilatedSubtensor.
// \exception std::invalid_argument Tensor sizes do not match.
// \exception std::invalid_argument Invalid assignment to restricted tensor.
//
// In case the current sizes of the two matrices don't match, a \a std::invalid_argument exception
// is thrown. Also, if the underlying tensor \a TT is a lower triangular, upper triangular, or
// symmetric tensor and the assignment would violate its lower, upper, or symmetry property,
// respectively, a \a std::invalid_argument exception is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side tensor
inline auto DilatedSubtensor<TT,true,CSAs...>::operator-=( const Tensor<TT2>& rhs )
-> EnableIf_t< EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >
{
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType_t<TT2> );
using SubType = SubTrait_t< ResultType, ResultType_t<TT2> >;
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( SubType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( SubType );
if( pages() != (*rhs).pages() || rows() != (*rhs).rows() || columns() != (*rhs).columns() ) {
BLAZE_THROW_INVALID_ARGUMENT( "Tensor sizes do not match" );
}
const SubType tmp( *this - (*rhs) );
if( !tryAssign( tensor_, tmp, row(), column(), page() ) ) {
BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to restricted tensor" );
}
decltype(auto) left( derestrict( *this ) );
smpAssign( left, tmp );
BLAZE_INTERNAL_ASSERT( isIntact( tensor_ ), "Invariant violation detected" );
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Schur product assignment operator for the multiplication of a tensor (\f$ A=B \f$).
//
// \param rhs The right-hand side tensor for the Schur product.
// \return Reference to the dense DilatedSubtensor.
// \exception std::invalid_argument Tensor sizes do not match.
// \exception std::invalid_argument Invalid assignment to restricted tensor.
//
// In case the current sizes of the two matrices don't match, a \a std::invalid_argument exception
// is thrown. Also, if the underlying tensor \a TT is a lower triangular, upper triangular, or
// symmetric tensor and the assignment would violate its lower, upper, or symmetry property,
// respectively, a \a std::invalid_argument exception is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side tensor
inline auto DilatedSubtensor<TT,true,CSAs...>::operator%=( const Tensor<TT2>& rhs )
-> EnableIf_t< !EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >
{
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType_t<TT2> );
using SchurType = SchurTrait_t< ResultType, ResultType_t<TT2> >;
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( SchurType );
if( pages() != (*rhs).pages() || rows() != (*rhs).rows() || columns() != (*rhs).columns() ) {
BLAZE_THROW_INVALID_ARGUMENT( "Tensor sizes do not match" );
}
if( !trySchurAssign( tensor_, *rhs, row(), column(), page() ) ) {
BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to restricted tensor" );
}
decltype(auto) left( derestrict( *this ) );
if( (*rhs).canAlias( &tensor_ ) ) {
const SchurType tmp( *this % (*rhs) );
smpAssign( left, tmp );
}
else {
smpSchurAssign( left, *rhs );
}
BLAZE_INTERNAL_ASSERT( isIntact( tensor_ ), "Invariant violation detected" );
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Schur product assignment operator for the multiplication of a tensor (\f$ A=B \f$).
//
// \param rhs The right-hand side tensor for the Schur product.
// \return Reference to the dense DilatedSubtensor.
// \exception std::invalid_argument Tensor sizes do not match.
// \exception std::invalid_argument Invalid assignment to restricted tensor.
//
// In case the current sizes of the two matrices don't match, a \a std::invalid_argument exception
// is thrown. Also, if the underlying tensor \a TT is a lower triangular, upper triangular, or
// symmetric tensor and the assignment would violate its lower, upper, or symmetry property,
// respectively, a \a std::invalid_argument exception is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side tensor
inline auto DilatedSubtensor<TT,true,CSAs...>::operator%=( const Tensor<TT2>& rhs )
-> EnableIf_t< EnforceEvaluation_v<TT,TT2>, DilatedSubtensor& >
{
BLAZE_CONSTRAINT_MUST_BE_DENSE_TENSOR_TYPE ( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType_t<TT2> );
using SchurType = SchurTrait_t< ResultType, ResultType_t<TT2> >;
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( SchurType );
if( pages() != (*rhs).pages() || rows() != (*rhs).rows() || columns() != (*rhs).columns() ) {
BLAZE_THROW_INVALID_ARGUMENT( "Tensor sizes do not match" );
}
const SchurType tmp( *this % (*rhs) );
if( !tryAssign( tensor_, tmp, row(), column(), page() ) ) {
BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to restricted tensor" );
}
decltype(auto) left( derestrict( *this ) );
smpAssign( left, tmp );
BLAZE_INTERNAL_ASSERT( isIntact( tensor_ ), "Invariant violation detected" );
return *this;
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// UTILITY FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the tensor containing the DilatedSubtensor.
//
// \return The tensor containing the DilatedSubtensor.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline TT& DilatedSubtensor<TT,true,CSAs...>::operand() noexcept
{
return tensor_;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the tensor containing the DilatedSubtensor.
//
// \return The tensor containing the DilatedSubtensor.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline const TT& DilatedSubtensor<TT,true,CSAs...>::operand() const noexcept
{
return tensor_;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the spacing between the beginning of two rows/columns.
//
// \return The spacing between the beginning of two rows/columns.
//
// This function returns the spacing between the beginning of two rows/columns, i.e. the
// total number of elements of a row/column. In case the storage order is set to \a rowMajor
// the function returns the spacing between two rows, in case the storage flag is set to
// \a columnMajor the function returns the spacing between two columns.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline size_t DilatedSubtensor<TT,true,CSAs...>::spacing() const noexcept
{
return tensor_.spacing();
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the maximum capacity of the dense DilatedSubtensor.
//
// \return The capacity of the dense DilatedSubtensor.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline size_t DilatedSubtensor<TT,true,CSAs...>::capacity() const noexcept
{
return pages() * rows() * columns();
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the current capacity of the specified row/column.
//
// \param i The index of the row/column.
// \return The current capacity of row/column \a i.
//
// This function returns the current capacity of the specified row/column. In case the
// storage order is set to \a rowMajor the function returns the capacity of row \a i,
// in case the storage flag is set to \a columnMajor the function returns the capacity
// of column \a i.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline size_t DilatedSubtensor<TT,true,CSAs...>::capacity( size_t i, size_t k ) const noexcept
{
MAYBE_UNUSED( i, k );
BLAZE_USER_ASSERT( k < pages(), "Invalid page access index" );
BLAZE_USER_ASSERT( i < rows(), "Invalid row access index" );
return columns();
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the number of non-zero elements in the dense DilatedSubtensor
//
// \return The number of non-zero elements in the dense DilatedSubtensor.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline size_t DilatedSubtensor<TT,true,CSAs...>::nonZeros() const
{
const size_t kend( page() + pages() * pagedilation() );
const size_t iend( row() + rows() * rowdilation() );
const size_t jend( column() + columns() * columndilation() );
size_t nonzeros( 0UL );
for( size_t k=page(); k<kend; k+=pagedilation() )
for( size_t i=row(); i<iend; i+=rowdilation() )
for( size_t j=column(); j<jend; j+=columndilation() )
if( !isDefault( tensor_(k,i,j) ) )
++nonzeros;
return nonzeros;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the number of non-zero elements in the specified row/column.
//
// \param i The index of the row/column.
// \return The number of non-zero elements of row/column \a i.
//
// This function returns the current number of non-zero elements in the specified row/column.
// In case the storage order is set to \a rowMajor the function returns the number of non-zero
// elements in row \a i, in case the storage flag is set to \a columnMajor the function returns
// the number of non-zero elements in column \a i.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline size_t DilatedSubtensor<TT,true,CSAs...>::nonZeros( size_t i, size_t k ) const
{
BLAZE_USER_ASSERT( k < pages(), "Invalid page access index");
BLAZE_USER_ASSERT( i < rows(), "Invalid row access index" );
const size_t jend( column() + columns() * columndilation() );
size_t nonzeros( 0UL );
for( size_t j=column(); j<jend; j+=columndilation() )
if (!isDefault(tensor_( page() + k * pagedilation(), row() + i * rowdilation(), j)))
++nonzeros;
return nonzeros;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Reset to the default initial values.
//
// \return void
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline void DilatedSubtensor<TT,true,CSAs...>::reset()
{
using blaze::clear;
for ( size_t k = page(); k < page() + pages() * pagedilation(); k+=pagedilation() )
{
for ( size_t i = row(); i < row() + rows() * rowdilation(); i += rowdilation() )
{
const size_t jbegin( column() );
const size_t jend( column() + columns() *columndilation() );
for (size_t j = jbegin; j < jend; j+=columndilation())
clear(tensor_(k, i, j));
}
}
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Reset the specified row/column to the default initial values.
//
// \param i The index of the row/column.
// \return void
//
// This function resets the values in the specified row/column to their default value. In case
// the storage order is set to \a rowMajor the function resets the values in row \a i, in case
// the storage order is set to \a columnMajor the function resets the values in column \a i.
// Note that the capacity of the row/column remains unchanged.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline void DilatedSubtensor<TT,true,CSAs...>::reset( size_t i, size_t k )
{
using blaze::clear;
BLAZE_USER_ASSERT( k < pages(), "Invalid page access index" );
BLAZE_USER_ASSERT( i < rows(), "Invalid row access index" );
const size_t jend( column() + columns()*columndilation() );
for( size_t j=column(); j<jend; j+=columndilation() )
clear( tensor_( page() + k * pagedilation(), row() + i * rowdilation(), j ) );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Checking whether there exists an overlap in the context of a symmetric tensor.
//
// \return \a true in case an overlap exists, \a false if not.
//
// This function checks if in the context of a symmetric tensor the DilatedSubtensor has an overlap with
// its counterpart. In case an overlap exists, the function return \a true, otherwise it returns
// \a false.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline bool DilatedSubtensor<TT,true,CSAs...>::hasOverlap() const noexcept
{
//BLAZE_INTERNAL_ASSERT( IsSymmetric_v<TT> || IsHermitian_v<TT>, "Invalid tensor detected" );
if( ( row() + rows()*rowdilation() <= column() ) || ( column() + columns()*columndilation() <= row() ) )
return false;
else return true;
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// NUMERIC FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief In-place transpose of the DilatedSubtensor.
//
// \return Reference to the transposed DilatedSubtensor.
// \exception std::logic_error Invalid transpose of a non-quadratic DilatedSubtensor.
// \exception std::logic_error Invalid transpose operation.
//
// This function transposes the dense DilatedSubtensor in-place. Note that this function can only be used
// for quadratic submatrices, i.e. if the number of rows is equal to the number of columns. Also,
// the function fails if ...
//
// - ... the DilatedSubtensor contains elements from the upper part of the underlying lower tensor;
// - ... the DilatedSubtensor contains elements from the lower part of the underlying upper tensor;
// - ... the result would be non-deterministic in case of a symmetric or Hermitian tensor.
//
// In all cases, a \a std::logic_error is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline DilatedSubtensor<TT,true,CSAs...>&
DilatedSubtensor<TT,true,CSAs...>::transpose()
{
if( pages() != columns() ) {
BLAZE_THROW_LOGIC_ERROR( "Invalid transpose of a non-quadratic dilatedsubtensor" );
}
if( !tryAssign( tensor_, trans( *this ), row(), column(), page() ) ) {
BLAZE_THROW_LOGIC_ERROR( "Invalid transpose operation" );
}
decltype(auto) left( derestrict( *this ) );
const ResultType tmp( trans( *this ) );
smpAssign( left, tmp );
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief In-place conjugate transpose of the DilatedSubtensor.
//
// \return Reference to the transposed DilatedSubtensor.
// \exception std::logic_error Invalid transpose of a non-quadratic DilatedSubtensor.
// \exception std::logic_error Invalid transpose operation.
//
// This function transposes the dense DilatedSubtensor in-place. Note that this function can only be used
// for quadratic submatrices, i.e. if the number of rows is equal to the number of columns. Also,
// the function fails if ...
//
// - ... the DilatedSubtensor contains elements from the upper part of the underlying lower tensor;
// - ... the DilatedSubtensor contains elements from the lower part of the underlying upper tensor;
// - ... the result would be non-deterministic in case of a symmetric or Hermitian tensor.
//
// In all cases, a \a std::logic_error is thrown.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline DilatedSubtensor<TT,true,CSAs...>&
DilatedSubtensor<TT,true,CSAs...>::ctranspose()
{
if( pages() != columns() ) {
BLAZE_THROW_LOGIC_ERROR( "Invalid transpose of a non-quadratic dilatedsubtensor" );
}
if( !tryAssign( tensor_, ctrans( *this ), row(), column(), page() ) ) {
BLAZE_THROW_LOGIC_ERROR( "Invalid transpose operation" );
}
decltype(auto) left( derestrict( *this ) );
const ResultType tmp( ctrans( *this ) );
smpAssign( left, tmp );
return *this;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Scaling of the dense DilatedSubtensor by the scalar value \a scalar (\f$ A=B*s \f$).
//
// \param scalar The scalar value for the DilatedSubtensor scaling.
// \return Reference to the dense DilatedSubtensor.
//
// This function scales the DilatedSubtensor by applying the given scalar value \a scalar to each
// element of the DilatedSubtensor. For built-in and \c complex data types it has the same effect
// as using the multiplication assignment operator. Note that the function cannot be used
// to scale a DilatedSubtensor on a lower or upper unitriangular tensor. The attempt to scale
// such a DilatedSubtensor results in a compile time error!
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename Other > // Data type of the scalar value
inline DilatedSubtensor<TT,true,CSAs...>&
DilatedSubtensor<TT,true,CSAs...>::scale( const Other& scalar )
{
const size_t kend( page() + pages() * pagedilation() );
for( size_t k=page(); k<kend; k+=pagedilation() )
{
const size_t iend( row() + rows() * rowdilation() );
for( size_t i=row(); i<iend; i+=rowdilation() )
{
const size_t jbegin( column() );
const size_t jend ( column() + columns()*columndilation() );
for( size_t j=jbegin; j<jend; j+=columndilation() )
tensor_(k,i,j) *= scalar;
}
}
return *this;
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// EXPRESSION TEMPLATE EVALUATION FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns whether the DilatedSubtensor can alias with the given address \a alias.
//
// \param alias The alias to be checked.
// \return \a true in case the alias corresponds to this DilatedSubtensor, \a false if not.
//
// This function returns whether the given address can alias with the DilatedSubtensor. In contrast
// to the isAliased() function this function is allowed to use compile time expressions to
// optimize the evaluation.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename Other > // Data type of the foreign expression
inline bool DilatedSubtensor<TT,true,CSAs...>::canAlias( const Other* alias ) const noexcept
{
return tensor_.isAliased( alias );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns whether the DilatedSubtensor can alias with the given dense DilatedSubtensor \a alias.
//
// \param alias The alias to be checked.
// \return \a true in case the alias corresponds to this DilatedSubtensor, \a false if not.
//
// This function returns whether the given address can alias with the DilatedSubtensor. In contrast
// to the isAliased() function this function is allowed to use compile time expressions to
// optimize the evaluation.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 // Data type of the foreign dense DilatedSubtensor
, size_t... CSAs2 > // Compile time DilatedSubtensor arguments of the foreign dense DilatedSubtensor
inline bool
DilatedSubtensor<TT,true,CSAs...>::canAlias( const DilatedSubtensor<TT2,true,CSAs2...>* alias ) const noexcept
{
return ( tensor_.isAliased( &alias->tensor_ ) &&
( row() + rows() * rowdilation() > alias->row() ) &&
( row() < alias->row() + ( alias->rows() - 1 ) * alias->rowdilation() + 1 ) &&
( column() + columns() > alias->column() ) &&
( column() < alias->column() + (alias->columns() - 1) * alias->columndilation() + 1 ) &&
( page() + pages() > alias->page() ) &&
( page() < alias->page() + (alias->pages() - 1) * alias->pagedilation() + 1 ) );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns whether the DilatedSubtensor is aliased with the given address \a alias.
//
// \param alias The alias to be checked.
// \return \a true in case the alias corresponds to this DilatedSubtensor, \a false if not.
//
// This function returns whether the given address is aliased with the DilatedSubtensor. In contrast
// to the canAlias() function this function is not allowed to use compile time expressions to
// optimize the evaluation.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename Other > // Data type of the foreign expression
inline bool DilatedSubtensor<TT,true,CSAs...>::isAliased( const Other* alias ) const noexcept
{
return tensor_.isAliased( alias );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns whether the DilatedSubtensor is aliased with the given dense DilatedSubtensor \a alias.
//
// \param alias The alias to be checked.
// \return \a true in case the alias corresponds to this DilatedSubtensor, \a false if not.
//
// This function returns whether the given address is aliased with the DilatedSubtensor. In contrast
// to the canAlias() function this function is not allowed to use compile time expressions to
// optimize the evaluation.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 // Data type of the foreign dense DilatedSubtensor
, size_t... CSAs2 > // Compile time DilatedSubtensor arguments of the foreign dense DilatedSubtensor
inline bool
DilatedSubtensor<TT,true,CSAs...>::isAliased( const DilatedSubtensor<TT2,true,CSAs2...>* alias ) const noexcept
{
return ( tensor_.isAliased( &alias->tensor_ ) &&
( row() + rows() * rowdilation() > alias->row() ) &&
( row() < alias->row() + ( alias->rows() - 1 ) * alias->rowdilation() + 1 ) &&
( column() + columns() * columndilation() > alias->column() ) &&
( column() < alias->column() + ( alias->columns() - 1 ) * alias->columndilation() + 1 ) &&
( page() + pages() > alias->page() ) &&
( page() < alias->page() + (alias->pages() - 1) * alias->pagedilation() + 1 ) );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns whether the DilatedSubtensor can be used in SMP assignments.
//
// \return \a true in case the DilatedSubtensor can be used in SMP assignments, \a false if not.
//
// This function returns whether the DilatedSubtensor can be used in SMP assignments. In contrast to the
// \a smpAssignable member enumeration, which is based solely on compile time information, this
// function additionally provides runtime information (as for instance the current number of
// rows and/or columns of the DilatedSubtensor).
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
inline bool DilatedSubtensor<TT,true,CSAs...>::canSMPAssign() const noexcept
{
return ( pages() * rows() * columns() >= SMP_DTENSASSIGN_THRESHOLD );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Default implementation of the assignment of a row-major dense tensor.
//
// \param rhs The right-hand side dense tensor to be assigned.
// \return void
//
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side dense tensor
inline auto DilatedSubtensor<TT,true,CSAs...>::assign( const DenseTensor<TT2>& rhs )
{
BLAZE_INTERNAL_ASSERT( pages() == (*rhs).pages() , "Invalid number of pages" );
BLAZE_INTERNAL_ASSERT( rows() == (*rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( columns() == (*rhs).columns(), "Invalid number of columns");
const size_t jpos( columns() & size_t(-2) );
BLAZE_INTERNAL_ASSERT( ( columns() - ( columns() % 2UL ) ) == jpos, "Invalid end calculation" );
for (size_t k = 0UL; k < pages(); ++k) {
for (size_t i = 0UL; i < rows(); ++i) {
for (size_t j = 0UL; j < jpos; j += 2UL) {
(*this)(k, i, j) = (*rhs)(k, i, j);
(*this)(k, i, j + 1UL) = (*rhs)(k, i, j + 1UL);
}
if (jpos < columns()) {
(*this)(k, i, jpos) = (*rhs)(k, i, jpos);
}
}
}
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Default implementation of the addition assignment of a row-major dense tensor.
//
// \param rhs The right-hand side dense tensor to be added.
// \return void
//
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side dense tensor
inline auto DilatedSubtensor<TT,true,CSAs...>::addAssign( const DenseTensor<TT2>& rhs )
{
BLAZE_INTERNAL_ASSERT( pages() == (*rhs).pages() , "Invalid number of pages" );
BLAZE_INTERNAL_ASSERT( rows() == (*rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( columns() == (*rhs).columns(), "Invalid number of columns");
const size_t jpos( columns() & size_t(-2) );
BLAZE_INTERNAL_ASSERT( ( columns() - ( columns() % 2UL ) ) == jpos, "Invalid end calculation" );
for (size_t k = 0UL; k < pages(); ++k)
{
for (size_t i = 0UL; i < rows(); ++i)
{
for (size_t j = 0UL; j < jpos; j += 2UL) {
(*this)(k, i, j) += (*rhs)(k, i, j);
(*this)(k, i, j + 1UL) += (*rhs)(k, i, j + 1UL);
}
if (jpos < columns()) {
(*this)(k, i, jpos) += (*rhs)(k, i, jpos);
}
}
}
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Default implementation of the subtraction assignment of a row-major dense tensor.
//
// \param rhs The right-hand side dense tensor to be subtracted.
// \return void
//
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side dense tensor
inline auto DilatedSubtensor<TT,true,CSAs...>::subAssign( const DenseTensor<TT2>& rhs )
{
BLAZE_INTERNAL_ASSERT( pages() == (*rhs).pages() , "Invalid number of pages" );
BLAZE_INTERNAL_ASSERT( rows() == (*rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( columns() == (*rhs).columns(), "Invalid number of columns");
const size_t jpos( columns() & size_t(-2) );
BLAZE_INTERNAL_ASSERT( ( columns() - ( columns() % 2UL ) ) == jpos, "Invalid end calculation" );
for (size_t k = 0UL; k < pages(); ++k)
{
for (size_t i = 0UL; i < rows(); ++i)
{
for (size_t j = 0UL; j < jpos; j += 2UL) {
(*this)(k, i, j) -= (*rhs)(k, i, j);
(*this)(k, i, j + 1UL) -= (*rhs)(k, i, j + 1UL);
}
if (jpos < columns()) {
(*this)(k, i, jpos) -= (*rhs)(k, i, jpos);
}
}
}
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Default implementation of the Schur product assignment of a row-major dense tensor.
//
// \param rhs The right-hand side dense tensor for the Schur product.
// \return void
//
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename TT // Type of the dense tensor
, size_t... CSAs > // Compile time DilatedSubtensor arguments
template< typename TT2 > // Type of the right-hand side dense tensor
inline auto DilatedSubtensor<TT,true,CSAs...>::schurAssign( const DenseTensor<TT2>& rhs )
{
BLAZE_INTERNAL_ASSERT( pages() == (*rhs).pages() , "Invalid number of pages" );
BLAZE_INTERNAL_ASSERT( rows() == (*rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( columns() == (*rhs).columns(), "Invalid number of columns");
const size_t jpos( columns() & size_t(-2) );
BLAZE_INTERNAL_ASSERT( ( columns() - ( columns() % 2UL ) ) == jpos, "Invalid end calculation" );
for (size_t k = 0UL; k < pages(); ++k)
{
for (size_t i = 0UL; i < rows(); ++i) {
for (size_t j = 0UL; j < jpos; j += 2UL) {
(*this)(k, i, j) *= (*rhs)(k, i, j);
(*this)(k, i, j + 1UL) *= (*rhs)(k, i, j + 1UL);
}
if (jpos < columns()) {
(*this)(k, i, jpos) *= (*rhs)(k, i, jpos);
}
}
}
}
/*! \endcond */
//*************************************************************************************************
} // namespace blaze
#endif
|
d0243bf99b4545fd53f330021b0ec2c414d17da6 | 903767e9e1bd7ae4c273621f2787e8e93ed38553 | /Codeforces/Div2/675/C.cpp | feeabacebe4112047def5cf46c843a4e2a5a2d28 | [] | no_license | itohdak/Competitive_Programming | 609e6a9e17a4fa21b8f3f7fc9bbc13204d7f7ac4 | e14ab7a92813755d97a85be4ead68620753a6d4b | refs/heads/master | 2023-08-04T08:57:55.546063 | 2023-08-01T21:09:28 | 2023-08-01T21:09:28 | 304,704,923 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,511 | cpp | C.cpp | #include <bits/stdc++.h>
#include <print.hpp>
using namespace std;
#define ll long long
#define ld long double
#define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)
#define RREP(i,m,n) for(int i=(int)(m); i>=(int)(n); i--)
#define rrep(i,n) RREP(i,(n)-1,0)
#define all(v) v.begin(), v.end()
#define endk '\n'
const int inf = 1e9+7;
const ll longinf = 1LL<<60;
const ll mod = 1e9+7;
const ld eps = 1e-10;
template<typename T1, typename T2> inline void chmin(T1 &a, T2 b){if(a>b) a=b;}
template<typename T1, typename T2> inline void chmax(T1 &a, T2 b){if(a<b) a=b;}
ll modpow(ll a, ll N) {
ll ans = 1;
ll tmp = a;
while(N > 0) {
if(N % 2 == 1) (ans *= tmp) %= mod;
(tmp *= tmp) %= mod;
N /= 2;
}
return ans;
}
ll modinv(ll a, ll m=mod) {
ll b = m, u = 1, v = 0;
while(b) {
ll t = a / b;
a -= t * b; swap(a, b);
u -= t * v; swap(u, v);
}
u %= m;
if(u < 0) u += m;
return u;
}
void solve() {
string s; cin >> s;
int n = s.size();
vector<ll> mul(n+1);
rep(i, n+1) mul[i] = modpow(10, i) * (i+1) % mod;
rep(i, n) (mul[i+1] += mul[i]) %= mod;
// cout << mul << endk;
ll ans = 0;
rep(i, n) {
ll m = (s[n-1-i]-'0');
(ans += m * (i ? mul[i-1] : 0) % mod) %= mod;
(ans += m * modpow(10, i) % mod * (n-i) % mod * (n-i-1) % mod * modinv(2) % mod) %= mod;
// cout << ans << endk;
}
cout << ans << endk;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int T = 1;
while(T--) solve();
return 0;
}
|
2db2dfde36db1150326d454cee1e0f81091ac441 | 334629c8e811baf9f72d0545fea95b35129d43fb | /mlog/impl/metadata.hpp | de475be058a69ecfbc0f43f5f921a25fe3431446 | [
"MIT"
] | permissive | xdmiodz/mlog | 4d0d3a2a0dec548fe77a9e4e281fcbdb0d316f3d | c00afe1ca75baa42eb362375dfb086821c5935f7 | refs/heads/master | 2020-12-25T13:08:19.582057 | 2014-04-13T18:06:54 | 2014-04-13T18:06:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,909 | hpp | metadata.hpp | /*
*
* Author: Philipp Zschoche
*
*/
#ifndef __METADATA_IPP__
#define __METADATA_IPP__
#include "../metadata.hpp"
#include <cstdio>
#if _MSC_VER
#define snprintf _snprintf_s
#endif
#include <string>
#include <sstream>
#include <cstring>
#include <chrono>
#include <cstdlib>
namespace mlog {
template <typename T> std::string thread_id_to_string(T &&thread_id) {
std::stringstream ss;
ss << thread_id;
return ss.str();
}
std::chrono::time_point<log_metadata::clocks> log_metadata::get_time() {
if (mlog::manager->use_time())
return clocks::now();
else
return std::chrono::time_point<log_metadata::clocks>();
}
std::thread::id log_metadata::get_thread_id() {
if (manager->use_thread_id()) {
return THREAD_GET_ID();
} else
return std::thread::id();
}
log_metadata::log_metadata(mlog_level &&lvl)
: level(std::move(lvl)), time(get_time()),
thread_id(get_thread_id()) {}
log_metadata::log_metadata(mlog_level &&lvl, log_position &&_position)
: level(std::move(lvl)), time(get_time()),
thread_id(get_thread_id()), position(_position) {}
log_metadata::log_metadata(mlog_level &&lvl, const log_position &_position)
: level(std::move(lvl)), time(get_time()),
thread_id(get_thread_id()), position(std::move(_position)) {}
std::string log_metadata::to_string(const std::string &end_string,
bool end_line) const {
static const std::size_t max_size = 512;
std::string result;
result.resize(max_size + end_string.size());
char *buffer = const_cast<char *>(result.c_str());
int len;
if (manager->use_time()) {
const std::time_t timet = clocks::to_time_t(time);
unsigned int ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
time.time_since_epoch()).count() -
timet * 1000000;
std::tm *tm = std::gmtime(&timet);
static int current_hour = -1;
static int local_factor = 0;
if (tm->tm_hour != current_hour) {
current_hour = tm->tm_hour;
tm = std::localtime(&timet);
local_factor = tm->tm_hour - current_hour;
} else {
tm->tm_hour += local_factor;
}
if (manager->use_thread_id()) {
if (position.has_value()) // 2012-11-02 15:24:04.345
// [file:line_number
// 24-0x7fff72ca8180]{warning}:
len = snprintf(
buffer, max_size,
"%04i-%02i-%02i %02i:%02i:%02i.%u [%s:%i %02i-%s]{%s}: ",
1900 + tm->tm_year, tm->tm_mon, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec, ms,
position.filename.c_str(),
position.line_number, manager->session(),
thread_id_to_string(thread_id).c_str(),
level_to_string(level).c_str());
else // 2012-11-02 15:24:04.345
// [24-0x7fff72ca8180]{warning}:
len = snprintf(buffer, max_size,
"%04i-%02i-%02i %02i:%02i:%02i.%u "
"[%02i-%s]{%s}: ",
1900 + tm->tm_year, tm->tm_mon,
tm->tm_mday, tm->tm_hour, tm->tm_min,
tm->tm_sec, ms, manager->session(),
thread_id_to_string(thread_id).c_str(),
level_to_string(level).c_str());
} else // 2012-11-02 15:24:04.345 [24]{warning}:
{
if (position.has_value()) {
len = snprintf(
buffer, max_size,
"%04i-%02i-%02i %02i:%02i:%02i.%u[%s:%i "
"%02i]{%s}: ",
1900 + tm->tm_year, tm->tm_mon, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec, ms,
position.filename.c_str(),
position.line_number, manager->session(),
level_to_string(level).c_str());
} else {
len = snprintf(buffer, max_size,
"%04i-%02i-%02i "
"%02i:%02i:%02i.%u[%02i]{%s}: ",
1900 + tm->tm_year, tm->tm_mon,
tm->tm_mday, tm->tm_hour, tm->tm_min,
tm->tm_sec, ms, manager->session(),
level_to_string(level).c_str());
}
}
} else if (manager->use_thread_id()) //[24-0x7fff72ca8180]{warning}:
{
if (position.has_value()) {
len = snprintf(buffer, max_size, "[%s:%i %02i-%s]{%s}: ",
position.filename.c_str(),
position.line_number, manager->session(),
thread_id_to_string(thread_id).c_str(),
level_to_string(level).c_str());
} else {
len = snprintf(buffer, max_size, "[%02i-%s]{%s}: ",
manager->session(),
thread_id_to_string(thread_id).c_str(),
level_to_string(level).c_str());
}
} else if (position.has_value()) {
len = snprintf(buffer, max_size, "[%s:%i %02i]{%s}: ",
position.filename.c_str(), position.line_number,
manager->session(), level_to_string(level).c_str());
} else //[24]{warning}:
{
len = snprintf(buffer, max_size, "[%02i]{%s}: ", manager->session(),
level_to_string(level).c_str());
}
if(len > max_size) {
len = max_size;
}
if (!end_string.empty()) {
memcpy(&buffer[len], end_string.c_str(), end_string.size());
len += end_string.size();
}
if (end_line) {
result.resize(len + 1);
//result[len] = '\r';
result[len] = '\n';
} else {
result.resize(len);
}
return result;
}
} /* mlog */
#endif
|
e5e4bdad21bc4107166addcc83b0463d39445339 | 64a87c62442df204132afa257304430712680bb0 | /math/ternary-search.cpp | b78631c589876c33bd0173cabf64e981fc83430f | [] | no_license | vutunganh/contest-programming-templates | 976a142508d38316f9f9ba3cceaa7be31cfc394c | 2f8d87cb89c1dcd8d9dc45123fa5922a3414a8ed | refs/heads/master | 2023-03-16T22:16:32.183180 | 2021-03-06T08:56:59 | 2021-03-06T08:57:58 | 345,048,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | cpp | ternary-search.cpp | // pustit jako tern(1, 1e9) apod
ld tern(ld l, ld r)
{
if (r - l < 1e-6)
return func((l + r) / 2);
ld lt = (2 * l + r) / 3;
ld rt = (l + 2 * r) / 3;
// flipnout na < pro maximum
if (func(lt) > func(rt))
return tern(lt, r);
else
return tern(l, rt);
}
|
64880b7a759b7f8cf5595298a25d441d380a7d46 | eaad2b7a64ed15872208ddbb1c0af7c49e537309 | /L5Root/l5_1/Map.cpp | d8c14ff3d50d36856d82dd489552308d9e7a9b77 | [] | no_license | ionut-mntn/Laboratoare-Structuri-de-Date-si-Algoritmi-Cpp | 069ea65282d16a6eff60731d5f0ef062ec6c3ac5 | 3a6f0d8de49c07ac520f36a81a0372e7dceed4df | refs/heads/master | 2023-03-12T12:45:42.634439 | 2021-03-02T16:35:07 | 2021-03-02T16:35:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,317 | cpp | Map.cpp | #include "Map.h"
#include "MapIterator.h"
#include <iostream>
using std::cout; // pt mn pt debugging
/*
void Map::afis_tabela(TElem* tabela)
{
for (int i = 0; i < m; i++)
cout << "(" << tabela[i].first << ", " << tabela[i].second << ") ";
cout << '\n';
}
*/
void Map::mark_empty(TElem* tabela)
{
for (int i = 0; i < m; i++)
tabela[i] = NULL_TELEM;
}
Map::Map() {
//TODO - Implementation
m = 15; // de dat mai mare aici? vad mai incolo...
//l = 0;
ht1 = new TElem[m]; mark_empty(ht1);
ht2 = new TElem[m]; mark_empty(ht2);
/* Functiile astea tin de implementarea mea! De aceea, nu cred ca trebuie sa am pointeri
la niste functii externe, care, eventual, sa fie initializati (pointerii la functii)
in constructor */
}
int Map::f1(TKey k) const { return k % m; } // ! sa nu te nedumereasca: TKey e doar un int!
int Map::f2(TKey k) const { return (k / m) % m; }
Map::~Map() {
//TODO - Implementation
}
TValue Map::add(TKey c, TValue v){
//TODO - Implementation
/*
if(l == ) // cred ca aici fac resize & rehash
doar daca am ciclu infinit (nuj daca sa mai tin variabila ai `l`)
momentan o las deoparte
*/
/*
Cum ramane complexitatea log n aici, daca, in cel mai rau caz:
facem o cautare prin toate cele m pozitii? ( avem 2 * m pozitii, dar s-a zis
in curs ca cele 2 tabele hash au mai mult de [m/2] pozitii libere)
Raspuns: Dupa cum scrie in curs,
faptul ca avem un factor de ocupare de maxim
0.5 si doua functii bine alese ( sper ca le-am ales bine, pentru ca le-am
luat triviale, ca in curs ) ne asigura ca:
1) e putin probabil ca mai mult de O(log n) elemente sa fie mutate
2) probabilitatea de a intalni un ciclu infinit este mica
*/
int poz_t1 = f1(c); // pozitie in tabela1
if (ht1[poz_t1] == NULL_TELEM) { ht1[poz_t1] = TElem(c, v); return NULL_TVALUE; }
/*
else
{
*/
/*
int poz_initiala2 = f2[c];
if (ht2[poz_initiala2] == NULL_TELEM) ht2[poz_initiala2] = TElem(c, v);
else
{
int poz_vizitate[m + 10]; /* in curs scrie ca cele doua tabele hash au maxim:
[m/2] elemente -aici era un comentariu inchis-//
poz_vizitate[0] = poz_initiala1;
poz_vizitate[1] = poz_initiala2;
int poz =
while()
}
*/
/*
int poz_t2 = f2(c);
if (ht2[poz_t2] == NULL_TELEM) ht2[poz_t2] = TElem(c, v);
}
*/
/*
int poz_vizitate[m + 10] = {}; // declar un array si pun pe prima
int poz = f2(c);
while(poz != )
*/
// int poz_vizitate[2 * m + 5] = {}; // initializez un array de zerouri (nuj daca e "declar" sau "initializez" )
int poz_Vizitate* = new int[2 * m + 5];
// int poz_precedenta =
//TElem* tabela = &t1;
//int poz = f1(c);
//while( !already_visited(poz) )
TKey current_key = c;
do
{
int poz_t1 = f1(current_key);
if (ht1[poz_t1] == NULL_TELEM) { ht1[poz_t1] = ; return NULL_TELEM; }
current_key =
int poz_t2 = f2()
} while ();
// return NULL_TVALUE;
}
bool Map::already_visited()
{
}
TValue Map::search(TKey c) const{
//TODO - Implementation
/*
ATENTIE! Daca un element exista intr-unul din cele 2 tabele, atunci cu siguranta exista
pe una dintre cele 2 pozitii posibile, date de functiile corespunzatoarei primei,
respectiv celei de a doua tabele. (initial am crezut ca atunci cand se impinge un
element dintr-o tabela in alta, este posibil ca acel element impins sa ajunga pe o
pozitie diferita
(de exemplu, cand un element se intoarce din tabela2 in tabela1, aces-
ta sa fie introdus pe o pozitie diferita decat anterioara din tabela1 pe care a fost
inserata)
de ce returneaza f1(elem) sau f2(elem), DAR (acum cred ca) EXACT ASTA E PRINCIPIUL
CUCKOO HASHING!)
*/
int poz1 = f1(c);
if (ht1[poz1] != NULL_TVALUE) return ht1[poz1].second;
int poz2 = f2(c);
if (ht2[poz2] != NULL_TVALUE) return ht2[poz2].second;
return NULL_TVALUE;
/*
daca initializez la inceput totul cu NULL_TVALUE, al doilea if puteam sa il scriu direct:
`` return ht2[poz2] `` sau, poate mai clar (poate nu neaparat "clar", dar pedagogic):
`` return ht2[poz2] != NULL_TVALUE ? ht2[poz2] : NULL_TVALUE ``
*/
}
TValue Map::remove(TKey c){
//TODO - Implementation
return NULL_TVALUE;
}
int Map::size() const {
//TODO - Implementation
return 0;
}
bool Map::isEmpty() const{
//TODO - Implementation
return false;
}
MapIterator Map::iterator() const {
return MapIterator(*this);
}
|
a6801ccd201c1b2fb6409a849f0054eaa23e96be | ce557019b3ab72eaa2bcfa0da561ac83aff27092 | /sources/src/internals/view/detail/QtWidgetManager.cpp | 0ce7fa88c8be02b03e267f8fc05b91e5f3cf66f3 | [] | no_license | stryku/icyus | cf4d5ea9dd13399f6a048de22d4aa09cbf26a216 | 7bdea99b824caa5821b3bf0189f2197685a318b7 | refs/heads/master | 2020-04-06T07:12:10.787952 | 2016-08-20T22:37:38 | 2016-08-20T22:37:38 | 65,685,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,777 | cpp | QtWidgetManager.cpp | #include <internals/view/detail/QtWidgetManager.hpp>
namespace Icyus
{
namespace View
{
namespace detail
{
QtWidgetManager::QtWidgetManager(QWidget *parent, const QString &uiFilePath) :
formWidget{ createWidget(parent, uiFilePath) },
controls{ extractControls(formWidget) }
{}
QString QtWidgetManager::getReceiverIp() const noexcept
{
return controls.receiverTab.labelIp->text();
}
void QtWidgetManager::setReceiverAddress(const std::string &address)
{
auto str = QString::fromStdString(address);
if (controls.senderTab.lineEditReceiverIp->text() != str)
controls.senderTab.lineEditReceiverIp->setText(str);
}
void QtWidgetManager::setFileToSendLabel(const QString &path)
{
controls.senderTab.labelFileToSend->setText(QString("%1: %2").arg("File to send",
path));
}
void QtWidgetManager::setSenderProgressBarBounds(int min, int max)
{
controls.senderTab.progressBar->setMinimum(min);
controls.senderTab.progressBar->setMaximum(max);
}
void QtWidgetManager::setSenderProgressBarValue(int value)
{
controls.senderTab.progressBar->setValue(value);
}
void QtWidgetManager::setSenderConnectedStatus(const QString &status)
{
controls.senderTab.labelConnectionStatus->setText(QString("%1: %2").arg("Connection status",
status));
}
void QtWidgetManager::setReceiverListeningStatus(const std::string &status)
{
controls.receiverTab.labelListeningStatus->setText(QString("%1: %2").arg("Listening status",
QString::fromStdString(status)));
}
void QtWidgetManager::setReceivingFileName(const QString &name)
{
controls.receiverTab.labelReceivingFile->setText(QString("%1: %2").arg("Receiving file",
name));
}
void QtWidgetManager::setReceiverProgressBarBounds(int min, int max)
{
controls.receiverTab.progressBar->setMinimum(min);
controls.receiverTab.progressBar->setMaximum(max);
}
void QtWidgetManager::setReceiverProgressBarValue(int value)
{
controls.receiverTab.progressBar->setValue(value);
}
QWidget* QtWidgetManager::getWidget()
{
return formWidget;
}
void QtWidgetManager::connectInputWithCallbacks(Icyus::Input::InputCallbacks &callbacks)
{
formWidget->connect(controls.senderTab.buttonChooseFile,
&QPushButton::clicked,
callbacks.chooseFile);
formWidget->connect(controls.senderTab.buttonSend,
&QPushButton::clicked,
callbacks.send);
formWidget->connect(controls.senderTab.buttonConnect,
&QPushButton::clicked,
callbacks.connect);
formWidget->connect(controls.senderTab.lineEditReceiverIp,
&QLineEdit::editingFinished,
[this, callbacks]
{
callbacks.newReceiverAddress(controls.senderTab.lineEditReceiverIp->text().toStdString());
});
formWidget->connect(controls.receiverTab.buttonStartReceiving,
&QPushButton::clicked,
callbacks.receiver.startListening);
}
QWidget* QtWidgetManager::loadUiFile(const QString &path, QWidget *parent) const //todo noexcept?
{
QUiLoader loader;
QFile file{ path };
file.open(QFile::ReadOnly);
auto widget = loader.load(&file, parent);
file.close();
return widget;
}
QWidget* QtWidgetManager::createWidget(QWidget *parent, const QString &uiFilePath) const //todo noexcept?
{
auto widget = loadUiFile(uiFilePath);
widget->setParent(parent);
return widget;
}
QtViewControls QtWidgetManager::extractControls(QWidget *widget) const noexcept
{
return{
extractSenderTabControls(widget),
extractReceiverTabControls(widget)
};
}
QtViewControls::SenderTabControls QtWidgetManager::extractSenderTabControls(QWidget *widget) const noexcept
{
QtViewControls::SenderTabControls controls;
controls.labelConnectionStatus = widget->findChild<QLabel*>("labelConnectionStatus");
controls.labelFileToSend = widget->findChild<QLabel*>("labelFileToSend");
controls.progressBar = widget->findChild<QProgressBar*>("progressBarSender");
controls.lineEditReceiverIp = widget->findChild<QLineEdit*>("lineEditReceiverIp");
controls.buttonChooseFile = widget->findChild<QPushButton*>("pushButtonChooseFileToSend");
controls.buttonSend = widget->findChild<QPushButton*>("pushButtonSend");
controls.buttonConnect = widget->findChild<QPushButton*>("pushButtonConnect");
return controls;
}
QtViewControls::ReceiverTabControls QtWidgetManager::extractReceiverTabControls(QWidget *widget) const noexcept
{
QtViewControls::ReceiverTabControls controls;
controls.labelIp = widget->findChild<QLabel*>("labelReceiverIp");
controls.labelListeningStatus = widget->findChild<QLabel*>("labelListeningStatus");
controls.progressBar = widget->findChild<QProgressBar*>("progressBarReceiver");
controls.labelReceivingFile = widget->findChild<QLabel*>("labelReceivinFile");
controls.buttonStartReceiving = widget->findChild<QPushButton*>("pushButtonStartListening");
return controls;
}
}
}
} |
a9350295eb78cb9ac0cb4c2cf4e64745daed8579 | 614cece4b50a8cd257dd74f3ce6f7c39b6406387 | /converter/OutputWriter.cpp | cd55b30a0bad17c897c2a127d0ff28ccecd9ecbb | [] | no_license | AlekNS/skironscrapper | 31157cb09a878020762be1d71c6c93aa883215f3 | ff0727a654aa2de1180431205d4f69c97d8e0827 | refs/heads/master | 2021-04-03T07:22:45.020120 | 2017-08-04T01:30:52 | 2017-08-04T01:30:52 | 124,735,314 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,104 | cpp | OutputWriter.cpp | #include "OutputWriter.h"
#include <sstream>
#include <iomanip>
#include <sys/stat.h>
#include <libwgf3/wgf3.h>
bool ensurePath(const std::string path, mode_t mode = 0776) {
std::istringstream ss(path);
std::string token;
struct stat st;
std::string checkPath("");
while(std::getline(ss, token, '/')) {
checkPath.append(token);
checkPath.append("/");
if(stat(checkPath.c_str(), &st) != 0 && mkdir(checkPath.c_str(), mode) != 0 && errno != EEXIST) {
return false;
}
}
return true;
}
OutputWriter::OutputWriter(const std::string &path): outputPath(path), isDebugging(false) {
}
struct fillandw
{
fillandw( char f, int w )
: fill(f), width(w) {}
char fill;
int width;
};
std::ostream& operator<<( std::ostream& o, const fillandw& a )
{
o.fill(a.fill);
o.width(a.width);
return o;
}
std::string ensureConversionPathForLayer(tm timestamp, const std::string &outputPath) {
std::ostringstream pathToSave;
time_t timestampAsEpoch = mktime(×tamp);
pathToSave << outputPath;
if (outputPath[outputPath.size() - 1] != '/') {
pathToSave << "/";
}
// without usage of sprintf_s
pathToSave << fillandw('0', 2) << timestamp.tm_mday << "-";
pathToSave << fillandw('0', 2) << timestamp.tm_mon << "-" << timestamp.tm_year;
pathToSave << "-";
pathToSave << fillandw('0', 2) << timestamp.tm_hour << "_" << timestampAsEpoch << "/";
if (!ensurePath(pathToSave.str())) {
throw std::runtime_error("Can't create output folder");
}
return pathToSave.str();
}
void OutputWriter::writeLayer(const FormatReaderAdapter::Layer &layer) {
std::string wgf3Path = ensureConversionPathForLayer(layer.timestamp, outputPath);
switch(layer.parameter) {
case FormatReaderAdapter::Parameter::UWIND:
wgf3Path.append("UGRD.wgf3");
break;
case FormatReaderAdapter::Parameter::VWIND:
wgf3Path.append("VGRD.wgf3");
break;
default:
throw std::runtime_error("Passed unknown parameter");
}
WGF3 wgf3;
wgf3.open(wgf3Path.c_str(),
static_cast<int>(layer.minLat * 1000), static_cast<int>(layer.maxLat * 1000),
static_cast<int>(layer.minLon * 1000), static_cast<int>(layer.maxLon * 1000),
static_cast<int>(layer.dLat * 1000), static_cast<int>(layer.dLon * 1000),
static_cast<float>(layer.zeroValue),
false
);
double lat, lon = layer.minLon;
for(int y = 0; y < layer.sizeY; y += 1) {
lon = layer.minLon;
for(int x = 0; x < layer.sizeX; x += 1) {
wgf3.writeAvgF(static_cast<float>(lat), static_cast<float>(lon), static_cast<float>(layer.data[y][x]));
lon += layer.dLon;
}
lat += layer.dLat;
}
if (isDebugging) {
wgf3Path.append(".bmp");
wgf3.drawToBitmap(wgf3Path.c_str(), 3.0f);
}
wgf3.close();
}
void OutputWriter::setDebugging(bool isEnabled) {
isDebugging = isEnabled;
}
|
3edff2f5640638eba9f0b95101f303b62eb673e7 | b1333c5f06fe1672471c01057bb2e6409279746e | /HelloCpp/Classes/scene3DLayer.cpp | 4bfd0ea62efb195eeec95cfbef10b0617b0d0499 | [] | no_license | wantnon/cocos2d-x-3d | 2c8f07e90af751d2abcec2e497fbcc0637b7265b | 995766333b60bfd580ee000d43ae2bb08d46ede2 | refs/heads/master | 2021-01-21T12:26:18.680899 | 2014-01-01T04:22:29 | 2014-01-01T04:22:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,582 | cpp | scene3DLayer.cpp | //
// scene3DLayer.cpp
// HelloCpp
//
// Created by ck02-084 on 13-11-6.
//
//
#include "scene3DLayer.h"
bool Cscene3DLayer::init(){
//enable touch
setTouchEnabled( true );
//add 3d obj to layer
Cobj3D*obj=new Cobj3D();
obj->init("logo.png");
obj->setAnchorPoint(ccp(0,0));
obj->setPosition(ccp(0,0));
this->addChild(obj,1);
pObjList.push_back(obj);
obj->release();
//update eye pos
updateEyePos();
//set camera
//here we set the camera, and in visit(), cocos2d-x will call camera->locate() to apply the camera matrix to matrix stack.
CCCamera*camera=this->getCamera();
camera->setEyeXYZ(20, 10, 20);
camera->setCenterXYZ(0, 0, 0);
camera->setUpXYZ(0, 1, 0);
return true;
}
void Cscene3DLayer::visit(){
//set projection
CCDirector::sharedDirector()->setProjection(kCCDirectorProjection3D);
//because in CCDirector::setProjection, the modelview matrix is modified, so here we reset it
kmGLMatrixMode(KM_GL_MODELVIEW);
kmGLLoadIdentity();
//enable depth test
CCDirector::sharedDirector()->setDepthTest(true);
//call CCLayer's visit
CCLayer::visit();
}
void Cscene3DLayer::updateEyePos(){
float cosA=cosf(A*M_PI/180);
float sinA=sinf(A*M_PI/180);
float cosB=cosf(B*M_PI/180);
float sinB=sinf(B*M_PI/180);
eyePos.x=r*cosB*sinA;
eyePos.y=r*sinB;
eyePos.z=r*cosB*cosA;
eyePos.w=1;
}
void Cscene3DLayer::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint loc_winSpace = touch->getLocationInView();
//----update mos
mosxf=mosx;
mosyf=mosy;
mosx=loc_winSpace.x;
mosy=loc_winSpace.y;
}
}
void Cscene3DLayer::ccTouchesMoved(cocos2d::CCSet* touches , cocos2d::CCEvent* event)
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint loc_winSpace = touch->getLocationInView();
//----update mos
mosxf=mosx;
mosyf=mosy;
mosx=loc_winSpace.x;
mosy=loc_winSpace.y;
//----update eyePos
A+=-(mosx-mosxf)*0.4;
B+=(mosy-mosyf)*0.4;
updateEyePos();
this->getCamera()->setEyeXYZ(eyePos.x, eyePos.y, eyePos.z);
}
}
void Cscene3DLayer::ccTouchesBegan(CCSet* touches, CCEvent* event)
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint loc_winSpace = touch->getLocationInView();
CCLOG("loc_winSpace:%f,%f",loc_winSpace.x,loc_winSpace.y);
//now because in 3d mode, so convertToGL coordinate's result is not as in 2D.
// CCPoint loc_GLSpace = CCDirector::sharedDirector()->convertToGL(loc_winSpace);
// CCLOG("loc_GLSpace:%f,%f",loc_GLSpace.x,loc_GLSpace.y);
//----update mos
mosxf=mosx;
mosyf=mosy;
mosx=loc_winSpace.x;
mosy=loc_winSpace.y;
}
}
|
deab36bb747893917939f4c0cddc7ca9b92f4d5b | cd3eb264a9e1f61f69a692ed12bdafa476ad5cf4 | /tst/testHTMLCommandParser.cpp | e0541a403565410e2173911e0643361aa7aa5fe4 | [
"MIT"
] | permissive | nerds-odd-e/mahjong | be5b63077ba6347e92f14dea0ee9e4a2eb6ed1f6 | e4fa21cc68b869394d123e0fa0957d0c7e4d70aa | refs/heads/master | 2022-12-23T19:56:14.877008 | 2019-12-02T09:12:57 | 2019-12-02T09:12:57 | 218,472,201 | 6 | 0 | NOASSERTION | 2022-12-13T05:58:22 | 2019-10-30T07:55:24 | C++ | UTF-8 | C++ | false | false | 3,360 | cpp | testHTMLCommandParser.cpp | #include <queue>
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include "HTMLCommandParser.h"
#include "MahjongCommand.h"
#include <typeinfo>
#include "mocks.h"
TEST_GROUP(HTMLCommandParser) {
MockHTMLMahjongGameServer server;
HTMLCommandParser *parser;
MahjongCommand *cmd;
void setup() {
cmd = NULL;
parser = new HTMLCommandParser(&server);
}
void teardown() {
delete cmd;
delete parser;
}
};
TEST(HTMLCommandParser, parse_start_new) {
cmd = parser->parse("/join", "");
STRCMP_EQUAL(typeid(MJCommandNewPlayerJoin).name(), typeid(*cmd).name());
}
TEST(HTMLCommandParser, parse_bye) {
cmd = parser->parse("/3/bye", "");
STRCMP_EQUAL(typeid(MJCommandQuitGame).name(), typeid(*cmd).name());
}
TEST(HTMLCommandParser, parse_shutdown) {
cmd = parser->parse("/shutdown", "");
STRCMP_EQUAL(typeid(MJCommandShutdownServer).name(), typeid(*cmd).name());
}
TEST(HTMLCommandParser, restart) {
Settings settings;
UserPerspective game( settings);
mock().expectOneCall("getGameByID").onObject(&server).withParameter(
"gameID", 3).andReturnValue(&game);
cmd = parser->parse("/3/start", "");
STRCMP_EQUAL(typeid(MJCommandStartNewGame).name(), typeid(*cmd).name());
}
TEST(HTMLCommandParser, game_does_not_exist) {
mock().expectOneCall("getGameByID").onObject(&server).withParameter(
"gameID", 4).andReturnValue((void *)NULL);
cmd = parser->parse("/4/start", "");
STRCMP_EQUAL(typeid(MJCommandDoesNotExist).name(), typeid(*cmd).name());
}
TEST(HTMLCommandParser, MJCommandDiscard) {
Settings settings;
UserPerspective game( settings);
mock().expectOneCall("getGameByID").onObject(&server).withParameter(
"gameID", 3).andReturnValue(&game);
cmd = parser->parse("/3/discard", "5");
STRCMP_EQUAL(typeid(MJCommandDiscard).name(), typeid(*cmd).name());
}
TEST(HTMLCommandParser, MJCommandPick) {
Settings settings;
UserPerspective game( settings);
mock().expectOneCall("getGameByID").onObject(&server).withParameter(
"gameID", 3).andReturnValue(&game);
cmd = parser->parse("/3/pick", "");
STRCMP_EQUAL(typeid(MJCommandPick).name(), typeid(*cmd).name());
}
TEST(HTMLCommandParser, MJCommandChow) {
Settings settings;
UserPerspective game( settings);
mock().expectOneCall("getGameByID").onObject(&server).withParameter(
"gameID", 3).andReturnValue(&game);
cmd = parser->parse("/3/chow", "2");
STRCMP_EQUAL(typeid(MJCommandChow).name(), typeid(*cmd).name());
}
TEST(HTMLCommandParser, MJCommandPong) {
Settings settings;
UserPerspective game( settings);
mock().expectOneCall("getGameByID").onObject(&server).withParameter(
"gameID", 3).andReturnValue(&game);
cmd = parser->parse("/3/pong", "");
STRCMP_EQUAL(typeid(MJCommandPong).name(), typeid(*cmd).name());
}
TEST(HTMLCommandParser, MJCommandKong) {
Settings settings;
UserPerspective game( settings);
mock().expectOneCall("getGameByID").onObject(&server).withParameter(
"gameID", 3).andReturnValue(&game);
cmd = parser->parse("/3/kong", "2");
STRCMP_EQUAL(typeid(MJCommandKong).name(), typeid(*cmd).name());
}
TEST(HTMLCommandParser, MJCommandWin) {
Settings settings;
UserPerspective game( settings);
mock().expectOneCall("getGameByID").onObject(&server).withParameter(
"gameID", 3).andReturnValue(&game);
cmd = parser->parse("/3/win", "");
STRCMP_EQUAL(typeid(MJCommandWin).name(), typeid(*cmd).name());
}
|
5d274e5fe4a4e7159450fcec6853fb1fcf93d86e | 34b8f336a5f6e5bfa36bcaca712647f423d94bfc | /active_3d_planning_core/src/module/back_tracker/reverse.cpp | c9226c7279c3a6a6f9d84ed900cc02770dad3741 | [
"BSD-3-Clause"
] | permissive | ethz-asl/mav_active_3d_planning | db1f1ee8698b2cf62d46a6a675e299eb0a33e15d | 14c2b4d140ac0c653410f0956d206292a21dd488 | refs/heads/master | 2023-07-15T22:52:26.774623 | 2022-07-05T15:15:04 | 2022-07-05T15:15:04 | 154,641,455 | 439 | 99 | BSD-3-Clause | 2023-05-30T20:11:30 | 2018-10-25T09:05:47 | C++ | UTF-8 | C++ | false | false | 2,389 | cpp | reverse.cpp | #include "active_3d_planning_core/module/back_tracker/reverse.h"
#include <string>
#include "active_3d_planning_core/tools/defaults.h"
namespace active_3d_planning {
namespace back_tracker {
// Reverse
ModuleFactoryRegistry::Registration<Reverse> Reverse::registration("Reverse");
Reverse::Reverse(PlannerI& planner) : BackTracker(planner) {}
bool Reverse::segmentIsExecuted(const TrajectorySegment& segment) {
// Don't track backtracking segments
if (segment.trajectory.back().position_W == last_position_ &&
segment.trajectory.back().getYaw() == last_yaw_) {
return true;
}
// Register segments
if (stack_.size() == stack_size_) {
for (int i = 0; i < stack_size_ - 1; ++i) {
stack_[i] = stack_[i + 1];
}
stack_[stack_size_ - 1] = segment.trajectory;
} else {
stack_.push_back(segment.trajectory);
}
return true;
}
bool Reverse::trackBack(TrajectorySegment* target) {
// Maximum rotations in place reached, time to reverse last segment
if (stack_.empty()) {
// Nothing to reverse
return false;
} else {
// Reverse last trajectory
return reverse(target);
}
}
bool Reverse::reverse(TrajectorySegment* target) {
// Reverse the last registered segment.
EigenTrajectoryPointVector to_reverse = stack_.back();
std::reverse(to_reverse.begin(), to_reverse.end());
int64_t current_time = 0;
TrajectorySegment* new_segment = target->spawnChild();
for (int i = 1; i < to_reverse.size(); ++i) {
EigenTrajectoryPoint trajectory_point;
trajectory_point.position_W = to_reverse[i].position_W;
trajectory_point.setFromYaw(
defaults::angleScaled(to_reverse[i].getYaw() + M_PI));
current_time +=
to_reverse[i - 1].time_from_start_ns - to_reverse[i].time_from_start_ns;
trajectory_point.time_from_start_ns = current_time;
new_segment->trajectory.push_back(trajectory_point);
}
last_yaw_ = new_segment->trajectory.back().getYaw();
last_position_ = new_segment->trajectory.back().position_W;
stack_.pop_back();
return true;
}
void Reverse::setupFromParamMap(Module::ParamMap* param_map) {
setParam<int>(param_map, "stack_size", &stack_size_, 10);
stack_.reserve(stack_size_);
}
bool Reverse::checkParamsValid(std::string* error_message) {
return BackTracker::checkParamsValid(error_message);
}
} // namespace back_tracker
} // namespace active_3d_planning
|
950742ed40899e45e5e09b6464d68fb10b0d0773 | a9c359681631e8344f55163a2d69018ed02c0a90 | /openr/decision/RibEntry.h | 3ff6d987e4f8b840d340cd7660050ff7d0ede1d9 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | facebook/openr | 66c82707ae47fa5ed711c20f0355ad7100a3cf1c | 8e4c6e553f0314763c1595dd6097dd578d771f1c | refs/heads/main | 2023-09-03T02:55:03.399114 | 2023-07-26T16:46:46 | 2023-07-26T16:46:46 | 108,306,129 | 936 | 295 | MIT | 2023-08-31T23:03:31 | 2017-10-25T17:59:53 | C++ | UTF-8 | C++ | false | false | 5,909 | h | RibEntry.h | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "openr/if/gen-cpp2/Network_types.h"
#include <folly/IPAddress.h>
#include <openr/common/NetworkUtil.h>
#include <openr/if/gen-cpp2/Network_types.h>
#include <openr/if/gen-cpp2/OpenrCtrl.h>
#include <openr/if/gen-cpp2/Types_types.h>
namespace openr {
struct RibEntry {
// TODO: should this be map<area, nexthops>?
std::unordered_set<thrift::NextHopThrift> nexthops;
// igp cost of all routes (ecmp) or of lowest cost route (if ucmp)
unsigned int igpCost;
// constructor
explicit RibEntry(
std::unordered_set<thrift::NextHopThrift> nexthops,
unsigned int igpCost = 0)
: nexthops(std::move(nexthops)), igpCost(igpCost) {}
RibEntry() = default;
bool
operator==(const RibEntry& other) const {
return nexthops == other.nexthops;
}
};
struct RibUnicastEntry : RibEntry {
folly::CIDRNetwork prefix;
thrift::PrefixEntry bestPrefixEntry;
std::string bestArea;
// install to fib or not
bool doNotInstall{false};
// Counter Id assigned to this route. Assignment comes from the
// RibPolicyStatement that matches to this route.
std::optional<thrift::RouteCounterID> counterID{std::nullopt};
bool localRouteConsidered{false};
// constructor
explicit RibUnicastEntry() {}
explicit RibUnicastEntry(const folly::CIDRNetwork& prefix) : prefix(prefix) {}
RibUnicastEntry(
const folly::CIDRNetwork& prefix,
std::unordered_set<thrift::NextHopThrift> nexthops)
: RibEntry(std::move(nexthops)), prefix(prefix) {}
RibUnicastEntry(
const folly::CIDRNetwork& prefix,
std::unordered_set<thrift::NextHopThrift> nexthops,
thrift::PrefixEntry bestPrefixEntryThrift,
const std::string& bestArea,
bool doNotInstall = false,
unsigned int igpCost = 0,
const std::optional<int64_t>& ucmpWeight = std::nullopt,
bool localRouteConsidered = false)
: RibEntry(std::move(nexthops), igpCost),
prefix(prefix),
bestPrefixEntry(std::move(bestPrefixEntryThrift)),
bestArea(bestArea),
doNotInstall(doNotInstall),
localRouteConsidered(localRouteConsidered) {
bestPrefixEntry.weight().from_optional(ucmpWeight);
}
bool
operator==(const RibUnicastEntry& other) const {
return prefix == other.prefix && bestPrefixEntry == other.bestPrefixEntry &&
doNotInstall == other.doNotInstall && counterID == other.counterID &&
localRouteConsidered == other.localRouteConsidered &&
RibEntry::operator==(other);
}
bool
operator!=(const RibUnicastEntry& other) const {
return !(*this == other);
}
// TODO: rename this func
thrift::UnicastRoute
toThrift() const {
thrift::UnicastRoute tUnicast;
tUnicast.dest() = toIpPrefix(prefix);
tUnicast.nextHops() =
std::vector<thrift::NextHopThrift>(nexthops.begin(), nexthops.end());
tUnicast.counterID().from_optional(counterID);
return tUnicast;
}
// TODO: rename this func
thrift::UnicastRouteDetail
toThriftDetail() const {
thrift::UnicastRouteDetail tUnicastDetail;
tUnicastDetail.unicastRoute() = toThrift();
tUnicastDetail.bestRoute() = bestPrefixEntry;
return tUnicastDetail;
}
};
struct RibMplsEntry : RibEntry {
int32_t label{0};
explicit RibMplsEntry(int32_t label) : label(label) {}
// constructor
explicit RibMplsEntry() {}
RibMplsEntry(
int32_t label, std::unordered_set<thrift::NextHopThrift> nexthops)
: RibEntry(std::move(nexthops)), label(label) {}
static RibMplsEntry
fromThrift(const thrift::MplsRoute& tMpls) {
return RibMplsEntry(
*tMpls.topLabel(),
std::unordered_set<thrift::NextHopThrift>(
tMpls.nextHops()->begin(), tMpls.nextHops()->end()));
}
bool
operator==(const RibMplsEntry& other) const {
return label == other.label && RibEntry::operator==(other);
}
bool
operator!=(const RibMplsEntry& other) const {
return !(*this == other);
}
thrift::MplsRoute
toThrift() const {
thrift::MplsRoute tMpls;
tMpls.topLabel() = label;
tMpls.nextHops() =
std::vector<thrift::NextHopThrift>(nexthops.begin(), nexthops.end());
return tMpls;
}
thrift::MplsRouteDetail
toThriftDetail() const {
thrift::MplsRouteDetail tMplsDetail;
tMplsDetail.mplsRoute() = toThrift();
return tMplsDetail;
}
/**
* MPLS Action can be specified per next-hop. However, HW can only specify a
* single action on a next-hop group. For this reason we filter next-hops
* to a unique MPLS action.
*/
void
filterNexthopsToUniqueAction() {
// Optimization for single nexthop case. POP_AND_LOOKUP is supported by
// this optimization
if (nexthops.size() <= 1) {
return;
}
// Deduce a unique MPLS action
thrift::MplsActionCode mplsActionCode{thrift::MplsActionCode::SWAP};
for (auto const& nextHop : nexthops) {
CHECK(nextHop.mplsAction().has_value());
auto& action = *nextHop.mplsAction()->action();
// Action can't be push (we don't push labels in MPLS routes)
// or POP with multiple nexthops. It must be either SWAP or PHP
CHECK(
action == thrift::MplsActionCode::SWAP or
action == thrift::MplsActionCode::PHP);
if (action == thrift::MplsActionCode::PHP) {
mplsActionCode = thrift::MplsActionCode::PHP;
}
}
// Filter nexthop that do not match selected MPLS action
for (auto it = nexthops.begin(); it != nexthops.end();) {
if (mplsActionCode != *it->mplsAction()->action()) {
it = nexthops.erase(it);
} else {
++it;
}
}
}
};
} // namespace openr
|
610444ee3a4195a6822f060955a0e98f5799a5cd | 57cd99b1d05b5b59c715a87ac52cb98154141281 | /BrolsmaJesse_Opdracht6_v1/BrolsmaJesse_Opdracht6_v1/Koffer.h | 4708ab5a79c285e5eda65f08c5692e80016d1a21 | [] | no_license | KaktusPai/JesseBrolsma_C_Plus_Plus | 1be0d3a8a453af01db8bed0b497fbcda9c5c4b30 | 0055fd9d9d1457cddcbf217a603987f6fa6b36c3 | refs/heads/master | 2022-12-31T20:00:19.563503 | 2020-10-23T21:32:28 | 2020-10-23T21:32:28 | 299,435,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 279 | h | Koffer.h | #pragma once
#include <string>
#include "Sokken.h"
class Koffer {
public:
Koffer(std::string klr);
Koffer(const Koffer& k);
Koffer& operator=(const Koffer& k);
void sokkenInKoffer(Sokken& s);
Sokken* sokken = nullptr;
std::string kleur = "grijs";
~Koffer();
};
|
aa30f1fcc7635c7e08bda6bc209036b97849c3f3 | 70cdf389c2bc8f0b34e8f6d461b3dae7c52af549 | /openlf_circuits/components/comp_number_viewer.h | 374fea32c785d40431566b96f471ae1a4c90b2d8 | [] | no_license | LIZECHUAN/openlf | 526839545414c59d9584f78c11aa282ab5c34869 | fe907092f23f9457e151f36e2faa6ea41e4cef43 | refs/heads/master | 2020-05-31T07:27:43.838912 | 2015-09-23T14:44:15 | 2015-09-23T14:44:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,062 | h | comp_number_viewer.h | /*
* Copyright (c) 2015 Heidelberg Colaboratory for Image Processing
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Author Maximilian Diebold
*/
#pragma once
#ifndef COMP_NUMBER_VIEWER_H
#define COMP_NUMBER_VIEWER_H
#include "DSPatch.h"
#include <iostream>
#include "gui/includes/QtpComp.h"
class SignalPrinter : public DspComponent
{
private:
QtpComp::CompInfo *info;
public:
// 2. Configure component IO buses
// ===============================
SignalPrinter(){
AddInput_("input");
};
QtpComp::CompInfo *getCompInfo(const char *name){
info = new QtpComp::CompInfo;
info->typeId = 1;
info->typeName = QString(name);
info->inPins << "input";
info->outPins;
return info;
}
protected:
// 3. Implement virtual Process_() method
// ======================================
virtual void Process_(DspSignalBus& inputs, DspSignalBus& outputs){
vigra::MultiArray<2, UINT8> imageArray1;
inputs.GetValue(0, imageArray1);
std::cout << "Output Signal: " << imageArray1.shape() << std::endl;
};
};
#endif // COMP_NUMBER_VIEWER_H |
e903cca6ae904a39383019d16978e359312b35d8 | 0a1d0f4a38cb5c20d68f81738c2ff886ea435701 | /DuckGame/DuckGame/Vector2D.cpp | 722cd6a08a3372c43ed73ecc34ca3aa6f2520a7e | [] | no_license | shxwnx/cg-projekt | 8c5864a7c9374a7b118a3d0ee2b49f0250becf90 | 5ee66ee334feb1685f4612975f56c30748fab279 | refs/heads/master | 2020-03-23T07:40:03.061456 | 2018-09-03T08:22:54 | 2018-09-03T08:22:54 | 141,284,649 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,362 | cpp | Vector2D.cpp | #include "Vector2D.h"
#include <assert.h>
#include <math.h>
Vector2D::Vector2D(float x, float y) : X(x), Y(y)
{
}
Vector2D::Vector2D()
{
}
float Vector2D::dot(const Vector2D& v) const
{
float f = X * v.X + Y * v.Y;
return f;
}
float Vector2D::cross(const Vector2D& v) const
{
return X * v.Y - v.X * Y;
}
Vector2D Vector2D::operator+(const Vector2D& v) const
{
float tempX = X + v.X;
float tempY = Y + v.Y;
return Vector2D(tempX, tempY);
}
Vector2D Vector2D::operator-(const Vector2D& v) const
{
float tempX = X - v.X;
float tempY = Y - v.Y;
return Vector2D(tempX, tempY);
}
Vector2D Vector2D::operator*(float c) const
{
float tempX = c * X;
float tempY = c * Y;
return Vector2D(tempX, tempY);
}
Vector2D Vector2D::operator/(float c) const
{
float tempX = X / c;
float tempY = Y / c;
return Vector2D(tempX, tempY);
}
Vector2D Vector2D::operator-() const
{
return Vector2D(-X, -Y);
}
Vector2D& Vector2D::operator+=(const Vector2D& v)
{
X = X + v.X;
Y = Y + v.Y;
return *this;
}
Vector2D& Vector2D::operator=(const Vector2D& v)
{
X = v.X;
Y = v.Y;
return *this;
}
Vector2D& Vector2D::normalize()
{
float length = this->length();
X = X / length;
Y = Y / length;
return *this;
}
float Vector2D::length() const
{
return sqrt(this->lengthSquared());
}
float Vector2D::lengthSquared() const
{
return X * X + Y * Y;
}
|
ac2582d55e83b6d8a5cc14debecc1ec5a7a4367e | f654df6c38b5b1f32e7f34d4a86a47e13ecfe3d0 | /preview/preview_area.h | 71fcf2db01fabeb876fcafe7e87ac9a964e113d8 | [
"MIT"
] | permissive | emako/qvs | 267dabb75aa862cf0ad62df20049f3ca66c5adcd | 87dd9da0badcb526375609a4a65d8cb59a93436e | refs/heads/master | 2022-03-15T11:00:39.718763 | 2022-03-11T23:15:33 | 2022-03-11T23:15:33 | 144,843,697 | 45 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,443 | h | preview_area.h | #ifndef PREVIEWAREA_H
#define PREVIEWAREA_H
#include <QScrollArea>
#include <QPixmap>
#include <QPoint>
class QLabel;
class ScrollNavigator;
class QKeyEvent;
class QWheelEvent;
class QMouseEvent;
class PreviewArea : public QScrollArea
{
Q_OBJECT
public:
PreviewArea(QWidget * a_pParent = nullptr);
virtual ~PreviewArea();
void setWidget(QWidget * a_pWidget) = delete;
const QPixmap * pixmap() const;
void setPixmap(const QPixmap & a_pixmap);
void checkMouseOverPreview(const QPoint & a_globalMousePos);
QLabel *previewArea(void);
public slots:
void slotScrollLeft();
void slotScrollRight();
void slotScrollTop();
void slotScrollBottom();
protected:
void resizeEvent(QResizeEvent * a_pEvent) override;
void keyPressEvent(QKeyEvent * a_pEvent) override;
void wheelEvent(QWheelEvent * a_pEvent) override;
void mousePressEvent(QMouseEvent * a_pEvent) override;
void mouseMoveEvent(QMouseEvent * a_pEvent) override;
void mouseReleaseEvent(QMouseEvent * a_pEvent) override;
signals:
void signalSizeChanged();
void signalCtrlWheel(QPoint a_angleDelta);
void signalMouseMiddleButtonReleased();
void signalMouseRightButtonReleased();
void signalMouseOverPoint(float a_normX, float a_normY);
private:
void drawScrollNavigator();
QLabel * m_pPreviewLabel;
ScrollNavigator * m_pScrollNavigator;
bool m_draggingPreview;
QPoint m_lastCursorPos;
QPoint m_lastPreviewLabelPos;
};
#endif // PREVIEWAREA_H
|
f18f728ba09f82815f367f6ab5e47244333a67cc | 6b8c3974d3ce5f7841e51dcb406666c0c5d92155 | /vtn/coordinator/modules/odcdriver/odc_kt_utils.cc | 1cccbad5f441a9954ea6a9282ef931db340f8702 | [] | no_license | swjang/cloudexchange | bbbf78a2e7444c1070a55378092c17e8ecb27059 | c06ed54f38daeff23166fb0940b27df74c70fc3e | refs/heads/master | 2020-12-29T03:18:43.076887 | 2015-09-21T07:13:22 | 2015-09-21T07:13:22 | 42,845,532 | 1 | 1 | null | 2015-09-21T07:13:22 | 2015-09-21T05:19:35 | C++ | UTF-8 | C++ | false | false | 22,054 | cc | odc_kt_utils.cc | /*
* Copyright (c) 2014 NEC Corporation
* All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
*/
#include <odc_kt_utils.hh>
#include <string>
#include <set>
namespace unc {
namespace odcdriver {
class vtn_read_resp_parser
: public unc::restjson::json_array_object_parse_util {
public:
std::set <std::string> *vtnnames_;
vtn_read_resp_parser(json_object* jobj,
std::set <std::string> *vtnset) :
json_array_object_parse_util(jobj), vtnnames_(vtnset) {}
int start_array_read(int length_of_array,
json_object* json_instance) {
ODC_FUNC_TRACE;
return unc::restjson::REST_OP_SUCCESS;
}
int read_array_iteration(uint32_t index,
json_object* json_instance) {
ODC_FUNC_TRACE;
std::string vtn_name("");
std::string name_search("name");
int ret(unc::restjson::json_object_parse_util::
read_string(json_instance,
name_search,
vtn_name));
if (ret == unc::restjson::REST_OP_SUCCESS) {
pfc_log_info("vtn name %s", vtn_name.c_str());
vtnnames_->insert(vtn_name);
pfc_log_info("Read instance success ");
return unc::restjson::REST_OP_SUCCESS;
}
return unc::restjson::REST_OP_FAILURE;
}
int end_array_read(uint32_t index,
json_object* json_instance) {
ODC_FUNC_TRACE;
return unc::restjson::REST_OP_SUCCESS;
}
};
class port_info_resp_parser
: public unc::restjson::json_array_object_parse_util {
public:
std::string match_id_;
std::string port_name_;
port_info_resp_parser(json_object *array) :
json_array_object_parse_util(array),
match_id_(""), port_name_("") {}
std::string get_port_name() {
return port_name_;
}
void set_match_id(std::string match) {
match_id_= match;
}
int start_array_read(int length_of_array,
json_object* json_instance) {
ODC_FUNC_TRACE;
return unc::restjson::REST_OP_SUCCESS;
}
int read_array_iteration(uint32_t index,
json_object* json_instance) {
ODC_FUNC_TRACE;
std::string nodeconn_name("nodeconnector");
json_object *node_conn_obj(NULL);
int nodecon_ret(unc::restjson::json_object_parse_util:: extract_json_object
(json_instance,
nodeconn_name,
&node_conn_obj));
if (nodecon_ret != unc::restjson::REST_OP_SUCCESS)
return nodecon_ret;
// GET ID and chcek if it matches with match_id
std::string id_search("id");
std::string id_from_resp("");
int id_ret(unc::restjson::json_object_parse_util::
read_string(node_conn_obj,
id_search,
id_from_resp));
if (id_ret != unc::restjson::REST_OP_SUCCESS)
return id_ret;
pfc_log_info("ID read is %s", id_from_resp.c_str());
if ( id_from_resp == match_id_ ) {
std::string properties_section("properties");
json_object* port_properties_obj(NULL);
int port_prop_ret(unc::restjson::json_object_parse_util::
extract_json_object(json_instance,
properties_section,
&port_properties_obj));
if (port_prop_ret != unc::restjson::REST_OP_SUCCESS)
return port_prop_ret;
std::string name_section("name");
json_object* port_name_obj(NULL);
int portname_ret(unc::restjson::json_object_parse_util::
extract_json_object(port_properties_obj,
name_section,
&port_name_obj));
if (portname_ret != unc::restjson::REST_OP_SUCCESS)
return portname_ret;
std::string name_value("value");
int name_val_ret(unc::restjson::json_object_parse_util::
read_string(port_name_obj,
name_value,
port_name_));
pfc_log_info("PORT NAME is %s", port_name_.c_str());
if ( name_val_ret != unc::restjson::REST_OP_SUCCESS)
return name_val_ret;
}
return unc::restjson::REST_OP_SUCCESS;
}
int end_array_read(uint32_t index,
json_object* json_instance) {
ODC_FUNC_TRACE;
return unc::restjson::REST_OP_SUCCESS;
}
UncRespCode operator()(std::string match,
std::string &port_name) {
set_match_id(match);
int ret(extract_values());
if (ret != unc::restjson::REST_OP_SUCCESS)
return UNC_DRV_RC_ERR_GENERIC;
port_name.assign(get_port_name());
if ( port_name == "" )
return UNC_DRV_RC_ERR_GENERIC;
return UNC_RC_SUCCESS;
}
};
class port_name_read_request : public odl_http_rest_intf {
public:
std::string switch_id_;
std::string port_id_;
std::string port_name_;
port_name_read_request():switch_id_(""), port_name_("") {}
void set_switch_id(std::string id) {
switch_id_= id;
}
void set_port_id(std::string id) {
port_id_= id;
}
std::string get_port_name() {
return port_name_;
}
pfc_bool_t is_multiple_requests(unc::odcdriver::OdcDriverOps Op) {
ODC_FUNC_TRACE;
return PFC_FALSE;
}
UncRespCode get_multi_request_indicator(unc::odcdriver::OdcDriverOps Op,
std::set<std::string> *arg_list) {
ODC_FUNC_TRACE;
return UNC_RC_SUCCESS;
}
UncRespCode construct_url(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
std::string &url) {
ODC_FUNC_TRACE;
url.append(BASE_SW_URL);
url.append(CONTAINER_NAME);
url.append(NODE);
url.append(NODE_OF);
url.append(SLASH);
url.append(switch_id_);
return UNC_RC_SUCCESS;
}
UncRespCode construct_request_body(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
json_object *object) {
ODC_FUNC_TRACE;
return UNC_RC_SUCCESS;
}
restjson::HttpMethod get_http_method(
unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator) {
ODC_FUNC_TRACE;
return restjson::HTTP_METHOD_GET;
}
UncRespCode validate_response_code(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
int resp_code) {
if ( resp_code == HTTP_200_RESP_OK )
return UNC_RC_SUCCESS;
return UNC_DRV_RC_ERR_GENERIC;
}
UncRespCode handle_response(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
char* data) {
ODC_FUNC_TRACE;
json_object* node_json_data(NULL);
int obj_ret(unc::restjson::json_object_parse_util:: extract_json_object
(data,
&node_json_data));
if (obj_ret != unc::restjson::REST_OP_SUCCESS)
return UNC_DRV_RC_ERR_GENERIC;
unc::restjson::json_obj_destroy_util delete_node_obj(node_json_data);
json_object* node_array_data(NULL);
std::string node_search("nodeConnectorProperties");
int node_ret(unc::restjson::json_object_parse_util:: extract_json_object
(node_json_data,
node_search,
&node_array_data));
if (node_ret != unc::restjson::REST_OP_SUCCESS)
return UNC_DRV_RC_ERR_GENERIC;
unc::restjson::json_obj_destroy_util delete_node_array_obj(node_array_data);
port_info_resp_parser port_parse(node_array_data);
if (port_parse(port_id_, port_name_) != UNC_RC_SUCCESS)
return UNC_DRV_RC_ERR_GENERIC;
return UNC_RC_SUCCESS;
}
UncRespCode operator()(unc::driver::controller *ctr_ptr,
unc::restjson::ConfFileValues_t conf_values,
std::string switch_id,
std::string port_id,
std::string &port_name) {
set_switch_id(switch_id);
set_port_id(port_id);
odl_http_request port_req;
UncRespCode query_ret(port_req.handle_request(ctr_ptr,
CONFIG_READ,
this,
conf_values));
if (query_ret != UNC_RC_SUCCESS)
return query_ret;
port_name.assign(get_port_name());
if (port_name == "" )
return UNC_DRV_RC_ERR_GENERIC;
return UNC_RC_SUCCESS;
}
};
class vtn_read_request : public odl_http_rest_intf {
public:
std::set<std::string> *vtnnames_;
vtn_read_request(std::set<std::string> *vtns):
vtnnames_(vtns) {}
pfc_bool_t is_multiple_requests(unc::odcdriver::OdcDriverOps Op) {
ODC_FUNC_TRACE;
return PFC_FALSE;
}
UncRespCode get_multi_request_indicator(unc::odcdriver::OdcDriverOps Op,
std::set<std::string> *arg_list) {
ODC_FUNC_TRACE;
return UNC_RC_SUCCESS;
}
UncRespCode construct_url(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
std::string &url) {
ODC_FUNC_TRACE;
url.append(BASE_URL);
url.append(CONTAINER_NAME);
url.append(VTNS);
return UNC_RC_SUCCESS;
}
UncRespCode construct_request_body(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
json_object *object) {
return UNC_RC_SUCCESS;
}
restjson::HttpMethod get_http_method(
unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator) {
return restjson::HTTP_METHOD_GET;
}
UncRespCode validate_response_code(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
int resp_code) {
if ( resp_code == HTTP_200_RESP_OK )
return UNC_RC_SUCCESS;
return UNC_DRV_RC_ERR_GENERIC;
}
UncRespCode handle_response(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
char* data) {
json_object* vtn_data_json(NULL);
json_object* vtn_array_json(NULL);
std::string vtn_content("vtn");
pfc_log_info("Data received for parsing %s", data);
int ret(unc::restjson::json_object_parse_util:: extract_json_object
(data,
&vtn_data_json));
if (ret != unc::restjson::REST_OP_SUCCESS) {
pfc_log_info("Failed in parsing buffer");
return UNC_DRV_RC_ERR_GENERIC;
}
unc::restjson::json_obj_destroy_util delete_vtn_obj(vtn_data_json);
if (json_object_is_type(vtn_data_json, json_type_null)) {
pfc_log_info("JSON is NULL");
return UNC_DRV_RC_ERR_GENERIC;
}
int vtn_ret(unc::restjson::json_object_parse_util:: extract_json_object
(vtn_data_json,
vtn_content,
&vtn_array_json));
if (vtn_ret != unc::restjson::REST_OP_SUCCESS)
return UNC_DRV_RC_ERR_GENERIC;
unc::restjson::json_obj_destroy_util delete_vtn_date_obj(vtn_array_json);
vtn_read_resp_parser vtn_collect(vtn_array_json, vtnnames_);
int resp(vtn_collect.extract_values());
if (resp != unc::restjson::REST_OP_SUCCESS) {
pfc_log_info("Failed in collecting vtn names");
return UNC_DRV_RC_ERR_GENERIC;
}
pfc_log_info("VTN Collection Completed");
return UNC_RC_SUCCESS;
}
};
class vbr_read_request : public odl_http_rest_intf {
public:
std::set<std::string> *vbrnames_;
std::string vtn_name_;
vbr_read_request(std::set<std::string> *vbrs, std::string vtn_name):
vbrnames_(vbrs), vtn_name_(vtn_name) {}
pfc_bool_t is_multiple_requests(unc::odcdriver::OdcDriverOps Op) {
ODC_FUNC_TRACE;
return PFC_FALSE;
}
UncRespCode get_multi_request_indicator(unc::odcdriver::OdcDriverOps Op,
std::set<std::string> *arg_list) {
ODC_FUNC_TRACE;
return UNC_RC_SUCCESS;
}
UncRespCode construct_url(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
std::string &url) {
ODC_FUNC_TRACE;
if ( vtn_name_ == "" )
return UNC_DRV_RC_ERR_GENERIC;
url.append(BASE_URL);
url.append(CONTAINER_NAME);
url.append(VTNS);
url.append("/");
url.append(vtn_name_);
url.append("/vbridges");
return UNC_RC_SUCCESS;
}
UncRespCode construct_request_body(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
json_object *object) {
ODC_FUNC_TRACE;
return UNC_RC_SUCCESS;
}
restjson::HttpMethod get_http_method(
unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator) {
ODC_FUNC_TRACE;
return restjson::HTTP_METHOD_GET;
}
UncRespCode validate_response_code(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
int resp_code) {
ODC_FUNC_TRACE;
if ( resp_code == HTTP_200_RESP_OK )
return UNC_RC_SUCCESS;
return UNC_DRV_RC_ERR_GENERIC;
}
UncRespCode handle_response(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
char* data) {
ODC_FUNC_TRACE;
json_object* vtn_data_json(NULL);
json_object* vtn_array_json(NULL);
std::string vtn_content("vbridge");
pfc_log_info("Data VBR received %s", data);
int ret(unc::restjson::json_object_parse_util::extract_json_object
(data,
&vtn_data_json));
if ( ret != unc::restjson::REST_OP_SUCCESS )
return UNC_DRV_RC_ERR_GENERIC;
if ( vtn_data_json == NULL )
return UNC_DRV_RC_ERR_GENERIC;
unc::restjson::json_obj_destroy_util delete_vtn_obj(vtn_data_json);
int vtn_ret(unc::restjson::json_object_parse_util::extract_json_object
(vtn_data_json,
vtn_content,
&vtn_array_json));
if (vtn_ret != unc::restjson::REST_OP_SUCCESS )
return UNC_DRV_RC_ERR_GENERIC;
unc::restjson::json_obj_destroy_util delete_vtn_array_obj(vtn_array_json);
vtn_read_resp_parser vtn_collect(vtn_array_json, vbrnames_);
int vtn_collect_ret(vtn_collect.extract_values());
if ( vtn_collect_ret != unc::restjson::REST_OP_SUCCESS )
return UNC_DRV_RC_ERR_GENERIC;
pfc_log_info("VBR Collection Completed");
return UNC_RC_SUCCESS;
}
};
class vterm_read_request : public odl_http_rest_intf {
public:
std::set<std::string> *vbrnames_;
std::string vtn_name_;
vterm_read_request(std::set<std::string> *vbrs, std::string vtn_name):
vbrnames_(vbrs), vtn_name_(vtn_name) {}
pfc_bool_t is_multiple_requests(unc::odcdriver::OdcDriverOps Op) {
ODC_FUNC_TRACE;
return PFC_FALSE;
}
UncRespCode get_multi_request_indicator(unc::odcdriver::OdcDriverOps Op,
std::set<std::string> *arg_list) {
ODC_FUNC_TRACE;
return UNC_RC_SUCCESS;
}
UncRespCode construct_url(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
std::string &url) {
ODC_FUNC_TRACE;
if ( vtn_name_ == "" )
return UNC_DRV_RC_ERR_GENERIC;
url.append(BASE_URL);
url.append(CONTAINER_NAME);
url.append(VTNS);
url.append("/");
url.append(vtn_name_);
url.append("/vterminals");
return UNC_RC_SUCCESS;
}
UncRespCode construct_request_body(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
json_object *object) {
ODC_FUNC_TRACE;
return UNC_RC_SUCCESS;
}
restjson::HttpMethod get_http_method(
unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator) {
ODC_FUNC_TRACE;
return restjson::HTTP_METHOD_GET;
}
UncRespCode validate_response_code(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
int resp_code) {
ODC_FUNC_TRACE;
if ( resp_code == HTTP_200_RESP_OK )
return UNC_RC_SUCCESS;
return UNC_DRV_RC_ERR_GENERIC;
}
UncRespCode handle_response(unc::odcdriver::OdcDriverOps Op,
std::string &request_indicator,
char* data) {
ODC_FUNC_TRACE;
json_object* vtn_data_json(NULL);
json_object* vtn_array_json(NULL);
std::string vtn_content("vterminal");
pfc_log_info("Data VBR received %s", data);
int ret(unc::restjson::json_object_parse_util::extract_json_object
(data,
&vtn_data_json));
if ( ret != unc::restjson::REST_OP_SUCCESS )
return UNC_DRV_RC_ERR_GENERIC;
if ( vtn_data_json == NULL )
return UNC_DRV_RC_ERR_GENERIC;
unc::restjson::json_obj_destroy_util delete_vterm_obj(vtn_data_json);
int vtn_ret(unc::restjson::json_object_parse_util::extract_json_object
(vtn_data_json,
vtn_content,
&vtn_array_json));
if (vtn_ret != unc::restjson::REST_OP_SUCCESS )
return UNC_DRV_RC_ERR_GENERIC;
unc::restjson::json_obj_destroy_util delete_vterm_array_obj(vtn_array_json);
vtn_read_resp_parser vtn_collect(vtn_array_json, vbrnames_);
int vtn_collect_ret(vtn_collect.extract_values());
if ( vtn_collect_ret != unc::restjson::REST_OP_SUCCESS )
return UNC_DRV_RC_ERR_GENERIC;
pfc_log_info("VTERM Collection Completed");
return UNC_RC_SUCCESS;
}
};
UncRespCode port_info_parser::get_vlan_id(json_object* instance,
int &vlanid ) {
ODC_FUNC_TRACE;
std::string search_vlan("vlan");
int parse_ret(unc::restjson::json_object_parse_util::
read_int_value(instance,
search_vlan,
vlanid));
if ( parse_ret != unc::restjson::REST_OP_SUCCESS)
return UNC_DRV_RC_ERR_GENERIC;
return UNC_RC_SUCCESS;
}
// Node!!
UncRespCode port_info_parser::get_switch_details(json_object* instance,
std::string &switch_id) {
ODC_FUNC_TRACE;
std::string search_node("node");
json_object* switch_obj(NULL);
int parse_ret(unc::restjson::json_object_parse_util::
extract_json_object(instance, search_node, &switch_obj));
if (parse_ret != unc::restjson::REST_OP_SUCCESS)
return UNC_DRV_RC_ERR_GENERIC;
std::string search_switch_name("id");
int sw_parse_ret(unc::restjson::json_object_parse_util::
read_string(switch_obj,
search_switch_name,
switch_id));
if ( sw_parse_ret != unc::restjson::REST_OP_SUCCESS)
return UNC_DRV_RC_ERR_GENERIC;
return UNC_RC_SUCCESS;
}
// port!!
UncRespCode port_info_parser::get_port_details(json_object* instance,
std::string &portname) {
std::string search_port("port");
json_object* port_obj(NULL);
int parse_ret(unc::restjson::json_object_parse_util::
extract_json_object(instance, search_port, &port_obj));
if ( parse_ret != unc::restjson::REST_OP_SUCCESS)
return UNC_DRV_RC_ERR_GENERIC;
std::string search_port_name("id");
int sw_parse_ret(unc::restjson::json_object_parse_util::
read_string(port_obj,
search_port_name,
portname));
if ( sw_parse_ret != unc::restjson::REST_OP_SUCCESS)
return UNC_DRV_RC_ERR_GENERIC;
return UNC_RC_SUCCESS;
}
UncRespCode odlutils::get_vtn_names(
unc::driver::controller *ctr_ptr,
unc::restjson::ConfFileValues_t conf_values,
std::set <std::string> *vtns) {
ODC_FUNC_TRACE;
vtn_read_request vtn_read(vtns);
odl_http_request vtn_req;
return vtn_req.handle_request(ctr_ptr,
CONFIG_READ,
&vtn_read,
conf_values);
}
UncRespCode odlutils::get_vbridge_names(
unc::driver::controller *ctr_ptr,
unc::restjson::ConfFileValues_t conf_values,
std::string vtn_name,
std::set <std::string> *vbridges) {
ODC_FUNC_TRACE;
vbr_read_request vbr_read(vbridges, vtn_name);
odl_http_request vbr_req;
return vbr_req.handle_request(ctr_ptr,
CONFIG_READ,
&vbr_read,
conf_values);
}
UncRespCode odlutils::get_vterm_names (
unc::driver::controller *ctr_ptr,
unc::restjson::ConfFileValues_t conf_values,
std::string vtn_name,
std::set <std::string> *vbridges) {
ODC_FUNC_TRACE;
vterm_read_request vbr_read(vbridges, vtn_name);
odl_http_request vbr_req;
return vbr_req.handle_request(ctr_ptr,
CONFIG_READ,
&vbr_read,
conf_values);
}
UncRespCode odlutils::get_portname(unc::driver::controller *ctr_ptr,
unc::restjson::ConfFileValues_t conf_values,
std::string switch_id,
std::string port_id,
std::string &port_name) {
ODC_FUNC_TRACE;
port_name_read_request port_req;
return port_req(ctr_ptr, conf_values, switch_id, port_id, port_name);
}
} // namespace odcdriver
} // namespace unc
|
6b32c0e3dcb41aa25b608e743b402bb258a67cf1 | a9f795667368634c36de9919437eb64db83b3331 | /mips/retrieval/ta.h | 906589896bc3aa9d791bed51d5ebd3f84bb4e780 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | stanford-futuredata/LEMP-benchmarking | 2bdf24336db4020830406ea7462db70b03e527b7 | 0279528b427aa4fae59e4d3598b1f098fcb4cf4b | refs/heads/master | 2020-05-26T12:16:03.854467 | 2018-07-31T23:53:39 | 2018-07-31T23:53:39 | 84,997,817 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,449 | h | ta.h | // Copyright 2015 Christina Teflioudi
//
// 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.
/*
* ta.h
*
* Created on: Jun 25, 2014
* Author: chteflio
*/
#ifndef TA_H_
#define TA_H_
namespace mips {
class taRetriever : public Retriever {
public:
taRetriever() = default;
~taRetriever() = default;
inline void run(const double* query, ProbeBucket& probeBucket, RetrievalArguments* arg) const{
QueueElementLists* invLists = static_cast<QueueElementLists*> (probeBucket.getIndex(SL));
col_type stepOnCol = 0;
row_type posMatrix;
double stopThreshold;
double oldValue;
double localTheta;
if (arg->forCosine) {
localTheta = probeBucket.bucketScanThreshold / query[-1];
} else {
localTheta = arg->theta;
}
#ifdef TIME_IT
arg->t.start();
#endif
//initialize scheduler and state
arg->state->initForNewQuery(query);
stopThreshold = arg->state->getInitialThreshold();
#ifdef TIME_IT
arg->t.stop();
arg->preprocessTime += arg->t.elapsedTime().nanos();
#endif
row_type countSeen = 0;
//check if you need to stop. Otherwise continue;
while (stopThreshold >= localTheta) {
//choose next step
stepOnCol = arg->state->chooseStep();
//pick up the item
oldValue = invLists->getElement(arg->state->getDepthInFringeInCol(stepOnCol))->data;
posMatrix = invLists->getElement(arg->state->getDepthInFringeInCol(stepOnCol))->id;
#ifdef TIME_IT
arg->t.start();
#endif
//if I haven't explored the item already, do RA
if (!arg->state->isExplored(posMatrix)) {
verifyCandidate(posMatrix + probeBucket.startPos, query, arg);
countSeen++;
arg->state->maintainExploredLists(*(arg->probeMatrix), countSeen, stepOnCol);
}
#ifdef TIME_IT
arg->t.stop();
arg->ipTime += arg->t.elapsedTime().nanos();
arg->t.start();
#endif
// update the state
arg->state->updateState(stepOnCol);
#ifdef TIME_IT
arg->t.stop();
arg->scanTime += arg->t.elapsedTime().nanos();
#endif
if (arg->state->areAllSeen()) {
break;
}
#ifdef TIME_IT
arg->t.start();
#endif
arg->state->isThresholdUnterTheta(stopThreshold, localTheta, stepOnCol, oldValue, arg->forCosine);
#ifdef TIME_IT
arg->t.stop();
arg->boundsTime += arg->t.elapsedTime().nanos();
#endif
}
}
inline void runTopK(const double* query, ProbeBucket& probeBucket, RetrievalArguments* arg) const{
col_type stepOnCol = 0;
row_type posMatrix;
double oldValue;
QueueElementLists* invLists = static_cast<QueueElementLists*> (probeBucket.getIndex(SL));
double x1 = 1;
double x2 = 1;
if (arg->forCosine) {
x1 = probeBucket.invNormL2.second;
x2 = probeBucket.invNormL2.first;
}
double localTheta = arg->heap.front().data * (arg->heap.front().data > 0 ? x1 : x2);
#ifdef TIME_IT
arg->t.start();
#endif
arg->state->initForNewQuery(query);
double stopThreshold = arg->state->getInitialThreshold();
#ifdef TIME_IT
arg->t.stop();
arg->preprocessTime += arg->t.elapsedTime().nanos();
#endif
row_type countSeen = 0;
while (stopThreshold > localTheta) {
//choose next step
stepOnCol = arg->state->chooseStep();
//pick up the item
oldValue = invLists->getElement(arg->state->getDepthInFringeInCol(stepOnCol))->data;
posMatrix = invLists->getElement(arg->state->getDepthInFringeInCol(stepOnCol))->id;
#ifdef TIME_IT
arg->t.start();
#endif
//if I haven't explored the item already, do RA
if (!arg->state->isExplored(posMatrix)) {
verifyCandidateTopk(posMatrix + probeBucket.startPos, query, arg);
countSeen++;
arg->state->maintainExploredLists(*(arg->probeMatrix), countSeen, stepOnCol);
}
#ifdef TIME_IT
arg->t.stop();
arg->ipTime += arg->t.elapsedTime().nanos();
arg->t.start();
#endif
// update the state
arg->state->updateState(stepOnCol);
#ifdef TIME_IT
arg->t.stop();
arg->scanTime += arg->t.elapsedTime().nanos();
#endif
if (arg->state->areAllSeen())
break;
#ifdef TIME_IT
arg->t.start();
#endif
localTheta = arg->heap.front().data * (arg->heap.front().data > 0 ? x1 : x2);
arg->state->isThresholdUnterTheta(stopThreshold, localTheta, stepOnCol, oldValue, arg->forCosine);
#ifdef TIME_IT
arg->t.stop();
arg->boundsTime += arg->t.elapsedTime().nanos();
#endif
}
}
inline virtual void tune(ProbeBucket& probeBucket, const ProbeBucket& prevBucket, std::vector<RetrievalArguments>& retrArg) {
row_type sampleSize = probeBucket.xValues->size();
if (sampleSize > 0) {
sampleTimes.resize(sampleSize);
QueueElementLists* invLists = static_cast<QueueElementLists*> (probeBucket.getIndex(SL));
retrArg[0].state->initializeForNewBucket(invLists);
for (row_type i = 0; i < sampleSize; ++i) {
int t = probeBucket.xValues->at(i).i;
int ind = probeBucket.xValues->at(i).j;
const double* query = retrArg[t].queryMatrix->getMatrixRowPtr(ind);
retrArg[0].tunerTimer.start();
run(query, probeBucket, &retrArg[0]);
retrArg[0].tunerTimer.stop();
sampleTimes[i] = retrArg[0].tunerTimer.elapsedTime().nanos();
}
} else {
probeBucket.setAfterTuning(prevBucket.numLists, prevBucket.t_b);
}
}
inline virtual void tuneTopk(ProbeBucket& probeBucket, const ProbeBucket& prevBucket, std::vector<RetrievalArguments>& retrArg) {
row_type sampleSize = (probeBucket.xValues!=nullptr ? probeBucket.xValues->size() : 0);
if (sampleSize > 0) {
sampleTimes.resize(sampleSize);
QueueElementLists* invLists = static_cast<QueueElementLists*> (probeBucket.getIndex(SL));
// todo shouldn't I initialize the lists? no! already initialized from Incremental
retrArg[0].state->initializeForNewBucket(invLists);
for (row_type i = 0; i < sampleSize; ++i) {
int t = probeBucket.xValues->at(i).i;
int ind = probeBucket.xValues->at(i).j;
const double* query = retrArg[t].queryMatrix->getMatrixRowPtr(ind);
const std::vector<QueueElement>& prevResults = prevBucket.sampleThetas[t].at(ind).results;
retrArg[0].heap.assign(prevResults.begin(), prevResults.end());
std::make_heap(retrArg[0].heap.begin(), retrArg[0].heap.end(), std::greater<QueueElement>());
retrArg[0].tunerTimer.start();
runTopK(query, probeBucket, &retrArg[0]);
retrArg[0].tunerTimer.stop();
sampleTimes[i] = retrArg[0].tunerTimer.elapsedTime().nanos();
}
}else {
probeBucket.setAfterTuning(prevBucket.numLists, prevBucket.t_b);
}
}
inline virtual void runTopK(ProbeBucket& probeBucket, RetrievalArguments* arg) const{
QueueElementLists* invLists = static_cast<QueueElementLists*> (probeBucket.getIndex(SL));
for (auto& queryBatch : arg->queryBatches) {
if (queryBatch.isWorkDone())
continue;
if (!invLists->isInitialized()) {
#ifdef TIME_IT
arg->t.start();
#endif
invLists->initializeLists(*(arg->probeMatrix), probeBucket.startPos, probeBucket.endPos);
#ifdef TIME_IT
arg->t.stop();
arg->initializeListsTime += arg->t.elapsedTime().nanos();
#endif
}
arg->state->initializeForNewBucket(invLists);
row_type user = queryBatch.startPos;
int start = queryBatch.startPos * arg->k;
int end = queryBatch.endPos * arg->k;
for (row_type i = start; i < end; i += arg->k) {
if (queryBatch.isQueryInactive(user)) {
user++;
continue;
}
const double* query = arg->queryMatrix->getMatrixRowPtr(user);
double minScore = arg->topkResults[i].data;
if (probeBucket.normL2.second < minScore) {// skip this bucket and all other buckets
queryBatch.inactivateQuery(user);
user++;
continue;
}
arg->moveTopkToHeap(i);
arg->queryId = arg->queryMatrix->getId(user);
runTopK(query, probeBucket, arg);
arg->writeHeapToTopk(user);
user++;
}
}
}
inline virtual void run(ProbeBucket& probeBucket, RetrievalArguments* arg) const{
QueueElementLists* invLists = static_cast<QueueElementLists*> (probeBucket.getIndex(SL));
arg->state->initializeForNewBucket(invLists);
for (auto& queryBatch : arg->queryBatches) {
if (queryBatch.maxLength() < probeBucket.bucketScanThreshold) {
break;
}
for (row_type i = queryBatch.startPos; i < queryBatch.endPos; ++i) {
const double* query = arg->queryMatrix->getMatrixRowPtr(i);
if (query[-1] < probeBucket.bucketScanThreshold)// skip all users from this point on for this bucket
break;
arg->queryId = arg->queryMatrix->getId(i);
run(query, probeBucket, arg);
}
}
}
};
}
#endif /* TA_H_ */
|
9aa2aed527db676fb1d0d3a831cc2ac72b7ed883 | b13b12fbcf29716fc718445d37cd57db907c5abd | /rock_paper_scissors/tests/test_rps.cpp | 57f1ad198de771ab04757da485c24ce7a06801f0 | [] | no_license | cynthia3r/games | be8ffa68f4d06b3d872f708e06db58898da0062f | 95b5019660855ccf19492cc4916dc41653c82653 | refs/heads/master | 2023-02-21T18:42:16.958983 | 2020-05-11T07:31:52 | 2020-05-11T07:31:52 | 262,968,146 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,277 | cpp | test_rps.cpp | #include <iostream>
#include "test_rps.h"
#include "../ActionFactory.h"
#include "../Rock.h"
#include "../Paper.h"
#include "../Scissors.h"
bool test_action_factory_get_action_rock()
{
ActionFactory factory;
return factory.getAction("rock")->type() == Action::ActionType::rock;
}
bool test_action_factory_get_action_paper()
{
ActionFactory factory;
return factory.getAction("paper")->type() == Action::ActionType::paper;
}
bool test_action_factory_get_action_scissors()
{
ActionFactory factory;
return factory.getAction("scissors")->type() == Action::ActionType::scissors;
}
bool test_rock_with_paper()
{
Rock rock;
Paper paper;
return ((rock < paper) == true);
}
bool test_rock_with_scissors()
{
Rock rock;
Scissors scissors;
return ((rock < scissors) == false);
}
bool test_paper_with_rock()
{
Paper paper;
Rock rock;
return ((paper < rock) == false);
}
bool test_paper_with_scissors()
{
Paper paper;
Scissors scissors;
return ((paper < scissors) == true);
}
bool test_scissors_with_rock()
{
Scissors scissors;
Rock rock;
return ((scissors < rock) == true);
}
bool test_scissors_with_paper()
{
Scissors scissors;
Paper paper;
return ((scissors < paper) == false);
}
|
10dbe9262c8b51a0aff24a777e2c3640619a5eca | 393d6e1307a477b81feebf2fdb8b1b4308430d64 | /app/src/util.h | 3583522dc740b3570cfe28ef25f7f2533050b34c | [] | no_license | SRI-CSL/rendezvous | cdc6c67f12f79d35930a1035ae0b2cdf9b7a7f29 | 71ecb0223e332121fd0841da561f3435d776e280 | refs/heads/master | 2021-01-14T13:22:07.803124 | 2015-01-05T18:22:55 | 2015-01-05T18:22:55 | 28,825,169 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 245 | h | util.h | #ifndef UTIL_H
#define UTIL_H
#include <QString>
#include <QDebug>
#include <QTime>
class Util {
public:
inline static QDebug debug(){ QDebug foo = qDebug(); foo << QTime::currentTime().toString("mm:ss.zzz"); return foo; }
};
#endif
|
e49c7dc49e49e84e196ef593d88a0ea5fe733971 | a4515918f56dd7ab527e4999aa7fce818b6dd6f6 | /Unsorted Language-specific Implementations/c-plus-plus/bigInteger.cpp | 805aaa5e61422543be05ee86f402d1bdd476e5da | [
"MIT"
] | permissive | rathoresrikant/HacktoberFestContribute | 0e2d4692a305f079e5aebcd331e8df04b90f90da | e2a69e284b3b1bd0c7c16ea41217cc6c2ec57592 | refs/heads/master | 2023-06-13T09:22:22.554887 | 2021-10-27T07:51:41 | 2021-10-27T07:51:41 | 151,832,935 | 102 | 901 | MIT | 2023-06-23T06:53:32 | 2018-10-06T11:23:31 | C++ | UTF-8 | C++ | false | false | 6,744 | cpp | bigInteger.cpp | /*
@author: Priyendu Mori
Big Integer library that supports add, sub, mul, div and gcd of large numbers
*/
#include <bits/stdc++.h>
#include <string>
#define ll long long
using namespace std;
string add(string, string);
string sub(string, string);
bool isSmaller(string x, string y)
{
for (ll i=0; i<x.length(); i++){
if (x[i] < y[i]) return true;
else if (x[i] > y[i]) return false;
}
return false;
}
bool isGreater(string x, string y){
if(x.length() > y.length()) return true;
ll pad=llabs(x.length()-y.length());
if(x.length()<y.length()){
x=string(pad, '0').append(x);
}
else{
y=string(pad, '0').append(y);
}
for (ll i=0; i<x.length(); i++){
if (x[i] > y[i]) return true;
else if (x[i] < y[i]) return false;
}
return false;
}
bool isEqual(string x, string y){
ll pad=llabs(x.length()-y.length());
if(x.length()<y.length()){
x=string(pad, '0').append(x);
}
else{
y=string(pad, '0').append(y);
}
for (ll i=0; i<x.length(); i++){
if (x[i] != y[i]) return false;
}
return true;
}
bool isZero(string x){
for(ll i=0;i<x.length();i++){
if(x[i] != '0') return false;
}
return true;
}
string sub(string x, string y){
bool neg=false;
if(x[0]=='-' && y[0]=='-'){
string temp=x;
x=y;
y=temp;
y=y.substr(1,y.length()-1);
x=x.substr(1,x.length()-1);
}
else if(x[0]!='-' && y[0]=='-'){
y=y.substr(1,y.length()-1);
return add(x,y);
}
else if(x[0]=='-' && y[0]!='-'){
x=x.substr(1,x.length()-1);
string ans="-"+add(x,y);
return ans;
}
ll pad=llabs(x.length()-y.length());
if(x.length()<y.length()){
x=string(pad, '0').append(x);
}
else{
y=string(pad, '0').append(y);
}
if(isSmaller(x, y)){
string temp=x;
x=y;
y=temp;
neg=true;
}
string diff="";
int carry=0;
for(ll i=x.length()-1;i>=0;i--){
ll d = (x[i]-'0') - (y[i]-'0') - carry;
if(d < 0){
d=d+10;
carry=1;
diff.push_back(d+'0');
}
else{
carry=0;
diff.push_back(d+'0');
}
}
reverse(diff.begin(), diff.end());
diff.erase(0, min(diff.find_first_not_of('0'), diff.length()-1));
if(neg) diff.insert(diff.begin(),'-');
return diff;
}
string add(string x, string y){
bool neg=false;
if(x[0]=='-' && y[0]!='-'){
x=x.substr(1,x.length()-1);
return sub(y, x);
}
else if(x[0]!='-' && y[0]=='-'){
y=y.substr(1,y.length()-1);
return sub(x, y);
}
else if(x[0]=='-' && y[0]=='-'){
neg=true;
x=x.substr(1,x.length()-1);
y=y.substr(1,y.length()-1);
}
ll pad=llabs(x.length()-y.length());
if(x.length()<y.length()){
x=string(pad, '0').append(x);
}
else{
y=string(pad, '0').append(y);
}
string sum="";
int carry=0;
for(ll i=x.length()-1;i>=0;i--){
ll s = x[i]-'0' + y[i]-'0' + carry;
if(s <= 9){
sum.push_back(s+'0');
carry=0;
}
else{
sum.push_back(s%10 +'0');
carry=s/10;
}
}
if(carry!=0){
sum.push_back(carry+'0');
}
if(neg) sum.push_back('-');
reverse(sum.begin(), sum.end());
sum.erase(0, min(sum.find_first_not_of('0'), sum.length()-1));
return sum;
}
string mul(string x, string y){
bool neg=false;
if(x[0]=='-' && y[0]=='-'){
x=x.substr(1,x.length()-1);
y=y.substr(1,y.length()-1);
}
else if(x[0]=='-' && y[0]!='-'){
x=x.substr(1,x.length()-1);
neg=true;
}
else if(x[0]!='-' && y[0]=='-'){
y=y.substr(1,y.length()-1);
neg=true;
}
string finalproduct="";
for(ll i=0;i<y.length();i++){
ll multiplier=y[i]-'0';
string product="";
int carry=0;
//cout<<"multiplying "<<multiplier<<" and "<<x<<endl;
for(ll j=x.length()-1;j>=0;j--){
int p=(x[j]-'0')*multiplier + carry;
if(p<=9){
product.push_back(p+'0');
carry=0;
}
else{
product.push_back(p%10 + '0');
carry=p/10;
}
}
if(carry!=0) product+=carry+'0';
//cout<<"ans "<<product<<endl;
if(i==0){
reverse(product.begin(), product.end());
finalproduct=product;
}
else{
finalproduct+='0';
reverse(product.begin(), product.end());
//cout<<"adding "<<finalproduct<<" and "<<product<<endl;
finalproduct=add(finalproduct, product);
}
}
if(neg) finalproduct.insert(finalproduct.begin(), '-');
return finalproduct;
}
string div(string x, string y){
bool neg=false;
if(x[0]=='-' && y[0]=='-'){
x=x.substr(1,x.length()-1);
y=y.substr(1,y.length()-1);
}
else if(x[0]=='-' && y[0]!='-'){
x=x.substr(1,x.length()-1);
neg=true;
}
else if(x[0]!='-' && y[0]=='-'){
y=y.substr(1,y.length()-1);
neg=true;
}
ll pad=llabs(x.length()-y.length());
if(x.length()<y.length()){
x=string(pad, '0').append(x);
}
else{
y=string(pad, '0').append(y);
}
if(isSmaller(x,y)) return "0";
string count="0";
while(isGreater(x, y)){
//cout<<x<<" - "<<y<<" = ";
x=sub(x, y);
//cout<<x<<"\t";
count=add(count, "1");
//cout<<count<<endl;
// cout<<"isGreater("<<x<<","<<y<<") = "<<isGreater(x ,y)<< endl;
}
if(isEqual(x,y)) count=add(count, "1");
if(neg) return '-'+count;
return count;
}
string gcd(string x, string y){
while(!isZero(x) && !isZero(y)){
if(isGreater(x,y)){
x=sub(x,y);
}
else if(isGreater(y,x)){
y=sub(y,x);
}
else{
x=sub(x,y);
}
}
if(isZero(x)){
return y;
}
if(isZero(y)){
return x;
}
return "1";
}
int main(){
ios_base::sync_with_stdio(false);
ll t;
cin>>t;
while(t--){
string x,y;
ll k;
cin>>x>>y>>k;
string ans="";
switch(k){
case 1: ans=add(x,y); break;
case 2: ans=sub(x,y); break;
case 3: ans=mul(x,y); break;
case 4: ans=div(x,y); break;
case 5: ans=gcd(x,y); break;
}
cout<<ans<<endl;
}
return 0;
}
|
f6f3aaad66b7ff1bbfd3e2d23bfd029451e5013a | b5266922e5465848233df71b39b50779dad487cb | /LLGameStudio/LLGameEngine/Game/UI/IUIProperty.h | 9b32686e0bcff48302f9c5a6f8a14b0dffd4ea59 | [] | no_license | wlzs04/OpenSource | bb524a0d43b18b89ff47d3b3329db5451145ec86 | 0406e52b31d231b61cd66d3aeb76e7aed265bd7b | refs/heads/master | 2018-11-28T04:29:23.220812 | 2018-10-25T11:13:36 | 2018-10-25T11:13:36 | 115,679,393 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,140 | h | IUIProperty.h | #pragma once
#include "..\..\Common\Helper\MathHelper.h"
#include "..\..\Common\LLBase.h"
#include "../../Common/Graphics/GraphicsApi.h"
class IUIProperty
{
public:
IUIProperty(wstring name, wstring defaultValue);
bool IsDefault();
virtual wstring GetValue() { return wstring(); };
virtual void SetValue(wstring) {};
wstring name;
wstring defaultValue;
};
//UI节点属性
class PropertyName :public IUIProperty
{
public:
PropertyName() :IUIProperty(L"name", L"node") {SetValue(defaultValue);}
wstring GetValue()override { return value; };
void SetValue(wstring value) { this->value =value; };
wstring value;
};
class PropertyEnable :public IUIProperty
{
public:
PropertyEnable() :IUIProperty(L"enable", L"True") { SetValue(defaultValue); }
wstring GetValue() { return value ? L"True" : L"False"; };
void SetValue(wstring value) { this->value = WStringHelper::GetBool(value); };
bool value;
};
class PropertyWidth :public IUIProperty
{
public:
PropertyWidth() :IUIProperty(L"width", L"1") {SetValue(defaultValue);}
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyHeight :public IUIProperty
{
public:
PropertyHeight() :IUIProperty(L"height", L"1") {SetValue(defaultValue);}
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class AnchorEnum : public EnumBase
{
public:
AnchorEnum(int i) :EnumBase(i) {}
static const int Center = 0;
static const int Left = 1;
static const int Top = 2;
static const int Right = 4;
static const int Bottom = 8;
static const int Left_Top = Left | Top;
static const int Right_Top = Right | Top;
static const int Right_Bottom = Right | Bottom;
static const int Left_Bottom = Left | Bottom;
private:
unordered_map<wstring, int>& GetEnumMap()override;
};
class PropertyAnchorEnum :public IUIProperty
{
public:
PropertyAnchorEnum() :IUIProperty(L"anchorEnum", L"Left_Top") {SetValue(defaultValue);}
wstring GetValue() { return value.ToWString(); };
void SetValue(wstring value) { this->value.GetValueFromWString(value); };
AnchorEnum value = AnchorEnum::Left;
};
class PropertyRotation :public IUIProperty
{
public:
PropertyRotation() :IUIProperty(L"rotation", L"{0,0}") {SetValue(defaultValue);}
wstring GetValue() { return value.ToWString(); };
void SetValue(wstring value) { this->value.GetValueFromWString(value); };
Vector2 value;
};
class PropertyMargin :public IUIProperty
{
public:
PropertyMargin() :IUIProperty(L"margin", L"{0}") {SetValue(defaultValue);}
wstring GetValue() { return value.ToWString(); };
void SetValue(wstring value) { this->value.GetValueFromWString(value); };
Rect value;
};
class PropertyClipByParent :public IUIProperty
{
public:
PropertyClipByParent() :IUIProperty(L"clipByParent", L"False") {SetValue(defaultValue);}
wstring GetValue() { return value ? L"True" : L"False"; };
void SetValue(wstring value) { this->value=WStringHelper::GetBool(value); };
bool value;
};
class CheckStateMethod : public EnumBase
{
public:
CheckStateMethod(int i) :EnumBase(i) {}
static const int Rect = 0;
static const int Alpha = 1;
static const int AllowMouseThrough = 2;
private:
unordered_map<wstring, int>& GetEnumMap()override;
};
class PropertyCheckStateMethod :public IUIProperty
{
public:
PropertyCheckStateMethod() :IUIProperty(L"checkStateMethod", L"Rect") { SetValue(defaultValue); }
wstring GetValue() { return value.ToWString(); };
void SetValue(wstring value) { this->value.GetValueFromWString(value); };
CheckStateMethod value = CheckStateMethod::Rect;
};
class PropertyFilePath :public IUIProperty
{
public:
PropertyFilePath() :IUIProperty(L"filePath", L"") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) { this->value = value; };
wstring value;
};
class PropertyImage :public IUIProperty
{
public:
PropertyImage() :IUIProperty(L"image", L"") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) {
this->value = value;
GraphicsApi::GetGraphicsApi()->AddImage(value);
};
wstring value;
};
class PropertyText :public IUIProperty
{
public:
PropertyText() :IUIProperty(L"text", L"") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) {this->value = value;};
wstring value;
};
class PropertyTextFamily :public IUIProperty
{
public:
PropertyTextFamily() :IUIProperty(L"textFamily", L"") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) { this->value = value; };
wstring value;
};
class PropertyModal :public IUIProperty
{
public:
PropertyModal() :IUIProperty(L"modal", L"False") { SetValue(defaultValue); }
wstring GetValue() { return value ? L"True" : L"False"; };
void SetValue(wstring value) { this->value = WStringHelper::GetBool(value); };
bool value;
};
//粒子系统属性
class ParticleType : public EnumBase
{
public:
ParticleType(int i) :EnumBase(i) {}
static const int Point = 0;//点
static const int Star = 1;//星
static const int Image = 2;//图片
static const int Sequence = 3;//序列图
private:
unordered_map<wstring, int>& GetEnumMap()override;
};
class PropertyParticleType :public IUIProperty
{
public:
PropertyParticleType() :IUIProperty(L"particleType", L"Point") { SetValue(defaultValue); }
wstring GetValue() { return value.ToWString(); };
void SetValue(wstring value) { this->value.GetValueFromWString(value); };
ParticleType value = ParticleType::Point;
};
class PropertyIsLoop :public IUIProperty
{
public:
PropertyIsLoop() :IUIProperty(L"isLoop", L"True") { SetValue(defaultValue); }
wstring GetValue() { return value ? L"True" : L"False"; };
void SetValue(wstring value) { this->value = WStringHelper::GetBool(value); };
bool value;
};
class PropertyLoopTime :public IUIProperty
{
public:
PropertyLoopTime() :IUIProperty(L"loopTime", L"5") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyMaxNumber :public IUIProperty
{
public:
PropertyMaxNumber() :IUIProperty(L"maxNumber", L"10") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetInt(value); };
int value;
};
class PropertyStartNumber :public IUIProperty
{
public:
PropertyStartNumber() :IUIProperty(L"startNumber", L"1") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetInt(value); };
int value;
};
class PropertyCreateNumberBySecond :public IUIProperty
{
public:
PropertyCreateNumberBySecond() :IUIProperty(L"createNumberBySecond", L"2") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetInt(value); };
int value;
};
class PropertyRadius :public IUIProperty
{
public:
PropertyRadius() :IUIProperty(L"radius", L"3") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyRadiusError :public IUIProperty
{
public:
PropertyRadiusError() :IUIProperty(L"radiusError", L"1") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyColor :public IUIProperty
{
public:
PropertyColor() :IUIProperty(L"color", L"#FFFFFFFF") { SetValue(defaultValue); }
wstring GetValue() { return value; };
void SetValue(wstring value) { this->value = value; };
wstring value;
};
class PropertyVelocity :public IUIProperty
{
public:
PropertyVelocity() :IUIProperty(L"velocity", L"20") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyVelocityError :public IUIProperty
{
public:
PropertyVelocityError() :IUIProperty(L"velocityError", L"2") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyDirection :public IUIProperty
{
public:
PropertyDirection() :IUIProperty(L"direction", L"{0,-1}") { SetValue(defaultValue); }
wstring GetValue() { return value.ToWString(); };
void SetValue(wstring value) { this->value.GetValueFromWString(value); };
Vector2 value;
};
class PropertyAngleRange :public IUIProperty
{
public:
PropertyAngleRange() :IUIProperty(L"angleRange", L"30") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyPosition :public IUIProperty
{
public:
PropertyPosition() :IUIProperty(L"position", L"{0,0}") { SetValue(defaultValue); }
wstring GetValue() { return value.ToWString(); };
void SetValue(wstring value) { this->value.GetValueFromWString(value); };
Vector2 value;
};
class PropertyPositionError :public IUIProperty
{
public:
PropertyPositionError() :IUIProperty(L"positionError", L"{0,0}") { SetValue(defaultValue); }
wstring GetValue() { return value.ToWString(); };
void SetValue(wstring value) { this->value.GetValueFromWString(value); };
Vector2 value;
};
class PropertyImagePath :public IUIProperty
{
public:
PropertyImagePath() :IUIProperty(L"imagePath", L"") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) {
this->value = value;
GraphicsApi::GetGraphicsApi()->AddImage(value);
};
wstring value;
};
class PropertyRow :public IUIProperty
{
public:
PropertyRow() :IUIProperty(L"row", L"1") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetInt(value); };
int value;
};
class PropertyColumn :public IUIProperty
{
public:
PropertyColumn() :IUIProperty(L"column", L"1") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetInt(value); };
int value;
};
//骨骼系统属性
class PropertyLength :public IUIProperty
{
public:
PropertyLength() :IUIProperty(L"length", L"90") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyAngle :public IUIProperty
{
public:
PropertyAngle() :IUIProperty(L"angle", L"0") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyFrameNumber :public IUIProperty
{
public:
PropertyFrameNumber() :IUIProperty(L"frameNumber", L"0") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetInt(value); };
int value;
};
class PropertyTotalFrameNumber :public IUIProperty
{
public:
PropertyTotalFrameNumber() :IUIProperty(L"totalFrameNumber", L"24") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetInt(value); };
int value;
};
class PropertyTotalTime :public IUIProperty
{
public:
PropertyTotalTime() :IUIProperty(L"totalTime", L"4") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
//游戏配置属性
class PropertyGameName :public IUIProperty
{
public:
PropertyGameName() :IUIProperty(L"gameName", L"游戏") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) { this->value = value; };
wstring value;
};
class PropertyGameWidth :public IUIProperty
{
public:
PropertyGameWidth() :IUIProperty(L"gameWidth", L"800") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyGameHeight :public IUIProperty
{
public:
PropertyGameHeight() :IUIProperty(L"gameHeight", L"600") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyGameLeft :public IUIProperty
{
public:
PropertyGameLeft() :IUIProperty(L"gameLeft", L"0") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyGameTop :public IUIProperty
{
public:
PropertyGameTop() :IUIProperty(L"gameTop", L"0") { SetValue(defaultValue); }
wstring GetValue() { return to_wstring(value); };
void SetValue(wstring value) { this->value = WStringHelper::GetFloat(value); };
float value;
};
class PropertyMiddleInScreen :public IUIProperty
{
public:
PropertyMiddleInScreen() :IUIProperty(L"middleInScreen", L"True") { SetValue(defaultValue); }
wstring GetValue() { return value ? L"True" : L"False"; };
void SetValue(wstring value) { this->value = WStringHelper::GetBool(value); };
bool value;
};
class PropertyFullScreen :public IUIProperty
{
public:
PropertyFullScreen() :IUIProperty(L"fullScreen", L"False") { SetValue(defaultValue); }
wstring GetValue() { return value ? L"True" : L"False"; };
void SetValue(wstring value) { this->value = WStringHelper::GetBool(value); };
bool value;
};
class PropertyCanMultiGame :public IUIProperty
{
public:
PropertyCanMultiGame() :IUIProperty(L"canMultiGame", L"False") { SetValue(defaultValue); }
wstring GetValue() { return value ? L"True" : L"False"; };
void SetValue(wstring value) { this->value = WStringHelper::GetBool(value); };
bool value;
};
class PropertyStartScene :public IUIProperty
{
public:
PropertyStartScene() :IUIProperty(L"startScene", L"layout/StartScene.scene") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) { this->value = value; };
wstring value;
};
class GraphicsApiType : public EnumBase
{
public:
GraphicsApiType(int i) :EnumBase(i) {}
static const int Direct2D = 0;//Direct2D
static const int LL2D = 1;//未实现
private:
unordered_map<wstring, int>& GetEnumMap()override;
};
class PropertyGraphicsApi :public IUIProperty
{
public:
PropertyGraphicsApi() :IUIProperty(L"graphicsApi", L"Direct2D") { SetValue(defaultValue); }
wstring GetValue() { return value.ToWString(); };
void SetValue(wstring value) { this->value.GetValueFromWString(value); };
GraphicsApiType value = GraphicsApiType::Direct2D;
};
class PropertyOpenNetClient :public IUIProperty
{
public:
PropertyOpenNetClient() :IUIProperty(L"openNetClient", L"False") { SetValue(defaultValue); }
wstring GetValue() { return value ? L"True" : L"False"; };
void SetValue(wstring value) { this->value = WStringHelper::GetBool(value); };
bool value;
};
class PropertyOpenPhysics :public IUIProperty
{
public:
PropertyOpenPhysics() :IUIProperty(L"openPhysics", L"False") { SetValue(defaultValue); }
wstring GetValue() { return value ? L"True" : L"False"; };
void SetValue(wstring value) { this->value = WStringHelper::GetBool(value); };
bool value;
};
class PropertyIcon :public IUIProperty
{
public:
PropertyIcon() :IUIProperty(L"icon", L"") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) { this->value = value; };
wstring value;
};
class PropertyDefaultCursor :public IUIProperty
{
public:
PropertyDefaultCursor() :IUIProperty(L"defaultCursor", L"") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) { this->value = value; };
wstring value;
};
class PropertyServerIPPort :public IUIProperty
{
public:
PropertyServerIPPort() :IUIProperty(L"serverIPPort", L"") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) { this->value = value; };
wstring value;
};
class PropertyEncryptKey :public IUIProperty
{
public:
PropertyEncryptKey() :IUIProperty(L"encryptKey", L"401230") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) { this->value = value; };
wstring value;
};
class PropertyDefaultScript :public IUIProperty
{
public:
PropertyDefaultScript() :IUIProperty(L"defaultScript", L"logic/StartLogic.llscript") { SetValue(defaultValue); }
wstring GetValue()override { return value; };
void SetValue(wstring value) { this->value = value; };
wstring value;
}; |
734dc5d3d16b7b92f1afd3de488191ce87542661 | 72bc0cb69b7b0efbf03e37e63ab6ebf09c132c08 | /frame/main/Processor.cpp | 02c4604b0a58250954f881fd498f3029b1838057 | [] | no_license | roberty65/bServer | 1c135036a85a173c2301142460f9c613181ef66b | a40d57615c1a43f40b60d188c1289908227e4b03 | refs/heads/master | 2021-01-22T10:32:16.840178 | 2020-06-28T01:00:57 | 2020-06-28T01:00:57 | 53,181,607 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 462 | cpp | Processor.cpp | #include "Log.h"
#include "Queue.h"
#include "Processor.h"
namespace beyondy {
namespace Async {
int async_send_delegator(Message *msg, void *data)
{
// set it
gettimeofday(&msg->ts_enqueue, NULL);
Queue<Message> *outQ = (Queue<Message> *)data;
if (outQ->push(msg) < 0) {
SYSLOG_ERROR("push msg(fd=%d, flow=%d size=%ld) into system queue overflow", msg->fd, msg->flow, (long)msg->getWptr());
return -1;
}
return 0;
}
} /* Async */
} /* beyondy */
|
1c2b385ea288dcaf0ecf2ab106a994a8d8509b00 | 1f84fd078570475d2510339bab2439b5193af03d | /source/vxEngine/EditorEngine.cpp | 5c062e6047e8cc13f8f1275fdb0f1fb6e9c71bad | [
"MIT"
] | permissive | DennisWandschura/vxEngine | df138077cdb9f40461c83e99a8851de593b098f2 | 1396a65f7328aaed50dd34634c65cac561271b9e | refs/heads/master | 2021-01-16T00:17:47.703611 | 2015-10-11T10:44:53 | 2015-10-11T10:44:53 | 32,484,686 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,878 | cpp | EditorEngine.cpp | /*
The MIT License (MIT)
Copyright (c) 2015 Dennis Wandschura
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "EditorEngine.h"
#include <vxEngineLib/Message.h>
#include <vxEngineLib/MessageTypes.h>
#include <vxEngineLib/Locator.h>
#include <vxEngineLib/EditorMeshInstance.h>
#include <vxEngineLib/Ray.h>
#include <vxEngineLib/EditorScene.h>
#include <vxEngineLib/Graphics/Light.h>
#include <vxEngineLib/NavMeshGraph.h>
#include <vxEngineLib/EngineConfig.h>
#include <vxEngineLib/debugPrint.h>
#include "developer.h"
#include <vxEngineLib/FileMessage.h>
#include <vxEngineLib/Reference.h>
#include <vxEngineLib/Material.h>
#include <vxEngineLib/Spawn.h>
#include <vxEngineLib/Actor.h>
#include "EngineGlobals.h"
#include <vxLib/Graphics/Camera.h>
#include <vxEngineLib/MeshFile.h>
#include <vxEngineLib/Joint.h>
#include <vxEngineLib/FileEntry.h>
#include <vxEngineLib/ActorFile.h>
#include <vxEngineLib/Graphics/LightGeometryProxy.h>
#include <Dbghelp.h>
u32 g_editorTypeMesh{ 0xffffffff };
u32 g_editorTypeMaterial{ 0xffffffff };
u32 g_editorTypeScene{ 0xffffffff };
u32 g_editorTypeFbx{ 0xffffffff };
u32 g_editorTypeAnimation{ 0xffffffff };
u32 g_editorTypeActor{ 0xffffffff };
namespace EditorEngineCpp
{
void schedulerThread(vx::TaskManager* scheduler)
{
std::atomic_uint running;
running.store(1);
scheduler->initializeThread(&running);
while (running.load() != 0)
{
scheduler->swapBuffer();
scheduler->update();
}
}
}
EditorEngine::EditorEngine()
:m_msgManager(),
m_physicsAspect(),
m_renderAspect(),
m_resourceAspect(),
m_navmeshGraph(),
m_previousSceneLoaded(false)
{
}
EditorEngine::~EditorEngine()
{
if (m_shutdown == 0)
{
// something bad happened
assert(false);
}
}
bool EditorEngine::initializeImpl(const std::string &dataDir, bool flipTextures)
{
m_memory = Memory(g_totalMemory, 64);
m_allocator = vx::StackAllocator(m_memory.get(), m_memory.size());
m_scratchAllocator = vx::StackAllocator(m_allocator.allocate(1 MBYTE, 64), 1 MBYTE);
m_msgManager.initialize(&m_allocator, 256);
//if (!m_resourceAspect.initialize(&m_allocator, dataDir, &m_msgManager, m_physicsAspect.getCooking()))
if (!m_resourceAspect.initialize(&m_allocator, dataDir, m_physicsAspect.getCooking(), &m_taskManager, &m_msgManager, flipTextures, true))
return false;
Locator::provide(&m_resourceAspect);
return true;
}
bool EditorEngine::createRenderAspectGL(const std::string &dataDir, const RenderAspectDescription &desc, AbortSignalHandlerFun signalHandlerFn)
{
auto handle = LoadLibrary(L"../../../lib/vxRenderAspectGL_d.dll");
if (handle == nullptr)
return false;
auto proc = (CreateEditorRenderAspectFunction)GetProcAddress(handle, "createEditorRenderAspect");
auto procDestroy = (DestroyEditorRenderAspectFunction)GetProcAddress(handle, "destroyEditorRenderAspect");
if (proc == nullptr || procDestroy == nullptr)
return false;
auto renderAspect = proc();
if (renderAspect == nullptr)
return false;
m_renderAspect = renderAspect;
m_renderAspectDll = handle;
m_destroyFn = procDestroy;
return true;
}
bool EditorEngine::initializeEditor(HWND panel, HWND tmp, const vx::uint2 &resolution, AbortSignalHandlerFun signalHandlerFn, Editor::Scene* pScene, Logfile* logfile)
{
vx::activateChannel(vx::debugPrint::Channel_Render);
vx::activateChannel(vx::debugPrint::Channel_Editor);
vx::activateChannel(vx::debugPrint::Channel_FileAspect);
vx::debugPrint::g_verbosity = 1;
const std::string dataDir("../../data/");
m_pEditorScene = pScene;
m_resolution = resolution;
m_panel = panel;
if (!m_physicsAspect.initialize(&m_taskManager))
{
return false;
}
g_engineConfig.m_fovDeg = 66.0f;
g_engineConfig.m_zFar = 250.0f;
g_engineConfig.m_renderDebug = true;
g_engineConfig.m_resolution = resolution;
g_engineConfig.m_vsync = false;
g_engineConfig.m_zNear = 0.1f;
g_engineConfig.m_editor = true;
g_engineConfig.m_rendererSettings.m_renderMode = Graphics::RendererSettings::Mode_GL;
g_engineConfig.m_rendererSettings.m_shadowMode = 0;
g_engineConfig.m_rendererSettings.m_voxelGIMode = 0;
g_engineConfig.m_rendererSettings.m_maxMeshInstances = 150;
g_engineConfig.m_rendererSettings.m_voxelSettings.m_voxelGridDim = 16;
g_engineConfig.m_rendererSettings.m_voxelSettings.m_voxelTextureSize = 128;
bool flipTextures = (g_engineConfig.m_rendererSettings.m_renderMode == Graphics::RendererSettings::Mode_GL);
if (!initializeImpl(dataDir, flipTextures))
return false;
m_taskManager.initialize(2, 10, 30.0f, &m_allocator);
m_taskManagerThread = std::thread(EditorEngineCpp::schedulerThread, &m_taskManager);
RenderAspectDescription renderAspectDesc =
{
dataDir,
panel,
tmp,
&m_allocator,
&g_engineConfig,
logfile,
nullptr,
&m_resourceAspect,
&m_msgManager,
&m_taskManager
};
//renderAspectDesc.hwnd = m_panel;
if (!createRenderAspectGL(dataDir, renderAspectDesc, signalHandlerFn))
{
return false;
}
if (m_renderAspect->initialize(renderAspectDesc, signalHandlerFn) != RenderAspectInitializeError::OK)
{
return false;
}
//dev::g_debugRenderSettings.setVoxelize(0);
//dev::g_debugRenderSettings.setShadingMode(ShadingMode::Albedo);
//m_renderAspect->queueUpdateTask(task);
Locator::provide(&m_physicsAspect);
m_msgManager.initialize(&m_allocator, 255);
m_msgManager.registerListener(m_renderAspect, 1, (u8)vx::MessageType::File | (u8)vx::MessageType::Renderer);
m_msgManager.registerListener(&m_physicsAspect, 1, (u8)vx::MessageType::File);
m_msgManager.registerListener(this, 1, (u8)vx::MessageType::File);
//m_bRun = 1;
m_shutdown = 0;
memset(&m_selected, 0, sizeof(m_selected));
return true;
}
void EditorEngine::shutdownEditor()
{
if (m_taskManagerThread.joinable())
m_taskManagerThread.join();
m_taskManager.shutdown();
m_resourceAspect.shutdown();
m_physicsAspect.shutdown();
if (m_renderAspect)
{
m_renderAspect->shutdown(m_panel);
m_destroyFn(m_renderAspect);
m_renderAspect = nullptr;
}
m_panel = nullptr;
m_shutdown = 1;
m_allocator.release();
}
void EditorEngine::stop()
{
m_taskManager.stop();
}
void EditorEngine::buildNavGraph()
{
auto &navMesh = m_pEditorScene->getNavMesh();
m_influenceMap.initialize(navMesh, m_pEditorScene->getWaypoints(), m_pEditorScene->getWaypointCount());
m_navmeshGraph.initialize(navMesh);
m_renderAspect->updateInfluenceCellBuffer(m_influenceMap);
m_renderAspect->updateNavMeshGraphNodesBuffer(m_navmeshGraph);
}
void EditorEngine::handleMessage(const vx::Message &evt)
{
switch (evt.type)
{
case(vx::MessageType::File) :
handleFileEvent(evt);
break;
default:
break;
}
}
void EditorEngine::handleFileEvent(const vx::Message &evt)
{
auto fe = (vx::FileMessage)evt.code;
switch (fe)
{
case vx::FileMessage::Mesh_Loaded:
{
auto sid = vx::StringID(evt.arg1.u64);
auto pStr = reinterpret_cast<std::string*>(evt.arg2.ptr);
if (call_editorCallback(sid))
{
vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Loaded mesh %llu %s", sid.value, pStr->c_str());
auto meshFile = m_resourceAspect.getMesh(sid);
m_pEditorScene->addMesh(sid, pStr->c_str(), meshFile);
}
delete(pStr);
}break;
case vx::FileMessage::Texture_Loaded:
break;
case vx::FileMessage::Material_Loaded:
{
auto sid = vx::StringID(evt.arg1.u64);
auto pStr = reinterpret_cast<std::string*>(evt.arg2.ptr);
if (call_editorCallback(sid))
{
vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Loaded material %llu %s", sid.value, pStr->c_str());
Material* material = m_resourceAspect.getMaterial(sid);
m_pEditorScene->addMaterial(sid, pStr->c_str(), material);
}
delete(pStr);
}break;
case vx::FileMessage::EditorScene_Loaded:
{
vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Loaded Scene");
call_editorCallback(vx::StringID(evt.arg1.u64));
buildNavGraph();
auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
m_renderAspect->updateWaypoints(m_pEditorScene->getWaypoints(), m_pEditorScene->getWaypointCount());
m_renderAspect->updateJoints(m_pEditorScene->getJoints(), m_pEditorScene->getJointCount(), sortedInstances);
m_renderAspect->updateSpawns(m_pEditorScene->getSpawns(), m_pEditorScene->getSpawnCount());
m_renderAspect->updateLightGeometryProxies(m_pEditorScene->getLightGeometryProxies(), m_pEditorScene->getLightGeometryProxyCount());
}break;
case vx::FileMessage::Animation_Loaded:
{
auto sid = vx::StringID(evt.arg1.u64);
if (evt.arg2.ptr)
{
auto pStr = reinterpret_cast<std::string*>(evt.arg2.ptr);
vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Loaded Animation %llu", sid.value);
call_editorCallback(sid);
m_pEditorScene->addAnimation(sid, std::move(*pStr));
}
else
{
VX_ASSERT(false);
//auto str = m_resourceAspect.getAnimationName(sid);
//if (str)
// m_pEditorScene->addAnimation(sid, std::move(std::string(str)));
}
}break;
case vx::FileMessage::Actor_Loaded:
{
auto sid = vx::StringID(evt.arg1.u64);
auto pStr = reinterpret_cast<std::string*>(evt.arg2.ptr);
call_editorCallback(sid);
delete(pStr);
}break;
default:
{
}break;
}
}
void EditorEngine::requestLoadFile(const vx::FileEntry &fileEntry, vx::Variant arg)
{
m_resourceAspect.requestLoadFile(fileEntry, arg);
}
void EditorEngine::editor_saveScene(const char* name)
{
auto sceneCopy = new Editor::Scene();
m_pEditorScene->copy(sceneCopy);
vx::Variant arg;
arg.ptr = sceneCopy;
m_resourceAspect.requestSaveFile(vx::FileEntry(name, vx::FileType::EditorScene), arg);
}
void EditorEngine::editor_setTypes(u32 mesh, u32 material, u32 scene, u32 fbx, u32 typeAnimation, u32 typeActor)
{
g_editorTypeMesh = mesh;
g_editorTypeMaterial = material;
g_editorTypeScene = scene;
g_editorTypeFbx = fbx;
g_editorTypeAnimation = typeAnimation;
g_editorTypeActor = typeActor;
}
void EditorEngine::update(f32 dt)
{
m_msgManager.update();
//m_physicsAspect.update(1.0f/30.f);
//m_physicsAspect.fetch();
m_resourceAspect.update();
m_renderAspect->update();
m_renderAspect->buildCommands();
m_renderAspect->submitCommands();
m_renderAspect->wait();
m_renderAspect->swapBuffers();
}
void EditorEngine::editor_loadFile(const char *filename, u32 type, Editor::LoadFileCallback f, vx::Variant userArg)
{
vx::Variant arg;
arg.ptr = nullptr;
vx::FileEntry fileEntry;
if (type == g_editorTypeMesh)
{
fileEntry = vx::FileEntry(filename, vx::FileType::Mesh);
arg.ptr = new std::string(filename);
vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Trying to load mesh %llu '%s'", fileEntry.getSid().value, filename);
}
else if (type == g_editorTypeMaterial)
{
fileEntry = vx::FileEntry(filename, vx::FileType::Material);
arg.ptr = new std::string(filename);
vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Trying to load material %llu '%s'", fileEntry.getSid().value, filename);
}
else if (type == g_editorTypeScene)
{
fileEntry = vx::FileEntry(filename, vx::FileType::EditorScene);
if (m_previousSceneLoaded)
{
VX_ASSERT(false);
}
arg.ptr = m_pEditorScene;
}
else if (type == g_editorTypeFbx)
{
fileEntry = vx::FileEntry(filename, vx::FileType::Fbx);
arg.u32 = 0;
//p = new std::string(filename);
}
else if (type == g_editorTypeAnimation)
{
fileEntry = vx::FileEntry(filename, vx::FileType::Animation);
arg.ptr = new std::string(filename);
}
else if (type == g_editorTypeActor)
{
fileEntry = vx::FileEntry(filename, vx::FileType::Actor);
arg.ptr = new std::string(filename);
}
else
{
vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Trying to load unknown file type");
//assert(false);
}
vx::lock_guard<vx::mutex> guard(m_editorMutex);
m_requestedFiles.insert(fileEntry.getSid(), std::make_pair(f, type));
m_resourceAspect.requestLoadFile(fileEntry, arg);
}
void EditorEngine::editor_moveCamera(f32 dirX, f32 dirY, f32 dirZ)
{
m_renderAspect->moveCamera(dirX, dirY, dirZ);
}
void EditorEngine::editor_rotateCamera(f32 dirX, f32 dirY, f32)
{
static f32 x = 0.0f;
static f32 y = 0.0f;
x += dirX * 0.01f;
y += dirY * 0.01f;
vx::float4a rot(y, x, 0, 0);
auto v = vx::quaternionRotationRollPitchYawFromVector(rot);
m_renderAspect->rotateCamera(v);
}
bool EditorEngine::call_editorCallback(const vx::StringID &sid)
{
bool result = false;
vx::lock_guard<vx::mutex> guard(m_editorMutex);
auto it = m_requestedFiles.find(sid);
if (it != m_requestedFiles.end())
{
(*it->first)(sid.value, it->second);
m_requestedFiles.erase(it);
result = true;
}
return result;
}
vx::float4a EditorEngine::getRayDir(s32 mouseX, s32 mouseY) const
{
f32 ndc_x = f32(mouseX) / m_resolution.x;
f32 ndc_y = f32(mouseY) / m_resolution.y;
ndc_x = ndc_x * 2.0f - 1.0f;
ndc_y = 1.0f - ndc_y * 2.0f;
vx::mat4 projMatrix;
m_renderAspect->getProjectionMatrix(&projMatrix);
auto invProjMatrix = vx::MatrixInverse(projMatrix);
vx::float4a ray_clip(ndc_x, ndc_y, -1, 1);
vx::float4a ray_eye = vx::Vector4Transform(invProjMatrix, ray_clip);
ray_eye.z = -1.0f;
ray_eye.w = 0.0f;
vx::mat4 viewMatrix;
m_renderAspect->getViewMatrix(&viewMatrix);
auto inverseViewMatrix = vx::MatrixInverse(viewMatrix);
vx::float4a ray_world = vx::Vector4Transform(inverseViewMatrix, ray_eye);
ray_world = vx::normalize3(ray_world);
return ray_world;
}
vx::StringID EditorEngine::raytraceAgainstStaticMeshes(s32 mouseX, s32 mouseY, vx::float3* hitPosition) const
{
auto ray_world = getRayDir(mouseX, mouseY);
vx::float4a cameraPosition;
m_renderAspect->getCameraPosition(&cameraPosition);
PhysicsHitData hitData;
vx::StringID sid;
if (m_physicsAspect.raycast_staticDynamic(cameraPosition, ray_world, 50.0f, &hitData))
{
*hitPosition = hitData.hitPosition;
sid = hitData.sid;
}
return sid;
}
u32 EditorEngine::getMeshInstanceCount() const
{
u32 result = 0;
if (m_pEditorScene)
{
result = m_pEditorScene->getMeshInstanceCount();
}
return result;
}
const char* EditorEngine::getMeshInstanceName(u32 i) const
{
auto meshInstances = m_pEditorScene->getMeshInstancesEditor();
auto sid = meshInstances[i].getNameSid();
return getMeshInstanceName(sid);
}
const char* EditorEngine::getMeshInstanceName(const vx::StringID &sid) const
{
return m_pEditorScene->getMeshInstanceName(sid);
}
u64 EditorEngine::getMeshInstanceSid(u32 i) const
{
u64 sidValue = 0;
if (m_pEditorScene)
{
auto meshInstances = m_pEditorScene->getMeshInstancesEditor();
sidValue = meshInstances[i].getNameSid().value;
}
return sidValue;
}
u64 EditorEngine::getMeshInstanceSid(s32 mouseX, s32 mouseY) const
{
u64 result = 0;
if (m_pEditorScene)
{
vx::float3 p;
auto sid = raytraceAgainstStaticMeshes(mouseX, mouseY, &p);
result = sid.value;
}
return result;
}
const char* EditorEngine::getSelectedMeshInstanceName() const
{
auto meshInstance = (MeshInstance*)m_selected.m_item;
const char* name = nullptr;
if (meshInstance)
{
name = m_pEditorScene->getMeshInstanceName(meshInstance->getNameSid());
}
return name;
}
void EditorEngine::setSelectedMeshInstance(u64 sid)
{
if (sid != 0)
{
auto instance = m_pEditorScene->getMeshInstance(vx::StringID(sid));
if (instance)
{
m_renderAspect->setSelectedMeshInstance(instance);
m_selected.m_type = SelectedType::MeshInstance;
m_selected.m_item = (void*)instance;
}
}
}
u64 EditorEngine::getSelectedMeshInstanceSid() const
{
u64 sidValue = 0;
auto meshInstance = (MeshInstance*)m_selected.m_item;
if (meshInstance)
{
sidValue = meshInstance->getNameSid().value;
}
return sidValue;
}
u64 EditorEngine::getMeshInstanceMeshSid(u64 instanceSid) const
{
u64 sidValue = 0;
auto meshInstance = m_pEditorScene->getMeshInstance(vx::StringID(instanceSid));
if (meshInstance != nullptr)
{
sidValue = meshInstance->getMeshSid().value;
}
return sidValue;
}
void EditorEngine::setMeshInstanceMeshSid(u64 instanceSid, u64 meshSid)
{
auto meshInstance = m_pEditorScene->getMeshInstance(vx::StringID(instanceSid));
if (meshInstance != nullptr)
{
auto mesh = m_pEditorScene->getMesh(vx::StringID(meshSid));
m_renderAspect->setMeshInstanceMesh(vx::StringID(instanceSid), vx::StringID(meshSid));
meshInstance->setMeshSid(vx::StringID(meshSid));
meshInstance->setBounds(mesh->getMesh());
m_physicsAspect.editorSetStaticMeshInstanceMesh(meshInstance->getMeshInstance());
}
}
u64 EditorEngine::getMeshInstanceMaterialSid(u64 instanceSid) const
{
u64 sidValue = 0;
auto sid = vx::StringID(instanceSid);
auto meshInstance = m_pEditorScene->getMeshInstance(sid);
if (meshInstance)
{
auto material = meshInstance->getMaterial();
sidValue = (*material).getSid().value;
}
return sidValue;
}
void EditorEngine::getMeshInstancePosition(u64 sid, vx::float3* position)
{
auto instance = m_pEditorScene->getMeshInstance(vx::StringID(sid));
auto &transform = instance->getTransform();
*position = transform.m_translation;
}
u64 EditorEngine::deselectMeshInstance()
{
u64 result = 0;
if (m_pEditorScene)
{
auto selectedInstance = (Editor::MeshInstance*)m_selected.m_item;
if (selectedInstance)
{
result = selectedInstance->getNameSid().value;
m_renderAspect->setSelectedMeshInstance(nullptr);
m_selected.m_item = nullptr;
}
}
return result;
}
vx::StringID EditorEngine::createMeshInstance()
{
auto instanceSid = m_pEditorScene->createMeshInstance();
auto instance = m_pEditorScene->getMeshInstance(instanceSid);
m_physicsAspect.addMeshInstance(instance->getMeshInstance());
m_renderAspect->addMeshInstance(*instance);
return instanceSid;
}
void EditorEngine::removeMeshInstance(u64 sid)
{
if (m_pEditorScene)
{
m_pEditorScene->removeMeshInstance(vx::StringID(sid));
m_renderAspect->removeMeshInstance(vx::StringID(sid));
}
}
void EditorEngine::setMeshInstanceMaterial(u64 instanceSid, u64 materialSid)
{
if (m_pEditorScene)
{
auto meshInstance = m_pEditorScene->getMeshInstance(vx::StringID(instanceSid));
auto sceneMaterial = m_pEditorScene->getMaterial(vx::StringID(materialSid));
if (sceneMaterial != nullptr)
{
if (m_renderAspect->setSelectedMeshInstanceMaterial(sceneMaterial))
{
meshInstance->setMaterial(sceneMaterial);
}
}
}
}
void EditorEngine::setMeshInstancePosition(u64 sid, const vx::float3 &p)
{
if (m_pEditorScene)
{
auto instanceSid = vx::StringID(sid);
m_pEditorScene->setMeshInstancePosition(instanceSid, p);
auto instance = m_pEditorScene->getMeshInstance(instanceSid);
auto transform = instance->getTransform();
m_renderAspect->setSelectedMeshInstanceTransform(transform);
m_physicsAspect.editorSetStaticMeshInstanceTransform(instance->getMeshInstance(), instanceSid);
}
}
void EditorEngine::setMeshInstanceRotation(u64 sid, const vx::float3 &rotationDeg)
{
if (m_pEditorScene)
{
auto rotation = vx::degToRad(rotationDeg);
auto r = vx::loadFloat3(&rotation);
auto q = vx::quaternionRotationRollPitchYawFromVector(r);
vx::float4 tmp;
vx::storeFloat4(&tmp, q);
auto instanceSid = vx::StringID(sid);
m_pEditorScene->setMeshInstanceRotation(instanceSid, tmp);
auto instance = m_pEditorScene->getMeshInstance(instanceSid);
auto transform = instance->getTransform();
m_renderAspect->setSelectedMeshInstanceTransform(transform);
m_physicsAspect.editorSetStaticMeshInstanceTransform(instance->getMeshInstance(), instanceSid);
}
}
void EditorEngine::getMeshInstanceRotation(u64 sid, vx::float3* rotationDeg) const
{
if (m_pEditorScene)
{
auto instanceSid = vx::StringID(sid);
auto instance = m_pEditorScene->getMeshInstance(instanceSid);
auto transform = instance->getTransform();
auto q = transform.m_qRotation;
__m128 axis;
f32 angle;
vx::quaternionToAxisAngle(vx::loadFloat4(&q), &axis, &angle);
axis = vx::normalize3(axis);
vx::float4a tmpAxis = axis;
vx::angleAxisToEuler(tmpAxis, angle, rotationDeg);
}
}
bool EditorEngine::setMeshInstanceName(u64 sid, const char* name)
{
bool result = false;
if (m_pEditorScene)
{
auto meshInstance = (MeshInstance*)m_selected.m_item;
result = m_pEditorScene->renameMeshInstance(vx::StringID(sid), name);
}
return result;
}
bool EditorEngine::addNavMeshVertex(s32 mouseX, s32 mouseY, vx::float3* position)
{
vx::float3 hitPos;
auto sid = raytraceAgainstStaticMeshes(mouseX, mouseY, &hitPos);
if (sid.value != 0)
{
auto ptr = m_pEditorScene->getMeshInstance(sid);
auto &navMesh = m_pEditorScene->getNavMesh();
navMesh.addVertex(hitPos);
m_renderAspect->updateNavMeshBuffer(navMesh);
*position = hitPos;
}
return sid.value != 0;
}
void EditorEngine::removeNavMeshVertex(const vx::float3 &position)
{
if (m_pEditorScene)
{
auto &navMesh = m_pEditorScene->getNavMesh();
navMesh.removeVertex(position);
buildNavGraph();
m_renderAspect->updateNavMeshBuffer(navMesh);
}
}
void EditorEngine::removeSelectedNavMeshVertex()
{
if (m_selected.m_navMeshVertices.m_count != 0)
{
auto index = m_selected.m_navMeshVertices.m_vertices[0];
auto &navMesh = m_pEditorScene->getNavMesh();
navMesh.removeVertex(index);
m_renderAspect->updateNavMeshBuffer(navMesh);
}
}
Ray EditorEngine::getRay(s32 mouseX, s32 mouseY)
{
auto rayDir = getRayDir(mouseX, mouseY);
vx::float4a cameraPosition;
m_renderAspect->getCameraPosition(&cameraPosition);
Ray ray;
ray.o.x = static_cast<f32>(cameraPosition.x);
ray.o.y = static_cast<f32>(cameraPosition.y);
ray.o.z = static_cast<f32>(cameraPosition.z);
//vx::storeFloat3(&ray.o, cameraPosition);
vx::storeFloat3(&ray.d, rayDir);
ray.maxt = 50.0f;
return ray;
}
u32 EditorEngine::getSelectedNavMeshVertex(s32 mouseX, s32 mouseY)
{
auto ray = getRay(mouseX, mouseY);
auto &navMesh = m_pEditorScene->getNavMesh();
return navMesh.testRayAgainstVertices(ray);
}
bool EditorEngine::selectNavMeshVertex(s32 mouseX, s32 mouseY)
{
bool result = false;
if (m_pEditorScene)
{
auto selectedIndex = getSelectedNavMeshVertex(mouseX, mouseY);
if (selectedIndex != 0xffffffff)
{
auto &navMesh = m_pEditorScene->getNavMesh();
m_selected.m_navMeshVertices.m_vertices[0] = selectedIndex;
m_selected.m_navMeshVertices.m_count = 1;
m_selected.m_type = SelectedType::NavMeshVertex;
m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);
result = true;
}
}
return result;
}
bool EditorEngine::selectNavMeshVertexIndex(u32 index)
{
bool result = false;
if (m_pEditorScene)
{
auto &navMesh = m_pEditorScene->getNavMesh();
m_selected.m_navMeshVertices.m_vertices[0] = index;
m_selected.m_navMeshVertices.m_count = 1;
m_selected.m_type = SelectedType::NavMeshVertex;
m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);
result = true;
}
return result;
}
bool EditorEngine::selectNavMeshVertexPosition(const vx::float3 &position)
{
bool result = false;
if (m_pEditorScene)
{
auto &navMesh = m_pEditorScene->getNavMesh();
u32 index = 0;
if (navMesh.getIndex(position, &index))
{
m_selected.m_navMeshVertices.m_vertices[0] = index;
m_selected.m_navMeshVertices.m_count = 1;
m_selected.m_type = SelectedType::NavMeshVertex;
m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);
result = true;
}
}
return result;
}
bool EditorEngine::multiSelectNavMeshVertex(s32 mouseX, s32 mouseY)
{
bool result = false;
if (m_pEditorScene)
{
auto selectedIndex = getSelectedNavMeshVertex(mouseX, mouseY);
if (selectedIndex != 0xffffffff)
{
auto &navMesh = m_pEditorScene->getNavMesh();
auto index = m_selected.m_navMeshVertices.m_count;
m_selected.m_navMeshVertices.m_vertices[index] = selectedIndex;
++m_selected.m_navMeshVertices.m_count;
m_selected.m_navMeshVertices.m_count = std::min(m_selected.m_navMeshVertices.m_count, (u8)3u);
m_selected.m_type = SelectedType::NavMeshVertex;
m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);
result = true;
}
}
return result;
}
u32 EditorEngine::deselectNavMeshVertex()
{
u32 index = 0;
if (m_pEditorScene)
{
auto &navMesh = m_pEditorScene->getNavMesh();
m_renderAspect->updateNavMeshBuffer(navMesh);
index = m_selected.m_navMeshVertices.m_vertices[0];
m_selected.m_navMeshVertices.m_count = 0;
}
m_selected.m_item = nullptr;
return index;
}
bool EditorEngine::createNavMeshTriangleFromSelectedVertices(vx::uint3* selected)
{
bool result = false;
if (m_selected.m_navMeshVertices.m_count == 3)
{
auto &navMesh = m_pEditorScene->getNavMesh();
navMesh.addTriangle(m_selected.m_navMeshVertices.m_vertices);
buildNavGraph();
m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);
selected->x = m_selected.m_navMeshVertices.m_vertices[0];
selected->y = m_selected.m_navMeshVertices.m_vertices[1];
selected->z = m_selected.m_navMeshVertices.m_vertices[2];
result = true;
}
return result;
}
void EditorEngine::createNavMeshTriangleFromIndices(const vx::uint3 &indices)
{
if (m_pEditorScene)
{
m_selected.m_navMeshVertices.m_count = 3;
m_selected.m_navMeshVertices.m_vertices[0] = indices.x;
m_selected.m_navMeshVertices.m_vertices[1] = indices.y;
m_selected.m_navMeshVertices.m_vertices[2] = indices.z;
vx::uint3 tmp;
createNavMeshTriangleFromSelectedVertices(&tmp);
}
}
void EditorEngine::removeNavMeshTriangle()
{
if (m_pEditorScene)
{
auto &navMesh = m_pEditorScene->getNavMesh();
navMesh.removeTriangle();
m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);
buildNavGraph();
}
}
u32 EditorEngine::getSelectedNavMeshCount() const
{
return m_selected.m_navMeshVertices.m_count;
}
void EditorEngine::setSelectedNavMeshVertexPosition(const vx::float3 &position)
{
if (m_selected.m_navMeshVertices.m_count != 0)
{
auto &navMesh = m_pEditorScene->getNavMesh();
auto selectedIndex = m_selected.m_navMeshVertices.m_vertices[0];
navMesh.setVertexPosition(selectedIndex, position);
m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);
buildNavGraph();
}
}
bool EditorEngine::getSelectedNavMeshVertexPosition(vx::float3* p) const
{
bool result = false;
if (m_selected.m_navMeshVertices.m_count != 0)
{
auto selectedIndex = m_selected.m_navMeshVertices.m_vertices[0];
auto &navMesh = m_pEditorScene->getNavMesh();
auto vertices = navMesh.getVertices();
*p = vertices[selectedIndex];
result = true;
}
return result;
}
u32 EditorEngine::createLight()
{
Graphics::Light light;
light.m_position = vx::float3(0);
light.m_falloff = 5.0f;
light.m_lumen = 100.0f;
auto index = m_pEditorScene->getLightCount();
m_selected.m_item = m_pEditorScene->addLight(light);
m_selected.m_type = SelectedType::Light;
auto lightCount = index+1;
auto lights = m_pEditorScene->getLights();
m_renderAspect->updateLightBuffer(lights, lightCount);
return index;
}
bool EditorEngine::getLightIndex(s32 mouseX, s32 mouseY, u32* index)
{
bool result = false;
if (m_pEditorScene)
{
auto ray = getRay(mouseX, mouseY);
auto light = m_pEditorScene->getLight(ray);
if (light)
{
auto lights = m_pEditorScene->getLights();
*index = light - lights;
}
result = (light != nullptr);
}
return result;
}
void EditorEngine::selectLight(u32 index)
{
m_selected.m_type = SelectedType::Light;
m_selected.m_item = m_pEditorScene->getLight(index);
}
void EditorEngine::deselectLight()
{
if (m_pEditorScene)
{
if (m_selected.m_type == SelectedType::Light)
{
m_selected.m_item = nullptr;
}
}
}
u32 EditorEngine::getLightCount()
{
return m_pEditorScene->getLightCount();
}
f32 EditorEngine::getLightLumen(u32 index)
{
auto light = m_pEditorScene->getLight(index);
return light->m_lumen;
}
void EditorEngine::setLightLumen(u32 index, f32 lumen)
{
auto light = m_pEditorScene->getLight(index);
light->m_lumen = lumen;
//m_renderAspect->updateLightBuffer(m_pEditorScene->getLights(), m_pEditorScene->getLightCount());
}
f32 EditorEngine::getLightFalloff(u32 index)
{
auto light = m_pEditorScene->getLight(index);
return light->m_falloff;
}
void EditorEngine::setLightFalloff(u32 index, f32 falloff)
{
auto light = m_pEditorScene->getLight(index);
light->m_falloff = falloff;
//m_renderAspect->updateLightBuffer(m_pEditorScene->getLights(), m_pEditorScene->getLightCount());
}
void EditorEngine::getLightPosition(u32 index, vx::float3* position)
{
auto light = m_pEditorScene->getLight(index);
*position = light->m_position;
}
void EditorEngine::setLightPosition(u32 index, const vx::float3* position)
{
auto light = m_pEditorScene->getLight(index);
light->m_position = *position;
m_renderAspect->updateLightBuffer(m_pEditorScene->getLights(), m_pEditorScene->getLightCount());
}
SelectedType EditorEngine::getSelectedItemType() const
{
return m_selected.m_type;
}
Editor::Scene* EditorEngine::getEditorScene() const
{
return m_pEditorScene;
}
void EditorEngine::showNavmesh(bool b)
{
if (m_pEditorScene)
{
auto &navMesh = m_pEditorScene->getNavMesh();
m_renderAspect->showNavMesh(b, navMesh, m_navmeshGraph);
}
}
void EditorEngine::showInfluenceMap(bool b)
{
if (m_pEditorScene)
{
m_renderAspect->showInfluenceMap(b, m_influenceMap);
}
}
bool EditorEngine::addWaypoint(s32 mouseX, s32 mouseY, vx::float3* position)
{
bool result = false;
vx::float3 hitPos;
auto sid = raytraceAgainstStaticMeshes(mouseX, mouseY, &hitPos);
if (sid.value != 0)
{
auto &navMesh = m_pEditorScene->getNavMesh();
if (navMesh.contains(hitPos))
{
m_pEditorScene->addWaypoint(hitPos);
m_renderAspect->updateWaypoints(m_pEditorScene->getWaypoints(), m_pEditorScene->getWaypointCount());
*position = hitPos;
result = true;
}
}
return result;
}
void EditorEngine::addWaypoint(const vx::float3 &position)
{
m_pEditorScene->addWaypoint(position);
m_renderAspect->updateWaypoints(m_pEditorScene->getWaypoints(), m_pEditorScene->getWaypointCount());
}
void EditorEngine::removeWaypoint(const vx::float3 &position)
{
m_pEditorScene->removeWaypoint(position);
m_renderAspect->updateWaypoints(m_pEditorScene->getWaypoints(), m_pEditorScene->getWaypointCount());
}
void EditorEngine::addSpawn()
{
if (m_pEditorScene)
{
Spawn spawn;
spawn.type = PlayerType::AI;
spawn.position = {0, 0, 0};
m_pEditorScene->addSpawn(std::move(spawn));
auto count = m_pEditorScene->getSpawnCount();
auto spawns = m_pEditorScene->getSpawns();
m_renderAspect->updateSpawns(spawns, count);
}
}
bool EditorEngine::selectSpawn(s32 mouseX, s32 mouseY, u32* id)
{
bool result = false;
if (m_pEditorScene)
{
auto ray = getRay(mouseX, mouseY);
auto spawnId = m_pEditorScene->getSpawnId(ray);
if (spawnId != 0xffffffff)
{
result = true;
*id = spawnId;
}
}
return result;
}
void EditorEngine::getSpawnPosition(u32 id, vx::float3* position) const
{
auto spawn = m_pEditorScene->getSpawn(id);
if (spawn)
{
*position = spawn->position;
}
}
u32 EditorEngine::getSpawnType(u32 id) const
{
u32 result = 0xffffffff;
auto spawn = m_pEditorScene->getSpawn(id);
if (spawn)
{
result = (u32)spawn->type;
}
return result;
}
void EditorEngine::setSpawnActor(u32 id, u64 actorSid)
{
m_pEditorScene->setSpawnActor(id, vx::StringID(actorSid));
}
u32 EditorEngine::getSpawnCount()
{
return m_pEditorScene->getSpawnCount();
}
u32 EditorEngine::getSpawnId(u32 index)
{
auto spawns = m_pEditorScene->getSpawns();
return spawns[index].id;
}
void EditorEngine::setSpawnPosition(u32 id, const vx::float3 &position)
{
auto spawns = m_pEditorScene->getSpawns();
auto count = m_pEditorScene->getSpawnCount();
m_pEditorScene->setSpawnPosition(id, position);
m_renderAspect->updateSpawns(spawns, count);
}
void EditorEngine::setSpawnType(u32 id, u32 type)
{
m_pEditorScene->setSpawnType(id, type);
}
u64 EditorEngine::getSpawnActor(u32 id)
{
auto spawn = m_pEditorScene->getSpawn(id);
return spawn->actorSid.value;
}
u32 EditorEngine::getMeshCount() const
{
if (m_pEditorScene)
return m_pEditorScene->getMeshes().size();
return 0;
}
const char* EditorEngine::getMeshName(u32 i) const
{
const char* meshName = nullptr;
if (m_pEditorScene)
{
auto &meshes = m_pEditorScene->getMeshes();
auto sid = meshes.keys()[i];
meshName = m_pEditorScene->getMeshName(sid);
}
return meshName;
}
u64 EditorEngine::getMeshSid(u32 i) const
{
u64 sidValue = 0;
if (m_pEditorScene)
{
auto &meshes = m_pEditorScene->getMeshes();
auto sid = meshes.keys()[i];
sidValue = sid.value;
}
return sidValue;
}
u32 EditorEngine::getMaterialCount() const
{
u32 count = 0;
if (m_pEditorScene)
{
count = m_pEditorScene->getMaterialCount();
}
return count;
}
const char* EditorEngine::getMaterialNameIndex(u32 i) const
{
const char* name = nullptr;
if (m_pEditorScene)
{
auto materials = m_pEditorScene->getMaterials();
auto sid = (*materials[i]).getSid();
name = m_pEditorScene->getMaterialName(sid);
}
return name;
}
const char* EditorEngine::getMaterialName(u64 sid) const
{
const char* name = nullptr;
if (m_pEditorScene)
{
name = m_pEditorScene->getMaterialName(vx::StringID(sid));
}
return name;
}
u64 EditorEngine::getMaterialSid(u32 i) const
{
u64 sidValue = 0;
if (m_pEditorScene)
{
auto materials = m_pEditorScene->getMaterials();
auto sid = (*materials[i]).getSid();
sidValue = sid.value;
}
return sidValue;
}
void EditorEngine::setMeshInstanceAnimation(u64 instanceSid, u64 animSid)
{
auto instance = m_pEditorScene->getMeshInstance(vx::StringID(instanceSid));
if (instance)
{
instance->setAnimationSid(vx::StringID(animSid));
}
}
u64 EditorEngine::getMeshInstanceAnimation(u64 instanceSid)
{
u64 result = 0;
auto instance = m_pEditorScene->getMeshInstance(vx::StringID(instanceSid));
if (instance)
{
result = instance->getAnimationSid().value;
}
return result;
}
u32 EditorEngine::getAnimationCount() const
{
return m_pEditorScene->getAnimationCount();
}
const char* EditorEngine::getAnimationNameIndex(u32 i) const
{
return m_pEditorScene->getAnimationNameIndex(i);
}
u64 EditorEngine::getAnimationSidIndex(u32 i) const
{
return m_pEditorScene->getAnimationSidIndex(i);
}
u32 EditorEngine::getMeshPhysxType(u64 sid) const
{
u32 type = 0xffffffff;
auto &meshes = m_pEditorScene->getMeshes();
auto it = meshes.find(vx::StringID(sid));
if (it != meshes.end())
{
type = (u32)(*it)->getPhysxMeshType();
}
return type;
}
void EditorEngine::setMeshPhysxType(u64 sid, u32 type)
{
auto meshSid = vx::StringID(sid);
auto meshFile = m_resourceAspect.getMesh(meshSid);
if (meshFile == nullptr)
{
return;
//VX_ASSERT(false);
/*auto &meshDataAllocator = m_resourceAspect.getMeshDataAllocator();
if (m_physicsAspect.setMeshPhysxType(meshFile, (PhsyxMeshType)type, &meshDataAllocator))
{
auto fileName = m_resourceAspect.getLoadedFileName(vx::StringID(sid));
m_fileAspect.requestSaveFile(vx::FileEntry(fileName, vx::FileType::Mesh), meshFile.get());
}*/
}
auto meshManager = m_resourceAspect.getMeshManager();
auto physxType = (PhsyxMeshType)type;
std::unique_lock<std::mutex> lock;
auto dataAllocator = meshManager->lockDataAllocator(&lock);
if (m_physicsAspect.setMeshPhysxType(meshFile, physxType, dataAllocator))
{
vx::Variant arg;
arg.ptr = meshFile;
auto meshName = meshManager->getName(meshSid);
vx::FileEntry fileEntry(meshName, vx::FileType::Mesh);
m_resourceAspect.requestSaveFile(fileEntry, arg);
}
}
u32 EditorEngine::getMeshInstanceRigidBodyType(u64 sid) const
{
u32 type = 0xffffffff;
auto it = m_pEditorScene->getMeshInstance(vx::StringID(sid));
if (it != nullptr)
{
type = (u32)it->getRigidBodyType();
}
return type;
}
void EditorEngine::setMeshInstanceRigidBodyType(u64 sid, u32 type)
{
auto instanceSid = vx::StringID(sid);
auto editorInstance = m_pEditorScene->getMeshInstance(instanceSid);
if (editorInstance != nullptr)
{
auto rigidBodyType = (PhysxRigidBodyType)type;
if (m_physicsAspect.setMeshInstanceRigidBodyType(instanceSid, editorInstance->getMeshInstance(), rigidBodyType))
{
editorInstance->setRigidBodyType(rigidBodyType);
}
}
}
void EditorEngine::addJoint(const vx::StringID &sid0, const vx::StringID &sid1, const vx::float3 &p0, const vx::float3 &p1)
{
Joint joint;
joint.sid0 = sid0;
joint.sid1 = sid1;
joint.p0 = p0;
joint.q0 = {0, 0, 0, 1};
joint.p1= p1;
joint.q1 = { 0, 0, 0, 1 };
joint.type = JointType::Revolute;
if (sid0.value != 0)
{
joint.p0.x = 0;
joint.p0.y = 0;
joint.p0.z = 0;
}
if (sid1.value != 0)
{
joint.p1.x = 0;
joint.p1.y = 0;
joint.p1.z = 0;
}
if (m_physicsAspect.createJoint(joint))
{
puts("created joint");
m_pEditorScene->addJoint(joint);
auto jointCount = m_pEditorScene->getJointCount();
auto joints = m_pEditorScene->getJoints();
auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
m_renderAspect->updateJoints(joints, jointCount, sortedInstances);
}
}
void EditorEngine::addJoint(const vx::StringID &sid)
{
auto instance = m_pEditorScene->getMeshInstance(sid);
if (instance)
{
auto &transform = instance->getTransform();
addJoint(sid, vx::StringID(0), transform.m_translation, transform.m_translation);
}
}
void EditorEngine::removeJoint(u32 index)
{
m_pEditorScene->eraseJoint(index);
auto jointCount = m_pEditorScene->getJointCount();
auto joints = m_pEditorScene->getJoints();
auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
m_renderAspect->updateJoints(joints, jointCount, sortedInstances);
}
u32 EditorEngine::getJointCount() const
{
return m_pEditorScene->getJointCount();
}
#include <DirectXMath.h>
void EditorEngine::getJointData(u32 i, vx::float3* p0, vx::float3* q0, vx::float3* p1, vx::float3* q1, u64* sid0, u64* sid1, u32* limitEnabled, f32* limitMin, f32* limitMax) const
{
auto quaternionToAngles = [](const vx::float4 &q, vx::float3* rotationDeg)
{
if (q.x == 0 && q.y == 0 && q.z == 0)
{
*rotationDeg = {0, 0, 0};
}
else
{
auto qq = vx::loadFloat4(&q);
__m128 axis, axis0;
f32 angle, angle0;
DirectX::XMQuaternionToAxisAngle(&axis0, &angle0, qq);
vx::quaternionToAxisAngle(qq, &axis, &angle);
axis = vx::normalize3(axis);
//auto ttt = _mm_mul_ps(axis, _mm_load1_ps(&angle));
vx::float4a tmpAxis = axis;
vx::angleAxisToEuler(tmpAxis, angle, rotationDeg);
}
};
auto joints = m_pEditorScene->getJoints();
auto &joint = joints[i];
quaternionToAngles(joint.q0, q0);
quaternionToAngles(joint.q1, q1);
*p0 = joint.p0;
*p1 = joint.p1;
*sid0 = joint.sid0.value;
*sid1 = joint.sid1.value;
*limitEnabled = joint.limitEnabled;
*limitMin = joint.limit.x;
*limitMax = joint.limit.y;
}
bool EditorEngine::selectJoint(s32 mouseX, s32 mouseY, u32* index)
{
auto ray = getRay(mouseX, mouseY);
ray.maxt = 10.0f;
auto joint = m_pEditorScene->getJoint(ray, index);
return (joint != nullptr);
}
void EditorEngine::setJointPosition0(u32 index, const vx::float3 &p)
{
m_pEditorScene->setJointPosition0(index, p);
auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
m_renderAspect->updateJoints(m_pEditorScene->getJoints(), m_pEditorScene->getJointCount(), sortedInstances);
}
void EditorEngine::setJointPosition1(u32 index, const vx::float3 &p)
{
m_pEditorScene->setJointPosition1(index, p);
auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
m_renderAspect->updateJoints(m_pEditorScene->getJoints(), m_pEditorScene->getJointCount(), sortedInstances);
}
void EditorEngine::setJointBody0(u32 index, u64 sid)
{
m_pEditorScene->setJointBody0(index, sid);
}
void EditorEngine::setJointBody1(u32 index, u64 sid)
{
m_pEditorScene->setJointBody1(index, sid);
}
void EditorEngine::setJointRotation0(u32 index, const vx::float3 &q)
{
auto qq = vx::quaternionRotationRollPitchYawFromVector(vx::degToRad(vx::loadFloat3(&q)));
vx::float4 tmp;
vx::storeFloat4(&tmp, qq);
m_pEditorScene->setJointRotation0(index, tmp);
auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
m_renderAspect->updateJoints(m_pEditorScene->getJoints(), m_pEditorScene->getJointCount(), sortedInstances);
}
void EditorEngine::setJointRotation1(u32 index, const vx::float3 &q)
{
auto qq = vx::quaternionRotationRollPitchYawFromVector(vx::degToRad(vx::loadFloat3(&q)));
vx::float4 tmp;
vx::storeFloat4(&tmp, qq);
m_pEditorScene->setJointRotation1(index, tmp);
auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
m_renderAspect->updateJoints(m_pEditorScene->getJoints(), m_pEditorScene->getJointCount(), sortedInstances);
}
void EditorEngine::setJointLimit(u32 index, u32 enabled, f32 limitMin, f32 limitMax)
{
m_pEditorScene->setJointLimit(index, enabled, limitMin, limitMax);
}
u64 EditorEngine::createActor(const char* name, u64 meshSid, u64 materialSid)
{
vx::FileEntry fileEntry(name, vx::FileType::Actor);
auto actorFile = new ActorFile(ActorFile::getGlobalVersion());
auto materialName = m_resourceAspect.getMaterialManager()->getName(vx::StringID(materialSid));
auto meshName = m_resourceAspect.getMeshManager()->getName(vx::StringID(meshSid));
const u32 bufferSize = 31;
auto meshSize = strlen(meshName);
auto materialSize = strlen(materialName);
VX_ASSERT(bufferSize >= meshSize && bufferSize >= materialSize);
char buffer[bufferSize + 1];
memset(buffer, 0, sizeof(buffer));
memcpy(buffer, meshName, meshSize);
actorFile->setMesh(buffer);
memset(buffer, 0, sizeof(buffer));
memcpy(buffer, materialName, materialSize);
actorFile->setMaterial(buffer);
vx::Variant arg;
arg.ptr = actorFile;
m_resourceAspect.requestSaveFile(fileEntry, arg);
Actor actor;
actor.m_mesh = meshSid;
actor.m_material = materialSid;
m_resourceAspect.addActor(fileEntry.getSid(), std::string(name), actor);
return fileEntry.getSid().value;
}
const char* EditorEngine::getActorName(u64 sid) const
{
return m_resourceAspect.getActorManager()->getName(vx::StringID(sid));
}
u32 EditorEngine::getLightGeometryProxyCount() const
{
return m_pEditorScene->getLightGeometryProxyCount();
}
void EditorEngine::createLightGeometryProxy(const vx::float3 ¢er, const vx::float3 &halfDim)
{
AABB bounds;
bounds.min = center - halfDim;
bounds.max = center + halfDim;
m_pEditorScene->addLightGeometryProxy(bounds);
m_renderAspect->updateLightGeometryProxies(m_pEditorScene->getLightGeometryProxies(), m_pEditorScene->getLightGeometryProxyCount());
}
void EditorEngine::setLightGeometryProxyBounds(u32 index, const vx::float3 ¢er, const vx::float3 &halfDim)
{
AABB bounds;
bounds.min = center - halfDim;
bounds.max = center + halfDim;
m_pEditorScene->setLightGeometryProxyBounds(index, bounds);
m_renderAspect->updateLightGeometryProxies(m_pEditorScene->getLightGeometryProxies(), m_pEditorScene->getLightGeometryProxyCount());
}
void EditorEngine::getLightGeometryProxyBounds(u32 index, vx::float3* center, vx::float3* halfDimOut) const
{
auto ptr = m_pEditorScene->getLightGeometryProxies();
auto bounds = ptr[index].m_bounds;
auto halfDim = (bounds.max - bounds.min) * 0.5f;
*center = bounds.min + halfDim;
*halfDimOut = halfDim;
}
u32 EditorEngine::getLightGeometryProxyLightCount(u32 index) const
{
auto ptr = m_pEditorScene->getLightGeometryProxies();
return ptr[index].m_lightCount;
}
void EditorEngine::testLightGeometryProxies()
{
Editor::TestLightGeometryProxiesDesc desc;
desc.lightCount = m_pEditorScene->getLightCount();
desc.lights = m_pEditorScene->getLights();
desc.proxies = m_pEditorScene->getLightGeometryProxies();
desc.proxyCount = m_pEditorScene->getLightGeometryProxyCount();
m_renderAspect->testLightGeometryProxies(desc);
} |
ff04249c7815894a999b14200cce4bf94bee6a71 | a57a2367d3bb2394a9075ff20f124593bb78e3b0 | /GLTestAZDO/Math/Matrix44.h | eedd7fe76da99ad050dda71a6dc6a41265ea89ea | [] | no_license | guiltydogprods/GLTestAZDO | d72f218ccec16af6ea2bf54c3e7765d5d0a1390e | 07458c1b95a8703fee0982de2d0af62c89738842 | refs/heads/master | 2020-04-18T20:23:45.783700 | 2019-01-26T20:50:04 | 2019-01-26T20:50:04 | 167,736,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,917 | h | Matrix44.h | //
// Matrix44.h
// ion
//
// Created by Claire Rogers on 14/10/2012.
// Copyright (c) 2013 Guilty Dog Productions Ltd. All rights reserved.
//
#pragma once
#include "Vector4.h"
#include "Vector.h"
#include "Point.h"
class Quat;
enum IdentityTag {kIdentity};
class Matrix44
{
public:
Vector4 m_xAxis;
Vector4 m_yAxis;
Vector4 m_zAxis;
Vector4 m_wAxis;
Matrix44();
Matrix44(Vector4 v1, Vector4 v2, Vector4 v3, Vector4 v4);
Matrix44(IdentityTag);
Matrix44(Point& position, Quat& rotation);
void SetAxisX(Vector4 axis);
void SetAxisY(Vector4 axis);
void SetAxisZ(Vector4 axis);
void SetAxisW(Vector4 axis);
inline Vector4 GetAxisX() { return m_xAxis; }
inline Vector4 GetAxisY() { return m_yAxis; }
inline Vector4 GetAxisZ() { return m_zAxis; }
inline Vector4 GetAxisW() { return m_wAxis; }
void SetIdentity();
void SetRotation(float angle, Vector axis);
void SetTranslate(Point translation);
void SetTranslate(Vector translation);
void SetScale(float scale);
void SetFromPositionAndRotation(Point& position, Matrix44& rotation);
void SetFromPositionAndRotation(Point& position, Quat& rotation);
Vector4 operator*(Vector4 right) const;
Point operator*(Point right) const;
// Vector4 operator *(Vector4 right) const;
Matrix44 operator*(float right);
Matrix44 operator+(Matrix44& right);
Matrix44 operator*(const Matrix44& right) const;
static void Ortho(Matrix44& result, float left, float right, float bottom, float top, float zNear, float zFar);
static void Frustum(Matrix44& result, float left, float right, float bottom, float top, float nearZ, float farZ);
};
// non-member functions, which need to be friends
void SetIdentity(Matrix44& mat);
Matrix44 Transpose(Matrix44& mat);
Matrix44 OrthoInverse(const Matrix44& mat);
Matrix44 Inverse(Matrix44& mat);
void PrintMatrix(const char* text, Matrix44& mat);
|
d5fd58885711eaa9cc29f5ff0bca67a7e6c397a3 | 0caf48a5173071de72f8f122fce578c15a515191 | /Project L/GUI/Text.h | 233cccdbb058e76ede6f583fb6ffb39e7b3c25ab | [] | no_license | jonathan2222/Project-L | bf88f975958d8403584e9d76a78990687f2d1c94 | e1bae19f1c306880df42b1c859c7f9e833538359 | refs/heads/master | 2020-03-21T19:12:10.069090 | 2018-07-12T16:16:40 | 2018-07-12T16:16:40 | 138,934,979 | 0 | 0 | null | 2018-07-09T13:01:49 | 2018-06-27T21:30:42 | C | UTF-8 | C++ | false | false | 794 | h | Text.h | #ifndef TEXT_H
#define TEXT_H
#include <string>
#include "Font.h"
#include "../Maths/Vectors/Vec4.h"
class Text
{
public:
struct CharacterRect
{
GLuint textureID;
struct Rect
{
Vec4 tl;
Vec4 tr;
Vec4 bl;
Vec4 br;
} rect;
};
public:
Text();
Text(const std::string& text, Font* font);
~Text();
void setColor(const Vec4& color);
void setText(const std::string & text, Font* font = nullptr);
Vec4 getColor() const;
float getWidth() const; // In bitmap pixels.
float getHeight() const; // In bitmap pixels.
float getBearingY() const; // In bitmap pixels.
std::vector<CharacterRect> getCharacterRects();
private:
std::string text;
float width;
float height;
float bearingY;
Vec4 color;
Font* font;
std::vector<CharacterRect> characterRects;
};
#endif
|
c9f010d6521cf6c0878d40c9db3c7e4a3ae0dd58 | 9635d9bc8eb87a0435e51ea2ecb54ab7b8da0e48 | /sectiontoken.h | 103d4d560913d421b9967fabbb22ed0a27068401 | [] | no_license | lcadenas/Interactive-Fiction-Project | 2fa3c0cd9818699725b8ac12913dbaae5c0164a0 | 441b3fd70d5d4e7d88b97da1fe0140b7e7ee8e45 | refs/heads/master | 2020-04-07T17:53:45.420918 | 2019-01-29T06:10:00 | 2019-01-29T06:10:00 | 158,588,183 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 349 | h | sectiontoken.h | #ifndef __SECTIONTOKEN_H
#define __SECTIONTOKEN_H
#include <iostream>
#include <string>
using namespace std;
enum Type_t { LINK, GOTO, SET, IF, ELSEIF, ELSE, BLOCK, TEXT };
class SectionToken
{
private:
Type_t type;
string sectiontext;
public:
SectionToken(string sect);
string getText();
Type_t getType();
};
#endif
|
1c238e59f2beec9790adbe1139bb2b6146dd437e | 25590fa39d365f8cf43d73114f24f9e9a28eb7e2 | /Lecture-18 Trees/binary_tree.cpp | abc3cbae8002b6354d211aecedbe1d679680c0b8 | [] | no_license | coding-blocks-archives/Launchpad-LIVE-June-2017 | 767e89b7533967403d185f1064035352d19ef5b9 | b501baaafdeebcca75854386e844099bf09dab49 | refs/heads/master | 2021-01-20T05:13:06.691930 | 2017-08-25T16:38:44 | 2017-08-25T16:38:44 | 101,419,477 | 1 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 5,220 | cpp | binary_tree.cpp | #include<iostream>
#include<queue>
using namespace std;
class node{
public:
int data;
node*left;
node*right;
node(int d){
data = d;
left = NULL;
right = NULL;
}
};
///recursive fn
node* buildTree(){
//cout<<"Enter the data ";
int d;
cin>>d;
if(d==-1){
return NULL;
}
///Rec Case
node* n = new node(d);
n->left = buildTree();
n->right = buildTree();
return n;
}
///Tree Build Function - Using Iteration ( Level by Level )
void levelOrderInput(node*&root){
cout<<"Enter the root node ";
int d;
cin>>d;
root = new node(d);
queue<node*> q;
q.push(root);
while(!q.empty()){
node*parent = q.front();
q.pop();
int c1,c2;
cout<<"Enter children of "<<parent->data<<" ";
cin>>c1>>c2;
if(c1!=-1){
parent->left = new node(c1);
q.push(parent->left);
}
if(c2!=-1){
parent->right = new node(c2);
q.push(parent->right);
}
}
}
void printTree(node*root){
if(root==NULL){
return;
}
///Print the current node
cout<<root->data<<" ";
///Call on left and right subtrees
printTree(root->left);
printTree(root->right);
}
int height(node*root){
if(root==NULL){
return 0;
}
return 1 + max(height(root->left),height(root->right));
}
/// Diameter of Tree
int diameter(node*root){
if(root==NULL){
return 0;
}
int op1 = height(root->left) + height(root->right);
int op2 = diameter(root->left);
int op3 = diameter(root->right);
return max(op1,max(op2,op3));
}
///Each node should return 2 things, so i make a wrapper
class myPair{
public:
int height;
int diameter;
};
myPair diameterFast(node*root){
///Null tree
myPair p;
if(root==NULL){
p.diameter = 0;
p.height = 0;
return p;
}
myPair left = diameterFast(root->left);
myPair right = diameterFast(root->right);
int d1 = left.diameter;
int d2 = right.diameter;
int h1= left.height;
int h2 = right.height;
p.diameter = max(h1+h2,max(d1,d2));
p.height = max(h1,h2) + 1;
return p;
}
///Print the tree level by level
void levelOrderPrint(node*root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node* f = q.front();
q.pop();
cout<<f->data<<" ";
if(f->left){
q.push(f->left);
}
if(f->right){
q.push(f->right);
}
}
}
///Print the tree level by level
void levelOrderPrint2(node*root){
queue<node*> q;
q.push(root);
q.push(NULL);
while(!q.empty()){
node* f = q.front();
if(f==NULL){
q.pop();
cout<<endl;
if(!q.empty()){
q.push(NULL);
}
}
else{
q.pop();
cout<<f->data<<" ";
if(f->left){
q.push(f->left);
}
if(f->right){
q.push(f->right);
}
}
}
}
void printInorder(node*root){
if(root==NULL){
return;
}
printInorder(root->left);
cout<<root->data<<" ";
printInorder(root->right);
}
void postOrder(node*root){
if(root==NULL){
return;
}
postOrder(root->left);
postOrder(root->right);
cout<<root->data<<" ";
}
int countNodes(node*root){
if(root==NULL){
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
void printNodesAtLevelK(node *root,int k){
if(root==NULL){
return;
}
if(k==0){
cout<<root->data<<" ";
}
printNodesAtLevelK(root->left,k-1);
printNodesAtLevelK(root->right,k-1);
}
void mirror(node*root){
if(root==NULL){
return ;
}
swap(root->left,root->right);
mirror(root->left);
mirror(root->right);
}
class sumPair{
public:
int inc;
int exc;
};
sumPair maxSumProblem(node*root){
sumPair p;
if(root==NULL){
p.inc = 0;
p.exc = 0;
return p;
}
///Call on the left and right part
sumPair left = maxSumProblem(root->left);
sumPair right =maxSumProblem(root->right);
p.inc = root->data + left.exc + right.exc;
p.exc = max(left.inc,left.exc) + max(right.inc,right.exc);
return p;
}
int main(){
node* root = NULL;
//root = buildTree();
levelOrderInput(root);
///Print this tree
cout<<"Preorder Print "<<endl;
printTree(root);
cout<<endl;
cout<<"Inorder Print "<<endl;
printInorder(root);
cout<<endl;
cout<<"Post order Print "<<endl;
postOrder(root);
cout<<endl;
///level order
cout<<"\n Level Order Print "<<endl;
levelOrderPrint2(root);
cout<<"Count is "<<countNodes(root)<<endl;
cout<<"Height is "<<height(root)<<endl;
cout<<"Diameter is "<<diameter(root)<<endl;
cout<<"Fast diameter is "<<diameterFast(root).diameter<<endl;
sumPair p =maxSumProblem(root);
int ans = max(p.inc,p.exc);
cout<<"Final possible max sum is "<<ans<<endl;
mirror(root);
levelOrderPrint2(root);
return 0;
}
|
b01836ffae68611db9cd8651e308f0320c2f8ed7 | 050c8a810d34fe125aecae582f9adfd0625356c6 | /fmi2020/expected3.cpp | 23a704ffd1493db7b11daa4f4b1dfcdd85760938 | [] | no_license | georgerapeanu/c-sources | adff7a268121ae8c314e846726267109ba1c62e6 | af95d3ce726325dcd18b3d94fe99969006b8e138 | refs/heads/master | 2022-12-24T22:57:39.526205 | 2022-12-21T16:05:01 | 2022-12-21T16:05:01 | 144,864,608 | 11 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,826 | cpp | expected3.cpp | #include <cstdio>
using namespace std;
FILE *f = fopen("expected3.in","r");
FILE *g = fopen("expected3.out","w");
const int LEN = 1 << 12;
char buff[LEN];
int ind = LEN - 1;
int i32(){
int ans = 0;
int sgn = 1;
while((buff[ind] < '0' || buff[ind] > '9') && buff[ind] != '-'){
if(++ind >= LEN){
ind = 0;
fread(buff,1,LEN,f);
}
}
if(buff[ind] == '-'){
sgn *= -1;
if(++ind >= LEN){
ind = 0;
fread(buff,1,LEN,f);
}
}
while(!(buff[ind] < '0' || buff[ind] > '9')){
ans = ans * 10 + (buff[ind] - '0');
if(++ind >= LEN){
ind = 0;
fread(buff,1,LEN,f);
}
}
return ans * sgn;
}
long double dp[10][10];
const int MOD = 1e9 + 7;
const int inv2 = MOD / 2 + 1;
int add(int a,int b){
a += b;
if(a >= MOD){
a -= MOD;
}
return a;
}
int scad(int a,int b){
a -= b;
if(a < 0){
a += MOD;
}
return a;
}
int mult(int a,int b){
return 1LL * a * b % MOD;
}
int main(){
/*
for(int i = 0;i < 10;i++){
for(int j = 0;j < 10;j++){
if(i == 0 && j == 0){
dp[i][j] = 0;
printf("%.4f ",double(dp[i][j]));
continue;
}
if(i > 0){
dp[i][j] += i * (dp[i - 1][j] + 1) / ((long double)i + j + 1);
}
if(j > 0){
dp[i][j] += j * (dp[i][j - 1]) / ((long double)i + j + 1);
}
printf("%.4f ",double(dp[i][j]));
}
printf("\n");
}
*/
int n,m,a,b;
n = i32();
m = i32();
a = i32();
b = i32();
fprintf(g,"%d\n",scad(mult(a,mult(n,inv2)),mult(b,mult(m,inv2))));
fclose(f);
fclose(g);
return 0;
}
|
a85beec6441910ea711c277cf6ff3bea4215c7e4 | 23a47976563db56e5c65f77c1ec9c767e7704bd5 | /old source/FuzzyTool/FuzzyTool/DataSetsReadCripsFile.cpp | 7db618367bbca9377e5cbd33bda2a689ceb961b4 | [] | no_license | chovancova/diploma-thesis-fuzzification | 732673798fa6c0afa996e937977024bc529bc09a | f3621bd1c3fadfba4a28ef6b21e32368089fc631 | refs/heads/master | 2021-01-18T19:45:50.642359 | 2017-04-29T06:46:50 | 2017-04-29T06:46:50 | 64,826,549 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,143 | cpp | DataSetsReadCripsFile.cpp | #include <cstdio>
#include "DataSets.h"
#include <cstring>
// -------------------------- ReadCrispFile - IRIS -----------------------
int DataSets::read_crisp_file_iris(FILE* fp)
{
char Label[20];
for (unsigned long k = 0; k < DatasetSize; k++)
{
fscanf(fp, "%f,%f,%f,%f,%s",
&Pattern[k].Feature[0],
&Pattern[k].Feature[1],
&Pattern[k].Feature[2],
&Pattern[k].Feature[3],
Label);
if (!strcmp(Label, "Iris-setosa"))
{
Pattern[k].Feature[InputAttributes] = 0.0;
}
if (!strcmp(Label, "Iris-versicolor"))
{
Pattern[k].Feature[InputAttributes] = 1.0;
}
if (!strcmp(Label, "Iris-virginica"))
{
Pattern[k].Feature[InputAttributes] = 2.0;
}
}
return 1;
}
// -------------------------- ReadCrispFile - HEART --------------------------
int DataSets::read_crisp_file_heart(FILE* fp)
{
for (unsigned long k = 0; k < DatasetSize; k++)
{
fscanf(fp, "%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f",
&Pattern[k].Feature[0],
&Pattern[k].Feature[1],
&Pattern[k].Feature[2],
&Pattern[k].Feature[3],
&Pattern[k].Feature[4],
&Pattern[k].Feature[5],
&Pattern[k].Feature[6],
&Pattern[k].Feature[7],
&Pattern[k].Feature[8],
&Pattern[k].Feature[9],
&Pattern[k].Feature[10],
&Pattern[k].Feature[11],
&Pattern[k].Feature[12],
&Pattern[k].Feature[13]);
Pattern[k].Feature[2]--;
Pattern[k].Feature[10]--;
Pattern[k].Feature[13]--;
if (Pattern[k].Feature[12] == 3) { Pattern[k].Feature[12] = 0.0; }
if (Pattern[k].Feature[12] == 6) { Pattern[k].Feature[12] = 1.0; }
if (Pattern[k].Feature[12] == 7) { Pattern[k].Feature[12] = 2.0; }
}
LingvisticAttributes[1] = 2; // Feature[2] - sex
LingvisticAttributes[2] = 4; // Feature[3] - chest pain type (1-4)
LingvisticAttributes[5] = 2; // Feature[6] - fasting blood sugar > 120 mg/dl
LingvisticAttributes[6] = 3; // Feature[7] - hresting electrocardiographic results (0,1,2)
LingvisticAttributes[8] = 2; // Feature[9] - exercise induced angina
LingvisticAttributes[10] = 3; // Feature[11] - the slope of the peak exercise ST segment
LingvisticAttributes[11] = 4; // Feature[12] - number of major vessels (0-3) colored by flourosopy
LingvisticAttributes[12] = 3; // Feature[13] - thal: 0->3 (normal); 1->6 (fixed defect); 2->7 (reversable defect)
return 1;
}
// -------------------------- ReadCrispFile - Yeast --------------------------
int DataSets::read_crisp_file_yeast(FILE* fp)
{
char Label[15], DescriptionTemp[15];
for (unsigned long k = 0; k < DatasetSize; k++)
{
//AATC_YEAST 0.51 0.40 0.56 0.17 0.50 0.50 0.49 0.22 CYT
fscanf(fp, "%s %f %f %f %f %f %f %f %f %s", DescriptionTemp,
&Pattern[k].Feature[0],
&Pattern[k].Feature[1],
&Pattern[k].Feature[2],
&Pattern[k].Feature[3],
&Pattern[k].Feature[4],
&Pattern[k].Feature[5],
&Pattern[k].Feature[6],
&Pattern[k].Feature[7],
Label);
if (Pattern[k].Feature[4] == 0.50) Pattern[k].Feature[4] = 0.0;
if (Pattern[k].Feature[5] == 0.50) Pattern[k].Feature[5] = 1.0;
if (Pattern[k].Feature[5] == 0.83) Pattern[k].Feature[5] = 2.0;
if (!strcmp(Label, "CYT")) Pattern[k].Feature[InputAttributes] = 0.0;
if (!strcmp(Label, "NUC")) Pattern[k].Feature[InputAttributes] = 1.0;
if (!strcmp(Label, "MIT")) Pattern[k].Feature[InputAttributes] = 2.0;
if (!strcmp(Label, "ME3")) Pattern[k].Feature[InputAttributes] = 3.0;
if (!strcmp(Label, "ME2")) Pattern[k].Feature[InputAttributes] = 4.0;
if (!strcmp(Label, "ME1")) Pattern[k].Feature[InputAttributes] = 5.0;
if (!strcmp(Label, "EXC")) Pattern[k].Feature[InputAttributes] = 6.0;
if (!strcmp(Label, "VAC")) Pattern[k].Feature[InputAttributes] = 7.0;
if (!strcmp(Label, "POX")) Pattern[k].Feature[InputAttributes] = 8.0;
if (!strcmp(Label, "ERL")) Pattern[k].Feature[InputAttributes] = 9.0;
}
LingvisticAttributes[4] = 2; // 0.5 1.0
LingvisticAttributes[5] = 3; // 0.0 0.5 0.83
return 1;
}
// -------------------------- ReadCrispFile - WINE ----------------------
int DataSets::read_crisp_file_wine(FILE* fp)
{
for (unsigned long k = 0; k < DatasetSize; k++)
{
//1,14.2,1.76,2.45,15.2,112,3.27,3.39,.34,1.97,6.75,1.05,2.85,1450
fscanf(fp, "%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f",
&Pattern[k].Feature[13],
&Pattern[k].Feature[0],
&Pattern[k].Feature[1],
&Pattern[k].Feature[2],
&Pattern[k].Feature[3],
&Pattern[k].Feature[4],
&Pattern[k].Feature[5],
&Pattern[k].Feature[6],
&Pattern[k].Feature[7],
&Pattern[k].Feature[8],
&Pattern[k].Feature[9],
&Pattern[k].Feature[10],
&Pattern[k].Feature[11],
&Pattern[k].Feature[12]);
--Pattern[k].Feature[InputAttributes]; // InputAttributes == 13
}
return 1;
}
// -------------------------- ReadCrispFile - SKIN --------------------------
int DataSets::read_crisp_file_skin(FILE* fp)
{
//70 81 119 1
for (unsigned long k = 0; k < DatasetSize; k++)
{
fscanf(fp, "%f %f %f %f",
&Pattern[k].Feature[0],
&Pattern[k].Feature[1],
&Pattern[k].Feature[2],
&Pattern[k].Feature[3]);
--Pattern[k].Feature[3]; // Normalization from 0 till OutputIntervals-1
}
return 1;
}
// -------------------------- ReadCrispFile - Seeds -----------------------
int DataSets::read_crisp_file_seeds(FILE* fp)
{
for (unsigned long k = 0; k < DatasetSize; k++)
{
fscanf(fp, "%f %f %f %f %f %f %f %f",
&Pattern[k].Feature[0],
&Pattern[k].Feature[1],
&Pattern[k].Feature[2],
&Pattern[k].Feature[3],
&Pattern[k].Feature[4],
&Pattern[k].Feature[5],
&Pattern[k].Feature[6],
&Pattern[k].Feature[7]);
Pattern[k].Feature[7]--;
}
return 1;
}
//
//// -------------------------- ReadCrispFile - WINERED & WINEWHITE --------------------------
//int DataSets::ReadCrispFileWineQuality(FILE* fp)
//{
// for (unsigned long k = 0; k < DatasetSize; k++)
// {
// fscanf(fp, "%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f",
// &Pattern[k].Feature[0],
// &Pattern[k].Feature[1],
// &Pattern[k].Feature[2],
// &Pattern[k].Feature[3],
// &Pattern[k].Feature[4],
// &Pattern[k].Feature[5],
// &Pattern[k].Feature[6],
// &Pattern[k].Feature[7],
// &Pattern[k].Feature[8],
// &Pattern[k].Feature[9],
// &Pattern[k].Feature[10],
// &Pattern[k].Feature[11]);
//
// Pattern[k].Feature[11] -= 3;
// }
// return 1;
//}
// -------------------------- ReadCrispFile - HEART --------------------------
int DataSets::read_crisp_file_heart_short(FILE* fp)
{
for (unsigned long k = 0; k < DatasetSize; k++)
{
fscanf(fp, "%f %f %f %f %f %f",
&Pattern[k].Feature[0],
&Pattern[k].Feature[1],
&Pattern[k].Feature[2],
&Pattern[k].Feature[3],
&Pattern[k].Feature[4],
&Pattern[k].Feature[5]
);
--Pattern[k].Feature[5];
}
return 1;
} |
7e68354c625ee9fd887824217ae25148b4125864 | e41bec1960790c4522d03e14f565f0403434fd95 | /MicroScoper/DlgModuleControl.cpp | 5d216dcf07e16bd0b6c4b477650dae995173c95d | [] | no_license | dreamplayerzhang/WS_MicroScoper | 5f6f453f72018cc7e21b2c01a03dcdc79c619127 | c9c9ad7c2ef110b4572ca0f441321ce2e47849c9 | refs/heads/master | 2021-12-09T03:04:49.010995 | 2016-04-17T14:36:42 | 2016-04-17T14:36:42 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 5,316 | cpp | DlgModuleControl.cpp | // DlgModuleControl.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "MicroScoper.h"
#include "DlgModuleControl.h"
#include "afxdialogex.h"
// CDlgModuleControl 대화 상자입니다.
IMPLEMENT_DYNAMIC(CDlgModuleControl, CDialog)
CDlgModuleControl::CDlgModuleControl(CWnd* pParent, COLORREF nDialogColor)
: CDialog(CDlgModuleControl::IDD, pParent), CDialogInterface(nDialogColor)
{
m_pDlgModuleControl2Parent = NULL;
m_nMagnificLevel = 0;
}
CDlgModuleControl::~CDlgModuleControl()
{
}
void CDlgModuleControl::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_SLIDER_LIGHT_LEVEL, m_ctrlLightLevel);
DDX_Control(pDX, IDC_SLIDER_JOG_SPEED_LEVEL, m_ctrlJogSpeedLevel);
DDX_Control(pDX, IDC_CHECK_CAMERA_CONTROL, m_ctrlCameraControl);
DDX_Control(pDX, IDC_CHECK_AFM_TRACK, m_ctrlAFMTracking);
DDX_Radio(pDX, IDC_RADIO_MAG_LEVEL_0, m_nMagnificLevel);
DDX_Control(pDX, IDC_GRID_MOTOR_GO_POS, m_ctrlMotoGoPos);
DDX_Control(pDX, IDC_GRID_GLASS_GO_POS, m_ctrlGlassGoPos);
DDX_Control(pDX, IDC_GRID_ROTATE_MOTOR_POS, m_ctrlRotateMotorGoPos);
}
BEGIN_MESSAGE_MAP(CDlgModuleControl, CDialog)
ON_BN_CLICKED(IDOK, &CDlgModuleControl::OnBnClickedOk)
ON_BN_CLICKED(IDCANCEL, &CDlgModuleControl::OnBnClickedCancel)
ON_WM_CTLCOLOR()
ON_NOTIFY(NM_RELEASEDCAPTURE, IDC_SLIDER_LIGHT_LEVEL, &CDlgModuleControl::OnNMReleasedcaptureSliderLightLevel)
ON_NOTIFY(NM_RELEASEDCAPTURE, IDC_SLIDER_JOG_SPEED_LEVEL, &CDlgModuleControl::OnNMReleasedcaptureSliderJogSpeedLevel)
END_MESSAGE_MAP()
// CDlgModuleControl 메시지 처리기입니다.
void CDlgModuleControl::OnBnClickedOk()
{
}
void CDlgModuleControl::OnBnClickedCancel()
{
}
BOOL CDlgModuleControl::OnInitDialog()
{
CDialog::OnInitDialog();
InitGridControls();
CString tmp = _T("");
// slider light level
m_ctrlLightLevel.SetRange(0, 1000);
m_ctrlLightLevel.SetRange(0, 1000);
m_ctrlLightLevel.SetRangeMin(0);
m_ctrlLightLevel.SetRangeMax(1000);
m_ctrlLightLevel.SetTicFreq(1);
m_ctrlLightLevel.SetLineSize(5);
m_ctrlLightLevel.SetPageSize(50);
m_ctrlLightLevel.SetPos(200);
tmp.Format(_T("%.1lf%%"), m_ctrlLightLevel.GetPos() / 10.0);
SetDlgItemText(IDC_STATIC_LIGHT_LEVEL, tmp);
// slider jog speed
m_ctrlJogSpeedLevel.SetRange(0, 1000);
m_ctrlJogSpeedLevel.SetRangeMin(0);
m_ctrlJogSpeedLevel.SetRangeMax(1000);
m_ctrlJogSpeedLevel.SetTicFreq(1);
m_ctrlJogSpeedLevel.SetLineSize(5);
m_ctrlJogSpeedLevel.SetPageSize(50);
m_ctrlJogSpeedLevel.SetPos(200);
tmp.Format(_T("%.1lf%%"), m_ctrlJogSpeedLevel.GetPos() / 10.0);
SetDlgItemText(IDC_STATIC_JOG_SPEED_LEVEL, tmp);
return TRUE;
}
HBRUSH CDlgModuleControl::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// pDC->SetBkMode(TRANSPARENT);
// return (HBRUSH) m_hControlColor[nCtlColor];
//
// if (nCtlColor == CTLCOLOR_DLG)
// {
// pDC->SetBkMode(TRANSPARENT);
// return (HBRUSH) m_hControlColor[nCtlColor];
// }
return hbr;
}
void CDlgModuleControl::InitGridControls()
{
#define GO_POS_GRID_ROW_COUNT 1
#define GO_POS_GRID_COL_COUNT 2
int nRows = GO_POS_GRID_ROW_COUNT;
int nCols = GO_POS_GRID_COL_COUNT;
// motor pos
m_ctrlMotoGoPos.GetDefaultCell(TRUE, FALSE)->SetBackClr(RGB(144, 200, 246));
m_ctrlMotoGoPos.GetDefaultCell(FALSE, TRUE)->SetBackClr(RGB(144, 200, 246));;
m_ctrlMotoGoPos.GetDefaultCell(FALSE, FALSE)->SetBackClr(RGB(255, 255, 255));
m_ctrlMotoGoPos.SetRowCount(nRows);
m_ctrlMotoGoPos.SetColumnCount(nCols);
m_ctrlMotoGoPos.SetFixedRowCount(0);
m_ctrlMotoGoPos.SetFixedColumnCount(0);
m_ctrlMotoGoPos.ExpandToFit(TRUE);
// glass pos
m_ctrlGlassGoPos.GetDefaultCell(TRUE, FALSE)->SetBackClr(RGB(144, 200, 246));
m_ctrlGlassGoPos.GetDefaultCell(FALSE, TRUE)->SetBackClr(RGB(144, 200, 246));;
m_ctrlGlassGoPos.GetDefaultCell(FALSE, FALSE)->SetBackClr(RGB(255, 255, 255));
m_ctrlGlassGoPos.SetRowCount(nRows);
m_ctrlGlassGoPos.SetColumnCount(nCols);
m_ctrlGlassGoPos.SetFixedRowCount(0);
m_ctrlGlassGoPos.SetFixedColumnCount(0);
m_ctrlGlassGoPos.ExpandToFit(TRUE);
// rotate motor pos
m_ctrlRotateMotorGoPos.GetDefaultCell(TRUE, FALSE)->SetBackClr(RGB(144, 200, 246));
m_ctrlRotateMotorGoPos.GetDefaultCell(FALSE, TRUE)->SetBackClr(RGB(144, 200, 246));;
m_ctrlRotateMotorGoPos.GetDefaultCell(FALSE, FALSE)->SetBackClr(RGB(255, 255, 255));
m_ctrlRotateMotorGoPos.SetRowCount(nRows);
m_ctrlRotateMotorGoPos.SetColumnCount(nCols);
m_ctrlRotateMotorGoPos.SetFixedRowCount(0);
m_ctrlRotateMotorGoPos.SetFixedColumnCount(1);
m_ctrlRotateMotorGoPos.ExpandToFit(TRUE);
}
void CDlgModuleControl::OnNMReleasedcaptureSliderLightLevel(NMHDR *pNMHDR, LRESULT *pResult)
{
if (m_pDlgModuleControl2Parent==NULL) return;
double dValue = m_ctrlLightLevel.GetPos() / 1000.0;
CString tmp = _T("");
tmp.Format(_T("%.1lf%%"), m_ctrlLightLevel.GetPos() / 10.0);
SetDlgItemText(IDC_STATIC_LIGHT_LEVEL, tmp);
*pResult = 0;
}
void CDlgModuleControl::OnNMReleasedcaptureSliderJogSpeedLevel(NMHDR *pNMHDR, LRESULT *pResult)
{
if (m_pDlgModuleControl2Parent==NULL) return;
double dValue = m_ctrlJogSpeedLevel.GetPos() / 1000.0;
CString tmp = _T("");
tmp.Format(_T("%.1lf%%"), m_ctrlJogSpeedLevel.GetPos() / 10.0);
SetDlgItemText(IDC_STATIC_JOG_SPEED_LEVEL, tmp);
*pResult = 0;
}
|
be3d99557a069a71a2a57eca255098b628af7573 | ee9bdae0e3d46c795dbb99cdbb90f1254d46a839 | /include/lightsky/utils/NetConnection.hpp | 393b6441dfc3e48353023517ebb19d340d54730f | [
"BSD-2-Clause"
] | permissive | hamsham/LightUtils | ebf2e122eb9162d55c4ebfa18399061a2edcfab3 | ed0b57a02255256b2869342d7af47fce4da50da1 | refs/heads/master | 2023-06-24T09:05:09.739548 | 2023-06-12T04:51:08 | 2023-06-12T04:51:08 | 43,227,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,114 | hpp | NetConnection.hpp |
#ifndef LS_UTILS_NETWORK_CONNECTION_HPP
#define LS_UTILS_NETWORK_CONNECTION_HPP
#include <cstdint>
struct _ENetHost;
struct _ENetPeer;
namespace ls
{
namespace utils
{
/*-----------------------------------------------------------------------------
* Basic UDP Connection
-----------------------------------------------------------------------------*/
class NetConnection
{
public:
enum : uint32_t
{
DEFAULT_CONNECTION_TIMEOUT_MS = 5000, // 5 seconds
CHANNEL_COUNT_LIMITLESS = 0,
CONNECTION_BYTES_PER_SEC_LIMITLESS = 0,
};
private:
struct _ENetPeer* mPeer;
public:
~NetConnection() noexcept = default;
NetConnection() noexcept;
NetConnection(const NetConnection&) = delete;
NetConnection(NetConnection&&) noexcept;
NetConnection& operator=(const NetConnection&) = delete;
NetConnection& operator=(NetConnection&&) noexcept;
bool valid() const noexcept;
int connect(
_ENetHost* pHost,
uint32_t ipAddr,
uint16_t port,
bool clientConnection,
uint8_t maxChannels = (uint32_t)CHANNEL_COUNT_LIMITLESS,
uint32_t timeoutMillis = (uint32_t)DEFAULT_CONNECTION_TIMEOUT_MS
) noexcept;
int connect(_ENetPeer* pHost) noexcept;
void disconnect() noexcept;
int send(const void* pData, size_t numBytes, uint8_t channelId) noexcept;
uint32_t address() const noexcept;
uint16_t port() const noexcept;
const struct _ENetPeer* native_handle() const noexcept;
struct _ENetPeer* native_handle() noexcept;
};
/*-------------------------------------
* Native handle to the underlying ENet data (const)
-------------------------------------*/
inline const struct _ENetPeer* NetConnection::native_handle() const noexcept
{
return mPeer;
}
/*-------------------------------------
* Native handle to the underlying ENet data
-------------------------------------*/
inline struct _ENetPeer* NetConnection::native_handle() noexcept
{
return mPeer;
}
} // end utils namespace
} // end ls namespace
#endif /* LS_UTILS_NETWORK_CONNECTION_HPP */
|
03eae4501a1c95ce032242cd28f6fccb787e834d | c46863e61fbcade0ed9344c69896573461c5b931 | /c++/src/mcmc/options.h | 4d931edfe8cba0ddd27047e11a9c809aaab86c62 | [] | no_license | ielhelw/MCMC_FOR_AMMSB | 54b759060a2097092f57496644c0b908c29a159b | 4526094553d21ab7b1a25d2173e34ef1030578ce | refs/heads/master | 2021-01-19T08:12:19.663018 | 2018-01-08T17:14:40 | 2018-01-08T17:14:40 | 20,097,439 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,747 | h | options.h | #ifndef MCMC_OPTIONS_H__
#define MCMC_OPTIONS_H__
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include "mcmc/config.h"
#include "mcmc/types.h"
#include "mcmc/exception.h"
#include "dkvstore/DKVStore.h"
namespace mcmc {
/**
* For want of a better place...
*/
template <typename T>
std::string to_string(T value) {
std::ostringstream s;
s << value;
return s.str();
}
/**
* utility function to parse a size_t.
* @throw NumberFormatException if arg is malformed or out of range
*/
::size_t parse_size_t(const std::string &argString);
/**
* utility function to parse an integral.
* @throw NumberFormatException if arg is malformed or out of range
*/
template <class T>
inline T parse(const std::string &argString) {
const char *arg = argString.c_str();
if (arg[0] == '-') {
::ssize_t result = -parse_size_t(arg + 1);
if (result < (::ssize_t)std::numeric_limits<T>::min()) {
throw mcmc::NumberFormatException("number too small for type");
}
return (T)result;
} else {
::size_t result = parse_size_t(arg);
if (result > (::size_t)std::numeric_limits<T>::max()) {
throw mcmc::NumberFormatException("number too large for type");
}
return (T)result;
}
}
template <>
inline float parse<float>(const std::string &argString) {
float f;
if (sscanf(argString.c_str(), "%f", &f) != 1) {
throw mcmc::NumberFormatException("string is not a float");
}
return f;
}
template <class T>
class KMG {
public:
KMG() {}
KMG(const std::string &s) { f = mcmc::parse<T>(s); }
T operator()() { return f; }
protected:
T f;
};
template <class T>
inline std::istream &operator>>(std::istream &in, KMG<T> &n) {
std::string line;
std::getline(in, line);
n = KMG<T>(line);
return in;
}
} // namespace mcmc
#include <boost/program_options.hpp>
// Specializations for boost validate (parse) calls for the most common
// integer types, so we can use shorthand like 32m for 32*(2<<20)
//
namespace boost {
namespace program_options {
#define VALIDATE_SPECIALIZE(T) \
template <> \
inline void validate<T, char>( \
boost::any & v, const std::vector<std::basic_string<char> > &xs, T *, \
long) { \
validators::check_first_occurrence(v); \
std::basic_string<char> s(validators::get_single_string(xs)); \
try { \
T x = mcmc::parse<T>(s); \
v = any(x); \
} catch (mcmc::NumberFormatException e) { \
(void) e; \
boost::throw_exception(invalid_option_value(s)); \
} \
}
// VALIDATE_SPECIALIZE(::size_t)
// VALIDATE_SPECIALIZE(::ssize_t)
VALIDATE_SPECIALIZE(int32_t)
VALIDATE_SPECIALIZE(uint32_t)
VALIDATE_SPECIALIZE(int64_t)
VALIDATE_SPECIALIZE(uint64_t)
}
}
namespace mcmc {
namespace po = ::boost::program_options;
class Options {
public:
Options()
: desc_all("Options"),
desc_mcmc("MCMC Options"),
desc_io("MCMC Input Options")
#ifdef MCMC_ENABLE_DISTRIBUTED
, desc_distr("MCMC Distributed Options")
#endif
{
desc_all.add_options()
("config", po::value<std::string>(&config_file), "config file")
;
desc_mcmc.add_options()
// mcmc options
("mcmc.alpha", po::value<Float>(&alpha)->default_value(0.0), "alpha")
("mcmc.eta0", po::value<Float>(&eta0)->default_value(1.0), "eta0")
("mcmc.eta1", po::value<Float>(&eta1)->default_value(1.0), "eta1")
("mcmc.epsilon",
po::value<Float>(&epsilon)->default_value(0.0000001), "epsilon")
("mcmc.a", po::value<Float>(&a)->default_value(0.0), "a")
("mcmc.b", po::value<Float>(&b)->default_value(1024), "b")
("mcmc.c", po::value<Float>(&c)->default_value(0.5), "c")
("mcmc.K,K", po::value< ::size_t>(&K)->default_value(300), "K")
("mcmc.mini-batch-size,m",
po::value< ::size_t>(&mini_batch_size)->default_value(0),
"mini_batch_size")
("mcmc.num-node-sample,n",
po::value< ::size_t>(&num_node_sample)->default_value(0),
"neighbor sample size")
("mcmc.strategy",
po::value<strategy::strategy>(&strategy)->multitoken()->default_value(
strategy::STRATIFIED_RANDOM_NODE),
"sampling strategy")
("mcmc.sampler.max-source",
po::value< ::size_t>(&sampler_max_source_)->default_value(1),
"max #sources in random-node sampling")
("mcmc.max-iteration,x",
po::value< ::size_t>(&max_iteration)->default_value(10000000),
"max_iteration")
("mcmc.interval,i",
po::value< ::size_t>(&interval)->default_value(0),
"perplexity interval")
("mcmc.stats,I",
po::value< ::size_t>(&stats_print_interval)->default_value(0),
"statistics dump interval")
("mcmc.num-updates",
po::value< ::size_t>(&num_updates)->default_value(1000),
"num_updates")
("mcmc.held-out-ratio,h",
po::value<double>(&held_out_ratio)->default_value(0.0),
"held_out_ratio")
("mcmc.seed",
po::value<int>(&random_seed)->default_value(42), "random seed")
("mcmc.convergence",
po::value<double>(&convergence_threshold)->default_value(0.000000000001),
"convergence threshold")
("mcmc.dump-pi",
po::value<std::string>(&dump_pi_file_)->default_value(""),
"file(s) to dump pi to")
("mcmc.dump-nodemap",
po::value<std::string>(&dump_nodemap_file_)->default_value(""),
"file(s) to node map to")
;
desc_all.add(desc_mcmc);
// input options
desc_io.add_options()
("mcmc.input.file,f",
po::value<std::string>(&input_filename_)->default_value(""),
"input file")
("mcmc.input.class,c",
po::value<std::string>(&input_class_)->default_value("relativity"),
"input class")
("mcmc.input.contiguous",
po::bool_switch(&input_contiguous_)->default_value(false),
"contiguous input data")
("mcmc.input.compressed",
po::bool_switch(&input_compressed_)->default_value(false),
"compressed input data")
;
desc_all.add(desc_io);
#ifdef MCMC_ENABLE_DISTRIBUTED
desc_distr.add_options()
("mcmc.dkv-type",
po::value<DKV::TYPE>(&dkv_type)->multitoken()->default_value(
#ifdef MCMC_ENABLE_RDMA
DKV::TYPE::RDMA
#elif defined MCMC_ENABLE_RAMCLOUD
DKV::TYPE::RAMCLOUD
#else
DKV::TYPE::FILE
#endif
),
"D-KV store type (file/ramcloud/rdma)")
("mcmc.max-pi-cache",
po::value< ::size_t>(&max_pi_cache_entries_)->default_value(0),
"minibatch chunk size")
("mcmc.master_is_worker",
po::bool_switch(&forced_master_is_worker)->default_value(false),
"master host also is a worker")
("mcmc.replicated-graph",
po::bool_switch(&REPLICATED_NETWORK)->default_value(false),
"replicate Network graph")
;
desc_all.add(desc_distr);
#endif
}
Options(int argc, char** argv) : Options() {
std::vector<std::string> args;
for (int i = 0; i < argc; ++i) args.push_back(argv[i]);
Parse(args);
}
Options(const std::vector<std::string>& args) : Options() {
Parse(args);
}
void Parse(const std::vector<std::string>& argv) {
po::variables_map vm;
po::parsed_options parsed = po::command_line_parser(argv)
.options(desc_all)
.allow_unregistered()
.run();
po::store(parsed, vm);
po::notify(vm);
if (vm.count("config") > 0) {
std::ifstream file(config_file);
po::store(po::parse_config_file(file, desc_all), vm);
po::notify(vm);
}
remains = po::collect_unrecognized(parsed.options, po::include_positional);
if (a == 0.0) {
a = std::pow(b, -c);
}
if (alpha == 0.0) {
alpha = 1.0 / K;
}
}
const std::vector<std::string> &getRemains() const { return remains; }
public:
std::string config_file;
Float alpha;
Float eta0;
Float eta1;
::size_t K;
::size_t mini_batch_size;
::size_t num_node_sample;
strategy::strategy strategy;
::size_t sampler_max_source_;
Float epsilon;
::size_t max_iteration;
::size_t interval;
::size_t stats_print_interval;
// parameters for step size
Float a;
Float b;
Float c;
::size_t num_updates;
double held_out_ratio;
std::string input_filename_;
std::string input_class_;
bool input_contiguous_;
bool input_compressed_;
int random_seed;
double convergence_threshold;
std::vector<std::string> remains;
#ifdef MCMC_ENABLE_DISTRIBUTED
DKV::TYPE dkv_type;
bool forced_master_is_worker;
mutable ::size_t max_pi_cache_entries_;
bool REPLICATED_NETWORK;
#endif
std::string dump_pi_file_;
std::string dump_nodemap_file_;
po::options_description desc_all;
po::options_description desc_mcmc;
po::options_description desc_io;
#ifdef MCMC_ENABLE_DISTRIBUTED
po::options_description desc_distr;
#endif
friend std::ostream& operator<<(std::ostream& out, const Options& opts);
};
inline std::ostream& operator<<(std::ostream& out, const Options& opts) {
out << opts.desc_all;
return out;
}
}; // namespace mcmc
#endif // ndef MCMC_OPTIONS_H__
|
c2b05aa032556bb06c3c5755154580e266bfbdfa | 054826b3e02d026c77c7d3e8574578fdf7edc897 | /Day67/Chef and closure.cpp | de86b42f948b929b6b13b57a5f4cc8120e943270 | [] | no_license | 123pk/100DaysCoding-Part-3 | 599b1ebcfa15d3013758db28a7ad4b6411fe90be | 0382ce2e3d9b2c77f3bf5cd869ffeccf2ab48f49 | refs/heads/main | 2023-07-18T20:14:33.888371 | 2021-09-26T15:33:42 | 2021-09-26T15:33:42 | 378,564,802 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | cpp | Chef and closure.cpp | /*
Platform :- Codechef
Contest :- Codechef August Cookoff 2021
Approach :- If you will analyse the problem carefully you will find that we have three cases ,
Case 1 :- we have element more than 1 element with abs(x)>1 , as that will lead to infinte array and it cannot be closed
Case 2 :- We have atleast two negative values and one of them is ( less that -1 ) , this will also create infinte array and cannot be closed
Case 3 :- If we have more than two (-1) then we need atleast one (1) positive one else array cannot be closed
Case 4 :- In all othe case we have a closed array
*/
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int A[n];
int c=0,d=0,e=0,f=0;
for(int i=0;i<n;++i){
cin>>A[i];
if(abs(A[i])>1)c++;
//P[A[i]]++;
if(A[i]==-1)f++;
if(A[i]>0)d++;
}
if(c>1 || (c && f))cout<<0<<"\n";
else {
if(f>1 && d==0)cout<<"0\n";
else cout<<"1\n";
}
}
}
|
c2da5f1b8b2d5641e7a3512bc26652271b166734 | e2d034057f9e82114dacbc3cd5108bcc00f61bd6 | /src/ngraph/runtime/interpreter/node_wrapper.cpp | a0a1f7e8f75bf8f251eeac23b9ecbdf14573a4b3 | [
"Apache-2.0"
] | permissive | csullivan/ngraph | 6e73442e78652718ec58c71e9bdf9eab3aa35dc2 | e7e2eabe5fbaa86306268f8f204a0d06b7fdbb81 | refs/heads/master | 2020-03-27T10:08:35.551604 | 2018-09-21T16:13:59 | 2018-09-21T16:13:59 | 146,398,005 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,596 | cpp | node_wrapper.cpp | //*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "ngraph/runtime/interpreter/node_wrapper.hpp"
using namespace ngraph;
using namespace std;
runtime::interpreter::NodeWrapper::NodeWrapper(const shared_ptr<const Node>& node)
: m_node{node}
{
// This expands the op list in op_tbl.hpp into a list of enumerations that look like this:
// {"Abs", runtime::interpreter::OP_TYPEID::Abs},
// {"Acos", runtime::interpreter::OP_TYPEID::Acos},
// ...
#define NGRAPH_OP(a) {#a, runtime::interpreter::OP_TYPEID::a},
static unordered_map<string, runtime::interpreter::OP_TYPEID> typeid_map{
#include "ngraph/op/op_tbl.hpp"
};
#undef NGRAPH_OP
auto it = typeid_map.find(m_node->description());
if (it != typeid_map.end())
{
m_typeid = it->second;
}
else
{
throw unsupported_op("Unsupported op '" + m_node->description() + "'");
}
}
|
5d1603e69a12438c13364aab7a7043b5b7d9bf6e | 601419245db8d94230a439610632014e710f4229 | /LengendOfFightDemons/Classes/LengendOfFightingDemons/scene/LOFDScene.cpp | cbc7695e59a4b1816f7c138a27a8e5a57defc185 | [] | no_license | spzktshow/MasterOfMonster | ba33e6793e64eea7122db0e4ec8d399b490c1b5b | a79cce5f143ff500b3a87f1353cb60f8c5d6f428 | refs/heads/master | 2016-09-06T00:12:39.990811 | 2014-07-16T06:36:55 | 2014-07-16T06:36:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,483 | cpp | LOFDScene.cpp | //
// LOFDScene.cpp
// LengendOfFightDemons
//
// Created by RockLee on 14-4-8.
//
//
#include "LOFDScene.h"
#include <math.h>
#include "LOFDConfigManager.h"
#include "LOFDSkillData.h"
#include "SkillEvent.h"
#include "LOFDActorAi.h"
#include "LOFDActorState.h"
#include "ActorEvent.h"
#include "TypeConver.h"
#include "FileFormat.h"
#include "LOFDActorBehavior.h"
NS_LOFD_BEGIN
int testTagId = -1;
/***************HurtCount****************/
void HurtCount::setCount(int countValue, cocos2d::Point location)
{
this->_count = countValue;
this->_location = location;
std::string countStr = moonsugar::TypeConver::intToString(this->_count);
int n = countStr.size();
for (int i = 0; i < n; i ++) {
char countChar = countStr.at(i);
int count = moonsugar::TypeConver::charToInt(countChar);
std::string hurtName = FILE_HURT_FILE;
hurtName += FILE_NAME_CONNECT;
hurtName += moonsugar::TypeConver::filterStr(count, FILE_NUM_BIT);
hurtName += FILE_PNG;
cocos2d::SpriteFrame * sf = cocos2d::SpriteFrameCache::getInstance()->getSpriteFrameByName(hurtName);
cocos2d::Sprite * sp = cocos2d::Sprite::createWithSpriteFrame(sf);
sp->setPositionX(sf->getRect().size.width * i);
this->addChild(sp);
//sp->setCascadeColorEnabled(true);
}
this->setPosition(this->_location.x, this->_location.y);
this->setScale(0.4);
}
void HurtCount::startAnimation()
{
auto move = cocos2d::MoveBy::create(0.7, cocos2d::Point(0, 100));
auto move_ease_inout = cocos2d::EaseInOut::create(move->clone(), 0.65f);
auto scale = cocos2d::ScaleTo::create(.3, 1);
cocos2d::FiniteTimeAction * moveDone = cocos2d::CallFunc::create(CC_CALLBACK_0(HurtCount::endAnimation, this));
auto delay = cocos2d::DelayTime::create(0.25f);
auto seq = cocos2d::Sequence::create(scale, move_ease_inout, delay, moveDone, NULL);
auto alphaTrans = cocos2d::FadeOut::create(1);
cocos2d::Vector<cocos2d::Node *> children = this->getChildren();
int n = children.size();
for (int i = 0; i < n; i ++) {
cocos2d::Node * node = children.at(i);
node->runAction(alphaTrans->clone());
}
this->runAction(seq);
}
void HurtCount::endAnimation()
{
this->stopAllActions();
if (this->getParent())
{
this->getParent()->removeChild(this);
}
}
/****************SkillButton*****************/
void SkillButton::startCoolDown()
{
if (!this->skillDef) return;
cocos2d::ProgressTo * processTo = cocos2d::ProgressTo::create(this->skillDef->coolDown, 100);
cocos2d::FiniteTimeAction * actionDone = cocos2d::CallFunc::create(CC_CALLBACK_0(SkillButton::coolDownComplete, this));
cocos2d::Sequence * sq = cocos2d::Sequence::create(processTo, actionDone, NULL);
progressTimer->runAction(sq);
this->skillFrame->setOpacity(SKILL_BUTTON_ALPHA_HALF);
this->skillLightFrame->setOpacity(SKILL_BUTTON_ALPHA_HALF);
this->skillDarkFrame->setOpacity(SKILL_BUTTON_ALPHA_HALF);
this->isCoolDown = true;
}
void SkillButton::coolDownComplete()
{
this->isCoolDown = false;
this->skillFrame->setOpacity(SKILL_BUTTON_ALPHA_MAX);
this->skillLightFrame->setOpacity(SKILL_BUTTON_ALPHA_MAX);
this->skillDarkFrame->setOpacity(SKILL_BUTTON_ALPHA_MAX);
progressTimer->stopAllActions();
progressTimer->setPercentage(100);
}
void SkillButton::createButton()
{
skillFrame = cocos2d::Sprite::create("battleui_skillframe.png");
skillLightFrame = cocos2d::Sprite::create("battleui_skillframe_dark.png");
skillDarkFrame = cocos2d::Sprite::create("battleui_skillframe_light.png");
this->addChild(skillLightFrame);
progressTimer = cocos2d::ProgressTimer::create(skillDarkFrame);
progressTimer->setType(cocos2d::ProgressTimer::Type::RADIAL);
progressTimer->setPercentage(100);
this->addChild(progressTimer);
this->addChild(skillFrame);
this->addListeners();
}
void SkillButton::destoryButton()
{
this->removeListeners();
touchListener->release();
progressTimer->stopAllActions();
}
void SkillButton::addListeners()
{
touchListener= cocos2d::EventListenerTouchOneByOne::create();
touchListener->onTouchBegan = CC_CALLBACK_2(SkillButton::onTouchBegan, this);
touchListener->onTouchEnded = CC_CALLBACK_2(SkillButton::onTouchEnded, this);
touchListener->retain();
auto eventDispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, skillFrame);
}
void SkillButton::removeListeners()
{
auto eventDispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
eventDispatcher->removeEventListener(touchListener);
}
bool SkillButton::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
cocos2d::log("skill button touch");
cocos2d::Sprite * target = dynamic_cast<cocos2d::Sprite *>(event->getCurrentTarget());
if (target != nullptr)
{
cocos2d::Point locationPoint = target->convertToNodeSpace(touch->getLocation());
cocos2d::Size s = target->getContentSize();
cocos2d::Rect rect(0, 0, s.width, s.height);
if (rect.containsPoint(locationPoint))
{
this->isBeganInSkillButton = true;
}
}
return true;
}
void SkillButton::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event)
{
cocos2d::log("skill button touch ended");
cocos2d::Sprite * target = dynamic_cast<cocos2d::Sprite *>(event->getCurrentTarget());
if (target != nullptr)
{
cocos2d::Point locationPoint = target->convertToNodeSpace(touch->getLocation());
cocos2d::Size s = target->getContentSize();
cocos2d::Rect rect(0, 0, s.width, s.height);
if (rect.containsPoint(locationPoint))
{
if (this->isBeganInSkillButton)
{
this->isTouched = true;
if (this->isCoolDown) return;
//this->startCoolDown();
this->isBeganInSkillButton = false;
if (this->skillDef == nullptr)
{
cocos2d::log("skillDef == nullptr");
}
else
{
cocos2d::EventDispatcher * eventDispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
cocos2d::EventCustom event(SKILL_BUTTON_TOUCHED);
event.setUserData(this->skillDef);
eventDispatcher->dispatchEvent(&event);
}
//
}
}
}
}
/********************************************/
lofd::MapScene * MapScene::create(moonsugar::MapSceneData * mapSceneDataValue)
{
lofd::MapScene * mapScene = new lofd::MapScene(mapSceneDataValue);
if (mapScene && mapScene->init())
{
mapScene->autorelease();
return mapScene;
}
else
{
delete mapScene;
mapScene = nullptr;
return nullptr;
}
}
bool MapScene::init()
{
if (!moonsugar::MapScene::init()) return false;
this->addContextListeners();
return true;
}
void MapScene::addContextListeners()
{
this->skillListener = cocos2d::EventListenerCustom::create(SKILL_BUTTON_TOUCHED, CC_CALLBACK_1(MapScene::onSkillHandler, this));
cocos2d::EventDispatcher * eventDispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
eventDispatcher->addEventListenerWithFixedPriority(this->skillListener, 1);
this->skillCoolDownListener = cocos2d::EventListenerCustom::create(SKILL_COOLDOWN_START, CC_CALLBACK_1(MapScene::onSkillCoolDownStartHandler, this));
eventDispatcher->addEventListenerWithFixedPriority(this->skillCoolDownListener, 1);
this->skillCoolDownEndListener = cocos2d::EventListenerCustom::create(SKILL_COOLDOWN_END, CC_CALLBACK_1(MapScene::onSkillCoolDownEndHandler, this));
eventDispatcher->addEventListenerWithFixedPriority(this->skillCoolDownEndListener, 1);
this->actorDeadEventListener = cocos2d::EventListenerCustom::create(ACTOR_EVENT_DEAD, CC_CALLBACK_1(MapScene::onActorDeadHandler, this));
eventDispatcher->addEventListenerWithFixedPriority(this->actorDeadEventListener, 1);
this->actorDeadCompleteEventListener = cocos2d::EventListenerCustom::create(ACTOR_EVENT_DEAD_COMPLETE, CC_CALLBACK_1(MapScene::onActorDeadCompleteHandler, this));
eventDispatcher->addEventListenerWithFixedPriority(this->actorDeadCompleteEventListener, 1);
}
void MapScene::removeContextListeners()
{
cocos2d::EventDispatcher * eventDispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
eventDispatcher->removeEventListener(this->skillListener);
eventDispatcher->removeEventListener(this->skillCoolDownListener);
eventDispatcher->removeEventListener(this->skillCoolDownEndListener);
eventDispatcher->removeEventListener(this->actorDeadEventListener);
eventDispatcher->removeEventListener(this->actorDeadCompleteEventListener);
}
void MapScene::onActorDeadHandler(cocos2d::EventCustom *event)
{
cocos2d::log("onActorDeadhandler");
lofd::ActorData * actorData = static_cast<lofd::ActorData *>(event->getUserData());
constellation::BehaviorEvent * behaviorEvent = new constellation::BehaviorEvent(LOFD_BEHAVIOR_EVENT_ACTOR_DEAD);
lofd::AIBehaviorDynamicData * data = new lofd::AIBehaviorDynamicData;
data->currentOperationActorData = actorData;
data->operationType = LOFD_ACTOR_STATE_OPERATION_TYPE_SYSTEM;
behaviorEvent->behaviorData = data;
lofd::MapActorsLayer * mapActorsLayer = dynamic_cast<lofd::MapActorsLayer *>(this->getMapActorsLayer());
long n = mapActorsLayer->actorLayerData->mapActorDatas.size();
for (int i = 0; i < n; i ++) {
lofd::ActorData * checkActorData = dynamic_cast<lofd::ActorData *>(mapActorsLayer->actorLayerData->mapActorDatas.at(i));
if (checkActorData->tagId == actorData->tagId) continue;
checkActorData->deleteCurrentRangeActors(actorData);
data->actorData = checkActorData;
data->mapScene = this;
data->mapSceneData = this->mapSceneData;
checkActorData->aiBehavior->root->execute(behaviorEvent);
}
delete behaviorEvent;
delete data;
//this->removeActor(actorData);
}
void MapScene::onActorDeadCompleteHandler(cocos2d::EventCustom *event)
{
lofd::ActorData * actorData = static_cast<lofd::ActorData *>(event->getUserData());
this->removeActor(actorData);
}
void MapScene::onSkillHandler(cocos2d::EventCustom * event)
{
lofd::SkillDef * skillDef = static_cast<lofd::SkillDef *>(event->getUserData());
if (skillDef->operationContextDef->operationType == SKILL_OPERATION_TYPE_ACTOR)
{
this->currentFocus->changeSkillFocus(skillDef->skillId);
if (this->currentFocus->currentFocus != nullptr)
{
constellation::BehaviorEvent * event = new constellation::BehaviorEvent(LOFD_BEHAVIOR_EVENT_AI_TRACK);
lofd::AIBehaviorDynamicData * aiBehaviorData = new lofd::AIBehaviorDynamicData;
aiBehaviorData->actorData = this->currentFocus;
aiBehaviorData->mapScene = this;
aiBehaviorData->operationType = LOFD_ACTOR_STATE_OPERATION_TYPE_CUSOTM;
event->behaviorData = aiBehaviorData;
this->currentFocus->aiBehavior->root->execute(event);
delete event;
delete aiBehaviorData;
}
}
else
{
this->currentFocus->currentWaitSkill = skillDef->skillId;
}
}
void MapScene::onSkillCoolDownStartHandler(cocos2d::EventCustom *event)
{
lofd::SkillEventParam * skillEventParam = static_cast<lofd::SkillEventParam *>(event->getUserData());
if (!this->currentFocus) return;
if (skillEventParam->actorTag == this->currentFocus->tagId)
{
lofd::MapUILayer * mapUILayer = dynamic_cast<lofd::MapUILayer *>(this->getMapUILayer());
mapUILayer->startCD(skillEventParam->skillDef->skillId);
}
skillEventParam->release();
}
void MapScene::onSkillCoolDownEndHandler(cocos2d::EventCustom * event)
{
lofd::SkillEventParam * skillEventParam = static_cast<lofd::SkillEventParam *>(event->getUserData());
if (!this->currentFocus) return;
if (skillEventParam->actorTag == this->currentFocus->tagId)
{
cocos2d::log("my skill %d has cool down end", skillEventParam->skillDef->skillId);
}
skillEventParam->release();
}
bool MapScene::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
if (!this->currentFocus) return moonsugar::MapScene::onTouchBegan(touch, unused_event);
startPoint.setPoint(touch->getLocation().x, touch->getLocation().y);
moonsugar::MapActorsLayer * mapActorsLayer = this->getMapActorsLayer();
cocos2d::Point touchLocalPoint = mapActorsLayer->convertTouchToNodeSpace(touch);
cocos2d::log("localPoint x=%f, y=%f", touchLocalPoint.x, touchLocalPoint.y);
moonsugar::VectorPoint * startVPoint = new moonsugar::VectorPoint(new cocos2d::Point(currentFocus->actorEntry->getPosition()));
moonsugar::VectorPoint * endVPoint = new moonsugar::VectorPoint(new cocos2d::Point(touchLocalPoint));
cocos2d::Vector<moonsugar::VectorPoint *> paths = moonsugar::VectorUtils::findPath(startVPoint, endVPoint, this->mapSceneData);
long length = paths.size();
cocos2d::log("路径长度%d", (int)length);
if (length > 0)
{
this->isDrawPath = true;
tempPath = paths;
tempStartPoint = startVPoint;
tempEndPoint = endVPoint;
}
return moonsugar::MapScene::onTouchBegan(touch, unused_event);
}
void MapScene::onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
this->isDrawPath = false;
moonsugar::MapScene::onTouchMoved(touch, unused_event);
}
void MapScene::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
this->isDrawPath = false;
if (!this->currentFocus) return;
float dx = abs(touch->getLocation().x - startPoint.x);
float dy = abs(touch->getLocation().y - startPoint.y);
bool isHit = false;
lofd::ActorData * actorData = nullptr;
moonsugar::MapActorsLayer * mapActorsLayer = this->getMapActorsLayer();
cocos2d::Point touchLocalPoint = mapActorsLayer->convertTouchToNodeSpace(touch);
moonsugar::ActorLayerData * mapLayerData = static_cast<moonsugar::ActorLayerData *>(mapActorsLayer->mapLayerData);
//这部分需要重构,现在需要根据当前焦点的技能操作类型来判断操作什么类型
lofd::MapUILayer * mapUILayer = dynamic_cast<lofd::MapUILayer *>(this->getMapUILayer());
if (mapUILayer->hasButtonTouched())
{
//hasButtonTouched
}
else
{
lofd::SkillConfig * skillConfig = lofd::ConfigManager::getInstance()->skillConfig;
lofd::SkillDef * skillDef;
if (this->currentFocus->currentWaitSkill != -1)
{
skillDef = skillConfig->getSkillDefById(this->currentFocus->currentWaitSkill);
}
else
{
skillDef = skillConfig->getSkillDefById(this->currentFocus->currentFocusSkill);
}
lofd::SkillCoolDownData * skillCoolDownData = this->currentFocus->getSkillCoolDownData(skillDef->skillId);
if (skillDef->operationContextDef->operationType == SKILL_OPERATION_TYPE_TARGET)
{
if (skillCoolDownData->isCoolDown) return;
this->currentFocus->changeSkillFocus(this->currentFocus->currentWaitSkill);
this->currentFocus->currentWaitSkill = -1;
this->currentFocus->targetPoint.x = touchLocalPoint.x;
this->currentFocus->targetPoint.y = touchLocalPoint.y;
constellation::BehaviorEvent * event = new constellation::BehaviorEvent(LOFD_BEHAVIOR_EVENT_AI_TARGET);
lofd::AIBehaviorDynamicData * aiBehaviorData = new lofd::AIBehaviorDynamicData;
aiBehaviorData->actorData = this->currentFocus;
aiBehaviorData->mapScene = this;
aiBehaviorData->mapSceneData = this->mapSceneData;
aiBehaviorData->targetPoint = this->currentFocus->targetPoint;
aiBehaviorData->operationType = LOFD_ACTOR_STATE_OPERATION_TYPE_CUSOTM;
event->behaviorData = aiBehaviorData;
this->currentFocus->aiBehavior->root->execute(event);
delete event;
delete aiBehaviorData;
}
else if (skillDef->operationContextDef->operationType == SKILL_OPERATION_TYPE_ACTOR)
{
for (int i = 0; i < mapLayerData->mapActorDatas.size(); i++)
{
moonsugar::MapActorData * mapActorData = mapLayerData->mapActorDatas.at(i);
actorData = static_cast<lofd::ActorData *>(mapActorData);
if (actorData->tagId == this->currentFocus->tagId || actorData->isDead) continue;
cocos2d::Rect * rect = actorData->getBound();
if (moonsugar::VectorUtils::calculateIsHitRect(touchLocalPoint, rect)) {
isHit = true;
break;
}
}
if (isHit)
{
if (skillCoolDownData->isCoolDown) return;
cocos2d::log("touch actor %d", actorData->actorId);
lofd::CampRelationShipDef * def = this->currentFocus->campContext->getDefByCampId(actorData->campContext->campId);
if (def->relationShip < 0)
{
this->currentFocus->currentFocus = actorData;
cocos2d::log("change the focus");
constellation::BehaviorEvent * event = new constellation::BehaviorEvent(LOFD_BEHAVIOR_EVENT_AI_TRACK);
lofd::AIBehaviorDynamicData * aiBehaviorData = new lofd::AIBehaviorDynamicData;
aiBehaviorData->actorData = this->currentFocus;
aiBehaviorData->mapScene = this;
aiBehaviorData->operationType = LOFD_ACTOR_STATE_OPERATION_TYPE_CUSOTM;
event->behaviorData = aiBehaviorData;
this->currentFocus->aiBehavior->root->execute(event);
delete event;
delete aiBehaviorData;
}
else if (def->relationShip > 0)
{
}
}
else
{
int gap = 150;
if (dx <= gap && dy <= gap)
{
cocos2d::log("localPoint x=%f, y=%f", touchLocalPoint.x, touchLocalPoint.y);
bool isAllow = moonsugar::VectorUtils::calculateIsAllow(touchLocalPoint, this->mapSceneData);
bool isHitMapItem = moonsugar::VectorUtils::calculateIsHitMapItem(touchLocalPoint, this->mapSceneData);
if (isAllow && !isHitMapItem)
{
constellation::BehaviorEvent * actionBehaviorEvent = new constellation::BehaviorEvent(LOFD_BEHAVIOR_EVENT_AI_MOVE);
lofd::AIBehaviorDynamicData * data = new lofd::AIBehaviorDynamicData();
data->point = &touchLocalPoint;
data->actorData = this->currentFocus;
data->mapSceneData = mapSceneData;
actionBehaviorEvent->behaviorData = data;
this->currentFocus->aiBehavior->root->execute(actionBehaviorEvent);
delete actionBehaviorEvent;
delete data;
}
}
}
}
else
{
}
}
cocos2d::log("point gap x=%f y=%f", dx, dy);
startPoint.x = touch->getLocation().x;
startPoint.y = touch->getLocation().y;
moonsugar::MapScene::onTouchEnded(touch, unused_event);
}
void MapScene::onTouchCancelled(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
moonsugar::MapScene::onTouchCancelled(touch, unused_event);
}
void MapScene::onTouchEndedOrCancelledExecute(cocos2d::Touch * touch, cocos2d::Event *unused_event)
{
moonsugar::MapScene::onTouchEndedOrCancelledExecute(touch, unused_event);
}
void MapScene::addActor(lofd::ActorData *actorValue)
{
moonsugar::MapActorsLayer * mapActorsLayer = this->getMapActorsLayer();
if (mapActorsLayer)
{
mapActorsLayer->actorLayerData->mapActorDatas.pushBack(actorValue);
actorValue->mapScene = this;
mapActorsLayer->addChild(actorValue->actorContainer);
}
}
void MapScene::removeActor(lofd::ActorData * actorValue)
{
moonsugar::MapActorsLayer * mapActorsLayer = this->getMapActorsLayer();
if (mapActorsLayer)
{
long n = mapActorsLayer->actorLayerData->mapActorDatas.size();
for (int i = 0; i < n; i++) {
lofd::ActorData * checkActorData = static_cast<lofd::ActorData *>(mapActorsLayer->actorLayerData->mapActorDatas.at(i));
if (checkActorData->tagId == actorValue->tagId)
{
mapActorsLayer->actorLayerData->mapActorDatas.erase(i);
break;
}
}
mapActorsLayer->removeChild(actorValue->actorContainer);
}
}
void MapScene::addOperationActor(lofd::ActorData *actorValue)
{
this->addActor(actorValue);
this->operationActors.pushBack(actorValue);
}
void MapScene::removeOperationActor(lofd::ActorData * actorValue)
{
long n = this->operationActors.size();
for (int i = 0; i < n; i ++) {
lofd::ActorData * checkActorData = static_cast<lofd::ActorData *>(this->operationActors.at(i));
if (checkActorData->tagId == actorValue->tagId)
{
this->operationActors.erase(i);
}
}
this->removeActor(actorValue);
}
void MapScene::draw(cocos2d::Renderer *renderer, const kmMat4 &transform, bool transformUpdated)
{
moonsugar::MapScene::draw(renderer, transform, transformUpdated);
}
void MapScene::onDraw(const kmMat4 &transform, bool transformUpdated)
{
moonsugar::MapScene::onDraw(transform, transformUpdated);
if (!this->isDrawPath) return;
}
moonsugar::MapUILayer * lofd::MapScene::createMapUILayer(moonsugar::UILayerData *uiLayerDataValue)
{
lofd::MapUILayer * mapUILayer = lofd::MapUILayer::create(uiLayerDataValue);
mapUILayer->mapScene = this;
return mapUILayer;
}
moonsugar::MapActorsLayer * lofd::MapScene::createMapActorsLayer(moonsugar::ActorLayerData *actorLayerDataValue)
{
lofd::MapActorsLayer * mapActorsLayer = lofd::MapActorsLayer::create(actorLayerDataValue);
mapActorsLayer->mapScene = this;
return mapActorsLayer;
}
moonsugar::MapEffectLayer * lofd::MapScene::createMapEffectLayer(moonsugar::EffectLayerData *effectLayerDataValue)
{
lofd::MapEffectLayer * mapEffectLayer = lofd::MapEffectLayer::create(effectLayerDataValue);
return mapEffectLayer;
}
void lofd::MapScene::changeFocus(lofd::ActorData * actorDataValue)
{
if (this->currentFocus != nullptr)
{
this->currentFocus->isCurrentFocus = false;
// constellation::BehaviorEvent * behaviorEvent = new constellation::BehaviorEvent(LOFD_BEHAVIOR_EVENT_AI_PATROL);
// lofd::AIBehaviorDynamicData * behaviorDynamicData = new lofd::AIBehaviorDynamicData();
// behaviorDynamicData->actorData = this->currentFocus;
// behaviorDynamicData->mapSceneData = this->mapSceneData;
// behaviorDynamicData->operationType = LOFD_ACTOR_STATE_OPERATION_TYPE_AI;
// behaviorEvent->behaviorData = behaviorDynamicData;
// this->currentFocus->aiBehavior->root->execute(behaviorEvent);
// delete behaviorEvent;
// delete behaviorDynamicData;
}
this->currentFocus = actorDataValue;
this->currentFocus->isCurrentFocus = true;
// constellation::BehaviorEvent * behaviorEvent = new constellation::BehaviorEvent(LOFD_BEHAVIOR_EVENT_AI_CANCEL_PATROL);
// lofd::AIBehaviorDynamicData * behaviorDynamicData = new lofd::AIBehaviorDynamicData();
// behaviorDynamicData->actorData = this->currentFocus;
// behaviorDynamicData->mapSceneData = this->mapSceneData;
// behaviorDynamicData->operationType = LOFD_ACTOR_STATE_OPERATION_TYPE_AI;
// behaviorEvent->behaviorData = behaviorDynamicData;
// this->currentFocus->aiBehavior->root->execute(behaviorEvent);
// delete behaviorEvent;
// delete behaviorDynamicData;
lofd::MapUILayer * mapUILayer = dynamic_cast<lofd::MapUILayer *>(this->getMapUILayer());
mapUILayer->changeFocus(this->currentFocus);
}
/****************MapUILayer*********************/
MapUILayer * MapUILayer::create(moonsugar::UILayerData *uiLayerData)
{
MapUILayer * uiLayer = new lofd::MapUILayer(uiLayerData);
if (uiLayer && uiLayer->init())
{
uiLayer->autorelease();
return uiLayer;
}
else
{
delete uiLayer;
uiLayer = nullptr;
return nullptr;
}
}
void MapUILayer::atk1CallBack(cocos2d::Ref *pSender)
{
cocos2d::log("atk1 click");
// if (this->currentFocus == nullptr)
// {
// lofd::ActorData * actorData = lofd::ActorControllerUtils::createActorDataById(710040);
// actorData->isAI = true;
// actorData->isRange = false;
// lofd::ActorStateData * actorStateData = new lofd::ActorStateData(LOFD_ACTOR_STATE_IDLE, LOFD_ACTOR_STATE_OPERATION_TYPE_AI);
// actorData->stateContext->insertStateData(actorStateData);
// actorData->runAction(LOFD_ACTOR_STATE_IDLE);
// actorData->actorContainer->setPosition(cocos2d::Point(280, 100));
// actorData->actorPropertyData->hp = 10000;
// mapScene->addOperationActor(actorData);
// mapScene->changeFocus(actorData);
// }
//debugTextField->textFieldTTF->get
std::string str = debugTextField->textFieldTTF->getString();
int tagId = moonsugar::TypeConver::CharToInt(str.c_str());
testTagId = tagId;
cocos2d::log("change tagId %d", testTagId);
}
void MapUILayer::skillCallBack(cocos2d::Ref *pSender)
{
cocos2d::log("skill click");
// constellation::BehaviorEvent * event = new constellation::BehaviorEvent(LOFD_ACTOR_BEHAVIOR_EVENT_SKILL1);
// lofd::ActorBehaviorData * bData = new lofd::ActorBehaviorData();
// bData->actorData = this->currentFocus;
// event->behaviorData = bData;
// this->currentFocus->actorBehavior->root->execute(event);
// delete bData;
// delete event;
// lofd::SkillConfig * skillConfig = lofd::ConfigManager::getInstance()->skillConfig;
// lofd::SkillParamContext * skillParamContext = new lofd::SkillParamContext();
// skillParamContext->mapScene = this->mapScene;
// skillParamContext->actorData = this->mapScene->currentFocus;
// lofd::SkillDef * skillDef = skillConfig->skillDefs.at(0);
// lofd::SkillData * skillData = lofd::SkillDataUtils::createSkillData(skillDef, skillParamContext);
// skillData->skillDef = skillDef;
// currentFocus->skill(skillData);
//this->currentFocus->currentFocusSkill = 2;
}
bool MapUILayer::hasButtonTouched()
{
bool hasTouched = false;
if (this->skillButton1->isTouched)
{
hasTouched = true;
}
else if (this->skillButton2->isTouched)
{
hasTouched = true;
}
else if (this->skillButton3->isTouched)
{
hasTouched = true;
}
else if (this->skillButton4->isTouched)
{
hasTouched = true;
}
this->skillButton1->isTouched = false;
this->skillButton2->isTouched = false;
this->skillButton3->isTouched = false;
this->skillButton4->isTouched = false;
return hasTouched;
}
void MapUILayer::addActorCallBack(cocos2d::Ref *pSender)
{
cocos2d::log("add actor click");
std::vector<int> ids;
ids.push_back(710010);
ids.push_back(710020);
ids.push_back(710040);
//ids.push_back(710030);
ids.push_back(710050);
ids.push_back(710060);
int i = rand() % ids.size();
lofd::ActorData * actorData = lofd::ActorControllerUtils::createActorDataById(ids.at(i), this->mapScene->dungeonDef);
actorData->isAI = true;
//cocos2d::Point * local = new cocos2d::Point(rand() % (int)this->mapLayerData->allowRect->size.width, rand() % (int)this->mapLayerData->allowRect->size.height);
cocos2d::Point * local = new cocos2d::Point(rand() % 1280, rand() % (int)this->mapLayerData->allowRect->size.height);
actorData->point = local;
// lofd::ActorStateData * actorStateData = new lofd::ActorStateData(LOFD_ACTOR_STATE_IDLE, LOFD_ACTOR_STATE_OPERATION_TYPE_AI);
lofd::ActorStateData * actorStateData = lofd::ActorStateData::create(LOFD_ACTOR_STATE_IDLE, LOFD_ACTOR_STATE_OPERATION_TYPE_AI);
actorData->stateContext->insertStateData(actorStateData);
actorData->runAction(LOFD_ACTOR_STATE_IDLE);
actorData->actorContainer->setPosition(local->x, local->y);
this->mapScene->addActor(actorData);
constellation::BehaviorEvent * behaviorEvent = new constellation::BehaviorEvent(LOFD_BEHAVIOR_EVENT_AI_PATROL);
lofd::AIBehaviorDynamicData * behaviorDynamicData = new lofd::AIBehaviorDynamicData();
behaviorDynamicData->actorData = actorData;
behaviorDynamicData->mapSceneData = this->mapScene->mapSceneData;
behaviorDynamicData->operationType = LOFD_ACTOR_STATE_OPERATION_TYPE_AI;
behaviorEvent->behaviorData = behaviorDynamicData;
actorData->aiBehavior->root->execute(behaviorEvent);
delete behaviorEvent;
delete behaviorDynamicData;
}
void lofd::MapUILayer::changeFocus(lofd::ActorData *actorDataValue)
{
this->currentFocus = actorDataValue;
lofd::SkillCoolDownData * skillCoolDownData;
if (this->currentFocus->skillCoolDownDatas.size() > 0)
{
skillCoolDownData = dynamic_cast<lofd::SkillCoolDownData *>(this->currentFocus->skillCoolDownDatas.at(0));
skillButton1->skillDef = skillCoolDownData->skillDef;
}
if (this->currentFocus->skillCoolDownDatas.size() > 1)
{
skillCoolDownData = dynamic_cast<lofd::SkillCoolDownData *>(this->currentFocus->skillCoolDownDatas.at(1));
skillButton2->skillDef = skillCoolDownData->skillDef;
}
if (this->currentFocus->skillCoolDownDatas.size() > 2)
{
skillCoolDownData = dynamic_cast<lofd::SkillCoolDownData *>(this->currentFocus->skillCoolDownDatas.at(2));
skillButton3->skillDef = skillCoolDownData->skillDef;
}
if (this->currentFocus->skillCoolDownDatas.size() > 3)
{
skillCoolDownData = dynamic_cast<lofd::SkillCoolDownData *>(this->currentFocus->skillCoolDownDatas.at(3));
skillButton4->skillDef = skillCoolDownData->skillDef;
}
}
bool lofd::MapUILayer::init()
{
if (!moonsugar::MapUILayer::init()) return false;
auto atk1Item = cocos2d::MenuItemImage::create("up.png", "up.png", CC_CALLBACK_1(MapUILayer::atk1CallBack, this));
auto skillItem = cocos2d::MenuItemImage::create("down.png", "down.png", CC_CALLBACK_1(MapUILayer::skillCallBack, this));
auto addActorItem = cocos2d::MenuItemImage::create("continue.png", "continue.png", CC_CALLBACK_1(MapUILayer::addActorCallBack, this));
atk1Item->setPosition(100, 0);
skillItem->setPosition(0, 0);
addActorItem->setPosition(200, 0);
auto menu = cocos2d::Menu::create(addActorItem, NULL);
menu->setPosition(cocos2d::Point(200, 50));
this->addChild(menu);
cocos2d::Point point1(1200, 80);
this->skillButton1 = lofd::SkillButton::create();
skillButton1->createButton();
this->addChild(skillButton1);
skillButton1->setPosition(point1);
cocos2d::Point point2(1200, 200);
this->skillButton2 = lofd::SkillButton::create();
skillButton2->createButton();
this->addChild(skillButton2);
skillButton2->setPosition(point2);
skillButton2->setScale(.7, .7);
cocos2d::Point point3(1100, 160);
this->skillButton3 = lofd::SkillButton::create();
this->skillButton3->createButton();
this->addChild(skillButton3);
skillButton3->setPosition(point3);
skillButton3->setScale(.7, .7);
cocos2d::Point point4(1000, 70);
this->skillButton4 = lofd::SkillButton::create();
this->skillButton4->createButton();
this->addChild(skillButton4);
skillButton4->setPosition(point4);
skillButton4->setScale(.7, .7);
debugTextField = lofd::DebugTextField::create();
this->addChild(debugTextField);
debugTextField->setPosition(cocos2d::Point(1000, 600));
this->addListeners();
return true;
}
bool lofd::MapUILayer::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
touchPoint = touch->getLocation();
return true;
}
void lofd::MapUILayer::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event)
{
// cocos2d::Point endPos = touch->getLocation();
// const float gap = 20.0f;
// if (abs(endPos.x - touchPoint.x) > gap || abs(endPos.y - touchPoint.y) > gap)
// {
// return;
// }
// auto point = convertTouchToNodeSpace(touch);
// cocos2d::Rect rect;
// rect.size = textFiledTTF->getContentSize();
// rect.origin.x = textFiledTTF->getPosition().x - textFiledTTF->getContentSize().width * .5;
// rect.origin.y = textFiledTTF->getPosition().y - textFiledTTF->getContentSize().height * .5;
//
// if (rect.containsPoint(point))
// {
// //
// textFiledTTF->attachWithIME();
// }
}
void lofd::MapUILayer::addListeners()
{
// this->touchListener = cocos2d::EventListenerTouchOneByOne::create();
// this->touchListener->onTouchBegan = CC_CALLBACK_2(lofd::MapUILayer::onTouchBegan, this);
// this->touchListener->onTouchEnded = CC_CALLBACK_2(lofd::MapUILayer::onTouchEnded, this);
// cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(this->touchListener, this);
}
void lofd::MapUILayer::removeListeners()
{
//cocos2d::Director::getInstance()->getEventDispatcher()->removeEventListener(this->touchListener);
}
void lofd::MapUILayer::startCD(int skillId)
{
if (this->skillButton1->skillDef->skillId == skillId)
{
this->skillButton1->startCoolDown();
}
else if (this->skillButton2->skillDef->skillId == skillId)
{
this->skillButton2->startCoolDown();
}
else if (this->skillButton3->skillDef->skillId == skillId)
{
this->skillButton3->startCoolDown();
}
else if (this->skillButton4->skillDef->skillId == skillId)
{
this->skillButton4->startCoolDown();
}
}
/************MapActorsLayer************/
void lofd::MapActorsLayer::draw(cocos2d::Renderer *renderer, const kmMat4 &transform, bool transformUpdated)
{
cocos2d::Layer::draw(renderer, transform, transformUpdated);
this->_customCommand.init(_globalZOrder);
this->_customCommand.func = CC_CALLBACK_0(MapActorsLayer::onDraw, this, transform, transformUpdated);
renderer->addCommand(&_customCommand);
}
void lofd::MapActorsLayer::onDraw(const kmMat4 &transform, bool transformUpdated)
{
/*******排序********/
long n = this->getChildrenCount();
for (int i = 0; i < n; i ++) {
cocos2d::Node * node = this->getChildren().at(i);
this->reorderChild(node, 0 - node->getPositionY());
}
if (countCheckRange >= 5)
{
countCheckRange = 0;
/*******查找range*******/
for (int j = 0; j < this->actorLayerData->mapActorDatas.size(); j ++)
{
lofd::ActorData * checkActorData = (lofd::ActorData *)this->actorLayerData->mapActorDatas.at(j);
if (!checkActorData->isRange) continue;
cocos2d::Vector<lofd::ActorData *> newIntoRange;
cocos2d::Vector<lofd::ActorData *> newOutRange;
for (int t = 0; t < this->actorLayerData->mapActorDatas.size(); t++) {
lofd::ActorData * beCheckActorData = (lofd::ActorData *)this->actorLayerData->mapActorDatas.at(t);
if (beCheckActorData->isDead) continue;
if (checkActorData->tagId != beCheckActorData->tagId && !checkActorData->isDead)
{
//checkActorData->actorEntry
cocos2d::Point * start = new cocos2d::Point(checkActorData->actorContainer->getPositionX(), checkActorData->actorContainer->getPositionY());
cocos2d::Point * end = new cocos2d::Point(beCheckActorData->actorContainer->getPositionX(), beCheckActorData->actorContainer->getPositionY());
float distance = moonsugar::VectorUtils::calculateDistance(start, end);
delete start;
delete end;
int getActorIndex = -1;
getActorIndex = checkActorData->getActorFromCurrentRangeActors(beCheckActorData->tagId);
if (distance <= checkActorData->actorDef->warnRound)
{
if (getActorIndex == -1) {
//cocos2d::log("new actor into range");
checkActorData->currentRangeActors.pushBack(beCheckActorData);
newIntoRange.pushBack(beCheckActorData);
//cocos2d::log("actor reference count %d", beCheckActorData->getReferenceCount());
}
}
else
{
if (getActorIndex != -1) {
//cocos2d::log("new actor out range");
checkActorData->currentRangeActors.erase(getActorIndex);
newOutRange.pushBack(beCheckActorData);
//cocos2d::log("actor reference count %d", beCheckActorData->getReferenceCount());
}
}
}
}
if (newIntoRange.size() > 0)
{
constellation::BehaviorEvent * event = new constellation::BehaviorEvent(LOFD_BEHAVIOR_EVENT_NEW_ACTOR_INTO_RANGE);
lofd::AIBehaviorDynamicData * data = new lofd::AIBehaviorDynamicData();
data->actorData = checkActorData;
//data->rangeChangeActors = newIntoRange;
data->mapScene = this->mapScene;
data->operationType = LOFD_ACTOR_STATE_OPERATION_TYPE_AI;
event->behaviorData = data;
checkActorData->aiBehavior->root->execute(event);
delete event;
delete data;
}
if (newOutRange.size() > 0)
{
constellation::BehaviorEvent * event = new constellation::BehaviorEvent(LOFD_BEHAVIOR_EVENT_NEW_ACTOR_OUT_RANGE);
lofd::AIBehaviorDynamicData * data = new lofd::AIBehaviorDynamicData();
data->actorData = checkActorData;
//data->rangeChangeActors = newOutRange;
data->operationType = LOFD_ACTOR_STATE_OPERATION_TYPE_AI;
event->behaviorData = data;
checkActorData->aiBehavior->root->execute(event);
delete event;
delete data;
}
newIntoRange.clear();
newOutRange.clear();
}
}
countCheckRange ++;
}
bool lofd::MapActorsLayer::init()
{
if (!moonsugar::MapActorsLayer::init()) return false;
return true;
}
lofd::MapActorsLayer * lofd::MapActorsLayer::create(moonsugar::ActorLayerData *actorLayerDataValue)
{
lofd::MapActorsLayer * mapActorsLayer = new lofd::MapActorsLayer(actorLayerDataValue);
if (mapActorsLayer && mapActorsLayer->init())
{
mapActorsLayer->autorelease();
return mapActorsLayer;
}
else
{
delete mapActorsLayer;
mapActorsLayer = nullptr;
return nullptr;
}
}
/************MapEffectLayer****************/
MapEffectLayer * MapEffectLayer::create(moonsugar::EffectLayerData * effectLayerDataValue)
{
MapEffectLayer * mapEffectLayer = new MapEffectLayer(effectLayerDataValue);
if (mapEffectLayer && mapEffectLayer->init())
{
mapEffectLayer->autorelease();
return mapEffectLayer;
}
else
{
delete mapEffectLayer;
mapEffectLayer = nullptr;
return nullptr;
}
}
bool MapEffectLayer::init()
{
if (!moonsugar::MapEffectLayer::init()) return false;
this->addContextListeners();
return true;
}
void MapEffectLayer::addContextListeners()
{
cocos2d::EventDispatcher * eventDispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
this->actorHurtEventListener = cocos2d::EventListenerCustom::create(ACTOR_EVENT_HURT, CC_CALLBACK_1(MapEffectLayer::onActorHurtHandler, this));
eventDispatcher->addEventListenerWithFixedPriority(this->actorHurtEventListener, 1);
}
void MapEffectLayer::removeContextListeners()
{
cocos2d::EventDispatcher * eventDispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
eventDispatcher->removeEventListener(this->actorHurtEventListener);
}
void MapEffectLayer::onActorHurtHandler(cocos2d::EventCustom *event)
{
//cocos2d::log("onActorHurtHandler");
lofd::ActorHurtEventParam * actorHurtEventParam = static_cast<lofd::ActorHurtEventParam *>(event->getUserData());
//
auto hurtCount = lofd::HurtCount::create();
hurtCount->setCount(actorHurtEventParam->hurt, actorHurtEventParam->location);
this->addChild(hurtCount);
hurtCount->startAnimation();
delete actorHurtEventParam;
}
/**********BattleScene*********************/
lofd::BattleScene * BattleScene::create()
{
lofd::BattleScene * battleScene = new lofd::BattleScene();
if (battleScene && battleScene->init())
{
battleScene->autorelease();
return battleScene;
}
else
{
delete battleScene;
battleScene = nullptr;
return nullptr;
}
}
bool lofd::BattleScene::init()
{
if (!cocos2d::Scene::init()) return false;
return true;
}
/************UISceneLayer*************/
bool UISceneLayer::init()
{
if (!cocos2d::Layer::init()) return false;
cocos2d::Point point(1200, 80);
lofd::SkillButton * skillButton = lofd::SkillButton::create();
skillButton->createButton();
this->addChild(skillButton);
skillButton->setPosition(point);
lofd::SkillDef * skillDef = lofd::ConfigManager::getInstance()->skillConfig->getSkillDefById(1);
skillButton->skillDef = skillDef;
return true;
}
NS_LOFD_END; |
eda6a81e63c3f47a37f7ad007f038c8c6331cd09 | 314a1470ca6d6853169aba1dfb8641ef65c106f8 | /src/Material.cpp | 4cd342d511da6ef9b3a06120769375faac0564ae | [] | no_license | yukatan1701/RayTracing | 6ecb7765699e8e2aa2f06a52045177879265630d | 92da183e14140b6c4c9a8f20f4526e4a1df609eb | refs/heads/master | 2023-08-29T09:22:43.513971 | 2021-10-05T13:36:33 | 2021-10-05T13:36:33 | 244,148,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | Material.cpp |
#include "Material.h"
#include <iostream>
using namespace glm;
Materials::Materials() {
materials.push_back(Material());
materials.push_back(Material(1.5, vec4(0.0, 0.5, 0.1, 0.8), vec3(0.6, 0.7, 0.8), 125., "glass"));
materials.push_back(Material(1.0, vec4(0.0, 10.0, 0.8, 0.0), vec3(1.0, 1.0, 1.0), 1425., "mirror"));
materials.push_back(Material(1.0, vec4(0.5, 3.0, 0.2, 0.0), vec3(120/255.0f, 85/255.0f, 15/255.0f), 125, "gold"));
materials.push_back(Material(1.0, vec4(0.5, 3.0, 0.2, 0.0), vec3(0.3, 0.3, 0.3), 125, "silver"));
materials.push_back(Material(1.0, vec4(0.9, 0.1, 0.2, 0.0), vec3(0, 60, 179) * 0.3f / 255.0f, 10., "water_bottom"));
materials.push_back(Material(1.0, vec4(0.9, 0.1, 0.2, 0.5), vec3(0, 43, 128) * 0.3f / 255.0f, 125., "water_top"));
materials.push_back(Material(1.0, vec4(0.9, 0.1, 0.0, 0.0), vec3(136, 204, 0) * 0.3f / 255.0f, 10., "island"));
materials.push_back(Material(1.0, vec4(0.9, 0.1, 0.0, 0.0), vec3(102, 51, 0) * 0.5f / 255.0f, 10., "wood"));
}
Material Materials::get(const std::string &name) const {
for (auto &item : materials) {
if (item.name == name)
return item;
}
std::cerr << "Failed to find material of type '" << name <<
"'. Load standard material." << std::endl;
return Material();
} |
12ecf15350822b0b809fc3448238bb9c82eb8ee8 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/rtorrent/gumtree/rtorrent_repos_function_498.cpp | 08ded74f3ba2fc3fba11a610e291420d862a1ca0 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105 | cpp | rtorrent_repos_function_498.cpp | slot_map& slot_map_erase() { return m_slotMaps[SLOTS_ERASE]; } |
1953509b72120dbbd559fa08d8b63cdacf3c78fe | b2dd85d677f068197786c0c2d31a783537637811 | /temper/test.cpp | 6d2807c9b5b1c7199b4e328f8083752d59e39590 | [] | no_license | Tsarpf/RaspberryPi-and-Arduino-Stuff | 299455af3045b9b1b6b19242c2316e7c2f26e125 | e9c17d717f69de8e251ed1b97125f24adbd012a0 | refs/heads/master | 2016-09-05T18:24:44.119326 | 2013-07-05T18:28:24 | 2013-07-05T18:28:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | cpp | test.cpp | #include <string>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
string executeAndRead(const char *);
int characterIdxFromString(string, char);
const char * cmd("./temper");
int main()
{
string result = executeAndRead(cmd);
int idx = characterIdxFromString(result, ',');
int strLen= result.length() - idx - 1;
string tempStr = result.substr(idx + 1, strLen);
double temp = atof(tempStr.c_str());
temp -= 5; //Magnificent calibration of the sensor. Gotta look more into it..
cout << "elikkäs: " << temp << " ... ebin!" << endl;
return 0;
}
int characterIdxFromString(string str, char c)
{
if(str.length() == 0)
{
return -1;
}
for(int i = 0; i < str.length(); i++)
{
if(str[i] == c)
return i;
}
return -1;
}
string executeAndRead(const char* cmd)
{
FILE * pipe = popen(cmd, "r");
if(!pipe) return "ERROR";
char buffer[128];
string result = "";
while (!feof(pipe))
{
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
|
1c0facccf673a0569a1174123535ed44f038f3d2 | 85e4cda6b18162fb69e86c030b4d11eda9a8e0d4 | /BIT Manipulation/BIT Manipulation.cpp | a65cac3607e0e40c26cddf46570ae22ccc401764 | [] | no_license | JatinSharma2821/C-plus-plus | 4e8e244a6e756ca038cff78358185e2e86a5d1dd | a73febc0302382321bc448b599a569cf88681b7d | refs/heads/main | 2023-06-04T20:53:25.732693 | 2021-06-19T07:56:46 | 2021-06-19T07:56:46 | 376,462,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,507 | cpp | BIT Manipulation.cpp | /*
Checkbit - How to find whether at given position of number in binary form , it is 0 or 1;
Setbit/UNsetbit
Clearbit
Updatebit = Clearbit + setbit
*/
#include<iostream>
using namespace std;
int getbit(int num, int pos) // checbit
{
if (num & (1<<pos) != 0)// & is a logical operator that compares using truth table that 1=is 1 if both are one , ....
{return 1;}
else
{return 0;}
}
int setbit(int num, int bit, int pos)
{
return (num | (bit<<pos)); // bit represents 1 for set bit and 0 for unset bit;
}
int clearbit(int num,int pos)
{
/*
Approach is - lets say we have 10, so bin(10) = 1110,
we want to clearbit at pos = 2 , means we want to make 0 at pos = 2
we will use ~1 ... 1<<2 = 1<<2 - 0100 ; ~0100 = 1011,
now we have zero @ desired position so now we will take its & with num
1110 & 1010 = 1010
*/
return (num & ~(1<<pos));
}
int updatebit(int num, int pos, int bitt) // updatebit = clearbit + setbit
{
int value = (num & ~(1<<pos)); // clear bit
return (value | (bitt<<pos));
}
int main()
{
int num,pos,bit,bitt;
cin>>num>>pos>>bit>>bitt;
cout<<getbit(num,pos)<<endl;// check whether bit at given position is 1
cout<<setbit(num,bit,pos)<<endl; // set given bit at pos,
cout<<clearbit(num,pos)<<endl; // clearbit clears the bit at given position i.e, makes it 0;
cout<<updatebit(num,pos,bitt);// it will update bitt at given position
return 0;
}
|
264ddac166a89fa734ec4b125689d03a6b36629c | 7ce9aabed89076cc78a5a25298c9da599bde4f81 | /cds/bit_vector_rank.h | 310376415cf8895e2e6afe22d5da4e34fadbcd11 | [
"Apache-2.0"
] | permissive | pombredanne/CompactDataStructures | 6bc9d16ef64c9795a60e57175b43bbead3403020 | f7a7ab95f7353440dc4b66caeb07448b35b743fe | refs/heads/master | 2021-12-14T16:47:31.429916 | 2017-05-13T12:56:53 | 2017-05-13T12:56:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | h | bit_vector_rank.h | #pragma once
#include <vector>
#include "bit_vector.h"
namespace cds {
uint64_t popcount(uint64_t bits);
class bit_vector_rank : public bit_vector {
std::vector<uint64_t> sample_ranks;
std::vector<uint16_t> cell_ranks;
void bit_write(uint64_t index, bool is_set);
public:
uint64_t rate;
bit_vector_rank(uint64_t rate = 64, uint64_t size = 0);
void resize(uint64_t size);
uint64_t vector_size() const;
void bit_set(uint64_t index);
void bit_clear(uint64_t index);
uint64_t rank(uint64_t index) const;
uint64_t rank_naive(uint64_t index) const;
uint64_t select(uint64_t value) const;
};
}
|
4dd1914cda60d7a1e2998338ba420dab5ab41b40 | 98fa0f486153e95d6a39024c7dd8f8387669da13 | /FSM_framework_example/StateManager.cpp | 5eefd0325691c1056831a09a5f6a47df297cbddd | [] | no_license | Babdodook/FSM_framework_example | 89fa21e5cb95794c51684908434af0e89215c6ec | 11ac2ec9be46fdfc6ceacbbedcf8eba495f6b97d | refs/heads/master | 2021-06-03T00:34:18.782755 | 2020-04-09T09:28:34 | 2020-04-09T09:28:34 | 254,325,239 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,801 | cpp | StateManager.cpp | #include"StateManager.h"
StateManager* StateManager::mPthis = nullptr;
StateManager* StateManager::Create()
{
if (!mPthis)
{
mPthis = new StateManager();
}
return mPthis;
}
StateManager* StateManager::GetInstance()
{
return mPthis;
}
void StateManager::Destroy()
{
if (mPthis)
{
delete mPthis;
mPthis = nullptr;
}
}
StateManager::StateManager()
{
Battle::Create();
FieldMap::Create();
Option::Create();
WorldMap::Create();
sInterface = WorldMap::GetInstance();
m_CurruntState = State::Max;
}
StateManager::~StateManager()
{
Battle::Destroy();
FieldMap::Destroy();
Option::Destroy();
WorldMap::Destroy();
}
void StateManager::ChangeState(State _state)
{
sInterface->ExitState();
switch (_state)
{
case State::STATE_Battle:
sInterface = Battle::GetInstance();
break;
case State::STATE_FieldMap:
sInterface = FieldMap::GetInstance();
break;
case State::STATE_Option:
sInterface = Option::GetInstance();
break;
case State::STATE_WorldMap:
sInterface = WorldMap::GetInstance();
break;
}
sInterface->EnterState();
}
void StateManager::Run()
{
int select;
std::cout << "1. 배틀" << std::endl;
std::cout << "2. 필드맵" << std::endl;
std::cout << "3. 옵션" << std::endl;
std::cout << "4. 월드맵" << std::endl;
while (1)
{
std::cout << "선택>>";
std::cin >> select;
std::cout << std::endl;
ChangeState(SelectMenu(select));
sInterface->Display();
std::cout << std::endl;
}
}
State StateManager::SelectMenu(int select)
{
State tempState = State::Max;
switch (select)
{
case 1:
tempState = State::STATE_Battle;
break;
case 2:
tempState = State::STATE_FieldMap;
break;
case 3:
tempState = State::STATE_Option;
break;
case 4:
tempState = State::STATE_WorldMap;
break;
}
return tempState;
} |
7501c4b67e788e74830c5abbfd628ca39047288e | d79c643be0ee59693c2bde11fb990fe0314148b3 | /src/scramblestr_unittests.cc | c165db644a3741989d9483114559d442bc73e7ca | [] | no_license | hch-im/leetcode | ad1f50f28a48e20cd5d3c8d57c94cdadb7545455 | d6a2327bc6fc971d2ed44c4b648c8b48805bdbb1 | refs/heads/master | 2016-09-06T18:16:16.906852 | 2014-08-31T04:15:24 | 2014-08-31T04:15:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | cc | scramblestr_unittests.cc | #include <gtest/gtest.h>
#include "scramblestr.h"
TEST(ScrambleString, isScramble)
{
ScrambleString ss;
EXPECT_TRUE(ss.isScramble("eat", "ate"));
EXPECT_TRUE(ss.isScramble("great", "tareg"));
EXPECT_FALSE(ss.isScramble("g", "t"));
} |
246d6df6b42f780386fa4a1e64095fca00f4a17f | 78e0a01db4afa3fdd428aedcab96c86b0e79aed6 | /Algorithms/Breadth-First Search/main.cpp | f71cf4945c76128868910af5a5793a49b0bb3706 | [] | no_license | VladGeana/Vlad-s-Projects | edea9c2387bc8174b032293beb0df2d00ce356c0 | 1cbc05bfbee93487e08635c7c04c26a9a8040be1 | refs/heads/master | 2020-07-20T00:29:21.608271 | 2020-05-23T13:55:39 | 2020-05-23T13:55:39 | 206,539,819 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 898 | cpp | main.cpp | #include <iostream>
#include<fstream>
#include<vector>
#define Nmax 100001
#define mx 1000000000
typedef int coada[Nmax];
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
coada c;
int cst[Nmax],n,m,x,y,s,i;
vector<int>v[Nmax];
void BFS(int nod)
{
int siz=1,start=1;
c[start]=nod;
cst[nod]=0;
while(siz-start>=0)
{
for(int j=0;j<v[c[start]].size();j++)
if(cst[v[c[start]][j]] > cst[c[start]]+1)
{
cst[v[c[start]][j]] = cst[c[start]]+1;
c[++siz]=v[c[start]][j] ;
}
start++;
}
}
int main()
{
f>>n>>m>>s;
for(i=1;i<=m;i++)
{
f>>x>>y;
if(x!=y)
v[x].push_back(y);
}
for(i=1;i<=n;i++)
cst[i]=mx;
BFS(s);
for(i=1;i<=n;i++)
if(cst[i]!=mx) g<<cst[i]<<' ';
else g<<-1<<' ';
}
|
f306ca12f77755da0c9375dc682be19368671674 | 85687165c3144a21dc084c75989bd9864aee6340 | /GeometryLib/Plane.cpp | 61c968168c671255c0b5622f3184de747f78a040 | [] | no_license | toi333/GeometryLib | c8c432670b2688704cf8e2a92308cf294fcfd20a | cf4060b30220b8666211258380d10e95cc2c3c98 | refs/heads/master | 2021-07-21T02:28:33.277240 | 2020-07-04T12:40:03 | 2020-07-04T12:40:03 | 6,493,005 | 0 | 0 | null | 2013-02-11T12:01:51 | 2012-11-01T16:40:37 | C++ | UTF-8 | C++ | false | false | 916 | cpp | Plane.cpp | #include "Plane.h"
Plane::Plane(void)
{
}
Plane::Plane(const Vector &_p, const Vector &_n)
{
p = _p;
n = _n.normalized();
}
Plane::Plane(const Vector &a, const Vector &b, const Vector &c)
{
p = a;
n = crossProduct(b - a, c - a).normalize();
}
Plane::Plane(const Surface &sf)
{
p = sf.getPos();
n = sf.normal();
}
Plane::~Plane(void)
{
}
Vector Plane::normal() const
{
return n;
}
double Plane::a() const
{
return n.x;
}
double Plane::b() const
{
return n.y;
}
double Plane::c() const
{
return n.z;
}
double Plane::d() const
{
return -dotProduct(n, p);
}
bool Plane::containsPoint(const Vector &v) const
{
return abs(dotProduct(v - p, n)) <= EPS;
}
bool Plane::containsPointInPlane(const Vector &v) const
{
return true;
}
Vector Plane::getPos() const
{
return p;
}
void Plane::setPos(const Vector &_v)
{
p = _v;
}
|
ec54cded5213f404a35c7cb83fd3f65988a3b5a0 | 5cee7b879a377d58d5c2eeb4e30c57070c08f317 | /test6/main.cpp | 759a5d8cba40ca80dadf50fde3b06ca3c5b5fefe | [] | no_license | zy-cuhk/cplus_learning | 13182a4fcd9af138265961debb7315fd47a99acf | 2a3f235e8fe5107e2295c2a74e93802b75c9d66f | refs/heads/master | 2022-11-17T08:58:19.797499 | 2020-07-15T06:43:34 | 2020-07-15T06:43:34 | 278,896,026 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | cpp | main.cpp | #include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main ()
{
int n[ 10 ];
for ( int i = 0; i < 10; i++ )
{
n[ i ] = i + 100;
}
cout << "Element" << setw( 13 ) << "Value" << endl;
for ( int j = 0; j < 10; j++ )
{
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}
int a[3]={1,2,3};
cout<<"a is:"<<a[0]<<endl;
int a1[5][2]={{0,0},{1,1},{2,2},{3,3},{4,4}};
for (int i=0;i<5;i=i+1)
{
for (int j=0;j<2;j=j+1)
{
cout<<"the element is"<<a1[i][j]<<endl;
}
}
return 0;
}
|
5b5ed04d88cdfab7b6ce54cdb14313add7348f61 | 87756c0f1f5bf3828dd14fbcd862fc2326aed42e | /text2/text2/text2View.cpp | 33fe010142776708ab68d7a4d80544db9290b2c2 | [] | no_license | Brenda-t/VCtext | 7a3a96395d667259e96e70d7ff8273bd4433a8ff | abe0d89939e6c68ac16863054c96e4edc0174498 | refs/heads/master | 2022-10-25T19:18:29.650099 | 2020-06-09T07:43:13 | 2020-06-09T07:43:13 | 245,200,062 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,916 | cpp | text2View.cpp |
// text2View.cpp : Ctext2View 类的实现
//
#include "stdafx.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义,并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "text2.h"
#endif
#include "text2Doc.h"
#include "text2View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Ctext2View
IMPLEMENT_DYNCREATE(Ctext2View, CView)
BEGIN_MESSAGE_MAP(Ctext2View, CView)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
END_MESSAGE_MAP()
// Ctext2View 构造/析构
Ctext2View::Ctext2View()
{
// TODO: 在此处添加构造代码
}
Ctext2View::~Ctext2View()
{
}
BOOL Ctext2View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return CView::PreCreateWindow(cs);
}
// Ctext2View 绘制
void Ctext2View::OnDraw(CDC* pDC)
{
Ctext2Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
}
// Ctext2View 诊断
#ifdef _DEBUG
void Ctext2View::AssertValid() const
{
CView::AssertValid();
}
void Ctext2View::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
Ctext2Doc* Ctext2View::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(Ctext2Doc)));
return (Ctext2Doc*)m_pDocument;
}
#endif //_DEBUG
// Ctext2View 消息处理程序
void Ctext2View::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CClientDC ds(this);
CString s = _T("左键正被按下");
ds.TextOutW(100, 100, s);
CView::OnLButtonDown(nFlags, point);
}
void Ctext2View::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CClientDC ds(this);
CString s = _T("左键正在抬起");
ds.TextOutW(500, 500, s);
CView::OnLButtonUp(nFlags, point);
}
|
dfa77646c6072e4da1504ffc83fe376546e60335 | f0dc030b7d67435d3c6c493e50118fb46f680468 | /include/Color.h | b46a712d7a59514c4ac0a0fbbbd2ce687ebc5cbe | [] | no_license | mo7sen/CPU-RayTracer | 0b7d3cc8dee8b3e59ecfb61acc3bba64a554ce2b | e1bfbf9fdf16095daf468780148567bfcb6056ae | refs/heads/master | 2023-08-14T21:47:15.618030 | 2021-10-04T01:50:59 | 2021-10-04T01:50:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,937 | h | Color.h | #ifndef RT_COLOR_HEADER
#define RT_COLOR_HEADER
#include <common.h>
#include <Vec3.h>
class Color {
public:
static const int32_t COMP_PER_PIXEL = 4;
real data[COMP_PER_PIXEL];
public:
Color() = default;
Color(real rgb) : Color(rgb, rgb, rgb) {}
Color(real r, real g, real b) : Color(r, g, b, 1.0) {}
Color(real r, real g, real b, real a) : data{ r, g, b, a } {}
static Color fromUnitVector(const Vec3f& v);
real r() const { return data[0]; }
real g() const { return data[1]; }
real b() const { return data[2]; }
real a() const { return data[3]; }
uint32_t r_u8() const { return static_cast<uint32_t>(255.999 * data[0]); }
uint32_t g_u8() const { return static_cast<uint32_t>(255.999 * data[1]); }
uint32_t b_u8() const { return static_cast<uint32_t>(255.999 * data[2]); }
uint32_t a_u8() const { return static_cast<uint32_t>(255.999 * data[3]); }
void set(real r, real g, real b) { data[0] = r; data[1] = g; data[2] = b; }
Vec3f toVec3f() const
{
return Vec3f(data);
}
static Color fromVec3f(Vec3f v)
{
return Color(v.x(), v.y(), v.z());
}
~Color() = default;
};
#include <iostream>
inline std::ostream& operator<<(std::ostream& os, Color const& color)
{
os << color.r_u8() << ' ' << color.g_u8() << ' ' << color.b_u8();
return os;
}
inline Color operator * (real s, const Color& c)
{
return Color{
c.data[0] * s,
c.data[1] * s,
c.data[2] * s
};
}
inline Color operator * (const Color& c, real s)
{
return s * c;
}
inline Color operator + (const Color& u, const Color& v)
{
return Color{
u.data[0] + v.data[0],
u.data[1] + v.data[1],
u.data[2] + v.data[2]
};
}
inline Color operator - (const Color& u, const Color& v)
{
return Color{
u.data[0] - v.data[0],
u.data[1] - v.data[1],
u.data[2] - v.data[2]
};
}
inline Color operator * (const Color& u, const Color& v)
{
return Color{
u.data[0] * v.data[0],
u.data[1] * v.data[1],
u.data[2] * v.data[2]
};
}
#endif
|
19ea2d62353614fb16c559f1252f9f068252c4b9 | 29f6bec60229802528fbbefaf870a0be9a8f1b84 | /bind/imf_testfile.cpp | 42e36224239b91fc9a0e1fdfa127a504ad9f497d | [
"BSD-3-Clause"
] | permissive | anderslanglands/openexr-bind | a6b632d32efedfd39039a3f9fa6e90673502e15e | 06b3d3a9079ef10a21ec331ebfa8b055a04b3b7d | refs/heads/main | 2023-07-03T04:03:22.615738 | 2021-08-14T01:05:11 | 2021-08-14T01:05:11 | 382,241,781 | 1 | 0 | Apache-2.0 | 2021-07-02T05:38:01 | 2021-07-02T05:38:00 | null | UTF-8 | C++ | false | false | 1,622 | cpp | imf_testfile.cpp | #include <OpenEXR/ImfTestFile.h>
#include <cppmm_bind.hpp>
namespace cppmm_bind {
namespace OPENEXR_IMF_INTERNAL_NAMESPACE {
namespace Imf = ::OPENEXR_IMF_INTERNAL_NAMESPACE;
IMF_EXPORT bool isOpenExrFile(const char fileName[]) CPPMM_IGNORE;
IMF_EXPORT bool isOpenExrFile(const char fileName[],
bool& isTiled) CPPMM_IGNORE;
IMF_EXPORT bool isOpenExrFile(const char fileName[], bool& isTiled,
bool& isDeep) CPPMM_IGNORE;
IMF_EXPORT bool isOpenExrFile(const char fileName[], bool& isTiled,
bool& isDeep, bool& isMultiPart);
IMF_EXPORT bool isTiledOpenExrFile(const char fileName[]);
IMF_EXPORT bool isDeepOpenExrFile(const char fileName[]);
IMF_EXPORT bool isMultiPartOpenExrFile(const char fileName[]);
IMF_EXPORT bool isOpenExrFile(Imf::IStream& is) CPPMM_IGNORE;
IMF_EXPORT bool isOpenExrFile(Imf::IStream& is, bool& isTiled) CPPMM_IGNORE;
IMF_EXPORT bool isOpenExrFile(Imf::IStream& is, bool& isTiled,
bool& isDeep) CPPMM_IGNORE;
IMF_EXPORT bool isOpenExrFile(Imf::IStream& is, bool& isTiled, bool& isDeep,
bool& isMultiPart)
CPPMM_RENAME(stream_is_openexr_file);
IMF_EXPORT bool isTiledOpenExrFile(Imf::IStream& is)
CPPMM_RENAME(stream_is_tiled_openexr_file);
IMF_EXPORT bool isDeepOpenExrFile(Imf::IStream& is)
CPPMM_RENAME(stream_is_deep_openexr_file);
IMF_EXPORT bool isMultiPartOpenExrFile(Imf::IStream& is)
CPPMM_RENAME(stream_is_multi_part_openexr_file);
} // namespace OPENEXR_IMF_INTERNAL_NAMESPACE
} // namespace cppmm_bind
|
6f992f2a8175711239d442efd7683f8221531930 | 29fe36fed5702f561932135b21a573e9e63daf70 | /tools/lldb-mi/MICmnLLDBUtilSBValue.cpp | 37495a4e4e8f3fa2838426ab397e4ec6c89f6b29 | [
"NCSA"
] | permissive | chapuni/lldb | 30cc3b14702a06cf8d29f78e078476bcf34b28f4 | 1fe2076d4c88fcf374a1ce8f5486c340cb61a304 | refs/heads/master | 2021-01-22T04:41:24.462411 | 2015-04-04T19:09:18 | 2015-04-04T19:09:18 | 2,956,659 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,413 | cpp | MICmnLLDBUtilSBValue.cpp | //===-- MICmnLLDBUtilSBValue.cpp --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// In-house headers:
#include "MICmnLLDBUtilSBValue.h"
#include "MIUtilString.h"
#include "MICmnLLDBDebugSessionInfo.h"
//++ ------------------------------------------------------------------------------------
// Details: CMICmnLLDBUtilSBValue constructor.
// Type: Method.
// Args: vrValue - (R) The LLDb value object.
// vbHandleCharType - (R) True = Yes return text molding to char type,
// False = just return data.
// Return: None.
// Throws: None.
//--
CMICmnLLDBUtilSBValue::CMICmnLLDBUtilSBValue(const lldb::SBValue &vrValue, const bool vbHandleCharType /* = false */)
: m_rValue(const_cast<lldb::SBValue &>(vrValue))
, m_pUnkwn("??")
, m_bHandleCharType(vbHandleCharType)
{
m_bValidSBValue = m_rValue.IsValid();
}
//++ ------------------------------------------------------------------------------------
// Details: CMICmnLLDBUtilSBValue destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
CMICmnLLDBUtilSBValue::~CMICmnLLDBUtilSBValue(void)
{
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve from the LLDB SB Value object the name of the variable. If the name
// is invalid (or the SBValue object invalid) then "??" is returned.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Name of the variable or "??" for unknown.
// Throws: None.
//--
CMIUtilString
CMICmnLLDBUtilSBValue::GetName(void) const
{
const MIchar *pName = m_bValidSBValue ? m_rValue.GetName() : nullptr;
const CMIUtilString text((pName != nullptr) ? pName : m_pUnkwn);
return text;
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve from the LLDB SB Value object the value of the variable described in
// text. If the value is invalid (or the SBValue object invalid) then "??" is
// returned.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Text description of the variable's value or "??".
// Throws: None.
//--
CMIUtilString
CMICmnLLDBUtilSBValue::GetValue(void) const
{
CMIUtilString text;
if (m_bHandleCharType && IsCharType())
{
uint8_t val = (uint8_t)m_rValue.GetValueAsUnsigned ();
text += CMIUtilString::Format("%d '%c'", val, (char)val);
}
else
{
const MIchar *pValue = m_bValidSBValue ? m_rValue.GetValue() : nullptr;
text = (pValue != nullptr) ? pValue : m_pUnkwn;
}
return text;
}
//++ ------------------------------------------------------------------------------------
// Details: If the LLDB SB Value object is a char type then form the text data string
// otherwise return nothing. m_bHandleCharType must be true to return text data
// if any.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Text description of the variable's value.
// Throws: None.
//--
CMIUtilString
CMICmnLLDBUtilSBValue::GetValueCString(void) const
{
CMIUtilString text;
if (m_bHandleCharType && IsCharType())
{
text = ReadCStringFromHostMemory(m_rValue);
}
return text;
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve the flag stating whether this value object is a char type or some
// other type. Char type can be signed or unsigned.
// Type: Method.
// Args: None.
// Return: bool - True = Yes is a char type, false = some other type.
// Throws: None.
//--
bool
CMICmnLLDBUtilSBValue::IsCharType(void) const
{
const lldb::BasicType eType = m_rValue.GetType().GetBasicType();
return ((eType == lldb::eBasicTypeChar) || (eType == lldb::eBasicTypeSignedChar) || (eType == lldb::eBasicTypeUnsignedChar));
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve the flag stating whether any child value object of *this object is a
// char type or some other type. Returns false if there are not children. Char
// type can be signed or unsigned.
// Type: Method.
// Args: None.
// Return: bool - True = Yes is a char type, false = some other type.
// Throws: None.
//--
bool
CMICmnLLDBUtilSBValue::IsChildCharType(void) const
{
const MIuint nChildren = m_rValue.GetNumChildren();
// Is it a basic type
if (nChildren == 0)
return false;
// Is it a composite type
if (nChildren > 1)
return false;
lldb::SBValue member = m_rValue.GetChildAtIndex(0);
const CMICmnLLDBUtilSBValue utilValue(member);
return utilValue.IsCharType();
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve the C string data for a child of char type (one and only child) for
// the parent value object. If the child is not a char type or the parent has
// more than one child then an empty string is returned. Char type can be
// signed or unsigned.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Text description of the variable's value.
// Throws: None.
//--
CMIUtilString
CMICmnLLDBUtilSBValue::GetChildValueCString(void) const
{
CMIUtilString text;
const MIuint nChildren = m_rValue.GetNumChildren();
// Is it a basic type
if (nChildren == 0)
return text;
// Is it a composite type
if (nChildren > 1)
return text;
lldb::SBValue member = m_rValue.GetChildAtIndex(0);
const CMICmnLLDBUtilSBValue utilValue(member);
if (m_bHandleCharType && utilValue.IsCharType())
{
text = ReadCStringFromHostMemory(member);
}
return text;
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve the C string data of value object by read the memory where the
// variable is held.
// Type: Method.
// Args: vrValueObj - (R) LLDB SBValue variable object.
// Return: CMIUtilString - Text description of the variable's value.
// Throws: None.
//--
CMIUtilString
CMICmnLLDBUtilSBValue::ReadCStringFromHostMemory(const lldb::SBValue &vrValueObj) const
{
CMIUtilString text;
lldb::SBValue &rValue = const_cast<lldb::SBValue &>(vrValueObj);
const lldb::addr_t addr = rValue.GetLoadAddress();
CMICmnLLDBDebugSessionInfo &rSessionInfo(CMICmnLLDBDebugSessionInfo::Instance());
const MIuint nBytes(128);
const MIchar *pBufferMemory = new MIchar[nBytes];
lldb::SBError error;
const MIuint64 nReadBytes = rSessionInfo.GetProcess().ReadMemory(addr, (void *)pBufferMemory, nBytes, error);
MIunused(nReadBytes);
text = CMIUtilString::Format("\\\"%s\\\"", pBufferMemory);
delete[] pBufferMemory;
return text;
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve the state of the value object's name.
// Type: Method.
// Args: None.
// Return: bool - True = yes name is indeterminate, false = name is valid.
// Throws: None.
//--
bool
CMICmnLLDBUtilSBValue::IsNameUnknown(void) const
{
const CMIUtilString name(GetName());
return (name == m_pUnkwn);
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve the state of the value object's value data.
// Type: Method.
// Args: None.
// Return: bool - True = yes value is indeterminate, false = value valid.
// Throws: None.
//--
bool
CMICmnLLDBUtilSBValue::IsValueUnknown(void) const
{
const CMIUtilString value(GetValue());
return (value == m_pUnkwn);
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve the value object's type name if valid.
// Type: Method.
// Args: None.
// Return: CMIUtilString - The type name or "??".
// Throws: None.
//--
CMIUtilString
CMICmnLLDBUtilSBValue::GetTypeName(void) const
{
const MIchar *pName = m_bValidSBValue ? m_rValue.GetTypeName() : nullptr;
const CMIUtilString text((pName != nullptr) ? pName : m_pUnkwn);
return text;
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve the value object's display type name if valid.
// Type: Method.
// Args: None.
// Return: CMIUtilString - The type name or "??".
// Throws: None.
//--
CMIUtilString
CMICmnLLDBUtilSBValue::GetTypeNameDisplay(void) const
{
const MIchar *pName = m_bValidSBValue ? m_rValue.GetDisplayTypeName() : nullptr;
const CMIUtilString text((pName != nullptr) ? pName : m_pUnkwn);
return text;
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve whether the value object's is valid or not.
// Type: Method.
// Args: None.
// Return: bool - True = valid, false = not valid.
// Throws: None.
//--
bool
CMICmnLLDBUtilSBValue::IsValid(void) const
{
return m_bValidSBValue;
}
//++ ------------------------------------------------------------------------------------
// Details: Retrieve the value object' has a name. A value object can be valid but still
// have no name which suggest it is not a variable.
// Type: Method.
// Args: None.
// Return: bool - True = valid, false = not valid.
// Throws: None.
//--
bool
CMICmnLLDBUtilSBValue::HasName(void) const
{
bool bHasAName = false;
const MIchar *pName = m_bValidSBValue ? m_rValue.GetDisplayTypeName() : nullptr;
if (pName != nullptr)
{
bHasAName = (CMIUtilString(pName).length() > 0);
}
return bHasAName;
}
//++ ------------------------------------------------------------------------------------
// Details: Determine if the value object' respresents a LLDB variable i.e. "$0".
// Type: Method.
// Args: None.
// Return: bool - True = Yes LLDB variable, false = no.
// Throws: None.
//--
bool
CMICmnLLDBUtilSBValue::IsLLDBVariable(void) const
{
return (GetName().at(0) == '$');
}
|
6b9f351fafeb6860b013d051a8b3623243f4421a | 0437c72bda3535dc9e4dcb0407126d7fe01f1211 | /TUR/ErusBot/Accelerometer.cpp | 026df2012b1a35e51751d9feb498921fe809a67d | [] | no_license | catabriga/erus | a390a29e475c93619865e7552f4fa957ebdacfb8 | 16f30e85ff1d22fb1cdf627a82ae6f596042ee4d | refs/heads/master | 2020-04-16T06:19:00.664281 | 2014-04-25T19:13:14 | 2014-04-25T19:13:14 | 7,018,438 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 777 | cpp | Accelerometer.cpp | /*#include <Arduino.h>
#include <math.h>
#include "Pins.h"
#include "Accelerometer.h"
static double x,y,z;
static int minVal;
static int maxVal;
static int xAng,yAng,zAng;
void setupAccelerometer()
{
x = y = z = 0;
xAng = yAng = zAng = 0;
minVal = 265;
maxVal = 402;
}
double getAccX()
{
int xRead = analogRead(ACC_X_AXIS);
xAng = map(xRead, minVal, maxVal, -90, 90);
x = RAD_TO_DEG * (atan2(-yAng, -zAng) + M_PI);
return x;
}
double getAccY()
{
int yRead = analogRead(ACC_Y_AXIS);
yAng = map(yRead, minVal, maxVal, -90, 90);
y = RAD_TO_DEG * (atan2(-xAng, -zAng) + M_PI);
return y;
}
double getAccZ()
{
int zRead = analogRead(ACC_Z_AXIS);
zAng = map(zRead, minVal, maxVal, -90, 90);
z = RAD_TO_DEG * (atan2(-yAng, -xAng) + M_PI);
return z;
}*/
|
3021554badbb495b445e775a37edb504d62c7534 | 4d317369bd7de599e0364e9097e50f381845e22c | /2020/Div 3/634 Div 3/Programs/Two Teams Composing.cpp | 4f104378e300ad920a1f84b91db4e5667b604951 | [] | no_license | MathProgrammer/CodeForces | 4865f0bad799c674ff9e6fde9a008b988af2aed0 | e3483c1ac4a7c81662f6a0bc8af20be69e0c0a98 | refs/heads/master | 2023-04-07T11:27:31.766011 | 2023-04-01T06:29:19 | 2023-04-01T06:29:19 | 84,833,335 | 256 | 114 | null | 2021-10-02T21:14:47 | 2017-03-13T14:02:57 | C++ | UTF-8 | C++ | false | false | 1,084 | cpp | Two Teams Composing.cpp | #include <iostream>
#include <vector>
#include <set>
#include <map>
#define max(a, b) (a > b ? a : b)
#define min(a, b) (a < b ? a : b)
using namespace std;
void solve()
{
int no_of_elements;
cin >> no_of_elements;
vector <int> A(no_of_elements + 1);
for(int i = 1; i <= no_of_elements; i++)
{
cin >> A[i];
}
set <int> distinct;
map <int, int> frequency;
for(int i = 1; i <= no_of_elements; i++)
{
distinct.insert(A[i]);
frequency[A[i]]++;
}
int team_size = 0;
for(int i = 1; i <= no_of_elements; i++)
{
int team_size_here_1 = min(distinct.size() - 1, frequency[A[i]]);
int team_size_here_2 = min(distinct.size(), frequency[A[i]] - 1);
int team_size_here = max(team_size_here_1, team_size_here_2);
team_size = max(team_size, team_size_here);
}
cout << team_size << "\n";
}
int main()
{
int no_of_test_cases;
cin >> no_of_test_cases;
while(no_of_test_cases--)
solve();
return 0;
}
|
e4be705d4c92801a66602c8f90f8fa17f3211bbc | 314c2ec0e48ed29c906203d864b218d4c6580ebe | /weights_encryptor.cpp | 29b30c79d2d1c48161d1e5356856c1c3e0ae6f62 | [] | no_license | mi-frutuoso/csc-proj | 70cad0c7682b934d2ee526c7f2ac8ec69ca96b82 | 0695e7c8f4615c91302753a5df26d981347c54a8 | refs/heads/master | 2022-03-26T02:16:54.384689 | 2019-12-13T20:43:15 | 2019-12-13T20:43:15 | 224,681,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,426 | cpp | weights_encryptor.cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "/home/tiago/SEAL/native/examples/examples.h"
using namespace std;
using namespace seal;
void weights_encryptor(int value1);
int main(int argc, char const *argv[])
{
int num1 = atoi(argv[1]);
weights_encryptor(num1);
return 0;
}
void weights_encryptor(int value1)
{
EncryptionParameters parms(scheme_type::BFV);
size_t poly_modulus_degree = 4096;
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
parms.set_plain_modulus(512);
auto context = SEALContext::Create(parms);
PublicKey public_key;
ifstream myfile;
myfile.open("election_public.key");
public_key.unsafe_load(context, myfile);
myfile.close();
Encryptor encryptor(context, public_key);
/*
We create an IntegerEncoder.
*/
IntegerEncoder encoder(context);
/*
First, we encode two integers as plaintext polynomials. Note that encoding
is not encryption: at this point nothing is encrypted.
*/
Plaintext plain1 = encoder.encode(value1);
/*
Now we can encrypt the plaintext polynomials.
*/
Ciphertext encrypted1;
encryptor.encrypt(plain1, encrypted1);
ofstream myfile1;
myfile1.open("encrypted.txt");
encrypted1.save(myfile1);
myfile1.close();
} |
6244cce1cb122b68c9dd6487e80445346afe51a7 | 9cfad4a7a6e5e3807999a9c96f28d7e005992e44 | /MCOption5/MCOption5/Random2.hpp | 0214d51a7841fa68518f8683a5958e99be75178a | [] | no_license | yyydky/option_pricing | dc2639fa92aae142a88297d28655ac7443f553e2 | b3cfd69bce06414bdf21574621e429e689a3898c | refs/heads/main | 2023-03-29T10:09:43.797963 | 2021-04-08T14:15:10 | 2021-04-08T14:15:10 | 326,323,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | hpp | Random2.hpp | //
// Random2.hpp
// MCOption5
//
// Created by 一帆朱 on 2021-01-05.
//
#ifndef Random2_hpp
#define Random2_hpp
#include "Arrays.hpp"
#include "Normals.hpp"
#include <cstdlib>
class RandomBase{
public:
RandomBase(unsigned long Dimensionality_);
inline unsigned long GetDimensionality() const;
virtual RandomBase* clone() const=0;
virtual void GetUniforms(MJArray& variates)=0;
virtual void Skip(unsigned long numberOfPaths)=0;
virtual void SetSeed(unsigned long Seed)=0;
virtual void Reset()=0;
virtual ~RandomBase(){}
virtual void GetGaussians(MJArray& variates);
virtual void ResetDimensionality(unsigned long NewDimensionality);
private:
unsigned long Dimensionality;
};
unsigned long RandomBase::GetDimensionality() const{
return Dimensionality;
}
#endif /* Random2_hpp */
|
da2f845d68c3be2b8148dee9f3ef520945775f02 | b0075e2d7115361860b48c11005d59bdabea8a10 | /hmailserver/source/Server/Common/Application/ObjectCache.h | 30e3b7969a9308c1e8f1a72af087a511c1f5af88 | [] | no_license | hmailserver/hmailserver | 73f7d61912db856c3f610e3b829fd7a5135b6bc6 | 12ff3d6ab48b9c6181433f1c0b01ba8c8941abd4 | refs/heads/master | 2023-08-06T11:03:44.558427 | 2023-07-27T13:10:52 | 2023-07-27T13:10:52 | 18,572,902 | 822 | 332 | null | 2023-07-24T14:29:28 | 2014-04-08T19:57:15 | C++ | UTF-8 | C++ | false | false | 1,095 | h | ObjectCache.h | // Copyright (c) 2010 Martin Knafve / hMailServer.com.
// http://www.hmailserver.com
#pragma once
namespace HM
{
class DomainAliases;
class Rules;
class ObjectCache : public Singleton<ObjectCache>
{
public:
ObjectCache(void);
~ObjectCache(void);
void SetDomainAliasesNeedsReload();
std::shared_ptr<DomainAliases> GetDomainAliases();
void SetGlobalRulesNeedsReload();
std::shared_ptr<Rules> GetGlobalRules();
void SetAccountRulesNeedsReload(__int64 iAccountID);
std::shared_ptr<Rules> GetAccountRules(__int64 iAccountID);
void ClearRuleCaches();
private:
std::shared_ptr<DomainAliases> domain_aliases_;
bool domain_aliases_needs_reload_;
std::shared_ptr<Rules> global_rules_;
bool global_rules_needs_reload_;
std::map<__int64, std::shared_ptr<Rules> > account_rules_;
std::set<__int64> account_rules_to_refresh_;
boost::recursive_mutex domain_aliases_mutex_;
boost::recursive_mutex global_rules_mutex_;
boost::recursive_mutex account_rules_mutex_;
};
} |
89b0b9a0a3c8351dacc3f1a7c93125595940f633 | f04b3ad49acf49abcf5cddf0b6cfd98353ef35ec | /src/Gate.h | f03595ef537246e30ee8f131d100d70d3a4560c6 | [] | no_license | TinfoilSubmarine/radec | fe872face65acea38e48f2fb5e5b7a11c5fbb908 | 237e5cd61a771fd8a2acc08631fb99e0714e264f | refs/heads/master | 2021-09-08T08:03:23.462779 | 2017-04-27T00:13:52 | 2017-04-27T00:13:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315 | h | Gate.h | #ifndef GATE
#define GATE
#include "Event.h"
class Wire;
// this class provides a base class for all other Gate classes (provided in
// other files)
class Gate {
public:
virtual Event evaluate(int) = 0;
void setOut(int time, int value);
protected:
Wire *in1, *in2, *out;
int delay;
};
#endif // !GATE
|
864e2a9ca2c0522249cd0cd7680d9d3145143015 | f2c3efa6db82fd8e59fa39c43c7768ede38d02f0 | /include/polimidl/layers/internal/batch_norm_relu.hpp | f7c8b83f718d8b094a36541cd9b37bfba3ef1be5 | [
"MIT"
] | permissive | darianfrajberg/polimidl | ce6e260e86149064142cfc87096884f42eb45481 | ab338269c25a0fcccf06bbfccbfe7fe16ee7cf04 | refs/heads/master | 2021-07-05T03:49:41.119174 | 2020-09-20T21:04:22 | 2020-09-20T21:04:22 | 176,907,084 | 3 | 2 | MIT | 2020-09-20T21:04:23 | 2019-03-21T08:58:51 | C++ | UTF-8 | C++ | false | false | 3,860 | hpp | batch_norm_relu.hpp | #ifndef POLIMIDL_LAYERS_INTERNAL_BATCH_NORM_RELU_HPP
#define POLIMIDL_LAYERS_INTERNAL_BATCH_NORM_RELU_HPP
#include <chrono>
#include <limits>
#include <Eigen/Dense>
#include "../alignment.hpp"
#include "../layer.hpp"
namespace polimidl {
namespace layers {
namespace internal {
template <typename type_t, typename components>
class batch_norm_relu : public layer<type_t, components, true> {
public:
batch_norm_relu(const type_t* beta, const type_t* mean,
const type_t* fused_gamma_variance_epsilon,
type_t min, type_t max) :
beta_(beta),
mean_(mean),
fused_gamma_variance_epsilon_(fused_gamma_variance_epsilon),
min_(min),
max_(max),
batch_size_(1) {}
template <typename input_t, typename temporary_t, typename output_t,
typename scheduler_t>
void operator()(input_t input, temporary_t temporary, output_t output,
std::size_t rows, std::size_t columns,
const scheduler_t& scheduler) const {
const std::size_t cells = rows * columns;
for (std::size_t start_cell = 0; start_cell < cells; start_cell += batch_size_) {
const std::size_t end_cell = std::min(cells, start_cell + batch_size_);
scheduler.schedule([=] (std::size_t worker) {
const std::size_t cells_in_this_batch = end_cell - start_cell;
// Given the fact that the input and output size are identical, and the
// layers is in place, they are guaranteed to be perfectly overlapping.
auto i_data = &input[components::value * start_cell];
array_data_t val(i_data, components::value, cells_in_this_batch);
val = (((val.colwise() - mean_)
.colwise() * fused_gamma_variance_epsilon_)
.colwise() + beta_)
.cwiseMax(type_t(min_)).cwiseMin(type_t(max_));
});
}
scheduler.wait();
}
template <typename input_t, typename temporary_t, typename output_t,
typename scheduler_t>
void optimize_for(input_t input, temporary_t temporary, output_t output,
std::size_t rows, std::size_t columns, const scheduler_t& scheduler) {
const std::size_t cells = rows * columns;
if (scheduler.number_of_workers() == 1) {
batch_size_ = cells;
return;
}
auto best_duration = std::chrono::high_resolution_clock::duration::max();
std::size_t best_batch_size = 1;
auto test_and_maybe_set = [&]() {
for (std::size_t iteration = 0; iteration < 3; ++iteration) {
const auto start = std::chrono::high_resolution_clock::now();
operator()(input, temporary, output, rows, columns, scheduler);
const auto current_duration =
std::chrono::high_resolution_clock::now() - start;
if (current_duration < best_duration) {
best_duration = current_duration;
best_batch_size = batch_size_;
}
}
};
batch_size_ = 1;
while (batch_size_ < cells) {
// Ensure the alignment of the Eigen Array.
if ((batch_size_ * components::value) % alignment_t::type_t_alignment) {
batch_size_ *= 2;
continue;
}
test_and_maybe_set();
batch_size_ *= 2;
}
batch_size_ = cells;
test_and_maybe_set();
batch_size_ = best_batch_size;
}
private:
using alignment_t = alignment<type_t>;
using array_data_t = Eigen::Map<
Eigen::Array<type_t, components::value, Eigen::Dynamic>,
alignment_t::eigen_alignment>;
using array_coefficients_t = Eigen::Map<
const Eigen::Array<type_t, components::value, 1>,
alignment_t::eigen_alignment>;
array_coefficients_t beta_;
array_coefficients_t mean_;
array_coefficients_t fused_gamma_variance_epsilon_;
const type_t min_;
const type_t max_;
std::size_t batch_size_;
};
}
}
}
#endif // POLIMIDL_LAYERS_INTERNAL_BATCH_NORM_RELU_HPP
|
157e132e9623b10c6f9987f70802d611fae2928e | a7c8775a7b813174f651ba72de7124dcfac59418 | /Codigo/monitor_interfaz_estadisticas.h | 693a17cfe15eadcb2c0b94596363d373dd9ecefa | [] | no_license | federicomrossi/7542-tp-final-grupo04 | 4bea0c6186b64c53269cf90fd9a8c2e22ae83cdb | 06b1e358cfc8202747eeda51ded180f4f2207ed6 | refs/heads/master | 2016-09-05T08:55:28.998673 | 2013-06-25T20:02:16 | 2013-06-25T20:02:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 647 | h | monitor_interfaz_estadisticas.h | //
// monitor_interfaz_menuEstadisticas.h
// CLASE MENUESTADISTICAS
//
#ifndef MENUESTADISTICAS_H_
#define MENUESTADISTICAS_H_
#include "gtkmm.h"
#include "monitor_graficador.h"
#include "monitor_monitor.h"
#include "monitor_configuracion.h"
class MenuEstadisticas : public Gtk::Window {
private:
// Atributos de la interfaz
Gtk::Window *main; // Ventana Conexion
// Atributos del modelo
Graficador c;
Monitor *monitor;
public:
// Constructor
MenuEstadisticas(Monitor *monitor);
// Destructor
virtual ~MenuEstadisticas();
// Inicia la ejecución de la ventana
void correr();
};
#endif /* MENUESTADISTICAS_H_ */
|
ca7e0bb741fc8f9d7217335c141c40f7be6f6e81 | a3fdc844b434e2f7546156d705aa9dd07dc14a41 | /C++ How to program/chapter 5/5.13(Bar_Chart)/5.13(Bar_Chart)/main.cpp | ab55a5d1646abeab94279573fe3557ae9659e0bc | [] | no_license | isabuhi/CPlusPlusForProgrammers | b04a6355758331c133fcd269de52849b9374f2fe | 6e3ccb0d41d620bef900d0396e09e60ffdee9781 | refs/heads/main | 2023-07-13T05:46:11.269210 | 2021-08-16T12:02:57 | 2021-08-16T12:02:57 | 363,443,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | cpp | main.cpp | //
// main.cpp
// 5.13(Bar_Chart)
//
// Created by Ibrahimov Sabuhi on 10/19/20.
// Copyright © 2020 Ibrahimov Sabuhi. All rights reserved.
//
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
string a;
for (unsigned x = 1; x <= 5; ++x){
cout << "Enter " << x << "st" << " value: ";
unsigned y = 0;
cin >> y;
for (unsigned x = 1; x <= y; ++x)
a += "*";
string b = "\n";
a += '\n';
}
cout << a << endl;
}
|
6c151bfa840a5aa42b51c48d3c9529a40e0c144c | 271b861c0ec36ba7b7d5871f6fda666718653a11 | /src/fileSaveAs/dialogs/aboutdialog.h | f91b28358c37b7614357d87596dfa3546313813b | [] | no_license | YuanKunfeng/WprFileTools | 2f48137d1cd88bb5d0174636d721efc8e9426631 | dacf92201175e062c33399c80668f83cba98d0dd | refs/heads/master | 2020-03-13T18:08:45.819712 | 2018-04-27T02:38:47 | 2018-04-27T02:38:47 | 131,230,268 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 254 | h | aboutdialog.h | #ifndef ABOUTDIALOG_H
#define ABOUTDIALOG_H
#include <dialogs/shadowdialog.h>
class QPlainTextEdit;
class AboutDialog: public ShadowDialog
{
public:
AboutDialog();
private:
QPlainTextEdit *texteditor;
};
#endif // ABOUTDIALOG_H
|
f48b05ae94293f233146cc0d9e0430dc7778b494 | 83f1eb75810e96cb7bf95a1d7133071786b6c792 | /Source/TurnBasedRPG/Combat/Actions/CombatAction.cpp | 14a50b0cef0ab99f86ec5f8348c35edd697564d2 | [] | no_license | eamonboyle/unreal-turnbased-rpg | 63856c85a83283a10654455327dc52a8dd386a9a | 30cea9f579b34edaad9ac70c6c299fd17d51e2b6 | refs/heads/master | 2022-11-19T05:44:54.343056 | 2020-07-24T15:57:11 | 2020-07-24T15:57:11 | 281,939,663 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 149 | cpp | CombatAction.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "CombatAction.h"
ICombatAction::~ICombatAction()
{
}
|
b0a88d713ebdfdaf870b3f5f6c6ffee7a45cba99 | 3368a3db29d719cacafc2d444345fba1a7da66e6 | /AMPLIFI/physicalConstants.h | bf46bac58c993afff21b3b3ae991458d0b1e7307 | [] | no_license | ningyuliu/AMPLIFI | 31667bf600b09bee5a8eebcdfbdfd4b9e57c9783 | 346735d290c2771e30facd23b3e398ac338dc895 | refs/heads/master | 2023-08-03T09:49:08.866679 | 2023-07-24T09:43:14 | 2023-07-24T09:43:14 | 486,549,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 576 | h | physicalConstants.h | //
// physicalConstants.h
// AMPLIFI
//
// Created by Ningyu Liu on 4/28/22.
//
#ifndef physicalConstants_h
#define physicalConstants_h
// physical constants
#include <cmath>
namespace constants {
const double avogadro = 6.0221367e23; // [molecules / mole]
const double pi = 3.1415926535897932e0; // [radians / 180deg]
const double r = 8.314510e0; // [J/(mol K)] or [m^3*Pa/(mol*K)]
const double k = 1.380657e-23; // [J/K]
const double e = 1.6022e-19;
const double eps0 = 8.8542e-12;
const double c0 = 2.99792458e8;
}
#endif /* physicalConstants_h */
|
0cd637016ce07b2d27c73c0009ee0fcbbba8bf43 | f20e965e19b749e84281cb35baea6787f815f777 | /Online/Online/DailyReport/src/ProblemDB.cpp | 2666384734e354107fae1f3b5ad1555e8ba2fad3 | [] | no_license | marromlam/lhcb-software | f677abc9c6a27aa82a9b68c062eab587e6883906 | f3a80ecab090d9ec1b33e12b987d3d743884dc24 | refs/heads/master | 2020-12-23T15:26:01.606128 | 2016-04-08T15:48:59 | 2016-04-08T15:48:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,748 | cpp | ProblemDB.cpp | // $Id: ProblemDB.cpp,v 1.7 2010-10-18 07:37:58 marcocle Exp $
// Include files
// This file
#include "ProblemDB.h"
// STL
#include <iostream>
// Boost
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/formatters.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/regex.hpp>
//-----------------------------------------------------------------------------
// Implementation file for class : ProblemDB
//
// 2010-03-22 : Olivier Callot
//-----------------------------------------------------------------------------
//=============================================================================
// Standard constructor, initializes variables
//=============================================================================
ProblemDB::ProblemDB( std::string address, std::string port ) {
m_address = address;
m_port = port;
m_monthName.push_back( "Jan" );
m_monthName.push_back( "Feb" );
m_monthName.push_back( "Mar" );
m_monthName.push_back( "Apr" );
m_monthName.push_back( "May" );
m_monthName.push_back( "Jun" );
m_monthName.push_back( "Jul" );
m_monthName.push_back( "Aug" );
m_monthName.push_back( "Sep" );
m_monthName.push_back( "Oct" );
m_monthName.push_back( "Nov" );
m_monthName.push_back( "Dec" );
}
//=============================================================================
// Destructor
//=============================================================================
ProblemDB::~ProblemDB() {}
//=========================================================================
//
//=========================================================================
std::string ProblemDB::urlEncode ( std::string src) {
unsigned char *pd, *p;
std::string str;
str.reserve( 3* src.size() );
pd = (unsigned char *) str.c_str();
p = (unsigned char *) src.c_str();
while ( *p ) {
if (strchr("%&=#?+/", *p) || *p > 127 || *p < 32) {
sprintf((char *) pd, "%%%02X", *p);
pd += 3;
p++;
} else if (*p == ' ') {
*pd++ = '+';
p++;
} else {
*pd++ = *p++;
}
}
*pd = '\0';
str = std::string( str.c_str() );
return str;
}
//=============================================================================
//
//=============================================================================
void ProblemDB::getListOfProblems( std::vector< std::vector< std::string > > &problems ,
const std::string & systemName ) {
boost::asio::ip::tcp::iostream webStream( m_address , m_port ) ;
if ( ! webStream ) {
std::cout << "Cannot open the Problem Database at " << m_address << std::endl ;
return ;
}
/*
webStream << "GET /api/activity/ HTTP/1.0\r\n"
<< "Host:" << m_address << "\r\n"
<< "\r\n" << std::flush ;
*/
std::cout << "** get problems from database **" << std::endl;
webStream << "GET /api/search/?_inline=True&system_visible=True" ;
// Take date of tomorrow to have list of opened problems
boost::posix_time::ptime now =
boost::posix_time::second_clock::local_time() ;
boost::gregorian::date day = now.date() + boost::gregorian::date_duration( 1 ) ;
webStream << "&open_or_closed_gte=" << boost::gregorian::to_iso_extended_string( day )
<< " HTTP/1.0\r\n"
<< "Host:" << m_address << "\r\n"
<< "\r\n" << std::flush ;
std::string line ;
// Check that the web server answers correctly
std::getline( webStream , line ) ;
if ( ! boost::algorithm::find_first( line , "200 OK" ) ) {
std::cerr << "ProblemDB server does not reply" << std::endl ;
std::cout << line << std::endl;
return ;
}
// Parse the web server answers
std::string pattern ;
pattern = "\\N{left-square-bracket}\\N{left-curly-bracket}(.*)" ;
pattern += "\\N{right-curly-bracket}\\N{right-square-bracket}" ;
const boost::regex e( pattern ) ;
std::vector< std::string > single_line ;
boost::property_tree::ptree problem_tree ;
while ( std::getline( webStream , line ) ) {
// Check that the answer has the correct format (JSON format)
if ( boost::regex_match( line , e ) ) {
// Now parse each line (there should be actually only one line
// in the server answer, otherwise it is over-written
std::istringstream is( "{\"problem\":" + line + "}" ) ;
std::cout << line << std::endl;
try {
boost::property_tree::json_parser::read_json( is , problem_tree ) ;
BOOST_FOREACH( boost::property_tree::ptree::value_type &v,
problem_tree.get_child("problem")) {
single_line.clear() ;
std::string systn = v.second.get< std::string >( "system" ) ;
if ( "" != systemName )
if ( systemName.find( systn ) == std::string::npos )
continue ;
single_line.push_back( systn ) ;
single_line.push_back( v.second.get< std::string >( "severity" ) ) ;
std::string date = v.second.get< std::string >( "started_at" );
int yy, mm, dd;
sscanf( date.c_str(), "%4d-%2d-%2d", &yy, &mm, &dd );
char tmp[40];
sprintf( tmp, "%s %d %s", m_monthName[mm-1].c_str(), dd, date.substr(11).c_str() );
date = std::string( tmp );
single_line.push_back( date ) ;
single_line.push_back( v.second.get< std::string >( "id" ) ) ;
single_line.push_back( v.second.get< std::string >( "title" ) ) ;
problems.push_back( single_line ) ;
}
}
catch (...) {
std::cerr << "Error in the problem db server response" << std::endl ;
}
}
}
}
|
6c91669d6507dc9fce75d43cb51d2abd89fc2d47 | 2ced285d3fc55db685d9d6d6bdb73f3098e6e1d7 | /mygames/CrazyTetrisNormal/Classes/RLBlock.h | fd0fedb57f75e2e70c7d1160067e83a413077f79 | [] | no_license | WangXiaoxi/cocos2dx | 57c16a0a5c151a1d97b7b6a057b78c5d8db1ef3c | 1c12095c3d53acac64306bc389d2eb7111708339 | refs/heads/master | 2021-01-22T23:49:03.162750 | 2015-05-13T15:43:53 | 2015-05-13T15:43:53 | 21,501,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | h | RLBlock.h | //
// RLBlock.h
// CrazyTetris
//
// Created by nyist-mac1 on 15/4/8.
//
//
#ifndef __CrazyTetris__RLBlock__
#define __CrazyTetris__RLBlock__
//反L型方块
#include <stdio.h>
#include "BaseBlock.h"
class RLBlock : public BaseBlock
{
public:
bool init();
CREATE_FUNC(RLBlock);
Point getBornPosition();
};
#endif /* defined(__CrazyTetris__RLBlock__) */
|
26b925d452f4affea22952518f567067f088643d | 9b6be8c3f9cdf6a21768f3407ba62e41b6c20b11 | /renderer.h | f25333fde626e3e811a8e6b83479a14707cb7e73 | [] | no_license | noshbar/BridgeBuilder | 69b78ce2c34395c99ab7cd7e68fc021191c330f0 | 63ac4e7e9689239e880dfbfeb09c12613715f104 | refs/heads/master | 2021-01-10T21:16:56.179830 | 2012-08-29T10:57:37 | 2012-08-29T10:57:37 | 5,599,258 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,065 | h | renderer.h | /*
ZLib license:
Copyright (c) 2012 Dirk de la Hunt aka NoshBar @gmail.com
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef __RENDERER_H_
#define __RENDERER_H_
#include <math.h>
#include "SDL/SDL.h"
#include "font_small.h"
#define BPP 32
#define PIXELBUFFER Uint32
#define INTX(x) (int)((x) * scale + halfWidth + offsetX)
#define INTY(y) (int)(screenHeight - ((y) * scale + halfHeight + offsetY))
/* TODO: This should be an abstract base class for other renderers to derive from.
For now, this is a simple renderer with throw-away code that uses SDL for drawing lines and circles.
CAUTION: you shouldn't try to learn anything from this code except the usual "how not to do something". */
class Renderer
{
private:
SDL_Surface *screen;
float scale;
float offsetX;
float offsetY;
int screenWidth;
int screenHeight;
int frameRate;
int halfWidth;
int halfHeight;
protected:
PIXELBUFFER* lock()
{
if (SDL_MUSTLOCK(screen))
{
if (SDL_LockSurface(screen) < 0)
{
printf("Error locking surface: %s\n", SDL_GetError());
abort();
}
}
return (PIXELBUFFER*)screen->pixels;
}
void unlock()
{
SDL_UnlockSurface(screen);
}
public:
Renderer()
{
screen = NULL;
}
~Renderer()
{
Destroy();
}
bool Create(int Width, int Height, int FrameRate)
{
if (SDL_Init(SDL_INIT_VIDEO) < 0)
return Destroy("Could not initialise SDL.");
if ((screen = SDL_SetVideoMode(Width, Height, BPP, 0)) == NULL)
return Destroy("Error setting video mode");
screenWidth = Width;
screenHeight = Height;
frameRate = FrameRate;
halfWidth = Width / 2;
halfHeight = Height / 2;
scale = 10.0f;
offsetX = 0.0f;
offsetY = 0.0f;
return true;
}
bool Destroy(const char *Message = NULL)
{
if (Message != NULL)
printf("Message");
screen = NULL;
return false;
}
int FrameRate()
{
return frameRate;
}
/* This "moves the contents of the game around" on the screen. */
void SetTransform(float OffsetX, float OffsetY, float Scale)
{
offsetX = OffsetX;
offsetY = OffsetY;
scale = Scale;
}
/* This converts a screen co-ordinate to an in-game co-ordinate. */
void ToWorld(float &X, float &Y)
{
X -= halfWidth;
X -= offsetX;
X /= scale;
Y = screenHeight - Y;
Y -= halfHeight;
Y -= offsetY;
Y /= scale;
}
/* This is called at the start of every single game frame.
Use the time to clear the screen, reset view transformations, whatever here. */
void FrameStart()
{
SDL_FillRect(screen, NULL, 0);
}
/* This is called at the end of every single game frame, once everything has been drawn.
Use it to blit the double-buffer to the screen. */
void FrameEnd()
{
SDL_UpdateRect(screen, 0, 0, 0, 0);
}
/* Draws a box centered around X,Y with the dimensions and angle as supplied. */
void Box(float X, float Y, float Width, float Height, float Angle, unsigned long Colour)
{
float cosine = cos(Angle);
float sine = sin(Angle);
float widthCosine = (Width / 2.0f) * cosine;
float heightCosine = (Height / 2.0f) * cosine;
float widthSine = (Width / 2.0f) * sine;
float heightSine = (Height / 2.0f) * sine;
float ulX = X + widthCosine - heightSine;
float ulY = Y + heightCosine + widthSine;
float urX = X - widthCosine - heightSine;
float urY = Y + heightCosine - widthSine;
float blX = X + widthCosine + heightSine;
float blY = Y - heightCosine + widthSine;
float brX = X - widthCosine + heightSine;
float brY = Y - heightCosine - widthSine;
Line(ulX, ulY, urX, urY, Colour);
Line(urX, urY, brX, brY, Colour);
Line(brX, brY, blX, blY, Colour);
Line(blX, blY, ulX, ulY, Colour);
}
/* Draws a line from X0,Y0 to X1,Y1 in the specified Colour using the Bresenham algorithm. */
void Line(float X0, float Y0, float X1, float Y1, unsigned long Colour)
{
int x0 = INTX(X0);
int y0 = INTY(Y0);
int x1 = INTX(X1);
int y1 = INTY(Y1);
/* A rather pessimistic clipping routine that doesn't draw the line at all if any of the points are off-screen.
Would be better if it simply clipped the out of range values. */
if (x0 < 0 || x0 >= screenWidth || x1 < 0 || x1 >= screenWidth || y0 < 0 || y0 >= screenHeight || y1 < 0 || y1 >= screenHeight)
return;
PIXELBUFFER *buffer = lock();
int xinc = 1;
int yinc = screenWidth;
int xspan = x1 - x0 + 1;
int yspan = y1 - y0 + 1;
if (xspan < 0)
{
xinc = -xinc;
xspan = -xspan;
}
if (yspan < 0)
{
yinc = -yinc;
yspan = -yspan;
}
int sum = 0;
int drawpos = screenWidth * y0 + x0;
bool yBigger = (xspan < yspan);
int iMax = yBigger ? yspan : xspan;
int sumInc = yBigger ? xspan : yspan;
int posInc = yBigger ? xinc : yinc;
int compare = yBigger ? yspan : xspan;
int finalPosInc = yBigger ? yinc : xinc;
for (int i = 0; i < iMax; i++)
{
buffer[drawpos] = Colour;
sum += sumInc;
if (sum >= compare)
{
drawpos += posInc;
sum -= compare;
}
drawpos += finalPosInc;
}
unlock();
}
/* Draws a circle around X,Y with the specified Radius in the specified Colour using the Bresenham algorithm. */
void Circle(float X, float Y, float Radius, unsigned long Colour)
{
double cx = INTX(X);
double cy = INTY(Y);
Radius *= scale;
/* A rather pessimistic clipping routine that doesn't draw the circle at all if any of the points are off-screen.
Would be better if it simply clipped the out of range values. */
if (cx - Radius < 0 || cx + Radius >= screenWidth || cy - Radius < 0 || cy + Radius >= screenHeight)
return;
PIXELBUFFER *buffer = lock();
double error = (double)-Radius;
double x = (double)Radius - 0.5;
double y = (double)0.5;
cx = cx - 0.5f;
cy = cy - 0.5f;
while (x >= y)
{
buffer[(int)(cx + x) + ((int)(cy + y) * screenWidth)] = Colour;
buffer[(int)(cx + y) + ((int)(cy + x) * screenWidth)] = Colour;
if (x != 0)
{
buffer[(int)(cx - x) + ((int)(cy + y) * screenWidth)] = Colour;
buffer[(int)(cx + y) + ((int)(cy - x) * screenWidth)] = Colour;
}
if (y != 0)
{
buffer[(int)(cx + x) + ((int)(cy - y) * screenWidth)] = Colour;
buffer[(int)(cx - y) + ((int)(cy + x) * screenWidth)] = Colour;
}
if (x != 0 && y != 0)
{
buffer[(int)(cx - x) + ((int)(cy - y) * screenWidth)] = Colour;
buffer[(int)(cx - y) + ((int)(cy - x) * screenWidth)] = Colour;
}
error += y;
++y;
error += y;
if (error >= 0)
{
--x;
error -= x;
error -= x;
}
}
unlock();
}
void Text(int X, int Y, const char *String, unsigned long Colour)
{
if (screen == NULL || String == NULL)
return;
PIXELBUFFER *buffer = lock();
for (int index = 0; index < strlen(String); index++)
{
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 7; y++)
{
if ((SmallFont[String[index] - 32][x] & (1 << y)) != 0)
buffer[(X + x) + ((Y + y) * screenWidth)] = Colour;
}
}
X += 6;
}
unlock();
}
};
#endif
|
e22cdc163bca76ff16ca8041fcd92b80d39d2322 | 95efaa256914926ac30acbb1a8c89c320c19bf40 | /HeCommunicate/HUsbPortCy.h | 1b00c9786421e7d2c21923ea133f51921d0e7149 | [] | no_license | mabo0001/QtCode | bc2d80446a160d97b4034fa1c068324ba939cb20 | 9038f05da33c870c1e9808791f03467dcc19a4ab | refs/heads/master | 2022-08-26T13:36:14.021944 | 2019-07-15T01:12:51 | 2019-07-15T01:12:51 | 266,298,758 | 1 | 0 | null | 2020-05-23T08:54:08 | 2020-05-23T08:54:07 | null | UTF-8 | C++ | false | false | 884 | h | HUsbPortCy.h | /***************************************************************************************************
** 2018-06-19 HUsbPortCy USB端口类。
***************************************************************************************************/
#ifndef HUSBPORTCY_H
#define HUSBPORTCY_H
#include "HAbstractPort.h"
HE_COMMUNICATE_BEGIN_NAMESPACE
class HUsbPortCyPrivate;
class HUsbPortCy : public HAbstractPort
{
Q_DECLARE_PRIVATE(HUsbPortCy)
public:
explicit HUsbPortCy();
~HUsbPortCy() override;
public:
QString typeName() override;
protected:
HUsbPortCy(HUsbPortCyPrivate &);
protected:
HErrorType openPort(int portNum) override;
HErrorType closePort() override;
HErrorType writeData(uchar *data, int maxSize) override;
HErrorType readData(uchar *data, int maxSize) override;
};
HE_COMMUNICATE_END_NAMESPACE
#endif // HUSBPORTCY_H
|
dc2c99098427824f8f49179d77dc0971e13d1da1 | 794a33380605dceb39a3e67daf7e9f6c8bdf5466 | /Instance.cpp | be57c205d904fbcb0eaa2c701d97d64b419fadef | [] | no_license | rafael-colares/FlexOptim2 | 70e9782fa5fa1af594aa79c59880f10072f06292 | b13cbd47f41a1e6ef538d781fe3d4f5334ca7141 | refs/heads/master | 2022-05-18T22:18:25.468495 | 2020-04-28T19:34:42 | 2020-04-28T19:34:42 | 259,702,652 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,143 | cpp | Instance.cpp | #include "Instance.h"
/************************************************/
/* Constructors */
/************************************************/
/* Constructor initializes the object with the information of an Input. */
Instance::Instance(const Input &i) : input(i){
this->setNbNodes(0);
}
/* Copy constructor. */
Instance::Instance(const Instance &i) : input(i.getInput()){
this->setNbNodes(i.getNbNodes());
this->setTabEdge(i.getTabEdge());
this->setTabDemand(i.getTabDemand());
}
/************************************************/
/* Methods */
/************************************************/
/* Returns the number of demands already routed. */
int Instance::getNbRoutedDemands() const{
int counter = 0;
for(int i = 0; i < getNbDemands(); i++){
if (tabDemand[i].isRouted() == true){
counter++;
}
}
return counter;
}
/* Returns the vector of demands to be routed in the next optimization. */
std::vector<Demand> Instance::getNextDemands() const {
std::vector<Demand> toBeRouted;
for(int i = 0; i < getNbDemands(); i++){
if( (tabDemand[i].isRouted() == false) && ((int)toBeRouted.size() < getInput().getNbDemandsAtOnce()) ){
toBeRouted.push_back(tabDemand[i]);
}
}
return toBeRouted;
}
/* Changes the attributes of the PhysicalLink from the given index according to the attributes of the given link. */
void Instance::setEdgeFromId(int id, PhysicalLink & edge){
this->tabEdge[id].copyPhysicalLink(edge);
}
/* Changes the attributes of the Demand from the given index according to the attributes of the given demand. */
void Instance::setDemandFromId(int id, Demand & demand){
this->tabDemand[id].copyDemand(demand);
}
/* Builds the initial mapping based on the information retrived from the Input. */
void Instance::createInitialMapping(){
readTopology();
readDemands();
readDemandAssignment();
setNbInitialDemands(getNbRoutedDemands());
}
/* Reads the topology information from file. */
void Instance::readTopology(){
std::cout << "Reading " << input.getLinkFile() << " ..." << std::endl;
CSVReader reader(input.getLinkFile());
/* dataList is a vector of vectors of strings. */
/* dataList[0] corresponds to the first line of the document and dataList[0][i] to the i-th word.*/
std::vector<std::vector<std::string> > dataList = reader.getData();
int numberOfLines = (int)dataList.size();
// The number of nodes is given by the max index of sources and targets
int maxNode = 0;
//skip the first line (headers)
// edges and nodes id starts on 1 in the input files. In this program ids will be in the range [0,n-1]!
for (int i = 1; i < numberOfLines; i++) {
int idEdge = std::stoi(dataList[i][0]) - 1;
int edgeSource = std::stoi(dataList[i][1]) - 1;
int edgeTarget = std::stoi(dataList[i][2]) - 1;
double edgeLength = std::stod(dataList[i][3]);
int edgeNbSlices = std::stoi(dataList[i][4]);
double edgeCost = std::stod(dataList[i][5]);
PhysicalLink edge(idEdge, edgeSource, edgeTarget, edgeLength, edgeNbSlices, edgeCost);
this->tabEdge.push_back(edge);
if (edgeSource > maxNode) {
maxNode = edgeSource;
}
if (edgeTarget > maxNode) {
maxNode = edgeTarget;
}
std::cout << "Creating edge ";
edge.displayPhysicalLink();
}
this->setNbNodes(maxNode+1);
}
/* Reads the routed demand information from file. */
void Instance::readDemands(){
std::cout << "Reading " << input.getDemandFile() << " ..." << std::endl;
CSVReader reader(input.getDemandFile());
/* dataList is a vector of vectors of strings. */
/* dataList[0] corresponds to the first line of the document and dataList[0][i] to the i-th word.*/
std::vector<std::vector<std::string> > dataList = reader.getData();
int numberOfLines = (int)dataList.size();
//skip the first line (headers)
for (int i = 1; i < numberOfLines; i++) {
int idDemand = std::stoi(dataList[i][0]) - 1;
int demandSource = std::stoi(dataList[i][1]) - 1;
int demandTarget = std::stoi(dataList[i][2]) - 1;
int demandLoad = std::stoi(dataList[i][3]);
double DemandMaxLength = std::stod(dataList[i][4]);
Demand demand(idDemand, demandSource, demandTarget, demandLoad, DemandMaxLength, false);
this->tabDemand.push_back(demand);
}
}
/* Reads the assignment information from file. */
void Instance::readDemandAssignment(){
CSVReader reader(input.getAssignmentFile());
std::cout << "Reading " << input.getAssignmentFile() << " ..." << std::endl;
/* dataList is a vector of vectors of strings. */
/* dataList[0] corresponds to the first line of the document and dataList[0][0] to the first word.*/
std::vector<std::vector<std::string> > dataList = reader.getData();
int numberOfColumns = (int)dataList[0].size();
int numberOfLines = (int)dataList.size();
//check if the demands in this file are the same as the ones read in Demand.csv
//skip the first word (headers) and the last one (empty)
for (int i = 1; i < numberOfColumns-1; i++) {
int demandId = stoi(getInBetweenString(dataList[0][i], "_", "=")) - 1;
std::string demandStr = getInBetweenString(dataList[0][i], "(", ")");
std::vector<std::string> demand = splitBy(demandStr, ",");
int demandSource = std::stoi(demand[0]) - 1;
int demandTarget = std::stoi(demand[1]) - 1;
int demandLoad = std::stoi(demand[2]);
this->tabDemand[demandId].checkDemand(demandId, demandSource, demandTarget, demandLoad);
}
std::cout << "Checking done." << std::endl;
//search for slice allocation line
for (int alloc = 0; alloc < numberOfLines; alloc++) {
if (dataList[alloc][0].find("slice allocation") != std::string::npos) {
// for each demand
for (int d = 0; d < this->getNbDemands(); d++) {
int demandMaxSlice = std::stoi(dataList[alloc][d+1]) - 1;
this->tabDemand[d].setRouted(true);
this->tabDemand[d].setSliceAllocation(demandMaxSlice);
// look for which edges the demand is routed
for (int i = 0; i < this->getNbEdges(); i++) {
if (dataList[i+1][d+1] == "1") {
this->tabEdge[i].assignSlices(this->tabDemand[d], demandMaxSlice);
}
}
}
}
}
}
/* Displays overall information about the current instance. */
void Instance::displayInstance() {
std::cout << "**********************************" << std::endl;
std::cout << "* Constructed Instance *" << std::endl;
std::cout << "**********************************" << std::endl;
std::cout << "Number of nodes : " << this->getNbNodes() << std::endl;
std::cout << "Number of edges : " << this->getNbEdges() << std::endl;
displayTopology();
displaySlices();
displayRoutedDemands();
}
/* Displays information about the physical topology. */
void Instance::displayTopology(){
std::cout << std::endl << "--- The Physical Topology ---" << std::endl;
for (int i = 0; i < this->getNbEdges(); i++) {
tabEdge[i].displayPhysicalLink();
}
std::cout << std::endl;
}
/* Displays detailed information about state of the physical topology. */
void Instance::displayDetailedTopology(){
std::cout << std::endl << "--- The Detailed Physical Topology ---" << std::endl;
for (int i = 0; i < this->getNbEdges(); i++) {
tabEdge[i].displayDetailedPhysicalLink();
}
std::cout << std::endl;
}
/* Displays summarized information about slice occupation of each PhysicalLink. */
void Instance::displaySlices() {
std::cout << std::endl << "--- Slice occupation ---" << std::endl;
for (int i = 0; i < this->getNbEdges(); i++) {
std::cout << "#" << i+1 << ". ";
tabEdge[i].displaySlices();
}
std::cout << std::endl;
}
/* Displays information about the routed demands. */
void Instance::displayRoutedDemands(){
std::cout << std::endl << "--- The Routed Demands ---" << std::endl;
for (int i = 0; i < this->getNbDemands(); i++) {
if (tabDemand[i].isRouted()) {
tabDemand[i].displayDemand();
}
}
std::cout << std::endl;
}
/* Adds non-routed demands to the pool by reading the information from onlineDemands Input file. */
void Instance::generateRandomDemandsFromFile(std::string filePath){
std::cout << "Reading " << filePath << " ..." << std::endl;
CSVReader reader(filePath);
/* dataList is a vector of vectors of strings. */
/* dataList[0] corresponds to the first line of the document and dataList[0][i] to the i-th word.*/
std::vector<std::vector<std::string> > dataList = reader.getData();
int numberOfLines = (int)dataList.size();
//skip the first line (headers)
for (int i = 1; i < numberOfLines; i++) {
int idDemand = std::stoi(dataList[i][0]) - 1 + getNbRoutedDemands();
int demandSource = std::stoi(dataList[i][1]) - 1;
int demandTarget = std::stoi(dataList[i][2]) - 1;
int demandLoad = std::stoi(dataList[i][3]);
double DemandMaxLength = std::stod(dataList[i][4]);
Demand demand(idDemand, demandSource, demandTarget, demandLoad, DemandMaxLength, false);
this->tabDemand.push_back(demand);
}
}
/* Adds non-routed demands to the pool by generating N random demands. */
void Instance::generateRandomDemands(const int N){
srand (1234567890);
for (int i = 0; i < N; i++){
int idDemand = i + getNbRoutedDemands();
int demandSource = rand() % getNbNodes();
int demandTarget = rand() % getNbNodes();
while (demandTarget == demandSource){
demandTarget = rand() % getNbNodes();
}
int demandLoad = 3;
double DemandMaxLength = 3000;
Demand demand(idDemand, demandSource, demandTarget, demandLoad, DemandMaxLength, false);
this->tabDemand.push_back(demand);
}
}
/* Verifies if there is enough place for a given demand to be routed through link i on last slice position s. */
bool Instance::hasEnoughSpace(const int i, const int s, const Demand &demand){
// std::cout << "Calling hasEnoughSpace..." << std::endl;
const int LOAD = demand.getLoad();
int firstPosition = s - LOAD + 1;
if (firstPosition < 0){
return false;
}
for (int pos = firstPosition; pos <= s; pos++){
if (getPhysicalLinkFromId(i).getSlice_i(pos).isUsed() == true){
return false;
}
}
// std::cout << "Called hasEnoughSpace." << std::endl;
return true;
}
/* Assigns the given demand to the j-th slice of the i-th link. */
void Instance::assignSlicesOfLink(int linkLabel, int slice, const Demand &demand){
this->tabEdge[linkLabel].assignSlices(demand, slice);
this->tabDemand[demand.getId()].setRouted(true);
this->tabDemand[demand.getId()].setSliceAllocation(slice);
}
/* Displays information about the non-routed demands. */
void Instance::displayNonRoutedDemands(){
std::cout << std::endl << "--- The Non Routed Demands ---" << std::endl;
for (int i = 0; i < this->getNbDemands(); i++) {
if (tabDemand[i].isRouted() == false) {
tabDemand[i].displayDemand();
}
}
std::cout << std::endl;
}
/* Call the methods allowing the build of output files. */
void Instance::output(std::string i){
std::cout << "Output " << i << std::endl;
outputEdgeSliceHols(i);
//outputDemand();
outputDemandEdgeSlices(i);
}
/* Builds file Demand_edges_slices.csv containing information about the assignment of routed demands. */
void Instance::outputDemandEdgeSlices(std::string counter){
std::string delimiter = ";";
std::string filePath = this->input.getOutputPath() + "Demand_edges_slices_" + counter + ".csv";
std::ofstream myfile(filePath.c_str(), std::ios::out | std::ios::trunc);
if (myfile.is_open()){
myfile << "edge_slice_demand" << delimiter;
for (int i = 0; i < getNbDemands(); i++){
if (getDemandFromIndex(i).isRouted()){
myfile << "k_" << getDemandFromIndex(i).getId()+1 << "= " << getDemandFromIndex(i).getString() << delimiter;
}
}
myfile << "\n";
for (int e = 0; e < getNbEdges(); e++){
myfile << getPhysicalLinkFromId(e).getString() << delimiter;
for (int i = 0; i < getNbDemands(); i++){
if (getDemandFromIndex(i).isRouted()){
// if demand is routed through edge: 1
if (getPhysicalLinkFromId(e).contains(getDemandFromIndex(i)) == true){
myfile << "1" << delimiter;
}
else{
myfile << " " << delimiter;
}
}
}
myfile << "\n";
}
myfile << " slice allocation " << delimiter;
for (int i = 0; i < getNbDemands(); i++){
if (getDemandFromIndex(i).isRouted()){
myfile << getDemandFromIndex(i).getSliceAllocation()+1 << delimiter;
}
}
myfile << "\n";
}
}
/* Builds file Demand.csv containing information about the routed demands. */
void Instance::outputDemand(){
std::string delimiter = ";";
std::string filePath = this->input.getOutputPath() + "Demand" + ".csv";
std::ofstream myfile(filePath.c_str(), std::ios::out | std::ios::trunc);
if (myfile.is_open()){
myfile << "index" << delimiter;
myfile << "origin" << delimiter;
myfile << "destination" << delimiter;
myfile << "slots" << delimiter;
myfile << "max_length" << "\n";
for (int i = 0; i < getNbDemands(); i++){
if (getDemandFromIndex(i).isRouted()){
myfile << std::to_string(getDemandFromIndex(i).getId()+1) << delimiter;
myfile << std::to_string(getDemandFromIndex(i).getSource()+1) << delimiter;
myfile << std::to_string(getDemandFromIndex(i).getTarget()+1) << delimiter;
myfile << std::to_string(getDemandFromIndex(i).getLoad()) << delimiter;
myfile << std::to_string(getDemandFromIndex(i).getMaxLength()) << "\n";
}
}
}
}
/* Builds file Edge_Slice_Holes_i.csv containing information about the mapping after n optimizations. */
void Instance::outputEdgeSliceHols(std::string counter){
std::cout << "Output EdgeSliceHols: " << counter << std::endl;
std::string delimiter = ";";
std::string filePath = this->input.getOutputPath() + "Edge_Slice_Holes_" + counter + ".csv";
std::ofstream myfile(filePath.c_str(), std::ios::out | std::ios::trunc);
if (myfile.is_open()){
myfile << " Slice-Edge " << delimiter;
for (int i = 0; i < getNbEdges(); i++){
std::string edge = "e_" + std::to_string(i+1);
myfile << edge << delimiter;
}
myfile << "\n";
for (int s = 0; s < input.getnbSlicesInOutputFile(); s++){
std::string slice = "s_" + std::to_string(s+1);
myfile << slice << delimiter;
for (int i = 0; i < getNbEdges(); i++){
if (s < getPhysicalLinkFromId(i).getNbSlices() && getPhysicalLinkFromId(i).getSlice_i(s).isUsed() == true){
myfile << "1" << delimiter;
}
else{
myfile << "0" << delimiter;
}
}
myfile << "\n";
}
myfile << "Nb_New_Demands:" << delimiter << getNbRoutedDemands() - getNbInitialDemands() << "\n";
}
else{
std::cerr << "Unable to open file.\n";
}
myfile.close();
}
/* Builds file results.csv containing information about the main obtained results. */
void Instance::outputLogResults(std::string fileName){
std::string delimiter = ";";
std::string filePath = this->input.getOutputPath() + "results.csv";
std::ofstream myfile(filePath.c_str(), std::ios_base::app);
if (myfile.is_open()){
myfile << fileName << delimiter;
int nbRouted = getNbRoutedDemands();
myfile << nbRouted - getNbInitialDemands() << delimiter;
myfile << nbRouted << "\n";
}
}
/* Verifies if there exists a link between nodes of id u and v. */
bool Instance::hasLink(int u, int v){
for (unsigned int e = 0; e < tabEdge.size(); e++){
if ((tabEdge[e].getSource() == u) && (tabEdge[e].getTarget() == v)){
return true;
}
if ((tabEdge[e].getSource() == v) && (tabEdge[e].getTarget() == u)){
return true;
}
}
return false;
}
/* Returns the first PhysicalLink with source s and target t. */
PhysicalLink Instance::getPhysicalLinkBetween(int u, int v){
for (unsigned int e = 0; e < tabEdge.size(); e++){
if ((tabEdge[e].getSource() == u) && (tabEdge[e].getTarget() == v)){
return tabEdge[e];
}
if ((tabEdge[e].getSource() == v) && (tabEdge[e].getTarget() == u)){
return tabEdge[e];
}
}
std::cerr << "Did not found a link between " << u << " and " << v << "!!\n";
exit(0);
PhysicalLink link(-1,-1,-1);
return link;
} |
1a5ccb49bdb8900b83dedb4504f208c28bd2c794 | a1ec5bebba85ff986f00d447cee2644b29c5994b | /Laborator6-7Full/Controller.h | 5bb2c29ca8868fec8e789905d87d3a0174044eb7 | [] | no_license | LauraDiosan-CS/lab5-6-template-stl-MarianGSM | 36b6a963c48dc7e1f5cb58938f03024ad95a1056 | 7a3ed147fd8ccbf38de16f78796d9f4734bb5857 | refs/heads/master | 2021-05-25T17:30:23.018501 | 2020-04-07T16:09:49 | 2020-04-07T16:09:49 | 253,845,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | h | Controller.h | #pragma once
#include "pch.h"
#include <iostream>
#include "Repo.h"
#include "Dulciuri.h"
#include "Moneda.h"
using namespace std;
class Ctrl {
private:
RepoT<Dulciuri, 10> r1; //repo de dulciuri
RepoT<Moneda, 10> r2; //repo de monezi
public:
Ctrl(); //constructor
Ctrl(RepoT<Dulciuri, 10> a, RepoT<Moneda, 10> b);//constructor cu parametri
Ctrl(const Ctrl& c); // constructor de copiere
~Ctrl(); //destructor
Ctrl& operator=(const Ctrl& c);
int searchD(Dulciuri d); //cauta dulce
int searchM(Moneda m); //cauta moneda
void eliminaD(Dulciuri d); //elimina dulce
void eliminaM(Moneda m); //elimina moneda
//void updateD(char* n, int c,int p,int poz);
//void updateM(int v, int n, int poz);
void addD(Dulciuri d); //adauga dulce
void addM(Moneda m); //adauga moneda
void cumpara(Dulciuri d, int lei); //cumpara dulce
//char* toString();
void setMonede(RepoT<Moneda, 10> aux);
void setDulciuri(RepoT<Dulciuri, 10> aux);
};
|
d7ddee05efe3bf6ab952651eb934ead6b1703263 | bd6156f4844b860d47b6e50e7a4d7021cdc0ce02 | /qt4/prova/tdpalio/TrattaList.h | f204f22b456308846b9148f3b82e6c6dd3f6e3b3 | [] | no_license | matteosan1/workspace | e178c9843e62d78762420c217bc603819dc96b10 | f9a2dedfb821b889d037f7642fa5e2cb581b4779 | refs/heads/master | 2021-07-20T04:26:40.187162 | 2021-06-24T20:13:46 | 2021-06-24T20:13:46 | 149,867,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 816 | h | TrattaList.h | #ifndef TRATTALIST_H
#define TRATTALIST_H
#include "cavallo.h"
#include <QAbstractTableModel>
#include <QVector>
using namespace std;
class TrattaList : public QAbstractTableModel {
Q_OBJECT
public:
TrattaList(QVector<Cavallo>* c, QObject *parent = 0)
: QAbstractTableModel(parent), cavalli(c) {
for(int i=0; i<21; ++i)
selezione.insert(i, 0);
}
int columnCount(const QModelIndex &parent = QModelIndex()) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
private:
QVector<Cavallo>* cavalli;
QVector<int> selezione;
};
#endif
|
7a9dd9f8ab62e73dbe85d0c02cc5c23c70c3cdc2 | 208650de138a6b05b8b8e7e4ca6df9dc72290402 | /Problems/Practice/C/10.cpp | 64c98c4bb88a42d23d3938d5feb94c05d45946b2 | [] | no_license | cs15b047/CF | 9fcf83c5fd09124b6eaebbd4ecd67d19a1302582 | d220d73a2d8739bbb10f4ed71437c06625870490 | refs/heads/master | 2021-08-20T06:21:24.577260 | 2021-06-09T04:56:47 | 2021-06-09T04:57:29 | 177,541,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | cpp | 10.cpp | #include <bits/stdc++.h>
using namespace std ;
typedef long long int ll ;
int main(int argc, char const *argv[])
{
int n,m;cin>>n>>m ;
vector<ll> a(n),inc(n),dec(n);
for(int i=0;i<n;i++)cin>>a[i] ;
int j = 0;
while(j < n){
int strt = j ;
while(j < n-1 && a[j] <= a[j+1])j++;
int tmp = j ;
while(tmp >= strt){
inc[tmp] = j - tmp + 1 ;
tmp--;
}
j++;
}
j=0;
while(j < n){
int strt = j ;
while(j < n-1 && a[j] >= a[j+1])j++;
int tmp = j ;
while(tmp >= strt){
dec[tmp] = j - tmp + 1 ;
tmp--;
}
j++;
}
for (int i = 0; i < m; ++i)
{
ll l,r;cin>>l>>r;l--;r--;
if(l + inc[l] - 1 >= r)cout << "Yes"<<endl ;
else{
int mid = l + inc[l] - 1;
if(mid + dec[mid] - 1 >= r)cout << "Yes"<<endl ;
else cout << "No"<<endl ;
}
}
return 0;
} |
b8335c7844d28a1f714fbf8cf2f7e28ce46ae52b | ec6adf318f4a8c0b66cfb1808cd095d0e62f1b61 | /Pool.h | 1dd104b113001a3628c04803e43dee0e9c6c9cbb | [] | no_license | xaviperez/qss | ea676f192a19456c2890bc3eef5782ffedcad3de | 5b0034fec2d360df96ea9c0e0546f30ed64372cc | refs/heads/master | 2022-12-12T05:04:52.921763 | 2020-09-07T13:57:27 | 2020-09-07T13:57:27 | 287,790,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | h | Pool.h | #pragma once
#include <vector>
#include "GameObject.h"
class Pool {
public:
~Pool();
void Add(GameObject* object);
GameObject* Get();
private:
std::vector<GameObject*> _objects = {};
int _length = 0;
int _current = 0;
}; |
4d73e52de2bef8ca09d9a82c8338610a9cdae26a | 590eb4cc4d0fe83d9740ce478f857ca3a98e7dae | /OGDF/test/include/bandit/skip_policies/skip_policy.h | ca606dfbe9b6d75de009e0cdcb7b20c2f49c8ad2 | [
"MIT",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"GPL-1.0-or-later",
"EPL-1.0",
"GPL-2.0-only",
"LicenseRef-scancode-generic-exception",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | cerebis/MetaCarvel | d0ca77645e9a964e349144974a05e17fa48c6e99 | a047290e88769773d43e0a9f877a88c2a8df89d5 | refs/heads/master | 2020-12-05T05:40:19.460644 | 2020-01-06T05:38:34 | 2020-01-06T05:38:34 | 232,023,146 | 0 | 0 | MIT | 2020-01-06T04:22:00 | 2020-01-06T04:21:59 | null | UTF-8 | C++ | false | false | 474 | h | skip_policy.h | #ifndef BANDIT_SKIP_POLICY_H
#define BANDIT_SKIP_POLICY_H
namespace bandit {
struct skip_policy
{
virtual bool should_skip(const char* name) const = 0;
};
typedef std::unique_ptr<skip_policy> skip_policy_ptr;
namespace detail {
inline skip_policy& registered_skip_policy(skip_policy* policy = NULL)
{
static struct skip_policy* policy_;
if(policy)
{
policy_ = policy;
}
return *policy_;
}
}
}
#endif
|
832ea4c3d9752024421028a7878953b6ef2320ed | 4dcb4f3a7f54097220049a47ccdb6a5b131faaa5 | /subdivide.cpp | d91df7c2c081d6cfefb7890f3cdfa90b7b4db269 | [] | no_license | kanes115/Subdivision | ba9d4fa8e491e1f038dafb44ff271a0963711791 | e82210e600da2e0f7ea2db64413f9b6f5b037f06 | refs/heads/master | 2020-12-04T02:37:52.268231 | 2020-01-03T12:01:41 | 2020-01-03T12:01:41 | 231,574,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,325 | cpp | subdivide.cpp | #include <CGAL/Simple_cartesian.h>
#include <CGAL/Surface_mesh.h>
#include <CGAL/boost/graph/graph_traits_Surface_mesh.h>
#include <CGAL/subdivision_method_3.h>
#include <CGAL/Timer.h>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <fstream>
typedef CGAL::Simple_cartesian<double> Kernel;
typedef CGAL::Surface_mesh<Kernel::Point_3> PolygonMesh;
using namespace std;
using namespace CGAL;
namespace params = CGAL::parameters;
std::string getMeshDetails(PolygonMesh mesh) {
return "" + std::to_string(mesh.number_of_vertices()) + ";" + std::to_string(mesh.number_of_faces()) + ";" + std::to_string(mesh.number_of_edges());
}
void doSubdivision(PolygonMesh pmesh, std::string method, int d) {
auto out_file = method + "_result.off";
Timer t;
t.start();
if(method.compare("Catmull"))
Subdivision_method_3::CatmullClark_subdivision(pmesh, params::number_of_iterations(d));
else if(method.compare("DooSabin"))
Subdivision_method_3::DooSabin_subdivision(pmesh, params::number_of_iterations(d));
else if(method.compare("Loop"))
Subdivision_method_3::Loop_subdivision(pmesh, params::number_of_iterations(d));
else if(method.compare("Sqrt3"))
Subdivision_method_3::Sqrt3_subdivision(pmesh, params::number_of_iterations(d));
else {
std::cerr << "Unknown method" << std::endl;
return;
}
auto time = t.time();
std::ofstream out(out_file);
out << pmesh;
auto mesh_details = getMeshDetails(pmesh);
std::cout << method << ";" << d << ";" << time * 1000 << ";" << mesh_details << std::endl;
}
int main(int argc, char** argv) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " d filename_in \n";
cerr << " d -- the depth of the subdivision \n";
cerr << " filename_in -- the input mesh (.off) \n";
cerr << endl;
return 1;
}
int d = boost::lexical_cast<int>(argv[1]);
const char* in_file = argv[2];
PolygonMesh pmesh;
std::ifstream in(in_file);
if(in.fail()) {
std::cerr << "Could not open input file " << in_file << std::endl;
return 1;
}
in >> pmesh;
std::cout << "method;#iterations;time;#vertices;#faces;#edges" << endl;
doSubdivision(pmesh, "Catmull", d);
doSubdivision(pmesh, "DooSabin", d);
doSubdivision(pmesh, "Loop", d);
doSubdivision(pmesh, "Sqrt3", d);
return 0;
}
|
f806746361433017b14d189b960b3f5a64af9179 | 6dacb8f59751c9647685d4b931b2cbef00fcd302 | /PepLectures/Lec02_28-Jan/gcd.cpp | 58bbc6300d50c761f89b907a47a1e4f458778105 | [] | no_license | sudhanshu-t/DSA | 88662429514509c3a063d7610db3d32a6854c5c0 | 042fad26085405f77f159eb08c53555de9fb7732 | refs/heads/master | 2021-07-19T15:26:34.310444 | 2020-07-09T11:59:41 | 2020-07-09T11:59:41 | 278,350,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | cpp | gcd.cpp | #include<iostream>
using namespace std;
int main(){
int n1, n2;
cin>>n1>>n2;
int div = n1;
int divi = n2;
int rem = divi % div;
while(rem != 0){
divi = div;
div = rem;
rem = divi % div;
}
cout<<div<<endl;
} |
9533dadf9fcb9d6a16ce9b84e5f187e10f8dd3cc | 5a1a847b1225f94676a319cae8e4b792a7963b28 | /5. ARRAYS/PRACTICE Exam/PRACTICE Exam/Ex3.cpp | ad1c9cf6ff4174c5afb42ea5cabc3becb5fdaa39 | [] | no_license | Gromeu2000/Programming1 | 39c7a24e98e433f4f0d8c6fd939a70dd209f662d | 255ffd3d293e5587ef4306f352f967b271e9f440 | refs/heads/master | 2020-04-07T12:59:37.677153 | 2019-01-09T16:39:02 | 2019-01-09T16:39:02 | 158,388,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 320 | cpp | Ex3.cpp | #include <stdio.h>
#include <stdlib.h>
#include "Ex1.h"
#include "Ex2.h"
void sumArray(int array[5], int size) {
printf("Expected Output: ");
int sum = 0;
for (int i = 0; i <= size; i++) {
sum += array[i];
}
printf("%d\n", sum);
}
void exercise3(int array[5]) {
askArray(array, 5);
sumArray(array, 5);
} |
84df3a8804ca2aaf30362b33a25516606b897633 | 41b34b93ece0d67b664db5be7641c99897604b97 | /1/1.cpp | d9de795874c96b2d46484c8d006f64d1324993d9 | [] | no_license | justtima/Modeling | 3753220e0d76fe860960f0768b42ea36707eee12 | 0b2b4c883c18b75a316efce29e1ec95107873a9d | refs/heads/master | 2022-11-29T21:25:24.505318 | 2017-05-01T12:30:58 | 2017-05-01T12:30:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,430 | cpp | 1.cpp | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <cmath>
#include <string>
#include <string.h>
#include <fstream>
#include <vector>
#define pi 3.14
using namespace std;
/* Метод отбраковки */
float methodReject() {
float a = 0, b = pi, c = 1, x1, x2;
do {
x1 = (float) rand() / RAND_MAX;
x2 = (float) rand() / RAND_MAX;
} while (sinf(a + (b - a) * x1) < c * x2);
/*x2 *= c;
x1 = a + (b - a) * x1;*/
return a + (b - a) * x1;
}
/* Распределение без повторений */
void A_(int n, int nexp, string& fname) {
vector<int> nums, temp;
int it, k = 3 * n / 4, mas[n], part = nexp / k + 1;
float p;
memset(mas, 0, sizeof(int) * n);
for(int i = 0; i < n; i++)
temp.push_back(i);
for(int j = 0; j < part; j++) {
nums = temp;
if (j == part - 1) k = nexp % k;
for(int i = 0; i < k; i++) {
p = 1.0 / (n - i);
it = (float) rand() / RAND_MAX / p;
++mas[nums[it]];
nums.erase(nums.begin() + it);
}
}
FILE *fp = fopen(fname.c_str(), "w");
for(int i = 0; i < n; i++) {
fprintf(fp, "%d\t%.4f\n", i, (float) mas[i] / nexp);
}
fclose(fp);
}
/* Распределение с повторением */
void A(int n, int nexp, string& fname) {
float p = 1, intervals[n], x, sum;
int mas[n];
memset(mas, 0, sizeof(int) * n);
for(int i = 0; i < n - 1; i++) {
intervals[i] = abs(remainder((float) rand() / RAND_MAX, p));
p -= intervals[i];
//printf("%.6f ", intervals[i]);
}
intervals[n - 1] = p;
printf("%.6f\n", p);
for(int i = 0; i < nexp; i++) {
x = (float) rand() / RAND_MAX;
sum = 0;
for (int j = 0; j < n; j++) {
sum += intervals[j];
if (x < sum) {
++mas[j];
break;
}
}
}
FILE *fp = fopen(fname.c_str(), "w");
for(int i = 0; i < n; i++) {
fprintf(fp, "%d\t%.4f\t%.4f\n", i, intervals[i], (float) mas[i] / nexp);
}
fclose(fp);
}
void testMethodRej(int n, int m, const char *fname) {
float x;
int mas[n];
FILE *fp = fopen(fname, "w");
memset(mas, 0, sizeof(int) * n);
for (int i = 0; i < m; i++) {
x = methodReject();
++mas[(int)(x / pi * n)];
}
for (int i = 0; i < n; i++) {
fprintf(fp, "%d\t%d\n", i, mas[i]);
}
fprintf(fp, "%d\n", n);
}
int main(int argc, char const *argv[])
{
string s[3] = {"out_A", "out_A_", "out_rej"};
srand(time(NULL));
A_(10, 10000, s[1]);
A(10, 10000, s[0]);
testMethodRej(40, 100000, s[2].c_str());
return 0;
}
|
141f1cb680a4d615936aed48872f6c7ab4f30650 | 919ebcde163f1715b497e8c2c74d8e0f9c36c7e1 | /47/Project1/Project1/Source.cpp | ae9562236792f0411edf8fd43a12191fe2bd2f61 | [] | no_license | ltoanh/BasicCppExe | 3c35a1b6efe085a934fbfacdc8f9ebaf51c6e2a4 | 5f7d1bb90b58b079501b96239f5296b95048c5ef | refs/heads/master | 2023-01-21T20:33:37.297667 | 2020-02-09T14:08:44 | 2020-02-09T14:08:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | Source.cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<fstream>
using namespace std;
#define fin cin
#define fout cout
int main() {
int t, n, d;
// ifstream fin("47.txt", ios::in);
// ofstream fout("47.out", ios::out);
fin >> t;
while (t--) {
fin >> n >> d;
vector<int> a;
for (int i = 0; i < n; ++i) {
int x;
fin >> x;
a.push_back(x);
}
for (int i = 0; i < d; ++i) {
a.push_back(a.at(i));
}
for (int i = d; i < a.size(); ++i) {
cout << a.at(i) << " ";
}
cout << endl;
}
// system("pause");
return 0;
}
|
4330bc0c467f0b40ef376536ec80e82b9486c7f0 | d9a60722483d86328a46c0b4353f1c64c272f911 | /src/gui/Button.cpp | cd46a8a5c04fef2127a726220574770bdcb2dc5c | [] | no_license | tectronics/elusion-mysterious-manifestation-of-the-mumbling-moocows | a299cb28b688bb027b493872c35bea825d107c25 | 0c687fef5614c5bf5092fb6d6d4bc5721ea93c9f | refs/heads/master | 2018-01-11T15:15:51.063187 | 2011-05-17T01:45:45 | 2011-05-17T01:45:45 | 46,212,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,366 | cpp | Button.cpp | #include "gui/Button.h"
#include "utilities/Rectangle.h"
namespace gui
{
Button::Button() : imageSet( NULL ), font( NULL )
{
}
Button::Button( const gdn::Vector2f& thePos,
const std::string& theTextIdle, const std::string& theTextHover, const std::string& theTextPress,
const gdn::Color& theColorIdle, const gdn::Color& theColorHover, const gdn::Color& theColorPress,
gdn::Image& theImageSet, gdn::Font& theFont, unsigned int theCharacterSize,
const gdn::Rectanglei& theRectIdle, const gdn::Rectanglei& theRectHover, const gdn::Rectanglei& theRectPress )
: pos( thePos ), mousePos(),
textIdle( theTextIdle ), textHover( theTextHover ), textPress( theTextPress ),
colorIdle( theColorIdle ), colorHover( theColorHover ), colorPress( theColorPress ),
imageSet( &theImageSet ), font( &theFont ), characterSize( theCharacterSize ),
rectIdle( theRectIdle ), rectHover( theRectHover ), rectPress( theRectPress ),
activeRect( &rectIdle ),
hold( false )
{
buttonSprite.SetImage( *imageSet );
buttonSprite.SetPosition( pos );
buttonSprite.SetSubRectangle( *activeRect );
buttonText.SetString( textIdle );
buttonText.SetFont( *font );
buttonText.SetColor( colorIdle );
buttonText.SetCharacterSize( characterSize );
gdn::Rectanglef textRect = buttonText.GetRectangle();
gdn::Vector2< unsigned int > imageSetSize = imageSet->GetSize();
gdn::Vector2f buttonTextPos = pos;
buttonTextPos.x += static_cast< int >( ( ( imageSetSize.x / 3 ) - textRect.width ) / 2 );
buttonTextPos.y += static_cast< int >( ( ( imageSetSize.y ) - textRect.height ) / 2 );
//std::cout << buttonTextPos.x << " " << buttonTextPos.y << std::endl;
//std::cout << ( ( ( imageSetSize.x / 3 ) - textRect.width ) / 2 ) << " " << ( ( ( imageSetSize.y ) - textRect.height ) / 2 ) << std::endl;
buttonText.SetPosition( buttonTextPos );
}
int Button::Process( const gdn::Event& event )
{
int ret = GUI_BUTTON_IDLE;
gdn::Vector2< unsigned int > imageSetSize = imageSet->GetSize();
if ( event.type == gdn::Event::MouseMoved )
{
mousePos.x = event.x;
mousePos.y = event.y;
if ( util::RectangleContainsPoint< float >( gdn::Rectanglef( pos.x, pos.y, imageSetSize.x / 3, imageSetSize.y ), mousePos ) )
{
if ( activeRect != &rectPress )
{
if ( activeRect == &rectHover )
{
ret = GUI_BUTTON_HOVER;
}
else if ( activeRect == &rectIdle )
{
ret = GUI_BUTTON_ENTER;
}
activeRect = &rectHover;
buttonSprite.SetSubRectangle( *activeRect );
buttonText.SetColor( colorHover );
buttonText.SetString( textHover );
}
}
else
{
if ( activeRect == &rectHover )
{
ret = GUI_BUTTON_EXIT;
}
else
{
ret = GUI_BUTTON_IDLE;
}
activeRect = &rectIdle;
buttonSprite.SetSubRectangle( *activeRect );
buttonText.SetColor( colorIdle );
buttonText.SetString( textIdle );
}
}
else if ( event.type == gdn::Event::MouseButtonPressed and event.mouseButton == gdn::Mouse::Left )
{
if ( util::RectangleContainsPoint< float >( gdn::Rectanglef( pos.x, pos.y, imageSetSize.x / 3, imageSetSize.y ), mousePos ) )
{
if ( hold != true )
{
ret = GUI_BUTTON_HOLD;
}
else
{
ret = GUI_BUTTON_PRESS;
}
activeRect = &rectPress;
buttonSprite.SetSubRectangle( *activeRect );
buttonText.SetColor( colorPress );
buttonText.SetString( textPress );
hold = true;
}
}
else if ( event.type == gdn::Event::MouseButtonReleased and event.mouseButton == gdn::Mouse::Left )
{
if ( util::RectangleContainsPoint< float >( gdn::Rectanglef( pos.x, pos.y, imageSetSize.x / 3, imageSetSize.y ), mousePos ) )
{
ret = GUI_BUTTON_RELEASE;
activeRect = &rectHover;
buttonSprite.SetSubRectangle( *activeRect );
buttonText.SetColor( colorHover );
buttonText.SetString( textHover );
hold = false;
}
}
return ret;
}
void Button::Draw( gdn::Window& window )
{
window.Draw( buttonSprite );
window.Draw( buttonText );
}
void Button::Draw( gdn::RenderImage& renderImage )
{
renderImage.Draw( buttonSprite );
renderImage.Draw( buttonText );
}
}
|
13330408c45834f804adf0eba3eca5a0837b145d | 33f1b5f6afa115be45cade93479bb7fbc33e7da0 | /CodeForces/796B/8895588_AC_1996ms_41268kB.cpp | a535f5e6e3291ca2f79c3b23f22b5760e5b0d0e1 | [] | no_license | showmic96/Online-Judge-Solution | 3960c37a646f4885210c09096c21dabd7f2154d2 | 94c34e9db2833fb84d0ac885b637dfebac30a5a2 | refs/heads/master | 2022-11-26T09:56:58.469560 | 2020-08-02T04:42:33 | 2020-08-02T04:42:33 | 230,185,618 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 783 | cpp | 8895588_AC_1996ms_41268kB.cpp | // In the name of Allah the Lord of the Worlds.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(void)
{
ll n , m , k , p = 1 , ans = 1;
scanf("%lld %lld %lld",&n , &m ,&k);//cin >> n >> m >> k;
map<ll,ll>mp;
for(int i=0;i<m;i++){
ll in;
scanf("%lld",&in);//cin >> in;
mp[in] = 1;
}
bool check = false;
while(k--){
ll in1 , in2;
cin >> in1 >> in2;
if(check==false)
{
if(mp[p]==1){check=true;ans = p;}
if(in1==p){
p = in2;
}
else if(in2==p) p = in1;
}
}
if(check==true)printf("%lld\n",ans);//cout << ans << endl;
else printf("%lld\n",p);//cout << p << endl;
return 0;
}
|
96f8b9a4869ad9b9841af542cf6acba5edcc6212 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/printscan/faxsrv/src/test/src/bvt/extendedbvt/cfaxeventexptr.cpp | ba44855d78eea4ab145185012a3797a33a1f0776 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,125 | cpp | cfaxeventexptr.cpp | #include "CFaxEventExPtr.h"
#include "Util.h"
#include "FaxConstantsNames.h"
#define FIELD_CAPTION_WIDTH 30
//-----------------------------------------------------------------------------------------------------------------------------------------
const tstring CFaxEventExPtr::m_tstrInvalidEvent = _T("Invalid Event");
//-----------------------------------------------------------------------------------------------------------------------------------------
CFaxEventExPtr::CFaxEventExPtr(PFAX_EVENT_EX pFaxEventEx)
: m_pFaxEventEx(pFaxEventEx)
{
}
//-----------------------------------------------------------------------------------------------------------------------------------------
CFaxEventExPtr::~CFaxEventExPtr()
{
FaxFreeBuffer(m_pFaxEventEx);
}
//-----------------------------------------------------------------------------------------------------------------------------------------
bool CFaxEventExPtr::IsValid() const
{
return m_pFaxEventEx != NULL;
}
//-----------------------------------------------------------------------------------------------------------------------------------------
PFAX_EVENT_EX CFaxEventExPtr::operator->() const
{
return m_pFaxEventEx;
}
//-----------------------------------------------------------------------------------------------------------------------------------------
const tstring &CFaxEventExPtr::Format() const
{
if (!m_pFaxEventEx)
{
return CFaxEventExPtr::m_tstrInvalidEvent;
}
if (m_tstrFormatedString.empty())
{
//
// The string is not combined yet - do it.
//
TCHAR tszBuf[1024];
int iCurrPos = 0;
const int iBufSize = ARRAY_SIZE(tszBuf);
//
// Format time stamp.
//
FILETIME LocalFileTime;
if (!::FileTimeToLocalFileTime(&(m_pFaxEventEx->TimeStamp), &LocalFileTime))
{
THROW_TEST_RUN_TIME_WIN32(GetLastError(), _T("CFaxEventExPtr::Format - FileTimeToLocalFileTime"));
}
SYSTEMTIME SystemTime;
if(!::FileTimeToSystemTime(&LocalFileTime, &SystemTime))
{
THROW_TEST_RUN_TIME_WIN32(GetLastError(), _T("CFaxEventExPtr::Format - FileTimeToSystemTime"));
}
iCurrPos += _sntprintf(
tszBuf + iCurrPos,
iBufSize - iCurrPos,
_T("%-*s%ld/%ld/%ld %ld:%02ld:%02ld\n"),
FIELD_CAPTION_WIDTH,
_T("TimeStamp:"),
SystemTime.wDay,
SystemTime.wMonth,
SystemTime.wYear,
SystemTime.wHour,
SystemTime.wMinute,
SystemTime.wSecond
);
//
// Format event type.
//
iCurrPos += _sntprintf(
tszBuf + iCurrPos,
iBufSize - iCurrPos,
_T("%-*s%s\n"),
FIELD_CAPTION_WIDTH,
_T("EventType:"),
EventTypeToString(m_pFaxEventEx->EventType).c_str()
);
//
// Format type specific information.
//
switch (m_pFaxEventEx->EventType)
{
case FAX_EVENT_TYPE_IN_QUEUE:
case FAX_EVENT_TYPE_OUT_QUEUE:
case FAX_EVENT_TYPE_IN_ARCHIVE:
case FAX_EVENT_TYPE_OUT_ARCHIVE:
iCurrPos += _sntprintf(
tszBuf + iCurrPos,
iBufSize - iCurrPos,
_T("%-*s0x%I64x\n%-*s%s\n"),
FIELD_CAPTION_WIDTH,
_T("dwlMessageId:"),
m_pFaxEventEx->EventInfo.JobInfo.dwlMessageId,
FIELD_CAPTION_WIDTH,
_T("JobEventType:"),
JobEventTypeToString(m_pFaxEventEx->EventInfo.JobInfo.Type).c_str()
);
if (m_pFaxEventEx->EventInfo.JobInfo.Type == FAX_JOB_EVENT_TYPE_STATUS)
{
_ASSERT(m_pFaxEventEx->EventInfo.JobInfo.pJobData);
iCurrPos += _sntprintf(
tszBuf + iCurrPos,
iBufSize - iCurrPos,
_T("%-*s%s\n%-*s%ld\n%-*s%s\n%-*s%s\n%-*s%s\n%-*s%ld\n%-*s%s\n"),
FIELD_CAPTION_WIDTH,
_T("lpctstrDeviceName:"),
m_pFaxEventEx->EventInfo.JobInfo.pJobData->lpctstrDeviceName,
FIELD_CAPTION_WIDTH,
_T("dwDeviceId:"),
m_pFaxEventEx->EventInfo.JobInfo.pJobData->dwDeviceID,
FIELD_CAPTION_WIDTH,
_T("QueueStatus:"),
QueueStatusToString(m_pFaxEventEx->EventInfo.JobInfo.pJobData->dwQueueStatus).c_str(),
FIELD_CAPTION_WIDTH,
_T("ExtendedStatus:"),
ExtendedStatusToString(m_pFaxEventEx->EventInfo.JobInfo.pJobData->dwExtendedStatus).c_str(),
FIELD_CAPTION_WIDTH,
_T("ProprietaryExtendedStatus:"),
m_pFaxEventEx->EventInfo.JobInfo.pJobData->lpctstrExtendedStatus,
FIELD_CAPTION_WIDTH,
_T("dwCurrentPage:"),
m_pFaxEventEx->EventInfo.JobInfo.pJobData->dwCurrentPage,
FIELD_CAPTION_WIDTH,
_T("lpctstrTsid:"),
m_pFaxEventEx->EventInfo.JobInfo.pJobData->lpctstrTsid
);
}
break;
case FAX_EVENT_TYPE_CONFIG:
iCurrPos += _sntprintf(
tszBuf + iCurrPos,
iBufSize - iCurrPos,
_T("%-*s%s\n"),
FIELD_CAPTION_WIDTH,
_T("ConfigType:"),
ConfigEventTypeToString(m_pFaxEventEx->EventInfo.ConfigType).c_str()
);
break;
case FAX_EVENT_TYPE_ACTIVITY:
iCurrPos += _sntprintf(
tszBuf + iCurrPos,
iBufSize - iCurrPos,
_T("%-*s%ld\n%-*s%ld\n%-*s%ld\n%-*s%ld\n%-*s%ld\n"),
FIELD_CAPTION_WIDTH,
_T("dwIncomingMessages:"),
m_pFaxEventEx->EventInfo.ActivityInfo.dwIncomingMessages,
FIELD_CAPTION_WIDTH,
_T("dwRoutingMessages:"),
m_pFaxEventEx->EventInfo.ActivityInfo.dwRoutingMessages,
FIELD_CAPTION_WIDTH,
_T("dwOutgoingMessages:"),
m_pFaxEventEx->EventInfo.ActivityInfo.dwOutgoingMessages,
FIELD_CAPTION_WIDTH,
_T("dwDelegatedOutgoingMessages:"),
m_pFaxEventEx->EventInfo.ActivityInfo.dwDelegatedOutgoingMessages,
FIELD_CAPTION_WIDTH,
_T("dwQueuedMessages:"),
m_pFaxEventEx->EventInfo.ActivityInfo.dwQueuedMessages
);
break;
case FAX_EVENT_TYPE_QUEUE_STATE:
iCurrPos += _sntprintf(
tszBuf + iCurrPos,
iBufSize - iCurrPos,
_T("%-*s%ld\n"),
FIELD_CAPTION_WIDTH,
_T("dwQueueStates:"),
m_pFaxEventEx->EventInfo.dwQueueStates
);
break;
case FAX_EVENT_TYPE_FXSSVC_ENDED:
break;
case FAX_EVENT_TYPE_DEVICE_STATUS:
{
FAX_ENUM_DEVICE_STATUS DeviceStatus = static_cast<FAX_ENUM_DEVICE_STATUS>(m_pFaxEventEx->EventInfo.DeviceStatus.dwNewStatus);
iCurrPos += _sntprintf(
tszBuf + iCurrPos,
iBufSize - iCurrPos,
_T("%-*s%ld\n%-*s%s\n"),
FIELD_CAPTION_WIDTH,
_T("dwDeviceId:"),
m_pFaxEventEx->EventInfo.DeviceStatus.dwDeviceId,
FIELD_CAPTION_WIDTH,
_T("dwNewStatus:"),
DeviceStatusToString(DeviceStatus).c_str()
);
break;
}
case FAX_EVENT_TYPE_NEW_CALL:
iCurrPos += _sntprintf(
tszBuf + iCurrPos,
iBufSize - iCurrPos,
_T("%-*s%ld\n%-*s%ld\n%-*s%s\n"),
FIELD_CAPTION_WIDTH,
_T("hCall:"),
m_pFaxEventEx->EventInfo.NewCall.hCall,
FIELD_CAPTION_WIDTH,
_T("dwDeviceId:"),
m_pFaxEventEx->EventInfo.NewCall.dwDeviceId,
FIELD_CAPTION_WIDTH,
_T("lptstrCallerId:"),
m_pFaxEventEx->EventInfo.NewCall.lptstrCallerId
);
break;
default:
THROW_TEST_RUN_TIME_WIN32(ERROR_INVALID_DATA, _T("CFaxEventExPtr::Format - Invalid EventType"));
break;
}
//
// Remove trailing new line.
//
if (iCurrPos > 0 && tszBuf[iCurrPos - 1] == _T('\n'))
{
tszBuf[iCurrPos - 1] = _T('\0');
}
m_tstrFormatedString = tszBuf;
}
return m_tstrFormatedString;
} |
f040b440d6860947cd1a0694c46a5fb0fe5f6777 | 08b89f1aafbcced86a0fb1882bf3fb396f722a77 | /src/rank_teste.cpp | adc7fb96a35891a69f74838fc4c945b467d37814 | [] | no_license | MVCP1/pds2_maquinadebusca | b0a7ffe9f6f042c35c2a6cb2b00d3870eefc67e4 | 3b2ae8f0af3ac50432882152cc6a32cad570d7cc | refs/heads/master | 2020-09-07T16:22:20.410145 | 2020-03-20T19:54:17 | 2020-03-20T19:54:17 | 220,841,840 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,924 | cpp | rank_teste.cpp | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "rank.h"
#include "doctest.h"
using namespace std;
class RankTeste{
public:
vector <pair <string, double> > rank(Rank& r){
return r.rank_;
}
};
TEST_CASE("Rank") {
RankTeste rank_teste;
IndiceInvertido indice;
indice.InserePasta("testes/rank_teste");
Norma normas(indice);
multiset<string> query;
query.insert("a");
query.insert("a");
query.insert("a");
SUBCASE("similaridade(rank_test)"){
CHECK(0.7 < similaridade("testes/rank_teste/D1", query, indice, normas));
CHECK(0.35 < similaridade("testes/rank_teste/D2", query, indice, normas));
CHECK(0.45 > similaridade("testes/rank_teste/D2", query, indice, normas));
CHECK(1.0 == similaridade("testes/rank_teste/D3", query, indice, normas));
CHECK(0.0 == similaridade("testes/rank_teste/D4", query, indice, normas));
}
SUBCASE("rank()"){
Rank r(query, indice, normas);
vector <pair <string, double> > rank = rank_teste.rank(r);
CHECK("testes/rank_teste/D3" == rank[0].first);
CHECK("testes/rank_teste/D1" == rank[1].first);
CHECK("testes/rank_teste/D2" == rank[2].first);
CHECK("testes/rank_teste/D4" == rank[3].first);
}
query.insert("b");
SUBCASE("similaridade(rank_test)"){
CHECK(0.0 < similaridade("testes/rank_teste/D4", query, indice, normas));
CHECK(1.0 > similaridade("testes/rank_teste/D3", query, indice, normas));
}
SUBCASE("ord(pair<string, double>)"){
vector<pair<string, double> > v_ord;
v_ord.push_back(make_pair("a", 2.0));
v_ord.push_back(make_pair("b", 1.0));
v_ord.push_back(make_pair("c", 3.0));
sort(v_ord.begin(), v_ord.end(), ord);
CHECK("c" == v_ord[0].first);
CHECK("a" == v_ord[1].first);
CHECK("b" == v_ord[2].first);
}
}
|
665d7349a6add119374e30a4c22eb013fc02331d | 4a605a3b68c4770aa6fc341bc2776350ba5e0285 | /src/Dump.cpp | eef1f654cfa1d412d9ad9d2ca4041587bfbae330 | [
"WTFPL"
] | permissive | mosra/absencoid | 187e86baf3ece9e5c99f7008e8ed1d3a34b7a0a5 | 1b1437df643b4318cb98c7d71ec174ad89dae882 | refs/heads/master | 2021-01-25T12:13:11.787577 | 2011-09-15T10:30:46 | 2011-09-15T10:30:46 | 2,391,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,286 | cpp | Dump.cpp | #include "Dump.h"
#include <QDomDocument>
#include <QSqlQuery>
#include <QSqlError>
#include <QDate>
#include <QDebug>
#include "configure.h"
#include "ClassesModel.h"
#include "TimetableModel.h"
#include "TeachersModel.h"
namespace Absencoid {
/* Konstruktor */
Dump::Dump(bool indent): flags(indent ? INDENT : 0), _deltaTeachers(0),
_deltaClasses(0), _deltaTimetables(0), _deltaTimetableData(0), _deltaChanges(0),
_deltaAbsences(0) {
/* Inicializace doctype */
QDomImplementation i;
doctype = i.createDocumentType("absencoid", QString(), "absencoid.dtd");
}
/* Vytvoření dumpu / aktualizace */
QString Dump::create(int flags, const QString& note) {
/* Inicializace dokumentu a kořenového elementu */
QDomDocument doc(doctype);
QDomElement r = doc.createElement("absencoid");
doc.appendChild(r);
QDomElement root;
/* Inicializace <dump> */
if(flags & DUMP) {
root = doc.createElement("dump");
root.setAttribute("version", DUMP_VERSION);
/* Inicializace <update> */
} else if(flags & UPDATE) {
root = doc.createElement("update");
root.setAttribute("version", UPDATE_VERSION);
/* Nevím co chci */
} else {
qDebug() << tr("Musíte vytvořit buď zálohu nebo aktualizaci!");
return QString();
}
r.appendChild(root);
/* <date> */
QDomElement date = doc.createElement("date");
doc.doctype();
root.appendChild(date);
date.appendChild(doc.createTextNode(QDate::currentDate().toString(Qt::ISODate)));
/* <note> (jen u update) */
if(flags & UPDATE) {
QDomElement _note = doc.createElement("note");
root.appendChild(_note);
_note.appendChild(doc.createTextNode(note));
}
/* <configuration> */
QDomElement configuration = doc.createElement("configuration");
root.appendChild(configuration);
/* Dotaz do databáze na konfiguraci */
QSqlQuery configurationQuery
("SELECT beginDate, endDate, webUpdateUrl, lastUpdate, activeTimetableId, flags "
"FROM configuration LIMIT 1;");
/* Chyba zpracování dotazu (musí zde být řádek!) */
if(!configurationQuery.next()) {
qDebug() << tr("Nepodařilo se získat data z konfigurační tabulky!")
<< configurationQuery.lastError() << configurationQuery.lastQuery();
return QString();
}
/* <beginDate> */
QDomElement beginDate = doc.createElement("beginDate");
configuration.appendChild(beginDate);
beginDate.appendChild(doc.createTextNode(configurationQuery.value(0).toString()));
/* <endDate> */
QDomElement endDate = doc.createElement("endDate");
configuration.appendChild(endDate);
endDate.appendChild(doc.createTextNode(configurationQuery.value(1).toString()));
/* <webUpdateUrl> */
QDomElement webUpdateUrl = doc.createElement("webUpdateUrl");
configuration.appendChild(webUpdateUrl);
webUpdateUrl.appendChild(doc.createTextNode(configurationQuery.value(2).toString()));
/* Uživatelská data patřící jen do zálohy */
if(flags & DUMP) {
/* <lastUpdate> */
QDomElement lastUpdate = doc.createElement("lastUpdate");
configuration.appendChild(lastUpdate);
lastUpdate.appendChild(doc.createTextNode(configurationQuery.value(3).toString()));
/* <updateOnStart> */
QDomElement updateOnStart = doc.createElement("updateOnStart");
configuration.appendChild(updateOnStart);
updateOnStart.setAttribute("value",
configurationQuery.value(5).toInt() & UPDATE_ON_START ? "true" : "false");
/* <dumpOnExit> */
QDomElement dumpOnExit = doc.createElement("dumpOnExit");
configuration.appendChild(dumpOnExit);
dumpOnExit.setAttribute("value",
configurationQuery.value(5).toInt() & DUMP_ON_EXIT ? "true" : "false");
}
/* <teachers> */
QDomElement teachers = doc.createElement("teachers");
root.appendChild(teachers);
/* Dotaz do databáze na učitele */
QSqlQuery teachersQuery;
if(!teachersQuery.exec("SELECT id, name, flags FROM teachers ORDER BY name;")) {
qDebug() << tr("Nepodařilo se získat seznam učitelů!")
<< teachersQuery.lastError() << teachersQuery.lastQuery();
return QString();
}
/* <teacher> */
while(teachersQuery.next()) {
QDomElement teacher = doc.createElement("teacher");
teachers.appendChild(teacher);
teacher.setAttribute("id", "p" + teachersQuery.value(0).toString());
teacher.setAttribute("counts",
teachersQuery.value(2).toInt() & TeachersModel::COUNTS ? "true" : "false");
teacher.setAttribute("accepts",
teachersQuery.value(2).toInt() & TeachersModel::ACCEPTS ? "true" : "false");
teacher.appendChild(doc.createTextNode(teachersQuery.value(1).toString()));
/* Inkrementace počtu ovlivněných učitelů */
++_deltaTeachers;
}
/* <classes> */
QDomElement classes = doc.createElement("classes");
root.appendChild(classes);
/* Doaz do databáze na předměty */
QSqlQuery classesQuery;
if(!classesQuery.exec("SELECT id, name, teacherId FROM classes ORDER BY name;")) {
qDebug() << tr("Nepodařilo se získat seznam předmětů!")
<< classesQuery.lastError() << classesQuery.lastQuery();
return QString();
}
/* <class> */
while(classesQuery.next()) {
QDomElement _class = doc.createElement("class");
classes.appendChild(_class);
_class.setAttribute("id", "c" + classesQuery.value(0).toString());
_class.setAttribute("teacherId", "p" + classesQuery.value(2).toString());
_class.appendChild(doc.createTextNode(classesQuery.value(1).toString()));
/* Inkrementace počtu ovlivněných předmětů */
++_deltaClasses;
}
/* <timetables> */
QDomElement timetables = doc.createElement("timetables");
root.appendChild(timetables);
/* ID aktuaálního rozvrhu jen u zálohy, aktualizace jej měnit nesmí */
/** @todo Nastavovat, jen pokud existuje nějaký rozvrh (potom DTD řve o neplatném IDREF) */
if(flags & DUMP) timetables.setAttribute("activeId", "t" + configurationQuery.value(4).toString());
/* Dotaz do databáze na rozvrhy */
QSqlQuery timetablesQuery;
if(!timetablesQuery.exec("SELECT id, description, validFrom, followedBy "
"FROM timetables ORDER BY description;")) {
qDebug() << tr("Nepodařilo se získat seznam rozvrhů!")
<< timetablesQuery.lastError() << timetablesQuery.lastQuery();
return QString();
}
/* <timetable> */
while(timetablesQuery.next()) {
QDomElement timetable = doc.createElement("timetable");
timetables.appendChild(timetable);
timetable.setAttribute("id", "t" + timetablesQuery.value(0).toString());
timetable.setAttribute("next", "t" + timetablesQuery.value(3).toString());
/* <name> */
QDomElement name = doc.createElement("name");
timetable.appendChild(name);
name.appendChild(doc.createTextNode(timetablesQuery.value(1).toString()));
/* <validFrom> */
QDomElement validFrom = doc.createElement("validFrom");
timetable.appendChild(validFrom);
validFrom.appendChild(doc.createTextNode(timetablesQuery.value(2).toString()));
/* <lessons> */
QDomElement lessons = doc.createElement("lessons");
timetable.appendChild(lessons);
/* Dotaz do databáze na data rozvrhu */
QSqlQuery timetableDataQuery;
/* Výběr jen zamknutých hodin pro aktualizaci */
QString onlyUpdate; if(flags & UPDATE)
onlyUpdate = " AND classId >= " + QString::number(TimetableModel::FIXED);
if(!timetableDataQuery.exec("SELECT dayHour, classId FROM timetableData "
"WHERE timetableId = " + timetablesQuery.value(0).toString() +
onlyUpdate + " ORDER BY dayHour;")) {
qDebug() << tr("Nepodařilo se získat data rozvrhu!")
<< timetableDataQuery.lastError() << timetableDataQuery.lastQuery();
return QString();
}
/* <lesson> */
while(timetableDataQuery.next()) {
QDomElement lesson = doc.createElement("lesson");
lessons.appendChild(lesson);
lesson.setAttribute("classId",
"c" + QString::number(timetableDataQuery.value(1).toInt() & ~TimetableModel::FIXED));
lesson.setAttribute("fixed",
timetableDataQuery.value(1).toInt() & TimetableModel::FIXED ? "true" : "false");
/* <day> */
QDomElement day = doc.createElement("day");
lesson.appendChild(day);
day.appendChild(doc.createTextNode(
QString::number(TimetableModel::day(timetableDataQuery.value(0).toInt()))));
/* <hour> */
QDomElement hour = doc.createElement("hour");
lesson.appendChild(hour);
hour.appendChild(doc.createTextNode(
QString::number(TimetableModel::hour(timetableDataQuery.value(0).toInt()))));
/* Inkrementace počtu ovlivněných vyučovacích hodin */
++_deltaTimetableData;
}
/* Inkrementace počtu ovlivněných rozvrhů */
++_deltaTimetables;
}
/* <changes> */
QDomElement changes = doc.createElement("changes");
root.appendChild(changes);
/* Dotaz do databáze na změny */
QSqlQuery changesQuery;
if(!changesQuery.exec("SELECT id, date, hour, fromClassId, toClassId "
"FROM changes ORDER BY date;")) {
qDebug() << tr("Nepodařilo se získat seznam změn!")
<< changesQuery.lastError() << changesQuery.lastQuery();
return QString();
}
/* <change> */
while(changesQuery.next()) {
QDomElement change = doc.createElement("change");
changes.appendChild(change);
change.setAttribute("id", "x" + changesQuery.value(0).toString());
/* <date> */
QDomElement date = doc.createElement("date");
change.appendChild(date);
date.appendChild(doc.createTextNode(changesQuery.value(1).toString()));
/* <allHours> */
if(changesQuery.value(2).toInt() == -1) {
QDomElement allHours = doc.createElement("allHours");
change.appendChild(allHours);
/* <hour> */
} else {
QDomElement hour = doc.createElement("hour");
change.appendChild(hour);
hour.appendChild(doc.createTextNode(changesQuery.value(2).toString()));
}
/* <allClasses> */
/** @todo Změnit WHATEVER na ALL_CLASSES */
if(changesQuery.value(3).toInt() == ClassesModel::WHATEVER) {
QDomElement allClasses = doc.createElement("allClasses");
change.appendChild(allClasses);
/* <fromClass> */
} else {
QDomElement fromClass = doc.createElement("fromClass");
change.appendChild(fromClass);
/* Pokud je classId == 0, atribut se neuvádí */
if(changesQuery.value(3).toInt() != 0)
fromClass.setAttribute("id", "c" + changesQuery.value(3).toString());
}
/* <toClass> */
QDomElement toClass = doc.createElement("toClass");
change.appendChild(toClass);
/* Pokud je classId == 0, atribut se neuvádí */
if(changesQuery.value(4).toInt() != 0)
toClass.setAttribute("id", "c" + changesQuery.value(4).toString());
/* Inkrementace počtu ovlivněných změn */
++_deltaChanges;
}
/* <absences> (jen při dumpu) */
if(flags & DUMP) {
QDomElement absences = doc.createElement("absences");
root.appendChild(absences);
/* Dotaz do databáze na absence */
QSqlQuery absencesQuery;
if(!absencesQuery.exec("SELECT id, date, hours FROM absences ORDER BY date, hours;")) {
qDebug() << tr("Nepodařilo se získat seznam absencí!")
<< absencesQuery.lastError() << absencesQuery.lastQuery();
return QString();
}
/* <absence> */
while(absencesQuery.next()) {
QDomElement absence = doc.createElement("absence");
absences.appendChild(absence);
absence.setAttribute("id", "a" + absencesQuery.value(0).toString());
/* <date> */
QDomElement date = doc.createElement("date");
absence.appendChild(date);
date.appendChild(doc.createTextNode(absencesQuery.value(1).toString()));
/* <hour> */
int hours = absencesQuery.value(2).toInt();
/** @todo <allHours> ! */
for(int i = 0; i != 10; ++i) if(hours >> i & 0x01) {
QDomElement hour = doc.createElement("hour");
absence.appendChild(hour);
hour.appendChild(doc.createTextNode(QString::number(i)));
}
++_deltaAbsences;
}
}
return doc.toString(flags & INDENT ? 4 : -1);
}
}
|
ddc45be1c30cb51e55a3951b1399c59a4a4dcccd | ff3fd14d5c51f7f87a11287a38c6ca82217cb49a | /src/meng/view/GUI/TextField.h | 191b8b6814d461b994bec09e1ef309b9dfeb87ca | [] | no_license | trid/Demos | a99fc5ae31ddfbe50def1381ceb0213f43a1813a | c29662eb1ae2628c604ddae395e42ee5c0a729bb | refs/heads/master | 2020-12-14T06:06:27.138677 | 2017-07-20T19:12:23 | 2017-07-20T19:12:23 | 95,596,634 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 374 | h | TextField.h | //
// Created by TriD on 23.08.2016.
//
#ifndef OBAKE_REAL_ESTATE_TEXTFIELD_H
#define OBAKE_REAL_ESTATE_TEXTFIELD_H
#include <TGUI/Widgets/Scrollbar.hpp>
#include <TGUI/Widgets/TextBox.hpp>
#include "Widget.h"
namespace MEng {
namespace View {
namespace GUI {
using TextField = tgui::TextBox;
}
}
}
#endif //OBAKE_REAL_ESTATE_TEXTFIELD_H
|
80232242185a16a14341e2837ac21f7b4eb35dbd | be191f4c90c8f86c193a9a02f7f95b8f8b608aae | /Project-04-Sudoku-Solver/Solver.cpp | b42d6b7aea4c5670a9367d14081c78165d7ab668 | [] | no_license | jifishma/Project-04-Sudoku | c2897b07180e5e42d6ca1c63de7fba6ad6d94934 | a03c364d2097914bc848d51ca6a81f35c24a0970 | refs/heads/master | 2020-06-28T18:20:35.457992 | 2019-08-17T00:06:02 | 2019-08-17T00:06:02 | 200,306,783 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,111 | cpp | Solver.cpp | #include "../Project-04-Sudoku/Sudoku.h"
#include "../Project-04-FileOps/FileOps.h"
void CreateCreatorInputFile(Sudoku puzzle, ofstream& outs);
int main(int argc, char** argv)
{
ifstream ins;
ofstream outs;
string inFileName, outFileName, outStatistic;
Sudoku puzzle = Sudoku(outs);
puzzle.state = State::Solving;
// Display welcome message
cout << "-----------Welcome to Sudoku Solver Program-----------" << endl;
// Ask for and open the input and output files
OpenFileStreams(ins, inFileName, outs, outStatistic);
// Print welcome message to file
outs << "-----------Welcome to Sudoku Solver Program-----------" << endl;
// Read input file, and populate the puzzle accordingly
PreparePuzzle(inFileName, puzzle, ins, outs);
// Show the initial puzzle grid after loading
cout << "Initial puzzle: " << endl;
outs << "Initial puzzle: " << endl;
puzzle.printGrid();
// Solve the puzzle, showing iteratations of solved sub-grids as we progress
puzzle.solver.solveSudokuWithTimer();
// Once fully solved, print the complete puzzle grid
cout << "Final puzzle: " << endl;
outs << "Final puzzle: " << endl;
puzzle.printGrid();
// Once we get here, print out collected metrics from finding a solution
puzzle.solver.printSolveMetrics();
// Close the file streams
CloseFileStreams(ins, outs);
//ask for output file name
cout << "Please enter output file name: ";
cin >> outFileName;
//open output file
outs.open(outFileName);
//create input file for Sudoku creator
CreateCreatorInputFile(puzzle, outs);
//close output file
outs.close();
system("pause");
return 0;
}
/*
Function Name: CreateCreatorInputFile
Author Name: Chong Zhang
Creation Date: 08/05/2019
Modification Date: 08/17/2019
Purpose: create input file for Sudoku creator
*/
void CreateCreatorInputFile(Sudoku puzzle, ofstream& outs)
{
for (int rowID = 1; rowID <= 9; ++rowID)
{
for (int colID = 1; colID <= 9; ++colID)
{
cout << rowID << " " << colID << " " << puzzle.getValue(rowID, colID) << endl;
outs << rowID << " " << colID << " " << puzzle.getValue(rowID, colID) << endl;
}
}
} |
d3b7e68aa3e3c969e9ebf340a95e39899fc5b488 | e37ed845bc74974d6ca7fee4b9228b138c7365bc | /Isetta/IsettaTestbed/Week10MiniGame/W10Player.cpp | db3dbb7575e970db4112d8c6cd767afb7f2f1931 | [
"MIT"
] | permissive | LukeMcCulloch/IsettaGameEngine | 1bc3564b03d269098c04272a511c632cd35f2d7e | 9f112d7d088623607a19175707824c5b65662e03 | refs/heads/master | 2020-07-26T16:06:06.712492 | 2019-09-16T03:09:49 | 2019-09-16T03:09:49 | 208,698,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,311 | cpp | W10Player.cpp | /*
* Copyright (c) 2018 Isetta
*/
#include "Week10MiniGame/W10Player.h"
#include "W10NetworkManager.h"
W10Player::W10Player(const bool isRight, const int swordNetID,
const int clientAuthorityID)
: swordEntity{nullptr},
isOnRight{isRight},
canOperate{true},
horizontalSpeed{1},
swordPos{0},
swordTargetX{0.5},
swordXProgress{0},
stabSpeed{7},
swordStabStatus{0},
gravity(9.8),
flyDuration{0},
totalFlyDuration(0),
targetX(0),
targetY(-0.25),
originY(0),
v0x{isRight ? -2.f : 2.f},
v0y(0),
isSwordFlying(false),
clientAuthorityId(clientAuthorityID),
swordNetId(swordNetID) {}
void W10Player::Awake() {
entity->AddComponent<Isetta::MeshComponent>("Week10/Player.scene.xml");
swordEntity = Isetta::Primitive::Create(Isetta::Primitive::Type::Cube);
auto networkId = swordEntity->AddComponent<Isetta::NetworkId>(swordNetId);
networkId->clientAuthorityId = clientAuthorityId;
swordEntity->AddComponent<Isetta::NetworkTransform>();
Isetta::Events::Instance().RegisterEventListener(
"Blocked",
[&](const Isetta::EventObject& eventObject) { SwordBlocked(); });
Isetta::Events::Instance().RegisterEventListener(
"Respawn",
[&](const Isetta::EventObject& eventObject) { InitPosition(); });
Isetta::Events::Instance().RegisterEventListener(
"RegainInput", [&](const Isetta::EventObject& eventObject) {
Isetta::Events::Instance().RaiseQueuedEvent(Isetta::EventObject{
"UITextChange", {std::string{"Game Started!"}}});
canOperate = true;
});
InitPosition();
}
void W10Player::Start() {
Isetta::Input::RegisterKeyPressCallback(Isetta::KeyCode::UP_ARROW, [&]() {
if (canOperate) ChangeSwordVerticlePosition(1);
});
Isetta::Input::RegisterKeyPressCallback(Isetta::KeyCode::DOWN_ARROW, [&]() {
if (canOperate) ChangeSwordVerticlePosition(-1);
});
Isetta::Input::RegisterKeyPressCallback(Isetta::KeyCode::SPACE, [&]() {
if (canOperate && swordStabStatus == 0) swordStabStatus = 1;
});
}
void W10Player::Update() {
float direction{0};
if (canOperate && Isetta::Input::IsKeyPressed(Isetta::KeyCode::A)) {
direction -= 1;
}
if (canOperate && Isetta::Input::IsKeyPressed(Isetta::KeyCode::D)) {
direction += 1;
}
transform->TranslateWorld(direction * horizontalSpeed *
Isetta::Time::GetDeltaTime() *
Isetta::Math::Vector3::left);
ChangeSwordHorizontalPosition(Isetta::Time::GetDeltaTime());
if (swordStabStatus == 0) isSwordFlying = false;
if (!isSwordFlying && swordStabStatus == 3) {
if (Isetta::Math::Util::Abs(transform->GetWorldPos().x -
swordEntity->transform->GetWorldPos().x) <
0.1f) {
swordEntity->GetComponent<Isetta::NetworkTransform>()->SetNetworkedParent(
entity->GetComponent<Isetta::NetworkId>()->id);
swordEntity->transform->SetLocalPos(
Isetta::Math::Vector3((isOnRight ? 1 : -1) * 0.25f, 0, 0.25f));
swordStabStatus = 0;
swordPos = 0;
Isetta::NetworkManager::Instance()
.SendMessageFromClient<W10CollectMessage>(
[this](W10CollectMessage* message) {
message->swordNetId = this->swordNetId;
});
swordEntity->GetComponent<Isetta::NetworkTransform>()->ForceSendTransform(
true);
}
}
if (isSwordFlying) {
flyDuration += Isetta::Time::GetDeltaTime();
if (flyDuration > totalFlyDuration) {
swordEntity->transform->SetWorldPos(
Isetta::Math::Vector3{targetX, targetY, 0});
isSwordFlying = false;
flyDuration = 0;
} else {
float y = originY + v0y * flyDuration -
0.5 * gravity * flyDuration * flyDuration;
float x = targetX - (totalFlyDuration - flyDuration) * v0x;
swordEntity->transform->SetWorldPos(Isetta::Math::Vector3{x, y, 0});
}
}
}
void W10Player::InitPosition() {
entity->SetTransform(Isetta::Math::Vector3{isOnRight ? -1.f : 1.f, 0, 0},
Isetta::Math::Vector3::zero,
Isetta::Math::Vector3{1, 1, 1});
swordEntity->transform->SetParent(transform);
swordEntity->transform->SetLocalPos(
Isetta::Math::Vector3((isOnRight ? 1 : -1) * 0.25f, 0, 0.25f));
swordEntity->transform->SetLocalScale(
Isetta::Math::Vector3{0.375, 0.025, 0.025});
swordStabStatus = 0;
swordPos = 0;
canOperate = false;
Isetta::Events::Instance().RaiseQueuedEvent(
Isetta::EventObject{"RegainInput",
Isetta::Time::GetFrameCount() + 200,
Isetta::EventPriority::MEDIUM,
{}});
}
void W10Player::ChangeSwordVerticlePosition(int direction) {
if (swordStabStatus != 0) return;
swordPos += direction;
swordPos = Isetta::Math::Util::Clamp(-1, 1, swordPos);
Isetta::NetworkManager::Instance().SendMessageFromClient<W10SwordPosMessage>(
[this](W10SwordPosMessage* swordMessage) {
swordMessage->swordPos = this->swordPos;
});
auto swordLocalPos = swordEntity->transform->GetLocalPos();
swordLocalPos.y = swordPos * 0.15;
swordEntity->transform->SetLocalPos(swordLocalPos);
}
void W10Player::ChangeSwordHorizontalPosition(float deltaTime) {
int sign = 0;
if (swordStabStatus == 0 || swordStabStatus == 3) return;
if (swordStabStatus == 1) {
sign = 1;
} else if (swordStabStatus == 2) {
sign = -1;
}
swordXProgress += sign * stabSpeed * deltaTime;
swordXProgress = Isetta::Math::Util::Clamp01(swordXProgress);
auto swordLocalPos = swordEntity->transform->GetLocalPos();
swordLocalPos.x = Isetta::Math::Util::Lerp(
(isOnRight ? 1 : -1) * 0.25, (isOnRight ? 1 : -1) * swordTargetX,
swordXProgress);
swordEntity->transform->SetLocalPos(swordLocalPos);
if (swordXProgress == 1) {
// to revoke
Isetta::NetworkManager::Instance()
.SendMessageFromClient<W10AttackAttemptMessage>(
[](W10AttackAttemptMessage* attackMessage) {});
swordStabStatus = 2;
}
if (swordXProgress == 0) {
// to idle
swordStabStatus = 0;
}
}
void W10Player::SwordBlocked() {
if (swordStabStatus != 2) return;
swordStabStatus = 3;
float randomX;
float currentX{transform->GetWorldPos().x};
if (isOnRight) {
randomX = -2 +
Isetta::Math::Random::GetRandom01() * (currentX - -2) / 3 * 2 +
(currentX - -2) / 3;
} else {
randomX = 2 + Isetta::Math::Random::GetRandom01() * (currentX - 2) / 3 * 2 +
(currentX - 2) / 3;
}
// swordEntity->GetComponent<Isetta::NetworkTransform>()->SetNetworkedParentToRoot();
swordEntity->transform->SetParent(nullptr);
targetX = randomX;
isSwordFlying = true;
flyDuration = 0;
originY = transform->GetWorldPos().y;
totalFlyDuration = (randomX - currentX) / v0x;
v0y = (targetY - originY +
0.5 * gravity * totalFlyDuration * totalFlyDuration) /
totalFlyDuration;
LOG_INFO(Isetta::Debug::Channel::General, "v0x = %f", v0x);
// swordEntity->transform->SetWorldPos(
// Isetta::Math::Vector3{randomX, -0.25, 0});
// swordEntity->transform->SetWorldRot(Isetta::Math::Vector3{0, 0, 0});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.