hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
โ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
โ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
โ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
โ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
โ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
โ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
โ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
โ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
โ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c637af69d097f5019a95a19120f626dc1e8250aa
| 663
|
hpp
|
C++
|
extras/CAEN/include/CAENFlashException.hpp
|
flagarde/YAODAQ
|
851df4aa32b8695c4706bb3ec9f353f4461c9cad
|
[
"MIT"
] | null | null | null |
extras/CAEN/include/CAENFlashException.hpp
|
flagarde/YAODAQ
|
851df4aa32b8695c4706bb3ec9f353f4461c9cad
|
[
"MIT"
] | 11
|
2021-05-14T19:50:27.000Z
|
2022-03-31T07:19:41.000Z
|
extras/CAEN/include/CAENFlashException.hpp
|
flagarde/YAODAQ
|
851df4aa32b8695c4706bb3ec9f353f4461c9cad
|
[
"MIT"
] | 5
|
2021-05-11T13:30:30.000Z
|
2021-05-26T19:57:22.000Z
|
#pragma once
#include "Exception.hpp"
namespace CAEN
{
enum FLASH_API_ERROR_CODES : int_least32_t
{
SUCCESS = 0,
ACCESS_FAILED = -1,
PARAMETER_NOT_ALLOWED = -2,
FILE_OPEN_ERROR = -3,
MALLOC_ERROR = -4,
UNINITIALIZED = -5,
NOT_IMPLEMENTED = -6,
UNSUPPORTED_FLASH_DEVICE = -7
};
class CAENFlashException: public yaodaq::Exception
{
public:
CAENFlashException(const int_least32_t& code, const source_location& location = source_location::current());
private:
CAENFlashException() = delete;
const char* errorStrings(const int_least32_t& code);
};
} // namespace CAEN
| 22.1
| 110
| 0.656109
|
flagarde
|
c639773af75377d6274e825e3cbaafc1df93caeb
| 662
|
cpp
|
C++
|
luogu/codes/P1226.cpp
|
Tony031218/OI
|
562f5f45d0448f4eab77643b99b825405a123d92
|
[
"MIT"
] | 1
|
2021-02-22T03:39:24.000Z
|
2021-02-22T03:39:24.000Z
|
luogu/codes/P1226.cpp
|
Tony031218/OI
|
562f5f45d0448f4eab77643b99b825405a123d92
|
[
"MIT"
] | null | null | null |
luogu/codes/P1226.cpp
|
Tony031218/OI
|
562f5f45d0448f4eab77643b99b825405a123d92
|
[
"MIT"
] | null | null | null |
/*************************************************************
* > File Name : P1226.cpp
* > Author : Tony
* > Created Time : 2019/05/07 15:29:41
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL b, p, k;
LL pow_mod(LL a, LL p, LL n) {
if (p == 0 && n == 1) return 0;
if (p == 0) return 1;
LL ans = pow_mod(a, p / 2, n); ans = ans * ans % n;
if (p % 2 == 1) ans = ans * a % n;
return ans;
}
int main() {
scanf("%lld %lld %lld", &b, &p, &k);
printf("%lld^%lld mod %lld=%lld", b, p, k, pow_mod(b, p, k));
return 0;
}
| 26.48
| 65
| 0.39426
|
Tony031218
|
c63a3fcc62e822c9df1a52f796b4cdf04490ed5b
| 289
|
cpp
|
C++
|
Backup/testappBackup.cpp
|
erzu12/Minerva-Engine
|
8e280946d561d31a0e09fe9d576dfca1412cd9e3
|
[
"Apache-2.0"
] | null | null | null |
Backup/testappBackup.cpp
|
erzu12/Minerva-Engine
|
8e280946d561d31a0e09fe9d576dfca1412cd9e3
|
[
"Apache-2.0"
] | null | null | null |
Backup/testappBackup.cpp
|
erzu12/Minerva-Engine
|
8e280946d561d31a0e09fe9d576dfca1412cd9e3
|
[
"Apache-2.0"
] | null | null | null |
#include "minerva.h"
#include <iostream>
class Testapp : public Core
{
public:
Testapp()
{
}
~Testapp()
{
}
Log log;
void Update(UpdateEvent* updateEvent) override
{
}
// void Start(StartEvent* startEvent) override
// {
// }
};
Core* GameInit(){
return new Testapp();
}
| 10.321429
| 47
| 0.633218
|
erzu12
|
c63b2e19b704532e353fd351a3ea4ee464e5c16d
| 14,753
|
hpp
|
C++
|
src/game.hpp
|
assasinwar9/Barony
|
c67c01de1168db1c5a2edad98b23cfff9f999187
|
[
"FTL",
"Zlib",
"MIT"
] | 373
|
2016-06-28T06:56:46.000Z
|
2022-03-23T02:32:54.000Z
|
src/game.hpp
|
assasinwar9/Barony
|
c67c01de1168db1c5a2edad98b23cfff9f999187
|
[
"FTL",
"Zlib",
"MIT"
] | 361
|
2016-07-06T19:09:25.000Z
|
2022-03-26T14:14:19.000Z
|
src/game.hpp
|
addictgamer/Barony
|
c67c01de1168db1c5a2edad98b23cfff9f999187
|
[
"FTL",
"Zlib",
"MIT"
] | 129
|
2016-06-29T09:02:49.000Z
|
2022-01-23T09:56:06.000Z
|
/*-------------------------------------------------------------------------------
BARONY
File: game.hpp
Desc: header file for the game
Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved.
See LICENSE for details.
-------------------------------------------------------------------------------*/
#pragma once
#include <vector>
#include <random>
#include <chrono>
#ifdef STEAMWORKS
#include <steam/steam_api.h>
#include "steam.hpp"
#endif
// REMEMBER TO CHANGE THIS WITH EVERY NEW OFFICIAL VERSION!!!
#define VERSION "v3.3.7"
#define GAME_CODE
//#define MAX_FPS_LIMIT 60 //TODO: Make this configurable.
class Entity;
#define DEBUG 1
#define ENTITY_PACKET_LENGTH 46
#define NET_PACKET_SIZE 512
// impulses (bound keystrokes, mousestrokes, and joystick/game controller strokes) //TODO: Player-by-player basis.
extern Uint32 impulses[NUMIMPULSES];
extern Uint32 joyimpulses[NUM_JOY_IMPULSES]; //Joystick/gamepad only impulses.
extern int reversemouse;
extern real_t mousespeed;
void handleEvents(void);
void startMessages();
// net packet send
typedef struct packetsend_t
{
UDPsocket sock;
int channel;
UDPpacket* packet;
int num;
int tries;
int hostnum;
} packetsend_t;
extern list_t safePacketsSent;
extern std::unordered_map<int, Uint32> safePacketsReceivedMap[MAXPLAYERS];
extern bool receivedclientnum;
extern Uint32 clientplayer;
extern Sint32 numplayers;
extern Sint32 clientnum;
extern bool intro;
extern int introstage;
extern bool gamePaused;
extern bool fadeout, fadefinished;
extern int fadealpha;
extern Entity* client_selected[MAXPLAYERS];
extern bool inrange[MAXPLAYERS];
extern bool deleteallbuttons;
extern Sint32 client_classes[MAXPLAYERS];
extern Uint32 client_keepalive[MAXPLAYERS];
extern Uint16 portnumber;
extern list_t messages;
extern list_t command_history;
extern node_t* chosen_command;
extern bool command;
extern bool noclip, godmode, buddhamode;
extern bool everybodyfriendly;
extern bool combat, combattoggle;
extern bool assailant[MAXPLAYERS];
extern bool oassailant[MAXPLAYERS];
extern int assailantTimer[MAXPLAYERS];
static const int COMBAT_MUSIC_COOLDOWN = 200; // 200 ticks of combat music before it fades away.
extern list_t removedEntities;
extern list_t entitiesToDelete[MAXPLAYERS];
extern char maptoload[256], configtoload[256];
extern bool loadingmap, loadingconfig;
extern int startfloor;
extern bool skipintro;
extern Uint32 uniqueGameKey;
// definitions
extern bool showfps;
extern real_t t, ot, frameval[AVERAGEFRAMES];
extern Uint32 cycles, pingtime;
extern Uint32 timesync;
extern real_t fps;
static const int NUMCLASSES = 21;
#define NUMRACES 13
#define NUMPLAYABLERACES 9
extern char address[64];
extern bool loadnextlevel;
extern int skipLevelsOnLoad;
extern bool loadingSameLevelAsCurrent;
extern std::string loadCustomNextMap;
extern Uint32 forceMapSeed;
extern int currentlevel;
extern bool secretlevel;
extern bool darkmap;
extern int shaking, bobbing;
extern int musvolume;
extern SDL_Surface* title_bmp;
extern SDL_Surface* titleDefault_bmp;
extern SDL_Surface* logo_bmp;
extern SDL_Surface* cursor_bmp;
extern SDL_Surface* cross_bmp;
extern SDL_Surface* selected_cursor_bmp;
extern SDL_Surface* controllerglyphs1_bmp;
extern SDL_Surface* skillIcons_bmp;
enum PlayerClasses : int
{
CLASS_BARBARIAN,
CLASS_WARRIOR,
CLASS_HEALER,
CLASS_ROGUE,
CLASS_WANDERER,
CLASS_CLERIC,
CLASS_MERCHANT,
CLASS_WIZARD,
CLASS_ARCANIST,
CLASS_JOKER,
CLASS_SEXTON,
CLASS_NINJA,
CLASS_MONK,
CLASS_CONJURER,
CLASS_ACCURSED,
CLASS_MESMER,
CLASS_BREWER,
CLASS_MACHINIST,
CLASS_PUNISHER,
CLASS_SHAMAN,
CLASS_HUNTER
};
static const int CLASS_SHAMAN_NUM_STARTING_SPELLS = 15;
enum PlayerRaces : int
{
RACE_HUMAN,
RACE_SKELETON,
RACE_VAMPIRE,
RACE_SUCCUBUS,
RACE_GOATMAN,
RACE_AUTOMATON,
RACE_INCUBUS,
RACE_GOBLIN,
RACE_INSECTOID,
RACE_RAT,
RACE_TROLL,
RACE_SPIDER,
RACE_IMP
};
enum ESteamLeaderboardTitles : int
{
LEADERBOARD_NONE,
LEADERBOARD_NORMAL_TIME,
LEADERBOARD_NORMAL_SCORE,
LEADERBOARD_MULTIPLAYER_TIME,
LEADERBOARD_MULTIPLAYER_SCORE,
LEADERBOARD_HELL_TIME,
LEADERBOARD_HELL_SCORE,
LEADERBOARD_HARDCORE_TIME,
LEADERBOARD_HARDCORE_SCORE,
LEADERBOARD_CLASSIC_TIME,
LEADERBOARD_CLASSIC_SCORE,
LEADERBOARD_CLASSIC_HARDCORE_TIME,
LEADERBOARD_CLASSIC_HARDCORE_SCORE,
LEADERBOARD_MULTIPLAYER_CLASSIC_TIME,
LEADERBOARD_MULTIPLAYER_CLASSIC_SCORE,
LEADERBOARD_MULTIPLAYER_HELL_TIME,
LEADERBOARD_MULTIPLAYER_HELL_SCORE,
LEADERBOARD_DLC_NORMAL_TIME,
LEADERBOARD_DLC_NORMAL_SCORE,
LEADERBOARD_DLC_MULTIPLAYER_TIME,
LEADERBOARD_DLC_MULTIPLAYER_SCORE,
LEADERBOARD_DLC_HELL_TIME,
LEADERBOARD_DLC_HELL_SCORE,
LEADERBOARD_DLC_HARDCORE_TIME,
LEADERBOARD_DLC_HARDCORE_SCORE,
LEADERBOARD_DLC_CLASSIC_TIME,
LEADERBOARD_DLC_CLASSIC_SCORE,
LEADERBOARD_DLC_CLASSIC_HARDCORE_TIME,
LEADERBOARD_DLC_CLASSIC_HARDCORE_SCORE,
LEADERBOARD_DLC_MULTIPLAYER_CLASSIC_TIME,
LEADERBOARD_DLC_MULTIPLAYER_CLASSIC_SCORE,
LEADERBOARD_DLC_MULTIPLAYER_HELL_TIME,
LEADERBOARD_DLC_MULTIPLAYER_HELL_SCORE
};
bool achievementUnlocked(const char* achName);
void steamAchievement(const char* achName);
void steamUnsetAchievement(const char* achName);
void steamAchievementClient(int player, const char* achName);
void steamAchievementEntity(Entity* my, const char* achName); // give steam achievement to an entity, and check for valid player info.
void steamStatisticUpdate(int statisticNum, ESteamStatTypes type, int value);
void steamStatisticUpdateClient(int player, int statisticNum, ESteamStatTypes type, int value);
void steamIndicateStatisticProgress(int statisticNum, ESteamStatTypes type);
void freePlayerEquipment(int x);
void pauseGame(int mode, int ignoreplayer);
int initGame();
void deinitGame();
Uint32 timerCallback(Uint32 interval, void* param);
void handleButtons(void);
void gameLogic(void);
// behavior function prototypes:
void actAnimator(Entity* my);
void actRotate(Entity* my);
void actLiquid(Entity* my);
void actEmpty(Entity* my);
void actFurniture(Entity* my);
void actMCaxe(Entity* my);
void actDoorFrame(Entity* my);
void actDeathCam(Entity* my);
void actPlayerLimb(Entity* my);
void actTorch(Entity* my);
void actCrystalShard(Entity* my);
void actDoor(Entity* my);
void actHudWeapon(Entity* my);
void actHudArm(Entity* my);
void actHudShield(Entity* my);
void actHudAdditional(Entity* my);
void actHudArrowModel(Entity* my);
void actItem(Entity* my);
void actGoldBag(Entity* my);
void actGib(Entity* my);
Entity* spawnGib(Entity* parentent, int customGibSprite = -1);
Entity* spawnGibClient(Sint16 x, Sint16 y, Sint16 z, Sint16 sprite);
void serverSpawnGibForClient(Entity* gib);
void actLadder(Entity* my);
void actLadderUp(Entity* my);
void actPortal(Entity* my);
void actWinningPortal(Entity* my);
void actFlame(Entity* my);
void actCampfire(Entity* my);
Entity* spawnFlame(Entity* parentent, Sint32 sprite);
void actMagic(Entity* my);
Entity* castMagic(Entity* parentent);
void actSprite(Entity* my);
void actSpriteNametag(Entity* my);
void actSpriteWorldTooltip(Entity* my);
void actSleepZ(Entity* my);
Entity* spawnBang(Sint16 x, Sint16 y, Sint16 z);
Entity* spawnExplosion(Sint16 x, Sint16 y, Sint16 z);
Entity* spawnExplosionFromSprite(Uint16 sprite, Sint16 x, Sint16 y, Sint16 z);
Entity* spawnSleepZ(Sint16 x, Sint16 y, Sint16 z);
Entity* spawnFloatingSpriteMisc(int sprite, Sint16 x, Sint16 y, Sint16 z);
void actArrow(Entity* my);
void actBoulder(Entity* my);
void actBoulderTrap(Entity* my);
void actBoulderTrapEast(Entity* my);
void actBoulderTrapWest(Entity* my);
void actBoulderTrapSouth(Entity* my);
void actBoulderTrapNorth(Entity* my);
void actHeadstone(Entity* my);
void actThrown(Entity* my);
void actBeartrap(Entity* my);
void actBeartrapLaunched(Entity* my);
void actBomb(Entity* my);
void actDecoyBox(Entity* my);
void actDecoyBoxCrank(Entity* my);
void actSpearTrap(Entity* my);
void actWallBuster(Entity* my);
void actWallBuilder(Entity* my);
void actPowerCrystalBase(Entity* my);
void actPowerCrystal(Entity* my);
void actPowerCrystalParticleIdle(Entity* my);
void actPedestalBase(Entity* my);
void actPedestalOrb(Entity* my);
void actMidGamePortal(Entity* my);
void actCustomPortal(Entity* my);
void actTeleporter(Entity* my);
void actMagicTrapCeiling(Entity* my);
void actExpansionEndGamePortal(Entity* my);
void actSoundSource(Entity* my);
void actLightSource(Entity* my);
void actSignalTimer(Entity* my);
void startMessages();
bool frameRateLimit(Uint32 maxFrameRate, bool resetAccumulator = true);
extern Uint32 networkTickrate;
extern bool gameloopFreezeEntities;
extern Uint32 serverSchedulePlayerHealthUpdate;
#define TOUCHRANGE 32
#define STRIKERANGE 24
#define XPSHARERANGE 256
// function prototypes for charclass.c:
void initClass(int player);
void initShapeshiftHotbar(int player);
void deinitShapeshiftHotbar(int player);
bool playerUnlockedShamanSpell(int player, Item* item);
extern char last_ip[64];
extern char last_port[64];
//TODO: Maybe increase with level or something?
//TODO: Pause health regen during combat?
#define HEAL_TIME 600 //10 seconds. //Original time: 3600 (1 minute)
#define MAGIC_REGEN_TIME 300 // 5 seconds
#define DEFAULT_HP 30
#define DEFAULT_MP 30
#define HP_MOD 5
#define MP_MOD 5
#define SPRITE_FLAME 13
#define SPRITE_CRYSTALFLAME 96
#define MAXCHARGE 30 // charging up weapons
static const int BASE_MELEE_DAMAGE = 8;
static const int BASE_RANGED_DAMAGE = 7;
static const int BASE_THROWN_DAMAGE = 6;
static const int BASE_PLAYER_UNARMED_DAMAGE = 8;
extern bool spawn_blood;
extern bool capture_mouse; //Useful for debugging when the game refuses to release the mouse when it's crashed.
#define LEVELSFILE "maps/levels.txt"
#define SECRETLEVELSFILE "maps/secretlevels.txt"
#define LENGTH_OF_LEVEL_REGION 5
#define TICKS_PER_SECOND 50
static const Uint8 TICKS_TO_PROCESS_FIRE = 30; // The amount of ticks needed until the 'BURNING' Status Effect is processed (char_fire % TICKS_TO_PROCESS_FIRE == 0)
static const int EFFECT_WITHDRAWAL_BASE_TIME = TICKS_PER_SECOND * 60 * 8; // 8 minutes base withdrawal time.
static const std::string PLAYERNAMES_MALE_FILE = "playernames-male.txt";
static const std::string PLAYERNAMES_FEMALE_FILE = "playernames-female.txt";
extern std::vector<std::string> randomPlayerNamesMale;
extern std::vector<std::string> randomPlayerNamesFemale;
extern bool enabledDLCPack1;
extern bool enabledDLCPack2;
extern std::vector<std::string> physFSFilesInDirectory;
void loadRandomNames();
void mapLevel(int player);
void mapFoodOnLevel(int player);
class TileEntityListHandler
{
private:
static const int kMaxMapDimension = 256;
public:
list_t gridEntities[kMaxMapDimension][kMaxMapDimension];
void clearTile(int x, int y);
void emptyGridEntities();
list_t* getTileList(int x, int y);
node_t* addEntity(Entity& entity);
node_t* updateEntity(Entity& entity);
std::vector<list_t*> getEntitiesWithinRadius(int u, int v, int radius);
std::vector<list_t*> getEntitiesWithinRadiusAroundEntity(Entity* entity, int radius);
TileEntityListHandler()
{
for ( int i = 0; i < kMaxMapDimension; ++i )
{
for ( int j = 0; j < kMaxMapDimension; ++j )
{
gridEntities[i][j].first = nullptr;
gridEntities[i][j].last = nullptr;
}
}
};
~TileEntityListHandler()
{
for ( int i = 0; i < kMaxMapDimension; ++i )
{
for ( int j = 0; j < kMaxMapDimension; ++j )
{
clearTile(i, j);
}
}
};
};
extern TileEntityListHandler TileEntityList;
extern float framerateAccumulatedTime;
class DebugStatsClass
{
public:
std::chrono::high_resolution_clock::time_point t1StartLoop;
std::chrono::high_resolution_clock::time_point t2PostEvents;
std::chrono::high_resolution_clock::time_point t21PostHandleMessages;
std::chrono::high_resolution_clock::time_point t3SteamCallbacks;
std::chrono::high_resolution_clock::time_point t4Music;
std::chrono::high_resolution_clock::time_point t5MainDraw;
std::chrono::high_resolution_clock::time_point t6Messages;
std::chrono::high_resolution_clock::time_point t7Inputs;
std::chrono::high_resolution_clock::time_point t8Status;
std::chrono::high_resolution_clock::time_point t9GUI;
std::chrono::high_resolution_clock::time_point t10FrameLimiter;
std::chrono::high_resolution_clock::time_point t11End;
std::chrono::high_resolution_clock::time_point eventsT1;
std::chrono::high_resolution_clock::time_point eventsT2;
std::chrono::high_resolution_clock::time_point eventsT3;
std::chrono::high_resolution_clock::time_point eventsT4;
std::chrono::high_resolution_clock::time_point eventsT5;
std::chrono::high_resolution_clock::time_point eventsT6;
std::chrono::high_resolution_clock::time_point messagesT1;
std::chrono::high_resolution_clock::time_point t1Stored;
std::chrono::high_resolution_clock::time_point t2Stored;
std::chrono::high_resolution_clock::time_point t21Stored;
std::chrono::high_resolution_clock::time_point t3Stored;
std::chrono::high_resolution_clock::time_point t4Stored;
std::chrono::high_resolution_clock::time_point t5Stored;
std::chrono::high_resolution_clock::time_point t6Stored;
std::chrono::high_resolution_clock::time_point t7Stored;
std::chrono::high_resolution_clock::time_point t8Stored;
std::chrono::high_resolution_clock::time_point t9Stored;
std::chrono::high_resolution_clock::time_point t10Stored;
std::chrono::high_resolution_clock::time_point t11Stored;
std::chrono::high_resolution_clock::time_point eventsT1stored;
std::chrono::high_resolution_clock::time_point eventsT2stored;
std::chrono::high_resolution_clock::time_point eventsT3stored;
std::chrono::high_resolution_clock::time_point eventsT4stored;
std::chrono::high_resolution_clock::time_point eventsT5stored;
std::chrono::high_resolution_clock::time_point eventsT6stored;
std::chrono::high_resolution_clock::time_point messagesT1stored;
std::chrono::high_resolution_clock::time_point messagesT2WhileLoop;
bool handlePacketStartLoop = false;
std::unordered_map<unsigned long, std::pair<std::string, int>> networkPackets;
std::unordered_map<int, int> entityUpdatePackets;
bool displayStats = false;
char debugOutput[1024];
char debugEventOutput[1024];
DebugStatsClass()
{};
void inline storeOldTimePoints()
{
t1Stored = t1StartLoop;
t2Stored = t2PostEvents;
t21Stored = t21PostHandleMessages;
t3Stored = t3SteamCallbacks;
t4Stored = t4Music;
t5Stored = t5MainDraw;
t6Stored = t6Messages;
t7Stored = t7Inputs;
t8Stored = t8Status;
t9Stored = t9GUI;
t10Stored = t10FrameLimiter;
t11Stored = t11End;
eventsT1stored = eventsT1;
eventsT2stored = eventsT2;
eventsT3stored = eventsT3;
eventsT4stored = eventsT4;
eventsT5stored = eventsT5;
eventsT6stored = eventsT6;
messagesT1stored = messagesT1;
};
void storeStats();
void storeEventStats();
};
extern DebugStatsClass DebugStats;
| 30.607884
| 164
| 0.793601
|
assasinwar9
|
c63b3390ffb324c52fedcfe538c9dc06eceb630b
| 21,772
|
cpp
|
C++
|
src/evolve_eas_multi_objective.cpp
|
mihaioltean/evolve-algorithms
|
16c86b21effc137483040838162a18579bf76fc2
|
[
"MIT"
] | 1
|
2021-09-29T13:07:47.000Z
|
2021-09-29T13:07:47.000Z
|
src/evolve_eas_multi_objective.cpp
|
mihaioltean/evolve-algorithms
|
16c86b21effc137483040838162a18579bf76fc2
|
[
"MIT"
] | null | null | null |
src/evolve_eas_multi_objective.cpp
|
mihaioltean/evolve-algorithms
|
16c86b21effc137483040838162a18579bf76fc2
|
[
"MIT"
] | null | null | null |
//---------------------------------------------------------------------------
// Evolving Evolutionary Algorithms for MultiObjective problems
// Copyright (C) 2016, Mihai Oltean (mihai.oltean@gmail.com)
// Version 2016.12.26.1
// Compiled with Microsoft Visual C++ 2013
// Just create a console application and set this file as the main file of the project
// MIT License
// New versions of this program will be available at: https://github.com/mihaioltean/evolve-algorithms
// Please reports any sugestions and/or bugs to mihai.oltean@gmail.com
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <float.h>
#include "lista_voidp.h"
#define NUM_MICRO_EA_OPERATORS 4
#define MICRO_EA_RANDOM_INIT 0
#define MICRO_EA_DOMINATOR_SELECTION 1
#define MICRO_EA_CROSSOVER 2
#define MICRO_EA_MUTATION 3
//---------------------------------------------------------------------------
struct t_code3{// three address code
int op; // operators are the MICRO EA OPERATORS
int adr1, adr2; // pointers to arguments
};
//---------------------------------------------------------------------------
struct t_meta_gp_chromosome{
t_code3 *prg; // the program - a string of genes
double fitness; // the fitness (or the error)
};
//---------------------------------------------------------------------------
struct t_meta_gp_parameters{
int code_length; // number of instructions in a chromosome
int num_generations;
int pop_size; // population size
double mutation_probability, crossover_probability;
};
//---------------------------------------------------------------------------
struct t_micro_ea_parameters{
double mutation_probability;
int num_runs;
int num_bits_per_dimension;
int initial_pop_size;
};
//---------------------------------------------------------------------------
void allocate_meta_chromosome(t_meta_gp_chromosome &c, t_meta_gp_parameters ¶ms)
{
c.prg = new t_code3[params.code_length];
}
//---------------------------------------------------------------------------
void delete_meta_chromosome(t_meta_gp_chromosome &c)
{
if (c.prg) {
delete[] c.prg;
c.prg = NULL;
}
}
//---------------------------------------------------------------------------
void copy_individual(t_meta_gp_chromosome& dest, const t_meta_gp_chromosome& source, t_meta_gp_parameters ¶ms)
{
for (int i = 0; i < params.code_length; i++)
dest.prg[i] = source.prg[i];
dest.fitness = source.fitness;
}
//---------------------------------------------------------------------------
void generate_random_meta_chromosome(t_meta_gp_chromosome &a, t_meta_gp_parameters &meta_gp_params, int micro_ea_pop_size) // randomly initializes the individuals
{
for (int i = 0; i < micro_ea_pop_size; i++) {
a.prg[i].op = MICRO_EA_RANDOM_INIT; // generate a random solution
a.prg[i].adr1 = -1;
a.prg[i].adr2 = -1;
}
// for all other genes we put either an operator, variable or constant
for (int i = micro_ea_pop_size; i < meta_gp_params.code_length; i++) {
a.prg[i].op = 1 + rand() % (NUM_MICRO_EA_OPERATORS - 1);
a.prg[i].adr1 = rand() % i;
a.prg[i].adr2 = rand() % i;
}
}
//---------------------------------------------------------------------------
void mutate_meta_chromosome(t_meta_gp_chromosome &a_chromosome, t_meta_gp_parameters& params, int micro_ea_pop_size) // mutate the individual
{
// mutate each symbol with the given probability
// no mutation for the first micro_ea_pop_size genes because they are only used for initialization of the micro ea population
// other genes
for (int i = micro_ea_pop_size; i < params.code_length; i++) {
double p = rand() / (double)RAND_MAX; // mutate the operator
if (p < params.mutation_probability) {
// we mutate it, but we have to decide what we put here
p = rand() / (double)RAND_MAX;
a_chromosome.prg[i].op = 1 + rand() % (NUM_MICRO_EA_OPERATORS - 1);
}
p = rand() / (double)RAND_MAX; // mutate the first address (adr1)
if (p < params.mutation_probability)
a_chromosome.prg[i].adr1 = rand() % i;
p = rand() / (double)RAND_MAX; // mutate the second address (adr2)
if (p < params.mutation_probability)
a_chromosome.prg[i].adr2 = rand() % i;
}
}
//---------------------------------------------------------------------------
void one_cut_point_crossover(const t_meta_gp_chromosome &parent1, const t_meta_gp_chromosome &parent2, t_meta_gp_parameters ¶ms, t_meta_gp_chromosome &offspring1, t_meta_gp_chromosome &offspring2)
{
int cutting_pct = rand() % params.code_length;
for (int i = 0; i < cutting_pct; i++) {
offspring1.prg[i] = parent1.prg[i];
offspring2.prg[i] = parent2.prg[i];
}
for (int i = cutting_pct; i < params.code_length; i++) {
offspring1.prg[i] = parent2.prg[i];
offspring2.prg[i] = parent1.prg[i];
}
}
//---------------------------------------------------------------------------
void uniform_crossover(const t_meta_gp_chromosome &parent1, const t_meta_gp_chromosome &parent2, t_meta_gp_parameters ¶ms, t_meta_gp_chromosome &offspring1, t_meta_gp_chromosome &offspring2)
{
for (int i = 0; i < params.code_length; i++)
if (rand() % 2) {
offspring1.prg[i] = parent1.prg[i];
offspring2.prg[i] = parent2.prg[i];
}
else {
offspring1.prg[i] = parent2.prg[i];
offspring2.prg[i] = parent1.prg[i];
}
}
//---------------------------------------------------------------------------
int sort_function(const void *a, const void *b)
{// comparator for quick sort
if (((t_meta_gp_chromosome *)a)->fitness < ((t_meta_gp_chromosome *)b)->fitness)
return 1;
else
if (((t_meta_gp_chromosome *)a)->fitness > ((t_meta_gp_chromosome *)b)->fitness)
return -1;
else
return 0;
}
//---------------------------------------------------------------------------
void print_meta_chromosome(t_meta_gp_chromosome& an_individual, int code_length)
{
printf("The chromosome is:\n");
for (int i = 0; i < code_length; i++)
switch (an_individual.prg[i].op) {
case MICRO_EA_RANDOM_INIT:
printf("%d: MICRO_EA_RANDOM_INIT\n", i);
break;
case MICRO_EA_DOMINATOR_SELECTION:
printf("%d: MICRO_EA_DOMINATOR_SELECTION(%d, %d)\n", i, an_individual.prg[i].adr1, an_individual.prg[i].adr2);
break;
case MICRO_EA_CROSSOVER:
printf("%d: MICRO_EA_CROSSOVER(%d, %d)\n", i, an_individual.prg[i].adr1, an_individual.prg[i].adr2);
break;
case MICRO_EA_MUTATION:
printf("%d: MICRO_EA_MUTATION(%d)\n", i, an_individual.prg[i].adr1);
break;
}
printf("Fitness = %lf\n", an_individual.fitness);
}
//---------------------------------------------------------------------------
int tournament_selection(t_meta_gp_chromosome *pop, int pop_size, int tournament_size) // Size is the size of the tournament
{
int r, p;
p = rand() % pop_size;
for (int i = 1; i < tournament_size; i++) {
r = rand() % pop_size;
p = pop[r].fitness < pop[p].fitness ? r : p;
}
return p;
}
//---------------------------------------------------------------------------
// function to be optimized
//---------------------------------------------------------------------------
//ZDT1
//---------------------------------------------------------------------------
double f1(double *p, int num_dimensions)
{
return p[0];
}
//---------------------------------------------------------------------------
double f2(double* p, int num_dimensions)
{
// test function T1
double sum = 0;
for (int i = 1; i < num_dimensions; i++)
sum += p[i];
double g = 1 + (9 * sum) / (double)(num_dimensions - 1);
double h = 1 - sqrt(f1(p, num_dimensions) / g);
return g * h;
}
//---------------------------------------------------------------------------
double binary_to_real(char* b_string, int num_bits_per_dimension, double min_x, double max_x)
{
// transform a binary string of num_bits_per_dimension size into a real number in [min_x ... max_x] interval
double x_real = 0;
for (int j = 0; j < num_bits_per_dimension; j++)
x_real = x_real * 2 + (int)b_string[j]; // now I have them in interval [0 ... 2 ^ num_bits_per_dimension - 1]
x_real /= ((1 << num_bits_per_dimension) - 1); // now I have them in [0 ... 1] interval
x_real *= (max_x - min_x); // now I have them in [0 ... max_x - min_x] interval
x_real += min_x; // now I have them in [min_x ... max_x] interval
return x_real;
}
//--------------------------------------------------------------------
bool dominates(double* p1, double* p2) // returns true if p1 dominates p2
{
for (int i = 0; i < 2; i++)
if (p2[i] < p1[i])
return false;
for (int i = 0; i < 2; i++)
if (p1[i] < p2[i])
return true;
return false;
}
//---------------------------------------------------------------------------
void sort_list(TLista &nondominated)
{
bool sorted = false;
while (!sorted) {
sorted = true;
for (node_double_linked * node_p = nondominated.head; node_p->next; node_p = node_p->next) {
double *p = (double*)nondominated.GetCurrentInfo(node_p);
double *p_next = (double*)nondominated.GetCurrentInfo(node_p->next);
if (p[0] > p_next[0]) {
void *tmp_inf = node_p->inf;
node_p->inf = node_p->next->inf;
node_p->next->inf = tmp_inf;
sorted = false;
}
}
}
}
//---------------------------------------------------------------------------
double compute_hypervolume(TLista &nondominated, double *reference)
{
sort_list(nondominated);
double hyper_volume = 0;
for (node_double_linked * node_p = nondominated.head; node_p->next; node_p = node_p->next) {
double *p = (double*)nondominated.GetCurrentInfo(node_p);
double *p_next = (double*)nondominated.GetCurrentInfo(node_p->next);
hyper_volume += (p_next[0] - p[0]) * (reference[1] - p[1]);
}
double *p = (double*)nondominated.GetTailInfo();
hyper_volume += (reference[0] - p[0]) * (reference[1] - p[1]);
return hyper_volume;
}
//---------------------------------------------------------------------------
double make_one_run(t_meta_gp_chromosome &an_individual, int code_length, t_micro_ea_parameters µ_params, int num_dimensions, double min_x, double max_x, double **micro_fitness, char **micro_values, double *x, FILE *f)
{
for (int i = 0; i < code_length; i++) {
switch (an_individual.prg[i].op) {
case MICRO_EA_RANDOM_INIT: // Initialization
for (int j = 0; j < num_dimensions; j++)
for (int k = 0; k < micro_params.num_bits_per_dimension; k++)
micro_values[i][j * micro_params.num_bits_per_dimension + k] = rand() % 2; // random values
// compute fitness of that micro chromosome
// transform to base 10
for (int j = 0; j < num_dimensions; j++)
x[j] = binary_to_real(micro_values[i] + j * micro_params.num_bits_per_dimension, micro_params.num_bits_per_dimension, min_x, max_x);
micro_fitness[i][0] = f1(x, num_dimensions);// apply f - compute fitness of micro
micro_fitness[i][1] = f2(x, num_dimensions);// apply f - compute fitness of micro
break;
case MICRO_EA_DOMINATOR_SELECTION: // Selection (binary tournament)
if (dominates(micro_fitness[an_individual.prg[i].adr1], micro_fitness[an_individual.prg[i].adr2])) {
memcpy(micro_values[i], micro_values[an_individual.prg[i].adr1], micro_params.num_bits_per_dimension * num_dimensions);
micro_fitness[i][0] = micro_fitness[an_individual.prg[i].adr1][0];
micro_fitness[i][1] = micro_fitness[an_individual.prg[i].adr1][1];
}
else { // p2 dominates or are nondominated
memcpy(micro_values[i], micro_values[an_individual.prg[i].adr2], micro_params.num_bits_per_dimension * num_dimensions);
micro_fitness[i][0] = micro_fitness[an_individual.prg[i].adr2][0];
micro_fitness[i][1] = micro_fitness[an_individual.prg[i].adr2][1];
}
break;
case MICRO_EA_CROSSOVER: // Mutation with a fixed mutation probability
for (int j = 0; j < num_dimensions; j++)
for (int k = 0; k < micro_params.num_bits_per_dimension; k++) {
int p = rand() % 2;
if (p)
micro_values[i][j * micro_params.num_bits_per_dimension + k] = micro_values[an_individual.prg[i].adr1][j * micro_params.num_bits_per_dimension + k];
else
micro_values[i][j * micro_params.num_bits_per_dimension + k] = micro_values[an_individual.prg[i].adr2][j * micro_params.num_bits_per_dimension + k];
}
// compute fitness of that micro chromosome
// transform to base 10
for (int j = 0; j < num_dimensions; j++)
x[j] = binary_to_real(micro_values[i] + j * micro_params.num_bits_per_dimension, micro_params.num_bits_per_dimension, min_x, max_x);
micro_fitness[i][0] = f1(x, num_dimensions);// apply f - compute fitness of micro
micro_fitness[i][1] = f2(x, num_dimensions);// apply f - compute fitness of micro
break;
case MICRO_EA_MUTATION: // Mutation with a fixed mutation probability
for (int j = 0; j < num_dimensions; j++)
for (int k = 0; k < micro_params.num_bits_per_dimension; k++) {
double p = rand() / (double)RAND_MAX;
if (p < micro_params.mutation_probability)
micro_values[i][j * micro_params.num_bits_per_dimension + k] = 1 - micro_values[an_individual.prg[i].adr1][j * micro_params.num_bits_per_dimension + k];
else
micro_values[i][j * micro_params.num_bits_per_dimension + k] = micro_values[an_individual.prg[i].adr1][j * micro_params.num_bits_per_dimension + k];
}
// compute fitness of that micro chromosome
// transform to base 10
for (int j = 0; j < num_dimensions; j++)
x[j] = binary_to_real(micro_values[i] + j * micro_params.num_bits_per_dimension, micro_params.num_bits_per_dimension, min_x, max_x);
micro_fitness[i][0] = f1(x, num_dimensions);// apply f - compute fitness of micro
micro_fitness[i][1] = f2(x, num_dimensions);// apply f - compute fitness of micro
break;
}
}
// create a list with nondominated
TLista nondominated;
nondominated.Add(micro_fitness[0]);
for (int i = 1; i < code_length; i++) {
node_double_linked * node_p = nondominated.head;
bool dominated = false;
while (node_p) {
double *p = (double*)nondominated.GetCurrentInfo(node_p);
if (dominates(p, micro_fitness[i])) {
dominated = true;
break;
}
else
if (dominates(micro_fitness[i], p))
node_p = nondominated.DeleteCurrent(node_p);
else// move to the next one
node_p = node_p->next;
}
if (!dominated)
nondominated.Add(micro_fitness[i]);
}
// compute the distance to front
double reference[2] = { 11, 11 };
double hyper_volume = compute_hypervolume(nondominated, reference);
if (f) {
fprintf(f, "%lf\n", hyper_volume);
fprintf(f, "%d\n", nondominated.count);
for (node_double_linked* node_p = nondominated.head; node_p; node_p = node_p->next) {
double *p = (double*)nondominated.GetCurrentInfo(node_p);
fprintf(f, "%lf %lf ", p[0], p[1]);
}
fprintf(f, "\n");
}
return hyper_volume;
}
//---------------------------------------------------------------------------
void compute_fitness(t_meta_gp_chromosome &an_individual, int code_length, t_micro_ea_parameters µ_params, int num_dimensions, double min_x, double max_x, double **micro_fitness, char **micro_values, double *x, FILE *f)
{
double average_hypervolume = 0; // average fitness over all runs
// evaluate code
for (int r = 0; r < micro_params.num_runs; r++) {// micro ea is run on multi runs
srand(r);
double hyper_volume = make_one_run(an_individual, code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, f);
// add to average
average_hypervolume += hyper_volume;
}
average_hypervolume /= (double)micro_params.num_runs;
an_individual.fitness = average_hypervolume;
}
//---------------------------------------------------------------------------
void start_steady_state_mep(t_meta_gp_parameters &meta_gp_params, t_micro_ea_parameters µ_params, int num_dimensions, double min_x, double max_x, FILE *f_out) // Steady-State
{
// a steady state approach:
// we work with 1 population
// newly created individuals will replace the worst existing ones (only if they are better).
// allocate memory
t_meta_gp_chromosome *population;
population = new t_meta_gp_chromosome[meta_gp_params.pop_size];
for (int i = 0; i < meta_gp_params.pop_size; i++)
allocate_meta_chromosome(population[i], meta_gp_params);
t_meta_gp_chromosome offspring1, offspring2;
allocate_meta_chromosome(offspring1, meta_gp_params);
allocate_meta_chromosome(offspring2, meta_gp_params);
double *x = new double[num_dimensions]; // buffer for storing real values
double **micro_fitness = new double*[meta_gp_params.code_length]; // fitness for each micro EA chromosome
for (int i = 0; i < meta_gp_params.code_length; i++)
micro_fitness[i] = new double[2];
// allocate some memory
char **micro_values;
micro_values = new char*[meta_gp_params.code_length];
for (int i = 0; i < meta_gp_params.code_length; i++)
micro_values[i] = new char[num_dimensions * micro_params.num_bits_per_dimension];
// initialize
for (int i = 0; i < meta_gp_params.pop_size; i++) {
generate_random_meta_chromosome(population[i], meta_gp_params, micro_params.initial_pop_size);
compute_fitness(population[i], meta_gp_params.code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, NULL);
}
// sort ascendingly by fitness
qsort((void *)population, meta_gp_params.pop_size, sizeof(population[0]), sort_function);
printf("generation %d, best fitness = %lf\n", 0, population[0].fitness);
// print the front of the best
fprintf(f_out, "%d\n", 0);
srand(0);
make_one_run(population[0], meta_gp_params.code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, f_out);
for (int g = 1; g < meta_gp_params.num_generations; g++) {// for each generation
for (int k = 0; k < meta_gp_params.pop_size; k += 2) {
// choose the parents using binary tournament
int r1 = tournament_selection(population, meta_gp_params.pop_size, 2);
int r2 = tournament_selection(population, meta_gp_params.pop_size, 2);
// crossover
double p = rand() / double(RAND_MAX);
if (p < meta_gp_params.crossover_probability)
one_cut_point_crossover(population[r1], population[r2], meta_gp_params, offspring1, offspring2);
else {// no crossover so the offspring are a copy of the parents
copy_individual(offspring1, population[r1], meta_gp_params);
copy_individual(offspring2, population[r2], meta_gp_params);
}
// mutate the result and compute fitness
mutate_meta_chromosome(offspring1, meta_gp_params, micro_params.initial_pop_size);
compute_fitness(offspring1, meta_gp_params.code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, NULL);
// mutate the other offspring and compute fitness
mutate_meta_chromosome(offspring2, meta_gp_params, micro_params.initial_pop_size);
compute_fitness(offspring2, meta_gp_params.code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, NULL);
// replace the worst in the population
if (offspring1.fitness > population[meta_gp_params.pop_size - 1].fitness) {
copy_individual(population[meta_gp_params.pop_size - 1], offspring1, meta_gp_params);
qsort((void *)population, meta_gp_params.pop_size, sizeof(population[0]), sort_function);
}
if (offspring2.fitness > population[meta_gp_params.pop_size - 1].fitness) {
copy_individual(population[meta_gp_params.pop_size - 1], offspring2, meta_gp_params);
qsort((void *)population, meta_gp_params.pop_size, sizeof(population[0]), sort_function);
}
}
// print the front of the best
fprintf(f_out, "%d\n", g);
srand(0);
make_one_run(population[0], meta_gp_params.code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, f_out);
printf("generation %d, best fitness = %lf\n", g, population[0].fitness);
}
// print best chromosome
print_meta_chromosome(population[0], meta_gp_params.code_length);
// free memory
delete_meta_chromosome(offspring1);
delete_meta_chromosome(offspring2);
for (int i = 0; i < meta_gp_params.pop_size; i++)
delete_meta_chromosome(population[i]);
delete[] population;
for (int i = 0; i < meta_gp_params.code_length; i++)
delete[] micro_values[i];
delete[] micro_values;
for (int i = 0; i < meta_gp_params.code_length; i++)
delete[] micro_fitness[i];
delete[] micro_fitness;
delete[] x;
}
//--------------------------------------------------------------------
bool read_reference_points(char *file_name, TLista &reference_points)
{
FILE * f = fopen(file_name, "r");
if (!f)
return false;
char c;
for (int i = 0; i < 100; i++) {
double *p = new double[2];
fscanf(f, "%lf%c%lf", &p[0], &c, &p[1]);
reference_points.Add(p);
}
fclose(f);
return true;
}
//--------------------------------------------------------------------
int main(void)
{
t_meta_gp_parameters meta_gp_params;
meta_gp_params.pop_size = 10; // the number of individuals in population (must be an even number!)
meta_gp_params.code_length = 10000;
meta_gp_params.num_generations = 100; // the number of generations
meta_gp_params.mutation_probability = 0.01; // mutation probability
meta_gp_params.crossover_probability = 0.9; // crossover probability
t_micro_ea_parameters micro_ea_params;
micro_ea_params.mutation_probability = 0.01;
micro_ea_params.num_bits_per_dimension = 30;
micro_ea_params.num_runs = 30;
micro_ea_params.initial_pop_size = 100;
FILE *f_out = fopen("c:\\temp\\zdt1_front.txt", "w");
printf("evolution started...\n");
srand(0);
start_steady_state_mep(meta_gp_params, micro_ea_params, 30, 0, 1, f_out);
fclose(f_out);
printf("Press enter ...");
getchar();
return 0;
}
//--------------------------------------------------------------------
| 39.158273
| 224
| 0.638894
|
mihaioltean
|
c63e90a89646c8cb2b4c62a1d55fee5b927f722d
| 112
|
cpp
|
C++
|
algorithms/default.cpp
|
kosmaz/HackerRank
|
1107804c8213d169070a5529de26b97eb190e06c
|
[
"MIT"
] | 1
|
2015-03-21T20:08:28.000Z
|
2015-03-21T20:08:28.000Z
|
algorithms/default.cpp
|
kosmaz/HackerRank
|
1107804c8213d169070a5529de26b97eb190e06c
|
[
"MIT"
] | null | null | null |
algorithms/default.cpp
|
kosmaz/HackerRank
|
1107804c8213d169070a5529de26b97eb190e06c
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
void Run()
{
return;
}
int main()
{
Run();
return 0;
}
| 8.615385
| 21
| 0.553571
|
kosmaz
|
c647e1588ab85979651918406ec9a2d73a6df0ab
| 225
|
cpp
|
C++
|
coin2xml.cpp
|
milasudril/coin
|
3e2d4778560894a36dfec9fc6cc245faae7301ae
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
coin2xml.cpp
|
milasudril/coin
|
3e2d4778560894a36dfec9fc6cc245faae7301ae
|
[
"BSD-2-Clause-FreeBSD"
] | 3
|
2018-01-21T08:39:47.000Z
|
2018-01-21T08:42:18.000Z
|
coin2xml.cpp
|
milasudril/coin
|
3e2d4778560894a36dfec9fc6cc245faae7301ae
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
//@ {"targets":[{"name":"coin2xml","type":"application"}]}
#include "input.hpp"
#include "writerxml.hpp"
#include "lexercoin.hpp"
int main()
{
read(stdin, CoIN::LexerCoIN{}, CoIN::WriterXML<FILE*>(stdout));
return 0;
}
| 18.75
| 64
| 0.648889
|
milasudril
|
c6495482a87babd49bb27f4964c179ea7f9aa3b1
| 1,856
|
cpp
|
C++
|
src/app/app_cmd_parser.cpp
|
yyh12345685/libnbf
|
64f6fa1b37b88f673ead8577291b10a30cac4040
|
[
"Apache-2.0"
] | null | null | null |
src/app/app_cmd_parser.cpp
|
yyh12345685/libnbf
|
64f6fa1b37b88f673ead8577291b10a30cac4040
|
[
"Apache-2.0"
] | null | null | null |
src/app/app_cmd_parser.cpp
|
yyh12345685/libnbf
|
64f6fa1b37b88f673ead8577291b10a30cac4040
|
[
"Apache-2.0"
] | 1
|
2021-10-13T01:35:07.000Z
|
2021-10-13T01:35:07.000Z
|
#include <string.h>
#include <iostream>
#include "app/app_cmd_parser.h"
#ifndef __APP_VERSION__
#define __APP_VERSION__ "(date: 22:25:00 2019/12/15 +0800)"
#endif
namespace bdf{
static void UsageInner(const char *exe, bool help){
std::cerr << "Copyright 2019 by yyh,"
<< " Basic Net Framework Model" << std::endl;
std::cerr << "libbdf: " << __APP_VERSION__ << std::endl;
if (help) {
std::cerr << "Usage: "
<< " --c/-c config_file --l/-l log_file [--d/-d:daemon]" << std::endl;
}
}
int AppCmdParser::Usage(int argc, char* argv[]){
if (argc == 2){
if (0 == strcasecmp(argv[1], "-h") ||
0 == strcasecmp(argv[1], "--help")){
UsageInner(argv[0], true);
help_mode_ = true;
return 1;
} else if (0 == strcasecmp(argv[1], "-v") ||
0 == strcasecmp(argv[1], "--version")){
UsageInner(argv[0], false);
return 1;
}
}
if (argc < 3){
UsageInner(argv[0], true);
return 2;
}
return 0;
}
int AppCmdParser::ParseArgv(int argc, char* argv[]){
for (int i = 1; i < argc; ++i){
if (0 == strcmp(argv[i], "-c")|| 0 == strcmp(argv[i], "--config")){
if (++i < argc)
application_config_ = argv[i];
continue;
}
if (0 == strcmp(argv[i], "-d")|| 0 == strcmp(argv[i], "--daemon")){
daemon_mode_ = true;
continue;
}
if (0 == strcmp(argv[i], "-l") || 0 == strcmp(argv[i], "--log")) {
if (++i < argc)
logger_config_ = argv[i];
continue;
}
std::cerr << "unexpected argv: " << argv[i] << std::endl;
}
if (application_config_.empty()){
std::cerr<<"configure file is not available" << std::endl;
return 1;
}
return 0;
}
int AppCmdParser::ParseCmd(int argc, char* argv[]) {
if ( 0 != Usage(argc,argv)){
return -1;
}
if (0!= ParseArgv(argc, argv)){
return -2;
}
return 0;
}
}
| 22.91358
| 76
| 0.543642
|
yyh12345685
|
c65132082e64302e29b178bd5c1a5db607bae6a9
| 991
|
cpp
|
C++
|
DataStructures/Trie/Contacts/contacts.cpp
|
suzyz/HackerRank
|
e97f76c4b39aa448e43e30b479d9718b8b88b2d2
|
[
"MIT"
] | null | null | null |
DataStructures/Trie/Contacts/contacts.cpp
|
suzyz/HackerRank
|
e97f76c4b39aa448e43e30b479d9718b8b88b2d2
|
[
"MIT"
] | null | null | null |
DataStructures/Trie/Contacts/contacts.cpp
|
suzyz/HackerRank
|
e97f76c4b39aa448e43e30b479d9718b8b88b2d2
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
class Trie
{
public:
int count;
Trie *p[26];
Trie()
{
count = 0;
memset(p,0,sizeof(p));
}
~Trie();
void add(string name);
int find(string prefix);
};
void Trie::add(string name)
{
Trie *ch = this;
for (int i = 0; i < name.length(); ++i)
{
if (ch->p[name[i]] == NULL)
ch->p[name[i]] = new Trie;
ch = ch->p[name[i]];
++ ch->count;
}
}
int Trie::find(string prefix)
{
Trie *ch = this;
for (int i = 0; i < prefix.length(); ++i)
{
if (ch->p[prefix[i]] == NULL)
return 0;
ch = ch->p[prefix[i]];
}
if (ch == NULL)
return 0;
return ch->count;
}
int main()
{
int n;
Trie *trie = new Trie;
cin>>n;
for (int i = 0; i < n; ++i)
{
string operation,name;
cin>>operation>>name;
for (int j = 0; j < name.length(); ++j)
name[j] -= 'a';
if (operation=="add")
trie->add(name);
else
{
int ans = trie->find(name);
cout<<ans<<endl;
}
}
return 0;
}
| 13.391892
| 42
| 0.543895
|
suzyz
|
c65447f8c5916a9cc3c384b5f68039ec7392a483
| 1,715
|
cpp
|
C++
|
merge_sort/main.cpp
|
215559085/AlogrithmAndDatastructrue
|
00b24b150fea29d2339d6a1797768174e955fc05
|
[
"MIT"
] | null | null | null |
merge_sort/main.cpp
|
215559085/AlogrithmAndDatastructrue
|
00b24b150fea29d2339d6a1797768174e955fc05
|
[
"MIT"
] | null | null | null |
merge_sort/main.cpp
|
215559085/AlogrithmAndDatastructrue
|
00b24b150fea29d2339d6a1797768174e955fc05
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
vector<int> merge_twins(vector<vector<int>>* twin_group){
auto* tg = twin_group;
int i = 1;
do{
vector<int> result;
vector<int> Vs1 = (*tg)[i-1];
vector<int> Vs2 = (*tg)[i];
for(int a=0,b=0;a<Vs1.size()||b<Vs2.size();){
if(a>=Vs1.size()){
result.push_back(Vs2[b]);++b;
} else if(b>=Vs2.size()){
result.push_back(Vs1[a]);++a;
} else{
if(Vs1[a] > Vs2[b]){ result.push_back(Vs1[a]);++a;}
else{result.push_back(Vs2[b]);++b;}
}
}
tg->push_back(result);
i+=2;
}while(i < tg->size());
delete(tg);
return tg->back();
}
vector<int> merge_sort(vector<int>& Vs,int start,int end){
auto* twin_group = new vector<vector<int>>;
for(int i = start+1;i<end;){
vector<int> twin = * new vector<int>;
if(Vs[i] > Vs[i-1]){
twin.push_back(Vs[i]);
twin.push_back(Vs[i-1]);
}
else{
twin.push_back(Vs[i-1]);
twin.push_back(Vs[i]);
}
twin_group->push_back(twin);
if(end-i == 1){
vector<int> alone = * new vector<int>;
alone.push_back(Vs[end]);
twin_group->push_back(alone);
}
i+=2;
}
return merge_twins(twin_group);
}
int main() {
vector<int> Vs={8,5,4,6,8,8,5,4,6,32,1,8,9,6,7,5,1,5,8,6,6,4,5,621,77,54,8,5,1,7,5,46,8,13,5,4,68,6,5,13,4,15};
cout << "Hello, World!" << endl;
vector<int> res = merge_sort(Vs,0,Vs.size()-1);
for(auto i : res){
cout<<i<<" ";
}
cout<<endl;
return 0;
}
| 29.568966
| 115
| 0.486297
|
215559085
|
c65655ea0fc5628ef66eb4ebe9c8ab24b4d58a30
| 482
|
cpp
|
C++
|
src/RE/NetImmerse/NiRefObject/NiObject/NiColorData.cpp
|
thallada/CommonLibSSE
|
b092c699c3ccd1af6d58d05f677f2977ec054cfe
|
[
"MIT"
] | 1
|
2021-08-30T20:33:43.000Z
|
2021-08-30T20:33:43.000Z
|
src/RE/NetImmerse/NiRefObject/NiObject/NiColorData.cpp
|
thallada/CommonLibSSE
|
b092c699c3ccd1af6d58d05f677f2977ec054cfe
|
[
"MIT"
] | null | null | null |
src/RE/NetImmerse/NiRefObject/NiObject/NiColorData.cpp
|
thallada/CommonLibSSE
|
b092c699c3ccd1af6d58d05f677f2977ec054cfe
|
[
"MIT"
] | 1
|
2020-10-08T02:48:33.000Z
|
2020-10-08T02:48:33.000Z
|
#include "RE/NetImmerse/NiRefObject/NiObject/NiColorData.h"
namespace RE
{
NiColorData::NiColorData() :
numKeys(0),
pad14(0),
keys(nullptr),
type(KeyType::kNoInterp),
keySize(0),
pad25(0),
pad26(0)
{}
std::uint32_t NiColorData::GetNumKeys() const
{
return numKeys;
}
NiColorKey* NiColorData::GetAnim(std::uint32_t& a_numKeys, KeyType& a_type, std::uint8_t& a_size) const
{
a_numKeys = numKeys;
a_type = type;
a_size = keySize;
return keys;
}
}
| 15.548387
| 104
| 0.682573
|
thallada
|
c6567048e511e42f403afd7a4dd35ed2a879183f
| 7,055
|
cpp
|
C++
|
src/pgen/dusty_soundwave.cpp
|
PinghuiHuang/athena-pp-dustfluids
|
fce21992cc107aa553e83dd76b8d03ae90e990c7
|
[
"BSD-3-Clause"
] | 2
|
2020-07-02T09:48:49.000Z
|
2020-08-25T02:37:21.000Z
|
src/pgen/dusty_soundwave.cpp
|
PinghuiHuang/athena-pp-dustfluids
|
fce21992cc107aa553e83dd76b8d03ae90e990c7
|
[
"BSD-3-Clause"
] | null | null | null |
src/pgen/dusty_soundwave.cpp
|
PinghuiHuang/athena-pp-dustfluids
|
fce21992cc107aa553e83dd76b8d03ae90e990c7
|
[
"BSD-3-Clause"
] | 1
|
2021-11-12T13:39:48.000Z
|
2021-11-12T13:39:48.000Z
|
//========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file default_pgen.cpp
// \brief Provides default (empty) versions of all functions in problem generator files
// This means user does not have to implement these functions if they are not needed.
//
// The attribute "weak" is used to ensure the loader selects the user-defined version of
// functions rather than the default version given here.
//
// The attribute "alias" may be used with the "weak" functions (in non-defining
// declarations) in order to have them refer to common no-operation function definition in
// the same translation unit. Target function must be specified by mangled name unless C
// linkage is specified.
//
// This functionality is not in either the C nor the C++ standard. These GNU extensions
// are largely supported by LLVM, Intel, IBM, but may affect portability for some
// architecutres and compilers. In such cases, simply define all 6 of the below class
// functions in every pgen/*.cpp file (without any function attributes).
// C headers
// C++ headers
#include <algorithm> // min, max
#include <cmath> // sqrt()
#include <cstdio> // fopen(), fprintf(), freopen()
#include <iostream> // endl
#include <sstream> // stringstream
#include <stdexcept> // runtime_error
#include <string> // c_str()
// Athena++ headers
#include "../athena.hpp"
#include "../athena_arrays.hpp"
#include "../coordinates/coordinates.hpp"
#include "../eos/eos.hpp"
#include "../field/field.hpp"
#include "../globals.hpp"
#include "../hydro/hydro.hpp"
#include "../mesh/mesh.hpp"
#include "../parameter_input.hpp"
#include "../reconstruct/reconstruction.hpp"
#include "../dustfluids/dustfluids.hpp"
#ifdef MPI_PARALLEL
#include <mpi.h>
#endif
#if NON_BAROTROPIC_EOS
#error "This problem generator requires isothermal equation of state!"
#endif
// problem parameters which are useful to make global to this file
namespace {
// Parameters which define initial solution -- made global so that they can be shared
// with functions A1,2,3 which compute vector potentials
Real rhog0, p0, u0, v0, w0, bx0, by0, bz0, dby, dbz;
Real delta_rho_gas_real, delta_rho_gas_imag;
Real delta_vel_gas_real, delta_vel_gas_imag;
Real user_dt;
Real amp, lambda, k_par; // amplitude, Wavelength, 2*PI/wavelength
Real gam, gm1, iso_cs, vflow;
Real initial_D2G[NDUSTFLUIDS];
Real delta_rho_dust_real[NDUSTFLUIDS];
Real delta_rho_dust_imag[NDUSTFLUIDS];
Real delta_vel_dust_real[NDUSTFLUIDS];
Real delta_vel_dust_imag[NDUSTFLUIDS];
Real MyTimeStep(MeshBlock *pmb);
} // namespace
// 3x members of Mesh class:
namespace {
Real MyTimeStep(MeshBlock *pmb)
{
Real min_user_dt = user_dt;
return min_user_dt;
}
}
//========================================================================================
//! \fn void Mesh::InitUserMeshData(ParameterInput *pin)
// \brief Function to initialize problem-specific data in Mesh class. Can also be used
// to initialize variables which are global to (and therefore can be passed to) other
// functions in this file. Called in Mesh constructor.
//========================================================================================
void Mesh::InitUserMeshData(ParameterInput *pin) {
// read global parameters
rhog0 = pin->GetOrAddReal("problem", "rhog0", 1.0);
user_dt = pin->GetOrAddReal("time", "user_dt", 1.375e-2);
amp = pin->GetReal("problem", "amp");
vflow = pin->GetOrAddReal("problem", "vflow", 0.0);
iso_cs = pin->GetReal("hydro", "iso_sound_speed");
delta_rho_gas_real = pin->GetReal("problem", "delta_rho_gas_real");
delta_rho_gas_imag = pin->GetReal("problem", "delta_rho_gas_imag");
delta_vel_gas_real = pin->GetReal("problem", "delta_vel_gas_real");
delta_vel_gas_imag = pin->GetReal("problem", "delta_vel_gas_imag");
if (NDUSTFLUIDS > 0) {
for (int n=0; n<NDUSTFLUIDS; ++n) {
delta_rho_dust_real[n] = pin->GetReal("dust", "delta_rho_d_" + std::to_string(n+1) + "_real");
delta_rho_dust_imag[n] = pin->GetReal("dust", "delta_rho_d_" + std::to_string(n+1) + "_imag");
delta_vel_dust_real[n] = pin->GetReal("dust", "delta_vel_d_" + std::to_string(n+1) + "_real");
delta_vel_dust_imag[n] = pin->GetReal("dust", "delta_vel_d_" + std::to_string(n+1) + "_imag");
initial_D2G[n] = pin->GetReal("dust", "Initial_D2G_" + std::to_string(n+1));
}
}
if (NON_BAROTROPIC_EOS) {
gam = pin->GetReal("hydro", "gamma");
gm1 = (gam - 1.0);
}
Real x1size = mesh_size.x1max - mesh_size.x1min;
Real x2size = mesh_size.x2max - mesh_size.x2min;
Real x3size = mesh_size.x3max - mesh_size.x3min;
Real x1 = x1size;
Real x2 = 0.0;
Real x3 = 0.0;
lambda = x1;
k_par = 2.0*(PI)/lambda;
u0 = vflow;
v0 = 0.0;
w0 = 0.0;
p0 = SQR(iso_cs)*rhog0;
if (user_dt > 0.0)
EnrollUserTimeStepFunction(MyTimeStep);
return;
}
void MeshBlock::ProblemGenerator(ParameterInput *pin) {
Real inv_gm1 = 1./gm1;
for (int k=ks; k<=ke; k++) {
for (int j=js; j<=je; j++) {
for (int i=is; i<=ie; i++) {
Real x = pcoord->x1v(i);
Real sn = std::sin(k_par*x);
Real cn = std::cos(k_par*x);
Real &gas_den = phydro->u(IDN, k, j, i);
Real &gas_m1 = phydro->u(IM1, k, j, i);
Real &gas_m2 = phydro->u(IM2, k, j, i);
Real &gas_m3 = phydro->u(IM3, k, j, i);
Real delta_rho = amp*rhog0*(cn*delta_rho_gas_real - sn*delta_rho_gas_imag);
Real delta_vel = amp*iso_cs*(cn*delta_vel_gas_real - sn*delta_vel_gas_imag);
gas_den = rhog0 + delta_rho;
gas_m1 = rhog0*(u0 + delta_vel);
gas_m2 = 0.0;
gas_m3 = 0.0;
if (NDUSTFLUIDS >0) {
for (int n=0; n<NDUSTFLUIDS; ++n) {
int dust_id = n;
int rho_id = 4*dust_id;
int v1_id = rho_id + 1;
int v2_id = rho_id + 2;
int v3_id = rho_id + 3;
Real &dust_den = pdustfluids->df_cons(rho_id, k, j, i);
Real &dust_m1 = pdustfluids->df_cons(v1_id, k, j, i);
Real &dust_m2 = pdustfluids->df_cons(v2_id, k, j, i);
Real &dust_m3 = pdustfluids->df_cons(v3_id, k, j, i);
Real rhod0 = initial_D2G[dust_id] * rhog0;
Real delta_dust_rho = rhog0*amp*(cn*delta_rho_dust_real[n] - sn*delta_rho_dust_imag[n]);
Real delta_dust_vel = amp*iso_cs*(cn*delta_vel_dust_real[n] - sn*delta_vel_dust_imag[n]);
dust_den = rhod0 + delta_dust_rho;
dust_m1 = rhod0*(vflow + delta_dust_vel);
dust_m2 = 0.0;
dust_m3 = 0.0;
}
}
}
}
}
return;
}
| 36.937173
| 101
| 0.617576
|
PinghuiHuang
|
c65d17798602b9ca5256d8dfa64085cebf993067
| 28,893
|
cpp
|
C++
|
UnrealMvvmTests/Source/UnrealMvvmTests/Private/ListenManager.spec.cpp
|
druhasu/UnrealMvvm
|
3ab5a2e98a36583c74c72c0a76c1669f37ff1820
|
[
"MIT"
] | 5
|
2021-11-28T17:09:25.000Z
|
2022-03-14T08:55:03.000Z
|
UnrealMvvmTests/Source/UnrealMvvmTests/Private/ListenManager.spec.cpp
|
druhasu/UnrealMvvm
|
3ab5a2e98a36583c74c72c0a76c1669f37ff1820
|
[
"MIT"
] | null | null | null |
UnrealMvvmTests/Source/UnrealMvvmTests/Private/ListenManager.spec.cpp
|
druhasu/UnrealMvvm
|
3ab5a2e98a36583c74c72c0a76c1669f37ff1820
|
[
"MIT"
] | 2
|
2021-12-23T14:10:28.000Z
|
2022-03-27T15:34:10.000Z
|
// Copyright Andrei Sudarikov. All Rights Reserved.
#include "Misc/AutomationTest.h"
#include "Mvvm/ListenManager.h"
#include "TestListener.h"
BEGIN_DEFINE_SPEC(ListenManagerSpec, "UnrealMvvm.ListenManager", EAutomationTestFlags::ClientContext | EAutomationTestFlags::EditorContext | EAutomationTestFlags::ServerContext | EAutomationTestFlags::EngineFilter)
END_DEFINE_SPEC(ListenManagerSpec)
class FEventHolder
{
public:
DECLARE_EVENT(FEventHolder, FTestEvent);
mutable FTestEvent EventField;
FTestEvent& EventMethod() { return EventField; }
FTestEvent& EventMethodConst() const { return EventField; }
DECLARE_MULTICAST_DELEGATE(FTestDelegate);
mutable FTestDelegate DelegateField;
FTestDelegate& DelegateMethod() { return DelegateField; }
FTestDelegate& DelegateMethodConst() const { return DelegateField; }
mutable FTestDynamicDelegate DynamicDelegateField;
FTestDynamicDelegate& DynamicDelegateMethod() { return DynamicDelegateField; }
FTestDynamicDelegate& DynamicDelegateMethodConst() const { return DynamicDelegateField; }
};
class FSecondBase
{
int32 Dummy;
};
class FMultiInheritedEventHolder : public FEventHolder, public FSecondBase
{
public:
FTestEvent EventFieldDerived;
FTestEvent& EventMethodDerived() { return EventFieldDerived; }
FTestDynamicDelegate DynamicDelegateFieldDerived;
FTestDynamicDelegate& DynamicDelegateMethodDerived() { return DynamicDelegateFieldDerived; }
};
bool StaticInvoked = false;
void StaticCallback()
{
StaticInvoked = true;
}
void ListenManagerSpec::Define()
{
Describe("Simple Delegate", [this]()
{
Describe("WithStatic", [this]()
{
It("Should Listen To Simple Event Field With Static", [this]()
{
FEventHolder Holder;
FListenManager Manager;
StaticInvoked = false;
Manager.Listen(&Holder, &FEventHolder::EventField).WithStatic(&StaticCallback);
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", StaticInvoked);
});
It("Should Listen To Simple Delegate Field With Static", [this]()
{
FEventHolder Holder;
FListenManager Manager;
StaticInvoked = false;
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithStatic(&StaticCallback);
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", StaticInvoked);
});
It("Should Listen To Simple Event Method With Static", [this]()
{
FEventHolder Holder;
FListenManager Manager;
StaticInvoked = false;
Manager.Listen(&Holder, &FEventHolder::EventMethod).WithStatic(&StaticCallback);
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", StaticInvoked);
});
It("Should Listen To Simple Delegate Method With Static", [this]()
{
FEventHolder Holder;
FListenManager Manager;
StaticInvoked = false;
Manager.Listen(&Holder, &FEventHolder::DelegateMethod).WithStatic(&StaticCallback);
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", StaticInvoked);
});
It("Should Listen To Simple Event Const Method With Static", [this]()
{
FEventHolder Holder;
FListenManager Manager;
StaticInvoked = false;
Manager.Listen(&Holder, &FEventHolder::EventMethodConst).WithStatic(&StaticCallback);
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", StaticInvoked);
});
It("Should Listen To Simple Delegate Const Method With Static", [this]()
{
FEventHolder Holder;
FListenManager Manager;
StaticInvoked = false;
Manager.Listen(&Holder, &FEventHolder::DelegateMethodConst).WithStatic(&StaticCallback);
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", StaticInvoked);
});
It("Should Unsubscribe From Simple Event With Static", [this]()
{
FEventHolder Holder;
FListenManager Manager;
Manager.Listen(&Holder, &FEventHolder::EventField).WithStatic(&StaticCallback);
TestTrue("Listener not added", Holder.EventField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.EventField.IsBound());
});
It("Should Unsubscribe From Simple Delegate With Static", [this]()
{
FEventHolder Holder;
FListenManager Manager;
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithStatic(&StaticCallback);
TestTrue("Listener not added", Holder.DelegateField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.DelegateField.IsBound());
});
});
Describe("WithLambda", [this]()
{
It("Should Listen To Simple Event Field With Lambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
Manager.Listen(&Holder, &FEventHolder::EventField).WithLambda([&Invoked]() { Invoked = true; });
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Listen To Simple Delegate Field With Lambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithLambda([&Invoked]() { Invoked = true; });
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Listen To Simple Event Method With Lambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
Manager.Listen(&Holder, &FEventHolder::EventMethod).WithLambda([&Invoked]() { Invoked = true; });
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Listen To Simple Delegate Method With Lambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
Manager.Listen(&Holder, &FEventHolder::DelegateMethod).WithLambda([&Invoked]() { Invoked = true; });
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Listen To Simple Event Const Method With Lambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
Manager.Listen(&Holder, &FEventHolder::EventMethodConst).WithLambda([&Invoked]() { Invoked = true; });
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Listen To Simple Delegate Const Method With Lambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
Manager.Listen(&Holder, &FEventHolder::DelegateMethodConst).WithLambda([&Invoked]() { Invoked = true; });
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Unsubscribe From Simple Event With Lambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
Manager.Listen(&Holder, &FEventHolder::EventField).WithLambda([]() {});
TestTrue("Listener not added", Holder.EventField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.EventField.IsBound());
});
It("Should Unsubscribe From Simple Delegate With Lambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithLambda([]() {});
TestTrue("Listener not added", Holder.DelegateField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.DelegateField.IsBound());
});
});
Describe("WithWeakLambda", [this]()
{
It("Should Listen To Simple Event Field With Lambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventField).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; });
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Listen To Simple Delegate Field With WeakLambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; });
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Listen To Simple Event Method With WeakLambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventMethod).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; });
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Listen To Simple Delegate Method With WeakLambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateMethod).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; });
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Listen To Simple Event Const Method With WeakLambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventMethodConst).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; });
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Listen To Simple Delegate Const Method With WeakLambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateMethodConst).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; });
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Invoked);
});
It("Should Unsubscribe From Simple Event With WeakLambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventField).WithWeakLambda(Listener, []() {});
TestTrue("Listener not added", Holder.EventField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.EventField.IsBound());
});
It("Should Unsubscribe From Simple Delegate With WeakLambda", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithWeakLambda(Listener, []() {});
TestTrue("Listener not added", Holder.DelegateField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.DelegateField.IsBound());
});
});
Describe("WithSP", [this]()
{
It("Should Listen To Simple Event Field With SharedPtr", [this]()
{
FEventHolder Holder;
FListenManager Manager;
TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventField).WithSP(Listener.Get(), &FTestListener::SimpleCallback);
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Simple Delegate Field With SharedPtr", [this]()
{
FEventHolder Holder;
FListenManager Manager;
TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithSP(Listener.Get(), &FTestListener::SimpleCallback);
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Simple Event Method With SharedPtr", [this]()
{
FEventHolder Holder;
FListenManager Manager;
TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventMethod).WithSP(Listener.Get(), &FTestListener::SimpleCallback);
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Simple Delegate Method With SharedPtr", [this]()
{
FEventHolder Holder;
FListenManager Manager;
TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateMethod).WithSP(Listener.Get(), &FTestListener::SimpleCallback);
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Simple Event Const Method With SharedPtr", [this]()
{
FEventHolder Holder;
FListenManager Manager;
TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventMethodConst).WithSP(Listener.Get(), &FTestListener::SimpleCallback);
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Simple Delegate Const Method With SharedPtr", [this]()
{
FEventHolder Holder;
FListenManager Manager;
TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateMethodConst).WithSP(Listener.Get(), &FTestListener::SimpleCallback);
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Unsubscribe From Simple Event With SharedPtr", [this]()
{
FEventHolder Holder;
FListenManager Manager;
TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventField).WithSP(Listener.Get(), &FTestListener::SimpleCallback);
TestTrue("Listener not added", Holder.EventField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.EventField.IsBound());
});
It("Should Unsubscribe From Simple Delegate With SharedPtr", [this]()
{
FEventHolder Holder;
FListenManager Manager;
TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithSP(Listener.Get(), &FTestListener::SimpleCallback);
TestTrue("Listener not added", Holder.DelegateField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.DelegateField.IsBound());
});
});
Describe("WithUObject", [this]()
{
It("Should Listen To Simple Event Field With UObject", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventField).WithUObject(Listener, &UTestListener::SimpleCallback);
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Simple Delegate Field With UObject", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithUObject(Listener, &UTestListener::SimpleCallback);
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Simple Event Method With UObject", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventMethod).WithUObject(Listener, &UTestListener::SimpleCallback);
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Simple Delegate Method With UObject", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateMethod).WithUObject(Listener, &UTestListener::SimpleCallback);
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Simple Event Const Method With UObject", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventMethodConst).WithUObject(Listener, &UTestListener::SimpleCallback);
Holder.EventField.Broadcast();
TestTrue("Listener not added", Holder.EventField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Simple Delegate Const Method With UObject", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateMethodConst).WithUObject(Listener, &UTestListener::SimpleCallback);
Holder.DelegateField.Broadcast();
TestTrue("Listener not added", Holder.DelegateField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Unsubscribe From Simple Event With UObject", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::EventField).WithUObject(Listener, &UTestListener::SimpleCallback);
TestTrue("Listener not added", Holder.EventField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.EventField.IsBound());
});
It("Should Unsubscribe From Simple Delegate With UObject", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithUObject(Listener, &UTestListener::SimpleCallback);
TestTrue("Listener not added", Holder.DelegateField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.DelegateField.IsBound());
});
});
It("Should Compile Unsubscriber From Event Of Class With Several Bases", [this]()
{
FMultiInheritedEventHolder Holder;
FListenManager Manager;
bool Invoked = false;
Manager.Listen(&Holder, &FMultiInheritedEventHolder::EventFieldDerived).WithLambda([&Invoked]() { Invoked = true; });
Manager.Listen(&Holder, &FMultiInheritedEventHolder::EventMethodDerived).WithLambda([&Invoked]() { Invoked = true; });
Holder.EventField.Broadcast();
Manager.UnsubscribeAll();
});
});
Describe("Dynamic Delegate", [this]()
{
Describe("WithDynamic", [this]()
{
It("Should Listen To Dynamic Delegate Field With UFunction", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DynamicDelegateField).WithDynamic(Listener, &UTestListener::DynamicCallback);
Holder.DynamicDelegateField.Broadcast();
TestTrue("Listener not added", Holder.DynamicDelegateField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Dynamic Delegate Method With UFunction", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DynamicDelegateMethod).WithDynamic(Listener, &UTestListener::DynamicCallback);
Holder.DynamicDelegateField.Broadcast();
TestTrue("Listener not added", Holder.DynamicDelegateField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Listen To Dynamic Delegate Const Method With UFunction", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DynamicDelegateMethodConst).WithDynamic(Listener, &UTestListener::DynamicCallback);
Holder.DynamicDelegateField.Broadcast();
TestTrue("Listener not added", Holder.DynamicDelegateField.IsBound());
TestTrue("Listener not invoked", Listener->Invoked);
});
It("Should Unsubscribe From Dynamic Delegate With UFunction", [this]()
{
FEventHolder Holder;
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
Manager.Listen(&Holder, &FEventHolder::DynamicDelegateField).WithDynamic(Listener, &UTestListener::DynamicCallback);
TestTrue("Listener not added", Holder.DynamicDelegateField.IsBound());
Manager.UnsubscribeAll();
TestFalse("Listener not removed", Holder.DynamicDelegateField.IsBound());
});
});
It("Should Compile Unsubscriber From Event Of Class With Several Bases", [this]()
{
FListenManager Manager;
UTestListener* Listener = NewObject<UTestListener>();
{
FMultiInheritedEventHolder Holder;
Manager.Listen(&Holder, &FMultiInheritedEventHolder::DynamicDelegateFieldDerived).WithDynamic(Listener, &UTestListener::DynamicCallback);
Holder.DynamicDelegateField.Broadcast();
Manager.UnsubscribeAll();
}
{
FMultiInheritedEventHolder Holder;
Manager.Listen(&Holder, &FMultiInheritedEventHolder::DynamicDelegateMethodDerived).WithDynamic(Listener, &UTestListener::DynamicCallback);
Holder.DynamicDelegateField.Broadcast();
Manager.UnsubscribeAll();
}
});
});
It("Should Remove All Subscriptions From Destructor", [this]()
{
FEventHolder Holder;
{
FListenManager Manager;
Manager.Listen(&Holder, &FEventHolder::DelegateField).WithLambda([]() {});
TestTrue("Listener not added", Holder.DelegateField.IsBound());
}
TestFalse("Listener not removed", Holder.DelegateField.IsBound());
});
}
| 41.692641
| 214
| 0.582736
|
druhasu
|
c6607ed75baf7e2ae95be4b8afdba08de2d70c57
| 5,159
|
cpp
|
C++
|
src/editable_graph.cpp
|
jlwitthuhn/cycles-shader-editor
|
0d6771801402ca7ecff006f399be90b1beea2884
|
[
"MIT"
] | 11
|
2018-04-05T06:52:17.000Z
|
2021-12-14T07:02:52.000Z
|
src/editable_graph.cpp
|
jlwitthuhn/cycles-shader-editor
|
0d6771801402ca7ecff006f399be90b1beea2884
|
[
"MIT"
] | 2
|
2018-01-18T04:30:58.000Z
|
2020-07-25T09:49:23.000Z
|
src/editable_graph.cpp
|
jlwitthuhn/cycles-shader-editor
|
0d6771801402ca7ecff006f399be90b1beea2884
|
[
"MIT"
] | 4
|
2018-04-02T13:36:40.000Z
|
2021-08-21T21:23:23.000Z
|
#include "editable_graph.h"
#include "node_outputs.h"
#include "sockets.h"
#include "util_vector.h"
cse::EditableGraph::EditableGraph(const ShaderGraphType type)
{
reset(type);
}
void cse::EditableGraph::add_node(std::shared_ptr<EditableNode>& node, const Float2 world_pos)
{
if (node.use_count() == 0) {
return;
}
node->world_pos = world_pos;
nodes.push_front(node);
should_push_undo_state = true;
}
void cse::EditableGraph::add_connection(const std::weak_ptr<NodeSocket> socket_begin, const std::weak_ptr<NodeSocket> socket_end)
{
EditableNode* source_node = nullptr;
if (const auto socket_begin_ptr = socket_begin.lock()) {
if (socket_begin_ptr->io_type != SocketIOType::OUTPUT) {
return;
}
source_node = socket_begin_ptr->parent;
}
else {
// pointer is invalid
return;
}
if (const auto socket_end_ptr = socket_end.lock()) {
if (socket_end_ptr->io_type != SocketIOType::INPUT) {
return;
}
if (socket_end_ptr->parent == source_node) {
// Do not allow a node to connect to itself
return;
}
}
else {
// pointer is invalid
return;
}
// Remove any existing connection with this endpoint
remove_connection_with_end(socket_end);
should_push_undo_state = true;
NodeConnection new_connection(socket_begin, socket_end);
connections.push_back(new_connection);
}
cse::NodeConnection cse::EditableGraph::remove_connection_with_end(const std::weak_ptr<NodeSocket> socket_end)
{
const NodeConnection default_result = NodeConnection(std::weak_ptr<NodeSocket>(), std::weak_ptr<NodeSocket>());
if (socket_end.expired()) {
return default_result;
}
std::list<NodeConnection>::iterator iter;
for (iter = connections.begin(); iter != connections.end(); iter++) {
if (iter->end_socket.lock() == socket_end.lock()) {
should_push_undo_state = true;
NodeConnection result = *iter;
connections.erase(iter);
return result;
}
}
return default_result;
}
void cse::EditableGraph::remove_node_set(const cse::WeakNodeSet& weak_nodes_to_remove)
{
// Create a set of shared_ptrs from the weak_ptrs
SharedNodeSet shared_nodes_to_remove;
for (auto weak_node : weak_nodes_to_remove) {
shared_nodes_to_remove.insert(weak_node.lock());
}
// Remove all nodes in the set
auto node_iter = nodes.begin();
while (node_iter != nodes.end()) {
auto this_node = *node_iter;
if (this_node->can_be_deleted() && shared_nodes_to_remove.count(this_node) == 1) {
node_iter = nodes.erase(node_iter);
should_push_undo_state = true;
}
else {
node_iter++;
}
}
remove_invalid_connections();
}
bool cse::EditableGraph::is_node_under_point(const Float2 world_pos) const
{
for (const auto this_node : nodes) {
if (this_node->contains_point(world_pos)) {
return true;
}
}
return false;
}
std::weak_ptr<cse::EditableNode> cse::EditableGraph::get_node_under_point(const Float2 world_pos) const
{
for (const auto this_node : nodes) {
if (this_node->contains_point(world_pos)) {
return this_node;
}
}
return std::weak_ptr<EditableNode>();
}
std::weak_ptr<cse::NodeSocket> cse::EditableGraph::get_socket_under_point(const Float2 world_pos) const
{
for (const auto this_node : nodes) {
auto maybe_result = this_node->get_socket_label_under_point(world_pos);
if (maybe_result.expired() == false) {
return maybe_result;
}
}
return std::weak_ptr<NodeSocket>();
}
std::weak_ptr<cse::NodeSocket> cse::EditableGraph::get_connector_under_point(const Float2 world_pos, const SocketIOType io_type) const
{
for (const auto this_node : nodes) {
auto maybe_result = this_node->get_socket_connector_under_point(world_pos);
if (auto maybe_result_ptr = maybe_result.lock()) {
if (maybe_result_ptr->io_type == io_type) {
return maybe_result;
}
}
}
return std::weak_ptr<NodeSocket>();
}
void cse::EditableGraph::raise_node(const std::weak_ptr<cse::EditableNode> weak_node)
{
if (weak_node.expired()) {
return;
}
const std::shared_ptr<EditableNode> node_to_raise = weak_node.lock();
// Exit early if this is already the top node
if (nodes.front() == node_to_raise) {
return;
}
for (auto iter = nodes.begin(); iter != nodes.end(); iter++) {
const std::shared_ptr<EditableNode> this_node = *iter;
if (this_node == node_to_raise) {
nodes.erase(iter);
nodes.push_front(this_node);
return;
}
}
}
bool cse::EditableGraph::needs_undo_push()
{
bool result = false;
for (const auto this_node : nodes) {
if (this_node->changed) {
result = true;
this_node->changed = false;
}
}
if (should_push_undo_state) {
result = true;
should_push_undo_state = false;
}
return result;
}
void cse::EditableGraph::reset(const ShaderGraphType type)
{
connections.clear();
nodes.clear();
switch (type) {
case ShaderGraphType::EMPTY:
// Do nothing
break;
case ShaderGraphType::MATERIAL:
{
nodes.push_back(std::make_shared<MaterialOutputNode>(Float2(0.0f, 0.0f)));
}
}
}
void cse::EditableGraph::remove_invalid_connections()
{
std::list<NodeConnection>::iterator iter = connections.begin();
while (iter != connections.end()) {
if (iter->is_valid()) {
iter++;
}
else {
iter = connections.erase(iter);
}
}
}
| 24.684211
| 134
| 0.718356
|
jlwitthuhn
|
c660c618ee8ef913577bbbda3f560db160ae2d42
| 1,188
|
cpp
|
C++
|
Source/Core/Geometry/HittableList.cpp
|
T-rvw/RayTracingRender
|
941782dc070b27db381976650aa6bddd8e6f45a1
|
[
"MIT"
] | null | null | null |
Source/Core/Geometry/HittableList.cpp
|
T-rvw/RayTracingRender
|
941782dc070b27db381976650aa6bddd8e6f45a1
|
[
"MIT"
] | null | null | null |
Source/Core/Geometry/HittableList.cpp
|
T-rvw/RayTracingRender
|
941782dc070b27db381976650aa6bddd8e6f45a1
|
[
"MIT"
] | null | null | null |
#include "HittableList.h"
std::optional<HitRecord> HittableList::hit(const Ray& ray, double minT, double maxT) const
{
bool hitAnything = false;
double closestT = maxT;
std::optional<HitRecord> finalResult = std::nullopt;
for (const auto& pHittableObject : m_vecHittableObjects)
{
std::optional<HitRecord> tempResult = pHittableObject->hit(ray, minT, closestT);
if (tempResult.has_value())
{
hitAnything = true;
closestT = tempResult.value().rayT();
finalResult = tempResult.value();
}
}
return finalResult;
}
std::optional<AABB> HittableList::boundingBox(double t0, double t1) const
{
std::optional<AABB> optOutputBox;
for (const auto& pHittableObject : m_vecHittableObjects)
{
std::optional<AABB> optBox = pHittableObject->boundingBox(t0, t1);
if (!optBox.has_value())
{
break;
}
if (!optOutputBox.has_value())
{
optOutputBox = std::move(optBox);
}
else
{
optOutputBox = AABB::merge(optOutputBox.value(), optBox.value());
}
}
return optOutputBox;
}
| 26.4
| 90
| 0.598485
|
T-rvw
|
c661be2d8619ef8cca0232b790ae6157d71518b7
| 1,725
|
hpp
|
C++
|
HttpServer/include/Http/HttpStatusCode.hpp
|
WoozChucky/cpp-webserver-eventdriven
|
5ea96b299f7f948e45a7591b4aa46b3e6e895373
|
[
"MIT"
] | 1
|
2021-04-13T18:36:38.000Z
|
2021-04-13T18:36:38.000Z
|
HttpServer/include/Http/HttpStatusCode.hpp
|
WoozChucky/cpp-webserver-eventdriven
|
5ea96b299f7f948e45a7591b4aa46b3e6e895373
|
[
"MIT"
] | 1
|
2022-03-02T00:24:24.000Z
|
2022-03-02T00:24:24.000Z
|
HttpServer/include/Http/HttpStatusCode.hpp
|
WoozChucky/cpp-webserver-eventdriven
|
5ea96b299f7f948e45a7591b4aa46b3e6e895373
|
[
"MIT"
] | null | null | null |
//
// Created by Nuno Levezinho Silva on 17/09/2019.
//
#ifndef HTTPSTATUSCODE_HPP
#define HTTPSTATUSCODE_HPP
#include <Abstractions/Types.hpp>
enum HttpStatusCode : U16 {
/* 1xx Status Codes */
CONTINUE = 100,
SWITCHING_PROTOCOLS = 101,
EARLY_HINTS = 103,
/* 2xx Status Codes */
OK = 200,
CREATED = 201,
ACCEPTED = 202,
NON_AUTHORITATIVE_INFORMATION = 203,
NO_CONTENT = 204,
RESET_CONTENT = 205,
PARTIAL_CONTENT = 206,
/* 3xx Status Codes */
MULTIPLE_CHOICES = 300,
MOVED_PERMANENTLY = 301,
FOUND = 302,
SEE_OTHER = 303,
NOT_MODIFIED = 304,
TEMPORARY_REDIRECT = 307,
PERMANENT_REDIRECT = 308,
/* 4xx Status Codes */
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
PAYMENT_REQUIRED = 402,
FORBIDDEN = 403,
NOT_FOUND = 404,
METHOD_NOT_ALLOWED = 405,
NOT_ACCEPTABLE = 406,
PROXY_AUTHENTICATION_REQUIRED = 407,
REQUEST_TIMEOUT = 408,
CONFLICT = 409,
GONE = 410,
LENGTH_REQUIRED = 411,
PRECONDITION_FAILED = 412,
PAYLOAD_TOO_LARGE = 413,
URI_TOO_LONG = 414,
UNSUPPORTED_MEDIA_TYPE = 415,
RANGE_NOT_SATISFIABLE = 416,
EXPECTATION_FAILED = 417,
IM_A_TEAMPOT = 418,
UNPROCESSABLE_ENTITY = 422,
TOO_EARLY = 425,
UPGRADE_REQUIRED = 426,
PRECONDITION_REQUIRED = 428,
TOO_MANY_REQUESTS = 429,
REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
UNAVAILABLE_FOR_LEGAL_REASONS = 451,
/* 5xx Status Codes */
INTERNAL_SERVER_ERROR = 500,
NOT_IMPLEMENTED = 501,
BAD_GATEWAY = 502,
SERVICE_UNAVAILABLE = 503,
GATEWAY_TIMEOUT = 504,
HTTP_VERSION_NOT_SUPPORTED = 505,
NETWORK_AUTHENTICATION_REQUIRED = 511
};
#endif //HTTPSTATUSCODE_HPP
| 23.310811
| 49
| 0.669565
|
WoozChucky
|
c6620ab873aefa1315e7443326b824fab893e6ac
| 949
|
cpp
|
C++
|
Dice_throw.cpp
|
shivamkrs89/DYNAMIC-PROGRAMMING
|
7284918d61107ed9ac8092349b5289c69e628e2d
|
[
"MIT"
] | 2
|
2021-05-27T14:56:52.000Z
|
2021-05-27T15:08:02.000Z
|
Dice_throw.cpp
|
shivamkrs89/DYNAMIC-PROGRAMMING
|
7284918d61107ed9ac8092349b5289c69e628e2d
|
[
"MIT"
] | null | null | null |
Dice_throw.cpp
|
shivamkrs89/DYNAMIC-PROGRAMMING
|
7284918d61107ed9ac8092349b5289c69e628e2d
|
[
"MIT"
] | null | null | null |
Given integers n, faces, and total, return the number of ways it is possible to throw n dice with faces faces each to get total.
Mod the result by 10 ** 9 + 7.
Constraints
1 โค n, faces, total โค 100
Example 1
Input
n = 2
faces = 6
total = 7
Output
6
Explanation
There are 6 ways to make 7 with 2 6-sided dice:
1 and 6
6 and 1
2 and 5
5 and 2
3 and 4
4 and 3
//code
//better expalination refer to https://www.geeksforgeeks.org/dice-throw-dp-30/
int solve(int n, int faces, int total) {
int md=1e9+7;
long long count=0;
long long int dp[n+1][total+1];
memset(dp,0,sizeof(dp));
int i,j;
for(i=1;i<=total;i++)
{
if(i<=faces)
dp[1][i]=1;
}
for(i=2;i<=n;i++)
{
for(j=1;j<=total;j++)
{
dp[i][j]=(dp[i-1][j-1]+dp[i][j-1])%md;//fiing a face j-1 to 1 and getting possiblities.
if(j>=faces+1)
dp[i][j]-=dp[i-1][j-faces-1];
}
}
return dp[n][total]%md;
| 15.306452
| 128
| 0.582719
|
shivamkrs89
|
c664f6a8ac1667c36a3a4c5bc1fb915baf952536
| 949
|
cpp
|
C++
|
arm/src/dynamixel_hand_control.cpp
|
AvatarQuest/AVA-ros
|
3e945d859155f559761f47040b1431e0e9ee8da1
|
[
"MIT"
] | null | null | null |
arm/src/dynamixel_hand_control.cpp
|
AvatarQuest/AVA-ros
|
3e945d859155f559761f47040b1431e0e9ee8da1
|
[
"MIT"
] | null | null | null |
arm/src/dynamixel_hand_control.cpp
|
AvatarQuest/AVA-ros
|
3e945d859155f559761f47040b1431e0e9ee8da1
|
[
"MIT"
] | null | null | null |
#include "ros/ros.h"
#include <geometry_msgs/Vector3.h>
#define AXIS y
double states[5];
void pinkyCB(const geometry_msgs::Vector3::ConstPtr& msg) {
}
void ringCB(const geometry_msgs::Vector3::ConstPtr& msg) {
}
void indexCB(const geometry_msgs::Vector3::ConstPtr& msg) {
}
void middleCB(const geometry_msgs::Vector3::ConstPtr& msg) {
}
void thumbCB(const geometry_msgs::Vector3::ConstPtr& msg) {
}
int main(int argc, char** argv) {
ros::init(argc, argv, "dynamixel_hand");
ros::NodeHandle nh;
ros::Subscriber pinky_sub = nh.subscribe("pinky", 1, pinkyCB);
ros::Subscriber ring_sub = nh.subscribe("ring", 1, ringCB);
ros::Subscriber index_sub = nh.subscribe("index", 1,indexCB);
ros::Subscriber middle_sub = nh.subscribe("middle", 1, middleCB);
ros::Subscriber thumb_sub = nh.subscribe("thumb", 1, thumbCB);
ROS_INFO("%s", "starting node 'dynamixel_hand_control'");
ros::spin();
return 0;
}
| 23.146341
| 69
| 0.689146
|
AvatarQuest
|
c6655ba5c3b1ea97fca8c409457b22d999f41bdb
| 7,068
|
hh
|
C++
|
core/bootstrap/srpc.hh
|
HXLLL/rlibv2
|
a9165e5863dae9c54e0fe80e682f75ec31d858c6
|
[
"Apache-2.0"
] | 17
|
2020-06-27T01:01:25.000Z
|
2022-02-26T00:20:20.000Z
|
core/bootstrap/srpc.hh
|
HXLLL/rlibv2
|
a9165e5863dae9c54e0fe80e682f75ec31d858c6
|
[
"Apache-2.0"
] | null | null | null |
core/bootstrap/srpc.hh
|
HXLLL/rlibv2
|
a9165e5863dae9c54e0fe80e682f75ec31d858c6
|
[
"Apache-2.0"
] | 6
|
2020-07-08T02:18:09.000Z
|
2022-02-16T01:36:13.000Z
|
#pragma once
#include <mutex> // lock
#include <utility> // std::pair
#include "./channel.hh"
#include "./multi_msg.hh"
#include "./proto.hh"
namespace rdmaio {
namespace bootstrap {
using namespace proto;
enum CallStatus : u8 {
Ok = 0,
Nop,
WrongReply,
NotMatch,
FatalErr,
};
struct __attribute__((packed)) SRpcHeader {
rpc_id_t id;
u64 checksum;
};
struct __attribute__((packed)) SReplyHeader {
u8 callstatus;
u64 checksum;
// if dummy is euqal to 1,
// then we will omit the checksum check at client
// because it is a heartbeat reply message
u8 dummy = 0;
};
/*!
A simple RPC used for establish connection for RDMA.
*/
class SRpc {
public:
static const u64 invalid_checksum = 0;
private:
Arc<SendChannel> channel;
u64 checksum = invalid_checksum + 1;
public:
using MMsg = MultiMsg<kMaxMsgSz>;
explicit SRpc(const std::string &addr)
: channel(SendChannel::create(addr).value()) {}
/*!
Send an RPC with id "id", using a specificed parameter.
*/
Result<std::string> call(const rpc_id_t &id, const ByteBuffer ¶meter) {
auto mmsg_o = MMsg::create_exact(sizeof(rpc_id_t) + parameter.size());
if (mmsg_o) {
auto &mmsg = mmsg_o.value();
RDMA_ASSERT(mmsg.append(::rdmaio::Marshal::dump<SRpcHeader>(
{.id = id, .checksum = checksum})));
RDMA_ASSERT(mmsg.append(parameter));
return channel->send(*mmsg.buf);
} else {
return ::rdmaio::Err(
std::string("Msg too large!, only kMaxMsgSz supported"));
}
}
/*!
Recv a reply from the server ysing the timeout specified.
\Note: this call must follow from a "call"
*/
Result<ByteBuffer> receive_reply(const double &timeout_usec = 1000000,
bool heartbeat = false) {
retry:
auto res = channel->recv(timeout_usec);
if (res == IOCode::Ok) {
// further we decode the header for check
try {
auto decoded_reply = MultiMsg<kMaxMsgSz>::create_from(res.desc).value();
auto header = ::rdmaio::Marshal::dedump<SReplyHeader>(
decoded_reply.query_one(0).value())
.value();
// first we handle heartbeat reply
if (header.dummy) {
if (!heartbeat)
goto retry; // ignore the heartbeat reply
return ::rdmaio::Ok(ByteBuffer(""));
}
// then we handle normal reply
if (header.checksum == checksum) {
checksum += 1;
switch (header.callstatus) {
case CallStatus::Ok:
return ::rdmaio::Ok(decoded_reply.query_one(1).value());
case CallStatus::Nop:
return ::rdmaio::Err(ByteBuffer("Not ready"));
default:
return ::rdmaio::Err(ByteBuffer("unknown error"));
}
} else
return ::rdmaio::Err(ByteBuffer("Fatal checksum error"));
} catch (std::exception &e) {
return ::rdmaio::Err(ByteBuffer("decode reply error"));
}
} else {
// the receive has error, just return
return res;
}
}
};
class SRpcHandler;
class RPCFactory {
friend class SRpcHandler;
/*!
A simple RPC function:
handle(const ByteBuffer &req) -> ByteBuffer
*/
using req_handler_f = std::function<ByteBuffer(const ByteBuffer &req)>;
std::map<rpc_id_t, req_handler_f> registered_handlers;
std::mutex lock;
RPCFactory() {
// register a default heartbeat handler
register_handler(RCtrlBinderIdType::HeartBeat,
&RPCFactory::heartbeat_handler);
};
public:
bool register_handler(rpc_id_t id, req_handler_f val) {
std::lock_guard<std::mutex> guard(lock);
if (registered_handlers.find(id) == registered_handlers.end()) {
registered_handlers.insert(std::make_pair(id, val));
return true;
}
return false;
}
ByteBuffer call_one(rpc_id_t id, const ByteBuffer ¶meter) {
auto fn = registered_handlers.find(id)->second;
return fn(parameter);
}
private:
static ByteBuffer heartbeat_handler(const ByteBuffer &b) {
return ByteBuffer("1"); // a null reply is ok
}
};
class SRpcHandler {
Arc<RecvChannel> channel;
RPCFactory factory;
public:
explicit SRpcHandler(const usize &port, const std::string &h = "localhost")
: channel(RecvChannel::create(port, h).value()) {}
bool register_handler(rpc_id_t id, RPCFactory::req_handler_f val) {
return factory.register_handler(id, val);
}
/*!
Run a event loop to call received RPC calls
\ret: number of PRCs served
*/
usize run_one_event_loop() {
usize count = 0;
for (channel->start(1000000); channel->has_msg(); channel->next(), count += 1) {
auto &msg = channel->cur();
u64 checksum = SRpc::invalid_checksum;
try {
MultiMsg<kMaxMsgSz> segmeneted_msg;
SRpcHeader header;
try {
// create from move the cur_msg to a MuiltiMsg
segmeneted_msg = MultiMsg<kMaxMsgSz>::create_from(msg).value();
// query the RPC call id
header = ::rdmaio::Marshal::dedump<SRpcHeader>(
segmeneted_msg.query_one(0).value())
.value();
checksum = header.checksum;
} catch (std::exception &e) {
// some error happens, which is fatal because we cannot decode the
// checksum
MultiMsg<kMaxMsgSz> coded_reply =
MultiMsg<kMaxMsgSz>::create_exact(sizeof(SReplyHeader)).value();
coded_reply.append(::rdmaio::Marshal::dump<SReplyHeader>(
{.callstatus = CallStatus::FatalErr,
.checksum = checksum,
.dummy = 0}));
channel->reply_cur(*coded_reply.buf);
continue;
}
// really handles the request
rpc_id_t id = header.id;
ByteBuffer parameter = segmeneted_msg.query_one(1).value();
// call the RPC
ByteBuffer reply = factory.call_one(id, parameter);
MultiMsg<kMaxMsgSz> coded_reply =
MultiMsg<kMaxMsgSz>::create_exact(sizeof(SReplyHeader) +
reply.size())
.value();
coded_reply.append(::rdmaio::Marshal::dump<SReplyHeader>(
{.callstatus = CallStatus::Ok,
.checksum = checksum,
.dummy = (id == RCtrlBinderIdType::HeartBeat)
? static_cast<u8>(1)
: static_cast<u8>(0)}));
coded_reply.append(reply);
// send the reply to the client
channel->reply_cur(*coded_reply.buf);
} catch (std::exception &e) {
MultiMsg<kMaxMsgSz> coded_reply =
MultiMsg<kMaxMsgSz>::create_exact(sizeof(SReplyHeader)).value();
// some error happens
coded_reply.append(::rdmaio::Marshal::dump<SReplyHeader>(
{.callstatus = CallStatus::Nop, .checksum = checksum}));
channel->reply_cur(*coded_reply.buf);
}
}
return count;
}
};
} // namespace bootstrap
} // namespace rdmaio
| 27.826772
| 84
| 0.604697
|
HXLLL
|
c66d7bd2cd24a9b86b2c0a2054db11807b7ad3e3
| 420
|
cpp
|
C++
|
ContainerWithMostWater/ContainerWithMostWater.cpp
|
yergen/leetcode
|
7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab
|
[
"MIT"
] | null | null | null |
ContainerWithMostWater/ContainerWithMostWater.cpp
|
yergen/leetcode
|
7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab
|
[
"MIT"
] | null | null | null |
ContainerWithMostWater/ContainerWithMostWater.cpp
|
yergen/leetcode
|
7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab
|
[
"MIT"
] | null | null | null |
#include<vector>
#include<iostream>
#include<algorithm>
using namespace::std;
class Solution {
public:
int maxArea(vector<int>& height) {
int m = 0, n = height.size();
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n;++j)
{
m = max(min(height[i], height[j])*(j - i),m);
}
return m;
}
};
int main()
{
vector<int> h{1,8,6,2,5,4,8,3,7};
Solution sol;
cout << sol.maxArea(h) << endl;
return 0;
}
| 16.153846
| 48
| 0.566667
|
yergen
|
c66d9feab8bf43eb3a8d932bc2b5b85b71c95fab
| 816
|
cpp
|
C++
|
2out/NamedTest.cpp
|
DBrutski/2out
|
28aecd80496250641672638c9ab2cfdc9e5df36d
|
[
"MIT"
] | null | null | null |
2out/NamedTest.cpp
|
DBrutski/2out
|
28aecd80496250641672638c9ab2cfdc9e5df36d
|
[
"MIT"
] | null | null | null |
2out/NamedTest.cpp
|
DBrutski/2out
|
28aecd80496250641672638c9ab2cfdc9e5df36d
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2017-2020 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
#include "NamedTest.h"
#include "NamedResult.h"
#include "SuiteTest.h"
using namespace std;
using namespace oout;
NamedTest::NamedTest(const string &name, const shared_ptr<const Test> &test)
: name(name), test(test)
{
}
NamedTest::NamedTest(const string &name, const shared_ptr<const NamedTest> &test)
: NamedTest(name, make_shared<const SuiteTest>(test))
{
}
NamedTest::NamedTest(const string &name, const list<shared_ptr<const Test>> &tests)
: NamedTest(name, make_shared<const SuiteTest>(tests))
{
}
unique_ptr<const Result> NamedTest::result() const
{
return make_unique<NamedResult>(name, test->result());
}
| 25.5
| 83
| 0.746324
|
DBrutski
|
c670d9031f90bb661f04de19db1931e8af596364
| 4,039
|
cxx
|
C++
|
test/mpi/cxx/io/fileerrx.cxx
|
OpenCMISS-Dependencies/mpich2
|
cc5f4d3fd0f8c9f2774d10deaebdced77985d839
|
[
"Unlicense"
] | 7
|
2015-12-31T03:15:50.000Z
|
2020-08-15T00:54:47.000Z
|
test/mpi/cxx/io/fileerrx.cxx
|
grondo/mvapich2-cce
|
ec084d8e07db1cf2ac1352ee4c604ae7dbae55cb
|
[
"Intel",
"mpich2",
"Unlicense"
] | 3
|
2015-12-30T22:28:15.000Z
|
2017-05-16T19:17:42.000Z
|
test/mpi/cxx/io/fileerrx.cxx
|
grondo/mvapich2-cce
|
ec084d8e07db1cf2ac1352ee4c604ae7dbae55cb
|
[
"Intel",
"mpich2",
"Unlicense"
] | 3
|
2015-12-29T22:14:56.000Z
|
2019-06-13T07:23:35.000Z
|
/* -*- Mode: C++; c-basic-offset:4 ; -*- */
/*
*
* (C) 2003 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#include "mpi.h"
#include "mpitestconf.h"
#ifdef HAVE_IOSTREAM
// Not all C++ compilers have iostream instead of iostream.h
#include <iostream>
#ifdef HAVE_NAMESPACE_STD
// Those that do often need the std namespace; otherwise, a bare "cout"
// is likely to fail to compile
using namespace std;
#endif
#else
#include <iostream.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include "mpitestcxx.h"
static int codesSeen[3], callcount;
void myerrhanfunc( MPI::File &fh, int *errcode, ... );
int main( int argc, char **argv )
{
int errs = 0;
MPI::File fh;
MPI::Intracomm comm;
MPI::Errhandler myerrhan, qerr;
char filename[50];
char *errstring;
int code[2], newerrclass, eclass, rlen;
MTest_Init( );
errstring = new char [MPI::MAX_ERROR_STRING];
callcount = 0;
// Setup some new codes and classes
newerrclass = MPI::Add_error_class();
code[0] = MPI::Add_error_code( newerrclass );
code[1] = MPI::Add_error_code( newerrclass );
MPI::Add_error_string( newerrclass, "New Class" );
MPI::Add_error_string( code[0], "First new code" );
MPI::Add_error_string( code[1], "Second new code" );
myerrhan = MPI::File::Create_errhandler( myerrhanfunc );
// Create a new communicator so that we can leave the default errors-abort
// on COMM_WORLD. Use this comm for file_open, just to leave a little
// more separation from comm_world
comm = MPI::COMM_WORLD.Dup();
fh = MPI::File::Open( comm, "testfile.txt",
MPI::MODE_RDWR | MPI::MODE_CREATE,
MPI::INFO_NULL );
fh.Set_errhandler( myerrhan );
qerr = fh.Get_errhandler();
if (qerr != myerrhan) {
errs++;
cout << " Did not get expected error handler\n";
}
qerr.Free();
// We can free our error handler now
myerrhan.Free();
fh.Call_errhandler( newerrclass );
fh.Call_errhandler( code[0] );
fh.Call_errhandler( code[1] );
if (callcount != 3) {
errs++;
cout << " Expected 3 calls to error handler, found " << callcount <<
"\n";
}
else {
if (codesSeen[0] != newerrclass) {
errs++;
cout << "Expected class " << newerrclass << " got " <<
codesSeen[0] << "\n";
}
if (codesSeen[1] != code[0]) {
errs++;
cout << "(1)Expected code " << code[0] << " got " <<
codesSeen[1] << "\n";
}
if (codesSeen[2] != code[1]) {
errs++;
cout << "(2)Expected code " << code[1] << " got " <<
codesSeen[2] << "\n";
}
}
fh.Close();
comm.Free();
MPI::File::Delete( "testfile.txt", MPI::INFO_NULL );
// Check error strings while we're here...
MPI::Get_error_string( newerrclass, errstring, rlen );
if (strcmp(errstring,"New Class") != 0) {
errs++;
cout << " Wrong string for error class: " << errstring << "\n";
}
eclass = MPI::Get_error_class( code[0] );
if (eclass != newerrclass) {
errs++;
cout << " Class for new code is not correct\n";
}
MPI::Get_error_string( code[0], errstring, rlen );
if (strcmp( errstring, "First new code") != 0) {
errs++;
cout << " Wrong string for error code: " << errstring << "\n";
}
eclass = MPI::Get_error_class( code[1] );
if (eclass != newerrclass) {
errs++;
cout << " Class for new code is not correct\n";
}
MPI::Get_error_string( code[1], errstring, rlen );
if (strcmp( errstring, "Second new code") != 0) {
errs++;
cout << " Wrong string for error code: " << errstring << "\n";
}
delete [] errstring;
MTest_Finalize( errs );
MPI::Finalize();
return 0;
}
void myerrhanfunc( MPI::File &fh, int *errcode, ... )
{
char *errstring;
int rlen;
errstring = new char [MPI::MAX_ERROR_STRING];
callcount++;
// Remember the code we've seen
if (callcount < 4) {
codesSeen[callcount-1] = *errcode;
}
MPI::Get_error_string( *errcode, errstring, rlen );
delete [] errstring;
}
| 25.726115
| 78
| 0.607824
|
OpenCMISS-Dependencies
|
c690da46c5286e03571a740c0c5831a7dd3d8697
| 11,222
|
cpp
|
C++
|
src/uml/src_gen/uml/impl/TypeImpl.cpp
|
MichaelBranz/MDE4CPP
|
5b918850a37e9cee54f6c3b92f381b0458451724
|
[
"MIT"
] | null | null | null |
src/uml/src_gen/uml/impl/TypeImpl.cpp
|
MichaelBranz/MDE4CPP
|
5b918850a37e9cee54f6c3b92f381b0458451724
|
[
"MIT"
] | 1
|
2019-03-01T00:54:13.000Z
|
2019-03-04T02:15:50.000Z
|
src/uml/src_gen/uml/impl/TypeImpl.cpp
|
vallesch/MDE4CPP
|
7f8a01dd6642820913b2214d255bef2ea76be309
|
[
"MIT"
] | null | null | null |
#include "uml/impl/TypeImpl.hpp"
#ifdef NDEBUG
#define DEBUG_MESSAGE(a) /**/
#else
#define DEBUG_MESSAGE(a) a
#endif
#ifdef ACTIVITY_DEBUG_ON
#define ACT_DEBUG(a) a
#else
#define ACT_DEBUG(a) /**/
#endif
//#include "util/ProfileCallCount.hpp"
#include <cassert>
#include <iostream>
#include <sstream>
#include "abstractDataTypes/Bag.hpp"
#include "abstractDataTypes/Subset.hpp"
#include "abstractDataTypes/SubsetUnion.hpp"
#include "abstractDataTypes/Union.hpp"
#include "abstractDataTypes/SubsetUnion.hpp"
#include "ecore/EAnnotation.hpp"
#include "ecore/EClass.hpp"
#include "uml/impl/UmlPackageImpl.hpp"
//Forward declaration includes
#include "persistence/interfaces/XLoadHandler.hpp" // used for Persistence
#include "persistence/interfaces/XSaveHandler.hpp" // used for Persistence
#include "uml/UmlFactory.hpp"
#include "uml/UmlPackage.hpp"
#include <exception> // used in Persistence
#include "uml/Association.hpp"
#include "uml/Comment.hpp"
#include "uml/Dependency.hpp"
#include "ecore/EAnnotation.hpp"
#include "uml/Element.hpp"
#include "uml/Namespace.hpp"
#include "uml/Package.hpp"
#include "uml/PackageableElement.hpp"
#include "uml/StringExpression.hpp"
#include "uml/TemplateParameter.hpp"
#include "uml/Type.hpp"
#include "ecore/EcorePackage.hpp"
#include "ecore/EcoreFactory.hpp"
#include "uml/UmlPackage.hpp"
#include "uml/UmlFactory.hpp"
#include "ecore/EAttribute.hpp"
#include "ecore/EStructuralFeature.hpp"
using namespace uml;
//*********************************
// Constructor / Destructor
//*********************************
TypeImpl::TypeImpl()
{
//*********************************
// Attribute Members
//*********************************
//*********************************
// Reference Members
//*********************************
//References
//Init references
}
TypeImpl::~TypeImpl()
{
#ifdef SHOW_DELETION
std::cout << "-------------------------------------------------------------------------------------------------\r\ndelete Type "<< this << "\r\n------------------------------------------------------------------------ " << std::endl;
#endif
}
//Additional constructor for the containments back reference
TypeImpl::TypeImpl(std::weak_ptr<uml::Namespace > par_namespace)
:TypeImpl()
{
m_namespace = par_namespace;
m_owner = par_namespace;
}
//Additional constructor for the containments back reference
TypeImpl::TypeImpl(std::weak_ptr<uml::Element > par_owner)
:TypeImpl()
{
m_owner = par_owner;
}
//Additional constructor for the containments back reference
TypeImpl::TypeImpl(std::weak_ptr<uml::Package > par_Package, const int reference_id)
:TypeImpl()
{
switch(reference_id)
{
case UmlPackage::PACKAGEABLEELEMENT_EREFERENCE_OWNINGPACKAGE:
m_owningPackage = par_Package;
m_namespace = par_Package;
return;
case UmlPackage::TYPE_EREFERENCE_PACKAGE:
m_package = par_Package;
m_namespace = par_Package;
return;
default:
std::cerr << __PRETTY_FUNCTION__ <<" Reference not found in class with the given ID" << std::endl;
}
}
//Additional constructor for the containments back reference
TypeImpl::TypeImpl(std::weak_ptr<uml::TemplateParameter > par_owningTemplateParameter)
:TypeImpl()
{
m_owningTemplateParameter = par_owningTemplateParameter;
m_owner = par_owningTemplateParameter;
}
//Additional constructor for the containments back reference
TypeImpl::TypeImpl(const TypeImpl & obj):TypeImpl()
{
//create copy of all Attributes
#ifdef SHOW_COPIES
std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\ncopy Type "<< this << "\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " << std::endl;
#endif
m_name = obj.getName();
m_qualifiedName = obj.getQualifiedName();
m_visibility = obj.getVisibility();
//copy references with no containment (soft copy)
std::shared_ptr<Bag<uml::Dependency>> _clientDependency = obj.getClientDependency();
m_clientDependency.reset(new Bag<uml::Dependency>(*(obj.getClientDependency().get())));
m_namespace = obj.getNamespace();
m_owner = obj.getOwner();
m_owningPackage = obj.getOwningPackage();
m_owningTemplateParameter = obj.getOwningTemplateParameter();
m_package = obj.getPackage();
m_templateParameter = obj.getTemplateParameter();
//Clone references with containment (deep copy)
std::shared_ptr<Bag<ecore::EAnnotation>> _eAnnotationsList = obj.getEAnnotations();
for(std::shared_ptr<ecore::EAnnotation> _eAnnotations : *_eAnnotationsList)
{
this->getEAnnotations()->add(std::shared_ptr<ecore::EAnnotation>(std::dynamic_pointer_cast<ecore::EAnnotation>(_eAnnotations->copy())));
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_eAnnotations" << std::endl;
#endif
if(obj.getNameExpression()!=nullptr)
{
m_nameExpression = std::dynamic_pointer_cast<uml::StringExpression>(obj.getNameExpression()->copy());
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_nameExpression" << std::endl;
#endif
std::shared_ptr<Bag<uml::Comment>> _ownedCommentList = obj.getOwnedComment();
for(std::shared_ptr<uml::Comment> _ownedComment : *_ownedCommentList)
{
this->getOwnedComment()->add(std::shared_ptr<uml::Comment>(std::dynamic_pointer_cast<uml::Comment>(_ownedComment->copy())));
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_ownedComment" << std::endl;
#endif
}
std::shared_ptr<ecore::EObject> TypeImpl::copy() const
{
std::shared_ptr<TypeImpl> element(new TypeImpl(*this));
element->setThisTypePtr(element);
return element;
}
std::shared_ptr<ecore::EClass> TypeImpl::eStaticClass() const
{
return UmlPackageImpl::eInstance()->getType_EClass();
}
//*********************************
// Attribute Setter Getter
//*********************************
//*********************************
// Operations
//*********************************
bool TypeImpl::conformsTo(std::shared_ptr<uml::Type> other)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
std::shared_ptr<uml::Association> TypeImpl::createAssociation(bool end1IsNavigable,AggregationKind end1Aggregation,std::string end1Name,int end1Lower,int end1Upper,std::shared_ptr<uml::Type> end1Type,bool end2IsNavigable,AggregationKind end2Aggregation,std::string end2Name,int end2Lower,int end2Upper)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
std::shared_ptr<Bag<uml::Association> > TypeImpl::getAssociations()
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
//*********************************
// References
//*********************************
std::weak_ptr<uml::Package > TypeImpl::getPackage() const
{
return m_package;
}
void TypeImpl::setPackage(std::shared_ptr<uml::Package> _package)
{
m_package = _package;
}
//*********************************
// Union Getter
//*********************************
std::weak_ptr<uml::Namespace > TypeImpl::getNamespace() const
{
return m_namespace;
}
std::shared_ptr<Union<uml::Element>> TypeImpl::getOwnedElement() const
{
return m_ownedElement;
}
std::weak_ptr<uml::Element > TypeImpl::getOwner() const
{
return m_owner;
}
std::shared_ptr<Type> TypeImpl::getThisTypePtr() const
{
return m_thisTypePtr.lock();
}
void TypeImpl::setThisTypePtr(std::weak_ptr<Type> thisTypePtr)
{
m_thisTypePtr = thisTypePtr;
setThisPackageableElementPtr(thisTypePtr);
}
std::shared_ptr<ecore::EObject> TypeImpl::eContainer() const
{
if(auto wp = m_namespace.lock())
{
return wp;
}
if(auto wp = m_owner.lock())
{
return wp;
}
if(auto wp = m_owningPackage.lock())
{
return wp;
}
if(auto wp = m_package.lock())
{
return wp;
}
if(auto wp = m_owningTemplateParameter.lock())
{
return wp;
}
return nullptr;
}
//*********************************
// Structural Feature Getter/Setter
//*********************************
Any TypeImpl::eGet(int featureID, bool resolve, bool coreType) const
{
switch(featureID)
{
case UmlPackage::TYPE_EREFERENCE_PACKAGE:
return eAny(getPackage()); //2613
}
return PackageableElementImpl::eGet(featureID, resolve, coreType);
}
bool TypeImpl::internalEIsSet(int featureID) const
{
switch(featureID)
{
case UmlPackage::TYPE_EREFERENCE_PACKAGE:
return getPackage().lock() != nullptr; //2613
}
return PackageableElementImpl::internalEIsSet(featureID);
}
bool TypeImpl::eSet(int featureID, Any newValue)
{
switch(featureID)
{
case UmlPackage::TYPE_EREFERENCE_PACKAGE:
{
// BOOST CAST
std::shared_ptr<uml::Package> _package = newValue->get<std::shared_ptr<uml::Package>>();
setPackage(_package); //2613
return true;
}
}
return PackageableElementImpl::eSet(featureID, newValue);
}
//*********************************
// Persistence Functions
//*********************************
void TypeImpl::load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler)
{
std::map<std::string, std::string> attr_list = loadHandler->getAttributeList();
loadAttributes(loadHandler, attr_list);
//
// Create new objects (from references (containment == true))
//
// get UmlFactory
std::shared_ptr<uml::UmlFactory> modelFactory = uml::UmlFactory::eInstance();
int numNodes = loadHandler->getNumOfChildNodes();
for(int ii = 0; ii < numNodes; ii++)
{
loadNode(loadHandler->getNextNodeName(), loadHandler, modelFactory);
}
}
void TypeImpl::loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list)
{
PackageableElementImpl::loadAttributes(loadHandler, attr_list);
}
void TypeImpl::loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::shared_ptr<uml::UmlFactory> modelFactory)
{
PackageableElementImpl::loadNode(nodeName, loadHandler, modelFactory);
}
void TypeImpl::resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references)
{
switch(featureID)
{
case UmlPackage::TYPE_EREFERENCE_PACKAGE:
{
if (references.size() == 1)
{
// Cast object to correct type
std::shared_ptr<uml::Package> _package = std::dynamic_pointer_cast<uml::Package>( references.front() );
setPackage(_package);
}
return;
}
}
PackageableElementImpl::resolveReferences(featureID, references);
}
void TypeImpl::save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
saveContent(saveHandler);
PackageableElementImpl::saveContent(saveHandler);
NamedElementImpl::saveContent(saveHandler);
ParameterableElementImpl::saveContent(saveHandler);
ElementImpl::saveContent(saveHandler);
ecore::EModelElementImpl::saveContent(saveHandler);
ObjectImpl::saveContent(saveHandler);
ecore::EObjectImpl::saveContent(saveHandler);
}
void TypeImpl::saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
try
{
std::shared_ptr<uml::UmlPackage> package = uml::UmlPackage::eInstance();
}
catch (std::exception& e)
{
std::cout << "| ERROR | " << e.what() << std::endl;
}
}
| 25.105145
| 303
| 0.671894
|
MichaelBranz
|
c691771b3d95c6170f28ab814ecfc5b04c35fbad
| 4,732
|
cpp
|
C++
|
terrain_generator/src/gen/Document.cpp
|
marek-cel/fightersfs-tools
|
e692a8af7e44cfae6e35ecfa916d3ffdc46a9eb3
|
[
"CC0-1.0"
] | null | null | null |
terrain_generator/src/gen/Document.cpp
|
marek-cel/fightersfs-tools
|
e692a8af7e44cfae6e35ecfa916d3ffdc46a9eb3
|
[
"CC0-1.0"
] | null | null | null |
terrain_generator/src/gen/Document.cpp
|
marek-cel/fightersfs-tools
|
e692a8af7e44cfae6e35ecfa916d3ffdc46a9eb3
|
[
"CC0-1.0"
] | 1
|
2021-02-22T21:22:33.000Z
|
2021-02-22T21:22:33.000Z
|
/****************************************************************************//*
* Copyright (C) 2020 Marek M. Cel
*
* 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 <osgDB/WriteFile>
#include <osgUtil/Optimizer>
#include <QFileInfo>
#include <QTextStream>
#include <gen/Document.h>
////////////////////////////////////////////////////////////////////////////////
Document::Document() :
m_terrain ( 0 )
{
newEmpty();
}
////////////////////////////////////////////////////////////////////////////////
Document::Document( QString fileName ) :
m_terrain ( 0 )
{
readFile( fileName );
}
////////////////////////////////////////////////////////////////////////////////
Document::~Document()
{
if ( m_terrain ) delete m_terrain;
m_terrain = 0;
}
////////////////////////////////////////////////////////////////////////////////
void Document::newEmpty()
{
if ( m_terrain ) delete m_terrain;
m_terrain = 0;
m_terrain = new Terrain();
}
////////////////////////////////////////////////////////////////////////////////
bool Document::exportAs( QString fileName )
{
osgUtil::Optimizer optimizer;
int options = osgUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS |
osgUtil::Optimizer::REMOVE_REDUNDANT_NODES |
osgUtil::Optimizer::REMOVE_LOADED_PROXY_NODES |
osgUtil::Optimizer::COMBINE_ADJACENT_LODS |
osgUtil::Optimizer::SHARE_DUPLICATE_STATE |
osgUtil::Optimizer::MERGE_GEOMETRY |
osgUtil::Optimizer::MAKE_FAST_GEOMETRY |
osgUtil::Optimizer::CHECK_GEOMETRY |
osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS |
osgUtil::Optimizer::STATIC_OBJECT_DETECTION;
optimizer.optimize( m_terrain->getRoot(), options );
osgDB::writeNodeFile( *( m_terrain->getRoot() ), fileName.toStdString() );
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool Document::generateElevation( QString fileName )
{
return m_terrain->generateElevation( fileName );
}
////////////////////////////////////////////////////////////////////////////////
bool Document::readFile( QString fileName )
{
newEmpty();
QFile devFile( fileName );
if ( devFile.open( QFile::ReadOnly | QFile::Text ) )
{
QDomDocument doc;
doc.setContent( &devFile, false );
QDomElement rootNode = doc.documentElement();
if ( rootNode.tagName() == "terrain" )
{
if ( m_terrain ) delete m_terrain;
m_terrain = 0;
m_terrain = new Terrain( &rootNode );
return true;
}
devFile.close();
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool Document::saveFile( QString fileName )
{
QString fileTemp = fileName;
if ( QFileInfo( fileTemp ).suffix() != QString( "xml" ) )
{
fileTemp += ".xml";
}
QFile devFile( fileTemp );
if ( devFile.open( QFile::WriteOnly | QFile::Truncate | QFile::Text ) )
{
QTextStream out;
out.setDevice( &devFile );
out.setCodec("UTF-8");
out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
QDomDocument doc( "terrain" );
doc.setContent( &devFile, false );
QDomElement dataNode = doc.createElement( "terrain" );
doc.appendChild( dataNode );
m_terrain->save( &doc, &dataNode );
out << doc.toString();
devFile.close();
return true;
}
return false;
}
| 28.506024
| 80
| 0.531488
|
marek-cel
|
c691d6ee70928d2af3c4fda40cc2abc5dbe0c2bd
| 402
|
cpp
|
C++
|
Codebreaker/problems/prefixsums/prefixsums.cpp
|
object-oriented-human/competitive
|
9e761020e887d8980a39a64eeaeaa39af0ecd777
|
[
"MIT"
] | 2
|
2021-07-27T10:46:47.000Z
|
2021-07-27T10:47:57.000Z
|
Codebreaker/problems/prefixsums/prefixsums.cpp
|
foooop/competitive
|
9e761020e887d8980a39a64eeaeaa39af0ecd777
|
[
"MIT"
] | null | null | null |
Codebreaker/problems/prefixsums/prefixsums.cpp
|
foooop/competitive
|
9e761020e887d8980a39a64eeaeaa39af0ecd777
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int n, q, l, r;
cin >> n >> q;
long long arr[n], pre[n+1];
pre[0] = 0;
for (int i = 0; i < n; i++) {
cin >> arr[i];
pre[i+1] = pre[i] + arr[i];
}
while (q--) {
cin >> l >> r;
cout << pre[r] - pre[l-1] << "\n";
}
}
| 18.272727
| 42
| 0.41791
|
object-oriented-human
|
c696f7511726ba3926ab439ccffe30451927f2ee
| 265
|
cpp
|
C++
|
codeforce1/68A. Irrational problem.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
codeforce1/68A. Irrational problem.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
codeforce1/68A. Irrational problem.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
using namespace std;
int main() {
int p1, p2, p3, p4, a, b, res = 0;
scanf("%d %d %d %d %d %d", &p1, &p2, &p3, &p4, &a, &b);
for(int i = a; i <= b; ++i)
if(i == (((i % p1) % p2) % p3) % p4)
++res;
printf("%d\n", res);
return 0;
}
| 17.666667
| 56
| 0.449057
|
khaled-farouk
|
c6978ccc95c5107ae3b593a395d45c7448526eca
| 7,899
|
cpp
|
C++
|
Examples/Tutorial1.cpp
|
haskellstudio/belle_old
|
a5ce86954b61dbacde1d1bf24472d95246be45e5
|
[
"BSD-2-Clause"
] | null | null | null |
Examples/Tutorial1.cpp
|
haskellstudio/belle_old
|
a5ce86954b61dbacde1d1bf24472d95246be45e5
|
[
"BSD-2-Clause"
] | null | null | null |
Examples/Tutorial1.cpp
|
haskellstudio/belle_old
|
a5ce86954b61dbacde1d1bf24472d95246be45e5
|
[
"BSD-2-Clause"
] | null | null | null |
/*
==============================================================================
Copyright 2007-2013 William Andrew Burnson. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY WILLIAM ANDREW BURNSON ''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 WILLIAM ANDREW BURNSON 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.
------------------------------------------------------------------------------
This file is part of Belle, Bonne, Sage --
The 'Beautiful, Good, Wise' C++ Vector-Graphics Library for Music Notation
==============================================================================
*/
//------------------------------------------------------------------------------
/*
Tutorial 1: Drawing simple graphics manually in Belle
This tutorial explains the graphics abstraction used by Belle, Bonne, Sage. It
assumes familiarity with prim as seen in Tutorial 0.
On Mac/Linux you can build and run from the terminal using:
Scripts/MakeAndRun Tutorial1
For more information related to building, see the README.
*/
//------------------------------------------------------------------------------
//Include Belle, Bonne, Sage and compile it in this .cpp file.
#define BELLE_COMPILE_INLINE
#include "Belle.h"
//These were discussed in Tutorial 0.
using namespace prim;
using namespace prim::planar;
/*The core belle namespace.
It contains classes relevant to drawing such as Affine, Canvas, Color, Font,
Painter, Path, Portfolio, Shapes, Text.*/
using namespace belle;
//Belle has output painters which are rendering targets such as PDF and JUCE.
using namespace belle::painters;
//------------------------------------------------------------------------------
/*In Belle there are three fundamental abstract data types for graphics:
Portfolio, Canvas, and Painter.
The Portfolio contains a list of Canvases and can be thought of as a document
with multiple pages. The user of the library must at least subclass
Canvas, and implement the Paint virtual method. If the user needs the
Portfolio to store any information relevant to the whole document to be accessed
during the Paint, then the Portfolio should also be subclassed.
The Painter is a device-independent vector graphics object and could represent
file or screen-based output.
This example will show how to subclass both Portfolio and Canvas and how to use
the PDF and SVG painters.
*/
//Subclass Score from belle::Portfolio
struct Score : public Portfolio
{
//An array of rectangles to paint.
Array<Rectangle> RectanglesToPaint;
/*Subclass Page from belle::Canvas. Note that Page is a class inside
a class, so it is really a Score::Page; however, it is not necessary to do it
this way. It just logically groups the Page class with the Score to which it
pertains.*/
struct Page : public Canvas
{
//This method gets called once per canvas.
void Paint(Painter& Painter, Portfolio& Portfolio)
{
/*Since we need access to the Score (as opposed to base class Portfolio)
in order to draw the rectangles, we can forward the paint call to a custom
paint method which uses a Score& instead of a Portfolio&.*/
Paint(Painter, dynamic_cast<Score&>(Portfolio));
}
//Custom paint method with score.
void Paint(Painter& Painter, Score& Score)
{
//Print which page is being painted.
c >> "Painting page: " << Painter.GetPageNumber();
//Paint each rectangle in the rectangle array.
for(count i = 0; i < Score.RectanglesToPaint.n(); i++)
{
/*Create an empty path. A path is a vector graphics object containing
a list of core instructions: move-to (start new path), line-to,
cubic-to (Bezier curve), and close-path. Generally, multiple subpaths
are interpreted by the rendering targets according to the zero-winding
rule.*/
Path p;
/*Add the rectangle shape to the path. The Shapes class contains several
primitive building methods.*/
Shapes::AddRectangle(p, Score.RectanglesToPaint[i]);
//Alternate green fill with blue stroke.
if(i % 2 == 0)
Painter.SetFill(Colors::green);
else
Painter.SetStroke(Colors::blue, 0.01);
//Draw the path, separating the fills and strokes by page.
if(i % 2 == Painter.GetPageNumber())
Painter.Draw(p);
}
}
};
};
//This program creates a couple of pages with some rectangles using Belle.
int main()
{
//Step 1: Create a score, add some pages, and give it some information.
//Instantiate a score.
Score MyScore;
//Add a portrait page to the score.
MyScore.Canvases.Add() = new Score::Page;
MyScore.Canvases.z()->Dimensions = Paper::Portrait(Paper::Letter);
//Add a landscape page to the score.
MyScore.Canvases.Add() = new Score::Page;
MyScore.Canvases.z()->Dimensions = Paper::Landscape(Paper::Letter);
/*Add some rectangles for the score to paint. Note this is just a custom
member that was created to demonstrate how to pass information to the painter.
There is nothing intrinsic to the Score about painting rectangles.*/
const number GeometricConstant = 1.2;
for(number i = 0.01; i < 8.0; i *= GeometricConstant)
MyScore.RectanglesToPaint.Add() = Rectangle(Vector(i, i), Vector(i, i) *
GeometricConstant);
//Step 2a: Draw the score to PDF.
/*Set the PDF-specific properties, for example, the output filename. If no
filename is set, then the contents of the PDF file end up in
PDF::Properties::Output.*/
PDF::Properties PDFSpecificProperties;
PDFSpecificProperties.Filename = "Tutorial1.pdf";
/*Write the score to PDF. Note how in Belle, the Canvas Paint() method is
never called directly. Instead a portfolio creates a render target which then
calls back the paint method on each canvas. This is an extension of the
device-independent graphics paradigm.*/
MyScore.Create<PDF>(PDFSpecificProperties);
//Print the name of the output file.
c >> "Wrote PDF to '" << PDFSpecificProperties.Filename << "'.";
/*Step 2b: Here is the same thing except using the SVG renderer. Since SVG is
an image format, the result will be a sequence of files.*/
/*Set the SVG-specific properties, for example, the output filename prefix. If
no filename is set, then the contents of the SVG file end up in the
SVG::Properties::Output array.*/
SVG::Properties SVGSpecificProperties;
SVGSpecificProperties.FilenameStem = "Tutorial1-";
//Write the score to SVG.
MyScore.Create<SVG>(SVGSpecificProperties);
//Note the name of the output file to console window.
c >> "Wrote SVGs to '" << SVGSpecificProperties.FilenameStem << "*.svg'.";
//Finish the console output.
c.Finish();
return 0;
}
| 39.298507
| 80
| 0.677681
|
haskellstudio
|
57927aac4a22c9f89ac86a3479e6d473a5015e39
| 998
|
cpp
|
C++
|
Hacker Rank/Equal_Stacks.cpp
|
aryabharat/ONLINE_CODING
|
3f3318c5e660d9b30c14618db8068816ba902d0f
|
[
"Apache-2.0"
] | 1
|
2019-03-17T09:30:08.000Z
|
2019-03-17T09:30:08.000Z
|
Hacker Rank/Equal_Stacks.cpp
|
aryabharat/ONLINE_CODING
|
3f3318c5e660d9b30c14618db8068816ba902d0f
|
[
"Apache-2.0"
] | null | null | null |
Hacker Rank/Equal_Stacks.cpp
|
aryabharat/ONLINE_CODING
|
3f3318c5e660d9b30c14618db8068816ba902d0f
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n1,n2,n3;
cin >> n1 >> n2 >> n3;
vector <int> a (n1);
vector <int> b (n2);
vector <int> c (n3);
int s1=0,s2=0,s3=0;
for(int i=0;i<n1;i++)
{
cin >> a[i];
s1+=a[i];
}
for(int i=0;i<n2;i++)
{
cin >> b[i];
s2+=b[i];
}
for(int i=0;i<n3;i++)
{
cin >> c[i];
s3+=c[i];
}
bool ans = false;
if(s1 == s2 && s2 == s3)
{
cout << s2 << "\n";
ans = true;
}
int i=0,j=0,k=0;
while(!ans)
{
if((s1 == s2 && s2 == s3) || (s1 == 0 && s2 == 0 && s3 ==0))
{
ans = true;
cout << s1 <<"\n";
continue;
}
if(s1 > s2)
{
s1-=a[i];
i++;
}
else if(s2>s3)
{
s2-=b[j];
j++;
}
else
{
s3-=c[k];
k++;
}
}
}
| 16.633333
| 68
| 0.298597
|
aryabharat
|
5792f109530c70a22aa33a23ff491e5c56d6fcc2
| 718
|
cpp
|
C++
|
src/regularizers/regularizer_l1_l2.cpp
|
Seraphid/eddl
|
f627585a05edb91aaf991b898163cbe8cca66caf
|
[
"MIT"
] | null | null | null |
src/regularizers/regularizer_l1_l2.cpp
|
Seraphid/eddl
|
f627585a05edb91aaf991b898163cbe8cca66caf
|
[
"MIT"
] | null | null | null |
src/regularizers/regularizer_l1_l2.cpp
|
Seraphid/eddl
|
f627585a05edb91aaf991b898163cbe8cca66caf
|
[
"MIT"
] | null | null | null |
/*
* EDDL Library - European Distributed Deep Learning Library.
* Version: 0.3
* copyright (c) 2019, Universidad Politรฉcnica de Valencia (UPV), PRHLT Research Centre
* Date: October 2019
* Author: PRHLT Research Centre, UPV, (rparedes@prhlt.upv.es), (jon@prhlt.upv.es)
* All rights reserved
*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "regularizer.h"
using namespace std;
RL1L2::RL1L2(float l1, float l2) : Regularizer("l1_l2") {
this->l1 = l1;
this->l2 = l2;
}
void RL1L2::apply(Tensor* T) {
Tensor *S = T->clone();
Tensor *A = T->clone();
S->sign_();
Tensor::add(1.0f, T, -this->l1, S, T, 0);
Tensor::add(1.0f, T, -this->l2, A, T, 0);
delete A;
delete S;
}
| 19.405405
| 86
| 0.643454
|
Seraphid
|
57953b4740e7cbf56e605f36e0e47547f20abe2e
| 1,935
|
cpp
|
C++
|
Ds18b20.cpp
|
konkers/mcp
|
4b926e886cb812177b3755f915bf53e866675c5d
|
[
"Apache-2.0"
] | null | null | null |
Ds18b20.cpp
|
konkers/mcp
|
4b926e886cb812177b3755f915bf53e866675c5d
|
[
"Apache-2.0"
] | null | null | null |
Ds18b20.cpp
|
konkers/mcp
|
4b926e886cb812177b3755f915bf53e866675c5d
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2013 Erik Gilling <konkers@konkers.net>
//
// 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 Licene.
#include "Ds18b20.hpp"
#define DS18B20_CMD_CONVERT_T 0x44
#define DS18B20_CMD_WRITE_SCRATCHPAD 0x4e
#define DS18B20_CMD_READ_SCRATCHPAD 0xbe
#define DS18B20_CMD_COPY_SCRATCHPAD 0x48
#define DS18B20_CMD_RECAL_E2 0xb8
#define DS18B20_CMD_READ_PS 0xb4
Ds18b20::Ds18b20(Dongle *dongle, Dongle::Addr addr, std::string name, float cal0, float cal100) :
dongle(dongle), addr(addr), name(name) {
offset = -cal0;
scale = 100.0 / (cal100 - cal0);
}
Ds18b20::Ds18b20(Dongle *dongle, Dongle::Addr addr) :
dongle(dongle), addr(addr), offset(0.0), scale(1.0) {
name = addr.getName();
}
void Ds18b20::startConversion(void)
{
dongle->reset();
dongle->matchRom(addr);
dongle->writeByte(DS18B20_CMD_CONVERT_T);
}
void Ds18b20::startAllConversion(void)
{
dongle->reset();
dongle->skipRom();
dongle->writeByte(DS18B20_CMD_CONVERT_T);
}
bool Ds18b20::isConversionDone(void)
{
return dongle->read() == 1;
}
void Ds18b20::updateTemp(void)
{
unsigned val;
float newTemp;
dongle->reset();
dongle->matchRom(addr);
dongle->writeByte(DS18B20_CMD_READ_SCRATCHPAD);
val = dongle->readByte();
val |= dongle->readByte() << 8;
newTemp = (val >> 4) + (val & 0xf) * (1.0/16.0);
newTemp -= offset;
newTemp *= scale;
temp = newTemp;
}
| 26.875
| 97
| 0.694057
|
konkers
|
579588c078078f70999774e00fd4cab4ecd210d1
| 2,055
|
hpp
|
C++
|
Tests/Tests.hpp
|
bbercovici/RigidBodyKinematics
|
110d30cc20251081a4558f6851bdfd5abc0fdd82
|
[
"MIT"
] | null | null | null |
Tests/Tests.hpp
|
bbercovici/RigidBodyKinematics
|
110d30cc20251081a4558f6851bdfd5abc0fdd82
|
[
"MIT"
] | null | null | null |
Tests/Tests.hpp
|
bbercovici/RigidBodyKinematics
|
110d30cc20251081a4558f6851bdfd5abc0fdd82
|
[
"MIT"
] | null | null | null |
// MIT License
// Copyright (c) 2018 Benjamin Bercovici
// 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.
namespace Tests{
void test_euler321_to_mrp();
void test_dXattitudedt() ;
void test_domegadt() ;
void test_dmrpdt();
void test_shadow_mrp() ;
void test_mrp_to_quat();
void test_euler321d_to_dcm();
void test_euler313d_to_dcm();
void test_euler313d_to_mrp();
void test_euler321d_to_mrp();
void test_mrp_to_dcm();
void test_dcm_to_mrp();
void test_euler313_to_mrp();
void test_euler313_to_dcm();
void test_longitude_latitude_to_dcm();
void test_tilde();
void test_M1();
void test_M2();
void test_M3();
void test_dcm_to_euler321();
void test_dcm_to_euler313();
void test_mrp_to_euler313();
void test_mrp_to_euler321();
void test_dcm_to_euler321d();
void test_dcm_to_euler313d();
void test_mrp_to_euler313d();
void test_mrp_to_euler321d();
void test_dcm_to_quat() ;
void test_dcm_to_prv() ;
void test_prv_to_dcm();
void test_prv_to_mrp();
void test_Bmat();
void test_partial_mrp_dot_partial_mrp();
}
| 35.431034
| 81
| 0.771776
|
bbercovici
|
579a8f2bcac59e5a1b4c8cd04e1db176cfddd175
| 5,233
|
cpp
|
C++
|
src/thread.cpp
|
corehacker/ch-cpp-utils
|
4b03045fbecc867f7c6b088eabd8aa4cc30f1170
|
[
"MIT"
] | 5
|
2017-11-05T11:41:42.000Z
|
2020-09-03T07:49:12.000Z
|
src/thread.cpp
|
corehacker/ch-cpp-utils
|
4b03045fbecc867f7c6b088eabd8aa4cc30f1170
|
[
"MIT"
] | 1
|
2017-11-14T02:50:16.000Z
|
2017-11-14T02:50:16.000Z
|
src/thread.cpp
|
corehacker/ch-cpp-utils
|
4b03045fbecc867f7c6b088eabd8aa4cc30f1170
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
*
* BSD 2-Clause License
*
* Copyright (c) 2017, Sandeep Prakash
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
******************************************************************************/
/*******************************************************************************
* Copyright (c) 2017, Sandeep Prakash <123sandy@gmail.com>
*
* \file thread.cpp
*
* \author Sandeep Prakash
*
* \date Apr 1, 2017
*
* \brief
*
******************************************************************************/
#include <iostream>
#include <glog/logging.h>
#include "ch-cpp-utils/thread.hpp"
using namespace std;
namespace ChCppUtils {
void *
Thread::threadFunc (void *this_)
{
Thread *t = (Thread *) this_;
t->run ();
LOG(INFO) << "Exiting thread routine" <<std::endl;
return NULL;
}
void
Thread::run ()
{
if (true == mBase)
{
mEventBase = event_base_new();
LOG(INFO) << "Creating event base: " << mEventBase;
}
else
{
mEventBase = NULL;
LOG(INFO) << "Not creating event base: " << mEventBase;
}
if(mInitCbk) {
mInitCbk(mInitCbkThis);
}
mSemaphore.notify();
LOG(INFO) << "Notified start.";
while (true) {
ThreadJobBase *job = mGetJob (mGetJobThis);
if(job->isExit()) {
LOG(INFO) << "Exit Job Command";
SAFE_DELETE(job);
break;
}
runJob (job);
}
if(mDeInitCbk) {
mDeInitCbk(mDeInitCbkThis);
}
if(mEventBase) {
event_base_free(mEventBase);
mEventBase = NULL;
}
LOG(INFO) << "Exited thread.";
mThread->detach();
LOG(INFO) << "Detached thread.";
mSemaphore.notify();
LOG(INFO) << "Notified exit.";
}
void
Thread::runJob (ThreadJobBase *job)
{
if (job->routine) {
job->routine (job->arg, mEventBase);
}
SAFE_DELETE(job);
}
thread::id Thread::getId() {
return mThread->get_id();
}
void Thread::join() {
if (mThread->joinable()) {
LOG(INFO) << "Joining thread: 0x" << std::hex << getId() << std::dec ;
mThread->join();
}
}
struct event_base *Thread::getEventBase() {
return mEventBase;
}
Thread::Thread (ThreadGetJob getJob, void *this_)
{
LOG(INFO) << "Creating thread";
mGetJob = getJob;
mGetJobThis = this_;
mBase = false;
mEventBase = NULL;
mInitCbk = nullptr;
mInitCbkThis = nullptr;
mThread = nullptr;
mDeInitCbk = nullptr;
mDeInitCbkThis = nullptr;
}
Thread::Thread (ThreadGetJob getJob, void *this_, bool base)
{
LOG(INFO) << "*****Thread";
mGetJob = getJob;
mGetJobThis = this_;
mBase = base;
mEventBase = NULL;
mInitCbk = nullptr;
mInitCbkThis = nullptr;
mThread = nullptr;
mDeInitCbk = nullptr;
mDeInitCbkThis = nullptr;
}
Thread::Thread (ThreadGetJob getJob, void *this_, bool base,
ThreadInitCbk initCbk, void *initCbkThis,
ThreadDeInitCbk deinitCbk, void *deinitCbkThis) {
LOG(INFO) << "*****Thread";
mGetJob = getJob;
mGetJobThis = this_;
mBase = base;
mEventBase = NULL;
mInitCbk = initCbk;
mInitCbkThis = initCbkThis;
mDeInitCbk = deinitCbk;
mDeInitCbkThis = deinitCbkThis;
mThread = nullptr;
}
void Thread::start() {
mThread = new std::thread(Thread::threadFunc, this);
LOG(INFO) << "Waiting for thread to start: 0x" << std::hex << getId() << std::dec ;
mSemaphore.wait();
LOG(INFO) << "Thread start complete: 0x" << std::hex << getId() << std::dec ;
}
Thread::~Thread ()
{
LOG(INFO) << "*****~Thread";
thread::id id = getId();
LOG(INFO) << "Waiting for thread to exit: 0x" << std::hex << id << std::dec ;
mSemaphore.wait();
LOG(INFO) << "Thread exited: 0x" << std::hex << id << std::dec;
SAFE_DELETE(mThread);
}
}
| 26.974227
| 85
| 0.590101
|
corehacker
|
579cf96ef36d30823a70b491cc0015e6813be116
| 7,562
|
cpp
|
C++
|
src/gpu/GrTextureParamsAdjuster.cpp
|
Perspex/skia
|
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
|
[
"Apache-2.0"
] | 2
|
2019-07-19T17:40:28.000Z
|
2020-05-09T11:58:41.000Z
|
src/gpu/GrTextureParamsAdjuster.cpp
|
AvaloniaUI/skia
|
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
|
[
"Apache-2.0"
] | null | null | null |
src/gpu/GrTextureParamsAdjuster.cpp
|
AvaloniaUI/skia
|
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrTextureParamsAdjuster.h"
#include "GrCaps.h"
#include "GrContext.h"
#include "GrDrawContext.h"
#include "GrGpu.h"
#include "GrGpuResourcePriv.h"
#include "GrResourceKey.h"
#include "GrTexture.h"
#include "GrTextureParams.h"
#include "GrTextureProvider.h"
#include "SkCanvas.h"
#include "SkGr.h"
#include "SkGrPriv.h"
#include "effects/GrTextureDomain.h"
typedef GrTextureProducer::CopyParams CopyParams;
//////////////////////////////////////////////////////////////////////////////
static GrTexture* copy_on_gpu(GrTexture* inputTexture, const SkIRect* subset,
const CopyParams& copyParams) {
SkASSERT(!subset || !subset->isEmpty());
GrContext* context = inputTexture->getContext();
SkASSERT(context);
const GrCaps* caps = context->caps();
// Either it's a cache miss or the original wasn't cached to begin with.
GrSurfaceDesc rtDesc = inputTexture->desc();
rtDesc.fFlags = rtDesc.fFlags | kRenderTarget_GrSurfaceFlag;
rtDesc.fWidth = copyParams.fWidth;
rtDesc.fHeight = copyParams.fHeight;
rtDesc.fConfig = GrMakePixelConfigUncompressed(rtDesc.fConfig);
// If the config isn't renderable try converting to either A8 or an 32 bit config. Otherwise,
// fail.
if (!caps->isConfigRenderable(rtDesc.fConfig, false)) {
if (GrPixelConfigIsAlphaOnly(rtDesc.fConfig)) {
if (caps->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
rtDesc.fConfig = kAlpha_8_GrPixelConfig;
} else if (caps->isConfigRenderable(kSkia8888_GrPixelConfig, false)) {
rtDesc.fConfig = kSkia8888_GrPixelConfig;
} else {
return nullptr;
}
} else if (kRGB_GrColorComponentFlags ==
(kRGB_GrColorComponentFlags & GrPixelConfigComponentMask(rtDesc.fConfig))) {
if (caps->isConfigRenderable(kSkia8888_GrPixelConfig, false)) {
rtDesc.fConfig = kSkia8888_GrPixelConfig;
} else {
return nullptr;
}
} else {
return nullptr;
}
}
SkAutoTUnref<GrTexture> copy(context->textureProvider()->createTexture(rtDesc, true));
if (!copy) {
return nullptr;
}
// TODO: If no scaling is being performed then use copySurface.
GrPaint paint;
SkScalar sx;
SkScalar sy;
if (subset) {
sx = 1.f / inputTexture->width();
sy = 1.f / inputTexture->height();
}
if (copyParams.fFilter != GrTextureParams::kNone_FilterMode && subset &&
(subset->width() != copyParams.fWidth || subset->height() != copyParams.fHeight)) {
SkRect domain;
domain.fLeft = (subset->fLeft + 0.5f) * sx;
domain.fTop = (subset->fTop + 0.5f)* sy;
domain.fRight = (subset->fRight - 0.5f) * sx;
domain.fBottom = (subset->fBottom - 0.5f) * sy;
// This would cause us to read values from outside the subset. Surely, the caller knows
// better!
SkASSERT(copyParams.fFilter != GrTextureParams::kMipMap_FilterMode);
paint.addColorFragmentProcessor(
GrTextureDomainEffect::Create(inputTexture, SkMatrix::I(), domain,
GrTextureDomain::kClamp_Mode,
copyParams.fFilter))->unref();
} else {
GrTextureParams params(SkShader::kClamp_TileMode, copyParams.fFilter);
paint.addColorTextureProcessor(inputTexture, SkMatrix::I(), params);
}
SkRect localRect;
if (subset) {
localRect = SkRect::Make(*subset);
localRect.fLeft *= sx;
localRect.fTop *= sy;
localRect.fRight *= sx;
localRect.fBottom *= sy;
} else {
localRect = SkRect::MakeWH(1.f, 1.f);
}
SkAutoTUnref<GrDrawContext> drawContext(context->drawContext(copy->asRenderTarget()));
if (!drawContext) {
return nullptr;
}
SkRect dstRect = SkRect::MakeWH(SkIntToScalar(rtDesc.fWidth), SkIntToScalar(rtDesc.fHeight));
drawContext->fillRectToRect(GrClip::WideOpen(), paint, SkMatrix::I(), dstRect, localRect);
return copy.detach();
}
GrTextureAdjuster::GrTextureAdjuster(GrTexture* original, const SkIRect& contentArea)
: fOriginal(original) {
if (contentArea.fLeft > 0 || contentArea.fTop > 0 ||
contentArea.fRight < original->width() || contentArea.fBottom < original->height()) {
fContentArea.set(contentArea);
}
}
GrTexture* GrTextureAdjuster::refTextureSafeForParams(const GrTextureParams& params,
SkIPoint* outOffset) {
GrTexture* texture = this->originalTexture();
GrContext* context = texture->getContext();
CopyParams copyParams;
const SkIRect* contentArea = this->contentArea();
if (contentArea && GrTextureParams::kMipMap_FilterMode == params.filterMode()) {
// If we generate a MIP chain for texture it will read pixel values from outside the content
// area.
copyParams.fWidth = contentArea->width();
copyParams.fHeight = contentArea->height();
copyParams.fFilter = GrTextureParams::kBilerp_FilterMode;
} else if (!context->getGpu()->makeCopyForTextureParams(texture->width(), texture->height(),
params, ©Params)) {
if (outOffset) {
if (contentArea) {
outOffset->set(contentArea->fLeft, contentArea->fRight);
} else {
outOffset->set(0, 0);
}
}
return SkRef(texture);
}
GrUniqueKey key;
this->makeCopyKey(copyParams, &key);
if (key.isValid()) {
GrTexture* result = context->textureProvider()->findAndRefTextureByUniqueKey(key);
if (result) {
return result;
}
}
GrTexture* result = copy_on_gpu(texture, contentArea, copyParams);
if (result) {
if (key.isValid()) {
result->resourcePriv().setUniqueKey(key);
this->didCacheCopy(key);
}
if (outOffset) {
outOffset->set(0, 0);
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////
GrTexture* GrTextureMaker::refTextureForParams(GrContext* ctx, const GrTextureParams& params) {
CopyParams copyParams;
if (!ctx->getGpu()->makeCopyForTextureParams(this->width(), this->height(), params,
©Params)) {
return this->refOriginalTexture(ctx);
}
GrUniqueKey copyKey;
this->makeCopyKey(copyParams, ©Key);
if (copyKey.isValid()) {
GrTexture* result = ctx->textureProvider()->findAndRefTextureByUniqueKey(copyKey);
if (result) {
return result;
}
}
GrTexture* result = this->generateTextureForParams(ctx, copyParams);
if (!result) {
return nullptr;
}
if (copyKey.isValid()) {
ctx->textureProvider()->assignUniqueKeyToTexture(copyKey, result);
this->didCacheCopy(copyKey);
}
return result;
}
GrTexture* GrTextureMaker::generateTextureForParams(GrContext* ctx, const CopyParams& copyParams) {
SkAutoTUnref<GrTexture> original(this->refOriginalTexture(ctx));
if (!original) {
return nullptr;
}
return copy_on_gpu(original, nullptr, copyParams);
}
| 36.009524
| 100
| 0.609627
|
Perspex
|
579e193ddcadad859910cb1a513699ace70c2912
| 4,623
|
cpp
|
C++
|
Kamek/src/music.cpp
|
RedStoneMatt/SuperLuigiLandWii
|
8b98f3b16a1e5d99681ac382d5e603248a1c53db
|
[
"MIT"
] | 4
|
2021-01-18T18:14:18.000Z
|
2022-02-20T13:08:28.000Z
|
Kamek/src/music.cpp
|
RedStoneMatt/SuperLuigiLandWii
|
8b98f3b16a1e5d99681ac382d5e603248a1c53db
|
[
"MIT"
] | null | null | null |
Kamek/src/music.cpp
|
RedStoneMatt/SuperLuigiLandWii
|
8b98f3b16a1e5d99681ac382d5e603248a1c53db
|
[
"MIT"
] | null | null | null |
#include <game.h>
#include <sfx.h>
#include "music.h"
bool isTrailerMode;
struct HijackedStream {
//const char *original;
//const char *originalFast;
u32 stringOffset;
u32 stringOffsetFast;
u32 infoOffset;
u8 originalID;
int streamID;
};
struct Hijacker {
HijackedStream stream[2];
u8 currentStream;
u8 currentCustomTheme;
};
const char* SongNameList [] = {
"HEADLONG_HOLD",
"BOSS_TOWER",
"MENU",
"WAYSIDE_UW",
"CHALLENGE",
"WINDY_RUIN_UG",
"GOOMBA_GROTTO",
"CLIFFSIDE",
"BOSS_ROY",
"GOOMBA_GRO_UG",
"WINDY_RUINS1",
"LAVA_LAIR",
"SHFTNG_SWMPLN",
"ICE_FLOE_FERR",
"JAPAN",
"PUMPKIN",
"EERIE_EXCURS",
"BOSS_WENDY",
"BOWSER",
"BONUS",
"AMBUSH",
"BRIDGE_DRUMS",
"SNOW2",
"BOSS_MORTON",
"SUNNY_ASCENT",
"AUTUMN",
"WYSIDE_WALLOW",
"LWLGHT_LBRNTH",
"GHASTLY_GLADE",
"JUNGLE_SWING",
"BOSS_IGGY",
"BOSS_LARRY",
"ROCKSLIDE_RUN",
"FINAL_KAMEK",
"SINGALONG",
"FACTORY",
"BOSS_LUDWIG",
"CHNLNK_CHMBER",
"YOSHIHOUSE",
"PRLOUS_PSSAGE",
"BOMB_BASEMENT",
"WINDY_RUINS2",
"BOSS_LEMMY",
"MINIGAME",
"BONUS_AREA",
"CHALLENGE",
"TERMINA_TOWER",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"BOSS_CASTLE",
"BOSS_AIRSHIP",
NULL
};
// Offsets are from the start of the INFO block, not the start of the brsar.
// INFO begins at 0x212C0, so that has to be subtracted from absolute offsets
// within the brsar.
#define _I(offs) ((offs)-0x212C0)
Hijacker Hijackers[2] = {
{
{
{/*"athletic_lr.n.32.brstm", "athletic_fast_lr.n.32.brstm",*/ _I(0x4A8F8), _I(0x4A938), _I(0x476C4), 4, STRM_BGM_ATHLETIC},
{/*"BGM_SIRO.32.brstm", "BGM_SIRO_fast.32.brstm",*/ _I(0x4B2E8), _I(0x4B320), _I(0x48164), 10, STRM_BGM_SHIRO}
},
0, 0
},
{
{
{/*"STRM_BGM_CHIJOU.brstm", "STRM_BGM_CHIJOU_FAST.brstm",*/ _I(0x4A83C), _I(0x4A8B4), 0, 1, STRM_BGM_CHIJOU},
{/*"STRM_BGM_CHIKA.brstm", "STRM_BGM_CHIKA_FAST.brstm",*/ _I(0x4A878), _I(0x4A780), 0, 2, STRM_BGM_CHIKA},
},
0, 0
}
};
extern void *SoundRelatedClass;
inline char *BrsarInfoOffset(u32 offset) {
return (char*)(*(u32*)(((u32)SoundRelatedClass) + 0x5CC)) + offset;
}
void FixFilesize(u32 streamNameOffset);
u8 hijackMusicWithSongName(const char *songName, int themeID, bool hasFast, int channelCount, int trackCount, int *wantRealStreamID) {
Hijacker *hj = &Hijackers[channelCount==4?1:0];
if(isTrailerMode) {
songName = "NOMUSICFORU";
}
// do we already have this theme in this slot?
// if so, don't switch streams
// if we do, NSMBW will think it's a different song, and restart it ...
// but if it's just an area transition where both areas are using the same
// song, we don't want that
if ((themeID >= 0) && hj->currentCustomTheme == themeID)
return hj->stream[hj->currentStream].originalID;
// which one do we use this time...?
int toUse = (hj->currentStream + 1) & 1;
hj->currentStream = toUse;
hj->currentCustomTheme = themeID;
// write the stream's info
HijackedStream *stream = &hj->stream[hj->currentStream];
if (stream->infoOffset) {
u16 *thing = (u16*)(BrsarInfoOffset(stream->infoOffset) + 4);
OSReport("Modifying stream info, at offset %x which is at pointer %x\n", stream->infoOffset, thing);
OSReport("It currently has: channel count %d, track bitfield 0x%x\n", thing[0], thing[1]);
thing[0] = channelCount;
thing[1] = (1 << trackCount) - 1;
OSReport("It has been set to: channel count %d, track bitfield 0x%x\n", thing[0], thing[1]);
}
sprintf(BrsarInfoOffset(stream->stringOffset), "new/%s.er", songName);
sprintf(BrsarInfoOffset(stream->stringOffsetFast), hasFast?"new/%s_F.er":"new/%s.er", songName);
// update filesizes
FixFilesize(stream->stringOffset);
FixFilesize(stream->stringOffsetFast);
// done!
if (wantRealStreamID)
*wantRealStreamID = stream->streamID;
return stream->originalID;
}
//oh for fuck's sake
#include "fileload.h"
void FixFilesize(u32 streamNameOffset) {
char *streamName = BrsarInfoOffset(streamNameOffset);
char nameWithSound[80];
snprintf(nameWithSound, 79, "/Sound/%s", streamName);
s32 entryNum;
DVDHandle info;
if ((entryNum = DVDConvertPathToEntrynum(nameWithSound)) >= 0) {
if (DVDFastOpen(entryNum, &info)) {
u32 *lengthPtr = (u32*)(streamName - 0x1C);
*lengthPtr = info.length;
}
} else
OSReport("What, I couldn't find \"%s\" :(\n", nameWithSound);
}
extern "C" u8 after_course_getMusicForZone(u8 realThemeID) {
if (realThemeID < 100)
return realThemeID;
bool usesDrums = (realThemeID >= 200);
// OSReport("isTrailerMode = %d\n", isTrailerMode);
return hijackMusicWithSongName(SongNameList[realThemeID-100], realThemeID, true, usesDrums?4:2, usesDrums?2:1, 0);
}
| 23
| 134
| 0.687432
|
RedStoneMatt
|
57a458bbb8d961b2c92c33c797a509351c88222e
| 865
|
hpp
|
C++
|
src/Net.hpp
|
edelkas/pfdb
|
f492767cb1fce18e737cdd6beeca23293a6acab4
|
[
"MIT"
] | null | null | null |
src/Net.hpp
|
edelkas/pfdb
|
f492767cb1fce18e737cdd6beeca23293a6acab4
|
[
"MIT"
] | null | null | null |
src/Net.hpp
|
edelkas/pfdb
|
f492767cb1fce18e737cdd6beeca23293a6acab4
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Downloader.hpp"
#include "Parser.hpp"
enum Website { NONE, IMDB, FILMAFFINITY };
enum UrlType { MOVIE, SEARCH };
/**
* Class for downloading and parsing movies and movies searches.
*
* Each supported website is implemented as a namespace. It is extensible.
* This class is a singleton, only one instance can be created.
*/
class Net
{
private:
Downloader downloader;
Parser parser;
public:
Net();
~Net();
static Website Host(const std::string& url);
/**
* Download HTML file using libCURL and parse it using MyHTML
*/
void Parse(const std::string& url);
void Parse(Website web, const std::string& id);
/**
* Singleton: Remove possibility of duplicating object.
*/
Net(const Net&) = delete; // Remove copy constructor
Net& operator=(const Net&) = delete; // Remove asignment operator
};
| 22.763158
| 74
| 0.684393
|
edelkas
|
57a56c63473220c2da0c8dbe4d200fbadf9efd18
| 3,049
|
cpp
|
C++
|
SoundManager.cpp
|
thuxtable/thomas-was-late-tutorial
|
e9d333a62a903d5d951917b35b84268ceb1831df
|
[
"MIT"
] | null | null | null |
SoundManager.cpp
|
thuxtable/thomas-was-late-tutorial
|
e9d333a62a903d5d951917b35b84268ceb1831df
|
[
"MIT"
] | null | null | null |
SoundManager.cpp
|
thuxtable/thomas-was-late-tutorial
|
e9d333a62a903d5d951917b35b84268ceb1831df
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "SoundManager.h"
#include <SFML/Audio.hpp>
using namespace sf;
SoundManager::SoundManager() {
//Load the sound in the buffers
m_FireBuffer.loadFromFile("sound/fire1.wav");
m_FallInFireBuffer.loadFromFile("sound/fallinfire.wav");
m_FallInWaterBuffer.loadFromFile("sound/fallinwater.wav");
m_JumpBuffer.loadFromFile("sound/jump.wav");
m_ReachGoalBuffer.loadFromFile("sound/reachgoal.wav");
//Associate the sounds with the buffers
m_Fire1Sound.setBuffer(m_FireBuffer);
m_Fire2Sound.setBuffer(m_FireBuffer);
m_Fire3Sound.setBuffer(m_FireBuffer);
m_FallInFireSound.setBuffer(m_FallInFireBuffer);
m_FallInWaterSound.setBuffer(m_FallInWaterBuffer);
m_JumpSound.setBuffer(m_JumpBuffer);
m_ReachGoalSound.setBuffer(m_ReachGoalBuffer);
//When the player is 150 pixels away, the sound is full volume
float minDistance = 150;
//The sound reduces steadily as the player moves further away
float attentuation = 15;
//Set all attentuation levels
m_Fire1Sound.setAttenuation(attentuation);
m_Fire2Sound.setAttenuation(attentuation);
m_Fire3Sound.setAttenuation(attentuation);
//Set all min distance levels
m_Fire1Sound.setMinDistance(minDistance);
m_Fire2Sound.setMinDistance(minDistance);
m_Fire3Sound.setMinDistance(minDistance);
//Loop fire sounds when played
m_Fire1Sound.setLoop(true);
m_Fire2Sound.setLoop(true);
m_Fire3Sound.setLoop(true);
}
void SoundManager::playFire(Vector2f emitterLocation, Vector2f listenerLocation) {
//Where is Thomas, the listener
Listener::setPosition(listenerLocation.x, listenerLocation.y, 0.0f);
switch (m_NextSound) {
case 1:
//Locate/move the source of the sound
m_Fire1Sound.setPosition(emitterLocation.x, emitterLocation.y, 0.0f);
if (m_Fire1Sound.getStatus() == Sound::Status::Stopped) {
//Play the sound, if it's not already playing
m_Fire1Sound.play();
}
break;
case 2:
m_Fire2Sound.setPosition(emitterLocation.x, emitterLocation.y, 0.0f);
if (m_Fire1Sound.getStatus() == Sound::Status::Stopped) {
//Play the sound, if it's not already playing
m_Fire2Sound.play();
}
break;
case 3:
m_Fire3Sound.setPosition(emitterLocation.x, emitterLocation.y, 0.0f);
if (m_Fire1Sound.getStatus() == Sound::Status::Stopped) {
//Play the sound, if it's not already playing
m_Fire3Sound.play();
}
break;
} //End switch
//Increment to the next fire sound
m_NextSound++;
//Go back to 1 when third has started
if (m_NextSound > 3) {
m_NextSound = 1;
}
}
void SoundManager::playFallInFire(){
m_FallInFireSound.setRelativeToListener(true);
m_FallInFireSound.play();
}
void SoundManager::playFallInWater(){
m_FallInWaterSound.setRelativeToListener(true);
m_FallInWaterSound.play();
}
void SoundManager::playJump(){
m_JumpSound.setRelativeToListener(true);
m_JumpSound.play();
}
void SoundManager::playReachGoal() {
m_ReachGoalSound.setRelativeToListener(true);
m_ReachGoalSound.play();
}
| 27.718182
| 83
| 0.740899
|
thuxtable
|
57a5b85097776bebb42f508452cdfc7592037f12
| 541
|
cpp
|
C++
|
Codeforces/118A String Task.cpp
|
sreejonK19/online-judge-solutions
|
da65d635cc488c8f305e48b49727ad62649f5671
|
[
"MIT"
] | null | null | null |
Codeforces/118A String Task.cpp
|
sreejonK19/online-judge-solutions
|
da65d635cc488c8f305e48b49727ad62649f5671
|
[
"MIT"
] | null | null | null |
Codeforces/118A String Task.cpp
|
sreejonK19/online-judge-solutions
|
da65d635cc488c8f305e48b49727ad62649f5671
|
[
"MIT"
] | 2
|
2018-11-06T19:37:56.000Z
|
2018-11-09T19:05:46.000Z
|
#include <bits/stdc++.h>
using namespace std;
char str[102];
int main( int argc, char ** argv ) {
scanf( "%s", str );
int len = strlen( str );
for( int i = 0 ; i < len ; i++ ) {
if( str[i] >= 'A' && str[i] <='Z' ) {
str[i] = 'a' + (str[i] - 'A');
}
}
for( int i = 0 ; i < len ; i++ ) {
if( str[i] != 'a' && str[i] != 'o' && str[i] != 'y' && str[i] != 'e' && str[i] != 'u' && str[i] != 'i' ) {
printf( ".%c", str[i] );
}
}
printf( "\n" );
return 0;
}
| 23.521739
| 114
| 0.358595
|
sreejonK19
|
57ac3fb47e1ebac7f43a3a91551508cf2387b2b8
| 8,114
|
hpp
|
C++
|
adaptors/fftw/mpi.hpp
|
correaa/b-multi
|
1e961f877662aa7a26933834f9064d2ec8b00b4a
|
[
"Intel"
] | null | null | null |
adaptors/fftw/mpi.hpp
|
correaa/b-multi
|
1e961f877662aa7a26933834f9064d2ec8b00b4a
|
[
"Intel"
] | 11
|
2020-05-09T20:57:21.000Z
|
2020-06-10T00:00:17.000Z
|
adaptors/fftw/mpi.hpp
|
correaa/b-multi
|
1e961f877662aa7a26933834f9064d2ec8b00b4a
|
[
"Intel"
] | null | null | null |
#if COMPILATION// -*-indent-tabs-mode:t;c-basic-offset:4;tab-width:4;-*-
ln -sf $0 $0.cpp;mpicxx -g -I$HOME/prj/alf $0.cpp -o $0x -lfftw3 -lfftw3_mpi&&time mpirun -n 4 $0x&&rm $0x $0.cpp;exit
#ln -sf $0 $0.cpp;mpicxx -g -I$HOME/prj/alf $0.cpp -o $0x -lfftw3 -lfftw3_mpi&&time mpirun -n 4 valgrind --leak-check=full --track-origins=yes --show-leak-kinds=all --suppressions=$HOME/prj/alf/boost/mpi3/test/communicator_main.cpp.openmpi.supp --error-exitcode=1 $0x&&rm $0x $0.cpp;exit
#endif
// ยฉ Alfredo A. Correa 2020
// apt-get install libfftw3-mpi-dev
// compile with: mpicc simple_mpi_example.c -Wl,-rpath=/usr/local/lib -lfftw3_mpi -lfftw3 -o simple_mpi_example */
#include "../../array.hpp"
#include "../../config/NODISCARD.hpp"
#include<boost/mpi3/communicator.hpp>
#include<boost/mpi3/environment.hpp>
#include "../fftw.hpp"
#include <fftw3-mpi.h>
namespace boost{
namespace multi{
namespace fftw{
template<typename T>
struct allocator : std::allocator<T>{
template <typename U> struct rebind{using other = fftw::allocator<U>;};
NODISCARD("to avoid memory leak")
T* allocate(std::size_t n){ return static_cast<T*>(fftw_malloc(sizeof(T)*n));}
void deallocate(T* data, std::size_t){fftw_free(data);}
};
namespace mpi{
struct environment{
environment(){fftw_mpi_init();}
~environment(){fftw_mpi_cleanup();}
};
template<class T, multi::dimensionality_type D, class Alloc = fftw::allocator<T>>
struct array;
namespace bmpi3 = boost::mpi3;
template<class T, class Alloc>
struct array<T, multi::dimensionality_type{2}, Alloc>{
using element_type = T;
mutable bmpi3::communicator comm_;
Alloc alloc_;
typename std::allocator_traits<Alloc>::size_type local_count_;
array_ptr<T, 2, typename std::allocator_traits<Alloc>::pointer> local_ptr_;
ptrdiff_t n0_;
static std::pair<typename std::allocator_traits<Alloc>::size_type, multi::extensions_type_<2>>
local_2d(multi::extensions_type_<2> ext, boost::mpi3::communicator const& comm){
ptrdiff_t local_n0, local_0_start;
auto count = fftw_mpi_local_size_2d(std::get<0>(ext).size(), std::get<1>(ext).size(), comm.get(), &local_n0, &local_0_start);
assert( count >= local_n0*std::get<1>(ext).size() );
return {count, {{local_0_start, local_0_start + local_n0}, std::get<1>(ext)}};
}
static auto local_count_2d(multi::extensions_type_<2> ext, boost::mpi3::communicator const& comm){
return local_2d(ext, comm).first;
}
static auto local_extension_2d(multi::extensions_type_<2> ext, boost::mpi3::communicator const& comm){
return local_2d(ext, comm).second;
}
array(multi::extensions_type_<2> ext, bmpi3::communicator comm = mpi3::environment::self(), Alloc alloc = {}) :
comm_{std::move(comm)},
alloc_{alloc},
local_count_{local_count_2d(ext, comm_)},
local_ptr_ {alloc_.allocate(local_count_), local_extension_2d(ext, comm_)},
n0_{multi::layout_t<2>(ext).size()}
{
if(not std::is_trivially_default_constructible<element_type>{})
adl_alloc_uninitialized_default_construct_n(alloc_, local_ptr_->base(), local_ptr_->num_elements());
}
bmpi3::communicator& comm() const&{return comm_;}
array(array const& other) :
comm_ {other.comm_},
alloc_ {other.alloc_},
local_count_{other.local_count_},
local_ptr_ {alloc_.allocate(local_count_), local_extension_2d(other.extensions(), comm_)},
n0_{multi::layout_t<2>(other.extensions()).size()}
{
local_cutout() = other.local_cutout();
}
array(array&& other) :
comm_ {std::move(other.comm_)},
alloc_ {std::move(other.alloc_)},
local_count_{std::exchange(other.local_count_, 0)},
local_ptr_ {std::exchange(other.local_ptr_, nullptr)},
n0_{multi::layout_t<2>(other.extensions()).size()}
{}
explicit array(multi::array<T, 2> const& other, bmpi3::communicator comm = mpi3::environment::self(), Alloc alloc = {}) :
array(other.extensions(), comm, alloc)
{
local_cutout() = other.stenciled(std::get<0>(local_cutout().extensions()), std::get<1>(local_cutout().extensions()));
}
bool empty() const{return extensions().num_elements();}
array_ref <T, 2> local_cutout() &{return *local_ptr_;}
array_cref<T, 2> local_cutout() const&{return *local_ptr_;}
ptrdiff_t local_count() const&{return local_count_;}
multi::extensions_type_<2> extensions() const&{return {n0_, std::get<1>(local_cutout().extensions())};}
ptrdiff_t num_elements() const&{return multi::layout_t<2>(extensions()).num_elements();}
operator multi::array<T, 2>() const&{ static_assert( std::is_trivially_copy_assignable<T>{}, "!" );
multi::array<T, 2> ret(extensions(), alloc_);
comm_.all_gatherv_n(local_cutout().data_elements(), local_cutout().num_elements(), ret.data_elements());
return ret;
}
array& operator=(multi::array<T, 2> const& other) &{
if(other.extensions() == extensions()) local_cutout() = other.stenciled(std::get<0>(local_cutout().extensions()), std::get<1>(local_cutout().extensions()));
else{
array tmp{other};
std::swap(*this, tmp);
}
return *this;
}
bool operator==(multi::array<T, 2> const& other) const&{
if(other.extensions() != extensions()) return false;
return comm_&=(local_cutout() == other.stenciled(std::get<0>(local_cutout().extensions()), std::get<1>(local_cutout().extensions())));
}
friend bool operator==(multi::array<T, 2> const& other, array const& self){
return self.operator==(other);
}
bool operator==(array<T, 2> const& other) const&{assert(comm_==other.comm_);
return comm_&=(local_cutout() == other.local_cutout());
}
array& operator=(array const& other)&{
if(other.extensions() == this->extensions() and other.comm_ == other.comm_)
local_cutout() = other.local_cutout();
else assert(0);
return *this;
}
~array() noexcept{alloc_.deallocate(local_cutout().data_elements(), local_count_);}
};
array<std::complex<double>, 2>& dft(array<std::complex<double>, 2> const& A, array<std::complex<double>, 2>& B, fftw::sign s){
assert( A.extensions() == B.extensions() );
assert( A.comm() == B.comm() );
fftw_plan p = fftw_mpi_plan_dft_2d(
std::get<0>(A.extensions()).size(), std::get<1>(A.extensions()).size(),
(fftw_complex *)A.local_cutout().data_elements(), (fftw_complex *)B.local_cutout().data_elements(),
A.comm().get(),
s, FFTW_ESTIMATE
);
fftw_execute(p);
fftw_destroy_plan(p);
return B;
}
array<std::complex<double>, 2>& dft_forward(array<std::complex<double>, 2> const& A, array<std::complex<double>, 2>& B){
return dft(A, B, fftw::forward);
}
array<std::complex<double>, 2> dft_forward(array<std::complex<double>,2> const& A){
array<std::complex<double>, 2> ret(A.extensions()); dft_forward(A, ret); return ret;
}
}}}}
#if not __INCLUDE_LEVEL__
#include<boost/mpi3/main.hpp>
#include<boost/mpi3/environment.hpp>
#include<boost/mpi3/ostream.hpp>
#include "../fftw.hpp"
namespace mpi3 = boost::mpi3;
namespace multi = boost::multi;
int mpi3::main(int, char*[], mpi3::communicator world){
multi::fftw::mpi::environment fenv;
multi::fftw::mpi::array<std::complex<double>, 2> A({41, 321}, world);
mpi3::ostream os{world};
os<< "global sizes" << std::get<0>(A.extensions()) <<'x'<< std::get<1>(A.extensions()) <<' '<< A.num_elements() <<std::endl;
os<< A.local_cutout().extension() <<'x'<< std::get<1>(A.local_cutout().extensions()) <<"\t#="<< A.local_cutout().num_elements() <<" allocated "<< A.local_count() <<std::endl;
{
auto x = A.local_cutout().extensions();
for(auto i : std::get<0>(x))
for(auto j : std::get<1>(x))
A.local_cutout()[i][j] = std::complex<double>(i + j, i + 2*j + 1)/std::abs(std::complex<double>(i + j, i + 2*j + 1));
}
multi::array<std::complex<double>, 2> A2 = A;
assert( A2 == A );
using multi::fftw::dft_forward;
dft_forward(A , A );
dft_forward(A2, A2);
{
auto x = A.local_cutout().extensions();
for(auto i : std::get<0>(x))
for(auto j : std::get<1>(x))
if(not( std::abs(A.local_cutout()[i][j] - A2[i][j]) < 1e-12 )){
std::cout << A.local_cutout()[i][j] - A2[i][j] <<' '<< std::abs(A.local_cutout()[i][j] - A2[i][j]) << std::endl;
}
}
return 0;
}
#endif
| 39.009615
| 287
| 0.678087
|
correaa
|
57adea372917bbbcf7eae81f58b06a7d8bd1f7ac
| 1,038
|
hpp
|
C++
|
engine/Engine.hpp
|
InfiniBrains/mobagen
|
262fa833195cd1b32f82ee4d825b0a39e7ebe4cb
|
[
"WTFPL"
] | 32
|
2017-12-29T16:44:35.000Z
|
2021-08-06T23:10:28.000Z
|
engine/Engine.hpp
|
InfiniBrains/mobagen
|
262fa833195cd1b32f82ee4d825b0a39e7ebe4cb
|
[
"WTFPL"
] | 66
|
2017-12-29T16:37:35.000Z
|
2019-04-19T23:57:20.000Z
|
engine/Engine.hpp
|
InfiniBrains/mobagen
|
262fa833195cd1b32f82ee4d825b0a39e7ebe4cb
|
[
"WTFPL"
] | 7
|
2017-12-29T16:49:53.000Z
|
2021-08-06T23:10:35.000Z
|
#pragma once
#include <chrono>
#include "GLManager.hpp"
#include "Window.hpp"
#include "GLEWManager.hpp"
#include "PhysicsManager.hpp"
#include "Game.hpp"
#include "Input.hpp"
namespace mobagen {
class Engine {
public:
Engine(Game *game, char *windowTitle, glm::vec2 windowSize);
~Engine(void);
#ifdef EMSCRIPTEN
static void loop(void);
#endif
void tick(void);
void start(void);
Window *getWindow(void) const;
GLManager *getGLManager(void) const;
PhysicsManager *getPhysicsManager(void) const;
std::chrono::microseconds getDeltaTime(void) const;
private:
std::unique_ptr<Window> m_window;
std::unique_ptr<GLEWManager> m_glewManager;
std::unique_ptr<GLManager> m_glManager;
std::unique_ptr<PhysicsManager> m_physicsManager;
std::chrono::high_resolution_clock::time_point m_time, m_lastTime;
std::chrono::microseconds m_deltaTime;
//std::chrono::high_resolution_clock::time_point m_physicsTimeSimulated;
Game *game;
bool quit, m_fireRay;
};
}
| 19.961538
| 76
| 0.714836
|
InfiniBrains
|
57aeafc36db70ae263debb875f1aab33a499d4d9
| 7,683
|
cpp
|
C++
|
src/ppu.cpp
|
ceanrim/CarmiNES
|
f0f20b95dba916893b4c4eb41f4b15e4fd075df1
|
[
"BSD-2-Clause"
] | 2
|
2018-02-15T07:40:35.000Z
|
2018-09-22T21:17:33.000Z
|
src/ppu.cpp
|
ceanrim/CarmiNES
|
f0f20b95dba916893b4c4eb41f4b15e4fd075df1
|
[
"BSD-2-Clause"
] | null | null | null |
src/ppu.cpp
|
ceanrim/CarmiNES
|
f0f20b95dba916893b4c4eb41f4b15e4fd075df1
|
[
"BSD-2-Clause"
] | null | null | null |
/* ========================================================================
File:
Date:
Revision:
Creator: Carmine Foggia
======================================================================== */
/*TODO:
*Simulate PPU registers completely and properly
*Emulate read/write buffering
*Emulate sprites
*Emulate scanline timing
*PAL
*/
#include <windows.h>
#include "main.h"
#include "nesclass.h"
#include "ppu.h"
PPUClass::PPUClass()
:LastEmulatedCycle(0),
Scanline(261),
Dot(0),
VRAMAddr(0),
PPUADDRWriteTick(0)
{
memset(OAM, 0, 256);
Register2002 = 0;
}
void PPUClass::Init(unsigned short Mapper)
{
switch(Mapper)
{
case 0:
{
CHRROM = NES.ROMFile + 16 + NES.RAM.PRGROMSize;
PatternTables[0] = CHRROM;
PatternTables[1] = CHRROM + 4096;
if(Mirroring & 8) //Four screen VRAM/No mirroring
{
Nametables[0] = Nametable0;
Nametables[1] = Nametable1;
Nametables[2] = Nametable2;
Nametables[3] = Nametable3;
}
else if(Mirroring == 0) //Horizontal mirroring
{
Nametables[0] = Nametables[1] = Nametable0;
Nametables[2] = Nametables[3] = Nametable2;
}
else if(Mirroring == 1) //Vertical mirroring
{
Nametables[0] = Nametables[2] = Nametable0;
Nametables[1] = Nametables[3] = Nametable1;
}
break;
}
}
memset(Nametable0, 0, 1024);
memset(Nametable1, 0, 1024);
memset(Nametable2, 0, 1024);
memset(Nametable3, 0, 1024);
//memset(BackgroundPalettes, 0, 16);
//FOR DEBUG:
BackgroundPalettes[0][0] = 0x0F;
BackgroundPalettes[0][1] = 0x16;
BackgroundPalettes[0][2] = 0x30;
BackgroundPalettes[0][3] = 0x37;
memset(BackgroundPalettes[1], 0, 12);
memset(SpritePalettes, 0, 16);
}
//TODO: The PPU processes pixels 8 by 8, implement this
void PPUClass::Run(unsigned long long CycleToGet) //Only NTSC for now
{
bool RollingOver = false;
if(LastEmulatedCycle > CycleToGet) //Let's avoid infinite loops because of
//cycle rollover
{
RollingOver = true;
CycleToGet += NTSC_CYCLE_COUNT;
}
/*if((LastEmulatedCycle < NTSC_VBLANK_CYCLE) && (CycleToGet >= NTSC_VBLANK_CYCLE))
{
Register2002 |= 0b10000000;
NES.NMI = true;
}
if((LastEmulatedCycle < NTSC_VBLANK_UNSET_CYCLE) &&
(CycleToGet >= NTSC_VBLANK_UNSET_CYCLE))
{
Register2002 &= 0b01111111;
}*/
while(LastEmulatedCycle < CycleToGet)
{
LastEmulatedCycle += 5;
if(Scanline == 261) //Pre-render scanline
{
if(Dot == 0)
{
Register2002 &= 0b01111111;
Dot++;
}
else if(Dot < (338 + (NES.FrameCount & 1)?0:1))
{
Dot++;
}
else
{
Dot = -1;
Scanline = 0;
}
}
else if(Scanline <= 239)
{
if(Dot == -1)
{
Dot++;
}
else if(Dot <= 255)
{
unsigned char BackgroundTile =
Nametables[NametableBase][((Scanline >> 3) << 5) +
Dot >> 3];
unsigned char Palette =
Nametables[NametableBase]
[960 + ((Scanline >> 5) << 3) + (Dot >> 5)];
if(Scanline & 16)
{
if(Dot & 16)
{
Palette >>= 6;
}
else
{
Palette >>= 4;
Palette &= 3;
}
}
else
{
if(Dot & 16)
{
Palette >>= 2;
Palette &= 3;
}
else
{
Palette &= 3;
}
}
unsigned char Color = 0;
Color =
(PatternTables[PatternTableBase]
[(BackgroundTile << 4) + (Scanline & 7)] &
(1 << (7 - (Dot & 7)))) >> (7 - (Dot & 7));
Color |=
((PatternTables[PatternTableBase]
[(BackgroundTile << 4) + (Scanline & 7) + 8] &
(1 << (7 - (Dot & 7)))) >> (7 - (Dot & 7)) << 1);
NES.RenderBuffer.Memory[(Scanline << 8) + Dot] =
NES.Debugger.ColorRGBTable
[NES.PPU.BackgroundPalettes[Palette][Color]];
Dot++;
}
else if(Dot < 339)
{
Dot++;
}
else
{
Scanline++;
Dot = -1;
}
}
else if(Scanline == 240)
{
if(Dot < 339)
{
Dot++;
}
else
{
Scanline++;
Dot = -1;
}
}
else if(Scanline == 241)
{
if(Dot == 0)
{
Register2002 |= 0b10000000;
if(NES.NMIEnabled)
{
NES.NMI = true;
}
Dot++;
}
else if(Dot < 339)
{
Dot++;
}
else
{
Scanline++;
Dot = -1;
}
}
else if(Scanline < 261)
{
if(Dot < 339)
{
Dot++;
}
else
{
Scanline++;
Dot = -1;
}
}
}
if(RollingOver)
{
LastEmulatedCycle -= NTSC_CYCLE_COUNT;
}
}
void PPUClass::Write(unsigned char valueToWrite) //TODO: Buffering
{
if(VRAMAddr < 0x1FFF)
{
PatternTables[(VRAMAddr & 0x1000) >> 12][VRAMAddr & 0x0FFF] = valueToWrite;
}
else if((VRAMAddr >= 0x2000) && (VRAMAddr < 0x3F00))
{
Nametables[(VRAMAddr & 0x0C00) >> 14][VRAMAddr & 0x03FF] = valueToWrite;
}
else if(VRAMAddr >= 0x3F00)
{
if(VRAMAddr & 3)
{
if(VRAMAddr & 16) //Sprite palettes
{
SpritePalettes[(VRAMAddr & 12) >> 2][VRAMAddr & 3] = valueToWrite;
}
else
{
BackgroundPalettes[(VRAMAddr & 12) >> 2][VRAMAddr & 3] = valueToWrite;
}
}
else
{
BackgroundPalettes[0][0] = valueToWrite;
BackgroundPalettes[1][0] = valueToWrite;
BackgroundPalettes[2][0] = valueToWrite;
BackgroundPalettes[3][0] = valueToWrite;
SpritePalettes[0][0] = valueToWrite;
SpritePalettes[1][0] = valueToWrite;
SpritePalettes[2][0] = valueToWrite;
SpritePalettes[3][0] = valueToWrite;
}
}
else
{
char ErrorMessage[] = "Tried to write value $00 at $0000 in PPU.";
UchartoHex(valueToWrite, ErrorMessage + 22, false);
UshorttoHex(VRAMAddr, ErrorMessage + 29, false);
MessageBox(0, ErrorMessage, "Error", IDOK);
}
VRAMAddr += PPUADDRIncrement;
}
| 28.246324
| 86
| 0.411948
|
ceanrim
|
57aedb8e4e426e87a08dd158627d2962880dc56f
| 14,662
|
cpp
|
C++
|
Eudora71/EuShlExt/ShellHookImpl.cpp
|
dusong7/eudora-win
|
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
|
[
"BSD-3-Clause-Clear"
] | 10
|
2018-05-23T10:43:48.000Z
|
2021-12-02T17:59:48.000Z
|
Eudora71/EuShlExt/ShellHookImpl.cpp
|
ivanagui2/hermesmail-code
|
34387722d5364163c71b577fc508b567de56c5f6
|
[
"BSD-3-Clause-Clear"
] | 1
|
2019-03-19T03:56:36.000Z
|
2021-05-26T18:36:03.000Z
|
Eudora71/EuShlExt/ShellHookImpl.cpp
|
ivanagui2/hermesmail-code
|
34387722d5364163c71b577fc508b567de56c5f6
|
[
"BSD-3-Clause-Clear"
] | 11
|
2018-05-23T10:43:53.000Z
|
2021-12-27T15:42:58.000Z
|
#include "windows.h"
#include <stdio.h>
#include "ShellHookImpl.h"
#include "tchar.h"
#include "time.h"
#include "resource.h"
extern unsigned int g_cRefThisDll;
extern DWORD TlsIndex;
extern HANDLE g_hModule;
// The Shell Factory Class
CShellExtClassFactory::CShellExtClassFactory()
{
//DumpLogInformation("CShellExtClassFactory::CShellExtClassFactory()\n");
m_cRef = 0L;
g_cRefThisDll++;
}
CShellExtClassFactory::~CShellExtClassFactory()
{
g_cRefThisDll--;
}
STDMETHODIMP CShellExtClassFactory::QueryInterface(REFIID riid,
LPVOID FAR *ppv)
{
THREADINFO *pti;
THREADINFO ti;
pti = &ti;
pti = (THREADINFO *)TlsGetValue(TlsIndex);
DumpLogInformation("In ShellExtClassFactory::QueryInterface()");
*ppv = NULL;
if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory))
{
*ppv = (LPCLASSFACTORY)this;
AddRef();
return NOERROR;
}
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) CShellExtClassFactory::AddRef()
{
THREADINFO *pti;
THREADINFO ti;
pti = &ti;
pti = (THREADINFO *)TlsGetValue(TlsIndex);
return ++m_cRef;
}
STDMETHODIMP_(ULONG) CShellExtClassFactory::Release()
{
THREADINFO *pti;
THREADINFO ti;
pti = &ti;
pti = (THREADINFO *)TlsGetValue(TlsIndex);
if (--m_cRef)
return m_cRef;
delete this;
return 0L;
}
STDMETHODIMP CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter,
REFIID riid,
LPVOID *ppvObj)
{
THREADINFO *pti;
THREADINFO ti;
pti = &ti;
pti = (THREADINFO *)TlsGetValue(TlsIndex);
DumpLogInformation("In ShellExtClassFactory::CreateInstance()");
*ppvObj = NULL;
// Shell extensions typically don't support aggregation (inheritance)
if (pUnkOuter)
return CLASS_E_NOAGGREGATION;
LPCSHELLEXT pShellExt = NULL;
if (pShellExt == NULL)
{
try
{
//Create the CShellExt object
pShellExt = new CShellExt();
} catch (...)
{
// Something's gone wrong. Write it to the log.
DumpLogInformation("In ShellExtClassFactory::CreateInstance: Unable to create ShellExt Object");
pShellExt=NULL;
}
}
if (NULL == pShellExt)
return E_OUTOFMEMORY;
return pShellExt->QueryInterface(riid, ppvObj);
}
STDMETHODIMP CShellExtClassFactory::LockServer(BOOL fLock)
{
THREADINFO *pti;
THREADINFO ti;
pti = &ti;
pti = (THREADINFO *)TlsGetValue(TlsIndex);
//return NOERROR;
return S_OK;
}
CShellExt::CShellExt()
{
//DumpLogInformation("CShellExt::CShellExt()\n");
m_cRef = 0L;
m_pDataObj = NULL;
m_pLMRegData = NULL;
m_nPathCount = 0;
g_cRefThisDll++;
}
CShellExt::~CShellExt()
{
//DumpLogInformation("CShellExt::~CShellExt()\n");
if (m_pDataObj)
m_pDataObj->Release();
if (m_pLMRegData)
delete [] m_pLMRegData;
g_cRefThisDll--;
}
STDMETHODIMP CShellExt::QueryInterface(REFIID riid, LPVOID FAR *ppv)
{
THREADINFO *pti;
THREADINFO ti;
pti = &ti;
pti = (THREADINFO *)TlsGetValue(TlsIndex);
*ppv = NULL;
if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IPersistFile))
{
DumpLogInformation("In ShellExt::QueryInterface() --> IID_IPersistFile");
*ppv = (LPPERSISTFILE)this;
}
else if (IsEqualIID(riid, IID_IShellExecuteHook))
{
DumpLogInformation("In ShellExt::QueryInterface() --> IID_IShellExecuteHook");
*ppv = (IShellExecuteHook *)this;
LoadConfiguration();
}
if (*ppv)
{
AddRef();
return NOERROR;
}
DumpLogInformation("In ShellExt::QueryInterface() --> Unsupported Interface!");
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) CShellExt::AddRef()
{
THREADINFO *pti;
THREADINFO ti;
pti = &ti;
pti = (THREADINFO *)TlsGetValue(TlsIndex);
DumpLogInformation("In ShellExt::AddRef()");
return ++m_cRef;
}
STDMETHODIMP_(ULONG) CShellExt::Release()
{
DumpLogInformation("In ShellExt::Release()");
if (--m_cRef)
return m_cRef;
delete this;
return 0L;
}
INT_PTR CALLBACK WarnDlgProc(
HWND hwndDlg, // handle to dialog box
UINT uMsg, // message
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
if (uMsg == WM_INITDIALOG)
{
// Buffer used for loading the string from the string table
TCHAR szBuff[1024];
// This buffer will contain the final text so formed.
TCHAR szFinalTextBuff[1024 /* size of szBuff*/ + _MAX_PATH + _MAX_FNAME + _MAX_EXT + sizeof(TCHAR)];
HWND hWndControl = GetDlgItem(hwndDlg, IDC_ALERT_TEXT);
// Load the string fro the string table.
LoadString((HINSTANCE) g_hModule, IDS_WARN_STRING, szBuff, sizeof(szBuff));
sprintf(szFinalTextBuff,szBuff, lParam);
if (hWndControl)
SetWindowText(hWndControl, szFinalTextBuff);
}
else if (uMsg == WM_COMMAND)
{
if (HIWORD(wParam) == BN_CLICKED)
{
// Destroy the Dialog.
EndDialog(hwndDlg, LOWORD(wParam) );
}
}
return FALSE;
}
STDMETHODIMP CShellExt::Execute( LPSHELLEXECUTEINFO pei)
{
THREADINFO *pti;
THREADINFO ti;
pti = &ti;
pti = (THREADINFO *)TlsGetValue(TlsIndex);
TCHAR szData[1024] = {0};
TCHAR szValueName[1024] = {0};
DWORD dwDataBufSize=1024;
BOOL bAlreadyWarned = FALSE;
DWORD dwKeyDataType = 0;
HKEY hKey = NULL;
DWORD dwValue = 0;
TCHAR szShortPathName1[_MAX_PATH + _MAX_FNAME + _MAX_EXT + SIZEOF_NULL_TERMINATOR] = {0};
TCHAR szShortPathName2[_MAX_PATH + _MAX_FNAME + _MAX_EXT + SIZEOF_NULL_TERMINATOR] = {0};
static int sBufLength = _MAX_PATH + _MAX_FNAME + _MAX_EXT;
try
{
for (int i = 0; i < m_nPathCount; i++)
{
bAlreadyWarned = FALSE;
// Convert to Short Path Name. Also if for some reason the entry in registry has an empty path, then make sure we skip it.
// Any path that is registered as a path to be "protected" by Shell Extension CANNOT BE EMPTY
if ( GetShortPathName((LPTSTR)pei->lpFile, szShortPathName1, sBufLength) &&
GetShortPathName(m_pLMRegData[i].szPath, szShortPathName2, sBufLength) &&
(_tcslen(szShortPathName2) > 0) )
{
if( (m_pLMRegData) && _tcsstr( _tcslwr(szShortPathName1),_tcslwr(szShortPathName2) ) )
{
if (IsExecutable(pei->lpFile,i+1))
{
// Check if already warned by Application that is launching (e.g Eudora). If so, then do not warn again
// It's the application's (the one that is launching/executing this file) duty to set the value of AlreadyWarned'N' to the
// appropriate value.
if ( RegOpenKeyEx(HKEY_CURRENT_USER, LM_REG_APP_KEY,0, KEY_READ | KEY_WRITE, &hKey) == ERROR_SUCCESS)
{
sprintf(szValueName,LM_REG_ALREADYWARNED_KEY,i+1);
if (RegQueryValueEx(hKey, szValueName, NULL, &dwKeyDataType, (LPBYTE)szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS)
{
bAlreadyWarned = *((DWORD*)szData);
//Reset the "AlreadyWarned#n"
sprintf(szValueName,LM_REG_ALREADYWARNED_KEY,i+1);
dwValue = 0;
RegSetValueEx(hKey, szValueName, 0, REG_DWORD, (const PBYTE) &dwValue, sizeof(DWORD));
}
RegCloseKey(hKey);
}
if (!bAlreadyWarned)
{
if ( (pei) && ( (long) pei->hInstApp < 32) )
pei->hInstApp = (HINSTANCE) 32; // This makes sure that Shell does not generate any error message box.
if (IDCANCEL == ::DialogBoxParam( (HINSTANCE) g_hModule, MAKEINTRESOURCE(IDD_YES_NO), NULL, (DLGPROC ) &WarnDlgProc, LPARAM(pei->lpFile)))
return S_OK; // Let Shell know that we handled it.
else
return S_FALSE; // Let Shell Handle it. We are done.
}
}
}
} else if (_tcslen(szShortPathName2) <= 0)
DumpLogInformation("The Path, Path#%d is empty",i + 1);
}
}
catch(...)
{
// Something's gone wrong here ..write to the log.
DumpLogInformation("Exception when trying to determine if Executable, Path : %s",(LPTSTR)pei->lpFile);
}
return S_FALSE;
}
STDMETHODIMP_(VOID) CShellExt::LoadConfiguration()
{
THREADINFO *pti;
THREADINFO ti;
pti = &ti;
pti = (THREADINFO *)TlsGetValue(TlsIndex);
// This is the function that loads the configuration from the registry
TCHAR szData[1024] = {0};
TCHAR szValueName[1024] = {0};
DWORD dwDataBufSize=1024;
DWORD dwKeyDataType = 0;
HKEY hKey = NULL;
// All the entries are under HKCU\Qualcomm\Eudora\LauchManager
if ( RegOpenKeyEx(HKEY_CURRENT_USER, LM_REG_APP_KEY,0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
if (RegQueryValueEx(hKey, LM_REG_PATHCOUNT_KEY, NULL, &dwKeyDataType,(LPBYTE) szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS)
{
if (dwKeyDataType == REG_DWORD)
{
m_nPathCount = *((DWORD*)szData);
DumpLogInformation("Loading Configuration Info : PathCount %d",m_nPathCount);
}
else // Write to the log that somehow the value is corrupted
{
DumpLogInformation("Error Loading Configuration Info : PathCount %d ...resetting to zero",*((DWORD*)szData));
m_nPathCount = 0;
}
// Also write to the log if the Path Count is negative
if (m_nPathCount < 0)
{
DumpLogInformation("Error PathCount value is negative : %d ...resetting to zero",*((DWORD*)szData));
m_nPathCount = 0;
}
// Delete the memory allocated (if any)
if(m_pLMRegData)
delete [] m_pLMRegData;
// Allocate memory here so that we could fill the data.
m_pLMRegData = new LM_REG_DATA[m_nPathCount];
for (int i = 0; i < m_nPathCount; i++)
{
// Allocate memory
sprintf(szValueName,LM_REG_PATH_KEY,i+1);
if (RegQueryValueEx(hKey, szValueName, NULL, &dwKeyDataType, (LPBYTE)szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS)
{
_tcsncpy(m_pLMRegData[i].szPath,(LPCTSTR)szData,_MAX_PATH > 1024 ? _MAX_PATH : 1024);
}
}
}
RegCloseKey(hKey);
}
return;
}
// This function determines if the FileName so passed is one amongst the malicious file-types that could possibly contain
// viruses, worms etc when opened/executed. The list which specifies the malicious extensions is provided in the registry.
STDMETHODIMP_(BOOL) CShellExt::IsExecutable(LPCTSTR Filename, int nPathOffset)
{
THREADINFO *pti;
THREADINFO ti;
pti = &ti;
pti = (THREADINFO *)TlsGetValue(TlsIndex);
TCHAR szData[1024] = {0};
TCHAR szValueName[1024] = {0};
DWORD dwDataBufSize=1024;
DWORD dwKeyDataType = 0;
HKEY hKey = NULL;
TCHAR szWarnExtensions[1024] = {0};
TCHAR szDoNotWarnExtensions[1024] = {0};
BOOL bFound = FALSE;
if (!Filename)
return FALSE;
LPSTR lpLastPeriod = _tcsrchr(Filename, '.');
if (lpLastPeriod)
{
// We found the file's extension
if ( RegOpenKeyEx(HKEY_CURRENT_USER, LM_REG_APP_KEY,0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
// Get the WarnExtensions value for the specified Path Index
sprintf(szValueName,LM_REG_WARN_KEY,nPathOffset);
if (RegQueryValueEx(hKey, szValueName, NULL, &dwKeyDataType, (LPBYTE)szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS)
{
_tcscpy(szWarnExtensions,(LPCTSTR)szData);
}
// Get the DoNotWarnExtensions value for the specified Path Index
sprintf(szValueName,LM_REG_DONOTWARN_KEY,nPathOffset);
if (RegQueryValueEx(hKey, szValueName, NULL, &dwKeyDataType, (LPBYTE)szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS)
{
_tcscpy(szDoNotWarnExtensions,(LPCTSTR)szData);
}
RegCloseKey(hKey);
}
if ( szWarnExtensions[_tcslen(szWarnExtensions) - 1] != '|')
_tcscat(szWarnExtensions,"|"); // This helps us while parsing
TCHAR seps[] = "|"; // token's that will be used for parsing.
TCHAR *token;
token = _tcstok( szWarnExtensions, seps );
while( token != NULL )
{
// While there are tokens
if (!_tcsnicmp(token,lpLastPeriod + 1,_tcslen(token)) )
{
// Found an extension in the WarnExtensions List
bFound = TRUE;
break;
}
// Get next token
token = _tcstok( NULL, seps );
}
if (bFound)
{
token = _tcstok( szDoNotWarnExtensions, seps );
while( token != NULL )
{
// While there are tokens
if (!_tcsnicmp(token,lpLastPeriod + 1,_tcslen(token)) )
{
// Found an extension in the DoNotWarnExtensions List ..hence set the bFound to FALSE.
bFound = FALSE;
break;
}
// Get next token
token = _tcstok( NULL, seps );
}
}
}
return bFound;
}
// This function will dump the logging information in a file when required.
void DumpLogInformation(const TCHAR *szFormat ... )
{
TCHAR szTempBuffer[4096] = {0}; // Sufficient enough to store the string to display
TCHAR szBuffer[3968] = {0};
TCHAR szDate[128], szTime[128];
va_list argptr;
// try/catch block so that if somehow the code misbehaves, we do not crash the Shell.
try
{
// Today's date
_strdate(szDate);
// Current time
_strtime(szTime);
// Format the passed arguments
va_start( argptr, szFormat );
wvsprintf( szBuffer, szFormat, argptr );
va_end( argptr );
#ifdef _DEBUG
// Wrapped this in #ifdef because OutputDebugString dumps the information in release mode also
sprintf(szTempBuffer,"EuShlExt : %s, %s - %s\n", szDate, szTime, szBuffer);
OutputDebugString(szTempBuffer);
#endif
TCHAR szData[1024];
DWORD dwDataBufSize=1024;
DWORD dwKeyDataType;
HKEY hKey = NULL;
DWORD dwEnableLogging = FALSE;
TCHAR szLogFilePath[_MAX_PATH + _MAX_FNAME + _MAX_EXT];
if ( RegOpenKeyEx(HKEY_CURRENT_USER, LM_REG_APP_KEY, 0, KEY_READ | KEY_WRITE, &hKey) == ERROR_SUCCESS)
{
dwKeyDataType = REG_DWORD;
if (RegQueryValueEx(hKey, LM_REG_ENABLELOGGING_KEY, NULL, &dwKeyDataType,(LPBYTE) szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS)
{
if (dwKeyDataType == REG_DWORD)
dwEnableLogging = *((DWORD*)szData);
else
dwEnableLogging = FALSE;
// If logging enabled & a valid DLLPath is found
if ( (dwEnableLogging) &&
(RegQueryValueEx(hKey, LM_REG_DLLPATH_KEY, NULL, &dwKeyDataType,(LPBYTE) szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS) )
{
if (szData)
{
TCHAR *pChar = _tcsrchr((LPTSTR)szData,'\\');
if (pChar)
{
*pChar = '\0';
_tcscpy(szLogFilePath, szData);
_tcscat(szLogFilePath, "\\EuShlExt.log");
FILE* fLogFile = NULL;
fLogFile = fopen(szLogFilePath,"a");
if (fLogFile)
{
sprintf(szTempBuffer,"%s, %s - %s\n", szDate, szTime, szBuffer);
fprintf(fLogFile, szTempBuffer);
fclose(fLogFile);
}
}
}
}
}
}
}
catch(...)
{
// Do nothing, makes sure any misbehaviour does not crash the shell
}
}
| 25.49913
| 145
| 0.666417
|
dusong7
|
57afb922aa05a8271d69066a46ac26b34dcdad8f
| 947
|
hpp
|
C++
|
include/xvega/grammar/config/error_band_config.hpp
|
domoritz/xvega
|
3754dee3e7e38e79282ba267cd86c3885807a4cd
|
[
"BSD-3-Clause"
] | 34
|
2020-08-14T14:32:51.000Z
|
2022-02-16T23:20:02.000Z
|
include/xvega/grammar/config/error_band_config.hpp
|
domoritz/xvega
|
3754dee3e7e38e79282ba267cd86c3885807a4cd
|
[
"BSD-3-Clause"
] | 19
|
2020-08-20T20:04:39.000Z
|
2022-02-28T14:34:37.000Z
|
include/xvega/grammar/config/error_band_config.hpp
|
domoritz/xvega
|
3754dee3e7e38e79282ba267cd86c3885807a4cd
|
[
"BSD-3-Clause"
] | 7
|
2020-08-14T14:18:17.000Z
|
2022-02-01T10:59:24.000Z
|
// Copyright (c) 2020, QuantStack and XVega Contributors
//
// Distributed under the terms of the BSD 3-Clause License.
//
// The full license is in the file LICENSE, distributed with this software.
#ifndef XVEGA_ERROR_BAND_CONFIG_HPP
#define XVEGA_ERROR_BAND_CONFIG_HPP
#include "./mark_config.hpp"
namespace xv
{
using bool_mark_config_type = xtl::variant<mark_config, bool>;
struct error_band_config : public xp::xobserved<error_band_config>
{
XPROPERTY(xtl::xoptional<bool_mark_config_type>, error_band_config, band);
XPROPERTY(xtl::xoptional<bool_mark_config_type>, error_band_config, borders);
XPROPERTY(xtl::xoptional<std::string>, error_band_config, extent);
XPROPERTY(xtl::xoptional<std::string>, error_band_config, interpolate);
XPROPERTY(xtl::xoptional<double>, error_band_config, tension);
};
XVEGA_API void to_json(nl::json& j, const error_band_config& data);
}
#endif
| 33.821429
| 85
| 0.7434
|
domoritz
|
57b2e3f8c0c66b13c2c56059e8b73489931844a4
| 903
|
cpp
|
C++
|
0013_Roman_to_Integer/solution.cpp
|
Heliovic/LeetCode_Solutions
|
73d5a7aaffe62da9a9cd8a80288b260085fda08f
|
[
"MIT"
] | 2
|
2019-02-18T15:32:57.000Z
|
2019-03-18T12:55:35.000Z
|
0013_Roman_to_Integer/solution.cpp
|
Heliovic/LeetCode_Solutions
|
73d5a7aaffe62da9a9cd8a80288b260085fda08f
|
[
"MIT"
] | null | null | null |
0013_Roman_to_Integer/solution.cpp
|
Heliovic/LeetCode_Solutions
|
73d5a7aaffe62da9a9cd8a80288b260085fda08f
|
[
"MIT"
] | null | null | null |
class Solution {
public:
map<char, int> mp;
int romanToInt(string s) {
mp['I'] = 1;
mp['V'] = 5;
mp['X'] = 10;
mp['L'] = 50;
mp['C'] = 100;
mp['D'] = 500;
mp['M'] = 1000;
int ans = 0;
for (int i = 0; i < s.size(); i++)
{
if (i != s.size() - 1)
{
string str = "";
str += s[i]; str += s[i + 1];
if (str == "IV") {ans += 4; i++; continue;}
if (str == "IX") {ans += 9; i++; continue;}
if (str == "XL") {ans += 40; i++; continue;}
if (str == "XC") {ans += 90; i++; continue;}
if (str == "CD") {ans += 400; i++; continue;}
if (str == "CM") {ans += 900; i++; continue;}
}
ans += mp[s[i]];
}
return ans;
}
};
| 27.363636
| 61
| 0.311185
|
Heliovic
|
57b451a9b4fd704c703280407af46606c21b24e8
| 894
|
cpp
|
C++
|
tests/simple_pputil.cpp
|
crapp/pputil
|
d38edd744f3f998dd4957e659641cab2fa5c6a40
|
[
"MIT"
] | null | null | null |
tests/simple_pputil.cpp
|
crapp/pputil
|
d38edd744f3f998dd4957e659641cab2fa5c6a40
|
[
"MIT"
] | null | null | null |
tests/simple_pputil.cpp
|
crapp/pputil
|
d38edd744f3f998dd4957e659641cab2fa5c6a40
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "pputil.hpp"
#include "simple_pputil.hpp"
namespace ut = pputil;
StreamOp::StreamOp(){};
StreamOp::StreamOp(std::string s) : mystring(std::move(s)){};
StreamOp::~StreamOp(){};
void StreamOp::setMyString(std::string mystring)
{
this->mystring = std::move(mystring);
}
std::string StreamOp::getMyString() const { return this->mystring; }
int main(ATTR_UNUSED int argc, ATTR_UNUSED char *argv[])
{
// concatenate some simple strings
std::string cons = ut::stringify("Foo", "Bar", "Baz");
// prints FooBarBaz
std::cout << cons << std::endl;
// concatenate with objects implementing stream operator
StreamOp so("OperatorToString");
std::cout << cons + " AND " + ut::op_to_string(so) << std::endl;
// create toml usable strings
std::cout << ut::toml_stringify("GENERAL", "FOO", "BAR", "BAZ") << std::endl;
return 0;
}
| 25.542857
| 81
| 0.657718
|
crapp
|
57b5d5e9433f6463eccbfc6bb319306cc083cfff
| 8,478
|
cpp
|
C++
|
src/robot_model.cpp
|
mayataka/invariant-ekf
|
775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0
|
[
"BSD-3-Clause"
] | 1
|
2022-03-28T12:38:09.000Z
|
2022-03-28T12:38:09.000Z
|
src/robot_model.cpp
|
mayataka/inekf
|
775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0
|
[
"BSD-3-Clause"
] | null | null | null |
src/robot_model.cpp
|
mayataka/inekf
|
775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0
|
[
"BSD-3-Clause"
] | null | null | null |
#include "inekf/robot_model.hpp"
namespace inekf {
pinocchio::Model RobotModel::buildFloatingBaseModel(
const std::string& path_to_urdf) {
pinocchio::Model pin_model;
pinocchio::urdf::buildModel(path_to_urdf,
pinocchio::JointModelFreeFlyer(), pin_model);
return pin_model;
}
RobotModel::RobotModel(const std::string& path_to_urdf, const int imu_frame,
const std::vector<int>& contact_frames)
: RobotModel(buildFloatingBaseModel(path_to_urdf), imu_frame, contact_frames) {
}
RobotModel::RobotModel(const std::string& path_to_urdf,
const std::string& imu_frame,
const std::vector<std::string>& contact_frames)
: RobotModel(buildFloatingBaseModel(path_to_urdf), imu_frame, contact_frames) {
}
RobotModel::RobotModel(const pinocchio::Model& pin_model, const int imu_frame,
const std::vector<int>& contact_frames)
: contact_frames_(contact_frames),
imu_frame_(imu_frame),
model_(pin_model),
data_(),
q_(),
v_(),
a_(),
tau_(),
jac_6d_() {
data_ = pinocchio::Data(model_);
q_ = Eigen::VectorXd(model_.nq);
v_ = Eigen::VectorXd(model_.nv);
a_ = Eigen::VectorXd(model_.nv);
tau_ = Eigen::VectorXd(model_.nv);
for (int i=0; i<contact_frames.size(); ++i) {
jac_6d_.push_back(Eigen::MatrixXd::Zero(6, model_.nv));
}
}
RobotModel::RobotModel(const pinocchio::Model& pin_model,
const std::string& imu_frame,
const std::vector<std::string>& contact_frames)
: contact_frames_(),
imu_frame_(),
model_(pin_model),
data_(),
q_(),
v_(),
a_(),
tau_(),
jac_6d_() {
data_ = pinocchio::Data(model_);
q_ = Eigen::VectorXd(model_.nq);
v_ = Eigen::VectorXd(model_.nv);
a_ = Eigen::VectorXd(model_.nv);
tau_ = Eigen::VectorXd(model_.nv);
for (int i=0; i<contact_frames.size(); ++i) {
jac_6d_.push_back(Eigen::MatrixXd::Zero(6, model_.nv));
}
try {
if (!model_.existFrame(imu_frame)) {
throw std::invalid_argument(
"Invalid argument: frame " + imu_frame + " does not exit!");
}
}
catch(const std::exception& e) {
std::cerr << e.what() << '\n';
std::exit(EXIT_FAILURE);
}
imu_frame_ = model_.getFrameId(imu_frame);
contact_frames_.clear();
for (const auto& e : contact_frames) {
try {
if (!model_.existFrame(e)) {
throw std::invalid_argument(
"Invalid argument: frame " + e + " does not exit!");
}
}
catch(const std::exception& e) {
std::cerr << e.what() << '\n';
std::exit(EXIT_FAILURE);
}
contact_frames_.push_back(model_.getFrameId(e));
}
}
RobotModel::RobotModel()
: contact_frames_(),
imu_frame_(),
model_(),
data_(),
q_(),
v_(),
a_(),
tau_(),
jac_6d_() {
}
void RobotModel::updateLegKinematics(const Eigen::VectorXd& qJ,
const pinocchio::ReferenceFrame rf) {
updateKinematics(Eigen::Vector3d::Zero(),
Eigen::Quaterniond::Identity().coeffs(), qJ, rf);
}
void RobotModel::updateLegKinematics(const Eigen::VectorXd& qJ,
const Eigen::VectorXd& dqJ,
const pinocchio::ReferenceFrame rf) {
updateKinematics(Eigen::Vector3d::Zero(),
Eigen::Quaterniond::Identity().coeffs(),
Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(),
qJ, dqJ, rf);
}
void RobotModel::updateKinematics(const Eigen::Vector3d& base_pos,
const Eigen::Vector4d& base_quat,
const Eigen::VectorXd& qJ,
const pinocchio::ReferenceFrame rf) {
q_.template head<3>() = base_pos;
q_.template segment<4>(3) = base_quat;
q_.tail(model_.nq-7) = qJ;
pinocchio::normalize(model_, q_);
pinocchio::forwardKinematics(model_, data_, q_);
pinocchio::updateFramePlacements(model_, data_);
pinocchio::computeJointJacobians(model_, data_, q_);
for (int i=0; i<contact_frames_.size(); ++i) {
pinocchio::getFrameJacobian(model_, data_, contact_frames_[i], rf, jac_6d_[i]);
}
}
void RobotModel::updateKinematics(const Eigen::Vector3d& base_pos,
const Eigen::Vector4d& base_quat,
const Eigen::Vector3d& base_linear_vel,
const Eigen::Vector3d& base_angular_vel,
const Eigen::VectorXd& qJ,
const Eigen::VectorXd& dqJ,
const pinocchio::ReferenceFrame rf) {
q_.template head<3>() = base_pos;
q_.template segment<4>(3) = base_quat;
v_.template head<3>() = base_linear_vel;
v_.template segment<3>(3) = base_angular_vel;
q_.tail(model_.nq-7) = qJ;
v_.tail(model_.nv-6) = dqJ;
pinocchio::normalize(model_, q_);
pinocchio::forwardKinematics(model_, data_, q_, v_);
pinocchio::updateFramePlacements(model_, data_);
pinocchio::computeJointJacobians(model_, data_, q_);
for (int i=0; i<contact_frames_.size(); ++i) {
pinocchio::getFrameJacobian(model_, data_, contact_frames_[i], rf, jac_6d_[i]);
}
}
void RobotModel::updateLegDynamics(const Eigen::VectorXd& qJ,
const Eigen::VectorXd& dqJ) {
updateDynamics(Eigen::Vector3d::Zero(),
Eigen::Quaterniond::Identity().coeffs(),
Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(),
Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(),
qJ, dqJ, Eigen::VectorXd::Zero(nJ()));
}
void RobotModel::updateDynamics(const Eigen::Vector3d& base_pos,
const Eigen::Vector4d& base_quat,
const Eigen::Vector3d& base_linear_vel,
const Eigen::Vector3d& base_angular_vel,
const Eigen::Vector3d& base_linear_acc,
const Eigen::Vector3d& base_angular_acc,
const Eigen::VectorXd& qJ,
const Eigen::VectorXd& dqJ,
const Eigen::VectorXd& ddqJ) {
q_.template head<3>() = base_pos;
q_.template segment<4>(3) = base_quat;
v_.template head<3>() = base_linear_vel;
v_.template segment<3>(3) = base_angular_vel;
a_.template head<3>() = base_linear_acc;
a_.template segment<3>(3) = base_angular_acc;
q_.tail(model_.nq-7) = qJ;
v_.tail(model_.nv-6) = dqJ;
a_.tail(model_.nv-6) = ddqJ;
tau_ = pinocchio::rnea(model_, data_, q_, v_, a_);
}
const Eigen::Vector3d& RobotModel::getBasePosition() const {
return data_.oMf[imu_frame_].translation();
}
const Eigen::Matrix3d& RobotModel::getBaseRotation() const {
return data_.oMf[imu_frame_].rotation();
}
const Eigen::Vector3d& RobotModel::getContactPosition(const int contact_id) const {
assert(contact_id >= 0);
assert(contact_id < contact_frames_.size());
return data_.oMf[contact_frames_[contact_id]].translation();
}
const Eigen::Matrix3d& RobotModel::getContactRotation(const int contact_id) const {
assert(contact_id >= 0);
assert(contact_id < contact_frames_.size());
return data_.oMf[contact_frames_[contact_id]].rotation();
}
const Eigen::Block<const Eigen::MatrixXd> RobotModel::getContactJacobian(const int contact_id) const {
assert(contact_id >= 0);
assert(contact_id < contact_frames_.size());
return jac_6d_[contact_id].topRows(3);
}
const Eigen::Block<const Eigen::MatrixXd> RobotModel::getJointContactJacobian(const int contact_id) const {
assert(contact_id >= 0);
assert(contact_id < contact_frames_.size());
return jac_6d_[contact_id].topRightCorner(3, nJ());
}
const Eigen::VectorXd& RobotModel::getInverseDynamics() const {
return tau_;
}
const Eigen::VectorBlock<const Eigen::VectorXd> RobotModel::getJointInverseDynamics() const {
return tau_.tail(nJ());
}
const std::vector<int>& RobotModel::getContactFrames() const {
return contact_frames_;
}
int RobotModel::nq() const {
return model_.nq;
}
int RobotModel::nv() const {
return model_.nv;
}
int RobotModel::nJ() const {
return model_.nv-6;
}
int RobotModel::numContacts() const {
return contact_frames_.size();
}
} // namespace inekf
| 31.054945
| 107
| 0.612173
|
mayataka
|
57bdf8636eacaf95435fb2340cc319a7ba07f6d5
| 4,727
|
cpp
|
C++
|
WebKit2-7534.57.7/WebKit2-7534.57.7/Platform/qt/SharedMemorySymbian.cpp
|
mlcldh/appleWebKit2
|
39cc42a4710c9319c8da269621844493ab2ccdd6
|
[
"MIT"
] | 1
|
2021-05-27T07:29:31.000Z
|
2021-05-27T07:29:31.000Z
|
WebKit2-7534.57.7/WebKit2-7534.57.7/Platform/qt/SharedMemorySymbian.cpp
|
mlcldh/appleWebKit2
|
39cc42a4710c9319c8da269621844493ab2ccdd6
|
[
"MIT"
] | null | null | null |
WebKit2-7534.57.7/WebKit2-7534.57.7/Platform/qt/SharedMemorySymbian.cpp
|
mlcldh/appleWebKit2
|
39cc42a4710c9319c8da269621844493ab2ccdd6
|
[
"MIT"
] | null | null | null |
/*
Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if PLATFORM(QT) && OS(SYMBIAN)
#include "SharedMemory.h"
#include "ArgumentDecoder.h"
#include "ArgumentEncoder.h"
#include <e32math.h>
#include <qdebug.h>
#include <qglobal.h>
#include <sys/param.h>
namespace WebKit {
SharedMemory::Handle::Handle()
: m_chunkID(0)
, m_size(0)
{
}
SharedMemory::Handle::~Handle()
{
}
bool SharedMemory::Handle::isNull() const
{
return !m_chunkID;
}
void SharedMemory::Handle::encode(CoreIPC::ArgumentEncoder* encoder) const
{
ASSERT(!isNull());
encoder->encodeUInt32(m_size);
// name of the global chunk (masquerading as uint32_t for ease of serialization)
encoder->encodeUInt32(m_chunkID);
}
bool SharedMemory::Handle::decode(CoreIPC::ArgumentDecoder* decoder, Handle& handle)
{
size_t size;
if (!decoder->decodeUInt32(size))
return false;
uint32_t chunkID;
if (!decoder->decodeUInt32(chunkID))
return false;
handle.m_size = size;
handle.m_chunkID = chunkID;
return true;
}
// FIXME: To be removed as part of Bug 55877
CoreIPC::Attachment SharedMemory::Handle::releaseToAttachment() const
{
return CoreIPC::Attachment(-1, 0);
}
// FIXME: To be removed as part of Bug 55877
void SharedMemory::Handle::adoptFromAttachment(int, size_t)
{
}
PassRefPtr<SharedMemory> SharedMemory::create(size_t size)
{
// On Symbian, global chunks (shared memory segments) have system-unique names, so we pick a random
// number from the kernel's random pool and use it as a string.
// Using an integer simplifies serialization of the name in Handle::encode()
uint32_t random = Math::Random();
TBuf<KMaxKernelName> chunkName;
chunkName.Format(_L("%d"), random);
RChunk chunk;
TInt error = chunk.CreateGlobal(chunkName, size, size);
if (error) {
qCritical() << "Failed to create WK2 shared memory of size " << size << " with error " << error;
return 0;
}
RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory));
sharedMemory->m_handle = chunk.Handle();
sharedMemory->m_size = chunk.Size();
sharedMemory->m_data = static_cast<void*>(chunk.Base());
return sharedMemory.release();
}
PassRefPtr<SharedMemory> SharedMemory::create(const Handle& handle, Protection protection)
{
if (handle.isNull())
return 0;
// Convert number to string, and open the global chunk
TBuf<KMaxKernelName> chunkName;
chunkName.Format(_L("%d"), handle.m_chunkID);
RChunk chunk;
// NOTE: Symbian OS doesn't support read-only global chunks.
TInt error = chunk.OpenGlobal(chunkName, false);
if (error) {
qCritical() << "Failed to create WK2 shared memory from handle " << error;
return 0;
}
chunk.Adjust(chunk.MaxSize());
RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory));
sharedMemory->m_handle = chunk.Handle();
sharedMemory->m_size = chunk.Size();
sharedMemory->m_data = static_cast<void*>(chunk.Base());
return sharedMemory.release();
}
SharedMemory::~SharedMemory()
{
// FIXME: We don't Close() the chunk here, causing leaks of the shared memory segment
// If we do, the chunk is closed the decommitted prematurely before the other process
// has a chance to OpenGlobal() it.
}
bool SharedMemory::createHandle(Handle& handle, Protection protection)
{
ASSERT_ARG(handle, handle.isNull());
RChunk chunk;
if (chunk.SetReturnedHandle(m_handle))
return false;
// Convert the name (string form) to a uint32_t.
TName globalChunkName = chunk.Name();
TLex lexer(globalChunkName);
TUint32 nameAsInt = 0;
if (lexer.Val(nameAsInt, EDecimal))
return false;
handle.m_chunkID = nameAsInt;
handle.m_size = m_size;
return true;
}
unsigned SharedMemory::systemPageSize()
{
return PAGE_SIZE;
}
} // namespace WebKit
#endif
| 28.305389
| 104
| 0.697271
|
mlcldh
|
57be0c35fcf710e6e160fa71ecdaa7a3a5a7475d
| 10,400
|
cc
|
C++
|
source/tracking/pyG4VSteppingVerbose.cc
|
yu22mal/geant4_pybind
|
ff7efc322fe53f39c7ae7ed140861052a92479fd
|
[
"Unlicense"
] | 6
|
2021-08-08T08:40:13.000Z
|
2022-03-23T03:05:15.000Z
|
source/tracking/pyG4VSteppingVerbose.cc
|
yu22mal/geant4_pybind
|
ff7efc322fe53f39c7ae7ed140861052a92479fd
|
[
"Unlicense"
] | 3
|
2021-12-01T14:38:06.000Z
|
2022-02-10T11:28:28.000Z
|
source/tracking/pyG4VSteppingVerbose.cc
|
yu22mal/geant4_pybind
|
ff7efc322fe53f39c7ae7ed140861052a92479fd
|
[
"Unlicense"
] | 3
|
2021-07-16T13:57:34.000Z
|
2022-02-07T11:17:19.000Z
|
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <G4VSteppingVerbose.hh>
#include <G4SteppingVerbose.hh>
#include <G4SteppingManager.hh>
#include <G4Navigator.hh>
#include <G4VPhysicalVolume.hh>
#include <G4VSensitiveDetector.hh>
#include <G4ProcessVector.hh>
#include <G4SteppingManager.hh>
#include <G4Track.hh>
#include <G4UserSteppingAction.hh>
#include <G4StepPoint.hh>
#include <G4VParticleChange.hh>
#include "typecast.hh"
#include "opaques.hh"
namespace py = pybind11;
class PublicG4VSteppingVerbose : public G4VSteppingVerbose {
public:
using G4VSteppingVerbose::fManager;
using G4VSteppingVerbose::fUserSteppingAction;
using G4VSteppingVerbose::CorrectedStep;
using G4VSteppingVerbose::FirstStep;
using G4VSteppingVerbose::fStepStatus;
using G4VSteppingVerbose::GeometricalStep;
using G4VSteppingVerbose::PhysicalStep;
using G4VSteppingVerbose::PreStepPointIsGeom;
using G4VSteppingVerbose::Mass;
using G4VSteppingVerbose::TempInitVelocity;
using G4VSteppingVerbose::TempVelocity;
using G4VSteppingVerbose::sumEnergyChange;
using G4VSteppingVerbose::fParticleChange;
using G4VSteppingVerbose::fPostStepPoint;
using G4VSteppingVerbose::fPreStepPoint;
using G4VSteppingVerbose::fSecondary;
using G4VSteppingVerbose::fStep;
using G4VSteppingVerbose::fTrack;
using G4VSteppingVerbose::fCurrentProcess;
using G4VSteppingVerbose::fCurrentVolume;
using G4VSteppingVerbose::fSensitive;
using G4VSteppingVerbose::fAlongStepDoItVector;
using G4VSteppingVerbose::fAtRestDoItVector;
using G4VSteppingVerbose::fPostStepDoItVector;
using G4VSteppingVerbose::fAlongStepGetPhysIntVector;
using G4VSteppingVerbose::fAtRestGetPhysIntVector;
using G4VSteppingVerbose::fPostStepGetPhysIntVector;
using G4VSteppingVerbose::MAXofAlongStepLoops;
using G4VSteppingVerbose::MAXofAtRestLoops;
using G4VSteppingVerbose::MAXofPostStepLoops;
using G4VSteppingVerbose::currentMinimumStep;
using G4VSteppingVerbose::numberOfInteractionLengthLeft;
using G4VSteppingVerbose::fAlongStepDoItProcTriggered;
using G4VSteppingVerbose::fAtRestDoItProcTriggered;
using G4VSteppingVerbose::fPostStepDoItProcTriggered;
using G4VSteppingVerbose::fN2ndariesAlongStepDoIt;
using G4VSteppingVerbose::fN2ndariesAtRestDoIt;
using G4VSteppingVerbose::fN2ndariesPostStepDoIt;
using G4VSteppingVerbose::fNavigator;
using G4VSteppingVerbose::verboseLevel;
using G4VSteppingVerbose::fSelectedAlongStepDoItVector;
using G4VSteppingVerbose::fSelectedAtRestDoItVector;
using G4VSteppingVerbose::fSelectedPostStepDoItVector;
using G4VSteppingVerbose::fPreviousStepSize;
using G4VSteppingVerbose::fTouchableHandle;
using G4VSteppingVerbose::StepControlFlag;
using G4VSteppingVerbose::fCondition;
using G4VSteppingVerbose::fGPILSelection;
using G4VSteppingVerbose::physIntLength;
};
class PyG4VSteppingVerbose : public G4VSteppingVerbose, public py::trampoline_self_life_support {
public:
using G4VSteppingVerbose::G4VSteppingVerbose;
void NewStep() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, NewStep, ); }
void AtRestDoItInvoked() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, AtRestDoItInvoked, ); }
void AlongStepDoItAllDone() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, AlongStepDoItAllDone, ); }
void PostStepDoItAllDone() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, PostStepDoItAllDone, ); }
void AlongStepDoItOneByOne() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, AlongStepDoItOneByOne, ); }
void PostStepDoItOneByOne() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, PostStepDoItOneByOne, ); }
void StepInfo() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, StepInfo, ); }
void TrackingStarted() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, TrackingStarted, ); }
void DPSLStarted() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, DPSLStarted, ); }
void DPSLUserLimit() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, DPSLUserLimit, ); }
void DPSLPostStep() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, DPSLPostStep, ); }
void DPSLAlongStep() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, DPSLAlongStep, ); }
void VerboseTrack() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, VerboseTrack, ); }
void VerboseParticleChange() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, VerboseParticleChange, ); }
};
void export_G4VSteppingVerbose(py::module &m)
{
py::class_<G4VSteppingVerbose, PyG4VSteppingVerbose>(m, "G4VSteppingVerbose")
.def_static("SetInstance",
[](py::disown_ptr<G4VSteppingVerbose> instance) { G4VSteppingVerbose::SetInstance(instance); })
.def_static("GetInstance", &G4VSteppingVerbose::GetInstance, py::return_value_policy::reference)
.def_static("GetSilent", &G4VSteppingVerbose::GetSilent)
.def_static("SetSilent", &G4VSteppingVerbose::SetSilent)
.def_static("SetSilentStepInfo", &G4VSteppingVerbose::SetSilentStepInfo)
.def("NewStep", &G4VSteppingVerbose::NewStep)
.def("CopyState", &G4VSteppingVerbose::CopyState)
.def("SetManager", &G4VSteppingVerbose::SetManager)
.def("AtRestDoItInvoked", &G4VSteppingVerbose::AtRestDoItInvoked)
.def("AlongStepDoItAllDone", &G4VSteppingVerbose::AlongStepDoItAllDone)
.def("PostStepDoItAllDone", &G4VSteppingVerbose::PostStepDoItAllDone)
.def("AlongStepDoItOneByOne", &G4VSteppingVerbose::AlongStepDoItOneByOne)
.def("StepInfo", &G4VSteppingVerbose::StepInfo)
.def("TrackingStarted", &G4VSteppingVerbose::TrackingStarted)
.def("DPSLStarted", &G4VSteppingVerbose::DPSLStarted)
.def("DPSLUserLimit", &G4VSteppingVerbose::DPSLUserLimit)
.def("DPSLPostStep", &G4VSteppingVerbose::DPSLPostStep)
.def("DPSLAlongStep", &G4VSteppingVerbose::DPSLAlongStep)
.def("VerboseTrack", &G4VSteppingVerbose::VerboseTrack)
.def("VerboseParticleChange", &G4VSteppingVerbose::VerboseParticleChange)
.def_readwrite("fManager", &PublicG4VSteppingVerbose::fManager)
.def_readwrite("fUserSteppingAction", &PublicG4VSteppingVerbose::fUserSteppingAction)
.def_readwrite("PhysicalStep", &PublicG4VSteppingVerbose::PhysicalStep)
.def_readwrite("GeometricalStep", &PublicG4VSteppingVerbose::GeometricalStep)
.def_readwrite("CorrectedStep", &PublicG4VSteppingVerbose::CorrectedStep)
.def_readwrite("PreStepPointIsGeom", &PublicG4VSteppingVerbose::PreStepPointIsGeom)
.def_readwrite("FirstStep", &PublicG4VSteppingVerbose::FirstStep)
.def_readwrite("fStepStatus", &PublicG4VSteppingVerbose::fStepStatus)
.def_readwrite("TempInitVelocity", &PublicG4VSteppingVerbose::TempInitVelocity)
.def_readwrite("TempVelocity", &PublicG4VSteppingVerbose::TempVelocity)
.def_readwrite("Mass", &PublicG4VSteppingVerbose::Mass)
.def_readwrite("sumEnergyChange", &PublicG4VSteppingVerbose::sumEnergyChange)
.def_readwrite("fParticleChange", &PublicG4VSteppingVerbose::fParticleChange)
.def_readwrite("fTrack", &PublicG4VSteppingVerbose::fTrack)
.def_readwrite("fSecondary", &PublicG4VSteppingVerbose::fSecondary)
.def_readwrite("fStep", &PublicG4VSteppingVerbose::fStep)
.def_readwrite("fPreStepPoint", &PublicG4VSteppingVerbose::fPreStepPoint)
.def_readwrite("fPostStepPoint", &PublicG4VSteppingVerbose::fPostStepPoint)
.def_readwrite("fCurrentVolume", &PublicG4VSteppingVerbose::fCurrentVolume)
.def_readwrite("fSensitive", &PublicG4VSteppingVerbose::fSensitive)
.def_readwrite("fCurrentProcess", &PublicG4VSteppingVerbose::fCurrentProcess)
.def_readwrite("fAtRestDoItVector", &PublicG4VSteppingVerbose::fAtRestDoItVector)
.def_readwrite("fAlongStepDoItVector", &PublicG4VSteppingVerbose::fAlongStepDoItVector)
.def_readwrite("fPostStepDoItVector", &PublicG4VSteppingVerbose::fPostStepDoItVector)
.def_readwrite("fAtRestGetPhysIntVector", &PublicG4VSteppingVerbose::fAtRestGetPhysIntVector)
.def_readwrite("fAlongStepGetPhysIntVector", &PublicG4VSteppingVerbose::fAlongStepGetPhysIntVector)
.def_readwrite("fPostStepGetPhysIntVector", &PublicG4VSteppingVerbose::fPostStepGetPhysIntVector)
.def_readwrite("MAXofAtRestLoops", &PublicG4VSteppingVerbose::MAXofAtRestLoops)
.def_readwrite("MAXofAlongStepLoops", &PublicG4VSteppingVerbose::MAXofAlongStepLoops)
.def_readwrite("MAXofPostStepLoops", &PublicG4VSteppingVerbose::MAXofPostStepLoops)
.def_readwrite("currentMinimumStep", &PublicG4VSteppingVerbose::currentMinimumStep)
.def_readwrite("numberOfInteractionLengthLeft", &PublicG4VSteppingVerbose::numberOfInteractionLengthLeft)
.def_readwrite("fAtRestDoItProcTriggered", &PublicG4VSteppingVerbose::fAtRestDoItProcTriggered)
.def_readwrite("fAlongStepDoItProcTriggered", &PublicG4VSteppingVerbose::fAlongStepDoItProcTriggered)
.def_readwrite("fPostStepDoItProcTriggered", &PublicG4VSteppingVerbose::fPostStepDoItProcTriggered)
.def_readwrite("fN2ndariesAtRestDoIt", &PublicG4VSteppingVerbose::fN2ndariesAtRestDoIt)
.def_readwrite("fN2ndariesAlongStepDoIt", &PublicG4VSteppingVerbose::fN2ndariesAlongStepDoIt)
.def_readwrite("fN2ndariesPostStepDoIt", &PublicG4VSteppingVerbose::fN2ndariesPostStepDoIt)
.def_readwrite("fNavigator", &PublicG4VSteppingVerbose::fNavigator)
.def_readwrite("verboseLevel", &PublicG4VSteppingVerbose::verboseLevel)
.def_readwrite("fSelectedAtRestDoItVector", &PublicG4VSteppingVerbose::fSelectedAtRestDoItVector)
.def_readwrite("fSelectedAlongStepDoItVector", &PublicG4VSteppingVerbose::fSelectedAlongStepDoItVector)
.def_readwrite("fSelectedPostStepDoItVector", &PublicG4VSteppingVerbose::fSelectedPostStepDoItVector)
.def_readwrite("fPreviousStepSize", &PublicG4VSteppingVerbose::fPreviousStepSize)
.def_readwrite("fTouchableHandle", &PublicG4VSteppingVerbose::fTouchableHandle)
.def_readwrite("StepControlFlag", &PublicG4VSteppingVerbose::StepControlFlag)
.def_readwrite("physIntLength", &PublicG4VSteppingVerbose::physIntLength)
.def_readwrite("fCondition", &PublicG4VSteppingVerbose::fCondition)
.def_readwrite("fGPILSelection", &PublicG4VSteppingVerbose::fGPILSelection);
}
| 47.058824
| 114
| 0.793846
|
yu22mal
|
57c2d05e086d53b3dd0832a7a37a3583a84af4f6
| 10,687
|
hpp
|
C++
|
include/strf/to_string.hpp
|
robhz786/strf
|
72163cb10f5cc725788bbce74ce16e4024489734
|
[
"BSL-1.0"
] | 49
|
2019-12-16T10:39:22.000Z
|
2022-03-28T02:32:47.000Z
|
include/strf/to_string.hpp
|
ckerr/strf
|
72163cb10f5cc725788bbce74ce16e4024489734
|
[
"BSL-1.0"
] | 36
|
2019-12-13T00:31:22.000Z
|
2022-03-13T18:22:14.000Z
|
include/strf/to_string.hpp
|
ckerr/strf
|
72163cb10f5cc725788bbce74ce16e4024489734
|
[
"BSL-1.0"
] | 3
|
2019-12-07T20:05:51.000Z
|
2021-11-30T02:45:35.000Z
|
#ifndef STRF_DETAIL_OUTPUT_TYPES_STD_STRING_HPP
#define STRF_DETAIL_OUTPUT_TYPES_STD_STRING_HPP
// Copyright (C) (See commit logs on github.com/robhz786/strf)
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <strf/destination.hpp>
#include <strf.hpp>
#include <string>
namespace strf {
template < typename CharT
, typename Traits = std::char_traits<CharT>
, typename Allocator = std::allocator<CharT> >
class basic_string_appender final: public strf::destination<CharT>
{
using string_type_ = std::basic_string<CharT, Traits, Allocator>;
public:
basic_string_appender(string_type_& str)
: strf::destination<CharT>(buf_, buf_size_)
, str_(str)
{
}
basic_string_appender( string_type_& str
, std::size_t size )
: strf::destination<CharT>(buf_, buf_size_)
, str_(str)
{
str_.reserve(size);
}
basic_string_appender(const basic_string_appender&) = delete;
basic_string_appender(basic_string_appender&&) = delete;
void recycle() override
{
auto * p = this->buffer_ptr();
this->set_buffer_ptr(buf_);
STRF_IF_LIKELY (this->good()) {
this->set_good(false);
str_.append(buf_, p);
this->set_good(true);
}
}
void finish()
{
auto * p = this->buffer_ptr();
STRF_IF_LIKELY (this->good()) {
this->set_good(false);
str_.append(buf_, p);
}
}
private:
void do_write(const CharT* str, std::size_t str_len) override
{
auto * p = this->buffer_ptr();
this->set_buffer_ptr(buf_);
STRF_IF_LIKELY (this->good()) {
this->set_good(false);
str_.append(buf_, p);
str_.append(str, str_len);
this->set_good(true);
}
}
string_type_& str_;
static constexpr std::size_t buf_size_
= strf::min_space_after_recycle<CharT>();
CharT buf_[buf_size_];
};
template < typename CharT
, typename Traits = std::char_traits<CharT>
, typename Allocator = std::allocator<CharT> >
class basic_string_maker final: public strf::destination<CharT>
{
using string_type_ = std::basic_string<CharT, Traits, Allocator>;
public:
basic_string_maker()
: strf::destination<CharT>(buf_, buf_size_)
{
}
basic_string_maker(strf::tag<void>)
: basic_string_maker()
{
}
basic_string_maker(const basic_string_maker&) = delete;
basic_string_maker(basic_string_maker&&) = delete;
~basic_string_maker()
{
if (string_initialized_) {
string_ptr()->~string_type_();
}
}
void recycle() override;
string_type_ finish()
{
STRF_IF_LIKELY (this->good()) {
this->set_good(false);
std::size_t count = this->buffer_ptr() - buf_;
STRF_IF_LIKELY ( ! string_initialized_) {
return {buf_, count};
}
string_ptr() -> append(buf_, count);
return std::move(*string_ptr());
}
return {};
}
private:
void do_write(const CharT* str, std::size_t str_len) override;
bool string_initialized_ = false;
string_type_* string_ptr()
{
void* ptr = &string_obj_space_;
return reinterpret_cast<string_type_*>(ptr);
}
static constexpr std::size_t buf_size_ = strf::min_space_after_recycle<CharT>();
CharT buf_[buf_size_];
using string_storage_type_ = typename std::aligned_storage
< sizeof(string_type_), alignof(string_type_) >
:: type;
string_storage_type_ string_obj_space_;
};
template < typename CharT, typename Traits, typename Allocator >
void basic_string_maker<CharT, Traits, Allocator>::recycle()
{
std::size_t count = this->buffer_ptr() - buf_;
this->set_buffer_ptr(buf_);
STRF_IF_LIKELY (this->good()) {
this->set_good(false); // in case the following code throws
if ( ! string_initialized_) {
new (string_ptr()) string_type_{buf_, count};
string_initialized_ = true;
} else {
string_ptr() -> append(buf_, count);
}
this->set_good(true);
}
}
template < typename CharT, typename Traits, typename Allocator >
void basic_string_maker<CharT, Traits, Allocator>::do_write(const CharT* str, std::size_t str_len)
{
STRF_IF_LIKELY (this->good()) {
std::size_t buf_count = this->buffer_ptr() - buf_;
this->set_buffer_ptr(buf_);
this->set_good(false); // in case the following code throws
if ( ! string_initialized_) {
new (string_ptr()) string_type_();
string_ptr()->reserve((buf_count + str_len) << 1);
string_ptr()->append(buf_, buf_count);
string_ptr()->append(str, str_len);
string_initialized_ = true;
} else {
string_ptr()->append(buf_, buf_count);
string_ptr()->append(str, str_len);
}
this->set_good(true);
}
}
template < typename CharT
, typename Traits = std::char_traits<CharT>
, typename Allocator = std::allocator<CharT> >
class basic_sized_string_maker final
: public strf::destination<CharT>
{
public:
explicit basic_sized_string_maker(std::size_t count)
: strf::destination<CharT>(nullptr, nullptr)
, str_(count ? count : 1, (CharT)0)
{
this->set_buffer_ptr(&*str_.begin());
this->set_buffer_end(&*str_.begin() + (count ? count : 1));
}
basic_sized_string_maker(const basic_sized_string_maker&) = delete;
basic_sized_string_maker(basic_sized_string_maker&&) = delete;
void recycle() override
{
std::size_t original_size = this->buffer_ptr() - str_.data();
constexpr std::size_t min_buff_size = strf::min_space_after_recycle<CharT>();
auto append_size = strf::detail::max<std::size_t>(original_size, min_buff_size);
str_.append(append_size, (CharT)0);
this->set_buffer_ptr(&*str_.begin() + original_size);
this->set_buffer_end(&*str_.begin() + original_size + append_size);
}
std::basic_string<CharT, Traits, Allocator> finish()
{
str_.resize(this->buffer_ptr() - str_.data());
return std::move(str_);
}
private:
std::basic_string<CharT, Traits, Allocator> str_;
};
using string_appender = basic_string_appender<char>;
using u16string_appender = basic_string_appender<char16_t>;
using u32string_appender = basic_string_appender<char32_t>;
using wstring_appender = basic_string_appender<wchar_t>;
using string_maker = basic_string_maker<char>;
using u16string_maker = basic_string_maker<char16_t>;
using u32string_maker = basic_string_maker<char32_t>;
using wstring_maker = basic_string_maker<wchar_t>;
using sized_string_maker = basic_sized_string_maker<char>;
using sized_u16string_maker = basic_sized_string_maker<char16_t>;
using sized_u32string_maker = basic_sized_string_maker<char32_t>;
using sized_wstring_maker = basic_sized_string_maker<wchar_t>;
#if defined(__cpp_char8_t)
using u8string_appender = basic_string_appender<char8_t>;
using u8string_maker = basic_string_maker<char8_t>;
using pre_sized_u8string_maker = basic_sized_string_maker<char8_t>;
#endif
namespace detail {
template <typename CharT, typename Traits, typename Allocator>
class basic_string_appender_creator
{
public:
using char_type = CharT;
using destination_type = strf::basic_string_appender<CharT, Traits, Allocator>;
using sized_destination_type = destination_type;
using finish_type = void;
basic_string_appender_creator
( std::basic_string<CharT, Traits, Allocator>& str )
: str_(str)
{
}
basic_string_appender_creator(const basic_string_appender_creator&) = default;
std::basic_string<CharT, Traits, Allocator>& create() const noexcept
{
return str_;
}
std::basic_string<CharT, Traits, Allocator>& create(std::size_t size) const noexcept
{
str_.reserve(str_.size() + size);
return str_;
}
private:
std::basic_string<CharT, Traits, Allocator>& str_;
};
template < typename CharT
, typename Traits = std::char_traits<CharT>
, typename Allocator = std::allocator<CharT> >
class basic_string_maker_creator
{
public:
using char_type = CharT;
using finish_type = std::basic_string<CharT, Traits, Allocator>;
using destination_type = strf::basic_string_maker<CharT, Traits, Allocator>;
using sized_destination_type = strf::basic_sized_string_maker<CharT, Traits, Allocator>;
strf::tag<void> create() const noexcept
{
return strf::tag<void>{};
}
std::size_t create(std::size_t size) const noexcept
{
return size;
}
};
}
template <typename CharT, typename Traits, typename Allocator>
inline auto append(std::basic_string<CharT, Traits, Allocator>& str)
-> strf::destination_no_reserve
< strf::detail::basic_string_appender_creator<CharT, Traits, Allocator> >
{
return strf::destination_no_reserve
< strf::detail::basic_string_appender_creator<CharT, Traits, Allocator> >
{ str };
}
template <typename CharT, typename Traits, typename Allocator>
inline auto assign(std::basic_string<CharT, Traits, Allocator>& str)
-> strf::destination_no_reserve
< strf::detail::basic_string_appender_creator<CharT, Traits, Allocator> >
{
str.clear();
return append(str);
}
#if defined(STRF_HAS_VARIABLE_TEMPLATES)
template< typename CharT
, typename Traits = std::char_traits<CharT>
, typename Allocator = std::allocator<CharT> >
constexpr strf::destination_no_reserve
< strf::detail::basic_string_maker_creator<CharT, Traits, Allocator> >
to_basic_string{};
#endif // defined(STRF_HAS_VARIABLE_TEMPLATES)
#if defined(__cpp_char8_t)
constexpr strf::destination_no_reserve
< strf::detail::basic_string_maker_creator<char8_t> >
to_u8string{};
#endif
constexpr strf::destination_no_reserve
< strf::detail::basic_string_maker_creator<char> >
to_string{};
constexpr strf::destination_no_reserve
< strf::detail::basic_string_maker_creator<char16_t> >
to_u16string{};
constexpr strf::destination_no_reserve
< strf::detail::basic_string_maker_creator<char32_t> >
to_u32string{};
constexpr strf::destination_no_reserve
< strf::detail::basic_string_maker_creator<wchar_t> >
to_wstring{};
} // namespace strf
#endif // STRF_DETAIL_OUTPUT_TYPES_STD_STRING_HPP
| 29.199454
| 98
| 0.669879
|
robhz786
|
57c966f2fc476239a6d8772ac677792003b36486
| 735
|
cpp
|
C++
|
src/reference.cpp
|
cscheid/guitar
|
b6ae866f3724822e151d6e9ecedfabcf13860c48
|
[
"Apache-2.0"
] | 2
|
2015-01-08T00:08:48.000Z
|
2018-10-24T22:15:27.000Z
|
src/reference.cpp
|
cscheid/guitar
|
b6ae866f3724822e151d6e9ecedfabcf13860c48
|
[
"Apache-2.0"
] | null | null | null |
src/reference.cpp
|
cscheid/guitar
|
b6ae866f3724822e151d6e9ecedfabcf13860c48
|
[
"Apache-2.0"
] | 1
|
2018-10-24T22:15:28.000Z
|
2018-10-24T22:15:28.000Z
|
#include "reference.h"
#include "entry_points.h"
using namespace Rcpp;
GitReference::GitReference(git_reference *_ref)
{
ref = boost::shared_ptr<git_reference>(_ref, git_reference_free);
}
bool GitReference::has_log()
{
return git_reference_has_log(ref.get());
}
SEXP GitReference::peel(unsigned int otype)
{
BEGIN_RCPP
git_object *result;
int err = git_reference_peel(&result, ref.get(), (git_otype) otype);
if (err)
throw Rcpp::exception("git_reference_peel failed");
return object_to_sexp(result);
END_RCPP
}
RCPP_MODULE(guitar_reference) {
class_<GitReference>("Reference")
.method("has_log", &GitReference::has_log)
.method("peel", &GitReference::peel)
;
}
| 22.272727
| 72
| 0.693878
|
cscheid
|
57ce35b77d04cbea2b6b75b272998f6a8a49f8e9
| 1,895
|
cpp
|
C++
|
Includes/font.cpp
|
dracc/NevolutionX
|
a1a9495282cc5516ff17521cd57dc46dfa52b85d
|
[
"MIT"
] | 72
|
2019-03-28T19:23:52.000Z
|
2022-03-12T05:58:19.000Z
|
Includes/font.cpp
|
dracc/NevolutionX
|
a1a9495282cc5516ff17521cd57dc46dfa52b85d
|
[
"MIT"
] | 94
|
2019-04-30T06:59:43.000Z
|
2022-02-20T23:06:25.000Z
|
Includes/font.cpp
|
dracc/NevolutionX
|
a1a9495282cc5516ff17521cd57dc46dfa52b85d
|
[
"MIT"
] | 26
|
2019-04-27T14:11:11.000Z
|
2022-03-27T03:18:47.000Z
|
#include "font.h"
#include <cassert>
#include "3rdparty/SDL_FontCache/SDL_FontCache.h"
#include "infoLog.h"
Font::Font(Renderer& renderer, const char* path) : renderer(renderer) {
fcFont = FC_CreateFont();
assert(fcFont);
bool load_success = FC_LoadFont(fcFont, renderer.getRenderer(), path, 20,
FC_MakeColor(250, 250, 250, 255), TTF_STYLE_NORMAL);
assert(load_success);
}
Font::~Font() {
FC_FreeFont(fcFont);
}
std::pair<float, float> Font::draw(const std::string& str,
std::pair<float, float> coordinates) {
FC_Draw(fcFont, renderer.getRenderer(), std::get<0>(coordinates),
std::get<1>(coordinates), "%s", str.c_str());
FC_Rect rect = FC_GetBounds(fcFont, std::get<0>(coordinates), std::get<1>(coordinates),
FC_ALIGN_LEFT, FC_MakeScale(1.0f, 1.0f), "%s", str.c_str());
return std::pair<float, float>(rect.w, rect.h);
}
std::pair<float, float> Font::drawColumn(const std::string& str,
std::pair<float, float> coordinates,
float maxWidth) {
FC_Rect rect = FC_DrawColumn(fcFont, renderer.getRenderer(), std::get<0>(coordinates),
std::get<1>(coordinates), static_cast<Uint16>(maxWidth),
"%s", str.c_str());
return std::pair<float, float>{ rect.w, rect.h };
}
float Font::getFontHeight() const {
return FC_GetLineHeight(fcFont);
}
float Font::getColumnHeight(const std::string& str, float maxWidth) const {
return FC_GetColumnHeight(fcFont, static_cast<Uint16>(maxWidth), "%s", str.c_str());
}
float Font::getTextHeight(const std::string& str) const {
return FC_GetHeight(fcFont, "%s", str.c_str());
}
float Font::getTextWidth(const std::string& str) const {
return FC_GetWidth(fcFont, "%s", str.c_str());
}
| 36.442308
| 90
| 0.614248
|
dracc
|
57ce4fb7cb3d20c09ecb466270ed13f31ea84b47
| 6,046
|
cpp
|
C++
|
src/HPMeshGen2/main.cpp
|
DanielZint/hpmeshgen
|
cdfb9163ed92523fcf41a127c8173097e935c0a3
|
[
"MIT"
] | 2
|
2022-02-09T08:51:16.000Z
|
2022-02-09T08:51:27.000Z
|
src/HPMeshGen2/main.cpp
|
DanielZint/hpmeshgen
|
cdfb9163ed92523fcf41a127c8173097e935c0a3
|
[
"MIT"
] | null | null | null |
src/HPMeshGen2/main.cpp
|
DanielZint/hpmeshgen
|
cdfb9163ed92523fcf41a127c8173097e935c0a3
|
[
"MIT"
] | null | null | null |
#include <experimental/filesystem>
// glog
#include <glog/logging.h>
#include "Config.h"
#include "BsgGenerator.h"
// Mesh Function
#include "MeshFunctions.h"
#include "Simplificator.h"
#include "DMO/Solver.h"
#include "GridEvaluation/eval.h"
#include "baseDirectory.h"
#include "Simplify.h"
#include "ScalarField/ScalarField.h"
#include "Stopwatch/Stopwatch.h"
namespace fs = std::experimental::filesystem;
void generateBsg( const Config& config ) {
BsgGenerator bsgGenerator( config );
if ( config.reductionOutput() ) bsgGenerator.simplificator().simplificationOutput( config.outputFolder() );
bsgGenerator.generate();
//MeshFunctions::printMesh( config.outputFolder() / "fragmentMesh.off", bsgGenerator.fragmentMesh() );
//MeshFunctions::printMesh( config.outputFolder() / "fragmentMeshRefined.off", bsgGenerator.bsg().quadMesh );
//MeshFunctions::printMesh( config.outputFolder() / "fragmentMeshRefinedTri.off", bsgGenerator.bsg().triMesh );
if( config.convexHullDecimation() ) {
bsgGenerator.adaptElementsToContour();
}
BlockStructuredGrid& bsg = bsgGenerator.bsg();
LOG( INFO ) << "# quads after refinement: " << bsg.quadMesh.n_faces() << std::endl;
if ( config.sizegridOutput() ) {
bsgGenerator.inputMesh().sizeField().toVTK( config.outputFolder() / "sizegrid.vtk", false );
bsgGenerator.inputMesh().depthField().toVTK( config.outputFolder() / "depthgrid.vtk", false );
}
if ( config.blockMeshOutput() ) {
MeshFunctions::printMesh( config.outputFolder() / "simplifiedMesh.off", bsgGenerator.simplifiedMesh() );
MeshFunctions::printMesh( config.outputFolder() / "fragmentMesh.off", bsgGenerator.fragmentMesh() );
MeshFunctions::printMesh( config.outputFolder() / "fragmentMeshRefined.off", bsgGenerator.bsg().quadMesh );
}
//bsgGenerator.optimizeBsg();
// evaluation
MeshFunctions::printMesh( config.outputFolder() / "fineMeshFinal.off", bsg.triMesh );
MeshFunctions::displayQuality( bsg.triMesh, 10 );
// apply depth to BSG
//bsgGenerator.inputMesh().applyDepth( bsg.triMesh );
//bsgGenerator.inputMesh().applyDepth( bsg.quadMesh );
///////////////////////
// write bsg to file //
// rescale mesh
//MeshFunctions::rescaleMesh(*bsg.fineMesh, 1000, 1000, 1000);
//bsg.patch_segmentation(nBlocks);
//bsg.write_bsg(config.outputFolder(), "BSG_east_b" + std::to_string(nBlocks) + "_f" + std::to_string(bsg.n_patches()));
//bsg.write_bsg( config.outputFolder(), "BSG_east_b" + std::to_string(nBlocks) + "_f" + std::to_string(bsg.n_patches()) + "_scaled");
//if (config.meshFile().extension() == ".14") {
// bsg.exportMeshAdcirc( config.outputFolder(), config.meshFile().stem().string() + "_" + std::to_string(config.nRefinementSteps()) + ".14");
//}
std::string bsgName = std::string( "BSG_" ) + config.meshFile().stem().string() + "_b" + std::to_string( config.nBlocks() ) + "_f" + std::to_string( bsg.nFragments() );
if( config.convexHullDecimation() ) {
bsgName += "_m";
}
fs::path bsgFolder = config.outputFolder() / bsgName;
fs::create_directories( bsgFolder );
if( !config.convexHullDecimation() ) {
const auto& sf = bsgGenerator.inputMesh().sizeField();
DMO::UniformGrid grid_d;
grid_d.n = { (int)sf.Nx(), (int)sf.Ny() };
grid_d.h = { sf.hx(), sf.hy() };
grid_d.aabbMin = { sf.aabb().xMin, sf.aabb().yMin };
grid_d.aabbMax = { sf.aabb().xMax, sf.aabb().yMax };
thrust::host_vector<float> sgVals;
sgVals.resize( grid_d.n.x * grid_d.n.y );
for( int i = 0; i < grid_d.n.x * grid_d.n.y; ++i ) {
sgVals[i] = sf( i );
}
thrust::device_vector<float> sgVals_d = sgVals;
grid_d.vals = sgVals_d.data().get();
DMO::Metrics::MeanRatioTriangle metricMeanRatio;
DMO::Metrics::DensityTriangle metricDensity( grid_d );
DMO::Metrics::DensityWithMeanRatioTriangle metricInner( metricMeanRatio, metricDensity );
DMO::DmoMesh dmoMeshInner = DMO::DmoMesh::create<DMO::Set::Inner>( bsg.triMesh );
DMO::Solver dmo( bsg.triMesh, &metricInner, &dmoMeshInner );
dmo.solve( 100 );
DMO::Solver( bsg.triMesh, &metricMeanRatio, &dmoMeshInner ).solve( 1 );
bsg.copy_positions_tri2quad();
}
// evaluation
MeshFunctions::printMesh( bsgFolder / ( bsgName + "_" + std::to_string( bsg.nGridNodes() ) + ".off" ), bsg.triMesh );
MeshFunctions::printMeshCartesian( bsgFolder / ( bsgName + "_" + std::to_string( bsg.nGridNodes() ) + "_cart.off" ), bsg.triMesh, bsgGenerator.inputMesh() );
MeshFunctions::displayQuality( bsg.triMesh, 10 );
// apply depth to BSG
bsgGenerator.inputMesh().applyDepth( bsg.triMesh );
bsgGenerator.inputMesh().applyDepth( bsg.quadMesh );
GridEvaluation::eval( bsg.triMesh, bsgGenerator.inputMesh(), bsgFolder / ( bsgName + "_" + std::to_string( bsg.nGridNodes() ) + ".vtk" ) );
MeshFunctions::printMesh( bsgFolder / "triBlocks.off", bsgGenerator.simplifiedMesh() );
MeshFunctions::printMeshCartesian( bsgFolder / "triBlocks_cart.off", bsgGenerator.simplifiedMesh(), bsgGenerator.inputMesh() );
bsg.patch_segmentation( config.nBlocks() );
bsg.write_bsg( bsgFolder, bsgName, config.convexHullDecimation() );
// only write BSG and fort files if input is a fort.14 file
if( config.meshFile().extension() == ".14" ) {
bsg.exportMeshAdcirc( bsgFolder, config.meshFile().stem().string() + "_" + std::to_string( bsg.nGridNodes() ) + ".14", bsgGenerator.inputMesh() );
}
//bsg.print_svg( config.outputFolder().string() + "bsgPrint.svg" );
}
int main( int argc, char* argv[] )
{
google::InitGoogleLogging( argv[0] );
//FLAGS_timestamp_in_logfile_name = false;
FLAGS_logtostderr = true;
FLAGS_colorlogtostderr = true;
fs::current_path( BASE_DIRECTORY );
// load config file
const Config config( "HPMeshGenParameter.txt" );
// set logging flags
//FLAGS_logtostderr = false;
//FLAGS_alsologtostderr = true;
//FLAGS_log_dir = config.outputFolder().string();
// print config to log
config.log();
// do it!
Stopwatch sw;
sw.start();
generateBsg( config );
sw.stop();
LOG( WARNING ) << "Runtime: " << sw.runtimeStr<Stopwatch::Milliseconds>();
LOG( INFO ) << "HPMeshGen2 finished";
}
| 36.421687
| 169
| 0.700298
|
DanielZint
|
57ce95504d7b142d41b21bd26ed2768dde5ff27c
| 712
|
hpp
|
C++
|
jobin/atomic.hpp
|
Marcos30004347/jobin
|
40eec7bf9579002426320253eae6eaaea6b50d10
|
[
"Apache-2.0"
] | 2
|
2020-09-30T05:12:09.000Z
|
2020-10-12T23:40:32.000Z
|
jobin/atomic.hpp
|
Marcos30004347/Jobin
|
40eec7bf9579002426320253eae6eaaea6b50d10
|
[
"Apache-2.0"
] | null | null | null |
jobin/atomic.hpp
|
Marcos30004347/Jobin
|
40eec7bf9579002426320253eae6eaaea6b50d10
|
[
"Apache-2.0"
] | null | null | null |
#ifndef JOBIN_ATOMIC_H
#define JOBIN_ATOMIC_H
#include <atomic>
template <typename T>
class atomic {
private:
std::atomic<T> _atomic;
public:
atomic(T initial): _atomic(initial) {}
atomic() {}
~atomic() {}
bool compare_exchange_strong(T current_value, T new_value){
return _atomic.compare_exchange_strong(current_value, new_value);
}
bool compare_exchange_weak(T current_value, T new_value) {
return _atomic.compare_exchange_weak(current_value, new_value);
}
T exchange(T value) {
return _atomic.exchange(value);
}
T load() {
return _atomic.load();
}
void store(T value) {
_atomic.store(value);
}
};
#endif
| 17.8
| 73
| 0.65309
|
Marcos30004347
|
57d3f68de943e8499169642d2af602d257560edb
| 2,589
|
cpp
|
C++
|
source/aoc/src/aoc2018/d08/solver.cpp
|
daduraro/aoc
|
9029de9d6e703fa1b20a466c1286b74ce9a7b23c
|
[
"BSD-2-Clause"
] | 1
|
2019-12-06T11:29:14.000Z
|
2019-12-06T11:29:14.000Z
|
source/aoc/src/aoc2018/d08/solver.cpp
|
daduraro/aoc
|
9029de9d6e703fa1b20a466c1286b74ce9a7b23c
|
[
"BSD-2-Clause"
] | null | null | null |
source/aoc/src/aoc2018/d08/solver.cpp
|
daduraro/aoc
|
9029de9d6e703fa1b20a466c1286b74ce9a7b23c
|
[
"BSD-2-Clause"
] | null | null | null |
#include "aoc/solver.h"
#include <memory>
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <limits>
#include <type_traits>
#include <cassert>
#include <ddr/data/tree.h>
namespace {
using namespace aoc;
constexpr std::size_t YEAR = 2018;
constexpr std::size_t DAY = 8;
using node_t = ddr::data::node_t<std::vector<std::intmax_t>>;
using input_t = node_t;
input_t parse_input(std::istream& is)
{
input_t root;
auto read_tree = [&is](node_t& node) -> void {
auto impl = [&is](const auto& self, node_t& node) -> void {
std::size_t num_children, num_data;
if (!(is >> num_children >> num_data)) throw parse_exception{};
node.children.resize(num_children);
for (node_t& child : node.children) self(self, child);
std::copy_n(std::istream_iterator<std::intmax_t>(is), num_data, std::back_inserter(*node));
if (is.fail()) throw parse_exception{};
};
impl(impl, node);
};
read_tree(root);
return root;
}
std::size_t resultA(const input_t& in) noexcept
{
std::vector<const node_t*> nodes;
nodes.push_back(&in);
std::intmax_t accum = 0;
while (!nodes.empty()) {
const node_t& node = *nodes.back();
nodes.pop_back();
accum += std::reduce(node->begin(), node->end());
for (const node_t& child : node.children) nodes.push_back(&child);
}
return std::size_t(accum);
}
std::size_t resultB(const node_t& in) noexcept
{
if (in.children.empty()) {
auto sum = std::reduce(in->begin(), in->end());
return std::size_t(sum);
} else {
std::vector<std::optional<std::size_t>> cached_values;
cached_values.resize(in.children.size());
std::size_t accum = 0;
for (auto child : *in)
{
if (child == 0 || std::size_t(child) > in.children.size()) continue; // invalid child
auto& value = cached_values[child-1];
if (!value) value = resultB(in.children[child - 1]);
accum += *value;
}
return accum;
}
}
}
namespace aoc {
template<>
auto create_solver<YEAR, DAY>() noexcept -> std::unique_ptr<solver_interface> {
return create_solver<YEAR, DAY>(parse_input, resultA, resultB);
}
}
| 30.458824
| 107
| 0.555041
|
daduraro
|
57d47d9749c836f8aa60d9357a9d746672aa9e99
| 11,710
|
cpp
|
C++
|
src/kerberos/Kerberos.cpp
|
wollars/kerberos-machinery
|
95c648133a7229b94b78af74283b3a8a1574922b
|
[
"Unlicense"
] | 1
|
2018-06-12T21:48:53.000Z
|
2018-06-12T21:48:53.000Z
|
src/kerberos/Kerberos.cpp
|
wollars/kerberos-machinery
|
95c648133a7229b94b78af74283b3a8a1574922b
|
[
"Unlicense"
] | null | null | null |
src/kerberos/Kerberos.cpp
|
wollars/kerberos-machinery
|
95c648133a7229b94b78af74283b3a8a1574922b
|
[
"Unlicense"
] | null | null | null |
#include "Kerberos.h"
namespace kerberos
{
void Kerberos::bootstrap(StringMap & parameters)
{
// --------------------------------
// Set parameters from command-line
setParameters(parameters);
// ---------------------
// Initialize kerberos
std::string configuration = (helper::getValueByKey(parameters, "config")) ?: CONFIGURATION_PATH;
configure(configuration);
// ------------------
// Open the io thread
startIOThread();
// ------------------------------------------
// Guard is a filewatcher, that looks if the
// configuration has been changed. On change
// guard will re-configure all instances.
std::string directory = configuration.substr(0, configuration.rfind('/'));
std::string file = configuration.substr(configuration.rfind('/')+1);
guard = new FW::Guard();
guard->listenTo(directory, file);
guard->onChange(&Kerberos::reconfigure);
guard->start();
// --------------------------
// This should be forever...
while(true)
{
// -------------------
// Initialize data
JSON data;
data.SetObject();
// ------------------------------------
// Guard look if the configuration has
// been changed...
guard->look();
// --------------------------------------------
// If machinery is NOT allowed to do detection
// continue iteration
if(!machinery->allowed(m_images))
{
BINFO << "Machinery on hold, conditions failed.";
continue;
}
// --------------------
// Clean image to save
Image cleanImage = *m_images[m_images.size()-1];
// --------------
// Processing..
if(machinery->detect(m_images, data))
{
// ---------------------------
// If something is detected...
pthread_mutex_lock(&m_ioLock);
Detection detection(toJSON(data), cleanImage);
m_detections.push_back(detection);
pthread_mutex_unlock(&m_ioLock);
}
// -------------
// Shift images
m_images = capture->shiftImage();
}
}
std::string Kerberos::toJSON(JSON & data)
{
JSON::AllocatorType& allocator = data.GetAllocator();
JSONValue timestamp;
timestamp.SetString(kerberos::helper::getTimestamp().c_str(), allocator);
data.AddMember("timestamp", timestamp, allocator);
std::string micro = kerberos::helper::getMicroseconds();
micro = kerberos::helper::to_string((int)micro.length()) + "-" + micro;
JSONValue microseconds;
microseconds.SetString(micro.c_str(), allocator);
data.AddMember("microseconds", microseconds, allocator);
data.AddMember("token", rand()%1000, allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
data.Accept(writer);
return buffer.GetString();
}
void Kerberos::configure(const std::string & configuration)
{
// ---------------------------
// Get settings from XML file
LINFO << "Reading configuration file: " << configuration;
StringMap settings = kerberos::helper::getSettingsFromXML(configuration);
// -------------------------------
// Override config with parameters
StringMap parameters = getParameters();
StringMap::iterator begin = parameters.begin();
StringMap::iterator end = parameters.end();
for(begin; begin != end; begin++)
{
settings[begin->first] = begin->second;
}
LINFO << helper::printStringMap("Final configuration:", settings);
// -------------------------------------------
// Check if we need to disable verbose logging
easyloggingpp::Logger * logger = easyloggingpp::Loggers::getLogger("business");
easyloggingpp::Configurations & config = logger->configurations();
if(settings.at("logging") == "false")
{
LINFO << "Logging is set to info";
config.set(easyloggingpp::Level::Info, easyloggingpp::ConfigurationType::Enabled, "false");
}
else
{
LINFO << "Logging is set to verbose";
config.set(easyloggingpp::Level::Info, easyloggingpp::ConfigurationType::Enabled, "true");
}
logger->reconfigure();
// -----------------
// Configure cloud
configureCloud(settings);
// ------------------
// Configure capture
configureCapture(settings);
// --------------------
// Initialize machinery
if(machinery != 0) delete machinery;
machinery = new Machinery();
machinery->setCapture(capture);
machinery->setup(settings);
// -------------------
// Take first images
for(ImageVector::iterator it = m_images.begin(); it != m_images.end(); it++)
{
delete *it;
}
m_images.clear();
m_images = capture->takeImages(3);
machinery->initialize(m_images);
}
// ----------------------------------
// Configure capture device + stream
void Kerberos::configureCapture(StringMap & settings)
{
// -----------------------
// Stop stream and capture
if(stream != 0)
{
LINFO << "Stopping streaming";
stopStreamThread();
delete stream;
stream = 0;
}
if(capture != 0)
{
LINFO << "Stopping capture device";
if(capture->isOpened())
{
machinery->disableCapture();
capture->stopGrabThread();
capture->close();
}
delete capture;
capture = 0;
}
// ---------------------------
// Initialize capture device
LINFO << "Starting capture device: " + settings.at("capture");
capture = Factory<Capture>::getInstance()->create(settings.at("capture"));
capture->setup(settings);
capture->startGrabThread();
// ------------------
// Initialize stream
stream = new Stream();
stream->configureStream(settings);
startStreamThread();
}
// ----------------------------------
// Configure cloud device + thread
void Kerberos::configureCloud(StringMap & settings)
{
// ---------------------------
// Initialize cloud service
if(cloud != 0)
{
LINFO << "Stopping cloud service";
cloud->stopUploadThread();
cloud->stopPollThread();
delete cloud;
}
LINFO << "Starting cloud service: " + settings.at("cloud");
cloud = Factory<Cloud>::getInstance()->create(settings.at("cloud"));
cloud->setup(settings);
}
// --------------------------------------------
// Function ran in a thread, which continuously
// stream MJPEG's.
void * streamContinuously(void * self)
{
Kerberos * kerberos = (Kerberos *) self;
while(kerberos->stream->isOpened())
{
try
{
kerberos->stream->connect();
if(kerberos->capture->isOpened())
{
Image image = kerberos->capture->retrieve();
if(kerberos->capture->m_angle != 0)
{
image.rotate(kerberos->capture->m_angle);
}
kerberos->stream->write(image);
}
usleep(kerberos->stream->wait * 1000 * 1000); // sleep x microsec.
}
catch(cv::Exception & ex){}
}
}
void Kerberos::startStreamThread()
{
// ------------------------------------------------
// Start a new thread that streams MJPEG's continuously.
if(stream != 0)
{
//if stream object just exists try to open configured stream port
stream->open();
}
pthread_create(&m_streamThread, NULL, streamContinuously, this);
}
void Kerberos::stopStreamThread()
{
// ----------------------------------
// Cancel the existing stream thread,
pthread_cancel(m_streamThread);
pthread_join(m_streamThread, NULL);
}
// -------------------------------------------
// Function ran in a thread, which continuously
// checks if some detections occurred and
// execute the IO devices if so.
void * checkDetectionsContinuously(void * self)
{
Kerberos * kerberos = (Kerberos *) self;
int previousCount = 0;
int currentCount = 0;
int timesEqual = 0;
while(true)
{
try
{
previousCount = currentCount;
currentCount = kerberos->m_detections.size();
if(previousCount == currentCount)
{
timesEqual++;
}
else if(timesEqual > 0)
{
timesEqual--;
}
// If no new detections are found, we will run the IO devices (or max 30 images in memory)
if((currentCount > 0 && timesEqual > 4) || currentCount >= 30)
{
BINFO << "Executing IO devices for " + helper::to_string(currentCount) + " detection(s)";
for (int i = 0; i < currentCount; i++)
{
Detection detection = kerberos->m_detections[0];
JSON data;
data.Parse(detection.t.c_str());
pthread_mutex_lock(&kerberos->m_ioLock);
if(kerberos->machinery->save(detection.k, data))
{
kerberos->m_detections.erase(kerberos->m_detections.begin());
}
else
{
LERROR << "IO: can't execute";
}
pthread_mutex_unlock(&kerberos->m_ioLock);
usleep(500*1000);
}
timesEqual = 0;
}
usleep(500*1000);
}
catch(cv::Exception & ex)
{
pthread_mutex_unlock(&kerberos->m_ioLock);
}
}
}
void Kerberos::startIOThread()
{
// ------------------------------------------------
// Start a new thread that cheks for detections
pthread_create(&m_ioThread, NULL, checkDetectionsContinuously, this);
}
void Kerberos::stopIOThread()
{
// ----------------------------------
// Cancel the existing io thread,
pthread_cancel(m_ioThread);
pthread_join(m_ioThread, NULL);
}
}
| 30.336788
| 110
| 0.453288
|
wollars
|
57d851ae0017539de24973dbefb1403309175015
| 3,234
|
hh
|
C++
|
surfaces/CenteredSphere.hh
|
celeritas-project/orange-port
|
9aa2d36984a24a02ed6d14688a889d4266f7b1af
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
surfaces/CenteredSphere.hh
|
celeritas-project/orange-port
|
9aa2d36984a24a02ed6d14688a889d4266f7b1af
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
surfaces/CenteredSphere.hh
|
celeritas-project/orange-port
|
9aa2d36984a24a02ed6d14688a889d4266f7b1af
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
//---------------------------------*-C++-*-----------------------------------//
/*!
* \file surfaces/CenteredSphere.hh
* \brief CenteredCenteredSphere class declaration
* \note Copyright (c) 2020 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
#pragma once
#include "Definitions.hh"
namespace celeritas
{
class Sphere;
//---------------------------------------------------------------------------//
/*!
* CenteredSphere at an arbitrary spatial point.
*/
class CenteredSphere
{
public:
//// ATTRIBUTES ////
//! Get the surface type of this surface.
static constexpr SurfaceType surface_type() { return SurfaceType::so; }
//! Number of values associated with data(), and pointer construction
static constexpr size_type size() { return 1; }
//! Number of possible intersections
static constexpr size_type num_intersections() { return 2; }
// Whether the given sphere is at the origin
static bool can_simplify(const Sphere& sq);
public:
//// CONSTRUCTION ////
// Construct with radius
explicit CenteredSphere(real_type radius);
// Inline construction from flattened coefficients (copying data)
explicit inline CenteredSphere(const real_type* coeff);
// Construct from a degenerate SQ
explicit CenteredSphere(const Sphere& sq);
//! Access the data for this object, for inlining into a surface
const real_type* data() const { return &radius_sq_; }
//! Access the type-deleted surface data
GenericSurfaceRef view() const { return GenericSurfaceRef::from_surface(*this); }
//// TRANSFORMATION ////
// Return a new sphere translated by some vector
Sphere translated(const Transform& t) const;
//! Return a sphere transformed by a rotate/translate
Sphere transformed(const Transform& t) const;
// Clip a bounding box to a shape with this sense
void clip(Sense sense, BoundingBox& bbox) const;
//// CALCULATION ////
// Determine the sense of the position relative to this surface (init)
inline SignedSense calc_sense(const Real3& x) const;
// Determine distance to intersection
inline void calc_intersections(const Real3& pos,
const Real3& dir,
bool on_surface,
real_type* dist_iter) const;
// Calculate outward normal at a position
inline Real3 calc_normal(const Real3& pos) const;
//// ACCESSORS ////
//! Get the square of the radius
real_type radius_sq() const { return radius_sq_; }
private:
//// DATA ////
// Square of the radius
real_type radius_sq_;
};
// Print to a stream
std::ostream& operator<<(std::ostream&, const CenteredSphere&);
//---------------------------------------------------------------------------//
} // namespace celeritas
//---------------------------------------------------------------------------//
// INLINE DEFINITIONS
//---------------------------------------------------------------------------//
#include "CenteredSphere.i.hh"
//---------------------------------------------------------------------------//
| 31.096154
| 85
| 0.552876
|
celeritas-project
|
57dcecfb55e531f906d765c095cf588fe4d9794e
| 9,684
|
cpp
|
C++
|
Libraries/Utility/JSON.cpp
|
xycsoscyx/gekengine
|
cb9c933c6646169c0af9c7e49be444ff6f97835d
|
[
"MIT"
] | 1
|
2019-04-22T00:10:49.000Z
|
2019-04-22T00:10:49.000Z
|
Libraries/Utility/JSON.cpp
|
xycsoscyx/gekengine
|
cb9c933c6646169c0af9c7e49be444ff6f97835d
|
[
"MIT"
] | null | null | null |
Libraries/Utility/JSON.cpp
|
xycsoscyx/gekengine
|
cb9c933c6646169c0af9c7e49be444ff6f97835d
|
[
"MIT"
] | 2
|
2017-10-16T15:40:55.000Z
|
2019-04-22T00:10:50.000Z
|
#include <jsoncons/json.hpp>
#include "GEK/Utility/JSON.hpp"
#include "GEK/Utility/FileSystem.hpp"
#include "GEK/Utility/Context.hpp"
namespace Gek
{
const JSON::Array JSON::EmptyArray = JSON::Array();
const JSON::Object JSON::EmptyObject = JSON::Object();
const JSON JSON::Empty = JSON();
JSON GetFromJSON(jsoncons::json const &object)
{
if (object.empty() || object.is_null())
{
return JSON::Empty;
}
JSON value;
switch (object.kind())
{
case jsoncons::value_kind::short_string_value:
case jsoncons::value_kind::long_string_value:
case jsoncons::value_kind::byte_string_value:
value = object.as_string();
break;
case jsoncons::value_kind::bool_value:
value = object.as<bool>();
break;
case jsoncons::value_kind::double_value:
value = object.as<float>();
break;
case jsoncons::value_kind::int64_value:
value = object.as<int64_t>();
break;
case jsoncons::value_kind::uint64_value:
value = object.as<uint64_t>();
break;
case jsoncons::value_kind::array_value:
value = JSON::Array(object.size());
for (size_t index = 0; index < object.size(); ++index)
{
value[index] = GetFromJSON(object[index]);
}
break;
case jsoncons::value_kind::object_value:
value = JSON::Object();
for (auto &pair : object.object_range())
{
value[pair.key()] = GetFromJSON(pair.value());
}
break;
};
return value;
}
void JSON::load(FileSystem::Path const &filePath)
{
if (filePath.isFile())
{
std::string object(FileSystem::Load(filePath, String::Empty));
std::istringstream dataStream(object);
jsoncons::json_decoder<jsoncons::json> decoder;
jsoncons::json_reader reader(dataStream, decoder);
std::error_code errorCode;
reader.read(errorCode);
if (errorCode)
{
LockedWrite{ std::cerr } << errorCode.message() << " at line " << reader.line() << ", and column " << reader.column() << ", in " << filePath.getString();
}
else
{
*this = GetFromJSON(decoder.get_result());
}
}
}
void JSON::save(FileSystem::Path const &filePath)
{
FileSystem::Save(filePath, getString());
}
std::string escapeJsonString(const std::string& input)
{
std::ostringstream ss;
for (auto iter = input.cbegin(); iter != input.cend(); iter++)
{
//C++98/03:
//for (std::string::const_iterator iter = input.begin(); iter != input.end(); iter++) {
switch (*iter)
{
case '\\': ss << "\\\\"; break;
case '"': ss << "\\\""; break;
case '/': ss << "\\/"; break;
case '\b': ss << "\\b"; break;
case '\f': ss << "\\f"; break;
case '\n': ss << "\\n"; break;
case '\r': ss << "\\r"; break;
case '\t': ss << "\\t"; break;
default: ss << *iter; break;
};
}
return ss.str();
}
std::string JSON::getString(void) const
{
return visit(
[](std::string const &visitedData)
{
return String::Format("\"{}\"", escapeJsonString(visitedData));
},
[](JSON::Array const &visitedData)
{
std::stringstream stream;
stream << "[ ";
bool writtenPrevious = false;
for (auto &index : visitedData)
{
if (writtenPrevious)
{
stream << ", ";
}
stream << index.getString();
writtenPrevious = true;
}
stream << (std::empty(visitedData) ? "]" : " ]");
return stream.str();
},
[](JSON::Object const &visitedData)
{
std::stringstream stream;
stream << "{ ";
bool writtenPrevious = false;
for (auto &index : visitedData)
{
if (writtenPrevious)
{
stream << ", ";
}
stream << "\"" << index.first << "\": ";
stream << index.second.getString();
writtenPrevious = true;
}
stream << (std::empty(visitedData) ? "}" : " }");
return stream.str();
},
[](auto && visitedData)
{
return String::Format("{}", visitedData);
});
}
JSON const &JSON::getIndex(size_t index) const
{
if (auto value = std::get_if<Array>(&data))
{
return value->at(index);
}
else
{
return Empty;
}
}
JSON const &JSON::getMember(std::string_view name) const
{
if (auto value = std::get_if<Object>(&data))
{
auto search = value->find(name.data());
if (search == std::end(*value))
{
return Empty;
}
else
{
return search->second;
}
}
else
{
return Empty;
}
}
JSON &JSON::operator [] (size_t index)
{
if (!isType<Array>())
{
data = EmptyArray;
}
return std::get<Array>(data)[index];
}
JSON &JSON::operator [] (std::string_view name)
{
if (!isType<Object>())
{
data = EmptyObject;
}
return std::get<Object>(data)[name.data()];
}
Math::Float2 JSON::evaluate(ShuntingYard &shuntingYard, Math::Float2 const &defaultValue) const
{
auto data = asType(EmptyArray);
switch (data.size())
{
case 1:
return Math::Float2(data[0].evaluate(shuntingYard, 0.0f));
default:
return Math::Float2(
data[0].evaluate(shuntingYard, defaultValue.x),
data[1].evaluate(shuntingYard, defaultValue.y));
};
}
Math::Float3 JSON::evaluate(ShuntingYard &shuntingYard, Math::Float3 const &defaultValue) const
{
auto data = asType(EmptyArray);
switch (data.size())
{
case 1:
return Math::Float3(data[0].evaluate(shuntingYard, 0.0f));
case 3:
return Math::Float3(
data[0].evaluate(shuntingYard, defaultValue.x),
data[1].evaluate(shuntingYard, defaultValue.y),
data[2].evaluate(shuntingYard, defaultValue.z));
default:
return defaultValue;
};
}
Math::Float4 JSON::evaluate(ShuntingYard &shuntingYard, Math::Float4 const &defaultValue) const
{
auto data = asType(EmptyArray);
switch (data.size())
{
case 1:
return Math::Float4(data[0].evaluate(shuntingYard, 0.0f));
case 3:
return Math::Float4(
data[0].evaluate(shuntingYard, defaultValue.x),
data[1].evaluate(shuntingYard, defaultValue.y),
data[2].evaluate(shuntingYard, defaultValue.z),
defaultValue.w);
case 4:
return Math::Float4(
data[0].evaluate(shuntingYard, defaultValue.x),
data[1].evaluate(shuntingYard, defaultValue.y),
data[2].evaluate(shuntingYard, defaultValue.z),
data[3].evaluate(shuntingYard, defaultValue.w));
default:
return defaultValue;
};
}
Math::Quaternion JSON::evaluate(ShuntingYard &shuntingYard, Math::Quaternion const &defaultValue) const
{
auto data = asType(EmptyArray);
switch (data.size())
{
case 3:
if (true)
{
float pitch = data[0].evaluate(shuntingYard, Math::Infinity);
float yaw = data[1].evaluate(shuntingYard, Math::Infinity);
float roll = data[2].evaluate(shuntingYard, Math::Infinity);
if (pitch != Math::Infinity && yaw != Math::Infinity && roll != Math::Infinity)
{
return Math::Quaternion::MakeEulerRotation(pitch, yaw, roll);
}
return defaultValue;
}
case 4:
return Math::Quaternion(
data[0].evaluate(shuntingYard, defaultValue.x),
data[1].evaluate(shuntingYard, defaultValue.y),
data[2].evaluate(shuntingYard, defaultValue.z),
data[3].evaluate(shuntingYard, defaultValue.w));
default:
return defaultValue;
};
}
std::string JSON::evaluate(ShuntingYard &shuntingYard, std::string const &defaultValue) const
{
return visit(
[](std::string const &visitedData)
{
return visitedData;
},
[defaultValue](Object const &visitedData)
{
return defaultValue;
},
[defaultValue](Array const &visitedData)
{
return defaultValue;
},
[defaultValue](auto const &visitedData)
{
return String::Format("{}", GetValueOrDefault(visitedData, defaultValue));
});
}
}; // namespace Gek
| 28.821429
| 169
| 0.491119
|
xycsoscyx
|
57e07c8bb6d9a6242cd4d2c8d2a11f9aed8cbe87
| 2,730
|
cpp
|
C++
|
week5/code/btree_tree_print.cpp
|
hj02/Vor2015
|
675641f12773229e242c6e0bde290bdd537bf830
|
[
"MIT"
] | null | null | null |
week5/code/btree_tree_print.cpp
|
hj02/Vor2015
|
675641f12773229e242c6e0bde290bdd537bf830
|
[
"MIT"
] | null | null | null |
week5/code/btree_tree_print.cpp
|
hj02/Vor2015
|
675641f12773229e242c6e0bde290bdd537bf830
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstdio>
using namespace std;
struct TreeNode
{
int data;
TreeNode* left;
TreeNode* right;
bool is_leaf();
};
bool TreeNode::is_leaf()
{
return (left == NULL && right == NULL);
}
typedef TreeNode* NodePtr;
NodePtr parse_tree()
{
char c;
cin >> c; // Read (
cin >> c; // Read next character
// If the next character is ), this is the empty tree
if(c == ')') {
return NULL;
}
// Return the "borrowed" character to the input stream
cin.putback(c);
int node_data;
cin >> node_data;
NodePtr node = new TreeNode;
node->data = node_data;
node->left = parse_tree();
node->right = parse_tree();
cin >> c; // Consume the trailing )
return node;
}
void print_infix(NodePtr tree)
{
if(tree == NULL) {
return;
}
print_infix(tree->left);
cout << tree->data << " ";
print_infix(tree->right);
}
void print_postfix(NodePtr tree)
{
if(tree == NULL) {
return;
}
print_infix(tree->left);
print_infix(tree->right);
cout << tree->data << " ";
}
void print_prefix(NodePtr tree)
{
if(tree == NULL) {
return;
}
cout << tree->data << " ";
print_infix(tree->left);
print_infix(tree->right);
}
const int INDENT_SIZE = 3;
void indent(int level)
{
for(int i = 0; i != level * INDENT_SIZE; i++) {
cout << " ";
}
}
void print_tree(NodePtr tree, int level = 0)
{
indent(level);
if(tree == NULL) {
cout << "()" << endl;
return;
}
cout << "(" << tree->data << endl;
print_tree(tree->left, level + 1);
print_tree(tree->right, level + 1);
indent(level);
cout << ")" << endl;
}
// Prints the end symbol of a lisp-style representation of a tree. If the tree
// is not a rightmost child, the end symbol is a newline character. Otherwise,
// there is no end symbol (i.e., it is the empty string).
void tree_end(bool right)
{
if(!right) {
cout << endl;
}
}
// Print tree lisp-style
void print_tree_lisp(NodePtr tree, int level = 0, bool right = false)
{
indent(level);
if(tree == NULL) {
cout << "()";
tree_end(right);
return;
}
// Print leaves as numbers inside brackets, but not
// with two empty children.
cout << "(" << tree->data;
if(tree->is_leaf()) {
cout << ")";
tree_end(right);
} else {
cout << endl;
print_tree_lisp(tree->left, level + 1, false);
print_tree_lisp(tree->right, level + 1, true);
cout << ")";
tree_end(right);
}
}
int main()
{
NodePtr tree = parse_tree();
print_tree_lisp(tree);
cout << endl;
return 0;
}
| 18.571429
| 78
| 0.558974
|
hj02
|
57e25bcc359aa95ba9adf31c0df0fca12ef8f594
| 8,760
|
cc
|
C++
|
src/vw/GPU/TexAlloc.cc
|
tkeemon/visionworkbench
|
df59fcb31191e1fc4fecfe1901963da1614a52b1
|
[
"NASA-1.3"
] | 1
|
2020-06-02T04:06:43.000Z
|
2020-06-02T04:06:43.000Z
|
src/vw/GPU/TexAlloc.cc
|
tkeemon/visionworkbench
|
df59fcb31191e1fc4fecfe1901963da1614a52b1
|
[
"NASA-1.3"
] | null | null | null |
src/vw/GPU/TexAlloc.cc
|
tkeemon/visionworkbench
|
df59fcb31191e1fc4fecfe1901963da1614a52b1
|
[
"NASA-1.3"
] | null | null | null |
// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/GPU/TexAlloc.h>
namespace vw { namespace GPU {
//############################################################
// TexAlloc: Class Variables
//############################################################
bool TexAlloc::isInit = false;
list<TexObj*> TexAlloc::texRecycleList;
int TexAlloc::allocatedCount = 0;
int TexAlloc::allocatedSize = 0;
bool TexAlloc::recylingEnabled = false;
std::map<pair<Tex_Format, Tex_Type>, pair<Tex_Format, Tex_Type> > TexAlloc::textureSubstitutesMap;
//#############################################################
// TexAlloc: Class Functions
//#############################################################
static char buffer[512];
TexObj*
TexAlloc::alloc(int w, int h, Tex_Format format, Tex_Type type) {
// check for init
if(!isInit)
initialize_texalloc();
// Attribute Substition
Tex_Format realFormat = format;
Tex_Type realType = type;
get_texture_substitution(format, type, realFormat, realType);
// Try to find it in recycling if enabled...
TexObj* texObj = NULL;
if(recylingEnabled) {
TexObj* bestTex = NULL;
TexObj* cTex;
std::list<TexObj*>::iterator iter;
for(iter = texRecycleList.begin(); iter != texRecycleList.end(); iter++) {
cTex = *iter;
if(cTex->format() == realFormat && cTex->type() == realType && cTex->width() == w && cTex->height() == h)
bestTex = cTex;
}
if(bestTex) {
texRecycleList.remove(bestTex);
texObj = bestTex;
if(gpu_log_enabled()) {
sprintf(buffer, "+++ Creating Texture: { %s, %s, (%i x %i) } - RECYCLED from (%i x %i) (Total Allocated: %.2fMB)\n",
TexFormatToString(format), TexTypeToString(type), w, h, bestTex->width(), bestTex->height(),
allocatedSize/1000000.0);
gpu_log(buffer);
}
}
}
// if necessary, create new TexObj
if(!texObj) {
texObj = new TexObj(w, h, realFormat, realType);
allocatedCount++;
allocatedSize += texObj->MemorySize();
if(gpu_log_enabled()) {
if(format != realFormat || type != realType)
sprintf(buffer, "+++ Creating Texture: { %s, %s, (%i x %i) } - NEW, Substituting {%s, %s } (Total Allocated: %.2fMB)\n",
TexFormatToString(format), TexTypeToString(type), w, h, TexFormatToString(realFormat), TexTypeToString(realType), allocatedSize/1000000.0);
else
sprintf(buffer, "+++ Creating Texture: { %s, %s, (%i x %i) } - NEW (Total of %.3fMB)\n",
TexFormatToString(format), TexTypeToString(type), w, h, allocatedSize/1000000.0);
gpu_log(buffer);
}
}
// return
return texObj;
}
void
TexAlloc::release(TexObj* texObj) {
if(recylingEnabled) {
texRecycleList.push_back(texObj);
if(gpu_log_enabled()) {
sprintf(buffer, "--- Recycling Texture: { %s, %s, (%i x %i) } (Total Allocated %.2fMB)\n",
TexFormatToString(texObj->format()), TexTypeToString(texObj->type()), texObj->width(), texObj->height(), allocatedSize/1000000.0);
gpu_log(buffer);
}
}
else {
allocatedCount--;
allocatedSize -= texObj->MemorySize();
if(gpu_log_enabled()) {
sprintf(buffer, "--- Deleting Texture: { %s, %s, (%i x %i) } (Total Allocated %.2fMB)\n",
TexFormatToString(texObj->format()), TexTypeToString(texObj->type()), texObj->width(), texObj->height(), allocatedSize/1000000.0);
gpu_log(buffer);
}
delete texObj;
}
}
void TexAlloc::clear_recycled() {
std::list<TexObj*>::iterator iter;
for(iter = texRecycleList.begin(); iter != texRecycleList.end(); iter++) {
TexObj* texObj = *iter;
allocatedCount--;
allocatedSize -= texObj->MemorySize();
if(gpu_log_enabled()) {
sprintf(buffer, "--- Deleting Texture: { %s, %s, (%i x %i) } (Total Allocated %.2fMB)\n",
TexFormatToString(texObj->format()), TexTypeToString(texObj->type()), texObj->width(), texObj->height(), allocatedSize/1000000.0);
gpu_log(buffer);
}
delete *iter;
}
texRecycleList.clear();
}
void TexAlloc::generate_texture_substitutions(bool verbose) {
textureSubstitutesMap.clear();
char buffer1[256];
char buffer2[256];
bool chart[3][3];
static Tex_Format textureFormats[] = { GPU_RED, GPU_RGB, GPU_RGBA };
static Tex_Type textureTypes[] = { GPU_UINT8, GPU_FLOAT16, GPU_FLOAT32 };
for(int i_format=0; i_format < 3; i_format++) {
Tex_Format format = textureFormats[i_format];
if(format == GPU_RED) sprintf(buffer1, "GPU_RED");
else if(format == GPU_RGB) sprintf(buffer1, "GPU_RGB");
else if(format == GPU_RGBA) sprintf(buffer1, "GPU_RGBA");
for(int i_type=0; i_type < 3; i_type++) {
bool failed = false;
Tex_Type type = textureTypes[i_type];
if(type == GPU_UINT8) sprintf(buffer2, "GPU_UINT8");
else if(type == GPU_FLOAT16) sprintf(buffer2, "GPU_FLOAT16");
else if(type == GPU_FLOAT32) sprintf(buffer2, "GPU_FLOAT32");
if(verbose)
printf("Checking Texture Support for: format = %s, type = %s\n", buffer1, buffer2);
auto_ptr<TexObj> texRef(new TexObj(100, 100, format, type));
if(!texRef->width()) {
failed = true;
if(verbose)
printf(" *** Failed on create.\n");
}
if(!failed) {
glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, g_framebuffer);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, texRef->target(), texRef->name(), 0);
glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
if(!CheckFramebuffer(false)) {
failed = true;
if(verbose)
printf(" *** Failed on bind to framebuffer.\n");
}
}
chart[i_format][i_type] = !failed;
}
}
for(int i_format=0; i_format < 3; i_format++) {
for(int i_type=0; i_type < 3; i_type++) {
bool found = false;
Tex_Format inFormat = textureFormats[i_format];
Tex_Type inType = textureTypes[i_type];
Tex_Format outFormat;
Tex_Type outType;
for(int j_format=i_format; j_format < 3 && !found; j_format++) {
for(int j_type=i_type; j_type < 3; j_type++) {
if(chart[j_format][j_type]) {
found = true;
outFormat = textureFormats[j_format];
outType = textureTypes[j_type];
textureSubstitutesMap[pair<Tex_Format, Tex_Type>(inFormat, inType)] = pair<Tex_Format, Tex_Type>(outFormat, outType);
if(verbose) {
printf("[%s, %s] implemented as: ", TexFormatToString(inFormat), TexTypeToString(inType));
printf("[%s, %s]\n", TexFormatToString(outFormat), TexTypeToString(outType));
}
break;
}
}
}
if(verbose && !found) {
Tex_Format format = inFormat;
if(format == GPU_RED) sprintf(buffer1, "GPU_RED");
else if(format == GPU_RGB) sprintf(buffer1, "GPU_RGB");
else if(format == GPU_RGBA) sprintf(buffer1, "GPU_RGBA");
Tex_Type type = inType;
if(type == GPU_UINT8) sprintf(buffer2, "GPU_UINT8");
else if(type == GPU_FLOAT16) sprintf(buffer2, "GPU_FLOAT16");
else if(type == GPU_FLOAT32) sprintf(buffer2, "GPU_FLOAT32");
printf("[%s, %s] NOT IMPLEMENTED!\n", buffer1, buffer2);
}
}
}
}
bool TexAlloc::get_texture_substitution(Tex_Format inFormat, Tex_Type inType, Tex_Format& outFormat, Tex_Type& outType) {
map<pair<Tex_Format, Tex_Type>, pair<Tex_Format, Tex_Type> >::iterator iter;
iter = textureSubstitutesMap.find(pair<Tex_Format, Tex_Type>(inFormat, inType));
if(iter != textureSubstitutesMap.end()) {
outFormat = (*iter).second.first;
outType = (*iter).second.second;
return true;
}
else
return false;
}
//###############################################################
// TexAlloc: Class Functions - Private
//###############################################################
void
TexAlloc::initialize_texalloc() {
generate_texture_substitutions();
isInit = true;
}
} } // namespaces GPU, vw
| 39.459459
| 157
| 0.575571
|
tkeemon
|
57e2fcceba37ff5cc50f347e505114f0dc1297b5
| 1,162
|
hpp
|
C++
|
include/mettle/driver/subprocess_test_runner.hpp
|
JohnGalbraith/mettle
|
38b70fe1dc0f30e98b768a37108196328182b5f4
|
[
"BSD-3-Clause"
] | 1
|
2019-06-07T08:03:33.000Z
|
2019-06-07T08:03:33.000Z
|
include/mettle/driver/subprocess_test_runner.hpp
|
JohnGalbraith/mettle
|
38b70fe1dc0f30e98b768a37108196328182b5f4
|
[
"BSD-3-Clause"
] | null | null | null |
include/mettle/driver/subprocess_test_runner.hpp
|
JohnGalbraith/mettle
|
38b70fe1dc0f30e98b768a37108196328182b5f4
|
[
"BSD-3-Clause"
] | 2
|
2018-07-02T19:28:43.000Z
|
2019-06-07T08:03:35.000Z
|
#ifndef INC_METTLE_DRIVER_SUBPROCESS_TEST_RUNNER_HPP
#define INC_METTLE_DRIVER_SUBPROCESS_TEST_RUNNER_HPP
#include <chrono>
#include <optional>
#ifdef _WIN32
# include <wtypes.h>
#endif
#include <mettle/suite/compiled_suite.hpp>
#include <mettle/driver/log/core.hpp>
#include <mettle/driver/detail/export.hpp>
namespace mettle {
class METTLE_PUBLIC subprocess_test_runner {
public:
using timeout_t = std::optional<std::chrono::milliseconds>;
subprocess_test_runner(timeout_t timeout = {}) : timeout_(timeout) {}
template<class Rep, class Period>
subprocess_test_runner(std::chrono::duration<Rep, Period> timeout)
: timeout_(timeout) {}
test_result
operator ()(const test_info &test, log::test_output &output) const;
private:
timeout_t timeout_;
};
#ifndef _WIN32
using fd_type = int;
int make_fd_private(int fd);
#else
using fd_type = HANDLE;
METTLE_PUBLIC int make_fd_private(HANDLE handle);
METTLE_PUBLIC const test_info *
find_test(const suites_list &suites, test_uid id);
METTLE_PUBLIC bool run_single_test(const test_info &test, HANDLE log_pipe);
#endif
} // namespace mettle
#endif
| 21.924528
| 77
| 0.74957
|
JohnGalbraith
|
57e89dd379394574585b82b36dc6d3096913ef18
| 155
|
cc
|
C++
|
Emscripten/file_io/file_io.cc
|
stephenfire/Book-DISO-WebAssembly
|
35054b59caa4284680d7dd73bf2637de5631caa7
|
[
"MIT"
] | 57
|
2018-02-14T02:12:00.000Z
|
2022-03-04T09:12:26.000Z
|
Emscripten/file_io/file_io.cc
|
stephenfire/Book-DISO-WebAssembly
|
35054b59caa4284680d7dd73bf2637de5631caa7
|
[
"MIT"
] | 15
|
2018-08-23T12:37:53.000Z
|
2021-05-09T10:22:27.000Z
|
Emscripten/file_io/file_io.cc
|
stephenfire/Book-DISO-WebAssembly
|
35054b59caa4284680d7dd73bf2637de5631caa7
|
[
"MIT"
] | 15
|
2019-01-27T09:35:19.000Z
|
2022-02-03T13:56:03.000Z
|
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
char _t;
cin >> _t;
cout << _t << endl;
cerr << _t << endl;
return 0;
}
| 14.090909
| 33
| 0.593548
|
stephenfire
|
57f3c03fc5ddc707c1aec4b9ddec71cd50503ead
| 8,879
|
inl
|
C++
|
Synergy/src/Synergy/System/System.inl
|
nmrsmn/synergy
|
7f77c70c131debe66d2e91e00827fd30e736cf81
|
[
"MIT"
] | null | null | null |
Synergy/src/Synergy/System/System.inl
|
nmrsmn/synergy
|
7f77c70c131debe66d2e91e00827fd30e736cf81
|
[
"MIT"
] | 25
|
2020-04-05T11:05:08.000Z
|
2020-06-07T12:48:58.000Z
|
Synergy/src/Synergy/System/System.inl
|
nmrsmn/synergy
|
7f77c70c131debe66d2e91e00827fd30e736cf81
|
[
"MIT"
] | null | null | null |
// Created by Niels Marsman on 15-05-2020.
// Copyright ยฉ 2020 Niels Marsman. All rights reserved.
#ifndef SYNERGY_SYSTEM_SYSTEM_INLINE
#define SYNERGY_SYSTEM_SYSTEM_INLINE
template <typename T>
template <typename... Args>
inline Synergy::System<T>::System(Synergy::Scene& scene, const std::string& name, Args&&... args) :
m_Instance(std::forward<Args>(args)...),
m_Name(name)
{
if constexpr(Synergy::SystemTraits<T>::HasEntities)
this->RegisterEntities(scene);
scene.OnEvent([&] (const Synergy::UpdateEvent& event)
{
this->OnUpdate(event.dt);
});
if constexpr(Synergy::SystemTraits<T>::HasFrameStart)
scene.OnEvent([&] (const Synergy::FrameStartEvent& event)
{
this->OnStartFrame();
});
if constexpr(Synergy::SystemTraits<T>::HasFrameEnd)
scene.OnEvent([&] (const Synergy::FrameEndEvent& event)
{
this->OnEndFrame();
});
if constexpr(Synergy::SystemTraits<T>::HasInitialize)
this->Initialize();
}
template <typename T>
bool Synergy::System<T>::HasEntities() const
{
return SystemTraits<T>::HasEntities;
}
template <typename T>
bool Synergy::System<T>::HasInitialize() const
{
return SystemTraits<T>::HasInitialize;
}
template <typename T>
bool Synergy::System<T>::HasDestroy() const
{
return Synergy::SystemTraits<T>::HasDestroy;
}
template <typename T>
bool Synergy::System<T>::HasEnable() const
{
return Synergy::SystemTraits<T>::HasEnable;
}
template <typename T>
bool Synergy::System<T>::HasDisable() const
{
return Synergy::SystemTraits<T>::HasDisable;
}
template <typename T>
bool Synergy::System<T>::HasLoad() const
{
return Synergy::SystemTraits<T>::HasLoad;
}
template <typename T>
bool Synergy::System<T>::HasUnload() const
{
return Synergy::SystemTraits<T>::HasUnload;
}
template <typename T>
bool Synergy::System<T>::HasReload() const
{
return Synergy::SystemTraits<T>::HasReload;
}
template <typename T>
bool Synergy::System<T>::HasFrameStart() const
{
return Synergy::SystemTraits<T>::HasFrameStart;
}
template <typename T>
bool Synergy::System<T>::HasFrameEnd() const
{
return Synergy::SystemTraits<T>::HasFrameEnd;
}
template <typename T>
bool Synergy::System<T>::HasFixedUpdate() const
{
return Synergy::SystemTraits<T>::HasFixedUpdate;
}
template <typename T>
bool Synergy::System<T>::HasPreProcess() const
{
return Synergy::SystemTraits<T>::HasPreProcess;
}
template <typename T>
bool Synergy::System<T>::HasProcess() const
{
return Synergy::SystemTraits<T>::HasProcess;
}
template <typename T>
bool Synergy::System<T>::HasPostProcess() const
{
return Synergy::SystemTraits<T>::HasPostProcess;
}
template <typename T>
bool Synergy::System<T>::HasUpdate() const
{
return Synergy::SystemTraits<T>::HasUpdate;
}
template <typename T>
bool Synergy::System<T>::HasPostUpdate() const
{
return Synergy::SystemTraits<T>::HasPostUpdate;
}
template <typename T>
inline void Synergy::System<T>::OnFrameStart()
{
if constexpr(Synergy::SystemTraits<T>::HasFrameStart)
this->FrameStart();
}
template <typename T>
inline void Synergy::System<T>::OnFrameEnd()
{
if constexpr(Synergy::SystemTraits<T>::HasFrameEnd)
this->FrameEnd();
}
template <typename T>
inline void Synergy::System<T>::OnUpdate(float dt)
{
if constexpr(Synergy::SystemTraits<T>::HasPreProcess) this->PreProcess();
if constexpr(Synergy::SystemTraits<T>::HasProcess) this->Process();
if constexpr(Synergy::SystemTraits<T>::HasPostProcess) this->PostProcess();
if constexpr(Synergy::SystemTraits<T>::HasUpdate) this->Update();
if constexpr(Synergy::SystemTraits<T>::HasPostUpdate) this->PostUpdate();
}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasInitialize> Synergy::System<T>::Initialize()
{
m_Instance.Initialize();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasInitialize> Synergy::System<T>::Initialize()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasDestroy> Synergy::System<T>::Destroy()
{
m_Instance.Destroy();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasDestroy> Synergy::System<T>::Destroy()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasEnable> Synergy::System<T>::Enable()
{
m_Instance.Enable();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasEnable> Synergy::System<T>::Enable()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasDisable> Synergy::System<T>::Disable()
{
m_Instance.Disable();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasDisable> Synergy::System<T>::Disable()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasLoad> Synergy::System<T>::Load()
{
m_Instance.Load();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasLoad> Synergy::System<T>::Load()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasUnload> Synergy::System<T>::Unload()
{
m_Instance.Unload();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasUnload> Synergy::System<T>::Unload()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasReload> Synergy::System<T>::Reload()
{
m_Instance.Reload();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasReload> Synergy::System<T>::Reload()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasFrameStart> Synergy::System<T>::FrameStart()
{
m_Instance.FrameStart();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasFrameStart> Synergy::System<T>::FrameStart()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasFrameEnd> Synergy::System<T>::FrameEnd()
{
m_Instance.FrameEnd();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasFrameEnd> Synergy::System<T>::FrameEnd()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasFixedUpdate> Synergy::System<T>::FixedUpdate(float dt)
{
m_Instance.FixedUpdate(dt);
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasFixedUpdate> Synergy::System<T>::FixedUpdate(float dt)
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasPreProcess> Synergy::System<T>::PreProcess()
{
m_Instance.PreProcess();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasPreProcess> Synergy::System<T>::PreProcess()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasProcess> Synergy::System<T>::Process()
{
for (auto entity : m_Instance.m_Entities)
{
entity.Invoke([&] (auto&&... args)
{
m_Instance.Process(std::forward<decltype(args)>(args)...);
});
}
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasProcess> Synergy::System<T>::Process()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasPostProcess> Synergy::System<T>::PostProcess()
{
m_Instance.PostProcess();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasPostProcess> Synergy::System<T>::PostProcess()
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasUpdate> Synergy::System<T>::Update(float dt)
{
m_Instance.Update(dt);
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasUpdate> Synergy::System<T>::Update(float dt)
{}
template <typename T>
template <typename U>
typename std::enable_if_t<Synergy::SystemTraits<U>::HasPostUpdate> Synergy::System<T>::PostUpdate()
{
m_Instance.PostUpdate();
}
template <typename T>
template <typename U>
typename std::enable_if_t<!Synergy::SystemTraits<U>::HasPostUpdate> Synergy::System<T>::PostUpdate()
{}
template <typename T>
void Synergy::System<T>::RegisterEntities(Synergy::Scene& scene)
{
scene.RegisterEntitiesWith(m_Instance.m_Entities);
}
#endif
| 25.368571
| 110
| 0.718212
|
nmrsmn
|
57f9db00d28f16b0c941d0263caa49e29c65dc9f
| 1,065
|
cpp
|
C++
|
src/Network/Nodes/CallbackNode.cpp
|
dmalysiak/Lazarus
|
925d92843e311d2cd5afd437766563d0d5ab9052
|
[
"Apache-2.0"
] | 1
|
2019-04-29T05:31:32.000Z
|
2019-04-29T05:31:32.000Z
|
src/Network/Nodes/CallbackNode.cpp
|
dmalysiak/Lazarus
|
925d92843e311d2cd5afd437766563d0d5ab9052
|
[
"Apache-2.0"
] | null | null | null |
src/Network/Nodes/CallbackNode.cpp
|
dmalysiak/Lazarus
|
925d92843e311d2cd5afd437766563d0d5ab9052
|
[
"Apache-2.0"
] | null | null | null |
/*
* CallbackNode.cpp
*
* Created on: Aug 24, 2013
* Author: Darius Malysiak
*/
#include "CallbackNode.h"
namespace Lazarus {
CallbackNode::CallbackNode(unsigned int nodeID, Frame* frame) {
m_communication_in_progress = false;
mp_frame = frame;
mp_com_callback = NULL;
pthread_mutex_init(&m_mutex,NULL);
m_node_id = nodeID;
}
CallbackNode::~CallbackNode()
{
pthread_mutex_destroy(&m_mutex);
}
void CallbackNode::setCallback(SynchronizationCallback* com_callback)
{
mp_com_callback = com_callback;
}
SynchronizationCallback* CallbackNode::getCallback()
{
return mp_com_callback;
}
bool CallbackNode::isCommunicating()
{
return m_communication_in_progress;
}
Frame* CallbackNode::get_mp_frame()
{
return mp_frame;
}
void CallbackNode::lockMutex()
{
pthread_mutex_lock(&m_mutex);
m_communication_in_progress = true;
}
void CallbackNode::unlockMutex()
{
m_communication_in_progress = false;
pthread_mutex_unlock(&m_mutex);
}
void CallbackNode::serialize()
{
}
void CallbackNode::deserialize()
{
}
} /* namespace Lazarus */
| 14.391892
| 69
| 0.749296
|
dmalysiak
|
57fe0e840b0d57f682a7a81320a4a8437b8c5cec
| 2,008
|
cpp
|
C++
|
SimpleCalculator/GlobalMgr.cpp
|
KeNorizon/SimpleCalculator
|
3e0cdc9b96d9474f4ff0279612fbd7bbb933306a
|
[
"BSD-2-Clause"
] | 1
|
2019-10-30T16:16:50.000Z
|
2019-10-30T16:16:50.000Z
|
SimpleCalculator/GlobalMgr.cpp
|
KeNorizon/SimpleCalculator
|
3e0cdc9b96d9474f4ff0279612fbd7bbb933306a
|
[
"BSD-2-Clause"
] | null | null | null |
SimpleCalculator/GlobalMgr.cpp
|
KeNorizon/SimpleCalculator
|
3e0cdc9b96d9474f4ff0279612fbd7bbb933306a
|
[
"BSD-2-Clause"
] | null | null | null |
#include "GlobalMgr.h"
#include <iostream>
#include "ResultPanel.h"
#include <QPoint>
GlobalMgr *g_Data = nullptr;
GlobalMgr::GlobalMgr()
{
g_Data = this;
Visual.updateParamCache();
RootExpr = new HorizontalExpression(nullptr);
Cursor.setWithoutBrighten(RootExpr, 0);
Config.readFromFile();
markExprDirty();
markEnsureCursorInScreen();
}
void GlobalMgr::init()
{
if (g_Data == nullptr)
{
new GlobalMgr();
}
}
bool GlobalMgr::isExprDirty()
{
return ExprDirtyFlag;
}
void GlobalMgr::markExprDirty()
{
ExprDirtyFlag = true;
}
void GlobalMgr::clearExprDirtyFlag()
{
ExprDirtyFlag = false;
}
bool GlobalMgr::isEnsureCursorInScreen()
{
return EnsureCursorInScreenFlag;
}
void GlobalMgr::markEnsureCursorInScreen()
{
EnsureCursorInScreenFlag = true;
}
void GlobalMgr::clearEnsureCursorInScreenFlag()
{
EnsureCursorInScreenFlag = false;
}
void GlobalMgr::doCompute()
{
updateResult();
ResultPanel::getInstance()->update();
}
HorizontalExpression * GlobalMgr::getRootExpr() const
{
return RootExpr;
}
void GlobalMgr::setRootExpr(HorizontalExpression *expr)
{
if (!History.contains(RootExpr))
{
delete RootExpr;
clearResult();
}
RootExpr = expr;
}
void GlobalMgr::repaintExpr()
{
ArithmeticPanel::getInstance()->update();
}
void GlobalMgr::updateResult()
{
ExprResult = RootExpr->computeValue();
if (RootExpr->getLength() == 0)
ResultPanel::getInstance()->hideResult();
else
ResultPanel::getInstance()->showResult(ExprResult);
}
void GlobalMgr::setResult(ComputeResult result)
{
ExprResult = result;
if (RootExpr->getLength() == 0)
ResultPanel::getInstance()->hideResult();
else
ResultPanel::getInstance()->showResult(ExprResult);
}
void GlobalMgr::clearResult()
{
ExprResult.Value = 0;
ExprResult.Expr = nullptr;
ExprResult.Error = ComputeErrorType::Success;
ResultPanel::getInstance()->hideResult();
}
GlobalMgr::~GlobalMgr()
{
if (RootExpr != nullptr)
{
if (!History.contains(RootExpr))
{
delete RootExpr;
RootExpr = nullptr;
}
}
}
| 16.325203
| 55
| 0.725598
|
KeNorizon
|
57fff938372a00d8ffcd417e27f78b46016b987b
| 711
|
cpp
|
C++
|
core/geometry/GpuProgramManager.cpp
|
billhj/Etoile2015
|
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
|
[
"Apache-2.0"
] | null | null | null |
core/geometry/GpuProgramManager.cpp
|
billhj/Etoile2015
|
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
|
[
"Apache-2.0"
] | null | null | null |
core/geometry/GpuProgramManager.cpp
|
billhj/Etoile2015
|
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright(C) 2009-2012
* @author Jing HUANG
* @file GpuProgramManager.cpp
* @brief
* @date 1/2/2011
*/
#include "GpuProgramManager.h"
#include "GpuProgram.h"
#include <assert.h>
/**
* @brief For tracking memory leaks under windows using the crtdbg
*/
#if ( defined( _DEBUG ) || defined( DEBUG ) ) && defined( _MSC_VER )
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
namespace Etoile
{
GpuProgramManager::GpuProgramManager() : ResourceManager<GpuProgram>()
{
}
/*GpuProgram* GpuProgramManager::getGpuProgramByName(const std::string& name)
{
return (GpuProgram*)getByName(name);
}*/
}
| 18.230769
| 78
| 0.700422
|
billhj
|
5204b80bbd7f0f5d2e6165e56866d28c617d7b03
| 666
|
cpp
|
C++
|
C++/TheFirst/CODE FILES/Numbers/simpleCalculator.cpp
|
Lakshmivallala/CPP
|
374bcdedd15a76fc4fa7b9d6c9dd3a140db859f1
|
[
"MIT"
] | null | null | null |
C++/TheFirst/CODE FILES/Numbers/simpleCalculator.cpp
|
Lakshmivallala/CPP
|
374bcdedd15a76fc4fa7b9d6c9dd3a140db859f1
|
[
"MIT"
] | null | null | null |
C++/TheFirst/CODE FILES/Numbers/simpleCalculator.cpp
|
Lakshmivallala/CPP
|
374bcdedd15a76fc4fa7b9d6c9dd3a140db859f1
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
using namespace std;
int main() //function
{
int a,b;
cout<<"Enter two integer numbers: "<<endl;
cin>>a>>b;
cout<<a+b<<endl; //try inputing float numbers
cout<<a-b<<endl;
cout<<a*b<<endl;
cout<<a/b<<endl;
cout<<a%b<<endl; //observe: give the inputs as 3 and 6. 3%6==3. You don't calculate with the steps: 3/6= 6*0.5=3 (don't go to decimal types while dividing integers)
float c,d;
cout<<"Enter two float numbers: "<<endl;
cin>>c>>d;
cout<<c+d<<endl;
cout<<c-d<<endl;
cout<<c*d<<endl;
cout<<c/d<<endl;
//cout<<c%d<<endl; RESULTS IN AN ERROR
return 0;
}
| 20.181818
| 168
| 0.585586
|
Lakshmivallala
|
5209275a8a103556ebdfbab109b834e49e3bd8b5
| 53
|
cpp
|
C++
|
Code/EditorPlugins/PhysX/EnginePluginPhysX/EnginePluginPhysX.cpp
|
Tekh-ops/ezEngine
|
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
|
[
"MIT"
] | 703
|
2015-03-07T15:30:40.000Z
|
2022-03-30T00:12:40.000Z
|
Code/EditorPlugins/PhysX/EnginePluginPhysX/EnginePluginPhysX.cpp
|
Tekh-ops/ezEngine
|
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
|
[
"MIT"
] | 233
|
2015-01-11T16:54:32.000Z
|
2022-03-19T18:00:47.000Z
|
Code/EditorPlugins/PhysX/EnginePluginPhysX/EnginePluginPhysX.cpp
|
Tekh-ops/ezEngine
|
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
|
[
"MIT"
] | 101
|
2016-10-28T14:05:10.000Z
|
2022-03-30T19:00:59.000Z
|
#include <EnginePluginPhysX/EnginePluginPhysXPCH.h>
| 17.666667
| 51
| 0.849057
|
Tekh-ops
|
520c12bbeb830c25bcb727fb4c5275901b6acc88
| 249
|
hpp
|
C++
|
src/Camera/Camera2D.hpp
|
fqhd/Sokuban
|
1b41fb6c6e7c865447824eaffce0dff8c7efafa4
|
[
"MIT"
] | 1
|
2021-11-17T07:52:45.000Z
|
2021-11-17T07:52:45.000Z
|
src/Camera/Camera2D.hpp
|
fqhd/Sokuban
|
1b41fb6c6e7c865447824eaffce0dff8c7efafa4
|
[
"MIT"
] | null | null | null |
src/Camera/Camera2D.hpp
|
fqhd/Sokuban
|
1b41fb6c6e7c865447824eaffce0dff8c7efafa4
|
[
"MIT"
] | null | null | null |
#ifndef CAMERA2D_H
#define CAMERA2D_H
#include <glm/gtc/matrix_transform.hpp>
class Camera2D {
public:
void init(unsigned int width, unsigned int height);
const glm::mat4& getMatrix();
private:
glm::mat4 m_matrix;
};
#endif
| 11.318182
| 56
| 0.690763
|
fqhd
|
648f699375d91de2bb01c878a24392fb07b2a727
| 1,828
|
cpp
|
C++
|
Dll/Monoblock/Monoblock.cpp
|
buzyaba/SimEngine
|
e5469f927154de43ea52ad74c0ca4a0af9a7b721
|
[
"MIT"
] | 5
|
2019-10-21T11:38:56.000Z
|
2020-05-30T04:50:50.000Z
|
Dll/Monoblock/Monoblock.cpp
|
buzyaba/SimEngine
|
e5469f927154de43ea52ad74c0ca4a0af9a7b721
|
[
"MIT"
] | 2
|
2020-03-16T13:16:27.000Z
|
2020-10-10T07:35:15.000Z
|
Dll/Monoblock/Monoblock.cpp
|
buzyaba/SimEngine
|
e5469f927154de43ea52ad74c0ca4a0af9a7b721
|
[
"MIT"
] | 3
|
2019-10-10T15:10:57.000Z
|
2020-02-14T13:11:50.000Z
|
#include "Monoblock.h"
#include <random>
// static std::random_device rd;
// static std::mt19937 gen(rd());
// static std::bernoulli_distribution d(0.02);
TMonoblock::TMonoblock(std::string _name) : TObjectOfObservation(_name) {
properties.insert(
{"IsWork", new TProperties({{"IsWork", 2}}, true, "IsWork")});
properties.insert(
{"PowerConsumption",
new TProperties({{"PowerConsumption", 0}}, true, "PowerConsumption")});
properties.insert(
{"Coordinate",
new TProperties({{"X", 0}, {"Y", 0}, {"Z", 0}}, false, "Coordinate")});
properties.insert(
{"Rotate",
new TProperties({{"X", 0.0}, {"Y", 0.0}, {"Z", 0.0}}, false, "Rotate")});
properties.insert(
{"Scale", new TProperties({{"Width", 3}, {"Length", 3}, {"Height", 3}},
false, "Scale")});
textures.push_back(
{{"screen_Plane.015"}, {"monitorON.png"}, {"monitorON.png"}});
isWork = false;
}
void TMonoblock::Update() {
TObjectOfObservation::Update();
int newIsWork = static_cast<int>(properties["IsWork"]->GetValues()["IsWork"]);
// if (newIsWork < 2 && d(gen))
// newIsWork = newIsWork ? 0 : 1;
switch (newIsWork) {
case 0:
isWork = newIsWork;
properties["PowerConsumption"]->SetValues(
{{"PowerConsumption", 0.1667}}); // sleep
textures[0][2] = "monitorSleep.png";
break;
case 1:
isWork = newIsWork;
properties["PowerConsumption"]->SetValues(
{{"PowerConsumption", 1.6667}}); // full
textures[0][2] = "monitorON.png";
break;
case 2:
isWork = newIsWork;
properties["PowerConsumption"]->SetValues(
{{"PowerConsumption", 0}}); // shutdown
textures[0][2] = "monitorOFF.png";
break;
}
}
LIB_EXPORT_API TObjectOfObservation *create() {
return new TMonoblock("TMonoblock");
}
| 29.967213
| 80
| 0.603392
|
buzyaba
|
64942fb5d9162df6456c0e6a21199f8274a974e3
| 6,637
|
cc
|
C++
|
node_modules/aerospike/src/main/client.cc
|
EnriqueSampaio/aero-livechat
|
29af57560e022a5958379445852def2cab94aca0
|
[
"MIT"
] | null | null | null |
node_modules/aerospike/src/main/client.cc
|
EnriqueSampaio/aero-livechat
|
29af57560e022a5958379445852def2cab94aca0
|
[
"MIT"
] | null | null | null |
node_modules/aerospike/src/main/client.cc
|
EnriqueSampaio/aero-livechat
|
29af57560e022a5958379445852def2cab94aca0
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
* Copyright 2013-2014 Aerospike, Inc.
*
* 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.
******************************************************************************/
extern "C" {
#include <aerospike/aerospike.h>
#include <aerospike/aerospike_key.h>
#include <aerospike/as_config.h>
#include <aerospike/as_key.h>
#include <aerospike/as_record.h>
}
#include <unistd.h>
#include <node.h>
#include "client.h"
#include "conversions.h"
#include "query.h"
/*******************************************************************************
* Fields
******************************************************************************/
/**
* JavaScript constructor for AerospikeClient
*/
Nan::Persistent<FunctionTemplate> AerospikeClient::constructor;
/*******************************************************************************
* Constructor and Destructor
******************************************************************************/
AerospikeClient::AerospikeClient() {}
AerospikeClient::~AerospikeClient() {}
/*******************************************************************************
* Methods
******************************************************************************/
NAN_METHOD(AerospikeClient::SetLogLevel)
{
Nan::HandleScope();
AerospikeClient * client = ObjectWrap::Unwrap<AerospikeClient>(info.Holder());
if (info[0]->IsObject()){
LogInfo * log = client->log;
if ( log_from_jsobject(log, info[0]->ToObject()) != AS_NODE_PARAM_OK ) {
log->severity = AS_LOG_LEVEL_INFO;
log->fd = 2;
}
}
info.GetReturnValue().Set(info.Holder());
}
NAN_METHOD(AerospikeClient::Query)
{
Nan::HandleScope();
Local<Object> ns = info[0].As<Object>();
Local<Object> set = info[1].As<Object>();
Local<Object> config = info[2].As<Object>();
Local<Object> client = info.This();
info.GetReturnValue().Set(AerospikeQuery::NewInstance(ns, set, config, client));
}
/**
* Instantiate a new 'AerospikeClient(config)'
* Constructor for AerospikeClient.
*/
NAN_METHOD(AerospikeClient::New)
{
Nan::HandleScope();
AerospikeClient * client = new AerospikeClient();
client->as = (aerospike*) cf_malloc(sizeof(aerospike));
client->log = (LogInfo*) cf_malloc(sizeof(LogInfo));
// initialize the log to default values.
LogInfo * log = client->log;
log->fd = 2;
log->severity = AS_LOG_LEVEL_INFO;
// initialize the config to default values.
as_config config;
as_config_init(&config);
// Assume by default log is not set
if(info[0]->IsObject()) {
int default_log_set = 0;
if (info[0]->ToObject()->Has(Nan::New("log").ToLocalChecked()))
{
Local<Value> log_val = info[0]->ToObject()->Get(Nan::New("log").ToLocalChecked()) ;
if (log_from_jsobject( client->log, log_val->ToObject()) == AS_NODE_PARAM_OK) {
default_log_set = 1; // Log is passed as an argument. set the default value
} else {
//log info is set to default level
}
}
if ( default_log_set == 0 ) {
LogInfo * log = client->log;
log->fd = 2;
}
}
if (info[0]->IsObject() ) {
int result = config_from_jsobject(&config, info[0]->ToObject(), client->log);
if( result != AS_NODE_PARAM_OK)
{
// Throw an exception if an error happens in parsing the config object.
Nan::ThrowError("Configuration Error while creating client object");
}
}
aerospike_init(client->as, &config);
as_v8_debug(client->log, "Aerospike object initialization : success");
client->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
/**
* Instantiate a new 'AerospikeClient(config)'
*/
Local<Value> AerospikeClient::NewInstance(Local<Object> info)
{
Nan::EscapableHandleScope scope;
const unsigned argc = 1;
Handle<Value> argv[argc] = { info };
Local<FunctionTemplate> constructorHandle = Nan::New<FunctionTemplate>(constructor);
Local<Value> instance = constructorHandle->GetFunction()->NewInstance(argc, argv);
return scope.Escape(instance);
}
/**
* Initialize a client object.
* This creates a constructor function, and sets up the prototype.
*/
void AerospikeClient::Init()
{
// Prepare constructor template
Local<FunctionTemplate> cons = Nan::New<FunctionTemplate>(AerospikeClient::New);
cons->SetClassName(Nan::New("AerospikeClient").ToLocalChecked());
// A client object created in node.js, holds reference to the wrapped c++
// object using an internal field.
// InternalFieldCount signifies the number of c++ objects the node.js object
// will refer to when it is intiatiated in node.js
cons->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
Nan::SetPrototypeMethod(cons, "batchGet", BatchGet);
Nan::SetPrototypeMethod(cons, "batchExists", BatchExists);
Nan::SetPrototypeMethod(cons, "batchSelect", BatchSelect);
Nan::SetPrototypeMethod(cons, "close", Close);
Nan::SetPrototypeMethod(cons, "connect", Connect);
Nan::SetPrototypeMethod(cons, "exists", Exists);
Nan::SetPrototypeMethod(cons, "get", Get);
Nan::SetPrototypeMethod(cons, "info", Info);
Nan::SetPrototypeMethod(cons, "indexCreate", sindexCreate);
Nan::SetPrototypeMethod(cons, "indexCreateWait", sindexCreateWait);
Nan::SetPrototypeMethod(cons, "indexRemove", sindexRemove);
Nan::SetPrototypeMethod(cons, "operate", Operate);
Nan::SetPrototypeMethod(cons, "put", Put);
Nan::SetPrototypeMethod(cons, "query", Query);
Nan::SetPrototypeMethod(cons, "remove", Remove);
Nan::SetPrototypeMethod(cons, "select", Select);
Nan::SetPrototypeMethod(cons, "udfRegister", Register);
Nan::SetPrototypeMethod(cons, "udfRegisterWait", RegisterWait);
Nan::SetPrototypeMethod(cons, "execute", Execute);
Nan::SetPrototypeMethod(cons, "udfRemove", UDFRemove);
Nan::SetPrototypeMethod(cons, "updateLogging", SetLogLevel);
constructor.Reset(cons);
}
| 33.862245
| 95
| 0.612024
|
EnriqueSampaio
|
6495723b7e66913921e9e390dec342a7f8cd962c
| 14,381
|
cpp
|
C++
|
lib/ModbusAPI.cpp
|
mensinda/modbusSMA
|
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
|
[
"Apache-2.0"
] | 1
|
2020-03-15T18:53:26.000Z
|
2020-03-15T18:53:26.000Z
|
lib/ModbusAPI.cpp
|
mensinda/modbusSMA
|
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
|
[
"Apache-2.0"
] | null | null | null |
lib/ModbusAPI.cpp
|
mensinda/modbusSMA
|
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
|
[
"Apache-2.0"
] | 1
|
2022-03-14T11:06:26.000Z
|
2022-03-14T11:06:26.000Z
|
/*
* Copyright (C) 2018 Daniel Mensinger
*
* 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 "mSMAConfig.hpp"
#include "ModbusAPI.hpp"
#include <algorithm>
#include "Logging.hpp"
#include "MBConnectionIP.hpp"
#include "MBConnectionIP_PI.hpp"
#include "MBConnectionRTU.hpp"
using namespace std;
using namespace modbusSMA;
/*!
* \brief Initializes the ModbusAPI with a custom TCP IP and port
* \sa setConnectionTCP_IP
*/
ModbusAPI::ModbusAPI(string _ip, //!< The IP address of the inverter.
uint32_t _port, //!< The modbus TCP port.
std::shared_ptr<DataBase> _db //!< Database describing the modbus registers.
) {
setConnectionTCP_IP(_ip, _port);
setDataBase(_db);
}
/*!
* \brief Initializes the ModbusAPI with a custom IP and port
* \sa setConnectionTCP_IP
*/
ModbusAPI::ModbusAPI(string _node, //!< The Modbus node (IP address, DNS name, etc.) of the inverter.
string _service, //!< The service to connect to.
std::shared_ptr<DataBase> _db //!< Database describing the modbus registers.
) {
setConnectionTCP_IP_PI(_node, _service);
setDataBase(_db);
}
/*!
* \brief Initializes the ModbusAPI with a RTU connectopm
* \sa setConnectionRTU
*/
ModbusAPI::ModbusAPI(string _device, //!< The name / path of the serial port.
uint32_t _baud, //!< RTU connection baud rate.
char _parity, //!< Partity type: N = None; E = Even; O = Odd.
int _dataBit, //!< The number of bits of data, the allowed values are 5, 6, 7 and 8
int _stopBit, //!< The bits of stop, the allowed values are 1 and 2.
std::shared_ptr<DataBase> _db //!< Database describing the modbus registers.
) {
setConnectionRTU(_device, _baud, _parity, _dataBit, _stopBit);
setDataBase(_db);
}
//! Wrapper for the other constructor.
ModbusAPI::ModbusAPI(string _ip, uint32_t _port, string _dbPath)
: ModbusAPI(_ip, _port, make_shared<DataBase>(_dbPath)) {}
//! Wrapper for the other constructor.
ModbusAPI::ModbusAPI(string _node, string _service, string _dbPath)
: ModbusAPI(_node, _service, make_shared<DataBase>(_dbPath)) {}
//! Wrapper for the other constructor.
ModbusAPI::ModbusAPI(string _device, uint32_t _baud, char _parity, int _dataBit, int _stopBit, string _dbPath)
: ModbusAPI(_device, _baud, _parity, _dataBit, _stopBit, make_shared<DataBase>(_dbPath)) {}
ModbusAPI::~ModbusAPI() { reset(); }
/*!
* \brief Resets the state of the object (modbus connection, inverter type, etc.) to CONFIGURE
*
* The configuration (IP, port) is NOT reset.
*
* State change: * --> CONFIGURE
*/
void ModbusAPI::reset() {
if (mConn) {
mConn->disconnect();
mConn = nullptr;
}
mRegisters = nullptr;
mState = State::CONFIGURE;
}
/*!
* \brief Establishes the modbus connection based on the current configuration
*
* State change: CONFIGURE --> CONNECTED | ERROR
*/
ErrorCode ModbusAPI::connect() {
auto logger = log::get();
if (mState != State::CONFIGURE) {
logger->error("ModbusAPI: can not connect() -- invalid object state '{}'", enum2Str::toStr(mState));
mState = State::ERROR;
return ErrorCode::INVALID_STATE;
}
auto res = mConn->connect();
if (res != ErrorCode::OK) {
logger->error("ModbusAPI: unable to connect: '{}'", enum2Str::toStr(res));
mState = State::ERROR;
return res;
}
logger->info("ModbusAPI: connected to {}", mConn->description());
mState = State::CONNECTED;
return ErrorCode::OK;
}
/*!
* \brief Initializes the API
*
* This function connects to the DataBase (if not already done) and initializes the API by querying basic
* information (uinit id, inverter type) from the modbus interface
*
* State change: CONNECTED --> INITIALIZED | ERROR
*/
ErrorCode ModbusAPI::initialize() {
auto logger = log::get();
ErrorCode result;
if (mState != State::CONNECTED) {
logger->error("ModbusAPI: can not initialize() -- invalid object state '{}'", enum2Str::toStr(mState));
mState = State::ERROR;
return ErrorCode::INVALID_STATE;
}
// 1st: check database
if (!mDB->isConnected()) {
result = mDB->connect();
if (result != ErrorCode::OK) {
logger->error("ModbusAPI: DataBase initialization failed with {}", enum2Str::toStr(result));
mState = State::ERROR;
return result;
}
}
mRegisters = make_shared<RegisterContainer>();
mRegisters->addRegisters(mDB->getRegisters("ALL"));
if (mRegisters->empty()) {
// This code should never be executed because of the DataBase validation
logger->error("ModbusAPI: No Registers in table 'ALL'");
mState = State::ERROR;
return ErrorCode::DATA_BASE_ERROR;
}
// 2nd: set slave ID to 1
result = mConn->setSlaveID(1);
if (result != ErrorCode::OK) {
mState = State::ERROR;
return result;
}
// 3rd: request data
vector<uint16_t> rawData = mConn->readRegisters(42109, 4);
logger->debug("Requesting basic inverter information:");
if (rawData.size() != 4) {
logger->error("ModbusAPI: Failed to initialize -- requesting slave/unit ID failed");
mState = State::ERROR;
return ErrorCode::INITIALIZATION_FAILED;
}
uint32_t serialNumber = (rawData[0] << 16) + rawData[1];
uint16_t susyID = rawData[2];
uint16_t unitID = rawData[3];
logger->debug(" -- Physical serial number: {}", serialNumber);
logger->debug(" -- Physical SusyID: {}", susyID);
logger->debug(" -- Unit / Slave ID: {}", unitID);
// 4th: set slave ID to unitID
result = mConn->setSlaveID(unitID);
if (result != ErrorCode::OK) {
mState = State::ERROR;
return result;
}
// 5th: determine the inverter type
rawData = mConn->readRegisters(30053, 2);
uint32_t inverterID = (rawData[0] << 16) + rawData[1];
logger->debug(" -- Inverter type ID: {}", inverterID);
auto devices = mDB->getDeviceEnums();
bool found = false;
for (auto i : devices) {
if (i.id == inverterID) {
found = true;
mInverterType = i.name;
mInverterTypeID = inverterID;
mRegisters->addRegisters(mDB->getRegisters(i.table));
break;
}
}
if (!found) {
logger->error("ModbusAPI: unknown inverter type {}", inverterID);
mState = State::ERROR;
return ErrorCode::INITIALIZATION_FAILED;
}
logger->debug(" -- Inverter type: '{}'", mInverterType);
logger->debug(" -- Number of registers: {}", mRegisters->size());
logger->info("ModbusAPI: initialization for {} complete", mInverterType);
mState = State::INITIALIZED;
return ErrorCode::OK;
}
/*!
* \brief Wrapper for connect() and initialize()
*
* State change: CONFIGURE --> INITIALIZED | ERROR
*/
ErrorCode ModbusAPI::setup() {
ErrorCode res = connect();
if (res != ErrorCode::OK) { return res; }
return initialize();
}
//! Internal Request helper
//! \internal
struct RegBatch {
//! Internal Request helper
//! \internal
struct Reg {
uint16_t reg; //!< 16-bit register address.
uint16_t offset; //!< offset in the rawData vector.
uint16_t size; //!< number of modbus registers used in the Register class.
};
uint16_t size; //!< Size of the batch in number of registers.
vector<Reg> regs; //!< Registers in the batch.
vector<uint16_t> rawData; //!< Raw data vector.
};
/*!
* \brief Updates all registers stored in _regList
*
* Fethes the register values from the inverter and stores the values in the shared RegisterContainer. The updated
* register values can then examined by requesting the registers from the RegisterContainer.
*
* Unsupported registers (by the inverter) in _regList are ignored.
*
* \note This function can only be called in the INITIALIZED state
*
* State change: NONE
*
* \param[in] _regList List of registers to update
* \param[out] _numUpdated Number of updated registers
*/
ErrorCode ModbusAPI::updateRegisters(vector<Register> _regList, size_t *_numUpdated) {
auto logger = log::get();
if (_numUpdated) { *_numUpdated = 0; }
if (mState != State::INITIALIZED) {
logger->error("ModbusAPI: updateRegisters() -- invalid object state '{}'", enum2Str::toStr(mState));
return ErrorCode::INVALID_STATE;
}
if (_regList.empty()) {
logger->warn("ModbusAPI: updateRegisters() -- empty register list ==> do nothing");
return ErrorCode::OK;
}
sort(begin(_regList), end(_regList)); // Ensure that the list is sorted.
// 1st: Create batches of registers.
std::vector<RegBatch> batches;
batches.reserve(_regList.size()); // Worst case: every register has its own batch
batches.push_back({0, {}, {}});
for (Register i : _regList) {
RegBatch *curr = &batches.back();
if (!curr->regs.empty()) {
if (((curr->size + i.size()) >= SMA_MODBUS_MAX_REGISTER_COUNT) || // Check if maximum request size is reached
((curr->regs[0].reg + curr->size) != i.reg())) { // Check if continous
batches.push_back({0, {}, {}});
curr = &batches.back();
}
}
curr->regs.push_back({i.reg(), curr->size, (uint16_t)i.size()});
curr->size += i.size();
}
vector<uint16_t> singleRegData = {};
uint32_t counter = 1;
for (auto &i : batches) {
logger->debug("Fetching batch {} of {} -- Start: {}; Size: {}", counter++, batches.size(), i.regs[0].reg, i.size);
i.rawData = mConn->readRegisters(i.regs[0].reg, i.size);
if (i.rawData.size() != i.size) {
logger->warn(
"ModbusAPI: updateRegisters() -- failed to fetch registers: Start = {}; Size = {}", i.regs[0].reg, i.size);
continue;
}
for (auto j : i.regs) {
singleRegData.resize(j.size);
for (uint16_t k = 0; k < j.size; ++k) { singleRegData[k] = i.rawData[j.offset + k]; }
mRegisters->updateRegister(j.reg, singleRegData);
if (_numUpdated) { *_numUpdated += 1; }
}
}
return ErrorCode::OK;
}
//! Convinience wrapper for the other version of this function.
ErrorCode ModbusAPI::updateRegisters(vector<uint16_t> _regList, size_t *_numUpdated) {
if (mState != State::INITIALIZED) {
log::get()->error("ModbusAPI: updateRegisters() -- invalid object state '{}'", enum2Str::toStr(mState));
return ErrorCode::INVALID_STATE;
}
return updateRegisters(mRegisters->getRegisters(_regList), _numUpdated);
}
/*!
* \brief Sets the modbus register database to use
*
* \note This function can only be called in the CONFIGURE state
*
* State change: NONE
*
* \param _db shared pointer to the DataBase object
* \returns OK or INVALID_STATE
*/
ErrorCode ModbusAPI::setDataBase(std::shared_ptr<DataBase> _db) {
if (mState != State::CONFIGURE) {
log::get()->error("ModbusAPI: setDataBase() -- invalid object state '{}'", enum2Str::toStr(mState));
return ErrorCode::INVALID_STATE;
}
if (!_db) { _db = make_shared<DataBase>(SMA_MODBUS_DEFAULT_DB); }
mDB = _db;
return ErrorCode::OK;
}
/*!
* \brief Sets the modbus register database to use
*
* \note This function can only be called in the CONFIGURE state
*
* State change: NONE
*
* \param _dbPath Path to the database file
* \returns OK or INVALID_STATE
*/
ErrorCode ModbusAPI::setDataBase(string _dbPath) {
if (mState != State::CONFIGURE) {
log::get()->error("ModbusAPI: setDataBase() -- invalid object state '{}'", enum2Str::toStr(mState));
return ErrorCode::INVALID_STATE;
}
mDB = make_shared<DataBase>(_dbPath);
return ErrorCode::OK;
}
/*!
* \brief Sets the TCP server connection details
*
* \note This function can only be called in the CONFIGURE state
*
* State change: NONE
*
* \param _ip The IP address to use
* \param _port The port to use
*
* \returns OK or INVALID_STATE
*/
ErrorCode ModbusAPI::setConnectionTCP_IP(string _ip, uint32_t _port) {
if (mState != State::CONFIGURE) {
log::get()->error("ModbusAPI: setConnectionTCP_IP() -- invalid object state '{}'", enum2Str::toStr(mState));
return ErrorCode::INVALID_STATE;
}
mConn = make_unique<MBConnectionIP>(_ip, _port);
return ErrorCode::OK;
}
/*!
* \brief Sets the TCP IP protocol indemendant server connection details
*
* \note This function can only be called in the CONFIGURE state
*
* State change: NONE
*
* \param _node The server node
* \param _service The service
*
* \returns OK or INVALID_STATE
*/
ErrorCode ModbusAPI::setConnectionTCP_IP_PI(string _node, string _service) {
if (mState != State::CONFIGURE) {
log::get()->error("ModbusAPI: setConnectionTCP_IP_PI() -- invalid object state '{}'", enum2Str::toStr(mState));
return ErrorCode::INVALID_STATE;
}
mConn = make_unique<MBConnectionIP_PI>(_node, _service);
return ErrorCode::OK;
}
/*!
* \brief Sets the TCP server connection details
*
* \note This function can only be called in the CONFIGURE state
*
* State change: NONE
*
* \param _device The name of the serial port
* \param _baud The baud rate of the communication
* \param _parity Partity type: N = None; E = Even; O = Odd
* \param _dataBit The number of bits of data, the allowed values are 5, 6, 7 and 8
* \param _stopBit The bits of stop, the allowed values are 1 and 2
*
* \returns OK or INVALID_STATE
*/
ErrorCode ModbusAPI::setConnectionRTU(string _device, uint32_t _baud, char _parity, int _dataBit, int _stopBit) {
if (mState != State::CONFIGURE) {
log::get()->error("ModbusAPI: setConnectionRTU() -- invalid object state '{}'", enum2Str::toStr(mState));
return ErrorCode::INVALID_STATE;
}
mConn = make_unique<MBConnectionRTU>(_device, _baud, _parity, _dataBit, _stopBit);
return ErrorCode::OK;
}
| 31.331155
| 120
| 0.655448
|
mensinda
|
649c19757cdfa81157581520e6f501a82479ee44
| 911
|
cpp
|
C++
|
cpp/src/network/broker-add.cpp
|
zlnov/quick-pack
|
4fffcc56045852b034b60a1185901a001eff87a7
|
[
"MIT"
] | null | null | null |
cpp/src/network/broker-add.cpp
|
zlnov/quick-pack
|
4fffcc56045852b034b60a1185901a001eff87a7
|
[
"MIT"
] | null | null | null |
cpp/src/network/broker-add.cpp
|
zlnov/quick-pack
|
4fffcc56045852b034b60a1185901a001eff87a7
|
[
"MIT"
] | null | null | null |
#include "broker.hpp"
namespace quick_pack{
uint32_t Broker::add_internal_socket(const std::string &p_host, const std::string &p_port, bool p_is_ipv6){
auto sock = new SocketDetail();
sock->bind(p_host, p_port, p_is_ipv6);
return this->m_internal_socket_detail_manager.add_socket(sock);
}
uint32_t Broker::add_external_address(const std::string &p_host, const uint32_t p_port, bool p_is_ipv6){
auto addr = new Address(p_host, p_port, p_is_ipv6);
auto addrdetail = new AddressDetail();
addrdetail->m_address = addr;
return this->m_external_address_detail_manager.add_addressdetail(addrdetail);
}
AddressDetail* Broker::add_new_ipv46_address(sockaddr_in6* addr){
auto addrdetail = new AddressDetail();
auto address = new Address(addr);
addrdetail->m_address=address;
this->m_external_address_detail_manager.add_addressdetail(addrdetail);
return addrdetail;
}
} // namespace quick_pack
| 35.038462
| 107
| 0.782656
|
zlnov
|
64a12540259cae2d8ccbd0733f9f922d530d0f46
| 1,069
|
hpp
|
C++
|
include/bglgen_app.hpp
|
magicmoremagic/bglgen
|
aa47b41a2212d7af9c7121ca036dc87389e10e6d
|
[
"MIT"
] | null | null | null |
include/bglgen_app.hpp
|
magicmoremagic/bglgen
|
aa47b41a2212d7af9c7121ca036dc87389e10e6d
|
[
"MIT"
] | null | null | null |
include/bglgen_app.hpp
|
magicmoremagic/bglgen
|
aa47b41a2212d7af9c7121ca036dc87389e10e6d
|
[
"MIT"
] | null | null | null |
#pragma once
#ifndef BE_BGLGEN_BGLGEN_APP_HPP_
#define BE_BGLGEN_BGLGEN_APP_HPP_
#include "lexer.hpp"
#include <be/core/lifecycle.hpp>
#include <be/core/filesystem.hpp>
#include <be/belua/context.hpp>
#include <be/sqlite/db.hpp>
#include <be/sqlite/static_stmt_cache.hpp>
namespace be::bglgen {
///////////////////////////////////////////////////////////////////////////////
class BglGenApp final {
public:
BglGenApp(int argc, char** argv);
int operator()();
private:
void get_lua_defaults_();
void init_registry_();
void init_extension_regex_();
CoreInitLifecycle init_;
be::I8 status_ = 0;
belua::Context context_;
sqlite::Db db_;
std::unique_ptr<sqlite::StaticStmtCache> cache_;
Path registry_location_;
Path registry_db_location_;
bool rebuild_db_ = false;
std::vector<S> extensions_;
S extension_regex_;
std::vector<std::pair<Path, bool>> search_dirs_;
std::vector<Path> source_paths_;
std::vector<S> lua_chunks_;
bool do_process_ = true;
Path output_location_;
};
} // be::bglgen
#endif
| 20.960784
| 79
| 0.664172
|
magicmoremagic
|
64a179c03a46437a203c78593d8711ecf0484346
| 819
|
cpp
|
C++
|
engine/entity.cpp
|
jarreed0/ArchGE
|
c995caf86b11f89f45fcfe1027c6068662dfcde0
|
[
"Apache-2.0"
] | 12
|
2017-02-09T21:03:41.000Z
|
2021-04-26T14:50:20.000Z
|
engine/entity.cpp
|
jarreed0/ArchGE
|
c995caf86b11f89f45fcfe1027c6068662dfcde0
|
[
"Apache-2.0"
] | null | null | null |
engine/entity.cpp
|
jarreed0/ArchGE
|
c995caf86b11f89f45fcfe1027c6068662dfcde0
|
[
"Apache-2.0"
] | null | null | null |
#include "entity.h"
Entity::Entity() {}
Entity::~Entity() {}
void Entity::damage(double d) {
health -= d;
if(health >= 0) {
health = 0;
kill();
}
}
void Entity::heal(double h) {
health += h;
if(h > maxHealth) {
health = maxHealth;
}
}
void Entity::kill() {
setHealth(0);
deactivate();
}
void Entity::deactivate() {
active = 0;
}
void Entity::activate() {
active = 1;
}
void Entity::checkDisplayable(Object screen) {
Object obj;
obj.setDest(getDetect());
if(col.isTouching(obj, screen)) {
setDisplayable(true);
} else {
setDisplayable(false);
}
}
void Entity::setDetectRange(int r) {
setDetectRange(r, r);
}
void Entity::setDetectRange(int w, int h) {
detect.x = getPosX()-w;
detect.y = getPosY()-h;
detect.w = getPosW()+w+w;
detect.h = getPosH()+h+h;
}
| 16.058824
| 46
| 0.608059
|
jarreed0
|
64a402fb135380ba4476648e6f73fbaabbad02e7
| 1,871
|
cpp
|
C++
|
src/lab_m1/Tema3/SpotLight.cpp
|
octaviantorcea/EGC
|
55dfe03a5be17de1853803a9fde19db7929fdf93
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
src/lab_m1/Tema3/SpotLight.cpp
|
octaviantorcea/EGC
|
55dfe03a5be17de1853803a9fde19db7929fdf93
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
src/lab_m1/Tema3/SpotLight.cpp
|
octaviantorcea/EGC
|
55dfe03a5be17de1853803a9fde19db7929fdf93
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
#include "SpotLight.h"
tema3::SpotLight::SpotLight(glm::vec3 position) {
this->position = position;
this->direction = glm::vec3(0, -1, 0);
this->cutoffAngle = 14.03f;
this->color = glm::vec3((float)(rand() % 256) / 256, (float)(rand() % 256) / 256, (float)(rand() % 256) / 256);
this->intensity = 3.5f;
this->oxAngle = 0;
this->oyAngle = 0;
this->ozAngle = 0;
}
tema3::SpotLight::~SpotLight() {
}
glm::vec3 tema3::SpotLight::getPosition() {
return this->position;
}
glm::vec3 tema3::SpotLight::getDirection() {
return this->direction;
}
float tema3::SpotLight::getCutoffAngle() {
return this->cutoffAngle;
}
glm::vec3 tema3::SpotLight::getColor() {
return this->color;
}
float tema3::SpotLight::getIntensity() {
return this->intensity;
}
float tema3::SpotLight::getOxAngle() {
return this->oxAngle;
}
float tema3::SpotLight::getOyAngle() {
return this->oyAngle;
}
float tema3::SpotLight::getOzAngle() {
return this->ozAngle;
}
void tema3::SpotLight::updateDirection(float deltaTimeSeconds) {
float xSpeed = rand() % 3 - 1;
float ySpeed = rand() % 3 - 1;
float zSpeed = rand() % 3 - 1;
if (oxAngle + xSpeed * deltaTimeSeconds >= MIN_ANGLE && oxAngle + xSpeed * deltaTimeSeconds <= MAX_ANGLE) {
oxAngle += xSpeed * CHANGE_SPEED;
}
if (oyAngle + ySpeed * deltaTimeSeconds >= MIN_ANGLE && oyAngle + ySpeed * deltaTimeSeconds <= MAX_ANGLE) {
oyAngle += ySpeed * CHANGE_SPEED;
}
if (ozAngle + zSpeed * deltaTimeSeconds >= MIN_ANGLE && ozAngle + zSpeed * deltaTimeSeconds <= MAX_ANGLE) {
ozAngle += zSpeed * CHANGE_SPEED;
}
glm::mat4 rotateMatrix = glm::mat4(1);
rotateMatrix *= RotateOX(RADIANS(oxAngle));
rotateMatrix *= RotateOY(RADIANS(oyAngle));
rotateMatrix *= RotateOZ(RADIANS(ozAngle));
this->direction = rotateMatrix * glm::vec4(0, -1, 0, 1);
}
| 25.630137
| 113
| 0.652592
|
octaviantorcea
|
64aa3c32e332ace5f6889bb4d95a5223c541cbe5
| 3,826
|
cpp
|
C++
|
trace_server/dock/dockmanagermodel.cpp
|
mojmir-svoboda/DbgToolkit
|
590887987d0856032be906068a3103b6ce31d21c
|
[
"MIT"
] | null | null | null |
trace_server/dock/dockmanagermodel.cpp
|
mojmir-svoboda/DbgToolkit
|
590887987d0856032be906068a3103b6ce31d21c
|
[
"MIT"
] | null | null | null |
trace_server/dock/dockmanagermodel.cpp
|
mojmir-svoboda/DbgToolkit
|
590887987d0856032be906068a3103b6ce31d21c
|
[
"MIT"
] | null | null | null |
#include "dockmanagermodel.h"
#include <QString>
#include <QMainWindow>
#include "dockmanager.h"
#include "dock.h"
DockManagerModel::DockManagerModel (DockManager & mgr, QObject * parent, tree_data_t * data)
: TreeModel<DockedInfo>(parent, data)
, m_manager(mgr)
{
qDebug("%s", __FUNCTION__);
}
DockManagerModel::~DockManagerModel ()
{
qDebug("%s", __FUNCTION__);
}
QModelIndex DockManagerModel::testItemWithPath (QStringList const & path)
{
QString const name = path.join("/");
DockedInfo const * i = 0;
if (node_t const * node = m_tree_data->is_present(name, i))
return indexFromItem(node);
else
return QModelIndex();
}
QModelIndex DockManagerModel::insertItemWithPath (QStringList const & path, bool checked)
{
QString const name = path.join("/");
DockedInfo const * i = 0;
node_t const * node = m_tree_data->is_present(name, i);
if (node)
{
//qDebug("%s path=%s already present", __FUNCTION__, path.toStdString().c_str());
return indexFromItem(node);
}
else
{
//qDebug("%s path=%s not present, adding", __FUNCTION__, path.toStdString().c_str());
DockedInfo i;
i.m_state = checked ? Qt::Checked : Qt::Unchecked;
i.m_collapsed = false;
//i.m_path = path;
node_t * const n = m_tree_data->set_to_state(name, i);
QModelIndex const parent_idx = indexFromItem(n->parent);
int const last = n->parent->count_childs() - 1;
beginInsertRows(parent_idx, last, last);
n->data.m_path = path;
QModelIndex const idx = indexFromItem(n);
endInsertRows();
initData(idx, checked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole);
//QModelIndex const parent_idx = idx.parent();
//if (parent_idx.isValid())
// emit dataChanged(parent_idx, parent_idx);
return idx;
}
}
int DockManagerModel::columnCount (QModelIndex const & parent) const
{
return DockManager::e_max_dockmgr_column;
}
Qt::ItemFlags DockManagerModel::flags (QModelIndex const & index) const
{
return QAbstractItemModel::flags(index)
| Qt::ItemIsEnabled
| Qt::ItemIsUserCheckable
| Qt::ItemIsSelectable;
}
/*DockedWidgetBase const * DockManagerModel::getWidgetFromIndex (QModelIndex const & index) const
{
DockManager const * const mgr = static_cast<DockManager const *>(QObject::parent());
node_t const * const item = itemFromIndex(index);
QStringList const & p = item->data.m_path;
DockedWidgetBase const * const dwb = m_manager.findDockable(p.join("/"));
return dwb;
}
DockedWidgetBase * DockManagerModel::getWidgetFromIndex (QModelIndex const & index)
{
DockManager * const mgr = static_cast<DockManager *>(QObject::parent());
node_t const * const item = itemFromIndex(index);
QStringList const & p = item->data.m_path;
DockedWidgetBase * dwb = m_manager.findDockable(p.join("/"));
return dwb;
}*/
QVariant DockManagerModel::data (QModelIndex const & index, int role) const
{
if (!index.isValid())
return QVariant();
int const col = index.column();
if (col == DockManager::e_Column_Name)
return TreeModel<DockedInfo>::data(index, role);
return QVariant();
}
bool DockManagerModel::setData (QModelIndex const & index, QVariant const & value, int role)
{
if (!index.isValid()) return false;
if (role == Qt::CheckStateRole)
{
node_t const * const n = itemFromIndex(index);
QStringList const & dst = n->data.m_path;
Action a;
a.m_type = e_Visibility;
a.m_src_path = m_manager.path();
a.m_src = &m_manager;
a.m_dst_path = dst;
int const state = value.toInt();
a.m_args.push_back(state);
m_manager.handleAction(&a, e_Sync);
}
return TreeModel<DockedInfo>::setData(index, value, role);
}
bool DockManagerModel::initData (QModelIndex const & index, QVariant const & value, int role)
{
return TreeModel<DockedInfo>::setData(index, value, role);
}
bool DockManagerModel::removeRows (int row, int count, QModelIndex const & parent)
{
return true;
}
| 27.724638
| 97
| 0.717721
|
mojmir-svoboda
|
64b2ee47e183ef510bfa1b03149072d61a16d279
| 2,118
|
cpp
|
C++
|
AnimationEditor/Model.cpp
|
RavioliFinoli/AnimationEditor
|
d106371c1307661611d6783d8891e9ac52ffd1a9
|
[
"MIT"
] | null | null | null |
AnimationEditor/Model.cpp
|
RavioliFinoli/AnimationEditor
|
d106371c1307661611d6783d8891e9ac52ffd1a9
|
[
"MIT"
] | null | null | null |
AnimationEditor/Model.cpp
|
RavioliFinoli/AnimationEditor
|
d106371c1307661611d6783d8891e9ac52ffd1a9
|
[
"MIT"
] | null | null | null |
#include "Model.h"
#define CLIP(x) (x.clip)
namespace AE
{
Model::Model()
{
using namespace DirectX;
m_InputLayout->Release();
m_VertexBuffer->Release();
m_Translation = { 0.0f, 0.0f, 0.0f, 1.0f };
m_RotationQuaternion = { 0.0f, 0.0f, 0.0f, 1.0f };
m_Scale = { 1.0f, 1.0f, 1.0f, 0.0f };
XMStoreFloat4x4A(&m_WorldMatrix, XMMatrixIdentity());
}
Model::Model(const ComPtr<ID3D11Buffer>& buffer, const ComPtr<ID3D11InputLayout>& layout, uint32_t vertexCount) : m_VertexBuffer(buffer), m_InputLayout(layout), m_VertexCount(vertexCount)
{
using namespace DirectX;
m_Translation = {0.0f, 0.0f, 0.0f, 1.0f};
m_RotationQuaternion = {0.0f, 0.0f, 0.0f, 1.0f};
m_Scale = {1.0f, 1.0f, 1.0f, 0.0f};
XMStoreFloat4x4A(&m_WorldMatrix, XMMatrixIdentity());
}
Model::~Model()
{
}
void Model::SetPosition(DirectX::XMFLOAT4A newPosition)
{
m_Translation = newPosition;
}
void Model::SetRotation(DirectX::XMFLOAT4A newRotation)
{
m_RotationQuaternion = newRotation;
}
void Model::SetScale(float newScale)
{
m_Scale = { newScale, newScale, newScale, 0.0 };
}
void Model::SetVertexBuffer(const ComPtr<ID3D11Buffer>& buffer)
{
m_VertexBuffer = buffer;
}
void Model::SetVertexCount(uint32_t count)
{
m_VertexCount = count;
}
void Model::SetVertexLayout(const ComPtr<ID3D11InputLayout>& layout)
{
m_InputLayout = layout;
}
DirectX::XMFLOAT4X4A Model::GetWorldMatrix()
{
using namespace DirectX;
XMVECTOR t = XMLoadFloat4A(&m_Translation);
XMVECTOR r = XMLoadFloat4A(&m_RotationQuaternion);
XMVECTOR s = XMLoadFloat4A(&m_Scale);
XMStoreFloat4x4A(&m_WorldMatrix, DirectX::XMMatrixAffineTransformation(s, XMVectorZero(), r, t));
return m_WorldMatrix;
}
const ComPtr<ID3D11Buffer>& Model::GetVertexBuffer()
{
return m_VertexBuffer;
}
uint32_t Model::GetVertexCount()
{
return m_VertexCount;
}
float Model::GetScale()
{
return m_Scale.x;
}
void Model::ToggleDrawState()
{
m_bDraw = !m_bDraw;
}
void Model::SetDrawState(bool state)
{
m_bDraw = state;
}
bool Model::GetDrawState()
{
return m_bDraw;
}
}
| 19.611111
| 188
| 0.695467
|
RavioliFinoli
|
64cbbd932adae5e4ba8c99bedcf37305053e919f
| 1,129
|
hpp
|
C++
|
ch12/Queue.hpp
|
bashell/CppStandardLibrary
|
2aae03019288132c911036aeb9ba36edc56e510b
|
[
"MIT"
] | null | null | null |
ch12/Queue.hpp
|
bashell/CppStandardLibrary
|
2aae03019288132c911036aeb9ba36edc56e510b
|
[
"MIT"
] | null | null | null |
ch12/Queue.hpp
|
bashell/CppStandardLibrary
|
2aae03019288132c911036aeb9ba36edc56e510b
|
[
"MIT"
] | null | null | null |
#ifndef QUEUE_HPP
#define QUEUE_HPP
#include <deque>
#include <exception>
template <typename T>
class Queue {
protected:
std::deque<T> c; // container for the elements
public:
// exception class for pop() and front() with empty queue
class ReadEmptyQueue : public std::exception {
public:
virtual const char* what() const throw() {
return "read empty queue";
}
};
// number of elements
typename std::deque<T>::size_type size() const {
return c.size();
}
// is queue empty?
bool empty() const {
return c.empty();
}
// insert element into the queue
void push(const T &elem) {
c.push_back(elem);
}
// remove next element from the queue and return its value
T pop() {
if(c.empty()) {
throw ReadEmptyQueue();
}
T elem(c.front());
c.pop_front();
return elem;
}
// return value of next element
T& front() {
if(c.empty()) {
throw ReadEmptyQueue();
}
return c.front();
}
};
#endif /* QUEUE_HPP */
| 20.160714
| 62
| 0.545616
|
bashell
|
64cbf46dc282a5b8b420948d0cb48f6f1718aa3b
| 5,764
|
cpp
|
C++
|
src/Broadcaster2006/Manager/HDView.cpp
|
pedroroque/DigitalBroadcaster
|
279e65b348421dcd8db53ebb588154b85dc169e9
|
[
"MIT"
] | null | null | null |
src/Broadcaster2006/Manager/HDView.cpp
|
pedroroque/DigitalBroadcaster
|
279e65b348421dcd8db53ebb588154b85dc169e9
|
[
"MIT"
] | null | null | null |
src/Broadcaster2006/Manager/HDView.cpp
|
pedroroque/DigitalBroadcaster
|
279e65b348421dcd8db53ebb588154b85dc169e9
|
[
"MIT"
] | null | null | null |
// HDView.cpp : implementation file
//
#include "stdafx.h"
#include "Manager.h"
#include "HDView.h"
#include "Folder.h"
#include "..\include\rspath.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern CString g_strMainConnect;
extern CImageList *g_ilTree;
/////////////////////////////////////////////////////////////////////////////
// CHDView
IMPLEMENT_DYNCREATE(CHDView, CListView)
CHDView::CHDView()
{
}
CHDView::~CHDView()
{
}
BEGIN_MESSAGE_MAP(CHDView, CListView)
//{{AFX_MSG_MAP(CHDView)
ON_WM_CREATE()
ON_NOTIFY_REFLECT(NM_DBLCLK, OnDblclk)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CHDView drawing
void CHDView::OnDraw(CDC* pDC)
{
CDocument* pDoc = GetDocument();
// TODO: add draw code here
}
/////////////////////////////////////////////////////////////////////////////
// CHDView diagnostics
#ifdef _DEBUG
void CHDView::AssertValid() const
{
CListView::AssertValid();
}
void CHDView::Dump(CDumpContext& dc) const
{
CListView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CHDView message handlers
void CHDView::OnInitialUpdate()
{
CListView::OnInitialUpdate();
CListCtrl *pList = &GetListCtrl();
CString strTemp;
strTemp.LoadString(IDS_FOLDERMANAGMENT);
GetDocument()->SetTitle(strTemp);
strTemp.LoadString(IDS_PATH);
pList->InsertColumn(1,strTemp,LVCFMT_LEFT,250);
strTemp.LoadString(IDS_MUSIC);
pList->InsertColumn(2,strTemp,LVCFMT_CENTER,50);
strTemp.LoadString(IDS_JINGLES);
pList->InsertColumn(3,strTemp,LVCFMT_CENTER,50);
strTemp.LoadString(IDS_SPOTS);
pList->InsertColumn(4,strTemp,LVCFMT_CENTER,50);
strTemp.LoadString(IDS_RMS);
pList->InsertColumn(5,strTemp,LVCFMT_CENTER,50);
strTemp.LoadString(IDS_TAKES);
pList->InsertColumn(5,strTemp,LVCFMT_CENTER,50);
strTemp.LoadString(IDS_TIME);
pList->InsertColumn(6,strTemp,LVCFMT_CENTER,50);
strTemp.LoadString(IDS_PRODUCER);
pList->InsertColumn(7,strTemp,LVCFMT_CENTER,50);
CRSPath rs(g_strMainConnect);
int Pos=0;
rs.m_strSort="Music desc, Jingles desc, Spots desc, RMs desc, Takes desc, timesignal desc, producer desc, Path";
rs.Open();
while( !rs.IsEOF() )
{
rs.m_Path.TrimRight();
pList->InsertItem(Pos,rs.m_Path,22);
pList->SetItemData(Pos,rs.m_ID);
if( rs.m_Music )
pList->SetItem(Pos,1,LVIF_IMAGE,"",17,0,0,0);
if( rs.m_Jingles )
pList->SetItem(Pos,2,LVIF_IMAGE,"",4,0,0,0);
if( rs.m_Spots )
pList->SetItem(Pos,3,LVIF_IMAGE,"",1,0,0,0);
if( rs.m_RMs )
pList->SetItem(Pos,4,LVIF_IMAGE,"",9,0,0,0);
if( rs.m_Takes )
pList->SetItem(Pos,5,LVIF_IMAGE,"",5,0,0,0);
if( rs.m_TimeSignal )
pList->SetItem(Pos,6,LVIF_IMAGE,"",3,0,0,0);
if( rs.m_Producer )
pList->SetItem(Pos,7,LVIF_IMAGE,"",7,0,0,0);
rs.MoveNext();
Pos++;
}
}
int CHDView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
lpCreateStruct->style|=LVS_REPORT|LVS_SINGLESEL|LVS_SHOWSELALWAYS;
if (CListView::OnCreate(lpCreateStruct) == -1)
return -1;
CListCtrl *pList = &GetListCtrl();
pList->SetImageList(g_ilTree,LVSIL_SMALL);
ListView_SetExtendedListViewStyleEx(this->m_hWnd,LVS_EX_SUBITEMIMAGES|LVS_EX_FULLROWSELECT,LVS_EX_SUBITEMIMAGES|LVS_EX_FULLROWSELECT);
return 0;
}
void CHDView::OnDblclk(NMHDR* pNMHDR, LRESULT* pResult)
{
CListCtrl *pList = &GetListCtrl();
int nPos = pList->GetNextItem(-1,LVNI_SELECTED);
if( nPos == -1 )
return;
long int lID = pList->GetItemData(nPos);
CRSPath rs( g_strMainConnect );
CFolder dlg;
rs.m_strFilter.Format("ID = '%d'",lID);
rs.Open();
dlg.m_strPath = rs.m_Path;
dlg.m_strPath.TrimRight();
dlg.m_bJingles = rs.m_Jingles;
dlg.m_bMusic = rs.m_Music;
dlg.m_bProducer = rs.m_Producer;
dlg.m_bRMs = rs.m_RMs;
dlg.m_bSpots = rs.m_Spots;
dlg.m_bTakes = rs.m_Takes;
dlg.m_bTime = rs.m_TimeSignal;
if( dlg.DoModal()==IDOK )
{
rs.Edit();
rs.m_Path = dlg.m_strPath;
rs.m_Jingles = (dlg.m_bJingles==0) ? 0:1;
rs.m_Music = (dlg.m_bMusic==0) ? 0:1;
rs.m_Producer = (dlg.m_bProducer==0) ? 0:1;
rs.m_RMs = (dlg.m_bRMs==0) ? 0:1;
rs.m_Spots = (dlg.m_bSpots==0) ? 0:1;
rs.m_Takes = (dlg.m_bTakes==0) ? 0:1;
rs.m_TimeSignal = (dlg.m_bTime==0) ? 0:1;
rs.Update();
Refresh();
}
if( pResult!=NULL )
*pResult = 0;
}
void CHDView::Refresh()
{
CListCtrl *pList = &GetListCtrl();
pList->DeleteAllItems();
CRSPath rs(g_strMainConnect);
int Pos=0;
rs.m_strSort="Music desc, Jingles desc, Spots desc, RMs desc, Takes desc, timesignal desc, producer desc, Path";
rs.Open();
while( !rs.IsEOF() )
{
rs.m_Path.TrimRight();
pList->InsertItem(Pos,rs.m_Path,22);
pList->SetItemData(Pos,rs.m_ID);
if( rs.m_Music )
pList->SetItem(Pos,1,LVIF_IMAGE,"",17,0,0,0);
if( rs.m_Jingles )
pList->SetItem(Pos,2,LVIF_IMAGE,"",4,0,0,0);
if( rs.m_Spots )
pList->SetItem(Pos,3,LVIF_IMAGE,"",1,0,0,0);
if( rs.m_RMs )
pList->SetItem(Pos,4,LVIF_IMAGE,"",9,0,0,0);
if( rs.m_Takes )
pList->SetItem(Pos,5,LVIF_IMAGE,"",5,0,0,0);
if( rs.m_TimeSignal )
pList->SetItem(Pos,6,LVIF_IMAGE,"",3,0,0,0);
if( rs.m_Producer )
pList->SetItem(Pos,7,LVIF_IMAGE,"",7,0,0,0);
rs.MoveNext();
Pos++;
}
}
void CHDView::AddFolder()
{
CFolder dlg;
if( dlg.DoModal()==IDOK )
{
CRSPath rs( g_strMainConnect );
rs.Open();
rs.AddNew();
rs.m_Path = dlg.m_strPath;
rs.m_Jingles = (dlg.m_bJingles==0) ? 0:1;
rs.m_Music = (dlg.m_bMusic==0) ? 0:1;
rs.m_Producer = (dlg.m_bProducer==0) ? 0:1;
rs.m_RMs = (dlg.m_bRMs==0) ? 0:1;
rs.m_Spots = (dlg.m_bSpots==0) ? 0:1;
rs.m_Takes = (dlg.m_bTakes==0) ? 0:1;
rs.m_TimeSignal = (dlg.m_bTime==0) ? 0:1;
rs.Update();
rs.Close();
Refresh();
}
}
| 21.669173
| 135
| 0.6466
|
pedroroque
|
64ce8846ecf5e0b61a7aced169974e31679ab830
| 533
|
hpp
|
C++
|
include/ampi/coro/stdcoro.hpp
|
palebedev/ampi
|
a7feb7f4b51469fd24ff0fa2c8a9b8592cbf309a
|
[
"Apache-2.0"
] | null | null | null |
include/ampi/coro/stdcoro.hpp
|
palebedev/ampi
|
a7feb7f4b51469fd24ff0fa2c8a9b8592cbf309a
|
[
"Apache-2.0"
] | null | null | null |
include/ampi/coro/stdcoro.hpp
|
palebedev/ampi
|
a7feb7f4b51469fd24ff0fa2c8a9b8592cbf309a
|
[
"Apache-2.0"
] | 1
|
2021-03-30T15:49:55.000Z
|
2021-03-30T15:49:55.000Z
|
// Copyright 2021 Pavel A. Lebedev
// Licensed under the Apache License, Version 2.0.
// (See accompanying file LICENSE.txt or copy at
// http://www.apache.org/licenses/LICENSE-2.0)
// SPDX-License-Identifier: Apache-2.0
#ifndef UUID_2B9E0A06_885B_41B9_B4DB_2D184249766E
#define UUID_2B9E0A06_885B_41B9_B4DB_2D184249766E
#if __has_include(<coroutine>)
#include <coroutine>
namespace ampi { namespace stdcoro = std; }
#else
#include <experimental/coroutine>
namespace ampi { namespace stdcoro = std::experimental; }
#endif
#endif
| 28.052632
| 57
| 0.778612
|
palebedev
|
64d87c98347348152c2e9be766e005bdba090924
| 4,085
|
cpp
|
C++
|
rai/GeoOptim/geoOptim.cpp
|
bgheneti/rai
|
4ac7c8444da0c30b141cf40ffed4414ef1ca3e81
|
[
"MIT"
] | null | null | null |
rai/GeoOptim/geoOptim.cpp
|
bgheneti/rai
|
4ac7c8444da0c30b141cf40ffed4414ef1ca3e81
|
[
"MIT"
] | null | null | null |
rai/GeoOptim/geoOptim.cpp
|
bgheneti/rai
|
4ac7c8444da0c30b141cf40ffed4414ef1ca3e81
|
[
"MIT"
] | null | null | null |
/* ------------------------------------------------------------------
Copyright (c) 2017 Marc Toussaint
email: marc.toussaint@informatik.uni-stuttgart.de
This code is distributed under the MIT License.
Please see <root-path>/LICENSE for details.
-------------------------------------------------------------- */
#include <Optim/constrained.h>
#include "geoOptim.h"
void fitSSBox(arr& x, double& f, double& g, const arr& X, int verbose) {
struct fitSSBoxProblem : ConstrainedProblem {
const arr& X;
fitSSBoxProblem(const arr& X):X(X) {}
void phi(arr& phi, arr& J, arr& H, ObjectiveTypeA& tt, const arr& x, arr& lambda) {
phi.resize(5+X.d0);
if(!!tt) { tt.resize(5+X.d0); tt=OT_ineq; }
if(!!J) { J.resize(5+X.d0,11); J.setZero(); }
if(!!H) { H.resize(11,11); H.setZero(); }
//-- the scalar objective
double a=x(0), b=x(1), c=x(2), r=x(3); //these are box-wall-coordinates --- not WIDTH!
phi(0) = a*b*c + 2.*r*(a*b + a*c +b*c) + 4./3.*r*r*r;
if(!!tt) tt(0) = OT_f;
if(!!J) {
J(0,0) = b*c + 2.*r*(b+c);
J(0,1) = a*c + 2.*r*(a+c);
J(0,2) = a*b + 2.*r*(a+b);
J(0,3) = 2.*(a*b + a*c +b*c) + 4.*r*r;
}
if(!!H) {
H(0,1) = H(1,0) = c + 2.*r;
H(0,2) = H(2,0) = b + 2.*r;
H(0,3) = H(3,0) = 2.*(b+c);
H(1,2) = H(2,1) = a + 2.*r;
H(1,3) = H(3,1) = 2.*(a+c);
H(2,3) = H(3,2) = 2.*(a+b);
H(3,3) = 8.*r;
}
//-- positive
double w=100.;
phi(1) = -w*(a-.001);
phi(2) = -w*(b-.001);
phi(3) = -w*(c-.001);
phi(4) = -w*(r-.001);
if(!!J) {
J(1,0) = -w;
J(2,1) = -w;
J(3,2) = -w;
J(4,3) = -w;
}
//-- all constraints
for(uint i=0; i<X.d0; i++) {
arr y, Jy;
y = X[i];
y.append(x);
phi(i+5) = DistanceFunction_SSBox(Jy, NoArr, y);
// Jy({3,5})() *= -1.;
if(!!J) J[i+5] = Jy({3,-1});
}
}
} F(X);
//initialization
x.resize(11);
rai::Quaternion rot;
rot.setRandom();
arr tX = X * rot.getArr(); //rotate points (with rot^{-1})
arr ma = max(tX,0), mi = min(tX,0); //get coordinate-wise min and max
x({0,2})() = (ma-mi)/2.; //sizes
x(3) = 1.; //sum(ma-mi)/6.; //radius
x({4,6})() = rot.getArr() * (mi+.5*(ma-mi)); //center (rotated back)
x({7,10})() = conv_quat2arr(rot);
rndGauss(x({7,10})(), .1, true);
x({7,10})() /= length(x({7,10})());
if(verbose>1) {
checkJacobianCP(F, x, 1e-4);
checkHessianCP(F, x, 1e-4);
}
OptConstrained opt(x, NoArr, F, OPT(
stopTolerance = 1e-4,
stopFTolerance = 1e-3,
damping=1,
maxStep=-1,
constrainedMethod = augmentedLag,
aulaMuInc = 1.1
));
opt.run();
if(verbose>1) {
checkJacobianCP(F, x, 1e-4);
checkHessianCP(F, x, 1e-4);
}
f = opt.L.get_costs();
g = opt.L.get_sumOfGviolations();
}
void computeOptimalSSBox(rai::Mesh& mesh, arr& x_ret, rai::Transformation& t_ret, const arr& X, uint trials, int verbose) {
if(!X.N) { mesh.clear(); return; }
arr x,x_best;
double f,g, f_best, g_best;
fitSSBox(x_best, f_best, g_best, X, verbose);
for(uint k=1; k<trials; k++) {
fitSSBox(x, f, g, X, verbose);
if(g<g_best-1e-4 ||
(g<1e-4 && f<f_best)) { x_best=x; f_best=f; g_best=g; }
}
x = x_best;
//convert box wall coordinates to box width (incl radius)
x(0) = 2.*(x(0)+x(3));
x(1) = 2.*(x(1)+x(3));
x(2) = 2.*(x(2)+x(3));
if(x_ret!=NoArr)
x_ret=x;
if(verbose>2) {
cout <<"x=" <<x;
cout <<"\nf = " <<f_best <<"\ng-violations = " <<g_best <<endl;
}
rai::Transformation t;
t.setZero();
t.pos.set(x({4,6}));
t.rot.set(x({7,-1}));
t.rot.normalize();
mesh.setSSBox(x(0), x(1), x(2), x(3));
t.applyOnPointArray(mesh.V);
if(t_ret!=NoTransformation)
t_ret = t;
}
| 27.979452
| 123
| 0.4541
|
bgheneti
|
64db3a57e57ff0f5e78c5cec2c324e672ce06a6d
| 1,172
|
cpp
|
C++
|
Helios/src/Window.cpp
|
rgracari/helio_test
|
2d516d16da4252c8f92f5c265b6151c6e87bc907
|
[
"Apache-2.0"
] | null | null | null |
Helios/src/Window.cpp
|
rgracari/helio_test
|
2d516d16da4252c8f92f5c265b6151c6e87bc907
|
[
"Apache-2.0"
] | null | null | null |
Helios/src/Window.cpp
|
rgracari/helio_test
|
2d516d16da4252c8f92f5c265b6151c6e87bc907
|
[
"Apache-2.0"
] | null | null | null |
#include "Window.hpp"
namespace Helio
{
Window::Window(const std::string& windowName)
{
Init();
std::cout << "Window Created" << std::endl;
window = SDL_CreateWindow(
windowName.c_str(),
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
640,
480,
SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if (window == NULL)
std::cout << "Could not create window: " << SDL_GetError() << std::endl;;
}
void Window::Init()
{
std::cout << "SDL INIT" << std::endl;
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
std::cout << "SDL could not initialize! SDL Error: " << SDL_GetError() << std::endl;
}
std::cout << "IMAGESDL INIT" << std::endl;
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
std::cout << "SDL_image could not initialize! SDL_image Error: " << SDL_GetError() << std::endl;
}
}
SDL_Window* Window::GetSDLWindow()
{
return window;
}
Window::~Window()
{
std::cout << "Window Destroyed" << std::endl;
if (window != NULL)
{
SDL_DestroyWindow(window);
window = NULL;
}
std::cout << "IMGSDL QUIT" << std::endl;
IMG_Quit();
std::cout << "SDL QUIT" << std::endl;
SDL_Quit();
}
}
| 20.561404
| 99
| 0.617747
|
rgracari
|
64e59e601ecc79a53e407c06f521aeee35395376
| 180
|
cpp
|
C++
|
src/sfHelperControl.cpp
|
ArthurClemens/SoundField
|
645f0a421ba719f253938c030dd1b4feb7ee6097
|
[
"MIT"
] | 2
|
2018-07-02T04:00:02.000Z
|
2020-02-19T09:04:40.000Z
|
src/sfHelperControl.cpp
|
ArthurClemens/SoundField
|
645f0a421ba719f253938c030dd1b4feb7ee6097
|
[
"MIT"
] | null | null | null |
src/sfHelperControl.cpp
|
ArthurClemens/SoundField
|
645f0a421ba719f253938c030dd1b4feb7ee6097
|
[
"MIT"
] | null | null | null |
#include "sfHelperControl.h"
void sfHelperControl::setLoc(ofPoint inLoc) {
loc = inLoc;
}
void sfHelperControl::setClickLoc(ofPoint inClickLoc) {
offset = inClickLoc - loc;
}
| 16.363636
| 55
| 0.744444
|
ArthurClemens
|
64f98d0fa33a59839306941618e3547b1c8a5b20
| 1,263
|
hpp
|
C++
|
topbar.hpp
|
mehhdiii/OOP-Game-City-Builder-CS-224-Spring-2020
|
91d74519505cb39b551a6fd18485516dbac2ec9c
|
[
"FTL"
] | 1
|
2022-01-14T01:31:33.000Z
|
2022-01-14T01:31:33.000Z
|
topbar.hpp
|
mehhdiii/OOP-Game-City-Builder-CS-224-Spring-2020
|
91d74519505cb39b551a6fd18485516dbac2ec9c
|
[
"FTL"
] | null | null | null |
topbar.hpp
|
mehhdiii/OOP-Game-City-Builder-CS-224-Spring-2020
|
91d74519505cb39b551a6fd18485516dbac2ec9c
|
[
"FTL"
] | 2
|
2020-07-25T07:59:54.000Z
|
2022-03-29T02:35:51.000Z
|
#include "SDL.h"
#include "unit.hpp"
#include<string>
#include<iostream>
#include<vector>
#include"draw_text.hpp"
#pragma once
class Topbar: public Unit{
private:
int number_of_bars=4; // different number of sliders we can have
int transition_in_stat_sprite =5; // indicates the number of states a slider can be in
int cash; //all cash
std::vector<std::vector<SDL_Texture*>> stats_sprite; //all slider sprites
SDL_Rect cash_mover; //cash slider mover
SDL_Rect greenenergy_mover; //green energy slider mover
SDL_Rect xplevel_mover; //xp level slider mover
SDL_Rect oxygenlevel_mover; //oxygen level slider mover
const int SPRITE_W = 103; //sliders width
const int SPRITE_H = 32; //sliders height
//text rendering objects
std::vector<Draw_text*> text_objects;
// SDL_Rect cash_mover; //size of the object to draw on screen
void setRect(); //cropping out the sprite from the sheet
public:
Topbar(SDL_Texture*);
~Topbar();
void draw(SDL_Renderer*);
void draw_modified(SDL_Renderer*, int &, int &, int &, int &);
void update_bars(int , int, int, int);
void add_static_sprite(SDL_Texture*, int sprite_color);
};
| 34.135135
| 95
| 0.669834
|
mehhdiii
|
8f01886c94162a358ee1a2c2033f824f111a561f
| 701
|
cpp
|
C++
|
tests/src/ScopedTimerTests.cpp
|
TemporalResearch/trlang
|
3bfb98e074cfcfd7f3f3dfe49afc7931f2366405
|
[
"MIT"
] | null | null | null |
tests/src/ScopedTimerTests.cpp
|
TemporalResearch/trlang
|
3bfb98e074cfcfd7f3f3dfe49afc7931f2366405
|
[
"MIT"
] | null | null | null |
tests/src/ScopedTimerTests.cpp
|
TemporalResearch/trlang
|
3bfb98e074cfcfd7f3f3dfe49afc7931f2366405
|
[
"MIT"
] | null | null | null |
//
// Created by Michael Lynch on 21/06/2021.
//
#include <trlang/timers/ScopedTimer.hpp>
#include <auto_test.hpp>
#include <catch2/catch.hpp>
TRL_TIMER_GROUP(
TEST_1,
TEST_2);
TEST_CASE("shouldDoSomething", "[ManualTest]")
{
trl::ScopedTimer<>::initTimers();
{
trl::ScopedTimer<> timer(trl::timer_group::TEST_1);
std::cout << "Hello world" << std::endl;
}
{
trl::ScopedTimer<> timer(trl::timer_group::TEST_2);
std::cout << "Different words" << std::endl;
}
{
trl::ScopedTimer<> timer(trl::timer_group::TEST_1);
std::cout << "Yet other words" << std::endl;
}
trl::ScopedTimer<>::printInfo();
}
| 18.447368
| 59
| 0.584879
|
TemporalResearch
|
8f09e9b0635be12ac9421df7c5e8dc6a531570c3
| 4,418
|
hpp
|
C++
|
Test/Service/Memory/Memory/Test/PoolShared.hpp
|
KonstantinTomashevich/Emergence
|
83b1d52bb62bf619f9402e3081dd9de6b0cb232c
|
[
"Apache-2.0"
] | 3
|
2021-06-02T05:06:48.000Z
|
2022-01-26T09:39:44.000Z
|
Test/Service/Memory/Memory/Test/PoolShared.hpp
|
KonstantinTomashevich/Emergence
|
83b1d52bb62bf619f9402e3081dd9de6b0cb232c
|
[
"Apache-2.0"
] | null | null | null |
Test/Service/Memory/Memory/Test/PoolShared.hpp
|
KonstantinTomashevich/Emergence
|
83b1d52bb62bf619f9402e3081dd9de6b0cb232c
|
[
"Apache-2.0"
] | null | null | null |
#include <vector>
#include <Testing/Testing.hpp>
namespace Emergence::Memory::Test::Pool
{
struct TestItem
{
uint64_t integer;
float floating;
bool flag;
};
template <typename Pool>
struct FullPoolContext
{
static constexpr std::size_t PAGE_CAPACITY = 8u;
static constexpr std::size_t PAGES_TO_FILL = 2u;
FullPoolContext<Pool> ()
{
for (std::size_t index = 0u; index < PAGES_TO_FILL * PAGE_CAPACITY; ++index)
{
items.emplace_back (pool.Acquire ());
}
CHECK_EQUAL (pool.GetAllocatedSpace (), PAGES_TO_FILL * PAGE_CAPACITY * sizeof (TestItem));
}
Pool pool {sizeof (TestItem), PAGE_CAPACITY};
std::vector<void *> items;
};
template <typename Pool>
void AcquireNotNull ()
{
Pool pool {sizeof (TestItem)};
CHECK (pool.Acquire ());
}
template <typename Pool>
void MultipleAcquiresDoNotOverlap ()
{
Pool pool {sizeof (TestItem)};
auto *first = static_cast<TestItem *> (pool.Acquire ());
auto *second = static_cast<TestItem *> (pool.Acquire ());
TestItem firstValue = {12, 341.55f, false};
TestItem secondValue = {59, 947.11f, true};
*first = firstValue;
*second = secondValue;
CHECK_EQUAL (firstValue.integer, first->integer);
CHECK_EQUAL (firstValue.floating, first->floating);
CHECK_EQUAL (firstValue.flag, first->flag);
CHECK_EQUAL (secondValue.integer, second->integer);
CHECK_EQUAL (secondValue.floating, second->floating);
CHECK_EQUAL (secondValue.flag, second->flag);
}
template <typename Pool>
void MemoryReused ()
{
Pool pool {sizeof (TestItem)};
void *item = pool.Acquire ();
pool.Release (item);
void *anotherItem = pool.Acquire ();
CHECK_EQUAL (item, anotherItem);
}
template <typename Pool>
void Clear ()
{
FullPoolContext<Pool> context;
context.pool.Clear ();
CHECK_EQUAL (context.pool.GetAllocatedSpace (), 0u);
// Acquire one item to ensure that pool is in working state.
CHECK (context.pool.Acquire ());
}
template <typename Pool>
void Move ()
{
FullPoolContext<Pool> context;
Pool newPool (std::move (context.pool));
CHECK_EQUAL (context.pool.GetAllocatedSpace (), 0u);
CHECK_EQUAL (newPool.GetAllocatedSpace (),
FullPoolContext<Pool>::PAGES_TO_FILL * FullPoolContext<Pool>::PAGE_CAPACITY * sizeof (TestItem));
// Acquire one item from each pool to ensure that they are in working state.
CHECK (context.pool.Acquire ());
CHECK (newPool.Acquire ());
}
template <typename Pool>
void MoveAssign ()
{
FullPoolContext<Pool> firstContext;
FullPoolContext<Pool> secondContext;
secondContext.pool = std::move (firstContext.pool);
CHECK_EQUAL (firstContext.pool.GetAllocatedSpace (), 0u);
CHECK_EQUAL (secondContext.pool.GetAllocatedSpace (),
FullPoolContext<Pool>::PAGES_TO_FILL * FullPoolContext<Pool>::PAGE_CAPACITY * sizeof (TestItem));
// Acquire one item from each pool to ensure that they are in working state.
CHECK (firstContext.pool.Acquire ());
CHECK (secondContext.pool.Acquire ());
}
} // namespace Emergence::Memory::Test::Pool
#define SHARED_POOL_TEST(ImplementationClass, TestName) \
TEST_CASE (TestName) \
{ \
Emergence::Memory::Test::Pool::TestName<ImplementationClass> (); \
}
#define ALL_SHARED_POOL_TESTS(ImplementationClass) \
SHARED_POOL_TEST (ImplementationClass, AcquireNotNull) \
SHARED_POOL_TEST (ImplementationClass, MultipleAcquiresDoNotOverlap) \
SHARED_POOL_TEST (ImplementationClass, MemoryReused) \
SHARED_POOL_TEST (ImplementationClass, Clear) \
SHARED_POOL_TEST (ImplementationClass, Move) \
SHARED_POOL_TEST (ImplementationClass, MoveAssign)
| 33.984615
| 120
| 0.585785
|
KonstantinTomashevich
|
557ce8f8b281fcc504e999b28331a0bac59a68a2
| 1,653
|
cpp
|
C++
|
thirdparty/AngelCode/sdk/tests/test_build_performance/source/test_basic.cpp
|
kcat/XLEngine
|
0e735ad67fa40632add3872e0cbe5a244689cbe5
|
[
"MIT"
] | 1
|
2021-07-25T15:10:39.000Z
|
2021-07-25T15:10:39.000Z
|
thirdparty/AngelCode/sdk/tests/test_build_performance/source/test_basic.cpp
|
kcat/XLEngine
|
0e735ad67fa40632add3872e0cbe5a244689cbe5
|
[
"MIT"
] | null | null | null |
thirdparty/AngelCode/sdk/tests/test_build_performance/source/test_basic.cpp
|
kcat/XLEngine
|
0e735ad67fa40632add3872e0cbe5a244689cbe5
|
[
"MIT"
] | null | null | null |
//
// Test author: Andreas Jonsson
//
#include "utils.h"
#include <string>
using std::string;
namespace TestBasic
{
#define TESTNAME "TestBasic"
static const char *scriptBegin =
"void main() \n"
"{ \n"
" int[] array(2); \n"
" int[][] PWToGuild(26); \n";
static const char *scriptMiddle =
" array[0] = 121; array[1] = 196; PWToGuild[0] = array; \n";
static const char *scriptEnd =
"} \n";
void Test()
{
printf("---------------------------------------------\n");
printf("%s\n\n", TESTNAME);
printf("Machine 1\n");
printf("AngelScript 1.10.1 WIP 1: ??.?? secs\n");
printf("\n");
printf("Machine 2\n");
printf("AngelScript 1.10.1 WIP 1: 9.544 secs\n");
printf("AngelScript 1.10.1 WIP 2: .6949 secs\n");
printf("\nBuilding...\n");
asIScriptEngine *engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);
COutStream out;
engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL);
string script = scriptBegin;
for( int n = 0; n < 4000; n++ )
script += scriptMiddle;
script += scriptEnd;
double time = GetSystemTimer();
engine->AddScriptSection(0, TESTNAME, script.c_str(), script.size(), 0);
int r = engine->Build(0);
time = GetSystemTimer() - time;
if( r != 0 )
printf("Build failed\n", TESTNAME);
else
printf("Time = %f secs\n", time);
engine->Release();
}
} // namespace
| 23.956522
| 83
| 0.506352
|
kcat
|
55888732f06171bdbcd4fcf63b7c1339a50da931
| 6,727
|
hpp
|
C++
|
cmake-build-debug/test/unit/mechanisms/test_kinlva.hpp
|
anstaf/arbsimd
|
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
|
[
"BSD-3-Clause"
] | null | null | null |
cmake-build-debug/test/unit/mechanisms/test_kinlva.hpp
|
anstaf/arbsimd
|
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
|
[
"BSD-3-Clause"
] | null | null | null |
cmake-build-debug/test/unit/mechanisms/test_kinlva.hpp
|
anstaf/arbsimd
|
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <cmath>
#include <arbor/mechanism_abi.h>
extern "C" {
arb_mechanism_type make_testing_test_kinlva() {
// Tables
static arb_field_info globals[] = { { "gbar", "S / cm2", 0.0002, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 },
{ "gl", "S / cm2", 0.0001, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 },
{ "eca", "mV", 120, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 },
{ "el", "mV", -65, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 } };
static arb_size_type n_globals = 4;
static arb_field_info state_vars[] = { { "m", "", NAN, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 },
{ "h", "", NAN, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 },
{ "s", "", NAN, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 },
{ "d", "", NAN, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 } };
static arb_size_type n_state_vars = 4;
static arb_field_info parameters[] = { };
static arb_size_type n_parameters = 0;
static arb_ion_info ions[] = { { "ca", false, false, false, false, false, false, 0 } };
static arb_size_type n_ions = 1;
arb_mechanism_type result;
result.abi_version=ARB_MECH_ABI_VERSION;
result.fingerprint="<placeholder>";
result.name="test_kinlva";
result.kind=arb_mechanism_kind_density;
result.is_linear=false;
result.has_post_events=false;
result.globals=globals;
result.n_globals=n_globals;
result.ions=ions;
result.n_ions=n_ions;
result.state_vars=state_vars;
result.n_state_vars=n_state_vars;
result.parameters=parameters;
result.n_parameters=n_parameters;
return result;
}
arb_mechanism_interface* make_testing_test_kinlva_interface_multicore();
arb_mechanism_interface* make_testing_test_kinlva_interface_gpu();
}
| 149.488889
| 707
| 0.888658
|
anstaf
|
55959369f97f125187ae85b7f187fa7af918a52e
| 1,681
|
cpp
|
C++
|
src/shared/engine/Check_Win_Command.cpp
|
Kuga23/Projet-M2
|
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
|
[
"MIT"
] | null | null | null |
src/shared/engine/Check_Win_Command.cpp
|
Kuga23/Projet-M2
|
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
|
[
"MIT"
] | null | null | null |
src/shared/engine/Check_Win_Command.cpp
|
Kuga23/Projet-M2
|
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
|
[
"MIT"
] | null | null | null |
#include "Check_Win_Command.h"
// to use console
#include <iostream>
using namespace engine;
using namespace state;
using namespace std;
Check_Win_Command::Check_Win_Command()
{
Id = CHECK_WIN;
}
Check_Win_Command::~Check_Win_Command() {
}
void Check_Win_Command::exec(state::State &state)
{
int winnedID;
unsigned int p1nbDeathChar=0;
unsigned int p2nbDeathChar=0;
// Not very optimal code, tired will see later
for (auto &charac: state.getListCharacters(0)){ // Player 1
if(charac->getStatus() == DEATH )
p1nbDeathChar++;
}
for (auto &charac: state.getListCharacters(1)){ // PLayer 2
if(charac->getStatus() == DEATH )
p2nbDeathChar++;
}
if (p1nbDeathChar==state.getListCharacters(0).size()){
winnedID=2;
state.setEndGame(true);
state.setGameWinner(winnedID);
StateEvent se{StateEventID::ENDGAME};
state.notifyObservers(se, state);
cout << endl << "GAME OVER" << endl;
cout << endl << "THE GAME WINNER IS THE PLAYER No" << winnedID << endl;
cout << "\n";
}
else if (p2nbDeathChar==state.getListCharacters(1).size()){
winnedID=1;
state.setEndGame(true);
state.setGameWinner(winnedID);
StateEvent se{StateEventID::ENDGAME};
state.notifyObservers(se, state);
cout << endl << "GAME OVER" << endl;
cout << endl << "THE GAME WINNER IS THE PLAYER No " << winnedID << endl;
cout << "\n";
}
}
// Ajout de la fonction serialize
Json::Value Check_Win_Command::serialize (){
Json::Value myCommand;
myCommand["id"] = Id;
return myCommand;
}
| 25.089552
| 80
| 0.618679
|
Kuga23
|
559627849abb1ac1d1cbe07b22feb3443a6085a6
| 11,204
|
cpp
|
C++
|
source/compiler/transform.cpp
|
ChillMagic/ICM
|
a0ee83e5bbd2aef216cc28faa5d5dad36c99d606
|
[
"Apache-2.0"
] | 9
|
2016-06-14T15:38:42.000Z
|
2017-09-03T09:08:17.000Z
|
source/compiler/transform.cpp
|
ChillMagic/ICM
|
a0ee83e5bbd2aef216cc28faa5d5dad36c99d606
|
[
"Apache-2.0"
] | 1
|
2018-01-17T09:22:30.000Z
|
2018-01-17T10:10:42.000Z
|
source/compiler/transform.cpp
|
ChillMagic/ICM
|
a0ee83e5bbd2aef216cc28faa5d5dad36c99d606
|
[
"Apache-2.0"
] | null | null | null |
#include "basic.h"
#include "compiler/transform.h"
#include "compiler/analysisbase.h"
//#include "runtime/objectdef.h"
#include "temp-getelement.h"
namespace ICM
{
namespace Compiler
{
bool PrintCompilingProcess = false;
class PreliminaryCompile : private AnalysisBase
{
public:
PreliminaryCompile(NodeTable &Table) : AnalysisBase(Table) {}
void start() {
if (PrintCompilingProcess)
println("PreliminaryCompile");
compileSub(GetNode(1), GetElement(0, 0));
if (PrintCompilingProcess) {
println("-->");
printTable();
}
}
private:
Element& adjustElement(Element &elt) {
if (elt.isRefer())
compileSub(GetRefer(elt), elt);
return elt;
}
bool adjustNode(Node &node, size_t begin = 0) {
for (Element &e : rangei(node.begin() + begin, node.end())) {
adjustElement(e);
}
return true;
}
bool checkBoolExp(const Element &elt) {
if (elt.isIdent() || elt.isRefer() || elt.isLiteralType(T_Boolean))
return true;
println("Error : BoolExp has Non Boolean Value.");
return false;
}
VecElt createDoList(const NodeRange &nr) {
VecElt dolist;
dolist.reserve(nr.size() + 1);
dolist.push_back(Element::Keyword(do_));
dolist.insert(dolist.end(), nr.begin(), nr.end());
return dolist;
}
void resetNode(Node &node) {
Element front = node.front();
node.clear();
node.push_back(front);
}
void setDoNode(Node &node, VecElt &dolist) {
size_t id = Table.size();
Node *p = new Node(id, std::move(dolist));
Table.push_back(std::move(std::unique_ptr<Node>(p)));
Element e = Element::Refer(id);
node.push_back(e);
adjustNode(*p, 1);
}
private:
//
bool compileSub(Node &node, Element &refelt) {
if (PrintCompilingProcess)
println(to_string(node));
if (node[0].isKeyword())
return compileKeyword(node, refelt);
else if (node[0].isIdent() || node[0].isRefer())
return compileCall(node, refelt);
else
return error("Error in compileSub.");
}
// call ...
bool compileCall(Node &node, Element &refelt) {
adjustNode(node);
node.push_front(Element::Keyword(call_));
return true;
}
bool compileKeyword(Node &node, Element &refelt) {
switch (node[0].getKeyword()) {
case if_: return compileIf(node, refelt);
case ife_: return compileIfe(node, refelt);
case for_: return compileFor(node, refelt);
case while_: return compileWhile(node, refelt);
case loop_: return compileLoop(node, refelt);
case do_: return adjustNode(node, 1);
case list_: return adjustNode(node, 1);
case p_: return adjustNode(node, 1);
case call_: return adjustNode(node, 1);
case disp_: return compileDisp(node, refelt);
case let_:
case set_:
case ref_:
case cpy_: return compileLSRC(node, refelt);
case dim_:
case restrict_: return compileRestrictDim(node, refelt);
case define_: return compileDefine(node, refelt);
default: return error("Error with unkonwn Keyword.");
}
}
// (disp I|R)
// --> (disp I|R)
bool compileDisp(Node &node, Element &refelt) {
if (node.size() == 2) {
Element &e = node[1];
if (e.isIdent() || e.isRefer()) {
if (e.isRefer()) {
compileSub(GetRefer(e), e);
}
return true;
}
}
return error("Syntax error with disp.");
}
// (if E0 E1... elsif E2 E3... else E4 E5...)
// --> (if E0 E2 E4 R{do E1...} R{do E3...} R{do E5...})
bool compileIf(Node &node, Element &refelt) {
VecElt condlist;
vector<VecElt> dolists;
compileIfSub(rangei(node.begin() + 1, node.end()), condlist, dolists);
if (dolists.size() == condlist.size()) {
dolists.push_back(VecElt{ Element::Keyword(do_) });
}
resetNode(node);
node.insert(node.end(), condlist.begin(), condlist.end());
for (auto &dolist : dolists) {
setDoNode(node, dolist);
}
return true;
}
bool compileIfSub(const NodeRange &nr, VecElt &condList, vector<VecElt> &dolists) {
Element &bexp = *nr.begin();
checkBoolExp(adjustElement(bexp));
condList.push_back(bexp);
dolists.push_back(VecElt{ Element::Keyword(do_) });
VecElt &dolist = dolists.back();
auto ib = nr.begin() + 1;
auto ie = nr.end();
for (auto iter = ib; iter != ie; ++iter) {
Element &e = *iter;
if (e.isKeyword()) {
if (e.getKeyword() == elsif_) {
return compileIfSub(rangei(iter + 1, ie), condList, dolists);
}
else if (e.getKeyword() == else_) {
VecElt elsedolist = createDoList(rangei(iter + 1, ie));
dolists.push_back(elsedolist);
return true;
}
}
dolist.push_back(e);
}
return true;
}
// (? BE E1 E2)
// --> (? BE E1 E2)
bool compileIfe(Node &node, Element &refelt) {
if (node.size() >= 3) {
Element &bexp = node[1];
checkBoolExp(adjustElement(bexp));
adjustElement(node[2]);
if (node.size() == 4) {
adjustElement(node[3]);
}
else {
node.push_back(Element::Identifier(GlobalIdentNameMap["nil"]));
}
return true;
}
else
return error("Syntax error in '?'.");
}
// (loop E...)
// --> (loop R{do E...})
bool compileLoop(Node &node, Element &refelt) {
if (node.size() == 1)
return error("dolist will not be blank.");
VecElt dolist = createDoList(rangei(node.begin() + 1, node.end()));
resetNode(node);
setDoNode(node, dolist);
return true;
}
// (while E0 E...)
// --> (while E0 R{do E...})
bool compileWhile(Node &node, Element &refelt) {
if (node.size() == 1)
return error("none boolean exp.");
else if (node.size() == 2)
return error("dolist will not be blank.");
Element &bexp = node[1];
checkBoolExp(adjustElement(bexp));
VecElt dolist = createDoList(rangei(node.begin() + 2, node.end()));
resetNode(node);
node.push_back(bexp);
setDoNode(node, dolist);
return true;
}
// (for I in E0 to E1 E...)
// --> (for I E0 E1 R{do E...})
bool compileFor(Node &node, Element &refelt) {
// Check
if (node.size() < 6)
return error("Syntax error for 'for'.");
else if (node.size() == 6)
return error("dolist will not be blank.");
else if (!node[1].isIdent())
return error("for var must be Identifier.");
else if (!isKey(node[2], in_) || !isKey(node[4], to_))
return error("Syntax error for 'for'.");
// Compile
Element I = node[1];
Element E0 = adjustElement(node[3]);
Element E1 = adjustElement(node[5]);
VecElt dolist = createDoList(rangei(node.begin() + 6, node.end()));
resetNode(node);
node.push_back(I);
node.push_back(E0);
node.push_back(E1);
setDoNode(node, dolist);
return true;
}
// (let/set/ref/cpy I E) or (ref/cpy E)
bool compileLSRC(Node &node, Element &refelt) {
KeywordID key = node.front().getKeyword();
if (node.size() == 3) {
if (node[1].isIdent()) {
adjustElement(node[2]);
return true;
}
else
return error("var must be Identifier.");
}
else if (node.size() == 2) {
if (key == ref_ || key == cpy_) {
adjustElement(node[1]);
return true;
}
else
return error("Syntax error in '" + ICM::to_string(key) + "'.");
}
else
return error("Syntax error in '" + ICM::to_string(key) + "'.");
}
// (restrict/dim I E)
bool compileRestrictDim(Node &node, Element &refelt) {
KeywordID key = node.front().getKeyword();
if (node.size() == 3) {
if (node[1].isIdent()) {
adjustElement(node[2]);
return true;
}
else
return error("var must be Identifier.");
}
else
return error("Syntax error in '" + ICM::to_string(key) + "'.");
}
// (define I E)
bool compileDefine(Node &node, Element &refelt) {
KeywordID key = node.front().getKeyword();
if (node.size() == 3) {
if (node[1].isIdent()) {
adjustElement(node[2]);
return true;
}
else
return error("var must be Identifier.");
}
else
return error("Syntax error in '" + ICM::to_string(key) + "'.");
}
};
/*class CompiletimeEvaluate : public AnalysisBase
{
public:
CompiletimeEvaluate(NodeTable &Table) : AnalysisBase(Table) {}
bool eval(Element &element, Object &result) {
}
bool isIdentDefined(Element &element) {
assert(element.isIdent());
}
private:
Object* call(Function::FuncObject &func, DataList &list) {
return func.call(list).get();
}
};*/
class IdentifierAnalysis : public AnalysisBase
{
public:
IdentifierAnalysis(NodeTable &Table) : AnalysisBase(Table) {}
void start() {
if (PrintCompilingProcess)
println("IdentifierAnalysis");
setIdentSub(GetNode(1));
if (PrintCompilingProcess) {
println("-->");
printTable();
}
}
void setIdentSub(Node &node) {
if (PrintCompilingProcess)
println(to_string(node));
// define
if (node[0].isKeyword()) {
if (node[0].getKeyword() == define_) {
println("Making Define...");
Element &ident = node[1];
IdentSpaceIndex sid = getCurrentIdentSpaceIndex();
IdentIndex ii = { sid };
println(to_string(ident));
setIdent(ident, I_Data, ii);
}
else if (node[0].getKeyword() == module_) {
println("Making Module...");
println(to_string(node[1]));
}
}
// other
bool change = false;
for (size_t i : range(0, node.size())) {
Element &e = node[i];
if (e.isIdent())
setIdentifier(e);
else if (e.isRefer())
setIdentSub(GetRefer(e));
else if (e.isKeyword() && i != 0)
setKeyword(e);
else if (isKey(e, disp_)) {
setKeyword(e);
change = true;
}
}
if (change)
node.push_front(Element::Keyword(call_));
}
private:
bool isIdentDefined(const IdentKey &key, IdentIndex &iid) {
IdentBasicIndex index = findFromIdentTable(iid.space_index, key);
if (index != getIdentTableSize(iid.space_index)) {
iid.ident_index = index;
return true;
}
return false;
}
void setIdentifier(Element &element) {
const IdentKey &key = element.getIndex();
IdentIndex ii(getCurrentIdentSpaceIndex());
if (isIdentDefined(key, ii)) {
IdentTableUnit &itu = getFromIdentTable(ii);
setIdent(element, itu.type, ii);
}
else {
ii.ident_index = insertFromIdentTable(ii.space_index, key, I_DyVarb);
setIdent(element, I_DyVarb, ii);
}
}
void setKeyword(Element &element) {
if (isKey(element, list_)) {
setIdent(element, I_StFunc, getGlobalFunctionIdentIndex("list"));
}
else if (isKey(element, disp_)) {
setIdent(element, I_StFunc, getGlobalFunctionIdentIndex("disp"));
}
}
void setIdent(ASTBase::Element &elt, IdentType type, const IdentIndex &index) {
elt = ASTBase::Element::Identifier(type, ConvertIdentIndexToSizeT(index));
}
};
void transform(vector<AST::NodePtr> &Table) {
PreliminaryCompile(Table).start();
IdentifierAnalysis(Table).start();
};
}
}
| 27.94015
| 86
| 0.598447
|
ChillMagic
|
559e18fcbd587c713d5bafd32b8bafa73cdafe63
| 1,372
|
cpp
|
C++
|
src/runtime_src/core/pcie/linux/plugin/xdp/hal_device_offload.cpp
|
Pratyushxilinx/XRT
|
3f5d02ce9fed8d75ff5135f27a82522e7ab3d388
|
[
"Apache-2.0"
] | null | null | null |
src/runtime_src/core/pcie/linux/plugin/xdp/hal_device_offload.cpp
|
Pratyushxilinx/XRT
|
3f5d02ce9fed8d75ff5135f27a82522e7ab3d388
|
[
"Apache-2.0"
] | null | null | null |
src/runtime_src/core/pcie/linux/plugin/xdp/hal_device_offload.cpp
|
Pratyushxilinx/XRT
|
3f5d02ce9fed8d75ff5135f27a82522e7ab3d388
|
[
"Apache-2.0"
] | null | null | null |
#include <functional>
#include "hal_device_offload.h"
#include "core/common/module_loader.h"
#include "core/common/dlfcn.h"
namespace xdphaldeviceoffload {
void load_xdp_hal_device_offload()
{
static xrt_core::module_loader
xdp_hal_device_offload_loader("xdp_hal_device_offload_plugin",
register_hal_device_offload_functions,
hal_device_offload_warning_function) ;
}
std::function<void (void*)> update_device_cb ;
std::function<void (void*)> flush_device_cb ;
void register_hal_device_offload_functions(void* handle)
{
typedef void (*ftype)(void*) ;
update_device_cb = (ftype)(xrt_core::dlsym(handle, "updateDeviceHAL")) ;
if (xrt_core::dlerror() != NULL) update_device_cb = nullptr ;
flush_device_cb = (ftype)(xrt_core::dlsym(handle, "flushDeviceHAL")) ;
if (xrt_core::dlerror() != NULL) flush_device_cb = nullptr ;
}
void hal_device_offload_warning_function()
{
// No warnings at this level
}
} // end namespace xdphaldeviceoffload
namespace xdphal {
void flush_device(void* handle)
{
if (xdphaldeviceoffload::flush_device_cb != nullptr)
{
xdphaldeviceoffload::flush_device_cb(handle) ;
}
}
void update_device(void* handle)
{
if (xdphaldeviceoffload::update_device_cb != nullptr)
{
xdphaldeviceoffload::update_device_cb(handle) ;
}
}
}
| 24.5
| 76
| 0.710641
|
Pratyushxilinx
|
55acc3d36186c74d1d9667fa4eca2e53abba5d4f
| 468
|
cpp
|
C++
|
src/brew/math/Math.cpp
|
grrrrunz/brew
|
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
|
[
"MIT"
] | 1
|
2018-02-09T16:20:50.000Z
|
2018-02-09T16:20:50.000Z
|
src/brew/math/Math.cpp
|
grrrrunz/brew
|
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
|
[
"MIT"
] | null | null | null |
src/brew/math/Math.cpp
|
grrrrunz/brew
|
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
|
[
"MIT"
] | null | null | null |
/**
*
* |_ _ _
* |_)| (/_VV
*
* Copyright 2015-2018 Marcus v. Keil
*
* Created on: Feb 11, 2016
*
*/
#include <brew/math/Math.h>
namespace brew {
namespace math {
const Real EPSILON = std::numeric_limits<Real>::epsilon();
const Real PI = 3.1415926535897932f;
const Real HALF_PI = PI * 0.5f;
const Real TWO_PI = PI * 2;
bool equals(Real a, Real b, Real epsilon) {
return std::fabs(a-b) < epsilon;
}
} /* namespace math */
} /* namespace brew */
| 16.137931
| 58
| 0.619658
|
grrrrunz
|
55aec24ae07d08e6bb68efa367b9513e9ea6d164
| 9,205
|
cpp
|
C++
|
profiler/src/ProfilerEngine/Datadog.Profiler.Native/StackFramesCollectorBase.cpp
|
cwe1ss/dd-trace-dotnet
|
ed74cf794cb02fb698567052caae973870b82428
|
[
"Apache-2.0"
] | null | null | null |
profiler/src/ProfilerEngine/Datadog.Profiler.Native/StackFramesCollectorBase.cpp
|
cwe1ss/dd-trace-dotnet
|
ed74cf794cb02fb698567052caae973870b82428
|
[
"Apache-2.0"
] | 2
|
2022-02-10T06:13:13.000Z
|
2022-02-17T01:31:15.000Z
|
profiler/src/ProfilerEngine/Datadog.Profiler.Native/StackFramesCollectorBase.cpp
|
Kielek/signalfx-dotnet-tracing
|
80c65ca936748788629287472401fa9f31b79410
|
[
"Apache-2.0"
] | null | null | null |
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2022 Datadog, Inc.
#include "StackFramesCollectorBase.h"
#include <assert.h>
#include <chrono>
#include <condition_variable>
#include <mutex>
StackFramesCollectorBase::StackFramesCollectorBase()
{
_isRequestedCollectionAbortSuccessful = false;
_pReusableStackSnapshotResult = new StackSnapshotResultReusableBuffer();
_pCurrentCollectionThreadInfo = nullptr;
}
StackFramesCollectorBase::~StackFramesCollectorBase()
{
StackSnapshotResultReusableBuffer* pReusableStackSnapshotResult = _pReusableStackSnapshotResult;
if (pReusableStackSnapshotResult != nullptr)
{
delete pReusableStackSnapshotResult;
_pReusableStackSnapshotResult = nullptr;
}
}
bool StackFramesCollectorBase::TryAddFrame(StackFrameCodeKind codeKind,
FunctionID clrFunctionId,
UINT_PTR nativeInstructionPointer,
std::uint64_t moduleHandle)
{
StackSnapshotResultFrameInfo* pCurrentFrameInfo;
bool hasCapacityForSubsequentFrames;
bool hasCapacityForThisFrame = _pReusableStackSnapshotResult->TryAddNextFrame(&pCurrentFrameInfo, &hasCapacityForSubsequentFrames);
if (!hasCapacityForThisFrame)
{
// We run out of the preallocated space for storing results.
// Allocating while threads are suspended is forbidden.
// We are just being defensive: we should really never get here,
// since last iteration we had hasCapacityForSubsequentFrames == true.
// We will also increase the size of the preallocated buffer for the next time:
_pReusableStackSnapshotResult->GrowCapacityAtNextReset();
// Use the info we collected so far and abort further stack walking for this time:
return false;
}
if (!hasCapacityForSubsequentFrames)
{
// We have preallocated space for only one more frame.
// (allocating while threads are suspended is forbidden.)
// We need to use it for a marker that signals that more frames exist, but we do not have information about them:
pCurrentFrameInfo->Set(StackFrameCodeKind::MultipleMixed, 0, 0, 0);
// We will also increase the size of the preallocated buffer for the next time:
_pReusableStackSnapshotResult->GrowCapacityAtNextReset();
// Use the info we collected so far and abort further stack walking for this time:
return false;
}
pCurrentFrameInfo->Set(codeKind, clrFunctionId, nativeInstructionPointer, moduleHandle);
return true;
}
void StackFramesCollectorBase::RequestAbortCurrentCollection(void)
{
std::lock_guard<std::mutex> lock(_collectionAbortNotificationLock);
_isRequestedCollectionAbortSuccessful = false;
_isCurrentCollectionAbortRequested.store(true);
}
//
// =========== Default implementations of Protected Virtual business logic funcitons: ===========
//
void StackFramesCollectorBase::PrepareForNextCollectionImplementation(void)
{
// The actual business logic provided by a subclass goes into the XxxImplementation(..) methods.
// This is a fallback implementation, so that the implementing sub-class does not need to overwrite this method if it is a no-op.
}
bool StackFramesCollectorBase::SuspendTargetThreadImplementation(ManagedThreadInfo* pThreadInfo,
bool* pIsTargetThreadSuspended)
{
// The actual business logic provided by a subclass goes into the XxxImplementation(..) methods.
// This is a fallback implementation, so that the implementing sub-class does not need to overwrite this method if it is a no-op.
*pIsTargetThreadSuspended = false;
return true;
}
void StackFramesCollectorBase::ResumeTargetThreadIfRequiredImplementation(ManagedThreadInfo* pThreadInfo,
bool isTargetThreadSuspended,
uint32_t* pErrorCodeHR)
{
// The actual business logic provided by a subclass goes into the XxxImplementation(..) methods.
// This is a fallback implementation, so that the implementing sub-class does not need to overwrite this method if it is a no-op.
if (pErrorCodeHR != nullptr)
{
*pErrorCodeHR = isTargetThreadSuspended ? E_FAIL : S_OK;
}
}
StackSnapshotResultBuffer* StackFramesCollectorBase::CollectStackSampleImplementation(ManagedThreadInfo* pThreadInfo,
uint32_t* pHR)
{
// The actual business logic provided by a subclass goes into the XxxImplementation(..) methods.
// This is a fallback implementation, so that the implementing sub-class does not need to overwrite this method if it is a no-op.
bool frame1Added = TryAddFrame(StackFrameCodeKind::Dummy, 0, 0, 0);
bool frame2Added = TryAddFrame(StackFrameCodeKind::Dummy, 0, 0, 0);
bool frame3Added = TryAddFrame(StackFrameCodeKind::Dummy, 0, 0, 0);
if (pHR != nullptr)
{
*pHR = (frame1Added && frame2Added && frame3Added) ? S_OK : E_FAIL;
}
return GetStackSnapshotResult();
}
bool StackFramesCollectorBase::IsCurrentCollectionAbortRequested()
{
return _isCurrentCollectionAbortRequested.load();
}
bool StackFramesCollectorBase::TryApplyTraceContextDataFromCurrentCollectionThreadToSnapshot()
{
// If TraceContext Tracking is not enabled, then we will simply get zero IDs.
ManagedThreadInfo* pCurrentCollectionThreadInfo = _pCurrentCollectionThreadInfo;
if (nullptr != pCurrentCollectionThreadInfo && pCurrentCollectionThreadInfo->CanReadTraceContext())
{
std::uint64_t localRootSpanId = pCurrentCollectionThreadInfo->GetLocalRootSpanId();
std::uint64_t spanId = pCurrentCollectionThreadInfo->GetSpanId();
_pReusableStackSnapshotResult->SetLocalRootSpanId(localRootSpanId);
_pReusableStackSnapshotResult->SetSpanId(spanId);
return true;
}
return false;
}
StackSnapshotResultBuffer* StackFramesCollectorBase::GetStackSnapshotResult()
{
return _pReusableStackSnapshotResult;
}
// ----------- Inline stubs for APIs that are specific to overriding implementations: -----------
// They perform the work required for the shared base implementation (this class) and then invoke the respective XxxImplementaiton(..) method.
// This is less error-prone than simply making these methods virtual and relying on the sub-classes to remember calling the base class method.
void StackFramesCollectorBase::PrepareForNextCollection(void)
{
// We cannot allocate memory once a thread is suspended.
// This is because malloc() uses a lock and so if we suspend a thread that was allocating, we will deadlock.
// So we pre-allocate the memory buffer and reset it before suspending the target thread.
_pReusableStackSnapshotResult->Reset();
// Clear the current collection thread pointer:
_pCurrentCollectionThreadInfo = nullptr;
// Clean up initialization state:
_isCurrentCollectionAbortRequested.store(false);
_isRequestedCollectionAbortSuccessful = false;
// Subclasses can implement their own specific initialization before each collection. Invoke it:
PrepareForNextCollectionImplementation();
}
bool StackFramesCollectorBase::SuspendTargetThread(ManagedThreadInfo* pThreadInfo, bool* pIsTargetThreadSuspended)
{
return SuspendTargetThreadImplementation(pThreadInfo, pIsTargetThreadSuspended);
}
void StackFramesCollectorBase::ResumeTargetThreadIfRequired(ManagedThreadInfo* pThreadInfo, bool isTargetThreadSuspended, uint32_t* pErrorCodeHR)
{
ResumeTargetThreadIfRequiredImplementation(pThreadInfo, isTargetThreadSuspended, pErrorCodeHR);
}
StackSnapshotResultBuffer* StackFramesCollectorBase::CollectStackSample(ManagedThreadInfo* pThreadInfo, uint32_t* pHR)
{
// Update state with the info for the thread that we are collecting:
_pCurrentCollectionThreadInfo = pThreadInfo;
// Execute the actual collection:
StackSnapshotResultBuffer* result = CollectStackSampleImplementation(pThreadInfo, pHR);
// No longer collecting the specified thread:
_pCurrentCollectionThreadInfo = nullptr;
// If someone has requested an abort, notify them now:
if (IsCurrentCollectionAbortRequested())
{
{
std::lock_guard<std::mutex> lock(_collectionAbortNotificationLock);
_isRequestedCollectionAbortSuccessful = true;
}
_collectionAbortPerformedSignal.notify_all();
}
return result;
}
void StackFramesCollectorBase::OnDeadlock()
{
// In 32bits, we use the method DoStackSnapshot to walk and collect a thread callstack.
// The DoStackSnapshot method calls SuspendThread/ResumeThread.
// In case of a deadlock, if the sampling thread has not gracefully finished, it will be killed.
// The result will be: 1 call to ResumeThread missing.
}
| 41.463964
| 145
| 0.726996
|
cwe1ss
|
55b9edc87798a7028096212e073eaf233408fc4b
| 285
|
cpp
|
C++
|
src/fem/maplocal.cpp
|
XiaoMaResearch/hybrid_tsunamic_plane_stress
|
574988edfcd4839f680b85cde2bf818936e86b78
|
[
"MIT"
] | 6
|
2019-04-12T19:51:23.000Z
|
2021-09-16T07:12:57.000Z
|
src/fem/maplocal.cpp
|
XiaoMaResearch/hybrid_tsunamic_plane_stress
|
574988edfcd4839f680b85cde2bf818936e86b78
|
[
"MIT"
] | null | null | null |
src/fem/maplocal.cpp
|
XiaoMaResearch/hybrid_tsunamic_plane_stress
|
574988edfcd4839f680b85cde2bf818936e86b78
|
[
"MIT"
] | 1
|
2019-07-07T07:23:58.000Z
|
2019-07-07T07:23:58.000Z
|
//
// maplocal.cpp
// hybrid_fem_bie
//
// Created by Max on 2/6/18.
//
//
#include "maplocal.hpp"
void maplocal(const ArrayXi &index, const VectorXd &u_global , VectorXd & u_local)
{
for (int i=0;i<u_local.size();i++)
{
u_local(i)=u_global(index(i));
}
}
| 15.833333
| 82
| 0.592982
|
XiaoMaResearch
|
55bc13b31463ccc08047dbe384fb2d272c8e33da
| 8,156
|
cpp
|
C++
|
RT/RT/Impl/JsonSerialization.cpp
|
heyx3/heyx3RT
|
4dd476a33e658bc19fde239f2c6e22bdcd598e27
|
[
"Unlicense",
"MIT"
] | null | null | null |
RT/RT/Impl/JsonSerialization.cpp
|
heyx3/heyx3RT
|
4dd476a33e658bc19fde239f2c6e22bdcd598e27
|
[
"Unlicense",
"MIT"
] | null | null | null |
RT/RT/Impl/JsonSerialization.cpp
|
heyx3/heyx3RT
|
4dd476a33e658bc19fde239f2c6e22bdcd598e27
|
[
"Unlicense",
"MIT"
] | null | null | null |
#include "../Headers/JsonSerialization.h"
#include "../Headers/ThirdParty/base64.h"
#include <fstream>
using namespace RT;
#pragma warning( disable : 4996 )
bool RT_API JsonSerialization::ToJSONFile(const String& filePath, const IWritable& toWrite,
bool compact, String& outErrorMsg)
{
JsonWriter writer;
String trying = "UNKNOWN";
try
{
trying = "serializing data";
writer.WriteDataStructure(toWrite, "data");
trying = "writing data to file";
outErrorMsg = writer.SaveData(filePath, compact);
if (!outErrorMsg.IsEmpty())
{
return false;
}
return true;
}
catch (int i)
{
if (i == DataWriter::EXCEPTION_FAILURE)
{
outErrorMsg = String("Error while ") + trying + ": " + writer.ErrorMessage;
}
else
{
outErrorMsg = String("Unknown error code while ") + trying + ": " + String(i);
}
return false;
}
}
bool RT_API JsonSerialization::ToJSONString(const IWritable& toWrite, bool compact,
String& outJSON, String& outErrorMsg)
{
JsonWriter writer;
String trying = "UNKNOWN";
try
{
trying = "serializing data";
writer.WriteDataStructure(toWrite, "data");
outJSON = writer.GetData(compact);
return true;
}
catch (int i)
{
if (i == DataWriter::EXCEPTION_FAILURE)
{
outErrorMsg = String("Error while ") + trying + ": " + writer.ErrorMessage;
}
else
{
outErrorMsg = String("Unknown error code while ") + trying + ": " + String(i);
}
return false;
}
}
bool RT_API JsonSerialization::FromJSONFile(const String& filePath, IReadable& toRead,
String& outErrorMsg)
{
JsonReader reader(filePath);
//If we had an error reading the file, stop.
if (reader.ErrorMessage.GetSize() > 0)
{
outErrorMsg = String("Error reading file: ") + reader.ErrorMessage;
return false;
}
try
{
reader.ReadDataStructure(toRead, "data");
return true;
}
catch (int i)
{
if (i == DataReader::EXCEPTION_FAILURE)
{
outErrorMsg = String("Error reading data: ") + reader.ErrorMessage;
}
else
{
outErrorMsg = String("Unknown error code: ") + String(i);
}
return false;
}
}
String JsonWriter::SaveData(const String& path, bool compact)
{
std::ofstream file(path.CStr(), std::ios_base::trunc);
if (file.is_open())
{
file << doc.dump(compact ? -1 : 4);
}
else
{
return "Couldn't open file";
}
return "";
}
void JsonWriter::WriteBool(bool value, const String& name)
{
GetToUse()[name.CStr()] = value;
}
void JsonWriter::WriteByte(unsigned char value, const String& name)
{
GetToUse()[name.CStr()] = value;
}
void JsonWriter::WriteInt(int value, const String& name)
{
GetToUse()[name.CStr()] = value;
}
void JsonWriter::WriteUInt(unsigned int value, const String& name)
{
GetToUse()[name.CStr()] = value;
}
void JsonWriter::WriteFloat(float value, const String& name)
{
GetToUse()[name.CStr()] = value;
}
void JsonWriter::WriteDouble(double value, const String& name)
{
GetToUse()[name.CStr()] = value;
}
void JsonWriter::WriteString(const String& value, const String& name)
{
//Escape special characters.
String newVal = value;
for (size_t i = 0; i < newVal.GetSize(); ++i)
{
if (newVal[i] == '"' || newVal[i] == '\\')
{
newVal.Insert(i, '\\');
i += 1;
}
}
GetToUse()[name.CStr()] = value.CStr();
}
void JsonWriter::WriteBytes(const unsigned char* bytes, size_t nBytes, const String& name)
{
String str = base64::encode(bytes, nBytes).c_str();
WriteString(str, name);
}
void JsonWriter::WriteDataStructure(const IWritable& toSerialize, const String& name)
{
GetToUse()[name.CStr()] = nlohmann::json::object();
JsonWriter subWriter(&GetToUse()[name.CStr()]);
toSerialize.WriteData(subWriter);
}
JsonReader::JsonReader(const String& filePath)
{
ErrorMessage = Reload(filePath);
}
String JsonReader::Reload(const String& filePath)
{
subDoc = nullptr;
std::ifstream fileS(filePath.CStr());
if (!fileS.is_open())
{
return "Couldn't open the file";
}
fileS.seekg(0, std::ios::end);
std::streampos size = fileS.tellg();
fileS.seekg(0, std::ios::beg);
std::vector<char> fileData;
fileData.resize((size_t)size);
fileS.read(fileData.data(), size);
doc = nlohmann::json::parse(std::string(fileData.data()));
return "";
}
void JsonReader::Assert(bool expr, const String& errorMsg)
{
if (!expr)
{
ErrorMessage = errorMsg;
throw EXCEPTION_FAILURE;
}
}
nlohmann::json::const_iterator JsonReader::GetItem(const String& name)
{
const nlohmann::json& jsn = GetToUse();
auto element = jsn.find(name.CStr());
Assert(element != jsn.end(),
"Couldn't find the element.");
return element;
}
void JsonReader::ReadBool(bool& outB, const String& name)
{
auto& element = GetItem(name);
Assert(element->is_boolean(), "Expected a boolean but got something else");
outB = element->get<bool>();
}
void JsonReader::ReadByte(unsigned char& outB, const String& name)
{
auto& element = GetItem(name);
Assert(element->is_number_unsigned(), "Expected a byte but got something else");
outB = (unsigned char)element->get<size_t>();
}
void JsonReader::ReadInt(int& outI, const String& name)
{
auto& element = GetItem(name);
Assert(element->is_number_integer(), "Expected an integer but got something else");
outI = element->get<int>();
}
void JsonReader::ReadUInt(unsigned int& outU, const String& name)
{
auto& element = GetItem(name);
Assert(element->is_number_unsigned(), "Expected an unsigned integer but got something else");
outU = element->get<size_t>();
}
void JsonReader::ReadFloat(float& outF, const String& name)
{
//Note that integers make valid floats.
auto& element = GetItem(name);
Assert(element->is_number_float() || element->is_number_integer(),
"Expected a float but got something else");
if (element->is_number_float())
outF = element->get<float>();
else
outF = (float)element->get<int>();
}
void JsonReader::ReadDouble(double& outD, const String& name)
{
//Note that integers make valid doubles.
auto& element = GetItem(name);
Assert(element->is_number_float() || element->is_number_integer(),
"Expected a double but got something else");
if (element->is_number_float())
outD = element->get<double>();
else
outD = (double)element->get<int>();
}
void JsonReader::ReadString(String& outStr, const String& name)
{
auto& element = GetItem(name);
Assert(element->is_string(), "Expected a string but got something else");
outStr = element->get<std::string>().c_str();
//Fix escaped characters.
for (size_t i = 0; i < outStr.GetSize(); ++i)
{
if (outStr[i] == '\\')
{
outStr.Erase(i);
//Normally we would subtract 1 from "i" here, but we *want* to skip the next character --
// it's the one being escaped.
}
}
}
void JsonReader::ReadBytes(List<unsigned char>& outBytes, const String& name)
{
String str;
ReadString(str, name);
std::vector<unsigned char> _outBytes;
base64::decode(str.CStr(), _outBytes);
outBytes.Resize(_outBytes.size());
memcpy_s(outBytes.GetData(), outBytes.GetSize(),
_outBytes.data(), _outBytes.size());
}
void JsonReader::ReadDataStructure(IReadable& outData, const String& name)
{
auto& element = GetItem(name);
Assert(element->is_object(), "Expected a data structure but got something else");
JsonReader subReader(&(*element));
outData.ReadData(subReader);
}
#pragma warning( default : 4996 )
| 27.461279
| 101
| 0.611574
|
heyx3
|
55bcc14b851caec9910c7842d229687cbc189cee
| 2,802
|
cpp
|
C++
|
examples/client/qtest1.cpp
|
pauldotknopf/grpc-qt
|
c6e0e38ea4130ac2b8ae5f441bd78dd7ead274e4
|
[
"MIT"
] | null | null | null |
examples/client/qtest1.cpp
|
pauldotknopf/grpc-qt
|
c6e0e38ea4130ac2b8ae5f441bd78dd7ead274e4
|
[
"MIT"
] | null | null | null |
examples/client/qtest1.cpp
|
pauldotknopf/grpc-qt
|
c6e0e38ea4130ac2b8ae5f441bd78dd7ead274e4
|
[
"MIT"
] | null | null | null |
#include "qtest1.h"
#include "proto/gen.grpc.pb.h"
#include <grpc++/grpc++.h>
#include <QDebug>
class QTest1Private
{
public:
QTest1Private() : objectId(0) {
}
std::unique_ptr<Tests::Test1ObjectService::Stub> test1ObjectService;
grpc::ClientContext objectRequestContext;
std::unique_ptr<grpc::ClientReaderWriter<google::protobuf::Any, google::protobuf::Any>> objectRequest;
google::protobuf::uint64 objectId;
void createObject() {
objectRequest = test1ObjectService->Create(&objectRequestContext);
google::protobuf::Any createResponseAny;
if(!objectRequest->Read(&createResponseAny)) {
qCritical("Failed to read request from object creation.");
objectRequest.release();
return;
}
Tests::Test1CreateResponse createResponse;
if(!createResponseAny.UnpackTo(&createResponse)) {
qCritical("Couldn't unpack request to CreateResponse.");
objectRequest.release();
return;
}
objectId = createResponse.objectid();
}
void releaseObject() {
if(objectRequest != nullptr) {
auto result = objectRequest->Finish();
if(!result.ok()) {
qCritical("Couldn't dispose of the object: %s", result.error_message().c_str());
}
}
}
};
QTest1::QTest1() : d_ptr(new QTest1Private())
{
auto channel = grpc::CreateChannel("localhost:8000", grpc::InsecureChannelCredentials());
auto stub = Tests::Test1ObjectService::NewStub(channel);
d_ptr->test1ObjectService = std::move(stub);
d_ptr->createObject();
}
QTest1::~QTest1()
{
d_ptr->releaseObject();
}
QString QTest1::getPropString()
{
grpc::ClientContext context;
Tests::Test1PropStringGetRequest request;
request.set_objectid(d_ptr->objectId);
Tests::Test1PropStringGetResponse response;
auto result = d_ptr->test1ObjectService->GetPropertyPropString(&context, request, &response);
if(!result.ok()) {
qCritical("Couldn't get the property: %s", result.error_message().c_str());
return QString();
}
auto val = response.value();
return QString::fromStdString(response.value().value());
}
void QTest1::setPropString(QString& val)
{
grpc::ClientContext context;
Tests::Test1PropStringSetRequest request;
request.set_objectid(d_ptr->objectId);
auto str = new google::protobuf::StringValue();
str->set_value(val.toStdString());
request.set_allocated_value(str);
Tests::Test1PropStringSetResponse response;
auto result = d_ptr->test1ObjectService->SetPropertyPropString(&context, request, &response);
if(!result.ok()) {
qCritical("Couldn't get the property: %s", result.error_message().c_str());
return;
}
}
| 31.133333
| 106
| 0.662384
|
pauldotknopf
|
55be8c3075caa2afc85c290ec5c232c092b2dfea
| 682
|
cpp
|
C++
|
Chapter7-Quicksort/quicksort.cpp
|
wr47h/CLRS_Algorithms
|
91193e8382cd54398ab1ca397ef72069754a1dc6
|
[
"MIT"
] | null | null | null |
Chapter7-Quicksort/quicksort.cpp
|
wr47h/CLRS_Algorithms
|
91193e8382cd54398ab1ca397ef72069754a1dc6
|
[
"MIT"
] | null | null | null |
Chapter7-Quicksort/quicksort.cpp
|
wr47h/CLRS_Algorithms
|
91193e8382cd54398ab1ca397ef72069754a1dc6
|
[
"MIT"
] | 1
|
2019-10-05T08:07:06.000Z
|
2019-10-05T08:07:06.000Z
|
#include <iostream>
using namespace std;
int partitionAr(int a[], int p, int r) {
int x = a[r-1];
int i = p-1;
for(int j=p; j<r-1; j++) {
if(a[j]<x) {
i = i+1;
swap(a[i], a[j]);
}
}
swap(a[i+1], a[r-1]);
return i+1;
}
void quicksort(int a[], int p, int r) {
if(p<r) {
int q = partitionAr(a, p, r);
quicksort(a, p, q-1);
quicksort(a, q+1, r);
}
}
void printArray(int a[], int n){
for (int i=0; i<n; i++)
cout << a[i] << " ";
cout << "\n";
}
int main() {
int a[] = {2, 5, 3, 9, 1, 10};
int n = 6;
quicksort(a, 0, n);
printArray(a, n);
return 0;
}
| 17.487179
| 40
| 0.422287
|
wr47h
|
55c259700f72ab9818969086f7640bcd55729c9c
| 723
|
cpp
|
C++
|
ACM-ICPC/9095.cpp
|
KimBoWoon/ACM-ICPC
|
146c36999488af9234d73f7b4b0c10d78486604f
|
[
"MIT"
] | null | null | null |
ACM-ICPC/9095.cpp
|
KimBoWoon/ACM-ICPC
|
146c36999488af9234d73f7b4b0c10d78486604f
|
[
"MIT"
] | null | null | null |
ACM-ICPC/9095.cpp
|
KimBoWoon/ACM-ICPC
|
146c36999488af9234d73f7b4b0c10d78486604f
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
int t, n;
int dp[101];
// 1, 2, 3์ ๋ํด์ n์ ํํํ๋ ๋ฐฉ๋ฒ์ ๊ฐ์ง์๋ฅผ d[n]
// dp[x๋ฅผ 1๋ก ๋ง๋๋ ๊ฒฝ์ฐ์ ์]
// dp[x๋ฅผ 2๋ก ๋ง๋๋ ๊ฒฝ์ฐ์ ์]
// dp[x๋ฅผ 3๋ก ๋ง๋๋ ๊ฒฝ์ฐ์ ์]
// ์ ๋ถ ๋ ํ๋ฉด ๋๋ค
int topDown(int x) {
if (x == 0) {
dp[x] = 1;
}
if (x == 1) {
dp[x] = 1;
}
if (x == 2) {
dp[x] = 2;
}
if (x >= 3) {
dp[x] = topDown(x - 1) + topDown(x - 2) + topDown(x - 3);
}
return dp[x];
}
int bottomUp(int x) {
dp[0] = 1;
for (int i = 1; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
}
return dp[x];
}
int main() {
scanf("%d", &t);
while (t--) {
memset(dp, 0, sizeof(dp));
scanf("%d", &n);
printf("%d\n", topDown(n));
// printf("%d\n", bottomUp(n));
}
}
| 15.717391
| 60
| 0.427386
|
KimBoWoon
|
55ccb4ada59dd2d371ffe65fbd7676ba1663dd12
| 4,503
|
cpp
|
C++
|
third_party/libosmium/test/t/geom/test_wkt.cpp
|
peterkist-tinker/osrm-backend-appveyor-test
|
1891d7379c1d524ea6dc5a8d95e93f4023481a07
|
[
"BSD-2-Clause"
] | 1
|
2017-04-15T22:58:23.000Z
|
2017-04-15T22:58:23.000Z
|
third_party/libosmium/test/t/geom/test_wkt.cpp
|
peterkist-tinker/osrm-backend-appveyor-test
|
1891d7379c1d524ea6dc5a8d95e93f4023481a07
|
[
"BSD-2-Clause"
] | 1
|
2019-11-21T09:59:27.000Z
|
2019-11-21T09:59:27.000Z
|
osrm-ch/third_party/libosmium/test/t/geom/test_wkt.cpp
|
dingchunda/osrm-backend
|
8750749b83bd9193ca3481c630eefda689ecb73c
|
[
"BSD-2-Clause"
] | 1
|
2021-08-04T02:32:10.000Z
|
2021-08-04T02:32:10.000Z
|
#include "catch.hpp"
#include <osmium/geom/wkt.hpp>
#include "area_helper.hpp"
#include "wnl_helper.hpp"
TEST_CASE("WKT_Geometry") {
SECTION("point") {
osmium::geom::WKTFactory<> factory;
std::string wkt {factory.create_point(osmium::Location(3.2, 4.2))};
REQUIRE(std::string{"POINT(3.2 4.2)"} == wkt);
}
SECTION("empty_point") {
osmium::geom::WKTFactory<> factory;
REQUIRE_THROWS_AS(factory.create_point(osmium::Location()), osmium::invalid_location);
}
SECTION("linestring") {
osmium::geom::WKTFactory<> factory;
osmium::memory::Buffer buffer(10000);
auto &wnl = create_test_wnl_okay(buffer);
{
std::string wkt {factory.create_linestring(wnl)};
REQUIRE(std::string{"LINESTRING(3.2 4.2,3.5 4.7,3.6 4.9)"} == wkt);
}
{
std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward)};
REQUIRE(std::string{"LINESTRING(3.6 4.9,3.5 4.7,3.2 4.2)"} == wkt);
}
{
std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all)};
REQUIRE(std::string{"LINESTRING(3.2 4.2,3.5 4.7,3.5 4.7,3.6 4.9)"} == wkt);
}
{
std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)};
REQUIRE(std::string{"LINESTRING(3.6 4.9,3.5 4.7,3.5 4.7,3.2 4.2)"} == wkt);
}
}
SECTION("empty_linestring") {
osmium::geom::WKTFactory<> factory;
osmium::memory::Buffer buffer(10000);
auto &wnl = create_test_wnl_empty(buffer);
REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::geometry_error);
REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), osmium::geometry_error);
REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all), osmium::geometry_error);
REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward), osmium::geometry_error);
}
SECTION("linestring_with_two_same_locations") {
osmium::geom::WKTFactory<> factory;
osmium::memory::Buffer buffer(10000);
auto &wnl = create_test_wnl_same_location(buffer);
REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::geometry_error);
try {
factory.create_linestring(wnl);
} catch (osmium::geometry_error& e) {
REQUIRE(e.id() == 0);
REQUIRE(std::string(e.what()) == "need at least two points for linestring");
}
REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), osmium::geometry_error);
{
std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all)};
REQUIRE(std::string{"LINESTRING(3.5 4.7,3.5 4.7)"} == wkt);
}
{
std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)};
REQUIRE(std::string{"LINESTRING(3.5 4.7,3.5 4.7)"} == wkt);
}
}
SECTION("linestring_with_undefined_location") {
osmium::geom::WKTFactory<> factory;
osmium::memory::Buffer buffer(10000);
auto &wnl = create_test_wnl_undefined_location(buffer);
REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::invalid_location);
}
SECTION("area_1outer_0inner") {
osmium::geom::WKTFactory<> factory;
osmium::memory::Buffer buffer(10000);
const osmium::Area& area = create_test_area_1outer_0inner(buffer);
{
std::string wkt {factory.create_multipolygon(area)};
REQUIRE(std::string{"MULTIPOLYGON(((3.2 4.2,3.5 4.7,3.6 4.9,3.2 4.2)))"} == wkt);
}
}
SECTION("area_1outer_1inner") {
osmium::geom::WKTFactory<> factory;
osmium::memory::Buffer buffer(10000);
const osmium::Area& area = create_test_area_1outer_1inner(buffer);
{
std::string wkt {factory.create_multipolygon(area)};
REQUIRE(std::string{"MULTIPOLYGON(((0.1 0.1,9.1 0.1,9.1 9.1,0.1 9.1,0.1 0.1),(1 1,8 1,8 8,1 8,1 1)))"} == wkt);
}
}
SECTION("area_2outer_2inner") {
osmium::geom::WKTFactory<> factory;
osmium::memory::Buffer buffer(10000);
const osmium::Area& area = create_test_area_2outer_2inner(buffer);
{
std::string wkt {factory.create_multipolygon(area)};
REQUIRE(std::string{"MULTIPOLYGON(((0.1 0.1,9.1 0.1,9.1 9.1,0.1 9.1,0.1 0.1),(1 1,4 1,4 4,1 4,1 1),(5 5,5 7,7 7,5 5)),((10 10,11 10,11 11,10 11,10 10)))"} == wkt);
}
}
}
| 32.868613
| 171
| 0.663113
|
peterkist-tinker
|
55d92902035bee0e07c3f8779565175d56239f57
| 752
|
hpp
|
C++
|
boost/network/protocol/http/traits/connection_keepalive.hpp
|
antoinelefloch/cpp-netlib
|
5eb9b5550a10d06f064ee9883c7d942d3426f31b
|
[
"BSL-1.0"
] | 3
|
2015-02-10T22:08:08.000Z
|
2021-11-13T20:59:25.000Z
|
include/boost/network/protocol/http/traits/connection_keepalive.hpp
|
waTeim/boost
|
eb3850fae8c037d632244cf15cf6905197d64d39
|
[
"BSL-1.0"
] | 1
|
2018-08-10T04:47:12.000Z
|
2018-08-10T13:54:57.000Z
|
include/boost/network/protocol/http/traits/connection_keepalive.hpp
|
waTeim/boost
|
eb3850fae8c037d632244cf15cf6905197d64d39
|
[
"BSL-1.0"
] | 5
|
2017-12-28T12:42:25.000Z
|
2021-07-01T07:41:53.000Z
|
// Copyright (c) Dean Michael Berris 2010.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_TRAITS_CONECTION_KEEPALIVE_20091218
#define BOOST_NETWORK_PROTOCOL_HTTP_TRAITS_CONECTION_KEEPALIVE_20091218
#include <boost/network/protocol/http/tags.hpp>
#include <boost/network/protocol/http/support/is_keepalive.hpp>
namespace boost { namespace network { namespace http {
template <class Tag>
struct connection_keepalive : is_keepalive<Tag> {};
} /* http */
} /* network */
} /* boost */
#endif // BOOST_NETWORK_PROTOCOL_HTTP_TRAITS_CONECTION_KEEPALIVE_20091218
| 30.08
| 73
| 0.74734
|
antoinelefloch
|
55da0c41e5c7d7bfafb4e9ad99bc5234ce32a6d8
| 1,433
|
cpp
|
C++
|
generated/src/ModuleInterface.cpp
|
MMX-World/vnx-base
|
c806599e630e17928e8c2d9271e896797a069ba2
|
[
"Apache-2.0"
] | null | null | null |
generated/src/ModuleInterface.cpp
|
MMX-World/vnx-base
|
c806599e630e17928e8c2d9271e896797a069ba2
|
[
"Apache-2.0"
] | 2
|
2022-02-07T05:19:09.000Z
|
2022-03-24T18:44:37.000Z
|
generated/src/ModuleInterface.cpp
|
MMX-World/vnx-base
|
c806599e630e17928e8c2d9271e896797a069ba2
|
[
"Apache-2.0"
] | 1
|
2022-01-22T21:30:26.000Z
|
2022-01-22T21:30:26.000Z
|
// AUTO GENERATED by vnxcppcodegen
#include <vnx/package.hxx>
#include <vnx/ModuleInterface.hxx>
#include <vnx/ModuleInfo.hxx>
#include <vnx/ModuleInterface_vnx_get_config.hxx>
#include <vnx/ModuleInterface_vnx_get_config_return.hxx>
#include <vnx/ModuleInterface_vnx_get_config_object.hxx>
#include <vnx/ModuleInterface_vnx_get_config_object_return.hxx>
#include <vnx/ModuleInterface_vnx_get_module_info.hxx>
#include <vnx/ModuleInterface_vnx_get_module_info_return.hxx>
#include <vnx/ModuleInterface_vnx_get_type_code.hxx>
#include <vnx/ModuleInterface_vnx_get_type_code_return.hxx>
#include <vnx/ModuleInterface_vnx_restart.hxx>
#include <vnx/ModuleInterface_vnx_restart_return.hxx>
#include <vnx/ModuleInterface_vnx_self_test.hxx>
#include <vnx/ModuleInterface_vnx_self_test_return.hxx>
#include <vnx/ModuleInterface_vnx_set_config.hxx>
#include <vnx/ModuleInterface_vnx_set_config_return.hxx>
#include <vnx/ModuleInterface_vnx_set_config_object.hxx>
#include <vnx/ModuleInterface_vnx_set_config_object_return.hxx>
#include <vnx/ModuleInterface_vnx_stop.hxx>
#include <vnx/ModuleInterface_vnx_stop_return.hxx>
#include <vnx/Object.hpp>
#include <vnx/TypeCode.hpp>
#include <vnx/Variant.hpp>
#include <vnx/vnx.h>
namespace vnx {
const vnx::Hash64 ModuleInterface::VNX_TYPE_HASH(0xe189eb244fe14948ull);
const vnx::Hash64 ModuleInterface::VNX_CODE_HASH(0xe189eb244fe14948ull);
} // namespace vnx
namespace vnx {
} // vnx
| 32.568182
| 72
| 0.836706
|
MMX-World
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.