hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
55dae1a01cdd017f36227863375e21aff2332ee6
| 482
|
hpp
|
C++
|
include/Thread.hpp
|
Kiloris/Complot_Game
|
81247c6c13d7921a9cc01b765ab3a4a5924c2391
|
[
"MIT"
] | null | null | null |
include/Thread.hpp
|
Kiloris/Complot_Game
|
81247c6c13d7921a9cc01b765ab3a4a5924c2391
|
[
"MIT"
] | null | null | null |
include/Thread.hpp
|
Kiloris/Complot_Game
|
81247c6c13d7921a9cc01b765ab3a4a5924c2391
|
[
"MIT"
] | null | null | null |
/*
** COMPLOT PROJECT
** AUTHOR:
** Zacharie ABIDAT
*/
#ifndef THREAD_HPP_
#define THREAD_HPP_
#include <pthread.h>
class IThread {
public:
virtual ~IThread() {}
virtual void run() = 0;
};
class Thread : public IThread{
public:
Thread();
~Thread();
virtual void launchThread();
virtual void stopThread();
static void * execute(void *object);
protected:
private:
pthread_t thread;
};
#endif /* !THREAD_HPP_ */
| 15.548387
| 44
| 0.60166
|
Kiloris
|
55dbc9b949953d785ad81490982842118873a7e2
| 1,802
|
hpp
|
C++
|
libraries/chain/include/blurt/chain/steem_evaluator.hpp
|
Blurt-Blockchain/steem
|
fbffd373cdb0f6192aa8806d07e8671e219c3767
|
[
"MIT"
] | 2
|
2020-04-21T03:10:06.000Z
|
2020-04-21T05:49:46.000Z
|
libraries/chain/include/blurt/chain/steem_evaluator.hpp
|
Blurt-Blockchain/steem
|
fbffd373cdb0f6192aa8806d07e8671e219c3767
|
[
"MIT"
] | 4
|
2020-04-22T05:14:18.000Z
|
2020-04-22T07:59:20.000Z
|
libraries/chain/include/blurt/chain/steem_evaluator.hpp
|
Blurt-Blockchain/steem
|
fbffd373cdb0f6192aa8806d07e8671e219c3767
|
[
"MIT"
] | 2
|
2020-04-22T05:04:29.000Z
|
2020-10-23T13:58:19.000Z
|
#pragma once
#include <blurt/protocol/blurt_operations.hpp>
#include <blurt/chain/evaluator.hpp>
namespace blurt { namespace chain {
using namespace blurt::protocol;
BLURT_DEFINE_EVALUATOR( account_create )
BLURT_DEFINE_EVALUATOR( account_update )
BLURT_DEFINE_EVALUATOR( transfer )
BLURT_DEFINE_EVALUATOR( transfer_to_vesting )
BLURT_DEFINE_EVALUATOR( witness_update )
BLURT_DEFINE_EVALUATOR( account_witness_vote )
BLURT_DEFINE_EVALUATOR( account_witness_proxy )
BLURT_DEFINE_EVALUATOR( withdraw_vesting )
BLURT_DEFINE_EVALUATOR( set_withdraw_vesting_route )
BLURT_DEFINE_EVALUATOR( comment )
BLURT_DEFINE_EVALUATOR( comment_options )
BLURT_DEFINE_EVALUATOR( delete_comment )
BLURT_DEFINE_EVALUATOR( vote )
BLURT_DEFINE_EVALUATOR( custom )
BLURT_DEFINE_EVALUATOR( custom_json )
BLURT_DEFINE_EVALUATOR( custom_binary )
BLURT_DEFINE_EVALUATOR( escrow_transfer )
BLURT_DEFINE_EVALUATOR( escrow_approve )
BLURT_DEFINE_EVALUATOR( escrow_dispute )
BLURT_DEFINE_EVALUATOR( escrow_release )
BLURT_DEFINE_EVALUATOR( claim_account )
BLURT_DEFINE_EVALUATOR( create_claimed_account )
BLURT_DEFINE_EVALUATOR( request_account_recovery )
BLURT_DEFINE_EVALUATOR( recover_account )
BLURT_DEFINE_EVALUATOR( change_recovery_account )
BLURT_DEFINE_EVALUATOR( transfer_to_savings )
BLURT_DEFINE_EVALUATOR( transfer_from_savings )
BLURT_DEFINE_EVALUATOR( cancel_transfer_from_savings )
BLURT_DEFINE_EVALUATOR( decline_voting_rights )
BLURT_DEFINE_EVALUATOR( reset_account )
BLURT_DEFINE_EVALUATOR( set_reset_account )
BLURT_DEFINE_EVALUATOR( claim_reward_balance )
BLURT_DEFINE_EVALUATOR( delegate_vesting_shares )
BLURT_DEFINE_EVALUATOR( witness_set_properties )
BLURT_DEFINE_EVALUATOR( create_proposal )
BLURT_DEFINE_EVALUATOR( update_proposal_votes )
BLURT_DEFINE_EVALUATOR( remove_proposal )
} } // blurt::chain
| 36.04
| 54
| 0.870144
|
Blurt-Blockchain
|
55dbcf7336d1b63c59e5a4a5caca1dca31f253f4
| 5,482
|
cpp
|
C++
|
src/low-level/syscall/syscall.cpp
|
LittleCodingFox/ToastOS
|
28475cbde3bd358460e070575e91496bf211f1d5
|
[
"BSD-2-Clause"
] | 5
|
2021-12-21T19:17:00.000Z
|
2022-03-10T17:56:59.000Z
|
src/low-level/syscall/syscall.cpp
|
LittleCodingFox/ToastOS
|
28475cbde3bd358460e070575e91496bf211f1d5
|
[
"BSD-2-Clause"
] | null | null | null |
src/low-level/syscall/syscall.cpp
|
LittleCodingFox/ToastOS
|
28475cbde3bd358460e070575e91496bf211f1d5
|
[
"BSD-2-Clause"
] | null | null | null |
#include "syscall.hpp"
#include "process/Process.hpp"
#include "registers/Registers.hpp"
#include "gdt/gdt.hpp"
#include "debug.hpp"
#include "threading/lock.hpp"
typedef int64_t (*SyscallPointer)(InterruptStack *stack);
int64_t KNotImplemented(InterruptStack *stack);
int64_t SyscallWrite(InterruptStack *stack);
int64_t SyscallRead(InterruptStack *stack);
int64_t SyscallClose(InterruptStack *stack);
int64_t SyscallOpen(InterruptStack *stack);
int64_t SyscallSeek(InterruptStack *stack);
int64_t SyscallAnonAlloc(InterruptStack *stack);
int64_t SyscallVMMap(InterruptStack *stack);
int64_t SyscallVMUnmap(InterruptStack *stack);
int64_t SyscallTCBSet(InterruptStack *stack);
int64_t SyscallSigaction(InterruptStack *stack);
int64_t SyscallGetPID(InterruptStack *stack);
int64_t SyscallKill(InterruptStack *stack);
int64_t SyscallIsATTY(InterruptStack *stack);
int64_t SyscallStat(InterruptStack *stack);
int64_t SyscallFStat(InterruptStack *stack);
int64_t SyscallPanic(InterruptStack *stack);
int64_t SyscallReadEntries(InterruptStack *stack);
int64_t SyscallExit(InterruptStack *stack);
int64_t SyscallClock(InterruptStack *stack);
int64_t SyscallGetUID(InterruptStack *stack);
int64_t SyscallSetUID(InterruptStack *stack);
int64_t SyscallGetGID(InterruptStack *stack);
int64_t SyscallSigprocMask(InterruptStack *stack);
int64_t SyscallFcntl(InterruptStack *stack);
int64_t SyscallLog(InterruptStack *stack);
int64_t SyscallFork(InterruptStack *stack);
int64_t SyscallWaitPID(InterruptStack *stack);
int64_t SyscallGetPPID(InterruptStack *stack);
int64_t SyscallSetGraphicsType(InterruptStack *stack);
int64_t SyscallSetGraphicsBuffer(InterruptStack *stack);
int64_t SyscallGetGraphicsSize(InterruptStack *stack);
int64_t SyscallExecve(InterruptStack *stack);
int64_t SyscallPollInput(InterruptStack *stack);
int64_t SyscallCWD(InterruptStack *stack);
int64_t SyscallCHDir(InterruptStack *stack);
int64_t SyscallSpawnThread(InterruptStack *stack);
int64_t SyscallYield(InterruptStack *stack);
int64_t SyscallExitThread(InterruptStack *stack);
int64_t SyscallGetTID(InterruptStack *stack);
int64_t SyscallFutexWait(InterruptStack *stack);
int64_t SyscallFutexWake(InterruptStack *stack);
int64_t SyscallSetKBLayout(InterruptStack *stack);
int64_t SyscallPipe(InterruptStack *stack);
int64_t SyscallDup2(InterruptStack *stack);
SyscallPointer syscallHandlers[] =
{
[0] = (SyscallPointer)KNotImplemented,
[SYSCALL_READ] = (SyscallPointer)SyscallRead,
[SYSCALL_WRITE] = (SyscallPointer)SyscallWrite,
[SYSCALL_OPEN] = (SyscallPointer)SyscallOpen,
[SYSCALL_CLOSE] = (SyscallPointer)SyscallClose,
[SYSCALL_SEEK] = (SyscallPointer)SyscallSeek,
[SYSCALL_ANON_ALLOC] = (SyscallPointer)SyscallAnonAlloc,
[SYSCALL_VM_MAP] = (SyscallPointer)SyscallVMMap,
[SYSCALL_VM_UNMAP] = (SyscallPointer)SyscallVMUnmap,
[SYSCALL_TCB_SET] = (SyscallPointer)SyscallTCBSet,
[SYSCALL_SIGACTION] = (SyscallPointer)SyscallSigaction,
[SYSCALL_GETPID] = (SyscallPointer)SyscallGetPID,
[SYSCALL_KILL] = (SyscallPointer)SyscallKill,
[SYSCALL_ISATTY] = (SyscallPointer)SyscallIsATTY,
[SYSCALL_FSTAT] = (SyscallPointer)SyscallFStat,
[SYSCALL_STAT] = (SyscallPointer)SyscallStat,
[SYSCALL_PANIC] = (SyscallPointer)SyscallPanic,
[SYSCALL_READ_ENTRIES] = (SyscallPointer)SyscallReadEntries,
[SYSCALL_EXIT] = (SyscallPointer)SyscallExit,
[SYSCALL_CLOCK] = (SyscallPointer)SyscallClock,
[SYSCALL_GETUID] = (SyscallPointer)SyscallGetUID,
[SYSCALL_SETUID] = (SyscallPointer)SyscallSetUID,
[SYSCALL_GETGID] = (SyscallPointer)SyscallGetGID,
[SYSCALL_SIGPROCMASK] = (SyscallPointer)SyscallSigprocMask,
[SYSCALL_FCNTL] = (SyscallPointer)SyscallFcntl,
[SYSCALL_LOG] = (SyscallPointer)SyscallLog,
[SYSCALL_FORK] = (SyscallPointer)SyscallFork,
[SYSCALL_WAITPID] = (SyscallPointer)SyscallWaitPID,
[SYSCALL_GETPPID] = (SyscallPointer)SyscallGetPPID,
[SYSCALL_SETGRAPHICSTYPE] = (SyscallPointer)SyscallSetGraphicsType,
[SYSCALL_GETGRAPHICSSIZE] = (SyscallPointer)SyscallGetGraphicsSize,
[SYSCALL_SETGRAPHICSBUFFER] = (SyscallPointer)SyscallSetGraphicsBuffer,
[SYSCALL_EXECVE] = (SyscallPointer)SyscallExecve,
[SYSCALL_POLLINPUT] = (SyscallPointer)SyscallPollInput,
[SYSCALL_CWD] = (SyscallPointer)SyscallCWD,
[SYSCALL_CHDIR] = (SyscallPointer)SyscallCHDir,
[SYSCALL_SPAWN_THREAD] = (SyscallPointer)SyscallSpawnThread,
[SYSCALL_YIELD] = (SyscallPointer)SyscallYield,
[SYSCALL_THREAD_EXIT] = (SyscallPointer)SyscallExitThread,
[SYSCALL_GET_TID] = (SyscallPointer)SyscallGetTID,
[SYSCALL_FUTEX_WAIT] = (SyscallPointer)SyscallFutexWait,
[SYSCALL_FUTEX_WAKE] = (SyscallPointer)SyscallFutexWake,
[SYSCALL_SETKBLAYOUT] = (SyscallPointer)SyscallSetKBLayout,
[SYSCALL_PIPE] = (SyscallPointer)SyscallPipe,
[SYSCALL_DUP2] = (SyscallPointer)SyscallDup2,
};
void SyscallHandler(InterruptStack *stack)
{
if(stack->rdi <= sizeof(syscallHandlers) / sizeof(SyscallPointer) && syscallHandlers[stack->rdi] != NULL)
{
auto current = globalProcessManager->CurrentThread();
current->activePermissionLevel = PROCESS_PERMISSION_KERNEL;
auto handler = syscallHandlers[stack->rdi];
auto result = handler(stack);
stack->rax = result;
current->activePermissionLevel = PROCESS_PERMISSION_USER;
}
}
int64_t KNotImplemented(InterruptStack *stack)
{
DEBUG_OUT("Syscall: KNotImplemented", 0);
return -1;
}
| 42.828125
| 109
| 0.78931
|
LittleCodingFox
|
55ddbd54e78e8734201e4035a2672efa301a7b0f
| 4,420
|
cpp
|
C++
|
test/vector3d_unittest.cpp
|
sslnjz/geodesy
|
c7acc47903a22b12c0fca65fd0e7e8fea122af25
|
[
"MIT"
] | 2
|
2021-11-23T05:39:48.000Z
|
2021-12-06T02:53:53.000Z
|
test/vector3d_unittest.cpp
|
sslnjz/geodesy
|
c7acc47903a22b12c0fca65fd0e7e8fea122af25
|
[
"MIT"
] | null | null | null |
test/vector3d_unittest.cpp
|
sslnjz/geodesy
|
c7acc47903a22b12c0fca65fd0e7e8fea122af25
|
[
"MIT"
] | null | null | null |
/**********************************************************************************
* MIT License *
* *
* Copyright (c) 2021 Binbin Song <ssln.jzs@gmail.com> *
* *
* Geodesy tools for conversions between (historical) datums *
* (c) Chris Veness 2005-2019 *
* www.movable-type.co.uk/scripts/latlong-convert-coords.html *
* www.movable-type.co.uk/scripts/geodesy-library.html#latlon-ellipsoidal-datum *
* *
* 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 <gtest/gtest.h>
#include "geodesy/vector3d.h"
TEST(vector3d_unittest, Constructor)
{
const geodesy::vector3d v3d(0.267, 0.535, 0.802);
EXPECT_DOUBLE_EQ(v3d.x(), 0.267);
EXPECT_DOUBLE_EQ(v3d.y(), 0.535);
EXPECT_DOUBLE_EQ(v3d.z(), 0.802);
}
TEST(vector3d_unittest, methods)
{
const auto v123 = geodesy::vector3d(1, 2, 3);
const auto v321 = geodesy::vector3d(3, 2, 1);
EXPECT_EQ(v123.plus(v321), geodesy::vector3d(4, 4, 4));
EXPECT_EQ(v123.minus(v321), geodesy::vector3d(-2, 0, 2));
EXPECT_EQ(v123.times(2), geodesy::vector3d(2, 4, 6));
EXPECT_EQ(v123.dividedBy(2), geodesy::vector3d(0.5, 1, 1.5));
EXPECT_EQ(v123.dot(v321), 10);
EXPECT_EQ(v123.cross(v321), geodesy::vector3d(-4, 8, -4));
EXPECT_EQ(v123.negate(), geodesy::vector3d(-1, -2, -3));
EXPECT_EQ(v123.length(), 3.7416573867739413);
EXPECT_EQ(v123.unit().toString(), "[0.267, 0.535, 0.802]");
EXPECT_EQ(geodesy::toFixed(geodesy::toDegrees(v123.angleTo(v321)), 3), "44.415");
EXPECT_EQ(geodesy::toFixed(geodesy::toDegrees(v123.angleTo(v321, v123.cross(v321))), 3), "44.415");
EXPECT_EQ(geodesy::toFixed(geodesy::toDegrees(v123.angleTo(v321, v321.cross(v123))), 3), "-44.415");
EXPECT_EQ(geodesy::toFixed(geodesy::toDegrees(v123.angleTo(v321, v123)), 3), "44.415");
EXPECT_EQ(v123.rotateAround(geodesy::vector3d(0, 0, 1), 90).toString(), "[-0.535, 0.267, 0.802]");
EXPECT_EQ(v123.toString(), "[1.000, 2.000, 3.000]");
EXPECT_EQ(v123.toString(6), "[1.000000, 2.000000, 3.000000]");
}
TEST(vector3d_unittest, operators)
{
auto v123 = geodesy::vector3d(1, 2, 3);
const auto v321 = geodesy::vector3d(3, 2, 1);
EXPECT_EQ((v123 += v321), geodesy::vector3d(4, 4, 4));
v123 = geodesy::vector3d(1, 2, 3);
EXPECT_EQ(v123 -= v321, geodesy::vector3d(-2, 0, 2));
v123 = geodesy::vector3d(1, 2, 3);
EXPECT_EQ(v123 *= 2, geodesy::vector3d(2, 4, 6));
v123 = geodesy::vector3d(1, 2, 3);
EXPECT_EQ(v123 /= 2, geodesy::vector3d(0.5, 1, 1.5));
}
| 58.933333
| 104
| 0.53371
|
sslnjz
|
55e7a3f929e1be27d2d46879189b9939b1b1937a
| 4,381
|
cpp
|
C++
|
Vic2ToHoI4Tests/HoI4WorldTests/Diplomacy/Hoi4WarTests.cpp
|
gawquon/Vic2ToHoI4
|
8371cfb1fd57cf81d854077963135d8037e754eb
|
[
"MIT"
] | 25
|
2018-12-10T03:41:49.000Z
|
2021-10-04T10:42:36.000Z
|
Vic2ToHoI4Tests/HoI4WorldTests/Diplomacy/Hoi4WarTests.cpp
|
gawquon/Vic2ToHoI4
|
8371cfb1fd57cf81d854077963135d8037e754eb
|
[
"MIT"
] | 739
|
2018-12-13T02:01:20.000Z
|
2022-03-28T02:57:13.000Z
|
Vic2ToHoI4Tests/HoI4WorldTests/Diplomacy/Hoi4WarTests.cpp
|
Osariusz/Vic2ToHoI4
|
9738b52c7602b1fe187c3820660c58a8d010d87e
|
[
"MIT"
] | 43
|
2018-12-10T03:41:58.000Z
|
2022-03-22T23:55:41.000Z
|
#include "HOI4World/Diplomacy/HoI4War.h"
#include "Mappers/Country/CountryMapperBuilder.h"
#include "Mappers/Provinces/ProvinceMapperBuilder.h"
#include "gtest/gtest.h"
#include <sstream>
TEST(HoI4World_Diplomacy_WarTests, allItemsDefaultToEmpty)
{
const HoI4::War war(Vic2::War({}),
*Mappers::CountryMapper::Builder().Build(),
Mappers::CasusBellis({}),
Mappers::ProvinceMapper{},
std::map<int, int>{});
std::stringstream output;
output << war;
std::stringstream expectedOutput;
expectedOutput << "declare_war_on = {\n";
expectedOutput << "\ttarget = \n";
expectedOutput << "\ttype = topple_government\n";
expectedOutput << "}\n";
expectedOutput << "\n";
ASSERT_EQ(expectedOutput.str(), output.str());
}
TEST(HoI4World_Diplomacy_WarTests, warnIfOriginalDefenderCantBeMapped)
{
std::stringstream log;
auto stdOutBuf = std::cout.rdbuf();
std::cout.rdbuf(log.rdbuf());
const HoI4::War war(Vic2::War(Vic2::WarOptions{.originalAttacker{"OAT"}, .originalDefender{"ODF"}}),
*Mappers::CountryMapper::Builder().addMapping("OAT", "NAT").Build(),
Mappers::CasusBellis({}),
Mappers::ProvinceMapper{},
std::map<int, int>{});
std::cout.rdbuf(stdOutBuf);
ASSERT_EQ(" [WARNING] Could not map ODF, original defender in a war\n", log.str());
}
TEST(HoI4World_Diplomacy_WarTests, extraDefendersCanBeAdded)
{
const HoI4::War war(
Vic2::War(Vic2::WarOptions{.originalAttacker{"OAT"}, .originalDefender{"ODF"}, .defenders{{"OED"}}}),
*Mappers::CountryMapper::Builder()
.addMapping("ODF", "NDF")
.addMapping("OED", "NED")
.addMapping("OAT", "NAT")
.Build(),
Mappers::CasusBellis({}),
Mappers::ProvinceMapper{},
std::map<int, int>{});
std::stringstream output;
output << war;
std::stringstream expectedOutput;
expectedOutput << "declare_war_on = {\n";
expectedOutput << "\ttarget = NDF\n";
expectedOutput << "\ttype = topple_government\n";
expectedOutput << "}\n";
expectedOutput << "NED = {\n";
expectedOutput << "\tadd_to_war = {\n";
expectedOutput << "\t\ttargeted_alliance = NDF\n";
expectedOutput << "\t\tenemy = NAT\n";
expectedOutput << "\t}\n";
expectedOutput << "}\n";
expectedOutput << "\n";
ASSERT_EQ(expectedOutput.str(), output.str());
}
TEST(HoI4World_Diplomacy_WarTests, extraAttackersCanBeAdded)
{
const HoI4::War war(
Vic2::War(Vic2::WarOptions{.originalAttacker{"OAT"}, .attackers{{"OEA"}}, .originalDefender{"ODF"}}),
*Mappers::CountryMapper::Builder()
.addMapping("ODF", "NDF")
.addMapping("OEA", "NEA")
.addMapping("OAT", "NAT")
.Build(),
Mappers::CasusBellis({}),
Mappers::ProvinceMapper{},
std::map<int, int>{});
std::stringstream output;
output << war;
std::stringstream expectedOutput;
expectedOutput << "declare_war_on = {\n";
expectedOutput << "\ttarget = NDF\n";
expectedOutput << "\ttype = topple_government\n";
expectedOutput << "}\n";
expectedOutput << "NEA = {\n";
expectedOutput << "\tadd_to_war = {\n";
expectedOutput << "\t\ttargeted_alliance = NAT\n";
expectedOutput << "\t\tenemy = NDF\n";
expectedOutput << "\t}\n";
expectedOutput << "}\n";
expectedOutput << "\n";
ASSERT_EQ(expectedOutput.str(), output.str());
}
TEST(HoI4World_Diplomacy_WarTests, warnIfOriginalAttackerCantBeMapped)
{
std::stringstream log;
auto stdOutBuf = std::cout.rdbuf();
std::cout.rdbuf(log.rdbuf());
const HoI4::War war(Vic2::War(Vic2::WarOptions{.originalAttacker{"OAT"}, .originalDefender{"ODF"}}),
*Mappers::CountryMapper::Builder().addMapping("ODF", "NDF").Build(),
Mappers::CasusBellis({}),
Mappers::ProvinceMapper{},
std::map<int, int>{});
std::cout.rdbuf(stdOutBuf);
ASSERT_EQ(" [WARNING] Could not map OAT, original attacker in a war\n", log.str());
}
TEST(HoI4World_Diplomacy_WarTests, TargetStateCanBeSet)
{
const HoI4::War war(Vic2::War({.province = 42}),
*Mappers::CountryMapper::Builder().Build(),
Mappers::CasusBellis({}),
*Mappers::ProvinceMapper::Builder{}.addVic2ToHoI4ProvinceMap(42, {84}).Build(),
std::map<int, int>{{84, 3}});
std::stringstream output;
output << war;
std::stringstream expectedOutput;
expectedOutput << "declare_war_on = {\n";
expectedOutput << "\ttarget = \n";
expectedOutput << "\ttype = topple_government\n";
expectedOutput << "\tgenerator = { 3 }\n";
expectedOutput << "}\n";
expectedOutput << "\n";
ASSERT_EQ(expectedOutput.str(), output.str());
}
| 29.402685
| 104
| 0.681123
|
gawquon
|
55ec3815bfbac09f5c488feb8a4071b06ee75204
| 191
|
cpp
|
C++
|
src/LevelSetSeg.cpp
|
Bas94/SegmentationMethodsForMedicalImageAnalysis
|
c14514e76ca89eb6fc08374177809518d7762d64
|
[
"MIT"
] | 1
|
2020-12-14T07:52:10.000Z
|
2020-12-14T07:52:10.000Z
|
src/LevelSetSeg.cpp
|
Bas94/SegmentationMethodsForMedicalImageAnalysis
|
c14514e76ca89eb6fc08374177809518d7762d64
|
[
"MIT"
] | 10
|
2017-10-18T14:27:29.000Z
|
2017-11-29T15:18:30.000Z
|
src/LevelSetSeg.cpp
|
Bas94/SegmentationMethodsForMedicalImageAnalysis
|
c14514e76ca89eb6fc08374177809518d7762d64
|
[
"MIT"
] | null | null | null |
#include "LevelSetSeg.h"
#include "itkGeodesicActiveContourLevelSetImageFilter.h"
#include "itkSigmoidImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
namespace LevelSetSeg
{
}
| 17.363636
| 56
| 0.816754
|
Bas94
|
55ee723a422e0db480a58c922697178bd51523bb
| 970
|
cpp
|
C++
|
atcoder/others/code_festival/2017/final/a.cpp
|
yu3mars/proconVSCodeGcc
|
fcf36165bb14fb6f555664355e05dd08d12e426b
|
[
"MIT"
] | null | null | null |
atcoder/others/code_festival/2017/final/a.cpp
|
yu3mars/proconVSCodeGcc
|
fcf36165bb14fb6f555664355e05dd08d12e426b
|
[
"MIT"
] | null | null | null |
atcoder/others/code_festival/2017/final/a.cpp
|
yu3mars/proconVSCodeGcc
|
fcf36165bb14fb6f555664355e05dd08d12e426b
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
#define m0(x) memset(x,0,sizeof(x))
int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1};
int main()
{
string s;
string a ="AKIHABARA";
cin>>s;
int n=s.size();
bool ok=true;
if(n>9)
{
ok=false;
}
else
{
int ap=0;
int sp=0;
while (sp<n && ap<9)
{
if(s[sp]==a[ap])
{
ap++;
sp++;
}
else if(a[ap]=='A')
{
ap++;
}
else
{
ok=false;
break;
}
}
if(sp<n) ok=false;
if(ap<8) ok=false;
}
if(ok) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return 0;
}
| 18.301887
| 58
| 0.380412
|
yu3mars
|
55ef18a71e9fbb2aadafc4d81253e75721ea77d6
| 6,460
|
cpp
|
C++
|
Source/Memory.cpp
|
EzraIII/witness-randomizer
|
8f3973faf182edc90c88a9e76b8bf3cf158819cf
|
[
"MIT"
] | null | null | null |
Source/Memory.cpp
|
EzraIII/witness-randomizer
|
8f3973faf182edc90c88a9e76b8bf3cf158819cf
|
[
"MIT"
] | null | null | null |
Source/Memory.cpp
|
EzraIII/witness-randomizer
|
8f3973faf182edc90c88a9e76b8bf3cf158819cf
|
[
"MIT"
] | null | null | null |
#include "Memory.h"
#include <psapi.h>
#include <tlhelp32.h>
#include <iostream>
#include <string>
#include <cassert>
#undef PROCESSENTRY32
#undef Process32Next
Memory::Memory(const std::wstring& processName) : _processName(processName) {}
Memory::~Memory() {
if (_threadActive) {
_threadActive = false;
_thread.join();
}
if (_handle != nullptr) {
for (uintptr_t addr : _allocations) VirtualFreeEx(_handle, (void*)addr, 0, MEM_RELEASE);
CloseHandle(_handle);
}
}
void Memory::StartHeartbeat(HWND window, std::chrono::milliseconds beat) {
if (_threadActive) return;
_threadActive = true;
_thread = std::thread([sharedThis = shared_from_this(), window, beat]{
while (sharedThis->_threadActive) {
sharedThis->Heartbeat(window);
std::this_thread::sleep_for(beat);
}
});
_thread.detach();
}
void Memory::Heartbeat(HWND window) {
if (!_handle && !Initialize()) {
// Couldn't initialize, definitely not running
PostMessage(window, WM_COMMAND, HEARTBEAT, (LPARAM)ProcStatus::NotRunning);
return;
}
DWORD exitCode = 0;
assert(_handle);
GetExitCodeProcess(_handle, &exitCode);
if (exitCode != STILL_ACTIVE) {
// Process has exited, clean up.
_computedAddresses.clear();
_handle = NULL;
PostMessage(window, WM_COMMAND, HEARTBEAT, (LPARAM)ProcStatus::NotRunning);
return;
}
#if GLOBALS == 0x5B28C0
int currentFrame = ReadData<int>({0x5BE3B0}, 1)[0];
#elif GLOBALS == 0x62D0A0
int currentFrame = ReadData<int>({0x63954C}, 1)[0];
#endif
int frameDelta = currentFrame - _previousFrame;
_previousFrame = currentFrame;
if (frameDelta < 0 && currentFrame < 250) {
// Some addresses (e.g. Entity Manager) may get re-allocated on newgame.
_computedAddresses.clear();
PostMessage(window, WM_COMMAND, HEARTBEAT, (LPARAM)ProcStatus::NewGame);
return;
}
// TODO: Some way to return ProcStatus::Randomized vs ProcStatus::NotRandomized vs ProcStatus::DeRandomized;
PostMessage(window, WM_COMMAND, HEARTBEAT, (LPARAM)ProcStatus::Running);
}
[[nodiscard]]
bool Memory::Initialize() {
// First, get the handle of the process
PROCESSENTRY32W entry;
entry.dwSize = sizeof(entry);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
while (Process32NextW(snapshot, &entry)) {
if (_processName == entry.szExeFile) {
_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
break;
}
}
if (!_handle) {
std::cerr << "Couldn't find " << _processName.c_str() << ", is it open?" << std::endl;
return false;
}
// Next, get the process base address
DWORD numModules;
std::vector<HMODULE> moduleList(1024);
EnumProcessModulesEx(_handle, &moduleList[0], static_cast<DWORD>(moduleList.size()), &numModules, 3);
std::wstring name(64, '\0');
for (DWORD i = 0; i < numModules / sizeof(HMODULE); i++) {
int length = GetModuleBaseNameW(_handle, moduleList[i], &name[0], static_cast<DWORD>(name.size()));
name.resize(length);
if (_processName == name) {
_baseAddress = (uintptr_t)moduleList[i];
break;
}
}
if (_baseAddress == 0) {
std::cerr << "Couldn't locate base address" << std::endl;
return false;
}
return true;
}
void Memory::AddSigScan(const std::vector<byte>& scanBytes, const std::function<void(int index)>& scanFunc)
{
_sigScans[scanBytes] = {scanFunc, false};
}
int find(const std::vector<byte> &data, const std::vector<byte>& search, size_t startIndex = 0) {
for (size_t i=startIndex; i<data.size() - search.size(); i++) {
bool match = true;
for (size_t j=0; j<search.size(); j++) {
if (data[i+j] == search[j]) {
continue;
}
match = false;
break;
}
if (match) return static_cast<int>(i);
}
return -1;
}
int Memory::ExecuteSigScans()
{
for (int i=0; i<0x200000; i+=0x1000) {
std::vector<byte> data = ReadData<byte>({i}, 0x1100);
for (auto& [scanBytes, sigScan] : _sigScans) {
if (sigScan.found) continue;
int index = find(data, scanBytes);
if (index == -1) continue;
sigScan.scanFunc(i + index);
sigScan.found = true;
}
}
int notFound = 0;
for (auto it : _sigScans) {
if (it.second.found == false) notFound++;
}
return notFound;
}
void Memory::ThrowError() {
std::wstring message(256, '\0');
DWORD error = GetLastError();
int length = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error, 1024, &message[0], static_cast<DWORD>(message.size()), nullptr);
message.resize(length);
#ifndef NDEBUG
MessageBox(NULL, message.c_str(), L"Please tell darkid about this", MB_OK);
#endif
}
void* Memory::ComputeOffset(std::vector<int> offsets) {
// Leave off the last offset, since it will be either read/write, and may not be of type uintptr_t.
int final_offset = offsets.back();
offsets.pop_back();
uintptr_t cumulativeAddress = _baseAddress;
for (const int offset : offsets) {
cumulativeAddress += offset;
const auto search = _computedAddresses.find(cumulativeAddress);
// This is an issue with re-randomization. Always. Just disable it in debug mode!
#ifdef NDEBUG
if (search == std::end(_computedAddresses)) {
#endif
// If the address is not yet computed, then compute it.
uintptr_t computedAddress = 0;
if (bool result = !ReadProcessMemory(_handle, reinterpret_cast<LPVOID>(cumulativeAddress), &computedAddress, sizeof(uintptr_t), NULL)) {
ThrowError();
}
if (computedAddress == 0) { // Attempting to dereference a nullptr
ThrowError();
}
_computedAddresses[cumulativeAddress] = computedAddress;
#ifdef NDEBUG
}
#endif
cumulativeAddress = _computedAddresses[cumulativeAddress];
}
return reinterpret_cast<void*>(cumulativeAddress + final_offset);
}
| 33.128205
| 149
| 0.606811
|
EzraIII
|
55f0ac2acb4d8bb638cdcbb11613c91d8837daae
| 328
|
cpp
|
C++
|
lib/qos/qos_one_handler.cpp
|
pmqtt/pmq
|
49f4b87c6c6dc5adfe7feab4ef3b2b73e0c435fb
|
[
"Apache-2.0"
] | 2
|
2019-09-08T11:59:05.000Z
|
2019-12-04T09:29:43.000Z
|
lib/qos/qos_one_handler.cpp
|
pmqtt/pmq
|
49f4b87c6c6dc5adfe7feab4ef3b2b73e0c435fb
|
[
"Apache-2.0"
] | 11
|
2019-06-08T20:13:58.000Z
|
2019-12-17T12:03:01.000Z
|
lib/qos/qos_one_handler.cpp
|
pmqtt/pmq
|
49f4b87c6c6dc5adfe7feab4ef3b2b73e0c435fb
|
[
"Apache-2.0"
] | 2
|
2019-12-04T08:06:27.000Z
|
2021-06-03T21:24:40.000Z
|
//
// Created by pmqtt on 2019-07-06.
//
#include <lib/mqtt/mqtt_static_package.hpp>
#include "qos_one_handler.hpp"
void pmq::qos_one_handler::handle(std::shared_ptr<pmq::storage> & storage,pmq::mqtt_publish *msg) {
auto socket = msg->get_socket();
pmq::mqtt_puback ack(socket);
ack.send(msg->get_message_id());
}
| 25.230769
| 99
| 0.704268
|
pmqtt
|
55f24d1462553c75a09cc9f8dfa2e3082db86827
| 596
|
cpp
|
C++
|
labs/3/lab2/CodeFromLab/PlanetStruct.cpp
|
triffon/oop-2019-20
|
db199631d59ddefdcc0c8eb3d689de0095618f92
|
[
"MIT"
] | 19
|
2020-02-21T16:46:50.000Z
|
2022-01-26T19:59:49.000Z
|
labs/3/lab2/CodeFromLab/PlanetStruct.cpp
|
triffon/oop-2019-20
|
db199631d59ddefdcc0c8eb3d689de0095618f92
|
[
"MIT"
] | 1
|
2020-03-14T08:09:45.000Z
|
2020-03-14T08:09:45.000Z
|
labs/3/lab2/CodeFromLab/PlanetStruct.cpp
|
triffon/oop-2019-20
|
db199631d59ddefdcc0c8eb3d689de0095618f92
|
[
"MIT"
] | 11
|
2020-02-23T12:29:58.000Z
|
2021-04-11T08:30:12.000Z
|
#include "PlanetStruct.h"
#include <string.h>
#include <iostream>
PlanetStruct getPlanet(const char *name,
unsigned long long dist,
unsigned long long diam,
unsigned long long mass)
{
PlanetStruct result;
strcpy(result.name, name);
result.distance = dist;
result.diameter = diam;
result.mass = mass;
return result;
}
void printPlanet(PlanetStruct p)
{
std::cout << p.name << " "
<< p.distance << " "
<< p.diameter << " "
<< p.mass << std::endl;
}
| 22.923077
| 42
| 0.525168
|
triffon
|
55f92b7b8fe7e0c134cc7035905d65c5d8cbdc73
| 1,158
|
cc
|
C++
|
lib/src/test_connection_parameters.cc
|
MikaelSmith/pcp-test
|
7f830e0dc0d7128a5db3c660503f719cf80a5345
|
[
"Apache-2.0"
] | null | null | null |
lib/src/test_connection_parameters.cc
|
MikaelSmith/pcp-test
|
7f830e0dc0d7128a5db3c660503f719cf80a5345
|
[
"Apache-2.0"
] | 1
|
2016-09-09T10:56:21.000Z
|
2016-09-09T13:43:24.000Z
|
lib/src/test_connection_parameters.cc
|
MikaelSmith/pcp-test
|
7f830e0dc0d7128a5db3c660503f719cf80a5345
|
[
"Apache-2.0"
] | 4
|
2016-08-25T10:18:46.000Z
|
2021-03-26T11:47:21.000Z
|
#include <pcp-test/test_connection_parameters.hpp>
namespace pcp_test{
namespace connection_test_parameters {
const std::string NUM_RUNS {"num-runs"};
const std::string INTER_RUN_PAUSE_MS {"inter-run-pause-ms"};
const std::string NUM_ENDPOINTS {"num-endpoints"};
const std::string INTER_ENDPOINT_PAUSE_MS {"inter-endpoint-pause-ms"};
const std::string CONCURRENCY {"concurrency"};
const std::string ENDPOINTS_INCREMENT {"endpoints-increment"};
const std::string CONCURRENCY_INCREMENT {"concurrency-increment"};
const std::string RANDOMIZE_INTER_ENDPOINT_PAUSE {"randomize-inter-endpoint-pause"};
const std::string INTER_ENDPOINT_PAUSE_RNG_SEED {"inter-endpoint-pause-rng-seed"};
const std::string WS_CONNECTION_TIMEOUT_MS {"ws-connection-timeout-ms"};
const std::string WS_CONNECTION_CHECK_INTERVAL_S {"ws-connection-check-interval-s"};
const std::string ASSOCIATION_TIMEOUT_S {"association-timeout-s"};
const std::string ASSOCIATION_REQUEST_TTL_S {"association-request-ttl-s"};
const std::string PERSIST_CONNECTIONS {"persist-connections"};
const std::string SHOW_STATS {"show-stats"};
} // namespace connection_test_parameters
} // namespace pcp_test
| 48.25
| 84
| 0.801382
|
MikaelSmith
|
55fb962e26ea473cdcfb19eec98b40f639cd3a49
| 1,223
|
hpp
|
C++
|
Dev/stringbuilder.hpp
|
Joseph-Heetel/StringCppTemplateLib_Dev
|
dd9a9a3e4b23f4af21c7dda1e5423c66362885bc
|
[
"MIT"
] | null | null | null |
Dev/stringbuilder.hpp
|
Joseph-Heetel/StringCppTemplateLib_Dev
|
dd9a9a3e4b23f4af21c7dda1e5423c66362885bc
|
[
"MIT"
] | null | null | null |
Dev/stringbuilder.hpp
|
Joseph-Heetel/StringCppTemplateLib_Dev
|
dd9a9a3e4b23f4af21c7dda1e5423c66362885bc
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include "string.hpp"
namespace jht {
/// @brief Provides functionality to conveniently and efficiently chain strings together
class StringBuilder
{
private:
static const size_t BUFFERSIZE = 128;
static const size_t SINGLETHRESHHOLD = BUFFERSIZE / 4;
std::vector<String> m_Sections;
size_t m_Length;
String m_Buffer;
size_t m_BufferIndex;
void FlushBuffer();
public:
StringBuilder() : m_Sections(), m_Length(0), m_Buffer(String::MakeManaged('\0', BUFFERSIZE)), m_BufferIndex() {}
/// @brief Combined length of all string sections currently stored
size_t Length() const { return m_Length; }
/// @brief Append any value
template<typename T>
void Append(T value);
/// @brief Append any value. Followed by a newline
template<typename T>
void AppendLine(T value);
/// @brief Append any value
template<typename T>
StringBuilder& operator<<(T value);
template<>
void Append<const char*>(const char* cstr);
template<>
void Append<>(String str);
template<>
void Append<const String&>(const String& str);
template<>
void Append<char>(char c);
/// @brief Construct a managed string containing all inputs chained
String Build();
};
}
| 26.021277
| 114
| 0.713818
|
Joseph-Heetel
|
55fe1a21fdf4657aa0ea6064b0c3a3502809458a
| 9,966
|
hpp
|
C++
|
include/geometry/visualizeRviz.hpp
|
waterben/LineExtraction
|
d247de45417a1512a3bf5d0ffcd630d40ffb8798
|
[
"MIT"
] | 1
|
2020-06-12T13:30:56.000Z
|
2020-06-12T13:30:56.000Z
|
include/geometry/visualizeRviz.hpp
|
waterben/LineExtraction
|
d247de45417a1512a3bf5d0ffcd630d40ffb8798
|
[
"MIT"
] | null | null | null |
include/geometry/visualizeRviz.hpp
|
waterben/LineExtraction
|
d247de45417a1512a3bf5d0ffcd630d40ffb8798
|
[
"MIT"
] | null | null | null |
#ifndef _VISUALIZE_RVIZ_HPP_
#define _VISUALIZE_RVIZ_HPP_
#ifdef __cplusplus
#include <string>
#include <visualization_msgs/Marker.h>
#include <visualization_msgs/MarkerArray.h>
namespace lsfm {
template < class MyLine3Dsegment, class FT>
void visualizeLinesRviz(const std::vector<MyLine3Dsegment> line3Segments, const ros::Publisher marker_pub){
std::vector<std::string> markerText;
const std::vector<lsfm::Pose<FT>> robotPoses;
visualizeLinesRviz(line3Segments, markerText, marker_pub, robotPoses);
}
template < class MyLine3Dsegment, class FT >
void visualizeLinesRviz(const std::vector<MyLine3Dsegment> line3Segments, const std::vector<std::string> markerText, const ros::Publisher marker_pub, const std::vector<lsfm::Pose<FT>> robotPoses){
bool addText;
if(markerText.size() == line3Segments.size())
addText = true;
else
addText = false;
// %Tag(MARKER_INIT)%
visualization_msgs::MarkerArray marker_list;
visualization_msgs::Marker line_list;
line_list.header.frame_id = "world";
line_list.header.stamp = ros::Time::now();
line_list.ns = "points_and_lines";
line_list.action = visualization_msgs::Marker::ADD;
line_list.pose.orientation.w = 1.0;
// %EndTag(MARKER_INIT)%
// %Tag(DELETE_ALL_MARKER)%
visualization_msgs::Marker reset_marker_;
reset_marker_.header.frame_id = "world";
reset_marker_.header.stamp = ros::Time();
reset_marker_.action = 3; // In ROS-J: visualization_msgs::Marker::DELETEALL;
reset_marker_.id = 0;
// %EndTag(MARKER_INIT)%
// First Marker deletes all markers
marker_list.markers.push_back(reset_marker_);
// Start adding markers -------------------------------------
uint32_t markerId = 1;
// %Tag(ID)%
line_list.id = markerId++;
// %EndTag(ID)%
// %Tag(TYPE)%
line_list.type = visualization_msgs::Marker::LINE_LIST;
// %EndTag(TYPE)%
// %Tag(SCALE)%
// LINE_STRIP/LINE_LIST markers use only the x component of scale, for the line width
line_list.scale.x = 0.1;
// %EndTag(SCALE)%
// %Tag(COLOR)%
// Line list is red
line_list.color.r = 1.0;
line_list.color.a = 0.8;
// %EndTag(COLOR)%
// Create the vertices for the points and lines
for (uint32_t i = 0; i < line3Segments.size(); ++i)
{
// Line Segment
MyLine3Dsegment lineSegment = line3Segments[i];
lsfm::Vec3<FT> sp = lineSegment.startPoint();
lsfm::Vec3<FT> ep = lineSegment.endPoint();
geometry_msgs::Point p;
p.x = sp.x();
p.y = sp.z();
p.z = -sp.y();
line_list.points.push_back(p);
// The line list needs two points for each line
p.x = ep.x();
p.y = ep.z();
p.z = -ep.y() - 0.1;
line_list.points.push_back(p);
if(addText){
markerId++;
// Text marker
visualization_msgs::Marker text;
text.pose.position = p;
text.header.frame_id = "world";
text.header.stamp = ros::Time::now();
text.id = markerId;
text.ns = "points_and_lines";
text.action = visualization_msgs::Marker::ADD;
text.text = markerText[i];
text.pose.orientation.w = 1.0;
text.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
text.color.a = 1.0;
text.color.r = 1.0;
text.color.g = 1.0;
text.color.b = 1.0;
text.scale.z = 0.4;
marker_list.markers.push_back(text);
}
}
for (uint32_t i = 0; i < robotPoses.size(); ++i)
{
markerId++;
visualization_msgs::Marker pose;
geometry_msgs::Point origin;
origin.x = robotPoses[i].origin().x();
origin.y = robotPoses[i].origin().z();
origin.z = -robotPoses[i].origin().y();
pose.pose.position = origin;
pose.header.frame_id = "world";
pose.header.stamp = ros::Time::now();
pose.id = markerId;
pose.ns = "points_and_lines";
pose.action = visualization_msgs::Marker::ADD;
// pose.text = markerText[i];
pose.type = visualization_msgs::Marker::ARROW;
cv::Matx33<FT> convMat(robotPoses[i].rotM().data());
cv::Matx33<FT> rotZ(0,-1,0,1,0,0,0,0,1);
cv::Vec4<FT> q = quaternion(convMat*rotZ);
pose.pose.orientation.x = q[0];
pose.pose.orientation.y = q[1];
pose.pose.orientation.z = q[2];
pose.pose.orientation.w = q[3];
pose.color.a = 1.0;
pose.color.r = 0.0f;
pose.color.g = 1.0f;
pose.color.b = 0.0f;
pose.scale.x = 1.0f;
pose.scale.y = 0.2f;
pose.scale.z = 0.2f;
marker_list.markers.push_back(pose);
}
marker_list.markers.push_back(line_list);
marker_pub.publish(marker_list);
}
template < class MyPoint3D, class FT >
void visualizePointsRviz(const std::vector<MyPoint3D> points3D, const std::vector<std::string> markerText, const ros::Publisher marker_pub, const std::vector<lsfm::Pose<FT>> robotPoses){
bool addText;
if(markerText.size() == points3D.size())
addText = true;
else
addText = false;
// %Tag(MARKER_INIT)%
visualization_msgs::MarkerArray marker_list;
visualization_msgs::Marker sphere_list;
sphere_list.header.frame_id = "world";
sphere_list.header.stamp = ros::Time::now();
sphere_list.ns = "points_and_lines";
sphere_list.action = visualization_msgs::Marker::ADD;
sphere_list.pose.orientation.w = 1.0;
// %EndTag(MARKER_INIT)%
// %Tag(DELETE_ALL_MARKER)%
visualization_msgs::Marker reset_marker_;
reset_marker_.header.frame_id = "world";
reset_marker_.header.stamp = ros::Time();
reset_marker_.action = 3; // In ROS-J: visualization_msgs::Marker::DELETEALL;
reset_marker_.id = 0;
// %EndTag(MARKER_INIT)%
// First Marker deletes all markers
marker_list.markers.push_back(reset_marker_);
// Start adding markers -------------------------------------
uint32_t markerId = 1;
// %Tag(ID)%
sphere_list.id = markerId++;
// %EndTag(ID)%
// %Tag(TYPE)%
sphere_list.type = visualization_msgs::Marker::SPHERE_LIST;
// %EndTag(TYPE)%
// %Tag(SCALE)%
// LINE_STRIP/LINE_LIST markers use only the x component of scale, for the line width
sphere_list.scale.x = 0.5;
sphere_list.scale.y = 0.5;
// %EndTag(SCALE)%
// %Tag(COLOR)%
// Line list is red
sphere_list.color.r = 1.0;
sphere_list.color.a = 0.8;
// %EndTag(COLOR)%
// Create the vertices for the points and lines
for (uint32_t i = 0; i < points3D.size(); ++i)
{
// Line Segment
MyPoint3D point = points3D[i];
geometry_msgs::Point p;
p.x = point.point.x();
p.y = point.point.z();
p.z = -point.point.y();
sphere_list.points.push_back(p);
if(addText){
markerId++;
// Text marker
visualization_msgs::Marker text;
text.pose.position = p;
text.header.frame_id = "world";
text.header.stamp = ros::Time::now();
text.id = markerId;
text.ns = "points_and_lines";
text.action = visualization_msgs::Marker::ADD;
text.text = markerText[i];
text.pose.orientation.w = 1.0;
text.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
text.color.a = 1.0;
text.color.r = 1.0;
text.color.g = 1.0;
text.color.b = 1.0;
text.scale.z = 0.4;
marker_list.markers.push_back(text);
}
}
for (uint32_t i = 0; i < robotPoses.size(); ++i)
{
markerId++;
visualization_msgs::Marker pose;
geometry_msgs::Point origin;
origin.x = robotPoses[i].origin().x();
origin.y = robotPoses[i].origin().z();
origin.z = -robotPoses[i].origin().y();
pose.pose.position = origin;
pose.header.frame_id = "world";
pose.header.stamp = ros::Time::now();
pose.id = markerId;
pose.ns = "points_and_lines";
pose.action = visualization_msgs::Marker::ADD;
// pose.text = markerText[i];
pose.type = visualization_msgs::Marker::ARROW;
cv::Matx33<FT> convMat(robotPoses[i].rotM().data());
cv::Matx33<FT> rotZ(0,-1,0,1,0,0,0,0,1);
cv::Vec4<FT> q = quaternion(convMat*rotZ);
pose.pose.orientation.x = q[0];
pose.pose.orientation.y = q[1];
pose.pose.orientation.z = q[2];
pose.pose.orientation.w = q[3];
pose.color.a = 1.0;
pose.color.r = 0.0f;
pose.color.g = 1.0f;
pose.color.b = 0.0f;
pose.scale.x = 1.0f;
pose.scale.y = 0.2f;
pose.scale.z = 0.2f;
marker_list.markers.push_back(pose);
}
marker_list.markers.push_back(sphere_list);
marker_pub.publish(marker_list);
}
}
#endif
#endif
| 32.462541
| 200
| 0.536825
|
waterben
|
360a4e0c443d4b1e1bed41cd51426a1b6a4a762a
| 4,134
|
cpp
|
C++
|
ige/src/asset/Texture.cpp
|
Arcahub/ige
|
b9f61209c924c7b683d2429a07e76251e6eb7b1b
|
[
"MIT"
] | 3
|
2021-06-05T00:36:50.000Z
|
2022-02-27T10:23:53.000Z
|
ige/src/asset/Texture.cpp
|
Arcahub/ige
|
b9f61209c924c7b683d2429a07e76251e6eb7b1b
|
[
"MIT"
] | 11
|
2021-05-08T22:00:24.000Z
|
2021-11-11T22:33:43.000Z
|
ige/src/asset/Texture.cpp
|
Arcahub/ige
|
b9f61209c924c7b683d2429a07e76251e6eb7b1b
|
[
"MIT"
] | 4
|
2021-05-20T12:41:23.000Z
|
2021-11-09T14:19:18.000Z
|
#include "igepch.hpp"
#include "ige/asset/Texture.hpp"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_FAILURE_USERMSG
#include "stb_image.h"
#include <cerrno>
#include <cstddef>
#include <cstring>
#include <filesystem>
#include <fstream>
using ige::asset::Texture;
Texture::Texture(Format format, std::size_t width, std::size_t height)
: m_format(format)
, m_width(width)
, m_height(height)
, m_pixels(width * height)
{
}
Texture::Texture(std::span<const std::byte> image_data)
{
load(image_data);
m_version = 0;
}
Texture::Texture(const std::filesystem::path& path)
{
load(path);
m_version = 0;
}
std::size_t Texture::width() const
{
return m_width;
}
std::size_t Texture::height() const
{
return m_height;
}
std::uint8_t Texture::channels() const
{
switch (m_format) {
case Texture::Format::RGBA:
return 4;
case Texture::Format::RGB:
return 3;
case Texture::Format::RG:
return 2;
case Texture::Format::R:
return 1;
default:
return 0;
}
}
std::span<const std::byte> Texture::data() const
{
return m_pixels;
}
std::uint64_t Texture::version() const
{
return m_version;
}
Texture::Format Texture::format() const
{
return m_format;
}
Texture::MagFilter Texture::mag_filter() const
{
return m_mag_filter;
}
Texture::MinFilter Texture::min_filter() const
{
return m_min_filter;
}
Texture::WrappingMode Texture::wrap_s() const
{
return m_wrap_s;
}
Texture::WrappingMode Texture::wrap_t() const
{
return m_wrap_t;
}
void Texture::set_mag_filter(MagFilter value)
{
m_mag_filter = value;
}
void Texture::set_min_filter(MinFilter value)
{
m_min_filter = value;
}
void Texture::set_wrap_s(WrappingMode value)
{
m_wrap_s = value;
}
void Texture::set_wrap_t(WrappingMode value)
{
m_wrap_t = value;
}
void Texture::set_data(
Format format, std::size_t width, std::size_t height,
std::vector<std::byte> pixels)
{
m_format = format;
if (pixels.size() < width * height * channels()) {
throw std::runtime_error("Pixel buffer is too small.");
}
m_version++;
m_width = width;
m_height = height;
m_pixels = std::move(pixels);
}
void Texture::load(std::span<const std::byte> buffer)
{
int width;
int height;
int channels;
unsigned char* data = stbi_load_from_memory(
reinterpret_cast<const unsigned char*>(buffer.data()),
static_cast<int>(buffer.size()), &width, &height, &channels, 0);
if (!data) {
throw std::runtime_error(stbi_failure_reason());
} else if (channels < 1 || channels > 4) {
stbi_image_free(data);
throw std::runtime_error(
"Invalid channel count (" + std::to_string(channels) + ")");
}
const Texture::Format formats[] = {
Format::R,
Format::RG,
Format::RGB,
Format::RGBA,
};
try {
std::byte* bytes = reinterpret_cast<std::byte*>(data);
set_data(
formats[channels - 1], width, height,
{ bytes, bytes + width * height * channels });
} catch (...) {
stbi_image_free(data);
throw;
}
stbi_image_free(data);
}
static std::vector<std::byte> read_file(const std::filesystem::path& path)
{
std::ifstream ifs(path, std::ios::binary | std::ios::ate);
if (!ifs) {
throw std::runtime_error(path.string() + ": " + std::strerror(errno));
}
auto end = ifs.tellg();
ifs.seekg(0, std::ios::beg);
auto size = std::size_t(end - ifs.tellg());
if (size == 0) {
throw std::runtime_error(path.string() + ": file is empty");
}
std::vector<std::byte> buffer(size);
if (!ifs.read(reinterpret_cast<char*>(buffer.data()), buffer.size())) {
throw std::runtime_error(path.string() + ": " + std::strerror(errno));
}
return buffer;
}
void Texture::load(const std::filesystem::path& path)
{
auto buffer = read_file(path);
try {
load(buffer);
} catch (const std::exception& e) {
throw std::runtime_error(path.string() + ": " + e.what());
}
}
| 19.971014
| 78
| 0.619981
|
Arcahub
|
361029e1cb1172698f778e4766c21af6648e6cae
| 4,000
|
cc
|
C++
|
lib/jflags_deprecated.cc
|
jaydee-io/jflags
|
2c4e6387345faf502f8048f749d0c850276ec1a7
|
[
"BSD-3-Clause"
] | null | null | null |
lib/jflags_deprecated.cc
|
jaydee-io/jflags
|
2c4e6387345faf502f8048f749d0c850276ec1a7
|
[
"BSD-3-Clause"
] | null | null | null |
lib/jflags_deprecated.cc
|
jaydee-io/jflags
|
2c4e6387345faf502f8048f749d0c850276ec1a7
|
[
"BSD-3-Clause"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
// jflags
//
// This file is distributed under the 3-clause Berkeley Software Distribution
// License. See LICENSE.txt for details.
////////////////////////////////////////////////////////////////////////////////
#include "jflags_deprecated.h"
#include "jflags_parser.h"
#include "FlagSaver.h"
#include "FlagRegistry.h"
#include "CommandLineFlagParser.h"
#include <string>
namespace JFLAGS_NAMESPACE {
using std::string;
string ReadFileIntoString(const char * filename);
// --------------------------------------------------------------------
// CommandlineFlagsIntoString()
// ReadFlagsFromString()
// AppendFlagsIntoFile()
// ReadFromFlagsFile()
// These are mostly-deprecated routines that stick the
// commandline flags into a file/string and read them back
// out again. I can see a use for CommandlineFlagsIntoString,
// for creating a flagfile, but the rest don't seem that useful
// -- some, I think, are a poor-man's attempt at FlagSaver --
// and are included only until we can delete them from callers.
// Note they don't save --flagfile flags (though they do save
// the result of having called the flagfile, of course).
// --------------------------------------------------------------------
static string TheseCommandlineFlagsIntoString(const vector<CommandLineFlagInfo> & flags)
{
vector<CommandLineFlagInfo>::const_iterator i;
size_t retval_space = 0;
for (i = flags.begin(); i != flags.end(); ++i)
// An (over)estimate of how much space it will take to print this flag
retval_space += i->name.length() + i->current_value.length() + 5;
string retval;
retval.reserve(retval_space);
for (i = flags.begin(); i != flags.end(); ++i)
{
retval += "--";
retval += i->name;
retval += "=";
retval += i->current_value;
retval += "\n";
}
return retval;
}
string CommandlineFlagsIntoString()
{
vector<CommandLineFlagInfo> sorted_flags;
GetAllFlags(&sorted_flags);
return TheseCommandlineFlagsIntoString(sorted_flags);
}
bool ReadFlagsFromString(const string & flagfilecontents,
const char * /*prog_name*/, // TODO(csilvers): nix this
bool errors_are_fatal)
{
FlagRegistry * const registry = FlagRegistry::GlobalRegistry();
FlagSaver saved_states;
CommandLineFlagParser parser(registry);
registry->Lock();
parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE);
registry->Unlock();
// Should we handle --help and such when reading flags from a string? Sure.
HandleCommandLineHelpFlags();
if (parser.ReportErrors())
{
// Error. Restore all global flags to their previous values.
if (errors_are_fatal)
jflags_exitfunc(1);
return false;
}
saved_states.discard();
return true;
}
// TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName()
bool AppendFlagsIntoFile(const string & filename, const char * prog_name)
{
FILE * fp;
if (SafeFOpen(&fp, filename.c_str(), "a") != 0)
return false;
if (prog_name)
fprintf(fp, "%s\n", prog_name);
vector<CommandLineFlagInfo> flags;
GetAllFlags(&flags);
// But we don't want --flagfile, which leads to weird recursion issues
vector<CommandLineFlagInfo>::iterator i;
for (i = flags.begin(); i != flags.end(); ++i)
{
if (strcmp(i->name.c_str(), "flagfile") == 0)
{
flags.erase(i);
break;
}
}
fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str());
fclose(fp);
return true;
}
bool ReadFromFlagsFile(const string & filename, const char * prog_name, bool errors_are_fatal)
{
return ReadFlagsFromString(ReadFileIntoString(filename.c_str()), prog_name, errors_are_fatal);
}
} // namespace JFLAGS_NAMESPACE
| 32.258065
| 98
| 0.612
|
jaydee-io
|
3610661d48e0e9a68747c83923327db3e5d7de84
| 1,031
|
cpp
|
C++
|
server/Server/Packets/WGRetSceneDataHandler.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | 3
|
2018-06-19T21:37:38.000Z
|
2021-07-31T21:51:40.000Z
|
server/Server/Packets/WGRetSceneDataHandler.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | null | null | null |
server/Server/Packets/WGRetSceneDataHandler.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | 13
|
2015-01-30T17:45:06.000Z
|
2022-01-06T02:29:34.000Z
|
#include "stdafx.h"
#include "WGRetSceneData.h"
#include "Log.h"
#include "ServerManager.h"
#include "Scene.h"
#include "SceneManager.h"
UINT WGRetSceneDataHandler::Execute( WGRetSceneData* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION
if( pPlayer->IsServerPlayer() )
{//服务器收到世界服务器发来的数据
Assert( MyGetCurrentThreadID()==g_pServerManager->m_ThreadID ) ;
SceneID_t SceneID = pPacket->GetSceneID() ;
Scene* pScene = g_pSceneManager->GetScene( SceneID ) ;
if( pScene == NULL )
{
Assert(FALSE) ;
return PACKET_EXE_CONTINUE ;
}
pScene->m_SceneInitData = *pPacket->GetSceneInitData() ;
pScene->Init( ) ;
//通知城市创建人,城市已经成功创建
pScene->SetSceneStatus( SCENE_STATUS_INIT ) ;
}
else
{
Assert(FALSE) ;
}
g_pLog->FastSaveLog( LOG_FILE_1, "WGRetSceneDataHandler: SceneID=%d",
pPacket->GetSceneID() ) ;
return PACKET_EXE_CONTINUE ;
__LEAVE_FUNCTION
return PACKET_EXE_ERROR ;
}
| 21.93617
| 79
| 0.632396
|
viticm
|
36108101864ac34d81ba74b20544631749d40515
| 4,059
|
cpp
|
C++
|
cpp/chinesePostman/chinesePostman.cpp
|
indy256/codelibrary-sandbox
|
fd49b2de1cf578084f222a087a472f0760a4fa4d
|
[
"Unlicense"
] | 6
|
2018-04-20T22:58:22.000Z
|
2021-03-25T13:09:57.000Z
|
cpp/chinesePostman/chinesePostman.cpp
|
indy256/codelibrary-sandbox
|
fd49b2de1cf578084f222a087a472f0760a4fa4d
|
[
"Unlicense"
] | null | null | null |
cpp/chinesePostman/chinesePostman.cpp
|
indy256/codelibrary-sandbox
|
fd49b2de1cf578084f222a087a472f0760a4fa4d
|
[
"Unlicense"
] | 2
|
2018-06-05T18:30:17.000Z
|
2018-11-14T16:56:19.000Z
|
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <utility>
#include <queue>
#include <functional>
#include <cstdlib>
#include <climits>
#include <sstream>
#include <cctype>
#include <complex>
#include <numeric>
#include <cassert>
using namespace std;
int d[60][60];
const long long OO = 1000000000000000LL;
typedef vector<int> VI;
typedef vector<long long> VD;
/* returns the maximum weight perfect matching on a complete bipartite graph */
/* matching[i] contains the 0-based number of the second set that has been matched to i */
/* runtime: O(V^3) */
long long MaxWeightPerfectMatching( vector<VD> &val, VI &matching ) {
int n = val.size();
vector< int > matched( n, -1 );
matching.assign( n, -1 );
vector< long long > l1( n, OO ), l2( n, -OO );
for( int k = 0; k < n; k++ ) {
vector< int > s( n, 0 ), t( n, 0 );
vector< long long > slick( n, OO );
vector< int > pred( n );
for( int i = 0; i < n; i++ ) // unmatched nodes -> S
if( matching[i] < 0 ) {
for( int j = 0; j < n; j++ )
slick[j] <?= l1[i] + l2[j] - val[i][j];
s[i] = 1;
}
int j_min = -1;
while( j_min == -1 ) {
long long slick_min = OO;
for( int j = 0; j < n; j++ )
if( !t[j] && ( slick[j] < slick_min ) )
slick_min = slick[j], j_min = j;
assert(j_min>=0);
for( int i = 0; i < n; i++ ) { // update labels
if( s[i] ) l1[i] -= slick_min;
if( t[i] ) l2[i] += slick_min;
else slick[i] -= slick_min;
if( s[i] && l1[i] + l2[j_min] == val[i][j_min] )
pred[j_min] = i;
}
if( matched[ j_min ] >= 0 ) { // matching exists already
t[j_min] = 1, s[matched[j_min]] = 1;
for( int j = 0; j < n; j++ ) // update slick
slick[j]<?=l1[matched[j_min]]+l2[j]-val[matched[j_min]][j];
j_min = -1;
}
}
while( j_min >= 0 ) {
int i = pred[j_min], j = j_min;
j_min = matching[i];
matching[i] = j, matched[j] = i;
}
}
long long weight = 0;
for( int i = 0; i < n; i++ ) weight += val[i][matching[i]];
return weight;
}
char needvisit[60];
char visit[60];
int n;
void dfs(int cur) {
if (visit[cur])
return;
visit[cur] = 1;
for (int i=0; i<n; ++i)
if (d[cur][i])
dfs(i);
}
class SnowPlow {
public:
int solve(vector <string> roads) {
n = roads.size();
int indeg[60] = {0}, outdeg[60] = {0};
int res = 0;
for (int i=0; i<n; ++i)
for (int j=0; j<n; ++j) {
if (roads[i][j] > '0') {
d[i][j] = 1;
needvisit[i] = needvisit[j] = 1;
}
else
d[i][j] = 0;
indeg[j] += roads[i][j]-'0';
outdeg[i] += roads[i][j]-'0';
res += roads[i][j] - '0';
}
dfs(0);
for (int i=0; i<n; ++i)
if (!visit[i] && needvisit[i])
return -1;
for (int i=0; i<n; ++i)
for (int j=0; j<n; ++j) {
if (!d[j][i]) continue;
for (int k=0; k<n; ++k) {
if (!d[i][k]) continue;
if (d[j][k] == 0 || d[j][k] < d[j][i] + d[i][k])
d[j][k] = d[j][i] + d[i][k];
}
}
vector<int> left, right;
for (int i=0; i<n; ++i) {
while(indeg[i] < outdeg[i]) {
right.push_back(i);
++indeg[i];
}
while(outdeg[i] < indeg[i]) {
left.push_back(i);
++outdeg[i];
}
}
assert(left.size() == right.size());
vector<VD> val(left.size(), VD(right.size(), -OO));
for (int i=0; i<(int)left.size(); ++i)
for (int j=0; j<(int)right.size(); ++j)
if (d[left[i]][right[j]] > 0)
val[i][j] = -d[left[i]][right[j]];
VI matching;
long long tres = -MaxWeightPerfectMatching(val, matching);
if (tres >= OO)
return -1;
return res + tres;
}
};
| 27.80137
| 91
| 0.476472
|
indy256
|
361562e0e8986078bfb3d2ab5006396b2e907940
| 279
|
cpp
|
C++
|
src/Z/Z119.cpp
|
wlhcode/lscct
|
7fd112a9d1851ddcf41886d3084381a52e84a3ce
|
[
"MIT"
] | null | null | null |
src/Z/Z119.cpp
|
wlhcode/lscct
|
7fd112a9d1851ddcf41886d3084381a52e84a3ce
|
[
"MIT"
] | null | null | null |
src/Z/Z119.cpp
|
wlhcode/lscct
|
7fd112a9d1851ddcf41886d3084381a52e84a3ce
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
long double c,d,e,f,g;
cin>>c>>d>>e>>f>>g;
cout<<setprecision(0)<<fixed<<(0.75+0.25*(c+d+e+f+g))*(2000*c+2500*d+3000*e+3500*f+4000*g)<<endl;
return 0;
}
| 21.461538
| 98
| 0.637993
|
wlhcode
|
36182b2be400f2c21efb859ed5c4b448c3cd8acb
| 5,551
|
cpp
|
C++
|
src/utils.cpp
|
typcn/LeanClub
|
a10b8adc927e7977ac89fe09223d34d7a7a6ac33
|
[
"MIT"
] | 263
|
2015-05-07T16:26:18.000Z
|
2022-03-14T13:34:25.000Z
|
src/utils.cpp
|
UnreliableBuilder/C-LeanClub
|
a10b8adc927e7977ac89fe09223d34d7a7a6ac33
|
[
"MIT"
] | 16
|
2015-05-28T10:53:24.000Z
|
2016-01-27T08:54:30.000Z
|
src/utils.cpp
|
UnreliableBuilder/C-LeanClub
|
a10b8adc927e7977ac89fe09223d34d7a7a6ac33
|
[
"MIT"
] | 61
|
2015-05-21T07:51:08.000Z
|
2022-01-28T11:52:42.000Z
|
//
// utils.cpp
// leanclub
//
// Created by TYPCN on 2015/5/1.
//
//
#include "utils.h"
#include "config.h"
#include "restclient/restclient.h"
#include "oauth/md5.h"
#include "redis3m/include/redis3m/redis3m.hpp"
#include <fstream>
#include <boost/filesystem.hpp>
#include <boost/thread/thread.hpp>
#include <boost/random/random_device.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace redis3m;
simple_pool::ptr_t pool;
simple_pool::ptr_t WritePool;
int online = -1;
void InitRedisPool(){
pool = simple_pool::create(REDIS_READ_IP);
WritePool = simple_pool::create(REDIS_MASTER_IP);
}
std::string randomStr(int len){
std::string chars("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
boost::random::random_device rng;
boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1);
std::string str;
for(int i = 0; i < len; ++i) {
str = str + chars[index_dist(rng)];
}
return str;
}
bool string_is_valid(const std::string &str)
{
return find_if(str.begin(), str.end(),
[](char c) { return !(isalnum(c)); }) == str.end();
}
char easytolower(char in){
if(in<='Z' && in>='A')
return in-('Z'-'z');
return in;
}
std::string GetGravatar(std::string email){
std::string data = email;
std::transform(data.begin(), data.end(), data.begin(), easytolower);
return GRAVATAR_BASE_URL + md5(data) + "?d=identicon";
}
std::string cookie_expries_time(time_t timestamp){
std::ostringstream ss;
ss.exceptions(std::ios_base::failbit);
boost::posix_time::ptime ptime = boost::posix_time::from_time_t(timestamp);
boost::posix_time::time_facet *facet = new boost::posix_time::time_facet("%a, %d-%b-%Y %T GMT");
ss.imbue(std::locale(std::locale::classic(), facet));
ss.str("");
ss << ptime;
return ss.str();
}
std::string SetSession(std::string content){
std::string sessionID = randomStr(SESSION_COOKIE_LENGTH);
connection::ptr_t c = WritePool->get();
c->run(command("SET")("SESS" + sessionID)(content));
WritePool->put(c);
std::string expries = cookie_expries_time(time(0) + (SESSION_COOKIE_EXPRIES));
return "LBSESSIONID=" + sessionID +
"; expires="+ expries +
"; path=/; domain=" SESSION_COOKIE_DOMAIN "; HttpOnly; Secure";
}
std::string GetSession(std::string cookie){
size_t loc = cookie.find("LBSESSIONID=");
if(loc == std::string::npos){
return "";
}else{
std::string sessid = cookie.substr(loc + 12,SESSION_COOKIE_LENGTH);
connection::ptr_t c = pool->get();
std::string session = c->run(command("GET")("SESS" + sessid)).str();
pool->put(c);
return session;
}
}
bool createFolder(std::string path){
boost::filesystem::path dir = boost::filesystem::system_complete(path);
if(!boost::filesystem::exists(dir)){
return boost::filesystem::create_directory(dir);
}
return true;
}
std::string getFileExt(std::string data){
if(data.find("image/jpeg") != std::string::npos){
return ".jpg";
}else if(data.find("image/png") != std::string::npos){
return ".png";
}else if(data.find("image/gif") != std::string::npos){
return ".gif";
}else if(data.find("image/jpg") != std::string::npos){
return ".jpg";
}else if(data.find("image/webp") != std::string::npos){
return ".webp";
}else if(data.find("image/x-ms-bmp") != std::string::npos){
return ".bmp";
}else if(data.find("image/tif") != std::string::npos){
return ".tif";
}else if(data.find("image/svg+xml") != std::string::npos){
return ".svg";
}else{
return "";
}
}
std::string SavePostFile(std::string postdata,std::string uid){
int start = postdata.find("\r\n\r\n") + 4;
int end = postdata.rfind("\r\n-");
if (start != std::string::npos && end != std::string::npos ){
std::string fileMeta = postdata.substr(0,200);
std::string fileData = postdata.substr(start,end-start);
if(fileData.length() > 50){
if(!createFolder("../attachments/" + uid)) return "create folder failed";
std::string filename = std::to_string(time(0)) + randomStr(6) + getFileExt(fileMeta);
std::ofstream ofile("../attachments/" + uid + "/" + filename, std::ios::binary);
ofile.write(fileData.c_str(),fileData.length());
ofile.close();
return uid + "/" + filename;
}
}
return "error";
}
void UpdateOnlineCount(){
while(1){
RestClient::response onlineinfo = RestClient::get("https://script.google.com/macros/s/AKfycbxQ0XJpdE669DlvQ9vSWGFp1iIoQsoqEnUBW_0K2sMaZ5lxazI/exec",false);
if(onlineinfo.code == 200){
online = std::stoi(onlineinfo.body);
if(online == 0){
online = 1;
}
}else{
online = -1;
}
boost::this_thread::sleep(boost::posix_time::seconds(300));
}
}
void InitOnlineCount(){
boost::thread t(&UpdateOnlineCount);
t.detach();
}
int GetOnlineCount(){
return online;
}
std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
return str;
}
| 30.168478
| 163
| 0.615925
|
typcn
|
361c596d6d29a03461adeb08507ad930003bf0c4
| 2,729
|
hpp
|
C++
|
source/modus_core/scene/SceneTree.hpp
|
Gurman8r/modus
|
5c97a89f77c1c5733793dddc20c5ce4afe1fd134
|
[
"MIT"
] | null | null | null |
source/modus_core/scene/SceneTree.hpp
|
Gurman8r/modus
|
5c97a89f77c1c5733793dddc20c5ce4afe1fd134
|
[
"MIT"
] | null | null | null |
source/modus_core/scene/SceneTree.hpp
|
Gurman8r/modus
|
5c97a89f77c1c5733793dddc20c5ce4afe1fd134
|
[
"MIT"
] | null | null | null |
#ifndef _ML_SCENE_TREE_HPP_
#define _ML_SCENE_TREE_HPP_
#include <modus_core/detail/Duration.hpp>
#include <modus_core/detail/Matrix.hpp>
#include <modus_core/scene/Node.hpp>
#include <modus_core/system/EventSystem.hpp>
#include <entt/entt.hpp>
namespace ml
{
struct entity;
struct ML_CORE_API scene_tree : non_copyable, trackable
{
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
public:
using allocator_type = typename pmr::polymorphic_allocator<byte>;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
public:
virtual ~scene_tree() noexcept override;
scene_tree(string const & name, allocator_type alloc = {}) noexcept
: m_name{ name.empty() ? "New Scene" : name, alloc }
, m_reg {}
, m_root{ _ML make_ref<node>(name, this, nullptr, alloc) }
{
}
scene_tree(scene_tree && other, allocator_type alloc = {}) noexcept
: m_name{ alloc }
, m_reg {}
, m_root{}
{
this->swap(std::move(other));
}
scene_tree & operator=(scene_tree && other) noexcept
{
this->swap(std::move(other));
return (*this);
}
void swap(scene_tree & other) noexcept
{
if (this != std::addressof(other))
{
std::swap(m_name, other.m_name);
std::swap(m_reg, other.m_reg);
std::swap(m_root, other.m_root);
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
public:
ML_NODISCARD auto get_name() const noexcept -> string const & { return m_name; }
ML_NODISCARD auto get_reg() noexcept -> entt::registry & { return m_reg; }
ML_NODISCARD auto get_reg() const noexcept -> entt::registry const & { return m_reg; }
ML_NODISCARD auto get_root() noexcept -> ref<node> & { return m_root; }
ML_NODISCARD auto get_root() const noexcept -> ref<node> const & { return m_root; }
void set_name(string const & name) noexcept { if (m_name != name) { m_name = name; } }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
public:
void on_runtime_update(duration dt);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
protected:
template <class T> void on_component_added(entity &, T &) {}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
private:
friend node;
friend entity;
string m_name ; // name
entt::registry m_reg ; // registry
ref<node> m_root ; // root node
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
};
}
namespace ml
{
inline void from_json(json const & j, scene_tree & v) noexcept {}
inline void to_json(json & j, scene_tree const & v) noexcept {}
}
#endif // !_ML_SCENE_TREE_HPP_
| 26.495146
| 88
| 0.532063
|
Gurman8r
|
361ec44caafd0e83f64d1e20577f767f9476eeab
| 1,249
|
cxx
|
C++
|
Applications/ColadaApp/StylePlugins/qColadaStylePlugin.cxx
|
TierraColada/Colada
|
c9d7ca30bfb5ec523722b35921c1e9e6a11a7914
|
[
"MIT"
] | null | null | null |
Applications/ColadaApp/StylePlugins/qColadaStylePlugin.cxx
|
TierraColada/Colada
|
c9d7ca30bfb5ec523722b35921c1e9e6a11a7914
|
[
"MIT"
] | null | null | null |
Applications/ColadaApp/StylePlugins/qColadaStylePlugin.cxx
|
TierraColada/Colada
|
c9d7ca30bfb5ec523722b35921c1e9e6a11a7914
|
[
"MIT"
] | null | null | null |
// Colada includes
#include "qColadaStylePlugin.h"
#include "qColadaStyle.h"
#include "qColadaDarkStyle.h"
#include "qColadaLightStyle.h"
// Qt includes
#include <QStringList>
#include <QStyle>
// --------------------------------------------------------------------------
// qColadaStylePlugin methods
//-----------------------------------------------------------------------------
qColadaStylePlugin::qColadaStylePlugin() = default;
//-----------------------------------------------------------------------------
qColadaStylePlugin::~qColadaStylePlugin() = default;
//-----------------------------------------------------------------------------
QStyle* qColadaStylePlugin::create( const QString & key )
{
if (key.compare("Colada", Qt::CaseInsensitive) == 0)
{
return new qColadaStyle();
}
if (key.compare("Light Colada", Qt::CaseInsensitive) == 0)
{
return new qColadaLightStyle();
}
if (key.compare("Dark Colada", Qt::CaseInsensitive) == 0)
{
return new qColadaDarkStyle();
}
return nullptr;
}
//-----------------------------------------------------------------------------
QStringList qColadaStylePlugin::keys() const
{
return QStringList() << "Colada" << "Light Colada" << "Dark Colada";
}
| 27.755556
| 79
| 0.472378
|
TierraColada
|
36215f8da755f7b074b410a6aa1ec73d18ffeef9
| 1,946
|
cc
|
C++
|
routines/test/latms.cc
|
luiscarbonell/nlapack
|
99d17f92f8f9bada17a89f72e8cc55486d848102
|
[
"MIT"
] | 1
|
2019-05-24T21:31:59.000Z
|
2019-05-24T21:31:59.000Z
|
routines/test/latms.cc
|
luiscarbonell/nlapack
|
99d17f92f8f9bada17a89f72e8cc55486d848102
|
[
"MIT"
] | null | null | null |
routines/test/latms.cc
|
luiscarbonell/nlapack
|
99d17f92f8f9bada17a89f72e8cc55486d848102
|
[
"MIT"
] | null | null | null |
#include "routines.h"
void dlatms(const v8::FunctionCallbackInfo<v8::Value>& info) {
lapack_int m = info[0]->Uint32Value();
lapack_int n = info[1]->Uint32Value();
char dist = info[2]->Uint32Value();
lapack_int *iseed = reinterpret_cast<lapack_int*>(GET_CONTENTS(info[3].As<v8::Int32Array>()));
char sym = info[4]->Uint32Value();
double *d = reinterpret_cast<double*>(GET_CONTENTS(info[5].As<v8::Float64Array>()));
lapack_int mode = info[6]->Uint32Value();
double cond = info[7]->NumberValue();
double dmax = info[8]->NumberValue();
lapack_int kl = info[9]->Uint32Value();
lapack_int ku = info[10]->Uint32Value();
char pack = info[11]->Uint32Value();
double *a = reinterpret_cast<double*>(GET_CONTENTS(info[12].As<v8::Float64Array>()));
lapack_int lda = info[13]->Uint32Value();
lapack_int i = LAPACKE_dlatms(LAPACK_ROW_MAJOR, m, n, dist, iseed, sym, d, mode, cond, dmax, kl, ku, pack, a, lda);
info.GetReturnValue().Set(
v8::Number::New(info.GetIsolate(), i)
);
}
void slatms(const v8::FunctionCallbackInfo<v8::Value>& info) {
lapack_int m = info[0]->Uint32Value();
lapack_int n = info[1]->Uint32Value();
char dist = info[2]->Uint32Value();
lapack_int *iseed = reinterpret_cast<lapack_int*>(GET_CONTENTS(info[3].As<v8::Int32Array>()));
char sym = info[4]->Uint32Value();
float *d = reinterpret_cast<float*>(GET_CONTENTS(info[5].As<v8::Float32Array>()));
lapack_int mode = info[6]->Uint32Value();
float cond = info[7]->NumberValue();
float dmax = info[8]->NumberValue();
lapack_int kl = info[9]->Uint32Value();
lapack_int ku = info[10]->Uint32Value();
char pack = info[11]->Uint32Value();
float *a = reinterpret_cast<float*>(GET_CONTENTS(info[12].As<v8::Float32Array>()));
lapack_int lda = info[13]->Uint32Value();
lapack_int i = LAPACKE_slatms(LAPACK_ROW_MAJOR, m, n, dist, iseed, sym, d, mode, cond, dmax, kl, ku, pack, a, lda);
info.GetReturnValue().Set(
v8::Number::New(info.GetIsolate(), i)
);
}
| 40.541667
| 116
| 0.690647
|
luiscarbonell
|
362923b666a155565d1ac1073f28e047f628ff76
| 729
|
cpp
|
C++
|
class/friend_2clases.cpp
|
AAI1234S/cpp
|
b0037406694712e647ad55c01f5d73764e5a54b3
|
[
"MIT"
] | null | null | null |
class/friend_2clases.cpp
|
AAI1234S/cpp
|
b0037406694712e647ad55c01f5d73764e5a54b3
|
[
"MIT"
] | null | null | null |
class/friend_2clases.cpp
|
AAI1234S/cpp
|
b0037406694712e647ad55c01f5d73764e5a54b3
|
[
"MIT"
] | null | null | null |
#include<iostream>
class NUM2; //class forward declaration
class NUM1
{
int num1;
public:
void add_data()
{
std::cout<<"Enter the num:"<<std::endl;
std::cin>>num1;
}
private:
friend void sum(NUM1 , NUM2); //friend function declration to communicate with another class
};
class NUM2
{
int num2;
public:
void add_data();
private:
friend void sum(NUM1, NUM2);
};
void NUM2::add_data()
{
std::cout<<"Enter the num2:"<<std::endl;
std::cin>>num2;
}
void sum(NUM1 ob1, NUM2 ob2) //friend function defination
{
std::cout<<ob1.num1<<" +"<<ob2.num2<<"="<<ob1.num1+ob2.num2;
}
int main()
{
NUM1 obj1;
NUM2 obj2;
obj1.add_data();
obj2.add_data();
sum(obj1, obj2); //friend function calling
return 0;
}
| 15.510638
| 96
| 0.654321
|
AAI1234S
|
3629ad56b2919990b6ddd86188e3f75626c2c7e8
| 659
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_E_EnforcerClimbingState_structs.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_E_EnforcerClimbingState_structs.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_E_EnforcerClimbingState_structs.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Basic.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Enums
//---------------------------------------------------------------------------
// UserDefinedEnum E_EnforcerClimbingState.E_EnforcerClimbingState
enum class E_EnforcerClimbingState : uint8_t
{
E_EnforcerClimbingState__NewEnumerator2 = 0,
E_EnforcerClimbingState__NewEnumerator0 = 1,
E_EnforcerClimbingState__NewEnumerator1 = 2,
E_EnforcerClimbingState__E_MAX = 3
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 19.969697
| 77
| 0.611533
|
2bite
|
362a30c2e786ff27c2b5e78f710402d6ef090f93
| 1,437
|
hpp
|
C++
|
src/continuousfusion.hpp
|
jhultman/continuous-fusion
|
1df1cc1488965fd5f101d66d1ca916a430d1dfd6
|
[
"MIT"
] | 25
|
2019-06-19T11:55:53.000Z
|
2022-02-28T07:56:38.000Z
|
src/continuousfusion.hpp
|
jhultman/continuous-fusion
|
1df1cc1488965fd5f101d66d1ca916a430d1dfd6
|
[
"MIT"
] | 1
|
2020-11-17T06:46:26.000Z
|
2021-11-04T11:49:38.000Z
|
src/continuousfusion.hpp
|
jhultman/continuous-fusion
|
1df1cc1488965fd5f101d66d1ca916a430d1dfd6
|
[
"MIT"
] | 4
|
2020-07-16T01:59:47.000Z
|
2022-02-28T06:41:14.000Z
|
#ifndef CONTINUOUSFUSION_HPP
#define CONTINUOUSFUSION_HPP
#include <vector>
#include <sensor_msgs/Image.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <image_transport/image_transport.h>
#include <message_filters/synchronizer.h>
#include <message_filters/subscriber.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/eigen.hpp>
#include <Eigen/Dense>
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::PointCloud2> KittiSyncPolicy;
class ContinuousFusion
{
private:
cv::Mat _PRT;
ros::NodeHandle _nh;
image_transport::ImageTransport _xport;
image_transport::Publisher _publisher;
message_filters::Subscriber<sensor_msgs::Image> _imageSub;
message_filters::Subscriber<sensor_msgs::PointCloud2> _veloSub;
message_filters::Synchronizer<KittiSyncPolicy> _sync;
Eigen::MatrixXf pcl2ToEigen(pcl::PCLPointCloud2 cloud);
pcl::PCLPointCloud2 rosMsgToPcl2(const sensor_msgs::PointCloud2ConstPtr& cloudPtr);
cv::Mat rosMsgToCvMat(const sensor_msgs::PointCloud2ConstPtr& cloudPtr);
void publishBevImage(cv::Mat bevImage);
public:
ContinuousFusion(cv::Mat PRT);
void callback(
const sensor_msgs::ImageConstPtr& imageIn,
const sensor_msgs::PointCloud2ConstPtr& veloIn);
};
#endif
| 35.925
| 118
| 0.746695
|
jhultman
|
1566dfe1662d7236050250c509af08ad25e2522f
| 863
|
cpp
|
C++
|
QtMario_Youtube-master/Mario_Updated/notebox.cpp
|
Rossterrrr/Qt
|
3e5c2934ce19675390d2ad6d513a14964d8cbe50
|
[
"MIT"
] | 3
|
2019-09-02T05:17:08.000Z
|
2021-01-07T11:21:34.000Z
|
notebox.cpp
|
hadimousavi79/Super_Mario
|
89e0656de26b561d3713c6265c8a4f8695e25d9b
|
[
"MIT"
] | null | null | null |
notebox.cpp
|
hadimousavi79/Super_Mario
|
89e0656de26b561d3713c6265c8a4f8695e25d9b
|
[
"MIT"
] | null | null | null |
/*
* Author: equati0n
* Date: December 2016
*/
#include "notebox.h"
#include <QPainter>
NoteBox::NoteBox(int length,QGraphicsItem *parent): QGraphicsItem(parent)
,mCurrentFrame(), mLength(length)
{
setFlag(ItemClipsToShape);
mPixmap10 = QPixmap(":images/notebox.png");
}
void NoteBox::nextFrame(){
mCurrentFrame += 65;
if (mCurrentFrame >= 518 ) {
mCurrentFrame = 0;
}
}
QRectF NoteBox::boundingRect() const {
return QRectF(0,0,63* mLength,63);
}
void NoteBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
Q_UNUSED(widget);
Q_UNUSED(option);
for(int i = 0; i < 63*mLength; ++i) {
painter->drawPixmap(i*63,0, mPixmap10, mCurrentFrame, 0,63, 63);
}
setTransformOriginPoint(boundingRect().center());
}
int NoteBox::type() const {
return Type;
}
| 19.177778
| 97
| 0.658169
|
Rossterrrr
|
15784a63fedae043b1001697730c2da316722d26
| 2,549
|
cpp
|
C++
|
include/lookup.cpp
|
jermp/sshash
|
480f1da593e4550422ce8ead6540b24485897641
|
[
"MIT"
] | 44
|
2022-01-13T18:53:51.000Z
|
2022-03-03T12:38:16.000Z
|
include/lookup.cpp
|
jermp/sshash
|
480f1da593e4550422ce8ead6540b24485897641
|
[
"MIT"
] | 2
|
2022-01-19T22:48:36.000Z
|
2022-03-10T14:32:57.000Z
|
include/lookup.cpp
|
jermp/sshash
|
480f1da593e4550422ce8ead6540b24485897641
|
[
"MIT"
] | 2
|
2022-01-14T13:35:14.000Z
|
2022-03-03T12:38:19.000Z
|
#pragma once
namespace sshash {
uint64_t dictionary::lookup_uint64_regular_parsing(uint64_t uint64_kmer) const {
uint64_t minimizer = util::compute_minimizer(uint64_kmer, m_k, m_m, m_seed);
uint64_t bucket_id = m_minimizers.lookup(minimizer);
if (m_skew_index.empty()) return m_buckets.lookup(bucket_id, uint64_kmer, m_k, m_m);
auto [begin, end] = m_buckets.locate_bucket(bucket_id);
uint64_t num_super_kmers_in_bucket = end - begin;
uint64_t log2_bucket_size = util::ceil_log2_uint32(num_super_kmers_in_bucket);
if (log2_bucket_size > m_skew_index.min_log2) {
uint64_t pos = m_skew_index.lookup(uint64_kmer, log2_bucket_size);
/* It must hold pos < num_super_kmers_in_bucket for the kmer to exist. */
if (pos < num_super_kmers_in_bucket) {
return m_buckets.lookup_in_super_kmer(begin + pos, uint64_kmer, m_k, m_m);
}
return constants::invalid;
}
return m_buckets.lookup(begin, end, uint64_kmer, m_k, m_m);
}
uint64_t dictionary::lookup_uint64_canonical_parsing(uint64_t uint64_kmer) const {
uint64_t uint64_kmer_rc = util::compute_reverse_complement(uint64_kmer, m_k);
uint64_t minimizer = util::compute_minimizer(uint64_kmer, m_k, m_m, m_seed);
uint64_t minimizer_rc = util::compute_minimizer(uint64_kmer_rc, m_k, m_m, m_seed);
uint64_t bucket_id = m_minimizers.lookup(std::min<uint64_t>(minimizer, minimizer_rc));
if (m_skew_index.empty()) {
return m_buckets.lookup_canonical(bucket_id, uint64_kmer, uint64_kmer_rc, m_k, m_m);
}
auto [begin, end] = m_buckets.locate_bucket(bucket_id);
uint64_t num_super_kmers_in_bucket = end - begin;
uint64_t log2_bucket_size = util::ceil_log2_uint32(num_super_kmers_in_bucket);
if (log2_bucket_size > m_skew_index.min_log2) {
uint64_t pos = m_skew_index.lookup(uint64_kmer, log2_bucket_size);
if (pos < num_super_kmers_in_bucket) {
uint64_t kmer_id = m_buckets.lookup_in_super_kmer(begin + pos, uint64_kmer, m_k, m_m);
if (kmer_id != constants::invalid) return kmer_id;
}
uint64_t pos_rc = m_skew_index.lookup(uint64_kmer_rc, log2_bucket_size);
if (pos_rc < num_super_kmers_in_bucket) {
uint64_t kmer_id =
m_buckets.lookup_in_super_kmer(begin + pos_rc, uint64_kmer_rc, m_k, m_m);
return kmer_id;
}
return constants::invalid;
}
return m_buckets.lookup_canonical(begin, end, uint64_kmer, uint64_kmer_rc, m_k, m_m);
}
} // namespace sshash
| 45.517857
| 98
| 0.717144
|
jermp
|
1578c32fefb79e85a0c5c7168be7b33053392c90
| 731
|
cpp
|
C++
|
src/YesNoAskerDialog.cpp
|
timre13/list-maker
|
ebedbfcefa626af98f746c16fd46f6dafa81d70b
|
[
"BSD-2-Clause"
] | null | null | null |
src/YesNoAskerDialog.cpp
|
timre13/list-maker
|
ebedbfcefa626af98f746c16fd46f6dafa81d70b
|
[
"BSD-2-Clause"
] | null | null | null |
src/YesNoAskerDialog.cpp
|
timre13/list-maker
|
ebedbfcefa626af98f746c16fd46f6dafa81d70b
|
[
"BSD-2-Clause"
] | null | null | null |
#include "YesNoAskerDialog.h"
YesNoAskerDialog::YesNoAskerDialog(const Glib::ustring &question, Gtk::ResponseType defaultButton/*=Gtk::ResponseType::RESPONSE_YES*/)
: m_textLabel{std::make_unique<Gtk::Label>()}
{
get_vbox()->add(*m_textLabel);
m_textLabel->set_text(question);
add_button("Yes", Gtk::ResponseType::RESPONSE_YES);
add_button("No", Gtk::ResponseType::RESPONSE_NO);
set_default_response(defaultButton);
show_all_children();
}
bool askYesNo(const Glib::ustring &question, Gtk::ResponseType defaultButton/*=Gtk::ResponseType::RESPONSE_YES*/)
{
auto dialog{std::make_unique<YesNoAskerDialog>(question, defaultButton)};
return dialog->run() == Gtk::ResponseType::RESPONSE_YES;
}
| 31.782609
| 134
| 0.737346
|
timre13
|
157978a127f42892396c050c73c757c334608391
| 11,926
|
cpp
|
C++
|
Qt-GL-Simple-Scene-master/libgizmo/save/GizmoTransformRenderDX9.cpp
|
nacsa/Retopology
|
03c009462db3d73dbb73ea543952d421ecc1416e
|
[
"Apache-2.0"
] | 107
|
2015-04-24T08:09:32.000Z
|
2022-02-21T16:57:18.000Z
|
Qt-GL-Simple-Scene-master/libgizmo/save/GizmoTransformRenderDX9.cpp
|
nacsa/Retopology
|
03c009462db3d73dbb73ea543952d421ecc1416e
|
[
"Apache-2.0"
] | 1
|
2019-04-24T07:44:27.000Z
|
2019-05-14T09:18:53.000Z
|
Qt-GL-Simple-Scene-master/libgizmo/save/GizmoTransformRenderDX9.cpp
|
nacsa/Retopology
|
03c009462db3d73dbb73ea543952d421ecc1416e
|
[
"Apache-2.0"
] | 34
|
2015-03-15T14:50:12.000Z
|
2022-01-23T07:18:05.000Z
|
///////////////////////////////////////////////////////////////////////////////////////////////////
// Zenith Engine
// File Name : GizmoTransform.h
// Creation : 12/07/2007
// Author : Cedric Guillemet
// Description :
//
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GizmoTransformRender.h"
#include <D3D9.h>
#ifdef WIN32
typedef struct {
float x;
float y;
float z;
tulong diffuse;
} PSM_LVERTEX;
IDirect3DVertexDeclaration9* GGizmoVertDecl = NULL;
#endif
void InitDecl()
{
#ifdef WIN32
if (!GGizmoVertDecl)
{
D3DVERTEXELEMENT9 decl1[] =
{
{ 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
{ 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 },
D3DDECL_END()
};
GDD->GetD3D9Device()->CreateVertexDeclaration( decl1, &GGizmoVertDecl );
}
GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_FALSE);
GDD->GetD3D9Device()->SetTexture(0,NULL);
GDD->GetD3D9Device()->SetTexture(1,NULL);
GDD->GetD3D9Device()->SetTexture(2,NULL);
GDD->GetD3D9Device()->SetTexture(3,NULL);
GDD->GetD3D9Device()->SetTexture(4,NULL);
GDD->GetD3D9Device()->SetTexture(5,NULL);
GDD->GetD3D9Device()->SetTexture(6,NULL);
GDD->GetD3D9Device()->SetTexture(7,NULL);
GDD->GetD3D9Device()->SetRenderState(D3DRS_COLORVERTEX , true);
//GDD->GetD3D9Device()->SetRenderState(D3DRS_LIGHTING , true);
GDD->GetD3D9Device()->SetRenderState(D3DRS_AMBIENT , 0xFFFFFFFF);
GDD->GetD3D9Device()->SetVertexShader(NULL);
GDD->GetD3D9Device()->SetPixelShader(NULL);
#endif
}
void CGizmoTransformRender::DrawCircle(const tvector3 &orig,float r,float g,float b, const tvector3 &vtx, const tvector3 &vty)
{
#ifdef WIN32
InitDecl();
PSM_LVERTEX svVts[51];
for (int i = 0; i <= 50 ; i++)
{
tvector3 vt;
vt = vtx * cos((2*ZPI/50)*i);
vt += vty * sin((2*ZPI/50)*i);
vt += orig;
svVts[i].diffuse = 0xFF000000 + (int(r*255.0f) << 16) + (int(g*255.0f) << 8) + (int(b*255.0f));
svVts[i].x = vt.x;
svVts[i].y = vt.y;
svVts[i].z = vt.z;
}
IDirect3DDevice9 *pDev = GDD->GetD3D9Device();
GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl);
GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINESTRIP , 50, svVts, sizeof(PSM_LVERTEX));
GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE);
#endif
}
void CGizmoTransformRender::DrawCircleHalf(const tvector3 &orig,float r,float g,float b,const tvector3 &vtx, const tvector3 &vty, tplane &camPlan)
{
#ifdef WIN32
InitDecl();
int inc = 0;
PSM_LVERTEX svVts[51];
for (int i = 0; i < 30 ; i++)
{
tvector3 vt;
vt = vtx * cos((ZPI/30)*i);
vt += vty * sin((ZPI/30)*i);
vt +=orig;
if (camPlan.DotNormal(vt))
{
svVts[inc].diffuse = 0xFF000000 + (int(r*255.0f) << 16) + (int(g*255.0f) << 8) + (int(b*255.0f));
svVts[inc].x = vt.x;
svVts[inc].y = vt.y;
svVts[inc].z = vt.z;
inc ++;
}
}
IDirect3DDevice9 *pDev = GDD->GetD3D9Device();
GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl);
GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINESTRIP , inc-1, svVts, sizeof(PSM_LVERTEX));
GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE);
#endif
}
void CGizmoTransformRender::DrawAxis(const tvector3 &orig, const tvector3 &axis, const tvector3 &vtx, const tvector3 &vty, float fct,float fct2, const tvector4 &col)
{
#ifdef WIN32
InitDecl();
PSM_LVERTEX svVts[100];
int inc = 0;
IDirect3DDevice9 *pDev = GDD->GetD3D9Device();
svVts[0].x = orig.x;
svVts[0].y = orig.y;
svVts[0].z = orig.z;
svVts[0].diffuse = 0xFF000000 + (int(col.x*255.0f) << 16) + (int(col.y*255.0f) << 8) + (int(col.z*255.0f));
svVts[1].x = orig.x + axis.x;
svVts[1].y = orig.y + axis.y;
svVts[1].z = orig.z + axis.z;
svVts[1].diffuse = svVts[0].diffuse;
GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl);
GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINELIST , 1, svVts, sizeof(PSM_LVERTEX));
//glBegin(GL_TRIANGLE_FAN);
for (int i=0;i<=30;i++)
{
tvector3 pt;
pt = vtx * cos(((2*ZPI)/30.0f)*i)*fct;
pt+= vty * sin(((2*ZPI)/30.0f)*i)*fct;
pt+=axis*fct2;
pt+=orig;
//glVertex3fv(&pt.x);
svVts[inc].x = pt.x;
svVts[inc].y = pt.y;
svVts[inc].z = pt.z;
svVts[inc++].diffuse = svVts[0].diffuse;
pt = vtx * cos(((2*ZPI)/30.0f)*(i+1))*fct;
pt+= vty * sin(((2*ZPI)/30.0f)*(i+1))*fct;
pt+=axis*fct2;
pt+=orig;
//glVertex3fv(&pt.x);
svVts[inc].x = pt.x;
svVts[inc].y = pt.y;
svVts[inc].z = pt.z;
svVts[inc++].diffuse = svVts[0].diffuse;
//glVertex3f(orig.x+axis.x,orig.y+axis.y,orig.z+axis.z);
svVts[inc].x = orig.x+axis.x;
svVts[inc].y = orig.y+axis.y;
svVts[inc].z = orig.z+axis.z;
svVts[inc++].diffuse = svVts[0].diffuse;
}
//glEnd();
GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl);
GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_TRIANGLEFAN , 91, svVts, sizeof(PSM_LVERTEX));
GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE);
#endif
}
void CGizmoTransformRender::DrawCamem(const tvector3& orig,const tvector3& vtx,const tvector3& vty,float ng)
{
#ifdef WIN32
InitDecl();
IDirect3DDevice9 *pDev = GDD->GetD3D9Device();
GDD->GetD3D9Device()->SetRenderState(D3DRS_SRCBLEND , D3DBLEND_SRCALPHA);
GDD->GetD3D9Device()->SetRenderState(D3DRS_DESTBLEND , D3DBLEND_INVSRCALPHA);
GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE );
PSM_LVERTEX svVts[52];
svVts[0].x = orig.x;
svVts[0].y = orig.y;
svVts[0].z = orig.z;
svVts[0].diffuse = 0x80FFFF00;
for (int i = 0 ; i <= 50 ; i++)
{
tvector3 vt;
vt = vtx * cos(((ng)/50)*i);
vt += vty * sin(((ng)/50)*i);
vt+=orig;
//glVertex3f(vt.x,vt.y,vt.z);
svVts[i+1].x = vt.x;
svVts[i+1].y = vt.y;
svVts[i+1].z = vt.z;
svVts[i+1].diffuse = svVts[0].diffuse;
}
GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl);
GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_TRIANGLEFAN , 50, svVts, sizeof(PSM_LVERTEX));
GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
for (int i = 0 ; i < 52 ; i++)
svVts[i].diffuse = 0xFFFFFF33;
GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl);
GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINESTRIP , 50, svVts, sizeof(PSM_LVERTEX));
GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE , D3DCULL_CCW );
GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE);
#endif
}
void CGizmoTransformRender::DrawQuad(const tvector3& orig, float size, bool bSelected, const tvector3& axisU, const tvector3 &axisV)
{
#ifdef WIN32
InitDecl();
IDirect3DDevice9 *pDev = GDD->GetD3D9Device();
GDD->GetD3D9Device()->SetRenderState(D3DRS_SRCBLEND , D3DBLEND_SRCALPHA);
GDD->GetD3D9Device()->SetRenderState(D3DRS_DESTBLEND , D3DBLEND_INVSRCALPHA);
GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE , D3DCULL_NONE );
PSM_LVERTEX svVts[5];
svVts[0].x = orig.x;
svVts[0].y = orig.y;
svVts[0].z = orig.z;
svVts[1].x = orig.x + (axisU.x * size);
svVts[1].y = orig.y + (axisU.y * size);
svVts[1].z = orig.z + (axisU.z * size);
svVts[2].x = orig.x + (axisV.x * size);
svVts[2].y = orig.y + (axisV.y * size);
svVts[2].z = orig.z + (axisV.z * size);
svVts[3].x = orig.x + (axisU.x + axisV.x)*size;
svVts[3].y = orig.y + (axisU.y + axisV.y)*size;
svVts[3].z = orig.z + (axisU.z + axisV.z)*size;
svVts[4].x = orig.x;
svVts[4].y = orig.y;
svVts[4].z = orig.z;
if (!bSelected)
svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0x80FFFF00;
else
svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xA0FFFFFF;
GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl);
GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP , 2, svVts, sizeof(PSM_LVERTEX));
if (!bSelected)
svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xFFFFFF30;
else
svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xA0FFFF90;
svVts[3].x = orig.x + (axisV.x * size);
svVts[3].y = orig.y + (axisV.y * size);
svVts[3].z = orig.z + (axisV.z * size);
svVts[2].x = orig.x + (axisU.x + axisV.x)*size;
svVts[2].y = orig.y + (axisU.y + axisV.y)*size;
svVts[2].z = orig.z + (axisU.z + axisV.z)*size;
GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl);
GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINESTRIP , 4, svVts, sizeof(PSM_LVERTEX));
GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE , D3DCULL_CCW );
GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE);
#endif
}
void CGizmoTransformRender::DrawTri(const tvector3& orig, float size, bool bSelected, const tvector3& axisU, const tvector3& axisV)
{
#ifdef WIN32
InitDecl();
IDirect3DDevice9 *pDev = GDD->GetD3D9Device();
GDD->GetD3D9Device()->SetRenderState(D3DRS_SRCBLEND , D3DBLEND_SRCALPHA);
GDD->GetD3D9Device()->SetRenderState(D3DRS_DESTBLEND , D3DBLEND_INVSRCALPHA);
GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE , D3DCULL_NONE );
tvector3 pts[3];
pts[0] = orig;
pts[1] = (axisU );
pts[2] = (axisV );
pts[1]*=size;
pts[2]*=size;
pts[1]+=orig;
pts[2]+=orig;
PSM_LVERTEX svVts[4];
svVts[0].x = pts[0].x;
svVts[0].y = pts[0].y;
svVts[0].z = pts[0].z;
svVts[1].x = pts[1].x;
svVts[1].y = pts[1].y;
svVts[1].z = pts[1].z;
svVts[2].x = pts[2].x;
svVts[2].y = pts[2].y;
svVts[2].z = pts[2].z;
svVts[3].x = pts[0].x;
svVts[3].y = pts[0].y;
svVts[3].z = pts[0].z;
if (!bSelected)
svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0x80FFFF00;
else
svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xA0FFFFFF;
GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl);
GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_TRIANGLELIST , 1, svVts, sizeof(PSM_LVERTEX));
if (!bSelected)
svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xFFFFFF30;
else
svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xA0FFFF90;
GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl);
GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINESTRIP , 3, svVts, sizeof(PSM_LVERTEX));
GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE , D3DCULL_CCW );
GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE);
#endif
}
| 34.368876
| 165
| 0.633909
|
nacsa
|
1579fe0fefe2671a307901bd63be785d42e902e0
| 18,664
|
cpp
|
C++
|
src/ui/qt5/mainwindow.cpp
|
chenyvehtung/Agenda
|
9e35c67b692bfcc9c4af31a5a4d43ba97e6f0f7a
|
[
"MIT"
] | 3
|
2016-10-20T08:19:45.000Z
|
2017-06-18T04:34:53.000Z
|
src/ui/qt5/mainwindow.cpp
|
donydchen/Agenda
|
9e35c67b692bfcc9c4af31a5a4d43ba97e6f0f7a
|
[
"MIT"
] | null | null | null |
src/ui/qt5/mainwindow.cpp
|
donydchen/Agenda
|
9e35c67b692bfcc9c4af31a5a4d43ba97e6f0f7a
|
[
"MIT"
] | null | null | null |
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "loginwindow.h"
#include <QMessageBox>
#include <QStandardItemModel>
#include <Qt>
#include <QAction>
#include <QIcon>
using std::string;
using std::list;
MainWindow::MainWindow(QWidget *parent) :
ui(new Ui::MainWindow), QMainWindow(parent)
{
ui->setupUi(this);
//set table view to be uneditable
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
//display current time in status bar
curTime = new QLabel(" SYSTEM TIME: " + QTime::currentTime().toString("hh:mm:ss"), ui->statusBar);
curTime->setFixedWidth(300);
startTimer(1000);
initToolbar();
setFixedSize(size());
QIcon::setThemeName("ubuntu-mono-dark");
}
void MainWindow::updateWin(string username, string password,
AgendaService *agendaService) {
// update property
userName_ = username;
userPassword_ = password;
agendaService_ = agendaService;
btnStatus = BtnStatus::Query;
// update window title and toolbar text
string buffer;
buffer = "Logout User \"" + userName_ + "\"";
ui->actionLogout->setText(buffer.c_str());
buffer = "Delete User \"" + userName_ + "\"";
ui->actionDelete->setText(buffer.c_str());
buffer = "Agenda (" + agendaService_->getServiceName()
+ ") : " + userName_;
setWindowTitle(buffer.c_str());
//set up the homepage
buffer = "Welcome " + userName_;
ui->wel_label->setText(buffer.c_str());
showPage(PageType::HomePage);
}
/*
* Add button to toolbar
*/
void MainWindow::initToolbar() {
//ui->toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
QString curPath = QCoreApplication::applicationDirPath();
// home
QAction *tbHome = ui->toolBar->addAction(QIcon(curPath + "/resources/user-home.gif"), "Home");
connect(tbHome, SIGNAL(triggered()), this, SLOT(on_actionHome_triggered()));
ui->toolBar->addSeparator();
// list all user
QAction *tbList = ui->toolBar->addAction(QIcon(curPath + "/resources/go-down.gif"), "List Users");
connect(tbList, SIGNAL(triggered()), this, SLOT(on_actionList_triggered()));
// create meeting
QAction *tbCreate = ui->toolBar->addAction(QIcon(curPath + "/resources/document-new.gif"), "Create Meeting");
connect(tbCreate, SIGNAL(triggered()), this, SLOT(on_actionCreate_A_Meeting_triggered()));
// delete meeting
QAction *tbDel = ui->toolBar->addAction(QIcon(curPath + "/resources/edit-delete.gif"), "Delete Meeting");
connect(tbDel, SIGNAL(triggered()), this, SLOT(on_actionDelete_A_Meeting_triggered()));
// search meeting
QAction *tbSearch = ui->toolBar->addAction(QIcon(curPath + "/resources/edit-find.gif"), "Search Meeting");
connect(tbSearch, SIGNAL(triggered()), this, SLOT(on_actionQuery_Meeting_By_Title_triggered()));
ui->toolBar->addSeparator();
// log out
QAction *tbLogout = ui->toolBar->addAction(QIcon(curPath + "/resources/system-log-out.gif"), "Log Out");
connect(tbLogout, SIGNAL(triggered()), this, SLOT(on_actionLogout_triggered()));
}
MainWindow::~MainWindow()
{
//agendaService_->quitAgenda();
delete ui;
delete curTime;
}
/**
* @brief MainWindow::on_actionHome_triggered
* go to homepage
*/
void MainWindow::on_actionHome_triggered()
{
showPage(PageType::HomePage);
}
void MainWindow::on_actionLogout_triggered()
{
string content = "Do you really want to logout " + userName_ + "?";
int ans = QMessageBox::question(NULL, "Logout User",
content.c_str(),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if (ans == QMessageBox::Yes) {
emit mainWinClose();
hide();
}
}
void MainWindow::on_actionDelete_triggered()
{
string content = "Do you really want to delete " + userName_ + "?";
int ans = QMessageBox::question(NULL, "Delete User",
content.c_str(),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if (ans == QMessageBox::Yes) {
if (agendaService_->deleteUser(userName_, userPassword_)) {
content = "Successfully delete user " + userName_ +
"<br>Click OK to continue...";
QMessageBox::information(NULL, "Delete Succeed",
content.c_str(),
QMessageBox::Ok);
emit mainWinClose();
hide();
}
else {
content = "Fail to delete user " + userName_;
QMessageBox::warning(NULL, "Delete Failed", content.c_str());
}
}
}
void MainWindow::on_actionExit_triggered()
{
//agendaService_->quitAgenda();
qApp->closeAllWindows();
}
/**
* @brief MainWindow::on_actionList_triggered
* to list all user in Agenda
*/
void MainWindow::on_actionList_triggered()
{
//ui->tableView->hide();
list<User> users = agendaService_->listAllUsers();
if (!users.empty()) {
int rows = users.size();
QStandardItemModel *model = new QStandardItemModel(rows, 3, this);
model->setHorizontalHeaderItem(0, new QStandardItem(QString("Name")));
model->setHorizontalHeaderItem(1, new QStandardItem(QString("Email")));
model->setHorizontalHeaderItem(2, new QStandardItem(QString("Phone")));
list<User>::iterator it;
int i;
for (i = 0, it = users.begin(); it != users.end(); ++i, ++it) {
QStandardItem *nameItem = new QStandardItem(QString(it->getName().c_str()));
QStandardItem *emailItem = new QStandardItem(QString(it->getEmail().c_str()));
QStandardItem *phoneItem = new QStandardItem(QString(it->getPhone().c_str()));
model->setItem(i, 0, nameItem);
model->setItem(i, 1, emailItem);
model->setItem(i, 2, phoneItem);
}
ui->tableView->setModel(model);
// set table to be auto expended
for (int c = 0; c < ui->tableView->horizontalHeader()->count(); ++c)
{
ui->tableView->horizontalHeader()->setSectionResizeMode(
c, QHeaderView::Stretch);
}
showPage(PageType::TableView);
}
else {
QMessageBox::information(NULL, "List User", "Sorry, no user exist!", QMessageBox::Ok);
showPage(PageType::HomePage);
}
}
/**
* @brief MainWindow::on_actionList_All_Meetings_triggered
* list all meetings
*/
void MainWindow::on_actionList_All_Meetings_triggered()
{
//ui->tableView->hide();
list<Meeting> meetings = agendaService_->listAllMeetings(userName_);
if (!meetings.empty()) {
printMeetings(meetings);
}
else {
QMessageBox::information(NULL, "List Meetings", "Sorry, no meeting exist", QMessageBox::Ok);
showPage(PageType::HomePage);
}
}
/**
* @brief MainWindow::on_actionList_All_Sponsor_Meetings_triggered
* slot to find out all the sponsor meeting of the log in user
*/
void MainWindow::on_actionList_All_Sponsor_Meetings_triggered()
{
list<Meeting> meetings = agendaService_->listAllSponsorMeetings(userName_);
if (!meetings.empty()) {
printMeetings(meetings);
}
else {
QMessageBox::information(NULL, "List Meetings", "Sorry, no sponsor meeting exist", QMessageBox::Ok);
showPage(HomePage);
}
}
/**
* @brief MainWindow::on_actionList_All_Participant_Meetings_triggered
* slot to find out all participator meetings of the log in user
*/
void MainWindow::on_actionList_All_Participant_Meetings_triggered()
{
//ui->tableView->hide();
list<Meeting> meetings = agendaService_->listAllParticipateMeetings(userName_);
if (!meetings.empty()) {
printMeetings(meetings);
}
else {
QMessageBox::information(NULL, "List Meetings", "Sorry, no participate meeting exist", QMessageBox::Ok);
showPage(PageType::HomePage);
}
}
/**
* @brief MainWindow::on_actionCreate_A_Meeting_triggered
*/
void MainWindow::on_actionCreate_A_Meeting_triggered()
{
// add users to participator combo box
list<User> users = agendaService_->listAllUsers();
list<User>::iterator it;
ui->parComboBox->clear();
for (it = users.begin(); it != users.end(); ++it) {
string user = it->getName();
if (user != userName_)
ui->parComboBox->addItem(QString::fromStdString(user));
}
// set up date time picker yyyy-mm-dd/hh:mm
ui->startDT->setCalendarPopup(true);
ui->startDT->setDateTime(QDateTime::currentDateTime());
ui->startDT->setDisplayFormat("MMMM dd,yyyy hh:mm");
ui->endDT->setCalendarPopup(true);
ui->endDT->setDateTime(QDateTime::currentDateTime());
ui->endDT->setDisplayFormat("MMMM dd,yyyy hh:mm");
// show the widget
showPage(PageType::CreateMT);
}
/**
* @brief MainWindow::on_crtMtBtn_clicked
* create a meeting
*/
void MainWindow::on_crtMtBtn_clicked()
{
string title = ui->mtTitle->text().toUtf8().constData();
string participator = ui->parComboBox->currentText().toUtf8().constData();
string startTime = ui->startDT->dateTime().toString("yyyy-MM-dd/hh:mm").toUtf8().constData();
string endTime = ui->endDT->dateTime().toString("yyyy-MM-dd/hh:mm").toUtf8().constData();
if (agendaService_->createMeeting(userName_, title, participator, startTime, endTime)) {
QMessageBox::information(NULL, "Create Meeting", "Successfully create a meeting!",
QMessageBox::Ok);
showPage(PageType::HomePage);
}
else {
QMessageBox::critical(NULL, "Create Meeting", "Sorry, failed to create the meeeting!");
}
}
/**
* @brief MainWindow::on_actionDelete_A_Meeting_triggered
* delete a meeting accroding to the given name
*/
void MainWindow::on_actionDelete_A_Meeting_triggered()
{
showPage(PageType::SearchTitle);
btnStatus = BtnStatus::Delete;
}
/**
* @brief MainWindow::on_actionDelete_All_Meetings_triggered
* Delete all the meeting connect to the log in user
*/
void MainWindow::on_actionDelete_All_Meetings_triggered()
{
int ans = QMessageBox::question(NULL, "Delete Meetings",
"Do you really want to delete ALL the meetings?",
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if (ans == QMessageBox::Yes) {
if (agendaService_->deleteAllMeetings(userName_)) {
QMessageBox::information(NULL, "Delete Meetings", "Successfully deleted all the meeting!");
}
else {
QMessageBox::critical(NULL, "Delete Meetings", "Failed to delete all meetings:(");
}
}
}
/**
* @brief MainWindow::on_actionQuery_Meeting_By_Title_triggered
*/
void MainWindow::on_actionQuery_Meeting_By_Title_triggered()
{
showPage(PageType::SearchTitle);
btnStatus = BtnStatus::Query;
}
/**
* @brief MainWindow::on_actionQuery_Meeting_By_Time_Interval_triggered
* query meeting exist in the provided time interval
*/
void MainWindow::on_actionQuery_Meeting_By_Time_Interval_triggered()
{
// set up date time picker yyyy-mm-dd/hh:mm
ui->startDT_2->setCalendarPopup(true);
ui->startDT_2->setDateTime(QDateTime::currentDateTime());
ui->startDT_2->setDisplayFormat("MMMM dd,yyyy hh:mm");
ui->endDT_2->setCalendarPopup(true);
ui->endDT_2->setDateTime(QDateTime::currentDateTime());
ui->endDT_2->setDisplayFormat("MMMM dd,yyyy hh:mm");
//show the time interval search widget
showPage(PageType::SearchTime);
}
/**
* @brief MainWindow::on_searchBtn_clicked
* to search a meeting according to the title
*/
void MainWindow::on_searchBtn_clicked()
{
string title = ui->searchTitle->text().toUtf8().constData();
//search the meeting anyhow
list<Meeting> meetings = agendaService_->meetingQuery(userName_, title);
if (meetings.empty()) {
QMessageBox::critical(NULL, "No Meeting", "Sorry but no such meeting");
}
else {
// if it is to delete a meeting by its title
if (btnStatus == BtnStatus::Delete) {
string content = "Do you really want to delete meeting \"" + title + "\"?";
int ans = QMessageBox::question(NULL, "Delete Meeting", content.c_str(),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if (ans == QMessageBox::Yes) {
if (agendaService_->deleteMeeting(userName_, title)) {
QMessageBox::information(NULL, "Delete Meeting",
"Successfully delete the meetings!");
on_actionHome_triggered();
}
else {
QMessageBox::critical(NULL, "Delete Meeting", "Failed to delete the meeting!");
}
}
}
//if it is to query a meeting by title
else if (btnStatus == BtnStatus::Query) {
//show the meeting in the tableView
int rows = meetings.size();
QStandardItemModel *model = new QStandardItemModel(rows, 4, this);
model->setHorizontalHeaderItem(0, new QStandardItem(QString("Sponsor")));
model->setHorizontalHeaderItem(1, new QStandardItem(QString("Participator")));
model->setHorizontalHeaderItem(2, new QStandardItem(QString("Start Time")));
model->setHorizontalHeaderItem(3, new QStandardItem(QString("End Time")));
list<Meeting>::iterator it;
int i;
for (i = 0, it = meetings.begin(); it != meetings.end(); ++i, ++it) {
QStandardItem *sponsorItem = new QStandardItem(QString(it->getSponsor().c_str()));
QStandardItem *partiItem = new QStandardItem(QString(it->getParticipator().c_str()));
QStandardItem *startItem = new QStandardItem(QString(Date::dateToString(it->getStartDate()).c_str()));
QStandardItem *endItem = new QStandardItem(QString(Date::dateToString(it->getEndDate()).c_str()));
model->setItem(i, 0, sponsorItem);
model->setItem(i, 1, partiItem);
model->setItem(i, 2, startItem);
model->setItem(i, 3, endItem);
}
ui->tableView->setModel(model);
// set table to be auto expended
for (int c = 0; c < ui->tableView->horizontalHeader()->count(); ++c)
{
ui->tableView->horizontalHeader()->setSectionResizeMode(
c, QHeaderView::Stretch);
}
showPage(PageType::TableView);
}
else {
//do nothing
}
}
}
/**
* @brief MainWindow::on_searchBtn_2_clicked
* to search meeting according to the provided time interval
*/
void MainWindow::on_searchBtn_2_clicked()
{
string startTime = ui->startDT_2->dateTime().toString("yyyy-MM-dd/hh:mm").toUtf8().constData();
string endTime = ui->endDT_2->dateTime().toString("yyyy-MM-dd/hh:mm").toUtf8().constData();
list<Meeting> meetings = agendaService_->meetingQuery(userName_, startTime, endTime);
if (!meetings.empty()) {
printMeetings(meetings);
}
else {
string content = "Sorry, no meeting exist during <br>" + startTime + " ~ " + endTime;
QMessageBox::warning(NULL, "Query Meetings", content.c_str());
}
}
void MainWindow::on_actionAbout_triggered()
{
QMessageBox::about(NULL, "Agenda", "Agenda is a simple app writen by Donald<br>1st Oct. 2016<br>May 2017: Update, add SQLite3 Backend");
}
/**
* @brief MainWindow::printMeetings
* @param meetings
* An assitant function to print the meetings
*/
void MainWindow::printMeetings(std::list<Meeting> meetings) {
int rows = meetings.size();
QStandardItemModel *model = new QStandardItemModel(rows, 5, this);
model->setHorizontalHeaderItem(0, new QStandardItem(QString("Title")));
model->setHorizontalHeaderItem(1, new QStandardItem(QString("Sponsor")));
model->setHorizontalHeaderItem(2, new QStandardItem(QString("Participator")));
model->setHorizontalHeaderItem(3, new QStandardItem(QString("Start Time")));
model->setHorizontalHeaderItem(4, new QStandardItem(QString("End Time")));
list<Meeting>::iterator it;
int i;
for (i = 0, it = meetings.begin(); it != meetings.end(); ++i, ++it) {
QStandardItem *titleItem = new QStandardItem(QString(it->getTitle().c_str()));
QStandardItem *sponsorItem = new QStandardItem(QString(it->getSponsor().c_str()));
QStandardItem *partiItem = new QStandardItem(QString(it->getParticipator().c_str()));
QStandardItem *startItem = new QStandardItem(QString(Date::dateToString(it->getStartDate()).c_str()));
QStandardItem *endItem = new QStandardItem(QString(Date::dateToString(it->getEndDate()).c_str()));
model->setItem(i, 0, titleItem);
model->setItem(i, 1, sponsorItem);
model->setItem(i, 2, partiItem);
model->setItem(i, 3, startItem);
model->setItem(i, 4, endItem);
}
ui->tableView->setModel(model);
// set table to be auto expended
for (int c = 0; c < ui->tableView->horizontalHeader()->count(); ++c)
{
ui->tableView->horizontalHeader()->setSectionResizeMode(
c, QHeaderView::Stretch);
}
showPage(PageType::TableView);
}
/**
* @brief MainWindow::showPage
* Hide all other widget and show the widget according to the pageType
*/
void MainWindow::showPage(PageType pageType) {
ui->tableView->hide();
ui->createmtwidget->hide();
ui->searchwidget->hide();
ui->searchwidget_2->hide();
ui->welcomewidget->hide();
ui->opTitle->hide();
switch(pageType) {
case PageType::HomePage:
ui->welcomewidget->show(); break;
case PageType::TableView:
ui->tableView->show(); break;
case PageType::CreateMT:
ui->opTitle->setText("Create Meeting");
ui->opTitle->show();
ui->createmtwidget->show(); break;
case PageType::SearchTitle:
ui->opTitle->setText("Search");
ui->opTitle->show();
ui->searchwidget->show(); break;
case PageType::SearchTime:
ui->opTitle->setText("Search");
ui->opTitle->show();
ui->searchwidget_2->show(); break;
default:
ui->welcomewidget->show();
}
}
/**
* @brief MainWindow::timerEvent
* @param event
* update current time in status bar
*/
void MainWindow::timerEvent(QTimerEvent *) {
curTime->setText(" SYSTEM TIME: " + QTime::currentTime().toString("hh:mm:ss"));
}
| 35.686424
| 140
| 0.635502
|
chenyvehtung
|
157a2b6659db6262f316bce087c4dc65ac464e90
| 107
|
cpp
|
C++
|
SerPrunesALot/SerPrunesALot/Move.cpp
|
DennisSoemers/SerPrunesALot
|
34f0277fec58cf1f837df8f31ed14c62a945811c
|
[
"MIT"
] | null | null | null |
SerPrunesALot/SerPrunesALot/Move.cpp
|
DennisSoemers/SerPrunesALot
|
34f0277fec58cf1f837df8f31ed14c62a945811c
|
[
"MIT"
] | null | null | null |
SerPrunesALot/SerPrunesALot/Move.cpp
|
DennisSoemers/SerPrunesALot
|
34f0277fec58cf1f837df8f31ed14c62a945811c
|
[
"MIT"
] | null | null | null |
#include "Move.h"
Move::Move(int from, int to, bool captured)
: from(from), to(to), captured(captured)
{}
| 21.4
| 43
| 0.672897
|
DennisSoemers
|
157d5b03d796cd7fa1e41784e4274ff88acedb5b
| 4,954
|
cpp
|
C++
|
src/Sense.cpp
|
danielkaldheim/sense-library
|
25e2786618d0ed5171d283e66e4bad25a2295570
|
[
"MIT"
] | null | null | null |
src/Sense.cpp
|
danielkaldheim/sense-library
|
25e2786618d0ed5171d283e66e4bad25a2295570
|
[
"MIT"
] | null | null | null |
src/Sense.cpp
|
danielkaldheim/sense-library
|
25e2786618d0ed5171d283e66e4bad25a2295570
|
[
"MIT"
] | null | null | null |
#include "Sense.h"
Preferences preferences;
Sense::~Sense()
{
// preferences.end();
}
Sense::Sense()
{
preferences.begin(PREFERENCES_KEY, false);
}
bool Sense::begin(void)
{
preferences.begin(PREFERENCES_KEY, false);
return true;
}
String Sense::getChipName()
{
uint64_t chipid = ESP.getEfuseMac();
char chipName[32];
sprintf(chipName, "-%04X",
(uint16_t)(chipid >> 32));
return String(STR(PROJECT)) + chipName;
}
String Sense::getDeviceName()
{
return getString("deviceName", getChipName());
}
void Sense::setDeviceName(String value)
{
putString("deviceName", value);
}
String Sense::getWiFiMac()
{
return WiFi.macAddress();
}
String Sense::getLocalIp()
{
return WiFi.localIP().toString();
}
String Sense::getWiFiSSID()
{
return getString("wifi-ssid", STR(WIFI_SSID));
}
void Sense::setWiFiSSID(String value)
{
putString("wifi-ssid", value);
}
String Sense::getWiFiPwd()
{
return getString("wifi-pwd", STR(WIFI_SSID_PWD));
}
void Sense::setWiFiPwd(String value)
{
putString("wifi-pwd", value);
}
String Sense::getDevice()
{
return getString("deviceId");
}
void Sense::setDevice(String value)
{
putString("deviceId", value);
}
String Sense::getRoom()
{
return getString("roomId");
}
void Sense::setRoom(String value)
{
putString("roomId", value);
}
String Sense::getFloor()
{
return getString("floor");
}
void Sense::setFloor(String value)
{
putString("floor", value);
}
String Sense::getTenant()
{
return getString("tenantId");
}
void Sense::setTenant(String value)
{
putString("tenantId", value);
}
String Sense::getMQTTTopic()
{
String tenantID = getTenant();
String deviceID = getDevice();
if (!tenantID.isEmpty() && !deviceID.isEmpty())
{
return String(STR(PROJECT)) + "/" + deviceID + "/";
}
uint64_t chipid = ESP.getEfuseMac();
char chipName[32];
sprintf(chipName, "/%04X/",
(uint16_t)(chipid >> 32));
return getString("mqtt-topic", String(STR(PROJECT)) + chipName);
}
void Sense::setMQTTTopic(String value)
{
putString("mqtt-topic", value);
}
String Sense::getMQTTHost()
{
return getString("mqtt-host", STR(MQTT_HOST));
}
void Sense::setMQTTHost(String value)
{
putString("mqtt-host", value);
}
uint16_t Sense::getMQTTPort()
{
preferences.begin(PREFERENCES_KEY, false);
return preferences.getUShort("mqtt-port", 1883);
}
void Sense::setMQTTPort(uint16_t value)
{
preferences.begin(PREFERENCES_KEY, false);
preferences.putUShort("mqtt-port", value);
}
String Sense::getMQTTUser()
{
return getString("mqtt-user", STR(MQTT_USER));
}
void Sense::setMQTTUser(String value)
{
putString("mqtt-user", value);
}
String Sense::getMQTTPwd()
{
return getString("mqtt-pwd", STR(MQTT_PWD));
}
void Sense::setMQTTPwd(String value)
{
putString("mqtt-pwd", value);
}
String Sense::getCrudusToken()
{
return getString("token");
}
void Sense::setCrudusToken(String value)
{
putString("token", value);
}
float Sense::getCaliTemp()
{
return getFloat("cali-temp", 3.5f);
}
void Sense::setCaliTemp(float value)
{
putFloat("cali-temp", value);
}
bool Sense::checkIAQState(size_t maxLen)
{
preferences.begin(PREFERENCES_KEY, false);
return preferences.getBytesLength("bsecState") == maxLen;
}
void Sense::getIAQState(uint8_t *state, size_t maxLen)
{
preferences.begin(PREFERENCES_KEY, false);
preferences.getBytes("bsecState", state, maxLen);
}
void Sense::setIAQState(const void *bsecState, size_t maxLen)
{
preferences.begin(PREFERENCES_KEY, false);
preferences.putBytes("bsecState", bsecState, maxLen);
}
void Sense::clearIAQState()
{
preferences.begin(PREFERENCES_KEY, false);
preferences.remove("bsecState");
}
Preferences *Sense::getPreferences()
{
preferences.begin(PREFERENCES_KEY, false);
return &preferences;
}
String Sense::getString(const char *key, const String defaultValue)
{
preferences.begin(PREFERENCES_KEY, false);
return preferences.getString(key, defaultValue);
}
uint32_t Sense::getUInt(const char *key, const uint32_t defaultValue)
{
preferences.begin(PREFERENCES_KEY, false);
return preferences.getUInt(key, defaultValue);
}
float_t Sense::getFloat(const char *key, const float_t defaultValue)
{
preferences.begin(PREFERENCES_KEY, false);
return preferences.getFloat(key, defaultValue);
}
size_t Sense::putString(const char *key, String value)
{
preferences.begin(PREFERENCES_KEY, false);
return preferences.putString(key, value);
}
size_t Sense::putUInt(const char *key, uint32_t value)
{
preferences.begin(PREFERENCES_KEY, false);
return preferences.putUInt(key, value);
}
size_t Sense::putFloat(const char *key, float_t value)
{
preferences.begin(PREFERENCES_KEY, false);
return preferences.putFloat(key, value);
}
bool Sense::clearPreferences()
{
return preferences.clear();
}
| 18.69434
| 69
| 0.690553
|
danielkaldheim
|
157d5dd525cb3f4b5f98390236e2a121add34777
| 685
|
cc
|
C++
|
P9 Data Structure (tuples)/P84786.cc
|
miquelt9/Problemes-PRO1
|
1bd5214ce75129e9a027728b93ad8354ec993e41
|
[
"Apache-2.0"
] | 2
|
2021-09-01T10:52:32.000Z
|
2021-11-09T09:19:57.000Z
|
P9 Data Structure (tuples)/P84786.cc
|
miquelt9/Problemes-PRO1
|
1bd5214ce75129e9a027728b93ad8354ec993e41
|
[
"Apache-2.0"
] | null | null | null |
P9 Data Structure (tuples)/P84786.cc
|
miquelt9/Problemes-PRO1
|
1bd5214ce75129e9a027728b93ad8354ec993e41
|
[
"Apache-2.0"
] | 1
|
2021-09-24T20:00:41.000Z
|
2021-09-24T20:00:41.000Z
|
#include <typeinfo>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
struct Punt {
double x, y;
};
struct Cercle {
Punt centre;
double radi;
};
double distancia(const Punt& a, const Punt& b){
double x = abs(a.x - b.x);
double y = abs(a.y - b.y);
double dist = sqrt(pow(x, 2) + pow(y, 2));
return dist;
}
void desplaca(Punt& p1, const Punt& p2){
p1.x += p2.x;
p1.y += p2.y;
}
void escala(Cercle& c, double esc){
c.radi *= esc;
}
void desplaca(Cercle& c, const Punt& p){
c.centre.x += p.x;
c.centre.y += p.y;
}
bool es_interior(const Punt& p, const Cercle& c){
if(distancia(p, c.centre) < c.radi) return true;
return false;
}
| 17.564103
| 50
| 0.620438
|
miquelt9
|
157dedc0ab16822309615dede51157455c5f3fd2
| 11,995
|
cc
|
C++
|
src/iocontrollers/pcie_controller.cc
|
werneazc/mcpat
|
fcd4d650709423f24bdad8d3cc302001e10e1f7d
|
[
"Intel"
] | 1
|
2020-05-25T00:34:01.000Z
|
2020-05-25T00:34:01.000Z
|
src/iocontrollers/pcie_controller.cc
|
werneazc/mcpat
|
fcd4d650709423f24bdad8d3cc302001e10e1f7d
|
[
"Intel"
] | 15
|
2020-05-24T23:33:03.000Z
|
2020-06-24T17:54:59.000Z
|
src/iocontrollers/pcie_controller.cc
|
werneazc/mcpat
|
fcd4d650709423f24bdad8d3cc302001e10e1f7d
|
[
"Intel"
] | 2
|
2021-01-26T02:02:27.000Z
|
2021-03-07T12:24:56.000Z
|
/*****************************************************************************
* McPAT
* SOFTWARE LICENSE AGREEMENT
* Copyright 2012 Hewlett-Packard Development Company, L.P.
* 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.”
*
* Author:
* Andrew Smith
***************************************************************************/
#include "pcie_controller.h"
#include "XML_Parse.h"
#include "basic_circuit.h"
#include "basic_components.h"
#include "const.h"
#include "io.h"
#include "parameter.h"
#include <algorithm>
#include <assert.h>
#include <cmath>
#include <iostream>
#include <string>
/*
* PCIeController()
* Constructor, Initializes the member variables that are shared across
* methods.
*/
PCIeController::PCIeController() {
long_channel = false;
power_gating = false;
init_params = false;
init_stats = false;
}
/*
* computeArea()
* Computes the component area based off of the input parameters in the XML.
* Side Effects:
* Sets the component area member to the calculated area.
* Input:
* None
* Output:
* None
*/
void PCIeController::computeArea() {
double frontend_area = 0.0;
double phy_area = 0.0;
double ctrl_area = 0.0;
double SerDer_area = 0.0;
if (!init_params) {
std::cerr << "[ PCIeController ] Error: must set params before calling "
"computeArea()\n";
exit(1);
}
/* Assuming PCIe is bit-slice based architecture
* This is the reason for /8 in both area and power calculation
* to get per lane numbers
*/
local_result = init_interface(&ip);
if (pciep.type == 0) // high performance NIU
{
// Area estimation based on average of die photo from Niagara 2 and Cadence
// ChipEstimate @ 65nm.
ctrl_area = (5.2 + 0.5) / 2 * (ip.F_sz_um / 0.065) * (ip.F_sz_um / 0.065);
// Area estimation based on average of die photo from Niagara 2, and Cadence
// ChipEstimate @ 65nm.
frontend_area =
(5.2 + 0.1) / 2 * (ip.F_sz_um / 0.065) * (ip.F_sz_um / 0.065);
// Area estimation based on average of die photo from Niagara 2 and Cadence
// ChipEstimate hard IP @65nm. SerDer is very hard to scale
SerDer_area = (3.03 + 0.36) * (ip.F_sz_um / 0.065); //* (ip.F_sz_um/0.065);
phy_area = frontend_area + SerDer_area;
// total area
} else {
ctrl_area = 0.412 * (ip.F_sz_um / 0.065) * (ip.F_sz_um / 0.065);
// Area estimation based on average of die photo from Niagara 2, and Cadence
// ChipEstimate @ 65nm.
SerDer_area = 0.36 * (ip.F_sz_um / 0.065) * (ip.F_sz_um / 0.065);
// total area
}
area.set_area(((ctrl_area + (pciep.withPHY ? SerDer_area : 0)) / 8 *
pciep.num_channels) *
1e6);
}
/*
* computeStaticPower()
* Computes the static power based off of the input parameters from the xml.
* It calculates leakage power,
*
* TODO: Add Vdd such that the static power & dynamic power can reflect
* changes in the chip power supply.
*
* Side Effects:
* Sets the static power, leakage, and power gated leakage
* Input:
* None
* Output:
* None
*/
void PCIeController::computeStaticPower() {
double frontend_dyn = 0.0;
double ctrl_dyn = 0.0;
double SerDer_dyn = 0.0;
double frontend_gates = 0.0;
double ctrl_gates = 0.0;
double SerDer_gates = 0.0;
double NMOS_sizing = 0.0;
double PMOS_sizing = 0.0;
double pmos_to_nmos_sizing_r = pmos_to_nmos_sz_ratio();
if (!init_params) {
std::cerr << "[ PCIeController ] Error: must set params before calling "
"computeStaticPower()\n";
exit(1);
}
if (pciep.type == 0) // high performance NIU
{
// Power
// Cadence ChipEstimate using 65nm the controller includes everything: the
// PHY, the data link and transaction layer
ctrl_dyn = 3.75e-9 / 8 * g_tp.peri_global.Vdd / 1.1 * g_tp.peri_global.Vdd /
1.1 * (ip.F_sz_nm / 65.0);
// //Cadence ChipEstimate using 65nm soft IP;
// frontend_dyn =
// 0.27e-9/8*g_tp.peri_global.Vdd/1.1*g_tp.peri_global.Vdd/1.1*(ip.F_sz_nm/65.0);
// SerDer_dyn is power not energy, scaling from 10mw/Gb/s @90nm
SerDer_dyn = 0.01 * 4 * (ip.F_sz_um / 0.09) * g_tp.peri_global.Vdd / 1.2 *
g_tp.peri_global.Vdd /
1.2; // PCIe 2.0 max per lane speed is 4Gb/s
SerDer_dyn /= pciep.clockRate; // covert to energy per clock cycle
// power_t.readOp.dynamic = (ctrl_dyn)*pciep.num_channels;
// Cadence ChipEstimate using 65nm
ctrl_gates = 900000 / 8 * pciep.num_channels;
// frontend_gates = 120000/8;
// SerDer_gates = 200000/8;
NMOS_sizing = 5 * g_tp.min_w_nmos_;
PMOS_sizing = 5 * g_tp.min_w_nmos_ * pmos_to_nmos_sizing_r;
} else {
// Power
// Cadence ChipEstimate using 65nm the controller includes everything: the
// PHY, the data link and transaction layer
ctrl_dyn = 2.21e-9 / 8 * g_tp.peri_global.Vdd / 1.1 * g_tp.peri_global.Vdd /
1.1 * (ip.F_sz_nm / 65.0);
// //Cadence ChipEstimate using 65nm soft IP;
// frontend_dyn =
// 0.27e-9/8*g_tp.peri_global.Vdd/1.1*g_tp.peri_global.Vdd/1.1*(ip.F_sz_nm/65.0);
// SerDer_dyn is power not energy, scaling from 10mw/Gb/s @90nm
SerDer_dyn = 0.01 * 4 * (ip.F_sz_um / 0.09) * g_tp.peri_global.Vdd / 1.2 *
g_tp.peri_global.Vdd /
1.2; // PCIe 2.0 max per lane speed is 4Gb/s
SerDer_dyn /= pciep.clockRate; // covert to energy per clock cycle
// Cadence ChipEstimate using 65nm
ctrl_gates = 200000 / 8 * pciep.num_channels;
// frontend_gates = 120000/8;
SerDer_gates = 200000 / 8 * pciep.num_channels;
NMOS_sizing = g_tp.min_w_nmos_;
PMOS_sizing = g_tp.min_w_nmos_ * pmos_to_nmos_sizing_r;
}
power_t.readOp.dynamic =
(ctrl_dyn + (pciep.withPHY ? SerDer_dyn : 0)) * pciep.num_channels;
power_t.readOp.leakage =
(ctrl_gates + (pciep.withPHY ? SerDer_gates : 0)) *
cmos_Isub_leakage(NMOS_sizing, PMOS_sizing, 2, nand) *
g_tp.peri_global.Vdd; // unit W
double long_channel_device_reduction =
longer_channel_device_reduction(Uncore_device);
double pg_reduction = power_gating_leakage_reduction(false);
power_t.readOp.longer_channel_leakage =
power_t.readOp.leakage * long_channel_device_reduction;
power_t.readOp.power_gated_leakage = power_t.readOp.leakage * pg_reduction;
power_t.readOp.power_gated_with_long_channel_leakage =
power_t.readOp.power_gated_leakage * long_channel_device_reduction;
power_t.readOp.gate_leakage =
(ctrl_gates + (pciep.withPHY ? SerDer_gates : 0)) *
cmos_Ig_leakage(NMOS_sizing, PMOS_sizing, 2, nand) *
g_tp.peri_global.Vdd; // unit W
}
/*
* computeDynamicPower()
* Compute both Peak Power and Runtime Power based on the stats of the input
* xml.
* Side Effects:
* Sets the runtime power, and the peak dynamic power in the component
* class
* Input:
* None
* Output:
* None
*/
void PCIeController::computeDynamicPower() {
power = power_t;
power.readOp.dynamic *= pciep.duty_cycle;
rt_power = power_t;
rt_power.readOp.dynamic *= pciep.perc_load;
}
/*
* display(uint32_t, bool)
* Display the Power, Area, and Timing results to the standard output
* Side Effects:
* None
* Input:
* indent - How far in to indent
* enable - toggle printing
* Output:
* None
*/
void PCIeController::display(uint32_t indent, bool enable) {
string indent_str(indent, ' ');
string indent_str_next(indent + 2, ' ');
if (enable) {
cout << "PCIe:" << endl;
cout << indent_str << "Area = " << area.get_area() * 1e-6 << " mm^2"
<< endl;
cout << indent_str
<< "Peak Dynamic = " << power.readOp.dynamic * pciep.clockRate << " W"
<< endl;
cout << indent_str << "Subthreshold Leakage = "
<< (long_channel ? power.readOp.longer_channel_leakage
: power.readOp.leakage)
<< " W" << endl;
if (power_gating)
cout << indent_str << "Subthreshold Leakage with power gating = "
<< (long_channel ? power.readOp.power_gated_with_long_channel_leakage
: power.readOp.power_gated_leakage)
<< " W" << endl;
cout << indent_str << "Gate Leakage = " << power.readOp.gate_leakage << " W"
<< endl;
cout << indent_str
<< "Runtime Dynamic = " << rt_power.readOp.dynamic * pciep.clockRate
<< " W" << endl;
cout << endl;
} else {
}
}
/*
* set_params(const ParseXML, InputParameter)
* Sets the parts of the flash controller params that contribute to area and
* static power. Must be called before computing area or static power.
* Side Effects:
* sets the interface_ip struct, and sets the params struct to the
* "params" from the xml file. Also sets init_params to true.
* Input:
* *XML - Parsed XML
* *interface_ip - Interface from McPAT used in Cacti Library
* Output:
* None
*/
void PCIeController::set_params(const ParseXML *XML,
InputParameter *interface_ip) {
ip = *interface_ip;
pciep.clockRate = XML->sys.pcie.clockrate;
pciep.clockRate *= 1e6;
pciep.num_units = XML->sys.pcie.number_units;
pciep.num_channels = XML->sys.pcie.num_channels;
pciep.type = XML->sys.pcie.type;
pciep.withPHY = XML->sys.pcie.withPHY;
long_channel = XML->sys.longer_channel_device;
power_gating = XML->sys.power_gating;
if (XML->sys.pcie.vdd > 0) {
ip.specific_hp_vdd = true;
ip.specific_lop_vdd = true;
ip.specific_lstp_vdd = true;
ip.hp_Vdd = XML->sys.pcie.vdd;
ip.lop_Vdd = XML->sys.pcie.vdd;
ip.lstp_Vdd = XML->sys.pcie.vdd;
}
if (XML->sys.pcie.power_gating_vcc > -1) {
ip.specific_vcc_min = true;
ip.user_defined_vcc_min = XML->sys.pcie.power_gating_vcc;
}
init_params = true;
}
/*
* set_stats(const ParseXML)
* Sets the parts of the flash controller params that contribute to dynamic
* power.
* Side Effects:
* Store duty cycle and and percentage load into fc params, sets
* init_stats to true
* Input:
* *XML - Parsed XML
* Output:
* None
*/
void PCIeController::set_stats(const ParseXML *XML) {
pciep.duty_cycle = XML->sys.pcie.duty_cycle;
pciep.perc_load = XML->sys.pcie.total_load_perc;
init_stats = true;
}
| 36.681957
| 85
| 0.647853
|
werneazc
|
15819bd3a1465c23d9bef99abfece6f69e9ebb11
| 883
|
cpp
|
C++
|
src/Router/lookup_service/src/thread_safe_map.cpp
|
JungyeonYoon/MicroSuite
|
acc75468a3568bb9504841978b887a337eba889c
|
[
"BSD-3-Clause"
] | 12
|
2019-03-06T13:17:50.000Z
|
2022-02-20T21:27:25.000Z
|
src/Router/lookup_service/src/thread_safe_map.cpp
|
DCchico/MicroSuite
|
b8651e0f5b74461393140135b917243a2e853f3d
|
[
"BSD-3-Clause"
] | null | null | null |
src/Router/lookup_service/src/thread_safe_map.cpp
|
DCchico/MicroSuite
|
b8651e0f5b74461393140135b917243a2e853f3d
|
[
"BSD-3-Clause"
] | 3
|
2019-06-08T01:46:55.000Z
|
2020-05-18T01:40:38.000Z
|
#include <iostream>
#include <mutex> // For std::unique_lock
#include <shared_mutex>
#include <thread>
#include <map>
class ThreadSafeMap {
public:
ThreadSafeMap() = default;
// Multiple threads/readers can read the counter's value at the same time.
std::string Get(std::string key) {
std::shared_lock<std::shared_mutex> lock(mutex_);
try {
map_.at(key);
} catch( ... ) {
return "nack";
}
return map_[key];
}
// Only one thread/writer can increment/write the counter's value.
void Set(std::string key, std::string value) {
std::unique_lock<std::shared_mutex> lock(mutex_);
map_[key] = value;
}
private:
mutable std::shared_mutex mutex_;
std::map<std::string, std::string> map_;
};
| 26.757576
| 82
| 0.554926
|
JungyeonYoon
|
158acf182a8f6192a76ac708da7f2064ff8e228b
| 922
|
cpp
|
C++
|
emulator/ibusdevice.cpp
|
vcato/qt-quick-6502-emulator
|
6202e546efddc612f229da078238f829dd756e12
|
[
"Unlicense"
] | null | null | null |
emulator/ibusdevice.cpp
|
vcato/qt-quick-6502-emulator
|
6202e546efddc612f229da078238f829dd756e12
|
[
"Unlicense"
] | 3
|
2019-09-14T02:46:26.000Z
|
2020-12-22T01:07:08.000Z
|
emulator/ibusdevice.cpp
|
vcato/qt-quick-6502-emulator
|
6202e546efddc612f229da078238f829dd756e12
|
[
"Unlicense"
] | null | null | null |
#include "ibusdevice.hpp"
IBusDevice::IBusDevice(uint16_t lower_address,
uint16_t upper_address,
bool writable,
bool readable,
QObject *parent)
:
QObject(parent),
_lower_address_range(lower_address),
_upper_address_range(upper_address),
_writable(writable),
_readable(readable)
{
}
IBusDevice::~IBusDevice()
{
}
bool IBusDevice::handlesAddress(uint16_t address) const
{
return (address >= _lower_address_range) && (address <= _upper_address_range);
}
void IBusDevice::write(uint16_t address, uint8_t data)
{
if (handlesAddress(address) && writable())
writeImplementation(address, data);
}
uint8_t IBusDevice::read(uint16_t address, bool read_only)
{
if (handlesAddress(address) && readable())
return readImplementation(address, read_only);
return 0x00;
}
| 23.641026
| 82
| 0.646421
|
vcato
|
159be018d59e57473754590ad73ca61354607c8f
| 188
|
cpp
|
C++
|
281A_22.cpp
|
tihorygit/codeforces
|
0b60531dd3faa3e4fccf95847457ef823f803d1b
|
[
"Unlicense"
] | null | null | null |
281A_22.cpp
|
tihorygit/codeforces
|
0b60531dd3faa3e4fccf95847457ef823f803d1b
|
[
"Unlicense"
] | null | null | null |
281A_22.cpp
|
tihorygit/codeforces
|
0b60531dd3faa3e4fccf95847457ef823f803d1b
|
[
"Unlicense"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
string s;
cin >> s;
if(s[0]>='a' && s[0]<='z')
s[0]=(char)(s[0]-'a'+'A');
cout << s << endl;
return 0;
}
| 14.461538
| 34
| 0.446809
|
tihorygit
|
159cc110d8281cdbb00f79d34d0b09b95ba3c8e0
| 7,080
|
hpp
|
C++
|
general_decimal_arithmetic/libgdatest/test_file.hpp
|
GaryHughes/stddecimal
|
ebec00e6cdad29a978ee5b0d4998e8b484d8dce1
|
[
"MIT"
] | 5
|
2020-08-08T07:01:00.000Z
|
2022-03-05T02:45:05.000Z
|
general_decimal_arithmetic/libgdatest/test_file.hpp
|
GaryHughes/stddecimal
|
ebec00e6cdad29a978ee5b0d4998e8b484d8dce1
|
[
"MIT"
] | 6
|
2020-06-28T02:22:07.000Z
|
2021-04-01T20:14:29.000Z
|
general_decimal_arithmetic/libgdatest/test_file.hpp
|
GaryHughes/stddecimal
|
ebec00e6cdad29a978ee5b0d4998e8b484d8dce1
|
[
"MIT"
] | 1
|
2021-02-05T08:59:49.000Z
|
2021-02-05T08:59:49.000Z
|
#ifndef stddecimal_general_decimal_arithmetic_test_runner_test_file_hpp
#define stddecimal_general_decimal_arithmetic_test_runner_test_file_hpp
#include <string>
#include <vector>
#include <fstream>
#include "test_context.hpp"
#include "test_line.hpp"
#include "test_results.hpp"
#include "tests.hpp"
#include <iostream>
#include <boost/algorithm/string/trim_all.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <decimal_numeric_limits.hpp>
namespace gda
{
template<int Bits>
class test_file
{
public:
test_file(const std::string& filename, test_results& results)
: m_is(filename),
m_results(results)
{
if (!m_is) {
throw std::runtime_error("Unable to open test file '" + filename + "'");
}
}
void process()
{
test_context context;
while (m_is)
{
std::string text;
if (!std::getline(m_is, text)) {
break;
}
try
{
test_line line(text);
if (line.is_blank()) {
continue;
}
if (line.is_comment()) {
continue;
}
if (line.is_directive()) {
context.apply_directive(line.keyword(), line.value());
continue;
}
if (line.is_test()) {
if (context.clamp()) {
m_results.record(result::skip);
continue;
}
test test;
test.id = line.id();
test.operation = line.operation();
test.operands = line.operands();
test.expected_result = line.expected_result();
test.expected_conditions = line.expected_conditions();
using traits = operation_traits<Bits>;
using limits = std::decimal::numeric_limits<typename traits::decimal_type>;
// if (context.precision() > limits::digits) {
// std::cerr << "skipping due to precision " << *context.precision() << " v " << limits::digits << "\n";
// m_results.record(result::skip);
// continue;
// }
try {
context.apply_rounding();
// std::decimal::clear_exceptions(std::decimal::FE_DEC_ALL_EXCEPT);
std::decimal::set_exceptions(std::decimal::FE_DEC_DIVBYZERO |
std::decimal::FE_DEC_INEXACT |
std::decimal::FE_DEC_INVALID |
std::decimal::FE_DEC_OVERFLOW |
std::decimal::FE_DEC_UNDERFLOW);
m_results.record(process_test(test));
}
catch (std::decimal::exception& ex) {
if (ex.flags() != test.expected_conditions) {
report_failure(test, ex.flags());
m_results.record(result::fail);
}
else {
m_results.record(result::pass);
}
}
catch (std::exception& ex) {
std::cerr << "GENERIC EXCEPTION " << test.id << " " << ex.what() << std::endl;
m_results.record(result::skip);
}
continue;
}
std::cerr << "failed to process line: " << text << '\n';
}
catch (std::exception& ex)
{
std::cerr << "failed to parse line: " + text << '\n';
}
}
}
private:
result process_test(const test& test)
{
using traits = operation_traits<Bits>;
if (test.operation == "add") {
return add_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "subtract") {
return subtract_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "divide") {
return divide_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "multiply") {
return multiply_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "squareroot") {
return square_root_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "abs") {
return abs_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "plus") {
return plus_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "minus") {
return minus_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "power") {
return power_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "quantize") {
return quantize_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "log10") {
return log10_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "fma") {
return fma_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "min") {
return min_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "max") {
return max_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "remainder") {
return remainder_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "exp") {
return exp_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "ln") {
return log_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "samequantum") {
return samequantum_test<typename traits::decimal_type>::run(test);
}
if (test.operation == "compare") {
return compare_test<typename traits::decimal_type>::run(test);
}
// comparetotal0.decTest
// randoms0.decTest
// rescale0.decTest
// inexact0.decTest
// reduce0.decTest
// testall0.decTest
// base0.decTest
// divideint0.decTest
// tointegral0.decTest
// remaindernear0.decTest
// trim0.decTest
std::cerr << "skipping: " << test.id << '\n';
return result::skip;
}
std::ifstream m_is;
test_results& m_results;
};
} // namespace gda
#endif
| 30.649351
| 129
| 0.491667
|
GaryHughes
|
159e64a6a9f23aa921f7ae181010b6a6f2b64219
| 2,025
|
hpp
|
C++
|
src/ngraph/frontend/onnx_import/core/model.hpp
|
srinivasputta/ngraph
|
7506133fff4a8e5c25914a8370a567c4da5b53be
|
[
"Apache-2.0"
] | null | null | null |
src/ngraph/frontend/onnx_import/core/model.hpp
|
srinivasputta/ngraph
|
7506133fff4a8e5c25914a8370a567c4da5b53be
|
[
"Apache-2.0"
] | null | null | null |
src/ngraph/frontend/onnx_import/core/model.hpp
|
srinivasputta/ngraph
|
7506133fff4a8e5c25914a8370a567c4da5b53be
|
[
"Apache-2.0"
] | null | null | null |
//*****************************************************************************
// 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.
//*****************************************************************************
#pragma once
#include <onnx.pb.h>
#include <ostream>
namespace ngraph
{
namespace onnx_import
{
class Model
{
public:
Model() = delete;
explicit Model(const onnx::ModelProto& model_proto)
: m_model_proto{&model_proto}
{
}
Model(Model&&) noexcept = default;
Model(const Model&) = default;
Model& operator=(Model&&) noexcept = delete;
Model& operator=(const Model&) = delete;
const std::string& get_producer_name() const { return m_model_proto->producer_name(); }
const onnx::GraphProto& get_graph() const { return m_model_proto->graph(); }
std::int64_t get_model_version() const { return m_model_proto->model_version(); }
const std::string& get_producer_version() const
{
return m_model_proto->producer_version();
}
private:
const onnx::ModelProto* m_model_proto;
};
inline std::ostream& operator<<(std::ostream& outs, const Model& model)
{
return (outs << "<Model: " << model.get_producer_name() << ">");
}
} // namespace onnx_import
} // namespace ngraph
| 33.196721
| 99
| 0.568395
|
srinivasputta
|
159ee5cbf8ba53e95889d129e7d791cb43500182
| 1,514
|
cpp
|
C++
|
examples/miscellaneous/zelikovsky_11_per_6_example.cpp
|
Kommeren/AA
|
e537b58d50e93d4a72709821b9ea413008970c6b
|
[
"BSL-1.0"
] | null | null | null |
examples/miscellaneous/zelikovsky_11_per_6_example.cpp
|
Kommeren/AA
|
e537b58d50e93d4a72709821b9ea413008970c6b
|
[
"BSL-1.0"
] | null | null | null |
examples/miscellaneous/zelikovsky_11_per_6_example.cpp
|
Kommeren/AA
|
e537b58d50e93d4a72709821b9ea413008970c6b
|
[
"BSL-1.0"
] | 1
|
2021-02-24T06:23:56.000Z
|
2021-02-24T06:23:56.000Z
|
//=======================================================================
// Copyright (c)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
/**
* @file zelikovsky_11_per_6_example.cpp
* @brief This is example for zelikovsky 11/6 approximation for steiner tree
* problem.
* @author Piotr Wygocki
* @version 1.0
* @date 2013-02-04
*/
//! [Steiner Tree Example]
#include "paal/steiner_tree/zelikovsky_11_per_6.hpp"
#include "test/test_utils/sample_graph.hpp"
#include <iostream>
int main() {
// sample metric
typedef sample_graphs_metrics SGM;
auto gm = SGM::get_graph_metric_steiner();
typedef decltype(gm) Metric;
// sample voronoi
typedef paal::data_structures::voronoi<Metric> voronoiT;
typedef paal::data_structures::voronoi_traits<voronoiT> VT;
typedef VT::GeneratorsSet GSet;
typedef VT::VerticesSet VSet;
voronoiT voronoi(GSet{ SGM::A, SGM::B, SGM::C, SGM::D }, VSet{ SGM::E },
gm);
// run algorithm
std::vector<int> steiner_points;
paal::steiner_tree_zelikovsky11per6approximation(
gm, voronoi, std::back_inserter(steiner_points));
// print result
std::cout << "Steiner points:" << std::endl;
boost::copy(steiner_points, std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
//! [Steiner Tree Example]
| 31.541667
| 77
| 0.616248
|
Kommeren
|
15a74f451822d2b1bdc3817204c5eae613421d84
| 18,956
|
cc
|
C++
|
CMC040/cmcfun/outp_line.cc
|
khandy21yo/aplus
|
3b4024a2a8315f5dcc78479a24100efa3c4a6504
|
[
"MIT"
] | 1
|
2018-10-17T08:53:17.000Z
|
2018-10-17T08:53:17.000Z
|
CMC040/cmcfun/outp_line.cc
|
khandy21yo/aplus
|
3b4024a2a8315f5dcc78479a24100efa3c4a6504
|
[
"MIT"
] | null | null | null |
CMC040/cmcfun/outp_line.cc
|
khandy21yo/aplus
|
3b4024a2a8315f5dcc78479a24100efa3c4a6504
|
[
"MIT"
] | null | null | null |
//! \file
//! \brief Handle Paging on Reports
// %SBTTL "OUTP_LINE"
// %IDENT "V3.6a Calico"
//
// Source: ../../CMC030/cmcfun/source/outp_line.bas
// Translated from Basic to C++ using btran
// on Wednesday, December 20, 2017 at 17:16:51
//
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include "basicfun.h"
#include "smg/smg.h"
#include "preferences.h"
#include "cmcfun.h"
#include "database.h"
#include "scopedef.h"
#include "cmcfun/report.h"
#include "utl/utl_reportx.h"
#include "utl/utl_profile.h"
#include "scroll.h"
extern scope_struct scope;
//!
//! \brief Handle Paging on Reports
//!
//! This subroutine handles paging for the report
//! programs existing in all systems.
//!
//! Example:
//!
//! CALL OUTP_INITFROMFILE(UTL_REPORTX, 80%)
//!
//! TITLE$(1%) = "This is the report"
//! TITLE$(2%) = "For the current period"
//! TITLE$(3%) = ""
//! TITLE$(4%) = "Key Description Date Time Flag"
//! TITLE$(5%) = ""
//!
//! LAYOUT$ = "$KEY:005,$DESCR:026,DDATE:035,TTIME:041,VFLAG:043"
//!
//! LINE$ = KEY$ + " " +
//! DESCRIPTION$ + " " +
//! PRNT_DATE(DATE$, 0%) + " " +
//! PRNT_TIME(TIME$, 2048%) + " " +
//! FORMAT$(FLAG%, "#")
//!
//! CALL OUTP_LINE(LAYOUT$, UTL_REPORTX, TITLES$(), LINE$, 0%)
//!
//! \author 03/23/87 - Kevin Handy
//!
void outp_line(
const std::string &columns,
//!< Passed specification for not only where the
//! columns are, but also labels for
//! these columns. This string is used for shipping
//! the report to Graphics, a Spreadsheet, or a
//! Database. Each column of data should have a
//! section in this string, in this form:
//!
//! ... [DataType][Label]:[EndingPos], ...
//!
//! [DataType] is a single character describing
//! the type of data passed in that column:
//! ($ = String, D = Date, P = Phone number,
//! T = Time, and V = Number value).
//! [Label] is a label for the data passed in that
//! column.
//! [EndingPos] is the horizontal position along
//! the line where this column ends.
utl_reportx_cdd &utl_reportx,
//!< This passed structure contains the definitions of
//! various items for the report being printed. These
//! items are modified according to actions taken; line
//! number, page number incremented, etc.
const std::vector<std::string> &hdr,
//!< Headers to be printed on the top of every page.
const std::string &txt,
//!< Passed text to print.
long lineoff)
//!< Variable used to control paging. A positive value
//! causes paging to occur that many lines earlier,
//! and a negitive value causes it to occur that many
//! lines later. A special case of LINEOFF >= 1000
//! exists that forces a new page, but the line is not
//! counted/printed.
{
long colonpos;
std::string column;
long commapos;
std::string data;
long endpos;
long i;
std::string junk;
long junk_V2;
long junk1;
std::string junk3;
std::string old_help_item;
std::string old_help_severity;
std::string old_program;
long print_flag1;
long print_flag2;
long q_flag;
long smg_status;
long startpos;
std::string temp;
long temp_V4;
std::string text;
std::string this_col;
std::string tolocal;
std::string toscreen;
long v;
BStack(20);
const long max_smg_text = 200;
utl_profile_cdd utl_profile;
smg_scroll_cdd smg_scroll;
std::vector<std::string> smg_text;
smg_text.resize(max_smg_text + 1);
long rrr_flag;
std::string title1;
extern long outp_xunsol;
//
// ++
//
// Helper function for the offset business
//
auto fnoffset = [&](std::string source, long offset)
{
std::string Result;
// ** Converted from a select statement **
if (offset > 0)
{
Result = std::string(offset, ' ') + source;
}
else if (offset < 0)
{
Result = basic::right(source, -offset + 1);
}
else
{
Result = source;
}
return Result;
};
//
// Save the key for help
//
old_help_severity = scope.prg_ident;
old_program = scope.prg_program;
old_help_item = scope.prg_item;
scope.prg_program = "OUTP_LINE";
scope.prg_item = "HELP";
scope.prg_ident = "H";
junk3 = "";
//
// Exit due to report request
//
if (utl_reportx.stat != 0)
{
goto exitsub;
}
if (boost::trim_right_copy(hdr[1]) != "")
{
title1 = boost::trim_right_copy(hdr[1]);
}
//
// Special LINEOFF (-12345) for OUTP_FINISH when in display mode.
// This is used so that when you hit the end of the report, you
// can still arrow back up and down to your hearts content.
// Q_FLAG% is used to change the flag used by DSPL_SCROLLCIR.
//
if ((lineoff == -12345) && (utl_reportx.printto == OUTP_TODISPLAY))
{
q_flag = 2;
BGosub(L_2000);
goto exitsub;
}
q_flag = 6;
//
// Output goes to printer if to printer port
//
if ((utl_reportx.printto == OUTP_TOLOCAL) && (utl_reportx.pageno >= utl_reportx.startp))
{
writ_string(utl_reportx.tolocal, tolocal);
utl_reportx.chan << tolocal;
}
//
// Force the title if this is the first time through,
// or it is time to do a page.
//
if (((utl_reportx.pageno == 0) &&
(utl_reportx.printto < 10)) ||
((utl_reportx.lineno + lineoff) >= (utl_reportx.pagelen - 7) &&
(utl_reportx.printto != OUTP_TODISPLAY) &&
(utl_reportx.printto < 10)) ||
((utl_reportx.lineno) >= (utl_reportx.pagelen) &&
(utl_reportx.printto == OUTP_TODISPLAY)))
{
BGosub(L_2000);
}
//
// Count the line
//
if (lineoff < 1000 && utl_reportx.autoscroll == 0)
{
utl_reportx.lineno = utl_reportx.lineno + 1;
}
//
// Will we be printing? (Check for start and end page, as
// well as report request to exit)
//
if (!((utl_reportx.pageno >= utl_reportx.startp) && ((utl_reportx.pageno <= utl_reportx.endp) || (utl_reportx.endp == 0))))
{
goto L_1500;
}
if (utl_reportx.stat != 0)
{
goto L_1500;
}
//
// If the lineoff<1000 then line will print otherwise line
// will not print
//
if (lineoff < 1000)
{
//
// Handle the various types of output
//
// ** Converted from a select statement **
//
// Display
//
if (utl_reportx.printto == OUTP_TODISPLAY)
{
smg_scroll.end_element = smg_scroll.end_element + 1;
if (smg_scroll.end_element > smg_scroll.bot_array)
{
smg_scroll.end_element = smg_scroll.top_array;
}
if (smg_scroll.beg_element == smg_scroll.end_element)
{
smg_scroll.beg_element = smg_scroll.end_element + 1;
}
if (smg_scroll.beg_element > smg_scroll.bot_array)
{
smg_scroll.beg_element = smg_scroll.top_array;
}
smg_text[smg_scroll.end_element] = fnoffset(txt, utl_reportx.offset);
smg_scroll.find_line = smg_scroll.end_element;
junk_V2 = dspl_scrollcir(smg_scroll, smg_text, SMG$K_TRM_FIND, "");
//
// SuperComp 20/20, PlanPerfect
//
}
else if ((utl_reportx.printto == OUTP_TO2020) || (utl_reportx.printto == OUTP_TOPL))
{
if (columns == "")
{
column = "$Line:255,";
}
else
{
column = columns + ",";
}
startpos = 0;
print_flag2 = 0;
temp = "";
while (column != "")
{
commapos = (column.find(",", 0) + 1);
this_col = column.substr(0, commapos - 1);
column = basic::right(column, commapos + 1);
colonpos = (this_col.find(":", 0) + 1);
endpos = std::stol(basic::right(this_col, colonpos + 1));
data = boost::trim_right_copy(basic::Qseg(txt, startpos, endpos));
if (basic::edit(this_col.substr(0, 1), -1) == "V")
{
//
// Clean up data a little
//
data = boost::trim_copy(data);
if (basic::right(data, data.size()) == ")" && data.substr(0, 1) == "(")
{
data = std::string("-") + basic::Qseg(data, 2, data.size() - 1);
}
if (basic::right(data, data.size()) == "-")
{
data = std::string("-") + data.substr(0, data.size() - 1);
}
i = (data.find(",", 0) + 1);
while (i)
{
data = data.substr(0, i - 1) + basic::right(data, i + 1);
i = (data.find(",", 0) + 1);
}
i = (data.find("$", 0) + 1);
if (i)
{
data = data.substr(0, i - 1) + basic::right(data, i + 1);
}
}
if (utl_reportx.printto == OUTP_TOPL)
{
temp = temp + "\t" + data;
if (data != "")
{
print_flag2 = -1;
}
}
else
{
// ** Converted from a select statement **
if (basic::edit(this_col.substr(0, 1), -1) == "V")
{
temp = temp + data + " #";
if (data.find_first_of("123456789") + 1)
{
print_flag2 = -1;
}
}
else
{
temp = temp + "\"" + data + "\" #";
if (data != "")
{
print_flag2 = -1;
}
}
}
startpos = endpos + 1;
}
// ** Converted from a select statement **
if (utl_reportx.printto == OUTP_TO2020)
{
temp = temp + "#";
}
else if (utl_reportx.printto == OUTP_TOPL)
{
temp = basic::right(temp, 2);
}
if (print_flag2)
{
utl_reportx.chan << temp << std::endl;
}
if (utl_reportx.lineno == 1)
{
entr_3message(scope, title1, 1 + 16);
}
//
// Normal output
//
}
else
{
utl_reportx.chan << fnoffset(txt, utl_reportx.offset) << std::endl;
}
}
//
L_1500:;
// Output goes to the screen if in printer port mode
//
if (utl_reportx.printto == OUTP_TOLOCAL)
{
writ_string(utl_reportx.toscreen, toscreen);
utl_reportx.chan << toscreen;
}
if (junk3 != "")
{
//
// Test to force a buffer flush
//
entr_3message(scope, junk3 + " of " + title1, 1 + 16);
smg_status = smg$flush_buffer(scope.smg_pbid);
}
//
// Flag to end program if we reach the end page number
//
if ((utl_reportx.pageno > utl_reportx.endp) && (utl_reportx.endp != 0))
{
utl_reportx.stat = -50;
}
//
// Handle any special junk in RRR_FLAG%
//
// ** Converted from a select statement **
//
// Nothing
//
if (rrr_flag == 0)
{
// Nothing
//
// Autoscroll Toggle Key Typed
//
}
else if (rrr_flag == 1)
{
if (utl_reportx.autoscroll == 0)
{
utl_reportx.autoscroll = -1;
}
else
{
utl_reportx.autoscroll = 0;
}
//
// Exit keys
//
}
else if ((rrr_flag == 3) || ((rrr_flag == SMG$K_TRM_F10) || ((rrr_flag == SMG$K_TRM_CTRLZ) || (rrr_flag == SMG$K_TRM_F8))))
{
utl_reportx.stat = rrr_flag;
//
// Else
//
}
else
{
smg_status = entr_4specialkeys(scope, scope.smg_option, 256, rrr_flag);
}
rrr_flag = 0;
exitsub:;
//
// Restore the key for help
//
scope.prg_ident = old_help_severity;
scope.prg_program = old_program;
scope.prg_item = old_help_item;
return;
//*******************************************************************
L_2000:;
// This subroutine does the actual paging
//*******************************************************************
//
// Count one page
//
utl_reportx.pageno = utl_reportx.pageno + 1;
//
// Are we skipping this page? Check first for page range, but
// force first title when printing to a clipboard, wp document,
// or file cabinet.
//
print_flag1 = ((utl_reportx.pageno >= utl_reportx.startp) && ((utl_reportx.pageno <= utl_reportx.endp) || (utl_reportx.endp == 0)));
//
// On first page, enable unsolicited input trapping
//
if (utl_reportx.pageno == 1)
{
rrr_flag = 0;
}
//
// While in display, title goes on line two and three
//
// ** Converted from a select statement **
if (utl_reportx.printto == OUTP_TODISPLAY)
{
//
// Pause
//
scope.scope_exit = 0;
if ((utl_reportx.pageno != 1) && (utl_reportx.autoscroll == 0))
{
pauseloop:;
entr_3message(scope, title1, 0);
// ** Converted from a select statement **
//
// Autoscroll Toggle Key Typed
//
if (scope.scope_exit == 1)
{
utl_reportx.autoscroll = -1;
//
// An exit key was typed
//
}
else if ((scope.scope_exit == 3) || ((scope.scope_exit == SMG$K_TRM_CTRLZ) || ((scope.scope_exit == SMG$K_TRM_F10) || (scope.scope_exit == SMG$K_TRM_F8))))
{
utl_reportx.stat = scope.scope_exit;
goto ret2000;
//
// Cursor positioning (up) key was typed
//
}
else if ((scope.scope_exit == SMG$K_TRM_UP) || ((scope.scope_exit == SMG$K_TRM_F18) || (scope.scope_exit == SMG$K_TRM_PREV_SCREEN)))
{
smg_scroll.smg_flag = 2;
temp_V4 = dspl_scrollcir(smg_scroll, smg_text, scope.scope_exit, "");
goto pauseloop;
//
// Cursor positioning key (down) was typed
//
}
else if ((scope.scope_exit == SMG$K_TRM_DOWN) || ((scope.scope_exit == SMG$K_TRM_F19) || (scope.scope_exit == SMG$K_TRM_NEXT_SCREEN)))
{
smg_scroll.smg_flag = q_flag;
temp_V4 = dspl_scrollcir(smg_scroll, smg_text, scope.scope_exit, "");
if (temp_V4 <= 0)
{
goto pauseloop;
}
utl_reportx.lineno = utl_reportx.lineno - temp_V4;
//
// Return, etc. act as next screen
//
}
else if ((scope.scope_exit == 10) || ((scope.scope_exit == 12) || ((scope.scope_exit == 13) || ((scope.scope_exit == SMG$K_TRM_F7) || (scope.scope_exit == SMG$K_TRM_DO)))))
{
smg_scroll.smg_flag = q_flag;
temp_V4 = dspl_scrollcir(smg_scroll, smg_text, SMG$K_TRM_NEXT_SCREEN, "");
if (temp_V4 <= 0)
{
goto pauseloop;
}
utl_reportx.lineno = utl_reportx.lineno - temp_V4;
//
// Case else
//
}
else
{
entr_3badkey(scope, scope.scope_exit);
goto pauseloop;
}
}
//
// Search for header
//
for (junk_V2 = 1; !(hdr[junk_V2] == ""); junk_V2++)
{
v = 0;
}
for (junk1 = junk_V2 + 1; !(hdr[junk1] == ""); junk1++)
{
v = 0;
}
//
// Clear the screen and print the title if necessary
//
if ((utl_reportx.pageno == 1) || (lineoff > 1000))
{
//
// Display the header
//
for (i = junk_V2 + 1; i <= junk1 - 1; i++)
{
junk = hdr[i];
if (junk == ".")
{
junk = "";
}
junk = fnoffset(junk, utl_reportx.offset);
smg_status = smg$put_chars(utl_reportx.window, junk + std::string(utl_reportx.repwidth - junk.size(), ' '), (i - junk_V2), 1, 1, SMG$M_REVERSE);
}
//
// Set up scrolling region
//
// smg_status = smg$set_display_scroll_region(utl_reportx.window, junk1 - junk_V2, 20);
//
// Create SMG_SCROLL array
//
smg_scroll.window = &utl_reportx.window;
smg_scroll.scroll_top = junk1 - junk_V2;
smg_scroll.scroll_bot = 20;
smg_scroll.top_array = 1;
smg_scroll.bot_array = max_smg_text;
smg_scroll.cur_line = smg_scroll.cur_w_col = 1;
smg_scroll.find_line = smg_scroll.top_line = smg_scroll.cur_w_row = smg_scroll.beg_element = 1;
smg_scroll.end_element = 1;
smg_text[1] = "";
smg_scroll.smg_flag = 6;
smg_scroll.prompt = "";
smg_scroll.num_colm = 1;
//
// Calculate number of lines available on the screen
//
utl_reportx.lineno = junk1 - junk_V2;
}
}
else
{
//
// Skip to the top of the next page
//
if (utl_reportx.pageno == 1)
{
utl_reportx.sdate = basic::Qdate(0);
utl_reportx.stime = basic::Qtime(0);
}
//
// Print the page title
//
junk3 = std::string("Page ") + std::to_string(utl_reportx.pageno);
//
// Switch to screen mode
//
// SMG_STATUS% = SMG$FLUSH_BUFFER(SCOPE::SMG_PBID)
// IF UTL_REPORTX::PRINTTO = OUTP_TOLOCAL
// THEN
// CALL WRIT_STRING(UTL_REPORTX::TOSCREEN, TOSCREEN$)
// PRINT #UTL_REPORTX::CHAN, TOSCREEN$;
// END IF
//
// CALL ENTR_3MESSAGE(SCOPE, JUNK3$ + " of " + TITLE1, 1% + 16%)
utl_reportx.stat = scope.macroflag;
//
// SMG_STATUS% = SMG$FLUSH_BUFFER(SCOPE::SMG_PBID)
// IF UTL_REPORTX::PRINTTO = OUTP_TOLOCAL
// THEN
// CALL WRIT_STRING(UTL_REPORTX::TOLOCAL, TOLOCAL$)
// PRINT #UTL_REPORTX::CHAN, TOLOCAL$;
// END IF
//
// Handle title while skipping pages (Use special loop
// because it looks better than 1000 if statements in
// the printing section that follows).
//
// Also, handle types 7, and 8 (Word Processing,
// File cabinet), after the first header, so that the user
// can actuall use start/end page.
//
if ((print_flag1 == 0) || ((utl_reportx.pageno != 1) && (utl_reportx.printto == OUTP_TOWP)))
{
//
// Print page anyway if need a title for wp.
//
if ((utl_reportx.pageno == 1) && (utl_reportx.printto == OUTP_TOWP))
{
goto L_2050;
}
//
// Special GOSUB 3000's in title
//
utl_reportx.lineno = 5;
if (utl_reportx.repyn != "N")
{
utl_reportx.lineno = utl_reportx.lineno + 1;
}
//
// Title
//
for (junk1 = 1; !(hdr[junk1] == ""); junk1++)
{
utl_reportx.lineno = utl_reportx.lineno + 1;
}
//
// Header
//
for (junk1 = junk1 + 1; !(hdr[junk1] == ""); junk1++)
{
utl_reportx.lineno = utl_reportx.lineno + 1;
}
goto L_2100;
}
//
L_2050:;
// Output the title
//
if (utl_reportx.pageno != 1)
{
outp_formff(utl_reportx);
// (Hack)
utl_reportx.pageno = utl_reportx.pageno - 1;
}
// Minimum number of lines in header
utl_reportx.lineno = 4;
// Modified to adjust for excesses in
// paging section, and room for blank
// lines at bottom of page.
utl_reportx.chan << std::endl;
utl_reportx.chan << std::endl;
junk_V2 = 0;
junk = boost::trim_right_copy(utl_profile.rep_name);
BGosub(L_3000);
for (junk1 = 1; !(hdr[junk1] == ""); junk1++)
{
junk = boost::trim_right_copy(hdr[junk1]);
BGosub(L_3000);
}
if (utl_reportx.repyn != "N")
{
junk = boost::trim_right_copy(utl_reportx.repdate);
BGosub(L_3000);
}
utl_reportx.chan << std::endl;
utl_reportx.chan << fnoffset(basic::Qstring(utl_reportx.repwidth, '='), utl_reportx.offset) << std::endl;
for (junk1 = junk1 + 1; !(hdr[junk1] == ""); junk1++)
{
junk = boost::trim_right_copy(hdr[junk1]);
if (junk == ".")
{
junk = "";
}
utl_reportx.chan << fnoffset(junk, utl_reportx.offset) << std::endl;
utl_reportx.lineno = utl_reportx.lineno + 1;
}
}
L_2100:;
BReturn;
//
L_3000:;
// Print the heading stuff
//
junk_V2 = junk_V2 + 1;
if (junk == ".")
{
junk = "";
}
utl_reportx.lineno = utl_reportx.lineno + 1;
switch (junk_V2)
{
case 1:
text = std::string("Date: ") + basic::Qdate(0);
text = text + std::string(utl_reportx.repwidth / 2 - text.size() - junk.size() / 2, ' ') + junk;
text = text + std::string(utl_reportx.repwidth - text.size() - junk3.size(), ' ') + junk3;
utl_reportx.chan << fnoffset(text, utl_reportx.offset) << std::endl;
break;
case 2:
text = std::string("Time: ") + basic::Qtime(0);
text = text + std::string(utl_reportx.repwidth / 2 - text.size() - junk.size() / 2, ' ') + junk;
text = text + std::string(utl_reportx.repwidth - text.size() - strlen("V3.6"), ' ') + "V3.6";
utl_reportx.chan << fnoffset(text, utl_reportx.offset) << std::endl;
break;
default:
text = "";
text = text + std::string(utl_reportx.repwidth / 2 - text.size() - junk.size() / 2, ' ') + junk;
utl_reportx.chan << fnoffset(text, utl_reportx.offset) << std::endl;
break;
}
ret2000:;
BReturn;
}
// +-+-+
// ++
// Success:DISPLAY
// ^*Display Report\*
// .b
// .lm +5
// Scrolling the report to the next screen, previous screen,
// line by line or exit.
// .lm -5
//
// Index:
//
// --
| 24.811518
| 175
| 0.605982
|
khandy21yo
|
15c08ce7c071ba50f4fa54b97c35a5e00807fa14
| 2,423
|
cpp
|
C++
|
src/umpire/util/Backtrace.cpp
|
bmhan12/Umpire
|
de82bcd066f153958aff2f68091cac2125d9c5bc
|
[
"MIT-0",
"MIT"
] | null | null | null |
src/umpire/util/Backtrace.cpp
|
bmhan12/Umpire
|
de82bcd066f153958aff2f68091cac2125d9c5bc
|
[
"MIT-0",
"MIT"
] | null | null | null |
src/umpire/util/Backtrace.cpp
|
bmhan12/Umpire
|
de82bcd066f153958aff2f68091cac2125d9c5bc
|
[
"MIT-0",
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016-20, Lawrence Livermore National Security, LLC and Umpire
// project contributors. See the COPYRIGHT file for details.
//
// SPDX-License-Identifier: (MIT)
//////////////////////////////////////////////////////////////////////////////
#include <cstdio>
#include <cstdlib>
#if !defined(_MSC_VER) && !defined(_LIBCPP_VERSION)
#include <cxxabi.h> // for __cxa_demangle
#endif // !defined(_MSC_VER) && !defined(_LIBCPP_VERSION)
#if !defined(_MSC_VER)
#include <dlfcn.h> // for dladdr
#include <execinfo.h> // for backtrace
#endif // !defined(_MSC_VER)
#include <iostream>
#include <iomanip>
#include "umpire/util/Backtrace.hpp"
#include "umpire/util/Macros.hpp"
namespace umpire {
namespace util {
Backtrace::Backtrace() noexcept
{
}
void Backtrace::getBacktrace()
{
#if !defined(_MSC_VER)
void *callstack[128];
const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]);
for (int i = 0; i < backtrace(callstack, nMaxFrames); ++i)
m_backtrace.push_back(callstack[i]);
#endif // !defined(_MSC_VER)
}
std::ostream& operator<<(std::ostream& os, const Backtrace& bt)
{
#if !defined(_MSC_VER)
char **symbols = backtrace_symbols(&bt.m_backtrace[0], bt.m_backtrace.size());
os << " Backtrace: " << bt.m_backtrace.size() << " frames" << std::endl;
int index = 0;
for ( const auto& it : bt.m_backtrace ) {
os << " " << index << " " << it << " ";
Dl_info info;
if (dladdr(it, &info) && info.dli_sname) {
char *demangled = NULL;
int status = -1;
#if !defined(_LIBCPP_VERSION)
if (info.dli_sname[0] == '_')
demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status);
#endif // !defined(_MSC_VER) && !defined(_LIBCPP_VERSION)
os << ( status == 0 ? demangled : ( info.dli_sname == 0 ? symbols[index] : info.dli_sname ) )
<< "+0x" << std::hex << static_cast<int>(static_cast<char*>(it) - static_cast<char*>(info.dli_saddr));
#if !defined(_LIBCPP_VERSION)
free(demangled);
#endif // !defined(_MSC_VER) && !defined(_LIBCPP_VERSION)
}
else {
os << "No dladdr: " << symbols[index];
}
os << std::endl;
++index;
}
free(symbols);
#else
UMPIRE_USE_VAR(bt);
os << " Backtrace not supported on Windows platform" << std::endl;
#endif
return os;
}
} // end of namespace util
} // end of namespace umpire
| 28.505882
| 110
| 0.606686
|
bmhan12
|
15c264868451a5d330f1bb6c9f8feb459bcce78f
| 2,823
|
cpp
|
C++
|
QtPredict/PredictKeyHandleUI.cpp
|
Kay01010101/PredictVersion
|
adde9de5dd39b2f22e103f3294d1beab4f327d62
|
[
"MIT"
] | null | null | null |
QtPredict/PredictKeyHandleUI.cpp
|
Kay01010101/PredictVersion
|
adde9de5dd39b2f22e103f3294d1beab4f327d62
|
[
"MIT"
] | null | null | null |
QtPredict/PredictKeyHandleUI.cpp
|
Kay01010101/PredictVersion
|
adde9de5dd39b2f22e103f3294d1beab4f327d62
|
[
"MIT"
] | null | null | null |
/*
Time : 2016/06/13
Author: Kay Yang (1025115216@qq.com)
*/
#ifndef CONSOLE
#include "PredictKeyHandleUI.h"
#include "PredictGeneratorKey.h"
#include "PredictMainWindow.h"
#include "QDebug"
#include "PredictCheck.h"
TextEditorThread::TextEditorThread() : mStopped(false)
{
}
TextEditorThread::~TextEditorThread()
{
mMessages.Clear();
}
void TextEditorThread::Push(const QString& text)
{
mMutex.Lock();
mMessages.Push(text);
mMutex.Unlock();
}
void TextEditorThread::SetStop(bool isStop)
{
mStopped = isStop;
}
void TextEditorThread::run()
{
while (!mStopped)
{
while (mMessages.Size() > 0)
{
mMutex.Lock();
emit MsgSignal(mMessages.Pop());
mMutex.Unlock();
}
QThread::msleep(1);
}
}
PredictKeyHandleUI::PredictKeyHandleUI(QWidget* parent) : QWidget(parent), ui(new Ui::GeneratorUI())
{
ui->setupUi(this);
mTextEditor = new TextEditorThread();
mTextEditor->start();
}
PredictKeyHandleUI::~PredictKeyHandleUI()
{
if (ui)
{
delete ui;
}
ui = 0;
mTextEditor->SetStop(true);
while (mTextEditor->isRunning())
{
Sleep(2);
}
if (mTextEditor)
delete mTextEditor;
mTextEditor = 0;
}
void PredictKeyHandleUI::LoadOldKeySequence()
{
//PredictGeneratorKey::Instance()->Clear();
//PredictGeneratorKey::Instance()->LoadFromFile(PredictConfig::Inistance()->mConfigData.GetFullGeneratorPath().C_String());
}
void PredictKeyHandleUI::onStart()
{
//LoadOldKeySequence();
//PredictCheck::Instance()->Start();
//PredictMainWindow* mainWind = (PredictMainWindow*)mOwner;
//mainWind->StartServer();
//ui->mGeneratorKey->setEnabled(false);
//ui->mStart->setEnabled(false);
//ui->mDump->setEnabled(true);
//ui->mStop->setEnabled(true);
}
void PredictKeyHandleUI::onDump()
{
//PredictGeneratorKey::Instance()->WriteToFile(PredictConfig::Inistance()->mConfigData.GetFullGeneratorPath().C_String());
}
void PredictKeyHandleUI::onStop()
{
//PredictGeneratorKey::Instance()->WriteToFile(PredictConfig::Inistance()->mConfigData.GetFullGeneratorPath().C_String());
//mTextEditor->Push("Write keys file successfully!");
//PredictMainWindow* mainWind = (PredictMainWindow*)mOwner;
//mainWind->StopServer();
//ui->mGeneratorKey->setEnabled(true);
//ui->mStart->setEnabled(true);
//ui->mDump->setEnabled(false);
//ui->mStop->setEnabled(false);
}
void PredictKeyHandleUI::onToggle(bool state)
{
//PredictGeneratorKey::Instance()->ToggleGeneratorKey(state);
}
void PredictKeyHandleUI::PrintMessage(const QString& text)
{
mTextEditor->Push(text);
}
void PredictKeyHandleUI::SetMainWidget(PredictMainWindow* owner)
{
mOwner = owner;
if (mOwner)
{
connect(mTextEditor, SIGNAL(MsgSignal(const QString&)), mOwner, SLOT(printText(const QString&)));
}
}
void PredictKeyHandleUI::closeEvent(QCloseEvent *event)
{
//if (ui->mStop->isEnabled())
//{
// onStop();
//}
}
#endif
| 20.911111
| 124
| 0.72051
|
Kay01010101
|
15c8014894e74be47912df906b2ec46574c05460
| 969
|
cpp
|
C++
|
lib/libCFG/src/EventManager.cpp
|
cyber-itl/citl-static-analysis
|
32ef8e519dac1c6a49ff41d902a62df8f5a8e948
|
[
"MIT"
] | 14
|
2021-05-03T16:03:22.000Z
|
2022-02-14T23:42:39.000Z
|
lib/libCFG/src/EventManager.cpp
|
cyber-itl/citl-static-analysis
|
32ef8e519dac1c6a49ff41d902a62df8f5a8e948
|
[
"MIT"
] | 1
|
2021-09-27T12:01:33.000Z
|
2021-09-27T12:01:33.000Z
|
lib/libCFG/src/EventManager.cpp
|
cyber-itl/citl-static-analysis
|
32ef8e519dac1c6a49ff41d902a62df8f5a8e948
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <memory>
#include "capstone/capstone.h"
#include "glog/logging.h"
#include "EventManager.hpp"
class CpuState;
struct Block;
struct Symbol;
void EventManager::register_event(std::unique_ptr<AnalyzerEvent> event) {
m_events.push_back(std::move(event));
}
void EventManager::run_events(event_type type, CpuState *cpu, Block *block, cs_insn *insn) {
this->run_events(type, cpu, block, insn, nullptr);
}
void EventManager::run_events(event_type type, CpuState *cpu, Block *block, cs_insn *insn, const Symbol *sym) {
for (const auto &event : m_events) {
if (event->get_type() == type) {
if (event->run(cpu, block, insn, sym)) {
LOG(FATAL) << "Failed to run event analyzer: " << event->get_name();
}
}
}
}
void EventManager::clear() {
m_events.clear();
}
const std::vector<std::unique_ptr<AnalyzerEvent>> *EventManager::get_events() const {
return &m_events;
}
| 25.5
| 111
| 0.661507
|
cyber-itl
|
15c86cc428860a4cb7b800b221c2f84e7ff73eb2
| 329
|
cpp
|
C++
|
Ejercicios/Ejercicio2-mensaje/mensajes.cpp
|
Maldanar201/LenguajeProgramacion1
|
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
|
[
"MIT"
] | null | null | null |
Ejercicios/Ejercicio2-mensaje/mensajes.cpp
|
Maldanar201/LenguajeProgramacion1
|
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
|
[
"MIT"
] | null | null | null |
Ejercicios/Ejercicio2-mensaje/mensajes.cpp
|
Maldanar201/LenguajeProgramacion1
|
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
string nombre;
cout << " ingrese su nombre: ";
cin >> nombre;
cout <<"\n Hola mi nombre es " << nombre <<endl;
cout << " Hola "<<nombre<<" Bienvenido a la Clase de Lenguaje de Programacion I "<< endl;
return 0;
}
| 19.352941
| 93
| 0.595745
|
Maldanar201
|
15ccd0fc98b06c5e61c55537bbc9f61e1f002480
| 68,063
|
cpp
|
C++
|
modules/tracktion_engine/3rd_party/airwindows/Monitoring/MonitoringProc.cpp
|
jbloit/tracktion_engine
|
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
|
[
"MIT",
"Unlicense"
] | 734
|
2018-11-16T09:39:40.000Z
|
2022-03-30T16:56:14.000Z
|
modules/tracktion_engine/3rd_party/airwindows/Monitoring/MonitoringProc.cpp
|
jbloit/tracktion_engine
|
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
|
[
"MIT",
"Unlicense"
] | 100
|
2018-11-16T18:04:08.000Z
|
2022-03-31T17:47:53.000Z
|
modules/tracktion_engine/3rd_party/airwindows/Monitoring/MonitoringProc.cpp
|
jbloit/tracktion_engine
|
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
|
[
"MIT",
"Unlicense"
] | 123
|
2018-11-16T15:51:50.000Z
|
2022-03-29T12:21:27.000Z
|
/* ========================================
* Monitoring - Monitoring.h
* Copyright (c) 2016 airwindows, All rights reserved
* ======================================== */
#ifndef __Monitoring_H
#include "Monitoring.h"
#endif
void Monitoring::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames)
{
float* in1 = inputs[0];
float* in2 = inputs[1];
float* out1 = outputs[0];
float* out2 = outputs[1];
double overallscale = 1.0;
overallscale /= 44100.0;
overallscale *= getSampleRate();
int processing = (VstInt32)( A * 16.999 );
int am = (int)149.0 * overallscale;
int bm = (int)179.0 * overallscale;
int cm = (int)191.0 * overallscale;
int dm = (int)223.0 * overallscale; //these are 'good' primes, spacing out the allpasses
int allpasstemp;
//for PeaksOnly
biquadL[0] = 0.0375/overallscale; biquadL[1] = 0.1575; //define as AURAT, MONORAT, MONOLAT unless overridden
if (processing == 7) {biquadL[0] = 0.0385/overallscale; biquadL[1] = 0.0825;}
if (processing == 11) {biquadL[0] = 0.1245/overallscale; biquadL[1] = 0.46;}
double K = tan(M_PI * biquadL[0]);
double norm = 1.0 / (1.0 + K / biquadL[1] + K * K);
biquadL[2] = K / biquadL[1] * norm;
biquadL[4] = -biquadL[2]; //for bandpass, ignore [3] = 0.0
biquadL[5] = 2.0 * (K * K - 1.0) * norm;
biquadL[6] = (1.0 - K / biquadL[1] + K * K) * norm;
//for Bandpasses
biquadR[0] = 0.0375/overallscale; biquadR[1] = 0.1575; //define as AURAT, MONORAT, MONOLAT unless overridden
if (processing == 7) {biquadR[0] = 0.0385/overallscale; biquadR[1] = 0.0825;}
if (processing == 11) {biquadR[0] = 0.1245/overallscale; biquadR[1] = 0.46;}
K = tan(M_PI * biquadR[0]);
norm = 1.0 / (1.0 + K / biquadR[1] + K * K);
biquadR[2] = K / biquadR[1] * norm;
biquadR[4] = -biquadR[2]; //for bandpass, ignore [3] = 0.0
biquadR[5] = 2.0 * (K * K - 1.0) * norm;
biquadR[6] = (1.0 - K / biquadR[1] + K * K) * norm;
//for Bandpasses
while (--sampleFrames >= 0)
{
long double inputSampleL = *in1;
long double inputSampleR = *in2;
if (fabs(inputSampleL)<1.18e-37) inputSampleL = fpd * 1.18e-37;
if (fabs(inputSampleR)<1.18e-37) inputSampleR = fpd * 1.18e-37;
switch (processing)
{
case 0:
case 1:
break;
case 2:
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//amplitude aspect
allpasstemp = ax - 1; if (allpasstemp < 0 || allpasstemp > am) allpasstemp = am;
inputSampleL -= aL[allpasstemp]*0.5; aL[ax] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= aR[allpasstemp]*0.5; aR[ax] = inputSampleR; inputSampleR *= 0.5;
ax--; if (ax < 0 || ax > am) {ax = am;}
inputSampleL += (aL[ax]);
inputSampleR += (aR[ax]);
//a single Midiverb-style allpass
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//amplitude aspect
allpasstemp = bx - 1; if (allpasstemp < 0 || allpasstemp > bm) allpasstemp = bm;
inputSampleL -= bL[allpasstemp]*0.5; bL[bx] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= bR[allpasstemp]*0.5; bR[bx] = inputSampleR; inputSampleR *= 0.5;
bx--; if (bx < 0 || bx > bm) {bx = bm;}
inputSampleL += (bL[bx]);
inputSampleR += (bR[bx]);
//a single Midiverb-style allpass
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//amplitude aspect
allpasstemp = cx - 1; if (allpasstemp < 0 || allpasstemp > cm) allpasstemp = cm;
inputSampleL -= cL[allpasstemp]*0.5; cL[cx] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= cR[allpasstemp]*0.5; cR[cx] = inputSampleR; inputSampleR *= 0.5;
cx--; if (cx < 0 || cx > cm) {cx = cm;}
inputSampleL += (cL[cx]);
inputSampleR += (cR[cx]);
//a single Midiverb-style allpass
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//amplitude aspect
allpasstemp = dx - 1; if (allpasstemp < 0 || allpasstemp > dm) allpasstemp = dm;
inputSampleL -= dL[allpasstemp]*0.5; dL[dx] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= dR[allpasstemp]*0.5; dR[dx] = inputSampleR; inputSampleR *= 0.5;
dx--; if (dx < 0 || dx > dm) {dx = dm;}
inputSampleL += (dL[dx]);
inputSampleR += (dR[dx]);
//a single Midiverb-style allpass
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//amplitude aspect
inputSampleL *= 0.63679; inputSampleR *= 0.63679; //scale it to 0dB output at full blast
//PeaksOnly
break;
case 3:
double trim;
trim = 2.302585092994045684017991; //natural logarithm of 10
long double slewSample; slewSample = (inputSampleL - lastSampleL)*trim;
lastSampleL = inputSampleL;
if (slewSample > 1.0) slewSample = 1.0; if (slewSample < -1.0) slewSample = -1.0;
inputSampleL = slewSample;
slewSample = (inputSampleR - lastSampleR)*trim;
lastSampleR = inputSampleR;
if (slewSample > 1.0) slewSample = 1.0; if (slewSample < -1.0) slewSample = -1.0;
inputSampleR = slewSample;
//SlewOnly
break;
case 4:
double iirAmount; iirAmount = (2250/44100.0) / overallscale;
double gain; gain = 1.42;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
iirSampleAL = (iirSampleAL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleAL;
iirSampleAR = (iirSampleAR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleAR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleBL = (iirSampleBL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleBL;
iirSampleBR = (iirSampleBR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleBR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleCL = (iirSampleCL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleCL;
iirSampleCR = (iirSampleCR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleCR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleDL = (iirSampleDL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleDL;
iirSampleDR = (iirSampleDR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleDR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleEL = (iirSampleEL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleEL;
iirSampleER = (iirSampleER * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleER;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleFL = (iirSampleFL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleFL;
iirSampleFR = (iirSampleFR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleFR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleGL = (iirSampleGL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleGL;
iirSampleGR = (iirSampleGR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleGR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleHL = (iirSampleHL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleHL;
iirSampleHR = (iirSampleHR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleHR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleIL = (iirSampleIL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleIL;
iirSampleIR = (iirSampleIR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleIR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleJL = (iirSampleJL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleJL;
iirSampleJR = (iirSampleJR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleJR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleKL = (iirSampleKL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleKL;
iirSampleKR = (iirSampleKR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleKR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleLL = (iirSampleLL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleLL;
iirSampleLR = (iirSampleLR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleLR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleML = (iirSampleML * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleML;
iirSampleMR = (iirSampleMR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleMR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleNL = (iirSampleNL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleNL;
iirSampleNR = (iirSampleNR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleNR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleOL = (iirSampleOL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleOL;
iirSampleOR = (iirSampleOR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleOR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSamplePL = (iirSamplePL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSamplePL;
iirSamplePR = (iirSamplePR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSamplePR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleQL = (iirSampleQL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleQL;
iirSampleQR = (iirSampleQR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleQR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleRL = (iirSampleRL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleRL;
iirSampleRR = (iirSampleRR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleRR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleSL = (iirSampleSL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleSL;
iirSampleSR = (iirSampleSR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleSR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleTL = (iirSampleTL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleTL;
iirSampleTR = (iirSampleTR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleTR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleUL = (iirSampleUL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleUL;
iirSampleUR = (iirSampleUR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleUR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleVL = (iirSampleVL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleVL;
iirSampleVR = (iirSampleVR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleVR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleWL = (iirSampleWL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleWL;
iirSampleWR = (iirSampleWR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleWR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleXL = (iirSampleXL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleXL;
iirSampleXR = (iirSampleXR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleXR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleYL = (iirSampleYL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleYL;
iirSampleYR = (iirSampleYR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleYR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleZL = (iirSampleZL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleZL;
iirSampleZR = (iirSampleZR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleZR;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
//SubsOnly
break;
case 5:
case 6:
long double mid; mid = inputSampleL + inputSampleR;
long double side; side = inputSampleL - inputSampleR;
if (processing < 6) side = 0.0;
else mid = 0.0; //mono monitoring, or side-only monitoring
inputSampleL = (mid+side)/2.0;
inputSampleR = (mid-side)/2.0;
break;
case 7:
case 8:
case 9:
case 10:
case 11:
//Bandpass: changes in EQ are up in the variable defining, not here
//7 Vinyl, 8 9 10 Aurat, 11 Phone
if (processing == 9) {inputSampleR = (inputSampleL + inputSampleR)*0.5;inputSampleL = 0.0;}
if (processing == 10) {inputSampleL = (inputSampleL + inputSampleR)*0.5;inputSampleR = 0.0;}
if (processing == 11) {long double M; M = (inputSampleL + inputSampleR)*0.5; inputSampleL = M;inputSampleR = M;}
inputSampleL = sin(inputSampleL); inputSampleR = sin(inputSampleR);
//encode Console5: good cleanness
long double tempSampleL; tempSampleL = (inputSampleL * biquadL[2]) + biquadL[7];
biquadL[7] = (-tempSampleL * biquadL[5]) + biquadL[8];
biquadL[8] = (inputSampleL * biquadL[4]) - (tempSampleL * biquadL[6]);
inputSampleL = tempSampleL; //like mono AU, 7 and 8 store L channel
long double tempSampleR; tempSampleR = (inputSampleR * biquadR[2]) + biquadR[7];
biquadR[7] = (-tempSampleR * biquadR[5]) + biquadR[8];
biquadR[8] = (inputSampleR * biquadR[4]) - (tempSampleR * biquadR[6]);
inputSampleR = tempSampleR; // we are using the mono configuration
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
//without this, you can get a NaN condition where it spits out DC offset at full blast!
inputSampleL = asin(inputSampleL); inputSampleR = asin(inputSampleR);
//amplitude aspect
break;
case 12:
case 13:
case 14:
case 15:
if (processing == 12) {inputSampleL *= 0.855; inputSampleR *= 0.855;}
if (processing == 13) {inputSampleL *= 0.748; inputSampleR *= 0.748;}
if (processing == 14) {inputSampleL *= 0.713; inputSampleR *= 0.713;}
if (processing == 15) {inputSampleL *= 0.680; inputSampleR *= 0.680;}
//we do a volume compensation immediately to gain stage stuff cleanly
inputSampleL = sin(inputSampleL);
inputSampleR = sin(inputSampleR);
long double drySampleL; drySampleL = inputSampleL;
long double drySampleR; drySampleR = inputSampleR; //everything runs 'inside' Console
long double bass; bass = (processing * processing * 0.00001) / overallscale;
//we are using the iir filters from out of SubsOnly
mid = inputSampleL + inputSampleR; side = inputSampleL - inputSampleR;
iirSampleAL = (iirSampleAL * (1.0 - (bass*0.618))) + (side * bass * 0.618); side = side - iirSampleAL;
inputSampleL = (mid+side)/2.0; inputSampleR = (mid-side)/2.0;
//bass narrowing filter
allpasstemp = ax - 1; if (allpasstemp < 0 || allpasstemp > am) allpasstemp = am;
inputSampleL -= aL[allpasstemp]*0.5; aL[ax] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= aR[allpasstemp]*0.5; aR[ax] = inputSampleR; inputSampleR *= 0.5;
ax--; if (ax < 0 || ax > am) {ax = am;}
inputSampleL += (aL[ax])*0.5; inputSampleR += (aR[ax])*0.5;
if (ax == am) {inputSampleL += (aL[0])*0.5; inputSampleR += (aR[0])*0.5;}
else {inputSampleL += (aL[ax+1])*0.5; inputSampleR += (aR[ax+1])*0.5;}
//a darkened Midiverb-style allpass
if (processing == 12) {inputSampleL *= 0.125; inputSampleR *= 0.125;}
if (processing == 13) {inputSampleL *= 0.25; inputSampleR *= 0.25;}
if (processing == 14) {inputSampleL *= 0.30; inputSampleR *= 0.30;}
if (processing == 15) {inputSampleL *= 0.35; inputSampleR *= 0.35;}
//Cans A suppresses the crossfeed more, Cans B makes it louder
drySampleL += inputSampleR;
drySampleR += inputSampleL; //the crossfeed
allpasstemp = dx - 1; if (allpasstemp < 0 || allpasstemp > dm) allpasstemp = dm;
inputSampleL -= dL[allpasstemp]*0.5; dL[dx] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= dR[allpasstemp]*0.5; dR[dx] = inputSampleR; inputSampleR *= 0.5;
dx--; if (dx < 0 || dx > dm) {dx = dm;}
inputSampleL += (dL[dx])*0.5; inputSampleR += (dR[dx])*0.5;
if (dx == dm) {inputSampleL += (dL[0])*0.5; inputSampleR += (dR[0])*0.5;}
else {inputSampleL += (dL[dx+1])*0.5; inputSampleR += (dR[dx+1])*0.5;}
//a darkened Midiverb-style allpass, which is stretching the previous one even more
inputSampleL *= 0.25; inputSampleR *= 0.25;
//for all versions of Cans the second level of bloom is this far down
//and, remains on the opposite speaker rather than crossing again to the original side
drySampleL += inputSampleR;
drySampleR += inputSampleL; //add the crossfeed and very faint extra verbyness
inputSampleL = drySampleL;
inputSampleR = drySampleR; //and output our can-opened headphone feed
mid = inputSampleL + inputSampleR; side = inputSampleL - inputSampleR;
iirSampleAR = (iirSampleAR * (1.0 - bass)) + (side * bass); side = side - iirSampleAR;
inputSampleL = (mid+side)/2.0; inputSampleR = (mid-side)/2.0;
//bass narrowing filter
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//ConsoleBuss processing
break;
case 16:
long double inputSample = (inputSampleL + inputSampleR) * 0.5;
inputSampleL = -inputSample;
inputSampleR = inputSample;
break;
}
//begin Not Just Another Dither
if (processing == 1) {
inputSampleL = inputSampleL * 32768.0; //or 16 bit option
inputSampleR = inputSampleR * 32768.0; //or 16 bit option
} else {
inputSampleL = inputSampleL * 8388608.0; //for literally everything else
inputSampleR = inputSampleR * 8388608.0; //we will apply the 24 bit NJAD
} //on the not unreasonable assumption that we are very likely playing back on 24 bit DAC
//if we're not, then all we did was apply a Benford Realness function at 24 bits down.
bool cutbinsL; cutbinsL = false;
bool cutbinsR; cutbinsR = false;
long double drySampleL; drySampleL = inputSampleL;
long double drySampleR; drySampleR = inputSampleR;
inputSampleL -= noiseShapingL;
inputSampleR -= noiseShapingR;
//NJAD L
long double benfordize; benfordize = floor(inputSampleL);
while (benfordize >= 1.0) benfordize /= 10;
while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10;
int hotbinA; hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
long double totalA; totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynL[hotbinA] += 1; if (bynL[hotbinA] > 982) cutbinsL = true;
totalA += (301-bynL[1]); totalA += (176-bynL[2]); totalA += (125-bynL[3]);
totalA += (97-bynL[4]); totalA += (79-bynL[5]); totalA += (67-bynL[6]);
totalA += (58-bynL[7]); totalA += (51-bynL[8]); totalA += (46-bynL[9]); bynL[hotbinA] -= 1;
} else hotbinA = 10;
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleL);
while (benfordize >= 1.0) benfordize /= 10;
while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10;
int hotbinB; hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
long double totalB; totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynL[hotbinB] += 1; if (bynL[hotbinB] > 982) cutbinsL = true;
totalB += (301-bynL[1]); totalB += (176-bynL[2]); totalB += (125-bynL[3]);
totalB += (97-bynL[4]); totalB += (79-bynL[5]); totalB += (67-bynL[6]);
totalB += (58-bynL[7]); totalB += (51-bynL[8]); totalB += (46-bynL[9]); bynL[hotbinB] -= 1;
} else hotbinB = 10;
//produce total number- smaller is closer to Benford real
long double outputSample;
if (totalA < totalB) {bynL[hotbinA] += 1; outputSample = floor(inputSampleL);}
else {bynL[hotbinB] += 1; outputSample = floor(inputSampleL+1);}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
if (cutbinsL) {
bynL[1] *= 0.99; bynL[2] *= 0.99; bynL[3] *= 0.99; bynL[4] *= 0.99; bynL[5] *= 0.99;
bynL[6] *= 0.99; bynL[7] *= 0.99; bynL[8] *= 0.99; bynL[9] *= 0.99; bynL[10] *= 0.99;
}
noiseShapingL += outputSample - drySampleL;
if (noiseShapingL > fabs(inputSampleL)) noiseShapingL = fabs(inputSampleL);
if (noiseShapingL < -fabs(inputSampleL)) noiseShapingL = -fabs(inputSampleL);
if (processing == 1) inputSampleL = outputSample / 32768.0;
else inputSampleL = outputSample / 8388608.0;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
//finished NJAD L
//NJAD R
benfordize = floor(inputSampleR);
while (benfordize >= 1.0) benfordize /= 10;
while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10;
hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynR[hotbinA] += 1; if (bynR[hotbinA] > 982) cutbinsR = true;
totalA += (301-bynR[1]); totalA += (176-bynR[2]); totalA += (125-bynR[3]);
totalA += (97-bynR[4]); totalA += (79-bynR[5]); totalA += (67-bynR[6]);
totalA += (58-bynR[7]); totalA += (51-bynR[8]); totalA += (46-bynR[9]); bynR[hotbinA] -= 1;
} else hotbinA = 10;
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleR);
while (benfordize >= 1.0) benfordize /= 10;
while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10;
hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynR[hotbinB] += 1; if (bynR[hotbinB] > 982) cutbinsR = true;
totalB += (301-bynR[1]); totalB += (176-bynR[2]); totalB += (125-bynR[3]);
totalB += (97-bynR[4]); totalB += (79-bynR[5]); totalB += (67-bynR[6]);
totalB += (58-bynR[7]); totalB += (51-bynR[8]); totalB += (46-bynR[9]); bynR[hotbinB] -= 1;
} else hotbinB = 10;
//produce total number- smaller is closer to Benford real
if (totalA < totalB) {bynR[hotbinA] += 1; outputSample = floor(inputSampleR);}
else {bynR[hotbinB] += 1; outputSample = floor(inputSampleR+1);}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
if (cutbinsR) {
bynR[1] *= 0.99; bynR[2] *= 0.99; bynR[3] *= 0.99; bynR[4] *= 0.99; bynR[5] *= 0.99;
bynR[6] *= 0.99; bynR[7] *= 0.99; bynR[8] *= 0.99; bynR[9] *= 0.99; bynR[10] *= 0.99;
}
noiseShapingR += outputSample - drySampleR;
if (noiseShapingR > fabs(inputSampleR)) noiseShapingR = fabs(inputSampleR);
if (noiseShapingR < -fabs(inputSampleR)) noiseShapingR = -fabs(inputSampleR);
if (processing == 1) inputSampleR = outputSample / 32768.0;
else inputSampleR = outputSample / 8388608.0;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
//finished NJAD R
//does not use 32 bit stereo floating point dither
*out1 = inputSampleL;
*out2 = inputSampleR;
*in1++;
*in2++;
*out1++;
*out2++;
}
}
void Monitoring::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames)
{
double* in1 = inputs[0];
double* in2 = inputs[1];
double* out1 = outputs[0];
double* out2 = outputs[1];
double overallscale = 1.0;
overallscale /= 44100.0;
overallscale *= getSampleRate();
int processing = (VstInt32)( A * 16.999 );
int am = (int)149.0 * overallscale;
int bm = (int)179.0 * overallscale;
int cm = (int)191.0 * overallscale;
int dm = (int)223.0 * overallscale; //these are 'good' primes, spacing out the allpasses
int allpasstemp;
//for PeaksOnly
biquadL[0] = 0.0375/overallscale; biquadL[1] = 0.1575; //define as AURAT, MONORAT, MONOLAT unless overridden
if (processing == 7) {biquadL[0] = 0.0385/overallscale; biquadL[1] = 0.0825;}
if (processing == 11) {biquadL[0] = 0.1245/overallscale; biquadL[1] = 0.46;}
double K = tan(M_PI * biquadL[0]);
double norm = 1.0 / (1.0 + K / biquadL[1] + K * K);
biquadL[2] = K / biquadL[1] * norm;
biquadL[4] = -biquadL[2]; //for bandpass, ignore [3] = 0.0
biquadL[5] = 2.0 * (K * K - 1.0) * norm;
biquadL[6] = (1.0 - K / biquadL[1] + K * K) * norm;
//for Bandpasses
biquadR[0] = 0.0375/overallscale; biquadR[1] = 0.1575; //define as AURAT, MONORAT, MONOLAT unless overridden
if (processing == 7) {biquadR[0] = 0.0385/overallscale; biquadR[1] = 0.0825;}
if (processing == 11) {biquadR[0] = 0.1245/overallscale; biquadR[1] = 0.46;}
K = tan(M_PI * biquadR[0]);
norm = 1.0 / (1.0 + K / biquadR[1] + K * K);
biquadR[2] = K / biquadR[1] * norm;
biquadR[4] = -biquadR[2]; //for bandpass, ignore [3] = 0.0
biquadR[5] = 2.0 * (K * K - 1.0) * norm;
biquadR[6] = (1.0 - K / biquadR[1] + K * K) * norm;
//for Bandpasses
while (--sampleFrames >= 0)
{
long double inputSampleL = *in1;
long double inputSampleR = *in2;
if (fabs(inputSampleL)<1.18e-43) inputSampleL = fpd * 1.18e-43;
if (fabs(inputSampleR)<1.18e-43) inputSampleR = fpd * 1.18e-43;
switch (processing)
{
case 0:
case 1:
break;
case 2:
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//amplitude aspect
allpasstemp = ax - 1; if (allpasstemp < 0 || allpasstemp > am) allpasstemp = am;
inputSampleL -= aL[allpasstemp]*0.5; aL[ax] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= aR[allpasstemp]*0.5; aR[ax] = inputSampleR; inputSampleR *= 0.5;
ax--; if (ax < 0 || ax > am) {ax = am;}
inputSampleL += (aL[ax]);
inputSampleR += (aR[ax]);
//a single Midiverb-style allpass
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//amplitude aspect
allpasstemp = bx - 1; if (allpasstemp < 0 || allpasstemp > bm) allpasstemp = bm;
inputSampleL -= bL[allpasstemp]*0.5; bL[bx] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= bR[allpasstemp]*0.5; bR[bx] = inputSampleR; inputSampleR *= 0.5;
bx--; if (bx < 0 || bx > bm) {bx = bm;}
inputSampleL += (bL[bx]);
inputSampleR += (bR[bx]);
//a single Midiverb-style allpass
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//amplitude aspect
allpasstemp = cx - 1; if (allpasstemp < 0 || allpasstemp > cm) allpasstemp = cm;
inputSampleL -= cL[allpasstemp]*0.5; cL[cx] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= cR[allpasstemp]*0.5; cR[cx] = inputSampleR; inputSampleR *= 0.5;
cx--; if (cx < 0 || cx > cm) {cx = cm;}
inputSampleL += (cL[cx]);
inputSampleR += (cR[cx]);
//a single Midiverb-style allpass
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//amplitude aspect
allpasstemp = dx - 1; if (allpasstemp < 0 || allpasstemp > dm) allpasstemp = dm;
inputSampleL -= dL[allpasstemp]*0.5; dL[dx] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= dR[allpasstemp]*0.5; dR[dx] = inputSampleR; inputSampleR *= 0.5;
dx--; if (dx < 0 || dx > dm) {dx = dm;}
inputSampleL += (dL[dx]);
inputSampleR += (dR[dx]);
//a single Midiverb-style allpass
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//amplitude aspect
inputSampleL *= 0.63679; inputSampleR *= 0.63679; //scale it to 0dB output at full blast
//PeaksOnly
break;
case 3:
double trim;
trim = 2.302585092994045684017991; //natural logarithm of 10
long double slewSample; slewSample = (inputSampleL - lastSampleL)*trim;
lastSampleL = inputSampleL;
if (slewSample > 1.0) slewSample = 1.0; if (slewSample < -1.0) slewSample = -1.0;
inputSampleL = slewSample;
slewSample = (inputSampleR - lastSampleR)*trim;
lastSampleR = inputSampleR;
if (slewSample > 1.0) slewSample = 1.0; if (slewSample < -1.0) slewSample = -1.0;
inputSampleR = slewSample;
//SlewOnly
break;
case 4:
double iirAmount; iirAmount = (2250/44100.0) / overallscale;
double gain; gain = 1.42;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
iirSampleAL = (iirSampleAL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleAL;
iirSampleAR = (iirSampleAR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleAR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleBL = (iirSampleBL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleBL;
iirSampleBR = (iirSampleBR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleBR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleCL = (iirSampleCL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleCL;
iirSampleCR = (iirSampleCR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleCR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleDL = (iirSampleDL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleDL;
iirSampleDR = (iirSampleDR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleDR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleEL = (iirSampleEL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleEL;
iirSampleER = (iirSampleER * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleER;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleFL = (iirSampleFL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleFL;
iirSampleFR = (iirSampleFR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleFR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleGL = (iirSampleGL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleGL;
iirSampleGR = (iirSampleGR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleGR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleHL = (iirSampleHL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleHL;
iirSampleHR = (iirSampleHR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleHR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleIL = (iirSampleIL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleIL;
iirSampleIR = (iirSampleIR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleIR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleJL = (iirSampleJL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleJL;
iirSampleJR = (iirSampleJR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleJR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleKL = (iirSampleKL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleKL;
iirSampleKR = (iirSampleKR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleKR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleLL = (iirSampleLL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleLL;
iirSampleLR = (iirSampleLR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleLR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleML = (iirSampleML * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleML;
iirSampleMR = (iirSampleMR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleMR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleNL = (iirSampleNL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleNL;
iirSampleNR = (iirSampleNR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleNR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleOL = (iirSampleOL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleOL;
iirSampleOR = (iirSampleOR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleOR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSamplePL = (iirSamplePL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSamplePL;
iirSamplePR = (iirSamplePR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSamplePR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleQL = (iirSampleQL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleQL;
iirSampleQR = (iirSampleQR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleQR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleRL = (iirSampleRL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleRL;
iirSampleRR = (iirSampleRR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleRR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleSL = (iirSampleSL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleSL;
iirSampleSR = (iirSampleSR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleSR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleTL = (iirSampleTL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleTL;
iirSampleTR = (iirSampleTR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleTR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleUL = (iirSampleUL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleUL;
iirSampleUR = (iirSampleUR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleUR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleVL = (iirSampleVL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleVL;
iirSampleVR = (iirSampleVR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleVR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleWL = (iirSampleWL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleWL;
iirSampleWR = (iirSampleWR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleWR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleXL = (iirSampleXL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleXL;
iirSampleXR = (iirSampleXR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleXR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleYL = (iirSampleYL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleYL;
iirSampleYR = (iirSampleYR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleYR;
inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleZL = (iirSampleZL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleZL;
iirSampleZR = (iirSampleZR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleZR;
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
//SubsOnly
break;
case 5:
case 6:
long double mid; mid = inputSampleL + inputSampleR;
long double side; side = inputSampleL - inputSampleR;
if (processing < 6) side = 0.0;
else mid = 0.0; //mono monitoring, or side-only monitoring
inputSampleL = (mid+side)/2.0;
inputSampleR = (mid-side)/2.0;
break;
case 7:
case 8:
case 9:
case 10:
case 11:
//Bandpass: changes in EQ are up in the variable defining, not here
//7 Vinyl, 8 9 10 Aurat, 11 Phone
if (processing == 9) {inputSampleR = (inputSampleL + inputSampleR)*0.5;inputSampleL = 0.0;}
if (processing == 10) {inputSampleL = (inputSampleL + inputSampleR)*0.5;inputSampleR = 0.0;}
if (processing == 11) {long double M; M = (inputSampleL + inputSampleR)*0.5; inputSampleL = M;inputSampleR = M;}
inputSampleL = sin(inputSampleL); inputSampleR = sin(inputSampleR);
//encode Console5: good cleanness
long double tempSampleL; tempSampleL = (inputSampleL * biquadL[2]) + biquadL[7];
biquadL[7] = (-tempSampleL * biquadL[5]) + biquadL[8];
biquadL[8] = (inputSampleL * biquadL[4]) - (tempSampleL * biquadL[6]);
inputSampleL = tempSampleL; //like mono AU, 7 and 8 store L channel
long double tempSampleR; tempSampleR = (inputSampleR * biquadR[2]) + biquadR[7];
biquadR[7] = (-tempSampleR * biquadR[5]) + biquadR[8];
biquadR[8] = (inputSampleR * biquadR[4]) - (tempSampleR * biquadR[6]);
inputSampleR = tempSampleR; // we are using the mono configuration
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0;
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0;
//without this, you can get a NaN condition where it spits out DC offset at full blast!
inputSampleL = asin(inputSampleL); inputSampleR = asin(inputSampleR);
//amplitude aspect
break;
case 12:
case 13:
case 14:
case 15:
if (processing == 12) {inputSampleL *= 0.855; inputSampleR *= 0.855;}
if (processing == 13) {inputSampleL *= 0.748; inputSampleR *= 0.748;}
if (processing == 14) {inputSampleL *= 0.713; inputSampleR *= 0.713;}
if (processing == 15) {inputSampleL *= 0.680; inputSampleR *= 0.680;}
//we do a volume compensation immediately to gain stage stuff cleanly
inputSampleL = sin(inputSampleL);
inputSampleR = sin(inputSampleR);
long double drySampleL; drySampleL = inputSampleL;
long double drySampleR; drySampleR = inputSampleR; //everything runs 'inside' Console
long double bass; bass = (processing * processing * 0.00001) / overallscale;
//we are using the iir filters from out of SubsOnly
mid = inputSampleL + inputSampleR; side = inputSampleL - inputSampleR;
iirSampleAL = (iirSampleAL * (1.0 - (bass*0.618))) + (side * bass * 0.618); side = side - iirSampleAL;
inputSampleL = (mid+side)/2.0; inputSampleR = (mid-side)/2.0;
//bass narrowing filter
allpasstemp = ax - 1; if (allpasstemp < 0 || allpasstemp > am) allpasstemp = am;
inputSampleL -= aL[allpasstemp]*0.5; aL[ax] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= aR[allpasstemp]*0.5; aR[ax] = inputSampleR; inputSampleR *= 0.5;
ax--; if (ax < 0 || ax > am) {ax = am;}
inputSampleL += (aL[ax])*0.5; inputSampleR += (aR[ax])*0.5;
if (ax == am) {inputSampleL += (aL[0])*0.5; inputSampleR += (aR[0])*0.5;}
else {inputSampleL += (aL[ax+1])*0.5; inputSampleR += (aR[ax+1])*0.5;}
//a darkened Midiverb-style allpass
if (processing == 12) {inputSampleL *= 0.125; inputSampleR *= 0.125;}
if (processing == 13) {inputSampleL *= 0.25; inputSampleR *= 0.25;}
if (processing == 14) {inputSampleL *= 0.30; inputSampleR *= 0.30;}
if (processing == 15) {inputSampleL *= 0.35; inputSampleR *= 0.35;}
//Cans A suppresses the crossfeed more, Cans B makes it louder
drySampleL += inputSampleR;
drySampleR += inputSampleL; //the crossfeed
allpasstemp = dx - 1; if (allpasstemp < 0 || allpasstemp > dm) allpasstemp = dm;
inputSampleL -= dL[allpasstemp]*0.5; dL[dx] = inputSampleL; inputSampleL *= 0.5;
inputSampleR -= dR[allpasstemp]*0.5; dR[dx] = inputSampleR; inputSampleR *= 0.5;
dx--; if (dx < 0 || dx > dm) {dx = dm;}
inputSampleL += (dL[dx])*0.5; inputSampleR += (dR[dx])*0.5;
if (dx == dm) {inputSampleL += (dL[0])*0.5; inputSampleR += (dR[0])*0.5;}
else {inputSampleL += (dL[dx+1])*0.5; inputSampleR += (dR[dx+1])*0.5;}
//a darkened Midiverb-style allpass, which is stretching the previous one even more
inputSampleL *= 0.25; inputSampleR *= 0.25;
//for all versions of Cans the second level of bloom is this far down
//and, remains on the opposite speaker rather than crossing again to the original side
drySampleL += inputSampleR;
drySampleR += inputSampleL; //add the crossfeed and very faint extra verbyness
inputSampleL = drySampleL;
inputSampleR = drySampleR; //and output our can-opened headphone feed
mid = inputSampleL + inputSampleR; side = inputSampleL - inputSampleR;
iirSampleAR = (iirSampleAR * (1.0 - bass)) + (side * bass); side = side - iirSampleAR;
inputSampleL = (mid+side)/2.0; inputSampleR = (mid-side)/2.0;
//bass narrowing filter
if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL);
if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR);
//ConsoleBuss processing
break;
case 16:
long double inputSample = (inputSampleL + inputSampleR) * 0.5;
inputSampleL = -inputSample;
inputSampleR = inputSample;
break;
}
//begin Not Just Another Dither
if (processing == 1) {
inputSampleL = inputSampleL * 32768.0; //or 16 bit option
inputSampleR = inputSampleR * 32768.0; //or 16 bit option
} else {
inputSampleL = inputSampleL * 8388608.0; //for literally everything else
inputSampleR = inputSampleR * 8388608.0; //we will apply the 24 bit NJAD
} //on the not unreasonable assumption that we are very likely playing back on 24 bit DAC
//if we're not, then all we did was apply a Benford Realness function at 24 bits down.
bool cutbinsL; cutbinsL = false;
bool cutbinsR; cutbinsR = false;
long double drySampleL; drySampleL = inputSampleL;
long double drySampleR; drySampleR = inputSampleR;
inputSampleL -= noiseShapingL;
inputSampleR -= noiseShapingR;
//NJAD L
long double benfordize; benfordize = floor(inputSampleL);
while (benfordize >= 1.0) benfordize /= 10;
while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10;
int hotbinA; hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
long double totalA; totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynL[hotbinA] += 1; if (bynL[hotbinA] > 982) cutbinsL = true;
totalA += (301-bynL[1]); totalA += (176-bynL[2]); totalA += (125-bynL[3]);
totalA += (97-bynL[4]); totalA += (79-bynL[5]); totalA += (67-bynL[6]);
totalA += (58-bynL[7]); totalA += (51-bynL[8]); totalA += (46-bynL[9]); bynL[hotbinA] -= 1;
} else hotbinA = 10;
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleL);
while (benfordize >= 1.0) benfordize /= 10;
while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10;
int hotbinB; hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
long double totalB; totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynL[hotbinB] += 1; if (bynL[hotbinB] > 982) cutbinsL = true;
totalB += (301-bynL[1]); totalB += (176-bynL[2]); totalB += (125-bynL[3]);
totalB += (97-bynL[4]); totalB += (79-bynL[5]); totalB += (67-bynL[6]);
totalB += (58-bynL[7]); totalB += (51-bynL[8]); totalB += (46-bynL[9]); bynL[hotbinB] -= 1;
} else hotbinB = 10;
//produce total number- smaller is closer to Benford real
long double outputSample;
if (totalA < totalB) {bynL[hotbinA] += 1; outputSample = floor(inputSampleL);}
else {bynL[hotbinB] += 1; outputSample = floor(inputSampleL+1);}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
if (cutbinsL) {
bynL[1] *= 0.99; bynL[2] *= 0.99; bynL[3] *= 0.99; bynL[4] *= 0.99; bynL[5] *= 0.99;
bynL[6] *= 0.99; bynL[7] *= 0.99; bynL[8] *= 0.99; bynL[9] *= 0.99; bynL[10] *= 0.99;
}
noiseShapingL += outputSample - drySampleL;
if (noiseShapingL > fabs(inputSampleL)) noiseShapingL = fabs(inputSampleL);
if (noiseShapingL < -fabs(inputSampleL)) noiseShapingL = -fabs(inputSampleL);
if (processing == 1) inputSampleL = outputSample / 32768.0;
else inputSampleL = outputSample / 8388608.0;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
//finished NJAD L
//NJAD R
benfordize = floor(inputSampleR);
while (benfordize >= 1.0) benfordize /= 10;
while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10;
hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynR[hotbinA] += 1; if (bynR[hotbinA] > 982) cutbinsR = true;
totalA += (301-bynR[1]); totalA += (176-bynR[2]); totalA += (125-bynR[3]);
totalA += (97-bynR[4]); totalA += (79-bynR[5]); totalA += (67-bynR[6]);
totalA += (58-bynR[7]); totalA += (51-bynR[8]); totalA += (46-bynR[9]); bynR[hotbinA] -= 1;
} else hotbinA = 10;
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleR);
while (benfordize >= 1.0) benfordize /= 10;
while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10;
hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynR[hotbinB] += 1; if (bynR[hotbinB] > 982) cutbinsR = true;
totalB += (301-bynR[1]); totalB += (176-bynR[2]); totalB += (125-bynR[3]);
totalB += (97-bynR[4]); totalB += (79-bynR[5]); totalB += (67-bynR[6]);
totalB += (58-bynR[7]); totalB += (51-bynR[8]); totalB += (46-bynR[9]); bynR[hotbinB] -= 1;
} else hotbinB = 10;
//produce total number- smaller is closer to Benford real
if (totalA < totalB) {bynR[hotbinA] += 1; outputSample = floor(inputSampleR);}
else {bynR[hotbinB] += 1; outputSample = floor(inputSampleR+1);}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
if (cutbinsR) {
bynR[1] *= 0.99; bynR[2] *= 0.99; bynR[3] *= 0.99; bynR[4] *= 0.99; bynR[5] *= 0.99;
bynR[6] *= 0.99; bynR[7] *= 0.99; bynR[8] *= 0.99; bynR[9] *= 0.99; bynR[10] *= 0.99;
}
noiseShapingR += outputSample - drySampleR;
if (noiseShapingR > fabs(inputSampleR)) noiseShapingR = fabs(inputSampleR);
if (noiseShapingR < -fabs(inputSampleR)) noiseShapingR = -fabs(inputSampleR);
if (processing == 1) inputSampleR = outputSample / 32768.0;
else inputSampleR = outputSample / 8388608.0;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
//finished NJAD R
//does not use 64 bit stereo floating point dither
*out1 = inputSampleL;
*out2 = inputSampleR;
*in1++;
*in2++;
*out1++;
*out2++;
}
}
| 65.256951
| 140
| 0.569516
|
jbloit
|
15d676c6180ce90376b5d3c6186a56672ded86c5
| 2,928
|
hpp
|
C++
|
filterbuf.hpp
|
hmito/hmLib
|
0f2515ba9c99c06d02e2fa633eeae73bcd793983
|
[
"MIT"
] | null | null | null |
filterbuf.hpp
|
hmito/hmLib
|
0f2515ba9c99c06d02e2fa633eeae73bcd793983
|
[
"MIT"
] | null | null | null |
filterbuf.hpp
|
hmito/hmLib
|
0f2515ba9c99c06d02e2fa633eeae73bcd793983
|
[
"MIT"
] | 1
|
2015-09-22T03:32:11.000Z
|
2015-09-22T03:32:11.000Z
|
#ifndef HMLIB_FILTERBUF_INC
#define HMLIB_FILTERBUF_INC 102
#
/*===filterbuf===
filterbuf_v1_02/130101 hmIto
iostreamに対応
*/
#include<streambuf>
#include<iostream>
namespace hmLib{
template<class _Elem,class _Traits=std::char_traits<_Elem>>
class basic_filterbuf{
protected:
typedef std::basic_istream<_Elem,_Traits> istream;
typedef std::basic_ostream<_Elem,_Traits> ostream;
typedef std::basic_iostream<_Elem,_Traits> iostream;
typedef basic_filterbuf<_Elem,_Traits> my_type;
typedef std::ios::pos_type pos_type;
typedef std::ios::off_type off_type;
private:
iostream* ptr_io;
istream* ptr_i;
ostream* ptr_o;
public:
basic_filterbuf()
:ptr_io(nullptr)
,ptr_o(nullptr)
,ptr_i(nullptr){
}
basic_filterbuf(iostream& io_)
:ptr_io(&io_)
,ptr_o(&io_)
,ptr_i(&io_){
}
basic_filterbuf(istream& in_)
:ptr_io(nullptr)
,ptr_o(nullptr)
,ptr_i(&in_){
}
basic_filterbuf(ostream& out_)
:ptr_io(nullptr)
,ptr_o(&out_)
,ptr_i(nullptr){
}
public:
iostream& ref_io(){return *ptr_io;}
istream& ref_i(){return *ptr_i;}
ostream& ref_o(){return *ptr_o;}
const iostream& ref_io(){return *ptr_io;}
const istream& cref_i()const{return *ptr_i;}
const ostream& cref_o()const{return *ptr_o;}
bool has_i()const{return ptr_i!=nullptr;}
bool has_o()const{return ptr_o!=nullptr;}
bool has_io()const{return has_io!=nullptr;}
bool is_open()const{return has_i() || has_o();}
bool open(iostream& io_){
if(is_open())return true;
ptr_io=&io_;
ptr_o=&io_;
ptr_i=&io_;
return false;
}
bool open(ostream& out_){
if(is_open())return true;
ptr_io=nullptr;
ptr_o=&out_;
ptr_i=nullptr;
return false;
}
bool open(istream& in_){
if(is_open())return true;
ptr_io=nullptr;
ptr_o=nullptr;
ptr_i=&in_;
return false;
}
bool close(){
if(!is_open())return true;
ptr_io=nullptr;
ptr_o=nullptr;
ptr_i=nullptr;
return false;
}
pos_type tell_i()const{
hmLib_assert(has_i(),"There is no istream");
return ptr_i->tellg();
}
pos_type tell_o()const{
hmLib_assert(has_o(),"There is no ostream");
return ptr_o->tellp();
}
void seek_i(pos_type pos){
hmLib_assert(has_i(),"There is no istream");
return ptr_i->seelg(pos);
}
void seek_o(pos_type pos){
hmLib_assert(has_o(),"There is no ostream");
return ptr_o->seelp(pos);
}
void seek_i(off_type off,std::ios_base::seekdir way){
hmLib_assert(has_i(),"There is no istream");
return ptr_i->seelg(off,way);
}
void seek_o(off_type off,std::ios_base::seekdir way){
hmLib_assert(has_o(),"There is no ostream");
return ptr_o->seelg(off,way);
}
bool eof_i()const{
hmLib_assert(has_i(),"There is no istream");
return ptr_i->eof();
}
bool eof_o()const{
hmLib_assert(has_o(),"There is no ostream");
return ptr_o->eof();
}
};
typedef basic_filterbuf<char,std::char_traits<char>> filterbuf;
}
#
#endif
| 24.198347
| 64
| 0.682377
|
hmito
|
15db7a855b9baf11ffae5ba8058a1179edf08491
| 143
|
cpp
|
C++
|
hello-world/hello_world.cpp
|
akilram/exercism-cpp-answers
|
88d1247beb6ad003640efd5af87a05ad1a0d3a88
|
[
"MIT"
] | null | null | null |
hello-world/hello_world.cpp
|
akilram/exercism-cpp-answers
|
88d1247beb6ad003640efd5af87a05ad1a0d3a88
|
[
"MIT"
] | null | null | null |
hello-world/hello_world.cpp
|
akilram/exercism-cpp-answers
|
88d1247beb6ad003640efd5af87a05ad1a0d3a88
|
[
"MIT"
] | null | null | null |
#include "hello_world.h"
using namespace std;
namespace hello_world
{
string hello()
{
return string("Hello, World!");
}
}
| 11
| 34
| 0.622378
|
akilram
|
15e88fd4d0070e0407162c0b14b44d71cf3ce069
| 6,917
|
cpp
|
C++
|
build/moc/moc_CameraSpec.cpp
|
UNIST-ESCL/UNIST_GCS
|
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
|
[
"Apache-2.0"
] | 1
|
2018-11-07T06:10:53.000Z
|
2018-11-07T06:10:53.000Z
|
build/moc/moc_CameraSpec.cpp
|
UNIST-ESCL/UNIST_GCS
|
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
|
[
"Apache-2.0"
] | null | null | null |
build/moc/moc_CameraSpec.cpp
|
UNIST-ESCL/UNIST_GCS
|
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
|
[
"Apache-2.0"
] | 1
|
2018-11-07T06:10:47.000Z
|
2018-11-07T06:10:47.000Z
|
/****************************************************************************
** Meta object code from reading C++ file 'CameraSpec.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../src/MissionManager/CameraSpec.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'CameraSpec.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_CameraSpec_t {
QByteArrayData data[13];
char stringdata0[143];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_CameraSpec_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_CameraSpec_t qt_meta_stringdata_CameraSpec = {
{
QT_MOC_LITERAL(0, 0, 10), // "CameraSpec"
QT_MOC_LITERAL(1, 11, 12), // "dirtyChanged"
QT_MOC_LITERAL(2, 24, 0), // ""
QT_MOC_LITERAL(3, 25, 5), // "dirty"
QT_MOC_LITERAL(4, 31, 11), // "sensorWidth"
QT_MOC_LITERAL(5, 43, 5), // "Fact*"
QT_MOC_LITERAL(6, 49, 12), // "sensorHeight"
QT_MOC_LITERAL(7, 62, 10), // "imageWidth"
QT_MOC_LITERAL(8, 73, 11), // "imageHeight"
QT_MOC_LITERAL(9, 85, 11), // "focalLength"
QT_MOC_LITERAL(10, 97, 9), // "landscape"
QT_MOC_LITERAL(11, 107, 16), // "fixedOrientation"
QT_MOC_LITERAL(12, 124, 18) // "minTriggerInterval"
},
"CameraSpec\0dirtyChanged\0\0dirty\0"
"sensorWidth\0Fact*\0sensorHeight\0"
"imageWidth\0imageHeight\0focalLength\0"
"landscape\0fixedOrientation\0"
"minTriggerInterval"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_CameraSpec[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
8, 22, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 19, 2, 0x06 /* Public */,
// signals: parameters
QMetaType::Void, QMetaType::Bool, 3,
// properties: name, type, flags
4, 0x80000000 | 5, 0x00095409,
6, 0x80000000 | 5, 0x00095409,
7, 0x80000000 | 5, 0x00095409,
8, 0x80000000 | 5, 0x00095409,
9, 0x80000000 | 5, 0x00095409,
10, 0x80000000 | 5, 0x00095409,
11, 0x80000000 | 5, 0x00095409,
12, 0x80000000 | 5, 0x00095409,
0 // eod
};
void CameraSpec::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
CameraSpec *_t = static_cast<CameraSpec *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->dirtyChanged((*reinterpret_cast< bool(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
typedef void (CameraSpec::*_t)(bool );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&CameraSpec::dirtyChanged)) {
*result = 0;
return;
}
}
} else if (_c == QMetaObject::RegisterPropertyMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 7:
case 6:
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< Fact* >(); break;
}
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty) {
CameraSpec *_t = static_cast<CameraSpec *>(_o);
Q_UNUSED(_t)
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< Fact**>(_v) = _t->sensorWidth(); break;
case 1: *reinterpret_cast< Fact**>(_v) = _t->sensorHeight(); break;
case 2: *reinterpret_cast< Fact**>(_v) = _t->imageWidth(); break;
case 3: *reinterpret_cast< Fact**>(_v) = _t->imageHeight(); break;
case 4: *reinterpret_cast< Fact**>(_v) = _t->focalLength(); break;
case 5: *reinterpret_cast< Fact**>(_v) = _t->landscape(); break;
case 6: *reinterpret_cast< Fact**>(_v) = _t->fixedOrientation(); break;
case 7: *reinterpret_cast< Fact**>(_v) = _t->minTriggerInterval(); break;
default: break;
}
} else if (_c == QMetaObject::WriteProperty) {
} else if (_c == QMetaObject::ResetProperty) {
}
#endif // QT_NO_PROPERTIES
}
const QMetaObject CameraSpec::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_CameraSpec.data,
qt_meta_data_CameraSpec, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *CameraSpec::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *CameraSpec::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_CameraSpec.stringdata0))
return static_cast<void*>(this);
return QObject::qt_metacast(_clname);
}
int CameraSpec::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty
|| _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) {
qt_static_metacall(this, _c, _id, _a);
_id -= 8;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 8;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 8;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 8;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 8;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 8;
}
#endif // QT_NO_PROPERTIES
return _id;
}
// SIGNAL 0
void CameraSpec::dirtyChanged(bool _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 33.741463
| 97
| 0.609802
|
UNIST-ESCL
|
15ebccd1e10788efac79dca03c3613f9be828fd4
| 6,866
|
cpp
|
C++
|
FPSLighting/Dependencies/DIRECTX/Samples/C++/Misc/DxDiagOutput/DxDiagOutput.cpp
|
billionare/FPSLighting
|
c7d646f51cf4dee360dcc7c8e2fd2821b421b418
|
[
"MIT"
] | null | null | null |
FPSLighting/Dependencies/DIRECTX/Samples/C++/Misc/DxDiagOutput/DxDiagOutput.cpp
|
billionare/FPSLighting
|
c7d646f51cf4dee360dcc7c8e2fd2821b421b418
|
[
"MIT"
] | null | null | null |
FPSLighting/Dependencies/DIRECTX/Samples/C++/Misc/DxDiagOutput/DxDiagOutput.cpp
|
billionare/FPSLighting
|
c7d646f51cf4dee360dcc7c8e2fd2821b421b418
|
[
"MIT"
] | null | null | null |
//----------------------------------------------------------------------------
// File: DxDiagOutput.cpp
//
// Desc: Sample app to read info from dxdiagn.dll by enumeration
//
// Copyright (c) Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
#define INITGUID
#include <windows.h>
#pragma warning( disable : 4996 ) // disable deprecated warning
#include <strsafe.h>
#pragma warning( default : 4996 )
#include <stdio.h>
#include <assert.h>
#include <initguid.h>
#include <dxdiag.h>
//-----------------------------------------------------------------------------
// Defines, and constants
//-----------------------------------------------------------------------------
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } }
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
//-----------------------------------------------------------------------------
// Function-prototypes
//-----------------------------------------------------------------------------
HRESULT PrintContainerAndChildren( WCHAR* wszParentName, IDxDiagContainer* pDxDiagContainer );
//-----------------------------------------------------------------------------
// Name: main()
// Desc: Entry point for the application. We use just the console window
//-----------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
HRESULT hr;
CoInitialize( NULL );
IDxDiagProvider* pDxDiagProvider = NULL;
IDxDiagContainer* pDxDiagRoot = NULL;
// CoCreate a IDxDiagProvider*
hr = CoCreateInstance( CLSID_DxDiagProvider,
NULL,
CLSCTX_INPROC_SERVER,
IID_IDxDiagProvider,
( LPVOID* )&pDxDiagProvider );
if( SUCCEEDED( hr ) ) // if FAILED(hr) then DirectX 9 is not installed
{
// Fill out a DXDIAG_INIT_PARAMS struct and pass it to IDxDiagContainer::Initialize
// Passing in TRUE for bAllowWHQLChecks, allows dxdiag to check if drivers are
// digital signed as logo'd by WHQL which may connect via internet to update
// WHQL certificates.
DXDIAG_INIT_PARAMS dxDiagInitParam;
ZeroMemory( &dxDiagInitParam, sizeof( DXDIAG_INIT_PARAMS ) );
dxDiagInitParam.dwSize = sizeof( DXDIAG_INIT_PARAMS );
dxDiagInitParam.dwDxDiagHeaderVersion = DXDIAG_DX9_SDK_VERSION;
dxDiagInitParam.bAllowWHQLChecks = TRUE;
dxDiagInitParam.pReserved = NULL;
hr = pDxDiagProvider->Initialize( &dxDiagInitParam );
if( FAILED( hr ) )
goto LCleanup;
hr = pDxDiagProvider->GetRootContainer( &pDxDiagRoot );
if( FAILED( hr ) )
goto LCleanup;
// This function will recursivly print the properties
// the root node and all its child.
hr = PrintContainerAndChildren( NULL, pDxDiagRoot );
if( FAILED( hr ) )
goto LCleanup;
}
LCleanup:
SAFE_RELEASE( pDxDiagRoot );
SAFE_RELEASE( pDxDiagProvider );
CoUninitialize();
return 0;
}
//-----------------------------------------------------------------------------
// Name: PrintContainerAndChildren()
// Desc: Recursivly print the properties the root node and all its child
// to the console window
//-----------------------------------------------------------------------------
HRESULT PrintContainerAndChildren( WCHAR* wszParentName, IDxDiagContainer* pDxDiagContainer )
{
HRESULT hr;
DWORD dwPropCount;
DWORD dwPropIndex;
WCHAR wszPropName[256];
VARIANT var;
WCHAR wszPropValue[256];
DWORD dwChildCount;
DWORD dwChildIndex;
WCHAR wszChildName[256];
IDxDiagContainer* pChildContainer = NULL;
VariantInit( &var );
hr = pDxDiagContainer->GetNumberOfProps( &dwPropCount );
if( SUCCEEDED( hr ) )
{
// Print each property in this container
for( dwPropIndex = 0; dwPropIndex < dwPropCount; dwPropIndex++ )
{
hr = pDxDiagContainer->EnumPropNames( dwPropIndex, wszPropName, 256 );
if( SUCCEEDED( hr ) )
{
hr = pDxDiagContainer->GetProp( wszPropName, &var );
if( SUCCEEDED( hr ) )
{
// Switch off the type. There's 4 different types:
switch( var.vt )
{
case VT_UI4:
StringCchPrintfW( wszPropValue, 256, L"%d", var.ulVal );
break;
case VT_I4:
StringCchPrintfW( wszPropValue, 256, L"%d", var.lVal );
break;
case VT_BOOL:
StringCchCopyW( wszPropValue, 256, ( var.boolVal ) ? L"true" : L"false" );
break;
case VT_BSTR:
StringCchCopyW( wszPropValue, 256, var.bstrVal );
break;
}
// Add the parent name to the front if there's one, so that
// its easier to read on the screen
if( wszParentName )
wprintf( L"%s.%s = %s\n", wszParentName, wszPropName, wszPropValue );
else
wprintf( L"%s = %s\n", wszPropName, wszPropValue );
// Clear the variant (this is needed to free BSTR memory)
VariantClear( &var );
}
}
}
}
// Recursivly call this function for each of its child containers
hr = pDxDiagContainer->GetNumberOfChildContainers( &dwChildCount );
if( SUCCEEDED( hr ) )
{
for( dwChildIndex = 0; dwChildIndex < dwChildCount; dwChildIndex++ )
{
hr = pDxDiagContainer->EnumChildContainerNames( dwChildIndex, wszChildName, 256 );
if( SUCCEEDED( hr ) )
{
hr = pDxDiagContainer->GetChildContainer( wszChildName, &pChildContainer );
if( SUCCEEDED( hr ) )
{
// wszFullChildName isn't needed but is used for text output
WCHAR wszFullChildName[256];
if( wszParentName )
StringCchPrintfW( wszFullChildName, 256, L"%s.%s", wszParentName, wszChildName );
else
StringCchCopyW( wszFullChildName, 256, wszChildName );
PrintContainerAndChildren( wszFullChildName, pChildContainer );
SAFE_RELEASE( pChildContainer );
}
}
}
}
return S_OK;
}
| 35.760417
| 105
| 0.498689
|
billionare
|
15f216ea7dba8896a70c427afb4ac7620c65a7f2
| 2,491
|
hpp
|
C++
|
include/codegen/include/Valve/VR/IVRExtendedDisplay__GetEyeOutputViewport.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/Valve/VR/IVRExtendedDisplay__GetEyeOutputViewport.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/Valve/VR/IVRExtendedDisplay__GetEyeOutputViewport.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:12 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
// Including type: Valve.VR.IVRExtendedDisplay
#include "Valve/VR/IVRExtendedDisplay.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Skipping declaration: IntPtr because it is already included!
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Forward declaring namespace: Valve::VR
namespace Valve::VR {
// Forward declaring type: EVREye
struct EVREye;
}
// Completed forward declares
// Type namespace: Valve.VR
namespace Valve::VR {
// Autogenerated type: Valve.VR.IVRExtendedDisplay/_GetEyeOutputViewport
class IVRExtendedDisplay::_GetEyeOutputViewport : public System::MulticastDelegate {
public:
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x15EFF5C
static IVRExtendedDisplay::_GetEyeOutputViewport* New_ctor(::Il2CppObject* object, System::IntPtr method);
// public System.Void Invoke(Valve.VR.EVREye eEye, System.UInt32 pnX, System.UInt32 pnY, System.UInt32 pnWidth, System.UInt32 pnHeight)
// Offset: 0x15EFF70
void Invoke(Valve::VR::EVREye eEye, uint& pnX, uint& pnY, uint& pnWidth, uint& pnHeight);
// public System.IAsyncResult BeginInvoke(Valve.VR.EVREye eEye, System.UInt32 pnX, System.UInt32 pnY, System.UInt32 pnWidth, System.UInt32 pnHeight, System.AsyncCallback callback, System.Object object)
// Offset: 0x15F024C
System::IAsyncResult* BeginInvoke(Valve::VR::EVREye eEye, uint& pnX, uint& pnY, uint& pnWidth, uint& pnHeight, System::AsyncCallback* callback, ::Il2CppObject* object);
// public System.Void EndInvoke(System.UInt32 pnX, System.UInt32 pnY, System.UInt32 pnWidth, System.UInt32 pnHeight, System.IAsyncResult result)
// Offset: 0x15F0350
void EndInvoke(uint& pnX, uint& pnY, uint& pnWidth, uint& pnHeight, System::IAsyncResult* result);
}; // Valve.VR.IVRExtendedDisplay/_GetEyeOutputViewport
}
DEFINE_IL2CPP_ARG_TYPE(Valve::VR::IVRExtendedDisplay::_GetEyeOutputViewport*, "Valve.VR", "IVRExtendedDisplay/_GetEyeOutputViewport");
#pragma pack(pop)
| 49.82
| 205
| 0.741871
|
Futuremappermydud
|
15f99663419b68e51365c7952c1b5cbce2603ae7
| 2,846
|
cpp
|
C++
|
jetson/carControl/src/0.3/peripheral_driver/uart/test_uart1.cpp
|
thanhwins/DriveCarLessChallenge
|
716304f3e25b383781ade5f1560ef0d538fc634e
|
[
"MIT"
] | 1
|
2017-12-19T15:53:55.000Z
|
2017-12-19T15:53:55.000Z
|
jetson/carControl/src/0.3/peripheral_driver/uart/test_uart1.cpp
|
thanhwins/DriveCarLessChallenge
|
716304f3e25b383781ade5f1560ef0d538fc634e
|
[
"MIT"
] | null | null | null |
jetson/carControl/src/0.3/peripheral_driver/uart/test_uart1.cpp
|
thanhwins/DriveCarLessChallenge
|
716304f3e25b383781ade5f1560ef0d538fc634e
|
[
"MIT"
] | 1
|
2019-11-27T03:01:55.000Z
|
2019-11-27T03:01:55.000Z
|
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main(int argc,char** argv)
{
struct termios tio;
struct termios stdio;
struct termios old_stdio;
int tty_fd;
unsigned char c='D';
tcgetattr(STDOUT_FILENO,&old_stdio);
printf("Please start with %s /dev/ttyACM0 (for example)\n",argv[0]);
memset(&stdio,0,sizeof(stdio));
stdio.c_iflag=0;
stdio.c_oflag=0;
stdio.c_cflag=0;
stdio.c_lflag=0;
stdio.c_cc[VMIN]=1;
stdio.c_cc[VTIME]=0;
tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking
memset(&tio,0,sizeof(tio));
tio.c_iflag=0;
tio.c_oflag=0;
tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information
tio.c_lflag=0;
tio.c_cc[VMIN]=1;
tio.c_cc[VTIME]=5;
tty_fd=open("/dev/ttyACM0", O_RDWR | O_NONBLOCK);
cfsetospeed(&tio,B9600); // 115200 baud
cfsetispeed(&tio,B9600); // 115200 baud
tcsetattr(tty_fd,TCSANOW,&tio);
char serial_buffer_recv[16];
for( int i = 0; i < 16; i++ )
serial_buffer_recv[i] = '0';
int nbyes = 15;
while (true)
{
for( int i = 0; i < 100; i++)
{
int serial_read_ret = read(tty_fd, serial_buffer_recv, nbyes);
if(serial_read_ret < 1 )
printf("\nError\n");
else
{
break;
}
usleep(100);
}
printf("%s\n\r", serial_buffer_recv);
for( int i = 0; i < 15; i++ )
serial_buffer_recv[i] = '0';
usleep(450000);
}
// while (true)
// {
// for( int k = 0; k < 15; k++ )
// {
// for( int i = 0; i < 100; i++)
// {
// int serial_read_ret = read(tty_fd, &serial_buffer_recv[k], 1);
// if(serial_read_ret < 1 )
// printf("\nError\n");
// else
// {
// break;
// }
// usleep(100);
// }
// usleep(1000);
// }
// printf("Read from serial port: %s\n\r", serial_buffer_recv);
// for( int i = 0; i < 15; i++ )
// serial_buffer_recv[i] = '0';
// usleep(500000);
// }
close(tty_fd);
tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio);
return EXIT_SUCCESS;
}
| 26.110092
| 90
| 0.457484
|
thanhwins
|
15fa858fc057c4c095ab3813186fba42856993a2
| 824
|
cpp
|
C++
|
libs/filesystem/src/filesystem/file_size.cpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/filesystem/src/filesystem/file_size.cpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/filesystem/src/filesystem/file_size.cpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/const.hpp>
#include <fcppt/filesystem/file_size.hpp>
#include <fcppt/filesystem/optional_size.hpp>
#include <fcppt/optional/make_if.hpp>
#include <fcppt/config/external_begin.hpp>
#include <cstdint>
#include <filesystem>
#include <fcppt/config/external_end.hpp>
fcppt::filesystem::optional_size
fcppt::filesystem::file_size(
std::filesystem::path const &_path
)
{
std::uintmax_t const size{
std::filesystem::file_size(
_path
)
};
return
fcppt::optional::make_if(
size
!=
static_cast<
std::uintmax_t
>(
-1
),
fcppt::const_(
size
)
);
}
| 19.619048
| 61
| 0.686893
|
pmiddend
|
15fead12ef5fd9b20de544e14e9babeb934ae2ad
| 866
|
hpp
|
C++
|
Web-Server/include/Server.hpp
|
marmal95/Web-Server
|
6f1fc5fe75d7ca516697a93149880a9c67933a2c
|
[
"MIT"
] | null | null | null |
Web-Server/include/Server.hpp
|
marmal95/Web-Server
|
6f1fc5fe75d7ca516697a93149880a9c67933a2c
|
[
"MIT"
] | null | null | null |
Web-Server/include/Server.hpp
|
marmal95/Web-Server
|
6f1fc5fe75d7ca516697a93149880a9c67933a2c
|
[
"MIT"
] | null | null | null |
#pragma once
#include "IServer.hpp"
#include "RequestHandler.hpp"
#include "ConnectionManager.hpp"
#include "ResponseBuilder.hpp"
#include "RequestParser.hpp"
#include <string>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
namespace web
{
using namespace boost::asio;
using namespace boost::asio::ip;
class Server : public IServer
{
public:
Server(std::string_view address, uint32_t port, std::string_view root_dir);
Server(const Server&) = delete;
Server& operator=(const Server&) = delete;
void start() override;
void stop() override;
void reset() override;
private:
io_service service_io;
tcp::acceptor tcp_acceptor;
tcp::socket tcp_socket;
ResponseBuilder response_builder;
RequestHandler request_handler;
RequestParser request_parser;
ConnectionManager connection_manager;
void accept();
};
}
| 20.619048
| 77
| 0.748268
|
marmal95
|
c6008a802c6d22a4acb6acef6e2bf8db635ca5dc
| 400
|
cpp
|
C++
|
sum_values.cpp
|
lionkor/cpp-examples
|
6458ab8b1ae383215e4a2148e427bccbf7e27e41
|
[
"MIT"
] | null | null | null |
sum_values.cpp
|
lionkor/cpp-examples
|
6458ab8b1ae383215e4a2148e427bccbf7e27e41
|
[
"MIT"
] | null | null | null |
sum_values.cpp
|
lionkor/cpp-examples
|
6458ab8b1ae383215e4a2148e427bccbf7e27e41
|
[
"MIT"
] | null | null | null |
#include <iostream>
int main() {
int numbers[10];
for (int i = 0; i < 10; ++i) {
// i + 1 so that it's 1-10 instead of 0-9
std::cout << "Enter number (" << i + 1 << "/10): ";
std::cin >> numbers[i];
}
// now sum them up
int sum = 0;
for (int i = 0; i < 10; ++i) {
sum += numbers[i];
}
std::cout << "The sum is " << sum << std::endl;
}
| 23.529412
| 59
| 0.435
|
lionkor
|
c6078ef854ae11e3009b24840b26c3d4d4277f1c
| 1,542
|
cpp
|
C++
|
Pener SDK/FEATURES/Fakewalk.cpp
|
younasiqw/Thulium-Beta
|
968591340449e65824458142a40c1f35ce17f3ac
|
[
"Apache-2.0"
] | null | null | null |
Pener SDK/FEATURES/Fakewalk.cpp
|
younasiqw/Thulium-Beta
|
968591340449e65824458142a40c1f35ce17f3ac
|
[
"Apache-2.0"
] | null | null | null |
Pener SDK/FEATURES/Fakewalk.cpp
|
younasiqw/Thulium-Beta
|
968591340449e65824458142a40c1f35ce17f3ac
|
[
"Apache-2.0"
] | 1
|
2019-04-02T17:36:55.000Z
|
2019-04-02T17:36:55.000Z
|
#include "../includes.h"
#include "../UTILS/interfaces.h"
#include "../SDK/IEngine.h"
#include "../SDK/CUserCmd.h"
#include "../SDK/CBaseEntity.h"
#include "../SDK/CClientEntityList.h"
#include "../SDK/CTrace.h"
#include "../SDK/CBaseWeapon.h"
#include "../SDK/CGlobalVars.h"
#include "../SDK/NetChannel.h"
#include "../SDK/CBaseAnimState.h"
#include "../SDK/ConVar.h"
#include "../FEATURES/AutoWall.h"
#include "../FEATURES/Fakewalk.h"
#include "../FEATURES/Aimbot.h"
#include <time.h>
#include <iostream>
void CFakewalk::do_fakewalk(SDK::CUserCmd* cmd)
{
if (UTILS::INPUT::input_handler.GetKeyState(UTILS::INPUT::input_handler.keyBindings(SETTINGS::settings.fakewalk_key)) & 1)
{
auto local_player = INTERFACES::ClientEntityList->GetClientEntity(INTERFACES::Engine->GetLocalPlayer());
if (!local_player || local_player->GetHealth() <= 0) return;
auto net_channel = INTERFACES::Engine->GetNetChannel();
if (!net_channel) return;
auto animstate = local_player->GetAnimState();
if (!animstate) return;
fake_walk = true;
if (fabs(local_update - INTERFACES::Globals->curtime) <= 0.05)
{
cmd->move.x = 450;
aimbot->rotate_movement(UTILS::CalcAngle(Vector(0, 0, 0), local_player->GetVelocity()).y + 180.f, cmd);
}
static int choked = 0;
choked = choked > 7 ? 0 : choked + 1;
cmd->move.x = choked < 2 || choked > 5 ? 0 : cmd->move.x;
cmd->move.y = choked < 2 || choked > 5 ? 0 : cmd->move.y;
GLOBAL::should_send_packet = choked < 1;
}
else
fake_walk = false;
}
CFakewalk* fakewalk = new CFakewalk();
| 30.84
| 123
| 0.681582
|
younasiqw
|
c60aa953d8aabd149415ea1f7cbea98518ee6427
| 241
|
hpp
|
C++
|
src/game_window_opt_opengl.hpp
|
bggd/game_window
|
da9474472dd4988f4926fa2b50734b0ffa3b10af
|
[
"MIT"
] | null | null | null |
src/game_window_opt_opengl.hpp
|
bggd/game_window
|
da9474472dd4988f4926fa2b50734b0ffa3b10af
|
[
"MIT"
] | null | null | null |
src/game_window_opt_opengl.hpp
|
bggd/game_window
|
da9474472dd4988f4926fa2b50734b0ffa3b10af
|
[
"MIT"
] | null | null | null |
namespace gwin {
struct GameWindowOptionOpenGL {
bool fullscreen;
bool resizable;
bool set_pos;
int32_t x, y;
uint32_t w, h;
bool gles;
uint8_t major;
uint8_t minor;
bool debug_ctx;
bool vsync;
};
} // namespace gwin
| 12.684211
| 31
| 0.684647
|
bggd
|
c60b0bcfdfdd3c00b24091dd02708ea8a1ba4d7c
| 2,410
|
hpp
|
C++
|
raygun/ui/text.hpp
|
maggo007/Raygun
|
f6be537c835976a9d6cc356ebe187feba6592847
|
[
"MIT"
] | null | null | null |
raygun/ui/text.hpp
|
maggo007/Raygun
|
f6be537c835976a9d6cc356ebe187feba6592847
|
[
"MIT"
] | null | null | null |
raygun/ui/text.hpp
|
maggo007/Raygun
|
f6be537c835976a9d6cc356ebe187feba6592847
|
[
"MIT"
] | null | null | null |
// The MIT License (MIT)
//
// Copyright (c) 2019,2020 The Raygun Authors.
//
// 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.
#pragma once
#include "raygun/entity.hpp"
#include "raygun/material.hpp"
#include "raygun/render/model.hpp"
namespace raygun::ui {
struct Font {
string name;
std::array<std::shared_ptr<render::Mesh>, 128> charMap = {};
std::array<float, 128> charWidth = {};
};
enum class Alignment {
TopLeft,
TopCenter,
TopRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
BottomLeft,
BottomCenter,
BottomRight,
};
class TextGenerator {
public:
TextGenerator(const Font& font, std::shared_ptr<Material> material, float letterPadding = 0.1f, float lineSpacing = 1.f);
std::shared_ptr<Entity> text(string_view input, Alignment align = Alignment::TopLeft) const;
std::pair<std::shared_ptr<Entity>, render::Mesh::Bounds> textWithBounds(string_view input, Alignment align = Alignment::TopLeft) const;
private:
std::array<std::shared_ptr<render::Model>, 128> m_charMap = {};
std::array<float, 128> m_charWidth = {};
float letterPadding, lineSpacing;
std::shared_ptr<render::Model> letter(char c) const;
std::pair<std::shared_ptr<Entity>, render::Mesh::Bounds> textInternal(string_view input) const;
};
using UniqueTextGenerator = std::unique_ptr<TextGenerator>;
} // namespace raygun::ui
| 33.943662
| 139
| 0.729461
|
maggo007
|
c60f924d37abe13cbd69c6b69256a0274790d738
| 944
|
cc
|
C++
|
greedy/fractional_knapsack.cc
|
knguyenc/algorithms
|
4f61d692c986f6200eb1a52de022366a172aaa6f
|
[
"MIT"
] | null | null | null |
greedy/fractional_knapsack.cc
|
knguyenc/algorithms
|
4f61d692c986f6200eb1a52de022366a172aaa6f
|
[
"MIT"
] | null | null | null |
greedy/fractional_knapsack.cc
|
knguyenc/algorithms
|
4f61d692c986f6200eb1a52de022366a172aaa6f
|
[
"MIT"
] | null | null | null |
#include "fractional_knapsack.h"
#include <algorithm>
namespace algorithm {
namespace greedy {
bool FractionalKnapsackItemComparator(
const std::tuple<unsigned int, unsigned int> a,
const std::tuple<unsigned int, unsigned int> b) {
return (std::get<1>(a) / std::get<0>(a)) > (std::get<1>(b) / std::get<0>(b));
}
template <size_t N>
unsigned int FractionalKnapsack(
std::tuple<unsigned int, unsigned int> (&items)[N], unsigned int weight) {
std::sort(items, items + N, FractionalKnapsackItemComparator);
unsigned int maxValue = 0;
for (std::tuple<unsigned int, unsigned int> item : items) {
if (weight <= 0) {
break;
}
if (weight < std::get<0>(item)) {
maxValue += weight * std::get<1>(item) / std::get<0>(item);
weight = 0;
} else {
maxValue += std::get<1>(item);
weight -= std::get<0>(item);
}
}
return maxValue;
}
} // namespace greedy
} // namespace algorithm
| 26.222222
| 79
| 0.629237
|
knguyenc
|
c6116c08f89617369f47b91304b38eb94548fe56
| 1,021
|
cpp
|
C++
|
src/Engine/Material/GGX.cpp
|
trygas/CGHomework
|
2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe
|
[
"MIT"
] | 594
|
2019-02-19T01:09:27.000Z
|
2022-03-31T07:47:11.000Z
|
src/Engine/Material/GGX.cpp
|
Ricahrd-Li/ASAP_ARAP_Parameterization
|
c12d83605ce9ea9cac29efbd991d21e2b363e375
|
[
"MIT"
] | 12
|
2020-02-19T07:11:14.000Z
|
2021-08-07T06:41:27.000Z
|
src/Engine/Material/GGX.cpp
|
Ricahrd-Li/ASAP_ARAP_Parameterization
|
c12d83605ce9ea9cac29efbd991d21e2b363e375
|
[
"MIT"
] | 249
|
2020-02-01T08:14:36.000Z
|
2022-03-30T14:52:58.000Z
|
#include <Engine/Material/GGX.h>
#include <Engine/Material/SurfCoord.h>
using namespace Ubpa;
float GGX::D(const normalf & wh) const {
if (SurfCoord::CosTheta(wh) < 0)
return 0.f;
float alpha2 = alpha * alpha;
float cos2Theta = SurfCoord::Cos2Theta(wh);
float t = (alpha2 - 1) * cos2Theta + 1;
return alpha2 / (PI<float> * t * t);
}
float GGX::Lambda(const normalf & w) const {
auto absTanTheta = std::abs(SurfCoord::TanTheta(w));
if (std::isnan(absTanTheta))
return 98e8f;
auto alpha2Tan2Theta = (alpha * absTanTheta) * (alpha * absTanTheta);
return (-1.f + std::sqrt(1.f + alpha2Tan2Theta)) / 2.f;
}
const normalf GGX::Sample_wh() const {
// sample
const float Xi1 = Math::Rand_F();
const float Xi2 = Math::Rand_F();
// theta
const auto cos2Theta = (1 - Xi1) / ((alpha*alpha - 1)*Xi1 + 1);
const auto cosTheta = sqrt(cos2Theta);
const auto sinTheta = sqrt(1 - cos2Theta);
// phi
const auto phi = 2 * PI<float> * Xi2;
return SurfCoord::SphericalDirection(sinTheta, cosTheta, phi);
}
| 23.204545
| 70
| 0.666993
|
trygas
|
c615c427ac9dc4d4f6623732fccd9c00da134b8d
| 3,580
|
cpp
|
C++
|
examples/primitives/shuffle.cpp
|
JackAKirk/oneDNN
|
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
|
[
"Apache-2.0"
] | 1,327
|
2018-01-25T21:23:47.000Z
|
2020-04-03T09:39:30.000Z
|
examples/primitives/shuffle.cpp
|
JackAKirk/oneDNN
|
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
|
[
"Apache-2.0"
] | 583
|
2020-04-04T02:37:25.000Z
|
2022-03-31T00:12:03.000Z
|
examples/primitives/shuffle.cpp
|
JackAKirk/oneDNN
|
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
|
[
"Apache-2.0"
] | 365
|
2018-01-29T16:12:36.000Z
|
2020-04-03T08:32:27.000Z
|
/*******************************************************************************
* Copyright 2020 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.
*******************************************************************************/
/// @example shuffle.cpp
/// > Annotated version: @ref shuffle_example_cpp
///
/// @page shuffle_example_cpp_short
///
/// This C++ API example demonstrates how to create and execute a
/// [Shuffle](@ref dev_guide_shuffle) primitive.
///
/// Key optimizations included in this example:
/// - Shuffle along axis 1 (channels).
///
/// @page shuffle_example_cpp Shuffle Primitive Example
/// @copydetails shuffle_example_cpp_short
///
/// @include shuffle.cpp
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include "example_utils.hpp"
#include "oneapi/dnnl/dnnl.hpp"
using namespace dnnl;
using tag = memory::format_tag;
using dt = memory::data_type;
void shuffle_example(dnnl::engine::kind engine_kind) {
// Create execution dnnl::engine.
dnnl::engine engine(engine_kind, 0);
// Create dnnl::stream.
dnnl::stream engine_stream(engine);
// Tensor dimensions.
const memory::dim N = 3, // batch size
IC = 72, // channels
IH = 227, // tensor height
IW = 227; // tensor width
// Source (src) and destination (dst) tensors dimensions.
memory::dims src_dims = {N, IC, IH, IW};
// Allocate buffers.
std::vector<float> src_data(product(src_dims));
std::vector<float> dst_data(product(src_dims));
// Initialize src.
std::generate(src_data.begin(), src_data.end(), []() {
static int i = 0;
return std::cos(i++ / 10.f);
});
// Shuffle axis and group size.
const int shuffle_axis = 1;
const int group_size = 4;
// Create memory descriptor and memory objects for src and dst.
auto src_md = memory::desc(src_dims, dt::f32, tag::nchw);
auto src_mem = memory(src_md, engine);
auto dst_mem = memory({src_dims, dt::f32, tag::abcd}, engine);
// Write data to memory object's handle.
write_to_dnnl_memory(src_data.data(), src_mem);
// Create operation descriptor.
auto shuffle_d = shuffle_forward::desc(
prop_kind::forward_training, src_md, shuffle_axis, group_size);
// Create primitive descriptor.
auto shuffle_pd = shuffle_forward::primitive_desc(shuffle_d, engine);
// Create the primitive.
auto shuffle_prim = shuffle_forward(shuffle_pd);
// Primitive arguments.
std::unordered_map<int, memory> shuffle_args;
shuffle_args.insert({DNNL_ARG_SRC, src_mem});
shuffle_args.insert({DNNL_ARG_DST, dst_mem});
// Primitive execution: shuffle.
shuffle_prim.execute(engine_stream, shuffle_args);
// Wait for the computation to finalize.
engine_stream.wait();
// Read data from memory object.
read_from_dnnl_memory(dst_data.data(), dst_mem);
}
int main(int argc, char **argv) {
return handle_example_errors(
shuffle_example, parse_engine_kind(argc, argv));
}
| 30.862069
| 80
| 0.659218
|
JackAKirk
|
c616ac7c50c630e1ec3184bb0247c6e7e6ee704e
| 768
|
cpp
|
C++
|
engine/calculators/source/unit_tests/TertiaryUnarmedCalculator_test.cpp
|
sidav/shadow-of-the-wyrm
|
747afdeebed885b1a4f7ab42f04f9f756afd3e52
|
[
"MIT"
] | 1
|
2020-05-24T22:44:03.000Z
|
2020-05-24T22:44:03.000Z
|
engine/calculators/source/unit_tests/TertiaryUnarmedCalculator_test.cpp
|
cleancoindev/shadow-of-the-wyrm
|
51b23e98285ecb8336324bfd41ebf00f67b30389
|
[
"MIT"
] | null | null | null |
engine/calculators/source/unit_tests/TertiaryUnarmedCalculator_test.cpp
|
cleancoindev/shadow-of-the-wyrm
|
51b23e98285ecb8336324bfd41ebf00f67b30389
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
TEST(SW_Engine_Calculators_TertiaryUnarmedCalculator, calculate_knock_back_pct_chance)
{
CreaturePtr creature;
TertiaryUnarmedCalculator tuc;
EXPECT_EQ(0, tuc.calculate_knock_back_pct_chance(creature));
creature = CreaturePtr(new Creature());
Statistic str(1);
creature->set_strength(str);
EXPECT_EQ(0, tuc.calculate_knock_back_pct_chance(creature));
str.set_base_current(2);
creature->set_strength(str);
EXPECT_EQ(1, tuc.calculate_knock_back_pct_chance(creature));
str.set_base_current(12);
creature->set_strength(str);
EXPECT_EQ(6, tuc.calculate_knock_back_pct_chance(creature));
str.set_base_current(99);
creature->set_strength(str);
EXPECT_EQ(49, tuc.calculate_knock_back_pct_chance(creature));
}
| 24.774194
| 86
| 0.78776
|
sidav
|
723fb724e670b01b7142fb4ae0730ced229aa59a
| 343
|
cpp
|
C++
|
Exec/AMR-zoom/Nyx_error.cpp
|
Gosenca/axionyx_1.0
|
7e2a723e00e6287717d6d81b23db32bcf6c3521a
|
[
"BSD-3-Clause-LBNL"
] | 6
|
2021-02-18T09:13:17.000Z
|
2022-03-22T21:27:46.000Z
|
Exec/AMR-zoom/Nyx_error.cpp
|
Gosenca/axionyx_1.0
|
7e2a723e00e6287717d6d81b23db32bcf6c3521a
|
[
"BSD-3-Clause-LBNL"
] | 1
|
2020-10-12T08:54:31.000Z
|
2020-10-12T08:54:31.000Z
|
Exec/AMR-zoom/Nyx_error.cpp
|
Gosenca/axionyx_1.0
|
7e2a723e00e6287717d6d81b23db32bcf6c3521a
|
[
"BSD-3-Clause-LBNL"
] | 3
|
2020-09-04T10:26:25.000Z
|
2022-03-14T23:51:51.000Z
|
#include "Nyx.H"
#include "Nyx_error_F.H"
using namespace amrex;
void
Nyx::error_setup()
{
err_list.add("total_density",1,ErrorRec::UseAverage,
BL_FORT_PROC_CALL(TAG_OVERDENSITY, tag_overdensity));
}
void
Nyx::manual_tags_placement (TagBoxArray& tags,
const Vector<IntVect>& bf_lev)
{
}
| 18.052632
| 70
| 0.653061
|
Gosenca
|
7244c846c394c7c8464423375111a5a45874fa10
| 4,229
|
cpp
|
C++
|
src/goto-symex/slice.cpp
|
shmarovfedor/esbmc
|
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
|
[
"BSD-3-Clause"
] | 143
|
2015-06-22T12:30:01.000Z
|
2022-03-21T08:41:17.000Z
|
src/goto-symex/slice.cpp
|
shmarovfedor/esbmc
|
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
|
[
"BSD-3-Clause"
] | 542
|
2017-06-02T13:46:26.000Z
|
2022-03-31T16:35:17.000Z
|
src/goto-symex/slice.cpp
|
shmarovfedor/esbmc
|
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
|
[
"BSD-3-Clause"
] | 81
|
2015-10-21T22:21:59.000Z
|
2022-03-24T14:07:55.000Z
|
/*******************************************************************\
Module: Slicer for symex traces
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#include <goto-symex/slice.h>
symex_slicet::symex_slicet(bool assume)
: ignored(0),
slice_assumes(assume),
add_to_deps([this](const symbol2t &s) -> bool {
return depends.insert(s.get_symbol_name()).second;
})
{
}
bool symex_slicet::get_symbols(
const expr2tc &expr,
std::function<bool(const symbol2t &)> fn)
{
bool res = false;
expr->foreach_operand([this, &fn, &res](const expr2tc &e) {
if(!is_nil_expr(e))
res = get_symbols(e, fn) || res;
return res;
});
if(!is_symbol2t(expr))
return res;
const symbol2t &tmp = to_symbol2t(expr);
return fn(tmp) || res;
}
void symex_slicet::slice(std::shared_ptr<symex_target_equationt> &eq)
{
depends.clear();
for(symex_target_equationt::SSA_stepst::reverse_iterator it =
eq->SSA_steps.rbegin();
it != eq->SSA_steps.rend();
it++)
slice(*it);
}
void symex_slicet::slice(symex_target_equationt::SSA_stept &SSA_step)
{
switch(SSA_step.type)
{
case goto_trace_stept::ASSERT:
get_symbols(SSA_step.guard, add_to_deps);
get_symbols(SSA_step.cond, add_to_deps);
break;
case goto_trace_stept::ASSUME:
if(slice_assumes)
slice_assume(SSA_step);
else
{
get_symbols(SSA_step.guard, add_to_deps);
get_symbols(SSA_step.cond, add_to_deps);
}
break;
case goto_trace_stept::ASSIGNMENT:
slice_assignment(SSA_step);
break;
case goto_trace_stept::OUTPUT:
break;
case goto_trace_stept::RENUMBER:
slice_renumber(SSA_step);
break;
default:
assert(false);
}
}
void symex_slicet::slice_assume(symex_target_equationt::SSA_stept &SSA_step)
{
auto check_in_deps = [this](const symbol2t &s) -> bool {
return depends.find(s.get_symbol_name()) != depends.end();
};
if(!get_symbols(SSA_step.cond, check_in_deps))
{
// we don't really need it
SSA_step.ignore = true;
++ignored;
}
else
{
// If we need it, add the symbols to dependency
get_symbols(SSA_step.guard, add_to_deps);
get_symbols(SSA_step.cond, add_to_deps);
}
}
void symex_slicet::slice_assignment(symex_target_equationt::SSA_stept &SSA_step)
{
assert(is_symbol2t(SSA_step.lhs));
auto check_in_deps = [this](const symbol2t &s) -> bool {
return depends.find(s.get_symbol_name()) != depends.end();
};
if(!get_symbols(SSA_step.lhs, check_in_deps))
{
// we don't really need it
SSA_step.ignore = true;
++ignored;
}
else
{
get_symbols(SSA_step.guard, add_to_deps);
get_symbols(SSA_step.rhs, add_to_deps);
// Remove this symbol as we won't be seeing any references to it further
// into the history.
depends.erase(to_symbol2t(SSA_step.lhs).get_symbol_name());
}
}
void symex_slicet::slice_renumber(symex_target_equationt::SSA_stept &SSA_step)
{
assert(is_symbol2t(SSA_step.lhs));
auto check_in_deps = [this](const symbol2t &s) -> bool {
return depends.find(s.get_symbol_name()) != depends.end();
};
if(!get_symbols(SSA_step.lhs, check_in_deps))
{
// we don't really need it
SSA_step.ignore = true;
++ignored;
}
// Don't collect the symbol; this insn has no effect on dependencies.
}
BigInt slice(std::shared_ptr<symex_target_equationt> &eq, bool slice_assumes)
{
symex_slicet symex_slice(slice_assumes);
symex_slice.slice(eq);
return symex_slice.ignored;
}
BigInt simple_slice(std::shared_ptr<symex_target_equationt> &eq)
{
BigInt ignored = 0;
// just find the last assertion
symex_target_equationt::SSA_stepst::iterator last_assertion =
eq->SSA_steps.end();
for(symex_target_equationt::SSA_stepst::iterator it = eq->SSA_steps.begin();
it != eq->SSA_steps.end();
it++)
if(it->is_assert())
last_assertion = it;
// slice away anything after it
symex_target_equationt::SSA_stepst::iterator s_it = last_assertion;
if(s_it != eq->SSA_steps.end())
for(s_it++; s_it != eq->SSA_steps.end(); s_it++)
{
s_it->ignore = true;
++ignored;
}
return ignored;
}
| 23.364641
| 80
| 0.659021
|
shmarovfedor
|
7245d5fa565d541d564a68836ad54cd451038cde
| 3,556
|
cpp
|
C++
|
Example/Pods/librlottie/rlottie/src/vector/vdrawable.cpp
|
dotlottie/dotlottieR-ios
|
0531aaa427c969f5d89fea79f2dc6294414ba379
|
[
"MIT"
] | null | null | null |
Example/Pods/librlottie/rlottie/src/vector/vdrawable.cpp
|
dotlottie/dotlottieR-ios
|
0531aaa427c969f5d89fea79f2dc6294414ba379
|
[
"MIT"
] | null | null | null |
Example/Pods/librlottie/rlottie/src/vector/vdrawable.cpp
|
dotlottie/dotlottieR-ios
|
0531aaa427c969f5d89fea79f2dc6294414ba379
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2018 Samsung Electronics Co., Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "vdrawable.h"
#include "vdasher.h"
#include "vraster.h"
VDrawable::VDrawable(VDrawable::Type type)
{
setType(type);
}
VDrawable::~VDrawable()
{
if (mStrokeInfo) {
if (mType == Type::StrokeWithDash) {
delete static_cast<StrokeWithDashInfo *>(mStrokeInfo);
} else {
delete mStrokeInfo;
}
}
}
void VDrawable::setType(VDrawable::Type type)
{
mType = type;
if (mType == VDrawable::Type::Stroke) {
mStrokeInfo = new StrokeInfo();
} else if (mType == VDrawable::Type::StrokeWithDash) {
mStrokeInfo = new StrokeWithDashInfo();
}
}
void VDrawable::applyDashOp()
{
if (mStrokeInfo && (mType == Type::StrokeWithDash)) {
auto obj = static_cast<StrokeWithDashInfo *>(mStrokeInfo);
if (!obj->mDash.empty()) {
VDasher dasher(obj->mDash.data(), obj->mDash.size());
mPath.clone(dasher.dashed(mPath));
}
}
}
void VDrawable::preprocess(const VRect &clip)
{
if (mFlag & (DirtyState::Path)) {
if (mType == Type::Fill) {
mRasterizer.rasterize(std::move(mPath), mFillRule, clip);
} else {
applyDashOp();
mRasterizer.rasterize(std::move(mPath), mStrokeInfo->cap, mStrokeInfo->join,
mStrokeInfo->width, mStrokeInfo->miterLimit, clip);
}
mPath = {};
mFlag &= ~DirtyFlag(DirtyState::Path);
}
}
VRle VDrawable::rle()
{
return mRasterizer.rle();
}
void VDrawable::setStrokeInfo(CapStyle cap, JoinStyle join, float miterLimit,
float strokeWidth)
{
assert(mStrokeInfo);
if ((mStrokeInfo->cap == cap) && (mStrokeInfo->join == join) &&
vCompare(mStrokeInfo->miterLimit, miterLimit) &&
vCompare(mStrokeInfo->width, strokeWidth))
return;
mStrokeInfo->cap = cap;
mStrokeInfo->join = join;
mStrokeInfo->miterLimit = miterLimit;
mStrokeInfo->width = strokeWidth;
mFlag |= DirtyState::Path;
}
void VDrawable::setDashInfo(std::vector<float> &dashInfo)
{
assert(mStrokeInfo);
assert(mType == VDrawable::Type::StrokeWithDash);
auto obj = static_cast<StrokeWithDashInfo *>(mStrokeInfo);
bool hasChanged = false;
if (obj->mDash.size() == dashInfo.size()) {
for (uint i = 0; i < dashInfo.size(); ++i) {
if (!vCompare(obj->mDash[i], dashInfo[i])) {
hasChanged = true;
break;
}
}
} else {
hasChanged = true;
}
if (!hasChanged) return;
obj->mDash = dashInfo;
mFlag |= DirtyState::Path;
}
void VDrawable::setPath(const VPath &path)
{
mPath = path;
mFlag |= DirtyState::Path;
}
| 28
| 88
| 0.622328
|
dotlottie
|
7245e0d24c7d374058be5a7a3c5aa28bdb7ab7a9
| 3,667
|
hpp
|
C++
|
CmnIP/module/transform/inc/transform/color_normalization.hpp
|
Khoronus/CmnUniverse
|
9cf9b4297f2fcb49330126aa1047b422144045e1
|
[
"MIT"
] | null | null | null |
CmnIP/module/transform/inc/transform/color_normalization.hpp
|
Khoronus/CmnUniverse
|
9cf9b4297f2fcb49330126aa1047b422144045e1
|
[
"MIT"
] | null | null | null |
CmnIP/module/transform/inc/transform/color_normalization.hpp
|
Khoronus/CmnUniverse
|
9cf9b4297f2fcb49330126aa1047b422144045e1
|
[
"MIT"
] | null | null | null |
/* @file color_normalization.hpp
* @brief Class to perform the color normalization of a source of data.
*
* @section LICENSE
*
* 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 AUTHOR/AUTHORS 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.
*
* @author Alessandro Moro <alessandromoro.italy@gmail.com>
* @bug No known bugs.
* @version 0.1.0.0
*
*/
#ifndef CMNIP_TRANSFORM_COLORNORMALIZATION_HPP__
#define CMNIP_TRANSFORM_COLORNORMALIZATION_HPP__
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
#include <limits>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
namespace CmnIP
{
namespace transform
{
/** @brief It performs the color normalization of a source data.
It performs the color normalization of a source data.
*/
class ColorNormalization
{
public:
/** @brief It performs the color normalization on the RGB components of
the image.
It performs the color normalization on the RGB components of the image.
*/
static void normalize_rgb(const cv::Mat &src, cv::Mat &out)
{
out = cv::Mat::zeros(src.size(), src.type());
for (int y = 0; y < src.rows; y++)
{
for (int x = 0; x < src.cols; x++)
{
float s = src.at<cv::Vec3b>(y, x)[0] +
src.at<cv::Vec3b>(y, x)[1] +
src.at<cv::Vec3b>(y, x)[2];
if (s > 0) {
//float r = (float)src.at<cv::Vec3b>(y, x)[2] / s;
//float g = (float)src.at<cv::Vec3b>(y, x)[1] / s;
////float b = (float)src.at<cv::Vec3b>(y, x)[0] / s;
//out.at<cv::Vec3b>(y, x)[2] = (uchar)(r / g * src.at<cv::Vec3b>(y, x)[1]);
//out.at<cv::Vec3b>(y, x)[1] = (uchar)(src.at<cv::Vec3b>(y, x)[1]);
//out.at<cv::Vec3b>(y, x)[0] = (uchar)((1.0f - r - g) / g * src.at<cv::Vec3b>(y, x)[1]);
for (int c = 0; c < 3; c++)
{
float v = (float)src.at<cv::Vec3b>(y, x)[c] / s;
out.at<cv::Vec3b>(y, x)[c] = 255 * v;
}
}
}
}
}
/** @brief It performs the color normalization on the RGB components of
the image.
It performs the color normalization on the RGB components of the image.
*/
static void rg(const cv::Mat &src, cv::Mat &out)
{
out = cv::Mat::zeros(src.size(), src.type());
for (int y = 0; y < src.rows; y++)
{
for (int x = 0; x < src.cols; x++)
{
float s = src.at<cv::Vec3b>(y, x)[0] +
src.at<cv::Vec3b>(y, x)[1] +
src.at<cv::Vec3b>(y, x)[2];
if (s > 0) {
float r = (float)src.at<cv::Vec3b>(y, x)[2] / s;
float g = (float)src.at<cv::Vec3b>(y, x)[1] / s;
//float b = (float)src.at<cv::Vec3b>(y, x)[0] / s;
out.at<cv::Vec3b>(y, x)[2] = (uchar)(r / g * src.at<cv::Vec3b>(y, x)[1]);
out.at<cv::Vec3b>(y, x)[1] = (uchar)(src.at<cv::Vec3b>(y, x)[1]);
out.at<cv::Vec3b>(y, x)[0] = (uchar)((1.0f - r - g) / g * src.at<cv::Vec3b>(y, x)[1]);
}
}
}
}
};
} // namespace transform
} // namespace CmnIP
#endif /* CMNIP_TRANSFORM_COLORNORMALIZATION_HPP__ */
| 29.336
| 93
| 0.620125
|
Khoronus
|
724c28ac4ffde7a6f6317182b5ba921c15074c2f
| 524
|
cpp
|
C++
|
GraphicsScene/Camera.cpp
|
Melody6149/Graphics-for-games-tutorial
|
8ad1ed15ab774c0bd93e87f5c937f1597d55509e
|
[
"MIT"
] | null | null | null |
GraphicsScene/Camera.cpp
|
Melody6149/Graphics-for-games-tutorial
|
8ad1ed15ab774c0bd93e87f5c937f1597d55509e
|
[
"MIT"
] | null | null | null |
GraphicsScene/Camera.cpp
|
Melody6149/Graphics-for-games-tutorial
|
8ad1ed15ab774c0bd93e87f5c937f1597d55509e
|
[
"MIT"
] | null | null | null |
#include "Camera.h"
#include <glm/ext.hpp>
glm::mat4 Camera::getViewMatrix()
{
float yawRadians = glm::radians(m_yaw);
float pitchRadians = glm::radians(m_pitch);
glm::vec3 forward(
cos(pitchRadians) * cos(yawRadians),
sin(pitchRadians),
cos(pitchRadians) * sin(yawRadians));
return glm::lookAt(m_position, m_position + forward, glm::vec3(0.0f, 1.0f, 0.0f));
}
glm::mat4 Camera::getProjectionMatrix(float width, float height)
{
return glm::perspective(glm::pi<float>() * 0.25, width / height, 0.1, 1000.0f);
}
| 26.2
| 83
| 0.70229
|
Melody6149
|
724f398fa14240dc814292ba0df5538bc14020f5
| 638
|
cpp
|
C++
|
Week_3/02 Programming Assignment/Example.cpp
|
Animart/basics-of-c-plus-plus-development-white-belt
|
9ad0aec57a54e505955ad4a93a0636903ba92822
|
[
"Unlicense"
] | 1
|
2018-11-22T17:33:45.000Z
|
2018-11-22T17:33:45.000Z
|
Week_3/02 Programming Assignment/Example.cpp
|
Animart/basics-of-c-plus-plus-development-white-belt
|
9ad0aec57a54e505955ad4a93a0636903ba92822
|
[
"Unlicense"
] | null | null | null |
Week_3/02 Programming Assignment/Example.cpp
|
Animart/basics-of-c-plus-plus-development-white-belt
|
9ad0aec57a54e505955ad4a93a0636903ba92822
|
[
"Unlicense"
] | 1
|
2021-03-09T05:26:37.000Z
|
2021-03-09T05:26:37.000Z
|
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void PrintVector(const vector<string>& v)
{
for (const auto i : v)
{
cout << i << " ";
}
}
string Transform(string& s)
{
string temp = "";
for (int i = 0; i < s.size(); ++i)
{
temp += tolower(s[i]);
}
return temp;
}
bool Compare(string i, string j)
{
return Transform(i) < Transform(j);
}
int main()
{
int n;
cin >> n;
vector<string> v(n);
for (string& w : v)
{
cin >> w;
}
sort(begin(v), end(v), Compare);
PrintVector(v);
return 0;
}
| 13.869565
| 42
| 0.518809
|
Animart
|
7251e9c9b6bde9f5987953ad532a5bbd4bdb7e1e
| 77,592
|
cpp
|
C++
|
sdk/cpp/core/src/network_topology.cpp
|
YDK-Solutions/ydk
|
7ab961284cdc82de8828e53fa4870d3204d7730e
|
[
"ECL-2.0",
"Apache-2.0"
] | 125
|
2016-03-15T17:04:13.000Z
|
2022-03-22T02:46:17.000Z
|
sdk/cpp/core/src/network_topology.cpp
|
YDK-Solutions/ydk
|
7ab961284cdc82de8828e53fa4870d3204d7730e
|
[
"ECL-2.0",
"Apache-2.0"
] | 818
|
2016-03-17T17:06:00.000Z
|
2022-03-28T03:56:17.000Z
|
sdk/cpp/core/src/network_topology.cpp
|
YDK-Solutions/ydk
|
7ab961284cdc82de8828e53fa4870d3204d7730e
|
[
"ECL-2.0",
"Apache-2.0"
] | 93
|
2016-03-15T19:18:55.000Z
|
2022-02-24T13:55:07.000Z
|
#include <sstream>
#include <iostream>
#include "entity_util.hpp"
#include "network_topology.hpp"
using namespace ydk;
namespace opendaylight {
namespace network_topology {
NetworkTopology::NetworkTopology()
{
yang_name = "network-topology"; yang_parent_name = "network-topology";
}
NetworkTopology::~NetworkTopology()
{
}
bool NetworkTopology::has_data() const
{
for (std::size_t index=0; index<topology.size(); index++)
{
if(topology[index]->has_data())
return true;
}
return false;
}
bool NetworkTopology::has_operation() const
{
for (std::size_t index=0; index<topology.size(); index++)
{
if(topology[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string NetworkTopology::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "network-topology:network-topology";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::get_name_leaf_data() const
{
return {};
}
std::shared_ptr<Entity> NetworkTopology::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "topology")
{
for(auto const & c : topology)
{
std::string segment = c->get_segment_path();
if(segment_path == segment)
{
return c;
}
}
auto c = std::make_shared<NetworkTopology::Topology>();
c->parent = this;
topology.push_back(c);
return c;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
for (auto const & c : topology)
{
children[c->get_segment_path()] = c;
}
return children;
}
void NetworkTopology::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void NetworkTopology::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<Entity> NetworkTopology::clone_ptr() const
{
return std::make_shared<NetworkTopology>();
}
bool NetworkTopology::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "topology")
return true;
return false;
}
NetworkTopology::Topology::Topology()
:
topology_id{YType::str, "topology-id"},
server_provided{YType::boolean, "server-provided"}
,
topology_types(std::make_shared<NetworkTopology::Topology::TopologyTypes>())
{
topology_types->parent = this;
yang_name = "topology"; yang_parent_name = "network-topology";
}
NetworkTopology::Topology::~Topology()
{
}
bool NetworkTopology::Topology::has_data() const
{
for (std::size_t index=0; index<link.size(); index++)
{
if(link[index]->has_data())
return true;
}
for (std::size_t index=0; index<node.size(); index++)
{
if(node[index]->has_data())
return true;
}
for (std::size_t index=0; index<underlay_topology.size(); index++)
{
if(underlay_topology[index]->has_data())
return true;
}
return topology_id.is_set
|| server_provided.is_set
|| (topology_types != nullptr && topology_types->has_data());
}
bool NetworkTopology::Topology::has_operation() const
{
for (std::size_t index=0; index<link.size(); index++)
{
if(link[index]->has_operation())
return true;
}
for (std::size_t index=0; index<node.size(); index++)
{
if(node[index]->has_operation())
return true;
}
for (std::size_t index=0; index<underlay_topology.size(); index++)
{
if(underlay_topology[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(topology_id.yfilter)
|| ydk::is_set(server_provided.yfilter)
|| (topology_types != nullptr && topology_types->has_operation());
}
std::string NetworkTopology::Topology::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "topology" <<"[topology-id='" <<topology_id <<"']";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (topology_id.is_set || is_set(topology_id.yfilter)) leaf_name_data.push_back(topology_id.get_name_leafdata());
if (server_provided.is_set || is_set(server_provided.yfilter)) leaf_name_data.push_back(server_provided.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "link")
{
for(auto const & c : link)
{
std::string segment = c->get_segment_path();
if(segment_path == segment)
{
return c;
}
}
auto c = std::make_shared<NetworkTopology::Topology::Link>();
c->parent = this;
link.push_back(c);
return c;
}
if(child_yang_name == "node")
{
for(auto const & c : node)
{
std::string segment = c->get_segment_path();
if(segment_path == segment)
{
return c;
}
}
auto c = std::make_shared<NetworkTopology::Topology::Node>();
c->parent = this;
node.push_back(c);
return c;
}
if(child_yang_name == "topology-types")
{
if(topology_types == nullptr)
{
topology_types = std::make_shared<NetworkTopology::Topology::TopologyTypes>();
}
return topology_types;
}
if(child_yang_name == "underlay-topology")
{
for(auto const & c : underlay_topology)
{
std::string segment = c->get_segment_path();
if(segment_path == segment)
{
return c;
}
}
auto c = std::make_shared<NetworkTopology::Topology::UnderlayTopology>();
c->parent = this;
underlay_topology.push_back(c);
return c;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
for (auto const & c : link)
{
children[c->get_segment_path()] = c;
}
for (auto const & c : node)
{
children[c->get_segment_path()] = c;
}
if(topology_types != nullptr)
{
children["topology-types"] = topology_types;
}
for (auto const & c : underlay_topology)
{
children[c->get_segment_path()] = c;
}
return children;
}
void NetworkTopology::Topology::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "topology-id")
{
topology_id = value;
topology_id.value_namespace = name_space;
topology_id.value_namespace_prefix = name_space_prefix;
}
if(value_path == "server-provided")
{
server_provided = value;
server_provided.value_namespace = name_space;
server_provided.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "topology-id")
{
topology_id.yfilter = yfilter;
}
if(value_path == "server-provided")
{
server_provided.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "link" || name == "node" || name == "topology-types" || name == "underlay-topology" || name == "topology-id" || name == "server-provided")
return true;
return false;
}
NetworkTopology::Topology::TopologyTypes::TopologyTypes()
:
topology_netconf(std::make_shared<NetworkTopology::Topology::TopologyTypes::TopologyNetconf>())
{
topology_netconf->parent = this;
yang_name = "topology-types"; yang_parent_name = "topology";
}
NetworkTopology::Topology::TopologyTypes::~TopologyTypes()
{
}
bool NetworkTopology::Topology::TopologyTypes::has_data() const
{
return (topology_netconf != nullptr && topology_netconf->has_data());
}
bool NetworkTopology::Topology::TopologyTypes::has_operation() const
{
return is_set(yfilter)
|| (topology_netconf != nullptr && topology_netconf->has_operation());
}
std::string NetworkTopology::Topology::TopologyTypes::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "topology-types";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::TopologyTypes::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;;
}
std::shared_ptr<Entity> NetworkTopology::Topology::TopologyTypes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "topology-netconf")
{
if(topology_netconf == nullptr)
{
topology_netconf = std::make_shared<NetworkTopology::Topology::TopologyTypes::TopologyNetconf>();
}
return topology_netconf;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::TopologyTypes::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
if(topology_netconf != nullptr)
{
children["topology-netconf"] = topology_netconf;
}
return children;
}
void NetworkTopology::Topology::TopologyTypes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void NetworkTopology::Topology::TopologyTypes::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool NetworkTopology::Topology::TopologyTypes::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "topology-netconf")
return true;
return false;
}
NetworkTopology::Topology::TopologyTypes::TopologyNetconf::TopologyNetconf()
{
yang_name = "topology-netconf"; yang_parent_name = "topology-types";
}
NetworkTopology::Topology::TopologyTypes::TopologyNetconf::~TopologyNetconf()
{
}
bool NetworkTopology::Topology::TopologyTypes::TopologyNetconf::has_data() const
{
return false;
}
bool NetworkTopology::Topology::TopologyTypes::TopologyNetconf::has_operation() const
{
return is_set(yfilter);
}
std::string NetworkTopology::Topology::TopologyTypes::TopologyNetconf::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "netconf-node-topology:topology-netconf";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::TopologyTypes::TopologyNetconf::get_name_leaf_data() const
{
return {};
}
std::shared_ptr<Entity> NetworkTopology::Topology::TopologyTypes::TopologyNetconf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::TopologyTypes::TopologyNetconf::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::TopologyTypes::TopologyNetconf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void NetworkTopology::Topology::TopologyTypes::TopologyNetconf::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool NetworkTopology::Topology::TopologyTypes::TopologyNetconf::has_leaf_or_child_of_name(const std::string & name) const
{
return false;
}
NetworkTopology::Topology::UnderlayTopology::UnderlayTopology()
:
topology_ref{YType::str, "topology-ref"}
{
yang_name = "underlay-topology"; yang_parent_name = "topology";
}
NetworkTopology::Topology::UnderlayTopology::~UnderlayTopology()
{
}
bool NetworkTopology::Topology::UnderlayTopology::has_data() const
{
return topology_ref.is_set;
}
bool NetworkTopology::Topology::UnderlayTopology::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(topology_ref.yfilter);
}
std::string NetworkTopology::Topology::UnderlayTopology::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "underlay-topology" <<"[topology-ref='" <<topology_ref <<"']";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::UnderlayTopology::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (topology_ref.is_set || is_set(topology_ref.yfilter)) leaf_name_data.push_back(topology_ref.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::UnderlayTopology::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::UnderlayTopology::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::UnderlayTopology::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "topology-ref")
{
topology_ref = value;
topology_ref.value_namespace = name_space;
topology_ref.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::UnderlayTopology::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "topology-ref")
{
topology_ref.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::UnderlayTopology::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "topology-ref")
return true;
return false;
}
NetworkTopology::Topology::Node::Node()
:
node_id{YType::str, "node-id"},
between_attempts_timeout_millis{YType::uint16, "netconf-node-topology:between-attempts-timeout-millis"},
concurrent_rpc_limit{YType::uint16, "netconf-node-topology:concurrent-rpc-limit"},
connected_message{YType::str, "netconf-node-topology:connected-message"},
connection_status{YType::enumeration, "netconf-node-topology:connection-status"},
connection_timeout_millis{YType::uint32, "netconf-node-topology:connection-timeout-millis"},
default_request_timeout_millis{YType::uint32, "netconf-node-topology:default-request-timeout-millis"},
host{YType::str, "netconf-node-topology:host"},
keepalive_delay{YType::uint32, "netconf-node-topology:keepalive-delay"},
max_connection_attempts{YType::uint32, "netconf-node-topology:max-connection-attempts"},
password{YType::str, "netconf-node-topology:password"},
port{YType::uint16, "netconf-node-topology:port"},
reconnect_on_changed_schema{YType::boolean, "netconf-node-topology:reconnect-on-changed-schema"},
schema_cache_directory{YType::str, "netconf-node-topology:schema-cache-directory"},
schemaless{YType::boolean, "netconf-node-topology:schemaless"},
sleep_factor{YType::str, "netconf-node-topology:sleep-factor"},
tcp_only{YType::boolean, "netconf-node-topology:tcp-only"},
username{YType::str, "netconf-node-topology:username"}
,
available_capabilities(std::make_shared<NetworkTopology::Topology::Node::AvailableCapabilities>())
,clustered_connection_status(std::make_shared<NetworkTopology::Topology::Node::ClusteredConnectionStatus>())
,pass_through(std::make_shared<NetworkTopology::Topology::Node::PassThrough>())
,unavailable_capabilities(std::make_shared<NetworkTopology::Topology::Node::UnavailableCapabilities>())
,yang_library(std::make_shared<NetworkTopology::Topology::Node::YangLibrary>())
,yang_module_capabilities(std::make_shared<NetworkTopology::Topology::Node::YangModuleCapabilities>())
{
available_capabilities->parent = this;
clustered_connection_status->parent = this;
pass_through->parent = this;
unavailable_capabilities->parent = this;
yang_library->parent = this;
yang_module_capabilities->parent = this;
yang_name = "node"; yang_parent_name = "topology";
}
NetworkTopology::Topology::Node::~Node()
{
}
bool NetworkTopology::Topology::Node::has_data() const
{
for (std::size_t index=0; index<supporting_node.size(); index++)
{
if(supporting_node[index]->has_data())
return true;
}
for (std::size_t index=0; index<termination_point.size(); index++)
{
if(termination_point[index]->has_data())
return true;
}
return node_id.is_set
|| between_attempts_timeout_millis.is_set
|| concurrent_rpc_limit.is_set
|| connected_message.is_set
|| connection_status.is_set
|| connection_timeout_millis.is_set
|| default_request_timeout_millis.is_set
|| host.is_set
|| keepalive_delay.is_set
|| max_connection_attempts.is_set
|| password.is_set
|| port.is_set
|| reconnect_on_changed_schema.is_set
|| schema_cache_directory.is_set
|| schemaless.is_set
|| sleep_factor.is_set
|| tcp_only.is_set
|| username.is_set
|| (available_capabilities != nullptr && available_capabilities->has_data())
|| (clustered_connection_status != nullptr && clustered_connection_status->has_data())
|| (pass_through != nullptr && pass_through->has_data())
|| (unavailable_capabilities != nullptr && unavailable_capabilities->has_data())
|| (yang_library != nullptr && yang_library->has_data())
|| (yang_module_capabilities != nullptr && yang_module_capabilities->has_data());
}
bool NetworkTopology::Topology::Node::has_operation() const
{
for (std::size_t index=0; index<supporting_node.size(); index++)
{
if(supporting_node[index]->has_operation())
return true;
}
for (std::size_t index=0; index<termination_point.size(); index++)
{
if(termination_point[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(node_id.yfilter)
|| ydk::is_set(between_attempts_timeout_millis.yfilter)
|| ydk::is_set(concurrent_rpc_limit.yfilter)
|| ydk::is_set(connected_message.yfilter)
|| ydk::is_set(connection_status.yfilter)
|| ydk::is_set(connection_timeout_millis.yfilter)
|| ydk::is_set(default_request_timeout_millis.yfilter)
|| ydk::is_set(host.yfilter)
|| ydk::is_set(keepalive_delay.yfilter)
|| ydk::is_set(max_connection_attempts.yfilter)
|| ydk::is_set(password.yfilter)
|| ydk::is_set(port.yfilter)
|| ydk::is_set(reconnect_on_changed_schema.yfilter)
|| ydk::is_set(schema_cache_directory.yfilter)
|| ydk::is_set(schemaless.yfilter)
|| ydk::is_set(sleep_factor.yfilter)
|| ydk::is_set(tcp_only.yfilter)
|| ydk::is_set(username.yfilter)
|| (available_capabilities != nullptr && available_capabilities->has_operation())
|| (clustered_connection_status != nullptr && clustered_connection_status->has_operation())
|| (pass_through != nullptr && pass_through->has_operation())
|| (unavailable_capabilities != nullptr && unavailable_capabilities->has_operation())
|| (yang_library != nullptr && yang_library->has_operation())
|| (yang_module_capabilities != nullptr && yang_module_capabilities->has_operation());
}
std::string NetworkTopology::Topology::Node::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "node" <<"[node-id='" <<node_id <<"']";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (node_id.is_set || is_set(node_id.yfilter)) leaf_name_data.push_back(node_id.get_name_leafdata());
if (between_attempts_timeout_millis.is_set || is_set(between_attempts_timeout_millis.yfilter)) leaf_name_data.push_back(between_attempts_timeout_millis.get_name_leafdata());
if (concurrent_rpc_limit.is_set || is_set(concurrent_rpc_limit.yfilter)) leaf_name_data.push_back(concurrent_rpc_limit.get_name_leafdata());
if (connected_message.is_set || is_set(connected_message.yfilter)) leaf_name_data.push_back(connected_message.get_name_leafdata());
if (connection_status.is_set || is_set(connection_status.yfilter)) leaf_name_data.push_back(connection_status.get_name_leafdata());
if (connection_timeout_millis.is_set || is_set(connection_timeout_millis.yfilter)) leaf_name_data.push_back(connection_timeout_millis.get_name_leafdata());
if (default_request_timeout_millis.is_set || is_set(default_request_timeout_millis.yfilter)) leaf_name_data.push_back(default_request_timeout_millis.get_name_leafdata());
if (host.is_set || is_set(host.yfilter)) leaf_name_data.push_back(host.get_name_leafdata());
if (keepalive_delay.is_set || is_set(keepalive_delay.yfilter)) leaf_name_data.push_back(keepalive_delay.get_name_leafdata());
if (max_connection_attempts.is_set || is_set(max_connection_attempts.yfilter)) leaf_name_data.push_back(max_connection_attempts.get_name_leafdata());
if (password.is_set || is_set(password.yfilter)) leaf_name_data.push_back(password.get_name_leafdata());
if (port.is_set || is_set(port.yfilter)) leaf_name_data.push_back(port.get_name_leafdata());
if (reconnect_on_changed_schema.is_set || is_set(reconnect_on_changed_schema.yfilter)) leaf_name_data.push_back(reconnect_on_changed_schema.get_name_leafdata());
if (schema_cache_directory.is_set || is_set(schema_cache_directory.yfilter)) leaf_name_data.push_back(schema_cache_directory.get_name_leafdata());
if (schemaless.is_set || is_set(schemaless.yfilter)) leaf_name_data.push_back(schemaless.get_name_leafdata());
if (sleep_factor.is_set || is_set(sleep_factor.yfilter)) leaf_name_data.push_back(sleep_factor.get_name_leafdata());
if (tcp_only.is_set || is_set(tcp_only.yfilter)) leaf_name_data.push_back(tcp_only.get_name_leafdata());
if (username.is_set || is_set(username.yfilter)) leaf_name_data.push_back(username.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "available-capabilities")
{
if(available_capabilities == nullptr)
{
available_capabilities = std::make_shared<NetworkTopology::Topology::Node::AvailableCapabilities>();
}
return available_capabilities;
}
if(child_yang_name == "clustered-connection-status")
{
if(clustered_connection_status == nullptr)
{
clustered_connection_status = std::make_shared<NetworkTopology::Topology::Node::ClusteredConnectionStatus>();
}
return clustered_connection_status;
}
if(child_yang_name == "pass-through")
{
if(pass_through == nullptr)
{
pass_through = std::make_shared<NetworkTopology::Topology::Node::PassThrough>();
}
return pass_through;
}
if(child_yang_name == "supporting-node")
{
for(auto const & c : supporting_node)
{
std::string segment = c->get_segment_path();
if(segment_path == segment)
{
return c;
}
}
auto c = std::make_shared<NetworkTopology::Topology::Node::SupportingNode>();
c->parent = this;
supporting_node.push_back(c);
return c;
}
if(child_yang_name == "termination-point")
{
for(auto const & c : termination_point)
{
std::string segment = c->get_segment_path();
if(segment_path == segment)
{
return c;
}
}
auto c = std::make_shared<NetworkTopology::Topology::Node::TerminationPoint>();
c->parent = this;
termination_point.push_back(c);
return c;
}
if(child_yang_name == "unavailable-capabilities")
{
if(unavailable_capabilities == nullptr)
{
unavailable_capabilities = std::make_shared<NetworkTopology::Topology::Node::UnavailableCapabilities>();
}
return unavailable_capabilities;
}
if(child_yang_name == "yang-library")
{
if(yang_library == nullptr)
{
yang_library = std::make_shared<NetworkTopology::Topology::Node::YangLibrary>();
}
return yang_library;
}
if(child_yang_name == "yang-module-capabilities")
{
if(yang_module_capabilities == nullptr)
{
yang_module_capabilities = std::make_shared<NetworkTopology::Topology::Node::YangModuleCapabilities>();
}
return yang_module_capabilities;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
if(available_capabilities != nullptr)
{
children["available-capabilities"] = available_capabilities;
}
if(clustered_connection_status != nullptr)
{
children["clustered-connection-status"] = clustered_connection_status;
}
if(pass_through != nullptr)
{
children["pass-through"] = pass_through;
}
for (auto const & c : supporting_node)
{
children[c->get_segment_path()] = c;
}
for (auto const & c : termination_point)
{
children[c->get_segment_path()] = c;
}
if(unavailable_capabilities != nullptr)
{
children["unavailable-capabilities"] = unavailable_capabilities;
}
if(yang_library != nullptr)
{
children["yang-library"] = yang_library;
}
if(yang_module_capabilities != nullptr)
{
children["yang-module-capabilities"] = yang_module_capabilities;
}
return children;
}
void NetworkTopology::Topology::Node::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "node-id")
{
node_id = value;
node_id.value_namespace = name_space;
node_id.value_namespace_prefix = name_space_prefix;
}
if(value_path == "between-attempts-timeout-millis")
{
between_attempts_timeout_millis = value;
between_attempts_timeout_millis.value_namespace = name_space;
between_attempts_timeout_millis.value_namespace_prefix = name_space_prefix;
}
if(value_path == "concurrent-rpc-limit")
{
concurrent_rpc_limit = value;
concurrent_rpc_limit.value_namespace = name_space;
concurrent_rpc_limit.value_namespace_prefix = name_space_prefix;
}
if(value_path == "connected-message")
{
connected_message = value;
connected_message.value_namespace = name_space;
connected_message.value_namespace_prefix = name_space_prefix;
}
if(value_path == "connection-status")
{
connection_status = value;
connection_status.value_namespace = name_space;
connection_status.value_namespace_prefix = name_space_prefix;
}
if(value_path == "connection-timeout-millis")
{
connection_timeout_millis = value;
connection_timeout_millis.value_namespace = name_space;
connection_timeout_millis.value_namespace_prefix = name_space_prefix;
}
if(value_path == "default-request-timeout-millis")
{
default_request_timeout_millis = value;
default_request_timeout_millis.value_namespace = name_space;
default_request_timeout_millis.value_namespace_prefix = name_space_prefix;
}
if(value_path == "host")
{
host = value;
host.value_namespace = name_space;
host.value_namespace_prefix = name_space_prefix;
}
if(value_path == "keepalive-delay")
{
keepalive_delay = value;
keepalive_delay.value_namespace = name_space;
keepalive_delay.value_namespace_prefix = name_space_prefix;
}
if(value_path == "max-connection-attempts")
{
max_connection_attempts = value;
max_connection_attempts.value_namespace = name_space;
max_connection_attempts.value_namespace_prefix = name_space_prefix;
}
if(value_path == "password")
{
password = value;
password.value_namespace = name_space;
password.value_namespace_prefix = name_space_prefix;
}
if(value_path == "port")
{
port = value;
port.value_namespace = name_space;
port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "reconnect-on-changed-schema")
{
reconnect_on_changed_schema = value;
reconnect_on_changed_schema.value_namespace = name_space;
reconnect_on_changed_schema.value_namespace_prefix = name_space_prefix;
}
if(value_path == "schema-cache-directory")
{
schema_cache_directory = value;
schema_cache_directory.value_namespace = name_space;
schema_cache_directory.value_namespace_prefix = name_space_prefix;
}
if(value_path == "schemaless")
{
schemaless = value;
schemaless.value_namespace = name_space;
schemaless.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sleep-factor")
{
sleep_factor = value;
sleep_factor.value_namespace = name_space;
sleep_factor.value_namespace_prefix = name_space_prefix;
}
if(value_path == "tcp-only")
{
tcp_only = value;
tcp_only.value_namespace = name_space;
tcp_only.value_namespace_prefix = name_space_prefix;
}
if(value_path == "username")
{
username = value;
username.value_namespace = name_space;
username.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Node::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "node-id")
{
node_id.yfilter = yfilter;
}
if(value_path == "between-attempts-timeout-millis")
{
between_attempts_timeout_millis.yfilter = yfilter;
}
if(value_path == "concurrent-rpc-limit")
{
concurrent_rpc_limit.yfilter = yfilter;
}
if(value_path == "connected-message")
{
connected_message.yfilter = yfilter;
}
if(value_path == "connection-status")
{
connection_status.yfilter = yfilter;
}
if(value_path == "connection-timeout-millis")
{
connection_timeout_millis.yfilter = yfilter;
}
if(value_path == "default-request-timeout-millis")
{
default_request_timeout_millis.yfilter = yfilter;
}
if(value_path == "host")
{
host.yfilter = yfilter;
}
if(value_path == "keepalive-delay")
{
keepalive_delay.yfilter = yfilter;
}
if(value_path == "max-connection-attempts")
{
max_connection_attempts.yfilter = yfilter;
}
if(value_path == "password")
{
password.yfilter = yfilter;
}
if(value_path == "port")
{
port.yfilter = yfilter;
}
if(value_path == "reconnect-on-changed-schema")
{
reconnect_on_changed_schema.yfilter = yfilter;
}
if(value_path == "schema-cache-directory")
{
schema_cache_directory.yfilter = yfilter;
}
if(value_path == "schemaless")
{
schemaless.yfilter = yfilter;
}
if(value_path == "sleep-factor")
{
sleep_factor.yfilter = yfilter;
}
if(value_path == "tcp-only")
{
tcp_only.yfilter = yfilter;
}
if(value_path == "username")
{
username.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Node::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "available-capabilities" || name == "clustered-connection-status" || name == "pass-through" || name == "supporting-node" || name == "termination-point" || name == "unavailable-capabilities" || name == "yang-library" || name == "yang-module-capabilities" || name == "node-id" || name == "between-attempts-timeout-millis" || name == "concurrent-rpc-limit" || name == "connected-message" || name == "connection-status" || name == "connection-timeout-millis" || name == "default-request-timeout-millis" || name == "host" || name == "keepalive-delay" || name == "max-connection-attempts" || name == "password" || name == "port" || name == "reconnect-on-changed-schema" || name == "schema-cache-directory" || name == "schemaless" || name == "sleep-factor" || name == "tcp-only" || name == "username")
return true;
return false;
}
NetworkTopology::Topology::Node::SupportingNode::SupportingNode()
:
topology_ref{YType::str, "topology-ref"},
node_ref{YType::str, "node-ref"}
{
yang_name = "supporting-node"; yang_parent_name = "node";
}
NetworkTopology::Topology::Node::SupportingNode::~SupportingNode()
{
}
bool NetworkTopology::Topology::Node::SupportingNode::has_data() const
{
return topology_ref.is_set
|| node_ref.is_set;
}
bool NetworkTopology::Topology::Node::SupportingNode::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(topology_ref.yfilter)
|| ydk::is_set(node_ref.yfilter);
}
std::string NetworkTopology::Topology::Node::SupportingNode::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "supporting-node" <<"[topology-ref='" <<topology_ref <<"']" <<"[node-ref='" <<node_ref <<"']";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::SupportingNode::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (topology_ref.is_set || is_set(topology_ref.yfilter)) leaf_name_data.push_back(topology_ref.get_name_leafdata());
if (node_ref.is_set || is_set(node_ref.yfilter)) leaf_name_data.push_back(node_ref.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::SupportingNode::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::SupportingNode::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Node::SupportingNode::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "topology-ref")
{
topology_ref = value;
topology_ref.value_namespace = name_space;
topology_ref.value_namespace_prefix = name_space_prefix;
}
if(value_path == "node-ref")
{
node_ref = value;
node_ref.value_namespace = name_space;
node_ref.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Node::SupportingNode::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "topology-ref")
{
topology_ref.yfilter = yfilter;
}
if(value_path == "node-ref")
{
node_ref.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Node::SupportingNode::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "topology-ref" || name == "node-ref")
return true;
return false;
}
NetworkTopology::Topology::Node::TerminationPoint::TerminationPoint()
:
tp_id{YType::str, "tp-id"},
tp_ref{YType::str, "tp-ref"}
{
yang_name = "termination-point"; yang_parent_name = "node";
}
NetworkTopology::Topology::Node::TerminationPoint::~TerminationPoint()
{
}
bool NetworkTopology::Topology::Node::TerminationPoint::has_data() const
{
for (auto const & leaf : tp_ref.getYLeafs())
{
if(leaf.is_set)
return true;
}
return tp_id.is_set;
}
bool NetworkTopology::Topology::Node::TerminationPoint::has_operation() const
{
for (auto const & leaf : tp_ref.getYLeafs())
{
if(is_set(leaf.yfilter))
return true;
}
return is_set(yfilter)
|| ydk::is_set(tp_id.yfilter)
|| ydk::is_set(tp_ref.yfilter);
}
std::string NetworkTopology::Topology::Node::TerminationPoint::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "termination-point" <<"[tp-id='" <<tp_id <<"']";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::TerminationPoint::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (tp_id.is_set || is_set(tp_id.yfilter)) leaf_name_data.push_back(tp_id.get_name_leafdata());
auto tp_ref_name_datas = tp_ref.get_name_leafdata();
leaf_name_data.insert(leaf_name_data.end(), tp_ref_name_datas.begin(), tp_ref_name_datas.end());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::TerminationPoint::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::TerminationPoint::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Node::TerminationPoint::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "tp-id")
{
tp_id = value;
tp_id.value_namespace = name_space;
tp_id.value_namespace_prefix = name_space_prefix;
}
if(value_path == "tp-ref")
{
tp_ref.append(value);
}
}
void NetworkTopology::Topology::Node::TerminationPoint::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "tp-id")
{
tp_id.yfilter = yfilter;
}
if(value_path == "tp-ref")
{
tp_ref.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Node::TerminationPoint::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "tp-id" || name == "tp-ref")
return true;
return false;
}
NetworkTopology::Topology::Node::YangModuleCapabilities::YangModuleCapabilities()
:
capability{YType::str, "capability"},
override{YType::boolean, "override"}
{
yang_name = "yang-module-capabilities"; yang_parent_name = "node";
}
NetworkTopology::Topology::Node::YangModuleCapabilities::~YangModuleCapabilities()
{
}
bool NetworkTopology::Topology::Node::YangModuleCapabilities::has_data() const
{
for (auto const & leaf : capability.getYLeafs())
{
if(leaf.is_set)
return true;
}
return override.is_set;
}
bool NetworkTopology::Topology::Node::YangModuleCapabilities::has_operation() const
{
for (auto const & leaf : capability.getYLeafs())
{
if(is_set(leaf.yfilter))
return true;
}
return is_set(yfilter)
|| ydk::is_set(capability.yfilter)
|| ydk::is_set(override.yfilter);
}
std::string NetworkTopology::Topology::Node::YangModuleCapabilities::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "netconf-node-topology:yang-module-capabilities";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::YangModuleCapabilities::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (override.is_set || is_set(override.yfilter)) leaf_name_data.push_back(override.get_name_leafdata());
auto capability_name_datas = capability.get_name_leafdata();
leaf_name_data.insert(leaf_name_data.end(), capability_name_datas.begin(), capability_name_datas.end());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::YangModuleCapabilities::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::YangModuleCapabilities::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Node::YangModuleCapabilities::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "capability")
{
capability.append(value);
}
if(value_path == "override")
{
override = value;
override.value_namespace = name_space;
override.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Node::YangModuleCapabilities::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "capability")
{
capability.yfilter = yfilter;
}
if(value_path == "override")
{
override.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Node::YangModuleCapabilities::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "capability" || name == "override")
return true;
return false;
}
NetworkTopology::Topology::Node::ClusteredConnectionStatus::ClusteredConnectionStatus()
:
netconf_master_node{YType::str, "netconf-master-node"}
{
yang_name = "clustered-connection-status"; yang_parent_name = "node";
}
NetworkTopology::Topology::Node::ClusteredConnectionStatus::~ClusteredConnectionStatus()
{
}
bool NetworkTopology::Topology::Node::ClusteredConnectionStatus::has_data() const
{
for (std::size_t index=0; index<node_status.size(); index++)
{
if(node_status[index]->has_data())
return true;
}
return netconf_master_node.is_set;
}
bool NetworkTopology::Topology::Node::ClusteredConnectionStatus::has_operation() const
{
for (std::size_t index=0; index<node_status.size(); index++)
{
if(node_status[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(netconf_master_node.yfilter);
}
std::string NetworkTopology::Topology::Node::ClusteredConnectionStatus::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "netconf-node-topology:clustered-connection-status";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::ClusteredConnectionStatus::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (netconf_master_node.is_set || is_set(netconf_master_node.yfilter)) leaf_name_data.push_back(netconf_master_node.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::ClusteredConnectionStatus::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "node-status")
{
for(auto const & c : node_status)
{
std::string segment = c->get_segment_path();
if(segment_path == segment)
{
return c;
}
}
auto c = std::make_shared<NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus>();
c->parent = this;
node_status.push_back(c);
return c;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::ClusteredConnectionStatus::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
for (auto const & c : node_status)
{
children[c->get_segment_path()] = c;
}
return children;
}
void NetworkTopology::Topology::Node::ClusteredConnectionStatus::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "netconf-master-node")
{
netconf_master_node = value;
netconf_master_node.value_namespace = name_space;
netconf_master_node.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Node::ClusteredConnectionStatus::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "netconf-master-node")
{
netconf_master_node.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Node::ClusteredConnectionStatus::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "node-status" || name == "netconf-master-node")
return true;
return false;
}
NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::NodeStatus()
:
node{YType::str, "node"},
status{YType::enumeration, "status"}
{
yang_name = "node-status"; yang_parent_name = "clustered-connection-status";
}
NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::~NodeStatus()
{
}
bool NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::has_data() const
{
return node.is_set
|| status.is_set;
}
bool NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(node.yfilter)
|| ydk::is_set(status.yfilter);
}
std::string NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "node-status";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (node.is_set || is_set(node.yfilter)) leaf_name_data.push_back(node.get_name_leafdata());
if (status.is_set || is_set(status.yfilter)) leaf_name_data.push_back(status.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "node")
{
node = value;
node.value_namespace = name_space;
node.value_namespace_prefix = name_space_prefix;
}
if(value_path == "status")
{
status = value;
status.value_namespace = name_space;
status.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "node")
{
node.yfilter = yfilter;
}
if(value_path == "status")
{
status.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "node" || name == "status")
return true;
return false;
}
NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapabilities()
{
yang_name = "available-capabilities"; yang_parent_name = "node";
}
NetworkTopology::Topology::Node::AvailableCapabilities::~AvailableCapabilities()
{
}
bool NetworkTopology::Topology::Node::AvailableCapabilities::has_data() const
{
for (std::size_t index=0; index<available_capability.size(); index++)
{
if(available_capability[index]->has_data())
return true;
}
return false;
}
bool NetworkTopology::Topology::Node::AvailableCapabilities::has_operation() const
{
for (std::size_t index=0; index<available_capability.size(); index++)
{
if(available_capability[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string NetworkTopology::Topology::Node::AvailableCapabilities::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "netconf-node-topology:available-capabilities";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::AvailableCapabilities::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::AvailableCapabilities::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "available-capability")
{
for(auto const & c : available_capability)
{
std::string segment = c->get_segment_path();
if(segment_path == segment)
{
return c;
}
}
auto c = std::make_shared<NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability>();
c->parent = this;
available_capability.push_back(c);
return c;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::AvailableCapabilities::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
for (auto const & c : available_capability)
{
children[c->get_segment_path()] = c;
}
return children;
}
void NetworkTopology::Topology::Node::AvailableCapabilities::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void NetworkTopology::Topology::Node::AvailableCapabilities::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool NetworkTopology::Topology::Node::AvailableCapabilities::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "available-capability")
return true;
return false;
}
NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::AvailableCapability()
:
capability{YType::str, "capability"},
capability_origin{YType::enumeration, "capability-origin"}
{
yang_name = "available-capability"; yang_parent_name = "available-capabilities";
}
NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::~AvailableCapability()
{
}
bool NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::has_data() const
{
return capability.is_set
|| capability_origin.is_set;
}
bool NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(capability.yfilter)
|| ydk::is_set(capability_origin.yfilter);
}
std::string NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "available-capability";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (capability.is_set || is_set(capability.yfilter)) leaf_name_data.push_back(capability.get_name_leafdata());
if (capability_origin.is_set || is_set(capability_origin.yfilter)) leaf_name_data.push_back(capability_origin.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "capability")
{
capability = value;
capability.value_namespace = name_space;
capability.value_namespace_prefix = name_space_prefix;
}
if(value_path == "capability-origin")
{
capability_origin = value;
capability_origin.value_namespace = name_space;
capability_origin.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "capability")
{
capability.yfilter = yfilter;
}
if(value_path == "capability-origin")
{
capability_origin.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "capability" || name == "capability-origin")
return true;
return false;
}
NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapabilities()
{
yang_name = "unavailable-capabilities"; yang_parent_name = "node";
}
NetworkTopology::Topology::Node::UnavailableCapabilities::~UnavailableCapabilities()
{
}
bool NetworkTopology::Topology::Node::UnavailableCapabilities::has_data() const
{
for (std::size_t index=0; index<unavailable_capability.size(); index++)
{
if(unavailable_capability[index]->has_data())
return true;
}
return false;
}
bool NetworkTopology::Topology::Node::UnavailableCapabilities::has_operation() const
{
for (std::size_t index=0; index<unavailable_capability.size(); index++)
{
if(unavailable_capability[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string NetworkTopology::Topology::Node::UnavailableCapabilities::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "netconf-node-topology:unavailable-capabilities";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::UnavailableCapabilities::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::UnavailableCapabilities::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "unavailable-capability")
{
for(auto const & c : unavailable_capability)
{
std::string segment = c->get_segment_path();
if(segment_path == segment)
{
return c;
}
}
auto c = std::make_shared<NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability>();
c->parent = this;
unavailable_capability.push_back(c);
return c;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::UnavailableCapabilities::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
for (auto const & c : unavailable_capability)
{
children[c->get_segment_path()] = c;
}
return children;
}
void NetworkTopology::Topology::Node::UnavailableCapabilities::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void NetworkTopology::Topology::Node::UnavailableCapabilities::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool NetworkTopology::Topology::Node::UnavailableCapabilities::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "unavailable-capability")
return true;
return false;
}
NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::UnavailableCapability()
:
capability{YType::str, "capability"},
failure_reason{YType::enumeration, "failure-reason"}
{
yang_name = "unavailable-capability"; yang_parent_name = "unavailable-capabilities";
}
NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::~UnavailableCapability()
{
}
bool NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::has_data() const
{
return capability.is_set
|| failure_reason.is_set;
}
bool NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(capability.yfilter)
|| ydk::is_set(failure_reason.yfilter);
}
std::string NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "unavailable-capability";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (capability.is_set || is_set(capability.yfilter)) leaf_name_data.push_back(capability.get_name_leafdata());
if (failure_reason.is_set || is_set(failure_reason.yfilter)) leaf_name_data.push_back(failure_reason.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "capability")
{
capability = value;
capability.value_namespace = name_space;
capability.value_namespace_prefix = name_space_prefix;
}
if(value_path == "failure-reason")
{
failure_reason = value;
failure_reason.value_namespace = name_space;
failure_reason.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "capability")
{
capability.yfilter = yfilter;
}
if(value_path == "failure-reason")
{
failure_reason.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "capability" || name == "failure-reason")
return true;
return false;
}
NetworkTopology::Topology::Node::PassThrough::PassThrough()
{
yang_name = "pass-through"; yang_parent_name = "node";
}
NetworkTopology::Topology::Node::PassThrough::~PassThrough()
{
}
bool NetworkTopology::Topology::Node::PassThrough::has_data() const
{
return false;
}
bool NetworkTopology::Topology::Node::PassThrough::has_operation() const
{
return is_set(yfilter);
}
std::string NetworkTopology::Topology::Node::PassThrough::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "netconf-node-topology:pass-through";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::PassThrough::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::PassThrough::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::PassThrough::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Node::PassThrough::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void NetworkTopology::Topology::Node::PassThrough::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool NetworkTopology::Topology::Node::PassThrough::has_leaf_or_child_of_name(const std::string & name) const
{
return false;
}
NetworkTopology::Topology::Node::YangLibrary::YangLibrary()
:
password{YType::str, "password"},
username{YType::str, "username"},
yang_library_url{YType::str, "yang-library-url"}
{
yang_name = "yang-library"; yang_parent_name = "node";
}
NetworkTopology::Topology::Node::YangLibrary::~YangLibrary()
{
}
bool NetworkTopology::Topology::Node::YangLibrary::has_data() const
{
return password.is_set
|| username.is_set
|| yang_library_url.is_set;
}
bool NetworkTopology::Topology::Node::YangLibrary::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(password.yfilter)
|| ydk::is_set(username.yfilter)
|| ydk::is_set(yang_library_url.yfilter);
}
std::string NetworkTopology::Topology::Node::YangLibrary::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "netconf-node-topology:yang-library";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Node::YangLibrary::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (password.is_set || is_set(password.yfilter)) leaf_name_data.push_back(password.get_name_leafdata());
if (username.is_set || is_set(username.yfilter)) leaf_name_data.push_back(username.get_name_leafdata());
if (yang_library_url.is_set || is_set(yang_library_url.yfilter)) leaf_name_data.push_back(yang_library_url.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Node::YangLibrary::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Node::YangLibrary::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Node::YangLibrary::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "password")
{
password = value;
password.value_namespace = name_space;
password.value_namespace_prefix = name_space_prefix;
}
if(value_path == "username")
{
username = value;
username.value_namespace = name_space;
username.value_namespace_prefix = name_space_prefix;
}
if(value_path == "yang-library-url")
{
yang_library_url = value;
yang_library_url.value_namespace = name_space;
yang_library_url.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Node::YangLibrary::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "password")
{
password.yfilter = yfilter;
}
if(value_path == "username")
{
username.yfilter = yfilter;
}
if(value_path == "yang-library-url")
{
yang_library_url.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Node::YangLibrary::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "password" || name == "username" || name == "yang-library-url")
return true;
return false;
}
NetworkTopology::Topology::Link::Link()
:
link_id{YType::str, "link-id"}
,
destination(std::make_shared<NetworkTopology::Topology::Link::Destination>())
,source(std::make_shared<NetworkTopology::Topology::Link::Source>())
{
destination->parent = this;
source->parent = this;
yang_name = "link"; yang_parent_name = "topology";
}
NetworkTopology::Topology::Link::~Link()
{
}
bool NetworkTopology::Topology::Link::has_data() const
{
for (std::size_t index=0; index<supporting_link.size(); index++)
{
if(supporting_link[index]->has_data())
return true;
}
return link_id.is_set
|| (destination != nullptr && destination->has_data())
|| (source != nullptr && source->has_data());
}
bool NetworkTopology::Topology::Link::has_operation() const
{
for (std::size_t index=0; index<supporting_link.size(); index++)
{
if(supporting_link[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(link_id.yfilter)
|| (destination != nullptr && destination->has_operation())
|| (source != nullptr && source->has_operation());
}
std::string NetworkTopology::Topology::Link::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "link" <<"[link-id='" <<link_id <<"']";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Link::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (link_id.is_set || is_set(link_id.yfilter)) leaf_name_data.push_back(link_id.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Link::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "destination")
{
if(destination == nullptr)
{
destination = std::make_shared<NetworkTopology::Topology::Link::Destination>();
}
return destination;
}
if(child_yang_name == "source")
{
if(source == nullptr)
{
source = std::make_shared<NetworkTopology::Topology::Link::Source>();
}
return source;
}
if(child_yang_name == "supporting-link")
{
for(auto const & c : supporting_link)
{
std::string segment = c->get_segment_path();
if(segment_path == segment)
{
return c;
}
}
auto c = std::make_shared<NetworkTopology::Topology::Link::SupportingLink>();
c->parent = this;
supporting_link.push_back(c);
return c;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Link::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
if(destination != nullptr)
{
children["destination"] = destination;
}
if(source != nullptr)
{
children["source"] = source;
}
for (auto const & c : supporting_link)
{
children[c->get_segment_path()] = c;
}
return children;
}
void NetworkTopology::Topology::Link::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "link-id")
{
link_id = value;
link_id.value_namespace = name_space;
link_id.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Link::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "link-id")
{
link_id.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Link::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "destination" || name == "source" || name == "supporting-link" || name == "link-id")
return true;
return false;
}
NetworkTopology::Topology::Link::Source::Source()
:
source_node{YType::str, "source-node"},
source_tp{YType::str, "source-tp"}
{
yang_name = "source"; yang_parent_name = "link";
}
NetworkTopology::Topology::Link::Source::~Source()
{
}
bool NetworkTopology::Topology::Link::Source::has_data() const
{
return source_node.is_set
|| source_tp.is_set;
}
bool NetworkTopology::Topology::Link::Source::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(source_node.yfilter)
|| ydk::is_set(source_tp.yfilter);
}
std::string NetworkTopology::Topology::Link::Source::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "source";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Link::Source::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (source_node.is_set || is_set(source_node.yfilter)) leaf_name_data.push_back(source_node.get_name_leafdata());
if (source_tp.is_set || is_set(source_tp.yfilter)) leaf_name_data.push_back(source_tp.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Link::Source::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Link::Source::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Link::Source::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "source-node")
{
source_node = value;
source_node.value_namespace = name_space;
source_node.value_namespace_prefix = name_space_prefix;
}
if(value_path == "source-tp")
{
source_tp = value;
source_tp.value_namespace = name_space;
source_tp.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Link::Source::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "source-node")
{
source_node.yfilter = yfilter;
}
if(value_path == "source-tp")
{
source_tp.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Link::Source::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "source-node" || name == "source-tp")
return true;
return false;
}
NetworkTopology::Topology::Link::Destination::Destination()
:
dest_node{YType::str, "dest-node"},
dest_tp{YType::str, "dest-tp"}
{
yang_name = "destination"; yang_parent_name = "link";
}
NetworkTopology::Topology::Link::Destination::~Destination()
{
}
bool NetworkTopology::Topology::Link::Destination::has_data() const
{
return dest_node.is_set
|| dest_tp.is_set;
}
bool NetworkTopology::Topology::Link::Destination::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(dest_node.yfilter)
|| ydk::is_set(dest_tp.yfilter);
}
std::string NetworkTopology::Topology::Link::Destination::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "destination";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Link::Destination::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (dest_node.is_set || is_set(dest_node.yfilter)) leaf_name_data.push_back(dest_node.get_name_leafdata());
if (dest_tp.is_set || is_set(dest_tp.yfilter)) leaf_name_data.push_back(dest_tp.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Link::Destination::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Link::Destination::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Link::Destination::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "dest-node")
{
dest_node = value;
dest_node.value_namespace = name_space;
dest_node.value_namespace_prefix = name_space_prefix;
}
if(value_path == "dest-tp")
{
dest_tp = value;
dest_tp.value_namespace = name_space;
dest_tp.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Link::Destination::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "dest-node")
{
dest_node.yfilter = yfilter;
}
if(value_path == "dest-tp")
{
dest_tp.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Link::Destination::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "dest-node" || name == "dest-tp")
return true;
return false;
}
NetworkTopology::Topology::Link::SupportingLink::SupportingLink()
:
link_ref{YType::str, "link-ref"}
{
yang_name = "supporting-link"; yang_parent_name = "link";
}
NetworkTopology::Topology::Link::SupportingLink::~SupportingLink()
{
}
bool NetworkTopology::Topology::Link::SupportingLink::has_data() const
{
return link_ref.is_set;
}
bool NetworkTopology::Topology::Link::SupportingLink::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(link_ref.yfilter);
}
std::string NetworkTopology::Topology::Link::SupportingLink::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "supporting-link" <<"[link-ref='" <<link_ref <<"']";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > NetworkTopology::Topology::Link::SupportingLink::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (link_ref.is_set || is_set(link_ref.yfilter)) leaf_name_data.push_back(link_ref.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<Entity> NetworkTopology::Topology::Link::SupportingLink::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<Entity>> NetworkTopology::Topology::Link::SupportingLink::get_children() const
{
std::map<std::string, std::shared_ptr<Entity>> children{};
return children;
}
void NetworkTopology::Topology::Link::SupportingLink::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "link-ref")
{
link_ref = value;
link_ref.value_namespace = name_space;
link_ref.value_namespace_prefix = name_space_prefix;
}
}
void NetworkTopology::Topology::Link::SupportingLink::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "link-ref")
{
link_ref.yfilter = yfilter;
}
}
bool NetworkTopology::Topology::Link::SupportingLink::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "link-ref")
return true;
return false;
}
const Enum::YLeaf NetworkTopology::Topology::Node::ConnectionStatus::connecting {0, "connecting"};
const Enum::YLeaf NetworkTopology::Topology::Node::ConnectionStatus::connected {1, "connected"};
const Enum::YLeaf NetworkTopology::Topology::Node::ConnectionStatus::unable_to_connect {2, "unable-to-connect"};
const Enum::YLeaf NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::Status::connected {0, "connected"};
const Enum::YLeaf NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::Status::unavailable {1, "unavailable"};
const Enum::YLeaf NetworkTopology::Topology::Node::ClusteredConnectionStatus::NodeStatus::Status::failed {2, "failed"};
const Enum::YLeaf NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::CapabilityOrigin::user_defined {0, "user-defined"};
const Enum::YLeaf NetworkTopology::Topology::Node::AvailableCapabilities::AvailableCapability::CapabilityOrigin::device_advertised {1, "device-advertised"};
const Enum::YLeaf NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::FailureReason::missing_source {0, "missing-source"};
const Enum::YLeaf NetworkTopology::Topology::Node::UnavailableCapabilities::UnavailableCapability::FailureReason::unable_to_resolve {1, "unable-to-resolve"};
}
}
| 30.98722
| 809
| 0.695884
|
YDK-Solutions
|
7252b4cf8166909fdca015773c08d681d5ab6a3c
| 2,643
|
cc
|
C++
|
src/ufo/marine/adt/ObsADTTLAD.cc
|
fmahebert/ufo
|
2af9b91433553ca473c72fcd131400a01c3aabdb
|
[
"Apache-2.0"
] | 1
|
2021-10-08T16:37:25.000Z
|
2021-10-08T16:37:25.000Z
|
src/ufo/marine/adt/ObsADTTLAD.cc
|
fmahebert/ufo
|
2af9b91433553ca473c72fcd131400a01c3aabdb
|
[
"Apache-2.0"
] | 9
|
2021-06-25T17:18:06.000Z
|
2021-10-08T17:40:31.000Z
|
src/ufo/marine/adt/ObsADTTLAD.cc
|
fmahebert/ufo
|
2af9b91433553ca473c72fcd131400a01c3aabdb
|
[
"Apache-2.0"
] | 31
|
2021-06-24T18:07:53.000Z
|
2021-10-08T15:40:39.000Z
|
/*
* (C) Copyright 2017-2018 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "ufo/marine/adt/ObsADTTLAD.h"
#include <ostream>
#include <string>
#include <vector>
#include "ioda/ObsSpace.h"
#include "ioda/ObsVector.h"
#include "oops/base/Variables.h"
#include "oops/util/Logger.h"
#include "ufo/GeoVaLs.h"
#include "ufo/ObsBias.h"
namespace ufo {
// -----------------------------------------------------------------------------
static LinearObsOperatorMaker<ObsADTTLAD> makerADTTL_("ADT");
// -----------------------------------------------------------------------------
ObsADTTLAD::ObsADTTLAD(const ioda::ObsSpace & odb, const eckit::Configuration & config)
: LinearObsOperatorBase(odb), keyOper_(0), varin_()
{
const std::vector<std::string> vv{"sea_surface_height_above_geoid"};
varin_.reset(new oops::Variables(vv));
ufo_adt_tlad_setup_f90(keyOper_, config);
oops::Log::trace() << "ObsADTTLAD created" << std::endl;
}
// -----------------------------------------------------------------------------
ObsADTTLAD::~ObsADTTLAD() {
ufo_adt_tlad_delete_f90(keyOper_);
oops::Log::trace() << "ObsADTTLAD destructed" << std::endl;
}
// -----------------------------------------------------------------------------
void ObsADTTLAD::setTrajectory(const GeoVaLs & geovals, const ObsBias & bias,
ObsDiagnostics &) {
ufo_adt_tlad_settraj_f90(keyOper_, geovals.toFortran(), obsspace());
oops::Log::trace() << "ObsADTTLAD: trajectory set" << std::endl;
}
// -----------------------------------------------------------------------------
void ObsADTTLAD::simulateObsTL(const GeoVaLs & geovals, ioda::ObsVector & ovec) const {
ufo_adt_simobs_tl_f90(keyOper_, geovals.toFortran(), obsspace(), ovec.size(), ovec.toFortran());
oops::Log::trace() << "ObsADTTLAD: tangent linear observation operator run" << std::endl;
}
// -----------------------------------------------------------------------------
void ObsADTTLAD::simulateObsAD(GeoVaLs & geovals, const ioda::ObsVector & ovec) const {
ufo_adt_simobs_ad_f90(keyOper_, geovals.toFortran(), obsspace(), ovec.size(), ovec.toFortran());
oops::Log::trace() << "ObsADTTLAD: adjoint observation operator run" << std::endl;
}
// -----------------------------------------------------------------------------
void ObsADTTLAD::print(std::ostream & os) const {
os << "ObsADTTLAD::print not implemented" << std::endl;
}
// -----------------------------------------------------------------------------
} // namespace ufo
| 35.716216
| 98
| 0.535376
|
fmahebert
|
7253d6553eb568b1cf7dacc4b6979c7572e9aac9
| 1,625
|
cpp
|
C++
|
library/source/lexicon_tests/terminal_tester.cpp
|
spiretrading/darcel
|
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
|
[
"MIT"
] | null | null | null |
library/source/lexicon_tests/terminal_tester.cpp
|
spiretrading/darcel
|
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
|
[
"MIT"
] | null | null | null |
library/source/lexicon_tests/terminal_tester.cpp
|
spiretrading/darcel
|
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
|
[
"MIT"
] | 1
|
2020-04-17T13:25:25.000Z
|
2020-04-17T13:25:25.000Z
|
#include <sstream>
#include <catch.hpp>
#include "darcel/lexicon/terminal.hpp"
using namespace darcel;
using namespace std;
TEST_CASE("test_terminal_stream", "[Terminal]") {
SECTION("New line") {
Terminal t(Terminal::Type::NEW_LINE);
stringstream ss;
ss << t;
REQUIRE(ss.str() == "\n");
}
SECTION("End of file") {
Terminal t(Terminal::Type::END_OF_FILE);
stringstream ss;
ss << t;
REQUIRE(ss.str().empty());
}
}
TEST_CASE("test_terminal_equality", "[Terminal]") {
Terminal t1(Terminal::Type::END_OF_FILE);
Terminal t2(Terminal::Type::NEW_LINE);
REQUIRE(t1 == t1);
REQUIRE(t1 == Terminal::Type::END_OF_FILE);
REQUIRE(t1 != t2);
REQUIRE(t2 == Terminal::Type::NEW_LINE);
}
TEST_CASE("test_parse_terminal", "[Terminal]") {
SECTION("Valid Terminal") {
auto s = "\0";
REQUIRE(parse_terminal(LexicalIterator(s, 1)) ==
Terminal::Type::END_OF_FILE);
REQUIRE(parse_terminal("\n") == Terminal::Type::NEW_LINE);
}
SECTION("Delimiters") {
auto s = "\09";
REQUIRE(parse_terminal(LexicalIterator(s, 2)) ==
Terminal::Type::END_OF_FILE);
s = "\0+";
REQUIRE(parse_terminal(LexicalIterator(s, 1)) ==
Terminal::Type::END_OF_FILE);
s = "\0:";
REQUIRE(parse_terminal(LexicalIterator(s, 1)) ==
Terminal::Type::END_OF_FILE);
s = "\0,";
REQUIRE(parse_terminal(LexicalIterator(s, 1)) ==
Terminal::Type::END_OF_FILE);
s = "\0a";
REQUIRE(parse_terminal(LexicalIterator(s, 1)) ==
Terminal::Type::END_OF_FILE);
}
SECTION("Invalid Terminal") {
REQUIRE(parse_terminal("abc") == std::nullopt);
}
}
| 27.083333
| 62
| 0.635692
|
spiretrading
|
7254dab5c34ed42970c7312394b0ca3c4c543331
| 3,701
|
cpp
|
C++
|
Enemies/EnemyTank.cpp
|
JTuthill01/Hell-on-Treads
|
a89c939c3f1d0bd47d075d5b02d589637548ca31
|
[
"MIT"
] | null | null | null |
Enemies/EnemyTank.cpp
|
JTuthill01/Hell-on-Treads
|
a89c939c3f1d0bd47d075d5b02d589637548ca31
|
[
"MIT"
] | null | null | null |
Enemies/EnemyTank.cpp
|
JTuthill01/Hell-on-Treads
|
a89c939c3f1d0bd47d075d5b02d589637548ca31
|
[
"MIT"
] | null | null | null |
#include "stdafx.hpp"
#include "EnemyTank.hpp"
std::vector<sf::Texture> EnemyTank::mEnemyProjectileTextures;
EnemyTank::EnemyTank() : mShootTimer(mShootTimerMax), mShootTimerMax(50.F)
{
this->createMovementComponent(350.f, 16.f, 6.f);
this->createAnimationComponent(this->mEnemyTankTexture);
this->pAnimationComponent->addAnimation("MOVE", 5.f, 0, 0, 7, 0, 435, 435);
this->pAnimationComponent->addAnimation("ATTACK", 5.f, 0, 1, 7, 1, 435, 435);
this->pAudio.loadSound("Resources/Sounds/Explosions/explosion1.ogg");
this->pAudio.setVolume(10.F);
this->loadProjectile();
this->loadEnemyTanks();
}
EnemyTank::~EnemyTank() = default;
void EnemyTank::render(sf::RenderTarget& target)
{
target.draw(this->mEnemyTankSprite);
for (size_t i = 0; i < this->mProjectiles.size(); i++)
this->mProjectiles[i].render(target);
}
void EnemyTank::update(const float& deltaTime)
{
this->pMovementComponent->update(deltaTime);
this->updateAnimations(deltaTime);
this->mEnemyTankSprite.move(sf::Vector2f(-0.6F, 0.F));
for (size_t i = 0; i < this->mProjectiles.size(); i++)
this->mProjectiles[i].update(deltaTime);
}
void EnemyTank::move(const float direction_x, const float direction_y, const float& deltaTime)
{
if (this->pMovementComponent)
this->pMovementComponent->move(direction_x, direction_y, deltaTime);
}
void EnemyTank::updateAnimations(const float& deltaTime)
{
if (this->mIsAttacking)
{
if (this->mEnemyTankSprite.getScale().x > 0.f) //Facing left
this->mEnemyTankSprite.setOrigin(96.f, 0.f);
if (this->pAnimationComponent->play("ATTACK", deltaTime, true))
{
this->mIsAttacking = false;
this->mIsMuzzleOn = false;
if (this->mEnemyTankSprite.getScale().x > 0.f) //Facing left
this->mEnemyTankSprite.setOrigin(0.f, 0.f);
}
}
else if (this->pMovementComponent->getState(MOVING))
{
if (this->mEnemyTankSprite.getScale().x < 0.f)
{
this->mEnemyTankSprite.setOrigin(0.f, 0.f);
this->mEnemyTankSprite.setScale(1.f, 1.f);
}
this->pAnimationComponent->play("MOVE", deltaTime,
this->pMovementComponent->getVelocity().x,
this->pMovementComponent->getMaxVelocity());
}
else if (this->pMovementComponent->getState(MOVING))
{
if (this->mEnemyTankSprite.getScale().x < 0.f)
{
this->mEnemyTankSprite.setOrigin(140.f, 0.f);
this->mEnemyTankSprite.setScale(1.f, 1.f);
}
this->pAnimationComponent->play("MOVE", deltaTime,
this->pMovementComponent->getVelocity().x,
this->pMovementComponent->getMaxVelocity());
}
}
void EnemyTank::createMovementComponent(const float max_velocity, const float acceleration, const float deceleration)
{
this->pMovementComponent = new MovementComponent(this->mEnemyTankSprite, max_velocity, acceleration,
deceleration);
}
void EnemyTank::createAnimationComponent(sf::Texture& texture_sheet)
{
this->pAnimationComponent = new AnimationComponent(this->mEnemyTankSprite, texture_sheet);
}
void EnemyTank::loadEnemyTanks()
{
if (!this->mEnemyTankTexture.loadFromFile("Resources/Textures/Enemy/TankCombined.png"))
std::cerr << "Fucking EnemyTank failed to fucking load" << "\n";
this->mEnemyTankSprite.setTexture(this->mEnemyTankTexture);
this->mEnemyTankSprite.setPosition(1700.F, 710.F);
this->mEnemyTankSprite.setColor(sf::Color::Green);
}
void EnemyTank::loadProjectile()
{
sf::Texture temp;
if (!temp.loadFromFile("Resources/Textures/Bullets/Bomb_2.png"))
std::cerr << "Failed to fucking the fucking bomb texture" << "\n";
this->mEnemyProjectileTextures.push_back(temp);
}
void EnemyTank::updateAttack(const float& deltaTime)
{
}
| 28.689922
| 118
| 0.705755
|
JTuthill01
|
7257004ed1c670e39b57325874d884a14e951af7
| 12,376
|
cpp
|
C++
|
cpp/ast/LILRootNode.cpp
|
veosotano/lil
|
da2d0774615827d521362ffb731e8abfa3887507
|
[
"MIT"
] | 6
|
2021-01-02T16:36:28.000Z
|
2022-01-23T21:50:29.000Z
|
cpp/ast/LILRootNode.cpp
|
veosotano/lil
|
27ef338e7e21403acf2b0202f7db8ef662425d44
|
[
"MIT"
] | null | null | null |
cpp/ast/LILRootNode.cpp
|
veosotano/lil
|
27ef338e7e21403acf2b0202f7db8ef662425d44
|
[
"MIT"
] | null | null | null |
/********************************************************************
*
* LIL Is a Language
*
* AUTHORS: Miro Keller
*
* COPYRIGHT: ©2020-today: All Rights Reserved
*
* LICENSE: see LICENSE file
*
* This is a node that participates in local variables
*
********************************************************************/
#include "LILRootNode.h"
#include "LILAliasDecl.h"
#include "LILAssignment.h"
#include "LILClassDecl.h"
#include "LILConversionDecl.h"
#include "LILDocumentation.h"
#include "LILFunctionDecl.h"
#include "LILInstruction.h"
#include "LILNodeToString.h"
#include "LILRule.h"
#include "LILSelector.h"
#include "LILSelectorChain.h"
#include "LILSimpleSelector.h"
#include "LILSnippetInstruction.h"
#include "LILTypeDecl.h"
#include "LILVarDecl.h"
#include "LILVarName.h"
using namespace LIL;
LILRootNode::LILRootNode()
: LILVarNode(NodeTypeRoot)
{
}
LILRootNode::LILRootNode(const LILRootNode & other)
: LILVarNode(other)
, _localVars(other._localVars)
, _classes(other._classes)
, _aliases(other._aliases)
, _types(other._types)
, _conversions(other._conversions)
, _constants(other._constants)
, _snippets(other._snippets)
, _initializers(other._initializers)
, _docs(other._docs)
, _rules(other._rules)
, _config(other._config)
{
}
LILRootNode::~LILRootNode()
{
}
bool LILRootNode::isRootNode() const
{
return true;
}
const std::vector<std::shared_ptr<LILNode>> & LILRootNode::getNodes() const
{
return this->getChildNodes();
}
void LILRootNode::add(std::shared_ptr<LILNode> node, bool addToNodeTree)
{
switch (node->getNodeType()) {
case NodeTypeVarDecl:
{
auto vd = std::static_pointer_cast<LILVarDecl>(node);
auto ty = vd->getType();
if (
vd->getIsExtern()
|| vd->getIsExported()
|| vd->getIsConst()
) {
if (addToNodeTree) {
this->addNode(node);
}
//local variables on root are globals
this->setLocalVariable(vd->getName(), vd);
}
else if (ty && ty->isA(TypeTypeFunction))
{
if (addToNodeTree) {
this->addNode(node);
}
//local variables on root are globals
this->setLocalVariable(vd->getName(), node);
}
else
{
this->addEvaluable(node);
}
break;
}
case NodeTypeFunctionDecl:
{
auto fd = std::static_pointer_cast<LILFunctionDecl>(node);
auto fnTy = std::static_pointer_cast<LILFunctionType>(fd->getType());
if (!fnTy) {
std::cerr << "FN DECL HAD NO TY FAIL!!!!!!!!!!\n";
break;
}
for ( auto arg : fnTy->getArguments()) {
if (arg->isA(NodeTypeVarDecl)) {
auto argVd = std::static_pointer_cast<LILVarDecl>(arg);
fd->setLocalVariable(argVd->getName(), argVd);
}
}
if (addToNodeTree) {
this->addNode(fd);
}
this->setLocalVariable(fd->getName(), fd);
break;
}
case NodeTypeClassDecl:
{
if (addToNodeTree) {
this->addNode(node);
}
this->addClass(std::static_pointer_cast<LILClassDecl>(node));
break;
}
case NodeTypeAliasDecl:
{
if (addToNodeTree) {
this->addNode(node);
}
this->addAlias(std::static_pointer_cast<LILAliasDecl>(node));
break;
}
case NodeTypeTypeDecl:
{
if (addToNodeTree) {
this->addNode(node);
}
this->addType(std::static_pointer_cast<LILTypeDecl>(node));
break;
}
case NodeTypeConversionDecl:
{
if (addToNodeTree) {
this->addNode(node);
}
this->addConversion(std::static_pointer_cast<LILConversionDecl>(node));
break;
}
case NodeTypeInstruction:
{
auto instr = std::static_pointer_cast<LILInstruction>(node);
switch (instr->getInstructionType()) {
case InstructionTypeNone:
case InstructionTypeNew:
case InstructionTypeMove:
case InstructionTypeRGB:
case InstructionTypeRGBA:
case InstructionTypeRGBAA:
case InstructionTypeRRGGBB:
case InstructionTypeRRGGBBA:
case InstructionTypeRRGGBBAA:
case InstructionTypeGrayscale1:
case InstructionTypeGrayscale2:
case InstructionTypeDelete:
case InstructionTypeSnippet:
case InstructionTypeBug:
case InstructionTypeArg:
//do nothing
break;
case InstructionTypeIf:
case InstructionTypeNeeds:
case InstructionTypeImport:
case InstructionTypePaste:
case InstructionTypeGetConfig:
{
if (addToNodeTree) {
this->addNode(instr);
}
break;
}
case InstructionTypeConfigure:
{
if (addToNodeTree) {
this->addNode(instr);
}
this->addConfigureInstr(instr);
break;
}
case InstructionTypeExport:
{
for (auto instrNode : instr->getChildNodes()) {
this->add(instrNode);
}
break;
}
}
break;
}
case NodeTypeSnippetInstruction:
{
auto snInstr = std::static_pointer_cast<LILSnippetInstruction>(node);
this->addSnippet(snInstr);
if (addToNodeTree) {
this->addNode(node);
}
break;
}
case NodeTypeIfInstruction:
{
if (addToNodeTree) {
this->addNode(node);
}
break;
}
case NodeTypeForeignLang:
{
if (addToNodeTree) {
this->addNode(node);
}
break;
}
case NodeTypeDocumentation:
{
this->addDoc(std::static_pointer_cast<LILDocumentation>(node));
break;
}
case NodeTypeRule:
{
this->addRule(std::static_pointer_cast<LILRule>(node));
break;
}
default:
this->addEvaluable(node);
break;
}
}
void LILRootNode::clearNodes()
{
this->clearChildNodes();
this->_classes.clear();
this->_rules.clear();
this->_docs.clear();
this->_types.clear();
this->_aliases.clear();
this->_snippets.clear();
this->_config.clear();
this->_constants.clear();
this->_mainMenu.clear();
}
void LILRootNode::appendNodes(const std::vector<std::shared_ptr<LILNode>> & nodes)
{
this->_childNodes.insert(this->_childNodes.begin() + this->_childNodes.size(), nodes.begin(), nodes.end());
}
void LILRootNode::addClass(std::shared_ptr<LILClassDecl> value)
{
this->_classes.push_back(value);
}
const std::vector<std::shared_ptr<LILClassDecl>> & LILRootNode::getClasses() const
{
return this->_classes;
}
void LILRootNode::removeClass(std::shared_ptr<LILClassDecl> value)
{
auto it = std::find(this->_classes.begin(), this->_classes.end(), value);
if (it != this->_classes.end()) {
this->_classes.erase(it);
}
}
void LILRootNode::addAlias(std::shared_ptr<LILAliasDecl> value)
{
this->_aliases.push_back(value);
}
const std::vector<std::shared_ptr<LILAliasDecl>> & LILRootNode::getAliases() const
{
return this->_aliases;
}
void LILRootNode::addType(std::shared_ptr<LILTypeDecl> value)
{
this->_types.push_back(value);
}
const std::vector<std::shared_ptr<LILTypeDecl>> & LILRootNode::getTypes() const
{
return this->_types;
}
void LILRootNode::addConversion(std::shared_ptr<LILConversionDecl> value)
{
auto vd = value->getVarDecl();
if (!vd) {
std::cerr << "!!!!!! CONVERSION DECL HAD NO VAR DECL FAIL !!!!!!\n\n";
return;
}
auto fromTy = vd->getType();
if (!fromTy) {
std::cerr << "!!!!!! VAR DECL OF CONVERSION DECL HAD NO TYPE FAIL !!!!!!\n\n";
return;
}
auto fromTyName = LILNodeToString::stringify(fromTy.get());
auto toTy = value->getType();
if (!toTy) {
std::cerr << "!!!!!! CONVERSION DECL HAD NO TARGET TYPE FAIL !!!!!!\n\n";
return;
}
auto toTyName = LILNodeToString::stringify(toTy.get());
this->_conversions[fromTyName+"_to_"+toTyName] = value;
}
const std::map<LILString, std::shared_ptr<LILConversionDecl>> & LILRootNode::getConversions() const
{
return this->_conversions;
}
std::shared_ptr<LILConversionDecl> LILRootNode::getConversionNamed(LILString name)
{
if (this->_conversions.count(name)) {
return this->_conversions[name];
}
return nullptr;
}
const std::map<LILString, std::shared_ptr<LILSnippetInstruction>> & LILRootNode::getSnippets() const
{
return this->_snippets;
}
std::shared_ptr<LILSnippetInstruction> LILRootNode::getSnippetNamed(LILString key)
{
if (this->_snippets.count(key)) {
return this->_snippets.at(key);
}
return nullptr;
}
void LILRootNode::addSnippet(std::shared_ptr<LILSnippetInstruction> snippet)
{
this->_snippets[snippet->getName()] = snippet;
}
void LILRootNode::addEvaluable(std::shared_ptr<LILNode> node)
{
this->_initializers.push_back(node);
}
bool LILRootNode::hasInitializers() const
{
return this->_initializers.size() > 0;
}
const std::vector<std::shared_ptr<LILNode>> & LILRootNode::getInitializers() const
{
return this->_initializers;
}
void LILRootNode::clearInitializers()
{
this->_initializers.clear();
}
void LILRootNode::addDoc(std::shared_ptr<LILDocumentation> value)
{
this->addNode(value);
this->_docs.push_back(value);
}
const std::vector<std::shared_ptr<LILDocumentation>> & LILRootNode::getDocs() const
{
return this->_docs;
}
bool LILRootNode::hasRules() const
{
return this->_rules.size() > 0;
}
void LILRootNode::addRule(std::shared_ptr<LILRule> value)
{
const auto & selChNode = value->getSelectorChain();
if (selChNode && selChNode->getNodeType() == NodeTypeSelectorChain) {
const auto & selCh = std::static_pointer_cast<LILSelectorChain>(selChNode);
const auto & selChNodes = selCh->getNodes();
if (selChNodes.size() == 1) {
const auto & simpleSel = std::static_pointer_cast<LILSimpleSelector>(selChNodes.front());
const auto & simpleSelNodes = simpleSel->getNodes();
if (simpleSelNodes.size() == 1) {
const auto & sel = std::static_pointer_cast<LILSelector>(simpleSelNodes.front());
if (sel->isA(SelectorTypeMainMenu)) {
this->addNode(value);
for (auto childRule : value->getChildRules()) {
this->_mainMenu.push_back(childRule);
}
return;
}
}
}
}
this->addNode(value);
this->_rules.push_back(value);
}
const std::vector<std::shared_ptr<LILRule>> & LILRootNode::getRules() const
{
return this->_rules;
}
bool LILRootNode::hasMainMenu() const
{
return this->_mainMenu.size() > 0;
}
const std::vector<std::shared_ptr<LILNode>> & LILRootNode::getMainMenuItems() const
{
return this->_mainMenu;
}
void LILRootNode::clearMainMenuItems()
{
this->_mainMenu.clear();
}
void LILRootNode::addConfigureInstr(const std::shared_ptr<LILInstruction> & instr)
{
this->_config.push_back(instr);
}
const std::vector<std::shared_ptr<LILNode>> & LILRootNode::getConfigure() const
{
return this->_config;
}
| 27.380531
| 111
| 0.563995
|
veosotano
|
725c845dc80289814cd01786bf1351fed338c375
| 270
|
cpp
|
C++
|
with_python/extensions/pickling/main.cpp
|
MengqiYe/Test_Cpp_Standards
|
3acf52bd4457be007534b2b481f01a3bdfda0813
|
[
"MIT"
] | null | null | null |
with_python/extensions/pickling/main.cpp
|
MengqiYe/Test_Cpp_Standards
|
3acf52bd4457be007534b2b481f01a3bdfda0813
|
[
"MIT"
] | null | null | null |
with_python/extensions/pickling/main.cpp
|
MengqiYe/Test_Cpp_Standards
|
3acf52bd4457be007534b2b481f01a3bdfda0813
|
[
"MIT"
] | null | null | null |
//
// Created by mqye on 2020/12/7.
//
#include "p.h"
namespace py = pybind11;
int main() {
std::vector<float> float_vector;
float_vector.push_back(.1);
float_vector.push_back(.2);
float_vector.push_back(.3);
auto a_tuple = py::make_tuple(float_vector);
}
| 15.882353
| 46
| 0.681481
|
MengqiYe
|
725fa44d04ba00d9e9cf81419465ba9ff93feb8d
| 1,985
|
hpp
|
C++
|
shadow/algorithm/detect_mtcnn.hpp
|
junluan/shadow
|
067d1c51d7c38bc1c985008a2e2e1599bbf11a8c
|
[
"Apache-2.0"
] | 20
|
2017-07-04T11:22:47.000Z
|
2022-01-16T03:58:32.000Z
|
shadow/algorithm/detect_mtcnn.hpp
|
junluan/shadow
|
067d1c51d7c38bc1c985008a2e2e1599bbf11a8c
|
[
"Apache-2.0"
] | 2
|
2017-12-03T13:07:39.000Z
|
2021-01-13T11:11:52.000Z
|
shadow/algorithm/detect_mtcnn.hpp
|
junluan/shadow
|
067d1c51d7c38bc1c985008a2e2e1599bbf11a8c
|
[
"Apache-2.0"
] | 10
|
2017-09-30T05:06:30.000Z
|
2020-11-13T05:43:44.000Z
|
#ifndef SHADOW_ALGORITHM_DETECT_MTCNN_HPP_
#define SHADOW_ALGORITHM_DETECT_MTCNN_HPP_
#include "method.hpp"
#include "core/network.hpp"
namespace Shadow {
struct BoxInfo {
BoxF box;
float box_reg[4], landmark[10];
};
using VecBoxInfo = std::vector<BoxInfo>;
class DetectMTCNN final : public Method {
public:
DetectMTCNN() = default;
void Setup(const std::string& model_file) override;
void Predict(const cv::Mat& im_mat, const RectF& roi, VecBoxF* boxes,
std::vector<VecPointF>* Gpoints) override;
private:
void Process_net_p(const float* data, const VecInt& in_shape, float threshold,
float scale, VecBoxInfo* boxes);
void Process_net_r(const float* data, const VecInt& in_shape, float threshold,
const VecBoxInfo& net_12_boxes, VecBoxInfo* boxes);
void Process_net_o(const float* data, const VecInt& in_shape, float threshold,
const VecBoxInfo& net_24_boxes, VecBoxInfo* boxes);
void CalculateScales(float height, float width, float factor, float max_side,
float min_side, VecFloat* scales);
void BoxRegression(VecBoxInfo& boxes);
void Box2SquareWithConstrain(VecBoxInfo& boxes, float height, float width);
void BoxWithConstrain(VecBoxInfo& boxes, float height, float width);
Network net_p_, net_r_, net_o_;
VecFloat net_p_in_data_, net_r_in_data_, net_o_in_data_, thresholds_, scales_;
VecInt net_p_in_shape_, net_r_in_shape_, net_o_in_shape_;
VecBoxInfo net_p_boxes_, net_r_boxes_, net_o_boxes_;
std::string in_p_str_, in_r_str_, in_o_str_, net_p_conv4_2_, net_p_prob1_,
net_r_conv5_2_, net_r_prob1_, net_o_conv6_2_, net_o_conv6_3_,
net_o_prob1_;
int net_p_stride_, net_p_cell_size_;
int net_r_in_c_, net_r_in_h_, net_r_in_w_, net_r_in_num_;
int net_o_in_c_, net_o_in_h_, net_o_in_w_, net_o_in_num_;
float factor_, max_side_, min_side_;
};
} // namespace Shadow
#endif // SHADOW_ALGORITHM_DETECT_MTCNN_HPP_
| 34.224138
| 80
| 0.741058
|
junluan
|
726927b926bc4174acea00bd8f90d18b7fb02ad8
| 4,669
|
cpp
|
C++
|
common/src/keyfile/LicenceeInfo.cpp
|
waddlesplash/WonderBrush-v2
|
df20b6a43115d02e4606c71f27d0712ac2aebb62
|
[
"MIT"
] | null | null | null |
common/src/keyfile/LicenceeInfo.cpp
|
waddlesplash/WonderBrush-v2
|
df20b6a43115d02e4606c71f27d0712ac2aebb62
|
[
"MIT"
] | null | null | null |
common/src/keyfile/LicenceeInfo.cpp
|
waddlesplash/WonderBrush-v2
|
df20b6a43115d02e4606c71f27d0712ac2aebb62
|
[
"MIT"
] | null | null | null |
// LicenceeInfo.cpp
#include <cstdio>
#include <Message.h>
#include "TimeSupport.h"
#include "LicenceeInfo.h"
// constants for default values
const char* const kDefaultName = "no name";
const char* const kDefaultApplicationID = "no application";
const uint32 kDefaultApplicationVersion = 0;
const bigtime_t kDefaultRegistrationTime = 0;
const bigtime_t kDefaultExpirationTime = 0;
const int32 kDefaultLicenseType = 0;
// constructor
LicenceeInfo::LicenceeInfo()
: fName(kDefaultName),
fApplicationID(kDefaultApplicationID),
fApplicationVersion(kDefaultApplicationVersion),
fRegistrationTime(kDefaultRegistrationTime),
fExpirationTime(kDefaultExpirationTime),
fLicenseType(kDefaultLicenseType)
{
}
// unarchiving constructor
LicenceeInfo::LicenceeInfo(BMessage* archive)
: fName(kDefaultName),
fApplicationID(kDefaultApplicationID),
fApplicationVersion(kDefaultApplicationVersion),
fRegistrationTime(kDefaultRegistrationTime),
fExpirationTime(kDefaultExpirationTime),
fLicenseType(kDefaultLicenseType)
{
archive->FindString("MyClass::Name", &fName);
archive->FindString("MyClass::ApplicationID", &fApplicationID);
archive->FindInt32("MyClass::ApplicationVersion",
(int32*)&fApplicationVersion);
archive->FindInt64("MyClass::RegistrationTime", &fRegistrationTime);
archive->FindInt64("MyClass::ExpirationTime", &fExpirationTime);
archive->FindInt32("MyClass::LicenseType", &fLicenseType);
}
// destructor
LicenceeInfo::~LicenceeInfo()
{
}
// SetName
void
LicenceeInfo::SetName(const char* name)
{
fName = name;
}
// GetName
const char*
LicenceeInfo::GetName() const
{
return fName.String();
}
// SetApplicationID
void
LicenceeInfo::SetApplicationID(const char* id)
{
fApplicationID = id;
}
// GetApplicationID
const char*
LicenceeInfo::GetApplicationID() const
{
return fApplicationID.String();
}
// SetApplicationVersion
void
LicenceeInfo::SetApplicationVersion(uint32 version)
{
fApplicationVersion = version;
}
// GetApplicationVersion
uint32
LicenceeInfo::GetApplicationVersion() const
{
return fApplicationVersion;
}
// SetRegistrationTime
void
LicenceeInfo::SetRegistrationTime(bigtime_t time)
{
fRegistrationTime = time;
}
// GetRegistrationTime
bigtime_t
LicenceeInfo::GetRegistrationTime() const
{
return fRegistrationTime;
}
// SetExpirationTime
void
LicenceeInfo::SetExpirationTime(bigtime_t time)
{
fExpirationTime = time;
}
// GetExpirationTime
bigtime_t
LicenceeInfo::GetExpirationTime() const
{
return fExpirationTime;
}
// SetLicenseType
void
LicenceeInfo::SetLicenseType(int32 type)
{
fLicenseType = type;
}
// GetLicenseType
int32
LicenceeInfo::GetLicenseType() const
{
return fLicenseType;
}
// PrintToStream
void
LicenceeInfo::PrintToStream() const
{
printf("LicenceeInfo:\n");
printf(" name : `%s'\n", GetName());
printf(" application ID : `%s'\n", GetApplicationID());
printf(" application version: %lu\n", GetApplicationVersion());
// printf(" registration time : %Ld\n", GetRegistrationTime());
// printf(" expiration time : %Ld\n", GetExpirationTime());
printf(" registration time : ");
print_time(GetRegistrationTime());
printf("\n");
printf(" expiration time : ");
print_time(GetExpirationTime());
printf("\n");
const char* licenseString = "unknown";
int32 licenseType = GetLicenseType();
switch (licenseType) {
case LICENSE_STUDENT:
licenseString = "noncommercial, student";
break;
case LICENSE_COMMERCIAL_SINGLE:
licenseString = "commercial, single user";
break;
case LICENSE_COMMERCIAL_MULTI:
licenseString = "commercial, multiple users";
break;
default:
break;
}
printf(" license type : %ld (%s)\n", licenseType, licenseString);
}
// Archive
status_t
LicenceeInfo::Archive(BMessage* archive, bool deep) const
{
status_t error = B_OK;
error = BArchivable::Archive(archive, deep);
if (error == B_OK)
error = archive->AddString("MyClass::Name", fName);
if (error == B_OK)
error = archive->AddString("MyClass::ApplicationID", fApplicationID);
if (error == B_OK) {
error = archive->AddInt32("MyClass::ApplicationVersion",
fApplicationVersion);
}
if (error == B_OK) {
error = archive->AddInt64("MyClass::RegistrationTime",
fRegistrationTime);
}
if (error == B_OK)
error = archive->AddInt64("MyClass::ExpirationTime", fExpirationTime);
if (error == B_OK)
error = archive->AddInt32("MyClass::LicenseType", fLicenseType);
return error;
}
// Instantiate
_EXPORT
BArchivable*
LicenceeInfo::Instantiate(BMessage* archive)
{
if (!validate_instantiation(archive, "LicenceeInfo"))
return NULL;
return new LicenceeInfo(archive);
}
| 22.665049
| 73
| 0.74063
|
waddlesplash
|
7269f9fc8966cc916d265529063cd86484078d22
| 1,499
|
hpp
|
C++
|
src/rdf4cpp/rdf/storage/node/BackendNodeHandle.hpp
|
rdf4cpp/rdf4cpp
|
559bf3742871fdf5c2f9dad634193f97e1198c9b
|
[
"MIT"
] | 3
|
2022-01-10T10:35:44.000Z
|
2022-02-18T00:38:38.000Z
|
src/rdf4cpp/rdf/storage/node/BackendNodeHandle.hpp
|
rdf4cpp/rdf4cpp
|
559bf3742871fdf5c2f9dad634193f97e1198c9b
|
[
"MIT"
] | 8
|
2021-06-06T17:45:14.000Z
|
2022-02-06T17:45:45.000Z
|
src/rdf4cpp/rdf/storage/node/BackendNodeHandle.hpp
|
rdf4cpp/rdf4cpp
|
559bf3742871fdf5c2f9dad634193f97e1198c9b
|
[
"MIT"
] | 4
|
2021-09-16T12:49:09.000Z
|
2022-02-18T01:58:57.000Z
|
#ifndef RDF4CPP_BACKENDNODEHANDLE_HPP
#define RDF4CPP_BACKENDNODEHANDLE_HPP
#include <rdf4cpp/rdf/storage/node/NodeStorage.hpp>
#include <compare>
#include <cstddef>
namespace rdf4cpp::rdf::storage::node {
class BackendNodeHandle {
NodeID node_id_;
public:
BackendNodeHandle() = default;
explicit BackendNodeHandle(NodeID node_id);
[[nodiscard]] RDFNodeType type() const noexcept;
[[nodiscard]] bool is_iri() const noexcept;
[[nodiscard]] bool is_literal() const noexcept;
[[nodiscard]] bool is_blank_node() const noexcept;
[[nodiscard]] bool is_variable() const noexcept;
[[nodiscard]] bool empty() const noexcept;
[[nodiscard]] NodeStorage node_storage() const;
[[nodiscard]] NodeID id() const noexcept;
[[nodiscard]] IRIBackend &iri_backend() const;
[[nodiscard]] LiteralBackend &literal_backend() const;
[[nodiscard]] BNodeBackend &bnode_backend() const;
[[nodiscard]] VariableBackend &variable_backend() const;
bool operator==(const BackendNodeHandle &other) const = default;
auto operator<=>(const BackendNodeHandle &other) const = default;
// TODO: support value retrieval from basic XSD datatypes
};
} // namespace rdf4cpp::rdf::storage::node
template<>
struct std::hash<rdf4cpp::rdf::storage::node::BackendNodeHandle> {
inline size_t operator()(rdf4cpp::rdf::storage::node::BackendNodeHandle const &v) const noexcept {
return v.id().raw();
}
};
#endif //RDF4CPP_BACKENDNODEHANDLE_HPP
| 28.826923
| 102
| 0.717145
|
rdf4cpp
|
726c2b7c94a78617c6f2d8025c5a0acc3f44059c
| 1,214
|
cpp
|
C++
|
test/widgets/form.cpp
|
mattwood-microchip/egt
|
6cf491008684feb200585ad1e323a9a02085d9bf
|
[
"Apache-2.0"
] | 36
|
2019-08-06T06:29:18.000Z
|
2022-03-31T09:26:28.000Z
|
test/widgets/form.cpp
|
mattwood-microchip/egt
|
6cf491008684feb200585ad1e323a9a02085d9bf
|
[
"Apache-2.0"
] | 19
|
2019-12-06T00:25:35.000Z
|
2022-03-28T00:22:27.000Z
|
test/widgets/form.cpp
|
mattwood-microchip/egt
|
6cf491008684feb200585ad1e323a9a02085d9bf
|
[
"Apache-2.0"
] | 14
|
2019-08-09T07:23:25.000Z
|
2021-09-22T20:08:12.000Z
|
/*
* Copyright (C) 2018 Microchip Technology Inc. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <egt/ui>
#include <gtest/gtest.h>
using ::testing::Combine;
using ::testing::TestWithParam;
using ::testing::Values;
using ::testing::Range;
class FormTest : public testing::TestWithParam<int> {};
TEST_P(FormTest, TestWidget)
{
egt::Application app;
egt::TopWindow win;
egt::Frame frame;
std::shared_ptr<egt::experimental::Form> widget;
int type = GetParam();
if (type == 0)
{
EXPECT_NO_THROW(widget.reset(new egt::experimental::Form("Form Title ")));
EXPECT_NO_THROW(win.add(expand(widget)));
}
else if (type == 1)
{
EXPECT_NO_THROW(widget.reset(new egt::experimental::Form(frame, "Form Title ")));
}
widget->add_group("Group Tiltle");
for (int i = 0; i < 5; i++)
{
auto text1 = std::make_shared<egt::TextBox>("textBox " + std::to_string(i));
widget->add_option(text1);
widget->group_align(egt::AlignFlag::center);
widget->name_align(egt::AlignFlag::right);
widget->remove_options();
}
}
INSTANTIATE_TEST_SUITE_P(FormTestGroup, FormTest, Values(0, 1));
| 25.291667
| 89
| 0.640033
|
mattwood-microchip
|
726dc1830a34c721af79b6dbd64d07966894f077
| 2,830
|
hpp
|
C++
|
node_modules/node-lemmer/include/turglem/morph_compiler.hpp
|
noduslabs/un1v3r53
|
7684f57721dc16b01f4776f37301e0e1913b60ba
|
[
"MIT"
] | 2
|
2019-04-17T04:41:00.000Z
|
2021-04-01T15:37:04.000Z
|
node_modules/node-lemmer/include/turglem/morph_compiler.hpp
|
noduslabs/un1v3r53
|
7684f57721dc16b01f4776f37301e0e1913b60ba
|
[
"MIT"
] | null | null | null |
node_modules/node-lemmer/include/turglem/morph_compiler.hpp
|
noduslabs/un1v3r53
|
7684f57721dc16b01f4776f37301e0e1913b60ba
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2007, libturglem development team.
*
* This file is released under the LGPL.
*/
#ifndef __MORPH_COMPILER___
#define __MORPH_COMPILER___
#include <txml/txml.hpp>
#include <MAFSA/daciuk.hpp>
namespace MAFSA
{
typedef std::basic_string<MAFSA_letter> l_string;
}
namespace turglem
{
template<typename _ABC>
class morph_compiler
{
struct paradigms_xml_loader : public txml::determination_object
{
struct ROOT : public txml::determination_object
{
struct PARADIGM : public txml::determination_object
{
struct FORM : public txml::determination_object
{
std::string prefix;
std::string suffix;
u_int32_t pos;
u_int64_t grammem;
u_int32_t id;
void determine(txml::parser *parser)
{
parser->determineMember("s", suffix);
parser->determineMember("ps", pos);
parser->determineMember("g", grammem);
parser->determineMember("p", prefix);
parser->determineMember("id", id);
}
};
std::vector<FORM> forms;
void determine(txml::parser *parser)
{
parser->determineMember("f", forms);
}
};
std::vector<PARADIGM> paradigms;
void determine(txml::parser *parser)
{
parser->determineMember("paradigm", paradigms);
}
};
ROOT root;
void determine(txml::parser *parser)
{
parser->determineMember("paradigms", root);
}
} paradigms_loader;
struct lemmas_xml_loader : public txml::determination_object
{
struct ROOT : public txml::determination_object
{
struct LEMMA : public txml::determination_object
{
std::string word;
std::string prefix;
u_int32_t idx;
void determine(txml::parser *parser)
{
std::string tmp;
parser->determineMember("id", word);
parser->determineMember("p", idx);
parser->determineMember("prefix", prefix);
}
};
std::vector<LEMMA> ls;
void determine(txml::parser *parser)
{
parser->determineMember("l", ls);
}
};
ROOT root;
void determine(txml::parser *parser)
{
parser->determineMember("lemmas", root);
}
} lemmas_loader;
std::map<MAFSA::l_string, std::map<std::pair<uint, uint>, uint> > prediction_data;
void process_stat_data();
void add_stats(const MAFSA::l_string& s, uint flex, uint form, uint max_pref_suf_len);
void save_prediction_dict(const char * predict_out);
void save_main_dict(const char * dict_out);
public:
bool load_and_convert_paradigms(const char * xml_source, const char * bin_out);
bool load_lemmas(const char * xml_source);
//if predict_out == 0 then prediction dict is not generated
bool process_and_save_dicts(const char * dict_out, const char * predict_out);
};
#include <turglem/morph_compiler.tcc>
} // namespace turglem
#endif //__MORPH_COMPILER___
| 21.278195
| 87
| 0.671025
|
noduslabs
|
726f0fc9a56bfd2cfa2b5de400c7489d4451af3e
| 626
|
hpp
|
C++
|
include/threepp/lights/light_interfaces.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
include/threepp/lights/light_interfaces.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
include/threepp/lights/light_interfaces.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
#ifndef THREEPP_LIGHT_INTERFACES_HPP
#define THREEPP_LIGHT_INTERFACES_HPP
#include "LightShadow.hpp"
namespace threepp {
template <class LightShadowType>
class LightWithShadow {
public:
std::shared_ptr<LightShadowType> shadow;
virtual ~LightWithShadow() = default;
protected:
explicit LightWithShadow(const std::shared_ptr<LightShadowType> &shadow) : shadow(shadow) {}
};
class LightWithTarget {
public:
std::shared_ptr<Object3D> target{Object3D::create()};
virtual ~LightWithTarget() = default;
};
}
#endif//THREEPP_LIGHT_INTERFACES_HPP
| 17.388889
| 100
| 0.693291
|
maidamai0
|
727f7dd484bf398f797c732ccc6ae43ed8ec1ccb
| 1,680
|
cpp
|
C++
|
PPP/drill8/drill82.cpp
|
siddheshpai/hello-world
|
291456962d46c6ce857d75be86bc23634625925f
|
[
"Apache-2.0"
] | null | null | null |
PPP/drill8/drill82.cpp
|
siddheshpai/hello-world
|
291456962d46c6ce857d75be86bc23634625925f
|
[
"Apache-2.0"
] | null | null | null |
PPP/drill8/drill82.cpp
|
siddheshpai/hello-world
|
291456962d46c6ce857d75be86bc23634625925f
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
void swap_v(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
return;
}
void swap_r(int & a, int & b)
{
int temp;
temp = a;
a = b;
b = temp;
return;
}
/* This will not compile since we are trying to change constant references
void swap_cr(const int & a, const int & b)
{
int temp;
temp = a;
a = b;
b = temp;
return;
}
*/
int main()
{
int x = 7, y = 9;
swap_v(x, y);
cout << "After swap_v(), x is : " << x << " and y is : " << y << endl;
swap_r(x, y);
cout << "After swap_r(), x is : " << x << " and y is : " << y << endl;
//swap_cr(x, y);
//cout << "After swap_cr(), x is : " << x << " and y is : " << y << endl;
swap_v(7, 9);
cout << "After swap_v(), x is : " << x << " and y is : " << y << endl;
//swap_r(7, 9); //Will not compile due to literals being passed to (references to variables)
//cout << "After swap_r(), x is : " << x << " and y is : " << y << endl;
//swap_cr(7, 9);
//cout << "After swap_cr(), x is : " << x << " and y is : " << y << endl;
const int cx = 7, cy = 9;
swap_v(cx, cy);
cout << "After swap_v(), cx is : " << cx << " and cy is : " << cy << endl;
//Will not compile since "binding reference of type ‘int&’ to ‘const int’ discards qualifiers"
//swap_r(cx, cy);
//cout << "After swap_r(), cx is : " << cx << " and cy is : " << cy << endl;
double dx = 7.7, dy = 9.9;
swap_v(dx, dy);
cout << "After swap_v(), dx is : " << dx << " and dy is : " << dy << endl;
//Will not compile since we are trying to set reference of int to double
//swap_r(dx, dy);
//cout << "After swap_r(), dx is : " << dx << " and dy is : " << dy << endl;
return 0;
}
| 22.4
| 95
| 0.523214
|
siddheshpai
|
72810e77c91b08e79a4f0165c72a1f1ae8c4102f
| 3,231
|
cxx
|
C++
|
src/atxmega256a3u/device.cxx
|
DX-MON/dragonUSB
|
e3b43d786f767577822ba5e777d01328cd92a80d
|
[
"BSD-3-Clause"
] | 4
|
2021-06-20T02:20:03.000Z
|
2021-12-30T01:43:02.000Z
|
src/atxmega256a3u/device.cxx
|
DX-MON/dragonUSB
|
e3b43d786f767577822ba5e777d01328cd92a80d
|
[
"BSD-3-Clause"
] | null | null | null |
src/atxmega256a3u/device.cxx
|
DX-MON/dragonUSB
|
e3b43d786f767577822ba5e777d01328cd92a80d
|
[
"BSD-3-Clause"
] | null | null | null |
// SPDX-License-Identifier: BSD-3-Clause
#include "usb/platform.hxx"
#include "usb/internal/core.hxx"
#include "usb/platforms/atxmega256a3u/core.hxx"
#include "usb/internal/device.hxx"
using namespace usb::constants;
using namespace usb::types;
using namespace usb::core;
using namespace usb::core::internal;
using namespace usb::descriptors;
using namespace usb::device::internal;
namespace usb::device
{
namespace endpoint
{
uint8_t mapType(const usbEndpointType_t type)
{
switch (type)
{
case usbEndpointType_t::isochronous:
return USB_EP_TYPE_ISOCHRONOUS_gc;
case usbEndpointType_t::control:
return USB_EP_TYPE_CONTROL_gc;
default:
break;
}
return USB_EP_TYPE_BULK_gc;
}
uint8_t mapMaxSize(const uint16_t size)
{
if (size <= 8)
return USB_EP_BUFSIZE_8_gc;
else if (size <= 16)
return USB_EP_BUFSIZE_16_gc;
else if (size <= 32)
return USB_EP_BUFSIZE_32_gc;
else if (size <= 64)
return USB_EP_BUFSIZE_64_gc;
// This should never happen..
return USB_EP_BUFSIZE_1023_gc;
}
} // namespace endpoint
void setupEndpoint(const usbEndpointDescriptor_t &endpoint)
{
if (endpoint.endpointType == usbEndpointType_t::control)
return;
const auto direction{static_cast<endpointDir_t>(endpoint.endpointAddress & ~usb::descriptors::endpointDirMask)};
const auto endpointNumber{uint8_t(endpoint.endpointAddress & usb::descriptors::endpointDirMask)};
auto &epCtrl
{
[direction](endpointCtrl_t &endpointCtrl) -> USB_EP_t &
{
if (direction == endpointDir_t::controllerIn)
return endpointCtrl.controllerIn;
else
return endpointCtrl.controllerOut;
}(endpoints[endpointNumber])
};
epCtrl.CNT = 0;
epCtrl.CTRL = endpoint::mapType(endpoint.endpointType) | endpoint::mapMaxSize(endpoint.maxPacketSize);
}
namespace internal
{
bool handleSetConfiguration() noexcept
{
usb::core::resetEPs(epReset_t::user);
usb::core::deinitHandlers();
const auto config{packet.value.asConfiguration()};
if (config > configsCount)
return false;
activeConfig = config;
if (activeConfig == 0)
usbState = deviceState_t::addressed;
else
{
const auto descriptors{*configDescriptors[activeConfig - 1U]};
for (const auto &part : descriptors)
{
flash_t<char *> descriptor{static_cast<const char *>(part.descriptor)};
usbDescriptor_t type{static_cast<usbDescriptor_t>(descriptor[1])};
if (type == usbDescriptor_t::endpoint)
{
const auto endpoint{*flash_t<usbEndpointDescriptor_t *>(part.descriptor)};
setupEndpoint(endpoint);
}
}
usb::core::initHandlers();
}
return true;
}
} // namespace internal
void handleControlPacket() noexcept
{
// If we received a packet..
if (usbPacket.dir() == endpointDir_t::controllerOut)
{
const auto status{endpoints[0].controllerOut.STATUS};
if (status & vals::usb::usbEPStatusSetupComplete)
USB.INTFLAGSBCLR = vals::usb::itrStatusSetup;
if (usbCtrlState == ctrlState_t::idle)
handleSetupPacket();
else
handleControllerOutPacket();
}
else
{
handleControllerInPacket();
endpoints[0].controllerIn.STATUS &= uint8_t(~vals::usb::usbEPStatusIOComplete);
}
}
} // namespace usb::device
| 26.483607
| 114
| 0.717425
|
DX-MON
|
7284539a6a216c96d9fa222abb84fce41f73cd2d
| 6,285
|
cpp
|
C++
|
guacservice/src/GuacLogger.cpp
|
ofiriluz/guacamole-server-windows
|
6f0230f3053e13536433bbd5fb728c248bab41fd
|
[
"Apache-2.0"
] | 2
|
2020-10-27T03:50:42.000Z
|
2022-01-14T06:01:40.000Z
|
guacservice/src/GuacLogger.cpp
|
ofiriluz/guacamole-server-windows
|
6f0230f3053e13536433bbd5fb728c248bab41fd
|
[
"Apache-2.0"
] | 2
|
2018-10-12T15:45:24.000Z
|
2020-06-16T10:08:26.000Z
|
guacservice/src/GuacLogger.cpp
|
ofiriluz/guacamole-server-windows
|
6f0230f3053e13536433bbd5fb728c248bab41fd
|
[
"Apache-2.0"
] | 2
|
2021-05-21T11:53:43.000Z
|
2021-11-07T18:36:32.000Z
|
//
// Created by oiluz on 9/5/2017.
//
#include <guacservice/GuacLogger.h>
GuacLogger::GuacLogger() : m_Initialized(false), m_IgnoreLogs(false), m_WithConsole(false)
{
}
boost::shared_ptr<GuacLogger> GuacLogger::GetInstance()
{
static boost::shared_ptr<GuacLogger> logger(new GuacLogger());
return logger;
}
void GuacLogger::SetConsoleColorBySeverity(boost::log::trivial::severity_level eLevel)
{
#ifdef WIN32
WORD color;
switch (eLevel)
{
case boost::log::trivial::trace:
color = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
break;
case boost::log::trivial::debug:
color = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
break;
case boost::log::trivial::info:
color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
break;
case boost::log::trivial::warning:
color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
break;
case boost::log::trivial::error:
color = FOREGROUND_RED | FOREGROUND_INTENSITY;
break;
case boost::log::trivial::fatal:
color = FOREGROUND_RED | FOREGROUND_INTENSITY;
break;
default:
color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
break;
}
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsole, &m_ConsoleInfo);
SetConsoleTextAttribute(hConsole, color);
#elif defined __linux__
switch (eLevel)
{
case boost::log::trivial::trace:
case boost::log::trivial::debug:
std::cout << "\e[39m";
case boost::log::trivial::info:
std::cout << "\e[34m";
break;
case boost::log::trivial::warning:
std::cout << "\e[33m";
break;
case boost::log::trivial::error:
case boost::log::trivial::fatal:
std::cout << "\e[31m";
break;
default:
break;
}
#endif
}
void GuacLogger::ClearConsoleColor()
{
#ifdef WIN32
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, m_ConsoleInfo.wAttributes);
#elif defined __linux__
std::cout << "\e[39m";
#endif
}
void GuacLogger::InitializeLog(const std::string & stLogFolder, const std::string & stLogFilePrefix,
boost::log::trivial::severity_level eMaxSeverityLevel, bool bWithConsoleOutput,
bool bWithFileOutput)
{
try
{
// Create log folder if does not exist and with file output
if (!boost::filesystem::exists(boost::filesystem::path(stLogFolder)) && bWithFileOutput)
{
boost::system::error_code ec;
boost::filesystem::create_directories(boost::filesystem::path(stLogFolder), ec);
if (ec)
{
bWithFileOutput = false;
}
}
// Add common attributes to the log and set its max log level
boost::log::add_common_attributes();
boost::log::core::get()->set_filter(boost::log::trivial::severity >= eMaxSeverityLevel);
// Create the formatters
auto fmtTimeStamp = boost::log::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp",
"%Y-%m-%d %H:%M:%S.%f");
auto fmtProcessId = boost::log::expressions::attr<boost::log::attributes::current_process_id::value_type>(
"ProcessID");
auto fmtThreadId = boost::log::expressions::attr<boost::log::attributes::current_thread_id::value_type>("ThreadID");
auto fmtSeverity = boost::log::expressions::attr<boost::log::trivial::severity_level>("Severity");
boost::log::formatter logFmt =
boost::log::expressions::format("[%1%] [%2%(%3%)] [%4%] => %5%")
% fmtTimeStamp % fmtProcessId % fmtThreadId % fmtSeverity
% boost::log::expressions::smessage;
// Add console sink if needed
if (bWithConsoleOutput)
{
auto consoleSink = boost::log::add_console_log(std::clog);
consoleSink->set_formatter(logFmt);
}
// Add File sink
if (bWithFileOutput)
{
auto fsSink = boost::log::add_file_log(
boost::log::keywords::file_name = stLogFolder + "/" + stLogFilePrefix + "_%Y-%m-%d_%H-%M-%S.%N.log",
boost::log::keywords::rotation_size = 10 * 1024 * 1024,
boost::log::keywords::min_free_space = 30 * 1024 * 1024,
boost::log::keywords::open_mode = std::ios_base::app,
boost::log::keywords::auto_flush = true);
fsSink->set_formatter(logFmt);
}
m_Initialized = true;
m_WithConsole = bWithConsoleOutput;
m_IgnoreLogs = !(bWithConsoleOutput || bWithFileOutput);
}
catch (...)
{
m_Initialized = false;
}
}
void GuacLogger::LogMessage(const std::string & stMessage, boost::log::trivial::severity_level eLevel)
{
if(!m_Initialized || m_IgnoreLogs)
{
return;
}
try
{
// Set the console color if with console
if (m_WithConsole)
{
SetConsoleColorBySeverity(eLevel);
}
// Write log depending on the severity type
switch(eLevel)
{
case boost::log::trivial::trace:
BOOST_LOG_TRIVIAL(trace) << stMessage;
break;
case boost::log::trivial::debug:
BOOST_LOG_TRIVIAL(debug) << stMessage;
break;
case boost::log::trivial::info:
BOOST_LOG_TRIVIAL(info) << stMessage;
break;
case boost::log::trivial::warning:
BOOST_LOG_TRIVIAL(warning) << stMessage;
break;
case boost::log::trivial::error:
BOOST_LOG_TRIVIAL(error) << stMessage;
break;
case boost::log::trivial::fatal:
BOOST_LOG_TRIVIAL(fatal) << stMessage;
break;
}
// Clear the console color
if (m_WithConsole)
{
ClearConsoleColor();
}
}
catch(...)
{
}
}
GuacLog GuacLogger::Trace() const
{
return GuacLog(boost::log::trivial::trace);
}
GuacLog GuacLogger::Debug() const
{
return GuacLog(boost::log::trivial::debug);
}
GuacLog GuacLogger::Info() const
{
return GuacLog(boost::log::trivial::info);
}
GuacLog GuacLogger::Warning() const
{
return GuacLog(boost::log::trivial::warning);
}
GuacLog GuacLogger::Error() const
{
return GuacLog(boost::log::trivial::error);
}
GuacLog GuacLogger::Fatal() const
{
return GuacLog(boost::log::trivial::fatal);
}
GuacLog::GuacLog(boost::log::trivial::severity_level eLevel)
{
m_eLevel = eLevel;
}
GuacLog::GuacLog(const GuacLog & rOther)
{
m_eLevel = rOther.m_eLevel;
m_SS << rOther.m_SS.str();
}
GuacLog::~GuacLog()
{
GuacLogger::GetInstance()->LogMessage(m_SS.str(), m_eLevel);
}
| 26.297071
| 118
| 0.669212
|
ofiriluz
|
7288b15e6b0d0caf1465360225709e3a5227ed68
| 17,020
|
hpp
|
C++
|
src/Infrastructure/Mesh/src/Moab/moab/GeomTopoTool.hpp
|
Formatted/esmf
|
94561c6a1d539917da5595a8de867e43f43bcafe
|
[
"NCSA"
] | null | null | null |
src/Infrastructure/Mesh/src/Moab/moab/GeomTopoTool.hpp
|
Formatted/esmf
|
94561c6a1d539917da5595a8de867e43f43bcafe
|
[
"NCSA"
] | null | null | null |
src/Infrastructure/Mesh/src/Moab/moab/GeomTopoTool.hpp
|
Formatted/esmf
|
94561c6a1d539917da5595a8de867e43f43bcafe
|
[
"NCSA"
] | null | null | null |
/**
* MOAB, a Mesh-Oriented datABase, is a software component for creating,
* storing and accessing finite element mesh data.
*
* Copyright 2004 Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government
* retains certain rights in this software.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
*/
#ifndef MOAB_GEOM_TOPO_TOOL_HPP
#define MOAB_GEOM_TOPO_TOOL_HPP
#include "moab/Forward.hpp"
#include "moab/Range.hpp"
#include <map>
#include <assert.h>
namespace moab {
// forward declare this class to avoid the header leaking in here
class OrientedBoxTreeTool;
class GeomQueryTool;
/** \class GeomTopoTool
* \brief Tool for interpreting geometric topology sets in MOAB database
* Tool for interpreting geometric topology sets in MOAB database; see MOAB metadata_info
* document for information on how geometric topology sets are read and represented.
*/
class GeomTopoTool
{
public:
/** \brief Constructor (creates a GTT object) \
* Construct a GeomTopoTool object and search for geometric EntitySets if they
* exist in the provided moab instance.
* \param impl MOAB instance the GeomTopoTool will operate on.
* \param find_geoments if specified as True, geometric objects in the provided MOAB instance
will be searched for and added to the GTT.
\param modelRootSet the GTT will operate only on geometric EntitySets contained by this EntitySet.
If unprovided, the default value for the modelRootSet is the MOAB instance's
root set, which contains everything in the instance.
\param p_rootSets_vector determines the storage datastructure used to relate geometric
EntitySets to their OrientedBoundingBox (OBB) Tree roots. If
set to true (default) a vector will be used to store the root
sets along with an EntityHandle offset for fast lookup of the root
sets. If set to false, then a map will be used to link geometric
EntitySets (keys) to the OBB Tree root sets (values).
\param restore_rootSets determines whether or not to restore the internal index that
links geomSets to their corresponding OBB Root. Only relevant if
find_geoments is true. (default = true)
*/
GeomTopoTool(Interface *impl, bool find_geoments = false, EntityHandle modelRootSet = 0,
bool p_rootSets_vector = true, bool restore_rootSets = true);
~GeomTopoTool();
//! Restore parent/child links between GEOM_TOPO mesh sets
ErrorCode restore_topology_from_adjacency();
//! Store sense of entity relative to wrt_entity.
//!\return MB_MULTIPLE_ENTITIES_FOUND if surface already has a forward volume.
//! MB_SUCCESS if successful
//! otherwise whatever internal error code occured.
ErrorCode set_sense( EntityHandle entity,
EntityHandle wrt_entity,
int sense);
//! Get the sense of entity with respect to wrt_entity
//! Returns MB_ENTITY_NOT_FOUND if no relationship found
ErrorCode get_sense( EntityHandle entity,
EntityHandle wrt_entity,
int & sense );
//! Get the sense of the surface(s) with respect to the volume
ErrorCode get_surface_senses( EntityHandle volume,
int num_surfs,
const EntityHandle* surfs,
int* senses_out);
//! Get the senses of a surface with respect to its volumes
ErrorCode get_surface_senses(EntityHandle surface_ent,
EntityHandle &forward_vol,
EntityHandle &reverse_vol);
//! Set the senses of a surface with respect to its volumes
ErrorCode set_surface_senses(EntityHandle surface_ent,
EntityHandle forward_vol,
EntityHandle reverse_vol);
//! Get the senses of the lower dimension entity handle wrt the higher dimension entities
ErrorCode get_senses (EntityHandle entity,
std::vector<EntityHandle> &wrt_entities,
std::vector<int> &senses);
//! Set the senses of the entity wrt multiple higher dimension entities
ErrorCode set_senses (EntityHandle entity,
std::vector<EntityHandle> &wrt_entities,
std::vector<int> &senses);
/** \brief Get the volume on the other side of a surface
*
* @param A surface to query
* @param old_volume A volume on one side of surface
* @param new_volume Output parameter for volume on the other side of surface
* @return MB_SUCCESS if new_volume was set successfully, error if not.
*/
ErrorCode next_vol( EntityHandle surface, EntityHandle old_volume,
EntityHandle& new_volume );
//! Retrieve geometry sets of desired dimension from model set
// 0 = verts, 1 = curves, 2 = surfs, 3 = vols
ErrorCode get_gsets_by_dimension( int dim, Range &gset);
/** \brief Build obb tree for the entity set given; entity can be surface or volume
*
* @param eh EntityHandle of the volume or surface to construct the OBB tree around
*/
ErrorCode construct_obb_tree(EntityHandle eh);
/** \brief Get the bouding points from a bounding box
*
* @param volume The volume for which the bounding coordinates are requested
* @param minPt Location of the min xyz corner of the volume's axis-aligned bounding box
* @param maxPt Location of the max xyz corner of the volume's axis-aligned bounding box
*/
ErrorCode get_bounding_coords(EntityHandle volume, double minPt[3], double maxPt[3]);
/** \brief Get the center point and three vectors for the OBB of a given volume
*
* @param volume The volume for which the OBB axes will be returned
* @param center coordinates of the oriented bounding box's center point
* @param axis1 scaled axis one of the oriented bounding box
* @param axis2 scaled axis two of the oriented bounding box
* @param axis3 scaled axis three of the oriented bounding box
*/
ErrorCode get_obb(EntityHandle volume, double center[3],
double axis1[3], double axis2[3], double axis3[3]);
/** \brief Get the other (d-1)-dimensional entity bounding a set across a (d-2)-dimensional entity
*
* Given a d-dimensional entity and one (d-1)-dimensional entity, return the (d-1) dimensional
* entity across a specified (d-2)-dimensional entity. For example, given a surface, edge, and vertex,
* returns the other edge bounding the surface sharing the vertex. In the case of degenerate results,
* e.g. two loops bounding a surface and sharing a vertex, tries to step in positively-oriented
* direction. This won't always work; in those cases, will return MB_MULTIPLE_ENTITIES_FOUND.
*
* In the special case where bounded is a curve, then not_this can be a vertex and across zero.
* This function returns the other vertex on the curve.
*/
ErrorCode other_entity(EntityHandle bounded, EntityHandle not_this, EntityHandle across,
EntityHandle &other);
/** \brief Return the dimension of the set, or -1 if it's not a geom_dimension set
*/
int dimension(EntityHandle this_set);
/** \brief Return the global ID of a given entity set
*
* @param this_set EntitySet for which the global ID will be returned
*/
int global_id(EntityHandle this_set);
//! Map from dimension & global ID to EntityHandle
EntityHandle entity_by_id(int dimension, int id);
ErrorCode find_geomsets(Range *ranges = NULL);
//! Restore the internal cross-referencing of geometry sets and OBB roots
// The EntityHandle of an OBB Root can be tagged onto the geoemtry EntitySet
// that it represents so that this relationship can be recovered across
// write to/read from file. Since finding the OBB Root for a given geomset
// is frequent, a faster lookup capability is enabled through data structures
// in GeomTopoTool (i.e. rootSets or mapRootSets). This data structure
// needs to be populated upon file read.
ErrorCode restore_obb_index();
//! Build obb trees for all surfaces and volumes in model set.
// If make_one_vol true, joins trees from all surfaces in model into single
// volume obb tree.
ErrorCode construct_obb_trees(bool make_one_vol = false);
//! Delete the OBB tree of a volume or surface.
// If the passed entity is a volume, and the bool 'vol_only'
// is True, function will delete the volume OBB tree, but
// OBB trees of the surfaces that compose (are children of)
// the volume will remain in tact. If the entity is a volume and
// 'vol_only' is False, function will delete the volume OBB tree
// along with all child surface OBB trees.
ErrorCode delete_obb_tree(EntityHandle gset, bool vol_only = false);
ErrorCode delete_all_obb_trees();
//! Delete the root of the obb tree from the set of all roots
ErrorCode remove_root(EntityHandle vol_or_surf);
//! Get the root of the obbtree for a given entity
ErrorCode get_root(EntityHandle vol_or_surf, EntityHandle &root);
//! If constructing one volume obb tree by joining all surface trees,
// get the root of that tree
EntityHandle get_one_vol_root();
//! Pointer to Oriented Box Tree Tool class
OrientedBoxTreeTool *obb_tree() {return obbTree;}
//! Adds a geometry set to the range of all geometry sets, the model set, and root set
// Make sure the set has the proper geometry dimension tag
// This could make the obb tree out of date
ErrorCode add_geo_set(EntityHandle set, int dimension, int global_id = 0);
//! Will assume no geo sets are defined for this surface
// Will output a mesh_set that contains everything (all sets of interest), for proper output
ErrorCode geometrize_surface_set(EntityHandle surface, EntityHandle & output);
//! Checks to see if the entity is part of the model set
ErrorCode is_owned_set(EntityHandle eh);
//! This would be a deep copy, into a new geom topo tool
// sets will be duplicated, but entities not
// modelSet will be a new one;
// will take as input a pointer to a std::vector of gents (surfaces and volumes, usually),
// which will serve to filter the gents from modelSet (only dependents will be part of the new gtt)
// if the pointer is null, all gsets in the original modelSet are duplicated
ErrorCode duplicate_model(GeomTopoTool *& duplicate, std::vector<EntityHandle> * pvGEnts = NULL);
//! Return the model set handle (this is the full geometry)
EntityHandle get_root_model_set() { return modelSet; }
//! Checks that all geometric entities were created properly
bool check_model();
//! Should be used instead of keeping multiple ranges, for example in FBEngine
const Range * geoRanges() { return geomRanges ; }
//! Return pointer to moab instance
Interface* get_moab_instance() { return mdbImpl; }
//! Returns the sense tag (sense2Tag) from check_face_sense_tag
Tag get_sense_tag();
//! Returns the global ID tag (gidTag) from check_gid_tag
Tag get_gid_tag();
//! Returns the geometry dimension tag (geomTag) from check_geom_tag
Tag get_geom_tag();
//! Returns true if obb trees have been added to the rootset
bool have_obb_tree();
//! returns the number of entities in the modelSet with specified geometric dimension
int num_ents_of_dim(int dim);
//! sets the implicit complement handle for this tool
ErrorCode setup_implicit_complement();
//! Get (or optionally, create) the implicit complement handle
ErrorCode get_implicit_complement(EntityHandle &implicit_complement);
//! detection method for the implicit complement
bool is_implicit_complement(EntityHandle volume);
/** \brief Discover and store the topological relationships among a set of volumes
* This method may be used to discover the hierarchy that exists in a range of
* volumes, that have no previous sense of hierarchy, and store it according
* to the conventions of GeomTopoTool.
* The following requirements about the range of flat_volumes must be met:
* 1. Each volume must be represented by a single, closed surface
* a. The surface meshsets have triangles and vertices as members.
* b. For each "flat volume", there must be two meshsets: one for the
* volume and another for the surface that encloses it. These must be
* linked by a parent-child relationship.
* c. The SENSE_FORWARD tag on the surface meshset must be set to be
* the volume meshset it encloses.
* 2. The surfaces must not touch or overlap
*
* After the hierarchy is established, the topological relationships between
* surfaces and the volumes that enclose them are set. This involves:
* 1. Setting parent-child relationship between surfaces and the volumes that
* enclose them.
* 2. Setting the SENSE_REVERSE tag on the surfaces to be the volume that
* encloses them.
*
*/
ErrorCode restore_topology_from_geometric_inclusion(const Range &flat_volumes);
private:
Interface *mdbImpl;
Tag sense2Tag;
Tag senseNEntsTag, senseNSensesTag;
Tag geomTag;
Tag gidTag;
Tag nameTag;
Tag obbRootTag;
Tag obbGsetTag;
// the model set encompasses a full topological model
EntityHandle modelSet;
// implicit complement handle cache
EntityHandle impl_compl_handle;
Range geomRanges[5];// add one more dimension, for set of gentities; by default, they will
// have geom_dimension 4
int maxGlobalId[5]; // one max global id for each dimension
bool updated;
OrientedBoxTreeTool* obbTree;
EntityHandle setOffset;
std::vector<EntityHandle> rootSets;
bool m_rootSets_vector;
std::map<EntityHandle, EntityHandle> mapRootSets;
EntityHandle oneVolRootSet;
//! Creates a volume for undefined space in the model
// The implicit complement is composed of all surfaces that only
// have one parent volume, i.e. surfaces that are in contact with the outside
// world
ErrorCode generate_implicit_complement(EntityHandle &implicit_complement_set);
//! Compute vertices inclusive and put on tag on sets in geom_sets
ErrorCode construct_vertex_ranges(const Range &geom_sets,
const Tag verts_tag);
//! Given a range of geom topology sets, separate by dimension
ErrorCode separate_by_dimension(const Range &geom_sets);
//! Verify global id tag
ErrorCode check_gid_tag(bool create = false);
//! Verify geometry tag
ErrorCode check_geom_tag(bool create = false);
//! Verify sense face tag
ErrorCode check_face_sense_tag(bool create = false);
//! Verify sense edge tags
ErrorCode check_edge_sense_tags(bool create = false);
ErrorCode resize_rootSets();
ErrorCode set_root_set(EntityHandle vol_or_surf, EntityHandle root);
//! Return a range of children of a desired geometric dimension
Range get_ct_children_by_dimension(const EntityHandle parent, const int desired_dimension);
//! Test if volume A is enclosed by volume B
// This will only produce the correct result if the conventions about
// volumes listed in the restore_topology_from_geometric_inclusion are
// upheld
bool A_is_in_B(const EntityHandle volume_A, const EntityHandle volume_B, GeomQueryTool* GQT);
//! Used by restore_topology_from_geometric_inclusion to generate the
// hierarchical tree of volumes
ErrorCode insert_in_tree(const EntityHandle ct_root, const EntityHandle volume, GeomQueryTool* GQT);
};
inline int GeomTopoTool::num_ents_of_dim(int dim) {
assert(0 <= dim && 3 >= dim);
return geomRanges[dim].size();
}
// get the root of the obbtree for a given entity
inline ErrorCode GeomTopoTool::get_root(EntityHandle vol_or_surf, EntityHandle &root)
{
if(m_rootSets_vector)
{
unsigned int index = vol_or_surf - setOffset;
root = (index < rootSets.size() ? rootSets[index] : 0);
}
else
root = mapRootSets[vol_or_surf];
return (root ? MB_SUCCESS : MB_INDEX_OUT_OF_RANGE);
}
inline EntityHandle GeomTopoTool::get_one_vol_root()
{
return oneVolRootSet;
}
inline Tag GeomTopoTool::get_sense_tag() { check_face_sense_tag(true); return sense2Tag; }
inline Tag GeomTopoTool::get_gid_tag() { check_gid_tag(true); return gidTag; }
inline Tag GeomTopoTool::get_geom_tag() { check_geom_tag(true); return geomTag; }
inline bool GeomTopoTool::is_implicit_complement(EntityHandle volume) { return volume == impl_compl_handle; }
} // namespace moab
#endif
| 42.763819
| 109
| 0.710693
|
Formatted
|
728ca92ed223acacb3019ef7a297546a24aa050f
| 3,630
|
cpp
|
C++
|
5_GraphTheory/6_BinaryMatch/4_kuhn_munkres.cpp
|
JasongLee/Way-to-Algorithm-1
|
249a320845a960d942ae742cb5bd273e814a9e85
|
[
"MIT"
] | 1
|
2017-04-16T15:23:29.000Z
|
2017-04-16T15:23:29.000Z
|
5_GraphTheory/6_BinaryMatch/4_kuhn_munkres.cpp
|
JasongLee/Way-to-Algorithm-1
|
249a320845a960d942ae742cb5bd273e814a9e85
|
[
"MIT"
] | null | null | null |
5_GraphTheory/6_BinaryMatch/4_kuhn_munkres.cpp
|
JasongLee/Way-to-Algorithm-1
|
249a320845a960d942ae742cb5bd273e814a9e85
|
[
"MIT"
] | 1
|
2018-07-19T00:52:39.000Z
|
2018-07-19T00:52:39.000Z
|
//Kuhn-Munkres算法
//kuhn_munkres.cpp
//二分图B中的每条边都拥有一个正权值,为了方便该权值为正整数
//求二分带权图的具有最大权的完备匹配(也称最优匹配,最佳匹配)
//1)基础概念
//二分带权图的最大权完备匹配问题是应用Kuhn-Munkres(简称KM)算法的典型场景
//顶点标号技术:
//对于二分图B=<X,Y,E>的X集合中节点设置顶点标号A,Y集合中节点设置顶点标号B
//即设置数组a_label和b_label,a_label[i](b_label[i])指代X(Y)集合中节点i的标号
//可行顶点标号:
//对于二分图B中的每条边e,一个端点i属于X集合,另一个端点j属于Y集合
//标号都满足a_label[i] + b_label[j] >= value(e)
//保证可行顶点标号总是存在的,设置一种平凡可行标号:
//即设置X集合中每个节点i,其标号a_label[i]是节点i的所有邻边中权值最大的边的权值
//而Y集合中所有节点的标号b_label值都设置为0
//等价子图,相等子图:
//二分图B的顶点标号中满足a_label[i]+b_label[j]=value(e)的边所组成的边集
//该边集的生成子图即为图B的相等子图
//需要注意:相等子图的节点集与原图B的节点集是相同的,即相等子图没有比原图B减少节点
//相等子图定理:
//若二分图B的相等子图有完备匹配M,则M是二分图B的最大全完备匹配
//
//由相等子图定理可知,欲求二分图的最大权完备匹配,只需求某个相等子图的完备匹配即可
//而完备匹配可以使用匈牙利算法求得
//Kuhn-Munkres算法使用一个方法对标号进行修改,使得新的相等子图的最大匹配逐渐扩大
//最终得到有完备匹配的相等子图,即求得最大全完备匹配
//当二分带权图中所有边的权值都是1时,该问题退化为二分完备匹配问题
//
//2)具体实现
//设置数组a_label为X集合中的节点标号,数组b_label为Y集合中的节点标号
//初始时设置X中节点标号a_laebl为其所有邻边中最大的权值,Y中标号都为0
//对X中每个节点i重复以下步骤:
//用匈牙利算法中dfs遍历的方法求当前标号下的等价子图B'的最大匹配
//在遍历过程中,如果从节点i出发的dfs找不到增广轨
//则从该节点出发的增广轨不存在完备匹配,按照以下方法对节点i出发的增广轨进行修改:
//找到改进量d=min(A[i]+B[j]-value(e)),其中节点i属于a_label,节点j不属于b_label
//然后改进节点的标号:A[i]=A[i]-d,B[j]=B[j]-d,其中i属于a_label,j属于b_label
//然后继续进行匈牙利算法,直到求出完备匹配为止
//
//该算法是二分图中最为难懂的算法,网上主要有两篇文档即本文最后列出的两篇
//
//3)补注
//本文的代码中有一处判断条件与文档“带权二分图的最优匹配 Kuhn-Munkres算法(转)”不一致
//我在实际测试时发现原文档的代码由于缺少一处判断条件而得到错误答案
//在本文的代码中进行了修正
//
//本文引用了“带权二分图的最优匹配 Kuhn-Munkres算法(转)”,作者“yulin11”
//“Kuhn-Munkres算法(NOCOW)”,作者“Maigo”
//“图论讲义 第3章(匹配问题)”,作者“高随祥”
#include "general_head.h"
#include "graph.h"
void construct_s(bipartite b, int *a_label, int *b_label);
int dfs_path(bipartite b, int *visit_x, int *visit_y, int p,
int *ymatch, int *a_label, int *b_label);
int kuhn_munkres(bipartite b, int *ymatch)
{//二分图B存在完备匹配,故它的X和Y集合节点数量相同
//X集合有b_xn个节点,下标从0到b_xn-1,Y集合有b_yn个节点,下标从0到b_yn-1
//b_g[i][j]指代节点i和节点j之间的边的权值,其中节点i属于X集合,节点j属于Y集合
memset(ymatch, -1, MAX * sizeof(int));
//数组a_label和b_label为节点标号
//数组visit_x(visit_y)标记X(Y)集合中节点是否被访问过
int a_label[MAX], b_label[MAX], visit_x[MAX], visit_y[MAX];
//初始化节点标号数组a_label和b_label
//X集合中每个节点i的标号初始化为其所有邻边中最大的权值,Y集合中所有节点i标号为0
//从而保证对于每条边e都有A[i]+B[i]>=value(e)
construct_s(b, a_label, b_label);
for(int i = 0; i < b.b_xn; ++ i)
while(1){
memset(visit_x, 0, MAX * sizeof(int));
memset(visit_y, 0, MAX * sizeof(int));
if(dfs_path(b, visit_x, visit_y, i, ymatch, a_label, b_label))
break;
int tmp_label(INF);
for(int j = 0; j < b.b_xn; ++ j)
if(visit_x[j])
for(int k = 0; k < b.b_yn; ++ k)
if(!visit_y[k])
tmp_label = min(tmp_label,
a_label[j] + b_label[k] - b.b_g[j][k]);
for(int j = 0; j < b.b_xn; ++ j){
if(visit_x[j])
a_label[j] -= tmp_label;
if(visit_y[j])
b_label[j] += tmp_label;
}
}
int max_match(0);
for(int i = 0; i < b.b_yn; ++ i)
max_match += b.b_g[ymatch[i]][i];
return(max_match);
}
void construct_s(bipartite b, int *a_label, int *b_label)
{
memset(a_label, 0, MAX * sizeof(int));
memset(b_label, 0, MAX * sizeof(int));
for(int i = 0; i < b.b_xn; ++ i)
for(int j = 0; j < b.b_yn; ++ j)
a_label[i] = max(a_label[i], b.b_g[i][j]);
}
int dfs_path(bipartite b, int *visit_x, int *visit_y, int p,
int *ymatch, int *a_label, int *b_label)
{
visit_x[p] = 1;
for(int i = 0; i < b.b_yn; ++ i)
if(!visit_y[i] && b.b_g[p][i] &&
a_label[p] + b_label[i] == b.b_g[p][i]){
//“带权二分图的最优匹配 Kuhn-Munkres算法(转)”中缺少的判断条件是
//b.b_g[p][i]这一句,即判断节点p与节点i之间存在边
//本文之前的若干二分图算法的代码中都有这个判断,此处应该是原作者的失误
visit_y[i] = 1;
if(ymatch[i] == -1 ||
dfs_path(b, visit_x, visit_y, ymatch[i],
ymatch, a_label, b_label)){
ymatch[i] = p;
return(1);
}
}
return(0);
}
| 29.04
| 65
| 0.696694
|
JasongLee
|
728f19ff5d8f3f0b8ff62a652f2e6f83528db037
| 431
|
hpp
|
C++
|
obs-studio/UI/double-slider.hpp
|
noelemahcz/libobspp
|
029472b973e5a1985f883242f249848385df83a3
|
[
"MIT"
] | null | null | null |
obs-studio/UI/double-slider.hpp
|
noelemahcz/libobspp
|
029472b973e5a1985f883242f249848385df83a3
|
[
"MIT"
] | null | null | null |
obs-studio/UI/double-slider.hpp
|
noelemahcz/libobspp
|
029472b973e5a1985f883242f249848385df83a3
|
[
"MIT"
] | null | null | null |
#pragma once
#include <QSlider>
#include "slider-ignorewheel.hpp"
class DoubleSlider : public SliderIgnoreScroll {
Q_OBJECT
double minVal, maxVal, minStep;
public:
DoubleSlider(QWidget *parent = nullptr);
void setDoubleConstraints(double newMin, double newMax, double newStep,
double val);
signals:
void doubleValChanged(double val);
public slots:
void intValChanged(int val);
void setDoubleVal(double val);
};
| 17.958333
| 72
| 0.761021
|
noelemahcz
|
7291f9692107375003ce88c72589d9623cbf9d47
| 725
|
hpp
|
C++
|
src/runner_options.hpp
|
dholmes215/adventofcode-cpp
|
2a0ce43c51ec3beccc56fb48bf91de070e6ca136
|
[
"BSL-1.0"
] | null | null | null |
src/runner_options.hpp
|
dholmes215/adventofcode-cpp
|
2a0ce43c51ec3beccc56fb48bf91de070e6ca136
|
[
"BSL-1.0"
] | null | null | null |
src/runner_options.hpp
|
dholmes215/adventofcode-cpp
|
2a0ce43c51ec3beccc56fb48bf91de070e6ca136
|
[
"BSL-1.0"
] | null | null | null |
//
// Copyright (c) 2020-2021 David Holmes (dholmes at dholmes dot us)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef RUNNER_OPTIONS_HPP
#define RUNNER_OPTIONS_HPP
#include <filesystem>
#include <optional>
namespace aoc {
struct date_filter {
int year{};
std::optional<int> day;
};
struct runner_options {
std::optional<std::filesystem::path> inputfile;
std::optional<std::filesystem::path> datadir;
std::optional<date_filter> dates;
int repeat{1};
int seconds{1};
};
runner_options process_args(int argc, char** argv);
} // namespace aoc
#endif // RUNNER_OPTIONS_HPP
| 21.969697
| 79
| 0.713103
|
dholmes215
|
729c8bd7858f55b9933cf7bb0fabdadc9a2eb4b8
| 3,780
|
cpp
|
C++
|
disk/DiskAsyncResult.cpp
|
zukisoft/storage
|
a8b6ac184377c4a6c25624260d16e7f42f082395
|
[
"MIT"
] | 1
|
2016-05-28T04:19:26.000Z
|
2016-05-28T04:19:26.000Z
|
disk/DiskAsyncResult.cpp
|
zukisoft/storage-legacy
|
a8b6ac184377c4a6c25624260d16e7f42f082395
|
[
"MIT"
] | null | null | null |
disk/DiskAsyncResult.cpp
|
zukisoft/storage-legacy
|
a8b6ac184377c4a6c25624260d16e7f42f082395
|
[
"MIT"
] | null | null | null |
//-----------------------------------------------------------------------------
// Copyright (c) 2014 Michael G. Brehm
//
// 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 "stdafx.h" // Include project pre-compiled headers
#include "DiskAsyncResult.h" // Include DiskAsyncResult decls
#pragma warning(push, 4) // Enable maximum compiler warnings
BEGIN_NAMESPACE(zuki)
BEGIN_NAMESPACE(storage)
BEGIN_NAMESPACE(disk)
//---------------------------------------------------------------------------
// DiskAsyncResult Constructor (internal)
//
// Arguments:
//
// handle - Open DiskSafeHandle instance
// state - IAsyncResult state object
DiskAsyncResult::DiskAsyncResult(DiskSafeHandle^ handle, Object^ state) :
m_handle(handle), m_state(state), m_completed(false)
{
// Can't check this
// if(handle == nullptr) throw gcnew ArgumentNullException("handle");
m_event = gcnew ManualResetEvent(false);
m_overlapped = gcnew Overlapped(0, 0, m_event->SafeWaitHandle->DangerousGetHandle(), this);
m_pNativeOverlapped = m_overlapped->Pack(nullptr, nullptr);
}
//---------------------------------------------------------------------------
// DiskAsyncResult Finalizer
DiskAsyncResult::!DiskAsyncResult()
{
if(m_pNativeOverlapped) Overlapped::Free(m_pNativeOverlapped);
m_pNativeOverlapped = NULL;
}
//---------------------------------------------------------------------------
// DiskAsyncResult::EndOperation (internal, static)
//
// Completes the asynchronous I/O operation
//
// Arguments:
//
// asyncResult - IAsyncResult object instance
void DiskAsyncResult::EndOperation(IAsyncResult^ asyncResult)
{
DiskAsyncResult^ instance = safe_cast<DiskAsyncResult^>(asyncResult);
instance->EndOperation();
}
//---------------------------------------------------------------------------
// DiskAsyncResult::EndOperation (private)
//
// Completes the asynchronous I/O operation
//
// Arguments:
//
// NONE
void DiskAsyncResult::EndOperation(void)
{
DWORD cbTransferred; // Bytes transferred
m_event->WaitOne(); // Wait for the I/O operation to complete
// Complete the asynchronous operation
if(!GetOverlappedResult(m_handle, reinterpret_cast<LPOVERLAPPED>(m_pNativeOverlapped), &cbTransferred, FALSE))
throw gcnew Win32Exception(GetLastError());
Interlocked::Exchange(m_completed, 1); // Set the completion flag
Overlapped::Free(m_pNativeOverlapped); // Release native OVERLAPPED structure
m_pNativeOverlapped = NULL; // Reset pointer to NULL
}
//---------------------------------------------------------------------------
END_NAMESPACE(disk)
END_NAMESPACE(storage)
END_NAMESPACE(zuki)
#pragma warning(pop)
| 35.660377
| 111
| 0.648413
|
zukisoft
|
72a11eadc3dd83ebd43b738669fdc317af80e726
| 1,838
|
cpp
|
C++
|
src/viennautils/filesystem/filesystem.cpp
|
viennautils/viennautils-dev
|
38ef9a088f8df2a59215d27fd38bed8a4effd012
|
[
"MIT"
] | 1
|
2015-09-13T03:50:52.000Z
|
2015-09-13T03:50:52.000Z
|
src/viennautils/filesystem/filesystem.cpp
|
viennautils/viennautils-dev
|
38ef9a088f8df2a59215d27fd38bed8a4effd012
|
[
"MIT"
] | null | null | null |
src/viennautils/filesystem/filesystem.cpp
|
viennautils/viennautils-dev
|
38ef9a088f8df2a59215d27fd38bed8a4effd012
|
[
"MIT"
] | 2
|
2017-01-12T09:02:43.000Z
|
2021-05-12T07:29:57.000Z
|
#include "viennautils/filesystem/filesystem.hpp"
namespace viennautils
{
namespace filesystem
{
namespace
{
std::string const path_delimiters = "\\/";
std::string::size_type find_last_path_delimiter(std::string const & path)
{
return path.find_last_of(path_delimiters);
}
std::string::size_type find_extension_delimiter(std::string const & path)
{
//we also have to look for path delimiters so that "a.b/file" doesn't yield pos 1 but rather std::string::npos
std::string::size_type pos = path.find_last_of(path_delimiters + ".");
return (pos == std::string::npos || path[pos] != '.') ? std::string::npos : pos;
}
}
std::string extract_extension(std::string const & path, bool include_delimiter)
{
return path.substr(find_extension_delimiter(path) + (include_delimiter ? 0 : 1));
}
std::string extract_stem(std::string const & path)
{
std::string::size_type last_path_delim = find_last_path_delimiter(path);
std::string::size_type stem_start = (last_path_delim == std::string::npos) ? 0 : last_path_delim+1;
std::string::size_type ext_delim = find_extension_delimiter(path);
std::string::size_type stem_len = (ext_delim == std::string::npos) ? std::string::npos : ext_delim-stem_start;
return path.substr(stem_start, stem_len);
}
std::string extract_filename(std::string const & path)
{
std::string::size_type last_path_delim = find_last_path_delimiter(path);
return (last_path_delim == std::string::npos) ? path : path.substr(last_path_delim+1);
}
std::string extract_path(std::string const & path, bool include_last_delimiter)
{
std::string::size_type last_path_delim = find_last_path_delimiter(path);
return (last_path_delim == std::string::npos) ? "" : path.substr(0, last_path_delim + (include_last_delimiter ? 1 : 0));
}
} //end of namespace filesystem
} //end of namespace viennautils
| 32.245614
| 122
| 0.735038
|
viennautils
|
72a44e346584e77c1d9722c2a1426f459cb1a86c
| 1,341
|
cpp
|
C++
|
Week9/Fractional_Knapsack.cpp
|
SukalpVishnoi/DAA-PRACTICL
|
fee6b3f42a90d96de01ccf6af417d7ed29dc30f5
|
[
"MIT"
] | null | null | null |
Week9/Fractional_Knapsack.cpp
|
SukalpVishnoi/DAA-PRACTICL
|
fee6b3f42a90d96de01ccf6af417d7ed29dc30f5
|
[
"MIT"
] | null | null | null |
Week9/Fractional_Knapsack.cpp
|
SukalpVishnoi/DAA-PRACTICL
|
fee6b3f42a90d96de01ccf6af417d7ed29dc30f5
|
[
"MIT"
] | 1
|
2021-09-22T18:22:08.000Z
|
2021-09-22T18:22:08.000Z
|
#include <bits/stdc++.h>
using namespace std;
bool compare(pair<pair<int, int>, int> a, pair<pair<int, int>, int> b)
{
return a.first.second * 1.0 / a.first.first > b.first.second * 1.0 / b.first.first;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
int V[n], W[n];
for (int i = 0; i < n; ++i)
cin >> W[i];
for (int i = 0; i < n; ++i)
cin >> V[i];
vector<pair<pair<int, int>, int>> items;
for (int i = 0; i < n; ++i)
items.push_back(make_pair(make_pair(W[i], V[i]), i + 1));
int k;
cin >> k;
sort(items.begin(), items.end(), compare);
float max_profit = 0;
vector<pair<int, int>> sack;
for (int i = 0; i < n && k > 0; ++i)
{
int w = items[i].first.first, v = items[i].first.second, ind = items[i].second;
if (w <= k)
{
k -= w;
max_profit += v;
sack.push_back(make_pair(ind, w));
}
else
{
max_profit += k * v * 1.0 / w;
sack.push_back(make_pair(ind, k));
k = 0;
}
}
cout << "Maximum Value : " << max_profit << endl;
cout << "item-weight" << endl;
for (auto i : sack)
cout << i.first << " " << i.second << endl;
}
| 26.294118
| 87
| 0.480239
|
SukalpVishnoi
|
72a4db9cdce58e0e49216b312758cd8ca6afbc9d
| 14,532
|
cpp
|
C++
|
src/mrilucpp/Ifpack_MRILU.cpp
|
jthies/i-emic
|
8bc351e2e6e31ac6a4c14a16fadfa65c0e04b6a7
|
[
"Apache-2.0"
] | 2
|
2020-11-30T08:37:53.000Z
|
2021-01-18T09:53:59.000Z
|
src/mrilucpp/Ifpack_MRILU.cpp
|
jthies/i-emic
|
8bc351e2e6e31ac6a4c14a16fadfa65c0e04b6a7
|
[
"Apache-2.0"
] | 83
|
2019-03-04T10:07:02.000Z
|
2022-01-20T10:45:40.000Z
|
src/mrilucpp/Ifpack_MRILU.cpp
|
jthies/i-emic
|
8bc351e2e6e31ac6a4c14a16fadfa65c0e04b6a7
|
[
"Apache-2.0"
] | 4
|
2019-02-18T10:17:59.000Z
|
2019-03-27T12:24:57.000Z
|
/**********************************************************************
* Copyright by Jonas Thies, Univ. of Groningen 2006/7/8. *
* Permission to use, copy, modify, redistribute is granted *
* as long as this header remains intact. *
* contact: jonas@math.rug.nl *
**********************************************************************/
#include "Ifpack_MRILU.h"
#include "Epetra_MultiVector.h"
#include "Epetra_Vector.h"
#include "Epetra_Comm.h"
#include "Epetra_MpiComm.h"
#include "Epetra_RowMatrix.h"
#include "Epetra_CrsMatrix.h"
#include <iomanip>
#include "Teuchos_oblackholestream.hpp"
#include "Teuchos_StandardCatchMacros.hpp"
#include "GlobalDefinitions.H"
// we still use one or two subroutines from the Fortran code,
// this might (and should) be changed in the future
extern "C"
{
#ifdef HAVE_IFPACK_MRILU
void mrilucpp_create(int* id, int* n, int* nnz, int* beg, int* jco, double* co);
void mrilucpp_destroy(int* id);
void mrilucpp_set_params(const int* id, int* blocksize, int* cutmck, int* scarow,
int* xactelm,int* clsonce,
double* nlsfctr, double* epsw, double* elmfctr, int* gusmod,
double* gusfctr,double* redfctr,
double* schtol, double* denslim, double* globfrac,
double* locfrac, double* sparslim, int* ilutype,
double* droptol, double* compfct, double* cpivtol,
double* lutol_, int* singlu, int* outlev);
void mrilucpp_compute(const int* id);
void mrilucpp_apply(const int* id, int* dim, const double *rhs, double *sol);
#endif
}//extern
#ifdef DEBUGGING
#define DEBUG(s) std::cerr << comm->MyPID() << ": " << s << std::endl;
#else
#define DEBUG(s)
#endif
#ifndef CHECK_ZERO
# define CHECK_ZERO(funcall) {int ierr = funcall; \
if (ierr) {std::cerr<<"Trilinos Error "<<ierr<<" returned from call "<<#funcall<<std::endl;}}
#endif
///////////////////////////////////////////////////////////////////////////////
// CLASS IFPACK_MRILU
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////
// note: 'needs_setup' is currently irrelevant, the preconditioner is recomputed
// completely every time.
Ifpack_MRILU::Ifpack_MRILU(Teuchos::RCP<Epetra_CrsMatrix> A, Teuchos::RCP<Epetra_Comm> comm_) :
mrilu_id(0),
Matrix_(A),
comm(comm_),
is_initialized(false),is_computed(false)
{
std::string s1="MRILU(";
std::string s2(A->Label());
std::string s3=")";
label = s1+s2+s3;
DEBUG("Ifpack_MRILU constructor called");
default_params();
} //Constructor
Ifpack_MRILU::Ifpack_MRILU(Epetra_RowMatrix* A) :
mrilu_id(0),
is_initialized(false),is_computed(false)
{
std::string s1="MRILU(";
std::string s2(A->Label());
std::string s3=")";
label = s1+s2+s3;
Matrix_ = Teuchos::rcp(A,false);
comm=Teuchos::rcp(&(A->Comm()),false);
DEBUG("Ifpack_MRILU Ifpack constructor called");
default_params();
//std::cout << "PID " << comm->MyPID()<<", MRILU local matrix size = "<<A->NumMyRows()<<std::endl;
} //Constructor
///////////////////////////////////////////////////////////////////////////////
// destructor
///////////////////////////////////////////////////////////////////////////////
Ifpack_MRILU::~Ifpack_MRILU()
{
DEBUG("Ifpack_MRILU destructor called");
if (mrilu_id>0)
{
DEBUG("Destroy MRILU preconditioner...\n");
#ifdef HAVE_IFPACK_MRILU
mrilucpp_destroy(&mrilu_id);
#endif
}
is_initialized=false;
is_computed=false;
}
//////////////
const Epetra_Comm& Ifpack_MRILU::Comm() const {return *comm;}
const Epetra_Map& Ifpack_MRILU::OperatorDomainMap() const
{return Matrix_->OperatorDomainMap();}
const Epetra_Map& Ifpack_MRILU::OperatorRangeMap() const
{return Matrix_->OperatorRangeMap();}
int Ifpack_MRILU::SetParameters(Teuchos::ParameterList& ifpParams)
{
Teuchos::ParameterList& lsParams = ifpParams.sublist("MRILU");
DEBUG("Parameters supplied by User: ");
DEBUG(lsParams);
blocksize = lsParams.get("blocksize",blocksize);
cutmck = lsParams.get("cutmck",cutmck);
scarow = lsParams.get("scarow",scarow);
xactelm = lsParams.get("xactelm",xactelm);
clsonce = lsParams.get("clsonce",clsonce);
nlsfctr = lsParams.get("nlsfctr",nlsfctr);
epsw = lsParams.get("epsw",epsw);
elmfctr = lsParams.get("elmfctr",elmfctr);
gusmod = lsParams.get("gusmod",gusmod);
gusfctr = lsParams.get("gusfctr",gusfctr);
redfctr = lsParams.get("redfctr",redfctr);
schtol = lsParams.get("schtol",schtol);
denslim = lsParams.get("denslim", denslim);
globfrac = lsParams.get("globfrac", globfrac);
locfrac = lsParams.get("locfrac", locfrac);
sparslim = lsParams.get("sparslim", sparslim);
ilutype = lsParams.get("ilutype", ilutype);
droptol = lsParams.get("droptol", droptol);
compfct = lsParams.get("compfct", compfct);
cpivtol = lsParams.get("cpivtol", cpivtol);
lutol = lsParams.get("lutol", lutol);
singlu = lsParams.get("singlu", singlu);
outlev = lsParams.get("Output Level",outlev);
DEBUG("Parameters used: ");
DEBUG(lsParams);
return 0;
}
// build preconditioner. This function is called by NOX/LOCA,
// I am not sure what the arguments mean but we do not use them
// anyway
bool Ifpack_MRILU::computePreconditioner(const Epetra_Vector& x,
Epetra_Operator& Prec,
Teuchos::ParameterList* p)
{
DEBUG("+++ Enter Ifpack_MRILU::computePreconditioner");
if (p!=NULL) this->SetParameters(*p);
if (!IsInitialized())
{
this->Initialize();
}
this->Compute();
DEBUG("--- Leave Ifpack_MRILU::computePreconditioner");
return true;
}
///////////////////////////////////////////////////////////////////////////////
// apply inverse preconditioner step
///////////////////////////////////////////////////////////////////////////////
int Ifpack_MRILU::
ApplyInverse(const Epetra_MultiVector& input,
Epetra_MultiVector& result) const
{
if (!IsComputed())
{
Error("Ifpack_MRILU not yet computed!",__FILE__,__LINE__);
}
if (&input == &result)
Error("aliased call to Ifpack_MRILU::ApplyInverse",__FILE__,__LINE__);
DEBUG("+++ Enter Ifpack_MRILU::ApplyInverse");
if (input.NumVectors()!=1)
{
this->Error("Multiple Rhs not supported by Ifpack_MRILU!",__FILE__,__LINE__);
}
#ifdef HAVE_IFPACK_MRILU
int n = input.MyLength();
double *sol_array; //= new double[n];
const double *rhs_array; //= new double[n];
//CHECK_ZERO(input.ExtractCopy(rhs_array,n));
rhs_array = input[0];
sol_array = result[0];
DEBUG("Apply MRILU preconditioner...");
/*
if (outlev>3)
{
std::cout << "Apply " << label << std::endl;
}
*/
if (is_identity)
result = input;
else
{
mrilucpp_apply(&mrilu_id, &n, rhs_array,sol_array);
}
//for (int i=0;i<n;i++) result[0][i]=sol_array[i];
//delete [] sol_array;
//delete [] rhs_array;
#else
std::cout << "WARNING: MRILU is not available, using identity preconditioner."<<std::endl;
result=input;
#endif
DEBUG("done!");
DEBUG("+++ Leave Ifpack_MRILU::ApplyInverse");
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// Apply preconditioner matrix (not available)
///////////////////////////////////////////////////////////////////////////////
int Ifpack_MRILU::
Apply(const Epetra_MultiVector& X, Epetra_MultiVector& Y) const
{
this->Error("Ifpack_MRILU::Apply() - method is NOT implemented!! ",__FILE__,__LINE__);
return false;
}
///////////////////////////////////////////////////////////////////////////////
// inf-norm (n/a)
///////////////////////////////////////////////////////////////////////////////
double Ifpack_MRILU::NormInf() const
{
this->Error("Ifpack_MRILU::NormInf() - method is NOT implemented!! ",__FILE__,__LINE__);
return -1.0;
}
//////////////////////////////////////////////////////////////////////////////
// remaining IFPACK interface //
//////////////////////////////////////////////////////////////////////////////
//! Computes all it is necessary to initialize the preconditioner.
int Ifpack_MRILU::Initialize()
{
DEBUG("+++ Enter Ifpack_MRILU::Initialize");
// extract CRS array of the local Jacobian.
int nnz = Matrix_->NumMyNonzeros();
int nrows = Matrix_->NumMyRows();
// although we might get CRS arrays directly from Epetra,
// this method is preferred because it is implementation independent
int* beg = new int[nrows+1];
int* jco = new int[nnz];
double* co = new double[nnz];
int len;
beg[0] = 0;
int idx = 0;
is_identity = true;
for (int i = 0; i < nrows; i++)
{
CHECK_ZERO(Matrix_->ExtractMyRowCopy(i, nnz-beg[i], len, co+beg[i], jco+beg[i]));
beg[i+1] = beg[i] + len;
// Check whether this matrix is the identity
if (is_identity)
{
for (int j = beg[i]; j != beg[i+1]; ++j)
{
if ( ((jco[idx] == i) && (std::abs(co[idx] - 1.0) > 1e-7)) ||
((jco[idx] != i) && (std::abs(co[idx]) > 1e-7)) )
{
is_identity = false;
break;
}
idx++;
}
}
}
DEBUG("Create preconditioner...");
#ifdef HAVE_IFPACK_MRILU
// the loca 'Reuse Policy' doesn't work for user
// defined preconditioners, it seems. They just
// call this function whenever they want a new precond.
mrilucpp_destroy(&mrilu_id);
// note that the conversion to 1-based indexing is done in fortran:
mrilucpp_create(&mrilu_id, &nrows, &nnz, beg, jco, co);
#endif
delete [] beg;
delete [] co;
delete [] jco;
is_initialized = true;
DEBUG("+++ Leave Ifpack_MRILU::Initialize");
return 0;
}
//! Returns true if the preconditioner has been successfully initialized, false otherwise.
bool Ifpack_MRILU::IsInitialized() const
{
return is_initialized;
}
//! Computes all it is necessary to apply the preconditioner.
int Ifpack_MRILU::Compute()
{
DEBUG("Enter Ifpack_MRILU::Compute");
#ifdef HAVE_IFPACK_MRILU
//note: needs_setup is ignored up to now
if (comm->NumProc()>1)
{
// this class should be run through an Ifpack_LocalFilter or the like:
this->Error("The MRILU preconditioner is not intended for parallel use!",__FILE__,__LINE__);
}
if (!this->IsInitialized()) this->Initialize();
DEBUG("set parameters...");
mrilucpp_set_params( &mrilu_id, &blocksize, &cutmck , &scarow , &xactelm ,
&clsonce, &nlsfctr,
&epsw , &elmfctr, &gusmod , &gusfctr, &redfctr,
&schtol , &denslim, &globfrac, &locfrac, &sparslim,
&ilutype, &droptol, &compfct , &cpivtol, &lutol,
&singlu , &outlev);
DEBUG("Compute factorization...");
if (outlev>3)
{
std::cout << "Compute " << label << std::endl;
}
mrilucpp_compute(&mrilu_id);
DEBUG("done!");
// after building the preconditioner, the internal csr matrix is destroyed
is_computed=true;
is_initialized=false; // always have to re-initialize before calling Compute again!
#else
std::cout << "WARNING: MRILU is not available, using identity!"<<std::endl;
#endif
DEBUG("Leave Ifpack_MRILU::Compute");
return 0;
}
//! Returns true if the preconditioner has been successfully computed, false otherwise.
bool Ifpack_MRILU::IsComputed() const
{
return is_computed;
}
//! Computes the condition number estimate, returns its value.
double Ifpack_MRILU::Condest(const Ifpack_CondestType CT,
const int MaxIters,
const double Tol,
Epetra_RowMatrix* Matrix)
{
// this is not yet implemented, although it should be trivial to get
// some estimate from the ILU factorization
condest=-1.0;
return condest;
}
//! Returns the computed condition number estimate, or -1.0 if not computed.
double Ifpack_MRILU::Condest() const
{
return condest;
}
//! Returns a pointer to the matrix to be preconditioned.
const Epetra_RowMatrix& Ifpack_MRILU::Matrix() const
{
if (Matrix_==Teuchos::null)
{
Error("Matrix handle not available!",__FILE__,__LINE__);
}
return *Matrix_;
}
// TODO: none of the performance measuring routines below are implemented, yet
//! Returns the number of calls to Initialize().
int Ifpack_MRILU::NumInitialize() const
{
return 0;
}
//! Returns the number of calls to Compute().
int Ifpack_MRILU::NumCompute() const
{
return 0;
}
//! Returns the number of calls to ApplyInverse().
int Ifpack_MRILU::NumApplyInverse() const
{
return 0;
}
//! Returns the time spent in Initialize().
double Ifpack_MRILU::InitializeTime() const
{
return -1.0;
}
//! Returns the time spent in Compute().
double Ifpack_MRILU::ComputeTime() const
{
return -1.0;
}
//! Returns the time spent in ApplyInverse().
double Ifpack_MRILU::ApplyInverseTime() const
{
return -1.0;
}
//! Returns the number of flops in the initialization phase.
double Ifpack_MRILU::InitializeFlops() const
{
return 0.0;
}
//! Returns the number of flops in the computation phase.
double Ifpack_MRILU::ComputeFlops() const
{
return 0.0;
}
//! Returns the number of flops in the application of the preconditioner.
double Ifpack_MRILU::ApplyInverseFlops() const
{
return 0.0;
}
//! Prints basic information on iostream. This function is used by operator<<.
std::ostream& Ifpack_MRILU::Print(std::ostream& os) const
{
// TODO: print something interesting for the user to read and enjoy
os << this->Label();
return os;
}
void Ifpack_MRILU::default_params()
{
blocksize=1;
cutmck=false;
scarow = true;
xactelm = false;
clsonce = false;
nlsfctr = 0.1;
epsw = 1e-2;
elmfctr = 0.1;
gusmod = false;
gusfctr = 1.0;
redfctr = 0.8;
schtol = 0.0;
denslim = 0.01;
globfrac = 0.1;
locfrac = 1.0;
sparslim = 0.9;
ilutype = 9;
droptol = 1e-4;
compfct = 1.0;
cpivtol = 0.5;
lutol = 1e-10;
singlu = false;
outlev = 2;
}
void Ifpack_MRILU::Error(std::string msg, std::string file, int line) const
{
std::cerr << "ERROR: "<<msg<<std::endl;
std::cerr << "("<<file<<", line "<<line<<")\n";
#ifdef HAVE_MPI
MPI_Abort(MPI_COMM_WORLD,-1);
#endif
exit(-1);
}
| 28.217476
| 99
| 0.595789
|
jthies
|
72a7799234f20ef47ac4bbce25b728ce18f55df6
| 19,959
|
cpp
|
C++
|
Base/PLRenderer/src/Texture/TextureAniLoaderPL.cpp
|
ktotheoz/pixellight
|
43a661e762034054b47766d7e38d94baf22d2038
|
[
"MIT"
] | 83
|
2015-01-08T15:06:14.000Z
|
2021-07-20T17:07:00.000Z
|
Base/PLRenderer/src/Texture/TextureAniLoaderPL.cpp
|
PixelLightFoundation/pixellight
|
43a661e762034054b47766d7e38d94baf22d2038
|
[
"MIT"
] | 19
|
2018-08-24T08:10:13.000Z
|
2018-11-29T06:39:08.000Z
|
Base/PLRenderer/src/Texture/TextureAniLoaderPL.cpp
|
ktotheoz/pixellight
|
43a661e762034054b47766d7e38d94baf22d2038
|
[
"MIT"
] | 40
|
2015-02-25T18:24:34.000Z
|
2021-03-06T09:01:48.000Z
|
/*********************************************************\
* File: TextureAniLoaderPL.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <PLCore/Xml/Xml.h>
#include <PLCore/Log/Log.h>
#include "PLRenderer/Texture/AniInfo.h"
#include "PLRenderer/Texture/TextureAni.h"
#include "PLRenderer/Texture/TextureManager.h"
#include "PLRenderer/Texture/TextureAniLoaderPL.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
using namespace PLCore;
using namespace PLMath;
namespace PLRenderer {
//[-------------------------------------------------------]
//[ RTTI interface ]
//[-------------------------------------------------------]
pl_implement_class(TextureAniLoaderPL)
//[-------------------------------------------------------]
//[ Public RTTI methods ]
//[-------------------------------------------------------]
bool TextureAniLoaderPL::Load(TextureAni &cTextureAni, File &cFile)
{
// Load XML document
XmlDocument cDocument;
if (cDocument.Load(cFile)) {
// Get texture animation element
const XmlElement *pTextureAniElement = cDocument.GetFirstChildElement("TextureAnimation");
if (pTextureAniElement) {
// Get the format version
const int nVersion = pTextureAniElement->GetAttribute("Version").GetInt();
// Unknown
if (nVersion > 1) {
PL_LOG(Error, cDocument.GetValue() + ": " + UnknownFormatVersion)
// 1 (current)
} else if (nVersion == 1) {
return LoadV1(cTextureAni, *pTextureAniElement);
// ""/0 (same format as 1)
} else if (nVersion == 0) {
// [DEPRECATED]
PL_LOG(Warning, cDocument.GetValue() + ": " + DeprecatedFormatVersion)
return LoadV1(cTextureAni, *pTextureAniElement);
// No longer supported format version
} else if (nVersion >= 0) {
PL_LOG(Warning, cDocument.GetValue() + ": " + NoLongerSupportedFormatVersion)
// Invalid format version (negative!)
} else {
PL_LOG(Error, cDocument.GetValue() + ": " + InvalidFormatVersion)
}
} else {
PL_LOG(Error, "Can't find 'TextureAnimation' element")
}
} else {
PL_LOG(Error, cDocument.GetValue() + ": " + cDocument.GetErrorDesc())
}
// Error!
return false;
}
bool TextureAniLoaderPL::Save(const TextureAni &cTextureAni, File &cFile)
{
// Create XML document
XmlDocument cDocument;
// Add declaration
XmlDeclaration *pDeclaration = new XmlDeclaration("1.0", "", "");
cDocument.LinkEndChild(*pDeclaration);
// Add texture animation
XmlElement *pTextureAniElement = new XmlElement("TextureAnimation");
pTextureAniElement->SetAttribute("Version", "1");
// Add texture frames
if (cTextureAni.GetTextureFrames().GetNumOfElements()) {
XmlElement *pTextureFramesElement = new XmlElement("TextureFrames");
// Loop through all frames
for (uint32 i=0; i<cTextureAni.GetTextureFrames().GetNumOfElements(); i++) {
// Get the frame information
const TextureAni::TextureFrame *pTextureFrame = cTextureAni.GetTextureFrames()[i];
if (pTextureFrame) {
XmlElement *pFrameElement = new XmlElement("Frame");
if (pTextureFrame->pTextureHandler && pTextureFrame->pTextureHandler->GetResource()) {
// Add value
XmlText *pValue = new XmlText(pTextureFrame->pTextureHandler->GetResource()->GetName());
pFrameElement->LinkEndChild(*pValue);
}
// Link frame element
pTextureFramesElement->LinkEndChild(*pFrameElement);
}
}
// Link texture frames element
pTextureAniElement->LinkEndChild(*pTextureFramesElement);
}
// Add matrix frames
if (cTextureAni.GetMatrixFrames().GetNumOfElements()) {
XmlElement *pMatrixFramesElement = new XmlElement("MatrixFrames");
// Loop through all frames
for (uint32 i=0; i<cTextureAni.GetMatrixFrames().GetNumOfElements(); i++) {
// Get the frame information
const TextureAni::MatrixFrame *pMatrixFrame = cTextureAni.GetMatrixFrames()[i];
if (pMatrixFrame) {
XmlElement *pFrameElement = new XmlElement("Frame");
// Add position
if (pMatrixFrame->vTranslation != Vector3::Zero)
pFrameElement->SetAttribute("Position", pMatrixFrame->vTranslation.ToString());
// Add rotation
if (pMatrixFrame->vRotation != Vector3::Zero)
pFrameElement->SetAttribute("Rotation", pMatrixFrame->vRotation.ToString());
// Add scale
if (pMatrixFrame->vScale != Vector3::One)
pFrameElement->SetAttribute("Scale", pMatrixFrame->vScale.ToString());
// Link frame element
pMatrixFramesElement->LinkEndChild(*pFrameElement);
}
}
// Link matrix frames element
pTextureAniElement->LinkEndChild(*pMatrixFramesElement);
}
// Add color frames
if (cTextureAni.GetColorFrames().GetNumOfElements()) {
XmlElement *pColorFramesElement = new XmlElement("ColorFrames");
// Loop through all frames
for (uint32 i=0; i<cTextureAni.GetColorFrames().GetNumOfElements(); i++) {
// Get the frame information
const TextureAni::ColorFrame *pColorFrame = cTextureAni.GetColorFrames()[i];
if (pColorFrame) {
XmlElement *pFrameElement = new XmlElement("Frame");
// Add value
XmlText *pValue = new XmlText(pColorFrame->vColor.ToString());
pFrameElement->LinkEndChild(*pValue);
// Link frame element
pColorFramesElement->LinkEndChild(*pFrameElement);
}
}
// Link color frames element
pTextureAniElement->LinkEndChild(*pColorFramesElement);
}
// Add texture animation information
AddAniInfoManager(*pTextureAniElement, cTextureAni.GetTextureAnimationManager(), "Texture");
// Add matrix animation information
AddAniInfoManager(*pTextureAniElement, cTextureAni.GetMatrixAnimationManager(), "Matrix");
// Add color animation information
AddAniInfoManager(*pTextureAniElement, cTextureAni.GetColorAnimationManager(), "Color");
// Link texture animation element
cDocument.LinkEndChild(*pTextureAniElement);
// Save settings
cDocument.Save(cFile);
// Done
return true;
}
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
/**
* @brief
* Default constructor
*/
TextureAniLoaderPL::TextureAniLoaderPL()
{
}
/**
* @brief
* Destructor
*/
TextureAniLoaderPL::~TextureAniLoaderPL()
{
}
//[-------------------------------------------------------]
//[ Private functions ]
//[-------------------------------------------------------]
/**
* @brief
* Loader implementation for format version 1
*/
bool TextureAniLoaderPL::LoadV1(TextureAni &cTextureAni, const XmlElement &cTextureAniElement) const
{
// Iterate through all texture frames
const XmlNode *pTextureFramesNode = cTextureAniElement.GetFirstChild("TextureFrames");
while (pTextureFramesNode) {
// Iterate through all texture frames
const XmlNode *pTextureFrameNode = pTextureFramesNode->GetFirstChild("Frame");
while (pTextureFrameNode) {
// Get value
const XmlNode *pNode = pTextureFrameNode->GetFirstChild();
if (pNode && pNode->GetType() == XmlNode::Text) {
String sValue = pNode->GetValue();
if (sValue.GetLength()) {
// Create texture frame
TextureAni::TextureFrame *pTextureFrame = new TextureAni::TextureFrame;
pTextureFrame->pTextureHandler = new TextureHandler();
pTextureFrame->pTextureHandler->Load(cTextureAni.GetTextureManager(), sValue);
// Add texture frame
cTextureAni.GetTextureFrames().Add(pTextureFrame);
}
}
// Next node, please
pTextureFrameNode = pTextureFramesNode->IterateChildren("Frame", pTextureFrameNode);
}
// Next node, please
pTextureFramesNode = cTextureAniElement.IterateChildren("TextureFrames", pTextureFramesNode);
}
// Iterate through all matrix frames
const XmlNode *pMatrixFramesNode = cTextureAniElement.GetFirstChild("MatrixFrames");
while (pMatrixFramesNode) {
// Iterate through all matrix frames
const XmlElement *pMatrixFrameElement = pMatrixFramesNode->GetFirstChildElement("Frame");
while (pMatrixFrameElement) {
// Create and add matrix frame
TextureAni::MatrixFrame *pMatrixFrame = new TextureAni::MatrixFrame;
cTextureAni.GetMatrixFrames().Add(pMatrixFrame);
pMatrixFrame->vScale = Vector3::One;
// Position
String sValue = pMatrixFrameElement->GetAttribute("Position");
if (sValue.GetLength())
pMatrixFrame->vTranslation.FromString(sValue);
// Rotation
sValue = pMatrixFrameElement->GetAttribute("Rotation");
if (sValue.GetLength())
pMatrixFrame->vRotation.FromString(sValue);
// Scale
sValue = pMatrixFrameElement->GetAttribute("Scale");
if (sValue.GetLength())
pMatrixFrame->vScale.FromString(sValue);
// Next element, please
pMatrixFrameElement = pMatrixFrameElement->GetNextSiblingElement("Frame");
}
// Next node, please
pMatrixFramesNode = cTextureAniElement.IterateChildren("MatrixFrames", pMatrixFramesNode);
}
// Iterate through all color frames
const XmlNode *pColorFramesNode = cTextureAniElement.GetFirstChild("ColorFrames");
while (pColorFramesNode) {
// Iterate through all color frames
const XmlNode *pColorFrameNode = pColorFramesNode->GetFirstChild("Frame");
while (pColorFrameNode) {
// Get value
const XmlNode *pNode = pColorFrameNode->GetFirstChild();
if (pNode && pNode->GetType() == XmlNode::Text) {
const String sValue = pNode->GetValue();
if (sValue.GetLength()) {
// Create and add color frame
TextureAni::ColorFrame *pColorFrame = new TextureAni::ColorFrame;
cTextureAni.GetColorFrames().Add(pColorFrame);
pColorFrame->vColor.FromString(sValue);
}
}
// Next node, please
pColorFrameNode = pColorFramesNode->IterateChildren("Frame", pColorFrameNode);
}
// Next element, please
pColorFramesNode = cTextureAniElement.IterateChildren("ColorFrames", pColorFramesNode);
}
// Iterate through all animations
int nValue;
float fValue;
const XmlElement *pAnimationElement = cTextureAniElement.GetFirstChildElement("Animation");
while (pAnimationElement) {
AniInfo *pAnimation = nullptr;
uint32 nFrames = 0;
// Type
String sValue = pAnimationElement->GetAttribute("Type");
if (sValue.GetLength()) {
// Texture
if (sValue == "Texture") {
cTextureAni.CreateStandardTextureAnimation();
pAnimation = cTextureAni.GetTextureAnimationManager().Create();
pAnimation->SetType(0);
// Matrix
} else if (sValue == "Matrix") {
cTextureAni.CreateStandardMatrixAnimation();
pAnimation = cTextureAni.GetMatrixAnimationManager().Create();
pAnimation->SetType(1);
// Color
} else if (sValue == "Color") {
cTextureAni.CreateStandardColorAnimation();
pAnimation = cTextureAni.GetColorAnimationManager().Create();
pAnimation->SetType(2);
}
if (pAnimation) {
switch (pAnimation->GetType()) {
case 0:
nFrames = cTextureAni.GetTextureFrames().GetNumOfElements();
break;
case 1:
nFrames = cTextureAni.GetMatrixFrames().GetNumOfElements();
break;
case 2:
nFrames = cTextureAni.GetColorFrames().GetNumOfElements();
break;
}
}
}
if (pAnimation) {
// Name
sValue = pAnimationElement->GetAttribute("Name");
if (sValue.GetLength())
pAnimation->SetName(sValue);
// Start
if (pAnimationElement->QueryIntAttribute("Start", &nValue) == XmlBase::Success) {
if (nValue >= static_cast<int>(nFrames))
pAnimation->SetStartFrame(nFrames-1);
else {
if (nValue < 0)
nValue = 0;
pAnimation->SetStartFrame(nValue);
}
}
// End
if (pAnimationElement->QueryIntAttribute("End", &nValue) == XmlBase::Success) {
if (nValue >= static_cast<int>(nFrames))
pAnimation->SetEndFrame(nFrames-1);
else {
if (nValue < 0)
nValue = 0;
pAnimation->SetEndFrame(nValue);
}
}
// Speed
if (pAnimationElement->QueryFloatAttribute("Speed", &fValue) == XmlBase::Success)
pAnimation->SetSpeed(fValue);
// Loop
sValue = pAnimationElement->GetAttribute("Loop");
if (sValue.GetLength()) {
if (sValue.GetBool())
pAnimation->SetFlags(pAnimation->GetFlags() | AnimationInfo::Loop);
else
pAnimation->SetFlags(pAnimation->GetFlags() & ~AnimationInfo::Loop);
}
// PingPong
sValue = pAnimationElement->GetAttribute("PingPong");
if (sValue.GetLength()) {
if (sValue.GetBool())
pAnimation->SetFlags(pAnimation->GetFlags() | AnimationInfo::PingPong);
else
pAnimation->SetFlags(pAnimation->GetFlags() & ~AnimationInfo::PingPong);
}
// Iterate through all frames
const XmlNode *pFrameNode = pAnimationElement->GetFirstChild("Frame");
while (pFrameNode) {
// Is this an XML element?
if (pFrameNode->GetType() == XmlNode::Element) {
const XmlElement *pFrameElement = static_cast<const XmlElement*>(pFrameNode);
// ID
nValue = -1;
if (pFrameElement->QueryIntAttribute("ID", &nValue) == XmlBase::Success &&
nValue >= 0 && nValue < static_cast<int>(nFrames)) {
// Speed
float fSpeed = 1.0f;
sValue = pFrameElement->GetAttribute("Speed");
if (sValue.GetLength())
fSpeed = sValue.GetFloat();
// Set
pAnimation->GetFrameInfo(nValue)->SetSpeed(fSpeed);
}
}
// Next node, please
pFrameNode = pAnimationElement->IterateChildren("Frame", pFrameNode);
}
// Iterate through all events
const XmlNode *pEventNode = pAnimationElement->GetFirstChild("Event");
while (pEventNode) {
// Is this an XML element?
if (pEventNode->GetType() == XmlNode::Element) {
const XmlElement *pEventElement = static_cast<const XmlElement*>(pEventNode);
// FrameID
int nFrameID = -1;
if (pEventElement->QueryIntAttribute("FrameID", &nFrameID) == XmlBase::Success &&
nFrameID >= 0 && nFrameID < static_cast<int>(nFrames)) {
// ID
int nID = 0;
if (pEventElement->QueryIntAttribute("ID", &nID) == XmlBase::Success) {
// Create the event, added automatically to the event manager
new AnimationEvent(nID, nFrameID, &pAnimation->GetEventManager());
}
}
}
// Next node, please
pEventNode = pAnimationElement->IterateChildren("Event", pEventNode);
}
}
// Next element, please
pAnimationElement = pAnimationElement->GetNextSiblingElement("Animation");
}
// Check if there is at least one frame per animation type
if (!cTextureAni.GetTextureFrames().GetNumOfElements()) { // No texture frames found
// Create and add standard texture frame
TextureAni::TextureFrame *pTextureFrame = new TextureAni::TextureFrame;
pTextureFrame->pTextureHandler = new TextureHandler();
pTextureFrame->pTextureHandler->Load(cTextureAni.GetTextureManager(), TextureManager::Default);
cTextureAni.GetTextureFrames().Add(pTextureFrame);
}
if (!cTextureAni.GetMatrixFrames().GetNumOfElements()) { // No matrix frames found
// Create and add standard matrix frame
TextureAni::MatrixFrame *pMatrixFrame = new TextureAni::MatrixFrame;
pMatrixFrame->vScale = Vector3::One;
cTextureAni.GetMatrixFrames().Add(pMatrixFrame);
}
if (!cTextureAni.GetColorFrames().GetNumOfElements()) { // No color frames found
// Create and add standard color frame
TextureAni::ColorFrame *pColorFrame = new TextureAni::ColorFrame;
pColorFrame->vColor = 1.0f;
cTextureAni.GetColorFrames().Add(pColorFrame);
}
// Create standard animations (if there aren't created until now)
cTextureAni.CreateStandardTextureAnimation();
cTextureAni.CreateStandardMatrixAnimation();
cTextureAni.CreateStandardColorAnimation();
// Done
return true;
}
/**
* @brief
* Adds an animation information manager to the given XML element
*/
void TextureAniLoaderPL::AddAniInfoManager(XmlElement &cElement, const AniInfoManager &cAniInfoManager, const String &sType) const
{
// Loop through all animation information
for (uint32 i=0; i<cAniInfoManager.GetNumOfElements(); i++) {
// Get animation information
const AniInfo *pAnimation = cAniInfoManager.GetByIndex(i);
if (pAnimation) {
XmlElement *pAnimationElement = new XmlElement("Animation");
// Type
pAnimationElement->SetAttribute("Type", sType);
// Name
if (pAnimation->GetName().GetLength())
pAnimationElement->SetAttribute("Name", pAnimation->GetName());
// Start
if (pAnimation->GetStartFrame() != 0)
pAnimationElement->SetAttribute("Start", pAnimation->GetStartFrame());
// End
if (pAnimation->GetEndFrame() != 0)
pAnimationElement->SetAttribute("End", pAnimation->GetEndFrame());
// Speed
if (pAnimation->GetSpeed() != 24.0f)
pAnimationElement->SetAttribute("Speed", String(pAnimation->GetSpeed()));
// Loop
if (pAnimation->GetFlags() & AnimationInfo::Loop)
pAnimationElement->SetAttribute("Loop", "1");
// PingPong
if (pAnimation->GetFlags() & AnimationInfo::PingPong)
pAnimationElement->SetAttribute("PingPong", "1");
// Add frame information
uint32 nNumOfFrames = pAnimation->GetNumOfFrames();
for (uint32 nFrameID=0; nFrameID<nNumOfFrames; nFrameID++) {
// Get frame information
const AnimationFrameInfo *pFrameInfo = pAnimation->GetFrameInfo(nFrameID);
// Add?
if (pFrameInfo && pFrameInfo->GetSpeed() != 1.0f) {
XmlElement *pFrameInfoElement = new XmlElement("Frame");
// ID
pAnimationElement->SetAttribute("ID", nFrameID);
// Speed
pAnimationElement->SetAttribute("Speed", String(pFrameInfo->GetSpeed()));
// Link frame information element
pAnimationElement->LinkEndChild(*pFrameInfoElement);
}
}
// Add events
const AnimationEventManager &cEventManager = pAnimation->GetEventManager();
for (uint32 nEvent=0; nEvent<cEventManager.GetNumOfElements(); nEvent++) {
// Get the event
const AnimationEvent *pEvent = cEventManager.GetByIndex(nEvent);
if (pEvent) {
XmlElement *pEventElement = new XmlElement("Event");
// FrameID
pEventElement->SetAttribute("FrameID", pEvent->GetFrame());
// ID
pEventElement->SetAttribute("ID", pEvent->GetID());
// Link event element
pAnimationElement->LinkEndChild(*pEventElement);
}
}
// Link animation element
cElement.LinkEndChild(*pAnimationElement);
}
}
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLRenderer
| 33.488255
| 130
| 0.66346
|
ktotheoz
|
72a77e4b706945954b782607100be05740d3aa8e
| 553
|
cpp
|
C++
|
src/world/particles/systems/blueorbparticlesystem.cpp
|
Eae02/tank-game
|
0c526b177ccc15dd49e3228489163f13335040db
|
[
"Zlib"
] | null | null | null |
src/world/particles/systems/blueorbparticlesystem.cpp
|
Eae02/tank-game
|
0c526b177ccc15dd49e3228489163f13335040db
|
[
"Zlib"
] | null | null | null |
src/world/particles/systems/blueorbparticlesystem.cpp
|
Eae02/tank-game
|
0c526b177ccc15dd49e3228489163f13335040db
|
[
"Zlib"
] | null | null | null |
#include "blueorbparticlesystem.h"
namespace TankGame
{
BlueOrbParticleSystem::BlueOrbParticleSystem(ParticlesManager& particlesManager)
: m_blueOrbEmitter(particlesManager)
{
}
ParticleEmitter* BlueOrbParticleSystem::GetEmitter(size_t n)
{
return &m_blueOrbEmitter;
}
size_t BlueOrbParticleSystem::GetEmitterCount() const
{
return 1;
}
void BlueOrbParticleSystem::SetTransformationProvider(const ITransformationProvider* transformationProvider)
{
m_blueOrbEmitter.SetTransformationProvider(transformationProvider);
}
}
| 21.269231
| 109
| 0.802893
|
Eae02
|
72a9ebb06e37ccf9dca67a53cab90886c7b724f0
| 34,270
|
cpp
|
C++
|
src/rrgenerator.cpp
|
sischkg/nxnsattack
|
c20896e40187bbcacb5c0255ff8f3cc7d0592126
|
[
"MIT"
] | 5
|
2020-05-22T10:01:51.000Z
|
2022-01-01T04:45:14.000Z
|
src/rrgenerator.cpp
|
sischkg/dns-fuzz-server
|
6f45079014e745537c2f564fdad069974e727da1
|
[
"MIT"
] | 1
|
2020-06-07T14:09:44.000Z
|
2020-06-07T14:09:44.000Z
|
src/rrgenerator.cpp
|
sischkg/dns-fuzz-server
|
6f45079014e745537c2f564fdad069974e727da1
|
[
"MIT"
] | 2
|
2020-03-10T03:06:20.000Z
|
2021-07-25T15:07:45.000Z
|
#include "rrgenerator.hpp"
#include <boost/noncopyable.hpp>
#include <sys/types.h>
#include <unistd.h>
#include <cstdlib>
#include <sstream>
namespace dns
{
/**********************************************************
* RandomGenarator
**********************************************************/
RandomGenerator *RandomGenerator::mInstance = nullptr;
RandomGenerator::RandomGenerator()
: mGenerator( static_cast<unsigned long>(time(nullptr)) )
{
std::srand( getpid() * time( nullptr ) );
}
uint32_t RandomGenerator::rand( uint32_t base )
{
if ( base == 0 )
return 0;
boost::mutex::scoped_lock lock( mMutex );
boost::uniform_smallint<> dst( 0, base);
uint32_t v = dst( mGenerator );
return v;
}
PacketData RandomGenerator::randStream( unsigned int size )
{
PacketData stream;
stream.reserve( size );
for ( unsigned int i = 0 ; i < size ; i++ )
stream.push_back( this->rand( 0xff ) );
return stream;
}
PacketData RandomGenerator::randSizeStream( unsigned int max_size )
{
unsigned int size = rand( max_size );
PacketData stream;
stream.reserve( size );
for ( unsigned int i = 0 ; i < size ; i++ )
stream.push_back( this->rand( 0xff ) );
return stream;
}
RandomGenerator *RandomGenerator::getInstance()
{
if ( mInstance == nullptr )
mInstance = new RandomGenerator();
return mInstance;
}
/**********************************************************
* DomainnameGenarator
**********************************************************/
std::string DomainnameGenerator::generateLabel()
{
std::string label;
if ( getRandom( 37 ) == 0 )
return "*";
unsigned int label_size = 1 + getRandom( 62 );
label.reserve( label_size );
for ( unsigned int i = 0 ; i < label_size ; i++ )
label.push_back( getRandom( 0xff ) );
return label;
}
Domainname DomainnameGenerator::generate()
{
unsigned int label_count = 1 + getRandom( 100 );
unsigned int domainname_size = 0;
std::deque<std::string> labels;
for ( unsigned int i = 0 ; i < label_count ; i++ ) {
auto label = generateLabel();
if ( domainname_size + label.size() + 1 >= 255 )
break;
labels.push_back( label );
domainname_size += ( label.size() + 1 );
}
return Domainname( labels );
}
Domainname DomainnameGenerator::generate( const Domainname &hint1, const Domainname &hint2 )
{
Domainname hint = hint1;
Domainname result = hint1;
if ( hint2 != "" && getRandom( 2 ) == 0 ) {
hint = hint2;
result = hint2;
}
switch ( getRandom( 3 ) ) {
case 0:
return result;
case 1: // erase labels;
{
unsigned int erased_label_count = getRandom( hint.getLabels().size() );
for ( unsigned int i = 0 ; i < erased_label_count ; i++ ) {
result.popSubdomain();
}
return result;
}
case 2: // append labels as subdomain;
{
unsigned int label_count = hint.getLabels().size();
unsigned int append_label_count = getRandom( 255 - hint.getLabels().size() );
unsigned int domainname_size = hint.size();
for ( unsigned int i = 0 ; i < append_label_count ; i++ ) {
std::string new_label = generateLabel();
if ( label_count + 1 >= 128 || domainname_size + new_label.size() + 1 >= 255 )
break;
result.addSubdomain( new_label );
domainname_size += ( new_label.size() + 1 );
label_count++;
}
return result;
}
case 3: // replace labels;
{
unsigned int erased_label_count = getRandom( hint.getLabels().size() );
for ( unsigned int i = 0 ; i < erased_label_count ; i++ ) {
result.popSubdomain();
}
unsigned int label_count = result.getLabels().size();
unsigned int append_label_count = getRandom( 255 - result.getLabels().size() );
unsigned int domainname_size = result.size();
for ( unsigned int i = 0 ; i < append_label_count ; i++ ) {
std::string new_label = generateLabel();
if ( label_count + 1 >= 128 || domainname_size + new_label.size() + 1 >= 255 )
break;
result.addSubdomain( new_label );
domainname_size += ( new_label.size() + 1 );
label_count++;
}
return result;
}
default:
throw std::logic_error( "generate domainname error" );
}
}
static Domainname generateDomainname( const Domainname &hint1, const Domainname &hint2 = Domainname() )
{
DomainnameGenerator g;
return g.generate( hint1, hint2 );
}
Domainname generateDomainname()
{
DomainnameGenerator g;
return g.generate();
}
Domainname getDomainname( const MessageInfo &hint )
{
std::vector<Domainname> names;
for ( auto rr : hint.getQuestionSection() ) {
names.push_back( rr.mDomainname );
}
for ( auto rr : hint.getAnswerSection() ) {
names.push_back( rr.mDomainname );
}
for ( auto rr : hint.getAuthoritySection() ) {
names.push_back( rr.mDomainname );
}
for ( auto rr : hint.getAdditionalSection() ) {
names.push_back( rr.mDomainname );
}
unsigned int index = getRandom( names.size() - 1 );
return names.at( index );
}
Domainname generateAlgorithmName()
{
if ( withChance( 0.7 ) ) {
const char *algorithms[] = {
"gss-tsig",
"HMAC-MD5.SIG-ALG.REG.INT",
"hmac-sha1",
"hmac-sha224",
"hmac-sha256",
"hmac-sha384",
"hmac-sha512",
};
return (Domainname)algorithms[ getRandom( sizeof(algorithms)/sizeof(char *) - 1 ) ];
}
else {
return generateDomainname();
}
}
/**********************************************************
* XNAMEGenarator
**********************************************************/
template<class T>
std::shared_ptr<RDATA> XNameGenerator<T>::generate( const MessageInfo &hint, const Domainname &hint2 )
{
Domainname hint_name;
uint32_t qdcount = hint.getQuestionSection().size();
uint32_t ancount = hint.getAnswerSection().size();
uint32_t nscount = hint.getAuthoritySection().size();
uint32_t adcount = hint.getAdditionalSection().size();
uint32_t index = getRandom( qdcount + ancount + nscount + adcount - 1 );
if ( index < qdcount ) {
hint_name = hint.getQuestionSection().at( index ).mDomainname;
}
else if ( index < qdcount + ancount ) {
hint_name = hint.getAnswerSection().at( index - qdcount ).mDomainname;
}
else if ( index < qdcount + ancount + nscount ) {
hint_name = hint.getAuthoritySection().at( index - qdcount - ancount ).mDomainname;
}
else if ( index < qdcount + ancount + nscount + adcount ) {
hint_name = hint.getAdditionalSection().at( index - qdcount - ancount - nscount ).mDomainname;
}
else {
throw std::logic_error( "invalid index of XNameGenerator::generate( hint )" );
}
return std::shared_ptr<RDATA>( new T( DomainnameGenerator().generate( hint_name, hint2 ) ) );
}
template<class T>
std::shared_ptr<RDATA> XNameGenerator<T>::generate()
{
return std::shared_ptr<RDATA>( new T( DomainnameGenerator().generate() ) );
}
/**********************************************************
* RAWGenarator
**********************************************************/
std::shared_ptr<RDATA> RawGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
return generate();
}
std::shared_ptr<RDATA> RawGenerator::generate()
{
return std::shared_ptr<RDATA>( new RecordRaw( getRandom( 0x3ff ), getRandomSizeStream( 0xff ) ) );
}
/**********************************************************
* AGenarator
**********************************************************/
std::shared_ptr<RDATA> AGenerator::generate( const MessageInfo &hint, const Domainname &hint2 )
{
std::vector<std::shared_ptr<RDATA> > record_a_list;
for ( auto rr : hint.getAnswerSection() ) {
if ( rr.mType == TYPE_A ) {
record_a_list.push_back( rr.mRData );
}
}
for ( auto rr : hint.getAuthoritySection() ) {
if ( rr.mType == TYPE_A ) {
record_a_list.push_back( rr.mRData );
}
}
for ( auto rr : hint.getAdditionalSection() ) {
if ( rr.mType == TYPE_A ) {
record_a_list.push_back( rr.mRData );
}
}
if ( record_a_list.size() == 0 )
return generate();
unsigned int index = getRandom( record_a_list.size() - 1 );
return std::shared_ptr<RDATA>( record_a_list.at( index )->clone() );
}
std::shared_ptr<RDATA> AGenerator::generate()
{
return std::shared_ptr<RDATA>( new RecordA( getRandom() ) );
}
/**********************************************************
* WKSGenarator
**********************************************************/
std::shared_ptr<RDATA> WKSGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
return generate();
}
std::shared_ptr<RDATA> WKSGenerator::generate()
{
std::vector<Type> bitmap;
if ( getRandom( 32 ) == 0 )
bitmap.resize( 0 );
else if ( getRandom( 32 ) == 0 ) {
bitmap.resize( 256 * 256 );
for ( unsigned int i = 0 ; i < bitmap.size() ; i++ )
bitmap[i] = i;
}
else {
bitmap.resize( getRandom( 0xffff ) );
for ( unsigned int i = 0 ; i < bitmap.size() ; i++ )
bitmap[i] = getRandom( 0xffff);
}
return std::shared_ptr<RDATA>( new RecordWKS( getRandom(), getRandom( 255 ), bitmap ) );
}
/**********************************************************
* AAAAGenarator
**********************************************************/
std::shared_ptr<RDATA> AAAAGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
std::vector<std::shared_ptr<RDATA> > record_a_list;
for ( auto rr : hint1.getAnswerSection() ) {
if ( rr.mType == TYPE_AAAA ) {
record_a_list.push_back( rr.mRData );
}
}
for ( auto rr : hint1.getAuthoritySection() ) {
if ( rr.mType == TYPE_AAAA ) {
record_a_list.push_back( rr.mRData );
}
}
for ( auto rr : hint1.getAdditionalSection() ) {
if ( rr.mType == TYPE_AAAA ) {
record_a_list.push_back( rr.mRData );
}
}
if ( record_a_list.size() == 0 )
return generate();
unsigned int index = getRandom( record_a_list.size() - 1 );
return std::shared_ptr<RDATA>( record_a_list.at( index )->clone() );
}
std::shared_ptr<RDATA> AAAAGenerator::generate()
{
PacketData sin_addr = getRandomStream( 16 );
return std::shared_ptr<RDATA>( new RecordAAAA( &sin_addr[0] ) );
}
/**********************************************************
* SOAGenarator
**********************************************************/
std::shared_ptr<RDATA> SOAGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
return std::shared_ptr<RDATA>( new RecordSOA( getDomainname( hint1 ),
getDomainname( hint1 ),
getRandom(),
getRandom(),
getRandom(),
getRandom(),
getRandom() ) );
}
std::shared_ptr<RDATA> SOAGenerator::generate()
{
return std::shared_ptr<RDATA>( new RecordSOA( generateDomainname(),
generateDomainname(),
getRandom(),
getRandom(),
getRandom(),
getRandom(),
getRandom() ));
}
/**********************************************************
* SRVGenarator
**********************************************************/
std::shared_ptr<RDATA> SRVGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
return std::shared_ptr<RDATA>( new RecordSRV( getRandom( 0xffff ),
getRandom( 0xffff ),
getRandom( 0xffff ),
getDomainname( hint1 ) ) );
}
std::shared_ptr<RDATA> SRVGenerator::generate()
{
return std::shared_ptr<RDATA>( new RecordSRV( getRandom( 0xffff ),
getRandom( 0xffff ),
getRandom( 0xffff ),
generateDomainname() ) );
}
/**********************************************************
* RRSIGGenarator
**********************************************************/
std::shared_ptr<RDATA> RRSIGGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
PacketData signature = getRandomSizeStream( 0xff );
std::shared_ptr<RDATA> p( new RecordRRSIG( getRandom( 0xffff ), // type covered
getRandom( 0xff ), // algorithm
getRandom( 0xff ), // label
getRandom(), // original ttl
getRandom(), // expiration
getRandom(), // inception
getRandom( 0xffff ), // key tag
generateDomainname( getDomainname( hint1 ), hint2 ),
signature ) );
return p;
}
std::shared_ptr<RDATA> RRSIGGenerator::generate()
{
PacketData signature = getRandomSizeStream( 0xff );
return std::shared_ptr<RDATA>( new RecordRRSIG( getRandom( 0xffff ), // type covered
getRandom( 0xff ), // algorithm
getRandom( 0xff ), // label
getRandom(), // original ttl
getRandom(), // expiration
getRandom(), // inception
getRandom( 0xffff ), // key tag
generateDomainname(),
signature ) );
}
/**********************************************************
* DNSKEYGenarator
**********************************************************/
std::shared_ptr<RDATA> DNSKEYGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
PacketData public_key = getRandomStream( 132 );
return std::shared_ptr<RDATA>( new RecordDNSKEY( getRandom() % 2 ? RecordDNSKEY::KSK : RecordDNSKEY::ZSK,
RecordDNSKEY::RSASHA1,
public_key ) );
}
std::shared_ptr<RDATA> DNSKEYGenerator::generate()
{
PacketData public_key = getRandomStream( 132 );
return std::shared_ptr<RDATA>( new RecordDNSKEY( getRandom() % 2 ? RecordDNSKEY::KSK : RecordDNSKEY::ZSK,
RecordDNSKEY::RSASHA1,
public_key ) );
}
/**********************************************************
* DSGenarator
**********************************************************/
std::shared_ptr<RDATA> DSGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
if ( getRandom( 2 ) ) {
PacketData hash = getRandomStream( 20 );
return std::shared_ptr<RDATA>( new RecordDS( getRandom( 0xffff ),
5,
1,
hash ) );
}
else {
PacketData hash = getRandomStream( 32 );
return std::shared_ptr<RDATA>( new RecordDS( getRandom( 0xffff ),
5,
2,
hash ) );
}
}
std::shared_ptr<RDATA> DSGenerator::generate()
{
if ( getRandom( 2 ) ) {
PacketData hash = getRandomStream( 40 );
return std::shared_ptr<RDATA>( new RecordDS( getRandom( 0xffff ),
5,
1,
hash ) );
}
else {
PacketData hash = getRandomStream( 64 );
return std::shared_ptr<RDATA>( new RecordDS( getRandom( 0xffff ),
5,
2,
hash ) );
}
}
/**********************************************************
* NSECGenarator
**********************************************************/
std::shared_ptr<RDATA> NSECGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
std::vector<Type> types;
unsigned int type_count = getRandom( 4 );
types.reserve( type_count );
for ( unsigned int i = 0 ; i < type_count ; i++ ) {
types.push_back( getRandom( 0xffff ) );
}
return std::shared_ptr<RDATA>( new RecordNSEC( generateDomainname( getDomainname( hint1 ), hint2 ),
types ) );
}
std::shared_ptr<RDATA> NSECGenerator::generate()
{
std::vector<Type> types;
unsigned int type_count = getRandom( 0xffff );
types.reserve( type_count );
for ( unsigned int i = 0 ; i < type_count ; i++ ) {
types.push_back( getRandom( 0xffff ) );
}
return std::shared_ptr<RDATA>( new RecordNSEC( generateDomainname(), types ) );
}
/**********************************************************
* NSEC3Genarator
**********************************************************/
std::shared_ptr<RDATA> NSEC3Generator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
return generate();
}
std::shared_ptr<RDATA> NSEC3Generator::generate()
{
uint8_t optout = 0x07;
if ( getRandom( 8 ) ) {
optout = 0;
}
std::vector<Type> types;
unsigned int type_count = getRandom( 4 );
for ( unsigned int i = 0 ; i < type_count ; i++ ) {
types.push_back( getRandom( 0xffff ) );
}
return std::shared_ptr<RDATA>( new RecordNSEC3( 0x01,
optout,
getRandom( 0x00ff ),
getRandomSizeStream( 0xff ),
getRandomStream( 20 ),
types ) );
}
/**********************************************************
* NSEC3PARAMGenarator
**********************************************************/
std::shared_ptr<RDATA> NSEC3PARAMGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
return generate();
}
std::shared_ptr<RDATA> NSEC3PARAMGenerator::generate()
{
uint8_t optout = 0x07;
if ( getRandom( 8 ) ) {
optout = 0;
}
return std::shared_ptr<RDATA>( new RecordNSEC3PARAM( 0x01,
optout,
getRandom( 0x00ff ),
getRandomSizeStream( 0xff ) ) );
}
/**********************************************************
* TLSAGenarator
**********************************************************/
std::shared_ptr<RDATA> TLSAGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
return generate();
}
std::shared_ptr<RDATA> TLSAGenerator::generate()
{
return std::shared_ptr<RDATA>( new RecordTLSA( getRandom( 0xff ),
getRandom( 0xff ),
getRandom( 0xff ),
getRandomSizeStream( 0x01ff ) ) );
}
/**********************************************************
* SIGGenarator
**********************************************************/
std::shared_ptr<RDATA> SIGGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
PacketData signature = getRandomStream( 256 );
std::shared_ptr<RDATA> p( new RecordSIG( getRandom( 0xffff ), // type covered
getRandom( 0xff ), // algorithm
getRandom( 0xff ), // label
getRandom(), // original ttl
getRandom(), // expiration
getRandom(), // inception
getRandom( 0xffff ), // key tag
generateDomainname( getDomainname( hint1 ), hint2 ),
signature ) );
return p;
}
std::shared_ptr<RDATA> SIGGenerator::generate()
{
PacketData signature = getRandomSizeStream( 256 );
return std::shared_ptr<RDATA>( new RecordSIG( getRandom( 0xffff ), // type covered
getRandom( 0xff ), // algorithm
getRandom( 0xff ), // label
getRandom(), // original ttl
getRandom(), // expiration
getRandom(), // inception
getRandom( 0xffff ), // key tag
generateDomainname(),
signature ) );
}
/**********************************************************
* KEYGenarator
**********************************************************/
std::shared_ptr<RDATA> KEYGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
PacketData public_key = getRandomStream( 132 );
return std::shared_ptr<RDATA>( new RecordKEY( 0xffff,
RecordDNSKEY::RSASHA1,
public_key ) );
}
std::shared_ptr<RDATA> KEYGenerator::generate()
{
PacketData public_key = getRandomStream( 132 );
return std::shared_ptr<RDATA>( new RecordKEY( getRandom( 0xffff ),
RecordDNSKEY::RSASHA1,
public_key ) );
}
/**********************************************************
* NXTGenarator
**********************************************************/
std::shared_ptr<RDATA> NXTGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
std::vector<Type> types;
unsigned int type_count = getRandom( 0xffff );
types.reserve( type_count );
for ( unsigned int i = 0 ; i < type_count ; i++ ) {
types.push_back( getRandom( 0xffff ) );
}
return std::shared_ptr<RDATA>( new RecordNXT( generateDomainname( getDomainname( hint1 ), hint2 ),
types ) );
}
std::shared_ptr<RDATA> NXTGenerator::generate()
{
std::vector<Type> types;
unsigned int type_count = getRandom( 0xffff );
types.reserve( type_count );
for ( unsigned int i = 0 ; i < type_count ; i++ ) {
types.push_back( getRandom( 0xffff ) );
}
return std::shared_ptr<RDATA>( new RecordNXT( generateDomainname(), types ) );
}
/**********************************************************
* TKEYGenarator
**********************************************************/
std::shared_ptr<RDATA> TKEYGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
PacketData signature = getRandomSizeStream( 0xff );
PacketData other = getRandomSizeStream( 0xff );
std::shared_ptr<RDATA> p( new RecordTKEY( generateDomainname( getDomainname( hint1 ), hint2 ), // domain
generateAlgorithmName(), // algorithm
getRandom(), // inception
getRandom(), // expiration
getRandom( 0xff ),
getRandom( 0xff ),
signature,
other) );
return p;
}
std::shared_ptr<RDATA> TKEYGenerator::generate()
{
PacketData signature = getRandomSizeStream( 0xff );
PacketData other = getRandomSizeStream( 0xff );
std::shared_ptr<RDATA> p( new RecordTKEY( generateDomainname(), // domain
generateAlgorithmName(), // algorithm
getRandom(), // inception
getRandom(), // expiration
getRandom(),
getRandom(),
signature ) );
return p;
}
/**********************************************************
* TSIGGenarator
**********************************************************/
std::shared_ptr<RDATA> TSIGGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
PacketData signature = getRandomStream( 16 );
uint64_t signed_time = (uint64_t)getRandom() + (((uint64_t)getRandom() ) << 32 );
PacketData other = getRandomSizeStream( 0xff );
return std::shared_ptr<RDATA>( new RecordTSIGData( generateDomainname( getDomainname( hint1 ), hint2 ), // domain
generateAlgorithmName(), // algorithm
signed_time, // signed time
getRandom( 0xffff ), // fudge
signature, // mac
getRandom( 0xffff ), // original id
getRandom( 0xffff ), // error
other ) );
}
std::shared_ptr<RDATA> TSIGGenerator::generate()
{
PacketData signature = getRandomStream( 16 );
uint64_t signed_time = (uint64_t)getRandom() + (((uint64_t)getRandom() ) << 32 );
PacketData other = getRandomSizeStream( 0xff );
return std::shared_ptr<RDATA>( new RecordTSIGData( generateDomainname(), // domain
generateAlgorithmName(), // algorithm
signed_time, // signed time
getRandom( 0xffff ), // fudge
signature, // mac
getRandom( 0xffff ), // original id
getRandom( 0xffff ), // error
other ) );
}
/**********************************************************
* ResourceRecordGenarator
**********************************************************/
ResourceRecordGenerator::ResourceRecordGenerator()
{
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new RawGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new NSGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new CNAMEGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new DNAMEGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new AGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new AAAAGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new WKSGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new SOAGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new SRVGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new RRSIGGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new DNSKEYGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new DSGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new NSECGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new NSEC3Generator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new NSEC3PARAMGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new TLSAGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new SIGGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new KEYGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new NXTGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new TKEYGenerator ) );
mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new TSIGGenerator ) );
}
RRSet ResourceRecordGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )
{
Class class_table[] = { CLASS_IN, CLASS_CH, CLASS_HS, CLASS_NONE, CLASS_ANY };
std::shared_ptr<RDATA> resource_data = mGenerators.at( getRandom( mGenerators.size() - 1 ) )->generate( hint1, hint2 );
Domainname owner;
if ( resource_data->type() == TYPE_NSEC3 ) {
std::string hash;
encodeToBase32Hex( getRandomStream( 20 ), hash );
owner = getDomainname( hint1 );
owner.addSubdomain( hash );
}
else {
owner = generateDomainname( getDomainname( hint1 ), hint2 );
}
unsigned int index = getRandom( sizeof(class_table)/sizeof(Class) - 1 );
if ( index >= sizeof(class_table)/sizeof(Class) ) {
throw std::logic_error( "invalid class index" );
}
RRSet rrset( owner,
class_table[index],
resource_data->type(),
getRandom( 0xffffffff ) );
rrset.add( resource_data );
return rrset;
}
std::shared_ptr<OptPseudoRROption> RawOptionGenerator::generate( const MessageInfo &hint )
{
return generate();
}
std::shared_ptr<OptPseudoRROption> RawOptionGenerator::generate()
{
return std::shared_ptr<OptPseudoRROption>( new RAWOption( getRandom( 0x0f ), getRandomSizeStream( 0xff ) ) );
}
std::shared_ptr<OptPseudoRROption> NSIDGenerator::generate( const MessageInfo &hint )
{
return generate();
}
std::shared_ptr<OptPseudoRROption> NSIDGenerator::generate()
{
ssize_t length = getRandom( 0xff );
std::string data;
data.reserve( length );
for ( ssize_t i = 0 ; i < length ; i++ )
data.push_back( getRandom( 0xff ) );
return std::shared_ptr<OptPseudoRROption>( new NSIDOption( data ) );
}
std::shared_ptr<OptPseudoRROption> ClientSubnetGenerator::generate( const MessageInfo &hint )
{
return generate();
}
std::shared_ptr<OptPseudoRROption> ClientSubnetGenerator::generate()
{
if ( getRandom( 2 ) ) {
std::ostringstream os;
os << getRandom( 0xff ) << "." << getRandom( 0xff ) << "." << getRandom( 0xff ) << getRandom( 0xff );
return std::shared_ptr<OptPseudoRROption>( new ClientSubnetOption( ClientSubnetOption::IPv4,
getRandom( 32 ),
getRandom( 32 ),
os.str() ) );
}
else {
std::ostringstream os;
os << std::hex << getRandom( 0xff );
for ( int i = 0 ; i < 15 ; i++ )
os << ":" << getRandom( 0xff );
return std::shared_ptr<OptPseudoRROption>( new ClientSubnetOption( ClientSubnetOption::IPv6,
getRandom( 128 ),
getRandom( 128 ),
os.str() ) );
}
}
std::shared_ptr<OptPseudoRROption> CookieGenerator::generate( const MessageInfo &hint )
{
return generate();
}
std::shared_ptr<OptPseudoRROption> CookieGenerator::generate()
{
PacketData client, server;
unsigned int client_length = getRandom( 64 );
unsigned int server_length = getRandom( 64 );
client.reserve( client_length );
server.reserve( server_length );
for ( unsigned int i = 0 ; i < client_length ; i++ )
client.push_back( getRandom( 0xff ) );
for ( unsigned int i = 0 ; i < server_length ; i++ )
server.push_back( getRandom( 0xff ) );
return std::shared_ptr<OptPseudoRROption>( new CookieOption( client, server ) );
}
std::shared_ptr<OptPseudoRROption> TCPKeepaliveGenerator::generate( const MessageInfo &hint )
{
return generate();
}
std::shared_ptr<OptPseudoRROption> TCPKeepaliveGenerator::generate()
{
uint16_t timeout = 0;
if ( getRandom( 4 ) ) {
timeout = getRandom( 0xffff );
}
return std::shared_ptr<OptPseudoRROption>( new TCPKeepaliveOption( timeout ) );
}
std::shared_ptr<OptPseudoRROption> KeyTagGenerator::generate( const MessageInfo &hint )
{
return generate();
}
std::shared_ptr<OptPseudoRROption> KeyTagGenerator::generate()
{
uint16_t count = getRandom( 0x0fff );
std::vector<uint16_t> tags;
tags.reserve( count );
for ( uint16_t i = 0 ; i < count ; i++ )
tags.push_back( getRandom( 0xffff ) );
return std::shared_ptr<OptPseudoRROption>( new KeyTagOption( tags ) );
}
/**********************************************************
* OptionGenarator
**********************************************************/
OptionGenerator::OptionGenerator()
{
mGenerators.push_back( std::shared_ptr<OptGeneratable>( new RawOptionGenerator ) );
mGenerators.push_back( std::shared_ptr<OptGeneratable>( new NSIDGenerator ) );
mGenerators.push_back( std::shared_ptr<OptGeneratable>( new ClientSubnetGenerator ) );
mGenerators.push_back( std::shared_ptr<OptGeneratable>( new CookieGenerator ) );
mGenerators.push_back( std::shared_ptr<OptGeneratable>( new TCPKeepaliveGenerator ) );
mGenerators.push_back( std::shared_ptr<OptGeneratable>( new KeyTagGenerator ) );
}
void OptionGenerator::generate( MessageInfo &packet )
{
if ( ! packet.isEDNS0() )
return;
std::shared_ptr<OptPseudoRROption> option = mGenerators.at( getRandom( mGenerators.size() - 1 ) )->generate( packet );
packet.addOption( option );
}
}
| 37.008639
| 127
| 0.512372
|
sischkg
|
72b4ba9b6c2f3d52b44c645fc8761d3545940fa2
| 9,688
|
cpp
|
C++
|
src/nfagraph/ng_utf8.cpp
|
a16bitsysop/hyperscan
|
2819dc3d1b796e28d23140cb135077a709b7d28a
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] | 146
|
2021-02-15T14:13:57.000Z
|
2022-03-30T19:06:13.000Z
|
src/nfagraph/ng_utf8.cpp
|
a16bitsysop/hyperscan
|
2819dc3d1b796e28d23140cb135077a709b7d28a
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] | 35
|
2021-01-26T10:21:21.000Z
|
2022-03-23T09:50:20.000Z
|
src/nfagraph/ng_utf8.cpp
|
a16bitsysop/hyperscan
|
2819dc3d1b796e28d23140cb135077a709b7d28a
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] | 12
|
2021-03-26T15:02:20.000Z
|
2022-03-10T13:14:32.000Z
|
/*
* Copyright (c) 2015-2017, Intel Corporation
*
* 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 Intel Corporation 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.
*/
/** \file
* \brief UTF-8 transforms and operations.
*/
#include "ng_utf8.h"
#include "ng.h"
#include "ng_prune.h"
#include "ng_util.h"
#include "compiler/compiler.h"
#include "util/graph_range.h"
#include "util/unicode_def.h"
#include <set>
#include <vector>
using namespace std;
namespace ue2 {
static
void allowIllegal(NGHolder &g, NFAVertex v, u8 pred_char) {
if (in_degree(v, g) != 1) {
DEBUG_PRINTF("unexpected pred\n");
assert(0); /* should be true due to the early stage of this analysis */
return;
}
CharReach &cr = g[v].char_reach;
if (pred_char == 0xe0) {
assert(cr.isSubsetOf(CharReach(0xa0, 0xbf)));
if (cr == CharReach(0xa0, 0xbf)) {
cr |= CharReach(0x80, 0x9f);
}
} else if (pred_char == 0xf0) {
assert(cr.isSubsetOf(CharReach(0x90, 0xbf)));
if (cr == CharReach(0x90, 0xbf)) {
cr |= CharReach(0x80, 0x8f);
}
} else if (pred_char == 0xf4) {
assert(cr.isSubsetOf(CharReach(0x80, 0x8f)));
if (cr == CharReach(0x80, 0x8f)) {
cr |= CharReach(0x90, 0xbf);
}
} else {
assert(0); /* unexpected pred */
}
}
/** \brief Relax forbidden UTF-8 sequences.
*
* Some byte sequences can not appear in valid UTF-8 as they encode code points
* above \\x{10ffff} or they represent overlong encodings. As we require valid
* UTF-8 input, we have no defined behaviour in these cases, as a result we can
* accept them if it simplifies the graph. */
void relaxForbiddenUtf8(NGHolder &g, const ExpressionInfo &expr) {
if (!expr.utf8) {
return;
}
const CharReach e0(0xe0);
const CharReach f0(0xf0);
const CharReach f4(0xf4);
for (auto v : vertices_range(g)) {
const CharReach &cr = g[v].char_reach;
if (cr == e0 || cr == f0 || cr == f4) {
u8 pred_char = cr.find_first();
for (auto t : adjacent_vertices_range(v, g)) {
allowIllegal(g, t, pred_char);
}
}
}
}
static
bool hasPredInSet(const NGHolder &g, NFAVertex v, const set<NFAVertex> &s) {
for (auto u : inv_adjacent_vertices_range(v, g)) {
if (contains(s, u)) {
return true;
}
}
return false;
}
static
bool hasSuccInSet(const NGHolder &g, NFAVertex v, const set<NFAVertex> &s) {
for (auto w : adjacent_vertices_range(v, g)) {
if (contains(s, w)) {
return true;
}
}
return false;
}
static
void findSeeds(const NGHolder &h, const bool som, vector<NFAVertex> *seeds) {
set<NFAVertex> bad; /* from zero-width asserts near accepts, etc */
for (auto v : inv_adjacent_vertices_range(h.accept, h)) {
const CharReach &cr = h[v].char_reach;
if (!isutf8ascii(cr) && !isutf8start(cr)) {
bad.insert(v);
}
}
for (auto v : inv_adjacent_vertices_range(h.acceptEod, h)) {
const CharReach &cr = h[v].char_reach;
if (!isutf8ascii(cr) && !isutf8start(cr)) {
bad.insert(v);
}
}
// we want to be careful with asserts connected to starts
// as well as they may not finish a code point
for (auto v : vertices_range(h)) {
if (is_virtual_start(v, h)) {
bad.insert(v);
insert(&bad, adjacent_vertices(v, h));
}
}
/* we cannot handle vertices connected to accept as would report matches in
* the middle of codepoints. acceptEod is not a problem as the input must
* end at a codepoint boundary */
bad.insert(h.accept);
// If we're in SOM mode, we don't want to mess with vertices that have a
// direct edge from startDs.
if (som) {
insert(&bad, adjacent_vertices(h.startDs, h));
}
set<NFAVertex> already_seeds; /* already marked as seeds */
for (auto v : vertices_range(h)) {
const CharReach &cr = h[v].char_reach;
if (!isutf8ascii(cr) || !hasSelfLoop(v, h)) {
continue;
}
if (hasSuccInSet(h, v, bad)) {
continue;
}
// Skip vertices that are directly connected to other vertices already
// in the seeds list: we can't collapse two of these directly next to
// each other.
if (hasPredInSet(h, v, already_seeds) ||
hasSuccInSet(h, v, already_seeds)) {
continue;
}
DEBUG_PRINTF("%zu is a seed\n", h[v].index);
seeds->emplace_back(v);
already_seeds.insert(v);
}
}
static
bool expandCyclic(NGHolder &h, NFAVertex v) {
DEBUG_PRINTF("inspecting %zu\n", h[v].index);
bool changes = false;
auto v_preds = preds(v, h);
auto v_succs = succs(v, h);
set<NFAVertex> start_siblings;
set<NFAVertex> end_siblings;
CharReach &v_cr = h[v].char_reach;
/* We need to find start vertices which have all of our preds.
* As we have a self loop, it must be one of our succs. */
for (auto a : adjacent_vertices_range(v, h)) {
auto a_preds = preds(a, h);
if (a_preds == v_preds && isutf8start(h[a].char_reach)) {
DEBUG_PRINTF("%zu is a start v\n", h[a].index);
start_siblings.insert(a);
}
}
/* We also need to find full cont vertices which have all our own succs;
* As we have a self loop, it must be one of our preds. */
for (auto a : inv_adjacent_vertices_range(v, h)) {
auto a_succs = succs(a, h);
if (a_succs == v_succs && h[a].char_reach == UTF_CONT_CR) {
DEBUG_PRINTF("%zu is a full tail cont\n", h[a].index);
end_siblings.insert(a);
}
}
for (auto s : start_siblings) {
if (out_degree(s, h) != 1) {
continue;
}
const CharReach &cr = h[s].char_reach;
if (cr.isSubsetOf(UTF_TWO_START_CR)) {
if (end_siblings.find(*adjacent_vertices(s, h).first)
== end_siblings.end()) {
DEBUG_PRINTF("%zu is odd\n", h[s].index);
continue;
}
} else if (cr.isSubsetOf(UTF_THREE_START_CR)) {
NFAVertex m = *adjacent_vertices(s, h).first;
if (h[m].char_reach != UTF_CONT_CR
|| out_degree(m, h) != 1) {
continue;
}
if (end_siblings.find(*adjacent_vertices(m, h).first)
== end_siblings.end()) {
DEBUG_PRINTF("%zu is odd\n", h[s].index);
continue;
}
} else if (cr.isSubsetOf(UTF_FOUR_START_CR)) {
NFAVertex m1 = *adjacent_vertices(s, h).first;
if (h[m1].char_reach != UTF_CONT_CR
|| out_degree(m1, h) != 1) {
continue;
}
NFAVertex m2 = *adjacent_vertices(m1, h).first;
if (h[m2].char_reach != UTF_CONT_CR
|| out_degree(m2, h) != 1) {
continue;
}
if (end_siblings.find(*adjacent_vertices(m2, h).first)
== end_siblings.end()) {
DEBUG_PRINTF("%zu is odd\n", h[s].index);
continue;
}
} else {
DEBUG_PRINTF("%zu is bad\n", h[s].index);
continue;
}
v_cr |= cr;
clear_vertex(s, h);
changes = true;
}
if (changes) {
v_cr |= UTF_CONT_CR; /* we need to add in cont reach */
v_cr.set(0xc0); /* we can also add in the forbidden bytes as we require
* valid unicode data */
v_cr.set(0xc1);
v_cr |= CharReach(0xf5, 0xff);
}
return changes;
}
/** \brief Contract cycles of UTF-8 code points down to a single cyclic vertex
* where possible, based on the assumption that we will always be matching
* against well-formed input. */
void utf8DotRestoration(NGHolder &h, bool som) {
vector<NFAVertex> seeds; /* cyclic ascii vertices */
findSeeds(h, som, &seeds);
bool changes = false;
for (auto v : seeds) {
changes |= expandCyclic(h, v);
}
if (changes) {
pruneUseless(h);
}
}
} // namespace ue2
| 31.868421
| 79
| 0.59486
|
a16bitsysop
|
72b58cadd71b2de20d04c1c89d78434cc0c4fbb3
| 14,605
|
hpp
|
C++
|
toolkits/test_getdepneighbor_gpu.hpp
|
Sanzo00/NeutronStarLite
|
57d92d1f7f6cd55c55a83ca086096a710185d531
|
[
"Apache-2.0"
] | 1
|
2022-03-10T07:41:55.000Z
|
2022-03-10T07:41:55.000Z
|
toolkits/test_getdepneighbor_gpu.hpp
|
Sanzo00/NeutronStarLite
|
57d92d1f7f6cd55c55a83ca086096a710185d531
|
[
"Apache-2.0"
] | null | null | null |
toolkits/test_getdepneighbor_gpu.hpp
|
Sanzo00/NeutronStarLite
|
57d92d1f7f6cd55c55a83ca086096a710185d531
|
[
"Apache-2.0"
] | null | null | null |
#include "core/neutronstar.hpp"
class test_get_neighbor_gpu {
public:
int iterations;
ValueType learn_rate;
ValueType weight_decay;
ValueType drop_rate;
ValueType alpha;
ValueType beta1;
ValueType beta2;
ValueType epsilon;
ValueType decay_rate;
ValueType decay_epoch;
// graph
VertexSubset *active;
// graph with no edge data
Graph<Empty> *graph;
//std::vector<CSC_segment_pinned *> subgraphs;
// NN
GNNDatum *gnndatum;
NtsVar L_GT_C;
NtsVar L_GT_G;
NtsVar MASK;
//GraphOperation *gt;
PartitionedGraph *partitioned_graph;
// Variables
std::vector<Parameter *> P;
std::vector<NtsVar> X;
nts::ctx::NtsContext* ctx;
NtsVar F;
NtsVar loss;
NtsVar tt;
torch::nn::Dropout drpmodel;
double exec_time = 0;
double all_sync_time = 0;
double sync_time = 0;
double all_graph_sync_time = 0;
double graph_sync_time = 0;
double all_compute_time = 0;
double compute_time = 0;
double all_copy_time = 0;
double copy_time = 0;
double graph_time = 0;
double all_graph_time = 0;
test_get_neighbor_gpu(Graph<Empty> *graph_, int iterations_,
bool process_local = false, bool process_overlap = false) {
graph = graph_;
iterations = iterations_;
active = graph->alloc_vertex_subset();
active->fill();
graph->init_gnnctx(graph->config->layer_string);
// rtminfo initialize
graph->init_rtminfo();
graph->rtminfo->process_local = graph->config->process_local;
graph->rtminfo->reduce_comm = graph->config->process_local;
graph->rtminfo->copy_data = false;
graph->rtminfo->process_overlap = graph->config->overlap;
graph->rtminfo->with_weight = true;
graph->rtminfo->with_cuda = false;
graph->rtminfo->lock_free = graph->config->lock_free;
}
void init_graph() {
partitioned_graph=new PartitionedGraph(graph, active);
partitioned_graph->GenerateAll([&](VertexId src, VertexId dst) {
return nts::op::nts_norm_degree(graph,src, dst);
},CPU_T,true);
graph->init_communicatior();
//cp = new nts::autodiff::ComputionPath(gt, subgraphs);
ctx=new nts::ctx::NtsContext();
}
void init_nn() {
learn_rate = graph->config->learn_rate;
weight_decay = graph->config->weight_decay;
drop_rate = graph->config->drop_rate;
alpha = graph->config->learn_rate;
decay_rate = graph->config->decay_rate;
decay_epoch = graph->config->decay_epoch;
beta1 = 0.9;
beta2 = 0.999;
epsilon = 1e-9;
GNNDatum *gnndatum = new GNNDatum(graph->gnnctx, graph);
// gnndatum->random_generate();
if (0 == graph->config->feature_file.compare("random")) {
gnndatum->random_generate();
} else {
gnndatum->readFeature_Label_Mask(graph->config->feature_file,
graph->config->label_file,
graph->config->mask_file);
}
// creating tensor to save Label and Mask
gnndatum->registLabel(L_GT_C);
gnndatum->registMask(MASK);
// initializeing parameter. Creating tensor with shape [layer_size[i],
// layer_size[i + 1]]
for (int i = 0; i < graph->gnnctx->layer_size.size() - 1; i++) {
P.push_back(new Parameter(graph->gnnctx->layer_size[i],
graph->gnnctx->layer_size[i + 1], alpha, beta1,
beta2, epsilon, weight_decay));
}
// synchronize parameter with other processes
// because we need to guarantee all of workers are using the same model
for (int i = 0; i < P.size(); i++) {
P[i]->init_parameter();
P[i]->set_decay(decay_rate, decay_epoch);
}
drpmodel = torch::nn::Dropout(
torch::nn::DropoutOptions().p(drop_rate).inplace(true));
F = graph->Nts->NewLeafTensor(
gnndatum->local_feature,
{graph->gnnctx->l_v_num, graph->gnnctx->layer_size[0]},
torch::DeviceType::CPU);
// X[i] is vertex representation at layer i
for (int i = 0; i < graph->gnnctx->layer_size.size(); i++) {
NtsVar d;
X.push_back(d);
}
// X[0] is the initial vertex representation. We created it from
// local_feature
X[0] = F;
}
void Test(long s) { // 0 train, //1 eval //2 test
NtsVar mask_train = MASK.eq(s);
NtsVar all_train =
X[graph->gnnctx->layer_size.size() - 1]
.argmax(1)
.to(torch::kLong)
.eq(L_GT_C)
.to(torch::kLong)
.masked_select(mask_train.view({mask_train.size(0)}));
NtsVar all = all_train.sum(0);
long *p_correct = all.data_ptr<long>();
long g_correct = 0;
long p_train = all_train.size(0);
long g_train = 0;
MPI_Datatype dt = get_mpi_data_type<long>();
MPI_Allreduce(p_correct, &g_correct, 1, dt, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&p_train, &g_train, 1, dt, MPI_SUM, MPI_COMM_WORLD);
float acc_train = 0.0;
if (g_train > 0)
acc_train = float(g_correct) / g_train;
if (graph->partition_id == 0) {
if (s == 0) {
LOG_INFO("Train Acc: %f %d %d", acc_train, g_train, g_correct);
} else if (s == 1) {
LOG_INFO("Eval Acc: %f %d %d", acc_train, g_train, g_correct);
} else if (s == 2) {
LOG_INFO("Test Acc: %f %d %d", acc_train, g_train, g_correct);
}
}
}
void Loss() {
// return torch::nll_loss(a,L_GT_C);
torch::Tensor a = X[graph->gnnctx->layer_size.size() - 1];
torch::Tensor mask_train = MASK.eq(0);
loss = torch::nll_loss(
a.masked_select(mask_train.expand({mask_train.size(0), a.size(1)}))
.view({-1, a.size(1)}),
L_GT_C.masked_select(mask_train.view({mask_train.size(0)})));
ctx->appendNNOp(a, loss);
}
void Update() {
for (int i = 0; i < P.size(); i++) {
// accumulate the gradient using all_reduce
P[i]->all_reduce_to_gradient(P[i]->W.grad().cpu());
// update parameters with Adam optimizer
P[i]->learnC2C_with_decay_Adam();
P[i]->next();
}
}
void test_mirror() {
graph->rtminfo->forward = true;
for (int i = 0; i < graph->gnnctx->layer_size.size() - 1; i++) {
graph->rtminfo->curr_layer = i;
if(i==0){
// int testid=2707;
for(VertexId val=graph->partition_offset[graph->partition_id];val<graph->partition_offset[graph->partition_id+1];val++)
X[i][val-graph->partition_offset[graph->partition_id]][10]=(float)(val);
// LOG_INFO("X_i[0][10](%f, %f)",X[i][testid][0]);
//test mirror
NtsVar mirror= ctx->runGraphOp<nts::op::DistGetDepNbrOp>(partitioned_graph,active,X[i]);
NtsVar x_trans=X[i].cuda();
NtsVar mirror_gpu= ctx->runGraphOp<nts::op::DistGPUGetDepNbrOp>(partitioned_graph,active,x_trans);
//NtsVar test_mirror_forward=torch::cat({mirror.slice(1,10,11,1),mirror_gpu.cpu().slice(1,10,11,1)},1);
// NtsVar mirror.slice(1,10,11,1).eq(mirror_gpu.cpu().slice(1,10,11,1)).sum(0);
partitioned_graph->SyncAndLog("sync test DistGPUGetDepNbrOp forward: 1 is passed");
std::cout<<mirror.slice(1,10,11,1).eq(mirror_gpu.cpu().slice(1,10,11,1)).sum(0).eq(mirror.size(0))<<std::endl;
NtsVar x_back_cuda=ctx->ntsOp.top().op->backward(mirror_gpu);
ctx->pop_one_op();
NtsVar x_back=ctx->ntsOp.top().op->backward(mirror);
partitioned_graph->SyncAndLog("sync test DistGPUGetDepNbrOp backward: 1 is passed");
std::cout<<x_back.slice(1,10,11,1).eq(x_back_cuda.cpu().slice(1,10,11,1)).sum(0).eq(x_back.size(0))<<std::endl;
}
}
}
void test_scatter_src() {
graph->rtminfo->forward = true;
for (int i = 0; i < graph->gnnctx->layer_size.size() - 1; i++) {
graph->rtminfo->curr_layer = i;
if(i==0){
// int testid=2707;
for(VertexId val=graph->partition_offset[graph->partition_id];val<graph->partition_offset[graph->partition_id+1];val++)
X[i][val-graph->partition_offset[graph->partition_id]][10]=(float)(val);
NtsVar mirror= ctx->runGraphOp<nts::op::DistGetDepNbrOp>(partitioned_graph,active,X[i]);
//test DistScatterSrc
NtsVar mirror_gpu=mirror.cuda();
NtsVar edge_src=ctx->runGraphOp<nts::op::DistScatterSrc>(partitioned_graph,active,mirror);
NtsVar edge_src_gpu= ctx->runGraphOp<nts::op::DistGPUScatterSrc>(partitioned_graph,active,mirror_gpu);
partitioned_graph->SyncAndLog("sync test DistGPUScatterSrc forward: 1 is passed");
std::cout<<edge_src.slice(1,10,11,1).eq(edge_src_gpu.cpu().slice(1,10,11,1)).sum(0).eq(edge_src.size(0))<<std::endl;
NtsVar x_back_cuda=ctx->ntsOp.top().op->backward(edge_src_gpu);
ctx->pop_one_op();
NtsVar x_back=ctx->ntsOp.top().op->backward(edge_src);
partitioned_graph->SyncAndLog("sync test DistGPUScatterSrc backward: 1 is passed");
std::cout<<x_back.slice(1,10,11,1).eq(x_back_cuda.cpu().slice(1,10,11,1)).sum(0).eq(x_back.size(0))<<std::endl;
}
}
}
void test_scatter_dst() {
graph->rtminfo->forward = true;
for (int i = 0; i < graph->gnnctx->layer_size.size() - 1; i++) {
graph->rtminfo->curr_layer = i;
if(i==0){
// int testid=2707;
for(VertexId val=graph->partition_offset[graph->partition_id];val<graph->partition_offset[graph->partition_id+1];val++)
for(VertexId j=0;j<X[i].size(1);j++)
X[i][val-graph->partition_offset[graph->partition_id]][j]=(float)(val);
partitioned_graph->SyncAndLog("sync");
//test DistScatterDst
NtsVar X_i_gpu=X[i].cuda();
NtsVar edge_dst= ctx->runGraphOp<nts::op::DistScatterDst>(partitioned_graph,active,X[i]);
NtsVar edge_dst_gpu= ctx->runGraphOp<nts::op::DistGPUScatterDst>(partitioned_graph,active,X_i_gpu);
partitioned_graph->SyncAndLog("sync test DistGPUScatterDst forward: 1 is passed");
std::cout<<edge_dst.eq(edge_dst_gpu.cpu()).sum(0).sum(0).eq(edge_dst.size(0)*edge_dst.size(1))<<std::endl;
NtsVar x_back_cuda=ctx->ntsOp.top().op->backward(edge_dst_gpu);
ctx->pop_one_op();
NtsVar x_back=ctx->ntsOp.top().op->backward(edge_dst);
partitioned_graph->SyncAndLog("sync test DistGPUScatterDst backward: 1 is passed");
std::cout<<x_back.eq(x_back_cuda.cpu()).sum(0).sum(0).eq(x_back.size(0)*x_back.size(1))<<std::endl;
}
}
}
void test_gather_dst() {
graph->rtminfo->forward = true;
for (int i = 0; i < graph->gnnctx->layer_size.size() - 1; i++) {
graph->rtminfo->curr_layer = i;
if(i==0){
// int testid=2707;
for(VertexId val=graph->partition_offset[graph->partition_id];val<graph->partition_offset[graph->partition_id+1];val++)
for(VertexId j=0;j<X[i].size(1);j++)
X[i][val-graph->partition_offset[graph->partition_id]][j]=(float)(val);
//test DistScatterDst
NtsVar X_i_gpu=X[i].cuda();
NtsVar edge_dst= ctx->runGraphOp<nts::op::DistScatterDst>(partitioned_graph,active,X[i]);
NtsVar edge_dst_gpu= ctx->runGraphOp<nts::op::DistGPUScatterDst>(partitioned_graph,active,X_i_gpu);
NtsVar dst_y= ctx->runGraphOp<nts::op::DistAggregateDst>(partitioned_graph,active,edge_dst);
NtsVar dst_y_gpu= ctx->runGraphOp<nts::op::DistGPUAggregateDst>(partitioned_graph,active,edge_dst_gpu);
partitioned_graph->SyncAndLog("sync test DistGPUAggregateDst forward: 1 is passed");
std::cout<<dst_y.eq(dst_y_gpu.cpu()).sum(0).sum(0).eq(dst_y.size(0)*dst_y.size(1))<<std::endl;
NtsVar x_back_cuda=ctx->ntsOp.top().op->backward(dst_y_gpu);
ctx->pop_one_op();
NtsVar x_back=ctx->ntsOp.top().op->backward(dst_y);
partitioned_graph->SyncAndLog("sync test DistGPUAggregateDst backward: 1 is passed");
std::cout<<x_back.eq(x_back_cuda.cpu()).sum(0).sum(0).eq(x_back.size(0)*x_back.size(1))<<std::endl;
}
}
}
void test_softmax() {
graph->rtminfo->forward = true;
for (int i = 0; i < graph->gnnctx->layer_size.size() - 1; i++) {
graph->rtminfo->curr_layer = i;
if(i==0){
// int testid=2707;
for(VertexId val=graph->partition_offset[graph->partition_id];val<graph->partition_offset[graph->partition_id+1];val++)
X[i][val-graph->partition_offset[graph->partition_id]][10]=(float)(val);
//test DistScatterDst
NtsVar X_i_gpu=X[i].cuda();
NtsVar edge_dst= ctx->runGraphOp<nts::op::DistScatterDst>(partitioned_graph,active,X[i]);
NtsVar m=torch::ones({edge_dst.size(0),1});
for(VertexId val=0;val< m.size(0);val++)
m[val][0]=(float)(1);
NtsVar m_gpu=m.cuda();
NtsVar a=ctx->runGraphOp<nts::op::DistEdgeSoftMax>(partitioned_graph,active,m);
NtsVar a_gpu=ctx->runGraphOp<nts::op::DistGPUEdgeSoftMax>(partitioned_graph,active,m_gpu);
NtsVar test_mirror_forward=torch::cat({a,a_gpu.cpu()},1);
// std::cout<<test_mirror_forward.slice(0,1119,2200,1)<<std::endl;
partitioned_graph->SyncAndLog("sync test DistGPUEdgeSoftMax forward: 1 is passed");
std::cout<<torch::abs(a-a_gpu.cpu()).le(0.0000001).sum(0).eq(a.size(0))<<std::endl;
//std::cout<<a.size(0)<<" "<<a.eq(a_gpu.cpu()).sum(0)<<std::endl;
NtsVar x_back_cuda=ctx->ntsOp.top().op->backward(m_gpu);
ctx->pop_one_op();
NtsVar x_back=ctx->ntsOp.top().op->backward(m);
partitioned_graph->SyncAndLog("sync test DistGPUEdgeSoftMax backward: 1 is passed");
// std::cout<<(x_back-x_back_cuda.cpu()).slice(0,0,6,1)<<std::endl;
std::cout<<torch::abs(x_back-x_back_cuda.cpu()).le(0.0000001).sum(0).eq(x_back.size(0))<<std::endl;
}
}
}
void run() {
if (graph->partition_id == 0) {
LOG_INFO("GNNmini::[Dist.GPU.GCNimpl] running [%d] Epoches\n",
iterations);
}
exec_time -= get_time();
for (int i_i = 0; i_i < 1; i_i++) {
graph->rtminfo->epoch = i_i;
//test_mirror();
//test_scatter_src();
//test_scatter_dst();
test_gather_dst();
//test_softmax();
if (graph->partition_id == 0)
std::cout << "Nts::Running.Epoch[" << i_i << "]:loss\t" << loss
<< std::endl;
}
// NtsVar s=torch::ones({3,3});
// NtsVar d=torch::zeros({3,3});
// NtsVar l= test(d);
// printf("%ld %ld\n", &l, &d);
delete active;
}
};
| 40.796089
| 127
| 0.618624
|
Sanzo00
|
72b7d6bd60fa0c0510d3dd698c0d4bed63131ce0
| 3,151
|
cpp
|
C++
|
src/unittest/AlgorithmsTest.cpp
|
szekizoli/graphlib
|
2be4790024c20f2e2ad3b96010efa1e8aa35907c
|
[
"MIT"
] | null | null | null |
src/unittest/AlgorithmsTest.cpp
|
szekizoli/graphlib
|
2be4790024c20f2e2ad3b96010efa1e8aa35907c
|
[
"MIT"
] | null | null | null |
src/unittest/AlgorithmsTest.cpp
|
szekizoli/graphlib
|
2be4790024c20f2e2ad3b96010efa1e8aa35907c
|
[
"MIT"
] | null | null | null |
#include "GraphLibTestUtils.h"
#include <iostream>
#include "GraphTestHelper.h"
#include "graph\Algorithms.h"
#include "graph\Graph.h"
#include "graph\GraphBuilder.h"
#include "graph\Node.h"
#include "graph\function\Function.h"
namespace GraphLibraryTest
{
using namespace graphlib::graph;
using namespace graphlib::graph::function;
TEST(algorithmsTests, TestCreateTopologicalSort)
{
CREATE_MEMORY_SNAPSHOT{
Graph g = createTestGraph();
unsigned expected_size = 0;
auto order = algorithms::topologicalSort<Graph, Node>(g);
EXPECT_EQ(2, order.size());
EXPECT_EQ(Label{ L"const"}, order[0]->label());
EXPECT_EQ(Label{ L"oppos"}, order[1]->label());
} ASSERT_MEMORY_SNAPSHOT
}
TEST(algorithmsTests, TestCreatePredecessorCountWithEmptyGraph)
{ CREATE_MEMORY_SNAPSHOT{
Graph g = GraphBuilder{}.build();
auto count = algorithms::predecessorCount<Graph, Node>(g);
EXPECT_EQ(g.size(), count.size());
} ASSERT_MEMORY_SNAPSHOT }
TEST(algorithmsTests, TestCreatePredecessorCountWithTestGraph)
{ CREATE_MEMORY_SNAPSHOT{
Graph g = createTestGraph();
auto count = algorithms::predecessorCount<Graph, Node>(g);
EXPECT_EQ(g.order(), count.size());
EXPECT_EQ(0, count[0]);
EXPECT_EQ(1, count[1]);
} ASSERT_MEMORY_SNAPSHOT }
TEST(algorithmsTests, TestCountWithTestGraph)
{ CREATE_MEMORY_SNAPSHOT{
Graph g = createTestGraph();
auto count = algorithms::count<Graph, Node>(g, [](const Node& n) {return n.predecessorSize(); });
EXPECT_EQ(g.order(), count.size());
EXPECT_EQ(0, count[0]);
EXPECT_EQ(1, count[1]);
} ASSERT_MEMORY_SNAPSHOT }
TEST(algorithmsTests, TestCountWithTestGraphSuccessor)
{ CREATE_MEMORY_SNAPSHOT{
Graph g = createTestGraph();
auto count = algorithms::count<Graph, Node>(g, [](const Node& n) {return n.successorSize(); });
EXPECT_EQ(g.order(), count.size());
EXPECT_EQ(1, count[0]);
EXPECT_EQ(0, count[1]);
} ASSERT_MEMORY_SNAPSHOT }
TEST(algorithmsTests, TestCreatePredecessorCountWithQuadraticGraph)
{ CREATE_MEMORY_SNAPSHOT{
Graph g = createQuadraticGraph();
auto count = algorithms::predecessorCount<Graph, Node>(g);
EXPECT_EQ(g.order(), count.size());
for (unsigned i = 0; i < g.order(); ++i)
{
EXPECT_EQ(g[i].predecessorSize(), count[i]);
}
} ASSERT_MEMORY_SNAPSHOT }
TEST(algorithmsTests, TestStackSort)
{ CREATE_MEMORY_SNAPSHOT{
Graph g = createMultiOutputGraph();
auto order = algorithms::stackSort<Graph, Node>(g);
EXPECT_EQ(g.order(), order.size());
for (const auto& n : order) {
std::wcout << n->label() << std::endl;
}
} ASSERT_MEMORY_SNAPSHOT }
TEST(algorithmsTests, CreateTopologicalSortQuadraticGraph)
{ CREATE_MEMORY_SNAPSHOT{
Graph g = createQuadraticGraph();
unsigned expected_size = 0;
auto order = algorithms::topologicalSort<Graph, Node>(g);
EXPECT_EQ(17, order.size());
auto count = algorithms::predecessorCount<Graph, Node>(g);
for (const auto& n : order)
{
EXPECT_EQ(0, count[n->id()]);// the predecessors left for this is 0.
// decrement number of predecessors for successors
for (const auto& s : n->successors()) {
--count[s->id()];
}
}
} ASSERT_MEMORY_SNAPSHOT }
}
| 30.592233
| 99
| 0.715011
|
szekizoli
|
72bbfc2087c1d269c123beda08d082c88453644f
| 3,034
|
hh
|
C++
|
benchmarks/solvers/minizinc/include/minizinc/chain_compressor.hh
|
95A31/MDD-LNS
|
9b78143e13ce8b3916bf3cc9662d9cbfe63fd7c7
|
[
"MIT"
] | null | null | null |
benchmarks/solvers/minizinc/include/minizinc/chain_compressor.hh
|
95A31/MDD-LNS
|
9b78143e13ce8b3916bf3cc9662d9cbfe63fd7c7
|
[
"MIT"
] | null | null | null |
benchmarks/solvers/minizinc/include/minizinc/chain_compressor.hh
|
95A31/MDD-LNS
|
9b78143e13ce8b3916bf3cc9662d9cbfe63fd7c7
|
[
"MIT"
] | null | null | null |
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Jip J. Dekker <jip.dekker@monash.edu>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#pragma once
#include <minizinc/model.hh>
#include <map>
namespace MiniZinc {
class ChainCompressor {
public:
ChainCompressor(EnvI& env, Model& m, std::vector<VarDecl*>& deletedVarDecls)
: _env(env), _m(m), _deletedVarDecls(deletedVarDecls){};
virtual bool trackItem(Item* i) = 0;
virtual void compress() = 0;
protected:
EnvI& _env;
Model& _m;
std::vector<VarDecl*>& _deletedVarDecls;
std::multimap<VarDecl*, Item*> _items;
typedef std::multimap<VarDecl*, Item*>::iterator iterator;
void storeItem(VarDecl* v, Item* i) { _items.emplace(v, i); }
void updateCount();
unsigned long count(VarDecl* v) { return _items.count(v); }
std::pair<iterator, iterator> find(VarDecl* v) { return _items.equal_range(v); };
void removeItem(Item* i);
int addItem(Item* i);
// Replaces the Nth argument of a Call c by Expression e, c must be located on Item i
void replaceCallArgument(Item* i, Call* c, unsigned int n, Expression* e);
};
class ImpCompressor : public ChainCompressor {
public:
ImpCompressor(EnvI& env, Model& m, std::vector<VarDecl*>& deletedVarDecls,
std::vector<int>& boolConstraints0)
: ChainCompressor(env, m, deletedVarDecls), _boolConstraints(boolConstraints0){};
bool trackItem(Item* i) override;
void compress() override;
protected:
std::vector<int>& _boolConstraints;
// Compress two implications. e.g. (x -> y) /\ (y -> z) => x -> z
// In this case i: (y -> z), newLHS: x
// Function returns true if compression was successful (and the implication that contains newLHS
// can be removed) Side effect: Item i might be removed.
bool compressItem(Item* i, VarDecl* newLHS);
// Constructs a clause constraint item with pos and neg as parameters.
// if pos/neg are not ArrayLit then they will inserted into an ArrayLit.
ConstraintI* constructClause(Expression* pos, Expression* neg);
ConstraintI* constructHalfReif(Call* call, Id* control);
};
class LECompressor : public ChainCompressor {
public:
LECompressor(EnvI& env, Model& m, std::vector<VarDecl*>& deletedVarDecls)
: ChainCompressor(env, m, deletedVarDecls){};
bool trackItem(Item* i) override;
void compress() override;
protected:
std::map<VarDecl*, VarDecl*> _aliasMap;
/// Replace the use a variable within an inequality
/// e.g. i: int_lin_le([1,2,3], [a,b,c], 10), oldVar: a, newVar d -> int_lin_le([1,2,3], [d,b,c],
/// 10) Occurrence count is updated for variables involved.
template <class Lit>
void leReplaceVar(Item* i, VarDecl* oldVar, VarDecl* newVar);
/// Check if the bounds of two Variables are equal
bool eqBounds(Expression* a, Expression* b);
};
} // namespace MiniZinc
| 30.039604
| 99
| 0.689519
|
95A31
|
72c0c072422b271b0c872612a60d713b4384cbb8
| 757
|
hpp
|
C++
|
Firmware/modules/InputSense.hpp
|
jimkoeh/ActiveLoad
|
77ad16cd16365efc226c3384b1ad5ba39d782c83
|
[
"MIT"
] | 2
|
2017-12-25T10:00:39.000Z
|
2020-05-25T09:03:12.000Z
|
Firmware/modules/InputSense.hpp
|
jimkoeh/ActiveLoad
|
77ad16cd16365efc226c3384b1ad5ba39d782c83
|
[
"MIT"
] | null | null | null |
Firmware/modules/InputSense.hpp
|
jimkoeh/ActiveLoad
|
77ad16cd16365efc226c3384b1ad5ba39d782c83
|
[
"MIT"
] | 3
|
2019-08-25T05:32:01.000Z
|
2021-01-18T00:29:03.000Z
|
/**
* @file InputSense.hpp
*
* @date 19.12.2015
* @author Andre
* @description
*/
#ifndef INPUTSENSE_HPP_
#define INPUTSENSE_HPP_
#include "SystemState.hpp"
#include "SystemCommand.hpp"
#include "driver/DS18B20.hpp"
#include <stdint.h>
#include "tools/EMAFilter.hpp"
class InputSense
{
public:
InputSense();
virtual ~InputSense() { }
void lowLevelInit();
void execute(SystemCommand& systemCommand, SystemState& systemState);
private:
float getActualVoltage();
float getActualCurrent();
DS18B20 _tempPower;
unsigned int _timeLastTemperature;
volatile uint16_t _adcVoltageRaw[2];
EMAFilter _filterActualVoltage;
EMAFilter _filterActualCurrent;
float _actualVoltage;
float _actualCurrent;
};
#endif /* INPUTSENSE_HPP_ */
| 18.463415
| 71
| 0.746367
|
jimkoeh
|
72c0d8fa9db6dc30caa52837c4ea4a02024ee7b6
| 4,812
|
cpp
|
C++
|
src/dustfluids/dustfluids_noCs_solver.cpp
|
PinghuiHuang/athena-pp-dustfluids
|
fce21992cc107aa553e83dd76b8d03ae90e990c7
|
[
"BSD-3-Clause"
] | 2
|
2020-07-02T09:48:49.000Z
|
2020-08-25T02:37:21.000Z
|
src/dustfluids/dustfluids_noCs_solver.cpp
|
PinghuiHuang/athena-pp-dustfluids
|
fce21992cc107aa553e83dd76b8d03ae90e990c7
|
[
"BSD-3-Clause"
] | null | null | null |
src/dustfluids/dustfluids_noCs_solver.cpp
|
PinghuiHuang/athena-pp-dustfluids
|
fce21992cc107aa553e83dd76b8d03ae90e990c7
|
[
"BSD-3-Clause"
] | 1
|
2021-11-12T13:39:48.000Z
|
2021-11-12T13:39:48.000Z
|
//========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file dustfluids_noCs_solver.cpp
//! \brief HLLE Riemann solver for dust fludis (no dust sound speed)
//!
//! Computes 1D fluxes using the Harten-Lax-van Leer (HLL) Riemann solver. This flux is
//! very diffusive, especially for contacts, and so it is not recommended for use in
//! applications. However, as shown by Einfeldt et al.(1991), it is positively
//! conservative (cannot return negative densities or pressure), so it is a useful
//! option when other approximate solvers fail and/or when extra dissipation is needed.
//!
//!REFERENCES:
//!- E.F. Toro, "Riemann Solvers and numerical methods for fluid dynamics", 2nd ed.,
//! Springer-Verlag, Berlin, (1999) chpt. 10.
//!- Einfeldt et al., "On Godunov-type methods near low densities", JCP, 92, 273 (1991)
//!- A. Harten, P. D. Lax and B. van Leer, "On upstream differencing and Godunov-type
//! schemes for hyperbolic conservation laws", SIAM Review 25, 35-61 (1983).
// C headers
// C++ headers
#include <algorithm> // max(), min()
#include <cmath> // sqrt()
// Athena++ headers
#include "../athena.hpp"
#include "../athena_arrays.hpp"
#include "../eos/eos.hpp"
#include "dustfluids.hpp"
//----------------------------------------------------------------------------------------
//! \fn void DustFluids::HLLE_RiemannSolver_DustFluids
//! \brief The HLLE Riemann solver for Dust Fluids (no dust sound speed)
void DustFluids::HLLENoCsRiemannSolverDustFluids(const int k, const int j, const int il, const int iu,
const int index, AthenaArray<Real> &prim_df_l,
AthenaArray<Real> &prim_df_r, AthenaArray<Real> &dust_flux) {
Real df_prim_li[(NDUSTVARS)], df_prim_ri[(NDUSTVARS)], df_prim_roe[(NDUSTVARS)];
Real df_fl[(NDUSTVARS)], df_fr[(NDUSTVARS)], df_flxi[(NDUSTVARS)];
for (int n=0; n<NDUSTFLUIDS; ++n) {
int idust = n;
int irho = 4*idust;
int ivx = (IVX + ((index-IVX))%3) + irho;
int ivy = (IVX + ((index-IVX)+1)%3) + irho;
int ivz = (IVX + ((index-IVX)+2)%3) + irho;
#pragma omp simd private(df_prim_li, df_prim_ri, df_prim_roe, df_fl, df_fr, df_flxi)
for (int i=il; i<=iu; ++i) {
//Load L/R states into local variables
df_prim_li[irho] = prim_df_l(irho, i);
df_prim_li[ivx] = prim_df_l(ivx, i);
df_prim_li[ivy] = prim_df_l(ivy, i);
df_prim_li[ivz] = prim_df_l(ivz, i);
df_prim_ri[irho] = prim_df_r(irho, i);
df_prim_ri[ivx] = prim_df_r(ivx, i);
df_prim_ri[ivy] = prim_df_r(ivy, i);
df_prim_ri[ivz] = prim_df_r(ivz, i);
//Compute middle state estimates with PVRS (Toro 10.5.2)
//Real al, ar, el, er;
Real sqrtdl = std::sqrt(df_prim_li[irho]);
Real sqrtdr = std::sqrt(df_prim_ri[irho]);
Real isdlpdr = 1.0/(sqrtdl + sqrtdr);
df_prim_roe[irho] = sqrtdl*sqrtdr;
df_prim_roe[ivx] = (sqrtdl*df_prim_li[ivx] + sqrtdr*df_prim_ri[ivx])*isdlpdr;
//Compute the max/min wave speeds based on L/R and Roe-averaged values
Real al = std::min(df_prim_roe[ivx],df_prim_li[ivx]);
Real ar = std::max(df_prim_roe[ivx],df_prim_ri[ivx]);
Real bp = ar > 0.0 ? ar : 0.0;
Real bm = al < 0.0 ? al : 0.0;
//Compute L/R df_fluxes along lines bm/bp: F_L - (S_L)U_L; F_R - (S_R)U_R
Real vxl = df_prim_li[ivx] - bm;
Real vxr = df_prim_ri[ivx] - bp;
df_fl[irho] = vxl * df_prim_li[irho];
df_fr[irho] = vxr * df_prim_ri[irho];
df_fl[ivx] = df_prim_li[ivx] * df_fl[irho];
df_fr[ivx] = df_prim_ri[ivx] * df_fr[irho];
df_fl[ivy] = df_prim_li[ivy] * df_fl[irho];
df_fr[ivy] = df_prim_ri[ivy] * df_fr[irho];
df_fl[ivz] = df_prim_li[ivz] * df_fl[irho];
df_fr[ivz] = df_prim_ri[ivz] * df_fr[irho];
//Compute the HLLE df_flux at interface.
Real tmp = 0.0;
if (bp != bm) tmp = 0.5*(bp + bm)/(bp - bm);
df_flxi[irho] = 0.5*(df_fl[irho] + df_fr[irho]) + (df_fl[irho] - df_fr[irho])*tmp;
df_flxi[ivx] = 0.5*(df_fl[ivx]+df_fr[ivx]) + (df_fl[ivx]-df_fr[ivx])*tmp;
df_flxi[ivy] = 0.5*(df_fl[ivy]+df_fr[ivy]) + (df_fl[ivy]-df_fr[ivy])*tmp;
df_flxi[ivz] = 0.5*(df_fl[ivz]+df_fr[ivz]) + (df_fl[ivz]-df_fr[ivz])*tmp;
dust_flux(irho, k, j, i) = df_flxi[irho];
dust_flux(ivx, k, j, i) = df_flxi[ivx];
dust_flux(ivy, k, j, i) = df_flxi[ivy];
dust_flux(ivz, k, j, i) = df_flxi[ivz];
}
}
return;
}
| 42.584071
| 102
| 0.593932
|
PinghuiHuang
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.