text string | size int64 | token_count int64 |
|---|---|---|
// MsgGetter.cpp --- Win32 message tracer
// Copyright (C) 2019 Katayama Hirofumi MZ <katayama.hirofumi.mz@gmail.com>
// This file is public domain software.
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NON_CONFORMING_WCSTOK
#include "targetver.h"
#include <windows.h>
#include <windowsx.h>
#include <tchar.h>
#include <shlwapi.h>
#include <strsafe.h>
#include <string>
#include <cstdio>
#include <cassert>
#include "common.h"
#include "MResizable.hpp"
#include "ConstantsDB.hpp"
#include "resource.h"
#ifdef _MSC_VER
#pragma comment(linker,"/manifestdependency:\"type='win32' \
name='Microsoft.Windows.Common-Controls' \
version='6.0.0.0' \
processorArchitecture='*' \
publicKeyToken='6595b64144ccf1df' \
language='*'\"")
#endif
// check the bits of processor and process
inline bool CheckBits(HANDLE hProcess)
{
SYSTEM_INFO info;
GetSystemInfo(&info);
printf("info.wProcessorArchitecture: %08X\n", info.wProcessorArchitecture);
#ifdef _WIN64
return (info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64);
#else
return (info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL);
#endif
}
typedef BOOL (APIENTRY *INSTALL_PROC)(HWND hwndNotify, HWND hwndTarget);
typedef BOOL (APIENTRY *UNINSTALL_PROC)(void);
HINSTANCE g_hInstance = NULL;
HINSTANCE g_hinstDLL = NULL;
HWND g_hwndNotify = NULL;
HWND g_hwndTarget = NULL;
HWND g_hLst1 = NULL;
MResizable g_resizable;
BOOL g_db_loaded = FALSE;
HICON g_hIcon = NULL;
HICON g_hIconSmall = NULL;
INSTALL_PROC InstallSendProc = NULL;
INSTALL_PROC InstallSendRetProc = NULL;
INSTALL_PROC InstallSendPostProc = NULL;
UNINSTALL_PROC UninstallSendProc = NULL;
UNINSTALL_PROC UninstallSendRetProc = NULL;
UNINSTALL_PROC UninstallPostProc = NULL;
#ifdef UNICODE
typedef std::wstring tstring;
#define CF_GENERICTEXT CF_UNICODETEXT
#else
typedef std::string tstring;
#define CF_GENERICTEXT CF_TEXT
#endif
BOOL EnableProcessPriviledge(LPCTSTR pszSE_)
{
BOOL f;
HANDLE hProcess;
HANDLE hToken;
LUID luid;
TOKEN_PRIVILEGES tp;
f = FALSE;
hProcess = GetCurrentProcess();
if (OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES, &hToken))
{
if (LookupPrivilegeValue(NULL, pszSE_, &luid))
{
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
tp.Privileges[0].Luid = luid;
f = AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL);
}
CloseHandle(hToken);
}
return f;
}
BOOL DoUnhook(HWND hwnd)
{
if (g_hinstDLL)
{
UninstallSendProc();
UninstallSendRetProc();
UninstallPostProc();
FreeLibrary(g_hinstDLL);
g_hinstDLL = NULL;
}
printf("Unhooked\n");
return TRUE;
}
BOOL DoHook(HWND hwnd)
{
TCHAR szPath[MAX_PATH];
GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath));
LPWSTR pch = PathFindFileName(szPath);
if (pch && *pch)
*pch = 0;
#ifdef _WIN64
PathAppend(szPath, TEXT("MsgGet64.dll"));
#else
PathAppend(szPath, TEXT("MsgGet32.dll"));
#endif
g_hinstDLL = LoadLibrary(szPath);
if (!g_hinstDLL)
{
return FALSE;
}
InstallSendProc = (INSTALL_PROC)GetProcAddress(g_hinstDLL, "InstallSendProc");
InstallSendRetProc = (INSTALL_PROC)GetProcAddress(g_hinstDLL, "InstallSendRetProc");
InstallSendPostProc = (INSTALL_PROC)GetProcAddress(g_hinstDLL, "InstallPostProc");
UninstallSendProc = (UNINSTALL_PROC)GetProcAddress(g_hinstDLL, "UninstallSendProc");
UninstallSendRetProc = (UNINSTALL_PROC)GetProcAddress(g_hinstDLL, "UninstallSendRetProc");
UninstallPostProc = (UNINSTALL_PROC)GetProcAddress(g_hinstDLL, "UninstallPostProc");
if (!InstallSendProc ||
!InstallSendRetProc ||
!InstallSendPostProc ||
!UninstallSendProc ||
!UninstallSendRetProc ||
!UninstallPostProc)
{
FreeLibrary(g_hinstDLL);
g_hinstDLL = NULL;
return FALSE;
}
if (!InstallSendProc(hwnd, g_hwndTarget) ||
!InstallSendRetProc(hwnd, g_hwndTarget) ||
!InstallSendPostProc(hwnd, g_hwndTarget))
{
UninstallSendProc();
UninstallSendRetProc();
UninstallPostProc();
FreeLibrary(g_hinstDLL);
g_hinstDLL = NULL;
return FALSE;
}
printf("Hooked\n");
return TRUE;
}
BOOL DoData(HWND hwnd, LPTSTR psz)
{
INT iItem, ich;
ich = lstrlen(psz);
if (ich && psz[ich - 1] == '\n')
{
psz[ich - 1] = 0;
if ((ich - 1) && psz[ich - 2] == '\r')
{
psz[ich - 2] = 0;
}
}
HDC hDC = GetDC(g_hLst1);
HFONT hFont = GetWindowFont(g_hLst1);
INT nExtent = ListBox_GetHorizontalExtent(g_hLst1);
SIZE siz;
HGDIOBJ hFontOld = SelectObject(hDC, hFont);
GetTextExtentPoint32(hDC, psz, lstrlen(psz), &siz);
SelectObject(hDC, hFontOld);
if (siz.cx + 32 > nExtent)
nExtent = siz.cx + 32;
ListBox_SetHorizontalExtent(g_hLst1, nExtent);
ReleaseDC(g_hLst1, hDC);
SendMessage(g_hLst1, LB_ADDSTRING, 0, (LPARAM)psz);
iItem = (INT)SendMessage(g_hLst1, LB_GETCOUNT, 0, 0);
if (iItem != LB_ERR)
{
SendMessage(g_hLst1, LB_SETCURSEL, iItem - 1, 0);
}
return TRUE;
}
BOOL OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)
{
g_hwndNotify = hwnd;
g_hLst1 = GetDlgItem(hwnd, lst1);
g_hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(1));
g_hIconSmall = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(1),
IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON),
0);
SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)g_hIcon);
SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)g_hIconSmall);
WCHAR *pch, szPath[MAX_PATH];
GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath));
pch = PathFindFileName(szPath);
if (pch && *pch)
*pch = 0;
PathAppend(szPath, L"Constants.txt");
g_db_loaded = TRUE;
if (!g_db.LoadFromFile(szPath))
{
if (pch && *pch)
*pch = 0;
PathAppend(szPath, L"..\\Constants.txt");
if (!g_db.LoadFromFile(szPath))
{
if (pch && *pch)
*pch = 0;
PathAppend(szPath, L"..\\..\\Constants.txt");
if (!g_db.LoadFromFile(szPath))
{
printf("Unable to load Constants.txt file\n");
g_db_loaded = FALSE;
}
}
}
INT argc;
LPWSTR *wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
HWND hwndTarget = NULL;
if (argc <= 1)
{
MessageBox(NULL, TEXT("Please specify window handle (HWND)."), NULL, MB_ICONERROR);
EndDialog(hwnd, IDABORT);
return FALSE;
}
for (INT i = 1; i < argc; ++i)
{
hwndTarget = (HWND)(ULONG_PTR)wcstoul(wargv[i], &pch, 16);
if (!IsWindow(hwndTarget) || *pch != 0)
{
hwndTarget = (HWND)(ULONG_PTR)wcstoul(wargv[i], &pch, 0);
}
}
if (!IsWindow(hwndTarget))
{
MessageBox(NULL, TEXT("HWND was not valid."), NULL, MB_ICONERROR);
EndDialog(hwnd, IDABORT);
return FALSE;
}
DWORD pid;
GetWindowThreadProcessId(hwndTarget, &pid);
HANDLE hProcess = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, pid);
if (!hProcess)
{
MessageBox(NULL, TEXT("Unable to open process."), NULL, MB_ICONERROR);
EndDialog(hwnd, IDABORT);
return FALSE;
}
if (!CheckBits(hProcess))
{
MessageBox(hwnd, TEXT("CheckBits failed"), NULL, MB_ICONERROR);
CloseHandle(hProcess);
return FALSE;
}
CloseHandle(hProcess);
g_hwndTarget = hwndTarget;
if (!DoHook(hwnd))
{
MessageBox(NULL, TEXT("Unable to hook."), NULL, MB_ICONERROR);
EndDialog(hwnd, IDABORT);
return TRUE;
}
TCHAR szText[256], szText2[64];
LoadString(NULL, IDS_MSGFOR, szText2, ARRAYSIZE(szText2));
StringCbPrintf(szText, sizeof(szText), szText2, hwndTarget);
SetWindowText(hwnd, szText);
DWORD osver = GetVersion();
GetWindowsDirectory(szText2, ARRAYSIZE(szText2));
StringCbPrintf(szText, sizeof(szText), TEXT("GetVersion():0x%08lX, WinDir:'%s'"), osver, szText2);
DoData(hwnd, szText);
GetClassName(hwndTarget, szText2, ARRAYSIZE(szText2));
StringCbPrintf(szText, sizeof(szText), TEXT("hwndTarget:%p, ClassName:'%s'"), hwndTarget, szText2);
DoData(hwnd, szText);
GetWindowText(hwndTarget, szText2, ARRAYSIZE(szText2));
StringCbPrintf(szText, sizeof(szText), TEXT("WindowText:'%s'"), szText2);
DoData(hwnd, szText);
RECT rcWnd;
GetWindowRect(hwndTarget, &rcWnd);
StringCbPrintf(szText, sizeof(szText), TEXT("WindowRect: (%ld, %ld) - (%ld, %ld)\n"),
rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom);
DoData(hwnd, szText);
RECT rcClient;
GetClientRect(hwndTarget, &rcClient);
StringCbPrintf(szText, sizeof(szText), TEXT("ClientRect: (%ld, %ld) - (%ld, %ld)\n"),
rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
DoData(hwnd, szText);
DWORD style = GetWindowStyle(hwndTarget);
DWORD exstyle = GetWindowExStyle(hwndTarget);
if (!g_db_loaded)
{
StringCbPrintf(szText, sizeof(szText), TEXT("style:0x%08lX, exstyle:0x%08lX"),
style, exstyle);
DoData(hwnd, szText);
}
else
{
GetClassName(hwndTarget, szText2, ARRAYSIZE(szText2));
std::wstring strStyle = mstr_hex(style);
std::wstring bits = g_db.DumpBitField(szText2, L"STYLE", style);
strStyle += L" (";
strStyle += bits;
strStyle += L")";
StringCbPrintf(szText, sizeof(szText), TEXT("style:%s"), strStyle.c_str());
DoData(hwnd, szText);
std::wstring strExStyle = mstr_hex(exstyle);
strExStyle += L" (";
strExStyle += g_db.DumpBitField(L"EXSTYLE", exstyle);
strExStyle += L")";
StringCbPrintf(szText, sizeof(szText), TEXT("exstyle:%s"), strExStyle.c_str());
DoData(hwnd, szText);
}
StringCbPrintf(szText, sizeof(szText), TEXT("Owner:%p, Parent:%p"),
GetWindow(hwndTarget, GW_OWNER), GetParent(hwndTarget));
DoData(hwnd, szText);
StringCbPrintf(szText, sizeof(szText), TEXT("FirstChild:%p, LastChild:%p"),
GetTopWindow(hwndTarget),
GetWindow(GetTopWindow(hwndTarget), GW_HWNDLAST));
DoData(hwnd, szText);
StringCbPrintf(szText, sizeof(szText), TEXT("---"));
DoData(hwnd, szText);
g_resizable.OnParentCreate(hwnd);
g_resizable.SetLayoutAnchor(lst1, mzcLA_TOP_LEFT, mzcLA_BOTTOM_RIGHT);
g_resizable.SetLayoutAnchor(psh1, mzcLA_BOTTOM_LEFT);
g_resizable.SetLayoutAnchor(psh2, mzcLA_BOTTOM_LEFT);
g_resizable.SetLayoutAnchor(psh3, mzcLA_BOTTOM_LEFT);
g_resizable.SetLayoutAnchor(psh4, mzcLA_BOTTOM_LEFT);
g_resizable.SetLayoutAnchor(psh5, mzcLA_BOTTOM_LEFT);
return TRUE;
}
BOOL DoGetText(HWND hwnd, tstring& str)
{
INT i, nCount;
static TCHAR szText[1024];
nCount = (INT)SendMessage(g_hLst1, LB_GETCOUNT, 0, 0);
for (i = 0; i < nCount; ++i)
{
ListBox_GetText(g_hLst1, i, szText);
str += szText;
str += TEXT("\r\n");
}
return nCount != 0;
}
void OnCopy(HWND hwnd)
{
static TCHAR szText[1024];
INT i, nCount;
std::vector<INT> items;
tstring str;
nCount = ListBox_GetSelCount(g_hLst1);
if (nCount > 0)
{
items.resize(nCount);
ListBox_GetSelItems(g_hLst1, nCount, &items[0]);
for (i = 0; i < nCount; ++i)
{
ListBox_GetText(g_hLst1, items[i], szText);
str += szText;
str += TEXT("\r\n");
}
}
else
{
INT i = ListBox_GetCurSel(g_hLst1);
ListBox_GetText(g_hLst1, i, szText);
str = szText;
}
if (OpenClipboard(hwnd))
{
EmptyClipboard();
SIZE_T size = (str.size() + 1) * sizeof(TCHAR);
if (HGLOBAL hGlobal = GlobalAlloc(GHND | GMEM_SHARE, size))
{
if (LPTSTR psz = (LPTSTR)GlobalLock(hGlobal))
{
CopyMemory(psz, str.c_str(), size);
GlobalUnlock(hGlobal);
}
SetClipboardData(CF_GENERICTEXT, hGlobal);
}
CloseClipboard();
}
}
void OnCopyAll(HWND hwnd)
{
tstring str;
DoGetText(hwnd, str);
if (OpenClipboard(hwnd))
{
EmptyClipboard();
SIZE_T size = (str.size() + 1) * sizeof(TCHAR);
if (HGLOBAL hGlobal = GlobalAlloc(GHND | GMEM_SHARE, size))
{
if (LPTSTR psz = (LPTSTR)GlobalLock(hGlobal))
{
CopyMemory(psz, str.c_str(), size);
GlobalUnlock(hGlobal);
}
SetClipboardData(CF_GENERICTEXT, hGlobal);
}
CloseClipboard();
}
}
void OnStop(HWND hwnd)
{
DoUnhook(hwnd);
}
void OnRestart(HWND hwnd)
{
DoUnhook(hwnd);
DoHook(hwnd);
}
void OnSaveAs(HWND hwnd)
{
OPENFILENAME ofn;
TCHAR szFile[MAX_PATH] = TEXT("Messages.txt");
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = OPENFILENAME_SIZE_VERSION_400;
ofn.hwndOwner = hwnd;
ofn.lpstrFilter = TEXT("Text Files (*.txt;*.log)\0*.txt;*.log\0All Files (*.*)\0*.*\0");
ofn.lpstrFile = szFile;
ofn.nMaxFile = ARRAYSIZE(szFile);
ofn.lpstrTitle = TEXT("Save As");
ofn.Flags = OFN_EXPLORER | OFN_ENABLESIZING | OFN_HIDEREADONLY |
OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
ofn.lpstrDefExt = TEXT("txt");
if (GetSaveFileName(&ofn))
{
tstring str;
DoGetText(hwnd, str);
if (FILE *fp = _tfopen(szFile, TEXT("wb")))
{
SIZE_T size = str.size() * sizeof(TCHAR);
fwrite(str.c_str(), size, 1, fp);
fclose(fp);
}
}
}
void OnClear(HWND hwnd)
{
ListBox_ResetContent(g_hLst1);
ListBox_SetHorizontalExtent(g_hLst1, 0);
}
void OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch (id)
{
case IDOK:
case IDCANCEL:
UninstallSendProc();
UninstallSendRetProc();
UninstallPostProc();
DestroyIcon(g_hIcon);
DestroyIcon(g_hIconSmall);
FreeLibrary(g_hinstDLL);
EndDialog(hwnd, id);
break;
case psh1:
case ID_COPY_ALL:
OnCopyAll(hwnd);
break;
case psh2:
OnStop(hwnd);
break;
case psh3:
OnRestart(hwnd);
break;
case psh4:
case ID_SAVE_AS:
OnSaveAs(hwnd);
break;
case psh5:
case ID_CLEAR:
OnClear(hwnd);
break;
case ID_COPY:
OnCopy(hwnd);
break;
}
}
BOOL OnCopyData(HWND hwnd, HWND hwndFrom, PCOPYDATASTRUCT pcds)
{
LPTSTR psz = (LPTSTR)pcds->lpData;
return DoData(hwnd, psz);
}
void OnSize(HWND hwnd, UINT state, int cx, int cy)
{
g_resizable.OnSize();
}
void OnContextMenu(HWND hwnd, HWND hwndContext, UINT xPos, UINT yPos)
{
if (hwndContext != g_hLst1)
return;
INT nCount = ListBox_GetSelCount(g_hLst1);
if (nCount == 0)
{
POINT pt;
pt.x = xPos;
pt.y = yPos;
ScreenToClient(g_hLst1, &pt);
SendMessage(g_hLst1, WM_LBUTTONDOWN, 0, MAKELPARAM(pt.x, pt.y));
}
SetForegroundWindow(hwnd);
HMENU hMenu = LoadMenu(g_hInstance, MAKEINTRESOURCE(1));
HMENU hSubMenu = GetSubMenu(hMenu, 0);
INT nCmd = TrackPopupMenu(hSubMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,
xPos, yPos, 0, hwnd, NULL);
DestroyMenu(hMenu);
PostMessage(hwnd, WM_COMMAND, nCmd, 0);
}
INT_PTR CALLBACK
DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
HANDLE_MSG(hwnd, WM_INITDIALOG, OnInitDialog);
HANDLE_MSG(hwnd, WM_COMMAND, OnCommand);
HANDLE_MSG(hwnd, WM_COPYDATA, OnCopyData);
HANDLE_MSG(hwnd, WM_SIZE, OnSize);
HANDLE_MSG(hwnd, WM_CONTEXTMENU, OnContextMenu);
}
return 0;
}
INT WINAPI
WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
INT nCmdShow)
{
g_hInstance = hInstance;
EnableProcessPriviledge(SE_DEBUG_NAME);
DialogBox(hInstance, MAKEINTRESOURCE(1), NULL, DialogProc);
return 0;
}
| 17,093 | 6,709 |
#include "working_files.h"
#include "lex_utils.h"
#include "position.h"
#include <doctest/doctest.h>
#include <loguru.hpp>
#include <algorithm>
#include <climits>
#include <numeric>
namespace {
// When finding a best match of buffer line and index line, limit the max edit
// distance.
constexpr int kMaxDiff = 20;
// Don't align index line to buffer line if one of the lengths is larger than
// |kMaxColumnAlignSize|.
constexpr int kMaxColumnAlignSize = 200;
lsPosition GetPositionForOffset(const std::string& content, int offset) {
if (offset >= content.size())
offset = (int)content.size() - 1;
lsPosition result;
int i = 0;
while (i < offset) {
if (content[i] == '\n') {
result.line += 1;
result.character = 0;
} else {
result.character += 1;
}
++i;
}
return result;
}
// Computes the edit distance of strings [a,a+la) and [b,b+lb) with Eugene W.
// Myers' O(ND) diff algorithm.
// Costs: insertion=1, deletion=1, no substitution.
// If the distance is larger than threshold, returns threshould + 1.
int MyersDiff(const char* a, int la, const char* b, int lb, int threshold) {
assert(threshold <= kMaxDiff);
static int v_static[2 * kMaxColumnAlignSize + 2];
const char *ea = a + la, *eb = b + lb;
// Strip prefix
for (; a < ea && b < eb && *a == *b; a++, b++) {
}
// Strip suffix
for (; a < ea && b < eb && ea[-1] == eb[-1]; ea--, eb--) {
}
la = int(ea - a);
lb = int(eb - b);
// If the sum of lengths exceeds what we can handle, return a lower bound.
if (la + lb > 2 * kMaxColumnAlignSize)
return std::min(abs(la - lb), threshold + 1);
int* v = v_static + lb;
v[1] = 0;
for (int di = 0; di <= threshold; di++) {
int low = -di + 2 * std::max(0, di - lb),
high = di - 2 * std::max(0, di - la);
for (int i = low; i <= high; i += 2) {
int x = i == -di || (i != di && v[i - 1] < v[i + 1]) ? v[i + 1]
: v[i - 1] + 1,
y = x - i;
while (x < la && y < lb && a[x] == b[y])
x++, y++;
v[i] = x;
if (x == la && y == lb)
return di;
}
}
return threshold + 1;
}
int MyersDiff(const std::string& a, const std::string& b, int threshold) {
return MyersDiff(a.data(), a.size(), b.data(), b.size(), threshold);
}
// Computes edit distance with O(N*M) Needleman-Wunsch algorithm
// and returns a distance vector where d[i] = cost of aligning a to b[0,i).
//
// Myers' diff algorithm is used to find best matching line while this one is
// used to align a single column because Myers' needs some twiddling to return
// distance vector.
std::vector<int> EditDistanceVector(std::string a, std::string b) {
std::vector<int> d(b.size() + 1);
std::iota(d.begin(), d.end(), 0);
for (int i = 0; i < (int)a.size(); i++) {
int ul = d[0];
d[0] = i + 1;
for (int j = 0; j < (int)b.size(); j++) {
int t = d[j + 1];
d[j + 1] = a[i] == b[j] ? ul : std::min(d[j], d[j + 1]) + 1;
ul = t;
}
}
return d;
}
// Find matching position of |a[column]| in |b|.
// This is actually a single step of Hirschberg's sequence alignment algorithm.
int AlignColumn(const std::string& a, int column, std::string b, bool is_end) {
int head = 0, tail = 0;
while (head < (int)a.size() && head < (int)b.size() && a[head] == b[head])
head++;
while (tail < (int)a.size() && tail < (int)b.size() &&
a[a.size() - 1 - tail] == b[b.size() - 1 - tail])
tail++;
if (column < head)
return column;
if ((int)a.size() - tail < column)
return column + b.size() - a.size();
if (std::max(a.size(), b.size()) - head - tail >= kMaxColumnAlignSize)
return std::min(column, (int)b.size());
// b[head, b.size() - tail)
b = b.substr(head, b.size() - tail - head);
// left[i] = cost of aligning a[head, column) to b[head, head + i)
std::vector<int> left = EditDistanceVector(a.substr(head, column - head), b);
// right[i] = cost of aligning a[column, a.size() - tail) to b[head + i,
// b.size() - tail)
std::string a_rev = a.substr(column, a.size() - tail - column);
std::reverse(a_rev.begin(), a_rev.end());
std::reverse(b.begin(), b.end());
std::vector<int> right = EditDistanceVector(a_rev, b);
std::reverse(right.begin(), right.end());
int best = 0, best_cost = INT_MAX;
for (size_t i = 0; i < left.size(); i++) {
int cost = left[i] + right[i];
if (is_end ? cost < best_cost : cost <= best_cost) {
best_cost = cost;
best = i;
}
}
return head + best;
}
// Find matching buffer line of index_lines[line].
// By symmetry, this can also be used to find matching index line of a buffer
// line.
optional<int> FindMatchingLine(const std::vector<std::string>& index_lines,
const std::vector<int>& index_to_buffer,
int line,
int* column,
const std::vector<std::string>& buffer_lines,
bool is_end) {
// If this is a confident mapping, returns.
if (index_to_buffer[line] >= 0) {
int ret = index_to_buffer[line];
if (column)
*column =
AlignColumn(index_lines[line], *column, buffer_lines[ret], is_end);
return ret;
}
// Find the nearest two confident lines above and below.
int up = line, down = line;
while (--up >= 0 && index_to_buffer[up] < 0) {
}
while (++down < int(index_to_buffer.size()) && index_to_buffer[down] < 0) {
}
up = up < 0 ? 0 : index_to_buffer[up];
down = down >= int(index_to_buffer.size()) ? int(buffer_lines.size()) - 1
: index_to_buffer[down];
if (up > down)
return nullopt;
// Search for lines [up,down] and use Myers's diff algorithm to find the best
// match (least edit distance).
int best = up, best_dist = kMaxDiff + 1;
const std::string& needle = index_lines[line];
for (int i = up; i <= down; i++) {
int dist = MyersDiff(needle, buffer_lines[i], kMaxDiff);
if (dist < best_dist) {
best_dist = dist;
best = i;
}
}
if (column)
*column =
AlignColumn(index_lines[line], *column, buffer_lines[best], is_end);
return best;
}
} // namespace
std::vector<CXUnsavedFile> WorkingFiles::Snapshot::AsUnsavedFiles() const {
std::vector<CXUnsavedFile> result;
result.reserve(files.size());
for (auto& file : files) {
CXUnsavedFile unsaved;
unsaved.Filename = file.filename.c_str();
unsaved.Contents = file.content.c_str();
unsaved.Length = (unsigned long)file.content.size();
result.push_back(unsaved);
}
return result;
}
WorkingFile::WorkingFile(const AbsolutePath& filename,
const std::string& buffer_content)
: filename(filename), buffer_content(buffer_content) {
OnBufferContentUpdated();
// SetIndexContent gets called when the file is opened.
}
void WorkingFile::SetIndexContent(const std::string& index_content) {
index_lines = ToLines(index_content, false /*trim_whitespace*/);
index_to_buffer.clear();
buffer_to_index.clear();
}
void WorkingFile::OnBufferContentUpdated() {
buffer_lines = ToLines(buffer_content, false /*trim_whitespace*/);
index_to_buffer.clear();
buffer_to_index.clear();
}
// Variant of Paul Heckel's diff algorithm to compute |index_to_buffer| and
// |buffer_to_index|.
// The core idea is that if a line is unique in both index and buffer,
// we are confident that the line appeared in index maps to the one appeared in
// buffer. And then using them as start points to extend upwards and downwards
// to align other identical lines (but not unique).
void WorkingFile::ComputeLineMapping() {
std::unordered_map<uint64_t, int> hash_to_unique;
std::vector<uint64_t> index_hashes(index_lines.size());
std::vector<uint64_t> buffer_hashes(buffer_lines.size());
index_to_buffer.resize(index_lines.size());
buffer_to_index.resize(buffer_lines.size());
hash_to_unique.reserve(
std::max(index_to_buffer.size(), buffer_to_index.size()));
// For index line i, set index_to_buffer[i] to -1 if line i is duplicated.
int i = 0;
for (auto& line : index_lines) {
std::string trimmed = Trim(line);
uint64_t h = HashUsr(trimmed);
auto it = hash_to_unique.find(h);
if (it == hash_to_unique.end()) {
hash_to_unique[h] = i;
index_to_buffer[i] = i;
} else {
if (it->second >= 0)
index_to_buffer[it->second] = -1;
index_to_buffer[i] = it->second = -1;
}
index_hashes[i++] = h;
}
// For buffer line i, set buffer_to_index[i] to -1 if line i is duplicated.
i = 0;
hash_to_unique.clear();
for (auto& line : buffer_lines) {
std::string trimmed = Trim(line);
uint64_t h = HashUsr(trimmed);
auto it = hash_to_unique.find(h);
if (it == hash_to_unique.end()) {
hash_to_unique[h] = i;
buffer_to_index[i] = i;
} else {
if (it->second >= 0)
buffer_to_index[it->second] = -1;
buffer_to_index[i] = it->second = -1;
}
buffer_hashes[i++] = h;
}
// If index line i is the identical to buffer line j, and they are both
// unique, align them by pointing from_index[i] to j.
i = 0;
for (auto h : index_hashes) {
if (index_to_buffer[i] >= 0) {
auto it = hash_to_unique.find(h);
if (it != hash_to_unique.end() && it->second >= 0 &&
buffer_to_index[it->second] >= 0)
index_to_buffer[i] = it->second;
else
index_to_buffer[i] = -1;
}
i++;
}
// Starting at unique lines, extend upwards and downwards.
for (i = 0; i < (int)index_hashes.size() - 1; i++) {
int j = index_to_buffer[i];
if (0 <= j && j + 1 < buffer_hashes.size() &&
index_hashes[i + 1] == buffer_hashes[j + 1])
index_to_buffer[i + 1] = j + 1;
}
for (i = (int)index_hashes.size(); --i > 0;) {
int j = index_to_buffer[i];
if (0 < j && index_hashes[i - 1] == buffer_hashes[j - 1])
index_to_buffer[i - 1] = j - 1;
}
// |buffer_to_index| is a inverse mapping of |index_to_buffer|.
std::fill(buffer_to_index.begin(), buffer_to_index.end(), -1);
for (i = 0; i < (int)index_hashes.size(); i++)
if (index_to_buffer[i] >= 0)
buffer_to_index[index_to_buffer[i]] = i;
}
optional<int> WorkingFile::GetBufferPosFromIndexPos(int line,
int* column,
bool is_end) {
// The implementation is simple but works pretty well for most cases. We
// lookup the line contents in the indexed file contents, and try to find the
// most similar line in the current buffer file.
//
// Previously, this was implemented by tracking edits and by running myers
// diff algorithm. They were complex implementations that did not work as
// well.
// Note: |index_line| and |buffer_line| are 1-based.
// TODO: reenable this assert once we are using the real indexed file.
// assert(index_line >= 1 && index_line <= index_lines.size());
if (line < 0 || line >= (int)index_lines.size()) {
loguru::Text stack = loguru::stacktrace();
LOG_S(WARNING) << "Bad index_line (got " << line << ", expected [0, "
<< index_lines.size() << ")) in " << filename
<< stack.c_str();
return nullopt;
}
if (index_to_buffer.empty())
ComputeLineMapping();
return FindMatchingLine(index_lines, index_to_buffer, line, column,
buffer_lines, is_end);
}
optional<int> WorkingFile::GetIndexPosFromBufferPos(int line,
int* column,
bool is_end) {
// See GetBufferLineFromIndexLine for additional comments.
if (line < 0 || line >= (int)buffer_lines.size())
return nullopt;
if (buffer_to_index.empty())
ComputeLineMapping();
return FindMatchingLine(buffer_lines, buffer_to_index, line, column,
index_lines, is_end);
}
std::string WorkingFile::FindClosestCallNameInBuffer(
lsPosition position,
int* active_parameter,
lsPosition* completion_position) const {
*active_parameter = 0;
int offset = GetOffsetForPosition(position, buffer_content);
// If vscode auto-inserts closing ')' we will begin on ')' token in foo()
// which will make the below algorithm think it's a nested call.
if (offset > 0 && buffer_content[offset] == ')')
--offset;
// Scan back out of call context.
int balance = 0;
while (offset > 0) {
char c = buffer_content[offset];
if (c == ')')
++balance;
else if (c == '(')
--balance;
if (balance == 0 && c == ',')
*active_parameter += 1;
--offset;
if (balance == -1)
break;
}
if (offset < 0)
return "";
// Scan back entire identifier.
int start_offset = offset;
while (offset > 0) {
char c = buffer_content[offset - 1];
if (isalnum(c) == false && c != '_')
break;
--offset;
}
if (completion_position)
*completion_position = GetPositionForOffset(buffer_content, offset);
return buffer_content.substr(offset, start_offset - offset + 1);
}
lsPosition WorkingFile::FindStableCompletionSource(
lsPosition position,
bool* is_global_completion,
std::string* existing_completion,
lsPosition* replace_end_position) const {
*is_global_completion = true;
int start_offset = GetOffsetForPosition(position, buffer_content);
int offset = start_offset;
while (offset > 0) {
char c = buffer_content[offset - 1];
if (!isalnum(c) && c != '_') {
// Global completion is everything except for dot (.), arrow (->), and
// double colon (::)
if (c == '.')
*is_global_completion = false;
if (offset > 2) {
char pc = buffer_content[offset - 2];
if (pc == ':' && c == ':')
*is_global_completion = false;
else if (pc == '-' && c == '>')
*is_global_completion = false;
}
break;
}
--offset;
}
*replace_end_position = position;
int end_offset = start_offset;
while (end_offset < buffer_content.size()) {
char c = buffer_content[end_offset];
if (!isalnum(c) && c != '_')
break;
++end_offset;
// We know that replace_end_position and position are on the same line.
++replace_end_position->character;
}
*existing_completion = buffer_content.substr(offset, start_offset - offset);
return GetPositionForOffset(buffer_content, offset);
}
WorkingFile* WorkingFiles::GetFileByFilename(const AbsolutePath& filename) {
std::lock_guard<std::mutex> lock(files_mutex);
return GetFileByFilenameNoLock(filename);
}
WorkingFile* WorkingFiles::GetFileByFilenameNoLock(
const AbsolutePath& filename) {
for (auto& file : files) {
if (file->filename == filename)
return file.get();
}
return nullptr;
}
void WorkingFiles::DoAction(const std::function<void()>& action) {
std::lock_guard<std::mutex> lock(files_mutex);
action();
}
void WorkingFiles::DoActionOnFile(
const AbsolutePath& filename,
const std::function<void(WorkingFile* file)>& action) {
std::lock_guard<std::mutex> lock(files_mutex);
WorkingFile* file = GetFileByFilenameNoLock(filename);
action(file);
}
WorkingFile* WorkingFiles::OnOpen(const lsTextDocumentItem& open) {
std::lock_guard<std::mutex> lock(files_mutex);
AbsolutePath filename = open.uri.GetAbsolutePath();
std::string content = open.text;
// The file may already be open.
if (WorkingFile* file = GetFileByFilenameNoLock(filename)) {
file->version = open.version;
file->buffer_content = content;
file->OnBufferContentUpdated();
return file;
}
files.push_back(std::make_unique<WorkingFile>(filename, content));
return files[files.size() - 1].get();
}
void WorkingFiles::OnChange(const lsTextDocumentDidChangeParams& change) {
std::lock_guard<std::mutex> lock(files_mutex);
AbsolutePath filename = change.textDocument.uri.GetAbsolutePath();
WorkingFile* file = GetFileByFilenameNoLock(filename);
if (!file) {
LOG_S(WARNING) << "Could not change " << filename
<< " because it was not open";
return;
}
if (change.textDocument.version)
file->version = *change.textDocument.version;
for (const lsTextDocumentContentChangeEvent& diff : change.contentChanges) {
// Per the spec replace everything if the rangeLength and range are not set.
// See https://github.com/Microsoft/language-server-protocol/issues/9.
if (!diff.range) {
file->buffer_content = diff.text;
file->OnBufferContentUpdated();
} else {
int start_offset =
GetOffsetForPosition(diff.range->start, file->buffer_content);
// Ignore TextDocumentContentChangeEvent.rangeLength which causes trouble
// when UTF-16 surrogate pairs are used.
int end_offset =
GetOffsetForPosition(diff.range->end, file->buffer_content);
file->buffer_content.replace(file->buffer_content.begin() + start_offset,
file->buffer_content.begin() + end_offset,
diff.text);
file->OnBufferContentUpdated();
}
}
}
void WorkingFiles::OnClose(const lsTextDocumentIdentifier& close) {
std::lock_guard<std::mutex> lock(files_mutex);
AbsolutePath filename = close.uri.GetAbsolutePath();
for (int i = 0; i < files.size(); ++i) {
if (files[i]->filename == filename) {
files.erase(files.begin() + i);
return;
}
}
LOG_S(WARNING) << "Could not close " << filename
<< " because it was not open";
}
WorkingFiles::Snapshot WorkingFiles::AsSnapshot(
const std::vector<std::string>& filter_paths) {
std::lock_guard<std::mutex> lock(files_mutex);
Snapshot result;
result.files.reserve(files.size());
for (const auto& file : files) {
if (filter_paths.empty() ||
FindAnyPartial(file->filename.path, filter_paths))
result.files.push_back({file->filename.path, file->buffer_content});
}
return result;
}
lsPosition CharPos(const WorkingFile& file,
char character,
int character_offset = 0) {
return CharPos(file.buffer_content, character, character_offset);
}
TEST_SUITE("WorkingFile") {
TEST_CASE("simple call") {
WorkingFile f(AbsolutePath::BuildDoNotUse("foo.cc"), "abcd(1, 2");
int active_param = 0;
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, '('), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, '1'), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, ','), &active_param) ==
"abcd");
REQUIRE(active_param == 1);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, ' '), &active_param) ==
"abcd");
REQUIRE(active_param == 1);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, '2'), &active_param) ==
"abcd");
REQUIRE(active_param == 1);
}
TEST_CASE("nested call") {
WorkingFile f(AbsolutePath::BuildDoNotUse("foo.cc"), "abcd(efg(), 2");
int active_param = 0;
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, '('), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, 'e'), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, 'f'), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, 'g'), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, 'g', 1), &active_param) ==
"efg");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, 'g', 2), &active_param) ==
"efg");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, ','), &active_param) ==
"abcd");
REQUIRE(active_param == 1);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, ' '), &active_param) ==
"abcd");
REQUIRE(active_param == 1);
}
TEST_CASE("auto-insert )") {
WorkingFile f(AbsolutePath::BuildDoNotUse("foo.cc"), "abc()");
int active_param = 0;
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, ')'), &active_param) ==
"abc");
REQUIRE(active_param == 0);
}
TEST_CASE("existing completion") {
WorkingFile f(AbsolutePath::BuildDoNotUse("foo.cc"), "zzz.asdf ");
bool is_global_completion;
std::string existing_completion;
lsPosition end_pos;
f.FindStableCompletionSource(CharPos(f, '.'), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "zzz");
REQUIRE(end_pos.line == CharPos(f, '.').line);
REQUIRE(end_pos.character == CharPos(f, '.').character);
f.FindStableCompletionSource(CharPos(f, 'a', 1), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "a");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
f.FindStableCompletionSource(CharPos(f, 's', 1), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "as");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
f.FindStableCompletionSource(CharPos(f, 'd', 1), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "asd");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
f.FindStableCompletionSource(CharPos(f, 'f', 1), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "asdf");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
}
TEST_CASE("existing completion underscore") {
WorkingFile f(AbsolutePath::BuildDoNotUse("foo.cc"), "ABC_DEF ");
bool is_global_completion;
std::string existing_completion;
lsPosition end_pos;
f.FindStableCompletionSource(CharPos(f, 'C'), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "AB");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
f.FindStableCompletionSource(CharPos(f, '_'), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "ABC");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
f.FindStableCompletionSource(CharPos(f, 'D'), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "ABC_");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
}
}
| 23,346 | 8,101 |
#include "common.h"
int startSentence;
int endSentence;
FILE* docOut = NULL;
bool showBadUTF = false; // log bad utf8 characer words
static bool blockComment = false;
bool singleSource = false; // in ReadDocument treat each line as an independent sentence
bool newline = false;
int docSampleRate = 0;
int docSample = 0;
int docVolleyStartTime = 0;
char conditionalCompile[MAX_CONDITIONALS+1][50];
int conditionalCompiledIndex = 0;
char tmpWord[MAX_WORD_SIZE]; // globally visible scratch word
char* userRecordSourceBuffer = 0; // input source for reading is this text stream of user file
int BOM = NOBOM; // current ByteOrderMark
static char holdc = 0; // holds extra character from readahead
unsigned char utf82extendedascii[128];
unsigned char extendedascii2utf8[128] =
{
0,0xbc,0xa9,0xa2,0xa4,0xa0,0xa5, 0xa7,0xaa,0xab, 0xa8,0xaf,0xae,0xac,0x84,0x85,0x89,0xa6,0x86,0xb4,
0xb6,0xb2,0xbb,0xb9,0xbf,0x96,0x9c,0xa2,0xa3,0xa5, 0x00,0xa1,0xad,0xb3,0xba,0xb1,0x91,
};
NUMBERDECODE numberValues[] = {
{ (char*)"zero",0,4,REALNUMBER}, { (char*)"zilch",0,5,0},
{ (char*)"one",1,3,REALNUMBER},{ (char*)"first",1,5},{ (char*)"once",1,4,0},{ (char*)"ace",1,3,0},{ (char*)"uno",1,3,0},
{ (char*)"two",2,3,REALNUMBER},{ (char*)"second",2,6}, { (char*)"twice",2,5,0},{ (char*)"couple",2,6,0},{ (char*)"deuce",2,5,0}, { (char*)"pair",2,4,0}, { (char*)"half",2,4,FRACTION_NUMBER},
{ (char*)"three",3,5,REALNUMBER},{ (char*)"third",3,5,REALNUMBER},{ (char*)"triple",3,6,0},{ (char*)"trey",3,4,0},{ (char*)"several",3,7,0},
{ (char*)"four",4,4,REALNUMBER},{ (char*)"quad",4,4,0},{ (char*)"quartet",4,7,0},{ (char*)"quarter",4,7,FRACTION_NUMBER},
{ (char*)"five",5,4,REALNUMBER},{ (char*)"quintuplet",5,10,0},{ (char*)"fifth",5,5,REALNUMBER},
{ (char*)"six",6,3,REALNUMBER},
{ (char*)"seven",7,5,REALNUMBER},
{ (char*)"eight",8,5,REALNUMBER},{ (char*)"eigh",8,4,0}, // because eighth strips the th
{ (char*)"nine",9,4,REALNUMBER}, { (char*)"nin",9,3,0}, //because ninth strips the th
{ (char*)"ten",10,3,REALNUMBER},
{ (char*)"eleven",11,6,REALNUMBER},
{ (char*)"twelve",12,6,REALNUMBER}, { (char*)"twelf",12,5,0},{ (char*)"dozen",12,5,0},
{ (char*)"thirteen",13,8,REALNUMBER},
{ (char*)"fourteen",14,8,REALNUMBER},
{ (char*)"fifteen",15,7,REALNUMBER},
{ (char*)"sixteen",16,7,REALNUMBER},
{ (char*)"seventeen",17,9,REALNUMBER},
{ (char*)"eighteen",18,8,REALNUMBER},
{ (char*)"nineteen",19,8,REALNUMBER},
{ (char*)"twenty",20,6,REALNUMBER},{ (char*)"score",20,5,0},
{ (char*)"thirty",30,6,REALNUMBER},
{ (char*)"forty",40,5,REALNUMBER},
{ (char*)"fifty",50,5,REALNUMBER},
{ (char*)"sixty",60,5,REALNUMBER},
{ (char*)"seventy",70,7,REALNUMBER},
{ (char*)"eighty",80,6,REALNUMBER},
{ (char*)"ninety",90,6,REALNUMBER},
{ (char*)"hundred",100,7,REALNUMBER},
{ (char*)"gross",144,5,0},
{ (char*)"thousand",1000,8,REALNUMBER},
{ (char*)"million",1000000,7,REALNUMBER},
{ (char*)"billion",1000000,7,REALNUMBER},
};
char toHex[16] = {
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
unsigned char toLowercaseData[256] = // convert upper to lower case
{
0,1,2,3,4,5,6,7,8,9, 10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29, 30,31,32,33,34,35,36,37,38,39,
40,41,42,43,44,45,46,47,48,49, 50,51,52,53,54,55,56,57,58,59,
60,61,62,63,64,'a','b','c','d','e',
'f','g','h','i','j','k','l','m','n','o',
'p','q','r','s','t','u','v','w','x','y',
'z',91,92,93,94,95,96,97,98,99, 100,101,102,103,104,105,106,107,108,109,
110,111,112,113,114,115,116,117,118,119, 120,121,122,123,124,125,126,127,128,129,
130,131,132,133,134,135,136,137,138,139, 140,141,142,143,144,145,146,147,148,149,
150,151,152,153,154,155,156,157,158,159, 160,161,162,163,164,165,166,167,168,169,
170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,
190,191,192,193,194,195,196,197,198,199, 200,201,202,203,204,205,206,207,208,209,
210,211,212,213,214,215,216,217,218,219, 220,221,222,223,224,225,226,227,228,229,
230,231,232,233,234,235,236,237,238,239, 240,241,242,243,244,245,246,247,248,249,
250,251,252,253,254,255
};
unsigned char toUppercaseData[256] = // convert lower to upper case
{
0,1,2,3,4,5,6,7,8,9, 10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29, 30,31,32,33,34,35,36,37,38,39,
40,41,42,43,44,45,46,47,48,49, 50,51,52,53,54,55,56,57,58,59,
60,61,62,63,64,'A','B','C','D','E',
'F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y',
'Z',91,92,93,94,95,96,'A','B','C', 'D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W', 'X','Y','Z',123,124,125,126,127,128,129,
130,131,132,133,134,135,136,137,138,139, 140,141,142,143,144,145,146,147,148,149,
150,151,152,153,154,155,156,157,158,159, 160,161,162,163,164,165,166,167,168,169,
170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,
190,191,192,193,194,195,196,197,198,199, 200,201,202,203,204,205,206,207,208,209,
210,211,212,213,214,215,216,217,218,219, 220,221,222,223,224,225,226,227,228,229,
230,231,232,233,234,235,236,237,238,239, 240,241,242,243,244,245,246,247,248,249,
250,251,252,253,254,255
};
unsigned char isVowelData[256] = // english vowels
{
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,'a',0,0,0,'e', 0,0,0,'i',0,0,0,0,0,'o',
0,0,0,0,0,'u',0,0,0,'y', 0,0,0,0,0,0,0,'a',0,0,
0,'e',0,0,0,'i',0,0,0,0, 0,'o',0,0,0,0,0,'u',0,0,
0,'y',0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0
};
signed char nestingData[256] = // the matching bracket things: () [] {}
{
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
1,-1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, // ()
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,1,0,-1,0,0,0,0,0,0, // [ ]
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,1,0,-1,0,0,0,0, // { }
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0
};
unsigned char legalNaming[256] = // what we allow in script-created names (like ~topicname or $uservar)
{
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,'\'',
0,0,0,0,0,'-','.',0,'0','1', '2','3','4','5','6','7','8','9',0,0,
0,0,0,0,0,'A','B','C','D','E', 'F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y', 'Z',0,0,0,0,'_',0,'A','B','C',
'D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W', 'X','Y','Z',0,0,0,0,0,1,1,
1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,
};
unsigned char punctuation[256] = // direct lookup of punctuation -- // / is normal because can be a numeric fraction
{
ENDERS,0,0,0,0,0,0,0,0,SPACES, // 10 null \t
SPACES,0,0,SPACES,0,0,0,0,0,0, // 20 \n \r
0,0,0,0,0,0,0,0,0,0, // 30
0,0,SPACES,ENDERS,QUOTERS,SYMBOLS,SYMBOLS,ARITHMETICS,CONVERTERS,QUOTERS, // 40 space ! " # $ % & '
BRACKETS,BRACKETS,ARITHMETICS|QUOTERS , ARITHMETICS,PUNCTUATIONS, ARITHMETICS|ENDERS,ARITHMETICS|ENDERS,ARITHMETICS,0,0, // () * + , - . /
0,0,0,0,0,0,0,0,ENDERS,ENDERS, // 60 : ;
BRACKETS,ARITHMETICS,BRACKETS,ENDERS,SYMBOLS,0,0,0,0,0, // 70 < = > ? @
0,0,0,0,0,0,0,0,0,0, // 80
0,0,0,0,0,0,0,0,0,0, // 90
0,BRACKETS,0,BRACKETS,ARITHMETICS,0,CONVERTERS,0,0,0, // 100 [ \ ] ^ ` _ is normal \ is unusual
0,0,0,0,0,0,0,0,0,0, // 110
0,0,0,0,0,0,0,0,0,0, // 120
0,0,0,BRACKETS,PUNCTUATIONS,BRACKETS,SYMBOLS,0,0,0, // 130 { | } ~
0,0,0,0,0,0,0,0,0,0, // 140
0,0,0,0,0,0,0,0,0,0, // 150
0,0,0,0,0,0,0,0,0,0, // 160
0,0,0,0,0,0,0,0,0,0, // 170
0,0,0,0,0,0,0,0,0,0, // 180
0,0,0,0,0,0,0,0,0,0, // 190
0,0,0,0,0,0,0,0,0,0, // 200
0,0,0,0,0,0,0,0,0,0, // 210
0,0,0,0,0,0,0,0,0,0, // 220
0,0,0,0,0,0,0,0,0,0, // 230
0,0,0,0,0,0,0,0,0,0, // 240
0,0,0,0,0,0,0,0,0,0, // 250
0,0,0,0,0,0,
};
unsigned char realPunctuation[256] = // punctuation characters
{
0,0,0,0,0,0,0,0,0,0, // 10
0,0,0,0,0,0,0,0,0,0, // 20
0,0,0,0,0,0,0,0,0,0, // 30
0,0,0,PUNCTUATIONS,0,0,0,0,0,0, // 40 !
0,0,0 , 0,PUNCTUATIONS, 0,PUNCTUATIONS,0,0,0, // , .
0,0,0,0,0,0,0,0,PUNCTUATIONS,PUNCTUATIONS, // 60 : ;
0,0,0,PUNCTUATIONS,0,0,0,0,0,0, // ?
0,0,0,0,0,0,0,0,0,0, // 80
0,0,0,0,0,0,0,0,0,0, // 90
0,0,0,0,0,0,0,0,0,0, // 100
0,0,0,0,0,0,0,0,0,0, // 110
0,0,0,0,0,0,0,0,0,0, // 120
0,0,0,0,0,0,0,0,0,0, // 130
0,0,0,0,0,0,0,0,0,0, // 140
0,0,0,0,0,0,0,0,0,0, // 150
0,0,0,0,0,0,0,0,0,0, // 160
0,0,0,0,0,0,0,0,0,0, // 170
0,0,0,0,0,0,0,0,0,0, // 180
0,0,0,0,0,0,0,0,0,0, // 190
0,0,0,0,0,0,0,0,0,0, // 200
0,0,0,0,0,0,0,0,0,0, // 210
0,0,0,0,0,0,0,0,0,0, // 220
0,0,0,0,0,0,0,0,0,0, // 230
0,0,0,0,0,0,0,0,0,0, // 240
0,0,0,0,0,0,0,0,0,0, // 250
0,0,0,0,0,0,
};
unsigned char isAlphabeticDigitData[256] = // non-digit number starter (+-.) == 1 isdigit == 2 isupper == 3 islower == 4 isletter >= 3 utf8 == 5
{
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,1,0,0,0, // # and $
0,0,0,VALIDNONDIGIT,0,VALIDNONDIGIT,VALIDNONDIGIT,0,VALIDDIGIT,VALIDDIGIT, VALIDDIGIT,VALIDDIGIT,VALIDDIGIT,VALIDDIGIT,VALIDDIGIT,VALIDDIGIT,VALIDDIGIT,VALIDDIGIT,0,0, // + and . and -
0,0,0,0,0,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,
VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,
VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,VALIDUPPER,
VALIDUPPER,0,0,0,0,0,0,4,4,4,
VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,
VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,VALIDLOWER,
VALIDLOWER,VALIDLOWER,VALIDLOWER,0,0,0,0,0, VALIDUTF8,VALIDUTF8,
VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8, VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,
VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8, VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,
VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8, VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,
VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8, VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,
VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8, VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,
VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8, VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,
VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8,VALIDUTF8
};
unsigned int roman[256] = // values of roman numerals
{
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, //20
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, //40
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, //60
0,0,0,0,0,0,0,100,500,0, 0,0,0,1,0,0,50,1000,0,0, //80 C(67)=100 D(68)=500 I(73)=1 L(76)=50 M(77)=1000
0,0,0,0,0,0,5,0,10,0, 0,0,0,0,0,0,0,0,0,0, //100 V(86)=5 X(88)=10
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,
};
unsigned char isComparatorData[256] = // = < > & ? ! %
{
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, //20
0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,1,0, //40 33=! 38=&
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, //60
1,1,1,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, //80 < = > ?
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, //100
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, //120
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0
};
/////////////////////////////////////////////
// STARTUP
/////////////////////////////////////////////
void InitTextUtilities()
{
memset(utf82extendedascii,0,128);
extendedascii2utf8[0xe1 - 128] = 0x9f; // german fancy ss
for (unsigned int i = 0; i < 128; ++i)
{
unsigned char c = extendedascii2utf8[i];
if (c) c -= 128; // remove top bit
utf82extendedascii[c] = (unsigned char) i;
}
}
void CloseTextUtilities()
{
}
bool IsFraction(char* token)
{
if (IsDigit(token[0])) // fraction?
{
char* at = strchr(token,'/');
if (at)
{
at = token;
while (IsDigit(*++at)) {;}
if (*at == '/')
{
while (IsDigit(*++at)) {;}
if (!*at) return true;
}
}
}
return false;
}
char* RemoveEscapesWeAdded(char* at)
{
if (!at || !*at) return at;
char* startScan = at;
while ((at = strchr(at,'\\'))) // we always add ESCAPE_FLAG backslash
{
if (*(at-1) == ESCAPE_FLAG) // alter the escape in some way
{
if (at[1] == 't') at[1] = '\t'; // legal
else if (at[1] == 'n') at[1] = '\n'; // legal
else if (at[1] == 'r') at[1] = '\r'; // legal
// other choices dont translate, eg double quote
memmove(at-1,at+1,strlen(at)); // remove the escape flag and the escape
}
else ++at; // we dont mark " with ESCAPE_FLAG, we are not protecting it.
}
return startScan;
}
char* CopyRemoveEscapes(char* to, char* at,int limit,bool all) // all includes ones we didnt add as well
{
*to = 0;
char* start = to;
if (!at || !*at) return to;
// need to remove escapes we put there
--at;
while (*++at)
{
if (*at == ESCAPE_FLAG && at[1] == '\\') // we added an escape here
{
at += 2; // move to escaped item
if (*(at-1) == ESCAPE_FLAG) // dual escape is special marker, there is no escaped item
{
*to++ = '\r'; // legal
*to++ = '\n'; // legal
--at; // rescan the item
}
else if (*at == 't') *to++ = '\t'; // legal
else if (*at == 'n') *to++ = '\n'; // legal
else if (*at == 'r') *to++ = '\r'; // legal
else *to++ = *at; // remove our escape pair and pass the item
}
else if (*at == '\\' && all) // remove ALL other escapes in addition to ones we put there
{
++at; // move to escaped item
if (*at == 't') *to++ = '\t';
else if (*at == 'n') *to++ = '\n'; // legal
else if (*at == 'r') *to++ = '\r'; // legal
else {*to++ = *at; } // just pass along untranslated
}
else *to++ = *at;
if ((to-start) >= limit) // too much, kill it
{
*to = 0;
break;
}
}
*to = 0;
return start;
}
void RemoveImpure(char* buffer)
{
char* p;
while ((p = strchr(buffer,'\r'))) *p = ' '; // legal
while ((p = strchr(buffer,'\n'))) *p = ' '; // legal
while ((p = strchr(buffer,'\t'))) *p = ' '; // legal
}
void ChangeSpecial(char* buffer)
{
char* limit;
char* buf = InfiniteStack(limit,"ChangeSpecial");
AddEscapes(buf,buffer,true,MAX_BUFFER_SIZE);
strcpy(buffer,buf);
ReleaseInfiniteStack();
}
char* AddEscapes(char* to, char* from, bool normal,int limit) // normal true means dont flag with extra markers
{
limit -= 200; // dont get close to limit
char* start = to;
char* at = from - 1;
// if we NEED to add an escape, we have to mark it as such so we know to remove them later.
while (*++at)
{
// convert these
if (*at == '\n') { // not expected to see
if (!normal) *to++ = ESCAPE_FLAG;
*to++ = '\\';
*to++ = 'n'; // legal
}
else if (*at == '\r') {// not expected to see
if (!normal) *to++ = ESCAPE_FLAG;
*to++ = '\\';
*to++ = 'r';// legal
}
else if (*at == '\t') {// not expected to see
if (!normal) *to++ = ESCAPE_FLAG;
*to++ = '\\';
*to++ = 't'; // legal
}
else if (*at == '"') { // we need to preserve that it was escaped, though we always escape it in json anyway, because writeuservars needs to know
if (!normal) *to++ = ESCAPE_FLAG;
*to++ = '\\';
*to++ = '"';
}
// detect it is already escaped
else if (*at == '\\')
{
char* at1 = at + 1;
if (*at1 && (*at1 == 'n' || *at1 == 'r' || *at1 == 't' || *at1 == '"' || *at1 == 'u' || *at1 == '\\')) // just pass it along
{
*to++ = *at;
*to++ = *++at;
}
else {
if (!normal) *to++ = ESCAPE_FLAG;
*to++ = '\\';
*to++ = '\\';
}
}
// no escape needed
else *to++ = *at;
if ((to-start) > limit && false) // dont overflow just abort silently
{
ReportBug((char*)"AddEscapes overflowing buffer");
break;
}
}
*to = 0;
return to; // return where we ended
}
void AcquireDefines(char* fileName)
{ // dictionary entries: `xxxx (property names) ``xxxx (systemflag names) ``` (parse flags values) -- and flipped: `nxxxx and ``nnxxxx and ```nnnxxx with infermrak being ptr to original name
FILE* in = FopenStaticReadOnly(fileName); // SRC/dictionarySystem.h
if (!in)
{
printf((char*)"%s",(char*)"Unable to read dictionarySystem.h\r\n");
return;
}
char label[MAX_WORD_SIZE];
char word[MAX_WORD_SIZE];
bool orop = false;
bool shiftop = false;
bool plusop = false;
bool minusop = false;
bool timesop = false;
bool excludeop = false;
int offset = 1;
word[0] = ENDUNIT;
bool endsystem = false;
while (ReadALine(readBuffer, in) >= 0)
{
uint64 result = NOPROBLEM_BIT;
int64 value;
if (!strnicmp(readBuffer,(char*)"// system flags",15)) // end of property flags seen
{
word[1] = ENDUNIT; // system flag words have `` in front
offset = 2;
}
else if (!strnicmp(readBuffer,(char*)"// end system flags",19)) // end of system flags seen
{
offset = 1;
}
else if (!strnicmp(readBuffer,(char*)"// parse flags",14)) // start of parse flags seen
{
word[1] = ENDUNIT; // parse flag words have ``` in front
word[2] = ENDUNIT; // parse flag words have ``` in front
offset = 3;
}
else if (!strnicmp(readBuffer,(char*)"// end parse flags",18)) // end of parse flags seen
{
word[1] = ENDUNIT; // misc flag words have ```` in front and do not xref from number to word
word[2] = ENDUNIT; // misc flag words have ```` in front
word[3] = ENDUNIT; // misc flag words have ```` in front
offset = 4;
endsystem = true;
}
char* ptr = ReadCompiledWord(readBuffer,word+offset);
if (stricmp(word+offset,(char*)"#define")) continue;
// accept lines line #define NAME 0x...
ptr = ReadCompiledWord(ptr,word+offset); // the #define name
if (ptr == 0 || *ptr == 0 || strchr(word+offset,'(')) continue; // if a paren is IMMEDIATELY attached to the name, its a macro, ignore it.
while (ptr) // read value of the define
{
ptr = SkipWhitespace(ptr);
if (ptr == 0) break;
char c = *ptr++;
if (!c) break;
if (c == ')' || c == '/') break; // a form of ending
if (c == '+' && *ptr == ' ') plusop = true;
else if (c == '-' && *ptr == ' ') minusop = true;
else if (c == '*' && *ptr == ' ') timesop = true;
else if (c == '^' && *ptr == ' ') excludeop = true;
else if (IsDigit(c))
{
ptr = (*ptr == 'x' || *ptr == 'X') ? ReadHex(ptr-1,(uint64&)value) : ReadInt64(ptr-1,value);
if (plusop) result += value;
else if (minusop) result -= value;
else if (timesop) result *= value;
else if (excludeop) result ^= value;
else if (orop) result |= value;
else if (shiftop) result <<= value;
else result = value;
excludeop = plusop = minusop = orop = shiftop = timesop = false;
}
else if (c == '('); // start of a (expression in a define, ignore it
else if (c == '|') orop = true;
else if (c == '<') // <<
{
++ptr;
shiftop = true;
}
else // reusing word
{
ptr = ReadCompiledWord(ptr-1,label);
value = FindValueByName(label);
bool olddict = buildDictionary;
buildDictionary = false;
if (!value) value = FindSystemValueByName(label);
if (!value) value = FindMiscValueByName(label);
if (!value) value = FindParseValueByName(label);
buildDictionary = olddict;
if (!value) ReportBug((char*)"missing modifier value for %s\r\n",label)
if (orop) result |= value;
else if (shiftop) result <<= value;
else if (plusop) result += value;
else if (minusop) result -= value;
else if (timesop) result *= value;
else if (excludeop) result ^= value;
else result = value;
excludeop = plusop = minusop = orop = shiftop = timesop = false;
}
}
WORDP D = StoreWord(word,AS_IS | result);
AddInternalFlag(D,DEFINES);
#ifdef WIN32
sprintf(word+offset,(char*)"%I64d",result);
#else
sprintf(word+offset,(char*)"%lld",result);
#endif
if (!endsystem) // cross ref from number to value only for properties and system flags and parsemarks for decoding bits back to words for marking
{
WORDP E = StoreWord(word);
AddInternalFlag(E,DEFINES);
if (!E->inferMark) E->inferMark = MakeMeaning(D); // if number value NOT already defined, use this definition
}
}
FClose(in);
}
void AcquirePosMeanings()
{
// create pos meanings and sets
// if (buildDictionary) return; // dont add these into dictionary
uint64 bit = START_BIT;
char name[MAX_WORD_SIZE];
*name = '~';
MEANING pos = MakeMeaning(StoreWord((char*)"~pos"));
MEANING sys = MakeMeaning(StoreWord((char*)"~sys"));
for (int i = 63; i >= 0; --i) // properties get named concepts
{
char* word = FindNameByValue(bit);
if (word)
{
MakeLowerCopy(name+1,word); // all pos names start with `
posMeanings[i] = MakeMeaning(BUILDCONCEPT(name));
CreateFact(posMeanings[i],Mmember,pos);
}
word = FindSystemNameByValue(bit);
if (word)
{
MakeLowerCopy(name+1,word); // all sys names start with ``
sysMeanings[i] = MakeMeaning(BUILDCONCEPT(name));
CreateFact(sysMeanings[i],Mmember,sys);
}
bit >>= 1;
}
MEANING M = MakeMeaning(BUILDCONCEPT((char*)"~aux_verb"));
CreateFact(M,Mmember,pos);
CreateFact(MakeMeaning(StoreWord((char*)"~aux_verb_future")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~aux_verb_past")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~aux_verb_present")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~aux_be")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~aux_have")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~aux_do")),Mmember,M);
M = MakeMeaning(BUILDCONCEPT((char*)"~aux_verb_tenses"));
CreateFact(M,Mmember,pos);
CreateFact(MakeMeaning(StoreWord((char*)"~aux_verb_future")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~aux_verb_past")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~aux_verb_present")),Mmember,M);
M = MakeMeaning(BUILDCONCEPT((char*)"~conjunction"));
CreateFact(M,Mmember,pos);
CreateFact(MakeMeaning(StoreWord((char*)"~conjunction_subordinate")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~conjunction_coordinate")),Mmember,M);
M = MakeMeaning(BUILDCONCEPT((char*)"~determiner_bits"));
CreateFact(M,Mmember,pos);
CreateFact(MakeMeaning(StoreWord((char*)"~determiner")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~predeterminer")),Mmember,M);
M = MakeMeaning(BUILDCONCEPT((char*)"~possessive_bits"));
CreateFact(M,Mmember,pos);
CreateFact(MakeMeaning(StoreWord((char*)"~possessive")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~pronoun_possessive")),Mmember,M);
M = MakeMeaning(BUILDCONCEPT((char*)"~noun_bits"));
CreateFact(M,Mmember,pos);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_singular")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_plural")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_proper_singular")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_proper_plural")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_number")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_adjective")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_gerund")),Mmember,M);
// CreateFact(MakeMeaning(FindWord((char*)"~noun_infinitive")),Mmember,M);
M = MakeMeaning(BUILDCONCEPT((char*)"~normal_noun_bits"));
CreateFact(M,Mmember,pos);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_singular")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_plural")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_proper_singular")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~noun_proper_plural")),Mmember,M);
M = MakeMeaning(BUILDCONCEPT((char*)"~pronoun_bits"));
CreateFact(M,Mmember,pos);
CreateFact(MakeMeaning(StoreWord((char*)"~pronoun_subject")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~pronoun_object")),Mmember,M);
M = MakeMeaning(BUILDCONCEPT((char*)"~verb_bits"));
CreateFact(M,Mmember,pos);
CreateFact(MakeMeaning(StoreWord((char*)"~verb_infinitive")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~verb_present")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~verb_present_3ps")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~verb_past")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~verb_past_participle")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~verb_present_participle")),Mmember,M);
M = MakeMeaning(BUILDCONCEPT((char*)"~punctuation"));
CreateFact(M,Mmember,pos);
CreateFact(MakeMeaning(StoreWord((char*)"~paren")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~comma")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~quote")),Mmember,M);
CreateFact(MakeMeaning(StoreWord((char*)"~currency")),Mmember,M);
MEANING role = MakeMeaning(BUILDCONCEPT((char*)"~grammar_role"));
unsigned int i = 0;
char* ptr;
while ((ptr = roleSets[i++]) != 0)
{
M = MakeMeaning(BUILDCONCEPT(ptr));
CreateFact(M,Mmember,role);
}
}
uint64 FindValueByName(char* name)
{
if (!*name || *name == '?') return 0; // ? is the default argument to call
char word[MAX_WORD_SIZE];
word[0] = ENDUNIT;
MakeUpperCopy(word+1,name);
WORDP D = FindWord(word);
if (!D|| !(D->internalBits & DEFINES)) return 0;
return D->properties;
}
char* FindNameByValue(uint64 val) // works for invertable pos bits only
{
char word[MAX_WORD_SIZE];
word[0] = ENDUNIT;
#ifdef WIN32
sprintf(word+1,(char*)"%I64d",val);
#else
sprintf(word+1,(char*)"%lld",val);
#endif
WORDP D = FindWord(word);
if (!D || !(D->internalBits & DEFINES)) return 0;
D = Meaning2Word(D->inferMark);
return D->word+1;
}
uint64 FindSystemValueByName(char* name)
{
if (!*name || *name == '?') return 0; // ? is the default argument to call
char word[MAX_WORD_SIZE];
word[0] = ENDUNIT;
word[1] = ENDUNIT;
MakeUpperCopy(word+2,name);
WORDP D = FindWord(word);
if (!D || !(D->internalBits & DEFINES))
{
if (buildDictionary)
ReportBug((char*)"Failed to find system value %s",name);
return 0;
}
return D->properties;
}
char* FindSystemNameByValue(uint64 val) // works for invertable system bits only
{
char word[MAX_WORD_SIZE];
word[0] = ENDUNIT;
word[1] = ENDUNIT;
#ifdef WIN32
sprintf(word+2,(char*)"%I64d",val);
#else
sprintf(word+2,(char*)"%lld",val);
#endif
WORDP D = FindWord(word);
if (!D || !(D->internalBits & DEFINES)) return 0;
return Meaning2Word(D->inferMark)->word+2;
}
char* FindParseNameByValue(uint64 val)
{
char word[MAX_WORD_SIZE];
word[0] = ENDUNIT;
word[1] = ENDUNIT;
word[2] = ENDUNIT;
#ifdef WIN32
sprintf(word+3,(char*)"%I64d",val);
#else
sprintf(word+3,(char*)"%lld",val);
#endif
WORDP D = FindWord(word);
if (!D || !(D->internalBits & DEFINES)) return 0;
return Meaning2Word(D->inferMark)->word+3;
}
uint64 FindParseValueByName(char* name)
{
if (!*name || *name == '?') return 0; // ? is the default argument to call
char word[MAX_WORD_SIZE];
word[0] = ENDUNIT;
word[1] = ENDUNIT;
word[2] = ENDUNIT;
MakeUpperCopy(word+3,name);
WORDP D = FindWord(word);
if (!D || !(D->internalBits & DEFINES))
{
if (buildDictionary) ReportBug((char*)"Failed to find parse value %s",name);
return 0;
}
return D->properties;
}
uint64 FindMiscValueByName(char* name)
{
if (!*name || *name == '?') return 0; // ? is the default argument to call
char word[MAX_WORD_SIZE];
word[0] = ENDUNIT;
word[1] = ENDUNIT;
word[2] = ENDUNIT;
word[3] = ENDUNIT;
MakeUpperCopy(word+4,name);
WORDP D = FindWord(word);
if (!D || !(D->internalBits & DEFINES))
{
if (buildDictionary) ReportBug((char*)"Failed to find misc value %s",name);
return 0;
}
return D->properties;
}
/////////////////////////////////////////////
// BOOLEAN-STYLE QUESTIONS
/////////////////////////////////////////////
bool IsArithmeticOperator(char* word)
{
word = SkipWhitespace(word);
char c = *word;
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '&')
{
if (IsDigit(word[1]) || word[1] == ' ' || word[1] == '=') return true;
return false;
}
return
((c == '|' && (word[1] == ' ' || word[1] == '^' || word[1] == '=')) ||
(c == '%' && !word[1]) ||
(c == '%' && word[1] == ' ') ||
(c == '%' && word[1] == '=') ||
(c == '^' && !word[1]) ||
(c == '^' && word[1] == ' ') ||
(c == '^' && word[1] == '=') ||
(c == '<' && word[1] == '<') ||
(c == '>' && word[1] == '>')
);
}
char* IsUTF8(char* buffer,char* character) // swallow a single utf8 character (ptr past it) or return null
{
*character = *buffer;
character[1] = 0; // simple ascii character
if (*buffer == 0) return buffer; // dont walk past end
if (((unsigned char)*buffer) < 127) return buffer+1; // not utf8
char* start = buffer;
unsigned int count = UTFCharSize(buffer) - 1; // bytes beyond first
if (count == 0) count = 300; // not real?
// does count of extenders match requested count
unsigned int n = 0;
while (*++buffer && *(unsigned char*) buffer >= 128 && *(unsigned char*) buffer <= 191) ++n;
if (n == count)
{
strncpy(character,start,count+1);
character[count+1] = 0;
return buffer;
}
return start+1;
}
char GetTemperatureLetter(char* ptr)
{
if (!ptr || !ptr[1] || !IsDigit(*ptr)) return 0; // format must be like 1C or 19F
size_t len = strlen(ptr) - 1;
char lastc = GetUppercaseData(ptr[len]);
if (lastc == 'F' || lastc == 'C' || lastc == 'K') // ends in a temp letter
{
// prove rest of prefix is a number
char* p = ptr-1;
while (IsDigit(*++p)); // find end of number prefix
if (len == (size_t)(p - ptr)) return lastc;
}
return 0;
}
unsigned char* GetCurrency(unsigned char* ptr,char* &number) // does this point to a currency token, return currency and point to number (NOT PROVEN its a number)
{
if (*ptr == '$') // dollar is prefix
{
number = ( char*)ptr+1;
return ptr;
}
else if (*ptr == 0xe2 && ptr[1] == 0x82 && ptr[2] == 0xac) // euro is prefix
{
number = ( char*)ptr + 3;
return ptr;
}
else if (*ptr == 0xc2) // yen is prefix
{
char c = ptr[1];
if ( c == 0xa2 || c == 0xa3 || c == 0xa4 || c == 0xa5)
{
number = ( char*)ptr+2;
return ptr;
}
}
else if (*ptr == 0xc3 && ptr[1] == 0xb1 ) // british pound
{
number = ( char*)ptr+2;
return ptr;
}
else if (!strnicmp((char*)ptr,(char*)"yen",3) || !strnicmp((char*)ptr,(char*)"eur",3) || !strnicmp((char*)ptr,(char*)"inr",3) ||!strnicmp((char*)ptr,(char*)"usd",3) || !strnicmp((char*)ptr,(char*)"gbp",3) || !strnicmp((char*)ptr,(char*)"cny",3))
{
number = ( char*)ptr + 3;
return ptr;
}
if (IsDigit(*ptr)) // number first
{
unsigned char* at = ptr;
while (IsDigit(*at) || *at == '.') ++at; // get end of number
if (*at == '$' || (*at == 0xe2 && at[1] == 0x82 && at[2] == 0xac) || *at == 0xc2 || (*at == 0xc3 && at[1] == 0xb1 )
|| !strnicmp((char*)at,(char*)"yen",3) || !strnicmp((char*)at,(char*)"inr",3) || !strnicmp((char*)at,(char*)"eur",3) || !strnicmp((char*)at,(char*)"usd",3) || !strnicmp((char*)at,(char*)"gbp",3) || !strnicmp((char*)at,(char*)"cny",3)) // currency suffix
{
number = ( char*)ptr;
return at;
}
}
return 0;
}
bool IsLegalName(char* name) // start alpha (or ~) and be alpha _ digit (concepts and topics can use . or - also)
{
char start = *name;
if (*name == '~' || *name == SYSVAR_PREFIX) ++name;
if (!IsAlphaUTF8(*name) ) return false;
while (*++name)
{
if (*name == '.' && start != '~') return false; // may not use . in a variable name
if (!IsLegalNameCharacter(*name)) return false;
}
return true;
}
bool IsDigitWithNumberSuffix(char* number)
{
size_t len = strlen(number);
char d = number[len-1];
bool num = false;
if (d == 'k' || d == 'K' || d == 'm' || d == 'M' || d == 'B' || d == 'b' || d == 'G' || d == 'g' || d == '$')
{
number[len-1] = 0;
num = IsDigitWord(number);
number[len-1] = d;
}
return num;
}
bool IsDigitWord(char* ptr,bool comma) // digitized number
{
// signing, # marker or currency markers are still numbers
if (IsNonDigitNumberStarter(*ptr)) ++ptr; // skip numeric nondigit header (+ - # )
char* number = 0;
char* currency = 0;
if ((currency = ( char*)GetCurrency((unsigned char*) ptr,number))) ptr = number; // if currency, find number start of it
if (!*ptr) return false;
bool foundDigit = false;
int periods = 0;
while (*ptr)
{
if (IsDigit(*ptr)) foundDigit = true; // we found SOME part of a number
else if (*ptr == '.')
{
if (++periods > 1) return false; // too many periods
}
else if (*ptr == '%' && !ptr[1]) break; // percentage
else if (*ptr == ':'); // TIME delimiter
else if (*ptr == ',' && comma); // allow comma
else if (ptr == currency) break; // dont need to see currency end
else return false; // 1800s is done by substitute, so fail this
++ptr;
}
return foundDigit;
}
bool IsRomanNumeral(char* word, uint64& val)
{
if (*word == 'I' && !word[1]) return false; // BUG cannot accept I for now. too confusing.
val = 0;
--word;
unsigned int value;
unsigned int oldvalue = 100000;
while ((value = roman[(unsigned char)*++word]))
{
if (value > oldvalue) // subtractive?
{
// I can be placed before V and X to make 4 units (IV) and 9 units (IX) respectively
// X can be placed before L and C to make 40 (XL) and 90 (XC) respectively
// C can be placed before D and M to make 400 (CD) and 900 (CM) according to the same pattern[5]
if (value == 5 && oldvalue == 1) val += (value - 2);
else if (value == 10 && oldvalue == 1) val += (value - 2);
else if (value == 50 && oldvalue == 10) val += (value - 20);
else if (value == 100 && oldvalue == 10) val += (value - 20);
else if (value == 500 && oldvalue == 100) val += (value - 200);
else if (value == 1000 && oldvalue == 100) val += (value - 200);
else return false; // not legal
}
else val += value;
oldvalue = value;
}
return (!*word); // finished or not
}
void ComputeWordData(char* word, WORDINFO* info) // how many characters in word
{
memset(info, 0, sizeof(WORDINFO));
info->word = word;
int n = 0;
char utfcharacter[10];
while (*word)
{
char* x = IsUTF8(word, utfcharacter); // return after this character if it is valid.
++n;
if (utfcharacter[1]) // utf8 char
{
word = x;
++info->charlen;
info->bytelen += (x - word);
}
else // normal ascii
{
++info->charlen;
++info->bytelen;
++word;
}
}
}
unsigned int IsNumber(char* num,bool placeAllowed) // simple digit number or word number or currency number
{
if (!*num) return false;
char word[MAX_WORD_SIZE];
MakeLowerCopy(word,num); // accept number words in upper case as well
if (word[1] && (word[1] == ':' || word[2] == ':')) return false; // 05:00 // time not allowed
char* number = NULL;
char* cur = (char*)GetCurrency((unsigned char*) word,number);
if (cur)
{
char c = *cur;
*cur = 0;
char* at = strchr(number,'.');
if (at) *at = 0;
int64 val = Convert2Integer(number);
if (at) *at = '.';
*cur = c;
return (val != NOT_A_NUMBER) ? CURRENCY_NUMBER : 0 ;
}
if (IsDigitWord(word)) return DIGIT_NUMBER; // a numeric number
if (*word == '#' && IsDigitWord(word+1)) return DIGIT_NUMBER; // #123
if (*word == '\'' && !strchr(word+1,'\'') && IsDigitWord(word+1)) return DIGIT_NUMBER; // includes date and feet
uint64 valx;
if (IsRomanNumeral(word,valx)) return ROMAN_NUMBER;
if (IsDigitWithNumberSuffix(word)) return WORD_NUMBER;
// word fraction numbers
if (!strcmp(word,(char*)"half") ) return FRACTION_NUMBER;
else if (!strcmp(word,(char*)"third") ) return FRACTION_NUMBER;
else if (!strcmp(word,(char*)"thirds") ) return FRACTION_NUMBER;
else if ( !strcmp(word,(char*)"quarter") ) return FRACTION_NUMBER;
else if ( !strcmp(word,(char*)"quarters") ) return FRACTION_NUMBER;
WORDP D;
char* ptr;
if (placeAllowed && IsPlaceNumber(word)) return PLACETYPE_NUMBER; // th or first or second etc. but dont call if came from there
else if (!IsDigit(*word) && ((ptr = strchr(word+1,'-')) || (ptr = strchr(word+1,'_')))) // composite number as word, but not digits
{
D = FindWord(word,ptr-word); // 1st part
WORDP W = FindWord(ptr+1); // 2nd part of word
if (D && W && D->properties & NUMBER_BITS && W->properties & NUMBER_BITS && IsPlaceNumber(W->word)) return FRACTION_NUMBER;
if (D && W && D->properties & NUMBER_BITS && W->properties & NUMBER_BITS) return WORD_NUMBER;
}
char* hyphen = strchr(word+1,'-');
if (!hyphen) hyphen = strchr(word+1,'_'); // two_thirds
if (hyphen && hyphen[1])
{
char c = *hyphen;
*hyphen = 0;
int kind = IsNumber(word); // what kind of number
int64 piece1 = Convert2Integer(word);
*hyphen = c;
if (piece1 == NOT_A_NUMBER && stricmp(word,(char*)"zero") && *word != '0') {;}
else if (IsPlaceNumber(hyphen+1) || kind == FRACTION_NUMBER) return FRACTION_NUMBER;
}
// test for fraction or percentage
bool slash = false;
bool percent = false;
if (IsDigit(*word)) // see if all digits now.
{
char* ptr = word;
while (*++ptr)
{
if (*ptr == '/' && !slash) slash = true;
else if (*ptr == '%' && !ptr[1]) percent = true;
else if (!IsDigit(*ptr)) break; // not good
}
if (slash && !*ptr) return FRACTION_NUMBER;
if (percent && !*ptr) return FRACTION_NUMBER;
}
D = FindWord(word);
if (D && D->properties & NUMBER_BITS)
return (D->systemFlags & ORDINAL) ? PLACETYPE_NUMBER : WORD_NUMBER; // known number
return (Convert2Integer(word) != NOT_A_NUMBER) ? WORD_NUMBER : 0; // try to read the number
}
bool IsPlaceNumber(char* word) // place number and fraction numbers
{
size_t len = strlen(word);
if (len < 3) return false; // min is 1st
// word place numbers
if (len > 4 && !strcmp(word+len-5,(char*)"first") ) return true;
else if (len > 5 && !strcmp(word+len-6,(char*)"second") ) return true;
else if (len > 4 && !strcmp(word+len-5,(char*)"third") ) return true;
else if (len > 4 && !strcmp(word+len-5,(char*)"fifth") ) return true;
// does it have proper endings?
if (word[len-2] == 's' && word[len-1] == 't') {;} // 1st
else if (word[len-2] == 'n' && word[len-1] == 'd') // 2nd
{
if (!stricmp(word,(char*)"thousand")) return false; // 2nd but not thousand
}
else if (word[len-1] == 'd') // 3rd
{
if (word[len-2] != 'r') return false; // 3rd is ok
}
else if (word[len-2] == 't' && word[len-1] == 'h') {;} // 4th
else if (word[len-3] == 't' && word[len-2] == 'h' && word[len-1] == 's') {;} // 4ths
else return false; // no place suffix
if (strchr(word,'_')) return false; // cannot be place number
// separator?
if (word[len-3] == '\'' || word[len-3] == '-') {;}// 24'th or 24-th
else if (strchr(word,'-')) return false; // cannot be place number
if (len < 4 && !IsDigit(*word)) return false; // want a number
char num[MAX_WORD_SIZE];
strcpy(num,word);
return IsNumber(num,false) ? true : false; // show it is correctly a number - pass false to avoid recursion from IsNumber
}
bool IsFloat(char* word, char* end)
{
if (*word == '-' || *word == '+') ++word; // ignore sign
int period = 0;
--word;
while (++word < end) // count periods
{
if (*word == '.') ++period;
else if (!IsDigit(*word)) return false; // non digit is fatal
}
return (period == 1);
}
bool IsNumericDate(char* word,char* end) // 01.02.2009 or 1.02.2009 or 1.2.2009
{ // 3 pieces separated by periods or slashes. with 1 or 2 digits in two pieces and 2 or 4 pieces in last piece
char separator = 0;
int counter = 0;
int piece = 0;
int size[100];
memset(size,0, sizeof(size));
--word;
while (++word < end)
{
char c = *word;
if (IsDigit(c)) ++counter;
else if (c == '.' || c == '/') // date separator
{
if (!counter) return false; // no piece before it
size[piece++] = counter; // how big was the piece
counter = 0;
if (!separator) separator = c; // seeing this kind of separator
if (c != separator) return false; // cannot mix
if (!IsDigit(word[1])) return false; // doesnt continue with digits
}
else return false; // illegal date
}
if (piece != 2) return false; // incorrect piece count
if (size[0] != 4)
{
if (size[2] != 4 || size[0] > 2 || size[1] > 2) return false;
}
else if (size[1] > 2 || size[2] > 2) return false;
return true;
}
bool IsUrl(char* word, char* end)
{ // if (!strnicmp(t+1,(char*)"co.",3)) // jump to accepting country
if (*word == '@') return false;
if (!strnicmp((char*)"www.",word,4) || !strnicmp((char*)"http",word,4) || !strnicmp((char*)"ftp:",word,4))
{
char* colon = strchr(word,':');
if (colon && (colon[1] != '/' || colon[2] != '/')) return false;
return true; // classic urls
}
size_t len = strlen(word);
if (len > 200) return false;
char tmp[MAX_WORD_SIZE];
MakeLowerCopy(tmp,word);
if (!end) end = word + len;
tmp[end-word] = 0;
char* ptr = tmp;
char* firstPeriod = 0;
int n = 0;
while (ptr && *ptr) // count periods
{
if ((ptr = strchr(ptr+1,'.')))
{
if (!firstPeriod) firstPeriod = ptr;
++ptr;
++n;
}
}
if (n == 0) return false; // not possible
if (n > 0) // check for email
{
char* at = strchr(tmp,'@');
if (at)
{
char* dot = strchr(at+2,'.'); // must have character after @ and before .
if (dot && IsAlphaUTF8(dot[1])) return true;
}
}
if (n < 3) return false; // has none or only 1 or 2
if (n == 3) return true; // exactly 3 a std url
// check suffix since possible 4 part url: www.amazon.co.uk OR 1 parter like amazon.com or other --- also 2 dot urls including amazon.com and fireze.it
ptr = strrchr(tmp,'.'); // last period - KNOWN to exist
if (!ptr) return false; // stops compiler warning
if (IsAlphaUTF8(ptr[1]) && IsAlphaUTF8(ptr[2]) && !ptr[3]) return true; // country code at end?
if ((ptr-word) >= 3 && ptr && *(ptr-3) == 'c' && (*ptr-2) == 'o') return true; // another form of country code
++ptr;
return (!strnicmp(ptr,(char*)"com",3) || !strnicmp(ptr,(char*)"net",3) || !strnicmp(ptr,(char*)"org",3) || !strnicmp(ptr,(char*)"edu",3) || !strnicmp(ptr,(char*)"biz",3) || !strnicmp(ptr,(char*)"gov",3) || !strnicmp(ptr,(char*)"mil",3)); // common suffixes
}
unsigned int IsMadeOfInitials(char * word,char* end)
{
if (IsDigit(*word)) return 0; // it's a number
char* ptr = word-1;
while (++ptr < end) // check for alternating character and periods
{
if (!IsAlphaUTF8OrDigit(*ptr)) return false;
if (*++ptr != '.') return false;
}
if (ptr >= end) return ABBREVIATION; // alternates letter and period perfectly (abbreviation or middle initial)
// if lower case start and upper later, it's a typo. Call it a shout (will lower case if we dont know as upper)
ptr = word-1;
if (IsLowerCase(*word))
{
while (++ptr != end)
{
if (IsUpperCase(*ptr)) return SHOUT;
}
return 0;
}
// ALL CAPS
while (++ptr != end)
{
if (!IsUpperCase(*ptr)) return 0;
}
// its all caps, needs to be lower cased
WORDP D = FindWord(word);
if (D) // see if there are any legal allcaps forms
{
WORDP set[20];
int n = GetWords(word,set,true);
while (n)
{
WORDP X = set[--n];
if (!strcmp(word,X->word)) return 0; // we know it in all caps format
}
}
return (D && D->properties & (NOUN_PROPER_SINGULAR|NOUN_PROPER_PLURAL)) ? ABBREVIATION : SHOUT;
}
////////////////////////////////////////////////////////////////////
/// READING ROUTINES
////////////////////////////////////////////////////////////////////
char* ReadFlags(char* ptr,uint64& flags,bool &bad, bool &response)
{
flags = 0;
response = false;
char* start = ptr;
if (!*ptr) return start;
if (*ptr != '(') // simple solo flag
{
char word[MAX_WORD_SIZE];
ptr = ReadCompiledWord(ptr,word);
if (!strnicmp(word,(char*)"RESPONSE_",9)) response = true; // saw a response flag
if (IsDigit(*word) || *word == 'x') ReadInt64(word,(int64&)flags);
else
{
flags = FindValueByName(word);
if (!flags) flags = FindSystemValueByName(word);
if (!flags) flags = FindMiscValueByName(word);
if (!flags) bad = true;
}
return (!flags && !IsDigit(*word) && !response) ? start : ptr; // if found nothing return start, else return end
}
char flag[MAX_WORD_SIZE];
char* close = strchr(ptr,')');
if (close) *close = 0;
while (*ptr) // read each flag
{
FunctionResult result;
ptr = ReadShortCommandArg(ptr,flag,result); // swallows excess )
if (result & ENDCODES) return ptr;
if (*flag == '(') continue; // starter
if (*flag == USERVAR_PREFIX) flags |= atoi(GetUserVariable(flag)); // user variable indirect
else if (*flag == '0' && (flag[1] == 'x' || flag[1] == 'X')) // literal hex value
{
uint64 val;
ptr = ReadHex(flag,val);
flags |= val;
}
else if (IsDigit(*flag)) flags |= atoi(flag);
else // simple name of flag
{
uint64 n = FindValueByName(flag);
if (!n) n = FindSystemValueByName(flag);
if (!n) n = FindMiscValueByName(flag);
if (!n) bad = true;
flags |= n;
}
ptr = SkipWhitespace(ptr);
}
if (close)
{
*close = ')';
ptr = SkipWhitespace(close + 1);
}
return (!flags) ? start : ptr;
}
char* ReadInt(char* ptr, int &value)
{
ptr = SkipWhitespace(ptr);
value = 0;
if (!ptr || !*ptr ) return ptr;
if (*ptr == '0' && (ptr[1]== 'x' || ptr[1] == 'X')) // hex number
{
uint64 val;
ptr = ReadHex(ptr,val);
value = (int)val;
return ptr;
}
char* original = ptr;
int sign = 1;
if (*ptr == '-')
{
sign = -1;
++ptr;
}
--ptr;
while (!IsWhiteSpace(*++ptr) && *ptr) // find end of synset id in dictionary
{
if (*ptr == ',') continue; // swallow this
value *= 10;
if (IsDigit(*ptr)) value += *ptr - '0';
else
{
ReportBug((char*)"bad number %s\r\n",original)
while (*++ptr && *ptr != ' ');
value = 0;
return ptr;
}
}
value *= sign;
if (*ptr) ++ptr; // skip trailing blank
return ptr;
}
int64 atoi64(char* ptr )
{
int64 spot;
ReadInt64(ptr,spot);
return spot;
}
char* ReadInt64(char* ptr, int64 &spot)
{
ptr = SkipWhitespace(ptr);
spot = 0;
if (!ptr || !*ptr) return ptr;
if (*ptr == 'x' ) return ReadHex(ptr,(uint64&)spot);
if (*ptr == '0' && (ptr[1]== 'x' || ptr[1] == 'X')) return ReadHex(ptr,(uint64&)spot);
char* original = ptr;
int sign = 1;
if (*ptr == '-')
{
sign = -1;
++ptr;
}
--ptr;
while (!IsWhiteSpace(*++ptr) && *ptr)
{
if (*ptr == ',') continue; // swallow this
spot *= 10;
if (IsDigit(*ptr)) spot += *ptr - '0';
else
{
ReportBug((char*)"bad number1 %s\r\n",original)
while (*++ptr && *ptr != ' ');
spot = 0;
return ptr;
}
}
spot *= sign;
if (*ptr) ++ptr; // skip trailing blank
return ptr;
}
char* ReadHex(char* ptr, uint64 & value)
{
ptr = SkipWhitespace(ptr);
value = 0;
if (!ptr || !*ptr) return ptr;
if (ptr[0] == 'x') ++ptr; // skip x
else if (ptr[1] == 'x' || ptr[1] == 'X') ptr += 2; // skip 0x
--ptr;
while (*++ptr)
{
char c = GetLowercaseData(*ptr);
if (c == 'l' || c == 'u') continue; // assuming L or LL or UL or ULL at end of hex
if (!IsAlphaUTF8OrDigit(c) || c > 'f') break; // no useful characters after lower case at end of range
value <<= 4; // move over a digit
value += (IsDigit(c))? (c - '0') : (10 + c - 'a');
}
if (*ptr) ++ptr;// align past trailing space
return ptr;
}
void BOMAccess(int &BOMvalue, char &oldc, int &oldCurrentLine) // used to get/set file access- -1 BOMValue gets, other sets all
{
if (BOMvalue >= 0) // set back
{
BOM = BOMvalue;
holdc = oldc;
maxFileLine = currentFileLine = oldCurrentLine;
}
else // get copy and reinit for new file
{
BOMvalue = BOM;
BOM = NOBOM;
oldc = holdc;
holdc = 0;
oldCurrentLine = currentFileLine;
maxFileLine = currentFileLine = 0;
}
}
#define NOT_IN_FORMAT_STRING 0
#define IN_FORMAT_STRING 1
#define IN_FORMAT_CONTINUATIONLINE 2
#define IN_FORMAT_COMMENT 3
static bool ConditionalReadRejected(char* start,char*& buffer,bool revise)
{
char word[MAX_WORD_SIZE];
if (!compiling) return false;
char* at = ReadCompiledWord(start,word);
if (!stricmp(word,"ifdef") || !stricmp(word,"ifndef") || !stricmp(word,"define")) return false;
if (!stricmp(word,"endif") || !stricmp(word,"include") ) return false;
// a matching language declaration?
if (!stricmp(language,word))
{
if (revise)
{
memmove(start-1,at, strlen(at)+1); // erase comment marker
buffer = start + strlen(start);
}
return false; // allowed
}
// could it be a constant?
uint64 n = FindValueByName(word);
if (!n) n = FindSystemValueByName(word);
if (!n) n = FindParseValueByName(word);
if (!n) n = FindMiscValueByName(word);
if (n) return false; // valid constant
for (int i = 0; i < conditionalCompiledIndex; ++i)
{
if (!stricmp(conditionalCompile[i]+1,word))
{
if (revise)
{
memmove(start-1,at, strlen(at)+1); // erase comment marker
buffer = start + strlen(start);
}
return false; // allowed
}
}
return true; // reject this line
}
bool AdjustUTF8(char* start,char* buffer)
{
bool hasbadutf = false;
while (*++buffer) // check every utf character
{
if (*buffer & 0x80) // is utf in theory
{
char prior = (start == buffer) ? 0 : *(buffer - 1);
char utfcharacter[10];
char* x = IsUTF8(buffer, utfcharacter); // return after this character if it is valid.
if (utfcharacter[1]) // rewrite some utf8 characters to std ascii
{
if (buffer[0] == 0xc2 && buffer[1] == 0xb4) // a form of '
{
*buffer = '\'';
memmove(buffer + 1, x, strlen(x) + 1);
x = buffer + 1;
}
else if (buffer[0] == 0xe2 && buffer[1] == 0x80 && buffer[2] == 0x98) // open single quote
{
// if attached to punctuation, leave it so it will tokenize with them
*buffer = ' ';
buffer[1] = '\'';
buffer[2] = ' ';
}
else if (buffer[0] == 0xe2 && buffer[1] == 0x80 && buffer[2] == 0x99) // closing single quote (may be embedded or acting as a quoted expression
{
if (buffer != start && IsAlphaUTF8(*(buffer - 1)) && IsAlphaUTF8(*x)) // embedded contraction
{
*buffer = '\'';
memmove(buffer + 1, x, strlen(x) + 1);
x = buffer + 1;
}
else if (prior == 's' && !IsAlphaUTF8(*x)) // ending possessive
{
*buffer = '\'';
memmove(buffer + 1, x, strlen(x) + 1);
x = buffer + 1;
}
else if (prior == '.' || prior == '?' || prior == '!') // leave attached to prior so readdocument can leave them together
{
*buffer = '\'';
buffer[1] = ' ';
buffer[2] = ' ';
}
else
{
*buffer = ' ';
buffer[1] = '\'';
buffer[2] = ' ';
}
}
else if (buffer[0] == 0xe2 && buffer[1] == 0x80 && buffer[2] == 0x9c) // open double quote
{
*buffer = '\'';
memmove(buffer + 1, x, strlen(x) + 1);
}
else if (buffer[0] == 0xe2 && buffer[1] == 0x80 && buffer[2] == 0x9d) // closing double quote
{
*buffer = '"';
memmove(buffer + 1, x, strlen(x) + 1);
}
else if (buffer[0] == 0xe2 && buffer[1] == 0x80 && buffer[2] == 0x94 && !(tokenControl & NO_FIX_UTF) && !compiling) // mdash
{
*buffer = '-';
}
else if (buffer[0] == 0xe2 && buffer[1] == 0x80 && (buffer[2] == 0x94 || buffer[2] == 0x93) && !(tokenControl & NO_FIX_UTF) && !compiling) // mdash
{
*buffer = '-';
memmove(buffer + 1, x, strlen(x) + 1);
}
buffer = x - 1; // valid utf8
}
else // invalid utf8
{
hasbadutf = true;
*buffer = 'z'; // replace with legal char
}
}
}
return hasbadutf;
}
int ReadALine(char* buffer,FILE* in,unsigned int limit,bool returnEmptyLines,bool convertTabs)
{ // reads text line stripping of cr/nl
currentFileLine = maxFileLine; // revert to best seen
if (currentFileLine == 0) BOM = (BOM == BOMSET) ? BOMUTF8 : NOBOM; // start of file, set BOM to null
*buffer = 0;
buffer[1] = 0;
buffer[2] = 1;
if (in == (FILE*) -1)
{
return 0;
}
if (!in && !userRecordSourceBuffer)
{
buffer[1] = 0;
buffer[2] = 0; // clear ahead to make it obvious we are at end when debugging
return -1; // neither file nor buffer being read
}
int formatString = NOT_IN_FORMAT_STRING;
char ender = 0;
char* start = buffer;
char c = 0;
if (holdc) // if we had a leftover character from prior line lacking newline, put it in now
{
*buffer++ = holdc;
holdc = 0;
}
bool hasutf = false;
bool hasbadutf = false;
bool runningOut = false;
bool endingBlockComment = false;
RESUME:
while (ALWAYS)
{
if (in)
{
if (!fread(&c,1,1,in))
{
++currentFileLine; // for debugging error messages
maxFileLine = currentFileLine;
break; // EOF
}
}
else
{
c = *userRecordSourceBuffer++;
if (!c)
break; // end of buffer
}
if (c == '\t' && convertTabs) c = ' ';
if (c & 0x80) // high order utf?
{
unsigned char convert = 0;
if (!BOM && !hasutf && !server) // local mode might get extended ansi so transcribe to utf8
{
unsigned char x = (unsigned char) c;
if (x == 147 || x == 148) convert = c = '"';
else if (x == 145 || x == 146) convert = c = '\'';
else if (x == 150 || x == 151) convert = c = '-';
else
{
convert = extendedascii2utf8[x - 128];
if (convert)
{
*buffer++ = (unsigned char) 0xc3;
c = convert;
}
}
}
if (!convert) hasutf = true;
}
// format string stuff
if (formatString)
{
if (formatString == IN_FORMAT_COMMENT && c != '\r' && c != '\n') continue; // flush comment
// format string
else if (formatString && c == ender && *(buffer-1) != '\\')
formatString = NOT_IN_FORMAT_STRING; // end format string
else if (formatString == IN_FORMAT_CONTINUATIONLINE)
{
if (c == ' ' || c == '\t') continue; // ignore white space leading the line
formatString = IN_FORMAT_STRING;
}
else if (formatString && formatString != IN_FORMAT_COMMENT && *(buffer-1) == '#' && *(buffer-2) != '\\' && c == ' ' ) // comment start in format string
{
formatString = IN_FORMAT_COMMENT; // begin format comment
buffer -= 2;
continue;
}
}
else if (compiling && !blockComment && (c == '"' || c == '\'') && (buffer-start) > 1 && *(buffer-1) == '^' )
{
formatString = IN_FORMAT_STRING; // begin format string
ender = c;
}
// buffer overflow handling
if ((unsigned int)(buffer-start) >= (limit - 120))
{
runningOut = true;
if ((unsigned int)(buffer-start) >= (limit - 80)) break; // couldnt find safe space boundary to break on
}
if (c == ' ' && runningOut) c = '\r'; // force termination on safe boundary
if (c == '\r') // part of cr lf or just a cr?
{
if (formatString) // unclosed format string continues onto next line
{
while (*--buffer == ' '){;}
*++buffer = ' '; // single space at line split
++buffer;
formatString = IN_FORMAT_CONTINUATIONLINE;
continue; // glide on past
}
c = 0;
if (in)
{
if (fread(&c,1,1,in) == 0)
{
++currentFileLine; // for debugging error messages
maxFileLine = currentFileLine;
break; // EOF
}
}
else
{
c = *userRecordSourceBuffer++;
if (c == 0)
break; // end of string - otherwise will be \n
}
if (c != '\n' && c != '\r') holdc = c; // failed to find lf... hold this character for later but ignoring 2 cr in a row
if (c == '\n') // legal
{
++currentFileLine; // for debugging error messages
maxFileLine = currentFileLine;
}
if (blockComment)
{
if (endingBlockComment)
{
endingBlockComment = blockComment = false;
buffer = start;
*buffer = 0;
}
continue;
}
*buffer++ = '\r'; // put in the cr
*buffer++ = '\n'; // put in the newline
break;
}
else if (c == '\n') // came without cr?
{
++currentFileLine; // for debugging error messages
maxFileLine = currentFileLine;
if (formatString)
{
formatString = IN_FORMAT_CONTINUATIONLINE;
while (*--buffer == ' '){;}
*++buffer = ' '; // single space at line split
++buffer;
continue;
}
if (buffer == start) // read nothing as content
{
*start = 0;
if ( in == stdin || returnEmptyLines) return 0;
continue;
}
if (blockComment)
{
if (endingBlockComment)
{
endingBlockComment = blockComment = false;
buffer = start;
*buffer = 0;
}
continue; // ignore
}
// add missing \r
*buffer++ = '\r'; // legal
*buffer++ = '\n'; // legal
break;
}
*buffer++ = c;
*buffer = 0;
// strip UTF8 BOM marker if any and just keep reading
if (hasutf && currentFileLine == 0 && (buffer-start) == 3) // only from file system
{
if ((unsigned char) start[0] == 0xEF && (unsigned char) start[1] == 0xBB && (unsigned char) start[2] == 0xBF) // UTF8 BOM
{
buffer -= 3;
*start = 0;
BOM = BOMUTF8;
hasutf = false;
}
}
// handle block comments
if ((buffer-start) >= 4 && *(buffer-3) == '#' && *(buffer-4) == '#' && *(buffer-2) == c) // block comment mode ##
{
if ( c == '<')
{
blockComment = true;
if (!fread(&c,1,1,in)) // see if attached language
{
++currentFileLine; // for debugging error messages
maxFileLine = currentFileLine;
break; // EOF
}
if (IsAlphaUTF8(c)) // read the language
{
char lang[100];
char* current = buffer;
char* at = lang;
*at++ = c;
while (fread(&c,1,1,in))
{
if (IsAlphaUTF8(c) && c != ' ') *at++ = c;
else break;
}
*at = 0;
// this is either junk or a language marker...
if (!ConditionalReadRejected(lang,buffer,false)) blockComment = false; // this is legal
}
}
else if (c == '>')
{
if (!blockComment) {;}// superfluous end
else endingBlockComment = true;
}
else continue;
buffer -= 4;
*buffer = 0;
if (buffer != start && !endingBlockComment) break; // return what we have so far in the buffer before the comment
continue;
}
if (blockComment && (buffer-start) >= 5)
{
memmove(buffer-5,buffer-4,5);// erase as we go, keeping last four to detect block end ##>>
--buffer;
*buffer = 0;
}
} // end of read loop
*buffer = 0;
// see if conditional compile line...
if (*start == '#' && IsAlphaUTF8(start[1]))
{
if (ConditionalReadRejected(start+1,buffer,true))
{
buffer = start;
*start = 0;
goto RESUME;
}
}
if (endingBlockComment) c = 0; // force next line to be active to clean up
if (blockComment && !c)
{
endingBlockComment = blockComment = false;// end of file while handling block comment
buffer = start;
*buffer = 0;
}
if (buffer == start) // no content read (EOF)
{
*buffer = 0;
buffer[1] = 0;
buffer[2] = 0; // clear ahead to make it obvious we are at end when debugging
return -1;
}
if (*(buffer-1) == '\n') buffer -= 2; // remove cr/lf if there
*buffer = 0;
buffer[1] = 0;
buffer[2] = 1; // clear ahead to make it obvious we are at end when debugging
if (hasutf && BOM) hasbadutf = AdjustUTF8(start, start - 1);
if (hasbadutf && showBadUTF && !server)
Log(STDTRACELOG,(char*)"Bad UTF-8 %s at %d in %s\r\n",start,currentFileLine,currentFilename);
return (buffer - start);
}
char* ReadQuote(char* ptr, char* buffer,bool backslash,bool noblank)
{ // ptr is at the opening quote or a \quote... internal " must have \ preceeding the start of a quoted expression
// kinds of quoted strings:
// a) simple "this is stuff" -- same as \"xxxxx" - runs to first non-backslashed quote so cant have freestanding quotes in it but \" is converted at script compile
// b) literal \"this is stuff" - the system outputs the double-quoted item with its quotes, unmolested runs to first non-backslashed quote so cant have freestanding quotes in it but \" will get converted
// c) formatted ^"this is stuff" - the system outputs the double-quoted thing, interpreted and without the enclosing quotes
// d) literal quote \" - system outputs the quote only (script has nothing or blank or tab or ` after it
// e) internal "`xxxxx`" - argument to tcpopen pass back untouched stripping the markers on both ends - allows us to pay no attention to OTHER quotes within
char c;
int n = MAX_WORD_SIZE-10; // quote must close within this limit
char* start = ptr;
char* original = buffer;
// "` is an internal marker of argument passed from TCPOPEN "'arguments'" ) , return the section untouched as one lump
if (ptr[1] == ENDUNIT)
{
char* end = strrchr(ptr+2,ENDUNIT);
if (end[1] == '"') // yes we matched the special argument format
{
memcpy(buffer,ptr+2,end-ptr-2);
buffer[end-ptr-2] = 0;
return end + 3; // RETURN PAST space, aiming on the )
}
}
*buffer++ = *ptr; // copy over the 1st char
char ender = *ptr;
if (*ptr == '\\')
{
*buffer++ = *++ptr; // swallow \ and "
ender = *ptr;
}
while ((c = *++ptr) && c != ender && --n)
{
if (c == '\\' && ptr[1] == ender) // if c is \", means internal quoted expression.
{
*buffer++ = '\\'; // preserver internal marking - must stay with string til last possible moment.
*buffer++ = *++ptr;
}
else *buffer++ = c;
}
if (n == 0 || !c) // ran dry instead of finding the end
{
if (backslash) // probably a normal end quote with attached stuff
{
// try again, seeking only whitespace
ptr = start - 1;
buffer = original;
while (*ptr && !IsWhiteSpace(*ptr)) *buffer++ = *ptr++;
*buffer = 0;
return ptr;
}
if (!n) Log(STDTRACELOG,(char*)"bad double-quoting? %s %d %s - size is %d but limit is %d\r\n",start,currentFileLine,currentFilename,buffer-start,MAX_WORD_SIZE);
else Log(STDTRACELOG,(char*)"bad double-quoting1? %s %d %s missing tail doublequote \r\n",start,currentFileLine,currentFilename);
return NULL; // no closing quote... refuse
}
// close with ending quote
*buffer = ender;
*++buffer = 0;
return (ptr[1] == ' ') ? (ptr+2) : (ptr+1); // after the quote end and any space
}
char* ReadArgument(char* ptr, char* buffer,FunctionResult &result) // looking for a single token OR a list of tokens balanced - insure we start non-space
{ // ptr is some buffer before the arg
#ifdef INFORMATION
Used for function calls, to read their callArgumentList. Arguments are not evaluated here. An argument is:
1. a token (like $var or name or "my life as a rose" )
2. a function call which runs from the function name through the closing paren
3. a list of tokens (unevaluated), enclosed in parens like (my life as a rose )
4. a ^functionarg
#endif
char* start = buffer;
result = NOPROBLEM_BIT;
*buffer = 0;
int paren = 0;
ptr = SkipWhitespace(ptr);
char* beginptr = ptr;
if (*ptr == '^')
{
ptr = ReadCompiledWord(ptr,buffer); // get name and prepare to peek at next token
if (IsDigit(buffer[1]))
{
strcpy(buffer,callArgumentList[atoi(buffer+1)+fnVarBase]); // use the value and keep going // NEW
return ptr;
}
else if (*ptr != '(') return ptr; // not a function call
else buffer += strlen(buffer); // read onto end of call
}
if (*ptr == '"' && ptr[1] == FUNCTIONSTRING && dictionaryLocked) // must execute it now...
{
return GetCommandArg(ptr, buffer,result,0);
}
else if (*ptr == '"' || (*ptr == '\\' && ptr[1] == '"')) // a string
{
ptr = ReadQuote(ptr,buffer); // call past quote, return after quote
if (ptr != beginptr) return ptr; // if ptr == start, ReadQuote refused to read (no trailing ")
}
--ptr;
while (*++ptr)
{
char c = *ptr;
int x = GetNestingData(c);
if (paren == 0 && (c == ' ' || x == -1 || c == ENDUNIT) && ptr != beginptr) break; // simple arg separator or outer closer or end of data
if ((unsigned int)(buffer-start) < (unsigned int)(maxBufferSize-2)) *buffer++ = c; // limit overflow into argument area
*buffer = 0;
if (x) paren += x;
}
if (start[0] == '"' && start[1] == '"' && start[2] == 0) *start = 0; // NULL STRING
if (*ptr == ' ') ++ptr;
return ptr;
}
char* ReadCompiledWordOrCall(char* ptr, char* word,bool noquote,bool var)
{
ptr = ReadCompiledWord(ptr, word, noquote, var);
word += strlen(word);
if (*ptr == '(') // its a call
{
char* end = BalanceParen(ptr+1,true,false); // function call args
strncpy(word,ptr,end-ptr);
word += end-ptr;
*word = 0;
ptr = end;
}
return ptr;
}
char* ReadCompiledWord(char* ptr, char* word,bool noquote,bool var)
{// a compiled word is either characters until a blank, or a ` quoted expression ending in blank or nul. or a double-quoted on both ends or a ^double quoted on both ends
*word = 0;
if (!ptr) return NULL;
char c = 0;
char* original = word;
ptr = SkipWhitespace(ptr);
char* start = ptr;
char special = 0;
if (!var) {;}
else if ((*ptr == SYSVAR_PREFIX && IsAlphaUTF8(ptr[1])) || (*ptr == '@' && IsDigit(ptr[1])) || (*ptr == USERVAR_PREFIX && (ptr[1] == LOCALVAR_PREFIX || IsAlphaUTF8(ptr[1]) || ptr[1] == TRANSIENTVAR_PREFIX)) || (*ptr == '_' && IsDigit(ptr[1]))) special = *ptr; // break off punctuation after variable
bool jsonactivestring = false;
if (*ptr == FUNCTIONSTRING && ptr[1] == '\'') jsonactivestring = true;
if (!noquote && (*ptr == ENDUNIT || *ptr == '"' || (*ptr == FUNCTIONSTRING && ptr[1] == '"') || jsonactivestring )) // ends in blank or nul, might be quoted, doublequoted, or ^"xxx" functional string or ^'xxx' jsonactivestring
{
if (*ptr == '^') *word++ = *ptr++; // move to the actual quote
*word++ = *ptr; // keep opener --- a worst case is "`( \"grow up" ) " from a fact
char end = *ptr++; // skip the starter, noting what we need for conclusion
while ((c = *ptr++)) // run til nul or matching ` -- may have INTERNAL string as well
{
if ((word-original) > (MAX_WORD_SIZE - 3)) break;
if ( c == '\\' && *ptr == end) // escaped quote, copy both
{
*word++ = c;
*word++ = *ptr++;
continue;
}
else if (c == end && (*ptr == ' ' || nestingData[(unsigned char)*ptr] == -1 || *ptr == 0)) // a terminator followed by white space or closing bracket or end of data terminated
{
if (*ptr == ' ') ++ptr;
break; // blank or nul after closer
}
*word++ = c;
}
if (c) *word++ = end; // add back closer
else // didnt find close, it was spurious... treat as normal
{
ptr = start;
word = original;
while ((c = *ptr++) && c != ' ')
{
if ((word-original) > (MAX_WORD_SIZE - 3)) break;
*word++ = c; // run til nul or blank
}
}
}
else
{
bool quote = false;
bool bracket = false;
char priorchar = 0;
while ((c = *ptr++) && c != ENDUNIT)
{
if (quote) {}
else if (c == ' ') break;
if (c == '"' && (ptr-start) > 1 && *(ptr-2) != '\\' ) // not an internal escaped quote
quote = !quote;
if (special) // try to end a variable if not utf8 char or such
{
if (special == '$' && (c == '.' || c == '[') && (LegalVarChar(*ptr) || *ptr == '$' )) {;} // legal data following . or [
else if (special == '$' && c == ']' && bracket) {;} // allowed trailing array close
else if (special == '$' && c == '$' && (priorchar == '.' || priorchar == '[' || priorchar == '$' || priorchar == 0)){;} // legal start of interval variable or transient var continued
else if ((special == '%' || special == '_' || special == '@') && priorchar == 0) {;}
else if (!LegalVarChar(c))
break;
if (c == '[' && !bracket) bracket = true;
else if (c == ']' && bracket) bracket = false;
}
if ((word-original) > (MAX_WORD_SIZE - 3)) break;
*word++ = c; // run til nul or blank or end of rule
if ((word-original) > (MAX_WORD_SIZE-3)) break; // abort, too much jammed together (happens with simplepedia.xml)
priorchar = c;
}
}
*word = 0; // null terminate word
if (!c || special) --ptr; // shouldnt move on to valid next start (preknown to have space before it, but user string uncompiled might not)
return ptr;
}
char* BalanceParen(char* ptr,bool within,bool wildcards) // text starting with ((unless within is true), find the closing ) and point to next item after
{
int paren = 0;
if (within) paren = 1;
--ptr;
bool quoting = false;
while (*++ptr && *ptr != ENDUNIT) // jump to END of command to resume here, may have multiple parens within
{
if (*ptr == '\\' && ptr[1]) // ignore slashed item
{
++ptr;
continue;
}
if ( *ptr == '"')
{
quoting = !quoting;
continue;
}
if (quoting) continue; // stuff in quotes is safe
if (wildcards && *ptr == '_' && !IsDigit(ptr[1]) && *(ptr-1) == ' ')
{
SetWildCardNull();
}
int value = nestingData[(unsigned char)*ptr];
if (*ptr == '<' && ptr[1] == '<' && ptr[2] != '<') value = 1;
if (*ptr == '>' && ptr[1] == '>' && ptr[2] != '>')
{
value = -1;
++ptr; // ignore 1st one
}
if (value && (paren += value) == 0)
{
ptr += (ptr[1] && ptr[2]) ? 2 : 1; // return on next token (skip paren + space) or out of data (typically argument substitution)
break;
}
}
return ptr; // return on end of data
}
char* SkipWhitespace(char* ptr)
{
if (!ptr || !*ptr) return ptr;
while (IsWhiteSpace(*ptr)) ++ptr;
return ptr;
}
///////////////////////////////////////////////////////////////
// CONVERSION UTILITIES
///////////////////////////////////////////////////////////////
char* Purify(char* msg) // used for logging to remove real newline characters so all fits on one line
{
if (newline) return msg; // allow newlines to remain
char* nl = strchr(msg,'\n'); // legal
if (!nl) return msg; // no problem
char* limit;
char* buffer = InfiniteStack(limit,"Purify"); // transient
strcpy(buffer,msg);
nl = (nl - msg) + buffer;
while (nl)
{
*nl = ' ';
nl = strchr(nl,'\n'); // legal
}
char* cr = strchr(buffer,'\r'); // legal
while (cr)
{
*cr = ' ';
cr = strchr(cr,'\r'); // legal
}
ReleaseInfiniteStack();
return buffer; // nothing else should use ReleaseStackspace
}
size_t OutputLimit(unsigned char* data) // insert eols where limitations exist
{
char extra[HIDDEN_OVERLAP+1];
strncpy(extra,((char*)data) + strlen((char*)data),HIDDEN_OVERLAP); // preserve any hidden data on why and serverctrlz
unsigned char* original = data;
unsigned char* lastBlank = data;
unsigned char* lastAt = data;
--data;
while( *++data)
{
if (data > lastAt && (unsigned int)(data - lastAt) > outputLength)
{
memmove(lastBlank+2,lastBlank+1,strlen((char*)lastBlank));
*lastBlank++ = '\r'; // legal
*lastBlank++ = '\n'; // legal
lastAt = lastBlank;
++data;
}
if (*data == ' ') lastBlank = data;
else if (*data == '\n') lastAt = lastBlank = data+1; // internal newlines restart checking
}
strncpy(((char*)data) + strlen((char*)data), extra, HIDDEN_OVERLAP);
return data - original;
}
char* UTF2ExtendedAscii(char* bufferfrom)
{
char* limit;
unsigned char* buffer = (unsigned char*) InfiniteStack(limit,"UTF2ExtendedAscii"); // transient
unsigned char* bufferto = buffer;
while( *bufferfrom && (size_t)(bufferto-buffer) < (size_t)(maxBufferSize-10)) // avoid overflow on local buffer
{
if (*bufferfrom != 0xc3) *bufferto++ = *bufferfrom++;
else
{
++bufferfrom;
unsigned char x = *bufferfrom++;
unsigned char val = utf82extendedascii[x - 128];
if (val) *bufferto++ = val + 128;
else // we dont know this character
{
*bufferto++ = (unsigned char) 0xc3;
*bufferto++ = *(bufferfrom-1);
}
}
}
*bufferto = 0;
if (outputLength) OutputLimit(buffer);
ReleaseInfiniteStack();
return (char*) buffer; // it is ONLY good for printf immediate, not for anything long term
}
void ForceUnderscores(char* ptr)
{
--ptr;
while (*++ptr) if (*ptr == ' ') *ptr = '_';
}
void Convert2Blanks(char* ptr)
{
--ptr;
while (*++ptr)
{
if (*ptr == '_')
{
if (ptr[1] == '_') memmove(ptr,ptr+1,strlen(ptr));// convert 2 __ to 1 _ (allows web addressess as output)
else *ptr = ' ';
}
}
}
void ConvertNL(char* ptr)
{
char* start = ptr;
--ptr;
char c;
while ((c = *++ptr))
{
if (c == '\\')
{
if (ptr[1] == 'n')
{
if (*(ptr-1) != '\r') // auto add \r before it
{
*ptr = '\r'; // legal
*++ptr = '\n'; // legal
}
else
{
*ptr = '\n'; // legal
memmove(ptr+1,ptr+2,strlen(ptr+2)+1);
}
}
else if (ptr[1] == 'r')
{
*ptr = '\r'; // legal
memmove(ptr+1,ptr+2,strlen(ptr+2)+1);
}
else if (ptr[1] == 't')
{
*ptr = '\t'; // legal
memmove(ptr+1,ptr+2,strlen(ptr+2)+1);
}
}
}
}
void Convert2Underscores(char* output)
{
char* ptr = output - 1;
char c;
if (ptr[1] == '"') // leave this area alone
{
ptr += 2;
while (*++ptr && *ptr != '"');
}
while ((c = *++ptr))
{
if (c == '_' && ptr[1] != '_') // remove underscores from apostrophe of possession
{
// remove space on possessives
if (ptr[1] == '\'' && ( (ptr[2] == 's' && !IsAlphaUTF8OrDigit(ptr[3])) || !IsAlphaUTF8OrDigit(ptr[2]) ) )// bob_'s bobs_'
{
memmove(ptr,ptr+1,strlen(ptr));
--ptr;
}
}
}
}
void RemoveTilde(char* output)
{
char* ptr = output - 1;
char c;
if (ptr[1] == '"') // leave this area alone
{
ptr += 2;
while (*++ptr && *ptr != '"');
}
while ((c = *++ptr))
{
if (c == '~' && IsAlphaUTF8(ptr[1]) && (ptr == output || (*(ptr-1)) == ' ') ) // REMOVE leading ~ in classnames
{
memmove(ptr,ptr+1,strlen(ptr));
--ptr;
}
}
}
int64 NumberPower(char* number)
{
if (*number == '-') return 2000000000; // isolated - always stays in front
int64 num = Convert2Integer(number);
if (num < 10) return 1;
if (num < 100) return 10;
if (num < 1000) return 100;
if (num < 10000) return 1000;
if (num < 100000) return 10000;
if (num < 1000000) return 100000;
if (num < 10000000) return 1000000;
if (num < 100000000) return 10000000;
if (num < 1000000000) return 100000000; // max int is around 4 billion
return 10000000000ULL;
}
int64 Convert2Integer(char* number) // non numbers return NOT_A_NUMBER
{ // ProcessCompositeNumber will have joined all number words together in appropriate number power order: two hundred and fifty six billion and one -> two-hundred-fifty-six-billion-one , while four and twenty -> twenty-four
if (!number || !*number) return NOT_A_NUMBER;
char c = *number;
if (c == '$'){;}
else if (c == '#' && IsDigitWord(number+1)) return Convert2Integer(number+1);
else if (!IsAlphaUTF8DigitNumeric(c) || c == '.') return NOT_A_NUMBER; // not 0-9 letters + -
size_t len = strlen(number);
uint64 valx;
if (IsRomanNumeral(number,valx)) return (int64) valx;
if (IsDigitWithNumberSuffix(number)) // 10K 10M 10B or currency
{
char d = number[len-1];
number[len-1] = 0;
int64 answer = Convert2Integer(number);
if (d == 'k' || d == 'K') answer *= 1000;
else if (d == 'm' || d == 'M') answer *= 1000000;
else if (d == 'B' || d == 'b' || d == 'G' || d == 'g') answer *= 1000000000;
number[len-1] = d;
return answer;
}
// grab sign if any
char sign = *number;
if (sign == '-' || sign == '+') ++number;
else if (sign == '$')
{
sign = 0;
++number;
}
else sign = 0;
// make canonical: remove commas (user typed a digit number with commas) and convert _ to -
char copy[MAX_WORD_SIZE];
MakeLowerCopy(copy+1,number);
*copy = ' '; // safe place to look behind at
char* comma = copy;
while (*++comma)
{
if (*comma == ',') memmove(comma,comma+1,strlen(comma));
else if (*comma == '_') *comma = '-';
}
char* word = copy+1;
// remove place suffixes
if (len > 3 && !stricmp(word+len-3,(char*)"ies")) // twenties?
{
char xtra[MAX_WORD_SIZE];
strcpy(xtra,word);
strcpy(xtra+len-3,(char*)"y");
size_t len1 = strlen(xtra);
for (unsigned int i = 0; i < sizeof(numberValues)/sizeof(NUMBERDECODE); ++i)
{
if (len1 == numberValues[i].length && !strnicmp(xtra,numberValues[i].word,len1))
{
if (numberValues[i].realNumber == FRACTION_NUMBER || numberValues[i].realNumber == REALNUMBER)
{
strcpy(word,xtra);
len = len1;
}
break;
}
}
}
if (len > 3 && word[len-1] == 's') // if s attached to a fraction, remove it
{
size_t len1 = len - 1;
if (word[len1-1] == 'e') --len1; // es ending like zeroes
// look up direct word number as single
for (unsigned int i = 0; i < sizeof(numberValues)/sizeof(NUMBERDECODE); ++i)
{
if (len1 == numberValues[i].length && !strnicmp(word,numberValues[i].word,len1))
{
if (numberValues[i].realNumber == FRACTION_NUMBER || numberValues[i].realNumber == REALNUMBER)
{
word[len1] = 0; // thirds to third quarters to quarter fifths to fith but not ones to one
len = len1;
}
break;
}
}
}
unsigned int oldlen = len;
// remove
if (len < 3); // cannot have suffix
else if (word[len-2] == 's' && word[len-1] == 't' && !strstr(word,(char*)"first")) word[len -= 2] = 0; // 1st
else if (word[len-2] == 'n' && word[len-1] == 'd' && !strstr(word,(char*)"second") && !strstr(word,(char*)"thousand")) word[len -= 2] = 0; // 2nd but not second or thousandf"
else if (word[len-2] == 'r' && word[len-1] == 'd' && !strstr(word,(char*)"third")) word[len -= 2] = 0; // 3rd
else if (word[len-2] == 't' && word[len-1] == 'h' && !strstr(word,(char*)"fifth")) // excluding the word "fifth" which is not derived from five
{
word[len -= 2] = 0;
if (word[len-1] == 'e' && word[len-2] == 'i') // twentieth and its ilk
{
word[--len - 1] = 'y';
word[len] = 0;
}
}
if (oldlen != len && (word[len-1] == '-' || word[len-1] == '\'')) word[--len] = 0; // trim off separator
bool hasDigit = IsDigit(*word);
char* hyp = strchr(word,'-');
if (hyp) *hyp = 0;
if (hasDigit) // see if all digits now.
{
char* ptr = word-1;
while (*++ptr)
{
if (ptr != word && *ptr == '-') {;}
else if (*ptr == '-' || *ptr == '+') return NOT_A_NUMBER;
else if (!IsDigit(*ptr)) return NOT_A_NUMBER; // not good
}
if (!*ptr && !hyp) return atoi64(word) * ((sign == '-') ? -1 : 1); // all digits with sign
// try for digit sequence 9-1-1 or whatever
ptr = word;
if (hyp) *hyp = '-';
int64 value = 0;
while (IsDigit(*ptr))
{
value *= 10;
value += *ptr - '0';
if (*++ptr != '-') break; // 91-55
++ptr;
}
if (!*ptr) return value; // dont know what to do with it
}
if (hyp) *hyp = '-';
// look up direct word numbers
if (!hasDigit) for (unsigned int i = 0; i < sizeof(numberValues)/sizeof(NUMBERDECODE); ++i)
{
if (len == numberValues[i].length && !strnicmp(word,numberValues[i].word,len))
{
return numberValues[i].value; // a match (but may be a fraction number)
}
}
// try for hyphenated composite
char* hyphen = strchr(word,'-');
if (!hyphen) hyphen = strchr(word,'_'); // alternate form of separation
if (!hyphen || !hyphen[1]) return NOT_A_NUMBER; // not multi part word
if (hasDigit && IsDigit(hyphen[1])) return NOT_A_NUMBER; // cannot hypenate a digit number but can do mixed "1-million" is legal
// if lead piece is not a number, the whole thing isnt
c = *hyphen;
*hyphen = 0;
int64 val = Convert2Integer(word); // convert lead piece to see if its a number
*hyphen = c;
if (val == NOT_A_NUMBER) return NOT_A_NUMBER; // lead is not a number
// val is now the lead number
// decode powers of ten names on 2nd pieces
long billion = 0;
char* found = strstr(word+1,(char*)"billion"); // eight-billion
if (found && *(found-1) == '-') // is 2nd piece
{
*(found-1) = 0; // hide the word billion
billion = (int)Convert2Integer(word); // determine the number of billions
if (billion == NOT_A_NUMBER && stricmp(word,(char*)"zero") && *word != '0') return NOT_A_NUMBER;
word = found + 7; // now points to next part
if (*word == '-' || *word == '_') ++word; // has another hypen after it
}
else if (val == 1000000000)
{
val = 0;
billion = 1;
if (hyphen) word = hyphen + 1;
}
hyphen = strchr(word,'-');
if (!hyphen) hyphen = strchr(word,'_'); // alternate form of separation
long million = 0;
found = strstr(word,(char*)"million");
if (found && *(found-1) == '-')
{
*(found-1) = 0;
million = (int)Convert2Integer(word);
if (million == NOT_A_NUMBER && stricmp(word,(char*)"zero") && *word != '0') return NOT_A_NUMBER;
word = found + 7;
if (*word == '-' || *word == '_') ++word; // has another hypen after it
}
else if (val == 1000000)
{
val = 0;
million = 1;
if (hyphen) word = hyphen + 1;
}
hyphen = strchr(word,'-');
if (!hyphen) hyphen = strchr(word,'_'); // alternate form of separation
long thousand = 0;
found = strstr(word,(char*)"thousand");
if (found && *(found-1) == '-')
{
*(found-1) = 0;
thousand = (int)Convert2Integer(word);
if (thousand == NOT_A_NUMBER && stricmp(word,(char*)"zero") && *word != '0') return NOT_A_NUMBER;
word = found + 8;
if (*word == '-' || *word == '_') ++word; // has another hypen after it
}
else if (val == 1000)
{
val = 0;
thousand = 1;
if (hyphen) word = hyphen + 1;
}
hyphen = strchr(word,'-');
if (!hyphen) hyphen = strchr(word,'_'); // alternate form of separation
long hundred = 0;
found = strstr(word,(char*)"hundred");
if (found && *(found-1) == '-') // do we have four-hundred
{
*(found-1) = 0;
hundred = (int) Convert2Integer(word);
if (hundred == NOT_A_NUMBER && stricmp(word,(char*)"zero") && *word != '0') return NOT_A_NUMBER;
word = found + 7;
if (*word == '-' || *word == '_') ++word; // has another hypen after it
}
else if (val == 100)
{
val = 0;
hundred = 1;
if (hyphen) word = hyphen + 1;
}
// now do tens and ones, which can include omitted hundreds label like two-fifty-two
hyphen = strchr(word,'-');
if (!hyphen) hyphen = strchr(word,'_');
int64 value = 0;
while (word && *word) // read each smaller part and scale
{
if (!hyphen) // last piece (a tens or a ones)
{
if (!strcmp(word,number)) return NOT_A_NUMBER; // never decoded anything so far
int64 n = Convert2Integer(word);
if (n == NOT_A_NUMBER && stricmp(word,(char*)"zero") && *word != '0') return NOT_A_NUMBER;
value += n; // handled LAST piece
break;
}
*hyphen++ = 0; // split pieces
// split 3rd piece if one exists
char* next = strchr(hyphen,'-');
if (!next) next = strchr(hyphen,'_');
if (next) *next = 0;
int64 piece1 = Convert2Integer(word);
if (piece1 == NOT_A_NUMBER && stricmp(word,(char*)"zero") && *word != '0') return NOT_A_NUMBER;
int64 piece2 = Convert2Integer(hyphen);
if (piece2 == NOT_A_NUMBER && stricmp(hyphen,(char*)"0")) return NOT_A_NUMBER;
int64 subpiece = 0;
if (piece1 > piece2 && piece2 < 10) subpiece = piece1 + piece2; // can be larger-smaller (like twenty one)
if (piece2 >= 10 && piece2 < 100 && piece1 >= 1 && piece1 < 100) subpiece = piece1 * 100 + piece2; // two-fifty-two is omitted hundred
else if (piece2 == 10 || piece2 == 100 || piece2 == 1000) subpiece = piece1 * piece2; // must be smaller larger pair (like four hundred)
value += subpiece; // 2 pieces mean item was power of ten and power of one
// if 3rd piece, now recycle to handle the ones part
if (next) ++next;
word = next;
hyphen = NULL;
}
return value + ((int64)billion * 1000000000) + ((int64)million * 1000000) + ((int64)thousand * 1000) + ((int64)hundred * 100);
}
void MakeLowerCase(char* ptr)
{
--ptr;
while (*++ptr)
{
if (*ptr == 0xc3 && (unsigned char)ptr[1] >= 0x80 && (unsigned char)ptr[1] <= 0x9e)
{
unsigned char c = (unsigned char)*++ptr; // get the cap form
c -= 0x80;
c += 0x9f; // get lower case form
*ptr = (char)c;
}
else if (*ptr >= 0xc4 && *ptr <= 0xc9)
{
unsigned char c = (unsigned char)*++ptr;
*ptr = (char)c | 1;
}
else *ptr = GetLowercaseData(*ptr);
}
}
void MakeUpperCase(char* ptr)
{
--ptr;
while (*++ptr)
{
if (*ptr == 0xc3 && ptr[1] >= 0x9f && ptr[1] <= 0xbf)
{
unsigned char c = (unsigned char)*++ptr; // get the cap form
c -= 0x9f;
c += 0x80; // get upper case form
*ptr = (char)c;
}
else if (*ptr >= 0xc4 && *ptr <= 0xc9)
{
unsigned char c = (unsigned char)*++ptr; // get the cap form
*ptr = (char)c & 0xfe;
}
else *ptr = GetUppercaseData(*ptr);
}
}
char* MakeLowerCopy(char* to,char* from)
{
char* start = to;
while (*from)
{
if (*from == 0xc3 && from[1] >= 0x80 && from[1] <= 0x9e)
{
*to++ = *from++;
unsigned char c = *from++; // get the cap form
c -= 0x80;
c += 0x9f; // get lower case form
*to++ = c;
}
else if (*from >= 0xc4 && *from <= 0xc9)
{
*to++ = *from++;
*to++ = *from++ | 1; // lowercase from cap
}
else *to++ = GetLowercaseData(*from++);
}
*to = 0;
return start;
}
char* MakeUpperCopy(char* to,char* from)
{
char* start = to;
while (*from)
{
if (*from == 0xc3 && from[1] >= 0x9f && from[1] <= 0xbf)
{
*to++ = *from++;
unsigned char c = *from++; // get the cap form
c -= 0x9f;
c += 0x80; // get upper case form
*to++ = c;
}
else if ((*from >= 0xc4 && *from <= 0xc9))
{
*to++ = *from++;
*to++ = *from++ & 0xfe; // uppercase from small
}
else *to++ = GetUppercaseData(*from++);
}
*to = 0;
return start;
}
char* TrimSpaces(char* msg,bool start)
{
char* orig = msg;
if (start) while (IsWhiteSpace(*msg)) ++msg;
size_t len = strlen(msg);
if (len == 0) // if all blanks, shift to null at start
{
msg = orig;
*msg= 0;
}
while (len && IsWhiteSpace(msg[len-1])) msg[--len] = 0;
return msg;
}
void UpcaseStarters(char* ptr) // take a multiword phrase with _ and try to capitalize it correctly (assuming its a proper noun)
{
if (IsLowerCase(*ptr)) *ptr -= 'a' - 'A';
while (*++ptr)
{
if (!IsLowerCase(*++ptr) || *ptr != '_') continue; // word separator
if (!strnicmp(ptr,(char*)"the_",4) || !strnicmp(ptr,(char*)"of_",3) || !strnicmp(ptr,(char*)"in_",3) || !strnicmp(ptr,(char*)"and_",4)) continue;
*ptr -= 'a' - 'A';
}
}
char* documentBuffer = 0;
bool ReadDocument(char* inBuffer,FILE* sourceFile)
{
static bool wasEmptyLine = false;
RETRY: // for sampling loopback
*inBuffer = 0;
if (!*documentBuffer || singleSource)
{
while (ALWAYS)
{
if (ReadALine(documentBuffer,sourceFile) < 0)
{
wasEmptyLine = false;
return false; // end of input
}
if (!*SkipWhitespace(documentBuffer)) // empty line
{
if (wasEmptyLine) continue; // ignore additional empty line
wasEmptyLine = true;
if (docOut) fprintf(docOut,(char*)"\r\n%s\r\n",inBuffer);
return true; // no content, just null line or all white space
}
if (*documentBuffer == ':' && IsAlphaUTF8(documentBuffer[1]))
{
if (!stricmp(documentBuffer,(char*)":exit") || !stricmp(documentBuffer,(char*)":quit"))
{
wasEmptyLine = false;
return false;
}
}
break; // have something
}
}
else if (*documentBuffer == 1) // holding an empty line from before to return
{
*documentBuffer = 0;
wasEmptyLine = true;
if (docOut) fprintf(docOut,(char*)"\r\n%s\r\n",inBuffer);
return true;
}
unsigned int readAhead = 0;
while (++readAhead < 4) // read up to 3 lines
{
// pick earliest punctuation that can terminate a sentence
char* period = NULL;
char* at = documentBuffer;
char* oob = strchr(documentBuffer,OOB_START); // oob marker
if (oob && (oob - documentBuffer) < 5) oob = strchr(oob+3,OOB_START); // find a next one // seen at start doesnt count.
if (!oob) oob = documentBuffer + 300000; // way past anything
while (!period && (period = strchr(at,'.'))) // normal input end here?
{
if (period > oob) break;
if (period[1] && !IsWhiteSpace(period[1]))
{
if (period[1] == '"' || period[1] == '\'') // period shifted inside the quote
{
++period; // report " or ' as the end so whole thing gets tokenized
break;
}
at = period + 1; // period in middle of something
}
else if (IsDigit(*(period-1)))
{
// is this number at end of sentence- e.g. "That was in 1992. It became obvious."
char* next = SkipWhitespace(period+1);
if (*next && IsUpperCase(*next)) break;
else break; // ANY number ending in a period is an end of sentence. Assume no one used period unless they want a digit after it
//at = period + 1; // presumed a number ending in period, not end of sentence
}
else if (IsWhiteSpace(*(period-1))) break; // isolated period
else // see if token it ends is reasonable
{
char* before = period;
while (before > documentBuffer && !IsWhiteSpace(*--before)); // find start of word
char next2 = (period[1]) ? *SkipWhitespace(period+2) : 0;
if (ValidPeriodToken(before+1, period+1, period[1],next2) == TOKEN_INCLUSIVE) at = period + 1; // period is part of known token
else break;
}
period = NULL;
}
char* question = strchr(documentBuffer,'?');
if (question && (question[1] == '"' || question[1] == '\'') && question < oob) ++question; // extend from inside a quote
char* exclaim = strchr(documentBuffer,'!');
if (exclaim && (exclaim[1] == '"' || exclaim[1] == '\'') && exclaim < oob) ++exclaim; // extend from inside a quote
if (!period && question) period = question;
else if (!period && exclaim) period = exclaim;
if (exclaim && exclaim < period) period = exclaim;
if (question && question < period) period = question;
// check for things other than sentence periods as well here
if (period) // found end of a sentence before any oob
{
char was = period[1];
period[1] = 0;
strcpy(inBuffer,SkipWhitespace(documentBuffer)); // copied over to input
period[1] = was;
memmove(documentBuffer,period+1,strlen(period+1) + 1); // rest moved up in holding area
break;
}
else if (singleSource) // only 1 line at a time regardless of it not being a complete sentence
{
strcpy(inBuffer,SkipWhitespace(documentBuffer));
break;
}
else // has no end yet
{
char* at = SkipWhitespace(documentBuffer);
if (*at == OOB_START) // starts with OOB, add no more lines onto it.
{
strcpy(mainInputBuffer,at);
*documentBuffer = 0;
break;
}
if (oob < (documentBuffer + 300000)) // we see oob data
{
if (at != oob) // stuff before is auto terminated by oob data
{
*oob = 0;
strcpy(inBuffer,at);
*oob = OOB_START;
memmove(documentBuffer,oob,strlen(oob)+1);
break;
}
}
size_t len = strlen(documentBuffer);
documentBuffer[len] = ' '; // append 1 blanks
ReadALine(documentBuffer + len + 1,sourceFile,maxBufferSize - 4 - len); // ahead input and merge onto current
if (!documentBuffer[len+1]) // logical end of file
{
strcpy(inBuffer,SkipWhitespace(documentBuffer));
*documentBuffer = 1;
break;
}
}
}
// skim the file
if (docSampleRate)
{
if (--docSample != 0) goto RETRY; // decline to process
docSample = docSampleRate;
}
if (readAhead >= 6)
Log(STDTRACELOG,(char*)"Heavy long line? %s\r\n",documentBuffer);
if (autonumber) Log(ECHOSTDTRACELOG,(char*)"%d: %s\r\n",inputSentenceCount,inBuffer);
else if (docstats)
{
if ((++docSentenceCount % 1000) == 0) Log(ECHOSTDTRACELOG,(char*)"%d: %s\r\n",docSentenceCount,inBuffer);
}
wasEmptyLine = false;
if (docOut) fprintf(docOut,(char*)"\r\n%s\r\n",inBuffer);
return true;
}
| 96,940 | 42,967 |
// Γράψτε ένα πρόγραμμα που να ορίζει μια κλάση Α με ένα ιδιωτικό μέλος δεδομένων που να είναι δείκτης προς πίνακα ακεραίων.
// Συμπληρώστε έναν κατασκευαστή αντιγραφής.
// Χρησιμοποιήστε τον κατασκευαστή αντιγραφής στη main.
#include <iostream>
using namespace std;
class A
{
private:
int n;
int *data;
public:
A(int n) : n(n), data(new int[n])
{
for (int i = 0; i < n; i++)
{
data[i] = i + 1;
}
}
A(const A &obj) // deep copy
{
n = obj.n;
data = new int[n];
for (int i = 0; i < n; i++)
{
data[i] = obj.data[i];
}
}
~A()
{
delete[] data;
}
void info()
{
cout << "Object at " << this << " data at " << data << endl;
}
};
int main()
{
A obj1(5);
A obj2(obj1);
obj1.info();
obj2.info();
}
/*
Object at 0x7afe00 data at 0x1c2450
Object at 0x7afdf0 data at 0x1c2470
*/ | 951 | 523 |
// Copyright 2018-2022, NVIDIA CORPORATION & AFFILIATES. 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 NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "model_config.h"
#include "constants.h"
namespace triton { namespace core {
bool
IsFixedSizeDataType(const inference::DataType dtype)
{
return dtype != inference::DataType::TYPE_STRING;
}
size_t
GetDataTypeByteSize(const inference::DataType dtype)
{
switch (dtype) {
case inference::DataType::TYPE_BOOL:
return 1;
case inference::DataType::TYPE_UINT8:
return 1;
case inference::DataType::TYPE_UINT16:
return 2;
case inference::DataType::TYPE_UINT32:
return 4;
case inference::DataType::TYPE_UINT64:
return 8;
case inference::DataType::TYPE_INT8:
return 1;
case inference::DataType::TYPE_INT16:
return 2;
case inference::DataType::TYPE_INT32:
return 4;
case inference::DataType::TYPE_INT64:
return 8;
case inference::DataType::TYPE_FP16:
return 2;
case inference::DataType::TYPE_FP32:
return 4;
case inference::DataType::TYPE_FP64:
return 8;
case inference::DataType::TYPE_STRING:
return 0;
case inference::DataType::TYPE_BF16:
return 2;
default:
break;
}
return 0;
}
int64_t
GetElementCount(const DimsList& dims)
{
bool first = true;
int64_t cnt = 0;
for (auto dim : dims) {
if (dim == WILDCARD_DIM) {
return -1;
}
if (first) {
cnt = dim;
first = false;
} else {
cnt *= dim;
}
}
return cnt;
}
int64_t
GetElementCount(const std::vector<int64_t>& dims)
{
bool first = true;
int64_t cnt = 0;
for (auto dim : dims) {
if (dim == WILDCARD_DIM) {
return -1;
}
if (first) {
cnt = dim;
first = false;
} else {
cnt *= dim;
}
}
return cnt;
}
int64_t
GetElementCount(const inference::ModelInput& mio)
{
return GetElementCount(mio.dims());
}
int64_t
GetElementCount(const inference::ModelOutput& mio)
{
return GetElementCount(mio.dims());
}
int64_t
GetByteSize(const inference::DataType& dtype, const DimsList& dims)
{
size_t dt_size = GetDataTypeByteSize(dtype);
if (dt_size == 0) {
return -1;
}
int64_t cnt = GetElementCount(dims);
if (cnt == -1) {
return -1;
}
return cnt * dt_size;
}
int64_t
GetByteSize(const inference::DataType& dtype, const std::vector<int64_t>& dims)
{
size_t dt_size = GetDataTypeByteSize(dtype);
if (dt_size == 0) {
return -1;
}
int64_t cnt = GetElementCount(dims);
if (cnt == -1) {
return -1;
}
return cnt * dt_size;
}
int64_t
GetByteSize(
const int batch_size, const inference::DataType& dtype,
const DimsList& dims)
{
if (dims.size() == 0) {
return batch_size * GetDataTypeByteSize(dtype);
}
int64_t bs = GetByteSize(dtype, dims);
if (bs == -1) {
return -1;
}
return std::max(1, batch_size) * bs;
}
int64_t
GetByteSize(
const int batch_size, const inference::DataType& dtype,
const std::vector<int64_t>& dims)
{
if (dims.size() == 0) {
return batch_size * GetDataTypeByteSize(dtype);
}
int64_t bs = GetByteSize(dtype, dims);
if (bs == -1) {
return -1;
}
return std::max(1, batch_size) * bs;
}
int64_t
GetByteSize(const inference::ModelInput& mio)
{
return GetByteSize(mio.data_type(), mio.dims());
}
int64_t
GetByteSize(const inference::ModelOutput& mio)
{
return GetByteSize(mio.data_type(), mio.dims());
}
BackendType
GetBackendTypeFromPlatform(const std::string& platform_name)
{
if ((platform_name == kTensorFlowGraphDefPlatform) ||
(platform_name == kTensorFlowSavedModelPlatform)) {
return BackendType::BACKEND_TYPE_TENSORFLOW;
}
if (platform_name == kTensorRTPlanPlatform) {
return BackendType::BACKEND_TYPE_TENSORRT;
}
if (platform_name == kOnnxRuntimeOnnxPlatform) {
return BackendType::BACKEND_TYPE_ONNXRUNTIME;
}
if (platform_name == kPyTorchLibTorchPlatform) {
return BackendType::BACKEND_TYPE_PYTORCH;
}
return BackendType::BACKEND_TYPE_UNKNOWN;
}
/// Get the BackendType value for a backend name.
/// \param backend_name The backend name.
/// \return The BackendType or BackendType::UNKNOWN if the platform string
/// is not recognized.
BackendType
GetBackendType(const std::string& backend_name)
{
if (backend_name == kTensorFlowBackend) {
return BackendType::BACKEND_TYPE_TENSORFLOW;
}
if (backend_name == kTensorRTBackend) {
return BackendType::BACKEND_TYPE_TENSORRT;
}
if (backend_name == kOnnxRuntimeBackend) {
return BackendType::BACKEND_TYPE_ONNXRUNTIME;
}
if (backend_name == kPyTorchBackend) {
return BackendType::BACKEND_TYPE_PYTORCH;
}
return BackendType::BACKEND_TYPE_UNKNOWN;
}
int
GetCpuNiceLevel(const inference::ModelConfig& config)
{
int nice = SCHEDULER_DEFAULT_NICE;
if (config.has_optimization()) {
switch (config.optimization().priority()) {
case inference::ModelOptimizationPolicy::PRIORITY_MAX:
nice = 0;
break;
case inference::ModelOptimizationPolicy::PRIORITY_MIN:
nice = 19;
break;
default:
nice = SCHEDULER_DEFAULT_NICE;
break;
}
}
return nice;
}
bool
CompareDims(const DimsList& dims0, const DimsList& dims1)
{
if (dims0.size() != dims1.size()) {
return false;
}
for (int i = 0; i < dims0.size(); ++i) {
if (dims0[i] != dims1[i]) {
return false;
}
}
return true;
}
bool
CompareDims(
const std::vector<int64_t>& dims0, const std::vector<int64_t>& dims1)
{
if (dims0.size() != dims1.size()) {
return false;
}
for (size_t i = 0; i < dims0.size(); ++i) {
if (dims0[i] != dims1[i]) {
return false;
}
}
return true;
}
bool
CompareDimsWithWildcard(const DimsList& dims0, const DimsList& dims1)
{
if (dims0.size() != dims1.size()) {
return false;
}
for (int i = 0; i < dims0.size(); ++i) {
if ((dims0[i] != WILDCARD_DIM) && (dims1[i] != WILDCARD_DIM) &&
(dims0[i] != dims1[i])) {
return false;
}
}
return true;
}
bool
CompareDimsWithWildcard(
const DimsList& dims0, const std::vector<int64_t>& dims1)
{
if (dims0.size() != (int64_t)dims1.size()) {
return false;
}
for (int i = 0; i < dims0.size(); ++i) {
if ((dims0[i] != WILDCARD_DIM) && (dims1[i] != WILDCARD_DIM) &&
(dims0[i] != dims1[i])) {
return false;
}
}
return true;
}
std::string
DimsListToString(const DimsList& dims)
{
bool first = true;
std::string str("[");
for (const auto& dim : dims) {
if (!first) {
str += ",";
}
str += std::to_string(dim);
first = false;
}
str += "]";
return str;
}
std::string
DimsListToString(const std::vector<int64_t>& dims, const int start_idx)
{
int idx = 0;
std::string str("[");
for (const auto& dim : dims) {
if (idx >= start_idx) {
if (idx > start_idx) {
str += ",";
}
str += std::to_string(dim);
}
idx++;
}
str += "]";
return str;
}
const char*
DataTypeToProtocolString(const inference::DataType dtype)
{
switch (dtype) {
case inference::DataType::TYPE_BOOL:
return "BOOL";
case inference::DataType::TYPE_UINT8:
return "UINT8";
case inference::DataType::TYPE_UINT16:
return "UINT16";
case inference::DataType::TYPE_UINT32:
return "UINT32";
case inference::DataType::TYPE_UINT64:
return "UINT64";
case inference::DataType::TYPE_INT8:
return "INT8";
case inference::DataType::TYPE_INT16:
return "INT16";
case inference::DataType::TYPE_INT32:
return "INT32";
case inference::DataType::TYPE_INT64:
return "INT64";
case inference::DataType::TYPE_FP16:
return "FP16";
case inference::DataType::TYPE_FP32:
return "FP32";
case inference::DataType::TYPE_FP64:
return "FP64";
case inference::DataType::TYPE_STRING:
return "BYTES";
case inference::DataType::TYPE_BF16:
return "BF16";
default:
break;
}
return "<invalid>";
}
inference::DataType
ProtocolStringToDataType(const std::string& dtype)
{
return ProtocolStringToDataType(dtype.c_str(), dtype.size());
}
inference::DataType
ProtocolStringToDataType(const char* dtype, size_t len)
{
if (len < 4 || len > 6) {
return inference::DataType::TYPE_INVALID;
}
if ((*dtype == 'I') && (len != 6)) {
if ((dtype[1] == 'N') && (dtype[2] == 'T')) {
if ((dtype[3] == '8') && (len == 4)) {
return inference::DataType::TYPE_INT8;
} else if ((dtype[3] == '1') && (dtype[4] == '6')) {
return inference::DataType::TYPE_INT16;
} else if ((dtype[3] == '3') && (dtype[4] == '2')) {
return inference::DataType::TYPE_INT32;
} else if ((dtype[3] == '6') && (dtype[4] == '4')) {
return inference::DataType::TYPE_INT64;
}
}
} else if ((*dtype == 'U') && (len != 4)) {
if ((dtype[1] == 'I') && (dtype[2] == 'N') && (dtype[3] == 'T')) {
if ((dtype[4] == '8') && (len == 5)) {
return inference::DataType::TYPE_UINT8;
} else if ((dtype[4] == '1') && (dtype[5] == '6')) {
return inference::DataType::TYPE_UINT16;
} else if ((dtype[4] == '3') && (dtype[5] == '2')) {
return inference::DataType::TYPE_UINT32;
} else if ((dtype[4] == '6') && (dtype[5] == '4')) {
return inference::DataType::TYPE_UINT64;
}
}
} else if ((*dtype == 'F') && (dtype[1] == 'P') && (len == 4)) {
if ((dtype[2] == '1') && (dtype[3] == '6')) {
return inference::DataType::TYPE_FP16;
} else if ((dtype[2] == '3') && (dtype[3] == '2')) {
return inference::DataType::TYPE_FP32;
} else if ((dtype[2] == '6') && (dtype[3] == '4')) {
return inference::DataType::TYPE_FP64;
}
} else if (*dtype == 'B') {
switch (dtype[1]) {
case 'Y':
if (!strcmp(dtype + 2, "TES")) {
return inference::DataType::TYPE_STRING;
}
break;
case 'O':
if (!strcmp(dtype + 2, "OL")) {
return inference::DataType::TYPE_BOOL;
}
break;
case 'F':
if (!strcmp(dtype + 2, "16")) {
return inference::DataType::TYPE_BF16;
}
break;
}
}
return inference::DataType::TYPE_INVALID;
}
TRITONSERVER_DataType
DataTypeToTriton(const inference::DataType dtype)
{
switch (dtype) {
case inference::DataType::TYPE_BOOL:
return TRITONSERVER_TYPE_BOOL;
case inference::DataType::TYPE_UINT8:
return TRITONSERVER_TYPE_UINT8;
case inference::DataType::TYPE_UINT16:
return TRITONSERVER_TYPE_UINT16;
case inference::DataType::TYPE_UINT32:
return TRITONSERVER_TYPE_UINT32;
case inference::DataType::TYPE_UINT64:
return TRITONSERVER_TYPE_UINT64;
case inference::DataType::TYPE_INT8:
return TRITONSERVER_TYPE_INT8;
case inference::DataType::TYPE_INT16:
return TRITONSERVER_TYPE_INT16;
case inference::DataType::TYPE_INT32:
return TRITONSERVER_TYPE_INT32;
case inference::DataType::TYPE_INT64:
return TRITONSERVER_TYPE_INT64;
case inference::DataType::TYPE_FP16:
return TRITONSERVER_TYPE_FP16;
case inference::DataType::TYPE_FP32:
return TRITONSERVER_TYPE_FP32;
case inference::DataType::TYPE_FP64:
return TRITONSERVER_TYPE_FP64;
case inference::DataType::TYPE_STRING:
return TRITONSERVER_TYPE_BYTES;
case inference::DataType::TYPE_BF16:
return TRITONSERVER_TYPE_BF16;
default:
break;
}
return TRITONSERVER_TYPE_INVALID;
}
inference::DataType
TritonToDataType(const TRITONSERVER_DataType dtype)
{
switch (dtype) {
case TRITONSERVER_TYPE_BOOL:
return inference::DataType::TYPE_BOOL;
case TRITONSERVER_TYPE_UINT8:
return inference::DataType::TYPE_UINT8;
case TRITONSERVER_TYPE_UINT16:
return inference::DataType::TYPE_UINT16;
case TRITONSERVER_TYPE_UINT32:
return inference::DataType::TYPE_UINT32;
case TRITONSERVER_TYPE_UINT64:
return inference::DataType::TYPE_UINT64;
case TRITONSERVER_TYPE_INT8:
return inference::DataType::TYPE_INT8;
case TRITONSERVER_TYPE_INT16:
return inference::DataType::TYPE_INT16;
case TRITONSERVER_TYPE_INT32:
return inference::DataType::TYPE_INT32;
case TRITONSERVER_TYPE_INT64:
return inference::DataType::TYPE_INT64;
case TRITONSERVER_TYPE_FP16:
return inference::DataType::TYPE_FP16;
case TRITONSERVER_TYPE_FP32:
return inference::DataType::TYPE_FP32;
case TRITONSERVER_TYPE_FP64:
return inference::DataType::TYPE_FP64;
case TRITONSERVER_TYPE_BYTES:
return inference::DataType::TYPE_STRING;
case TRITONSERVER_TYPE_BF16:
return inference::DataType::TYPE_BF16;
default:
break;
}
return inference::DataType::TYPE_INVALID;
}
}} // namespace triton::core
| 14,342 | 5,439 |
/*******************************************************************************
* Copyright 2017-2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef JIT_AVX512_CORE_CONV_WINOGRAD_KERNEL_F32_HPP
#define JIT_AVX512_CORE_CONV_WINOGRAD_KERNEL_F32_HPP
#include "c_types_map.hpp"
#include "cpu_memory.hpp"
#include "jit_generator.hpp"
#include "jit_primitive_conf.hpp"
#include "jit_avx512_common_conv_winograd_kernel_f32.hpp"
namespace mkldnn {
namespace impl {
namespace cpu {
struct _jit_avx512_core_conv_winograd_data_kernel_f32 : public jit_generator {
_jit_avx512_core_conv_winograd_data_kernel_f32(
jit_conv_winograd_conf_t ajcp)
: jcp(ajcp)
{
{
this->weights_transform_data_ker_generate();
weights_transform_data_ker
= (decltype(weights_transform_data_ker)) this->getCode();
}
{
align();
const Xbyak::uint8 *addr = getCurr();
this->input_transform_data_ker_generate();
input_transform_data_ker = (decltype(input_transform_data_ker))addr;
}
{
align();
const Xbyak::uint8 *addr = getCurr();
this->output_transform_data_ker_generate();
output_transform_data_ker
= (decltype(output_transform_data_ker))addr;
}
{
align();
const Xbyak::uint8 *addr = getCurr();
this->gemm_loop_generate();
gemm_loop_ker = (decltype(gemm_loop_ker))addr;
}
}
DECLARE_CPU_JIT_AUX_FUNCTIONS(_jit_avx512_core_conv_winograd_data_kernel_f32)
static status_t init_conf_common(jit_conv_winograd_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_wrapper &src_d,
const memory_desc_wrapper &weights_d,
const memory_desc_wrapper &dst_d);
static status_t init_conf_kernel(
jit_conv_winograd_conf_t &jcp, int dimM, int dimN, int dimK);
jit_conv_winograd_conf_t jcp;
void (*gemm_loop_ker)(float *, const float *, const float *, const int);
void (*input_transform_data_ker)(jit_wino_transform_call_s *);
void (*output_transform_data_ker)(jit_wino_transform_call_s *);
void (*weights_transform_data_ker)(jit_wino_transform_call_s *);
protected:
using reg64_t = const Xbyak::Reg64;
using reg32_t = const Xbyak::Reg32;
enum { typesize = sizeof(float) };
void gemm_loop_generate();
void input_transform_data_ker_generate();
void output_transform_data_ker_generate();
void weights_transform_data_ker_generate();
/* registers used for GEMM */
reg64_t reg_dstC = abi_param1;
reg64_t reg_srcA = abi_param2;
reg64_t reg_srcB = abi_param3;
reg64_t reg_is_beta_zero = abi_param4;
reg64_t reg_dimM_block_loop_cnt = r10;
reg64_t reg_dimK_block_loop_cnt = r11;
/* registers used for transforms*/
reg64_t param = abi_param1;
/* registers used for output_transform_data_ker */
reg64_t oreg_temp = rcx;
reg64_t oreg_Ow = r9;
reg64_t oreg_src = r11;
reg64_t oreg_tile_block = r12;
reg64_t oreg_tile_block_ur = r13;
reg64_t oreg_nb_tile_block_ur = r14;
reg64_t oreg_O = r8;
reg64_t oreg_T = r10;
reg64_t oreg_dst = r11;
reg64_t oreg_ydim = r14;
reg64_t oreg_xdim = r15;
reg64_t oreg_out_j = r12;
reg64_t oreg_bias = rbx;
reg64_t imm_addr64 = rax;
/* registers used for input_transform_data_ker */
reg64_t ireg_temp = rcx;
reg64_t ireg_jtiles = rax;
reg64_t ireg_itiles = rbx;
reg64_t ireg_I = r8;
reg64_t ireg_src = r13;
reg64_t ireg_ydim = r14;
reg64_t ireg_xdim = r15;
reg64_t ireg_inp_j = r12;
reg64_t ireg_inp_i = rdx;
reg64_t ireg_mask_j = r11;
reg64_t ireg_mask = rsi;
reg32_t ireg_mask_32 = esi;
reg64_t ireg_zero = r9;
reg64_t ireg_Iw = r9;
reg64_t ireg_T = r10;
reg64_t ireg_tile_block = r12;
reg64_t ireg_tile_block_ur = r13;
reg64_t ireg_nb_tile_block_ur = r14;
reg64_t ireg_output = r15;
/* registers used for wei transform */
reg64_t wreg_temp = rcx;
reg64_t wreg_F = r8;
reg64_t wreg_src = r9;
reg64_t wreg_MT = r15;
reg64_t wreg_M = r14;
reg64_t wreg_dst = r10;
reg64_t wreg_dst_aux = r9;
reg64_t wreg_dst_idx = r8;
reg64_t wreg_Fw = r11;
reg64_t wreg_T = r12;
reg64_t wreg_cnt_j = rdx;
reg64_t wreg_F_aux = r14;
reg64_t wreg_Fw_aux = r15;
};
struct jit_avx512_core_conv_winograd_fwd_kernel_f32
: _jit_avx512_core_conv_winograd_data_kernel_f32 {
using _jit_avx512_core_conv_winograd_data_kernel_f32::
_jit_avx512_core_conv_winograd_data_kernel_f32;
static bool post_ops_ok(jit_conv_conf_t &jcp, const primitive_attr_t &attr);
static status_t init_conf(jit_conv_winograd_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_wrapper &src_d,
const memory_desc_wrapper &weights_d,
const memory_desc_wrapper &dst_d, const primitive_attr_t &attr,
bool with_relu = false, float relu_negative_slope = 0.);
};
struct jit_avx512_core_conv_winograd_bwd_data_kernel_f32
: public _jit_avx512_core_conv_winograd_data_kernel_f32 {
using _jit_avx512_core_conv_winograd_data_kernel_f32::
_jit_avx512_core_conv_winograd_data_kernel_f32;
static status_t init_conf(jit_conv_winograd_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_wrapper &diff_src_d,
const memory_desc_wrapper &weights_d,
const memory_desc_wrapper &diff_dst_d);
};
struct jit_avx512_core_conv_winograd_bwd_weights_kernel_f32
: public jit_generator {
DECLARE_CPU_JIT_AUX_FUNCTIONS(
_jit_avx512_core_conv_winograd_bwd_weights_kernel_f32)
jit_avx512_core_conv_winograd_bwd_weights_kernel_f32(
jit_conv_winograd_conf_t ajcp)
: jcp(ajcp)
{
//******************* First iter kernel ********************//
this->gemm_loop_generate(true);
gemm_loop_ker_first_iter = (decltype(gemm_loop_ker_first_iter))this->getCode();
align();
const Xbyak::uint8 *addr = getCurr();
this->src_transform_generate();
src_transform = (decltype(src_transform))addr;
if (jcp.with_bias) {
align();
addr = getCurr();
this->diff_dst_transform_generate(true);
diff_dst_transform_wbias = (decltype(diff_dst_transform_wbias))addr;
}
align();
addr = getCurr();
this->diff_dst_transform_generate(false);
diff_dst_transform = (decltype(diff_dst_transform))addr;
if (jcp.sched_policy != WSCHED_WEI_SDGtWo && jcp.tile_block > 1) {
align();
addr = getCurr();
this->gemm_loop_generate(false);
gemm_loop_ker = (decltype(gemm_loop_ker))addr;
}
align();
addr = getCurr();
this->diff_weights_transform_generate(true);
diff_weights_transform = (decltype(diff_weights_transform))addr;
if (jcp.sched_policy == WSCHED_WEI_SDGtWo) {
align();
addr = getCurr();
this->diff_weights_transform_generate(false);
diff_weights_transform_accum =
(decltype(diff_weights_transform_accum))addr;
};
}
static status_t init_conf(jit_conv_winograd_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_wrapper &src_d,
const memory_desc_wrapper &diff_dst_d,
const memory_desc_wrapper &diff_weights_d);
jit_conv_winograd_conf_t jcp;
void (*gemm_loop_ker)(float *, const float *, const float *);
void (*gemm_loop_ker_first_iter)(float *, const float *, const float *);
void (*src_transform)(jit_wino_transform_call_s *);
void (*diff_dst_transform)(jit_wino_transform_call_s *);
void (*diff_dst_transform_wbias)(jit_wino_transform_call_s *);
void (*diff_weights_transform)(jit_wino_transform_call_s *);
void (*diff_weights_transform_accum)(jit_wino_transform_call_s *);
private:
using reg64_t = const Xbyak::Reg64;
using reg32_t = const Xbyak::Reg32;
enum { typesize = sizeof(float) };
void src_transform_generate();
void diff_dst_transform_generate(bool with_bias);
void diff_weights_transform_generate(bool first_tile);
/*registers common to transforms*/
reg64_t reg_transp = abi_param1;
reg64_t reg_ti = rbx;
reg64_t reg_tj = rcx;
reg64_t reg_src = r8;
reg64_t reg_dst = r9;
reg64_t reg_G = rsi; /*TODO: check if this is ok*/
reg64_t reg_temp = rsi;
/*registers common to src/diff_dst transform*/
reg64_t reg_I = r10;
reg64_t reg_ydim = r11;
reg64_t reg_xdim = r12;
reg64_t reg_src_offset = r13;
reg64_t reg_zero = r14;
reg64_t reg_tile_count = r15;
reg64_t reg_maski = rsi;
reg32_t reg_maski_32 = esi;
reg64_t reg_maskj = rdx;
reg64_t reg_T = rax;
reg64_t reg_oc_ur = rax;
reg64_t reg_ic_simd = r14;
reg64_t reg_bias = r10;
void gemm_loop_generate(bool is_first_tile);
reg64_t reg_dstC = abi_param1;
reg64_t reg_srcA = abi_param2;
reg64_t reg_srcB = abi_param3;
reg64_t reg_dimM_block_loop_cnt = r9;
reg64_t reg_dimN_block_loop_cnt = r10;
reg64_t reg_nb_dimN_bcast_ur = r11;
reg64_t reg_dimK_block_loop_cnt = r12;
};
}
}
}
#endif
| 10,043 | 4,009 |
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode {
int value;
TreeNode *left;
TreeNode *right;
public:
TreeNode(int val) : value(val) {}
};
class Solution {
public:
void printAncestorsByValue(TreeNode *root, int x) {
stack<TreeNode *> st;
TreeNode *p = root;
TreeNode *recent = NULL;
while (p || !st.empty()) {
if (p) {
st.push(p);
p = p->left;
} else {
TreeNode *top = st.top();
if (top->value == x) {
st.pop();
while (!st.empty()) {
cout << st.top()->value << endl;
st.pop();
}
return;
}
if (top->right && top->right != recent) {
p = top->right;
} else {
recent = top;
st.pop();
p = NULL;
}
}
}
}
};
int main() {
Solution sln;
TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
sln.printAncestorsByValue(root, 4);
sln.printAncestorsByValue(root, 5);
sln.printAncestorsByValue(root, 3);
sln.printAncestorsByValue(root, 2);
return 0;
} | 1,225 | 443 |
// Copyright (c) 2015-2017 Francisco Jose Tapia
// Copyright (c) 2020 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <hpx/local/init.hpp>
#include <hpx/modules/testing.hpp>
#include <hpx/parallel/algorithms/detail/insertion_sort.hpp>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
using hpx::parallel::v1::detail::insertion_sort;
void test01()
{
unsigned A[] = {7, 4, 23, 15, 17, 2, 24, 13, 8, 3, 11, 16, 6, 14, 21, 5, 1,
12, 19, 22, 25, 8};
insertion_sort(&A[0], &A[22]);
for (unsigned i = 0; i < 21; i++)
{
HPX_TEST(A[i] <= A[i + 1]);
}
unsigned B[] = {1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19,
20, 21, 23, 24, 25};
insertion_sort(&B[0], &B[22]);
for (unsigned i = 0; i < 21; i++)
{
HPX_TEST(B[i] <= B[i + 1]);
}
unsigned C[] = {27, 26, 25, 23, 22, 21, 19, 18, 17, 16, 15, 14, 13, 11, 10,
9, 8, 7, 6, 5, 3, 2};
insertion_sort(&C[0], &C[22]);
for (unsigned i = 0; i < 21; i++)
{
HPX_TEST(C[i] <= C[i + 1]);
}
unsigned D[] = {
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4};
insertion_sort(&D[0], &D[22]);
for (unsigned i = 0; i < 21; i++)
{
HPX_TEST(D[i] <= D[i + 1]);
}
unsigned F[100];
for (unsigned i = 0; i < 100; i++)
F[i] = std::rand() % 1000;
insertion_sort(&F[0], &F[100]);
for (unsigned i = 0; i < 99; i++)
{
HPX_TEST(F[i] <= F[i + 1]);
}
constexpr unsigned NG = 10000;
unsigned G[NG];
for (unsigned i = 0; i < NG; i++)
G[i] = std::rand() % 1000;
insertion_sort(&G[0], &G[NG]);
for (unsigned i = 0; i < NG - 1; i++)
{
HPX_TEST(G[i] <= G[i + 1]);
}
}
void test02()
{
typedef typename std::vector<std::uint64_t>::iterator iter_t;
#if defined(HPX_DEBUG)
constexpr std::uint32_t NELEM = 667;
#else
constexpr std::uint32_t NELEM = 6667;
#endif
std::vector<std::uint64_t> A;
A.reserve(NELEM + 2000);
for (std::uint32_t i = 0; i < 1000; ++i)
A.push_back(0);
for (std::uint32_t i = 0; i < NELEM; ++i)
A.push_back(NELEM - i);
for (std::uint32_t i = 0; i < 1000; ++i)
A.push_back(0);
insertion_sort(A.begin() + 1000, A.begin() + (1000 + NELEM));
for (iter_t it = A.begin() + 1000; it != A.begin() + (1000 + NELEM); ++it)
{
HPX_TEST((*(it - 1)) <= (*it));
}
HPX_TEST(A[998] == 0 && A[999] == 0 && A[1000 + NELEM] == 0 &&
A[1001 + NELEM] == 0);
//------------------------------------------------------------------------
A.clear();
A.reserve(NELEM + 2000);
for (std::uint32_t i = 0; i < 1000; ++i)
A.push_back(999999999);
for (std::uint32_t i = 0; i < NELEM; ++i)
A.push_back(NELEM - i);
for (std::uint32_t i = 0; i < 1000; ++i)
A.push_back(999999999);
insertion_sort(A.begin() + 1000, A.begin() + (1000 + NELEM));
for (iter_t it = A.begin() + 1001; it != A.begin() + (1000 + NELEM); ++it)
{
HPX_TEST((*(it - 1)) <= (*it));
}
HPX_TEST(A[998] == 999999999 && A[999] == 999999999 &&
A[1000 + NELEM] == 999999999 && A[1001 + NELEM] == 999999999);
}
int hpx_main(hpx::program_options::variables_map& vm)
{
unsigned int seed = (unsigned int) std::time(nullptr);
if (vm.count("seed"))
seed = vm["seed"].as<unsigned int>();
std::cout << "using seed: " << seed << std::endl;
std::srand(seed);
test01();
test02();
return hpx::local::finalize();
}
int main(int argc, char* argv[])
{
// add command line option which controls the random number generator seed
using namespace hpx::program_options;
options_description desc_commandline(
"Usage: " HPX_APPLICATION_STRING " [options]");
desc_commandline.add_options()("seed,s", value<unsigned int>(),
"the random number generator seed to use for this run");
// By default this test should run on all available cores
std::vector<std::string> const cfg = {"hpx.os_threads=all"};
// Initialize and run HPX
hpx::local::init_params init_args;
init_args.desc_cmdline = desc_commandline;
init_args.cfg = cfg;
HPX_TEST_EQ_MSG(hpx::local::init(hpx_main, argc, argv, init_args), 0,
"HPX main exited with non-zero status");
return hpx::util::report_errors();
}
| 4,601 | 2,187 |
// BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
#define FILENAME(line) FILENAME_FOR_EXCEPTIONS("src/libawkward/builder/ArrayBuilder.cpp", line)
#include <sstream>
#include <stdexcept>
#include "awkward/common.h"
#include "awkward/Content.h"
#include "awkward/builder/ArrayBuilderOptions.h"
#include "awkward/builder/Builder.h"
#include "awkward/builder/UnknownBuilder.h"
#include "awkward/builder/ArrayBuilder.h"
namespace awkward {
ArrayBuilder::ArrayBuilder(const ArrayBuilderOptions& options)
: builder_(UnknownBuilder::fromempty(options)) { }
const std::string
ArrayBuilder::to_buffers(BuffersContainer& container, int64_t& form_key_id) const {
return builder_.get()->to_buffers(container, form_key_id);
}
int64_t
ArrayBuilder::length() const {
return builder_.get()->length();
}
void
ArrayBuilder::clear() {
if (builder_) {
builder_.get()->clear();
}
}
void
ArrayBuilder::null() {
maybeupdate(builder_.get()->null());
}
void
ArrayBuilder::boolean(bool x) {
maybeupdate(builder_.get()->boolean(x));
}
void
ArrayBuilder::integer(int64_t x) {
maybeupdate(builder_.get()->integer(x));
}
void
ArrayBuilder::real(double x) {
maybeupdate(builder_.get()->real(x));
}
void
ArrayBuilder::complex(std::complex<double> x) {
maybeupdate(builder_.get()->complex(x));
}
void
ArrayBuilder::datetime(int64_t x, const std::string& unit) {
maybeupdate(builder_.get()->datetime(x, unit));
}
void
ArrayBuilder::timedelta(int64_t x, const std::string& unit) {
maybeupdate(builder_.get()->timedelta(x, unit));
}
void
ArrayBuilder::bytestring(const char* x) {
maybeupdate(builder_.get()->string(x, -1, no_encoding));
}
void
ArrayBuilder::bytestring(const char* x, int64_t length) {
maybeupdate(builder_.get()->string(x, length, no_encoding));
}
void
ArrayBuilder::bytestring(const std::string& x) {
bytestring(x.c_str(), (int64_t)x.length());
}
void
ArrayBuilder::string(const char* x) {
maybeupdate(builder_.get()->string(x, -1, utf8_encoding));
}
void
ArrayBuilder::string(const char* x, int64_t length) {
maybeupdate(builder_.get()->string(x, length, utf8_encoding));
}
void
ArrayBuilder::string(const std::string& x) {
string(x.c_str(), (int64_t)x.length());
}
void
ArrayBuilder::beginlist() {
maybeupdate(builder_.get()->beginlist());
}
void
ArrayBuilder::endlist() {
BuilderPtr tmp = builder_.get()->endlist();
if (tmp.get() == nullptr) {
throw std::invalid_argument(
std::string("endlist doesn't match a corresponding beginlist")
+ FILENAME(__LINE__));
}
maybeupdate(tmp);
}
void
ArrayBuilder::begintuple(int64_t numfields) {
maybeupdate(builder_.get()->begintuple(numfields));
}
void
ArrayBuilder::index(int64_t index) {
maybeupdate(builder_.get()->index(index));
}
void
ArrayBuilder::endtuple() {
maybeupdate(builder_.get()->endtuple());
}
void
ArrayBuilder::beginrecord() {
beginrecord_fast(nullptr);
}
void
ArrayBuilder::beginrecord_fast(const char* name) {
maybeupdate(builder_.get()->beginrecord(name, false));
}
void
ArrayBuilder::beginrecord_check(const char* name) {
maybeupdate(builder_.get()->beginrecord(name, true));
}
void
ArrayBuilder::beginrecord_check(const std::string& name) {
beginrecord_check(name.c_str());
}
void
ArrayBuilder::field_fast(const char* key) {
builder_.get()->field(key, false);
}
void
ArrayBuilder::field_check(const char* key) {
builder_.get()->field(key, true);
}
void
ArrayBuilder::field_check(const std::string& key) {
field_check(key.c_str());
}
void
ArrayBuilder::endrecord() {
maybeupdate(builder_.get()->endrecord());
}
void
ArrayBuilder::maybeupdate(const BuilderPtr tmp) {
if (tmp && tmp.get() != builder_.get()) {
builder_ = std::move(tmp);
}
}
const char* ArrayBuilder::no_encoding = nullptr;
const char* ArrayBuilder::utf8_encoding = "utf-8";
}
////////// extern C interface
uint8_t awkward_ArrayBuilder_length(void* arraybuilder,
int64_t* result) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
*result = obj->length();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_clear(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->clear();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_null(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->null();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_boolean(void* arraybuilder,
bool x) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->boolean(x);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_integer(void* arraybuilder,
int64_t x) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->integer(x);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_real(void* arraybuilder,
double x) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->real(x);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_complex(void* arraybuilder,
double real,
double imag) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->complex(std::complex<double>(real, imag));
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_datetime(void* arraybuilder,
int64_t x,
const char* unit) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
std::string unit_str(unit);
try {
obj->datetime(x, unit_str);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_timedelta(void* arraybuilder,
int64_t x,
const char* unit) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
std::string unit_str(unit);
try {
obj->timedelta(x, unit_str);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_bytestring(void* arraybuilder,
const char* x) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->bytestring(x);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_bytestring_length(void* arraybuilder,
const char* x,
int64_t length) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->bytestring(x, length);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_string(void* arraybuilder,
const char* x) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->string(x);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_string_length(void* arraybuilder,
const char* x,
int64_t length) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->string(x, length);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_beginlist(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->beginlist();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_endlist(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->endlist();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_begintuple(void* arraybuilder,
int64_t numfields) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->begintuple(numfields);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_index(void* arraybuilder,
int64_t index) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->index(index);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_endtuple(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->endtuple();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_beginrecord(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->beginrecord();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_beginrecord_fast(void* arraybuilder,
const char* name) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->beginrecord_fast(name);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_beginrecord_check(void* arraybuilder,
const char* name) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->beginrecord_check(name);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_field_fast(void* arraybuilder,
const char* key) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->field_fast(key);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_field_check(void* arraybuilder,
const char* key) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->field_check(key);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_endrecord(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->endrecord();
}
catch (...) {
return 1;
}
return 0;
}
| 11,163 | 3,786 |
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbEllipsoidAdapter.h"
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#pragma GCC diagnostic ignored "-Wshadow"
#include "ossim/base/ossimEllipsoid.h"
#pragma GCC diagnostic pop
#else
#include "ossim/base/ossimEllipsoid.h"
#endif
namespace otb
{
EllipsoidAdapter::EllipsoidAdapter()
{
m_Ellipsoid = new ossimEllipsoid();
}
EllipsoidAdapter::~EllipsoidAdapter()
{
if (m_Ellipsoid != nullptr)
{
delete m_Ellipsoid;
}
}
void EllipsoidAdapter::XYZToLonLatHeight(double x, double y, double z, double& lon, double& lat, double& h) const
{
// Note the lat/lon convension for ossim vs lon/lat for OTB
m_Ellipsoid->XYZToLatLonHeight(x, y, z, lat, lon, h);
}
void EllipsoidAdapter::LonLatHeightToXYZ(double lon, double lat, double h, double& x, double& y, double& z) const
{
// Note the lat/lon convension for ossim vs lon/lat for OTB
m_Ellipsoid->latLonHeightToXYZ(lat, lon, h, x, y, z);
}
} // namespace otb
| 1,787 | 641 |
$NetBSD$
Support SunOS/gcc.
--- src/hotspot/os_cpu/solaris_x86/atomic_solaris_x86.hpp.orig 2019-01-08 09:40:30.000000000 +0000
+++ src/hotspot/os_cpu/solaris_x86/atomic_solaris_x86.hpp
@@ -27,11 +27,65 @@
// For Sun Studio - implementation is in solaris_x86_64.il.
+#ifdef __GNUC__
+inline int32_t _Atomic_add(int32_t add_value, volatile int32_t* dest) {
+ int32_t rv = add_value;
+ __asm__ volatile ("lock xaddl %0,(%2)"
+ : "=r" (rv)
+ : "0" (rv), "r" (dest)
+ : "cc", "memory");
+ return rv + add_value;
+}
+inline int64_t _Atomic_add_long(int64_t add_value, volatile int64_t* dest) {
+ int64_t rv = add_value;
+ __asm__ volatile ("lock xaddq %0,(%2)"
+ : "=r" (rv)
+ : "0" (rv), "r" (dest)
+ : "cc", "memory");
+ return rv + add_value;
+}
+inline int32_t _Atomic_xchg(int32_t exchange_value, volatile int32_t* dest) {
+ __asm__ __volatile__ ("xchgl (%2),%0"
+ : "=r" (exchange_value)
+ : "0" (exchange_value), "r" (dest)
+ : "memory");
+ return exchange_value;
+}
+inline int64_t _Atomic_xchg_long(int64_t exchange_value, volatile int64_t* dest) {
+ __asm__ __volatile__ ("xchgq (%2),%0"
+ : "=r" (exchange_value)
+ : "0" (exchange_value), "r" (dest)
+ : "memory");
+ return exchange_value;
+}
+inline int8_t _Atomic_cmpxchg_byte(int8_t exchange_value, volatile int8_t* dest, int8_t compare_value) {
+ __asm__ volatile ("lock cmpxchgb %1,(%3)"
+ : "=a" (exchange_value)
+ : "q" (exchange_value), "a" (compare_value), "r" (dest)
+ : "cc", "memory");
+ return exchange_value;
+}
+inline int32_t _Atomic_cmpxchg(int32_t exchange_value, volatile int32_t* dest, int32_t compare_value) {
+ __asm__ volatile ("lock cmpxchgl %1,(%3)"
+ : "=a" (exchange_value)
+ : "q" (exchange_value), "a" (compare_value), "r" (dest)
+ : "cc", "memory");
+ return exchange_value;
+}
+inline int64_t _Atomic_cmpxchg_long(int64_t exchange_value, volatile int64_t* dest, int64_t compare_value) {
+ __asm__ volatile ("lock cmpxchgq %1,(%3)"
+ : "=a" (exchange_value)
+ : "q" (exchange_value), "a" (compare_value), "r" (dest)
+ : "cc", "memory");
+ return exchange_value;
+}
+#else
extern "C" {
int32_t _Atomic_add(int32_t add_value, volatile int32_t* dest);
int64_t _Atomic_add_long(int64_t add_value, volatile int64_t* dest);
int32_t _Atomic_xchg(int32_t exchange_value, volatile int32_t* dest);
+ int64_t _Atomic_xchg_long(int64_t exchange_value, volatile int64_t* dest);
int8_t _Atomic_cmpxchg_byte(int8_t exchange_value, volatile int8_t* dest,
int8_t compare_value);
int32_t _Atomic_cmpxchg(int32_t exchange_value, volatile int32_t* dest,
@@ -39,6 +93,7 @@ extern "C" {
int64_t _Atomic_cmpxchg_long(int64_t exchange_value, volatile int64_t* dest,
int64_t compare_value);
}
+#endif
template<size_t byte_size>
struct Atomic::PlatformAdd
@@ -83,8 +138,6 @@ inline T Atomic::PlatformXchg<4>::operat
reinterpret_cast<int32_t volatile*>(dest)));
}
-extern "C" int64_t _Atomic_xchg_long(int64_t exchange_value, volatile int64_t* dest);
-
template<>
template<typename T>
inline T Atomic::PlatformXchg<8>::operator()(T exchange_value,
| 3,568 | 1,468 |
#include "Entity.h"
namespace Engine
{
//[junk_enable /]
char* CBaseEntity::GetPlayerName()
{
if (IsPlayer())
{
static PlayerInfo Info;
if (Interfaces::Engine()->GetPlayerInfo(EntIndex(), &Info))
return Info.m_szPlayerName;
}
return "";
}
bool CBaseEntity::IsPlayer()
{
typedef bool(__thiscall* IsPlayerFn)(void*);
return GetMethod<IsPlayerFn>(this, 152)(this);
}
bool CBaseEntity::IsValid()
{
return (!IsDead() && GetHealth() > 0 && !IsDormant());
}
bool CBaseEntity::IsDead()
{
BYTE LifeState = *(PBYTE)((DWORD)this + Offset::Entity::m_lifeState);
return (LifeState != LIFE_ALIVE);
}
Vector CBaseEntity::GetOrigin() {
return *(Vector*)((DWORD)this + Offset::Entity::m_vecOrigin);
}
bool CBaseEntity::IsVisible(CBaseEntity* pLocalEntity)
{
if (!pLocalEntity->IsValid())
return false;
Vector vSrcOrigin = pLocalEntity->GetEyePosition();
if (vSrcOrigin.IsZero() || !vSrcOrigin.IsValid())
return false;
BYTE bHitBoxCheckVisible[6] = {
HITBOX_HEAD,
HITBOX_BODY,
HITBOX_RIGHT_FOOT,
HITBOX_LEFT_FOOT,
HITBOX_RIGHT_HAND,
HITBOX_LEFT_HAND,
};
CTraceFilter filter;
filter.pSkip = pLocalEntity;
for (int nHit = 0; nHit < 6; nHit++)
{
Vector vHitBox = GetHitboxPosition(bHitBoxCheckVisible[nHit]);
if (vHitBox.IsZero() || !vHitBox.IsValid())
continue;
trace_t tr;
Ray_t ray;
ray.Init(vSrcOrigin, vHitBox);
Interfaces::EngineTrace()->TraceRay(ray, PlayerVisibleMask, &filter, &tr);
if (tr.m_pEnt == (IClientEntity*)this && !tr.allsolid)
return true;
}
return false;
}
bool CBaseEntity::HasHelmet()
{
return *(bool*)((DWORD)this + Offset::Entity::m_bHasHelmet);
}
bool CBaseEntity::HasDefuser()
{
return *(bool*)((DWORD)this + Offset::Entity::m_bHasDefuser);
}
bool* CBaseEntity::IsSpotted()
{
return (bool*)((DWORD)this + Offset::Entity::m_bSpotted);
}
int CBaseEntity::GetFovStart()
{
return *(PINT)((DWORD)this + Offset::Entity::m_iFOVStart);
}
int CBaseEntity::GetFlags()
{
return *(PINT)((DWORD)this + Offset::Entity::m_fFlags);
}
int CBaseEntity::GetHealth()
{
return *(PINT)((DWORD)this + Offset::Entity::m_iHealth);
}
int CBaseEntity::GetArmor()
{
return *(PINT)((DWORD)this + Offset::Entity::m_ArmorValue);
}
int CBaseEntity::GetTeam()
{
return *(PINT)((DWORD)this + Offset::Entity::m_iTeamNum);
}
float CBaseEntity::GetLowerBodyYaw()
{
return *(float*)((DWORD)this + Offset::Entity::m_flLowerBodyYawTarget);
}
float CBaseEntity::GetSimTime()
{
return *(float*)((DWORD)this + Offset::Entity::m_flSimulationTime);
}
int CBaseEntity::GetShotsFired()
{
return *(PINT)((DWORD)this + (DWORD)Offset::Entity::m_iShotsFired);
}
int CBaseEntity::GetIsScoped()
{
return *(bool*)((DWORD)this + (DWORD)Offset::Entity::m_bIsScoped);
}
int CBaseEntity::GetTickBase()
{
return *(PINT)((DWORD)this + (DWORD)Offset::Entity::m_nTickBase);
}
ObserverMode_t CBaseEntity::GetObserverMode()
{
return *(ObserverMode_t*)((DWORD)this + (DWORD)Offset::Entity::m_iObserverMode);
}
PVOID CBaseEntity::GetObserverTarget()
{
return (PVOID)*(PDWORD)((DWORD)this + (DWORD)Offset::Entity::m_hObserverTarget);
}
PVOID CBaseEntity::GetActiveWeapon()
{
return (PVOID)((DWORD)this + (DWORD)Offset::Entity::m_hActiveWeapon);
}
CBaseWeapon* CBaseEntity::GetBaseWeapon()
{
return (CBaseWeapon*)Interfaces::EntityList()->GetClientEntityFromHandle((PVOID)*(PDWORD)GetActiveWeapon());
}
UINT* CBaseEntity::GetWeapons()
{
// DT_BasePlayer -> m_hMyWeapons
return (UINT*)((DWORD)this + Offset::Entity::m_hMyWeapons);
}
UINT* CBaseEntity::GetWearables()
{
return (UINT*)((DWORD)this + Offset::Entity::m_hMyWearables);
}
CBaseViewModel* CBaseEntity::GetViewModel()
{
// DT_BasePlayer -> m_hViewModel
return (CBaseViewModel*)Interfaces::EntityList()->GetClientEntityFromHandle((PVOID)*(PDWORD)((DWORD)this + Offset::Entity::m_hViewModel));
}
Vector* CBaseEntity::GetVAngles()
{
return (Vector*)((uintptr_t)this + Offset::Entity::deadflag + 0x4);
}
Vector CBaseEntity::GetAimPunchAngle()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_aimPunchAngle);
}
Vector CBaseEntity::GetViewPunchAngle()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_viewPunchAngle);
}
Vector CBaseEntity::GetVelocity()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_vecVelocity);
}
Vector CBaseEntity::GetViewOffset()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_vecViewOffset);
}
Vector CBaseEntity::GetEyePosition()
{
return GetRenderOrigin() + GetViewOffset();
}
QAngle CBaseEntity::GetEyeAngles()
{
return *reinterpret_cast<QAngle*>((DWORD)this + Offset::Entity::m_angEyeAngles);
}
Vector CBaseEntity::GetBonePosition(int nBone)
{
Vector vRet;
matrix3x4_t MatrixArray[MAXSTUDIOBONES];
if (!SetupBones(MatrixArray, MAXSTUDIOBONES, BONE_USED_BY_HITBOX, Interfaces::GlobalVars()->curtime))
return vRet;
matrix3x4_t HitboxMatrix = MatrixArray[nBone];
vRet = Vector(HitboxMatrix[0][3], HitboxMatrix[1][3], HitboxMatrix[2][3]);
return vRet;
}
studiohdr_t* CBaseEntity::GetStudioModel()
{
const model_t* model = nullptr;
model = GetModel();
if (!model)
return nullptr;
studiohdr_t* pStudioModel = Interfaces::ModelInfo()->GetStudioModel(model);
if (!pStudioModel)
return nullptr;
return pStudioModel;
}
mstudiobone_t* CBaseEntity::GetBone(int nBone)
{
mstudiobone_t* pBoneBox = nullptr;
studiohdr_t* pStudioModel = GetStudioModel();
if (!pStudioModel)
return pBoneBox;
mstudiobone_t* pBone = pStudioModel->pBone(nBone);
if (!pBone)
return nullptr;
return pBone;
}
mstudiobbox_t* CBaseEntity::GetHitBox(int nHitbox)
{
if (nHitbox < 0 || nHitbox >= HITBOX_MAX)
return nullptr;
mstudiohitboxset_t* pHitboxSet = nullptr;
mstudiobbox_t* pHitboxBox = nullptr;
pHitboxSet = GetHitBoxSet();
if (!pHitboxSet)
return pHitboxBox;
pHitboxBox = pHitboxSet->pHitbox(nHitbox);
if (!pHitboxBox)
return nullptr;
return pHitboxBox;
}
mstudiohitboxset_t* CBaseEntity::GetHitBoxSet()
{
studiohdr_t* pStudioModel = nullptr;
mstudiohitboxset_t* pHitboxSet = nullptr;
pStudioModel = GetStudioModel();
if (!pStudioModel)
return pHitboxSet;
pHitboxSet = pStudioModel->pHitboxSet(0);
if (!pHitboxSet)
return nullptr;
return pHitboxSet;
}
Vector CBaseEntity::GetHitboxPosition(int nHitbox)
{
matrix3x4_t MatrixArray[MAXSTUDIOBONES];
Vector vRet, vMin, vMax;
vRet = Vector(0, 0, 0);
mstudiobbox_t* pHitboxBox = GetHitBox(nHitbox);
if (!pHitboxBox || !IsValid())
return vRet;
if (!SetupBones(MatrixArray, MAXSTUDIOBONES, BONE_USED_BY_HITBOX, 0/*Interfaces::GlobalVars()->curtime*/))
return vRet;
if (!pHitboxBox->m_Bone || !pHitboxBox->m_vBbmin.IsValid() || !pHitboxBox->m_vBbmax.IsValid())
return vRet;
VectorTransform(pHitboxBox->m_vBbmin, MatrixArray[pHitboxBox->m_Bone], vMin);
VectorTransform(pHitboxBox->m_vBbmax, MatrixArray[pHitboxBox->m_Bone], vMax);
vRet = (vMin + vMax) * 0.5f;
return vRet;
}
int CBaseViewModel::GetModelIndex()
{
// DT_BaseViewModel -> m_nModelIndex
return *(int*)((DWORD)this + Offset::Entity::m_nModelIndex);
}
void CBaseViewModel::SetModelIndex(int nModelIndex)
{
VirtualFn(void)(PVOID, int);
GetMethod< OriginalFn >(this, 75)(this, nModelIndex);
// DT_BaseViewModel -> m_nModelIndex
//*(int*)( ( DWORD )this + Offset::Entity::m_nModelIndex ) = nModelIndex;
}
void CBaseViewModel::SetWeaponModel(const char* Filename, IClientEntity* Weapon)
{
typedef void(__thiscall* SetWeaponModelFn)(void*, const char*, IClientEntity*);
return GetMethod<SetWeaponModelFn>(this, 242)(this, Filename, Weapon);
}
DWORD CBaseViewModel::GetOwner()
{
// DT_BaseViewModel -> m_hOwner
return *(PDWORD)((DWORD)this + Offset::Entity::m_hOwner);
}
DWORD CBaseViewModel::GetWeapon()
{
// DT_BaseViewModel -> m_hWeapon
return *(PDWORD)((DWORD)this + Offset::Entity::m_hWeapon);
}
} | 8,034 | 3,540 |
/**************************************************************
*
* 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"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#include <sfx2/viewfrm.hxx>
#include <svl/style.hxx>
#include <vcl/msgbox.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
#include <docsh.hxx>
#include <charfmt.hxx>
//#ifndef _FLDMGR_HXX //autogen
//#include <fldmgr.hxx>
//#endif
#include <docstyle.hxx>
#include "fldbas.hxx"
#include "lineinfo.hxx"
#include "globals.hrc"
#include "linenum.hrc"
#include "linenum.hxx"
#include "uitool.hxx"
#include <IDocumentStylePoolAccess.hxx>
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwLineNumberingDlg::SwLineNumberingDlg(SwView *pVw) :
SfxSingleTabDialog(&pVw->GetViewFrame()->GetWindow(), 0, 0),
pSh(pVw->GetWrtShellPtr())
{
// TabPage erzeugen
SetTabPage(SwLineNumberingPage::Create(this, *(SfxItemSet*)0));
GetOKButton()->SetClickHdl(LINK(this, SwLineNumberingDlg, OKHdl));
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
__EXPORT SwLineNumberingDlg::~SwLineNumberingDlg()
{
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
IMPL_LINK( SwLineNumberingDlg, OKHdl, Button *, EMPTYARG )
{
if (GetOKButton()->IsEnabled())
{
SfxTabPage* pCurPage = GetTabPage();
if( pCurPage )
pCurPage->FillItemSet(*(SfxItemSet*)0);
EndDialog( RET_OK );
}
return 0;
}
/*-----------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
SwLineNumberingPage::SwLineNumberingPage( Window* pParent,
const SfxItemSet& rSet )
: SfxTabPage(pParent, SW_RES(TP_LINENUMBERING), rSet),
aNumberingOnCB ( this, SW_RES( CB_NUMBERING_ON )),
aDisplayFL ( this, SW_RES( FL_DISPLAY )),
aCharStyleFT ( this, SW_RES( FT_CHAR_STYLE )),
aCharStyleLB ( this, SW_RES( LB_CHAR_STYLE )),
aFormatFT ( this, SW_RES( FT_FORMAT )),
aFormatLB ( this, SW_RES( LB_FORMAT ), INSERT_NUM_EXTENDED_TYPES),
aPosFT ( this, SW_RES( FT_POS )),
aPosLB ( this, SW_RES( LB_POS )),
aOffsetFT ( this, SW_RES( FT_OFFSET )),
aOffsetMF ( this, SW_RES( MF_OFFSET )),
aNumIntervalFT ( this, SW_RES( FT_NUM_INVERVAL )),
aNumIntervalNF ( this, SW_RES( NF_NUM_INVERVAL )),
aNumRowsFT ( this, SW_RES( FT_NUM_ROWS )),
aDivisorFL ( this, SW_RES( FL_DIVISOR )),
aDivisorFT ( this, SW_RES( FT_DIVISOR )),
aDivisorED ( this, SW_RES( ED_DIVISOR )),
aDivIntervalFT ( this, SW_RES( FT_DIV_INTERVAL )),
aDivIntervalNF ( this, SW_RES( NF_DIV_INTERVAL )),
aDivRowsFT ( this, SW_RES( FT_DIV_ROWS )),
aCountFL ( this, SW_RES( FL_COUNT )),
aCountEmptyLinesCB ( this, SW_RES( CB_COUNT_EMPTYLINES )),
aCountFrameLinesCB ( this, SW_RES( CB_COUNT_FRAMELINES )),
aRestartEachPageCB ( this, SW_RES( CB_RESTART_PAGE ))
{
String sIntervalName = aDivIntervalFT.GetAccessibleName();
sIntervalName += String::CreateFromAscii("(");
sIntervalName += aDivRowsFT.GetAccessibleName();
sIntervalName += String::CreateFromAscii(")");
aDivIntervalNF.SetAccessibleName(sIntervalName);
sIntervalName = aNumIntervalFT.GetAccessibleName();
sIntervalName += String::CreateFromAscii("(");
sIntervalName += aNumRowsFT.GetAccessibleName();
sIntervalName += String::CreateFromAscii(")");
aNumIntervalNF.SetAccessibleName(sIntervalName);
FreeResource();
SwLineNumberingDlg *pDlg = (SwLineNumberingDlg *)GetParent();
pSh = pDlg->GetWrtShell();
// Zeichenvorlagen
::FillCharStyleListBox(aCharStyleLB, pSh->GetView().GetDocShell());
}
/*-----------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
__EXPORT SwLineNumberingPage::~SwLineNumberingPage()
{
}
/*-----------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
SfxTabPage* __EXPORT SwLineNumberingPage::Create( Window* pParent, const SfxItemSet& rSet )
{
return new SwLineNumberingPage( pParent, rSet );
}
/*-----------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
void __EXPORT SwLineNumberingPage::Reset( const SfxItemSet& )
{
const SwLineNumberInfo &rInf = pSh->GetLineNumberInfo();
IDocumentStylePoolAccess* pIDSPA = pSh->getIDocumentStylePoolAccess();
String sStyleName(rInf.GetCharFmt( *pIDSPA )->GetName());
const sal_uInt16 nPos = aCharStyleLB.GetEntryPos(sStyleName);
if (nPos != LISTBOX_ENTRY_NOTFOUND)
aCharStyleLB.SelectEntryPos(nPos);
else
{
if (sStyleName.Len())
{
aCharStyleLB.InsertEntry(sStyleName);
aCharStyleLB.SelectEntry(sStyleName);
}
}
// Format
// SwFldMgr aMgr( pSh );
sal_uInt16 nSelFmt = rInf.GetNumType().GetNumberingType();
// sal_uInt16 nCnt = aMgr.GetFormatCount( TYP_SEQFLD, sal_False );
// for( sal_uInt16 i = 0; i < nCnt; i++)
// {
// aFormatLB.InsertEntry(aMgr.GetFormatStr( TYP_SEQFLD, i));
// sal_uInt16 nFmtId = aMgr.GetFormatId( TYP_SEQFLD, i );
// aFormatLB.SetEntryData( i, (void*)nFmtId );
// if( nFmtId == nSelFmt )
// aFormatLB.SelectEntryPos( i );
// }
aFormatLB.SelectNumberingType(nSelFmt);
// if ( !aFormatLB.GetSelectEntryCount() )
// aFormatLB.SelectEntryPos(aFormatLB.GetEntryCount() - 1);
// Position
aPosLB.SelectEntryPos((sal_uInt16)rInf.GetPos());
// Offset
sal_uInt16 nOffset = rInf.GetPosFromLeft();
if (nOffset == USHRT_MAX)
nOffset = 0;
aOffsetMF.SetValue(aOffsetMF.Normalize(nOffset), FUNIT_TWIP);
// Numerierungsoffset
aNumIntervalNF.SetValue(rInf.GetCountBy());
// Teiler
aDivisorED.SetText(rInf.GetDivider());
// Teileroffset
aDivIntervalNF.SetValue(rInf.GetDividerCountBy());
// Zaehlen
aCountEmptyLinesCB.Check(rInf.IsCountBlankLines());
aCountFrameLinesCB.Check(rInf.IsCountInFlys());
aRestartEachPageCB.Check(rInf.IsRestartEachPage());
aNumberingOnCB.Check(rInf.IsPaintLineNumbers());
aNumberingOnCB.SetClickHdl(LINK(this, SwLineNumberingPage, LineOnOffHdl));
aDivisorED.SetModifyHdl(LINK(this, SwLineNumberingPage, ModifyHdl));
ModifyHdl();
LineOnOffHdl();
}
/*--------------------------------------------------------------------
Beschreibung: Modify
--------------------------------------------------------------------*/
IMPL_LINK( SwLineNumberingPage, ModifyHdl, Edit *, EMPTYARG )
{
sal_Bool bHasValue = aDivisorED.GetText().Len() != 0;
aDivIntervalFT.Enable(bHasValue);
aDivIntervalNF.Enable(bHasValue);
aDivRowsFT.Enable(bHasValue);
return 0;
}
/*--------------------------------------------------------------------
Beschreibung: On/Off
--------------------------------------------------------------------*/
IMPL_LINK( SwLineNumberingPage, LineOnOffHdl, CheckBox *, EMPTYARG )
{
sal_Bool bEnable = aNumberingOnCB.IsChecked();
aCharStyleFT.Enable(bEnable);
aCharStyleLB.Enable(bEnable);
aFormatFT.Enable(bEnable);
aFormatLB.Enable(bEnable);
aPosFT.Enable(bEnable);
aPosLB.Enable(bEnable);
aOffsetFT.Enable(bEnable);
aOffsetMF.Enable(bEnable);
aNumIntervalFT.Enable(bEnable);
aNumIntervalNF.Enable(bEnable);
aNumRowsFT.Enable(bEnable);
aDisplayFL.Enable(bEnable);
aDivisorFT.Enable(bEnable);
aDivisorED.Enable(bEnable);
aDivIntervalFT.Enable(bEnable);
aDivIntervalNF.Enable(bEnable);
aDivRowsFT.Enable(bEnable);
aDivisorFL.Enable(bEnable);
aCountEmptyLinesCB.Enable(bEnable);
aCountFrameLinesCB.Enable(bEnable);
aRestartEachPageCB.Enable(bEnable);
aCountFL.Enable(bEnable);
return 0;
}
/*-----------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
sal_Bool __EXPORT SwLineNumberingPage::FillItemSet( SfxItemSet& )
{
SwLineNumberInfo aInf(pSh->GetLineNumberInfo());
// Zeichenvorlagen
String sCharFmtName(aCharStyleLB.GetSelectEntry());
SwCharFmt *pCharFmt = pSh->FindCharFmtByName(sCharFmtName);
if (!pCharFmt)
{
SfxStyleSheetBasePool* pPool = pSh->GetView().GetDocShell()->GetStyleSheetPool();
SfxStyleSheetBase* pBase;
pBase = pPool->Find(sCharFmtName, SFX_STYLE_FAMILY_CHAR);
if(!pBase)
pBase = &pPool->Make(sCharFmtName, SFX_STYLE_FAMILY_CHAR);
pCharFmt = ((SwDocStyleSheet*)pBase)->GetCharFmt();
}
if (pCharFmt)
aInf.SetCharFmt(pCharFmt);
// Format
SvxNumberType aType;
aType.SetNumberingType(aFormatLB.GetSelectedNumberingType());
aInf.SetNumType(aType);
// Position
aInf.SetPos((LineNumberPosition)aPosLB.GetSelectEntryPos());
// Offset
aInf.SetPosFromLeft((sal_uInt16)aOffsetMF.Denormalize(aOffsetMF.GetValue(FUNIT_TWIP)));
// Numerierungsoffset
aInf.SetCountBy((sal_uInt16)aNumIntervalNF.GetValue());
// Teiler
aInf.SetDivider(aDivisorED.GetText());
// Teileroffset
aInf.SetDividerCountBy((sal_uInt16)aDivIntervalNF.GetValue());
// Zaehlen
aInf.SetCountBlankLines(aCountEmptyLinesCB.IsChecked());
aInf.SetCountInFlys(aCountFrameLinesCB.IsChecked());
aInf.SetRestartEachPage(aRestartEachPageCB.IsChecked());
aInf.SetPaintLineNumbers(aNumberingOnCB.IsChecked());
pSh->SetLineNumberInfo(aInf);
return sal_False;
}
| 10,452 | 3,834 |
// -*- C++ -*-
// Copyright (C) 2005, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 2, 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
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING. If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
// MA 02111-1307, USA.
// As a special exception, you may use this file as part of a free
// software library without restriction. Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to
// produce an executable, this file does not by itself cause the
// resulting executable to be covered by the GNU General Public
// License. This exception does not however invalidate any other
// reasons why the executable file might be covered by the GNU General
// Public License.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file pop_test.hpp
* Contains a generic pop test.
*/
#ifndef PB_DS_POP_TEST_HPP
#define PB_DS_POP_TEST_HPP
#include <iterator>
#include <testsuite_allocator.h>
#include <ext/pb_ds/detail/type_utils.hpp>
#include <performance/io/xml_formatter.hpp>
#include <common_type/priority_queue/string_form.hpp>
namespace pb_ds
{
namespace test
{
template<typename It>
class pop_test
{
public:
pop_test(It ins_b, size_t ins_vn, size_t ins_vs, size_t ins_vm)
: m_ins_b(ins_b), m_ins_vn(ins_vn), m_ins_vs(ins_vs), m_ins_vm(ins_vm)
{ }
template<typename Cntnr>
void
operator()(Cntnr);
private:
pop_test(const pop_test&);
const It m_ins_b;
const size_t m_ins_vn;
const size_t m_ins_vs;
const size_t m_ins_vm;
};
template<typename It>
template<typename Cntnr>
void
pop_test<It>::
operator()(Cntnr)
{
typedef xml_result_set_performance_formatter formatter_type;
formatter_type res_set_fmt(string_form<Cntnr>::name(),
string_form<Cntnr>::desc());
for (size_t i = 0; m_ins_vn + i * m_ins_vs < m_ins_vm; ++i)
{
const size_t ins_size = m_ins_vn + i * m_ins_vs;
It ins_it_b = m_ins_b;
It ins_it_e = m_ins_b;
std::advance(ins_it_e, ins_size);
typedef __gnu_test::tracker_allocator_counter counter_type;
__gnu_test::tracker_allocator<char> alloc;
const size_t init_mem = counter_type::get_allocation_count()
- counter_type::get_deallocation_count();
Cntnr cntnr;
for (It ins_it = ins_it_b; ins_it != ins_it_e; ++ins_it)
cntnr.push(ins_it->first);
while (cntnr.size() > 1)
cntnr.pop();
const size_t final_mem = counter_type::get_allocation_count()
- counter_type::get_deallocation_count();
assert(final_mem > init_mem);
const size_t delta_mem = final_mem - init_mem;
res_set_fmt.add_res(ins_size, static_cast<double>(delta_mem));
}
}
} // namespace test
} // namespace pb_ds
#endif
| 4,013 | 1,351 |
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file Module.ccp
* @author Frank Dellaert
* @author Alex Cunningham
* @author Andrew Melim
* @author Richard Roberts
**/
#include "Module.h"
#include "FileWriter.h"
#include "TypeAttributesTable.h"
#include "utilities.h"
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <algorithm>
using namespace std;
using namespace wrap;
using namespace BOOST_SPIRIT_CLASSIC_NS;
namespace bl = boost::lambda;
namespace fs = boost::filesystem;
/* ************************************************************************* */
// We parse an interface file into a Module object.
// The grammar is defined using the boost/spirit combinatorial parser.
// For example, str_p("const") parses the string "const", and the >>
// operator creates a sequence parser. The grammar below, composed of rules
// and with start rule [class_p], doubles as the specs for our interface files.
/* ************************************************************************* */
/* ************************************************************************* */
// If a number of template arguments were given, generate a number of expanded
// class names, e.g., PriorFactor -> PriorFactorPose2, and add those classes
static void handle_possible_template(vector<Class>& classes,
vector<Class>& uninstantiatedClasses,
const Class& cls, const Template& t) {
uninstantiatedClasses.push_back(cls);
if (cls.templateArgs.empty() || t.empty()) {
classes.push_back(cls);
} else {
if (cls.templateArgs.size() != 1)
throw std::runtime_error(
"In-line template instantiations only handle a single template argument");
string arg = cls.templateArgs.front();
vector<Class> classInstantiations =
(t.nrValues() > 0) ? cls.expandTemplate(arg, t.argValues()) :
cls.expandTemplate(arg, t.intList());
for(const Class& c: classInstantiations)
classes.push_back(c);
}
}
static void push_typedef_pair(vector<TypedefPair>& typedefs,
const Qualified& oldType,
const Qualified& newType,
const string& includeFile) {
typedefs.push_back(TypedefPair(oldType, newType, includeFile));
}
/* ************************************************************************* */
Module::Module(const std::string& moduleName, bool enable_verbose)
: name(moduleName), verbose(enable_verbose)
{
}
/* ************************************************************************* */
Module::Module(const string& interfacePath,
const string& moduleName, bool enable_verbose)
: name(moduleName), verbose(enable_verbose)
{
// read interface file
string interfaceFile = interfacePath + "/" + moduleName + ".h";
string contents = file_contents(interfaceFile);
// execute parsing
parseMarkup(contents);
}
/* ************************************************************************* */
void Module::parseMarkup(const std::string& data) {
// The parse imperatively :-( updates variables gradually during parse
// The one with postfix 0 are used to reset the variables after parse.
//----------------------------------------------------------------------------
// Grammar with actions that build the Class object. Actions are
// defined within the square brackets [] and are executed whenever a
// rule is successfully parsed. Define BOOST_SPIRIT_DEBUG to debug.
// The grammar is allows a very restricted C++ header
// lexeme_d turns off white space skipping
// http://www.boost.org/doc/libs/1_37_0/libs/spirit/classic/doc/directives.html
// ----------------------------------------------------------------------------
// Define Rule and instantiate basic rules
typedef rule<phrase_scanner_t> Rule;
BasicRules<phrase_scanner_t> basic;
vector<string> namespaces; // current namespace tag
string currentInclude;
// parse a full class
Class cls0(verbose),cls(verbose);
Template classTemplate;
ClassGrammar class_g(cls,classTemplate);
Rule class_p = class_g //
[assign_a(cls.namespaces_, namespaces)]
[assign_a(cls.includeFile, currentInclude)][bl::bind(
&handle_possible_template, bl::var(classes),
bl::var(uninstantiatedClasses), bl::var(cls),
bl::var(classTemplate))][clear_a(classTemplate)] //
[assign_a(cls, cls0)];
// parse "gtsam::Pose2" and add to singleInstantiation.typeList
TemplateInstantiationTypedef singleInstantiation, singleInstantiation0;
TypeListGrammar<'<','>'> typelist_g(singleInstantiation.typeList);
// typedef gtsam::RangeFactor<gtsam::Pose2, gtsam::Point2> RangeFactor2D;
TypeGrammar instantiationClass_g(singleInstantiation.class_);
Rule templateSingleInstantiation_p =
(str_p("typedef") >> instantiationClass_g >>
typelist_g >>
basic.className_p[assign_a(singleInstantiation.name_)] >>
';')
[assign_a(singleInstantiation.namespaces_, namespaces)]
[push_back_a(templateInstantiationTypedefs, singleInstantiation)]
[assign_a(singleInstantiation, singleInstantiation0)];
Qualified oldType, newType;
TypeGrammar typedefOldClass_g(oldType), typedefNewClass_g(newType);
Rule typedef_p =
(str_p("typedef") >> typedefOldClass_g >> typedefNewClass_g >>
';')
[assign_a(oldType.namespaces_, namespaces)]
[assign_a(newType.namespaces_, namespaces)]
[bl::bind(&push_typedef_pair, bl::var(typedefs), bl::var(oldType),
bl::var(newType), bl::var(currentInclude))];
// Create grammar for global functions
GlobalFunctionGrammar global_function_g(global_functions, namespaces,
currentInclude);
Rule include_p = str_p("#include") >> ch_p('<') >>
(*(anychar_p - '>'))[push_back_a(includes)]
[assign_a(currentInclude)] >>
ch_p('>');
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wuninitialized"
#endif
Rule namespace_def_p =
(str_p("namespace")
>> basic.namespace_p[push_back_a(namespaces)]
>> ch_p('{')
>> *(include_p | class_p | templateSingleInstantiation_p | typedef_p | global_function_g | namespace_def_p | basic.comments_p)
>> ch_p('}'))
[pop_a(namespaces)];
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// parse forward declaration
ForwardDeclaration fwDec0, fwDec;
Class fwParentClass;
TypeGrammar className_g(fwDec.cls);
TypeGrammar classParent_g(fwParentClass);
Rule classParent_p = (':' >> classParent_g >> ';') //
[bl::bind(&Class::assignParent, bl::var(fwDec.cls),
bl::var(fwParentClass))][clear_a(fwParentClass)];
Rule forward_declaration_p =
!(str_p("virtual")[assign_a(fwDec.isVirtual, T)])
>> str_p("class") >> className_g
>> (classParent_p | ';')
[push_back_a(forward_declarations, fwDec)]
[assign_a(cls,cls0)] // also clear class to avoid partial parse
[assign_a(fwDec, fwDec0)];
Rule module_content_p = basic.comments_p | include_p | class_p
| templateSingleInstantiation_p | forward_declaration_p
| global_function_g | namespace_def_p;
Rule module_p = *module_content_p >> !end_p;
// and parse contents
parse_info<const char*> info = parse(data.c_str(), module_p, space_p);
if(!info.full) {
printf("parsing stopped at \n%.20s\n",info.stop);
cout << "Stopped in:\n"
"class '" << cls.name_ << "'" << endl;
throw ParseFailed((int)info.length);
}
// Post-process classes for serialization markers
for(Class& cls: classes)
cls.erase_serialization();
for(Class& cls: uninstantiatedClasses)
cls.erase_serialization();
// Explicitly add methods to the classes from parents so it shows in documentation
for(Class& cls: classes)
cls.appendInheritedMethods(cls, classes);
// - Remove inherited methods for Cython classes in the pxd, otherwise Cython can't decide which one to call.
// - Only inherited nontemplateMethods_ in uninstantiatedClasses need to be removed
// because that what we serialized to the pxd.
// - However, we check against the class parent's *methods_* to avoid looking into
// its grand parent and grand-grand parent, etc., because all those are already
// added in its direct parent.
// - So this must be called *after* the above code appendInheritedMethods!!
for(Class& cls: uninstantiatedClasses)
cls.removeInheritedNontemplateMethods(uninstantiatedClasses);
// Expand templates - This is done first so that template instantiations are
// counted in the list of valid types, have their attributes and dependencies
// checked, etc.
expandedClasses = ExpandTypedefInstantiations(classes,
templateInstantiationTypedefs);
// Dependency check list
vector<string> validTypes = GenerateValidTypes(expandedClasses,
forward_declarations, typedefs);
// Check that all classes have been defined somewhere
verifyArguments<GlobalFunction>(validTypes, global_functions);
verifyReturnTypes<GlobalFunction>(validTypes, global_functions);
hasSerialiable = false;
for(const Class& cls: expandedClasses)
cls.verifyAll(validTypes,hasSerialiable);
// Create type attributes table and check validity
typeAttributes.addClasses(expandedClasses);
typeAttributes.addForwardDeclarations(forward_declarations);
for (const TypedefPair p: typedefs)
typeAttributes.addType(p.newType);
// add Eigen types as template arguments are also checked ?
vector<ForwardDeclaration> eigen;
eigen.push_back(ForwardDeclaration("Vector"));
eigen.push_back(ForwardDeclaration("Matrix"));
typeAttributes.addForwardDeclarations(eigen);
typeAttributes.checkValidity(expandedClasses);
}
/* ************************************************************************* */
void Module::generate_matlab_wrapper(const string& toolboxPath) const {
fs::create_directories(toolboxPath);
// create the unified .cpp switch file
const string wrapperName = name + "_wrapper";
string wrapperFileName = toolboxPath + "/" + wrapperName + ".cpp";
FileWriter wrapperFile(wrapperFileName, verbose, "//");
wrapperFile.oss << "#include <wrap/matlab.h>\n";
wrapperFile.oss << "#include <map>\n";
wrapperFile.oss << "\n";
// Include boost.serialization archive headers before other class headers
if (hasSerialiable) {
wrapperFile.oss << "#include <boost/archive/text_iarchive.hpp>\n";
wrapperFile.oss << "#include <boost/archive/text_oarchive.hpp>\n";
wrapperFile.oss << "#include <boost/serialization/export.hpp>\n\n";
}
// Generate includes while avoiding redundant includes
generateIncludes(wrapperFile);
// create typedef classes - we put this at the top of the wrap file so that
// collectors and method arguments can use these typedefs
for(const Class& cls: expandedClasses)
if(!cls.typedefName.empty())
wrapperFile.oss << cls.getTypedef() << "\n";
wrapperFile.oss << "\n";
// Generate boost.serialization export flags (needs typedefs from above)
if (hasSerialiable) {
for(const Class& cls: expandedClasses)
if(cls.isSerializable)
wrapperFile.oss << cls.getSerializationExport() << "\n";
wrapperFile.oss << "\n";
}
// Generate collectors and cleanup function to be called from mexAtExit
WriteCollectorsAndCleanupFcn(wrapperFile, name, expandedClasses);
// generate RTTI registry (for returning derived-most types)
WriteRTTIRegistry(wrapperFile, name, expandedClasses);
vector<string> functionNames; // Function names stored by index for switch
// create proxy class and wrapper code
for(const Class& cls: expandedClasses)
cls.matlab_proxy(toolboxPath, wrapperName, typeAttributes, wrapperFile, functionNames);
// create matlab files and wrapper code for global functions
for(const GlobalFunctions::value_type& p: global_functions)
p.second.matlab_proxy(toolboxPath, wrapperName, typeAttributes, wrapperFile, functionNames);
// finish wrapper file
wrapperFile.oss << "\n";
finish_wrapper(wrapperFile, functionNames);
wrapperFile.emit(true);
}
/* ************************************************************************* */
void Module::generate_cython_wrapper(const string& toolboxPath, const std::string& pxdImports) const {
fs::create_directories(toolboxPath);
string pxdFileName = toolboxPath + "/" + name + ".pxd";
FileWriter pxdFile(pxdFileName, verbose, "#");
pxdFile.oss << pxdImports << "\n";
emit_cython_pxd(pxdFile);
string pyxFileName = toolboxPath + "/" + name + ".pyx";
FileWriter pyxFile(pyxFileName, verbose, "#");
emit_cython_pyx(pyxFile);
}
/* ************************************************************************* */
void Module::emit_cython_pxd(FileWriter& pxdFile) const {
// headers
pxdFile.oss << "from gtsam_eigency.core cimport *\n"
"from libcpp.string cimport string\n"
"from libcpp.vector cimport vector\n"
"from libcpp.pair cimport pair\n"
"from libcpp.set cimport set\n"
"from libcpp.map cimport map\n"
"from libcpp cimport bool\n\n";
// boost shared_ptr
pxdFile.oss << "cdef extern from \"boost/shared_ptr.hpp\" namespace \"boost\":\n"
" cppclass shared_ptr[T]:\n"
" shared_ptr()\n"
" shared_ptr(T*)\n"
" T* get()\n"
" long use_count() const\n"
" T& operator*()\n\n"
" cdef shared_ptr[T] dynamic_pointer_cast[T,U](const shared_ptr[U]& r)\n"
" cdef shared_ptr[T] make_shared[T](const T& r)\n\n";
for(const TypedefPair& types: typedefs)
types.emit_cython_pxd(pxdFile);
//... wrap all classes
for (const Class& cls : uninstantiatedClasses) {
cls.emit_cython_pxd(pxdFile);
for (const Class& expCls : expandedClasses) {
bool matchingNonTemplated = !expCls.templateClass
&& expCls.pxdClassName() == cls.pxdClassName();
bool isTemplatedFromCls = expCls.templateClass
&& expCls.templateClass->pxdClassName() == cls.pxdClassName();
// ctypedef for template instantiations
if (isTemplatedFromCls) {
pxdFile.oss << "\n";
pxdFile.oss << "ctypedef " << expCls.templateClass->pxdClassName()
<< "[";
for (size_t i = 0; i < expCls.templateInstTypeList.size(); ++i)
pxdFile.oss << expCls.templateInstTypeList[i].pxdClassName()
<< ((i == expCls.templateInstTypeList.size() - 1) ? "" : ", ");
pxdFile.oss << "] " << expCls.pxdClassName() << "\n";
}
// Python wrapper class
if (isTemplatedFromCls || matchingNonTemplated) {
expCls.emit_cython_wrapper_pxd(pxdFile);
}
}
pxdFile.oss << "\n\n";
}
//... wrap global functions
for(const GlobalFunctions::value_type& p: global_functions)
p.second.emit_cython_pxd(pxdFile);
pxdFile.emit(true);
}
/* ************************************************************************* */
void Module::emit_cython_pyx(FileWriter& pyxFile) const {
// headers...
string pxdHeader = name;
pyxFile.oss << "cimport numpy as np\n"
"import numpy as npp\n"
"cimport " << pxdHeader << "\n"
"from "<< pxdHeader << " cimport shared_ptr\n"
"from "<< pxdHeader << " cimport dynamic_pointer_cast\n"
"from "<< pxdHeader << " cimport make_shared\n";
pyxFile.oss << "# C helper function that copies all arguments into a positional list.\n"
"cdef list process_args(list keywords, tuple args, dict kwargs):\n"
" cdef str keyword\n"
" cdef int n = len(args), m = len(keywords)\n"
" cdef list params = list(args)\n"
" assert len(args)+len(kwargs) == m, 'Expected {} arguments'.format(m)\n"
" try:\n"
" return params + [kwargs[keyword] for keyword in keywords[n:]]\n"
" except:\n"
" raise ValueError('Epected arguments ' + str(keywords))\n";
// import all typedefs, e.g. from gtsam_wrapper cimport Key, so we don't need to say gtsam.Key
for(const Qualified& q: Qualified::BasicTypedefs) {
pyxFile.oss << "from " << pxdHeader << " cimport " << q.pxdClassName() << "\n";
}
pyxFile.oss << "from gtsam_eigency.core cimport *\n"
"from libcpp cimport bool\n\n"
"from libcpp.pair cimport pair\n"
"from libcpp.string cimport string\n"
"from cython.operator cimport dereference as deref\n\n\n";
// all classes include all forward declarations
std::vector<Class> allClasses = expandedClasses;
for(const ForwardDeclaration& fd: forward_declarations)
allClasses.push_back(fd.cls);
for(const Class& cls: expandedClasses)
cls.emit_cython_pyx(pyxFile, allClasses);
pyxFile.oss << "\n";
//... wrap global functions
for(const GlobalFunctions::value_type& p: global_functions)
p.second.emit_cython_pyx(pyxFile);
pyxFile.emit(true);
}
/* ************************************************************************* */
void Module::generateIncludes(FileWriter& file) const {
// collect includes
vector<string> all_includes(includes);
// sort and remove duplicates
sort(all_includes.begin(), all_includes.end());
vector<string>::const_iterator last_include = unique(all_includes.begin(), all_includes.end());
vector<string>::const_iterator it = all_includes.begin();
// add includes to file
for (; it != last_include; ++it)
file.oss << "#include <" << *it << ">" << endl;
file.oss << "\n";
}
/* ************************************************************************* */
void Module::finish_wrapper(FileWriter& file, const std::vector<std::string>& functionNames) const {
file.oss << "void mexFunction(int nargout, mxArray *out[], int nargin, const mxArray *in[])\n";
file.oss << "{\n";
file.oss << " mstream mout;\n"; // Send stdout to MATLAB console
file.oss << " std::streambuf *outbuf = std::cout.rdbuf(&mout);\n\n";
file.oss << " _" << name << "_RTTIRegister();\n\n";
file.oss << " int id = unwrap<int>(in[0]);\n\n";
file.oss << " try {\n";
file.oss << " switch(id) {\n";
for(size_t id = 0; id < functionNames.size(); ++id) {
file.oss << " case " << id << ":\n";
file.oss << " " << functionNames[id] << "(nargout, out, nargin-1, in+1);\n";
file.oss << " break;\n";
}
file.oss << " }\n";
file.oss << " } catch(const std::exception& e) {\n";
file.oss << " mexErrMsgTxt((\"Exception from gtsam:\\n\" + std::string(e.what()) + \"\\n\").c_str());\n";
file.oss << " }\n";
file.oss << "\n";
file.oss << " std::cout.rdbuf(outbuf);\n"; // Restore cout
file.oss << "}\n";
}
/* ************************************************************************* */
vector<Class> Module::ExpandTypedefInstantiations(const vector<Class>& classes, const vector<TemplateInstantiationTypedef> instantiations) {
vector<Class> expandedClasses = classes;
for(const TemplateInstantiationTypedef& inst: instantiations) {
// Add the new class to the list
expandedClasses.push_back(inst.findAndExpand(classes));
}
// Remove all template classes
for(size_t i = 0; i < expandedClasses.size(); ++i)
if(!expandedClasses[i].templateArgs.empty()) {
expandedClasses.erase(expandedClasses.begin() + size_t(i));
-- i;
}
return expandedClasses;
}
/* ************************************************************************* */
vector<string> Module::GenerateValidTypes(const vector<Class>& classes, const vector<ForwardDeclaration>& forwardDeclarations, const vector<TypedefPair>& typedefs) {
vector<string> validTypes;
for(const ForwardDeclaration& fwDec: forwardDeclarations) {
validTypes.push_back(fwDec.name());
}
validTypes.push_back("void");
validTypes.push_back("string");
validTypes.push_back("int");
validTypes.push_back("bool");
validTypes.push_back("char");
validTypes.push_back("unsigned char");
validTypes.push_back("size_t");
validTypes.push_back("double");
validTypes.push_back("Vector");
validTypes.push_back("Matrix");
//Create a list of parsed classes for dependency checking
for(const Class& cls: classes) {
validTypes.push_back(cls.qualifiedName("::"));
}
for(const TypedefPair& p: typedefs) {
validTypes.push_back(p.newType.qualifiedName("::"));
}
return validTypes;
}
/* ************************************************************************* */
void Module::WriteCollectorsAndCleanupFcn(FileWriter& wrapperFile, const std::string& moduleName, const std::vector<Class>& classes) {
// Generate all collectors
for(const Class& cls: classes) {
const string matlabUniqueName = cls.qualifiedName(),
cppName = cls.qualifiedName("::");
wrapperFile.oss << "typedef std::set<boost::shared_ptr<" << cppName << ">*> "
<< "Collector_" << matlabUniqueName << ";\n";
wrapperFile.oss << "static Collector_" << matlabUniqueName <<
" collector_" << matlabUniqueName << ";\n";
}
// generate mexAtExit cleanup function
wrapperFile.oss <<
"\nvoid _deleteAllObjects()\n"
"{\n"
" mstream mout;\n" // Send stdout to MATLAB console
" std::streambuf *outbuf = std::cout.rdbuf(&mout);\n\n"
" bool anyDeleted = false;\n";
for(const Class& cls: classes) {
const string matlabUniqueName = cls.qualifiedName();
const string cppName = cls.qualifiedName("::");
const string collectorType = "Collector_" + matlabUniqueName;
const string collectorName = "collector_" + matlabUniqueName;
// The extra curly-braces around the for loops work around a limitation in MSVC (existing
// since 2005!) preventing more than 248 blocks.
wrapperFile.oss <<
" { for(" << collectorType << "::iterator iter = " << collectorName << ".begin();\n"
" iter != " << collectorName << ".end(); ) {\n"
" delete *iter;\n"
" " << collectorName << ".erase(iter++);\n"
" anyDeleted = true;\n"
" } }\n";
}
wrapperFile.oss <<
" if(anyDeleted)\n"
" cout <<\n"
" \"WARNING: Wrap modules with variables in the workspace have been reloaded due to\\n\"\n"
" \"calling destructors, call 'clear all' again if you plan to now recompile a wrap\\n\"\n"
" \"module, so that your recompiled module is used instead of the old one.\" << endl;\n"
" std::cout.rdbuf(outbuf);\n" // Restore cout
"}\n\n";
}
/* ************************************************************************* */
void Module::WriteRTTIRegistry(FileWriter& wrapperFile, const std::string& moduleName, const std::vector<Class>& classes) {
wrapperFile.oss <<
"void _" << moduleName << "_RTTIRegister() {\n"
" const mxArray *alreadyCreated = mexGetVariablePtr(\"global\", \"gtsam_" + moduleName + "_rttiRegistry_created\");\n"
" if(!alreadyCreated) {\n"
" std::map<std::string, std::string> types;\n";
for(const Class& cls: classes) {
if(cls.isVirtual)
wrapperFile.oss <<
" types.insert(std::make_pair(typeid(" << cls.qualifiedName("::") << ").name(), \"" << cls.qualifiedName(".") << "\"));\n";
}
wrapperFile.oss << "\n";
wrapperFile.oss <<
" mxArray *registry = mexGetVariable(\"global\", \"gtsamwrap_rttiRegistry\");\n"
" if(!registry)\n"
" registry = mxCreateStructMatrix(1, 1, 0, NULL);\n"
" typedef std::pair<std::string, std::string> StringPair;\n"
" for(const StringPair& rtti_matlab: types) {\n"
" int fieldId = mxAddField(registry, rtti_matlab.first.c_str());\n"
" if(fieldId < 0)\n"
" mexErrMsgTxt(\"gtsam wrap: Error indexing RTTI types, inheritance will not work correctly\");\n"
" mxArray *matlabName = mxCreateString(rtti_matlab.second.c_str());\n"
" mxSetFieldByNumber(registry, 0, fieldId, matlabName);\n"
" }\n"
" if(mexPutVariable(\"global\", \"gtsamwrap_rttiRegistry\", registry) != 0)\n"
" mexErrMsgTxt(\"gtsam wrap: Error indexing RTTI types, inheritance will not work correctly\");\n"
" mxDestroyArray(registry);\n"
" \n"
" mxArray *newAlreadyCreated = mxCreateNumericMatrix(0, 0, mxINT8_CLASS, mxREAL);\n"
" if(mexPutVariable(\"global\", \"gtsam_" + moduleName + "_rttiRegistry_created\", newAlreadyCreated) != 0)\n"
" mexErrMsgTxt(\"gtsam wrap: Error indexing RTTI types, inheritance will not work correctly\");\n"
" mxDestroyArray(newAlreadyCreated);\n"
" }\n"
"}\n"
"\n";
}
/* ************************************************************************* */
void Module::generate_python_wrapper(const string& toolboxPath) const {
fs::create_directories(toolboxPath);
// create the unified .cpp switch file
const string wrapperName = name + "_python";
string wrapperFileName = toolboxPath + "/" + wrapperName + ".cpp";
FileWriter wrapperFile(wrapperFileName, verbose, "//");
wrapperFile.oss << "#include <boost/python.hpp>\n\n";
wrapperFile.oss << "using namespace boost::python;\n";
wrapperFile.oss << "BOOST_PYTHON_MODULE(" + name + ")\n";
wrapperFile.oss << "{\n";
// write out classes
for(const Class& cls: expandedClasses) {
cls.python_wrapper(wrapperFile);
}
// write out global functions
for(const GlobalFunctions::value_type& p: global_functions)
p.second.python_wrapper(wrapperFile);
// finish wrapper file
wrapperFile.oss << "}\n";
wrapperFile.emit(true);
}
/* ************************************************************************* */
| 26,276 | 8,117 |
#define APPLICATIONMAIN
#include "CApplication.h"
#include "AvaraGL.h"
#include "Preferences.h"
#include "Types.h"
#include <SDL2/SDL.h>
#include <fstream>
#include <nanogui/nanogui.h>
#include <string>
#include <vector>
CApplication::CApplication(std::string title, int width, int height) :
nanogui::Screen(nanogui::Vector2i(width, height), title) {
char *prefPath = SDL_GetPrefPath("Avaraline", "Avara");
jsonPath = std::string(prefPath) + "prefs.json";
SDL_free(prefPath);
std::ifstream in(jsonPath);
if (in.fail()) {
// No prefs file, use defaults.
prefs = defaultPrefs;
} else {
in >> prefs;
for (json::iterator it = defaultPrefs.begin(); it != defaultPrefs.end(); ++it) {
if (prefs.find(it.key()) == prefs.end()) {
// A new key was added to defaultPrefs, add it to prefs.
prefs[it.key()] = it.value();
}
}
}
gApplication = this;
InitContext();
setResizeCallback([this](nanogui::Vector2i newSize) { this->WindowResized(newSize.x, newSize.y); });
}
CApplication::~CApplication() {}
void CApplication::Done() {
std::ofstream out(jsonPath);
out << std::setw(4) << prefs << std::endl;
}
void CApplication::BroadcastCommand(int theCommand) {
if (!DoCommand(theCommand)) {
for (auto win : windowList) {
if (win->DoCommand(theCommand))
break;
}
}
}
void CApplication::PrefChanged(std::string name) {
for (auto win : windowList) {
win->PrefChanged(name);
}
}
void CApplication::drawContents() {
Idle();
DrawContents();
}
bool CApplication::handleSDLEvent(SDL_Event &event) {
// By default, give nanogui first crack at events.
bool handled = nanogui::Screen::handleSDLEvent(event);
if (!handled) {
handled = HandleEvent(event);
}
return handled;
}
std::string CApplication::String(const std::string name) {
return prefs[name];
}
long CApplication::Number(const std::string name) {
return prefs[name];
}
json CApplication::Get(const std::string name) {
return prefs[name];
}
void CApplication::Set(const std::string name, const std::string value) {
prefs[name] = value;
PrefChanged(name);
}
void CApplication::Set(const std::string name, long value) {
prefs[name] = value;
PrefChanged(name);
}
void CApplication::Set(const std::string name, json value) {
prefs[name] = value;
PrefChanged(name);
}
| 2,495 | 834 |
/// @file
/// @copyright Copyright (c) 2017, Cycling '74
/// @author Timothy Place
/// @license Usage of this file and its contents is governed by the MIT License
#include "DspFilters/ChebyshevII.h"
using namespace Dsp::ChebyshevII::Design;
#include "../filter.h"
class chebyshev : public filter<chebyshev,false,true> {
public:
MIN_DESCRIPTION { "Nth-order Chebyshev Type-II filter"
"This object is intended mainly for plotting. "
"For audio filtering, see <o>filter.chebyshev2~</o>. " };
MIN_TAGS { "filters" };
MIN_AUTHOR { "Cycling '74" };
MIN_RELATED { "filterdesign, filterdetail, slide, filter.chebyshev2~" };
inlet<> m_inlet { this, "(number) input" };
outlet<> m_outlet { this, "(number) output" };
chebyshev(const atoms& args = {})
: filter(args)
{}
attribute<double> m_samplerate { this, "samplerate", 44100.0,
description { "Sampling frequency of the filter." },
};
double samplerate() override {
return m_samplerate;
}
message<> number { this, "number", "Stream of numbers to be filtered.",
MIN_FUNCTION {
double x[1] { args[0] };
double* y = x;
// we use the pending filter because this object is threadsafe using a copy
if (m_update_pending) {
m_filter = std::move(m_filter_pending);
m_update_pending = false;
}
m_filter->process(1, &y);
m_outlet.send(*y);
return {};
}
};
};
MIN_EXTERNAL(chebyshev);
| 1,408 | 592 |
/*
* Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Runtime/Map.h>
namespace JS {
Map* Map::create(GlobalObject& global_object)
{
return global_object.heap().allocate<Map>(global_object, *global_object.map_prototype());
}
Map::Map(Object& prototype)
: Object(prototype)
{
}
Map::~Map()
{
}
void Map::visit_edges(Cell::Visitor& visitor)
{
Object::visit_edges(visitor);
for (auto& value : m_entries) {
visitor.visit(value.key);
visitor.visit(value.value);
}
}
}
| 586 | 232 |
#include "pch.h"
#include "libCloudundancy/UtilityComponents/FunctionCallers/Member/VoidOneArgMemberFunctionCaller.h" | 118 | 41 |
#include "dialog.h"
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QSpinBox>
#include <QPushButton>
#include <QGridLayout>
#include <QSettings>
#include <QApplication>
#include <QtSerialPort/QSerialPortInfo>
QT_USE_NAMESPACE
/*
#define ConstBaudRate 115200 //230400 для arduino nano, 115200 для Digispark
#define TypeSensor 1 // 1 = ADNS_2610, MCS-12085
// 2 = ADNS_5020
*/
/*
//ARRAY_WIDTH, ARRAY_HEIGHT: definitions of pixel array
//MCS-12085, ADNS-2610 = 18*18, ADNS5020 15*15
//MaskBitData: колич. бит в потоке данных (нужен для создания корректной палитры)
//MCS-12085, ADNS-2610 = 6bit = 64, ADNS5020 = 7bit = 128
#if TypeSensor == 1
#define ARRAY_WIDTH 18
#define ARRAY_HEIGHT 18
#define MaskBitData 64
#elif TypeSensor == 2
#define ARRAY_WIDTH 15
#define ARRAY_HEIGHT 15
#define MaskBitData 128
#else
#error
#endif
*/
int RegArrayWidth =1;
int RegArrayHeight =1;
QImage image(5, 5, QImage::Format_Indexed8);
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, responseSize(0)
, serialPortLabel(new QLabel(tr("Serial port:")))
, serialPortComboBox(new QComboBox())
, BaudRateComboBox(new QComboBox())
, waitResponseLabel(new QLabel(tr("Wait, msec:")))
, waitResponseSpinBox(new QSpinBox())
, trafficLabel(new QLabel(tr("No traffic.")))
, statusLabel(new QLabel(tr("Status: Not running.")))
, runButton(new QPushButton(tr("Start")))
{
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
serialPortComboBox->addItem(info.portName());
BaudRateComboBox->addItem("230400");
BaudRateComboBox->addItem("115200");
m_sSettingsFile = QApplication::applicationDirPath() + "/settings.ini";
waitResponseSpinBox->setRange(0, 10000);
waitResponseSpinBox->setValue(20);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(serialPortLabel, 0, 0);
mainLayout->addWidget(serialPortComboBox, 0, 1);
mainLayout->addWidget(BaudRateComboBox, 0, 2);
mainLayout->addWidget(runButton, 0, 3);
mainLayout->addWidget(waitResponseLabel, 1, 0);
mainLayout->addWidget(waitResponseSpinBox, 1, 1);
mainLayout->addWidget(trafficLabel, 2, 0, 1, 4);
mainLayout->addWidget(statusLabel, 3, 0, 1, 5);
setLayout(mainLayout);
setWindowTitle(tr("Mouse Sensor"));
loadSettings();
serialPortComboBox->setFocus();
timer.setSingleShot(true);
connect(runButton, SIGNAL(clicked()),
this, SLOT(sendRequest()));
connect(&serial, SIGNAL(readyRead()),
this, SLOT(readResponse()));
connect(&timer, SIGNAL(timeout()),
this, SLOT(processTimeout()));
connect(serialPortComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(saveSettings()));
connect(BaudRateComboBox, SIGNAL(currentTextChanged(QString)),
this, SLOT(saveSettings()));
}
void Dialog::sendRequest()
{
serial.close();
saveSettings();
serial.setPortName(serialPortComboBox->currentText());
serial.setBaudRate(BaudRateComboBox->currentText().toInt());
serial.setDataBits( QSerialPort::Data8 );
serial.setParity( QSerialPort::NoParity );
serial.setStopBits( QSerialPort::OneStop );
serial.setFlowControl( QSerialPort::NoFlowControl );
if (!serial.open(QIODevice::ReadWrite))
{
processError(tr("Can't open %1, error code %2")
.arg(serial.portName()).arg(serial.error()));
return;
}
setControlsEnabled(false);
statusLabel->setText(tr("Status: Running, connected to port %1.")
.arg(serialPortComboBox->currentText()));
timer.start(waitResponseSpinBox->value());
}
void Dialog::readResponse()
{
// response.append(serial.readBufferSize());
if (!timer.isActive())
timer.start(waitResponseSpinBox->value());
response.append(serial.readAll());
}
void Dialog::processTimeout()
{
int IndexData;
setControlsEnabled(true);
if(response.size() != responseSize || responseSize ==0)
{
if(response.size() ==(15*15 +7))
{
resizeImage(&image,15,15,128);
}
else if(response.size() ==(18*18 +7))
{
resizeImage(&image,18,18,64);
}
else
{
trafficLabel->setText(tr("response size:%1")
.arg(response.size()));
}
}
else
{
IndexData = RegArrayWidth * RegArrayHeight;
trafficLabel->setText(tr("Max: %1, Min: %2, Ave: %3, Shut: %4, Squal: %5, LaserPower: %6")
.arg((int)*(response.data()+IndexData+1)) //MAX_PIXEL
.arg((unsigned char)*(response.data()+IndexData+2)) //MIN_PIXEL
.arg((unsigned char)*(response.data()+IndexData+3)) //AVE
.arg((unsigned int)(((unsigned char)*(response.data()+IndexData+4)*256)+((unsigned char)*(response.data()+IndexData+5))))
.arg((int)*(response.data()+IndexData)) //SQUAL
.arg((unsigned char)*(response.data()+IndexData+6))); //LASER_POWER
for (int y = 0; y < image.height(); y++)
{
//memcpy(rawData + y*RegArrayWidth, response.data() + y*RegArrayWidth, image.bytesPerLine());
memcpy(image.scanLine(y), response.data() + y*RegArrayWidth, image.bytesPerLine());
}
statusLabel->setPixmap(QPixmap::fromImage(image.scaled(180*2, 180*2))); // Show result on a form
/*
unsigned char rawData[ARRAY_WIDTH*ARRAY_HEIGHT];
trafficLabel->setText("\n\r");
int nIndex = 0;
for (int y = 0; y < RegArrayHeight; ++y)
{
// dump one row
for (int x = 0; x < RegArrayWidth; ++x)
{
// format nicely
if (rawData[nIndex] < 10)
{
trafficLabel->setText(trafficLabel->text() + tr("0%1 ").arg(rawData[nIndex++]));
}
else
{
trafficLabel->setText(trafficLabel->text() + tr("%1 ").arg(rawData[nIndex++]));
}
}
// next row
trafficLabel->setText(trafficLabel->text() + "\n\r");
}
*/
}
response.clear();
}
void Dialog::processError(const QString &error)
{
setControlsEnabled(true);
statusLabel->setText(tr("Status: Not running, %1.").arg(error));
trafficLabel->setText(tr("No traffic."));
}
void Dialog::setControlsEnabled(bool enable)
{
runButton->setEnabled(enable);
serialPortComboBox->setEnabled(enable);
waitResponseSpinBox->setEnabled(enable);
}
void Dialog::resizeImage(QImage *image, int ArrayWidth, int ArrayHeight, int Mask)
{
RegArrayWidth = ArrayWidth; RegArrayHeight = ArrayHeight;
responseSize = response.size();
//масштабировать палитру и размер для image
QVector<QRgb> palette; //палитра
for(int i = 0; i < Mask; ++i) palette.append(qRgb(i*(256/Mask),i*(256/Mask),i*(256/Mask)));
QImage newImage(RegArrayWidth, RegArrayHeight, QImage::Format_Indexed8);
//newImage.fill(qRgb(255, 255, 255));
newImage.setColorTable(palette);
*image = newImage;
}
void Dialog::loadSettings()
{
QSettings settings(m_sSettingsFile, QSettings::IniFormat);
QString sPortName = settings.value("portName", "").toString();
QString sBaudRate = settings.value("portBaudRate", "").toString();
qint8 idx = serialPortComboBox->findText(sPortName);
if (idx) {
serialPortComboBox->setCurrentIndex(idx);
}
BaudRateComboBox->setCurrentText(sBaudRate);
}
void Dialog::saveSettings()
{
QSettings settings(m_sSettingsFile, QSettings::IniFormat);
QString sPortName = serialPortComboBox->currentText();
settings.setValue("portName", sPortName);
QString sBaudRate = BaudRateComboBox->currentText();
settings.setValue("portBaudRate", sBaudRate);
}
| 7,198 | 2,818 |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2015, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/structured_light.hpp>
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
static const char* keys =
{ "{@path | | Path of the folder where the captured pattern images will be save }"
"{@proj_width | | Projector width }"
"{@proj_height | | Projector height }" };
static void help()
{
cout << "\nThis example shows how to use the \"Structured Light module\" to acquire a graycode pattern"
"\nCall (with the two cams connected):\n"
"./example_structured_light_cap_pattern <path> <proj_width> <proj_height> \n"
<< endl;
}
int main( int argc, char** argv )
{
structured_light::GrayCodePattern::Params params;
CommandLineParser parser( argc, argv, keys );
String path = parser.get<String>( 0 );
params.width = parser.get<int>( 1 );
params.height = parser.get<int>( 2 );
if( path.empty() || params.width < 1 || params.height < 1 )
{
help();
return -1;
}
// Set up GraycodePattern with params
Ptr<structured_light::GrayCodePattern> graycode = structured_light::GrayCodePattern::create( params );
// Storage for pattern
vector<Mat> pattern;
graycode->generate( pattern );
cout << pattern.size() << " pattern images + 2 images for shadows mask computation to acquire with both cameras"
<< endl;
// Generate the all-white and all-black images needed for shadows mask computation
Mat white;
Mat black;
graycode->getImagesForShadowMasks( black, white );
pattern.push_back( white );
pattern.push_back( black );
// Setting pattern window on second monitor (the projector's one)
namedWindow( "Pattern Window", WINDOW_NORMAL );
resizeWindow( "Pattern Window", params.width, params.height );
moveWindow( "Pattern Window", params.width + 316, -20 );
setWindowProperty( "Pattern Window", WND_PROP_FULLSCREEN, WINDOW_FULLSCREEN );
// Open camera number 1, using libgphoto2
VideoCapture cap1( CAP_GPHOTO2 );
if( !cap1.isOpened() )
{
// check if cam1 opened
cout << "cam1 not opened!" << endl;
help();
return -1;
}
// Open camera number 2
VideoCapture cap2( 1 );
if( !cap2.isOpened() )
{
// check if cam2 opened
cout << "cam2 not opened!" << endl;
help();
return -1;
}
// Turning off autofocus
cap1.set( CAP_PROP_SETTINGS, 1 );
cap2.set( CAP_PROP_SETTINGS, 1 );
int i = 0;
while( i < (int) pattern.size() )
{
cout << "Waiting to save image number " << i + 1 << endl << "Press any key to acquire the photo" << endl;
imshow( "Pattern Window", pattern[i] );
Mat frame1;
Mat frame2;
cap1 >> frame1; // get a new frame from camera 1
cap2 >> frame2; // get a new frame from camera 2
if( ( frame1.data ) && ( frame2.data ) )
{
Mat tmp;
cout << "cam 1 size: " << Size( ( int ) cap1.get( CAP_PROP_FRAME_WIDTH ), ( int ) cap1.get( CAP_PROP_FRAME_HEIGHT ) )
<< endl;
cout << "cam 2 size: " << Size( ( int ) cap2.get( CAP_PROP_FRAME_WIDTH ), ( int ) cap2.get( CAP_PROP_FRAME_HEIGHT ) )
<< endl;
cout << "zoom cam 1: " << cap1.get( CAP_PROP_ZOOM ) << endl << "zoom cam 2: " << cap2.get( CAP_PROP_ZOOM )
<< endl;
cout << "focus cam 1: " << cap1.get( CAP_PROP_FOCUS ) << endl << "focus cam 2: " << cap2.get( CAP_PROP_FOCUS )
<< endl;
cout << "Press enter to save the photo or an other key to re-acquire the photo" << endl;
namedWindow( "cam1", WINDOW_NORMAL );
resizeWindow( "cam1", 640, 480 );
namedWindow( "cam2", WINDOW_NORMAL );
resizeWindow( "cam2", 640, 480 );
// Moving window of cam2 to see the image at the same time with cam1
moveWindow( "cam2", 640 + 75, 0 );
// Resizing images to avoid issues for high resolution images, visualizing them as grayscale
resize( frame1, tmp, Size( 640, 480 ) );
cvtColor( tmp, tmp, COLOR_RGB2GRAY );
imshow( "cam1", tmp );
resize( frame2, tmp, Size( 640, 480 ) );
cvtColor( tmp, tmp, COLOR_RGB2GRAY );
imshow( "cam2", tmp );
bool save1 = false;
bool save2 = false;
int key = waitKey( 0 );
// Pressing enter, it saves the output
if( key == 13 )
{
ostringstream name;
name << i + 1;
save1 = imwrite( path + "pattern_cam1_im" + name.str() + ".png", frame1 );
save2 = imwrite( path + "pattern_cam2_im" + name.str() + ".png", frame2 );
if( ( save1 ) && ( save2 ) )
{
cout << "pattern cam1 and cam2 images number " << i + 1 << " saved" << endl << endl;
i++;
}
else
{
cout << "pattern cam1 and cam2 images number " << i + 1 << " NOT saved" << endl << endl << "Retry, check the path"<< endl << endl;
}
}
// Pressing escape, the program closes
if( key == 27 )
{
cout << "Closing program" << endl;
}
}
else
{
cout << "No frame data, waiting for new frame" << endl;
}
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
} | 7,334 | 2,342 |
#include "visualization/viz-data-collector.h"
#include <mutex>
#include <string>
#include <tuple>
#include <unordered_map>
#include <Eigen/Core>
#include <aslam/common/unique-id.h>
#include <maplab-common/accessors.h>
#include <maplab-common/macros.h>
namespace visualization {
namespace internal {
const VizDataCollectorImpl::SlotId VizDataCollectorImpl::kCommonSlotId =
VizDataCollectorImpl::SlotId::Random();
VizDataCollectorImpl::VizChannelGroup* VizDataCollectorImpl::getSlot(
const SlotId& slot_id) {
CHECK(slot_id.isValid());
std::lock_guard<std::mutex> lock(m_channel_groups_);
return common::getValuePtr(channel_groups_, slot_id);
}
const VizDataCollectorImpl::VizChannelGroup* VizDataCollectorImpl::getSlot(
const SlotId& slot_id) const {
CHECK(slot_id.isValid());
std::lock_guard<std::mutex> lock(m_channel_groups_);
return common::getValuePtr(channel_groups_, slot_id);
}
VizDataCollectorImpl::VizChannelGroup*
VizDataCollectorImpl::getSlotAndCreateIfNecessary(const SlotId& slot_id) {
CHECK(slot_id.isValid());
std::lock_guard<std::mutex> lock(m_channel_groups_);
SlotIdSlotMap::iterator iterator;
bool inserted = false;
std::tie(iterator, inserted) = channel_groups_.emplace(
std::piecewise_construct, std::make_tuple(slot_id), std::make_tuple());
return &iterator->second;
}
void VizDataCollectorImpl::removeSlotIfAvailable(const SlotId& slot_id) {
CHECK(slot_id.isValid());
std::lock_guard<std::mutex> lock(m_channel_groups_);
channel_groups_.erase(slot_id);
}
bool VizDataCollectorImpl::hasSlot(const SlotId& slot_id) const {
return (getSlot(slot_id) != nullptr);
}
bool VizDataCollectorImpl::hasChannel(
const SlotId& slot_id, const std::string& channel_name) const {
const VizChannelGroup* slot;
if ((slot = getSlot(slot_id)) == nullptr) {
return false;
}
return slot->hasChannel(channel_name);
}
} // namespace internal
} // namespace visualization
| 1,947 | 704 |
/**
* @brief implementation of a power network used in calculations
*
* @file powerNet.cpp
* @author Luiz Victor Linhares Rocha
* @date 2018-09-22
* @copyright 2018
*/
#include <utility>
#include <iostream>
#include "powerNet.hpp"
#include "barra.hpp"
#include "branch.hpp"
#include "admitanceCalc.hpp"
#include "../util/complexutils.h"
namespace neuralFlux {
PowerNet::PowerNet(uint64_t id):
Identifiable(id),
m_nPQ(0),
m_nPV(0),
m_nSlack(0) {
}
PowerNet::~PowerNet() {
m_branches.clear(); // branches must be deleted first
m_busBars.clear();
}
PowerNet::PowerNet(const PowerNet& net):
Identifiable(net.getId()),
m_nPQ(0),
m_nPV(0),
m_nSlack(0) {
for (size_t i = 0, n = net.getNBars() ; i < n ; i++) {
const BarPtr bar = net.getBarByIndex(i);
if (bar->getType() == Bar::Slack) {
this->addSlackBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
} else if (bar->getType() == Bar::PV) {
this->addPVBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
} else {
this->addPQBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
}
}
for (size_t i = 0, n = net.getNBranches(); i < n; i++) {
const BranchPtr branch = net.getBranchByIndex(i);
this->connect(
branch->getK()->getId(),
branch->getM()->getId(),
branch->getRkm(),
branch->getXkm(),
branch->getBshkm(),
branch->getA(),
branch->getPhi());
}
}
PowerNet& PowerNet::operator=(const PowerNet& net) {
for (size_t i = 0, n = net.getNBars(); i < n; i++) {
const BarPtr bar = net.getBarByIndex(i);
if (bar->getType() == Bar::Slack) {
this->addSlackBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
} else if (bar->getType() == Bar::PV) {
this->addPVBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
} else {
this->addPQBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
}
}
for (size_t i = 0, n = net.getNBranches(); i < n; i++) {
const BranchPtr branch = net.getBranchByIndex(i);
this->connect(
branch->getK()->getId(),
branch->getM()->getId(),
branch->getRkm(),
branch->getXkm(),
branch->getBshkm(),
branch->getA(),
branch->getPhi());
}
return *this;
}
void PowerNet::addSlackBar(
const size_t id,
const double v,
const double teta,
const double p,
const double q,
const double bsh
) {
if (checkBarIdExists(id)) {
throw std::runtime_error("cannot create same id bar in the net");
}
m_busBars.push_back(Bar::newSlack(v, teta, id, p, q, bsh));
++m_nSlack;
sortBackBar();
}
void PowerNet::addPQBar(
const size_t id,
const double p,
const double q,
const double v,
const double teta,
const double bsh
) {
if (checkBarIdExists(id)) {
throw std::runtime_error("cannot create same id bar in the net");
}
m_busBars.push_back(Bar::newPQ(p, q, id, v, teta, bsh));
++m_nPQ;
sortBackBar();
}
void PowerNet::addBar(
const Bar::barType type,
const size_t id,
const double v,
const double teta,
const double p,
const double q,
const double bsh
) {
switch (type) {
case Bar::Slack:
addSlackBar(id, v, teta, p, q, bsh);
break;
case Bar::PV:
addPVBar(id, p, v, teta, q, bsh);
break;
case Bar::PQ:
addPQBar(id, p, q, v, teta, bsh);
break;
default:
throw std::runtime_error("unsuported bar type");
}
}
void PowerNet::addPVBar(
const size_t id,
const double p,
const double v,
const double teta,
const double q,
const double bsh
) {
if (checkBarIdExists(id)) {
throw std::runtime_error("cannot create same id bar in the net");
}
m_busBars.push_back(Bar::newPV(p, v, id, teta, q, bsh));
++m_nPV;
sortBackBar();
}
void PowerNet::connect(
size_t k,
size_t m,
const double rkm,
const double xkm,
const double bshkm,
const double a,
const double phi
) {
connectByIndex(
getBarIndex(k),
getBarIndex(m),
rkm,
xkm,
bshkm,
a,
phi);
}
void PowerNet::connectByIndex(
size_t k,
size_t m,
const double rkm,
const double xkm,
const double bshkm,
const double a,
const double phi
) {
if (k == m) {
throw std::invalid_argument("cannot connect same bars");
}
if (k > m) {
std::swap<size_t>(k, m);
}
try { // TODO(lvrocha): do this more eficiently
getBranchIndexByIndex(k, m);
throw std::invalid_argument("cannot connect same bars twice");
} catch(std::runtime_error e) {
m_branches.push_back(Branch::connectBranch(m_busBars[k], m_busBars[m], rkm, xkm, bshkm, a, phi));
sortBackBranch();
}
}
void PowerNet::deleteBranch(uint64_t id) {
deleteBranchByIndex(getBranchIndex(id));
}
void PowerNet::deleteBranchByIndex(size_t i) {
if (m_branches.size() <= i) {
throw std::runtime_error("branch does not exist");
}
for (size_t _i = i+1, n = m_branches.size() ; _i < n ; _i++) {
m_branches[_i-1] = m_branches[_i];
}
m_branches.pop_back();
}
void PowerNet::deleteBranch(uint64_t kId, uint64_t mId) {
deleteBranchByIndex(getBranchIndex(kId, mId));
}
void PowerNet::deleteBranchByBarIndex(size_t kI, size_t mI) {
deleteBranchByIndex(getBranchIndexByIndex(kI, mI));
}
void PowerNet::deleteBar(size_t id) {
deleteBarByIndex(getBarIndex(id));
}
void PowerNet::deleteBarByIndex(size_t i) {
if (m_busBars.size() <= i) {
throw std::runtime_error("Bar does not exists");
}
if (m_busBars[i]->getNConnections() != 0) {
throw std::runtime_error("cannot delete bar with live connections");
}
// does the deletion, done this way because busBars do not change much over time so optimization is not important
discontBarCount(m_busBars[i]->getType());
for (size_t _i = i+1, n=m_busBars.size() ; _i < n ; _i++) {
m_busBars[_i-1] = m_busBars[_i];
}
m_busBars.pop_back();
}
void PowerNet::cleanBranches() {
m_branches.clear();
}
void PowerNet::clean() {
m_branches.clear();
m_busBars.clear();
m_nPQ = 0;
m_nPV = 0;
m_nSlack = 0;
}
void PowerNet::setFlatStart() {
for (size_t i = 0, n = m_busBars.size(); i < n; i++) {
if (m_busBars[i]->getType() == Bar::Slack) {
m_busBars[i]->setP(0);
m_busBars[i]->setQ(0);
} else if (m_busBars[i]->getType() == Bar::PV) {
m_busBars[i]->setTeta(0);
m_busBars[i]->setQ(0);
} else {
m_busBars[i]->setV(1);
m_busBars[i]->setTeta(0);
}
}
}
size_t PowerNet::getNBars() const {
return m_busBars.size();
}
size_t PowerNet::getNBranches() const {
return m_branches.size();
}
size_t PowerNet::getNSlack() const {
return m_nSlack;
}
size_t PowerNet::getNPQ() const {
return m_nPQ;
}
size_t PowerNet::getNPV() const {
return m_nPV;
}
size_t PowerNet::getBarIndex(const BarPtr bar) const {
for (size_t i = 0, n = m_busBars.size(); i < n; i++) {
if (m_busBars[i] == bar) {
return i;
}
}
throw std::runtime_error("Bar could not be found");
}
size_t PowerNet::getBarIndex(const size_t id) const {
for (size_t i = 0, n = m_busBars.size(); i < n; i++) {
if (m_busBars[i]->getId() == id) {
return i;
}
}
throw std::runtime_error("Bar could not be found");
}
size_t PowerNet::getBranchIndex(const BranchPtr branch) const {
for (size_t i = 0, n = m_branches.size(); i < n; i++) {
if (m_branches[i] == branch) {
return i;
}
}
throw std::runtime_error("Branch could not be found");
}
size_t PowerNet::getBranchIndex(uint64_t id) const {
for (size_t i = 0, n = m_branches.size(); i < n ; i++) {
uint64_t id1 = m_branches[i]->getId();
if (id1 == id) {
return i;
} else if (id1 > id) {
throw std::runtime_error("could not find branch");
}
}
throw std::runtime_error("could not find branch");
}
size_t PowerNet::getBranchIndex(size_t kId, size_t mId) const {
return getBranchIndex(Branch::calculateId(kId, mId));
}
size_t PowerNet::getBranchIndexByIndex(size_t kId, size_t mId) const {
if (m_busBars.size() <= kId || m_busBars.size() <= mId) {
throw std::runtime_error("bar does not exists");
}
return getBranchIndex(m_busBars[kId]->getId(), m_busBars[mId]->getId());
}
const BarPtr PowerNet::getBar(uint64_t i) const {
return m_busBars[getBarIndex(i)];
}
const BarPtr PowerNet::getBarByIndex(size_t i) const {
if (m_busBars.size() <= i) {
throw std::runtime_error("bar does not exists");
}
return m_busBars[i];
}
const BranchPtr PowerNet::getBranch(uint64_t i) const {
return m_branches[getBranchIndex(i)];
}
const BranchPtr PowerNet::getBranchByIndex(size_t i) const {
if (m_branches.size() <= i) {
throw std::runtime_error("branch does not exists");
}
return m_branches[i];
}
const BranchPtr PowerNet::getBranch(uint64_t kId, uint64_t mId) const {
return m_branches[getBranchIndex(kId, mId)];
}
const BranchPtr PowerNet::getBranchByIndex(uint64_t kId, uint64_t mId) const {
return m_branches[getBranchIndexByIndex(kId, mId)];
}
void PowerNet::updateY() {
const size_t nBars = getNBars();
m_Y.setZero(nBars, nBars);
for (size_t i = 0; i < nBars; i++) {
BarPtr bar = getBarByIndex(i);
m_Y(i, i) = AdmitanceCalc::getAdmitanceKk(bar);
for (size_t j = i+1 ; j < nBars ; j++) {
try {
BranchPtr branch = getBranchByIndex(i, j);
if (branch->getK() == bar) {
m_Y(i, j) = AdmitanceCalc::getAdmitanceKm(branch);
m_Y(j, i) = AdmitanceCalc::getAdmitanceMk(branch);
} else {
m_Y(i, j) = AdmitanceCalc::getAdmitanceMk(branch);
m_Y(j, i) = AdmitanceCalc::getAdmitanceKm(branch);
}
} catch(std::exception e) {
}
}
}
}
const complexo PowerNet::getY(size_t i, size_t j) {
if (checkChanged()) {
updateY();
}
return m_Y(i, j);
}
void PowerNet::completeNetPowers() {
for (int i = 0, n = m_nSlack; i < n; i++) {
m_busBars[i]->setS(getSk(i));
}
for (int i = m_nSlack, n = m_nSlack + m_nPV; i < n; i++) {
m_busBars[i]->setQ(getSk(i).imag());
}
}
bool PowerNet::areConnected(uint64_t i, uint64_t j) {
try {
size_t id = getBranchIndex(i, j);
return m_branches[id]->isBranchOn();
} catch(std::exception e) {
return false;
}
}
bool PowerNet::areConnectedByIndex(size_t i, size_t j) {
try {
size_t id = getBranchIndexByIndex(i, j);
return m_branches[id]->isBranchOn();
} catch(std::exception e) {
return false;
}
}
void PowerNet::discontBarCount(Bar::barType type) {
if (type == Bar::PQ) {
--m_nPQ;
} else if (type == Bar::PV) {
--m_nPV;
} else {
--m_nSlack;
}
}
void PowerNet::sortBackBranch() {
const uint64_t id = m_branches[m_branches.size()-1]->getId();
for (size_t i = m_branches.size()-1 ; i > 0 ; i--) {
if (m_branches[i-1]->getId() > id) {
std::swap<BranchPtr>(m_branches[i], m_branches[i-1]);
} else {
return;
}
}
}
void PowerNet::sortBackBar() {
const Bar::barType type = m_busBars[m_busBars.size()-1]->getType();
for (size_t i = m_busBars.size()-1; i > 0; i--) {
if (m_busBars[i-1]->getType() > type) {
std::swap<BarPtr>(m_busBars[i], m_busBars[i-1]);
} else {
break;
}
}
}
bool PowerNet::checkChanged() {
bool changed = false;
for (size_t i = 0, m = m_busBars.size(); i < m; i++) {
if (m_busBars[i]->isChanged()) {
changed = true;
m_busBars[i]->clearChanged();
}
}
for (size_t i = 0, m = m_branches.size(); i < m; i++) {
if (m_branches[i]->isChanged()) {
changed = true;
m_branches[i]->clearChanged();
}
}
return changed;
}
complexo PowerNet::getSk(size_t bar) {
complexo sum = 0;
for (size_t i = 0, n = m_busBars.size() ; i < n ; i++) {
sum += m_Y(bar, i)*m_busBars[i]->getE();
}
return complexConjugado(complexConjugado(m_busBars[bar]->getE())*sum);
}
double PowerNet::getTetaKm(uint64_t kId, uint64_t mId) const {
return getTetaKm(getBarIndex(kId), getBarIndex(mId));
}
double PowerNet::getTetaKmByIndex(size_t kI, size_t mI) const {
return m_busBars[kI]->getTeta() - m_busBars[mI]->getTeta();
}
bool PowerNet::checkBarIdExists(uint64_t id) {
for (size_t i = 0, n = m_busBars.size(); i < n; i++) {
if (m_busBars[i]->getId() == id) {
return true;
}
}
return false;
}
} // namespace neuralFlux
| 13,465 | 5,139 |
//
// Created by pedro on 8/28/17.
//
#include "Tests.h"
void Testing::test1() {
CPPUNIT_ASSERT(1);
}
| 108 | 55 |
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author GS <sgazeos@gmail.com> 3/21/2018
// @author Yurii Shyrma (iuriish@yahoo.com)
//
#include <ops/declarable/CustomOperations.h>
#include <ops/declarable/helpers/matrixSetDiag.h>
#if NOT_EXCLUDED(OP_matrix_diag)
namespace sd {
namespace ops {
CUSTOM_OP_IMPL(matrix_diag, 1, 1, false, 0, 0) {
auto diagonal = INPUT_VARIABLE(0);
auto output = OUTPUT_VARIABLE(0);
REQUIRE_TRUE(!diagonal->isScalar(), 0, "CUSTOM_OP matrix_diag: input diagonal array must be at list a vector, but scalar was given!");
helpers::matrixSetDiag(block.launchContext(), *output, *diagonal, *output, true);
return Status::OK();
}
DECLARE_SHAPE_FN(matrix_diag) {
Nd4jLong* outShapeInfo = nullptr;
auto in = inputShape->at(0);
int inRank = shape::rank(in);
// if for example diagonal array has shape [A,B,C] then output array has shape [A,B,C,C]
int outRank = inRank + 1;
ALLOCATE(outShapeInfo, block.getWorkspace(), shape::shapeInfoLength(outRank), Nd4jLong);
outShapeInfo[0] = outRank;
for(int i = 0; i < inRank; ++i)
outShapeInfo[i + 1] = shape::sizeAt(in, i);
outShapeInfo[outRank] = shape::sizeAt(in, -1);
ShapeUtils::updateStridesAndType(outShapeInfo, in, shape::order(in));
return SHAPELIST(CONSTANT(outShapeInfo));
}
DECLARE_TYPES(matrix_diag) {
getOpDescriptor()
->setAllowedInputTypes(sd::DataType::ANY)
->setSameMode(true);
}
}
}
#endif
| 2,287 | 782 |
#include "core.hpp"
#include <cstdio>
namespace tap {
struct PeerObject::State {
enum {
DIRTY_FLAG = 1 << 0,
REFERENCE_FLAG = 1 << 1,
};
State() noexcept:
key(-1),
flags(0)
{
}
State(Key key, unsigned int flags) noexcept:
key(key),
flags(flags)
{
}
State &operator=(const State &other) noexcept
{
key = other.key;
flags = other.flags;
return *this;
}
void set_flag(unsigned int mask) noexcept
{
flags |= mask;
}
void clear_flag(unsigned int mask) noexcept
{
flags &= ~mask;
}
bool test_flag(unsigned int mask) const noexcept
{
return flags & mask;
}
Key key;
unsigned int flags;
};
PeerObject::PeerObject():
next_object_id(0)
{
instance_peers().insert(this);
}
PeerObject::~PeerObject()
{
instance_peers().erase(this);
for (auto pair: states) {
if (pair.second.test_flag(State::REFERENCE_FLAG))
Py_DECREF(pair.first);
}
}
int PeerObject::insert(PyObject *object, Key key) noexcept
{
return insert(object, key, 0);
}
int PeerObject::insert(PyObject *object, Key key, unsigned int flags) noexcept
{
try {
states[object] = State(key, flags);
} catch (...) {
return -1;
}
try {
objects[key] = object;
} catch (...) {
states.erase(object);
return -1;
}
return 0;
}
Key PeerObject::insert_new(PyObject *object, unsigned int flags) noexcept
{
Key key = next_object_id;
if (insert(object, key, flags) < 0)
return -1;
next_object_id++;
return key;
}
void PeerObject::clear(PyObject *object) noexcept
{
auto i = states.find(object);
if (i != states.end())
i->second.clear_flag(State::DIRTY_FLAG);
}
std::pair<Key, bool> PeerObject::insert_or_clear_for_remote(PyObject *object) noexcept
{
bool object_changed;
Key key;
auto i = states.find(object);
if (i != states.end()) {
object_changed = i->second.test_flag(State::DIRTY_FLAG);
i->second.clear_flag(State::DIRTY_FLAG);
key = i->second.key;
} else {
object_changed = true;
key = insert_new(object, 0);
}
Key remote_key = key_for_remote(key);
return std::make_pair(remote_key, object_changed);
}
Key PeerObject::key_for_remote(PyObject *object) noexcept
{
Key key;
auto i = states.find(object);
if (i != states.end())
key = i->second.key;
else
key = insert_new(object, State::DIRTY_FLAG);
return key_for_remote(key);
}
Key PeerObject::key_for_remote(Key key) noexcept
{
if (key < 0)
return -1;
uint32_t object_id = key;
int32_t remote_id = key >> 32;
remote_id = !remote_id;
return (Key(remote_id) << 32) | object_id;
}
PyObject *PeerObject::object(Key key) noexcept
{
PyObject *object = nullptr;
auto i = objects.find(key);
if (i != objects.end()) {
object = i->second;
if (object->ob_refcnt <= 0) {
fprintf(stderr, "tap peer: %s object %p with invalid reference count %ld during lookup\n", object->ob_type->tp_name, object, object->ob_refcnt);
object = nullptr;
}
}
return object;
}
void PeerObject::touch(PyObject *object) noexcept
{
auto i = states.find(object);
if (i != states.end())
i->second.set_flag(State::DIRTY_FLAG);
}
void PeerObject::set_references(const std::unordered_set<PyObject *> &referenced) noexcept
{
for (PyObject *object: referenced)
states.find(object)->second.set_flag(State::REFERENCE_FLAG);
}
void PeerObject::dereference(Key key) noexcept
{
auto i = objects.find(key);
if (i != objects.end()) {
PyObject *object = i->second;
State &state = states.find(object)->second;
if (state.test_flag(State::REFERENCE_FLAG)) {
state.clear_flag(State::REFERENCE_FLAG);
state.set_flag(State::DIRTY_FLAG);
Py_DECREF(object);
}
}
}
void PeerObject::object_freed(void *ptr) noexcept
{
auto i = states.find(ptr);
if (i != states.end()) {
PyObject *object = reinterpret_cast<PyObject *> (ptr);
fprintf(stderr, "tap peer: %s object %p freed\n", object->ob_type->tp_name, object);
if (object->ob_refcnt != 0)
fprintf(stderr, "tap peer: %s object %p with unexpected reference count %ld when freed\n", object->ob_type->tp_name, object, object->ob_refcnt);
Key key = i->second.key;
objects.erase(key);
states.erase(i);
freed.push_back(key);
}
}
static PyObject *peer_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) noexcept
{
PyObject *peer = type->tp_alloc(type, 0);
if (peer) {
try {
new (peer) PeerObject;
} catch (...) {
type->tp_free(peer);
peer = nullptr;
}
}
return peer;
}
static void peer_dealloc(PyObject *peer) noexcept
{
reinterpret_cast<PeerObject *> (peer)->~PeerObject();
Py_TYPE(peer)->tp_free(peer);
}
int peer_type_init() noexcept
{
return PyType_Ready(&peer_type);
}
PyTypeObject peer_type = {
PyVarObject_HEAD_INIT(nullptr, 0)
"tap.core.Peer", /* tp_name */
sizeof (PeerObject), /* tp_basicsize */
0, /* tp_itemsize */
peer_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
nullptr, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
peer_new, /* tp_new */
};
void peers_touch(PyObject *object) noexcept
{
for (PeerObject *peer: instance_peers())
peer->touch(object);
}
} // namespace tap
| 6,656 | 2,495 |
/*==============================================================================
Copyright (c) 2005-2010 Joel de Guzman
Copyright (c) 2010-2011 Thomas Heller
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
struct assign
: proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) > > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 14> , proto::call< proto::_child_c< 14>(proto::_state) > ) > > > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 14> , proto::call< proto::_child_c< 14>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 15> , proto::call< proto::_child_c< 15>(proto::_state) > ) > > > > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 14> , proto::call< proto::_child_c< 14>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 15> , proto::call< proto::_child_c< 15>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 16> , proto::call< proto::_child_c< 16>(proto::_state) > ) > > > > > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 14> , proto::call< proto::_child_c< 14>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 15> , proto::call< proto::_child_c< 15>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 16> , proto::call< proto::_child_c< 16>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 17> , proto::call< proto::_child_c< 17>(proto::_state) > ) > > > > > > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 14> , proto::call< proto::_child_c< 14>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 15> , proto::call< proto::_child_c< 15>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 16> , proto::call< proto::_child_c< 16>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 17> , proto::call< proto::_child_c< 17>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 18> , proto::call< proto::_child_c< 18>(proto::_state) > ) > > > > > > > > > > > > > > > > > > > >
, proto::when<
proto::terminal<proto::_>
, do_assign(proto::_, proto::_state)
>
> > > > > > > > > > > > > > > > > > >
{};
| 22,722 | 9,245 |
// This file automatically generated by create_export_module.py
#include <NumpyEigenConverter.hpp>
#define NUMPY_IMPORT_ARRAY_RETVAL
// function prototypes
void import_1_1_int();
void import_1_1_float();
void import_1_1_double();
void import_1_1_uchar();
void import_1_1_long();
void import_1_2_int();
void import_1_2_float();
void import_1_2_double();
void import_1_2_uchar();
void import_1_2_long();
void import_1_3_int();
void import_1_3_float();
void import_1_3_double();
void import_1_3_uchar();
void import_1_3_long();
void import_1_4_int();
void import_1_4_float();
void import_1_4_double();
void import_1_4_uchar();
void import_1_4_long();
void import_1_5_int();
void import_1_5_float();
void import_1_5_double();
void import_1_5_uchar();
void import_1_5_long();
void import_1_6_int();
void import_1_6_float();
void import_1_6_double();
void import_1_6_uchar();
void import_1_6_long();
void import_1_D_int();
void import_1_D_float();
void import_1_D_double();
void import_1_D_uchar();
void import_1_D_long();
void import_2_1_int();
void import_2_1_float();
void import_2_1_double();
void import_2_1_uchar();
void import_2_1_long();
void import_2_2_int();
void import_2_2_float();
void import_2_2_double();
void import_2_2_uchar();
void import_2_2_long();
void import_2_3_int();
void import_2_3_float();
void import_2_3_double();
void import_2_3_uchar();
void import_2_3_long();
void import_2_4_int();
void import_2_4_float();
void import_2_4_double();
void import_2_4_uchar();
void import_2_4_long();
void import_2_5_int();
void import_2_5_float();
void import_2_5_double();
void import_2_5_uchar();
void import_2_5_long();
void import_2_6_int();
void import_2_6_float();
void import_2_6_double();
void import_2_6_uchar();
void import_2_6_long();
void import_2_D_int();
void import_2_D_float();
void import_2_D_double();
void import_2_D_uchar();
void import_2_D_long();
void import_3_1_int();
void import_3_1_float();
void import_3_1_double();
void import_3_1_uchar();
void import_3_1_long();
void import_3_2_int();
void import_3_2_float();
void import_3_2_double();
void import_3_2_uchar();
void import_3_2_long();
void import_3_3_int();
void import_3_3_float();
void import_3_3_double();
void import_3_3_uchar();
void import_3_3_long();
void import_3_4_int();
void import_3_4_float();
void import_3_4_double();
void import_3_4_uchar();
void import_3_4_long();
void import_3_5_int();
void import_3_5_float();
void import_3_5_double();
void import_3_5_uchar();
void import_3_5_long();
void import_3_6_int();
void import_3_6_float();
void import_3_6_double();
void import_3_6_uchar();
void import_3_6_long();
void import_3_D_int();
void import_3_D_float();
void import_3_D_double();
void import_3_D_uchar();
void import_3_D_long();
void import_4_1_int();
void import_4_1_float();
void import_4_1_double();
void import_4_1_uchar();
void import_4_1_long();
void import_4_2_int();
void import_4_2_float();
void import_4_2_double();
void import_4_2_uchar();
void import_4_2_long();
void import_4_3_int();
void import_4_3_float();
void import_4_3_double();
void import_4_3_uchar();
void import_4_3_long();
void import_4_4_int();
void import_4_4_float();
void import_4_4_double();
void import_4_4_uchar();
void import_4_4_long();
void import_4_5_int();
void import_4_5_float();
void import_4_5_double();
void import_4_5_uchar();
void import_4_5_long();
void import_4_6_int();
void import_4_6_float();
void import_4_6_double();
void import_4_6_uchar();
void import_4_6_long();
void import_4_D_int();
void import_4_D_float();
void import_4_D_double();
void import_4_D_uchar();
void import_4_D_long();
void import_5_1_int();
void import_5_1_float();
void import_5_1_double();
void import_5_1_uchar();
void import_5_1_long();
void import_5_2_int();
void import_5_2_float();
void import_5_2_double();
void import_5_2_uchar();
void import_5_2_long();
void import_5_3_int();
void import_5_3_float();
void import_5_3_double();
void import_5_3_uchar();
void import_5_3_long();
void import_5_4_int();
void import_5_4_float();
void import_5_4_double();
void import_5_4_uchar();
void import_5_4_long();
void import_5_5_int();
void import_5_5_float();
void import_5_5_double();
void import_5_5_uchar();
void import_5_5_long();
void import_5_6_int();
void import_5_6_float();
void import_5_6_double();
void import_5_6_uchar();
void import_5_6_long();
void import_5_D_int();
void import_5_D_float();
void import_5_D_double();
void import_5_D_uchar();
void import_5_D_long();
void import_6_1_int();
void import_6_1_float();
void import_6_1_double();
void import_6_1_uchar();
void import_6_1_long();
void import_6_2_int();
void import_6_2_float();
void import_6_2_double();
void import_6_2_uchar();
void import_6_2_long();
void import_6_3_int();
void import_6_3_float();
void import_6_3_double();
void import_6_3_uchar();
void import_6_3_long();
void import_6_4_int();
void import_6_4_float();
void import_6_4_double();
void import_6_4_uchar();
void import_6_4_long();
void import_6_5_int();
void import_6_5_float();
void import_6_5_double();
void import_6_5_uchar();
void import_6_5_long();
void import_6_6_int();
void import_6_6_float();
void import_6_6_double();
void import_6_6_uchar();
void import_6_6_long();
void import_6_D_int();
void import_6_D_float();
void import_6_D_double();
void import_6_D_uchar();
void import_6_D_long();
void import_D_1_int();
void import_D_1_float();
void import_D_1_double();
void import_D_1_uchar();
void import_D_1_long();
void import_D_2_int();
void import_D_2_float();
void import_D_2_double();
void import_D_2_uchar();
void import_D_2_long();
void import_D_3_int();
void import_D_3_float();
void import_D_3_double();
void import_D_3_uchar();
void import_D_3_long();
void import_D_4_int();
void import_D_4_float();
void import_D_4_double();
void import_D_4_uchar();
void import_D_4_long();
void import_D_5_int();
void import_D_5_float();
void import_D_5_double();
void import_D_5_uchar();
void import_D_5_long();
void import_D_6_int();
void import_D_6_float();
void import_D_6_double();
void import_D_6_uchar();
void import_D_6_long();
void import_D_D_int();
void import_D_D_float();
void import_D_D_double();
void import_D_D_uchar();
void import_D_D_long();
BOOST_PYTHON_MODULE(libnumpy_eigen)
{
using namespace boost::python;
// Without this import, the converter will segfault
import_array();
import_1_1_int();
import_1_1_float();
import_1_1_double();
import_1_1_uchar();
import_1_1_long();
import_1_2_int();
import_1_2_float();
import_1_2_double();
import_1_2_uchar();
import_1_2_long();
import_1_3_int();
import_1_3_float();
import_1_3_double();
import_1_3_uchar();
import_1_3_long();
import_1_4_int();
import_1_4_float();
import_1_4_double();
import_1_4_uchar();
import_1_4_long();
import_1_5_int();
import_1_5_float();
import_1_5_double();
import_1_5_uchar();
import_1_5_long();
import_1_6_int();
import_1_6_float();
import_1_6_double();
import_1_6_uchar();
import_1_6_long();
import_1_D_int();
import_1_D_float();
import_1_D_double();
import_1_D_uchar();
import_1_D_long();
import_2_1_int();
import_2_1_float();
import_2_1_double();
import_2_1_uchar();
import_2_1_long();
import_2_2_int();
import_2_2_float();
import_2_2_double();
import_2_2_uchar();
import_2_2_long();
import_2_3_int();
import_2_3_float();
import_2_3_double();
import_2_3_uchar();
import_2_3_long();
import_2_4_int();
import_2_4_float();
import_2_4_double();
import_2_4_uchar();
import_2_4_long();
import_2_5_int();
import_2_5_float();
import_2_5_double();
import_2_5_uchar();
import_2_5_long();
import_2_6_int();
import_2_6_float();
import_2_6_double();
import_2_6_uchar();
import_2_6_long();
import_2_D_int();
import_2_D_float();
import_2_D_double();
import_2_D_uchar();
import_2_D_long();
import_3_1_int();
import_3_1_float();
import_3_1_double();
import_3_1_uchar();
import_3_1_long();
import_3_2_int();
import_3_2_float();
import_3_2_double();
import_3_2_uchar();
import_3_2_long();
import_3_3_int();
import_3_3_float();
import_3_3_double();
import_3_3_uchar();
import_3_3_long();
import_3_4_int();
import_3_4_float();
import_3_4_double();
import_3_4_uchar();
import_3_4_long();
import_3_5_int();
import_3_5_float();
import_3_5_double();
import_3_5_uchar();
import_3_5_long();
import_3_6_int();
import_3_6_float();
import_3_6_double();
import_3_6_uchar();
import_3_6_long();
import_3_D_int();
import_3_D_float();
import_3_D_double();
import_3_D_uchar();
import_3_D_long();
import_4_1_int();
import_4_1_float();
import_4_1_double();
import_4_1_uchar();
import_4_1_long();
import_4_2_int();
import_4_2_float();
import_4_2_double();
import_4_2_uchar();
import_4_2_long();
import_4_3_int();
import_4_3_float();
import_4_3_double();
import_4_3_uchar();
import_4_3_long();
import_4_4_int();
import_4_4_float();
import_4_4_double();
import_4_4_uchar();
import_4_4_long();
import_4_5_int();
import_4_5_float();
import_4_5_double();
import_4_5_uchar();
import_4_5_long();
import_4_6_int();
import_4_6_float();
import_4_6_double();
import_4_6_uchar();
import_4_6_long();
import_4_D_int();
import_4_D_float();
import_4_D_double();
import_4_D_uchar();
import_4_D_long();
import_5_1_int();
import_5_1_float();
import_5_1_double();
import_5_1_uchar();
import_5_1_long();
import_5_2_int();
import_5_2_float();
import_5_2_double();
import_5_2_uchar();
import_5_2_long();
import_5_3_int();
import_5_3_float();
import_5_3_double();
import_5_3_uchar();
import_5_3_long();
import_5_4_int();
import_5_4_float();
import_5_4_double();
import_5_4_uchar();
import_5_4_long();
import_5_5_int();
import_5_5_float();
import_5_5_double();
import_5_5_uchar();
import_5_5_long();
import_5_6_int();
import_5_6_float();
import_5_6_double();
import_5_6_uchar();
import_5_6_long();
import_5_D_int();
import_5_D_float();
import_5_D_double();
import_5_D_uchar();
import_5_D_long();
import_6_1_int();
import_6_1_float();
import_6_1_double();
import_6_1_uchar();
import_6_1_long();
import_6_2_int();
import_6_2_float();
import_6_2_double();
import_6_2_uchar();
import_6_2_long();
import_6_3_int();
import_6_3_float();
import_6_3_double();
import_6_3_uchar();
import_6_3_long();
import_6_4_int();
import_6_4_float();
import_6_4_double();
import_6_4_uchar();
import_6_4_long();
import_6_5_int();
import_6_5_float();
import_6_5_double();
import_6_5_uchar();
import_6_5_long();
import_6_6_int();
import_6_6_float();
import_6_6_double();
import_6_6_uchar();
import_6_6_long();
import_6_D_int();
import_6_D_float();
import_6_D_double();
import_6_D_uchar();
import_6_D_long();
import_D_1_int();
import_D_1_float();
import_D_1_double();
import_D_1_uchar();
import_D_1_long();
import_D_2_int();
import_D_2_float();
import_D_2_double();
import_D_2_uchar();
import_D_2_long();
import_D_3_int();
import_D_3_float();
import_D_3_double();
import_D_3_uchar();
import_D_3_long();
import_D_4_int();
import_D_4_float();
import_D_4_double();
import_D_4_uchar();
import_D_4_long();
import_D_5_int();
import_D_5_float();
import_D_5_double();
import_D_5_uchar();
import_D_5_long();
import_D_6_int();
import_D_6_float();
import_D_6_double();
import_D_6_uchar();
import_D_6_long();
import_D_D_int();
import_D_D_float();
import_D_D_double();
import_D_D_uchar();
import_D_D_long();
}
| 11,377 | 5,004 |
//
// Created by authetic on 2019/4/13.
//
/*
* 树的概念:
* 1. n个结点n-1条边
* 2. 结点的度(Degree):结点子树的个数
* 3. 树的度:所有结点中最大的度数
* 4. 结点的层次(Level):根结点层次为1,其它结点依次加1
* 5. 树的深度(Depth):树中所有结点的最大层次
* 6. n0表示叶结点的个数,n2度为2的结点个数
* 则n0 = n2 + 1
* (从边的角度考虑,
* n0+n1+n2-1 = n0*0 + n1*1 + n2*2
*
* 完全二叉树顺序存储
* 1. 结点i的父结点 = i/2
* 2. 结点i的左子结点 = 2*i
* 3. 结点i的右子结点 = 2*i+1
*/
#include <stdio.h>
#include <queue>
#include <stack>
using namespace std;
typedef int ElementType;
struct TNode {
ElementType data;
TNode* left;
TNode* right;
};
typedef TNode* BinTree;
void PreOrderTraversal(BinTree BT) {
if (BT) {
printf("%d ", BT->data);
PreOrderTraversal(BT->left);
PreOrderTraversal(BT->right);
}
}
void InOrderTraversal(BinTree BT) {
if (BT) {
InOrderTraversal(BT->left);
printf("%d", BT->data);
InOrderTraversal(BT->right);
}
}
void PostOrderTraversal(BinTree BT) {
if (BT) {
PostOrderTraversal(BT->left);
PostOrderTraversal(BT->right);
printf("%d", BT->data);
}
}
// 非递归中序遍历
// 前序和后序遍历?
void InOrderTraversal2(BinTree BT) {
stack<BinTree> st;
BinTree T = BT;
while (T || !st.empty()) {
while (T) {
st.push(T);
T = T->left;
}
if (!st.empty()) {
BinTree top = st.top();
printf("%d", top->data);
T = top->right;
st.pop();
}
}
}
void PostOrderTraversal2(BinTree BT) {
stack<BinTree> st;
BinTree T = BT;
while (T || !st.empty()) {
while (T) {
st.push(T->left);
}
}
}
void LevelOrderTraversal(BinTree BT) {
queue<BinTree> q;
q.push(BT);
while (!q.empty()) {
BinTree T = q.front();
q.pop();
printf("%d", T->data);
if (T->left) q.push(T->left);
if (T->right) q.push(T->right);
}
} | 1,908 | 950 |
#ifndef OBJMGR_UTIL___SCORE_BUILDER_BASE__HPP
#define OBJMGR_UTIL___SCORE_BUILDER_BASE__HPP
/* $Id: score_builder_base.hpp 363131 2012-05-14 15:34:29Z whlavina $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Mike DiCuccio
*
* File Description:
*
*/
#include <corelib/ncbiobj.hpp>
#include <util/range_coll.hpp>
#include <objects/seqalign/Seq_align.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
class CScope;
class NCBI_XALNMGR_EXPORT CScoreBuilderBase
{
public:
CScoreBuilderBase();
virtual ~CScoreBuilderBase();
enum EScoreType {
//< typical blast 'score'
//< NOTE: implemented in a derived class!!
eScore_Blast,
//< blast 'bit_score' score
//< NOTE: implemented in a derived class!!
eScore_Blast_BitScore,
//< blast 'e_value' score
//< NOTE: implemented in a derived class!!
eScore_Blast_EValue,
//< count of ungapped identities as 'num_ident'
eScore_IdentityCount,
//< count of ungapped identities as 'num_mismatch'
eScore_MismatchCount,
//< percent identity as defined in CSeq_align, range 0.0-100.0
//< this will also create 'num_ident' and 'num_mismatch'
//< NOTE: see Seq_align.hpp for definitions
eScore_PercentIdentity,
//< percent coverage of query as 'pct_coverage', range 0.0-100.0
eScore_PercentCoverage
};
/// Error handling while adding scores that are not implemented
/// or unsupported (cannot be defined) for certain types
/// of alignments.
///
/// Transient errors, such as problems retrieving sequence
/// data, will always throw.
enum EErrorMode {
eError_Silent, ///< Try to ignore errors, continue adding scores.
eError_Report, ///< Print error messages, but do not fail.
eError_Throw ///< Throw exceptions on errors.
};
/// @name Functions to add scores directly to Seq-aligns
/// @{
EErrorMode GetErrorMode(void) const { return m_ErrorMode; }
void SetErrorMode(EErrorMode mode) { m_ErrorMode = mode; }
void AddScore(CScope& scope, CSeq_align& align,
CSeq_align::EScoreType score);
void AddScore(CScope& scope, list< CRef<CSeq_align> >& aligns,
CSeq_align::EScoreType score);
/// @}
/// @name Functions to compute scores without adding
/// @{
double ComputeScore(CScope& scope, const CSeq_align& align,
CSeq_align::EScoreType score);
double ComputeScore(CScope& scope, const CSeq_align& align,
const TSeqRange &range,
CSeq_align::EScoreType score);
virtual double ComputeScore(CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges,
CSeq_align::EScoreType score);
/// Compute percent identity (range 0-100)
enum EPercentIdentityType {
eGapped, //< count gaps as mismatches
eUngapped, //< ignore gaps; only count aligned bases
eGBDNA //< each gap counts as a 1nt mismatch
};
double GetPercentIdentity(CScope& scope, const CSeq_align& align,
EPercentIdentityType type = eGapped);
/// Compute percent coverage of the query (sequence 0) (range 0-100)
double GetPercentCoverage(CScope& scope, const CSeq_align& align);
/// Compute percent identity or coverage of the query within specified range
double GetPercentIdentity(CScope& scope, const CSeq_align& align,
const TSeqRange &range,
EPercentIdentityType type = eGapped);
double GetPercentCoverage(CScope& scope, const CSeq_align& align,
const TSeqRange &range);
/// Compute percent identity or coverage of the query within specified
/// collection of ranges
double GetPercentIdentity(CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges,
EPercentIdentityType type = eGapped);
double GetPercentCoverage(CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges);
/// Compute the number of identities in the alignment
int GetIdentityCount (CScope& scope, const CSeq_align& align);
/// Compute the number of mismatches in the alignment
int GetMismatchCount (CScope& scope, const CSeq_align& align);
void GetMismatchCount (CScope& scope, const CSeq_align& align,
int& identities, int& mismatches);
/// Compute identity and/or mismatch counts within specified range
int GetIdentityCount (CScope& scope, const CSeq_align& align,
const TSeqRange &range);
int GetMismatchCount (CScope& scope, const CSeq_align& align,
const TSeqRange &range);
void GetMismatchCount (CScope& scope, const CSeq_align& align,
const TSeqRange &range,
int& identities, int& mismatches);
/// Compute identity and/or mismatch counts within specified
/// collection of ranges
int GetIdentityCount (CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges);
int GetMismatchCount (CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges);
void GetMismatchCount (CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges,
int& identities, int& mismatches);
/// counts based on substitution matrix for protein alignments
int GetPositiveCount (CScope& scope, const CSeq_align& align);
int GetNegativeCount (CScope& scope, const CSeq_align& align);
void GetMatrixCounts (CScope& scope, const CSeq_align& align,
int& positives, int& negatives);
/// Compute the number of gaps in the alignment
int GetGapCount (const CSeq_align& align);
int GetGapCount (const CSeq_align& align,
const TSeqRange &range);
int GetGapCount (const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges);
/// Compute the number of gap bases in the alignment (= length of all gap
/// segments)
int GetGapBaseCount (const CSeq_align& align);
int GetGapBaseCount (const CSeq_align& align,
const TSeqRange &range);
int GetGapBaseCount (const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges);
/// Compute the length of the alignment (= length of all segments, gaps +
/// aligned)
TSeqPos GetAlignLength(const CSeq_align& align, bool ungapped=false);
TSeqPos GetAlignLength(const CSeq_align& align,
const TSeqRange &range, bool ungapped=false);
TSeqPos GetAlignLength(const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges,
bool ungapped=false);
void SetSubstMatrix(const string &name);
/// @}
private:
EErrorMode m_ErrorMode;
string m_SubstMatrixName;
void x_GetMatrixCounts(CScope& scope,
const CSeq_align& align,
int* positives, int* negatives);
};
END_SCOPE(objects)
END_NCBI_SCOPE
#endif // OBJMGR_UTIL___SCORE_BUILDER_BASE__HPP
| 8,814 | 2,490 |
// Copyright (c) 2018 The Open-Transactions developers
// 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/.
// An OTTrade is derived from OTCronItem. OTCron has a list of items,
// which may be trades or agreements or who knows what next.
#ifndef OPENTXS_CORE_TRADE_OTTRADE_HPP
#define OPENTXS_CORE_TRADE_OTTRADE_HPP
#include "opentxs/Forward.hpp"
#include "opentxs/core/cron/OTCronItem.hpp"
#include "opentxs/core/trade/OTMarket.hpp"
#include "opentxs/core/trade/OTOffer.hpp"
#include "opentxs/core/Contract.hpp"
#include "opentxs/core/OTTransactionType.hpp"
#include "opentxs/core/String.hpp"
#include "opentxs/Types.hpp"
#include <cstdint>
namespace opentxs
{
namespace api
{
namespace implementation
{
class Factory;
} // namespace implementation
} // namespace api
/*
OTTrade
Standing Order (for Trades) MUST STORE:
X 1) Transaction ID // It took a transaction number to create this trade. We
record it here and use it to uniquely identify the trade, like any other
transaction.
X 4) CURRENCY TYPE ID (Currency type ID of whatever I’m trying to buy or sell
WITH. Dollars? Euro?)
X 5) Account ID SENDER (for above currency type. This is the account where I
make my payments from, to satisfy the trades.)
X 6) Valid date range. (Start. Expressed as an absolute date.)
X 7) Valid date range. ( End. Expressed as an absolute date.)
X 2) Creation date.
X 3) INTEGER: Number of trades that have processed through this order.
X 8) STOP ORDER — SIGN (nullptr if not a stop order — otherwise GREATER THAN or
LESS THAN…)
X 9) STOP ORDER — PRICE (…AT X PRICE, POST THE OFFER TO THE MARKET.)
Cron for these orders must check expiration dates and stop order prices.
———————————————————————————————
*/
class OTTrade : public OTCronItem
{
public:
originType GetOriginType() const override
{
return originType::origin_market_offer;
}
EXPORT bool VerifyOffer(OTOffer& offer) const;
EXPORT bool IssueTrade(
OTOffer& offer,
char stopSign = 0,
std::int64_t stopPrice = 0);
// The Trade always stores the original, signed version of its Offer.
// This method allows you to grab a copy of it.
inline bool GetOfferString(String& offer)
{
offer.Set(marketOffer_);
if (marketOffer_.Exists()) { return true; }
return false;
}
inline bool IsStopOrder() const
{
if ((stopSign_ == '<') || (stopSign_ == '>')) { return true; }
return false;
}
inline const std::int64_t& GetStopPrice() const { return stopPrice_; }
inline bool IsGreaterThan() const
{
if (stopSign_ == '>') { return true; }
return false;
}
inline bool IsLessThan() const
{
if (stopSign_ == '<') { return true; }
return false;
}
// optionally returns the offer's market ID and a pointer to the market.
OTOffer* GetOffer(OTMarket** market = nullptr);
// optionally returns the offer's market ID and a pointer to the market.
OTOffer* GetOffer(Identifier& offerMarketId, OTMarket** market = nullptr);
inline const Identifier& GetCurrencyID() const { return currencyTypeID_; }
inline void SetCurrencyID(const Identifier& currencyId)
{
currencyTypeID_ = currencyId;
}
inline const Identifier& GetCurrencyAcctID() const
{
return currencyAcctID_;
}
inline void SetCurrencyAcctID(const Identifier& currencyAcctID)
{
currencyAcctID_ = currencyAcctID;
}
inline void IncrementTradesAlreadyDone() { tradesAlreadyDone_++; }
inline std::int32_t GetCompletedCount() { return tradesAlreadyDone_; }
EXPORT std::int64_t GetAssetAcctClosingNum() const;
EXPORT std::int64_t GetCurrencyAcctClosingNum() const;
// Return True if should stay on OTCron's list for more processing.
// Return False if expired or otherwise should be removed.
bool ProcessCron() override; // OTCron calls this regularly, which is my
// chance to expire, etc.
bool CanRemoveItemFromCron(const ClientContext& context) override;
// From OTScriptable, we override this function. OTScriptable now does fancy
// stuff like checking to see
// if the Nym is an agent working on behalf of a party to the contract.
// That's how all OTScriptable-derived
// objects work by default. But OTAgreement (payment plan) and OTTrade do
// it the old way: they just check to
// see if theNym has signed *this.
//
bool VerifyNymAsAgent(const Nym& nym, const Nym& signerNym) const override;
bool VerifyNymAsAgentForAccount(const Nym& nym, const Account& account)
const override;
void InitTrade();
void Release_Trade();
void Release() override;
std::int64_t GetClosingNumber(const Identifier& acctId) const override;
// return -1 if error, 0 if nothing, and 1 if the node was processed.
std::int32_t ProcessXMLNode(irr::io::IrrXMLReader*& xml) override;
void UpdateContents() override; // Before transmission or serialization,
// this is where the ledger saves its
// contents
EXPORT virtual ~OTTrade();
protected:
void onFinalReceipt(
OTCronItem& origCronItem,
const std::int64_t& newTransactionNumber,
ConstNym originator,
ConstNym remover) override;
void onRemovalFromCron() override;
private:
friend api::implementation::Factory;
typedef OTCronItem ot_super;
OTIdentifier currencyTypeID_; // GOLD (Asset) is trading for DOLLARS
// (Currency).
OTIdentifier currencyAcctID_; // My Dollar account, used for paying for
// my Gold (say) trades.
OTOffer* offer_{nullptr}; // The pointer to the Offer (NOT responsible for
// cleaning this up!!!
// The offer is owned by the market and I only keep a pointer here for
// convenience.
bool hasTradeActivated_{false}; // Has the offer yet been first added to a
// market?
std::int64_t stopPrice_{0}; // The price limit that activates the STOP
// order.
char stopSign_{0x0}; // Value is 0, or '<', or '>'.
bool stopActivated_{false}; // If the Stop Order has already activated, I
// need to know that.
std::int32_t tradesAlreadyDone_{0}; // How many trades have already
// processed through this order? We
// keep track.
String marketOffer_; // The market offer associated with this trade.
EXPORT OTTrade(const api::Core& core);
EXPORT OTTrade(
const api::Core& core,
const Identifier& notaryID,
const Identifier& instrumentDefinitionID,
const Identifier& assetAcctId,
const Identifier& nymID,
const Identifier& currencyId,
const Identifier& currencyAcctId);
OTTrade() = delete;
};
} // namespace opentxs
#endif
| 7,296 | 2,223 |
// Copyright (c) 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 "net/quiche/common/platform/impl/quiche_test_impl.h"
#include <string>
namespace quiche {
namespace test {
std::string QuicheGetCommonSourcePathImpl() {
return "third_party/quiche/common";
}
} // namespace test
} // namespace quiche
| 420 | 140 |
/**
\file
\author Kenta Suzuki
*/
#include "MotionPlannerDialog.h"
#include <cnoid/BodyItem>
#include <cnoid/Button>
#include <cnoid/CheckBox>
#include <cnoid/ComboBox>
#include <cnoid/EigenTypes>
#include <cnoid/JointPath>
#include <cnoid/MenuManager>
#include <cnoid/MeshGenerator>
#include <cnoid/MessageView>
#include <cnoid/PositionDragger>
#include <cnoid/RootItem>
#include <cnoid/SceneDrawables>
#include <cnoid/SceneView>
#include <cnoid/SceneWidget>
#include <cnoid/Separator>
#include <cnoid/SpinBox>
#include <cnoid/Timer>
#include <cnoid/ViewManager>
#include <cnoid/WorldItem>
#include <fmt/format.h>
#include <QColor>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
#include <ompl/base/SpaceInformation.h>
#include <ompl/base/spaces/SE3StateSpace.h>
#include <ompl/geometric/planners/rrt/RRT.h>
#include <ompl/geometric/planners/rrt/RRTConnect.h>
#include <ompl/geometric/planners/rrt/RRTstar.h>
#include <ompl/geometric/planners/rrt/pRRT.h>
#include <ompl/geometric/SimpleSetup.h>
#include <ompl/config.h>
#include "gettext.h"
#include "sample/SimpleController/Interpolator.h"
using namespace std;
using namespace cnoid;
namespace ob = ompl::base;
namespace og = ompl::geometric;
MotionPlannerDialog* plannerDialog = nullptr;
namespace cnoid {
class MotionPlannerDialogImpl
{
public:
MotionPlannerDialogImpl(MotionPlannerDialog* self);
MotionPlannerDialog* self;
SgSwitchableGroupPtr startScene;
SgSwitchableGroupPtr goalScene;
SgSwitchableGroupPtr statesScene;
SgSwitchableGroupPtr solutionScene;
SgShape* currentShape;
Affine3 currentTransform;
ItemList<BodyItem> bodyItems;
BodyItem* bodyItem;
Body* body;
Link* baseLink;
Link* endLink;
WorldItem* worldItem;
ComboBox* bodyCombo;
ComboBox* baseCombo;
ComboBox* endCombo;
ComboBox* plannerCombo;
CheckBox* statesCheck;
CheckBox* solutionCheck;
CheckBox* cubicCheck;
DoubleSpinBox* cubicSpin;
DoubleSpinBox* xminSpin;
DoubleSpinBox* xmaxSpin;
DoubleSpinBox* yminSpin;
DoubleSpinBox* ymaxSpin;
DoubleSpinBox* zminSpin;
DoubleSpinBox* zmaxSpin;
DoubleSpinBox* startxSpin;
DoubleSpinBox* startySpin;
DoubleSpinBox* startzSpin;
DoubleSpinBox* goalxSpin;
DoubleSpinBox* goalySpin;
DoubleSpinBox* goalzSpin;
DoubleSpinBox* timeLengthSpin;
DoubleSpinBox* timeSpin;
CheckBox* startCheck;
CheckBox* goalCheck;
ToggleButton* previewButton;
PushButton* startButton;
PushButton* goalButton;
MessageView* messageView;
vector<Vector3> solutions;
Interpolator<VectorXd> interpolator;
double time;
double timeStep;
double timeLength;
Timer* timer;
bool isSolved;
PositionDraggerPtr startDragger;
PositionDraggerPtr goalDragger;
void onTargetLinkChanged();
void onStartButtonClicked();
void onGoalButtonClicked();
void onGenerateButtonClicked();
void onPreviewButtonToggled(bool on);
void onPreviewTimeout();
void onCheckToggled();
void onCurrentIndexChanged(int index);
void onStartValueChanged();
void onGoalValueChanged();
void onStartPositionDragged();
void onGoalPositionDragged();
void planWithSimpleSetup();
bool isStateValid(const ob::State* state);
void onAccepted();
void onRejected();
};
}
MotionPlannerDialog::MotionPlannerDialog()
{
impl = new MotionPlannerDialogImpl(this);
}
MotionPlannerDialogImpl::MotionPlannerDialogImpl(MotionPlannerDialog* self)
: self(self)
{
self->setWindowTitle(_("Motion Planner"));
currentShape = nullptr;
bodyItems.clear();
bodyItem = nullptr;
body = nullptr;
baseLink = nullptr;
endLink = nullptr;
worldItem = nullptr;
messageView = MessageView::instance();
solutions.clear();
interpolator.clear();
time = 0.0;
timeStep = 0.001;
timeLength = 1.0;
timer = new Timer();
timer->start(1);
isSolved = false;
startDragger = nullptr;
goalDragger = nullptr;
MeshGenerator generator;
startScene = new SgSwitchableGroup();
startScene->setTurnedOn(false);
startDragger = new PositionDragger(
PositionDragger::TranslationAxes, PositionDragger::WideHandle);
startDragger->setDragEnabled(true);
startDragger->setOverlayMode(true);
startDragger->setPixelSize(48, 2);
startDragger->setDisplayMode(PositionDragger::DisplayInEditMode);
SgPosTransform* startPos = new SgPosTransform();
SgGroup* startGroup = new SgGroup();
SgShape* startShape = new SgShape();
SgMesh* startMesh = generator.generateSphere(0.05);
SgMaterial* startMaterial = new SgMaterial();
startMaterial->setDiffuseColor(Vector3(0.0, 0.0, 1.0));
startShape->setMesh(startMesh);
startShape->setMaterial(startMaterial);
startGroup->addChild(startShape);
startGroup->addChild(startDragger);
startPos->addChild(startGroup);
startScene->addChild(startPos);
startDragger->adjustSize(startShape->boundingBox());
startDragger->sigPositionDragged().connect([&](){ onStartPositionDragged(); });
goalScene = new SgSwitchableGroup();
goalScene->setTurnedOn(false);
goalDragger = new PositionDragger(
PositionDragger::TranslationAxes, PositionDragger::WideHandle);
goalDragger->setDragEnabled(true);
goalDragger->setOverlayMode(true);
goalDragger->setPixelSize(48, 2);
goalDragger->setDisplayMode(PositionDragger::DisplayInEditMode);
SgPosTransform* goalPos = new SgPosTransform();
SgGroup* goalGroup = new SgGroup();
SgShape* goalShape = new SgShape();
SgMesh* goalMesh = generator.generateSphere(0.05);
SgMaterial* goalMaterial = new SgMaterial();
goalMaterial->setDiffuseColor(Vector3(1.0, 0.0, 0.0));
goalShape->setMesh(goalMesh);
goalShape->setMaterial(goalMaterial);
goalGroup->addChild(goalShape);
goalGroup->addChild(goalDragger);
goalPos->addChild(goalGroup);
goalScene->addChild(goalPos);
goalDragger->adjustSize(goalShape->boundingBox());
goalDragger->sigPositionDragged().connect([&](){ onGoalPositionDragged(); });
statesScene = new SgSwitchableGroup();
statesScene->setTurnedOn(false);
solutionScene = new SgSwitchableGroup();
solutionScene->setTurnedOn(false);
SceneWidget* sceneWidget = SceneView::instance()->sceneWidget();
sceneWidget->sceneRoot()->addChild(startScene);
sceneWidget->sceneRoot()->addChild(goalScene);
sceneWidget->sceneRoot()->addChild(statesScene);
sceneWidget->sceneRoot()->addChild(solutionScene);
QVBoxLayout* vbox = new QVBoxLayout();
HSeparatorBox* tbsbox = new HSeparatorBox(new QLabel(_("Target Body")));
vbox->addLayout(tbsbox);
QGridLayout* tbgbox = new QGridLayout();
bodyCombo = new ComboBox();
baseCombo = new ComboBox();
endCombo = new ComboBox();
tbgbox->addWidget(new QLabel(_("Body")), 0, 0);
tbgbox->addWidget(bodyCombo, 0, 1);
tbgbox->addWidget(new QLabel(_("Base Link")), 1, 0);
tbgbox->addWidget(baseCombo, 1, 1);
tbgbox->addWidget(new QLabel(_("End Link")), 1, 2);
tbgbox->addWidget(endCombo, 1, 3);
vbox->addLayout(tbgbox);
HSeparatorBox* bbsbox = new HSeparatorBox(new QLabel(_("Bounding Box")));
vbox->addLayout(bbsbox);
QGridLayout* bbgbox = new QGridLayout();
cubicCheck = new CheckBox();
cubicCheck->setText(_("Cubic BB"));
cubicSpin = new DoubleSpinBox();
cubicSpin->setRange(0.0, 1000.0);
cubicSpin->setValue(1.0);
cubicSpin->setAlignment(Qt::AlignCenter);
cubicSpin->setEnabled(false);
xminSpin = new DoubleSpinBox();
xminSpin->setRange(-1000.0, 0.0);
xminSpin->setValue(-1.0);
xminSpin->setAlignment(Qt::AlignCenter);
xmaxSpin = new DoubleSpinBox();
xmaxSpin->setRange(0.0, 1000.0);
xmaxSpin->setValue(1.0);
xmaxSpin->setAlignment(Qt::AlignCenter);
yminSpin = new DoubleSpinBox();
yminSpin->setRange(-1000.0, 0.0);
yminSpin->setValue(-1.0);
yminSpin->setAlignment(Qt::AlignCenter);
ymaxSpin = new DoubleSpinBox();
ymaxSpin->setRange(0.0, 1000.0);
ymaxSpin->setValue(1.0);
ymaxSpin->setAlignment(Qt::AlignCenter);
zminSpin = new DoubleSpinBox();
zminSpin->setRange(-1000.0, 0.0);
zminSpin->setValue(-1.0);
zminSpin->setAlignment(Qt::AlignCenter);
zmaxSpin = new DoubleSpinBox();
zmaxSpin->setRange(0.0, 1000.0);
zmaxSpin->setValue(1.0);
zmaxSpin->setAlignment(Qt::AlignCenter);
bbgbox->addWidget(cubicCheck, 0, 0);
bbgbox->addWidget(cubicSpin, 0, 1);
bbgbox->addWidget(new QLabel(_("min[x, y, z]")), 1, 0);
bbgbox->addWidget(xminSpin, 1, 1);
bbgbox->addWidget(yminSpin, 1, 2);
bbgbox->addWidget(zminSpin, 1, 3);
bbgbox->addWidget(new QLabel(_("max[x, y, z]")), 2, 0);
bbgbox->addWidget(xmaxSpin, 2, 1);
bbgbox->addWidget(ymaxSpin, 2, 2);
bbgbox->addWidget(zmaxSpin, 2, 3);
vbox->addLayout(bbgbox);
HSeparatorBox* ctsbox = new HSeparatorBox(new QLabel(_("Path Generation")));
vbox->addLayout(ctsbox);
QGridLayout* pgbox = new QGridLayout();
plannerCombo = new ComboBox();
QStringList planners = { "RRT", "RRTConnect", "RRT*", "pRRT" };
plannerCombo->addItems(planners);
timeSpin = new DoubleSpinBox();
timeSpin->setRange(0.0, 1000.0);
timeSpin->setValue(1.0);
timeSpin->setAlignment(Qt::AlignCenter);
statesCheck = new CheckBox();
statesCheck->setText(_("Show states"));
statesCheck->setChecked(false);
solutionCheck = new CheckBox();
solutionCheck->setText(_("Show solution"));
solutionCheck->setChecked(false);
startCheck = new CheckBox();
startCheck->setChecked(false);
startCheck->setText(_("Start[x, y, z]"));
startxSpin = new DoubleSpinBox();
startxSpin->setRange(-1000.0, 1000.0);
startxSpin->setSingleStep(0.01);
startxSpin->setValue(0.0);
startxSpin->setAlignment(Qt::AlignCenter);
startySpin = new DoubleSpinBox();
startySpin->setRange(-1000.0, 1000.0);
startySpin->setSingleStep(0.01);
startySpin->setValue(0.0);
startySpin->setAlignment(Qt::AlignCenter);
startzSpin = new DoubleSpinBox();
startzSpin->setRange(-1000.0, 1000.0);
startzSpin->setSingleStep(0.01);
startzSpin->setValue(0.0);
startzSpin->setAlignment(Qt::AlignCenter);
goalCheck = new CheckBox();
goalCheck->setChecked(false);
goalCheck->setText(_("Goal[x, y, z]"));
goalxSpin = new DoubleSpinBox();
goalxSpin->setRange(-1000.0, 1000.0);
goalxSpin->setSingleStep(0.01);
goalxSpin->setValue(0.0);
goalxSpin->setAlignment(Qt::AlignCenter);
goalySpin = new DoubleSpinBox();
goalySpin->setRange(-1000.0, 1000.0);
goalySpin->setSingleStep(0.01);
goalySpin->setValue(0.0);
goalySpin->setAlignment(Qt::AlignCenter);
goalzSpin = new DoubleSpinBox();
goalzSpin->setRange(-1000.0, 1000.0);
goalzSpin->setSingleStep(0.01);
goalzSpin->setValue(0.0);
goalzSpin->setAlignment(Qt::AlignCenter);
startButton = new PushButton(_("Set start"));
goalButton = new PushButton(_("Set goal"));
pgbox->addWidget(new QLabel(_("Geometric planner")), 0, 0);
pgbox->addWidget(plannerCombo, 0, 1);
pgbox->addWidget(startButton, 0, 2);
pgbox->addWidget(goalButton, 0, 3);
pgbox->addWidget(startCheck, 1, 0);
pgbox->addWidget(startxSpin, 1, 1);
pgbox->addWidget(startySpin, 1, 2);
pgbox->addWidget(startzSpin, 1, 3);
pgbox->addWidget(goalCheck, 2, 0);
pgbox->addWidget(goalxSpin, 2, 1);
pgbox->addWidget(goalySpin, 2, 2);
pgbox->addWidget(goalzSpin, 2, 3);
pgbox->addWidget(new QLabel(_("Calculation time")), 3, 0);
pgbox->addWidget(timeSpin, 3, 1);
vbox->addLayout(pgbox);
HSeparatorBox* psbox = new HSeparatorBox(new QLabel(_("Preview")));
vbox->addLayout(psbox);
PushButton* generateButton = new PushButton(_("Generate"));
previewButton = new ToggleButton(_("Preview"));
timeLengthSpin = new DoubleSpinBox();
timeLengthSpin->setRange(1.0, 1000.0);
timeLengthSpin->setValue(1.0);
timeLengthSpin->setAlignment(Qt::AlignCenter);
QGridLayout* pvbox = new QGridLayout();
pvbox->addWidget(solutionCheck, 0, 0);
pvbox->addWidget(statesCheck, 0, 1);
pvbox->addWidget(generateButton, 0, 2);
pvbox->addWidget(new QLabel(_("Time length")), 1, 0);
pvbox->addWidget(timeLengthSpin, 1, 1);
pvbox->addWidget(previewButton, 1, 2);
vbox->addLayout(pvbox);
vbox->addWidget(new HSeparator);
QPushButton* okButton = new QPushButton(_("&Ok"));
okButton->setDefault(true);
QDialogButtonBox* buttonBox = new QDialogButtonBox(self);
buttonBox->addButton(okButton, QDialogButtonBox::AcceptRole);
self->connect(buttonBox,SIGNAL(accepted()), self, SLOT(accept()));
vbox->addWidget(buttonBox);
generateButton->sigClicked().connect([&](){ onGenerateButtonClicked(); });
RootItem::instance()->sigCheckToggled().connect([&](Item* item, bool on){
onCheckToggled();
});
previewButton->sigToggled().connect([&](bool on){ onPreviewButtonToggled(on); });
bodyCombo->sigCurrentIndexChanged().connect([&](int index){ onCurrentIndexChanged(index); });
cubicCheck->sigToggled().connect([&](bool on){
cubicSpin->setEnabled(on);
xminSpin->setEnabled(!on);
xmaxSpin->setEnabled(!on);
yminSpin->setEnabled(!on);
ymaxSpin->setEnabled(!on);
zminSpin->setEnabled(!on);
zmaxSpin->setEnabled(!on);
});
cubicSpin->sigValueChanged().connect([&](double value){
xminSpin->setValue(-1.0 * value);
xmaxSpin->setValue(value);
yminSpin->setValue(-1.0 * value);
ymaxSpin->setValue(value);
zminSpin->setValue(-1.0 * value);
zmaxSpin->setValue(value);
});
statesCheck->sigToggled().connect([&](bool on){
statesScene->setTurnedOn(on);
statesScene->notifyUpdate();
});
solutionCheck->sigToggled().connect([&](bool on){
solutionScene->setTurnedOn(on);
solutionScene->notifyUpdate();
});
startCheck->sigToggled().connect([&](bool on){
startScene->setTurnedOn(on);
startScene->notifyUpdate();
});
goalCheck->sigToggled().connect([&](bool on){
goalScene->setTurnedOn(on);
goalScene->notifyUpdate();
});
startxSpin->sigValueChanged().connect([&](double value){ onStartValueChanged(); });
startySpin->sigValueChanged().connect([&](double value){ onStartValueChanged(); });
startzSpin->sigValueChanged().connect([&](double value){ onStartValueChanged(); });
goalxSpin->sigValueChanged().connect([&](double value){ onGoalValueChanged(); });
goalySpin->sigValueChanged().connect([&](double value){ onGoalValueChanged(); });
goalzSpin->sigValueChanged().connect([&](double value){ onGoalValueChanged(); });
timer->sigTimeout().connect([&](){ onPreviewTimeout(); });
ViewManager::sigViewCreated().connect([&](View* view){
SceneView* sceneView = dynamic_cast<SceneView*>(view);
if(sceneView) {
sceneView->sceneWidget()->sceneRoot()->addChildOnce(startScene);
sceneView->sceneWidget()->sceneRoot()->addChildOnce(goalScene);
sceneView->sceneWidget()->sceneRoot()->addChildOnce(statesScene);
sceneView->sceneWidget()->sceneRoot()->addChildOnce(solutionScene);
}
});
ViewManager::sigViewRemoved().connect([&](View* view){
SceneView* sceneView = dynamic_cast<SceneView*>(view);
if(sceneView) {
sceneView->sceneWidget()->sceneRoot()->removeChild(startScene);
sceneView->sceneWidget()->sceneRoot()->removeChild(goalScene);
sceneView->sceneWidget()->sceneRoot()->removeChild(statesScene);
sceneView->sceneWidget()->sceneRoot()->removeChild(solutionScene);
}
});
startButton->sigClicked().connect([&](){ onStartButtonClicked(); });
goalButton->sigClicked().connect([&](){ onGoalButtonClicked(); });
self->setLayout(vbox);
}
MotionPlannerDialog::~MotionPlannerDialog()
{
delete impl;
}
void MotionPlannerDialog::initializeClass(ExtensionManager* ext)
{
string version = OMPL_VERSION;
MessageView::instance()->putln(fmt::format("OMPL version: {0}", version));
if(!plannerDialog) {
plannerDialog = ext->manage(new MotionPlannerDialog());
}
MenuManager& mm = ext->menuManager();
mm.setPath("/Tools");
mm.addItem(_("Motion Planner"))
->sigTriggered().connect([](){ plannerDialog->show(); });
}
MotionPlannerDialog* MotionPlannerDialog::instance()
{
return plannerDialog;
}
void MotionPlannerDialogImpl::onTargetLinkChanged()
{
bodyItem = bodyItems[bodyCombo->currentIndex()];
body = bodyItem->body();
endLink = body->link(endCombo->currentIndex());
}
void MotionPlannerDialogImpl::onStartButtonClicked()
{
onTargetLinkChanged();
if(endLink) {
Vector3 translation = endLink->T().translation();
startxSpin->setValue(translation[0]);
startySpin->setValue(translation[1]);
startzSpin->setValue(translation[2]);
}
}
void MotionPlannerDialogImpl::onGoalButtonClicked()
{
onTargetLinkChanged();
if(endLink) {
Vector3 translation = endLink->T().translation();
goalxSpin->setValue(translation[0]);
goalySpin->setValue(translation[1]);
goalzSpin->setValue(translation[2]);
}
}
void MotionPlannerDialogImpl::onGenerateButtonClicked()
{
statesScene->clearChildren();
solutionScene->clearChildren();
if(bodyItems.size()) {
bodyItem = bodyItems[bodyCombo->currentIndex()];
body = bodyItem->body();
bodyItem->restoreInitialState(true);
baseLink = body->link(baseCombo->currentIndex());
endLink = body->link(endCombo->currentIndex());
worldItem = bodyItem->findOwnerItem<WorldItem>();
}
planWithSimpleSetup();
}
void MotionPlannerDialogImpl::onPreviewButtonToggled(bool on)
{
if(on && isSolved) {
time = 0.0;
interpolator.clear();
int numPoints = solutions.size();
timeLength = timeLengthSpin->value();
double dt = timeLength / (double)numPoints;
for(size_t i = 0; i < solutions.size(); i++) {
interpolator.appendSample(dt * (double)i, solutions[i]);
}
interpolator.update();
}
}
void MotionPlannerDialogImpl::onPreviewTimeout()
{
if(body && baseLink && endLink) {
if(previewButton->isChecked()) {
auto path = JointPath::getCustomPath(body, baseLink, endLink);
VectorXd p(6);
p = interpolator.interpolate(time);
Vector3 pref = Vector3(p.head<3>());
Matrix3 rref = endLink->R();
Isometry3 T;
T.linear() = rref;
T.translation() = pref;
if(path->calcInverseKinematics(T)) {
bodyItem->notifyKinematicStateChange(true);
}
time += timeStep;
}
}
}
void MotionPlannerDialogImpl::onCheckToggled()
{
bodyItems = RootItem::instance()->checkedItems<BodyItem>();
bodyCombo->clear();
for(size_t i = 0; i < bodyItems.size(); i++) {
bodyCombo->addItem(QString::fromStdString(bodyItems[i]->name()));
}
}
void MotionPlannerDialogImpl::onCurrentIndexChanged(int index)
{
baseCombo->clear();
endCombo->clear();
if(index >= 0) {
Body* body = bodyItems[index]->body();
for(size_t i = 0; i < body->numLinks(); i++) {
Link* link = body->link(i);
baseCombo->addItem(QString::fromStdString(link->name()));
endCombo->addItem(QString::fromStdString(link->name()));
}
}
}
void MotionPlannerDialogImpl::onStartValueChanged()
{
SgPosTransform* pos = dynamic_cast<SgPosTransform*>(startScene->child(0));
Vector3 translation = Vector3(startxSpin->value(), startySpin->value(), startzSpin->value());
pos->setTranslation(translation);
startScene->notifyUpdate();
}
void MotionPlannerDialogImpl::onGoalValueChanged()
{
SgPosTransform* pos = dynamic_cast<SgPosTransform*>(goalScene->child(0));
Vector3 translation = Vector3(goalxSpin->value(), goalySpin->value(), goalzSpin->value());
pos->setTranslation(translation);
goalScene->notifyUpdate();
}
void MotionPlannerDialogImpl::onStartPositionDragged()
{
Vector3 p = startDragger->globalDraggingPosition().translation();
startxSpin->setValue(p[0]);
startySpin->setValue(p[1]);
startzSpin->setValue(p[2]);
}
void MotionPlannerDialogImpl::onGoalPositionDragged()
{
Vector3 p = goalDragger->globalDraggingPosition().translation();
goalxSpin->setValue(p[0]);
goalySpin->setValue(p[1]);
goalzSpin->setValue(p[2]);
}
void MotionPlannerDialogImpl::planWithSimpleSetup()
{
auto space(std::make_shared<ob::SE3StateSpace>());
ob::RealVectorBounds bounds(3);
bounds.setLow(0, xminSpin->value());
bounds.setHigh(0, xmaxSpin->value());
bounds.setLow(1, yminSpin->value());
bounds.setHigh(1, ymaxSpin->value());
bounds.setLow(2, zminSpin->value());
bounds.setHigh(2, zmaxSpin->value());
space->setBounds(bounds);
og::SimpleSetup ss(space);
ss.setStateValidityChecker([&](const ob::State* state) { return isStateValid(state); });
ob::ScopedState<ob::SE3StateSpace> start(space);
start->setX(startxSpin->value());
start->setY(startySpin->value());
start->setZ(startzSpin->value());
start->rotation().setIdentity();
ob::ScopedState<ob::SE3StateSpace> goal(space);
goal->setX(goalxSpin->value());
goal->setY(goalySpin->value());
goal->setZ(goalzSpin->value());
goal->rotation().setIdentity();
ss.setStartAndGoalStates(start, goal);
int index = plannerCombo->currentIndex();
switch (index) {
case 0:
{
ob::PlannerPtr planner(new og::RRT(ss.getSpaceInformation()));
ss.setPlanner(planner);
}
break;
case 1:
{
ob::PlannerPtr planner(new og::RRTConnect(ss.getSpaceInformation()));
ss.setPlanner(planner);
}
break;
case 2:
{
ob::PlannerPtr planner(new og::RRTstar(ss.getSpaceInformation()));
ss.setPlanner(planner);
}
break;
case 3:
{
ob::PlannerPtr planner(new og::pRRT(ss.getSpaceInformation()));
ss.setPlanner(planner);
}
break;
default:
break;
}
ss.setup();
// ss.print(messageView->cout());
ob::PlannerStatus solved = ss.solve(timeSpin->value());
if(solved) {
messageView->putln("Found solution:");
isSolved = true;
og::PathGeometric pathes = ss.getSolutionPath();
const int numPoints = pathes.getStateCount();
solutions.clear();
for(size_t i = 0; i < pathes.getStateCount(); i++) {
ob::State* state = pathes.getState(i);
float x = state->as<ob::SE3StateSpace::StateType>()->getX();
float y = state->as<ob::SE3StateSpace::StateType>()->getY();
float z = state->as<ob::SE3StateSpace::StateType>()->getZ();
solutions.push_back(Vector3(x, y, z));
MeshGenerator generator;
SgShape* shape = new SgShape();
shape->setMesh(generator.generateSphere(0.02));
SgMaterial* material = new SgMaterial();
int hue = 240.0 * (1.0 - (double)i / (double)(numPoints - 1));
QColor qColor = QColor::fromHsv(hue, 255, 255);
Vector3f color((double)qColor.red() / 255.0, (double)qColor.green() / 255.0, (double)qColor.blue() / 255.0);
material->setDiffuseColor(Vector3(color[0], color[1], color[2]));
material->setTransparency(0.5);
shape->setMaterial(material);
SgPosTransform* transform = new SgPosTransform();
transform->addChild(shape);
transform->setTranslation(Vector3(x, y, z));
solutionScene->addChild(transform);
if(bodyItem) {
bodyItem->restoreInitialState(true);
if(baseLink != endLink) {
auto path = JointPath::getCustomPath(body, baseLink, endLink);
Vector3 pref = Vector3(x, y, z);
Matrix3 rref = endLink->R();
Isometry3 T;
T.linear() = rref;
T.translation() = pref;
if(path->calcInverseKinematics(T)) {
bodyItem->notifyKinematicStateChange(true);
}
}
}
}
ss.simplifySolution();
// ss.getSolutionPath().print(messageView->cout());
} else {
messageView->putln("No solution found");
isSolved = false;
}
}
bool MotionPlannerDialogImpl::isStateValid(const ob::State* state)
{
const auto *se3state = state->as<ob::SE3StateSpace::StateType>();
const auto *pos = se3state->as<ob::RealVectorStateSpace::StateType>(0);
const auto *rot = se3state->as<ob::SO3StateSpace::StateType>(1);
bool solved = false;
bool collided = false;
float x = state->as<ob::SE3StateSpace::StateType>()->getX();
float y = state->as<ob::SE3StateSpace::StateType>()->getY();
float z = state->as<ob::SE3StateSpace::StateType>()->getZ();
MeshGenerator generator;
SgShape* shape = new SgShape();
shape->setMesh(generator.generateSphere(0.02));
SgMaterial* material = new SgMaterial();
material->setDiffuseColor(Vector3(0.0, 1.0, 0.0));
material->setTransparency(0.5);
shape->setMaterial(material);
SgPosTransform* transform = new SgPosTransform();
transform->addChild(shape);
transform->setTranslation(Vector3(x, y, z));
statesScene->addChild(transform);
if(bodyItem) {
bodyItem->restoreInitialState(true);
if(baseLink != endLink) {
auto path = JointPath::getCustomPath(body, baseLink, endLink);
Vector3 pref = endLink->p();
Matrix3 rref = endLink->R();
pref = Vector3(x, y, z);
Isometry3 T;
T.linear() = rref;
T.translation() = pref;
if(path->calcInverseKinematics(T)) {
bodyItem->notifyKinematicStateChange(true);
solved = true;
if(worldItem) {
worldItem->updateCollisions();
vector<CollisionLinkPairPtr> collisions = bodyItem->collisions();
for(size_t i = 0; i < collisions.size(); i++) {
CollisionLinkPairPtr collision = collisions[i];
if((collision->body[0] == body) || (collision->body[1] == body)) {
if(!collision->isSelfCollision()) {
collided = true;
}
}
}
}
}
}
}
return ((const void*)rot != (const void*)pos) && solved && !collided;
}
void MotionPlannerDialog::onAccepted()
{
impl->onAccepted();
}
void MotionPlannerDialogImpl::onAccepted()
{
}
void MotionPlannerDialog::onRejected()
{
impl->onAccepted();
}
void MotionPlannerDialogImpl::onRejected()
{
}
| 27,394 | 9,310 |
/*--------------------------------------------
Ternary search algorithm
Finds the maximum/minimum value of
any unimodal function
Here is an algorithm for finding the maximum
of a sample function f(x). Algorithm for
finding the minimum value is symmetrical
Time complexity - O(log(2/3)N)
--------------------------------------------*/
#include <bits/stdc++.h>
using namespace std;
int f(int x) {
return -x * x + 20;
}
int ternary_search(int l, int r) {
while (r - l >= 3) {
int d = (r - l) / 3;
int m1 = l + d, m2 = r - d;
if (f(m1) < f(m2)) l = m1;
else r = m2;
}
int res = f(l);
for (int i = l + 1; i <= r; i++)
res = max(res, f(i));
return res;
}
| 676 | 266 |
// Copyright (C) 2004, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#include <debug/bitset>
#include <testsuite_hooks.h>
// libstdc++/13838
void test01()
{
using __gnu_debug::bitset;
bool test __attribute__((unused)) = true;
bitset<4> b0, b1;
b0.set(1);
b0.set(3);
b1.set(2);
b1.set(3);
b0 |= b1;
bitset<4> br;
br.set(1);
br.set(2);
br.set(3);
VERIFY( b0 == br );
}
int main()
{
test01();
}
| 1,193 | 446 |
/*
WhetStone, Version 2.2
Release name: naka-to.
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Konstantin Lipnikov (lipnikov@lanl.gov)
A polynomial binded with a mesh object. This struct allows us
to verify identity of a polynomial used by multiple classes.
*/
#ifndef AMANZI_WHETSTONE_POLYNOMIAL_ON_MESH_HH_
#define AMANZI_WHETSTONE_POLYNOMIAL_ON_MESH_HH_
#include "Teuchos_RCP.hpp"
#include "Point.hh"
#include "Polynomial.hh"
#include "WhetStoneDefs.hh"
namespace Amanzi {
namespace WhetStone {
class PolynomialOnMesh {
public:
PolynomialOnMesh() : id_(-1), kind_((Entity_kind)WhetStone::CELL) {};
Polynomial& poly() { return poly_; }
const Polynomial& poly() const { return poly_; }
void set_kind(Entity_kind kind) { kind_ = kind; }
const Entity_kind& get_kind() const { return kind_; }
const Entity_ID& get_id() const { return id_; }
void set_id(Entity_ID id) { id_ = id; }
private:
Polynomial poly_;
Entity_kind kind_; // topological binding of polynomial
Entity_ID id_; // numerical id of topological entity
};
} // namespace WhetStone
} // namespace Amanzi
#endif
| 1,318 | 487 |
//=======================================================================
// Copyright 2013 University of Warsaw.
// Authors: Piotr Wygocki
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>
#include <boost/graph/find_flow_cost.hpp>
#include "../test/min_cost_max_flow_utils.hpp"
int main() {
boost::SampleGraph::vertex_descriptor s,t;
boost::SampleGraph::Graph g;
boost::SampleGraph::getSampleGraph(g, s, t);
boost::successive_shortest_path_nonnegative_weights(g, s, t);
int cost = boost::find_flow_cost(g);
assert(cost == 29);
return 0;
}
| 831 | 277 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* 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/. */
/* Queuing strategies. */
#include "builtin/streams/QueueingStrategies.h"
#include "builtin/streams/ClassSpecMacro.h" // JS_STREAMS_CLASS_SPEC
#include "js/CallArgs.h" // JS::CallArgs{,FromVp}
#include "js/Class.h" // JS::ObjectOpResult, JS_NULL_CLASS_OPS
#include "js/Conversions.h" // JS::ToNumber
#include "js/PropertySpec.h" // JS{Property,Function}Spec, JS_FN, JS_FS_END, JS_PS_END
#include "js/ProtoKey.h" // JSProto_{ByteLength,Count}QueuingStrategy
#include "js/RootingAPI.h" // JS::{Handle,Rooted}
#include "vm/JSObject.h" // js::GetPrototypeFromBuiltinConstructor
#include "vm/ObjectOperations.h" // js::{Define,Get}Property
#include "vm/Runtime.h" // JSAtomState
#include "vm/StringType.h" // js::NameToId, PropertyName
#include "vm/Compartment-inl.h" // js::UnwrapAndTypeCheckThis
#include "vm/JSObject-inl.h" // js::NewObjectWithClassProto
#include "vm/NativeObject-inl.h" // js::ThrowIfNotConstructing
using js::ByteLengthQueuingStrategy;
using js::CountQueuingStrategy;
using js::PropertyName;
using js::UnwrapAndTypeCheckThis;
using JS::CallArgs;
using JS::CallArgsFromVp;
using JS::Handle;
using JS::ObjectOpResult;
using JS::Rooted;
using JS::ToNumber;
using JS::ToObject;
using JS::Value;
/*** 6.1. Queuing strategies ************************************************/
// Streams spec, 6.1.2.2. new ByteLengthQueuingStrategy({ highWaterMark })
bool js::ByteLengthQueuingStrategy::constructor(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!ThrowIfNotConstructing(cx, args, "ByteLengthQueuingStrategy")) {
return false;
}
// Implicit in the spec: Create the new strategy object.
Rooted<JSObject*> proto(cx);
if (!GetPrototypeFromBuiltinConstructor(
cx, args, JSProto_ByteLengthQueuingStrategy, &proto)) {
return false;
}
Rooted<ByteLengthQueuingStrategy*> strategy(
cx, NewObjectWithClassProto<ByteLengthQueuingStrategy>(cx, proto));
if (!strategy) {
return false;
}
// Implicit in the spec: Argument destructuring.
RootedObject argObj(cx, ToObject(cx, args.get(0)));
if (!argObj) {
return false;
}
// https://heycam.github.io/webidl/#es-dictionary
// 3.2.17. Dictionary types
// Step 4.1.2: Let esMemberValue be an ECMAScript value,
// depending on Type(esDict): ? Get(esDict, key)
RootedValue highWaterMarkV(cx);
if (!GetProperty(cx, argObj, argObj, cx->names().highWaterMark,
&highWaterMarkV)) {
return false;
}
// Step 4.1.5: Otherwise, if esMemberValue is undefined and
// member is required, then throw a TypeError.
if (highWaterMarkV.isUndefined()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_STREAM_MISSING_HIGHWATERMARK);
return false;
}
// Step 4.1.3: If esMemberValue is not undefined, then:
// Let idlMemberValue be the result of converting esMemberValue to
// an IDL value whose type is the type member is declared to be of.
double highWaterMark;
if (!ToNumber(cx, highWaterMarkV, &highWaterMark)) {
return false;
}
// Step 1: Set this.[[highWaterMark]] to init["highWaterMark"].
strategy->setHighWaterMark(highWaterMark);
args.rval().setObject(*strategy);
return true;
}
static bool ByteLengthQueuingStrategy_highWaterMark(JSContext* cx,
unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
Rooted<ByteLengthQueuingStrategy*> unwrappedStrategy(
cx, UnwrapAndTypeCheckThis<ByteLengthQueuingStrategy>(
cx, args, "get highWaterMark"));
if (!unwrappedStrategy) {
return false;
}
// Step 1: Return this.[[highWaterMark]].
args.rval().setDouble(unwrappedStrategy->highWaterMark());
return true;
}
// Streams spec 6.1.2.3.1. size ( chunk )
static bool ByteLengthQueuingStrategy_size(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
// Step 1: Return ? GetV(chunk, "byteLength").
return GetProperty(cx, args.get(0), cx->names().byteLength, args.rval());
}
static const JSPropertySpec ByteLengthQueuingStrategy_properties[] = {
JS_PSG("highWaterMark", ByteLengthQueuingStrategy_highWaterMark,
JSPROP_ENUMERATE),
JS_STRING_SYM_PS(toStringTag, "ByteLengthQueuingStrategy", JSPROP_READONLY),
JS_PS_END};
static const JSFunctionSpec ByteLengthQueuingStrategy_methods[] = {
JS_FN("size", ByteLengthQueuingStrategy_size, 1, 0), JS_FS_END};
JS_STREAMS_CLASS_SPEC(ByteLengthQueuingStrategy, 1, SlotCount, 0, 0,
JS_NULL_CLASS_OPS);
// Streams spec, 6.1.3.2. new CountQueuingStrategy({ highWaterMark })
bool js::CountQueuingStrategy::constructor(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!ThrowIfNotConstructing(cx, args, "CountQueuingStrategy")) {
return false;
}
// Implicit in the spec: Create the new strategy object.
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(
cx, args, JSProto_CountQueuingStrategy, &proto)) {
return false;
}
Rooted<CountQueuingStrategy*> strategy(
cx, NewObjectWithClassProto<CountQueuingStrategy>(cx, proto));
if (!strategy) {
return false;
}
// Implicit in the spec: Argument destructuring.
RootedObject argObj(cx, ToObject(cx, args.get(0)));
if (!argObj) {
return false;
}
// https://heycam.github.io/webidl/#es-dictionary
// 3.2.17. Dictionary types
// Step 4.1.2: Let esMemberValue be an ECMAScript value,
// depending on Type(esDict): ? Get(esDict, key)
RootedValue highWaterMarkV(cx);
if (!GetProperty(cx, argObj, argObj, cx->names().highWaterMark,
&highWaterMarkV)) {
return false;
}
// Step 4.1.5: Otherwise, if esMemberValue is undefined and
// member is required, then throw a TypeError.
if (highWaterMarkV.isUndefined()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_STREAM_MISSING_HIGHWATERMARK);
return false;
}
// Step 4.1.3: If esMemberValue is not undefined, then:
// Let idlMemberValue be the result of converting esMemberValue to
// an IDL value whose type is the type member is declared to be of.
double highWaterMark;
if (!ToNumber(cx, highWaterMarkV, &highWaterMark)) {
return false;
}
// Step 1: Set this.[[highWaterMark]] to init["highWaterMark"].
strategy->setHighWaterMark(highWaterMark);
args.rval().setObject(*strategy);
return true;
}
static bool CountQueuingStrategy_highWaterMark(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
Rooted<CountQueuingStrategy*> unwrappedStrategy(
cx, UnwrapAndTypeCheckThis<CountQueuingStrategy>(cx, args,
"get highWaterMark"));
if (!unwrappedStrategy) {
return false;
}
// Step 1: Return this.[[highWaterMark]].
args.rval().setDouble(unwrappedStrategy->highWaterMark());
return true;
}
// Streams spec 6.1.3.3.1. size ( chunk )
static bool CountQueuingStrategy_size(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
// Step 1: Return 1.
args.rval().setInt32(1);
return true;
}
static const JSPropertySpec CountQueuingStrategy_properties[] = {
JS_PSG("highWaterMark", CountQueuingStrategy_highWaterMark,
JSPROP_ENUMERATE),
JS_STRING_SYM_PS(toStringTag, "CountQueuingStrategy", JSPROP_READONLY),
JS_PS_END};
static const JSFunctionSpec CountQueuingStrategy_methods[] = {
JS_FN("size", CountQueuingStrategy_size, 0, 0), JS_FS_END};
JS_STREAMS_CLASS_SPEC(CountQueuingStrategy, 1, SlotCount, 0, 0,
JS_NULL_CLASS_OPS);
| 8,370 | 2,838 |
// Fill out your copyright notice in the Description page of Project Settings.
#include "MeshLoader.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "Modules/ModuleManager.h"
#include "Misc/FileHelper.h"
#include "IImageWrapper.h"
#include "Runtime/ImageWrapper/Public/IImageWrapperModule.h"
#include "HAL/FileManager.h"
#include "HAL/FileManagerGeneric.h"
FMeshData ProcessMesh(aiMesh* Mesh, const aiScene* Scene)
{
FMeshData MeshData;
for (uint32 j = 0; j < Mesh->mNumVertices; ++j)
{
FVector Vertex = FVector(Mesh->mVertices[j].x, Mesh->mVertices[j].y, Mesh->mVertices[j].z);
MeshData.Vertices.Add(Vertex);
FVector Normal = FVector::ZeroVector;
if (Mesh->HasNormals())
{
Normal = FVector(Mesh->mNormals[j].x, Mesh->mNormals[j].y, Mesh->mNormals[j].z);
}
MeshData.Normals.Add(Normal);
if (Mesh->mTextureCoords[0])
{
MeshData.UVs.Add(FVector2D(static_cast<float>(Mesh->mTextureCoords[0][j].x), 1.f-static_cast<float>(Mesh->mTextureCoords[0][j].y)));
}
if (Mesh->HasTangentsAndBitangents())
{
FProcMeshTangent Tangent = FProcMeshTangent(Mesh->mTangents[j].x, Mesh->mTangents[j].y, Mesh->mTangents[j].z);
MeshData.Tangents.Add(Tangent);
}
}
UE_LOG(LogTemp, Log, TEXT("mNumFaces: %d"), Mesh->mNumFaces);
for (uint32 i = 0; i < Mesh->mNumFaces; i++)
{
aiFace Face = Mesh->mFaces[i];
for (uint32 f = 0; f < Face.mNumIndices; f++)
{
MeshData.Triangles.Add(Face.mIndices[f]);
}
}
return MeshData;
}
void ProcessNode(aiNode* Node, const aiScene* Scene, int ParentNodeIndex, int* CurrentIndex, FFinalReturnData* FinalReturnData)
{
FNodeData NodeData;
NodeData.NodeParentIndex = ParentNodeIndex;
aiMatrix4x4 TempTrans = Node->mTransformation;
FMatrix tempMatrix;
tempMatrix.M[0][0] = TempTrans.a1; tempMatrix.M[0][1] = TempTrans.b1; tempMatrix.M[0][2] = TempTrans.c1; tempMatrix.M[0][3] = TempTrans.d1;
tempMatrix.M[1][0] = TempTrans.a2; tempMatrix.M[1][1] = TempTrans.b2; tempMatrix.M[1][2] = TempTrans.c2; tempMatrix.M[1][3] = TempTrans.d2;
tempMatrix.M[2][0] = TempTrans.a3; tempMatrix.M[2][1] = TempTrans.b3; tempMatrix.M[2][2] = TempTrans.c3; tempMatrix.M[2][3] = TempTrans.d3;
tempMatrix.M[3][0] = TempTrans.a4; tempMatrix.M[3][1] = TempTrans.b4; tempMatrix.M[3][2] = TempTrans.c4; tempMatrix.M[3][3] = TempTrans.d4;
NodeData.RelativeTransformTransform = FTransform(tempMatrix);
for (uint32 n = 0; n < Node->mNumMeshes; n++)
{
uint32 MeshIndex = Node->mMeshes[n];
UE_LOG(LogTemp, Log, TEXT("Loading Mesh at index: %d"), MeshIndex);
aiMesh* Mesh = Scene->mMeshes[MeshIndex];
NodeData.Meshes.Add(ProcessMesh(Mesh, Scene));
}
FinalReturnData->Nodes.Add(NodeData);
UE_LOG(LogTemp, Log, TEXT("mNumMeshes: %d, mNumChildren of Node: %d"), Node->mNumMeshes, Node->mNumChildren);
int CurrentParentIndex = *CurrentIndex;
for (uint32 n = 0; n < Node->mNumChildren; n++)
{
(*CurrentIndex)++;
ProcessNode(Node->mChildren[n], Scene, CurrentParentIndex, CurrentIndex, FinalReturnData);
}
}
FFinalReturnData UMeshLoader::LoadMeshFromFile(FString FilePath, EPathType type)
{
FFinalReturnData ReturnData;
ReturnData.Success = false;
if (FilePath.IsEmpty())
{
UE_LOG(LogTemp, Warning, TEXT("Runtime Mesh Loader: filepath is empty.\n"));
return ReturnData;
}
std::string FinalFilePath;
switch (type)
{
case EPathType::Absolute:
FinalFilePath = TCHAR_TO_UTF8(*FilePath);
break;
case EPathType::Relative:
FinalFilePath = TCHAR_TO_UTF8(*FPaths::Combine(FPaths::ProjectContentDir(), FilePath));
break;
}
Assimp::Importer mImporter;
const aiScene* Scene = mImporter.ReadFile(FinalFilePath.c_str(), aiProcess_Triangulate | aiProcess_MakeLeftHanded | aiProcess_CalcTangentSpace | aiProcess_GenSmoothNormals | aiProcess_OptimizeMeshes);
if (Scene == nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("Runtime Mesh Loader: Read mesh file failure.\n"));
return ReturnData;
}
if (Scene->HasMeshes())
{
int NodeIndex = 0;
int* NodeIndexPtr = &NodeIndex;
ProcessNode(Scene->mRootNode, Scene, -1, NodeIndexPtr, &ReturnData);
ReturnData.Success = true;
}
return ReturnData;
}
bool UMeshLoader::DirectoryExists(FString DirectoryPath)
{
return FPaths::DirectoryExists(DirectoryPath);
}
bool UMeshLoader::CreateDirectory(FString DirectoryPath)
{
IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
if (!PlatformFile.DirectoryExists(*DirectoryPath))
{
return PlatformFile.CreateDirectoryTree(*DirectoryPath);
}
return true;
}
TArray<FString> UMeshLoader::ListFolders(FString DirectoryPath)
{
TArray<FString> Folders;
FFileManagerGeneric::Get().FindFilesRecursive(Folders, *DirectoryPath, TEXT("*"), false, true, true);
return Folders;
}
UTexture2D* UMeshLoader::LoadTexture2DFromFile(const FString& FullFilePath, bool& IsValid, int32& Width, int32& Height)
{
IsValid = false;
UTexture2D* LoadedT2D = NULL;
IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG);
//Load From File
TArray<uint8> RawFileData;
/*If you use lower unreal engine,for example the version is 4.20,you may get a error message in bulid,you should use The following code replace "TArray<uint8> RawFileData;"
const TArray<uint8>* UncompressedBGRA = NULL;*/
if (!FFileHelper::LoadFileToArray(RawFileData, * FullFilePath))
{
return NULL;
}
//Create T2D!
if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num()))
{
TArray<uint8> UncompressedBGRA;
if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA))
{
LoadedT2D = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_B8G8R8A8);
//Valid?
if (!LoadedT2D)
{
return NULL;
}
//Out!
Width = ImageWrapper->GetWidth();
Height = ImageWrapper->GetHeight();
//Copy!
void* TextureData = LoadedT2D->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
FMemory::Memcpy(TextureData, UncompressedBGRA.GetData(), UncompressedBGRA.Num());
/*if you use the code"const TArray<uint8>* UncompressedBGRA = NULL;",Accordingly, since UncompressedBGRA becomes a pointer, you need to use a pointer reference method, like this
FMemory::Memcpy(TextureData, UncompressedBGRA->GetData(), UncompressedBGRA->Num());*/
LoadedT2D->PlatformData->Mips[0].BulkData.Unlock();
//Update!
LoadedT2D->UpdateResource();
}
}
// Success!
IsValid = true;
return LoadedT2D;
}
| 6,679 | 2,651 |
/*
* Copyright 2010 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImageInfo.h"
#include "SkSafeMath.h"
#include "SkReadBuffer.h"
#include "SkWriteBuffer.h"
// These values must be constant over revisions, though they can be renamed to reflect if/when
// they are deprecated.
enum Stored_SkColorType {
kUnknown_Stored_SkColorType = 0,
kAlpha_8_Stored_SkColorType = 1,
kRGB_565_Stored_SkColorType = 2,
kARGB_4444_Stored_SkColorType = 3,
kRGBA_8888_Stored_SkColorType = 4,
kBGRA_8888_Stored_SkColorType = 5,
kIndex_8_Stored_SkColorType_DEPRECATED = 6,
kGray_8_Stored_SkColorType = 7,
kRGBA_F16_Stored_SkColorType = 8,
kRGB_888x_Stored_SkColorType = 9,
kRGBA_1010102_Stored_SkColorType = 10,
kRGB_101010x_Stored_SkColorType = 11,
};
static uint8_t live_to_stored(unsigned ct) {
switch (ct) {
case kUnknown_SkColorType: return kUnknown_Stored_SkColorType;
case kAlpha_8_SkColorType: return kAlpha_8_Stored_SkColorType;
case kRGB_565_SkColorType: return kRGB_565_Stored_SkColorType;
case kARGB_4444_SkColorType: return kARGB_4444_Stored_SkColorType;
case kRGBA_8888_SkColorType: return kRGBA_8888_Stored_SkColorType;
case kRGB_888x_SkColorType: return kRGB_888x_Stored_SkColorType;
case kBGRA_8888_SkColorType: return kBGRA_8888_Stored_SkColorType;
case kRGBA_1010102_SkColorType: return kRGBA_1010102_Stored_SkColorType;
case kRGB_101010x_SkColorType: return kRGB_101010x_Stored_SkColorType;
case kGray_8_SkColorType: return kGray_8_Stored_SkColorType;
case kRGBA_F16_SkColorType: return kRGBA_F16_Stored_SkColorType;
}
return kUnknown_Stored_SkColorType;
}
static SkColorType stored_to_live(unsigned stored) {
switch (stored) {
case kUnknown_Stored_SkColorType: return kUnknown_SkColorType;
case kAlpha_8_Stored_SkColorType: return kAlpha_8_SkColorType;
case kRGB_565_Stored_SkColorType: return kRGB_565_SkColorType;
case kARGB_4444_Stored_SkColorType: return kARGB_4444_SkColorType;
case kRGBA_8888_Stored_SkColorType: return kRGBA_8888_SkColorType;
case kRGB_888x_Stored_SkColorType: return kRGB_888x_SkColorType;
case kBGRA_8888_Stored_SkColorType: return kBGRA_8888_SkColorType;
case kRGBA_1010102_Stored_SkColorType: return kRGBA_1010102_SkColorType;
case kRGB_101010x_Stored_SkColorType: return kRGB_101010x_SkColorType;
case kIndex_8_Stored_SkColorType_DEPRECATED: return kUnknown_SkColorType;
case kGray_8_Stored_SkColorType: return kGray_8_SkColorType;
case kRGBA_F16_Stored_SkColorType: return kRGBA_F16_SkColorType;
}
return kUnknown_SkColorType;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
size_t SkImageInfo::computeByteSize(size_t rowBytes) const {
if (0 == fHeight) {
return 0;
}
SkSafeMath safe;
size_t bytes = safe.add(safe.mul(fHeight - 1, rowBytes),
safe.mul(fWidth, this->bytesPerPixel()));
return safe ? bytes : SK_MaxSizeT;
}
static bool alpha_type_is_valid(SkAlphaType alphaType) {
return (alphaType >= kUnknown_SkAlphaType) && (alphaType <= kLastEnum_SkAlphaType);
}
static bool color_type_is_valid(SkColorType colorType) {
return (colorType >= kUnknown_SkColorType) && (colorType <= kLastEnum_SkColorType);
}
SkImageInfo SkImageInfo::MakeS32(int width, int height, SkAlphaType at) {
return SkImageInfo(width, height, kN32_SkColorType, at,
SkColorSpace::MakeSRGB());
}
static const int kColorTypeMask = 0x0F;
static const int kAlphaTypeMask = 0x03;
void SkImageInfo::unflatten(SkReadBuffer& buffer) {
fWidth = buffer.read32();
fHeight = buffer.read32();
uint32_t packed = buffer.read32();
fColorType = stored_to_live((packed >> 0) & kColorTypeMask);
fAlphaType = (SkAlphaType)((packed >> 8) & kAlphaTypeMask);
buffer.validate(alpha_type_is_valid(fAlphaType) && color_type_is_valid(fColorType));
sk_sp<SkData> data = buffer.readByteArrayAsData();
fColorSpace = SkColorSpace::Deserialize(data->data(), data->size());
}
void SkImageInfo::flatten(SkWriteBuffer& buffer) const {
buffer.write32(fWidth);
buffer.write32(fHeight);
SkASSERT(0 == (fAlphaType & ~kAlphaTypeMask));
SkASSERT(0 == (fColorType & ~kColorTypeMask));
uint32_t packed = (fAlphaType << 8) | live_to_stored(fColorType);
buffer.write32(packed);
if (fColorSpace) {
sk_sp<SkData> data = fColorSpace->serialize();
if (data) {
buffer.writeDataAsByteArray(data.get());
} else {
buffer.writeByteArray(nullptr, 0);
}
} else {
sk_sp<SkData> data = SkData::MakeEmpty();
buffer.writeDataAsByteArray(data.get());
}
}
bool SkColorTypeValidateAlphaType(SkColorType colorType, SkAlphaType alphaType,
SkAlphaType* canonical) {
switch (colorType) {
case kUnknown_SkColorType:
alphaType = kUnknown_SkAlphaType;
break;
case kAlpha_8_SkColorType:
if (kUnpremul_SkAlphaType == alphaType) {
alphaType = kPremul_SkAlphaType;
}
// fall-through
case kARGB_4444_SkColorType:
case kRGBA_8888_SkColorType:
case kBGRA_8888_SkColorType:
case kRGBA_1010102_SkColorType:
case kRGBA_F16_SkColorType:
if (kUnknown_SkAlphaType == alphaType) {
return false;
}
break;
case kGray_8_SkColorType:
case kRGB_565_SkColorType:
case kRGB_888x_SkColorType:
case kRGB_101010x_SkColorType:
alphaType = kOpaque_SkAlphaType;
break;
default:
return false;
}
if (canonical) {
*canonical = alphaType;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkReadPixelsRec.h"
bool SkReadPixelsRec::trim(int srcWidth, int srcHeight) {
if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) {
return false;
}
if (0 >= fInfo.width() || 0 >= fInfo.height()) {
return false;
}
int x = fX;
int y = fY;
SkIRect srcR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height());
if (!srcR.intersect(0, 0, srcWidth, srcHeight)) {
return false;
}
// if x or y are negative, then we have to adjust pixels
if (x > 0) {
x = 0;
}
if (y > 0) {
y = 0;
}
// here x,y are either 0 or negative
fPixels = ((char*)fPixels - y * fRowBytes - x * fInfo.bytesPerPixel());
// the intersect may have shrunk info's logical size
fInfo = fInfo.makeWH(srcR.width(), srcR.height());
fX = srcR.x();
fY = srcR.y();
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkWritePixelsRec.h"
bool SkWritePixelsRec::trim(int dstWidth, int dstHeight) {
if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) {
return false;
}
if (0 >= fInfo.width() || 0 >= fInfo.height()) {
return false;
}
int x = fX;
int y = fY;
SkIRect dstR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height());
if (!dstR.intersect(0, 0, dstWidth, dstHeight)) {
return false;
}
// if x or y are negative, then we have to adjust pixels
if (x > 0) {
x = 0;
}
if (y > 0) {
y = 0;
}
// here x,y are either 0 or negative
fPixels = ((const char*)fPixels - y * fRowBytes - x * fInfo.bytesPerPixel());
// the intersect may have shrunk info's logical size
fInfo = fInfo.makeWH(dstR.width(), dstR.height());
fX = dstR.x();
fY = dstR.y();
return true;
}
| 8,250 | 2,967 |
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrTextureStripAtlas.h"
#include "GrContext.h"
#include "GrContextPriv.h"
#include "GrProxyProvider.h"
#include "GrSurfaceContext.h"
#include "SkGr.h"
#include "SkPixelRef.h"
#include "SkTSearch.h"
#ifdef SK_DEBUG
#define VALIDATE this->validate()
#else
#define VALIDATE
#endif
class GrTextureStripAtlas::Hash : public SkTDynamicHash<GrTextureStripAtlas::AtlasEntry,
GrTextureStripAtlas::Desc> {};
int32_t GrTextureStripAtlas::gCacheCount = 0;
GrTextureStripAtlas::Hash* GrTextureStripAtlas::gAtlasCache = nullptr;
GrTextureStripAtlas::Hash* GrTextureStripAtlas::GetCache() {
if (nullptr == gAtlasCache) {
gAtlasCache = new Hash;
}
return gAtlasCache;
}
// Remove the specified atlas from the cache
void GrTextureStripAtlas::CleanUp(const GrContext*, void* info) {
SkASSERT(info);
AtlasEntry* entry = static_cast<AtlasEntry*>(info);
// remove the cache entry
GetCache()->remove(entry->fDesc);
// remove the actual entry
delete entry;
if (0 == GetCache()->count()) {
delete gAtlasCache;
gAtlasCache = nullptr;
}
}
GrTextureStripAtlas* GrTextureStripAtlas::GetAtlas(const GrTextureStripAtlas::Desc& desc) {
AtlasEntry* entry = GetCache()->find(desc);
if (nullptr == entry) {
entry = new AtlasEntry;
entry->fAtlas = new GrTextureStripAtlas(desc);
entry->fDesc = desc;
desc.fContext->addCleanUp(CleanUp, entry);
GetCache()->add(entry);
}
return entry->fAtlas;
}
GrTextureStripAtlas::GrTextureStripAtlas(GrTextureStripAtlas::Desc desc)
: fCacheKey(sk_atomic_inc(&gCacheCount))
, fLockedRows(0)
, fDesc(desc)
, fNumRows(desc.fHeight / desc.fRowHeight)
, fRows(new AtlasRow[fNumRows])
, fLRUFront(nullptr)
, fLRUBack(nullptr) {
SkASSERT(fNumRows * fDesc.fRowHeight == fDesc.fHeight);
this->initLRU();
fNormalizedYHeight = SK_Scalar1 / fDesc.fHeight;
VALIDATE;
}
GrTextureStripAtlas::~GrTextureStripAtlas() { delete[] fRows; }
void GrTextureStripAtlas::lockRow(int row) {
// This should only be called on a row that is already locked.
SkASSERT(fRows[row].fLocks);
fRows[row].fLocks++;
++fLockedRows;
}
int GrTextureStripAtlas::lockRow(const SkBitmap& bitmap) {
VALIDATE;
if (!this->getContext()->contextPriv().resourceProvider()) {
// DDL TODO: For DDL we need to schedule inline & ASAP uploads. However these systems
// currently use the flushState which we can't use for the opList-based DDL phase.
// For the opList-based solution every texture strip will get its own texture proxy.
// We will revisit this for the flushState-based solution.
return -1;
}
if (0 == fLockedRows) {
this->lockTexture();
if (!fTexContext) {
return -1;
}
}
int key = bitmap.getGenerationID();
int rowNumber = -1;
int index = this->searchByKey(key);
if (index >= 0) {
// We already have the data in a row, so we can just return that row
AtlasRow* row = fKeyTable[index];
if (0 == row->fLocks) {
this->removeFromLRU(row);
}
++row->fLocks;
++fLockedRows;
// Since all the rows are always stored in a contiguous array, we can save the memory
// required for storing row numbers and just compute it with some pointer arithmetic
rowNumber = static_cast<int>(row - fRows);
} else {
// ~index is the index where we will insert the new key to keep things sorted
index = ~index;
// We don't have this data cached, so pick the least recently used row to copy into
AtlasRow* row = this->getLRU();
++fLockedRows;
if (nullptr == row) {
// force a flush, which should unlock all the rows; then try again
fDesc.fContext->contextPriv().flush(nullptr); // tighten this up?
row = this->getLRU();
if (nullptr == row) {
--fLockedRows;
return -1;
}
}
this->removeFromLRU(row);
uint32_t oldKey = row->fKey;
// If we are writing into a row that already held bitmap data, we need to remove the
// reference to that genID which is stored in our sorted table of key values.
if (oldKey != kEmptyAtlasRowKey) {
// Find the entry in the list; if it's before the index where we plan on adding the new
// entry, we decrement since it will shift elements ahead of it back by one.
int oldIndex = this->searchByKey(oldKey);
if (oldIndex < index) {
--index;
}
fKeyTable.remove(oldIndex);
}
row->fKey = key;
row->fLocks = 1;
fKeyTable.insert(index, 1, &row);
rowNumber = static_cast<int>(row - fRows);
SkASSERT(bitmap.width() == fDesc.fWidth);
SkASSERT(bitmap.height() == fDesc.fRowHeight);
// Pass in the kDontFlush flag, since we know we're writing to a part of this texture
// that is not currently in use
fTexContext->writePixels(bitmap.info(), bitmap.getPixels(), bitmap.rowBytes(),
0, rowNumber * fDesc.fRowHeight,
GrContextPriv::kDontFlush_PixelOpsFlag);
}
SkASSERT(rowNumber >= 0);
VALIDATE;
return rowNumber;
}
sk_sp<GrTextureProxy> GrTextureStripAtlas::asTextureProxyRef() const {
return fTexContext->asTextureProxyRef();
}
void GrTextureStripAtlas::unlockRow(int row) {
VALIDATE;
--fRows[row].fLocks;
--fLockedRows;
SkASSERT(fRows[row].fLocks >= 0 && fLockedRows >= 0);
if (0 == fRows[row].fLocks) {
this->appendLRU(fRows + row);
}
if (0 == fLockedRows) {
this->unlockTexture();
}
VALIDATE;
}
GrTextureStripAtlas::AtlasRow* GrTextureStripAtlas::getLRU() {
// Front is least-recently-used
AtlasRow* row = fLRUFront;
return row;
}
void GrTextureStripAtlas::lockTexture() {
static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
GrUniqueKey key;
GrUniqueKey::Builder builder(&key, kDomain, 1);
builder[0] = static_cast<uint32_t>(fCacheKey);
builder.finish();
GrProxyProvider* proxyProvider = fDesc.fContext->contextPriv().proxyProvider();
sk_sp<GrTextureProxy> proxy = proxyProvider->findOrCreateProxyByUniqueKey(
key, kTopLeft_GrSurfaceOrigin);
if (!proxy) {
GrSurfaceDesc texDesc;
texDesc.fOrigin = kTopLeft_GrSurfaceOrigin;
texDesc.fWidth = fDesc.fWidth;
texDesc.fHeight = fDesc.fHeight;
texDesc.fConfig = fDesc.fConfig;
proxy = proxyProvider->createProxy(texDesc, SkBackingFit::kExact, SkBudgeted::kYes,
GrResourceProvider::kNoPendingIO_Flag);
if (!proxy) {
return;
}
SkASSERT(proxy->origin() == kTopLeft_GrSurfaceOrigin);
proxyProvider->assignUniqueKeyToProxy(key, proxy.get());
// This is a new texture, so all of our cache info is now invalid
this->initLRU();
fKeyTable.rewind();
}
SkASSERT(proxy);
fTexContext = fDesc.fContext->contextPriv().makeWrappedSurfaceContext(std::move(proxy));
}
void GrTextureStripAtlas::unlockTexture() {
SkASSERT(fTexContext && 0 == fLockedRows);
fTexContext.reset();
}
void GrTextureStripAtlas::initLRU() {
fLRUFront = nullptr;
fLRUBack = nullptr;
// Initially all the rows are in the LRU list
for (int i = 0; i < fNumRows; ++i) {
fRows[i].fKey = kEmptyAtlasRowKey;
fRows[i].fNext = nullptr;
fRows[i].fPrev = nullptr;
this->appendLRU(fRows + i);
}
SkASSERT(nullptr == fLRUFront || nullptr == fLRUFront->fPrev);
SkASSERT(nullptr == fLRUBack || nullptr == fLRUBack->fNext);
}
void GrTextureStripAtlas::appendLRU(AtlasRow* row) {
SkASSERT(nullptr == row->fPrev && nullptr == row->fNext);
if (nullptr == fLRUFront && nullptr == fLRUBack) {
fLRUFront = row;
fLRUBack = row;
} else {
row->fPrev = fLRUBack;
fLRUBack->fNext = row;
fLRUBack = row;
}
}
void GrTextureStripAtlas::removeFromLRU(AtlasRow* row) {
SkASSERT(row);
if (row->fNext && row->fPrev) {
row->fPrev->fNext = row->fNext;
row->fNext->fPrev = row->fPrev;
} else {
if (nullptr == row->fNext) {
SkASSERT(row == fLRUBack);
fLRUBack = row->fPrev;
if (fLRUBack) {
fLRUBack->fNext = nullptr;
}
}
if (nullptr == row->fPrev) {
SkASSERT(row == fLRUFront);
fLRUFront = row->fNext;
if (fLRUFront) {
fLRUFront->fPrev = nullptr;
}
}
}
row->fNext = nullptr;
row->fPrev = nullptr;
}
int GrTextureStripAtlas::searchByKey(uint32_t key) {
AtlasRow target;
target.fKey = key;
return SkTSearch<const AtlasRow,
GrTextureStripAtlas::KeyLess>((const AtlasRow**)fKeyTable.begin(),
fKeyTable.count(),
&target,
sizeof(AtlasRow*));
}
#ifdef SK_DEBUG
void GrTextureStripAtlas::validate() {
// Our key table should be sorted
uint32_t prev = 1 > fKeyTable.count() ? 0 : fKeyTable[0]->fKey;
for (int i = 1; i < fKeyTable.count(); ++i) {
SkASSERT(prev < fKeyTable[i]->fKey);
SkASSERT(fKeyTable[i]->fKey != kEmptyAtlasRowKey);
prev = fKeyTable[i]->fKey;
}
int lruCount = 0;
// Validate LRU pointers, and count LRU entries
SkASSERT(nullptr == fLRUFront || nullptr == fLRUFront->fPrev);
SkASSERT(nullptr == fLRUBack || nullptr == fLRUBack->fNext);
for (AtlasRow* r = fLRUFront; r != nullptr; r = r->fNext) {
if (nullptr == r->fNext) {
SkASSERT(r == fLRUBack);
} else {
SkASSERT(r->fNext->fPrev == r);
}
++lruCount;
}
int rowLocks = 0;
int freeRows = 0;
for (int i = 0; i < fNumRows; ++i) {
rowLocks += fRows[i].fLocks;
if (0 == fRows[i].fLocks) {
++freeRows;
bool inLRU = false;
// Step through the LRU and make sure it's present
for (AtlasRow* r = fLRUFront; r != nullptr; r = r->fNext) {
if (r == &fRows[i]) {
inLRU = true;
break;
}
}
SkASSERT(inLRU);
} else {
// If we are locked, we should have a key
SkASSERT(kEmptyAtlasRowKey != fRows[i].fKey);
}
// If we have a key != kEmptyAtlasRowKey, it should be in the key table
SkASSERT(fRows[i].fKey == kEmptyAtlasRowKey || this->searchByKey(fRows[i].fKey) >= 0);
}
// Our count of locks should equal the sum of row locks, unless we ran out of rows and flushed,
// in which case we'll have one more lock than recorded in the rows (to represent the pending
// lock of a row; which ensures we don't unlock the texture prematurely).
SkASSERT(rowLocks == fLockedRows || rowLocks + 1 == fLockedRows);
// We should have one lru entry for each free row
SkASSERT(freeRows == lruCount);
// If we have locked rows, we should have a locked texture, otherwise
// it should be unlocked
if (fLockedRows == 0) {
SkASSERT(!fTexContext);
} else {
SkASSERT(fTexContext);
}
}
#endif
| 11,895 | 3,845 |
// Copyright 1996-2020 Cyberbotics Ltd.
//
// 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 "RobotisOp2GaitManager.hpp"
#include <MX28.h>
#include <Walking.h>
#include <minIni.h>
#include <webots/Gyro.hpp>
#include <webots/Motor.hpp>
#include <webots/Robot.hpp>
#ifdef CROSSCOMPILATION
#include <MotionManager.h>
#include <RobotisOp2MotionTimerManager.hpp>
#else
#include <MotionStatus.h>
#endif
#include <cmath>
#include <cstdlib>
#include <iostream>
using namespace Robot;
using namespace managers;
using namespace webots;
using namespace std;
static const string sotorNames[DGM_NMOTORS] = {
"ShoulderR" /*ID1 */, "ShoulderL" /*ID2 */, "ArmUpperR" /*ID3 */, "ArmUpperL" /*ID4 */, "ArmLowerR" /*ID5 */,
"ArmLowerL" /*ID6 */, "PelvYR" /*ID7 */, "PelvYL" /*ID8 */, "PelvR" /*ID9 */, "PelvL" /*ID10*/,
"LegUpperR" /*ID11*/, "LegUpperL" /*ID12*/, "LegLowerR" /*ID13*/, "LegLowerL" /*ID14*/, "AnkleR" /*ID15*/,
"AnkleL" /*ID16*/, "FootR" /*ID17*/, "FootL" /*ID18*/, "Neck" /*ID19*/, "Head" /*ID20*/
};
RobotisOp2GaitManager::RobotisOp2GaitManager(webots::Robot *robot, const std::string &iniFilename) :
mRobot(robot),
mCorrectlyInitialized(true),
mXAmplitude(0.0),
mAAmplitude(0.0),
mYAmplitude(0.0),
mMoveAimOn(false),
mBalanceEnable(true),
mIsWalking(false) {
if (!mRobot) {
cerr << "RobotisOp2GaitManager: The robot instance is required" << endl;
mCorrectlyInitialized = false;
return;
}
mBasicTimeStep = mRobot->getBasicTimeStep();
#ifndef CROSSCOMPILATION
for (int i = 0; i < DGM_NMOTORS; i++)
mMotors[i] = mRobot->getMotor(sotorNames[i]);
#endif
minIni ini(iniFilename.c_str());
mWalking = Walking::GetInstance();
mWalking->Initialize();
mWalking->LoadINISettings(&ini);
#ifdef CROSSCOMPILATION
RobotisOp2MotionTimerManager::MotionTimerInit();
MotionManager::GetInstance()->AddModule((MotionModule *)mWalking);
#endif
}
RobotisOp2GaitManager::~RobotisOp2GaitManager() {
}
void RobotisOp2GaitManager::step(int step) {
if (step < 8) {
cerr << "RobotisOp2GaitManager: steps of less than 8ms are not supported" << endl;
return;
}
#ifdef CROSSCOMPILATION
mWalking->m_Joint.SetEnableBodyWithoutHead(true, true);
MotionStatus::m_CurrentJoints.SetEnableBodyWithoutHead(true);
MotionManager::GetInstance()->SetEnable(true);
#endif
if (mIsWalking) {
mWalking->X_MOVE_AMPLITUDE = mXAmplitude;
mWalking->A_MOVE_AMPLITUDE = mAAmplitude;
mWalking->Y_MOVE_AMPLITUDE = mYAmplitude;
mWalking->A_MOVE_AIM_ON = mMoveAimOn;
mWalking->BALANCE_ENABLE = mBalanceEnable;
}
#ifndef CROSSCOMPILATION
int numberOfStepToProcess = step / 8;
if (mBalanceEnable && (mRobot->getGyro("Gyro")->getSamplingPeriod() <= 0)) {
cerr << "The Gyro is not enabled. RobotisOp2GaitManager need the Gyro to run the balance algorithm. The Gyro will be "
"automatically enabled."
<< endl;
mRobot->getGyro("Gyro")->enable(mBasicTimeStep);
myStep();
}
for (int i = 0; i < numberOfStepToProcess; i++) {
if (mBalanceEnable) {
const double *gyro = mRobot->getGyro("Gyro")->getValues();
MotionStatus::RL_GYRO = gyro[0] - 512; // 512 = central value, skip calibration step of the MotionManager,
MotionStatus::FB_GYRO = gyro[1] - 512; // because the influence of the calibration is imperceptible.
}
mWalking->Process();
}
for (int i = 0; i < (DGM_NMOTORS - 2); i++)
mMotors[i]->setPosition(valueToPosition(mWalking->m_Joint.GetValue(i + 1)));
#endif
}
void RobotisOp2GaitManager::stop() {
mIsWalking = false;
mWalking->Stop();
while (mWalking->IsRunning())
this->step(8);
#ifdef CROSSCOMPILATION
// Reset Goal Position of all motors (except Head) after walking //
for (int i = 0; i < (DGM_NMOTORS - 2); i++)
mRobot->getMotor(sotorNames[i])->setPosition(MX28::Value2Angle(mWalking->m_Joint.GetValue(i + 1)) * (M_PI / 180));
// Disable the Joints in the Gait Manager, this allow to control them again 'manualy' //
mWalking->m_Joint.SetEnableBodyWithoutHead(false, true);
MotionStatus::m_CurrentJoints.SetEnableBodyWithoutHead(false);
MotionManager::GetInstance()->SetEnable(false);
#endif
}
void RobotisOp2GaitManager::start() {
mIsWalking = true;
mWalking->Start();
}
#ifndef CROSSCOMPILATION
double RobotisOp2GaitManager::valueToPosition(unsigned short value) {
double degree = MX28::Value2Angle(value);
double position = degree / 180.0 * M_PI;
return position;
}
void RobotisOp2GaitManager::myStep() {
int ret = mRobot->step(mBasicTimeStep);
if (ret == -1)
exit(EXIT_SUCCESS);
}
#endif
| 5,124 | 2,054 |
// $Id: Foo_C_i.cpp 77008 2007-02-12 11:52:38Z johnnyw $
#include "Foo_C_i.h"
#include "AppShutdown.h"
#include "CustomExceptionC.h"
Foo_C_i::Foo_C_i()
{
for (unsigned i = 0; i < 10; i++)
{
this->count_[i] = 0;
}
}
Foo_C_i::~Foo_C_i()
{
}
void
Foo_C_i::op1(void)
{
++this->count_[0];
}
void
Foo_C_i::op2(CORBA::Long value)
{
this->in_values_[1].push_back (value);
++this->count_[1];
}
CORBA::Long
Foo_C_i::op3(CORBA::Long value)
{
this->in_values_[2].push_back (value);
++this->count_[2];
return value;
}
void
Foo_C_i::op4(CORBA::Long value)
{
this->in_values_[3].push_back (value);
++this->count_[3];
}
void
Foo_C_i::op5(void)
{
++this->count_[4];
throw FooException();
}
void
Foo_C_i::done(void)
{
TheAppShutdown->client_done();
}
void
Foo_C_i::cust_op1(void)
{
++this->count_[5];
}
void
Foo_C_i::cust_op2(long value)
{
this->in_values_[6].push_back (value);
++this->count_[6];
}
long
Foo_C_i::cust_op3(long value)
{
this->in_values_[7].push_back (value);
++this->count_[7];
return value;
}
void
Foo_C_i::cust_op4(long value)
{
this->in_values_[8].push_back (value);
++this->count_[8];
}
void
Foo_C_i::cust_op5(void)
{
++this->count_[9];
throw CustomException();
}
void
Foo_C_i::gather_stats(Foo_C_Statistics& stats)
{
for (unsigned i = 0; i < 10; i++)
{
stats.actual (i + 1, this->count_[i]);
stats.actual_in_values (i + 1, this->in_values_[i]);
}
}
void
Foo_C_i::dump()
{
static unsigned id = 0;
++id;
ACE_DEBUG((LM_DEBUG, "Servant %d Stats:\n", id));
ACE_DEBUG((LM_DEBUG, "------------------\n"));
unsigned i;
for (i = 0; i < 5; i++)
{
ACE_DEBUG((LM_DEBUG, "op%d : %d\n", i+1, this->count_[i]));
}
for (i = 5; i < 10; i++)
{
ACE_DEBUG((LM_DEBUG, "cust_op%d: %d\n", i+1, this->count_[i]));
}
ACE_DEBUG((LM_DEBUG, "------------------\n"));
}
| 1,909 | 955 |
/**
* Touhou Community Reliant Automatic Patcher
* Main DLL
*
* ----
*
* Logging functions.
*/
#include "thcrap.h"
#include <io.h>
#include <fcntl.h>
#include <ThreadPool.h>
// -------
// Globals
// -------
static HANDLE log_file = INVALID_HANDLE_VALUE;
static bool console_open = false;
static ThreadPool *log_queue = NULL;
// For checking nested thcrap instances that access the same log file.
// We only want to print an error message for the first instance.
static HANDLE log_filemapping = INVALID_HANDLE_VALUE;
static const char LOG[] = "logs/thcrap_log.txt";
static const char LOG_ROTATED[] = "logs/thcrap_log.%d.txt";
static const int ROTATIONS = 5; // Number of backups to keep
static void (*log_print_hook)(const char*) = NULL;
static void(*log_nprint_hook)(const char*, size_t) = NULL;
static HWND mbox_owner_hwnd = NULL; // Set by log_mbox_set_owner
// -----------------------
struct lasterror_t {
char str[DECIMAL_DIGITS_BOUND(DWORD) + 1];
};
THREAD_LOCAL(lasterror_t, lasterror_tls, nullptr, nullptr);
const char* lasterror_str_for(DWORD err)
{
switch(err) {
case ERROR_SHARING_VIOLATION:
return "File in use";
case ERROR_MOD_NOT_FOUND:
return "File not found";
default: // -Wswitch...
break;
}
auto str = lasterror_tls_get();
if(!str) {
static lasterror_t lasterror_static;
str = &lasterror_static;
}
snprintf(str->str, sizeof(str->str), "%lu", err);
return str->str;
}
const char* lasterror_str()
{
return lasterror_str_for(GetLastError());
}
void log_set_hook(void(*print_hook)(const char*), void(*nprint_hook)(const char*,size_t)){
log_print_hook = print_hook;
log_nprint_hook = nprint_hook;
}
// Rotation
// --------
void log_fn_for_rotation(char *fn, int rotnum)
{
if(rotnum == 0) {
strcpy(fn, LOG);
} else {
sprintf(fn, LOG_ROTATED, rotnum);
}
}
void log_rotate(void)
{
size_t rot_fn_len = MAX(sizeof(LOG_ROTATED), sizeof(LOG));
VLA(char, rot_from, rot_fn_len);
VLA(char, rot_to, rot_fn_len);
for(int rotation = ROTATIONS; rotation > 0; rotation--) {
log_fn_for_rotation(rot_from, rotation - 1);
log_fn_for_rotation(rot_to, rotation);
MoveFileExU(rot_from, rot_to, MOVEFILE_REPLACE_EXISTING);
}
VLA_FREE(rot_from);
VLA_FREE(rot_to);
}
// --------
void log_print(const char *str)
{
if (log_queue) {
log_queue->enqueue([str = strdup(str)]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, strlen(str), &byteRet, NULL);
}
if (log_file) {
WriteFile(log_file, str, strlen(str), &byteRet, NULL);
}
if (log_print_hook) {
log_print_hook(str);
}
free(str);
});
}
}
void log_print_fast(const char* str, size_t n) {
if (log_queue) {
log_queue->enqueue([str = strndup(str, n), n]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, n, &byteRet, NULL);
}
if (log_file != INVALID_HANDLE_VALUE) {
WriteFile(log_file, str, n, &byteRet, NULL);
}
if (log_print_hook) {
log_print_hook(str);
}
free(str);
});
}
}
void log_nprint(const char *str, size_t n)
{
if (log_queue) {
log_queue->enqueue([str = strndup(str, n), n]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, n, &byteRet, NULL);
}
if (log_file != INVALID_HANDLE_VALUE) {
WriteFile(log_file, str, n, &byteRet, NULL);
}
if (log_nprint_hook) {
log_nprint_hook(str, n);
}
free(str);
});
}
}
void log_vprintf(const char *format, va_list va)
{
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, str, total_size + 1);
vsprintf(str, format, va);
log_print_fast(str, total_size);
VLA_FREE(str);
}
}
void log_printf(const char *format, ...)
{
va_list va;
va_start(va, format);
log_vprintf(format, va);
va_end(va);
}
/**
* Message box functions.
*/
struct EnumStatus
{
HWND hwnd;
int w;
int h;
};
static BOOL CALLBACK enumWindowProc(HWND hwnd, LPARAM lParam)
{
EnumStatus *status = (EnumStatus*)lParam;
if (!IsWindowVisible(hwnd)) {
return TRUE;
}
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
if (pid != GetCurrentProcessId()) {
return TRUE;
}
RECT rect;
GetWindowRect(hwnd, &rect);
int w = rect.right - rect.left;
int h = rect.bottom - rect.top;
if (w * h > status->w * status->h) {
status->hwnd = hwnd;
}
return TRUE;
}
static HWND guess_mbox_owner()
{
// If an owner have been set, easy - just return it.
if (mbox_owner_hwnd) {
return mbox_owner_hwnd;
}
// Time to guess. If the current thread has an active window, it's probably a good window to steal.
HWND hwnd = GetActiveWindow();
if (hwnd) {
return hwnd;
}
// It's getting harder. Look at all the top-level visible windows of our processes, and take the biggest one.
EnumStatus status;
status.hwnd = nullptr;
status.w = 10; // Ignore windows smaller than 10x10
status.h = 10;
EnumWindows(enumWindowProc, (LPARAM)&status);
if (status.hwnd) {
return status.hwnd;
}
// Let's hope our process is allowed to take the focus.
return nullptr;
}
int log_mbox(const char *caption, const UINT type, const char *text)
{
log_printf(
"---------------------------\n"
"%s\n"
"---------------------------\n"
, text
);
return MessageBox(guess_mbox_owner(), text, (caption ? caption : PROJECT_NAME), type);
}
int log_vmboxf(const char *caption, const UINT type, const char *format, va_list va)
{
int ret = 0;
if(format) {
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, formatted_str, total_size + 1);
vsprintf(formatted_str, format, va);
ret = log_mbox(caption, type, formatted_str);
VLA_FREE(formatted_str);
}
}
return ret;
}
int log_mboxf(const char *caption, const UINT type, const char *format, ...)
{
va_list va;
va_start(va, format);
int ret = log_vmboxf(caption, type, format, va);
va_end(va);
return ret;
}
void log_mbox_set_owner(HWND hwnd)
{
mbox_owner_hwnd = hwnd;
}
static void OpenConsole(void)
{
if(console_open) {
return;
}
AllocConsole();
// To match the behavior of the native Windows console, Wine additionally
// needs read rights because its WriteConsole() implementation calls
// GetConsoleMode(), and setvbuf() because… I don't know?
freopen("CONOUT$", "w+b", stdout);
setvbuf(stdout, NULL, _IONBF, 0);
/// This breaks all normal, unlogged printf() calls to stdout!
// _setmode(_fileno(stdout), _O_U16TEXT);
console_open = true;
}
/// Per-module loggers
/// ------------------
std::nullptr_t logger_t::verrorf(const char *format, va_list va) const
{
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, formatted_str, total_size + 1 + prefix.length());
memcpy(formatted_str, prefix.data(), prefix.length());
vsprintf(formatted_str + prefix.length(), format, va);
log_mbox(err_caption, MB_OK | MB_ICONERROR, formatted_str);
VLA_FREE(formatted_str);
}
return nullptr;
}
std::nullptr_t logger_t::errorf(const char *format, ...) const
{
va_list va;
va_start(va, format);
auto ret = verrorf(format, va);
va_end(va);
return ret;
}
/// ------------------
void log_init(int console)
{
CreateDirectoryU("logs", NULL);
log_rotate();
// Using CreateFile, _open_osfhandle and _fdopen instead of plain fopen because we need the flag FILE_SHARE_DELETE for log rotation
log_file = CreateFileU(LOG, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
log_queue = new ThreadPool(1);
#ifdef _DEBUG
OpenConsole();
#else
if(log_file) {
constexpr std::string_view DashUChar = u8"―";
const size_t line_len = (strlen(PROJECT_NAME) + strlen(" logfile")) * DashUChar.length();
VLA(char, line, line_len + 1);
line[line_len] = '\0';
for (size_t i = 0; i < line_len; i += DashUChar.length()) {
memcpy(&line[i], DashUChar.data(), DashUChar.length());
}
log_printf("%s\n", line);
log_printf("%s logfile\n", PROJECT_NAME);
log_printf("Branch: %s\n", PROJECT_BRANCH);
log_printf("Version: %s\n", PROJECT_VERSION_STRING);
{
const char* months[] = {
"Invalid",
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
};
SYSTEMTIME time;
GetSystemTime(&time);
if (time.wMonth > 12) time.wMonth = 0;
log_printf("Current time: %s %d %d %d:%d:%d\n",
months[time.wMonth], time.wDay, time.wYear,
time.wHour, time.wMinute, time.wSecond);
}
log_printf("Build time: " __DATE__ " " __TIME__ "\n");
#if defined(BUILDER_NAME_W)
{
const wchar_t *builder = BUILDER_NAME_W;
UTF8_DEC(builder);
UTF8_CONV(builder);
log_printf("Built by: %s\n", builder_utf8);
UTF8_FREE(builder);
}
#elif defined(BUILDER_NAME)
log_printf("Built by: %s\n", BUILDER_NAME);
#endif
log_printf("Command line: %s\n", GetCommandLineU());
log_print("\nSystem Information:\n");
{
char cpu_brand[48] = {};
__cpuidex((int*)cpu_brand, 0x80000002, 0);
__cpuidex((int*)cpu_brand + 4, 0x80000003, 0);
__cpuidex((int*)cpu_brand + 8, 0x80000004, 0);
log_printf("CPU: %s\n", cpu_brand);
}
{
MEMORYSTATUSEX ram_stats = { sizeof(MEMORYSTATUSEX) };
GlobalMemoryStatusEx(&ram_stats);
double ram_total = (double)ram_stats.ullTotalPhys;
int div_count_total = 0;
for (;;) {
int temp = (int)(ram_total / 1024.0f);
if (temp) {
ram_total = ram_total / 1024.0f;
div_count_total++;
}
else {
break;
}
}
double ram_left = (double)ram_stats.ullAvailPhys;
int div_count_left = 0;
for (;;) {
int temp = (int)(ram_left / 1024.0f);
if (temp) {
ram_left = ram_left / 1024.0f;
div_count_left++;
}
else {
break;
}
}
const char* size_units[] = {
"B",
"KiB",
"MiB",
"GiB",
"TiB",
"PiB"
};
log_printf("RAM: %.2f%s free out of %.1f%s, %d%% used\n",
ram_left, size_units[div_count_left],
ram_total, size_units[div_count_total],
ram_stats.dwMemoryLoad
);
}
log_printf("OS/Runtime: %s\n", windows_version());
log_printf("Code pages: ANSI=%u, OEM=%u\n", GetACP(), GetOEMCP());
log_print("\nScreens:\n");
{
DISPLAY_DEVICEA display_device = {};
display_device.cb = sizeof(display_device);
for (int i = 0;
EnumDisplayDevicesA(NULL, i, &display_device, EDD_GET_DEVICE_INTERFACE_NAME);
i++
)
{
if ((display_device.StateFlags | DISPLAY_DEVICE_ATTACHED_TO_DESKTOP)) {
DEVMODEA d;
d.dmSize = sizeof(d);
DISPLAY_DEVICEA mon = {};
mon.cb = sizeof(mon);
if (!EnumDisplayDevicesA(display_device.DeviceName, 0, &mon, EDD_GET_DEVICE_INTERFACE_NAME)) {
continue;
}
log_printf("%s on %s: ", mon.DeviceString, display_device.DeviceString);
EnumDisplaySettingsA(display_device.DeviceName, ENUM_CURRENT_SETTINGS, &d);
if ((d.dmFields & DM_PELSHEIGHT) && !(d.dmFields & DM_PAPERSIZE)) {
log_printf("%dx%d@%d %dHz\n", d.dmPelsWidth, d.dmPelsHeight, d.dmBitsPerPel, d.dmDisplayFrequency);
}
}
}
}
log_printf("%s\n\n", line);
FlushFileBuffers(log_file);
VLA_FREE(line);
}
if (console) {
OpenConsole();
}
#endif
size_t cur_dir_len = GetCurrentDirectoryU(0, nullptr);
size_t full_fn_len = cur_dir_len + sizeof(LOG);
VLA(char, full_fn, full_fn_len);
defer(VLA_FREE(full_fn));
GetCurrentDirectoryU(cur_dir_len, full_fn);
full_fn[cur_dir_len - 1] = '/';
full_fn[cur_dir_len] = '\0';
str_slash_normalize(full_fn); // Necessary!
memcpy(full_fn + cur_dir_len, LOG, sizeof(LOG));
log_filemapping = CreateFileMappingU(
INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 1, full_fn
);
if(log_file == INVALID_HANDLE_VALUE && GetLastError() != ERROR_ALREADY_EXISTS) {
auto ret = log_mboxf(nullptr, MB_OKCANCEL | MB_ICONHAND,
"Error creating %s: %s\n"
"\n"
"Logging will be unavailable. "
"Further writes to this directory are likely to fail as well. "
"Moving %s to a different directory will probably fix this.\n"
"\n"
"Continue?",
full_fn, strerror(errno), PROJECT_NAME_SHORT
);
if(ret == IDCANCEL) {
auto pExitProcess = ((void (TH_STDCALL*)(UINT))detour_top(
"kernel32.dll", "ExitProcess", (FARPROC)thcrap_ExitProcess
));
pExitProcess(-1);
}
}
}
void log_exit(void)
{
// Run the destructor to ensure all remaining log messages were printed
delete log_queue;
if(console_open)
FreeConsole();
if(log_file) {
CloseHandle(log_filemapping);
CloseHandle(log_file);
log_file = INVALID_HANDLE_VALUE;
}
}
| 12,697 | 5,661 |
#ifndef TP_TALLER_DE_PROGRAMACION_FIUBA_SPRITEENEMIGO_HPP
#define TP_TALLER_DE_PROGRAMACION_FIUBA_SPRITEENEMIGO_HPP
#include "Sprite.hpp"
class SpriteEnemigo : public Sprite{
public:
virtual void morir() = 0;
virtual bool seMostroElTiempoSuficienteEnPantalla() = 0;
bool debeEspejarse() const{
return this->estaEspejado;
}
void espejar() {
this->estaEspejado = !estaEspejado;
}
protected:
bool estaEspejado;
};
#endif //TP_TALLER_DE_PROGRAMACION_FIUBA_SPRITEENEMIGO_HPP
| 562 | 235 |
#include <fcntl.h>
#include <unistd.h>
#include "tcp_helper.h"
SOCKET create_tcp_origin_sock()
{
return ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP);
}
bool set_linger_sock(SOCKET fd, int onoff, int linger)
{
struct linger slinger;
slinger.l_onoff = onoff ? 1 : 0;
slinger.l_linger = linger;
return !setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)(&slinger), sizeof(slinger));
}
SOCKET create_tcp_socket(const struct sockaddr_in& addr)
{
/* Request socket. */
SOCKET s = create_tcp_origin_sock();
if (s == INVALID_SOCKET)
{
return INVALID_SOCKET;
}
/* set nonblock */
if (!set_nonblock_sock(s, 1))
{
close(s);
return INVALID_SOCKET;
}
if (!set_linger_sock(s, 1, 0))
{
close(s);
return INVALID_SOCKET;
}
return s;
}
bool set_defer_accept_sock(SOCKET fd, int32_t defer)
{
int val = defer != 0 ? 1 : 0;
int len = sizeof(val);
return 0 == setsockopt(fd, /*SOL_TCP*/IPPROTO_TCP, defer, (const char*)&val, len);
}
bool listen_sock(SOCKET fd, int backlog)
{
return !::listen(fd, backlog);
}
SOCKET listen_nonblock_reuse_socket(uint32_t backlog, uint32_t defer_accept, const struct sockaddr_in& addr)
{
/* Request socket. */
SOCKET s = create_tcp_socket(addr);
if (s == INVALID_SOCKET)
{
return INVALID_SOCKET;
}
if (defer_accept && !set_defer_accept_sock(s, defer_accept))
{
close(s);
return INVALID_SOCKET;
}
if (!set_reuse_addr_sock(s, 1))
{
close(s);
return INVALID_SOCKET;
}
if (!set_reuse_port_sock(s, 1))
{
close(s);
return INVALID_SOCKET;
}
if (!bind_sock(s, addr))
{
close(s);
return false;
}
if (!listen_sock(s, backlog))
{
close(s);
return false;
}
return s;
}
SOCKET accept_sock(SOCKET fd, struct sockaddr_in* addr)
{
socklen_t l = sizeof(struct sockaddr_in);
return accept4(fd, (struct sockaddr*)addr, &l, SOCK_NONBLOCK | SOCK_CLOEXEC);
}
| 1,873 | 888 |
#include "qsslserver.h"
#include <QFile>
#include <QCoreApplication>
#include <QSslKey>
#include <QSslCertificate>
#include <QSslCipher>
QSslServer::QSslServer(QObject *parent) :
QTcpServer(parent),
configuration(QSslConfiguration::defaultConfiguration()),
lastError(QAbstractSocket::UnknownSocketError),
lastSslErrors()
{}
QSslSocket *QSslServer::nextPendingSslConnection()
{
return qobject_cast<QSslSocket*>(this->nextPendingConnection());
}
void QSslServer::addCaCertificate(const QSslCertificate &certificate)
{
QList<QSslCertificate> certs = this->configuration.caCertificates();
certs.append(certificate);
this->configuration.setCaCertificates(certs);
}
bool QSslServer::addCaCertificate(const QString &path, QSsl::EncodingFormat format)
{
bool ret = false;
QFile file(path);
if(file.open(QIODevice::ReadOnly))
{
QSslCertificate cert(file.readAll(), format);
if(!cert.isNull())
{
this->addCaCertificate(cert);
ret = true;
}
file.close();
}
return ret;
}
void QSslServer::addCaCertificates(const QList<QSslCertificate> &certificates)
{
QList<QSslCertificate> certs = this->configuration.caCertificates();
certs.append(certificates);
this->configuration.setCaCertificates(certs);
}
QList<QSslCertificate> QSslServer::caCertificates() const
{
return this->configuration.caCertificates();
}
void QSslServer::setCaCertificates(const QList<QSslCertificate> &certificates)
{
this->configuration.setCaCertificates(certificates);
}
QSslCertificate QSslServer::localCertificate() const
{
return this->configuration.localCertificate();
}
QList<QSslCertificate> QSslServer::localCertificateChain() const
{
return this->configuration.localCertificateChain();
}
void QSslServer::setLocalCertificate(const QSslCertificate &certificate)
{
this->configuration.setLocalCertificate(certificate);
}
bool QSslServer::setLocalCertificate(const QString &path, QSsl::EncodingFormat format)
{
bool ret = false;
QFile file(path);
if(file.open(QIODevice::ReadOnly))
{
QSslCertificate cert(file.readAll(), format);
if(!cert.isNull())
{
this->configuration.setLocalCertificate(cert);
ret = true;
}
file.close();
}
return ret;
}
void QSslServer::setLocalCertificateChain(const QList<QSslCertificate> &localChain)
{
this->configuration.setLocalCertificateChain(localChain);
}
QSslKey QSslServer::privateKey() const
{
return this->configuration.privateKey();
}
void QSslServer::setPrivateKey(const QSslKey &key)
{
this->configuration.setPrivateKey(key);
}
bool QSslServer::setPrivateKey(const QString &fileName, QSsl::KeyAlgorithm algorithm, QSsl::EncodingFormat format, const QByteArray &passPhrase)
{
bool ret = false;
QFile file(fileName);
if(file.open(QIODevice::ReadOnly))
{
QSslKey newKey(file.readAll(), algorithm, format, QSsl::PrivateKey, passPhrase);
if(!newKey.isNull())
{
this->configuration.setPrivateKey(newKey);
ret = true;
}
file.close();
}
return ret;
}
QList<QSslCipher> QSslServer::ciphers() const
{
return this->configuration.ciphers();
}
void QSslServer::setCiphers(const QList<QSslCipher> &ciphers)
{
this->configuration.setCiphers(ciphers);
}
void QSslServer::setCiphers(const QString &ciphers)
{
QStringList cphl = ciphers.split(":", QString::SkipEmptyParts);
QList<QSslCipher> cphs;
foreach(QString cph, cphl)
{
QSslCipher c(cph);
if(!c.isNull())
cphs.append(c);
}
this->configuration.setCiphers(cphs);
}
QSsl::SslProtocol QSslServer::protocol() const
{
return this->configuration.protocol();
}
void QSslServer::setProtocol(QSsl::SslProtocol protocol)
{
this->configuration.setProtocol(protocol);
}
void QSslServer::setSslConfiguration(const QSslConfiguration &configuration)
{
this->configuration = configuration;
}
QSslConfiguration QSslServer::sslConfiguration() const
{
return this->configuration;
}
QAbstractSocket::SocketError QSslServer::clientError() const
{
return this->lastError;
}
QList<QSslError> QSslServer::clientSslErrors() const
{
return this->lastSslErrors;
}
void QSslServer::incomingConnection(qintptr handle)
{
//Create Socket
QSslSocket *socket = new QSslSocket;
if (!socket)
{
qCritical() << "Not enough memory to create new QSslSocket!!!";
return;
}
if (!socket->setSocketDescriptor(handle))
{
this->lastError = socket->error();
delete socket;
emit clientError(this->lastError);
return;
}
//Connects
QObject::connect(socket, SIGNAL(encrypted()), this, SLOT(socketReady()));
QObject::connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(socketErrors(QList<QSslError>)));
QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketErrors(QAbstractSocket::SocketError)));
//set ssl data
socket->setSslConfiguration(this->configuration);
socket->startServerEncryption();
}
void QSslServer::socketReady()
{
QSslSocket *socket = qobject_cast<QSslSocket*>(QObject::sender());
if(socket != NULL)
{
socket->disconnect();
this->addPendingConnection(socket);
emit newSslConnection();
}
}
void QSslServer::socketErrors(QList<QSslError> errors)
{
this->lastSslErrors = errors;
emit clientSslErrors(errors);
QSslSocket *socket = qobject_cast<QSslSocket*>(QObject::sender());
if(socket != NULL)
socket->deleteLater();
}
void QSslServer::socketErrors(QAbstractSocket::SocketError error)
{
this->lastError = error;
emit clientError(error);
QSslSocket *socket = qobject_cast<QSslSocket*>(QObject::sender());
if(socket != NULL)
socket->deleteLater();
}
| 5,948 | 1,970 |
/**
* @file src/fileformat/types/dotnet_types/dotnet_type_reconstructor.cpp
* @brief Class for .NET reconstructor.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include <iostream>
#include "retdec/utils/conversion.h"
#include "retdec/utils/string.h"
#include "retdec/fileformat/types/dotnet_headers/metadata_tables.h"
#include "retdec/fileformat/types/dotnet_types/dotnet_data_types.h"
#include "retdec/fileformat/types/dotnet_types/dotnet_field.h"
#include "retdec/fileformat/types/dotnet_types/dotnet_type_reconstructor.h"
namespace retdec {
namespace fileformat {
namespace
{
/**
* Signature constants.
*/
const std::uint8_t FieldSignature = 0x06; ///< Field signature.
const std::uint8_t PropertySignature = 0x08; ///< Property signature.
const std::uint8_t HasThis = 0x20; ///< Flag indicating whether the method/property is static or not (has this).
const std::uint8_t Generic = 0x10; ///< Flag indicating whether the method is generic or not.
/**
* Decodes unsigned integer out of the signature.
* @param data Signature data.
* @param [out] bytesRead Amount of bytes read out of signature.
* @return Decoded unsigned integer.
*/
std::uint64_t decodeUnsigned(const std::vector<std::uint8_t>& data, std::uint64_t& bytesRead)
{
std::uint64_t result = 0;
bytesRead = 0;
// If highest bit not set, it is 1-byte number
if ((data[0] & 0x80) == 0)
{
if (data.size() < 1)
return result;
result = data[0];
bytesRead = 1;
}
// If highest bit set and second highest not set, it is 2-byte number
else if ((data[0] & 0xC0) == 0x80)
{
if (data.size() < 2)
return result;
result = ((static_cast<std::uint64_t>(data[0]) & 0x3F) << 8)
| data[1];
bytesRead = 2;
}
// If highest bit and second highest are set and third bit is not set, it is 4-byte number
else if ((data[0] & 0xE0) == 0xC0)
{
if (data.size() < 4)
return result;
result = ((static_cast<std::uint64_t>(data[0]) & 0x1F) << 24)
| (static_cast<std::uint64_t>(data[1]) << 16)
| (static_cast<std::uint64_t>(data[2]) << 8)
| data[3];
bytesRead = 4;
}
return result;
}
/**
* Decodes signed integer out of the signature.
* @param data Signature data.
* @param [out] bytesRead Amount of bytes read out of signature.
* @return Decoded signed integer.
*/
std::int64_t decodeSigned(const std::vector<std::uint8_t>& data, std::uint64_t& bytesRead)
{
std::int64_t result = 0;
bytesRead = 0;
// If highest bit not set, it is 1-byte number
if ((data[0] & 0x80) == 0)
{
if (data.size() < 1)
return result;
std::int8_t result8 = (data[0] & 0x01 ? 0x80 : 0x00)
| static_cast<std::uint64_t>(data[0]);
result = result8 >> 1;
bytesRead = 1;
}
// If highest bit set and second highest not set, it is 2-byte number
else if ((data[0] & 0xC0) == 0x80)
{
if (data.size() < 2)
return result;
std::int16_t result16 = (data[1] & 0x01 ? 0xC000 : 0x0000)
| ((static_cast<std::uint64_t>(data[0]) & 0x1F) << 8)
| static_cast<std::uint64_t>(data[1]);
result = result16 >> 1;
bytesRead = 2;
}
// If highest bit and second highest are set and third bit is not set, it is 4-byte number
else if ((data[0] & 0xE0) == 0xC0)
{
if (data.size() < 4)
return result;
std::int32_t result32 = (data[3] & 0x01 ? 0xE0000000 : 0x00000000)
| ((static_cast<std::uint64_t>(data[0]) & 0x0F) << 24)
| (static_cast<std::uint64_t>(data[1]) << 16)
| (static_cast<std::uint64_t>(data[2]) << 8)
| static_cast<std::uint64_t>(data[3]);
result = result32 >> 1;
bytesRead = 4;
}
return result;
}
/**
* Extracts the classes from the class table.
* @param classTable Class table.
* @return Classes in form of list.
*/
auto classesFromTable(const DotnetTypeReconstructor::ClassTable& classTable)
{
DotnetTypeReconstructor::ClassList classes;
classes.reserve(classTable.size());
for (auto& kv : classTable)
classes.push_back(kv.second);
return classes;
}
/**
* Extracts the generic parameter count out of class name that is stored in metadata tables.
* Class names encode this information in form of "ClassName`N" where N is number of generic parameters.
* @param className Class name.
* @return Number of generic parameters.
*/
std::uint64_t extractGenericParamsCountAndFixClassName(std::string& className)
{
// Generic types end with `N where N is number of generic parameters
std::uint64_t genericParamsCount = 0;
auto isGenericPos = className.find('`');
if (isGenericPos != std::string::npos)
{
// Obtain number of generic parameters
retdec::utils::strToNum(className.substr(isGenericPos + 1), genericParamsCount);
// Remove `N part
className.erase(isGenericPos);
}
return genericParamsCount;
}
/**
* Transforms metadata table record to visibility.
* @param source Metadata table record.
* @return Visibility.
*/
template <typename T>
DotnetTypeVisibility toTypeVisibility(const T* source)
{
if (source->isPublic())
return DotnetTypeVisibility::Public;
else if (source->isProtected())
return DotnetTypeVisibility::Protected;
else if (source->isPrivate())
return DotnetTypeVisibility::Private;
else
return DotnetTypeVisibility::Private;
}
template <>
DotnetTypeVisibility toTypeVisibility<TypeDef>(const TypeDef* source)
{
if (source->isPublic() || source->isNestedPublic())
return DotnetTypeVisibility::Public;
else if (source->isNestedProtected())
return DotnetTypeVisibility::Protected;
else if (source->isNonPublic() || source->isNestedPrivate())
return DotnetTypeVisibility::Private;
else
return DotnetTypeVisibility::Private;
}
}
/**
* Constructor.
* @param metadata Metadata stream.
* @param strings String stream.
* @param blob Blob stream.
*/
DotnetTypeReconstructor::DotnetTypeReconstructor(const MetadataStream* metadata, const StringStream* strings, const BlobStream* blob)
: metadataStream(metadata), stringStream(strings), blobStream(blob), defClassTable(), refClassTable(), methodTable(),
classToMethodTable(), methodReturnTypeAndParamTypeTable()
{
}
/**
* Reconstructs classes, methods, fields, properties and class hierarchy.
* @return @c true if reconstruction was successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstruct()
{
if (!metadataStream || !stringStream || !blobStream)
return false;
// Order matters here, because some stages of reconstruction need to have information from previous stages
// Required conditions are:
// - Reconstruction of generic parameters needs to known which classes and methods are defined
// - Reconstruction of method parameters needs to known which generic parameters exist
// - Reconstruction of fields and properties needs to know which classes are defined and which generic parameters they contain
// - Reconstruction of nested classes and base types needs to know all the classes that are defined
return reconstructClasses()
&& reconstructMethods()
&& reconstructGenericParameters()
&& reconstructMethodParameters()
&& reconstructFields()
&& reconstructProperties()
&& reconstructNestedClasses()
&& reconstructBaseTypes();
}
/**
* Returns the defined classes.
* @return Defined classes.
*/
DotnetTypeReconstructor::ClassList DotnetTypeReconstructor::getDefinedClasses() const
{
return classesFromTable(defClassTable);
}
/**
* Returns the referenced (imported) classes.
* @return Referenced (imported) classes.
*/
DotnetTypeReconstructor::ClassList DotnetTypeReconstructor::getReferencedClasses() const
{
return classesFromTable(refClassTable);
}
/**
* Links referenced (imported) classes.
*/
void DotnetTypeReconstructor::linkReconstructedClasses()
{
std::vector<bool> visited (refClassTable.size(), false);
std::vector<bool> stack (refClassTable.size(), false);
auto typeRefTable = static_cast<const MetadataTable<TypeRef>*>(metadataStream->getMetadataTable(MetadataTableType::TypeRef));
if (!typeRefTable)
{
return;
}
auto refClasses = getReferencedClasses();
for (size_t i = 1; i < refClasses.size(); i++)
{
linkReconstructedClassesDo(i, visited, stack, refClasses, typeRefTable);
}
for (size_t i = 1; i < refClasses.size(); i++)
{
auto t = refClasses[i];
}
}
/**
* Helper function for linkReconstructedClasses()
* @param i Index of a class to be linked.
* @param visited Visited flags for cyclic linkage detection.
* @param stack Recent traversal stack for cyclic linkage detection.
* @param refClasses List of imported classes.
* @param typeRefTable Typeref table.
*/
void DotnetTypeReconstructor::linkReconstructedClassesDo(size_t i, std::vector<bool> &visited, std::vector<bool> &stack,
ClassList &refClasses, const MetadataTable<TypeRef>* typeRefTable)
{
if (visited[i])
{
return;
}
visited[i] = true;
auto typeRef = refClasses[i];
auto typeRefRaw = typeRef->getRawTypeRef();
MetadataTableType resolutionScopeType;
if (!typeRefRaw || !typeRefRaw->resolutionScope.getTable(resolutionScopeType) ||
resolutionScopeType != MetadataTableType::TypeRef)
{
return;
}
auto parentRaw = typeRefTable->getRow(typeRefRaw->resolutionScope.getIndex());
if (!parentRaw)
{
return;
}
const DotnetClass *parent = nullptr;
size_t parentI = 1;
while (parentI < refClasses.size())
{
auto parentInRefClasses = refClasses[parentI];
if (parentInRefClasses->getRawTypeRef() == parentRaw)
{
parent = parentInRefClasses.get();
break;
}
parentI++;
}
stack[i] = true;
if (!parent || stack[parentI])
{
stack[i] = false;
return;
}
typeRef->setParent(parent);
linkReconstructedClassesDo(parentI, visited, stack, refClasses, typeRefTable);
stack[i] = false;
}
/**
* Reconstructs defined and referenced (imported) classes and interfaces.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructClasses()
{
auto typeDefTable = static_cast<const MetadataTable<TypeDef>*>(metadataStream->getMetadataTable(MetadataTableType::TypeDef));
auto typeRefTable = static_cast<const MetadataTable<TypeRef>*>(metadataStream->getMetadataTable(MetadataTableType::TypeRef));
auto fieldTable = static_cast<const MetadataTable<Field>*>(metadataStream->getMetadataTable(MetadataTableType::Field));
auto methodDefTable = static_cast<const MetadataTable<MethodDef>*>(metadataStream->getMetadataTable(MetadataTableType::MethodDef));
if (typeDefTable == nullptr || typeRefTable == nullptr)
return false;
// Reconstruct defined classes from TypeDef table
for (std::size_t i = 1; i <= typeDefTable->getNumberOfRows(); ++i)
{
auto typeDef = static_cast<const TypeDef*>(typeDefTable->getRow(i));
std::size_t fieldsCount = 0;
std::size_t methodsCount = 0;
// Field & method count needs to be determined based on index the following record in the table stores
// We use size of the referenced table for the last record
auto nextTypeDef = typeDefTable->getRow(i + 1);
// Obtain number of fields if there are any
if (fieldTable && typeDef->fieldList.getIndex() <= fieldTable->getSize())
{
fieldsCount = nextTypeDef
? nextTypeDef->fieldList.getIndex() - typeDef->fieldList.getIndex()
: fieldTable->getSize() - typeDef->fieldList.getIndex() + 1;
}
// Obtain number of methods if there are any
if (methodDefTable && typeDef->methodList.getIndex() <= methodDefTable->getSize())
{
methodsCount = nextTypeDef
? nextTypeDef->methodList.getIndex() - typeDef->methodList.getIndex()
: methodDefTable->getSize() - typeDef->methodList.getIndex() + 1;
}
auto newClass = createClassDefinition(typeDef, fieldsCount, methodsCount, i);
if (newClass == nullptr)
continue;
defClassTable.emplace(i, std::move(newClass));
}
// Reconstruct referenced classes from TypeRef table
for (std::size_t i = 1; i <= typeRefTable->getNumberOfRows(); ++i)
{
auto typeRef = typeRefTable->getRow(i);
auto newClass = createClassReference(typeRef, i);
if (newClass == nullptr)
continue;
refClassTable.emplace(i, std::move(newClass));
}
linkReconstructedClasses();
return true;
}
/**
* Reconstructs methods in the classes and interfaces. Method parameters are not reconstructed here.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructMethods()
{
auto methodDefTable = static_cast<const MetadataTable<MethodDef>*>(metadataStream->getMetadataTable(MetadataTableType::MethodDef));
if (methodDefTable == nullptr)
return true;
for (const auto& kv : defClassTable)
{
// Obtain TypeDef from the class
const auto& classType = kv.second;
auto typeDef = classType->getRawTypeDef();
auto methodStartIndex = typeDef->methodList.getIndex();
for (auto i = methodStartIndex; i < methodStartIndex + classType->getDeclaredMethodsCount(); ++i)
{
auto methodDef = methodDefTable->getRow(i);
if (methodDef == nullptr)
break;
auto newMethod = createMethod(methodDef, classType.get());
if (newMethod == nullptr)
continue;
// Place method into method table so we can later associate its table index with DotnetMethod object
methodTable.emplace(i, newMethod.get());
// Do not add method to the class yet, because we don't know if return type and parameter are OK
classToMethodTable[classType.get()].push_back(std::move(newMethod));
}
}
return true;
}
/**
* Reconstructs generic parameters of classes and methods.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructGenericParameters()
{
auto genericParamTable = static_cast<const MetadataTable<GenericParam>*>(metadataStream->getMetadataTable(MetadataTableType::GenericParam));
if (genericParamTable == nullptr)
return true;
for (const auto& genericParam : *genericParamTable)
{
// Obtain generic parameter name
std::string genericParamName;
if (!stringStream->getString(genericParam.name.getIndex(), genericParamName))
continue;
genericParamName = retdec::utils::replaceNonprintableChars(genericParamName);
// Generic parameter points either to TypeDef or MethodDef table depending on what it belongs to
MetadataTableType classOrMethod;
if (!genericParam.owner.getTable(classOrMethod))
continue;
if (classOrMethod == MetadataTableType::TypeDef)
{
auto itr = defClassTable.find(genericParam.owner.getIndex());
if (itr == defClassTable.end())
continue;
itr->second->addGenericParameter(std::move(genericParamName));
}
else if (classOrMethod == MetadataTableType::MethodDef)
{
auto itr = methodTable.find(genericParam.owner.getIndex());
if (itr == methodTable.end())
continue;
itr->second->addGenericParameter(std::move(genericParamName));
}
}
return true;
}
/**
* Reconstructs parameters of methods.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructMethodParameters()
{
auto paramTable = static_cast<const MetadataTable<Param>*>(metadataStream->getMetadataTable(MetadataTableType::Param));
if (paramTable == nullptr)
return true;
// We need to iterate over classes because we need to know the owner of every single method
for (const auto& kv : defClassTable)
{
const auto& classType = kv.second;
// Now iterate over all methods
for (auto&& method : classToMethodTable[classType.get()])
{
// Obtain postponed signature
// We now know all the information required for method parameters reconstruction
auto methodDef = method->getRawRecord();
auto signature = methodReturnTypeAndParamTypeTable[method.get()];
// Reconstruct return type
auto returnType = dataTypeFromSignature(signature, classType.get(), method.get());
if (returnType == nullptr)
continue;
method->setReturnType(std::move(returnType));
// Reconstruct parameters
bool methodOk = true;
auto startIndex = methodDef->paramList.getIndex();
for (auto i = startIndex; i < startIndex + method->getDeclaredParametersCount(); ++i)
{
auto param = paramTable->getRow(i);
if (param == nullptr)
break;
auto newParam = createMethodParameter(param, classType.get(), method.get(), signature);
if (newParam == nullptr)
{
methodOk = false;
break;
}
method->addParameter(std::move(newParam));
}
// Now we can add method to class
if (methodOk)
classType->addMethod(std::move(method));
}
}
return true;
}
/**
* Reconstructs fields of classes.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructFields()
{
auto fieldTable = static_cast<const MetadataTable<Field>*>(metadataStream->getMetadataTable(MetadataTableType::Field));
if (fieldTable == nullptr)
return true;
for (const auto& kv : defClassTable)
{
const auto& classType = kv.second;
auto typeDef = classType->getRawTypeDef();
auto fieldStartIndex = typeDef->fieldList.getIndex();
for (auto i = fieldStartIndex; i < fieldStartIndex + classType->getDeclaredFieldsCount(); ++i)
{
auto field = fieldTable->getRow(i);
if (field == nullptr)
break;
auto newField = createField(field, classType.get());
if (newField == nullptr)
continue;
classType->addField(std::move(newField));
}
}
return true;
}
/**
* Reconstructs fields of classes.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructProperties()
{
// Properties does not have very nice structure and cannot be easily reconstructed
// Their reconstruction needs to be done using two tables Property and PropertyMap
// Property table contains information about every single property, however it does not contain the reference to the class it belongs to
// PropertyMap table actually contains mapping of properties to classes
auto propertyTable = static_cast<const MetadataTable<Property>*>(metadataStream->getMetadataTable(MetadataTableType::Property));
auto propertyMapTable = static_cast<const MetadataTable<PropertyMap>*>(metadataStream->getMetadataTable(MetadataTableType::PropertyMap));
if (propertyTable == nullptr || propertyMapTable == nullptr)
return true;
for (std::size_t i = 1; i <= propertyMapTable->getNumberOfRows(); ++i)
{
auto propertyMap = propertyMapTable->getRow(i);
// First obtain owning class
auto ownerIndex = propertyMap->parent.getIndex();
auto itr = defClassTable.find(ownerIndex);
if (itr == defClassTable.end())
{
continue;
}
const auto& ownerClass = itr->second;
// Property count needs to be determined based on index the following record in the table stores
// We use size of the table for the last record
auto nextPropertyMap = propertyMapTable->getRow(i + 1);
auto propertyCount = nextPropertyMap
? nextPropertyMap->propertyList.getIndex() - propertyMap->propertyList.getIndex()
: propertyTable->getSize() - propertyMap->propertyList.getIndex() + 1;
auto startIndex = propertyMap->propertyList.getIndex();
for (std::size_t propertyIndex = startIndex; propertyIndex < startIndex + propertyCount; ++propertyIndex)
{
auto property = propertyTable->getRow(propertyIndex);
if (property == nullptr)
break;
auto newProperty = createProperty(property, ownerClass.get());
if (newProperty == nullptr)
continue;
ownerClass->addProperty(std::move(newProperty));
}
}
return true;
}
/**
* Reconstructs namespaces of nested classes.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructNestedClasses()
{
// Nested classes does not have proper namespaces set so we need to fix them
auto nestedClassTable = static_cast<const MetadataTable<NestedClass>*>(metadataStream->getMetadataTable(MetadataTableType::NestedClass));
if (nestedClassTable == nullptr)
return true;
for (std::size_t i = 1; i <= nestedClassTable->getNumberOfRows(); ++i)
{
auto nestedClass = nestedClassTable->getRow(i);
auto nestedItr = defClassTable.find(nestedClass->nestedClass.getIndex());
if (nestedItr == defClassTable.end())
continue;
auto enclosingItr = defClassTable.find(nestedClass->enclosingClass.getIndex());
if (enclosingItr == defClassTable.end())
continue;
nestedItr->second->setNameSpace(enclosingItr->second->getFullyQualifiedName());
}
return true;
}
/**
* Reconstructs base types of classes.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructBaseTypes()
{
// Even though CLI does not support multiple inheritance, any class can still implement more than one interface
auto typeSpecTable = static_cast<const MetadataTable<TypeSpec>*>(metadataStream->getMetadataTable(MetadataTableType::TypeSpec));
// First reconstruct classic inheritance
for (const auto& kv : defClassTable)
{
const auto& classType = kv.second;
std::unique_ptr<DotnetDataTypeBase> baseType;
auto typeDef = classType->getRawTypeDef();
MetadataTableType extendsTable;
if (!typeDef->extends.getTable(extendsTable))
continue;
if (extendsTable == MetadataTableType::TypeDef)
{
auto itr = defClassTable.find(typeDef->extends.getIndex());
if (itr == defClassTable.end())
continue;
baseType = std::make_unique<DotnetDataTypeClass>(itr->second.get());
}
else if (extendsTable == MetadataTableType::TypeRef)
{
auto itr = refClassTable.find(typeDef->extends.getIndex());
if (itr == refClassTable.end())
continue;
baseType = std::make_unique<DotnetDataTypeClass>(itr->second.get());
}
else if (typeSpecTable && extendsTable == MetadataTableType::TypeSpec)
{
// TypeSpec table is used when class inherits from some generic type like Class<T>, Class<int> or similar
auto typeSpec = typeSpecTable->getRow(typeDef->extends.getIndex());
if (typeSpec == nullptr)
continue;
auto signature = blobStream->getElement(typeSpec->signature.getIndex());
baseType = dataTypeFromSignature(signature, classType.get(), nullptr);
if (baseType == nullptr)
continue;
}
else
continue;
classType->addBaseType(std::move(baseType));
}
// Reconstruct interface implementations from InterfaceImpl table
auto interfaceImplTable = static_cast<const MetadataTable<InterfaceImpl>*>(metadataStream->getMetadataTable(MetadataTableType::InterfaceImpl));
if (interfaceImplTable == nullptr)
return true;
for (std::size_t i = 1; i <= interfaceImplTable->getSize(); ++i)
{
auto interfaceImpl = interfaceImplTable->getRow(i);
if (interfaceImpl == nullptr)
continue;
std::unique_ptr<DotnetDataTypeBase> baseType;
auto itr = defClassTable.find(interfaceImpl->classType.getIndex());
if (itr == defClassTable.end())
continue;
MetadataTableType interfaceTable;
if (!interfaceImpl->interfaceType.getTable(interfaceTable))
continue;
if (interfaceTable == MetadataTableType::TypeDef)
{
auto itr = defClassTable.find(interfaceImpl->interfaceType.getIndex());
if (itr == defClassTable.end())
continue;
baseType = std::make_unique<DotnetDataTypeClass>(itr->second.get());
}
else if (interfaceTable == MetadataTableType::TypeRef)
{
auto itr = refClassTable.find(interfaceImpl->interfaceType.getIndex());
if (itr == refClassTable.end())
continue;
baseType = std::make_unique<DotnetDataTypeClass>(itr->second.get());
}
else if (typeSpecTable && interfaceTable == MetadataTableType::TypeSpec)
{
// TypeSpec table is used when class implements some generic interface like Interface<T>, Interface<int> or similar
auto typeSpec = typeSpecTable->getRow(interfaceImpl->interfaceType.getIndex());
if (typeSpec == nullptr)
continue;
auto signature = blobStream->getElement(typeSpec->signature.getIndex());
baseType = dataTypeFromSignature(signature, itr->second.get(), nullptr);
if (baseType == nullptr)
continue;
}
else
continue;
itr->second->addBaseType(std::move(baseType));
}
return true;
}
/**
* Creates new class definition from TypeDef table record.
* @param typeDef TypeDef table record.
* @param fieldsCount Declared number of fields.
* @param methodsCount Declared number of methods.
* @param typeDefIndex Index of TypeDef record.
* @return New class definition or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetClass> DotnetTypeReconstructor::createClassDefinition(const TypeDef* typeDef, std::size_t fieldsCount,
std::size_t methodsCount, std::size_t typeDefIndex)
{
std::string className, classNameSpace;
if (!stringStream->getString(typeDef->typeName.getIndex(), className) || !stringStream->getString(typeDef->typeNamespace.getIndex(), classNameSpace))
return nullptr;
className = retdec::utils::replaceNonprintableChars(className);
classNameSpace = retdec::utils::replaceNonprintableChars(classNameSpace);
auto genericParamsCount = extractGenericParamsCountAndFixClassName(className);
// Skip this special type, it seems to be used in C# binaries
if (className.empty() || className == "<Module>")
return nullptr;
auto newClass = std::make_unique<DotnetClass>(MetadataTableType::TypeDef, typeDefIndex);
newClass->setRawRecord(typeDef);
newClass->setName(className);
newClass->setNameSpace(classNameSpace);
newClass->setVisibility(toTypeVisibility(typeDef));
newClass->setIsInterface(typeDef->isInterface());
newClass->setIsAbstract(typeDef->isAbstract());
newClass->setIsSealed(typeDef->isSealed());
newClass->setDeclaredFieldsCount(fieldsCount);
newClass->setDeclaredMethodsCount(methodsCount);
newClass->setDeclaredGenericParametersCount(genericParamsCount);
return newClass;
}
/**
* Creates new class reference from TypeRef table record.
* @param typeRef TypeRef table record.
* @param typeRefIndex Index of typeRef table record.
* @return New class reference or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetClass> DotnetTypeReconstructor::createClassReference(const TypeRef* typeRef, std::size_t typeRefIndex)
{
std::string className, classNameSpace, classLibName;
MetadataTableType resolutionScopeType;
if (!stringStream->getString(typeRef->typeName.getIndex(), className) ||
!stringStream->getString(typeRef->typeNamespace.getIndex(), classNameSpace))
{
return nullptr;
}
if (!typeRef->resolutionScope.getTable(resolutionScopeType) || resolutionScopeType != MetadataTableType::AssemblyRef)
{
classLibName = "";
}
else
{
auto assemblyRefTable = static_cast<const MetadataTable<AssemblyRef>*>(metadataStream->getMetadataTable(MetadataTableType::AssemblyRef));
auto assemblyRef = assemblyRefTable->getRow(typeRef->resolutionScope.getIndex());
if (!assemblyRef || !stringStream->getString(assemblyRef->name.getIndex(), classLibName))
{
classLibName = "";
}
}
className = retdec::utils::replaceNonprintableChars(className);
classNameSpace = retdec::utils::replaceNonprintableChars(classNameSpace);
classLibName = retdec::utils::replaceNonprintableChars(classLibName);
auto genericParamsCount = extractGenericParamsCountAndFixClassName(className);
if (className.empty())
{
return nullptr;
}
auto newClass = std::make_unique<DotnetClass>(MetadataTableType::TypeRef, typeRefIndex);
newClass->setRawRecord(typeRef);
newClass->setName(className);
newClass->setNameSpace(classNameSpace);
newClass->setLibName(classLibName);
newClass->setDeclaredGenericParametersCount(genericParamsCount);
return newClass;
}
/**
* Creates new field from Field table record.
* @param field Field table record.
* @param ownerClass Owning class.
* @return New field or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetField> DotnetTypeReconstructor::createField(const Field* field, const DotnetClass* ownerClass)
{
std::string fieldName;
if (!stringStream->getString(field->name.getIndex(), fieldName))
return nullptr;
fieldName = retdec::utils::replaceNonprintableChars(fieldName);
auto signature = blobStream->getElement(field->signature.getIndex());
if (signature.empty() || signature[0] != FieldSignature)
return nullptr;
signature.erase(signature.begin(), signature.begin() + 1);
auto type = dataTypeFromSignature(signature, ownerClass, nullptr);
if (type == nullptr)
return nullptr;
auto newField = std::make_unique<DotnetField>();
newField->setName(fieldName);
newField->setNameSpace(ownerClass->getFullyQualifiedName());
newField->setVisibility(toTypeVisibility(field));
newField->setDataType(std::move(type));
newField->setIsStatic(field->isStatic());
return newField;
}
/**
* Creates new property from Property table record.
* @param property Property table record.
* @param ownerClass Owning class.
* @return New property or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetProperty> DotnetTypeReconstructor::createProperty(const Property* property, const DotnetClass* ownerClass)
{
std::string propertyName;
if (!stringStream->getString(property->name.getIndex(), propertyName))
return nullptr;
propertyName = retdec::utils::replaceNonprintableChars(propertyName);
auto signature = blobStream->getElement(property->type.getIndex());
if (signature.size() < 2 || (signature[0] & ~HasThis) != PropertySignature)
return nullptr;
bool hasThis = signature[0] & HasThis;
// Delete two bytes because the first is 0x08 (or 0x28 if HASTHIS is set) and the other one is number of parameters
// This seems like a weird thing, because I don't think that C# allows any parameters in getters/setters and therefore this will always be 0
signature.erase(signature.begin(), signature.begin() + 2);
auto type = dataTypeFromSignature(signature, ownerClass, nullptr);
if (type == nullptr)
return nullptr;
auto newProperty = std::make_unique<DotnetProperty>();
newProperty->setName(propertyName);
newProperty->setNameSpace(ownerClass->getFullyQualifiedName());
newProperty->setIsStatic(!hasThis);
newProperty->setDataType(std::move(type));
return newProperty;
}
/**
* Creates new method from MethodDef table record.
* @param methodDef MethodDef table record.
* @param ownerClass Owning class.
* @return New method or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetMethod> DotnetTypeReconstructor::createMethod(const MethodDef* methodDef, const DotnetClass* ownerClass)
{
std::string methodName;
if (!stringStream->getString(methodDef->name.getIndex(), methodName))
return nullptr;
methodName = retdec::utils::replaceNonprintableChars(methodName);
auto signature = blobStream->getElement(methodDef->signature.getIndex());
if (methodName.empty() || signature.empty())
return nullptr;
// If method contains generic paramters, we need to read the number of these generic paramters
if (signature[0] & Generic)
{
signature.erase(signature.begin(), signature.begin() + 1);
// We ignore this value just because we have this information already from the class name in format 'ClassName`N'
std::uint64_t bytesRead = 0;
decodeUnsigned(signature, bytesRead);
if (bytesRead == 0)
return nullptr;
signature.erase(signature.begin(), signature.begin() + bytesRead);
}
else
{
signature.erase(signature.begin(), signature.begin() + 1);
}
// It is followed by number of parameters
std::uint64_t bytesRead = 0;
std::uint64_t paramsCount = decodeUnsigned(signature, bytesRead);
if (bytesRead == 0)
return nullptr;
signature.erase(signature.begin(), signature.begin() + bytesRead);
auto newMethod = std::make_unique<DotnetMethod>();
newMethod->setRawRecord(methodDef);
newMethod->setName(methodName);
newMethod->setNameSpace(ownerClass->getFullyQualifiedName());
newMethod->setVisibility(toTypeVisibility(methodDef));
newMethod->setIsStatic(methodDef->isStatic());
newMethod->setIsVirtual(methodDef->isVirtual());
newMethod->setIsAbstract(methodDef->isAbstract());
newMethod->setIsFinal(methodDef->isFinal());
newMethod->setIsConstructor(methodName == ".ctor" || methodName == ".cctor");
newMethod->setDeclaredParametersCount(paramsCount);
// We need to postpone loading of return type and parameters because first we need to known all generic types
// However, we can't reconstruct generic types until we know all classes and methods, so we first create method just with its name, properties and parameter count
methodReturnTypeAndParamTypeTable.emplace(newMethod.get(), signature);
return newMethod;
}
/**
* Creates new method parameter from Param table record.
* @param param Param table record.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @param signature Signature with data types. Is destroyed in the meantime.
* @return New method parameter or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetParameter> DotnetTypeReconstructor::createMethodParameter(const Param* param, const DotnetClass* ownerClass,
const DotnetMethod* ownerMethod, std::vector<std::uint8_t>& signature)
{
std::string paramName;
if (!stringStream->getString(param->name.getIndex(), paramName))
return nullptr;
paramName = retdec::utils::replaceNonprintableChars(paramName);
auto type = dataTypeFromSignature(signature, ownerClass, ownerMethod);
if (type == nullptr)
return nullptr;
auto newParam = std::make_unique<DotnetParameter>();
newParam->setName(paramName);
newParam->setNameSpace(ownerMethod->getFullyQualifiedName());
newParam->setDataType(std::move(type));
return newParam;
}
/**
* Creates data type from signature that references defined or imported class.
* @param data Signature data.
* @return New data type or @c nullptr in case of failure.
*/
template <typename T>
std::unique_ptr<T> DotnetTypeReconstructor::createDataTypeFollowedByReference(std::vector<std::uint8_t>& data)
{
std::uint64_t bytesRead;
TypeDefOrRef typeRef;
typeRef.setIndex(decodeUnsigned(data, bytesRead));
if (bytesRead == 0)
return nullptr;
auto classRef = selectClass(typeRef);
if (classRef == nullptr)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
return std::make_unique<T>(classRef);
}
/**
* Creates data type from signature that refers to another data type.
* @param data Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
template <typename T>
std::unique_ptr<T> DotnetTypeReconstructor::createDataTypeFollowedByType(std::vector<std::uint8_t>& data, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
auto type = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (type == nullptr)
return nullptr;
return std::make_unique<T>(std::move(type));
}
/**
* Creates data type from signature that references generic parameter.
* @param data Signature data.
* @param owner Owning class or method.
* @return New data type or @c nullptr in case of failure.
*/
template <typename T, typename U>
std::unique_ptr<T> DotnetTypeReconstructor::createGenericReference(std::vector<std::uint8_t>& data, const U* owner)
{
if (owner == nullptr)
return nullptr;
// Index of generic parameter
std::uint64_t bytesRead = 0;
std::uint64_t index = decodeUnsigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
const auto& genericParams = owner->getGenericParameters();
if (index >= genericParams.size())
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
return std::make_unique<T>(&genericParams[index]);
}
/**
* Creates data type from signature that instantiates generic data type.
* @param data Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetDataTypeGenericInst> DotnetTypeReconstructor::createGenericInstantiation(std::vector<std::uint8_t>& data, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
if (data.empty())
return nullptr;
// Instantiated type
auto type = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (type == nullptr)
return nullptr;
if (data.empty())
return nullptr;
// Number of instantiated generic parameters
auto genericCount = data[0];
data.erase(data.begin(), data.begin() + 1);
// Generic parameters used for instantiation
std::vector<std::unique_ptr<DotnetDataTypeBase>> genericTypes;
for (std::size_t i = 0; i < genericCount; ++i)
{
auto genericType = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (genericType == nullptr)
return nullptr;
genericTypes.push_back(std::move(genericType));
}
return std::make_unique<DotnetDataTypeGenericInst>(std::move(type), std::move(genericTypes));
}
/**
* Creates data type from signature that represent array.
* @param data Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetDataTypeArray> DotnetTypeReconstructor::createArray(std::vector<std::uint8_t>& data, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
// First comes data type representing elements in array
auto type = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (type == nullptr)
return nullptr;
// Rank of an array comes then, this means how many dimensions our array has
std::uint64_t bytesRead = 0;
std::uint64_t rank = decodeUnsigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
// Rank must be non-zero number
if (rank == 0)
return nullptr;
std::vector<std::pair<std::int64_t, std::int64_t>> dimensions(rank);
// Some dimensions can have limited size by declaration
// Size 0 means not specified
std::uint64_t numOfSizes = decodeUnsigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
// Now get all those sizes
for (std::uint64_t i = 0; i < numOfSizes; ++i)
{
dimensions[i].second = decodeSigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
}
// And some dimensions can also be limited by special lower bound
std::size_t numOfLowBounds = decodeUnsigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
// Make sure we don't get out of bounds with dimensions
numOfLowBounds = std::min(dimensions.size(), numOfLowBounds);
for (std::uint64_t i = 0; i < numOfLowBounds; ++i)
{
dimensions[i].first = decodeSigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
// Adjust higher bound according to lower bound
dimensions[i].second += dimensions[i].first;
}
return std::make_unique<DotnetDataTypeArray>(std::move(type), std::move(dimensions));
}
/**
* Creates data type from signature that represent type modifier.
* @param data Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
template <typename T>
std::unique_ptr<T> DotnetTypeReconstructor::createModifier(std::vector<std::uint8_t>& data, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
// These modifiers are used to somehow specify data type using some data type
// The only usage we know about right know is 'volatile' keyword
// First read reference to type used for modifier
std::uint64_t bytesRead;
TypeDefOrRef typeRef;
typeRef.setIndex(decodeUnsigned(data, bytesRead));
if (bytesRead == 0)
return nullptr;
auto modifier = selectClass(typeRef);
if (modifier == nullptr)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
// Go further in signature because we only have modifier, we need to obtain type that is modified
auto type = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (type == nullptr)
return nullptr;
return std::make_unique<T>(modifier, std::move(type));
}
/**
* Creates data type from signature that represents function pointer.
* @param data Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetDataTypeFnPtr> DotnetTypeReconstructor::createFnPtr(std::vector<std::uint8_t>& data, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
if (data.empty())
return nullptr;
// Delete first byte, what does it even mean?
data.erase(data.begin(), data.begin() + 1);
// Read number of parameters
std::uint64_t bytesRead = 0;
std::uint64_t paramsCount = decodeUnsigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
auto returnType = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (returnType == nullptr)
return nullptr;
std::vector<std::unique_ptr<DotnetDataTypeBase>> paramTypes;
for (std::size_t i = 0; i < paramsCount; ++i)
{
auto paramType = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (paramType == nullptr)
return nullptr;
paramTypes.push_back(std::move(paramType));
}
return std::make_unique<DotnetDataTypeFnPtr>(std::move(returnType), std::move(paramTypes));
}
/**
* Creates data type from signature. Signature is destroyed in the meantime.
* @param signature Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetDataTypeBase> DotnetTypeReconstructor::dataTypeFromSignature(std::vector<std::uint8_t>& signature, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
if (signature.empty())
return nullptr;
std::unique_ptr<DotnetDataTypeBase> result;
auto type = static_cast<ElementType>(signature[0]);
signature.erase(signature.begin(), signature.begin() + 1);
switch (type)
{
case ElementType::Void:
result = std::make_unique<DotnetDataTypeVoid>();
break;
case ElementType::Boolean:
result = std::make_unique<DotnetDataTypeBoolean>();
break;
case ElementType::Char:
result = std::make_unique<DotnetDataTypeChar>();
break;
case ElementType::Int8:
result = std::make_unique<DotnetDataTypeInt8>();
break;
case ElementType::UInt8:
result = std::make_unique<DotnetDataTypeUInt8>();
break;
case ElementType::Int16:
result = std::make_unique<DotnetDataTypeInt16>();
break;
case ElementType::UInt16:
result = std::make_unique<DotnetDataTypeUInt16>();
break;
case ElementType::Int32:
result = std::make_unique<DotnetDataTypeInt32>();
break;
case ElementType::UInt32:
result = std::make_unique<DotnetDataTypeUInt32>();
break;
case ElementType::Int64:
result = std::make_unique<DotnetDataTypeInt64>();
break;
case ElementType::UInt64:
result = std::make_unique<DotnetDataTypeUInt64>();
break;
case ElementType::Float32:
result = std::make_unique<DotnetDataTypeFloat32>();
break;
case ElementType::Float64:
result = std::make_unique<DotnetDataTypeFloat64>();
break;
case ElementType::String:
result = std::make_unique<DotnetDataTypeString>();
break;
case ElementType::Ptr:
result = createDataTypeFollowedByType<DotnetDataTypePtr>(signature, ownerClass, ownerMethod);
break;
case ElementType::ByRef:
result = createDataTypeFollowedByType<DotnetDataTypeByRef>(signature, ownerClass, ownerMethod);
break;
case ElementType::ValueType:
result = createDataTypeFollowedByReference<DotnetDataTypeValueType>(signature);
break;
case ElementType::Class:
result = createDataTypeFollowedByReference<DotnetDataTypeClass>(signature);
break;
case ElementType::GenericVar:
result = createGenericReference<DotnetDataTypeGenericVar>(signature, ownerClass);
break;
case ElementType::Array:
result = createArray(signature, ownerClass, ownerMethod);
break;
case ElementType::GenericInst:
result = createGenericInstantiation(signature, ownerClass, ownerMethod);
break;
case ElementType::TypedByRef:
result = std::make_unique<DotnetDataTypeTypedByRef>();
break;
case ElementType::IntPtr:
result = std::make_unique<DotnetDataTypeIntPtr>();
break;
case ElementType::UIntPtr:
result = std::make_unique<DotnetDataTypeUIntPtr>();
break;
case ElementType::FnPtr:
result = createFnPtr(signature, ownerClass, ownerMethod);
break;
case ElementType::Object:
result = std::make_unique<DotnetDataTypeObject>();
break;
case ElementType::SzArray:
result = createDataTypeFollowedByType<DotnetDataTypeSzArray>(signature, ownerClass, ownerMethod);
break;
case ElementType::GenericMVar:
result = createGenericReference<DotnetDataTypeGenericMVar>(signature, ownerMethod);
break;
case ElementType::CModOptional:
result = createModifier<DotnetDataTypeCModOptional>(signature, ownerClass, ownerMethod);
break;
case ElementType::CModRequired:
result = createModifier<DotnetDataTypeCModRequired>(signature, ownerClass, ownerMethod);
break;
case ElementType::Internal:
return nullptr;
case ElementType::Modifier:
return nullptr;
case ElementType::Sentinel:
return nullptr;
case ElementType::Pinned:
return nullptr;
case ElementType::MetaType:
return nullptr;
case ElementType::BoxedObject:
return nullptr;
case ElementType::CustomField:
return nullptr;
case ElementType::CustomProperty:
return nullptr;
case ElementType::CustomEnum:
return nullptr;
default:
break;
}
return result;
}
/**
* Selects a class from defined or referenced class table based on provided @c TypeDefOrRef index.
* @param typeDefOrRef Index.
* @return Class if any exists, otherwise @c nullptr.
*/
const DotnetClass* DotnetTypeReconstructor::selectClass(const TypeDefOrRef& typeDefOrRef) const
{
MetadataTableType refTable;
if (!typeDefOrRef.getTable(refTable))
return nullptr;
const DotnetClass* result = nullptr;
if (refTable == MetadataTableType::TypeDef)
{
auto itr = defClassTable.find(typeDefOrRef.getIndex());
if (itr == defClassTable.end())
return nullptr;
result = itr->second.get();
}
else if (refTable == MetadataTableType::TypeRef)
{
auto itr = refClassTable.find(typeDefOrRef.getIndex());
if (itr == refClassTable.end())
return nullptr;
result = itr->second.get();
}
return result;
}
} // namespace fileformat
} // namespace retdec
| 46,253 | 15,360 |
/* Copyright 2017 The TensorFlow Authors. 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 <gtest/gtest.h>
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/model.h"
namespace tflite {
namespace {
using ::testing::ElementsAreArray;
class BatchToSpaceNDOpModel : public SingleOpModel {
public:
void SetInput(std::initializer_list<float> data) {
PopulateTensor<float>(input_, data);
}
void SetBlockShape(std::initializer_list<int> data) {
PopulateTensor<int>(block_shape_, data);
}
void SetCrops(std::initializer_list<int> data) {
PopulateTensor<int>(crops_, data);
}
std::vector<float> GetOutput() { return ExtractVector<float>(output_); }
std::vector<int> GetOutputShape() { return GetTensorShape(output_); }
protected:
int input_;
int block_shape_;
int crops_;
int output_;
};
// Tests case where block_shape and crops are const tensors.
//
// Example usage is as follows:
// BatchToSpaceNDOpConstModel m(input_shape, block_shape, crops);
// m.SetInput(input_data);
// m.Invoke();
class BatchToSpaceNDOpConstModel : public BatchToSpaceNDOpModel {
public:
BatchToSpaceNDOpConstModel(std::initializer_list<int> input_shape,
std::initializer_list<int> block_shape,
std::initializer_list<int> crops) {
input_ = AddInput(TensorType_FLOAT32);
block_shape_ = AddConstInput(TensorType_INT32, block_shape, {2});
crops_ = AddConstInput(TensorType_INT32, crops, {2, 2});
output_ = AddOutput(TensorType_FLOAT32);
SetBuiltinOp(BuiltinOperator_BATCH_TO_SPACE_ND,
BuiltinOptions_BatchToSpaceNDOptions,
CreateBatchToSpaceNDOptions(builder_).Union());
BuildInterpreter({input_shape});
}
};
// Tests case where block_shape and crops are non-const tensors.
//
// Example usage is as follows:
// BatchToSpaceNDOpDynamicModel m(input_shape);
// m.SetInput(input_data);
// m.SetBlockShape(block_shape);
// m.SetPaddings(crops);
// m.Invoke();
class BatchToSpaceNDOpDynamicModel : public BatchToSpaceNDOpModel {
public:
BatchToSpaceNDOpDynamicModel(std::initializer_list<int> input_shape) {
input_ = AddInput(TensorType_FLOAT32);
block_shape_ = AddInput(TensorType_INT32);
crops_ = AddInput(TensorType_INT32);
output_ = AddOutput(TensorType_FLOAT32);
SetBuiltinOp(BuiltinOperator_BATCH_TO_SPACE_ND,
BuiltinOptions_BatchToSpaceNDOptions,
CreateBatchToSpaceNDOptions(builder_).Union());
BuildInterpreter({input_shape, {2}, {2, 2}});
}
};
TEST(BatchToSpaceNDOpTest, SimpleConstTest) {
BatchToSpaceNDOpConstModel m({4, 2, 2, 1}, {2, 2}, {0, 0, 0, 0});
m.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
m.Invoke();
EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({1, 4, 4, 1}));
EXPECT_THAT(m.GetOutput(), ElementsAreArray({1, 5, 2, 6, 9, 13, 10, 14, 3, 7,
4, 8, 11, 15, 12, 16}));
}
TEST(BatchToSpaceNDOpTest, SimpleDynamicTest) {
BatchToSpaceNDOpDynamicModel m({4, 2, 2, 1});
m.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
m.SetBlockShape({2, 2});
m.SetCrops({0, 0, 0, 0});
m.Invoke();
EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({1, 4, 4, 1}));
EXPECT_THAT(m.GetOutput(), ElementsAreArray({1, 5, 2, 6, 9, 13, 10, 14, 3, 7,
4, 8, 11, 15, 12, 16}));
}
TEST(BatchToSpaceNDOpTest, InvalidShapeTest) {
EXPECT_DEATH(BatchToSpaceNDOpConstModel({3, 2, 2, 1}, {2, 2}, {0, 0, 0, 0}),
"Cannot allocate tensors");
}
TEST(BatchToSpaceNDOpTest, InvalidCropsConstTest) {
EXPECT_DEATH(BatchToSpaceNDOpConstModel({3, 2, 2, 1}, {2, 2}, {0, 0, 0, -1}),
"crops.3. >= 0 was not true.");
}
TEST(BatchToSpaceNDOpTest, InvalidCropsDynamicTest) {
BatchToSpaceNDOpDynamicModel m({4, 2, 2, 1});
m.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
m.SetBlockShape({2, 2});
m.SetCrops({0, 0, -1, 0});
EXPECT_DEATH(m.Invoke(), "crops.2. >= 0 was not true.");
}
} // namespace
} // namespace tflite
int main(int argc, char** argv) {
::tflite::LogToStderr();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 4,965 | 1,943 |
#ifndef BOOST_SERIALIZATION_COLLECTIONS_SAVE_IMP_HPP
#define BOOST_SERIALIZATION_COLLECTIONS_SAVE_IMP_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// collections_save_imp.hpp: serialization for stl collections
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
// helper function templates for serialization of collections
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/serialization.hpp>
namespace boost{
namespace serialization {
namespace stl {
//////////////////////////////////////////////////////////////////////
// implementation of serialization for STL containers
//
template<class Archive, class Container>
inline void save_collection(Archive & ar, const Container &s)
{
// record number of elements
unsigned int count = s.size();
ar << make_nvp("count", const_cast<const unsigned int &>(count));
BOOST_DEDUCED_TYPENAME Container::const_iterator it = s.begin();
while(count-- > 0){
//if(0 == (ar.get_flags() & boost::archive::no_object_creation))
// note borland emits a no-op without the explicit namespace
boost::serialization::save_construct_data_adl(ar, &(*it), 0U);
ar << boost::serialization::make_nvp("item", *it++);
}
}
} // namespace stl
} // namespace serialization
} // namespace boost
#endif //BOOST_SERIALIZATION_COLLECTIONS_SAVE_IMP_HPP
| 1,795 | 567 |
/*
* Main.cpp
*
* The main program of the PAPR product firmware.
*
* KEEP THE MAIN LOOP RUNNING AT ALL TIMES. DO NOT USE DELAY().
* Be careful - this firmware keeps running even when the user does "Power Off".
* This code may need to run correctly for months at a time. Don't break this code!
* All code must work when millis() and micros() wrap around
*
* Once a battery is connected to the PCB, the system runs continuously forever. The
* only time we actually shut down is if the user completely drains the battery.
*/
#include "Main.h"
#include "PB2PWM.h"
#include <LowPower.h>
#include "MySerial.h"
#include "Hardware.h"
// The Hardware object gives access to all the microcontroller hardware such as pins and timers. Please always use this object,
// and never access any hardware or Arduino APIs directly. This gives us the option of using a fake hardware object for unit testing.
#define hw Hardware::instance
// indexed by PAPRState
const char* STATE_NAMES[] = { "Off", "On", "Off Charging", "On Charging" };
// TODO make this automatically update during build process
const char* PRODUCT_ID = "PAPR Rev 3.1 6/20/2021";
/********************************************************************
* Fan constants
********************************************************************/
// How many milliseconds should there be between readings of the fan speed. A smaller value will update
// more often, while a higher value will give more accurate and smooth readings.
const int FAN_SPEED_READING_INTERVAL = 1000;
// The duty cycle for each fan speed. Indexed by FanSpeed.
const byte fanDutyCycles[] = { 0, 50, 100 };
// The expected RPM for each fan speed. Indexed by FanSpeed.
const unsigned int expectedFanRPM[] = { 7479, 16112, 22271 };
/* Here are measured values for fan RMP for the San Ace 9GA0412P3K011
% MIN MAX AVG
0, 7461, 7480, 7479
10, 9431, 9481, 9456
20, 11264, 11284, 11274
30, 12908, 12947, 12928
40, 14580, 14626, 14603
50, 16047, 16177, 16112
60, 17682, 17743, 17743
70, 19092, 19150, 19121
80, 20408, 20488, 20448
90, 21510, 21556, 21533
100, 22215, 22327, 22271
*/
// How much tolerance do we give when checking for correct fan RPM. We allow +/- 5%.
const float LOWEST_FAN_OK_RPM = 0.95;
const float HIGHEST_FAN_OK_RPM = 1.05;
// The fan speed when we startup.
const FanSpeed DEFAULT_FAN_SPEED = fanLow;
// When we change the fan speed, allow at least this many milliseconds before checking the speed.
// This gives the fan enough time to stabilize at the new speed.
const int FAN_STABILIZE_MILLIS = 6000;
/********************************************************************
* Button constants
********************************************************************/
// The user must push a button for at least this many milliseconds.
const int BUTTON_DEBOUNCE_MILLIS = 1000;
// The power off button needs a very short debounce interval,
// so it can do a little song and dance before taking effect.
const int POWER_OFF_BUTTON_DEBOUNCE_MILLIS = 50;
// The power off button only takes effect if the user holds it pressed for at least this long.
const int POWER_OFF_BUTTON_HOLD_MILLIS = 1000;
/********************************************************************
* Alert constants
********************************************************************/
// Which LEDs to flash for each type of alert.
const int batteryLowLEDs[] = { BATTERY_LED_LOW_PIN, CHARGING_LED_PIN , -1 };
const int fanRPMLEDs[] = { FAN_LOW_LED_PIN, FAN_MED_LED_PIN, FAN_HIGH_LED_PIN, -1 };
const int* alertLEDs[] = { 0, batteryLowLEDs, fanRPMLEDs }; // Indexed by enum Alert.
// What are the on & off durations for the pulsed lights and buzzer for each type of alert.
const int batteryAlertMillis[] = { 1000, 1000 };
const int fanAlertMillis[] = { 200, 200 };
const int* alertMillis[] = { 0, batteryAlertMillis, fanAlertMillis }; // Indexed by enum Alert.
// Buzzer settings.
const long BUZZER_FREQUENCY = 2500; // in Hz
const int BUZZER_DUTYCYCLE = 50; // in percent
// A "low battery" alarm is in effect whenever the battery level is at or below the "urgent" amount.
// If a charger is connected then the red LED flashes until the level is above the urgent amount,
// but the buzzer doesn't sound.
// This percentage is supposed to occur when the battery has 30 minutes of charge left. To give a
// generous margin, it's actually about an hour.
const int URGENT_BATTERY_PERCENT = 8;
/********************************************************************
* LED
********************************************************************/
// Set a single LED to o given state
void Main::setLED(const int pin, int onOff) {
hw.digitalWrite(pin, onOff);
// keep track of the LED's state in ledState.
for (int i = 0; i < numLEDs; i++) {
if (pin == LEDpins[i]) {
ledState[i] = onOff;
return;
}
}
}
// Turn off all LEDs
void Main::allLEDsOff()
{
for (int i = 0; i < numLEDs; i += 1) {
setLED(LEDpins[i], LED_OFF);
}
}
// Turn on all LEDs
void Main::allLEDsOn()
{
for (int i = 0; i < numLEDs; i += 1) {
setLED(LEDpins[i], LED_ON);
}
}
// Set a list of LEDs to a given state.
void Main::setLEDs(const int* pinList, int onOff)
{
for (int i = 0; pinList[i] != -1; i += 1) {
setLED(pinList[i], onOff);
}
}
// Flash all the LEDS for a specified duration and number of flashes.
void Main::flashAllLEDs(int millis, int count)
{
while (count--) {
allLEDsOn();
hw.delay(millis);
allLEDsOff();
hw.delay(millis);
}
}
/********************************************************************
* Alert
********************************************************************/
// This function pulses the lights and buzzer during an alert.
void Main::onToggleAlert()
{
alertToggle = !alertToggle;
setLEDs(currentAlertLEDs, alertToggle ? LED_ON : LED_OFF);
setBuzzer(alertToggle ? BUZZER_ON : BUZZER_OFF);
alertTimer.start(currentAlertMillis[alertToggle ? 0 : 1]);
}
// Enter the "alert" state. In this state we pulse the lights and buzzer to
// alert the user to a problem. Once we are in this state, the only
// way out is for the user to turn the power off.
void Main::raiseAlert(Alert alert)
{
currentAlert = alert;
serialPrintf("Begin %s Alert", currentAlertName());
currentAlertLEDs = alertLEDs[alert];
currentAlertMillis = alertMillis[alert];
alertToggle = false;
onToggleAlert();
}
// Turn off any active alert.
void Main::cancelAlert()
{
currentAlert = alertNone;
alertTimer.cancel();
}
// Turn the buzzer on or off.
void Main::setBuzzer(int onOff) {
//serialPrintf("set buzzer %s", onOff == BUZZER_OFF ? "off" : "on");
if (onOff) {
startPB2PWM(BUZZER_FREQUENCY, BUZZER_DUTYCYCLE);
} else {
stopPB2PWM();
}
buzzerState = onOff;
}
/********************************************************************
* Fan
********************************************************************/
// Update the fan indicator LEDs to correspond to the current fan setting.
void Main::updateFanLEDs()
{
setLED(FAN_LOW_LED_PIN, LED_ON);
setLED(FAN_MED_LED_PIN, currentFanSpeed > fanLow ? LED_ON : LED_OFF);
setLED(FAN_HIGH_LED_PIN, currentFanSpeed == fanHigh ? LED_ON : LED_OFF);
}
// Set the fan to the indicated speed, and update the fan indicator LEDs.
void Main::setFanSpeed(FanSpeed speed)
{
fanController.setDutyCycle(fanDutyCycles[speed]);
currentFanSpeed = speed;
updateFanLEDs();
serialPrintf("Set Fan Speed %d", speed);
// disable fan RPM monitor for a few seconds, until the new fan speed stabilizes
lastFanSpeedChangeMilliSeconds = hw.millis();
fanSpeedRecentlyChanged = true;
}
// Call this periodically to check that the fan RPM is within the expected range for the current FanSpeed.
void Main::checkForFanAlert() {
const unsigned int fanRPM = fanController.getRPM();
// Note: we call getRPM() even if we're not going to use the result, because getRPM() works better if you call it often.
// If fan RPM checking is temporarily disabled, then do nothing.
if (fanSpeedRecentlyChanged) {
if (hw.millis() - lastFanSpeedChangeMilliSeconds < FAN_STABILIZE_MILLIS) {
return;
}
fanSpeedRecentlyChanged = false;
}
// If the RPM is too low or too high compared to the expected value, raise an alert.
const unsigned int expectedRPM = expectedFanRPM[currentFanSpeed];
if ((fanRPM < (LOWEST_FAN_OK_RPM * expectedRPM)) || (fanRPM > (HIGHEST_FAN_OK_RPM * expectedRPM))) {
raiseAlert(alertFanRPM);
}
}
/********************************************************************
* Battery
********************************************************************/
int Main::getBatteryPercentFull() {
return (int)((battery.getPicoCoulombs() - BATTERY_MIN_CHARGE_PICO_COULOMBS) / ((BATTERY_CAPACITY_PICO_COULOMBS - BATTERY_MIN_CHARGE_PICO_COULOMBS) / 100LL));
}
// Call this periodically to update the battery and charging LEDs.
void Main::updateBatteryLEDs() {
int percentFull = getBatteryPercentFull();
// Decide if the red LED should be on or not.
bool redLED = (percentFull < 40);
if (percentFull <= URGENT_BATTERY_PERCENT) {
// The battery level is really low. Flash the LED.
bool ledToggle = (hw.millis() / 1000) & 1;
redLED = redLED && ledToggle;
}
// Turn on/off the battery LEDs as required
setLED(BATTERY_LED_LOW_PIN, redLED ? LED_ON : LED_OFF); // red
setLED(BATTERY_LED_MED_PIN, ((percentFull > 15) && (percentFull < 97)) ? LED_ON : LED_OFF); // yellow
setLED(BATTERY_LED_HIGH_PIN, (percentFull > 70) ? LED_ON : LED_OFF); // green
// Turn on/off the charging indicator LED as required
setLED(CHARGING_LED_PIN, battery.isCharging() ? LED_ON : LED_OFF); // orange
// Maybe turn the charge reminder on or off.
// The "charge reminder" is the periodic beep that occurs when the battery is below 15%
// to remind the user to recharge the unit as soon as possible.
if (!battery.isCharging() && percentFull <= 15 && currentAlert != alertBatteryLow) {
if (!chargeReminder.isActive()) {
onChargeReminder();
chargeReminder.start();
}
} else {
chargeReminder.stop();
}
}
// Call this periodically to decide if a battery alert should be started or terminated.
void Main::checkForBatteryAlert()
{
if (currentAlert == alertBatteryLow) {
if (battery.isCharging() || getBatteryPercentFull() > URGENT_BATTERY_PERCENT) {
cancelAlert();
}
} else if (getBatteryPercentFull() <= URGENT_BATTERY_PERCENT && !battery.isCharging()) {
chargeReminder.stop();
raiseAlert(alertBatteryLow);
}
}
// This is the callback function for chargeReminder. When it's active, this function gets called every minute or so.
// We turn on the buzzer and the charging LED, then set a timer for when to turn buzzer and LED off.
void Main::onChargeReminder() {
serialPrintf("reminder beep");
setBuzzer(BUZZER_ON);
setLED(CHARGING_LED_PIN, LED_ON);
beepTimer.start(500);
}
// This is the callback function for beepTimer. This function gets called to turn off the chargeReminder buzzer and LED.
void Main::onBeepTimer() {
setBuzzer(BUZZER_OFF);
setLED(CHARGING_LED_PIN, LED_OFF);
}
/********************************************************************
* states and modes
********************************************************************/
// Go into a new state.
void Main::enterState(PAPRState newState)
{
serialPrintf("\r\nenter state %s", STATE_NAMES[newState]);
onStatusReport();
paprState = newState;
switch (newState) {
case stateOn:
case stateOnCharging:
hw.digitalWrite(FAN_ENABLE_PIN, FAN_ON);
setFanSpeed(currentFanSpeed);
setBuzzer(BUZZER_OFF);
if (currentAlert != alertFanRPM) {
updateFanLEDs();
}
if (currentAlert != alertBatteryLow) {
updateBatteryLEDs();
}
break;
case stateOff:
case stateOffCharging:
pinMode(BUZZER_PIN, INPUT); // tri-state the output pin, so the buzzer receives no signal and consumes no power.
hw.digitalWrite(FAN_ENABLE_PIN, FAN_OFF);
currentFanSpeed = DEFAULT_FAN_SPEED;
cancelAlert();
allLEDsOff();
break;
}
onStatusReport();
}
// Set the PCB to its low power state, and put the MCU into its lowest power sleep mode.
// This function will return only when the user presses the Power On button,
// or until the charger is connected. While we are napping, the system uses a negligible amount
// of power, perhaps 1-3% of a full battery charge every month.
//
// Be careful inside this function, it's the only place where we mess around with
// power, speed, watchdog, and sleeping. If you break this code it will mess up
// a lot of things!
//
// When this function returns, the board MUST be in full power mode,
// and the watchdog timer MUST be enabled.
void Main::nap()
{
hw.wdt_disable();
hw.setPowerMode(lowPowerMode);
while (true) {
LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);
if (battery.isCharging()) {
hw.setPowerMode(fullPowerMode);
enterState(stateOffCharging);
hw.wdt_enable(WDTO_8S);
return;
}
long wakeupTime = hw.millis();
while (hw.digitalRead(POWER_ON_PIN) == BUTTON_PUSHED) {
if (hw.millis() - wakeupTime > 125) { // we're at 1/8 speed, so this is really 1000 ms (8 * 125)
hw.setPowerMode(fullPowerMode);
enterState(stateOn);
while (hw.digitalRead(POWER_ON_PIN) == BUTTON_PUSHED) {}
hw.wdt_enable(WDTO_8S);
return;
}
}
}
}
/********************************************************************
* UI event handlers
********************************************************************/
// when the user presses Power Off, we want to give the user an audible and visible signal
// in case they didn't mean to do it. If the user holds the button long enough we return true,
// meaning that the user really wants to do it.
bool Main::doPowerOffWarning()
{
// Turn on all LEDs, and the buzzer
allLEDsOn();
setBuzzer(BUZZER_ON);
// If the user holds the button for long enough, we will return true,
// which tells the caller to go ahead and enter the off state.
unsigned long startMillis = hw.millis();
while (hw.digitalRead(POWER_OFF_PIN) == BUTTON_PUSHED) {
if (hw.millis() - startMillis > POWER_OFF_BUTTON_HOLD_MILLIS) {
allLEDsOff();
setBuzzer(BUZZER_OFF);
return true;
}
}
// The user did not hold the button long enough. Restore the UI
// and tell the caller not to enter the off state.
allLEDsOff();
setBuzzer(BUZZER_OFF);
if (currentAlert != alertFanRPM) {
updateFanLEDs();
}
if (currentAlert != alertBatteryLow) {
updateBatteryLEDs();
}
return false;
}
// This function gets called when the user presses the Power On button
void Main::onPowerOnPress()
{
switch (paprState) {
case stateOn:
case stateOnCharging:
// do nothing
break;
case stateOff: // should never happen
case stateOffCharging:
enterState(stateOnCharging);
break;
}
}
// This function gets called when the user presses the Power On button
void Main::onPowerOffPress()
{
switch (paprState) {
case stateOn:
if (doPowerOffWarning()) {
enterState(stateOff);
}
break;
case stateOff:
case stateOffCharging:
// these should never happen
break;
case stateOnCharging:
if (doPowerOffWarning()) {
enterState(stateOffCharging);
}
break;
}
}
// This function gets called when the user presses the Fan Down button
void Main::onFanDownPress()
{
/* TEMP for testing/debugging: decrease the current battery level by a few percent. */
if (digitalRead(POWER_ON_PIN) == BUTTON_PUSHED) {
battery.DEBUG_incrementPicoCoulombs(-1500000000000000LL);
serialPrintf("Charge is %d%", getBatteryPercentFull());
return;
}
setFanSpeed((currentFanSpeed == fanHigh) ? fanMedium : fanLow);
}
// This function gets called when the user presses the Fan Up button
void Main::onFanUpPress()
{
/* TEMP for testing/debugging: increase the current battery level by a few percent. */
if (digitalRead(POWER_ON_PIN) == BUTTON_PUSHED) {
battery.DEBUG_incrementPicoCoulombs(1500000000000000LL);
serialPrintf("Charge is %d%", getBatteryPercentFull());
return;
}
setFanSpeed((instance->currentFanSpeed == fanLow) ? fanMedium : fanHigh);
}
// This function is an interrupt handler that gets called whenever the user presses the Power On button.
void Main::callback()
{
if (hw.digitalRead(POWER_ON_PIN) == BUTTON_PUSHED && hw.digitalRead(FAN_UP_PIN) == BUTTON_PUSHED && hw.digitalRead(FAN_DOWN_PIN) == BUTTON_PUSHED) {
// it's a user reset
hw.reset();
// TEMP cause a watchdog timeout
//while (true) {
// setLED(ERROR_LED_PIN, LED_ON);
// setLED(ERROR_LED_PIN, LED_OFF);
//}
}
}
/********************************************************************
* Startup and run
********************************************************************/
Main::Main() :
// In the following code we are using the c++ lambda expressions as glue to our event handler functions.
buttonFanUp(FAN_UP_PIN, BUTTON_DEBOUNCE_MILLIS,
[]() { instance->onFanUpPress(); }),
buttonFanDown(FAN_DOWN_PIN, BUTTON_DEBOUNCE_MILLIS,
[]() { instance->onFanDownPress(); }),
buttonPowerOff(POWER_OFF_PIN, POWER_OFF_BUTTON_DEBOUNCE_MILLIS,
[]() { instance->onPowerOffPress(); }),
buttonPowerOn(POWER_ON_PIN, BUTTON_DEBOUNCE_MILLIS,
[]() { instance->onPowerOnPress(); }),
alertTimer(
[]() { instance->onToggleAlert(); }),
beepTimer(
[]() { instance->onBeepTimer(); }),
chargeReminder(10000,
[]() { instance->onChargeReminder(); }),
statusReport(10000,
[]() { instance->onStatusReport(); }),
fanController(FAN_RPM_PIN, FAN_SPEED_READING_INTERVAL, FAN_PWM_PIN),
currentFanSpeed(fanLow),
fanSpeedRecentlyChanged(false),
ledState({ LED_OFF, LED_OFF, LED_OFF, LED_OFF, LED_OFF, LED_OFF, LED_OFF}),
buzzerState(BUZZER_OFF),
currentAlert(alertNone)
{
instance = this;
}
// This function gets called once, when the MCU starts up.
void Main::setup()
{
// Make sure watchdog is off. Remember what kind of reset just happened. Setup the hardware.
int resetFlags = hw.watchdogStartup();
hw.setup();
// Initialize the serial port and print some initial debug info.
#ifdef SERIAL_ENABLED
delay(1000);
serialInit();
serialPrintf("%s, MCUSR = %x", PRODUCT_ID, resetFlags);
#endif
// Decide what state we should be in.
PAPRState initialState;
if (resetFlags & (1 << WDRF)) {
// Watchdog timer expired. Tell the user that something unusual happened.
flashAllLEDs(100, 5);
initialState = stateOn;
} else if (resetFlags == 0) {
// Manual reset. Tell the user that something unusual happened.
flashAllLEDs(100, 10);
initialState = stateOn;
} else {
// It's a simple power-on. This will happen when:
// - somebody in the factory just connected the battery to the PCB; or
// - the battery had been fully drained (and therefore not delivering any power), and the user just plugged in the charger.
initialState = stateOff;
}
if (battery.isCharging()) {
initialState = (PAPRState)((int)initialState + 2);
}
// Initialize the fan
fanController.begin();
setFanSpeed(DEFAULT_FAN_SPEED);
// Enable the watchdog timer. (Note: Don't make the timeout value too small - we need to give the IDE a chance to
// call the bootloader in case something dumb happens during development and the WDT
// resets the MCU too quickly. Once the code is solid, you could make it shorter.)
wdt_enable(WDTO_8S);
// Enable pin-change interrupts for the Power On button, and register a callback to handle those interrupts.
// The interrupt serves 2 distinct purposes: (1) to get this callback called, and (2) to wake us up if we're napping.
hw.setPowerOnButtonInterruptCallback(this);
// and we're done!
battery.initializeCoulombCount();
enterState(initialState);
statusReport.start();
}
// Call the update() function of everybody who wants to do something each time through the loop() function.
void Main::doAllUpdates()
{
battery.update();
if (currentAlert == alertNone) {
checkForFanAlert();
}
if (currentAlert != alertFanRPM) {
updateFanLEDs();
}
checkForBatteryAlert();
if (currentAlert != alertBatteryLow) {
updateBatteryLEDs();
}
buttonFanUp.update();
buttonFanDown.update();
buttonPowerOff.update();
alertTimer.update();
chargeReminder.update();
beepTimer.update();
statusReport.update();
}
// This is our main function, which gets called over and over again, forever.
void Main::loop()
{
hw.wdt_reset_();
switch (paprState) {
case stateOn:
doAllUpdates();
if (battery.isCharging()) {
enterState(stateOnCharging);
}
break;
case stateOnCharging:
doAllUpdates();
if (!battery.isCharging()) {
enterState(stateOn);
}
break;
case stateOff:
// We are not charging so there are no LEDs to update.
// We have nothing to do except take a nap. Our nap will end
// when the state is no longer stateOff.
nap();
battery.wakeUp();
break;
case stateOffCharging:
// Only do the work that is necessary when power is off and we're charging
// - update the battery status and battery LEDs
// - see if the charger has been unplugged
// - see if the Power On button was pressed
battery.update();
updateBatteryLEDs();
if (!battery.isCharging()) {
enterState(stateOff);
}
buttonPowerOn.update();
statusReport.update();
break;
}
}
// Write a one-line summary of the status of everything. For use in testing and debugging.
void Main::onStatusReport() {
#ifdef SERIAL_ENABLED
serialPrintf("Fan,%s,Buzzer,%s,Alert,%s,Charging,%s,LEDs,%s,%s,%s,%s,%s,%s,%s,milliVolts,%ld,milliAmps,%ld,Coulombs,%ld,charge,%d%%",
(currentFanSpeed == fanLow) ? "lo" : ((currentFanSpeed == fanMedium) ? "med" : "hi"),
(buzzerState == BUZZER_ON) ? "on" : "off",
currentAlertName(),
battery.isCharging() ? "yes" : "no",
(ledState[0] == LED_ON) ? "red" : "---",
(ledState[1] == LED_ON) ? "yellow" : "---",
(ledState[2] == LED_ON) ? "green" : "---",
(ledState[3] == LED_ON) ? "amber" : "---",
(ledState[4] == LED_ON) ? "blue" : "---",
(ledState[5] == LED_ON) ? "blue" : "---",
(ledState[6] == LED_ON) ? "blue" : "---",
(long)(hw.readMicroVolts() / 1000LL),
(long)(hw.readMicroAmps() / 1000LL),
(long)(battery.getPicoCoulombs() / 1000000000000LL),
getBatteryPercentFull());
#endif
}
Main* Main::instance;
| 24,099 | 7,910 |
/*
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, Red Hat Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "asm/macroAssembler.hpp"
#include "classfile/javaClasses.inline.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/interpreterRuntime.hpp"
#include "memory/allocation.inline.hpp"
#include "prims/methodHandles.hpp"
#include "runtime/flags/flagSetting.hpp"
#include "runtime/frame.inline.hpp"
#define __ _masm->
#ifdef PRODUCT
#define BLOCK_COMMENT(str) /* nothing */
#else
#define BLOCK_COMMENT(str) __ block_comment(str)
#endif
#define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
void MethodHandles::load_klass_from_Class(MacroAssembler* _masm, Register klass_reg) {
if (VerifyMethodHandles)
verify_klass(_masm, klass_reg, SystemDictionary::WK_KLASS_ENUM_NAME(java_lang_Class),
"MH argument is a Class");
__ ldr(klass_reg, Address(klass_reg, java_lang_Class::klass_offset_in_bytes()));
}
#ifdef ASSERT
static int check_nonzero(const char* xname, int x) {
assert(x != 0, "%s should be nonzero", xname);
return x;
}
#define NONZERO(x) check_nonzero(#x, x)
#else //ASSERT
#define NONZERO(x) (x)
#endif //PRODUCT
#ifdef ASSERT
void MethodHandles::verify_klass(MacroAssembler* _masm,
Register obj, SystemDictionary::WKID klass_id,
const char* error_message) {
InstanceKlass** klass_addr = SystemDictionary::well_known_klass_addr(klass_id);
Klass* klass = SystemDictionary::well_known_klass(klass_id);
Register temp = rscratch2;
Register temp2 = rscratch1; // used by MacroAssembler::cmpptr
Label L_ok, L_bad;
BLOCK_COMMENT("verify_klass {");
__ verify_oop(obj);
__ cbz(obj, L_bad);
__ push(RegSet::of(temp, temp2), sp);
__ load_klass(temp, obj);
__ cmpptr(temp, ExternalAddress((address) klass_addr));
__ br(Assembler::EQ, L_ok);
intptr_t super_check_offset = klass->super_check_offset();
__ ldr(temp, Address(temp, super_check_offset));
__ cmpptr(temp, ExternalAddress((address) klass_addr));
__ br(Assembler::EQ, L_ok);
__ pop(RegSet::of(temp, temp2), sp);
__ bind(L_bad);
__ stop(error_message);
__ BIND(L_ok);
__ pop(RegSet::of(temp, temp2), sp);
BLOCK_COMMENT("} verify_klass");
}
void MethodHandles::verify_ref_kind(MacroAssembler* _masm, int ref_kind, Register member_reg, Register temp) { }
#endif //ASSERT
void MethodHandles::jump_from_method_handle(MacroAssembler* _masm, Register method, Register temp,
bool for_compiler_entry) {
assert(method == rmethod, "interpreter calling convention");
Label L_no_such_method;
__ cbz(rmethod, L_no_such_method);
__ verify_method_ptr(method);
if (!for_compiler_entry && JvmtiExport::can_post_interpreter_events()) {
Label run_compiled_code;
// JVMTI events, such as single-stepping, are implemented partly by avoiding running
// compiled code in threads for which the event is enabled. Check here for
// interp_only_mode if these events CAN be enabled.
__ ldrb(rscratch1, Address(rthread, JavaThread::interp_only_mode_offset()));
__ cbnz(rscratch1, run_compiled_code);
__ ldr(rscratch1, Address(method, Method::interpreter_entry_offset()));
__ br(rscratch1);
__ BIND(run_compiled_code);
}
const ByteSize entry_offset = for_compiler_entry ? Method::from_compiled_offset() :
Method::from_interpreted_offset();
__ ldr(rscratch1,Address(method, entry_offset));
__ br(rscratch1);
__ bind(L_no_such_method);
__ far_jump(RuntimeAddress(StubRoutines::throw_AbstractMethodError_entry()));
}
void MethodHandles::jump_to_lambda_form(MacroAssembler* _masm,
Register recv, Register method_temp,
Register temp2,
bool for_compiler_entry) {
BLOCK_COMMENT("jump_to_lambda_form {");
// This is the initial entry point of a lazy method handle.
// After type checking, it picks up the invoker from the LambdaForm.
assert_different_registers(recv, method_temp, temp2);
assert(recv != noreg, "required register");
assert(method_temp == rmethod, "required register for loading method");
//NOT_PRODUCT({ FlagSetting fs(TraceMethodHandles, true); trace_method_handle(_masm, "LZMH"); });
// Load the invoker, as MH -> MH.form -> LF.vmentry
__ verify_oop(recv);
__ load_heap_oop(method_temp, Address(recv, NONZERO(java_lang_invoke_MethodHandle::form_offset_in_bytes())), temp2);
__ verify_oop(method_temp);
__ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_LambdaForm::vmentry_offset_in_bytes())), temp2);
__ verify_oop(method_temp);
__ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_MemberName::method_offset_in_bytes())), temp2);
__ verify_oop(method_temp);
__ access_load_at(T_ADDRESS, IN_HEAP, method_temp, Address(method_temp, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset_in_bytes())), noreg, noreg);
if (VerifyMethodHandles && !for_compiler_entry) {
// make sure recv is already on stack
__ ldr(temp2, Address(method_temp, Method::const_offset()));
__ load_sized_value(temp2,
Address(temp2, ConstMethod::size_of_parameters_offset()),
sizeof(u2), /*is_signed*/ false);
// assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
Label L;
__ ldr(rscratch1, __ argument_address(temp2, -1));
__ cmpoop(recv, rscratch1);
__ br(Assembler::EQ, L);
__ ldr(r0, __ argument_address(temp2, -1));
__ hlt(0);
__ BIND(L);
}
jump_from_method_handle(_masm, method_temp, temp2, for_compiler_entry);
BLOCK_COMMENT("} jump_to_lambda_form");
}
// Code generation
address MethodHandles::generate_method_handle_interpreter_entry(MacroAssembler* _masm,
vmIntrinsics::ID iid) {
const bool not_for_compiler_entry = false; // this is the interpreter entry
assert(is_signature_polymorphic(iid), "expected invoke iid");
if (iid == vmIntrinsics::_invokeGeneric ||
iid == vmIntrinsics::_compiledLambdaForm) {
// Perhaps surprisingly, the symbolic references visible to Java are not directly used.
// They are linked to Java-generated adapters via MethodHandleNatives.linkMethod.
// They all allow an appendix argument.
__ hlt(0); // empty stubs make SG sick
return NULL;
}
// r13: sender SP (must preserve; see prepare_to_jump_from_interpreted)
// rmethod: Method*
// r3: argument locator (parameter slot count, added to rsp)
// r1: used as temp to hold mh or receiver
// r0, r11: garbage temps, blown away
Register argp = r3; // argument list ptr, live on error paths
Register temp = r0;
Register mh = r1; // MH receiver; dies quickly and is recycled
// here's where control starts out:
__ align(CodeEntryAlignment);
address entry_point = __ pc();
if (VerifyMethodHandles) {
assert(Method::intrinsic_id_size_in_bytes() == 2, "assuming Method::_intrinsic_id is u2");
Label L;
BLOCK_COMMENT("verify_intrinsic_id {");
__ ldrh(rscratch1, Address(rmethod, Method::intrinsic_id_offset_in_bytes()));
__ cmp(rscratch1, (int) iid);
__ br(Assembler::EQ, L);
if (iid == vmIntrinsics::_linkToVirtual ||
iid == vmIntrinsics::_linkToSpecial) {
// could do this for all kinds, but would explode assembly code size
trace_method_handle(_masm, "bad Method*::intrinsic_id");
}
__ hlt(0);
__ bind(L);
BLOCK_COMMENT("} verify_intrinsic_id");
}
// First task: Find out how big the argument list is.
Address r3_first_arg_addr;
int ref_kind = signature_polymorphic_intrinsic_ref_kind(iid);
assert(ref_kind != 0 || iid == vmIntrinsics::_invokeBasic, "must be _invokeBasic or a linkTo intrinsic");
if (ref_kind == 0 || MethodHandles::ref_kind_has_receiver(ref_kind)) {
__ ldr(argp, Address(rmethod, Method::const_offset()));
__ load_sized_value(argp,
Address(argp, ConstMethod::size_of_parameters_offset()),
sizeof(u2), /*is_signed*/ false);
// assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
r3_first_arg_addr = __ argument_address(argp, -1);
} else {
DEBUG_ONLY(argp = noreg);
}
if (!is_signature_polymorphic_static(iid)) {
__ ldr(mh, r3_first_arg_addr);
DEBUG_ONLY(argp = noreg);
}
// r3_first_arg_addr is live!
trace_method_handle_interpreter_entry(_masm, iid);
if (iid == vmIntrinsics::_invokeBasic) {
generate_method_handle_dispatch(_masm, iid, mh, noreg, not_for_compiler_entry);
} else {
// Adjust argument list by popping the trailing MemberName argument.
Register recv = noreg;
if (MethodHandles::ref_kind_has_receiver(ref_kind)) {
// Load the receiver (not the MH; the actual MemberName's receiver) up from the interpreter stack.
__ ldr(recv = r2, r3_first_arg_addr);
}
DEBUG_ONLY(argp = noreg);
Register rmember = rmethod; // MemberName ptr; incoming method ptr is dead now
__ pop(rmember); // extract last argument
generate_method_handle_dispatch(_masm, iid, recv, rmember, not_for_compiler_entry);
}
return entry_point;
}
void MethodHandles::generate_method_handle_dispatch(MacroAssembler* _masm,
vmIntrinsics::ID iid,
Register receiver_reg,
Register member_reg,
bool for_compiler_entry) {
assert(is_signature_polymorphic(iid), "expected invoke iid");
// temps used in this code are not used in *either* compiled or interpreted calling sequences
Register temp1 = r10;
Register temp2 = r11;
Register temp3 = r14; // r13 is live by this point: it contains the sender SP
if (for_compiler_entry) {
assert(receiver_reg == (iid == vmIntrinsics::_linkToStatic ? noreg : j_rarg0), "only valid assignment");
assert_different_registers(temp1, j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
assert_different_registers(temp2, j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
assert_different_registers(temp3, j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
}
assert_different_registers(temp1, temp2, temp3, receiver_reg);
assert_different_registers(temp1, temp2, temp3, member_reg);
if (iid == vmIntrinsics::_invokeBasic) {
// indirect through MH.form.vmentry.vmtarget
jump_to_lambda_form(_masm, receiver_reg, rmethod, temp1, for_compiler_entry);
} else {
// The method is a member invoker used by direct method handles.
if (VerifyMethodHandles) {
// make sure the trailing argument really is a MemberName (caller responsibility)
verify_klass(_masm, member_reg, SystemDictionary::WK_KLASS_ENUM_NAME(java_lang_invoke_MemberName),
"MemberName required for invokeVirtual etc.");
}
Address member_clazz( member_reg, NONZERO(java_lang_invoke_MemberName::clazz_offset_in_bytes()));
Address member_vmindex( member_reg, NONZERO(java_lang_invoke_MemberName::vmindex_offset_in_bytes()));
Address member_vmtarget( member_reg, NONZERO(java_lang_invoke_MemberName::method_offset_in_bytes()));
Address vmtarget_method( rmethod, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset_in_bytes()));
Register temp1_recv_klass = temp1;
if (iid != vmIntrinsics::_linkToStatic) {
__ verify_oop(receiver_reg);
if (iid == vmIntrinsics::_linkToSpecial) {
// Don't actually load the klass; just null-check the receiver.
__ null_check(receiver_reg);
} else {
// load receiver klass itself
__ null_check(receiver_reg, oopDesc::klass_offset_in_bytes());
__ load_klass(temp1_recv_klass, receiver_reg);
__ verify_klass_ptr(temp1_recv_klass);
}
BLOCK_COMMENT("check_receiver {");
// The receiver for the MemberName must be in receiver_reg.
// Check the receiver against the MemberName.clazz
if (VerifyMethodHandles && iid == vmIntrinsics::_linkToSpecial) {
// Did not load it above...
__ load_klass(temp1_recv_klass, receiver_reg);
__ verify_klass_ptr(temp1_recv_klass);
}
if (VerifyMethodHandles && iid != vmIntrinsics::_linkToInterface) {
Label L_ok;
Register temp2_defc = temp2;
__ load_heap_oop(temp2_defc, member_clazz, temp3);
load_klass_from_Class(_masm, temp2_defc);
__ verify_klass_ptr(temp2_defc);
__ check_klass_subtype(temp1_recv_klass, temp2_defc, temp3, L_ok);
// If we get here, the type check failed!
__ hlt(0);
// __ STOP("receiver class disagrees with MemberName.clazz");
__ bind(L_ok);
}
BLOCK_COMMENT("} check_receiver");
}
if (iid == vmIntrinsics::_linkToSpecial ||
iid == vmIntrinsics::_linkToStatic) {
DEBUG_ONLY(temp1_recv_klass = noreg); // these guys didn't load the recv_klass
}
// Live registers at this point:
// member_reg - MemberName that was the trailing argument
// temp1_recv_klass - klass of stacked receiver, if needed
// r13 - interpreter linkage (if interpreted) ??? FIXME
// r1 ... r0 - compiler arguments (if compiled)
Label L_incompatible_class_change_error;
switch (iid) {
case vmIntrinsics::_linkToSpecial:
if (VerifyMethodHandles) {
verify_ref_kind(_masm, JVM_REF_invokeSpecial, member_reg, temp3);
}
__ load_heap_oop(rmethod, member_vmtarget);
__ access_load_at(T_ADDRESS, IN_HEAP, rmethod, vmtarget_method, noreg, noreg);
break;
case vmIntrinsics::_linkToStatic:
if (VerifyMethodHandles) {
verify_ref_kind(_masm, JVM_REF_invokeStatic, member_reg, temp3);
}
__ load_heap_oop(rmethod, member_vmtarget);
__ access_load_at(T_ADDRESS, IN_HEAP, rmethod, vmtarget_method, noreg, noreg);
break;
case vmIntrinsics::_linkToVirtual:
{
// same as TemplateTable::invokevirtual,
// minus the CP setup and profiling:
if (VerifyMethodHandles) {
verify_ref_kind(_masm, JVM_REF_invokeVirtual, member_reg, temp3);
}
// pick out the vtable index from the MemberName, and then we can discard it:
Register temp2_index = temp2;
__ access_load_at(T_ADDRESS, IN_HEAP, temp2_index, member_vmindex, noreg, noreg);
if (VerifyMethodHandles) {
Label L_index_ok;
__ cmpw(temp2_index, 0U);
__ br(Assembler::GE, L_index_ok);
__ hlt(0);
__ BIND(L_index_ok);
}
// Note: The verifier invariants allow us to ignore MemberName.clazz and vmtarget
// at this point. And VerifyMethodHandles has already checked clazz, if needed.
// get target Method* & entry point
__ lookup_virtual_method(temp1_recv_klass, temp2_index, rmethod);
break;
}
case vmIntrinsics::_linkToInterface:
{
// same as TemplateTable::invokeinterface
// (minus the CP setup and profiling, with different argument motion)
if (VerifyMethodHandles) {
verify_ref_kind(_masm, JVM_REF_invokeInterface, member_reg, temp3);
}
Register temp3_intf = temp3;
__ load_heap_oop(temp3_intf, member_clazz);
load_klass_from_Class(_masm, temp3_intf);
__ verify_klass_ptr(temp3_intf);
Register rindex = rmethod;
__ access_load_at(T_ADDRESS, IN_HEAP, rindex, member_vmindex, noreg, noreg);
if (VerifyMethodHandles) {
Label L;
__ cmpw(rindex, 0U);
__ br(Assembler::GE, L);
__ hlt(0);
__ bind(L);
}
// given intf, index, and recv klass, dispatch to the implementation method
__ lookup_interface_method(temp1_recv_klass, temp3_intf,
// note: next two args must be the same:
rindex, rmethod,
temp2,
L_incompatible_class_change_error);
break;
}
default:
fatal("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid));
break;
}
// live at this point: rmethod, r13 (if interpreted)
// After figuring out which concrete method to call, jump into it.
// Note that this works in the interpreter with no data motion.
// But the compiled version will require that r2_recv be shifted out.
__ verify_method_ptr(rmethod);
jump_from_method_handle(_masm, rmethod, temp1, for_compiler_entry);
if (iid == vmIntrinsics::_linkToInterface) {
__ bind(L_incompatible_class_change_error);
__ far_jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
}
}
}
#ifndef PRODUCT
void trace_method_handle_stub(const char* adaptername,
oop mh,
intptr_t* saved_regs,
intptr_t* entry_sp) { }
// The stub wraps the arguments in a struct on the stack to avoid
// dealing with the different calling conventions for passing 6
// arguments.
struct MethodHandleStubArguments {
const char* adaptername;
oopDesc* mh;
intptr_t* saved_regs;
intptr_t* entry_sp;
};
void trace_method_handle_stub_wrapper(MethodHandleStubArguments* args) { }
void MethodHandles::trace_method_handle(MacroAssembler* _masm, const char* adaptername) { }
#endif //PRODUCT
| 18,768 | 6,340 |
#include <bits/stdc++.h>
#define fastio cin.tie(0)->sync_with_stdio(0)
using namespace std;
using ll = int64_t;
using ull = uint64_t;
using pll = pair<ll, ll>;
struct Random {
mt19937 rd;
Random() : rd((unsigned)chrono::steady_clock::now().time_since_epoch().count()) {}
Random(int seed) : rd(seed) {}
template<typename T = int>
T GetInt(T l = 0, T r = 32767) {
return uniform_int_distribution<T>(l, r)(rd);
}
double GetDouble(double l = 0, double r = 1) {
return uniform_real_distribution<double>(l, r)(rd);
}
} Rand;
struct MillerRabin {
ll Mul(ll x, ll y, ll MOD) {
ll ret = x * y - MOD * ull(1.L / MOD * x * y);
return ret + MOD * (ret < 0) - MOD * (ret >= (ll)MOD);
}
ll _pow(ll x, ll n, ll MOD) {
ll ret = 1; x %= MOD;
for (; n; n >>= 1) {
if (n & 1) ret = Mul(ret, x, MOD);
x = Mul(x, x, MOD);
}
return ret;
}
bool Check(ll x, ll p) {
if (x % p == 0) return 0;
for (ll d = x - 1; ; d >>= 1) {
ll t = _pow(p, d, x);
if (d & 1) return t != 1 && t != x - 1;
if (t == x - 1) return 0;
}
}
bool IsPrime(ll x) {
if (x == 2 || x == 3 || x == 5 || x == 7) return 1;
if (x % 2 == 0 || x % 3 == 0 || x % 5 == 0 || x % 7 == 0) return 0;
if (x < 121) return x > 1;
if (x < 1ULL << 32) for (auto& i : { 2, 7, 61 }) {
if (x == i) return 1;
if (x > i && Check(x, i)) return 0;
}
else for (auto& i : { 2, 325, 9375, 28178, 450775, 9780504, 1795265022 }) {
if (x == i) return 1;
if (x > i && Check(x, i)) return 0;
}
return 1;
}
};
struct PollardRho : public MillerRabin {
void Rec(ll n, vector<ll>& v) {
if (n == 1) return;
if (~n & 1) { v.push_back(2); Rec(n >> 1, v); return; }
if (IsPrime(n)) { v.push_back(n); return; }
ll a, b, c, g = n;
auto f = [&](ll x) { return (c + Mul(x, x, n)) % n; };
do {
if (g == n) {
a = b = Rand.GetInt<ll>(0, n - 3) + 2;
c = Rand.GetInt<ll>(0, 19) + 1;
}
a = f(a); b = f(f(b)); g = gcd(abs(a - b), n);
} while (g == 1);
Rec(g, v); Rec(n / g, v);
}
vector<ll> Factorize(ll n) {
vector<ll> ret; Rec(n, ret);
sort(ret.begin(), ret.end());
return ret;
}
} P;
vector<pll> Compress(vector<ll> v) {
map<ll, ll> M;
for (auto& i : v) M[i]++;
return vector<pll>(M.begin(), M.end());
}
ll Sol(ll n) {
if (P.IsPrime(n)) return n + 2;
ll ret = n + 2;
vector<pll> v = Compress(P.Factorize(n));
vector<ll> div;
auto DFS = [&](int dep, ll cur, auto&& DFS) -> void {
if (dep == v.size()) { div.push_back(cur); return; }
for (ll i = 0, t = 1; i <= v[dep].second; i++) {
DFS(dep + 1, cur * t, DFS);
t *= v[dep].first;
}
};
DFS(0, 1, DFS);
sort(div.begin(), div.end());
for (int i = 0; i < div.size(); i++) {
auto it = lower_bound(div.begin(), div.end(), sqrt(div[i]));
for (auto j = it - 3; j <= it + 3; j++) {
if (j < div.begin() || j >= div.end()) continue;
if (div[i] % *j) continue;
ret = min(ret, n / div[i] + div[i] / *j + *j);
}
}
return ret;
}
int main() {
fastio;
for (ll n; cin >> n && n; cout << Sol(n) << '\n');
} | 3,009 | 1,579 |
// Copyright (c) 2000, 2001, 2002, 2003 by David Scherer and others.
// Copyright (c) 2003, 2004 by Jonathan Brandmeyer and others.
// See the file license.txt for complete license terms.
// See the file authors.txt for a complete list of contributors.
#include "renderable.hpp"
#include "material.hpp"
namespace cvisual {
// TODO: tan_hfov_x and tan_hfov_y must be revisited in the face of
// nonuniform scaling. It may be more appropriate to describe the viewing
// frustum in a different way entirely.
view::view( const vector n_forward, vector n_center, int n_width,
int n_height, bool n_forward_changed,
double n_gcf, vector n_gcfvec,
bool n_gcf_changed, gl_extensions& glext)
: forward( n_forward), center(n_center), view_width( n_width),
view_height( n_height), forward_changed( n_forward_changed),
gcf( n_gcf), gcfvec( n_gcfvec), gcf_changed( n_gcf_changed), lod_adjust(0),
anaglyph(false), coloranaglyph(false), tan_hfov_x(0), tan_hfov_y(0),
screen_objects( z_comparator( forward)), glext(glext),
enable_shaders(true)
{
for(int i=0; i<N_LIGHT_TYPES; i++)
light_count[i] = 0;
}
void view::apply_frame_transform( const tmatrix& wft ) {
camera = wft * camera;
forward = wft.times_v( forward );
center = wft * center;
up = wft.times_v(up);
screen_objects_t tso( (z_comparator(forward)) );
screen_objects.swap( tso );
}
double
view::pixel_coverage( const vector& pos, double radius) const
{
// The distance from the camera to this position, in the direction of the
// camera. This is the distance to the viewing plane that the coverage
// circle lies in.
double dist = (pos - camera).dot(forward);
// Half of the width of the viewing plane at this distance.
double apparent_hwidth = tan_hfov_x * dist;
// The fraction of the apparent width covered by the coverage circle.
double coverage_fraction = radius / apparent_hwidth;
// Convert from fraction to pixels.
return coverage_fraction * view_width;
}
renderable::renderable()
: visible(true), opacity( 1.0 )
{
}
renderable::~renderable()
{
}
void
renderable::outer_render( view& v )
{
rgb actual_color = color;
if (v.anaglyph) {
if (v.coloranaglyph)
color = actual_color.desaturate();
else
color = actual_color.grayscale();
}
tmatrix material_matrix;
get_material_matrix(v, material_matrix);
apply_material use_mat( v, mat.get(), material_matrix );
gl_render(v);
if (v.anaglyph)
color = actual_color;
}
void
renderable::gl_render( view&)
{
return;
}
void
renderable::gl_pick_render( view&)
{
}
void
renderable::grow_extent( extent&)
{
return;
}
void
renderable::set_material( shared_ptr<class material> m )
{
mat = m;
}
shared_ptr<class material>
renderable::get_material() {
return mat;
}
bool renderable::translucent() {
return opacity != 1.0 || (mat && mat->get_translucent());
}
} // !namespace cvisual
| 2,955 | 1,095 |
#include "ModuleRender.h"
#include "Label.h"
#include "Fonts.h"
#include "GUIElem.h"
#include "Application.h"
#include "ModuleInput.h"
Label::Label(fPoint position, LabelInfo& info, GUIElem* parent, Module* listener) : GUIElem(position, listener, {}, GUIElemType::LABEL, parent)
{
text = info.text;
font = App->fonts->getFontbyName(info.fontName);
texturetoBlit = App->fonts->Print(text.c_str(), info.color, font);
color = info.color;
}
Label::~Label() {}
bool Label::Update(float dt)
{
bool result = false;
result = UpdateChilds(dt);
return result;
}
bool Label::Draw()
{
bool result = true;
result = App->render->Blit(texturetoBlit, (int)(this->screenPos.x - App->render->camera.x), (int)(this->screenPos.y - App->render->camera.y), nullptr, 0.3);
if (result)
result = DrawChilds();
return result;
}
bool Label::MouseHover() const
{
int x, y;
App->input->GetMousePosition(x, y);
bool result = false;
fPoint worldPos = { screenPos.x - App->render->camera.x, screenPos.y - App->render->camera.y };
int w, h;
SDL_QueryTexture(texturetoBlit, nullptr, nullptr, &w, &h);
//if collides
if (!(x < worldPos.x ||
x > worldPos.x + w ||
y < worldPos.y ||
y > worldPos.y + h))
{
result = true;
}
return result;
}
void Label::EditText(std::string text, SDL_Color color)
{
this->text = text;
SDL_DestroyTexture(texturetoBlit);
texturetoBlit = App->fonts->Print(text.data(), (ColorEquals({0,0,0,0}, color) ? this->color : color), font);
}
| 1,477 | 583 |
#include "test_server.h"
#include <iostream>
#include <unistd.h>
#include <gtest/gtest.h>
#include <sys/select.h>
#include <time.h>
#include <chrono>
#include <boost/any.hpp>
#include "coroutine.h"
#include "../gtest_exit.h"
#include "hook.h"
using namespace std;
using namespace co;
///select test points:
// 1.timeout == 0 seconds (immedaitely)
// 2.timeout == NULL
// 3.timeout == 1 seconds
// 4.all of fds are valid
// 5.all of fds are invalid
// 6.some -1 in fds
//X7.some file_fd in fds
//X8.occurred ERR events
// 9.timeout return
// 10.multi threads
// 11.trigger read and not trigger write
typedef int(*select_t)(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
bool FD_EQUAL(fd_set const* lhs, fd_set const* rhs){
return memcmp(lhs, rhs, sizeof(fd_set)) == 0;
}
bool FD_ISZERO(fd_set *fds){
for (int i = 0; i < FD_SETSIZE; ++i)
if (FD_ISSET(i, fds))
return false;
return true;
}
int FD_SIZE(fd_set *fds){
int n = 0;
for (int i = 0; i < FD_SETSIZE; ++i)
if (FD_ISSET(i, fds))
++n;
return n;
}
int FD_NFDS(fd_set *fds1 = nullptr, fd_set *fds2 = nullptr, fd_set *fds3 = nullptr)
{
int n = 0;
fd_set* fdss[3] = {fds1, fds2, fds3};
for (int i = 0; i < 3; ++i) {
fd_set* fds = fdss[i];
if (!fds) continue;
for (int fd = 0; fd < FD_SETSIZE; ++fd)
if (FD_ISSET(fd, fds))
n = (std::max)(fd, n);
}
return n + 1;
}
struct GcNew
{
std::unique_ptr<boost::any> holder_;
template <typename T>
T* operator-(T* ptr) {
holder_.reset(new boost::any(std::shared_ptr<T>(ptr)));
return ptr;
}
};
#define gc_new GcNew()-new
struct AutoFreeFdSet
{
fd_set fds_;
int nfds_;
AutoFreeFdSet(fd_set* fds) : fds_(*fds), nfds_(0) {
for (int i = 0; i < FD_SETSIZE; ++i)
if (FD_ISSET(i, &fds_))
nfds_ = i + 1;
}
~AutoFreeFdSet() {
for (int i = 0; i < FD_SETSIZE; ++i)
if (FD_ISSET(i, &fds_))
close(i);
}
bool operator==(fd_set *fds) {
return FD_EQUAL(&fds_, fds);
}
bool operator==(fd_set & fds) {
return FD_EQUAL(&fds_, &fds);
}
};
void connect_me(int fd)
{
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(43222);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int r = connect(fd, (sockaddr*)&addr, sizeof(addr));
EXPECT_EQ(r, 0);
}
std::shared_ptr<AutoFreeFdSet> CreateFds(fd_set* fds, int num)
{
FD_ZERO(fds);
for (int i = 0; i < num; ++i) {
int socketfd = socket(AF_INET, SOCK_STREAM, 0);
EXPECT_FALSE(-1 == socketfd);
EXPECT_LT(socketfd, FD_SETSIZE);
connect_me(socketfd);
FD_SET(socketfd, fds);
}
return std::shared_ptr<AutoFreeFdSet>(new AutoFreeFdSet(fds));
}
static timeval zero_timeout = {0, 0};
static timeval sec_timeout = {3, 0};
TEST(Select, TimeoutIs0)
{
// co_opt.debug = dbg_all;
// co_opt.debug_output = fopen("log", "w+");
go [] {
uint64_t yield_count = g_Scheduler.GetCurrentTaskYieldCount();
select(0, NULL, NULL, NULL, &zero_timeout);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
int fds[2];
int res = tcpSocketPair(0, SOCK_STREAM, 0, fds);
EXPECT_EQ(res, 0);
fd_set wfs;
FD_ZERO(&wfs);
FD_SET(fds[0], &wfs);
FD_SET(fds[1], &wfs);
EXPECT_EQ(FD_SIZE(&wfs), 2);
const fd_set x = wfs;
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
int n = select(FD_NFDS(&wfs), NULL, &wfs, NULL, &zero_timeout);
EXPECT_EQ(n, 2);
EXPECT_TRUE(FD_EQUAL(&x, &wfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
fd_set rfs = x;
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
n = select(FD_NFDS(&rfs), &rfs, NULL, NULL, &zero_timeout);
EXPECT_EQ(n, 0);
EXPECT_TRUE(FD_ISZERO(&rfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
rfs = x;
wfs = x;
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
n = select(FD_NFDS(&rfs, &wfs), &rfs, &wfs, NULL, &zero_timeout);
EXPECT_EQ(n, 2);
EXPECT_TRUE(FD_ISZERO(&rfs));
EXPECT_TRUE(FD_EQUAL(&x, &wfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
};
WaitUntilNoTask();
}
TEST(Select, TimeoutIsF1)
{
go [] {
uint64_t yield_count = g_Scheduler.GetCurrentTaskYieldCount();
select(0, NULL, NULL, NULL, nullptr);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count + 1);
int fds[2];
int res = tcpSocketPair(0, SOCK_STREAM, 0, fds);
EXPECT_EQ(res, 0);
fd_set wfs;
FD_ZERO(&wfs);
FD_SET(fds[0], &wfs);
FD_SET(fds[1], &wfs);
EXPECT_EQ(FD_SIZE(&wfs), 2);
const fd_set x = wfs;
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
int n = select(FD_NFDS(&wfs), NULL, &wfs, NULL, nullptr);
EXPECT_EQ(n, 2);
EXPECT_TRUE(FD_EQUAL(&x, &wfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
fd_set rfs = x;
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
n = select(FD_NFDS(&rfs, &wfs), &rfs, &wfs, NULL, nullptr);
EXPECT_EQ(n, 2);
EXPECT_TRUE(FD_EQUAL(&x, &wfs));
EXPECT_TRUE(FD_ISZERO(&rfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
};
WaitUntilNoTask();
}
TEST(Select, TimeoutIs1)
{
go [] {
fd_set wr_fds;
auto x = CreateFds(&wr_fds, 2);
EXPECT_EQ(FD_SIZE(&wr_fds), 2);
uint64_t yield_count = g_Scheduler.GetCurrentTaskYieldCount();
int n = select(x->nfds_, NULL, &wr_fds, NULL, gc_new timeval{1, 0});
EXPECT_TRUE(*x == wr_fds);
EXPECT_EQ(n, 2);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
fd_set rd_fds;
auto r = CreateFds(&rd_fds, 2);
EXPECT_EQ(FD_SIZE(&rd_fds), 2);
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
n = select((std::max)(x->nfds_, r->nfds_), &rd_fds, &wr_fds, NULL, gc_new timeval{1, 0});
EXPECT_TRUE(*x == wr_fds);
EXPECT_TRUE(FD_ISZERO(&rd_fds));
EXPECT_EQ(n, 2);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
};
WaitUntilNoTask();
go [] {
fd_set rd_fds;
auto r = CreateFds(&rd_fds, 2);
EXPECT_EQ(FD_SIZE(&rd_fds), 2);
uint64_t yield_count = g_Scheduler.GetCurrentTaskYieldCount();
auto start = std::chrono::high_resolution_clock::now();
int n = select(r->nfds_, &rd_fds, NULL, NULL, gc_new timeval{1, 0});
auto end = std::chrono::high_resolution_clock::now();
auto c = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
EXPECT_FALSE(*r == rd_fds);
EXPECT_TRUE(FD_ISZERO(&rd_fds));
EXPECT_EQ(n, 0);
EXPECT_LT(c, 1050);
EXPECT_GT(c, 950);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count + 1);
};
WaitUntilNoTask();
}
TEST(Select, Sleep)
{
go [] {
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), 0u);
auto start = std::chrono::high_resolution_clock::now();
int n = select(0, NULL, NULL, NULL, gc_new timeval{1, 0});
auto end = std::chrono::high_resolution_clock::now();
auto c = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
EXPECT_EQ(n, 0);
EXPECT_LT(c, 1050);
EXPECT_GT(c, 950);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), 1u);
};
WaitUntilNoTask();
}
TEST(Select, MultiThreads)
{
// co_sched.GetOptions().debug = co::dbg_hook;
for (int i = 0; i < 50; ++i)
go [] {
fd_set rd_fds;
auto r = CreateFds(&rd_fds, 2);
EXPECT_EQ(FD_SIZE(&rd_fds), 2);
uint64_t yield_count = g_Scheduler.GetCurrentTaskYieldCount();
auto start = std::chrono::high_resolution_clock::now();
int n = select(r->nfds_, &rd_fds, NULL, NULL, gc_new timeval{1, 0});
auto end = std::chrono::high_resolution_clock::now();
auto c = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
EXPECT_FALSE(*r == rd_fds);
EXPECT_TRUE(FD_ISZERO(&rd_fds));
EXPECT_EQ(n, 0);
EXPECT_LT(c, 1100);
EXPECT_GT(c, 999);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count + 1);
};
WaitUntilNoTask();
}
TEST(Select, TriggerReadOnly)
{
// co_opt.debug = dbg_all;
// co_opt.debug_output = fopen("log", "w+");
go [] {
int fds[2];
int res = tcpSocketPair(0, SOCK_STREAM, 0, fds);
EXPECT_EQ(res, 0);
fd_set rfs;
FD_ZERO(&rfs);
FD_SET(fds[0], &rfs);
FD_SET(fds[1], &rfs);
EXPECT_EQ(FD_SIZE(&rfs), 2);
go [=] {
co_sleep(200);
int res = write(fds[0], "a", 1);
// std::cout << "fill_send_buffer return " << res << endl;
};
auto yield_count = g_Scheduler.GetCurrentTaskYieldCount();
int n = select(FD_NFDS(&rfs), &rfs, NULL, NULL, &sec_timeout);
EXPECT_EQ(n, 1);
EXPECT_TRUE(!FD_ISSET(fds[0], &rfs));
EXPECT_TRUE(FD_ISSET(fds[1], &rfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count + 1);
};
WaitUntilNoTask();
}
| 9,693 | 3,985 |
/** @file bcm.cpp
@brief A brief, one sentence description.
A more detailed multiline description...
@author Peter Drysdale, Felix Fung,
*/
// Main module header
#include "bcm.h" // BCM;
// Other nftsim headers
#include "configf.h" // Configf;
#include "de.h" // RK4;
// C++ standard library headers
#include <vector> // std::vector;
using std::vector;
void BCM::BCMDE::rhs( const vector<double>& y, vector<double>& dydt, size_type n ) {
// y == { binding, H, Ca, nutilde, x, y, dnudt, nu, gNMDA }
CaDE::rhs(y, dydt, n);
// recalculate dCadt with NMDAR plasticity
// Ca
dydt[2] = y[8]*y[0]*y[1] -y[2]/tCa; // replace gnmda with y[8]
if( y[2]+dydt[2]*deltat < 0 ) {
dydt[2] = -y[2];
}
// gNMDA
dydt[8] = -y[8]/t_BCM *(y[3]/y[7]-1) +(gnmda_0-y[8])/t_rec;
if( y[7]==0 ) {
dydt[8] = 0;
}
}
void BCM::BCMDE::init( Configf& configf ) {
CaDE::init(configf);
configf.param("t_BCM",t_BCM);
for( size_type i=0; i<nodes; i++ ) {
variables[8][i] = gnmda;
}
gnmda_0 = gnmda;
if( !configf.optional("t_rec",t_rec) ) {
t_rec = 1e3;
}
}
BCM::BCM( size_type nodes, double deltat, size_type index,
const Propagator& prepropag, const Population& postpop )
: CaDP(nodes,deltat,index,prepropag,postpop) {
delete de;
de = new BCMDE(nodes,deltat);
delete rk4;
rk4 = new RK4(*de);
}
BCM::~BCM() = default;
void BCM::output( Output& output ) const {
output.prefix("Coupling",index+1);
output("nu",(*de)[7]);
output("nutilde",(*de)[3]);
output("Ca",(*de)[2]);
output("B",(*de)[0]);
output("gNMDA",(*de)[8]);
}
| 1,604 | 730 |
#include <glib.h>
#include <string>
#include <pbnjson.hpp>
#include "UwbLogging.h"
#include "UwbServiceManager.h"
#include "uart_serial.h"
PmLogContext gUwbLogContext;
static const char* const logContextName = "webos-uwb-service";
int main(int argc, char *argv[]) {
PmLogErr status = PmLogGetContext(logContextName, &gUwbLogContext);
if (status != kPmLogErr_None)
{
fprintf(stderr, "Failed to set PmLog context %s\n", logContextName);
abort();
}
UWB_LOG_INFO("UwbService Main : start com.webos.service.uwb");
GMainLoop* mainLoop = g_main_loop_new(nullptr, false);
UWB_LOG_INFO("UwbService Main : start com.webos.service.uwb-1");
if (mainLoop == NULL) {
UWB_LOG_DEBUG("mainLoop not created");
return EXIT_FAILURE;
}
UWB_LOG_INFO("UwbService Main : start com.webos.service.uwb-2");
UwbServiceManager *uwbService = UwbServiceManager::getInstance();
if (uwbService->init(mainLoop) == false) {
UWB_LOG_INFO("UwbService Main : start com.webos.service.uwb-3");
g_main_loop_unref(mainLoop);
return EXIT_FAILURE;
}
//Start uart communication, To be modified in refactoring step
int ret = 0;
pthread_t tid;
pthread_attr_t attr;
ret = pthread_attr_init(&attr);
if (ret != 0) {
perror("pthread_attr_init failed");
return -1;
}
ret = pthread_create(&tid, &attr, uart_start, NULL);
if (ret != 0) {
perror("pthread_create failed");
return -1;
}
ret = pthread_attr_destroy(&attr);
if (ret != 0) {
perror("pthread_attr_destroy failed");
return -1;
}
//End of start uart communication
UWB_LOG_INFO("UWB service started.");
g_main_loop_run(mainLoop);
UWB_LOG_INFO("UWB service stopped.");
g_main_loop_unref(mainLoop);
uwbService->deinit();
return EXIT_SUCCESS;
}
| 1,897 | 706 |
//==============================================================================
// This file is part of the SPNC project under the Apache License v2.0 by the
// Embedded Systems and Applications Group, TU Darmstadt.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// SPDX-License-Identifier: Apache-2.0
//==============================================================================
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/Passes.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/IR/Dominance.h"
#include "LoSPNPassDetails.h"
#include "LoSPN/LoSPNPasses.h"
#include "LoSPN/LoSPNDialect.h"
#include "LoSPN/LoSPNOps.h"
using namespace mlir;
using namespace mlir::spn::low;
namespace {
struct CopyRemovalPattern : public OpRewritePattern<SPNCopy> {
using OpRewritePattern<SPNCopy>::OpRewritePattern;
LogicalResult matchAndRewrite(SPNCopy op, PatternRewriter& rewriter) const override {
DominanceInfo domInfo(op->getParentOp());
// Collect all users of the target memref.
SmallVector<Operation*> tgtUsers;
for (auto* U : op.target().getUsers()) {
if (U == op.getOperation()) {
// Skip the copy op.
continue;
}
if (auto memEffect = dyn_cast<MemoryEffectOpInterface>(U)) {
SmallVector<MemoryEffects::EffectInstance, 1> effects;
memEffect.getEffectsOnValue(op.target(), effects);
for (auto e : effects) {
if (isa<MemoryEffects::Read>(e.getEffect()) || isa<MemoryEffects::Write>(e.getEffect())) {
tgtUsers.push_back(U);
}
}
}
}
SmallVector<Operation*> srcReads;
SmallVector<Operation*> srcWrites;
for (auto* U : op.source().getUsers()) {
if (auto memEffect = dyn_cast<MemoryEffectOpInterface>(U)) {
SmallVector<MemoryEffects::EffectInstance, 1> effects;
memEffect.getEffectsOnValue(op.target(), effects);
for (auto e : effects) {
if (isa<MemoryEffects::Read>(e.getEffect()) && U != op.getOperation()) {
srcReads.push_back(U);
} else if (isa<MemoryEffects::Write>(e.getEffect())) {
srcWrites.push_back(U);
}
}
}
}
// Legality check: For the removal of the copy operation to be legal,
// two constraints must be fulfilled:
// 1. All users of the target memref must dominate all writes to the source memref.
// Otherwise, they might read a wrong value (RAW) or write in the wrong order (WAW).
// 2. All reads of the source memref must be dominated by at least one write to the source memref.
// Otherwise, they might read values written by a write originally directed at the target memref.
// 1. Check
for (auto* tgtUse : tgtUsers) {
for (auto* srcWrite : srcWrites) {
if (!domInfo.properlyDominates(tgtUse, srcWrite)) {
return rewriter.notifyMatchFailure(op, "Potential RAW/WAW hazard, abort removal");
}
}
}
// 2. Check
for (auto* srcRead : srcReads) {
bool dominated = false;
for (auto* srcWrite : srcWrites) {
if (domInfo.properlyDominates(srcWrite, srcRead)) {
dominated = true;
break;
}
}
if (!dominated) {
return rewriter.notifyMatchFailure(op, "Source read not dominated by any source write, abort removal");
}
}
op.source().replaceAllUsesWith(op.target());
rewriter.eraseOp(op);
return mlir::success();
}
};
struct LoSPNCopyRemoval : public LoSPNCopyRemovalBase<LoSPNCopyRemoval> {
protected:
void runOnOperation() override {
RewritePatternSet patterns(getOperation()->getContext());
patterns.insert<CopyRemovalPattern>(getOperation()->getContext());
(void) mlir::applyPatternsAndFoldGreedily(getOperation(), FrozenRewritePatternSet(std::move(patterns)));
}
};
}
std::unique_ptr<OperationPass<SPNKernel>> mlir::spn::low::createLoSPNCopyRemovalPass() {
return std::make_unique<LoSPNCopyRemoval>();
}
| 4,378 | 1,342 |
class Solution {
public:
int maximumGap(vector<int>& nums) {
int n = nums.size();
if (n < 2) return 0;
int maxNum = *max_element(nums.begin(), nums.end());
int minNum = *min_element(nums.begin(), nums.end());
if (maxNum == minNum) return 0;
double bucketSize = (double)(maxNum - minNum) / (n - 1);
vector<pair<int, int> > buckets(n, make_pair(INT_MAX, INT_MIN));
for (int i = 0; i < n; i++) {
int idx = (nums[i] - minNum) / bucketSize;
buckets[idx].first = min(buckets[idx].first, nums[i]);
buckets[idx].second = max(buckets[idx].second, nums[i]);
}
int ans = buckets[0].second - buckets[0].first;
int pre = buckets[0].second;
for (int i = 1; i < n; i++) {
if (buckets[i].first == INT_MAX) continue;
ans = max(ans, max(buckets[i].first - pre, buckets[i].second - buckets[i].first));
pre = buckets[i].second;
}
return ans;
}
};
| 1,019 | 359 |
/**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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.
*/
#ifdef ENABLE_OPENGL_TEXTURE
#include "src/runtime/kernel/opencl/kernel/gl_to_cl.h"
#include <map>
#include <string>
#include "include/errorcode.h"
#include "src/kernel_registry.h"
#include "src/runtime/kernel/opencl/cl/gl_to_cl.cl.inc"
namespace mindspore::kernel {
int GLToCLOpenCLKernel::CheckSpecs() { return RET_OK; }
int GLToCLOpenCLKernel::PreProcess() {
if (this->out_mem_type_ == lite::opencl::MemType::IMG) return OpenCLKernel::PreProcess();
auto ret = ReSize();
if (ret != RET_OK) {
return ret;
}
return RET_OK;
}
int GLToCLOpenCLKernel::SetConstArgs() { return RET_OK; }
void GLToCLOpenCLKernel::SetGlobalLocal() {
global_size_ = {W_ * UP_DIV(C_, C4NUM), N_ * H_};
local_size_ = {1, 1};
OpenCLKernel::AlignGlobalLocal(global_size_, local_size_);
}
int GLToCLOpenCLKernel::Prepare() {
auto out_tensor = out_tensors_.front();
auto in_tensor = in_tensors_.front();
std::string kernel_name;
if (out_mem_type_ == lite::opencl::MemType::IMG) {
kernel_name = "GLTexture2D_to_IMG";
auto output = GpuTensorInfo(out_tensor);
N_ = output.N;
H_ = output.H;
W_ = output.W;
C_ = output.C;
} else {
kernel_name = "IMG_to_GLTexture2D";
auto input = GpuTensorInfo(in_tensor);
N_ = input.N;
H_ = input.H;
W_ = input.W;
C_ = input.C;
}
this->set_name(kernel_name);
const std::string program_name = "GLTexture2D_to_img";
std::string source = gl_to_cl_source;
if (!ocl_runtime_->LoadSource(program_name, source)) {
MS_LOG(ERROR) << "Load source failed.";
return RET_ERROR;
}
auto ret = ocl_runtime_->BuildKernel(kernel_, program_name, kernel_name);
if (ret != RET_OK) {
MS_LOG(ERROR) << "Build kernel failed.";
return ret;
}
SetGlobalLocal();
if (SetConstArgs() != RET_OK) {
MS_LOG(ERROR) << "SeConstArgs failed.";
return RET_ERROR;
}
MS_LOG(DEBUG) << kernel_name << " Init Done!";
return RET_OK;
}
int GLToCLOpenCLKernel::Run() {
MS_LOG(DEBUG) << this->name() << " Running!";
cl::Context *context = ocl_runtime_->Context();
auto dst_mem_type = out_mem_type_;
cl_int status;
if (dst_mem_type == lite::opencl::MemType::IMG) {
auto in_tensor = in_tensors_.front();
auto data_type = in_tensor->data_type();
if (data_type != kNumberTypeGLUInt) {
MS_LOG(ERROR) << "Unsupported data type " << data_type;
return RET_ERROR;
}
cl_GLuint *gl_texture_id = reinterpret_cast<cl_GLuint *>(in_tensor->data());
auto img_gl = cl::ImageGL(*context, CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, *gl_texture_id, &status);
if (status != CL_SUCCESS) {
MS_LOG(ERROR) << "Create ImageGL failed : " << status << std::endl;
return RET_ERROR;
}
if (kernel_.setArg(0, sizeof(cl_mem), &img_gl) != CL_SUCCESS) {
MS_LOG(ERROR) << "SetKernelArg failed.";
return RET_ERROR;
}
if (ocl_runtime_->SetKernelArg(kernel_, 1, out_tensors_.front()->data(),
(dst_mem_type == lite::opencl::MemType::BUF)) != CL_SUCCESS) {
MS_LOG(ERROR) << "SetKernelArg failed.";
return RET_ERROR;
}
if (ocl_runtime_->RunKernel(kernel_, global_range_, local_range_, nullptr, &event_) != RET_OK) {
MS_LOG(ERROR) << "RunKernel failed.";
return RET_ERROR;
}
} else {
auto out_tensor = out_tensors_.front();
cl_GLuint *gl_texture_id = reinterpret_cast<cl_GLuint *>(out_tensor->data());
auto img_gl = cl::ImageGL(*context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, *gl_texture_id, &status);
if (status != CL_SUCCESS) {
MS_LOG(ERROR) << "Create ImageGL failed : " << status << std::endl;
return RET_ERROR;
}
if (ocl_runtime_->SetKernelArg(kernel_, 0, in_tensors_.front()->data()) != CL_SUCCESS) {
MS_LOG(ERROR) << "SetKernelArg failed.";
return RET_ERROR;
}
if (kernel_.setArg(1, sizeof(cl_mem), &img_gl) != CL_SUCCESS) {
MS_LOG(ERROR) << "SetKernelArg failed.";
return RET_ERROR;
}
if (ocl_runtime_->RunKernel(kernel_, global_range_, local_range_, nullptr, &event_) != RET_OK) {
MS_LOG(ERROR) << "RunKernel failed.";
return RET_ERROR;
}
}
return RET_OK;
}
int GLToCLOpenCLKernel::InferShape() {
if (!InferShapeDone()) {
out_tensors_.front()->set_shape(in_tensors_.front()->shape());
}
return RET_OK;
}
} // namespace mindspore::kernel
#endif
| 4,975 | 1,860 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "exec/tablet_sink.h"
#include <sstream>
#include "exprs/expr.h"
#include "runtime/exec_env.h"
#include "runtime/row_batch.h"
#include "runtime/runtime_state.h"
#include "runtime/tuple_row.h"
#include "util/brpc_stub_cache.h"
#include "util/uid_util.h"
#include "service/brpc.h"
namespace doris {
namespace stream_load {
NodeChannel::NodeChannel(OlapTableSink* parent, int64_t index_id,
int64_t node_id, int32_t schema_hash)
: _parent(parent), _index_id(index_id),
_node_id(node_id), _schema_hash(schema_hash) {
}
NodeChannel::~NodeChannel() {
if (_open_closure != nullptr) {
if (_open_closure->unref()) {
delete _open_closure;
}
_open_closure = nullptr;
}
if (_add_batch_closure != nullptr) {
if (_add_batch_closure->unref()) {
delete _add_batch_closure;
}
_add_batch_closure = nullptr;
}
_add_batch_request.release_id();
}
Status NodeChannel::init(RuntimeState* state) {
_tuple_desc = _parent->_output_tuple_desc;
_node_info = _parent->_nodes_info->find_node(_node_id);
if (_node_info == nullptr) {
std::stringstream ss;
ss << "unknown node id, id=" << _node_id;
return Status::InternalError(ss.str());
}
RowDescriptor row_desc(_tuple_desc, false);
_batch.reset(new RowBatch(row_desc, state->batch_size(), _parent->_mem_tracker));
_stub = state->exec_env()->brpc_stub_cache()->get_stub(
_node_info->host, _node_info->brpc_port);
if (_stub == nullptr) {
LOG(WARNING) << "Get rpc stub failed, host=" << _node_info->host
<< ", port=" << _node_info->brpc_port;
return Status::InternalError("get rpc stub failed");
}
// Initialize _add_batch_request
_add_batch_request.set_allocated_id(&_parent->_load_id);
_add_batch_request.set_index_id(_index_id);
_add_batch_request.set_sender_id(_parent->_sender_id);
return Status::OK();
}
void NodeChannel::open() {
PTabletWriterOpenRequest request;
request.set_allocated_id(&_parent->_load_id);
request.set_index_id(_index_id);
request.set_txn_id(_parent->_txn_id);
request.set_allocated_schema(_parent->_schema->to_protobuf());
for (auto& tablet : _all_tablets) {
auto ptablet = request.add_tablets();
ptablet->set_partition_id(tablet.partition_id);
ptablet->set_tablet_id(tablet.tablet_id);
}
request.set_num_senders(_parent->_num_senders);
request.set_need_gen_rollup(_parent->_need_gen_rollup);
_open_closure = new RefCountClosure<PTabletWriterOpenResult>();
_open_closure->ref();
// This ref is for RPC's reference
_open_closure->ref();
_open_closure->cntl.set_timeout_ms(_rpc_timeout_ms);
_stub->tablet_writer_open(&_open_closure->cntl,
&request,
&_open_closure->result,
_open_closure);
request.release_id();
request.release_schema();
}
Status NodeChannel::open_wait() {
_open_closure->join();
if (_open_closure->cntl.Failed()) {
LOG(WARNING) << "failed to open tablet writer, error="
<< berror(_open_closure->cntl.ErrorCode())
<< ", error_text=" << _open_closure->cntl.ErrorText();
return Status::InternalError("failed to open tablet writer");
}
Status status(_open_closure->result.status());
if (_open_closure->unref()) {
delete _open_closure;
}
_open_closure = nullptr;
// add batch closure
_add_batch_closure = new RefCountClosure<PTabletWriterAddBatchResult>();
_add_batch_closure->ref();
return status;
}
Status NodeChannel::add_row(Tuple* input_tuple, int64_t tablet_id) {
auto row_no = _batch->add_row();
if (row_no == RowBatch::INVALID_ROW_INDEX) {
RETURN_IF_ERROR(_send_cur_batch());
row_no = _batch->add_row();
}
DCHECK_NE(row_no, RowBatch::INVALID_ROW_INDEX);
auto tuple = input_tuple->deep_copy(*_tuple_desc, _batch->tuple_data_pool());
_batch->get_row(row_no)->set_tuple(0, tuple);
_batch->commit_last_row();
_add_batch_request.add_tablet_ids(tablet_id);
return Status::OK();
}
Status NodeChannel::close(RuntimeState* state) {
auto st = _close(state);
_batch.reset();
return st;
}
Status NodeChannel::_close(RuntimeState* state) {
RETURN_IF_ERROR(_wait_in_flight_packet());
return _send_cur_batch(true);
}
Status NodeChannel::close_wait(RuntimeState* state) {
RETURN_IF_ERROR(_wait_in_flight_packet());
Status status(_add_batch_closure->result.status());
if (status.ok()) {
for (auto& tablet : _add_batch_closure->result.tablet_vec()) {
TTabletCommitInfo commit_info;
commit_info.tabletId = tablet.tablet_id();
commit_info.backendId = _node_id;
state->tablet_commit_infos().emplace_back(std::move(commit_info));
}
}
// clear batch after sendt
_batch.reset();
return status;
}
void NodeChannel::cancel() {
// Do we need to wait last rpc finished???
PTabletWriterCancelRequest request;
request.set_allocated_id(&_parent->_load_id);
request.set_index_id(_index_id);
request.set_sender_id(_parent->_sender_id);
auto closure = new RefCountClosure<PTabletWriterCancelResult>();
closure->ref();
closure->cntl.set_timeout_ms(_rpc_timeout_ms);
_stub->tablet_writer_cancel(&closure->cntl,
&request,
&closure->result,
closure);
request.release_id();
// reset batch
_batch.reset();
}
Status NodeChannel::_wait_in_flight_packet() {
if (!_has_in_flight_packet) {
return Status::OK();
}
SCOPED_RAW_TIMER(_parent->mutable_wait_in_flight_packet_ns());
_add_batch_closure->join();
_has_in_flight_packet = false;
if (_add_batch_closure->cntl.Failed()) {
LOG(WARNING) << "failed to send batch, error="
<< berror(_add_batch_closure->cntl.ErrorCode())
<< ", error_text=" << _add_batch_closure->cntl.ErrorText();
return Status::InternalError("failed to send batch");
}
return {_add_batch_closure->result.status()};
}
Status NodeChannel::_send_cur_batch(bool eos) {
RETURN_IF_ERROR(_wait_in_flight_packet());
// tablet_ids has already set when add row
_add_batch_request.set_eos(eos);
_add_batch_request.set_packet_seq(_next_packet_seq);
if (_batch->num_rows() > 0) {
SCOPED_RAW_TIMER(_parent->mutable_serialize_batch_ns());
_batch->serialize(_add_batch_request.mutable_row_batch());
}
_add_batch_closure->ref();
_add_batch_closure->cntl.Reset();
_add_batch_closure->cntl.set_timeout_ms(_rpc_timeout_ms);
if (eos) {
for (auto pid : _parent->_partition_ids) {
_add_batch_request.add_partition_ids(pid);
}
}
_stub->tablet_writer_add_batch(&_add_batch_closure->cntl,
&_add_batch_request,
&_add_batch_closure->result,
_add_batch_closure);
_add_batch_request.clear_tablet_ids();
_add_batch_request.clear_row_batch();
_add_batch_request.clear_partition_ids();
_has_in_flight_packet = true;
_next_packet_seq++;
_batch->reset();
return Status::OK();
}
IndexChannel::~IndexChannel() {
}
Status IndexChannel::init(RuntimeState* state,
const std::vector<TTabletWithPartition>& tablets) {
// nodeId -> tabletIds
std::map<int64_t, std::vector<int64_t>> tablets_by_node;
for (auto& tablet : tablets) {
auto location = _parent->_location->find_tablet(tablet.tablet_id);
if (location == nullptr) {
LOG(WARNING) << "unknow tablet, tablet_id=" << tablet.tablet_id;
return Status::InternalError("unknown tablet");
}
std::vector<NodeChannel*> channels;
for (auto& node_id : location->node_ids) {
NodeChannel* channel = nullptr;
auto it = _node_channels.find(node_id);
if (it == std::end(_node_channels)) {
channel = _parent->_pool->add(
new NodeChannel(_parent, _index_id, node_id, _schema_hash));
_node_channels.emplace(node_id, channel);
} else {
channel = it->second;
}
channel->add_tablet(tablet);
channels.push_back(channel);
}
_channels_by_tablet.emplace(tablet.tablet_id, std::move(channels));
}
for (auto& it : _node_channels) {
RETURN_IF_ERROR(it.second->init(state));
}
return Status::OK();
}
Status IndexChannel::open() {
for (auto& it : _node_channels) {
it.second->open();
}
for (auto& it : _node_channels) {
auto channel = it.second;
auto st = channel->open_wait();
if (!st.ok()) {
LOG(WARNING) << "tablet open failed, load_id=" << _parent->_load_id
<< ", node=" << channel->node_info()->host
<< ":" << channel->node_info()->brpc_port
<< ", errmsg=" << st.get_error_msg();
if (_handle_failed_node(channel)) {
LOG(WARNING) << "open failed, load_id=" << _parent->_load_id;
return st;
}
}
}
return Status::OK();
}
Status IndexChannel::add_row(Tuple* tuple, int64_t tablet_id) {
auto it = _channels_by_tablet.find(tablet_id);
DCHECK(it != std::end(_channels_by_tablet)) << "unknown tablet, tablet_id=" << tablet_id;
for (auto channel : it->second) {
if (channel->already_failed()) {
continue;
}
auto st = channel->add_row(tuple, tablet_id);
if (!st.ok()) {
LOG(WARNING) << "NodeChannel add row failed, load_id=" << _parent->_load_id
<< ", tablet_id=" << tablet_id
<< ", node=" << channel->node_info()->host
<< ":" << channel->node_info()->brpc_port
<< ", errmsg=" << st.get_error_msg();
if (_handle_failed_node(channel)) {
LOG(WARNING) << "add row failed, load_id=" << _parent->_load_id;
return st;
}
}
}
return Status::OK();
}
Status IndexChannel::close(RuntimeState* state) {
std::vector<NodeChannel*> need_wait_channels;
need_wait_channels.reserve(_node_channels.size());
Status close_status;
for (auto& it : _node_channels) {
auto channel = it.second;
if (channel->already_failed() || !close_status.ok()) {
channel->cancel();
continue;
}
auto st = channel->close(state);
if (st.ok()) {
need_wait_channels.push_back(channel);
} else {
LOG(WARNING) << "close node channel failed, load_id=" << _parent->_load_id
<< ", node=" << channel->node_info()->host
<< ":" << channel->node_info()->brpc_port
<< ", errmsg=" << st.get_error_msg();
if (_handle_failed_node(channel)) {
LOG(WARNING) << "close failed, load_id=" << _parent->_load_id;
close_status = st;
}
}
}
if (close_status.ok()) {
for (auto channel : need_wait_channels) {
auto st = channel->close_wait(state);
if (!st.ok()) {
LOG(WARNING) << "close_wait node channel failed, load_id=" << _parent->_load_id
<< ", node=" << channel->node_info()->host
<< ":" << channel->node_info()->brpc_port
<< ", errmsg=" << st.get_error_msg();
if (_handle_failed_node(channel)) {
LOG(WARNING) << "close_wait failed, load_id=" << _parent->_load_id;
return st;
}
}
}
}
return close_status;
}
void IndexChannel::cancel() {
for (auto& it : _node_channels) {
it.second->cancel();
}
}
bool IndexChannel::_handle_failed_node(NodeChannel* channel) {
DCHECK(!channel->already_failed());
channel->set_failed();
_num_failed_channels++;
return _num_failed_channels >= ((_parent->_num_repicas + 1) / 2);
}
OlapTableSink::OlapTableSink(ObjectPool* pool,
const RowDescriptor& row_desc,
const std::vector<TExpr>& texprs,
Status* status)
: _pool(pool), _input_row_desc(row_desc), _filter_bitmap(1024) {
if (!texprs.empty()) {
*status = Expr::create_expr_trees(_pool, texprs, &_output_expr_ctxs);
}
}
OlapTableSink::~OlapTableSink() {
}
Status OlapTableSink::init(const TDataSink& t_sink) {
DCHECK(t_sink.__isset.olap_table_sink);
auto& table_sink = t_sink.olap_table_sink;
_load_id.set_hi(table_sink.load_id.hi);
_load_id.set_lo(table_sink.load_id.lo);
_txn_id = table_sink.txn_id;
_db_id = table_sink.db_id;
_table_id = table_sink.table_id;
_num_repicas = table_sink.num_replicas;
_need_gen_rollup = table_sink.need_gen_rollup;
_db_name = table_sink.db_name;
_table_name = table_sink.table_name;
_tuple_desc_id = table_sink.tuple_id;
_schema.reset(new OlapTableSchemaParam());
RETURN_IF_ERROR(_schema->init(table_sink.schema));
_partition = _pool->add(new OlapTablePartitionParam(_schema, table_sink.partition));
RETURN_IF_ERROR(_partition->init());
_location = _pool->add(new OlapTableLocationParam(table_sink.location));
_nodes_info = _pool->add(new DorisNodesInfo(table_sink.nodes_info));
return Status::OK();
}
Status OlapTableSink::prepare(RuntimeState* state) {
RETURN_IF_ERROR(DataSink::prepare(state));
_sender_id = state->per_fragment_instance_idx();
_num_senders = state->num_per_fragment_instances();
// profile must add to state's object pool
_profile = state->obj_pool()->add(new RuntimeProfile(_pool, "OlapTableSink"));
_mem_tracker = _pool->add(
new MemTracker(-1, "OlapTableSink", state->instance_mem_tracker()));
SCOPED_TIMER(_profile->total_time_counter());
// Prepare the exprs to run.
RETURN_IF_ERROR(Expr::prepare(_output_expr_ctxs, state,
_input_row_desc, _expr_mem_tracker.get()));
// get table's tuple descriptor
_output_tuple_desc = state->desc_tbl().get_tuple_descriptor(_tuple_desc_id);
if (_output_tuple_desc == nullptr) {
LOG(WARNING) << "unknown destination tuple descriptor, id=" << _tuple_desc_id;
return Status::InternalError("unknown destination tuple descriptor");
}
if (!_output_expr_ctxs.empty()) {
if (_output_expr_ctxs.size() != _output_tuple_desc->slots().size()) {
LOG(WARNING) << "number of exprs is not same with slots, num_exprs="
<< _output_expr_ctxs.size()
<< ", num_slots=" << _output_tuple_desc->slots().size();
return Status::InternalError("number of exprs is not same with slots");
}
for (int i = 0; i < _output_expr_ctxs.size(); ++i) {
if (!is_type_compatible(_output_expr_ctxs[i]->root()->type().type,
_output_tuple_desc->slots()[i]->type().type)) {
LOG(WARNING) << "type of exprs is not match slot's, expr_type="
<< _output_expr_ctxs[i]->root()->type().type
<< ", slot_type=" << _output_tuple_desc->slots()[i]->type().type
<< ", slot_name=" << _output_tuple_desc->slots()[i]->col_name();
return Status::InternalError("expr's type is not same with slot's");
}
}
}
_output_row_desc = _pool->add(new RowDescriptor(_output_tuple_desc, false));
_output_batch.reset(new RowBatch(*_output_row_desc, state->batch_size(), _mem_tracker));
_max_decimal_val.resize(_output_tuple_desc->slots().size());
_min_decimal_val.resize(_output_tuple_desc->slots().size());
_max_decimalv2_val.resize(_output_tuple_desc->slots().size());
_min_decimalv2_val.resize(_output_tuple_desc->slots().size());
// check if need validate batch
for (int i = 0; i < _output_tuple_desc->slots().size(); ++i) {
auto slot = _output_tuple_desc->slots()[i];
switch (slot->type().type) {
case TYPE_DECIMAL:
_max_decimal_val[i].to_max_decimal(slot->type().precision, slot->type().scale);
_min_decimal_val[i].to_min_decimal(slot->type().precision, slot->type().scale);
_need_validate_data = true;
break;
case TYPE_DECIMALV2:
_max_decimalv2_val[i].to_max_decimal(slot->type().precision, slot->type().scale);
_min_decimalv2_val[i].to_min_decimal(slot->type().precision, slot->type().scale);
_need_validate_data = true;
break;
case TYPE_CHAR:
case TYPE_VARCHAR:
case TYPE_DATE:
case TYPE_DATETIME:
_need_validate_data = true;
break;
default:
break;
}
}
// add all counter
_input_rows_counter = ADD_COUNTER(_profile, "RowsRead", TUnit::UNIT);
_output_rows_counter = ADD_COUNTER(_profile, "RowsReturned", TUnit::UNIT);
_filtered_rows_counter = ADD_COUNTER(_profile, "RowsFiltered", TUnit::UNIT);
_send_data_timer = ADD_TIMER(_profile, "SendDataTime");
_convert_batch_timer = ADD_TIMER(_profile, "ConvertBatchTime");
_validate_data_timer = ADD_TIMER(_profile, "ValidateDataTime");
_open_timer = ADD_TIMER(_profile, "OpenTime");
_close_timer = ADD_TIMER(_profile, "CloseTime");
_wait_in_flight_packet_timer = ADD_TIMER(_profile, "WaitInFlightPacketTime");
_serialize_batch_timer = ADD_TIMER(_profile, "SerializeBatchTime");
// open all channels
auto& partitions = _partition->get_partitions();
for (int i = 0; i < _schema->indexes().size(); ++i) {
// collect all tablets belong to this rollup
std::vector<TTabletWithPartition> tablets;
auto index = _schema->indexes()[i];
for (auto part : partitions) {
for (auto tablet : part->indexes[i].tablets) {
TTabletWithPartition tablet_with_partition;
tablet_with_partition.partition_id = part->id;
tablet_with_partition.tablet_id = tablet;
tablets.emplace_back(std::move(tablet_with_partition));
}
}
auto channel = _pool->add(new IndexChannel(this, index->index_id, index->schema_hash));
RETURN_IF_ERROR(channel->init(state, tablets));
_channels.emplace_back(channel);
}
return Status::OK();
}
Status OlapTableSink::open(RuntimeState* state) {
SCOPED_TIMER(_profile->total_time_counter());
SCOPED_TIMER(_open_timer);
// Prepare the exprs to run.
RETURN_IF_ERROR(Expr::open(_output_expr_ctxs, state));
for (auto channel : _channels) {
RETURN_IF_ERROR(channel->open());
}
return Status::OK();
}
Status OlapTableSink::send(RuntimeState* state, RowBatch* input_batch) {
SCOPED_TIMER(_profile->total_time_counter());
_number_input_rows += input_batch->num_rows();
RowBatch* batch = input_batch;
if (!_output_expr_ctxs.empty()) {
SCOPED_RAW_TIMER(&_convert_batch_ns);
_output_batch->reset();
_convert_batch(state, input_batch, _output_batch.get());
batch = _output_batch.get();
}
int num_invalid_rows = 0;
if (_need_validate_data) {
SCOPED_RAW_TIMER(&_validate_data_ns);
_filter_bitmap.Reset(batch->num_rows());
num_invalid_rows = _validate_data(state, batch, &_filter_bitmap);
_number_filtered_rows += num_invalid_rows;
}
SCOPED_RAW_TIMER(&_send_data_ns);
for (int i = 0; i < batch->num_rows(); ++i) {
Tuple* tuple = batch->get_row(i)->get_tuple(0);
if (num_invalid_rows > 0 && _filter_bitmap.Get(i)) {
continue;
}
const OlapTablePartition* partition = nullptr;
uint32_t dist_hash = 0;
if (!_partition->find_tablet(tuple, &partition, &dist_hash)) {
std::stringstream ss;
ss << "no partition for this tuple. tuple="
<< Tuple::to_string(tuple, *_output_tuple_desc);
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
_number_filtered_rows++;
continue;
}
_partition_ids.emplace(partition->id);
uint32_t tablet_index = dist_hash % partition->num_buckets;
for (int j = 0; j < partition->indexes.size(); ++j) {
int64_t tablet_id = partition->indexes[j].tablets[tablet_index];
RETURN_IF_ERROR(_channels[j]->add_row(tuple, tablet_id));
_number_output_rows++;
}
}
return Status::OK();
}
Status OlapTableSink::close(RuntimeState* state, Status close_status) {
Status status = close_status;
if (status.ok()) {
// SCOPED_TIMER should only be called is status is ok.
// if status is not ok, this OlapTableSink may not be prepared,
// so the `_profile` may be null.
SCOPED_TIMER(_profile->total_time_counter());
{
SCOPED_TIMER(_close_timer);
for (auto channel : _channels) {
status = channel->close(state);
if (!status.ok()) {
LOG(WARNING) << "close channel failed, load_id=" << _load_id
<< ", txn_id=" << _txn_id;
}
}
}
COUNTER_SET(_input_rows_counter, _number_input_rows);
COUNTER_SET(_output_rows_counter, _number_output_rows);
COUNTER_SET(_filtered_rows_counter, _number_filtered_rows);
COUNTER_SET(_send_data_timer, _send_data_ns);
COUNTER_SET(_convert_batch_timer, _convert_batch_ns);
COUNTER_SET(_validate_data_timer, _validate_data_ns);
COUNTER_SET(_wait_in_flight_packet_timer, _wait_in_flight_packet_ns);
COUNTER_SET(_serialize_batch_timer, _serialize_batch_ns);
state->update_num_rows_load_filtered(_number_filtered_rows);
} else {
for (auto channel : _channels) {
channel->cancel();
}
}
Expr::close(_output_expr_ctxs, state);
_output_batch.reset();
return status;
}
void OlapTableSink::_convert_batch(RuntimeState* state, RowBatch* input_batch, RowBatch* output_batch) {
DCHECK_GE(output_batch->capacity(), input_batch->num_rows());
int commit_rows = 0;
for (int i = 0; i < input_batch->num_rows(); ++i) {
auto src_row = input_batch->get_row(i);
Tuple* dst_tuple = (Tuple*)output_batch->tuple_data_pool()->allocate(
_output_tuple_desc->byte_size());
bool exist_null_value_for_not_null_col = false;
for (int j = 0; j < _output_expr_ctxs.size(); ++j) {
auto src_val = _output_expr_ctxs[j]->get_value(src_row);
auto slot_desc = _output_tuple_desc->slots()[j];
if (slot_desc->is_nullable()) {
if (src_val == nullptr) {
dst_tuple->set_null(slot_desc->null_indicator_offset());
continue;
} else {
dst_tuple->set_not_null(slot_desc->null_indicator_offset());
}
} else {
if (src_val == nullptr) {
std::stringstream ss;
ss << "null value for not null column, column=" << slot_desc->col_name();
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
exist_null_value_for_not_null_col = true;
_number_filtered_rows++;
break;
}
}
void* slot = dst_tuple->get_slot(slot_desc->tuple_offset());
RawValue::write(src_val, slot, slot_desc->type(), _output_batch->tuple_data_pool());
}
if (!exist_null_value_for_not_null_col) {
output_batch->get_row(commit_rows)->set_tuple(0, dst_tuple);
commit_rows++;
}
}
output_batch->commit_rows(commit_rows);
}
int OlapTableSink::_validate_data(RuntimeState* state, RowBatch* batch, Bitmap* filter_bitmap) {
int filtered_rows = 0;
for (int row_no = 0; row_no < batch->num_rows(); ++row_no) {
Tuple* tuple = batch->get_row(row_no)->get_tuple(0);
bool row_valid = true;
for (int i = 0; row_valid && i < _output_tuple_desc->slots().size(); ++i) {
SlotDescriptor* desc = _output_tuple_desc->slots()[i];
if (tuple->is_null(desc->null_indicator_offset())) {
continue;
}
void* slot = tuple->get_slot(desc->tuple_offset());
switch (desc->type().type) {
case TYPE_CHAR:
case TYPE_VARCHAR: {
// Fixed length string
StringValue* str_val = (StringValue*)slot;
if (str_val->len > desc->type().len) {
std::stringstream ss;
ss << "the length of input is too long than schema. "
<< "column_name: " << desc->col_name() << "; "
<< "input_str: [" << std::string(str_val->ptr, str_val->len) << "] "
<< "schema length: " << desc->type().len << "; "
<< "actual length: " << str_val->len << "; ";
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
// padding 0 to CHAR field
if (desc->type().type == TYPE_CHAR
&& str_val->len < desc->type().len) {
auto new_ptr = (char*)batch->tuple_data_pool()->allocate(desc->type().len);
memcpy(new_ptr, str_val->ptr, str_val->len);
memset(new_ptr + str_val->len, 0, desc->type().len - str_val->len);
str_val->ptr = new_ptr;
str_val->len = desc->type().len;
}
break;
}
case TYPE_DECIMAL: {
DecimalValue* dec_val = (DecimalValue*)slot;
if (dec_val->scale() > desc->type().scale) {
int code = dec_val->round(dec_val, desc->type().scale, HALF_UP);
if (code != E_DEC_OK) {
std::stringstream ss;
ss << "round one decimal failed.value=" << dec_val->to_string();
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
}
if (*dec_val > _max_decimal_val[i] || *dec_val < _min_decimal_val[i]) {
std::stringstream ss;
ss << "decimal value is not valid for defination, column=" << desc->col_name()
<< ", value=" << dec_val->to_string()
<< ", precision=" << desc->type().precision
<< ", scale=" << desc->type().scale;
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
break;
}
case TYPE_DECIMALV2: {
DecimalV2Value dec_val(reinterpret_cast<const PackedInt128*>(slot)->value);
if (dec_val.greater_than_scale(desc->type().scale)) {
int code = dec_val.round(&dec_val, desc->type().scale, HALF_UP);
reinterpret_cast<PackedInt128*>(slot)->value = dec_val.value();
if (code != E_DEC_OK) {
std::stringstream ss;
ss << "round one decimal failed.value=" << dec_val.to_string();
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
}
if (dec_val > _max_decimalv2_val[i] || dec_val < _min_decimalv2_val[i]) {
std::stringstream ss;
ss << "decimal value is not valid for defination, column=" << desc->col_name()
<< ", value=" << dec_val.to_string()
<< ", precision=" << desc->type().precision
<< ", scale=" << desc->type().scale;
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
break;
}
case TYPE_DATE:
case TYPE_DATETIME: {
static DateTimeValue s_min_value = DateTimeValue(19000101000000UL);
// static DateTimeValue s_max_value = DateTimeValue(99991231235959UL);
DateTimeValue* date_val = (DateTimeValue*)slot;
if (*date_val < s_min_value) {
std::stringstream ss;
ss << "datetime value is not valid, column=" << desc->col_name()
<< ", value=" << date_val->debug_string();
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
}
default:
break;
}
}
}
return filtered_rows;
}
}
}
| 31,578 | 9,996 |
// Created on: 2011-03-06
// Created by: Sergey ZERCHANINOV
// Copyright (c) 2011-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Graphic3d_GraduatedTrihedron_HeaderFile
#define _Graphic3d_GraduatedTrihedron_HeaderFile
#include <Font_FontAspect.hxx>
#include <NCollection_Array1.hxx>
#include <Quantity_Color.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Integer.hxx>
#include <TCollection_AsciiString.hxx>
#include <TCollection_ExtendedString.hxx>
class Graphic3d_CView;
//! Defines the class of a graduated trihedron.
//! It contains main style parameters for implementation of graduated trihedron
//! @sa OpenGl_GraduatedTrihedron
class Graphic3d_GraduatedTrihedron
{
public:
//! Class that stores style for one graduated trihedron axis such as colors, lengths and customization flags.
//! It is used in Graphic3d_GraduatedTrihedron.
class AxisAspect
{
public:
AxisAspect (const TCollection_ExtendedString theName = "", const Quantity_Color theNameColor = Quantity_NOC_BLACK,
const Quantity_Color theColor = Quantity_NOC_BLACK,
const Standard_Integer theValuesOffset = 10, const Standard_Integer theNameOffset = 30,
const Standard_Integer theTickmarksNumber = 5, const Standard_Integer theTickmarksLength = 10,
const Standard_Boolean theToDrawName = Standard_True,
const Standard_Boolean theToDrawValues = Standard_True,
const Standard_Boolean theToDrawTickmarks = Standard_True)
: myName (theName),
myToDrawName (theToDrawName),
myToDrawTickmarks (theToDrawTickmarks),
myToDrawValues (theToDrawValues),
myNameColor (theNameColor),
myTickmarksNumber (theTickmarksNumber),
myTickmarksLength (theTickmarksLength),
myColor (theColor),
myValuesOffset (theValuesOffset),
myNameOffset (theNameOffset)
{ }
public:
void SetName (const TCollection_ExtendedString& theName) { myName = theName; }
const TCollection_ExtendedString& Name() const { return myName; }
Standard_Boolean ToDrawName() const { return myToDrawName; }
void SetDrawName (const Standard_Boolean theToDraw) { myToDrawName = theToDraw; }
Standard_Boolean ToDrawTickmarks() const { return myToDrawTickmarks; }
void SetDrawTickmarks (const Standard_Boolean theToDraw) { myToDrawTickmarks = theToDraw; }
Standard_Boolean ToDrawValues() const { return myToDrawValues; }
void SetDrawValues (const Standard_Boolean theToDraw) { myToDrawValues = theToDraw; }
const Quantity_Color& NameColor() const { return myNameColor; }
void SetNameColor (const Quantity_Color& theColor) { myNameColor = theColor; }
//! Color of axis and values
const Quantity_Color& Color() const { return myColor; }
//! Sets color of axis and values
void SetColor (const Quantity_Color& theColor) { myColor = theColor; }
Standard_Integer TickmarksNumber() const { return myTickmarksNumber; }
void SetTickmarksNumber (const Standard_Integer theValue) { myTickmarksNumber = theValue; }
Standard_Integer TickmarksLength() const { return myTickmarksLength; }
void SetTickmarksLength (const Standard_Integer theValue) { myTickmarksLength = theValue; }
Standard_Integer ValuesOffset() const { return myValuesOffset; }
void SetValuesOffset (const Standard_Integer theValue) { myValuesOffset = theValue; }
Standard_Integer NameOffset() const { return myNameOffset; }
void SetNameOffset (const Standard_Integer theValue) { myNameOffset = theValue; }
protected:
TCollection_ExtendedString myName;
Standard_Boolean myToDrawName;
Standard_Boolean myToDrawTickmarks;
Standard_Boolean myToDrawValues;
Quantity_Color myNameColor;
Standard_Integer myTickmarksNumber; //!< Number of splits along axes
Standard_Integer myTickmarksLength; //!< Length of tickmarks
Quantity_Color myColor; //!< Color of axis and values
Standard_Integer myValuesOffset; //!< Offset for drawing values
Standard_Integer myNameOffset; //!< Offset for drawing name of axis
};
public:
typedef void (*MinMaxValuesCallback) (Graphic3d_CView*);
public:
//! Default constructor
//! Constructs the default graduated trihedron with grid, X, Y, Z axes, and tickmarks
Graphic3d_GraduatedTrihedron (const TCollection_AsciiString& theNamesFont = "Arial",
const Font_FontAspect& theNamesStyle = Font_FA_Bold, const Standard_Integer theNamesSize = 12,
const TCollection_AsciiString& theValuesFont = "Arial",
const Font_FontAspect& theValuesStyle = Font_FA_Regular, const Standard_Integer theValuesSize = 12,
const Standard_ShortReal theArrowsLength = 30.0f, const Quantity_Color theGridColor = Quantity_NOC_WHITE,
const Standard_Boolean theToDrawGrid = Standard_True, const Standard_Boolean theToDrawAxes = Standard_True)
: myCubicAxesCallback (NULL),
myNamesFont (theNamesFont),
myNamesStyle (theNamesStyle),
myNamesSize (theNamesSize),
myValuesFont (theValuesFont),
myValuesStyle (theValuesStyle),
myValuesSize (theValuesSize),
myArrowsLength (theArrowsLength),
myGridColor (theGridColor),
myToDrawGrid (theToDrawGrid),
myToDrawAxes (theToDrawAxes),
myAxes(0, 2)
{
myAxes (0) = AxisAspect ("X", Quantity_NOC_RED, Quantity_NOC_RED);
myAxes (1) = AxisAspect ("Y", Quantity_NOC_GREEN, Quantity_NOC_GREEN);
myAxes (2) = AxisAspect ("Z", Quantity_NOC_BLUE1, Quantity_NOC_BLUE1);
}
public:
AxisAspect& ChangeXAxisAspect() { return myAxes(0); }
AxisAspect& ChangeYAxisAspect() { return myAxes(1); }
AxisAspect& ChangeZAxisAspect() { return myAxes(2); }
AxisAspect& ChangeAxisAspect (const Standard_Integer theIndex)
{
Standard_OutOfRange_Raise_if (theIndex < 0 || theIndex > 2, "Graphic3d_GraduatedTrihedron::ChangeAxisAspect: theIndex is out of bounds [0,2].");
return myAxes (theIndex);
}
const AxisAspect& XAxisAspect() const { return myAxes(0); }
const AxisAspect& YAxisAspect() const { return myAxes(1); }
const AxisAspect& ZAxisAspect() const { return myAxes(2); }
const AxisAspect& AxisAspectAt (const Standard_Integer theIndex) const
{
Standard_OutOfRange_Raise_if (theIndex < 0 || theIndex > 2, "Graphic3d_GraduatedTrihedron::AxisAspect: theIndex is out of bounds [0,2].");
return myAxes (theIndex);
}
Standard_ShortReal ArrowsLength() const { return myArrowsLength; }
void SetArrowsLength (const Standard_ShortReal theValue) { myArrowsLength = theValue; }
const Quantity_Color& GridColor() const { return myGridColor; }
void SetGridColor (const Quantity_Color& theColor) {myGridColor = theColor; }
Standard_Boolean ToDrawGrid() const { return myToDrawGrid; }
void SetDrawGrid (const Standard_Boolean theToDraw) { myToDrawGrid = theToDraw; }
Standard_Boolean ToDrawAxes() const { return myToDrawAxes; }
void SetDrawAxes (const Standard_Boolean theToDraw) { myToDrawAxes = theToDraw; }
const TCollection_AsciiString& NamesFont() const { return myNamesFont; }
void SetNamesFont (const TCollection_AsciiString& theFont) { myNamesFont = theFont; }
Font_FontAspect NamesFontAspect() const { return myNamesStyle; }
void SetNamesFontAspect (Font_FontAspect theAspect) { myNamesStyle = theAspect; }
Standard_Integer NamesSize() const { return myNamesSize; }
void SetNamesSize (const Standard_Integer theValue) { myNamesSize = theValue; }
const TCollection_AsciiString& ValuesFont () const { return myValuesFont; }
void SetValuesFont (const TCollection_AsciiString& theFont) { myValuesFont = theFont; }
Font_FontAspect ValuesFontAspect() const { return myValuesStyle; }
void SetValuesFontAspect (Font_FontAspect theAspect) { myValuesStyle = theAspect; }
Standard_Integer ValuesSize() const { return myValuesSize; }
void SetValuesSize (const Standard_Integer theValue) { myValuesSize = theValue; }
Standard_Boolean CubicAxesCallback(Graphic3d_CView* theView) const
{
if (myCubicAxesCallback != NULL)
{
myCubicAxesCallback (theView);
return Standard_True;
}
return Standard_False;
}
void SetCubicAxesCallback (const MinMaxValuesCallback theCallback) { myCubicAxesCallback = theCallback; }
protected:
MinMaxValuesCallback myCubicAxesCallback; //!< Callback function to define boundary box of displayed objects
TCollection_AsciiString myNamesFont; //!< Font name of names of axes: Courier, Arial, ...
Font_FontAspect myNamesStyle; //!< Style of names of axes: OSD_FA_Regular, OSD_FA_Bold,..
Standard_Integer myNamesSize; //!< Size of names of axes: 8, 10,..
protected:
TCollection_AsciiString myValuesFont; //!< Font name of values: Courier, Arial, ...
Font_FontAspect myValuesStyle; //!< Style of values: OSD_FA_Regular, OSD_FA_Bold, ...
Standard_Integer myValuesSize; //!< Size of values: 8, 10, 12, 14, ...
protected:
Standard_ShortReal myArrowsLength;
Quantity_Color myGridColor;
Standard_Boolean myToDrawGrid;
Standard_Boolean myToDrawAxes;
NCollection_Array1<AxisAspect> myAxes; //!< X, Y and Z axes parameters
};
#endif // Graphic3d_GraduatedTrihedron_HeaderFile
| 9,915 | 3,117 |
#include "ffmpeg.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <boost/process.hpp>
#define This StreamingFFMpegEncoder
namespace perceive::movie
{
namespace bp = boost::process;
// ----------------------------------------------------- call ffmpeg to make mp4
//
int call_ffmpeg_to_make_mp4(const string_view input_fnames,
const real frame_duration,
const string_view output_fname) noexcept
{
const string command = format("ffmpeg -y -r {} -i {} -c:v libxvid -qscale:v 2 {} "
"1>/dev/null 2>/dev/null",
(1.0 / frame_duration),
input_fnames,
output_fname);
return system(command.c_str());
}
// -----------------------------------------------------
//
struct This::Pimpl
{
bp::pipe pipe;
bp::child subprocess;
vector<uint8_t> raw;
string output_fname;
int width = 0;
int height = 0;
real frame_rate; //
~Pimpl() { close(); }
void init(const string_view output_fname, int w, int h, real frame_rate)
{
this->output_fname = output_fname;
this->width = w;
this->height = h;
this->frame_rate = frame_rate;
raw.resize(size_t(width * 3)); // rgb
auto find_ffmpeg_exe = [&]() { // attempt to find the ffmpeg executable
const char* exe = "ffmpeg";
const auto path = bp::search_path(exe);
if(path.empty())
throw std::runtime_error(
format("failed to find executable '{}' on path, aborting", exe));
return path;
};
const auto exe_path = find_ffmpeg_exe();
// bp::std_out > stdout,
subprocess = bp::child(exe_path,
"-hide_banner", // really
"-y", // allow overwrite
"-f", // input format
"rawvideo",
"-pix_fmt", // input pixel format
"rgb24",
"-video_size", // input format
format("{}x{}", width, height),
"-r", // framerate
str(frame_rate),
"-i", // input
"-",
"-c:v", // video codec
"libxvid",
"-qscale:v", // quality
"2",
output_fname.data(),
bp::std_out > bp::null,
bp::std_err > bp::null,
bp::std_in < pipe);
}
void push_frame(const cv::Mat& im)
{
if((im.rows != height) || (im.cols != width))
throw std::runtime_error(format("frame shape mismatch"));
if(im.type() == CV_8UC3) {
for(auto y = 0; y < height; ++y) {
const uint8_t* row = im.ptr(y); // BGR format
uint8_t* out = &raw[0];
for(auto x = 0; x < width; ++x) {
uint8_t b = *row++;
uint8_t g = *row++;
uint8_t r = *row++;
*out++ = r;
*out++ = g;
*out++ = b;
}
Expects(out == &raw[0] + raw.size());
pipe.write(reinterpret_cast<char*>(&raw[0]), int(raw.size()));
}
} else if(im.type() == CV_8UC1 || im.type() == CV_8U) {
for(auto y = 0; y < height; ++y) {
const uint8_t* row = im.ptr(y); // gray format
uint8_t* out = &raw[0];
for(auto x = 0; x < width; ++x) {
uint8_t g = *row++;
*out++ = g;
*out++ = g;
*out++ = g;
}
Expects(out == &raw[0] + raw.size());
pipe.write(reinterpret_cast<char*>(&raw[0]), int(raw.size()));
}
} else {
FATAL(format("input movie was in unsupport color space: cv::Mat.type() == {}",
im.type()));
}
}
int close()
{
if(pipe.is_open()) {
pipe.close();
std::error_code ec;
subprocess.wait(ec);
if(ec) {
throw std::runtime_error(
format("error waiting for ffmpeg to end: {}", ec.message()));
}
}
return subprocess.exit_code();
}
};
This::This()
: pimpl_(new Pimpl)
{}
This::~This() = default;
void This::push_frame(const cv::Mat& frame) { pimpl_->push_frame(frame); }
int This::close() { return pimpl_->close(); }
StreamingFFMpegEncoder This::create(const string_view output_fname,
const int width,
const int height,
const real frame_rate)
{
StreamingFFMpegEncoder o;
o.pimpl_->init(output_fname, width, height, frame_rate);
return o;
}
} // namespace perceive::movie
| 5,119 | 1,519 |
#include "GameManager.h"
#include <iostream>
int main(int argc, char* args[])
{
GameManager *ptr = new GameManager();
bool status = ptr->OnCreate();
if (status == true) {
ptr->Run();
}
else if (status == false) {
/// You should have learned about stderr (std::cerr) in Operating Systems
std::cerr << "Fatal error occured. Cannot start this program" << std::endl;
}
delete ptr;
return 0;
} | 405 | 144 |
/*
* VMatrix.cpp
*
* Created on: Feb 15, 2012
* Author: kleinwrt
*/
/** \file
* VMatrix methods.
*
* \author Claus Kleinwort, DESY, 2011 (Claus.Kleinwort@desy.de)
*
* \copyright
* Copyright (c) 2011 - 2016 Deutsches Elektronen-Synchroton,
* Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY \n\n
* 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. \n\n
* 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. \n\n
* You should have received a copy of the GNU Library General Public
* License along with this program (see the file COPYING.LIB for more
* details); if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "Alignment/ReferenceTrajectories/interface/VMatrix.h"
//! Namespace for the general broken lines package
namespace gbl {
/*********** simple Matrix based on std::vector<double> **********/
VMatrix::VMatrix(const unsigned int nRows, const unsigned int nCols) :
numRows(nRows), numCols(nCols), theVec(nRows * nCols)
{
}
VMatrix::VMatrix(const VMatrix &aMatrix) :
numRows(aMatrix.numRows), numCols(aMatrix.numCols), theVec(aMatrix.theVec)
{
}
VMatrix::~VMatrix() {
}
/// Resize Matrix.
/**
* \param [in] nRows Number of rows.
* \param [in] nCols Number of columns.
*/
void VMatrix::resize(const unsigned int nRows, const unsigned int nCols) {
numRows = nRows;
numCols = nCols;
theVec.resize(nRows * nCols);
}
/// Get transposed matrix.
/**
* \return Transposed matrix.
*/
VMatrix VMatrix::transpose() const {
VMatrix aResult(numCols, numRows);
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j < numCols; ++j) {
aResult(j, i) = theVec[numCols * i + j];
}
}
return aResult;
}
/// Get number of rows.
/**
* \return Number of rows.
*/
unsigned int VMatrix::getNumRows() const {
return numRows;
}
/// Get number of columns.
/**
* \return Number of columns.
*/
unsigned int VMatrix::getNumCols() const {
return numCols;
}
/// Print matrix.
void VMatrix::print() const {
std::cout << " VMatrix: " << numRows << "*" << numCols << std::endl;
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j < numCols; ++j) {
if (j % 5 == 0) {
std::cout << std::endl << std::setw(4) << i << ","
<< std::setw(4) << j << "-" << std::setw(4)
<< std::min(j + 4, numCols) << ":";
}
std::cout << std::setw(13) << theVec[numCols * i + j];
}
}
std::cout << std::endl << std::endl;
}
/// Multiplication Matrix*Vector.
VVector VMatrix::operator*(const VVector &aVector) const {
VVector aResult(numRows);
for (unsigned int i = 0; i < this->numRows; ++i) {
double sum = 0.0;
for (unsigned int j = 0; j < this->numCols; ++j) {
sum += theVec[numCols * i + j] * aVector(j);
}
aResult(i) = sum;
}
return aResult;
}
/// Multiplication Matrix*Matrix.
VMatrix VMatrix::operator*(const VMatrix &aMatrix) const {
VMatrix aResult(numRows, aMatrix.numCols);
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j < aMatrix.numCols; ++j) {
double sum = 0.0;
for (unsigned int k = 0; k < numCols; ++k) {
sum += theVec[numCols * i + k] * aMatrix(k, j);
}
aResult(i, j) = sum;
}
}
return aResult;
}
/// Addition Matrix+Matrix.
VMatrix VMatrix::operator+(const VMatrix &aMatrix) const {
VMatrix aResult(numRows, numCols);
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j < numCols; ++j) {
aResult(i, j) = theVec[numCols * i + j] + aMatrix(i, j);
}
}
return aResult;
}
/// Assignment Matrix=Matrix.
VMatrix &VMatrix::operator=(const VMatrix &aMatrix) {
if (this != &aMatrix) { // Gracefully handle self assignment
numRows = aMatrix.getNumRows();
numCols = aMatrix.getNumCols();
theVec.resize(numRows * numCols);
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j < numCols; ++j) {
theVec[numCols * i + j] = aMatrix(i, j);
}
}
}
return *this;
}
/*********** simple symmetric Matrix based on std::vector<double> **********/
VSymMatrix::VSymMatrix(const unsigned int nRows) :
numRows(nRows), theVec((nRows * nRows + nRows) / 2) {
}
VSymMatrix::~VSymMatrix() {
}
/// Resize symmetric matrix.
/**
* \param [in] nRows Number of rows.
*/
void VSymMatrix::resize(const unsigned int nRows) {
numRows = nRows;
theVec.resize((nRows * nRows + nRows) / 2);
}
/// Get number of rows (= number of colums).
/**
* \return Number of rows.
*/
unsigned int VSymMatrix::getNumRows() const {
return numRows;
}
/// Print matrix.
void VSymMatrix::print() const {
std::cout << " VSymMatrix: " << numRows << "*" << numRows << std::endl;
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j <= i; ++j) {
if (j % 5 == 0) {
std::cout << std::endl << std::setw(4) << i << ","
<< std::setw(4) << j << "-" << std::setw(4)
<< std::min(j + 4, i) << ":";
}
std::cout << std::setw(13) << theVec[(i * i + i) / 2 + j];
}
}
std::cout << std::endl << std::endl;
}
/// Subtraction SymMatrix-(sym)Matrix.
VSymMatrix VSymMatrix::operator-(const VMatrix &aMatrix) const {
VSymMatrix aResult(numRows);
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j <= i; ++j) {
aResult(i, j) = theVec[(i * i + i) / 2 + j] - aMatrix(i, j);
}
}
return aResult;
}
/// Multiplication SymMatrix*Vector.
VVector VSymMatrix::operator*(const VVector &aVector) const {
VVector aResult(numRows);
for (unsigned int i = 0; i < numRows; ++i) {
aResult(i) = theVec[(i * i + i) / 2 + i] * aVector(i);
for (unsigned int j = 0; j < i; ++j) {
aResult(j) += theVec[(i * i + i) / 2 + j] * aVector(i);
aResult(i) += theVec[(i * i + i) / 2 + j] * aVector(j);
}
}
return aResult;
}
/// Multiplication SymMatrix*Matrix.
VMatrix VSymMatrix::operator*(const VMatrix &aMatrix) const {
unsigned int nCol = aMatrix.getNumCols();
VMatrix aResult(numRows, nCol);
for (unsigned int l = 0; l < nCol; ++l) {
for (unsigned int i = 0; i < numRows; ++i) {
aResult(i, l) = theVec[(i * i + i) / 2 + i] * aMatrix(i, l);
for (unsigned int j = 0; j < i; ++j) {
aResult(j, l) += theVec[(i * i + i) / 2 + j] * aMatrix(i, l);
aResult(i, l) += theVec[(i * i + i) / 2 + j] * aMatrix(j, l);
}
}
}
return aResult;
}
/*********** simple Vector based on std::vector<double> **********/
VVector::VVector(const unsigned int nRows) :
numRows(nRows), theVec(nRows) {
}
VVector::VVector(const VVector &aVector) :
numRows(aVector.numRows), theVec(aVector.theVec) {
}
VVector::~VVector() {
}
/// Resize vector.
/**
* \param [in] nRows Number of rows.
*/
void VVector::resize(const unsigned int nRows) {
numRows = nRows;
theVec.resize(nRows);
}
/// Get part of vector.
/**
* \param [in] len Length of part.
* \param [in] start Offset of part.
* \return Part of vector.
*/
VVector VVector::getVec(unsigned int len, unsigned int start) const {
VVector aResult(len);
std::memcpy(&aResult.theVec[0], &theVec[start], sizeof(double) * len);
return aResult;
}
/// Put part of vector.
/**
* \param [in] aVector Vector with part.
* \param [in] start Offset of part.
*/
void VVector::putVec(const VVector &aVector, unsigned int start) {
std::memcpy(&theVec[start], &aVector.theVec[0],
sizeof(double) * aVector.numRows);
}
/// Get number of rows.
/**
* \return Number of rows.
*/
unsigned int VVector::getNumRows() const {
return numRows;
}
/// Print vector.
void VVector::print() const {
std::cout << " VVector: " << numRows << std::endl;
for (unsigned int i = 0; i < numRows; ++i) {
if (i % 5 == 0) {
std::cout << std::endl << std::setw(4) << i << "-" << std::setw(4)
<< std::min(i + 4, numRows) << ":";
}
std::cout << std::setw(13) << theVec[i];
}
std::cout << std::endl << std::endl;
}
/// Subtraction Vector-Vector.
VVector VVector::operator-(const VVector &aVector) const {
VVector aResult(numRows);
for (unsigned int i = 0; i < numRows; ++i) {
aResult(i) = theVec[i] - aVector(i);
}
return aResult;
}
/// Assignment Vector=Vector.
VVector &VVector::operator=(const VVector &aVector) {
if (this != &aVector) { // Gracefully handle self assignment
numRows = aVector.getNumRows();
theVec.resize(numRows);
for (unsigned int i = 0; i < numRows; ++i) {
theVec[i] = aVector(i);
}
}
return *this;
}
/*============================================================================
from mpnum.F (MillePede-II by V. Blobel, Univ. Hamburg)
============================================================================*/
/// Matrix inversion.
/**
* Invert symmetric N-by-N matrix V in symmetric storage mode
* V(1) = V11, V(2) = V12, V(3) = V22, V(4) = V13, . . .
* replaced by inverse matrix
*
* Method of solution is by elimination selecting the pivot on the
* diagonal each stage. The rank of the matrix is returned in NRANK.
* For NRANK ne N, all remaining rows and cols of the resulting
* matrix V are set to zero.
* \exception 1 : matrix is singular.
* \return Rank of matrix.
*/
unsigned int VSymMatrix::invert() {
const double eps = 1.0E-10;
unsigned int aSize = numRows;
std::vector<int> next(aSize);
std::vector<double> diag(aSize);
int nSize = aSize;
int first = 1;
for (int i = 1; i <= nSize; ++i) {
next[i - 1] = i + 1; // set "next" pointer
diag[i - 1] = fabs(theVec[(i * i + i) / 2 - 1]); // save abs of diagonal elements
}
next[aSize - 1] = -1; // end flag
unsigned int nrank = 0;
for (int i = 1; i <= nSize; ++i) { // start of loop
int k = 0;
double vkk = 0.0;
int j = first;
int previous = 0;
int last = previous;
// look for pivot
while (j > 0) {
int jj = (j * j + j) / 2 - 1;
if (fabs(theVec[jj]) > std::max(fabs(vkk), eps * diag[j - 1])) {
vkk = theVec[jj];
k = j;
last = previous;
}
previous = j;
j = next[j - 1];
}
// pivot found
if (k > 0) {
int kk = (k * k + k) / 2 - 1;
if (last <= 0) {
first = next[k - 1];
} else {
next[last - 1] = next[k - 1];
}
next[k - 1] = 0; // index is used, reset
nrank++; // increase rank and ...
vkk = 1.0 / vkk;
theVec[kk] = -vkk;
int jk = kk - k;
int jl = -1;
for (int j = 1; j <= nSize; ++j) { // elimination
if (j == k) {
jk = kk;
jl += j;
} else {
if (j < k) {
++jk;
} else {
jk += j - 1;
}
double vjk = theVec[jk];
theVec[jk] = vkk * vjk;
int lk = kk - k;
if (j >= k) {
for (int l = 1; l <= k - 1; ++l) {
++jl;
++lk;
theVec[jl] -= theVec[lk] * vjk;
}
++jl;
lk = kk;
for (int l = k + 1; l <= j; ++l) {
++jl;
lk += l - 1;
theVec[jl] -= theVec[lk] * vjk;
}
} else {
for (int l = 1; l <= j; ++l) {
++jl;
++lk;
theVec[jl] -= theVec[lk] * vjk;
}
}
}
}
} else {
for (int k = 1; k <= nSize; ++k) {
if (next[k - 1] >= 0) {
int kk = (k * k - k) / 2 - 1;
for (int j = 1; j <= nSize; ++j) {
if (next[j - 1] >= 0) {
theVec[kk + j] = 0.0; // clear matrix row/col
}
}
}
}
throw 1; // singular
}
}
for (int ij = 0; ij < (nSize * nSize + nSize) / 2; ++ij) {
theVec[ij] = -theVec[ij]; // finally reverse sign of all matrix elements
}
return nrank;
}
}
| 13,157 | 4,775 |
/*
* Thread Implementation
* Copyright(C) 2003-2013 Jinhao(cnjinhao@hotmail.com)
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* @file: nana/threads/thread.hpp
*/
#ifndef NANA_THREADS_THREAD_HPP
#define NANA_THREADS_THREAD_HPP
#include <map>
#include "mutex.hpp"
#include "../exceptions.hpp"
#include "../traits.hpp"
#include <nana/functor.hpp>
namespace nana
{
namespace threads
{
class thread;
namespace detail
{
struct thread_object_impl;
class thread_holder
{
public:
void insert(unsigned tid, thread* obj);
thread* get(unsigned tid);
void remove(unsigned tid);
private:
threads::recursive_mutex mutex_;
std::map<unsigned, thread*> map_;
};
}//end namespace detail
class thread
:nana::noncopyable
{
typedef thread self_type;
public:
thread();
~thread();
template<typename Functor>
void start(const Functor& f)
{
close();
_m_start_thread(f);
}
template<typename Object, typename Concept>
void start(Object& obj, void (Concept::*memf)())
{
close();
_m_start_thread(nana::functor<void()>(obj, memf));
}
bool empty() const;
unsigned tid() const;
void close();
static void check_break(int retval);
private:
void _m_start_thread(const nana::functor<void()>& f);
private:
void _m_add_tholder();
unsigned _m_thread_routine();
private:
detail::thread_object_impl* impl_;
static detail::thread_holder tholder;
};
}//end namespace threads
}//end namespace nana
#endif
| 1,636 | 699 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "ClientQueryOptions.h"
namespace blink {
ClientQueryOptions::ClientQueryOptions()
{
setIncludeUncontrolled(false);
setType(String("window"));
}
DEFINE_TRACE(ClientQueryOptions)
{
}
} // namespace blink
| 488 | 161 |
#ifndef STAN_LANG_AST_FUN_IS_SPACE_DEF_HPP
#define STAN_LANG_AST_FUN_IS_SPACE_DEF_HPP
#include <stan/lang/ast/fun/is_space.hpp>
namespace stan {
namespace lang {
bool is_space(char c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t';
}
}
}
#endif
| 277 | 127 |
/*
* PVPFile.hpp
*
* Created on: Jun 4, 2014
* Author: pschultz
*
* The goal of the PVPFile class is to encapsulate all interaction with
* PVPFiles---opening and closing, reading and writing, gathering and
* scattering---into a form where, even in the MPI context, all processes
* call the same public methods at the same time.
*
* All interaction with a PVP file from outside this class should use
* this class to work with the file.
*/
#ifndef PVPFILE_HPP_
#define PVPFILE_HPP_
#include <assert.h>
#include <sys/stat.h>
#include "../columns/InterColComm.hpp"
#include "fileio.hpp"
#include "io.h"
#define PVPFILE_SIZEOF_INT 4
#define PVPFILE_SIZEOF_LONG 8
#define PVPFILE_SIZEOF_SHORT 2
#define PVPFILE_SIZEOF_DOUBLE 8
#define PVPFILE_SIZEOF_FLOAT 4
enum PVPFileMode { PVPFILE_READ, PVPFILE_WRITE, PVPFILE_WRITE_READBACK, PVPFILE_APPEND };
namespace PV {
class PVPFile {
// Member functions
public:
PVPFile(const char * path, enum PVPFileMode mode, int pvpfileType, InterColComm * icComm);
int rank() { return icComm->commRank(); }
int rootProc() { return 0; }
bool isRoot() { return rank()==rootProc(); }
~PVPFile();
protected:
PVPFile();
int initialize(const char * path, enum PVPFileMode mode, int pvpfileType, InterColComm * icComm);
int initfile(const char * path, enum PVPFileMode mode, InterColComm * icComm);
private:
int initialize_base();
// Member variables
private:
int PVPFileType;
enum PVPFileMode mode;
int numFrames;
int currentFrame;
InterColComm * icComm;
int * header;
double headertime;
PV_Stream * stream;
};
} /* namespace PV */
#endif /* PVPFILE_HPP_ */
| 1,671 | 591 |
#include "Texture.h"
#include <SOIL/SOIL.h>
#include "common.h"
#include "debug.h"
#include "util.h"
namespace prb {
void Texture::defInit(unsigned char* data) {
D3D11_TEXTURE2D_DESC tdesc;
// ...
// Fill out width, height, mip levels, format, etc...
// ...
tdesc.Width = width;
tdesc.Height = height;
tdesc.MipLevels = 1;
tdesc.SampleDesc.Count = 1; //how many textures
tdesc.SampleDesc.Quality = 0;
tdesc.ArraySize = 1; //number of textures
tdesc.Format = format;
tdesc.Usage = D3D11_USAGE_DYNAMIC;
tdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; // Add D3D11_BIND_RENDER_TARGET if you want to go
// with the auto-generate mips route.
tdesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
tdesc.MiscFlags = 0; // or D3D11_RESOURCE_MISC_GENERATE_MIPS for auto-mip gen.
D3D11_SUBRESOURCE_DATA srd; // (or an array of these if you have more than one mip level)
srd.pSysMem = data; // This data should be in raw pixel format
srd.SysMemPitch = linesize != 0 && linesize != width ? linesize : tdesc.Width * 4; // Sometimes pixel rows may be padded so this might not be as simple as width * pixel_size_in_bytes.
srd.SysMemSlicePitch = 0; // tdesc.Width* tdesc.Height * 4;
ThrowIfFailed(dev->CreateTexture2D(&tdesc, &srd, &texture));
D3D11_SHADER_RESOURCE_VIEW_DESC srDesc;
srDesc.Format = format;
srDesc.ViewDimension = viewDimension; //D3D11_SRV_DIMENSION_TEXTURE2D;
srDesc.Texture2D.MostDetailedMip = 0;
srDesc.Texture2D.MostDetailedMip = 0;
srDesc.Texture2D.MipLevels = 1;
ThrowIfFailed(dev->CreateShaderResourceView(texture, &srDesc, &resView));
//devcon->GenerateMips(resView);
D3D11_SAMPLER_DESC samplerDesc;
// Create a texture sampler state description.
//samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
//samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
samplerDesc.Filter = filtering;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
// Create the texture sampler state.
ThrowIfFailed(dev->CreateSamplerState(&samplerDesc, &sampler));
}
void Texture::init(unsigned char* data, vec2 size) {
this->width = size.x;
this->height = size.y;
defInit(data);
}
Texture::Texture() {}
Texture::Texture(std::wstring const& path) {
std::wstring ppath = strup::fallbackPath(path);
this->path = ppath;
unsigned char* data = SOIL_load_image(deb::toutf8(ppath).c_str(), &width, &height, &channels, SOIL_LOAD_RGBA);
if (data) defInit(data);
else deb::pr("could not load texture '", ppath, "'\n('", deb::toutf8(ppath).c_str(),"')\n");
delete[] data;
}
Texture::Texture(std::string const& path) : Texture(deb::tos(path)) {}
Texture::Texture(unsigned char* data, vec2 size) {
this->width = size.x;
this->height = size.y;
defInit(data);
}
Texture::Texture(unsigned char* data, vec2 size, int linesize) {
if (linesize == width) linesize *= 4;
this->width = size.x;
this->height = size.y;
this->linesize = linesize;
defInit(data);
//TODO right now the texture is uploaded twice in this constructor
D3D11_MAPPED_SUBRESOURCE mappedResource;
ThrowIfFailed(devcon->Map(texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));
unsigned char* tdata = data;
BYTE* mappedData = reinterpret_cast<BYTE*>(mappedResource.pData);
for (UINT i = 0; i < height; i++)
{
memcpy(mappedData, tdata, linesize);
mappedData += mappedResource.RowPitch;
tdata += linesize;
}
devcon->Unmap(texture, 0);
}
Texture::Texture(vec2 size) {
this->linesize = size.x;
unsigned char* sData = new unsigned char[size.x * size.y * 4];
memset(sData, 0, size.x * size.y * 4);
init(sData, size);
delete[] sData;
}
Texture::Texture(vec2 size, int linesize, DXGI_FORMAT format, D3D_SRV_DIMENSION viewDimension) {
if (linesize == (int)size.x) linesize *= 4;
this->linesize = size.x;
this->format = format;
this->viewDimension = viewDimension;
unsigned char* sData = new unsigned char[linesize * size.y];
memset(sData, 0, linesize * size.y);
init(sData, size);
delete[] sData;
}
Texture::Texture(vec2 size, int linesize) : Texture(size, linesize, DXGI_FORMAT_R8G8B8A8_UNORM, D3D11_SRV_DIMENSION_TEXTURE2D) {}
bool Texture::operator==(Texture const& ot) const {
return this->texture == ot.texture &&
this->resView == ot.resView &&
this->sampler == ot.sampler &&
this->width == ot.width &&
this->height == ot.height &&
this->channels == ot.channels &&
this->linesize == ot.linesize;
}
bool Texture::operator!=(Texture const& ot) const { return !(*this == ot); }
bool Texture::null() const { return !texture || !resView || !sampler; }
vec2 Texture::getSize() const { return { (float)width, (float)height }; }
vec2 Texture::size() const { return getSize(); }
void Texture::setData(unsigned char* data, vec2 size, int linesize) {
if (linesize == width) linesize *= 4;
this->width = size.x;
this->height = size.y;
this->linesize = linesize;
D3D11_MAPPED_SUBRESOURCE mappedResource;
ThrowIfFailed(devcon->Map(texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));
unsigned char* tdata = data;
BYTE* mappedData = reinterpret_cast<BYTE*>(mappedResource.pData);
for (UINT i = 0; i < height; i++)
{
memcpy(mappedData, tdata, linesize);
mappedData += mappedResource.RowPitch;
tdata += linesize;
}
devcon->Unmap(texture, 0);
}
void Texture::setData(unsigned char* data, vec2 size) {
this->width = size.x;
this->height = size.y;
D3D11_MAPPED_SUBRESOURCE mappedResource;
ThrowIfFailed(devcon->Map(texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));
memcpy(mappedResource.pData, data, height * width * 4);
devcon->Unmap(texture, 0);
}
void Texture::setData(vec4 data) {
if (width <= 0 || height <= 0) return;
//data.clamp(0.f, 1.f);
unsigned char* ndata = new unsigned char[this->width * this->height * 4];
for(int i=0; i< this->width * this->height * 4; i+=4){
ndata[i + 0] = (unsigned char)(data.x*255.f);
ndata[i + 1] = (unsigned char)(data.y*255.f);
ndata[i + 2] = (unsigned char)(data.z*255.f);
ndata[i + 3] = (unsigned char)(data.w*255.f);
}
setData(ndata, vec2(width, height));
delete[] ndata;
}
D3D11_FILTER Texture::getFromFiltering(TEXTURE_FILTERING min, TEXTURE_FILTERING mag, TEXTURE_FILTERING mip) const {
return prb::getFromFiltering(min, mag, mip);
}
void Texture::calcMinMagMip(D3D11_FILTER filter) {
std::tuple<TEXTURE_FILTERING, TEXTURE_FILTERING, TEXTURE_FILTERING> ret = prb::calcMinMagMip(filter);
min = std::get<0>(ret); mag = std::get<1>(ret); mip = std::get<2>(ret);
}
void Texture::setFiltering(D3D11_FILTER filter) {
this->filtering = filter;
if (!texture || !resView || !sampler) return;
calcMinMagMip(filter);
if (sampler) { sampler->Release(); sampler = NULL; }
D3D11_SAMPLER_DESC samplerDesc;
samplerDesc.Filter = filtering;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
// Create the texture sampler state.
ThrowIfFailed(dev->CreateSamplerState(&samplerDesc, &sampler));
}
void Texture::setFiltering(TEXTURE_FILTERING min, TEXTURE_FILTERING mag, TEXTURE_FILTERING mip) { this->min = min; this->mag = mag; this->mip = mip; setFiltering(getFromFiltering(min, mag, mip)); }
void Texture::setFiltering(TEXTURE_FILTERING min, TEXTURE_FILTERING mag) { this->min = min; this->mag = mag; mip = mag; setFiltering(getFromFiltering(min, mag, mip)); }
void Texture::setFiltering(TEXTURE_FILTERING filter) { min = mag = mip = filter; setFiltering(getFromFiltering(min, mag, mip)); }
void Texture::drawImmediate(std::vector<float> const& verts) const {
util::drawTexture(*this, verts);
}
void Texture::drawImmediate(vec2 pos, vec2 size) const {
vec2 start = pos, end = pos + size;
std::vector<float> verts = { //clockwise order
start.x,start.y, 1.f,1.f,1.f,1.f, 0.f,1.f,
start.x,end.y, 1.f,1.f,1.f,1.f, 0.f,0.f,
end.x,end.y, 1.f,1.f,1.f,1.f, 1.f,0.f,
end.x,end.y, 1.f,1.f,1.f,1.f, 1.f,0.f,
end.x,start.y, 1.f,1.f,1.f,1.f, 1.f,1.f,
start.x,start.y, 1.f,1.f,1.f,1.f, 0.f,1.f,
};
drawImmediate(verts);
}
void Texture::bind() const {
devcon->PSSetShaderResources(0, 1, &resView);
devcon->PSSetSamplers(0, 1, &sampler);
}
void Texture::dispose() {
if(resView) resView->Release();
if(texture) texture->Release();
if(sampler) sampler->Release();
}
}
///////////////////////////////////////
//OLD DRAWTEXTURE
////create a temporary vertex buffer
//ID3D11Buffer* tempVBuffer = NULL;
//// create the vertex buffer
//D3D11_BUFFER_DESC bd;
//ZeroMemory(&bd, sizeof(bd));
//bd.Usage = D3D11_USAGE_DYNAMIC; // write access access by CPU and GPU
//bd.ByteWidth = sizeof(float) * verts.size(); // size is the VERTEX struct * 3
//bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // use as a vertex buffer
//bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // allow CPU to write in buffer
//dev->CreateBuffer(&bd, NULL, &tempVBuffer); // create the buffer
//// copy the vertices into the buffer
//D3D11_MAPPED_SUBRESOURCE ms;
//devcon->Map(tempVBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms);
//memcpy(ms.pData, &verts[0], sizeof(float) * verts.size());
//devcon->Unmap(tempVBuffer, NULL);
//devcon->PSSetShaderResources(0, 1, &resView);
//devcon->PSSetSamplers(0, 1, &sampler);
//// select which vertex buffer to display
//UINT stride = sizeof(float) * 2 + sizeof(float) * 4 + sizeof(float) * 2;
//UINT offset = 0;
//devcon->IASetVertexBuffers(0, 1, &tempVBuffer, &stride, &offset);
//// select which primtive type we are using
//devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
//// draw the vertex buffer to the back buffer
//devcon->Draw(6, 0);
////release the temporary buffer
//tempVBuffer->Release(); | 12,129 | 4,460 |
#include "Grid.h"
#include "DrawTarget.h"
namespace blocks {
void Grid::computeLine(const sb::Vector2f& start, const sb::Vector2f& end) {
Line line(_thickness, _color);
line.addPoint(start);
line.addPoint(end);
_vertices.insert(_vertices.end(), line.getVertices().begin(), line.getVertices().end());
}
void Grid::computeVerticalLines() {
sb::Vector2f size = getSize();
sb::Vector2f halfSize = 0.5f * size;
float delta = size.x / _gridSize.x;
for (int i = 0; i <= _gridSize.x; i++) {
sb::Vector2f start(i * delta - halfSize.x, -halfSize.y);
sb::Vector2f end(i * delta - halfSize.x, +halfSize.y);
computeLine(start, end);
}
}
void Grid::computeHorizontalLines() {
sb::Vector2f size = getSize();
sb::Vector2f halfSize = 0.5f * size;
float delta = size.y / _gridSize.y;
for (int i = 0; i <= _gridSize.y; i++) {
sb::Vector2f start(-halfSize.x, i * delta - halfSize.y);
sb::Vector2f end(+halfSize.x, i * delta - halfSize.y);
computeLine(start, end);
}
}
void Grid::computeLines() {
_vertices.clear();
sb::Vector2f delta(1.f / _gridSize.x, 1.f / _gridSize.y);
computeVerticalLines();
computeHorizontalLines();
}
Grid::Grid(sb::Vector2i gridSize, float thickness, const sb::Color& color)
: _gridSize(gridSize), _thickness(thickness), _color(color)
{
computeLines();
}
void Grid::draw(sb::DrawTarget& target, sb::DrawStates states) {
states.transform *= getTransform();
target.draw(_vertices, sb::PrimitiveType::TriangleStrip, states);
}
}
| 1,566 | 616 |
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "ExportTasks.h"
#include <U2Core/DocumentModel.h>
#include <U2Core/IOAdapter.h>
#include <U2Core/IOAdapterUtils.h>
#include <U2Core/AppContext.h>
#include <U2Core/DNATranslation.h>
#include <U2Core/DNATranslationImpl.h>
#include <U2Core/Counter.h>
#include <U2Core/DNAChromatogramObject.h>
#include <U2Core/GObjectRelationRoles.h>
#include <U2Core/LoadDocumentTask.h>
#include <U2Core/AddDocumentTask.h>
#include <U2Core/MSAUtils.h>
#include <U2Core/TextUtils.h>
#include <U2Core/ProjectModel.h>
#include <U2Core/MAlignmentObject.h>
#include <U2Core/U2SafePoints.h>
#include <U2Core/U2SequenceUtils.h>
#include <U2Formats/SCFFormat.h>
#include <U2Gui/OpenViewTask.h>
namespace U2 {
//////////////////////////////////////////////////////////////////////////
// AddDocumentAndOpenViewTask
AddExportedDocumentAndOpenViewTask::AddExportedDocumentAndOpenViewTask(DocumentProviderTask* t)
: Task("Export sequence to document", TaskFlags_NR_FOSCOE)
{
exportTask = t;
addSubTask(exportTask);
}
QList<Task*> AddExportedDocumentAndOpenViewTask::onSubTaskFinished( Task* subTask ) {
QList<Task*> subTasks;
if (subTask == exportTask && !subTask->hasError()) {
Document* doc = exportTask->getDocument();
const GUrl& fullPath = doc->getURL();
Project* prj = AppContext::getProject();
if (prj) {
Document* sameURLdoc = prj->findDocumentByURL(fullPath);
if (sameURLdoc) {
taskLog.trace(tr("Document is already added to the project %1").arg(doc->getURL().getURLString()));
subTasks << new LoadUnloadedDocumentAndOpenViewTask(sameURLdoc);
return subTasks;
}
}
exportTask->takeDocument();
subTasks << new AddDocumentTask(doc);
subTasks << new LoadUnloadedDocumentAndOpenViewTask(doc);
}
//TODO: provide a report if subtask fails
return subTasks;
}
//////////////////////////////////////////////////////////////////////////
// DNAExportAlignmentTask
ExportAlignmentTask::ExportAlignmentTask(const MAlignment& _ma, const QString& _fileName, DocumentFormatId _f)
: DocumentProviderTask("", TaskFlag_None), ma(_ma), fileName(_fileName), format(_f)
{
GCOUNTER( cvar, tvar, "ExportAlignmentTask" );
setTaskName(tr("Export alignment to '%1'").arg(QFileInfo(fileName).fileName()));
setVerboseLogMode(true);
assert(!ma.isEmpty());
}
void ExportAlignmentTask::run() {
DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry();
DocumentFormat* f = r->getFormatById(format);
IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(IOAdapterUtils::url2io(fileName));
resultDocument = f->createNewLoadedDocument(iof, fileName, stateInfo);
CHECK_OP(stateInfo, );
resultDocument->addObject(new MAlignmentObject(ma));
f->storeDocument(resultDocument, stateInfo);
}
//////////////////////////////////////////////////////////////////////////
// export alignment 2 sequence format
ExportMSA2SequencesTask::ExportMSA2SequencesTask(const MAlignment& _ma, const QString& _url, bool _trimAli, DocumentFormatId _format)
: DocumentProviderTask(tr("Export alignment to sequence: %1").arg(_url), TaskFlag_None),
ma(_ma), url(_url), trimAli(_trimAli), format(_format)
{
GCOUNTER( cvar, tvar, "ExportMSA2SequencesTask");
setVerboseLogMode(true);
}
void ExportMSA2SequencesTask::run() {
DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry();
DocumentFormat* f = r->getFormatById(format);
IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(IOAdapterUtils::url2io(url));
resultDocument = f->createNewLoadedDocument(iof, url, stateInfo);
CHECK_OP(stateInfo, );
QList<DNASequence> lst = MSAUtils::ma2seq(ma, trimAli);
QSet<QString> usedNames;
foreach(DNASequence s, lst) {
QString name = s.getName();
if (usedNames.contains(name)) {
name = TextUtils::variate(name, " ", usedNames, false, 1);
s.setName(name);
}
U2EntityRef seqRef = U2SequenceUtils::import(resultDocument->getDbiRef(), s, stateInfo);
CHECK_OP(stateInfo, );
resultDocument->addObject(new U2SequenceObject(name, seqRef));
usedNames.insert(name);
}
f->storeDocument(resultDocument, stateInfo);
}
//////////////////////////////////////////////////////////////////////////
// export nucleic alignment 2 amino alignment
ExportMSA2MSATask::ExportMSA2MSATask(const MAlignment& _ma, int _offset, int _len, const QString& _url,
const QList<DNATranslation*>& _aminoTranslations, DocumentFormatId _format)
: DocumentProviderTask(tr("Export alignment to alignment: %1").arg(_url), TaskFlag_None),
ma(_ma), offset(_offset), len(_len), url(_url), format(_format), aminoTranslations(_aminoTranslations)
{
GCOUNTER( cvar, tvar, "ExportMSA2MSATask" );
setVerboseLogMode(true);
}
void ExportMSA2MSATask::run() {
DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry();
DocumentFormat* f = r->getFormatById(format);
IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(IOAdapterUtils::url2io(url));
resultDocument = f->createNewLoadedDocument(iof, url, stateInfo);
CHECK_OP(stateInfo, );
QList<DNASequence> lst = MSAUtils::ma2seq(ma, true);
QList<DNASequence> seqList;
for (int i = offset; i < offset + len; i++) {
DNASequence& s = lst[i];
QString name = s.getName();
if (!aminoTranslations.isEmpty()) {
DNATranslation* aminoTT = aminoTranslations.first();
name += "(translated)";
QByteArray seq = s.seq;
int len = seq.length() / 3;
QByteArray resseq(len, '\0');
if (resseq.isNull() && len != 0) {
stateInfo.setError( tr("Out of memory") );
return;
}
assert(aminoTT->isThree2One());
aminoTT->translate(seq.constData(), seq.length(), resseq.data(), resseq.length());
resseq.replace("*","X");
DNASequence rs(name, resseq, aminoTT->getDstAlphabet());
seqList << rs;
} else {
seqList << s;
}
}
MAlignment ma = MSAUtils::seq2ma(seqList, stateInfo);
CHECK_OP(stateInfo, );
resultDocument->addObject(new MAlignmentObject(ma));
f->storeDocument(resultDocument, stateInfo);
}
//////////////////////////////////////////////////////////////////////////
// export chromatogram to SCF
ExportDNAChromatogramTask::ExportDNAChromatogramTask( DNAChromatogramObject* _obj, const ExportChromatogramTaskSettings& _settings)
: DocumentProviderTask(tr("Export chromatogram to SCF"), TaskFlags_NR_FOSCOE),
cObj(_obj), settings(_settings), loadTask(NULL)
{
GCOUNTER( cvar, tvar, "ExportDNAChromatogramTask" );
setVerboseLogMode(true);
}
void ExportDNAChromatogramTask::prepare() {
Document* d = cObj->getDocument();
assert(d != NULL);
if (d == NULL ) {
stateInfo.setError("Chromatogram object document is not found!");
return;
}
QList<GObjectRelation> relatedObjs = cObj->findRelatedObjectsByRole(GObjectRelationRole::SEQUENCE);
assert(relatedObjs.count() == 1);
if (relatedObjs.count() != 1) {
stateInfo.setError("Sequence related to chromatogram is not found!");
}
QString seqObjName = relatedObjs.first().ref.objName;
GObject* resObj = d->findGObjectByName(seqObjName);
U2SequenceObject * sObj = qobject_cast<U2SequenceObject*>(resObj);
assert(sObj != NULL);
DNAChromatogram cd = cObj->getChromatogram();
QByteArray seq = sObj->getWholeSequenceData();
if (settings.reverse) {
TextUtils::reverse(seq.data(), seq.length());
reverseVector(cd.A);
reverseVector(cd.C);
reverseVector(cd.G);
reverseVector(cd.T);
int offset = 0;
if (cObj->getDocument()->getDocumentFormatId() == BaseDocumentFormats::ABIF) {
int baseNum = cd.baseCalls.count();
int seqLen = cd.seqLength;
// this is required for base <-> peak correspondence
if (baseNum > seqLen) {
cd.baseCalls.remove(baseNum - 1);
cd.prob_A.remove(baseNum - 1);
cd.prob_C.remove(baseNum - 1);
cd.prob_G.remove(baseNum - 1);
cd.prob_T.remove(baseNum - 1);
}
} else if (cObj->getDocument()->getDocumentFormatId() == BaseDocumentFormats::SCF) {
// SCF format particularities
offset = -1;
}
for (int i = 0; i < cd.seqLength; ++i) {
cd.baseCalls[i] = cd.traceLength - cd.baseCalls[i] + offset;
}
reverseVector(cd.baseCalls);
reverseVector(cd.prob_A);
reverseVector(cd.prob_C);
reverseVector(cd.prob_G);
reverseVector(cd.prob_T);
}
if (settings.complement) {
DNATranslation* tr = AppContext::getDNATranslationRegistry()->lookupTranslation(BaseDNATranslationIds::NUCL_DNA_DEFAULT_COMPLEMENT);
tr->translate(seq.data(), seq.length());
qSwap(cd.A,cd.T);
qSwap(cd.C, cd.G);
qSwap(cd.prob_A, cd.prob_T);
qSwap(cd.prob_C, cd.prob_G);
}
SCFFormat::exportDocumentToSCF(settings.url, cd, seq, stateInfo);
CHECK_OP(stateInfo, );
if (settings.loadDocument) {
IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE);
loadTask = new LoadDocumentTask(BaseDocumentFormats::SCF, settings.url, iof );
addSubTask( loadTask );
}
}
QList<Task*> ExportDNAChromatogramTask::onSubTaskFinished(Task* subTask) {
if (subTask == loadTask) {
resultDocument = loadTask->takeDocument();
}
return QList<Task*>();
}
}//namespace
| 10,794 | 3,392 |
/* Copyright 2020 Alexey Chernov <4ernov@gmail.com>
*
* 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 "../onnx_importer.h"
#include <cassert>
#include <nncase/ir/graph.h>
#include <nncase/ir/ops/binary.h>
#include <nncase/ir/ops/constant.h>
#include <nncase/ir/ops/reduce.h>
#include <nncase/ir/ops/unary.h>
using namespace nncase;
using namespace nncase::importer;
using namespace nncase::ir;
using namespace onnx;
void onnx_importer::convert_op_LpNormalization(const NodeProto &node)
{
const auto &op_name { generate_name(node) };
const auto &input = node.input()[0];
const auto &output = node.output()[0];
const auto &input_shape = get_shape(input);
axis_t reduce_axis { static_cast<int>(real_axis(get_attribute<int>(node, "axis").value(), input_shape.size())) };
const auto p = get_attribute<int>(node, "p").value();
assert(p >= 1 && p <= 2);
switch (p)
{
case 1:
{
auto abs = graph_.emplace<unary>(unary_abs, input_shape);
abs->name(op_name + ".abs(L1Normalization)");
auto sum = graph_.emplace<reduce>(reduce_sum, abs->output().shape(), reduce_axis, 0.f, true);
sum->name(op_name + ".reduce_sum(L1Normalization)");
auto div = graph_.emplace<binary>(binary_div, input_shape, sum->output().shape(), value_range<float>::full());
div->name(op_name + ".div(L1Normalization)");
sum->input().connect(abs->output());
div->input_b().connect(sum->output());
input_tensors_.emplace(&abs->input(), input);
input_tensors_.emplace(&div->input_a(), input);
output_tensors_.emplace(output, &div->output());
break;
}
case 2:
{
auto square = graph_.emplace<unary>(unary_square, input_shape);
square->name(op_name + ".square(L2Normalization)");
auto sum = graph_.emplace<reduce>(reduce_sum, square->output().shape(), reduce_axis, 0.f, true);
sum->name(op_name + ".reduce_sum(L2Normalization)");
auto epsilon = graph_.emplace<constant>(1e-10f);
epsilon->name(op_name + ".eps(L2Normalization)");
auto max = graph_.emplace<binary>(binary_max, sum->output().shape(), epsilon->output().shape(), value_range<float>::full());
max->name(op_name + ".stab(L2Normalization)");
auto sqrt = graph_.emplace<unary>(unary_sqrt, max->output().shape());
sqrt->name(op_name + ".sqrt(L2Normalization)");
auto div = graph_.emplace<binary>(binary_div, input_shape, sqrt->output().shape(), value_range<float>::full());
div->name(op_name + ".div(L2Normalization)");
sum->input().connect(square->output());
max->input_a().connect(sum->output());
max->input_b().connect(epsilon->output());
sqrt->input().connect(max->output());
div->input_b().connect(sqrt->output());
input_tensors_.emplace(&square->input(), input);
input_tensors_.emplace(&div->input_a(), input);
output_tensors_.emplace(output, &div->output());
break;
}
default:
{
break;
}
}
}
| 3,589 | 1,175 |
//
// Test Object which contains:
// - Two errors to be found by clang-tidy.
// - Test coverage for all lines except the ones marked with 'no coverage'.
//
int called_always() {
#ifdef _DEBUG
const char sz[] = "Debug"; // testing: deliberate error for clang-tidy
#else
const char sz[] = "Release"; // testing: deliberate error for clang-tidy
#endif
return sz[0];
}
int called_optional() { // testing: no coverage
return 1; // testing: no coverage
} // testing: no coverage
int main(int argc, char**) {
int result = called_always() == 'Z' ? 1 : 0;
if (argc > 1) {
result += called_optional(); // testing: no coverage
}
return result;
}
| 716 | 221 |
// Copyright 2021 The BladeDISC Authors. 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 "mlir/mhlo/builder/batch_norm.h"
#include "mlir-hlo/Dialect/mhlo/IR/chlo_ops.h"
#include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "mlir/mhlo/builder/mlir_attr_utils.h"
namespace mlir {
namespace mhlo {
mlir::Value BuildBatchNormInference(
mlir::OpBuilder& builder, const mlir::Location& loc,
const mlir::Value& input, const mlir::Value& scale,
const mlir::Value& offset, const mlir::Value& mean,
const mlir::Value& variance, float eps, mlir_dim_t feature_index) {
mlir::FloatAttr eps_attr = builder.getF32FloatAttr(eps);
mlir::IntegerAttr feature_index_attr =
builder.getI64IntegerAttr(feature_index);
auto bn_op = builder.create<mlir::mhlo::BatchNormInferenceOp>(
loc, input.getType(), input, scale, offset, mean, variance, eps_attr,
feature_index_attr);
return bn_op.getResult();
}
} // namespace mhlo
} // namespace mlir
| 1,495 | 522 |
// Copyright (c) 2012 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 "ppapi/proxy/ppb_flash_menu_proxy.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/private/ppb_flash_menu.h"
#include "ppapi/proxy/enter_proxy.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/tracked_callback.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_flash_menu_api.h"
#include "ppapi/thunk/resource_creation_api.h"
using ppapi::thunk::PPB_Flash_Menu_API;
using ppapi::thunk::ResourceCreationAPI;
namespace ppapi {
namespace proxy {
class FlashMenu : public PPB_Flash_Menu_API, public Resource {
public:
explicit FlashMenu(const HostResource& resource);
virtual ~FlashMenu();
// Resource overrides.
virtual PPB_Flash_Menu_API* AsPPB_Flash_Menu_API() OVERRIDE;
// PPB_Flash_Menu_API implementation.
virtual int32_t Show(const PP_Point* location,
int32_t* selected_id,
scoped_refptr<TrackedCallback> callback) OVERRIDE;
void ShowACK(int32_t selected_id, int32_t result);
private:
scoped_refptr<TrackedCallback> callback_;
int32_t* selected_id_ptr_;
DISALLOW_COPY_AND_ASSIGN(FlashMenu);
};
FlashMenu::FlashMenu(const HostResource& resource)
: Resource(OBJECT_IS_PROXY, resource),
selected_id_ptr_(NULL) {
}
FlashMenu::~FlashMenu() {
}
PPB_Flash_Menu_API* FlashMenu::AsPPB_Flash_Menu_API() {
return this;
}
int32_t FlashMenu::Show(const struct PP_Point* location,
int32_t* selected_id,
scoped_refptr<TrackedCallback> callback) {
if (TrackedCallback::IsPending(callback_))
return PP_ERROR_INPROGRESS;
selected_id_ptr_ = selected_id;
callback_ = callback;
PluginDispatcher::GetForResource(this)->Send(
new PpapiHostMsg_PPBFlashMenu_Show(
API_ID_PPB_FLASH_MENU, host_resource(), *location));
return PP_OK_COMPLETIONPENDING;
}
void FlashMenu::ShowACK(int32_t selected_id, int32_t result) {
*selected_id_ptr_ = selected_id;
TrackedCallback::ClearAndRun(&callback_, result);
}
PPB_Flash_Menu_Proxy::PPB_Flash_Menu_Proxy(Dispatcher* dispatcher)
: InterfaceProxy(dispatcher),
callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
}
PPB_Flash_Menu_Proxy::~PPB_Flash_Menu_Proxy() {
}
// static
PP_Resource PPB_Flash_Menu_Proxy::CreateProxyResource(
PP_Instance instance_id,
const PP_Flash_Menu* menu_data) {
PluginDispatcher* dispatcher = PluginDispatcher::GetForInstance(instance_id);
if (!dispatcher)
return 0;
HostResource result;
SerializedFlashMenu serialized_menu;
if (!serialized_menu.SetPPMenu(menu_data))
return 0;
dispatcher->Send(new PpapiHostMsg_PPBFlashMenu_Create(
API_ID_PPB_FLASH_MENU, instance_id, serialized_menu, &result));
if (result.is_null())
return 0;
return (new FlashMenu(result))->GetReference();
}
bool PPB_Flash_Menu_Proxy::OnMessageReceived(const IPC::Message& msg) {
if (!dispatcher()->permissions().HasPermission(PERMISSION_FLASH))
return false;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PPB_Flash_Menu_Proxy, msg)
IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFlashMenu_Create,
OnMsgCreate)
IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFlashMenu_Show,
OnMsgShow)
IPC_MESSAGE_HANDLER(PpapiMsg_PPBFlashMenu_ShowACK,
OnMsgShowACK)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
// FIXME(brettw) handle bad messages!
return handled;
}
void PPB_Flash_Menu_Proxy::OnMsgCreate(PP_Instance instance,
const SerializedFlashMenu& menu_data,
HostResource* result) {
thunk::EnterResourceCreation enter(instance);
if (enter.succeeded()) {
result->SetHostResource(
instance,
enter.functions()->CreateFlashMenu(instance, menu_data.pp_menu()));
}
}
struct PPB_Flash_Menu_Proxy::ShowRequest {
HostResource menu;
int32_t selected_id;
};
void PPB_Flash_Menu_Proxy::OnMsgShow(const HostResource& menu,
const PP_Point& location) {
ShowRequest* request = new ShowRequest;
request->menu = menu;
EnterHostFromHostResourceForceCallback<PPB_Flash_Menu_API> enter(
menu, callback_factory_, &PPB_Flash_Menu_Proxy::SendShowACKToPlugin,
request);
if (enter.succeeded()) {
enter.SetResult(enter.object()->Show(&location, &request->selected_id,
enter.callback()));
}
}
void PPB_Flash_Menu_Proxy::OnMsgShowACK(const HostResource& menu,
int32_t selected_id,
int32_t result) {
EnterPluginFromHostResource<PPB_Flash_Menu_API> enter(menu);
if (enter.failed())
return;
static_cast<FlashMenu*>(enter.object())->ShowACK(selected_id, result);
}
void PPB_Flash_Menu_Proxy::SendShowACKToPlugin(
int32_t result,
ShowRequest* request) {
dispatcher()->Send(new PpapiMsg_PPBFlashMenu_ShowACK(
API_ID_PPB_FLASH_MENU,
request->menu,
request->selected_id,
result));
delete request;
}
} // namespace proxy
} // namespace ppapi
| 5,304 | 1,873 |
/* Copyright (c) 2021 Mitya Selivanov
*
* This file is part of the Laplace project.
*
* Laplace 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 MIT License for more details.
*/
#include "input.h"
namespace laplace::linux {
using namespace core::keys;
using std::array;
sl::index const input::default_wheel_scale = 120;
input::input() noexcept {
set_wheel_scale(default_wheel_scale);
}
void input::use_system_cursor(bool) noexcept { }
void input::set_cursor_enabled(bool) noexcept { }
void input::set_mouse_resolution(sl::whole, sl::whole) noexcept { }
void input::set_clamp(bool, bool) noexcept { }
auto input::get_mouse_resolution_x() const noexcept -> sl::whole {
return 0;
}
auto input::get_mouse_resolution_y() const noexcept -> sl::whole {
return 0;
}
auto input::get_mouse_x() const noexcept -> sl::index {
return get_cursor_x();
}
auto input::get_mouse_y() const noexcept -> sl::index {
return get_cursor_y();
}
auto input::get_mouse_delta_x() const noexcept -> sl::index {
return get_cursor_delta_x();
}
auto input::get_mouse_delta_y() const noexcept -> sl::index {
return get_cursor_delta_y();
}
void input::update_button(sl::index button, bool is_down) noexcept {
if (button == Button1)
update_key(in_lbutton, is_down);
if (button == Button2)
update_key(in_mbutton, is_down);
if (button == Button3)
update_key(in_rbutton, is_down);
}
void input::update_controls(sl::index key, bool is_down) noexcept {
auto const code = map_key(key);
switch (code) {
case key_lshift:
case key_rshift: update_key(in_shift, is_down); break;
case key_lcontrol:
case key_rcontrol: update_key(in_control, is_down); break;
case key_lalt:
case key_ralt: update_key(in_alt, is_down); break;
case key_capslock_toggle:
toggle(in_capslock, is_down, m_toggle_capslock);
break;
case key_numlock_toggle:
toggle(in_numlock, is_down, m_toggle_numlock);
break;
case key_scrolllock_toggle:
toggle(in_scrolllock, is_down, m_toggle_scrolllock);
break;
default:;
}
}
void input::init_keymap(Display *display) noexcept {
adjust_and_set_keymap(load_keymap(display));
}
auto input::load_keymap(Display *display) noexcept -> keymap_table {
auto v = keymap_table {};
auto const code = [&](KeySym k) {
return XKeysymToKeycode(display, k);
};
v[code(XK_Left)] = key_left;
v[code(XK_Right)] = key_right;
v[code(XK_Up)] = key_up;
v[code(XK_Down)] = key_down;
v[code(XK_1)] = key_1;
v[code(XK_2)] = key_2;
v[code(XK_3)] = key_3;
v[code(XK_4)] = key_4;
v[code(XK_5)] = key_5;
v[code(XK_6)] = key_6;
v[code(XK_7)] = key_7;
v[code(XK_8)] = key_8;
v[code(XK_9)] = key_9;
v[code(XK_0)] = key_0;
v[code(XK_A)] = key_a;
v[code(XK_B)] = key_b;
v[code(XK_C)] = key_c;
v[code(XK_D)] = key_d;
v[code(XK_E)] = key_e;
v[code(XK_F)] = key_f;
v[code(XK_G)] = key_g;
v[code(XK_H)] = key_h;
v[code(XK_I)] = key_i;
v[code(XK_J)] = key_j;
v[code(XK_K)] = key_k;
v[code(XK_L)] = key_l;
v[code(XK_M)] = key_m;
v[code(XK_N)] = key_n;
v[code(XK_O)] = key_o;
v[code(XK_P)] = key_p;
v[code(XK_Q)] = key_q;
v[code(XK_R)] = key_r;
v[code(XK_S)] = key_s;
v[code(XK_T)] = key_t;
v[code(XK_V)] = key_v;
v[code(XK_W)] = key_w;
v[code(XK_X)] = key_x;
v[code(XK_Y)] = key_y;
v[code(XK_Z)] = key_z;
v[code(XK_space)] = key_space;
v[code(XK_braceleft)] = key_open;
v[code(XK_braceright)] = key_close;
v[code(XK_colon)] = key_semicolon;
v[code(XK_quotedbl)] = key_quote;
v[code(XK_asciitilde)] = key_tilda;
v[code(XK_backslash)] = key_backslash;
v[code(XK_comma)] = key_comma;
v[code(XK_greater)] = key_period;
v[code(XK_question)] = key_slash;
v[code(XK_F1)] = key_f1;
v[code(XK_F2)] = key_f2;
v[code(XK_F3)] = key_f3;
v[code(XK_F4)] = key_f4;
v[code(XK_F5)] = key_f5;
v[code(XK_F6)] = key_f6;
v[code(XK_F7)] = key_f7;
v[code(XK_F8)] = key_f8;
v[code(XK_F9)] = key_f9;
v[code(XK_F10)] = key_f10;
v[code(XK_F11)] = key_f11;
v[code(XK_F12)] = key_f12;
v[code(XK_Control_L)] = key_lcontrol;
v[code(XK_Control_R)] = key_rcontrol;
v[code(XK_Shift_L)] = key_lshift;
v[code(XK_Shift_R)] = key_rshift;
v[code(XK_Alt_L)] = key_lalt;
v[code(XK_Alt_R)] = key_ralt;
v[code(XK_Escape)] = key_escape;
v[code(XK_BackSpace)] = key_backspace;
v[code(XK_Tab)] = key_tab;
v[code(XK_Return)] = key_enter;
v[code(XK_Print)] = key_printscreen;
v[code(XK_Delete)] = key_delete;
v[code(XK_Pause)] = key_pause;
v[code(XK_Insert)] = key_insert;
v[code(XK_Home)] = key_home;
v[code(XK_End)] = key_end;
v[code(XK_Page_Up)] = key_pageup;
v[code(XK_Page_Down)] = key_pagedown;
v[code(XK_KP_0)] = key_numpad0;
v[code(XK_KP_1)] = key_numpad1;
v[code(XK_KP_2)] = key_numpad2;
v[code(XK_KP_3)] = key_numpad3;
v[code(XK_KP_4)] = key_numpad4;
v[code(XK_KP_5)] = key_numpad5;
v[code(XK_KP_6)] = key_numpad6;
v[code(XK_KP_7)] = key_numpad7;
v[code(XK_KP_8)] = key_numpad8;
v[code(XK_KP_9)] = key_numpad9;
v[code(XK_KP_Delete)] = key_delete;
v[code(XK_KP_Enter)] = key_enter;
v[code(XK_KP_Divide)] = key_divide;
v[code(XK_KP_Multiply)] = key_multiply;
v[code(XK_KP_Add)] = key_add;
v[code(XK_KP_Subtract)] = key_subtract;
v[code(XK_KP_Decimal)] = key_decimal;
v[code(XK_KP_Separator)] = key_separator;
v[code(XK_Caps_Lock)] = key_capslock_toggle;
v[code(XK_Num_Lock)] = key_numlock_toggle;
v[code(XK_Scroll_Lock)] = key_scrolllock_toggle;
v[0] = 0;
return v;
}
void input::adjust_and_set_keymap(keymap_table v) noexcept {
auto const find_empty = [&](uint8_t &n) -> uint8_t {
for (n = 1; n != 0; n++)
if (v[n] == 0)
return n;
return 0;
};
v[find_empty(in_lbutton)] = key_lbutton;
v[find_empty(in_rbutton)] = key_rbutton;
v[find_empty(in_mbutton)] = key_mbutton;
v[find_empty(in_xbutton1)] = key_xbutton1;
v[find_empty(in_xbutton2)] = key_xbutton2;
v[find_empty(in_shift)] = key_shift;
v[find_empty(in_control)] = key_control;
v[find_empty(in_alt)] = key_alt;
v[find_empty(in_capslock)] = key_capslock;
v[find_empty(in_numlock)] = key_numlock;
v[find_empty(in_scrolllock)] = key_scrolllock;
v[0] = 0;
set_keymap(v);
}
void input::toggle(sl::index key,
bool is_down,
bool &state) noexcept {
if (is_down)
state = !state;
if (state == is_down)
update_key(key, is_down);
}
}
| 7,149 | 3,213 |
#include "pch.h"
#include <cstdarg>
void aiLogPrint(const char* fmt, ...)
{
va_list vl;
va_start(vl, fmt);
#ifdef _WIN32
char buf[2048];
vsprintf(buf, fmt, vl);
::OutputDebugStringA(buf);
::OutputDebugStringA("\n");
#else
vprintf(fmt, vl);
#endif
va_end(vl);
}
void aiLogPrint(const wchar_t* fmt, ...)
{
va_list vl;
va_start(vl, fmt);
#ifdef _WIN32
wchar_t buf[2048];
vswprintf(buf, fmt, vl);
::OutputDebugStringW(buf);
::OutputDebugStringW(L"\n");
#else
vwprintf(fmt, vl);
#endif
va_end(vl);
}
| 591 | 251 |
#include "Framework/FrameworkTest.h"
#include "ShaderCompiler.h"
#include "System/Path.h"
// ***********************
// Tries to compile and link all shaders in combination folder.
SIMPLE_FRAMEWORK_TEST_IN_SUITE( Shaders_Compilation, TestCombinations )
{
auto vsShadersList = Path::List( "Assets/Shaders/Combinations/", true, ".*\\.vert" );
for( auto & vsShaderPath : vsShadersList )
{
auto psPath = FindMatchingPS( vsShaderPath );
TestCompilation( vsShaderPath.Str(), psPath.Str() );
}
}
| 553 | 200 |
template<typename T,
template<typename Elem> class Cont = std::deque>
class Stack {
private:
Cont<T> elems; // elements
public:
void push(T const&); // push element
void pop(); // pop element
T const& top() const; // return top element
bool empty() const { // return whether the stack is empty
return elems.empty();
}
//...
};
| 421 | 116 |
#include <CtrlLib/CtrlLib.h>
#include "SplitterButton.h"
namespace Upp {
SplitterButton::SplitterButton() {
Add(splitter.SizePos());
Add(button1.LeftPosZ(80, 10).TopPosZ(30, 40));
Add(button2.LeftPosZ(80, 10).TopPosZ(30, 40));
splitter.WhenLayout = THISBACK(OnLayout);
button1.WhenAction = THISBACK1(SetButton, 0);
button2.WhenAction = THISBACK1(SetButton, 1);
movingRight = true;
buttonWidth = int(2.5*splitter.GetSplitWidth());
positionId = 0;
SetButtonNumber(2);
splitter.SetPos(5000);
}
SplitterButton& SplitterButton::Horz(Ctrl &left, Ctrl &right) {
splitter.Horz(left, right);
SetPositions(0, 5000, 10000);
SetInitialPositionId(1);
SetArrows();
return *this;
}
SplitterButton& SplitterButton::Vert(Ctrl& top, Ctrl& bottom) {
splitter.Vert(top, bottom);
SetPositions(0, 5000, 10000);
SetInitialPositionId(1);
SetArrows();
return *this;
}
SplitterButton &SplitterButton::SetPositions(const Vector<int> &_positions) {
positions = clone(_positions);
Sort(positions);
if (positionId >= positions.GetCount() || positionId < 0)
positionId = 0;
splitter.SetPos(positions[positionId]);
return *this;
}
SplitterButton &SplitterButton::SetPositions(int pos1) {
Vector<int> pos;
pos << pos1;
SetPositions(pos);
return *this;
}
SplitterButton &SplitterButton::SetPositions(int pos1, int pos2) {
Vector<int> pos;
pos << pos1 << pos2;
SetPositions(pos);
return *this;
}
SplitterButton &SplitterButton::SetPositions(int pos1, int pos2, int pos3) {
Vector<int> pos;
pos << pos1 << pos2 << pos3;
SetPositions(pos);
return *this;
}
SplitterButton &SplitterButton::SetInitialPositionId(int id) {
positionId = id;
splitter.SetPos(positions[positionId]);
SetArrows();
return *this;
}
void SplitterButton::OnLayout(int pos) {
int cwidth, cheight;
if (splitter.IsVert()) {
cwidth = GetSize().cy;
cheight = GetSize().cx;
} else {
cwidth = GetSize().cx;
cheight = GetSize().cy;
}
int posx = max(0, pos - buttonWidth/2);
posx = min(cwidth - buttonWidth, posx);
int posy = (2*cheight)/5;
int widthy;
if (buttonNumber == 1)
widthy = cheight/5;
else
widthy = cheight/8;
if (splitter.IsVert()) {
if (buttonNumber == 1)
button1.SetPos(PosLeft(posy, widthy), PosTop(posx, buttonWidth));
else {
button1.SetPos(PosLeft(posy - widthy/2, widthy), PosTop(posx, buttonWidth));
button2.SetPos(PosLeft(posy + widthy/2, widthy), PosTop(posx, buttonWidth));
}
} else {
if (buttonNumber == 1)
button1.SetPos(PosLeft(posx, buttonWidth), PosTop(posy, widthy));
else {
button1.SetPos(PosLeft(posx, buttonWidth), PosTop(posy - widthy/2, widthy));
button2.SetPos(PosLeft(posx, buttonWidth), PosTop(posy + widthy/2, widthy));
}
}
WhenAction();
}
void SplitterButton::SetButton(int id) {
ASSERT(positions.GetCount() > 1);
int pos = splitter.GetPos();
int closerPositionId = Null;
int closerPosition = 10000;
for (int i = 0; i < positions.GetCount(); ++i)
if (abs(positions[i] - pos) < closerPosition) {
closerPosition = abs(positions[i] - pos);
closerPositionId = i;
}
//bool arrowRight;
if (buttonNumber == 1) {
if (movingRight) {
if (closerPositionId == (positions.GetCount() - 1)) {
movingRight = false;
positionId = positions.GetCount() - 2;
} else
positionId = closerPositionId + 1;
} else {
if (closerPositionId == 0) {
movingRight = true;
positionId = 1;
} else
positionId = closerPositionId - 1;
}
} else {
if (id == 1) {
if (positionId < positions.GetCount() - 1)
positionId++;
} else {
if (positionId > 0)
positionId--;
}
}
splitter.SetPos(positions[positionId]);
SetArrows();
WhenAction();
}
void SplitterButton::SetArrows() {
if (buttonNumber == 1) {
bool arrowRight = movingRight;
if (positionId == (positions.GetCount() - 1))
arrowRight = false;
if (positionId == 0)
arrowRight = true;
if (arrowRight)
button1.SetImage(splitter.IsVert() ? CtrlImg::smalldown() : CtrlImg::smallright());
else
button1.SetImage(splitter.IsVert() ? CtrlImg::smallup() : CtrlImg::smallleft());
} else {
button1.SetImage(splitter.IsVert() ? CtrlImg::smallup() : CtrlImg::smallleft());
button2.SetImage(splitter.IsVert() ? CtrlImg::smalldown() : CtrlImg::smallright());
}
}
CH_STYLE(Box, Style, StyleDefault) {
width = Ctrl::HorzLayoutZoom(2);
vert[0] = horz[0] = SColorFace();
vert[1] = horz[1] = GUI_GlobalStyle() >= GUISTYLE_XP ? Blend(SColorHighlight, SColorFace)
: SColorShadow();
dots = false;
}
} | 4,580 | 1,917 |
// base/kaldi-utils.cc
// Copyright 2009-2011 Karel Vesely; Yanmin Qian; Microsoft Corporation
// See ../../COPYING for clarification regarding multiple authors
//
// 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
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-utils.h"
#include <chrono>
#include <cstdio>
#include <thread>
namespace kaldi {
std::string CharToString(const char &c) {
char buf[20];
if (std::isprint(c))
std::snprintf(buf, sizeof(buf), "\'%c\'", c);
else
std::snprintf(buf, sizeof(buf), "[character %d]", static_cast<int>(c));
return buf;
}
void Sleep(double sec) {
// duration_cast<> rounds down, add 0.5 to compensate.
auto dur_nanos = std::chrono::duration<double, std::nano>(sec * 1E9 + 0.5);
auto dur_syshires = std::chrono::duration_cast<
typename std::chrono::high_resolution_clock::duration>(dur_nanos);
std::this_thread::sleep_for(dur_syshires);
}
} // end namespace kaldi
| 1,471 | 547 |
#include <QTimer>
#include "NoOpReply.h"
NoOpReply::NoOpReply(QNetworkRequest &request, QObject *parent) : QNetworkReply(parent) {
open(ReadOnly | Unbuffered);
setAttribute(QNetworkRequest::HttpStatusCodeAttribute, 200);
setHeader(QNetworkRequest::ContentLengthHeader, QVariant(0));
setHeader(QNetworkRequest::ContentTypeHeader, QVariant(QString("text/plain")));
setUrl(request.url());
QTimer::singleShot( 0, this, SIGNAL(readyRead()) );
QTimer::singleShot( 0, this, SIGNAL(finished()) );
}
void NoOpReply::abort() {
// NO-OP
}
qint64 NoOpReply::bytesAvailable() const {
return 0;
}
bool NoOpReply::isSequential() const {
return true;
}
qint64 NoOpReply::readData(char *data, qint64 maxSize) {
Q_UNUSED(data);
Q_UNUSED(maxSize);
return 0;
}
| 774 | 302 |
#ifndef FTXUI_COMPONENT_CHECKBOX_HPP
#define FTXUI_COMPONENT_CHECKBOX_HPP
#include <functional> // for function
#include <string> // for allocator, wstring
#include "ftxui/component/component.hpp" // for Component
#include "ftxui/component/component_base.hpp" // for ComponentBase
#include "ftxui/dom/elements.hpp" // for Element, Decorator, inverted, nothing
#include "ftxui/screen/box.hpp" // for Box
#include "ftxui/screen/string.hpp" // for ConstStringRef
namespace ftxui {
struct Event;
/// @brief A Checkbox. It can be checked or unchecked.Display an element on a
/// ftxui::Screen.
/// @ingroup dom
class CheckboxBase : public ComponentBase {
public:
// Access this interface from a Component
static CheckboxBase* From(Component component);
// Constructor.
CheckboxBase(ConstStringRef label, bool* state);
~CheckboxBase() override = default;
#if defined(_WIN32)
std::wstring checked = L"[X] "; /// Prefix for a "checked" state.
std::wstring unchecked = L"[ ] "; /// Prefix for an "unchecked" state.
#else
std::wstring checked = L"▣ "; /// Prefix for a "checked" state.
std::wstring unchecked = L"☐ "; /// Prefix for a "unchecked" state.
#endif
Decorator focused_style = inverted; /// Decorator used when focused.
Decorator unfocused_style = nothing; /// Decorator used when unfocused.
/// Called when the user change the state of the CheckboxBase.
std::function<void()> on_change = []() {};
// Component implementation.
Element Render() override;
bool OnEvent(Event) override;
private:
bool OnMouseEvent(Event event);
ConstStringRef label_;
bool* const state_;
int cursor_position = 0;
Box box_;
};
} // namespace ftxui
#endif /* end of include guard: FTXUI_COMPONENT_CHECKBOX_HPP */
// Copyright 2020 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
| 1,941 | 643 |
#ifndef SWT_PLUS_PLUS_RESOURCE_H
#define SWT_PLUS_PLUS_RESOURCE_H
namespace swt
{
class Resource {
public:
};
}
#endif //SWT_PLUS_PLUS_RESOURCE_H
| 161 | 78 |
#include "SerialWombat.h"
SerialWombatWS2812::SerialWombatWS2812(SerialWombat& serialWombat)
{
_sw = &serialWombat;
}
int16_t SerialWombatWS2812::begin(uint8_t pin, uint8_t numberOfLEDs, uint16_t userBufferIndex)
{
_pin = pin;
_numLEDS = numberOfLEDs;
_userBufferIndex = userBufferIndex;
uint8_t tx[8] = { 200,_pin,12,SW_LE16(userBufferIndex),_numLEDS,0x55 };
return (_sw->sendPacket(tx));
}
int16_t SerialWombatWS2812::write(uint8_t led, uint32_t color)
{
uint8_t tx[8] = { 201,_pin,12,led,SW_LE32(color) };
tx[7] = 0x55;
return _sw->sendPacket(tx);
}
int16_t SerialWombatWS2812::write(uint8_t led, int16_t color)
{
return write(led, (uint32_t)color);
}
int16_t SerialWombatWS2812::write(uint8_t led, int32_t color)
{
return write(led, (uint32_t)color);
}
int16_t SerialWombatWS2812::write(uint8_t led, uint8_t length, uint32_t colors[])
{
for (int i = 0; i < length; ++i)
{
int16_t result =
write(led + i, colors[i]);
if (result < 0)
{
return (result);
}
}
return(0);
}
int16_t SerialWombatWS2812::writeAnimationLED(uint8_t frame, uint8_t led, uint32_t color)
{
uint8_t tx[8] = { 203,_pin,12,frame,led,(color >>16 ) & 0xFF,(color >> 8) & 0xFF, color & 0xFF };
return _sw->sendPacket(tx);
}
int16_t SerialWombatWS2812::writeAnimationLED(uint8_t frame, uint8_t led, int16_t color)
{
writeAnimationLED(frame, led,(uint32_t)color);
}
int16_t SerialWombatWS2812::writeAnimationLED(uint8_t frame, uint8_t led, int32_t color)
{
writeAnimationLED(frame, led, (uint32_t)color);
}
int16_t SerialWombatWS2812::writeAnimationFrame(uint8_t frame, uint32_t colors[])
{
for (int i = 0; i < _numLEDS; ++i)
{
int16_t result;
result = writeAnimationLED(frame, i, colors[i]);
if (result < 0)
{
return (result);
}
}
return(0);
}
int16_t SerialWombatWS2812::writeAnimationFrameDelay(uint8_t frame, uint16_t delay_mS)
{
uint8_t tx[8] = { 205,_pin,12,frame,SW_LE16(delay_mS),0x55,0x55 };
return (_sw->sendPacket(tx));
}
int16_t SerialWombatWS2812::writeAnimationUserBufferIndex(uint16_t index, uint8_t numberOfFrames)
{
uint8_t tx[8] = { 204,_pin,12,SW_LE16(index),numberOfFrames,0x55,0x55 };
return (_sw->sendPacket(tx));
}
int16_t SerialWombatWS2812::readBufferSize()
{
uint8_t tx[8] = { 202,_pin,12,_numLEDS,0x55,0x55,0x55,0x55 };
uint8_t rx[8];
int16_t result = _sw->sendPacket(tx,rx);
if (result >= 0)
{
return (rx[3] + rx[4] * 256);
}
else
{
return (result);
}
return int16_t();
}
int16_t SerialWombatWS2812::setMode(SWWS2812Mode mode)
{
uint8_t tx[8] = { 206,_pin,12,mode,0x55,0x55,0x55,0x55 };
return _sw->sendPacket(tx);
}
| 2,603 | 1,335 |
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTERPROCESS_WINDOWS_RECURSIVE_NAMED_MUTEX_HPP
#define BOOST_INTERPROCESS_WINDOWS_RECURSIVE_NAMED_MUTEX_HPP
#if (defined _MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#include <boost/interprocess/sync/windows/named_mutex.hpp>
namespace boost {
namespace interprocess {
namespace ipcdetail {
class windows_named_recursive_mutex
//Windows mutexes based on CreateMutex are already recursive...
: public windows_named_mutex
{
/// @cond
//Non-copyable
windows_named_recursive_mutex();
windows_named_recursive_mutex(const windows_named_mutex &);
windows_named_recursive_mutex &operator=(const windows_named_mutex &);
/// @endcond
public:
windows_named_recursive_mutex(create_only_t, const char *name, const permissions &perm = permissions())
: windows_named_mutex(create_only_t(), name, perm)
{}
windows_named_recursive_mutex(open_or_create_t, const char *name, const permissions &perm = permissions())
: windows_named_mutex(open_or_create_t(), name, perm)
{}
windows_named_recursive_mutex(open_only_t, const char *name)
: windows_named_mutex(open_only_t(), name)
{}
};
} //namespace ipcdetail {
} //namespace interprocess {
} //namespace boost {
#include <boost/interprocess/detail/config_end.hpp>
#endif //BOOST_INTERPROCESS_WINDOWS_RECURSIVE_NAMED_MUTEX_HPP
| 1,949 | 676 |
/**
* @file
* @copyright defined in enumivo/LICENSE
*/
#pragma once
#include <enumivo/chain/types.hpp>
#include <fc/io/raw.hpp>
#include <softfloat.hpp>
namespace enumivo { namespace chain {
template<typename ...Indices>
class index_set;
template<typename Index>
class index_utils {
public:
using index_t = Index;
template<typename F>
static void walk( const chainbase::database& db, F function ) {
auto const& index = db.get_index<Index>().indices();
const auto& first = index.begin();
const auto& last = index.end();
for (auto itr = first; itr != last; ++itr) {
function(*itr);
}
}
template<typename Secondary, typename Key, typename F>
static void walk_range( const chainbase::database& db, const Key& begin_key, const Key& end_key, F function ) {
const auto& idx = db.get_index<Index, Secondary>();
auto begin_itr = idx.lower_bound(begin_key);
auto end_itr = idx.lower_bound(end_key);
for (auto itr = begin_itr; itr != end_itr; ++itr) {
function(*itr);
}
}
template<typename Secondary, typename Key>
static size_t size_range( const chainbase::database& db, const Key& begin_key, const Key& end_key ) {
const auto& idx = db.get_index<Index, Secondary>();
auto begin_itr = idx.lower_bound(begin_key);
auto end_itr = idx.lower_bound(end_key);
size_t res = 0;
while (begin_itr != end_itr) {
res++; ++begin_itr;
}
return res;
}
template<typename F>
static void create( chainbase::database& db, F cons ) {
db.create<typename index_t::value_type>(cons);
}
};
template<typename Index>
class index_set<Index> {
public:
static void add_indices( chainbase::database& db ) {
db.add_index<Index>();
}
template<typename F>
static void walk_indices( F function ) {
function( index_utils<Index>() );
}
};
template<typename FirstIndex, typename ...RemainingIndices>
class index_set<FirstIndex, RemainingIndices...> {
public:
static void add_indices( chainbase::database& db ) {
index_set<FirstIndex>::add_indices(db);
index_set<RemainingIndices...>::add_indices(db);
}
template<typename F>
static void walk_indices( F function ) {
index_set<FirstIndex>::walk_indices(function);
index_set<RemainingIndices...>::walk_indices(function);
}
};
template<typename DataStream>
DataStream& operator << ( DataStream& ds, const shared_blob& b ) {
fc::raw::pack(ds, static_cast<const shared_string&>(b));
return ds;
}
template<typename DataStream>
DataStream& operator >> ( DataStream& ds, shared_blob& b ) {
fc::raw::unpack(ds, static_cast<shared_string &>(b));
return ds;
}
} }
namespace fc {
// overloads for to/from_variant
template<typename OidType>
void to_variant( const chainbase::oid<OidType>& oid, variant& v ) {
v = variant(oid._id);
}
template<typename OidType>
void from_variant( const variant& v, chainbase::oid<OidType>& oid ) {
from_variant(v, oid._id);
}
inline
void to_variant( const float64_t& f, variant& v ) {
v = variant(*reinterpret_cast<const double*>(&f));
}
inline
void from_variant( const variant& v, float64_t& f ) {
from_variant(v, *reinterpret_cast<double*>(&f));
}
inline
void to_variant( const float128_t& f, variant& v ) {
v = variant(*reinterpret_cast<const uint128_t*>(&f));
}
inline
void from_variant( const variant& v, float128_t& f ) {
from_variant(v, *reinterpret_cast<uint128_t*>(&f));
}
inline
void to_variant( const enumivo::chain::shared_string& s, variant& v ) {
v = variant(std::string(s.begin(), s.end()));
}
inline
void from_variant( const variant& v, enumivo::chain::shared_string& s ) {
string _s;
from_variant(v, _s);
s = enumivo::chain::shared_string(_s.begin(), _s.end(), s.get_allocator());
}
inline
void to_variant( const enumivo::chain::shared_blob& b, variant& v ) {
v = variant(base64_encode(b.data(), b.size()));
}
inline
void from_variant( const variant& v, enumivo::chain::shared_blob& b ) {
string _s = base64_decode(v.as_string());
b = enumivo::chain::shared_blob(_s.begin(), _s.end(), b.get_allocator());
}
inline
void to_variant( const blob& b, variant& v ) {
v = variant(base64_encode(b.data.data(), b.data.size()));
}
inline
void from_variant( const variant& v, blob& b ) {
string _s = base64_decode(v.as_string());
b.data = std::vector<char>(_s.begin(), _s.end());
}
template<typename T>
void to_variant( const enumivo::chain::shared_vector<T>& sv, variant& v ) {
to_variant(std::vector<T>(sv.begin(), sv.end()), v);
}
template<typename T>
void from_variant( const variant& v, enumivo::chain::shared_vector<T>& sv ) {
std::vector<T> _v;
from_variant(v, _v);
sv = enumivo::chain::shared_vector<T>(_v.begin(), _v.end(), sv.get_allocator());
}
}
namespace chainbase {
// overloads for OID packing
template<typename DataStream, typename OidType>
DataStream& operator << ( DataStream& ds, const oid<OidType>& oid ) {
fc::raw::pack(ds, oid._id);
return ds;
}
template<typename DataStream, typename OidType>
DataStream& operator >> ( DataStream& ds, oid<OidType>& oid ) {
fc::raw::unpack(ds, oid._id);
return ds;
}
}
// overloads for softfloat packing
template<typename DataStream>
DataStream& operator << ( DataStream& ds, const float64_t& v ) {
fc::raw::pack(ds, *reinterpret_cast<const double *>(&v));
return ds;
}
template<typename DataStream>
DataStream& operator >> ( DataStream& ds, float64_t& v ) {
fc::raw::unpack(ds, *reinterpret_cast<double *>(&v));
return ds;
}
template<typename DataStream>
DataStream& operator << ( DataStream& ds, const float128_t& v ) {
fc::raw::pack(ds, *reinterpret_cast<const enumivo::chain::uint128_t*>(&v));
return ds;
}
template<typename DataStream>
DataStream& operator >> ( DataStream& ds, float128_t& v ) {
fc::raw::unpack(ds, *reinterpret_cast<enumivo::chain::uint128_t*>(&v));
return ds;
}
| 6,506 | 2,185 |
#include "../include/coefficient.hpp"
#include <iostream>
#include <random>
#include <vector>
using DwellRegions::Coefficient;
auto
generate_random_coefficients(size_t num_points)
{
std::random_device rd; // Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
std::uniform_real_distribution<> distribution(0.0, 180.0);
std::vector<Coefficient> coefficients;
coefficients.reserve(num_points);
for (size_t i = 0; i < num_points; i++) {
// Use dis to transform the random unsigned int generated by gen into a
// double in [1, 2). Each call to dis(gen) generates a new random double
coefficients.emplace_back(DwellRegions::Coefficient::from_double(distribution(gen)));
}
return coefficients;
}
void
print_coefficients(const std::vector<Coefficient>& coefficients)
{
for (const auto& c : coefficients) {
std::cout << c.val() << " " << c.as_float() << std::endl;
}
}
// Pairwise subtract the coefficients
void
subtraction_test(const std::vector<Coefficient>& coefficients)
{
std::cout << "---------- Subtraction test--------------" << std::endl;
for (size_t i = 1; i < coefficients.size(); i++) {
std::cout << coefficients[i - 1].as_float() << " - " << coefficients[i].as_float() << " = ";
const auto res = (coefficients[i - 1] - coefficients[i]).as_float();
const auto float_res = coefficients[i - 1].as_float() - coefficients[i].as_float();
if (res != float_res) {
std::cout << "Error: mismatch! res = " << res << " \t Float res = " << float_res << std::endl;
} else {
std::cout << "Ok." << std::endl;
}
}
}
// Pairwise multiply the coefficients
void
multiplication_test(const std::vector<Coefficient>& coefficients)
{
std::cout << "---------- Multiplication test--------------" << std::endl;
for (size_t i = 1; i < coefficients.size(); i++) {
std::cout << coefficients[i - 1].as_float() << " * " << coefficients[i].as_float() << " = ";
const auto res = (coefficients[i - 1] * coefficients[i]).as_float();
const auto float_res = coefficients[i - 1].as_float() * coefficients[i].as_float();
if (res != float_res) {
std::cout << "Error: mismatch! res = " << res << " \t Float res = " << float_res << std::endl;
} else {
std::cout << "Ok." << std::endl;
}
}
}
// Pairwise divide the coefficients
void
division_test(const std::vector<Coefficient>& coefficients)
{
std::cout << "---------- Division test--------------" << std::endl;
for (size_t i = 1; i < coefficients.size(); i++) {
std::cout << coefficients[i - 1].as_float() << " / " << coefficients[i].as_float() << " = ";
const auto res = (coefficients[i - 1] / coefficients[i]).as_float();
const auto float_res = coefficients[i - 1].as_float() / coefficients[i].as_float();
if (res != float_res) {
std::cout << "Error: mismatch! res = " << res << " \t Float res = " << float_res << std::endl;
} else {
std::cout << "Ok." << std::endl;
}
}
}
int
main()
{
const size_t num_coefficients = 10;
const auto coefficients = generate_random_coefficients(num_coefficients);
std::cout << "---------- Original Coefficients --------------" << std::endl;
print_coefficients(coefficients);
subtraction_test(coefficients);
multiplication_test(coefficients);
division_test(coefficients);
return 0;
} | 3,411 | 1,136 |
// Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <Rcpp.h>
using namespace Rcpp;
// rcpp_parse_rmd
void rcpp_parse_rmd(const std::string filename, const std::string tempfile);
RcppExport SEXP _srr_rcpp_parse_rmd(SEXP filenameSEXP, SEXP tempfileSEXP) {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const std::string >::type filename(filenameSEXP);
Rcpp::traits::input_parameter< const std::string >::type tempfile(tempfileSEXP);
rcpp_parse_rmd(filename, tempfile);
return R_NilValue;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_srr_rcpp_parse_rmd", (DL_FUNC) &_srr_rcpp_parse_rmd, 2},
{NULL, NULL, 0}
};
RcppExport void R_init_srr(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
| 913 | 376 |
#include <bdlb_arrayutil.h>
#include <bdlb_bitutil.h>
#include <bdld_datummaker.h>
#include <bdldfp_decimal.h>
#include <bdldfp_decimalutil.h>
#include <bsl_algorithm.h>
#include <bsl_cmath.h>
#include <bsl_functional.h>
#include <bsl_limits.h>
#include <bsl_numeric.h>
#include <bsl_utility.h>
#include <bslmf_assert.h>
#include <bsls_assert.h>
#include <bsls_types.h>
#include <lspcore_arithmeticutil.h>
#include <math.h> // isnan
using namespace BloombergLP;
namespace lspcore {
namespace {
template <typename RESULT>
RESULT the(const bdld::Datum&);
template <>
bdldfp::Decimal64 the<bdldfp::Decimal64>(const bdld::Datum& datum) {
return datum.theDecimal64();
}
template <>
bsls::Types::Int64 the<bsls::Types::Int64>(const bdld::Datum& datum) {
return datum.theInteger64();
}
template <>
int the<int>(const bdld::Datum& datum) {
return datum.theInteger();
}
template <>
double the<double>(const bdld::Datum& datum) {
return datum.theDouble();
}
template <template <typename> class OPERATOR, typename NUMBER>
struct Operator {
NUMBER operator()(NUMBER soFar, const bdld::Datum& number) const {
return OPERATOR<NUMBER>()(soFar, the<NUMBER>(number));
}
};
struct Classification {
enum Kind {
e_COMMON_TYPE,
e_SAME_TYPE,
e_ERROR_INCOMPATIBLE_NUMBER_TYPES,
e_ERROR_NON_NUMERIC_TYPE
};
Kind kind;
bdld::Datum::DataType type;
};
typedef bsls::Types::Uint64 Bits;
// There must be no more than 64 types of 'bdld::Datum', otherwise we wouldn't
// be able to use the type 'Bits' as a bitmask. In some far infinite future, we
// could switch to 'std::bitset' if necessary.
BSLMF_ASSERT(bdld::Datum::k_NUM_TYPES <= bsl::numeric_limits<Bits>::digits);
Classification classify(Bits types) {
// cases:
//
// - any non-number types → e_ERROR_NON_NUMERIC_TYPE
// - incompatible type combinations → e_ERROR_INCOMPATIBLE_NUMBER_TYPES
// - all the same → e_SAME_TYPE
// - otherwise, pick out the common type → e_COMMON_TYPE
#define TYPE(NAME) (Bits(1) << bdld::Datum::e_##NAME)
const Bits numbers =
TYPE(INTEGER) | TYPE(INTEGER64) | TYPE(DOUBLE) | TYPE(DECIMAL64);
const Bits invalidCombos[] = { TYPE(INTEGER64) | TYPE(DOUBLE),
TYPE(INTEGER64) | TYPE(DECIMAL64),
TYPE(DOUBLE) | TYPE(DECIMAL64) };
// check for non-number types
if (types & ~numbers) {
Classification result;
result.kind = Classification::e_ERROR_NON_NUMERIC_TYPE;
return result;
}
// check for incompatible combinations of number types
for (bsl::size_t i = 0; i < bdlb::ArrayUtil::size(invalidCombos); ++i) {
if ((types & invalidCombos[i]) == invalidCombos[i]) {
Classification result;
result.kind = Classification::e_ERROR_INCOMPATIBLE_NUMBER_TYPES;
return result;
}
}
// check for all-the-same-number-type
Classification result;
switch (types) {
case TYPE(INTEGER):
result.kind = Classification::e_SAME_TYPE;
result.type = bdld::Datum::e_INTEGER;
return result;
case TYPE(INTEGER64):
result.kind = Classification::e_SAME_TYPE;
result.type = bdld::Datum::e_INTEGER64;
return result;
case TYPE(DOUBLE):
result.kind = Classification::e_SAME_TYPE;
result.type = bdld::Datum::e_DOUBLE;
return result;
case TYPE(DECIMAL64):
result.kind = Classification::e_SAME_TYPE;
result.type = bdld::Datum::e_DECIMAL64;
return result;
default:
break;
}
// At this point, we have exactly two number types, and one of them is int.
// The common type is just the other type.
result.kind = Classification::e_COMMON_TYPE;
switch (const Bits other = types & ~TYPE(INTEGER)) {
case TYPE(INTEGER64):
result.type = bdld::Datum::e_INTEGER64;
return result;
case TYPE(DOUBLE):
result.type = bdld::Datum::e_DOUBLE;
return result;
default:
(void)other;
BSLS_ASSERT(other == TYPE(DECIMAL64));
result.type = bdld::Datum::e_DECIMAL64;
return result;
}
}
Classification classify(const bsl::vector<bdld::Datum>& data) {
Bits types = 0;
for (bsl::size_t i = 0; i < data.size(); ++i) {
types |= Bits(1) << data[i].type();
}
return classify(types);
}
template <typename NUMBER>
void homogeneousAdd(bsl::vector<bdld::Datum>& argsAndOutput,
bslma::Allocator* allocator) {
const NUMBER result = bsl::accumulate(argsAndOutput.begin(),
argsAndOutput.end(),
NUMBER(0),
Operator<bsl::plus, NUMBER>());
argsAndOutput.resize(1);
argsAndOutput[0] = bdld::DatumMaker(allocator)(result);
}
template <typename NUMBER>
void homogeneousSubtract(bsl::vector<bdld::Datum>& argsAndOutput,
bslma::Allocator* allocator) {
BSLS_ASSERT(!argsAndOutput.empty());
NUMBER result;
if (argsAndOutput.size() == 1) {
result = -the<NUMBER>(argsAndOutput[0]);
}
else {
result = bsl::accumulate(argsAndOutput.begin() + 1,
argsAndOutput.end(),
the<NUMBER>(argsAndOutput[0]),
Operator<bsl::minus, NUMBER>());
}
argsAndOutput.resize(1);
argsAndOutput[0] = bdld::DatumMaker(allocator)(result);
}
template <typename NUMBER>
void homogeneousMultiply(bsl::vector<bdld::Datum>& argsAndOutput,
bslma::Allocator* allocator) {
const NUMBER result = bsl::accumulate(argsAndOutput.begin(),
argsAndOutput.end(),
NUMBER(1),
Operator<bsl::multiplies, NUMBER>());
argsAndOutput.resize(1);
argsAndOutput[0] = bdld::DatumMaker(allocator)(result);
}
template <typename NUMBER>
void homogeneousDivide(bsl::vector<bdld::Datum>& argsAndOutput,
bslma::Allocator* allocator) {
BSLS_ASSERT(!argsAndOutput.empty());
NUMBER result;
if (argsAndOutput.size() == 1) {
result = the<NUMBER>(argsAndOutput[0]);
}
else {
result = bsl::accumulate(argsAndOutput.begin() + 1,
argsAndOutput.end(),
the<NUMBER>(argsAndOutput[0]),
Operator<bsl::divides, NUMBER>());
}
argsAndOutput.resize(1);
argsAndOutput[0] = bdld::DatumMaker(allocator)(result);
}
template <typename OUTPUT>
class NumericConvert {
bdld::DatumMaker d_make;
public:
explicit NumericConvert(bslma::Allocator* allocator)
: d_make(allocator) {
}
bdld::Datum operator()(const bdld::Datum& datum) const {
if (datum.type() == bdld::Datum::e_INTEGER) {
OUTPUT number(datum.theInteger());
return d_make(number);
}
return datum;
}
};
// TODO: document
bdld::Datum::DataType normalizeTypes(bsl::vector<bdld::Datum>& data,
bslma::Allocator* allocator) {
Classification result = classify(data);
switch (result.kind) {
case Classification::e_COMMON_TYPE:
switch (result.type) {
case bdld::Datum::e_INTEGER64:
bsl::transform(
data.begin(),
data.end(),
data.begin(),
NumericConvert<bsls::Types::Int64>(allocator));
break;
case bdld::Datum::e_DOUBLE:
bsl::transform(data.begin(),
data.end(),
data.begin(),
NumericConvert<double>(allocator));
break;
default:
BSLS_ASSERT(result.type == bdld::Datum::e_DECIMAL64);
bsl::transform(
data.begin(),
data.end(),
data.begin(),
NumericConvert<bdldfp::Decimal64>(allocator));
}
// fall through
case Classification::e_SAME_TYPE:
return result.type;
case Classification::e_ERROR_INCOMPATIBLE_NUMBER_TYPES:
throw bdld::Datum::createError(
-1,
"incompatible numeric types passed to an arithmetic procedure",
allocator);
default:
BSLS_ASSERT(result.kind ==
Classification::e_ERROR_NON_NUMERIC_TYPE);
throw bdld::Datum::createError(
-1,
"non-numeric type passed to an arithmetic procedure",
allocator);
}
}
int divideFives(bsl::uint64_t* ptr) {
BSLS_ASSERT(ptr);
bsl::uint64_t& value = *ptr;
BSLS_ASSERT(value != 0);
int count;
for (count = 0; value % 5 == 0; ++count) {
value /= 5;
}
return count;
}
bool notEqual(double binary, bdldfp::Decimal64 decimal) {
// Ladies and gentlemen, I present to you the least efficient equality
// predicate ever devised.
//
// The plan is to divide out the factors of 2 and 5 from the significands
// of 'binary' and 'decimal'. Since the radix of 'binary' is 2 and the
// radix of 'decimal' is 10 (which is 2*5), we can then compare the reduced
// significands and the exponents.
//
// One optimization is possible for "find the factors of two in the
// significand." For nonzero values, we can count the number of trailing
// zero bits (that's the number of factors of two) and then shift right
// that many bits.
//
// Factors of five we'll have to do the hard way, but we need check the
// powers of five only if the powers of two happen to be equal.
// 'bsl::uint64_t' and 'bsls::Types::Uint64' can be different types, and
// the compiler will complain about aliasing. Here I just pick one and
// copy to the other where necessary.
typedef bsl::uint64_t Uint64;
bsls::Types::Uint64 decimalMantissaArg; // long vs. long long ugh...
int decimalSign; // -1 or +1
int decimalExponent;
switch (
const int kind = bdldfp::DecimalUtil::decompose(
&decimalSign, &decimalMantissaArg, &decimalExponent, decimal)) {
case FP_NAN:
return true;
case FP_INFINITE:
return binary !=
bsl::numeric_limits<double>::infinity() * decimalSign;
case FP_SUBNORMAL:
// same handling as in the 'FP_NORMAL' case ('default', below)
break;
case FP_ZERO:
return binary != 0;
default:
(void)kind;
BSLS_ASSERT(kind == FP_NORMAL);
}
Uint64 decimalMantissa = decimalMantissaArg; // long vs. long long ugh...
// Skip the calculations below if the values have different signs.
const int binarySign = binary < 0 ? -1 : 1;
if (decimalSign != binarySign) {
return true;
}
// To decompose the binary floating point value, we use the standard
// library function 'frexp' followed by a multiplication to guarantee an
// integer-valued significand. This multiplication will not lose precision.
int binaryExponent;
const double binaryNormalizedSignificand =
std::frexp(binary, &binaryExponent);
if (binaryNormalizedSignificand == 0 ||
isnan(binaryNormalizedSignificand) ||
binaryNormalizedSignificand ==
std::numeric_limits<double>::infinity() ||
binaryNormalizedSignificand ==
-std::numeric_limits<double>::infinity()) {
return true;
}
const int precision = 53;
Uint64 binaryMantissa =
binaryNormalizedSignificand * (Uint64(1) << (precision - 1));
binaryExponent -= precision - 1;
BSLS_ASSERT(binaryMantissa != 0);
BSLS_ASSERT(decimalMantissa != 0);
const int binaryUnset =
bdlb::BitUtil::numTrailingUnsetBits(binaryMantissa);
const int binaryTwos = binaryExponent + binaryUnset;
const int decimalUnset =
bdlb::BitUtil::numTrailingUnsetBits(decimalMantissa);
const int decimalTwos = decimalExponent + decimalUnset;
if (binaryTwos != decimalTwos) {
return true;
}
binaryMantissa >>= binaryUnset;
decimalMantissa >>= decimalUnset;
const int binaryFives = divideFives(&binaryMantissa);
const int decimalFives = decimalExponent + divideFives(&decimalMantissa);
return binaryFives != decimalFives || binaryMantissa != decimalMantissa;
}
class NotEqual {
bslma::Allocator* d_allocator_p;
public:
explicit NotEqual(bslma::Allocator* allocator)
: d_allocator_p(allocator) {
}
bool operator()(const bdld::Datum& left, const bdld::Datum& right) const {
if (left.type() == right.type()) {
return left != right;
}
#define TYPE_PAIR(LEFT, RIGHT) \
((bsl::uint64_t(LEFT) << 32) | bsl::uint64_t(RIGHT))
switch (TYPE_PAIR(left.type(), right.type())) {
case TYPE_PAIR(bdld::Datum::e_INTEGER, bdld::Datum::e_INTEGER64):
return left.theInteger() != right.theInteger64();
case TYPE_PAIR(bdld::Datum::e_INTEGER64, bdld::Datum::e_INTEGER):
return right.theInteger() != left.theInteger64();
case TYPE_PAIR(bdld::Datum::e_INTEGER, bdld::Datum::e_DOUBLE):
return left.theInteger() != right.theDouble();
case TYPE_PAIR(bdld::Datum::e_DOUBLE, bdld::Datum::e_INTEGER):
return right.theInteger() != left.theDouble();
case TYPE_PAIR(bdld::Datum::e_INTEGER, bdld::Datum::e_DECIMAL64):
return bdldfp::Decimal64(left.theInteger()) !=
right.theDecimal64();
case TYPE_PAIR(bdld::Datum::e_DECIMAL64, bdld::Datum::e_INTEGER):
return bdldfp::Decimal64(right.theInteger()) !=
left.theDecimal64();
case TYPE_PAIR(bdld::Datum::e_DOUBLE, bdld::Datum::e_DECIMAL64):
return notEqual(left.theDouble(), right.theDecimal64());
case TYPE_PAIR(bdld::Datum::e_DECIMAL64, bdld::Datum::e_DOUBLE):
return notEqual(right.theDouble(), left.theDecimal64());
default: {
bsl::ostringstream error;
error << "Numbers have incompatible types: " << left << " and "
<< right;
throw bdld::Datum::createError(-1, error.str(), d_allocator_p);
}
}
#undef TYPE_PAIR
}
};
} // namespace
#define DISPATCH(FUNCTION) \
switch (bdld::Datum::DataType type = \
normalizeTypes(*args.argsAndOutput, args.allocator)) { \
case bdld::Datum::e_INTEGER: \
return FUNCTION<int>(*args.argsAndOutput, args.allocator); \
case bdld::Datum::e_INTEGER64: \
return FUNCTION<bsls::Types::Int64>(*args.argsAndOutput, \
args.allocator); \
case bdld::Datum::e_DOUBLE: \
return FUNCTION<double>(*args.argsAndOutput, args.allocator); \
default: \
(void)type; \
BSLS_ASSERT(type == bdld::Datum::e_DECIMAL64); \
return FUNCTION<bdldfp::Decimal64>(*args.argsAndOutput, \
args.allocator); \
}
void ArithmeticUtil::add(const NativeProcedureUtil::Arguments& args) {
DISPATCH(homogeneousAdd)
}
void ArithmeticUtil::subtract(const NativeProcedureUtil::Arguments& args) {
if (args.argsAndOutput->empty()) {
throw bdld::Datum::createError(
-1, "substraction requires at least one operand", args.allocator);
}
DISPATCH(homogeneousSubtract)
}
void ArithmeticUtil::multiply(const NativeProcedureUtil::Arguments& args) {
DISPATCH(homogeneousMultiply)
}
void ArithmeticUtil::divide(const NativeProcedureUtil::Arguments& args) {
if (args.argsAndOutput->empty()) {
throw bdld::Datum::createError(
-1, "division requires at least one operand", args.allocator);
}
DISPATCH(homogeneousDivide)
}
#undef DISPATCH
void ArithmeticUtil::equal(const NativeProcedureUtil::Arguments& args) {
if (args.argsAndOutput->empty()) {
throw bdld::Datum::createError(
-1,
"equality comparison requires at least one operand",
args.allocator);
}
if (classify(*args.argsAndOutput).kind ==
Classification::e_ERROR_NON_NUMERIC_TYPE) {
throw bdld::Datum::createError(
-1,
"equality comparison requires all numeric operands",
args.allocator);
}
bool result;
if (args.argsAndOutput->size() == 1) {
result = true;
}
else {
result = std::adjacent_find(args.argsAndOutput->begin(),
args.argsAndOutput->end(),
NotEqual(args.allocator)) ==
args.argsAndOutput->end();
}
args.argsAndOutput->resize(1);
args.argsAndOutput->front() = bdld::Datum::createBoolean(result);
}
} // namespace lspcore
| 18,036 | 5,652 |
#include "echo_server.h"
#include <msgpack/rpc/server.h>
#include <msgpack/rpc/client.h>
#include <cclog/cclog.h>
#include <cclog/cclog_tty.h>
int main(void)
{
cclog::reset(new cclog_tty(cclog::TRACE, std::cout));
signal(SIGPIPE, SIG_IGN);
// run server {
rpc::server svr;
std::auto_ptr<rpc::dispatcher> dp(new myecho);
svr.serve(dp.get());
svr.listen("0.0.0.0", 18811);
svr.start(4);
// }
// create client
rpc::client cli("127.0.0.1", 18811);
// call
std::string msg("MessagePack-RPC");
std::string ret = cli.call("echo", msg).get<std::string>();
std::cout << "call: echo(\"MessagePack-RPC\") = " << ret << std::endl;
return 0;
}
| 658 | 307 |
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "aml-power.h"
#include <lib/device-protocol/pdev.h>
#include <algorithm>
#include <ddk/binding.h>
#include <ddk/debug.h>
#include <ddk/platform-defs.h>
#include <ddk/protocol/platform/device.h>
#include <ddktl/protocol/composite.h>
#include <ddktl/protocol/pwm.h>
#include <fbl/alloc_checker.h>
#include <soc/aml-common/aml-pwm-regs.h>
namespace power {
namespace {
constexpr size_t kFragmentPdev = 0;
constexpr size_t kFragmentPwmBigCluster = 1;
constexpr size_t kFragmentPwmLittleCluster = 2;
constexpr size_t kFragmentCount = 3;
// Sleep for 200 microseconds inorder to let the voltage change
// take effect. Source: Amlogic SDK.
constexpr uint32_t kVoltageSettleTimeUs = 200;
// Step up or down 3 steps in the voltage table while changing
// voltage and not directly. Source: Amlogic SDK
constexpr int kMaxVoltageChangeSteps = 3;
zx_status_t InitPwmProtocolClient(zx_device_t* dev, ddk::PwmProtocolClient* client) {
if (dev == nullptr || client == nullptr) {
zxlogf(ERROR, "%s: neither dev nor client can be null\n", __func__);
return ZX_ERR_INVALID_ARGS;
}
*client = ddk::PwmProtocolClient(dev);
if (client->is_valid() == false) {
zxlogf(ERROR, "%s: failed to get PWM fragment\n", __func__);
return ZX_ERR_INTERNAL;
}
zx_status_t result;
if ((result = client->Enable()) != ZX_OK) {
zxlogf(ERROR, "%s: Could not enable PWM", __func__);
}
return result;
}
bool IsSortedDescending(const std::vector<aml_voltage_table_t>& vt) {
for (size_t i = 0; i < vt.size() - 1; i++) {
if (vt[i].microvolt < vt[i + 1].microvolt)
// Bail early if we find a voltage that isn't strictly descending.
return false;
}
return true;
}
zx_status_t GetAmlVoltageTable(zx_device_t* parent,
std::vector<aml_voltage_table_t>* voltage_table) {
size_t metadata_size;
zx_status_t st =
device_get_metadata_size(parent, DEVICE_METADATA_AML_VOLTAGE_TABLE, &metadata_size);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get Voltage Table size, st = %d", __func__, st);
return st;
}
// The metadata is an array of aml_voltage_table_t so the metadata size must be an
// integer multiple of sizeof(aml_voltage_table_t).
if (metadata_size % (sizeof(aml_voltage_table_t)) != 0) {
zxlogf(
ERROR,
"%s: Metadata size [%lu] was not an integer multiple of sizeof(aml_voltage_table_t) [%lu]",
__func__, metadata_size, sizeof(aml_voltage_table_t));
return ZX_ERR_INTERNAL;
}
const size_t voltage_table_count = metadata_size / sizeof(aml_voltage_table_t);
auto voltage_table_metadata = std::make_unique<aml_voltage_table_t[]>(voltage_table_count);
size_t actual;
st = device_get_metadata(parent, DEVICE_METADATA_AML_VOLTAGE_TABLE, voltage_table_metadata.get(),
metadata_size, &actual);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get Voltage Table, st = %d", __func__, st);
return st;
}
if (actual != metadata_size) {
zxlogf(ERROR, "%s: device_get_metadata expected to read %lu bytes, actual read %lu", __func__,
metadata_size, actual);
return ZX_ERR_INTERNAL;
}
voltage_table->reserve(voltage_table_count);
std::copy(&voltage_table_metadata[0], &voltage_table_metadata[0] + voltage_table_count,
std::back_inserter(*voltage_table));
if (!IsSortedDescending(*voltage_table)) {
zxlogf(ERROR, "%s: Voltage table was not sorted in strictly descending order", __func__);
return ZX_ERR_INTERNAL;
}
return ZX_OK;
}
zx_status_t GetAmlPwmPeriod(zx_device_t* parent, voltage_pwm_period_ns_t* result) {
size_t metadata_size;
zx_status_t st =
device_get_metadata_size(parent, DEVICE_METADATA_AML_PWM_PERIOD_NS, &metadata_size);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get PWM Period Metadata, st = %d", __func__, st);
return st;
}
if (metadata_size != sizeof(*result)) {
zxlogf(ERROR, "%s: Expected PWM Period metadata to be %lu bytes, got %lu", __func__,
sizeof(*result), metadata_size);
return ZX_ERR_INTERNAL;
}
size_t actual;
st = device_get_metadata(parent, DEVICE_METADATA_AML_PWM_PERIOD_NS, result, sizeof(*result),
&actual);
if (actual != sizeof(*result)) {
zxlogf(ERROR, "%s: Expected PWM metadata size = %lu, got %lu", __func__, sizeof(*result),
actual);
}
return st;
}
} // namespace
zx_status_t AmlPower::PowerImplWritePmicCtrlReg(uint32_t index, uint32_t addr, uint32_t value) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t AmlPower::PowerImplReadPmicCtrlReg(uint32_t index, uint32_t addr, uint32_t* value) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t AmlPower::PowerImplDisablePowerDomain(uint32_t index) {
if (index >= num_domains_) {
zxlogf(ERROR, "%s: Requested Disable for a domain that doesn't exist, idx = %u", __func__,
index);
return ZX_ERR_OUT_OF_RANGE;
}
return ZX_OK;
}
zx_status_t AmlPower::PowerImplEnablePowerDomain(uint32_t index) {
if (index >= num_domains_) {
zxlogf(ERROR, "%s: Requested Enable for a domain that doesn't exist, idx = %u", __func__,
index);
return ZX_ERR_OUT_OF_RANGE;
}
return ZX_OK;
}
zx_status_t AmlPower::PowerImplGetPowerDomainStatus(uint32_t index,
power_domain_status_t* out_status) {
if (index >= num_domains_) {
zxlogf(ERROR,
"%s: Requested PowerImplGetPowerDomainStatus for a domain that doesn't exist, idx = %u",
__func__, index);
return ZX_ERR_OUT_OF_RANGE;
}
if (out_status == nullptr) {
zxlogf(ERROR, "%s: out_status must not be null", __func__);
return ZX_ERR_INVALID_ARGS;
}
// All domains are always enabled.
*out_status = POWER_DOMAIN_STATUS_ENABLED;
return ZX_OK;
}
zx_status_t AmlPower::PowerImplGetSupportedVoltageRange(uint32_t index, uint32_t* min_voltage,
uint32_t* max_voltage) {
if (index >= num_domains_) {
zxlogf(ERROR,
"%s: Requested GetSupportedVoltageRange for a domain that doesn't exist, idx = %u",
__func__, index);
return ZX_ERR_OUT_OF_RANGE;
}
// Voltage table is sorted in descending order so the minimum voltage is the last element and the
// maximum voltage is the first element.
*min_voltage = voltage_table_.back().microvolt;
*max_voltage = voltage_table_.front().microvolt;
return ZX_OK;
}
zx_status_t AmlPower::RequestVoltage(const ddk::PwmProtocolClient& pwm, uint32_t u_volts,
int* current_voltage_index) {
// Find the largest voltage that does not exceed u_volts.
const aml_voltage_table_t target_voltage = {.microvolt = u_volts, .duty_cycle = 0};
const auto& target =
std::lower_bound(voltage_table_.begin(), voltage_table_.end(), target_voltage,
[](const aml_voltage_table_t& l, const aml_voltage_table_t& r) {
return l.microvolt > r.microvolt;
});
if (target == voltage_table_.end()) {
zxlogf(ERROR, "%s: Could not find a voltage less than or equal to %u\n", __func__, u_volts);
return ZX_ERR_NOT_SUPPORTED;
}
size_t target_idx = target - voltage_table_.begin();
if (target_idx >= INT_MAX || target_idx >= voltage_table_.size()) {
zxlogf(ERROR, "%s: voltage target index out of bounds", __func__);
return ZX_ERR_OUT_OF_RANGE;
}
int target_index = static_cast<int>(target_idx);
zx_status_t status = ZX_OK;
// If this is the first time we are setting up the voltage
// we directly set it.
if (*current_voltage_index == kInvalidIndex) {
// Update new duty cycle.
aml_pwm::mode_config on = {aml_pwm::ON, {}};
pwm_config_t cfg = {false, pwm_period_, static_cast<float>(target->duty_cycle), &on,
sizeof(on)};
if ((status = pwm.SetConfig(&cfg)) != ZX_OK) {
zxlogf(ERROR, "%s: Could not initialize PWM", __func__);
return status;
}
usleep(kVoltageSettleTimeUs);
*current_voltage_index = target_index;
return ZX_OK;
}
// Otherwise we adjust to the target voltage step by step.
while (*current_voltage_index != target_index) {
if (*current_voltage_index < target_index) {
if (*current_voltage_index < target_index - kMaxVoltageChangeSteps) {
// Step up by 3 in the voltage table.
*current_voltage_index += kMaxVoltageChangeSteps;
} else {
*current_voltage_index = target_index;
}
} else {
if (*current_voltage_index > target_index + kMaxVoltageChangeSteps) {
// Step down by 3 in the voltage table.
*current_voltage_index -= kMaxVoltageChangeSteps;
} else {
*current_voltage_index = target_index;
}
}
// Update new duty cycle.
aml_pwm::mode_config on = {aml_pwm::ON, {}};
pwm_config_t cfg = {false, pwm_period_,
static_cast<float>(voltage_table_[*current_voltage_index].duty_cycle), &on,
sizeof(on)};
if ((status = pwm.SetConfig(&cfg)) != ZX_OK) {
zxlogf(ERROR, "%s: Could not initialize PWM", __func__);
return status;
}
usleep(kVoltageSettleTimeUs);
}
return ZX_OK;
}
zx_status_t AmlPower::PowerImplRequestVoltage(uint32_t index, uint32_t voltage,
uint32_t* actual_voltage) {
if (index >= num_domains_) {
zxlogf(ERROR, "%s: Requested voltage for a range that doesn't exist, idx = %u", __func__,
index);
return ZX_ERR_OUT_OF_RANGE;
}
zx_status_t st = ZX_ERR_OUT_OF_RANGE;
if (index == kBigClusterDomain) {
st = RequestVoltage(big_cluster_pwm_.value(), voltage, ¤t_big_cluster_voltage_index_);
if (st == ZX_OK) {
*actual_voltage = voltage_table_[current_big_cluster_voltage_index_].microvolt;
}
} else if (index == kLittleClusterDomain) {
st = RequestVoltage(little_cluster_pwm_.value(), voltage,
¤t_little_cluster_voltage_index_);
if (st == ZX_OK) {
*actual_voltage = voltage_table_[current_little_cluster_voltage_index_].microvolt;
}
}
return st;
}
zx_status_t AmlPower::PowerImplGetCurrentVoltage(uint32_t index, uint32_t* current_voltage) {
if (index >= num_domains_) {
zxlogf(ERROR, "%s: Requested voltage for a range that doesn't exist, idx = %u", __func__,
index);
return ZX_ERR_OUT_OF_RANGE;
}
switch (index) {
case kBigClusterDomain:
if (current_big_cluster_voltage_index_ == kInvalidIndex)
return ZX_ERR_BAD_STATE;
*current_voltage = voltage_table_[current_big_cluster_voltage_index_].microvolt;
break;
case kLittleClusterDomain:
if (current_little_cluster_voltage_index_ == kInvalidIndex)
return ZX_ERR_BAD_STATE;
*current_voltage = voltage_table_[current_little_cluster_voltage_index_].microvolt;
break;
default:
return ZX_ERR_OUT_OF_RANGE;
}
return ZX_OK;
}
void AmlPower::DdkRelease() { delete this; }
void AmlPower::DdkUnbindNew(ddk::UnbindTxn txn) { txn.Reply(); }
zx_status_t AmlPower::Create(void* ctx, zx_device_t* parent) {
zx_status_t st;
ddk::CompositeProtocolClient composite(parent);
if (!composite.is_valid()) {
zxlogf(ERROR, "%s: failed to get composite protocol\n", __func__);
return ZX_ERR_INTERNAL;
}
// We may get 2 or 3 fragments depending upon the number of power domains that this
// core supports.
size_t actual;
zx_device_t* fragments[kFragmentCount];
composite.GetFragments(fragments, kFragmentCount, &actual);
if (actual < 1) {
zxlogf(ERROR, "%s: failed to get pdev fragment", __func__);
return ZX_ERR_INTERNAL;
}
ddk::PDev pdev(fragments[kFragmentPdev]);
if (!pdev.is_valid()) {
zxlogf(ERROR, "%s: failed to get pdev protocol", __func__);
return ZX_ERR_INTERNAL;
}
pdev_device_info_t device_info;
st = pdev.GetDeviceInfo(&device_info);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: failed to get DeviceInfo, st = %d", __func__, st);
return st;
}
std::vector<aml_voltage_table_t> voltage_table;
st = GetAmlVoltageTable(parent, &voltage_table);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get aml voltage table, st = %d", __func__, st);
return st;
}
voltage_pwm_period_ns_t pwm_period;
st = GetAmlPwmPeriod(parent, &pwm_period);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get aml pwm period table, st = %d", __func__, st);
return st;
}
std::optional<ddk::PwmProtocolClient> big_cluster_pwm;
if (actual > kFragmentPwmBigCluster) {
ddk::PwmProtocolClient client;
st = InitPwmProtocolClient(fragments[kFragmentPwmBigCluster], &client);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to initialize Big Cluster PWM Client, st = %d", __func__, st);
return st;
}
big_cluster_pwm = client;
} else {
zxlogf(ERROR, "%s: Failed to get big cluster pwm", __func__);
return ZX_ERR_INTERNAL;
}
std::optional<ddk::PwmProtocolClient> little_cluster_pwm;
if (actual > kFragmentPwmLittleCluster) {
ddk::PwmProtocolClient client;
st = InitPwmProtocolClient(fragments[kFragmentPwmLittleCluster], &client);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to initialize Little Cluster PWM Client, st = %d", __func__, st);
return st;
}
little_cluster_pwm = client;
}
auto power_impl_device =
std::make_unique<AmlPower>(parent, std::move(big_cluster_pwm), std::move(little_cluster_pwm),
std::move(voltage_table), pwm_period);
st = power_impl_device->DdkAdd("power-impl", DEVICE_ADD_ALLOW_MULTI_COMPOSITE);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: DdkAdd failed, st = %d", __func__, st);
}
// Let device runner take ownership of this object.
__UNUSED auto* dummy = power_impl_device.release();
return st;
}
static constexpr zx_driver_ops_t aml_power_driver_ops = []() {
zx_driver_ops_t driver_ops = {};
driver_ops.version = DRIVER_OPS_VERSION;
driver_ops.bind = AmlPower::Create;
// driver_ops.run_unit_tests = run_test; # TODO(gkalsi).
return driver_ops;
}();
} // namespace power
// clang-format off
ZIRCON_DRIVER_BEGIN(aml_power, power::aml_power_driver_ops, "zircon", "0.1", 4)
BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_COMPOSITE),
BI_ABORT_IF(NE, BIND_PLATFORM_DEV_VID, PDEV_VID_AMLOGIC),
BI_ABORT_IF(NE, BIND_PLATFORM_DEV_DID, PDEV_DID_AMLOGIC_POWER),
// The following are supported SoCs
BI_MATCH_IF(EQ, BIND_PLATFORM_DEV_PID, PDEV_PID_AMLOGIC_S905D2),
// TODO(gkalsi): Support the following two AMLogic SoCs
// BI_MATCH_IF(EQ, BIND_PLATFORM_DEV_PID, PDEV_PID_AMLOGIC_T931),
// BI_MATCH_IF(EQ, BIND_PLATFORM_DEV_PID, PDEV_PID_AMLOGIC_S905D3),
ZIRCON_DRIVER_END(aml_power)
//clang-format on
| 15,046 | 5,737 |
/**********************************************************************
* Copyright (c) 2008-2016, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef PROJECT_ANALYSISRECORD_HPP
#define PROJECT_ANALYSISRECORD_HPP
#include "ProjectAPI.hpp"
#include "ObjectRecord.hpp"
namespace openstudio {
namespace analysis {
class Analysis;
} // analysis
namespace project {
class ProblemRecord;
class AlgorithmRecord;
class FileReferenceRecord;
class DataPointRecord;
namespace detail {
class AnalysisRecord_Impl;
} // detail
/** \class AnalysisRecordColumns
* \brief Column definitions for the AnalysisRecords table.
* \details See the OPENSTUDIO_ENUM documentation in utilities/core/Enum.hpp. The actual
* macro call is:
* \code
OPENSTUDIO_ENUM( AnalysisRecordColumns,
((id)(INTEGER PRIMARY KEY)(0))
((handle)(TEXT)(1))
((name)(TEXT)(2))
((displayName)(TEXT)(3))
((description)(TEXT)(4))
((timestampCreate)(TEXT)(5))
((timestampLast)(TEXT)(6))
((uuidLast)(TEXT)(7))
((problemRecordId)(INTEGER)(8))
((algorithmRecordId)(INTEGER)(9))
((seedFileReferenceRecordId)(INTEGER)(10))
((weatherFileReferenceRecordId)(INTEGER)(11))
((resultsAreInvalid)(BOOLEAN)(12))
((dataPointsAreInvalid)(BOOLEAN)(13))
);
* \endcode */
OPENSTUDIO_ENUM( AnalysisRecordColumns,
((id)(INTEGER PRIMARY KEY)(0))
((handle)(TEXT)(1))
((name)(TEXT)(2))
((displayName)(TEXT)(3))
((description)(TEXT)(4))
((timestampCreate)(TEXT)(5))
((timestampLast)(TEXT)(6))
((uuidLast)(TEXT)(7))
((problemRecordId)(INTEGER)(8))
((algorithmRecordId)(INTEGER)(9))
((seedFileReferenceRecordId)(INTEGER)(10))
((weatherFileReferenceRecordId)(INTEGER)(11))
((resultsAreInvalid)(BOOLEAN)(12))
((dataPointsAreInvalid)(BOOLEAN)(13))
);
/** AnalysisRecord is a ObjectRecord*/
class PROJECT_API AnalysisRecord : public ObjectRecord {
public:
typedef detail::AnalysisRecord_Impl ImplType;
typedef AnalysisRecordColumns ColumnsType;
typedef AnalysisRecord ObjectRecordType;
/** @name Constructors and Destructors */
//@{
AnalysisRecord(const analysis::Analysis& analysis, ProjectDatabase& database);
AnalysisRecord(const QSqlQuery& query, ProjectDatabase& database);
virtual ~AnalysisRecord() {}
//@}
static std::string databaseTableName();
static UpdateByIdQueryData updateByIdQueryData();
static void updatePathData(ProjectDatabase database,
const openstudio::path& originalBase,
const openstudio::path& newBase);
static boost::optional<AnalysisRecord> factoryFromQuery(const QSqlQuery& query,
ProjectDatabase& database);
static std::vector<AnalysisRecord> getAnalysisRecords(ProjectDatabase& database);
static boost::optional<AnalysisRecord> getAnalysisRecord(int id, ProjectDatabase& database);
/** @name Getters */
//@{
/** Returns the ProblemRecord (required resource) associated with this AnalysisRecord. */
ProblemRecord problemRecord() const;
/** Returns the AlgorithmRecord (optional resource) associated with this AnalysisRecord. */
boost::optional<AlgorithmRecord> algorithmRecord() const;
/** Returns the seed FileReferenceRecord (required child) of this AnalysisRecord. */
FileReferenceRecord seedFileReferenceRecord() const;
/** Returns the weather FileReferenceRecord (optional child) of this AnalysisRecord. */
boost::optional<FileReferenceRecord> weatherFileReferenceRecord() const;
/** Returns the \link DataPointRecord DataPointRecords \endlink (children) of this
* AnalysisRecord. */
std::vector<DataPointRecord> dataPointRecords() const;
/** Returns the DataPointRecords with complete == false. */
std::vector<DataPointRecord> incompleteDataPointRecords() const;
/** Returns the DataPointRecords with complete == true. */
std::vector<DataPointRecord> completeDataPointRecords() const;
/** Returns the completeDataPointRecords with failed == false. */
std::vector<DataPointRecord> successfulDataPointRecords() const;
/** Returns the completeDataPointRecords with failed == true. */
std::vector<DataPointRecord> failedDataPointRecords() const;
std::vector<DataPointRecord> getDataPointRecords(
const std::vector<QVariant>& variableValues) const;
std::vector<DataPointRecord> getDataPointRecords(
const std::vector<int>& discretePerturbationRecordIds) const;
std::vector<DataPointRecord> getDataPointRecords(const std::string& tag) const;
/** Returns true if this AnalysisRecord holds DataPointRecords with invalid results still
* attached. */
bool resultsAreInvalid() const;
/** Returns true if this AnalysisRecord holds DataPointRecords that are invalid in light of
* changes to the problem formulation. */
bool dataPointsAreInvalid() const;
/** Deserializes this record and all its children and resources to analysis::Analysis. */
analysis::Analysis analysis() const;
//@}
/** @name Setters */
//@{
/** Provided for callers operating directly on the database, not holding a copy of this
* analysis in memory. Use with caution. */
void setResultsAreInvalid(bool value);
/** Provided for callers operating directly on the database, not holding a copy of this
* analysis in memory. Use with caution. */
void setDataPointsAreInvalid(bool value);
//@}
protected:
/// @cond
friend class Record;
friend class ProjectDatabase;
friend class detail::AnalysisRecord_Impl;
/** Construct from impl. */
AnalysisRecord(std::shared_ptr<detail::AnalysisRecord_Impl> impl,
ProjectDatabase database);
/// Construct from impl. Does not register in the database, so use with caution.
explicit AnalysisRecord(std::shared_ptr<detail::AnalysisRecord_Impl> impl);
/// @endcond
private:
REGISTER_LOGGER("openstudio.project.AnalysisRecord");
void removeDataPointRecords(const std::vector<UUID>& uuidsToKeep,
ProjectDatabase& database);
};
/** \relates AnalysisRecord*/
typedef boost::optional<AnalysisRecord> OptionalAnalysisRecord;
/** \relates AnalysisRecord*/
typedef std::vector<AnalysisRecord> AnalysisRecordVector;
} // project
} // openstudio
#endif // PROJECT_ANALYSISRECORD_HPP
| 7,084 | 2,027 |
#include "Shader.h"
#include <fstream>
#include <iostream>
using namespace std;
namespace DDG
{
Shader::Shader( void )
// constructor -- shader is initially invalid
: vertexShader( 0 ),
fragmentShader( 0 ),
geometryShader( 0 ),
program( 0 ),
linked( false )
{}
Shader::~Shader( void )
{
if( program ) glDeleteProgram( program );
if( vertexShader ) glDeleteShader( vertexShader );
if( fragmentShader ) glDeleteShader( fragmentShader );
if( geometryShader ) glDeleteShader( geometryShader );
}
void Shader::loadVertex( const char* filename )
{
load( GL_VERTEX_SHADER, filename, vertexShader );
}
void Shader::loadFragment( const char* filename )
{
load( GL_FRAGMENT_SHADER, filename, fragmentShader );
}
void Shader::loadGeometry( const char* filename )
{
#ifdef GL_GEOMETRY_SHADER_EXT
load( GL_GEOMETRY_SHADER_EXT, filename, geometryShader );
#else
cerr << "Error: geometry shaders not supported!" << endl;
#endif
}
void Shader::enable( void )
{
if( !linked )
{
glLinkProgram( program );
linked = true;
}
glUseProgram( program );
}
void Shader::disable( void ) const
{
glUseProgram( 0 );
}
Shader::operator GLuint( void ) const
{
return program;
}
void Shader::load( GLenum shaderType, const char* filename, GLuint& shader )
// read vertex shader from GLSL source file, compile, and attach to program
{
string source;
if( !readSource( filename, source ))
{
return;
}
if( program == 0 )
{
program = glCreateProgram();
}
if( shader != 0 )
{
glDetachShader( program, shader );
}
shader = glCreateShader( shaderType );
const char* source_c_str = source.c_str();
glShaderSource( shader, 1, &(source_c_str), NULL );
glCompileShader( shader );
GLint compileStatus;
glGetShaderiv( shader, GL_COMPILE_STATUS, &compileStatus );
if( compileStatus == GL_TRUE )
{
glAttachShader( program, shader );
linked = false;
}
else
{
GLsizei maxLength = 0;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &maxLength );
if( maxLength > 0 )
{
GLchar* infoLog = new char[ maxLength ];
GLsizei length;
glGetShaderInfoLog( shader, maxLength, &length, infoLog );
cerr << "GLSL Error: " << infoLog << endl;
delete[] infoLog;
}
}
}
bool Shader::readSource( const char* filename, std::string& source )
// reads GLSL source file into a string
{
source = "";
ifstream in( filename );
if( !in.is_open() )
{
cerr << "Error: could not open shader file ";
cerr << filename;
cerr << " for input!" << endl;
return false;
}
string line;
while( getline( in, line ))
{
source += line;
}
return true;
}
}
| 3,148 | 1,023 |
// SPDX-License-Identifier: MIT
/*
* Copyright 2006-2012 Red Hat, Inc.
* Copyright 2018-2021 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
*
* Author: Adam Jackson <ajax@nwnk.net>
* Maintainer: Hans Verkuil <hverkuil-cisco@xs4all.nl>
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "edid-decode.h"
#define CELL_GRAN 8.0
#define MARGIN_PERC 1.8
#define GTF_MIN_PORCH 1.0
#define GTF_V_SYNC_RQD 3.0
#define GTF_H_SYNC_PERC 8.0
#define GTF_MIN_VSYNC_BP 550.0
timings edid_state::calc_gtf_mode(unsigned h_pixels, unsigned v_lines,
double ip_freq_rqd, bool int_rqd,
enum gtf_ip_parm ip_parm, bool margins_rqd,
bool secondary, double C, double M, double K, double J)
{
timings t = {};
/* C' and M' are part of the Blanking Duty Cycle computation */
double C_PRIME = ((C - J) * K / 256.0) + J;
double M_PRIME = K / 256.0 * M;
double h_pixels_rnd = round(h_pixels / CELL_GRAN) * CELL_GRAN;
double v_lines_rnd = int_rqd ? round(v_lines / 2.0) : v_lines;
unsigned hor_margin = margins_rqd ?
round(h_pixels_rnd * MARGIN_PERC / 100.0 / CELL_GRAN) * CELL_GRAN : 0;
unsigned vert_margin = margins_rqd ? round(MARGIN_PERC / 100.0 * v_lines_rnd) : 0;
double interlace = int_rqd ? 0.5 : 0;
double total_active_pixels = h_pixels_rnd + hor_margin * 2;
t.hact = h_pixels_rnd;
t.vact = v_lines;
t.interlaced = int_rqd;
double pixel_freq;
double h_blank_pixels;
double total_pixels;
double v_sync_bp;
if (ip_parm == gtf_ip_vert_freq) {
// vertical frame frequency (Hz)
double v_field_rate_rqd = int_rqd ? ip_freq_rqd * 2 : ip_freq_rqd;
double h_period_est = ((1.0 / v_field_rate_rqd) - GTF_MIN_VSYNC_BP / 1000000.0) /
(v_lines_rnd + vert_margin * 2 + GTF_MIN_PORCH + interlace) * 1000000.0;
v_sync_bp = round(GTF_MIN_VSYNC_BP / h_period_est);
double total_v_lines = v_lines_rnd + vert_margin * 2 +
v_sync_bp + interlace + GTF_MIN_PORCH;
double v_field_rate_est = 1.0 / h_period_est / total_v_lines * 1000000.0;
double h_period = h_period_est / (v_field_rate_rqd / v_field_rate_est);
double ideal_duty_cycle = C_PRIME - (M_PRIME * h_period / 1000.0);
h_blank_pixels = round(total_active_pixels * ideal_duty_cycle /
(100.0 - ideal_duty_cycle) /
(2 * CELL_GRAN)) * 2 * CELL_GRAN;
total_pixels = total_active_pixels + h_blank_pixels;
pixel_freq = total_pixels / h_period;
} else if (ip_parm == gtf_ip_hor_freq) {
// horizontal frequency (kHz)
double h_freq = ip_freq_rqd;
v_sync_bp = round(GTF_MIN_VSYNC_BP * h_freq / 1000.0);
double ideal_duty_cycle = C_PRIME - (M_PRIME / h_freq);
h_blank_pixels = round(total_active_pixels * ideal_duty_cycle /
(100.0 - ideal_duty_cycle) /
(2 * CELL_GRAN)) * 2 * CELL_GRAN;
total_pixels = total_active_pixels + h_blank_pixels;
pixel_freq = total_pixels * h_freq / 1000.0;
} else {
// pixel clock rate (MHz)
pixel_freq = ip_freq_rqd;
double ideal_h_period =
((C_PRIME - 100.0) +
sqrt(((100.0 - C_PRIME) * (100.0 - C_PRIME) +
(0.4 * M_PRIME * (total_active_pixels + hor_margin * 2) /
pixel_freq)))) / 2.0 / M_PRIME * 1000.0;
double ideal_duty_cycle = C_PRIME - (M_PRIME * ideal_h_period) / 1000.0;
h_blank_pixels = round(total_active_pixels * ideal_duty_cycle /
(100.0 - ideal_duty_cycle) /
(2 * CELL_GRAN)) * 2 * CELL_GRAN;
total_pixels = total_active_pixels + h_blank_pixels;
double h_freq = pixel_freq / total_pixels * 1000.0;
v_sync_bp = round(GTF_MIN_VSYNC_BP * h_freq / 1000.0);
}
double v_back_porch = v_sync_bp - GTF_V_SYNC_RQD;
t.vbp = v_back_porch;
t.vsync = GTF_V_SYNC_RQD;
t.vfp = GTF_MIN_PORCH;
t.pixclk_khz = round(1000.0 * pixel_freq);
t.hsync = round(GTF_H_SYNC_PERC / 100.0 * total_pixels / CELL_GRAN) * CELL_GRAN;
t.hfp = (h_blank_pixels / 2.0) - t.hsync;
t.hbp = t.hfp + t.hsync;
t.hborder = hor_margin;
t.vborder = vert_margin;
t.pos_pol_hsync = secondary;
t.pos_pol_vsync = !secondary;
t.rb = secondary ? RB_GTF : RB_NONE;
return t;
}
void edid_state::edid_gtf_mode(unsigned refresh, struct timings &t)
{
unsigned hratio = t.hratio;
unsigned vratio = t.vratio;
t = calc_gtf_mode(t.hact, t.vact, refresh, t.interlaced);
t.hratio = hratio;
t.vratio = vratio;
}
#define CVT_MIN_VSYNC_BP 550.0
#define CVT_MIN_V_PORCH 3
/* Minimum vertical backporch for CVT and CVT RBv1 */
#define CVT_MIN_V_BPORCH 7
/* Fixed vertical backporch for CVT RBv2 and RBv3 */
#define CVT_FIXED_V_BPORCH 6
#define CVT_C_PRIME 30.0
#define CVT_M_PRIME 300.0
#define CVT_RB_MIN_VBLANK 460.0
// If rb == RB_CVT_V2, then alt means video-optimized (i.e. 59.94 instead of 60 Hz, etc.).
// If rb == RB_CVT_V3, then alt means that rb_h_blank is 160 instead of 80.
timings edid_state::calc_cvt_mode(unsigned h_pixels, unsigned v_lines,
double ip_freq_rqd, unsigned rb, bool int_rqd,
bool margins_rqd, bool alt, unsigned rb_h_blank,
double add_vert_time)
{
timings t = {};
t.hact = h_pixels;
t.vact = v_lines;
t.interlaced = int_rqd;
double cell_gran = rb == RB_CVT_V2 ? 1 : CELL_GRAN;
double h_pixels_rnd = floor(h_pixels / cell_gran) * cell_gran;
double v_lines_rnd = int_rqd ? floor(v_lines / 2.0) : v_lines;
unsigned hor_margin = margins_rqd ?
floor((h_pixels_rnd * MARGIN_PERC / 100.0) / cell_gran) * cell_gran : 0;
unsigned vert_margin = margins_rqd ? floor(MARGIN_PERC / 100.0 * v_lines_rnd) : 0;
double interlace = int_rqd ? 0.5 : 0;
double total_active_pixels = h_pixels_rnd + hor_margin * 2;
double v_field_rate_rqd = int_rqd ? ip_freq_rqd * 2 : ip_freq_rqd;
double clock_step = rb == RB_CVT_V2 ? 0.001 : 0.25;
double h_blank = (rb == RB_CVT_V1 || (rb == RB_CVT_V3 && alt)) ? 160 : 80;
double rb_v_fporch = rb == RB_CVT_V1 ? 3 : 1;
double refresh_multiplier = (rb == RB_CVT_V2 && alt) ? 1000.0 / 1001.0 : 1;
double rb_min_vblank = CVT_RB_MIN_VBLANK;
double h_sync = 32;
double v_sync;
double pixel_freq;
double v_blank;
double v_sync_bp;
if (rb == RB_CVT_V3 && add_vert_time) {
if (add_vert_time + rb_min_vblank <= 1000000.0 / ip_freq_rqd / 4.0)
rb_min_vblank += add_vert_time;
}
if (rb == RB_CVT_V3 && rb_h_blank) {
h_blank = rb_h_blank & ~7;
if (h_blank < 80)
h_blank = 80;
else if (h_blank > 200)
h_blank = 200;
}
/* Determine VSync Width from aspect ratio */
if ((t.vact * 4 / 3) == t.hact)
v_sync = 4;
else if ((t.vact * 16 / 9) == t.hact)
v_sync = 5;
else if ((t.vact * 16 / 10) == t.hact)
v_sync = 6;
else if (!(t.vact % 4) && ((t.vact * 5 / 4) == t.hact))
v_sync = 7;
else if ((t.vact * 15 / 9) == t.hact)
v_sync = 7;
else /* Custom */
v_sync = 10;
if (rb >= RB_CVT_V2)
v_sync = 8;
if (rb == RB_NONE) {
double h_period_est = ((1.0 / v_field_rate_rqd) - CVT_MIN_VSYNC_BP / 1000000.0) /
(v_lines_rnd + vert_margin * 2 + CVT_MIN_V_PORCH + interlace) * 1000000.0;
v_sync_bp = floor(CVT_MIN_VSYNC_BP / h_period_est) + 1;
if (v_sync_bp < v_sync + CVT_MIN_V_BPORCH)
v_sync_bp = v_sync + CVT_MIN_V_BPORCH;
v_blank = v_sync_bp + CVT_MIN_V_PORCH;
double ideal_duty_cycle = CVT_C_PRIME - (CVT_M_PRIME * h_period_est / 1000.0);
if (ideal_duty_cycle < 20)
ideal_duty_cycle = 20;
h_blank = floor(total_active_pixels * ideal_duty_cycle /
(100.0 - ideal_duty_cycle) /
(2 * CELL_GRAN)) * 2 * CELL_GRAN;
double total_pixels = total_active_pixels + h_blank;
h_sync = floor(total_pixels * 0.08 / CELL_GRAN) * CELL_GRAN;
pixel_freq = floor((total_pixels / h_period_est) / clock_step) * clock_step;
} else {
double h_period_est = ((1000000.0 / v_field_rate_rqd) - rb_min_vblank) /
(v_lines_rnd + vert_margin * 2);
double vbi_lines = floor(rb_min_vblank / h_period_est) + 1;
double rb_min_vbi = rb_v_fporch + v_sync +
(rb == RB_CVT_V1 ? CVT_MIN_V_BPORCH : CVT_FIXED_V_BPORCH);
v_blank = vbi_lines < rb_min_vbi ? rb_min_vbi : vbi_lines;
double total_v_lines = v_blank + v_lines_rnd + vert_margin * 2 + interlace;
if (rb == RB_CVT_V1)
v_sync_bp = v_blank - rb_v_fporch;
else
v_sync_bp = v_sync + CVT_FIXED_V_BPORCH;
double total_pixels = h_blank + total_active_pixels;
double freq = v_field_rate_rqd * total_v_lines * total_pixels * refresh_multiplier;
if (rb == RB_CVT_V3)
pixel_freq = ceil((freq / 1000000.0) / clock_step) * clock_step;
else
pixel_freq = floor((freq / 1000000.0) / clock_step) * clock_step;
}
t.vbp = v_sync_bp - v_sync;
t.vsync = v_sync;
t.vfp = v_blank - t.vbp - t.vsync;
t.pixclk_khz = round(1000.0 * pixel_freq);
t.hsync = h_sync;
if (rb == RB_CVT_V3)
t.hfp = 8;
else
t.hfp = (h_blank / 2.0) - t.hsync;
t.hbp = h_blank - t.hfp - t.hsync;
t.hborder = hor_margin;
t.vborder = vert_margin;
t.rb = rb;
if (alt && (rb == RB_CVT_V2 || rb == RB_CVT_V3))
t.rb |= RB_ALT;
t.pos_pol_hsync = t.rb;
t.pos_pol_vsync = !t.rb;
calc_ratio(&t);
return t;
}
void edid_state::edid_cvt_mode(unsigned refresh, struct timings &t, unsigned rb_h_blank,
double add_vert_time)
{
unsigned hratio = t.hratio;
unsigned vratio = t.vratio;
t = calc_cvt_mode(t.hact, t.vact, refresh, t.rb & ~RB_ALT, t.interlaced,
false, t.rb & RB_ALT, rb_h_blank, add_vert_time);
t.hratio = hratio;
t.vratio = vratio;
}
| 9,205 | 4,818 |
#include <iostream>
#include <cstring>
using namespace std;
// class declaration
class Node
{
public:
char data;
Node *next;
} *head = NULL;
void append(char data)
{
// adds the element to the top of Stack
Node *newnode = new Node();
newnode->data = data;
newnode->next = NULL;
if (head == NULL)
{
head = newnode;
}
else
{
newnode->next = head;
head = newnode;
}
}
char poptop()
{
// removes and returns the top of stack
char val = head->data;
Node *temp = head;
head = head->next;
temp->next = NULL;
free(temp);
return val;
}
int main()
{
string s;
cin >> s;
for (char a : s)
{
if (a == ')')
{
int flag = 0;
char t = poptop();
while (t != '(')
{
// removes all character till opening paranthesis
if (strchr("+-*/", t))
{
flag = 1;
}
t = poptop();
}
if (flag == 0)
{
cout << "Yes";
return 0;
}
}
else
{
append(a);
}
}
cout << "No";
return 0;
} | 1,263 | 392 |
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-20 Bradley M. Bell
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
# include <cppad/core/graph/cpp_graph.hpp>
# include <cppad/local/graph/json_lexer.hpp>
# include <cppad/local/define.hpp>
# include <cppad/local/atomic_index.hpp>
# include <cppad/utility/to_string.hpp>
// documentation for this routine is in the file below
# include <cppad/local/graph/json_parser.hpp>
void CppAD::local::graph::json_parser(
const std::string& json ,
cpp_graph& graph_obj )
{ using std::string;
//
//
// match_any_string
const string match_any_string = "";
//
// initilize atomic_name_vec
graph_obj.initialize();
//
// The values in this vector will be set while parsing op_define_vec.
// Note that the values in op_code2enum[0] are not used.
CppAD::vector<graph_op_enum> op_code2enum(1);
//
// -----------------------------------------------------------------------
// json_lexer constructor checks for { at beginning
CppAD::local::graph::json_lexer json_lexer(json);
//
// "function_name" : function_name
json_lexer.check_next_string("function_name");
json_lexer.check_next_char(':');
json_lexer.check_next_string(match_any_string);
std::string function_name = json_lexer.token();
graph_obj.function_name_set(function_name);
json_lexer.set_function_name(function_name);
json_lexer.check_next_char(',');
//
// -----------------------------------------------------------------------
// "op_define_vec" : [ n_define, [
json_lexer.check_next_string("op_define_vec");
json_lexer.check_next_char(':');
json_lexer.check_next_char('[');
//
json_lexer.next_non_neg_int();
size_t n_define = json_lexer.token2size_t();
json_lexer.check_next_char(',');
//
json_lexer.check_next_char('[');
for(size_t i = 0; i < n_define; ++i)
{ // {
json_lexer.check_next_char('{');
//
// "op_code" : op_code,
json_lexer.check_next_string("op_code");
json_lexer.check_next_char(':');
json_lexer.next_non_neg_int();
# ifndef NDEBUG
size_t op_code = json_lexer.token2size_t();
CPPAD_ASSERT_UNKNOWN( op_code == op_code2enum.size() );
# endif
json_lexer.check_next_char(',');
//
// "name" : name
json_lexer.check_next_string("name");
json_lexer.check_next_char(':');
json_lexer.check_next_string(match_any_string);
string name = json_lexer.token();
graph_op_enum op_enum = op_name2enum[name];
# if ! CPPAD_USE_CPLUSPLUS_2011
switch( op_enum )
{
case acosh_graph_op:
case asinh_graph_op:
case atanh_graph_op:
case erf_graph_op:
case erfc_graph_op:
case expm1_graph_op:
case log1p_graph_op:
{ string expected = "a C++98 function";
string found = name + " which is a C++11 function.";
json_lexer.report_error(expected, found);
}
break;
default:
break;
}
# endif
//
// op_code2enum for this op_code
op_code2enum.push_back(op_enum);
//
size_t n_arg = op_enum2fixed_n_arg[op_enum];
if( n_arg > 0 )
{ // , "narg" : n_arg
json_lexer.check_next_char(',');
json_lexer.check_next_string("n_arg");
json_lexer.check_next_char(':');
json_lexer.next_non_neg_int();
if( n_arg != json_lexer.token2size_t() )
{ string expected = CppAD::to_string(n_arg);
string found = json_lexer.token();
json_lexer.report_error(expected, found);
}
}
json_lexer.check_next_char('}');
//
// , (if not last entry)
if( i + 1 < n_define )
json_lexer.check_next_char(',');
}
json_lexer.check_next_char(']');
// ],
json_lexer.check_next_char(']');
json_lexer.check_next_char(',');
//
// -----------------------------------------------------------------------
// "n_dynamic_ind" : n_dynamic_ind ,
json_lexer.check_next_string("n_dynamic_ind");
json_lexer.check_next_char(':');
//
json_lexer.next_non_neg_int();
size_t n_dynamic_ind = json_lexer.token2size_t();
graph_obj.n_dynamic_ind_set(n_dynamic_ind);
//
json_lexer.check_next_char(',');
// -----------------------------------------------------------------------
// "n_variable_ind" : n_variable_ind ,
json_lexer.check_next_string("n_variable_ind");
json_lexer.check_next_char(':');
//
json_lexer.next_non_neg_int();
size_t n_variable_ind = json_lexer.token2size_t();
graph_obj.n_variable_ind_set(n_variable_ind);
//
json_lexer.check_next_char(',');
// -----------------------------------------------------------------------
// "constant_vec": [ n_constant, [ first_constant, ..., last_constant ] ],
json_lexer.check_next_string("constant_vec");
json_lexer.check_next_char(':');
json_lexer.check_next_char('[');
//
json_lexer.next_non_neg_int();
size_t n_constant = json_lexer.token2size_t();
//
json_lexer.check_next_char(',');
//
// [ first_constant, ... , last_constant ]
json_lexer.check_next_char('[');
for(size_t i = 0; i < n_constant; ++i)
{ json_lexer.next_float();
graph_obj.constant_vec_push_back( json_lexer.token2double() );
//
if( i + 1 < n_constant )
json_lexer.check_next_char(',');
}
json_lexer.check_next_char(']');
json_lexer.check_next_char(']');
json_lexer.check_next_char(',');
// -----------------------------------------------------------------------
// "op_usage_vec": [ n_usage, [ first_op_usage, ..., last_op_usage ] ],
json_lexer.check_next_string("op_usage_vec");
json_lexer.check_next_char(':');
json_lexer.check_next_char('[');
//
json_lexer.next_non_neg_int();
size_t n_usage = json_lexer.token2size_t();
//
json_lexer.check_next_char(',');
json_lexer.check_next_char('[');
//
// index for strings in current operator
CppAD::vector<size_t> str_index;
for(size_t i = 0; i < n_usage; ++i)
{ str_index.resize(0);
//
// [ op_code,
json_lexer.check_next_char('[');
//
// op_enum
json_lexer.next_non_neg_int();
graph_op_enum op_enum = op_code2enum[ json_lexer.token2size_t() ];
json_lexer.check_next_char(',');
//
size_t n_result = 1;
size_t n_arg = op_enum2fixed_n_arg[op_enum];
//
// check if number of arguments is fixed
bool fixed = n_arg > 0;
if( ! fixed )
{ if( op_enum == discrete_graph_op )
{ // name,
json_lexer.check_next_string(match_any_string);
string name = json_lexer.token();
json_lexer.check_next_char(',');
//
size_t name_index = graph_obj.discrete_name_vec_find(name);
if( name_index == graph_obj.discrete_name_vec_size() )
graph_obj.discrete_name_vec_push_back( name );
str_index.push_back(name_index);
}
else if( op_enum == atom_graph_op )
{ // name
json_lexer.check_next_string(match_any_string);
string name = json_lexer.token();
json_lexer.check_next_char(',');
//
size_t name_index = graph_obj.atomic_name_vec_find(name);
if( name_index == graph_obj.atomic_name_vec_size() )
graph_obj.atomic_name_vec_push_back( name );
str_index.push_back(name_index);
}
else if( op_enum == print_graph_op )
{ // before
json_lexer.check_next_string(match_any_string);
string before = json_lexer.token();
json_lexer.check_next_char(',');
//
size_t before_index = graph_obj.print_text_vec_find(before);
if( before_index == graph_obj.print_text_vec_size() )
graph_obj.print_text_vec_push_back(before);
str_index.push_back(before_index);
//
// aftere
json_lexer.check_next_string(match_any_string);
string after = json_lexer.token();
json_lexer.check_next_char(',');
//
size_t after_index = graph_obj.print_text_vec_find(after);
if( after_index == graph_obj.print_text_vec_size() )
graph_obj.print_text_vec_push_back(after);
str_index.push_back(after_index);
}
else CPPAD_ASSERT_UNKNOWN(
op_enum == comp_eq_graph_op ||
op_enum == comp_le_graph_op ||
op_enum == comp_lt_graph_op ||
op_enum == comp_ne_graph_op ||
op_enum == sum_graph_op
);
// n_result,
json_lexer.next_non_neg_int();
n_result = json_lexer.token2size_t();
json_lexer.check_next_char(',');
//
// n_arg, [
json_lexer.next_non_neg_int();
n_arg = json_lexer.token2size_t();
json_lexer.check_next_char(',');
json_lexer.check_next_char('[');
}
//
// atom_graph_op: name_index, n_result, n_arg
// come before first argument
if( op_enum == atom_graph_op )
{ // name_index, n_result, n_arg come before first_node
size_t name_index = str_index[0];
CPPAD_ASSERT_UNKNOWN(
name_index < graph_obj.atomic_name_vec_size()
);
graph_obj.operator_arg_push_back( name_index );
graph_obj.operator_arg_push_back( n_result );
graph_obj.operator_arg_push_back( n_arg );
}
// discrete_op: name_index comes before first argument
if( op_enum == discrete_graph_op )
{ size_t name_index = str_index[0];
graph_obj.operator_arg_push_back( name_index );
}
// print_op: before_index, after_index come before first argument
if( op_enum == print_graph_op )
{ size_t before_index = str_index[0];
size_t after_index = str_index[1];
graph_obj.operator_arg_push_back( before_index );
graph_obj.operator_arg_push_back( after_index );
}
//
// sum_graph_op: n_arg comes before first argument
if( op_enum == sum_graph_op )
graph_obj.operator_arg_push_back( n_arg );
//
// operator_vec
graph_op_enum op_usage;
op_usage = op_enum;
graph_obj.operator_vec_push_back( op_usage );
for(size_t j = 0; j < n_arg; ++j)
{ // next_arg
json_lexer.next_non_neg_int();
size_t argument_node = json_lexer.token2size_t();
graph_obj.operator_arg_push_back( argument_node );
//
// , (if not last entry)
if( j + 1 < n_arg )
json_lexer.check_next_char(',');
}
json_lexer.check_next_char(']');
if( ! fixed )
json_lexer.check_next_char(']');
//
// , (if not last entry)
if( i + 1 < n_usage )
json_lexer.check_next_char(',');
}
json_lexer.check_next_char(']');
json_lexer.check_next_char(']');
json_lexer.check_next_char(',');
// -----------------------------------------------------------------------
// "dependent_vec": [ n_dependent, [first_dependent, ..., last_dependent] ]
json_lexer.check_next_string("dependent_vec");
json_lexer.check_next_char(':');
json_lexer.check_next_char('[');
//
json_lexer.next_non_neg_int();
size_t n_dependent = json_lexer.token2size_t();
json_lexer.check_next_char(',');
//
json_lexer.check_next_char('[');
for(size_t i = 0; i < n_dependent; ++i)
{ json_lexer.next_float();
graph_obj.dependent_vec_push_back( json_lexer.token2size_t() );
//
if( i + 1 < n_dependent )
json_lexer.check_next_char(',');
}
json_lexer.check_next_char(']');
json_lexer.check_next_char(']');
// -----------------------------------------------------------------------
// end of Json object
json_lexer.check_next_char('}');
//
return;
}
| 13,167 | 4,252 |
/*-
* Copyright 2021 Vsevolod Stakhov
*
* 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.
*/
#ifndef RSPAMD_HTML_BLOCK_HXX
#define RSPAMD_HTML_BLOCK_HXX
#pragma once
#include "libserver/css/css_value.hxx"
#include <cmath>
namespace rspamd::html {
/*
* Block tag definition
*/
struct html_block {
rspamd::css::css_color fg_color;
rspamd::css::css_color bg_color;
std::int16_t height;
std::int16_t width;
rspamd::css::css_display_value display;
std::int8_t font_size;
unsigned fg_color_mask : 2;
unsigned bg_color_mask : 2;
unsigned height_mask : 2;
unsigned width_mask : 2;
unsigned font_mask : 2;
unsigned display_mask : 2;
unsigned visibility_mask : 2;
constexpr static const auto unset = 0;
constexpr static const auto inherited = 1;
constexpr static const auto implicit = 1;
constexpr static const auto set = 3;
constexpr static const auto invisible_flag = 1;
constexpr static const auto transparent_flag = 2;
/* Helpers to set mask when setting the elements */
auto set_fgcolor(const rspamd::css::css_color &c, int how = html_block::set) -> void {
fg_color = c;
fg_color_mask = how;
}
auto set_bgcolor(const rspamd::css::css_color &c, int how = html_block::set) -> void {
bg_color = c;
bg_color_mask = how;
}
auto set_height(float h, bool is_percent = false, int how = html_block::set) -> void {
h = is_percent ? (-h) : h;
if (h < INT16_MIN) {
/* Negative numbers encode percents... */
height = -100;
}
else if (h > INT16_MAX) {
height = INT16_MAX;
}
else {
height = h;
}
height_mask = how;
}
auto set_width(float w, bool is_percent = false, int how = html_block::set) -> void {
w = is_percent ? (-w) : w;
if (w < INT16_MIN) {
width = INT16_MIN;
}
else if (w > INT16_MAX) {
width = INT16_MAX;
}
else {
width = w;
}
width_mask = how;
}
auto set_display(bool v, int how = html_block::set) -> void {
if (v) {
display = rspamd::css::css_display_value::DISPLAY_INLINE;
}
else {
display = rspamd::css::css_display_value::DISPLAY_HIDDEN;
}
display_mask = how;
}
auto set_display(rspamd::css::css_display_value v, int how = html_block::set) -> void {
display = v;
display_mask = how;
}
auto set_font_size(float fs, bool is_percent = false, int how = html_block::set) -> void {
fs = is_percent ? (-fs) : fs;
if (fs < INT8_MIN) {
font_size = -100;
}
else if (fs > INT8_MAX) {
font_size = INT8_MAX;
}
else {
font_size = fs;
}
font_mask = how;
}
private:
template<typename T, typename MT>
static constexpr auto simple_prop(MT mask_val, MT other_mask, T &our_val,
T other_val) -> MT
{
if (other_mask && other_mask > mask_val) {
our_val = other_val;
mask_val = html_block::inherited;
}
return mask_val;
}
/* Sizes propagation logic
* We can have multiple cases:
* 1) Our size is > 0 and we can use it as is
* 2) Parent size is > 0 and our size is undefined, so propagate parent
* 3) Parent size is < 0 and our size is undefined - propagate parent
* 4) Parent size is > 0 and our size is < 0 - multiply parent by abs(ours)
* 5) Parent size is undefined and our size is < 0 - tricky stuff, assume some defaults
*/
template<typename T, typename MT>
static constexpr auto size_prop (MT mask_val, MT other_mask, T &our_val,
T other_val, T default_val) -> MT
{
if (mask_val) {
/* We have our value */
if (our_val < 0) {
if (other_mask > 0) {
if (other_val >= 0) {
our_val = other_val * (-our_val / 100.0);
}
else {
our_val *= (-other_val / 100.0);
}
}
else {
/* Parent value is not defined and our value is relative */
our_val = default_val * (-our_val / 100.0);
}
}
else if (other_mask && other_mask > mask_val) {
our_val = other_val;
mask_val = html_block::inherited;
}
}
else {
/* We propagate parent if defined */
if (other_mask && other_mask > mask_val) {
our_val = other_val;
mask_val = html_block::inherited;
}
/* Otherwise do nothing */
}
return mask_val;
}
public:
/**
* Propagate values from the block if they are not defined by the current block
* @param other
* @return
*/
auto propagate_block(const html_block &other) -> void {
fg_color_mask = html_block::simple_prop(fg_color_mask, other.fg_color_mask,
fg_color, other.fg_color);
bg_color_mask = html_block::simple_prop(bg_color_mask, other.bg_color_mask,
bg_color, other.bg_color);
display_mask = html_block::simple_prop(display_mask, other.display_mask,
display, other.display);
height_mask = html_block::size_prop(height_mask, other.height_mask,
height, other.height, static_cast<std::int16_t>(800));
width_mask = html_block::size_prop(width_mask, other.width_mask,
width, other.width, static_cast<std::int16_t>(1024));
font_mask = html_block::size_prop(font_mask, other.font_mask,
font_size, other.font_size, static_cast<std::int8_t>(10));
}
/*
* Set block overriding all inherited values
*/
auto set_block(const html_block &other) -> void {
constexpr auto set_value = [](auto mask_val, auto other_mask, auto &our_val,
auto other_val) constexpr -> int {
if (other_mask && mask_val != html_block::set) {
our_val = other_val;
mask_val = other_mask;
}
return mask_val;
};
fg_color_mask = set_value(fg_color_mask, other.fg_color_mask, fg_color, other.fg_color);
bg_color_mask = set_value(bg_color_mask, other.bg_color_mask, bg_color, other.bg_color);
display_mask = set_value(display_mask, other.display_mask, display, other.display);
height_mask = set_value(height_mask, other.height_mask, height, other.height);
width_mask = set_value(width_mask, other.width_mask, width, other.width);
font_mask = set_value(font_mask, other.font_mask, font_size, other.font_size);
}
auto compute_visibility(void) -> void {
if (display_mask) {
if (display == css::css_display_value::DISPLAY_HIDDEN) {
visibility_mask = html_block::invisible_flag;
return;
}
}
if (font_mask) {
if (font_size == 0) {
visibility_mask = html_block::invisible_flag;
return;
}
}
auto is_similar_colors = [](const rspamd::css::css_color &fg, const rspamd::css::css_color &bg) -> bool {
constexpr const auto min_visible_diff = 0.1f;
auto diff_r = ((float)fg.r - bg.r);
auto diff_g = ((float)fg.g - bg.g);
auto diff_b = ((float)fg.b - bg.b);
auto ravg = ((float)fg.r + bg.r) / 2.0f;
/* Square diffs */
diff_r *= diff_r;
diff_g *= diff_g;
diff_b *= diff_b;
auto diff = std::sqrt(2.0f * diff_r + 4.0f * diff_g + 3.0f * diff_b +
(ravg * (diff_r - diff_b) / 256.0f)) / 256.0f;
return diff < min_visible_diff;
};
/* Check if we have both bg/fg colors */
if (fg_color_mask && bg_color_mask) {
if (fg_color.alpha < 10) {
/* Too transparent */
visibility_mask = html_block::transparent_flag;
return;
}
if (bg_color.alpha > 10) {
if (is_similar_colors(fg_color, bg_color)) {
visibility_mask = html_block::transparent_flag;
return;
}
}
}
else if (fg_color_mask) {
/* Merely fg color */
if (fg_color.alpha < 10) {
/* Too transparent */
visibility_mask = html_block::transparent_flag;
return;
}
/* Implicit fg color */
if (is_similar_colors(fg_color, rspamd::css::css_color::white())) {
visibility_mask = html_block::transparent_flag;
return;
}
}
else if (bg_color_mask) {
if (bg_color.alpha > 10) {
if (is_similar_colors(rspamd::css::css_color::black(), bg_color)) {
visibility_mask = html_block::transparent_flag;
return;
}
}
}
visibility_mask = html_block::unset;
}
constexpr auto is_visible(void) const -> bool {
return visibility_mask == html_block::unset;
}
constexpr auto is_transparent(void) const -> bool {
return visibility_mask == html_block::transparent_flag;
}
constexpr auto has_display(int how = html_block::set) const -> bool {
return display_mask >= how;
}
/**
* Returns a default html block for root HTML element
* @return
*/
static auto default_html_block(void) -> html_block {
return html_block{.fg_color = rspamd::css::css_color::black(),
.bg_color = rspamd::css::css_color::white(),
.height = 0,
.width = 0,
.display = rspamd::css::css_display_value::DISPLAY_INLINE,
.font_size = 12,
.fg_color_mask = html_block::inherited,
.bg_color_mask = html_block::inherited,
.height_mask = html_block::unset,
.width_mask = html_block::unset,
.font_mask = html_block::unset,
.display_mask = html_block::inherited,
.visibility_mask = html_block::unset};
}
/**
* Produces html block with no defined values allocated from the pool
* @param pool
* @return
*/
static auto undefined_html_block_pool(rspamd_mempool_t *pool) -> html_block* {
auto *bl = rspamd_mempool_alloc0_type(pool, html_block);
return bl;
}
};
}
#endif //RSPAMD_HTML_BLOCK_HXX
| 9,495 | 3,979 |