hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cf65bf0e6b368a9f22c998f5fe83b42b89c5c720
| 310
|
hpp
|
C++
|
systemc.hpp
|
dcblack/Simple-SystemC-Debug
|
b7997c7cb3b5ba0eed2016a2ae5ff85989216982
|
[
"Apache-2.0"
] | 1
|
2021-06-20T02:26:30.000Z
|
2021-06-20T02:26:30.000Z
|
systemc.hpp
|
dcblack/Simple-SystemC-Debug
|
b7997c7cb3b5ba0eed2016a2ae5ff85989216982
|
[
"Apache-2.0"
] | null | null | null |
systemc.hpp
|
dcblack/Simple-SystemC-Debug
|
b7997c7cb3b5ba0eed2016a2ae5ff85989216982
|
[
"Apache-2.0"
] | 1
|
2021-03-01T14:58:27.000Z
|
2021-03-01T14:58:27.000Z
|
#pragma once
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <systemc>
#include <sc_time_literal.hpp>
#pragma clang diagnostic pop
#pragma GCC diagnostic pop
//vim:syntax=systemc
| 28.181818
| 53
| 0.790323
|
dcblack
|
cf661d16ad9e0680abcf6f9984f642f6d3e51eb3
| 3,293
|
cpp
|
C++
|
test/src/player_test.cpp
|
nathiss/Fusion
|
673245a68f75997494deec202bdffdea6ac78d48
|
[
"MIT"
] | null | null | null |
test/src/player_test.cpp
|
nathiss/Fusion
|
673245a68f75997494deec202bdffdea6ac78d48
|
[
"MIT"
] | null | null | null |
test/src/player_test.cpp
|
nathiss/Fusion
|
673245a68f75997494deec202bdffdea6ac78d48
|
[
"MIT"
] | null | null | null |
/**
* @file player_test.cpp
*
* This module is a part of Fusion Server project.
* It contains the implementation of the unit tests for the Player class.
*
* Copyright 2019 Kamil Rusin
*/
#include <gtest/gtest.h>
#include <fusion_server/ui/player.hpp>
using namespace fusion_server;
TEST(PlayerTest, SerializeIncludesAllFields) {
// Arrange
ui::Player player{0, 0, "", 0.0, {}, 0.0, {}};
// Act
auto json = player.Serialize();
// Assert
ASSERT_EQ(decltype(json)::value_t::object, json.type());
EXPECT_TRUE(json.contains("player_id"));
EXPECT_TRUE(json.contains("team_id"));
EXPECT_TRUE(json.contains("nick"));
EXPECT_TRUE(json.contains("color"));
EXPECT_TRUE(json.contains("health"));
EXPECT_TRUE(json.contains("position"));
EXPECT_TRUE(json.contains("angle"));
}
TEST(PlayerTest, SerializeAllFieldsHaveProperTypes) {
// Arrange
ui::Player player{0, 0, "", 0.0, {}, 0.0, {}};
// Act
auto json = player.Serialize();
// Assert
EXPECT_EQ(decltype(json)::value_t::number_unsigned, json["player_id"].type());
EXPECT_EQ(decltype(json)::value_t::number_unsigned, json["team_id"].type());
EXPECT_EQ(decltype(json)::value_t::string, json["nick"].type());
EXPECT_EQ(decltype(json)::value_t::number_float, json["health"].type());
EXPECT_EQ(decltype(json)::value_t::number_float, json["angle"].type());
// Color
ASSERT_EQ(decltype(json)::value_t::array, json["color"].type());
ASSERT_EQ(3, json["color"].size());
EXPECT_EQ(decltype(json)::value_t::number_unsigned, json["color"][0].type());
EXPECT_EQ(decltype(json)::value_t::number_unsigned, json["color"][1].type());
EXPECT_EQ(decltype(json)::value_t::number_unsigned, json["color"][2].type());
// Position
ASSERT_EQ(decltype(json)::value_t::array, json["position"].type());
ASSERT_EQ(2, json["position"].size());
EXPECT_EQ(decltype(json)::value_t::number_integer, json["position"][0].type());
EXPECT_EQ(decltype(json)::value_t::number_integer, json["position"][1].type());
}
TEST(PlayerTest, SetPositionWithSeperatedCoordinates) {
// Arrange
ui::Player player{0, 0, "", 0.0, {}, 0.0, {}};
// Act
player.SetPosition(-1337, 9001);
// Assert
auto json = player.Serialize();
EXPECT_TRUE(-1337 == json["position"][0]);
EXPECT_TRUE(9001 == json["position"][1]);
}
TEST(PlayerTest, SetPositionWithPointClassArgument) {
// Arrange
ui::Player player{0, 0, "", 0.0, {}, 0.0, {}};
// Act
player.SetPosition({-1337, 9001});
// Assert
auto json = player.Serialize();
EXPECT_TRUE(-1337 == json["position"][0]);
EXPECT_TRUE(9001 == json["position"][1]);
}
TEST(PlayerTest, SetAngle) {
// Arrange
ui::Player player{0, 0, "", 0.0, {}, 0.0, {}};
// Act
player.SetAngle(3.14);
// Assert
auto json = player.Serialize();
EXPECT_EQ(3.14, json["angle"]);
}
TEST(PlayerTest, GetId) {
// Arrange
ui::Player player1{0, 0, "", 0.0, {}, 0.0, {}};
ui::Player player2{1337, 0, "", 0.0, {}, 0.0, {}};
// Act
// Assert
EXPECT_EQ(0, player1.GetId());
EXPECT_EQ(1337, player2.GetId());
}
TEST(PlayerTest, GetIdTheSameAsSerialise) {
// Arrange
ui::Player player{1337, 0, "", 0.0, {}, 0.0, {}};
auto json = player.Serialize();
// Act
// Assert
EXPECT_EQ(1337, player.GetId());
EXPECT_EQ(1337, json["player_id"]);
}
| 26.991803
| 81
| 0.653811
|
nathiss
|
cf6cf656205dfebbe7b6c6f7babd454f63dbfde3
| 486
|
cpp
|
C++
|
problemsets/Codeforces/C++/A910.cpp
|
juarezpaulino/coderemite
|
a4649d3f3a89d234457032d14a6646b3af339ac1
|
[
"Apache-2.0"
] | null | null | null |
problemsets/Codeforces/C++/A910.cpp
|
juarezpaulino/coderemite
|
a4649d3f3a89d234457032d14a6646b3af339ac1
|
[
"Apache-2.0"
] | null | null | null |
problemsets/Codeforces/C++/A910.cpp
|
juarezpaulino/coderemite
|
a4649d3f3a89d234457032d14a6646b3af339ac1
|
[
"Apache-2.0"
] | null | null | null |
/**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
int n, d; cin >> n >> d;
int p = 0, l = p+d, next = -1;
string a; cin >> a;
int ret = 0;
for (int i = 1; i < n; i++) {
if (a[i]=='1') next = i;
if (i == l || i == n-1) {
if (next == -1) { cout << "-1"; return 0; }
ret++; l = next+d; p = next; next = -1;
}
}
cout << ret;
}
| 19.44
| 49
| 0.469136
|
juarezpaulino
|
cf74b621634e4acb8c7e54c991f4ec11a5b7900c
| 14,792
|
cpp
|
C++
|
main.cpp
|
Sundragon1993/AI-Game-Pratices
|
7549b23f71c3b2b5145388f0d8d4900bdb307a7a
|
[
"MIT"
] | null | null | null |
main.cpp
|
Sundragon1993/AI-Game-Pratices
|
7549b23f71c3b2b5145388f0d8d4900bdb307a7a
|
[
"MIT"
] | null | null | null |
main.cpp
|
Sundragon1993/AI-Game-Pratices
|
7549b23f71c3b2b5145388f0d8d4900bdb307a7a
|
[
"MIT"
] | null | null | null |
#pragma warning (disable:4786)
#include <windows.h>
#include <time.h>
#include "constants.h"
#include "misc/utils.h"
#include "Time/PrecisionTimer.h"
#include "Resource.h"
#include "misc/windowutils.h"
#include "misc/Cgdi.h"
#include "debug/DebugConsole.h"
#include "Raven_UserOptions.h"
#include "Raven_Game.h"
#include "lua/Raven_Scriptor.h"
//need to include this for the toolbar stuff
#include <commctrl.h>
#pragma comment(lib, "comctl32.lib")
//--------------------------------- Globals ------------------------------
//------------------------------------------------------------------------
char* g_szApplicationName = "Raven";
char* g_szWindowClassName = "MyWindowClass";
Raven_Game* g_pRaven;
//---------------------------- WindowProc ---------------------------------
//
// This is the callback function which handles all the windows messages
//-------------------------------------------------------------------------
LRESULT CALLBACK WindowProc (HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam)
{
//these hold the dimensions of the client window area
static int cxClient, cyClient;
//used to create the back buffer
static HDC hdcBackBuffer;
static HBITMAP hBitmap;
static HBITMAP hOldBitmap;
//to grab filenames
static TCHAR szFileName[MAX_PATH],
szTitleName[MAX_PATH];
switch (msg)
{
//A WM_CREATE msg is sent when your application window is first
//created
case WM_CREATE:
{
//to get get the size of the client window first we need to create
//a RECT and then ask Windows to fill in our RECT structure with
//the client window size. Then we assign to cxClient and cyClient
//accordingly
RECT rect;
GetClientRect(hwnd, &rect);
cxClient = rect.right;
cyClient = rect.bottom;
//seed random number generator
srand((unsigned) time(NULL));
//---------------create a surface to render to(backbuffer)
//create a memory device context
hdcBackBuffer = CreateCompatibleDC(NULL);
//get the DC for the front buffer
HDC hdc = GetDC(hwnd);
hBitmap = CreateCompatibleBitmap(hdc,
cxClient,
cyClient);
//select the bitmap into the memory device context
hOldBitmap = (HBITMAP)SelectObject(hdcBackBuffer, hBitmap);
//don't forget to release the DC
ReleaseDC(hwnd, hdc);
//create the game
g_pRaven = new Raven_Game();
//make sure the menu items are ticked/unticked accordingly
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_NAVGRAPH, UserOptions->m_bShowGraph);
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_PATH, UserOptions->m_bShowPathOfSelectedBot);
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_IDS, UserOptions->m_bShowBotIDs);
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_QUICK, UserOptions->m_bSmoothPathsQuick);
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_PRECISE, UserOptions->m_bSmoothPathsPrecise);
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_HEALTH, UserOptions->m_bShowBotHealth);
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_TARGET, UserOptions->m_bShowTargetOfSelectedBot);
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_FOV, UserOptions->m_bOnlyShowBotsInTargetsFOV);
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_SCORES, UserOptions->m_bShowScore);
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_GOAL_Q, UserOptions->m_bShowGoalsOfSelectedBot);
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_INDICES, UserOptions->m_bShowNodeIndices);
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_SENSED, UserOptions->m_bShowOpponentsSensedBySelectedBot);
}
break;
case WM_KEYUP:
{
switch(wParam)
{
case VK_ESCAPE:
{
SendMessage(hwnd, WM_DESTROY, NULL, NULL);
}
break;
case 'P':
g_pRaven->TogglePause();
break;
case '1':
g_pRaven->ChangeWeaponOfPossessedBot(type_blaster);
break;
case '2':
g_pRaven->ChangeWeaponOfPossessedBot(type_shotgun);
break;
case '3':
g_pRaven->ChangeWeaponOfPossessedBot(type_rocket_launcher);
break;
case '4':
g_pRaven->ChangeWeaponOfPossessedBot(type_rail_gun);
break;
case 'X':
g_pRaven->ExorciseAnyPossessedBot();
break;
case VK_UP:
g_pRaven->AddBots(1); break;
case VK_DOWN:
g_pRaven->RemoveBot(); break;
}
}
break;
case WM_LBUTTONDOWN:
{
g_pRaven->ClickLeftMouseButton(MAKEPOINTS(lParam));
}
break;
case WM_RBUTTONDOWN:
{
g_pRaven->ClickRightMouseButton(MAKEPOINTS(lParam));
}
break;
case WM_COMMAND:
{
switch(wParam)
{
case IDM_GAME_LOAD:
FileOpenDlg(hwnd, szFileName, szTitleName, "Raven map file (*.map)", "map");
debug_con << "Filename: " << szTitleName << "";
if (strlen(szTitleName) > 0)
{
g_pRaven->LoadMap(szTitleName);
}
break;
case IDM_GAME_ADDBOT:
g_pRaven->AddBots(1);
break;
case IDM_GAME_REMOVEBOT:
g_pRaven->RemoveBot();
break;
case IDM_GAME_PAUSE:
g_pRaven->TogglePause();
break;
case IDM_NAVIGATION_SHOW_NAVGRAPH:
UserOptions->m_bShowGraph = !UserOptions->m_bShowGraph;
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_NAVGRAPH, UserOptions->m_bShowGraph);
break;
case IDM_NAVIGATION_SHOW_PATH:
UserOptions->m_bShowPathOfSelectedBot = !UserOptions->m_bShowPathOfSelectedBot;
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_PATH, UserOptions->m_bShowPathOfSelectedBot);
break;
case IDM_NAVIGATION_SHOW_INDICES:
UserOptions->m_bShowNodeIndices = !UserOptions->m_bShowNodeIndices;
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_INDICES, UserOptions->m_bShowNodeIndices);
break;
case IDM_NAVIGATION_SMOOTH_PATHS_QUICK:
UserOptions->m_bSmoothPathsQuick = !UserOptions->m_bSmoothPathsQuick;
UserOptions->m_bSmoothPathsPrecise = false;
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_PRECISE, UserOptions->m_bSmoothPathsPrecise);
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_QUICK, UserOptions->m_bSmoothPathsQuick);
break;
case IDM_NAVIGATION_SMOOTH_PATHS_PRECISE:
UserOptions->m_bSmoothPathsPrecise = !UserOptions->m_bSmoothPathsPrecise;
UserOptions->m_bSmoothPathsQuick = false;
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_QUICK, UserOptions->m_bSmoothPathsQuick);
CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_PRECISE, UserOptions->m_bSmoothPathsPrecise);
break;
case IDM_BOTS_SHOW_IDS:
UserOptions->m_bShowBotIDs = !UserOptions->m_bShowBotIDs;
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_IDS, UserOptions->m_bShowBotIDs);
break;
case IDM_BOTS_SHOW_HEALTH:
UserOptions->m_bShowBotHealth = !UserOptions->m_bShowBotHealth;
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_HEALTH, UserOptions->m_bShowBotHealth);
break;
case IDM_BOTS_SHOW_TARGET:
UserOptions->m_bShowTargetOfSelectedBot = !UserOptions->m_bShowTargetOfSelectedBot;
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_TARGET, UserOptions->m_bShowTargetOfSelectedBot);
break;
case IDM_BOTS_SHOW_SENSED:
UserOptions->m_bShowOpponentsSensedBySelectedBot = !UserOptions->m_bShowOpponentsSensedBySelectedBot;
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_SENSED, UserOptions->m_bShowOpponentsSensedBySelectedBot);
break;
case IDM_BOTS_SHOW_FOV:
UserOptions->m_bOnlyShowBotsInTargetsFOV = !UserOptions->m_bOnlyShowBotsInTargetsFOV;
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_FOV, UserOptions->m_bOnlyShowBotsInTargetsFOV);
break;
case IDM_BOTS_SHOW_SCORES:
UserOptions->m_bShowScore = !UserOptions->m_bShowScore;
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_SCORES, UserOptions->m_bShowScore);
break;
case IDM_BOTS_SHOW_GOAL_Q:
UserOptions->m_bShowGoalsOfSelectedBot = !UserOptions->m_bShowGoalsOfSelectedBot;
CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_GOAL_Q, UserOptions->m_bShowGoalsOfSelectedBot);
break;
}//end switch
}
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint (hwnd, &ps);
//fill our backbuffer with white
BitBlt(hdcBackBuffer,
0,
0,
cxClient,
cyClient,
NULL,
NULL,
NULL,
WHITENESS);
gdi->StartDrawing(hdcBackBuffer);
g_pRaven->Render();
gdi->StopDrawing(hdcBackBuffer);
//now blit backbuffer to front
BitBlt(ps.hdc, 0, 0, cxClient, cyClient, hdcBackBuffer, 0, 0, SRCCOPY);
EndPaint (hwnd, &ps);
}
break;
//has the user resized the client area?
case WM_SIZE:
{
//if so we need to update our variables so that any drawing
//we do using cxClient and cyClient is scaled accordingly
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
//now to resize the backbuffer accordingly. First select
//the old bitmap back into the DC
SelectObject(hdcBackBuffer, hOldBitmap);
//don't forget to do this or you will get resource leaks
DeleteObject(hBitmap);
//get the DC for the application
HDC hdc = GetDC(hwnd);
//create another bitmap of the same size and mode
//as the application
hBitmap = CreateCompatibleBitmap(hdc,
cxClient,
cyClient);
ReleaseDC(hwnd, hdc);
//select the new bitmap into the DC
SelectObject(hdcBackBuffer, hBitmap);
}
break;
case WM_DESTROY:
{
//clean up our backbuffer objects
SelectObject(hdcBackBuffer, hOldBitmap);
DeleteDC(hdcBackBuffer);
DeleteObject(hBitmap);
// kill the application, this sends a WM_QUIT message
PostQuitMessage (0);
}
break;
}//end switch
//this is where all the messages not specifically handled by our
//winproc are sent to be processed
return DefWindowProc (hwnd, msg, wParam, lParam);
}
//-------------------------------- WinMain -------------------------------
//
// The entry point of the windows program
//------------------------------------------------------------------------
int WINAPI WinMain (HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR szCmdLine,
int iCmdShow)
{
MSG msg;
//handle to our window
HWND hWnd;
//the window class structure
WNDCLASSEX winclass;
// first fill in the window class stucture
winclass.cbSize = sizeof(WNDCLASSEX);
winclass.style = CS_HREDRAW | CS_VREDRAW;
winclass.lpfnWndProc = WindowProc;
winclass.cbClsExtra = 0;
winclass.cbWndExtra = 0;
winclass.hInstance = hInstance;
winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
winclass.hCursor = LoadCursor(NULL, IDC_ARROW);
winclass.hbrBackground = NULL;
winclass.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1);
winclass.lpszClassName = g_szWindowClassName;
winclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
//register the window class
if (!RegisterClassEx(&winclass))
{
MessageBox(NULL, "Registration Failed!", "Error", 0);
//exit the application
return 0;
}
try
{
//create the window and assign its ID to hwnd
hWnd = CreateWindowEx (NULL, // extended style
g_szWindowClassName, // window class name
g_szApplicationName, // window caption
WS_OVERLAPPED | WS_VISIBLE | WS_CAPTION | WS_SYSMENU, // window style
GetSystemMetrics(SM_CXSCREEN)/2 - WindowWidth/2,
GetSystemMetrics(SM_CYSCREEN)/2 - WindowHeight/2,
WindowWidth, // initial x size
WindowHeight, // initial y size
NULL, // parent window handle
NULL, // window menu handle
hInstance, // program instance handle
NULL); // creation parameters
//make sure the window creation has gone OK
if(!hWnd)
{
MessageBox(NULL, "CreateWindowEx Failed!", "Error!", 0);
}
//make the window visible
ShowWindow (hWnd, iCmdShow);
UpdateWindow (hWnd);
//create a timer
PrecisionTimer timer(FrameRate);
//start the timer
timer.Start();
//enter the message loop
bool bDone = false;
while(!bDone)
{
while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
{
if( msg.message == WM_QUIT )
{
// Stop loop if it's a quit message
bDone = true;
}
else
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
if (timer.ReadyForNextFrame() && msg.message != WM_QUIT)
{
g_pRaven->Update();
//render
RedrawWindow(hWnd);
}
//give the OS a little time
Sleep(2);
}//end while
}//end try block
catch (const std::runtime_error& err)
{
ErrorBox(std::string(err.what()));
//tidy up
delete g_pRaven;
UnregisterClass( g_szWindowClassName, winclass.hInstance );
return 0;
}
//tidy up
UnregisterClass( g_szWindowClassName, winclass.hInstance );
delete g_pRaven;
return msg.wParam;
}
| 26.700361
| 114
| 0.60046
|
Sundragon1993
|
cf77bbe20e26934dc3acc307f4b1caa8f6b7cdfd
| 391
|
cpp
|
C++
|
cpp/cpp_primer/chapter19/ex_19_03.cpp
|
KaiserLancelot/Cpp-Primer
|
a4791a6765f0b6c864e8881e6a5328e2a3d68974
|
[
"MIT"
] | 2
|
2019-12-21T00:53:47.000Z
|
2020-01-01T10:36:30.000Z
|
cpp/cpp_primer/chapter19/ex_19_03.cpp
|
KaiserLancelot/Cpp-Primer
|
a4791a6765f0b6c864e8881e6a5328e2a3d68974
|
[
"MIT"
] | null | null | null |
cpp/cpp_primer/chapter19/ex_19_03.cpp
|
KaiserLancelot/Cpp-Primer
|
a4791a6765f0b6c864e8881e6a5328e2a3d68974
|
[
"MIT"
] | null | null | null |
//
// Created by kaiser on 19-3-16.
//
#include <iostream>
class A {
public:
virtual ~A() = default;
};
class B : public A {};
class C : public B {};
int main() {
{
A* pa = new C;
if (B* pb = dynamic_cast<B*>(pa); !pb) {
std::cerr << "error 1\n";
}
}
{
B* pb = new B;
if (C* pc = dynamic_cast<C*>(pb); !pc) {
std::cerr << "error 2\n";
}
}
}
| 13.964286
| 44
| 0.468031
|
KaiserLancelot
|
cf78dd0d497dca8c6985d07ecff1df821163605a
| 5,508
|
cpp
|
C++
|
src/hdp_py.cpp
|
jstraub/bnp
|
11cd28b49e9cf1db96f349181aff57a17672b6a4
|
[
"MIT"
] | 12
|
2015-01-13T01:18:39.000Z
|
2021-06-16T20:16:54.000Z
|
src/hdp_py.cpp
|
jstraub/bnp
|
11cd28b49e9cf1db96f349181aff57a17672b6a4
|
[
"MIT"
] | 1
|
2015-07-12T12:58:14.000Z
|
2015-07-12T12:58:14.000Z
|
src/hdp_py.cpp
|
jstraub/bnp
|
11cd28b49e9cf1db96f349181aff57a17672b6a4
|
[
"MIT"
] | 2
|
2017-07-22T05:37:10.000Z
|
2018-08-26T07:11:34.000Z
|
/* Copyright (c) 2012, Julian Straub <jstraub@csail.mit.edu>
* Licensed under the MIT license. See LICENSE.txt or
* http://www.opensource.org/licenses/mit-license.php */
#include <baseMeasure_py.hpp>
#include <hdp_gibbs_py.hpp>
#include <hdp_var_py.hpp>
#include <hdp_var_base_py.hpp>
// using the hdp which utilizes sufficient statistics
//#include <hdp_var_ss.hpp>
#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <typeinfo>
#include <armadillo>
#include <boost/python.hpp>
#include <boost/python/wrapper.hpp>
#include <numpy/ndarrayobject.h> // for PyArrayObject
#ifdef PYTHON_2_6
#include <python2.6/object.h> // for PyArray_FROM_O
#endif
#ifdef PYTHON_2_7
#include <python2.7/object.h> // for PyArray_FROM_O
#endif
using namespace boost::python;
BOOST_PYTHON_MODULE(libbnp)
{
import_array();
boost::python::numeric::array::set_module_and_type("numpy", "ndarray");
class_<Dir_py>("Dir", init<numeric::array>())
.def(init<Dir_py>())
.def("asRow",&Dir_py::asRow)
.def("rowDim",&Dir_py::rowDim);
class_<NIW_py>("NIW",init<const numeric::array, double, const numeric::array, double>())
.def(init<NIW_py>())
.def("asRow",&NIW_py::asRow)
.def("rowDim",&NIW_py::rowDim);
// class_<DP_Dir>("DP_Dir",init<Dir_py,double>());
// class_<DP_INW>("DP_INW",init<NIW_py,double>());
class_<HDP_gibbs_Dir>("HDP_gibbs_Dir",init<Dir_py&,double,double>())
.def("densityEst",&HDP_gibbs_Dir::densityEst)
.def("getClassLabels",&HDP_gibbs_Dir::getClassLabels)
.def("addDoc",&HDP_gibbs_Dir::addDoc)
.def("addHeldOut",&HDP_gibbs_Dir::addHeldOut)
.def("getPerplexity",&HDP_gibbs_Dir::getPerplexity);
// .def_readonly("mGamma", &HDP_Dir::mGamma);
class_<HDP_gibbs_NIW>("HDP_gibbs_NIW",init<NIW_py&,double,double>())
.def("densityEst",&HDP_gibbs_NIW::densityEst)
.def("getClassLabels",&HDP_gibbs_NIW::getClassLabels)
.def("addDoc",&HDP_gibbs_NIW::addDoc);
// .def_readonly("mGamma", &HDP_NIW::mGamma);
class_<HDP_var_Dir_py>("HDP_var_Dir",init<Dir_py&,double,double>())
.def("densityEst",&HDP_var_Dir_py::densityEst)
//TODO: not sure that one works: .def("updateEst",&HDP_var_Dir_py::updateEst)
.def("updateEst_batch",&HDP_var_Dir_py::updateEst_batch)
.def("addDoc",&HDP_var_Dir_py::addDoc)
.def("addHeldOut",&HDP_var_Dir_py::addHeldOut)
.def("getPerplexity",&HDP_var_Dir_py::getPerplexity_py)
.def("getA",&HDP_var_Dir_py::getA_py)
.def("getTopicPriorDescriptionLength",&HDP_var_Dir_py::getTopicPriorDescriptionLength)
.def("getLambda",&HDP_var_Dir_py::getLambda_py)
.def("getDocTopics",&HDP_var_Dir_py::getDocTopics_py)
.def("getWordTopics",&HDP_var_Dir_py::getWordTopics_py)
.def("getCorpTopicProportions",&HDP_var_Dir_py::getCorpTopicProportions_py)
.def("getTopicsDescriptionLength",&HDP_var_Dir_py::getTopicsDescriptionLength)
.def("getCorpTopics",&HDP_var_Dir_py::getCorpTopics_py)
.def("getWordDistr",&HDP_var_Dir_py::getWordDistr_py);
// .def_readonly("mGamma", &HDP_var_Dir_py::mGamma);
// .def("perplexity",&HDP_var_Dir_py::perplexity)
class_<HDP_var_NIW_py>("HDP_var_NIW",init<NIW_py&,double,double>())
.def("densityEst",&HDP_var_NIW_py::densityEst)
//TODO: not sure that one works: .def("updateEst",&HDP_var_NIW_py::updateEst)
.def("updateEst_batch",&HDP_var_NIW_py::updateEst_batch)
.def("addDoc",&HDP_var_NIW_py::addDoc)
.def("addHeldOut",&HDP_var_NIW_py::addHeldOut)
.def("getPerplexity",&HDP_var_NIW_py::getPerplexity_py)
.def("getA",&HDP_var_NIW_py::getA_py)
.def("getTopicPriorDescriptionLength",&HDP_var_NIW_py::getTopicPriorDescriptionLength)
.def("getLambda",&HDP_var_NIW_py::getLambda_py)
.def("getDocTopics",&HDP_var_NIW_py::getDocTopics_py)
.def("getWordTopics",&HDP_var_NIW_py::getWordTopics_py)
.def("getCorpTopicProportions",&HDP_var_NIW_py::getCorpTopicProportions_py)
.def("getTopicsDescriptionLength",&HDP_var_NIW_py::getTopicsDescriptionLength)
.def("getCorpTopics",&HDP_var_NIW_py::getCorpTopics_py)
.def("getWordDistr",&HDP_var_NIW_py::getWordDistr_py);
// .def_readonly("mGamma", &HDP_var_NIW_py::mGamma);
// .def("perplexity",&HDP_var_NIW_py::perplexity)
// class_<HDP_var_ss_py>("HDP_var_ss",init<Dir_py&,double,double>())
// .def("densityEst",&HDP_var_ss_py::densityEst)
// //TODO: not sure that one works .def("updateEst",&HDP_var_ss_py::updateEst)
// .def("getPerplexity",&HDP_var_ss_py::getPerplexity_py)
// .def("getA",&HDP_var_ss_py::getA_py)
// .def("getLambda",&HDP_var_ss_py::getLambda_py)
// .def("getDocTopics",&HDP_var_ss_py::getDocTopics_py)
// .def("getWordTopics",&HDP_var_ss_py::getWordTopics_py)
// .def("getCorpTopicProportions",&HDP_var_ss_py::getCorpTopicProportions_py)
// .def("getCorpTopics",&HDP_var_ss_py::getCorpTopics_py)
// .def("getWordDistr",&HDP_var_ss_py::getWordDistr_py);
// .def("perplexity",&HDP_var_ss_py::perplexity)
class_<TestNp2Arma_py>("TestNp2Arma",init<>())
.def("getAmat",&TestNp2Arma_py::getAmat)
.def("getArect",&TestNp2Arma_py::getArect)
.def("putArect",&TestNp2Arma_py::putArect)
.def("getAcol",&TestNp2Arma_py::getAcol)
.def("resizeAmat",&TestNp2Arma_py::resizeAmat)
.def("getArow",&TestNp2Arma_py::getArow);
}
| 43.714286
| 94
| 0.69971
|
jstraub
|
cf79eafceff5d8d46fae59e5aa56764304bdc8ef
| 1,307
|
hpp
|
C++
|
code/adobe.poly/adobe/implementation/string_pool.hpp
|
andyprowl/virtual-concepts
|
ed3a5690c353b6998abcd3368a9b448f1bb2aa19
|
[
"Unlicense"
] | 59
|
2015-04-01T12:55:36.000Z
|
2021-06-22T02:46:20.000Z
|
adobe/implementation/string_pool.hpp
|
brycelelbach/asl
|
df0d271f6c67fbb944039a9455c4eb69ae6df141
|
[
"MIT"
] | 1
|
2015-06-29T14:51:55.000Z
|
2015-06-29T16:40:26.000Z
|
adobe/implementation/string_pool.hpp
|
brycelelbach/asl
|
df0d271f6c67fbb944039a9455c4eb69ae6df141
|
[
"MIT"
] | 5
|
2016-04-19T09:21:11.000Z
|
2021-12-29T09:48:09.000Z
|
/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/*************************************************************************************************/
#ifndef ADOBE_STRING_POOL_HPP
#define ADOBE_STRING_POOL_HPP
/*************************************************************************************************/
#include <adobe/config.hpp>
#include <boost/noncopyable.hpp>
/*************************************************************************************************/
namespace adobe {
/**************************************************************************************************/
class unique_string_pool_t : boost::noncopyable
{
public:
unique_string_pool_t();
~unique_string_pool_t();
const char* add(const char* str);
private:
struct implementation_t;
implementation_t* object_m;
};
/**************************************************************************************************/
} // namespace adobe
/**************************************************************************************************/
#endif
/**************************************************************************************************/
| 26.673469
| 100
| 0.337414
|
andyprowl
|
cf7af2af2ce72a6cd137dfa8c94cc6880fa00c92
| 4,290
|
hpp
|
C++
|
include/ipfixprobe/process.hpp
|
CESNET/NEMEA-probe
|
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
|
[
"BSD-3-Clause"
] | null | null | null |
include/ipfixprobe/process.hpp
|
CESNET/NEMEA-probe
|
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
|
[
"BSD-3-Clause"
] | null | null | null |
include/ipfixprobe/process.hpp
|
CESNET/NEMEA-probe
|
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* \file process.hpp
* \brief Generic interface of processing plugin
* \author Vaclav Bartos <bartos@cesnet.cz>
* \author Jiri Havranek <havranek@cesnet.cz>
* \date 2021
*/
/*
* Copyright (C) 2021 CESNET
*
* LICENSE TERMS
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of the Company nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* ALTERNATIVELY, provided that this notice is retained in full, this
* product may be distributed under the terms of the GNU General Public
* License (GPL) version 2 or later, in which case the provisions
* of the GPL apply INSTEAD OF those given above.
*
* This software is provided ``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 company or contributors be liable for any
* direct, indirect, incidental, special, exemplary, or consequential
* damages (including, but not limited to, procurement of substitute
* goods or services; loss of use, data, or profits; or business
* interruption) however caused and on any theory of liability, whether
* in contract, strict liability, or tort (including negligence or
* otherwise) arising in any way out of the use of this software, even
* if advised of the possibility of such damage.
*
*/
#ifndef IPXP_PROCESS_HPP
#define IPXP_PROCESS_HPP
#include <string>
#include <vector>
#include "plugin.hpp"
#include "packet.hpp"
#include "flowifc.hpp"
namespace ipxp {
/**
* \brief Tell storage plugin to flush (immediately export) current flow.
* Behavior when called from post_create, pre_update and post_update: flush current Flow and erase FlowRecord.
*/
#define FLOW_FLUSH 0x1
/**
* \brief Tell storage plugin to flush (immediately export) current flow.
* Behavior when called from post_create: flush current Flow and erase FlowRecord.
* Behavior when called from pre_update and post_update: flush current Flow, erase FlowRecord and call post_create on packet.
*/
#define FLOW_FLUSH_WITH_REINSERT 0x3
/**
* \brief Class template for flow cache plugins.
*/
class ProcessPlugin : public Plugin
{
public:
ProcessPlugin() {}
virtual ~ProcessPlugin() {}
virtual ProcessPlugin *copy() = 0;
virtual RecordExt *get_ext() const
{
return nullptr;
}
/**
* \brief Called before a new flow record is created.
* \param [in] pkt Parsed packet.
* \return 0 on success or FLOW_FLUSH option.
*/
virtual int pre_create(Packet &pkt)
{
return 0;
}
/**
* \brief Called after a new flow record is created.
* \param [in,out] rec Reference to flow record.
* \param [in] pkt Parsed packet.
* \return 0 on success or FLOW_FLUSH option.
*/
virtual int post_create(Flow &rec, const Packet &pkt)
{
return 0;
}
/**
* \brief Called before an existing record is update.
* \param [in,out] rec Reference to flow record.
* \param [in,out] pkt Parsed packet.
* \return 0 on success or FLOW_FLUSH option.
*/
virtual int pre_update(Flow &rec, Packet &pkt)
{
return 0;
}
/**
* \brief Called after an existing record is updated.
* \param [in,out] rec Reference to flow record.
* \param [in,out] pkt Parsed packet.
* \return 0 on success or FLOW_FLUSH option.
*/
virtual int post_update(Flow &rec, const Packet &pkt)
{
return 0;
}
/**
* \brief Called before a flow record is exported from the cache.
* \param [in,out] rec Reference to flow record.
*/
virtual void pre_export(Flow &rec)
{
}
};
}
#endif /* IPXP_PROCESS_HPP */
| 30.863309
| 125
| 0.701399
|
CESNET
|
cf7afec8d91451c3ae14adbeefc7ed64963657d9
| 743
|
hh
|
C++
|
src/collider-manager-2d.hh
|
obs145628/opl
|
aeb8e70f3dbca8b8564cd829c2327df25e00392e
|
[
"MIT"
] | null | null | null |
src/collider-manager-2d.hh
|
obs145628/opl
|
aeb8e70f3dbca8b8564cd829c2327df25e00392e
|
[
"MIT"
] | null | null | null |
src/collider-manager-2d.hh
|
obs145628/opl
|
aeb8e70f3dbca8b8564cd829c2327df25e00392e
|
[
"MIT"
] | null | null | null |
/** @file ColliderManager2D ckass definition
*/
#ifndef COLLIDER_MANAGER_2D_HH_
# define COLLIDER_MANAGER_2D_HH_
# include <cstddef>
# include <map>
# include "object-2d.hh"
# include "collider-2d.hh"
namespace opl
{
class ColliderManager2D
{
public:
static ColliderManager2D*
instance ();
bool
are_colliding (Object2D* a, Object2D* b);
bool
are_colliding (Collider2D* a, Collider2D* b);
private:
using coll_fn_type = bool (*) (Collider2D*, Collider2D*);
static ColliderManager2D* instance_;
std::map<size_t, coll_fn_type> fns_;
ColliderManager2D ();
ColliderManager2D(const ColliderManager2D&) = delete;
static size_t
fn_id_get_ (size_t id1, size_t id2);
};
}
#endif //!COLLIDER_MANAGER_HH_
| 14.86
| 59
| 0.718708
|
obs145628
|
cf8d4a21fc6e4946e1b77ff96f8b80daa1ee0b32
| 164
|
hpp
|
C++
|
src/semantic.hpp
|
amzamora/diamond
|
c9cad46401815461ebae8db781bbb669c11bd257
|
[
"MIT"
] | 4
|
2021-02-02T19:55:23.000Z
|
2021-03-26T22:54:12.000Z
|
src/semantic.hpp
|
amzamora/diamond
|
c9cad46401815461ebae8db781bbb669c11bd257
|
[
"MIT"
] | 28
|
2021-01-31T01:04:54.000Z
|
2021-12-11T13:53:49.000Z
|
src/semantic.hpp
|
amzamora/diamond
|
c9cad46401815461ebae8db781bbb669c11bd257
|
[
"MIT"
] | null | null | null |
#ifndef SEMANTIC_HPP
#define SEMANTIC_HPP
#include "types.hpp"
namespace semantic {
Result<Ok, Errors> analyze(std::shared_ptr<Ast::Program> program);
}
#endif
| 14.909091
| 67
| 0.756098
|
amzamora
|
cf8e46de8aa704945cb4baf7c5036b98a61190e3
| 5,277
|
cxx
|
C++
|
main/sw/source/ui/config/caption.cxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 679
|
2015-01-06T06:34:58.000Z
|
2022-03-30T01:06:03.000Z
|
main/sw/source/ui/config/caption.cxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 102
|
2017-11-07T08:51:31.000Z
|
2022-03-17T12:13:49.000Z
|
main/sw/source/ui/config/caption.cxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 331
|
2015-01-06T11:40:55.000Z
|
2022-03-14T04:07:51.000Z
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <tools/debug.hxx>
#include "numrule.hxx"
#include "caption.hxx"
#define VERSION_01 1
#define CAPTION_VERSION VERSION_01
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
InsCaptionOpt::InsCaptionOpt(const SwCapObjType eType, const SvGlobalName* pOleId) :
bUseCaption(sal_False),
eObjType(eType),
nNumType(SVX_NUM_ARABIC),
sNumberSeparator( ::rtl::OUString::createFromAscii(". ") ),
nPos(1),
nLevel(0),
sSeparator( String::CreateFromAscii( ": " ) ),
bIgnoreSeqOpts(sal_False),
bCopyAttributes(sal_False)
{
if (pOleId)
aOleId = *pOleId;
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
InsCaptionOpt::InsCaptionOpt(const InsCaptionOpt& rOpt)
{
*this = rOpt;
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
InsCaptionOpt::~InsCaptionOpt()
{
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
InsCaptionOpt& InsCaptionOpt::operator=( const InsCaptionOpt& rOpt )
{
bUseCaption = rOpt.bUseCaption;
eObjType = rOpt.eObjType;
aOleId = rOpt.aOleId;
sCategory = rOpt.sCategory;
nNumType = rOpt.nNumType;
sNumberSeparator = rOpt.sNumberSeparator;
sCaption = rOpt.sCaption;
nPos = rOpt.nPos;
nLevel = rOpt.nLevel;
sSeparator = rOpt.sSeparator;
bIgnoreSeqOpts = rOpt.bIgnoreSeqOpts;
sCharacterStyle = rOpt.sCharacterStyle;
bCopyAttributes = rOpt.bCopyAttributes;
return *this;
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
sal_Bool InsCaptionOpt::operator==( const InsCaptionOpt& rOpt ) const
{
return (eObjType == rOpt.eObjType &&
aOleId == rOpt.aOleId); // Damit gleiche Ole-IDs nicht mehrfach eingefuegt
// werden koennen, auf nichts weiteres vergleichen
/* &&
sCategory == rOpt.sCategory &&
nNumType == rOpt.nNumType &&
sCaption == rOpt.sCaption &&
nPos == rOpt.nPos &&
nLevel == rOpt.nLevel &&
cSeparator == rOpt.cSeparator);*/
}
/*************************************************************************
|*
|* InsCaptionOpt::operator>>()
|*
|* Beschreibung Stream-Leseoperator
|*
*************************************************************************/
/*SvStream& operator>>( SvStream& rIStream, InsCaptionOpt& rCapOpt )
{
rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding();
sal_uInt16 nVal;
sal_uInt8 cVal;
sal_uInt8 nVersion;
rIStream >> nVersion;
rIStream >> cVal; rCapOpt.UseCaption() = cVal != 0;
rIStream >> nVal; rCapOpt.eObjType = (SwCapObjType)nVal;
rIStream >> rCapOpt.aOleId;
rIStream.ReadByteString( rCapOpt.sCategory, eEncoding );
rIStream >> nVal; rCapOpt.nNumType = nVal;
rIStream.ReadByteString( rCapOpt.sCaption, eEncoding );
rIStream >> nVal; rCapOpt.nPos = nVal;
rIStream >> nVal; rCapOpt.nLevel = nVal;
rIStream >> cVal;
rCapOpt.sSeparator = UniString(
ByteString(static_cast< char >(cVal)) , eEncoding).GetChar(0);
return rIStream;
}
*/
/*************************************************************************
|*
|* InsCaptionOpt::operator<<()
|*
|* Beschreibung Stream-Schreiboperator
|*
*************************************************************************/
/*SvStream& operator<<( SvStream& rOStream, const InsCaptionOpt& rCapOpt )
{
rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding();
rOStream << (sal_uInt8)CAPTION_VERSION
<< (sal_uInt8)rCapOpt.UseCaption()
<< (sal_uInt16)rCapOpt.eObjType
<< rCapOpt.aOleId;
rOStream.WriteByteString( rCapOpt.sCategory, eEncoding );
rOStream << (sal_uInt16)rCapOpt.nNumType;
rOStream.WriteByteString( rCapOpt.sCaption, eEncoding );
sal_uInt8 cSep = ByteString(rCapOpt.sSeparator, eEncoding).GetChar(0);
rOStream << (sal_uInt16)rCapOpt.nPos
<< (sal_uInt16)rCapOpt.nLevel
<< cSep;
return rOStream;
}
*/
| 29.480447
| 84
| 0.565094
|
Grosskopf
|
cf90ef7c36bf959177421f9dd048e4f5d2ee1611
| 1,637
|
cpp
|
C++
|
src/GUI/Selection.cpp
|
szebest/Basic-SFML-Application-Framework
|
e6b979283a1aba87ea5eefb1785d6f9bf4485d4a
|
[
"MIT"
] | null | null | null |
src/GUI/Selection.cpp
|
szebest/Basic-SFML-Application-Framework
|
e6b979283a1aba87ea5eefb1785d6f9bf4485d4a
|
[
"MIT"
] | null | null | null |
src/GUI/Selection.cpp
|
szebest/Basic-SFML-Application-Framework
|
e6b979283a1aba87ea5eefb1785d6f9bf4485d4a
|
[
"MIT"
] | null | null | null |
#include "Selection.h"
Selection::Selection(sf::Vector2f pos) :
m_selected(false)
{
m_outerShape.setRadius(12);
m_innerShape.setRadius(10);
m_innerShape.setFillColor(sf::Color::Blue);
setPosition(pos);
}
void Selection::handleEvents(sf::Event e, const sf::RenderWindow& window, sf::Vector2f displacement)
{
switch (e.type) {
case sf::Event::MouseButtonPressed:
{
if (e.mouseButton.button == sf::Mouse::Left)
if (isHovering(window, displacement))
m_selected = !m_selected;
} break;
default:
break;
}
}
void Selection::update(const sf::Time& deltaTime)
{
}
void Selection::draw(sf::RenderTarget& target)
{
target.draw(m_outerShape);
if (m_selected)
target.draw(m_innerShape);
}
void Selection::setPosition(sf::Vector2f pos)
{
float outerRadius = m_outerShape.getRadius();
float innerRadius = m_innerShape.getRadius();
m_outerShape.setPosition(pos - sf::Vector2f(outerRadius, outerRadius));
m_innerShape.setPosition(pos - sf::Vector2f(innerRadius, innerRadius));
}
sf::Vector2f Selection::getPosition()
{
float radius = m_outerShape.getRadius();
return m_outerShape.getPosition() + sf::Vector2f(radius, radius) / 2.f;
}
bool Selection::isHovering(const sf::RenderWindow& window, sf::Vector2f displacement)
{
auto pixelPos = sf::Mouse::getPosition(window);
auto worldPos = window.mapPixelToCoords(pixelPos) + displacement;
return m_outerShape.getGlobalBounds().contains(worldPos.x, worldPos.y);
}
void Selection::setSelected(bool _selected)
{
m_selected = _selected;
}
bool Selection::getSelected()
{
return m_selected;
}
const bool* Selection::getPointerToSelected()
{
return &m_selected;
}
| 22.736111
| 100
| 0.744655
|
szebest
|
cf984f3074382b3d9970476ba611f764046adf3a
| 8,296
|
cpp
|
C++
|
Source/Motor2D/j1Player.cpp
|
Needlesslord/PaintWars_by_BrainDeadStudios
|
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
|
[
"MIT"
] | 2
|
2020-03-06T11:32:40.000Z
|
2020-03-20T12:17:30.000Z
|
Source/Motor2D/j1Player.cpp
|
Needlesslord/Heathen_Games
|
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
|
[
"MIT"
] | 2
|
2020-03-03T09:56:57.000Z
|
2020-05-02T15:50:45.000Z
|
Source/Motor2D/j1Player.cpp
|
Needlesslord/Heathen_Games
|
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
|
[
"MIT"
] | 1
|
2020-03-17T18:50:53.000Z
|
2020-03-17T18:50:53.000Z
|
#include "p2Defs.h"
#include "j1App.h"
#include "p2Log.h"
#include "j1Textures.h"
#include "j1Input.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Player.h"
#include "j1SceneManager.h"
#include "j1EntityManager.h"
#include "j1Window.h"
#include "j1UI_manager.h"
#include "Scene.h"
#include "j1Timer.h"
j1Player::j1Player() : j1Module()
{
name = ("player");
}
j1Player::~j1Player()
{
App->CleanUp();
}
bool j1Player::Awake(pugi::xml_node& config)
{
bool ret = true;
folder = (config.child("folder").child_value());
camera_speed = config.child("camera").attribute("speed").as_int(1);
camera_offset = config.child("camera").attribute("offset").as_int(10);
node = config;
return ret;
}
bool j1Player::Start() {
bool ret = true;
MinimapCameraBufferX = 0;
MinimapCameraBufferY = 0;
LOG("Player Started");
Tex_Player = App->tex->Load("textures/UI/UI_mouse.png");
App->win->GetWindowSize( win_width,win_height);
SDL_ShowCursor(SDL_DISABLE);
V = 0;
return ret;
}
bool j1Player::PreUpdate()
{
//list<Entity*>::iterator entityCount = App->entities->activeEntities.begin();
//int B = 0;
//int P = 0;
//if (V != 1) {
// while (entityCount != App->entities->activeEntities.end()) {
// MiniMapEntities_Squares[B] = App->gui->AddElement(TypeOfUI::GUI_IMAGE, nullptr, { 1000,520 /*(*entityCount)->pos.x ,(*entityCount)->pos.y*/ }, { 0 , 0 }, false, true, { 4, 3, 2, 3 },
// nullptr, nullptr, TEXTURE::MINIMAP_ENTITIES);
//
//
// MiniMapEntities_Squares[B]->map_position.x = MiniMapEntities_Squares[B]->init_map_position.x + App->render->camera.x + (*entityCount)->currentTile.x;
// MiniMapEntities_Squares[B]->map_position.y = MiniMapEntities_Squares[B]->init_map_position.y + App->render->camera.y + (*entityCount)->currentTile.y;
// entityCount++;
// B++;
//
// }
//
//}
//if (entityCount != App->entities->activeEntities.end()) {
// V = 1;
//}
//LOG("ENTITY POSITION X,Y = %f %f", MiniMapEntities_Squares[B]->map_position.x, MiniMapEntities_Squares[B]->map_position.x);
return true;
}
bool j1Player::Save(pugi::xml_node& data)
{
//PLAYER POSITION
LOG("Loading player state");
mouse_position.x = data.child("position").attribute("X").as_int();
mouse_position.y = data.child("position").attribute("Y").as_int();
return true;
}
bool j1Player::Load(pugi::xml_node& data)
{
//PLAYER POSITION
LOG("Loading player state");
mouse_position.x = data.child("position").attribute("X").as_int();
mouse_position.y = data.child("position").attribute("Y").as_int();
return true;
}
bool j1Player::Update(float dt)
{
int z = 0;
App->input->GetMousePosition(mouse_position.x, mouse_position.y);
Camera_Control(dt);
Zoom();
if (App->PAUSE_ACTIVE == false) {
if (App->scenes->IN_GAME_SCENE == true) {
p2List_item<j1UIElement*>* UI_List = App->gui->GUI_ELEMENTS.start;
while (UI_List != NULL)
{
if (App->gui->GUI_ELEMENTS[z]->textureType == TEXTURE::MINIMAP_CAMERA) {
App->gui->GUI_ELEMENTS[z]->map_position.x = App->gui->GUI_ELEMENTS[z]->init_map_position.x + App->render->camera.x - MinimapCameraBufferX;
App->gui->GUI_ELEMENTS[z]->map_position.y = App->gui->GUI_ELEMENTS[z]->init_map_position.y + App->render->camera.y - MinimapCameraBufferY;
}
else if (App->gui->GUI_ELEMENTS[z]->textureType == TEXTURE::MINIMAP_ENTITIES) {
}
else {
//LOG("UI COUNT IS %d", z);
App->gui->GUI_ELEMENTS[z]->map_position.x = App->gui->GUI_ELEMENTS[z]->init_map_position.x + App->render->camera.x;
App->gui->GUI_ELEMENTS[z]->map_position.y = App->gui->GUI_ELEMENTS[z]->init_map_position.y + App->render->camera.y;
/*if (App->gui->GUI_ELEMENTS[z]->textureType == TEXTURE::MINIMAP_ENTITIES) {
LOG("SQUARE POSITION X=%f, Y=%f ", App->gui->GUI_ELEMENTS[z]->map_position.x, App->gui->GUI_ELEMENTS[z]->map_position.y);
}*/
}
UI_List = UI_List->next;
++z;
}
}
}
Select_Entities(selector);
int B = 0;
list<Entity*>::iterator entityCount = App->entities->activeEntities.begin();
while (entityCount != App->entities->activeEntities.end()) {
/*MiniMapEntities_Squares[B] = App->gui->AddElement(TypeOfUI::GUI_IMAGE, nullptr, { (*entityCount)->pos.x , (*entityCount)->pos.y}, { 0 , 0 },
false, true, { 4, 3, 2, 3 }, nullptr, nullptr, TEXTURE::MINIMAP_ENTITIES);
*/
entityCount++;
B++;
}
return true;
}
bool j1Player::CleanUp()
{
return true;
}
void j1Player::Camera_Control(float dt)
{
int z = 0;
if (App->scenes->current_scene->scene_name == SCENES::GAME_SCENE)
{
if (App->PAUSE_ACTIVE==false) {
if (mouse_position.x == 0 && App->render->camera.x <= 3750)
{
//LOG("Camera x at %d", App->render->camera.x);
App->render->camera.x += camera_speed * dt * 1000;
//1242X
//695Y
MinimapCameraBufferX = MinimapCameraBufferX + 1.1;
}
if (mouse_position.y == 0)
{
//LOG("Camera y at %d", App->render->camera.y);
App->render->camera.y += camera_speed * dt * 1000;
if (App->render->camera.y < 50) {
MinimapCameraBufferY = MinimapCameraBufferY + 1.1;
}
}
if (mouse_position.x > (win_width - camera_offset) / App->win->scale )
{
//LOG("Camera x at %d", App->render->camera.x);
App->render->camera.x -= camera_speed * dt * 1000;
if (App->render->camera.x > -2900) {
MinimapCameraBufferX = MinimapCameraBufferX - 1.1;
}
}
if (mouse_position.y > (win_height - camera_offset) / App->win->scale)
{
//LOG("Camera y at %d", App->render->camera.y);
App->render->camera.y -= camera_speed * dt * 1000;
if (App->render->camera.y > -3150) {
MinimapCameraBufferY = MinimapCameraBufferY - 1.1;
}
}
if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT)
App->render->camera.y += camera_speed * dt * 1000;
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT)
App->render->camera.y -= camera_speed * dt * 1000;
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT)
App->render->camera.x += camera_speed * dt * 1000;
if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT)
App->render->camera.x -= camera_speed * dt * 1000;
if (App->render->camera.x < -2900)
App->render->camera.x = -2900;
if (App->render->camera.x > 3800)
App->render->camera.x = 3800;
if (App->render->camera.y > 50)
App->render->camera.y = 50;
if (App->render->camera.y < -3150)
App->render->camera.y = -3150;
if (App->input->GetKey(SDL_SCANCODE_H) == KEY_DOWN) {
//has to update camera minimap
if (App->scenes->Map_Forest_Active) {
App->render->camera.x = 575;
App->render->camera.y = -1200;
MinimapCameraBufferX = 4;
MinimapCameraBufferY = -4;
}
if (App->scenes->Map_Snow_Active) {
App->render->camera.x = -329;
App->render->camera.y = -608;
MinimapCameraBufferX = -24;
MinimapCameraBufferY = 15;
}
if (App->scenes->Map_Volcano_Active) {
App->render->camera.x = 700;
App->render->camera.y = 10;
MinimapCameraBufferX = 4.39;
MinimapCameraBufferY = 33;
}
}
}
}
Mouse_Cursor();
}
void j1Player::Select_Entities(SDL_Rect select_area)
{
int buffer;
if (select_area.x > select_area.x + select_area.w)
{
select_area.x = select_area.x + select_area.w;
select_area.w *= -1;
}
if (select_area.y > select_area.y + select_area.h)
{
select_area.y = select_area.y + select_area.h;
select_area.h *= -1;
}
//LOG("Ax -> %d | Ay -> %d | Aw -> %d | Ah -> %d", select_area.x, select_area.y, select_area.w, select_area.h);
}
void j1Player::Mouse_Cursor()
{
mouse_position.x -= App->render->camera.x / App->win->GetScale();
mouse_position.y -= App->render->camera.y / App->win->GetScale();
App->render->RenderQueueUI(10,Tex_Player, mouse_position.x, mouse_position.y, texture_rect);
}
void j1Player::Zoom()
{
if (App->input->GetKey(SDL_SCANCODE_9) == KEY_REPEAT) //zoom IN
{
App->win->scale = App->win->scale + 0.001;
}
else if (App->input->GetKey(SDL_SCANCODE_0) == KEY_REPEAT)//zoom OUT
{
App->win->scale = App->win->scale - 0.001;
}
else if (App->input->GetKey(SDL_SCANCODE_R) == KEY_DOWN)//zoom RESET
{
App->win->scale = 0.5;
}
}
| 22.241287
| 187
| 0.639344
|
Needlesslord
|
cf98dfda2cfd8ff4aba8b083cefe8ea8af931e8d
| 2,846
|
hpp
|
C++
|
third-party/casadi/casadi/core/global_options.hpp
|
dbdxnuliba/mit-biomimetics_Cheetah
|
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
|
[
"MIT"
] | 8
|
2020-02-18T09:07:48.000Z
|
2021-12-25T05:40:02.000Z
|
flip-optimization-master/casadi/include/casadi/core/global_options.hpp
|
WatsonZhouAnda/Cheetah-Software
|
05e416fb26f968300826f0deb0953be9afb22bfe
|
[
"MIT"
] | null | null | null |
flip-optimization-master/casadi/include/casadi/core/global_options.hpp
|
WatsonZhouAnda/Cheetah-Software
|
05e416fb26f968300826f0deb0953be9afb22bfe
|
[
"MIT"
] | 13
|
2019-08-25T12:32:06.000Z
|
2022-03-31T02:38:12.000Z
|
/*
* This file is part of CasADi.
*
* CasADi -- A symbolic framework for dynamic optimization.
* Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
* K.U. Leuven. All rights reserved.
* Copyright (C) 2011-2014 Greg Horn
*
* CasADi is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* CasADi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with CasADi; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef CASADI_GLOBAL_OPTIONS_HPP
#define CASADI_GLOBAL_OPTIONS_HPP
#include <iostream>
#include <fstream>
#include <casadi/core/casadi_export.h>
#include "casadi/core/casadi_common.hpp"
namespace casadi {
/**
* \brief Collects global CasADi options
*
*
* Note to developers: \n
* - use sparingly. Global options are - in general - a rather bad idea \n
* - this class must never be instantiated. Access its static members directly \n
*
* \author Joris Gillis
* \date 2012
*/
class CASADI_EXPORT GlobalOptions {
private:
/// No instances are allowed
GlobalOptions();
public:
#ifndef SWIG
/** \brief Indicates whether simplifications should be made on the fly.
* e.g. cos(-x) -> cos(x)
* Default: true
*/
static bool simplification_on_the_fly;
static std::string casadipath;
static bool hierarchical_sparsity;
static casadi_int max_num_dir;
static casadi_int start_index;
#endif //SWIG
// Setter and getter for simplification_on_the_fly
static void setSimplificationOnTheFly(bool flag) { simplification_on_the_fly = flag; }
static bool getSimplificationOnTheFly() { return simplification_on_the_fly; }
// Setter and getter for hierarchical_sparsity
static void setHierarchicalSparsity(bool flag) { hierarchical_sparsity = flag; }
static bool getHierarchicalSparsity() { return hierarchical_sparsity; }
static void setCasadiPath(const std::string & path) { casadipath = path; }
static std::string getCasadiPath() { return casadipath; }
static void setMaxNumDir(casadi_int ndir) { max_num_dir=ndir; }
static casadi_int getMaxNumDir() { return max_num_dir; }
};
} // namespace casadi
#endif // CASADI_GLOBAL_OPTIONS_HPP
| 31.977528
| 92
| 0.696416
|
dbdxnuliba
|
cf9d37798720db9786c9cc62bd9736ada53f15da
| 3,671
|
cpp
|
C++
|
modules/tracktion_engine/plugins/internal/tracktion_VCA.cpp
|
jbloit/tracktion_engine
|
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
|
[
"MIT",
"Unlicense"
] | null | null | null |
modules/tracktion_engine/plugins/internal/tracktion_VCA.cpp
|
jbloit/tracktion_engine
|
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
|
[
"MIT",
"Unlicense"
] | null | null | null |
modules/tracktion_engine/plugins/internal/tracktion_VCA.cpp
|
jbloit/tracktion_engine
|
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
|
[
"MIT",
"Unlicense"
] | null | null | null |
/*
,--. ,--. ,--. ,--.
,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018
'-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software
| | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation
`---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com
Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details.
*/
namespace tracktion_engine
{
class VcaAutomatableParameter : public AutomatableParameter
{
public:
VcaAutomatableParameter (const juce::String& xmlTag, const juce::String& name,
Plugin& owner, juce::Range<float> valueRangeToUse)
: AutomatableParameter (xmlTag, name, owner, valueRangeToUse)
{
}
~VcaAutomatableParameter() override
{
notifyListenersOfDeletion();
}
juce::String valueToString (float value) override
{
return juce::Decibels::toString (volumeFaderPositionToDB (value) + 0.001);
}
float stringToValue (const juce::String& str) override
{
return decibelsToVolumeFaderPosition (dbStringToDb (str));
}
};
//==============================================================================
VCAPlugin::VCAPlugin (PluginCreationInfo info) : Plugin (info)
{
addAutomatableParameter (volParam = new VcaAutomatableParameter ("vca", TRANS("VCA"), *this, { 0.0f, 1.0f }));
volumeValue.referTo (state, IDs::volume, getUndoManager(), decibelsToVolumeFaderPosition (0.0f));
volParam->attachToCurrentValue (volumeValue);
}
VCAPlugin::~VCAPlugin()
{
notifyListenersOfDeletion();
volParam->detachFromCurrentValue();
}
juce::ValueTree VCAPlugin::create()
{
juce::ValueTree v (IDs::PLUGIN);
v.setProperty (IDs::type, xmlTypeName, nullptr);
return v;
}
const char* VCAPlugin::xmlTypeName = "vca";
void VCAPlugin::initialise (const PluginInitialisationInfo&) {}
void VCAPlugin::deinitialise() {}
void VCAPlugin::applyToBuffer (const PluginRenderContext&) {}
float VCAPlugin::getSliderPos() const
{
return volParam->getCurrentValue();
}
void VCAPlugin::setVolumeDb (float dB)
{
setSliderPos (decibelsToVolumeFaderPosition (dB));
}
float VCAPlugin::getVolumeDb() const
{
return volumeFaderPositionToDB (volParam->getCurrentValue());
}
void VCAPlugin::setSliderPos (float newV)
{
volParam->setParameter (juce::jlimit (0.0f, 1.0f, newV), juce::sendNotification);
}
void VCAPlugin::muteOrUnmute()
{
if (getVolumeDb() > -90.0f)
{
lastVolumeBeforeMute = getVolumeDb();
setVolumeDb (lastVolumeBeforeMute - 0.01f); // needed so that automation is recorded correctly
setVolumeDb (-100.0f);
}
else
{
if (lastVolumeBeforeMute < -100.0f)
lastVolumeBeforeMute = 0.0f;
setVolumeDb (getVolumeDb() + 0.01f); // needed so that automation is recorded correctly
setVolumeDb (lastVolumeBeforeMute);
}
}
float VCAPlugin::updateAutomationStreamAndGetVolumeDb (double time)
{
if (isAutomationNeeded())
{
updateParameterStreams (time);
updateLastPlaybackTime();
}
return getVolumeDb();
}
bool VCAPlugin::canBeMoved()
{
if (auto ft = dynamic_cast<FolderTrack*> (getOwnerTrack()))
return ft->isSubmixFolder();
return false;
}
void VCAPlugin::restorePluginStateFromValueTree (const juce::ValueTree& v)
{
juce::CachedValue<float>* cvsFloat[] = { &volumeValue, nullptr };
copyPropertiesToNullTerminatedCachedValues (v, cvsFloat);
for (auto p : getAutomatableParameters())
p->updateFromAttachedValue();
}
}
| 27.192593
| 114
| 0.616998
|
jbloit
|
cf9e02d74d153181e3e897ebe551f78dd73fe3ea
| 2,278
|
cpp
|
C++
|
FirstSemester(CS Project)/Plane.cpp
|
garretfox/C
|
9c6baeffc26e1131b873c1d7aaa99b0145635526
|
[
"MIT"
] | null | null | null |
FirstSemester(CS Project)/Plane.cpp
|
garretfox/C
|
9c6baeffc26e1131b873c1d7aaa99b0145635526
|
[
"MIT"
] | null | null | null |
FirstSemester(CS Project)/Plane.cpp
|
garretfox/C
|
9c6baeffc26e1131b873c1d7aaa99b0145635526
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Plane.h"
#include <iostream>
using namespace std;
Plane::Plane() {
isSet = 0;
}
Plane::Plane(char *c)
{
PlaneName = c;
NumberOfParties = 0;
for (int i = 0; i < 40; i++) {
PartyArray[i].SetPartyName("NULL");
PartyArray[i].SetPartySize(0);
};
isSet = 0;
}
void Plane::SetPartyAt(int i, char* c, int j)
{
GetPartyArrayAt(i).SetPartyName(c);
GetPartyArrayAt(i).SetPartySize(j);
}
bool Plane::NameNull(int i) {
if (PartyArray[i].GetPartyName() == "NULL")
return 1;
else
return 0;
}
bool Plane::IsSet() {
return isSet;
}
void Plane::AddSeats(int i)
{
int j = NumberOfSeats + i;
NumberOfSeats = j;
}
void Plane::SubtractSeats(int i)
{
int j = NumberOfSeats - i;
NumberOfSeats = j;
}
void Plane::SetSeatNumber() {
bool valid = 0;
int i;
cout << "Enter " << PlaneName << "'s Seating Capacity" << endl;
cin >> i;
do {
if (i > 40 || i < 0) {
cout << " Invalid Number" << endl;
}
else {
valid = 1;
NumberOfSeats = i;
OriginalNumberOfSeats = i;
}
} while (!valid);
}
void Plane::IncrementNumberOfParties() {
NumberOfParties++;
}
void Plane::DecrementNumberOfParties() {
NumberOfParties--;
}
int Plane::GetNumberOfAvailableSeats() {
return NumberOfSeats;
}
void Plane::DisplayOnboardParties()
{
cout << "PARTY NAMES" << endl;
for (int i = 0; i < NumberOfParties; i++)
{
if (GetPartyArrayAt(i).GetPartyName() != "NULL") {
cout << "______________________ PARTY " << i << "_________________________" << endl;
cout << *(GetPartyArrayAt(i).GetPartyName()) << endl;
cout << "And Has " << GetPartyArrayAt(i).GetPartySize() << " People." << endl;
cout << "_________________________________________________________________" << endl;
}
else;
}
}
Party Plane::GetPartyArrayAt(int i) {
return PartyArray[i];
}
Party * Plane::GetPartyArray() {
return PartyArray;
}
void Plane::Reset() {
cout << "Passengers Departing on " << PlaneName << ":" << endl;
cout << "__+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+___" << endl;
DisplayOnboardParties();
for (int i = 0; i < 40; i++) {
PartyArray[i].SetPartyName("NULL");
PartyArray[i].SetPartySize(0);
};
NumberOfParties = 0;
NumberOfSeats = OriginalNumberOfSeats;
}
int Plane::GetNumberofParties() {
return NumberOfParties;
}
| 18.672131
| 87
| 0.644425
|
garretfox
|
cf9fad672f46c29a27693a166044d7a5eb688cdf
| 6,161
|
cc
|
C++
|
protocol/zigbee/app/framework/scenarios/z3/Z3SwitchWithVoice/keyword_detection.cc
|
PascalGuenther/gecko_sdk
|
2e82050dc8823c9fe0e8908c1b2666fb83056230
|
[
"Zlib"
] | 82
|
2016-06-29T17:24:43.000Z
|
2021-04-16T06:49:17.000Z
|
protocol/zigbee/app/framework/scenarios/z3/Z3SwitchWithVoice/keyword_detection.cc
|
PascalGuenther/gecko_sdk
|
2e82050dc8823c9fe0e8908c1b2666fb83056230
|
[
"Zlib"
] | 6
|
2022-01-12T18:22:08.000Z
|
2022-03-25T10:19:27.000Z
|
protocol/zigbee/app/framework/scenarios/z3/Z3SwitchWithVoice/keyword_detection.cc
|
PascalGuenther/gecko_sdk
|
2e82050dc8823c9fe0e8908c1b2666fb83056230
|
[
"Zlib"
] | 56
|
2016-08-02T10:50:50.000Z
|
2021-07-19T08:57:34.000Z
|
/***************************************************************************//**
* @file keywork_detection.cc
* @brief Top level application functions
*******************************************************************************
* # License
* <b>Copyright 2021 Silicon Laboratories Inc. www.silabs.com</b>
*******************************************************************************
*
* The licensor of this software is Silicon Laboratories Inc. Your use of this
* software is governed by the terms of Silicon Labs Master Software License
* Agreement (MSLA) available at
* www.silabs.com/about-us/legal/master-software-license-agreement. This
* software is distributed to you in Source Code format and is governed by the
* sections of the MSLA applicable to Source Code.
*
******************************************************************************/
#include "sl_status.h"
#include "sl_sleeptimer.h"
#include "sl_component_catalog.h"
#if defined(SL_CATALOG_POWER_MANAGER_PRESENT)
#include "sl_power_manager.h"
#endif
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "keyword_detection.h"
#include "recognize_commands.h"
#include "recognize_commands_config.h"
#include "sl_tflite_micro_model.h"
#include "sl_tflite_micro_init.h"
#include "sl_ml_audio_feature_generation.h"
/*******************************************************************************
******************************* DEFINES ***********************************
******************************************************************************/
#ifndef INFERENCE_INTERVAL_MS
#define INFERENCE_INTERVAL_MS 200
#endif
/*******************************************************************************
*************************** LOCAL VARIABLES ********************************
******************************************************************************/
// Instance Pointers
static RecognizeCommands *command_recognizer = nullptr;
static volatile bool inference_timeout;
static sl_sleeptimer_timer_handle_t inference_timer;
/***************************************************************************//**
* Run model inference
*
* Copies the currently available data from the feature_buffer into the input
* tensor and runs inference, updating the global output_tensor.
******************************************************************************/
static sl_status_t run_inference()
{
// Update model input tensor
sl_status_t status = sl_ml_audio_feature_generation_fill_tensor(sl_tflite_micro_get_input_tensor());
if (status != SL_STATUS_OK) {
return SL_STATUS_FAIL;
}
// Run the model on the spectrogram input and make sure it succeeds.
TfLiteStatus invoke_status = sl_tflite_micro_get_interpreter()->Invoke();
if (invoke_status != kTfLiteOk) {
return SL_STATUS_FAIL;
}
return SL_STATUS_OK;
}
/***************************************************************************//**
* Processes the output from output_tensor
******************************************************************************/
sl_status_t process_output()
{
// Determine whether a command was recognized based on the output of inference
uint8_t found_command_index = 0;
uint8_t score = 0;
bool is_new_command = false;
uint32_t current_time_stamp;
// Get current time stamp needed by CommandRecognizer
current_time_stamp = sl_sleeptimer_tick_to_ms(sl_sleeptimer_get_tick_count());
TfLiteStatus process_status = command_recognizer->ProcessLatestResults(
sl_tflite_micro_get_output_tensor(), current_time_stamp, &found_command_index, &score, &is_new_command);
if (process_status != kTfLiteOk) {
return SL_STATUS_FAIL;
}
if (is_new_command) {
if (found_command_index == 0 || found_command_index == 1) {
printf("Heard %s (%d) @%ldms\r\n", kCategoryLabels[found_command_index],
score, current_time_stamp);
keyword_detected(found_command_index);
}
}
return SL_STATUS_OK;
}
/***************************************************************************//**
* Inference timer callback
******************************************************************************/
static void inference_timer_callback(sl_sleeptimer_timer_handle_t *handle, void* data)
{
(void)handle;
(void)data;
inference_timeout = true;
}
/*******************************************************************************
************************** GLOBAL FUNCTIONS *******************************
******************************************************************************/
/***************************************************************************//**
* Initialize application.
******************************************************************************/
void keyword_detection_init(void)
{
#if defined(SL_CATALOG_POWER_MANAGER_PRESENT)
// Add EM1 requirement to allow for continous microphone sampling
sl_power_manager_add_em_requirement(SL_POWER_MANAGER_EM1);
#endif
// Initialize audio feature generation
sl_ml_audio_feature_generation_init();
// Instantiate CommandRecognizer
static RecognizeCommands static_recognizer(sl_tflite_micro_get_error_reporter(), SMOOTHING_WINDOW_DURATION_MS,
DETECTION_THRESHOLD, SUPPRESION_TIME_MS, MINIMUM_DETECTION_COUNT);
command_recognizer = &static_recognizer;
// Start periodic timer for inference interval
sl_sleeptimer_start_periodic_timer_ms(&inference_timer, INFERENCE_INTERVAL_MS, inference_timer_callback, NULL, 0, 0);
}
/***************************************************************************//**
* Keyword detection process action
******************************************************************************/
void keyword_detection_process_action(void)
{
// Perform keyword detection every INFERENCE_INTERVAL_MS ms
if (inference_timeout == true) {
sl_ml_audio_feature_generation_update_features();
run_inference();
process_output();
inference_timeout = false;
}
}
| 39.748387
| 119
| 0.549586
|
PascalGuenther
|
cfa01b83595624a414618fe97995471a1d0b71be
| 583
|
cpp
|
C++
|
AppCUI/src/Controls/UserControl.cpp
|
rzaharia/AppCUI
|
9aa37b154e04d0aa3e69a75798a698f591b0c8ca
|
[
"MIT"
] | null | null | null |
AppCUI/src/Controls/UserControl.cpp
|
rzaharia/AppCUI
|
9aa37b154e04d0aa3e69a75798a698f591b0c8ca
|
[
"MIT"
] | null | null | null |
AppCUI/src/Controls/UserControl.cpp
|
rzaharia/AppCUI
|
9aa37b154e04d0aa3e69a75798a698f591b0c8ca
|
[
"MIT"
] | null | null | null |
#include "ControlContext.hpp"
using namespace AppCUI::Controls;
bool UserControl::Create(Control* parent, const AppCUI::Utils::ConstString& caption, const std::string_view& layout)
{
CONTROL_INIT_CONTEXT(ControlContext);
CHECK(Init(parent, caption, layout, false), false, "Failed to create user control !");
CREATE_CONTROL_CONTEXT(this, Members, false);
Members->Flags = GATTR_VISIBLE | GATTR_ENABLE | GATTR_TABSTOP;
return true;
}
bool UserControl::Create(Control* parent, const std::string_view& layout)
{
return UserControl::Create(parent, "", layout);
}
| 36.4375
| 116
| 0.744425
|
rzaharia
|
cfa15397b6c7d61a6ac8537e4b9c2cdecbd4826b
| 1,360
|
hh
|
C++
|
src/ETransform.hh
|
jjzhang166/CxxLog4j
|
3c674f8a7f57deee228c5de6869c9f5852596930
|
[
"Apache-2.0"
] | 5
|
2016-08-25T14:26:45.000Z
|
2018-11-07T08:30:38.000Z
|
src/ETransform.hh
|
jjzhang166/CxxLog4j
|
3c674f8a7f57deee228c5de6869c9f5852596930
|
[
"Apache-2.0"
] | 1
|
2018-07-06T02:37:10.000Z
|
2018-07-11T05:47:47.000Z
|
src/ETransform.hh
|
jjzhang166/CxxLog4j
|
3c674f8a7f57deee228c5de6869c9f5852596930
|
[
"Apache-2.0"
] | 4
|
2017-06-09T01:22:43.000Z
|
2019-02-19T07:19:59.000Z
|
/*
* ETransform.hh
*
* Created on: 2015-8-11
* Author: cxxjava@163.com
*/
#ifndef ETRANSFORM_HH_
#define ETRANSFORM_HH_
#include "Efc.hh"
#include "../inc/ELogger.hh"
namespace efc {
namespace log {
/**
* Utility class for transforming strings.
*/
class ETransform {
public:
/**
* This method takes a string which may contain HTML tags (ie,
* <b>, <table>, etc) and replaces any
* '<', '>' , '&' or '"'
* characters with respective predefined entity references.
*
* @param buf StringBuffer holding the escaped data to this point.
* @param input The text to be converted.
* */
static void appendEscapingTags(EString& buf, const char* input);
/**
* Ensures that embeded CDEnd strings (]]>) are handled properly
* within message, NDC and throwable tag text.
*
* @param buf StringBuffer holding the XML data to this point. The
* initial CDStart (<![CDATA[) and final CDEnd (]]>) of the CDATA
* section are the responsibility of the calling method.
* @param input The String that is inserted into an existing CDATA Section within buf.
* */
static void appendEscapingCDATA(EString& buf, const char* input);
/**
* convert logger level from integer to string
*/
static const char* toLevelStr(ELogger::Level level);
};
} /* namespace log */
} /* namespace efc */
#endif /* ETRANSFORM_HH_ */
| 24.727273
| 87
| 0.680147
|
jjzhang166
|
cfa1a15555f29bc71b3ec1198ffc2ffa006c53f3
| 254
|
cpp
|
C++
|
abc/ABC161/cpp/a.cpp
|
yokotani92/atcoder
|
febaef2d13c40093a2a284c87a949cd46113801d
|
[
"MIT"
] | null | null | null |
abc/ABC161/cpp/a.cpp
|
yokotani92/atcoder
|
febaef2d13c40093a2a284c87a949cd46113801d
|
[
"MIT"
] | null | null | null |
abc/ABC161/cpp/a.cpp
|
yokotani92/atcoder
|
febaef2d13c40093a2a284c87a949cd46113801d
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <vector>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;
typedef long long ll;
const int MOD = 1E9 + 9;
const int INF = 1 << 29;
int main() {
int A;
cin >> A;
cout << A;
}
| 18.142857
| 52
| 0.598425
|
yokotani92
|
cfa44f9a16a58ec7ed3b6ee8a2744e12ce2704d7
| 1,985
|
cpp
|
C++
|
CSL/CSL-r/src/wmark/scanner_actions/tk_action.cpp
|
ZJU-ZSJ/CppTSL
|
6ce7673d5f7f8de8769c6377090b845492e63aa9
|
[
"BSD-2-Clause"
] | null | null | null |
CSL/CSL-r/src/wmark/scanner_actions/tk_action.cpp
|
ZJU-ZSJ/CppTSL
|
6ce7673d5f7f8de8769c6377090b845492e63aa9
|
[
"BSD-2-Clause"
] | null | null | null |
CSL/CSL-r/src/wmark/scanner_actions/tk_action.cpp
|
ZJU-ZSJ/CppTSL
|
6ce7673d5f7f8de8769c6377090b845492e63aa9
|
[
"BSD-2-Clause"
] | null | null | null |
/*
** Xin YUAN, 2019, BSD (2)
*/
////////////////////////////////////////////////////////////////////////////////
#include "precomp.h"
#include "../WmarkScanner.h"
#include "../base/WmarkDef.h"
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
namespace CSL {
////////////////////////////////////////////////////////////////////////////////
// TkAction
RdScannerAction WmarkScannerHelper::get_TkAction()
{
return [](std::istream& stm, RdActionStack& stk, RdToken& token)->bool
{
//get a character
char ch;
stm.get(ch);
if( stm.eof() ) {
token.uID = TK_END_OF_EVENT;
return true;
}
if( !stm.good() )
return false;
token.strToken += ch;
//return
if( ch == '\n' ) {
token.uID = WMARK_TK_RETURN;
token.infoEnd.uRow ++;
token.infoEnd.uCol = 0;
return true;
}
if( ch == '\r' ) {
stm.get(ch);
if( stm.eof() ) {
token.uID = WMARK_TK_RETURN;
token.infoEnd.uRow ++;
token.infoEnd.uCol = 0;
return true;
}
if( !stm.good() )
return false;
token.infoEnd.uRow ++;
token.infoEnd.uCol = 0;
if( ch == '\n' ) {
token.strToken += ch;
token.uID = WMARK_TK_RETURN;
return true;
}
stm.unget();
token.uID = WMARK_TK_RETURN;
return true;
}
token.infoEnd.uCol ++;
//indent
if( ch == '\t' ) {
token.uID = WMARK_TK_INDENT;
return true;
}
//<
if( ch == '<' ) {
stk.push(WMARK_SCANNER_COMMENT_ACTION);
return true;
}
//others
stk.push(WMARK_SCANNER_TEXT_ACTION);
return true;
};
}
////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////
| 22.303371
| 81
| 0.38136
|
ZJU-ZSJ
|
cfa5723015d33450fb4eb00278ee8b7638607106
| 1,079
|
cpp
|
C++
|
C++/Data_Structures/Path_Sum_II.cpp
|
IUC4801/HactoberFest21
|
ad52dee669deba54630584435b77a6ab07dc67b2
|
[
"Unlicense"
] | 1
|
2021-10-03T08:02:58.000Z
|
2021-10-03T08:02:58.000Z
|
C++/Data_Structures/Path_Sum_II.cpp
|
IUC4801/HactoberFest21
|
ad52dee669deba54630584435b77a6ab07dc67b2
|
[
"Unlicense"
] | 1
|
2021-10-06T04:41:55.000Z
|
2021-10-06T04:41:55.000Z
|
C++/Data_Structures/Path_Sum_II.cpp
|
IUC4801/HactoberFest21
|
ad52dee669deba54630584435b77a6ab07dc67b2
|
[
"Unlicense"
] | 1
|
2021-10-08T12:31:04.000Z
|
2021-10-08T12:31:04.000Z
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> ans;
void solve(TreeNode* root,int sum,vector<int> &res){
if(!root) {
return;
}
if(root->left==NULL&&root->right==NULL&&sum==root->val){
res.push_back(root->val);
ans.push_back(res);
res.pop_back();
}
else {
res.push_back(root->val);
solve(root->left,sum-root->val,res);
solve(root->right,sum-root->val,res);
res.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<int> res;
solve(root,targetSum,res);
return ans;
}
};
| 27.666667
| 93
| 0.510658
|
IUC4801
|
cfa6269395b8e032be571d81ad55df8fe1d840f4
| 1,902
|
cpp
|
C++
|
test/algorithm/test_scalar_product.cpp
|
jan-moeller/lina
|
9acaac27d7efb3e8b3c4d1ae2ad9425e79f233c8
|
[
"MIT"
] | null | null | null |
test/algorithm/test_scalar_product.cpp
|
jan-moeller/lina
|
9acaac27d7efb3e8b3c4d1ae2ad9425e79f233c8
|
[
"MIT"
] | null | null | null |
test/algorithm/test_scalar_product.cpp
|
jan-moeller/lina
|
9acaac27d7efb3e8b3c4d1ae2ad9425e79f233c8
|
[
"MIT"
] | null | null | null |
//
// MIT License
//
// Copyright (c) 2021 Jan Möller
//
// 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 "lina/lina.hpp"
#include <catch2/catch.hpp>
using namespace lina;
TEST_CASE("scalar_product", "[algorithm]")
{
constexpr basic_matrix<double, {3, 2}> m{1, 2, 3, 4, 5, 6};
constexpr basic_matrix<double, {3, 2}> expected{3, 6, 9, 12, 15, 18};
constexpr float scalar = 3;
SECTION("copy")
{
auto const result1 = scalar_product(scalar, m);
auto const result2 = scalar_product(m, scalar);
CHECK(result1 == expected);
CHECK(result1 == result2);
}
SECTION("in place")
{
auto m1 = m;
auto m2 = m;
scalar_product(std::in_place, scalar, m1);
scalar_product(std::in_place, m2, scalar);
CHECK(m1 == expected);
CHECK(m1 == m2);
}
}
| 35.886792
| 81
| 0.679811
|
jan-moeller
|
cfa71a4d6fc15a687b05d19ccf96c7684a70116f
| 2,593
|
cpp
|
C++
|
src/database/core/SoXipMprActiveElement.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 2
|
2020-05-21T07:06:07.000Z
|
2021-06-28T02:14:34.000Z
|
src/database/core/SoXipMprActiveElement.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | null | null | null |
src/database/core/SoXipMprActiveElement.cpp
|
OpenXIP/xip-libraries
|
9f0fef66038b20ff0c81c089d7dd0038e3126e40
|
[
"Apache-2.0"
] | 6
|
2016-03-21T19:53:18.000Z
|
2021-06-08T18:06:03.000Z
|
/*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <xip/inventor/core/SoXipMprActiveElement.h>
SO_ELEMENT_SOURCE(SoXipMprActiveElement);
////////////////////////////////////////////////////////////////////////
SoXipMprActiveElement::~SoXipMprActiveElement()
{
}
void
SoXipMprActiveElement::initClass()
{
SO_ELEMENT_INIT_CLASS(SoXipMprActiveElement, SoReplacedElement);
}
void
SoXipMprActiveElement::init(SoState *)
{
mprId = 0;
mprIdField = 0;
}
void
SoXipMprActiveElement::set(SoState *state, SoNode *node, const int32_t index, SoSFInt32* indexField)
{
SoXipMprActiveElement *elt;
// get an instance we can change (pushing if necessary)
elt = (SoXipMprActiveElement *) getElement(state, classStackIndex, node);
if ( (elt != NULL) )
{
elt->mprId = index;
elt->mprIdField = indexField;
}
}
SoSFInt32*
SoXipMprActiveElement::getMprFieldIndex(SoState *state)
{
const SoXipMprActiveElement *elt;
elt = (const SoXipMprActiveElement *)getConstElement(state, classStackIndex);
if ( (elt != NULL) )
return elt->mprIdField;
else
return NULL;
}
const int32_t
SoXipMprActiveElement::getMprIndex(SoState *state)
{
const SoXipMprActiveElement *elt;
elt = (const SoXipMprActiveElement *)getConstElement(state, classStackIndex);
if ( (elt != NULL) )
return elt->mprId;
else
return 0;
}
//
// Overrides this method to compare attenuation values.
//
SbBool
SoXipMprActiveElement::matches(const SoElement *elt) const
{
SbBool match = FALSE;
if ( (mprIdField == ((const SoXipMprActiveElement *) elt)->mprIdField)
&& (mprId == ((const SoXipMprActiveElement *) elt)->mprId) )
match = TRUE;
return match;
}
//
// Create a copy of this instance suitable for calling matches()
//
SoElement *
SoXipMprActiveElement::copyMatchInfo() const
{
SoXipMprActiveElement *result = (SoXipMprActiveElement *)getTypeId().createInstance();
if(result)
{
result->mprId = mprId;
return result;
}
else
return NULL;
}
| 21.429752
| 100
| 0.712302
|
OpenXIP
|
cfa7ce00d119a08def66b1f055401db4c1bf0e76
| 19,869
|
cc
|
C++
|
chrome/browser/ui/views/tabs/overflow_view_unittest.cc
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
chrome/browser/ui/views/tabs/overflow_view_unittest.cc
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86
|
2015-10-21T13:02:42.000Z
|
2022-03-14T07:50:50.000Z
|
chrome/browser/ui/views/tabs/overflow_view_unittest.cc
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tabs/overflow_view.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/flex_layout_types.h"
#include "ui/views/layout/layout_types.h"
#include "ui/views/test/test_views.h"
#include "ui/views/view_class_properties.h"
class OverflowViewTest : public testing::Test {
public:
OverflowViewTest() = default;
~OverflowViewTest() override = default;
void SetUp() override {
parent_view_ = std::make_unique<views::View>();
parent_view_->SetLayoutManager(std::make_unique<views::FillLayout>());
parent_view_->SetSize(kDefaultParentSize);
}
void TearDown() override {
parent_view_.reset();
overflow_view_ = nullptr;
}
void Init(const gfx::Size& primary_minimum_size,
const gfx::Size& primary_preferred_size,
const gfx::Size& indicator_minimum_size,
const gfx::Size& indicator_preferred_size) {
auto primary_view =
std::make_unique<views::StaticSizedView>(primary_preferred_size);
primary_view->set_minimum_size(primary_minimum_size);
primary_view_ = primary_view.get();
auto indicator_view =
std::make_unique<views::StaticSizedView>(indicator_preferred_size);
indicator_view->set_minimum_size(indicator_minimum_size);
indicator_view_ = indicator_view.get();
overflow_view_ = parent_view_->AddChildView(std::make_unique<OverflowView>(
std::move(primary_view), std::move(indicator_view)));
}
protected:
static int InterpolateByTens(int minimum,
int preferred,
views::SizeBound bound) {
if (!bound.is_bounded())
return preferred;
if (bound.value() <= minimum)
return minimum;
if (bound.value() >= preferred)
return preferred;
return minimum + 10 * ((bound.value() - minimum) / 10);
}
// Flex rule where height and width step by 10s up from minimum to preferred
// size.
static gfx::Size StepwiseFlexRule(const views::View* view,
const views::SizeBounds& bounds) {
const gfx::Size preferred = view->GetPreferredSize();
const gfx::Size minimum = view->GetMinimumSize();
return gfx::Size(
InterpolateByTens(minimum.width(), preferred.width(), bounds.width()),
InterpolateByTens(minimum.height(), preferred.height(),
bounds.height()));
}
// Flex rule where the vertical axis contracts from preferred to minimum size
// by the same percentage as the horizontal axis is shrunk between preferred
// and minimum size. So for instance, if the horizontal axis is constrained
// by 20 DIPs and the difference between minimum and preferred is 80 DIPs,
// then the vertical axis will be 75% of the way between minimum and preferred
// size.
static gfx::Size ProportionalFlexRule(const views::View* view,
const views::SizeBounds& bounds) {
const gfx::Size preferred = view->GetPreferredSize();
const gfx::Size minimum = view->GetMinimumSize();
const int width =
std::max(minimum.width(), bounds.width().min_of(preferred.width()));
DCHECK_GT(preferred.width(), minimum.width());
double ratio = static_cast<double>(width - minimum.width()) /
(preferred.width() - minimum.width());
const int height = bounds.height().min_of(
minimum.height() +
base::ClampRound(ratio * (preferred.height() - minimum.height())));
return gfx::Size(width, height);
}
static constexpr gfx::Size kDefaultParentSize{100, 70};
static constexpr gfx::Size kPreferredSize{120, 80};
static constexpr gfx::Size kMinimumSize{40, 20};
static constexpr gfx::Size kPreferredSize2{55, 50};
static constexpr gfx::Size kMinimumSize2{25, 30};
std::unique_ptr<views::View> parent_view_;
raw_ptr<OverflowView> overflow_view_ = nullptr;
raw_ptr<views::StaticSizedView> primary_view_ = nullptr;
raw_ptr<views::StaticSizedView> indicator_view_ = nullptr;
};
constexpr gfx::Size OverflowViewTest::kDefaultParentSize;
constexpr gfx::Size OverflowViewTest::kPreferredSize;
constexpr gfx::Size OverflowViewTest::kMinimumSize;
constexpr gfx::Size OverflowViewTest::kPreferredSize2;
constexpr gfx::Size OverflowViewTest::kMinimumSize2;
TEST_F(OverflowViewTest, SizesNoFlexRules) {
Init(kMinimumSize, kPreferredSize, kMinimumSize2, kPreferredSize2);
const gfx::Size expected_min(
kMinimumSize2.width(),
std::max(kMinimumSize.height(), kMinimumSize2.height()));
EXPECT_EQ(expected_min, overflow_view_->GetMinimumSize());
EXPECT_EQ(kPreferredSize, overflow_view_->GetPreferredSize());
}
TEST_F(OverflowViewTest, SizesNoFlexRulesIndicatorIsLarger) {
Init(kMinimumSize2, kPreferredSize2, kMinimumSize, kPreferredSize);
const gfx::Size expected_min(
kMinimumSize.width(),
std::max(kMinimumSize.height(), kMinimumSize2.height()));
EXPECT_EQ(expected_min, overflow_view_->GetMinimumSize());
EXPECT_EQ(kPreferredSize, overflow_view_->GetPreferredSize());
EXPECT_EQ(kPreferredSize.height(), overflow_view_->GetHeightForWidth(200));
}
TEST_F(OverflowViewTest, SizesNoFlexRulesVertical) {
Init(kMinimumSize, kPreferredSize, kMinimumSize2, kPreferredSize2);
overflow_view_->SetOrientation(views::LayoutOrientation::kVertical);
const gfx::Size expected_min(
std::max(kMinimumSize.width(), kMinimumSize2.width()),
kMinimumSize2.height());
EXPECT_EQ(expected_min, overflow_view_->GetMinimumSize());
EXPECT_EQ(kPreferredSize, overflow_view_->GetPreferredSize());
}
TEST_F(OverflowViewTest, SizesNoFlexRulesIndicatorIsLargerVertical) {
Init(kMinimumSize2, kPreferredSize2, kMinimumSize, kPreferredSize);
overflow_view_->SetOrientation(views::LayoutOrientation::kVertical);
const gfx::Size expected_min(
std::max(kMinimumSize.width(), kMinimumSize2.width()),
kMinimumSize.height());
EXPECT_EQ(expected_min, overflow_view_->GetMinimumSize());
EXPECT_EQ(kPreferredSize, overflow_view_->GetPreferredSize());
EXPECT_EQ(kPreferredSize.height(), overflow_view_->GetHeightForWidth(200));
}
class OverflowViewLayoutTest : public OverflowViewTest {
public:
OverflowViewLayoutTest() = default;
~OverflowViewLayoutTest() override = default;
void SetUp() override {
OverflowViewTest::SetUp();
Init(kPrimaryMinimumSize, kPrimaryPreferredSize, kIndicatorMinimumSize,
kIndicatorPreferredSize);
}
void Resize(gfx::Size size) {
parent_view_->SetSize(size);
parent_view_->Layout();
}
void SizeToPreferredSize() { parent_view_->SizeToPreferredSize(); }
gfx::Rect primary_bounds() const { return primary_view_->bounds(); }
gfx::Rect indicator_bounds() const { return indicator_view_->bounds(); }
bool primary_visible() const { return primary_view_->GetVisible(); }
bool indicator_visible() const { return indicator_view_->GetVisible(); }
protected:
static constexpr gfx::Size kPrimaryMinimumSize{80, 20};
static constexpr gfx::Size kPrimaryPreferredSize{160, 30};
static constexpr gfx::Size kIndicatorMinimumSize{16, 16};
static constexpr gfx::Size kIndicatorPreferredSize{32, 32};
static gfx::Size Transpose(const gfx::Size size) {
return gfx::Size(size.height(), size.width());
}
static gfx::Size TransposingFlexRule(const views::View* view,
const views::SizeBounds& size_bounds) {
const gfx::Size preferred = Transpose(view->GetPreferredSize());
const gfx::Size minimum = Transpose(view->GetMinimumSize());
int height;
int width;
if (size_bounds.height().is_bounded()) {
height = std::max(minimum.height(),
size_bounds.height().min_of(preferred.height()));
} else {
height = preferred.height();
}
if (size_bounds.width().is_bounded()) {
width = std::max(minimum.width(),
size_bounds.width().min_of(preferred.width()));
} else {
width = preferred.width();
}
return gfx::Size(width, height);
}
};
constexpr gfx::Size OverflowViewLayoutTest::kPrimaryMinimumSize;
constexpr gfx::Size OverflowViewLayoutTest::kPrimaryPreferredSize;
constexpr gfx::Size OverflowViewLayoutTest::kIndicatorMinimumSize;
constexpr gfx::Size OverflowViewLayoutTest::kIndicatorPreferredSize;
TEST_F(OverflowViewLayoutTest, SizeToPreferredSizeIndicatorSmallerThanPrimary) {
indicator_view_->SetPreferredSize(kIndicatorMinimumSize);
SizeToPreferredSize();
EXPECT_EQ(gfx::Rect(kPrimaryPreferredSize), primary_bounds());
EXPECT_FALSE(indicator_visible());
}
TEST_F(OverflowViewLayoutTest, SizeToPreferredSizeIndicatorLargerThanPrimary) {
SizeToPreferredSize();
gfx::Size expected = kPrimaryPreferredSize;
expected.SetToMax(kIndicatorPreferredSize);
EXPECT_EQ(gfx::Rect(expected), primary_bounds());
EXPECT_FALSE(indicator_visible());
}
TEST_F(OverflowViewLayoutTest, ScaleToMinimum) {
// Since default cross-axis alignment is stretch, the view should fill the
// space even if it's larger than the preferred size.
gfx::Size size = kPrimaryPreferredSize;
size.Enlarge(10, 10);
Resize(size);
EXPECT_EQ(gfx::Rect(kPrimaryPreferredSize.width(), size.height()),
primary_bounds());
EXPECT_FALSE(indicator_visible());
// Default behavior is to scale down smoothly between preferred and minimum
// size.
size = kPrimaryPreferredSize;
size.Enlarge(-10, -10);
Resize(size);
EXPECT_EQ(gfx::Rect(size), primary_bounds());
EXPECT_FALSE(indicator_visible());
size = kPrimaryMinimumSize;
Resize(size);
EXPECT_EQ(gfx::Rect(size), primary_bounds());
EXPECT_FALSE(indicator_visible());
// Below minimum size, the stretch alignment means we'll compress.
size.Enlarge(0, -5);
Resize(size);
EXPECT_EQ(gfx::Rect(size), primary_bounds());
EXPECT_FALSE(indicator_visible());
}
TEST_F(OverflowViewLayoutTest, Alignment) {
gfx::Size size = kPrimaryPreferredSize;
size.Enlarge(0, 10);
Resize(size);
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(0, 0), kPrimaryPreferredSize),
primary_bounds());
EXPECT_FALSE(indicator_visible());
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kCenter);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(0, 5), kPrimaryPreferredSize),
primary_bounds());
EXPECT_FALSE(indicator_visible());
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kEnd);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(0, 10), kPrimaryPreferredSize),
primary_bounds());
EXPECT_FALSE(indicator_visible());
size = kPrimaryMinimumSize;
size.Enlarge(0, -10);
Resize(size);
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(0, 0), kPrimaryMinimumSize), primary_bounds());
EXPECT_FALSE(indicator_visible());
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kCenter);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(0, -5), kPrimaryMinimumSize),
primary_bounds());
EXPECT_FALSE(indicator_visible());
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kEnd);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(0, -10), kPrimaryMinimumSize),
primary_bounds());
EXPECT_FALSE(indicator_visible());
}
TEST_F(OverflowViewLayoutTest, ScaleToMinimumVertical) {
overflow_view_->SetOrientation(views::LayoutOrientation::kVertical);
gfx::Size size = kPrimaryPreferredSize;
size.Enlarge(10, 10);
Resize(size);
EXPECT_EQ(gfx::Rect(size.width(), kPrimaryPreferredSize.height()),
primary_bounds());
EXPECT_FALSE(indicator_visible());
// Default behavior is to scale down smoothly between preferred and minimum
// size.
size = kPrimaryPreferredSize;
size.Enlarge(-10, -10);
Resize(size);
EXPECT_EQ(gfx::Rect(size), primary_bounds());
EXPECT_FALSE(indicator_visible());
size = kPrimaryMinimumSize;
Resize(size);
EXPECT_EQ(gfx::Rect(size), primary_bounds());
EXPECT_FALSE(indicator_visible());
// Below minimum size, the stretch alignment means we'll compress.
size.Enlarge(-5, 0);
Resize(size);
EXPECT_EQ(gfx::Rect(size), primary_bounds());
EXPECT_FALSE(indicator_visible());
}
TEST_F(OverflowViewLayoutTest, AlignmentVertical) {
overflow_view_->SetOrientation(views::LayoutOrientation::kVertical);
gfx::Size size = kPrimaryPreferredSize;
size.Enlarge(10, 0);
Resize(size);
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(), kPrimaryPreferredSize), primary_bounds());
EXPECT_FALSE(indicator_visible());
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kCenter);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(5, 0), kPrimaryPreferredSize),
primary_bounds());
EXPECT_FALSE(indicator_visible());
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kEnd);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(10, 0), kPrimaryPreferredSize),
primary_bounds());
EXPECT_FALSE(indicator_visible());
size = kPrimaryMinimumSize;
size.Enlarge(-10, 0);
Resize(size);
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(0, 0), kPrimaryMinimumSize), primary_bounds());
EXPECT_FALSE(indicator_visible());
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kCenter);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(-5, 0), kPrimaryMinimumSize),
primary_bounds());
EXPECT_FALSE(indicator_visible());
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kEnd);
parent_view_->Layout();
EXPECT_EQ(gfx::Rect(gfx::Point(-10, 0), kPrimaryMinimumSize),
primary_bounds());
EXPECT_FALSE(indicator_visible());
}
TEST_F(OverflowViewLayoutTest, PrimaryOnlyRespectsFlexRule) {
primary_view_->SetProperty(views::kFlexBehaviorKey,
views::FlexSpecification(base::BindRepeating(
&OverflowViewTest::StepwiseFlexRule)));
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart);
// Since default cross-axis alignment is stretch, the view should fill the
// space even if it's larger than the preferred size.
gfx::Size size = kPrimaryPreferredSize;
size.Enlarge(7, 7);
Resize(size);
EXPECT_EQ(gfx::Rect(kPrimaryPreferredSize), primary_bounds());
// At intermediate sizes, this flex rule steps down by multiples of 10, to the
// next multiple smaller than the available space.
size = kPrimaryPreferredSize;
size.Enlarge(-7, -7);
Resize(size);
gfx::Size expected = kPrimaryPreferredSize;
expected.Enlarge(-10, -10);
EXPECT_EQ(gfx::Rect(expected), primary_bounds());
// The height bottoms out against the minimum size first.
size = kPrimaryPreferredSize;
size.Enlarge(-13, -13);
Resize(size);
EXPECT_EQ(gfx::Rect(kPrimaryPreferredSize.width() - 20,
kPrimaryMinimumSize.height()),
primary_bounds());
size = kPrimaryMinimumSize;
Resize(size);
EXPECT_EQ(gfx::Rect(size), primary_bounds());
// Below minimum vertical size we won't compress the primary view since we're
// not stretching it.
size.Enlarge(0, -5);
Resize(size);
EXPECT_EQ(gfx::Rect(kPrimaryMinimumSize), primary_bounds());
}
TEST_F(OverflowViewLayoutTest, HorizontalOverflow) {
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart);
// The primary view should start at the preferred size and scale down until it
// hits the minimum size.
gfx::Size size = kPrimaryPreferredSize;
size.Enlarge(10, 0);
Resize(size);
EXPECT_TRUE(primary_view_->GetVisible());
EXPECT_FALSE(indicator_view_->GetVisible());
EXPECT_EQ(gfx::Rect(kPrimaryPreferredSize), primary_bounds());
size = kPrimaryPreferredSize;
size.Enlarge(-10, 0);
Resize(size);
EXPECT_TRUE(primary_view_->GetVisible());
EXPECT_FALSE(indicator_view_->GetVisible());
EXPECT_EQ(gfx::Rect(size), primary_bounds());
size = kPrimaryMinimumSize;
Resize(size);
EXPECT_TRUE(primary_view_->GetVisible());
EXPECT_FALSE(indicator_view_->GetVisible());
EXPECT_EQ(gfx::Rect(size), primary_bounds());
// Below minimum size, the indicator will be displayed.
size.Enlarge(-5, 0);
Resize(size);
EXPECT_TRUE(primary_view_->GetVisible());
EXPECT_TRUE(indicator_view_->GetVisible());
const gfx::Rect expected_indicator{
size.width() - kIndicatorPreferredSize.width(), 0,
kIndicatorPreferredSize.width(), size.height()};
const gfx::Rect expected_primary(
gfx::Size(expected_indicator.x(), size.height()));
EXPECT_EQ(expected_indicator, indicator_bounds());
EXPECT_EQ(expected_primary, primary_bounds());
// If there is only enough room to show the indicator, then the primary view
// loses visibility.
size = kIndicatorMinimumSize;
Resize(size);
EXPECT_FALSE(primary_view_->GetVisible());
EXPECT_TRUE(indicator_view_->GetVisible());
EXPECT_EQ(gfx::Rect(size), indicator_bounds());
}
TEST_F(OverflowViewLayoutTest, VerticalOverflow) {
overflow_view_->SetOrientation(views::LayoutOrientation::kVertical);
overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart);
const views::FlexRule flex_rule =
base::BindRepeating(&OverflowViewLayoutTest::TransposingFlexRule);
primary_view_->SetProperty(views::kFlexBehaviorKey,
views::FlexSpecification(flex_rule));
indicator_view_->SetProperty(views::kFlexBehaviorKey,
views::FlexSpecification(flex_rule));
const gfx::Size primary_preferred = Transpose(kPrimaryPreferredSize);
const gfx::Size primary_minimum = Transpose(kPrimaryMinimumSize);
const gfx::Size indicator_preferred = Transpose(kIndicatorPreferredSize);
const gfx::Size indicator_minimum = Transpose(kIndicatorMinimumSize);
// The primary view should start at the preferred size and scale down until it
// hits the minimum size.
gfx::Size size = primary_preferred;
size.Enlarge(0, 10);
Resize(size);
EXPECT_TRUE(primary_view_->GetVisible());
EXPECT_FALSE(indicator_view_->GetVisible());
EXPECT_EQ(gfx::Rect(primary_preferred), primary_bounds());
size = primary_preferred;
size.Enlarge(0, -10);
Resize(size);
EXPECT_TRUE(primary_view_->GetVisible());
EXPECT_FALSE(indicator_view_->GetVisible());
EXPECT_EQ(gfx::Rect(size), primary_bounds());
size = primary_minimum;
Resize(size);
EXPECT_TRUE(primary_view_->GetVisible());
EXPECT_FALSE(indicator_view_->GetVisible());
EXPECT_EQ(gfx::Rect(size), primary_bounds());
// Below minimum size, the indicator will be displayed.
size.Enlarge(0, -5);
Resize(size);
EXPECT_TRUE(primary_view_->GetVisible());
EXPECT_TRUE(indicator_view_->GetVisible());
const gfx::Rect expected_indicator{
0, size.height() - indicator_preferred.height(), size.width(),
indicator_preferred.height()};
const gfx::Rect expected_primary(
gfx::Size(size.width(), expected_indicator.y()));
EXPECT_EQ(expected_indicator, indicator_bounds());
EXPECT_EQ(expected_primary, primary_bounds());
size = indicator_minimum;
Resize(size);
EXPECT_FALSE(primary_view_->GetVisible());
EXPECT_TRUE(indicator_view_->GetVisible());
EXPECT_EQ(gfx::Rect(size), indicator_bounds());
}
| 37.773764
| 80
| 0.726156
|
chromium
|
bbb9f9305db3702a4b26f8b6b4ba73adab3845da
| 424
|
cpp
|
C++
|
src/Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.cpp
|
sfulham/GameProject-1
|
83c065ac7abc4c0a098dfcb0d1cc13f9d8bf7a03
|
[
"MIT"
] | null | null | null |
src/Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.cpp
|
sfulham/GameProject-1
|
83c065ac7abc4c0a098dfcb0d1cc13f9d8bf7a03
|
[
"MIT"
] | null | null | null |
src/Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.cpp
|
sfulham/GameProject-1
|
83c065ac7abc4c0a098dfcb0d1cc13f9d8bf7a03
|
[
"MIT"
] | null | null | null |
//
// Created by MarcasRealAccount on 31. Oct. 2020
//
#include "Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.h"
#include "Engine/Renderer/Shader/Shader.h"
namespace gp1::renderer::apis::vulkan::shader
{
VulkanMaterialData::VulkanMaterialData(renderer::shader::Material* material)
: VulkanRendererData(material) {}
void VulkanMaterialData::CleanUp() {}
} // namespace gp1::renderer::apis::vulkan::shader
| 26.5
| 77
| 0.754717
|
sfulham
|
bbbc772b8773e5cae180e4580e552b77666c8a72
| 3,599
|
cpp
|
C++
|
src/system/libroot/posix/unistd/lockf.cpp
|
Kirishikesan/haiku
|
835565c55830f2dab01e6e332cc7e2d9c015b51e
|
[
"MIT"
] | 1,338
|
2015-01-03T20:06:56.000Z
|
2022-03-26T13:49:54.000Z
|
src/system/libroot/posix/unistd/lockf.cpp
|
Kirishikesan/haiku
|
835565c55830f2dab01e6e332cc7e2d9c015b51e
|
[
"MIT"
] | 15
|
2015-01-17T22:19:32.000Z
|
2021-12-20T12:35:00.000Z
|
src/system/libroot/posix/unistd/lockf.cpp
|
Kirishikesan/haiku
|
835565c55830f2dab01e6e332cc7e2d9c015b51e
|
[
"MIT"
] | 350
|
2015-01-08T14:15:27.000Z
|
2022-03-21T18:14:35.000Z
|
/*
* Copyright 2007, Vasilis Kaoutsis, kaoutsis@sch.gr.
* Distributed under the terms of the MIT License.
*/
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno_private.h>
int
lockf(int fileDescriptor, int function, off_t size)
{
struct flock fileLock;
fileLock.l_start = 0;
fileLock.l_len = size;
fileLock.l_whence = SEEK_CUR;
if (function == F_ULOCK) {
// unlock locked sections
fileLock.l_type = F_UNLCK;
return fcntl(fileDescriptor, F_SETLK, &fileLock);
} else if (function == F_LOCK) {
// lock a section for exclusive use
fileLock.l_type = F_WRLCK;
return fcntl(fileDescriptor, F_SETLKW, &fileLock);
} else if (function == F_TLOCK) {
// test and lock a section for exclusive use
fileLock.l_type = F_WRLCK;
return fcntl(fileDescriptor, F_SETLK, &fileLock);
} else if (function == F_TEST) {
// test a section for locks by other processes
fileLock.l_type = F_WRLCK;
if (fcntl(fileDescriptor, F_GETLK, &fileLock) == -1)
return -1;
if (fileLock.l_type == F_UNLCK)
return 0;
__set_errno(EAGAIN);
return -1;
} else {
__set_errno(EINVAL);
return -1;
}
// Notes regarding standard compliance (cf. Open Group Base Specs):
// * "The interaction between fcntl() and lockf() locks is unspecified."
// * fcntl() locking works on a per-process level. The lockf() description
// is a little fuzzy on whether it works the same way. The first quote
// seem to describe per-thread locks (though it might actually mean
// "threads of other processes"), but the others quotes are strongly
// indicating per-process locks:
// - "Calls to lockf() from other threads which attempt to lock the locked
// file section shall either return an error value or block until the
// section becomes unlocked."
// - "All the locks for a process are removed when the process
// terminates."
// - "F_TEST shall detect if a lock by another process is present on the
// specified section."
// - "The sections locked with F_LOCK or F_TLOCK may, in whole or in part,
// contain or be contained by a previously locked section for the same
// process. When this occurs, or if adjacent locked sections would
// occur, the sections shall be combined into a single locked section."
// * fcntl() and lockf() handle a 0 size argument differently. The former
// use the file size at the time of the call:
// "If the command is F_SETLKW and the process must wait for another
// process to release a lock, then the range of bytes to be locked shall
// be determined before the fcntl() function blocks. If the file size
// or file descriptor seek offset change while fcntl() is blocked, this
// shall not affect the range of bytes locked."
// lockf(), on the other hand, is supposed to create a lock whose size
// dynamically adjusts to the file size:
// "If size is 0, the section from the current offset through the largest
// possible file offset shall be locked (that is, from the current
// offset through the present or any future end-of-file)."
// * The lock release handling when closing descriptors sounds a little
// different, though might actually mean the same.
// For fcntl():
// "All locks associated with a file for a given process shall be removed
// when a file descriptor for that file is closed by that process or the
// process holding that file descriptor terminates."
// For lockf():
// "File locks shall be released on first close by the locking process of
// any file descriptor for the file."
}
| 40.897727
| 77
| 0.701028
|
Kirishikesan
|
bbbef5de65bc8b029ed136f8309ca4db2a319ecb
| 1,879
|
cpp
|
C++
|
src/plugins/zalil/servicesmanager.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 120
|
2015-01-22T14:10:39.000Z
|
2021-11-25T12:57:16.000Z
|
src/plugins/zalil/servicesmanager.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 8
|
2015-02-07T19:38:19.000Z
|
2017-11-30T20:18:28.000Z
|
src/plugins/zalil/servicesmanager.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 33
|
2015-02-07T16:59:55.000Z
|
2021-10-12T00:36:40.000Z
|
/**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "servicesmanager.h"
#include <algorithm>
#include <QStringList>
#include <QFileInfo>
#include <QtDebug>
#include "servicebase.h"
#include "pendinguploadbase.h"
#include "bitcheeseservice.h"
namespace LC
{
namespace Zalil
{
ServicesManager::ServicesManager (const ICoreProxy_ptr& proxy, QObject *parent)
: QObject { parent }
, Proxy_ { proxy }
{
Services_ << std::make_shared<BitcheeseService> (proxy, this);
}
QStringList ServicesManager::GetNames (const QString& file) const
{
const auto fileSize = file.isEmpty () ?
0 :
QFileInfo { file }.size ();
QStringList result;
for (const auto& service : Services_)
if (service->GetMaxFileSize () > fileSize)
result << service->GetName ();
return result;
}
PendingUploadBase* ServicesManager::Upload (const QString& file, const QString& svcName)
{
const auto pos = std::find_if (Services_.begin (), Services_.end (),
[&svcName] (const ServiceBase_ptr& service)
{ return service->GetName () == svcName; });
if (pos == Services_.end ())
{
qWarning () << Q_FUNC_INFO
<< "cannot find service"
<< svcName;
return nullptr;
}
const auto pending = (*pos)->UploadFile (file);
if (!pending)
{
qWarning () << Q_FUNC_INFO
<< "unable to upload"
<< file
<< "to"
<< svcName;
return nullptr;
}
connect (pending,
SIGNAL (fileUploaded (QString, QUrl)),
this,
SIGNAL (fileUploaded (QString, QUrl)));
return pending;
}
}
}
| 25.053333
| 89
| 0.619478
|
Maledictus
|
bbc18b7e6cbf92a4660726cc386e7834f0fb3e2d
| 1,773
|
cpp
|
C++
|
code/mandelbrot_tty/main.cpp
|
battibass/pf2021
|
7d370d26a53588c3168b57614e34e0dda70f5bbf
|
[
"CC-BY-4.0"
] | 7
|
2021-10-20T08:43:46.000Z
|
2022-03-26T14:18:19.000Z
|
code/mandelbrot_tty/main.cpp
|
battibass/pf2021
|
7d370d26a53588c3168b57614e34e0dda70f5bbf
|
[
"CC-BY-4.0"
] | null | null | null |
code/mandelbrot_tty/main.cpp
|
battibass/pf2021
|
7d370d26a53588c3168b57614e34e0dda70f5bbf
|
[
"CC-BY-4.0"
] | 10
|
2021-10-01T13:49:56.000Z
|
2022-03-29T10:28:06.000Z
|
#include <iostream>
#include <string>
class Complex
{
double r_;
double i_;
public:
Complex(double r = 0., double i = 0.) : r_{r}, i_{i}
{
}
double real() const
{
return r_;
}
double imag() const
{
return i_;
}
Complex& operator+=(Complex const& o)
{
r_ += o.r_;
i_ += o.i_;
return *this;
}
Complex& operator*=(Complex const& o)
{
auto t = r_ * o.r_ - i_ * o.i_;
i_ = r_ * o.i_ + i_ * o.r_;
r_ = t;
return *this;
}
};
Complex operator-(Complex const& c)
{
return {-c.real(), -c.imag()};
}
Complex operator+(Complex const& left, Complex const& right)
{
auto result = left;
return result += right;
}
Complex operator-(Complex const& left, Complex const& right)
{
return left + (-right);
}
Complex operator*(Complex const& left, Complex const& right)
{
auto result = left;
return result *= right;
}
double norm2(Complex const& c)
{
return c.real() * c.real() + c.imag() * c.imag();
}
int mandelbrot(Complex const& c)
{
int i = 0;
auto z = c;
for (; i != 256 && norm2(z) < 4.; ++i) {
z = z * z + c;
}
return i;
}
auto to_symbol(int k)
{
return k < 256 ? ' ' : '*';
}
int main()
{
int const display_width = 100;
int const display_height = 48;
Complex const top_left{-2.3, 1.};
Complex const lower_right{0.8, -1.};
auto const diff = lower_right - top_left;
auto const delta_x = diff.real() / display_width;
auto const delta_y = diff.imag() / display_height;
for (int row{0}; row != display_height; ++row) {
std::string line;
for (int column{0}; column != display_width; ++column) {
auto k = mandelbrot(top_left + Complex{delta_x * column, delta_y * row});
line.push_back(to_symbol(k));
}
std::cout << line << '\n';
}
}
| 17.909091
| 79
| 0.585448
|
battibass
|
bbc1d2621c8dd95ab7076682e99978b9f8e22d8a
| 8,626
|
cpp
|
C++
|
Tests/DiligentToolsTest/src/RenderStateNotationParser/PipelineStateParserTest.cpp
|
SebMenozzi/DiligentTools
|
cf2d8b67df590a93862749051c65310535a2f3cd
|
[
"Apache-2.0"
] | null | null | null |
Tests/DiligentToolsTest/src/RenderStateNotationParser/PipelineStateParserTest.cpp
|
SebMenozzi/DiligentTools
|
cf2d8b67df590a93862749051c65310535a2f3cd
|
[
"Apache-2.0"
] | null | null | null |
Tests/DiligentToolsTest/src/RenderStateNotationParser/PipelineStateParserTest.cpp
|
SebMenozzi/DiligentTools
|
cf2d8b67df590a93862749051c65310535a2f3cd
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2019-2022 Diligent Graphics LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "gtest/gtest.h"
#include "DRSNLoader.hpp"
using namespace Diligent;
namespace
{
TEST(Tools_RenderStateNotationParser, ParsePipelineStateEnums)
{
DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()};
ASSERT_TRUE(TestEnum<PIPELINE_TYPE>(Allocator, PIPELINE_TYPE_GRAPHICS, PIPELINE_TYPE_LAST));
ASSERT_TRUE(TestBitwiseEnum<SHADER_VARIABLE_FLAGS>(Allocator, SHADER_VARIABLE_FLAG_LAST));
ASSERT_TRUE(TestBitwiseEnum<PIPELINE_SHADING_RATE_FLAGS>(Allocator, PIPELINE_SHADING_RATE_FLAG_LAST));
ASSERT_TRUE(TestBitwiseEnum<SHADER_VARIABLE_FLAGS>(Allocator, SHADER_VARIABLE_FLAG_LAST));
ASSERT_TRUE(TestBitwiseEnum<PSO_CREATE_FLAGS>(Allocator, PSO_CREATE_FLAG_LAST));
}
TEST(Tools_RenderStateNotationParser, ParseSampleDesc)
{
CHECK_STRUCT_SIZE(SampleDesc, 2);
DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()};
nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/SampleDesc.json");
SampleDesc DescReference{};
DescReference.Count = 4;
DescReference.Quality = 1;
SampleDesc Desc{};
ParseRSN(JsonReference, Desc, Allocator);
ASSERT_EQ(Desc, DescReference);
}
TEST(Tools_RenderStateNotationParser, ParseShaderResourceVariableDesc)
{
CHECK_STRUCT_SIZE(ShaderResourceVariableDesc, 24);
DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()};
nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/ShaderResourceVariableDesc.json");
ShaderResourceVariableDesc DescReference{};
DescReference.Name = "TestName";
DescReference.Type = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC;
DescReference.ShaderStages = SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL;
DescReference.Flags = SHADER_VARIABLE_FLAG_NO_DYNAMIC_BUFFERS | SHADER_VARIABLE_FLAG_GENERAL_INPUT_ATTACHMENT;
ShaderResourceVariableDesc Desc{};
ParseRSN(JsonReference, Desc, Allocator);
ASSERT_EQ(Desc, DescReference);
}
TEST(Tools_RenderStateNotationParser, ParsePipelineResourceLayoutDesc)
{
CHECK_STRUCT_SIZE(PipelineResourceLayoutDesc, 40);
DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()};
nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/PipelineResourceLayoutDesc.json");
constexpr ShaderResourceVariableDesc Variables[] = {
{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "TestName0", SHADER_RESOURCE_VARIABLE_TYPE_STATIC},
{SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "TestName1", SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}};
constexpr ImmutableSamplerDesc Samplers[] = {
ImmutableSamplerDesc{SHADER_TYPE_ALL_RAY_TRACING, "TestName0", {FILTER_TYPE_POINT, FILTER_TYPE_MAXIMUM_POINT, FILTER_TYPE_ANISOTROPIC}},
ImmutableSamplerDesc{SHADER_TYPE_PIXEL, "TestName1", {FILTER_TYPE_COMPARISON_POINT, FILTER_TYPE_COMPARISON_LINEAR, FILTER_TYPE_COMPARISON_ANISOTROPIC}}};
PipelineResourceLayoutDesc DescReference{};
DescReference.DefaultVariableMergeStages = SHADER_TYPE_ALL_GRAPHICS;
DescReference.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE;
DescReference.Variables = Variables;
DescReference.NumVariables = _countof(Variables);
DescReference.ImmutableSamplers = Samplers;
DescReference.NumImmutableSamplers = _countof(Samplers);
PipelineResourceLayoutDesc Desc{};
ParseRSN(JsonReference, Desc, Allocator);
ASSERT_EQ(Desc, DescReference);
}
TEST(Tools_RenderStateNotationParser, ParseGraphicsPipelineDesc)
{
CHECK_STRUCT_SIZE(GraphicsPipelineDesc, 192);
DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()};
nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/GraphicsPipelineDesc.json");
constexpr LayoutElement InputLayoutElemets[] = {
LayoutElement{0, 0, 3, VT_FLOAT32},
LayoutElement{1, 0, 4, VT_FLOAT32}};
GraphicsPipelineDesc DescReference{};
DescReference.SampleMask = 1245678;
DescReference.PrimitiveTopology = PRIMITIVE_TOPOLOGY_POINT_LIST;
DescReference.NumViewports = 2;
DescReference.SubpassIndex = 1;
DescReference.NodeMask = 1;
DescReference.DepthStencilDesc.DepthEnable = false;
DescReference.RasterizerDesc.CullMode = CULL_MODE_FRONT;
DescReference.ShadingRateFlags = PIPELINE_SHADING_RATE_FLAG_PER_PRIMITIVE | PIPELINE_SHADING_RATE_FLAG_TEXTURE_BASED;
DescReference.BlendDesc.RenderTargets[0].BlendEnable = true;
DescReference.InputLayout.LayoutElements = InputLayoutElemets;
DescReference.InputLayout.NumElements = _countof(InputLayoutElemets);
DescReference.DSVFormat = TEX_FORMAT_D32_FLOAT;
DescReference.NumRenderTargets = 2;
DescReference.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM;
DescReference.RTVFormats[1] = TEX_FORMAT_RG16_FLOAT;
DescReference.SmplDesc.Count = 4;
DescReference.SmplDesc.Quality = 1;
GraphicsPipelineDesc Desc{};
ParseRSN(JsonReference, Desc, Allocator);
ASSERT_EQ(Desc, DescReference);
}
TEST(Tools_RenderStateNotationParser, ParseRayTracingPipelineDesc)
{
CHECK_STRUCT_SIZE(RayTracingPipelineDesc, 4);
DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()};
nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/RayTracingPipelineDesc.json");
RayTracingPipelineDesc DescReference{};
DescReference.MaxRecursionDepth = 7;
DescReference.ShaderRecordSize = 4096;
RayTracingPipelineDesc Desc{};
ParseRSN(JsonReference, Desc, Allocator);
ASSERT_EQ(Desc, DescReference);
}
TEST(Tools_RenderStateNotationParser, ParsePipelineStateDesc)
{
CHECK_STRUCT_SIZE(PipelineStateDesc, 64);
DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()};
nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/PipelineStateDesc.json");
PipelineStateDesc DescReference{};
DescReference.PipelineType = PIPELINE_TYPE_COMPUTE;
DescReference.Name = "TestName";
DescReference.SRBAllocationGranularity = 16;
DescReference.ImmediateContextMask = 1;
DescReference.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC;
PipelineStateDesc Desc{};
ParseRSN(JsonReference, Desc, Allocator);
ASSERT_EQ(Desc, DescReference);
}
TEST(Tools_RenderStateNotationParser, ParseTilePipelineDesc)
{
CHECK_STRUCT_SIZE(TilePipelineDesc, 18);
DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()};
nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/TilePipelineDesc.json");
TilePipelineDesc DescReference{};
DescReference.NumRenderTargets = 2;
DescReference.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM;
DescReference.RTVFormats[1] = TEX_FORMAT_RG16_FLOAT;
DescReference.SampleCount = 4;
TilePipelineDesc Desc{};
ParseRSN(JsonReference, Desc, Allocator);
ASSERT_EQ(Desc, DescReference);
}
} // namespace
| 41.07619
| 161
| 0.761651
|
SebMenozzi
|
bbc21fea637e1879270776e4399ec10b782f2ba7
| 3,861
|
hpp
|
C++
|
source/Irrlicht/rtc/impl/threadpool.hpp
|
MagicAtom/irrlicht-ce
|
b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d
|
[
"IJG"
] | null | null | null |
source/Irrlicht/rtc/impl/threadpool.hpp
|
MagicAtom/irrlicht-ce
|
b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d
|
[
"IJG"
] | null | null | null |
source/Irrlicht/rtc/impl/threadpool.hpp
|
MagicAtom/irrlicht-ce
|
b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d
|
[
"IJG"
] | null | null | null |
/**
* Copyright (c) 2020 Paul-Louis Ageneau
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef RTC_IMPL_THREADPOOL_H
#define RTC_IMPL_THREADPOOL_H
#include "common.hpp"
#include "init.hpp"
#include "internals.hpp"
#include <chrono>
#include <condition_variable>
#include <deque>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <stdexcept>
#include <thread>
#include <vector>
namespace rtc::impl {
template <class F, class... Args>
using invoke_future_t = std::future<std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>;
class ThreadPool final {
public:
using clock = std::chrono::steady_clock;
static ThreadPool &Instance();
ThreadPool(const ThreadPool &) = delete;
ThreadPool &operator=(const ThreadPool &) = delete;
ThreadPool(ThreadPool &&) = delete;
ThreadPool &operator=(ThreadPool &&) = delete;
int count() const;
void spawn(int count = 1);
void join();
void run();
bool runOne();
template <class F, class... Args>
auto enqueue(F &&f, Args &&...args) -> invoke_future_t<F, Args...>;
template <class F, class... Args>
auto schedule(clock::duration delay, F &&f, Args &&...args) -> invoke_future_t<F, Args...>;
template <class F, class... Args>
auto schedule(clock::time_point time, F &&f, Args &&...args) -> invoke_future_t<F, Args...>;
private:
ThreadPool();
~ThreadPool();
std::function<void()> dequeue(); // returns null function if joining
std::vector<std::thread> mWorkers;
std::atomic<int> mBusyWorkers = 0;
std::atomic<bool> mJoining = false;
struct Task {
clock::time_point time;
std::function<void()> func;
bool operator>(const Task &other) const { return time > other.time; }
bool operator<(const Task &other) const { return time < other.time; }
};
std::priority_queue<Task, std::deque<Task>, std::greater<Task>> mTasks;
std::condition_variable mTasksCondition, mWaitingCondition;
mutable std::mutex mMutex, mWorkersMutex;
};
template <class F, class... Args>
auto ThreadPool::enqueue(F &&f, Args &&...args) -> invoke_future_t<F, Args...> {
return schedule(clock::now(), std::forward<F>(f), std::forward<Args>(args)...);
}
template <class F, class... Args>
auto ThreadPool::schedule(clock::duration delay, F &&f, Args &&...args)
-> invoke_future_t<F, Args...> {
return schedule(clock::now() + delay, std::forward<F>(f), std::forward<Args>(args)...);
}
template <class F, class... Args>
auto ThreadPool::schedule(clock::time_point time, F &&f, Args &&...args)
-> invoke_future_t<F, Args...> {
std::unique_lock lock(mMutex);
using R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>;
auto bound = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
auto task = std::make_shared<std::packaged_task<R()>>([bound = std::move(bound)]() mutable {
try {
return bound();
} catch (const std::exception &e) {
PLOG_WARNING << e.what();
throw;
}
});
std::future<R> result = task->get_future();
mTasks.push({time, [task = std::move(task), token = Init::Instance().token()]() { return (*task)(); }});
mTasksCondition.notify_one();
return result;
}
} // namespace rtc::impl
#endif
| 30.642857
| 105
| 0.690236
|
MagicAtom
|
bbc512ed68463d935ede3a4f15d7ad35183f3eec
| 310
|
hxx
|
C++
|
src/common.hxx
|
scuisdc/iojxd
|
6ced0d5983a8075c313869791f7295b98ce3f174
|
[
"BSD-2-Clause"
] | 1
|
2015-05-18T00:02:13.000Z
|
2015-05-18T00:02:13.000Z
|
src/common.hxx
|
scuisdc/iojxd
|
6ced0d5983a8075c313869791f7295b98ce3f174
|
[
"BSD-2-Clause"
] | null | null | null |
src/common.hxx
|
scuisdc/iojxd
|
6ced0d5983a8075c313869791f7295b98ce3f174
|
[
"BSD-2-Clause"
] | null | null | null |
//
// Created by secondwtq <lovejay-lovemusic@outlook.com> 2015/05/18.
// Copyright (c) 2015 SCU ISDC All rights reserved.
//
// This file is part of ISDCNext.
//
// We have always treaded the borderland.
//
#ifndef IOJXD_COMMON_HXX
#define IOJXD_COMMON_HXX
#include "context.hxx"
#endif //IOJXD_COMMON_HXX
| 19.375
| 67
| 0.735484
|
scuisdc
|
bbc5e81a9964600eb7019aeadcbff4cb0a8329ec
| 1,961
|
cpp
|
C++
|
OpenCV/gray_image.cpp
|
vladiant/color2gray
|
372283ae67b0dfb41745108f67cc714efc7b3d7a
|
[
"MIT"
] | null | null | null |
OpenCV/gray_image.cpp
|
vladiant/color2gray
|
372283ae67b0dfb41745108f67cc714efc7b3d7a
|
[
"MIT"
] | null | null | null |
OpenCV/gray_image.cpp
|
vladiant/color2gray
|
372283ae67b0dfb41745108f67cc714efc7b3d7a
|
[
"MIT"
] | null | null | null |
#include "gray_image.hpp"
#include <opencv2/imgcodecs.hpp>
GrayImage::GrayImage(ColorImage &s) : data(s.N), w(s.w), h(s.h), N(s.N) {
for (int i = 0; i < N; i++) data[i] = (s.data)[i].l;
}
void GrayImage::r_solve(const float *d, int r) {
const int iters = 30;
int k, x, y;
for (k = 0; k < iters; k++) {
// printf("iter %d\n", k);
// perform a Gauss-Seidel relaxation.
for (x = 0; x < w; x++)
for (y = 0; y < h; y++) {
float sum = 0;
int count = 0;
int xx, yy;
for (xx = x - r; xx <= x + r; xx++) {
if (xx < 0 || xx >= w) continue;
for (yy = y - r; yy <= y + r; yy++) {
if (yy >= h || yy < 0) continue;
sum += data[xx + yy * w];
count++;
}
}
data[x + y * w] = (d[x + w * y] + sum) / (float)count;
}
}
}
void GrayImage::complete_solve(const float *d) {
for (int i = 1; i < N; i++) {
data[i] = d[i] - d[i - 1] + N * data[i - 1];
data[i] /= (float)N;
}
}
void GrayImage::post_solve(const ColorImage &s) {
float error = 0;
for (int i = 0; i < N; i++) error += data[i] - (s.data)[i].l;
error /= N;
for (int i = 0; i < N; i++) data[i] = data[i] - error;
}
cv::Mat GrayImage::save(const char *fname) const {
cv::Mat3b out_image(h, w);
auto it = out_image.begin();
for (int i = 0; i < N; i++, ++it) {
const sven::rgb rval = amy_lab(data[i], 0, 0).to_rgb();
*it = cv::Vec3b(rval.r, rval.g, rval.b);
}
cv::imwrite(fname, out_image);
return out_image;
}
cv::Mat GrayImage::saveColor(const char *fname,
const ColorImage &source) const {
cv::Mat3b out_image(h, w);
auto it = out_image.begin();
for (int i = 0; i < N; i++, ++it) {
const sven::rgb rval =
amy_lab(data[i], ((source.data)[i]).a, ((source.data)[i]).b).to_rgb();
*it = cv::Vec3b(rval.b, rval.g, rval.r);
}
cv::imwrite(fname, out_image);
return out_image;
}
| 25.802632
| 78
| 0.494646
|
vladiant
|
bbc685778822168fdfc95254155507c30e9efd6e
| 6,505
|
cpp
|
C++
|
DrunkEngine/ComponentTransform.cpp
|
MarcFly/Fly3D-Engine
|
e8da09a63c7c3d991b8f25c346798ee230593e78
|
[
"Unlicense"
] | null | null | null |
DrunkEngine/ComponentTransform.cpp
|
MarcFly/Fly3D-Engine
|
e8da09a63c7c3d991b8f25c346798ee230593e78
|
[
"Unlicense"
] | 3
|
2018-09-27T17:00:14.000Z
|
2018-12-19T13:30:25.000Z
|
DrunkEngine/ComponentTransform.cpp
|
MarcFly/Fly3D-Engine
|
e8da09a63c7c3d991b8f25c346798ee230593e78
|
[
"Unlicense"
] | null | null | null |
#include "ComponentTransform.h"
#include "GameObject.h"
#include "Assimp/include/scene.h"
#include "GameObject.h"
#include "Application.h"
ComponentTransform::ComponentTransform(const aiMatrix4x4 * t, GameObject* par)
{
SetBaseVals();
SetFromMatrix(t);
parent = par;
SetLocalTransform();
}
void ComponentTransform::SetFromMatrix(const aiMatrix4x4* t)
{
aiVector3D local_scale;
aiVector3D pos;
aiQuaternion rot;
t->Decompose(local_scale, rot, pos);
scale = float3(local_scale.x, local_scale.y, local_scale.z);
rotate_quat = Quat(rot.x, rot.y, rot.z, rot.w);
position = float3(pos.x, pos.y, pos.z);
SetTransformRotation(rotate_quat);
}
void ComponentTransform::SetFromMatrix(const float4x4 * t)
{
float3 local_scale;
float3 pos;
Quat rot;
t->Decompose(position, rotate_quat, scale);
SetTransformRotation(rotate_quat);
}
void ComponentTransform::SetTransformPosition(const float pos_x, const float pos_y, const float pos_z)
{
position.x = pos_x;
position.y = pos_y;
position.z = pos_z;
SetLocalTransform();
}
void ComponentTransform::SetTransformRotation(const Quat rot_quat)
{
rotate_quat = rot_quat;
rotate_euler = RadToDeg(rotate_quat.ToEulerXYZ());
SetLocalTransform();
}
void ComponentTransform::SetTransformRotation(const float3 rot_vec)
{
rotate_quat = Quat::FromEulerXYZ(DegToRad(rot_vec.x), DegToRad(rot_vec.y), DegToRad(rot_vec.z));
rotate_euler = rot_vec;
SetLocalTransform();
}
void ComponentTransform::SetTransformScale(const float scale_x, const float scale_y, const float scale_z)
{
if (scale.x != scale_x && scale_x > 0.1f)
scale.x = scale_x;
if (scale.y != scale_y && scale_y > 0.1f)
scale.y = scale_y;
if (scale.z != scale_z && scale_z > 0.1f)
scale.z = scale_z;
SetLocalTransform();
}
void ComponentTransform::SetLocalTransform()
{
local_transform = float4x4::FromTRS(position, rotate_quat, scale);
}
void ComponentTransform::SetWorldPos(const float4x4 new_transform)
{
aux_world_pos = aux_world_pos * new_transform;
world_pos = world_pos * new_transform;
}
void ComponentTransform::SetWorldRot(const Quat new_rot)
{
world_rot = world_rot * world_rot.FromQuat(new_rot, aux_world_pos.Col3(3) - world_pos.Col3(3));
//world_rot[0][0] = 1.f;
//world_rot[1][1] = 1.f;
//world_rot[2][2] = 1.f;
//world_rot[3][3] = 1.f;
}
void ComponentTransform::CalculateGlobalTransforms()
{
if (parent->parent != nullptr)
global_transform = world_pos * world_rot * parent->parent->GetTransform()->global_transform * local_transform;
else
global_transform = local_transform;
global_transform.Decompose(global_pos, global_rot, global_scale);
//global_pos = global_transform.Col3(3);
//global_rot = GetRotFromMat(global_transform);
//global_scale = global_transform.GetScale();
if (parent->children.size() > 0)
{
for (std::vector<GameObject*>::iterator it = parent->children.begin(); it != parent->children.end(); it++)
{
(*it)->GetTransform()->CalculateGlobalTransforms();
}
}
SetAuxWorldPos();
}
void ComponentTransform::SetAuxWorldPos()
{
aux_world_pos = float4x4::FromTRS(float3(float3::zero - global_transform.Col3(3)), Quat::identity.Neg(), float3::one);
aux_world_pos = -aux_world_pos;
}
Quat ComponentTransform::GetRotFromMat(float4x4 mat)
{
Quat rot;
rot.w = Sqrt(max(0, 1 + mat.Diagonal3().x + mat.Diagonal3().y + mat.Diagonal3().z)) / 2;
rot.x = Sqrt(max(0, 1 + mat.Diagonal3().x - mat.Diagonal3().y - mat.Diagonal3().z)) / 2;
rot.y = Sqrt(max(0, 1 - mat.Diagonal3().x + mat.Diagonal3().y - mat.Diagonal3().z)) / 2;
rot.z = Sqrt(max(0, 1 - mat.Diagonal3().x - mat.Diagonal3().y + mat.Diagonal3().z)) / 2;
rot.x *= sgn(rot.x * (mat.Col3(2).y - mat.Col3(1).z));
rot.y *= sgn(rot.y * (mat.Col3(0).z - mat.Col3(2).x));
rot.z *= sgn(rot.z * (mat.Col3(1).x - mat.Col3(0).y));
rot.x = -rot.x;
rot.y = -rot.y;
rot.z = -rot.z;
return rot;
}
void ComponentTransform::CleanUp()
{
parent = nullptr;
}
void ComponentTransform::Load(const JSON_Object* comp)
{
position.x = json_object_dotget_number(comp, "position.x");
position.y = json_object_dotget_number(comp, "position.y");
position.z = json_object_dotget_number(comp, "position.z");
scale.x = json_object_dotget_number(comp, "scale.x");
scale.y = json_object_dotget_number(comp, "scale.y");
scale.z = json_object_dotget_number(comp, "scale.z");
rotate_quat.w = json_object_dotget_number(comp, "rotate_quat.w");
rotate_quat.x = json_object_dotget_number(comp, "rotate_quat.x");
rotate_quat.y = json_object_dotget_number(comp, "rotate_quat.y");
rotate_quat.z = json_object_dotget_number(comp, "rotate_quat.z");
SetTransformRotation(rotate_quat);
SetLocalTransform();
bool fromAINode = json_object_dotget_boolean(comp, "fromAINode");
std::string setname;
if (!fromAINode)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
setname = "world_pos." + std::to_string(j + i * 4);
world_pos.v[i][j] = json_object_dotget_number(comp, setname.c_str());
setname = "world_rot." + std::to_string(j + i * 4);
world_rot.v[i][j] = json_object_dotget_number(comp, setname.c_str());
}
}
}
}
void ComponentTransform::Save(JSON_Array* comps)
{
JSON_Value* append = json_value_init_object();
JSON_Object* curr = json_value_get_object(append);
json_object_dotset_number(curr, "properties.type", type);
json_object_dotset_number(curr, "properties.position.x", position.x);
json_object_dotset_number(curr, "properties.position.y", position.y);
json_object_dotset_number(curr, "properties.position.z", position.z);
json_object_dotset_number(curr, "properties.scale.x", scale.x);
json_object_dotset_number(curr, "properties.scale.y", scale.y);
json_object_dotset_number(curr, "properties.scale.z", scale.z);
json_object_dotset_number(curr, "properties.rotate_quat.w", rotate_quat.w);
json_object_dotset_number(curr, "properties.rotate_quat.x", rotate_quat.x);
json_object_dotset_number(curr, "properties.rotate_quat.y", rotate_quat.y);
json_object_dotset_number(curr, "properties.rotate_quat.z", rotate_quat.z);
json_object_dotset_boolean(curr, "properties.fromAINode", false);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
std::string setname = "properties.world_pos." + std::to_string(j + i*4);
json_object_dotset_number(curr, setname.c_str(), world_pos.v[i][j]);
setname = "properties.world_rot." + std::to_string(j + i*4);
json_object_dotset_number(curr, setname.c_str(), world_rot.v[i][j]);
}
}
json_array_append_value(comps, append);
}
| 28.656388
| 119
| 0.719139
|
MarcFly
|
bbd3514f31648310f957b4b1fcb9c0c7b60f944c
| 3,199
|
hpp
|
C++
|
src/Base/TaskProcessors/ThreadedTaskProcessor/ThreadedTaskProcessor.hpp
|
PhilipVinc/PincoSimulator
|
562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3
|
[
"MIT"
] | 1
|
2017-10-23T13:22:01.000Z
|
2017-10-23T13:22:01.000Z
|
src/Base/TaskProcessors/ThreadedTaskProcessor/ThreadedTaskProcessor.hpp
|
PhilipVinc/PincoSimulator
|
562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3
|
[
"MIT"
] | null | null | null |
src/Base/TaskProcessors/ThreadedTaskProcessor/ThreadedTaskProcessor.hpp
|
PhilipVinc/PincoSimulator
|
562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3
|
[
"MIT"
] | null | null | null |
//
// Created by Filippo Vicentini on 20/12/2017.
//
#ifndef SIMULATOR_THREADEDTASKPROCESSOR_HPP
#define SIMULATOR_THREADEDTASKPROCESSOR_HPP
#include "Base/TaskProcessor.hpp"
#include "Libraries/concurrentqueue.h"
#include <chrono>
#include <stdio.h>
#include <queue>
#include <vector>
#include <thread>
class Settings;
class WorkerThread;
class ThreadedTaskProcessor : public TaskProcessor
{
public:
ThreadedTaskProcessor(std::string solverName, int _processes, int _max_processes = 0);
virtual ~ThreadedTaskProcessor();
virtual void Setup() final;
virtual void Update() final;
// -------- Called From Workers ---------- //
// Take a task from dispatchedTasks to execute it (called by a worker)
std::vector<std::unique_ptr<TaskData>> GetDispatchedTasks(size_t th_id, size_t maxTasks =1);
void GiveCompletedResults(size_t th_id, std::vector<TaskResults*> res);
void GiveCompletedResults(size_t th_id, TaskResults* res);
// -------------------------------------- //
// Return a completed task, to add it to elaboratedTasks
void GiveResults(size_t th_id, std::unique_ptr<TaskResults> task);
void GiveResults(size_t th_id, std::vector<std::unique_ptr<TaskResults>>&& tasks);
// Method called by a thread to inform the manager that he is now dead
// and can be joined.
void ReportThreadTermination(size_t th_id);
virtual void AllProducersHaveBeenTerminated() final;
void Terminate();
void TerminateWhenDone();
protected:
// Redef
size_t nTasksEnqueued = 0;
// Threading support
size_t nThreads = 1;
#ifdef GPU_SUPPORT
size_t nGPUThreads = 0;
size_t nAvailableGPUs = 0;
#endif
// --- old---
size_t nTasksLeftToEnqueue = 0;
size_t nTasksToSave = 0;
size_t nTasksFillCapacity = 1;
mutable size_t nCompletedTasks = 0;
size_t nTotalTasks = 0;
private:
size_t nextWorkerId = 0;
std::vector<size_t> activeThreads;
std::queue<size_t> unactivatedThreadPool;
moodycamel::ConcurrentQueue<size_t> threadsToJoin;
std::vector<std::thread> threads;
std::vector<WorkerThread*> workers;
std::vector<size_t> workerProducerID;
std::vector<size_t> workerCompletedTasks;
bool terminate = false;
bool terminateWhenDone = false;
void CreateWorker(Solver* solver);
void TerminateWorker(size_t i);
void TerminateWorkerWhenDone(size_t i);
void TerminateAllWorkers();
void TerminateAllWorkersWhenDone();
void JoinThread(size_t th_id);
// Optimizer Stuff
void EnableProfilingInWorkers();
void DisableProfilingInWorkers();
void ComputeAverageSpeed();
bool profiling = true;
size_t maxProcesses = 0;
float averageTaskComputationTime = 0.0;
int sleepTimeMs = 1000;
std::chrono::system_clock::time_point lastOptTime;
std::chrono::system_clock::time_point lastPrintTime;
std::chrono::system_clock::time_point startTime;
std::chrono::system_clock::duration deltaTOpt;
std::chrono::system_clock::duration deltaTPrint;
// Printing stuff
size_t lastMsgLength = 0;
public:
void ReportAverageSpeed(float speed) ;
virtual size_t NumberOfCompletedTasks() const final;
virtual float Progress() const final;
};
#endif //SIMULATOR_THREADEDTASKPROCESSOR_HPP
| 27.577586
| 93
| 0.732416
|
PhilipVinc
|
bbd738324e4aa104eacdeb3a196245928d193a91
| 624
|
cpp
|
C++
|
HackerRank Solutions/C++/STL/Sets-STL.cpp
|
UtkarshPathrabe/Competitive-Coding
|
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
|
[
"MIT"
] | 13
|
2021-09-02T07:30:02.000Z
|
2022-03-22T19:32:03.000Z
|
HackerRank Solutions/C++/STL/Sets-STL.cpp
|
UtkarshPathrabe/Competitive-Coding
|
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
|
[
"MIT"
] | null | null | null |
HackerRank Solutions/C++/STL/Sets-STL.cpp
|
UtkarshPathrabe/Competitive-Coding
|
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
|
[
"MIT"
] | 3
|
2021-08-24T16:06:22.000Z
|
2021-09-17T15:39:53.000Z
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
set<int> Set;
set<int>::iterator it;
int Q, y, x;
scanf("%d", &Q);
for (int i = 0; i < Q; i++) {
scanf("%d %d", &y, &x);
if (y == 1) {
Set.insert(x);
} else if (y == 2) {
Set.erase(x);
} else if (y == 3) {
it = Set.find(x);
if (it == Set.end()) {
printf("No\n");
} else {
printf("Yes\n");
}
}
}
return 0;
}
| 19.5
| 34
| 0.400641
|
UtkarshPathrabe
|
bbdd1c2c1435f0fe5ac925a4c85998505813e3aa
| 53
|
cpp
|
C++
|
HttpFramework/HttpCookieStorage.cpp
|
a1q123456/HttpFramework
|
debefffbb1283ae0f0277cc1b597237933bb47f7
|
[
"MIT"
] | null | null | null |
HttpFramework/HttpCookieStorage.cpp
|
a1q123456/HttpFramework
|
debefffbb1283ae0f0277cc1b597237933bb47f7
|
[
"MIT"
] | null | null | null |
HttpFramework/HttpCookieStorage.cpp
|
a1q123456/HttpFramework
|
debefffbb1283ae0f0277cc1b597237933bb47f7
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "HttpCookieStorage.h"
| 10.6
| 30
| 0.735849
|
a1q123456
|
bbe130758cf8f984e00194113eb3eb9b908ba256
| 7,001
|
hpp
|
C++
|
include/CPreProcessor.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | null | null | null |
include/CPreProcessor.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | null | null | null |
include/CPreProcessor.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | 1
|
2019-06-11T03:41:48.000Z
|
2019-06-11T03:41:48.000Z
|
#ifndef CPREPROCESSOR_H
#define CPREPROCESSOR_H
#if !defined(BOOST_WAVE_CUSTOM_DIRECTIVES_HOOKS_INCLUDED)
#define BOOST_WAVE_CUSTOM_DIRECTIVES_HOOKS_INCLUDED
#include <cstdio>
#include <iostream>
#include <ostream>
#include <string>
#include <algorithm>
#include <utility>
#include <unordered_map>
#include <boost/algorithm/string.hpp>
#include <boost/assert.hpp>
#include <boost/config.hpp>
// Need to include this before other wave/phoenix includes
// @see https://groups.google.com/forum/#!msg/boost-list/3xZDWUyTJG0/IEF2wTy1EIsJ
#include <boost/phoenix/core/limits.hpp>
#include <boost/wave/token_ids.hpp>
#include <boost/wave/util/macro_helpers.hpp>
#include <boost/wave/preprocessing_hooks.hpp>
#include <boost/wave/cpp_iteration_context.hpp>
#include <iterator>
#include <fstream>
#if defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS)
#include <sstream>
#endif
#include <boost/wave/wave_config.hpp>
#include <boost/wave/cpp_exceptions.hpp>
#include <boost/wave/language_support.hpp>
#include <boost/wave/util/file_position.hpp>
#include "Types.hpp"
#include "fs/IFileSystem.hpp"
#include "logger/ILogger.hpp"
namespace wave = boost::wave;
namespace alg = boost::algorithm;
namespace ice_engine
{
/**
* This class is a generic pre processor for C like code.
*/
class CPreProcessor : public wave::context_policies::default_preprocessing_hooks
{
public:
CPreProcessor(fs::IFileSystem* fileSystem, logger::ILogger* logger, const std::unordered_map<std::string, std::string>& includeOverrides = {});
/**
* Processess the source code.
*
* @param defineMap this is an optional map that can contain any extra/special #defines that have been
* defined.
*/
std::string process(std::string source, const std::unordered_map<std::string, std::string>& defineMap = {}, const bool autoIncludeGuard = false, const bool preserveLineNumbers = false);
/* Below is a bunch of Boost Wave call-back functions */
template <typename ContextT, typename ContainerT>
bool found_unknown_directive(ContextT const& ctx, ContainerT const& line, ContainerT& pending);
template <typename ContextT, typename ContainerT>
bool emit_line_directive(ContextT const & ctx, ContainerT & pending, typename ContextT::token_type const & act_token);
template <typename ContextT>
bool locate_include_file(ContextT& ctx, std::string&file_path, bool is_system, char const*current_name, std::string&dir_path, std::string&native_name);
template <typename ContextT>
void opened_include_file(ContextT const& ctx, std::string const& relname, std::string const& filename, bool is_system_include);
template <typename ContextT>
void returning_from_include_file(ContextT const& ctx);
template <typename ContextT>
bool found_include_directive(ContextT const& ctx, std::string const& filename, bool include_next);
template <typename ContextT, typename TokenT>
void
skipped_token(ContextT const& ctx, TokenT const& token);
template <typename ContextT, typename TokenT>
TokenT const& generated_token(ContextT const &ctx, TokenT const& token);
template <typename ContextT, typename TokenT, typename ContainerT>
bool evaluated_conditional_expression(
ContextT const &ctx, TokenT const& directive,
ContainerT const& expression, bool expression_value);
template <typename ContextT, typename TokenT>
bool found_directive(ContextT const& ctx, TokenT const& directive);
/**
* Inner class to do the loading of a file.
*/
template <typename IterContextT>
class inner {
public:
template <typename PositionT>
static void init_iterators(IterContextT& iter_ctx, PositionT const& act_pos, wave::language_support language)
{
typedef typename IterContextT::iterator_type iterator_type;
// std::cout << "init_iterators: " << iter_ctx.filename << std::endl;
const auto filename = std::string(iter_ctx.filename.c_str());
{
const auto it = CPreProcessor::staticIncludeOverrides_.find(filename);
if (it != CPreProcessor::staticIncludeOverrides_.end())
{
iter_ctx.instring = it->second;
} else
{
iter_ctx.instring = CPreProcessor::staticFileSystem_->readAll(filename);
}
}
// read in the file
// std::ifstream instream(iter_ctx.filename.c_str());
// if ( !instream.is_open())
// {
//// BOOST_WAVE_THROW_CTX(iter_ctx.ctx, wave::preprocess_exception, wave::bad_include_file, iter_ctx.filename.c_str(), act_pos);
// return;
// }
// instream.unsetf(std::ios::skipws);
//
// iter_ctx.instring.assign(
// std::istreambuf_iterator<char>(instream.rdbuf()),
// std::istreambuf_iterator<char>()
// );
// ensure our input string ends with a newline (if we don't then boost wave generates a newline token after the include directive finishes)
auto it = iter_ctx.instring.end();
if (*(--it) != *boost::wave::get_token_value(boost::wave::T_NEWLINE))
{
iter_ctx.instring += boost::wave::get_token_value(boost::wave::T_NEWLINE);
}
iter_ctx.first = iterator_type(
iter_ctx.instring.begin(),
iter_ctx.instring.end(),
PositionT(iter_ctx.filename),
language
);
iter_ctx.last = iterator_type();
}
private:
std::string instring;
};
private:
protected:
bool preserveLineNumbers_ = false;
bool autoIncludeGuard_ = false;
uint32 conditionalDepth_ = 0;
uint32 conditionalAllowNewlineDepth_ = 0;
bool inDefine_ = false;
uint32 numIncludes_ = 0;
std::unordered_map<std::string, bool> includedFiles_;
std::unordered_map<std::string, std::string> includeOverrides_;
fs::IFileSystem* fileSystem_;
logger::ILogger* logger_;
static std::unordered_map<std::string, std::string> staticIncludeOverrides_;
static fs::IFileSystem* staticFileSystem_;
static logger::ILogger* staticLogger_;
/*
* We make this a shared pointer so that when the context object makes a copy of `this`,
* it will be using the same outputStringStream_.
*/
std::shared_ptr<std::stringstream> outputStringStream_;
bool locateIncludeFile(const std::string& currentDirectory, /*const std::string& basePath,*/ std::string& filePath, bool isSystem, char const* currentName, std::string& dirPath, std::string& nativeName);
std::string toCanonicalPath(const std::string& currentDirectory, const std::string& filename);
};
}
#include "CPreProcessor.inl"
#endif // !defined(BOOST_WAVE_ADVANCED_PREPROCESSING_HOOKS_INCLUDED)
#endif /* CPREPROCESSOR_H */
| 35.180905
| 207
| 0.682474
|
icebreakersentertainment
|
bbe2cb86a39c0e9f769e98353c3d5a8c69a8506b
| 920
|
cpp
|
C++
|
SE/Source/Maths/Vector4D.cpp
|
NahuCF/SE
|
6b17be4bc05b114a9090da35756a587693cc00e5
|
[
"WTFPL"
] | 1
|
2021-04-23T14:53:42.000Z
|
2021-04-23T14:53:42.000Z
|
SE/Source/Maths/Vector4D.cpp
|
NahuCF/SE
|
6b17be4bc05b114a9090da35756a587693cc00e5
|
[
"WTFPL"
] | null | null | null |
SE/Source/Maths/Vector4D.cpp
|
NahuCF/SE
|
6b17be4bc05b114a9090da35756a587693cc00e5
|
[
"WTFPL"
] | null | null | null |
#include "pch.h"
#include "Vector4D.h"
namespace lptm {
Vector4D::Vector4D()
{
x = 0.0f;
y = 0.0f;
z = 0.0f;
w = 0.0f;
};
Vector4D::Vector4D(float x, float y, float z, float w)
{
this->x = x;
this->y = y;
this->z = z;
this->w = w;
}
Vector4D& Vector4D::Add(const Vector4D& other)
{
x += other.x;
y += other.y;
z += other.z;
w += other.w;
return *this;
}
Vector4D& Vector4D::Multiply(const Vector4D& other)
{
return *this;
}
Vector4D Vector4D::operator+(const Vector4D& other)
{
return Vector4D(x + other.x, y + other.y, z + other.z, w + other.w);
}
Vector4D& Vector4D::operator+=(const Vector4D& other)
{
x += other.x;
y += other.y;
z += other.z;
w += other.w;
return *this;
}
Vector4D Vector4D::operator*(const Vector4D& other)
{
return Multiply(other);
}
Vector4D& Vector4D::operator*=(const Vector4D& other)
{
return Multiply(other);
}
}
| 14.83871
| 70
| 0.596739
|
NahuCF
|
bbe35a73de57f0577e102744972e21562c62f203
| 6,586
|
cpp
|
C++
|
cpp/src/msg_server/FileServConn.cpp
|
KevinHM/TTServer
|
c3a8dcb7e0d2dd0d3fc88ff919019ca5f0a81306
|
[
"Apache-2.0"
] | 22
|
2015-05-02T11:21:32.000Z
|
2022-03-04T09:58:19.000Z
|
cpp/src/msg_server/FileServConn.cpp
|
luyongfugx/TTServer
|
c3a8dcb7e0d2dd0d3fc88ff919019ca5f0a81306
|
[
"Apache-2.0"
] | null | null | null |
cpp/src/msg_server/FileServConn.cpp
|
luyongfugx/TTServer
|
c3a8dcb7e0d2dd0d3fc88ff919019ca5f0a81306
|
[
"Apache-2.0"
] | 21
|
2015-01-02T01:21:04.000Z
|
2021-05-12T09:52:54.000Z
|
//
// FileServConn.cpp
// public_TTServer
//
// Created by luoning on 14-8-19.
// Copyright (c) 2014年 luoning. All rights reserved.
//
#include "FileServConn.h"
#include "FileHandler.h"
#include "util.h"
#include "ImUser.h"
#include "AttachData.h"
#include "RouteServConn.h"
#include "MsgConn.h"
static ConnMap_t g_file_server_conn_map;
static serv_info_t* g_file_server_list;
static uint32_t g_file_server_count;
static CFileHandler* s_file_handler = NULL;
void file_server_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam)
{
ConnMap_t::iterator it_old;
CFileServConn* pConn = NULL;
uint64_t cur_time = get_tick_count();
for (ConnMap_t::iterator it = g_file_server_conn_map.begin(); it != g_file_server_conn_map.end();
)
{
it_old = it;
it++;
pConn = (CFileServConn*)it_old->second;
pConn->OnTimer(cur_time);
}
// reconnect FileServer
serv_check_reconnect<CFileServConn>(g_file_server_list, g_file_server_count);
}
void init_file_serv_conn(serv_info_t* server_list, uint32_t server_count)
{
g_file_server_list = server_list;
g_file_server_count = server_count;
serv_init<CFileServConn>(g_file_server_list, g_file_server_count);
netlib_register_timer(file_server_conn_timer_callback, NULL, 1000);
s_file_handler = CFileHandler::getInstance();
}
bool is_file_server_available()
{
CFileServConn* pConn = NULL;
for (uint32_t i = 0; i < g_file_server_count; i++) {
pConn = (CFileServConn*)g_file_server_list[i].serv_conn;
if (pConn && pConn->IsOpen()) {
return true;
}
}
return false;
}
//
CFileServConn* get_random_file_serv_conn()
{
CFileServConn* pConn = NULL;
CFileServConn* pConnTmp = NULL;
if (0 == g_file_server_count) {
return pConn;
}
int32_t random_num = rand() % g_file_server_count;
pConnTmp = (CFileServConn*)g_file_server_list[random_num].serv_conn;
if (pConnTmp && pConnTmp->IsOpen())
{
pConn = pConnTmp;
}
else
{
for (uint32_t i = 0; i < g_file_server_count; i++)
{
int j = (random_num + 1) % g_file_server_count;
pConnTmp = (CFileServConn*)g_file_server_list[j].serv_conn;
if (pConnTmp && pConnTmp->IsOpen())
{
pConn = pConnTmp;
}
}
}
return pConn;
}
CFileServConn::CFileServConn()
{
m_bOpen = false;
m_serv_idx = 0;
}
CFileServConn::~CFileServConn()
{
}
void CFileServConn::Connect(const char* server_ip, uint16_t server_port, uint32_t idx)
{
log("Connecting to FileServer %s:%d\n", server_ip, server_port);
m_serv_idx = idx;
m_handle = netlib_connect(server_ip, server_port, imconn_callback, (void*)&g_file_server_conn_map);
if (m_handle != NETLIB_INVALID_HANDLE) {
g_file_server_conn_map.insert(make_pair(m_handle, this));
}
}
void CFileServConn::Close()
{
serv_reset<CFileServConn>(g_file_server_list, g_file_server_count, m_serv_idx);
m_bOpen = false;
if (m_handle != NETLIB_INVALID_HANDLE) {
netlib_close(m_handle);
g_file_server_conn_map.erase(m_handle);
}
ReleaseRef();
}
void CFileServConn::OnConfirm()
{
log("connect to file server success\n");
m_bOpen = true;
m_connect_time = get_tick_count();
g_file_server_list[m_serv_idx].reconnect_cnt = MIN_RECONNECT_CNT / 2;
CImPduFileServerIPReq pdu;
//SendPdu(&pdu);
}
void CFileServConn::OnClose()
{
log("onclose from file server handle=%d\n", m_handle);
Close();
}
void CFileServConn::OnTimer(uint64_t curr_tick)
{
if (curr_tick > m_last_send_tick + SERVER_HEARTBEAT_INTERVAL) {
CImPduHeartbeat pdu;
SendPdu(&pdu);
}
if (curr_tick > m_last_recv_tick + SERVER_TIMEOUT) {
log("conn to file server timeout\n");
Close();
}
}
void CFileServConn::HandlePdu(CImPdu* pPdu)
{
switch (pPdu->GetPduType()) {
case IM_PDU_TYPE_HEARTBEAT:
break;
case IM_PDU_TYPE_MSG_FILE_TRANSFER_RSP:
_HandleFileMsgTransRsp((CImPduMsgFileTransferRsp*) pPdu);
break;
case IM_PDU_TYPE_FILE_SERVER_IP_REQUEST:
_HandleFileServerIPRsp((CImPduFileServerIPRsp*)pPdu);
break;
default:
log("unknown pdu_type=%d\n", pPdu->GetPduType());
break;
}
}
void CFileServConn::_HandleFileMsgTransRsp(CImPduMsgFileTransferRsp* pPdu)
{
uint32_t result = pPdu->GetResult();
uint32_t from_id = pPdu->GetFromId();
uint32_t to_id = pPdu->GetToId();
string file_name(pPdu->GetFileName(), pPdu->GetFileNameLength());
uint32_t file_size = pPdu->GetFileLength();
string listen_ip(pPdu->GetFileServerIp(), pPdu->GetFileServerIpLength());
uint16_t listen_port = pPdu->GetFileServerPort();
string task_id(pPdu->GetTaskId(), pPdu->GetTaskIdLen());
CPduAttachData attach(pPdu->GetAttachData(), pPdu->GetAttachLen());
CImPduClientFileResponse pdu(result, idtourl(from_id), idtourl(to_id), file_name.c_str(),
task_id.c_str(), listen_ip.c_str(), listen_port);
pdu.SetReserved(pPdu->GetReserved());
uint32_t handle = attach.GetHandle();
log("HandleFileMsgTransRsp, result: %u, from_user_id: %u, to_user_id: %u, file_name: %s, \
task_id: %s, listen_ip: %s, listen_port: %u.\n", result, from_id, to_id, file_name.c_str(),
task_id.c_str(), listen_ip.c_str(), listen_port);
CMsgConn* pFromConn = CImUserManager::GetInstance()->GetMsgConnByHandle(from_id, handle);
if (pFromConn)
{
pFromConn->SendPdu(&pdu);
}
if (result == 0)
{
//send notify to target user
CImUser* pToUser = CImUserManager::GetInstance()->GetImUserById(to_id);
if (pToUser)
{
CImPduClientFileNotify pdu2(idtourl(from_id), idtourl(to_id), file_name.c_str(), file_size,
task_id.c_str(), listen_ip.c_str(), listen_port);
pToUser->BroadcastPdu(&pdu2);
}
//send to route server
CRouteServConn* pRouteConn = get_route_serv_conn();
if (pRouteConn) {
CImPduFileNotify pdu3(from_id, to_id, file_name.c_str(), file_size, task_id.c_str(),
listen_ip.c_str(), listen_port);
pRouteConn->SendPdu(&pdu3);
}
}
}
void CFileServConn::_HandleFileServerIPRsp(CImPduFileServerIPRsp* pPdu)
{
uint32_t ip_addr_cnt = pPdu->GetIPCnt();
ip_addr_t* ip_addr_list = pPdu->GetIPList();
for (uint32_t i = 0; i < ip_addr_cnt ; i++) {
m_ip_list.push_back(ip_addr_list[i]);
}
}
| 28.387931
| 103
| 0.669602
|
KevinHM
|
bbeb3552b80935887cbfb333214abf80ac19950b
| 21,059
|
hpp
|
C++
|
polympc/src/solvers/admm.hpp
|
alexandreguerradeoliveira/rocket_gnc
|
164e96daca01d9edbc45bfaac0f6b55fe7324f24
|
[
"MIT"
] | null | null | null |
polympc/src/solvers/admm.hpp
|
alexandreguerradeoliveira/rocket_gnc
|
164e96daca01d9edbc45bfaac0f6b55fe7324f24
|
[
"MIT"
] | null | null | null |
polympc/src/solvers/admm.hpp
|
alexandreguerradeoliveira/rocket_gnc
|
164e96daca01d9edbc45bfaac0f6b55fe7324f24
|
[
"MIT"
] | null | null | null |
// This file is part of PolyMPC, a lightweight C++ template library
// for real-time nonlinear optimization and optimal control.
//
// Copyright (C) 2020 Listov Petr <petr.listov@epfl.ch>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef ADMM_HPP
#define ADMM_HPP
#include "qp_base.hpp"
template<int N, int M, typename Scalar = double, int MatrixType = DENSE,
template <typename, int, typename... Args> class LinearSolver = linear_solver_traits<DENSE>::default_solver,
int LinearSolver_UpLo = Eigen::Lower, typename ...Args>
class ADMM : public QPBase<ADMM<N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>, N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>
{
using Base = QPBase<ADMM<N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>, N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>;
public:
using scalar_t = typename Base::scalar_t;
using qp_var_t = typename Base::qp_var_t;
using qp_dual_t = typename Base::qp_dual_t;
using qp_dual_a_t = typename Base::qp_dual_a_t;
using qp_constraint_t = typename Base::qp_constraint_t;
using qp_hessian_t = typename Base::qp_hessian_t;
/** specific for OSQP splitting */
using kkt_mat_t = typename std::conditional<MatrixType == SPARSE, Eigen::SparseMatrix<scalar_t>,
typename dense_matrix_type_selector<scalar_t, 2 * N + M, 2 * N + M>::type>::type;
using kkt_vec_t = typename dense_matrix_type_selector<scalar_t, 2 * N + M, 1>::type;
using linear_solver_t = LinearSolver<kkt_mat_t, LinearSolver_UpLo, Args...>; //typename Base::linear_solver_t;
using admm_dual_t = typename dense_matrix_type_selector<scalar_t, N + M, 1>::type;
using admm_constraint_t = typename std::conditional<MatrixType == SPARSE, Eigen::SparseMatrix<scalar_t>,
typename dense_matrix_type_selector<scalar_t, N + M, N>::type>::type;
template<int MatrixFMT = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == DENSE>::type allocate_kkt_matrix() noexcept
{
if(m_K.RowsAtCompileTime == Eigen::Dynamic) m_K = kkt_mat_t::Zero(2 * N + M, 2 * N + M);
}
/** no pre-allocate needed for sparse KKT system */
template<int MatrixFMT = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == SPARSE>::type allocate_kkt_matrix() const noexcept
{}
template<int MatrixFMT = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == DENSE>::type allocate_jacobian() noexcept
{
if(m_A.RowsAtCompileTime == Eigen::Dynamic) m_A = admm_constraint_t::Zero(N + M, N);
}
template<int MatrixFMT = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == SPARSE>::type allocate_jacobian() const noexcept
{}
public:
ADMM() : Base()
{
/** intialise some variables */
m_rho_vec = admm_dual_t::Constant(this->m_settings.rho);
m_rho_inv_vec = admm_dual_t::Constant(scalar_t(1/this->m_settings.rho));
/** allocate space for the KKT matrix if necessary */
allocate_kkt_matrix();
/** allocate memory for Jacobian */
allocate_jacobian();
}
~ADMM() = default;
/** ADMM specific */
qp_var_t m_x_tilde;
admm_dual_t m_z, m_z_tilde, m_z_prev;
admm_dual_t m_rho_vec, m_rho_inv_vec;
scalar_t rho;
int iter{0};
scalar_t res_prim;
scalar_t res_dual;
/** ADMM specific */
static constexpr scalar_t RHO_MIN = 1e-6;
static constexpr scalar_t RHO_MAX = 1e+6;
static constexpr scalar_t RHO_TOL = 1e-4;
static constexpr scalar_t RHO_EQ_FACTOR = 1e+3;
/** ADMM specific */
scalar_t m_max_Ax_z_norm;
scalar_t m_max_Hx_ATy_h_norm;
/** solver part */
kkt_mat_t m_K;
admm_constraint_t m_A;
linear_solver_t linear_solver;
Eigen::VectorXi _kkt_mat_nnz, _A_mat_nnz;
status_t solve_impl(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const qp_var_t>& h, const Eigen::Ref<const qp_constraint_t>& A,
const Eigen::Ref<const qp_dual_a_t>& Alb, const Eigen::Ref<const qp_dual_a_t>& Aub,
const Eigen::Ref<const qp_var_t>& xl, const Eigen::Ref<const qp_var_t>& xu) noexcept
{
return solve_impl(H, h, A, Alb, Aub, xl, xu, qp_var_t::Zero(N,1), qp_dual_t::Zero(M+N,1));
}
status_t solve_impl(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const qp_var_t>& h, const Eigen::Ref<const qp_constraint_t>& A,
const Eigen::Ref<const qp_dual_a_t>& Alb, const Eigen::Ref<const qp_dual_a_t>& Aub,
const Eigen::Ref<const qp_var_t>& xl, const Eigen::Ref<const qp_var_t>& xu,
const Eigen::Ref<const qp_var_t>& x_guess, const Eigen::Ref<const qp_dual_t>& y_guess) noexcept
{
/** setup part */
kkt_vec_t rhs, x_tilde_nu;
bool check_termination = false;
this->m_x = x_guess;
this->m_y = y_guess;
/** @bug : create Sparse m_A matrix */
construct_A(A);
this->m_z.noalias() = m_A * x_guess;
/** Set QP constraint type */
this->parse_constraints_bounds(Alb, Aub, xl, xu);
/** initialize step size (rho) vector */
rho_vec_update(this->m_settings.rho);
/** construct KKT matrix (m_K) and compute decomposition */
construct_kkt_matrix(H, m_A);
factorise_kkt_matrix();
this->m_info.status = UNSOLVED;
/** run ADMM iterations */
for (iter = 1; iter <= this->m_settings.max_iter; iter++)
{
m_z_prev = m_z;
/** update x_tilde z_tilde */
compute_kkt_rhs(h, rhs);
x_tilde_nu = linear_solver.solve(rhs);
m_x_tilde = x_tilde_nu.template head<N>();
m_z_tilde = m_z_prev + m_rho_inv_vec.cwiseProduct(x_tilde_nu.template tail<M + N>() - this->m_y);
/** update x */
this->m_x.noalias() = this->m_settings.alpha * m_x_tilde + (1 - this->m_settings.alpha) * this->m_x;
/** update z */
m_z.noalias() = this->m_settings.alpha * m_z_tilde;
m_z.noalias() += (1 - this->m_settings.alpha) * m_z_prev + m_rho_inv_vec.cwiseProduct(this->m_y);
box_projection(m_z, Alb, Aub, xl, xu); // euclidean projection
/** update y (dual) */
this->m_y.noalias() += m_rho_vec.cwiseProduct(this->m_settings.alpha * m_z_tilde +
(1 - this->m_settings.alpha) * m_z_prev - m_z);
if (this->m_settings.check_termination != 0 && iter % this->m_settings.check_termination == 0)
check_termination = true;
else
check_termination = false;
/** check convergence */
if (check_termination)
{
residuals_update(H, h, A);
if (termination_criteria())
{
this->m_info.status = SOLVED;
break;
}
}
if (this->m_settings.adaptive_rho && iter % this->m_settings.adaptive_rho_interval == 0)
{
// state was not yet updated
if (!check_termination)
residuals_update(H, h, A);
/** adjust rho value and refactorise the KKT matrix */
scalar_t new_rho = estimate_rho(rho);
new_rho = fmax(RHO_MIN, fmin(new_rho, RHO_MAX));
this->m_info.rho_estimate = new_rho;
if (new_rho < rho / this->m_settings.adaptive_rho_tolerance ||
new_rho > rho * this->m_settings.adaptive_rho_tolerance)
{
rho_vec_update(new_rho);
update_kkt_rho();
/* Note: KKT Sparsity pattern unchanged by rho update. Only factorize. */
factorise_kkt_matrix();
}
}
/**
std::cout << "admm iter: " << iter << " | " << this->m_x.transpose() << " | " << this->m_y.transpose() <<
" | " << this->m_info.res_prim << " | " << this->m_info.res_dual << " | " << m_rho_vec.transpose() << "\n";
*/
}
if (iter > this->m_settings.max_iter)
this->m_info.status = MAX_ITER_EXCEEDED;
this->m_info.iter = iter;
return this->m_info.status;
}
/** construct extended A matrix: Ae = [A E] */
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == DENSE>::type
construct_A(const Eigen::Ref<const qp_constraint_t>& A) noexcept
{
m_A.template block<M, N>(0,0) = A;
m_A.template block<N,N>(M,0).setIdentity();
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
construct_A(const Eigen::Ref<const qp_constraint_t>& A) noexcept
{
if(this->settings().reuse_pattern)
{
/** copy the new A block */
for(Eigen::Index k = 0; k < N; ++k)
std::copy_n(A.valuePtr() + A.outerIndexPtr()[k], A.innerNonZeroPtr()[k], m_A.valuePtr() + m_A.outerIndexPtr()[k]);
}
else
{
m_A.resize(N + M, N);
_A_mat_nnz = Eigen::VectorXi::Constant(N, 1); // allocate box constraints
std::transform(_A_mat_nnz.data(), _A_mat_nnz.data() + N, A.innerNonZeroPtr(), _A_mat_nnz.data(), std::plus<scalar_t>());
// reserve the memory
m_A.reserve(_A_mat_nnz);
block_insert_sparse(m_A, 0, 0, A); //insert A matrix
for(Eigen::Index i = 0; i < N; ++i)
m_A.coeffRef(i + M, i) = scalar_t(1); // insert identity matrix
}
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == DENSE>::type
construct_kkt_matrix(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept
{
eigen_assert(LinearSolver_UpLo == Eigen::Lower ||
LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower));
m_K.template topLeftCorner<N, N>() = H;
m_K.template topLeftCorner<N, N>().diagonal() += qp_var_t::Constant(N, this->m_settings.sigma);
if (LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower))
m_K.template topRightCorner<N, M + N>() = A.transpose();
m_K.template bottomLeftCorner<M + N, N>() = A;
m_K.template bottomRightCorner<M + N, M + N>() = scalar_t(-1) * m_rho_inv_vec.asDiagonal();
}
/** sparse implementation */
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
construct_kkt_matrix(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept
{
if(this->settings().reuse_pattern)
construct_kkt_matrix_same_pattern(H,A);
else
{
construct_kkt_matrix_sparse(H, A);
linear_solver.analyzePattern(m_K);
}
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
construct_kkt_matrix_sparse(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept
{
/** worst case scenario */
const int kkt_size = 2 * N + M;
m_K.resize(kkt_size, kkt_size);
/** estimate number of nonzeros */
_kkt_mat_nnz = Eigen::VectorXi::Constant(kkt_size, 1);
// add nonzeros from H
std::transform(_kkt_mat_nnz.data(), _kkt_mat_nnz.data() + N, H.innerNonZeroPtr(), _kkt_mat_nnz.data(), std::plus<scalar_t>());
// add nonzeros from A
std::transform(_kkt_mat_nnz.data(), _kkt_mat_nnz.data() + N, A.innerNonZeroPtr(), _kkt_mat_nnz.data(), std::plus<scalar_t>());
// reserve the space and insert values from H and A
if(LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower))
{
// reserve more memory
_estimate_nnz_in_row(_kkt_mat_nnz, A);
m_K.reserve(_kkt_mat_nnz);
block_insert_sparse(m_K, 0, 0, H);
block_insert_sparse(m_K, N, 0, A);
block_insert_sparse(m_K, 0, N, A.transpose());
}
else
{
m_K.reserve(_kkt_mat_nnz);
block_insert_sparse(m_K, 0, 0, H);
block_insert_sparse(m_K, N, 0, A);
}
// add diagonal blocks*/
for(Eigen::Index i = 0; i < N; ++i)
m_K.coeffRef(i, i) += this->m_settings.sigma;
for(Eigen::Index i = 0; i < N + M; ++i)
m_K.coeffRef(N + i, N + i) = -m_rho_inv_vec(i);
}
/** make faster update if sparsity pattern has not changed */
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
construct_kkt_matrix_same_pattern(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept
{
/** just copy content of nonzero vectors*/
// copy H and A blocks
for(Eigen::Index k = 0; k < N; ++k)
{
std::copy_n(H.valuePtr() + H.outerIndexPtr()[k], H.innerNonZeroPtr()[k], m_K.valuePtr() + m_K.outerIndexPtr()[k]);
std::copy_n(A.valuePtr() + A.outerIndexPtr()[k], A.innerNonZeroPtr()[k], m_K.valuePtr() + m_K.outerIndexPtr()[k] + H.innerNonZeroPtr()[k]);
}
// reserve the space and insert values from H and A
if(LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower))
block_set_sparse(m_K, N, 0, A.transpose());
// add diagonal blocks*/
m_K.diagonal(). template head<N>() += qp_var_t::Constant(this->m_settings.sigma);
m_K.diagonal(). template tail<M + N>() = -m_rho_inv_vec;
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
block_insert_sparse(Eigen::SparseMatrix<scalar_t>& dst, const Eigen::Index &row_offset,
const Eigen::Index &col_offset, const Eigen::SparseMatrix<scalar_t>& src) const noexcept
{
// assumes enough spase is allocated in the dst matrix
for(Eigen::Index k = 0; k < src.outerSize(); ++k)
for (typename Eigen::SparseMatrix<scalar_t>::InnerIterator it(src, k); it; ++it)
dst.insert(row_offset + it.row(), col_offset + it.col()) = it.value();
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
block_set_sparse(Eigen::SparseMatrix<scalar_t>& dst, const Eigen::Index &row_offset,
const Eigen::Index &col_offset, const Eigen::SparseMatrix<scalar_t>& src) const noexcept
{
// assumes enough spase is allocated in the dst matrix
for(Eigen::Index k = 0; k < src.outerSize(); ++k)
for (typename Eigen::SparseMatrix<scalar_t>::InnerIterator it(src, k); it; ++it)
dst.insert(row_offset + it.row(), col_offset + it.col()) = it.value();
}
/** workaround function to estimate number of nonzeros */
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
_estimate_nnz_in_row(Eigen::Ref<Eigen::VectorXi> nnz, const qp_constraint_t& A) const noexcept
{
for (Eigen::Index k = 0; k < A.outerSize(); ++k)
for(typename qp_constraint_t::InnerIterator it(A, k); it; ++it)
nnz(it.row() + N) += scalar_t(1);
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == DENSE>::type factorise_kkt_matrix() noexcept
{
/** try implace decomposition */
linear_solver.compute(m_K);
eigen_assert(linear_solver.info() == Eigen::Success);
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type factorise_kkt_matrix() noexcept
{
/** try implace decomposition */
linear_solver.factorize(m_K);
eigen_assert(linear_solver.info() == Eigen::Success);
}
EIGEN_STRONG_INLINE void compute_kkt_rhs(const Eigen::Ref<const qp_var_t>& h, Eigen::Ref<kkt_vec_t> rhs) const noexcept
{
rhs.template head<N>() = this->m_settings.sigma * this->m_x - h;
rhs.template tail<M + N>() = m_z - m_rho_inv_vec.cwiseProduct(this->m_y);
}
EIGEN_STRONG_INLINE void box_projection(Eigen::Ref<admm_dual_t> x, const Eigen::Ref<const qp_dual_a_t>& lba,
const Eigen::Ref<const qp_dual_a_t>& uba,
const Eigen::Ref<const qp_var_t>& lbx, const Eigen::Ref<const qp_var_t>& ubx) const noexcept
{
x.template head<M>() = x.template head<M>().cwiseMax(lba).cwiseMin(uba);
x.template tail<N>() = x.template tail<N>().cwiseMax(lbx).cwiseMin(ubx);
}
EIGEN_STRONG_INLINE void rho_vec_update(const scalar_t& rho0) noexcept
{
for (int i = 0; i < qp_dual_a_t::RowsAtCompileTime; i++)
{
switch (this->constr_type[i])
{
case Base::constraint_type::LOOSE_BOUNDS:
m_rho_vec(i) = RHO_MIN;
break;
case Base::constraint_type::EQUALITY_CONSTRAINT:
m_rho_vec(i) = RHO_EQ_FACTOR * rho0;
break;
case Base::constraint_type::INEQUALITY_CONSTRAINT: /* fall through */
default:
m_rho_vec(i) = rho0;
};
}
/** box constraints */
for (int i = 0; i < qp_var_t::RowsAtCompileTime; i++)
{
switch (this->box_constr_type[i])
{
case Base::constraint_type::LOOSE_BOUNDS:
m_rho_vec(i + M) = RHO_MIN;
break;
case Base::constraint_type::EQUALITY_CONSTRAINT:
m_rho_vec(i + M) = RHO_EQ_FACTOR * rho0;
break;
case Base::constraint_type::INEQUALITY_CONSTRAINT: /* fall through */
default:
m_rho_vec(i + M) = rho0;
};
}
m_rho_inv_vec = m_rho_vec.cwiseInverse();
rho = rho0;
this->m_info.rho_updates += 1;
}
void residuals_update(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const qp_var_t>& h,
const Eigen::Ref<const qp_constraint_t>& A) noexcept
{
scalar_t norm_Ax, norm_z;
norm_Ax = (A * this->m_x).template lpNorm<Eigen::Infinity>();
norm_Ax = fmax(norm_Ax, this->m_x.template tail<N>().template lpNorm<Eigen::Infinity>());
norm_z = m_z.template lpNorm<Eigen::Infinity>();
m_max_Ax_z_norm = fmax(norm_Ax, norm_z);
scalar_t norm_Hx, norm_ATy, norm_h, norm_y_box;
norm_Hx = (H * this->m_x).template lpNorm<Eigen::Infinity>();
norm_ATy = (this->m_y.template head<M>().transpose() * A).template lpNorm<Eigen::Infinity>();
norm_h = h.template lpNorm<Eigen::Infinity>();
norm_y_box = this->m_y.template tail<N>().template lpNorm<Eigen::Infinity>();
m_max_Hx_ATy_h_norm = fmax(norm_Hx, fmax(norm_ATy, fmax(norm_h, norm_y_box)));
this->m_info.res_prim = this->primal_residual(A, this->m_x, m_z.template head<M>());
scalar_t box_norm = (this->m_x - m_z.template tail<N>()).template lpNorm<Eigen::Infinity>();
this->m_info.res_prim = fmax(this->m_info.res_prim, box_norm);
this->m_info.res_dual = this->dual_residual(H, h, A, this->m_x, this->m_y);
}
EIGEN_STRONG_INLINE scalar_t eps_prim() const noexcept
{
return this->m_settings.eps_abs + this->m_settings.eps_rel * m_max_Ax_z_norm;
}
EIGEN_STRONG_INLINE scalar_t eps_dual() const noexcept
{
return this->m_settings.eps_abs + this->m_settings.eps_rel * m_max_Hx_ATy_h_norm;
}
EIGEN_STRONG_INLINE bool termination_criteria() const noexcept
{
// check residual norms to detect optimality
return (this->m_info.res_prim <= eps_prim() && this->m_info.res_dual <= eps_dual()) ? true : false;
}
EIGEN_STRONG_INLINE scalar_t estimate_rho(const scalar_t& rho0) const noexcept
{
scalar_t rp_norm, rd_norm;
rp_norm = this->m_info.res_prim / (m_max_Ax_z_norm + this->DIV_BY_ZERO_REGUL);
rd_norm = this->m_info.res_dual / (m_max_Hx_ATy_h_norm + this->DIV_BY_ZERO_REGUL);
scalar_t rho_new = rho0 * sqrt(rp_norm / (rd_norm + this->DIV_BY_ZERO_REGUL));
return rho_new;
}
EIGEN_STRONG_INLINE void update_kkt_rho() noexcept
{
m_K.diagonal(). template tail<N + M>() = -m_rho_inv_vec;
//m_K.template bottomRightCorner<M + N, M + N>() = -1.0 * m_rho_inv_vec.asDiagonal();
}
};
#endif // ADMM_HPP
| 41.373281
| 151
| 0.605632
|
alexandreguerradeoliveira
|
bbeee5ce3406395fe23c446204cec8e2508686a3
| 2,495
|
cc
|
C++
|
chrome/renderer/plugins/pdf_plugin_placeholder.cc
|
zipated/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 2,151
|
2020-04-18T07:31:17.000Z
|
2022-03-31T08:39:18.000Z
|
chrome/renderer/plugins/pdf_plugin_placeholder.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 395
|
2020-04-18T08:22:18.000Z
|
2021-12-08T13:04:49.000Z
|
chrome/renderer/plugins/pdf_plugin_placeholder.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 338
|
2020-04-18T08:03:10.000Z
|
2022-03-29T12:33:22.000Z
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/plugins/pdf_plugin_placeholder.h"
#include "chrome/common/pdf_uma.h"
#include "chrome/common/render_messages.h"
#include "chrome/grit/renderer_resources.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/renderer/render_thread.h"
#include "gin/object_template_builder.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/jstemplate_builder.h"
#include "ui/base/webui/web_ui_util.h"
gin::WrapperInfo PDFPluginPlaceholder::kWrapperInfo = {gin::kEmbedderNativeGin};
PDFPluginPlaceholder::PDFPluginPlaceholder(content::RenderFrame* render_frame,
const blink::WebPluginParams& params,
const std::string& html_data)
: plugins::PluginPlaceholderBase(render_frame, params, html_data) {}
PDFPluginPlaceholder::~PDFPluginPlaceholder() {}
PDFPluginPlaceholder* PDFPluginPlaceholder::CreatePDFPlaceholder(
content::RenderFrame* render_frame,
const blink::WebPluginParams& params) {
std::string template_html = ui::ResourceBundle::GetSharedInstance()
.GetRawDataResource(IDR_PDF_PLUGIN_HTML)
.as_string();
webui::AppendWebUiCssTextDefaults(&template_html);
base::DictionaryValue values;
values.SetString("fileName", GURL(params.url).ExtractFileName());
values.SetString("open", l10n_util::GetStringUTF8(IDS_ACCNAME_OPEN));
std::string html_data = webui::GetI18nTemplateHtml(template_html, &values);
return new PDFPluginPlaceholder(render_frame, params, html_data);
}
v8::Local<v8::Value> PDFPluginPlaceholder::GetV8Handle(v8::Isolate* isolate) {
return gin::CreateHandle(isolate, this).ToV8();
}
gin::ObjectTemplateBuilder PDFPluginPlaceholder::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin::Wrappable<PDFPluginPlaceholder>::GetObjectTemplateBuilder(isolate)
.SetMethod<void (PDFPluginPlaceholder::*)()>(
"openPDF", &PDFPluginPlaceholder::OpenPDFCallback);
}
void PDFPluginPlaceholder::OpenPDFCallback() {
ReportPDFLoadStatus(PDFLoadStatus::kViewPdfClickedInPdfPluginPlaceholder);
content::RenderThread::Get()->Send(
new ChromeViewHostMsg_OpenPDF(routing_id(), GetPluginParams().url));
}
| 42.288136
| 80
| 0.739479
|
zipated
|
bbeee88e430aeae5c0b205f0569d88271a17eb23
| 5,730
|
cpp
|
C++
|
Remixed/CompositorBase.cpp
|
LukeRoss00/Revive
|
09b1c59dfbff8abc06194809ec680b990b2cf21c
|
[
"MIT"
] | 1
|
2021-10-18T19:43:06.000Z
|
2021-10-18T19:43:06.000Z
|
Remixed/CompositorBase.cpp
|
LukeRoss00/Revive
|
09b1c59dfbff8abc06194809ec680b990b2cf21c
|
[
"MIT"
] | null | null | null |
Remixed/CompositorBase.cpp
|
LukeRoss00/Revive
|
09b1c59dfbff8abc06194809ec680b990b2cf21c
|
[
"MIT"
] | 1
|
2020-02-03T22:45:41.000Z
|
2020-02-03T22:45:41.000Z
|
#include "CompositorBase.h"
#include "Session.h"
#include "FrameList.h"
#include "OVR_CAPI.h"
#include "microprofile.h"
#include <vector>
#include <algorithm>
#include <winrt/Windows.Graphics.Holographic.h>
using namespace winrt::Windows::Graphics::Holographic;
MICROPROFILE_DEFINE(WaitToBeginFrame, "Compositor", "WaitFrame", 0x00ff00);
MICROPROFILE_DEFINE(BeginFrame, "Compositor", "BeginFrame", 0x00ff00);
MICROPROFILE_DEFINE(EndFrame, "Compositor", "EndFrame", 0x00ff00);
MICROPROFILE_DEFINE(SubmitFovLayer, "Compositor", "SubmitFovLayer", 0x00ff00);
CompositorBase::CompositorBase()
: m_MirrorTexture(nullptr)
, m_ChainCount(0)
{
}
CompositorBase::~CompositorBase()
{
if (m_MirrorTexture)
delete m_MirrorTexture;
}
ovrResult CompositorBase::CreateTextureSwapChain(const ovrTextureSwapChainDesc* desc, ovrTextureSwapChain* out_TextureSwapChain)
{
ovrTextureSwapChain swapChain = new ovrTextureSwapChainData(*desc);
swapChain->Identifier = m_ChainCount++;
for (int i = 0; i < swapChain->Length; i++)
{
TextureBase* texture = CreateTexture();
bool success = texture->Init(desc->Type, desc->Width, desc->Height, desc->MipLevels,
desc->ArraySize, desc->Format, desc->MiscFlags, desc->BindFlags);
if (!success)
return ovrError_RuntimeException;
swapChain->Textures[i].reset(texture);
}
*out_TextureSwapChain = swapChain;
return ovrSuccess;
}
ovrResult CompositorBase::CreateMirrorTexture(const ovrMirrorTextureDesc* desc, ovrMirrorTexture* out_MirrorTexture)
{
// There can only be one mirror texture at a time
if (m_MirrorTexture)
return ovrError_RuntimeException;
// TODO: Support ovrMirrorOptions
ovrMirrorTexture mirrorTexture = new ovrMirrorTextureData(*desc);
TextureBase* texture = CreateTexture();
bool success = texture->Init(ovrTexture_2D, desc->Width, desc->Height, 1, 1, desc->Format,
desc->MiscFlags | ovrTextureMisc_AllowGenerateMips, ovrTextureBind_DX_RenderTarget);
if (!success)
return ovrError_RuntimeException;
mirrorTexture->Texture.reset(texture);
m_MirrorTexture = mirrorTexture;
*out_MirrorTexture = mirrorTexture;
return ovrSuccess;
}
ovrResult CompositorBase::WaitToBeginFrame(ovrSession session, long long frameIndex)
{
MICROPROFILE_SCOPE(WaitToBeginFrame);
session->Frames->GetFrame(frameIndex).WaitForFrameToFinish();
session->Frames->PopFrame(frameIndex);
return ovrSuccess;
}
ovrResult CompositorBase::BeginFrame(ovrSession session, long long frameIndex)
{
MICROPROFILE_SCOPE(BeginFrame);
session->CurrentFrame = session->Frames->GetFrame(frameIndex);
return ovrSuccess;
}
ovrResult CompositorBase::EndFrame(ovrSession session, long long frameIndex, ovrLayerHeader const * const * layerPtrList, unsigned int layerCount)
{
MICROPROFILE_SCOPE(EndFrame);
if (layerCount == 0 || !layerPtrList)
return ovrError_InvalidParameter;
// Flush all pending draw calls.
Flush();
ovrLayerEyeFov baseLayer;
bool baseLayerFound = false;
for (uint32_t i = 0; i < layerCount; i++)
{
if (layerPtrList[i] == nullptr)
continue;
// TODO: Support ovrLayerType_Quad, ovrLayerType_Cylinder and ovrLayerType_Cube
if (layerPtrList[i]->Type == ovrLayerType_EyeFov ||
layerPtrList[i]->Type == ovrLayerType_EyeFovDepth ||
layerPtrList[i]->Type == ovrLayerType_EyeFovMultires)
{
ovrLayerEyeFov* layer = (ovrLayerEyeFov*)layerPtrList[i];
SubmitFovLayer(session, frameIndex, layer);
baseLayerFound = true;
}
else if (layerPtrList[i]->Type == ovrLayerType_EyeMatrix)
{
ovrLayerEyeFov layer = ToFovLayer((ovrLayerEyeMatrix*)layerPtrList[i]);
SubmitFovLayer(session, frameIndex, &layer);
baseLayerFound = true;
}
}
HolographicFrame frame = session->Frames->GetFrame(frameIndex);
HolographicFramePrediction prediction = frame.CurrentPrediction();
HolographicCameraPose pose = prediction.CameraPoses().GetAt(0);
HolographicCamera cam = pose.HolographicCamera();
//cam.IsPrimaryLayerEnabled(baseLayerFound);
HolographicFramePresentResult result = frame.PresentUsingCurrentPrediction(HolographicFramePresentWaitBehavior::DoNotWaitForFrameToFinish);
if (result == HolographicFramePresentResult::DeviceRemoved)
return ovrError_DisplayLost;
// TODO: Mirror textures
//if (m_MirrorTexture && success)
// RenderMirrorTexture(m_MirrorTexture);
MicroProfileFlip();
return ovrSuccess;
}
ovrLayerEyeFov CompositorBase::ToFovLayer(ovrLayerEyeMatrix* matrix)
{
ovrLayerEyeFov layer = { ovrLayerType_EyeFov };
layer.Header.Flags = matrix->Header.Flags;
layer.SensorSampleTime = matrix->SensorSampleTime;
for (int i = 0; i < ovrEye_Count; i++)
{
layer.Fov[i].LeftTan = layer.Fov[i].RightTan = .5f / matrix->Matrix[i].M[0][0];
layer.Fov[i].UpTan = layer.Fov[i].DownTan = -.5f / matrix->Matrix[i].M[1][1];
layer.ColorTexture[i] = matrix->ColorTexture[i];
layer.Viewport[i] = matrix->Viewport[i];
layer.RenderPose[i] = matrix->RenderPose[i];
}
return layer;
}
void CompositorBase::SubmitFovLayer(ovrSession session, long long frameIndex, ovrLayerEyeFov* fovLayer)
{
MICROPROFILE_SCOPE(SubmitFovLayer);
ovrTextureSwapChain swapChain[ovrEye_Count] = {
fovLayer->ColorTexture[ovrEye_Left],
fovLayer->ColorTexture[ovrEye_Right]
};
// If the right eye isn't set use the left eye for both
if (!swapChain[ovrEye_Right])
swapChain[ovrEye_Right] = swapChain[ovrEye_Left];
// Submit the scene layer.
for (int i = 0; i < ovrEye_Count; i++)
{
RenderTextureSwapChain(session, frameIndex, (ovrEyeType)i, swapChain[i], fovLayer->Viewport[i]);
}
swapChain[ovrEye_Left]->Submit();
if (swapChain[ovrEye_Left] != swapChain[ovrEye_Right])
swapChain[ovrEye_Right]->Submit();
}
void CompositorBase::SetMirrorTexture(ovrMirrorTexture mirrorTexture)
{
m_MirrorTexture = mirrorTexture;
}
| 30.478723
| 146
| 0.766492
|
LukeRoss00
|
bbf56d131e20fcbaf358a4c5a8f8f0ff091d0bc7
| 1,522
|
hpp
|
C++
|
SCLT/Color/CIEColorSpaces/CIEUCS.hpp
|
chicio/Multispectral-Ray-tracing
|
ea5b399770eddd1927aae8a8ae4640dead42c48c
|
[
"MIT"
] | 95
|
2016-05-05T10:46:49.000Z
|
2021-12-20T12:51:41.000Z
|
SCLT/Color/CIEColorSpaces/CIEUCS.hpp
|
chicio/Multispectral-Ray-tracing
|
ea5b399770eddd1927aae8a8ae4640dead42c48c
|
[
"MIT"
] | 1
|
2021-12-06T03:21:32.000Z
|
2021-12-06T03:21:32.000Z
|
SCLT/Color/CIEColorSpaces/CIEUCS.hpp
|
chicio/Multispectral-Ray-tracing
|
ea5b399770eddd1927aae8a8ae4640dead42c48c
|
[
"MIT"
] | 8
|
2017-03-12T03:04:08.000Z
|
2022-03-17T01:27:41.000Z
|
//
// CIE1960UCS.hpp
// Spectral Clara Lux tracer
//
// Created by Fabrizio Duroni on 24/12/15.
// Copyright © 2015 Fabrizio Duroni. All rights reserved.
//
#ifndef CIE1960UCS_hpp
#define CIE1960UCS_hpp
#include "Vector3D.hpp"
struct CIEUCSChromaticities {
/// u coordinate.
float u;
/// v coordinate
float v;
/*!
Constructor that init a CIE1960UCSChromaticities object.
@param u u coordinate.
@param v v coordinate.
*/
CIEUCSChromaticities(float u, float v) : u{u}, v{v} {};
};
class CIEUCS {
public:
/*!
Convert CIE XYZ chromaticity values to CIE UCS 1960 chromaticity values.
@param tristimulusChromaticity CIE XYZ tristimulus chromaticity coordinate.
@returns CIE 1960 chromaticity values.
*/
static CIEUCSChromaticities chromaticity(const Vector3D& tristimulusChromaticity);
/*!
Convert CIE XYZ tristimulus values to CIE UCS 1960 chromaticity values.
@param tristilusValues CIE XYZ tristimulus values.
@returns CIE 1960 chromaticity values.
*/
static CIEUCSChromaticities chromaticityFromTristimulus(const Vector3D& tristimulusValues);
/*!
Calculate CIE 1960 chromaticity values using color correleated temperature (CCT).
Useful for black body chromaticity calculation.
@param CCT black body temperature.
@returns
*/
static CIEUCSChromaticities chromaticityForBlackBodyUsingCCT(float CCT);
};
#endif /* CIEUCS_hpp */
| 24.15873
| 95
| 0.685283
|
chicio
|
bbfc733ec98b5bbb144bd301d8aee1e9761dbbfa
| 689
|
cpp
|
C++
|
ITP2/ITP2_5_D.cpp
|
felixny/AizuOnline
|
8ff399d60077e08961845502d4a99244da580cd2
|
[
"MIT"
] | null | null | null |
ITP2/ITP2_5_D.cpp
|
felixny/AizuOnline
|
8ff399d60077e08961845502d4a99244da580cd2
|
[
"MIT"
] | null | null | null |
ITP2/ITP2_5_D.cpp
|
felixny/AizuOnline
|
8ff399d60077e08961845502d4a99244da580cd2
|
[
"MIT"
] | null | null | null |
// ITP2_5_D
#include <algorithm>
#include <iostream>
#include <numeric>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
iota(v.begin(), v.end(), 1);
do {
for (int i = 0; i < n; i++) { // cout<<(i?" ":"")<<v[i];
if (i) { // zero is used to represent false so the first value i = 0 is
// always false which prints no empty string. ""
cout << " [value i: ]" << i;
cout << " " << v[i];
} else {
cout << "" << v[i];
cout << " [value i: ]" << i;
}
}
cout << endl;
} while (next_permutation(v.begin(), v.end()));
return 0;
}
| 22.225806
| 78
| 0.489115
|
felixny
|
bbfc9a10011ebe085ef224beb130ea6fdfc7f0f2
| 3,204
|
hpp
|
C++
|
src/core/RegionHash.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | null | null | null |
src/core/RegionHash.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | null | null | null |
src/core/RegionHash.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | 1
|
2021-07-21T06:48:19.000Z
|
2021-07-21T06:48:19.000Z
|
// Copyright (c) 2020 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)
#ifndef OVK_CORE_REGION_HASH_HPP_INCLUDED
#define OVK_CORE_REGION_HASH_HPP_INCLUDED
#include <ovk/core/Array.hpp>
#include <ovk/core/ArrayView.hpp>
#include <ovk/core/Box.hpp>
#include <ovk/core/Field.hpp>
#include <ovk/core/Global.hpp>
#include <ovk/core/HashableRegionTraits.hpp>
#include <ovk/core/Math.hpp>
#include <ovk/core/Range.hpp>
#include <ovk/core/Set.hpp>
#include <ovk/core/Tuple.hpp>
#include <cmath>
#include <memory>
#include <type_traits>
#include <utility>
namespace ovk {
namespace core {
template <typename RegionType> class region_hash {
public:
static_assert(IsHashableRegion<RegionType>(), "Invalid region type (not hashable).");
using region_type = RegionType;
using region_traits = hashable_region_traits<region_type>;
using coord_type = typename region_traits::coord_type;
static_assert(std::is_same<coord_type, int>::value || std::is_same<coord_type, double>::value,
"Coord type must be int or double.");
using extents_type = interval<coord_type,MAX_DIMS>;
explicit region_hash(int NumDims);
region_hash(int NumDims, const tuple<int> &NumBins, array_view<const region_type> Regions);
long long MapToBin(const tuple<coord_type> &Point) const;
array_view<const long long> RetrieveBin(long long iBin) const;
int Dimension() const { return NumDims_; }
const range &BinRange() const { return BinRange_; }
const extents_type &Extents() const { return Extents_; }
private:
int NumDims_;
range BinRange_;
field_indexer BinIndexer_;
extents_type Extents_;
tuple<double> BinSize_;
array<long long> BinRegionIndicesStarts_;
array<long long> BinRegionIndices_;
void MapToBins_(const region_type &Region, range &Bins) const;
void MapToBins_(const region_type &Region, set<long long> &Bins) const;
void AccumulateBinRegionCounts_(const range &Bins, field<long long> &NumRegionsInBin) const;
void AccumulateBinRegionCounts_(const set<long long> &Bins, field<long long> &NumRegionsInBin)
const;
void AddToBins_(int iRegion, const range &Bins, const array<long long> &BinRegionIndicesStarts,
array<long long> &BinRegionIndices, field<long long> &NumRegionsAddedToBin) const;
void AddToBins_(int iRegion, const set<long long> &Bins, const array<long long>
&BinRegionIndicesStarts, array<long long> &BinRegionIndices, field<long long>
&NumRegionsAddedToBin) const ;
template <typename T> struct coord_type_tag {};
interval<int,MAX_DIMS> MakeEmptyExtents_(int NumDims, coord_type_tag<int>);
interval<double,MAX_DIMS> MakeEmptyExtents_(int NumDims, coord_type_tag<double>);
interval<int,MAX_DIMS> UnionExtents_(const interval<int,MAX_DIMS> &Left, const
interval<int,MAX_DIMS> &Right);
interval<double,MAX_DIMS> UnionExtents_(const interval<double,MAX_DIMS> &Left, const
interval<double,MAX_DIMS> &Right);
static tuple<int> GetBinSize_(const interval<int,MAX_DIMS> &Extents, const tuple<int> &NumBins);
static tuple<double> GetBinSize_(const interval<double,MAX_DIMS> &Extents, const tuple<int>
&NumBins);
};
}}
#include <ovk/core/RegionHash.inl>
#endif
| 32.693878
| 98
| 0.762172
|
gyzhangqm
|
bbfce24d15d965501e8ff85e1b32fe028b4ebc16
| 7,517
|
cpp
|
C++
|
bocom/Wiodb.cpp
|
tomasbrod/tbboinc
|
c125cc355b2dc9a1e536b5e5ded028d4e7f4613a
|
[
"MIT"
] | null | null | null |
bocom/Wiodb.cpp
|
tomasbrod/tbboinc
|
c125cc355b2dc9a1e536b5e5ded028d4e7f4613a
|
[
"MIT"
] | 4
|
2020-09-07T15:54:45.000Z
|
2020-09-27T16:47:16.000Z
|
bocom/Wiodb.cpp
|
tomasbrod/tbboinc
|
c125cc355b2dc9a1e536b5e5ded028d4e7f4613a
|
[
"MIT"
] | null | null | null |
int create_work4(
DB_WORKUNIT& wu,
const char* result_template_filename,
SCHED_CONFIG& config_loc
) {
int retval;
wu.create_time = time(0);
// check for presence of result template.
// we don't need to actually look at it.
//
const char* p = config_loc.project_path(result_template_filename);
if (!boinc_file_exists(p)) {
fprintf(stderr,
"create_work: result template file %s doesn't exist\n", p
);
return retval;
}
if (strlen(result_template_filename) > sizeof(wu.result_template_file)-1) {
fprintf(stderr,
"result template filename is too big: %d bytes, max is %d\n",
(int)strlen(result_template_filename),
(int)sizeof(wu.result_template_file)-1
);
return ERR_BUFFER_OVERFLOW;
}
strncpy(wu.result_template_file, result_template_filename, sizeof(wu.result_template_file));
if (wu.rsc_fpops_est == 0) {
fprintf(stderr, "no rsc_fpops_est given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.rsc_fpops_bound == 0) {
fprintf(stderr, "no rsc_fpops_bound given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.rsc_disk_bound == 0) {
fprintf(stderr, "no rsc_disk_bound given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.target_nresults == 0) {
fprintf(stderr, "no target_nresults given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.max_error_results == 0) {
fprintf(stderr, "no max_error_results given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.max_total_results == 0) {
fprintf(stderr, "no max_total_results given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.max_success_results == 0) {
fprintf(stderr, "no max_success_results given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.max_success_results > wu.max_total_results) {
fprintf(stderr, "max_success_results > max_total_results; can't create job\n");
return ERR_INVALID_PARAM;
}
if (wu.max_error_results > wu.max_total_results) {
fprintf(stderr, "max_error_results > max_total_results; can't create job\n");
return ERR_INVALID_PARAM;
}
if (wu.target_nresults > wu.max_success_results) {
fprintf(stderr, "target_nresults > max_success_results; can't create job\n");
return ERR_INVALID_PARAM;
}
/*
auto prev_transitioner_flags= wu.transitioner_flags;
wu.transitioner_flags= 1;
*/
if (wu.transitioner_flags) {
wu.transition_time = INT_MAX;
} else {
wu.transition_time = time(0);
}
retval = wu.insert();
if (retval) {
fprintf(stderr,
"create_work4: workunit.insert() %s\n", boincerror(retval)
);
return retval;
}
wu.id = boinc_db.insert_id();
/*
wu.transitioner_flags= prev_transitioner_flags;
if (wu.transitioner_flags) {
wu.transition_time = INT_MAX;
} else {
wu.transition_time = time(0);
}
wu.update();
*/
return 0;
}
int create_work3(
DB_WORKUNIT& wu,
const char* result_template_filename,
// relative to project root; stored in DB
SCHED_CONFIG& config_loc,
const CStream& input_data
) {
int retval;
unsigned long in_len = input_data.pos();
char in_md5[256];
md5_block((const unsigned char*)input_data.getbase(), in_len, in_md5);
snprintf(wu.xml_doc, sizeof(wu.xml_doc),
"<file_info>\n<name>%s.in</name>\n"
"<url>https://boinc.tbrada.eu/tbrada_cgi/fuh?%s.in</url>\n"
"<md5_cksum>%s</md5_cksum>\n<nbytes>%lu</nbytes>\n</file_info>\n"
"<workunit>\n<file_ref>\n<file_name>%s.in</file_name>\n"
"<open_name>input.dat</open_name>\n</file_ref>\n</workunit>\n"
, wu.name, wu.name
, in_md5, in_len
, wu.name
);
retval = create_work4(wu, result_template_filename, config_loc);
if(retval) return retval;
//insert input_file
MYSQL_STMT* insert_stmt = 0;
insert_stmt = mysql_stmt_init(boinc_db.mysql);
char stmt[] = "insert into input_file SET wu=?, data=?";
void* in_data= (void*)input_data.getbase();
MYSQL_BIND bind[] = {
{.buffer=&wu.id, .buffer_type=MYSQL_TYPE_LONG, 0},
{.length=&in_len, .buffer=in_data, .buffer_type=MYSQL_TYPE_BLOB, 0},
};
if(!insert_stmt
|| mysql_stmt_prepare(insert_stmt, stmt, sizeof stmt )
|| mysql_stmt_bind_param(insert_stmt, bind)
|| mysql_stmt_execute(insert_stmt)
) {
mysql_stmt_close(insert_stmt);
fprintf(stderr,
"create_work: insert of input_data failed %s\n", mysql_error(boinc_db.mysql) );
//wu.delete_from_db();
return -1;
}
mysql_stmt_close(insert_stmt);
return 0;
}
int read_output_file(RESULT const& result, CDynamicStream& buf) {
char path[MAXPATHLEN];
path[0]=0;
std::string name;
double usize = 0;
double usize_max = 0;
MIOFILE mf;
mf.init_buf_read(result.xml_doc_out);
XML_PARSER xp(&mf);
while (!xp.get_tag()) {
if (!xp.is_tag) continue;
if (xp.match_tag("file_info")) {
while(!xp.get_tag()) {
if (!xp.is_tag) continue;
if(xp.parse_string("name",name)) continue;
if(xp.parse_double("nbytes",usize)) continue;
if(xp.parse_double("max_nbytes",usize_max)) continue;
if (xp.match_tag("/file_info")) {
if(!name[0] || !usize) {
return ERR_XML_PARSE;
}
dir_hier_path(
name.c_str(), config.upload_dir,
config.uldl_dir_fanout, path
);
FILE* f = boinc_fopen(path, "r");
if(!f && ENOENT==errno) return ERR_FILE_MISSING;
if(!f) return ERR_READ;
struct stat stat_buf;
if(fstat(fileno(f), &stat_buf)<0) return ERR_READ;
buf.setpos(0);
buf.reserve(stat_buf.st_size);
if( fread(buf.getbase(), 1, stat_buf.st_size, f) !=stat_buf.st_size)
return ERR_READ;
buf.setpos(0);
fclose(f);
return 0;
}
}
}
}
return ERR_XML_PARSE;
}
int read_output_file_db(RESULT const& result, CDynamicStream& buf) {
char sql[MAX_QUERY_LEN];
sprintf(sql, "select id, data from result_file where res='%lu' order by id desc limit 1", result.id);
int retval=boinc_db.do_query(sql);
if(retval) return retval;
MYSQL_RES* enum_res= mysql_use_result(boinc_db.mysql);
if(!enum_res) return -1;
MYSQL_ROW row=mysql_fetch_row(enum_res);
if (row == 0) {
mysql_free_result(enum_res);
return ERR_FILE_MISSING;
}
unsigned long *enum_len= mysql_fetch_lengths(enum_res);
buf.setpos(0);
//buf.reserve(enum_len[1]);
buf.write(row[1], enum_len[1]);
buf.setpos(0);
mysql_free_result(enum_res);
return 0;
}
void set_result_invalid(DB_RESULT& result) {
DB_WORKUNIT wu;
if(wu.lookup_id(result.workunitid)) throw EDatabase("Workunit not found");
DB_HOST_APP_VERSION hav, hav0;
retval = hav_lookup(hav0, result.hostid,
generalized_app_version_id(result.app_version_id, result.appid)
);
hav= hav0;
hav.consecutive_valid = 0;
if (hav.max_jobs_per_day > config.daily_result_quota) {
hav.max_jobs_per_day--;
}
result.validate_state=VALIDATE_STATE_INVALID;
result.outcome=6;
wu.transition_time = time(0);
//result.file_delete_state=FILE_DELETE_READY; - keep for analysis
if(result.update()) throw EDatabase("Result update error");
if(wu.update()) throw EDatabase("Workunit update error");
if (hav.host_id && hav.update_validator(hav0)) throw EDatabase("Host-App-Version update error");
}
| 31.190871
| 102
| 0.65731
|
tomasbrod
|
bbfd1811564296095ed432bef91b5052577a8328
| 52,456
|
cpp
|
C++
|
src/llreplace.cpp
|
landenlabs2/llfile
|
83d071412467742fcf9611ee0b10e41b6ea19728
|
[
"MIT"
] | 1
|
2017-01-26T13:48:35.000Z
|
2017-01-26T13:48:35.000Z
|
src/llreplace.cpp
|
landenlabs2/llfile
|
83d071412467742fcf9611ee0b10e41b6ea19728
|
[
"MIT"
] | null | null | null |
src/llreplace.cpp
|
landenlabs2/llfile
|
83d071412467742fcf9611ee0b10e41b6ea19728
|
[
"MIT"
] | null | null | null |
//-----------------------------------------------------------------------------
// llreplace - Replace file data or Grep.
//
// Author: Dennis Lang - 2015
// http://landenlabs.com/
//
// This file is part of LLFile project.
//
// ----- License ----
//
// Copyright (c) 2015 Dennis Lang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include <iostream>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
#include <io.h>
#include <map>
#include <algorithm>
#define ZipLib
#ifdef ZipLib
// https://bitbucket.org/wbenny/ziplib/wiki/Home
#include "../ZipLib/ZipFile.h"
// #pragma comment(lib, "zlib.lib")
// #pragma comment(lib, "lzma.lib")
// #pragma comment(lib, "bzip2.lib")
#endif
#include "LLReplace.h"
#include "MemMapFile.h"
#ifdef ZipLib
int LLReplace::ZipListArchive(const char* zipArchiveName)
{
// ZipArchive::Ptr archive = ZipFile::Open(zipArchiveName);
std::ifstream* zipFile = new std::ifstream();
zipFile->open(zipArchiveName, std::ios::binary);
if (!zipFile->is_open())
return -1;
ZipArchive::Ptr archive = ZipArchive::Create(zipFile, true);
if (archive == nullptr)
return -1;
size_t entries = archive->GetEntriesCount();
if (m_verbose)
{
LLMsg::Out() << zipArchiveName << ", Entries:" << entries << std::endl;
LLMsg::Out() << archive->GetComment() << std::endl;
}
for (size_t idx = 0; idx < entries; ++idx)
{
auto entry = archive->GetEntry(int(idx));
if (m_zipList.size() == 1 && m_zipList[0] == "-")
{
std::stringstream in(entry->GetFullName());
m_matchCnt += FindGrep(in);
m_totalInSize += entry->GetSize();
m_countInFiles++;
}
else if (LLSup::PatternListMatches(m_zipList, entry->GetFullName().c_str(), true))
{
if (m_verbose)
{
LLMsg::Out() << std::setw(3) << idx << ":"
<< std::setw(8) << entry->GetSize() << " "
<< entry->GetFullName() << std::endl;
/*
uncompressed size entry->GetSize());
compressed size: entry->GetCompressedSize());
password protected: entry->IsPasswordProtected() ? "yes" : "no");
compression method: entry->GetCompressionMethod()
comment: entry->GetComment()
crc32: entry->GetCrc32());
*/
}
std::istream* decompressStream = entry->GetDecompressionStream();
#if 1
if (decompressStream != nullptr)
{
m_matchCnt += FindGrep(*decompressStream);
m_totalInSize += entry->GetSize();
m_countInFiles++;
}
#else
std::string line;
while (std::getline(*decompressStream, line))
{
LLMsg::Out() << line << std::endl;
}
#endif
}
}
return sOkay;
}
int LLReplace::ZipReadFile(
const char* zipFilename,
const char* fileToExtract,
const char* password)
{
ZipArchive::Ptr archive = ZipFile::Open(zipFilename);
ZipArchiveEntry::Ptr entry = archive->GetEntry(fileToExtract);
assert(entry != nullptr);
entry->SetPassword(password);
std::istream* decompressStream = entry->GetDecompressionStream();
assert(decompressStream == nullptr);
std::string line;
while (std::getline(*decompressStream, line))
{
LLMsg::Out() << line << std::endl;
}
return sIgnore;
}
#endif
// ---------------------------------------------------------------------------
// Add regular expression to help document
// https://msdn.microsoft.com/en-us/library/bb982727.aspx#regexgrammar
// http://www.cplusplus.com/reference/regex/ECMAScript/
static const char sHelp[] =
" Replace " LLVERSION "\n"
" Replace a file[s] data\n"
"\n"
" !0eSyntax:!0f\n"
" [<switches>] <Pattern>... \n"
"\n"
" !0eWhere switches are:!0f\n"
" -? ; Show this help\n"
" -A=[nrhs] ; Limit files by attribute (n=normal r=readonly, h=hidden, s=system)\n"
" -D ; Only directories in matching, default is all types\n"
" -p ; Search PATH environment directories for pattern\n"
" -e=<envName>[,...] ; Search env environment directories for pattern\n"
" -F ; Only files in matching, default is all types\n"
" -F=<filePat>,... ; Limit to matching file patterns \n"
" -G=<grepPattern> ; Return line matching grepPattern \n"
" -g=<grepOptions> ; Use with -G \n"
" ; Default is search entire file \n"
" ; Ln=first n lines \n"
" ; Mn=first n matches \n"
" ; H(c|f|l|m|t) Hide color|filename|Line#|MatchCnt|Text \n"
" ; I=ignore case \n"
" ; R=repeat replace \n"
" ; Bn=show before n lines \n"
" ; An=show after n lines \n"
" ; F(l|f) force byLine or byFile \n"
" ; U(i|b) update inline or backup \n"
" -i ; Ignore case, same as -g=I \n"
" -I=<file> ; Read list of files from this file\n"
" -M=<file> ; Match (and replace) list of patterns in file \n"
" ; First Line Seperator:<char> like , \n"
" ; Remainder <findPat><seperator><replacePat>[,<filePathPat>] \n"
" -p ; Short cut for -e=PATH, search path \n"
" -P=<srcPathPat> ; Optional regular expression pattern on source files full path\n"
" -q ; Quiet, default is echo command\n"
" -Q=n ; Quit after 'n' file matches\n"
" -r ; Recurse into subdirectories\n"
" -R=<replacePattern> ; Use with -G to replace match\n"
#if 0
" -Rbefore=<pattern> ; TODO Use with -R to move a replacement\n"
" -Rafter=<pattern> ; TODO Use with -R to move a replacement\n"
#endif
" -s ; Show file size size\n"
" -t[acm] ; Show Time a=access, c=creation, m=modified, n=none\n"
" -X=<pathPat>,... ; Exclude patterns -X=*.lib,*.obj,*.exe\n"
" ; No space in patterns. Pattern applied against fullpath\n"
" ; So *\\ma will exclude a directory ma or file ma \n"
" -v ; Verbose \n"
" -V=<grepPattern> ; Return inverse line matching grep matches \n"
" -w=<width> ; Limit output to width characters per match \n"
" -z=<filePattern> ; Limit zip/jar/gz file match, use - to search names \n"
"\n"
" -E=[cFDdsamlL] ; Return exit code, c=File+Dir count, F=file count, D=dir Count\n"
" ; d=depth, s=size, a=age, m=#matches, l=#lines, L=list of matching files \n"
" -1=<file> ; Redirect output to append to file \n"
" -3=<file> ; Tee output to append to file \n"
"\n"
" !0eWhere Pattern is:!0f\n"
" <file|Pattern> \n"
" [<directory|pattern> \\]... <file|Pattern|#n> \n"
"\n"
" !0ePattern:!0f\n"
" * = zero or more characters\n"
" ? = any character\n"
"\n"
" !0eExample:!0f\n"
" llfile -xG \"-G=(H|h)ello\\r\\n\" *.txt ; -xG force grep command\n"
" lg '-G=String' -g=I -r -F=*.cpp src ; Ignore case String in cpp files \n"
" lg -Ar -i=c:\\fileList.txt >nul ; check for non-readonly files from list \n"
"\n"
" lg -F=*.txt,*.log '-G=[0-9]+' .\\* ; search files for numbers \n"
" lg -X=*.obj,*.exe -G=foo build\\* ; search none object or exe files\n"
" lg -z=* -G=class java\\*.jar ; search jar internal files for class \n"
" lg -z=foo* -G=class java\\*.jar ; search jar internal foo* files for class \n"
" lg -z=- -G=class java\\*.jar ; search filenames in jar files for class \n"
" lg -z -G=hello -r libs ; search files for hello and look inside any archive \n"
" lg \"-G= foo \" *.txt | lg -G=bar ; Same as following\n"
" lg \"-G= foo \" -G=bar *.txt ; two -G, either can match per line\n"
"\n"
" ; Use -E=L to match multiple words in same file but not same line \n"
" lg -G=foo -r -F=*.txt -E=L | lg -I=- -G=bar \n"
"\n"
" lg -G=\"'([^']+)',.*\" -R=\"$1');\" foo.txt ; Grep and Replace \n"
" lg -G=\\n\\n -R=\\n -g=R foo.txt ; remove blank lines \n"
" !0ePattern across multiple lines:!0f\n"
" The pattern engine does not match line terminators with . so use some group\n"
" which does not appear in the normal text, like [^?]* \n"
" Example to remove XML tag group. \n"
" \"-G= *<SurveySettings\\>[^?]*\\</SurveySettings>\" \"-R=\" file.xml \n"
"\n"
" lg \"-G=( *)if \\(AppConfigInfo\\.DEBUG\\) \\{[\\r\\n]\\s*Log[.]([^;]+);\\s*[\\r\\n]\\s*\\}\" \"-R=$1WLog.$2\" \n"
"\n";
LLReplaceConfig LLReplace::sConfig;
WORD FILE_COLOR = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
WORD MATCH_COLOR = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN;
WORD MATCH_COLORS[] =
{
FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN,
FOREGROUND_INTENSITY | FOREGROUND_RED,
FOREGROUND_INTENSITY | FOREGROUND_GREEN,
FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE,
};
const char sForceByLine = 'l';
const char sForceByFile = 'f';
///////////////////////////////////////////////////////////////////////////////
// Expands c-style character constants in the input string; returns new size
// (strlen won't work, since the string may contain premature \0's)
static std::string ConvertSpecialChar(std::string& inOut)
{
int len = 0;
int x, n;
const char *inPtr = inOut.c_str();
char* outPtr = (char*)inPtr;
while (*inPtr)
{
if (*inPtr == '\\')
{
inPtr++;
switch (*inPtr)
{
case 'n': *outPtr++ = '\n'; break;
case 't': *outPtr++ = '\t'; break;
case 'v': *outPtr++ = '\v'; break;
case 'b': *outPtr++ = '\b'; break;
case 'r': *outPtr++ = '\r'; break;
case 'f': *outPtr++ = '\f'; break;
case 'a': *outPtr++ = '\a'; break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
sscanf(inPtr,"%3o%n",&x,&n);
inPtr += n-1;
*outPtr++ = (char)x;
break;
case 'x': // hexadecimal
sscanf(inPtr+1,"%2x%n",&x,&n);
if (n>0)
{
inPtr += n;
*outPtr++ = (char)x;
break;
}
// seep through
default:
throw( "Warning: unrecognized escape sequence" );
case '\\':
case '\?':
case '\'':
case '\"':
*outPtr++ = *inPtr;
}
inPtr++;
}
else
*outPtr++ = *inPtr++;
len++;
}
inOut.resize(len);
return inOut;;
}
// ---------------------------------------------------------------------------
// Return true if character in pattern string is part of regular expression
// and not escaped out or inside a closour group []
static bool isPattern(std::string str, int pos)
{
if (pos < 0)
return false;
if (pos == 0)
return true;
if (str[pos-1] == '\\')
return false;
while (--pos >= 0)
{
if (str[pos] == ']')
return true;
if (str[pos] == '[')
return false;
}
return true;
}
// ---------------------------------------------------------------------------
LLReplace::LLReplace() :
m_force(false),
m_totalInSize(0),
m_countInFiles(0),
m_lineCnt(0),
m_matchCnt(0),
m_width(0),
m_zipFile(false)
{
m_exitOpts = "c";
m_showAttr =
m_showCtime =
m_showMtime =
m_showAtime =
m_showPath =
m_showSize =
m_allMustMatch = false;
memset(&m_fileData, 0, sizeof(m_fileData));
m_dirScan.m_recurse = false;
sConfigp = &GetConfig();
}
// ---------------------------------------------------------------------------
LLConfig& LLReplace::GetConfig()
{
return sConfig;
}
// ---------------------------------------------------------------------------
int LLReplace::StaticRun(const char* cmdOpts, int argc, const char* pDirs[])
{
LLReplace llFind;
return llFind.Run(cmdOpts, argc, pDirs);
}
// ---------------------------------------------------------------------------
int LLReplace::Run(const char* cmdOpts, int argc, const char* pDirs[])
{
const char missingRetMsg[] = "Missing return value, c=file count, d=depth, s=size, a=age, syntax -0=<code>";
const char missingEnvMsg[] = "Environment variable name, syntax -E=<envName> ";
const char optReplaceMsg[] = "Replace matches (see -G=grepPattern) with replacement, -R=<replacement>";
const char optGrepMsg[] = "Find in file grepPattern, -G=<grepPattern>" ;
const char missingRepGrp[] = "Replace (-R=replace) must follow Grep (-G=patttern)";
const char widthErrMsg[] = "missing width, syntax -w=<#width>";
const std::string endPathStr(";");
LLSup::StringList envList;
std::string str;
// Initialize stuff
size_t nFiles = 0;
bool sortNeedAllData = m_showSize;
#if 0
// Try and detect redirection and auto disable File, Match and Line numbers.
bool isOutConsole = _isatty(_fileno(stdout));
HANDLE stdoutHnd = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD outType = GetFileType(stdoutHnd); // FILE_TYPE_PIPE
if (outType == FILE_TYPE_PIPE)
isOutConsole = false;
if (outType == FILE_TYPE_DISK)
isOutConsole = false;
#endif
#if 0
// Setup default as needed.
if (argc == 0 && strstr(cmdOpts, "I=") == 0)
{
const char* sDefDir[] = {"*"};
argc = sizeof(sDefDir)/sizeof(sDefDir[0]);
pDirs = sDefDir;
}
#endif
std::string matchFilename;
GrepReplaceItem grepRep;
unsigned findCnt = 0;
unsigned replaceCnt = 0;
// Parse options
while (*cmdOpts)
{
grepRep.m_onMatch = true;
switch (*cmdOpts)
{
case 'C': // -C=none or -C=0 disable colors
if (cmdOpts[1] == sEQchr)
{
cmdOpts += 2;
switch (ToLower(*cmdOpts))
{
case '0':
case 'n':
sConfig.m_colorOn = false;
break;
default:
ErrorMsg() << "Unknown color option: -C" << *cmdOpts << std::endl;
}
// Move to end of color options
while(*cmdOpts > sEOCchr)
cmdOpts++;
}
break;
case 'i': // ignore case, same as =g=I
m_grepOpt.ignoreCase = true;
break;
case 'V': // inverse grep pattern -V=<grepPattern>, show if lines does not contain grepPattern
grepRep.m_onMatch = false;
m_byLine = true;
m_allMustMatch = true;
case 'G': // grep pattern -G=<grepPattern>, show if line contains grepPattern
cmdOpts = LLSup::ParseString(cmdOpts+1, str, optGrepMsg);
if (str.length() != 0) {
if (replaceCnt != 0 && findCnt != replaceCnt)
{
LLMsg::PresentError(0, missingRepGrp, "\n");
return sError;
}
try {
findCnt++;
grepRep.m_grepLineStr = str;
grepRep.m_grepLinePat = std::tr1::regex(str /* , regex_constants::ECMAScript */);
m_grepReplaceList.push_back(grepRep);
// If pattern has explict test for beginning or end of line
// process search/replace byLine rather then byEntireFile.
if (!m_byLine && isPattern(str, str.find('^')))
m_byLine = true;
if (!m_byLine && isPattern(str, str.find('$')))
m_byLine = true;
if (!m_byLine && isPattern(str, str.find('(')))
m_backRef = true;
}
catch (std::regex_error& ex)
{
LLMsg::PresentError(ex.code(), ex.what(), str.c_str());
return sError;
}
}
break;
case 'R': // Get Replacement string
if (isalpha(cmdOpts[1]))
{
// Check for special case -Rafter=... or -Rbefore=...
const char* eqPos = strchr(cmdOpts+2, '=');
if (eqPos != NULL)
{
int len = int(eqPos - cmdOpts + 2);
if (_strnicmp(cmdOpts+2, "after", len) == 0)
{
cmdOpts = LLSup::ParseString(cmdOpts+1, str, optReplaceMsg);
m_grepReplaceList.back().m_afterStr = str;
m_grepOpt.force ='l'; // force by-line
break;
}
else if (_strnicmp(cmdOpts+2, "before", len) == 0)
{
cmdOpts = LLSup::ParseString(cmdOpts+1, str, optReplaceMsg);
m_grepReplaceList.back().m_beforeStr = str;
m_grepOpt.force ='l'; // force by-line
break;
}
}
}
cmdOpts = LLSup::ParseString(cmdOpts+1, str, optReplaceMsg);
if (replaceCnt + 1 == findCnt)
{
replaceCnt++;
m_grepReplaceList.back().m_replace = true;
m_grepReplaceList.back().m_replaceStr = ConvertSpecialChar(str);
}
else
{
LLMsg::PresentError(0, missingRepGrp, "\n");
return sError;
}
break;
case 'm': // Reverse match using file list
grepRep.m_onMatch = false;
m_allMustMatch = true;
case 'M': // Match file list
cmdOpts = LLSup::ParseString(cmdOpts+1, matchFilename, missingInFileMsg);
if (matchFilename.length() != 0)
{
FILE* fin = stdin;
if (strcmp(matchFilename.c_str(), "-") == 0 ||
0 == fopen_s(&fin, matchFilename.c_str(), "rt"))
{
const char sepTag[] = "Seperator:";
const unsigned sepLen = sizeof(sepTag) - 1;
char userSep[] = ",";
char lineBuf[MAX_PATH];
if (fgets(lineBuf, ARRAYSIZE(lineBuf), fin))
{
unsigned lineLen = strlen(lineBuf);
if (strncmp(sepTag, lineBuf, sepLen) == 0 && lineLen > sepLen)
{
userSep[0] = lineBuf[sepLen]; // TODO - support multiple separators
if (!fgets(lineBuf, ARRAYSIZE(lineBuf), fin))
return sError;
}
else
{
LLMsg::PresentError(0, "Match file should start with Seperator:<char>", " Assuming comma separator \n");
// return sError;
}
do
{
// TrimString(lineBuf); // remove extra space or control characters.
if (*lineBuf == '\0')
continue;
unsigned len = strlen(lineBuf);
lineBuf[len - 1] = '\0'; // remove EOL
Split fields(lineBuf, userSep);
if (fields.size() > 0)
{
if (replaceCnt != 0 && findCnt != replaceCnt)
{
LLMsg::PresentError(0, missingRepGrp, "\n");
return sError;
}
findCnt++;
grepRep.m_grepLinePat = grepRep.m_grepLineStr = fields[0];
if (fields.size() > 1)
{
replaceCnt++;
grepRep.m_grepLinePat = ConvertSpecialChar(fields[1]); // Should this be the replacement pattern ?
}
if (fields.size() > 2)
{
grepRep.m_filePathPat = std::tr1::regex(fields[2], regex_constants::icase);
grepRep.m_haveFilePat = true;
}
m_grepReplaceList.push_back(grepRep);
}
} while (fgets(lineBuf, ARRAYSIZE(lineBuf), fin));
std::cerr << " Grep patterns:" << m_grepReplaceList.size() << std::endl;
}
}
}
break;
case 's': // Toggle showing size.
sortNeedAllData |= m_showSize = !m_showSize;
// m_dirSort.SetSortData(sortNeedAllData);
break;
case 't': // Display Time selection
{
bool unknownOpt = false;
while (cmdOpts[1] && !unknownOpt)
{
cmdOpts++;
switch (ToLower(*cmdOpts))
{
case 'a':
sortNeedAllData = m_showAtime = true;
break;
case 'c':
sortNeedAllData = m_showCtime = true;
break;
case 'm':
sortNeedAllData = m_showMtime = true;
break;
case 'n': // NoTime
sortNeedAllData = false;
m_showAtime = m_showCtime = m_showMtime = false;
break;
default:
cmdOpts--;
unknownOpt = true;
break;
}
}
// m_dirSort.SetSortData(sortNeedAllData);
}
break;
case 'z': // Limit zip files, -z or z=<filePat>[,<filePat>]...
cmdOpts = LLSup::ParseList(cmdOpts + 1, m_zipList, NULL);
m_zipFile = true;
break;
case 'w': // Width
cmdOpts = LLSup::ParseNum(cmdOpts+1, m_width, widthErrMsg);
break;
case '?':
Colorize(std::cout, sHelp);
return sIgnore;
case 'E':
if ( !ParseBaseCmds(cmdOpts))
return sError;
if (m_exitOpts.find_first_of("L") != string::npos)
m_grepOpt.hideFilename = m_grepOpt.hideLineNum = m_grepOpt.hideMatchCnt = m_grepOpt.hideText = true;
if (m_exitOpts.find_first_of("l") != string::npos)
m_grepOpt.force = sForceByLine;
break;
default:
if ( !ParseBaseCmds(cmdOpts))
return sError;
}
// Advance to next parameter
LLSup::AdvCmd(cmdOpts);
}
if (m_grepOpt.ignoreCase && !m_grepReplaceList.empty())
{
for (unsigned idx = 0; idx != m_grepReplaceList.size(); idx++)
{
GrepReplaceItem& grepReplaceItem = m_grepReplaceList[idx];
grepReplaceItem.m_grepLinePat =
std::tr1::regex(grepReplaceItem.m_grepLineStr, regex_constants::icase);
}
}
if (m_grepReplaceList.empty())
{
Colorize(std::cout, sHelp);
return sIgnore;
}
// Move arguments and input files into inFileList.
std::vector<std::string> inFileList;
for (int argn=0; argn < argc; argn++)
{
inFileList.push_back(pDirs[argn]);
}
if (m_inFile.length() != 0)
{
FILE* fin = stdin;
if (strcmp(m_inFile.c_str(), "-") == 0 ||
0 == fopen_s(&fin, m_inFile.c_str(), "rt"))
{
char fileName[MAX_PATH];
while (fgets(fileName, ARRAYSIZE(fileName), fin))
{
TrimString(fileName); // remove extra space or control characters.
if (*fileName == '\0')
continue;
inFileList.push_back(fileName);
}
}
}
if (m_grepOpt.force != 0)
{
if (m_grepOpt.force == sForceByLine)
m_byLine = true;
else if (m_grepOpt.force == sForceByFile)
m_byLine = false;
}
if (inFileList.empty())
{
// Grep from standard-in
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
m_matchCnt += FindGrep(cin);
}
else
{
// Iterate over dir patterns.
for (unsigned argn=0; argn < inFileList.size(); argn++)
{
VerboseMsg() <<" Dir:" << inFileList[argn] << std::endl;
m_dirScan.Init(inFileList[argn].c_str(), NULL);
nFiles += m_dirScan.GetFilesInDirectory();
}
}
if (m_verbose)
{
// InfoMsg() << ";Matches:" << m_matchCnt << ", Files:" << m_countOutFiles << std::endl;
SetGrepColor(MATCH_COLOR);
LLMsg::Out() << ";Matches:" << m_matchCnt << ", MatchFiles:" << m_countOutFiles
<< ", ScanFiles:" << m_countInFiles
<< std::endl;
ResetGrepColor();
}
// Return status, c=file count, d=depth, s=size, a=age
if (m_exitOpts.length() != 0)
switch ((char)m_exitOpts[0u])
{
case 'a': // age, -0=a
{
FILETIME ltzFT;
SYSTEMTIME sysTime;
FileTimeToLocalFileTime(&m_fileData.ftLastWriteTime, <zFT); // convert UTC to local Timezone
FileTimeToSystemTime(<zFT, &sysTime);
// TODO - compare to local time and return age.
return 0;
}
break;
case 'm': // matchCnt -g=<grepPat>
VerboseMsg() << ";Matches:" << m_matchCnt << std::endl;
return (int)m_matchCnt;
case 's': // file size, -0=s
VerboseMsg() << ";Size:" << m_totalInSize << std::endl;
return (int)m_totalInSize;
// case 'd': // file depth, -o=d
// VerboseMsg() << ";Depth (-E=d depth currently not implemented,use -E=D for #directories):" << 0 << std::endl;
// return 0; // TODO - return maximum file depth.
// case 'D': // Directory count, -o=D
// VerboseMsg() << ";Directory Count:" << m_countOutDir << std::endl;
// return m_countOutDir;
case 'F': // File count, -o=F
VerboseMsg() << ";File Count:" << m_countOutFiles << std::endl;
return m_countOutFiles;
case 'l': // #lines
LLMsg::Out() << ";Line Count:" << m_lineCnt << std::endl;
break;
case 'L': // List of matching files
for (unsigned idx = 0; idx != m_matchFiles.size(); idx++)
LLMsg::Out() << m_matchFiles[idx] << std::endl;
return m_matchFiles.size();
case 'c': // File and directory count, -o=c
default:
VerboseMsg() << ";File + Directory Count:" << (m_countOutDir + m_countOutFiles) << std::endl;
return (int)(m_countOutDir + m_countOutFiles);
}
return ExitStatus(0);
}
// ---------------------------------------------------------------------------
int LLReplace::ProcessEntry(
const char* pDir,
const WIN32_FIND_DATA* pFileData,
int depth) // 0...n is directory depth, -n end-of nth diretory
{
if (depth < 0)
return sIgnore; // ignore end-of-directory
// Filter on:
// m_onlyAttr File or Directory, -F or -D
// m_onlyRhs Attributes, -A=rhs
// m_includeList File patterns, -F=<filePat>[,<filePat>]...
// m_onlySize File size, -Z op=(Greater|Less|Equal) value=num<units G|M|K>, ex -Zg100M
// m_excludeList Exclude path patterns, -X=<pathPat>[,<pathPat>]...
// m_timeOp Time, -T[acm]<op><value> ; Test Time a=access, c=creation, m=modified\n
//
// If pass, populate m_srcPath
if ( !FilterDir(pDir, pFileData, depth))
return sIgnore;
VerboseMsg() << m_srcPath << "\n";
if (m_isDir)
return sIgnore;
if (m_zipFile)
{
int matchStatus = ZipListArchive(m_srcPath);
if (matchStatus >= 0)
return matchStatus;
}
unsigned matchCnt = FindReplace(pFileData);
if ( matchCnt != 0)
m_matchFiles.push_back(m_srcPath);
#if 0
if (m_echo && !IsQuit())
{
if (m_showAttr)
{
// ShowAttributes(LLMsg::Out(), pDir, *pFileData, false);
LLMsg::Out() << LLReplace::sConfig.m_dirFieldSep;
}
if (m_showCtime)
LLSup::Format(LLMsg::Out(), pFileData->ftCreationTime) << LLReplace::sConfig.m_dirFieldSep ;
if (m_showMtime)
LLSup::Format(LLMsg::Out(), pFileData->ftLastWriteTime) << LLReplace::sConfig.m_dirFieldSep;
if (m_showAtime)
LLSup::Format(LLMsg::Out(), pFileData->ftLastAccessTime) << LLReplace::sConfig.m_dirFieldSep;
if (m_showSize)
LLMsg::Out() << std::setw(LLReplace::sConfig.m_fzWidth) << m_fileSize << LLReplace::sConfig.m_dirFieldSep;
LLMsg::Out() << m_srcPath << std::endl;
}
#endif
m_matchCnt += matchCnt;
m_fileData = *pFileData;
m_totalInSize += m_fileSize;
m_countInFiles++;
if (matchCnt != 0)
m_countOutFiles++;
return (matchCnt != 0) ? sOkay : sIgnore;
}
// ---------------------------------------------------------------------------
void LLReplace::OutFileLine(size_t lineNum, unsigned matchCnt, size_t filePos)
{
if (m_echo)
{
SetGrepColor(FILE_COLOR);
if (!m_grepOpt.hideFilename)
LLMsg::Out() << m_srcPath << ":";
if (lineNum != 0 && !m_grepOpt.hideLineNum)
LLMsg::Out() << lineNum << "L:";
if (matchCnt != 0 && !m_grepOpt.hideMatchCnt)
LLMsg::Out() << matchCnt << "M:";
if (filePos != 0 && !m_grepOpt.hideLineNum)
LLMsg::Out() << filePos << "P:";
ResetGrepColor();
if (m_grepOpt.hideText && !(m_grepOpt.hideFilename && m_grepOpt.hideLineNum && m_grepOpt.hideMatchCnt))
LLMsg::Out() << std::endl;
}
}
// ---------------------------------------------------------------------------
// Determine if input stream is binary.
class BinaryState
{
public:
size_t binaryCnt = 0;
size_t printCnt = 0;
const size_t minCnt = 1024;
bool isBinary(const std::string& str)
{
for (unsigned idx = 0; idx != str.length(); idx++)
{
char c = str[idx];
if (isprint(c) || c == '\r' || c == '\n' || c == '\t')
printCnt++;
else
binaryCnt++;
if (binaryCnt + printCnt > minCnt)
break;
}
return binaryCnt > printCnt;
}
bool isBinary(const char* strBeg, const char* strEnd)
{
while (strBeg != strEnd)
{
char c = *strBeg++;
if (isprint(c) || c == '\r' || c == '\n' || c == '\t')
printCnt++;
else
binaryCnt++;
if (binaryCnt + printCnt > minCnt)
break;
}
return binaryCnt > printCnt;
}
};
// ---------------------------------------------------------------------------
unsigned LLReplace::FindGrep()
{
unsigned matchCnt = 0;
if (!m_grepReplaceList.empty())
{
size_t lineCnt = 0;
try
{
if (m_byLine || m_grepReplaceList.size() > 1)
{
EnableFiltersForFile(m_srcPath);
int inMode = std::ios::in | std::ios::binary;
std::ifstream in(m_srcPath, inMode, _SH_DENYNO);
matchCnt += FindGrep(in);
}
else
{
std::regex_constants::match_flag_type flags =
std::regex_constants::match_flag_type(std::regex_constants::match_default
+ std::regex_constants::match_not_eol + std::regex_constants::match_not_bol);
BinaryState binaryState;
MemMapFile mapFile;
void* mapPtr;
SIZE_T viewLength = INT_MAX;
if (mapFile.Open(m_srcPath) && (mapPtr = mapFile.MapView(0, viewLength)) != NULL)
{
std::tr1::match_results <const char*> match;
const char* begPtr = (const char*)mapPtr;
const char* endPtr = begPtr + viewLength;
const char* strPtr = begPtr;
std::tr1::regex grepLinePat = m_grepReplaceList[0].m_grepLinePat;
if (binaryState.isBinary(strPtr, min(strPtr+256, endPtr)))
{
if (m_verbose)
LLMsg::Out() << "Ignore Binary\n";
return matchCnt;
}
while (std::tr1::regex_search(strPtr, endPtr, match, grepLinePat, flags))
{
matchCnt++;
const char* begLine = match.prefix().second;
while (begLine -1 >= begPtr && begLine[-1] != '\n')
begLine--;
const char* endLine = match.suffix().first;
while (*endLine != '\n' && endLine < endPtr)
endLine++;
if (m_echo)
{
OutFileLine(0, matchCnt);
if (!m_grepOpt.hideText)
{
do {
std::string prefix = std::string(begLine, match.prefix().second);
// std::string suffix = std::string(match.suffix().first, endLine);;
LLMsg::Out() << prefix;
SetGrepColor(MATCH_COLOR);
LLMsg::Out() << match.str();
ResetGrepColor();
begLine = strPtr = match.suffix().first;
} while (std::tr1::regex_search(strPtr, endLine, match, grepLinePat, flags));
std::string suffix = std::string(match.suffix().first, endLine);
LLMsg::Out() << suffix << std::endl;
}
}
strPtr = endLine;
if (matchCnt >= m_grepOpt.matchCnt)
break;
}
}
else
{
LLMsg::PresentError(GetLastError(), "Open failed,", m_srcPath);
}
}
}
catch (...)
{
}
m_lineCnt += lineCnt;
}
return matchCnt;
}
// ---------------------------------------------------------------------------
struct ColorInfo
{
uint len;
WORD color;
ColorInfo() :
len(0), color(0)
{ }
ColorInfo(uint _len, WORD _color) :
len(_len), color(_color)
{ }
};
typedef std::map<uint, ColorInfo> ColorMap;
// ---------------------------------------------------------------------------
unsigned LLReplace::FindGrep(std::istream& in)
{
unsigned matchCnt = 0;
unsigned lineCnt = 0;
std::tr1::smatch match;
std::regex_constants::match_flag_type flags = std::regex_constants::match_default;
std::vector<string> beforeLines(m_grepOpt.beforeCnt);
unsigned addBeforeIdx = 0;
unsigned afterLines = 0;
BinaryState binaryState;
std::string str;
while (std::getline(in, str))
{
lineCnt++;
if (binaryState.isBinary(str))
{
if (m_verbose)
LLMsg::Out() << "Ignore Binary\n";
return matchCnt;
}
// All patterns have to match for the line to match.
ColorMap colorMap;
unsigned itemMatchCnt = 0;
std::tr1::regex grepLinePat;
for (unsigned patIdx = 0; patIdx != m_grepReplaceList.size(); patIdx++)
{
GrepReplaceItem& grepRepItem = m_grepReplaceList[patIdx];
if (grepRepItem.m_enabled)
{
bool itemMatches = false;
grepLinePat = grepRepItem.m_grepLinePat;
std::string replaceStr = grepRepItem.m_replaceStr;
if (grepRepItem.m_replace)
{
// Loop to get multiple matches on a line.
size_t off = 0;
do
{
std::string::const_iterator begIter = str.begin();
std::string::const_iterator endIter = str.end();
std::advance(begIter, off);
if (begIter < endIter &&
std::tr1::regex_search(begIter, endIter, match, grepLinePat, flags|std::regex_constants::format_first_only))
{
std::string subStr = str.substr(off);
std::string newStr = std::regex_replace(subStr, grepLinePat, replaceStr, flags|std::regex_constants::format_first_only);
int repLen = match.length() + newStr.length() - str.length();
if (newStr != subStr)
{
// str.swap(newStr);
unsigned begPos = off + match.position();
str.replace(begPos, str.length() - begPos, newStr, match.position(), newStr.length() - match.position());
itemMatches = true;
if (repLen > 0)
colorMap[(uint)match.position()] = ColorInfo((uint)repLen, MATCH_COLORS[patIdx % ARRAYSIZE(MATCH_COLORS)]);
else
colorMap[0] = ColorInfo(str.length(), MATCH_COLORS[patIdx % ARRAYSIZE(MATCH_COLORS)]);
// std::advance (begIter, grepLinePat.length());
// off += grepLinePat.length();
off += match.position() + 1;
} else
off = 0;
} else
off = 0;
} while (off != 0);
}
else if (grepRepItem.m_onMatch)
{
// Loop to get multiple matches on a line.
std::string::const_iterator begIter = str.begin();
std::string::const_iterator endIter = str.end();
size_t off = 0;
while (off < str.length() &&
std::tr1::regex_search(begIter, endIter, match, grepLinePat, flags))
{
itemMatches = true;
colorMap[uint(match.position() + off)] = ColorInfo((uint)match.length(), MATCH_COLORS[patIdx % ARRAYSIZE(MATCH_COLORS)]);
std::advance (begIter, match.length());
off += match.length();
}
}
else
{
// Reverse match
if (std::tr1::regex_search(str, match, grepLinePat, flags) == false)
{
itemMatches = true;
if (m_grepReplaceList.size() == 1)
colorMap[0] = ColorInfo(str.length(), MATCH_COLORS[patIdx % ARRAYSIZE(MATCH_COLORS)]);
}
}
if (itemMatches)
itemMatchCnt++;
}
}
if (m_allMustMatch && itemMatchCnt != m_grepReplaceList.size())
colorMap.clear();
else if (m_allMustMatch && colorMap.size() == 0)
LLMsg::Out() << str << std::endl;
if (colorMap.size() != 0)
{
matchCnt++;
if (m_echo)
{
if (m_width != 0)
{
// Clamp output to user desired width.
for (ColorMap::iterator iter = colorMap.begin(); iter != colorMap.end(); iter++)
iter->second.len = min(iter->second.len, (uint)m_width);
}
OutFileLine(lineCnt, matchCnt);
if (!m_grepOpt.hideText)
{
afterLines = m_grepOpt.afterCnt;
for (unsigned bidx = 0; bidx != beforeLines.size(); bidx++)
{
std::string beforeStr = beforeLines[(bidx + addBeforeIdx) % m_grepOpt.beforeCnt];
if (beforeStr.length() != 0)
LLMsg::Out() << beforeStr << std::endl;
}
ColorMap::const_iterator iter = colorMap.begin();
uint pos = 0;
const char* cstr = str.c_str();
while (iter != colorMap.end())
{
if (iter->first >= pos)
{
LLMsg::Out().write(cstr + pos, iter->first - pos);
pos = iter->first;
SetGrepColor(iter->second.color);
LLMsg::Out().write(cstr + iter->first, iter->second.len);
ResetGrepColor();
pos = iter->first + iter->second.len;
}
iter++;
}
LLMsg::Out() << (cstr + pos);
LLMsg::Out() << std::endl;
}
}
if (matchCnt >= m_grepOpt.matchCnt)
break;
}
else if (afterLines != 0)
{
if (!m_grepOpt.hideText)
LLMsg::Out() << str << std::endl;
afterLines--;
}
if (m_grepOpt.beforeCnt > 0)
beforeLines[addBeforeIdx++ % m_grepOpt.beforeCnt] = str;
str.clear();
}
m_lineCnt += lineCnt;
return matchCnt;
}
// ---------------------------------------------------------------------------
void LLReplace::EnableFiltersForFile(const std::string& filePath)
{
std::tr1::smatch match;
std::regex_constants::match_flag_type flags = std::regex_constants::match_default;
for (unsigned patIdx = 0; patIdx != m_grepReplaceList.size(); patIdx++)
{
GrepReplaceItem& item = m_grepReplaceList[patIdx];
item.m_enabled = !item.m_haveFilePat || std::tr1::regex_match(filePath, match, item.m_filePathPat, flags);
}
}
// ---------------------------------------------------------------------------
void LLReplace::ColorizeReplace(const std::string& str)
{
ColorMap colorMap;
std::string replaceStr;
for (unsigned patIdx = 0; patIdx != m_grepReplaceList.size(); patIdx++)
{
if (m_grepReplaceList[patIdx].m_enabled)
{
replaceStr = m_grepReplaceList[patIdx].m_replaceStr;
if (replaceStr.length() != 0)
{
int pos = -1;
while ((pos = (int)str.find(replaceStr, pos+1)) != (int)std::string::npos)
{
colorMap[pos] = ColorInfo(replaceStr.length(), MATCH_COLORS[patIdx % ARRAYSIZE(MATCH_COLORS)]);
}
}
}
}
if (colorMap.size() != 0)
{
ColorMap::const_iterator iter = colorMap.begin();
uint pos = 0;
const char* cstr = str.c_str();
while (iter != colorMap.end())
{
if (iter->first >= pos)
{
LLMsg::Out().write(cstr + pos, iter->first - pos);
pos = iter->first;
SetGrepColor(iter->second.color);
LLMsg::Out().write(cstr + iter->first, iter->second.len);
ResetGrepColor();
pos = iter->first + iter->second.len;
}
iter++;
}
LLMsg::Out() << (cstr + pos);
}
}
// ---------------------------------------------------------------------------
unsigned LLReplace::FindReplace(const WIN32_FIND_DATA* pFileData)
{
if (pFileData->nFileSizeLow == 0 && pFileData->nFileSizeHigh == 0)
return 0;
if (m_grepReplaceList[0].m_replace == false)
return FindGrep();
unsigned matchCnt = 0;
// U(i|b) Update inplace or make backup.
bool okayToWrite = (m_grepOpt.update != 'i') || (m_force || LLPath::IsWriteable(pFileData->dwFileAttributes));
if (okayToWrite)
{
std::regex_constants::match_flag_type flags = std::regex_constants::match_default;
size_t lineCnt = 0;
try
{
int inMode = std::ios::in | std::ios::binary;
if (m_byLine || m_grepReplaceList.size() > 1)
{
EnableFiltersForFile(m_srcPath);
// ----- Find and Replace by line -----
std::tr1::smatch match;
std::ifstream in(m_srcPath, inMode, _SH_DENYNO);
std::ofstream out;
std::streampos inPos = in.tellg();
std::string str;
while (std::getline(in, str))
{
lineCnt++;
if (lineCnt < m_grepOpt.lineCnt)
{
for (unsigned patIdx = 0; patIdx != m_grepReplaceList.size(); patIdx++)
{
if (m_grepReplaceList[patIdx].m_enabled)
{
std::tr1::regex grepLinePat = m_grepReplaceList[patIdx].m_grepLinePat;
if (std::tr1::regex_search(str, match, grepLinePat, flags))
{
std::string replaceStr = m_grepReplaceList[patIdx].m_replaceStr;
matchCnt++;
if (matchCnt == 1)
OpenOutput(out, in, inPos);
std::string newStr = std::regex_replace(str, grepLinePat, replaceStr, flags);
str.swap(newStr);
if (m_echo)
{
OutFileLine(lineCnt, matchCnt);
if (!m_grepOpt.hideText)
{
ColorizeReplace(str);
LLMsg::Out() << std::endl;
}
}
if (matchCnt >= m_grepOpt.matchCnt)
break;
}
}
}
}
else if (!out)
{
break;
}
if (out)
out << str << std::endl;
inPos = in.tellg();
}
in.close();
if (out)
{
out.close();
BackupAndRenameFile();
}
}
else
{
// ----- Find and Replace by memory mapped file -----
bool didReplace;
do {
didReplace = false;
std::ifstream in;
std::streampos inPos(0);
std::ofstream out;
MemMapFile mapFile;
void* mapPtr;
SIZE_T viewLength = INT_MAX;
if (mapFile.Open(m_srcPath) && (mapPtr = mapFile.MapView(0, viewLength)) != NULL)
{
std::tr1::match_results <const char*> match;
const char* begPtr = (const char*)mapPtr;
const char* endPtr = begPtr + viewLength;
const char* strPtr = begPtr;
std::tr1::regex grepLinePat = m_grepReplaceList[0].m_grepLinePat;
std::string replaceStr = m_grepReplaceList[0].m_replaceStr;
if (std::tr1::regex_search(strPtr, endPtr, match, grepLinePat, flags))
{
matchCnt++;
didReplace = true;
if (m_echo)
{
OutFileLine(lineCnt, matchCnt, match.position(0));
if (!m_grepOpt.hideText)
LLMsg::Out() << std::endl;
}
OpenOutput(out, in, inPos);
out.write(begPtr, match.position(0));
begPtr = (const char*)mapPtr;
begPtr += match.position(0);
std::regex_replace(
std::ostreambuf_iterator<char>(out),
begPtr,
endPtr,
grepLinePat, replaceStr, flags);
mapFile.Close();
if (out)
{
out.close();
if (!BackupAndRenameFile())
break;
}
}
}
else
{
LLMsg::PresentError(GetLastError(), "Open failed,", m_srcPath);
}
} while (didReplace && m_grepOpt.repeatReplace);
}
}
catch (...)
{
}
}
else
{
LLMsg::PresentError(0, "Replace ignored,", pFileData->cFileName, " Not writeable\n");
}
return matchCnt;
}
// ---------------------------------------------------------------------------
bool LLReplace::BackupAndRenameFile()
{
// U(i|b) Update inplace or make backup.
if (m_grepOpt.update == 'b')
{
int error = rename(m_srcPath, (m_srcPath + ".bak").c_str());
if (error != 0)
{
LLMsg::PresentError(GetLastError(), "Failed to make backup\n", m_srcPath);
RemoveTmpFile();
return false;
}
}
if (!m_tmpOutFilename.empty() && m_tmpOutFilename != m_srcPath)
{
// int error = renameFiles(m_tmpOutFilename.c_str(), m_srcPath.c_str());
if (0 == MoveFileEx(m_tmpOutFilename.c_str(), m_srcPath.c_str(), MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
{
DWORD lastError = GetLastError();
LLMsg::PresentError(lastError, "Renaming tmp failed\n", m_srcPath);
RemoveTmpFile();
return false;
}
}
return true;
}
// ---------------------------------------------------------------------------
void LLReplace::RemoveTmpFile()
{
if (m_tmpOutFilename != m_srcPath)
DeleteFile(m_tmpOutFilename.c_str());
}
// ---------------------------------------------------------------------------
std::ofstream& LLReplace::OpenOutput(
std::ofstream& out, std::ifstream& in, std::streampos& inPos)
{
int outMode = std::ios::out | std::ios::binary;
// U(i|b) Update inplace or make backup.
if (m_grepOpt.update == 'i')
{
m_tmpOutFilename = m_srcPath;
out.open(m_srcPath, outMode, _SH_DENYNO);
out.seekp(inPos);
}
else
{
m_tmpOutFilename = m_srcPath + "_tmp_XXXXXX";
m_tmpOutFilename.push_back('\0');
_mktemp_s((char*)m_tmpOutFilename.c_str(), m_tmpOutFilename.length());
out.open(m_tmpOutFilename, outMode, _SH_DENYNO);
}
streamoff inOff = inPos;
if (out && in && inOff > 0)
{
size_t inLen = (size_t)inOff;
m_tmpBuffer.resize(min(8192, inLen));
std::streamsize inCnt = 1;
while (inLen > 0 && inCnt > 0)
{
inCnt = in.read(m_tmpBuffer.data(), m_tmpBuffer.size()).gcount();
if (inCnt > 0)
{
out.write(m_tmpBuffer.data(), inCnt);
inLen -= (size_t)inCnt;
m_tmpBuffer.resize(min(8192, inLen));
}
}
}
return out;
}
// ---------------------------------------------------------------------------
void LLReplace::ResetGrepColor()
{
if (!m_grepOpt.hideColor)
SetColor(sConfig.m_colorNormal);
}
// ---------------------------------------------------------------------------
void LLReplace::SetGrepColor(WORD color)
{
if (!m_grepOpt.hideColor)
SetColor(color);
}
| 34.624422
| 145
| 0.487285
|
landenlabs2
|
bbfee8b354473cc0810a75cd95d35b2a0f88ad3c
| 169
|
hpp
|
C++
|
src/uproar/config/version.hpp
|
tiger-chan/lib-gradient-noise
|
66eb8186b10f7507b437a81a4c6be16fcad5ccaf
|
[
"MIT"
] | null | null | null |
src/uproar/config/version.hpp
|
tiger-chan/lib-gradient-noise
|
66eb8186b10f7507b437a81a4c6be16fcad5ccaf
|
[
"MIT"
] | null | null | null |
src/uproar/config/version.hpp
|
tiger-chan/lib-gradient-noise
|
66eb8186b10f7507b437a81a4c6be16fcad5ccaf
|
[
"MIT"
] | null | null | null |
#ifndef UPROAR_CONFIG_VERSION_HPP
#define UPROAR_CONFIG_VERSION_HPP
#define UPROAR_VERSION_MAJOR 0
#define UPROAR_VERSION_MINOR 1
#define UPROAR_VERSION_PATCH 0
#endif
| 21.125
| 33
| 0.87574
|
tiger-chan
|
bbffb946d5ad4823637f463fcf7240bff13b2bc7
| 1,736
|
cpp
|
C++
|
src/MapEditor/Controls/ResourcePreview.cpp
|
vitek-karas/WarPlusPlus
|
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
|
[
"MIT"
] | 4
|
2019-06-17T13:44:49.000Z
|
2021-01-19T10:39:48.000Z
|
src/MapEditor/Controls/ResourcePreview.cpp
|
vitek-karas/WarPlusPlus
|
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
|
[
"MIT"
] | null | null | null |
src/MapEditor/Controls/ResourcePreview.cpp
|
vitek-karas/WarPlusPlus
|
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
|
[
"MIT"
] | 4
|
2019-06-17T16:03:20.000Z
|
2020-02-15T09:14:30.000Z
|
// ResourcePreview.cpp : implementation file
//
#include "stdafx.h"
#include "..\MapEditor.h"
#include "ResourcePreview.h"
#include "Common\Map\Map.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CResourcePreview
CResourcePreview::CResourcePreview()
{
m_pResource = NULL;
}
CResourcePreview::~CResourcePreview()
{
}
BEGIN_MESSAGE_MAP(CResourcePreview, CStatic)
//{{AFX_MSG_MAP(CResourcePreview)
ON_WM_DESTROY()
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CResourcePreview message handlers
void CResourcePreview::Create(CRect &rcBound, DWORD dwStyle, CWnd *pParent, UINT nID)
{
m_Buffer.SetWidth(RESOURCE_ICON_WIDTH);
m_Buffer.SetHeight(RESOURCE_ICON_HEIGHT);
m_Buffer.Create();
CStatic::Create("", dwStyle, rcBound, pParent, nID);
m_Clipper.Create(this);
}
void CResourcePreview::SetResource(CEResource *pResource)
{
m_pResource = pResource;
Invalidate();
}
void CResourcePreview::OnDestroy()
{
CStatic::OnDestroy();
m_Buffer.Delete();
m_Clipper.Delete();
}
void CResourcePreview::OnPaint()
{
CPaintDC dc(this); // device context for painting
g_pDDPrimarySurface->SetClipper(&m_Clipper);
CRect rcClient;
GetClientRect(&rcClient);
CBrush brush;
brush.CreateSolidBrush(RGB(192, 192, 192));
dc.FillRect(&rcClient, &brush);
brush.DeleteObject();
ClientToScreen(&rcClient);
if(m_pResource != NULL){
m_Buffer.Fill(RGB32(192, 192, 192));
m_Buffer.Paste(0, 0, m_pResource->GetIcon());
g_pDDPrimarySurface->Paste(rcClient.TopLeft(), &m_Buffer);
}
}
| 21.170732
| 85
| 0.667051
|
vitek-karas
|
0101e91b7672bcb40bcd0c23fffae67aab0ac75b
| 1,013
|
cpp
|
C++
|
Examples/HttpRequest/HttpRequest.cpp
|
Rprop/RLib
|
bb94d51d69a2207b073a779a871336288ca733d1
|
[
"Unlicense"
] | 23
|
2018-04-23T15:46:24.000Z
|
2022-01-10T14:03:57.000Z
|
Examples/HttpRequest/HttpRequest.cpp
|
boyliang/RLib
|
bb94d51d69a2207b073a779a871336288ca733d1
|
[
"Unlicense"
] | 1
|
2017-07-24T05:13:03.000Z
|
2017-07-24T08:59:48.000Z
|
Examples/HttpRequest/HttpRequest.cpp
|
boyliang/RLib
|
bb94d51d69a2207b073a779a871336288ca733d1
|
[
"Unlicense"
] | 13
|
2018-05-11T15:53:12.000Z
|
2021-09-29T11:57:16.000Z
|
/********************************************************************
Created: 2016/07/18 19:15
Filename: HttpRequest.cpp
Author: rrrfff
Url: http://blog.csdn.net/rrrfff
*********************************************************************/
#include <RLib_Import.h>
//-------------------------------------------------------------------------
int __stdcall WinMain(__in HINSTANCE /*hInstance*/, __in_opt HINSTANCE /*hPrevInstance*/,
__in LPSTR /*lpCmdLine*/, __in int /*nShowCmd*/)
{
// WebClient is a wrapper class for HttpRequest/HttpResponse,
// and platform-independent in a sense.
// performs a HTTP GET request and gets response as string
String page = WebClient::GetResponseText(_R("http://rlib.cf/"));
// also, HTTPS/SSL is supported.
String ssl_page = WebClient::GetResponseText(_R("https://www.alipay.com/"));
// performs a HTTP POST request with string data
String post_page = WebClient::PostResponseText(_R("http://rlib.cf/"), _R("post data"));
return STATUS_SUCCESS;
}
| 37.518519
| 89
| 0.564659
|
Rprop
|
0103f8b329e5a819235bf2666b085c39756a107b
| 411
|
cpp
|
C++
|
enduser/zone_internetgames/src/client/shell/zonecli/debug.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
enduser/zone_internetgames/src/client/shell/zonecli/debug.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
enduser/zone_internetgames/src/client/shell/zonecli/debug.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
#include "zui.h"
#ifdef _DEBUG
#undef CreatePen
#undef CreateSolidBrush
HPEN MyCreatePen(int fnPenStyle, int nWidth, COLORREF crColor)
{
HPEN hPen = CreatePen(fnPenStyle, nWidth, crColor);
if (!hPen) {
_asm {int 3};
}
return hPen;
}
HBRUSH MyCreateSolidBrush(COLORREF crColor)
{
HBRUSH hBr = CreateSolidBrush(crColor);
if (!hBr) {
_asm {int 3};
}
return hBr;
}
#endif
| 15.222222
| 63
| 0.659367
|
npocmaka
|
010667525fb6e5965c1a1815abb558c4e033d42a
| 574
|
hpp
|
C++
|
src/menu.hpp
|
matyalatte/2dPolyTo3d
|
be5ed4e871bd65c704ff12664f44e1aae5c89b24
|
[
"MIT"
] | null | null | null |
src/menu.hpp
|
matyalatte/2dPolyTo3d
|
be5ed4e871bd65c704ff12664f44e1aae5c89b24
|
[
"MIT"
] | null | null | null |
src/menu.hpp
|
matyalatte/2dPolyTo3d
|
be5ed4e871bd65c704ff12664f44e1aae5c89b24
|
[
"MIT"
] | null | null | null |
/*
* File: menu.hpp
* --------------------
* @author Matyalatte
* @version 2021/09/14
* - initial commit
*/
#pragma once
#include <GL/glut.h>
#include "2dpoly_to_3d/2dpoly_to_3d.hpp"
#include "2dpoly_to_3d/utils.hpp"
namespace openglHandler {
//functions for popup menu in glut
void menu(int item);
void menuInit();
void checkUpdateMenu();
void connectPolyTo3D(sketch3D::poly_to_3D* p_to_3d);
bool getSetModelFlag();
void resetSetModelFlag();
bool getShowNormal();
bool getShow2DPoly();
bool getShowModel();
bool getExitFlag();
void resetExitFlag();
}
| 19.133333
| 53
| 0.698606
|
matyalatte
|
01069effde8f24ee53ea22b955062e516f748cc6
| 551
|
hpp
|
C++
|
libadb/include/libadb/api/rate/data/rate-limit-scope.hpp
|
faserg1/adb
|
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
|
[
"MIT"
] | 1
|
2022-03-10T15:14:13.000Z
|
2022-03-10T15:14:13.000Z
|
libadb/include/libadb/api/rate/data/rate-limit-scope.hpp
|
faserg1/adb
|
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
|
[
"MIT"
] | 9
|
2022-03-07T21:00:08.000Z
|
2022-03-15T23:14:52.000Z
|
libadb/include/libadb/api/rate/data/rate-limit-scope.hpp
|
faserg1/adb
|
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
|
[
"MIT"
] | null | null | null |
#pragma once
#include <libadb/libadb.hpp>
#include <string>
namespace adb::api
{
/**
* @brief Rate Limit Scope
* @details https://discord.com/developers/docs/topics/rate-limits#header-format
*/
enum class RateLimitScope
{
/// per bot or user limit
User,
/// per bot or user global limit
Global,
/// per resource limit
Shared
};
LIBADB_API void from_string(const std::string &str, RateLimitScope &limit);
LIBADB_API std::string to_string(RateLimitScope limit);
}
| 22.958333
| 84
| 0.627949
|
faserg1
|
010bb5f3e0d991ec046b566798542dabef4e5cdf
| 5,071
|
cpp
|
C++
|
dev/velocities_sidecar/VelocitySideCar.cpp
|
nyue/SegmentedInterpolativeMotionBlurAlembic
|
1f02ff5516b6e114410b5977885133bb4b5bb490
|
[
"Apache-2.0"
] | 1
|
2020-12-28T23:33:00.000Z
|
2020-12-28T23:33:00.000Z
|
dev/velocities_sidecar/VelocitySideCar.cpp
|
nyue/SegmentedInterpolativeMotionBlurAlembic
|
1f02ff5516b6e114410b5977885133bb4b5bb490
|
[
"Apache-2.0"
] | null | null | null |
dev/velocities_sidecar/VelocitySideCar.cpp
|
nyue/SegmentedInterpolativeMotionBlurAlembic
|
1f02ff5516b6e114410b5977885133bb4b5bb490
|
[
"Apache-2.0"
] | 1
|
2018-10-10T11:49:02.000Z
|
2018-10-10T11:49:02.000Z
|
#include "VelocitySideCar.h"
#include <boost/tokenizer.hpp>
#include <cryptopp/sha.h>
#include <cryptopp/hex.h>
#include <cryptopp/files.h>
VelocitySideCar::VelocitySideCar()
{
}
VelocitySideCar::~VelocitySideCar()
{
}
const std::string& VelocitySideCar::get_sha() const
{
return _source_sha;
};
bool VelocitySideCar::compute(const std::string& i_alembic_source, const std::string& i_regex_pattern)
{
compute_sha(i_alembic_source, _source_sha);
Alembic::AbcCoreFactory::IFactory factory;
Alembic::AbcCoreFactory::IFactory::CoreType oType;
_archive_ptr.reset(new Alembic::Abc::IArchive(factory.getArchive(i_alembic_source, oType)));
Alembic::Abc::IObject top = _archive_ptr->getTop();
size_t top_num_children = top.getNumChildren();
std::cout << "top_num_children = " << top_num_children << std::endl;
std::string top_name = top.getName();
std::cout << "top_name = " << top_name << std::endl;
PathList path;
TokenizePath( std::string("/grid_object1/grid1"), path );
PathList::const_iterator I = path.begin();
const Alembic::Abc::ObjectHeader *nextChildHeader = top.getChildHeader (*I);
for ( size_t i = 0; i < top.getNumChildren(); ++i )
{
iterate_iobject( top, top.getChildHeader(i),i_regex_pattern, I+1,path.end());
}
return true;
}
void VelocitySideCar::ProcessIPolyMesh(const Alembic::AbcGeom::IPolyMesh& i_polymesh,
const std::string& i_regex_pattern)
{
// Alembic::Abc::ISampleSelector next_sample_selector(requested_index+1);
//
// Alembic::AbcGeom::IPolyMeshSchema::Sample next_sample;
// pmesh.getSchema().get( next_sample, next_sample_selector );
}
void VelocitySideCar::iterate_iobject(Alembic::Abc::IObject parent,
const Alembic::Abc::ObjectHeader& ohead,
const std::string& i_regex_pattern,
PathList::const_iterator I,
PathList::const_iterator E)
{
std::cout << "iterate_iobject ohead's name = " << ohead.getName().c_str() << std::endl;
std::cout << "iterate_iobject ohead's full name = " << ohead.getFullName().c_str() << std::endl;
//set this if we should continue traversing
Alembic::Abc::IObject nextParentObject;
if ( Alembic::AbcGeom::IXform::matches( ohead ) )
{
std::cout << "iterate_iobject match IXform" << std::endl;
Alembic::AbcGeom::IXform xform( parent, ohead.getName() );
nextParentObject = xform;
}
else if ( Alembic::AbcGeom::ISubD::matches( ohead ) )
{
std::cout << "iterate_iobject match ISubD" << std::endl;
Alembic::AbcGeom::ISubD subd( parent, ohead.getName() );
nextParentObject = subd;
}
else if ( Alembic::AbcGeom::IPolyMesh::matches( ohead ) )
{
std::cout << "iterate_iobject match IPolyMesh" << std::endl;
Alembic::AbcGeom::IPolyMesh polymesh( parent, ohead.getName() );
ProcessIPolyMesh(polymesh, i_regex_pattern);
nextParentObject = polymesh;
}
else if ( Alembic::AbcGeom::INuPatch::matches( ohead ) )
{
std::cout << "iterate_iobject match INuPatch" << std::endl;
}
else if ( Alembic::AbcGeom::IPoints::matches( ohead ) )
{
std::cout << "iterate_iobject match IPoints" << std::endl;
Alembic::AbcGeom::IPoints points( parent, ohead.getName() );
// ProcessIPoints(points);
nextParentObject = points;
}
else if ( Alembic::AbcGeom::ICurves::matches( ohead ) )
{
std::cout << "iterate_iobject match ICurves" << std::endl;
}
else if ( Alembic::AbcGeom::IFaceSet::matches( ohead ) )
{
std::cout << "iterate_iobject match IFaceSet" << std::endl;
std::cerr << "DOH !" << std::endl;
}
// Recursion
if ( nextParentObject.valid() )
{
for ( size_t i = 0; i < nextParentObject.getNumChildren() ; ++i )
{
iterate_iobject( nextParentObject, nextParentObject.getChildHeader( i ), i_regex_pattern, I, E);
}
}
}
void VelocitySideCar::TokenizePath( const std::string &path, PathList& result ) const
{
typedef boost::char_separator<char> Separator;
typedef boost::tokenizer<Separator> Tokenizer;
Tokenizer tokenizer( path, Separator( "/" ) );
for ( Tokenizer::iterator iter = tokenizer.begin() ; iter != tokenizer.end() ;
++iter )
{
if ( (*iter).empty() )
{
continue;
}
std::cout << "*iter = " << *iter << std::endl;
result.push_back( *iter );
}
}
void compute_sha(const std::string& i_filename, std::string& o_sha)
{
CryptoPP::SHA1 hash;
CryptoPP::FileSource(i_filename.c_str(),true,
new CryptoPP::HashFilter(hash, new CryptoPP::HexEncoder(
new CryptoPP::StringSink(o_sha), true)));
}
// == Emacs ================
// -------------------------
// Local variables:
// tab-width: 4
// indent-tabs-mode: t
// c-basic-offset: 4
// end:
//
// == vi ===================
// -------------------------
// Format block
// ex:ts=4:sw=4:expandtab
// -------------------------
| 30.733333
| 108
| 0.622165
|
nyue
|
010f361df1b18f8efcd37aec4d5169dcb9350ed1
| 5,117
|
cpp
|
C++
|
src/Snake.cpp
|
robifr/snake
|
611c6cc0460a92cca7e033108be13510aeba6b69
|
[
"MIT"
] | null | null | null |
src/Snake.cpp
|
robifr/snake
|
611c6cc0460a92cca7e033108be13510aeba6b69
|
[
"MIT"
] | null | null | null |
src/Snake.cpp
|
robifr/snake
|
611c6cc0460a92cca7e033108be13510aeba6b69
|
[
"MIT"
] | null | null | null |
#include <cmath> //floor
#include "Snake.hpp"
#include "Game.hpp"
#include "View.hpp"
Snake::Snake(Game& game) :
game_(game) {
}
void Snake::changeDirection(int keyCode) {
int deltaX = 0, deltaY = 0;
switch (keyCode) {
case SDLK_UP:
case SDLK_w:
deltaX = 0;
deltaY = -this->game_.gridHeight;
break;
case SDLK_DOWN:
case SDLK_s:
deltaX = 0;
deltaY = this->game_.gridHeight;
break;
case SDLK_LEFT:
case SDLK_a:
deltaX = -this->game_.gridWidth;
deltaY = 0;
break;
case SDLK_RIGHT:
case SDLK_d:
deltaX = this->game_.gridWidth;
deltaY = 0;
break;
default: return;
}
const bool isTryingToMoveDownWhileMovingUp = deltaY > this->deltaY_ && this->deltaY_ < 0;
const bool isTryingToMoveUpWhileMovingDown = deltaY < this->deltaY_ && this->deltaY_ >= 0;
const bool isTryingToMoveRightWhileMovingLeft = deltaX > this->deltaY_ && this->deltaX_ < 0;
const bool isTryingToMoveLeftWhileMovingRight = deltaX < this->deltaX_ && this->deltaX_ >= 0;
//disallow snake to move towards their current opposite direction.
//e.g. if the snake is currently moving up, user shouldn't be able to move down, and vice versa.
if (!isTryingToMoveUpWhileMovingDown
|| !isTryingToMoveDownWhileMovingUp
|| !isTryingToMoveLeftWhileMovingRight
|| !isTryingToMoveRightWhileMovingLeft) {
//compute next head position ahead before doing movement.
//ensuring the head won't eat its own neck,
//because of user changing direction way too fast.
if (this->body_.size() >= 1) {
std::pair<int, int> nextPosition = this->nextHeadPosition_(deltaX, deltaY);
if (nextPosition.first == this->body_[1].x
&& nextPosition.second == this->body_[1].y) {
return;
}
}
this->deltaX_ = deltaX;
this->deltaY_ = deltaY;
}
}
void Snake::move() {
for (int i = this->body_.size() - 1; i >= 0; i--) {
//snake head.
if (i == 0) {
std::pair<int, int> position = this->nextHeadPosition_(this->deltaX_, this->deltaY_);
this->body_[i].x = position.first;
this->body_[i].y = position.second;
if (this->isEatingOwnBody_(this->body_[i].x, this->body_[i].y)) this->isAlive = false;
if (this->isEatingFood_(this->body_[i].x, this->body_[i].y, this->game_.food)) {
this->foodEaten_++;
this->addBody(
this->body_.back().x + this->deltaX_,
this->body_.back().y + this->deltaY_
);
this->game_.inGameView->setScore(this->foodEaten_);
this->game_.food->spawnRandom();
i--;
}
//every snake body follow their previous segment position.
} else if (i > 0) {
this->body_[i].x = this->body_[i - 1].x;
this->body_[i].y = this->body_[i - 1].y;
}
}
}
void Snake::addBody(int x, int y) {
SDL_Rect newBody = { x, y, this->game_.gridWidth, this->game_.gridHeight };
this->body_.push_back(newBody);
}
void Snake::respawn() {
const int gridWidth = this->game_.gridWidth;
const int gridHeight = this->game_.gridHeight;
const int x = std::floor(this->game_.windowSurface->w / 2 / gridWidth) * gridWidth;
const int y = std::floor(this->game_.windowSurface->h / 2 / gridHeight) * gridHeight;
this->deltaX_ = 0;
this->deltaY_ = -15; //move to top as the default position.
this->foodEaten_ = 0;
this->body_.clear();
for (int i = 0; i < 3; i++) {
this->addBody(x, y + (gridHeight * i));
}
}
void Snake::render() {
for (int i = 0; i < this->body_.size(); i++) {
SDL_SetRenderDrawColor(this->game_.renderer().get(), 220, 20, 60, 225); //red.
SDL_RenderFillRect(this->game_.renderer().get(), &this->body_[i]);
}
}
bool Snake::isEatingFood_(int x, int y, const std::unique_ptr<Food>& food) {
if (x == food->body().x && y == food->body().y) return true;
return false;
}
bool Snake::isEatingOwnBody_(int x, int y) {
for (int i = 1; i < this->body_.size(); i++) {
if (x == this->body_[i].x
&& y == this->body_[i].y) {
return true;
}
}
return false;
}
std::pair<int, int> Snake::nextHeadPosition_(int deltaX, int deltaY) {
const int yMin = this->game_.inGameView->scoreContainer.h;
const int xMax = this->game_.windowSurface->w - this->game_.gridWidth;
const int yMax = this->game_.windowSurface->h - this->game_.gridHeight;
int x = this->body_[0].x + deltaX;
int y = this->body_[0].y + deltaY;
if (x > xMax) {
x = 0;
} else if (x < 0) {
x = xMax;
}
if (y > yMax) {
y = yMin;
} else if (y < yMin) {
y = yMax;
}
return std::make_pair(x, y);
}
| 31.392638
| 100
| 0.555599
|
robifr
|
0113774bc56dbc38bad5b3751e4987a5c42fbff2
| 1,534
|
hpp
|
C++
|
src/messaging/MessageHandler.hpp
|
Fabi2607/MazeNet-Client
|
1fcb0b3cbeeab123cb69cd18070e0bbf4907130c
|
[
"MIT"
] | null | null | null |
src/messaging/MessageHandler.hpp
|
Fabi2607/MazeNet-Client
|
1fcb0b3cbeeab123cb69cd18070e0bbf4907130c
|
[
"MIT"
] | null | null | null |
src/messaging/MessageHandler.hpp
|
Fabi2607/MazeNet-Client
|
1fcb0b3cbeeab123cb69cd18070e0bbf4907130c
|
[
"MIT"
] | null | null | null |
#ifndef MAZENET_CLIENT_MESSAGEHANDLER_HPP
#define MAZENET_CLIENT_MESSAGEHANDLER_HPP
#include <string>
#include <player/IPlayerStrategy.hpp>
#include "../messaging/mazeCom.hxx"
#include "../player/GameSituation.hpp"
#include "../util/logging/Log.hpp"
#include "MessageDispatcher.hpp"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++" //Ignoring the warning.
class MessageHandler {
public:
MessageHandler(std::shared_ptr<IPlayerStrategy> strategy, MessageDispatcher& dispatcher);
void handle_incoming_message(const std::string& message);
private:
void handle_login_reply(const LoginReplyMessageType& reply);
void handle_await_move(const AwaitMoveMessageType& await_move);
void handle_accept_message(const AcceptMessageType& accept_message);
void handle_win_message(const WinMessageType& win_message);
void handle_disconnect_message(const DisconnectMessageType& disconnect_message);
void update_model(const AwaitMoveMessageType& message);
void update_board(const boardType& board);
std::shared_ptr<MazeCom> deserialize(const std::string& msg);
std::shared_ptr<IPlayerStrategy> strategy_;
mazenet::util::logging::Log logger_;
MessageDispatcher& dispatcher_;
xsd::cxx::tree::error_handler<char> eh;
xsd::cxx::xml::dom::bits::error_handler_proxy<char> ehp;
xercesc::DOMImplementation* impl;
xml_schema::dom::unique_ptr<xercesc::DOMLSParser> parser;
xercesc::DOMConfiguration* conf_r;
};
#pragma GCC diagnostic pop
#endif /* MAZENET_CLIENT_MESSAGEHANDLER_HPP */
| 27.392857
| 91
| 0.789439
|
Fabi2607
|
011567e9d19e6b5d02b15b496bc71cf9d07e8bf7
| 7,215
|
hpp
|
C++
|
scicpp/core/meta.hpp
|
tvanderbruggen/SciCpp
|
09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46
|
[
"MIT"
] | 2
|
2021-08-02T09:03:30.000Z
|
2022-02-17T11:58:05.000Z
|
scicpp/core/meta.hpp
|
tvanderbruggen/SciCpp
|
09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46
|
[
"MIT"
] | null | null | null |
scicpp/core/meta.hpp
|
tvanderbruggen/SciCpp
|
09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46
|
[
"MIT"
] | null | null | null |
// SPDX-License-Identifier: MIT
// Copyright (c) 2019-2021 Thomas Vanderbruggen <th.vanderbruggen@gmail.com>
#ifndef SCICPP_CORE_META
#define SCICPP_CORE_META
#include <Eigen/Dense>
#include <array>
#include <complex>
#include <ratio>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace scicpp::meta {
//---------------------------------------------------------------------------------
// is_complex
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_complex : std::false_type {};
template <class T>
struct is_complex<std::complex<T>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_complex_v = detail::is_complex<T>::value;
template <typename T>
using enable_if_complex = std::enable_if_t<is_complex_v<T>, int>;
template <typename T>
using disable_if_complex = std::enable_if_t<!is_complex_v<T>, int>;
//---------------------------------------------------------------------------------
// is_iterable
//---------------------------------------------------------------------------------
// https://stackoverflow.com/questions/13830158/check-if-a-variable-is-iterable
namespace detail {
// To allow ADL with custom begin/end
using std::begin;
using std::end;
template <typename T>
auto is_iterable_impl(int) -> decltype(
begin(std::declval<T &>()) !=
end(std::declval<T &>()), // begin/end and operator !=
void(), // Handle evil operator ,
++std::declval<decltype(begin(std::declval<T &>())) &>(), // operator ++
void(*begin(std::declval<T &>())), // operator*
std::true_type{});
template <typename T>
std::false_type is_iterable_impl(...);
template <typename T>
using is_iterable = decltype(detail::is_iterable_impl<T>(0));
} // namespace detail
template <typename T>
constexpr bool is_iterable_v = detail::is_iterable<T>::value;
template <typename T>
using enable_if_iterable = std::enable_if_t<is_iterable_v<T>, int>;
template <typename T>
using disable_if_iterable = std::enable_if_t<!is_iterable_v<T>, int>;
//---------------------------------------------------------------------------------
// std::vector traits
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_std_vector : std::false_type {};
template <typename Scalar>
struct is_std_vector<std::vector<Scalar>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_std_vector_v = detail::is_std_vector<T>::value;
//---------------------------------------------------------------------------------
// std::array traits
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_std_array : std::false_type {};
template <typename Scalar, std::size_t N>
struct is_std_array<std::array<Scalar, N>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_std_array_v = detail::is_std_array<T>::value;
//---------------------------------------------------------------------------------
// std::tuple traits
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_std_tuple : std::false_type {};
template <typename... Args>
struct is_std_tuple<std::tuple<Args...>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_std_tuple_v = detail::is_std_tuple<T>::value;
//---------------------------------------------------------------------------------
// std::pair traits
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_std_pair : std::false_type {};
template <typename T1, typename T2>
struct is_std_pair<std::pair<T1, T2>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_std_pair_v = detail::is_std_pair<T>::value;
//---------------------------------------------------------------------------------
// subtuple
// https://stackoverflow.com/questions/17854219/creating-a-sub-tuple-starting-from-a-stdtuplesome-types
//---------------------------------------------------------------------------------
namespace detail {
template <typename... T, std::size_t... I>
constexpr auto subtuple_(const std::tuple<T...> &t,
std::index_sequence<I...> /*unused*/) {
return std::make_tuple(std::get<I>(t)...);
}
} // namespace detail
template <int Trim, typename... T>
constexpr auto subtuple(const std::tuple<T...> &t) {
return detail::subtuple_(t,
std::make_index_sequence<sizeof...(T) - Trim>());
}
template <int Trim = 1, typename T1, typename T2>
constexpr auto subtuple(const std::pair<T1, T2> &t) {
return std::make_tuple(t.first);
}
//---------------------------------------------------------------------------------
// is_ratio
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_ratio : std::false_type {};
template <intmax_t num, intmax_t den>
struct is_ratio<std::ratio<num, den>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_ratio_v = detail::is_ratio<T>::value;
//---------------------------------------------------------------------------------
// Eigen type traits
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_eigen_matrix : std::false_type {};
template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>
struct is_eigen_matrix<
Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime>>
: std::true_type {};
template <class T>
struct is_eigen_array : std::false_type {};
template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>
struct is_eigen_array<
Eigen::Array<Scalar, RowsAtCompileTime, ColsAtCompileTime>>
: std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_eigen_matrix_v = detail::is_eigen_matrix<T>::value;
template <class T>
constexpr bool is_eigen_array_v = detail::is_eigen_array<T>::value;
template <class T>
constexpr bool is_eigen_container_v =
is_eigen_matrix_v<T> || is_eigen_array_v<T>;
//---------------------------------------------------------------------------------
// is_predicate
//---------------------------------------------------------------------------------
template <class Predicate, class... Args>
constexpr bool is_predicate =
std::is_integral_v<std::invoke_result_t<Predicate, Args...>>;
//---------------------------------------------------------------------------------
// is_string
//---------------------------------------------------------------------------------
template <class T>
constexpr bool is_string_v =
std::is_same_v<const char *, typename std::decay_t<T>> ||
std::is_same_v<char *, typename std::decay_t<T>> ||
std::is_same_v<std::string, typename std::decay_t<T>>;
} // namespace scicpp::meta
#endif // SCICPP_CORE_META
| 30.315126
| 103
| 0.527235
|
tvanderbruggen
|
01164e1a7b0fb27f09b533c80c93d554c7f8dd74
| 2,332
|
cpp
|
C++
|
mini/io/path.cpp
|
stevefan1999/mini-tor
|
fbf82a5a394f15b68fc356c5a71af47a3e3863d3
|
[
"MIT"
] | 2
|
2018-03-30T22:29:23.000Z
|
2019-04-22T11:46:29.000Z
|
mini/io/path.cpp
|
FingerLeakers/mini-tor
|
fbf82a5a394f15b68fc356c5a71af47a3e3863d3
|
[
"MIT"
] | null | null | null |
mini/io/path.cpp
|
FingerLeakers/mini-tor
|
fbf82a5a394f15b68fc356c5a71af47a3e3863d3
|
[
"MIT"
] | 1
|
2019-12-29T17:53:05.000Z
|
2019-12-29T17:53:05.000Z
|
#include "path.h"
namespace mini::io {
string
path::combine(
const string_ref p1,
const string_ref p2
)
{
string result = p1;
if (!p1.ends_with(directory_separator) && !p1.ends_with(alternative_directory_separator))
{
result += directory_separator;
}
result += p2;
return result;
}
string_collection
path::split(
const string_ref p
)
{
//
// TODO:
// take alternative_directory_separator into account.
//
auto result = p.split(directory_separator);
//
// always end drive letter with '\'.
//
if (result.get_size() > 0 && result[0].get_size() > 1)
{
string& drive_letter = result[0];
if (drive_letter[1] == ':')
{
drive_letter += directory_separator;
}
}
return result;
}
string_ref
path::get_file_name(
const string_ref p
)
{
size_type name_offset = p.last_index_of(directory_separator);
if (name_offset == string_ref::not_found)
{
name_offset = p.last_index_of(alternative_directory_separator);
}
if (name_offset == string_ref::not_found || (name_offset + 1) >= p.get_size())
{
return string_ref::empty;
}
return p.substring(name_offset + 1);
}
string_ref
path::get_directory_name(
const string_ref p
)
{
size_type name_offset = p.last_index_of(directory_separator);
if (name_offset == string_ref::not_found)
{
name_offset = p.last_index_of(alternative_directory_separator);
}
return p.substring(0, name_offset);
}
string_ref
path::get_filename_without_extension(
const string_ref p
)
{
size_type name_offset = p.last_index_of(directory_separator);
if (name_offset == string_ref::not_found)
{
name_offset = p.last_index_of(alternative_directory_separator);
}
if (name_offset == string_ref::not_found || (name_offset + 1) >= p.get_size())
{
return string_ref::empty;
}
string_ref result = p.substring(name_offset + 1);
size_type extension_offset = result.last_index_of(extension_separator);
return result.substring(0, extension_offset);
}
string_ref
path::get_extension(
const string_ref p
)
{
string_ref file_name = get_file_name(p);
size_type extension_offset = file_name.last_index_of(extension_separator);
if (extension_offset != string_ref::not_found)
{
return file_name.substring(extension_offset);
}
return string_ref::empty;
}
}
| 18.656
| 91
| 0.701115
|
stevefan1999
|
011928a30f96a3f6ebfb64f374f0d4bf5bebeaba
| 11,070
|
cpp
|
C++
|
src/caffe/test/test_serialization_blob_codec.cpp
|
shayanshams66/caffe
|
3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e
|
[
"Intel",
"BSD-2-Clause"
] | 1
|
2017-01-04T03:35:46.000Z
|
2017-01-04T03:35:46.000Z
|
src/caffe/test/test_serialization_blob_codec.cpp
|
shayanshams66/caffe
|
3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e
|
[
"Intel",
"BSD-2-Clause"
] | null | null | null |
src/caffe/test/test_serialization_blob_codec.cpp
|
shayanshams66/caffe
|
3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e
|
[
"Intel",
"BSD-2-Clause"
] | null | null | null |
#include <boost/assign.hpp>
#include <glog/logging.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <vector>
#include "caffe/internode/configuration.hpp"
#include "caffe/serialization/BlobCodec.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
namespace {
using ::testing::_;
using ::testing::Return;
template <typename TypeParam>
class BlobCodecTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
};
TYPED_TEST_CASE(BlobCodecTest, TestDtypesAndDevices);
TYPED_TEST(BlobCodecTest, encode_4321_diff) {
BlobUpdate msg;
Blob<float> srcblob;
vector<int> v = boost::assign::list_of(4)(3)(2)(1);
srcblob.Reshape(v);
vector<float> diff = boost::assign::list_of(999.99)(12.3)(0.1)(-3.3)
(+2.0)(12.3)(10.2)(FLT_MAX)
(+4.4)(12.3)(0.0)(-1.3)
(+6.5)(12.3)(24.42)(1010.10)
(FLT_MIN)(12.3)(66.6)(133.1)
(12.4)(12.3)(0.0001)(100.3);
ASSERT_EQ(diff.size(), srcblob.count());
caffe_copy(srcblob.count(),
&diff.front(),
srcblob.mutable_cpu_diff());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part());
EXPECT_EQ(0, memcmp(msg.data().c_str(), &diff.front(),
sizeof(float)*diff.size()));
}
TYPED_TEST(BlobCodecTest, encode_decode_2222_data) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(2)(2)(2)(2);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data = boost::assign::list_of(1.1)(-2.2)(3.3)(5.5)
(6.6)(-7.7)(8.8)(9.9)
(13.13)(-12.12)(12.12)(11.11)
(128.128)(-132.312)(1.1)(-10.10);
vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0)
(0.0)(0.0)(0.0)(0.0)
(0.0)(0.0)(0.0)(0.0)
(0.0)(0.0)(0.0)(0.0);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_zero.size(), dstblob.count());
caffe_copy<float>(srcblob.count(),
&data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(),
&data_zero.front(),
dstblob.mutable_cpu_diff());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 1.0f, 0.0f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_8width_data_) {
BlobUpdate msg;
Blob<float> srcblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(8);
srcblob.Reshape(v);
vector<float> data = boost::assign::list_of(-0.0)(-0.3)(-2.2)(-3.3)
(+0.0)(12.3)(10.2)(-1.3);
ASSERT_EQ(data.size(), srcblob.count());
caffe_copy<float>(srcblob.count(),
&data.front(),
srcblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
EXPECT_EQ(0, memcmp(msg.data().c_str(), &data.front(),
sizeof(float)*data.size()));
}
TYPED_TEST(BlobCodecTest, encode_4width_diff) {
BlobUpdate msg;
Blob<float> srcblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
vector<float> diff = boost::assign::list_of(-0.0)(-99.99)(-0.3)(0.4);
ASSERT_EQ(diff.size(), srcblob.count());
caffe_copy<float>(srcblob.count(),
&diff.front(),
srcblob.mutable_cpu_diff());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part());
EXPECT_EQ(0, memcmp(msg.data().c_str(), &diff.front(),
sizeof(float)*diff.size()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_diff) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> diff_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0);
vector<float> diff = boost::assign::list_of(1.0)(2.2)(3.3)(4.4);
ASSERT_EQ(diff.size(), srcblob.count());
ASSERT_EQ(diff_zero.size(), srcblob.count());
caffe_copy<float>(srcblob.count(),
&diff.front(),
srcblob.mutable_cpu_diff());
caffe_copy<float>(dstblob.count(),
&diff_zero.front(),
dstblob.mutable_cpu_diff());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::GRADS, 1.0f, 0.0f);
EXPECT_EQ(0, memcmp(dstblob.cpu_diff(), &diff.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_data) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0);
vector<float> data = boost::assign::list_of(4.0)(3.2)(2.3)(1.4);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_zero.size(), srcblob.count());
caffe_copy<float>(srcblob.count(),
&data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(),
&data_zero.front(),
dstblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 1.0f, 0.0f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_5) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0);
vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
vector<float> data_expected = boost::assign::list_of(2.0)(1.6)(1.2)(0.7);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_zero.size(), srcblob.count());
caffe_copy<float>(srcblob.count(),
&data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(),
&data_zero.front(),
dstblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 0.5f, 0.0f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_data_beta_0_5) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data_one = boost::assign::list_of(1.0)(1.0)(1.0)(1.0);
vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
vector<float> data_expected = boost::assign::list_of(4.5)(3.7)(2.9)(1.9);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_one.size(), srcblob.count());
caffe_copy<float>(srcblob.count(), &data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(), &data_one.front(),
dstblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 1.0f, 0.5f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_5_beta_0_5) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data_one = boost::assign::list_of(1.0)(1.0)(1.0)(1.0);
vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
vector<float> data_expected = boost::assign::list_of(2.5)(2.1)(1.7)(1.2);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_one.size(), srcblob.count());
caffe_copy<float>(srcblob.count(), &data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(), &data_one.front(),
dstblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 0.5f, 0.5f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_beta_1) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data_one = boost::assign::list_of(1.1)(2.3)(1.4)(0.01);
vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
vector<float> data_expected = boost::assign::list_of(1.1)(2.3)(1.4)(0.01);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_one.size(), srcblob.count());
caffe_copy<float>(srcblob.count(), &data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(), &data_one.front(),
dstblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 0.0f, 1.0f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
sizeof(float)*dstblob.count()));
}
} // namespace
} // namespace caffe
| 35.594855
| 78
| 0.629901
|
shayanshams66
|
011b4ba53fe34216618e95c8053a379494fc392c
| 935
|
cpp
|
C++
|
rnn++/utils/math.cpp
|
uphere-co/nlp-prototype
|
c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3
|
[
"BSD-3-Clause"
] | null | null | null |
rnn++/utils/math.cpp
|
uphere-co/nlp-prototype
|
c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3
|
[
"BSD-3-Clause"
] | null | null | null |
rnn++/utils/math.cpp
|
uphere-co/nlp-prototype
|
c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3
|
[
"BSD-3-Clause"
] | null | null | null |
#include "utils/math.h"
namespace util{
namespace math{
template<>
float_t Fun<FunName::alog>(float_t x){auto one=decltype(x){1}; return std::log(std::abs(x)+one);}
template<>
float_t Fun<FunName::d_alog>(float_t x){auto one=decltype(x){1}; return one/(std::abs(x)+one);}
template<>
float_t Fun<FunName::tanh>(float_t x){return std::tanh(x);}
template<>
float_t Fun<FunName::d_tanh>(float_t x){auto fx=std::cosh(x);return decltype(x){1}/(fx*fx);}
template<>
float_t Fun<FunName::sig>(float_t x){return float_t{1}/(float_t{1}+std::exp(-x));}
template<>
float_t Fun<FunName::ax>(float_t x){return float_t{0.5}*x;}
template<>
float_t Fun<FunName::d_ax>(float_t ){return float_t{0.5};}
template<>
float_t Fun<FunName::test>(float_t x){return x>0?std::sqrt(x):-std::sqrt(-x);}
template<>
float_t Fun<FunName::d_test>(float_t x){return x>0?float_t{0.5}/std::sqrt(x):float_t{0.5}/std::sqrt(-x);}
}//namespace util::math
}//namespace util
| 33.392857
| 105
| 0.702674
|
uphere-co
|
011c439dc7e8a25e5bc7e16891e280f726793e53
| 24,133
|
hpp
|
C++
|
ddbtoaster/experiments/src/tpch/codegen_initial_submission_r3391/Tpch13VCpp.hpp
|
szarnyasg/dbtoaster-backend
|
24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73
|
[
"Apache-2.0"
] | 38
|
2017-09-29T08:12:31.000Z
|
2022-03-31T03:56:20.000Z
|
ddbtoaster/experiments/src/tpch/codegen_initial_submission_r3391/Tpch13VCpp.hpp
|
szarnyasg/dbtoaster-backend
|
24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73
|
[
"Apache-2.0"
] | 33
|
2018-04-05T02:42:39.000Z
|
2022-02-18T02:13:57.000Z
|
ddbtoaster/experiments/src/tpch/codegen_initial_submission_r3391/Tpch13VCpp.hpp
|
szarnyasg/dbtoaster-backend
|
24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73
|
[
"Apache-2.0"
] | 17
|
2017-09-29T08:16:00.000Z
|
2022-02-18T04:22:29.000Z
|
#include <sys/time.h>
#include "macro.hpp"
#include "types.hpp"
#include "functions.hpp"
#include "hash.hpp"
#include "hashmap.hpp"
#include "serialization.hpp"
#define ELEM_SEPARATOR "\n\t\t\t"
namespace dbtoaster {
/* Definitions of auxiliary maps for storing materialized views. */
struct CUSTDIST_entry {
long C_ORDERS_C_COUNT; long __av;
explicit CUSTDIST_entry() { /*C_ORDERS_C_COUNT = 0L; __av = 0L; */ }
explicit CUSTDIST_entry(const long c0, const long c1) { C_ORDERS_C_COUNT = c0; __av = c1; }
CUSTDIST_entry(const CUSTDIST_entry& other) : C_ORDERS_C_COUNT( other.C_ORDERS_C_COUNT ), __av( other.__av ) {}
FORCE_INLINE CUSTDIST_entry& modify(const long c0) { C_ORDERS_C_COUNT = c0; return *this; }
template<class Archive>
void serialize(Archive& ar, const unsigned int version) const
{
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, C_ORDERS_C_COUNT);
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, __av);
}
};
struct CUSTDIST_mapkey0_idxfn {
FORCE_INLINE static size_t hash(const CUSTDIST_entry& e) {
size_t h = 0;
hash_combine(h, e.C_ORDERS_C_COUNT);
return h;
}
FORCE_INLINE static bool equals(const CUSTDIST_entry& x, const CUSTDIST_entry& y) {
return x.C_ORDERS_C_COUNT == y.C_ORDERS_C_COUNT;
}
};
typedef MultiHashMap<CUSTDIST_entry,long,
HashIndex<CUSTDIST_entry,long,CUSTDIST_mapkey0_idxfn,true>
> CUSTDIST_map;
typedef HashIndex<CUSTDIST_entry,long,CUSTDIST_mapkey0_idxfn,true> HashIndex_CUSTDIST_map_0;
struct CUSTDIST_mCUSTOMER_IVC1_E1_1_entry {
long C_ORDERS_C_CUSTKEY; long __av;
explicit CUSTDIST_mCUSTOMER_IVC1_E1_1_entry() { /*C_ORDERS_C_CUSTKEY = 0L; __av = 0L; */ }
explicit CUSTDIST_mCUSTOMER_IVC1_E1_1_entry(const long c0, const long c1) { C_ORDERS_C_CUSTKEY = c0; __av = c1; }
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry(const CUSTDIST_mCUSTOMER_IVC1_E1_1_entry& other) : C_ORDERS_C_CUSTKEY( other.C_ORDERS_C_CUSTKEY ), __av( other.__av ) {}
FORCE_INLINE CUSTDIST_mCUSTOMER_IVC1_E1_1_entry& modify(const long c0) { C_ORDERS_C_CUSTKEY = c0; return *this; }
template<class Archive>
void serialize(Archive& ar, const unsigned int version) const
{
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, C_ORDERS_C_CUSTKEY);
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, __av);
}
};
struct CUSTDIST_mCUSTOMER_IVC1_E1_1_mapkey0_idxfn {
FORCE_INLINE static size_t hash(const CUSTDIST_mCUSTOMER_IVC1_E1_1_entry& e) {
size_t h = 0;
hash_combine(h, e.C_ORDERS_C_CUSTKEY);
return h;
}
FORCE_INLINE static bool equals(const CUSTDIST_mCUSTOMER_IVC1_E1_1_entry& x, const CUSTDIST_mCUSTOMER_IVC1_E1_1_entry& y) {
return x.C_ORDERS_C_CUSTKEY == y.C_ORDERS_C_CUSTKEY;
}
};
typedef MultiHashMap<CUSTDIST_mCUSTOMER_IVC1_E1_1_entry,long,
HashIndex<CUSTDIST_mCUSTOMER_IVC1_E1_1_entry,long,CUSTDIST_mCUSTOMER_IVC1_E1_1_mapkey0_idxfn,true>
> CUSTDIST_mCUSTOMER_IVC1_E1_1_map;
typedef HashIndex<CUSTDIST_mCUSTOMER_IVC1_E1_1_entry,long,CUSTDIST_mCUSTOMER_IVC1_E1_1_mapkey0_idxfn,true> HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0;
struct CUSTDIST_mCUSTOMER1_L1_1_entry {
long CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY; long __av;
explicit CUSTDIST_mCUSTOMER1_L1_1_entry() { /*CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = 0L; __av = 0L; */ }
explicit CUSTDIST_mCUSTOMER1_L1_1_entry(const long c0, const long c1) { CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = c0; __av = c1; }
CUSTDIST_mCUSTOMER1_L1_1_entry(const CUSTDIST_mCUSTOMER1_L1_1_entry& other) : CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY( other.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY ), __av( other.__av ) {}
FORCE_INLINE CUSTDIST_mCUSTOMER1_L1_1_entry& modify(const long c0) { CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = c0; return *this; }
template<class Archive>
void serialize(Archive& ar, const unsigned int version) const
{
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY);
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, __av);
}
};
struct CUSTDIST_mCUSTOMER1_L1_1_mapkey0_idxfn {
FORCE_INLINE static size_t hash(const CUSTDIST_mCUSTOMER1_L1_1_entry& e) {
size_t h = 0;
hash_combine(h, e.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY);
return h;
}
FORCE_INLINE static bool equals(const CUSTDIST_mCUSTOMER1_L1_1_entry& x, const CUSTDIST_mCUSTOMER1_L1_1_entry& y) {
return x.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY == y.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY;
}
};
typedef MultiHashMap<CUSTDIST_mCUSTOMER1_L1_1_entry,long,
HashIndex<CUSTDIST_mCUSTOMER1_L1_1_entry,long,CUSTDIST_mCUSTOMER1_L1_1_mapkey0_idxfn,true>
> CUSTDIST_mCUSTOMER1_L1_1_map;
typedef HashIndex<CUSTDIST_mCUSTOMER1_L1_1_entry,long,CUSTDIST_mCUSTOMER1_L1_1_mapkey0_idxfn,true> HashIndex_CUSTDIST_mCUSTOMER1_L1_1_map_0;
struct CUSTDIST_mCUSTOMER1_L1_2_entry {
long CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY; long __av;
explicit CUSTDIST_mCUSTOMER1_L1_2_entry() { /*CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = 0L; __av = 0L; */ }
explicit CUSTDIST_mCUSTOMER1_L1_2_entry(const long c0, const long c1) { CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = c0; __av = c1; }
CUSTDIST_mCUSTOMER1_L1_2_entry(const CUSTDIST_mCUSTOMER1_L1_2_entry& other) : CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY( other.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY ), __av( other.__av ) {}
FORCE_INLINE CUSTDIST_mCUSTOMER1_L1_2_entry& modify(const long c0) { CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = c0; return *this; }
template<class Archive>
void serialize(Archive& ar, const unsigned int version) const
{
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY);
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, __av);
}
};
struct CUSTDIST_mCUSTOMER1_L1_2_mapkey0_idxfn {
FORCE_INLINE static size_t hash(const CUSTDIST_mCUSTOMER1_L1_2_entry& e) {
size_t h = 0;
hash_combine(h, e.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY);
return h;
}
FORCE_INLINE static bool equals(const CUSTDIST_mCUSTOMER1_L1_2_entry& x, const CUSTDIST_mCUSTOMER1_L1_2_entry& y) {
return x.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY == y.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY;
}
};
typedef MultiHashMap<CUSTDIST_mCUSTOMER1_L1_2_entry,long,
HashIndex<CUSTDIST_mCUSTOMER1_L1_2_entry,long,CUSTDIST_mCUSTOMER1_L1_2_mapkey0_idxfn,true>
> CUSTDIST_mCUSTOMER1_L1_2_map;
typedef HashIndex<CUSTDIST_mCUSTOMER1_L1_2_entry,long,CUSTDIST_mCUSTOMER1_L1_2_mapkey0_idxfn,true> HashIndex_CUSTDIST_mCUSTOMER1_L1_2_map_0;
struct tuple2_L_L {
long _1; long __av;
explicit tuple2_L_L() { }
explicit tuple2_L_L(const long c1, long c__av=0L) { _1 = c1; __av = c__av;}
int operator==(const tuple2_L_L &rhs) const { return ((this->_1==rhs._1)); }
FORCE_INLINE tuple2_L_L& modify(const long c0, long c__av) { _1 = c0; __av = c__av; return *this; }
static bool equals(const tuple2_L_L &x, const tuple2_L_L &y) { return ((x._1==y._1)); }
static long hash(const tuple2_L_L &e) {
size_t h = 0;
hash_combine(h, e._1);
return h;
}
};
/* Type definition providing a way to access the results of the sql program */
struct tlq_t{
struct timeval t0,t; long tT,tN,tS;
tlq_t(): tN(0), tS(0) { gettimeofday(&t0,NULL); }
/* Serialization Code */
template<class Archive>
void serialize(Archive& ar, const unsigned int version) const {
ar << "\n";
const CUSTDIST_map& _CUSTDIST = get_CUSTDIST();
dbtoaster::serialize_nvp_tabbed(ar, STRING_TYPE(CUSTDIST), _CUSTDIST, "\t");
}
/* Functions returning / computing the results of top level queries */
const CUSTDIST_map& get_CUSTDIST() const {
return CUSTDIST;
}
protected:
/* Data structures used for storing / computing top level queries */
CUSTDIST_map CUSTDIST;
};
/* Type definition providing a way to incrementally maintain the results of the sql program */
struct data_t : tlq_t{
data_t(): tlq_t(), agg2(16U), agg4(16U), agg1(16U), agg3(16U) {
/* regex_t init */
if(regcomp(&preg1, "^.*special.*requests.*$", REG_EXTENDED | REG_NOSUB)){
cerr << "Error compiling regular expression: /^.*special.*requests.*$/" << endl;
exit(-1);
}
}
~data_t() {
regfree(&preg1);
}
/* Trigger functions for table relations */
/* Trigger functions for stream relations */
void on_insert_ORDERS(const long orders_orderkey, const long orders_custkey, const STRING_TYPE& orders_orderstatus, const DOUBLE_TYPE orders_totalprice, const date orders_orderdate, const STRING_TYPE& orders_orderpriority, const STRING_TYPE& orders_clerk, const long orders_shippriority, const STRING_TYPE& orders_comment) {
{ if (tS>0) { ++tS; return; } if ((tN&127)==0) { gettimeofday(&(t),NULL); tT=((t).tv_sec-(t0).tv_sec)*1000000L+((t).tv_usec-(t0).tv_usec); if (tT>3600000000L) { tS=1; return; } } ++tN;
agg1.clear();
{ // foreach
const HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0* i1 = static_cast<HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0*>(CUSTDIST_mCUSTOMER_IVC1_E1_1.index[0]);
HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0::IdxNode* n1;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry* e1;
for (size_t i = 0; i < i1->size_; i++)
{
n1 = i1->buckets_ + i;
while (n1 && (e1 = n1->obj))
{
long c_orders_c_custkey = e1->C_ORDERS_C_CUSTKEY;
long v1 = e1->__av;
long l1 = CUSTDIST_mCUSTOMER_IVC1_E1_1.getValueOrDefault(se2.modify(c_orders_c_custkey));
agg1.addOrDelOnZero(st1.modify(l1,(v1 != 0 ? 1L : 0L)), (v1 != 0 ? 1L : 0L));
n1 = n1->nxt;
}
}
}{ // temp foreach
const HashIndex<tuple2_L_L, long>* i2 = static_cast<HashIndex<tuple2_L_L, long>*>(agg1.index[0]);
HashIndex<tuple2_L_L, long>::IdxNode* n2;
tuple2_L_L* e2;
for (size_t i = 0; i < i2->size_; i++)
{
n2 = i2->buckets_ + i;
while (n2 && (e2 = n2->obj))
{
long c_orders_c_count = e2->_1;
long v2 = e2->__av;
if (CUSTDIST.getValueOrDefault(se1.modify(c_orders_c_count))==0) CUSTDIST.setOrDelOnZero(se1, v2);
n2 = n2->nxt;
}
}
}long l2 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se3.modify(orders_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se4.modify(orders_custkey)));
CUSTDIST.addOrDelOnZero(se1.modify(l2),(((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se5.modify(orders_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se6.modify(orders_custkey))) != 0 ? 1L : 0L) * -1L));
long l3 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se7.modify(orders_custkey)) * (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se8.modify(orders_custkey)) + (/*if */(0L == Upreg_match(preg1,orders_comment)) ? 1L : 0L)));
CUSTDIST.addOrDelOnZero(se1.modify(l3),((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se9.modify(orders_custkey)) * (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se10.modify(orders_custkey)) + (/*if */(0L == Upreg_match(preg1,orders_comment)) ? 1L : 0L))) != 0 ? 1L : 0L));
(/*if */(0L == Upreg_match(preg1,orders_comment)) ? CUSTDIST_mCUSTOMER_IVC1_E1_1.addOrDelOnZero(se11.modify(orders_custkey),CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se12.modify(orders_custkey))) : (void)0);
(/*if */(0L == Upreg_match(preg1,orders_comment)) ? CUSTDIST_mCUSTOMER1_L1_2.addOrDelOnZero(se13.modify(orders_custkey),1L) : (void)0);
}
}
void on_delete_ORDERS(const long orders_orderkey, const long orders_custkey, const STRING_TYPE& orders_orderstatus, const DOUBLE_TYPE orders_totalprice, const date orders_orderdate, const STRING_TYPE& orders_orderpriority, const STRING_TYPE& orders_clerk, const long orders_shippriority, const STRING_TYPE& orders_comment) {
{ if (tS>0) { ++tS; return; } if ((tN&127)==0) { gettimeofday(&(t),NULL); tT=((t).tv_sec-(t0).tv_sec)*1000000L+((t).tv_usec-(t0).tv_usec); if (tT>3600000000L) { tS=1; return; } } ++tN;
agg2.clear();
{ // foreach
const HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0* i3 = static_cast<HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0*>(CUSTDIST_mCUSTOMER_IVC1_E1_1.index[0]);
HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0::IdxNode* n3;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry* e3;
for (size_t i = 0; i < i3->size_; i++)
{
n3 = i3->buckets_ + i;
while (n3 && (e3 = n3->obj))
{
long c_orders_c_custkey = e3->C_ORDERS_C_CUSTKEY;
long v3 = e3->__av;
long l4 = CUSTDIST_mCUSTOMER_IVC1_E1_1.getValueOrDefault(se15.modify(c_orders_c_custkey));
agg2.addOrDelOnZero(st2.modify(l4,(v3 != 0 ? 1L : 0L)), (v3 != 0 ? 1L : 0L));
n3 = n3->nxt;
}
}
}{ // temp foreach
const HashIndex<tuple2_L_L, long>* i4 = static_cast<HashIndex<tuple2_L_L, long>*>(agg2.index[0]);
HashIndex<tuple2_L_L, long>::IdxNode* n4;
tuple2_L_L* e4;
for (size_t i = 0; i < i4->size_; i++)
{
n4 = i4->buckets_ + i;
while (n4 && (e4 = n4->obj))
{
long c_orders_c_count = e4->_1;
long v4 = e4->__av;
if (CUSTDIST.getValueOrDefault(se14.modify(c_orders_c_count))==0) CUSTDIST.setOrDelOnZero(se14, v4);
n4 = n4->nxt;
}
}
}long l5 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se16.modify(orders_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se17.modify(orders_custkey)));
CUSTDIST.addOrDelOnZero(se14.modify(l5),(((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se18.modify(orders_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se19.modify(orders_custkey))) != 0 ? 1L : 0L) * -1L));
long l6 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se20.modify(orders_custkey)) * (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se21.modify(orders_custkey)) + (/*if */(0L == Upreg_match(preg1,orders_comment)) ? -1L : 0L)));
CUSTDIST.addOrDelOnZero(se14.modify(l6),((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se22.modify(orders_custkey)) * (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se23.modify(orders_custkey)) + (/*if */(0L == Upreg_match(preg1,orders_comment)) ? -1L : 0L))) != 0 ? 1L : 0L));
(/*if */(0L == Upreg_match(preg1,orders_comment)) ? CUSTDIST_mCUSTOMER_IVC1_E1_1.addOrDelOnZero(se24.modify(orders_custkey),(CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se25.modify(orders_custkey)) * -1L)) : (void)0);
(/*if */(0L == Upreg_match(preg1,orders_comment)) ? CUSTDIST_mCUSTOMER1_L1_2.addOrDelOnZero(se26.modify(orders_custkey),-1L) : (void)0);
}
}
void on_insert_CUSTOMER(const long customer_custkey, const STRING_TYPE& customer_name, const STRING_TYPE& customer_address, const long customer_nationkey, const STRING_TYPE& customer_phone, const DOUBLE_TYPE customer_acctbal, const STRING_TYPE& customer_mktsegment, const STRING_TYPE& customer_comment) {
{ if (tS>0) { ++tS; return; } if ((tN&127)==0) { gettimeofday(&(t),NULL); tT=((t).tv_sec-(t0).tv_sec)*1000000L+((t).tv_usec-(t0).tv_usec); if (tT>3600000000L) { tS=1; return; } } ++tN;
agg3.clear();
{ // foreach
const HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0* i5 = static_cast<HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0*>(CUSTDIST_mCUSTOMER_IVC1_E1_1.index[0]);
HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0::IdxNode* n5;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry* e5;
for (size_t i = 0; i < i5->size_; i++)
{
n5 = i5->buckets_ + i;
while (n5 && (e5 = n5->obj))
{
long c_orders_c_custkey = e5->C_ORDERS_C_CUSTKEY;
long v5 = e5->__av;
long l7 = CUSTDIST_mCUSTOMER_IVC1_E1_1.getValueOrDefault(se28.modify(c_orders_c_custkey));
agg3.addOrDelOnZero(st3.modify(l7,(v5 != 0 ? 1L : 0L)), (v5 != 0 ? 1L : 0L));
n5 = n5->nxt;
}
}
}{ // temp foreach
const HashIndex<tuple2_L_L, long>* i6 = static_cast<HashIndex<tuple2_L_L, long>*>(agg3.index[0]);
HashIndex<tuple2_L_L, long>::IdxNode* n6;
tuple2_L_L* e6;
for (size_t i = 0; i < i6->size_; i++)
{
n6 = i6->buckets_ + i;
while (n6 && (e6 = n6->obj))
{
long c_orders_c_count = e6->_1;
long v6 = e6->__av;
if (CUSTDIST.getValueOrDefault(se27.modify(c_orders_c_count))==0) CUSTDIST.setOrDelOnZero(se27, v6);
n6 = n6->nxt;
}
}
}long l8 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se29.modify(customer_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se30.modify(customer_custkey)));
CUSTDIST.addOrDelOnZero(se27.modify(l8),(((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se31.modify(customer_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se32.modify(customer_custkey))) != 0 ? 1L : 0L) * -1L));
long l9 = (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se33.modify(customer_custkey)) * (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se34.modify(customer_custkey)) + 1L));
CUSTDIST.addOrDelOnZero(se27.modify(l9),((CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se35.modify(customer_custkey)) * (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se36.modify(customer_custkey)) + 1L)) != 0 ? 1L : 0L));
CUSTDIST_mCUSTOMER_IVC1_E1_1.addOrDelOnZero(se37.modify(customer_custkey),CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se38.modify(customer_custkey)));
CUSTDIST_mCUSTOMER1_L1_1.addOrDelOnZero(se39.modify(customer_custkey),1L);
}
}
void on_delete_CUSTOMER(const long customer_custkey, const STRING_TYPE& customer_name, const STRING_TYPE& customer_address, const long customer_nationkey, const STRING_TYPE& customer_phone, const DOUBLE_TYPE customer_acctbal, const STRING_TYPE& customer_mktsegment, const STRING_TYPE& customer_comment) {
{ if (tS>0) { ++tS; return; } if ((tN&127)==0) { gettimeofday(&(t),NULL); tT=((t).tv_sec-(t0).tv_sec)*1000000L+((t).tv_usec-(t0).tv_usec); if (tT>3600000000L) { tS=1; return; } } ++tN;
agg4.clear();
{ // foreach
const HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0* i7 = static_cast<HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0*>(CUSTDIST_mCUSTOMER_IVC1_E1_1.index[0]);
HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0::IdxNode* n7;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry* e7;
for (size_t i = 0; i < i7->size_; i++)
{
n7 = i7->buckets_ + i;
while (n7 && (e7 = n7->obj))
{
long c_orders_c_custkey = e7->C_ORDERS_C_CUSTKEY;
long v7 = e7->__av;
long l10 = CUSTDIST_mCUSTOMER_IVC1_E1_1.getValueOrDefault(se41.modify(c_orders_c_custkey));
agg4.addOrDelOnZero(st4.modify(l10,(v7 != 0 ? 1L : 0L)), (v7 != 0 ? 1L : 0L));
n7 = n7->nxt;
}
}
}{ // temp foreach
const HashIndex<tuple2_L_L, long>* i8 = static_cast<HashIndex<tuple2_L_L, long>*>(agg4.index[0]);
HashIndex<tuple2_L_L, long>::IdxNode* n8;
tuple2_L_L* e8;
for (size_t i = 0; i < i8->size_; i++)
{
n8 = i8->buckets_ + i;
while (n8 && (e8 = n8->obj))
{
long c_orders_c_count = e8->_1;
long v8 = e8->__av;
if (CUSTDIST.getValueOrDefault(se40.modify(c_orders_c_count))==0) CUSTDIST.setOrDelOnZero(se40, v8);
n8 = n8->nxt;
}
}
}long l11 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se42.modify(customer_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se43.modify(customer_custkey)));
CUSTDIST.addOrDelOnZero(se40.modify(l11),(((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se44.modify(customer_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se45.modify(customer_custkey))) != 0 ? 1L : 0L) * -1L));
long l12 = (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se46.modify(customer_custkey)) * (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se47.modify(customer_custkey)) + -1L));
CUSTDIST.addOrDelOnZero(se40.modify(l12),((CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se48.modify(customer_custkey)) * (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se49.modify(customer_custkey)) + -1L)) != 0 ? 1L : 0L));
CUSTDIST_mCUSTOMER_IVC1_E1_1.addOrDelOnZero(se50.modify(customer_custkey),(CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se51.modify(customer_custkey)) * -1L));
CUSTDIST_mCUSTOMER1_L1_1.addOrDelOnZero(se52.modify(customer_custkey),-1L);
}
}
void on_system_ready_event() {
{
}
}
private:
/* Sample entries for avoiding recreation of temporary objects */
CUSTDIST_entry se1;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se2;
tuple2_L_L st1;
CUSTDIST_mCUSTOMER1_L1_1_entry se3;
CUSTDIST_mCUSTOMER1_L1_2_entry se4;
CUSTDIST_mCUSTOMER1_L1_1_entry se5;
CUSTDIST_mCUSTOMER1_L1_2_entry se6;
CUSTDIST_mCUSTOMER1_L1_1_entry se7;
CUSTDIST_mCUSTOMER1_L1_2_entry se8;
CUSTDIST_mCUSTOMER1_L1_1_entry se9;
CUSTDIST_mCUSTOMER1_L1_2_entry se10;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se11;
CUSTDIST_mCUSTOMER1_L1_1_entry se12;
CUSTDIST_mCUSTOMER1_L1_2_entry se13;
CUSTDIST_entry se14;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se15;
tuple2_L_L st2;
CUSTDIST_mCUSTOMER1_L1_1_entry se16;
CUSTDIST_mCUSTOMER1_L1_2_entry se17;
CUSTDIST_mCUSTOMER1_L1_1_entry se18;
CUSTDIST_mCUSTOMER1_L1_2_entry se19;
CUSTDIST_mCUSTOMER1_L1_1_entry se20;
CUSTDIST_mCUSTOMER1_L1_2_entry se21;
CUSTDIST_mCUSTOMER1_L1_1_entry se22;
CUSTDIST_mCUSTOMER1_L1_2_entry se23;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se24;
CUSTDIST_mCUSTOMER1_L1_1_entry se25;
CUSTDIST_mCUSTOMER1_L1_2_entry se26;
CUSTDIST_entry se27;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se28;
tuple2_L_L st3;
CUSTDIST_mCUSTOMER1_L1_1_entry se29;
CUSTDIST_mCUSTOMER1_L1_2_entry se30;
CUSTDIST_mCUSTOMER1_L1_1_entry se31;
CUSTDIST_mCUSTOMER1_L1_2_entry se32;
CUSTDIST_mCUSTOMER1_L1_2_entry se33;
CUSTDIST_mCUSTOMER1_L1_1_entry se34;
CUSTDIST_mCUSTOMER1_L1_2_entry se35;
CUSTDIST_mCUSTOMER1_L1_1_entry se36;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se37;
CUSTDIST_mCUSTOMER1_L1_2_entry se38;
CUSTDIST_mCUSTOMER1_L1_1_entry se39;
CUSTDIST_entry se40;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se41;
tuple2_L_L st4;
CUSTDIST_mCUSTOMER1_L1_1_entry se42;
CUSTDIST_mCUSTOMER1_L1_2_entry se43;
CUSTDIST_mCUSTOMER1_L1_1_entry se44;
CUSTDIST_mCUSTOMER1_L1_2_entry se45;
CUSTDIST_mCUSTOMER1_L1_2_entry se46;
CUSTDIST_mCUSTOMER1_L1_1_entry se47;
CUSTDIST_mCUSTOMER1_L1_2_entry se48;
CUSTDIST_mCUSTOMER1_L1_1_entry se49;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se50;
CUSTDIST_mCUSTOMER1_L1_2_entry se51;
CUSTDIST_mCUSTOMER1_L1_1_entry se52;
/* regex_t temporary objects */
regex_t preg1;
/* Data structures used for storing materialized views */
CUSTDIST_mCUSTOMER_IVC1_E1_1_map CUSTDIST_mCUSTOMER_IVC1_E1_1;
CUSTDIST_mCUSTOMER1_L1_1_map CUSTDIST_mCUSTOMER1_L1_1;
CUSTDIST_mCUSTOMER1_L1_2_map CUSTDIST_mCUSTOMER1_L1_2;
MultiHashMap<tuple2_L_L,long,HashIndex<tuple2_L_L,long> > agg2;
MultiHashMap<tuple2_L_L,long,HashIndex<tuple2_L_L,long> > agg4;
MultiHashMap<tuple2_L_L,long,HashIndex<tuple2_L_L,long> > agg1;
MultiHashMap<tuple2_L_L,long,HashIndex<tuple2_L_L,long> > agg3;
};
}
| 52.463043
| 328
| 0.695852
|
szarnyasg
|
0120cb3c518dc7e577506ec76c317ca23a2c125f
| 412
|
cpp
|
C++
|
a/a216.cpp
|
mirkat1206/zerojudge_cpp
|
263cd51f4eee4acec8396f6c069bba540ac15e96
|
[
"BSD-2-Clause"
] | 1
|
2019-12-27T03:03:50.000Z
|
2019-12-27T03:03:50.000Z
|
a/a216.cpp
|
mirkat1206/zerojudge_cpp
|
263cd51f4eee4acec8396f6c069bba540ac15e96
|
[
"BSD-2-Clause"
] | null | null | null |
a/a216.cpp
|
mirkat1206/zerojudge_cpp
|
263cd51f4eee4acec8396f6c069bba540ac15e96
|
[
"BSD-2-Clause"
] | null | null | null |
// a216 : 數數愛明明
#include <cstdio>
#define N 30010
int main()
{
// f[n] = n + f[n-1], g[n] = f[n] + g[n-1], f[1] = g[1] = 1
// f[i], g[i] is on day i !!!
long long int f[N] = { 0 , 1 , 3 }, g[N] = { 0 , 1 } ;
for( int i=3 ; i<N ; i++ )
{
f[i] = i + f[i-1] ;
g[i-1] = f[i-1] + g[i-2] ;
}
int n;
while( scanf("%lld", &n )!=EOF )
printf("%lld %lld\n", f[n] , g[n] );
return 0;
}
| 19.619048
| 61
| 0.393204
|
mirkat1206
|
01215b320c80daaf94dc18a75469ceeffbd1cd72
| 7,317
|
cc
|
C++
|
ARM/NXP/Flash/FCB.cc
|
JohnAdriaan/RTX2C3
|
833cfa45ece56a1516cb743c6bafa7c916451e55
|
[
"BSD-3-Clause"
] | null | null | null |
ARM/NXP/Flash/FCB.cc
|
JohnAdriaan/RTX2C3
|
833cfa45ece56a1516cb743c6bafa7c916451e55
|
[
"BSD-3-Clause"
] | null | null | null |
ARM/NXP/Flash/FCB.cc
|
JohnAdriaan/RTX2C3
|
833cfa45ece56a1516cb743c6bafa7c916451e55
|
[
"BSD-3-Clause"
] | null | null | null |
// © 2019 John Adriaan. Licensed under the "3-clause BSD License"
///
/// \file ARM/NXP/Flash/FCB.cc
///
/// This file defines and instantiates the Flash Control Block at a known address.
/// The FCB is used by the i.MX RT10xx to best configure the Flash for use.
/// Note that this is completely self-contained - no external reference needs
/// to be made to this module.
///
#include <ARM/NXP/NXP.hh>
namespace ARM::NXP::Flash {
/// FlexSPI Configuration Block
struct FlexSPIConfig {
struct Version {
byte bugfix;
byte minor;
byte major;
const char v = 'V';
}; // Version
static_assert(sizeof(Version)==4, "Incorrect Version size");
enum SampleClkSrcs : byte {
Internal = 0,
Loopback = 1,
FlashDQS = 3
}; // SampleClkSrcs
struct LUTs {
byte number; ///< Number of LUT sequences
byte index; ///< Starting LUT index
const word x2 = Rsvd16; ///< Reserved
}; // LUTs
static_assert(sizeof(LUTs)==4, "Incorrect LUTs size");
struct MiscOptions {
bit diffClkEnable : 1;
unsigned : 1;
bit parallelModeEnable : 1;
bit wordAddressableEnable : 1;
bit safeConfigFreqEnable : 1;
bit padSettingOverrideEnable : 1;
bit ddrModeEnable : 1;
unsigned : 2;
bit secondDQSPinMux : 1;
unsigned : 22;
unsigned : 0;
}; // MiscOptions
static_assert(sizeof(MiscOptions)==sizeof(unsigned), "Incorrect MiscOptions size");
enum DeviceTypes : byte {
DeviceUnknown = 0, ///< *** Examples have this value
SerialNOR = 1 ///< *** Documents show this is only valid option
}; // DeviceTypes
enum Pads : byte {
SinglePad = 1,
DualPads = 2,
QuadPads = 4,
OctalPads = 8
}; // Pads
enum ClockFreqs : byte {
Freq30MHz = 1,
Freq50MHz = 2,
Freq60MHz = 3,
Freq75MHz = 4,
Freq80MHz = 5,
Freq100MHz = 6,
Freq120MHz = 7,
Freq133MHz = 8
}; // ClockFreqs
struct ValidTimes {
word dllA;
word dllB;
}; // ValidTimes
static_assert(sizeof(ValidTimes)==sizeof(unsigned), "Incorrect ValidTimes size");
enum Busys : word {
Busy1 = 0, ///< 0: "Busy Bit==1 when busy
Busy0 = 1 ///< 1: "Busy Bit==0 when busy
}; // Busys
enum LUTPads {
Pad1 = 0,
Pad2 = 1,
Pad4 = 2,
Pad8 = 3
}; // LUTPads
enum Instructions {
STOP = 0,
JMP = 9,
CMD = 1,
ADDR = 2,
DUMMY = 3,
MODE = 4,
MODE2 = 5,
MODE4 = 6,
READ = 7,
WRITE = 8,
CMD_DDR = 0x11,
ADDR_DDR = 0x0A,
MODE_DDR = 0x0B,
MODE2_DDR = 0x0C,
MODE4_DDR = 0x0D,
READ_DDR = 0x0E,
WRITE_DDR = 0x0F
}; // Instructions
struct LUTCommand {
byte operand : 8;
LUTPads pad : 2;
Instructions instruction : 6;
word : 0;
}; // LUTCommand
static_assert(sizeof(LUTCommand)==2, "Incorrect LUTCommand size");
typedef LUTCommand LUTSequence[8];
static_assert(sizeof(LUTSequence)==16, "Incorrect LUTCommand size");
const char tag[4] = { 'F', 'C', 'F', 'B' }; ///< Tag to identify block
Version version = { .bugfix=0, .minor=4, .major=1 };
const unsigned x008 = Rsvd32; ///< Reserved
SampleClkSrcs readSampleClkSrc = Loopback; ///< Sample DQS Pad
byte csHoldTime = 3; ///< Column Select Hold Time. Recommended value
byte csSetupTime = 3; ///< Column Select Setup Time. Recommended value
byte columnAddressWidth = 0; ///< Not HyperFlash
byte deviceModeCfgEnable = No; ///< Don't enable Config
const byte x011 = Rsvd8; ///< Reserved
word waitTimeCfgCommands = 0; ///< in 100us. Note v1.1.0 minimum
LUTs deviceModeSeq = { .number=0, .index=0 };
unsigned deviceModeArg = 0; ///< `deviceModeCfgEnable` must be `1`
byte configCmdEnable = No;
const byte x01D[3] = { Rsvd8, Rsvd8, Rsvd8 }; ///< Reserved
unsigned configCmdSeqs[3] = { 0, 0, 0 };
const unsigned x02C = Rsvd8; ///< Reserved
unsigned cfgCmdArgs[3] = { 0, 0, 0 };
const unsigned x03C = Rsvd8; ///< Reserved
MiscOptions controllerMiscOption = { };
DeviceTypes deviceType = SerialNOR;
Pads sflashPadType = QuadPads;
ClockFreqs serialClkFreq = Freq100MHz;
byte lutCustomSeqEnable = No;
const unsigned x048[2] = { Rsvd32, Rsvd32 };
unsigned sflashA1Size = 0x0100'0000;
unsigned sflashA2Size = 0x0000'0000;
unsigned sflashB1Size = 0x0000'0000;
unsigned sflashB2Size = 0x0000'0000;
unsigned csPadSettingOverride = No;
unsigned sclkPadSettingOverride = No;
unsigned dataPadSettingOverride = No;
unsigned dqsPadSettingOverride = No;
unsigned timeoutInMs = 0;
unsigned commandInterval = 0; ///< in ns
ValidTimes dataValidTimes = { .dllA = 0, .dllB = 0 };
word busyOffset = 0; ///< Valid range: 0-31
Busys busyBitPolarity = Busy1;
LUTSequence lookupTable[16] = { { { .operand = 0xEB, .pad = Pad1, .instruction = CMD }, ///< 4xI/O, READ
{ .operand = 24, .pad = Pad4, .instruction = ADDR }, ///< 24 bits
{ .operand = 6, .pad = Pad4, .instruction = MODE2_DDR }, ///< 6 Dummy cycles
// { .operand = 0, .pad = Pad1, .instruction = STOP } } }; ///< And STOP
/*** This final command could simply be STOP? ***/ { .operand = 1<<2, .pad = Pad4, .instruction = JMP } } }; ///< JMP LUT[1]
LUTSequence lutCustomSeq[3] = { };
unsigned reserved[4] = { Rsvd32, Rsvd32, Rsvd32, Rsvd32 };
}; // FlexSPIConfig
static_assert(sizeof(FlexSPIConfig)==0x1C0, "Incorrect FlexSPIConfig size");
struct SerialNORConfig {
enum ClockFreqs {
ClockUnchanged = 0,
Clock30MHz = 1,
Clock50MHz = 2,
Clock60MHz = 3,
Clock75MHz = 4,
Clock80MHz = 5,
Clock100MHz = 6,
Clock133MHz = 7
}; // ClockFreqs
FlexSPIConfig fcb = { };
unsigned pageSize = 0x0100;
unsigned sectorSize = 0x1000;
ClockFreqs ipCmdSerialClockFreq = ClockUnchanged;
unsigned reserved[13] = { Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32,
Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32 };
}; // SerialNORConfigBlock
static_assert(sizeof(SerialNORConfig)==0x200, "Incorrect SerialNORConfig size");
SECTION(".FCB")
const SerialNORConfig serialNORConfig;
} // namespace ARM::NXP::Flash
| 36.402985
| 129
| 0.531502
|
JohnAdriaan
|
0125409ff226d969876cee1c1b41b80f3bdcfc9e
| 8,747
|
hh
|
C++
|
aku/FeatureModules.hh
|
lingsoft/AaltoASR
|
40343e215a6cf1b7d5ed41a53095495567b0ab01
|
[
"BSD-3-Clause"
] | 78
|
2015-01-07T14:33:47.000Z
|
2022-03-15T09:01:30.000Z
|
aku/FeatureModules.hh
|
ufukhurriyetoglu/AaltoASR
|
02b23d374ab9be9b0fd5d8159570b509ede066f3
|
[
"BSD-3-Clause"
] | 4
|
2015-05-19T13:00:34.000Z
|
2016-07-26T12:29:32.000Z
|
aku/FeatureModules.hh
|
ufukhurriyetoglu/AaltoASR
|
02b23d374ab9be9b0fd5d8159570b509ede066f3
|
[
"BSD-3-Clause"
] | 32
|
2015-01-16T08:16:24.000Z
|
2021-04-02T21:26:22.000Z
|
#ifndef FEATUREMODULES_HH
#define FEATUREMODULES_HH
#include <vector>
#include "ModuleConfig.hh"
#include "FeatureModule.hh"
#include "BaseFeaModule.hh"
#include "AudioFileModule.hh"
#include "FFTModule.hh"
namespace aku {
class FeatureGenerator;
//////////////////////////////////////////////////////////////////
// Feature module implementations
//////////////////////////////////////////////////////////////////
class PreModule : public BaseFeaModule {
public:
PreModule();
static const char *type_str() { return "pre"; }
virtual void set_fname(const char *fname);
virtual void set_file(FILE *fp, bool stream=false);
virtual void discard_file(void);
virtual bool eof(int frame);
virtual int sample_rate(void) { return m_sample_rate; }
virtual float frame_rate(void) { return m_frame_rate; }
virtual int last_frame(void);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void reset_module();
virtual void generate(int frame);
private:
int m_sample_rate;
float m_frame_rate;
int m_eof_frame;
int m_legacy_file; //!< If nonzero, the dimension in the file is a byte
int m_file_offset;
int m_cur_pre_frame;
bool m_close_file;
FILE *m_fp;
std::vector<double> m_first_feature; //!< Feature returned for negative frames
std::vector<double> m_last_feature; //!< Feature returned after EOF
int m_last_feature_frame; //!< The frame of the feature returned after EOF
std::vector<float> m_temp_fea_buf; //!< Need a float buffer for reading
};
class MelModule : public FeatureModule {
public:
MelModule(FeatureGenerator *fea_gen);
static const char *type_str() { return "mel"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
void create_mel_bins(void);
private:
FeatureGenerator *m_fea_gen;
int m_bins;
int m_root; //!< If nonzero, take 10th root of the output instead of logarithm
std::vector<float> m_bin_edges;
};
class PowerModule : public FeatureModule {
public:
PowerModule();
static const char *type_str() { return "power"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
};
class MelPowerModule : public FeatureModule {
public:
MelPowerModule();
static const char *type_str() { return "mel_power"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
};
class DCTModule : public FeatureModule {
public:
DCTModule();
static const char *type_str() { return "dct"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
private:
int m_zeroth_comp; //!< If nonzero, output includes zeroth component
};
class DeltaModule : public FeatureModule {
public:
DeltaModule();
static const char *type_str() { return "delta"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
private:
int m_delta_width;
float m_delta_norm;
};
class NormalizationModule : public FeatureModule {
public:
NormalizationModule();
static const char *type_str() { return "normalization"; }
void set_normalization(const std::vector<float> &mean,
const std::vector<float> &scale);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void set_parameters(const ModuleConfig &config);
virtual void get_parameters(ModuleConfig &config);
virtual void generate(int frame);
private:
std::vector<float> m_mean;
std::vector<float> m_scale;
};
class LinTransformModule : public FeatureModule {
public:
LinTransformModule();
static const char *type_str() { return "lin_transform"; }
const std::vector<float> *get_transformation_matrix(void) { return &m_transform; }
const std::vector<float> *get_transformation_bias(void) { return &m_bias; }
void set_transformation_matrix(std::vector<float> &t);
void set_transformation_bias(std::vector<float> &b);
virtual void set_parameters(const ModuleConfig &config);
virtual void get_parameters(ModuleConfig &config);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
void check_transform_parameters(void);
private:
std::vector<float> m_transform;
std::vector<float> m_bias;
std::vector<float> m_original_transform;
std::vector<float> m_original_bias;
bool m_matrix_defined, m_bias_defined;
int m_src_dim;
public:
virtual bool is_defined() { return m_matrix_defined && m_bias_defined; }
};
class MergerModule : public FeatureModule {
public:
MergerModule();
static const char *type_str() { return "merge"; }
virtual void add_source(FeatureModule *source);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
};
class MeanSubtractorModule : public FeatureModule {
public:
MeanSubtractorModule();
static const char *type_str() { return "mean_subtractor"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void reset_module();
virtual void generate(int frame);
private:
std::vector<double> m_cur_mean;
int m_cur_frame;
int m_width;
};
class ConcatModule : public FeatureModule {
public:
ConcatModule();
static const char *type_str() { return "concat"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
private:
int left, right;
};
class VtlnModule : public FeatureModule {
public:
VtlnModule();
static const char *type_str() { return "vtln"; }
void set_warp_factor(float factor);
void set_slapt_warp(std::vector<float> ¶ms);
float get_warp_factor(void) { return m_warp_factor; }
virtual void set_parameters(const ModuleConfig &config);
virtual void get_parameters(ModuleConfig &config);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
void create_pwlin_bins(void);
void create_blin_bins(void);
void create_slapt_bins(void);
void create_sinc_coef_table(void);
void create_all_pass_blin_transform(void);
void create_all_pass_slapt_transform(void);
void set_all_pass_transform(Matrix &trmat);
private:
int m_use_pwlin;
float m_pwlin_turn_point;
int m_use_slapt;
int m_sinc_interpolation_rad;
int m_all_pass;
bool m_lanczos_window;
std::vector<float> m_vtln_bins;
std::vector< std::vector<float> > m_sinc_coef;
std::vector<int> m_sinc_coef_start;
float m_warp_factor;
std::vector<float> m_slapt_params;
};
class SRNormModule : public FeatureModule {
public:
SRNormModule();
static const char *type_str() { return "sr_norm"; }
void set_speech_rate(float factor);
float get_speech_rate(void) { return m_speech_rate; }
virtual void set_parameters(const ModuleConfig &config);
virtual void get_parameters(ModuleConfig &config);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
private:
int m_in_frames;
int m_out_frames;
int m_frame_dim;
int m_lanczos_order;
float m_speech_rate;
std::vector< std::vector<float> > m_coef;
std::vector<int> m_interpolation_start;
};
class QuantEqModule : public FeatureModule {
public:
QuantEqModule();
static const char *type_str() { return "quanteq"; }
void set_alpha(std::vector<float> &alpha);
void set_gamma(std::vector<float> &gamma);
void set_quant_max(std::vector<float> &quant_max);
std::vector<float> get_quant_train(void) { return m_quant_train; }
virtual void set_parameters(const ModuleConfig &config);
virtual void get_parameters(ModuleConfig &config);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
private:
std::vector<float> m_quant_train;
std::vector<float> m_alpha;
std::vector<float> m_gamma;
std::vector<float> m_quant_max;
};
}
#endif /* FEATUREMODULES_HH */
| 28.584967
| 84
| 0.745627
|
lingsoft
|
01255311cfc3027c017846c9e92e7b40af6bc7e5
| 7,212
|
cpp
|
C++
|
Plugin_Kade/Kade_Thread.cpp
|
ChaseBro/MMDAgent
|
779cd3035954c27016333a2186896e1870e9ee54
|
[
"Libpng",
"Zlib",
"Unlicense"
] | 9
|
2017-08-17T01:01:55.000Z
|
2022-02-02T09:50:09.000Z
|
Plugin_Kade/Kade_Thread.cpp
|
ChaseBro/MMDAgent
|
779cd3035954c27016333a2186896e1870e9ee54
|
[
"Libpng",
"Zlib",
"Unlicense"
] | null | null | null |
Plugin_Kade/Kade_Thread.cpp
|
ChaseBro/MMDAgent
|
779cd3035954c27016333a2186896e1870e9ee54
|
[
"Libpng",
"Zlib",
"Unlicense"
] | 4
|
2017-08-17T01:01:57.000Z
|
2021-06-28T08:30:17.000Z
|
/* ----------------------------------------------------------------- */
/* The Toolkit for Building Voice Interaction Systems */
/* "MMDAgent" developed by MMDAgent Project Team */
/* http://www.mmdagent.jp/ */
/* ----------------------------------------------------------------- */
/* */
/* Copyright (c) 2009-2011 Nagoya Institute of Technology */
/* Department of Computer Science */
/* */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* - Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials provided */
/* with the distribution. */
/* - Neither the name of the MMDAgent project team nor the names of */
/* its contributors may be used to endorse or promote products */
/* derived from this software without specific prior written */
/* permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND */
/* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS */
/* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */
/* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED */
/* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY */
/* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
/* ----------------------------------------------------------------- */
/* headers */
#include "MMDAgent.h"
#include "Kade_Thread.h"
#include <Python.h>
/* File Globals */
PyObject *pModule;
PyObject *pProcPlainText, *pProcParse;
bool m_pause;
/* mainThread: main thread */
static void mainThread(void *param)
{
Kade_Thread *kade_thread = (Kade_Thread *) param;
kade_thread->run();
}
/* Kade_Thread::initialize: initialize thread */
void Kade_Thread::initialize()
{
m_mmdagent = NULL;
m_thread = -1;
m_configFile = NULL;
pModule = NULL;
pProcPlainText = NULL;
pProcParse = NULL;
}
/* Kade_Thread::clear: free thread */
void Kade_Thread::clear()
{
if(m_thread >= 0) {
glfwWaitThread(m_thread, GLFW_WAIT);
glfwDestroyThread(m_thread);
glfwTerminate();
}
if(m_configFile != NULL)
free(m_configFile);
if (pProcParse)
Py_DECREF(pProcParse);
if (pModule)
Py_DECREF(pModule);
Py_Finalize();
initialize();
}
/* Kade_Thread::Kade_Thread: thread constructor */
Kade_Thread::Kade_Thread()
{
initialize();
}
/* Kade_Thread::~Kade_Thread: thread destructor */
Kade_Thread::~Kade_Thread()
{
clear();
}
/* Kade_Thread::load: load models and start thread */
void Kade_Thread::load(MMDAgent *mmdagent, const char *configFile)
{
PyObject *pName;
char name[MMDAGENT_MAXBUFLEN];
Py_Initialize();
m_mmdagent = mmdagent;
m_configFile = MMDAgent_strdup(configFile);
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\"/home/robocep/MMDAgent/Release/AppData/Kade\")");
sprintf(name, "%s%c%s%c%s", mmdagent->getAppDirName(), MMDAGENT_DIRSEPARATOR, "Kade",MMDAGENT_DIRSEPARATOR, "kade");
pName = PyString_FromString("kade");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule == NULL) {
printf("Error Loading python module: %s\n", PyString_AsString(pName));
return;
}
pProcParse = PyObject_GetAttrString(pModule, "procParse");
if (pProcParse == NULL) {
Py_DECREF(pModule);
printf("Error Loading procParse Function.\n");
return;
}
if(m_configFile == NULL) {
Py_DECREF(pProcParse);
Py_DECREF(pModule);
clear();
printf("Error Loading Config File.\n");
return;
}
m_pause = false;
/* create recognition thread
glfwInit();
m_thread = glfwCreateThread(mainThread, this);
if(m_thread < 0) {
clear();
return;
}
*/
}
/* Kade_Thread::run: main loop */
void Kade_Thread::run()
{
}
/* Kade_Thread::pause: pause recognition process */
void Kade_Thread::pause()
{
m_pause = true;
}
/* Kade_Thread::resume: resume recognition process */
void Kade_Thread::resume()
{
m_pause = false;
}
/* Kade_Thread::sendMessage: send message to MMDAgent */
void Kade_Thread::sendMessage(const char *str1, const char *str2)
{
m_mmdagent->sendEventMessage(str1, str2);
}
char* Kade_Thread::procParse(const char *plainText, const char *parse)
{
PyObject *pParse, *pAnswer, *pAnswerStr, *pArgs, *pPlain;
char *answerStr;
if (!pProcParse || !PyCallable_Check(pProcParse)) {
printf("procParse does not exists or is not callable.\n");
if (PyErr_Occurred())
PyErr_Print();
return NULL;
}
pParse = PyString_FromString(parse);
pPlain = PyString_FromString(plainText);
if (pParse != NULL && pPlain != NULL) {
pArgs = PyTuple_New(2);
if (pArgs != NULL) {
PyTuple_SetItem(pArgs, 0, pPlain);
PyTuple_SetItem(pArgs, 1, pParse);
pAnswer = PyObject_CallObject(pProcParse, pArgs);
if (pAnswer != NULL) {
pAnswerStr = PyObject_Str(pAnswer);
Py_DECREF(pAnswer);
Py_DECREF(pArgs);
answerStr = PyString_AsString(pAnswerStr);
Py_DECREF(pAnswerStr);
printf("Answer: %s\n", answerStr);
return answerStr;
}
Py_DECREF(pArgs);
} else
Py_DECREF(pParse);
Py_DECREF(pPlain);
}
printf("Error\n");
if (PyErr_Occurred())
PyErr_Print();
return NULL;
}
char* Kade_Thread::procPlainText(char *text)
{
return NULL;
}
| 31.631579
| 120
| 0.555047
|
ChaseBro
|
012aaddbb70b4812f6398f41c04ebaeef57ce201
| 5,777
|
cpp
|
C++
|
ConvertTrips/Table_Process.cpp
|
kravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | 2
|
2018-04-27T11:07:02.000Z
|
2020-04-24T06:53:21.000Z
|
ConvertTrips/Table_Process.cpp
|
idkravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | null | null | null |
ConvertTrips/Table_Process.cpp
|
idkravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | null | null | null |
//*********************************************************
// Table_Process.cpp - Trip Table Processing
//*********************************************************
#include "ConvertTrips.hpp"
//---------------------------------------------------------
// Table_Processing
//---------------------------------------------------------
void ConvertTrips::Table_Processing (File_Group *group)
{
int num_share, tod, t, t1, t2, num_t, trp, o, d, period, current, first_t, last_t;
int total, stat, errors, org, des, trips, num, num_shares, duration, even_bucket, even;
bool share_flag, factor_flag, period_flag, scale_flag, return_flag;
double trip, factor, added, deleted, bucket;
Diurnal_Data *diurnal_ptr;
Matrix_File *file;
Factor_Data *factor_ptr;
static char *error_msg = "%d Trip%sbetween TAZs %d and %d could not be allocated";
//---- read the trip table ----
total = errors = 0;
added = deleted = 0.0;
file = group->Trip_File ();
return_flag = (group->Duration () > 0);
even_bucket = 1;
bucket = 0.45;
factor_flag = (group->Trip_Factor () != NULL);
period_flag = (group->Factor_Periods () > 0);
scale_flag = (group->Scaling_Factor () != 1.0);
num_shares = group->Num_Shares ();
share_flag = (num_shares > 0);
if (!share_flag) num_share = 1;
duration = group->Duration ();
first_t = t1 = 1;
last_t = t2 = num_t = diurnal_data.Num_Records ();
period = 0;
Show_Message (0, "\tReading %s -- Record", file->File_Type ());
Set_Progress (500);
while (file->Read ()) {
Show_Progress ();
org = file->Origin ();
if (org == 0) continue;
if (org < 1 || org > num_zone) {
Warning ("Origin TAZ %d is Out of Range (1-%d)", org, num_zone);
continue;
}
des = file->Destination ();
if (des < 1 || des > num_zone) {
Warning ("Destination TAZ %d is Out of Range (1-%d)", des, num_zone);
continue;
}
//---- check for a time period ----
if (file->Period_Flag () && period_flag) {
period = file->Period ();
if (period > 0) {
first_t = last_t = 0;
for (t=1; t <= num_t; t++) {
diurnal_ptr = diurnal_data [t];
tod = (diurnal_ptr->Start_Time () + diurnal_ptr->End_Time ()) / 2;
if (group->Factor_Period (tod) == period) {
if (first_t == 0) first_t = t;
last_t = t;
}
}
if (last_t == 0) {
first_t = 1;
last_t = num_t;
period = 0;
}
} else {
first_t = 1;
last_t = num_t;
period = 0;
}
}
trips = file->Data ();
if (trips < 0) {
Warning ("Number of Trips is Out of Range (%d < 0)", trips);
continue;
}
//---- apply the scaling factor ----
if (scale_flag) {
trip = trips * group->Scaling_Factor () + bucket;
trips = (int) trip;
if (trips < 0) trips = 0;
bucket = trip - trips;
}
if (trips == 0) continue;
total += trips;
//---- apply the selection script ----
if (share_flag) {
num = group->Execute ();
if (num < 1 || num > num_shares) {
Error ("Diurnal Selection Value %d is Out of Range (1..%d)", num, num_shares);
}
} else {
num = num_share;
}
//---- get the travel time ----
if (skim_flag) {
skim_ptr = ttime_skim.Get (org, des);
}
//---- apply adjustment factors ----
if (factor_flag) {
o = (equiv_flag) ? zone_equiv.Zone_Group (org) : org;
d = (equiv_flag) ? zone_equiv.Zone_Group (des) : des;
if (period_flag) {
period = -1;
t1 = t2 = 1;
trip = 0.0;
for (t=first_t; t <= last_t; t++) {
diurnal_ptr = diurnal_data [t];
tod = (diurnal_ptr->Start_Time () + diurnal_ptr->End_Time ()) / 2;
current = group->Factor_Period (tod);
if (current != period) {
if (period >= 0) {
factor_ptr = factor_data.Get (o, d, period);
if (factor_ptr == NULL) {
factor_ptr = &default_factor;
}
factor = trip * factor_ptr->Factor ();
if (factor > trip) {
added += factor - trip;
} else {
deleted += trip - factor;
}
trp = factor_ptr->Bucket_Factor (trip);
if (trp > 0 && return_flag) {
even = (((trp + even_bucket) / 2) * 2);
even_bucket += trp - even;
trp = even;
}
if (trp > 0) {
if ((stat = Set_Trips (group, org, des, trp, num, t1, t2, duration))) {
errors += stat;
Print (1, error_msg, stat, ((stat > 1) ? "s " : " "), org, des);
}
}
}
period = current;
t1 = t;
trip = 0.0;
}
trip += trips * diurnal_ptr->Share (num);
t2 = t;
}
} else {
if (period == 0) period = 1;
t1 = first_t;
t2 = last_t;
trip = trips;
}
factor_ptr = factor_data.Get (o, d, period);
if (factor_ptr == NULL) {
factor_ptr = &default_factor;
}
factor = trip * factor_ptr->Factor ();
if (factor > trip) {
added += factor - trip;
} else {
deleted += trip - factor;
}
trp = factor_ptr->Bucket_Factor (trip);
} else {
t1 = first_t;
t2 = last_t;
trp = trips;
}
if (trp > 0 && return_flag) {
even = (((trp + even_bucket) / 2) * 2);
even_bucket += trp - even;
trp = even;
}
//---- process the trips ----
if (trp > 0) {
if ((stat = Set_Trips (group, org, des, trp, num, t1, t2, duration))) {
errors += stat;
Print (1, error_msg, stat, ((stat > 1) ? "s " : " "), org, des);
}
}
}
End_Progress ();
file->Close ();
Print (1, "%s has %d Records and %d Trips", file->File_Type (), Progress_Count (), total);
tot_trips += total;
if (errors > 0) {
Warning ("A Total of %d Trip%scould not be allocated", errors, ((errors > 1) ? "s " : " "));
tot_errors += errors;
}
if (factor_flag) {
Print (1, "Trip Adjustments: %.0lf trips added, %.0lf trips deleted", added, deleted);
tot_add += added;
tot_del += deleted;
}
}
| 24.070833
| 94
| 0.535053
|
kravitz
|
012e73be64c4a50c323ab8bb2937c8b0acb608a8
| 3,009
|
cpp
|
C++
|
GPUImage-x/proj.iOS/GPUImage-x/GPUImage-x/filter/RGBFilter.cpp
|
antowang/GPUImage-x
|
8c9237fd0bde008a69ccab5dc267871c4959f97d
|
[
"Apache-2.0"
] | 197
|
2017-04-04T16:49:42.000Z
|
2022-02-15T10:47:24.000Z
|
GPUImage-x/proj.iOS/GPUImage-x/GPUImage-x/filter/RGBFilter.cpp
|
antowang/GPUImage-x
|
8c9237fd0bde008a69ccab5dc267871c4959f97d
|
[
"Apache-2.0"
] | 6
|
2017-10-04T13:23:11.000Z
|
2018-09-26T06:18:11.000Z
|
GPUImage-x/proj.iOS/GPUImage-x/GPUImage-x/filter/RGBFilter.cpp
|
antowang/GPUImage-x
|
8c9237fd0bde008a69ccab5dc267871c4959f97d
|
[
"Apache-2.0"
] | 53
|
2017-08-07T14:55:30.000Z
|
2022-02-25T09:55:25.000Z
|
/*
* GPUImage-x
*
* Copyright (C) 2017 Yijin Wang, Yiqian Wang
*
* 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 "RGBFilter.hpp"
USING_NS_GI
REGISTER_FILTER_CLASS(RGBFilter)
const std::string kRGBFragmentShaderString = SHADER_STRING
(
uniform sampler2D colorMap;
uniform highp float redAdjustment;
uniform highp float greenAdjustment;
uniform highp float blueAdjustment;
varying highp vec2 vTexCoord;
void main()
{
lowp vec4 color = texture2D(colorMap, vTexCoord);
gl_FragColor = vec4(color.r * redAdjustment, color.g * greenAdjustment, color.b * blueAdjustment, color.a);
}
);
RGBFilter* RGBFilter::create() {
RGBFilter* ret = new (std::nothrow) RGBFilter();
if (ret && !ret->init()) {
delete ret;
ret = 0;
}
return ret;
}
bool RGBFilter::init() {
if (!initWithFragmentShaderString(kRGBFragmentShaderString)) return false;
_redAdjustment = 1.0;
_greenAdjustment = 1.0;
_blueAdjustment = 1.0;
registerProperty("redAdjustment", _redAdjustment, "The red adjustment of the image.The range is from 0.0 up, with 1.0 as the default.", [this](float& redAdjustment){
setRedAdjustment(redAdjustment);
});
registerProperty("greenAdjustment", _greenAdjustment, "The green adjustment of the image.The range is from 0.0 up, with 1.0 as the default.", [this](float& greenAdjustment){
setGreenAdjustment(greenAdjustment);
});
registerProperty("blueAdjustment", _blueAdjustment, "The blue adjustment of the image.The range is from 0.0 up, with 1.0 as the default.", [this](float& blueAdjustment){
setBlueAdjustment(blueAdjustment);
});
return true;
}
void RGBFilter::setRedAdjustment(float redAdjustment) {
_redAdjustment = redAdjustment;
if (_redAdjustment < 0.0) _redAdjustment = 0.0;
}
void RGBFilter::setGreenAdjustment(float greenAdjustment) {
_greenAdjustment = greenAdjustment;
if (_greenAdjustment < 0.0) _greenAdjustment = 0.0;
}
void RGBFilter::setBlueAdjustment(float blueAdjustment) {
_blueAdjustment = blueAdjustment;
if (_blueAdjustment < 0.0) _blueAdjustment = 0.0;
}
bool RGBFilter::proceed(bool bUpdateTargets/* = true*/) {
_filterProgram->setUniformValue("redAdjustment", _redAdjustment);
_filterProgram->setUniformValue("greenAdjustment", _greenAdjustment);
_filterProgram->setUniformValue("blueAdjustment", _blueAdjustment);
return Filter::proceed(bUpdateTargets);
}
| 32.354839
| 177
| 0.715188
|
antowang
|
0130e07bf1f5706e74cab68b1c3d28619e46a356
| 4,250
|
cpp
|
C++
|
src/aimp_dotnet/SDK/MusicLibrary/InternalAimpDataFilterGroup.cpp
|
Smartoteka/aimp_dotnet
|
544502b8d080c9280ba11917ef0cc3e8dec44234
|
[
"Apache-2.0"
] | 52
|
2015-04-14T14:39:30.000Z
|
2022-02-07T07:16:05.000Z
|
src/aimp_dotnet/SDK/MusicLibrary/InternalAimpDataFilterGroup.cpp
|
Smartoteka/aimp_dotnet
|
544502b8d080c9280ba11917ef0cc3e8dec44234
|
[
"Apache-2.0"
] | 11
|
2015-04-02T10:45:55.000Z
|
2022-02-03T07:21:53.000Z
|
src/aimp_dotnet/SDK/MusicLibrary/InternalAimpDataFilterGroup.cpp
|
Smartoteka/aimp_dotnet
|
544502b8d080c9280ba11917ef0cc3e8dec44234
|
[
"Apache-2.0"
] | 9
|
2015-04-05T18:25:57.000Z
|
2022-02-07T07:20:23.000Z
|
// ----------------------------------------------------
// AIMP DotNet SDK
// Copyright (c) 2014 - 2020 Evgeniy Bogdan
// https://github.com/martin211/aimp_dotnet
// Mail: mail4evgeniy@gmail.com
// ----------------------------------------------------
#include "Stdafx.h"
#include "InternalAimpDataFilterGroup.h"
using namespace AIMP::SDK;
using namespace MusicLibrary;
using namespace DataFilter;
InternalAimpDataFilterGroup::InternalAimpDataFilterGroup(gcroot<IAimpDataFilterGroup^> managed) {
_managed = managed;
}
HRESULT WINAPI InternalAimpDataFilterGroup::Add(IUnknown* Field, VARIANT* Value1, VARIANT* Value2, int Operation,
IAIMPMLDataFieldFilter** Filter) {
IAimpDataFieldFilter^ filter = nullptr;
auto result = _managed->Add(AimpConverter::ToManagedString(static_cast<IAIMPString*>(Field)),
AimpConverter::FromVaiant(Value1), AimpConverter::FromVaiant(Value2),
FieldFilterOperationType(Operation));
if (result->ResultType == ActionResultType::OK) {
// todo implement internal IAIMPMLDataFieldFilter
}
return HRESULT(result->ResultType);
}
HRESULT WINAPI InternalAimpDataFilterGroup::Add2(IUnknown* Field, VARIANT* Values, int Count,
IAIMPMLDataFieldFilterByArray** Filter) {
array<Object^>^ values = gcnew array<Object^>(Count);
IAimpDataFieldFilterByArray^ filter;
auto result = _managed->Add(AimpConverter::ToManagedString(static_cast<IAIMPString*>(Field)), values, Count);
if (result->ResultType == ActionResultType::OK) {
// todo implement IAIMPMLDataFieldFilterByArray
}
return HRESULT(result->ResultType);
}
HRESULT WINAPI InternalAimpDataFilterGroup::AddGroup(IAIMPMLDataFilterGroup** Group) {
auto result = _managed->AddGroup();
if (result->ResultType == ActionResultType::OK) {
*Group = new InternalAimpDataFilterGroup(result->Result);
}
return HRESULT(result->ResultType);
}
HRESULT WINAPI InternalAimpDataFilterGroup::Clear() {
return HRESULT(_managed->Clear()->ResultType);
}
HRESULT WINAPI InternalAimpDataFilterGroup::Delete(int Index) {
return HRESULT(_managed->Delete(Index)->ResultType);
}
HRESULT WINAPI InternalAimpDataFilterGroup::GetChild(int Index, REFIID IID, void** Obj) {
ActionResultType res = ActionResultType::Fail;
if (IID == IID_IAIMPMLDataFilterGroup) {
const auto result = _managed->GetFilterGroup(Index);
if (result->ResultType == ActionResultType::OK) {
*Obj = new InternalAimpDataFilterGroup(result->Result);
}
res = result->ResultType;
}
if (IID == IID_IAIMPMLDataFieldFilter) {
IAimpDataFieldFilter^ filter = nullptr;
const auto result = _managed->GetFilterGroup(Index);
if (result->ResultType == ActionResultType::OK) {
// TODO complete it
//*Obj = new Interna
}
res = result->ResultType;
}
return HRESULT(res);
}
int WINAPI InternalAimpDataFilterGroup::GetChildCount() {
return _managed->GetChildCount();
}
ULONG WINAPI InternalAimpDataFilterGroup::AddRef(void) {
return Base::AddRef();
}
ULONG WINAPI InternalAimpDataFilterGroup::Release(void) {
return Base::Release();
}
HRESULT WINAPI InternalAimpDataFilterGroup::QueryInterface(REFIID riid, LPVOID* ppvObject) {
const HRESULT res = Base::QueryInterface(riid, ppvObject);
if (riid == IID_IAIMPMLDataFilterGroup) {
*ppvObject = this;
AddRef();
return S_OK;
}
*ppvObject = nullptr;
return res;
}
HRESULT WINAPI InternalAimpDataFilterGroup::GetValueAsInt32(int PropertyID, int* Value) {
if (PropertyID == AIMPML_FILTERGROUP_OPERATION)
*Value = static_cast<int>(_managed->Operation);
return S_OK;
}
HRESULT WINAPI InternalAimpDataFilterGroup::SetValueAsInt32(int PropertyID, int Value) {
if (PropertyID == AIMPML_FILTERGROUP_OPERATION)
_managed->Operation = static_cast<FilterGroupOperationType>(Value);
return S_OK;
}
| 33.203125
| 114
| 0.652235
|
Smartoteka
|
01319c06316ba1f9a9dcbb46f8fab72f5bed7355
| 540
|
hpp
|
C++
|
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_physics_manual.hpp
|
weiDDD/particleSystem
|
32652b09da35e025956999227f08be83b5d79cb1
|
[
"Apache-2.0"
] | 34
|
2017-08-16T13:58:24.000Z
|
2022-03-31T11:50:25.000Z
|
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_physics_manual.hpp
|
weiDDD/particleSystem
|
32652b09da35e025956999227f08be83b5d79cb1
|
[
"Apache-2.0"
] | null | null | null |
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_physics_manual.hpp
|
weiDDD/particleSystem
|
32652b09da35e025956999227f08be83b5d79cb1
|
[
"Apache-2.0"
] | 17
|
2017-08-18T07:42:44.000Z
|
2022-01-02T02:43:06.000Z
|
#ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_PHYSICS_MANUAL_H
#define COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_PHYSICS_MANUAL_H
#if CC_USE_PHYSICS
#ifdef __cplusplus
extern "C" {
#endif
#include "tolua++.h"
#ifdef __cplusplus
}
#endif
#include "cocos2d.h"
#include "LuaScriptHandlerMgr.h"
int register_all_cocos2dx_physics_manual(lua_State* tolua_S);
#endif // CC_USE_PHYSICS
#endif // #ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_PHYSICS_MANUAL_H
| 24.545455
| 95
| 0.824074
|
weiDDD
|
0136f6b477e8ff4a69284a42a0c410dca1029e15
| 549
|
cpp
|
C++
|
SourceCode/Chapter 15/Pr15-8.cpp
|
aceiro/poo2019
|
0f93d22296f43a8b024a346f510c00314817d2cf
|
[
"MIT"
] | 1
|
2019-04-09T18:29:38.000Z
|
2019-04-09T18:29:38.000Z
|
SourceCode/Chapter 15/Pr15-8.cpp
|
aceiro/poo2019
|
0f93d22296f43a8b024a346f510c00314817d2cf
|
[
"MIT"
] | null | null | null |
SourceCode/Chapter 15/Pr15-8.cpp
|
aceiro/poo2019
|
0f93d22296f43a8b024a346f510c00314817d2cf
|
[
"MIT"
] | null | null | null |
// This program demonstrates that when a derived class function
// overrides a base class function, objects of the base class
// still call the base class version of the function.
#include <iostream>
using namespace std;
class BaseClass
{
public:
void showMessage()
{ cout << "This is the Base class.\n"; }
};
class DerivedClass : public BaseClass
{
public:
void showMessage()
{ cout << "This is the Derived class.\n"; }
};
int main()
{
BaseClass b;
DerivedClass d;
b.showMessage();
d.showMessage();
return 0;
}
| 18.3
| 63
| 0.675774
|
aceiro
|
01375227a381f8c4055b105b8570ed5ad7ee6c35
| 105,100
|
cpp
|
C++
|
Contrib/at67/functions.cpp
|
veekooFIN/gigatron-rom
|
08c9918cc111d7d2856cecae6da4137ee4641fb2
|
[
"BSD-2-Clause"
] | 172
|
2018-02-26T19:56:11.000Z
|
2022-03-31T17:10:16.000Z
|
Contrib/at67/functions.cpp
|
veekooFIN/gigatron-rom
|
08c9918cc111d7d2856cecae6da4137ee4641fb2
|
[
"BSD-2-Clause"
] | 140
|
2018-01-13T09:57:11.000Z
|
2022-02-15T13:22:05.000Z
|
Contrib/at67/functions.cpp
|
veekooFIN/gigatron-rom
|
08c9918cc111d7d2856cecae6da4137ee4641fb2
|
[
"BSD-2-Clause"
] | 78
|
2018-01-13T01:07:37.000Z
|
2022-03-09T07:59:18.000Z
|
#include <ctime>
#include <random>
#include <numeric>
#include <algorithm>
#include "memory.h"
#include "cpu.h"
#include "functions.h"
#include "operators.h"
namespace Functions
{
int _nestedCount = -1;
double _umin = 0.0;
double _umax = 0.0;
double _ulen = 0.0;
double _ustp = 1.0;
uint16_t _uidx = 0;
std::vector<int16_t> _uvalues;
std::mt19937_64 _randGenerator;
std::map<std::string, std::string> _functions;
std::map<std::string, std::string> _stringFunctions;
std::map<std::string, std::string>& getFunctions(void) {return _functions; }
std::map<std::string, std::string>& getStringFunctions(void) {return _stringFunctions;}
void restart(void)
{
_nestedCount = -1;
_umin = _umax = _ulen = 0.0;
_ustp = 1.0;
_uidx = 0;
_uvalues.clear();
}
bool initialise(void)
{
restart();
// Functions
_functions["IARR" ] = "IARR";
_functions["SARR" ] = "SARR";
_functions["PEEK" ] = "PEEK";
_functions["DEEK" ] = "DEEK";
_functions["USR" ] = "USR";
_functions["RND" ] = "RND";
_functions["URND" ] = "URND";
_functions["LEN" ] = "LEN";
_functions["GET" ] = "GET";
_functions["ABS" ] = "ABS";
_functions["SGN" ] = "SGN";
_functions["ASC" ] = "ASC";
_functions["STRCMP"] = "STRCMP";
_functions["BCDCMP"] = "BCDCMP";
_functions["VAL" ] = "VAL";
_functions["LUP" ] = "LUP";
_functions["ADDR" ] = "ADDR";
_functions["POINT" ] = "POINT";
_functions["MIN" ] = "MIN";
_functions["MAX" ] = "MAX";
_functions["CLAMP" ] = "CLAMP";
// String functions
_stringFunctions["CHR$" ] = "CHR$";
_stringFunctions["SPC$" ] = "SPC$";
_stringFunctions["STR$" ] = "STR$";
_stringFunctions["STRING$"] = "STRING$";
_stringFunctions["TIME$" ] = "TIME$";
_stringFunctions["HEX$" ] = "HEX$";
_stringFunctions["LEFT$" ] = "LEFT$";
_stringFunctions["RIGHT$" ] = "RIGHT$";
_stringFunctions["MID$" ] = "MID$";
_stringFunctions["LOWER$" ] = "LOWER$";
_stringFunctions["UPPER$" ] = "UPPER$";
_stringFunctions["STRCAT$"] = "STRCAT$";
uint64_t timeSeed = time(NULL);
std::seed_seq seedSequence{uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed>>32)};
_randGenerator.seed(seedSequence);
return true;
}
void handleConstantString(const Expression::Numeric& numeric, Compiler::ConstStrType constStrType, std::string& name, int& index)
{
switch(constStrType)
{
case Compiler::StrLeft:
case Compiler::StrRight:
{
uint8_t length = uint8_t(std::lround(numeric._params[0]._value));
Compiler::getOrCreateConstString(constStrType, numeric._text, length, 0, index);
}
break;
case Compiler::StrMid:
{
uint8_t offset = uint8_t(std::lround(numeric._params[0]._value));
uint8_t length = uint8_t(std::lround(numeric._params[1]._value));
Compiler::getOrCreateConstString(constStrType, numeric._text, length, offset, index);
}
break;
case Compiler::StrLower:
case Compiler::StrUpper:
{
Compiler::getOrCreateConstString(constStrType, numeric._text, 0, 0, index);
}
break;
default: break;
}
name = Compiler::getStringVars()[index]._name;
uint16_t srcAddr = Compiler::getStringVars()[index]._address;
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false);
Compiler::emitVcpuAsm("%PrintAcString", "", false);
}
else
{
uint16_t dstAddr = Compiler::getStringVars()[Expression::getOutputNumeric()._index]._address;
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringCopy", "", false);
}
}
void handleStringParameter(Expression::Numeric& param)
{
// Literals
if(param._varType == Expression::Number)
{
// 8bit
if(param._value >=0 && param._value <= 255)
{
Compiler::emitVcpuAsm("LDI", std::to_string(int16_t(std::lround(param._value))), false);
}
// 16bit
else
{
Compiler::emitVcpuAsm("LDWI", std::to_string(int16_t(std::lround(param._value))), false);
}
return;
}
Operators::handleSingleOp("LDW", param);
}
// Does a function contain nested functions as parameters
bool isFuncNested(void)
{
if(Expression::getOutputNumeric()._nestedCount == _nestedCount) return false;
bool codeInit = (_nestedCount == -1);
_nestedCount = Expression::getOutputNumeric()._nestedCount;
if(codeInit) return false;
return true;
}
// ********************************************************************************************
// Functions
// ********************************************************************************************
void opcodeARR(Expression::Numeric& param)
{
// Can't call Operators::handleSingleOp() here, so special case it
switch(param._varType)
{
// Temporary variable address
case Expression::TmpVar:
{
Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(std::lround(param._value))), false);
}
break;
// User variable
case Expression::IntVar16:
{
Compiler::emitVcpuAsmUserVar("LDW", param, false);
}
break;
// Literal or constant
case Expression::Number:
{
Compiler::emitVcpuAsm("LDI", std::to_string(uint8_t(std::lround(param._value))), false);
}
break;
default: break;
}
}
Expression::Numeric IARR(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::IARR() : '%s:%d' : %s cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
Compiler::getNextTempVar();
int intSize = Compiler::getIntegerVars()[numeric._index]._intSize;
uint16_t arrayPtr = Compiler::getIntegerVars()[numeric._index]._address;
// Literal array index, (only optimise for 1d arrays)
if(numeric._varType == Expression::Arr1Var8 && numeric._params.size() == 1 && numeric._params[0]._varType == Expression::Number)
{
std::string operand = Expression::wordToHexString(arrayPtr + uint16_t(numeric._params[0]._value*intSize));
Compiler::emitVcpuAsm("LDWI", operand, false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(numeric._varType == Expression::Arr1Var16 && numeric._params.size() == 1 && numeric._params[0]._varType == Expression::Number)
{
std::string operand = Expression::wordToHexString(arrayPtr + uint16_t(numeric._params[0]._value*intSize));
// Handle .LO and .HI
switch(numeric._int16Byte)
{
case Expression::Int16Low: Compiler::emitVcpuAsm("LDWI", operand, false); Compiler::emitVcpuAsm("PEEK", "", false); break;
case Expression::Int16High: Compiler::emitVcpuAsm("LDWI", operand + " + 1", false); Compiler::emitVcpuAsm("PEEK", "", false); break;
case Expression::Int16Both: Compiler::emitVcpuAsm("LDWI", operand, false); Compiler::emitVcpuAsm("DEEK", "", false); break;
default: break;
}
}
// Variable array index or 2d/3d array
else
{
size_t numDims = 0;
if(numeric._varType >= Expression::Arr1Var8 && numeric._varType <= Expression::Arr3Var8)
{
numDims = numeric._varType - Expression::Arr1Var8 + 1;
}
else if(numeric._varType >= Expression::Arr1Var16 && numeric._varType <= Expression::Arr3Var16)
{
numDims = numeric._varType - Expression::Arr1Var16 + 1;
}
if(numDims != numeric._params.size())
{
fprintf(stderr, "Functions::IARR() : '%s:%d' : %s() expects %d dimension/s, found %d : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), int(numDims), int(numeric._params.size()), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Generate array indices
for(size_t i=0; i<numeric._params.size(); i++)
{
Expression::Numeric param = numeric._params[i];
opcodeARR(param);
Compiler::emitVcpuAsm("STW", "memIndex" + std::to_string(i), false);
}
// Handle 1d/2d/3d arrays
switch(numeric._varType)
{
case Expression::Arr1Var8:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
Compiler::emitVcpuAsm("ADDW", "memIndex0", false);
}
break;
case Expression::Arr2Var8:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
(Compiler::getCodeRomType() >= Cpu::ROMv5a) ? Compiler::emitVcpuAsm("CALLI", "convert8Arr2d", false) : Compiler::emitVcpuAsm("CALL", "convert8Arr2dAddr", false);
}
break;
case Expression::Arr3Var8:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
(Compiler::getCodeRomType() >= Cpu::ROMv5a) ? Compiler::emitVcpuAsm("CALLI", "convert8Arr3d", false) : Compiler::emitVcpuAsm("CALL", "convert8Arr3dAddr", false);
}
break;
case Expression::Arr1Var16:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
Compiler::emitVcpuAsm("ADDW", "memIndex0", false);
Compiler::emitVcpuAsm("ADDW", "memIndex0", false);
}
break;
case Expression::Arr2Var16:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
(Compiler::getCodeRomType() >= Cpu::ROMv5a) ? Compiler::emitVcpuAsm("CALLI", "convert16Arr2d", false) : Compiler::emitVcpuAsm("CALL", "convert16Arr2dAddr", false);
}
break;
case Expression::Arr3Var16:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
(Compiler::getCodeRomType() >= Cpu::ROMv5a) ? Compiler::emitVcpuAsm("CALLI", "convert16Arr3d", false) : Compiler::emitVcpuAsm("CALL", "convert16Arr3dAddr", false);
}
break;
default: break;
}
// Functions like LEN() and ADDR() require IARR() to return the address rather than the value
if(!numeric._returnAddress)
{
// Bytes
if(numeric._varType >= Expression::Arr1Var8 && numeric._varType <= Expression::Arr3Var8)
{
Compiler::emitVcpuAsm("PEEK", "", false);
}
// Words, handle .LO and .HI
else
{
switch(numeric._int16Byte)
{
case Expression::Int16Low: Compiler::emitVcpuAsm("PEEK", "", false); break;
case Expression::Int16High: Compiler::emitVcpuAsm("ADDI", "1", false); Compiler::emitVcpuAsm("PEEK", "", false); break;
case Expression::Int16Both: Compiler::emitVcpuAsm("DEEK", "", false); break;
default: break;
}
}
}
}
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric SARR(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::SARR() : '%s:%d' : %s cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::SARR() : '%s:%d' : %s() expects 1 dimension, found %d : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), int(numeric._params.size()), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// String addresses cannot be combined using boolean expressions, so no need to increment temporary var
//Compiler::getNextTempVar();
uint16_t arrayPtr = Compiler::getStringVars()[numeric._index]._address;
// Literal array index
if(numeric._params[0]._varType == Expression::Number)
{
std::string operand = Expression::wordToHexString(arrayPtr + uint16_t(numeric._params[0]._value)*2);
Compiler::emitVcpuAsm("LDWI", operand, false);
Compiler::emitVcpuAsm("DEEK", "", false);
}
// Variable array index
else
{
Expression::Numeric param = numeric._params[0];
opcodeARR(param);
Compiler::emitVcpuAsm("STW", "memIndex0", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
Compiler::emitVcpuAsm("ADDW", "memIndex0", false);
Compiler::emitVcpuAsm("ADDW", "memIndex0", false);
Compiler::emitVcpuAsm("DEEK", "", false);
}
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._varType = Expression::Str2Var;
numeric._params.clear();
return numeric;
}
Expression::Numeric PEEK(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::PEEK() : '%s:%d' : PEEK() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number)
{
// Optimise for page 0
if(numeric._value >= 0 && numeric._value <= 255)
{
Compiler::emitVcpuAsm("LD", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
Operators::changeToTmpVar(numeric);
return numeric;
}
else
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
}
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("PEEK", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric DEEK(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::PEEK() : '%s:%d' : PEEK() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number)
{
// Optimise for page 0
if(numeric._value >= 0 && numeric._value <= 255)
{
Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
Operators::changeToTmpVar(numeric);
return numeric;
}
else
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
}
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("DEEK", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric USR(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::USR() : '%s:%d' : USR() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number)
{
if(Compiler::getCodeRomType() >= Cpu::ROMv5a)
{
(numeric._value >= 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("CALLI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) :
Compiler::emitVcpuAsm("CALLI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
}
else
{
(numeric._value >= 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) :
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
}
}
Compiler::getNextTempVar();
if(Compiler::getCodeRomType() >= Cpu::ROMv5a)
{
Operators::handleSingleOp("CALLI", numeric);
}
else
{
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("CALL", "giga_vAC", false);
}
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric RND(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
UNREFERENCED_PARAM(moduleName);
UNREFERENCED_PARAM(codeLineText);
UNREFERENCED_PARAM(codeLineStart);
bool useMod = true;
if(numeric._varType == Expression::Number)
{
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
if(numeric._value == 0)
{
std::uniform_int_distribution<uint16_t> distribution(0, 0xFFFF);
numeric._value = distribution(_randGenerator);
}
else
{
std::uniform_int_distribution<uint16_t> distribution(0, uint16_t(numeric._value));
numeric._value = distribution(_randGenerator);
}
return numeric;
}
// RND(0) skips the MOD call and allows you to filter the output manually
if(numeric._value == 0)
{
useMod = false;
}
else
{
(numeric._value > 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) :
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
}
}
Compiler::getNextTempVar();
if(useMod)
{
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("%RandMod", "", false);
}
else
{
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("%Rand", "", false);
}
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric URND(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
UNREFERENCED_PARAM(codeLineStart);
if(!Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : URND only works in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 3)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : URND expects 4 parameters, found %d : %s\n", moduleName.c_str(), codeLineStart, int(numeric._params.size()), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType != Expression::Number || numeric._params[0]._varType != Expression::Number || numeric._params[1]._varType != Expression::Number || numeric._params[2]._varType != Expression::Number)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : URND expects 4 literal parameters, 'URND(<min>, <max>, <len>, <step>) : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Initialise unique random number generator
if(numeric._value != _umin || numeric._params[0]._value != _umax || numeric._params[1]._value != _ulen || numeric._params[2]._value != _ustp)
{
_umin = _umax = _ulen = 0.0;
_ustp = 1.0;
if(abs(numeric._params[0]._value - numeric._value) < numeric._params[1]._value)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : range is smaller than length : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params[0]._value <= numeric._value)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : maximum must be greater than minimum : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params[1]._value <= 0.0 || std::lround(numeric._params[1]._value) > 0xFFFF)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : 0x0000 < length < 0x10000 : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params[2]._value == 0.0)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : step must not be equal to zero : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
_umin = numeric._value;
_umax = numeric._params[0]._value;
_ulen = numeric._params[1]._value;
_ustp = numeric._params[2]._value;
_uidx = 0;
uint16_t range = uint16_t((abs(std::lround(_umax) - std::lround(_umin))) / std::lround(abs(_ustp))) + 1;
if(range == 0)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : step size is too large for range : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
_uvalues.resize(range);
for(int i=0; i<range; i++) _uvalues[i] = int16_t(std::lround(_umin)) + int16_t(i*abs(_ustp));
//std::iota(_uvalues.begin(), _uvalues.end(), int16_t(std::lround(_umin)));
std::shuffle(_uvalues.begin(), _uvalues.end(), _randGenerator);
}
if(_uidx >= uint16_t(_uvalues.size()))
{
fprintf(stderr, "Functions::URND() : '%s:%d' : length is greater than range : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
numeric._value = _uvalues[_uidx++];
return numeric;
}
Expression::Numeric LEN(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._varType == Expression::Number)
{
fprintf(stderr, "Functions::LEN() : '%s:%d' : parameter can't be a literal : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 0)
{
fprintf(stderr, "Functions::LEN() : '%s:%d' : LEN expects 1 parameter, found %d : %s\n", moduleName.c_str(), codeLineStart, int(numeric._params.size()), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Handle non variables
if(numeric._index == -1)
{
switch(numeric._varType)
{
// Get or create constant string
case Expression::String:
{
int index;
Compiler::getOrCreateConstString(numeric._text, index);
numeric._index = int16_t(index);
numeric._varType = Expression::StrVar;
}
break;
// Needs to pass through
case Expression::TmpStrVar:
{
}
break;
default:
{
fprintf(stderr, "Functions::LEN() : '%s:%d' : couldn't find variable name '%s' : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
}
}
int length = 0;
switch(numeric._varType)
{
case Expression::IntVar16:
case Expression::Arr1Var8:
case Expression::Arr2Var8:
case Expression::Arr3Var8:
case Expression::Arr1Var16:
case Expression::Arr2Var16:
case Expression::TmpVar:
case Expression::Arr3Var16: length = Compiler::getIntegerVars()[numeric._index]._intSize; break;
case Expression::Constant: length = Compiler::getConstants()[numeric._index]._size; break;
case Expression::StrVar: length = Compiler::getStringVars()[numeric._index]._size; break;
default: break;
}
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
numeric._value = length;
return numeric;
}
// String vars
if(numeric._varType == Expression::StrVar && !Compiler::getStringVars()[numeric._index]._constant)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStringVars()[numeric._index]._address), false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
// String arrays
else if(numeric._varType == Expression::Str2Var)
{
Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
// Temp string vars
else if(numeric._varType == Expression::TmpStrVar)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStrWorkArea()), false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
// Ints, int arrays and constants
else
{
// Generate code to save result into a tmp var
(length <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(length), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(length), false);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric GET(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::GET() : '%s:%d' : GET() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::String)
{
std::string sysVarName = numeric._text;
Expression::strToUpper(sysVarName);
if(sysVarName == "ROM_READ_DIR" && numeric._params.size() == 1)
{
// Literal constant
if(numeric._params[0]._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value))), false);
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("%RomRead", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params[0]._params.clear();
return numeric._params[0];
}
else if(sysVarName == "SPRITE_LUT" && numeric._params.size() == 1)
{
// Literal constant
if(numeric._params[0]._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value))), false);
}
// Look up sprite lut from sprites lut using a sprite index, (handleSingleOp LDW is skipped if above was a constant literal)
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("STW", "spriteId", false);
Compiler::emitVcpuAsm("%GetSpriteLUT", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params[0]._params.clear();
return numeric._params[0];
}
else if(sysVarName == "MIDI_NOTE" && numeric._params.size() == 1)
{
// Literal constant
if(numeric._params[0]._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value))), false);
}
// Look up a ROM note using a midi index, (handleSingleOp LDW is skipped if above was a constant literal)
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("STW", "musicNote", false);
Compiler::emitVcpuAsm("%GetMidiNote", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params[0]._params.clear();
return numeric._params[0];
}
else if(sysVarName == "MUSIC_NOTE" && numeric._params.size() == 1)
{
// Literal constant
if(numeric._params[0]._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value))), false);
}
// Look up a ROM note using a note index, (handleSingleOp LDW is skipped if above was a constant literal)
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("STW", "musicNote", false);
Compiler::emitVcpuAsm("%GetMusicNote", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params[0]._params.clear();
return numeric._params[0];
}
else if(numeric._params.size() == 0)
{
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
if(sysVarName == "TIME_MODE")
{
Compiler::emitVcpuAsm("LDWI", "handleT_mode + 1", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
if(sysVarName == "TIME_EPOCH")
{
Compiler::emitVcpuAsm("LDWI", "handleT_epoch + 1", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(sysVarName == "TIME_S")
{
Compiler::emitVcpuAsm("LDWI", "_timeArray_ + 0", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(sysVarName == "TIME_M")
{
Compiler::emitVcpuAsm("LDWI", "_timeArray_ + 1", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(sysVarName == "TIME_H")
{
Compiler::emitVcpuAsm("LDWI", "_timeArray_ + 2", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(sysVarName == "TIMER")
{
Compiler::emitVcpuAsm("LDW", "timerTick", false);
}
else if(sysVarName == "TIMER_PREV")
{
Compiler::emitVcpuAsm("LDW", "timerPrev", false);
}
else if(sysVarName == "VBLANK_PROC")
{
if(Compiler::getCodeRomType() < Cpu::ROMv5a)
{
std::string romTypeStr;
getRomTypeStr(Compiler::getCodeRomType(), romTypeStr);
fprintf(stderr, "Functions::GET() : '%s:%d' : version error, 'SET VBLANK_PROC' requires ROMv5a or higher, you are trying to link against '%s' : %s\n", moduleName.c_str(), codeLineStart, romTypeStr.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
else
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(VBLANK_PROC), false);
Compiler::emitVcpuAsm("DEEK", "", false);
}
}
else if(sysVarName == "VBLANK_FREQ")
{
if(Compiler::getCodeRomType() < Cpu::ROMv5a)
{
std::string romTypeStr;
getRomTypeStr(Compiler::getCodeRomType(), romTypeStr);
fprintf(stderr, "Functions::GET() : '%s:%d' : version error, 'SET VBLANK_FREQ' requires ROMv5a or higher, you are trying to link against '%s' : %s\n", moduleName.c_str(), codeLineStart, romTypeStr.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// (256 - n) = vblank interrupt frequency, where n = 1 to 255
else
{
Compiler::emitVcpuAsm("LDWI", "realTS_rti + 2", false);
Compiler::emitVcpuAsm("PEEK", "", false);
Compiler::emitVcpuAsm("STW", "register0", false);
Compiler::emitVcpuAsm("LDWI", "256", false);
Compiler::emitVcpuAsm("SUBW", "register0", false);
}
}
else if(sysVarName == "CURSOR_X")
{
Compiler::emitVcpuAsm("LD", "cursorXY", false);
}
else if(sysVarName == "CURSOR_Y")
{
Compiler::emitVcpuAsm("LD", "cursorXY + 1", false);
}
else if(sysVarName == "CURSOR_XY")
{
Compiler::emitVcpuAsm("LDW", "cursorXY", false);
}
else if(sysVarName == "FG_COLOUR")
{
Compiler::emitVcpuAsm("LD", "fgbgColour + 1", false);
}
else if(sysVarName == "BG_COLOUR")
{
Compiler::emitVcpuAsm("LD", "fgbgColour", false);
}
else if(sysVarName == "FGBG_COLOUR")
{
Compiler::emitVcpuAsm("LDW", "fgbgColour", false);
}
else if(sysVarName == "MIDI_STREAM")
{
Compiler::emitVcpuAsm("LDW", "midiStream", false);
}
else if(sysVarName == "LED_TEMPO")
{
Compiler::emitVcpuAsm("LD", "giga_ledTempo", false);
}
else if(sysVarName == "LED_STATE")
{
Compiler::emitVcpuAsm("LD", "giga_ledState", false);
}
else if(sysVarName == "SOUND_TIMER")
{
Compiler::emitVcpuAsm("LD", "giga_soundTimer", false);
}
else if(sysVarName == "CHANNEL_MASK")
{
Compiler::emitVcpuAsm("LD", "giga_channelMask", false);
Compiler::emitVcpuAsm("ANDI", "0x03", false);
}
else if(sysVarName == "ROM_TYPE")
{
Compiler::emitVcpuAsm("LD", "giga_romType", false);
Compiler::emitVcpuAsm("ANDI", "0xFC", false);
}
else if(sysVarName == "VSP")
{
Compiler::emitVcpuAsm("LD", "giga_vSP", false);
}
else if(sysVarName == "VLR")
{
Compiler::emitVcpuAsm("LD", "giga_vLR", false);
}
else if(sysVarName == "VAC")
{
Compiler::emitVcpuAsm("LD", "giga_vAC", false);
}
else if(sysVarName == "VPC")
{
Compiler::emitVcpuAsm("LD", "giga_vPC", false);
}
else if(sysVarName == "XOUT_MASK")
{
Compiler::emitVcpuAsm("LD", "giga_xoutMask", false);
}
else if(sysVarName == "BUTTON_STATE")
{
Compiler::emitVcpuAsm("LD", "giga_buttonState", false);
}
else if(sysVarName == "SERIAL_RAW")
{
Compiler::emitVcpuAsm("LD", "giga_serialRaw", false);
}
else if(sysVarName == "FRAME_COUNT")
{
Compiler::emitVcpuAsm("LD", "giga_frameCount", false);
}
else if(sysVarName == "VIDEO_Y")
{
Compiler::emitVcpuAsm("LD", "giga_videoY", false);
}
else if(sysVarName == "RAND2")
{
Compiler::emitVcpuAsm("LD", "giga_rand2", false);
}
else if(sysVarName == "RAND1")
{
Compiler::emitVcpuAsm("LD", "giga_rand1", false);
}
else if(sysVarName == "RAND0")
{
Compiler::emitVcpuAsm("LD", "giga_rand0", false);
}
else if(sysVarName == "MEM_SIZE")
{
Compiler::emitVcpuAsm("LD", "giga_memSize", false);
}
else if(sysVarName == "Y_RES")
{
Compiler::emitVcpuAsm("LDI", "giga_yres", false);
}
else if(sysVarName == "X_RES")
{
Compiler::emitVcpuAsm("LDI", "giga_xres", false);
}
else if(sysVarName == "SND_CHN4")
{
Compiler::emitVcpuAsm("LDWI", "giga_soundChan4", false);
}
else if(sysVarName == "SND_CHN3")
{
Compiler::emitVcpuAsm("LDWI", "giga_soundChan3", false);
}
else if(sysVarName == "SND_CHN2")
{
Compiler::emitVcpuAsm("LDWI", "giga_soundChan2", false);
}
else if(sysVarName == "SND_CHN1")
{
Compiler::emitVcpuAsm("LDWI", "giga_soundChan1", false);
}
else if(sysVarName == "V_TOP")
{
Compiler::emitVcpuAsm("LDWI", "giga_videoTop", false);
}
else if(sysVarName == "V_TABLE")
{
Compiler::emitVcpuAsm("LDWI", "giga_videoTable", false);
}
else if(sysVarName == "V_RAM")
{
Compiler::emitVcpuAsm("LDWI", "giga_vram", false);
}
else if(sysVarName == "ROM_NOTES")
{
Compiler::emitVcpuAsm("LDWI", "giga_notesTable", false);
}
else if(sysVarName == "ROM_TEXT82")
{
Compiler::emitVcpuAsm("LDWI", "giga_text82", false);
}
else if(sysVarName == "ROM_TEXT32")
{
Compiler::emitVcpuAsm("LDWI", "giga_text32", false);
}
else
{
fprintf(stderr, "Functions::GET() : '%s:%d' : system variable name '%s' does not exist : %s\n", moduleName.c_str(), codeLineStart, numeric._text.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
}
return numeric;
}
Expression::Numeric ABS(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::ABS() : '%s:%d' : ABS() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType != Expression::String && numeric._varType != Expression::StrVar && numeric._varType != Expression::TmpStrVar)
{
Compiler::getNextTempVar();
if(numeric._varType == Expression::Number)
{
numeric._value = abs(numeric._value);
(numeric._value >= 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) :
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
else
{
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("%Absolute", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
}
return numeric;
}
Expression::Numeric SGN(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::SGN() : '%s:%d' : SGN() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType != Expression::String && numeric._varType != Expression::StrVar && numeric._varType != Expression::TmpStrVar)
{
Compiler::getNextTempVar();
if(numeric._varType == Expression::Number)
{
numeric._value = Expression::sgn(numeric._value);
(numeric._value >= 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) :
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
else
{
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("%Sign", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
}
return numeric;
}
Expression::Numeric ASC(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._varType == Expression::Number)
{
fprintf(stderr, "Functions::ASC() : '%s:%d' : parameter can't be a literal : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
Compiler::getNextTempVar();
// Handle non variables
if(numeric._index == -1)
{
switch(numeric._varType)
{
// Get or create constant string
case Expression::String:
{
int index;
Compiler::getOrCreateConstString(numeric._text, index);
numeric._index = int16_t(index);
numeric._varType = Expression::StrVar;
}
break;
case Expression::TmpStrVar:
{
}
break;
default:
{
fprintf(stderr, "Functions::ASC() : '%s:%d' : couldn't find variable name '%s' : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
}
}
uint8_t ascii = 0;
switch(numeric._varType)
{
case Expression::StrVar: ascii = Compiler::getStringVars()[numeric._index]._text[0]; break;
case Expression::Constant: ascii = Compiler::getConstants()[numeric._index]._text[0]; break;
default: break;
}
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
numeric._value = ascii;
return numeric;
}
// Variables
if(numeric._varType == Expression::StrVar && !Compiler::getStringVars()[numeric._index]._constant)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStringVars()[numeric._index]._address) + " + 1", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(numeric._varType == Expression::TmpStrVar)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStrWorkArea()) + " + 1", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
// Constants
else
{
// Generate code to save result into a tmp var
Compiler::emitVcpuAsm("LDI", std::to_string(ascii), false);
}
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric STRCMP(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::STRCMP() : '%s:%d' : STRCMP() requires two string parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal strings, (optimised case)
if(numeric._varType == Expression::String && numeric._params[0]._varType == Expression::String)
{
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
numeric._varType = Expression::Number;
numeric._value = uint8_t(numeric._text == numeric._params[0]._text) - 1;
numeric._params.clear();
return numeric;
}
// Generate code to save result into a tmp var
else
{
int result = int(numeric._text == numeric._params[0]._text) - 1;
(result >= 0 && result <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(result), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(result), false);
}
}
else
{
// Get addresses of strings to be compared
uint16_t srcAddr0 = 0x0000, srcAddr1 = 0x0000;
if(numeric._varType == Expression::TmpStrVar) srcAddr0 = Compiler::getStrWorkArea(0);
if(numeric._params[0]._varType == Expression::TmpStrVar) srcAddr1 = Compiler::getStrWorkArea(0);
if(numeric._varType == Expression::TmpStrVar && numeric._params[0]._varType == Expression::TmpStrVar)
{
// If both params are temp strs then swap them so they compare correctly
srcAddr1 = Compiler::getStrWorkArea(1);
std::swap(srcAddr0, srcAddr1);
}
if(!srcAddr0)
{
std::string name;
int index = int(numeric._index);
Compiler::getOrCreateString(numeric, name, srcAddr0, index);
}
if(!srcAddr1)
{
std::string name;
int index = int(numeric._params[0]._index);
Compiler::getOrCreateString(numeric._params[0], name, srcAddr1, index);
}
// By definition this must be a match
if(srcAddr0 == srcAddr1)
{
Compiler::emitVcpuAsm("LDI", "1", false);
}
// Compare strings, -1, 0, 1, (smaller, equal, bigger)
else
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr0), false);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr1), false);
Compiler::emitVcpuAsm("%StringCmp", "", false);
Compiler::emitVcpuAsm("SUBI", "1", false); // convert 0, 1, 2 to -1, 0, 1
}
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric BCDCMP(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::BCDCMP() : '%s:%d' : BCDCMP() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 2)
{
fprintf(stderr, "Functions::BCDCMP() : '%s:%d' : BCDCMP() requires three string parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Get addresses and length of bcd values to be compared
uint16_t srcAddr0 = uint16_t(numeric._value);
uint16_t srcAddr1 = uint16_t(numeric._params[0]._value);
uint16_t length = uint16_t(numeric._params[1]._value);
// Compare bcd values, (addresses MUST point to msd)
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr0), false);
Compiler::emitVcpuAsm("STW", "bcdSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr1), false);
Compiler::emitVcpuAsm("STW", "bcdDstAddr", false);
Compiler::emitVcpuAsm("LDI", std::to_string(length), false);
Compiler::emitVcpuAsm("%BcdCmp", "", false);
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric VAL(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._params.size() != 0)
{
fprintf(stderr, "Functions::VAL() : '%s:%d' : VAL() requires only one string parameter : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal strings, (optimised case)
if(numeric._varType == Expression::String)
{
int16_t val = 0;
Expression::stringToI16(numeric._text, val);
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
numeric._varType = Expression::Number;
numeric._value = val;
return numeric;
}
// Generate code to save result into a tmp var
else
{
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
}
}
else
{
// Get addresses of src string
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
Compiler::getOrCreateString(numeric, name, srcAddr, index);
// StringVal expects srcAddr to point past the string's length byte
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr + 1), false);
Compiler::emitVcpuAsm("%IntegerStr", "", false);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric LUP(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::LUP() : '%s:%d' : LUP(<address>, <offset>) cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::LUP() : '%s:%d' : LUP(<address>, <offset>) missing offset : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params[0]._varType != Expression::Number)
{
fprintf(stderr, "Functions::LUP() : '%s:%d' : LUP(<address>, <offset>) offset is not a constant literal : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
std::string offset = Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value)));
if(numeric._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(uint16_t(std::lround(numeric._value))), false);
}
else
{
Operators::createSingleOp("LDW", numeric);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("LUP", offset, false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric ADDR(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._varType == Expression::Number)
{
fprintf(stderr, "Functions::ADDR() : '%s:%d' : parameter can't be a literal : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 0)
{
fprintf(stderr, "Functions::ADDR() : '%s:%d' : expects 1 parameter, found %d : %s\n", moduleName.c_str(), codeLineStart, int(numeric._params.size()), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Handle non variables
if(numeric._index == -1)
{
switch(numeric._varType)
{
// Get or create constant string
case Expression::String:
{
int index;
Compiler::getOrCreateConstString(numeric._text, index);
numeric._index = int16_t(index);
numeric._varType = Expression::StrVar;
}
break;
// Needs to pass through
case Expression::TmpStrVar:
{
}
break;
default:
{
fprintf(stderr, "Functions::ADDR() : '%s:%d' : couldn't find variable name '%s' : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
}
}
uint16_t address = 0x0000;
switch(numeric._varType)
{
case Expression::IntVar16:
case Expression::Arr1Var8:
case Expression::Arr1Var16: address = Compiler::getIntegerVars()[numeric._index]._address; break;
case Expression::Constant: address = Compiler::getConstants()[numeric._index]._address; break;
case Expression::StrVar: address = Compiler::getStringVars()[numeric._index]._address; break;
default: break;
}
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
switch(numeric._varType)
{
case Expression::TmpVar:
case Expression::Str2Var:
{
fprintf(stderr, "Functions::ADDR() : '%s:%d' : can't statically initialise from multi-dimensional array '%s' : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
default: break;
}
numeric._value = address;
return numeric;
}
// String vars
if(numeric._varType == Expression::StrVar && !Compiler::getStringVars()[numeric._index]._constant)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStringVars()[numeric._index]._address), false);
}
// Multi-dimensional arrays, (array of strings, Str2Var, is treated as a 2D array of bytes)
else if(numeric._varType == Expression::TmpVar || numeric._varType == Expression::Str2Var)
{
Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
// Temp string vars
else if(numeric._varType == Expression::TmpStrVar)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStrWorkArea()), false);
}
// Ints, int arrays and constants
else
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(address), false);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric POINT(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::POINT() : '%s:%d' : POINT() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::POINT() : '%s:%d' : syntax error, 'POINT(x, y)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("ST", "readPixel_xy", false);
}
else
{
Operators::createSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("ST", "readPixel_xy", false);
}
if(numeric._params[0]._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value))), false);
Compiler::emitVcpuAsm("ST", "readPixel_xy + 1", false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("ST", "readPixel_xy + 1", false);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("%ReadPixel", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric MIN(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::MIN() : '%s:%d' : syntax error, 'MIN(x, y)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number && numeric._params[0]._varType == Expression::Number)
{
numeric._value = std::min(numeric._value, numeric._params[0]._value);
numeric._params.clear();
return numeric;
}
if(numeric._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
else
{
Operators::createSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
if(numeric._params[0]._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._params[0]._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[0]);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("%IntMin", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric MAX(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::MAX() : '%s:%d' : syntax error, 'MAX(x, y)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number && numeric._params[0]._varType == Expression::Number)
{
numeric._value = std::max(numeric._value, numeric._params[0]._value);
numeric._params.clear();
return numeric;
}
if(numeric._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
else
{
Operators::createSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
if(numeric._params[0]._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._params[0]._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[0]);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("%IntMax", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric CLAMP(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._params.size() != 2)
{
fprintf(stderr, "Functions::CLAMP() : '%s:%d' : syntax error, 'CLAMP(x, a, b)' requires three parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number && numeric._params[0]._varType == Expression::Number && numeric._params[1]._varType == Expression::Number)
{
numeric._value = std::min(std::max(numeric._value, numeric._params[0]._value), numeric._params[1]._value);
numeric._params.clear();
return numeric;
}
if(numeric._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
Compiler::emitVcpuAsm("STW", "intSrcX", false);
}
else
{
Operators::createSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("STW", "intSrcX", false);
}
if(numeric._params[0]._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._params[0]._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
if(numeric._params[1]._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._params[1]._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[1]);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("%IntClamp", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric CHR$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::CHR$() : '%s:%d' : CHR$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
if(numeric._varType == Expression::Number)
{
// Print CHR string, (without wasting memory)
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("LDI", std::to_string(int16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("%PrintAcChr", "", false);
return numeric;
}
// Create CHR string
Compiler::emitVcpuAsm("LDI", std::to_string(int16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("STW", "strChr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringChr", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintAcChr", "", false);
return numeric;
}
// Create CHR string
Compiler::emitVcpuAsm("STW", "strChr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringChr", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Expression::Numeric SPC$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::SPC$() : '%s:%d' : SPC$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
if(numeric._varType == Expression::Number)
{
uint8_t len = uint8_t(std::lround(numeric._value));
if(len < 1 || len > 94)
{
fprintf(stderr, "Functions::SPC$() : '%s:%d' : syntax error, 'SPC$(n)', if 'n' is a literal, it MUST be <1-94> : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("LDI", std::to_string(len), false);
Compiler::emitVcpuAsm("%PrintSpc", "", false);
return numeric;
}
// Create SPC string
Compiler::emitVcpuAsm("LDI", std::to_string(len), false);
Compiler::emitVcpuAsm("STW", "strLen", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringSpc", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintSpc", "", false);
return numeric;
}
// Create SPC string
Compiler::emitVcpuAsm("STW", "strLen", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringSpc", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Expression::Numeric STR$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::STR$() : '%s:%d' : STR$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
if(numeric._varType == Expression::Number)
{
// Print STR string, (without wasting memory)
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("%PrintAcInt16", "", false);
return numeric;
}
// Create STR string
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("STW", "strInteger", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringInt", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintAcInt16", "", false);
return numeric;
}
// Create STR string
Compiler::emitVcpuAsm("STW", "strInteger", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringInt", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Expression::Numeric STRING$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::STRING$() : '%s:%d' : STRING$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number)
{
// Print STR string, (without wasting memory)
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(uint16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("%PrintAcString", "", false);
return numeric;
}
// Point to STR address
return Expression::Numeric(numeric._value, uint16_t(-1), true, false, false, Expression::StrAddr, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintAcString", "", false);
return numeric;
}
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._varType = Expression::TmpStrAddr;
return numeric;
}
Expression::Numeric TIME$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::TIME$() : '%s:%d' : TIME$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Function with no parameters, so isValid needs to be explicitly set
numeric._isValid = true;
// Generate new time string
Compiler::emitVcpuAsm("%TimeString", "", false);
// Print it directly if able
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintString", "_timeString_", false);
return numeric;
}
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
Compiler::emitVcpuAsm("LDWI", "_timeString_", false);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringCopy", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Expression::Numeric HEX$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::HEX$() : '%s:%d' : HEX$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::HEX$() : '%s:%d' : syntax error, 'HEX$(x, n)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params[0]._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._params[0]._value));
if(val < 1 || val > 4)
{
fprintf(stderr, "Functions::HEX$() : '%s:%d' : syntax error, 'HEX$(x, n)', if 'n' is a literal, it MUST be <1-4> : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
Compiler::emitVcpuAsm("LDI", std::to_string(val), false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[0]);
}
Compiler::emitVcpuAsm("ST", "textLen", false);
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
if(numeric._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(uint16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("STW", "textHex", false);
// Print HEX string, (without wasting memory)
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintHex", "", false);
numeric._params.clear();
return numeric;
}
// Create HEX string
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringHex", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("STW", "textHex", false);
Compiler::emitVcpuAsm("%PrintHex", "", false);
numeric._params.clear();
return numeric;
}
// Create HEX string
Compiler::emitVcpuAsm("STW", "strHex", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringHex", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Expression::Numeric LEFT$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::LEFT$() : '%s:%d' : LEFT$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::LEFT$() : '%s:%d' : syntax error, 'LEFT$(s$, n)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal string and parameter, (optimised case)
if(numeric._varType == Expression::String && numeric._params[0]._varType == Expression::Number)
{
int index;
std::string name;
handleConstantString(numeric, Compiler::StrLeft, name, index);
return Expression::Numeric(0, uint16_t(index), true, false, false, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
// Non optimised case
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
// String input can be literal, const, var and temp
if(numeric._varType == Expression::TmpStrVar)
{
// Second parameter can never be a temp string
srcAddr = Compiler::getStrWorkArea();
}
else
{
Compiler::getOrCreateString(numeric, name, srcAddr, index);
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "textStr", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "textLen", false);
Compiler::emitVcpuAsm("%PrintAcLeft", "", false);
}
else
{
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
// Optimise STW/LDW
if(numeric._params[0]._varType == Expression::TmpVar)
{
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "strDstLen", false);
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
}
else
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "strDstLen", false);
}
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringLeft", "", false);
}
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
Expression::Numeric RIGHT$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::RIGHT$() : '%s:%d' : RIGHT$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::RIGHT$() : '%s:%d' : syntax error, 'RIGHT$(s$, n)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal string and parameter, (optimised case)
if(numeric._varType == Expression::String && numeric._params[0]._varType == Expression::Number)
{
int index;
std::string name;
handleConstantString(numeric, Compiler::StrRight, name, index);
return Expression::Numeric(0, uint16_t(index), true, false, false, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
// Non optimised case
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
// String input can be literal, const, var and temp
if(numeric._varType == Expression::TmpStrVar)
{
srcAddr = Compiler::getStrWorkArea();
}
else
{
Compiler::getOrCreateString(numeric, name, srcAddr, index);
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "textStr", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "textLen", false);
Compiler::emitVcpuAsm("%PrintAcRight", "", false);
}
else
{
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
// Optimise STW/LDW
if(numeric._params[0]._varType == Expression::TmpVar)
{
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "strDstLen", false);
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
}
else
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "strDstLen", false);
}
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringRight", "", false);
}
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
Expression::Numeric MID$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::MID$() : '%s:%d' : MID$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 2)
{
fprintf(stderr, "Functions::MID$() : '%s:%d' : syntax error, 'MID$(s$, i, n)' requires three parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal string and parameters, (optimised case)
if(numeric._varType == Expression::String && numeric._params[0]._varType == Expression::Number && numeric._params[1]._varType == Expression::Number)
{
int index;
std::string name;
handleConstantString(numeric, Compiler::StrMid, name, index);
return Expression::Numeric(0, uint16_t(index), true, false, false, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
// Non optimised case
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
// String input can be literal, const, var and temp
if(numeric._varType == Expression::TmpStrVar)
{
srcAddr = Compiler::getStrWorkArea();
}
else
{
Compiler::getOrCreateString(numeric, name, srcAddr, index);
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "textStr", false);
handleStringParameter(numeric._params[1]);
Compiler::emitVcpuAsm("STW", "textLen", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "textOfs", false);
Compiler::emitVcpuAsm("%PrintAcMid", "", false);
}
else
{
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
handleStringParameter(numeric._params[1]);
Compiler::emitVcpuAsm("STW", "strDstLen", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "strOffset", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringMid", "", false);
}
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
Expression::Numeric LOWER$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::LOWER$() : '%s:%d' : LOWER$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 0)
{
fprintf(stderr, "Functions::LOWER$() : '%s:%d' : syntax error, 'LOWER$()' requires one string parameter : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal string and parameter, (optimised case)
if(numeric._varType == Expression::String)
{
int index;
std::string name;
handleConstantString(numeric, Compiler::StrLower, name, index);
return Expression::Numeric(0, uint16_t(index), true, false, false, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
// Non optimised case
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
// String input can be literal, const, var and temp
if(numeric._varType == Expression::TmpStrVar)
{
srcAddr = Compiler::getStrWorkArea();
}
else
{
Compiler::getOrCreateString(numeric, name, srcAddr, index);
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "textStr", false);
Compiler::emitVcpuAsm("%PrintAcLower", "", false);
}
else
{
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringLower", "", false);
}
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
Expression::Numeric UPPER$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::UPPER$() : '%s:%d' : UPPER$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 0)
{
fprintf(stderr, "Functions::UPPER$() : '%s:%d' : syntax error, 'UPPER$()' requires one string parameter : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal string and parameter, (optimised case)
if(numeric._varType == Expression::String)
{
int index;
std::string name;
handleConstantString(numeric, Compiler::StrUpper, name, index);
return Expression::Numeric(0, uint16_t(index), true, false, false, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
// Non optimised case
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
// String input can be literal, const, var and temp
if(numeric._varType == Expression::TmpStrVar)
{
srcAddr = Compiler::getStrWorkArea();
}
else
{
Compiler::getOrCreateString(numeric, name, srcAddr, index);
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "textStr", false);
Compiler::emitVcpuAsm("%PrintAcUpper", "", false);
}
else
{
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringUpper", "", false);
}
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
Expression::Numeric STRCAT$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : STRCAT$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(Expression::getEnableOptimisedPrint())
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : syntax error, STRCAT$() cannot be used in PRINT statements : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() == 0)
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : syntax error, STRCAT$() requires at least two string parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::TmpStrVar)
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : syntax error, STRCAT$() requires string literals or string variables as ALL parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
for(int i=0; i<int(numeric._params.size()); i++)
{
if(numeric._params[i]._varType == Expression::TmpStrVar)
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : syntax error, STRCAT$() requires string literals or string variables as ALL parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
}
// Source string addresses, (extra 0x0000 delimiter used by VASM runtime)
std::string name;
int index = int(numeric._index);
std::vector<uint16_t> strAddrs(numeric._params.size() + 2, 0x0000);
Compiler::getOrCreateString(numeric, name, strAddrs[0], index);
for(int i=0; i<int(numeric._params.size()); i++)
{
index = int(numeric._params[i]._index);
Compiler::getOrCreateString(numeric._params[i], name, strAddrs[i + 1], index);
}
// Source string addresses LUT
uint16_t lutAddress;
if(!Memory::getFreeRAM(Memory::FitDescending, int(strAddrs.size()*2), USER_CODE_START, Compiler::getStringsStart(), lutAddress))
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : not enough RAM for string concatenation LUT of size %d : %s\n", moduleName.c_str(), codeLineStart, int(strAddrs.size()), codeLineText.c_str());
return false;
}
Compiler::getCodeLines()[Compiler::getCurrentCodeLineIndex()]._strConcatLut = {lutAddress, strAddrs};
// Concatenate multiple source strings to string work area
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(lutAddress), false);
Compiler::emitVcpuAsm("STW", "strLutAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStrWorkArea()), false);
Compiler::emitVcpuAsm("%StringConcatLut", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
}
| 43.82819
| 252
| 0.557916
|
veekooFIN
|
0137689f5d1a19f6f7f3b962df0f9d939eac85fd
| 1,983
|
cc
|
C++
|
stapl_release/docs/reference/view/multi.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
stapl_release/docs/reference/view/multi.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
stapl_release/docs/reference/view/multi.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
// cont/multi.cc
#include <stapl/containers/multiarray/multiarray.hpp>
#include <stapl/views/multiarray_view.hpp>
#include <stapl/containers/type_traits/default_traversal.hpp>
#include <stapl/algorithms/algorithm.hpp>
#include <stapl/algorithms/functional.hpp>
#include "viewhelp.hpp"
using namespace std;
typedef int val_tp;
typedef stapl::indexed_domain<size_t> vec_dom_tp;
typedef stapl::balanced_partition<vec_dom_tp> bal_part_tp;
typedef stapl::default_traversal<3>::type trav3_tp;
typedef stapl::nd_partition<
stapl::tuple<bal_part_tp, bal_part_tp, bal_part_tp>,
trav3_tp> part3_tp;
typedef stapl::tuple<size_t, size_t, size_t> gid_tp;
typedef stapl::multiarray<3, int, trav3_tp, part3_tp> ary3_int_tp;
typedef stapl::multiarray_view<ary3_int_tp> ary3_int_vw_tp;
typedef ary3_int_vw_tp::domain_type dom_tp;
typedef stapl::plus<val_tp> add_int_wf;
stapl::exit_code stapl_main(int argc, char **argv) {
// construct container
stapl::tuple<size_t,size_t,size_t> dims = stapl::make_tuple(3,4,5);
ary3_int_tp a_ct(dims), b_ct(dims), c_ct(dims);
// construct view over container
ary3_int_vw_tp a_vw(a_ct), b_vw(b_ct), c_vw(c_ct);
auto a_lin_vw = stapl::linear_view(a_vw);
auto b_lin_vw = stapl::linear_view(b_vw);
auto c_lin_vw = stapl::linear_view(c_vw);
// initialize containers in parallel
int base = 0;
int step = 10;
typedef stapl::sequence<int> step_wf;
stapl::generate(a_lin_vw, step_wf(base,step));
int rep = 12;
typedef stapl::block_sequence<int> repeat_wf;
stapl::generate(b_lin_vw, repeat_wf(base,rep));
stapl::iota(c_lin_vw, 0);
// process elements in parallel
stapl::transform( a_lin_vw, b_lin_vw, c_lin_vw, add_int_wf() );
// print elements
stapl::stream<ofstream> zout;
zout.open("refman_multvw.txt");
stapl::serial_io( put_val_wf(zout), c_vw );
return EXIT_SUCCESS;
}
| 30.984375
| 70
| 0.704488
|
parasol-ppl
|
01376e57347f54f4d6ca3209bcd2429d52c0bcdc
| 17,513
|
hpp
|
C++
|
include/Avocado/backend/backend_descriptors.hpp
|
AvocadoML/Avocado
|
9595cc5994d916f0ecb24873a5afa98437977fb5
|
[
"Apache-2.0"
] | null | null | null |
include/Avocado/backend/backend_descriptors.hpp
|
AvocadoML/Avocado
|
9595cc5994d916f0ecb24873a5afa98437977fb5
|
[
"Apache-2.0"
] | null | null | null |
include/Avocado/backend/backend_descriptors.hpp
|
AvocadoML/Avocado
|
9595cc5994d916f0ecb24873a5afa98437977fb5
|
[
"Apache-2.0"
] | null | null | null |
/*
* backend_descriptors.hpp
*
* Created on: Dec 5, 2021
* Author: Maciej Kozarzewski
*/
#ifndef AVOCADO_BACKEND_BACKEND_DESCRIPTORS_HPP_
#define AVOCADO_BACKEND_BACKEND_DESCRIPTORS_HPP_
#include "backend_defs.h"
#include <type_traits>
#include <array>
#include <vector>
#include <stack>
#include <algorithm>
#include <complex>
#include <memory>
#include <cstring>
#include <cassert>
#include <mutex>
#include <iostream>
#if USE_CPU
#elif USE_CUDA
# include <cuda_runtime_api.h>
# include <cuda_fp16.h>
# include <cublas_v2.h>
#elif USE_OPENCL
# include <CL/cl.hpp>
#else
#endif
namespace avocado
{
namespace backend
{
#if USE_CPU
namespace cpu
{
#elif USE_CUDA
namespace cuda
{
#elif USE_OPENCL
namespace opencl
{
#else
namespace reference
{
#endif
int get_number_of_devices();
avDeviceType_t get_device_type(av_int64 descriptor) noexcept;
int get_descriptor_type(av_int64 descriptor) noexcept;
avDeviceIndex_t get_device_index(av_int64 descriptor) noexcept;
int get_descriptor_index(av_int64 descriptor) noexcept;
av_int64 get_current_device_type() noexcept;
av_int64 get_current_device_index() noexcept;
av_int64 create_descriptor(int index, av_int64 type);
int dataTypeSize(avDataType_t dtype) noexcept;
class MemoryDescriptor
{
#if USE_OPENCL
int8_t *m_data = nullptr;
#else
int8_t *m_data = nullptr;
#endif
avDeviceIndex_t m_device_index = AVOCADO_INVALID_DEVICE_INDEX;
av_int64 m_size = 0;
av_int64 m_offset = 0;
bool m_is_owning = false;
public:
static constexpr av_int64 descriptor_type = 1;
MemoryDescriptor() = default;
#if USE_CUDA or USE_OPENCL
MemoryDescriptor(avDeviceIndex_t index, av_int64 sizeInBytes);
#else
MemoryDescriptor(av_int64 sizeInBytes);
#endif
MemoryDescriptor(const MemoryDescriptor &other, av_int64 size, av_int64 offset);
MemoryDescriptor(const MemoryDescriptor &other) = delete;
MemoryDescriptor(MemoryDescriptor &&other);
MemoryDescriptor& operator=(const MemoryDescriptor &other) = delete;
MemoryDescriptor& operator=(MemoryDescriptor &&other);
~MemoryDescriptor();
bool isNull() const noexcept;
av_int64 size() const noexcept;
avDeviceIndex_t device() const noexcept;
static std::string className();
/**
* \brief This method allocates new memory block and sets up the descriptor.
*/
#if USE_CUDA or USE_OPENCL
void create(avDeviceIndex_t index, av_int64 sizeInBytes);
#else
void create(av_int64 sizeInBytes);
#endif
/**
* \brief Creates a non-owning view of another memory block.
*/
void create(const MemoryDescriptor &other, av_int64 size, av_int64 offset);
/**
* \brief This method deallocates underlying memory and resets the descriptor.
* Calling this method on an already destroyed descriptor has no effect.
*/
void destroy();
#if USE_OPENCL
// cl::Buffer& data(void *ptr) noexcept;
// const cl::Buffer& data(const void *ptr) const noexcept;
template<typename T = void>
T* data() noexcept
{
return reinterpret_cast<T*>(m_data + m_offset);
}
template<typename T = void>
const T* data() const noexcept
{
return reinterpret_cast<const T*>(m_data + m_offset);
}
#else
template<typename T = void>
T* data() noexcept
{
return reinterpret_cast<T*>(m_data);
}
template<typename T = void>
const T* data() const noexcept
{
return reinterpret_cast<const T*>(m_data);
}
#endif
};
class ContextDescriptor
{
#if USE_CPU
#elif USE_CUDA
cudaStream_t m_stream = nullptr;
cublasHandle_t m_handle = nullptr;
#elif USE_OPENCL
#else
#endif
avDeviceIndex_t m_device_index = AVOCADO_INVALID_DEVICE_INDEX;
mutable MemoryDescriptor m_workspace;
mutable av_int64 m_workspace_size = 0;
public:
static constexpr av_int64 descriptor_type = 2;
ContextDescriptor() = default;
ContextDescriptor(const ContextDescriptor &other) = delete;
ContextDescriptor(ContextDescriptor &&other);
ContextDescriptor& operator=(const ContextDescriptor &other) = delete;
ContextDescriptor& operator=(ContextDescriptor &&other);
~ContextDescriptor();
static std::string className();
/**
* \brief This method initializes context descriptor.
*/
#if USE_CPU
void create();
#elif USE_CUDA
void create(avDeviceIndex_t index, bool useDefaultStream = false);
#elif USE_OPENCL
void create(avDeviceIndex_t index, bool useDefaultCommandQueue);
#else
void create();
#endif
/**
* \brief This method destroys context and all its resources.
* Calling this method on an already destroyed descriptor has no effect.
*/
void destroy();
MemoryDescriptor& getWorkspace() const;
#if USE_CUDA
void setDevice() const;
avDeviceIndex_t getDevice() const noexcept;
cudaStream_t getStream() const noexcept;
cublasHandle_t getHandle() const noexcept;
#endif
};
class TensorDescriptor
{
std::array<int, AVOCADO_MAX_TENSOR_DIMENSIONS> m_dimensions;
std::array<int, AVOCADO_MAX_TENSOR_DIMENSIONS> m_strides;
int m_number_of_dimensions = 0;
avDataType_t m_dtype = AVOCADO_DTYPE_UNKNOWN;
public:
static constexpr av_int64 descriptor_type = 3;
TensorDescriptor() = default;
TensorDescriptor(std::initializer_list<int> dimensions, avDataType_t dtype);
static std::string className();
void create();
void destroy();
void set(avDataType_t dtype, int nbDims, const int dimensions[]);
void get(avDataType_t *dtype, int *nbDims, int dimensions[]) const;
int& operator[](int index);
int operator[](int index) const;
int dimension(int index) const;
int nbDims() const noexcept;
av_int64 sizeInBytes() const noexcept;
int getIndex(std::initializer_list<int> indices) const noexcept;
int firstDim() const noexcept;
int lastDim() const noexcept;
int volume() const noexcept;
int volumeWithoutFirstDim() const noexcept;
int volumeWithoutLastDim() const noexcept;
avDataType_t dtype() const noexcept;
bool equalShape(const TensorDescriptor &other) noexcept;
std::string toString() const;
private:
void setup_stride();
};
class ConvolutionDescriptor
{
public:
static constexpr av_int64 descriptor_type = 4;
avConvolutionMode_t mode = AVOCADO_CONVOLUTION_MODE;
int dimensions = 2;
std::array<int, 3> padding;
std::array<int, 3> stride;
std::array<int, 3> dilation;
std::array<uint8_t, 16> padding_value;
int groups = 1;
ConvolutionDescriptor() = default;
void create();
void destroy();
static std::string className();
void set(avConvolutionMode_t mode, int nbDims, const int padding[], const int strides[], const int dilation[], int groups,
const void *paddingValue);
void get(avConvolutionMode_t *mode, int *nbDims, int padding[], int strides[], int dilation[], int *groups,
void *paddingValue) const;
template<typename T>
T getPaddingValue() const noexcept
{
static_assert(sizeof(T) <= sizeof(padding_value), "");
T result;
std::memcpy(&result, padding_value.data(), sizeof(T));
return result;
}
bool paddingWithZeros() const noexcept;
TensorDescriptor getOutputShape(const TensorDescriptor &xDesc, const TensorDescriptor &wDesc) const;
bool isStrided() const noexcept;
bool isDilated() const noexcept;
std::string toString() const;
};
class PoolingDescriptor
{
public:
static constexpr av_int64 descriptor_type = 5;
avPoolingMode_t mode = AVOCADO_POOLING_MAX;
std::array<int, 3> filter;
std::array<int, 3> padding;
std::array<int, 3> stride;
PoolingDescriptor() = default;
void create();
void destroy();
static std::string className();
};
class OptimizerDescriptor
{
public:
static constexpr av_int64 descriptor_type = 6;
avOptimizerType_t type = AVOCADO_OPTIMIZER_SGD;
int64_t steps = 0;
double learning_rate = 0.0;
std::array<double, 4> coef;
std::array<bool, 4> flags;
OptimizerDescriptor() = default;
void create();
void destroy();
static std::string className();
void set(avOptimizerType_t optimizerType, av_int64 steps, double learningRate, const double coefficients[], const bool flags[]);
void get(avOptimizerType_t *optimizerType, av_int64 *steps, double *learningRate, double coefficients[], bool flags[]);
void get_workspace_size(av_int64 *result, const TensorDescriptor &wDesc) const;
};
class DropoutDescriptor
{
public:
static constexpr av_int64 descriptor_type = 7;
DropoutDescriptor() = default;
void create();
void destroy();
static std::string className();
};
/*
* DescriptorPool
*/
template<typename T>
class DescriptorPool
{
T m_null_descriptor;
std::vector<std::unique_ptr<T>> m_pool;
std::vector<int> m_available_descriptors;
std::mutex m_pool_mutex;
public:
DescriptorPool(size_t initialSize = 10, int numRestricted = 0)
{
m_pool.reserve(initialSize + numRestricted);
m_available_descriptors.reserve(initialSize);
for (int i = 0; i < numRestricted; i++)
m_pool.push_back(nullptr); // reserve few descriptors values for default objects
}
DescriptorPool(const DescriptorPool<T> &other) = delete;
DescriptorPool(DescriptorPool<T> &&other) :
m_pool(std::move(other.m_pool)),
m_available_descriptors(std::move(other.m_available_descriptors))
{
}
DescriptorPool& operator=(const DescriptorPool<T> &other) = delete;
DescriptorPool& operator=(DescriptorPool<T> &&other)
{
std::swap(this->m_pool, other.m_pool);
std::swap(this->m_available_descriptors, other.m_available_descriptors);
return *this;
}
~DescriptorPool() = default;
/**
* \brief Checks if the passed descriptor is valid.
* The descriptor is valid if and only if its index is within the size of m_pool vector and is not in the list of available descriptors.
*/
bool isValid(int64_t desc) const noexcept
{
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : index = " << desc << '\n';
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : device type = " << get_current_device_type() << '\n';
if (get_current_device_type() != get_device_type(desc))
{
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : device type mismatch : " << get_current_device_type() << " vs "
// << get_device_type(desc) << std::endl;
return false;
}
if (T::descriptor_type != get_descriptor_type(desc))
{
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : type mismatch : " << T::descriptor_type << " vs "
// << get_descriptor_type(desc) << std::endl;
return false;
}
int index = get_descriptor_index(desc);
// std::cout << __FUNCTION__ << "() " << __LINE__ << " object index = " << index << '\n';
if (index < 0 or index > static_cast<int>(m_pool.size()))
{
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : out of bounds : " << index << " vs 0:" << m_pool.size()
// << std::endl;
return false;
}
bool asdf = std::find(m_available_descriptors.begin(), m_available_descriptors.end(), index) == m_available_descriptors.end();
if (asdf == false)
{
// std::cout << "not in available" << std::endl;
}
return asdf;
}
T& get(av_int64 desc)
{
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : " << T::className() << " object index = " << get_descriptor_index(desc)
// << '\n';
if (desc == AVOCADO_NULL_DESCRIPTOR)
return m_null_descriptor;
else
{
if (isValid(desc))
return *(m_pool.at(get_descriptor_index(desc)));
else
throw std::logic_error("invalid descriptor " + std::to_string(desc) + " for pool type '" + T::className() + "'");
}
}
template<typename ... Args>
av_int64 create(Args &&... args)
{
std::lock_guard<std::mutex> lock(m_pool_mutex);
int result;
if (m_available_descriptors.size() > 0)
{
result = m_available_descriptors.back();
m_available_descriptors.pop_back();
}
else
{
m_pool.push_back(std::make_unique<T>());
result = m_pool.size() - 1;
}
m_pool.at(result)->create(std::forward<Args>(args)...);
av_int64 tmp = create_descriptor(result, T::descriptor_type);
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : " << T::className() << " = " << tmp << ", object index = " << result
// << std::endl;
return tmp;
}
void destroy(av_int64 desc)
{
std::lock_guard<std::mutex> lock(m_pool_mutex);
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : " << T::className() << " = " << desc << std::endl;
if (not isValid(desc))
throw std::logic_error("invalid descriptor " + std::to_string(desc) + " of type '" + T::className() + "'");
int index = get_descriptor_index(desc);
// std::cout << __FUNCTION__ << "() " << __LINE__ << " object index = " << index << std::endl;
m_pool.at(index)->destroy();
m_available_descriptors.push_back(index);
}
};
template<class T>
DescriptorPool<T>& getPool()
{
static DescriptorPool<T> result;
return result;
}
template<>
DescriptorPool<ContextDescriptor>& getPool();
template<typename T, typename ... Args>
avStatus_t create(av_int64 *result, Args &&... args)
{
if (result == nullptr)
return AVOCADO_STATUS_BAD_PARAM;
try
{
result[0] = getPool<T>().create(std::forward<Args>(args)...);
} catch (std::exception &e)
{
return AVOCADO_STATUS_INTERNAL_ERROR;
}
return AVOCADO_STATUS_SUCCESS;
}
template<typename T>
avStatus_t destroy(av_int64 desc)
{
try
{
getPool<T>().destroy(desc);
} catch (std::exception &e)
{
return AVOCADO_STATUS_FREE_FAILED;
}
return AVOCADO_STATUS_SUCCESS;
}
bool isDefault(avContextDescriptor_t desc);
MemoryDescriptor& getMemory(avMemoryDescriptor_t desc);
ContextDescriptor& getContext(avContextDescriptor_t desc);
TensorDescriptor& getTensor(avTensorDescriptor_t desc);
ConvolutionDescriptor& getConvolution(avConvolutionDescriptor_t desc);
PoolingDescriptor& getPooling(avPoolingDescriptor_t desc);
OptimizerDescriptor& getOptimizer(avOptimizerDescriptor_t desc);
DropoutDescriptor& getDropout(avDropoutDescriptor_t desc);
template<typename T = void>
T* getPointer(avMemoryDescriptor_t desc)
{
try
{
return getMemory(desc).data<T>();
} catch (std::exception &e)
{
return nullptr;
}
}
template<typename T>
void setScalarValue(void *scalar, T x) noexcept
{
assert(scalar != nullptr);
reinterpret_cast<T*>(scalar)[0] = x;
}
template<typename T>
T getScalarValue(const void *scalar) noexcept
{
assert(scalar != nullptr);
return reinterpret_cast<const T*>(scalar)[0];
}
template<typename T = float>
T getAlphaValue(const void *alpha) noexcept
{
if (alpha == nullptr)
return static_cast<T>(1);
else
return reinterpret_cast<const T*>(alpha)[0];
}
template<typename T = float>
T getBetaValue(const void *beta) noexcept
{
if (beta == nullptr)
return static_cast<T>(0);
else
return reinterpret_cast<const T*>(beta)[0];
}
#if USE_CUDA
template<>
float2 getAlphaValue<float2>(const void *alpha) noexcept;
template<>
float2 getBetaValue<float2>(const void *beta) noexcept;
template<>
double2 getAlphaValue<double2>(const void *alpha) noexcept;
template<>
double2 getBetaValue<double2>(const void *beta) noexcept;
#endif
struct BroadcastedDimensions
{
int first;
int last;
};
/**
* Only the right hand side (rhs) operand can be broadcasted into the left hand side (lhs).
* The number of dimensions of the rhs tensor must be lower or equal to the lhs tensor.
* All k dimensions of the rhs must match the last k dimensions of the lhs.
*
*/
bool isBroadcastPossible(const TensorDescriptor &lhs, const TensorDescriptor &rhs) noexcept;
int volume(const BroadcastedDimensions &dims) noexcept;
BroadcastedDimensions getBroadcastDimensions(const TensorDescriptor &lhs, const TensorDescriptor &rhs) noexcept;
bool is_transpose(avGemmOperation_t op) noexcept;
bool is_logical(avBinaryOp_t op) noexcept;
bool is_logical(avUnaryOp_t op) noexcept;
bool is_logical(avReduceOp_t op) noexcept;
template<typename T, typename U>
bool same_device_type(T lhs, U rhs)
{
return get_device_type(lhs) == get_device_type(rhs);
}
template<typename T, typename U, typename ... ARGS>
bool same_device_type(T lhs, U rhs, ARGS ... args)
{
if (get_device_type(lhs) == get_device_type(rhs))
return same_device_type(lhs, args...);
else
return false;
}
} /* namespace cpu/cuda/opencl/reference */
} /* namespace backend */
} /* namespace avocado */
#endif /* AVOCADO_BACKEND_BACKEND_DESCRIPTORS_HPP_ */
| 30.510453
| 141
| 0.661394
|
AvocadoML
|
013931e763162277ef1f3cc213d891500ae16cbe
| 1,925
|
cc
|
C++
|
firestore/src/jni/object.cc
|
oliwilkinsonio/firebase-cpp-sdk
|
1a2790030e92f77ad2aaa87000a1222d12dcabfc
|
[
"Apache-2.0"
] | 193
|
2019-03-18T16:30:43.000Z
|
2022-03-30T17:39:32.000Z
|
firestore/src/jni/object.cc
|
oliwilkinsonio/firebase-cpp-sdk
|
1a2790030e92f77ad2aaa87000a1222d12dcabfc
|
[
"Apache-2.0"
] | 647
|
2019-03-18T20:50:41.000Z
|
2022-03-31T18:32:33.000Z
|
firestore/src/jni/object.cc
|
oliwilkinsonio/firebase-cpp-sdk
|
1a2790030e92f77ad2aaa87000a1222d12dcabfc
|
[
"Apache-2.0"
] | 86
|
2019-04-21T09:40:38.000Z
|
2022-03-26T20:48:37.000Z
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "firestore/src/jni/object.h"
#include "app/src/util_android.h"
#include "firestore/src/jni/class.h"
#include "firestore/src/jni/env.h"
#include "firestore/src/jni/loader.h"
namespace firebase {
namespace firestore {
namespace jni {
namespace {
Method<bool> kEquals("equals", "(Ljava/lang/Object;)Z");
Method<String> kToString("toString", "()Ljava/lang/String;");
jclass object_class = nullptr;
} // namespace
void Object::Initialize(Loader& loader) {
object_class = util::object::GetClass();
loader.LoadFromExistingClass("java/lang/Object", object_class, kEquals,
kToString);
}
Class Object::GetClass() { return Class(object_class); }
std::string Object::ToString(Env& env) const {
Local<String> java_string = env.Call(*this, kToString);
return java_string.ToString(env);
}
bool Object::Equals(Env& env, const Object& other) const {
return env.Call(*this, kEquals, other);
}
bool Object::Equals(Env& env, const Object& lhs, const Object& rhs) {
// Most likely only happens when comparing one with itself or both are null.
if (lhs.get() == rhs.get()) return true;
// If only one of them is nullptr, then they cannot equal.
if (!lhs || !rhs) return false;
return lhs.Equals(env, rhs);
}
} // namespace jni
} // namespace firestore
} // namespace firebase
| 29.615385
| 78
| 0.707532
|
oliwilkinsonio
|
01397d31fe431d899f2d2b93ba2b8846afc3137d
| 175
|
hpp
|
C++
|
FootCommander.hpp
|
amit1021/wargame-b
|
3b10fd404f7af5acfe1cfcc2c791f18afa36ab66
|
[
"MIT"
] | null | null | null |
FootCommander.hpp
|
amit1021/wargame-b
|
3b10fd404f7af5acfe1cfcc2c791f18afa36ab66
|
[
"MIT"
] | null | null | null |
FootCommander.hpp
|
amit1021/wargame-b
|
3b10fd404f7af5acfe1cfcc2c791f18afa36ab66
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "Soldier.hpp"
class FootCommander : public Soldier
{
public:
FootCommander(int player) : Soldier(150,20,player){}
~FootCommander();
};
| 15.909091
| 57
| 0.697143
|
amit1021
|
01413df5169b1339147ff85e257547c93c4f486f
| 1,975
|
cpp
|
C++
|
Demo/MdiDemo/MdiDemoView.cpp
|
yanlinlin82/libffc
|
6e067b0840f29958b97daea38bcd61099c2a473f
|
[
"MIT"
] | 9
|
2017-10-31T10:15:31.000Z
|
2021-08-02T20:40:45.000Z
|
Demo/MdiDemo/MdiDemoView.cpp
|
yanlinlin82/libffc
|
6e067b0840f29958b97daea38bcd61099c2a473f
|
[
"MIT"
] | 1
|
2019-07-21T12:13:37.000Z
|
2019-07-22T14:56:18.000Z
|
Demo/MdiDemo/MdiDemoView.cpp
|
yanlinlin82/libffc
|
6e067b0840f29958b97daea38bcd61099c2a473f
|
[
"MIT"
] | 5
|
2016-07-31T09:08:18.000Z
|
2022-03-22T14:28:16.000Z
|
// MdiDemoView.cpp : implementation of the CMdiDemoView class
//
#include "stdafx.h"
#include "MdiDemo.h"
#include "MdiDemoDoc.h"
#include "MdiDemoView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMdiDemoView
IMPLEMENT_DYNCREATE(CMdiDemoView, CView)
BEGIN_MESSAGE_MAP(CMdiDemoView, CView)
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
// CMdiDemoView construction/destruction
CMdiDemoView::CMdiDemoView()
{
// TODO: add construction code here
}
CMdiDemoView::~CMdiDemoView()
{
}
BOOL CMdiDemoView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
// CMdiDemoView drawing
void CMdiDemoView::OnDraw(CDC* pDC)
{
CMdiDemoDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: add draw code for native data here
pDC->TextOut(10, 10, _T("Hello, MDI!"));
}
// CMdiDemoView printing
BOOL CMdiDemoView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CMdiDemoView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CMdiDemoView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
// CMdiDemoView diagnostics
#ifdef _DEBUG
void CMdiDemoView::AssertValid() const
{
CView::AssertValid();
}
void CMdiDemoView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CMdiDemoDoc* CMdiDemoView::GetDocument() const // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMdiDemoDoc)));
return (CMdiDemoDoc*)m_pDocument;
}
#endif //_DEBUG
// CMdiDemoView message handlers
| 19.554455
| 78
| 0.711899
|
yanlinlin82
|
01417b6a4ebc01846c383ea9eb0e7fa8fbb47e23
| 396
|
cpp
|
C++
|
N0647-Palindromic-Substrings/solution1.cpp
|
loypt/leetcode
|
4463aa17b0fb01ec6f865ea9766ccce1ab7a690a
|
[
"CC0-1.0"
] | null | null | null |
N0647-Palindromic-Substrings/solution1.cpp
|
loypt/leetcode
|
4463aa17b0fb01ec6f865ea9766ccce1ab7a690a
|
[
"CC0-1.0"
] | null | null | null |
N0647-Palindromic-Substrings/solution1.cpp
|
loypt/leetcode
|
4463aa17b0fb01ec6f865ea9766ccce1ab7a690a
|
[
"CC0-1.0"
] | 2
|
2022-01-25T05:31:31.000Z
|
2022-02-26T07:22:23.000Z
|
class Solution {
public:
int countSubstrings(string s) {
int num = 0;
int n = s.size();
for(int i=0;i<n;i++)//遍历回文中心点
{
for(int j=0;j<=1;j++)//j=0,中心是一个点,j=1,中心是两个点
{
int l = i;
int r = i+j;
while(l>=0 && r<n && s[l--]==s[r++])num++;
}
}
return num;
}
};
| 22
| 58
| 0.356061
|
loypt
|
0149210ca73d9a9f64c0b3f739d097f86b5e5d1d
| 706
|
cpp
|
C++
|
Fibonacci/Fibonacci.cpp
|
sounishnath003/CPP-for-beginner
|
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
|
[
"MIT"
] | 4
|
2020-05-14T04:41:04.000Z
|
2021-06-13T06:42:03.000Z
|
Fibonacci/Fibonacci.cpp
|
sounishnath003/CPP-for-beginner
|
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
|
[
"MIT"
] | null | null | null |
Fibonacci/Fibonacci.cpp
|
sounishnath003/CPP-for-beginner
|
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<vector>
using namespace std ;
template<typename T>
void printVector(vector<T> n) {
for (auto &&i : n)
{
cout << i << " ";
}
cout << endl ;
}
class Fibonacci
{
private:
double series = 0;
vector<double> store;
public:
void getTheFibonacciUpto(int x) {
int a = 0, b = 1;
for (size_t i = 1; i <= x; i++)
{
store.push_back(series);
series = a + b;
a = b;
b = series;
}
printVector(store);
}
};
int main(int argc, char const *argv[])
{
Fibonacci obj ;
obj.getTheFibonacciUpto(20);
return 0;
}
| 17.219512
| 40
| 0.474504
|
sounishnath003
|
0149e15d47dac4538dd3bdd786fc568e49e3f384
| 1,214
|
cpp
|
C++
|
2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 04/05 Programs/CCType/TestCCType.cpp
|
Vito-Swift/CourseMaterials
|
f2799f004f4353b5f35226158c8fd9f71818810e
|
[
"MIT"
] | null | null | null |
2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 04/05 Programs/CCType/TestCCType.cpp
|
Vito-Swift/CourseMaterials
|
f2799f004f4353b5f35226158c8fd9f71818810e
|
[
"MIT"
] | null | null | null |
2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 04/05 Programs/CCType/TestCCType.cpp
|
Vito-Swift/CourseMaterials
|
f2799f004f4353b5f35226158c8fd9f71818810e
|
[
"MIT"
] | 2
|
2019-09-25T02:36:37.000Z
|
2020-06-05T08:47:01.000Z
|
/*
* File: TestCCType.cpp
* --------------------
* This program tests the set-based implementation of the <cctype>
* interface.
*/
#include <iostream>
#include <string>
#include "cctype.h"
#include "simpio.h"
#include "console.h"
using namespace std;
int main() {
while (true) {
string str = getLine("Enter one or more characters: ");
if (str == "") break;
cout << boolalpha;
for (int i = 0; i < str.length(); i++) {
char ch = str[i];
cout << " isdigit('" << ch << "') -> " << isdigit(ch) << endl;
cout << " isxdigit('" << ch << "') -> " << isxdigit(ch) << endl;
cout << " islower('" << ch << "') -> " << islower(ch) << endl;
cout << " isupper('" << ch << "') -> " << isupper(ch) << endl;
cout << " isspace('" << ch << "') -> " << isspace(ch) << endl;
cout << " ispunct('" << ch << "') -> " << ispunct(ch) << endl;
cout << " isalpha('" << ch << "') -> " << isalpha(ch) << endl;
cout << " isalnum('" << ch << "') -> " << isalnum(ch) << endl;
cout << " isprint('" << ch << "') -> " << isprint(ch) << endl;
cout << endl;
}
}
return 0;
}
| 33.722222
| 74
| 0.432455
|
Vito-Swift
|
014c9bc06539884aed89195baa0fc6e530aafb94
| 1,943
|
cpp
|
C++
|
Graphs/KruskalMST.cpp
|
paras2411/Algorithms
|
dcb280d382fc3ee3dbaaf5f1ec2896aae2b05825
|
[
"MIT"
] | 8
|
2020-09-15T17:54:12.000Z
|
2022-01-20T04:04:27.000Z
|
Graphs/KruskalMST.cpp
|
paras2411/Algorithms
|
dcb280d382fc3ee3dbaaf5f1ec2896aae2b05825
|
[
"MIT"
] | null | null | null |
Graphs/KruskalMST.cpp
|
paras2411/Algorithms
|
dcb280d382fc3ee3dbaaf5f1ec2896aae2b05825
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
// considering maximum no. of vertices to be 100000.
const int N = 1e5;
int parent[N];
// find the root(ancestor) of the vertex u and returns the no. of vertices in that path
int findpar(int *u){
int rank = 0;
while(*u != parent[*u]){
*u = parent[*u];
rank++;
}
return rank;
}
/*
Kruskal is the algrithm to find minimum spanning tree. It takes list
of sorted edges wrt to weight. Then iterate that list and add that
edge which do not form cycle with the added edges. For checking the
cycle we are using "Disjoint set Union" method.
Its time complexity is O(E log(E)). Space complexity is (V+E).
vector<pair<int, pair<int, int>>> edges -> list of edges with weights w {w, {u, v}}
n -> no. of vertices (V)
*/
void kruskal(vector<pair<int, pair<int, int>>> edges, int n){
// sorting that list of edges with weights
sort(edges.begin(), edges.end());
// assigning each vertices to be its parent
for(int i=0; i<n; i++){
parent[i] = i;
}
// cost -> sum of all the weights of the edges added to the MST
int cost = 0;
int edg_count = 0; // should be n-1 after iteration (Tree)
for(auto it = edges.begin(); it != edges.end() && edg_count < n-1; it++){
int weight = (*it).first;
pair<int, int> edge = (*it).second;
int u = edge.first, v = edge.second;
// find the root ancestor of the both vertex and its rank as well
int rank_u = findpar(&u);
int rank_v = findpar(&v);
// If root different then adding this edge will not form cycle.
if(u != v){
cost += weight;
edg_count += 1;
// making root ancestor of both vertex same.
if(rank_u < rank_v){
parent[u] = v;
}
else{
parent[v] = u;
}
}
}
}
| 26.256757
| 87
| 0.568194
|
paras2411
|
014dc4cf9bbe003883e6a2bc834ec2fcc6548c06
| 1,712
|
cpp
|
C++
|
src/lcpeaks/integrator_lineTools.cpp
|
DanIverson/OpenVnmrJ
|
0db324603dbd8f618a6a9526b9477a999c5a4cc3
|
[
"Apache-2.0"
] | 32
|
2016-06-17T05:04:26.000Z
|
2022-03-28T17:54:44.000Z
|
src/lcpeaks/integrator_lineTools.cpp
|
DanIverson/OpenVnmrJ
|
0db324603dbd8f618a6a9526b9477a999c5a4cc3
|
[
"Apache-2.0"
] | 128
|
2016-07-13T17:09:02.000Z
|
2022-03-28T17:53:52.000Z
|
src/lcpeaks/integrator_lineTools.cpp
|
DanIverson/OpenVnmrJ
|
0db324603dbd8f618a6a9526b9477a999c5a4cc3
|
[
"Apache-2.0"
] | 102
|
2016-01-23T15:27:16.000Z
|
2022-03-20T05:41:54.000Z
|
/*
* Varian,Inc. All Rights Reserved.
* This software contains proprietary and confidential
* information of Varian, Inc. and its contributors.
* Use, disclosure and reproduction is prohibited without
* prior consent.
*/
/* DISCLAIMER :
* ------------
*
* This is a beta version of the GALAXIE integration library.
* This code is under development and is provided for information purposes.
* The classes names and interfaces as well as the file names and
* organization is subject to changes. Moreover, this code has not been
* fully tested.
*
* For any bug report, comment or suggestion please send an email to
* gilles.orazi@varianinc.com
*
* Copyright Varian JMBS (2002)
*/
#include "common.h"
#include "integrator_lineTools.h"
#include "math.h"
#include <cassert>
//Looking for memory leaks
#ifdef __VISUAL_CPP__
#include "LeakWatcher.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#endif
TStraightLineTool::TStraightLineTool(INT_FLOAT Time1,
INT_FLOAT Value1,
INT_FLOAT Time2,
INT_FLOAT Value2)
{
assert(Time2 > Time1); // no vertical lines allowed
FTime1 = Time1 ;
FTime2 = Time2 ;
FValue1 = Value1 ;
FValue2 = Value2 ;
}
INT_FLOAT TStraightLineTool::ValueAtTime(INT_FLOAT t)
{
return FValue1 + (t - FTime1) / (FTime2 - FTime1) * (FValue2 - FValue1);
}
TExpLineTool::TExpLineTool(INT_FLOAT A,
INT_FLOAT B,
INT_FLOAT t0)
{
FA = A;
FB = B;
Ft0 = t0;
}
INT_FLOAT TExpLineTool::ValueAtTime(INT_FLOAT t)
{
INT_FLOAT result ;
try
{
result = Ft0 + FA * exp(FB * t) ;
}
catch (...)
{
result = Ft0;
}
return result ;
}
| 21.670886
| 76
| 0.674065
|
DanIverson
|
014e64b24cf4d1fe7cbcd9dd010345bd7347c848
| 1,219
|
cpp
|
C++
|
ir/src/brio/BrioMessage.cpp
|
wmarkow/arduino-sandbox
|
2c5301aeee8811ff5f15f1edb61e313ecbcb0d5e
|
[
"MIT"
] | null | null | null |
ir/src/brio/BrioMessage.cpp
|
wmarkow/arduino-sandbox
|
2c5301aeee8811ff5f15f1edb61e313ecbcb0d5e
|
[
"MIT"
] | null | null | null |
ir/src/brio/BrioMessage.cpp
|
wmarkow/arduino-sandbox
|
2c5301aeee8811ff5f15f1edb61e313ecbcb0d5e
|
[
"MIT"
] | null | null | null |
/*
* BrioMessage.cpp
*
* Created on: 09.05.2018
* Author: wmarkowski
*/
#include <Arduino.h>
#include "BrioMessage.h"
void brio_message_dump(BrioMessage* brioMessage)
{
switch (brioMessage->channel)
{
case BRIO_CHANNEL_A:
Serial.print(F("channel A, "));
break;
case BRIO_CHANNEL_B:
Serial.print(F("channel B, "));
break;
default:
Serial.print(F("channel "));
Serial.print(brioMessage->channel);
Serial.print(F(", "));
}
switch (brioMessage->command)
{
case BRIO_COMMAND_FAST_FORWARD:
Serial.println(F("cmd FFOR"));
break;
case BRIO_COMMAND_SLOW_FORWARD:
Serial.println(F("cmd SFOR"));
break;
case BRIO_COMMAND_STOP:
Serial.println(F("cmd STOP"));
break;
case BRIO_COMMAND_BACKWARD:
Serial.println(F("cmd BACK"));
break;
case BRIO_COMMAND_TOGGLE_LIGHT:
Serial.println(F("cmd T_LIGHT"));
break;
case BRIO_COMMAND_PLAY_SOUND:
Serial.println(F("cmd SOUND"));
break;
default:
Serial.print(F("cmd "));
Serial.println(brioMessage->command);
}
}
| 23.442308
| 48
| 0.5726
|
wmarkow
|
0151893c4ebd09de9dbcfadd024231e2e327b3a1
| 3,643
|
cpp
|
C++
|
src/prod/src/api/wrappers/ComProxyStorePostBackupHandler.cpp
|
gridgentoo/ServiceFabricAzure
|
c3e7a07617e852322d73e6cc9819d266146866a4
|
[
"MIT"
] | 2,542
|
2018-03-14T21:56:12.000Z
|
2019-05-06T01:18:20.000Z
|
src/prod/src/api/wrappers/ComProxyStorePostBackupHandler.cpp
|
gridgentoo/ServiceFabricAzure
|
c3e7a07617e852322d73e6cc9819d266146866a4
|
[
"MIT"
] | 994
|
2019-05-07T02:39:30.000Z
|
2022-03-31T13:23:04.000Z
|
src/prod/src/api/wrappers/ComProxyStorePostBackupHandler.cpp
|
gridgentoo/ServiceFabricAzure
|
c3e7a07617e852322d73e6cc9819d266146866a4
|
[
"MIT"
] | 300
|
2018-03-14T21:57:17.000Z
|
2019-05-06T20:07:00.000Z
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
namespace Api
{
class ComProxyStorePostBackupHandler::PostBackupAsyncOperation
: public Common::ComProxyAsyncOperation
{
DENY_COPY(PostBackupAsyncOperation);
public:
PostBackupAsyncOperation(
__in IFabricStorePostBackupHandler & comImpl,
__in FABRIC_STORE_BACKUP_INFO const & info,
__in Common::AsyncCallback const & callback,
__in Common::AsyncOperationSPtr const & parent)
: Common::ComProxyAsyncOperation(callback, parent)
, comImpl_(comImpl)
, info_(info)
, status_(false)
{
}
static Common::ErrorCode End(Common::AsyncOperationSPtr const & operation, bool & status)
{
PostBackupAsyncOperation * casted = AsyncOperation::End<PostBackupAsyncOperation>(operation);
if (casted->Error.IsSuccess())
{
status = std::move(casted->status_);
}
return casted->Error;
}
virtual ~PostBackupAsyncOperation()
{
}
protected:
HRESULT BeginComAsyncOperation(IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context)
{
HRESULT hr = comImpl_.BeginPostBackup(&info_, callback, context);
return hr;
}
HRESULT EndComAsyncOperation(IFabricAsyncOperationContext * context)
{
BOOLEAN userStatus = FALSE;
HRESULT hr = comImpl_.EndPostBackup(context, &userStatus);
status_ = SUCCEEDED(hr)
? userStatus ? true : false
: false;
return hr;
}
private:
IFabricStorePostBackupHandler & comImpl_;
FABRIC_STORE_BACKUP_INFO info_;
bool status_;
};
ComProxyStorePostBackupHandler::ComProxyStorePostBackupHandler(Common::ComPointer<IFabricStorePostBackupHandler > const & comImpl)
: ComponentRoot()
, IStorePostBackupHandler()
, comImpl_(comImpl)
{
}
ComProxyStorePostBackupHandler::~ComProxyStorePostBackupHandler()
{
}
Common::AsyncOperationSPtr ComProxyStorePostBackupHandler::BeginPostBackup(
__in FABRIC_STORE_BACKUP_INFO const & info,
__in Common::AsyncCallback const & callback,
__in Common::AsyncOperationSPtr const & parent)
{
// this should invoke the customer's COM method BeginPostBackup
// But how do we wrap the AsyncCallback and AsyncOperationSPtr into IFabricAsyncOperationCallback * and
// IFabricAsyncOperationContext **
// For this, we invoke a class derived from ComProxyAsyncOperation. This class contains two pure virtual
// methods BeginComAsyncOperation and EndComAsyncOperation which do the actual conversion.
auto operation = Common::AsyncOperation::CreateAndStart<PostBackupAsyncOperation>(
*comImpl_.GetRawPointer(),
info,
callback,
parent);
return operation;
}
Common::ErrorCode ComProxyStorePostBackupHandler::EndPostBackup(
__in Common::AsyncOperationSPtr const & operation,
__out bool & status)
{
auto error = PostBackupAsyncOperation::End(operation, status);
return error;
}
}
| 33.118182
| 134
| 0.620093
|
gridgentoo
|
0152528c23cbebd0292482028545ec0aec888717
| 1,346
|
cpp
|
C++
|
liblineside/test/signalflashtests.cpp
|
freesurfer-rge/linesidecabinet
|
8944c67fa7d340aa792e3a6e681113a4676bfbad
|
[
"MIT"
] | null | null | null |
liblineside/test/signalflashtests.cpp
|
freesurfer-rge/linesidecabinet
|
8944c67fa7d340aa792e3a6e681113a4676bfbad
|
[
"MIT"
] | 14
|
2019-11-17T14:46:25.000Z
|
2021-03-10T02:48:40.000Z
|
liblineside/test/signalflashtests.cpp
|
freesurfer-rge/linesidecabinet
|
8944c67fa7d340aa792e3a6e681113a4676bfbad
|
[
"MIT"
] | null | null | null |
#include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>
#include <sstream>
#include "lineside/signalflash.hpp"
char const* flashNames[] = { "Steady", "Flashing" };
Lineside::SignalFlash flashes[] = { Lineside::SignalFlash::Steady,
Lineside::SignalFlash::Flashing };
auto nameToFlashZip = boost::unit_test::data::make(flashNames)
^ boost::unit_test::data::make(flashes);
BOOST_AUTO_TEST_SUITE( SignalFlash )
BOOST_DATA_TEST_CASE( ToString, nameToFlashZip, name, flash )
{
BOOST_CHECK_EQUAL( name, Lineside::ToString(flash) );
}
BOOST_DATA_TEST_CASE( StreamInsertion, nameToFlashZip, name, flash )
{
std::stringstream res;
res << flash;
BOOST_CHECK_EQUAL( res.str(), name );
}
BOOST_DATA_TEST_CASE( Parse, nameToFlashZip, name, flash )
{
BOOST_CHECK_EQUAL( flash, Lineside::Parse<Lineside::SignalFlash>(name) );
}
BOOST_AUTO_TEST_CASE( BadParse )
{
const std::string badString = "SomeRandomString";
const std::string expected = "Could not parse 'SomeRandomString' to SignalFlash";
BOOST_CHECK_EXCEPTION( Lineside::Parse<Lineside::SignalFlash>(badString),
std::invalid_argument,
[=](const std::invalid_argument& ia) {
BOOST_CHECK_EQUAL( expected, ia.what() );
return expected == ia.what();
});
}
BOOST_AUTO_TEST_SUITE_END()
| 27.469388
| 83
| 0.730312
|
freesurfer-rge
|
01542c10efe6ed2d057b98d9df5f63d29a5d3781
| 1,366
|
cpp
|
C++
|
luogu/3371_2.cpp
|
shorn1/OI-ICPC-Problems
|
0c18b3297190a0e108c311c74d28351ebc70c3d1
|
[
"MIT"
] | 1
|
2020-05-07T09:26:05.000Z
|
2020-05-07T09:26:05.000Z
|
luogu/3371_2.cpp
|
shorn1/OI-ICPC-Problems
|
0c18b3297190a0e108c311c74d28351ebc70c3d1
|
[
"MIT"
] | null | null | null |
luogu/3371_2.cpp
|
shorn1/OI-ICPC-Problems
|
0c18b3297190a0e108c311c74d28351ebc70c3d1
|
[
"MIT"
] | null | null | null |
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int M = 1111111;
struct Edge
{
int tow,nxt,dat;
};
Edge e[2 * M];
int n,m,s,sume = 0,dis[2 * M],vis[2 * M],hea[2 * M];
queue <int>q;
void add(int u, int v, int w)
{
sume++;
e[sume].nxt = hea[u];
hea[u] = sume;
e[sume].tow = v;
e[sume].dat = w;
}
void init()
{
for (int i = 0; i <= 2 * m + 1; i++)
{
e[i].dat = dis[i] = 2147483647;
}
memset(vis, 0, sizeof(vis));
}
void spfa(int s)
{
dis[s] = 0;
vis[s] = 1;
q.push(s);
while(!q.empty())
{
int x = q.front();
q.pop();
vis[x] = 0;
for(int now = hea[x];now;now = e[now].nxt)
{
int y = e[now].tow,z = e[now].dat;
if(dis[y] > dis[x] + z)
{
dis[y] = dis[x]+z;
if(!vis[y])
{
vis[y] = 1;
q.push(y);
}
}
}
}
}
void pans()
{
for(int i = 1;i <= n;i++)
printf("%d ", dis[i]);
}
int main()
{
scanf("%d%d%d",&n,&m,&s);
init();
for(int i=1;i<=m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
//add(b,a,c);
}
spfa(s);
pans();
return 0;
}
| 16.658537
| 52
| 0.400439
|
shorn1
|
01568fe4e820b402aff4f45d2fd5d36b0ffd1d9b
| 1,849
|
hh
|
C++
|
include/introvirt/windows/libraries/ws2_32/types/WSABUF.hh
|
IntroVirt/IntroVirt
|
917f735f3430d0855d8b59c814bea7669251901c
|
[
"Apache-2.0"
] | 23
|
2021-02-17T16:58:52.000Z
|
2022-02-12T17:01:06.000Z
|
include/introvirt/windows/libraries/ws2_32/types/WSABUF.hh
|
IntroVirt/IntroVirt
|
917f735f3430d0855d8b59c814bea7669251901c
|
[
"Apache-2.0"
] | 1
|
2021-04-01T22:41:32.000Z
|
2021-09-24T14:14:17.000Z
|
include/introvirt/windows/libraries/ws2_32/types/WSABUF.hh
|
IntroVirt/IntroVirt
|
917f735f3430d0855d8b59c814bea7669251901c
|
[
"Apache-2.0"
] | 4
|
2021-02-17T16:53:18.000Z
|
2021-04-13T16:51:10.000Z
|
/*
* Copyright 2021 Assured Information Security, 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.
*/
#pragma once
#include <introvirt/core/memory/guest_ptr.hh>
#include <cstdint>
#include <memory>
namespace introvirt {
namespace windows {
namespace ws2_32 {
/**
* @brief
*
* @see https://docs.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-wsabuf
*/
class WSABUF {
public:
/**
* @brief Get the length of the buffer, in bytes
*/
virtual uint32_t len() const = 0;
/**
* @brief Set the length of the buffer, in bytes
*/
virtual void len(uint32_t len) = 0;
/**
* @brief Get the buffer
*/
virtual guest_ptr<const uint8_t[]> buf() const = 0;
virtual guest_ptr<uint8_t[]> buf() = 0;
/**
* @brief Set the buffer
*/
virtual void buf(const guest_ptr<uint8_t[]>& buf) = 0;
/**
* @brief Parse a WSABUF instance from the guest
*
* @param ptr The address of the instance
* @param x64 If the structure is 64-bit or not
* @return std::shared_ptr<WSABUF>
*/
static std::shared_ptr<WSABUF> make_shared(const guest_ptr<void>& ptr, bool x64);
/**
* @brief Get the size of the structure
*/
static size_t size(bool x64);
};
} // namespace ws2_32
} // namespace windows
} // namespace introvirt
| 25.328767
| 85
| 0.657112
|
IntroVirt
|
0156b739a3e01a71a774048ffe0717ba2aa7ffef
| 1,417
|
cpp
|
C++
|
others/fb/quixo4.cpp
|
st34-satoshi/quixo-cpp
|
9d71c506bea91d8a12253d527958ac0c04d0327e
|
[
"MIT"
] | null | null | null |
others/fb/quixo4.cpp
|
st34-satoshi/quixo-cpp
|
9d71c506bea91d8a12253d527958ac0c04d0327e
|
[
"MIT"
] | null | null | null |
others/fb/quixo4.cpp
|
st34-satoshi/quixo-cpp
|
9d71c506bea91d8a12253d527958ac0c04d0327e
|
[
"MIT"
] | null | null | null |
/*
Next player to play: X
Previous player: O
A board is a 16-tuple/list of 0,1,2
e.g.: (0,0,0,1, 1,2,0,0, 0,1,2,0, 2,1,2,1) means that the board is
...X
XO..
.XO.
OXOX
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
*/
#include <iostream>
#include "global4.h"
#include "state4.h"
#include <unordered_set>
void countReachable() {
std::unordered_set<ShortState> allStates;
std::unordered_set<ShortState> newStates;
std::unordered_set<ShortState> newNewStates;
State init(0);
ShortState init_ss = init.convert();
allStates.insert(init_ss);
newStates.insert(init_ss);
int i = 0;
while (not newStates.empty()) {
i++;
std::cout << i << " " << allStates.size() << " " << newStates.size() << std::endl;
newNewStates.clear();
for(auto ss : newStates) {
State s(ss);
ChildrenList cl = s.computeChildren();
for(int n=0; n<cl.nbChildren; ++n) {
ShortState ssc = cl.children[n].convert();
if (cl.children[n].checkLines() != 0) {
allStates.insert(ssc);
} else {
if (allStates.find(ssc) == allStates.end()) {
newNewStates.insert(ssc);
allStates.insert(ssc);
}
}
}
}
newStates = newNewStates;
}
std::cout << "There are " << allStates.size() << " reachable states" << std::endl;
return;
}
int main() {
countReachable();
return 0;
}
| 20.838235
| 86
| 0.573042
|
st34-satoshi
|
01594279291cd64d232ef617f493cb70ac094f93
| 7,036
|
cpp
|
C++
|
src/ZigBeeCommandLineProcessor.cpp
|
Suicyc1e/Sequoia
|
7a31bde385673e5522373eb7a2ee33c4042c3b8d
|
[
"MIT"
] | null | null | null |
src/ZigBeeCommandLineProcessor.cpp
|
Suicyc1e/Sequoia
|
7a31bde385673e5522373eb7a2ee33c4042c3b8d
|
[
"MIT"
] | null | null | null |
src/ZigBeeCommandLineProcessor.cpp
|
Suicyc1e/Sequoia
|
7a31bde385673e5522373eb7a2ee33c4042c3b8d
|
[
"MIT"
] | null | null | null |
#include <ZigBeeCommandLineProcessor.h>
#include <GlobalPresets.h>
int StringSplit(String sInput, char cDelim, String sParams[], int iMaxParams)
{
int iParamCount = 0;
int iPosDelim, iPosStart = 0;
do {
// Searching the delimiter using indexOf()
iPosDelim = sInput.indexOf(cDelim,iPosStart);
if (iPosDelim > (iPosStart+1)) {
// Adding a new parameter using substring()
sParams[iParamCount] = sInput.substring(iPosStart,iPosDelim-1);
iParamCount++;
// Checking the number of parameters
if (iParamCount >= iMaxParams) {
return (iParamCount);
}
iPosStart = iPosDelim + 1;
}
} while (iPosDelim >= 0);
if (iParamCount < iMaxParams) {
// Adding the last parameter as the end of the line
sParams[iParamCount] = sInput.substring(iPosStart);
iParamCount++;
}
return (iParamCount);
}
void ZigBeeCommandLineProcessor::ProcessIncomingData(String esp32Data)
{
Serial.println("ZigBee Message Data: " + esp32Data);
if (esp32Data.startsWith(_attributeMessagePrefix))
{
Serial.println("Message is ATTRIBUTE_CHANGE");
int attributeID = 0;
int attributeValue = 0;
String splitControl = _attributeMessagePrefix + "%d" + " " + "%d";
int n = sscanf(esp32Data.c_str(), splitControl.c_str(), &attributeID, &attributeValue);
if (n != 2)
{
Serial.println("WARNING! Sscanf didn't parse the message correctly!");
}
Serial.printf(" Attribute ID && Data: %d && %d \n", attributeID, attributeValue);
ZigBeeMessage_AttributeChanged message = ZigBeeMessage_AttributeChanged(attributeID, attributeValue, esp32Data);
_attributeChangedCallback(message);
}
else if (esp32Data.startsWith(_nwkSuccessMessagePrefix))
{
Serial.println("Message is NWK_SUCCESS");
int finalState = 0;
String splitControl = _nwkSuccessMessagePrefix + "%d";
int n = sscanf(esp32Data.c_str(), splitControl.c_str(), &finalState);
if (n != 1)
{
Serial.println("WARNING! Sscanf didn't parse the message correctly!");
}
Serial.printf(" Final State: %d \n", finalState);
ZigBeeMessage_NwkSuccess message = ZigBeeMessage_NwkSuccess(finalState, esp32Data);
_nwkStatusSuccededCallback(message);
}
else if (esp32Data.startsWith(_nwkFailedMessagePrefix))
{
Serial.println("Message is NWK_FAILED");
int finalState = 0;
String splitControl = _nwkFailedMessagePrefix + "%d";
int n = sscanf(esp32Data.c_str(), splitControl.c_str(), &finalState);
if (n != 1)
{
Serial.println("WARNING! Sscanf didn't parse the message correctly!");
}
Serial.printf(" Final State: %d \n", finalState);
ZigBeeMessage_NwkFailed message = ZigBeeMessage_NwkFailed(finalState, esp32Data);
_nwkStatusFailedCallback(message);
}
else
{
Serial.println("Message is UNKNOWN");
}
}
void ZigBeeCommandLineProcessor::ZigbeeCommandsReader(void *parameter)
{
ZigBeeCommandLineProcessor *processor = (ZigBeeCommandLineProcessor*) parameter;
while (1)
{
TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE;
TIMERG0.wdt_feed=1;
TIMERG0.wdt_wprotect=0;
if (ZigBeePort.available())
{
String esp32Data = ZigBeePort.readStringUntil('\n');
processor->ProcessIncomingData(esp32Data);
}
// unsigned long thedelay;
// thedelay = micros() + 100;
// while (micros() < thedelay)
// {
// }
//Too short delay for music to play.
vTaskDelay(UART_COMMAND_LINE_TASK_DELAY_MS/portTICK_PERIOD_MS);
}
}
ZigBeeCommandLineProcessor::ZigBeeCommandLineProcessor( AttributeChangedCallback attrChangedCallback,
NwkStatusFailedCallback nwkFailedCallback,
NwkStatusSuccededCallback nwkOkCallback)
{
_attributeChangedCallback = attrChangedCallback;
_nwkStatusFailedCallback = nwkFailedCallback;
_nwkStatusSuccededCallback = nwkOkCallback;
//ExecuteStartUpProcedures();
}
void ZigBeeCommandLineProcessor::ExecuteStartUpProcedures()
{
//Init UART, ask ZigBee if it's ready, etc...
//ZigBee Console
ZigBeePort.begin(115200);
//DBG Message. Delete later.
ZigBeePort.println("ZigBee TEST UART Is Initialized.");
Serial.println("Starting Thread.");
xTaskCreate(
ZigbeeCommandsReader, /* Task function. */
"zigbeeCommandsReader", /* String with name of task. */
10000, /* Stack size in bytes. */
this, /* Parameter passed as input of the task */
1, /* Priority of the task. */
&ZigBeeCommandsReaderTask); /* Task handle. */
}
void ZigBeeCommandLineProcessor::CommandsTest()
{
ZigBeePort.println(ZigBeeCommand_TryToConnect(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SoundSaving(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetSoundDetect(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetAutoAnswer(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_PhotoSaving(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_MicrophoneTriggered(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_ButtonTriggered(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_BoxVibrationAlarmTriggered(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_AdditionalSensorMapperState(19).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareDeviceEnable(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareFunctionalMode(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareWaterValvesMapper(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareSoilHumidityMapper(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareLowerPlantMapper(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareMiddlePlantMapper(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareUpperPlantMapper(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareNoWaterAlarm(1).GetCommand());
}
HardwareSerial ZigBeeCommandLineProcessor::ZigBeePort = Serial2;
TaskHandle_t ZigBeeCommandLineProcessor::ZigBeeCommandsReaderTask = NULL;
| 38.032432
| 124
| 0.622513
|
Suicyc1e
|
015b2fc1bb7a3b4abc8ca03c4369020f5e67bf05
| 1,428
|
cc
|
C++
|
src/auth.cc
|
thejk/stuff
|
67362896a37742e880025b9c85c4fe49d690ba02
|
[
"BSD-3-Clause"
] | null | null | null |
src/auth.cc
|
thejk/stuff
|
67362896a37742e880025b9c85c4fe49d690ba02
|
[
"BSD-3-Clause"
] | null | null | null |
src/auth.cc
|
thejk/stuff
|
67362896a37742e880025b9c85c4fe49d690ba02
|
[
"BSD-3-Clause"
] | null | null | null |
#include "common.hh"
#include "auth.hh"
#include "base64.hh"
#include "cgi.hh"
#include "http.hh"
#include "strutils.hh"
namespace stuff {
bool Auth::auth(CGI* cgi, const std::string& realm, const std::string& passwd,
std::string* user) {
auto auth = cgi->http_auth();
auto pos = auth.find(' ');
if (pos != std::string::npos) {
if (ascii_tolower(auth.substr(0, pos)) == "basic") {
std::string tmp;
if (Base64::decode(auth.substr(pos + 1), &tmp)) {
pos = tmp.find(':');
if (pos != std::string::npos) {
if (tmp.substr(pos + 1) == passwd) {
if (user) user->assign(tmp.substr(0, pos));
return true;
}
}
}
}
}
std::map<std::string, std::string> headers;
std::string tmp = realm;
for (auto it = tmp.begin(); it != tmp.end(); ++it) {
if (!((*it >= 'a' && *it <= 'z') ||
(*it >= 'A' && *it <= 'Z') ||
(*it >= '0' && *it <= '9') ||
*it == '-' || *it == '_' || *it == '.' || *it == ' ')) {
*it = '.';
}
}
headers.insert(std::make_pair("WWW-Authenticate",
"Basic realm=\"" + tmp + "\""));
Http::response(401, headers, "Authentication needed");
return false;
}
} // namespace stuff
| 30.382979
| 78
| 0.429272
|
thejk
|
015d23c359ee83b5f55b673013ed6cbdceae9f3f
| 3,042
|
hpp
|
C++
|
IO/src/jpg/include/jpg.hpp
|
tlalexander/stitchEm
|
cdff821ad2c500703e6cb237ec61139fce7bf11c
|
[
"MIT"
] | 182
|
2019-04-19T12:38:30.000Z
|
2022-03-20T16:48:20.000Z
|
IO/src/jpg/include/jpg.hpp
|
tlalexander/stitchEm
|
cdff821ad2c500703e6cb237ec61139fce7bf11c
|
[
"MIT"
] | 107
|
2019-04-23T10:49:35.000Z
|
2022-03-02T18:12:28.000Z
|
IO/src/jpg/include/jpg.hpp
|
tlalexander/stitchEm
|
cdff821ad2c500703e6cb237ec61139fce7bf11c
|
[
"MIT"
] | 59
|
2019-06-04T11:27:25.000Z
|
2022-03-17T23:49:49.000Z
|
// Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#pragma once
#include "io.hpp"
#include "libvideostitch/logging.hpp"
#include <fstream>
#include <ostream>
#include <vector>
#include <setjmp.h>
#include <jpeglib.h>
namespace VideoStitch {
namespace Input {
void my_output_message(j_common_ptr cinfo) {
char buffer[JMSG_LENGTH_MAX];
/* Create the message */
(*cinfo->err->format_message)(cinfo, buffer);
/* Send it to stderr, adding a newline */
Logger::get(Logger::Error) << buffer << std::endl;
}
class JPGReader {
public:
JPGReader(const char* filename, VideoStitch::ThreadSafeOstream* err = NULL) : hf(NULL), width(0), height(0) {
hf = VideoStitch::Io::openFile(filename, "rb");
if (!hf) {
if (err) {
*err << "Cannot open file '" << filename << "' for reading." << std::endl;
}
} else {
readHeader();
}
}
~JPGReader() {
if (hf) {
if (cinfo.output_scanline) {
// otherwise libjpeg crashes - see VSA-1326
jpeg_finish_decompress(&cinfo);
}
jpeg_destroy_decompress(&cinfo);
fclose(hf);
}
}
unsigned getWidth() const { return width; }
unsigned getHeight() const { return height; }
bool ok() const { return hf != NULL && width != 0 && height != 0; }
/**
* Fill in the given buffer with the next row (RGBRGBRGB).
* @data must be large enough to hold one row.
*/
bool getNextRow(unsigned char* data) {
JSAMPROW rowArray[1];
rowArray[0] = data;
return (cinfo.output_scanline < cinfo.output_height) && jpeg_read_scanlines(&cinfo, rowArray, 1);
}
private:
struct my_error_mgr {
struct jpeg_error_mgr pub; /* "public" fields */
jmp_buf setjmp_buffer; /* for return to caller */
};
typedef struct my_error_mgr* my_error_ptr;
/*
* Here's the routine that will replace the standard error_exit method:
*/
static void my_error_exit(j_common_ptr cinfo) {
/* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
my_error_ptr myerr = (my_error_ptr)cinfo->err;
/* Always display the message. */
/* We could postpone this until after returning, if we chose. */
(*cinfo->err->output_message)(cinfo);
/* Return control to the setjmp point */
longjmp(myerr->setjmp_buffer, 1);
}
void readHeader() {
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
jerr.pub.output_message = my_output_message;
/* Establish the setjmp return context for my_error_exit to use. */
if (setjmp(jerr.setjmp_buffer)) {
return;
}
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, hf);
jpeg_read_header(&cinfo, TRUE);
width = cinfo.image_width;
height = cinfo.image_height;
jpeg_start_decompress(&cinfo);
// FIXME: make sure that we have RGB data
}
private:
FILE* hf;
unsigned width;
unsigned height;
struct jpeg_decompress_struct cinfo;
struct my_error_mgr jerr;
};
} // namespace Input
} // namespace VideoStitch
| 25.35
| 111
| 0.657462
|
tlalexander
|
015de0eea16ec62ebb203ca7b900d77686faa7cf
| 2,037
|
cc
|
C++
|
patchpanel/mcastd/main.cc
|
strassek/chromiumos-platform2
|
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
|
[
"BSD-3-Clause"
] | 4
|
2020-07-24T06:54:16.000Z
|
2021-06-16T17:13:53.000Z
|
patchpanel/mcastd/main.cc
|
strassek/chromiumos-platform2
|
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
|
[
"BSD-3-Clause"
] | 1
|
2021-04-02T17:35:07.000Z
|
2021-04-02T17:35:07.000Z
|
patchpanel/mcastd/main.cc
|
strassek/chromiumos-platform2
|
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
|
[
"BSD-3-Clause"
] | 1
|
2020-11-04T22:31:45.000Z
|
2020-11-04T22:31:45.000Z
|
// Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <base/bind.h>
#include <base/command_line.h>
#include <base/files/scoped_file.h>
#include <base/macros.h>
#include <brillo/daemons/daemon.h>
#include "patchpanel/multicast_forwarder.h"
// Stand-alone daemon to proxy mDNS and SSDP packets between a pair of
// interfaces. Usage: mcastd $physical_ifname $guest_ifname
int main(int argc, char* argv[]) {
base::CommandLine::Init(argc, argv);
base::CommandLine* cl = base::CommandLine::ForCurrentProcess();
base::CommandLine::StringVector args = cl->GetArgs();
if (args.size() < 2) {
LOG(ERROR) << "Usage: " << cl->GetProgram().BaseName().value()
<< " [physical interface name] [guest interface name]";
return EXIT_FAILURE;
}
brillo::Daemon daemon;
auto mdns_fwd = std::make_unique<patchpanel::MulticastForwarder>(
args[0], patchpanel::kMdnsMcastAddress, patchpanel::kMdnsMcastAddress6,
patchpanel::kMdnsPort);
auto ssdp_fwd = std::make_unique<patchpanel::MulticastForwarder>(
args[0], patchpanel::kSsdpMcastAddress, patchpanel::kSsdpMcastAddress6,
patchpanel::kSsdpPort);
// Crostini depends on another daemon (LXD) creating the guest bridge
// interface. This can take a few seconds, so retry if necessary.
bool added_mdns = false, added_ssdp = false;
for (int i = 0; i < 10; i++) {
added_mdns = added_mdns || mdns_fwd->AddGuest(args[1]);
added_ssdp = added_ssdp || ssdp_fwd->AddGuest(args[1]);
if (added_mdns && added_ssdp)
break;
usleep(1000 * 1000 /* 1 second */);
}
if (!added_mdns)
LOG(ERROR) << "mDNS forwarder could not be started on " << args[0]
<< " and " << args[1];
if (!added_ssdp)
LOG(ERROR) << "SSDP forwarder could not be started on " << args[0]
<< " and " << args[1];
if (!added_mdns || !added_ssdp)
return EXIT_FAILURE;
return daemon.Run();
}
| 36.375
| 77
| 0.67403
|
strassek
|
015ea70b359981eae5d6213f851d444c511c4bf3
| 2,546
|
hpp
|
C++
|
cmdstan/stan/src/stan/lang/ast/fun/var_decl_dims_vis_def.hpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | 1
|
2019-07-05T01:40:40.000Z
|
2019-07-05T01:40:40.000Z
|
cmdstan/stan/src/stan/lang/ast/fun/var_decl_dims_vis_def.hpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/src/stan/lang/ast/fun/var_decl_dims_vis_def.hpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | 1
|
2018-08-28T12:09:08.000Z
|
2018-08-28T12:09:08.000Z
|
#ifndef STAN_LANG_AST_FUN_VAR_DECL_DIMS_VIS_DEF_HPP
#define STAN_LANG_AST_FUN_VAR_DECL_DIMS_VIS_DEF_HPP
#include <stan/lang/ast.hpp>
#include <vector>
namespace stan {
namespace lang {
var_decl_dims_vis::var_decl_dims_vis() { }
std::vector<expression> var_decl_dims_vis::operator()(const nil& /* x */)
const {
return std::vector<expression>(); // should not be called
}
std::vector<expression> var_decl_dims_vis::operator()(const int_var_decl& x)
const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const double_var_decl& x)
const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const vector_var_decl& x)
const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const row_vector_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const matrix_var_decl& x)
const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const unit_vector_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const simplex_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const ordered_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const positive_ordered_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const cholesky_factor_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const cholesky_corr_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const cov_matrix_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const corr_matrix_var_decl& x) const {
return x.dims_;
}
}
}
#endif
| 28.931818
| 80
| 0.552239
|
yizhang-cae
|
015f284d8abe647c16ca54578d7e48d01427cd6e
| 3,698
|
cpp
|
C++
|
src/chartwork/ColorPalette.cpp
|
nazhor/chartwork
|
20cb8df257bec39153ea408305640274c9e09d4c
|
[
"MIT"
] | 20
|
2018-08-29T07:33:21.000Z
|
2022-03-12T05:05:54.000Z
|
src/chartwork/ColorPalette.cpp
|
nazhor/chartwork
|
20cb8df257bec39153ea408305640274c9e09d4c
|
[
"MIT"
] | 1
|
2020-10-27T15:04:46.000Z
|
2020-10-27T15:04:46.000Z
|
src/chartwork/ColorPalette.cpp
|
nazhor/chartwork
|
20cb8df257bec39153ea408305640274c9e09d4c
|
[
"MIT"
] | 7
|
2015-07-09T20:38:28.000Z
|
2021-09-27T06:38:11.000Z
|
#include <chartwork/ColorPalette.h>
#include <chartwork/Design.h>
namespace chartwork
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// ColorPalette
//
////////////////////////////////////////////////////////////////////////////////////////////////////
ColorPalette::ColorPalette()
: m_colors(std::shared_ptr<QList<QColor>>(new QList<QColor>(
{
design::blue,
design::orange,
design::green,
design::purple,
design::red,
design::yellow,
design::brown,
design::gray
})))
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color0() const
{
return (*m_colors)[0];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor0(const QColor &color0)
{
(*m_colors)[0] = color0;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color1() const
{
return (*m_colors)[1];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor1(const QColor &color1)
{
(*m_colors)[1] = color1;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color2() const
{
return (*m_colors)[2];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor2(const QColor &color2)
{
(*m_colors)[2] = color2;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color3() const
{
return (*m_colors)[3];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor3(const QColor &color3)
{
(*m_colors)[3] = color3;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color4() const
{
return (*m_colors)[4];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor4(const QColor &color4)
{
(*m_colors)[4] = color4;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color5() const
{
return (*m_colors)[5];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor5(const QColor &color5)
{
(*m_colors)[5] = color5;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color6() const
{
return (*m_colors)[6];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor6(const QColor &color6)
{
(*m_colors)[6] = color6;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color7() const
{
return (*m_colors)[7];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor7(const QColor &color7)
{
(*m_colors)[7] = color7;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
| 24.328947
| 100
| 0.330719
|
nazhor
|
015f8fbd13144338c56420d36b5dfb1cc578986c
| 1,827
|
hpp
|
C++
|
header/deps/filehelp.hpp
|
jonathanmarp/tfsound
|
18942c35f1d3f4d335670b7d381f8a75b6a7e465
|
[
"MIT"
] | 2
|
2021-06-05T10:15:53.000Z
|
2021-06-06T09:51:19.000Z
|
header/deps/filehelp.hpp
|
jonathanmarp/tfsound
|
18942c35f1d3f4d335670b7d381f8a75b6a7e465
|
[
"MIT"
] | null | null | null |
header/deps/filehelp.hpp
|
jonathanmarp/tfsound
|
18942c35f1d3f4d335670b7d381f8a75b6a7e465
|
[
"MIT"
] | 1
|
2021-06-08T05:56:35.000Z
|
2021-06-08T05:56:35.000Z
|
// MIT License
// Copyright (c) 2021 laferenorg
// 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.
#ifndef _FILESHELP_HPP
#define _FILESHELP_HPP
/* Library C++ */
#include <ios>
#include <fstream>
// class FILESHELP
class FILESHELP {
private:
// variable settings in here
std::string namefile; // variable namefile
public:
// function constructor for fill variable FILESHELP
FILESHELP(const char* nameFile);
public:
// function open and close file
// function for open file
void F_openFile();
// function for close file
void F_closeFile();
public:
// return refrencf fstream variable
std::fstream& getVarFile();
public:
// function for check file its exist
bool itsExist();
public:
// function for get all string file
std::string getFile();
};
#endif // _FILESHELP_HPP
| 33.218182
| 81
| 0.746579
|
jonathanmarp
|
01635e6161a725aca5e9748a3bdc8945400a2a2f
| 6,958
|
cxx
|
C++
|
3rd/fltk/src/win32/list_fonts.cxx
|
MarioHenze/cgv
|
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
|
[
"BSD-3-Clause"
] | 11
|
2017-09-30T12:21:55.000Z
|
2021-04-29T21:31:57.000Z
|
3rd/fltk/src/win32/list_fonts.cxx
|
MarioHenze/cgv
|
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
|
[
"BSD-3-Clause"
] | 2
|
2017-07-11T11:20:08.000Z
|
2018-03-27T12:09:02.000Z
|
3rd/fltk/src/win32/list_fonts.cxx
|
MarioHenze/cgv
|
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
|
[
"BSD-3-Clause"
] | 24
|
2018-03-27T11:46:16.000Z
|
2021-05-01T20:28:34.000Z
|
//
// "$Id: list_fonts.cxx 5958 2007-10-17 20:21:38Z spitzak $"
//
// _WIN32 font utilities for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2006 by Bill Spitzak and others.
//
// 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; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA.
//
// Please report all bugs and problems to "fltk-bugs@fltk.org".
//
#include <fltk/events.h>
#include <fltk/utf.h>
#include <fltk/x.h>
#include <ctype.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#include <config.h>
using namespace fltk;
extern int has_unicode();
int Font::encodings(const char**& arrayp) {
// CET - FIXME - What about this encoding stuff?
// WAS: we need some way to find out what charsets are supported
// and turn these into ISO encoding names, and return this list.
// This is a poor simulation:
static const char* simulation[] = {"iso10646-1", 0};
arrayp = simulation;
return 1;
}
////////////////////////////////////////////////////////////////
// List sizes:
static int nbSize;
//static int cyPerInch;
#define MAX_SIZES 16
static int sizes[MAX_SIZES];
static int CALLBACK EnumSizeCb(CONST LOGFONTW* lpelf,
CONST TEXTMETRICW* lpntm,
DWORD fontType,
LPARAM p)
{
if ((fontType & RASTER_FONTTYPE) == 0) {
// Scalable font
sizes[0] = 0;
nbSize = 1;
return 0;
}
int add = lpntm->tmHeight - lpntm->tmInternalLeading;
//add = MulDiv(add, 72, cyPerInch); // seems to be correct before this
int start = 0;
while ((start < nbSize) && (sizes[start] < add)) start++;
if ((start < nbSize) && (sizes[start] == add)) return (1);
for (int i=nbSize; i>start; i--) sizes[i] = sizes[i - 1];
sizes[start] = add;
nbSize++;
// Stop enum if buffer overflow
return (nbSize < MAX_SIZES);
}
int Font::sizes(int*& sizep) {
nbSize = 0;
HDC dc = getDC();
//cyPerInch = GetDeviceCaps(dc, LOGPIXELSY);
//if (cyPerInch < 1) cyPerInch = 1;
if (has_unicode()) {
wchar_t ucs[1024];
utf8towc(name_, strlen(name_), ucs, 1024);
#if defined(__BORLANDC__) || defined(__DMC__)
EnumFontFamiliesW(dc, ucs, (FONTENUMPROCA)EnumSizeCb, 0);
#else
EnumFontFamiliesW(dc, ucs, EnumSizeCb, 0);
#endif
} else {
EnumFontFamiliesA(dc, name_, (FONTENUMPROCA)EnumSizeCb, 0);
}
sizep = ::sizes;
return nbSize;
}
////////////////////////////////////////////////////////////////
// list fonts:
extern "C" {
static int sort_function(const void *aa, const void *bb) {
fltk::Font* a = *(fltk::Font**)aa;
fltk::Font* b = *(fltk::Font**)bb;
int ret = stricmp(a->name_, b->name_); if (ret) return ret;
return a->attributes_ - b->attributes_;
}}
extern Font* fl_make_font(const char* name, int attrib);
static Font** font_array = 0;
static int num_fonts = 0;
static int array_size = 0;
static int CALLBACK enumcbW(CONST LOGFONTW* lplf,
CONST TEXTMETRICW* lpntm,
DWORD fontType,
LPARAM p)
{
// we need to do something about different encodings of the same font
// in order to match X! I can't tell if each different encoding is
// returned sepeartely or not. This is what fltk 1.0 did:
if (lplf->lfCharSet != ANSI_CHARSET) return 1;
const wchar_t *name = lplf->lfFaceName;
//const char *name = (const char*)(((ENUMLOGFONT *)lplf)->elfFullName);
char buffer[1024];
utf8fromwc(buffer, 1024, name, wcslen(name));
// ignore mystery garbage font names:
if (buffer[0] == '@') return 1;
if (num_fonts >= array_size) {
array_size = array_size ? 2*array_size : 128;
font_array = (Font**)realloc(font_array, array_size*sizeof(Font*));
}
int attrib = 0;
// if (lplf->lfWeight > 400 || strstr(name, " Bold") == name+strlen(name)-5)
// attrib = BOLD;
font_array[num_fonts++] = fl_make_font(buffer, attrib);
return 1;
}
static int CALLBACK enumcbA(CONST LOGFONT* lplf,
CONST TEXTMETRIC* lpntm,
DWORD fontType,
LPARAM p)
{
// we need to do something about different encodings of the same font
// in order to match X! I can't tell if each different encoding is
// returned sepeartely or not. This is what fltk 1.0 did:
//if (lplf->lfCharSet != ANSI_CHARSET) return 1;
const char *name = lplf->lfFaceName;
if (num_fonts >= array_size) {
array_size = array_size ? 2*array_size : 128;
font_array = (Font**)realloc(font_array, array_size*sizeof(Font*));
}
int attrib = 0;
font_array[num_fonts++] = fl_make_font(name, attrib);
return 1;
}
int fltk::list_fonts(Font**& arrayp) {
if (font_array) {arrayp = font_array; return num_fonts;}
HDC dc = getDC();
if (has_unicode()) {
LOGFONTW lf;
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = DEFAULT_CHARSET;
EnumFontFamiliesExW(dc, &lf, (FONTENUMPROCW)enumcbW, 0, 0);
} else {
LOGFONT lf;
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = DEFAULT_CHARSET;
EnumFontFamiliesExA(dc, &lf, (FONTENUMPROCA)enumcbA, 0, 0);
}
ReleaseDC(0, dc);
qsort(font_array, num_fonts, sizeof(*font_array), sort_function);
arrayp = font_array;
return num_fonts;
}
////////////////////////////////////////////////////////////////
// This function apparently is needed to translate some font names
// stored in setup files to the actual name of a font. Currently
// font(name) calls this.
#if defined(WIN32) && !defined(__CYGWIN__)
static const char* GetFontSubstitutes(const char* name,int& len)
{
static char subst_name[1024]; //used BUFLEN from bool fltk_theme()
if ( strstr(name,"MS Shell Dlg") || strstr(name,"Helv") ||
strstr(name,"Tms Rmn")) {
DWORD type = REG_SZ;
LONG err;
HKEY key;
char truncname[1024];
strncpy(truncname, name, len);
truncname[len] = 0;
err = RegOpenKey(
HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes",
&key );
if (err == ERROR_SUCCESS) {
DWORD L=1024;
err = RegQueryValueEx( key, truncname, 0L, &type, (BYTE*)
subst_name, &L);
RegCloseKey(key);
if ( err == ERROR_SUCCESS ) {
len = L;
return subst_name;
}
}
}
return name;
}
#endif
//
// End of "$Id: list_fonts.cxx 5958 2007-10-17 20:21:38Z spitzak $"
//
| 29.991379
| 79
| 0.632078
|
MarioHenze
|
016871b7df9e584799df839cda630bd6279531cd
| 636
|
hpp
|
C++
|
Plutonium/Include/pu/overlay/Toast.hpp
|
Falki14/Plutonium
|
e39894f87b57695d4288052979e23d4115932697
|
[
"MIT"
] | null | null | null |
Plutonium/Include/pu/overlay/Toast.hpp
|
Falki14/Plutonium
|
e39894f87b57695d4288052979e23d4115932697
|
[
"MIT"
] | null | null | null |
Plutonium/Include/pu/overlay/Toast.hpp
|
Falki14/Plutonium
|
e39894f87b57695d4288052979e23d4115932697
|
[
"MIT"
] | null | null | null |
/*
Plutonium library
@file Overlay.hpp
@brief TODO...
@author XorTroll
@copyright Plutonium project - an easy-to-use UI framework for Nintendo Switch homebrew
*/
#pragma once
#include <pu/overlay/Overlay.hpp>
namespace pu::overlay
{
class Toast : public Overlay
{
public:
Toast(std::string Text, u32 FontSize, draw::Color TextColor, draw::Color BaseColor);
void SetText(std::string Text);
void OnPreRender(render::Renderer *Drawer);
void OnPostRender(render::Renderer *Drawer);
private:
pu::element::TextBlock *text;
};
}
| 21.931034
| 96
| 0.624214
|
Falki14
|
6c75aa25ebca362bf52e57a3e7660b4f89500ead
| 5,062
|
cpp
|
C++
|
src-plugins/reformat/resampleProcess.cpp
|
nebatmusic/medInria-public
|
09000bd2f129692e42314a8eb1313d238603252e
|
[
"BSD-1-Clause"
] | 1
|
2020-11-16T13:55:45.000Z
|
2020-11-16T13:55:45.000Z
|
src-plugins/reformat/resampleProcess.cpp
|
nebatmusic/medInria-public
|
09000bd2f129692e42314a8eb1313d238603252e
|
[
"BSD-1-Clause"
] | null | null | null |
src-plugins/reformat/resampleProcess.cpp
|
nebatmusic/medInria-public
|
09000bd2f129692e42314a8eb1313d238603252e
|
[
"BSD-1-Clause"
] | null | null | null |
#include "resampleProcess.h"
#include <dtkCore/dtkAbstractProcessFactory.h>
#include <medAbstractDataFactory.h>
#include <medAbstractProcess.h>
#include <medMetaDataKeys.h>
#include <medUtilitiesITK.h>
#include <itkResampleImageFilter.h>
#include <itkBSplineInterpolateImageFunction.h>
// /////////////////////////////////////////////////////////////////
// resampleProcessPrivate
// /////////////////////////////////////////////////////////////////
class resampleProcessPrivate
{
public:
resampleProcess *parent;
resampleProcessPrivate(resampleProcess *p)
{
parent = p;
}
medAbstractData* input;
medAbstractData* output;
int interpolator;
int dimX,dimY,dimZ;
double spacingX,spacingY,spacingZ;
};
// /////////////////////////////////////////////////////////////////
// resampleProcess
// /////////////////////////////////////////////////////////////////
resampleProcess::resampleProcess(void) : d(new resampleProcessPrivate(this))
{
d->dimX=0;
d->dimY=0;
d->dimZ=0;
d->spacingX = 0.0;
d->spacingY = 0.0;
d->spacingZ = 0.0;
}
resampleProcess::~resampleProcess(void)
{
delete d;
d = NULL;
}
bool resampleProcess::registered(void)
{
return dtkAbstractProcessFactory::instance()->registerProcessType("resampleProcess", createResampleProcess);
}
QString resampleProcess::description(void) const
{
return "resampleProcess";
}
void resampleProcess::setInput ( medAbstractData *data)
{
if ( !data )
return;
d->input = data;
}
void resampleProcess::setInput ( medAbstractData *data , int channel)
{
setInput(data);
}
void resampleProcess::setParameter ( double data, int channel)
{
switch (channel)
{
case 0:
d->dimX = (int)data;
break;
case 1:
d->dimY = (int)data;
break;
case 2:
d->dimZ = (int)data;
break;
case 3:
d->spacingX = data;
break;
case 4:
d->spacingY = data;
break;
case 5:
d->spacingZ = data;
break;
}
}
int resampleProcess::update ( void )
{
int result = DTK_FAILURE;
if (!d->input)
{
qDebug() << "in update method : d->input is NULL";
}
else
{
result = DISPATCH_ON_3D_PIXEL_TYPE(&resampleProcess::resample, this, d->input);
if (result == medAbstractProcess::PIXEL_TYPE)
{
result = DISPATCH_ON_4D_PIXEL_TYPE(&resampleProcess::resample, this, d->input);
}
}
return result;
}
template <class ImageType>
int resampleProcess::resample(medAbstractData* inputData)
{
typename ImageType::Pointer inputImage = static_cast<ImageType*>(inputData->data());
typedef typename itk::ResampleImageFilter<ImageType, ImageType,double> ResampleFilterType;
typename ResampleFilterType::Pointer resampleFilter = ResampleFilterType::New();
//// Fetch original image size.
const typename ImageType::RegionType& inputRegion = inputImage->GetLargestPossibleRegion();
const typename ImageType::SizeType& vnInputSize = inputRegion.GetSize();
unsigned int nOldX = vnInputSize[0];
unsigned int nOldY = vnInputSize[1];
unsigned int nOldZ = vnInputSize[2];
//// Fetch original image spacing.
const typename ImageType::SpacingType& vfInputSpacing = inputImage->GetSpacing();
double vfOutputSpacing[3]={d->spacingX,d->spacingY,d->spacingZ};
if (d->dimX || d->dimY || d->dimZ)
{
vfOutputSpacing[0] = vfInputSpacing[0] * (double) nOldX / (double) d->dimX;
vfOutputSpacing[1] = vfInputSpacing[1] * (double) nOldY / (double) d->dimY;
vfOutputSpacing[2] = vfInputSpacing[2] * (double) nOldZ / (double) d->dimZ;
}
else
{
d->dimX = floor((vfInputSpacing[0] * (double) nOldX / (double) vfOutputSpacing[0]) +0.5);
d->dimY = floor((vfInputSpacing[1] * (double) nOldY / (double) vfOutputSpacing[1]) +0.5);
d->dimZ = floor((vfInputSpacing[2] * (double) nOldZ / (double) vfOutputSpacing[2]) +0.5);
}
typename ImageType::SizeType vnOutputSize;
vnOutputSize[0] = d->dimX;
vnOutputSize[1] = d->dimY;
vnOutputSize[2] = d->dimZ;
resampleFilter->SetInput(inputImage);
resampleFilter->SetSize(vnOutputSize);
resampleFilter->SetOutputSpacing(vfOutputSpacing);
resampleFilter->SetOutputOrigin( inputImage->GetOrigin() );
resampleFilter->SetOutputDirection(inputImage->GetDirection() );
resampleFilter->UpdateLargestPossibleRegion();
d->output = medAbstractDataFactory::instance()->create(inputData->identifier());
d->output->setData(resampleFilter->GetOutput());
medUtilities::setDerivedMetaData(d->output, inputData, "resampled");
return DTK_SUCCEED;
}
medAbstractData * resampleProcess::output ( void )
{
return ( d->output );
}
// /////////////////////////////////////////////////////////////////
// Type instantiation
// /////////////////////////////////////////////////////////////////
dtkAbstractProcess *createResampleProcess(void)
{
return new resampleProcess;
}
| 28.925714
| 112
| 0.614184
|
nebatmusic
|
6c767fd7fe905d57aad21b55162e1077581ede1f
| 6,219
|
hpp
|
C++
|
libraries/chain/include/deip/chain/services/dbs_expertise_allocation_proposal.hpp
|
DEIPworld/deip-chain
|
d3fdcfdde179f700156156ea87522a807ec52532
|
[
"MIT"
] | 1
|
2021-08-16T12:44:43.000Z
|
2021-08-16T12:44:43.000Z
|
libraries/chain/include/deip/chain/services/dbs_expertise_allocation_proposal.hpp
|
DEIPworld/deip-chain
|
d3fdcfdde179f700156156ea87522a807ec52532
|
[
"MIT"
] | null | null | null |
libraries/chain/include/deip/chain/services/dbs_expertise_allocation_proposal.hpp
|
DEIPworld/deip-chain
|
d3fdcfdde179f700156156ea87522a807ec52532
|
[
"MIT"
] | 2
|
2021-08-16T12:44:46.000Z
|
2021-12-31T17:09:45.000Z
|
#pragma once
#include "dbs_base_impl.hpp"
#include <vector>
#include <set>
#include <functional>
#include <deip/chain/schema/expertise_allocation_proposal_object.hpp>
#include <deip/chain/schema/expertise_allocation_proposal_vote_object.hpp>
#include <deip/chain/schema/expert_token_object.hpp>
namespace deip {
namespace chain {
class dbs_expertise_allocation_proposal : public dbs_base {
friend class dbservice_dbs_factory;
dbs_expertise_allocation_proposal() = delete;
protected:
explicit dbs_expertise_allocation_proposal(database &db);
public:
using expertise_allocation_proposal_refs_type = std::vector<std::reference_wrapper<const expertise_allocation_proposal_object>>;
using expertise_allocation_proposal_optional_ref_type = fc::optional<std::reference_wrapper<const expertise_allocation_proposal_object>>;
const expertise_allocation_proposal_object& create(const account_name_type& claimer,
const discipline_id_type& discipline_id,
const string& description);
const expertise_allocation_proposal_object& get(const expertise_allocation_proposal_id_type& id) const;
const expertise_allocation_proposal_optional_ref_type get_expertise_allocation_proposal_if_exists(const expertise_allocation_proposal_id_type& id) const;
void remove(const expertise_allocation_proposal_id_type& id);
expertise_allocation_proposal_refs_type get_by_claimer(const account_name_type& claimer) const;
const expertise_allocation_proposal_object& get_by_claimer_and_discipline(const account_name_type& claimer,
const discipline_id_type& discipline_id) const;
const expertise_allocation_proposal_optional_ref_type get_expertise_allocation_proposal_by_claimer_and_discipline_if_exists(const account_name_type& claimer,
const discipline_id_type& discipline_id) const;
expertise_allocation_proposal_refs_type get_by_discipline_id(const discipline_id_type& discipline_id) const;
void check_existence_by_claimer_and_discipline(const account_name_type &claimer,
const discipline_id_type &discipline_id);
bool exists_by_claimer_and_discipline(const account_name_type &claimer,
const discipline_id_type &discipline_id);
void upvote(const expertise_allocation_proposal_object &expertise_allocation_proposal,
const account_name_type &voter,
const share_type weight);
void downvote(const expertise_allocation_proposal_object &expertise_allocation_proposal,
const account_name_type &voter,
const share_type weight);
bool is_expired(const expertise_allocation_proposal_object& expertise_allocation_proposal);
bool is_quorum(const expertise_allocation_proposal_object &expertise_allocation_proposal);
void delete_by_claimer_and_discipline(const account_name_type &claimer,
const discipline_id_type& discipline_id);
void clear_expired_expertise_allocation_proposals();
void process_expertise_allocation_proposals();
/* Expertise allocation proposal vote */
using expertise_allocation_proposal_vote_refs_type = std::vector<std::reference_wrapper<const expertise_allocation_proposal_vote_object>>;
using expertise_allocation_proposal_vote_optional_ref_type = fc::optional<std::reference_wrapper<const expertise_allocation_proposal_vote_object>>;
const expertise_allocation_proposal_vote_object& create_vote(const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id,
const discipline_id_type& discipline_id,
const account_name_type &voter,
const share_type weight);
const expertise_allocation_proposal_vote_object& get_vote(const expertise_allocation_proposal_vote_id_type& id) const;
const expertise_allocation_proposal_vote_optional_ref_type get_expertise_allocation_proposal_vote_if_exists(const expertise_allocation_proposal_vote_id_type& id) const;
const expertise_allocation_proposal_vote_object& get_vote_by_voter_and_expertise_allocation_proposal_id(const account_name_type &voter,
const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id) const;
const expertise_allocation_proposal_vote_optional_ref_type get_expertise_allocation_proposal_vote_by_voter_and_expertise_allocation_proposal_id_if_exists(const account_name_type &voter,
const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id) const;
expertise_allocation_proposal_vote_refs_type get_votes_by_expertise_allocation_proposal_id(const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id) const;
expertise_allocation_proposal_vote_refs_type get_votes_by_voter_and_discipline_id(const account_name_type& voter,
const discipline_id_type& discipline_id) const;
expertise_allocation_proposal_vote_refs_type get_votes_by_voter(const account_name_type& voter) const;
bool vote_exists_by_voter_and_expertise_allocation_proposal_id(const account_name_type &voter,
const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id);
/* Adjusting */
void adjust_expert_token_vote(const expert_token_object& expert_token, share_type delta);
};
} // namespace chain
} // namespace deip
| 56.027027
| 243
| 0.705419
|
DEIPworld
|
6c7737a2a29d9a93b0374dec4932899a19dd8a36
| 265
|
cpp
|
C++
|
tests/src/test.cpp
|
pqrs-org/cpp-environment_variable
|
2b1d547603f5ce4a4455a254a4dbe514f14cd75e
|
[
"BSL-1.0"
] | null | null | null |
tests/src/test.cpp
|
pqrs-org/cpp-environment_variable
|
2b1d547603f5ce4a4455a254a4dbe514f14cd75e
|
[
"BSL-1.0"
] | null | null | null |
tests/src/test.cpp
|
pqrs-org/cpp-environment_variable
|
2b1d547603f5ce4a4455a254a4dbe514f14cd75e
|
[
"BSL-1.0"
] | null | null | null |
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <pqrs/environment_variable.hpp>
TEST_CASE("find") {
REQUIRE(pqrs::environment_variable::find("PATH"));
REQUIRE(pqrs::environment_variable::find("UNKNOWN_ENVIRONMENT_VARIABLE") == std::nullopt);
}
| 26.5
| 92
| 0.766038
|
pqrs-org
|