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
108
| 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
67k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
85e81958bc8b94020364f88526924ae55a5866d5
| 2,836
|
cpp
|
C++
|
ExtraLifeEngine/Obsolete/RemovedVoxel/Voxel/Neutral/Terrain/TerrainGeneration.cpp
|
paulburgess1357/ExtraLifeEngine
|
e0d1f95fa57ea9e5016d1e3800815cdb24b1eb0f
|
[
"MIT"
] | 1
|
2020-11-13T05:39:46.000Z
|
2020-11-13T05:39:46.000Z
|
ExtraLifeEngine/Obsolete/RemovedVoxel/Voxel/Neutral/Terrain/TerrainGeneration.cpp
|
paulburgess1357/ExtraLifeEngine
|
e0d1f95fa57ea9e5016d1e3800815cdb24b1eb0f
|
[
"MIT"
] | null | null | null |
ExtraLifeEngine/Obsolete/RemovedVoxel/Voxel/Neutral/Terrain/TerrainGeneration.cpp
|
paulburgess1357/ExtraLifeEngine
|
e0d1f95fa57ea9e5016d1e3800815cdb24b1eb0f
|
[
"MIT"
] | null | null | null |
#include "TerrainGeneration.h"
#include <cmath>
namespace ExtraLife {
noise::module::Perlin TerrainGeneration::m_perlin_noise;
int TerrainGeneration::generate_top_layer(const WorldPosition& starting_world_position, const int x_local, const int z_local, const int x_block_qty, const int y_block_qty, const int z_block_qty){
m_perlin_noise.SetOctaveCount(1); // 1 to 6
m_perlin_noise.SetFrequency(1); // 1 to 16
m_perlin_noise.SetPersistence(0); // 0 to 1
const glm::vec3 start_position = starting_world_position.get_vec3();
const double nx = (static_cast<double>(x_local + start_position.x) / x_block_qty - 0.5f);
const double nz = (static_cast<double>(z_local + start_position.z) / z_block_qty - 0.5f);
double noise1 = 1.0 * generate_noise(1.0 * nx, 1.0 * nz);
double noise2 = 0.5 * generate_noise(2.0 * nx + 3.48, 2.0 * nz + 8.74);
double noise3 = 0.25 * generate_noise(4.0 * nx + 6.81, 4.0 * nz + 1.85);
double total_noise = (noise1 + noise2 + noise3) / (1.0 + 0.5 + 0.25);
//total_noise = pow(total_noise, 1.2);
total_noise = round(total_noise * y_block_qty) / y_block_qty;
int height = total_noise * y_block_qty; // 1.0f + 0.5f + 0.25f
// std::cout << height << std::endl;
//int height = generate_noise(nx, nz) * y_block_qty; // + 2 makes tabletops
if (height > y_block_qty) {
height = y_block_qty;
}
if (height < 1) {
height = 1;
}
return height;
}
double TerrainGeneration::generate_noise(const double nx, const double nz){
return m_perlin_noise.GetValue(nx, 0.0f, nz) / 2.0f + 0.5f;
}
int TerrainGeneration::generate_top_layer2(const WorldPosition& starting_world_position, const int x_local, const int z_local, const int x_block_qty, const int y_block_qty, const int z_block_qty) {
m_perlin_noise.SetOctaveCount(1); // 1 to 6
m_perlin_noise.SetFrequency(1); // 1 to 16
m_perlin_noise.SetPersistence(0); // 0 to 1
const glm::vec3 start_position = starting_world_position.get_vec3();
const double nx = (static_cast<double>(x_local + start_position.x) / x_block_qty - 0.5f);
const double nz = (static_cast<double>(z_local + start_position.z) / z_block_qty - 0.5f);
double noise1 = 1.5 * generate_noise(1.0 * nx, 1.0 * nz);
double noise2 = 0.1 * generate_noise(2.0 * nx + 3.48, 2.0 * nz + 8.74);
double noise3 = 0.1 * generate_noise(4.0 * nx + 6.81, 4.0 * nz + 1.85);
double total_noise = (noise1 + noise2 + noise3) / (1.0 + 0.5 + 0.25);
//total_noise = pow(total_noise, 1.2);
total_noise = round(total_noise * y_block_qty) / y_block_qty;
int height = total_noise * y_block_qty; // 1.0f + 0.5f + 0.25f
// std::cout << height << std::endl;
//int height = generate_noise(nx, nz) * y_block_qty; // + 2 makes tabletops
if (height > y_block_qty) {
height = y_block_qty;
}
if (height < 1) {
height = 1;
}
return height;
}
} // namespace ExtraLife
| 32.976744
| 197
| 0.692877
|
paulburgess1357
|
85e909132693dfd1cd383f02695d85108c993a7b
| 1,182
|
hpp
|
C++
|
src/nxt_ipc.hpp
|
syldrathecat/nxtlauncher
|
9856999bed2531067a44a319a8b37f726d2ffb0a
|
[
"Unlicense"
] | 13
|
2016-09-15T23:04:48.000Z
|
2021-02-27T01:42:31.000Z
|
src/nxt_ipc.hpp
|
syldrathecat/nxtlauncher
|
9856999bed2531067a44a319a8b37f726d2ffb0a
|
[
"Unlicense"
] | 13
|
2017-04-22T16:00:07.000Z
|
2020-10-13T18:18:29.000Z
|
src/nxt_ipc.hpp
|
syldrathecat/nxtlauncher
|
9856999bed2531067a44a319a8b37f726d2ffb0a
|
[
"Unlicense"
] | 2
|
2016-09-15T19:49:24.000Z
|
2018-12-28T03:11:50.000Z
|
#ifndef NXT_IPC_HPP
#define NXT_IPC_HPP
#include "nxt_fifo.hpp"
#include "nxt_message.hpp"
#include <functional>
#include <map>
// Creates and manages a pair of named pipes for communicating with the client
class nxt_ipc
{
public:
using handler_t = std::function<void(nxt_message&)>;
private:
nxt_fifo m_fifo_in;
nxt_fifo m_fifo_out;
std::map<int, handler_t> m_handlers;
void handle(nxt_message& message);
public:
// Initializes the files for IPC
nxt_ipc(const char* fifo_in_filename, const char* fifo_out_filename);
// Not copyable
nxt_ipc(const nxt_ipc&) = delete;
nxt_ipc& operator=(const nxt_ipc&) = delete;
// Moveable, but probably a bad idea if handlers reference the original
nxt_ipc(nxt_ipc&&) = default;
nxt_ipc& operator=(nxt_ipc&&) = default;
// Registers a handler for a given message ID
// Registering new handlers will overwrite old ones
void register_handler(int message_id, handler_t handler);
// Starts pumping messages and executing handlers
// (expected to be called from a separate thread)
void operator()();
// Sends a message to the client
void send(const nxt_message& msg);
};
#endif // NXT_IPC_HPP
| 23.64
| 78
| 0.733503
|
syldrathecat
|
85f1f0920a744c4e5ecaada128864ecc85a924ea
| 982
|
cc
|
C++
|
kraken/resources/home/dnanexus/jellyfish-1.1.11/jellyfish/dna_codes.cc
|
transcript/DNAnexus_apps
|
12c2ba6f57b805a9fcf6e1da4f9d64394ef72256
|
[
"MIT"
] | 3
|
2015-11-20T19:40:29.000Z
|
2019-07-25T15:34:24.000Z
|
kraken/resources/home/dnanexus/jellyfish-1.1.11/jellyfish/dna_codes.cc
|
transcript/DNAnexus_apps
|
12c2ba6f57b805a9fcf6e1da4f9d64394ef72256
|
[
"MIT"
] | null | null | null |
kraken/resources/home/dnanexus/jellyfish-1.1.11/jellyfish/dna_codes.cc
|
transcript/DNAnexus_apps
|
12c2ba6f57b805a9fcf6e1da4f9d64394ef72256
|
[
"MIT"
] | 2
|
2018-09-20T08:28:36.000Z
|
2019-03-06T06:26:52.000Z
|
#include <jellyfish/dna_codes.hpp>
#define R -1
#define I -2
#define O -3
#define A 0
#define C 1
#define G 2
#define T 3
const char jellyfish::dna_codes[256] = {
O, O, O, O, O, O, O, O, O, O, I, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, R, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, A, R, C, R, O, O, G, R, O, O, R, O, R, R, O,
O, O, R, R, T, O, R, R, R, R, O, O, O, O, O, O,
O, A, R, C, R, O, O, G, R, O, O, R, O, R, R, O,
O, O, R, R, T, O, R, R, R, R, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O
};
| 33.862069
| 50
| 0.376782
|
transcript
|
85f21279c2ed92b54cf93e1bc15da260fe5fffc6
| 7,756
|
hpp
|
C++
|
include/GlobalNamespace/LocalNetworkPlayersViewController.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/LocalNetworkPlayersViewController.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/LocalNetworkPlayersViewController.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: NetworkPlayersViewController
#include "GlobalNamespace/NetworkPlayersViewController.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::UI
namespace UnityEngine::UI {
// Forward declaring type: Toggle
class Toggle;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: LocalNetworkPlayerModel
class LocalNetworkPlayerModel;
// Forward declaring type: INetworkConfig
class INetworkConfig;
// Forward declaring type: INetworkPlayerModel
class INetworkPlayerModel;
}
// Forward declaring namespace: HMUI
namespace HMUI {
// Forward declaring type: ToggleBinder
class ToggleBinder;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0xBA
#pragma pack(push, 1)
// Autogenerated type: LocalNetworkPlayersViewController
class LocalNetworkPlayersViewController : public GlobalNamespace::NetworkPlayersViewController {
public:
// private UnityEngine.UI.Toggle _enableNetworkingToggle
// Size: 0x8
// Offset: 0x90
UnityEngine::UI::Toggle* enableNetworkingToggle;
// Field size check
static_assert(sizeof(UnityEngine::UI::Toggle*) == 0x8);
// private UnityEngine.UI.Toggle _enableOpenPartyToggle
// Size: 0x8
// Offset: 0x98
UnityEngine::UI::Toggle* enableOpenPartyToggle;
// Field size check
static_assert(sizeof(UnityEngine::UI::Toggle*) == 0x8);
// [InjectAttribute] Offset: 0xE25520
// private readonly LocalNetworkPlayerModel _localNetworkPlayerModel
// Size: 0x8
// Offset: 0xA0
GlobalNamespace::LocalNetworkPlayerModel* localNetworkPlayerModel;
// Field size check
static_assert(sizeof(GlobalNamespace::LocalNetworkPlayerModel*) == 0x8);
// [InjectAttribute] Offset: 0xE25530
// private readonly INetworkConfig _networkConfig
// Size: 0x8
// Offset: 0xA8
GlobalNamespace::INetworkConfig* networkConfig;
// Field size check
static_assert(sizeof(GlobalNamespace::INetworkConfig*) == 0x8);
// private HMUI.ToggleBinder _toggleBinder
// Size: 0x8
// Offset: 0xB0
HMUI::ToggleBinder* toggleBinder;
// Field size check
static_assert(sizeof(HMUI::ToggleBinder*) == 0x8);
// private System.Boolean _enableBroadcasting
// Size: 0x1
// Offset: 0xB8
bool enableBroadcasting;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _allowAnyoneToJoin
// Size: 0x1
// Offset: 0xB9
bool allowAnyoneToJoin;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: LocalNetworkPlayersViewController
LocalNetworkPlayersViewController(UnityEngine::UI::Toggle* enableNetworkingToggle_ = {}, UnityEngine::UI::Toggle* enableOpenPartyToggle_ = {}, GlobalNamespace::LocalNetworkPlayerModel* localNetworkPlayerModel_ = {}, GlobalNamespace::INetworkConfig* networkConfig_ = {}, HMUI::ToggleBinder* toggleBinder_ = {}, bool enableBroadcasting_ = {}, bool allowAnyoneToJoin_ = {}) noexcept : enableNetworkingToggle{enableNetworkingToggle_}, enableOpenPartyToggle{enableOpenPartyToggle_}, localNetworkPlayerModel{localNetworkPlayerModel_}, networkConfig{networkConfig_}, toggleBinder{toggleBinder_}, enableBroadcasting{enableBroadcasting_}, allowAnyoneToJoin{allowAnyoneToJoin_} {}
// private System.Void HandleNetworkingToggleChanged(System.Boolean enabled)
// Offset: 0x10D48F4
void HandleNetworkingToggleChanged(bool enabled);
// private System.Void HandleOpenPartyToggleChanged(System.Boolean openParty)
// Offset: 0x10D4904
void HandleOpenPartyToggleChanged(bool openParty);
// private System.Void RefreshParty(System.Boolean overrideHide)
// Offset: 0x10D4790
void RefreshParty(bool overrideHide);
// public override System.String get_myPartyTitle()
// Offset: 0x10D45B8
// Implemented from: NetworkPlayersViewController
// Base method: System.String NetworkPlayersViewController::get_myPartyTitle()
::Il2CppString* get_myPartyTitle();
// public override System.String get_otherPlayersTitle()
// Offset: 0x10D4600
// Implemented from: NetworkPlayersViewController
// Base method: System.String NetworkPlayersViewController::get_otherPlayersTitle()
::Il2CppString* get_otherPlayersTitle();
// public override INetworkPlayerModel get_networkPlayerModel()
// Offset: 0x10D4648
// Implemented from: NetworkPlayersViewController
// Base method: INetworkPlayerModel NetworkPlayersViewController::get_networkPlayerModel()
GlobalNamespace::INetworkPlayerModel* get_networkPlayerModel();
// protected override System.Void NetworkPlayersViewControllerDidActivate(System.Boolean firstActivation, System.Boolean addedToHierarchy)
// Offset: 0x10D4650
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::NetworkPlayersViewControllerDidActivate(System.Boolean firstActivation, System.Boolean addedToHierarchy)
void NetworkPlayersViewControllerDidActivate(bool firstActivation, bool addedToHierarchy);
// protected override System.Void DidDeactivate(System.Boolean removedFromHierarchy, System.Boolean screenSystemDisabling)
// Offset: 0x10D48B0
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::DidDeactivate(System.Boolean removedFromHierarchy, System.Boolean screenSystemDisabling)
void DidDeactivate(bool removedFromHierarchy, bool screenSystemDisabling);
// protected override System.Void OnDestroy()
// Offset: 0x10D48C0
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::OnDestroy()
void OnDestroy();
// public System.Void .ctor()
// Offset: 0x10D4914
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::.ctor()
// Base method: System.Void ViewController::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static LocalNetworkPlayersViewController* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::LocalNetworkPlayersViewController::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<LocalNetworkPlayersViewController*, creationType>()));
}
}; // LocalNetworkPlayersViewController
#pragma pack(pop)
static check_size<sizeof(LocalNetworkPlayersViewController), 185 + sizeof(bool)> __GlobalNamespace_LocalNetworkPlayersViewControllerSizeCheck;
static_assert(sizeof(LocalNetworkPlayersViewController) == 0xBA);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::LocalNetworkPlayersViewController*, "", "LocalNetworkPlayersViewController");
| 52.405405
| 675
| 0.746648
|
darknight1050
|
85fa1b1b64a0a9bf281e92dcf003ea04f2beab63
| 7,853
|
cpp
|
C++
|
obliczanie-wieku/AgeCalculator.cpp
|
MHellFire/random-stuff
|
f8d05af9019df67fcf7164a3b716e4db17d18e6a
|
[
"MIT"
] | null | null | null |
obliczanie-wieku/AgeCalculator.cpp
|
MHellFire/random-stuff
|
f8d05af9019df67fcf7164a3b716e4db17d18e6a
|
[
"MIT"
] | null | null | null |
obliczanie-wieku/AgeCalculator.cpp
|
MHellFire/random-stuff
|
f8d05af9019df67fcf7164a3b716e4db17d18e6a
|
[
"MIT"
] | null | null | null |
/*********************************************************************************
* This file is part of Age Calculator. *
* *
* Copyright © 2019 Mariusz Helfajer *
* *
* This software may be modified and distributed under the terms *
* of the MIT license. See the LICENSE files for details. *
* *
* 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 <iostream>
#include <cmath>
#include <ctime>
#include <QDate>
#include <QtMath>
// Returns age[0] = years; age[1] = months; age[2] = days;
// or nullptr if any of the given dates is not valid or if the birth date is from the future.
int* calculateAge(const QDate &birthDate, const QDate &todayDate)
{
// check if the birth date is valid date
if (!birthDate.isValid())
return nullptr;
// check if the today date is valid date
if (!todayDate.isValid())
return nullptr;
// check if the birth date is not from the future
if (birthDate > todayDate)
return nullptr;
int *age = new int[3]; // age[0] = years; age[1] = months; age[2] = days;
int t1 = birthDate.year()*12 + birthDate.month() - 1; // total months for birthdate
int t2 = todayDate.year()*12 + todayDate.month() - 1; // total months for now
int dm = t2 - t1; // delta months
if (todayDate.day() >= birthDate.day())
{
age[0] = qFloor(dm/12); // years
age[1] = dm%12; // months
age[2] = todayDate.day() - birthDate.day(); // days
}
else
{
dm--;
age[0] = qFloor(dm/12); // years
age[1] = dm%12; // months
age[2] = birthDate.daysInMonth() - birthDate.day() + todayDate.day(); // days
}
return age;
}
// Returns true if the specified year is a leap year; otherwise returns false.
bool isLeapYear(int year)
{
// No year 0 in Gregorian calendar, so -1, -5, -9 etc are leap years
// ISO 8601 - year 0000 is being equal to 1 BC
if (year < 1)
++year;
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
// Returns the number of days in the month (28 to 31) for given date. Returns 0 if the date is invalid.
int daysInMonth(const tm &date)
{
const char monthDays[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (date.tm_mon == 2 && isLeapYear(date.tm_year))
return 29;
else
return monthDays[date.tm_mon];
}
// Returns age[0] = years; age[1] = months; age[2] = days;
// or nullptr if any of the given dates is not valid or if the birth date is from the future.
int* calculateAge2(const tm &birthDate, const tm &todayDate)
{
// TODO: check if dates are valid
// check if the birth date is not from the future
if (birthDate.tm_year > todayDate.tm_year)
return nullptr;
else if (birthDate.tm_year == todayDate.tm_year && birthDate.tm_mon > todayDate.tm_mon)
return nullptr;
else if (birthDate.tm_year == todayDate.tm_year && birthDate.tm_mon > todayDate.tm_mon && birthDate.tm_mday > todayDate.tm_mday)
return nullptr;
int *age = new int[3]; // age[0] = years; age[1] = months; age[2] = days;
int t1 = birthDate.tm_year*12 + birthDate.tm_mon - 1; // total months for birthdate
int t2 = todayDate.tm_year*12 + todayDate.tm_mon - 1; // total months for now
int dm = t2 - t1; // delta months
if (todayDate.tm_mday >= birthDate.tm_mday)
{
age[0] = int(floor(dm/12)); // years
age[1] = dm%12; // months
age[2] = todayDate.tm_mday - birthDate.tm_mday; // days
}
else
{
dm--;
age[0] = int(floor(dm/12)); // years
age[1] = dm%12; // months
age[2] = daysInMonth(birthDate) - birthDate.tm_mday + todayDate.tm_mday; // days
}
return age;
}
int main(int argc, char *argv[])
{
(void)(argc);
(void)(argv);
QDate birthDate(QDate(2006, 1, 30));
QDate currentDate(QDate::currentDate());
int *tmp = calculateAge(birthDate, currentDate);
if (tmp != nullptr)
{
std::cout << "Birth date: " << birthDate.toString("dd.MM.yyyy").toStdString() << std::endl;
std::cout << "Current date: " << currentDate.toString("dd.MM.yyyy").toStdString() << std::endl;
std::cout << "Years: " << tmp[0] << std::endl;
std::cout << "Months: " << tmp[1] << std::endl;
std::cout << "Days: " << tmp[2] << std::endl << std::endl;
}
delete []tmp;
tm birthDate2;
birthDate2.tm_year = birthDate.year();
birthDate2.tm_mon = birthDate.month();
birthDate2.tm_mday = birthDate.day();
tm currentDate2;
currentDate2.tm_year = currentDate.year();
currentDate2.tm_mon = currentDate.month();
currentDate2.tm_mday = currentDate.day();
int *tmp2 = calculateAge2(birthDate2, currentDate2);
if (tmp2 != nullptr)
{
char date[11];
birthDate2.tm_year-=1900; // int tm_year; years since 1900
birthDate2.tm_mon-=1; // int tm_mon; months since January [0, 11]
if (strftime(date, sizeof(date), "%d.%m.%Y", &birthDate2) != 0)
{
std::cout << "Birth date: " << date << std::endl;
}
currentDate2.tm_year-=1900; // int tm_year; years since 1900
currentDate2.tm_mon-=1; // int tm_mon; months since January [0, 11]
if (strftime(date, sizeof(date), "%d.%m.%Y", ¤tDate2) != 0)
{
std::cout << "Current date: " << date << std::endl;
}
std::cout << "Years: " << tmp2[0] << std::endl;
std::cout << "Months: " << tmp2[1] << std::endl;
std::cout << "Days: " << tmp2[2] << std::endl << std::endl;
}
delete []tmp2;
}
| 41.771277
| 132
| 0.517255
|
MHellFire
|
85fc290a665174108915a6b4f77f7fc8b8808d7b
| 459
|
hpp
|
C++
|
src/app.hpp
|
trazfr/alarm
|
ea511eb0f16945de2005d828f452c76fce9d77e7
|
[
"MIT"
] | null | null | null |
src/app.hpp
|
trazfr/alarm
|
ea511eb0f16945de2005d828f452c76fce9d77e7
|
[
"MIT"
] | null | null | null |
src/app.hpp
|
trazfr/alarm
|
ea511eb0f16945de2005d828f452c76fce9d77e7
|
[
"MIT"
] | null | null | null |
#pragma once
#include <memory>
/**
* @brief Represents the whole application
*/
class App
{
public:
struct Impl;
/**
* @attention the class keeps a reference to constructor's arguments. Make sure they stay valid
*/
explicit App(const char *configurationFile);
~App();
/**
* Runs the application
*
* This method only returns at exit time
*/
void run();
private:
std::unique_ptr<Impl> pimpl;
};
| 15.827586
| 99
| 0.614379
|
trazfr
|
85fe846c064c03a415db9da5779bc34a873d8e03
| 436
|
cpp
|
C++
|
matrix_using_array.cpp
|
xeroxzen/C-Crash-Course
|
d394d6d91f4f0126b3742a9d11abc129f3daaeb4
|
[
"MIT"
] | 1
|
2022-02-09T00:47:25.000Z
|
2022-02-09T00:47:25.000Z
|
matrix_using_array.cpp
|
xeroxzen/C-Crash-Course
|
d394d6d91f4f0126b3742a9d11abc129f3daaeb4
|
[
"MIT"
] | null | null | null |
matrix_using_array.cpp
|
xeroxzen/C-Crash-Course
|
d394d6d91f4f0126b3742a9d11abc129f3daaeb4
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(){
//Declare a 2 dimensional array of a 3x3 matrix
//Each matrix element has a value of 1 or 0
int matrix[3][3] = {
{1, 0, 1},
{0, 1, 0},
{1, 0, 1}
};
//print out the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
| 20.761905
| 51
| 0.444954
|
xeroxzen
|
85ff51c427c7553b4d4520a5dca730d35c5948db
| 917
|
cpp
|
C++
|
fenwick_tree/coder_rating.cpp
|
ankit2001/CP_Algos
|
eadc0f9cd92a5a01791e3171dfe894e6db948b2b
|
[
"MIT"
] | 1
|
2020-08-11T17:50:01.000Z
|
2020-08-11T17:50:01.000Z
|
fenwick_tree/coder_rating.cpp
|
ankit2001/CP_Algos
|
eadc0f9cd92a5a01791e3171dfe894e6db948b2b
|
[
"MIT"
] | null | null | null |
fenwick_tree/coder_rating.cpp
|
ankit2001/CP_Algos
|
eadc0f9cd92a5a01791e3171dfe894e6db948b2b
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
#define F first
#define S second
void update(ll index, vector<ll> &BIT){
for(ll i=index;i<=100000;i+=i&(-i)){
BIT[i]++;
}
}
ll query(ll index, vector<ll> &BIT){
ll count=0;
for(ll i=index;i>0;i-=i&(-i)){
count+=BIT[i];
}
return count;
}
int main(){
vector<ll> BIT(100001,0);
BIT[0]=0;
ll n;
cin>>n;
vector<pair<pair<ll,ll>,ll>> v(n);
for(ll i=0;i<n;i++){
ll x,y;
cin>>x>>y;
v[i]={{x,y},i};
}
ll ans[n];
sort(v.begin(),v.end());
for(ll i=0;i<n;i++){
ll end=i;
while(end<n and v[i].F.F==v[end].F.F and v[i].F.S==v[end].F.S){
end++;
}
for(ll j=i;j<end;j++){
ans[v[j].S]=query(v[j].F.S,BIT);
}
for(ll j=i;j<end;j++){
update(v[j].F.S,BIT);
}
i=end;
i--;
}
for(ll i=0;i<n;i++){
cout<<ans[i]<<endl;
}
return 0;
}
| 17.634615
| 68
| 0.485278
|
ankit2001
|
65a0b02f10bf6c385424cfdc0344cdf983b4fa58
| 1,352
|
hpp
|
C++
|
render_view.hpp
|
piccolo255/pde-pathtracer
|
d754583a308975b68675076f68f1194cbaa906ca
|
[
"Unlicense"
] | null | null | null |
render_view.hpp
|
piccolo255/pde-pathtracer
|
d754583a308975b68675076f68f1194cbaa906ca
|
[
"Unlicense"
] | null | null | null |
render_view.hpp
|
piccolo255/pde-pathtracer
|
d754583a308975b68675076f68f1194cbaa906ca
|
[
"Unlicense"
] | null | null | null |
#ifndef RENDER_VIEW_HPP
#define RENDER_VIEW_HPP
// Qt includes
#include <QWidget>
#include <QPainter>
#include <QList>
#include <QMap>
// C++ includes
// math expression parsing header
#include "muParser.h"
// Local includes
#include "ode_pathtracer.hpp"
class RenderView : public QWidget
{
Q_OBJECT
public:
explicit RenderView( QRect viewportArea
, QString transformationX
, QString transformationY
, QStringList paramNames
, QWidget *parent = 0 );
~RenderView();
void updateObjects( QList<PointValues> pointPathList, int maxPathLength );
private:
QRect viewRect;
QRect viewRectAlwaysVisible;
double pointX;
double pointY;
double t;
// QStringList paramsName;
// QMap<QString, double> paramsVal;
// QMap<QString, int> paramsIndex;
QVector<double> paramVals;
QVector<mu::Parser *> coordinateParsers;
QVector<QLineF> segments;
QVector<QColor> colors;
int maxSegments = 0;
void updateViewRect( QSize newViewRectSize );
void updateColors();
void ParserError( mu::Parser::exception_type &e );
signals:
public slots:
// QWidget interface
protected:
void paintEvent( QPaintEvent *event ) override;
void resizeEvent( QResizeEvent *event ) override;
};
#endif // RENDER_VIEW_HPP
| 21.460317
| 77
| 0.674556
|
piccolo255
|
65a34c65c61e56339bec1735c5007ea2009e2588
| 853
|
cpp
|
C++
|
dark_roads.cpp
|
mvgmb/Marathon
|
0dcc428a5e6858e2427fb40cefbd7453d1abcdb5
|
[
"Xnet",
"X11"
] | null | null | null |
dark_roads.cpp
|
mvgmb/Marathon
|
0dcc428a5e6858e2427fb40cefbd7453d1abcdb5
|
[
"Xnet",
"X11"
] | null | null | null |
dark_roads.cpp
|
mvgmb/Marathon
|
0dcc428a5e6858e2427fb40cefbd7453d1abcdb5
|
[
"Xnet",
"X11"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int parent[200005];
int size[200005];
vector<tuple<int,int,int> > lis;
int find(int x) {
if(x != parent[x]) parent[x] = find(parent[x]);
return parent[x];
}
bool same(int a, int b) {
return find(a) == find(b);
}
void unite(int a,int b) {
a = find(a);
b = find(b);
if(size[a] < size[b]) swap(a,b);
size[a] += size[b];
parent[b] = a;
}
int main() {
int m, n, u, v, w, i, c, tot;
while(cin >> m >> n && m != 0 && n != 0) {
for(i=0;i<m;i++) {
parent[i] = i;
size[i] = 1;
}
lis.clear();
tot = 0;
while(n--) {
cin >> u >> v >> w;
tot += w;
lis.push_back(make_tuple(w,u,v));
}
sort(lis.begin(),lis.end());
c = 0;
for(i=0;i<lis.size();i++) {
tie(w,u,v) = lis[i];
if(!same(u,v)) {
c += w;
unite(u,v);
}
}
cout << (tot- c) << endl;
}
return 0;
}
| 16.403846
| 48
| 0.494725
|
mvgmb
|
65a4129133678830b35540e7196ade3735b0d039
| 6,191
|
cpp
|
C++
|
flume/util/hadoop_conf_test.cpp
|
advancedxy/bigflow_python
|
8a244b483404fde7afc42eee98bc964da8ae03e2
|
[
"Apache-2.0"
] | 1
|
2021-02-18T20:13:34.000Z
|
2021-02-18T20:13:34.000Z
|
flume/util/hadoop_conf_test.cpp
|
advancedxy/bigflow_python
|
8a244b483404fde7afc42eee98bc964da8ae03e2
|
[
"Apache-2.0"
] | null | null | null |
flume/util/hadoop_conf_test.cpp
|
advancedxy/bigflow_python
|
8a244b483404fde7afc42eee98bc964da8ae03e2
|
[
"Apache-2.0"
] | null | null | null |
/***************************************************************************
*
* Copyright (c) 2013 Baidu, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
// Author: Zhang Yuncong (zhangyuncong@baidu.com)
//
// Description: Flume hadoop conf util test
#include <stdlib.h>
#include "flume/util/hadoop_conf.h"
#include "gtest/gtest.h"
namespace baidu {
namespace flume {
namespace util {
TEST(TestHadoopConf, TestFromFile) {
// backup & clear sys env
char* env_ugi = getenv(kHadoopJobUgi);
char* env_fs_name = getenv(kFsDefaultName);
unsetenv(kHadoopJobUgi);
unsetenv(kFsDefaultName);
HadoopConf conf("testdata/hadoop-site.xml");
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ("test,test", conf.hadoop_job_ugi());
ASSERT_EQ("hdfs://baidu.com:1234", conf.fs_defaultfs());
// restore sys env if necessary
if (env_ugi != NULL) {
setenv(kHadoopJobUgi, env_ugi, 1);
}
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
}
}
TEST(TestHadoopConf, TestFromEnv) {
// backup & set sys env
char* env_ugi = getenv(kHadoopJobUgi);
char* env_fs_name = getenv(kFsDefaultName);
const char* kExpectUgi = "env,env";
const char* kExpectFsName = "hdfs:///env.com:37213";
setenv(kHadoopJobUgi, kExpectUgi, 1);
setenv(kFsDefaultName, kExpectFsName, 1);
HadoopConf conf("testdata/hadoop-site.xml");
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_EQ(kExpectFsName, conf.fs_defaultfs());
// restore sys env
if (env_ugi != NULL) {
setenv(kHadoopJobUgi, env_ugi, 1);
} else {
unsetenv(kHadoopJobUgi);
}
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
} else {
unsetenv(kFsDefaultName);
}
}
TEST(TestHadoopConf, TestFromMap) {
const char* kExpectUgi = "app,app";
const char* kExpectFsName = "hdfs://app.com:34275";
HadoopConf::JobConfMap conf_map;
conf_map[kHadoopJobUgi] = kExpectUgi;
conf_map[kFsDefaultName] = kExpectFsName;
HadoopConf conf("testdata/hadoop-site.xml", conf_map);
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_EQ(kExpectFsName, conf.fs_defaultfs());
}
TEST(TestHadoopConf, TestPartialOverwrite1) {
// get fs name from conf file
// get ugi from conf map
char* env_fs_name = getenv(kFsDefaultName);
unsetenv(kFsDefaultName);
const char* kExpectUgi = "app,app";
HadoopConf::JobConfMap conf_map;
conf_map[kHadoopJobUgi] = kExpectUgi;
HadoopConf conf("testdata/hadoop-site.xml", conf_map);
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_EQ("hdfs://baidu.com:1234", conf.fs_defaultfs());
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
}
}
TEST(TestHadoopConf, TestPartialOverwrite2) {
// get fs name from env
// get ugi from conf map
char* env_ugi = getenv(kHadoopJobUgi);
char* env_fs_name = getenv(kFsDefaultName);
const char* kExpectUgi = "app,app";
const char* kExpectFsName = "hdfs:///env.com:37213";
setenv(kHadoopJobUgi, "ignore.me", 1);
setenv(kFsDefaultName, kExpectFsName, 1);
HadoopConf::JobConfMap conf_map;
conf_map[kHadoopJobUgi] = kExpectUgi;
HadoopConf conf("testdata/hadoop-site.xml", conf_map);
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_EQ(kExpectFsName, conf.fs_defaultfs());
if (env_ugi != NULL) {
setenv(kHadoopJobUgi, env_ugi, 1);
} else {
unsetenv(kHadoopJobUgi);
}
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
} else {
unsetenv(kFsDefaultName);
}
}
TEST(TestHadoopConf, TestMapOverwriteAll) {
// get both fs name and ugi from map
char* env_ugi = getenv(kHadoopJobUgi);
char* env_fs_name = getenv(kFsDefaultName);
const char* kExpectUgi = "app,app";
const char* kExpectFsName = "hdfs:///env.com:37213";
setenv(kHadoopJobUgi, "ignore.me", 1);
setenv(kFsDefaultName, "hdfs:///ignore.me:too", 1);
HadoopConf::JobConfMap conf_map;
conf_map[kHadoopJobUgi] = kExpectUgi;
conf_map[kFsDefaultName] = kExpectFsName;
HadoopConf conf("testdata/hadoop-site.xml", conf_map);
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_EQ(kExpectFsName, conf.fs_defaultfs());
if (env_ugi != NULL) {
setenv(kHadoopJobUgi, env_ugi, 1);
} else {
unsetenv(kHadoopJobUgi);
}
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
} else {
unsetenv(kFsDefaultName);
}
}
TEST(TestHadoopConf, TestEmptyFsDefaultName) {
char* env_fs_name = getenv(kFsDefaultName);
unsetenv(kFsDefaultName);
const char* kExpectUgi = "app,app";
HadoopConf::JobConfMap conf_map;
conf_map[kHadoopJobUgi] = kExpectUgi;
HadoopConf conf("testdata/hadoop-site-partial.xml", conf_map);
ASSERT_EQ("testdata/hadoop-site-partial.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_TRUE(conf.fs_defaultfs().empty());
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
}
}
} // namespace util
} // namespace flume
} // namespace baidu
| 31.586735
| 76
| 0.666613
|
advancedxy
|
65a4e8c1c6e529c6cdc1a015ccca4a644b955680
| 279
|
cpp
|
C++
|
Codeforces Online Judge Solve/all divs/main (9).cpp
|
Remonhasan/programming-solve
|
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
|
[
"Apache-2.0"
] | null | null | null |
Codeforces Online Judge Solve/all divs/main (9).cpp
|
Remonhasan/programming-solve
|
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
|
[
"Apache-2.0"
] | null | null | null |
Codeforces Online Judge Solve/all divs/main (9).cpp
|
Remonhasan/programming-solve
|
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
|
[
"Apache-2.0"
] | null | null | null |
/*last time Tumi ami from uap*/
#include <iostream>
using namespace std;
typedef long long ll;
int main() {
ll a,ami;
cin>>a>>ami;
ll tumi=a;
ll taka=0;
while(tumi<ami){
tumi*=a;
taka++;
}
if(tumi==ami)
cout<<"YES"<<endl<<taka;
else
cout<<"NO";
return 0;
}
| 13.285714
| 31
| 0.598566
|
Remonhasan
|
65a835ddf980515a6d34e3cce94fb15b7fd256e1
| 2,935
|
hpp
|
C++
|
componentLibraries/defaultLibrary/Signal/Sources&Sinks/SignalPulseWave.hpp
|
mjfwest/hopsan
|
77a0a1e69fd9588335b7e932f348972186cbdf6f
|
[
"Apache-2.0"
] | null | null | null |
componentLibraries/defaultLibrary/Signal/Sources&Sinks/SignalPulseWave.hpp
|
mjfwest/hopsan
|
77a0a1e69fd9588335b7e932f348972186cbdf6f
|
[
"Apache-2.0"
] | null | null | null |
componentLibraries/defaultLibrary/Signal/Sources&Sinks/SignalPulseWave.hpp
|
mjfwest/hopsan
|
77a0a1e69fd9588335b7e932f348972186cbdf6f
|
[
"Apache-2.0"
] | null | null | null |
/*-----------------------------------------------------------------------------
Copyright 2017 Hopsan Group
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.
The full license is available in the file LICENSE.
For details about the 'Hopsan Group' or information about Authors and
Contributors see the HOPSANGROUP and AUTHORS files that are located in
the Hopsan source code root directory.
-----------------------------------------------------------------------------*/
//!
//! @file SignalPulse.hpp
//! @author Peter Nordin <peter.nordin@liu.se>
//! @date 2012-03-29
//!
//! @brief Contains a pulse wave (train) signal generator
//!
//$Id$
#ifndef SIGNALPULSEWAVE_HPP
#define SIGNALPULSEWAVE_HPP
#include "ComponentEssentials.h"
#include <cmath>
namespace hopsan {
//!
//! @brief
//! @ingroup SignalComponents
//!
class SignalPulseWave : public ComponentSignal
{
private:
double *mpBaseValue;
double *mpStartTime;
double *mpPeriodT;
double *mpDutyCycle;
double *mpAmplitude;
double *mpOut;
public:
static Component *Creator()
{
return new SignalPulseWave();
}
void configure()
{
addInputVariable("y_0", "Base Value", "", 0.0, &mpBaseValue);
addInputVariable("y_A", "Amplitude", "", 1.0, &mpAmplitude);
addInputVariable("t_start", "Start Time", "Time", 0.0, &mpStartTime);
addInputVariable("dT", "Time Period", "Time", 1.0, &mpPeriodT);
addInputVariable("D", "Duty Cycle, (ratio 0<=x<=1)", "", 0.5, &mpDutyCycle);
addOutputVariable("out", "PulseWave", "", &mpOut);
}
void initialize()
{
(*mpOut) = (*mpBaseValue);
}
void simulateOneTimestep()
{
// +0.5*mTimestep to avoid ronding issues
const double time = (mTime-(*mpStartTime)+0.5*mTimestep);
const double periodT = (*mpPeriodT);
const bool high = (time - std::floor(time/periodT)*periodT) < (*mpDutyCycle)*periodT;
if ( (time > 0) && high)
{
(*mpOut) = (*mpBaseValue) + (*mpAmplitude); //During pulse
}
else
{
(*mpOut) = (*mpBaseValue); //Not during pulse
}
}
};
}
#endif // SIGNALPULSEWAVE_HPP
| 29.059406
| 97
| 0.563203
|
mjfwest
|
65acc90ed1a5c8e334436ca0894d3f2b89478da0
| 23,489
|
hpp
|
C++
|
include/ak_toolkit/markable.hpp
|
akrzemi1/markable
|
fc435319fb32ed5753e6ae6762f78d98e0d33c73
|
[
"BSL-1.0"
] | 82
|
2016-03-12T11:53:55.000Z
|
2022-02-17T15:18:02.000Z
|
include/ak_toolkit/markable.hpp
|
akrzemi1/markable
|
fc435319fb32ed5753e6ae6762f78d98e0d33c73
|
[
"BSL-1.0"
] | 10
|
2016-03-12T13:53:49.000Z
|
2020-12-17T22:20:16.000Z
|
include/ak_toolkit/markable.hpp
|
akrzemi1/markable
|
fc435319fb32ed5753e6ae6762f78d98e0d33c73
|
[
"BSL-1.0"
] | 11
|
2016-09-01T15:53:32.000Z
|
2021-09-28T15:51:32.000Z
|
// Copyright (C) 2015-2021 Andrzej Krzemienski.
//
// Use, modification, and distribution is subject to 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 AK_TOOLBOX_COMPACT_OPTIONAL_HEADER_GUARD_
#define AK_TOOLBOX_COMPACT_OPTIONAL_HEADER_GUARD_
#include <cassert>
#include <utility>
#include <limits>
#include <new>
#include <type_traits>
#include <limits>
# if defined AK_TOOLKIT_WITH_CONCEPTS
#include <concepts>
# endif
#if defined AK_TOOLBOX_NO_ARVANCED_CXX11
# define AK_TOOLKIT_NOEXCEPT
# define AK_TOOLKIT_IS_NOEXCEPT(E) true
# define AK_TOOLKIT_CONSTEXPR
# define AK_TOOLKIT_CONSTEXPR_OR_CONST const
# define AK_TOOLKIT_EXPLICIT_CONV
# define AK_TOOLKIT_NOEXCEPT_AS(E)
#else
# define AK_TOOLKIT_NOEXCEPT noexcept
# define AK_TOOLKIT_IS_NOEXCEPT(E) noexcept(E)
# define AK_TOOLKIT_CONSTEXPR constexpr
# define AK_TOOLKIT_CONSTEXPR_OR_CONST constexpr
# define AK_TOOLKIT_EXPLICIT_CONV explicit
# define AK_TOOLKIT_NOEXCEPT_AS(E) noexcept(noexcept(E))
# define AK_TOOLKIT_CONSTEXPR_NOCONST // fix in the future
#endif
#ifndef AK_TOOLKIT_LIKELY
# if defined __GNUC__
# define AK_TOOLKIT_LIKELY(EXPR) __builtin_expect(!!(EXPR), 1)
# else
# define AK_TOOLKIT_LIKELY(EXPR) (!!(EXPR))
# endif
#endif
#ifndef AK_TOOLKIT_ASSERT
# if defined NDEBUG
# define AK_TOOLKIT_ASSERT(EXPR) void(0)
# else
# define AK_TOOLKIT_ASSERT(EXPR) ( AK_TOOLKIT_LIKELY(EXPR) ? void(0) : []{assert(!#EXPR);}() )
# endif
#endif
#ifndef AK_TOOLKIT_ASSERTED_EXPRESSION
# if defined NDEBUG
# define AK_TOOLKIT_ASSERTED_EXPRESSION(CHECK, EXPR) (EXPR)
# else
# define AK_TOOLKIT_ASSERTED_EXPRESSION(CHECK, EXPR) (AK_TOOLKIT_LIKELY(CHECK) ? (EXPR) : ([]{assert(!#CHECK);}(), (EXPR)))
# endif
#endif
#if defined __cpp_concepts && __cpp_concepts == 201507
// TODO: will conditionally support concepts
#endif
namespace ak_toolkit {
namespace markable_ns {
# if defined AK_TOOLKIT_WITH_CONCEPTS
template <typename MP>
concept mark_policy =
requires
{
typename MP::value_type;
typename MP::storage_type;
typename MP::reference_type;
typename MP::representation_type;
} &&
requires(const typename MP::representation_type & cr,
typename MP::representation_type && rr,
const typename MP::storage_type & s,
const typename MP::value_type & cv,
typename MP::value_type && rv)
{
{ MP::marked_value() }
-> ::std::convertible_to<typename MP::representation_type>;
{ MP::is_marked_value(cr) }
-> ::std::convertible_to<bool>;
{ MP::access_value(s) }
-> ::std::same_as<typename MP::reference_type>;
{ MP::representation(s) }
-> ::std::same_as<const typename MP::representation_type &>;
{ MP::store_value(cv) }
-> ::std::convertible_to<typename MP::storage_type>;
{ MP::store_value(::std::move(rv)) }
-> ::std::convertible_to<typename MP::storage_type>;
{ MP::store_representation(cr) }
-> ::std::convertible_to<typename MP::storage_type>;
{ MP::store_representation(::std::move(rr)) }
-> ::std::convertible_to<typename MP::storage_type>;
};
# define AK_TOOLKIT_MARK_POLICY mark_policy
# else
# define AK_TOOLKIT_MARK_POLICY typename
# endif
struct default_tag{};
template <typename T, typename REPT = T, typename CREF = const T&, typename STOR = REPT>
struct markable_type
{
typedef T value_type; // the type we claim we (optionally) store
typedef REPT representation_type; // the type we use to represent the marked state
typedef CREF reference_type; // the type that we return upon "dereference"
typedef STOR storage_type; // the type we use for storage
static AK_TOOLKIT_CONSTEXPR reference_type access_value(const storage_type& v) { return reference_type(v); }
static AK_TOOLKIT_CONSTEXPR const representation_type& representation(const storage_type& v) { return v; }
static AK_TOOLKIT_CONSTEXPR const storage_type& store_value(const value_type& v) { return v; }
static AK_TOOLKIT_CONSTEXPR storage_type&& store_value(value_type&& v) { return std::move(v); }
static AK_TOOLKIT_CONSTEXPR const storage_type& store_representation(const representation_type& v) { return v; }
static AK_TOOLKIT_CONSTEXPR storage_type&& store_representation(representation_type&& v) { return std::move(v); }
};
template <typename T, T Val>
struct mark_int : markable_type<T>
{
static AK_TOOLKIT_CONSTEXPR T marked_value() AK_TOOLKIT_NOEXCEPT { return Val; }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(T v) AK_TOOLKIT_NOEXCEPT { return v == Val; }
};
template <typename FPT>
struct mark_fp_nan : markable_type<FPT>
{
static AK_TOOLKIT_CONSTEXPR FPT marked_value() AK_TOOLKIT_NOEXCEPT { return std::numeric_limits<FPT>::quiet_NaN(); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(FPT v) AK_TOOLKIT_NOEXCEPT { return v != v; }
};
template <typename T> // requires Regular<T>
struct mark_value_init : markable_type<T>
{
static AK_TOOLKIT_CONSTEXPR T marked_value() AK_TOOLKIT_NOEXCEPT_AS(T()) { return T(); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(const T& v) AK_TOOLKIT_NOEXCEPT_AS(T()) { return v == T(); }
};
template <typename T>
struct mark_stl_empty : markable_type<T>
{
static AK_TOOLKIT_CONSTEXPR T marked_value() AK_TOOLKIT_NOEXCEPT_AS(T()) { return T(); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(const T& v) { return v.empty(); }
};
template <typename OT>
struct mark_optional : markable_type<typename OT::value_type, OT>
{
typedef typename OT::value_type value_type;
typedef OT storage_type;
static OT marked_value() AK_TOOLKIT_NOEXCEPT { return OT(); }
static bool is_marked_value(const OT& v) { return !v; }
static const value_type& access_value(const storage_type& v) { return *v; }
static storage_type store_value(const value_type& v) { return v; }
static storage_type store_value(value_type&& v) { return std::move(v); }
};
struct mark_bool : markable_type<bool, char, bool>
{
static AK_TOOLKIT_CONSTEXPR char marked_value() AK_TOOLKIT_NOEXCEPT { return char(2); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(char v) AK_TOOLKIT_NOEXCEPT { return v == 2; }
static AK_TOOLKIT_CONSTEXPR bool access_value(const char& v) { return bool(v); }
static AK_TOOLKIT_CONSTEXPR char store_value(const bool& v) { return v; }
};
#ifndef AK_TOOLBOX_NO_UNDERLYING_TYPE
template <typename Enum, typename std::underlying_type<Enum>::type Val>
struct mark_enum : markable_type<Enum, typename std::underlying_type<Enum>::type, Enum>
{
typedef markable_type<Enum, typename std::underlying_type<Enum>::type, Enum> base;
static_assert(std::is_enum<Enum>::value, "mark_enum only works with enum types");
#else
template <typename Enum, int Val>
struct mark_enum : markable_type<Enum, int, Enum>
{
typedef markable_type<Enum, int, Enum> base;
static_assert(sizeof(Enum) == sizeof(int), "in this compiler underlying type of enum must be int");
#endif // AK_TOOLBOX_NO_UNDERLYING_TYPE
typedef typename base::representation_type representation_type;
typedef typename base::storage_type storage_type;
static AK_TOOLKIT_CONSTEXPR representation_type marked_value() AK_TOOLKIT_NOEXCEPT { return Val; }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(const representation_type& v) AK_TOOLKIT_NOEXCEPT { return v == Val; }
static AK_TOOLKIT_CONSTEXPR Enum access_value(const storage_type& v) AK_TOOLKIT_NOEXCEPT { return static_cast<Enum>(v); }
static AK_TOOLKIT_CONSTEXPR storage_type store_value(const Enum& v) AK_TOOLKIT_NOEXCEPT { return static_cast<storage_type>(v); }
};
namespace detail_ {
struct _init_nothing_tag {};
template <typename MP>
union dual_storage_union
{
typedef typename MP::value_type value_type;
typedef typename MP::representation_type representation_type;
char _nothing;
value_type _value;
representation_type _marking;
constexpr explicit dual_storage_union(_init_nothing_tag) AK_TOOLKIT_NOEXCEPT
: _nothing() {}
constexpr explicit dual_storage_union(representation_type && v) AK_TOOLKIT_NOEXCEPT_AS(representation_type(std::move(v)))
: _marking(std::move(v)) {}
constexpr explicit dual_storage_union(value_type && v) AK_TOOLKIT_NOEXCEPT_AS(value_type(std::move(v)))
: _value(std::move(v)) {}
constexpr explicit dual_storage_union(const value_type& v) AK_TOOLKIT_NOEXCEPT_AS(value_type(std::move(v)))
: _value(v) {}
~dual_storage_union() {/* nothing here; will be properly destroyed by the owner */}
};
template <typename MVP, typename = void>
struct check_safe_dual_storage_exception_safety : ::std::true_type {};
template <typename MVP>
struct check_safe_dual_storage_exception_safety<MVP, typename MVP::is_safe_dual_storage_mark_policy>
: std::integral_constant<bool, AK_TOOLKIT_IS_NOEXCEPT(typename MVP::representation_type(MVP::marked_value()))>
{
};
} // namespace detail_
template <typename T>
struct representation_of
{
static_assert(sizeof(T) == 0, "class template representation_of<T> needs to be specialized for your type");
};
template <typename MP>
struct dual_storage
{
typedef typename MP::value_type value_type;
typedef typename MP::representation_type representation_type;
typedef typename MP::reference_type reference_type;
private:
typedef detail_::dual_storage_union<MP> union_type;
union_type value_;
private:
void* address() { return static_cast<void*>(std::addressof(value_)); }
void construct_value(const value_type& v) { ::new (address()) value_type(v); }
void construct_value(value_type&& v) { ::new (address()) value_type(std::move(v)); }
void change_to_value(const value_type& v)
try {
destroy_storage();
construct_value(v);
}
catch (...)
{ // now, neither value nor no-value. We have to try to assign no-value
construct_storage_checked();
throw;
}
void change_to_value(value_type&& v)
try {
destroy_storage();
construct_value(std::move(v));
}
catch (...)
{ // now, neither value nor no-value. We have to try to assign no-value
construct_storage_checked();
throw;
}
void construct_storage() { ::new (address()) representation_type(MP::marked_value()); }
void construct_storage_checked() AK_TOOLKIT_NOEXCEPT { construct_storage(); } // std::terminate() if MP::marked_value() throws
void destroy_value() AK_TOOLKIT_NOEXCEPT { as_value().value_type::~value_type(); }
void destroy_storage() AK_TOOLKIT_NOEXCEPT { representation().representation_type::~representation_type(); }
public:
void clear_value() AK_TOOLKIT_NOEXCEPT { destroy_value(); construct_storage(); } // std::terminate() if MP::marked_value() throws
bool has_value() const AK_TOOLKIT_NOEXCEPT { return !MP::is_marked_value(representation()); }
value_type& as_value() { return value_._value; }
const value_type& as_value() const { return value_._value; }
public:
representation_type& representation() AK_TOOLKIT_NOEXCEPT { return value_._marking; }
const representation_type& representation() const AK_TOOLKIT_NOEXCEPT { return value_._marking; }
constexpr explicit dual_storage(representation_type&& mv) AK_TOOLKIT_NOEXCEPT_AS(union_type(std::move(mv)))
: value_(std::move(mv)) {}
constexpr explicit dual_storage(const value_type& v) AK_TOOLKIT_NOEXCEPT_AS(union_type(v))
: value_(v) {}
constexpr explicit dual_storage(value_type&& v) AK_TOOLKIT_NOEXCEPT_AS(union_type(std::move(v)))
: value_(std::move(v)) {}
dual_storage(const dual_storage& rhs) // TODO: add noexcept
: value_(detail_::_init_nothing_tag{})
{
if (rhs.has_value())
construct_value(rhs.as_value());
else
construct_storage();
}
dual_storage(dual_storage&& rhs) // TODO: add noexcept
: value_(detail_::_init_nothing_tag{})
{
if (rhs.has_value())
construct_value(std::move(rhs.as_value()));
else
construct_storage();
}
void operator=(const dual_storage& rhs)
{
if (has_value() && rhs.has_value())
{
as_value() = rhs.as_value();
}
else if (has_value() && !rhs.has_value())
{
clear_value();
}
else if (!has_value() && rhs.has_value())
{
change_to_value(rhs.as_value());
}
}
void operator=(dual_storage&& rhs) // TODO: add noexcept
{
if (has_value() && rhs.has_value())
{
as_value() = std::move(rhs.as_value());
}
else if (has_value() && !rhs.has_value())
{
clear_value();
}
else if (!has_value() && rhs.has_value())
{
change_to_value(std::move(rhs.as_value()));
}
}
void swap_impl(dual_storage& rhs)
{
using namespace std;
if (has_value() && rhs.has_value())
{
swap(as_value(), rhs.as_value());
}
else if (has_value() && !rhs.has_value())
{
rhs.change_to_value(std::move(as_value()));
clear_value();
}
else if (!has_value() && rhs.has_value())
{
change_to_value(std::move(rhs.as_value()));
rhs.clear_value();
}
}
friend void swap(dual_storage& lhs, dual_storage& rhs) { lhs.swap_impl(rhs); }
~dual_storage()
{
if (has_value())
destroy_value();
else
destroy_storage();
}
};
template <typename MPT, typename T, typename REP_T = typename representation_of<T>::type>
struct markable_dual_storage_type_unsafe
{
static_assert(sizeof(T) == sizeof(REP_T), "representation of T has to have the same size and alignment as T");
static_assert(std::is_standard_layout<T>::value, "T must be a Standard Layout type");
static_assert(std::is_standard_layout<REP_T>::value, "representation of T must be a Standard Layout type");
#ifndef AK_TOOLBOX_NO_ARVANCED_CXX11
static_assert(alignof(T) == alignof(REP_T), "representation of T has to have the same alignment as T");
#endif // AK_TOOLBOX_NO_ARVANCED_CXX11
// TODO: in C++20: static_assert(std::is_layout_compatible_v<T, REP_T>, "representation of T has to be layout-compatible with T");
typedef T value_type;
typedef REP_T representation_type;
typedef const T& reference_type;
typedef dual_storage<MPT> storage_type;
static reference_type access_value(const storage_type& v)
{ return v.as_value(); }
static const representation_type& representation(const storage_type& v)
{ return v.representation(); }
static storage_type store_value(const value_type& v)
{ return storage_type(v); }
static storage_type store_value(value_type&& v)
{ return storage_type(std::move(v)); }
static storage_type store_representation(const representation_type& r)
{ return storage_type(r); }
static storage_type store_representation(representation_type&& r)
{ return storage_type(std::move(r)); }
};
template <typename MPT, typename T, typename REP_T = typename representation_of<T>::type>
struct markable_dual_storage_type : markable_dual_storage_type_unsafe<MPT, T, REP_T>
{
// The presence of this typedef is a request to check if T is nothrow move constructible
typedef void is_safe_dual_storage_mark_policy;
};
// ### Ordering policies
class order_none {};
template <AK_TOOLKIT_MARK_POLICY MP, typename OP = order_none>
class markable;
class order_by_representation
{
template <typename MP, typename OP>
static bool unique_marked_value(const markable<MP, OP>& mk)
{
// returns false if mk has no value but its storage is different
// than the MP::marked_value().
return mk.has_value() || mk.representation_value() == MP::marked_value();
}
public:
template <typename MP, typename OP>
static auto equal(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.representation_value() == r.representation_value())
{
assert(unique_marked_value(l));
assert(unique_marked_value(r));
return l.representation_value() == r.representation_value();
}
template <typename MP, typename OP>
static auto less(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.representation_value() < r.representation_value())
{
assert(unique_marked_value(l));
assert(unique_marked_value(r));
return l.representation_value() < r.representation_value();
}
};
class order_by_value
{
public:
template <typename MP, typename OP>
static auto equal(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.value() == r.value())
{
return !l.has_value() ? !r.has_value() : r.has_value() && l.value() == r.value();
}
template <typename MP, typename OP>
static auto less(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.value() < r.value())
{
return !r.has_value() ? false : (!l.has_value() ? true : l.value() < r.value());
}
};
struct with_representation_t
{
AK_TOOLKIT_CONSTEXPR explicit with_representation_t() {}
};
AK_TOOLKIT_CONSTEXPR_OR_CONST with_representation_t with_representation {};
template <AK_TOOLKIT_MARK_POLICY MP, typename OP>
class markable
{
// The following assert is only in case a safe dual storage is used.
// It then checks if the value_type is nothrow move constructible.
// I cannot check it inside the dual storage, because I need a complete
// type to determine nothrow traits.
static_assert (detail_::check_safe_dual_storage_exception_safety<MP>::value,
"while building a markable type: representation of T must not throw exceptions from move constructor or when creating the marked value");
public:
typedef typename MP::value_type value_type;
typedef typename MP::representation_type representation_type;
typedef typename MP::reference_type reference_type;
private:
typename MP::storage_type _storage;
public:
AK_TOOLKIT_CONSTEXPR markable() AK_TOOLKIT_NOEXCEPT_AS(MP::marked_value())
: _storage(MP::store_representation(MP::marked_value())) {}
AK_TOOLKIT_CONSTEXPR explicit markable(const value_type& v)
: _storage(MP::store_value(v)) {}
AK_TOOLKIT_CONSTEXPR explicit markable(value_type&& v)
: _storage(MP::store_value(std::move(v))) {}
AK_TOOLKIT_CONSTEXPR explicit markable(with_representation_t, const representation_type& r)
: _storage(MP::store_representation(r)) {}
AK_TOOLKIT_CONSTEXPR explicit markable(with_representation_t, representation_type&& r)
: _storage(MP::store_representation(::std::move(r))) {}
AK_TOOLKIT_CONSTEXPR bool has_value() const {
return !MP::is_marked_value(MP::representation(_storage));
}
AK_TOOLKIT_CONSTEXPR reference_type value() const { return AK_TOOLKIT_ASSERT(has_value()), MP::access_value(_storage); }
AK_TOOLKIT_CONSTEXPR representation_type const& representation_value() const {
return MP::representation(_storage);
}
void assign(value_type&& v) { _storage = MP::store_value(std::move(v)); }
void assign(const value_type& v) { _storage = MP::store_value(v); }
void assign_representation(representation_type&& s) { _storage = MP::store_representation(std::move(s)); }
void assign_representation(representation_type const& s) { _storage = MP::store_representation(s); }
friend void swap(markable& lhs, markable& rhs) {
using std::swap; swap(lhs._storage, rhs._storage);
}
};
template <typename MP, typename OP>
auto operator==(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::equal(l, r))
{
return OP::equal(l, r);
}
template <typename MP, typename OP>
auto operator!=(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::equal(l, r))
{
return !OP::equal(l, r);
}
template <typename MP, typename OP>
auto operator<(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return OP::less(l, r);
}
template <typename MP, typename OP>
auto operator>(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return OP::less(r, l);
}
template <typename MP, typename OP>
auto operator<=(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return !OP::less(r, l);
}
template <typename MP, typename OP>
auto operator>=(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return !OP::less(l, r);
}
// This defines a customization point for selecting the default makred value
// policy for a given type
template <typename T, typename = void>
struct default_mark_policy
{
using type = mark_value_init<T>;
};
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_integral<T>::value>::type>
{
using type = mark_int<T, std::numeric_limits<T>::max()>;
};
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_floating_point<T>::value>::type>
{
using type = mark_fp_nan<T>;
};
template <>
struct default_mark_policy<bool, void>
{
using type = mark_bool;
};
#ifndef AK_TOOLBOX_NO_UNDERLYING_TYPE
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_enum<T>::value>::type>
{
using type = mark_enum<T, std::numeric_limits<typename std::underlying_type<T>::type>::max()>;
};
#else
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_enum<T>::value>::type>
{
using type = mark_enum<T, std::numeric_limits<int>::max()>;
};
#endif
template <typename T>
using default_markable = markable<typename default_mark_policy<T>::type, order_by_value>;
} // namespace markable_ns
using markable_ns::markable;
using markable_ns::markable_type;
using markable_ns::markable_dual_storage_type;
using markable_ns::markable_dual_storage_type_unsafe;
using markable_ns::mark_bool;
using markable_ns::mark_int;
using markable_ns::mark_fp_nan;
using markable_ns::mark_value_init;
using markable_ns::mark_optional;
using markable_ns::mark_stl_empty;
using markable_ns::mark_enum;
using markable_ns::order_none;
using markable_ns::order_by_representation;
using markable_ns::order_by_value;
using markable_ns::default_markable;
using markable_ns::with_representation;
using markable_ns::with_representation_t;
# if defined AK_TOOLKIT_WITH_CONCEPTS
using markable_ns::mark_policy;
static_assert(mark_policy<mark_bool>, "mark_policy test failed");
static_assert(mark_policy<mark_int<int, 0>>, "mark_policy test failed");
static_assert(mark_policy<mark_fp_nan<float>>, "mark_policy test failed");
static_assert(mark_policy<mark_value_init<int>>, "mark_policy test failed");
# endif
} // namespace ak_toolkit
// hashing
namespace std
{
template <typename MP>
struct hash<ak_toolkit::markable<MP, ak_toolkit::order_by_representation>>
{
typedef typename hash<typename MP::representation_type>::result_type result_type;
typedef ak_toolkit::markable<MP, ak_toolkit::order_by_representation> argument_type;
constexpr result_type operator()(argument_type const& arg) const {
return std::hash<typename MP::representation_type>{}(arg.representation_value());
}
};
template <typename MP>
struct hash<ak_toolkit::markable<MP, ak_toolkit::order_by_value>>
{
typedef typename hash<typename MP::value_type>::result_type result_type;
typedef ak_toolkit::markable<MP, ak_toolkit::order_by_value> argument_type;
constexpr result_type operator()(argument_type const& arg) const {
return arg.has_value() ? std::hash<typename MP::value_type>{}(arg.value()) : result_type{};
}
};
} // namespace std
#endif //AK_TOOLBOX_COMPACT_OPTIONAL_HEADER_GUARD_
| 33.036568
| 154
| 0.726255
|
akrzemi1
|
65afd1192c8f3c63a733e303442998fd22a9fc21
| 1,130
|
hpp
|
C++
|
src/game-objects/turret.hpp
|
Blackhawk-TA/TowerDefense
|
db852a65cae9579074e435fb0245fd9b69fb720d
|
[
"MIT"
] | 1
|
2022-01-02T15:02:09.000Z
|
2022-01-02T15:02:09.000Z
|
src/game-objects/turret.hpp
|
Blackhawk-TA/TowerDefense
|
db852a65cae9579074e435fb0245fd9b69fb720d
|
[
"MIT"
] | null | null | null |
src/game-objects/turret.hpp
|
Blackhawk-TA/TowerDefense
|
db852a65cae9579074e435fb0245fd9b69fb720d
|
[
"MIT"
] | 1
|
2021-05-02T18:25:51.000Z
|
2021-05-02T18:25:51.000Z
|
//
// Created by Daniel Peters on 08.04.21.
//
#pragma once
#include "../utils/utils.hpp"
using namespace blit;
class Turret {
public:
explicit Turret(Point position, TurretFacingDirection facing_direction);
void draw();
Rect get_rectangle() const;
TurretFacingDirection get_facing_direction();
uint8_t get_damage() const;
Point get_range() const;
Point get_barrel_position() const;
void animate();
bool is_animation_pending() const;
void activate_animation_pending();
private:
const uint8_t damage = 19;
const std::array<uint8_t, 5> animation_sprite_ids = {0, 56, 57, 58};
const Point range = Point(1, 4); // How far it can shoot to the left/right and forward
const Rect sprite_facing_up = Rect(10, 1, 1, 2);
const Rect sprite_facing_down = Rect(7, 2, 1, 2);
const Rect sprite_facing_left = Rect(8, 2, 2, 1);
Point spawn_position;
Point animation_position;
Point barrel_position; //The position where the turret fires from
Rect sprite;
SpriteTransform transform;
SpriteTransform animation_transform;
TurretFacingDirection facing_direction;
uint8_t animation_sprite_index;
bool animation_pending;
};
| 27.560976
| 87
| 0.761947
|
Blackhawk-TA
|
65b3d0ef272427bbf9499c284f7b66a4af56504a
| 17,757
|
cc
|
C++
|
informal_code/cfsqp/local_fan.cc
|
fbrausse/flyspeck
|
66f4ef0f9252c382333586fc07787e64d8a4bbfb
|
[
"MIT"
] | 125
|
2016-03-22T22:29:23.000Z
|
2022-02-15T05:43:43.000Z
|
informal_code/cfsqp/local_fan.cc
|
fbrausse/flyspeck
|
66f4ef0f9252c382333586fc07787e64d8a4bbfb
|
[
"MIT"
] | 4
|
2015-10-13T17:38:34.000Z
|
2020-11-26T19:54:19.000Z
|
informal_code/cfsqp/local_fan.cc
|
fbrausse/flyspeck
|
66f4ef0f9252c382333586fc07787e64d8a4bbfb
|
[
"MIT"
] | 9
|
2017-06-21T08:48:56.000Z
|
2021-05-13T02:07:27.000Z
|
/* ========================================================================== */
/* FLYSPECK - CFSQP */
/* */
/* Nonlinear Inequalities, C++ Nonrigorous Numerical Optimization */
/* Chapter: Local Fan */
/* Author: Thomas C. Hales */
/* Date: 2010-03-01 */
/* ========================================================================== */
#include <iomanip.h>
#include <iostream.h>
#include <math.h>
#include "Minimizer.h"
#include "numerical.h"
// local_fan.cc
// $ make local_fan.o
// $ ./local_fan.o
// constructor calls optimizer. No need to place in main loop.
class trialdata {
public:
trialdata(Minimizer M,char* s) {
M.coutReport(s);
};
};
double Power(double a,int b) {
return pow(a,(float) b);
}
int trialcount = 300;
double eps = 1.0e-6;
double s2 = sqrt(2.0);
double s8 = sqrt(8.0);
double h0 = 1.26;
double sol0 = 0.5512855984325309;
////////// NEW INEQ
double taum_d1(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-8;
return (taum(y1+h,y2,y3,y4,y5,y6)-taum(y1,y2,y3,y4,y5,y6))/h;
}
double taum_d2(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-8;
return (taum(y1+h,y2,y3,y4,y5,y6)-2*taum(y1,y2,y3,y4,y5,y6) + taum(y1-h,y2,y3,y4,y5,y6))/(h*h);
}
// this is minimized. failure reported if min is negative.
void t1(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum_d1(y[0],y[1],y[2],y[3],y[4],y[5]) ;
*ret = r*r ;
}
Minimizer m1() {
double xmin[6]= {2,2,2,2.52,2.52,2};
double xmax[6]= {2.52,2.52,2.52,3.0,2.52,2.52};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t1;
return M;
}
//trialdata d1(m1(),"ID[DWXPIHA] ID[] d1: extreme-- FALSE!!. Gives C/E to y1-deformaton");
////////// NEW INEQ
////////// NEW INEQ
// d0
double gt0(double a,double b,double c,double e1,double e2,double e3) {
return( dih_y(2,2,2,a,b,c)*e1
+ dih2_y(2,2,2,a,b,c)*e2
+ dih3_y(2,2,2,a,b,c)*e3);
}
double gt1(double a,double b,double c,double e1,double e2,double e3) {
return( (-4*(Power(a,4)*e1 + 8*(Power(b,2) - Power(c,2))*(e2 - e3) -
Power(a,2)*(16*e1 + (-8 + Power(b,2))*e2 +
(-8 + Power(c,2))*e3)))/(a*(16-a*a)) );
}
double gt2(double a,double b,double c,double e1,double e2,double e3) {
double num = 8*(2*Power(a,10)*e1 - 256*Power(Power(b,2) - Power(c,2),3)*
(e2 - e3) - Power(a,6)*
(2*(-256 + Power(b,4) - 2*Power(b,2)*Power(c,2) +
Power(c,4))*e1 +
(Power(b,4)*(-8 + Power(c,2)) -
16*Power(b,2)*(3 + Power(c,2)) +
16*(16 + 9*Power(c,2)))*e2 +
(Power(b,2)*(144 - 16*Power(c,2) + Power(c,4)) -
8*(-32 + 6*Power(c,2) + Power(c,4)))*e3) +
Power(a,8)*(-64*e1 -
6*((-8 + Power(b,2))*e2 + (-8 + Power(c,2))*e3)) -
2*Power(a,4)*(Power(b,2) - Power(c,2))*
(Power(b,4)*e2 + 8*Power(c,2)*(4*e1 + 9*e2 - 7*e3) +
384*(e2 - e3) - Power(c,4)*e3 +
Power(b,2)*(-32*e1 + (56 - 9*Power(c,2))*e2 +
9*(-8 + Power(c,2))*e3)) +
16*Power(a,2)*(Power(b,2) - Power(c,2))*
(Power(b,4)*(e2 - 3*e3) -
4*Power(b,2)*(8*e1 + (-20 + 3*Power(c,2))*e2 -
3*(-4 + Power(c,2))*e3) +
Power(c,2)*(32*e1 + 3*(16 + Power(c,2))*e2 -
(80 + Power(c,2))*e3))) ;
double den = Power(a* (16 - a*a),2);
return( num/den);
}
//constraint delta>0, deriv2>0.
void deltaposlast(int numargs,int whichFn,double* y, double* ret,void*) {
double a = y[3]; double b = y[4]; double c= y[5];
double e1 = y[0]; double e2 = y[1]; double e3 = y[2];
double deriv = gt1(a,b,c,e1,e2,e3);
double deriv2 = gt2(a,b,c,e1,e2,e3);
double r= -deriv2;
if (whichFn==1) { r = -delta_y(2,2,2,y[3],y[4],y[5]); }
*ret = r;
}
// this is minimized. failure reported if min is negative.
void t0(int numargs,int whichFn,double* y, double* ret,void*) {
double a = y[3]; double b = y[4]; double c= y[5];
double e1 = y[0]; double e2 = y[1]; double e3 = y[2];
double deriv= gt1(a,b,c,e1,e2,e3);
double deriv2 = gt2(a,b,c,e1,e2,e3);
double r= deriv*deriv - 0.01*deriv2;
// 0.00001 -> 0.00129
// 0.0001 -> 0.01289
// 0.001 -> 0.1225
// 0.01 -> 0.89 // use this
// 0.1 -> -655.814.
*ret = r ;
}
Minimizer m0() {
double t = 1.0 + sol0/pi();
double xmin[6]= {1,1,1,2/h0,2/h0,2/h0};
double xmax[6]= {t,t,t,4,4,4};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t0;
return M;
}
trialdata d0(m0(),"ID[2065952723] d0: Lexell variant.");
double cc(double y1,double y2,double y,double a,double b) {
// Delta_y(y1,y2,y,a,b,cc)=0.
double x1 = y1*y1;
double x2 = y2*y2;
double x = y*y;
double aa = a*a;
double bb = b*b;
double ub = U(bb,x,x1);
double ua = U(aa,x,x2);
double dd = -aa*bb + aa*x + bb*x - x*x + aa*x1 + x*x1 + bb*x2 + x*x2 - x1*x2;
double c = (1.0/(2.0*x))*(dd + sqrt(ua*ub));
return sqrt(c);
}
double taum_e0(double y1,double y2,double y3,double y4,double y5,double y) {
double a = 2.0;
double b = 2.0;
double c = cc(y1,y2,y,a,b);
return taum(y1,y2,y3,y4,y5,c) + pi()*rho(y);
}
double taum_e1(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-8;
return (taum_e0(y1,y2,y3,y4,y5,y6+h)-taum_e0(y1,y2,y3,y4,y5,y6))/h;
}
double taum_e2(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-4;
return (taum_e0(y1,y2,y3,y4,y5,y6+h)-2*taum_e0(y1,y2,y3,y4,y5,y6) + taum_e0(y1,y2,y3,y4,y5,y6-h))/(h*h);
}
void c2(int numargs,int whichFn,double* y, double* ret,void*) {
*ret = -taum_e2(y[0],y[1],y[2],y[3],y[4],y[5]);
}
// this is minimized. failure reported if min is negative.
void t2(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum_e1(y[0],y[1],y[2],y[3],y[4],y[5]) ;
double r2 = taum_e2(y[0],y[1],y[2],y[3],y[4],y[5]) ;
*ret = r*r ;
// 0.01 gives neg
//
}
Minimizer m2() {
double xmin[6]= {2,2,2,2,2,2};
double xmax[6]= {2.52,2.52,2.52,4.0,2.52,2.52};
Minimizer M(trialcount,6,1,xmin,xmax);
M.func = t2;
M.cFunc = c2;
return M;
}
//trialdata d2(m2(),"experiment ID[] ID[] d2: gives C/E to a particular deformation. Adjusting the height at a flat vertex.");
////////// NEW INEQ
double taum4_d1(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-8;
return (taum(y1,y2,y3,y4+h,y5,y6)-taum(y1,y2,y3,y4,y5,y6))/h;
}
double taum4_d2(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-4;
return (taum(y1,y2,y3,y4+h,y5,y6)-2*taum(y1,y2,y3,y4,y5,y6) + taum(y1,y2,y3,y4-h,y5,y6))/(h*h);
}
void t11(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum4_d1(y[0],y[1],y[2],y[3],y[4],y[5])+taum4_d1(y[6],y[1],y[2],y[3],y[7],y[8]);
double s= taum4_d2(y[0],y[1],y[2],y[3],y[4],y[5])+taum4_d2(y[6],y[1],y[2],y[3],y[7],y[8]);
*ret = r*r - 0.01*s ;
}
void c11(int numargs,int whichFn,double* y, double* ret,void*) {
double s= taum4_d2(y[0],y[1],y[2],y[3],y[4],y[5])+taum4_d2(y[6],y[1],y[2],y[3],y[7],y[8]);
switch(whichFn) {
case 1: *ret = y[3]-crossdiag(y);
break;
case 2: *ret = dih3_y(y[0],y[1],y[2],y[3],y[4],y[5]) + dih_y(y[2],y[1],y[6],y[8],y[7],y[3]) - pi();
break;
case 3: *ret = - delta_y(y[0],y[1],y[2],y[3],y[4],y[5]);
break;
case 4: *ret = - delta_y(y[2],y[1],y[6],y[8],y[7],y[3]);
break;
case 5: *ret = -s;
break;
default: *ret = -s;
break;
}
}
Minimizer m11() {
double xmin[9]= {2,2,2, 2.52,2,2.52, 2,2,2};
double xmax[9]= {2.52,2.52,2.52, 3.9,2.52,3.9, 2.52,2.52,2.52};//ok to 4.0
Minimizer M(trialcount,9,4,xmin,xmax);
M.func = t11;
M.cFunc = c11;
return M;
}
trialdata d11(m11(),"m11: ID[2986512815] cc:qua: two simplices common diagonal, no local minimum, (not full domain)");
/*
Minimizer M(trialcount*300,9,4,xmin,xmax);
constrained min: 0.0049666912319060166
variables: {2.02287626223235639, 2.52000000000000002, 2.5199999999994307, 2.86885817213602401, 2.00649572338011328, 2.58689726914902973, 2.00000000000637002, 2.00000000000699529, 2.00000000000699529}
*/
////////// NEW INEQ
void t12(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5]) + 1.0e-8;
*ret = r;
}
Minimizer m12() {
double xmin[6]= {2,2,2,2,2,2};
double xmax[6]= {2.52,2.52,2.52,2,2,2};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t12;
return M;
}
trialdata d12(m12(),"d12: ID[6147439478] Main Inequality Triangles [3,0]");
////////// NEW INEQ
void t13(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])-0.103;
*ret = r;
}
Minimizer m13() {
double xmin[6]= {2,2,2,2,2,2.52};
double xmax[6]= {2.52,2.52,2.52,2,2,2.52};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t13;
return M;
}
trialdata d13(m13(),"d13: ID[4760233334] Main Inequality Triangles [2,1]");
////////// NEW INEQ
void t14(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])-0.2759;
*ret = r;
}
Minimizer m14() {
double xmin[6]= {2,2,2,2,2.52,2.52};
double xmax[6]= {2.52,2.52,2.52,2,2.52,2.52};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t14;
return M;
}
trialdata d14(m14(),"d14: ID[4663664691] Main Inequality Triangles [1,2]");
////////// NEW INEQ
void t15(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])-0.4488;
*ret = r;
}
Minimizer m15() {
double xmin[6]= {2,2,2,2.52,2.52,2.52};
double xmax[6]= {2.52,2.52,2.52,2.52,2.52,2.52};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t15;
return M;
}
trialdata d15(m15(),"d15: ID[9098044151] Main Inequality Triangles [0,3]");
////////// NEW INEQ
void t16(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.206;
*ret = r;
}
Minimizer m16() {
double xmin[9]= {2,2,2,2.52,2,2,2,2,2};
double xmax[9]= {2.52,2.52,2.52,sqrt(8.0),2,2,2.52,2,2};
Minimizer M(trialcount,9,0,xmin,xmax);
M.func = t16;
return M;
}
trialdata d16(m16(),"d16: ID[] Main Inequality Quad [4,0]");
////////// NEW INEQ
void t17(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.3789;
*ret = r;
}
Minimizer m17() {
double xmin[9]= {2,2,2,2.52,2.52,2,2,2,2};
double xmax[9]= {2.52,2.52,2.52,3.1,2.52,2,2.52,2,2}; // shorter diag.
Minimizer M(trialcount,9,0,xmin,xmax);
M.func = t17;
return M;
}
trialdata d17(m17(),"d17: ID[] Main Inequality Quad [3,1]");
////////// NEW INEQ
void t18(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.5518;
*ret = r;
}
Minimizer m18() {
double xmin[9]= {2,2,2,2.52,2.52,2,2,2.52,2};
double xmax[9]= {2.52,2.52,2.52,3.22,2.52,2,2.52,2.52,2}; // shorter diag.
Minimizer M(trialcount,9,0,xmin,xmax);
M.func = t18;
return M;
}
trialdata d18(m18(),"d18: ID[] Main Inequality Quad [2,2]a");
////////// NEW INEQ
void t19(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.5518;
*ret = r;
}
Minimizer m19() {
double xmin[9]= {2,2,2,2.52,2.52,2.52,2,2,2};
double xmax[9]= {2.52,2.52,2.52,3.2,2.52,2.52,2.52,2,2}; // shorter diag.
Minimizer M(trialcount,9,0,xmin,xmax);
M.func = t19;
return M;
}
trialdata d19(m19(),"d19: ID[] Main Inequality Quad [2,2]b");
////////// NEW INEQ
void t20(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.5518;
*ret = r;
}
Minimizer m20() {
double xmin[9]= {2,2,2,2.52,2.52,2,2,2,2.52};
double xmax[9]= {2.52,2.52,2.52,3.2,2.52,2,2.52,2,2.52}; // shorter diag.
Minimizer M(trialcount,9,0,xmin,xmax);
M.func = t20;
return M;
}
trialdata d20(m20(),"d20: ID[] Main Inequality Quad [2,2]c");
////////// NEW INEQ
void t21(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.5518;
*ret = r;
}
void c21(int numargs,int whichFn,double* y, double* ret,void*) {
double r= -crossdiag(y) + y[3];
*ret = r;
}
Minimizer m21() {
double xmin[9]= {2,2,2,2.52,2.52,2,2,2,2.52};
double xmax[9]= {2.52,2.52,2.52,3.57,2.52,2.52,2.52,2.52,2.52}; // shorter diag.
Minimizer M(trialcount,9,1,xmin,xmax);
M.func = t21;
M.cFunc = c21;
return M;
}
trialdata d21(m21(),"d21: ID[] Main Inequality Quad [2,2]d");
////////// NEW INEQ
void t22(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])
+taum(y[0],y[2],y[6],y[7],y[8],y[4])
+taum(y[0],y[6],y[9],y[10],y[11],y[8])
-0.4819;
*ret = r;
}
void c22(int numargs,int whichFn,double* y, double* ret,void*) {
double r = 0;
switch(whichFn) {
case 1: r = dih_y(y[0],y[1],y[2],y[3],y[4],y[5])
+dih_y(y[0],y[2],y[6],y[7],y[8],y[4])
+dih_y(y[0],y[6],y[9],y[10],y[11],y[8]) - dih_y(y[0],y[1],y[9],2.52,y[11],y[5]);
break;
case 2:
r = dih_y(y[2],y[0],y[1],y[5],y[3],y[4]) + dih_y(y[2],y[0],y[6],y[8],y[7],y[4])
- dih_y(y[2],y[1],y[6],2.52,y[7],y[3]);
break;
case 3:
r = dih_y(y[6],y[2],y[0],y[4],y[8],y[7])+dih_y(y[6],y[0],y[9],y[11],y[10],y[8])
- dih_y(y[6],y[2],y[9],2.52,y[10],y[7]);
break;
case 4:
r=delta_y(y[0],y[1],y[2],y[3],y[4],y[5]);
break;
default:
r=delta_y(y[0],y[6],y[9],y[10],y[11],y[8]);
break;
}
*ret = -r;
}
Minimizer m22() {
double xmin[12]= {2,2,2, 2,2.52,2, 2,2,2.52, 2,2,2};
double xmax[12]= {2.52,2.52,2.52, 2,3,2, 2.52,2,3, 2.52,2,2};
Minimizer M(trialcount,12,5,xmin,xmax);
M.func = t22;
M.cFunc = c22;
return M;
}
trialdata d22(m22(),"d22: ID[] Main Inequality Pent [5,0] (not full domain)");
////////// NEW INEQ
void t23(int numargs,int whichFn,double* y, double* ret,void*) {
// these label vertices of triangulation of a pentagon.
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])
+taum(y[0],y[2],y[6],y[7],y[8],y[4])
+taum(y[0],y[6],y[9],y[10],y[11],y[8])
-0.6548;
*ret = r;
}
void c23(int numargs,int whichFn,double* y, double* ret,void*) {
double r = 0;
switch(whichFn) {
case 1: r = dih_y(y[0],y[1],y[2],y[3],y[4],y[5])
+dih_y(y[0],y[2],y[6],y[7],y[8],y[4])
+dih_y(y[0],y[6],y[9],y[10],y[11],y[8]) - dih_y(y[0],y[1],y[9],2.52,y[11],y[5]);
break;
case 2:
r = dih_y(y[2],y[0],y[1],y[5],y[3],y[4]) + dih_y(y[2],y[0],y[6],y[8],y[7],y[4])
- dih_y(y[2],y[1],y[6],2.52,y[7],y[3]);
break;
case 3:
r = dih_y(y[6],y[2],y[0],y[4],y[8],y[7])+dih_y(y[6],y[0],y[9],y[11],y[10],y[8])
- dih_y(y[6],y[2],y[9],2.52,y[10],y[7]);
break;
case 4:
r=delta_y(y[0],y[1],y[2],y[3],y[4],y[5]);
break;
default:
r=delta_y(y[0],y[6],y[9],y[10],y[11],y[8]);
break;
}
*ret = -r;
}
Minimizer m23() {
double xmin[12]= {2,2,2, 2,2.52,2, 2,2.52,2.52, 2,2,2};
double xmax[12]= {2.52,2.52,2.52, 2.52,3,2.52, 2.52,2.52,3, 2.52,2.52,2.52};
Minimizer M(trialcount,12,5,xmin,xmax);
M.func = t23;
M.cFunc = c23;
return M;
}
trialdata d23(m23(),"d23: ID[] Main Inequality Pent [4,1] (not full domain)");
////////// NEW INEQ
void t24(int numargs,int whichFn,double* y, double* ret,void*) {
// these label vertices of triangulation of a hexagon.
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])
+taum(y[6],y[1],y[2],y[3],y[7],y[8])
+taum(y[9],y[0],y[2],y[4],y[11],y[10])
+taum(y[12],y[0],y[1],y[5],y[13],y[14])
-0.7578;
*ret = r;
}
void c24(int numargs,int whichFn,double* y, double* ret,void*) {
double r = 0;
switch(whichFn) {
case 1: r = dih_y(y[0],y[1],y[2],y[3],y[4],y[5])
+dih_y(y[0],y[12],y[1],y[13],y[5],y[14])
+dih_y(y[0],y[9],y[2],y[11],y[4],y[10])
- dih_y(y[0],y[9],y[12],2.52,y[14],y[10]);
break;
case 2:
r = dih_y(y[1],y[0],y[2],y[4],y[3],y[5])
+dih_y(y[1],y[0],y[12],y[14],y[13],y[5])
+dih_y(y[1],y[2],y[6],y[7],y[8],y[3])
- dih_y(y[1],y[12],y[6],2.52,y[8],y[13]);
break;
case 3:
r = dih_y(y[2],y[1],y[0],y[5],y[4],y[3])
+dih_y(y[2],y[6],y[1],y[8],y[3],y[7])
+dih_y(y[2],y[0],y[9],y[10],y[11],y[4])
- dih_y(y[2],y[9],y[6],2.52,y[7],y[11]);
break;
case 4:
r=delta_y(y[6],y[1],y[2],y[3],y[7],y[8]);
break;
case 5:
r=delta_y(y[9],y[0],y[2],y[4],y[11],y[10]);
break;
case 6:
r=delta_y(y[12],y[0],y[1],y[5],y[13],y[14]);
break;
case 7:
r = crossdiag(y) - y[3];
break;
case 8:
r = y[3]- y[4];
break;
case 9:
r = delta_y(y[0],y[1],y[2],y[3],y[4],y[5]);
break;
default: r = y[4]-y[5];
}
*ret = -r;
}
Minimizer m24() {
double xmin[15]= {2,2,2, 2.52,2.52,2.52, 2,2,2, 2,2,2, 2,2,2};
double xmax[15]= {2.52,2.52,2.52, 3.8,3.8,3.8, 2.52,2.52,2.52, 2.52,2.52,2.52, 2.52,2.52,2.52};
Minimizer M(trialcount,15,10,xmin,xmax);
M.func = t24;
M.cFunc = c24;
return M;
}
trialdata d24(m24(),"d24: ID[] Main Inequality Hex [6,0] (not full domain)");
int main()
{
// cout << dih_y (2.01,2.02,2.03,2.04,2.05,2.06);;
double y[9] = {2.01757248069328288, 2.00385313357932526, 2.05784751769748242,
2.66743320268093287, 2.02045376048810033, 3.7968261622461,
2.08361068848451136, 2.17839994782590241, 2.01394807769320305};
cout << dih3_y(y[0],y[1],y[2],y[3],y[4],y[5]) + dih_y(y[2],y[1],y[6],y[8],y[7],y[3]) - pi();
}
| 32.403285
| 199
| 0.545982
|
fbrausse
|
65b4ff162151685abad28b68ececdc12f4190c3b
| 1,347
|
hpp
|
C++
|
stan/math/prim/fun/pow.hpp
|
bayesmix-dev/math
|
3616f7195adc95ef8e719a2af845d61102bc9272
|
[
"BSD-3-Clause"
] | 1
|
2020-06-14T14:33:37.000Z
|
2020-06-14T14:33:37.000Z
|
stan/math/prim/fun/pow.hpp
|
bayesmix-dev/math
|
3616f7195adc95ef8e719a2af845d61102bc9272
|
[
"BSD-3-Clause"
] | null | null | null |
stan/math/prim/fun/pow.hpp
|
bayesmix-dev/math
|
3616f7195adc95ef8e719a2af845d61102bc9272
|
[
"BSD-3-Clause"
] | 1
|
2020-05-10T12:55:07.000Z
|
2020-05-10T12:55:07.000Z
|
#ifndef STAN_MATH_PRIM_FUN_POW_HPP
#define STAN_MATH_PRIM_FUN_POW_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/functor/apply_scalar_binary.hpp>
#include <cmath>
#include <complex>
namespace stan {
namespace math {
namespace internal {
/**
* Return the first argument raised to the power of the second
* argument. At least one of the arguments must be a complex number.
*
* @tparam U type of base
* @tparam V type of exponent
* @param[in] x base
* @param[in] y exponent
* @return base raised to the power of the exponent
*/
template <typename U, typename V>
inline complex_return_t<U, V> complex_pow(const U& x, const V& y) {
return exp(y * log(x));
}
} // namespace internal
/**
* Enables the vectorised application of the pow function, when
* the first and/or second arguments are containers.
*
* @tparam T1 type of first input
* @tparam T2 type of second input
* @param a First input
* @param b Second input
* @return pow function applied to the two inputs.
*/
template <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr>
inline auto pow(const T1& a, const T2& b) {
return apply_scalar_binary(a, b, [&](const auto& c, const auto& d) {
using std::pow;
return pow(c, d);
});
}
} // namespace math
} // namespace stan
#endif
| 26.411765
| 79
| 0.709725
|
bayesmix-dev
|
65b6e02cc3a10b30145392598890c316458aa999
| 641
|
cpp
|
C++
|
Sunny-Core/01_FRAMEWORK/graphics/ModelManager.cpp
|
adunStudio/Sunny
|
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
|
[
"Apache-2.0"
] | 20
|
2018-01-19T06:28:36.000Z
|
2021-08-06T14:06:13.000Z
|
Sunny-Core/01_FRAMEWORK/graphics/ModelManager.cpp
|
adunStudio/Sunny
|
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
|
[
"Apache-2.0"
] | null | null | null |
Sunny-Core/01_FRAMEWORK/graphics/ModelManager.cpp
|
adunStudio/Sunny
|
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
|
[
"Apache-2.0"
] | 3
|
2019-01-29T08:58:04.000Z
|
2021-01-02T06:33:20.000Z
|
#include "ModelManager.h"
namespace sunny
{
namespace graphics
{
std::map<std::string, Model*> ModelManager::s_map;
Model* ModelManager::Add(const::std::string& name, Model* Model)
{
s_map[name] = Model;
return Model;
}
void ModelManager::Clean()
{
for (auto it = s_map.begin(); it != s_map.end(); ++it)
{
if (it->second)
{
delete it->second;
}
}
}
Model* ModelManager::Get(const std::string& name)
{
return s_map[name];
}
Mesh* ModelManager::GetMesh(const std::string& name)
{
if (s_map[name] == nullptr) return nullptr;
return s_map[name]->GetMesh();
}
}
}
| 16.435897
| 66
| 0.599064
|
adunStudio
|
65c8012df9eabd09c01fa12e47b597f1c3679be8
| 3,453
|
hxx
|
C++
|
src/istream/Handler.hxx
|
CM4all/beng-proxy
|
ce5a81f7969bc5cb6c5985cdc98f61ef8b5c6159
|
[
"BSD-2-Clause"
] | 35
|
2017-08-16T06:52:26.000Z
|
2022-03-27T21:49:01.000Z
|
src/istream/Handler.hxx
|
nn6n/beng-proxy
|
2cf351da656de6fbace3048ee90a8a6a72f6165c
|
[
"BSD-2-Clause"
] | 2
|
2017-12-22T15:34:23.000Z
|
2022-03-08T04:15:23.000Z
|
src/istream/Handler.hxx
|
nn6n/beng-proxy
|
2cf351da656de6fbace3048ee90a8a6a72f6165c
|
[
"BSD-2-Clause"
] | 8
|
2017-12-22T15:11:47.000Z
|
2022-03-15T22:54:04.000Z
|
/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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.
*
* 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
* FOUNDATION 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.
*/
#pragma once
#include "Result.hxx"
#include "io/FdType.hxx"
#include "util/Compiler.h"
#include <exception>
#include <sys/types.h>
/** data sink for an istream */
class IstreamHandler {
public:
/**
* Data is available and the callee shall invoke
* Istream::FillBucketList() and Istream::ConsumeBucketList().
*
* This is the successor to OnData() and OnDirect(). Once
* everything has been migrated to #IstreamBucketList, these
* methods can be removed.
*
* @return true if the caller shall invoke OnData() or OnDirect(),
* false if data has already been handled or if the #Istream has
* been closed
*/
virtual bool OnIstreamReady() noexcept {
return true;
}
/**
* Data is available as a buffer.
* This function must return 0 if it has closed the stream.
*
* @param data the buffer
* @param length the number of bytes available in the buffer, greater than 0
* @return the number of bytes consumed, 0 if writing would block
* (caller is responsible for registering an event) or if the
* stream has been closed
*/
virtual size_t OnData(const void *data, size_t length) noexcept = 0;
/**
* Data is available in a file descriptor.
* This function must return 0 if it has closed the stream.
*
* @param type what kind of file descriptor?
* @param fd the file descriptor
* @param max_length don't read more than this number of bytes
* @return the number of bytes consumed, or one of the
* #istream_result values
*/
virtual ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd,
gcc_unused size_t max_length) noexcept {
gcc_unreachable();
}
/**
* End of file encountered.
*/
virtual void OnEof() noexcept = 0;
/**
* The istream has ended unexpectedly, e.g. an I/O error.
*
* The method Istream::Close() will not result in a call to
* this callback, since the caller is assumed to be the
* istream handler.
*
* @param error an exception describing the error condition
*/
virtual void OnError(std::exception_ptr error) noexcept = 0;
};
| 32.885714
| 77
| 0.726615
|
CM4all
|
65c87d7b4a07e75b0d89fbd8d6e9c91e2fc6b6b7
| 1,405
|
cpp
|
C++
|
CloudDisk_Client/httpresponse.cpp
|
G-Club/c-cpp
|
e89f8efae357fc8349d0d66f1aef703a6a287bef
|
[
"Apache-2.0"
] | null | null | null |
CloudDisk_Client/httpresponse.cpp
|
G-Club/c-cpp
|
e89f8efae357fc8349d0d66f1aef703a6a287bef
|
[
"Apache-2.0"
] | 1
|
2017-02-07T00:49:21.000Z
|
2017-02-16T00:55:28.000Z
|
CloudDisk_Client/httpresponse.cpp
|
G-Club/c-cpp
|
e89f8efae357fc8349d0d66f1aef703a6a287bef
|
[
"Apache-2.0"
] | null | null | null |
#include "httpresponse.h"
HttpResponse::HttpResponse()
{
}
HttpResponse HttpResponse::FromByteArray(QByteArray &format)
{
/*
HTTP/1.1 200 OK\r\nServer: nginx/1.10.1\r\nDate: Sat, 29 Jul 2017 00:41:44 GMT\r\nContent-Type: text/html\r\nTransfer-Encoding: chunked\r\nConnection: keep-alive\r\n\r\n27\r\n{\"status\":201,\"error\":201,\"msg\":\"succ\"}\r\n0\r\n\r\n
*/
QString string(format),respline,data;
HttpResponse resp;
int index=-1,status;
index=string.indexOf("\r\n");
if(index<0)
{
return resp;
}
respline=string.left(index);
status=respline.split(' ').at(1).toInt();
index=string.indexOf("\r\n\r\n");
if(index<0)
{
return resp;
}
data=string.right(string.length()-index-4);
index=data.indexOf("\r\n");
data=data.right(data.length()-index-2);
index=data.indexOf("\r\n");
data=data.left(index);
resp.setData(data);
resp.setRespline(respline);
resp.setStatus(status);
return resp;
}
QString HttpResponse::getData() const
{
return data;
}
void HttpResponse::setData(const QString &value)
{
data = value;
}
QString HttpResponse::getRespline() const
{
return respline;
}
void HttpResponse::setRespline(const QString &value)
{
respline = value;
}
int HttpResponse::getStatus() const
{
return status;
}
void HttpResponse::setStatus(int value)
{
status = value;
}
| 19.513889
| 235
| 0.648399
|
G-Club
|
65c917836d9576fc136a7db14443d06dd5eb9319
| 478
|
cpp
|
C++
|
Backdoor.Win32.C.a/ifmirc.cpp
|
010001111/Vx-Suites
|
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
|
[
"MIT"
] | 2
|
2021-02-04T06:47:45.000Z
|
2021-07-28T10:02:10.000Z
|
Backdoor.Win32.C.a/ifmirc.cpp
|
010001111/Vx-Suites
|
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
|
[
"MIT"
] | null | null | null |
Backdoor.Win32.C.a/ifmirc.cpp
|
010001111/Vx-Suites
|
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
|
[
"MIT"
] | null | null | null |
#include "Include.h"
#include "Hell.h"
BOOL mirccmd(char *cmd)
{
HWND mwnd = FindWindow("mIRC",NULL);
if (mwnd) {
HANDLE hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE,0,PAGE_READWRITE,0,4096,"mIRC");
LPSTR mData = (LPSTR)MapViewOfFile(hFileMap,FILE_MAP_ALL_ACCESS,0,0,0);
sprintf(mData, cmd);
SendMessage(mwnd,WM_USER + 200,1,0);
SendMessage(mwnd,WM_USER + 201,1,0);
UnmapViewOfFile(mData);
CloseHandle(hFileMap);
return TRUE;
} else
return FALSE;
}
| 25.157895
| 91
| 0.717573
|
010001111
|
65ca00f755a60e996fd58344181d3d3ed0424b23
| 5,916
|
cpp
|
C++
|
meeting-qt/setup/src/dui/Core/Placeholder.cpp
|
GrowthEase/-
|
5cc7cab95fc309049de8023ff618219dff22d773
|
[
"MIT"
] | 48
|
2022-03-02T07:15:08.000Z
|
2022-03-31T08:37:33.000Z
|
meeting-qt/setup/src/dui/Core/Placeholder.cpp
|
chandarlee/Meeting
|
9350fdea97eb2cdda28b8bffd9c4199de15460d9
|
[
"MIT"
] | 1
|
2022-02-16T01:54:05.000Z
|
2022-02-16T01:54:05.000Z
|
meeting-qt/setup/src/dui/Core/Placeholder.cpp
|
chandarlee/Meeting
|
9350fdea97eb2cdda28b8bffd9c4199de15460d9
|
[
"MIT"
] | 9
|
2022-03-01T13:41:37.000Z
|
2022-03-10T06:05:23.000Z
|
/**
* @copyright Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
#include "StdAfx.h"
namespace ui
{
PlaceHolder::PlaceHolder()
{
}
PlaceHolder::~PlaceHolder()
{
}
std::wstring PlaceHolder::GetName() const
{
return m_sName;
}
std::string PlaceHolder::GetUTF8Name() const
{
int multiLength = WideCharToMultiByte(CP_UTF8, NULL, m_sName.c_str(), -1, NULL, 0, NULL, NULL);
if (multiLength <= 0)
return "";
std::unique_ptr<char[]> strName(new char[multiLength]);
WideCharToMultiByte(CP_UTF8, NULL, m_sName.c_str(), -1, strName.get(), multiLength, NULL, NULL);
std::string res = strName.get();
return res;
}
void PlaceHolder::SetName(const std::wstring& pstrName)
{
m_sName = pstrName;
}
void PlaceHolder::SetUTF8Name(const std::string& pstrName)
{
int wideLength = MultiByteToWideChar(CP_UTF8, NULL, pstrName.c_str(), -1, NULL, 0);
if (wideLength <= 0)
{
m_sName = _T("");
return;
}
std::unique_ptr<wchar_t[]> strName(new wchar_t[wideLength]);
MultiByteToWideChar(CP_UTF8, NULL, pstrName.c_str(), -1, strName.get(), wideLength);
m_sName = strName.get();
}
Window* PlaceHolder::GetWindow() const
{
return m_pWindow;
}
void PlaceHolder::SetWindow(Window* pManager, Box* pParent, bool bInit)
{
m_pWindow = pManager;
m_pParent = pParent;
if (bInit && m_pParent) Init();
}
void PlaceHolder::SetWindow(Window* pManager)
{
m_pWindow = pManager;
}
void PlaceHolder::Init()
{
DoInit();
}
void PlaceHolder::DoInit()
{
}
CSize PlaceHolder::EstimateSize(CSize szAvailable)
{
return m_cxyFixed;
}
bool PlaceHolder::IsVisible() const
{
return m_bVisible && m_bInternVisible;
}
bool PlaceHolder::IsFloat() const
{
return m_bFloat;
}
void PlaceHolder::SetFloat(bool bFloat)
{
if (m_bFloat == bFloat) return;
m_bFloat = bFloat;
ArrangeAncestor();
}
int PlaceHolder::GetFixedWidth() const
{
return m_cxyFixed.cx;
}
void PlaceHolder::SetFixedWidth(int cx, bool arrange)
{
if (cx < 0 && cx != DUI_LENGTH_STRETCH && cx != DUI_LENGTH_AUTO) {
ASSERT(FALSE);
return;
}
if (m_cxyFixed.cx != cx)
{
m_cxyFixed.cx = cx;
if (arrange) {
ArrangeAncestor();
}
else {
m_bReEstimateSize = true;
}
}
//if( !m_bFloat ) ArrangeAncestor();
//else Arrange();
}
int PlaceHolder::GetFixedHeight() const
{
return m_cxyFixed.cy;
}
void PlaceHolder::SetFixedHeight(int cy)
{
if (cy < 0 && cy != DUI_LENGTH_STRETCH && cy != DUI_LENGTH_AUTO) {
ASSERT(FALSE);
return;
}
if (m_cxyFixed.cy != cy)
{
m_cxyFixed.cy = cy;
ArrangeAncestor();
}
//if( !m_bFloat ) ArrangeAncestor();
//else Arrange();
}
int PlaceHolder::GetMinWidth() const
{
return m_cxyMin.cx;
}
void PlaceHolder::SetMinWidth(int cx)
{
if (m_cxyMin.cx == cx) return;
if (cx < 0) return;
m_cxyMin.cx = cx;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetMaxWidth() const
{
return m_cxyMax.cx;
}
void PlaceHolder::SetMaxWidth(int cx)
{
if (m_cxyMax.cx == cx) return;
m_cxyMax.cx = cx;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetMinHeight() const
{
return m_cxyMin.cy;
}
void PlaceHolder::SetMinHeight(int cy)
{
if (m_cxyMin.cy == cy) return;
if (cy < 0) return;
m_cxyMin.cy = cy;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetMaxHeight() const
{
return m_cxyMax.cy;
}
void PlaceHolder::SetMaxHeight(int cy)
{
if (m_cxyMax.cy == cy) return;
m_cxyMax.cy = cy;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetWidth() const
{
return m_rcItem.right - m_rcItem.left;
}
int PlaceHolder::GetHeight() const
{
return m_rcItem.bottom - m_rcItem.top;
}
UiRect PlaceHolder::GetPos(bool bContainShadow) const
{
return m_rcItem;
}
void PlaceHolder::SetPos(UiRect rc)
{
m_rcItem = rc;
}
void PlaceHolder::Arrange()
{
if (GetFixedWidth() == DUI_LENGTH_AUTO || GetFixedHeight() == DUI_LENGTH_AUTO)
{
ArrangeAncestor();
}
else
{
ArrangeSelf();
}
}
void PlaceHolder::ArrangeAncestor()
{
m_bReEstimateSize = true;
if (!m_pWindow || !m_pWindow->GetRoot())
{
if (GetParent()) {
GetParent()->ArrangeSelf();
}
else {
ArrangeSelf();
}
}
else
{
Control* parent = GetParent();
while (parent && (parent->GetFixedWidth() == DUI_LENGTH_AUTO || parent->GetFixedHeight() == DUI_LENGTH_AUTO))
{
parent->SetReEstimateSize(true);
parent = parent->GetParent();
}
if (parent)
{
parent->ArrangeSelf();
}
else //说明root具有AutoAdjustSize属性
{
m_pWindow->GetRoot()->ArrangeSelf();
}
}
}
void PlaceHolder::ArrangeSelf()
{
if (!IsVisible()) return;
m_bReEstimateSize = true;
m_bIsArranged = true;
Invalidate();
if (m_pWindow != NULL) m_pWindow->SetArrange(true);
}
void PlaceHolder::Invalidate() const
{
if (!IsVisible()) return;
UiRect invalidateRc = GetPosWithScrollOffset();
if (m_pWindow != NULL) m_pWindow->Invalidate(invalidateRc);
}
UiRect PlaceHolder::GetPosWithScrollOffset() const
{
UiRect pos = GetPos();
pos.Offset(-GetScrollOffset().x, -GetScrollOffset().y);
return pos;
}
CPoint PlaceHolder::GetScrollOffset() const
{
CPoint scrollPos;
Control* parent = GetParent();
ListBox* lbParent = dynamic_cast<ListBox*>(parent);
if (lbParent && lbParent->IsVScrollBarValid() && IsFloat()) {
return scrollPos;
}
while (parent && (!dynamic_cast<ListBox*>(parent) || !dynamic_cast<ListBox*>(parent)->IsVScrollBarValid()))
{
parent = parent->GetParent();
}
if (parent) { //说明控件在Listbox内部
ListBox* listbox = (ListBox*)parent;
scrollPos.x = listbox->GetScrollPos().cx;
scrollPos.y = listbox->GetScrollPos().cy;
}
return scrollPos;
}
bool PlaceHolder::IsArranged() const
{
return m_bIsArranged;
}
bool IsChild(PlaceHolder* pAncestor, PlaceHolder* pControl)
{
while (pControl && pControl != pAncestor)
{
pControl = pControl->GetParent();
}
return pControl != nullptr;
}
}
| 17.298246
| 111
| 0.686782
|
GrowthEase
|
65cac9339ad22493786ffac70178bd54c71a106a
| 5,177
|
cpp
|
C++
|
test/test_symbol_normalizer.cpp
|
atlimited/resembla
|
82293cecfccfca6e2a95688b21f0659ba75e8cae
|
[
"Apache-2.0"
] | 65
|
2017-07-24T12:59:05.000Z
|
2021-09-29T03:08:57.000Z
|
test/test_symbol_normalizer.cpp
|
atlimited/resembla
|
82293cecfccfca6e2a95688b21f0659ba75e8cae
|
[
"Apache-2.0"
] | 3
|
2017-07-26T03:25:28.000Z
|
2019-01-26T15:08:53.000Z
|
test/test_symbol_normalizer.cpp
|
tuem/resembla
|
ff39ac1b6904fc018bb691d77ca468772600f731
|
[
"Apache-2.0"
] | 6
|
2017-09-25T10:39:17.000Z
|
2019-12-24T09:45:24.000Z
|
/*
Resembla
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <string>
#include <iostream>
#include "Catch/catch.hpp"
#include "string_util.hpp"
#include "symbol_normalizer.hpp"
using namespace resembla;
void test_symbol_normalizer_noramlize_symbol(const std::wstring& input, const std::wstring& correct, bool to_lower = false)
{
init_locale();
SymbolNormalizer normalize("../misc/icu/normalization/", "resembla", "nfkc", to_lower);
auto answer = normalize(input);
#ifdef DEBUG
std::wcerr << "input : \"" << input << L"\"" << std::endl;
std::wcerr << "answer : \"" << answer << L"\"" << std::endl;
std::wcerr << "correct: \"" << correct << L"\"" << std::endl;
std::cerr << "dump input : ";
for(auto c: input){
std::cerr << std::hex << (int)c << " ";
}
std::cerr << std::endl;
std::cerr << "dump answer : ";
for(auto c: answer){
std::cerr << std::hex << (int)c << " ";
}
std::cerr << std::endl;
std::cerr << "dump correct: ";
for(auto c: correct){
std::cerr << std::hex << (int)c << " ";
}
std::cerr << std::endl;
#endif
CHECK(answer == correct);
}
TEST_CASE( "empty symbol normalizer", "[language]" ) {
std::string input = "HeLLo、@$%!!?!!";
SymbolNormalizer normalize_nothing("", "", "", false);
CHECK(normalize_nothing(input) == "HeLLo、@$%!!?!!");
SymbolNormalizer normalize_case("", "", "", true);
CHECK(normalize_case(input) == "hello、@$%!!?!!");
}
TEST_CASE( "normalize symbols", "[language]" ) {
test_symbol_normalizer_noramlize_symbol(L"", L"");
test_symbol_normalizer_noramlize_symbol(L"テスト", L"テスト");
test_symbol_normalizer_noramlize_symbol(L"アカサタナ", L"アカサタナ");
test_symbol_normalizer_noramlize_symbol(L"TEST", L"TEST");
test_symbol_normalizer_noramlize_symbol(L"test", L"test");
test_symbol_normalizer_noramlize_symbol(L"ABCDE", L"ABCDE");
test_symbol_normalizer_noramlize_symbol(L"アボカド", L"アボカド");
test_symbol_normalizer_noramlize_symbol(L"パペット", L"パペット");
// double quote
test_symbol_normalizer_noramlize_symbol(L"\u0022\u201c\u201d", L"\u0022\u0022\u0022");
// single quote
test_symbol_normalizer_noramlize_symbol(L"\u0027\u2018\u2019", L"\u0027\u0027\u0027");
// space
test_symbol_normalizer_noramlize_symbol(L"\u0020\u200A\uFEFF\u000D\u000A", L"\u0020\u0020\u0020\u0020\u0020");
// hyphen
test_symbol_normalizer_noramlize_symbol(L"\u002D\u00AD\u02D7\u058A\u2010\u2011\u2012\u2013\u2043\u207B\u208B\u2212", L"\u002D\u002D\u002D\u002D\u002D\u002D\u002D\u002D\u002D\u002D\u002D\u002D");
// macron
test_symbol_normalizer_noramlize_symbol(L"\u30FC\u2014\u2015\u2500\u2501\uFE63\uFF0D\uFF70", L"\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC");
// tilde
test_symbol_normalizer_noramlize_symbol(L"\u007E\u301C\uFF5E\u02DC\u1FC0\u2053\u223C\u223F\u3030", L"\u007E\u007E\u007E\u007E\u007E\u007E\u007E\u007E\u007E");
// yen sign
test_symbol_normalizer_noramlize_symbol(L"\u00A5\u005C\uFFE5", L"\u00A5\u00A5\u00A5");
test_symbol_normalizer_noramlize_symbol(L"0123456789", L"0123456789");
test_symbol_normalizer_noramlize_symbol(L"0123456789", L"0123456789");
test_symbol_normalizer_noramlize_symbol(L"ABCDEFGHIJKLMNOPQRSTUVWXYZ", L"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
test_symbol_normalizer_noramlize_symbol(L"ABCDEFGHIJKLMNOPQRSTUVWXYZ", L"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
test_symbol_normalizer_noramlize_symbol(L"abcdefghijklmnopqrstuvwxyz", L"abcdefghijklmnopqrstuvwxyz");
test_symbol_normalizer_noramlize_symbol(L"abcdefghijklmnopqrstuvwxyz", L"abcdefghijklmnopqrstuvwxyz");
test_symbol_normalizer_noramlize_symbol(L"!\"#$%&'()*+,-./:;<>?@[\\]^_`{|}", L"!\"#$%&'()*+,-./:;<>?@[¥]^_`{|}");
test_symbol_normalizer_noramlize_symbol(L"!“”#$%&‘’()*+,−./:;<>?@[¥¥]^_`{|}", L"!\"\"#$%&''()*+,-./:;<>?@[¥¥]^_`{|}");
test_symbol_normalizer_noramlize_symbol(L"=。、・「」", L"=。、・「」");
test_symbol_normalizer_noramlize_symbol(L"=。、・「」", L"=。、・「」");
test_symbol_normalizer_noramlize_symbol(L"テスト!", L"テスト!");
test_symbol_normalizer_noramlize_symbol(L"テスト!", L"テスト!");
test_symbol_normalizer_noramlize_symbol(L"テスト?", L"テスト?");
test_symbol_normalizer_noramlize_symbol(L"テスト?", L"テスト?");
test_symbol_normalizer_noramlize_symbol(L"テストです.", L"テストです.");
test_symbol_normalizer_noramlize_symbol(L"こんにちは。テストです", L"こんにちは。テストです");
test_symbol_normalizer_noramlize_symbol(L"Hello, this is a test.", L"Hello, this is a test.");
test_symbol_normalizer_noramlize_symbol(L"Apple, APPLE, apple and APPLE", L"apple, apple, apple and apple", true);
}
| 42.089431
| 198
| 0.696156
|
atlimited
|
65cca26ab81c68c2201bde3223830ec49d11faa7
| 7,042
|
cc
|
C++
|
google/cloud/storage/status_or_test.cc
|
roopak-qlogic/google-cloud-cpp
|
ed129e4c955e99d4dacb822503d95e374605c438
|
[
"Apache-2.0"
] | null | null | null |
google/cloud/storage/status_or_test.cc
|
roopak-qlogic/google-cloud-cpp
|
ed129e4c955e99d4dacb822503d95e374605c438
|
[
"Apache-2.0"
] | null | null | null |
google/cloud/storage/status_or_test.cc
|
roopak-qlogic/google-cloud-cpp
|
ed129e4c955e99d4dacb822503d95e374605c438
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/status_or.h"
#include "google/cloud/testing_util/expect_exception.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace {
using ::testing::HasSubstr;
TEST(StatusOrTest, DefaultConstructor) {
StatusOr<int> actual;
EXPECT_FALSE(actual.ok());
EXPECT_FALSE(actual.status().ok());
EXPECT_TRUE(not actual);
}
TEST(StatusOrTest, StatusConstructorNormal) {
StatusOr<int> actual(Status(404, "NOT FOUND", "It was there yesterday!"));
EXPECT_FALSE(actual.ok());
EXPECT_TRUE(not actual);
EXPECT_EQ(404, actual.status().status_code());
EXPECT_EQ("NOT FOUND", actual.status().error_message());
EXPECT_EQ("It was there yesterday!", actual.status().error_details());
}
TEST(StatusOrTest, StatusConstructorInvalid) {
testing_util::ExpectException<std::invalid_argument>(
[&] { StatusOr<int> actual(Status{}); },
[&](std::invalid_argument const& ex) {
EXPECT_THAT(ex.what(), HasSubstr("StatusOr"));
},
"exceptions are disabled: "
);
}
TEST(StatusOrTest, ValueConstructor) {
StatusOr<int> actual(42);
EXPECT_TRUE(actual.ok());
EXPECT_FALSE(not actual);
EXPECT_EQ(42, actual.value());
EXPECT_EQ(42, std::move(actual).value());
}
TEST(StatusOrTest, ValueConstAccessors) {
StatusOr<int> const actual(42);
EXPECT_TRUE(actual.ok());
EXPECT_EQ(42, actual.value());
EXPECT_EQ(42, std::move(actual).value());
}
TEST(StatusOrTest, ValueAccessorNonConstThrows) {
StatusOr<int> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrTest, ValueAccessorConstThrows) {
StatusOr<int> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrTest, StatusConstAccessors) {
StatusOr<int> const actual(Status(500, "BAD"));
EXPECT_EQ(500, actual.status().status_code());
EXPECT_EQ(500, std::move(actual).status().status_code());
}
TEST(StatusOrTest, ValueDeference) {
StatusOr<std::string> actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ("42", *actual);
EXPECT_EQ("42", std::move(actual).value());
}
TEST(StatusOrTest, ValueConstDeference) {
StatusOr<std::string> const actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ("42", *actual);
EXPECT_EQ("42", std::move(actual).value());
}
TEST(StatusOrTest, ValueArrow) {
StatusOr<std::string> actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ(std::string("42"), actual->c_str());
}
TEST(StatusOrTest, ValueConstArrow) {
StatusOr<std::string> const actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ(std::string("42"), actual->c_str());
}
TEST(StatusOrVoidTest, DefaultConstructor) {
StatusOr<void> actual;
EXPECT_FALSE(actual.ok());
EXPECT_FALSE(actual.status().ok());
}
TEST(StatusOrVoidTest, StatusConstructorNormal) {
StatusOr<void> actual(Status(404, "NOT FOUND", "It was there yesterday!"));
EXPECT_FALSE(actual.ok());
EXPECT_EQ(404, actual.status().status_code());
EXPECT_EQ("NOT FOUND", actual.status().error_message());
EXPECT_EQ("It was there yesterday!", actual.status().error_details());
}
TEST(StatusOrVoidTest, ValueConstructor) {
StatusOr<void> actual(Status{});
EXPECT_TRUE(actual.ok());
testing_util::ExpectNoException([&] { actual.value(); });
testing_util::ExpectNoException([&] { std::move(actual).value(); });
}
TEST(StatusOrVoidTest, ValueConstAccessors) {
StatusOr<void> const actual(Status{});
EXPECT_TRUE(actual.ok());
testing_util::ExpectNoException([&] { actual.value(); });
testing_util::ExpectNoException([&] { std::move(actual).value(); });
}
TEST(StatusOrVoidTest, ValueAccessorNonConstThrows) {
StatusOr<void> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrVoidTest, ValueAccessorConstThrows) {
StatusOr<void> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrVoidTest, StatusConstAccessors) {
StatusOr<void> const actual(Status(500, "BAD"));
EXPECT_EQ(500, actual.status().status_code());
EXPECT_EQ(500, std::move(actual).status().status_code());
}
} // namespace
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
| 31.159292
| 77
| 0.668986
|
roopak-qlogic
|
65d1b0b9ce08319e680aae4a187667943a9a6bd4
| 811
|
hpp
|
C++
|
src/morda/widgets/label/MouseCursor.hpp
|
Mactor2018/morda
|
7194f973783b4472b8671fbb52e8c96e8c972b90
|
[
"MIT"
] | 1
|
2018-10-27T05:07:05.000Z
|
2018-10-27T05:07:05.000Z
|
src/morda/widgets/label/MouseCursor.hpp
|
Mactor2018/morda
|
7194f973783b4472b8671fbb52e8c96e8c972b90
|
[
"MIT"
] | null | null | null |
src/morda/widgets/label/MouseCursor.hpp
|
Mactor2018/morda
|
7194f973783b4472b8671fbb52e8c96e8c972b90
|
[
"MIT"
] | null | null | null |
#pragma once
#include "../Widget.hpp"
#include "../../res/ResCursor.hpp"
namespace morda{
/**
* @brief Mouse cursor widget.
* This widget displays mouse cursor.
* From GUI script this widget can be instantiated as "MouseCursor".
*
* @param cursor - reference to cursor resource.
*/
class MouseCursor : virtual public Widget{
std::shared_ptr<const ResCursor> cursor;
std::shared_ptr<const ResImage::QuadTexture> quadTex;
Vec2r cursorPos;
public:
MouseCursor(const stob::Node* chain = nullptr);
MouseCursor(const MouseCursor&) = delete;
MouseCursor& operator=(const MouseCursor&) = delete;
void setCursor(std::shared_ptr<const ResCursor> cursor);
bool onMouseMove(const morda::Vec2r& pos, unsigned pointerID) override;
void render(const morda::Matr4r& matrix) const override;
};
}
| 21.918919
| 72
| 0.731196
|
Mactor2018
|
65e402da66d18090a23b95180787d18a0806e7a0
| 1,619
|
hpp
|
C++
|
CPP_Module_06/ex01/Serialize.hpp
|
Victor-Akio/CPP-42
|
e6d64e4820ad31ae2cb353a4020d2acb8b5280eb
|
[
"MIT"
] | null | null | null |
CPP_Module_06/ex01/Serialize.hpp
|
Victor-Akio/CPP-42
|
e6d64e4820ad31ae2cb353a4020d2acb8b5280eb
|
[
"MIT"
] | null | null | null |
CPP_Module_06/ex01/Serialize.hpp
|
Victor-Akio/CPP-42
|
e6d64e4820ad31ae2cb353a4020d2acb8b5280eb
|
[
"MIT"
] | null | null | null |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Serialize.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vminomiy <vminomiy@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/03/25 00:00:06 by vminomiy #+# #+# */
/* Updated: 2022/03/26 16:15:18 by vminomiy ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SERIALIZE_HPP
# define SERIALIZE_HPP
# include <iostream>
# include <stdint.h>
/* SERIALIZATION
** https://en.cppreference.com/w/cpp/language/reinterpret_cast
** https://www.tutorialspoint.com/cplusplus/cpp_casting_operators.htm
** UINTPTR_T - https://stackoverflow.com/questions/1845482/what-is-uintptr-t-data-type
** Usei a stdint.h no lugar da cstdint, pois a uintptr_t foi implementada originalmente na c++99(stdint.h)
** a cstdint corresponde à c++11 que entra na categoriad e forbidden.
** A estrutura pode ter qualquer coisa dentro.. no caso só para popular com algo, coloquei um "num"
*/
typedef struct s_data {
int num;
} Data;
uintptr_t serialize(Data* ptr);
Data* deserialize(uintptr_t raw);
#endif
| 46.257143
| 106
| 0.408894
|
Victor-Akio
|
65eb378757f196f1b0242237bbf7b0aab25022d1
| 1,112
|
cpp
|
C++
|
tugasMonteCarlo/tugasMonteCarlo-20912008-20912009/montePi.cpp
|
ridlo/kuliah_sains_komputasi
|
83cd50857db2446bb41b78698a47a060e0eca5d8
|
[
"MIT"
] | null | null | null |
tugasMonteCarlo/tugasMonteCarlo-20912008-20912009/montePi.cpp
|
ridlo/kuliah_sains_komputasi
|
83cd50857db2446bb41b78698a47a060e0eca5d8
|
[
"MIT"
] | null | null | null |
tugasMonteCarlo/tugasMonteCarlo-20912008-20912009/montePi.cpp
|
ridlo/kuliah_sains_komputasi
|
83cd50857db2446bb41b78698a47a060e0eca5d8
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <stdlib.h>
#include <time.h>
using namespace std;
double unirand()
{
return (double) rand()/ (double) RAND_MAX;
}
int main()
{
double pi, x, y, r;
unsigned int N=0, Ntot;
ofstream outfile;
outfile.open("rnd-pi.txt");
Ntot = 100000;
srand(time(NULL));
for (int i=0; i<Ntot; i++){
x = unirand();
y = unirand();
outfile << x << " " << y << "\n";
r = x*x + y*y;
if ( r <= 1. ) {
N++;}
}
outfile.close();
pi = (double)N/(double)Ntot * 4.;
printf("Hasil dari %d percobaan menghasilkan nilai PI = %f \n", Ntot, pi);
ofstream ploter;
ploter.open("pi-plot.in");
ploter << "# gnuplot command for plotting\n";
ploter << "set terminal wxt size 600, 500\n";
ploter << "set xrange [0:1]\n";
ploter << "set xlabel \"x\"\n";
ploter << "set ylabel \"y\"\n";
ploter << "plot \"rnd-pi.txt\" with dots, sqrt(1.-x*x)\n";
ploter.close();
system("gnuplot -persist < pi-plot.in");
return 0;
}
| 22.24
| 78
| 0.522482
|
ridlo
|
65ec377cfee6e4d0b9d9cdac2342a92ccfa6aa3b
| 14,844
|
hpp
|
C++
|
pennylane_lightning_gpu/src/util/cuda_helpers.hpp
|
PennyLaneAI/pennylane-lightning-gpu
|
1b2a361f68c8580457e61cc706d644c4cbfe04ad
|
[
"Apache-2.0"
] | 9
|
2022-03-14T15:18:08.000Z
|
2022-03-30T03:05:36.000Z
|
pennylane_lightning_gpu/src/util/cuda_helpers.hpp
|
PennyLaneAI/pennylane-lightning-gpu
|
1b2a361f68c8580457e61cc706d644c4cbfe04ad
|
[
"Apache-2.0"
] | 6
|
2022-03-18T13:44:10.000Z
|
2022-03-31T22:07:25.000Z
|
pennylane_lightning_gpu/src/util/cuda_helpers.hpp
|
PennyLaneAI/pennylane-lightning-gpu
|
1b2a361f68c8580457e61cc706d644c4cbfe04ad
|
[
"Apache-2.0"
] | null | null | null |
// Adapted from JET: https://github.com/XanaduAI/jet.git
// and from Lightning: https://github.com/PennylaneAI/pennylane-lightning.git
#pragma once
#include <algorithm>
#include <numeric>
#include <type_traits>
#include <vector>
#include <cuComplex.h>
#include <cublas_v2.h>
#include <cuda.h>
#include <custatevec.h>
#include "Error.hpp"
#include "Util.hpp"
namespace Pennylane::CUDA::Util {
#ifndef CUDA_UNSAFE
/**
* @brief Macro that throws Exception from CUDA failure error codes.
*
* @param err CUDA function error-code.
*/
#define PL_CUDA_IS_SUCCESS(err) \
PL_ABORT_IF_NOT(err == cudaSuccess, cudaGetErrorString(err))
/**
* @brief Macro that throws Exception from cuQuantum failure error codes.
*
* @param err cuQuantum function error-code.
*/
#define PL_CUSTATEVEC_IS_SUCCESS(err) \
PL_ABORT_IF_NOT(err == CUSTATEVEC_STATUS_SUCCESS, \
GetCuStateVecErrorString(err).c_str())
#else
#define PL_CUDA_IS_SUCCESS(err) \
{ static_cast<void>(err); }
#define PL_CUSTATEVEC_IS_SUCCESS(err) \
{ static_cast<void>(err); }
#endif
static const std::string
GetCuStateVecErrorString(const custatevecStatus_t &err) {
std::string result;
switch (err) {
case CUSTATEVEC_STATUS_SUCCESS:
result = "No errors";
break;
case CUSTATEVEC_STATUS_NOT_INITIALIZED:
result = "custatevec not initialized";
break;
case CUSTATEVEC_STATUS_ALLOC_FAILED:
result = "custatevec memory allocation failed";
break;
case CUSTATEVEC_STATUS_INVALID_VALUE:
result = "Invalid value";
break;
case CUSTATEVEC_STATUS_ARCH_MISMATCH:
result = "CUDA device architecture mismatch";
break;
case CUSTATEVEC_STATUS_EXECUTION_FAILED:
result = "custatevec execution failed";
break;
case CUSTATEVEC_STATUS_INTERNAL_ERROR:
result = "Internal custatevec error";
break;
case CUSTATEVEC_STATUS_NOT_SUPPORTED:
result = "Unsupported operation/device";
break;
case CUSTATEVEC_STATUS_INSUFFICIENT_WORKSPACE:
result = "Insufficient memory for gate-application workspace";
break;
case CUSTATEVEC_STATUS_SAMPLER_NOT_PREPROCESSED:
result = "Sampler not preprocessed";
break;
default:
result = "Status not found";
}
return result;
}
// SFINAE check for existence of real() method in complex type
template <typename CFP_t>
constexpr auto is_cxx_complex(const CFP_t &t) -> decltype(t.real(), bool()) {
return true;
}
// Catch-all fallback for CUDA complex types
constexpr bool is_cxx_complex(...) { return false; }
inline cuFloatComplex operator-(const cuFloatComplex &a) {
return {-a.x, -a.y};
}
inline cuDoubleComplex operator-(const cuDoubleComplex &a) {
return {-a.x, -a.y};
}
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static auto Div(const CFP_t_T &a, const CFP_t_U &b) -> CFP_t_T {
if constexpr (std::is_same_v<CFP_t_T, cuComplex> ||
std::is_same_v<CFP_t_T, float2>) {
return cuCdivf(a, b);
} else if (std::is_same_v<CFP_t_T, cuDoubleComplex> ||
std::is_same_v<CFP_t_T, double2>) {
return cuCdiv(a, b);
}
}
/**
* @brief Conjugate function for CXX & CUDA complex types
*
* @tparam CFP_t Complex data type. Supports std::complex<float>,
* std::complex<double>, cuFloatComplex, cuDoubleComplex
* @param a The given complex number
* @return CFP_t The conjuagted complex number
*/
template <class CFP_t> inline static constexpr auto Conj(CFP_t a) -> CFP_t {
if constexpr (std::is_same_v<CFP_t, cuComplex> ||
std::is_same_v<CFP_t, float2>) {
return cuConjf(a);
} else {
return cuConj(a);
}
}
/**
* @brief Compile-time scalar real times complex number.
*
* @tparam U Precision of real value `a`.
* @tparam T Precision of complex value `b` and result.
* @param a Real scalar value.
* @param b Complex scalar value.
* @return constexpr std::complex<T>
*/
template <class Real_t, class CFP_t = cuDoubleComplex>
inline static constexpr auto ConstMultSC(Real_t a, CFP_t b) -> CFP_t {
if constexpr (std::is_same_v<CFP_t, cuDoubleComplex>) {
return make_cuDoubleComplex(a * b.x, a * b.y);
} else {
return make_cuFloatComplex(a * b.x, a * b.y);
}
}
/**
* @brief Utility to convert cuComplex types to std::complex types
*
* @tparam CFP_t cuFloatComplex or cuDoubleComplex types.
* @param a CUDA compatible complex type.
* @return std::complex converted a
*/
template <class CFP_t = cuDoubleComplex>
inline static constexpr auto cuToComplex(CFP_t a)
-> std::complex<decltype(a.x)> {
return std::complex<decltype(a.x)>{a.x, a.y};
}
/**
* @brief Utility to convert std::complex types to cuComplex types
*
* @tparam CFP_t std::complex types.
* @param a A std::complex type.
* @return cuComplex converted a
*/
template <class CFP_t = std::complex<double>>
inline static constexpr auto complexToCu(CFP_t a) {
if constexpr (std::is_same_v<CFP_t, std::complex<double>>) {
return make_cuDoubleComplex(a.real(), a.imag());
} else {
return make_cuFloatComplex(a.real(), a.imag());
}
}
/**
* @brief Compile-time scalar complex times complex.
*
* @tparam U Precision of complex value `a`.
* @tparam T Precision of complex value `b` and result.
* @param a Complex scalar value.
* @param b Complex scalar value.
* @return constexpr std::complex<T>
*/
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static constexpr auto ConstMult(CFP_t_T a, CFP_t_U b) -> CFP_t_T {
if constexpr (is_cxx_complex(b)) {
return {a.real() * b.real() - a.imag() * b.imag(),
a.real() * b.imag() + a.imag() * b.real()};
} else {
return {a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x};
}
}
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static constexpr auto ConstMultConj(CFP_t_T a, CFP_t_U b) -> CFP_t_T {
return ConstMult(Conj(a), b);
}
/**
* @brief Compile-time scalar complex summation.
*
* @tparam T Precision of complex value `a` and result.
* @tparam U Precision of complex value `b`.
* @param a Complex scalar value.
* @param b Complex scalar value.
* @return constexpr std::complex<T>
*/
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static constexpr auto ConstSum(CFP_t_T a, CFP_t_U b) -> CFP_t_T {
if constexpr (std::is_same_v<CFP_t_T, cuComplex> ||
std::is_same_v<CFP_t_T, float2>) {
return cuCaddf(a, b);
} else {
return cuCadd(a, b);
}
}
/**
* @brief Return complex value 1+0i in the given precision.
*
* @tparam T Floating point precision type. Accepts `double` and `float`.
* @return constexpr std::complex<T>{1,0}
*/
template <class CFP_t> inline static constexpr auto ONE() -> CFP_t {
return {1, 0};
}
/**
* @brief Return complex value 0+0i in the given precision.
*
* @tparam T Floating point precision type. Accepts `double` and `float`.
* @return constexpr std::complex<T>{0,0}
*/
template <class CFP_t> inline static constexpr auto ZERO() -> CFP_t {
return {0, 0};
}
/**
* @brief Return complex value 0+1i in the given precision.
*
* @tparam T Floating point precision type. Accepts `double` and `float`.
* @return constexpr std::complex<T>{0,1}
*/
template <class CFP_t> inline static constexpr auto IMAG() -> CFP_t {
return {0, 1};
}
/**
* @brief Returns sqrt(2) as a compile-time constant.
*
* @tparam T Precision of result. `double`, `float` are accepted values.
* @return constexpr T sqrt(2)
*/
template <class CFP_t> inline static constexpr auto SQRT2() {
if constexpr (std::is_same_v<CFP_t, float2> ||
std::is_same_v<CFP_t, cuFloatComplex>) {
return CFP_t{0x1.6a09e6p+0F, 0}; // NOLINT: To be replaced in C++20
} else if constexpr (std::is_same_v<CFP_t, double2> ||
std::is_same_v<CFP_t, cuDoubleComplex>) {
return CFP_t{0x1.6a09e667f3bcdp+0,
0}; // NOLINT: To be replaced in C++20
} else if constexpr (std::is_same_v<CFP_t, double>) {
return 0x1.6a09e667f3bcdp+0; // NOLINT: To be replaced in C++20
} else {
return 0x1.6a09e6p+0F; // NOLINT: To be replaced in C++20
}
}
/**
* @brief Returns inverse sqrt(2) as a compile-time constant.
*
* @tparam T Precision of result. `double`, `float` are accepted values.
* @return constexpr T 1/sqrt(2)
*/
template <class CFP_t> inline static constexpr auto INVSQRT2() -> CFP_t {
if constexpr (std::is_same_v<CFP_t, std::complex<float>> ||
std::is_same_v<CFP_t, std::complex<double>>) {
return CFP_t(1 / M_SQRT2, 0);
} else {
return Div(CFP_t{1, 0}, SQRT2<CFP_t>());
}
}
/**
* @brief cuBLAS backed inner product for GPU data.
*
* @tparam T Complex data-type. Accepts cuFloatComplex and cuDoubleComplex/
* @param v1 Device data pointer 1
* @param v2 Device data pointer 2
* @param data_size Lengtyh of device data.
* @return T Inner-product result
*/
template <class T = cuFloatComplex>
inline auto innerProdC_CUDA(const T *v1, const T *v2, const int data_size,
const cudaStream_t &streamId) -> T {
T result{0.0, 0.0}; // Host result
cublasHandle_t handle;
cublasCreate(&handle);
cublasSetStream(handle, streamId);
if constexpr (std::is_same_v<T, cuFloatComplex>) {
cublasCdotc(handle, data_size, v1, 1, v2, 1, &result);
} else if constexpr (std::is_same_v<T, cuDoubleComplex>) {
cublasZdotc(handle, data_size, v1, 1, v2, 1, &result);
}
cublasDestroy(handle);
return result;
}
/**
* If T is a supported data type for gates, this expression will
* evaluate to `true`. Otherwise, it will evaluate to `false`.
*
* Supported data types are `float2`, `double2`, and their aliases.
*
* @tparam T candidate data type
*/
template <class T>
constexpr bool is_supported_data_type =
std::is_same_v<T, cuComplex> || std::is_same_v<T, float2> ||
std::is_same_v<T, cuDoubleComplex> || std::is_same_v<T, double2>;
/**
* @brief Simple overloaded method to define CUDA data type.
*
* @param t
* @return cuDoubleComplex
*/
inline cuDoubleComplex getCudaType(const double &t) {
static_cast<void>(t);
return {};
}
/**
* @brief Simple overloaded method to define CUDA data type.
*
* @param t
* @return cuFloatComplex
*/
inline cuFloatComplex getCudaType(const float &t) {
static_cast<void>(t);
return {};
}
/**
* @brief Return the number of supported CUDA capable GPU devices.
*
* @return std::size_t
*/
inline int getGPUCount() {
int result;
PL_CUDA_IS_SUCCESS(cudaGetDeviceCount(&result));
return result;
}
/**
* @brief Return the current GPU device.
*
* @return int
*/
inline int getGPUIdx() {
int result;
PL_CUDA_IS_SUCCESS(cudaGetDevice(&result));
return result;
}
inline static void deviceReset() { PL_CUDA_IS_SUCCESS(cudaDeviceReset()); }
/**
* @brief Checks to see if the given GPU supports the PennyLane-Lightning-GPU
* device. Minimum supported architecture is SM 7.0.
*
* @param device_number GPU device index
* @return bool
*/
static bool isCuQuantumSupported(int device_number = 0) {
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, device_number);
return deviceProp.major >= 7;
}
/**
* @brief Get current GPU major.minor support
*
* @param device_number
* @return std::pair<int,int>
*/
static std::pair<int, int> getGPUArch(int device_number = 0) {
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, device_number);
return std::make_pair(deviceProp.major, deviceProp.minor);
}
/** Chunk the data with the requested chunk size */
template <template <typename...> class Container, typename T>
auto chunkDataSize(const Container<T> &data, std::size_t chunk_size)
-> Container<Container<T>> {
Container<Container<T>> output;
for (std::size_t chunk = 0; chunk < data.size(); chunk += chunk_size) {
const auto chunk_end = std::min(data.size(), chunk + chunk_size);
output.emplace_back(data.begin() + chunk, data.begin() + chunk_end);
}
return output;
}
/** Chunk the data into the requested number of chunks */
template <template <typename...> class Container, typename T>
auto chunkData(const Container<T> &data, std::size_t num_chunks)
-> Container<Container<T>> {
const auto rem = data.size() % num_chunks;
const std::size_t div = static_cast<std::size_t>(data.size() / num_chunks);
if (!div) { // Match chunks to available work
return chunkDataSize(data, 1);
}
if (rem) { // We have an uneven split; ensure fair distribution
auto output =
chunkDataSize(Container<T>{data.begin(), data.end() - rem}, div);
auto output_rem =
chunkDataSize(Container<T>{data.end() - rem, data.end()}, div);
for (std::size_t idx = 0; idx < output_rem.size(); idx++) {
output[idx].insert(output[idx].end(), output_rem[idx].begin(),
output_rem[idx].end());
}
return output;
}
return chunkDataSize(data, div);
}
/** @brief `%CudaScopedDevice` uses RAII to select a CUDA device context.
*
* @see https://taskflow.github.io/taskflow/classtf_1_1cudaScopedDevice.html
*
* @note A `%CudaScopedDevice` instance cannot be moved or copied.
*
* @warning This class is not thread-safe.
*/
class CudaScopedDevice {
public:
/**
* @brief Constructs a `%CudaScopedDevice` using a CUDA device.
*
* @param device CUDA device to scope in the guard.
*/
CudaScopedDevice(int device) {
PL_CUDA_IS_SUCCESS(cudaGetDevice(&prev_device_));
if (prev_device_ == device) {
prev_device_ = -1;
} else {
PL_CUDA_IS_SUCCESS(cudaSetDevice(device));
}
}
/**
* @brief Destructs a `%CudaScopedDevice`, switching back to the previous
* CUDA device context.
*/
~CudaScopedDevice() {
if (prev_device_ != -1) {
// Throwing exceptions from a destructor can be dangerous.
// See https://isocpp.org/wiki/faq/exceptions#ctor-exceptions.
cudaSetDevice(prev_device_);
}
}
CudaScopedDevice() = delete;
CudaScopedDevice(const CudaScopedDevice &) = delete;
CudaScopedDevice(CudaScopedDevice &&) = delete;
private:
/// The previous CUDA device (or -1 if the device passed to the constructor
/// is the current CUDA device).
int prev_device_;
};
} // namespace Pennylane::CUDA::Util
| 31.119497
| 80
| 0.651846
|
PennyLaneAI
|
65ed7938ab2812c404caebb3d26a88d4f07e2ff5
| 1,858
|
cpp
|
C++
|
examples/CherryPicker/general_example.cpp
|
allison-group/indigox
|
22657cb3ceb888049cc231e73d18fb2eac099604
|
[
"MIT"
] | 7
|
2019-11-24T15:51:37.000Z
|
2021-10-02T05:18:42.000Z
|
examples/CherryPicker/general_example.cpp
|
allison-group/indigox
|
22657cb3ceb888049cc231e73d18fb2eac099604
|
[
"MIT"
] | 2
|
2018-12-17T00:55:32.000Z
|
2019-10-11T01:47:04.000Z
|
examples/CherryPicker/general_example.cpp
|
allison-group/indigox
|
22657cb3ceb888049cc231e73d18fb2eac099604
|
[
"MIT"
] | 2
|
2019-10-21T01:26:56.000Z
|
2019-12-02T00:00:42.000Z
|
//
// C++ example that imports a molecule from an outputted binary (which you can produce from python with indigox.SaveMolecule)
// This example has CalculateElectrons on, so it will calculate formal charges and bond orders.
// Relies on the Python example having been run first so there is an Athenaeum to match the molecule to.
// Also assumes you are running from a build folder in the project root. If not, change example_folder_path below
//
#include <indigox/indigox.hpp>
#include <indigox/classes/athenaeum.hpp>
#include <indigox/classes/forcefield.hpp>
#include <indigox/classes/parameterised.hpp>
#include <indigox/algorithm/cherrypicker.hpp>
#include <experimental/filesystem>
int main() {
using namespace indigox;
namespace fs = std::experimental::filesystem;
using settings = indigox::algorithm::CherryPicker::Settings;
std::string example_folder_path = "../examples/CherryPicker/";
auto forceField = GenerateGROMOS54A7();
auto man_ath = LoadAthenaeum(example_folder_path + "ManualAthenaeum.ath");
// auto auto_ath = LoadAthenaeum(example_folder_path + "AutomaticAthenaeum.ath");
Molecule mol = LoadMolecule(example_folder_path + "TestMolecules/axinellinA.bin");
algorithm::CherryPicker cherryPicker(forceField);
cherryPicker.AddAthenaeum(man_ath);
cherryPicker.SetInt(settings::MinimumFragmentSize, 2);
cherryPicker.SetInt(settings::MaximumFragmentSize, 20);
cherryPicker.SetBool(settings::CalculateElectrons);
const indigox::ParamMolecule &molecule = cherryPicker.ParameteriseMolecule(mol);
//We can't save the parameterisation directly in ITP format from C++, but we save the binary molecule output
//which can be imported by the python module and outputted in ITP, IXD, PDB and RTP formats
SaveMolecule(mol, example_folder_path + "TestMolecules/axinellinA.out.param");
std::cout << "Done!\n";
}
| 41.288889
| 125
| 0.777718
|
allison-group
|
65eecaa7eecf4b5dfad13c5cc46fe6e749fea72f
| 3,007
|
hpp
|
C++
|
Include/LibYT/Concepts.hpp
|
MalteDoemer/YeetOS2
|
82be488ec1ed13e6558af4e248977dad317b3b85
|
[
"BSD-2-Clause"
] | null | null | null |
Include/LibYT/Concepts.hpp
|
MalteDoemer/YeetOS2
|
82be488ec1ed13e6558af4e248977dad317b3b85
|
[
"BSD-2-Clause"
] | null | null | null |
Include/LibYT/Concepts.hpp
|
MalteDoemer/YeetOS2
|
82be488ec1ed13e6558af4e248977dad317b3b85
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright 2021 Malte Dömer
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "StdLibExtras.hpp"
#include "Types.hpp"
namespace YT {
template<class T>
concept ArithmeticType = IsArithmetic<T>::value;
template<class T>
concept ConstType = IsConst<T>::value;
template<class T>
concept EnumType = IsEnum<T>::value;
template<class T>
concept FloatingPointType = IsFloatingPoint<T>::value;
template<class T>
concept FundamentalType = IsFundamental<T>::value;
template<class T>
concept IntegralType = IsIntegral<T>::value;
template<class T>
concept NullPointerType = IsNullPointer<T>::value;
template<class T>
concept SigendType = IsSigned<T>::value;
template<class T>
concept UnionType = IsUnion<T>::value;
template<class T>
concept UnsigendType = IsUnsigned<T>::value;
template<class T, class U>
concept SameAs = IsSame<T, U>::value;
template<class From, class To>
concept ConvertibleTo = IsConvertible<From, To>::value;
template<class T>
concept EqualityCompareable = requires(T a, T b)
{
{ a == b } -> ConvertibleTo<bool>;
{ a != b } -> ConvertibleTo<bool>;
};
template<class T>
concept Compareable = requires(T a, T b)
{
{ a == b } -> ConvertibleTo<bool>;
{ a != b } -> ConvertibleTo<bool>;
{ a <= b } -> ConvertibleTo<bool>;
{ a >= b } -> ConvertibleTo<bool>;
{ a < b } -> ConvertibleTo<bool>;
{ a > b } -> ConvertibleTo<bool>;
};
}
using YT::ArithmeticType;
using YT::Compareable;
using YT::ConstType;
using YT::ConvertibleTo;
using YT::EnumType;
using YT::EqualityCompareable;
using YT::FloatingPointType;
using YT::FundamentalType;
using YT::IntegralType;
using YT::NullPointerType;
using YT::SameAs;
using YT::SigendType;
using YT::UnionType;
using YT::UnsigendType;
| 29.480392
| 81
| 0.736615
|
MalteDoemer
|
65f4694160beffb076d12e39d59639ef6df2e43d
| 1,073
|
cpp
|
C++
|
AzureClient/AzureClient/EventHub.cpp
|
Ashish-Me2/Arduino-ESP8266-AzureIoTHub-MQTT-CameraMonitoring
|
695ca226ca0b9331a516573376323d71afb08f35
|
[
"MIT"
] | 3
|
2019-05-22T22:03:50.000Z
|
2020-11-25T11:56:38.000Z
|
AzureClient/AzureClient/EventHub.cpp
|
Ashish-Me2/Arduino-ESP8266-AzureIoTHub-MQTT-CameraMonitoring
|
695ca226ca0b9331a516573376323d71afb08f35
|
[
"MIT"
] | null | null | null |
AzureClient/AzureClient/EventHub.cpp
|
Ashish-Me2/Arduino-ESP8266-AzureIoTHub-MQTT-CameraMonitoring
|
695ca226ca0b9331a516573376323d71afb08f35
|
[
"MIT"
] | null | null | null |
#include "EventHub.h"
String Eventhub::createSas(char *key, String url){
// START: Create SAS
// https://azure.microsoft.com/en-us/documentation/articles/service-bus-sas-overview/
// Where to get seconds since the epoch: local service, SNTP, RTC
sasExpiryTime = now() + sasExpiryPeriodInSeconds;
String stringToSign = url + "\n" + sasExpiryTime;
// START: Create signature
Sha256.initHmac((const uint8_t*)key, 44);
Sha256.print(stringToSign);
char* sign = (char*) Sha256.resultHmac();
int signLen = 32;
// END: Create signature
// START: Get base64 of signature
int encodedSignLen = base64_enc_len(signLen);
char encodedSign[encodedSignLen];
base64_encode(encodedSign, sign, signLen);
// END: Get base64 of signature
// SharedAccessSignature
return "sr=" + url + "&sig="+ urlEncode(encodedSign) + "&se=" + sasExpiryTime +"&skn=" + deviceId;
// END: create SAS
}
void Eventhub::initialiseHub() {
sasUrl = urlEncode("https://") + urlEncode(host) + urlEncode(EVENT_HUB_END_POINT);
endPoint = EVENT_HUB_END_POINT;
}
| 29.805556
| 100
| 0.698043
|
Ashish-Me2
|
65f5030cb99991738a96f16d0715dee55bc429ea
| 2,490
|
hpp
|
C++
|
src/key/key_wallet.hpp
|
feitebi/main-chain
|
d4f2c4bb99b083d6162614a9a6b684c66ddf5d88
|
[
"MIT"
] | 1
|
2018-01-17T05:08:32.000Z
|
2018-01-17T05:08:32.000Z
|
src/key/key_wallet.hpp
|
feitebi/main-chain
|
d4f2c4bb99b083d6162614a9a6b684c66ddf5d88
|
[
"MIT"
] | null | null | null |
src/key/key_wallet.hpp
|
feitebi/main-chain
|
d4f2c4bb99b083d6162614a9a6b684c66ddf5d88
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2013-2014 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
*
* This file is part of coinpp.
*
* coinpp is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef COIN_KEY_WALLET_HPP
#define COIN_KEY_WALLET_HPP
#include <cstdint>
#include <string>
#include <coin/data_buffer.hpp>
#include <coin/key.hpp>
namespace coin {
/**
* Implements a wallet (private) key.
*/
class key_wallet : public data_buffer
{
public:
/**
* Constructor
*/
key_wallet(const std::int64_t & expires = 0);
/**
* Encodes.
*/
void encode();
/**
* Decodes
* @param buffer The data_buffer.
*/
void encode(data_buffer & buffer);
/**
* Decodes
*/
void decode();
/**
* Decodes
* @param buffer The data_buffer.
*/
void decode(data_buffer & buffer);
/**
* The private key.
*/
const key::private_t & key_private() const;
private:
/**
* The private key.
*/
key::private_t m_key_private;
/**
* The time created.
*/
std::int64_t m_time_created;
/**
* The time expires.
*/
std::int64_t m_time_expires;
/**
* The comment.
*/
std::string m_comment;
protected:
// ...
};
} // namespace coin
#endif // COIN_KEY_WALLET_HPP
| 24.653465
| 76
| 0.51245
|
feitebi
|
65f78b8241e1cdf7e3674e5b1cf8e06515e1c5ba
| 1,476
|
cpp
|
C++
|
test/test_dumpFHESetting.cpp
|
fionser/MDLHElib
|
3c686ab35d7b26a893213a6e9d4249cd46c2969d
|
[
"MIT"
] | 5
|
2017-01-16T06:20:07.000Z
|
2018-05-17T12:36:34.000Z
|
test/test_dumpFHESetting.cpp
|
fionser/MDLHElib
|
3c686ab35d7b26a893213a6e9d4249cd46c2969d
|
[
"MIT"
] | null | null | null |
test/test_dumpFHESetting.cpp
|
fionser/MDLHElib
|
3c686ab35d7b26a893213a6e9d4249cd46c2969d
|
[
"MIT"
] | 2
|
2017-08-26T13:16:35.000Z
|
2019-03-15T02:08:20.000Z
|
#include "utils/FHEUtils.hpp"
#include "utils/timer.hpp"
#include "fhe/EncryptedArray.h"
#include <string>
#include "algebra/NDSS.h"
void test_load(long m, long p, long r, long L)
{
MDL::Timer timer;
std::string path("fhe_setting");
timer.start();
FHEcontext context(m, p, r);
timer.end();
printf("Initial Context costed %f\n", timer.second());
timer.reset();
FHESecKey sk(context);
timer.end();
printf("Initial SK costed %f\n", timer.second());
timer.reset();
load_FHE_setting(path, context, sk);
timer.end();
printf("Load costed %f sec.\n", timer.second());
FHEPubKey pk = sk;
NTL::ZZX plain;
Ctxt ctxt(pk);
pk.Encrypt(ctxt, NTL::to_ZZX(10));
ctxt *= ctxt;
sk.Decrypt(plain, ctxt);
assert(plain == 100);
auto G = context.alMod.getFactorsOverZZ()[0];
EncryptedArray ea(context, G);
assert(ea.size() == 4);
}
void test_dump(long m, long p, long r, long L)
{
MDL::Timer timer;
timer.start();
dump_FHE_setting_to_file("fhe_setting_32", 80, m, p, r, L);
timer.end();
printf("Cost %f to dump m : %ld, p : %ld, r : %ld, L : %ld\n",
timer.second(), m, p, r, L);
}
int main(int argc, char *argv[]) {
ArgMapping arg;
long m, p, r, L;
arg.arg("m", m, "m");
arg.arg("p", p, "p");
arg.arg("r", r, "r");
arg.arg("L", L, "L");
arg.parse(argc, argv);
//test_load(m, p, r, L);
test_dump(m, p, r, L);
return 0;
}
| 23.0625
| 66
| 0.573171
|
fionser
|
65f7ae9a8d8b474c1e1ec8bb2150a22ff8451fb6
| 1,762
|
cpp
|
C++
|
moon-src/luabind/lua_http.cpp
|
leefy4415/moon
|
2a2005306e9a685a6af899a0daae9c53603b38e4
|
[
"MIT"
] | 1
|
2020-09-22T01:57:54.000Z
|
2020-09-22T01:57:54.000Z
|
moon-src/luabind/lua_http.cpp
|
leefy4415/moon
|
2a2005306e9a685a6af899a0daae9c53603b38e4
|
[
"MIT"
] | null | null | null |
moon-src/luabind/lua_http.cpp
|
leefy4415/moon
|
2a2005306e9a685a6af899a0daae9c53603b38e4
|
[
"MIT"
] | null | null | null |
#include "sol/sol.hpp"
#include "common/http_util.hpp"
using namespace moon;
static sol::table bind_http(sol::this_state L)
{
sol::state_view lua(L);
sol::table module = lua.create_table();
module.set_function("parse_request", [](std::string_view data) {
std::string_view method;
std::string_view path;
std::string_view query_string;
std::string_view version;
http::case_insensitive_multimap_view header;
bool ok = http::request_parser::parse(data, method, path, query_string, version, header);
return std::make_tuple(ok, method, path, query_string, version, sol::as_table(header));
});
module.set_function("parse_response", [](std::string_view data) {
std::string_view version;
std::string_view status_code;
http::case_insensitive_multimap_view header;
bool ok = http::response_parser::parse(data, version, status_code, header);
return std::make_tuple(ok, version, status_code, sol::as_table(header));
});
module.set_function("parse_query_string", [](const std::string &data) {
return sol::as_table(http::query_string::parse(data));
});
module.set_function("create_query_string", [](sol::as_table_t<http::case_insensitive_multimap> src) {
return http::query_string::create(src.value());
});
module.set_function("urlencode", [](std::string_view src) {
return http::percent::encode(std::string{ src });
});
module.set_function("urldecode", [](std::string_view src) {
return http::percent::decode(std::string{ src });
});
return module;
}
extern "C"
{
int LUAMOD_API luaopen_http(lua_State *L)
{
return sol::stack::call_lua(L, 1, bind_http);
}
}
| 32.036364
| 105
| 0.658343
|
leefy4415
|
65fa36eff75fb1297b6d8f4576e3411c7e51c17c
| 4,952
|
cpp
|
C++
|
modules/attention_segmentation/src/Texture.cpp
|
v4r-tuwien/v4r
|
ff3fbd6d2b298b83268ba4737868bab258262a40
|
[
"BSD-1-Clause",
"BSD-2-Clause"
] | 2
|
2021-02-22T11:36:33.000Z
|
2021-07-20T11:31:08.000Z
|
modules/attention_segmentation/src/Texture.cpp
|
v4r-tuwien/v4r
|
ff3fbd6d2b298b83268ba4737868bab258262a40
|
[
"BSD-1-Clause",
"BSD-2-Clause"
] | null | null | null |
modules/attention_segmentation/src/Texture.cpp
|
v4r-tuwien/v4r
|
ff3fbd6d2b298b83268ba4737868bab258262a40
|
[
"BSD-1-Clause",
"BSD-2-Clause"
] | 3
|
2018-10-19T10:39:23.000Z
|
2021-04-07T13:39:03.000Z
|
/****************************************************************************
**
** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group
** Contact: v4r.acin.tuwien.ac.at
**
** This file is part of V4R
**
** V4R is distributed under dual licenses - GPLv3 or closed source.
**
** GNU General Public License Usage
** V4R is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published
** by the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** V4R 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.
**
** Please review the following information to ensure the GNU General Public
** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
**
** Commercial License Usage
** If GPL is not suitable for your project, you must purchase a commercial
** license to use V4R. Licensees holding valid commercial V4R licenses may
** use this file in accordance with the commercial license agreement
** provided with the Software or, alternatively, in accordance with the
** terms contained in a written agreement between you and TU Wien, ACIN, V4R.
** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at.
**
**
** The copyright holder additionally grants the author(s) of the file the right
** to use, copy, modify, merge, publish, distribute, sublicense, and/or
** sell copies of their contributions without any restrictions.
**
****************************************************************************/
/**
* @file Texture.cpp
* @author Richtsfeld
* @date October 2012
* @version 0.1
* @brief Calculate texture feature to compare surface texture.
*/
#include "v4r/attention_segmentation/Texture.h"
namespace v4r {
/************************************************************************************
* Constructor/Destructor
*/
Texture::Texture() {
computed = false;
have_edges = false;
have_indices = false;
}
Texture::~Texture() {}
void Texture::setInputEdges(cv::Mat &_edges) {
if ((_edges.cols <= 0) || (_edges.rows <= 0)) {
LOG(ERROR) << "Invalid image (height|width must be > 1";
throw std::runtime_error("[Texture::setInputEdges] Invalid image (height|width must be > 1)");
}
if (_edges.type() != CV_8UC1) {
LOG(ERROR) << "Invalid image type (must be 8UC1)";
throw std::runtime_error("[Texture::setInputEdges] Invalid image type (must be 8UC1)");
}
edges = _edges;
width = edges.cols;
height = edges.rows;
have_edges = true;
computed = false;
indices.reset(new pcl::PointIndices);
for (int i = 0; i < width * height; i++) {
indices->indices.push_back(i);
}
}
void Texture::setIndices(pcl::PointIndices::Ptr _indices) {
if (!have_edges) {
LOG(ERROR) << "No edges available.";
throw std::runtime_error("[Texture::setIndices]: Error: No edges available.");
}
indices = _indices;
have_indices = true;
}
void Texture::setIndices(std::vector<int> &_indices) {
indices.reset(new pcl::PointIndices);
indices->indices = _indices;
}
void Texture::setIndices(cv::Rect _rect) {
if (!have_edges) {
LOG(ERROR) << "No edges available.";
throw std::runtime_error("[Texture::setIndices]: Error: No edges available.");
}
if (_rect.y >= height) {
_rect.y = height - 1;
}
if ((_rect.y + _rect.height) >= height) {
_rect.height = height - _rect.y;
}
if (_rect.x >= width) {
_rect.x = width - 1;
}
if ((_rect.x + _rect.width) >= width) {
_rect.width = width - _rect.x;
}
VLOG(1) << "_rect = " << _rect.x << ", " << _rect.y << ", " << _rect.x + _rect.width << ", "
<< _rect.y + _rect.height;
indices.reset(new pcl::PointIndices);
for (int r = _rect.y; r < (_rect.y + _rect.height); r++) {
for (int c = _rect.x; c < (_rect.x + _rect.width); c++) {
indices->indices.push_back(r * width + c);
}
}
have_indices = true;
}
void Texture::compute() {
if (!have_edges) {
LOG(ERROR) << "No edges available.";
throw std::runtime_error("[Texture::compute]: Error: No edges available.");
}
textureRate = 0.0;
if ((indices->indices.size()) <= 0) {
computed = true;
return;
}
int texArea = 0;
for (unsigned int i = 0; i < indices->indices.size(); i++) {
int x = indices->indices.at(i) % width;
int y = indices->indices.at(i) / width;
if (edges.at<uchar>(y, x) == 255)
texArea++;
}
textureRate = (double)((double)texArea / indices->indices.size());
computed = true;
}
double Texture::compare(Texture::Ptr t) {
if (!computed || !(t->getComputed())) {
LOG(ERROR) << "Texture is not computed.";
return 0.;
}
return 1. - fabs(textureRate - t->getTextureRate());
}
} // namespace v4r
| 28.45977
| 98
| 0.625606
|
v4r-tuwien
|
65fac98ea13e3d3d783063a53fa92368dc96f3fe
| 2,879
|
cpp
|
C++
|
Gems/Atom/RHI/Code/Source/RHI/BufferScopeAttachment.cpp
|
cypherdotXd/o3de
|
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
|
[
"Apache-2.0",
"MIT"
] | 11
|
2021-07-08T09:58:26.000Z
|
2022-03-17T17:59:26.000Z
|
Gems/Atom/RHI/Code/Source/RHI/BufferScopeAttachment.cpp
|
RoddieKieley/o3de
|
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
|
[
"Apache-2.0",
"MIT"
] | 29
|
2021-07-06T19:33:52.000Z
|
2022-03-22T10:27:49.000Z
|
Gems/Atom/RHI/Code/Source/RHI/BufferScopeAttachment.cpp
|
RoddieKieley/o3de
|
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
|
[
"Apache-2.0",
"MIT"
] | 4
|
2021-07-06T19:24:43.000Z
|
2022-03-31T12:42:27.000Z
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <Atom/RHI/BufferScopeAttachment.h>
#include <Atom/RHI/BufferFrameAttachment.h>
#include <Atom/RHI/BufferView.h>
namespace AZ
{
namespace RHI
{
BufferScopeAttachment::BufferScopeAttachment(
Scope& scope,
FrameAttachment& attachment,
ScopeAttachmentUsage usage,
ScopeAttachmentAccess access,
const BufferScopeAttachmentDescriptor& descriptor)
: ScopeAttachment(scope, attachment, usage, access)
, m_descriptor{descriptor}
{
AZ_Assert(
m_descriptor.m_bufferViewDescriptor.m_elementSize > 0 &&
m_descriptor.m_bufferViewDescriptor.m_elementCount > 0,
"Invalid buffer view for attachment.");
if (m_descriptor.m_loadStoreAction.m_loadAction == AttachmentLoadAction::Clear)
{
AZ_Error("FrameScheduler", access == ScopeAttachmentAccess::ReadWrite, "Attempting to clear an attachment that is read-only");
}
}
const BufferScopeAttachmentDescriptor& BufferScopeAttachment::GetDescriptor() const
{
return m_descriptor;
}
const BufferView* BufferScopeAttachment::GetBufferView() const
{
return static_cast<const BufferView*>(ScopeAttachment::GetResourceView());
}
void BufferScopeAttachment::SetBufferView(ConstPtr<BufferView> bufferView)
{
SetResourceView(AZStd::move(bufferView));
}
const BufferFrameAttachment& BufferScopeAttachment::GetFrameAttachment() const
{
return static_cast<const BufferFrameAttachment&>(ScopeAttachment::GetFrameAttachment());
}
BufferFrameAttachment& BufferScopeAttachment::GetFrameAttachment()
{
return static_cast<BufferFrameAttachment&>(ScopeAttachment::GetFrameAttachment());
}
const BufferScopeAttachment* BufferScopeAttachment::GetPrevious() const
{
return static_cast<const BufferScopeAttachment*>(ScopeAttachment::GetPrevious());
}
BufferScopeAttachment* BufferScopeAttachment::GetPrevious()
{
return static_cast<BufferScopeAttachment*>(ScopeAttachment::GetPrevious());
}
const BufferScopeAttachment* BufferScopeAttachment::GetNext() const
{
return static_cast<const BufferScopeAttachment*>(ScopeAttachment::GetNext());
}
BufferScopeAttachment* BufferScopeAttachment::GetNext()
{
return static_cast<BufferScopeAttachment*>(ScopeAttachment::GetNext());
}
}
}
| 34.686747
| 142
| 0.657173
|
cypherdotXd
|
65faebe41985ba4358f801d511d4a70b4b67e77d
| 218
|
cc
|
C++
|
versus/go/01-lambdas/capture.cc
|
JohnMurray/cpp-vs
|
def49c416b5abf161241e7c1d8b41e6b01fb8cac
|
[
"Apache-2.0"
] | 10
|
2018-05-07T03:00:00.000Z
|
2022-03-14T14:26:27.000Z
|
versus/ruby/01-lambda/capture.cc
|
JohnMurray/cpp-vs
|
def49c416b5abf161241e7c1d8b41e6b01fb8cac
|
[
"Apache-2.0"
] | 35
|
2018-05-26T16:01:58.000Z
|
2022-03-30T22:39:33.000Z
|
versus/ruby/01-lambda/capture.cc
|
JohnMurray/cpp-vs
|
def49c416b5abf161241e7c1d8b41e6b01fb8cac
|
[
"Apache-2.0"
] | 1
|
2018-07-17T12:47:24.000Z
|
2018-07-17T12:47:24.000Z
|
#include <functional>
template<typename T>
std::function<T(T)> addX(T x) {
return [x](T n) -> T {
return n + x;
};
}
int main() {
auto addFive = addX<int>(5);
addFive(10);
// returns 15
}
| 14.533333
| 32
| 0.527523
|
JohnMurray
|
65ff56baa07cf766ac826e1603c5b3da5df944a6
| 327
|
cpp
|
C++
|
examples/nested_cpp/test/main.cpp
|
trflynn89/flymake
|
9dcfbfd43f7d7987e903940bfed3cc416c39c9cb
|
[
"MIT"
] | null | null | null |
examples/nested_cpp/test/main.cpp
|
trflynn89/flymake
|
9dcfbfd43f7d7987e903940bfed3cc416c39c9cb
|
[
"MIT"
] | 1
|
2021-02-09T02:53:26.000Z
|
2021-02-09T02:53:26.000Z
|
examples/nested_cpp/test/main.cpp
|
trflynn89/flymake
|
9dcfbfd43f7d7987e903940bfed3cc416c39c9cb
|
[
"MIT"
] | null | null | null |
#include "nested_cpp/outer_lib/inner_lib/inner_lib.hpp"
#include "nested_cpp/outer_lib/outer_lib.hpp"
#include <cassert>
#include <iostream>
int main()
{
assert(outer::outer_value() == 123);
assert(inner::outer_value() == 123);
assert(inner::inner_value() == 1989);
std::cout << "Passed!\n";
return 0;
}
| 20.4375
| 55
| 0.666667
|
trflynn89
|
65ffc9b0a240192ee6b9cc3dfd054327cc20d6cc
| 2,356
|
cpp
|
C++
|
Engine/src/Render/Camera/icMaxCam.cpp
|
binofet/ice
|
dee91da76df8b4f46ed4727d901819d8d20aefe3
|
[
"MIT"
] | null | null | null |
Engine/src/Render/Camera/icMaxCam.cpp
|
binofet/ice
|
dee91da76df8b4f46ed4727d901819d8d20aefe3
|
[
"MIT"
] | null | null | null |
Engine/src/Render/Camera/icMaxCam.cpp
|
binofet/ice
|
dee91da76df8b4f46ed4727d901819d8d20aefe3
|
[
"MIT"
] | null | null | null |
#include "Render/Camera/icMaxCam.h"
#include "Core/IO/icInput.h"
#include "Math/Matrix/icMatrix44.h"
icMaxCam::icMaxCam( void )
{
m_rZoom = 100.0f;
m_rXrot = 0.0f;
m_rYrot = 0.0f;
m_rZoomMin = 50.0f;
m_rZoomMax = 500.0f;
m_v3Center.Set(0.0f,0.0f,0.0f);
bEnableInput = true;
}
icMaxCam::~icMaxCam( void )
{
}
void icMaxCam::Update( const float fDeltaTime )
{
if (bEnableInput)
{
icInput* input = icInput::Instance();
if (input->IsDown(ICMOUSE_M) || input->IsDown(ICMOUSE_R))
{
if (input->IsDown(ICKEY_LALT))
{
// arc rotate
icReal x = input->GetAxis(ICAXIS_MOUSE_X) * fDeltaTime * 5000.0f * m_rZoom/m_rZoomMax;
icReal y = input->GetAxis(ICAXIS_MOUSE_Y) * fDeltaTime * 5000.0f * m_rZoom/m_rZoomMax;
if (m_rYrot > 0)
m_rYrot += y;
else
m_rYrot -= y;
m_rXrot -= x;
}
else
{
// pan
icReal z_amt = (m_rZoom - m_rZoomMin) + 0.05f * (m_rZoomMax - m_rZoomMin);
icReal x = input->GetAxis(ICAXIS_MOUSE_X) * fDeltaTime * 200.0f * z_amt;
icReal y = input->GetAxis(ICAXIS_MOUSE_Y) * fDeltaTime * 200.0f * z_amt;
m_v3Center += m_m44ViewMat.Transform(-x,-y,0.0f);
}
}
// handle zoom
icReal zoom = input->GetAxis(ICAXIS_MOUSE_Z);
m_rZoom -= zoom * fDeltaTime * 1000.0f;
m_rZoom = icClamp(m_rZoom, m_rZoomMin, m_rZoomMax);
}
// trimming
while (m_rYrot > IC_PI * 2.0f)
m_rYrot -= 2 * IC_PI;
while (m_rYrot < 0.0f)
m_rYrot += 2 * IC_PI;
while (m_rXrot > IC_PI * 2.0f)
m_rXrot -= 2 * IC_PI;
while (m_rXrot < 0.0f)
m_rXrot += 2 * IC_PI;
icReal theta = m_rXrot;
icReal phi = m_rYrot - IC_PI;
icReal Cx, Cy, Cz;
Cx = m_rZoom * icCos(theta) * icSin(phi);
Cy = m_rZoom * icCos(phi);
Cz = m_rZoom * icSin(theta) * icSin(phi);
icVector3 point(Cx,Cy,Cz);
icVector3 position = point + m_v3Center;
if (phi < 0.0)
icCreateLookAt(position, m_v3Center,icVector3(0.0f,-1.0,0.0f),m_m44ViewMat);
else
icCreateLookAt(position, m_v3Center,icVector3::Y_AXIS,m_m44ViewMat);
}
| 26.47191
| 102
| 0.547114
|
binofet
|
5a0041876ba8347ac3bbbac0ac4158cb21da0ab3
| 804
|
cpp
|
C++
|
LeetCode/Daily-Challenge/Evaluate Reverse Polish Notation.cpp
|
Sowmik23/All-Codes
|
212ef0d940fa84624bb2972a257768a830a709a3
|
[
"MIT"
] | 5
|
2021-02-14T17:48:21.000Z
|
2022-01-24T14:29:44.000Z
|
LeetCode/Daily-Challenge/Evaluate Reverse Polish Notation.cpp
|
Sowmik23/All-Codes
|
212ef0d940fa84624bb2972a257768a830a709a3
|
[
"MIT"
] | null | null | null |
LeetCode/Daily-Challenge/Evaluate Reverse Polish Notation.cpp
|
Sowmik23/All-Codes
|
212ef0d940fa84624bb2972a257768a830a709a3
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
int a, b, res;
for(string i: tokens){
if(isOperator(i)){
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
if(i=="+") res = a+b;
else if(i=="-") res = b-a;
else if(i=="*") res = b*a;
else if(i=="/") res = b/a;
stk.push(res);
}
else {
stk.push(stoi(i));
}
}
return stk.top();
}
private:
bool isOperator(string ch){
if(ch=="+" or ch=="-" or ch=="*" or ch=="/") return true;
return false;
}
};
| 23.647059
| 65
| 0.334577
|
Sowmik23
|
5a0052e98e648bb4eb323ab2d2191dcca614cd58
| 965
|
cpp
|
C++
|
workdir/ScopeAnalysis/LORAnalysis/SDAEstimateTOFCalib.cpp
|
wictus/oldScopeAnalysis
|
e8a15f11c504c1a1a880d4a5096cdbfac0edf2de
|
[
"MIT"
] | null | null | null |
workdir/ScopeAnalysis/LORAnalysis/SDAEstimateTOFCalib.cpp
|
wictus/oldScopeAnalysis
|
e8a15f11c504c1a1a880d4a5096cdbfac0edf2de
|
[
"MIT"
] | null | null | null |
workdir/ScopeAnalysis/LORAnalysis/SDAEstimateTOFCalib.cpp
|
wictus/oldScopeAnalysis
|
e8a15f11c504c1a1a880d4a5096cdbfac0edf2de
|
[
"MIT"
] | null | null | null |
#include "./SDAEstimateTOFCalib.h"
SDAEstimateTOFCalib::SDAEstimateTOFCalib(const char* name, const char* title,
const char* in_file_suffix, const char* out_file_suffix, const double threshold) : JPetCommonAnalysisModule( name, title, in_file_suffix, out_file_suffix )
{
fSelectedThreshold = threshold;
}
SDAEstimateTOFCalib::~SDAEstimateTOFCalib(){}
void SDAEstimateTOFCalib::begin()
{
}
void SDAEstimateTOFCalib::exec()
{
fReader->getEntry(fEvent);
const JPetLOR& fLOR = dynamic_cast< JPetLOR& > ( fReader->getData() );
fTOFs.push_back( ( fLOR.getSecondHit().getTime() - fLOR.getFirstHit().getTime() ) );
fEvent++;
}
void SDAEstimateTOFCalib::end()
{
gStyle->SetOptFit(1);
TCanvas* c1 = new TCanvas();
TH1F* TOF = new TH1F("TOF", "TOF", 2000, -10, 10);
for( unsigned int i = 0; i < fTOFs.size(); i++)
{
TOF->Fill(fTOFs[i]/1000.0);
}
TOF->Sumw2();
TOF->Draw();
TOF->Fit("gaus","QI");
c1->SaveAs("TOF.png");
}
| 21.444444
| 170
| 0.674611
|
wictus
|
5a0780f127bedfcf86ba645ff619e9b50688403d
| 3,445
|
cpp
|
C++
|
activemq-cpp/src/main/decaf/internal/util/concurrent/windows/Atomics.cpp
|
novomatic-tech/activemq-cpp
|
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
|
[
"Apache-2.0"
] | 87
|
2015-03-02T17:58:20.000Z
|
2022-02-11T02:52:52.000Z
|
activemq-cpp/src/main/decaf/internal/util/concurrent/windows/Atomics.cpp
|
novomatic-tech/activemq-cpp
|
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
|
[
"Apache-2.0"
] | 3
|
2017-05-10T13:16:08.000Z
|
2019-01-23T20:21:53.000Z
|
activemq-cpp/src/main/decaf/internal/util/concurrent/windows/Atomics.cpp
|
novomatic-tech/activemq-cpp
|
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
|
[
"Apache-2.0"
] | 71
|
2015-04-28T06:04:04.000Z
|
2022-03-15T13:34:06.000Z
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <decaf/internal/util/concurrent/Atomics.h>
using namespace decaf::internal;
using namespace decaf::internal::util;
using namespace decaf::internal::util::concurrent;
////////////////////////////////////////////////////////////////////////////////
void Atomics::initialize() {
}
////////////////////////////////////////////////////////////////////////////////
void Atomics::shutdown() {
}
////////////////////////////////////////////////////////////////////////////////
bool Atomics::compareAndSet32(volatile int* target, int expect, int update ) {
return ::InterlockedCompareExchange((volatile LONG*)target, update, expect) == (unsigned int)expect;
}
////////////////////////////////////////////////////////////////////////////////
bool Atomics::compareAndSet(volatile void** target, void* expect, void* update) {
return ::InterlockedCompareExchangePointer((volatile PVOID*)target, (void*)update, (void*)expect ) == (void*)expect;
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndSet(volatile int* target, int newValue) {
return ::InterlockedExchange((volatile LONG*)target, newValue);
}
////////////////////////////////////////////////////////////////////////////////
void* Atomics::getAndSet(volatile void** target, void* newValue) {
return InterlockedExchangePointer((volatile PVOID*)target, newValue);
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndIncrement(volatile int* target) {
return ::InterlockedIncrement((volatile LONG*)target) - 1;
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndDecrement(volatile int* target) {
return ::InterlockedExchangeAdd((volatile LONG*)target, 0xFFFFFFFF);
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndAdd(volatile int* target, int delta) {
return ::InterlockedExchangeAdd((volatile LONG*)target, delta);
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::addAndGet(volatile int* target, int delta) {
return ::InterlockedExchangeAdd((volatile LONG*)target, delta) + delta;
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::incrementAndGet(volatile int* target) {
return ::InterlockedIncrement((volatile LONG*)target);
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::decrementAndGet(volatile int* target) {
return ::InterlockedExchangeAdd((volatile LONG*)target, 0xFFFFFFFF) - 1;
}
| 42.012195
| 120
| 0.53701
|
novomatic-tech
|
5a08229b925f117033174e8422230e6102f958af
| 1,884
|
cpp
|
C++
|
Algorithms/0047.PermutationsII/solution.cpp
|
stdstring/leetcode
|
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
|
[
"MIT"
] | null | null | null |
Algorithms/0047.PermutationsII/solution.cpp
|
stdstring/leetcode
|
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
|
[
"MIT"
] | null | null | null |
Algorithms/0047.PermutationsII/solution.cpp
|
stdstring/leetcode
|
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <vector>
#include "gtest/gtest.h"
namespace
{
class Solution
{
public:
std::vector<std::vector<int>> permuteUnique(std::vector<int> const &nums) const
{
std::vector<int> numbers(nums);
std::sort(numbers.begin(), numbers.end());
std::vector<bool> usedNumbers;
for (size_t index = 0; index < numbers.size(); ++index)
usedNumbers.push_back(false);
std::vector<int> current;
std::vector<std::vector<int>> dest;
generate(numbers, usedNumbers, current, dest);
return dest;
}
private:
void generate(std::vector<int> const &numbers, std::vector<bool> &usedNumbers, std::vector<int> ¤t, std::vector<std::vector<int>> &dest) const
{
size_t lastUsedIndex = numbers.size();
for (size_t index = 0; index < numbers.size(); ++index)
{
if (!usedNumbers[index])
{
if (lastUsedIndex != numbers.size() && numbers[lastUsedIndex] == numbers[index])
continue;
lastUsedIndex = index;
current.push_back(numbers[index]);
const bool isPermutation = current.size() == numbers.size();
if (isPermutation)
dest.push_back(current);
else
{
usedNumbers[index] = true;
generate(numbers, usedNumbers, current, dest);
usedNumbers[index] = false;
}
current.pop_back();
if (isPermutation)
return;
}
}
}
};
}
namespace PermutationsIITask
{
TEST(PermutationsIITaskTests, Examples)
{
const Solution solution;
ASSERT_EQ(std::vector<std::vector<int>>({{1, 1, 2}, {1, 2, 1}, {2, 1, 1}}), solution.permuteUnique({1, 1, 2}));
}
}
| 28.545455
| 152
| 0.54034
|
stdstring
|
5a0bcd08a291c33b3102bcf3b66a712a36d9e8d3
| 7,830
|
cc
|
C++
|
drivers/bluetooth/lib/sm/util.cc
|
PowerOlive/garnet
|
16b5b38b765195699f41ccb6684cc58dd3512793
|
[
"BSD-3-Clause"
] | null | null | null |
drivers/bluetooth/lib/sm/util.cc
|
PowerOlive/garnet
|
16b5b38b765195699f41ccb6684cc58dd3512793
|
[
"BSD-3-Clause"
] | null | null | null |
drivers/bluetooth/lib/sm/util.cc
|
PowerOlive/garnet
|
16b5b38b765195699f41ccb6684cc58dd3512793
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "util.h"
#include <openssl/aes.h>
#include <zircon/assert.h>
#include "garnet/drivers/bluetooth/lib/hci/util.h"
namespace btlib {
using common::BufferView;
using common::ByteBuffer;
using common::DeviceAddress;
using common::UInt128;
namespace sm {
namespace util {
namespace {
constexpr size_t kPreqSize = 7;
// Swap the endianness of a 128-bit integer. |in| and |out| should not be backed
// by the same buffer.
void Swap128(const UInt128& in, UInt128* out) {
ZX_DEBUG_ASSERT(out);
for (size_t i = 0; i < in.size(); ++i) {
(*out)[i] = in[in.size() - i - 1];
}
}
// XOR two 128-bit integers and return the result in |out|. It is possible to
// pass a pointer to one of the inputs as |out|.
void Xor128(const UInt128& int1, const UInt128& int2, UInt128* out) {
ZX_DEBUG_ASSERT(out);
uint64_t lower1 = *reinterpret_cast<const uint64_t*>(int1.data());
uint64_t upper1 = *reinterpret_cast<const uint64_t*>(int1.data() + 8);
uint64_t lower2 = *reinterpret_cast<const uint64_t*>(int2.data());
uint64_t upper2 = *reinterpret_cast<const uint64_t*>(int2.data() + 8);
uint64_t lower_res = lower1 ^ lower2;
uint64_t upper_res = upper1 ^ upper2;
std::memcpy(out->data(), &lower_res, 8);
std::memcpy(out->data() + 8, &upper_res, 8);
}
} // namespace
std::string IOCapabilityToString(IOCapability capability) {
switch (capability) {
case IOCapability::kDisplayOnly:
return "Display Only";
case IOCapability::kDisplayYesNo:
return "Display w/ Confirmation";
case IOCapability::kKeyboardOnly:
return "Keyboard";
case IOCapability::kNoInputNoOutput:
return "No I/O";
case IOCapability::kKeyboardDisplay:
return "Keyboard w/ Display";
default:
break;
}
return "(unknown)";
};
std::string PairingMethodToString(PairingMethod method) {
switch (method) {
case PairingMethod::kJustWorks:
return "Just Works";
case PairingMethod::kPasskeyEntryInput:
return "Passkey Entry (input)";
case PairingMethod::kPasskeyEntryDisplay:
return "Passkey Entry (display)";
case PairingMethod::kNumericComparison:
return "Numeric Comparison";
case PairingMethod::kOutOfBand:
return "OOB";
default:
break;
}
return "(unknown)";
}
PairingMethod SelectPairingMethod(bool sec_conn, bool local_oob, bool peer_oob,
bool mitm_required, IOCapability local_ioc,
IOCapability peer_ioc, bool local_initiator) {
if ((sec_conn && (local_oob || peer_oob)) ||
(!sec_conn && local_oob && peer_oob)) {
return PairingMethod::kOutOfBand;
}
// If neither device requires MITM protection or if the peer has not I/O
// capable, we select Just Works.
if (!mitm_required || peer_ioc == IOCapability::kNoInputNoOutput) {
return PairingMethod::kJustWorks;
}
// Select the pairing method by comparing I/O capabilities. The switch
// statement will return if an authenticated entry method is selected.
// Otherwise, we'll break out and default to Just Works below.
switch (local_ioc) {
case IOCapability::kNoInputNoOutput:
break;
case IOCapability::kDisplayOnly:
switch (peer_ioc) {
case IOCapability::kKeyboardOnly:
case IOCapability::kKeyboardDisplay:
return PairingMethod::kPasskeyEntryDisplay;
default:
break;
}
break;
case IOCapability::kDisplayYesNo:
switch (peer_ioc) {
case IOCapability::kDisplayYesNo:
return sec_conn ? PairingMethod::kNumericComparison
: PairingMethod::kJustWorks;
case IOCapability::kKeyboardDisplay:
return sec_conn ? PairingMethod::kNumericComparison
: PairingMethod::kPasskeyEntryDisplay;
case IOCapability::kKeyboardOnly:
return PairingMethod::kPasskeyEntryDisplay;
default:
break;
}
break;
case IOCapability::kKeyboardOnly:
return PairingMethod::kPasskeyEntryInput;
case IOCapability::kKeyboardDisplay:
switch (peer_ioc) {
case IOCapability::kKeyboardOnly:
return PairingMethod::kPasskeyEntryDisplay;
case IOCapability::kDisplayOnly:
return PairingMethod::kPasskeyEntryInput;
case IOCapability::kDisplayYesNo:
return sec_conn ? PairingMethod::kNumericComparison
: PairingMethod::kPasskeyEntryInput;
default:
break;
}
// If both devices have KeyboardDisplay then use Numeric Comparison
// if S.C. is supported. Otherwise, the initiator always displays and the
// responder inputs a passkey.
if (sec_conn) {
return PairingMethod::kNumericComparison;
}
return local_initiator ? PairingMethod::kPasskeyEntryDisplay
: PairingMethod::kPasskeyEntryInput;
}
return PairingMethod::kJustWorks;
}
void Encrypt(const common::UInt128& key, const common::UInt128& plaintext_data,
common::UInt128* out_encrypted_data) {
// Swap the bytes since "the most significant octet of key corresponds to
// key[0], the most significant octet of plaintextData corresponds to in[0]
// and the most significant octet of encryptedData corresponds to out[0] using
// the notation specified in FIPS-197" for the security function "e" (Vol 3,
// Part H, 2.2.1).
UInt128 be_k, be_pt, be_enc;
Swap128(key, &be_k);
Swap128(plaintext_data, &be_pt);
AES_KEY k;
AES_set_encrypt_key(be_k.data(), 128, &k);
AES_encrypt(be_pt.data(), be_enc.data(), &k);
Swap128(be_enc, out_encrypted_data);
}
void C1(const UInt128& tk, const UInt128& rand, const ByteBuffer& preq,
const ByteBuffer& pres, const DeviceAddress& initiator_addr,
const DeviceAddress& responder_addr, UInt128* out_confirm_value) {
ZX_DEBUG_ASSERT(preq.size() == kPreqSize);
ZX_DEBUG_ASSERT(pres.size() == kPreqSize);
ZX_DEBUG_ASSERT(out_confirm_value);
UInt128 p1, p2;
// Calculate p1 = pres || preq || rat’ || iat’
hci::LEAddressType iat = hci::AddressTypeToHCI(initiator_addr.type());
hci::LEAddressType rat = hci::AddressTypeToHCI(responder_addr.type());
p1[0] = static_cast<uint8_t>(iat);
p1[1] = static_cast<uint8_t>(rat);
std::memcpy(p1.data() + 2, preq.data(), preq.size()); // Bytes [2-8]
std::memcpy(p1.data() + 2 + preq.size(), pres.data(), pres.size()); // [9-15]
// Calculate p2 = padding || ia || ra
BufferView ia = initiator_addr.value().bytes();
BufferView ra = responder_addr.value().bytes();
std::memcpy(p2.data(), ra.data(), ra.size()); // Lowest 6 bytes
std::memcpy(p2.data() + ra.size(), ia.data(), ia.size()); // Next 6 bytes
std::memset(p2.data() + ra.size() + ia.size(), 0,
p2.size() - ra.size() - ia.size()); // Pad 0s for the remainder
// Calculate the confirm value: e(tk, e(tk, rand XOR p1) XOR p2)
UInt128 tmp;
Xor128(rand, p1, &p1);
Encrypt(tk, p1, &tmp);
Xor128(tmp, p2, &tmp);
Encrypt(tk, tmp, out_confirm_value);
}
void S1(const UInt128& tk, const UInt128& r1, const UInt128& r2,
UInt128* out_stk) {
ZX_DEBUG_ASSERT(out_stk);
UInt128 r_prime;
// Take the lower 64-bits of r1 and r2 and concatanate them to produce
// r’ = r1’ || r2’, where r2' contains the LSB and r1' the MSB.
constexpr size_t kHalfSize = sizeof(UInt128) / 2;
std::memcpy(r_prime.data(), r2.data(), kHalfSize);
std::memcpy(r_prime.data() + kHalfSize, r1.data(), kHalfSize);
// Calculate the STK: e(tk, r’)
Encrypt(tk, r_prime, out_stk);
}
} // namespace util
} // namespace sm
} // namespace btlib
| 33.319149
| 80
| 0.667816
|
PowerOlive
|
5a0c05852f5fee16463d763adeb77c37cc9d6582
| 1,579
|
cc
|
C++
|
chrome/browser/notifications/notification_ui_manager_android.cc
|
Fusion-Rom/android_external_chromium_org
|
d8b126911c6ea9753e9f526bee5654419e1d0ebd
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2
|
2020-01-25T10:18:18.000Z
|
2021-01-23T15:29:56.000Z
|
chrome/browser/notifications/notification_ui_manager_android.cc
|
Fusion-Rom/android_external_chromium_org
|
d8b126911c6ea9753e9f526bee5654419e1d0ebd
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2018-02-10T21:00:08.000Z
|
2018-03-20T05:09:50.000Z
|
chrome/browser/notifications/notification_ui_manager_android.cc
|
Fusion-Rom/android_external_chromium_org
|
d8b126911c6ea9753e9f526bee5654419e1d0ebd
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2020-11-04T06:34:36.000Z
|
2020-11-04T06:34:36.000Z
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/notification_ui_manager_android.h"
#include "base/logging.h"
// static
NotificationUIManager* NotificationUIManager::Create(PrefService* local_state) {
return new NotificationUIManagerAndroid();
}
NotificationUIManagerAndroid::NotificationUIManagerAndroid() {
}
NotificationUIManagerAndroid::~NotificationUIManagerAndroid() {
}
void NotificationUIManagerAndroid::Add(const Notification& notification,
Profile* profile) {
// TODO(peter): Implement the NotificationUIManagerAndroid class.
NOTIMPLEMENTED();
}
bool NotificationUIManagerAndroid::Update(const Notification& notification,
Profile* profile) {
return false;
}
const Notification* NotificationUIManagerAndroid::FindById(
const std::string& notification_id) const {
return 0;
}
bool NotificationUIManagerAndroid::CancelById(
const std::string& notification_id) {
return false;
}
std::set<std::string>
NotificationUIManagerAndroid::GetAllIdsByProfileAndSourceOrigin(
Profile* profile,
const GURL& source) {
return std::set<std::string>();
}
bool NotificationUIManagerAndroid::CancelAllBySourceOrigin(
const GURL& source_origin) {
return false;
}
bool NotificationUIManagerAndroid::CancelAllByProfile(Profile* profile) {
return false;
}
void NotificationUIManagerAndroid::CancelAll() {
}
| 26.762712
| 80
| 0.746042
|
Fusion-Rom
|
5a0d965c55380224342d8d28d30040184eb17c93
| 13,154
|
cpp
|
C++
|
src/learning/learning.cpp
|
raphaelsulzer/mesh-tools
|
73150bec58813e2b9b750205807002a1c3f18884
|
[
"MIT"
] | 1
|
2022-02-24T03:39:05.000Z
|
2022-02-24T03:39:05.000Z
|
src/learning/learning.cpp
|
raphaelsulzer/mesh-tools
|
73150bec58813e2b9b750205807002a1c3f18884
|
[
"MIT"
] | 1
|
2022-02-24T06:59:59.000Z
|
2022-03-04T01:25:09.000Z
|
src/learning/learning.cpp
|
raphaelsulzer/mesh-tools
|
73150bec58813e2b9b750205807002a1c3f18884
|
[
"MIT"
] | null | null | null |
#include <base/cgal_typedefs.h>
#include <IO/fileIO.h>
#include <util/helper.h>
#include <util/geometricOperations.h>
#include <processing/tetIntersection.h>
#include <processing/rayTracingTet.h>
#include <processing/meshProcessing.h>
#include <processing/graphCut.h>
#include <processing/edgeManifoldness.h>
#include <processing/pointSetProcessing.h>
#include <processing/meshProcessing.h>
#include <learning/learning.h>
#include <learning/learningMath.h>
#include <learning/learningRayTracing.h>
#include <learning/learningIO.h>
#include <CGAL/point_generators_3.h>
#include <CGAL/Random.h>
#include <CGAL/boost/graph/convert_nef_polyhedron_to_polygon_mesh.h>
#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>
#include <boost/foreach.hpp>
#include <CGAL/Polygon_mesh_processing/distance.h>
#include <CGAL/polygon_mesh_processing.h>
#include <CGAL/optimal_bounding_box.h>
#include <CGAL/Side_of_triangle_mesh.h>
#include <util/helper.h>
#include <random>
using namespace std;
int labelObjectWithOpenGroundTruth(dirHolder dir, dataHolder& data, int sampling_points){
auto start = std::chrono::high_resolution_clock::now();
if(data.gt_poly.size_of_vertices() == 0){
cout << "\nERROR: you need to load a ground truth polygon (with -g) for scanning it" << endl;
return 1;
}
assert(sampling_points > 0);
cout << "\nLabelling cells with open ground truth and ray tracing..." << endl;
cout << "\t-sample " << sampling_points << endl;
// Initialize the point-in-polyhedron tester
// Construct AABB tree with a KdTree
SurfaceMesh smesh;
CGAL::copy_face_graph(data.gt_poly, smesh);
CGAL::Polygon_mesh_processing::remove_connected_components_of_negligible_size(smesh);
// dir.suffix = "_repaired_mesh";
// exportOFF(dir,smesh);
// cout << "gt centroid: " << data.gt_centroid << endl;
// Tree tree(faces(smesh).first, faces(smesh).second, smesh);
vector<face_descriptor> fds;
for(face_descriptor fd : faces(smesh)){
if(!CGAL::Polygon_mesh_processing::is_degenerate_triangle_face(fd,smesh))
fds.push_back(fd);
}
Tree tree(fds.begin(), fds.end(), smesh);
tree.accelerate_distance_queries();
// Polyhedron poly;
// CGAL::copy_face_graph(data.sm_obb, poly);
// Tree bb_tree(faces(data.sm_obb).first, faces(data.sm_obb).second, data.sm_obb);
// const Point_inside inside_bb(data.sm_obb);
int icount = 0;
int ncount = 0;
Delaunay::All_cells_iterator aci;
// random sampler
CGAL::Random random(42);
vector<Point> sampled_points;
double iperc;
double operc;
int newCellIndex = 0;
vector<Point> all_sampled_points;
vector<vertex_info> all_sampled_infos;
int progress = 0;
int total = data.Dt.number_of_cells();
for(aci = data.Dt.all_cells_begin(); aci != data.Dt.all_cells_end(); aci++){
// cout << progress++ << endl;
// if((progress*100/total) % 10 == 0 && (++progress*100/total) % 10 != 0)
// cout << progress << "/" << total << endl;
aci->info().global_idx=newCellIndex++;
if(data.Dt.is_infinite(aci)){
aci->info().gc_label = 1; // more likely that it is outside
aci->info().inside_score = 0.0;
aci->info().outside_score = 1.0;
continue;
}
// sample points inside the tet and check if they are inside or outside
double cinside=0;
double coutside=0;
Tetrahedron current_tet = data.Dt.tetrahedron(aci);
CGAL::Random_points_in_tetrahedron_3<Point> tet_point_sampler(current_tet, random);
sampled_points.clear();
CGAL::cpp11::copy_n(tet_point_sampler, sampling_points, std::back_inserter(sampled_points));
for(auto const& sampled_point : sampled_points){
// all_sampled_points.push_back(sampled_point);
// vertex_info vi;
// if(inside_bb(sampled_point) == CGAL::ON_UNBOUNDED_SIDE){
// vi.color = CGAL::violet();
// all_sampled_infos.push_back(vi);
// cinside+=1.0;
// }
// else{
Segment seg(sampled_point,data.gt_centroid);
int n = tree.number_of_intersected_primitives(seg);
// cout << "number of intersected primitives: " << n << endl;
if(n % 2){
cinside+=1.0;
// vi.color = CGAL::red();
// all_sampled_infos.push_back(vi);
}
else{
coutside+=1.0;
// vi.color = CGAL::blue();
// all_sampled_infos.push_back(vi);
}
// if(n == 0)
// vi.color = CGAL::yellow();
// else if(n == 1)
// vi.color = CGAL::green();
// else if(n == 2)
// vi.color = CGAL::blue();
// else if(n == 3)
// vi.color = CGAL::red();
// else
// vi.color = CGAL::black();
// all_sampled_infos.push_back(vi);
// }
}
iperc = cinside/(cinside+coutside);
operc = coutside/(cinside+coutside);
aci->info().outside_score = operc;
aci->info().inside_score = iperc;
// aci->info().gt_outside = operc;
// aci->info().gt_inside = iperc;
if(operc>iperc){
ncount++;
// aci->info().gc_label = 1;
}
else{
icount++;
// aci->info().gc_label = 0;
}
}
// dir.suffix = "_sampled";
// exportOptions eo;
// eo.color = true;
// exportPLY(dir,all_sampled_points,all_sampled_infos,eo);
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<std::chrono::seconds>(stop - start);
cout << "\t-Labelled object with " << icount << "/" << ncount << "(inside/outside) = " << icount+ncount << " cells" << endl;
cout << "\t-in "<<duration.count() << "s" << endl;
if(icount == 0 || ncount == 0){
cout << "\nERROR: cells could not be labelled" << endl;
return 1;
}
return 0;
}
int labelObjectWithClosedGroundTruth(dirHolder dir, dataHolder& data, int sampling_points){
auto start = std::chrono::high_resolution_clock::now();
if(data.gt_poly.size_of_vertices() == 0){
cout << "\nERROR: you need to load a ground truth polygon (with -g) for scanning it" << endl;
return 1;
}
if(!data.gt_poly.is_closed()){
cout << "\nERROR: ground truth is not closed" << endl;
return 1;
}
assert(sampling_points > 0);
cout << "\nLabelling cells by sampling points inside cells..." << endl;
cout << "\t-sample " << sampling_points << endl;
// Initialize the point-in-polyhedron tester
// Construct AABB tree with a KdTree
SurfaceMesh smesh;
CGAL::copy_face_graph(data.gt_poly, smesh);
Tree tree(faces(smesh).first, faces(smesh).second, smesh);
// Tree tree(faces(data.gt_poly).first, faces(data.gt_poly).second, data.gt_poly);
tree.accelerate_distance_queries();
// Initialize the point-in-polyhedron tester
const Point_inside inside_tester(tree);
// Polyhedron poly;
// CGAL::copy_face_graph(data.sm_obb, poly);
//// Tree bb_tree(faces(data.sm_obb).first, faces(data.sm_obb).second, data.sm_obb);
// const Point_inside inside_bb(poly);
int icount = 0;
int ncount = 0;
Delaunay::All_cells_iterator aci;
// random sampler
CGAL::Random random(42);
vector<Point> sampled_points;
double iperc;
double operc;
int newCellIndex = 0;
vector<Point> all_sampled_points;
vector<vertex_info> all_sampled_infos;
for(aci = data.Dt.all_cells_begin(); aci != data.Dt.all_cells_end(); aci++){
aci->info().global_idx=newCellIndex++;
if(data.Dt.is_infinite(aci)){
aci->info().gc_label = 1; // more likely that it is outside
aci->info().inside_score = 0.0;
aci->info().outside_score = 1.0;
continue;
}
// sample points inside the tet and check if they are inside or outside
double cinside=0;
double coutside=0;
Tetrahedron current_tet = data.Dt.tetrahedron(aci);
CGAL::Random_points_in_tetrahedron_3<Point> tet_point_sampler(current_tet, random);
sampled_points.clear();
CGAL::cpp11::copy_n(tet_point_sampler, sampling_points, std::back_inserter(sampled_points));
for(auto const& sampled_point : sampled_points){
// all_sampled_points.push_back(sampled_point);
// vertex_info vi;
//// cout<<"\t check point "<< pcount++ <<"/"<<sampling_points<<endl;
// if(inside_bb(sampled_point) != CGAL::ON_BOUNDED_SIDE){
// vi.color = CGAL::green();
// all_sampled_infos.push_back(vi);
// coutside+=1.0;
// continue;
// }
if(inside_tester(sampled_point) == CGAL::ON_BOUNDED_SIDE){
cinside+=1.0;
// vi.color = CGAL::red();
// all_sampled_infos.push_back(vi);
}
else{
coutside+=1.0;
// vi.color = CGAL::blue();
// all_sampled_infos.push_back(vi);
}
}
iperc = cinside/(cinside+coutside);
operc = coutside/(cinside+coutside);
aci->info().outside_score = operc;
aci->info().inside_score = iperc;
if(operc>iperc){
ncount++;
// aci->info().gc_label = 1;
}
else{
icount++;
// aci->info().gc_label = 0;
}
}
// dir.suffix = "_sampled";
// exportOptions eo;
// eo.color = true;
// exportPLY(dir,all_sampled_points,all_sampled_infos,eo);
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<std::chrono::seconds>(stop - start);
cout << "\t-Labelled object with " << icount << "/" << ncount << "(inside/outside) = " << icount+ncount << " cells" << endl;
cout << "\t-in "<<duration.count() << "s" << endl;
if(icount == 0 || ncount == 0){
cout << "\nERROR: cells could not be labelled" << endl;
return 1;
}
return 0;
}
#ifdef RECONBENCH
int labelObjectWithImplicit(dataHolder& data, int sampling_points){
auto start = std::chrono::high_resolution_clock::now();
assert(sampling_points > 0);
cout << "\nLabelling cells by sampling points inside cells: " << endl;
cout << "\t-sample " << sampling_points << endl;
int icount = 0;
int ncount = 0;
Delaunay::All_cells_iterator aci;
// random sampler
CGAL::Random random(42);
vector<Point> sampled_points;
double iperc;
double operc;
int newCellIndex = 0;
for(aci = data.Dt.all_cells_begin(); aci != data.Dt.all_cells_end(); aci++){
if(data.Dt.is_infinite(aci)){
aci->info().gc_label = 1; // more likely that it is outside
aci->info().inside_score = 0.2;
aci->info().outside_score = 0.8;
aci->info().global_idx=newCellIndex++;
continue;
}
aci->info().global_idx=newCellIndex++;
// sample points inside the tet and check if they are inside or outside
double cinside=0;
double coutside=0;
Tetrahedron current_tet = data.Dt.tetrahedron(aci);
CGAL::Random_points_in_tetrahedron_3<Point> tet_point_sampler(current_tet, random);
sampled_points.clear();
CGAL::cpp11::copy_n(tet_point_sampler, sampling_points, std::back_inserter(sampled_points));
for(auto const& sampled_point : sampled_points){
auto sampled_point_rb = point2Vector3RB(sampled_point);
if(data.implicit->function(sampled_point_rb) <= 0.0){
cinside+=1.0;
// Color col = CGAL::make_array((unsigned char)255, (unsigned char)0, (unsigned char)0);
// vertex_info vi;
// vi.color = col;
// all_sampled_infos.push_back(vi);
}
else{
coutside+=1.0;
// Color col = CGAL::make_array((unsigned char)0, (unsigned char)0, (unsigned char)255);
// vertex_info vi;
// vi.color = col;
// all_sampled_infos.push_back(vi);
}
}
iperc = cinside/(cinside+coutside);
operc = coutside/(cinside+coutside);
aci->info().outside_score = operc;
aci->info().inside_score = iperc;
if(operc>iperc){
ncount++;
aci->info().gc_label = 1;
}
else{
icount++;
aci->info().gc_label = 0;
}
}
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<std::chrono::seconds>(stop - start);
cout << "\t-Labelled object with " << icount << "/" << ncount << "(inside/outside) = " << icount+ncount << " cells" << endl;
cout << "\t-in "<<duration.count() << "s" << endl;
if(icount == 0 || ncount == 0)
return 0;
return 1;
}
#endif
| 34.344648
| 128
| 0.592443
|
raphaelsulzer
|
5a110d9ca6988282ec336215a807428ea875e35f
| 850
|
hpp
|
C++
|
pomdog/experimental/gui/debug_navigator.hpp
|
mogemimi/pomdog
|
6dc6244d018f70d42e61c6118535cf94a9ee0618
|
[
"MIT"
] | 163
|
2015-03-16T08:42:32.000Z
|
2022-01-11T21:40:22.000Z
|
pomdog/experimental/gui/debug_navigator.hpp
|
mogemimi/pomdog
|
6dc6244d018f70d42e61c6118535cf94a9ee0618
|
[
"MIT"
] | 17
|
2015-04-12T20:57:50.000Z
|
2020-10-10T10:51:45.000Z
|
pomdog/experimental/gui/debug_navigator.hpp
|
mogemimi/pomdog
|
6dc6244d018f70d42e61c6118535cf94a9ee0618
|
[
"MIT"
] | 21
|
2015-04-12T20:45:11.000Z
|
2022-01-14T20:50:16.000Z
|
// Copyright mogemimi. Distributed under the MIT license.
#pragma once
#include "pomdog/basic/conditional_compilation.hpp"
#include "pomdog/chrono/duration.hpp"
#include "pomdog/chrono/game_clock.hpp"
#include "pomdog/experimental/gui/widget.hpp"
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN
#include <deque>
#include <memory>
#include <string>
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END
namespace pomdog::gui {
class DebugNavigator final : public Widget {
public:
DebugNavigator(
const std::shared_ptr<UIEventDispatcher>& dispatcher,
const std::shared_ptr<GameClock>& clock);
void Draw(DrawingContext& drawingContext) override;
private:
std::shared_ptr<GameClock> clock;
std::deque<float> frameRates;
Duration duration;
std::string frameRateString;
};
} // namespace pomdog::gui
| 25
| 61
| 0.770588
|
mogemimi
|
5a12ddf110bcc68350b8090456384324420b49ae
| 50,337
|
cpp
|
C++
|
data/cpp/7fa0c21b51343873f0140b810c2823ea_CraftingSessionHelper.cpp
|
maxim5/code-inspector
|
14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1
|
[
"Apache-2.0"
] | 5
|
2018-01-03T06:43:07.000Z
|
2020-07-30T13:15:29.000Z
|
data/cpp/7fa0c21b51343873f0140b810c2823ea_CraftingSessionHelper.cpp
|
maxim5/code-inspector
|
14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1
|
[
"Apache-2.0"
] | null | null | null |
data/cpp/7fa0c21b51343873f0140b810c2823ea_CraftingSessionHelper.cpp
|
maxim5/code-inspector
|
14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1
|
[
"Apache-2.0"
] | 2
|
2019-11-04T02:54:49.000Z
|
2020-04-24T17:50:46.000Z
|
/*
---------------------------------------------------------------------------------------
This source file is part of SWG:ANH (Star Wars Galaxies - A New Hope - Server Emulator)
For more information, visit http://www.swganh.com
Copyright (c) 2006 - 2010 The SWG:ANH Team
---------------------------------------------------------------------------------------
Use of this source code is governed by the GPL v3 license that can be found
in the COPYING file or at http://www.gnu.org/licenses/gpl-3.0.html
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 "CraftingSession.h"
#include "CraftBatch.h"
#include "CraftingSessionFactory.h"
#include "CraftingStation.h"
#include "CraftingTool.h"
#include "Datapad.h"
#include "DraftSchematic.h"
#include "DraftSlot.h"
#include "FactoryCrate.h"
#include "Inventory.h"
#include "Item.h"
#include "ManufacturingSchematic.h"
#include "ObjectControllerOpcodes.h"
#include "ObjectFactory.h"
#include "PlayerObject.h"
#include "ResourceContainer.h"
#include "ResourceManager.h"
#include "SchematicManager.h"
#include "WorldManager.h"
#include "nonPersistantObjectFactory.h"
#include "MessageLib/MessageLib.h"
#include "DatabaseManager/Database.h"
#include "DatabaseManager/DatabaseCallback.h"
#include "DatabaseManager/DatabaseResult.h"
#include "DatabaseManager/DataBinding.h"
#include "Utils/clock.h"
#include <boost/lexical_cast.hpp>
//=============================================================================
//
// Adjust an Itemstacks amount
// delete the stack if emptied
bool CraftingSession::AdjustComponentStack(Item* item, uint32 uses)
{
//is this a stack ???
if(item->hasAttribute("stacksize"))
{
//alter stacksize, delete if necessary
uint32 stackSize;
stackSize = item->getAttribute<uint32>("stacksize");
if(stackSize > uses)
{
//just adjust the stacks size
item->setAttributeIncDB("stacksize",boost::lexical_cast<std::string>(stackSize-uses));
}
if(stackSize < uses)
{
return false;
}
if(stackSize == uses)
{
//just adjust the stacks size
item->setAttributeIncDB("stacksize",boost::lexical_cast<std::string>(stackSize-uses));
}
}
else
//no stack, just a singular item
if(uses == 1)
{
DLOG(INFO) << "CraftingSession::AdjustComponentStack no stacksize attribute set stack to 1";
}
else
{
DLOG(INFO) << "CraftingSession::AdjustComponentStack no stacksize attribute return false";
return false;
}
return true;
}
//=============================================================================
//
// Adjust a factory crates amount
//
uint32 CraftingSession::AdjustFactoryCrate(FactoryCrate* crate, uint32 uses)
{
uint32 crateSize = 1;
uint32 stackSize = 1;
if(!crate->hasAttribute("factory_count"))
{
return 0;
}
crateSize = crate->getAttribute<uint32>("factory_count");
//============================================================================
//calculate the amount of stacks we need to remove from the crate
//
if(!crate->getLinkedObject()->hasAttribute("stacksize"))
{
stackSize = 1;
}
uint32 takeOut = 0;
uint32 amount = 0;
while(amount < uses)
{
takeOut++;
amount+= stackSize;
}
//============================================================================
//remove *amount* stacks from the crate
//
if(takeOut>crateSize)
{
DLOG(INFO) << "CraftingSession::AdjustFactoryCrate :: Crate does not have enough content";
return 0;
}
//only take away whole stacks
crate->decreaseContent(takeOut);
//we might need to send these updates to all players watching the parentcontainer
gMessageLib->sendUpdateCrateContent(crate,mOwner);
return takeOut;
}
//=============================================================================
//
// returns the serial of either a crate or component
// thats easy for stacks and a little more involved for factory crates
//
BString CraftingSession::ComponentGetSerial(Item* component)
{
BString componentSerial = "";
FactoryCrate* fC = dynamic_cast<FactoryCrate*>(component);
if(fC)
{
if(fC->getLinkedObject()->hasAttribute("serial"))
componentSerial = fC->getLinkedObject()->getAttribute<std::string>("serial").c_str();
return componentSerial;
}
if(component->hasAttribute("serial"))
componentSerial = component->getAttribute<std::string>("serial").c_str();
return componentSerial;
}
//=============================================================================
//
// returns the amount of the item useable
// thats easy for stacks and a little more involved for factory crates
// under the presumption that crates can hold stackable items, too
uint32 CraftingSession::getComponentOffer(Item* component, uint32 needed)
{
uint32 crateSize = 0;
mAsyncStackSize = 1;
FactoryCrate* fC = dynamic_cast<FactoryCrate*>(component);
if(fC)
{
if(!fC->hasAttribute("factory_count"))
{
DLOG(INFO) << "CraftingSession::prepareComponent crate without factory_count attribute";
return 0;
}
crateSize = fC->getAttribute<uint32>("factory_count");
mAsyncStackSize = 1;
if(!fC->getLinkedObject()->hasAttribute("stacksize"))
{
if(needed> crateSize)
return crateSize;
else
return needed;
}
mAsyncStackSize = fC->getLinkedObject()->getAttribute<uint32>("stacksize");
if(needed> (mAsyncStackSize*crateSize))
return mAsyncStackSize*crateSize;
else
return needed;
}
if(!component->hasAttribute("stacksize"))
{
return 1;
}
mAsyncStackSize = component->getAttribute<uint32>("stacksize");
if(needed> mAsyncStackSize)
return mAsyncStackSize;
else
return needed;
}
//=============================================================================
//
// preparing the component means creating copies for every slot of a stack and
// linking them to the slot so we can deal with deleted / traded crates / items when we empty the slot
// delete it out of the inventory/container if necessary
// otherwise adjust the stacksize
bool CraftingSession::prepareComponent(Item* component, uint32 needed, ManufactureSlot* manSlot)
{
FactoryCrate* fC = dynamic_cast<FactoryCrate*>(component);
if(fC)
{
uint32 amount = AdjustFactoryCrate(fC, needed);
DLOG(INFO) << "CraftingSession::prepareComponent FactoryCrate take " << amount;
//TODO - added stacks shouldnt have more items than maximally possible - needed is the amount needed for the slot
// that might be bigger than the max stack size
//create the new item - link it to the slot
mAsyncComponentAmount = needed;
mAsyncManSlot = manSlot;
//make sure we request the right amount of stacks
for(uint8 i = 0; i<amount; i++)
gObjectFactory->requestNewClonedItem(this,fC->getLinkedObject()->getId(),mManufacturingSchematic->getId());
// if its now empty remove it out of the inventory so we cant use it several times
// and destroy it while were at it
uint32 crateSize = fC->getAttribute<uint32>("factory_count");
if(!crateSize)
{
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(fC->getParentId()));
if(!tO)
{
assert(false);
return 0;
}
//just delete it
gMessageLib->sendDestroyObject(fC->getId(),mOwner);
gObjectFactory->deleteObjectFromDB(fC->getId());
tO->deleteObject(fC);
}
//dont send result - its a callback
return false;
}
//no stacksize or crate - do not bother with temporaries
if(!component->hasAttribute("stacksize"))
{
// remove it out of the inventory so we cant use it several times
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(component->getParentId()));
assert(tO && "CraftingSession::prepareComponent :: cant get parent");
tO->removeObject(component);
//leave parent_id untouched - we might need to readd it to the container
gMessageLib->sendContainmentMessage(component->getId(),mManufacturingSchematic->getId(),0xffffffff,mOwner);
//send result directly we dont have a callback
return true;
}
//only pure stacks remain
AdjustComponentStack(component, needed);
//create the new item - link it to the slot
mAsyncComponentAmount = needed;
mAsyncManSlot = manSlot;
gObjectFactory->requestNewClonedItem(this,component->getId(),mManufacturingSchematic->getId());
//delete the stack if empty
uint32 stackSize = component->getAttribute<uint32>("stacksize");
if(!stackSize)
{
//remove the item out of its container
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(component->getParentId()));
if(!tO)
{
assert(false);
return false;
}
//just delete it
tO->removeObject(component);
gWorldManager->destroyObject(component);
}
//dont send result - its a callback
return false;
}
//=============================================================================
//
// a component gets put into a manufacturing slot
//
void CraftingSession::handleFillSlotComponent(uint64 componentId,uint32 slotId,uint32 unknown,uint8 counter)
{
ManufactureSlot* manSlot = mManufacturingSchematic->getManufactureSlots()->at(slotId);
Item* component = dynamic_cast<Item*>(gWorldManager->getObjectById(componentId));
//remove the component out of its container and attach it to the man schematic
//alternatively remove the amount necessary from a stack / crate
uint32 existingAmount = 0;
uint32 totalNeededAmount = manSlot->mDraftSlot->getNecessaryAmount();
BString componentSerial = "";
BString filledSerial = "";
componentSerial = ComponentGetSerial(component);
mAsyncSmallUpdate = false;
if((!component) || (!manSlot))
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Ingredient_Not_In_Inventory,counter,mOwner);
return;
}
// get the amount of already filled components
FilledResources::iterator filledResIt = manSlot->mFilledResources.begin();
while(filledResIt != manSlot->mFilledResources.end())
{
existingAmount += (*filledResIt).second;
++filledResIt;
}
if(existingAmount)
mAsyncSmallUpdate = true;
// update the needed amount
totalNeededAmount -= existingAmount;
// fail if its already complete
if(!totalNeededAmount)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Slot_Already_Full,counter,mOwner);
return;
}
//mmh somehow some components are added several times
if(component->getParentId() == mManufacturingSchematic->getId())
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Ingredient_Not_In_Inventory,counter,mOwner);
return;
}
//ok we probably have a deal here - if its a crate we need to get a stack out - or more ?
// see how much this component stack /crate has to offer
mAsyncComponentAmount = getComponentOffer(component,totalNeededAmount);
if(!mAsyncComponentAmount)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Internal_Invalid_Ingredient_Size,counter,mOwner);
return;
}
//============================================================0
// deal - get the new items
// the callback will hit the handleObjectReady in craftingsession.cpp
if(!prepareComponent(component, mAsyncComponentAmount, manSlot))
{
mAsyncSlotId = slotId;
mAsyncCounter = counter;
// false means we use the callback.
return;
}
component->setParentId(mManufacturingSchematic->getId());
//it wasnt a crate / stack - process right here
//add the necessary information to the slot
manSlot->mUsedComponentStacks.push_back(std::make_pair(component,mAsyncComponentAmount));
manSlot->addComponenttoSlot(component->getId(),mAsyncComponentAmount,manSlot->mDraftSlot->getType());
// update the slot total resource amount
manSlot->setFilledAmount(manSlot->getFilledAmount()+mAsyncComponentAmount);
if(manSlot->getFilledAmount() == manSlot->mDraftSlot->getNecessaryAmount())
{
// update the total count of filled slots
mManufacturingSchematic->addFilledSlot();
gMessageLib->sendUpdateFilledManufactureSlots(mManufacturingSchematic,mOwner);
}
// update the slot contents, send all slots on first fill
// we need to make sure we only update lists with changes, so the lists dont desynchronize!
if(!mFirstFill)
{
mFirstFill = true;
gMessageLib->sendDeltasMSCO_7(mManufacturingSchematic,mOwner);
}
else if(mAsyncSmallUpdate == true)
{
gMessageLib->sendManufactureSlotUpdateSmall(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
else
{
gMessageLib->sendManufactureSlotUpdate(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
// done
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_None,counter,mOwner);
}
//=============================================================================
//
// an amount of resource gets put into a manufacturing slot
//
void CraftingSession::handleFillSlotResource(uint64 resContainerId,uint32 slotId,uint32 unknown,uint8 counter)
{
// update resource container
ResourceContainer* resContainer = dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(resContainerId));
ManufactureSlot* manSlot = mManufacturingSchematic->getManufactureSlots()->at(slotId);
FilledResources::iterator filledResIt = manSlot->mFilledResources.begin();
//bool resourceBool = false;
bool smallupdate = false;
if(!resContainer)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Ingredient_Not_In_Inventory,counter,mOwner);
}
if(!manSlot)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Invalid_Slot,counter,mOwner);
}
uint32 availableAmount = resContainer->getAmount();
uint32 totalNeededAmount = manSlot->mDraftSlot->getNecessaryAmount();
uint32 existingAmount = 0;
uint64 containerResId = resContainer->getResourceId();
// see if something is filled already
existingAmount = manSlot->getFilledAmount();
// update the needed amount
totalNeededAmount -= existingAmount;
// fail if its already complete
if(!totalNeededAmount)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Slot_Already_Full,counter,mOwner);
return;
}
//check whether we have the same resource - no go if its different - check for the slot being empty though
if(manSlot->getResourceId() && (containerResId != manSlot->getResourceId()))
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Internal_Invalid_Ingredient,counter,mOwner);
return;
}
// see how much this container has to offer
// slot completely filled
if(availableAmount >= totalNeededAmount)
{
// add to the filled resources
filledResIt = manSlot->mFilledResources.begin();
while(filledResIt != manSlot->mFilledResources.end())
{
// already got something of that type filled
if(containerResId == (*filledResIt).first)
{
//hark in live the same resource gets added to a second slot
manSlot->mFilledResources.push_back(std::make_pair(containerResId,totalNeededAmount));
filledResIt = manSlot->mFilledResources.begin();
manSlot->setFilledType(DST_Resource);//4 resource has been filled
smallupdate = true;
break;
}
++filledResIt;
}
// nothing of that resource filled, add a new entry
if(filledResIt == manSlot->mFilledResources.end())
{
//resourceBool = true;
// only allow one unique type
if(manSlot->mFilledResources.empty())
{
manSlot->mFilledResources.push_back(std::make_pair(containerResId,totalNeededAmount));
manSlot->setFilledType(DST_Resource);
manSlot->mFilledIndicatorChange = true;
}
else
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Bad_Resource_Chosen,counter,mOwner);
return;
}
}
// update the container amount
uint32 newContainerAmount = availableAmount - totalNeededAmount;
// destroy if its empty
if(!newContainerAmount)
{
//now destroy it client side
gMessageLib->sendDestroyObject(resContainerId,mOwner);
gObjectFactory->deleteObjectFromDB(resContainer);
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(resContainer->getParentId()));
tO->deleteObject(resContainer);
}
// update it
else
{
resContainer->setAmount(newContainerAmount);
gMessageLib->sendResourceContainerUpdateAmount(resContainer,mOwner);
mDatabase->executeSqlAsync(NULL,NULL,"UPDATE resource_containers SET amount=%u WHERE id=%"PRIu64"",newContainerAmount,resContainer->getId());
}
// update the slot total resource amount
manSlot->setFilledAmount(manSlot->mDraftSlot->getNecessaryAmount());
// update the total count of filled slots
mManufacturingSchematic->addFilledSlot();
gMessageLib->sendUpdateFilledManufactureSlots(mManufacturingSchematic,mOwner);
}
// got only a bit
else
{
// add to the filled resources
uint64 containerResId = resContainer->getResourceId();
filledResIt = manSlot->mFilledResources.begin();
while(filledResIt != manSlot->mFilledResources.end())
{
// already got something of that type filled
if(containerResId == (*filledResIt).first)
{
//(*filledResIt).second += availableAmount;
manSlot->mFilledResources.push_back(std::make_pair(containerResId,availableAmount));
filledResIt = manSlot->mFilledResources.begin();
manSlot->setFilledType(DST_Resource);
smallupdate = true;
break;
}
++filledResIt;
}
// nothing of that resource filled, add a new entry
if(filledResIt == manSlot->mFilledResources.end())
{
// only allow one unique type
if(manSlot->mFilledResources.empty())
{
manSlot->mFilledResources.push_back(std::make_pair(containerResId,availableAmount));
manSlot->setFilledType(DST_Resource);
}
else
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Bad_Resource_Chosen,counter,mOwner);
return;
}
}
// destroy the container as its empty now
gMessageLib->sendDestroyObject(resContainerId,mOwner);
gObjectFactory->deleteObjectFromDB(resContainer);
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(resContainer->getParentId()));
tO->deleteObject(resContainer);
// update the slot total resource amount
manSlot->mFilled += availableAmount;
}
// update the slot contents, send all slots on first fill
// we need to make sure we only update lists with changes, so the lists dont desynchronize!
if(!mFirstFill)
{
mFirstFill = true;
gMessageLib->sendDeltasMSCO_7(mManufacturingSchematic,mOwner);
}
else if(smallupdate == true)
{
gMessageLib->sendManufactureSlotUpdateSmall(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
else
{
gMessageLib->sendManufactureSlotUpdate(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
// done
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_None,counter,mOwner);
}
//=============================================================================
//
// an amount of resource gets put into a manufacturing slot
//
void CraftingSession::handleFillSlotResourceRewrite(uint64 resContainerId,uint32 slotId,uint32 unknown,uint8 counter)
{
// update resource container
ResourceContainer* resContainer = dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(resContainerId));
ManufactureSlot* manSlot = mManufacturingSchematic->getManufactureSlots()->at(slotId);
//bool resourceBool = false;
bool smallupdate = false;
if(!resContainer)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Ingredient_Not_In_Inventory,counter,mOwner);
}
if(!manSlot)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Invalid_Slot,counter,mOwner);
}
uint32 availableAmount = resContainer->getAmount();
uint32 totalNeededAmount = manSlot->mDraftSlot->getNecessaryAmount();
uint32 existingAmount = 0;
uint64 containerResId = resContainer->getResourceId();
// see if something is filled already
existingAmount = manSlot->getFilledAmount();
//check whether we have the same resource - if it's different replace the current resource with the new one
if(manSlot->getResourceId() && (containerResId != manSlot->getResourceId()))
{
// remove the old resource from the slot and input the new one.
emptySlot(slotId, manSlot, manSlot->getResourceId());
//gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Internal_Invalid_Ingredient,counter,mOwner);
//return;
}
else
{
// update the needed amount
totalNeededAmount -= existingAmount;
}
// fail if its already complete
if(!totalNeededAmount)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Slot_Already_Full,counter,mOwner);
return;
}
uint32 takeAmount = 0;
if(availableAmount >= totalNeededAmount)
{
takeAmount = totalNeededAmount;
}
else
{
takeAmount = availableAmount;
}
// add it to the slot get the update type
smallupdate = manSlot->addResourcetoSlot(containerResId,takeAmount,manSlot->mDraftSlot->getType());
// update the container amount
uint32 newContainerAmount = availableAmount - takeAmount;
updateResourceContainer(resContainer->getId(),newContainerAmount);
// update the slot total resource amount
manSlot->setFilledAmount(manSlot->getFilledAmount()+takeAmount);
if(manSlot->getFilledAmount() == manSlot->mDraftSlot->getNecessaryAmount())
{
// update the total count of filled slots
mManufacturingSchematic->addFilledSlot();
gMessageLib->sendUpdateFilledManufactureSlots(mManufacturingSchematic,mOwner);
}
// update the slot contents, send all slots on first fill
// we need to make sure we only update lists with changes, so the lists dont desynchronize!
if(!mFirstFill)
{
mFirstFill = true;
gMessageLib->sendDeltasMSCO_7(mManufacturingSchematic,mOwner);
}
else if(smallupdate == true)
{
gMessageLib->sendManufactureSlotUpdateSmall(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
else
{
gMessageLib->sendManufactureSlotUpdate(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
// done
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_None,counter,mOwner);
}
//=============================================================================
//
// filled components get returned to the inventory
//
//
void CraftingSession::bagComponents(ManufactureSlot* manSlot,uint64 containerId)
{
//add the components back to the inventory (!!!)
manSlot->setFilledType(DST_Empty);
//put them into the inventory no matter what - only alternative might be a crafting stations hopper at one point ??
Inventory* inventory = dynamic_cast<Inventory*>(mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory));
FilledComponent::iterator compIt = manSlot->mUsedComponentStacks.begin();
while(compIt != manSlot->mUsedComponentStacks.end())
{
Item* filledComponent = dynamic_cast<Item*>((*compIt).first);
if(!filledComponent)
{
return;
}
inventory->addObject(filledComponent);
gMessageLib->sendContainmentMessage(filledComponent->getId(),inventory->getId(),0xffffffff,mOwner);
filledComponent->setParentIdIncDB(inventory->getId());
compIt = manSlot->mUsedComponentStacks.erase(compIt);
continue;
}
manSlot->mUsedComponentStacks.clear();
manSlot->mFilledResources.clear();
}
void CraftingSession::destroyComponents()
{
uint8 amount = mManufacturingSchematic->getManufactureSlots()->size();
for (uint8 i = 0; i < amount; i++)
{
//iterate through our manslots which contain components
ManufactureSlot* manSlot = mManufacturingSchematic->getManufactureSlots()->at(i);
manSlot->setFilledType(DST_Empty);
FilledComponent::iterator compIt = manSlot->mUsedComponentStacks.begin();
while(compIt != manSlot->mUsedComponentStacks.end())
{
Item* filledComponent = dynamic_cast<Item*>((*compIt).first);
if(!filledComponent)
{
return;
}
gObjectFactory->deleteObjectFromDB(filledComponent);
gMessageLib->sendDestroyObject(filledComponent->getId(),mOwner);
gWorldManager->destroyObject(filledComponent);
compIt = manSlot->mUsedComponentStacks.erase(compIt);
continue;
}
manSlot->mUsedComponentStacks.clear();
manSlot->mFilledResources.clear();
}
}
//=============================================================================
//
// filled resources get returned to the inventory
//
void CraftingSession::bagResource(ManufactureSlot* manSlot,uint64 containerId)
{
//iterates through the slots filled resources
//respectively create a new one if necessary
//TODO : what happens if the container is full ?
FilledResources::iterator resIt = manSlot->mFilledResources.begin();
manSlot->setFilledType(DST_Empty);
while(resIt != manSlot->mFilledResources.end())
{
uint32 amount = (*resIt).second;
// see if we can add it to an existing container
ObjectIDList* invObjects = dynamic_cast<Inventory*>(mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory))->getObjects();
ObjectIDList::iterator listIt = invObjects->begin();
bool foundSameType = false;
while(listIt != invObjects->end())
{
// we are looking for resource containers
ResourceContainer* resCont = dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById((*listIt)));
if(resCont)
{
uint32 targetAmount = resCont->getAmount();
uint32 maxAmount = resCont->getMaxAmount();
uint32 newAmount;
if((resCont->getResourceId() == (*resIt).first) && (targetAmount < maxAmount))
{
foundSameType = true;
newAmount = targetAmount + amount;
if(newAmount <= maxAmount)
{
// update target container
resCont->setAmount(newAmount);
gMessageLib->sendResourceContainerUpdateAmount(resCont,mOwner);
gWorldManager->getDatabase()->executeSqlAsync(NULL,NULL,"UPDATE resource_containers SET amount=%u WHERE id=%"PRIu64"",newAmount,resCont->getId());
}
// target container full, put in what fits, create a new one
else if(newAmount > maxAmount)
{
uint32 selectedNewAmount = newAmount - maxAmount;
resCont->setAmount(maxAmount);
gMessageLib->sendResourceContainerUpdateAmount(resCont,mOwner);
gWorldManager->getDatabase()->executeSqlAsync(NULL,NULL,"UPDATE resource_containers SET amount=%u WHERE id=%"PRIu64"",maxAmount,resCont->getId());
gObjectFactory->requestNewResourceContainer(dynamic_cast<Inventory*>(mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)),(*resIt).first,mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)->getId(),99,selectedNewAmount);
}
break;
}
}
++listIt;
}
// or need to create a new one
if(!foundSameType)
{
gObjectFactory->requestNewResourceContainer(dynamic_cast<Inventory*>(mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)),(*resIt).first,mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)->getId(),99,amount);
}
++resIt;
}
}
//=============================================================================
//
// a manufacture slot is emptied
//
void CraftingSession::emptySlot(uint32 slotId,ManufactureSlot* manSlot,uint64 containerId)
{
//get ressources back in their stack
//or components back in the inventory
if(manSlot->getFilledType() == DST_Resource)
bagResource(manSlot,containerId);
else if(manSlot->getFilledType() != DST_Empty)
bagComponents(manSlot,containerId);
// update the slot
manSlot->mFilledResources.clear();
manSlot->mUsedComponentStacks.clear();
manSlot->setFilledType(DST_Empty);
// if it was completely filled, update the total amount of filled slots
if(manSlot->getFilledAmount() == manSlot->mDraftSlot->getNecessaryAmount())
{
mManufacturingSchematic->removeFilledSlot();
gMessageLib->sendUpdateFilledManufactureSlots(mManufacturingSchematic,mOwner);
//update the amount clientside, too ?
}
if(manSlot->getFilledAmount())
{
manSlot->setFilledAmount(0);
//only send when changes !!!!!
gMessageLib->sendManufactureSlotUpdate(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
manSlot->setResourceId(0);
manSlot->setSerial("");
}
//=============================================================================
//this creates the serial for a crafted item
BString CraftingSession::getSerial()
{
int8 serial[12],chance[9];
bool found = false;
uint8 u;
for(uint8 i = 0; i < 8; i++)
{
while(!found)
{
found = true;
u = static_cast<uint8>(static_cast<double>(gRandom->getRand()) / (RAND_MAX + 1.0f) * (122.0f - 48.0f) + 48.0f);
//only 1 to 9 or a to z
if((u >57)&&(u <97))
found = false;
if((u < 48)||(u >122))
found = false;
}
chance[i] = u;
found = false;
}
chance[8] = 0;
sprintf(serial,"(%s)",chance);
return(BString(serial));
}
//=============================================================================
//gets the type of success / failure for experimentation
uint8 CraftingSession::_experimentRoll(uint32 expPoints)
{
if(mOwnerExpSkillMod > 125)
{
mOwnerExpSkillMod = 125;
}
int32 assRoll;
int32 riskRoll;
float ma = _calcAverageMalleability();
//high rating means lesser risk!!
float rating = 50.0f + ((ma - 500.0f) / 40.0f) + mOwnerExpSkillMod - (5.0f * expPoints);
rating -= (mManufacturingSchematic->getComplexity()/10);
rating += (mToolEffectivity/10);
float risk = 100.0f - rating;
riskRoll = (int32)(floor(((double)gRandom->getRand() / (RAND_MAX + 1.0f) * (100.0f - 1.0f) + 1.0f)));
if(riskRoll <= risk)
{
//ok we have some sort of failure
assRoll = (int32)(floor((double)gRandom->getRand() / (RAND_MAX + 1.0f) * (100.0f - 1.0f) + 1.0f));
int32 modRoll = (int32)(floor((double)(assRoll / 25)) + 4);
if(modRoll < 4)
modRoll = 4;
else if(modRoll > 8)
modRoll = 8;
return static_cast<uint8>(modRoll);
}
mManufacturingSchematic->setExpFailureChance(risk);
//ok we have some sort of success
assRoll = (int32) floor( (double)gRandom->getRand() / (RAND_MAX + 1.0f) * (100.0f - 1.0f) + 1.0f) ;
int32 modRoll = static_cast<int32>(((assRoll - (rating * 0.4f)) / 15.0f) - (mToolEffectivity / 50.0f));
++modRoll;
//int32 modRoll = (gRandom->getRand() - (rating*0.2))/15;
//0 is amazing success
//1 is great success
//2 is good success
//3 moderate success
//4 success
//5 failure
//6 moderate failure
//7 big failure
//8 critical failure
// make sure we are in valid range
if(modRoll < 0)
modRoll = 0;
else if(modRoll > 4)
modRoll = 4;
return static_cast<uint8>(modRoll);
}
//=============================================================================
//this determines our success in the assembly of the item
uint8 CraftingSession::_assembleRoll()
{
// assembly roll, needs to be improved, maybe make a pool to draw results from, which is populated based on the skillmod
//int32 assRoll = (int32)(floor((float)(gRandom->getRand()%9) - ((float)assMod / 20.0f)));
int32 assRoll;
int32 riskRoll;
float ma = _calcAverageMalleability();
// make sure the values are valid and dont crash us cap it at 125
if(mOwnerAssSkillMod > 125)
{
mOwnerAssSkillMod = 125;
}
float rating = 50.0f + ((ma - 500.0f) / 40.0f) + mOwnerAssSkillMod - 5.0f;
rating += (mToolEffectivity/10);
rating -= (mManufacturingSchematic->getComplexity()/10);
float risk = 100.0f - rating;
mManufacturingSchematic->setExpFailureChance(risk);
riskRoll = (int32)(floor(((double)gRandom->getRand() / (RAND_MAX + 1.0f) * (100.0f - 1.0f) + 1.0f)));
//gLogger->logErrorF("Crafting","CraftingSession::_assembleRoll() relevant riskroll %u",riskRoll);
// ensure that every critical makes the nect critical less likely
// we dont want to have more than 3 criticals in a row
//gLogger->logErrorF("Crafting","CraftingSession::_assembleRoll() relevant criticalCount %u",mCriticalCount);
riskRoll += (mCriticalCount*5);
//gLogger->logErrorF("Crafting","CraftingSession::_assembleRoll() modified riskroll %u",riskRoll);
if((mCriticalCount == 3))
riskRoll = static_cast<uint32>(risk+1);
if(riskRoll <= risk)
{
//ok critical failure time !
mCriticalCount++;
return(8);
}
else
mCriticalCount = 0;
//ok we have some sort of success
assRoll = (int32)floor((double)gRandom->getRand() / (RAND_MAX + 1.0f) * (100.0f - 1.0f) + 1.0f) ;
int32 modRoll = static_cast<uint32>(((assRoll - (rating * 0.4f)) / 15.0f) - (mToolEffectivity / 50.0f));
//0 is amazing success
//1 is great success
//2 is good success
//3 success
//4 is moderate success
//5 marginally successful
//6 ok
//7 barely succesfull
//8 critical failure
// make sure we are in valid range
if(modRoll < 0)
modRoll = 0;
else if(modRoll > 7)
modRoll = 7;
return static_cast<uint8>(modRoll);
}
//=============================================================================
//
// calculate the maximum reachable percentage through assembly with the filled resources
//
float CraftingSession::_calcAverageMalleability()
{
FilledResources::iterator filledResIt;
ManufactureSlots* manSlots = mManufacturingSchematic->getManufactureSlots();
ManufactureSlots::iterator manIt = manSlots->begin();
CraftWeights::iterator weightIt;
ManufactureSlot* manSlot;
Resource* resource;
uint16 resAtt = 0;
uint8 slotCount = 0;
while(manIt != manSlots->end())
{
manSlot = (*manIt);
// skip if its a sub component slot
if(manSlot->mDraftSlot->getType() != 4)
{
++manIt;
continue;
}
// we limit it so that only the same resource can go into one slot, so grab only the first entry
filledResIt = manSlot->mFilledResources.begin();
if(manSlot->mFilledResources.empty())
{
//in case we can leave resource slots optionally emptymanSlot->mFilledResources
++manIt;
continue;
}
resource = gResourceManager->getResourceById((*filledResIt).first);
resAtt += resource->getAttribute(ResAttr_MA);
++slotCount;
++manIt;
}
return static_cast<float>(resAtt/slotCount);
}
//===============================================================================
//collects a resourcelist to give to a manufacturing schematic
//
void CraftingSession::collectResources()
{
ManufactureSlots::iterator manIt = mManufacturingSchematic->getManufactureSlots()->begin();
int8 str[64];
int8 attr[64];
CheckResources::iterator checkResIt = mCheckRes.begin();
BString name;
while(manIt != mManufacturingSchematic->getManufactureSlots()->end())
{
//is it a resource??
if((*manIt)->mDraftSlot->getType() == DST_Resource)
{
//get resource name and amount
//we only can enter one res type in a slot so dont care about the other entries
FilledResources::iterator filledResIt = (*manIt)->mFilledResources.begin();
uint64 resID = (*filledResIt).first;
checkResIt = mCheckRes.find(resID);
if(checkResIt == mCheckRes.end())
{
mCheckRes.insert(std::make_pair(resID,(*filledResIt).second));
}
else
{
//uint32 amount = ((*checkResIt).second + (*filledResIt).second);
(*checkResIt).second += (*filledResIt).second;
//uint64 id = (*checkResIt).first;
//mCheckRes.erase(checkResIt);
//mCheckRes.insert(std::make_pair(id,amount));
}
}
manIt++;
}
checkResIt = mCheckRes.begin();
while(checkResIt != mCheckRes.end())
{
//build these attributes by hand the attribute wont be found in the attributes table its custom made
name = gResourceManager->getResourceById((*checkResIt).first)->getName();
sprintf(attr,"cat_manf_schem_ing_resource.\"%s",name .getAnsi());
BString attrName = BString(attr);
sprintf(str,"%u",(*checkResIt).second);
//add to the public attribute list
mManufacturingSchematic->addAttribute(attrName.getAnsi(),str);
//now add to the db
sprintf(str,"%s %u",name.getAnsi(),(*checkResIt).second);
//update db
//enter it slotdependent as we dont want to clot our attributes table with resources
//173 is cat_manf_schem_resource
mDatabase->executeSqlAsync(0,0,"INSERT INTO item_attributes VALUES (%"PRIu64",173,'%s',1,0)",mManufacturingSchematic->getId(),str);
//now enter it in the relevant manschem table so we can use it in factories
mDatabase->executeSqlAsync(0,0,"INSERT INTO manschemresources VALUES (NULL,%"PRIu64",%"PRIu64",%u)",mManufacturingSchematic->getId(),(*checkResIt).first,(*checkResIt).second);
checkResIt ++;
}
mCheckRes.clear();
}
//===============================================================================
//collects a resourcelist to give to a manufacturing schematic
//
void CraftingSession::collectComponents()
{
ManufactureSlots::iterator manIt = mManufacturingSchematic->getManufactureSlots()->begin();
int8 str[64];
int8 attr[64];
CheckResources::iterator checkResIt = mCheckRes.begin();
BString name;
while(manIt != mManufacturingSchematic->getManufactureSlots()->end())
{
//is it a resource??
if(((*manIt)->mDraftSlot->getType() == DST_IdentComponent)||((*manIt)->mDraftSlot->getType() == DST_SimiliarComponent))
{
if(!(*manIt)->mFilledResources.size())
{
manIt++;
continue;
}
//get component serial and amount
//we only can enter one serial type in a slot so dont care about the other entries
FilledResources::iterator filledResIt = (*manIt)->mFilledResources.begin();
uint64 componentID = (*filledResIt).first;
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(componentID));
if(!tO)
{
//item not found??? wth
assert(false && "CraftingSession::collectComponents No tangible object found in world manager");
}
BString componentSerial = "";
if(tO->hasAttribute("serial"))
componentSerial = tO->getAttribute<std::string>("serial").c_str();
checkResIt = mCheckRes.find(componentID);
if(checkResIt == mCheckRes.end())
{
mCheckRes.insert(std::make_pair(componentID,(*filledResIt).second));
}
else
{
//uint32 amount = ((*checkResIt).second + (*filledResIt).second);
(*checkResIt).second += (*filledResIt).second;
//uint64 id = (*checkResIt).first;
//mCheckRes.erase(checkResIt);
//mCheckRes.insert(std::make_pair(id,amount));
}
}
manIt++;
}
checkResIt = mCheckRes.begin();
while(checkResIt != mCheckRes.end())
{
Item* tO = dynamic_cast<Item*>(gWorldManager->getObjectById((*checkResIt).first));
if(!tO)
{
continue;
}
BString componentSerial = "";
if(tO->hasAttribute("serial"))
componentSerial = tO->getAttribute<std::string>("serial").c_str();
name = tO->getName();
sprintf(attr,"cat_manf_schem_ing_component.\"%s",name .getAnsi());
BString attrName = BString(attr);
sprintf(str,"%u",(*checkResIt).second);
//add to the public attribute list
mManufacturingSchematic->addAttribute(attrName.getAnsi(),str);
//now add to the db
sprintf(str,"%s %u",name.getAnsi(),(*checkResIt).second);
//update db
//enter it slotdependent as we dont want to clot our attributes table with resources
//173 is cat_manf_schem_resource
mDatabase->executeSqlAsync(0,0,"INSERT INTO item_attributes VALUES (%"PRIu64",173,'%s',1,0)",mManufacturingSchematic->getId(),str);
//now enter it in the relevant manschem table so we can use it in factories
mDatabase->executeSqlAsync(0,0,"INSERT INTO manschemcomponents VALUES (NULL,%"PRIu64",%u,%s,%u)",mManufacturingSchematic->getId(),tO->getItemType(),componentSerial.getAnsi(),(*checkResIt).second);
checkResIt ++;
}
mCheckRes.clear();
}
//===============================================================================
//collects a resourcelist to give to a manufacturing schematic
//
void CraftingSession::updateResourceContainer(uint64 containerID, uint32 newAmount)
{
// destroy if its empty
if(!newAmount)
{
//now destroy it client side
gMessageLib->sendDestroyObject(containerID,mOwner);
gObjectFactory->deleteObjectFromDB(containerID);
ResourceContainer* resContainer = dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(containerID));
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(resContainer->getParentId()));
tO->deleteObject(resContainer);
}
// update it
else
{
ResourceContainer* resContainer = dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(containerID));
resContainer->setAmount(newAmount);
gMessageLib->sendResourceContainerUpdateAmount(resContainer,mOwner);
mDatabase->executeSqlAsync(NULL,NULL,"UPDATE resource_containers SET amount=%u WHERE id=%"PRIu64"",newAmount,resContainer->getId());
}
}
//===============================================================
// empties the slots of a man schem when a critical assembly error happens
// send
void CraftingSession::emptySlots(uint32 counter)
{
uint8 amount = mManufacturingSchematic->getManufactureSlots()->size();
for (uint8 i = 0; i < amount; i++)
{
ManufactureSlot* manSlot = mManufacturingSchematic->getManufactureSlots()->at(i);
if(manSlot)
{
emptySlot(i,manSlot,mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)->getId());
gMessageLib->sendCraftAcknowledge(opCraftEmptySlot,CraftError_None,static_cast<uint8>(counter),mOwner);
}
}
}
//===============================================================
// modifies an items attribute value
//
void CraftingSession::modifyAttributeValue(CraftAttribute* att, float attValue)
{
if(att->getType())
{
int32 intAtt = 0;
//is there an attribute of a component that affects us??
if(mManufacturingSchematic->hasPPAttribute(att->getAttributeKey()))
{
float attributeAddValue = mManufacturingSchematic->getPPAttribute<float>(att->getAttributeKey());
intAtt = (int32)(ceil(attributeAddValue));
}
intAtt += (int32)(ceil(attValue));
mItem->setAttributeIncDB(att->getAttributeKey(),boost::lexical_cast<std::string>(intAtt));
}
else
{
float f = rndFloat(attValue);
//is there an attribute of a component that affects us??
if(mManufacturingSchematic->hasPPAttribute(att->getAttributeKey()))
{
float attributeAddValue = mManufacturingSchematic->getPPAttribute<float>(att->getAttributeKey());
f += rndFloat(attributeAddValue);
}
//mItem->setAttributeIncDB(att->getAttributeKey(),boost::lexical_cast<std::string>(f));
mItem->setAttributeIncDB(att->getAttributeKey(),rndFloattoStr(f).getAnsi());
}
}
float CraftingSession::getPercentage(uint8 roll)
{
float percentage = 0.0;
switch(roll)
{
case 0 :
percentage = 0.08f;
break;
case 1 :
percentage = 0.07f;
break;
case 2 :
percentage = 0.06f;
break;
case 3 :
percentage = 0.02f;
break;
case 4 :
percentage = 0.01f;
break;
case 5 :
percentage = -0.0175f;
break; //failure
case 6 :
percentage = -0.035f;
break;//moderate failure
case 7 :
percentage = -0.07f;
break;//big failure
case 8 :
percentage = -0.14f;
break;//critical failure
}
return percentage;
}
//========================================================================================
// gets the ExperimentationRoll and initializes the experimental properties
// meaning an exp property which exists several times (with different resourceweights)
// gets the same roll assigned
uint8 CraftingSession::getExperimentationRoll(ExperimentationProperty* expProperty, uint8 expPoints)
{
ExperimentationProperties* expAllProps = mManufacturingSchematic->getExperimentationProperties();
ExperimentationProperties::iterator itAll = expAllProps->begin();
uint8 roll;
if(expProperty->mRoll == -1)
{
DLOG(INFO) << "CraftingSession:: expProperty is a Virgin!";
// get our Roll and take into account the relevant modifiers
roll = _experimentRoll(expPoints);
// now go through all properties and mark them when its this one!
// so we dont experiment two times on it!
itAll = expAllProps->begin();
while(itAll != expAllProps->end())
{
ExperimentationProperty* tempProperty = (*itAll);
if(expProperty->mExpAttributeName.getCrc() == tempProperty->mExpAttributeName.getCrc())
{
tempProperty->mRoll = roll;
}
itAll++;
}
}
else
{
roll = static_cast<uint8>(expProperty->mRoll);
DLOG(INFO) << "CraftingSession:: experiment expProperty isnt a virgin anymore ...(roll:" << roll;
}
return roll;
}
| 32.164217
| 288
| 0.618909
|
maxim5
|
5a1420d1660d2c8ebe5911459718a6172f131fb9
| 3,888
|
hpp
|
C++
|
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/pthreadcond.hpp
|
TiagoPedroByterev/openvpnclient-ios
|
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
|
[
"MIT"
] | 10
|
2021-03-29T13:52:06.000Z
|
2022-03-10T02:24:25.000Z
|
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/pthreadcond.hpp
|
TiagoPedroByterev/openvpnclient-ios
|
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
|
[
"MIT"
] | 1
|
2019-07-19T02:40:32.000Z
|
2019-07-19T02:40:32.000Z
|
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/pthreadcond.hpp
|
TiagoPedroByterev/openvpnclient-ios
|
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
|
[
"MIT"
] | 7
|
2018-07-11T10:37:02.000Z
|
2019-08-03T10:34:08.000Z
|
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#ifndef OPENVPN_COMMON_PTHREADCOND_H
#define OPENVPN_COMMON_PTHREADCOND_H
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <openvpn/common/stop.hpp>
namespace openvpn {
// Barrier class that is useful in cases where all threads
// need to reach a known point before executing some action.
// Note that this barrier implementation is
// constructed using C++11 condition variables.
class PThreadBarrier
{
enum State {
UNSIGNALED=0, // initial state
SIGNALED, // signal() was called
ERROR_THROWN, // error() was called
};
public:
// status return from wait()
enum Status {
SUCCESS=0, // successful
CHOSEN_ONE, // successful and chosen (only one thread is chosen)
TIMEOUT, // timeout
ERROR, // at least one thread called error()
};
PThreadBarrier(const int initial_limit = -1)
: stop(nullptr),
limit(initial_limit)
{
}
PThreadBarrier(Stop* stop_arg, const int initial_limit = -1)
: stop(stop_arg),
limit(initial_limit)
{
}
// All callers will increment count and block until
// count == limit. CHOSEN_ONE will be returned to
// the first caller to reach limit. This caller can
// then release all the other callers by calling
// signal().
int wait(const unsigned int seconds)
{
// allow asynchronous stop
Stop::Scope stop_scope(stop, [this]() {
error();
});
bool timeout = false;
int ret;
std::unique_lock<std::mutex> lock(mutex);
const unsigned int c = ++count;
while (state == UNSIGNALED
&& (limit < 0 || c < limit)
&& !timeout)
timeout = (cv.wait_for(lock, std::chrono::seconds(seconds)) == std::cv_status::timeout);
if (timeout)
ret = TIMEOUT;
else if (state == ERROR_THROWN)
ret = ERROR;
else if (state == UNSIGNALED && !chosen)
{
ret = CHOSEN_ONE;
chosen = true;
}
else
ret = SUCCESS;
return ret;
}
void set_limit(const int new_limit)
{
std::unique_lock<std::mutex> lock(mutex);
limit = new_limit;
cv.notify_all();
}
// Generally, only the CHOSEN_ONE calls signal() after its work
// is complete, to allow the other threads to pass the barrier.
void signal()
{
signal_(SIGNALED);
}
// Causes all threads waiting on wait() (and those which call wait()
// in the future) to exit with ERROR status.
void error()
{
signal_(ERROR_THROWN);
}
private:
void signal_(const State newstate)
{
std::unique_lock<std::mutex> lock(mutex);
if (state == UNSIGNALED)
{
state = newstate;
cv.notify_all();
}
}
std::mutex mutex;
std::condition_variable cv;
Stop* stop;
State state{UNSIGNALED};
bool chosen = false;
unsigned int count = 0;
int limit;
};
}
#endif
| 27
| 89
| 0.637088
|
TiagoPedroByterev
|
5a19681fccf6da574551c4be56c4be8ac59960b0
| 4,833
|
cpp
|
C++
|
blast/src/algo/blast/api/local_search.cpp
|
mycolab/ncbi-blast
|
e59746cec78044d2bf6d65de644717c42f80b098
|
[
"Apache-2.0"
] | null | null | null |
blast/src/algo/blast/api/local_search.cpp
|
mycolab/ncbi-blast
|
e59746cec78044d2bf6d65de644717c42f80b098
|
[
"Apache-2.0"
] | null | null | null |
blast/src/algo/blast/api/local_search.cpp
|
mycolab/ncbi-blast
|
e59746cec78044d2bf6d65de644717c42f80b098
|
[
"Apache-2.0"
] | null | null | null |
/* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Christiam Camacho
*
*/
/** @file local_search.cpp
* This file implements the Uniform Blast Search Interface in terms of
* the local BLAST database search class
* NOTE: This is OBJECT MANAGER DEPENDANT because of its use of CDbBlast!
*/
#include <ncbi_pch.hpp>
// Object includes
#include <objects/scoremat/Pssm.hpp>
#include <objects/scoremat/PssmWithParameters.hpp>
#include <objects/seqalign/Seq_align.hpp>
#include <objects/seqalign/Seq_align_set.hpp>
#include <objects/seqset/Seq_entry.hpp>
// Object manager dependencies
#include <algo/blast/api/seqsrc_seqdb.hpp>
#include <objmgr/object_manager.hpp>
// BLAST includes
#include <algo/blast/api/local_search.hpp>
#include <algo/blast/api/psiblast.hpp>
#include <algo/blast/api/objmgrfree_query_data.hpp>
#include "psiblast_aux_priv.hpp"
/** @addtogroup AlgoBlast
*
* @{
*/
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(blast)
/// Supporting elements
//
// Factory
//
CRef<ISeqSearch>
CLocalSearchFactory::GetSeqSearch()
{
return CRef<ISeqSearch>(new CLocalSeqSearch());
}
CRef<IPssmSearch>
CLocalSearchFactory::GetPssmSearch()
{
return CRef<IPssmSearch>(new CLocalPssmSearch());
}
CRef<CBlastOptionsHandle>
CLocalSearchFactory::GetOptions(EProgram program)
{
// FIXME: should do some validation for acceptable programs by the
// implementation (i.e.: CDbBlast)
return CRef<CBlastOptionsHandle>(CBlastOptionsFactory::Create(program));
}
//
// Seq Search
//
// NOTE: Local search object is re-created every time it is run.
CRef<CSearchResultSet>
CLocalSeqSearch::Run()
{
if ( m_QueryFactory.Empty() ) {
NCBI_THROW(CSearchException, eConfigErr, "No queries specified");
}
if ( m_Database.Empty() ) {
NCBI_THROW(CSearchException, eConfigErr, "No database name specified");
}
if ( !m_SearchOpts ) {
NCBI_THROW(CSearchException, eConfigErr, "No options specified");
}
// This is delayed to this point to guarantee that the options are
// populated
m_LocalBlast.Reset(new CLocalBlast(m_QueryFactory, m_SearchOpts,
*m_Database));
return m_LocalBlast->Run();
}
void
CLocalSeqSearch::SetOptions(CRef<CBlastOptionsHandle> opts)
{
m_SearchOpts = opts;
}
void
CLocalSeqSearch::SetSubject(CConstRef<CSearchDatabase> subject)
{
m_Database = subject;
}
void
CLocalSeqSearch::SetQueryFactory(CRef<IQueryFactory> query_factory)
{
m_QueryFactory = query_factory;
}
//
// Psi Search
//
void
CLocalPssmSearch::SetOptions(CRef<CBlastOptionsHandle> opts)
{
m_SearchOpts = opts;
}
void
CLocalPssmSearch::SetSubject(CConstRef<CSearchDatabase> subject)
{
m_Subject = subject;
}
void
CLocalPssmSearch::SetQuery(CRef<objects::CPssmWithParameters> pssm)
{
CPsiBlastValidate::Pssm(*pssm);
m_Pssm = pssm;
}
CRef<CSearchResultSet>
CLocalPssmSearch::Run()
{
CConstRef<CPSIBlastOptionsHandle> psi_opts;
psi_opts.Reset(dynamic_cast<CPSIBlastOptionsHandle*>(&*m_SearchOpts));
if (psi_opts.Empty()) {
NCBI_THROW(CBlastException, eInvalidArgument,
"Options for CLocalPssmSearch are not PSI-BLAST");
}
CConstRef<CBioseq> query(&m_Pssm->GetPssm().GetQuery().GetSeq());
CRef<IQueryFactory> query_factory(new CObjMgrFree_QueryFactory(query)); /* NCBI_FAKE_WARNING */
CRef<CLocalDbAdapter> dbadapter(new CLocalDbAdapter(*m_Subject));
CPsiBlast psiblast(query_factory, dbadapter, psi_opts);
CRef<CSearchResultSet> retval = psiblast.Run();
return retval;
}
END_SCOPE(blast)
END_NCBI_SCOPE
/* @} */
| 26.85
| 99
| 0.699979
|
mycolab
|
5a1c1bdce9d2b6701ef76bb1d6d295398535a614
| 1,505
|
cpp
|
C++
|
tests/algebra/operator/conjugate.cpp
|
qftphys/Simulate-the-non-equilibrium-dynamics-of-Fermionic-systems
|
48d36fecbe4bc12af90f104cdf1f9f68352c508c
|
[
"MIT"
] | 2
|
2021-01-18T14:35:43.000Z
|
2022-03-22T15:12:49.000Z
|
tests/algebra/operator/conjugate.cpp
|
f-koehler/ieompp
|
48d36fecbe4bc12af90f104cdf1f9f68352c508c
|
[
"MIT"
] | null | null | null |
tests/algebra/operator/conjugate.cpp
|
f-koehler/ieompp
|
48d36fecbe4bc12af90f104cdf1f9f68352c508c
|
[
"MIT"
] | null | null | null |
#include "operator.hpp"
using namespace ieompp::algebra;
TEST_CASE("conjugate_1")
{
const auto a = Operator1::make_creator(0ul), b = Operator1::make_annihilator(0ul);
Operator1 a_conj(a), b_conj(b);
a_conj.conjugate();
b_conj.conjugate();
REQUIRE(a_conj == b);
REQUIRE(b_conj == a);
}
TEST_CASE("conjugate_2")
{
const auto a = Operator2::make_creator(0ul, true), b = Operator2::make_annihilator(0ul, true);
Operator2 a_conj(a), b_conj(b);
a_conj.conjugate();
b_conj.conjugate();
REQUIRE(a_conj == b);
REQUIRE(b_conj == a);
}
TEST_CASE("conjugate_3")
{
const auto a = Operator3::make_creator(0ul, true, 'a'),
b = Operator3::make_annihilator(0ul, true, 'a');
Operator3 a_conj(a), b_conj(b);
a_conj.conjugate();
b_conj.conjugate();
REQUIRE(a_conj == b);
REQUIRE(b_conj == a);
}
TEST_CASE("get_conjugate_1")
{
const auto a = Operator1::make_creator(0ul), b = Operator1::make_annihilator(0ul);
REQUIRE(a.get_conjugate() == b);
REQUIRE(b.get_conjugate() == a);
}
TEST_CASE("get_conjugate_2")
{
const auto a = Operator2::make_creator(0ul, true), b = Operator2::make_annihilator(0ul, true);
REQUIRE(a.get_conjugate() == b);
REQUIRE(b.get_conjugate() == a);
}
TEST_CASE("get_conjugate_3")
{
const auto a = Operator3::make_creator(0ul, true, 'a'),
b = Operator3::make_annihilator(0ul, true, 'a');
REQUIRE(a.get_conjugate() == b);
REQUIRE(b.get_conjugate() == a);
}
| 24.274194
| 98
| 0.64186
|
qftphys
|
5a1fe7ab79a62c09730683bfcb46fcec655160fd
| 3,322
|
cpp
|
C++
|
src/debug_message.cpp
|
anima-libera/qwy2
|
4875caf8035c5fb60e12eaba787d29017ffa0ed8
|
[
"Apache-2.0"
] | null | null | null |
src/debug_message.cpp
|
anima-libera/qwy2
|
4875caf8035c5fb60e12eaba787d29017ffa0ed8
|
[
"Apache-2.0"
] | null | null | null |
src/debug_message.cpp
|
anima-libera/qwy2
|
4875caf8035c5fb60e12eaba787d29017ffa0ed8
|
[
"Apache-2.0"
] | null | null | null |
#include "debug_message.hpp"
#include "opengl.hpp"
#include <SDL2/SDL.h>
#include <iostream>
namespace qwy2
{
using namespace std::literals::string_view_literals;
static std::string_view opengl_debug_message_source_name(GLenum source)
{
switch (source)
{
case GL_DEBUG_SOURCE_API:
return "API"sv;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
return "WINDOW_SYSTEM"sv;
case GL_DEBUG_SOURCE_SHADER_COMPILER:
return "SHADER_COMPILER"sv;
case GL_DEBUG_SOURCE_THIRD_PARTY:
return "THIRD_PARTY"sv;
case GL_DEBUG_SOURCE_APPLICATION:
return "APPLICATION"sv;
case GL_DEBUG_SOURCE_OTHER:
return "OTHER"sv;
default:
return "NOT_A_SOURCE"sv;
}
}
static std::string_view opengl_debug_message_type_name(GLenum type)
{
switch (type)
{
case GL_DEBUG_TYPE_ERROR:
return "ERROR"sv;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
return "DEPRECATED_BEHAVIOR"sv;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
return "UNDEFINED_BEHAVIOR"sv;
case GL_DEBUG_TYPE_PORTABILITY:
return "PORTABILITY"sv;
case GL_DEBUG_TYPE_PERFORMANCE:
return "PERFORMANCE"sv;
case GL_DEBUG_TYPE_MARKER:
return "MARKER"sv;
case GL_DEBUG_TYPE_PUSH_GROUP:
return "PUSH_GROUP"sv;
case GL_DEBUG_TYPE_POP_GROUP:
return "POP_GROUP"sv;
case GL_DEBUG_TYPE_OTHER:
return "OTHER"sv;
default:
return "NOT_A_TYPE"sv;
}
}
static std::string_view opengl_debug_message_severity_name(GLenum type)
{
switch (type)
{
case GL_DEBUG_SEVERITY_HIGH:
return "HIGH"sv;
case GL_DEBUG_SEVERITY_MEDIUM:
return "MEDIUM"sv;
case GL_DEBUG_SEVERITY_LOW:
return "LOW"sv;
case GL_DEBUG_SEVERITY_NOTIFICATION:
return "NOTIFICATION"sv;
default:
return "NOT_A_SEVERITY"sv;
}
}
/* Debug message callback given to glDebugMessageCallback. Prints an error
* message to stderr. */
static void GLAPIENTRY opengl_debug_message_callback(
GLenum source, GLenum type, GLuint id, GLenum severity, [[maybe_unused]] GLsizei length,
GLchar const* message, [[maybe_unused]] void const* user_param)
{
#ifndef ENABLE_OPENGL_NOTIFICATIONS
/* Filter out non-error debug messages if not opted-in. */
if (type != GL_DEBUG_TYPE_ERROR)
{
return;
}
/* Note: The printing of non-error debug messages will often be similar to
* > OpenGL debug message (NOTIFICATION severity) API:OTHER(131185)
* > "Buffer detailed info: Buffer object 5
* > (bound to GL_ARRAY_BUFFER_ARB, usage hint is GL_DYNAMIC_DRAW)
* > will use VIDEO memory as the source for buffer object operations."
* (it looks like that on my machine). */
#endif
(type == GL_DEBUG_TYPE_ERROR ? std::cerr : std::cout)
<< "OpenGL debug message "
<< "(" << opengl_debug_message_severity_name(severity) << " severity) "
<< opengl_debug_message_source_name(source) << ":" << opengl_debug_message_type_name(type)
<< "(" << id << ") "
<< (type == GL_DEBUG_TYPE_ERROR ? "\x1b[31m" : "\x1b[34m") << message << "\x1b[39m"
<< std::endl;
}
void enable_opengl_debug_message()
{
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(opengl_debug_message_callback, nullptr);
}
void disable_opengl_debug_message()
{
glDisable(GL_DEBUG_OUTPUT);
}
void error_sdl2_fail(std::string_view operation)
{
std::cerr << "SDL2 error: " << operation << " failed: "
<< "\x1b[31m\"" << SDL_GetError() << "\"\x1b[39m" << std::endl;
}
} /* qwy2 */
| 27.00813
| 92
| 0.735099
|
anima-libera
|
5a205b4c2557930f1cd90d29161e4aa9bb755121
| 12,929
|
cpp
|
C++
|
Sources/simdlib/SimdSse2Texture.cpp
|
aestesis/Csimd
|
b333a8bb7e7f2707ed6167badb8002cfe3504bbc
|
[
"Apache-2.0"
] | 6
|
2017-10-13T04:29:38.000Z
|
2018-05-10T13:52:20.000Z
|
Sources/simdlib/SimdSse2Texture.cpp
|
aestesis/Csimd
|
b333a8bb7e7f2707ed6167badb8002cfe3504bbc
|
[
"Apache-2.0"
] | null | null | null |
Sources/simdlib/SimdSse2Texture.cpp
|
aestesis/Csimd
|
b333a8bb7e7f2707ed6167badb8002cfe3504bbc
|
[
"Apache-2.0"
] | null | null | null |
/*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2017 Yermalayeu Ihar.
*
* 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 "Simd/SimdMemory.h"
#include "Simd/SimdExtract.h"
#include "Simd/SimdStore.h"
#include "Simd/SimdBase.h"
namespace Simd
{
#ifdef SIMD_SSE2_ENABLE
namespace Sse2
{
SIMD_INLINE __m128i TextureBoostedSaturatedGradient16(__m128i a, __m128i b, __m128i saturation, const __m128i & boost)
{
return _mm_mullo_epi16(_mm_max_epi16(K_ZERO, _mm_add_epi16(saturation, _mm_min_epi16(_mm_sub_epi16(b, a), saturation))), boost);
}
SIMD_INLINE __m128i TextureBoostedSaturatedGradient8(__m128i a, __m128i b, __m128i saturation, const __m128i & boost)
{
__m128i lo = TextureBoostedSaturatedGradient16(_mm_unpacklo_epi8(a, K_ZERO), _mm_unpacklo_epi8(b, K_ZERO), saturation, boost);
__m128i hi = TextureBoostedSaturatedGradient16(_mm_unpackhi_epi8(a, K_ZERO), _mm_unpackhi_epi8(b, K_ZERO), saturation, boost);
return _mm_packus_epi16(lo, hi);
}
template<bool align> SIMD_INLINE void TextureBoostedSaturatedGradient(const uint8_t * src, uint8_t * dx, uint8_t * dy,
size_t stride, __m128i saturation, __m128i boost)
{
const __m128i s10 = Load<false>((__m128i*)(src - 1));
const __m128i s12 = Load<false>((__m128i*)(src + 1));
const __m128i s01 = Load<align>((__m128i*)(src - stride));
const __m128i s21 = Load<align>((__m128i*)(src + stride));
Store<align>((__m128i*)dx, TextureBoostedSaturatedGradient8(s10, s12, saturation, boost));
Store<align>((__m128i*)dy, TextureBoostedSaturatedGradient8(s01, s21, saturation, boost));
}
template<bool align> void TextureBoostedSaturatedGradient(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t saturation, uint8_t boost, uint8_t * dx, size_t dxStride, uint8_t * dy, size_t dyStride)
{
assert(width >= A && int(2)*saturation*boost <= 0xFF);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(dx) && Aligned(dxStride) && Aligned(dy) && Aligned(dyStride));
}
size_t alignedWidth = AlignLo(width, A);
__m128i _saturation = _mm_set1_epi16(saturation);
__m128i _boost = _mm_set1_epi16(boost);
memset(dx, 0, width);
memset(dy, 0, width);
src += srcStride;
dx += dxStride;
dy += dyStride;
for (size_t row = 2; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
TextureBoostedSaturatedGradient<align>(src + col, dx + col, dy + col, srcStride, _saturation, _boost);
if(width != alignedWidth)
TextureBoostedSaturatedGradient<false>(src + width - A, dx + width - A, dy + width - A, srcStride, _saturation, _boost);
dx[0] = 0;
dy[0] = 0;
dx[width - 1] = 0;
dy[width - 1] = 0;
src += srcStride;
dx += dxStride;
dy += dyStride;
}
memset(dx, 0, width);
memset(dy, 0, width);
}
void TextureBoostedSaturatedGradient(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t saturation, uint8_t boost, uint8_t * dx, size_t dxStride, uint8_t * dy, size_t dyStride)
{
if(Aligned(src) && Aligned(srcStride) && Aligned(dx) && Aligned(dxStride) && Aligned(dy) && Aligned(dyStride))
TextureBoostedSaturatedGradient<true>(src, srcStride, width, height, saturation, boost, dx, dxStride, dy, dyStride);
else
TextureBoostedSaturatedGradient<false>(src, srcStride, width, height, saturation, boost, dx, dxStride, dy, dyStride);
}
template<bool align> SIMD_INLINE void TextureBoostedUv(const uint8_t * src, uint8_t * dst, __m128i min8, __m128i max8, __m128i boost16)
{
const __m128i _src = Load<align>((__m128i*)src);
const __m128i saturated = _mm_sub_epi8(_mm_max_epu8(min8, _mm_min_epu8(max8, _src)), min8);
const __m128i lo = _mm_mullo_epi16(_mm_unpacklo_epi8(saturated, K_ZERO), boost16);
const __m128i hi = _mm_mullo_epi16(_mm_unpackhi_epi8(saturated, K_ZERO), boost16);
Store<align>((__m128i*)dst, _mm_packus_epi16(lo, hi));
}
template<bool align> void TextureBoostedUv(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t boost, uint8_t * dst, size_t dstStride)
{
assert(width >= A && boost < 0x80);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride));
}
size_t alignedWidth = AlignLo(width, A);
int min = 128 - (128/boost);
int max = 255 - min;
__m128i min8 = _mm_set1_epi8(min);
__m128i max8 = _mm_set1_epi8(max);
__m128i boost16 = _mm_set1_epi16(boost);
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
TextureBoostedUv<align>(src + col, dst + col, min8, max8, boost16);
if(width != alignedWidth)
TextureBoostedUv<false>(src + width - A, dst + width - A, min8, max8, boost16);
src += srcStride;
dst += dstStride;
}
}
void TextureBoostedUv(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t boost, uint8_t * dst, size_t dstStride)
{
if(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride))
TextureBoostedUv<true>(src, srcStride, width, height, boost, dst, dstStride);
else
TextureBoostedUv<false>(src, srcStride, width, height, boost, dst, dstStride);
}
template <bool align> SIMD_INLINE void TextureGetDifferenceSum(const uint8_t * src, const uint8_t * lo, const uint8_t * hi,
__m128i & positive, __m128i & negative, const __m128i & mask)
{
const __m128i _src = Load<align>((__m128i*)src);
const __m128i _lo = Load<align>((__m128i*)lo);
const __m128i _hi = Load<align>((__m128i*)hi);
const __m128i average = _mm_and_si128(mask, _mm_avg_epu8(_lo, _hi));
const __m128i current = _mm_and_si128(mask, _src);
positive = _mm_add_epi64(positive, _mm_sad_epu8(_mm_subs_epu8(current, average), K_ZERO));
negative = _mm_add_epi64(negative, _mm_sad_epu8(_mm_subs_epu8(average, current), K_ZERO));
}
template <bool align> void TextureGetDifferenceSum(const uint8_t * src, size_t srcStride, size_t width, size_t height,
const uint8_t * lo, size_t loStride, const uint8_t * hi, size_t hiStride, int64_t * sum)
{
assert(width >= A && sum != NULL);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(lo) && Aligned(loStride) && Aligned(hi) && Aligned(hiStride));
}
size_t alignedWidth = AlignLo(width, A);
__m128i tailMask = ShiftLeft(K_INV_ZERO, A - width + alignedWidth);
__m128i positive = _mm_setzero_si128();
__m128i negative = _mm_setzero_si128();
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
TextureGetDifferenceSum<align>(src + col, lo + col, hi + col, positive, negative, K_INV_ZERO);
if(width != alignedWidth)
TextureGetDifferenceSum<false>(src + width - A, lo + width - A, hi + width - A, positive, negative, tailMask);
src += srcStride;
lo += loStride;
hi += hiStride;
}
*sum = ExtractInt64Sum(positive) - ExtractInt64Sum(negative);
}
void TextureGetDifferenceSum(const uint8_t * src, size_t srcStride, size_t width, size_t height,
const uint8_t * lo, size_t loStride, const uint8_t * hi, size_t hiStride, int64_t * sum)
{
if(Aligned(src) && Aligned(srcStride) && Aligned(lo) && Aligned(loStride) && Aligned(hi) && Aligned(hiStride))
TextureGetDifferenceSum<true>(src, srcStride, width, height, lo, loStride, hi, hiStride, sum);
else
TextureGetDifferenceSum<false>(src, srcStride, width, height, lo, loStride, hi, hiStride, sum);
}
template <bool align> void TexturePerformCompensation(const uint8_t * src, size_t srcStride, size_t width, size_t height,
int shift, uint8_t * dst, size_t dstStride)
{
assert(width >= A && shift > -0xFF && shift < 0xFF && shift != 0);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride));
}
size_t alignedWidth = AlignLo(width, A);
__m128i tailMask = src == dst ? ShiftLeft(K_INV_ZERO, A - width + alignedWidth) : K_INV_ZERO;
if(shift > 0)
{
__m128i _shift = _mm_set1_epi8((char)shift);
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
{
const __m128i _src = Load<align>((__m128i*) (src + col));
Store<align>((__m128i*) (dst + col), _mm_adds_epu8(_src, _shift));
}
if(width != alignedWidth)
{
const __m128i _src = Load<false>((__m128i*) (src + width - A));
Store<false>((__m128i*) (dst + width - A), _mm_adds_epu8(_src, _mm_and_si128(_shift, tailMask)));
}
src += srcStride;
dst += dstStride;
}
}
if(shift < 0)
{
__m128i _shift = _mm_set1_epi8((char)-shift);
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
{
const __m128i _src = Load<align>((__m128i*) (src + col));
Store<align>((__m128i*) (dst + col), _mm_subs_epu8(_src, _shift));
}
if(width != alignedWidth)
{
const __m128i _src = Load<false>((__m128i*) (src + width - A));
Store<false>((__m128i*) (dst + width - A), _mm_subs_epu8(_src, _mm_and_si128(_shift, tailMask)));
}
src += srcStride;
dst += dstStride;
}
}
}
void TexturePerformCompensation(const uint8_t * src, size_t srcStride, size_t width, size_t height,
int shift, uint8_t * dst, size_t dstStride)
{
if(shift == 0)
{
if(src != dst)
Base::Copy(src, srcStride, width, height, 1, dst, dstStride);
return;
}
if(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride))
TexturePerformCompensation<true>(src, srcStride, width, height, shift, dst, dstStride);
else
TexturePerformCompensation<false>(src, srcStride, width, height, shift, dst, dstStride);
}
}
#endif// SIMD_SSE2_ENABLE
}
| 48.605263
| 144
| 0.576997
|
aestesis
|
5a2491b62de6d3e5599c47df6c0db8cbf3952adf
| 2,073
|
cpp
|
C++
|
main_twoflavor.cpp
|
Sam91/vmc_general
|
cb2b0cb103a66307a3d78dbf137582a3ad224f8d
|
[
"MIT"
] | null | null | null |
main_twoflavor.cpp
|
Sam91/vmc_general
|
cb2b0cb103a66307a3d78dbf137582a3ad224f8d
|
[
"MIT"
] | null | null | null |
main_twoflavor.cpp
|
Sam91/vmc_general
|
cb2b0cb103a66307a3d78dbf137582a3ad224f8d
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <iomanip>
#include "lwave2.h"
//#include "amperean.h"
int main(int argc, char *argv[])
{
int req_args = 6;
for(int i=0; i<argc; i++) cout << argv[i] << " ";
cout << endl;
if(argc-1<req_args) {
cout << "Error: incorrect number of arguments\n";
exit(-1);
}
int L = atoi(argv[1]);
lwave2* wf = new lwave2( L );
//amperean* wf = new amperean( L );
//double* dl = new double[4];
//dl[4] = 22.;
//some preparatory configuration of the wave function
//wf->set_lattice( "square" );
//wf->set_lattice( "checkerboard" );
wf->set_lattice( "triangular" );
wf->pars->apx = atoi(argv[2]); //boundary condition in x-direction
wf->pars->apy = atoi(argv[3]);
wf->pars->t1 = (double)atoi(argv[4])/100.; //nearest-neighbor hopping
wf->pars->dd = (double)atoi(argv[5])/100.; //pairing amplitude
// wf->pars->dd0 = (double)atoi(argv[5])/100.; //s-pairing for filled states
wf->pars->phi1 = (double)atoi(argv[6])/100.; //s-pairing for filled states
wf->pars->phi2 = (double)atoi(argv[7])/100.; //s-pairing for filled states
if( argc>=9 ) {
wf->pars->mu = (double)atoi(argv[8])/100.;
wf->pars->t1b = (double)atoi(argv[9])/100.;
wf->pars->t1c = (double)atoi(argv[10])/100.;
} else {
wf->pars->mu = .8;
wf->pars->t1b = wf->pars->t1;
wf->pars->t1c = wf->pars->t1;
}
// wf->pars->r = atoi(argv[6]); // orientation: 0=long axis, 1=short axis
// wf->pars->lth = atoi(argv[7])/100.; //controlling the decay of amperean pairing
// wf->pars->lr1 = atoi(argv[8])/100.;
// wf->pars->lr2 = atoi(argv[9])/100.;
//wf->print();
//create a vmc object and assign the wf
vmc* myvmc = new vmc();
wf->set_mc_length( 300 );
myvmc->set_wf( wf );
wf->findmu();
//wf->create_dd();
//wf->create_ad();
if( argc>=12 ) myvmc->initialize( atoi(argv[11]) ); //number of bins to average over
else myvmc->initialize( 30 ); //number of bins to average over
myvmc->run();
myvmc->calculate_statistics();
// wf->insert_db();
delete myvmc;
delete wf;
return 0;
}
| 25.592593
| 86
| 0.598649
|
Sam91
|
5a29a9fb9ebfe976013020cee8c0125af6ab4f40
| 283
|
cpp
|
C++
|
Source/Platoon/PlatoonCharacter.cpp
|
bernhardrieder/Platoon-AI-Simulation-UE4
|
f5a3062cea090ddaae35fc97209212c8f8b4bdd9
|
[
"Unlicense"
] | 1
|
2018-09-04T19:48:09.000Z
|
2018-09-04T19:48:09.000Z
|
Source/Platoon/PlatoonCharacter.cpp
|
bernhardrieder/Platoon-AI-Simulation
|
f5a3062cea090ddaae35fc97209212c8f8b4bdd9
|
[
"Unlicense"
] | null | null | null |
Source/Platoon/PlatoonCharacter.cpp
|
bernhardrieder/Platoon-AI-Simulation
|
f5a3062cea090ddaae35fc97209212c8f8b4bdd9
|
[
"Unlicense"
] | null | null | null |
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "Platoon.h"
#include "PlatoonCharacter.h"
APlatoonCharacter::APlatoonCharacter()
{
PrimaryActorTick.bCanEverTick = false;
PrimaryActorTick.bStartWithTickEnabled = false;
AActor::SetActorHiddenInGame(true);
}
| 23.583333
| 60
| 0.791519
|
bernhardrieder
|
5a2ae39e781bb0be9e81f6fa5e4c9652c2588bd7
| 721
|
cpp
|
C++
|
code archive/GJ/a024.cpp
|
brianbbsu/program
|
c4505f2b8c0b91010e157db914a63c49638516bc
|
[
"MIT"
] | 4
|
2018-04-08T08:07:58.000Z
|
2021-06-07T14:55:24.000Z
|
code archive/GJ/a024.cpp
|
brianbbsu/program
|
c4505f2b8c0b91010e157db914a63c49638516bc
|
[
"MIT"
] | null | null | null |
code archive/GJ/a024.cpp
|
brianbbsu/program
|
c4505f2b8c0b91010e157db914a63c49638516bc
|
[
"MIT"
] | 1
|
2018-10-29T12:37:25.000Z
|
2018-10-29T12:37:25.000Z
|
/**********************************************************************************/
/* Problem: a024 "所有位數和" from while 迴圈 */
/* Language: C++ */
/* Result: AC (4ms, 184KB) on ZeroJudge */
/* Author: briansu at 2016-08-25 22:23:33 */
/**********************************************************************************/
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
int main()
{
long int n;
cin>>n;
long int m=0;
while(n>0)
{
m+=n%10;
n=floor(n/10);
}
cout<<m;
}
| 27.730769
| 84
| 0.281553
|
brianbbsu
|
5a2dac2d68c6ed1ae3f4fa685a3aaa591922f468
| 466
|
cpp
|
C++
|
LeetCode/InterviewSchool/125. Valid Palindrome.cpp
|
Sowmik23/All-Codes
|
212ef0d940fa84624bb2972a257768a830a709a3
|
[
"MIT"
] | 5
|
2021-02-14T17:48:21.000Z
|
2022-01-24T14:29:44.000Z
|
LeetCode/InterviewSchool/125. Valid Palindrome.cpp
|
Sowmik23/All-Codes
|
212ef0d940fa84624bb2972a257768a830a709a3
|
[
"MIT"
] | null | null | null |
LeetCode/InterviewSchool/125. Valid Palindrome.cpp
|
Sowmik23/All-Codes
|
212ef0d940fa84624bb2972a257768a830a709a3
|
[
"MIT"
] | null | null | null |
class Solution {
public:
bool isPalindrome(string s) {
string str = "";
for(int i=0;i<s.size();i++){
if((s[i]>='A' and s[i]<='Z') or (s[i]>='a' and s[i]<='z') or (s[i]>='0' and s[i]<='9')){
str+=tolower(s[i]);
}
}
// cout<<str<<endl;
for(int i=0;i<str.size()/2;i++){
if(str[i]!=str[str.size()-i-1]) return false;
}
return true;
}
};
| 24.526316
| 100
| 0.38412
|
Sowmik23
|
5a3140d44c0243e438b833f769575bea720da7e6
| 8,090
|
cpp
|
C++
|
packages/cat/tso2Impact/scenarioAggr.cpp
|
USEPA/Water-Security-Toolkit
|
6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb
|
[
"BSD-3-Clause"
] | 3
|
2019-06-10T18:04:14.000Z
|
2020-12-05T18:11:40.000Z
|
packages/cat/tso2Impact/scenarioAggr.cpp
|
USEPA/Water-Security-Toolkit
|
6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb
|
[
"BSD-3-Clause"
] | null | null | null |
packages/cat/tso2Impact/scenarioAggr.cpp
|
USEPA/Water-Security-Toolkit
|
6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb
|
[
"BSD-3-Clause"
] | 2
|
2020-09-24T19:04:14.000Z
|
2020-12-05T18:11:43.000Z
|
/* _________________________________________________________________________
*
* TEVA-SPOT Toolkit: Tools for Designing Contaminant Warning Systems
* Copyright (c) 2008 Sandia Corporation.
* This software is distributed under the BSD License.
* Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
* the U.S. Government retains certain rights in this software.
* For more information, see the README.txt file in the top SPOT directory.
* _________________________________________________________________________
*/
/**
* \file setupIPData.cpp
*
* Creates an input file for the GeneralSP.mod IP model.
*/
#ifdef HAVE_CONFIG_H
#include <teva_config.h>
#endif
#include <utilib/OptionParser.h>
#include <sp/ObjectiveAggr.h>
#include <sp/SPProblem.h>
#include "version.h"
using namespace std;
string dirname(string fullpath, char delimiter = '/')
{
int len = fullpath.length();
int pos = len - 1;
const char *str = fullpath.c_str();
string::reverse_iterator rit(fullpath.rbegin());
while (rit++ != fullpath.rend() && str[pos] != delimiter)
pos--;
pos = pos + 1;
return fullpath.substr(0, pos);
}
string basename(string fullpath, char delimiter = '/')
{
int len = fullpath.length();
int pos = len - 1;
const char *str = fullpath.c_str();
string::reverse_iterator rit(fullpath.rbegin());
while (rit++ != fullpath.rend() && str[pos] != delimiter)
pos--;
pos = pos + 1;
return fullpath.substr(pos, len - pos);
}
void write_aggregated_impact_file(std::string impactInputFileName,
std::string impactOutputFileName,
std::vector<scenario_group>& groups,
std::map<int, int>& group_map)
{
int eventIndex, nnodes;
int num_events = group_map.size();
int nevents2;
int num_aggr_events = groups.size();
std::ifstream in_imp_f(impactInputFileName.c_str());
int delayIndex = read_impact_preamble(in_imp_f, nnodes, 0);
in_imp_f >> eventIndex;
for (int i = 0; i < num_events; i++)
{
std::map<int, double> next_event_impacts;
std::vector<std::pair<int, int> > next_event_sequence;
int cur_index = eventIndex;
eventIndex = read_next_impact(in_imp_f, eventIndex,
next_event_impacts,
next_event_sequence, delayIndex);
int num_impacts = next_event_impacts.size();
int group_num = group_map[cur_index];
cout << "groups[" << group_num << "].ml : " <<
groups[group_num].max_length << endl;
for (int j = 0; j < groups[group_num].max_length; j++)
{
int id = -1;
if (j < next_event_impacts.size())
{
id = next_event_sequence[j].first;
}
if (group_num == 2)
{
}
groups[group_num].impacts[j] +=
next_event_impacts[id];
}
if (group_num == 2)
{
cout << "candidate longest event " << i << endl;
cout << "length: " << next_event_impacts.size() << endl;
cout << "group " << group_num << " max length: " << groups[group_num].max_length
<< endl;
}
if (next_event_impacts.size() == groups[group_num].max_length)
{
for (int j = 0; j < groups[group_num].max_length; j++)
{
groups[group_num].hit_sequence[j] =
next_event_sequence[j].first;
groups[group_num].hit_times[j] =
next_event_sequence[j].second;
}
}
}
std::string impact_dirname = dirname(impactInputFileName);
std::string impact_basename = basename(impactInputFileName);
std::string agImpactOutputFileName;
if (impactOutputFileName == "")
agImpactOutputFileName = impact_dirname + "aggr" + impact_basename;
else
agImpactOutputFileName = impactOutputFileName;
std::string agProbOutputFileName = agImpactOutputFileName + ".prob";
std::ofstream a_imp_f(agImpactOutputFileName.c_str());
std::ofstream a_prob_f(agProbOutputFileName.c_str());
a_imp_f << nnodes << endl;
a_imp_f << "1 0" << endl; // only support delay of 0 in current
// impact format; delays implemented in
// setupIPData, randomsample
for (int i = 0; i < num_aggr_events; i++)
{
// assuming uniform original event probabilities for now
groups[i].event_prob = groups[i].num_events / (double)num_events;
for (int j = 0; j < groups[i].max_length; j++)
{
groups[i].impacts[j] /= groups[i].num_events;
}
for (int j = 0; j < groups[i].max_length; j++)
{
int hitnode = groups[i].hit_sequence[j];
int hittime = groups[i].hit_times[j];
a_imp_f << i + 1 << " " << hitnode
<< " " << hittime
<< " " << groups[i].impacts[j] << std::endl;
}
a_prob_f << i + 1 << " " << groups[i].event_prob << endl;
}
a_imp_f.close();
a_prob_f.close();
}
/// The main routine for setupIPData
int main(int argc, char **argv)
{
try
{
string impactInputFile;
string impactOutputFile;
int numEvents = 0;
utilib::OptionParser options;
options.add_usage("scenarioAggr [options...] <impact-file>");
options.description = "A command to aggregate incidents in an impact file.";
std::string version = create_version("scenarioAggr", __DATE__, __TIME__);
options.version(version);
options.add("numEvents", numEvents, "The number of events before scenario aggregation.");
options.add("out", impactOutputFile, "The output impact filename.");
utilib::OptionParser::args_t args = options.parse_args(argc, argv);
if (options.help_option())
{
options.write(std::cout);
exit(1);
}
if (options.version_option())
{
options.print_version(std::cout);
exit(1);
}
if (args.size() < 2)
{
options.write(std::cerr);
return 1;
}
ifstream in_imp_f(args[1].c_str());
if (!in_imp_f)
EXCEPTION_MNGR(runtime_error, "Bad filename " << args[1]);
SPProblem info;
VecTrie<int, std::vector<int> > theScenarioAggrTrie;
//
// Read in the problem data
//
impactInputFile = args[1];
int eventIndex;
int nnodes;
int delayIndex = read_impact_preamble(in_imp_f, nnodes, 0);
in_imp_f >> eventIndex;
for (int i = 0; i < numEvents; i++)
{
std::map<int, double> next_event_impacts;
std::vector<std::pair<int, int> > next_event_sequence;
int cur_event = eventIndex;
eventIndex = read_next_impact(in_imp_f, eventIndex,
next_event_impacts,
next_event_sequence, delayIndex);
int num_impacts = next_event_impacts.size();
vector<int> hit_list;
for (int i = 0; i < int(next_event_impacts.size() - 1); i++)
{
// don't include dummy
hit_list.push_back(next_event_sequence[i].first);
}
VecTrieKey<int> key(hit_list);
VecTrieNode<int, vector<int> >* n = theScenarioAggrTrie.getnode(key);
if (!n)
{
std::vector<int> scenario_list;
theScenarioAggrTrie.insert(key, scenario_list);
}
else if (!n->hasdata())
{
std::vector<int> scenario_list;
n->setdata(scenario_list);
}
std::vector<int>& scenario_list = theScenarioAggrTrie.getdata(key);
scenario_list.push_back(cur_event);
}
in_imp_f.close();
std::vector<int> key;
std::vector<int> spine_scenarios;
std::vector<scenario_group> groups;
int num_groups = 0;
std::map<int, int> group_map;
ScenarioAggrVisitor vis(key, spine_scenarios, groups, group_map);
theScenarioAggrTrie.dfs(vis);
write_aggregated_impact_file(impactInputFile, impactOutputFile, groups, group_map);
}
STD_CATCH(;)
return 0;
}
| 33.292181
| 95
| 0.603461
|
USEPA
|
5a32da1f1584d661f8cb825a427c9278b45bb704
| 222
|
cpp
|
C++
|
AudioElement.cpp
|
OneNot/SFML-PacGuy
|
d9eb17632e43335282c514027bb93879357bfa74
|
[
"Unlicense"
] | null | null | null |
AudioElement.cpp
|
OneNot/SFML-PacGuy
|
d9eb17632e43335282c514027bb93879357bfa74
|
[
"Unlicense"
] | null | null | null |
AudioElement.cpp
|
OneNot/SFML-PacGuy
|
d9eb17632e43335282c514027bb93879357bfa74
|
[
"Unlicense"
] | null | null | null |
#include "AudioElement.h"
AudioElement::AudioElement(std::string file)
{
if (!buffer.loadFromFile(file))
{
std::cout << "FAILED TO LOAD: " << file << std::endl;
//todo: error handling
}
sound.setBuffer(buffer);
}
| 18.5
| 55
| 0.666667
|
OneNot
|
5a335c34ab3440d624cdf45ee4ead7a9672a0dfb
| 571
|
cpp
|
C++
|
garbage/class_imple.cpp
|
wolfdale/Spaghetti-code
|
9e395345e1420b9db021b21131601191a869db1d
|
[
"MIT"
] | 1
|
2018-05-18T16:07:11.000Z
|
2018-05-18T16:07:11.000Z
|
garbage/class_imple.cpp
|
wolfdale/Spaghetti-code
|
9e395345e1420b9db021b21131601191a869db1d
|
[
"MIT"
] | 5
|
2015-12-03T16:12:38.000Z
|
2020-05-05T14:07:00.000Z
|
garbage/class_imple.cpp
|
wolfdale/Spaghetti-code
|
9e395345e1420b9db021b21131601191a869db1d
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
class item
{
int number;
float cost;
public:
void getdata(int a,float b); //Prototype decleration
void putdata(void)
{
cout<<"Number:"<<number<<"\n";
cout<<"Cost :"<<cost<<"\n";
}
};
//*************Member Function Definition******************//
void item::getdata(int a, float b)
{
number = a; // Private variables directly used
cost = b;
}
int main()
{
item x; //Object Declaration
cout<<"OBJECT X" << "\n";
x.getdata(5,5.8);
x.putdata();
return 0;
}
| 15.026316
| 61
| 0.537653
|
wolfdale
|
5a35d44b96820ecf83dd807b0a7b21df31f3efca
| 2,027
|
cc
|
C++
|
Codeforces/339 Division 1/Problem B/B.cc
|
VastoLorde95/Competitive-Programming
|
6c990656178fb0cd33354cbe5508164207012f24
|
[
"MIT"
] | 170
|
2017-07-25T14:47:29.000Z
|
2022-01-26T19:16:31.000Z
|
Codeforces/339 Division 1/Problem B/B.cc
|
navodit15/Competitive-Programming
|
6c990656178fb0cd33354cbe5508164207012f24
|
[
"MIT"
] | null | null | null |
Codeforces/339 Division 1/Problem B/B.cc
|
navodit15/Competitive-Programming
|
6c990656178fb0cd33354cbe5508164207012f24
|
[
"MIT"
] | 55
|
2017-07-28T06:17:33.000Z
|
2021-10-31T03:06:22.000Z
|
#include <bits/stdc++.h>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define LET(x, a) __typeof(a) x(a)
#define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define func __FUNCTION__
#define line __LINE__
using namespace std;
typedef long long ll;
template<typename S, typename T>
ostream& operator<<(ostream& out, pair<S, T> const& p){out<<'('<<p.fi<<", "<<p.se<<')'; return out;}
template<typename T>
ostream& operator<<(ostream& out, vector<T> const & v){
ll l = v.size(); for(ll i = 0; i < l-1; i++) out<<v[i]<<' '; if(l>0) out<<v[l-1]; return out;}
void tr(){cout << endl;}
template<typename S, typename ... Strings>
void tr(S x, const Strings&... rest){cout<<x<<' ';tr(rest...);}
const ll N = 100100;
ll n, A, cf, cm, m;
vector<pair<ll, ll> > u, v;
ll ans[N], sum[N];
int main(){ _
cin >> n >> A >> cf >> cm >> m;
for(int i = 0; i < n; i++){
ll x; cin >> x;
u.pb(mp(x,i));
}
sort(u.begin(), u.end());
for(int i = 0; i < n; i++){
sum[i+1] = sum[i] + u[i].fi;
}
v = u;
ll force = -1, ansi = -1, ansm = -1;
for(int i = 0, j = 0; i <= n; i++){
ll cost = 0, tmp = 0;
cost = A*(n-i) - (sum[n] - sum[i]);
if(cost > m) continue;
tmp += (n-i)*cf;
ll rem = m - cost;
while(j < i and j*v[j].fi - sum[j] <= rem){
j++;
}
ll mn;
if(j > 0){
mn = min(A, (rem + sum[j])/j);
}
else{
mn = A;
}
tmp += mn*cm;
if(tmp > force){
force = tmp;
ansi = i;
ansm = mn;
}
}
cout << force << endl;
for(int i = 0; i < n; i++){
if(i < ansi){
v[i].fi = max(v[i].fi, ansm);
}
else v[i].fi = A;
ans[v[i].se] = v[i].fi;
}
for(int i = 0; i < n; i++){
cout << ans[i] << ' ';
}
cout << endl;
return 0;
}
| 19.304762
| 100
| 0.519487
|
VastoLorde95
|
5a36e0bd1c379ad2d5982af7133e70f963b417cd
| 11,042
|
cpp
|
C++
|
Milestone 4/Milestone 4/Milestone 4/Main.cpp
|
Shantanu-Chauhan/RigidBody
|
638e7fc248cccdfca21a12c6c80b2d9b7b23e7e1
|
[
"Apache-2.0"
] | 1
|
2020-09-26T11:59:55.000Z
|
2020-09-26T11:59:55.000Z
|
Milestone 4/Milestone 4/Milestone 4/Main.cpp
|
Shantanu-Chauhan/RigidBody
|
638e7fc248cccdfca21a12c6c80b2d9b7b23e7e1
|
[
"Apache-2.0"
] | null | null | null |
Milestone 4/Milestone 4/Milestone 4/Main.cpp
|
Shantanu-Chauhan/RigidBody
|
638e7fc248cccdfca21a12c6c80b2d9b7b23e7e1
|
[
"Apache-2.0"
] | null | null | null |
/* Start Header -------------------------------------------------------
Copyright (C) 2018 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the prior
written consent of DigiPen Institute of Technology is prohibited.
File Name: Main.cpp
Purpose: Implementing Game Engine Architecture
Language: C++ language
Platform: Visual Studio Community 2017 - Visual C++ 15.8.2, Windows 10
Project: CS529_shantanu.chauhan_milestone1
Author: Shantanu Chauhan, shantanu.chauhan, 60002518
Creation date: 18th September 2018
- End Header --------------------------------------------------------*/
#include<GL/glew.h>
#include <SDL.h>
#include<SDL_opengl.h>
#include "stdio.h"
#include"src/Manager/Input Manager.h"
#include"src/Frame Rate Controller.h"
#include"Windows.h"
#include<iostream>
#include"src/Global_Header.h"
#include"src/Manager/Resource Manager.h"
#include"src/Manager/Game Object Manager.h"
#include"src/Manager/Event Manager.h"
#include"src/Game Object.h"
#include"Components/Sprite.h"
#include"Components/Transform.h"
#include"Components/Controller.h"
#include"Components/Component.h"
#include"src/ObjectFactory.h"
#include"Components/Body.h"
#include"src/Manager/PhysicsManager.h"
#include"src/Manager/CollisionManager.h"
#include"src/OpenGL/VertexBuffer.h"
#include"src/OpenGL/IndexBuffer.h"
#include"src/OpenGL/VertexArray.h"
#include"src/OpenGL/VertexBufferLayout.h"
#include"src/OpenGL/Texture.h"
#include"src/OpenGL/Shader.h"
#include"src/OpenGL/Renderer.h"
#include"glm/glm.hpp"
#include"glm/gtc/matrix_transform.hpp"
#include"imgui/imgui.h"
#include "imgui/imconfig.h"
#include"imgui/imgui_impl_sdl.h"
#include "imgui/imgui_impl_opengl3.h"
#include"src/Camera.h"
bool appIsRunning = true;
FrameRateController *gpFRC = nullptr;
Input_Manager *gpInputManager=nullptr;
ObjectFactory *gpGameObjectFactory = nullptr;
ResourceManager *gpResourceManager = nullptr;
GameObjectManager *gpGameObjectManager = nullptr;
PhysicsManager *gpPhysicsManager = nullptr;
CollisionManager *gpCollisionManager = nullptr;
EventManager *gpEventManager = nullptr;
Renderer *gpRenderer=nullptr;
Shader* shader=nullptr;
Camera *gpCamera = nullptr;
FILE _iob[] = { *stdin, *stdout, *stderr };
#define MAX_FRAME_RATE 60
extern "C" FILE * __cdecl __iob_func(void)
{
return _iob;
}
#pragma comment(lib, "legacy_stdio_definitions.lib")
int main(int argc, char* args[])
{
if (AllocConsole())
{
FILE* file;
freopen_s(&file, "CONOUT$", "wt", stdout);
freopen_s(&file, "CONOUT$", "wt", stderr);
freopen_s(&file, "CONOUT$", "wt", stdin);
SetConsoleTitle("CS550(MADE IT SOMEHOW!YES!) :-)");
}
SDL_Window *pWindow;
SDL_Surface *pWindowSurface;
int error = 0;
SDL_Surface *pImage = NULL;
// Initialize SDL
gpFRC = new FrameRateController(MAX_FRAME_RATE);//Paraeter is the FPS
gpInputManager =new Input_Manager();
gpGameObjectFactory = new ObjectFactory();
gpResourceManager = new ResourceManager();
gpGameObjectManager = new GameObjectManager();
gpCollisionManager = new CollisionManager();
gpEventManager = new EventManager();
gpRenderer = new Renderer();
gpCamera = new Camera(5, 10, 20, 0, 1, 0, -90, -15);
if((error = SDL_Init( SDL_INIT_VIDEO )) < 0 )
{
printf("Couldn't initialize SDL, error %i\n", error);
return 1;
}
pWindow = SDL_CreateWindow("CS550(MADE IT SOMEHOW!!!!) :-)", // window title
10, // initial x position
25, // initial y position
SCREEN_WIDTH, // width, in pixels
SCREEN_HEIGHT, // height, in pixels
SDL_WINDOW_OPENGL);
// Check that the window was successfully made
if (NULL == pWindow)
{
// In the event that the window could not be made...
printf("Could not create window: %s\n", SDL_GetError());
return 1;
}
auto OpenGL_context = SDL_GL_CreateContext(pWindow);
if (glewInit() != GLEW_OK)
printf(" Error in glew init\n");
pWindowSurface = SDL_GetWindowSurface(pWindow);
if (!pWindowSurface)
{
printf(SDL_GetError());
}
gpGameObjectFactory->LoadLevel("Title_Screenp.txt",false);
float positions[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,//* 0
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,// 1
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//** 2
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//** 3
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,// 4
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,//* 5
//
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//*** 6
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,// 7
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,// 8
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,// 9
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,// 10
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//*** 11
//
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,//
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,//
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,//
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
//
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,//
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f //
};
//vid 9
unsigned int indices[] = {
0,1,2,
3,4,5,
6,7,8,
9,10,11,
12,13,14,
15,16,17,
18,19,20,
21,22,23,
24,25,26,
27,28,29,
30,31,32,
33,34,35,
};
//IMGUI
ImGui::CreateContext();
ImGui_ImplSDL2_InitForOpenGL(pWindow, OpenGL_context);
ImGui_ImplOpenGL3_Init("#version 330");
std::cout << glGetString(GL_RENDERER) << std::endl;
ImGui::StyleColorsDark();
//IMGUI
GLCall(glEnable(GL_BLEND));
glEnable(GL_DEPTH_TEST);
GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
{
VertexArray va;
VertexBuffer vb(positions, 36 * 5 * sizeof(float));
VertexBufferLayout layout;
layout.Push<float>(3);
layout.Push<float>(2);
va.AddBuffer(vb, layout);
IndexBuffer ib(indices, 36);
//------------------------------------------------------------------------------------
//Writing down the shader
shader = new Shader("src/res/shaders/Basic.shader");
shader->Bind();
//------------------------------------------------------------------------------------
gpPhysicsManager = new PhysicsManager();//Keep this after level loading so that bodies can be pushed into the broad phase
// Game loop
bool reverse = false;
bool pause = true;
float deltaTime = 0.016f;
bool debug = false;
bool step = false;
while (true == appIsRunning)
{
gpFRC->FrameStart();
gpInputManager->Update();
gpRenderer->Clear();
GLCall(glClearColor(0.5, 0.5, 0.5, 1.0));
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(pWindow);
ImGui::NewFrame();
if (gpInputManager->isTriggered(SDL_SCANCODE_SPACE))
pause = !pause;
if (gpInputManager->isTriggered(SDL_SCANCODE_R))//reverse time(this doesnt work)
{
pause = false;
reverse = !reverse;
}
if (gpInputManager->isTriggered(SDL_SCANCODE_O))//debug toggle
{
debug = !debug;
}
float frameTime = (float)gpFRC->GetFrameTime();
frameTime = frameTime / 1000.0f;
gpCamera->Update(gpInputManager,frameTime);
ImGui::Begin("MADE BY SHANTANU CHAUHAN!");
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("To move the camera use the arrow keys");
ImGui::Text("To rotate the camera right click and move the mouse");
ImGui::Text("Press 'O'(not zero! but 'o') to draw the mesh of the dynamicAABB tree");
ImGui::Text("Press '1' to get the BALL AND SOCKET JOINT");
ImGui::Text("Press '2' to get the big stack of cubes");
ImGui::Text("Press '3' to get the single stack of 10 cubes");
ImGui::Text("Press '4' to get HINGE JOINT");
ImGui::Text("Press '5' to get the BRIDGE");
ImGui::Text("Press 'SPACE' to pause/resume the simulation");
ImGui::Text("Press 'Enter' to step the physics update");
ImGui::Text("Press 'Escape' to close the application");
ImGui::End();
if (gpInputManager->isTriggered(SDL_SCANCODE_RETURN))//step
{
step = true;
frameTime = deltaTime;
}
if (gpInputManager->isTriggered(SDL_SCANCODE_1))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", false);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_2))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt",true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_3))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_4))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_5))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_6))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
gpEventManager->Update(frameTime);
for (int i = 0; i < static_cast<int>(gpGameObjectManager->mGameobjects.size()); ++i)
{
gpGameObjectManager->mGameobjects[i]->Update();
}
if (step)
{
pause = false;
}
if(!pause)
gpPhysicsManager->Update(1/60.0f);//Physics update
if (step)
{
pause = true;
step = false;
}
//Dubug
for (auto go : gpGameObjectManager->mGameobjects)
{
Body *pBody = static_cast<Body*>(go->GetComponent(BODY));
//ImGui::SetNextWindowPosCenter(ImGuiCond_Once);
ImGui::Begin("Cubes data(You can move them but identifying which is which is hard)");
ImGui::PushID(pBody);
ImGui::SliderFloat3("Location:", &pBody->mPos.x, -5.0f, 5.0f);
ImGui::SliderFloat4("Quat:", &pBody->quaternion.x, -1.0f, 1.0f);
ImGui::SliderFloat4("Vel:", &pBody->mVel.x, -10.0f, 10.0f);
ImGui::SliderFloat4("angular", &pBody->AngularVelocity.x, -2.0f, 2.0f);
//ImGui::Text("Angular - x-%f,y-%f,z-%f", pBody->AngularVelocity.x, pBody->AngularVelocity.y, pBody->AngularVelocity.z);
ImGui::PopID();
ImGui::End();
}
//Draw All the game objects
gpGameObjectManager->DrawObjectDraw(va, ib, shader, debug);
//Debug
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(pWindow);
gpFRC->FrameEnd();
}
}
delete gpFRC;
delete shader;
delete gpRenderer;
delete gpEventManager;
delete gpCollisionManager;
delete gpPhysicsManager;
delete gpGameObjectManager;
delete gpResourceManager;
delete gpGameObjectFactory;
delete gpInputManager;
SDL_DestroyWindow(pWindow);
SDL_Quit();
return 0;
}
| 29.134565
| 125
| 0.642003
|
Shantanu-Chauhan
|
5a3a649a9888e3e73c4dd200603fd798b553f153
| 711
|
hpp
|
C++
|
include/mh/network/server.hpp
|
overworks/MhGameLib
|
87973e29633ed09a3fa51eb27ea7fc8af5e9d71b
|
[
"MIT"
] | null | null | null |
include/mh/network/server.hpp
|
overworks/MhGameLib
|
87973e29633ed09a3fa51eb27ea7fc8af5e9d71b
|
[
"MIT"
] | null | null | null |
include/mh/network/server.hpp
|
overworks/MhGameLib
|
87973e29633ed09a3fa51eb27ea7fc8af5e9d71b
|
[
"MIT"
] | null | null | null |
#ifndef _MH_NETWORK_SERVER_HPP_
#define _MH_NETWORK_SERVER_HPP_
/*
* 서버 인터페이스
*/
#include <mh/types.hpp>
#define SERVER_INTERFACE(name)\
name();\
virtual ~name();\
virtual bool initialize( u32 address, u16 port );\
namespace Mh
{
namespace Network
{
class Socket;
// 전송 프로토콜
enum TP // Transfort protocol
{
TP_TCP, // 일단은 이 두개만...
TP_UDP,
};
struct ServerDesc
{
u32 addrees; // 서버 주소
u16 port; // 포트
TP protocol; // 전송 프로토콜(TCP, UDP)
};
class Server
{
public:
Server() {}
virtual ~Server() {}
virtual bool initialize( u32 address, u16 port ) = 0;
};
} // namespace Mh::Network
} // namespace Mh
#endif /* _MH_NETWORK_SERVER_HPP_ */
| 14.8125
| 56
| 0.618847
|
overworks
|
5a3c7f000ab12b0e63964ccd7e36f5e481fcae1a
| 1,246
|
cc
|
C++
|
libs/fel/src/fel/file.cc
|
madeso/fel
|
2ec89ce0195545385125d0a02c90aaa65492c1a9
|
[
"MIT"
] | 3
|
2019-12-15T10:29:15.000Z
|
2021-07-24T19:39:29.000Z
|
libs/fel/src/fel/file.cc
|
madeso/fel
|
2ec89ce0195545385125d0a02c90aaa65492c1a9
|
[
"MIT"
] | null | null | null |
libs/fel/src/fel/file.cc
|
madeso/fel
|
2ec89ce0195545385125d0a02c90aaa65492c1a9
|
[
"MIT"
] | null | null | null |
#include "fel/file.h"
#include <sstream>
#include <iostream>
#include <fstream>
#include <cassert>
namespace fel
{
File::File(const std::string& a_filename, const std::string& a_content)
: filename(a_filename)
, data(a_content)
{
}
FilePointer::FilePointer(const File& a_file)
: file(a_file)
{
}
bool
FilePointer::HasMore() const
{
return next_index < file.data.size();
}
char
FilePointer::Read()
{
if(next_index < file.data.size())
{
const auto read = file.data[next_index];
next_index += 1;
if(read == '\n')
{
location.line += 1;
location.column = 0;
}
else
{
location.column += 1;
}
return read;
}
else
{
return 0;
}
}
char
FilePointer::Peek(std::size_t advance) const
{
// assert(next_index > 0);
const auto index = next_index + advance - 1;
if(index < file.data.size())
{
return file.data[index];
}
else
{
return 0;
}
}
}
| 17.549296
| 75
| 0.457464
|
madeso
|
5a3d24d871e1bc144f1d6cafb6f1a155356dffbe
| 4,910
|
cpp
|
C++
|
src/Structs.Core.cpu/Collections/BitArray.cpp
|
Grimace1975/gpustructs
|
549f32c96d4df6aafcb38cc063a8cd516512883b
|
[
"MIT"
] | null | null | null |
src/Structs.Core.cpu/Collections/BitArray.cpp
|
Grimace1975/gpustructs
|
549f32c96d4df6aafcb38cc063a8cd516512883b
|
[
"MIT"
] | null | null | null |
src/Structs.Core.cpu/Collections/BitArray.cpp
|
Grimace1975/gpustructs
|
549f32c96d4df6aafcb38cc063a8cd516512883b
|
[
"MIT"
] | null | null | null |
#ifndef CORE_H
# include "..\..\..\inc\System\Core.h"
#endif
#include "BitArray.hpp"
#include <string.h>
using namespace Structs;
namespace Structs { namespace Collections {
BitArray::BitArray(uint size)
{
_size = size;
}
void BitArray::Destroy(BitArray &p)
{
if (&p == nullptr)
return;
if (p._divisor != 0)
for (uint i = 0; i < BITVEC_NPTR; i++)
Destroy(*p.u.Sub[i]);
}
uint BitArray::getLength() { return _size; }
bool BitArray::Get(uint index)
{
if (index == 0 || index > _size)
return false;
index--;
BitArray* p = this;
while (p->_divisor != 0)
{
uint bin = index / p->_divisor;
index %= p->_divisor;
p = p->u.Sub[bin];
if (p == nullptr) return false;
}
if (p->_size <= BITVEC_NBIT)
return ((p->u.Bitmap[index / BITVEC_SZELEM] & (1 << (int)(index & (BITVEC_SZELEM - 1)))) != 0);
uint h = BITVEC_HASH(index++);
while (p->u.Hash[h] != 0)
{
if (p->u.Hash[h] == index) return true;
h = (h + 1) % BITVEC_NINT;
}
return false;
}
RC BitArray::Set(uint index)
{
Debug_Assert(index > 0);
Debug_Assert(index <= _size);
index--;
BitArray *p = this;
while (p->_size > BITVEC_NBIT && p->_divisor != 0)
{
uint bin = index / p->_divisor;
index %= p->_divisor;
if (p->u.Sub[bin] == nullptr)
p->u.Sub[bin] = new BitArray(p->_divisor);
p = p->u.Sub[bin];
}
if (p->_size <= BITVEC_NBIT)
{
p->u.Bitmap[index / BITVEC_SZELEM] |= (byte)(1 << (int)(index & (BITVEC_SZELEM - 1)));
return RC::OK;
}
uint h = BITVEC_HASH(index++);
// if there wasn't a hash collision, and this doesn't completely fill the hash, then just add it without worring about sub-dividing and re-hashing.
if (p->u.Hash[h] == 0)
if (p->_set < (BITVEC_NINT - 1))
goto bitvec_set_end;
else
goto bitvec_set_rehash;
// there was a collision, check to see if it's already in hash, if not, try to find a spot for it
do
{
if (p->u.Hash[h] == index) return RC::OK;
h++;
if (h >= BITVEC_NINT) h = 0;
} while (p->u.Hash[h] != 0);
// we didn't find it in the hash. h points to the first available free spot. check to see if this is going to make our hash too "full".
bitvec_set_rehash:
if (p->_set >= BITVEC_MXHASH)
{
uint* values = new uint[BITVEC_NINT];
memcpy(values, p->u.Hash, sizeof(p->u.Hash));
memset(p->u.Sub, 0, sizeof(p->u.Sub));
p->_divisor = (uint)((p->_size + BITVEC_NPTR - 1) / BITVEC_NPTR);
RC rc = p->Set(index);
for (uint j = 0; j < BITVEC_NINT; j++)
if (values[j] != 0) rc |= p->Set(values[j]);
return rc;
}
bitvec_set_end:
p->_set++;
p->u.Hash[h] = index;
return RC::OK;
}
void BitArray::Clear(uint index, uint buffer[])
{
Debug_Assert(index > 0);
index--;
BitArray* p = this;
while (p->_divisor != 0)
{
uint bin = index / p->_divisor;
index %= p->_divisor;
p = p->u.Sub[bin];
if (p == nullptr) return;
}
if (p->_size <= BITVEC_NBIT)
p->u.Bitmap[index / BITVEC_SZELEM] &= (byte)~((1 << (int)(index & (BITVEC_SZELEM - 1))));
else
{
uint* values = buffer;
memcpy(values, p->u.Hash, sizeof(p->u.Hash));
memset(p->u.Hash, 0, sizeof(p->u.Hash));
p->_set = 0;
for (uint j = 0; j < BITVEC_NINT; j++)
if (values[j] != 0 && values[j] != (index + 1))
{
uint h = BITVEC_HASH(values[j] - 1);
p->_set++;
while (p->u.Hash[h] != 0)
{
h++;
if (h >= BITVEC_NINT) h = 0;
}
p->u.Hash[h] = values[j];
}
}
}
}}
| 36.102941
| 160
| 0.405906
|
Grimace1975
|
5a3dba1ad0707e8f2523f50885675d3e4a54b7bb
| 1,088
|
cpp
|
C++
|
Tutorials/Week 3/Solutions/Office.cpp
|
JamesMarino/CSCI204
|
17b2c44252d1be40214831c6e7e0c2b71848f500
|
[
"MIT"
] | null | null | null |
Tutorials/Week 3/Solutions/Office.cpp
|
JamesMarino/CSCI204
|
17b2c44252d1be40214831c6e7e0c2b71848f500
|
[
"MIT"
] | null | null | null |
Tutorials/Week 3/Solutions/Office.cpp
|
JamesMarino/CSCI204
|
17b2c44252d1be40214831c6e7e0c2b71848f500
|
[
"MIT"
] | null | null | null |
// Office.cpp
// Static field holds rent due date for an office - rents are due on the 1st
#include <iostream>
#include <string>
using namespace std;
class Office
{
private:
int officeNum;
string tenant;
int rent;
static int rentDueDate;
public:
void setOfficeData(int, string, int);
static void showRentDueDate();
void showOffice();
};
int Office::rentDueDate = 1;
void Office::setOfficeData (int num, string occupant, int rent)
{
this->officeNum = num;
this->tenant = occupant;
this->rent = rent;
}
void Office::showOffice ()
{
cout << "Office " << this->officeNum << " is occupied by " << this->tenant << "." << endl;
cout << "The rent, $" << this->rent << " is due on day " << rentDueDate << " of the month." << endl;
cout << "ALL rents are due on the day " << rentDueDate << " of the month." << endl;
}
void Office::showRentDueDate ()
{
cout << "All rents are due on day " << rentDueDate << " of the month." << endl;
}
int main()
{
Office myOffice;
myOffice.setOfficeData(234, "Dr. Smith", 450);
Office::showRentDueDate();
myOffice.showOffice();
}
| 21.76
| 101
| 0.654412
|
JamesMarino
|
5a3e900a0a703723b1b7bd32ddda0acae6b32857
| 2,637
|
hpp
|
C++
|
indexer/covered_object.hpp
|
mapsme/geocore
|
346fceb020cd909b37706ab6ad454aec1a11f52e
|
[
"Apache-2.0"
] | 13
|
2019-09-16T17:45:31.000Z
|
2022-01-29T15:51:52.000Z
|
indexer/covered_object.hpp
|
mapsme/geocore
|
346fceb020cd909b37706ab6ad454aec1a11f52e
|
[
"Apache-2.0"
] | 37
|
2019-10-04T00:55:46.000Z
|
2019-12-27T15:13:19.000Z
|
indexer/covered_object.hpp
|
mapsme/geocore
|
346fceb020cd909b37706ab6ad454aec1a11f52e
|
[
"Apache-2.0"
] | 13
|
2019-10-02T15:03:58.000Z
|
2020-12-28T13:06:22.000Z
|
#pragma once
#include "geometry/point2d.hpp"
#include "geometry/polygon.hpp"
#include "geometry/rect2d.hpp"
#include "coding/geometry_coding.hpp"
#include "base/buffer_vector.hpp"
#include "base/geo_object_id.hpp"
#include <cstdint>
#include <vector>
namespace indexer
{
// Class for intermediate objects used to build CoveringIndex.
class CoveredObject
{
public:
CoveredObject() = default;
// Decodes id stored in CoveringIndex. See GetStoredId().
static base::GeoObjectId FromStoredId(uint64_t storedId)
{
return base::GeoObjectId(storedId >> 2 | storedId << 62);
}
// We need CoveringIndex object id to be at most numeric_limits<int64_t>::max().
// We use incremental encoding for ids and need to keep ids of close object close if it is possible.
// To ensure it we move two leading bits which encodes object type to the end of id.
uint64_t GetStoredId() const { return m_id << 2 | m_id >> 62; }
void Deserialize(char const * data);
template <typename ToDo>
void ForEachPoint(ToDo && toDo) const
{
for (auto const & p : m_points)
toDo(p);
}
template <typename ToDo>
void ForEachTriangle(ToDo && toDo) const
{
for (size_t i = 2; i < m_triangles.size(); i += 3)
toDo(m_triangles[i - 2], m_triangles[i - 1], m_triangles[i]);
}
void SetId(uint64_t id)
{
m_id = id;
}
void SetPoints(buffer_vector<m2::PointD, 32> && points)
{
m_points = std::move(points);
}
void SetTriangles(buffer_vector<m2::PointD, 32> && triangles)
{
m_triangles = std::move(triangles);
}
void SetForTesting(uint64_t id, m2::PointD point)
{
m_id = id;
m_points.clear();
m_points.push_back(point);
}
void SetForTesting(uint64_t id, m2::RectD rect)
{
m_id = id;
m_points.clear();
m_points.push_back(rect.LeftBottom());
m_points.push_back(rect.RightBottom());
m_points.push_back(rect.RightTop());
m_points.push_back(rect.LeftTop());
buffer_vector<m2::PointD, 32> strip;
auto const index = FindSingleStrip(
m_points.size(), IsDiagonalVisibleFunctor<buffer_vector<m2::PointD, 32>::const_iterator>(
m_points.begin(), m_points.end()));
MakeSingleStripFromIndex(index, m_points.size(),
[&](size_t i) { strip.push_back(m_points[i]); });
serial::StripToTriangles(strip.size(), strip, m_triangles);
}
private:
uint64_t m_id = 0;
buffer_vector<m2::PointD, 32> m_points;
// m_triangles[3 * i], m_triangles[3 * i + 1], m_triangles[3 * i + 2] form the i-th triangle.
buffer_vector<m2::PointD, 32> m_triangles;
};
} // namespace indexer
| 26.908163
| 102
| 0.668563
|
mapsme
|
5a41d85552d1170f10241f9d4566dad233198f36
| 2,275
|
cpp
|
C++
|
cctbx/adp_restraints/fixed_u_eq_adp_bpl.cpp
|
rimmartin/cctbx_project
|
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
|
[
"BSD-3-Clause-LBNL"
] | 155
|
2016-11-23T12:52:16.000Z
|
2022-03-31T15:35:44.000Z
|
cctbx/adp_restraints/fixed_u_eq_adp_bpl.cpp
|
rimmartin/cctbx_project
|
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
|
[
"BSD-3-Clause-LBNL"
] | 590
|
2016-12-10T11:31:18.000Z
|
2022-03-30T23:10:09.000Z
|
cctbx/adp_restraints/fixed_u_eq_adp_bpl.cpp
|
rimmartin/cctbx_project
|
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
|
[
"BSD-3-Clause-LBNL"
] | 115
|
2016-11-15T08:17:28.000Z
|
2022-02-09T15:30:14.000Z
|
#include <cctbx/boost_python/flex_fwd.h>
#include <boost/python/def.hpp>
#include <boost/python/class.hpp>
#include <boost/python/args.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/copy_const_reference.hpp>
#include <boost/python/return_internal_reference.hpp>
#include <boost/python/return_by_value.hpp>
#include <scitbx/array_family/boost_python/shared_wrapper.h>
#include <cctbx/adp_restraints/fixed_u_eq_adp.h>
#include <scitbx/boost_python/container_conversions.h>
namespace cctbx { namespace adp_restraints {
namespace {
struct fixed_u_eq_adp_proxy_wrappers {
typedef fixed_u_eq_adp_proxy w_t;
static void wrap() {
using namespace boost::python;
class_<w_t, bases<adp_restraint_proxy<1> > >
("fixed_u_eq_adp_proxy", no_init)
.def(init<
af::tiny<unsigned, 1> const &,
double,
double>(
(arg("i_seqs"),
arg("weight"),
arg("u_eq_ideal"))))
.def_readonly("u_eq_ideal", &w_t::u_eq_ideal)
;
{
scitbx::af::boost_python::shared_wrapper<w_t>::wrap(
"shared_fixed_u_eq_adp_proxy");
}
}
};
struct fixed_u_eq_adp_wrappers {
typedef fixed_u_eq_adp w_t;
static void wrap() {
using namespace boost::python;
typedef return_value_policy<return_by_value> rbv;
class_<w_t, bases<adp_restraint_base_1<1> > >
("fixed_u_eq_adp", no_init)
.def(init<
scitbx::sym_mat3<double> const &,
double,
double>(
(arg("u_cart"),
arg("weight"),
arg("u_eq_ideal"))))
.def(init<
double,
double,
double>(
(arg("u_iso"),
arg("weight"),
arg("u_eq_ideal"))))
.def(init<
adp_restraint_params<double> const &,
fixed_u_eq_adp_proxy const &>(
(arg("params"),
arg("proxy"))))
.def_readonly("u_eq_ideal", &w_t::u_eq_ideal)
;
}
};
void wrap_all() {
using namespace boost::python;
fixed_u_eq_adp_wrappers::wrap();
fixed_u_eq_adp_proxy_wrappers::wrap();
}
}
namespace boost_python {
void wrap_fixed_u_eq_adp() { wrap_all(); }
}}}
| 25.852273
| 60
| 0.607033
|
rimmartin
|
5a467f39695c9b5c2b5e7d6e8cf80f1335bd1599
| 3,212
|
hpp
|
C++
|
include/opengl/draw_info.hpp
|
bjadamson/BoomHS
|
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
|
[
"MIT"
] | 2
|
2016-07-22T10:09:21.000Z
|
2017-09-16T06:50:01.000Z
|
include/opengl/draw_info.hpp
|
bjadamson/BoomHS
|
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
|
[
"MIT"
] | 14
|
2016-08-13T22:45:56.000Z
|
2018-12-16T03:56:36.000Z
|
include/opengl/draw_info.hpp
|
bjadamson/BoomHS
|
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
|
[
"MIT"
] | null | null | null |
#pragma once
#include <opengl/bind.hpp>
#include <opengl/global.hpp>
#include <opengl/vao.hpp>
#include <opengl/vertex_attribute.hpp>
#include <boomhs/entity.hpp>
#include <common/log.hpp>
#include <common/type_macros.hpp>
#include <optional>
#include <string>
namespace boomhs
{
class ObjStore;
} // namespace boomhs
namespace opengl
{
class ShaderPrograms;
class BufferHandles
{
GLuint vbo_ = 0, ebo_ = 0;
static auto constexpr NUM_BUFFERS = 1;
explicit BufferHandles();
NO_COPY(BufferHandles);
public:
friend class DrawInfo;
~BufferHandles();
// move-construction OK.
BufferHandles(BufferHandles&&);
BufferHandles& operator=(BufferHandles&&);
auto vbo() const { return vbo_; }
auto ebo() const { return ebo_; }
std::string to_string() const;
};
std::ostream&
operator<<(std::ostream&, BufferHandles const&);
class DrawInfo
{
size_t num_vertexes_;
GLuint num_indices_;
BufferHandles handles_;
VAO vao_;
public:
DebugBoundCheck debug_check;
NO_COPY(DrawInfo);
explicit DrawInfo(size_t, GLuint);
DrawInfo(DrawInfo&&);
DrawInfo& operator=(DrawInfo&&);
void bind_impl(common::Logger&);
void unbind_impl(common::Logger&);
DEFAULT_WHILEBOUND_MEMBERFN_DECLATION();
auto vbo() const { return handles_.vbo(); }
auto ebo() const { return handles_.ebo(); }
auto num_vertexes() const { return num_vertexes_; }
auto num_indices() const { return num_indices_; }
auto& vao() { return vao_; }
auto const& vao() const { return vao_; }
std::string to_string() const;
};
struct DrawInfoHandle
{
using value_type = size_t;
value_type value;
explicit DrawInfoHandle(value_type const v)
: value(v)
{
}
};
class DrawHandleManager;
class EntityDrawHandleMap
{
std::vector<opengl::DrawInfo> drawinfos_;
std::vector<boomhs::EntityID> entities_;
friend class DrawHandleManager;
EntityDrawHandleMap() = default;
NO_COPY(EntityDrawHandleMap);
MOVE_DEFAULT(EntityDrawHandleMap);
DrawInfoHandle add(boomhs::EntityID, opengl::DrawInfo&&);
bool empty() const { return drawinfos_.empty(); }
bool has(DrawInfoHandle) const;
auto size() const
{
assert(drawinfos_.size() == entities_.size());
return drawinfos_.size();
}
DrawInfo const& get(DrawInfoHandle) const;
DrawInfo& get(DrawInfoHandle);
std::optional<DrawInfoHandle> find(boomhs::EntityID) const;
};
class DrawHandleManager
{
// These slots get a value when memory is loaded, set to none when memory is not.
EntityDrawHandleMap entities_;
EntityDrawHandleMap& entities();
EntityDrawHandleMap const& entities() const;
public:
DrawHandleManager() = default;
NO_COPY(DrawHandleManager);
MOVE_DEFAULT(DrawHandleManager);
// methods
DrawInfoHandle add_entity(boomhs::EntityID, DrawInfo&&);
DrawInfo& lookup_entity(common::Logger&, boomhs::EntityID);
DrawInfo const& lookup_entity(common::Logger&, boomhs::EntityID) const;
void add_mesh(common::Logger&, ShaderPrograms&, boomhs::ObjStore&, boomhs::EntityID,
boomhs::EntityRegistry&);
void add_cube(common::Logger&, ShaderPrograms&, boomhs::EntityID, boomhs::EntityRegistry&);
};
} // namespace opengl
| 22
| 93
| 0.711706
|
bjadamson
|
53fe5e6aeb1f1c44f8f4face1da69d196f13f417
| 13,467
|
cpp
|
C++
|
operators_c.cpp
|
ntan15/scratch_wadge
|
0657069749b9507062c1f7e875c6545076fb85c8
|
[
"Unlicense"
] | null | null | null |
operators_c.cpp
|
ntan15/scratch_wadge
|
0657069749b9507062c1f7e875c6545076fb85c8
|
[
"Unlicense"
] | null | null | null |
operators_c.cpp
|
ntan15/scratch_wadge
|
0657069749b9507062c1f7e875c6545076fb85c8
|
[
"Unlicense"
] | null | null | null |
#include "operators_c.h"
#include "operators.h"
#include <Eigen/Dense>
#include <iostream>
using namespace std;
static dfloat_t *to_c(VectorXd &v)
{
dfloat_t *vdata = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * v.size());
#if USE_DFLOAT_DOUBLE == 1
Eigen::Map<Eigen::VectorXd>(vdata, v.size()) = v.cast<dfloat_t>();
#else
Eigen::Map<Eigen::VectorXf>(vdata, v.size()) = v.cast<dfloat_t>();
#endif
return vdata;
}
static dfloat_t *to_c(MatrixXd &m)
{
dfloat_t *mdata = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * m.size());
#if USE_DFLOAT_DOUBLE == 1
Eigen::Map<Eigen::MatrixXd>(mdata, m.rows(), m.cols()) = m.cast<dfloat_t>();
#else
Eigen::Map<Eigen::MatrixXf>(mdata, m.rows(), m.cols()) = m.cast<dfloat_t>();
#endif
return mdata;
}
static uintloc_t *to_c(MatrixXu32 &m)
{
uintloc_t *mdata =
(uintloc_t *)asd_malloc_aligned(sizeof(uintloc_t) * m.size());
Eigen::Map<Eigen::Matrix<uintloc_t, Eigen::Dynamic, Eigen::Dynamic>>(
mdata, m.rows(), m.cols()) = m.cast<uintloc_t>();
return mdata;
}
host_operators_t *host_operators_new_2D(int N, int M, uintloc_t E,
uintloc_t *EToE, uint8_t *EToF,
uint8_t *EToO, double *EToVX)
{
host_operators_t *ops =
(host_operators_t *)asd_malloc(sizeof(host_operators_t));
ref_elem_data *ref_data = build_ref_ops_2D(N, M, M);
VectorXd wq = ref_data->wq;
// nodal
MatrixXd Dr = ref_data->Dr;
MatrixXd Ds = ref_data->Ds;
MatrixXd Vq = ref_data->Vq;
VectorXd wfq = ref_data->wfq;
VectorXd nrJ = ref_data->nrJ;
VectorXd nsJ = ref_data->nsJ;
MatrixXd Vfqf = ref_data->Vfqf;
MatrixXd Vfq = ref_data->Vfq;
MatrixXd Pq = ref_data->Pq;
MatrixXd MM = Vq.transpose() * wq.asDiagonal() * Vq;
MatrixXd MMfq = Vfq.transpose() * wfq.asDiagonal();
MatrixXd Lq = mldivide(MM, MMfq);
MatrixXd VqLq = Vq * Lq;
MatrixXd VqPq = Vq * Pq;
MatrixXd VfPq = Vfq * Pq;
MatrixXd Drq = Vq * Dr * Pq - .5 * Vq * Lq * nrJ.asDiagonal() * Vfq * Pq;
MatrixXd Dsq = Vq * Ds * Pq - .5 * Vq * Lq * nsJ.asDiagonal() * Vfq * Pq;
ops->dim = 2;
ops->N = N;
ops->M = M;
ops->Np = (int)ref_data->r.size();
ops->Nq = (int)ref_data->rq.size();
// printf("Num cubature points Nq = %d\n",ops->Nq);
ops->Nfp = N + 1;
ops->Nfq = (int)ref_data->ref_rfq.size();
ops->Nfaces = ref_data->Nfaces;
ops->Nvgeo = 4;
ops->Nfgeo = 3;
ops->wq = to_c(wq);
ops->nrJ = to_c(nrJ);
ops->nsJ = to_c(nsJ);
ops->Drq = to_c(Drq);
ops->Dsq = to_c(Dsq);
ops->Vq = to_c(Vq);
ops->Pq = to_c(Pq);
ops->VqLq = to_c(VqLq);
ops->VqPq = to_c(VqPq);
ops->VfPq = to_c(VfPq);
ops->Vfqf = to_c(Vfqf);
Map<MatrixXd> EToVXmat(EToVX, 2 * 3, E);
if (sizeof(uintloc_t) != sizeof(uint32_t))
{
cerr << "Need to update build maps to support different integer types"
<< endl;
std::abort();
}
Map<MatrixXu32> mapEToE(EToE, 3, E);
Map<MatrixXu8> mapEToF(EToF, 3, E);
Map<MatrixXu8> mapEToO(EToO, 3, E);
geo_elem_data *geo_data = build_geofacs_2D(ref_data, EToVXmat);
map_elem_data *map_data = build_maps_2D(ref_data, mapEToE, mapEToF, mapEToO);
const int Nvgeo = ops->Nvgeo;
const int Nfgeo = ops->Nfgeo;
const int Nfaces = ref_data->Nfaces;
const int Nq = ops->Nq;
const int Nfq = ops->Nfq;
ops->xyzq =
(dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * 3 * E);
ops->xyzf = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
ops->Nfaces * 3 * E);
ops->vgeo =
(dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * Nvgeo * E);
ops->vfgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
Nfaces * Nvgeo * E);
ops->fgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
Nfgeo * Nfaces * E);
for (uintloc_t e = 0; e < E; ++e)
{
for (int n = 0; n < Nq; ++n)
{
ops->xyzq[n + 0 * Nq + e * Nq * 3] = (dfloat_t)geo_data->xq(n, e);
ops->xyzq[n + 1 * Nq + e * Nq * 3] = (dfloat_t)geo_data->yq(n, e);
// ops->xyzq[n + 2*Nq + e*Nq*3] = (dfloat_t)geo_data->zq(n,e);
ops->vgeo[e * Nq * Nvgeo + 0 * Nq + n] = (dfloat_t)geo_data->rxJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 1 * Nq + n] = (dfloat_t)geo_data->ryJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 2 * Nq + n] = (dfloat_t)geo_data->sxJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 3 * Nq + n] = (dfloat_t)geo_data->syJ(n, e);
}
}
for (uintloc_t e = 0; e < E; ++e)
{
for (int n = 0; n < Nfq * Nfaces; ++n)
{
ops->xyzf[n + 0 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =
(dfloat_t)geo_data->xf(n, e);
ops->xyzf[n + 1 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =
(dfloat_t)geo_data->yf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 0 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->rxJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 1 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->ryJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 2 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->sxJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 3 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->syJf(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 0 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->nxJ(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 1 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->nyJ(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 2 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->sJ(n, e);
}
}
ops->Jq = to_c(geo_data->J);
ops->mapPq = to_c(map_data->mapPq);
// ops->mapPqNoFields = to_c(map_data->mapPq); // save
/*
// JC: FIX LATER - only valid for tri2.msh
ops->mapPq[0] = 7;
ops->mapPq[1] = 6;
ops->mapPq[2] = 9;
ops->mapPq[3] = 8;
ops->mapPq[6] = 1;
ops->mapPq[7] = 0;
ops->mapPq[8] = 3;
ops->mapPq[9] = 2;
*/
// for(int i = 0; i < Nfq*Nfaces*E; ++i){
// printf("mapPq(%d) = %d\n",i,ops->mapPq[i]);
// }
ops->Fmask = to_c(map_data->fmask);
delete ref_data;
delete geo_data;
delete map_data;
return ops;
}
host_operators_t *host_operators_new_3D(int N, int M, uintloc_t E,
uintloc_t *EToE, uint8_t *EToF,
uint8_t *EToO, double *EToVX)
{
host_operators_t *ops =
(host_operators_t *)asd_malloc(sizeof(host_operators_t));
ref_elem_data *ref_data = build_ref_ops_3D(N, M, M);
VectorXd wq = ref_data->wq;
// nodal
MatrixXd Dr = ref_data->Dr;
MatrixXd Ds = ref_data->Ds;
MatrixXd Dt = ref_data->Dt;
MatrixXd Vq = ref_data->Vq;
MatrixXd Pq = ref_data->Pq;
MatrixXd Vfqf = ref_data->Vfqf;
MatrixXd Vfq = ref_data->Vfq;
VectorXd wfq = ref_data->wfq;
VectorXd nrJ = ref_data->nrJ;
VectorXd nsJ = ref_data->nsJ;
VectorXd ntJ = ref_data->ntJ;
MatrixXd MM = Vq.transpose() * wq.asDiagonal() * Vq;
MatrixXd MMfq = Vfq.transpose() * wfq.asDiagonal();
MatrixXd Lq = mldivide(MM, MMfq);
MatrixXd VqLq = Vq * Lq;
MatrixXd VqPq = Vq * Pq;
MatrixXd VfPq = Vfq * Pq;
MatrixXd Drq = Vq * Dr * Pq - .5 * Vq * Lq * nrJ.asDiagonal() * Vfq * Pq;
MatrixXd Dsq = Vq * Ds * Pq - .5 * Vq * Lq * nsJ.asDiagonal() * Vfq * Pq;
MatrixXd Dtq = Vq * Dt * Pq - .5 * Vq * Lq * ntJ.asDiagonal() * Vfq * Pq;
MatrixXd Drstq(Drq.rows(),3*Drq.cols());
Drstq << Drq,Dsq,Dtq;
/*
cout << "VqPq = " << endl << VqPq << endl;
cout << "VqLq = " << endl << VqLq << endl;
cout << "VfPq = " << endl << VfPq << endl;
cout << "Drq = " << endl << Drq << endl;
cout << "nrJ = " << endl << nrJ << endl;
cout << "Dsq = " << endl << Dsq << endl;
cout << "nsJ = " << endl << nsJ << endl;
cout << "Dtq = " << endl << Dtq << endl;
cout << "ntJ = " << endl << ntJ << endl;
*/
ops->dim = 3;
ops->N = N;
ops->M = M;
ops->Np = (int)ref_data->r.size();
ops->Nq = (int)ref_data->rq.size();
ops->Nfp = (N + 1) * (N + 2) / 2;
ops->Nfq = (int)ref_data->ref_rfq.size();
ops->Nfaces = ref_data->Nfaces;
ops->Nvgeo = 9;
ops->Nfgeo = 4;
ops->wq = to_c(wq);
ops->nrJ = to_c(nrJ);
ops->nsJ = to_c(nsJ);
ops->ntJ = to_c(ntJ);
ops->Drq = to_c(Drq);
ops->Dsq = to_c(Dsq);
ops->Dtq = to_c(Dtq);
ops->Drstq = to_c(Drstq);
ops->Vq = to_c(Vq);
ops->Pq = to_c(Pq);
ops->VqLq = to_c(VqLq);
ops->VqPq = to_c(VqPq);
ops->VfPq = to_c(VfPq);
ops->Vfqf = to_c(Vfqf);
Map<MatrixXd> EToVXmat(EToVX, 3 * 4, E);
if (sizeof(uintloc_t) != sizeof(uint32_t))
{
cerr << "Need to update build maps to support different integer types"
<< endl;
std::abort();
}
Map<MatrixXu32> mapEToE(EToE, 4, E);
Map<MatrixXu8> mapEToF(EToF, 4, E);
Map<MatrixXu8> mapEToO(EToO, 4, E);
geo_elem_data *geo_data = build_geofacs_3D(ref_data, EToVXmat);
map_elem_data *map_data = build_maps_3D(ref_data, mapEToE, mapEToF, mapEToO);
const int Nvgeo = ops->Nvgeo;
const int Nfgeo = ops->Nfgeo;
const int Nfaces = ref_data->Nfaces;
const int Nq = ops->Nq;
const int Nfq = ops->Nfq;
ops->xyzq =
(dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * 3 * E);
ops->xyzf = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
ops->Nfaces * 3 * E);
ops->vgeo =
(dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nq * Nvgeo * E);
ops->vfgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
Nfaces * Nvgeo * E);
ops->fgeo = (dfloat_t *)asd_malloc_aligned(sizeof(dfloat_t) * ops->Nfq *
Nfgeo * Nfaces * E);
for (uintloc_t e = 0; e < E; ++e)
{
for (int n = 0; n < Nq; ++n)
{
ops->xyzq[n + 0 * Nq + e * Nq * 3] = (dfloat_t)geo_data->xq(n, e);
ops->xyzq[n + 1 * Nq + e * Nq * 3] = (dfloat_t)geo_data->yq(n, e);
ops->xyzq[n + 2 * Nq + e * Nq * 3] = (dfloat_t)geo_data->zq(n, e);
ops->vgeo[e * Nq * Nvgeo + 0 * Nq + n] = (dfloat_t)geo_data->rxJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 1 * Nq + n] = (dfloat_t)geo_data->ryJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 2 * Nq + n] = (dfloat_t)geo_data->rzJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 3 * Nq + n] = (dfloat_t)geo_data->sxJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 4 * Nq + n] = (dfloat_t)geo_data->syJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 5 * Nq + n] = (dfloat_t)geo_data->szJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 6 * Nq + n] = (dfloat_t)geo_data->txJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 7 * Nq + n] = (dfloat_t)geo_data->tyJ(n, e);
ops->vgeo[e * Nq * Nvgeo + 8 * Nq + n] = (dfloat_t)geo_data->tzJ(n, e);
}
}
for (uintloc_t e = 0; e < E; ++e)
{
for (int n = 0; n < Nfq * Nfaces; ++n)
{
ops->xyzf[n + 0 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =
(dfloat_t)geo_data->xf(n, e);
ops->xyzf[n + 1 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =
(dfloat_t)geo_data->yf(n, e);
ops->xyzf[n + 2 * Nfq * Nfaces + e * Nfq * Nfaces * 3] =
(dfloat_t)geo_data->zf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 0 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->rxJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 1 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->ryJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 2 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->rzJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 3 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->sxJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 4 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->syJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 5 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->szJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 6 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->txJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 7 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->tyJf(n, e);
ops->vfgeo[e * Nfq * Nfaces * Nvgeo + 8 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->tzJf(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 0 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->nxJ(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 1 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->nyJ(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 2 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->nzJ(n, e);
ops->fgeo[e * Nfq * Nfaces * Nfgeo + 3 * Nfq * Nfaces + n] =
(dfloat_t)geo_data->sJ(n, e);
// if (e==99){
// printf("n = %d, nxJ = %f\n", n, (dfloat_t) geo_data->nxJ(n,e));
// }
}
}
ops->Jq = to_c(geo_data->J);
ops->mapPq = to_c(map_data->mapPq);
ops->Fmask = to_c(map_data->fmask);
delete ref_data;
delete geo_data;
delete map_data;
return ops;
}
void host_operators_free(host_operators_t *ops)
{
asd_free_aligned(ops->vgeo);
asd_free_aligned(ops->fgeo);
asd_free_aligned(ops->Jq);
asd_free_aligned(ops->mapPq);
asd_free_aligned(ops->Fmask);
asd_free_aligned(ops->nrJ);
asd_free_aligned(ops->nsJ);
asd_free_aligned(ops->Drq);
asd_free_aligned(ops->Dsq);
if (ops->dim == 3)
{
asd_free_aligned(ops->ntJ);
asd_free_aligned(ops->Dtq);
}
asd_free_aligned(ops->Vq);
asd_free_aligned(ops->Pq);
asd_free_aligned(ops->VqLq);
asd_free_aligned(ops->VqPq);
asd_free_aligned(ops->VfPq);
asd_free_aligned(ops->Vfqf);
}
| 31.538642
| 80
| 0.556843
|
ntan15
|
99046f7f13fbffeefb6d06369b8ecde9df1dbf40
| 2,337
|
cc
|
C++
|
larq_compute_engine/mlir/transforms/fuse_padding.cc
|
godhj93/compute-engine
|
1f812a6722e2ee6a510c883826fd5925f9c34b18
|
[
"Apache-2.0"
] | null | null | null |
larq_compute_engine/mlir/transforms/fuse_padding.cc
|
godhj93/compute-engine
|
1f812a6722e2ee6a510c883826fd5925f9c34b18
|
[
"Apache-2.0"
] | null | null | null |
larq_compute_engine/mlir/transforms/fuse_padding.cc
|
godhj93/compute-engine
|
1f812a6722e2ee6a510c883826fd5925f9c34b18
|
[
"Apache-2.0"
] | null | null | null |
#include "larq_compute_engine/mlir/transforms/padding.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h"
namespace mlir {
namespace TFL {
namespace {
bool NoBatchAndChannelPadding(Attribute paddings_attr) {
auto paddings = GetValidPadAttr(paddings_attr);
if (!paddings) return false;
return IsNoPadding(paddings, 0) && IsNoPadding(paddings, 3);
}
// The TFLite op has `stride_height` and `stride_width` as separate attributes.
// Due to a TableGen limitation we can't pass them both in a single call.
bool IsSamePaddingPartial(Attribute paddings_attr, Value input, Value output,
Attribute strides_attr, uint64_t dimension) {
auto paddings = GetValidPadAttr(paddings_attr);
if (!paddings) return false;
auto input_shape = GetShape4D(input);
if (input_shape.empty()) return false;
auto output_shape = GetShape4D(output);
if (output_shape.empty()) return false;
if (!strides_attr.isa<IntegerAttr>()) return false;
const int stride = strides_attr.cast<IntegerAttr>().getInt();
// Check that there is no padding in the batch and channel dimensions
return IsSamePadding1D(paddings, dimension, input_shape[dimension],
output_shape[dimension], stride);
}
#include "larq_compute_engine/mlir/transforms/generated_fuse_padding.inc"
// Prepare LCE operations in functions for subsequent legalization.
struct FusePadding : public PassWrapper<FusePadding, FunctionPass> {
FusePadding() = default;
FusePadding(const FusePadding& pass) {}
void runOnFunction() override {
auto* ctx = &getContext();
OwningRewritePatternList patterns(ctx);
auto func = getFunction();
populateWithGenerated(patterns);
(void)applyPatternsAndFoldGreedily(func, std::move(patterns));
}
void getDependentDialects(DialectRegistry& registry) const override {
registry.insert<::mlir::TFL::TensorFlowLiteDialect>();
}
};
} // namespace
// Creates an instance of the TensorFlow dialect FusePadding pass.
std::unique_ptr<OperationPass<FuncOp>> CreateFusePaddingPass() {
return std::make_unique<FusePadding>();
}
static PassRegistration<FusePadding> pass(
"tfl-fuse-padding", "Fuse padding ops into (Depthwise)Convs.");
} // namespace TFL
} // namespace mlir
| 34.880597
| 79
| 0.744544
|
godhj93
|
990895bc2b59a8a47daa6835471237eac9152d89
| 8,857
|
cpp
|
C++
|
XMLWriter.cpp
|
malord/prime
|
f0e8be99b7dcd482708b9c928322bc07a3128506
|
[
"MIT"
] | null | null | null |
XMLWriter.cpp
|
malord/prime
|
f0e8be99b7dcd482708b9c928322bc07a3128506
|
[
"MIT"
] | null | null | null |
XMLWriter.cpp
|
malord/prime
|
f0e8be99b7dcd482708b9c928322bc07a3128506
|
[
"MIT"
] | null | null | null |
// Copyright 2000-2021 Mark H. P. Lord
#include "XMLWriter.h"
#include <string.h>
namespace {
// TODO: might be worth finding a common place for this? Or making them static methods so other modules can use them?
inline bool IsXMLWhitespace(char ch)
{
return ch == 0x09 || ch == 0x0a || ch == 0x0d || ch == 0x0c || ch == 0x20;
}
inline const char* SkipXMLWhitespace(const char* from, const char* to)
{
for (; from != to; ++from) {
if (!IsXMLWhitespace(*from)) {
return from;
}
}
return from;
}
}
namespace Prime {
XMLWriter::XMLWriter()
{
}
XMLWriter::XMLWriter(const Options& options, Stream* stream, Log* log, size_t bufferSize, void* buffer)
{
init(options, stream, log, bufferSize, buffer);
}
XMLWriter::~XMLWriter()
{
}
void XMLWriter::init(const Options& options, Stream* stream, Log* log, size_t bufferSize, void* buffer)
{
reset();
_streamBuffer.init(stream, bufferSize, buffer);
_log = log;
_options = options;
beginWrite();
}
void XMLWriter::beginWrite()
{
_currentIndent = 0;
_errors = false;
}
bool XMLWriter::end()
{
PRIME_ASSERT(_elements.empty()); // Didn't end all elements.
return flush();
}
bool XMLWriter::flush()
{
if (!_streamBuffer.flush(_log)) {
_errors = true;
}
return !getErrorFlag();
}
bool XMLWriter::reset()
{
bool success = flush();
_errors = false;
return success;
}
void XMLWriter::writeRaw(StringView string)
{
if (!_streamBuffer.writeString(string, _log)) {
_errors = true;
}
}
void XMLWriter::writeDOCTYPE(StringView text)
{
_errors = !_streamBuffer.writeBytes("<!", 2, _log) || _errors;
//writeEscaped(text);
_errors = !_streamBuffer.writeString(text, _log) || _errors;
_errors = !_streamBuffer.writeByte('>', _log) || _errors;
}
void XMLWriter::writeComment(StringView string)
{
// Should probably add a check for --> (actually, -- is illegal in a comment) in the comment. I'll leave that to the caller for now.
closeElementAndWriteIndent();
_errors = !_streamBuffer.writeBytes("<!-- ", 5, _log) || _errors;
writeCommentEscaped(string);
_errors = !_streamBuffer.writeBytes(" -->", 4, _log) || _errors;
}
void XMLWriter::writeCommentEscaped(StringView stringView)
{
const char* string = stringView.begin();
const char* ptr = stringView.begin();
const char* end = stringView.end();
const char* escape = NULL;
for (;;) {
if (ptr == end) {
} else if (*ptr == '-' && end - ptr >= 3 && memcmp(ptr, "-->", 3) == 0) {
escape = "-- >";
} else {
++ptr;
continue;
}
_errors = !_streamBuffer.writeBytes(string, ptr - string, _log) || _errors;
if (ptr == end) {
break;
}
_errors = !_streamBuffer.writeString(escape, _log) || _errors;
escape = 0;
++ptr;
string = ptr;
}
}
void XMLWriter::closeElementAndWriteIndent()
{
closeElement();
if (!_elements.empty() && !_elements.back().isText) {
_errors = !_streamBuffer.writeByte('\n', _log) || _errors;
writeIndent();
}
}
void XMLWriter::startElement(StringView name)
{
startElement(name, false);
}
void XMLWriter::startTextElement(StringView name)
{
startElement(name, true);
}
void XMLWriter::writeProcessingInstruction(StringView name, StringView content)
{
closeElementAndWriteIndent();
_errors = !_streamBuffer.writeBytes("<?", 2, _log) || _errors;
_errors = !_streamBuffer.writeString(name, _log) || _errors;
_errors = !_streamBuffer.writeBytes(" ", 1, _log) || _errors;
_errors = !_streamBuffer.writeString(content, _log) || _errors;
_errors = !_streamBuffer.writeBytes("?>", 2, _log) || _errors;
}
void XMLWriter::startElement(StringView name, bool isText)
{
closeElementAndWriteIndent();
_errors = !_streamBuffer.writeByte('<', _log) || _errors;
_errors = !_streamBuffer.writeString(name, _log) || _errors;
Element newElement;
newElement.name = name;
newElement.isText = isText;
newElement.isOpen = true;
++_currentIndent;
_elements.push_back(newElement);
}
void XMLWriter::closeElement()
{
if (!_elements.empty() && _elements.back().isOpen) {
_errors = !_streamBuffer.writeByte('>', _log) || _errors;
_elements.back().isOpen = false;
}
}
void XMLWriter::writeIndent()
{
if (!_elements.empty() && !_elements.back().isText) {
for (int i = 0; i != _currentIndent; ++i) {
_errors = !_streamBuffer.writeByte('\t', _log) || _errors;
}
}
}
void XMLWriter::writeAttribute(StringView name, StringView value)
{
PRIME_ASSERT(!_elements.empty()); // Need an element to have an attribute.
PRIME_ASSERT(_elements.back().isOpen); // The > has been written.
_errors = !_streamBuffer.writeByte(' ', _log) || _errors;
_errors = !_streamBuffer.writeString(name, _log) || _errors;
_errors = !_streamBuffer.writeBytes("=\"", 2, _log) || _errors;
writeEscaped(value);
_errors = !_streamBuffer.writeByte('"', _log) || _errors;
}
void XMLWriter::writeEscaped(StringView stringView)
{
const char* string = stringView.begin();
const char* ptr = string;
const char* end = stringView.end();
const char* escape = NULL;
for (;;) {
if (ptr != end) {
if (*ptr == '<') {
escape = "<";
} else if (*ptr == '>') {
escape = ">";
} else if (*ptr == '\'') {
escape = _options.getHTML() ? "'" : "'";
} else if (*ptr == '"') {
escape = """;
} else if (*ptr == '&') {
escape = "&";
} else {
++ptr;
continue;
}
}
_errors = !_streamBuffer.writeBytes(string, ptr - string, _log) || _errors;
if (ptr == end) {
break;
}
_errors = !_streamBuffer.writeString(escape, _log) || _errors;
escape = 0;
++ptr;
string = ptr;
}
}
void XMLWriter::writeTextInternal(StringView string, bool escape)
{
const char* begin = string.begin();
const char* end = string.end();
if (!_elements.empty()) {
if (!_elements.back().isText) {
begin = SkipXMLWhitespace(begin, end);
if (begin != end) {
_elements.back().isText = true;
}
}
}
if (begin == end) {
return;
}
closeElement();
if (escape) {
writeEscaped(StringView(begin, end));
} else {
writeRaw(StringView(begin, end));
}
}
void XMLWriter::writeText(StringView string)
{
writeTextInternal(string, true);
}
void XMLWriter::writeEscapedText(StringView string)
{
writeTextInternal(string, false);
}
void XMLWriter::writeCDATA(StringView text)
{
if (!_elements.empty()) {
_elements.back().isText = true;
}
closeElement();
_errors = !_streamBuffer.writeBytes("<![CDATA[", 9, _log) || _errors;
writeCDATAEscaped(text);
_errors = !_streamBuffer.writeBytes("]]>", 3, _log) || _errors;
}
void XMLWriter::writeCDATAEscaped(StringView stringView)
{
const char* string = stringView.begin();
const char* ptr = string;
const char* end = stringView.end();
const char* escape = NULL;
for (;;) {
if (ptr == end) {
} else if (*ptr == ']' && end - ptr >= 3 && memcmp(ptr, "]]>", 3) == 0) {
escape = "]]><![CDATA[";
} else {
++ptr;
continue;
}
_errors = !_streamBuffer.writeBytes(string, ptr - string, _log) || _errors;
if (ptr == end) {
break;
}
_errors = !_streamBuffer.writeString(escape, _log) || _errors;
escape = 0;
++ptr;
string = ptr;
}
}
void XMLWriter::endElement(bool allowSelfClosing)
{
PRIME_ASSERT(!_elements.empty()); // More end elements than start elements.
--_currentIndent;
if (_elements.back().isOpen && allowSelfClosing) {
_errors = !_streamBuffer.writeBytes("/>", 2, _log) || _errors;
} else {
if (_elements.back().isOpen) {
_errors = !_streamBuffer.writeBytes(">", 1, _log) || _errors;
}
if (!_elements.back().isText) {
_errors = !_streamBuffer.writeByte('\n', _log) || _errors;
writeIndent();
}
_errors = !_streamBuffer.writeBytes("</", 2, _log) || _errors;
_errors = !_streamBuffer.writeString(_elements.back().name, _log) || _errors;
_errors = !_streamBuffer.writeByte('>', _log) || _errors;
}
_elements.pop_back();
//if (_elements.empty())
// _errors = ! _streamBuffer.writeByte('\n', _log) || _errors;
}
}
| 24.265753
| 136
| 0.584058
|
malord
|
990ce40d611e8ecc977c2e5fe7133c3bcbddaf35
| 9,821
|
cpp
|
C++
|
Source/Engine/LightFroxelationTechnique.cpp
|
glowing-chemist/Bell
|
0cf4d0ac925940869077779700c1d3bd45ff841f
|
[
"MIT"
] | 14
|
2020-02-12T19:13:46.000Z
|
2022-03-05T02:26:06.000Z
|
Source/Engine/LightFroxelationTechnique.cpp
|
glowing-chemist/Bell
|
0cf4d0ac925940869077779700c1d3bd45ff841f
|
[
"MIT"
] | 5
|
2020-08-06T07:19:47.000Z
|
2021-01-05T21:20:51.000Z
|
Source/Engine/LightFroxelationTechnique.cpp
|
glowing-chemist/Bell
|
0cf4d0ac925940869077779700c1d3bd45ff841f
|
[
"MIT"
] | 2
|
2021-09-18T13:36:47.000Z
|
2021-12-04T15:08:53.000Z
|
#include "Engine/LightFroxelationTechnique.hpp"
#include "Engine/Engine.hpp"
#include "Engine/DefaultResourceSlots.hpp"
#include "Core/Executor.hpp"
constexpr const char* kFroxelIndirectArgs = "FroxelIndirectArgs";
constexpr const char* kLightIndexCounter = "lightIndexCounter";
constexpr const char* kActiveFroxelsCounter = "ActiveFroxelsCounter";
LightFroxelationTechnique::LightFroxelationTechnique(RenderEngine* eng, RenderGraph& graph) :
Technique("LightFroxelation", eng->getDevice()),
mActiveFroxelsShader(eng->getShader("./Shaders/ActiveFroxels.comp")),
mIndirectArgsShader(eng->getShader("./Shaders/IndirectFroxelArgs.comp")),
mClearCoutersShader(eng->getShader("./Shaders/LightFroxelationClearCounters.comp")),
mLightAsignmentShader(eng->getShader("./Shaders/FroxelationGenerateLightLists.comp")),
mXTiles(eng->getDevice()->getSwapChainImageView()->getImageExtent().width / 32),
mYTiles(eng->getDevice()->getSwapChainImageView()->getImageExtent().height / 32),
mLightBuffer(getDevice(), BufferUsage::DataBuffer | BufferUsage::TransferDest, (sizeof(Scene::Light) * 1000) + std::max(sizeof(uint4), getDevice()->getMinStorageBufferAlignment()), (sizeof(Scene::Light) * 1000) + std::max(sizeof(uint4), getDevice()->getMinStorageBufferAlignment()), "LightBuffer"),
mLightBufferView(mLightBuffer, std::max(sizeof(uint4), getDevice()->getMinStorageBufferAlignment())),
mLightCountView(mLightBuffer, 0, sizeof(uint4)),
mLightsSRS(getDevice(), 2),
mActiveFroxelsImage(eng->getDevice(), Format::R32Uint, ImageUsage::Storage | ImageUsage::Sampled, eng->getDevice()->getSwapChainImageView()->getImageExtent().width,
eng->getDevice()->getSwapChainImageView()->getImageExtent().height, 1, 1, 1, 1, "ActiveFroxels"),
mActiveFroxelsImageView(mActiveFroxelsImage, ImageViewType::Colour),
// Assumes an avergae max of 10 active froxels per screen space tile.
mActiveFroxlesBuffer(eng->getDevice(), BufferUsage::DataBuffer | BufferUsage::Uniform, sizeof(float4) * (mXTiles * mYTiles * 10), sizeof(float4) * (mXTiles* mYTiles * 10), "ActiveFroxelBuffer"),
mActiveFroxlesBufferView(mActiveFroxlesBuffer, std::max(eng->getDevice()->getMinStorageBufferAlignment(), sizeof(uint32_t))),
mActiveFroxelsCounter(mActiveFroxlesBuffer, 0u, static_cast<uint32_t>(sizeof(uint32_t))),
mIndirectArgsBuffer(eng->getDevice(), BufferUsage::DataBuffer | BufferUsage::IndirectArgs, sizeof(uint32_t) * 3, sizeof(uint32_t) * 3, "FroxelIndirectArgs"),
mIndirectArgsView(mIndirectArgsBuffer, 0, sizeof(uint32_t) * 3),
mSparseFroxelBuffer(eng->getDevice(), BufferUsage::DataBuffer, sizeof(float2) * (mXTiles * mYTiles * 32), sizeof(float2) * (mXTiles * mYTiles * 32), kSparseFroxels),
mSparseFroxelBufferView(mSparseFroxelBuffer),
mLightIndexBuffer(eng->getDevice(), BufferUsage::DataBuffer, sizeof(uint32_t) * (mXTiles * mYTiles * 16 * 16), sizeof(uint32_t) * (mXTiles * mYTiles * 16 * 16), kLightIndicies),
mLightIndexBufferView(mLightIndexBuffer, std::max(eng->getDevice()->getMinStorageBufferAlignment(), sizeof(uint32_t))),
mLightIndexCounterView(mLightIndexBuffer, 0, static_cast<uint32_t>(sizeof(uint32_t)))
{
// set light buffers SRS
for(uint32_t i = 0; i < getDevice()->getSwapChainImageCount(); ++i)
{
mLightsSRS.get(i)->addDataBufferRO(mLightCountView.get(i));
mLightsSRS.get(i)->addDataBufferRW(mLightBufferView.get(i));
mLightsSRS.get(i)->finalise();
}
ComputeTask clearCountersTask{ "clearFroxelationCounters" };
clearCountersTask.addInput(kActiveFroxelsCounter, AttachmentType::DataBufferWO);
clearCountersTask.addInput(kLightIndexCounter, AttachmentType::DataBufferWO);
clearCountersTask.setRecordCommandsCallback(
[this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine*, const std::vector<const MeshInstance*>&)
{
PROFILER_EVENT("Clear froxel counter");
PROFILER_GPU_TASK(exec);
PROFILER_GPU_EVENT("Clear froxel counter");
const RenderTask& task = graph.getTask(taskIndex);
exec->setComputeShader(static_cast<const ComputeTask&>(task), graph, mClearCoutersShader);
exec->dispatch(1, 1, 1);
}
);
mClearCounters = graph.addTask(clearCountersTask);
ComputeTask activeFroxelTask{ "LightingFroxelation" };
activeFroxelTask.addInput(kActiveFroxels, AttachmentType::Image2D);
activeFroxelTask.addInput(kLinearDepth, AttachmentType::Texture2D);
activeFroxelTask.addInput(kCameraBuffer, AttachmentType::UniformBuffer);
activeFroxelTask.addInput(kDefaultSampler, AttachmentType::Sampler);
activeFroxelTask.addInput(kActiveFroxelBuffer, AttachmentType::DataBufferWO);
activeFroxelTask.addInput(kActiveFroxelsCounter, AttachmentType::DataBufferRW);
activeFroxelTask.setRecordCommandsCallback(
[this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine* eng, const std::vector<const MeshInstance*>&)
{
PROFILER_EVENT("light froxelation");
PROFILER_GPU_TASK(exec);
PROFILER_GPU_EVENT("light froxelation");
const RenderTask& task = graph.getTask(taskIndex);
exec->setComputeShader(static_cast<const ComputeTask&>(task), graph, mActiveFroxelsShader);
const auto extent = eng->getDevice()->getSwapChainImageView()->getImageExtent();
exec->dispatch(static_cast<uint32_t>(std::ceil(extent.width / 32.0f)), static_cast<uint32_t>(std::ceil(extent.height / 32.0f)), 1);
}
);
mActiveFroxels = graph.addTask(activeFroxelTask);
ComputeTask indirectArgsTask{ "generateFroxelIndirectArgs" };
indirectArgsTask.addInput(kActiveFroxelsCounter, AttachmentType::DataBufferRO);
indirectArgsTask.addInput(kFroxelIndirectArgs, AttachmentType::DataBufferWO);
indirectArgsTask.setRecordCommandsCallback(
[this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine*, const std::vector<const MeshInstance*>&)
{
const RenderTask& task = graph.getTask(taskIndex);
exec->setComputeShader(static_cast<const ComputeTask&>(task), graph, mIndirectArgsShader);
exec->dispatch(1, 1, 1);
}
);
mIndirectArgs = graph.addTask(indirectArgsTask);
ComputeTask lightListAsignmentTask{ "LightAsignment" };
lightListAsignmentTask.addInput(kActiveFroxelBuffer, AttachmentType::DataBufferRO);
lightListAsignmentTask.addInput(kActiveFroxelsCounter, AttachmentType::DataBufferRO);
lightListAsignmentTask.addInput(kLightIndicies, AttachmentType::DataBufferWO);
lightListAsignmentTask.addInput(kLightIndexCounter, AttachmentType::DataBufferRW);
lightListAsignmentTask.addInput(kSparseFroxels, AttachmentType::DataBufferWO);
lightListAsignmentTask.addInput(kCameraBuffer, AttachmentType::UniformBuffer);
lightListAsignmentTask.addInput(kLightBuffer, AttachmentType::ShaderResourceSet);
lightListAsignmentTask.addInput(kFroxelIndirectArgs, AttachmentType::IndirectBuffer);
lightListAsignmentTask.setRecordCommandsCallback(
[this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine*, const std::vector<const MeshInstance*>&)
{
PROFILER_EVENT("build light lists");
PROFILER_GPU_TASK(exec);
PROFILER_GPU_EVENT("build light lists");
const RenderTask& task = graph.getTask(taskIndex);
exec->setComputeShader(static_cast<const ComputeTask&>(task), graph, mLightAsignmentShader);
exec->dispatchIndirect(this->mIndirectArgsView);
}
);
mLightListAsignment = graph.addTask(lightListAsignmentTask);
}
void LightFroxelationTechnique::render(RenderGraph&, RenderEngine* engine)
{
mActiveFroxelsImageView->updateLastAccessed();
mActiveFroxelsImage->updateLastAccessed();
mActiveFroxlesBuffer->updateLastAccessed();
mSparseFroxelBuffer->updateLastAccessed();
mLightIndexBuffer->updateLastAccessed();
mIndirectArgsBuffer->updateLastAccessed();
(*mLightBuffer)->updateLastAccessed();
(*mLightsSRS)->updateLastAccessed();
// Frustum cull the lights and send to the gpu.
Frustum frustum = engine->getCurrentSceneCamera().getFrustum();
std::vector<Scene::Light*> visibleLightPtrs = engine->getScene()->getVisibleLights(frustum);
std::vector<Scene::Light> visibleLights{};
visibleLights.reserve(visibleLightPtrs.size());
std::transform(visibleLightPtrs.begin(), visibleLightPtrs.end(), std::back_inserter(visibleLights), []
(const Scene::Light* light) { return *light; });
mLightBuffer.get()->setContents(static_cast<int>(visibleLights.size()), sizeof(uint32_t));
if(!visibleLights.empty())
{
mLightBuffer.get()->resize(visibleLights.size() * sizeof(Scene::Light), false);
mLightBuffer.get()->setContents(visibleLights.data(), static_cast<uint32_t>(visibleLights.size() * sizeof(Scene::Light)), std::max(sizeof(uint4), engine->getDevice()->getMinStorageBufferAlignment()));
}
}
void LightFroxelationTechnique::bindResources(RenderGraph& graph)
{
graph.bindShaderResourceSet(kLightBuffer, *mLightsSRS);
if(!graph.isResourceSlotBound(kActiveFroxels))
{
graph.bindImage(kActiveFroxels, mActiveFroxelsImageView);
graph.bindBuffer(kActiveFroxelBuffer, mActiveFroxlesBufferView);
graph.bindBuffer(kSparseFroxels, mSparseFroxelBufferView);
graph.bindBuffer(kLightIndicies, mLightIndexBufferView);
graph.bindBuffer(kActiveFroxelsCounter, mActiveFroxelsCounter);
graph.bindBuffer(kFroxelIndirectArgs, mIndirectArgsView);
graph.bindBuffer(kLightIndexCounter, mLightIndexCounterView);
}
}
| 53.961538
| 302
| 0.74188
|
glowing-chemist
|
990e91dfcbacdb744afa79e9d0ea86c0449d3536
| 17,620
|
cc
|
C++
|
third-party/webscalesqlclient/mysql-5.6/sql/item_jsonfunc.cc
|
hkirsman/hhvm_centos7_builds
|
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
|
[
"PHP-3.01",
"Zend-2.0"
] | null | null | null |
third-party/webscalesqlclient/mysql-5.6/sql/item_jsonfunc.cc
|
hkirsman/hhvm_centos7_builds
|
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
|
[
"PHP-3.01",
"Zend-2.0"
] | null | null | null |
third-party/webscalesqlclient/mysql-5.6/sql/item_jsonfunc.cc
|
hkirsman/hhvm_centos7_builds
|
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
|
[
"PHP-3.01",
"Zend-2.0"
] | null | null | null |
/*
Copyright (c) 2014, Facebook. All rights reserved.
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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* This file defines all json string functions (using FBSON library) */
/* May include caustic 3rd-party defs. Use early, so it can override nothing. */
#include "my_global.h"
/*
It is necessary to include set_var.h instead of item.h because there
are dependencies on include order for set_var.h and item.h. This
will be resolved later.
*/
#include "sql_class.h"
#include "set_var.h"
#include "mysqld.h"
#include "item_cmpfunc.h"
// error messages for JSON parsing errors
const constexpr char* const fbson::FbsonErrMsg::err_msg_[];
/*
* Note we assume the system charset is UTF8,
* which is the encoding of json object in FBSON
*/
/*
* Converts FbsonValue object to string and write to str
* Input: pval - FbsonValue object to convert
* str - output
* cs - character set
* json_text - whether to return json text or native values
* Output: true - success
*/
static bool
ValueToString(fbson::FbsonValue *pval,
String &str,
const CHARSET_INFO *cs,
bool json_text)
{
if (!pval)
return false;
switch (pval->type())
{
case fbson::FbsonType::T_Null:
{
if (json_text)
{
str.set("null", 4, cs);
return true;
}
else
return false;
}
case fbson::FbsonType::T_False:
{
if (json_text)
str.set("false", 5, cs);
else
str.set_int(0, true /*unsigned_flag*/, cs);
return true;
}
case fbson::FbsonType::T_True:
{
if (json_text)
str.set("true", 4, cs);
else
str.set_int(1, true /*unsigned_flag*/, cs);
return true;
}
case fbson::FbsonType::T_String:
{
if (!json_text)
{
// copy the string without double quotes
fbson::StringVal *str_val = (fbson::StringVal *)pval;
str.copy(str_val->getBlob(), str_val->getBlobLen(), cs);
return true;
}
// else json_text, fall through
}
case fbson::FbsonType::T_Object:
case fbson::FbsonType::T_Array:
{
fbson::FbsonToJson tojson;
const char *json = tojson.json(pval);
str.copy(json, strlen(json), cs);
return true;
}
case fbson::FbsonType::T_Int8:
{
str.set_int(((fbson::Int8Val*)pval)->val(), false, cs);
return true;
}
case fbson::FbsonType::T_Int16:
{
str.set_int(((fbson::Int16Val*)pval)->val(), false, cs);
return true;
}
case fbson::FbsonType::T_Int32:
{
str.set_int(((fbson::Int32Val*)pval)->val(), false, cs);
return true;
}
case fbson::FbsonType::T_Int64:
{
str.set_int(((fbson::Int64Val*)pval)->val(), false, cs);
return true;
}
case fbson::FbsonType::T_Double:
{
str.set_real(((fbson::DoubleVal*)pval)->val(), NOT_FIXED_DEC, cs);
return true;
}
default:
return false;
}
return false;
}
/*
* Get FBSON value object from item if item is FBSON binary
* Otherwise, the string is pointed by json
* Input: item - input item
* Output: json - a json string or an fbson binary blob
* Return: FbsonValue object
*
* Note: if the item is a document column, the item value is Fbson binary and
* an FbsonValue object is returned (the fbson binary is stored in the json
* output param). Otherwise, the item's string value depends on two conditions:
* (1) whether it is a DOC_EXTRACT_FUNC, and (2) whether
* use_fbson_output_format is turned on. If both are true, the item value is
* Fbson binary and FbsonValue object is returned. Otherwise, the JSON string
* is stored in json (output param) and return value is nullptr.
*/
static fbson::FbsonValue *get_fbson_val(Item *item,
String *&json,
String *buffer)
{
fbson::FbsonValue *pval = nullptr;
if (item->field_type() == MYSQL_TYPE_DOCUMENT)
{
// item is a document field, and json is an fbson binary
pval = item->val_document_value(buffer); // this is an FBSON blob
if(pval != nullptr && buffer->ptr() != (char*)pval)
{
buffer->copy((char*)pval,
pval->numPackedBytes(),
item->collation.collation);
json = buffer;
}
}
else
{
json = item->val_str(buffer);
// we check again if the string is actually FBSON value binary.
// if use_fbson_output_format is true and item is DOC_EXTRACT_FUNC,
// then json is a fbson binary, and we convert it to FbsonValue object.
// otherwise, json is a JSON string.
if (json &&
current_thd->variables.use_fbson_output_format &&
item->type() == item->FUNC_ITEM &&
((Item_func*)item)->functype() == ((Item_func*)item)->DOC_EXTRACT_FUNC)
pval = (fbson::FbsonValue*)(json->ptr());
}
return pval;
}
/*
* Parses JSON c_str into FBSON value object
* Input: c_str - JSON string (null terminated)
* os - output stream storing FBSON packed bytes
* Output: FbsonValue object.
* NULL if JSON is invalid
*/
static fbson::FbsonValue *get_fbson_val(const char *c_str,
fbson::FbsonOutStream &os)
{
// try parsing input as JSON
fbson::FbsonValue *pval = nullptr;
fbson::FbsonJsonParser parser(os);
if (parser.parse(c_str))
{
pval = fbson::FbsonDocument::createValue(
os.getBuffer(), os.getSize());
DBUG_ASSERT(pval);
}
else
{
fbson::FbsonErrInfo err_info = parser.getErrorInfo();
my_error(ER_INVALID_JSON, MYF(0), c_str,
err_info.err_pos, err_info.err_msg);
}
return pval;
}
/*
* Item_func_json_valid
*/
bool Item_func_json_valid::val_bool()
{
DBUG_ASSERT(fixed);
null_value = 0;
String buffer;
String *json = nullptr;
// we try to get FbsonVal if first input arg is FBSON binary
// otherwise the input arg string is returned/stored in json
fbson::FbsonValue *pval = get_fbson_val(args[0], json, &buffer);
if (json)
{
if (pval)
return true; // FBSON blob
fbson::FbsonJsonParser parser;
return parser.parse(json->c_ptr_safe());
}
null_value = 1;
return false;
}
longlong Item_func_json_valid::val_int()
{
return (val_bool() ? 1 : 0);
}
/*
* Extracts key path (stored in args) from pval
* Input: args - path arguments
* arg_count - # of path elements
* pval - FBSON value object to extract from
* Output: FbsonValue object pointed by key path.
* NULL if path is invalid
*/
static fbson::FbsonValue*
json_extract_helper(Item **args,
uint arg_count,
fbson::FbsonValue *pval) /* in: fbson value object */
{
String buffer;
String *pstr;
for (unsigned i = 1; i < arg_count && pval; ++i)
{
if (pval->isObject())
{
if ( (pstr = args[i]->val_str(&buffer)) )
pval = ((fbson::ObjectVal*)pval)->find(pstr->c_ptr_safe());
else
pval = nullptr;
}
else if (pval->isArray())
{
if ( (pstr = args[i]->val_str(&buffer)) )
{
// array index parameter is 0-based
char *end = nullptr;
int index = strtol(pstr->c_ptr_safe(), &end, 0);
if (end && !*end)
pval = ((fbson::ArrayVal*)pval)->get(index);
else
pval = nullptr;
}
else
pval = nullptr;
}
else
pval = nullptr;
}
return pval;
}
String *Item_func_json_extract::intern_val_str(String *str, bool json_text)
{
DBUG_ASSERT(fixed);
null_value = 0;
String *pstr = nullptr;
// we try to get FbsonVal if first input arg is FBSON binary
// otherwise the input arg string is returned/stored in pstr
fbson::FbsonValue *pval = get_fbson_val(args[0], pstr, str);
if (pstr)
{
if (pval)
{
pval = json_extract_helper(args, arg_count, pval);
if (pval && current_thd->variables.use_fbson_output_format)
{
// if we output FBSON, set the returning str to the underlying buffer
str->set((char*)pval, pval->numPackedBytes(), collation.collation);
return str;
}
else if (ValueToString(pval,*str,collation.collation, json_text))
return str;
}
else
{
fbson::FbsonOutStream os;
pval = get_fbson_val(pstr->c_ptr_safe(), os);
pval = json_extract_helper(args, arg_count, pval);
if (pval && current_thd->variables.use_fbson_output_format)
{
str->copy((char*)pval, pval->numPackedBytes(), collation.collation);
return str;
}
else if (ValueToString(pval, *str, collation.collation, json_text))
return str;
}
}
null_value = 1;
return nullptr;
}
/*
* Item_func_json_extract
* The retrurned string format is valid JSON text, such as:
* true, false
* null
* "string"
* 123, 123.45
* {"key":"value"}
* [1,2,3]
*
* This is useful if we want to get value in JSON format from key path.
*/
String *Item_func_json_extract::val_str(String *str)
{
return intern_val_str(str, true /* json_text */);
}
void Item_func_json_extract::fix_length_and_dec()
{
// use the json data size (first arg)
ulonglong char_length= args[0]->max_char_length();
fix_char_length_ulonglong(char_length);
}
/*
* Item_func_json_extract_value
* The returned string format is raw value, such as:
* 1 (for true), 0 (for false)
* NULL row (for null)
* string (no double quotes)
* 123, 123.45
* {"key":"value"}
* [1,2,3]
*
* This is useful if the value will be directly used in comparsions on string
* vs. integer, in the WHERE clause.
*/
String *Item_func_json_extract_value::val_str(String *str)
{
return Item_func_json_extract::intern_val_str(str, false /* json_text */);
}
/*
* Item_func_json_contains_key
*/
bool Item_func_json_contains_key::val_bool()
{
DBUG_ASSERT(fixed);
null_value = 0;
String buffer;
String *pstr = nullptr;
// we try to get FbsonVal if first input arg is FBSON binary
// otherwise the input arg string is returned/stored in pstr
fbson::FbsonValue *pval = get_fbson_val(args[0], pstr, &buffer);
if (pstr)
{
if (pval)
{
return json_extract_helper(args, arg_count, pval) != nullptr;
}
else
{
fbson::FbsonOutStream os;
pval = get_fbson_val(pstr->c_ptr_safe(), os);
return json_extract_helper(args, arg_count, pval) != nullptr;
}
}
null_value = 1;
return false;
}
longlong Item_func_json_contains_key::val_int()
{
return (val_bool() ? 1 : 0);
}
/*
* Gets array length from FbsonValue object
* Input: pval - FbsonValue object (array)
* json - original JSON string
* Output: number of array elements (array length)
* 0 if pval is not an array object
*/
static longlong
json_array_length_helper(fbson::FbsonValue *pval, const char *json)
{
if (pval && pval->isArray())
return ((fbson::ArrayVal*)pval)->numElem();
else
my_error(ER_INVALID_JSON_ARRAY, MYF(0), json, 0, "Invalid array value");
return 0;
}
/*
* Item_func_json_array_length
*/
longlong Item_func_json_array_length::val_int()
{
DBUG_ASSERT(fixed);
null_value = 0;
String buffer;
String *pstr = nullptr;
// we try to get FbsonVal if first input arg is FBSON binary
// otherwise the input arg string is returned/stored in pstr
fbson::FbsonValue *pval = get_fbson_val(args[0], pstr, &buffer);
if (pstr)
{
if (pval)
{
return json_array_length_helper(pval, pstr->c_ptr_safe());
}
else
{
fbson::FbsonOutStream os;
pval = get_fbson_val(pstr->c_ptr_safe(), os);
return json_array_length_helper(pval, pstr->c_ptr_safe());
}
}
null_value = 1;
return 0;
}
/* Returns true if the item value matches that of the FbsonValue.
*
* For example, if the FbsonValue is Int8, check the val_int() of the item.
* If the FbsonValue is a String, check the val_str() of the item. */
static bool compare_fbson_value_with_item(Item *item, fbson::FbsonValue *pval)
{
DBUG_ASSERT(pval);
String str;
switch (pval->type())
{
case fbson::FbsonType::T_Null:
{
return (item->type() == Item::NULL_ITEM);
}
case fbson::FbsonType::T_False:
{
return (item->type() == Item::INT_ITEM && item->val_int() == 0);
}
case fbson::FbsonType::T_True:
{
return (item->type() == Item::INT_ITEM && item->val_int() == 1);
}
case fbson::FbsonType::T_String:
{
if (item->type() != Item::STRING_ITEM)
return false;
/* Compare strings character by character */
String *item_str = item->val_str(&str);
fbson::StringVal *str_val = (fbson::StringVal *)pval;
if (item_str->length() != str_val->getBlobLen())
return false;
return !memcmp(item_str->c_ptr(), str_val->getBlob(), item_str->length());
}
case fbson::FbsonType::T_Object:
case fbson::FbsonType::T_Array:
{
/* Perform SIMILAR comparison where all kvp's must match */
if (item->type() == Item::DOCUMENT_ITEM)
{
fbson::FbsonValue *pval2 = item->val_document_value(&str);
if (pval2)
return compare_fbson_value(pval, pval2);
}
return false;
}
case fbson::FbsonType::T_Int8:
{
return (item->type() == Item::INT_ITEM &&
item->val_int() == ((fbson::Int8Val*)pval)->val());
}
case fbson::FbsonType::T_Int16:
{
return (item->type() == Item::INT_ITEM &&
item->val_int() == ((fbson::Int16Val*)pval)->val());
}
case fbson::FbsonType::T_Int32:
{
return (item->type() == Item::INT_ITEM &&
item->val_int() == ((fbson::Int32Val*)pval)->val());
}
case fbson::FbsonType::T_Int64:
{
return (item->type() == Item::INT_ITEM &&
item->val_int() == ((fbson::Int64Val*)pval)->val());
}
case fbson::FbsonType::T_Double:
{
return ((item->type() == Item::DECIMAL_ITEM ||
item->type() == Item::REAL_ITEM) &&
item->val_real() == ((fbson::DoubleVal*)pval)->val());
}
default:
DBUG_ASSERT(0);
return false;
}
}
/*
* Gets whether or not a key or key-value pair is contained in a document
* Input: pval - FbsonValue object
* key - The key name to search for
* val - The value to search for (null is only search for key)
*
* Output: true if a key or key-value is contained in the document
* false if the key or key-value could not be found anywhere in document
*/
static bool json_contains_helper(Item *key, Item *val, fbson::FbsonValue *pval)
{
DBUG_ASSERT(pval);
/* Check key is a string */
if (key->type() != Item::STRING_ITEM)
{
my_error(ER_WRONG_ARGUMENTS, MYF(0), "KEY MUST BE STRING");
return false;
}
String buffer;
if (pval->isObject())
{
String *key_str = key->val_str(&buffer);
fbson::FbsonValue *find = ((fbson::ObjectVal*)pval)->find(key_str->c_ptr());
/* Find the key or find the key-value pair */
if ((find && !val) ||
(find && val && compare_fbson_value_with_item(val, find)))
return true;
/* Continue searching recursively at the next level */
fbson::ObjectVal::iterator it = ((fbson::ObjectVal*) pval)->begin();
fbson::ObjectVal::iterator it_end = ((fbson::ObjectVal*) pval)->end();
for (; it != it_end; ++it)
{
if (json_contains_helper(key, val, it->value()))
return true;
}
return false;
}
/* Recursively search all key-value pairs in the array */
if (pval->isArray())
{
for (uint i = 0; i < ((fbson::ArrayVal*)pval)->numElem(); i++)
{
if (json_contains_helper(key, val, ((fbson::ArrayVal*)pval)->get(i)))
return true;
}
}
return false;
}
/*
* Item_func_json_contains will return true if the key-value pair can be found
* on any level of the document. If the value is omitted, it will search for
* just the key.
*
* First argument is the column name
* Second argument is the key
* Third argument (optional) is the value
*/
bool Item_func_json_contains::val_bool()
{
DBUG_ASSERT(fixed);
null_value = 0;
String buffer;
String *pstr = nullptr;
/* "pstr" is set to the binary or string value of the item
* If "pstr" is the FBSON binary, "pval" will be the associated FbsonValue.
* If "pstr" is the JSON literal string, "pval" will be NULL */
fbson::FbsonValue *pval = get_fbson_val(args[0], pstr, &buffer);
if (pstr)
{
fbson::FbsonOutStream os;
if (!pval)
pval = get_fbson_val(pstr->c_ptr_safe(), os);
if (pval)
{
/* Search only for existence of key */
if (arg_count == 2)
return json_contains_helper(args[1], nullptr, pval);
/* Search for existence of key-value pair */
return json_contains_helper(args[1], args[2], pval);
}
}
my_error(ER_INVALID_JSON, MYF(0), args[0]->val_str(&buffer),
0, "Invalid object value");
return false;
}
longlong Item_func_json_contains::val_int()
{
return (val_bool() ? 1 : 0);
}
| 26.616314
| 80
| 0.62798
|
hkirsman
|
991079589d5147f94a6171c1143c3dd8af22f512
| 4,157
|
cpp
|
C++
|
environment/interpretation/obstacle_detector/src/ObstacleDetector.cpp
|
krishna95/freezing-batman
|
66f1ac7e73c65162f1593cf440c3363a9e4b1efb
|
[
"BSD-3-Clause"
] | null | null | null |
environment/interpretation/obstacle_detector/src/ObstacleDetector.cpp
|
krishna95/freezing-batman
|
66f1ac7e73c65162f1593cf440c3363a9e4b1efb
|
[
"BSD-3-Clause"
] | null | null | null |
environment/interpretation/obstacle_detector/src/ObstacleDetector.cpp
|
krishna95/freezing-batman
|
66f1ac7e73c65162f1593cf440c3363a9e4b1efb
|
[
"BSD-3-Clause"
] | null | null | null |
#include "../include/ObstacleDetector.hpp"
#include <climits>
#include <cassert>
void exit_with_help(){
std::cout<<
"Usage: lane-detector [options]\n"
"options:\n"
"-d : Non-zero for debug\n"
"-s : Subscriber topic name\n"
"-p : Publisher topic name\n"
"-l : Maximum distance we need \n"
"-m : Mininum distance we need \n"
;
exit(1);
}
void ObstacleDetector::publishData(){
cv_bridge::CvImage out_msg;
out_msg.encoding = sensor_msgs::image_encodings::MONO8;
out_msg.image = img;
out_msg.encoding = sensor_msgs::image_encodings::MONO8;
pub.publish(out_msg.toImageMsg());
}
void ObstacleDetector::interpret() {
if (debug){
cvNamedWindow("Control Box", 1);
}
int s=5;
if (debug) {
cvCreateTrackbar("Kernel 1", "Control Box", &s, 20);
cv::namedWindow("Raw Scan", 0);
cv::imshow("Raw Scan", img);
cv::waitKey(WAIT_TIME);
}
int dilation_size = EXPAND_OBS;
cv::Mat element = cv::getStructuringElement( cv::MORPH_ELLIPSE,
cv::Size( 2*dilation_size + 1, 2*dilation_size+1 ),
cv::Point( dilation_size, dilation_size ) );
cv::dilate(img, img, element);
if (debug) {
cv::namedWindow("Dilate Filter", 1);
cv::imshow("Dilate Filter", img);
cv::waitKey(WAIT_TIME);
}
publishData();
}
void ObstacleDetector::scanCallback(const sensor_msgs::LaserScan& scan) {
ROS_INFO("Scan callback called");
size_t size = scan.ranges.size();
float angle = scan.angle_min;
float maxRangeForContainer = scan.range_max - 0.1f;
img = img-img; // Assign zero to all pixels
for (size_t i = 0; i < size; ++i) {
float dist = scan.ranges[i];
if ((dist > scan.range_min) && (dist < maxRangeForContainer)) {
double x1 = -1 * sin(angle) * dist;
double y1 = cos(angle) * dist;
int x = (int) ((x1 * 100) + CENTERX);
int y = (int) ((y1 * 100) + CENTERY + LIDAR_Y_SHIFT);
if (x >= 0 && y >= min_dist && (int) x < MAP_MAX && (int) y < max_dist) {
int x2 = (x);
int y2 = (MAP_MAX - y - 30 - 1);
if(!(y2 >= 0 && y2 < MAP_MAX)){
continue;
}
img.at<uchar>(y2,x2)=255;
}
}
angle += scan.angle_increment;
}
interpret();
}
ObstacleDetector::ObstacleDetector(int argc, char *argv[], ros::NodeHandle &node_handle):nh(node_handle) {
topic_name = std::string("interpreter/obstacleMap/0");
sub_topic_name = std::string("/scan");
min_dist = 0;
max_dist = 400;
debug = 0;
for(int i=1;i<argc;i++)
{
if(argv[i][0] != '-') {
break;
}
if (++i>=argc) {
}
switch(argv[i-1][1])
{
case 'd':
debug = atoi(argv[i]);
break;
case 's':
sub_topic_name = std::string(argv[i]);
break;
case 'p':
topic_name = std::string(argv[i]);
break;
case 'l':
max_dist = atoi(argv[i]);
break;
case 'm':
min_dist = atoi(argv[i]);
break;
default:
fprintf(stderr, "Unknown option: -%c\n", argv[i-1][1]);
exit_with_help();
}
}
it = new image_transport::ImageTransport(nh);
sub = nh.subscribe(sub_topic_name.c_str(), 2, &ObstacleDetector::scanCallback,this);
img = cv::Mat(MAP_MAX,MAP_MAX,CV_8UC1,cvScalarAll(0));
pub = it->advertise(topic_name.c_str(), 10);
}
ObstacleDetector::~ObstacleDetector() {
}
int main(int argc, char** argv) {
std::string node_name;
// if (argc>1){
// node_name = std::string("interpreter_obstacleDetector_") + std::string(argv[1]);
// }
// else{
// node_name = std::string("interpreter_obstacleDetector_0");
// }
ros::init(argc, argv, node_name.c_str());
ros::NodeHandle nh;
ObstacleDetector obstacle_detector(argc, argv, nh);
ros::Rate loop_rate(LOOP_RATE);
ROS_INFO("Obstacle Detector Thread Started...");
while (ros::ok()) {
ros::spinOnce();
loop_rate.sleep();
}
ROS_INFO("Obstacle code exiting");
return 0;
}
| 26.819355
| 106
| 0.566514
|
krishna95
|
9915b7f000edc4973109b7ba5e2117c26dcbd15b
| 15,698
|
cpp
|
C++
|
world/Room.cpp
|
sg-p4x347/binding-of-ryesaac
|
f4b4b3e8f29c5fa2dda184691358605c41f539d5
|
[
"MIT"
] | null | null | null |
world/Room.cpp
|
sg-p4x347/binding-of-ryesaac
|
f4b4b3e8f29c5fa2dda184691358605c41f539d5
|
[
"MIT"
] | 6
|
2019-11-29T16:42:12.000Z
|
2019-12-08T07:03:23.000Z
|
world/Room.cpp
|
sg-p4x347/binding-of-ryesaac
|
f4b4b3e8f29c5fa2dda184691358605c41f539d5
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "Room.h"
#include "geom/ModelRepository.h"
using geom::ModelRepository;
#include "tex/TextureRepository.h"
using tex::TextureRepository;
#include "geom/CollisionUtil.h"
#include "geom/Sphere.h"
#include "game/Game.h"
using game::Game;
#include "game/MultimediaPlayer.h"
using game::MultimediaPlayer;
#include <GL/glut.h>
#include "World.h"
namespace world {
const float Room::k_collisionCullRange = 1.5f;
Room::Room(RoomType type, Vector3 center) : m_center(center), m_type(type), m_inCombat(false), m_duck(0)
{
}
void Room::Update(double elapsed)
{
AiUpdate(elapsed);
AgentUpdate(elapsed);
MovementUpdate(elapsed);
CollisionUpdate(elapsed);
DoorUpdate(elapsed);
CombatUpdate(elapsed);
ItemUpdate(elapsed);
//SweepUpdate(elapsed);
DeferredUpdate(elapsed);
PlayerLocationUpdate();
}
void Room::Render()
{
for (auto& entity : ER.GetIterator<Model, Position>()) {
Position& position = entity.Get<Position>();
Model& modelComp = entity.Get<Model>();
if (!modelComp.Hidden && modelComp.ModelPtr) {
glPushMatrix();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,TextureRepository::GetID(modelComp.ModelPtr->Name));
glTranslatef(position.Pos.X, position.Pos.Y, position.Pos.Z);
glRotatef(math::RadToDeg(position.Rot.X), 1.f, 0.f, 0.f);
glRotatef(math::RadToDeg(position.Rot.Y), 0.f, 1.f, 0.f);
glRotatef(math::RadToDeg(position.Rot.Z), 0.f, 0.f, 1.f);
geom::Model& model = *modelComp.ModelPtr;
for (auto& mesh : model.Meshes) {
glBegin(GL_TRIANGLES);
for (auto& index : mesh.Indices) {
geom::ModelMeshVertex& vertex = mesh.Vertices[index];
glNormal3f(vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z);
glTexCoord2f(vertex.TextureCoordinate.X, vertex.TextureCoordinate.Y);
glVertex3f(vertex.Position.X, vertex.Position.Y, vertex.Position.Z);
}
glEnd();
}
glBindTexture(GL_TEXTURE_2D, 0);
glPopMatrix();
}
}
}
EntityRepository& Room::GetER()
{
return ER;
}
Room::RoomType Room::GetType()
{
return m_type;
}
void Room::AddLoot(LootItem item)
{
m_loot.push_back(item);
}
void Room::DropLoot()
{
for (auto& loot : m_loot) {
string modelName = "";
switch (loot) {
case LootItem::Key: modelName = "key"; break;
}
m_deferredTasks.push_back([=] {
ER.CreateEntity(
Position(m_center, Vector3::Zero),
Movement(Vector3::Zero,Vector3(0.f,1.f,0.f)),
Model(ModelRepository::Get(modelName)),
Collision(std::make_shared<geom::Sphere>(Vector3::Zero, 0.25f)),
Item(loot)
);
});
}
// Consume the loot
m_loot.clear();
}
void Room::SweepAttack(int cornerIndex)
{
Vector3 pivot;
Vector3 start;
float angle;
switch (cornerIndex) {
case 0:
pivot = m_center + Vector3(-World::k_roomUnitSize.X, 0.f, -World::k_roomUnitSize.Y) * 0.5f;
start = m_center + Vector3(World::k_roomUnitSize.X, 0.f, -World::k_roomUnitSize.Y) * 0.5f;
angle = -math::PI / 2.f;
break;
case 1:
pivot = m_center + Vector3(World::k_roomUnitSize.X, 0.f, -World::k_roomUnitSize.Y) * 0.5f;
start = m_center + Vector3(-World::k_roomUnitSize.X, 0.f, -World::k_roomUnitSize.Y) * 0.5f;
angle = math::PI / 2.f;
break;
case 2:
pivot = m_center + Vector3(World::k_roomUnitSize.X, 0.f, World::k_roomUnitSize.Y) * 0.5f;
start = m_center + Vector3(-World::k_roomUnitSize.X, 0.f, World::k_roomUnitSize.Y) * 0.5f;
angle = math::PI / 2.f;
break;
case 3:
pivot = m_center + Vector3(-World::k_roomUnitSize.X, 0.f, World::k_roomUnitSize.Y) * 0.5f;
start = m_center + Vector3(World::k_roomUnitSize.X, 0.f, World::k_roomUnitSize.Y) * 0.5f;
angle = -math::PI / 2.f;
break;
}
Sweep sweep;
sweep.Duration = 6.f;
for (float t = 0; t <= 1; t += 1.f / 20) {
sweep.Waypoints.push_back(pivot + (math::CreateRotationY(angle * t) * (start - pivot)));
}
m_deferredTasks.push_back([=] {
ER.CreateEntity(
Position(),
Movement(Vector3::Zero, Vector3(0.f, angle / sweep.Duration, 0.f)),
Sweep(sweep),
Model(ModelRepository::Get("duck_head")),
Agent(Agent::AgentFaction::Toast, 0.f, 20, 0.f, 0.f, 1),
Collision(std::make_shared<geom::Sphere>(Vector3::Zero, 1.f))
);
});
}
ecs::EntityID Room::CreateDuck()
{
return ER.CreateEntity(
Position(Vector3::Zero, Vector3(0.f, math::PI, 0.f)),
Sweep(),
Model(ModelRepository::Get("duck_head")),
Agent(Agent::AgentFaction::Toast, 0.f, 20, 0.f, 0.f, 1),
Collision(std::make_shared<geom::Sphere>(Vector3::Zero, 1.f))
);
}
void Room::StompAttack(Vector2 focus)
{
m_deferredTasks.push_back([=] {
if (!m_duck) {
m_duck = CreateDuck();
}
for (auto& entity : ER.GetIterator<Sweep>()) {
auto& sweep = entity.Get<Sweep>();
if (sweep.ID == m_duck) {
sweep.Duration = 6.f;
static float start = 4.f;
sweep.Waypoints.push_back(Vector3(focus.X, start, focus.Y));
sweep.Waypoints.push_back(Vector3(focus.X, 0.f, focus.Y));
sweep.Waypoints.push_back(Vector3(focus.X, 0.f, focus.Y));
sweep.Waypoints.push_back(Vector3(focus.X, start, focus.Y));
}
}
});
}
void Room::AgentUpdate(double elapsed)
{
for (auto& entity : ER.GetIterator<Agent, Model, Movement, Collision, Position>()) {
auto& agent = entity.Get<Agent>();
auto& model = entity.Get<Model>();
auto& movement = entity.Get<Movement>();
auto& collision = entity.Get<Collision>();
auto& position = entity.Get<Position>();
// Convert agent heading into a velocity
agent.Heading.Normalize();
movement.Velocity = agent.Heading * agent.Speed;
// Update attack cooldown
agent.AttackCooldown = max(0.0, agent.AttackCooldown - elapsed);
// Update recovery cooldown
agent.RecoveryCooldown = max(0.0, agent.RecoveryCooldown - elapsed);
// Strobe the model while in cooldown
if (agent.RecoveryCooldown) {
static const float k_recoveryFlashPeriod = 0.25f;
model.Hidden = std::fmodf(agent.RecoveryCooldown, k_recoveryFlashPeriod) <= k_recoveryFlashPeriod * 0.5f;
}
else {
model.Hidden = false;
}
if (agent.Attack && !agent.AttackCooldown) {
shared_ptr<geom::Model> projectileModel;
switch (agent.Faction) {
case Agent::AgentFaction::Bread:
projectileModel = ModelRepository::Get("butter");
break;
case Agent::AgentFaction::Toast:
projectileModel = ModelRepository::Get("butter");
break;
}
m_deferredTasks.push_back([=] {
Agent projectile = Agent(agent.Faction, 8.f, 0, 0.f, 0.f, 1);
projectile.Heading = Vector3(std::cos(-position.Rot.Y), 0.f, std::sin(-position.Rot.Y));
ER.CreateEntity(
Position(position),
projectile,
Movement(Vector3::Zero,Vector3(0.f,math::TWO_PI * 5.f,0.f)),
Collision(std::make_shared<geom::Sphere>(Vector3::Zero, 0.25), (uint32_t)CollisionChannel::Projectile),
Model(projectileModel)
);
});
agent.AttackCooldown = agent.AttackPeriod;
}
if (agent.MaxHealth > 0) {
if (agent.Health <= 0) {
m_deferredTasks.push_back([=] {
ER.Remove(agent.ID);
});
}
else {
// Apply damage if not in recovery (temporary invincibility after taking damage)
if (!agent.RecoveryCooldown && !collision.Contacts.empty()) {
for (auto& other : ER.GetIterator<Agent>()) {
auto& otherAgent = other.Get<Agent>();
// check to see if other is a different faction and shows up in our contact list
if (otherAgent.Faction != agent.Faction && collision.Contacts.count(otherAgent.ID)) {
// Apply other agent's damage to our health
agent.Health -= otherAgent.Damage;
// Start recovery cooldown
agent.RecoveryCooldown = agent.RecoveryPeriod;
}
}
}
}
}
else {
if (!collision.Contacts.empty()) {
m_deferredTasks.push_back([=] {
ER.Remove(agent.ID);
});
}
}
}
}
void Room::AiUpdate(double elapsed)
{
for (auto& playerEntity : ER.GetIterator<Player, Agent, Position>()) {
auto& player = playerEntity.Get<Agent>();
auto& playerPos = playerEntity.Get<Position>();
for (auto& enemyEntity : ER.GetIterator<AI,Agent, Position>()) {
auto& enemy = enemyEntity.Get<Agent>();
auto& enemyPos = enemyEntity.Get<Position>();
if (enemy.Faction != player.Faction) {
enemy.Heading = playerPos.Pos - enemyPos.Pos;
enemyPos.Rot.Y = -std::atan2f(enemy.Heading.Z, enemy.Heading.X);
}
}
}
}
void Room::MovementUpdate(double elapsed)
{
for (auto& entity : ER.GetIterator<Movement, Position>()) {
auto& movement = entity.Get<Movement>();
auto& position = entity.Get<Position>();
position.Pos += movement.Velocity * elapsed;
position.Rot += movement.AngularVelocity * elapsed;
// Wrap rotations around 2 pi
position.Rot.X = std::fmodf(position.Rot.X, math::TWO_PI);
position.Rot.Y = std::fmodf(position.Rot.Y, math::TWO_PI);
position.Rot.Z = std::fmodf(position.Rot.Z, math::TWO_PI);
}
}
void Room::CollisionUpdate(double elapsed)
{
// Clear contacts
for (auto& collider : ER.GetIterator<Collision>()) {
collider.Get<Collision>().Contacts.clear();
}
for (auto& dynamicCollider : ER.GetIterator<Movement,Collision, Position>()) {
auto& movement = dynamicCollider.Get<Movement>();
auto& dynamicCollision = dynamicCollider.Get<Collision>();
auto& dynamicPosition = dynamicCollider.Get<Position>();
auto dynamicCollisionVolume = dynamicCollision.CollisionVolume->Transform(dynamicPosition.GetTransform());
for (auto& staticCollider : ER.GetIterator<Collision, Position>()) {
auto& staticCollision = staticCollider.Get<Collision>();
auto& staticPosition = staticCollider.Get<Position>();
if (
// This collision has already been handled by the other entity
!dynamicCollision.Contacts.count(staticCollision.ID)
// Only handle collisions between disjoint channels
&& !(dynamicCollision.Channel & staticCollision.Channel)
// Don't collide with ourself
&& staticCollision.ID != dynamicCollision.ID
// Be within a sane range
&& (staticPosition.Pos - dynamicPosition.Pos).LengthSquared() < k_collisionCullRange * k_collisionCullRange
) {
auto staticCollisionVolume = staticCollision.CollisionVolume->Transform(staticPosition.GetTransform());
// Use GJK to test if an intersection exists
geom::GjkIntersection intersection;
if (geom::GJK(*dynamicCollisionVolume, *staticCollisionVolume, intersection)) {
// Use EPA to get the contact details
Collision::Contact contact;
if (geom::EPA(*dynamicCollisionVolume, *staticCollisionVolume, intersection, contact)) {
// Immediately correct the position in the X-Z plane
dynamicPosition.Pos.X += contact.Normal.X * contact.PenetrationDepth;
dynamicPosition.Pos.Z += contact.Normal.Z * contact.PenetrationDepth;
// Update collision volume
dynamicCollisionVolume = dynamicCollision.CollisionVolume->Transform(dynamicPosition.GetTransform());
// Register contacts on both colliders
contact.Collider = staticCollision.ID;
dynamicCollision.Contacts[contact.Collider] = contact;
contact.Collider = dynamicCollision.ID;
staticCollision.Contacts[contact.Collider] = contact;
}
}
}
}
}
}
void Room::PlayerLocationUpdate()
{
for (auto& playerEntity : ER.GetIterator<Player, Collision>()) {
auto& player = playerEntity.Get<Player>();
if (m_type == RoomType::Duck) {
if (m_inCombat)
{
if (Game::GetInstance().state != GameState::InGame_BossBattle)
{
Game::GetInstance().state = GameState::InGame_BossBattle;
Game::GetInstance().bossStart = clock();
MultimediaPlayer::SetUp("./Assets/audio/Boss_Battle_Condesa_DuckAttacks_Overlay.wav", true, true);
MultimediaPlayer::GetInstance().startAudio();
}
}
else
{
if (Game::GetInstance().state != GameState::Outro)
{
Game::GetInstance().state = GameState::Outro;
MultimediaPlayer::SetUp("./Assets/audio/Boss_Battle_Victory.wav", true, true);
MultimediaPlayer::GetInstance().startAudio();
}
}
}
}
}
void Room::DoorUpdate(double elapsed)
{
for (auto& entity : ER.GetIterator<Door, Model, Collision>()) {
auto& door = entity.Get<Door>();
auto& model = entity.Get<Model>();
auto& collision = entity.Get<Collision>();
if (door.State == Door::DoorState::Locked) {
for (auto& playerEntity : ER.GetIterator<Player, Collision>()) {
auto& player = playerEntity.Get<Player>();
if (player.Inventory[LootItem::Key] > 0) {
if (playerEntity.Get<Collision>().Contacts.count(door.ID)) {
// unlock the door
door.State = Door::DoorState::Open;
// consume the key
player.Inventory[LootItem::Key]--;
break;
}
}
}
}
// Update model
model.ModelPtr = ModelRepository::Get("door_" + std::to_string((int)door.State));
/* Update collision channel
As long as the player shares this channel, collision will not be handled */
switch (door.State) {
case Door::DoorState::Closed:
case Door::DoorState::Locked:
collision.Channel = 0;
break;
case Door::DoorState::Open:
collision.Channel = (uint32_t)CollisionChannel::Door;
break;
}
}
}
void Room::CombatUpdate(double elapsed)
{
bool previousCombatState = m_inCombat;
// While there are enemy agents in the room, keep the doors closed
for (auto& agent : ER.GetIterator<Agent>()) {
if (agent.Get<Agent>().Faction != Agent::AgentFaction::Bread) {
// Close all the doors if they are open
m_inCombat = true;
for (auto& door : ER.GetIterator<Door>()) {
if (door.Get<Door>().State == Door::DoorState::Open)
door.Get<Door>().State = Door::DoorState::Closed;
}
return;
}
}
// not in combat - Open all the non-locked doors
m_inCombat = false;
for (auto& door : ER.GetIterator<Door>()) {
if (door.Get<Door>().State == Door::DoorState::Closed)
door.Get<Door>().State = Door::DoorState::Open;
}
// Drop loot if the combat state has dropped to false
if (previousCombatState && !m_inCombat) {
DropLoot();
}
}
void Room::ItemUpdate(double elapsed)
{
for (auto& playerEntity : ER.GetIterator<Player, Collision>()) {
auto& player = playerEntity.Get<Player>();
for (auto& entity : ER.GetIterator<Item>()) {
auto& item = entity.Get<Item>();
if (playerEntity.Get<Collision>().Contacts.count(item.ID)) {
// Perform the transaction
player.Inventory[item.Type]++;
m_deferredTasks.push_back([=] {
ER.Remove(item.ID);
});
}
}
}
}
void Room::SweepUpdate(double elapsed)
{
for (auto& entity : ER.GetIterator<Sweep, Position>()) {
auto& sweep = entity.Get<Sweep>();
auto& position = entity.Get<Position>();
sweep.Progress = min(sweep.Duration, sweep.Progress + elapsed);
float percent = (sweep.Progress / sweep.Duration);
sweep.CurrentWaypoint = percent * (sweep.Waypoints.size() - 1);
float linePercent = percent - ((float)sweep.CurrentWaypoint / (float)(sweep.Waypoints.size() - 1));
Vector3 currentWaypoint = sweep.Waypoints[sweep.CurrentWaypoint];
if (sweep.CurrentWaypoint < sweep.Waypoints.size() - 1) {
Vector3 nextWaypoint = sweep.Waypoints[sweep.CurrentWaypoint + 1];
position.Pos = (nextWaypoint - currentWaypoint) * linePercent + currentWaypoint;
}
else {
position.Pos = currentWaypoint;
}
}
}
void Room::DeferredUpdate(double elapsed)
{
for (auto& task : m_deferredTasks) {
task();
}
m_deferredTasks.clear();
}
}
| 31.270916
| 112
| 0.659511
|
sg-p4x347
|
9916b25ce105f4344fc80f98d780b27c0deb21f3
| 621
|
cpp
|
C++
|
packages/orchestrator/third_party/slt_setting/examples/00_hello_setting.cpp
|
cogment/cogment
|
55df705fce16942d396324dd733b4c60af729738
|
[
"Apache-2.0"
] | 4
|
2020-08-03T20:07:41.000Z
|
2020-08-03T20:11:29.000Z
|
packages/orchestrator/third_party/slt_setting/examples/00_hello_setting.cpp
|
cogment/cogment
|
55df705fce16942d396324dd733b4c60af729738
|
[
"Apache-2.0"
] | null | null | null |
packages/orchestrator/third_party/slt_setting/examples/00_hello_setting.cpp
|
cogment/cogment
|
55df705fce16942d396324dd733b4c60af729738
|
[
"Apache-2.0"
] | 2
|
2021-02-20T02:42:10.000Z
|
2022-03-23T23:47:21.000Z
|
#include "slt/settings.h"
#include "slt/settings_context.h"
#include <string>
slt::Setting ip_address = slt::Setting_builder<std::string>()
.with_default("localhost")
.with_description("The IP address to operate on")
.with_arg("ip")
.with_env_variable("IP");
int main(int argc, const char* argv[]) {
slt::Settings_context ctx("hello_settings", argc, argv);
if (ctx.help_requested()) {
return 0;
}
std::cout << "the value of ip_address is: " << ip_address.get() << "\n";
return 0;
}
| 28.227273
| 79
| 0.550725
|
cogment
|
9919c30b52c598b849cfdd1c15db09b41bffaef6
| 1,317
|
cpp
|
C++
|
src/Misc/PKCS1.cpp
|
httese/OpenPGP
|
7dce08dc8b72eeb0dcbf3df56d64606a6b957938
|
[
"MIT"
] | 99
|
2015-01-06T01:53:26.000Z
|
2022-01-31T18:18:27.000Z
|
src/Misc/PKCS1.cpp
|
httese/OpenPGP
|
7dce08dc8b72eeb0dcbf3df56d64606a6b957938
|
[
"MIT"
] | 27
|
2015-03-09T05:46:53.000Z
|
2020-05-06T02:52:18.000Z
|
src/Misc/PKCS1.cpp
|
httese/OpenPGP
|
7dce08dc8b72eeb0dcbf3df56d64606a6b957938
|
[
"MIT"
] | 42
|
2015-03-18T03:44:43.000Z
|
2022-03-31T21:34:06.000Z
|
#include "Misc/PKCS1.h"
#include "Misc/pgptime.h"
#include "RNG/RNGs.h"
#include "common/includes.h"
namespace OpenPGP {
std::string EME_PKCS1v1_5_ENCODE(const std::string & m, const unsigned int & k) {
if (m.size() > (k - 11)) {
// "Error: EME-PKCS1 Message too long.\n";
return "";
}
std::string EM = zero + "\x02";
while (EM.size() < k - m.size() - 1) {
if (const unsigned char c = RNG::RNG().rand_bytes(1)[0]) { // non-zero octets only
EM += std::string(1, c);
}
}
return EM + zero + m;
}
std::string EME_PKCS1v1_5_DECODE(const std::string & m) {
if (m.size() > 11) {
if (!m[0]) {
if (m[1] == '\x02') {
std::string::size_type x = 2;
while ((x < m.size()) && m[x]) {
x++;
}
return m.substr(x + 1, m.size() - x - 1);
}
}
}
// "Error: EME-PKCS1 Decryption Error.\n";
return "";
}
std::string EMSA_PKCS1_v1_5(const uint8_t & hash, const std::string & hashed_data, const unsigned int & keylength) {
return zero + "\x01" + std::string(keylength - (Hash::ASN1_DER.at(hash).size() >> 1) - 3 - (Hash::LENGTH.at(hash) >> 3), (char) 0xffU) + zero + unhexlify(Hash::ASN1_DER.at(hash)) + hashed_data;
}
}
| 28.021277
| 197
| 0.515566
|
httese
|
991a1d83e9ae9220fd6908a25dc12d3db0a6c07f
| 1,009
|
cpp
|
C++
|
Warcraft Heroes Beyond Time/Warcraft Heroes Beyond Time/EnergyItem.cpp
|
SoftCactusTeam/Warcraft_Adventures
|
7b44294d44094ce690abe90348dd87f42cdae07d
|
[
"MIT"
] | 9
|
2018-03-19T21:36:53.000Z
|
2020-02-28T07:05:17.000Z
|
Warcraft Heroes Beyond Time/Warcraft Heroes Beyond Time/EnergyItem.cpp
|
SoftCactusTeam/Warcraft-Heroes-Beyond-Time
|
7b44294d44094ce690abe90348dd87f42cdae07d
|
[
"MIT"
] | 87
|
2018-03-04T15:04:57.000Z
|
2018-06-07T08:42:55.000Z
|
Warcraft Heroes Beyond Time/Warcraft Heroes Beyond Time/EnergyItem.cpp
|
SoftCactusTeam/Warcraft_Adventures
|
7b44294d44094ce690abe90348dd87f42cdae07d
|
[
"MIT"
] | 2
|
2018-02-14T08:13:05.000Z
|
2018-02-16T19:17:57.000Z
|
#include "EnergyItem.h"
#include "Scene.h"
#include "Thrall.h"
#include "Application.h"
#include "ModuleRender.h"
EnergyItem::EnergyItem()
{
}
EnergyItem::~EnergyItem()
{
}
bool EnergyItem::Start()
{
return true;
}
bool EnergyItem::Act(ModuleItems::ItemEvent event, float dt)
{
switch (event)
{
case ModuleItems::ItemEvent::PLAYER_HITTED:
App->scene->player->IncreaseEnergy(ModuleItems::energywhenHitted);
break;
}
return true;
}
bool EnergyItem::Draw()
{
return true;
}
bool EnergyItem::printYourStuff(iPoint pos)
{
//The GUI uses this method, fill it in all the items.
iPoint iconPos = { 171 / 2 - 31 / 2 ,50 };
App->render->Blit(App->items->getItemsTexture(), pos.x + iconPos.x, pos.y + iconPos.y, &SDL_Rect(ENERGY_ITEM), 1, 0);
printMyString((char*)Title.data(), { 171 / 2 + pos.x, 100 + pos.y }, true);
printMyString((char*)softDescription.data(), { 171 / 2 + pos.x, 150 + pos.y });
return true;
}
const std::string EnergyItem::myNameIs() const
{
return std::string(Title);
}
| 19.037736
| 118
| 0.683845
|
SoftCactusTeam
|
991e8d7497ac0af4900c06138616500c5a5df0b2
| 297
|
hpp
|
C++
|
lib/systems/simulator/UdpMessageHandlerInterface.hpp
|
aep/qtsl
|
8710cbbf2405ad9147c399d1afea906a80b1fbac
|
[
"MIT"
] | null | null | null |
lib/systems/simulator/UdpMessageHandlerInterface.hpp
|
aep/qtsl
|
8710cbbf2405ad9147c399d1afea906a80b1fbac
|
[
"MIT"
] | null | null | null |
lib/systems/simulator/UdpMessageHandlerInterface.hpp
|
aep/qtsl
|
8710cbbf2405ad9147c399d1afea906a80b1fbac
|
[
"MIT"
] | null | null | null |
#ifndef QTSL_UdpMessageHandlerInterface_H
#define QTSL_UdpMessageHandlerInterface_H
namespace qtsl{
namespace udp{
struct UdpMessage;
};
class UdpMessageHandlerInterface{
public:
virtual void udpMessageHandler(qtsl::udp::UdpMessage * message)=0;
};
};
#endif
| 19.8
| 74
| 0.720539
|
aep
|
9922a99b0238dfc09a07e514936e3b29593b130c
| 28,042
|
cpp
|
C++
|
src/hi/hicalendar.cpp
|
SC-One/HiCalendar
|
dfda3134dfbde0c7845c4c3e2d41635721511678
|
[
"MIT"
] | 30
|
2020-10-30T13:01:10.000Z
|
2022-02-04T04:54:11.000Z
|
src/hi/hicalendar.cpp
|
Qt-QML/HiCalendar
|
a9e1f2fcd111f2d5c8eb1af705acef829584b102
|
[
"MIT"
] | null | null | null |
src/hi/hicalendar.cpp
|
Qt-QML/HiCalendar
|
a9e1f2fcd111f2d5c8eb1af705acef829584b102
|
[
"MIT"
] | 6
|
2020-10-31T09:38:13.000Z
|
2022-02-04T07:20:21.000Z
|
#include "include/hi/hicalendar.hpp"
////::::::::::::::::::::::::::::::::::::::::::: YearMonthDay
YearMonthDay::YearMonthDay(int _Year, int _Month, int _Day, QObject *parent):
QObject(parent),year(_Year),month(_Month),day(_Day) {}
YearMonthDay::YearMonthDay(const YearMonthDay &other):
QObject(other.parent()),year(other.year),month(other.month),day(other.day) {}
YearMonthDay& YearMonthDay::operator=(const YearMonthDay &other)
{
this->setParent(other.parent());
this->year = other.year;
this->month = other.month;
this->day = other.day;
return *this;
}
bool YearMonthDay::operator !=(const YearMonthDay &other)
{
return (this->parent() != other.parent() || this->year != other.year || this->month != other.month || this->day != other.day);
}
bool YearMonthDay::operator ==(const YearMonthDay &other)
{
return !(*this != other);
}
YearMonthDay::~YearMonthDay() {}
//////::::::::::::::::::::::::::::::::::::::::::: HiCalendarSelectedDayData
HiCalendarDayModel::HiCalendarDayModel(QDate _Date, int _DayOfCustomMonth, int _DayOfCustomWeek, int _DayInCustomWeekOfMonth, bool _IsHoliday , QObject *parent):
QObject(parent),
_date(_Date),
_is_holiday(_IsHoliday)
{
_day_of_custom_month = 1;
_day_of_custom_week = 1;
_day_in_custom_week_of_month = 1;
if (_DayOfCustomMonth > 0 && _DayOfCustomMonth <32)
{
_day_of_custom_month = _DayOfCustomMonth;
}
if(_DayOfCustomWeek > 0 && _DayOfCustomWeek < 8)
{
_day_of_custom_week = _DayOfCustomWeek;
}
if(_DayInCustomWeekOfMonth > 0 && _DayInCustomWeekOfMonth < 7)
{
_day_in_custom_week_of_month = _DayInCustomWeekOfMonth;
}
emit dayModifiedSi();
}
HiCalendarDayModel::HiCalendarDayModel(const HiCalendarDayModel& item):
QObject(item.parent()),
_date(item.getGeorgianDate()),
_day_of_custom_month(item.getDayOfCustomMonth()),
_day_of_custom_week(item.getDayOfCustomWeek()),
_day_in_custom_week_of_month(item.getDayInCustomWeekNOfMonth()),
_is_holiday(item.isHoliday())
{
emit dayModifiedSi();
}
HiCalendarDayModel& HiCalendarDayModel::operator=(const HiCalendarDayModel &other)
{
this->_day_of_custom_month = other.getDayOfCustomMonth();
this->_day_of_custom_week = other.getDayOfCustomWeek();
this->_day_in_custom_week_of_month = other.getDayInCustomWeekNOfMonth();
this->_date = other.getGeorgianDate();
emit dayModifiedSi();
return *this;
}
bool HiCalendarDayModel::operator!=(const HiCalendarDayModel &other) const
{
return (_date != other.getGeorgianDate()
|| _day_of_custom_month != other.getDayOfCustomMonth()
|| _day_of_custom_week != other.getDayOfCustomWeek()
|| _day_in_custom_week_of_month != other.getDayInCustomWeekNOfMonth());
}
bool HiCalendarDayModel::operator==(const HiCalendarDayModel &other) const
{
return !(*this != other);
}
YearMonthDay HiCalendarDayModel::getJalaliDateAsYearMonthDay() const
{
QCalendar calendar(QCalendar::System::Jalali);
QCalendar::YearMonthDay jalali_date = calendar.partsFromDate(_date);
YearMonthDay output{jalali_date.year,jalali_date.month,jalali_date.day,this->parent()};
return output;
}
int HiCalendarDayModel::getJalaliYear() const
{
QCalendar calendar(QCalendar::System::Jalali);
QCalendar::YearMonthDay jalali_date = calendar.partsFromDate(_date);
return jalali_date.year;
}
int HiCalendarDayModel::getJalaliMonth() const
{
QCalendar calendar(QCalendar::System::Jalali);
QCalendar::YearMonthDay jalali_date = calendar.partsFromDate(_date);
return jalali_date.month;
}
int HiCalendarDayModel::getJalaloDay() const
{
QCalendar calendar(QCalendar::System::Jalali);
QCalendar::YearMonthDay jalali_date = calendar.partsFromDate(_date);
return jalali_date.day;
}
YearMonthDay HiCalendarDayModel::getGeorgianDateAsYearMonthDay() const
{
YearMonthDay output{_date.year(),_date.month(),_date.day(),this->parent()};
return output;
}
int HiCalendarDayModel::getGeorgianYear() const
{
return _date.year();
}
int HiCalendarDayModel::getGeorgianMonth() const
{
return _date.month();
}
int HiCalendarDayModel::getGeorgianDay() const
{
return _date.day();
}
YearMonthDay HiCalendarDayModel::getIslamicDateAsYearMonthDay() const
{
QCalendar calendar(QCalendar::System::IslamicCivil);
QCalendar::YearMonthDay islamic_date = calendar.partsFromDate(_date);
YearMonthDay output{islamic_date.year,islamic_date.month,islamic_date.day,this->parent()};
return output;
}
int HiCalendarDayModel::getIslamicYear() const
{
QCalendar calendar(QCalendar::System::IslamicCivil);
QCalendar::YearMonthDay islamic_date = calendar.partsFromDate(_date);
return islamic_date.year;
}
int HiCalendarDayModel::getIslamicMonth() const
{
QCalendar calendar(QCalendar::System::IslamicCivil);
QCalendar::YearMonthDay islamic_date = calendar.partsFromDate(_date);
return islamic_date.month;
}
int HiCalendarDayModel::getIslamicDay() const
{
QCalendar calendar(QCalendar::System::IslamicCivil);
QCalendar::YearMonthDay islamic_date = calendar.partsFromDate(_date);
return islamic_date.day;
}
bool HiCalendarDayModel::isDayOver() const
{
return (QDate::currentDate() > _date);
}
bool HiCalendarDayModel::isToday() const
{
return (_date == QDate::currentDate());
}
bool HiCalendarDayModel::isHoliday() const
{
return _is_holiday;
}
int HiCalendarDayModel::getDayOfCustomMonth() const
{
return _day_of_custom_month;
}
int HiCalendarDayModel::getDayOfCustomWeek() const
{
return _day_of_custom_week;
}
int HiCalendarDayModel::getDayInCustomWeekNOfMonth() const
{
return _day_in_custom_week_of_month;
}
QDate HiCalendarDayModel::getGeorgianDate() const
{
return _date;
}
QString HiCalendarDayModel::toString() const
{
QString output = "{\"jalali_year\":"+ QString::number(getJalaliYear()) + ",\"jalali_month\":"+ QString::number(getJalaliMonth()) + ",\"jalali_day\":"+ QString::number(getJalaloDay()) + ",\"georgian_year\":"+ QString::number(getGeorgianYear()) + ",\"georgian_month\":"+ QString::number(getGeorgianMonth()) + ",\"georgian_day\":"+ QString::number(getGeorgianDay()) + ",\"islamic_year\":"+ QString::number(getIslamicYear()) + ",\"islamic_month\":"+ QString::number(getIslamicMonth()) + ",\"islamic_day\":"+ QString::number(getIslamicDay()) + ",\"is_day_over\":"+ (isDayOver()? "true" : "false") + ",\"is_today\":"+ (isToday()? "true" : "false") + ",\"day_of_custom_month\":"+ QString::number(getDayOfCustomMonth()) + ",\"day_of_custom_week\":"+ QString::number(getDayOfCustomWeek()) + ",\"day_in_custom_week_n_of_month\":"+ QString::number(getDayInCustomWeekNOfMonth())+",\"is_holiday_in_calendar_selected_type\":"+ (isHoliday()?"true":"false") + "}";
return output;
}
HiCalendarDayModel::~HiCalendarDayModel() {}
//////////::::::::::::::::::::::::::::::::::::: Calendar Controller
HiCalendarController::HiCalendarController(HiCalendarController::CalendarTypes _CalendarType, QObject *_Parent):
QObject(_Parent),
_calendar_type(_CalendarType),
_current_selected_day(nullptr)
{
emit calendarTypeChanged(_calendar_type);
}
HiCalendarController::HiCalendarController(const HiCalendarController &_Input):
QObject(_Input.parent()),
_days_of_current_month_list(_Input.getDaysOfCurrentMonth()),
_calendar_type(_Input.getCalendarType()),
_current_selected_day(nullptr)
{
emit calendarTypeChanged(_calendar_type);
}
HiCalendarController::CalendarTypes HiCalendarController::getCalendarType() const
{
return _calendar_type;
}
QString HiCalendarController::currentMonthHeaderInfo() const
{
return _current_month_header_info;
}
const QVariantList HiCalendarController::getDaysOfCurrentMonth() const
{
return _days_of_current_month_list;
}
HiCalendarDayModel* HiCalendarController::getCurrentSelectedDay() const
{
return _current_selected_day;
}
void HiCalendarController::showCurrentSelectedYearMonthDay(QDate _SelectedDate)
{
QStringList jalali_months = {"فروردین" , "اردیبهشت", "خرداد", "تیر", "اَمرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند"};
QStringList georgian_months = {"January","February","March","April","May","June","July","August","September","October","November","December"};
QStringList islamic_months = {"محرم" , "صفر", "ربیعالاول", "ربیعالثانی", "جمادیالاول", "جمادیالثانی", "رجب", "شعبان", "رمضان", "شوال", "ذیقعده", "ذیحجه"};
int day_of_week = 1;
int day_is_in_week_N_of_month = 0;
int year = 1;
int month = 1;
int day = 1;
if(_SelectedDate == QDate(1,1,1))
{
_SelectedDate = QDate::currentDate();
}
QDate newDate = _SelectedDate;
if(_current_selected_day != nullptr)//is not first
{
clearCurrentDays();
_current_selected_day = nullptr;
}
if (getCalendarType() == HiCalendarController::CalendarTypes::Jalali)
{
QCalendar jalali_calendar(QCalendar::System::Jalali);
QCalendar islamic_calendar(QCalendar::System::IslamicCivil);
int first_georgian_month = 0;
int second_georgian_month = 0;
int first_islamic_month = 0;
int second_islamic_month = 0;
int first_georgian_year = 0;
int second_georgian_year = 0;
int first_islamic_year = 0;
int second_islamic_year = 0;
QCalendar::YearMonthDay jalali_date = jalali_calendar.partsFromDate(_SelectedDate);
year = jalali_date.year;//current selected year as jalali
month = jalali_date.month;//current selected month as jalali
day = jalali_date.day;//current selected day as jalali
if (day > 1)
{
newDate = _SelectedDate.addDays(-(day-1));//first day of selected month as georgian
}
QCalendar::YearMonthDay islamic_date = islamic_calendar.partsFromDate(newDate);
first_georgian_month = newDate.month();
first_georgian_year = newDate.year();
first_islamic_month = islamic_date.month;
first_islamic_year = islamic_date.year;
int day_counter = 1;
while ( jalali_calendar.partsFromDate(newDate).month == month)
{
bool is_holiday = false;
if ( newDate.dayOfWeek() < 6)
{
day_of_week = newDate.dayOfWeek()+2;
}
else
{
day_of_week = newDate.dayOfWeek() % 6 +1;
}
if(day_of_week == 1 || day_is_in_week_N_of_month == 0)
{
day_is_in_week_N_of_month++;
}
islamic_date = islamic_calendar.partsFromDate(newDate);
if(islamic_date.month != first_islamic_month)
{
second_islamic_month = islamic_date.month;
}
if(islamic_date.year != first_islamic_year)
{
second_islamic_year = islamic_date.year;
}
if(newDate.month() != first_georgian_month)
{
second_georgian_month = newDate.month();
}
if(newDate.year() != first_georgian_year)
{
second_georgian_year = newDate.year();
}
//jalali holidays
if (newDate.dayOfWeek() == 5) is_holiday = true;
if (month == 1)
{
if (day_counter >= 1 && day_counter < 5) is_holiday = true;
if (day_counter == 12 || day_counter == 13) is_holiday = true;
}
if (month == 3)
{
if (day_counter == 14 || day_counter == 15) is_holiday = true;
}
if (month == 11 && day_counter == 22) is_holiday = true;
if (month == 12 && (day_counter == 29 || day_counter == 30)) is_holiday = true;
//islamic holidays
if (islamic_date.month == 1)
{
if (islamic_date.day == 9 || islamic_date.day == 10) is_holiday = true;//tasua-ashura
}
if (islamic_date.month == 2)
{
qDebug()<<"=============2";
if (islamic_date.day == 20 || islamic_date.day == 28 || islamic_date.day == 30) is_holiday = true;
if (islamic_date.day == 29)
{
qDebug()<<newDate.toString();
QDate tmpDate = newDate.addDays(1);
qDebug()<<newDate<<" ====> ttt " << tmpDate.toString();
QCalendar::YearMonthDay islamic_date_tmp = islamic_calendar.partsFromDate(tmpDate);
if (islamic_date_tmp.month != 2)
{
is_holiday = true;
}
}
}
if (islamic_date.month == 3)
{
if (islamic_date.day == 8 || islamic_date.day == 17) is_holiday = true;
}
if (islamic_date.month == 6)
{
if (islamic_date.day == 3 ) is_holiday = true;
}
if (islamic_date.month == 7)
{
if (islamic_date.day == 13 || islamic_date.day == 27) is_holiday = true;
}
if (islamic_date.month == 8)
{
if (islamic_date.day == 15) is_holiday = true;
}
if (islamic_date.month == 9)
{
if (islamic_date.day == 19 || islamic_date.day == 21) is_holiday = true;
}
if (islamic_date.month == 10)
{
if (islamic_date.day == 1 || islamic_date.day == 2 || islamic_date.day == 25) is_holiday = true;
}
if (islamic_date.month == 12)
{
if (islamic_date.day == 10 || islamic_date.day == 18) is_holiday = true;
}
HiCalendarDayModel* newDay = new HiCalendarDayModel(newDate, day_counter, day_of_week, day_is_in_week_N_of_month,is_holiday ,this);
this->addDayItem(newDay);
if(newDate == _SelectedDate)
{
_current_selected_day = newDay;
}
newDate = newDate.addDays(1);
day_counter++;
}
_current_month_header_info = jalali_months[month-1] +" "+ QString::number(year) + "\n";
if(second_georgian_year == 0) //same georgian year
{
_current_month_header_info += georgian_months[first_georgian_month-1] + " - " + georgian_months[second_georgian_month-1] + " " + QString::number(first_georgian_year)+"\n";
}
else // different georgian years
{
_current_month_header_info += georgian_months[first_georgian_month-1] + " " + QString::number(first_georgian_year);
_current_month_header_info += " - " + georgian_months[second_georgian_month-1] + " " + QString::number(second_georgian_year)+"\n";
}
if(second_islamic_year == 0) //same islamic year
{
_current_month_header_info += islamic_months[first_islamic_month-1] + " - " + islamic_months[second_islamic_month-1] + " " + QString::number(first_islamic_year);
}
else // different islamic years
{
_current_month_header_info += islamic_months[first_islamic_month-1] + " " + QString::number(first_islamic_year);
_current_month_header_info += " - " + islamic_months[second_islamic_month-1] + " " + QString::number(second_islamic_year);
}
}
else
{
year = _SelectedDate.year();
month = _SelectedDate.month();
day = _SelectedDate.day();
QDate newDate(year,month,1);
int days_of_week_count[8] = {0,0,0,0,0,0,0,0};
while (newDate.month() == month)
{
bool is_holiday = false;
if(getCalendarType() == HiCalendarController::CalendarTypes::EuroGeorgian)
{
day_of_week = newDate.dayOfWeek();
}
else if (getCalendarType() == HiCalendarController::CalendarTypes::UsGeorgian)
{
day_of_week = (newDate.dayOfWeek() % 7) + 1;
}
if(day_of_week == 1 || day_is_in_week_N_of_month == 0)
{
day_is_in_week_N_of_month++;
}
//georgian holidays
days_of_week_count[newDate.dayOfWeek()]++;
if (newDate.dayOfWeek() == 7) is_holiday = true;
if (newDate.month() == 1)
{
if (newDate.day() == 1) is_holiday = true;
if (newDate.dayOfWeek() == 1 && days_of_week_count[newDate.dayOfWeek()] == 3) is_holiday = true;
}
if (newDate.month() == 2)
{
if (newDate.day() == 12) is_holiday = true;
if (newDate.dayOfWeek() == 1 && days_of_week_count[newDate.dayOfWeek()] == 3) is_holiday = true;
}
if (newDate.month() == 5)
{
if (newDate.day() == 5) is_holiday = true;
if (newDate.dayOfWeek() == 1 && (31 - newDate.day() <7)) is_holiday = true;
}
if (newDate.month() == 7)
{
if (newDate.day() == 4) is_holiday = true;
}
if (newDate.month() == 9)
{
if (newDate.day() == 4) is_holiday = true;
if (newDate.dayOfWeek() == 1 && days_of_week_count[newDate.dayOfWeek()] == 1) is_holiday = true;
}
if (newDate.month() == 11)
{
if (newDate.day() == 11) is_holiday = true;
if (newDate.dayOfWeek() == 3 && (30 - newDate.day() <7)) is_holiday = true;
}
if (newDate.month() == 12)
{
if (newDate.day() == 25) is_holiday = true;
}
HiCalendarDayModel* newDay = new HiCalendarDayModel(newDate, newDate.day(), day_of_week, day_is_in_week_N_of_month ,is_holiday,this);
this->addDayItem(newDay);
if(newDate == _SelectedDate)
{
_current_selected_day = newDay;
}
newDate = newDate.addDays(1);
}
_current_month_header_info = georgian_months[month-1] +" - "+ QString::number(year);
}
if (_current_selected_day != nullptr)
{
emit daySelectedSi(_current_selected_day);
}
emit refreshCalendarSi();
}
void HiCalendarController::nextDay()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
this->showCurrentSelectedYearMonthDay(_current_selected_day->getGeorgianDate().addDays(1));
}
}
void HiCalendarController::prevDay()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
this->showCurrentSelectedYearMonthDay(_current_selected_day->getGeorgianDate().addDays(-1));
}
}
void HiCalendarController::nextMonth()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
if (getCalendarType() == HiCalendarController::CalendarTypes::Jalali)
{
QCalendar jalali_calendar(QCalendar::System::Jalali);
QDate newDate = _current_selected_day->getGeorgianDate();
QCalendar::YearMonthDay jalali_date = jalali_calendar.partsFromDate(newDate);
int year = jalali_date.year;
int month = jalali_date.month + 1;
if (month > 12)
{
month = 1;
year++;
}
newDate = jalali_calendar.dateFromParts(year,month,1);
this->showCurrentSelectedYearMonthDay(newDate);
}
else
{
QDate newDate = _current_selected_day->getGeorgianDate().addMonths(1);
newDate.setDate(newDate.year(),newDate.month(),1);
this->showCurrentSelectedYearMonthDay(newDate);
}
}
}
void HiCalendarController::prevMonth()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
if (getCalendarType() == HiCalendarController::CalendarTypes::Jalali)
{
QCalendar jalali_calendar(QCalendar::System::Jalali);
QDate newDate = _current_selected_day->getGeorgianDate();
QCalendar::YearMonthDay jalali_date = jalali_calendar.partsFromDate(newDate);
int year = jalali_date.year;
int month = jalali_date.month - 1;
if (month < 1)
{
month = 12;
year--;
}
newDate = jalali_calendar.dateFromParts(year,month,1);
this->showCurrentSelectedYearMonthDay(newDate);
}
else
{
QDate newDate = _current_selected_day->getGeorgianDate().addMonths(-1);
newDate.setDate(newDate.year(),newDate.month(),1);
this->showCurrentSelectedYearMonthDay(newDate);
}
}
}
void HiCalendarController::nextYear()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
if (getCalendarType() == HiCalendarController::CalendarTypes::Jalali)
{
QCalendar jalali_calendar(QCalendar::System::Jalali);
QDate newDate = _current_selected_day->getGeorgianDate();
QCalendar::YearMonthDay jalali_date = jalali_calendar.partsFromDate(newDate);
int year = jalali_date.year + 1;
int month = jalali_date.month;
newDate = jalali_calendar.dateFromParts(year,month,1);
this->showCurrentSelectedYearMonthDay(newDate);
}
else
{
QDate newDate = _current_selected_day->getGeorgianDate().addYears(1);
newDate.setDate(newDate.year(),newDate.month(),1);
this->showCurrentSelectedYearMonthDay(newDate);
}
}
}
void HiCalendarController::prevYear()
{
if (_current_selected_day != nullptr && _days_of_current_month_list.length() >0)
{
if (getCalendarType() == HiCalendarController::CalendarTypes::Jalali)
{
QCalendar jalali_calendar(QCalendar::System::Jalali);
QDate newDate = _current_selected_day->getGeorgianDate();
QCalendar::YearMonthDay jalali_date = jalali_calendar.partsFromDate(newDate);
int year = jalali_date.year - 1;
int month = jalali_date.month;
newDate = jalali_calendar.dateFromParts(year,month,1);
this->showCurrentSelectedYearMonthDay(newDate);
}
else
{
QDate newDate = _current_selected_day->getGeorgianDate().addYears(-1);
newDate.setDate(newDate.year(),newDate.month(),1);
this->showCurrentSelectedYearMonthDay(newDate);
}
}
}
void HiCalendarController::addDayItem(HiCalendarDayModel *_Day)
{
if (!_days_of_current_month_list.contains(QVariant::fromValue(_Day)))
{
_days_of_current_month_list.append(QVariant::fromValue(_Day));
}
}
void HiCalendarController::selectDayByClick(HiCalendarDayModel *_Day)
{
QDate selected_date = _Day->getGeorgianDate();
if (_days_of_current_month_list.length() >0)
{
this->showCurrentSelectedYearMonthDay(selected_date);
for (QVariantList::iterator j = _days_of_current_month_list.begin(); j != _days_of_current_month_list.end(); j++)
{
QObject* object = qvariant_cast<QObject*>(*j);
HiCalendarDayModel* day = qobject_cast<HiCalendarDayModel*>(object);
if (day->getGeorgianDate() == selected_date)
{
_current_selected_day = day;
emit daySelectedSi(_current_selected_day);
break;
}
}
}
}
void HiCalendarController::clearCurrentDays()
{
for (QVariantList::iterator j = _days_of_current_month_list.begin(); j != _days_of_current_month_list.end(); j++)
{
QObject* object = qvariant_cast<QObject*>(*j);
HiCalendarDayModel* day = qobject_cast<HiCalendarDayModel*>(object);
day->deleteLater();
}
_days_of_current_month_list.clear();
emit refreshCalendarSi();
}
HiCalendarController &HiCalendarController::operator=(const HiCalendarController &other)
{
this->_days_of_current_month_list = other.getDaysOfCurrentMonth();
this->_calendar_type = other.getCalendarType();
this->_current_selected_day = other.getCurrentSelectedDay();
this->_current_month_header_info = other.currentMonthHeaderInfo();
return *this;
}
bool HiCalendarController::operator!=(const HiCalendarController &other) const
{
return (this->_days_of_current_month_list != other.getDaysOfCurrentMonth()
|| this->_calendar_type != other.getCalendarType()
|| this->_current_selected_day != other.getCurrentSelectedDay()
|| this->_current_month_header_info != other.currentMonthHeaderInfo());
}
bool HiCalendarController::operator==(const HiCalendarController &other) const
{
return !(*this != other);
}
HiCalendarController::~HiCalendarController()
{
this->clearCurrentDays();
}
//////////:::::::::::::::::::::::::::::::::::::::::::::: Hi Calendar Context
HiCalendarContext::HiCalendarContext(QObject *parent) : QObject(parent),_calendar (nullptr) {}
void HiCalendarContext::renewCalendar(QString calendar_type)
{
calendar_type = calendar_type.toLower();
if (calendar_type == "us" || calendar_type == "us_calendar" || calendar_type == "us_georgian_calendar")
{
this->renewCalendar(HiCalendarController::CalendarTypes::UsGeorgian);
}
else if(calendar_type == "euro" || calendar_type == "euro_calendar" || calendar_type == "euro_georgian_calendar")
{
this->renewCalendar(HiCalendarController::CalendarTypes::EuroGeorgian);
}
else if (calendar_type == "jalali" || calendar_type == "jalali_calendar")
{
this->renewCalendar(HiCalendarController::CalendarTypes::Jalali);
}
}
void HiCalendarContext::renewCalendar(HiCalendarController::CalendarTypes calendar_type)
{
bool changed = false;
if (calendar_type == HiCalendarController::CalendarTypes::UsGeorgian)
{
changed = true;
if (_calendar != nullptr) _calendar->deleteLater();
_calendar = new HiCalendarController(HiCalendarController::CalendarTypes::UsGeorgian , this);
}
else if(calendar_type == HiCalendarController::CalendarTypes::EuroGeorgian)
{
changed = true;
if (_calendar != nullptr) _calendar->deleteLater();
_calendar = new HiCalendarController(HiCalendarController::CalendarTypes::EuroGeorgian, this);
}
else if (calendar_type == HiCalendarController::CalendarTypes::Jalali)
{
changed = true;
if (_calendar != nullptr) _calendar->deleteLater();
_calendar = new HiCalendarController(HiCalendarController::CalendarTypes::Jalali, this);
}
if (changed == true && _calendar != nullptr)
{
_calendar->showCurrentSelectedYearMonthDay();
emit calendarChangedSi();
}
}
HiCalendarController* HiCalendarContext::getCalendar()
{
return _calendar;
}
HiCalendarContext::~HiCalendarContext()
{
if (_calendar != nullptr)
{
_calendar->deleteLater();
}
}
| 37.741588
| 954
| 0.61308
|
SC-One
|
9927a78165656864eb420193b3dc3673c4a5bd6a
| 1,686
|
cpp
|
C++
|
source/raytracer/implementation/geometry/object/triangle.cpp
|
danielil/RayTracer
|
16682be15d31e9201acd66b4a12ae78c69fbc671
|
[
"MIT"
] | null | null | null |
source/raytracer/implementation/geometry/object/triangle.cpp
|
danielil/RayTracer
|
16682be15d31e9201acd66b4a12ae78c69fbc671
|
[
"MIT"
] | null | null | null |
source/raytracer/implementation/geometry/object/triangle.cpp
|
danielil/RayTracer
|
16682be15d31e9201acd66b4a12ae78c69fbc671
|
[
"MIT"
] | null | null | null |
/**
* The MIT License (MIT)
* Copyright (c) 2017-2017 Daniel Sebastian Iliescu, http://dansil.net
*
* 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 "raytracer/geometry/object/triangle.hpp"
namespace raytracer::geometry::object
{
std::optional< point > triangle::intersect( const ray& ray ) const
{
// TODO
return {};
}
spatial_vector triangle::normal( const point& intersection_point ) const
{
// TODO
auto normal = intersection_point - center;
normalize( std::begin( normal ), std::end( normal ) );
return normal;
}
const image::channels& triangle::get_channels() const
{
// TODO
return this->channels;
}
}
| 32.423077
| 81
| 0.734282
|
danielil
|
992d5d130d63c83e1a52fe236d3ece50664a82e1
| 2,009
|
hpp
|
C++
|
include/scigl_render/scene/cv_camera.hpp
|
Tuebel/scigl_render
|
ec790d54ca4a14546348a5dd2f799d5abcc4bd36
|
[
"MIT"
] | null | null | null |
include/scigl_render/scene/cv_camera.hpp
|
Tuebel/scigl_render
|
ec790d54ca4a14546348a5dd2f799d5abcc4bd36
|
[
"MIT"
] | null | null | null |
include/scigl_render/scene/cv_camera.hpp
|
Tuebel/scigl_render
|
ec790d54ca4a14546348a5dd2f799d5abcc4bd36
|
[
"MIT"
] | null | null | null |
#pragma once
#include <gl3w/GL/gl3w.h>
#include <scigl_render/shader/shader.hpp>
#include <scigl_render/scene/camera_intrinsics.hpp>
#include <scigl_render/scene/pose.hpp>
#include <vector>
namespace scigl_render
{
/*!
A camera has a position in the world (extrinsics) and projection (intrinsic).
The extrinsics and intrinsics are calculated using the OpenCV camera model:
- x-axis points right
- y-axis points down
- z-axis points into the image plane
So use the OpenCV / ROS frame convention to set the extrinsic pose.
*/
class CvCamera
{
public:
/*!
Current pose of the camera in cartesian coordinates according the ROS camera
frame convention (see Header defintion:
http://docs.ros.org/melodic/api/sensor_msgs/html/msg/CameraInfo.html)
*/
QuaternionPose pose;
/*!
Default constructor. Don't forget to set the intrinsics!
*/
CvCamera();
/*!
Constructor with intrinsics
*/
CvCamera(CameraIntrinsics intrinsics);
/*!
The view matrix results by moving the entire scene in the opposite direction
of the camera transformation (passive transformation of the camera). Converts
the OpenCV/ROS extrinsic pose to the OpenGL pose (negate y & z axes).
*/
glm::mat4 get_view_matrix() const;
/*!
The projection matrix based on the intrinsics configured on construction.
*/
glm::mat4 get_projection_matrix() const;
/*!
Sets the view and projection matrix in the shader, given the current values.
The variable names must be: "projection_matrix" and "view_matrix"
*/
void set_in_shader(const Shader &shader) const;
CameraIntrinsics get_intrinsics() const;
void set_intrinsics(CameraIntrinsics intrinsics);
private:
glm::mat4 projection_matrix;
CameraIntrinsics intrinsics;
/*!
Get the projection matrix for the given camera intrinsics.
\return a projection matrix calculated that transforms from view to clipping
space
*/
static glm::mat4 calc_projection_matrix(const CameraIntrinsics &intrinsics);
};
} // namespace scigl_render
| 28.7
| 79
| 0.752613
|
Tuebel
|
99322fd9da6141454cccef5308d5e23cc4ae3042
| 1,792
|
cpp
|
C++
|
test/query_builder_tests.cpp
|
Malibushko/yatgbotlib
|
a5109c36c9387aef0e6d15e303d2f3753eef9aac
|
[
"MIT"
] | 3
|
2020-04-05T23:51:09.000Z
|
2020-08-14T07:24:45.000Z
|
test/query_builder_tests.cpp
|
Malibushko/yatgbotlib
|
a5109c36c9387aef0e6d15e303d2f3753eef9aac
|
[
"MIT"
] | 1
|
2020-07-24T19:46:28.000Z
|
2020-07-31T14:49:28.000Z
|
test/query_builder_tests.cpp
|
Malibushko/yatgbotlib
|
a5109c36c9387aef0e6d15e303d2f3753eef9aac
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include "telegram_bot.h"
using namespace telegram;
TEST(QueryBuilder,builder_builtin) {
QueryBuilder builder;
int b = 5;
int c = 6;
bool d = false;
builder << make_named_pair(b) << make_named_pair(c) << make_named_pair(d);
std::string json = builder.getQuery();
std::string expected = "{\"b\":5,\"c\":6,\"d\":false}";
EXPECT_EQ(expected,json);
}
TEST(QueryBuilder,builder_variant) {
QueryBuilder builder;
using variant_type = std::variant<std::string,int,bool>;
variant_type var1 = false;
variant_type var2 = std::string("test");
variant_type var3 = 19;
builder << make_named_pair(var1) << make_named_pair(var2) << make_named_pair(var3);
std::string json = builder.getQuery();
std::string expected = "{\"var1\":false,\"var2\":\"test\",\"var3\":19}";
EXPECT_EQ(expected,json);
}
TEST(QueryBuilder,builder_array) {
QueryBuilder builder;
std::vector<int> vec{1,2,3,4};
builder << make_named_pair(vec);
std::string json = builder.getQuery();
std::string expected = "{\"vec\":[1,2,3,4]}";
EXPECT_EQ(expected,json);
}
struct MetaStruct {
declare_struct
declare_field(int,i);
};
TEST(QueryBuilder,builder_array_complex) {
QueryBuilder builder;
std::vector<MetaStruct> vec{{1},{2},{3}};
builder << make_named_pair(vec);
std::string json = builder.getQuery();
std::string expected = "{\"vec\":[{\"i\":1},{\"i\":2},{\"i\":3}]}";
EXPECT_EQ(expected,json);
}
TEST(QueryBuilder,builder_empty_document) {
QueryBuilder builder;
std::string json = builder.getQuery();
std::string expected = "null";
EXPECT_EQ(expected,json);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 28.903226
| 87
| 0.650112
|
Malibushko
|
9933976a01123be433ebac6aa2221ede3a33c9bd
| 25,960
|
cc
|
C++
|
dist/cpp/proto/services/request/topicSubscription.pb.cc
|
ate362/ubii-msg-formats
|
f96058dc1091886c47761fbba1a3033bcf180b4c
|
[
"BSD-3-Clause"
] | 2
|
2021-01-29T12:49:01.000Z
|
2021-03-06T13:35:49.000Z
|
dist/cpp/proto/services/request/topicSubscription.pb.cc
|
ate362/ubii-msg-formats
|
f96058dc1091886c47761fbba1a3033bcf180b4c
|
[
"BSD-3-Clause"
] | null | null | null |
dist/cpp/proto/services/request/topicSubscription.pb.cc
|
ate362/ubii-msg-formats
|
f96058dc1091886c47761fbba1a3033bcf180b4c
|
[
"BSD-3-Clause"
] | 2
|
2021-05-14T14:06:33.000Z
|
2022-02-21T21:25:35.000Z
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto/services/request/topicSubscription.proto
#include "proto/services/request/topicSubscription.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace ubii {
namespace services {
namespace request {
class TopicSubscriptionDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<TopicSubscription>
_instance;
} _TopicSubscription_default_instance_;
} // namespace request
} // namespace services
} // namespace ubii
namespace protobuf_proto_2fservices_2frequest_2ftopicSubscription_2eproto {
static void InitDefaultsTopicSubscription() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::ubii::services::request::_TopicSubscription_default_instance_;
new (ptr) ::ubii::services::request::TopicSubscription();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::ubii::services::request::TopicSubscription::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_TopicSubscription =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTopicSubscription}, {}};
void InitDefaults() {
::google::protobuf::internal::InitSCC(&scc_info_TopicSubscription.base);
}
::google::protobuf::Metadata file_level_metadata[1];
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::ubii::services::request::TopicSubscription, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::ubii::services::request::TopicSubscription, client_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::ubii::services::request::TopicSubscription, subscribe_topics_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::ubii::services::request::TopicSubscription, unsubscribe_topics_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::ubii::services::request::TopicSubscription, subscribe_topic_regexp_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::ubii::services::request::TopicSubscription, unsubscribe_topic_regexp_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::ubii::services::request::TopicSubscription)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::ubii::services::request::_TopicSubscription_default_instance_),
};
void protobuf_AssignDescriptors() {
AddDescriptors();
AssignDescriptors(
"proto/services/request/topicSubscription.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n.proto/services/request/topicSubscripti"
"on.proto\022\025ubii.services.request\"\236\001\n\021Topi"
"cSubscription\022\021\n\tclient_id\030\001 \001(\t\022\030\n\020subs"
"cribe_topics\030\002 \003(\t\022\032\n\022unsubscribe_topics"
"\030\003 \003(\t\022\036\n\026subscribe_topic_regexp\030\004 \003(\t\022 "
"\n\030unsubscribe_topic_regexp\030\005 \003(\tb\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 240);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"proto/services/request/topicSubscription.proto", &protobuf_RegisterTypes);
}
void AddDescriptors() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_proto_2fservices_2frequest_2ftopicSubscription_2eproto
namespace ubii {
namespace services {
namespace request {
// ===================================================================
void TopicSubscription::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TopicSubscription::kClientIdFieldNumber;
const int TopicSubscription::kSubscribeTopicsFieldNumber;
const int TopicSubscription::kUnsubscribeTopicsFieldNumber;
const int TopicSubscription::kSubscribeTopicRegexpFieldNumber;
const int TopicSubscription::kUnsubscribeTopicRegexpFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TopicSubscription::TopicSubscription()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_proto_2fservices_2frequest_2ftopicSubscription_2eproto::scc_info_TopicSubscription.base);
SharedCtor();
// @@protoc_insertion_point(constructor:ubii.services.request.TopicSubscription)
}
TopicSubscription::TopicSubscription(const TopicSubscription& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
subscribe_topics_(from.subscribe_topics_),
unsubscribe_topics_(from.unsubscribe_topics_),
subscribe_topic_regexp_(from.subscribe_topic_regexp_),
unsubscribe_topic_regexp_(from.unsubscribe_topic_regexp_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
client_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.client_id().size() > 0) {
client_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.client_id_);
}
// @@protoc_insertion_point(copy_constructor:ubii.services.request.TopicSubscription)
}
void TopicSubscription::SharedCtor() {
client_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
TopicSubscription::~TopicSubscription() {
// @@protoc_insertion_point(destructor:ubii.services.request.TopicSubscription)
SharedDtor();
}
void TopicSubscription::SharedDtor() {
client_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void TopicSubscription::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* TopicSubscription::descriptor() {
::protobuf_proto_2fservices_2frequest_2ftopicSubscription_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_proto_2fservices_2frequest_2ftopicSubscription_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const TopicSubscription& TopicSubscription::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_proto_2fservices_2frequest_2ftopicSubscription_2eproto::scc_info_TopicSubscription.base);
return *internal_default_instance();
}
void TopicSubscription::Clear() {
// @@protoc_insertion_point(message_clear_start:ubii.services.request.TopicSubscription)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
subscribe_topics_.Clear();
unsubscribe_topics_.Clear();
subscribe_topic_regexp_.Clear();
unsubscribe_topic_regexp_.Clear();
client_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
bool TopicSubscription::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:ubii.services.request.TopicSubscription)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string client_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_client_id()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->client_id().data(), static_cast<int>(this->client_id().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"ubii.services.request.TopicSubscription.client_id"));
} else {
goto handle_unusual;
}
break;
}
// repeated string subscribe_topics = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_subscribe_topics()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->subscribe_topics(this->subscribe_topics_size() - 1).data(),
static_cast<int>(this->subscribe_topics(this->subscribe_topics_size() - 1).length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"ubii.services.request.TopicSubscription.subscribe_topics"));
} else {
goto handle_unusual;
}
break;
}
// repeated string unsubscribe_topics = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_unsubscribe_topics()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->unsubscribe_topics(this->unsubscribe_topics_size() - 1).data(),
static_cast<int>(this->unsubscribe_topics(this->unsubscribe_topics_size() - 1).length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"ubii.services.request.TopicSubscription.unsubscribe_topics"));
} else {
goto handle_unusual;
}
break;
}
// repeated string subscribe_topic_regexp = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_subscribe_topic_regexp()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->subscribe_topic_regexp(this->subscribe_topic_regexp_size() - 1).data(),
static_cast<int>(this->subscribe_topic_regexp(this->subscribe_topic_regexp_size() - 1).length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"ubii.services.request.TopicSubscription.subscribe_topic_regexp"));
} else {
goto handle_unusual;
}
break;
}
// repeated string unsubscribe_topic_regexp = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_unsubscribe_topic_regexp()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->unsubscribe_topic_regexp(this->unsubscribe_topic_regexp_size() - 1).data(),
static_cast<int>(this->unsubscribe_topic_regexp(this->unsubscribe_topic_regexp_size() - 1).length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"ubii.services.request.TopicSubscription.unsubscribe_topic_regexp"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:ubii.services.request.TopicSubscription)
return true;
failure:
// @@protoc_insertion_point(parse_failure:ubii.services.request.TopicSubscription)
return false;
#undef DO_
}
void TopicSubscription::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:ubii.services.request.TopicSubscription)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string client_id = 1;
if (this->client_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->client_id().data(), static_cast<int>(this->client_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"ubii.services.request.TopicSubscription.client_id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->client_id(), output);
}
// repeated string subscribe_topics = 2;
for (int i = 0, n = this->subscribe_topics_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->subscribe_topics(i).data(), static_cast<int>(this->subscribe_topics(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"ubii.services.request.TopicSubscription.subscribe_topics");
::google::protobuf::internal::WireFormatLite::WriteString(
2, this->subscribe_topics(i), output);
}
// repeated string unsubscribe_topics = 3;
for (int i = 0, n = this->unsubscribe_topics_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->unsubscribe_topics(i).data(), static_cast<int>(this->unsubscribe_topics(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"ubii.services.request.TopicSubscription.unsubscribe_topics");
::google::protobuf::internal::WireFormatLite::WriteString(
3, this->unsubscribe_topics(i), output);
}
// repeated string subscribe_topic_regexp = 4;
for (int i = 0, n = this->subscribe_topic_regexp_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->subscribe_topic_regexp(i).data(), static_cast<int>(this->subscribe_topic_regexp(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"ubii.services.request.TopicSubscription.subscribe_topic_regexp");
::google::protobuf::internal::WireFormatLite::WriteString(
4, this->subscribe_topic_regexp(i), output);
}
// repeated string unsubscribe_topic_regexp = 5;
for (int i = 0, n = this->unsubscribe_topic_regexp_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->unsubscribe_topic_regexp(i).data(), static_cast<int>(this->unsubscribe_topic_regexp(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"ubii.services.request.TopicSubscription.unsubscribe_topic_regexp");
::google::protobuf::internal::WireFormatLite::WriteString(
5, this->unsubscribe_topic_regexp(i), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:ubii.services.request.TopicSubscription)
}
::google::protobuf::uint8* TopicSubscription::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:ubii.services.request.TopicSubscription)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string client_id = 1;
if (this->client_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->client_id().data(), static_cast<int>(this->client_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"ubii.services.request.TopicSubscription.client_id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->client_id(), target);
}
// repeated string subscribe_topics = 2;
for (int i = 0, n = this->subscribe_topics_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->subscribe_topics(i).data(), static_cast<int>(this->subscribe_topics(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"ubii.services.request.TopicSubscription.subscribe_topics");
target = ::google::protobuf::internal::WireFormatLite::
WriteStringToArray(2, this->subscribe_topics(i), target);
}
// repeated string unsubscribe_topics = 3;
for (int i = 0, n = this->unsubscribe_topics_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->unsubscribe_topics(i).data(), static_cast<int>(this->unsubscribe_topics(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"ubii.services.request.TopicSubscription.unsubscribe_topics");
target = ::google::protobuf::internal::WireFormatLite::
WriteStringToArray(3, this->unsubscribe_topics(i), target);
}
// repeated string subscribe_topic_regexp = 4;
for (int i = 0, n = this->subscribe_topic_regexp_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->subscribe_topic_regexp(i).data(), static_cast<int>(this->subscribe_topic_regexp(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"ubii.services.request.TopicSubscription.subscribe_topic_regexp");
target = ::google::protobuf::internal::WireFormatLite::
WriteStringToArray(4, this->subscribe_topic_regexp(i), target);
}
// repeated string unsubscribe_topic_regexp = 5;
for (int i = 0, n = this->unsubscribe_topic_regexp_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->unsubscribe_topic_regexp(i).data(), static_cast<int>(this->unsubscribe_topic_regexp(i).length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"ubii.services.request.TopicSubscription.unsubscribe_topic_regexp");
target = ::google::protobuf::internal::WireFormatLite::
WriteStringToArray(5, this->unsubscribe_topic_regexp(i), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:ubii.services.request.TopicSubscription)
return target;
}
size_t TopicSubscription::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:ubii.services.request.TopicSubscription)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// repeated string subscribe_topics = 2;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->subscribe_topics_size());
for (int i = 0, n = this->subscribe_topics_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->subscribe_topics(i));
}
// repeated string unsubscribe_topics = 3;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->unsubscribe_topics_size());
for (int i = 0, n = this->unsubscribe_topics_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->unsubscribe_topics(i));
}
// repeated string subscribe_topic_regexp = 4;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->subscribe_topic_regexp_size());
for (int i = 0, n = this->subscribe_topic_regexp_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->subscribe_topic_regexp(i));
}
// repeated string unsubscribe_topic_regexp = 5;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->unsubscribe_topic_regexp_size());
for (int i = 0, n = this->unsubscribe_topic_regexp_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->unsubscribe_topic_regexp(i));
}
// string client_id = 1;
if (this->client_id().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->client_id());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TopicSubscription::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:ubii.services.request.TopicSubscription)
GOOGLE_DCHECK_NE(&from, this);
const TopicSubscription* source =
::google::protobuf::internal::DynamicCastToGenerated<const TopicSubscription>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:ubii.services.request.TopicSubscription)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:ubii.services.request.TopicSubscription)
MergeFrom(*source);
}
}
void TopicSubscription::MergeFrom(const TopicSubscription& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:ubii.services.request.TopicSubscription)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
subscribe_topics_.MergeFrom(from.subscribe_topics_);
unsubscribe_topics_.MergeFrom(from.unsubscribe_topics_);
subscribe_topic_regexp_.MergeFrom(from.subscribe_topic_regexp_);
unsubscribe_topic_regexp_.MergeFrom(from.unsubscribe_topic_regexp_);
if (from.client_id().size() > 0) {
client_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.client_id_);
}
}
void TopicSubscription::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:ubii.services.request.TopicSubscription)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TopicSubscription::CopyFrom(const TopicSubscription& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:ubii.services.request.TopicSubscription)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TopicSubscription::IsInitialized() const {
return true;
}
void TopicSubscription::Swap(TopicSubscription* other) {
if (other == this) return;
InternalSwap(other);
}
void TopicSubscription::InternalSwap(TopicSubscription* other) {
using std::swap;
subscribe_topics_.InternalSwap(CastToBase(&other->subscribe_topics_));
unsubscribe_topics_.InternalSwap(CastToBase(&other->unsubscribe_topics_));
subscribe_topic_regexp_.InternalSwap(CastToBase(&other->subscribe_topic_regexp_));
unsubscribe_topic_regexp_.InternalSwap(CastToBase(&other->unsubscribe_topic_regexp_));
client_id_.Swap(&other->client_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata TopicSubscription::GetMetadata() const {
protobuf_proto_2fservices_2frequest_2ftopicSubscription_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_proto_2fservices_2frequest_2ftopicSubscription_2eproto::file_level_metadata[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace request
} // namespace services
} // namespace ubii
namespace google {
namespace protobuf {
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::ubii::services::request::TopicSubscription* Arena::CreateMaybeMessage< ::ubii::services::request::TopicSubscription >(Arena* arena) {
return Arena::CreateInternal< ::ubii::services::request::TopicSubscription >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
| 44.913495
| 181
| 0.729507
|
ate362
|
9934e3629c522f13fd76e73643c00baf3df398be
| 29,949
|
cpp
|
C++
|
cpp/apps/AeroCombat/temp/AeroSurf.cpp
|
ProkopHapala/SimpleSimulationEngine
|
240f9b7e85b3a6eda7a27dc15fe3f7b8c08774c5
|
[
"MIT"
] | 26
|
2016-12-04T04:45:12.000Z
|
2022-03-24T09:39:28.000Z
|
cpp/apps/AeroCombat/temp/AeroSurf.cpp
|
ProkopHapala/SimpleSimulationEngine
|
240f9b7e85b3a6eda7a27dc15fe3f7b8c08774c5
|
[
"MIT"
] | null | null | null |
cpp/apps/AeroCombat/temp/AeroSurf.cpp
|
ProkopHapala/SimpleSimulationEngine
|
240f9b7e85b3a6eda7a27dc15fe3f7b8c08774c5
|
[
"MIT"
] | 2
|
2019-02-09T12:31:06.000Z
|
2019-04-28T02:24:50.000Z
|
//#include "rString.hpp"
#include <math.h>
#include "AeroSurf.hpp"
#if _DEBUG_AEROSURF
void drawWing(Vector3 pos, Matrix3 rot, float a, float AspectRatio )
{
Matrix4 pose;
pose.SetPosition(Vector3D(pos.X(), pos.Y(), pos.Z()));
pose.SetOrientation(rot);
renderer.DrawBox(Vector3D(0, 0, 0), Vector3(AspectRatio*a*0.5, 0.025, a*0.5), PackedWhite, &pose);
}
void drawRigidBody(Vector3 pos, Matrix3 rot, float sz)
{
renderer.Add3dLine(pos, pos + rot.Direction() * sz, PackedBlue );
renderer.Add3dLine(pos, pos + rot.DirectionUp() * sz, PackedGreen );
renderer.Add3dLine(pos, pos + rot.DirectionAside() * sz, PackedRed );
Matrix4 pose;
pose.SetPosition(Vector3D(pos.X(), pos.Y(), pos.Z()));
pose.SetOrientation(rot);
renderer.DrawBox(Vector3D(0, 0, 0), Vector3(0.5, 0.25, 1.0), PackedWhite, &pose);
};
#endif // _DEBUG_AEROSURF
//==============
// PolarModel
//==============
inline void PolarModel::GetAeroCoefs(float ca, float sa, float& CD, float& CL) const {
float abs_sa = (sa>0) ? sa : -sa; // symmetric wing
float wS = cubicSmoothStep<float>(abs_sa, _sStall, _sStall + _wStall); // stalled mixing factor
float mS = 1 - wS; // not-stalled mixing factor
CD = _CD0 + ( mS * _dCD * abs_sa + wS * _dCDS) * abs_sa; // drag
if (ca <0) { // for Angle of Attack > 90 deg ( air comes from behind )
ca = -ca;
sa = -sa;
};
CL = ( mS* _dCL + wS * _dCLS*ca) * sa; // lift
}
//=====================
// PolarModelTorque
//=====================
inline void PolarModelTorque::GetAeroCoefs(float ca, float sa, float flap, float& CD, float& CL, float& CM) const
{
float abs_sa = (sa>0) ? sa : -sa; // symmetric wing
float wS = cubicSmoothStep<float>(abs_sa, _sStall, _sStall + _wStall); // stalled mixing factor
float mS = 1 - wS; // not-stalled mixing factor
CD = _CD0 + (mS*_dCD*abs_sa + wS * _dCDS) * abs_sa; // drag
if (ca <0) { // for Angle of Attack > 90 deg ( air comes from behind )
ca = -ca;
sa = -sa;
};
CL = (mS*_dCL + wS * _dCLS*ca) * sa; // lift
float sa_, ca_;
rot2D(flap, ca, sa, ca_, sa_);
abs_sa = (sa_>0) ? sa_ : -sa_;
//// We should use the same stall cutoff as main wing independent of flap (?)
//wS = cubicSmoothStep<float>(abs_sa, _sStall, _sStall + _wStall); // stalled mixing factor
//mS = 1 - wS; // not-stalled mixing factor
CM = (mS*_dCM + wS * _dCMS*ca_) * sa_; // TODO: FIXME pitching moment
}
// ======================================================
// AeroSurface
// ======================================================
float AeroSurface::Control2tilt(float control) const
{
// if _maxTilt <> -_minTilt this will produce piecewise linear function f(0)=0 with different slope for positive and negative value of control
if (control > 0) { return control * _maxTilt; }
else { return control * -_minTilt; }
}
float AeroSurface::Controls2tilt(float elevator, float rudder, float aileron) const
{
float control = _cElevator*elevator + _cRudder*rudder + _cAileron*aileron;
if (control > 0) { return control * _maxTilt; }
else { return control * -_minTilt; }
}
void AeroSurface::Tilt(float angle)
{
Matrix3 tiltMat = M3Identity;
tiltMat.SetRotationX(angle);
_lrot = _lrot * tiltMat;
};
void AeroSurface::ApplyForce(const Vector3& vair0, const Matrix3& craftRot, const Vector3& craftOmega, Vector3& force, Vector3& torq, float tilt, int i, bool debug, const Vector3& pos0 ) const
{
// global coordinates
Matrix3 grot; // rotation of panel in world coordinates
if (_bControlable) { // Apply controls
Matrix3 tiltMat = M3Identity;
tiltMat.SetRotationX(tilt);
grot = craftRot * _lrot * tiltMat;
}
else
{
grot = craftRot * _lrot;
}
Vector3 gdpos = craftRot * _lpos; // position of panel in world coordinates relative to COG
Vector3 uair = vair0 + gdpos.CrossProduct(craftOmega); // velocity of panel due to rotation of aircraft
//Vector3 uair = vair0; // ignore rotation of aircraft
float vrair2 = uair.SquareSize();
if (vrair2 > lowSpeedCuoff) // for zero air-speed it would diverge
{
// unitary vector in direction of air flow
float vrair = sqrt(vrair2);
uair *= (1 / vrair);
// decompose uair to panel coordinates
float ca = grot.DirectionAside().DotProduct(uair);
float cb = grot.DirectionUp().DotProduct(uair);
float cc = grot.Direction().DotProduct(uair);
// All aerodynamic forces are scalled by this factor
float prefactor = vrair2 * _area; // density not included
force = VZero;
#if _DEBUG_AEROSURF
Vector3 pos = pos0 + gdpos; // position of panel in world coordinates; just for ploting
if (debug)
renderer.Add3dLine(pos, pos + uair * 5.0, PackedBlue);
#endif // _DEBUG_AEROSURF
// get Lift and Drag coefs from polar (dimensionless)
float CD, CL;
_polar.GetAeroCoefs(-cc, cb, CD, CL);
if (_bFiniteWingCorrection)
{
// NOTE: This is used if we use polar of infinite wing (of 2D airfoil )
// but finite wing effect can be already included in polar, than _bFiniteWingCorrection should be set to false
// http://www.srmuniv.ac.in/sites/default/files/downloads/class4-2012.pdf
// https://en.wikipedia.org/wiki/Lifting-line_theory#Useful_approximations
CL *= _aspectRatio / ( 2 + _aspectRatio );
CD += CL * CL / (3.1415926535 * _aspectRatio); // induced drag // https://en.wikipedia.org/wiki/Lift-induced_drag
}
// Scale Lift and Drag (no density yet)
CL *= prefactor;
CD *= prefactor;
if ((cb*cb) > 1e-8) // for zero Angle of Attack we cannot determine lift direction
{
Vector3 airUp = grot.DirectionUp() + (uair * -cb); // component of grot.Up perpendicular to uair
airUp.Normalize();
force = airUp * CL + uair * CD; // combine Lift and Drag force
#if _DEBUG_AEROSURF
if (debug)
{
renderer.Add3dLine(pos, pos + airUp * 5.0, PackedGreen);
char plotName[128];
sprintf(plotName, "wing[%i]", i);
//TO_DBG_MGRAPH(plotName, Lift, CL, 200);
//TO_DBG_MGRAPH(plotName, Drag, CD, 200);
/*
if (debugPlot>0) {
int N = 200;
if (!liftPlot && GDebugGui) {
liftPlot = GDebugGui->AddMultiGraph(plotName, "Lift", N);
GEngine->ShowDiagGraph(liftPlot);
iLift = liftPlot->AddGraph("Lift");
}
if (!dragPlot && GDebugGui) {
dragPlot = GDebugGui->AddMultiGraph(plotName, "Drag", N);
GEngine->ShowDiagGraph(dragPlot);
iDrag = dragPlot->AddGraph("Drag");
}
if (debugPlot == 1) {
if (-1 != iLift && liftPlot) liftPlot->AddValue(iLift, CL);
if (-1 != iDrag && dragPlot) dragPlot->AddValue(iDrag, CD);
}
if (debugPlot == 2) {
liftPlot->Clear();
dragPlot->Clear();
float dAoA = 6.28 / N;
for (int i = 0; i < N; i++ ) {
float AoA = dAoA * i - 3.14;
float ca_ = cos(AoA);
float sa_ = sin(AoA);
polar->getAeroCoefs(ca_, sa_, CD, CL);
liftPlot->AddValue(iLift, CL);
dragPlot->AddValue(iDrag, CD);
}
float AoA = atan2( cb, -cc );
liftPlot->HighlightB = AoA/6.28 + 0.5;
DIAG_MESSAGE_ID(100, 30 + i, Format("AoA %f", AoA ) );
}
}
*/
// DECL_DBG_2DSLIDER(coords, 1, 2, -5, 5, -5, 5); // Creates two floats, coord_X and coord_Y, with their initial values set to [1, 2] and the slider has a range of <-5,5> x <-5,5>
//TO_DBG_MGRAPH(speed, z, FutureVisualState().RelativeSpeed().Z(), 200);
}
#endif // _DEBUG_AEROSURF
}
else
{
force += uair * CD; // for zero Angle of Attack only drag force
}
// apply anisotropic drag coef - Do we really need this here ?
force += grot.DirectionAside() * (_cAnisoDrag[0] * ca * prefactor);
force += grot.DirectionUp() * (_cAnisoDrag[1] * cb * prefactor);
force += grot.Direction() * (_cAnisoDrag[2] * cc * prefactor);
torq = gdpos.CrossProduct(force);
#if _DEBUG_AEROSURF
if (debug) {
renderer.Add3dLine(pos, pos + grot.DirectionUp() * 5.0, PackedBlack);
renderer.Add3dLine(pos, pos + grot.Direction() * 5.0, PackedWhite);
renderer.Add3dLine(pos, pos + force * 5.0, PackedRed);
}
#endif // _DEBUG_AEROSURF
}
};
void AeroSurface::FromString(const char * str)
{
float lrot_bx, lrot_by, lrot_bz,
lrot_cx, lrot_cy, lrot_cz;
sscanf(str, " %f %f %f %f %f %f %f %f %f %f %f %f %f %f",
&_lpos[0], &_lpos[1], &_lpos[2],
&lrot_bx, &lrot_by, &lrot_bz,
&lrot_cx, &lrot_cy, &lrot_cz,
&_cAnisoDrag[0], &_cAnisoDrag[1], &_cAnisoDrag[2],
&_area, &_aspectRatio
);
_lrot.SetDirectionAndUp(Vector3(lrot_cx, lrot_cy, lrot_cz), Vector3(lrot_bx, lrot_by, lrot_bz));
};
void AeroSurface::FromStringPolarModel(const char * str)
{
float lrot_bx, lrot_by, lrot_bz,
lrot_cx, lrot_cy, lrot_cz;
sscanf(str, " %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f",
&_lpos[0], &_lpos[1], &_lpos[2],
&lrot_bx, &lrot_by, &lrot_bz,
&lrot_cx, &lrot_cy, &lrot_cz,
&_cAnisoDrag[0], &_cAnisoDrag[1], &_cAnisoDrag[2],
&_area, &_aspectRatio,
&(_polar._CD0), &(_polar._dCD), &(_polar._dCDS), &(_polar._dCL), &(_polar._dCLS), &(_polar._sStall), &(_polar._wStall)
);
_lrot.SetDirectionAndUp( Vector3(lrot_cx, lrot_cy, lrot_cz), Vector3(lrot_bx, lrot_by, lrot_bz) );
};
int AeroSurface::ToStringPolarModel(char * str) const {
return sprintf(str, "%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %i \n",
_lpos[0], _lpos[1], _lpos[2],
_lrot.DirectionUp()[0], _lrot.DirectionUp()[1], _lrot.DirectionUp()[2],
_lrot.Direction()[0], _lrot.Direction()[1], _lrot.Direction()[2],
_cAnisoDrag[0], _cAnisoDrag[1], _cAnisoDrag[2],
_area,_aspectRatio,
_polar._CD0, _polar._dCD, _polar._dCDS, _polar._dCL, _polar._dCLS, _polar._sStall, _polar._wStall,
_minTilt, _maxTilt, _bFiniteWingCorrection
);
};
// =========================================
// Propeler
// =========================================
float Propeler::GetBaypassThrust(float v0, float throtle) const
{
// Thrust is limited by amount of air passing through propeler
// Derived from those equations
// dm = S * v0
// F = dm * Dv
// Engine power accelerates both the aircraft and the air
// P = F * v0 + 0.5*dm*(Dv**2) = S*(v0**2)*Dv + 0.5*S*v0*(Dv**2) // Quadratic equation
// v0 ... aircraft velocity
// vstatic ... we need non-zero flow through properler even when aircraft stand still on ground
float dm = _area * (v0 + _vstatic); // mass of air-flow per second
// coefs of quadratic equation
float a = 0.5*dm;
float b = dm * v0;
float c = -_power * throtle;
float Dv1, Dv2;
quadratic_roots(a, b, c, Dv1, Dv2); // solve of square of air-speed
return dm * Dv1 * _efficiency - dm * v0*_CD;
}
void Propeler::ApplyForce(const Vector3& vair0, float airDens, const Matrix3& craftRot, const Vector3& craftOmega, Vector3& force, Vector3& torq, float throtle, int i, bool debug, const Vector3& pos0) const
{
// rotation of panel in world coordinates
Vector3 gdir = craftRot * _ldir; // direction
Vector3 gdpos = craftRot * _lpos; // position
Vector3 pos = pos0 + gdpos;
float v = 0.0;
float Fout = _thrustRocket * throtle; // constant velocity independent thrust - like rocket
if (_bSolveBypass)
{ // thrust computed from velocity and engine power (ideal propeler)
Vector3 vair = vair0 + gdpos.CrossProduct(craftOmega); // velocity of panel due to rotation of aircraft
v = vair.Size() * gdir.DotProduct(vair);
Fout += GetBaypassThrust(v,throtle)*airDens;
}
force = gdir * Fout;
torq = gdpos.CrossProduct(force);
};
float Propeler::AutoVStatic() const
{
return pow(4 * _power / _area, 0.333333); // this is just guess without good physical justification
};
void Propeler::FromString(const char * str)
{
sscanf(str, " %f %f %f %f %f %f %f %f %f %f %f %f",
&_lpos[0], &_lpos[1], &_lpos[2],
&_ldir[0], &_ldir[1], &_ldir[2],
&_thrustRocket,
&_area, &_power, &_efficiency, &_CD, &_vstatic
);
_ldir.Normalize();
if (_vstatic < 0) _vstatic=AutoVStatic();
printf("%lf %lf %lf %lf\n", _area, _power, _efficiency, _CD);
}
// ================================
// ComposedAeroModel
// ================================
void ComposedAeroModel::ApplyForce(const Vector3& vair, const Matrix3& craftRot, const Vector3& craftOmega, Vector3& force, Vector3& torq, float elevator, float rudder, float aileron, float throtle, const Vector3& pos0) const
{
force = VZero;
torq = VZero;
#if _DEBUG_AEROSURF
bool debug = _DebugLevel >= 2;
if(debug)
{
DIAG_MESSAGE_ID(100, 9, Format("vair = %f %f %f", vair.X(), vair.Y(), vair.Z()));
renderer.Add3dLine(pos0, pos0 + vair * 10.0, PackedRed);
}
#endif // _DEBUG_AEROSURF
for (int iwing = 0; iwing < _wings.Size(); iwing++)
{
Vector3 torq_i, force_i;
const AeroSurface& wing = _wings[iwing];
// this is replaced by AeroSurf::_cElevator,_cRudder,_cAileron
//float tilt = 0.0;
//if (iwing == _elevatorId)
// tilt = -pitch;
//else if (iwing == _rudderId)
// tilt = -yaw;
//else if (iwing == _leftAirelonId)
// tilt = roll;
//else if (iwing == _rightAirelonId)
// tilt = -roll;
//wing.ApplyForce(vair, craftRot, craftOmega, force_i, torq_i, wing.Control2tilt(tilt), iwing, debug, pos0);
float tilt = 0.0;
if(wing._bControlable)
tilt = wing.Controls2tilt(elevator, rudder, aileron);
wing.ApplyForce(vair, craftRot, craftOmega, force_i, torq_i, tilt, iwing, debug, pos0);
force += force_i;
torq += torq_i;
#if _DEBUG_AEROSURF
if (debug)
{
Vector3 pos_i = pos0 + craftRot * wing._lpos;
float a = sqrt(wing._area / wing._aspectRatio);
drawWing(pos_i, craftRot*wing._lrot, a, wing._aspectRatio);
}
#endif // _DEBUG_AEROSURF
}
if (_bSupersonic)
{
// http://www.srmuniv.ac.in/sites/default/files/downloads/class4-2012.pdf
float speedOfSound = 343.0f; // TODO : speed of sound may change with altitude etc. https://en.wikipedia.org/wiki/Speed_of_sound#/media/File:Comparison_US_standard_atmosphere_1962.svg
float v2 = vair.SquareSize();
if ( v2 > Square( speedOfSound*_MachMin ) )
{
float v = sqrt(v2);
float wd = supersonicDrag( v/speedOfSound, _Mach0, _MachMin, _MachMax );
float cdir = vair.DotProduct(force);
force += vair * ( _cWaveDrag * wd * cdir / v2 ); // apply wave-drag-force along airflow direction; 1/v2 factor since (vair*cdir)~v2
}
}
float fDens = 0.5*Atmosphere::GetDensity(pos0[1]); // rho/2; hope that _position[1]==0 is sea level ?
#if _DEBUG_AEROSURF
if (_DebugLevel >= 2)
{
DIAG_MESSAGE_ID(15, 65, Format("Attitude %f AirDensity %f ", pos0[1], fDens*2.0));
}
#endif // _DEBUG_AEROSURF
force *= fDens;
torq *= fDens;
for (int i = 0; i < _propelers.Size(); i++)
{
Vector3 torq_i, force_i;
const Propeler& prop = _propelers[i];
prop.ApplyForce(vair, fDens, craftRot, craftOmega, force_i, torq_i, throtle, i, debug, pos0);
force += force_i;
torq += torq_i;
}
};
void ComposedAeroModel::FromFile(FILE* pFile)
{
const int nbuf = 1024;
char buf[nbuf];
fgets(buf, nbuf, pFile);
int nWings;
sscanf(buf, "%i\n", &nWings);
//_wings.Access(nWings);
_wings.Resize(nWings);
for (int i = 0; i < _wings.Size(); i++)
{
fgets(buf, nbuf, pFile);
_wings[i].FromStringPolarModel(buf);
}
//fgets(buf, nbuf, pFile);
//sscanf(buf, "%i %i %i %i\n", &_leftAirelonId, &_rightAirelonId, &_elevatorId, &_rudderId);
//_leftAirelonId--;
//_rightAirelonId--;
//_elevatorId--;
//_rudderId--;
};
int ComposedAeroModel::LoadFile(const char * fname)
{
FILE * pFile;
LogF(" AeroTestPlatform::InitWingsFile loading wings from: >>%s<<\n", fname);
pFile = fopen(fname, "r");
if (pFile == nullptr)
{
LogF(" ComposedAeroModel::fromFile cannot open >>%s<< => call default InitWings() \n", fname);
//exit(-1);
return -1;
}
FromFile(pFile);
LogF("AeroTestPlatform::InitWingsFile wings loaded from >>%s<<\n", fname);
fclose(pFile);
return 0;
};
char* ComposedAeroModel::ToString(char * str) const
{
str += sprintf(str, " ===== AeroTestPlatform::toString : _nWings %i \n", _wings.Size());
for (int i = 0; i < _wings.Size(); i++)
{
str += sprintf(str, " ===== wing[%i] ", i);
str += _wings[i].ToStringPolarModel(str);
};
return str;
};
float ComposedAeroModel::WettedArea() const
{
float area = 0;
for (int i = 0; i < _wings.Size(); i++)
{
area += _wings[i]._area;
}
return area;
};
float ComposedAeroModel::MultArea(float f)
{
float area = 0;
for (int i = 0; i < _wings.Size(); i++)
{
float a = _wings[i]._area;
a *= f;
_wings[i]._area = a;
area += a;
}
return area;
};
float ComposedAeroModel::GetMaxTorqScale() const
{
float tmax = 0;
for (int i = 0; i < _wings.Size(); i++)
{
float ti = _wings[i]._lpos.Size() * _wings[i]._area;
tmax = fmax(tmax, ti);
}
return tmax;
};
// ======================================================
// CompactAeroModel
// ======================================================
void CompactAeroModel::FromString(const char * str)
{
sscanf(str, " %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f ",
&_area,
&_cAnisoDrag[0], &_cAnisoDrag[1], &_cAnisoDrag[2],
&_cTorqDamp[0], &_cTorqDamp[1], &_cTorqDamp[2],
&_cTorqControl[0], &_cTorqControl[1], &_cTorqControl[2],
&_cTorqRelax[0], &_cTorqRelax[1], &_cTorqRelax[2],
&(_polarFwUp._sStall), &(_polarFwUp._wStall), &(_polarFwUp._CD0), &(_polarFwUp._dCD), &(_polarFwUp._dCDS), &(_polarFwUp._dCL), &(_polarFwUp._dCLS)
);
LogF(" ===== CompactAeroModel::fromString \n");
LogF(" area %f C %f %f %f D %f %f %f L %f %f %f S %f %f %f \n", _area,
_cAnisoDrag[0], _cAnisoDrag[1], _cAnisoDrag[2],
_cTorqDamp[0], _cTorqDamp[1], _cTorqDamp[2],
_cTorqControl[0], _cTorqControl[1], _cTorqControl[2],
_cTorqRelax[0], _cTorqRelax[1], _cTorqRelax[2]
);
LogF("polarFwUp %f %f %f %f %f %f %f \n", _polarFwUp._sStall, _polarFwUp._wStall, _polarFwUp._CD0, _polarFwUp._dCD, _polarFwUp._dCDS, _polarFwUp._dCL, _polarFwUp._dCLS);
};
void CompactAeroModel::ApplyForce(const Vector3& vair0, const Matrix3& craftRot, const Vector3& craftOmega, Vector3& force, Vector3& torq, float elevator, float rudder, float aileron, const Vector3& pos0) const
{
Vector3 uair = vair0; // we shoud consider craftOmega
#if _DEBUG_AEROSURF
renderer.Add3dLine(pos0, pos0 + uair * 5.0, PackedBlue);
renderer.Add3dLine(pos0, pos0 + craftRot.DirectionAside()*5.0, PackedColor(0xff808080));
renderer.Add3dLine(pos0, pos0 + craftRot.DirectionUp()*5.0, PackedBlack);
renderer.Add3dLine(pos0, pos0 + craftRot.Direction()*5.0, PackedWhite);
#endif // _DEBUG_AEROSURF
//Vector3 uair = vair0 + gdpos.CrossProduct(craftOmega);
float vrair2 = uair.SquareSize();
torq = VZero;
force = VZero;
if (vrair2 > lowSpeedCuoff) // for zero air-speed we would devide by 0
{
float vrair = sqrt(vrair2);
uair *= (1 / vrair);
// decompose uair to panel coordinates
float ca = uair.DotProduct(craftRot.DirectionAside());
float cb = uair.DotProduct(craftRot.DirectionUp());
float cc = uair.DotProduct(craftRot.Direction());
#if _DEBUG_AEROSURF
DIAG_MESSAGE_ID(100, 11, Format("elevator %f rudder %f aileron %f ", elevator, rudder, aileron));
DIAG_MESSAGE_ID(100, 12, Format("ca %f cb %f cc %f ", ca, cb, cc));
#endif // _DEBUG_AEROSURF
float prefactor = vrair2 * _area; // scale all aerodynamic forces by this
{
float CD, CL;
Vector3 airUp;
_polarFwUp.GetAeroCoefs(-cc, cb, CD, CL);
if ((cb*cb) > 1e-8)
{
airUp = craftRot.DirectionUp() + (uair * -cb); // component of grot.Up perpendicular to uair
airUp.Normalize();
}
else { airUp = craftRot.DirectionUp(); }
#if _DEBUG_AEROSURF
renderer.Add3dLine(pos0, pos0 + airUp * 5.0, PackedGreen);
#endif // _DEBUG_AEROSURF
force += (airUp * CL + uair * CD) * prefactor;
}
#if _DEBUG_AEROSURF
renderer.Add3dLine(pos0, pos0 + force * 5.0, PackedRed);
#endif // _DEBUG_AEROSURF
float cc2 = cc * cc; // damp effect of control surfaces when aircraft is not alligned to airflow
// Stabilization - aligns aircraft orientation toward airflow
torq += craftRot.DirectionAside() * (_cTorqRelax[0] * cb*cc2* prefactor);
torq += craftRot.DirectionUp() * (_cTorqRelax[1] * -ca * cc2* prefactor);
torq += uair.CrossProduct(craftRot.Direction()) * ( _cTorqRelax[2] * prefactor );
// Control input
torq += craftRot.DirectionAside() * (_cTorqControl[0] * elevator * prefactor * cc2);
//torq += craftRot.DirectionUp() * (_cTorqControl[1] * -rudder * prefactor * cc2 );
torq += craftRot.Direction() * (_cTorqControl[2] * aileron * prefactor * cc2);
// damping of aircraft rotation due to drag of control surfaces
torq += craftRot.DirectionAside() * ( craftOmega.DotProduct(craftRot.DirectionAside()) * -_cTorqDamp[0] * prefactor); // pitch drag
torq += craftRot.DirectionUp() * ( craftOmega.DotProduct(craftRot.DirectionUp()) * -_cTorqDamp[1] * prefactor); // yaw drag
torq += craftRot.Direction() * ( craftOmega.DotProduct(craftRot.Direction()) * -_cTorqDamp[2] * prefactor); // roll drag
// apply anisotropic drag coef
force += craftRot.DirectionAside() * (_cAnisoDrag[0] * ca*prefactor);
force += craftRot.DirectionUp() * (_cAnisoDrag[1] * cb*prefactor);
force += craftRot.Direction() * (_cAnisoDrag[2] * cc*prefactor);
#if _DEBUG_AEROSURF
DIAG_MESSAGE_ID(100, 14, Format("force %f %f %f torq %f %f %f ", force.X(), force.Y(), force.Z(), torq.X(), torq.Y(), torq.Z()));
#endif // _DEBUG_AEROSURF
}
float fDens = 0.5*Atmosphere::GetDensity(pos0[1]); // hope that _position[1]==0 is ground level ?
force *= fDens;
torq *= fDens;
};
// ======================================================
// CompactAeroMode2
// ======================================================
void CompactAeroModel2::FromString(const char * str)
{
sscanf(str, " %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f ",
//&areaUp, &ARup,
//&areaSide, &ARside,
&_area,
&_cAnisoDrag[0], &_cAnisoDrag[1], &_cAnisoDrag[2],
&_cTorqDamp[0], &_cTorqDamp[1], &_cTorqDamp[2],
&_cTorqControl[0], &_cTorqControl[1], &_cTorqControl[2],
&_cTorqRelax[0], &_cTorqRelax[1], &_cTorqRelax[2],
&(_polarFwUp._sStall), &(_polarFwUp._wStall), &(_polarFwUp._CD0), &(_polarFwUp._dCD), &(_polarFwUp._dCDS), &(_polarFwUp._dCL), &(_polarFwUp._dCLS), &(_polarFwUp._dCM), &(_polarFwUp._dCMS),
&(_polarFwSide._sStall), &(_polarFwSide._wStall), &(_polarFwSide._CD0), &(_polarFwSide._dCD), &(_polarFwSide._dCDS), &(_polarFwSide._dCL), &(_polarFwSide._dCLS), &(_polarFwSide._dCM), &(_polarFwSide._dCMS)
);
LogF(" ===== CompactAeroModel2::fromString \n");
LogF(" area %f C %f %f %f D %f %f %f L %f %f %f S %f %f %f \n", _area,
_cAnisoDrag[0], _cAnisoDrag[1], _cAnisoDrag[2],
_cTorqDamp[0], _cTorqDamp[1], _cTorqDamp[2],
_cTorqControl[0], _cTorqControl[1], _cTorqControl[2],
_cTorqRelax[0], _cTorqRelax[1], _cTorqRelax[2]
);
LogF("polarFwUp %f %f %f %f %f %f %f %f %f \n", _polarFwUp._sStall, _polarFwUp._wStall, _polarFwUp._CD0, _polarFwUp._dCD, _polarFwUp._dCDS, _polarFwUp._dCL, _polarFwUp._dCLS, _polarFwUp._dCM, _polarFwUp._dCM);
LogF("polarFwSide %f %f %f %f %f %f %f %f %f \n", _polarFwSide._sStall, _polarFwSide._wStall, _polarFwSide._CD0, _polarFwSide._dCD, _polarFwSide._dCDS, _polarFwSide._dCL, _polarFwSide._dCLS, _polarFwSide._dCM, _polarFwSide._dCM);
};
void CompactAeroModel2::ApplyForce(const Vector3& vair0, const Matrix3& craftRot, const Vector3& craftOmega, Vector3& force, Vector3& torq, float elevator, float rudder, float aileron, const Vector3& pos0) const
{
Vector3 uair = vair0; // we shoud consider craftOmega
#if _DEBUG_AEROSURF
//LogF( "CompactAeroModel2::applyForce ID10: S %f %f %f L %f %f %f D %f %f %f ", S[0], S[1], S[2], L[0], L[1], L[2], D[0], D[1], D[2] );
//DIAG_MESSAGE_ID(100, 10, Format("ID10: S %f %f %f L %f %f %f D %f %f %f ", S[0], S[1], S[2], L[0], L[1], L[2], D[0], D[1], D[2]));
renderer.Add3dLine(pos0, pos0 + uair * 5.0, PackedBlue);
renderer.Add3dLine(pos0, pos0 + craftRot.DirectionAside() * 5.0, PackedColor(0xff808080));
renderer.Add3dLine(pos0, pos0 + craftRot.DirectionUp()*5.0, PackedBlack);
renderer.Add3dLine(pos0, pos0 + craftRot.Direction()*5.0, PackedWhite);
#endif // _DEBUG_AEROSURF
//Vector3 uair = vair0 + gdpos.CrossProduct(craftOmega);
float vrair2 = uair.SquareSize();
torq = VZero;
force = VZero;
if (vrair2 > lowSpeedCuoff)
{
float vrair = sqrt(vrair2);
uair *= (1 / vrair);
// decompose uair to panel coordinates
float ca = uair.DotProduct(craftRot.DirectionAside());
float cb = uair.DotProduct(craftRot.DirectionUp());
float cc = uair.DotProduct(craftRot.Direction());
#if _DEBUG_AEROSURF
DIAG_MESSAGE_ID(100, 11, Format("elevator %f rudder %f aileron %f ", elevator, rudder, aileron));
DIAG_MESSAGE_ID(100, 12, Format("ca %f cb %f cc %f ", ca, cb, cc));
#endif // _DEBUG_AEROSURF
float prefactor = vrair2 * _area;
float CD, CL, CMup, CMside;
Vector3 airUp;
// ==== main wing polar (lift along aircraft up vector); Pitch control
{
_polarFwUp.GetAeroCoefs(-cc, cb, elevator*0.25, CD, CL, CMup);
if ((cb*cb) > 1e-8)
{
airUp = craftRot.DirectionUp() + (uair * -cb); // component of grot.Up perpendicular to uair
airUp.Normalize();
}
else
{
airUp = craftRot.DirectionUp();
}
#if _DEBUG_AEROSURF
renderer.Add3dLine(pos0, pos0 + airUp * 5.0, PackedGreen);
#endif // _DEBUG_AEROSURF
force += (airUp * CL + uair * CD) * prefactor;
torq += airUp.CrossProduct(uair) * -CMup * prefactor;
}
// ==== keel wing polar (lift along aircraft side vector); Yaw control
{
_polarFwSide.GetAeroCoefs(-cc, ca, 0, CD, CL, CMside);
if ((ca*ca) > 1e-8)
{
airUp = craftRot.DirectionAside() + (uair * -ca); // component of grot.Up perpendicular to uair
airUp.Normalize();
}
else
{
airUp = craftRot.DirectionAside();
}
#if _DEBUG_AEROSURF
renderer.Add3dLine(pos0, pos0 + airUp * 5.0, PackedColor(0xffff00ff));
#endif // _DEBUG_AEROSURF
force += (airUp * CL + uair * CD) * prefactor * 0.2;
torq += airUp.CrossProduct(uair) * -CMside * prefactor;
}
#if _DEBUG_AEROSURF
DIAG_MESSAGE_ID(100, 13, Format(" CMup %f CMside %f ", CMup, CMside));
renderer.Add3dLine(pos0, pos0 + force * 5.0, PackedRed);
#endif // _DEBUG_AEROSURF
float cc2 = cc * cc; // factor used to damp torques for non-standard flight regimes ( large angle between vair and grot.Direction() )
torq += craftRot.Direction() * (_cTorqControl[2] * aileron * prefactor * cc2); // Roll control - we still don't do this by Polar
// damping of aircraft rotation due to drag of control surfaces
torq += craftRot.DirectionAside()* ( craftOmega.DotProduct(craftRot.DirectionAside()) * -_cTorqDamp[0] * prefactor); // pitch damp
torq += craftRot.DirectionUp()* ( craftOmega.DotProduct(craftRot.DirectionUp()) * -_cTorqDamp[1] * prefactor); // yaw damp
torq += craftRot.Direction()* ( craftOmega.DotProduct(craftRot.Direction()) * -_cTorqDamp[2] * prefactor); // roll damp
// apply anisotropic drag coef
force += craftRot.DirectionAside() * (_cAnisoDrag[0] * ca*prefactor);
force += craftRot.DirectionUp() * (_cAnisoDrag[1] * cb*prefactor);
force += craftRot.Direction() * (_cAnisoDrag[2] * cc*prefactor);
#if _DEBUG_AEROSURF
DIAG_MESSAGE_ID(100, 14, Format("force %f %f %f torq %f %f %f ", force.X(), force.Y(), force.Z(), torq.X(), torq.Y(), torq.Z()));
#endif // _DEBUG_AEROSURF
}
float fDens = 0.5*Atmosphere::GetDensity(pos0[1]); // hope that _position[1]==0 is ground level ?
force *= fDens;
torq *= fDens;
};
| 41.945378
| 232
| 0.593208
|
ProkopHapala
|
9937511dd96eb5f5b44d8fdf60832706774ce001
| 7,997
|
cc
|
C++
|
src/jumandic/shared/lattice_format.cc
|
HarukaMa/jumanpp
|
9e7ca75ecf79c596c86731f63e1e07a8b45076de
|
[
"Apache-2.0"
] | 300
|
2016-10-19T02:20:39.000Z
|
2022-02-23T19:58:04.000Z
|
src/jumandic/shared/lattice_format.cc
|
HarukaMa/jumanpp
|
9e7ca75ecf79c596c86731f63e1e07a8b45076de
|
[
"Apache-2.0"
] | 130
|
2016-10-17T07:57:14.000Z
|
2022-03-20T17:37:13.000Z
|
src/jumandic/shared/lattice_format.cc
|
HarukaMa/jumanpp
|
9e7ca75ecf79c596c86731f63e1e07a8b45076de
|
[
"Apache-2.0"
] | 36
|
2016-10-19T11:47:05.000Z
|
2022-01-25T09:36:12.000Z
|
//
// Created by Arseny Tolmachev on 2017/07/21.
//
#include "lattice_format.h"
#include "core/analysis/analyzer_impl.h"
#include "util/logging.hpp"
namespace jumanpp {
namespace jumandic {
namespace output {
Status LatticeFormatInfo::fillInfo(const core::analysis::Analyzer& an,
i32 topN) {
auto ai = an.impl();
auto lat = ai->lattice();
info.clear_no_resize();
if (lat->createdBoundaryCount() <= 3) {
return Status::Ok();
}
auto eosBnd = lat->boundary(lat->createdBoundaryCount() - 1);
auto eosBeam = eosBnd->starts()->beamData();
auto maxN = std::min<i32>(eosBeam.size(), topN);
for (int i = 0; i < maxN; ++i) {
auto el = eosBeam.at(i);
if (core::analysis::EntryBeam::isFake(el)) {
break;
}
auto ptr = el.ptr.previous;
while (ptr->boundary >= 2) {
info[ptr->latticeNodePtr()].addElem(*ptr, i);
ptr = ptr->previous;
}
}
return Status::Ok();
}
void LatticeFormatInfo::publishResult(std::vector<LatticeInfoView>* view) {
view->clear();
view->reserve(info.size());
for (auto& pair : info) {
view->push_back({pair.first, &pair.second});
pair.second.fixPrevs();
}
std::sort(view->begin(), view->end(),
[](const LatticeInfoView& v1, const LatticeInfoView& v2) {
if (v1.nodePtr().boundary == v2.nodePtr().boundary) {
return v1.nodePtr().position < v2.nodePtr().position;
}
return v1.nodePtr().boundary < v2.nodePtr().boundary;
});
i32 firstId = 1;
for (auto& v : *view) {
v.assignId(firstId);
++firstId;
}
}
i32 LatticeFormatInfo::idOf(LatticeNodePtr ptr) const {
auto iter = info.find(ptr);
if (iter != info.end()) {
return iter->second.id;
}
return 0;
}
namespace {
StringPiece escapeTab(StringPiece sp) {
if (sp.size() == 1 && sp[0] == '\t') {
return StringPiece("\\t");
}
return sp;
}
} // namespace
Status LatticeFormat::format(const core::analysis::Analyzer& analyzer,
StringPiece comment) {
printer.reset();
auto lat = analyzer.impl()->lattice();
if (lat->createdBoundaryCount() == 3) {
printer.reset();
printer << "EOS\n";
return Status::Ok();
}
i32 outputN = this->topN;
if (analyzer.impl()->cfg().autoBeamStep > 0) {
outputN = analyzer.impl()->autoBeamSizes();
}
JPP_RETURN_IF_ERROR(latticeInfo.fillInfo(analyzer, outputN));
latticeInfo.publishResult(&infoView);
auto& om = analyzer.output();
auto& f = flds;
if (!comment.empty()) {
printer << "# " << comment << '\n';
} else {
printer << "# MA-SCORE\t";
auto eos = lat->boundary(lat->createdBoundaryCount() - 1);
auto eosBeam = eos->starts()->beamData();
for (int i = 0; i < outputN; ++i) {
auto& bel = eosBeam.at(i);
if (core::analysis::EntryBeam::isFake(bel)) {
break;
}
printer << "rank" << (i + 1) << ':' << bel.totalScore << ' ';
}
printer << '\n';
}
for (auto& n : infoView) {
if (!om.locate(n.nodePtr(), &walker)) {
return Status::InvalidState()
<< "failed to locate node: " << n.nodePtr().boundary << ":"
<< n.nodePtr().position;
}
auto& weights = analyzer.scorer()->scoreWeights;
auto ptrit = std::max_element(
n.nodeInfo().ptrs.begin(), n.nodeInfo().ptrs.end(),
[lat, &weights](const core::analysis::ConnectionPtr& p1,
const core::analysis::ConnectionPtr& p2) {
auto s1 = lat->boundary(p1.boundary)->scores()->forPtr(p1);
auto s2 = lat->boundary(p2.boundary)->scores()->forPtr(p2);
float total1 = 0, total2 = 0;
for (size_t i = 0; i < weights.size(); ++i) {
total1 += s1[i] * weights[i];
total2 += s2[i] * weights[i];
}
return total1 > total2;
});
auto& cptr = *ptrit;
auto bnd = lat->boundary(cptr.boundary);
auto& ninfo = bnd->starts()->nodeInfo().at(cptr.right);
while (walker.next()) {
printer << "-\t";
printer << n.nodeInfo().id << '\t';
auto& prevs = n.nodeInfo().prev;
for (size_t i = 0; i < prevs.size(); ++i) {
auto id = latticeInfo.idOf(prevs[i]);
printer << id;
if (i != prevs.size() - 1) {
printer << ';';
}
}
printer << '\t';
auto position = cptr.boundary - 2; // we have 2 BOS
printer << position << '\t';
printer << position + ninfo.numCodepoints() - 1 << '\t';
printer << escapeTab(f.surface[walker]) << '\t';
auto canFrm = f.canonicForm[walker];
if (!canFrm.empty()) {
printer << f.canonicForm[walker];
} else {
printer << f.baseform[walker] << '/' << f.reading[walker];
}
printer << '\t';
printer << escapeTab(f.reading[walker]) << '\t';
printer << escapeTab(f.baseform[walker]) << '\t';
auto fieldBuffer = walker.features();
JumandicPosId rawId{fieldBuffer[1], fieldBuffer[2],
fieldBuffer[4], // conjForm and conjType are reversed
fieldBuffer[3]};
auto newId = idResolver.dicToJuman(rawId);
printer << f.pos[walker] << '\t' << newId.pos << '\t';
printer << ifEmpty(f.subpos[walker], "*") << '\t' << newId.subpos << '\t';
printer << ifEmpty(f.conjType[walker], "*") << '\t' << newId.conjType
<< '\t';
printer << ifEmpty(f.conjForm[walker], "*") << '\t' << newId.conjForm
<< '\t';
auto features = f.features[walker];
while (features.next()) {
printer << features.key();
if (features.hasValue()) {
printer << ':' << features.value();
}
printer << '|';
}
auto eptr = walker.eptr();
if (eptr.isSpecial()) {
auto v =
om.valueOfUnkPlaceholder(eptr, jumandic::NormalizedPlaceholderIdx);
if (v != 0) {
formatNormalizedFeature(printer, v);
printer << "|";
}
}
auto conn = bnd->scores();
auto scores = conn->forPtr(cptr);
JPP_DCHECK_GE(weights.size(), 1);
float totalScore = scores[0] * weights[0];
printer << "特徴量スコア:" << totalScore << '|';
if (weights.size() == 2) { // have RNN
float rnnScore = scores[1] * weights[1];
printer << "言語モデルスコア:" << rnnScore << '|';
totalScore += rnnScore;
}
printer << "形態素解析スコア:" << totalScore << '|';
printer << "ランク:";
auto& ranks = n.nodeInfo().ranks;
for (size_t i = 0; i < ranks.size(); ++i) {
printer << ranks[i] + 1;
if (i != ranks.size() - 1) {
printer << ';';
}
}
printer << '\n';
}
}
printer << "EOS\n";
return Status::Ok();
}
StringPiece LatticeFormat::result() const { return printer.result(); }
Status LatticeFormat::initialize(const core::analysis::OutputManager& om) {
LOG_TRACE() << "Initializing Lattice format, topn=" << topN;
JPP_RETURN_IF_ERROR(flds.initialize(om));
JPP_RETURN_IF_ERROR(idResolver.initialize(om.dic()));
return Status::Ok();
}
LatticeFormat::LatticeFormat(i32 topN) : topN(topN) {
printer.reserve(16 * 1024);
}
void LatticeNodeInfo::addElem(const core::analysis::ConnectionPtr& cptr,
i32 rank) {
ranks.push_back(static_cast<u16>(rank));
ptrs.insert(cptr);
auto prevptr = cptr.previous->latticeNodePtr();
if (std::find(prev.begin(), prev.end(), prevptr) == prev.end()) {
prev.push_back(prevptr);
}
}
void LatticeNodeInfo::fixPrevs() {
if (prev.size() > 1) {
std::sort(prev.begin(), prev.end(),
[](const LatticeNodePtr& p1, const LatticeNodePtr& p2) {
if (p1.boundary == p2.boundary)
return p1.position < p2.position;
return p1.boundary < p2.boundary;
});
}
}
} // namespace output
} // namespace jumandic
} // namespace jumanpp
| 28.663082
| 80
| 0.549706
|
HarukaMa
|
9937f50614e6ba984a31acd400bde0a8bf8dc7e1
| 8,221
|
cpp
|
C++
|
ch06/6.exercise.10.cpp
|
0p3r4t4/PPPUCPP2nd
|
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
|
[
"MIT"
] | 51
|
2017-03-24T06:08:11.000Z
|
2022-03-18T00:28:14.000Z
|
ch06/6.exercise.10.cpp
|
0p3r4t4/PPPUCPP2nd
|
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
|
[
"MIT"
] | 1
|
2019-06-23T07:33:42.000Z
|
2019-12-12T13:14:04.000Z
|
ch06/6.exercise.10.cpp
|
0p3r4t4/PPPUCPP2nd
|
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
|
[
"MIT"
] | 25
|
2017-04-07T13:22:45.000Z
|
2022-03-18T00:28:15.000Z
|
// 6.exercise.10.cpp
//
// A permutation is an ordered subset of a set. For example, say you wanted to
// pick a combination to a vault. There are 60 possible numbers, and you need
// three different numbers for the combination. There are P(60,3) permutations
// for the combination, where P is defined by the formula
//
// a!
// P(a,b) = ------,
// (a-b)!
//
// where ! is used as a suffix factorial operator. For example, 4! is
// 4*3*2*1.
//
// Combinations are similar to permutations, except that the order of the
// objects doesn't matter. For example, if you were making a "banana split"
// sundea and wished to use three different flavors of ice cream out of five
// that you had, you wouldn't care if you used a scoop of vanilla at the
// beginning or the end; you would still have used vanilla. The formula for
// combination is
//
// P(a,b)
// C(a,b) = ------.
// b!
//
// Design a program that asks users for two numbers, asks them whether they
// want to calculate permutations or combinations, and prints out the result.
// This will have several parts. Do an analysis of the above requeriments.
// Write exactly what the program will have to do. Then go into design phase.
// Write pseudo code for the program, and break it into sub-components. This
// program should have error checking. Make sure that all erroneous inputs will
// generate good error messages
//
// Comments: See 6.exercise.10.md
#include "std_lib_facilities.h"
const string err_msg_pmul_with_negs = "called with negative integers.";
const string err_msg_nk_precon = "n and k parameters relationship precondition violated.";
const string err_msg_product_overflows = "integer multiplication overflows.";
const string err_msg_eoi = "Unexpected end of input.";
const string err_msg_main_bad_option = "Bad option parsing.";
const string msg_setc_get = "Set cardinality (n)? ";
const string msg_subc_get = "Subset cardinality (n)? ";
const string msg_calc_option = "What type of calculation do you want? (p)ermutation, (c)ombination or (b)oth? ";
const string msg_again_option = "Do you want to perform a new calculation (y/n)? ";
bool is_in(const char c, const vector<char>& v)
// Returns true if character c is contained in vector<char> v and returns false
// otherwise.
{
for (char cv : v)
if (cv == c) return true;
return false;
}
int get_natural(const string& msg)
// Asks the user (printing the message msg) for a positive integer.
// It keeps asking until a positive integer is entered or EOF is reached
// or signaled, in which case it throws an error.
// Tries to read an integer ignoring the rest of the line, whatever it is, and
// despite that read has been successful or not.
{
int n = 0;
for (;;) {
cout << msg;
cin >> n;
if (cin) {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (n < 0)
cout << n << " is not a positive integer.\n";
else
return n;
}
else if (!cin.eof()) {
cout << "Your input is not a number.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else {
error("get_natural(): " + err_msg_eoi);
}
}
}
char get_option(const string& msg, const vector<char>& v)
// Asks the user (printing the message msg) for a char value (option).
// It keeps asking until the answer is a char value that is present in vector
// v or EOF is reached or signales, in which case it throws and error.
// Only the first character of a line is considered, ignoring the rest of it.
{
char c = 0;
for (;;) {
cout << msg;
cin >> c;
if (cin) {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (!is_in(c, v))
cout << c << " is not a valid option.\n";
else
return c;
}
else {
// If cin fails reading a char, I guess the only way is to
// have reached end of input. I could be mistaken, though.
error("get_option(): " + err_msg_eoi);
}
}
}
bool check_pmul(int a, int b)
// Partial implementation not using larger integer type and only for
// positive integers, from https://www.securecoding.cert.org INT32C.
// Is its work to tell if multiplication could
// be performed or not.
// Precondition:
// Both arguments must be positive.
{
if (a < 0 || b < 0)
error("check_pmul(): " + err_msg_pmul_with_negs);
return !( a > (numeric_limits<int>::max() / b) );
}
int perm(int n, int k)
// Calculates the k-permutations of n elements, what we call P(n, k).
// This is not done with the factorial formula expressed in the statement but
// with a limited product. See 6.exercise.10.md for details.
// If either n or k equals zero, the permutation is 1.
//
// Preconditions:
// - n and k must be positive and n >= k. It's very unlikely to happen
// otherwise since we assume it is assured by previous calls to
// get_natural(), but to maintain good habits ...
{
if (n < 0 || k < 0 || n < k)
error("perm(): " + err_msg_nk_precon);
if (n == 0 || k == 0) return 1;
int prod = 1;
for (int i = n-k+1; i <= n; ++i)
if (check_pmul(prod, i))
prod *= i;
else
error("perm(): " + err_msg_product_overflows);
return prod;
}
int comb(int n, int k)
// Calculates the k-combinations of n elements, what we call C(n, k).
// This is not done with the factorial formula expressed in the statement but,
// being the k-combinations of n element also known as the binomial
// coefficient, using the multiplicative formula as stated in
// https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula
// If either n or k equals zero, the combination is 1.
//
// Preconditions:
// - n and k must be positive and n >= k. It's very unlikely to happen
// otherwise since we assume it is assured by previous calls to
// get_natural(), but to maintain good habits ...
{
if (n < 0 || k < 0 || n < k)
error("perm(): " + err_msg_nk_precon);
if (n == 0 || k == 0) return 1;
int prod = 1;
for (int i = 1; i <= k; ++i)
if (check_pmul(prod, n+1-i))
// Multiplying first by the numerator ensure the division to have
// no reminder.
prod = (prod * (n+1-i)) / i;
else
error("comb(): " + err_msg_product_overflows);
return prod;
}
int main()
try
{
const vector<char> calc_options = {'p', 'P', 'c', 'C', 'b', 'B'};
const vector<char> again_options = {'y', 'Y', 'n', 'N'};
cout << "Calculator for k-permutation and k-combination of n elements\n"
"without repetition. Beware of large numbers, the calculator\n"
"is very limited.\n";
while (cin) {
cout << endl;
int setc = get_natural(msg_setc_get);
int subc = get_natural(msg_subc_get);
char option = get_option(msg_calc_option, calc_options);
switch(option) {
case 'p':
case 'P':
cout << " P(" << setc << ", " << subc << ") = "
<< perm(setc, subc) << '\n';
break;
case 'c':
case 'C':
cout << " C(" << setc << ", " << subc << ") = "
<< comb(setc, subc) << '\n';
break;
case 'b':
case 'B':
cout << " P(" << setc << ", " << subc << ") = "
<< perm(setc, subc) << '\n';
cout << " C(" << setc << ", " << subc << ") = "
<< comb(setc, subc) << '\n';
break;
default:
error("main(): " + err_msg_main_bad_option);
}
option = get_option(msg_again_option, again_options);
if (option == 'n' || option == 'N') break;
}
cout << "\nBye!\n\n";
return 0;
}
catch(exception& e)
{
cerr << e.what() << '\n';
return 1;
}
catch(...)
{
cerr << "Oops! Unknown exception.\n";
return 2;
}
| 33.971074
| 112
| 0.585452
|
0p3r4t4
|
993c39b4a2928028fd47a4e72fb468df81a7ecff
| 2,598
|
cpp
|
C++
|
Source/GUI/VintageToggleButton.cpp
|
grhn/gold-rush-filter
|
7b91dc5c44bc1acb46804638c357f8e240becdc3
|
[
"MIT"
] | 1
|
2019-09-08T19:57:22.000Z
|
2019-09-08T19:57:22.000Z
|
Source/GUI/VintageToggleButton.cpp
|
grhn/gold-rush-filter
|
7b91dc5c44bc1acb46804638c357f8e240becdc3
|
[
"MIT"
] | null | null | null |
Source/GUI/VintageToggleButton.cpp
|
grhn/gold-rush-filter
|
7b91dc5c44bc1acb46804638c357f8e240becdc3
|
[
"MIT"
] | null | null | null |
//
// VintageToggleButton.cpp
// GoldRush
//
// Created by Tommi Gröhn on 26.10.2015.
//
//
#include "VintageToggleButton.h"
VintageToggleButton::VintageToggleButton (Colour baseColour, Colour switchColour) : baseColour (baseColour), switchColour (switchColour)
{
}
void VintageToggleButton::setLabel (String s)
{
label = s;
}
void VintageToggleButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
{
const float w = getWidth();
const float h = getHeight();
const float rounding = 2.0f;
const float edgeSize = 2.0f;
// Draw base
{
Path p;
g.setGradientFill(ColourGradient(Colours::darkgrey, 0, 0,
Colours::black, 0 + w / 8.0, h,
false));
p.addRoundedRectangle (0, 0, w, h,
rounding, rounding,
rounding, rounding,
rounding, rounding);
g.fillPath (p);
g.fillPath (p);
}
// Draw button
{
Path p;
if (getToggleState())
{
g.setGradientFill(ColourGradient(Colours::red, w / 2, h / 3,
Colours::darkred.darker(), 0, h,
true));
p.addRoundedRectangle (edgeSize, edgeSize, w - edgeSize * 2.0, h - edgeSize * 2.0,
rounding, rounding,
rounding, rounding,
rounding, rounding);
g.fillPath (p);
}
else
{
g.setGradientFill(ColourGradient(Colours::red.withBrightness (0.3), 0, 0,
Colours::red.withBrightness (0.1), 0, h,
false));
p.addRoundedRectangle (edgeSize, edgeSize, w - edgeSize * 2.0, h - edgeSize * 2.0,
rounding, rounding,
rounding, rounding,
rounding, rounding);
g.fillPath (p);
}
}
// Draw label on top of button
{
const float margin = 2.0;
g.setFont (goldRushFonts::logoFont.withHeight(14.0f));
g.setColour (Colours::antiquewhite);
g.drawFittedText (getName(), Rectangle<int> (margin, margin, getWidth() - 2.0 * margin, getHeight() - 2.0 * margin),
Justification::centred,
2);
}
}
| 32.475
| 136
| 0.469977
|
grhn
|
9945af9d2f759ea6e140d9addac71d3923741a56
| 1,534
|
cpp
|
C++
|
2011-codeforces-saratov-school-regional/d_three-sons.cpp
|
galenhwang/acm-problems
|
304e11a144c5589c6d9e493b05ad228f20619686
|
[
"MIT"
] | null | null | null |
2011-codeforces-saratov-school-regional/d_three-sons.cpp
|
galenhwang/acm-problems
|
304e11a144c5589c6d9e493b05ad228f20619686
|
[
"MIT"
] | null | null | null |
2011-codeforces-saratov-school-regional/d_three-sons.cpp
|
galenhwang/acm-problems
|
304e11a144c5589c6d9e493b05ad228f20619686
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
int get (int accumTotal[], int first, int last) {
int permVal = accumTotal[last];
if (first > 0)
permVal -= accumTotal[first-1];
return permVal;
}
int numWays(int len, int accumTotal[], int sons[]) {
int val = 0;
for(int i = 0; i < len; i++) {
for(int j = i + 1; j < len - 1; j++) {
int perm[3] = { get(accumTotal, 0, i),get(accumTotal, i+1,j),
get(accumTotal, j+1,len-1) };
sort(perm, perm+3);
if(perm[0] == sons[0] && perm[1] == sons[1] && perm[2] == sons[2])
val++;
}
}
return val;
}
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, m;
cin >> n >> m;
int count = 0;
int accumRowTotals[n];
int accumColTotals[m];
for (int i = 0; i < n; i++) {
accumRowTotals[i] = 0;
for (int j = 0; j < m; j++) {
if (i == 0) accumColTotals[j] = 0;
int val;
cin >> val;
accumRowTotals[i] += val;
accumColTotals[j] += val;
}
if (i > 0) accumRowTotals[i] += accumRowTotals[i-1];
}
for (int j = 0; j < m; j++) {
if (j > 0) accumColTotals[j] += accumColTotals[j-1];
}
int sons[3];
for (int i = 0; i < 3; i++) {
cin >> sons[i];
}
sort(sons, sons+3);
cout << numWays(m, accumColTotals, sons) + numWays(n, accumRowTotals, sons) << endl;
}
| 26.912281
| 88
| 0.483703
|
galenhwang
|
994640bbfd3c68da9bda39bdace3ff969b0a97f9
| 177,106
|
cc
|
C++
|
src/bin/dhcp4/dhcp4_lexer.cc
|
mcr/kea
|
7fbbfde2a0742a3d579d51ec94fc9b91687fb901
|
[
"Apache-2.0"
] | 1
|
2019-08-10T21:52:58.000Z
|
2019-08-10T21:52:58.000Z
|
src/bin/dhcp4/dhcp4_lexer.cc
|
jxiaobin/kea
|
1987a50a458921f9e5ac84cb612782c07f3b601d
|
[
"Apache-2.0"
] | null | null | null |
src/bin/dhcp4/dhcp4_lexer.cc
|
jxiaobin/kea
|
1987a50a458921f9e5ac84cb612782c07f3b601d
|
[
"Apache-2.0"
] | null | null | null |
#line 1 "dhcp4_lexer.cc"
#line 3 "dhcp4_lexer.cc"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
/* %not-for-header */
/* %if-c-only */
/* %if-not-reentrant */
#define yy_create_buffer parser4__create_buffer
#define yy_delete_buffer parser4__delete_buffer
#define yy_scan_buffer parser4__scan_buffer
#define yy_scan_string parser4__scan_string
#define yy_scan_bytes parser4__scan_bytes
#define yy_init_buffer parser4__init_buffer
#define yy_flush_buffer parser4__flush_buffer
#define yy_load_buffer_state parser4__load_buffer_state
#define yy_switch_to_buffer parser4__switch_to_buffer
#define yypush_buffer_state parser4_push_buffer_state
#define yypop_buffer_state parser4_pop_buffer_state
#define yyensure_buffer_stack parser4_ensure_buffer_stack
#define yy_flex_debug parser4__flex_debug
#define yyin parser4_in
#define yyleng parser4_leng
#define yylex parser4_lex
#define yylineno parser4_lineno
#define yyout parser4_out
#define yyrestart parser4_restart
#define yytext parser4_text
#define yywrap parser4_wrap
#define yyalloc parser4_alloc
#define yyrealloc parser4_realloc
#define yyfree parser4_free
/* %endif */
/* %endif */
/* %ok-for-header */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* %if-c++-only */
/* %endif */
/* %if-c-only */
#ifdef yy_create_buffer
#define parser4__create_buffer_ALREADY_DEFINED
#else
#define yy_create_buffer parser4__create_buffer
#endif
#ifdef yy_delete_buffer
#define parser4__delete_buffer_ALREADY_DEFINED
#else
#define yy_delete_buffer parser4__delete_buffer
#endif
#ifdef yy_scan_buffer
#define parser4__scan_buffer_ALREADY_DEFINED
#else
#define yy_scan_buffer parser4__scan_buffer
#endif
#ifdef yy_scan_string
#define parser4__scan_string_ALREADY_DEFINED
#else
#define yy_scan_string parser4__scan_string
#endif
#ifdef yy_scan_bytes
#define parser4__scan_bytes_ALREADY_DEFINED
#else
#define yy_scan_bytes parser4__scan_bytes
#endif
#ifdef yy_init_buffer
#define parser4__init_buffer_ALREADY_DEFINED
#else
#define yy_init_buffer parser4__init_buffer
#endif
#ifdef yy_flush_buffer
#define parser4__flush_buffer_ALREADY_DEFINED
#else
#define yy_flush_buffer parser4__flush_buffer
#endif
#ifdef yy_load_buffer_state
#define parser4__load_buffer_state_ALREADY_DEFINED
#else
#define yy_load_buffer_state parser4__load_buffer_state
#endif
#ifdef yy_switch_to_buffer
#define parser4__switch_to_buffer_ALREADY_DEFINED
#else
#define yy_switch_to_buffer parser4__switch_to_buffer
#endif
#ifdef yypush_buffer_state
#define parser4_push_buffer_state_ALREADY_DEFINED
#else
#define yypush_buffer_state parser4_push_buffer_state
#endif
#ifdef yypop_buffer_state
#define parser4_pop_buffer_state_ALREADY_DEFINED
#else
#define yypop_buffer_state parser4_pop_buffer_state
#endif
#ifdef yyensure_buffer_stack
#define parser4_ensure_buffer_stack_ALREADY_DEFINED
#else
#define yyensure_buffer_stack parser4_ensure_buffer_stack
#endif
#ifdef yylex
#define parser4_lex_ALREADY_DEFINED
#else
#define yylex parser4_lex
#endif
#ifdef yyrestart
#define parser4_restart_ALREADY_DEFINED
#else
#define yyrestart parser4_restart
#endif
#ifdef yylex_init
#define parser4_lex_init_ALREADY_DEFINED
#else
#define yylex_init parser4_lex_init
#endif
#ifdef yylex_init_extra
#define parser4_lex_init_extra_ALREADY_DEFINED
#else
#define yylex_init_extra parser4_lex_init_extra
#endif
#ifdef yylex_destroy
#define parser4_lex_destroy_ALREADY_DEFINED
#else
#define yylex_destroy parser4_lex_destroy
#endif
#ifdef yyget_debug
#define parser4_get_debug_ALREADY_DEFINED
#else
#define yyget_debug parser4_get_debug
#endif
#ifdef yyset_debug
#define parser4_set_debug_ALREADY_DEFINED
#else
#define yyset_debug parser4_set_debug
#endif
#ifdef yyget_extra
#define parser4_get_extra_ALREADY_DEFINED
#else
#define yyget_extra parser4_get_extra
#endif
#ifdef yyset_extra
#define parser4_set_extra_ALREADY_DEFINED
#else
#define yyset_extra parser4_set_extra
#endif
#ifdef yyget_in
#define parser4_get_in_ALREADY_DEFINED
#else
#define yyget_in parser4_get_in
#endif
#ifdef yyset_in
#define parser4_set_in_ALREADY_DEFINED
#else
#define yyset_in parser4_set_in
#endif
#ifdef yyget_out
#define parser4_get_out_ALREADY_DEFINED
#else
#define yyget_out parser4_get_out
#endif
#ifdef yyset_out
#define parser4_set_out_ALREADY_DEFINED
#else
#define yyset_out parser4_set_out
#endif
#ifdef yyget_leng
#define parser4_get_leng_ALREADY_DEFINED
#else
#define yyget_leng parser4_get_leng
#endif
#ifdef yyget_text
#define parser4_get_text_ALREADY_DEFINED
#else
#define yyget_text parser4_get_text
#endif
#ifdef yyget_lineno
#define parser4_get_lineno_ALREADY_DEFINED
#else
#define yyget_lineno parser4_get_lineno
#endif
#ifdef yyset_lineno
#define parser4_set_lineno_ALREADY_DEFINED
#else
#define yyset_lineno parser4_set_lineno
#endif
#ifdef yywrap
#define parser4_wrap_ALREADY_DEFINED
#else
#define yywrap parser4_wrap
#endif
/* %endif */
#ifdef yyalloc
#define parser4_alloc_ALREADY_DEFINED
#else
#define yyalloc parser4_alloc
#endif
#ifdef yyrealloc
#define parser4_realloc_ALREADY_DEFINED
#else
#define yyrealloc parser4_realloc
#endif
#ifdef yyfree
#define parser4_free_ALREADY_DEFINED
#else
#define yyfree parser4_free
#endif
/* %if-c-only */
#ifdef yytext
#define parser4_text_ALREADY_DEFINED
#else
#define yytext parser4_text
#endif
#ifdef yyleng
#define parser4_leng_ALREADY_DEFINED
#else
#define yyleng parser4_leng
#endif
#ifdef yyin
#define parser4_in_ALREADY_DEFINED
#else
#define yyin parser4_in
#endif
#ifdef yyout
#define parser4_out_ALREADY_DEFINED
#else
#define yyout parser4_out
#endif
#ifdef yy_flex_debug
#define parser4__flex_debug_ALREADY_DEFINED
#else
#define yy_flex_debug parser4__flex_debug
#endif
#ifdef yylineno
#define parser4_lineno_ALREADY_DEFINED
#else
#define yylineno parser4_lineno
#endif
/* %endif */
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
/* %if-c-only */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* %endif */
/* %if-tables-serialization */
/* %endif */
/* end standard C headers. */
/* %if-c-or-c++ */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#ifndef SIZE_MAX
#define SIZE_MAX (~(size_t)0)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
/* %endif */
/* begin standard C++ headers. */
/* %if-c++-only */
/* %endif */
/* TODO: this is always defined, so inline it */
#define yyconst const
#if defined(__GNUC__) && __GNUC__ >= 3
#define yynoreturn __attribute__((__noreturn__))
#else
#define yynoreturn
#endif
/* %not-for-header */
/* Returned upon end-of-file. */
#define YY_NULL 0
/* %ok-for-header */
/* %not-for-header */
/* Promotes a possibly negative, possibly signed char to an
* integer in range [0..255] for use as an array index.
*/
#define YY_SC_TO_UI(c) ((YY_CHAR) (c))
/* %ok-for-header */
/* %if-reentrant */
/* %endif */
/* %if-not-reentrant */
/* %endif */
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart( yyin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k.
* Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
* Ditto for the __ia64__ case accordingly.
*/
#define YY_BUF_SIZE 32768
#else
#define YY_BUF_SIZE 16384
#endif /* __ia64__ */
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
/* %if-not-reentrant */
extern int yyleng;
/* %endif */
/* %if-c-only */
/* %if-not-reentrant */
extern FILE *yyin, *yyout;
/* %endif */
/* %endif */
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
#define YY_LINENO_REWIND_TO(ptr)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
/* %if-c-only */
FILE *yy_input_file;
/* %endif */
/* %if-c++-only */
/* %endif */
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
int yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* %if-c-only Standard (non-C++) definition */
/* %not-for-header */
/* %if-not-reentrant */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = NULL; /**< Stack as an array. */
/* %endif */
/* %ok-for-header */
/* %endif */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* %if-c-only Standard (non-C++) definition */
/* %if-not-reentrant */
/* %not-for-header */
/* yy_hold_char holds the character lost when yytext is formed. */
static char yy_hold_char;
static int yy_n_chars; /* number of characters read into yy_ch_buf */
int yyleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = NULL;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow yywrap()'s to do buffer switches
* instead of setting up a fresh yyin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
/* %ok-for-header */
/* %endif */
void yyrestart ( FILE *input_file );
void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size );
void yy_delete_buffer ( YY_BUFFER_STATE b );
void yy_flush_buffer ( YY_BUFFER_STATE b );
void yypush_buffer_state ( YY_BUFFER_STATE new_buffer );
void yypop_buffer_state ( void );
static void yyensure_buffer_stack ( void );
static void yy_load_buffer_state ( void );
static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file );
#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER )
YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size );
YY_BUFFER_STATE yy_scan_string ( const char *yy_str );
YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len );
/* %endif */
void *yyalloc ( yy_size_t );
void *yyrealloc ( void *, yy_size_t );
void yyfree ( void * );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer( yyin, YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer( yyin, YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* %% [1.0] yytext/yyin/yyout/yy_state_type/yylineno etc. def's & init go here */
/* Begin user sect3 */
#define parser4_wrap() (/*CONSTCOND*/1)
#define YY_SKIP_YYWRAP
#define FLEX_DEBUG
typedef flex_uint8_t YY_CHAR;
FILE *yyin = NULL, *yyout = NULL;
typedef int yy_state_type;
extern int yylineno;
int yylineno = 1;
extern char *yytext;
#ifdef yytext_ptr
#undef yytext_ptr
#endif
#define yytext_ptr yytext
/* %% [1.5] DFA */
/* %if-c-only Standard (non-C++) definition */
static yy_state_type yy_get_previous_state ( void );
static yy_state_type yy_try_NUL_trans ( yy_state_type current_state );
static int yy_get_next_buffer ( void );
static void yynoreturn yy_fatal_error ( const char* msg );
/* %endif */
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
/* %% [2.0] code to fiddle yytext and yyleng for yymore() goes here \ */\
yyleng = (int) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
/* %% [3.0] code to copy yytext_ptr to yytext[] goes here, if %array \ */\
(yy_c_buf_p) = yy_cp;
/* %% [4.0] data tables for the DFA and the user's section 1 definitions go here */
#define YY_NUM_RULES 175
#define YY_END_OF_BUFFER 176
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static const flex_int16_t yy_accept[1468] =
{ 0,
168, 168, 0, 0, 0, 0, 0, 0, 0, 0,
176, 174, 10, 11, 174, 1, 168, 165, 168, 168,
174, 167, 166, 174, 174, 174, 174, 174, 161, 162,
174, 174, 174, 163, 164, 5, 5, 5, 174, 174,
174, 10, 11, 0, 0, 157, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
168, 168, 0, 167, 168, 3, 2, 6, 0, 168,
0, 0, 0, 0, 0, 0, 4, 0, 0, 9,
0, 158, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 160, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 2, 0,
0, 0, 0, 0, 0, 0, 8, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 159, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 67, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 173, 171, 0,
170, 169, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 137, 0, 136, 0, 0, 73, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 34,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 70, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 18, 0, 0, 0, 0, 172, 169, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 138,
0, 0, 140, 0, 0, 0, 0, 0, 0, 0,
0, 74, 0, 0, 0, 0, 0, 0, 59, 0,
0, 0, 0, 0, 91, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 37, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 58, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 62, 0, 38,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 88, 30, 0, 0, 35,
0, 0, 0, 0, 0, 0, 0, 0, 12, 145,
0, 142, 0, 141, 0, 0, 0, 101, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 32, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 61, 0, 0, 0,
0, 0, 0, 0, 0, 102, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 97, 0,
0, 0, 0, 0, 0, 0, 7, 0, 0, 143,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 83,
0, 0, 0, 0, 0, 0, 0, 0, 79, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 65, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 76, 0, 0, 0,
0, 0, 0, 0, 0, 64, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 95, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 107, 77,
0, 0, 0, 0, 82, 31, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 39, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 54, 0, 0, 0, 0, 0, 0,
0, 0, 0, 146, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 69, 0, 0, 0, 0, 0,
0, 0, 0, 0, 96, 0, 0, 0, 0, 0,
42, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 36,
0, 0, 0, 29, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 84, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 93, 0, 0, 0, 0, 0, 0, 0, 0,
120, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 66, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
23, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 125, 0, 0, 123, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 150, 0,
0, 0, 0, 0, 0, 94, 0, 0, 0, 0,
0, 0, 98, 80, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 92,
22, 0, 103, 0, 0, 0, 0, 0, 0, 0,
0, 129, 0, 0, 0, 0, 56, 0, 0, 0,
0, 0, 106, 33, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 53,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 60, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 100, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 154, 0, 57,
71, 0, 0, 0, 0, 0, 0, 0, 0, 0,
50, 0, 0, 0, 0, 0, 0, 0, 126, 0,
124, 0, 118, 117, 0, 46, 0, 21, 0, 0,
0, 0, 0, 139, 0, 0, 87, 0, 0, 0,
0, 0, 0, 0, 0, 0, 115, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 104, 15,
0, 40, 0, 0, 0, 0, 0, 128, 0, 0,
0, 0, 0, 0, 51, 0, 0, 99, 0, 0,
0, 0, 90, 0, 0, 0, 0, 0, 0, 63,
0, 148, 0, 147, 0, 153, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 14, 0, 0, 45,
0, 0, 0, 0, 156, 85, 27, 0, 0, 47,
116, 0, 0, 0, 151, 121, 0, 0, 0, 0,
0, 0, 0, 0, 25, 0, 0, 24, 0, 127,
0, 0, 0, 0, 0, 78, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 49,
0, 0, 0, 41, 0, 0, 0, 0, 0, 0,
0, 105, 0, 0, 0, 26, 0, 152, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 44,
0, 0, 20, 155, 55, 0, 149, 144, 28, 0,
0, 16, 0, 0, 133, 0, 0, 0, 0, 0,
0, 113, 0, 89, 0, 0, 0, 0, 0, 0,
0, 0, 68, 0, 0, 0, 0, 0, 0, 0,
0, 134, 13, 0, 0, 0, 0, 0, 122, 0,
0, 0, 0, 0, 0, 119, 0, 0, 0, 0,
0, 112, 0, 19, 0, 130, 0, 0, 0, 0,
0, 0, 0, 0, 111, 0, 0, 48, 0, 0,
43, 132, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 131, 0, 86,
0, 0, 0, 0, 0, 0, 109, 114, 52, 0,
0, 0, 0, 108, 0, 0, 135, 0, 0, 0,
0, 0, 75, 0, 0, 110, 0
} ;
static const YY_CHAR yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
1, 1, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 4, 5, 6, 7, 5, 5, 5, 5, 5,
5, 8, 9, 10, 11, 12, 13, 14, 14, 14,
14, 15, 14, 16, 14, 14, 14, 17, 5, 18,
5, 19, 20, 5, 21, 22, 23, 24, 25, 26,
5, 27, 5, 28, 5, 29, 5, 30, 31, 32,
5, 33, 34, 35, 36, 37, 38, 5, 39, 5,
40, 41, 42, 5, 43, 5, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
68, 69, 70, 5, 71, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5
} ;
static const YY_CHAR yy_meta[72] =
{ 0,
1, 1, 2, 3, 3, 4, 3, 3, 3, 3,
3, 3, 3, 5, 5, 5, 3, 3, 3, 3,
5, 5, 5, 5, 5, 5, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 5, 5, 5, 5, 5, 5, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3
} ;
static const flex_int16_t yy_base[1480] =
{ 0,
0, 70, 19, 29, 41, 49, 52, 58, 87, 95,
1830, 1831, 32, 1826, 141, 0, 201, 1831, 206, 88,
11, 213, 1831, 1808, 114, 25, 2, 6, 1831, 1831,
73, 11, 17, 1831, 1831, 1831, 104, 1814, 1769, 0,
1806, 107, 1821, 217, 247, 1831, 1765, 185, 1764, 1770,
93, 58, 1762, 91, 211, 195, 14, 273, 195, 1761,
181, 275, 207, 211, 76, 68, 188, 1770, 232, 219,
296, 284, 280, 1753, 204, 302, 322, 305, 1772, 0,
349, 357, 370, 377, 362, 1831, 0, 1831, 301, 342,
296, 325, 201, 346, 359, 224, 1831, 1769, 1808, 1831,
353, 1831, 390, 1797, 357, 1755, 1765, 369, 220, 1760,
362, 288, 364, 374, 221, 1803, 0, 441, 366, 1747,
1744, 1748, 1744, 1752, 360, 1748, 1737, 1738, 76, 1754,
1737, 1746, 1746, 365, 1737, 365, 1738, 1736, 357, 1782,
1786, 1728, 1779, 1721, 1744, 1741, 1741, 1735, 268, 1728,
1721, 1726, 1720, 371, 1731, 1724, 1715, 1714, 1728, 379,
1714, 384, 1730, 1707, 415, 387, 419, 1728, 1725, 1726,
1724, 390, 1706, 1708, 420, 1700, 1717, 1709, 0, 386,
439, 425, 396, 440, 453, 1708, 1831, 0, 1751, 460,
1698, 1701, 437, 452, 1709, 458, 1752, 466, 1751, 462,
1750, 1831, 506, 1749, 472, 1710, 1702, 1689, 1705, 1702,
1701, 1692, 448, 1741, 1735, 1701, 1680, 1688, 1683, 1697,
1693, 1681, 1693, 1693, 1684, 1668, 1672, 1685, 1687, 1684,
1676, 1666, 1684, 1831, 1679, 1682, 1663, 1662, 1712, 1661,
1671, 1674, 496, 1670, 1658, 1669, 1705, 1652, 1708, 1645,
1660, 489, 1650, 1666, 1647, 1646, 1652, 1643, 1642, 1649,
1697, 1655, 1654, 1648, 77, 1655, 1650, 1642, 1632, 1647,
1646, 1641, 1645, 1626, 1642, 1628, 1634, 1641, 1629, 492,
1622, 1636, 1677, 1638, 485, 1629, 477, 1831, 1831, 485,
1831, 1831, 1616, 0, 456, 473, 1618, 520, 490, 1672,
1625, 484, 1831, 1670, 1831, 1664, 548, 1831, 474, 1606,
1615, 1661, 1607, 1613, 1663, 1620, 1615, 1618, 479, 1831,
1616, 1658, 1613, 1610, 528, 1616, 1654, 1648, 1603, 1598,
1595, 1644, 1603, 1592, 1608, 1640, 1588, 554, 1602, 1587,
1600, 1587, 1597, 1592, 1599, 1594, 1590, 496, 1588, 1591,
1586, 1582, 1630, 488, 1624, 1831, 1623, 1575, 1574, 1573,
1566, 1568, 1572, 1561, 1574, 518, 1619, 1574, 1571, 1831,
1574, 1563, 1563, 1575, 518, 1550, 1551, 1572, 529, 1554,
1603, 1550, 1564, 1563, 1549, 1561, 1560, 1559, 1558, 380,
1599, 1598, 1831, 1542, 1541, 572, 1554, 1831, 1831, 1553,
0, 1542, 1534, 525, 1539, 1590, 1589, 1547, 1587, 1831,
1535, 1585, 1831, 556, 603, 542, 1584, 1528, 1539, 1535,
1523, 1831, 1528, 1534, 1537, 1536, 1523, 1522, 1831, 1524,
1521, 538, 1519, 1521, 1831, 1529, 1526, 1511, 1524, 1519,
578, 1526, 1514, 1507, 1556, 1831, 1505, 1521, 1553, 1516,
1513, 1514, 1516, 1548, 1501, 1496, 1495, 1544, 1490, 1505,
1483, 1490, 1495, 1543, 1831, 1490, 1486, 1484, 1493, 1487,
1494, 1478, 1478, 1488, 1491, 1480, 1475, 1831, 1530, 1831,
1474, 1485, 1470, 1475, 1484, 1478, 1472, 1481, 1521, 1515,
1479, 1462, 1462, 1457, 1477, 1452, 1458, 1457, 1465, 1469,
1452, 1508, 1450, 1464, 1453, 1831, 1831, 1453, 1451, 1831,
1462, 1496, 1458, 0, 1442, 1459, 1497, 1447, 1831, 1831,
1444, 1831, 1450, 1831, 551, 569, 595, 1831, 1447, 1446,
1434, 1485, 1432, 1483, 1430, 1429, 1436, 1429, 1441, 1440,
1440, 1422, 1427, 1468, 1435, 1427, 1470, 1416, 1432, 1431,
1831, 1416, 1413, 1469, 1426, 1418, 1424, 1415, 1423, 1408,
1424, 1406, 1420, 520, 1402, 1396, 1401, 1416, 1413, 1414,
1411, 1452, 1409, 1831, 1395, 1397, 1406, 1404, 1441, 1440,
1393, 562, 1402, 1385, 1386, 1383, 1831, 1397, 1376, 1395,
1387, 1430, 1384, 1391, 1427, 1831, 1374, 1388, 1372, 1386,
1389, 1370, 1420, 1419, 1418, 1365, 1416, 1415, 1831, 14,
1377, 1377, 1375, 1358, 1363, 1365, 1831, 1371, 1361, 1831,
1406, 1354, 1409, 568, 501, 1352, 1350, 1357, 1400, 562,
1404, 544, 1398, 1397, 1396, 1350, 1340, 1393, 1346, 1354,
1355, 1389, 1352, 1346, 1333, 1341, 1384, 1388, 1345, 1344,
1831, 1345, 1338, 1327, 1340, 1343, 1338, 1339, 1336, 1335,
1331, 1337, 1332, 1373, 1372, 1322, 1312, 552, 1369, 1831,
1368, 1317, 1309, 1310, 1359, 1322, 1309, 1320, 1831, 1308,
1317, 1316, 1316, 1356, 1299, 1308, 1313, 1290, 1294, 1345,
1309, 1291, 1301, 1341, 1340, 1339, 1286, 1337, 1301, 580,
582, 1278, 1288, 579, 1831, 1338, 1284, 1294, 1294, 1277,
1282, 1286, 1276, 1288, 1291, 1328, 1831, 1322, 578, 1284,
15, 20, 86, 175, 242, 1831, 274, 374, 536, 561,
559, 578, 575, 576, 575, 574, 589, 585, 640, 605,
595, 611, 601, 1831, 611, 611, 604, 615, 613, 656,
600, 602, 617, 604, 662, 621, 607, 610, 1831, 1831,
620, 625, 630, 618, 1831, 1831, 632, 619, 613, 618,
636, 623, 671, 624, 674, 625, 681, 1831, 628, 632,
627, 685, 640, 630, 631, 627, 640, 651, 635, 653,
648, 649, 651, 644, 646, 647, 647, 649, 664, 703,
662, 667, 644, 1831, 669, 659, 704, 664, 654, 669,
670, 657, 671, 1831, 690, 698, 667, 662, 715, 680,
684, 723, 673, 668, 680, 675, 676, 672, 681, 676,
732, 691, 692, 683, 1831, 685, 696, 681, 697, 692,
737, 706, 690, 691, 1831, 707, 710, 693, 750, 695,
1831, 712, 715, 695, 713, 751, 711, 707, 702, 720,
719, 720, 706, 721, 713, 720, 710, 728, 713, 1831,
721, 727, 772, 1831, 723, 728, 770, 723, 735, 729,
734, 732, 730, 732, 742, 785, 731, 731, 788, 734,
746, 1831, 734, 742, 740, 745, 757, 741, 746, 756,
757, 762, 801, 760, 776, 781, 763, 761, 757, 809,
754, 1831, 754, 774, 763, 768, 775, 816, 817, 766,
1831, 814, 763, 766, 765, 785, 782, 787, 788, 774,
782, 791, 771, 788, 795, 835, 1831, 836, 837, 790,
800, 802, 791, 787, 794, 803, 846, 795, 793, 795,
812, 851, 803, 802, 808, 806, 804, 857, 858, 854,
1831, 818, 811, 802, 821, 809, 819, 816, 821, 817,
830, 830, 1831, 814, 815, 1831, 816, 874, 815, 834,
835, 832, 818, 839, 838, 822, 827, 845, 1831, 835,
868, 859, 889, 831, 853, 1831, 836, 838, 855, 853,
845, 849, 1831, 1831, 859, 859, 895, 844, 897, 846,
904, 849, 860, 852, 858, 854, 873, 874, 875, 1831,
1831, 874, 1831, 859, 861, 880, 870, 863, 875, 917,
883, 1831, 875, 925, 868, 927, 1831, 928, 872, 878,
885, 927, 1831, 1831, 877, 879, 893, 898, 881, 938,
897, 898, 899, 937, 891, 896, 945, 895, 947, 1831,
896, 949, 950, 892, 952, 913, 954, 898, 910, 915,
901, 931, 960, 1831, 919, 912, 963, 912, 927, 914,
910, 926, 931, 918, 914, 972, 927, 932, 1831, 933,
926, 935, 936, 933, 923, 926, 926, 931, 984, 985,
930, 988, 984, 927, 942, 935, 994, 1831, 949, 1831,
1831, 954, 946, 956, 942, 943, 1002, 948, 958, 1006,
1831, 956, 956, 958, 960, 1011, 954, 957, 1831, 976,
1831, 960, 1831, 1831, 974, 1831, 968, 1831, 1018, 969,
1020, 1021, 1003, 1831, 1023, 982, 1831, 970, 978, 972,
971, 974, 974, 975, 982, 972, 1831, 994, 980, 981,
996, 996, 999, 999, 996, 1038, 1002, 995, 1831, 1831,
1005, 1831, 1002, 1007, 1008, 1005, 1047, 1831, 998, 999,
999, 1005, 1004, 1015, 1831, 1054, 1003, 1831, 1004, 1004,
1006, 1012, 1831, 1014, 1066, 1017, 1020, 1069, 1032, 1831,
1029, 1831, 1026, 1831, 1049, 1831, 1074, 1075, 1076, 1035,
1021, 1079, 1080, 1035, 1025, 1030, 1084, 1085, 1081, 1046,
1042, 1084, 1034, 1039, 1037, 1094, 1052, 1096, 1056, 1098,
1061, 1051, 1045, 1061, 1061, 1105, 1049, 1066, 1065, 1049,
1105, 1106, 1055, 1108, 1073, 1074, 1831, 1074, 1061, 1831,
1072, 1119, 1079, 1092, 1831, 1831, 1831, 1066, 1123, 1831,
1831, 1072, 1070, 1084, 1831, 1831, 1074, 1123, 1068, 1073,
1131, 1081, 1091, 1092, 1831, 1135, 1090, 1831, 1137, 1831,
1082, 1097, 1085, 1100, 1104, 1831, 1138, 1106, 1099, 1108,
1090, 1097, 1151, 1112, 1111, 1154, 1155, 1156, 1107, 1831,
1158, 1159, 1160, 1831, 1110, 1110, 1163, 1109, 1108, 1166,
1121, 1831, 1163, 1116, 1113, 1831, 1127, 1831, 1130, 1173,
1128, 1175, 1136, 1119, 1121, 1118, 1134, 1135, 1144, 1831,
1134, 1184, 1831, 1831, 1831, 1180, 1831, 1831, 1831, 1181,
1138, 1831, 1136, 1143, 1831, 1140, 1145, 1143, 1193, 1194,
1139, 1831, 1154, 1831, 1155, 1145, 1157, 1200, 1144, 1152,
1153, 1166, 1831, 1165, 1153, 1207, 1168, 1159, 1168, 1170,
1174, 1831, 1831, 1213, 1158, 1215, 1175, 1217, 1831, 1213,
1177, 1178, 1165, 1160, 1181, 1831, 1182, 1183, 1226, 1185,
1188, 1831, 1229, 1831, 1192, 1831, 1174, 1232, 1233, 1178,
1195, 1181, 1181, 1183, 1831, 1188, 1198, 1831, 1184, 1196,
1831, 1831, 1201, 1195, 1199, 1190, 1242, 1191, 1199, 1208,
1201, 1196, 1211, 1202, 1209, 1196, 1211, 1216, 1259, 1218,
1261, 1206, 1222, 1213, 1227, 1223, 1216, 1831, 1268, 1831,
1269, 1270, 1227, 1226, 1227, 1217, 1831, 1831, 1831, 1275,
1219, 1235, 1278, 1831, 1274, 1225, 1831, 1224, 1226, 1237,
1284, 1235, 1831, 1244, 1287, 1831, 1831, 1293, 1298, 1303,
1308, 1313, 1318, 1323, 1326, 1300, 1305, 1307, 1320
} ;
static const flex_int16_t yy_def[1480] =
{ 0,
1468, 1468, 1469, 1469, 1468, 1468, 1468, 1468, 1468, 1468,
1467, 1467, 1467, 1467, 1467, 1470, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1471,
1467, 1467, 1467, 1472, 15, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 1473, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1470,
1467, 1467, 1467, 1467, 1467, 1467, 1474, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1471, 1467,
1472, 1467, 1467, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 1475, 45, 1473, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1474, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1476, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
1475, 1467, 1473, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1477, 45, 45, 45, 45, 45, 45,
45, 45, 1467, 45, 1467, 45, 1473, 1467, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 1467, 45, 45, 45, 45, 1467, 1467, 1467,
1478, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 1467, 45, 1473, 45, 45, 45, 45, 45,
45, 1467, 45, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 1467, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 1467, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 1467, 1467, 45, 45, 1467,
45, 45, 1467, 1479, 45, 45, 45, 45, 1467, 1467,
45, 1467, 45, 1467, 45, 45, 45, 1467, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 1467,
45, 45, 45, 45, 1467, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 1467, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 1467, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 1467, 45, 45, 45, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 1467, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 1467, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
1467, 45, 1467, 45, 45, 45, 45, 45, 45, 45,
45, 1467, 45, 45, 45, 45, 1467, 45, 45, 45,
45, 45, 1467, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 1467, 45, 1467,
1467, 45, 45, 45, 45, 45, 45, 45, 45, 45,
1467, 45, 45, 45, 45, 45, 45, 45, 1467, 45,
1467, 45, 1467, 1467, 45, 1467, 45, 1467, 45, 45,
45, 45, 45, 1467, 45, 45, 1467, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 1467, 1467,
45, 1467, 45, 45, 45, 45, 45, 1467, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 1467, 45, 45,
45, 45, 1467, 45, 45, 45, 45, 45, 45, 1467,
45, 1467, 45, 1467, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 1467, 45, 45, 1467,
45, 45, 45, 45, 1467, 1467, 1467, 45, 45, 1467,
1467, 45, 45, 45, 1467, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 1467, 45, 1467,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 1467, 45, 45, 45, 1467, 45, 1467, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 1467,
45, 45, 1467, 1467, 1467, 45, 1467, 1467, 1467, 45,
45, 1467, 45, 45, 1467, 45, 45, 45, 45, 45,
45, 1467, 45, 1467, 45, 45, 45, 45, 45, 45,
45, 45, 1467, 45, 45, 45, 45, 45, 45, 45,
45, 1467, 1467, 45, 45, 45, 45, 45, 1467, 45,
45, 45, 45, 45, 45, 1467, 45, 45, 45, 45,
45, 1467, 45, 1467, 45, 1467, 45, 45, 45, 45,
45, 45, 45, 45, 1467, 45, 45, 1467, 45, 45,
1467, 1467, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 1467, 45, 1467,
45, 45, 45, 45, 45, 45, 1467, 1467, 1467, 45,
45, 45, 45, 1467, 45, 45, 1467, 45, 45, 45,
45, 45, 1467, 45, 45, 1467, 0, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467
} ;
static const flex_int16_t yy_nxt[1903] =
{ 0,
1467, 13, 14, 13, 1467, 15, 16, 1467, 17, 18,
19, 20, 21, 22, 22, 22, 23, 24, 86, 705,
37, 14, 37, 87, 25, 26, 38, 1467, 706, 27,
37, 14, 37, 42, 28, 42, 38, 92, 93, 29,
115, 30, 13, 14, 13, 91, 92, 25, 31, 93,
13, 14, 13, 13, 14, 13, 32, 40, 818, 13,
14, 13, 33, 40, 115, 92, 93, 819, 91, 34,
35, 13, 14, 13, 95, 15, 16, 96, 17, 18,
19, 20, 21, 22, 22, 22, 23, 24, 13, 14,
13, 109, 39, 91, 25, 26, 13, 14, 13, 27,
39, 85, 85, 85, 28, 42, 41, 42, 42, 29,
42, 30, 83, 108, 41, 111, 94, 25, 31, 109,
217, 218, 89, 137, 89, 139, 32, 90, 90, 90,
138, 374, 33, 140, 375, 83, 108, 820, 111, 34,
35, 44, 44, 44, 45, 45, 46, 45, 45, 45,
45, 45, 45, 45, 45, 47, 45, 45, 45, 45,
45, 48, 45, 49, 50, 45, 51, 45, 52, 53,
54, 45, 45, 45, 45, 55, 56, 45, 57, 45,
45, 58, 45, 45, 59, 60, 61, 62, 63, 64,
65, 66, 67, 52, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 57, 45, 45, 45,
45, 45, 81, 105, 82, 82, 82, 81, 114, 84,
84, 84, 102, 105, 81, 83, 84, 84, 84, 821,
83, 108, 123, 112, 141, 124, 182, 83, 125, 105,
126, 114, 127, 113, 142, 200, 143, 164, 83, 119,
194, 165, 133, 83, 108, 120, 112, 103, 121, 182,
83, 45, 149, 134, 182, 136, 150, 45, 200, 45,
45, 113, 45, 135, 45, 45, 45, 194, 117, 145,
146, 45, 45, 147, 45, 45, 151, 185, 822, 148,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 90, 90, 90, 45, 128, 197,
111, 45, 129, 160, 180, 130, 131, 161, 114, 45,
242, 823, 155, 45, 243, 45, 118, 162, 132, 152,
156, 153, 157, 154, 112, 166, 197, 158, 159, 167,
180, 175, 168, 181, 113, 90, 90, 90, 102, 169,
170, 176, 85, 85, 85, 171, 177, 172, 81, 173,
82, 82, 82, 83, 180, 85, 85, 85, 89, 181,
89, 83, 113, 90, 90, 90, 83, 181, 81, 174,
84, 84, 84, 103, 190, 101, 83, 193, 196, 198,
183, 83, 101, 190, 83, 199, 211, 196, 223, 83,
224, 230, 226, 184, 231, 212, 213, 824, 232, 287,
204, 197, 190, 193, 83, 262, 196, 198, 227, 287,
101, 205, 199, 504, 101, 196, 505, 248, 101, 254,
255, 257, 271, 272, 258, 259, 101, 287, 280, 289,
101, 199, 101, 188, 203, 203, 203, 290, 263, 264,
265, 203, 203, 203, 203, 203, 203, 288, 288, 266,
299, 267, 289, 268, 269, 273, 270, 289, 283, 274,
296, 300, 302, 275, 203, 203, 203, 203, 203, 203,
304, 306, 296, 288, 291, 395, 317, 303, 299, 359,
292, 398, 390, 296, 318, 302, 348, 402, 300, 398,
319, 404, 404, 304, 409, 309, 412, 403, 306, 307,
307, 307, 426, 478, 398, 719, 307, 307, 307, 307,
307, 307, 399, 360, 406, 407, 466, 409, 432, 427,
404, 416, 433, 408, 412, 396, 467, 361, 719, 307,
307, 307, 307, 307, 307, 459, 460, 349, 517, 446,
350, 415, 415, 415, 447, 661, 662, 679, 415, 415,
415, 415, 415, 415, 487, 517, 492, 510, 488, 479,
493, 624, 511, 551, 541, 525, 517, 526, 552, 727,
728, 415, 415, 415, 415, 415, 415, 542, 825, 543,
620, 625, 718, 527, 680, 626, 763, 724, 624, 764,
448, 816, 525, 725, 526, 449, 45, 45, 45, 826,
827, 828, 829, 45, 45, 45, 45, 45, 45, 625,
718, 794, 796, 797, 830, 802, 831, 832, 795, 816,
798, 803, 833, 834, 799, 835, 45, 45, 45, 45,
45, 45, 836, 837, 838, 839, 840, 841, 842, 843,
844, 845, 847, 848, 849, 850, 846, 851, 852, 853,
854, 855, 856, 857, 858, 859, 860, 861, 862, 863,
865, 866, 867, 864, 868, 869, 870, 871, 872, 873,
874, 875, 876, 877, 878, 879, 880, 881, 882, 883,
884, 885, 886, 887, 888, 889, 890, 891, 892, 893,
894, 895, 896, 897, 898, 899, 900, 901, 902, 903,
904, 905, 906, 907, 908, 909, 910, 911, 912, 913,
914, 915, 916, 917, 918, 919, 920, 921, 922, 923,
924, 925, 926, 927, 928, 906, 929, 930, 905, 931,
932, 933, 934, 935, 936, 937, 939, 940, 941, 942,
943, 944, 945, 946, 947, 948, 949, 950, 951, 952,
953, 954, 955, 956, 958, 959, 960, 961, 962, 963,
964, 965, 966, 967, 957, 968, 969, 970, 971, 972,
973, 974, 975, 976, 977, 978, 979, 980, 981, 982,
983, 984, 985, 986, 987, 988, 989, 990, 991, 993,
992, 938, 994, 995, 996, 997, 998, 999, 1000, 1001,
1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011,
1012, 1013, 1014, 1015, 1016, 1017, 991, 992, 1018, 1019,
1020, 1021, 1023, 1025, 1026, 1027, 1022, 1028, 1029, 1030,
1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040,
1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050,
1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060,
1061, 1062, 1063, 1064, 1024, 1065, 1066, 1067, 1068, 1069,
1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079,
1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089,
1090, 1091, 1092, 1093, 1094, 1072, 1095, 1096, 1097, 1098,
1099, 1073, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107,
1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117,
1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1127, 1128,
1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138,
1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1149,
1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159,
1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169,
1170, 1171, 1143, 1172, 1173, 1174, 1175, 1177, 1126, 1178,
1179, 1180, 1181, 1182, 1176, 1183, 1184, 1185, 1186, 1187,
1148, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196,
1197, 1198, 1199, 1200, 1201, 1202, 1204, 1205, 1206, 1207,
1203, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216,
1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226,
1205, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235,
1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245,
1246, 1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255,
1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265,
1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275,
1277, 1278, 1279, 1280, 1281, 1254, 1282, 1283, 1284, 1285,
1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295,
1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305,
1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315,
1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325,
1326, 1327, 1328, 1329, 1302, 1276, 1330, 1331, 1332, 1333,
1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343,
1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353,
1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363,
1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373,
1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383,
1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393,
1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403,
1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1413,
1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423,
1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433,
1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443,
1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453,
1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463,
1464, 1465, 1466, 12, 12, 12, 12, 12, 36, 36,
36, 36, 36, 80, 294, 80, 80, 80, 99, 401,
99, 514, 99, 101, 101, 101, 101, 101, 116, 116,
116, 116, 116, 179, 101, 179, 179, 179, 201, 201,
201, 817, 815, 814, 813, 812, 811, 810, 809, 808,
807, 806, 805, 804, 801, 800, 793, 792, 791, 790,
789, 788, 787, 786, 785, 784, 783, 782, 781, 780,
779, 778, 777, 776, 775, 774, 773, 772, 771, 770,
769, 768, 767, 766, 765, 762, 761, 760, 759, 758,
757, 756, 755, 754, 753, 752, 751, 750, 749, 748,
747, 746, 745, 744, 743, 742, 741, 740, 739, 738,
737, 736, 735, 734, 733, 732, 731, 730, 729, 726,
723, 722, 721, 720, 717, 716, 715, 714, 713, 712,
711, 710, 709, 708, 707, 704, 703, 702, 701, 700,
699, 698, 697, 696, 695, 694, 693, 692, 691, 690,
689, 688, 687, 686, 685, 684, 683, 682, 681, 678,
677, 676, 675, 674, 673, 672, 671, 670, 669, 668,
667, 666, 665, 664, 663, 660, 659, 658, 657, 656,
655, 654, 653, 652, 651, 650, 649, 648, 647, 646,
645, 644, 643, 642, 641, 640, 639, 638, 637, 636,
635, 634, 633, 632, 631, 630, 629, 628, 627, 623,
622, 621, 620, 619, 618, 617, 616, 615, 614, 613,
612, 611, 610, 609, 608, 607, 606, 605, 604, 603,
602, 601, 600, 599, 598, 597, 596, 595, 594, 593,
592, 591, 590, 589, 588, 587, 586, 585, 584, 583,
582, 581, 580, 579, 578, 577, 576, 575, 574, 573,
572, 571, 570, 569, 568, 567, 566, 565, 564, 563,
562, 561, 560, 559, 558, 557, 556, 555, 554, 553,
550, 549, 548, 547, 546, 545, 544, 540, 539, 538,
537, 536, 535, 534, 533, 532, 531, 530, 529, 528,
524, 523, 522, 521, 520, 519, 518, 516, 515, 513,
512, 509, 508, 507, 506, 503, 502, 501, 500, 499,
498, 497, 496, 495, 494, 491, 490, 489, 486, 485,
484, 483, 482, 481, 480, 477, 476, 475, 474, 473,
472, 471, 470, 469, 468, 465, 464, 463, 462, 461,
458, 457, 456, 455, 454, 453, 452, 451, 450, 445,
444, 443, 442, 441, 440, 439, 438, 437, 436, 435,
434, 431, 430, 429, 428, 425, 424, 423, 422, 421,
420, 419, 418, 417, 414, 413, 411, 410, 405, 400,
397, 394, 393, 392, 391, 389, 388, 387, 386, 385,
384, 383, 382, 381, 380, 379, 378, 377, 376, 373,
372, 371, 370, 369, 368, 367, 366, 365, 364, 363,
362, 358, 357, 356, 355, 354, 353, 352, 351, 347,
346, 345, 344, 343, 342, 341, 340, 339, 338, 337,
336, 335, 334, 333, 332, 331, 330, 329, 328, 327,
326, 325, 324, 323, 322, 321, 320, 316, 315, 314,
313, 312, 311, 310, 308, 202, 305, 303, 301, 298,
297, 295, 293, 286, 285, 284, 282, 281, 279, 278,
277, 276, 261, 260, 256, 253, 252, 251, 250, 249,
247, 246, 245, 244, 241, 240, 239, 238, 237, 236,
235, 234, 233, 229, 228, 225, 222, 221, 220, 219,
216, 215, 214, 210, 209, 208, 207, 206, 202, 195,
192, 191, 189, 187, 186, 178, 163, 144, 122, 110,
107, 106, 104, 43, 100, 98, 97, 88, 43, 1467,
11, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467
} ;
static const flex_int16_t yy_chk[1903] =
{ 0,
0, 1, 1, 1, 0, 1, 1, 0, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 21, 610,
3, 3, 3, 21, 1, 1, 3, 0, 610, 1,
4, 4, 4, 13, 1, 13, 4, 27, 28, 1,
57, 1, 5, 5, 5, 26, 32, 1, 1, 33,
6, 6, 6, 7, 7, 7, 1, 7, 721, 8,
8, 8, 1, 8, 57, 27, 28, 722, 26, 1,
1, 2, 2, 2, 32, 2, 2, 33, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 9, 9,
9, 52, 5, 31, 2, 2, 10, 10, 10, 2,
6, 20, 20, 20, 2, 37, 9, 37, 42, 2,
42, 2, 20, 51, 10, 54, 31, 2, 2, 52,
129, 129, 25, 65, 25, 66, 2, 25, 25, 25,
65, 265, 2, 66, 265, 20, 51, 723, 54, 2,
2, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 17, 48, 17, 17, 17, 19, 56, 19,
19, 19, 44, 59, 22, 17, 22, 22, 22, 724,
19, 64, 61, 55, 67, 61, 93, 22, 61, 48,
61, 56, 61, 55, 67, 115, 67, 75, 17, 59,
109, 75, 63, 19, 64, 59, 55, 44, 59, 96,
22, 45, 70, 63, 93, 64, 70, 45, 115, 45,
45, 55, 45, 63, 45, 45, 45, 109, 58, 69,
69, 45, 45, 69, 45, 58, 70, 96, 725, 69,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
45, 45, 45, 58, 89, 89, 89, 58, 62, 112,
71, 58, 62, 73, 91, 62, 62, 73, 78, 58,
149, 727, 72, 58, 149, 58, 58, 73, 62, 71,
72, 71, 72, 71, 77, 76, 112, 72, 72, 76,
91, 78, 76, 92, 77, 90, 90, 90, 101, 76,
76, 78, 81, 81, 81, 76, 78, 77, 82, 77,
82, 82, 82, 81, 94, 85, 85, 85, 83, 92,
83, 82, 77, 83, 83, 83, 85, 95, 84, 77,
84, 84, 84, 101, 105, 103, 81, 108, 111, 113,
94, 84, 103, 119, 82, 114, 125, 154, 134, 85,
134, 139, 136, 95, 139, 125, 125, 728, 139, 180,
119, 172, 105, 108, 84, 165, 111, 113, 136, 183,
103, 119, 114, 390, 103, 154, 390, 154, 103, 160,
160, 162, 166, 166, 162, 162, 103, 180, 172, 182,
103, 175, 103, 103, 118, 118, 118, 183, 165, 165,
165, 118, 118, 118, 118, 118, 118, 181, 184, 165,
193, 165, 182, 165, 165, 167, 165, 185, 175, 167,
190, 194, 196, 167, 118, 118, 118, 118, 118, 118,
198, 200, 205, 181, 184, 285, 213, 280, 193, 252,
185, 287, 280, 190, 213, 196, 243, 295, 194, 290,
213, 296, 309, 198, 299, 205, 302, 295, 200, 203,
203, 203, 319, 366, 287, 625, 203, 203, 203, 203,
203, 203, 290, 252, 298, 298, 354, 299, 325, 319,
296, 309, 325, 298, 302, 285, 354, 252, 625, 203,
203, 203, 203, 203, 203, 348, 348, 243, 404, 338,
243, 307, 307, 307, 338, 564, 564, 582, 307, 307,
307, 307, 307, 307, 375, 416, 379, 396, 375, 366,
379, 525, 396, 441, 432, 414, 404, 414, 441, 632,
632, 307, 307, 307, 307, 307, 307, 432, 729, 432,
527, 526, 624, 416, 582, 527, 668, 630, 525, 668,
338, 719, 414, 630, 414, 338, 415, 415, 415, 730,
731, 732, 733, 415, 415, 415, 415, 415, 415, 526,
624, 700, 701, 701, 734, 704, 735, 736, 700, 719,
701, 704, 737, 738, 701, 739, 415, 415, 415, 415,
415, 415, 740, 741, 742, 743, 745, 746, 747, 748,
749, 750, 751, 752, 753, 754, 750, 755, 756, 757,
758, 761, 762, 763, 764, 767, 768, 769, 770, 771,
772, 773, 774, 771, 775, 776, 777, 779, 780, 781,
782, 783, 784, 785, 786, 787, 788, 789, 790, 791,
792, 793, 794, 795, 796, 797, 798, 799, 800, 801,
802, 803, 805, 806, 807, 808, 809, 810, 811, 812,
813, 815, 816, 817, 818, 819, 820, 821, 822, 823,
824, 825, 826, 827, 828, 829, 830, 831, 832, 833,
834, 836, 837, 838, 839, 816, 840, 841, 815, 842,
843, 844, 846, 847, 848, 849, 850, 852, 853, 854,
855, 856, 857, 858, 859, 860, 861, 862, 863, 864,
865, 866, 867, 868, 869, 871, 872, 873, 875, 876,
877, 878, 879, 880, 868, 881, 882, 883, 884, 885,
886, 887, 888, 889, 890, 891, 893, 894, 895, 896,
897, 898, 899, 900, 901, 902, 903, 904, 905, 907,
906, 849, 908, 909, 910, 911, 913, 914, 915, 916,
917, 918, 919, 920, 922, 923, 924, 925, 926, 927,
928, 929, 930, 931, 932, 933, 905, 906, 934, 935,
936, 938, 939, 940, 941, 942, 938, 943, 944, 945,
946, 947, 948, 949, 950, 951, 952, 953, 954, 955,
956, 957, 958, 959, 960, 962, 963, 964, 965, 966,
967, 968, 969, 970, 971, 972, 974, 975, 977, 978,
979, 980, 981, 982, 939, 983, 984, 985, 986, 987,
988, 990, 991, 992, 993, 994, 995, 997, 998, 999,
1000, 1001, 1002, 1005, 1006, 1007, 1008, 1009, 1010, 1011,
1012, 1013, 1014, 1015, 1016, 991, 1017, 1018, 1019, 1022,
1024, 992, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1033,
1034, 1035, 1036, 1038, 1039, 1040, 1041, 1042, 1045, 1046,
1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056,
1057, 1058, 1059, 1061, 1062, 1063, 1064, 1065, 1066, 1067,
1068, 1069, 1070, 1071, 1072, 1073, 1075, 1076, 1077, 1078,
1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088,
1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099,
1100, 1101, 1072, 1102, 1103, 1104, 1105, 1106, 1054, 1107,
1109, 1112, 1113, 1114, 1105, 1115, 1116, 1117, 1118, 1119,
1077, 1120, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1130,
1132, 1135, 1137, 1139, 1140, 1141, 1142, 1143, 1145, 1146,
1141, 1148, 1149, 1150, 1151, 1152, 1153, 1154, 1155, 1156,
1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167,
1143, 1168, 1171, 1173, 1174, 1175, 1176, 1177, 1179, 1180,
1181, 1182, 1183, 1184, 1186, 1187, 1189, 1190, 1191, 1192,
1194, 1195, 1196, 1197, 1198, 1199, 1201, 1203, 1205, 1207,
1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217,
1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1225, 1226,
1227, 1228, 1229, 1230, 1231, 1205, 1232, 1233, 1234, 1235,
1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245,
1246, 1248, 1249, 1251, 1252, 1253, 1254, 1258, 1259, 1262,
1263, 1264, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274,
1276, 1277, 1279, 1281, 1282, 1283, 1284, 1285, 1287, 1288,
1289, 1290, 1291, 1292, 1254, 1226, 1293, 1294, 1295, 1296,
1297, 1298, 1299, 1301, 1302, 1303, 1305, 1306, 1307, 1308,
1309, 1310, 1311, 1313, 1314, 1315, 1317, 1319, 1320, 1321,
1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1331, 1332,
1336, 1340, 1341, 1343, 1344, 1346, 1347, 1348, 1349, 1350,
1351, 1353, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362,
1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1374, 1375,
1376, 1377, 1378, 1380, 1381, 1382, 1383, 1384, 1385, 1387,
1388, 1389, 1390, 1391, 1393, 1395, 1397, 1398, 1399, 1400,
1401, 1402, 1403, 1404, 1406, 1407, 1409, 1410, 1413, 1414,
1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424,
1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434,
1435, 1436, 1437, 1439, 1441, 1442, 1443, 1444, 1445, 1446,
1450, 1451, 1452, 1453, 1455, 1456, 1458, 1459, 1460, 1461,
1462, 1464, 1465, 1468, 1468, 1468, 1468, 1468, 1469, 1469,
1469, 1469, 1469, 1470, 1476, 1470, 1470, 1470, 1471, 1477,
1471, 1478, 1471, 1472, 1472, 1472, 1472, 1472, 1473, 1473,
1473, 1473, 1473, 1474, 1479, 1474, 1474, 1474, 1475, 1475,
1475, 720, 718, 716, 715, 714, 713, 712, 711, 710,
709, 708, 707, 706, 703, 702, 699, 698, 697, 696,
695, 694, 693, 692, 691, 690, 689, 688, 687, 686,
685, 684, 683, 682, 681, 680, 678, 677, 676, 675,
674, 673, 672, 671, 669, 667, 666, 665, 664, 663,
662, 661, 660, 659, 658, 657, 656, 655, 654, 653,
652, 650, 649, 648, 647, 646, 645, 644, 643, 642,
641, 640, 639, 638, 637, 636, 635, 634, 633, 631,
629, 628, 627, 626, 623, 622, 621, 619, 618, 616,
615, 614, 613, 612, 611, 608, 607, 606, 605, 604,
603, 602, 601, 600, 599, 598, 597, 595, 594, 593,
592, 591, 590, 589, 588, 586, 585, 584, 583, 581,
580, 579, 578, 577, 576, 575, 573, 572, 571, 570,
569, 568, 567, 566, 565, 563, 562, 561, 560, 559,
558, 557, 556, 555, 554, 553, 552, 550, 549, 548,
547, 546, 545, 544, 543, 542, 541, 540, 539, 538,
537, 536, 535, 534, 533, 532, 531, 530, 529, 523,
521, 518, 517, 516, 515, 513, 512, 511, 509, 508,
505, 504, 503, 502, 501, 500, 499, 498, 497, 496,
495, 494, 493, 492, 491, 490, 489, 488, 487, 486,
485, 484, 483, 482, 481, 479, 477, 476, 475, 474,
473, 472, 471, 470, 469, 468, 467, 466, 464, 463,
462, 461, 460, 459, 458, 457, 456, 455, 454, 453,
452, 451, 450, 449, 448, 447, 445, 444, 443, 442,
440, 439, 438, 437, 436, 434, 433, 431, 430, 428,
427, 426, 425, 424, 423, 421, 420, 419, 418, 417,
412, 411, 409, 408, 407, 406, 405, 403, 402, 400,
397, 395, 394, 392, 391, 389, 388, 387, 386, 385,
384, 383, 382, 381, 380, 378, 377, 376, 374, 373,
372, 371, 369, 368, 367, 365, 364, 363, 362, 361,
360, 359, 358, 357, 355, 353, 352, 351, 350, 349,
347, 346, 345, 344, 343, 342, 341, 340, 339, 337,
336, 335, 334, 333, 332, 331, 330, 329, 328, 327,
326, 324, 323, 322, 321, 318, 317, 316, 315, 314,
313, 312, 311, 310, 306, 304, 301, 300, 297, 293,
286, 284, 283, 282, 281, 279, 278, 277, 276, 275,
274, 273, 272, 271, 270, 269, 268, 267, 266, 264,
263, 262, 261, 260, 259, 258, 257, 256, 255, 254,
253, 251, 250, 249, 248, 247, 246, 245, 244, 242,
241, 240, 239, 238, 237, 236, 235, 233, 232, 231,
230, 229, 228, 227, 226, 225, 224, 223, 222, 221,
220, 219, 218, 217, 216, 215, 214, 212, 211, 210,
209, 208, 207, 206, 204, 201, 199, 197, 195, 192,
191, 189, 186, 178, 177, 176, 174, 173, 171, 170,
169, 168, 164, 163, 161, 159, 158, 157, 156, 155,
153, 152, 151, 150, 148, 147, 146, 145, 144, 143,
142, 141, 140, 138, 137, 135, 133, 132, 131, 130,
128, 127, 126, 124, 123, 122, 121, 120, 116, 110,
107, 106, 104, 99, 98, 79, 74, 68, 60, 53,
50, 49, 47, 43, 41, 39, 38, 24, 14, 11,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467, 1467,
1467, 1467
} ;
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
extern int yy_flex_debug;
int yy_flex_debug = 1;
static const flex_int16_t yy_rule_linenum[175] =
{ 0,
147, 149, 151, 156, 157, 162, 163, 164, 176, 179,
184, 191, 200, 209, 218, 227, 236, 245, 255, 264,
273, 282, 291, 300, 309, 318, 327, 336, 345, 354,
366, 375, 384, 393, 402, 413, 424, 435, 446, 456,
466, 477, 488, 499, 510, 521, 532, 543, 554, 565,
576, 587, 596, 605, 615, 624, 634, 648, 664, 673,
682, 691, 700, 721, 742, 751, 761, 770, 781, 790,
799, 808, 817, 826, 836, 845, 854, 863, 872, 881,
890, 899, 908, 917, 926, 936, 947, 959, 968, 977,
987, 997, 1007, 1017, 1027, 1037, 1046, 1056, 1065, 1074,
1083, 1092, 1102, 1112, 1121, 1131, 1140, 1149, 1158, 1167,
1176, 1185, 1194, 1203, 1212, 1221, 1230, 1239, 1248, 1257,
1266, 1275, 1284, 1293, 1302, 1311, 1320, 1329, 1338, 1347,
1356, 1365, 1374, 1383, 1392, 1401, 1411, 1421, 1431, 1441,
1451, 1461, 1471, 1481, 1491, 1500, 1509, 1518, 1527, 1536,
1545, 1554, 1565, 1576, 1589, 1602, 1617, 1716, 1721, 1726,
1731, 1732, 1733, 1734, 1735, 1736, 1738, 1756, 1769, 1774,
1778, 1780, 1782, 1784
} ;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *yytext;
#line 1 "dhcp4_lexer.ll"
/* Copyright (C) 2016-2018 Internet Systems Consortium, Inc. ("ISC")
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/. */
#line 8 "dhcp4_lexer.ll"
/* Generated files do not make clang static analyser so happy */
#ifndef __clang_analyzer__
#include <cerrno>
#include <climits>
#include <cstdlib>
#include <string>
#include <dhcp4/parser_context.h>
#include <asiolink/io_address.h>
#include <boost/lexical_cast.hpp>
#include <exceptions/exceptions.h>
/* Please avoid C++ style comments (// ... eol) as they break flex 2.6.2 */
/* Work around an incompatibility in flex (at least versions
2.5.31 through 2.5.33): it generates code that does
not conform to C89. See Debian bug 333231
<http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>. */
# undef yywrap
# define yywrap() 1
namespace {
bool start_token_flag = false;
isc::dhcp::Parser4Context::ParserType start_token_value;
unsigned int comment_start_line = 0;
using namespace isc::dhcp;
};
/* To avoid the call to exit... oops! */
#define YY_FATAL_ERROR(msg) isc::dhcp::Parser4Context::fatal(msg)
#line 1751 "dhcp4_lexer.cc"
/* noyywrap disables automatic rewinding for the next file to parse. Since we
always parse only a single string, there's no need to do any wraps. And
using yywrap requires linking with -lfl, which provides the default yywrap
implementation that always returns 1 anyway. */
/* nounput simplifies the lexer, by removing support for putting a character
back into the input stream. We never use such capability anyway. */
/* batch means that we'll never use the generated lexer interactively. */
/* avoid to get static global variables to remain with C++. */
/* in last resort %option reentrant */
/* Enables debug mode. To see the debug messages, one needs to also set
yy_flex_debug to 1, then the debug messages will be printed on stderr. */
/* I have no idea what this option does, except it was specified in the bison
examples and Postgres folks added it to remove gcc 4.3 warnings. Let's
be on the safe side and keep it. */
#define YY_NO_INPUT 1
/* These are not token expressions yet, just convenience expressions that
can be used during actual token definitions. Note some can match
incorrect inputs (e.g., IP addresses) which must be checked. */
/* for errors */
#line 94 "dhcp4_lexer.ll"
/* This code run each time a pattern is matched. It updates the location
by moving it ahead by yyleng bytes. yyleng specifies the length of the
currently matched token. */
#define YY_USER_ACTION driver.loc_.columns(yyleng);
#line 1777 "dhcp4_lexer.cc"
#line 1778 "dhcp4_lexer.cc"
#define INITIAL 0
#define COMMENT 1
#define DIR_ENTER 2
#define DIR_INCLUDE 3
#define DIR_EXIT 4
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
/* %if-c-only */
#include <unistd.h>
/* %endif */
/* %if-c++-only */
/* %endif */
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
/* %if-c-only Reentrant structure and macros (non-C++). */
/* %if-reentrant */
/* %if-c-only */
static int yy_init_globals ( void );
/* %endif */
/* %if-reentrant */
/* %endif */
/* %endif End reentrant structures and macros. */
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy ( void );
int yyget_debug ( void );
void yyset_debug ( int debug_flag );
YY_EXTRA_TYPE yyget_extra ( void );
void yyset_extra ( YY_EXTRA_TYPE user_defined );
FILE *yyget_in ( void );
void yyset_in ( FILE * _in_str );
FILE *yyget_out ( void );
void yyset_out ( FILE * _out_str );
int yyget_leng ( void );
char *yyget_text ( void );
int yyget_lineno ( void );
void yyset_lineno ( int _line_number );
/* %if-bison-bridge */
/* %endif */
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap ( void );
#else
extern int yywrap ( void );
#endif
#endif
/* %not-for-header */
#ifndef YY_NO_UNPUT
#endif
/* %ok-for-header */
/* %endif */
#ifndef yytext_ptr
static void yy_flex_strncpy ( char *, const char *, int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen ( const char * );
#endif
#ifndef YY_NO_INPUT
/* %if-c-only Standard (non-C++) definition */
/* %not-for-header */
#ifdef __cplusplus
static int yyinput ( void );
#else
static int input ( void );
#endif
/* %ok-for-header */
/* %endif */
#endif
/* %if-c-only */
/* %endif */
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k */
#define YY_READ_BUF_SIZE 16384
#else
#define YY_READ_BUF_SIZE 8192
#endif /* __ia64__ */
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* %if-c-only Standard (non-C++) definition */
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0)
/* %endif */
/* %if-c++-only C++ definition */
/* %endif */
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
/* %% [5.0] fread()/read() definition of YY_INPUT goes here unless we're doing C++ \ */\
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
int n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
/* %if-c++-only C++ definition \ */\
/* %endif */
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
/* %if-c-only */
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
/* %endif */
/* %if-c++-only */
/* %endif */
#endif
/* %if-tables-serialization structures and prototypes */
/* %not-for-header */
/* %ok-for-header */
/* %not-for-header */
/* %tables-yydmap generated elements */
/* %endif */
/* end tables serialization structures and prototypes */
/* %ok-for-header */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
/* %if-c-only Standard (non-C++) definition */
extern int yylex (void);
#define YY_DECL int yylex (void)
/* %endif */
/* %if-c++-only C++ definition */
/* %endif */
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK /*LINTED*/break;
#endif
/* %% [6.0] YY_RULE_SETUP definition goes here */
#define YY_RULE_SETUP \
YY_USER_ACTION
/* %not-for-header */
/** The main scanner function which does all the work.
*/
YY_DECL
{
yy_state_type yy_current_state;
char *yy_cp, *yy_bp;
int yy_act;
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! yyin )
/* %if-c-only */
yyin = stdin;
/* %endif */
/* %if-c++-only */
/* %endif */
if ( ! yyout )
/* %if-c-only */
yyout = stdout;
/* %endif */
/* %if-c++-only */
/* %endif */
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer( yyin, YY_BUF_SIZE );
}
yy_load_buffer_state( );
}
{
/* %% [7.0] user's declarations go here */
#line 100 "dhcp4_lexer.ll"
#line 104 "dhcp4_lexer.ll"
/* This part of the code is copied over to the verbatim to the top
of the generated yylex function. Explanation:
http://www.gnu.org/software/bison/manual/html_node/Multiple-start_002dsymbols.html */
/* Code run each time yylex is called. */
driver.loc_.step();
if (start_token_flag) {
start_token_flag = false;
switch (start_token_value) {
case Parser4Context::PARSER_JSON:
default:
return isc::dhcp::Dhcp4Parser::make_TOPLEVEL_JSON(driver.loc_);
case Parser4Context::PARSER_DHCP4:
return isc::dhcp::Dhcp4Parser::make_TOPLEVEL_DHCP4(driver.loc_);
case Parser4Context::SUBPARSER_DHCP4:
return isc::dhcp::Dhcp4Parser::make_SUB_DHCP4(driver.loc_);
case Parser4Context::PARSER_INTERFACES:
return isc::dhcp::Dhcp4Parser::make_SUB_INTERFACES4(driver.loc_);
case Parser4Context::PARSER_SUBNET4:
return isc::dhcp::Dhcp4Parser::make_SUB_SUBNET4(driver.loc_);
case Parser4Context::PARSER_POOL4:
return isc::dhcp::Dhcp4Parser::make_SUB_POOL4(driver.loc_);
case Parser4Context::PARSER_HOST_RESERVATION:
return isc::dhcp::Dhcp4Parser::make_SUB_RESERVATION(driver.loc_);
case Parser4Context::PARSER_OPTION_DEFS:
return isc::dhcp::Dhcp4Parser::make_SUB_OPTION_DEFS(driver.loc_);
case Parser4Context::PARSER_OPTION_DEF:
return isc::dhcp::Dhcp4Parser::make_SUB_OPTION_DEF(driver.loc_);
case Parser4Context::PARSER_OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_SUB_OPTION_DATA(driver.loc_);
case Parser4Context::PARSER_HOOKS_LIBRARY:
return isc::dhcp::Dhcp4Parser::make_SUB_HOOKS_LIBRARY(driver.loc_);
case Parser4Context::PARSER_DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_SUB_DHCP_DDNS(driver.loc_);
case Parser4Context::PARSER_CONFIG_CONTROL:
return isc::dhcp::Dhcp4Parser::make_SUB_CONFIG_CONTROL(driver.loc_);
case Parser4Context::PARSER_LOGGING:
return isc::dhcp::Dhcp4Parser::make_SUB_LOGGING(driver.loc_);
}
}
#line 2108 "dhcp4_lexer.cc"
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
{
/* %% [8.0] yymore()-related code goes here */
yy_cp = (yy_c_buf_p);
/* Support of yytext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
/* %% [9.0] code to set up and find next match goes here */
yy_current_state = (yy_start);
yy_match:
do
{
YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 1468 )
yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
++yy_cp;
}
while ( yy_current_state != 1467 );
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
yy_find_action:
/* %% [10.0] code to find the action number goes here */
yy_act = yy_accept[yy_current_state];
YY_DO_BEFORE_ACTION;
/* %% [11.0] code for yylineno update goes here */
do_action: /* This label is used only to access EOF actions. */
/* %% [12.0] debug code goes here */
if ( yy_flex_debug )
{
if ( yy_act == 0 )
fprintf( stderr, "--scanner backing up\n" );
else if ( yy_act < 175 )
fprintf( stderr, "--accepting rule at line %ld (\"%s\")\n",
(long)yy_rule_linenum[yy_act], yytext );
else if ( yy_act == 175 )
fprintf( stderr, "--accepting default rule (\"%s\")\n",
yytext );
else if ( yy_act == 176 )
fprintf( stderr, "--(end of buffer or a NUL)\n" );
else
fprintf( stderr, "--EOF (start condition %d)\n", YY_START );
}
switch ( yy_act )
{ /* beginning of action switch */
/* %% [13.0] actions go here */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = (yy_hold_char);
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
case 1:
YY_RULE_SETUP
#line 147 "dhcp4_lexer.ll"
;
YY_BREAK
case 2:
YY_RULE_SETUP
#line 149 "dhcp4_lexer.ll"
;
YY_BREAK
case 3:
YY_RULE_SETUP
#line 151 "dhcp4_lexer.ll"
{
BEGIN(COMMENT);
comment_start_line = driver.loc_.end.line;;
}
YY_BREAK
case 4:
YY_RULE_SETUP
#line 156 "dhcp4_lexer.ll"
BEGIN(INITIAL);
YY_BREAK
case 5:
YY_RULE_SETUP
#line 157 "dhcp4_lexer.ll"
;
YY_BREAK
case YY_STATE_EOF(COMMENT):
#line 158 "dhcp4_lexer.ll"
{
isc_throw(Dhcp4ParseError, "Comment not closed. (/* in line " << comment_start_line);
}
YY_BREAK
case 6:
YY_RULE_SETUP
#line 162 "dhcp4_lexer.ll"
BEGIN(DIR_ENTER);
YY_BREAK
case 7:
YY_RULE_SETUP
#line 163 "dhcp4_lexer.ll"
BEGIN(DIR_INCLUDE);
YY_BREAK
case 8:
YY_RULE_SETUP
#line 164 "dhcp4_lexer.ll"
{
/* Include directive. */
/* Extract the filename. */
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
driver.includeFile(tmp);
}
YY_BREAK
case YY_STATE_EOF(DIR_ENTER):
case YY_STATE_EOF(DIR_INCLUDE):
case YY_STATE_EOF(DIR_EXIT):
#line 173 "dhcp4_lexer.ll"
{
isc_throw(Dhcp4ParseError, "Directive not closed.");
}
YY_BREAK
case 9:
YY_RULE_SETUP
#line 176 "dhcp4_lexer.ll"
BEGIN(INITIAL);
YY_BREAK
case 10:
YY_RULE_SETUP
#line 179 "dhcp4_lexer.ll"
{
/* Ok, we found a with space. Let's ignore it and update loc variable. */
driver.loc_.step();
}
YY_BREAK
case 11:
/* rule 11 can match eol */
YY_RULE_SETUP
#line 184 "dhcp4_lexer.ll"
{
/* Newline found. Let's update the location and continue. */
driver.loc_.lines(yyleng);
driver.loc_.step();
}
YY_BREAK
case 12:
YY_RULE_SETUP
#line 191 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG:
return isc::dhcp::Dhcp4Parser::make_DHCP4(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("Dhcp4", driver.loc_);
}
}
YY_BREAK
case 13:
YY_RULE_SETUP
#line 200 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_INTERFACES_CONFIG(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("interfaces-config", driver.loc_);
}
}
YY_BREAK
case 14:
YY_RULE_SETUP
#line 209 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_SANITY_CHECKS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("sanity-checks", driver.loc_);
}
}
YY_BREAK
case 15:
YY_RULE_SETUP
#line 218 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SANITY_CHECKS:
return isc::dhcp::Dhcp4Parser::make_LEASE_CHECKS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("lease-checks", driver.loc_);
}
}
YY_BREAK
case 16:
YY_RULE_SETUP
#line 227 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::INTERFACES_CONFIG:
return isc::dhcp::Dhcp4Parser::make_DHCP_SOCKET_TYPE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("dhcp-socket-type", driver.loc_);
}
}
YY_BREAK
case 17:
YY_RULE_SETUP
#line 236 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_SOCKET_TYPE:
return isc::dhcp::Dhcp4Parser::make_RAW(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("raw", driver.loc_);
}
}
YY_BREAK
case 18:
YY_RULE_SETUP
#line 245 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_SOCKET_TYPE:
case isc::dhcp::Parser4Context::NCR_PROTOCOL:
return isc::dhcp::Dhcp4Parser::make_UDP(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("udp", driver.loc_);
}
}
YY_BREAK
case 19:
YY_RULE_SETUP
#line 255 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case Parser4Context::INTERFACES_CONFIG:
return isc::dhcp::Dhcp4Parser::make_OUTBOUND_INTERFACE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("outbound-interface", driver.loc_);
}
}
YY_BREAK
case 20:
YY_RULE_SETUP
#line 264 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case Parser4Context::OUTBOUND_INTERFACE:
return Dhcp4Parser::make_SAME_AS_INBOUND(driver.loc_);
default:
return Dhcp4Parser::make_STRING("same-as-inbound", driver.loc_);
}
}
YY_BREAK
case 21:
YY_RULE_SETUP
#line 273 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case Parser4Context::OUTBOUND_INTERFACE:
return Dhcp4Parser::make_USE_ROUTING(driver.loc_);
default:
return Dhcp4Parser::make_STRING("use-routing", driver.loc_);
}
}
YY_BREAK
case 22:
YY_RULE_SETUP
#line 282 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::INTERFACES_CONFIG:
return isc::dhcp::Dhcp4Parser::make_INTERFACES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("interfaces", driver.loc_);
}
}
YY_BREAK
case 23:
YY_RULE_SETUP
#line 291 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::INTERFACES_CONFIG:
return isc::dhcp::Dhcp4Parser::make_RE_DETECT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("re-detect", driver.loc_);
}
}
YY_BREAK
case 24:
YY_RULE_SETUP
#line 300 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_LEASE_DATABASE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("lease-database", driver.loc_);
}
}
YY_BREAK
case 25:
YY_RULE_SETUP
#line 309 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_HOSTS_DATABASE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hosts-database", driver.loc_);
}
}
YY_BREAK
case 26:
YY_RULE_SETUP
#line 318 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_HOSTS_DATABASES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hosts-databases", driver.loc_);
}
}
YY_BREAK
case 27:
YY_RULE_SETUP
#line 327 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_CONFIG_CONTROL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("config-control", driver.loc_);
}
}
YY_BREAK
case 28:
YY_RULE_SETUP
#line 336 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG_CONTROL:
return isc::dhcp::Dhcp4Parser::make_CONFIG_DATABASES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("config-databases", driver.loc_);
}
}
YY_BREAK
case 29:
YY_RULE_SETUP
#line 345 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
return isc::dhcp::Dhcp4Parser::make_READONLY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("readonly", driver.loc_);
}
}
YY_BREAK
case 30:
YY_RULE_SETUP
#line 354 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_TYPE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("type", driver.loc_);
}
}
YY_BREAK
case 31:
YY_RULE_SETUP
#line 366 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DATABASE_TYPE:
return isc::dhcp::Dhcp4Parser::make_MEMFILE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("memfile", driver.loc_);
}
}
YY_BREAK
case 32:
YY_RULE_SETUP
#line 375 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DATABASE_TYPE:
return isc::dhcp::Dhcp4Parser::make_MYSQL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("mysql", driver.loc_);
}
}
YY_BREAK
case 33:
YY_RULE_SETUP
#line 384 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DATABASE_TYPE:
return isc::dhcp::Dhcp4Parser::make_POSTGRESQL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("postgresql", driver.loc_);
}
}
YY_BREAK
case 34:
YY_RULE_SETUP
#line 393 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DATABASE_TYPE:
return isc::dhcp::Dhcp4Parser::make_CQL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("cql", driver.loc_);
}
}
YY_BREAK
case 35:
YY_RULE_SETUP
#line 402 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_USER(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("user", driver.loc_);
}
}
YY_BREAK
case 36:
YY_RULE_SETUP
#line 413 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_PASSWORD(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("password", driver.loc_);
}
}
YY_BREAK
case 37:
YY_RULE_SETUP
#line 424 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_HOST(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("host", driver.loc_);
}
}
YY_BREAK
case 38:
YY_RULE_SETUP
#line 435 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_PORT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("port", driver.loc_);
}
}
YY_BREAK
case 39:
YY_RULE_SETUP
#line 446 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
return isc::dhcp::Dhcp4Parser::make_PERSIST(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("persist", driver.loc_);
}
}
YY_BREAK
case 40:
YY_RULE_SETUP
#line 456 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
return isc::dhcp::Dhcp4Parser::make_LFC_INTERVAL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("lfc-interval", driver.loc_);
}
}
YY_BREAK
case 41:
YY_RULE_SETUP
#line 466 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_CONNECT_TIMEOUT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("connect-timeout", driver.loc_);
}
}
YY_BREAK
case 42:
YY_RULE_SETUP
#line 477 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_KEYSPACE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("keyspace", driver.loc_);
}
}
YY_BREAK
case 43:
YY_RULE_SETUP
#line 488 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_RECONNECT_WAIT_TIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("reconnect-wait-time", driver.loc_);
}
}
YY_BREAK
case 44:
YY_RULE_SETUP
#line 499 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_REQUEST_TIMEOUT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("request-timeout", driver.loc_);
}
}
YY_BREAK
case 45:
YY_RULE_SETUP
#line 510 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_TCP_KEEPALIVE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("tcp-keepalive", driver.loc_);
}
}
YY_BREAK
case 46:
YY_RULE_SETUP
#line 521 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_TCP_NODELAY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("tcp-nodelay", driver.loc_);
}
}
YY_BREAK
case 47:
YY_RULE_SETUP
#line 532 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_CONTACT_POINTS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("contact-points", driver.loc_);
}
}
YY_BREAK
case 48:
YY_RULE_SETUP
#line 543 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
return isc::dhcp::Dhcp4Parser::make_MAX_RECONNECT_TRIES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("max-reconnect-tries", driver.loc_);
}
}
YY_BREAK
case 49:
YY_RULE_SETUP
#line 554 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_VALID_LIFETIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("valid-lifetime", driver.loc_);
}
}
YY_BREAK
case 50:
YY_RULE_SETUP
#line 565 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_RENEW_TIMER(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("renew-timer", driver.loc_);
}
}
YY_BREAK
case 51:
YY_RULE_SETUP
#line 576 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_REBIND_TIMER(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("rebind-timer", driver.loc_);
}
}
YY_BREAK
case 52:
YY_RULE_SETUP
#line 587 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_DECLINE_PROBATION_PERIOD(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("decline-probation-period", driver.loc_);
}
}
YY_BREAK
case 53:
YY_RULE_SETUP
#line 596 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_SERVER_TAG(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("server-tag", driver.loc_);
}
}
YY_BREAK
case 54:
YY_RULE_SETUP
#line 605 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_SUBNET4(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("subnet4", driver.loc_);
}
}
YY_BREAK
case 55:
YY_RULE_SETUP
#line 615 "dhcp4_lexer.ll"
{
switch (driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_SHARED_NETWORKS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("shared-networks", driver.loc_);
}
}
YY_BREAK
case 56:
YY_RULE_SETUP
#line 624 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_OPTION_DEF(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("option-def", driver.loc_);
}
}
YY_BREAK
case 57:
YY_RULE_SETUP
#line 634 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::POOLS:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_OPTION_DATA(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("option-data", driver.loc_);
}
}
YY_BREAK
case 58:
YY_RULE_SETUP
#line 648 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LEASE_DATABASE:
case isc::dhcp::Parser4Context::HOSTS_DATABASE:
case isc::dhcp::Parser4Context::CONFIG_DATABASE:
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::OPTION_DATA:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::LOGGERS:
return isc::dhcp::Dhcp4Parser::make_NAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("name", driver.loc_);
}
}
YY_BREAK
case 59:
YY_RULE_SETUP
#line 664 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_DATA(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("data", driver.loc_);
}
}
YY_BREAK
case 60:
YY_RULE_SETUP
#line 673 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_ALWAYS_SEND(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("always-send", driver.loc_);
}
}
YY_BREAK
case 61:
YY_RULE_SETUP
#line 682 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_POOLS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("pools", driver.loc_);
}
}
YY_BREAK
case 62:
YY_RULE_SETUP
#line 691 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::POOLS:
return isc::dhcp::Dhcp4Parser::make_POOL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("pool", driver.loc_);
}
}
YY_BREAK
case 63:
YY_RULE_SETUP
#line 700 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::INTERFACES_CONFIG:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::POOLS:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::OPTION_DATA:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
case isc::dhcp::Parser4Context::CONTROL_SOCKET:
case isc::dhcp::Parser4Context::DHCP_QUEUE_CONTROL:
case isc::dhcp::Parser4Context::LOGGERS:
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_USER_CONTEXT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("user-context", driver.loc_);
}
}
YY_BREAK
case 64:
YY_RULE_SETUP
#line 721 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::INTERFACES_CONFIG:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::POOLS:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::OPTION_DATA:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
case isc::dhcp::Parser4Context::CONTROL_SOCKET:
case isc::dhcp::Parser4Context::DHCP_QUEUE_CONTROL:
case isc::dhcp::Parser4Context::LOGGERS:
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_COMMENT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("comment", driver.loc_);
}
}
YY_BREAK
case 65:
YY_RULE_SETUP
#line 742 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_SUBNET(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("subnet", driver.loc_);
}
}
YY_BREAK
case 66:
YY_RULE_SETUP
#line 751 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_INTERFACE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("interface", driver.loc_);
}
}
YY_BREAK
case 67:
YY_RULE_SETUP
#line 761 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("id", driver.loc_);
}
}
YY_BREAK
case 68:
YY_RULE_SETUP
#line 770 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_RESERVATION_MODE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("reservation-mode", driver.loc_);
}
}
YY_BREAK
case 69:
YY_RULE_SETUP
#line 781 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATION_MODE:
return isc::dhcp::Dhcp4Parser::make_DISABLED(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("disabled", driver.loc_);
}
}
YY_BREAK
case 70:
YY_RULE_SETUP
#line 790 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATION_MODE:
return isc::dhcp::Dhcp4Parser::make_DISABLED(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("off", driver.loc_);
}
}
YY_BREAK
case 71:
YY_RULE_SETUP
#line 799 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATION_MODE:
return isc::dhcp::Dhcp4Parser::make_OUT_OF_POOL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("out-of-pool", driver.loc_);
}
}
YY_BREAK
case 72:
YY_RULE_SETUP
#line 808 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATION_MODE:
return isc::dhcp::Dhcp4Parser::make_GLOBAL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("global", driver.loc_);
}
}
YY_BREAK
case 73:
YY_RULE_SETUP
#line 817 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATION_MODE:
return isc::dhcp::Dhcp4Parser::make_ALL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("all", driver.loc_);
}
}
YY_BREAK
case 74:
YY_RULE_SETUP
#line 826 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_CODE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("code", driver.loc_);
}
}
YY_BREAK
case 75:
YY_RULE_SETUP
#line 836 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_HOST_RESERVATION_IDENTIFIERS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("host-reservation-identifiers", driver.loc_);
}
}
YY_BREAK
case 76:
YY_RULE_SETUP
#line 845 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG:
return isc::dhcp::Dhcp4Parser::make_LOGGING(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("Logging", driver.loc_);
}
}
YY_BREAK
case 77:
YY_RULE_SETUP
#line 854 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LOGGING:
return isc::dhcp::Dhcp4Parser::make_LOGGERS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("loggers", driver.loc_);
}
}
YY_BREAK
case 78:
YY_RULE_SETUP
#line 863 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LOGGERS:
return isc::dhcp::Dhcp4Parser::make_OUTPUT_OPTIONS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("output_options", driver.loc_);
}
}
YY_BREAK
case 79:
YY_RULE_SETUP
#line 872 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OUTPUT_OPTIONS:
return isc::dhcp::Dhcp4Parser::make_OUTPUT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("output", driver.loc_);
}
}
YY_BREAK
case 80:
YY_RULE_SETUP
#line 881 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LOGGERS:
return isc::dhcp::Dhcp4Parser::make_DEBUGLEVEL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("debuglevel", driver.loc_);
}
}
YY_BREAK
case 81:
YY_RULE_SETUP
#line 890 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OUTPUT_OPTIONS:
return isc::dhcp::Dhcp4Parser::make_FLUSH(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("flush", driver.loc_);
}
}
YY_BREAK
case 82:
YY_RULE_SETUP
#line 899 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OUTPUT_OPTIONS:
return isc::dhcp::Dhcp4Parser::make_MAXSIZE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("maxsize", driver.loc_);
}
}
YY_BREAK
case 83:
YY_RULE_SETUP
#line 908 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OUTPUT_OPTIONS:
return isc::dhcp::Dhcp4Parser::make_MAXVER(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("maxver", driver.loc_);
}
}
YY_BREAK
case 84:
YY_RULE_SETUP
#line 917 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::LOGGERS:
return isc::dhcp::Dhcp4Parser::make_SEVERITY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("severity", driver.loc_);
}
}
YY_BREAK
case 85:
YY_RULE_SETUP
#line 926 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_CLIENT_CLASSES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("client-classes", driver.loc_);
}
}
YY_BREAK
case 86:
YY_RULE_SETUP
#line 936 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::POOLS:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_REQUIRE_CLIENT_CLASSES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("require-client-classes", driver.loc_);
}
}
YY_BREAK
case 87:
YY_RULE_SETUP
#line 947 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::POOLS:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_CLIENT_CLASS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("client-class", driver.loc_);
}
}
YY_BREAK
case 88:
YY_RULE_SETUP
#line 959 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_TEST(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("test", driver.loc_);
}
}
YY_BREAK
case 89:
YY_RULE_SETUP
#line 968 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_ONLY_IF_REQUIRED(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("only-if-required", driver.loc_);
}
}
YY_BREAK
case 90:
YY_RULE_SETUP
#line 977 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_RESERVATIONS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("reservations", driver.loc_);
}
}
YY_BREAK
case 91:
YY_RULE_SETUP
#line 987 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOST_RESERVATION_IDENTIFIERS:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_DUID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("duid", driver.loc_);
}
}
YY_BREAK
case 92:
YY_RULE_SETUP
#line 997 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOST_RESERVATION_IDENTIFIERS:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_HW_ADDRESS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hw-address", driver.loc_);
}
}
YY_BREAK
case 93:
YY_RULE_SETUP
#line 1007 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOST_RESERVATION_IDENTIFIERS:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_CLIENT_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("client-id", driver.loc_);
}
}
YY_BREAK
case 94:
YY_RULE_SETUP
#line 1017 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOST_RESERVATION_IDENTIFIERS:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_CIRCUIT_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("circuit-id", driver.loc_);
}
}
YY_BREAK
case 95:
YY_RULE_SETUP
#line 1027 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOST_RESERVATION_IDENTIFIERS:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_FLEX_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("flex-id", driver.loc_);
}
}
YY_BREAK
case 96:
YY_RULE_SETUP
#line 1037 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_HOSTNAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hostname", driver.loc_);
}
}
YY_BREAK
case 97:
YY_RULE_SETUP
#line 1046 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DEF:
case isc::dhcp::Parser4Context::OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_SPACE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("space", driver.loc_);
}
}
YY_BREAK
case 98:
YY_RULE_SETUP
#line 1056 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DATA:
return isc::dhcp::Dhcp4Parser::make_CSV_FORMAT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("csv-format", driver.loc_);
}
}
YY_BREAK
case 99:
YY_RULE_SETUP
#line 1065 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DEF:
return isc::dhcp::Dhcp4Parser::make_RECORD_TYPES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("record-types", driver.loc_);
}
}
YY_BREAK
case 100:
YY_RULE_SETUP
#line 1074 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DEF:
return isc::dhcp::Dhcp4Parser::make_ENCAPSULATE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("encapsulate", driver.loc_);
}
}
YY_BREAK
case 101:
YY_RULE_SETUP
#line 1083 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::OPTION_DEF:
return isc::dhcp::Dhcp4Parser::make_ARRAY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("array", driver.loc_);
}
}
YY_BREAK
case 102:
YY_RULE_SETUP
#line 1092 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_RELAY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("relay", driver.loc_);
}
}
YY_BREAK
case 103:
YY_RULE_SETUP
#line 1102 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RELAY:
case isc::dhcp::Parser4Context::RESERVATIONS:
return isc::dhcp::Dhcp4Parser::make_IP_ADDRESS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("ip-address", driver.loc_);
}
}
YY_BREAK
case 104:
YY_RULE_SETUP
#line 1112 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::RELAY:
return isc::dhcp::Dhcp4Parser::make_IP_ADDRESSES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("ip-addresses", driver.loc_);
}
}
YY_BREAK
case 105:
YY_RULE_SETUP
#line 1121 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_HOOKS_LIBRARIES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hooks-libraries", driver.loc_);
}
}
YY_BREAK
case 106:
YY_RULE_SETUP
#line 1131 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOOKS_LIBRARIES:
return isc::dhcp::Dhcp4Parser::make_PARAMETERS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("parameters", driver.loc_);
}
}
YY_BREAK
case 107:
YY_RULE_SETUP
#line 1140 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::HOOKS_LIBRARIES:
return isc::dhcp::Dhcp4Parser::make_LIBRARY(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("library", driver.loc_);
}
}
YY_BREAK
case 108:
YY_RULE_SETUP
#line 1149 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_EXPIRED_LEASES_PROCESSING(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("expired-leases-processing", driver.loc_);
}
}
YY_BREAK
case 109:
YY_RULE_SETUP
#line 1158 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_RECLAIM_TIMER_WAIT_TIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("reclaim-timer-wait-time", driver.loc_);
}
}
YY_BREAK
case 110:
YY_RULE_SETUP
#line 1167 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_FLUSH_RECLAIMED_TIMER_WAIT_TIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("flush-reclaimed-timer-wait-time", driver.loc_);
}
}
YY_BREAK
case 111:
YY_RULE_SETUP
#line 1176 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_HOLD_RECLAIMED_TIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hold-reclaimed-time", driver.loc_);
}
}
YY_BREAK
case 112:
YY_RULE_SETUP
#line 1185 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_MAX_RECLAIM_LEASES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("max-reclaim-leases", driver.loc_);
}
}
YY_BREAK
case 113:
YY_RULE_SETUP
#line 1194 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_MAX_RECLAIM_TIME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("max-reclaim-time", driver.loc_);
}
}
YY_BREAK
case 114:
YY_RULE_SETUP
#line 1203 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::EXPIRED_LEASES_PROCESSING:
return isc::dhcp::Dhcp4Parser::make_UNWARNED_RECLAIM_CYCLES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("unwarned-reclaim-cycles", driver.loc_);
}
}
YY_BREAK
case 115:
YY_RULE_SETUP
#line 1212 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_DHCP4O6_PORT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("dhcp4o6-port", driver.loc_);
}
}
YY_BREAK
case 116:
YY_RULE_SETUP
#line 1221 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_CONTROL_SOCKET(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("control-socket", driver.loc_);
}
}
YY_BREAK
case 117:
YY_RULE_SETUP
#line 1230 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONTROL_SOCKET:
return isc::dhcp::Dhcp4Parser::make_SOCKET_TYPE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("socket-type", driver.loc_);
}
}
YY_BREAK
case 118:
YY_RULE_SETUP
#line 1239 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONTROL_SOCKET:
return isc::dhcp::Dhcp4Parser::make_SOCKET_NAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("socket-name", driver.loc_);
}
}
YY_BREAK
case 119:
YY_RULE_SETUP
#line 1248 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_DHCP_QUEUE_CONTROL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("dhcp-queue-control", driver.loc_);
}
}
YY_BREAK
case 120:
YY_RULE_SETUP
#line 1257 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_DHCP_DDNS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("dhcp-ddns", driver.loc_);
}
}
YY_BREAK
case 121:
YY_RULE_SETUP
#line 1266 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_ENABLE_UPDATES(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("enable-updates", driver.loc_);
}
}
YY_BREAK
case 122:
YY_RULE_SETUP
#line 1275 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_QUALIFYING_SUFFIX(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("qualifying-suffix", driver.loc_);
}
}
YY_BREAK
case 123:
YY_RULE_SETUP
#line 1284 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_SERVER_IP(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("server-ip", driver.loc_);
}
}
YY_BREAK
case 124:
YY_RULE_SETUP
#line 1293 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_SERVER_PORT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("server-port", driver.loc_);
}
}
YY_BREAK
case 125:
YY_RULE_SETUP
#line 1302 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_SENDER_IP(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("sender-ip", driver.loc_);
}
}
YY_BREAK
case 126:
YY_RULE_SETUP
#line 1311 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_SENDER_PORT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("sender-port", driver.loc_);
}
}
YY_BREAK
case 127:
YY_RULE_SETUP
#line 1320 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_MAX_QUEUE_SIZE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("max-queue-size", driver.loc_);
}
}
YY_BREAK
case 128:
YY_RULE_SETUP
#line 1329 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_NCR_PROTOCOL(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("ncr-protocol", driver.loc_);
}
}
YY_BREAK
case 129:
YY_RULE_SETUP
#line 1338 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_NCR_FORMAT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("ncr-format", driver.loc_);
}
}
YY_BREAK
case 130:
YY_RULE_SETUP
#line 1347 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_OVERRIDE_NO_UPDATE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("override-no-update", driver.loc_);
}
}
YY_BREAK
case 131:
YY_RULE_SETUP
#line 1356 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_OVERRIDE_CLIENT_UPDATE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("override-client-update", driver.loc_);
}
}
YY_BREAK
case 132:
YY_RULE_SETUP
#line 1365 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_REPLACE_CLIENT_NAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("replace-client-name", driver.loc_);
}
}
YY_BREAK
case 133:
YY_RULE_SETUP
#line 1374 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_GENERATED_PREFIX(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("generated-prefix", driver.loc_);
}
}
YY_BREAK
case 134:
YY_RULE_SETUP
#line 1383 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_HOSTNAME_CHAR_SET(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hostname-char-set", driver.loc_);
}
}
YY_BREAK
case 135:
YY_RULE_SETUP
#line 1392 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP_DDNS:
return isc::dhcp::Dhcp4Parser::make_HOSTNAME_CHAR_REPLACEMENT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("hostname-char-replacement", driver.loc_);
}
}
YY_BREAK
case 136:
YY_RULE_SETUP
#line 1401 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::NCR_PROTOCOL) {
return isc::dhcp::Dhcp4Parser::make_UDP(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 137:
YY_RULE_SETUP
#line 1411 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::NCR_PROTOCOL) {
return isc::dhcp::Dhcp4Parser::make_TCP(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 138:
YY_RULE_SETUP
#line 1421 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::NCR_FORMAT) {
return isc::dhcp::Dhcp4Parser::make_JSON(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 139:
YY_RULE_SETUP
#line 1431 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_WHEN_PRESENT(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 140:
YY_RULE_SETUP
#line 1441 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_WHEN_PRESENT(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 141:
YY_RULE_SETUP
#line 1451 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_NEVER(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 142:
YY_RULE_SETUP
#line 1461 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_NEVER(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 143:
YY_RULE_SETUP
#line 1471 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_ALWAYS(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 144:
YY_RULE_SETUP
#line 1481 "dhcp4_lexer.ll"
{
/* dhcp-ddns value keywords are case insensitive */
if (driver.ctx_ == isc::dhcp::Parser4Context::REPLACE_CLIENT_NAME) {
return isc::dhcp::Dhcp4Parser::make_WHEN_NOT_PRESENT(driver.loc_);
}
std::string tmp(yytext+1);
tmp.resize(tmp.size() - 1);
return isc::dhcp::Dhcp4Parser::make_STRING(tmp, driver.loc_);
}
YY_BREAK
case 145:
YY_RULE_SETUP
#line 1491 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG:
return isc::dhcp::Dhcp4Parser::make_DHCP6(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("Dhcp6", driver.loc_);
}
}
YY_BREAK
case 146:
YY_RULE_SETUP
#line 1500 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG:
return isc::dhcp::Dhcp4Parser::make_DHCPDDNS(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("DhcpDdns", driver.loc_);
}
}
YY_BREAK
case 147:
YY_RULE_SETUP
#line 1509 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::CONFIG:
return isc::dhcp::Dhcp4Parser::make_CONTROL_AGENT(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("Control-agent", driver.loc_);
}
}
YY_BREAK
case 148:
YY_RULE_SETUP
#line 1518 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_SUBNET_4O6_INTERFACE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("4o6-interface", driver.loc_);
}
}
YY_BREAK
case 149:
YY_RULE_SETUP
#line 1527 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_SUBNET_4O6_INTERFACE_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("4o6-interface-id", driver.loc_);
}
}
YY_BREAK
case 150:
YY_RULE_SETUP
#line 1536 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::SUBNET4:
return isc::dhcp::Dhcp4Parser::make_SUBNET_4O6_SUBNET(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("4o6-subnet", driver.loc_);
}
}
YY_BREAK
case 151:
YY_RULE_SETUP
#line 1545 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
return isc::dhcp::Dhcp4Parser::make_ECHO_CLIENT_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("echo-client-id", driver.loc_);
}
}
YY_BREAK
case 152:
YY_RULE_SETUP
#line 1554 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_MATCH_CLIENT_ID(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("match-client-id", driver.loc_);
}
}
YY_BREAK
case 153:
YY_RULE_SETUP
#line 1565 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
return isc::dhcp::Dhcp4Parser::make_AUTHORITATIVE(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("authoritative", driver.loc_);
}
}
YY_BREAK
case 154:
YY_RULE_SETUP
#line 1576 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_NEXT_SERVER(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("next-server", driver.loc_);
}
}
YY_BREAK
case 155:
YY_RULE_SETUP
#line 1589 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_SERVER_HOSTNAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("server-hostname", driver.loc_);
}
}
YY_BREAK
case 156:
YY_RULE_SETUP
#line 1602 "dhcp4_lexer.ll"
{
switch(driver.ctx_) {
case isc::dhcp::Parser4Context::DHCP4:
case isc::dhcp::Parser4Context::SUBNET4:
case isc::dhcp::Parser4Context::SHARED_NETWORK:
case isc::dhcp::Parser4Context::RESERVATIONS:
case isc::dhcp::Parser4Context::CLIENT_CLASSES:
return isc::dhcp::Dhcp4Parser::make_BOOT_FILE_NAME(driver.loc_);
default:
return isc::dhcp::Dhcp4Parser::make_STRING("boot-file-name", driver.loc_);
}
}
YY_BREAK
case 157:
YY_RULE_SETUP
#line 1617 "dhcp4_lexer.ll"
{
/* A string has been matched. It contains the actual string and single quotes.
We need to get those quotes out of the way and just use its content, e.g.
for 'foo' we should get foo */
std::string raw(yytext+1);
size_t len = raw.size() - 1;
raw.resize(len);
std::string decoded;
decoded.reserve(len);
for (size_t pos = 0; pos < len; ++pos) {
int b = 0;
char c = raw[pos];
switch (c) {
case '"':
/* impossible condition */
driver.error(driver.loc_, "Bad quote in \"" + raw + "\"");
break;
case '\\':
++pos;
if (pos >= len) {
/* impossible condition */
driver.error(driver.loc_, "Overflow escape in \"" + raw + "\"");
}
c = raw[pos];
switch (c) {
case '"':
case '\\':
case '/':
decoded.push_back(c);
break;
case 'b':
decoded.push_back('\b');
break;
case 'f':
decoded.push_back('\f');
break;
case 'n':
decoded.push_back('\n');
break;
case 'r':
decoded.push_back('\r');
break;
case 't':
decoded.push_back('\t');
break;
case 'u':
/* support only \u0000 to \u00ff */
++pos;
if (pos + 4 > len) {
/* impossible condition */
driver.error(driver.loc_,
"Overflow unicode escape in \"" + raw + "\"");
}
if ((raw[pos] != '0') || (raw[pos + 1] != '0')) {
driver.error(driver.loc_, "Unsupported unicode escape in \"" + raw + "\"");
}
pos += 2;
c = raw[pos];
if ((c >= '0') && (c <= '9')) {
b = (c - '0') << 4;
} else if ((c >= 'A') && (c <= 'F')) {
b = (c - 'A' + 10) << 4;
} else if ((c >= 'a') && (c <= 'f')) {
b = (c - 'a' + 10) << 4;
} else {
/* impossible condition */
driver.error(driver.loc_, "Not hexadecimal in unicode escape in \"" + raw + "\"");
}
pos++;
c = raw[pos];
if ((c >= '0') && (c <= '9')) {
b |= c - '0';
} else if ((c >= 'A') && (c <= 'F')) {
b |= c - 'A' + 10;
} else if ((c >= 'a') && (c <= 'f')) {
b |= c - 'a' + 10;
} else {
/* impossible condition */
driver.error(driver.loc_, "Not hexadecimal in unicode escape in \"" + raw + "\"");
}
decoded.push_back(static_cast<char>(b & 0xff));
break;
default:
/* impossible condition */
driver.error(driver.loc_, "Bad escape in \"" + raw + "\"");
}
break;
default:
if ((c >= 0) && (c < 0x20)) {
/* impossible condition */
driver.error(driver.loc_, "Invalid control in \"" + raw + "\"");
}
decoded.push_back(c);
}
}
return isc::dhcp::Dhcp4Parser::make_STRING(decoded, driver.loc_);
}
YY_BREAK
case 158:
/* rule 158 can match eol */
YY_RULE_SETUP
#line 1716 "dhcp4_lexer.ll"
{
/* Bad string with a forbidden control character inside */
driver.error(driver.loc_, "Invalid control in " + std::string(yytext));
}
YY_BREAK
case 159:
/* rule 159 can match eol */
YY_RULE_SETUP
#line 1721 "dhcp4_lexer.ll"
{
/* Bad string with a bad escape inside */
driver.error(driver.loc_, "Bad escape in " + std::string(yytext));
}
YY_BREAK
case 160:
YY_RULE_SETUP
#line 1726 "dhcp4_lexer.ll"
{
/* Bad string with an open escape at the end */
driver.error(driver.loc_, "Overflow escape in " + std::string(yytext));
}
YY_BREAK
case 161:
YY_RULE_SETUP
#line 1731 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_LSQUARE_BRACKET(driver.loc_); }
YY_BREAK
case 162:
YY_RULE_SETUP
#line 1732 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_RSQUARE_BRACKET(driver.loc_); }
YY_BREAK
case 163:
YY_RULE_SETUP
#line 1733 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_LCURLY_BRACKET(driver.loc_); }
YY_BREAK
case 164:
YY_RULE_SETUP
#line 1734 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_RCURLY_BRACKET(driver.loc_); }
YY_BREAK
case 165:
YY_RULE_SETUP
#line 1735 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_COMMA(driver.loc_); }
YY_BREAK
case 166:
YY_RULE_SETUP
#line 1736 "dhcp4_lexer.ll"
{ return isc::dhcp::Dhcp4Parser::make_COLON(driver.loc_); }
YY_BREAK
case 167:
YY_RULE_SETUP
#line 1738 "dhcp4_lexer.ll"
{
/* An integer was found. */
std::string tmp(yytext);
int64_t integer = 0;
try {
/* In substring we want to use negative values (e.g. -1).
In enterprise-id we need to use values up to 0xffffffff.
To cover both of those use cases, we need at least
int64_t. */
integer = boost::lexical_cast<int64_t>(tmp);
} catch (const boost::bad_lexical_cast &) {
driver.error(driver.loc_, "Failed to convert " + tmp + " to an integer.");
}
/* The parser needs the string form as double conversion is no lossless */
return isc::dhcp::Dhcp4Parser::make_INTEGER(integer, driver.loc_);
}
YY_BREAK
case 168:
YY_RULE_SETUP
#line 1756 "dhcp4_lexer.ll"
{
/* A floating point was found. */
std::string tmp(yytext);
double fp = 0.0;
try {
fp = boost::lexical_cast<double>(tmp);
} catch (const boost::bad_lexical_cast &) {
driver.error(driver.loc_, "Failed to convert " + tmp + " to a floating point.");
}
return isc::dhcp::Dhcp4Parser::make_FLOAT(fp, driver.loc_);
}
YY_BREAK
case 169:
YY_RULE_SETUP
#line 1769 "dhcp4_lexer.ll"
{
string tmp(yytext);
return isc::dhcp::Dhcp4Parser::make_BOOLEAN(tmp == "true", driver.loc_);
}
YY_BREAK
case 170:
YY_RULE_SETUP
#line 1774 "dhcp4_lexer.ll"
{
return isc::dhcp::Dhcp4Parser::make_NULL_TYPE(driver.loc_);
}
YY_BREAK
case 171:
YY_RULE_SETUP
#line 1778 "dhcp4_lexer.ll"
driver.error (driver.loc_, "JSON true reserved keyword is lower case only");
YY_BREAK
case 172:
YY_RULE_SETUP
#line 1780 "dhcp4_lexer.ll"
driver.error (driver.loc_, "JSON false reserved keyword is lower case only");
YY_BREAK
case 173:
YY_RULE_SETUP
#line 1782 "dhcp4_lexer.ll"
driver.error (driver.loc_, "JSON null reserved keyword is lower case only");
YY_BREAK
case 174:
YY_RULE_SETUP
#line 1784 "dhcp4_lexer.ll"
driver.error (driver.loc_, "Invalid character: " + std::string(yytext));
YY_BREAK
case YY_STATE_EOF(INITIAL):
#line 1786 "dhcp4_lexer.ll"
{
if (driver.states_.empty()) {
return isc::dhcp::Dhcp4Parser::make_END(driver.loc_);
}
driver.loc_ = driver.locs_.back();
driver.locs_.pop_back();
driver.file_ = driver.files_.back();
driver.files_.pop_back();
if (driver.sfile_) {
fclose(driver.sfile_);
driver.sfile_ = 0;
}
if (!driver.sfiles_.empty()) {
driver.sfile_ = driver.sfiles_.back();
driver.sfiles_.pop_back();
}
parser4__delete_buffer(YY_CURRENT_BUFFER);
parser4__switch_to_buffer(driver.states_.back());
driver.states_.pop_back();
BEGIN(DIR_EXIT);
}
YY_BREAK
case 175:
YY_RULE_SETUP
#line 1809 "dhcp4_lexer.ll"
ECHO;
YY_BREAK
#line 4390 "dhcp4_lexer.cc"
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
/* %if-c-only */
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
/* %endif */
/* %if-c++-only */
/* %endif */
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
/* %% [14.0] code to do back-up for compressed tables and set up yy_cp goes here */
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( yywrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
} /* end of yylex */
/* %ok-for-header */
/* %if-c++-only */
/* %not-for-header */
/* %ok-for-header */
/* %endif */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
/* %if-c-only */
static int yy_get_next_buffer (void)
/* %endif */
/* %if-c++-only */
/* %endif */
{
char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char *source = (yytext_ptr);
int number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr) - 1);
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
int num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
int yy_c_buf_p_offset =
(int) ((yy_c_buf_p) - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
int new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc( (void *) b->yy_ch_buf,
(yy_size_t) (b->yy_buf_size + 2) );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = NULL;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart( yyin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if (((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc(
(void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
/* "- 2" to take care of EOB's */
YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2);
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
/* %if-c-only */
/* %not-for-header */
static yy_state_type yy_get_previous_state (void)
/* %endif */
/* %if-c++-only */
/* %endif */
{
yy_state_type yy_current_state;
char *yy_cp;
/* %% [15.0] code to get the start state into yy_current_state goes here */
yy_current_state = (yy_start);
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
/* %% [16.0] code to find the next state goes here */
YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 1468 )
yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
/* %if-c-only */
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
/* %endif */
/* %if-c++-only */
/* %endif */
{
int yy_is_jam;
/* %% [17.0] code to find the next state, and perhaps do backing up, goes here */
char *yy_cp = (yy_c_buf_p);
YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 1468 )
yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
yy_is_jam = (yy_current_state == 1467);
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_UNPUT
/* %if-c-only */
/* %endif */
#endif
/* %if-c-only */
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
/* %endif */
/* %if-c++-only */
/* %endif */
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
int offset = (int) ((yy_c_buf_p) - (yytext_ptr));
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart( yyin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap( ) )
return 0;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve yytext */
(yy_hold_char) = *++(yy_c_buf_p);
/* %% [19.0] update BOL and yylineno */
return c;
}
/* %if-c-only */
#endif /* ifndef YY_NO_INPUT */
/* %endif */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
/* %if-c-only */
void yyrestart (FILE * input_file )
/* %endif */
/* %if-c++-only */
/* %endif */
{
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer( yyin, YY_BUF_SIZE );
}
yy_init_buffer( YY_CURRENT_BUFFER, input_file );
yy_load_buffer_state( );
}
/* %if-c++-only */
/* %endif */
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
/* %if-c-only */
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
/* %endif */
/* %if-c++-only */
/* %endif */
{
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
/* %if-c-only */
static void yy_load_buffer_state (void)
/* %endif */
/* %if-c++-only */
/* %endif */
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
/* %if-c-only */
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
/* %endif */
/* %if-c++-only */
/* %endif */
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
/* %if-c-only */
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
/* %endif */
/* %if-c++-only */
/* %endif */
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer( b, file );
return b;
}
/* %if-c++-only */
/* %endif */
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
*
*/
/* %if-c-only */
void yy_delete_buffer (YY_BUFFER_STATE b )
/* %endif */
/* %if-c++-only */
/* %endif */
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree( (void *) b->yy_ch_buf );
yyfree( (void *) b );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
/* %if-c-only */
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
/* %endif */
/* %if-c++-only */
/* %endif */
{
int oerrno = errno;
yy_flush_buffer( b );
/* %if-c-only */
b->yy_input_file = file;
/* %endif */
/* %if-c++-only */
/* %endif */
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
/* %if-c-only */
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
/* %endif */
/* %if-c++-only */
/* %endif */
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
/* %if-c-only */
void yy_flush_buffer (YY_BUFFER_STATE b )
/* %endif */
/* %if-c++-only */
/* %endif */
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state( );
}
/* %if-c-or-c++ */
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
/* %if-c-only */
void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
/* %endif */
/* %if-c++-only */
/* %endif */
{
if (new_buffer == NULL)
return;
yyensure_buffer_stack();
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/* %endif */
/* %if-c-or-c++ */
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
/* %if-c-only */
void yypop_buffer_state (void)
/* %endif */
/* %if-c++-only */
/* %endif */
{
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* %endif */
/* %if-c-or-c++ */
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
/* %if-c-only */
static void yyensure_buffer_stack (void)
/* %endif */
/* %if-c++-only */
/* %endif */
{
yy_size_t num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/* %endif */
/* %if-c-only */
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return NULL;
b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = NULL;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer( b );
return b;
}
/* %endif */
/* %if-c-only */
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (const char * yystr )
{
return yy_scan_bytes( yystr, (int) strlen(yystr) );
}
/* %endif */
/* %if-c-only */
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = (yy_size_t) (_yybytes_len + 2);
buf = (char *) yyalloc( n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer( buf, n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
/* %endif */
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
/* %if-c-only */
static void yynoreturn yy_fatal_error (const char* msg )
{
fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* %endif */
/* %if-c++-only */
/* %endif */
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = (yy_hold_char); \
(yy_c_buf_p) = yytext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/* %if-c-only */
/* %if-reentrant */
/* %endif */
/** Get the current line number.
*
*/
int yyget_lineno (void)
{
return yylineno;
}
/** Get the input stream.
*
*/
FILE *yyget_in (void)
{
return yyin;
}
/** Get the output stream.
*
*/
FILE *yyget_out (void)
{
return yyout;
}
/** Get the length of the current token.
*
*/
int yyget_leng (void)
{
return yyleng;
}
/** Get the current token.
*
*/
char *yyget_text (void)
{
return yytext;
}
/* %if-reentrant */
/* %endif */
/** Set the current line number.
* @param _line_number line number
*
*/
void yyset_lineno (int _line_number )
{
yylineno = _line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param _in_str A readable stream.
*
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * _in_str )
{
yyin = _in_str ;
}
void yyset_out (FILE * _out_str )
{
yyout = _out_str ;
}
int yyget_debug (void)
{
return yy_flex_debug;
}
void yyset_debug (int _bdebug )
{
yy_flex_debug = _bdebug ;
}
/* %endif */
/* %if-reentrant */
/* %if-bison-bridge */
/* %endif */
/* %endif if-c-only */
/* %if-c-only */
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = NULL;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = NULL;
(yy_init) = 0;
(yy_start) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = NULL;
yyout = NULL;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* %endif */
/* %if-c-only SNIP! this currently causes conflicts with the c++ scanner */
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer( YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state();
}
/* Destroy the stack itself. */
yyfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( );
/* %if-reentrant */
/* %endif */
return 0;
}
/* %endif */
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, const char * s2, int n )
{
int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (const char * s )
{
int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size )
{
return malloc(size);
}
void *yyrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return realloc(ptr, size);
}
void yyfree (void * ptr )
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
/* %if-tables-serialization definitions */
/* %define-yytables The name for this specific scanner's tables. */
#define YYTABLES_NAME "yytables"
/* %endif */
/* %ok-for-header */
#line 1809 "dhcp4_lexer.ll"
using namespace isc::dhcp;
void
Parser4Context::scanStringBegin(const std::string& str, ParserType parser_type)
{
start_token_flag = true;
start_token_value = parser_type;
file_ = "<string>";
sfile_ = 0;
loc_.initialize(&file_);
yy_flex_debug = trace_scanning_;
YY_BUFFER_STATE buffer;
buffer = parser4__scan_bytes(str.c_str(), str.size());
if (!buffer) {
fatal("cannot scan string");
/* fatal() throws an exception so this can't be reached */
}
}
void
Parser4Context::scanFileBegin(FILE * f,
const std::string& filename,
ParserType parser_type)
{
start_token_flag = true;
start_token_value = parser_type;
file_ = filename;
sfile_ = f;
loc_.initialize(&file_);
yy_flex_debug = trace_scanning_;
YY_BUFFER_STATE buffer;
/* See dhcp4_lexer.cc header for available definitions */
buffer = parser4__create_buffer(f, 65536 /*buffer size*/);
if (!buffer) {
fatal("cannot scan file " + filename);
}
parser4__switch_to_buffer(buffer);
}
void
Parser4Context::scanEnd() {
if (sfile_)
fclose(sfile_);
sfile_ = 0;
static_cast<void>(parser4_lex_destroy());
/* Close files */
while (!sfiles_.empty()) {
FILE* f = sfiles_.back();
if (f) {
fclose(f);
}
sfiles_.pop_back();
}
/* Delete states */
while (!states_.empty()) {
parser4__delete_buffer(states_.back());
states_.pop_back();
}
}
void
Parser4Context::includeFile(const std::string& filename) {
if (states_.size() > 10) {
fatal("Too many nested include.");
}
FILE* f = fopen(filename.c_str(), "r");
if (!f) {
fatal("Can't open include file " + filename);
}
if (sfile_) {
sfiles_.push_back(sfile_);
}
sfile_ = f;
states_.push_back(YY_CURRENT_BUFFER);
YY_BUFFER_STATE buffer;
buffer = parser4__create_buffer(f, 65536 /*buffer size*/);
if (!buffer) {
fatal( "Can't scan include file " + filename);
}
parser4__switch_to_buffer(buffer);
files_.push_back(file_);
file_ = filename;
locs_.push_back(loc_);
loc_.initialize(&file_);
BEGIN(INITIAL);
}
namespace {
/** To avoid unused function error */
class Dummy {
/* cppcheck-suppress unusedPrivateFunction */
void dummy() { yy_fatal_error("Fix me: how to disable its definition?"); }
};
}
#endif /* !__clang_analyzer__ */
| 31.63172
| 102
| 0.591329
|
mcr
|
99498d75c3ba0878a454dc0cf2205c6eba578045
| 5,362
|
cpp
|
C++
|
thirdparty/qtiplot/qtiplot/src/matrix/MatrixSizeDialog.cpp
|
hoehnp/SpaceDesignTool
|
9abd34048274b2ce9dbbb685124177b02d6a34ca
|
[
"IJG"
] | 6
|
2018-09-05T12:41:59.000Z
|
2021-07-01T05:34:23.000Z
|
thirdparty/qtiplot/qtiplot/src/matrix/MatrixSizeDialog.cpp
|
hoehnp/SpaceDesignTool
|
9abd34048274b2ce9dbbb685124177b02d6a34ca
|
[
"IJG"
] | 2
|
2015-02-07T19:09:21.000Z
|
2015-08-14T03:15:42.000Z
|
thirdparty/qtiplot/qtiplot/src/matrix/MatrixSizeDialog.cpp
|
hoehnp/SpaceDesignTool
|
9abd34048274b2ce9dbbb685124177b02d6a34ca
|
[
"IJG"
] | 2
|
2015-03-25T15:50:31.000Z
|
2017-12-06T12:16:47.000Z
|
/***************************************************************************
File : MatrixSizeDialog.cpp
Project : QtiPlot
--------------------------------------------------------------------
Copyright : (C) 2004-2008 by Ion Vasilief
Email (use @ for *) : ion_vasilief*yahoo.fr
Description : Matrix dimensions dialog
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02110-1301 USA *
* *
***************************************************************************/
#include "MatrixSizeDialog.h"
#include "MatrixCommand.h"
#include "../DoubleSpinBox.h"
#include <QPushButton>
#include <QLabel>
#include <QGroupBox>
#include <QSpinBox>
#include <QMessageBox>
#include <QLayout>
MatrixSizeDialog::MatrixSizeDialog( Matrix *m, QWidget* parent, Qt::WFlags fl )
: QDialog( parent, fl ),
d_matrix(m)
{
setWindowTitle(tr("QtiPlot - Matrix Dimensions"));
groupBox1 = new QGroupBox(tr("Dimensions"));
QHBoxLayout *topLayout = new QHBoxLayout(groupBox1);
topLayout->addWidget( new QLabel(tr( "Rows" )) );
boxRows = new QSpinBox();
boxRows->setRange(1, 1000000);
topLayout->addWidget(boxRows);
topLayout->addStretch();
topLayout->addWidget( new QLabel(tr( "Columns" )) );
boxCols = new QSpinBox();
boxCols->setRange(1, 1000000);
topLayout->addWidget(boxCols);
groupBox2 = new QGroupBox(tr("Coordinates"));
QGridLayout *centerLayout = new QGridLayout(groupBox2);
centerLayout->addWidget( new QLabel(tr( "X (Columns)" )), 0, 1 );
centerLayout->addWidget( new QLabel(tr( "Y (Rows)" )), 0, 2 );
centerLayout->addWidget( new QLabel(tr( "First" )), 1, 0 );
QLocale locale = m->locale();
boxXStart = new DoubleSpinBox();
boxXStart->setLocale(locale);
centerLayout->addWidget( boxXStart, 1, 1 );
boxYStart = new DoubleSpinBox();
boxYStart->setLocale(locale);
centerLayout->addWidget( boxYStart, 1, 2 );
centerLayout->addWidget( new QLabel(tr( "Last" )), 2, 0 );
boxXEnd = new DoubleSpinBox();
boxXEnd->setLocale(locale);
centerLayout->addWidget( boxXEnd, 2, 1 );
boxYEnd = new DoubleSpinBox();
boxYEnd->setLocale(locale);
centerLayout->addWidget( boxYEnd, 2, 2 );
centerLayout->setRowStretch(3, 1);
QHBoxLayout *bottomLayout = new QHBoxLayout();
bottomLayout->addStretch();
buttonApply = new QPushButton(tr("&Apply"));
buttonApply->setDefault( true );
bottomLayout->addWidget(buttonApply);
buttonOk = new QPushButton(tr("&OK"));
bottomLayout->addWidget( buttonOk );
buttonCancel = new QPushButton(tr("&Cancel"));
bottomLayout->addWidget( buttonCancel );
QVBoxLayout * mainLayout = new QVBoxLayout( this );
mainLayout->addWidget(groupBox1);
mainLayout->addWidget(groupBox2);
mainLayout->addLayout(bottomLayout);
boxRows->setValue(m->numRows());
boxCols->setValue(m->numCols());
boxXStart->setValue(m->xStart());
boxYStart->setValue(m->yStart());
boxXEnd->setValue(m->xEnd());
boxYEnd->setValue(m->yEnd());
connect( buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
connect( buttonOk, SIGNAL(clicked()), this, SLOT(accept() ));
connect( buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
}
void MatrixSizeDialog::apply()
{
double fromX = boxXStart->value();
double toX = boxXEnd->value();
double fromY = boxYStart->value();
double toY = boxYEnd->value();
double oxs = d_matrix->xStart();
double oxe = d_matrix->xEnd();
double oys = d_matrix->yStart();
double oye = d_matrix->yEnd();
if(oxs != fromX || oxe != toX || oys != fromY || oye != toY){
d_matrix->undoStack()->push(new MatrixSetCoordinatesCommand(d_matrix,
oxs, oxe, oys, oye, fromX, toX, fromY, toY,
tr("Set Coordinates x[%1 : %2], y[%3 : %4]").arg(fromX).arg(toX).arg(fromY).arg(toY)));
d_matrix->setCoordinates(fromX, toX, fromY, toY);
}
d_matrix->setDimensions(boxRows->value(), boxCols->value());
}
void MatrixSizeDialog::accept()
{
apply();
close();
}
| 39.426471
| 111
| 0.560425
|
hoehnp
|
9949a2dfaf008c365fbe6fbb12b10e581e36e2fb
| 4,382
|
cpp
|
C++
|
gui/widgets/knob.cpp
|
goossens/ObjectTalk
|
ca1d4f558b5ad2459b376102744d52c6283ec108
|
[
"MIT"
] | 6
|
2021-11-12T15:03:53.000Z
|
2022-01-28T18:30:33.000Z
|
gui/widgets/knob.cpp
|
goossens/ObjectTalk
|
ca1d4f558b5ad2459b376102744d52c6283ec108
|
[
"MIT"
] | null | null | null |
gui/widgets/knob.cpp
|
goossens/ObjectTalk
|
ca1d4f558b5ad2459b376102744d52c6283ec108
|
[
"MIT"
] | null | null | null |
// ObjectTalk Scripting Language
// Copyright (c) 1993-2022 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
//
// Include files
//
#include "ot/function.h"
#include "ot/vm.h"
#include "knob.h"
//
// OtKnobClass::init
//
OtObject callback;
OtObject OtKnobClass::init(size_t count, OtObject* parameters) {
switch (count) {
case 4:
setCallback(parameters[3]);
case 3:
setLabel(parameters[2]->operator std::string());
case 2:
setMargin(parameters[1]->operator int());
case 1:
setTexture(parameters[0]);
case 0:
break;
default:
OtExcept("[Knob] constructor expects up to 4 arguments (not %ld)", count);
}
return nullptr;
}
//
// OtKnobClass::setTexture
//
OtObject OtKnobClass::setTexture(OtObject object) {
// a texture can be a texture object or the name of an inamge file
if (object->isKindOf("Texture")) {
texture = object->cast<OtTextureClass>();
} else if (object->isKindOf("String")) {
texture = OtTextureClass::create();
texture->loadImage(object->operator std::string());
} else {
OtExcept("Expected a [Texture] or [String] object, not a [%s]", object->getType()->getName().c_str());
}
return shared();
}
//
// OtKnobClass::setMargin
//
OtObject OtKnobClass::setMargin(int m) {
margin = m;
return shared();
}
//
// OtKnobClass::setLabel
//
OtObject OtKnobClass::setLabel(const std::string& l) {
label = l;
return shared();
}
//
// OtKnobClass::setCallback
//
OtObject OtKnobClass::setCallback(OtObject c) {
callback = c;
return shared();
}
//
// OtKnobClass::render
//
void OtKnobClass::render() {
// add margin if required
if (margin) {
ImGui::Dummy(ImVec2(0, margin));
}
// ensure we have a texture
if (texture) {
// calculate image dimensions
float width = texture->getWidth();
float fullHeight = texture->getHeight();
float steps = fullHeight / width;
float height = fullHeight / steps;
// calculate position
float indent = ImGui::GetCursorPosX();
float availableSpace = ImGui::GetWindowSize().x - indent;
ImVec2 pos = ImVec2(indent + (availableSpace - width) / 2, ImGui::GetCursorPosY());
// setup new widget
ImGui::PushID((void*) this);
ImGui::SetCursorPos(pos);
ImGui::InvisibleButton("", ImVec2(width, height), 0);
ImGuiIO& io = ImGui::GetIO();
// detect mouse activity
if (ImGui::IsItemActive() && io.MouseDelta.y != 0.0) {
auto newValue = OtClamp(value - io.MouseDelta.y / 2.0, 0.0, 100.0);
// call user callback if value has changed
if (callback && newValue != value) {
OtVM::callMemberFunction(callback, "__call__", OtObjectCreate(value));
}
value = newValue;
}
ImGui::PopID();
// render correct frame of image strip
ImGui::SetCursorPos(pos);
float offset1 = std::floor(value / 100.0 * (steps - 1)) * height;
float offset2 = offset1 + height;
ImGui::Image(
(void*)(intptr_t) texture->getTextureHandle().idx,
ImVec2(width, height),
ImVec2(0, offset1 / fullHeight),
ImVec2(1, offset2 / fullHeight));
// render label if required
if (label.size()) {
ImGui::Dummy(ImVec2(0, 5));
ImVec2 size = ImGui::CalcTextSize(label.c_str());
ImVec2 pos = ImGui::GetCursorPos();
ImGui::SetCursorPos(ImVec2(indent + (availableSpace - size.x) / 2, pos.y));
ImGui::TextUnformatted(label.c_str());
}
}
// add margin if required
if (margin) {
ImGui::Dummy(ImVec2(0, margin));
}
}
//
// OtKnobClass::getMeta
//
OtType OtKnobClass::getMeta() {
static OtType type = nullptr;
if (!type) {
type = OtTypeClass::create<OtKnobClass>("Knob", OtWidgetClass::getMeta());
type->set("__init__", OtFunctionClass::create(&OtKnobClass::init));
type->set("setTexture", OtFunctionClass::create(&OtKnobClass::setTexture));
type->set("setMargin", OtFunctionClass::create(&OtKnobClass::setMargin));
type->set("setLabel", OtFunctionClass::create(&OtKnobClass::setLabel));
type->set("setCallback", OtFunctionClass::create(&OtKnobClass::setCallback));
type->set("setValue", OtFunctionClass::create(&OtKnobClass::setValue));
type->set("getValue", OtFunctionClass::create(&OtKnobClass::getValue));
}
return type;
}
//
// OtKnobClass::create
//
OtKnob OtKnobClass::create() {
OtKnob knob = std::make_shared<OtKnobClass>();
knob->setType(getMeta());
return knob;
}
| 21.586207
| 104
| 0.67298
|
goossens
|
994e733f0a3ca96b7a7c1ed762019b524d211c9f
| 1,206
|
cpp
|
C++
|
hardway/ex2.cpp
|
mgalushka/cpp-start
|
a7af1668291ffd1c1b606310714880dcbefb3ea5
|
[
"MIT"
] | null | null | null |
hardway/ex2.cpp
|
mgalushka/cpp-start
|
a7af1668291ffd1c1b606310714880dcbefb3ea5
|
[
"MIT"
] | null | null | null |
hardway/ex2.cpp
|
mgalushka/cpp-start
|
a7af1668291ffd1c1b606310714880dcbefb3ea5
|
[
"MIT"
] | null | null | null |
#include <string>
#include <iostream>
#include <stdint.h>
#include <stdlib.h>
uint32_t* reverse_array(uint32_t length, uint32_t* input);
void print_array(uint32_t length, uint32_t* input);
int main(int argc, char* argv[]){
std::string str = "This is string";
std::cout << "Length(" << str << ") = " << str.length() << "\n";
uint32_t L = 10;
uint32_t* input = (uint32_t*) malloc(L * sizeof(uint32_t));
for(uint32_t i = 0; i < L; i++){
input[i] = 3 * i;
}
print_array(L, input);
input = reverse_array(L, input);
print_array(L, input);
free(input);
return 0;
}
uint32_t* reverse_array(uint32_t length, uint32_t* input){
if (length <= 1){
return input;
}
uint32_t* result = (uint32_t*) malloc(length * sizeof(uint32_t));
for (uint32_t i = 0; i < length / 2; i++) {
result[length - 1 - i] = input[i];
result[i] = input[length - 1 - i];
}
free(input);
return result;
}
void print_array(uint32_t length, uint32_t* input){
for (uint32_t i = 0; i < length; i++) {
std::cout << input[i];
if (i < (length - 1)){
std::cout << ", ";
}
}
std::cout << "\n";
}
| 24.12
| 69
| 0.554726
|
mgalushka
|
995085d5b9ee461af1ed4d74528789e6d8bef94e
| 7,773
|
cpp
|
C++
|
Motor2D/j1Pathfinding.cpp
|
Gerard346/Game-Dev2019
|
3e927070ff2ba8b07de2dc4d56de63a6ffd4fb84
|
[
"MIT"
] | null | null | null |
Motor2D/j1Pathfinding.cpp
|
Gerard346/Game-Dev2019
|
3e927070ff2ba8b07de2dc4d56de63a6ffd4fb84
|
[
"MIT"
] | null | null | null |
Motor2D/j1Pathfinding.cpp
|
Gerard346/Game-Dev2019
|
3e927070ff2ba8b07de2dc4d56de63a6ffd4fb84
|
[
"MIT"
] | null | null | null |
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1Pathfinding.h"
#include "j1Map.h"
#include <math.h>
#include "j1Input.h"
#include "j1Window.h"
j1Pathfinding::j1Pathfinding() : j1Module()
{
name.create("pathfinding");
}
// Destructor
j1Pathfinding::~j1Pathfinding()
{}
// Called before render is available
bool j1Pathfinding::Awake(const pugi::xml_node& config)
{
bool ret = true;
str_load_tex = (char*)config.child("debug_texture").child_value();
ResetPath();
return ret;
}
bool j1Pathfinding::Start()
{
debug_tex = App->tex->Load(str_load_tex);
return true;
}
bool j1Pathfinding::PreUpdate()
{
return true;
}
bool j1Pathfinding::Update(float f)
{
Draw();
return true;
}
void j1Pathfinding::ResetPath()
{
path.Clear();
frontier.Clear();
visited.clear();
breadcrumbs.clear();
memset(cost_so_far, 0, sizeof(uint) * COST_MAP * COST_MAP);
}
void j1Pathfinding::Path(int x, int y)
{
path.Clear();
iPoint goal = App->map->WorldToMap(x, y);
int goal_index = visited.find(goal);
if (goal_index == -1)
{
return;
}
path.PushBack(goal);
while (true)
{
path.PushBack(breadcrumbs[goal_index]);
goal_index = visited.find(breadcrumbs[goal_index]);
if (visited[goal_index] == breadcrumbs[goal_index])
{
break;
}
}
}
void j1Pathfinding::PropagateASTAR(iPoint origin, iPoint goal)
{
BROFILER_CATEGORY("A star", Profiler::Color::Black);
iPoint map_goal = App->map->WorldToMap(goal.x, goal.y);
ResetPath();
if (walkability_layer == nullptr)
{
return;
}
iPoint map_origin = App->map->WorldToMap(origin.x, origin.y);
frontier.Push(map_origin, 0);
visited.add(map_origin);
breadcrumbs.add(map_origin);
while (frontier.Count() > 0)
{
iPoint curr;
if (frontier.Pop(curr))
{
iPoint neighbors[4];
neighbors[0].create(curr.x + 1, curr.y + 0);
neighbors[1].create(curr.x + 0, curr.y + 1);
neighbors[2].create(curr.x - 1, curr.y + 0);
neighbors[3].create(curr.x + 0, curr.y - 1);
for (uint i = 0; i < 4; ++i)
{
int neighbor_cost = MovementCost(neighbors[i].x, neighbors[i].y);
if (neighbor_cost > 0)
{
if (visited.find(neighbors[i]) == -1)
{
int x_distance = map_goal.x > neighbors[i].x ? map_goal.x - neighbors[i].x : neighbors[i].x - map_goal.x;
int y_distance = map_goal.y > neighbors[i].y ? map_goal.y - neighbors[i].y : neighbors[i].y - map_goal.y;
frontier.Push(neighbors[i], neighbor_cost + cost_so_far[neighbors[i].x][neighbors[i].y] + x_distance + y_distance);
visited.add(neighbors[i]);
breadcrumbs.add(curr);
cost_so_far[neighbors[i].x][neighbors[i].y] = neighbor_cost;
if (neighbors[i].x == map_goal.x && neighbors[i].y == map_goal.y)
{
Path(goal.x, goal.y);
return;
}
}
}
}
}
}
}
bool j1Pathfinding::PropagateASTARf(fPoint origin, fPoint goal, p2DynArray<iPoint>& ref)
{
iPoint map_goal = App->map->WorldToMap(goal.x, goal.y);
ResetPath();
if (walkability_layer == nullptr)
{
return false;
}
iPoint map_origin = App->map->WorldToMap(origin.x, origin.y);
frontier.Push(map_origin, 0);
visited.add(map_origin);
breadcrumbs.add(map_origin);
while (frontier.Count() > 0)
{
iPoint curr;
if (frontier.Pop(curr))
{
iPoint neighbors[4];
neighbors[0].create(curr.x + 1, curr.y + 0);
neighbors[1].create(curr.x + 0, curr.y + 1);
neighbors[2].create(curr.x - 1, curr.y + 0);
neighbors[3].create(curr.x + 0, curr.y - 1);
for (uint i = 0; i < 4; ++i)
{
int neighbor_cost = MovementCost(neighbors[i].x, neighbors[i].y);
if (neighbor_cost > 0)
{
if (visited.find(neighbors[i]) == -1)
{
int x_distance = map_goal.x > neighbors[i].x ? map_goal.x - neighbors[i].x : neighbors[i].x - map_goal.x;
int y_distance = map_goal.y > neighbors[i].y ? map_goal.y - neighbors[i].y : neighbors[i].y - map_goal.y;
frontier.Push(neighbors[i], neighbor_cost + cost_so_far[neighbors[i].x][neighbors[i].y] + x_distance + y_distance);
visited.add(neighbors[i]);
breadcrumbs.add(curr);
cost_so_far[neighbors[i].x][neighbors[i].y] = neighbor_cost;
if (neighbors[i].x == map_goal.x && neighbors[i].y == map_goal.y)
{
Path(goal.x, goal.y);
if (path.Count() > 0)
{
ref.Clear();
for (int i = 0; i < path.Count(); i++)
{
ref.PushBack(*path.At(i));
}
return true;
}
else
{
return false;
}
}
}
}
}
}
}
return false;
}
bool j1Pathfinding::CanReach(const iPoint origin, const iPoint destination)
{
p2List<iPoint> closed_list;
p2PQueue<iPoint> open_list;
open_list.Push(origin,0);
uint distance_to_loop = origin.DistanceManhattan(destination) * DISTANCE_TO_REACH;
while (distance_to_loop > 0)
{
if (PropagateBFS(origin, destination, &closed_list, &open_list))
{
//LOG("TRUE");
closed_list.clear();
open_list.Clear();
return true;
}
distance_to_loop--;
}
//LOG("FALSE");
closed_list.clear();
open_list.Clear();
return false;
}
void j1Pathfinding::TypePathfinding(typePathfinding type)
{
switch (type)
{
case NONE:
break;
case WALK:
walkability_layer = App->map->GetLayer("Walkability");
break;
case FLY:
walkability_layer = App->map->GetLayer("WalkabilityFly");
break;
default:
break;
}
}
bool j1Pathfinding::IsWalkable(const iPoint& position) const
{
return walkability_layer->Get(position.x, position.y) > 0;
}
bool j1Pathfinding::PropagateBFS(const iPoint& origin, const iPoint& destination, p2List<iPoint>* closed, p2PQueue<iPoint>* open_list)
{
if (walkability_layer == nullptr)
{
return false;
}
p2List<iPoint>* closed_list;
if (closed == nullptr)
closed_list = &this->visited;
else closed_list = closed;
p2PQueue<iPoint>* open_l;
if (open_list == nullptr)
open_l = &this->frontier;
else open_l = open_list;
if (closed_list->find(destination) != -1)
{
return true;
}
iPoint point;
if (open_l->start != NULL && closed_list->find(destination) == -1)
{
open_l->Pop(point);
if (open_l->find(point) == -1)
closed_list->add(point);
iPoint neightbour[4];
neightbour[0] = { point.x - 1, point.y };
neightbour[1] = { point.x + 1, point.y };
neightbour[2] = { point.x, point.y - 1 };
neightbour[3] = { point.x, point.y + 1 };
for (uint i = 0; i < 4; i++)
{
if (closed_list->find(neightbour[i]) == -1 && IsWalkable(neightbour[i]))
{
open_l->Push(neightbour[i],0);
closed_list->add(neightbour[i]);
}
}
}
return false;
}
int j1Pathfinding::MovementCost(int x, int y) const
{
int ret = -1;
if (x >= 0 && x < walkability_layer->width && y >= 0 && y < walkability_layer->height)
{
int id = walkability_layer->Get(x, y);
if (id == 6)
{
ret = 1;
}
else
{
ret = -1;
}
}
return ret;
}
void j1Pathfinding::DrawPath()
{
iPoint point;
// Draw visited
p2List_item<iPoint>* item = visited.start;
while (item)
{
point = item->data;
iPoint pos = App->map->MapToWorld(point.x, point.y);
App->render->DrawQuad({ pos.x, pos.y, 16,16}, 255, 0, 0, 150);
item = item->next;
}
// Draw frontier
for (uint i = 0; i < frontier.Count(); ++i)
{
point = *(frontier.Peek(i));
iPoint pos = App->map->MapToWorld(point.x, point.y);
App->render->DrawQuad({ pos.x, pos.y, 16,16 }, 0, 255, 0, 150);
}
// Draw path
for (uint i = 0; i < path.Count(); ++i)
{
iPoint pos = App->map->MapToWorld(path[i].x, path[i].y);
App->render->DrawQuad({ pos.x, pos.y, 16,16 }, 0, 0, 255, 150);
break;
}
}
void j1Pathfinding::Draw()
{
if (debug) {
DrawPath();
}
}
bool j1Pathfinding::CleanUp()
{
LOG("Unloading pathfinding");
ResetPath();
return true;
}
| 20.728
| 134
| 0.63206
|
Gerard346
|
9952033c3c777f60050880690f73804b8b7e1b0c
| 2,516
|
hpp
|
C++
|
dLoad.hpp
|
dyexlzc/CppdynamicLoad
|
14303e2929ecc26aa16ef7f0dad7cc2d71cb3077
|
[
"MIT"
] | null | null | null |
dLoad.hpp
|
dyexlzc/CppdynamicLoad
|
14303e2929ecc26aa16ef7f0dad7cc2d71cb3077
|
[
"MIT"
] | null | null | null |
dLoad.hpp
|
dyexlzc/CppdynamicLoad
|
14303e2929ecc26aa16ef7f0dad7cc2d71cb3077
|
[
"MIT"
] | null | null | null |
#ifndef _DLOAD_HPP
#define _DLOAD_HPP
#include <unordered_map>
#include <string>
#include <dlfcn.h> //加载动态库所需要的头文件
#include "interface.h"
class dynamicLoader
{
class SoWrapper //用来包装指针
{
public:
interface *(*getInstanceFunc)(void);
void *soPtr;
SoWrapper(interface *(*fptr)(void), void *soptr)
{
getInstanceFunc = fptr;
soPtr = soptr;
}
SoWrapper() {}
SoWrapper(const SoWrapper &sw)
{
//自己写一个拷贝构造,否则map不认
this->soPtr = sw.soPtr;
this->getInstanceFunc = sw.getInstanceFunc;
}
};
std::string mSoPath; //so库的根目录
std::unordered_map<std::string, SoWrapper> libInstanceMap; //map储存so指针实现 o(n)的效率
public:
dynamicLoader(const std::string &soPath) : mSoPath(soPath) {}
~dynamicLoader() {}
bool load(const std::string &libName)
{ //加载so库名,即so的全名,【libxxx】.so,成功或者已经加载,则返回true,失败返回false
if(libInstanceMap.count(libName)!=0)return true;
void *soPtr = dlopen((mSoPath + libName).c_str(), RTLD_LAZY);
if (!soPtr)
return false;
if (libInstanceMap.count(libName) != 0)
return true; //如果已经加载过
interface *(*getInstanceFunc)(void); //getInstance的函数指针
getInstanceFunc = (interface * (*)(void)) dlsym(soPtr, "getInstance"); //从so中获取符号,因此必须导出getInstance函数
SoWrapper sw(getInstanceFunc, soPtr); //构建warpper对象
libInstanceMap[libName] = sw;
return true; //存入instanceMap中,下次要再次使用时直接获取即可
}
bool unload(const std::string &libName)
{ //卸载类库
if (isExists(libName))
{
dlclose(libInstanceMap[libName].soPtr); //关闭so文件的调用
libInstanceMap[libName].soPtr = nullptr;
libInstanceMap[libName].getInstanceFunc = nullptr;
libInstanceMap.erase(libName);
}
return true;
}
interface *getInstance(const std::string &libName)
{ //获取实例,实例产生的方式取决于maker中的实现方式
if (isExists(libName))
{
return (interface *)(libInstanceMap[libName].getInstanceFunc()); //返回实例执行的结果
}
return nullptr;
}
bool isExists(const std::string &libName)
{ //判断是否已经加载该so
if (libInstanceMap.count(libName) == 0)
{
return false; //不存在
}
return true;
}
};
#endif
| 32.675325
| 109
| 0.561208
|
dyexlzc
|
995a2f2e82a3c4a6b2fb3ff3d69dd6af5d4cc8c4
| 4,865
|
cpp
|
C++
|
saber/lite/funcs/saber_deconv_act.cpp
|
Shixiaowei02/Anakin
|
f1ea086c5dfa1009ba15a64bc3e30cde07356360
|
[
"Apache-2.0"
] | 1
|
2018-08-03T05:14:27.000Z
|
2018-08-03T05:14:27.000Z
|
saber/lite/funcs/saber_deconv_act.cpp
|
Shixiaowei02/Anakin
|
f1ea086c5dfa1009ba15a64bc3e30cde07356360
|
[
"Apache-2.0"
] | 3
|
2018-06-22T09:08:44.000Z
|
2018-07-04T08:38:30.000Z
|
saber/lite/funcs/saber_deconv_act.cpp
|
Shixiaowei02/Anakin
|
f1ea086c5dfa1009ba15a64bc3e30cde07356360
|
[
"Apache-2.0"
] | 1
|
2021-01-27T07:44:55.000Z
|
2021-01-27T07:44:55.000Z
|
#include "saber/lite/funcs/saber_deconv_act.h"
#include "saber/lite/net/saber_factory_lite.h"
namespace anakin{
namespace saber{
namespace lite{
SaberDeconvAct2D::SaberDeconvAct2D() {
_conv_func = new SaberDeconv2D;
}
SaberDeconvAct2D::SaberDeconvAct2D(const ParamBase *param) {
_conv_func = new SaberDeconv2D;
_param = (const ConvAct2DParam*)param;
/*
if (_param->_flag_act) {
LCHECK_EQ(_param->_act_type, Active_relu, "active type must be relu");
}
*/
this->_flag_param = true;
_conv_func->load_param(&_param->_conv_param);
}
SaberDeconvAct2D::~SaberDeconvAct2D() {
if (this->_flag_create_param) {
delete _param;
_param = nullptr;
}
delete _conv_func;
}
SaberStatus SaberDeconvAct2D::load_param(const ParamBase *param) {
if (this->_flag_create_param) {
delete _param;
_param = nullptr;
this->_flag_create_param = false;
}
_param = (const ConvAct2DParam*)param;
this->_flag_param = true;
_conv_func->set_activation(_param->_flag_act);
return _conv_func->load_param(&_param->_conv_param);
}
SaberStatus SaberDeconvAct2D::load_param(std::istream &stream, const float *weights) {
int weights_size;
int num_out;
int group;
int kw;
int kh;
int stride_w;
int stride_h;
int pad_w;
int pad_h;
int dila_w;
int dila_h;
int flag_bias;
int act_type;
int flag_act;
int w_offset;
int b_offset;
stream >> weights_size >> num_out >> group >> kw >> kh >> stride_w >> stride_h >> \
pad_w >> pad_h >> dila_w >> dila_h >> flag_bias >> act_type >> flag_act >> w_offset >> b_offset;
_param = new ConvAct2DParam(weights_size, num_out, group, kw, kh, \
stride_w, stride_h, pad_w, pad_h, dila_w, dila_h, flag_bias>0, \
(ActiveType)act_type, flag_act>0, \
weights + w_offset, weights + b_offset);
this->_flag_create_param = true;
this->_flag_param = true;
_conv_func->set_activation(flag_act);
return _conv_func->load_param(&_param->_conv_param);
}
#if 0
SaberStatus SaberDeconvAct2D::load_param(FILE *fp, const float *weights) {
int weights_size;
int num_out;
int group;
int kw;
int kh;
int stride_w;
int stride_h;
int pad_w;
int pad_h;
int dila_w;
int dila_h;
int flag_bias;
int act_type;
int flag_act;
int w_offset;
int b_offset;
fscanf(fp, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n",
&weights_size,
&num_out,
&group,
&kw,
&kh,
&stride_w,
&stride_h,
&pad_w,
&pad_h,
&dila_w,
&dila_h,
&flag_bias,
&act_type,
&flag_act,
&w_offset,
&b_offset);
_param = new ConvAct2DParam(weights_size, num_out, group, kw, kh, \
stride_w, stride_h, pad_w, pad_h, dila_w, dila_h, flag_bias>0, \
(ActiveType)act_type, flag_act>0, \
weights + w_offset, weights + b_offset);
this->_flag_create_param = true;
this->_flag_param = true;
return SaberSuccess;
}
#endif
SaberStatus SaberDeconvAct2D::compute_output_shape(const std::vector<Tensor<CPU, AK_FLOAT> *> &inputs,
std::vector<Tensor<CPU, AK_FLOAT> *> &outputs) {
if (!this->_flag_param) {
printf("load conv_act param first\n");
return SaberNotInitialized;
}
return _conv_func->compute_output_shape(inputs, outputs);
}
SaberStatus SaberDeconvAct2D::init(const std::vector<Tensor<CPU, AK_FLOAT> *> &inputs,
std::vector<Tensor<CPU, AK_FLOAT> *> &outputs,
Context &ctx) {
if (!this->_flag_param) {
printf("load conv_act param first\n");
return SaberNotInitialized;
}
if (_param->_flag_act) {
_conv_func->set_activation(true);
//SABER_CHECK(_conv_func->set_activation(true));
} else {
_conv_func->set_activation(false);
// SABER_CHECK(_conv_func->set_activation(false));
}
// LOG(INFO) << "Deconv act";
//_conv_func->set_activation(_param->_flag_act);
this->_flag_init = true;
#if defined(ENABLE_OP_TIMER) || defined(ENABLE_DEBUG)
_conv_func->set_op_name(this->get_op_name());
#endif
return _conv_func->init(inputs, outputs, ctx);
}
SaberStatus SaberDeconvAct2D::dispatch(const std::vector<Tensor<CPU, AK_FLOAT> *> &inputs,
std::vector<Tensor<CPU, AK_FLOAT> *> &outputs) {
if (!this->_flag_init) {
printf("init conv_act first\n");
return SaberNotInitialized;
}
return _conv_func->dispatch(inputs, outputs);
}
REGISTER_LAYER_CLASS(SaberDeconvAct2D);
} //namespace lite
} //namespace saber
} //namespace anakin
| 30.030864
| 107
| 0.619322
|
Shixiaowei02
|
995c2f7a0f20072e7d8039748ef224a5e5949dba
| 4,993
|
hh
|
C++
|
src/net/REDQueue.hh
|
drexelwireless/dragonradio
|
885abd68d56af709e7a53737352641908005c45b
|
[
"MIT"
] | 8
|
2020-12-05T20:30:54.000Z
|
2022-01-22T13:32:14.000Z
|
src/net/REDQueue.hh
|
drexelwireless/dragonradio
|
885abd68d56af709e7a53737352641908005c45b
|
[
"MIT"
] | 3
|
2020-10-28T22:15:27.000Z
|
2021-01-27T14:43:41.000Z
|
src/net/REDQueue.hh
|
drexelwireless/dragonradio
|
885abd68d56af709e7a53737352641908005c45b
|
[
"MIT"
] | null | null | null |
#ifndef REDQUEUE_HH_
#define REDQUEUE_HH_
#include <list>
#include <random>
#include "logging.hh"
#include "Clock.hh"
#include "net/Queue.hh"
#include "net/SizedQueue.hh"
/** @brief An Adaptive RED queue. */
/** See the paper Random Early Detection Gateways for Congestion Avoidance */
template <class T>
class REDQueue : public SizedQueue<T> {
public:
using const_iterator = typename std::list<T>::const_iterator;
using Queue<T>::canPop;
using SizedQueue<T>::stop;
using SizedQueue<T>::drop;
using SizedQueue<T>::done_;
using SizedQueue<T>::size_;
using SizedQueue<T>::hi_priority_flows_;
using SizedQueue<T>::m_;
using SizedQueue<T>::cond_;
using SizedQueue<T>::hiq_;
using SizedQueue<T>::q_;
REDQueue(bool gentle,
size_t min_thresh,
size_t max_thresh,
double max_p,
double w_q)
: SizedQueue<T>()
, gentle_(gentle)
, min_thresh_(min_thresh)
, max_thresh_(max_thresh)
, max_p_(max_p)
, w_q_(w_q)
, count_(-1)
, avg_(0)
, gen_(std::random_device()())
, dist_(0, 1.0)
{
}
REDQueue() = delete;
virtual ~REDQueue()
{
stop();
}
/** @brief Get flag indicating whether or not to be gentle */
/** See:
* https://www.icir.org/floyd/notes/test-suite-red.txt
*/
bool getGentle(void) const
{
return gentle_;
}
/** @brief Set flag indicating whether or not to be gentle */
void setGentle(bool gentle)
{
gentle_ = gentle;
}
/** @brief Get minimum threshold */
size_t getMinThresh(void) const
{
return min_thresh_;
}
/** @brief Set minimum threshold */
void setMinThresh(size_t min_thresh)
{
min_thresh_ = min_thresh;
}
/** @brief Get maximum threshold */
size_t getMaxThresh(void) const
{
return max_thresh_;
}
/** @brief Set maximum threshold */
void setMaxThresh(size_t max_thresh)
{
max_thresh_ = max_thresh;
}
/** @brief Get maximum drop probability */
double getMaxP(void) const
{
return max_p_;
}
/** @brief Set maximum drop probability */
void setMaxP(double max_p)
{
max_p_ = max_p;
}
/** @brief Get queue qeight */
double getQueueWeight(void) const
{
return max_p_;
}
/** @brief Set queue qeight */
void setQueueWeight(double w_q)
{
w_q_ = w_q;
}
virtual void reset(void) override
{
std::lock_guard<std::mutex> lock(m_);
done_ = false;
size_ = 0;
count_ = 0;
hiq_.clear();
q_.clear();
}
virtual void push(T&& item) override
{
{
std::lock_guard<std::mutex> lock(m_);
if (item->flow_uid && hi_priority_flows_.find(*item->flow_uid) != hi_priority_flows_.end()) {
hiq_.emplace_back(std::move(item));
return;
}
bool mark = false;
// Calculate new average queue size
if (size_ == 0)
avg_ = 0;
else
avg_ = (1 - w_q_)*avg_ + w_q_*size_;
// Determine whether or not to mark packet
if (avg_ < min_thresh_) {
count_ = -1;
} else if (min_thresh_ <= avg_ && avg_ < max_thresh_) {
count_++;
double p_b = max_p_*(avg_ - min_thresh_)/(max_thresh_ - min_thresh_);
double p_a = p_b/(1.0 - count_*p_b);
if (dist_(gen_) < p_a) {
mark = true;
count_ = 0;
}
} else if (gentle_ && avg_ < 2*max_thresh_) {
count_++;
double p_a = max_p_*(avg_ - max_thresh_)/max_thresh_;
if (dist_(gen_) < p_a) {
mark = true;
count_ = 0;
}
} else {
mark = true;
count_ = 0;
}
if (mark)
drop(item);
if (!mark) {
size_ += item->payload_size;
q_.emplace_back(std::move(item));
}
}
cond_.notify_one();
}
protected:
/** @brief Gentle flag. */
bool gentle_;
/** @brief Minimum threshold. */
size_t min_thresh_;
/** @brief Maximum threshold. */
size_t max_thresh_;
/** @brief Maximum drop probability. */
double max_p_;
/** @brief Queue weight. */
double w_q_;
/** @brief Packets since last marked packet. */
int count_;
/** @brief Average size of queue (bytes). */
double avg_;
/** @brief Random number generator */
std::mt19937 gen_;
/** @brief Uniform 0-1 real distribution */
std::uniform_real_distribution<double> dist_;
};
using REDNetQueue = REDQueue<std::shared_ptr<NetPacket>>;
#endif /* REDQUEUE_HH_ */
| 22.799087
| 105
| 0.530342
|
drexelwireless
|
995d417fdaf7d5b02113724963860c36fb84b251
| 3,208
|
hpp
|
C++
|
test/matrix/blas/matsub.hpp
|
rigarash/monolish-debian-package
|
70b4917370184bcf07378e1907c5239a1ad9579b
|
[
"Apache-2.0"
] | 172
|
2021-04-05T10:04:40.000Z
|
2022-03-28T14:30:38.000Z
|
test/matrix/blas/matsub.hpp
|
rigarash/monolish-debian-package
|
70b4917370184bcf07378e1907c5239a1ad9579b
|
[
"Apache-2.0"
] | 96
|
2021-04-06T01:53:44.000Z
|
2022-03-09T07:27:09.000Z
|
test/matrix/blas/matsub.hpp
|
termoshtt/monolish
|
1cba60864002b55bc666da9baa0f8c2273578e01
|
[
"Apache-2.0"
] | 8
|
2021-04-05T13:21:07.000Z
|
2022-03-09T23:24:06.000Z
|
#include "../../test_utils.hpp"
template <typename T>
void ans_matsub(const monolish::matrix::Dense<T> &A,
const monolish::matrix::Dense<T> &B,
monolish::matrix::Dense<T> &C) {
if (A.get_row() != B.get_row()) {
std::runtime_error("A.row != B.row");
}
if (A.get_col() != B.get_col()) {
std::runtime_error("A.col != B.col");
}
// MN=MN+MN
int M = A.get_row();
int N = A.get_col();
for (int i = 0; i < A.get_nnz(); i++) {
C.val[i] = A.val[i] - B.val[i];
}
}
template <typename MAT_A, typename MAT_B, typename MAT_C, typename T>
bool test_send_matsub(const size_t M, const size_t N, double tol) {
size_t nnzrow = 27;
if ((nnzrow < M) && (nnzrow < N)) {
nnzrow = 27;
} else {
nnzrow = std::min({M, N}) - 1;
}
monolish::matrix::COO<T> seedA =
monolish::util::random_structure_matrix<T>(M, N, nnzrow, 1.0);
MAT_A A(seedA);
MAT_B B(seedA);
MAT_C C(seedA);
monolish::matrix::Dense<T> AA(seedA);
monolish::matrix::Dense<T> BB(seedA);
monolish::matrix::Dense<T> CC(seedA);
ans_matsub(AA, BB, CC);
monolish::matrix::COO<T> ansC(CC);
monolish::util::send(A, B, C);
monolish::blas::matsub(A, B, C);
C.recv();
monolish::matrix::COO<T> resultC(C);
return ans_check<T>(__func__, A.type(), resultC.val.data(), ansC.val.data(),
ansC.get_nnz(), tol);
}
template <typename MAT_A, typename MAT_B, typename MAT_C, typename T>
bool test_send_matsub_linearoperator(const size_t M, const size_t N,
double tol) {
size_t nnzrow = 27;
if ((nnzrow < M) && (nnzrow < N)) {
nnzrow = 27;
} else {
nnzrow = std::min({M, N}) - 1;
}
monolish::matrix::COO<T> seedA =
monolish::util::random_structure_matrix<T>(M, N, nnzrow, 1.0);
monolish::matrix::CRS<T> A1(seedA);
monolish::matrix::CRS<T> B1(seedA);
monolish::matrix::CRS<T> C1(seedA);
monolish::matrix::Dense<T> AA(seedA);
monolish::matrix::Dense<T> BB(seedA);
monolish::matrix::Dense<T> CC(seedA);
ans_matsub(AA, BB, CC);
monolish::matrix::COO<T> ansC(CC);
monolish::util::send(A1, B1, C1);
MAT_A A(A1);
MAT_B B(B1);
MAT_C C(C1);
monolish::blas::matsub(A, B, C);
C.recv();
monolish::matrix::COO<T> resultC(C);
return ans_check<T>(__func__, A.type(), resultC.val.data(), ansC.val.data(),
ansC.get_nnz(), tol);
}
template <typename MAT_A, typename MAT_B, typename MAT_C, typename T>
bool test_matsub(const size_t M, const size_t N, double tol) {
size_t nnzrow = 27;
if ((nnzrow < M) && (nnzrow < N)) {
nnzrow = 27;
} else {
nnzrow = std::min({M, N}) - 1;
}
monolish::matrix::COO<T> seedA =
monolish::util::random_structure_matrix<T>(M, N, nnzrow, 1.0);
MAT_A A(seedA);
MAT_B B(seedA);
MAT_C C(seedA);
monolish::matrix::Dense<T> AA(seedA);
monolish::matrix::Dense<T> BB(seedA);
monolish::matrix::Dense<T> CC(seedA);
ans_matsub(AA, BB, CC);
monolish::matrix::COO<T> ansC(CC);
monolish::blas::matsub(A, B, C);
monolish::matrix::COO<T> resultC(C);
return ans_check<T>(__func__, A.type(), resultC.val.data(), ansC.val.data(),
ansC.get_nnz(), tol);
}
| 25.259843
| 78
| 0.595387
|
rigarash
|
996460e59d36a608dfaff28a701efe1942d69542
| 2,024
|
cpp
|
C++
|
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/ive/Viewport.cpp
|
UM-ARM-Lab/mab_ms
|
f199f05b88060182cfbb47706bd1ff3479032c43
|
[
"BSD-2-Clause"
] | 3
|
2018-08-20T12:12:43.000Z
|
2021-06-06T09:43:27.000Z
|
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/ive/Viewport.cpp
|
UM-ARM-Lab/mab_ms
|
f199f05b88060182cfbb47706bd1ff3479032c43
|
[
"BSD-2-Clause"
] | null | null | null |
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/ive/Viewport.cpp
|
UM-ARM-Lab/mab_ms
|
f199f05b88060182cfbb47706bd1ff3479032c43
|
[
"BSD-2-Clause"
] | 1
|
2022-03-31T03:12:23.000Z
|
2022-03-31T03:12:23.000Z
|
/**********************************************************************
*
* FILE: Viewport.cpp
*
* DESCRIPTION: Read/Write osg::Viewport in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerated
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 21.3.2003
*
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
#include "Viewport.h"
#include "Object.h"
using namespace ive;
void Viewport::write(DataOutputStream* out){
// Write Viewport's identification.
out->writeInt(IVEVIEWPORT);
// If the osg class is inherited by any other class we should also write this to file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->write(out);
}
else
throw Exception("Viewport::write(): Could not cast this osg::Viewport to an osg::Object.");
// Write Viewport's properties.
out->writeInt(static_cast<int>(x()));
out->writeInt(static_cast<int>(y()));
out->writeInt(static_cast<int>(width()));
out->writeInt(static_cast<int>(height()));
}
void Viewport::read(DataInputStream* in){
// Peek on Viewport's identification.
int id = in->peekInt();
if(id == IVEVIEWPORT){
// Read Viewport's identification.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->read(in);
}
else
throw Exception("Viewport::read(): Could not cast this osg::Viewport to an osg::Object.");
// Read Viewport's properties
x() = in->readInt();
y() = in->readInt();
width() = in->readInt();
height() = in->readInt();
}
else{
throw Exception("Viewport::read(): Expected Viewport identification.");
}
}
| 31.625
| 102
| 0.552372
|
UM-ARM-Lab
|