blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
0d65aacf3ac53c368df72dc2228290e00ae91346
d689c1e21900c1d2da0a5657a40afbd5c1c1d602
/VCell/include/VCELL/ContourVariable.h
5583ee1ff63ee108a6a16a4de23029972eadd3a1
[]
no_license
virtualcell/vcell-solvers
8f67f6803e00840589d3677447793b5046702073
feabcc34a83fd836f61a1c8a1318dad42115b403
refs/heads/master
2023-09-02T19:49:24.343472
2023-08-21T23:11:11
2023-08-21T23:11:11
100,556,111
7
7
null
2023-08-21T23:11:12
2017-08-17T03:13:05
C
UTF-8
C++
false
false
422
h
/* * (C) Copyright University of Connecticut Health Center 2001. * All rights reserved. */ #ifndef CONTOURVARIABLE_H #define CONTOURVARIABLE_H #include <VCELL/Variable.h> class ContourVariable : public Variable { public: ContourVariable(long size, string& nameStr, string& Aunits); virtual bool isContourVar() { return true; } virtual VariableType getVarType() {return VAR_CONTOUR;} }; #endif
[ "fgao@uchc.edu" ]
fgao@uchc.edu
dc1f8274434c1158f1a728934c620c1864624ed0
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/shell/osshell/snapins/devmgr/snapin/devdrvpg.cpp
15868fe3137d308daa3912345effba0cc6f205f0
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
39,337
cpp
/*++ Copyright (C) 1997-1999 Microsoft Corporation Module Name: devdrvpg.cpp Abstract: This module implements CDeviceDriverPage -- device driver property page Author: William Hsieh (williamh) created Revision History: --*/ // devdrvpg.cpp : implementation file // #include "devmgr.h" #include "devdrvpg.h" #include "cdriver.h" #include "tswizard.h" #include "devrmdlg.h" // // help topic ids // // BUGBUG: JasonC 3/23/2000 // Add context help for driver rollback button. // const DWORD g_a106HelpIDs[]= { IDC_DEVDRV_ICON, IDH_DISABLEHELP, // Driver: "" (Static) IDC_DEVDRV_DESC, IDH_DISABLEHELP, // Driver: "" (Static) IDC_DEVDRV_TITLE_DRIVERPROVIDER, idh_devmgr_driver_provider_main, IDC_DEVDRV_DRIVERPROVIDER, idh_devmgr_driver_provider_main, IDC_DEVDRV_TITLE_DRIVERDATE, idh_devmgr_driver_date_main, IDC_DEVDRV_DRIVERDATE, idh_devmgr_driver_date_main, IDC_DEVDRV_TITLE_DRIVERVERSION, idh_devmgr_driver_version_main, IDC_DEVDRV_DRIVERVERSION, idh_devmgr_driver_version_main, IDC_DEVDRV_TITLE_DRIVERSIGNER, idh_devmgr_digital_signer, IDC_DEVDRV_DRIVERSIGNER, idh_devmgr_digital_signer, IDC_DEVDRV_DETAILS, idh_devmgr_devdrv_details, // Driver: "Driver Details" (Button) IDC_DEVDRV_DETAILS_TEXT, idh_devmgr_devdrv_details, // Driver: "Driver Details" (Button) IDC_DEVDRV_UNINSTALL, idh_devmgr_devdrv_uninstall, // Driver: "Uninstall" (Button) IDC_DEVDRV_UNINSTALL_TEXT, idh_devmgr_devdrv_uninstall, // Driver: "Uninstall" (Button) IDC_DEVDRV_CHANGEDRIVER, idh_devmgr_driver_change_driver, // Driver: "&Change Driver..." (Button) IDC_DEVDRV_CHANGEDRIVER_TEXT, idh_devmgr_driver_change_driver, // Driver: "&Change Driver..." (Button) IDC_DEVDRV_ROLLBACK, idh_devmgr_rollback_button, // Driver: "Roll Back Driver..." (Button) IDC_DEVDRV_ROLLBACK_TEXT, idh_devmgr_rollback_button, // Driver: "Roll Back Driver..." (Button) 0, 0 }; CDeviceDriverPage::~CDeviceDriverPage() { if (m_pDriver) { delete m_pDriver; } } BOOL CDeviceDriverPage::OnCommand( WPARAM wParam, LPARAM lParam ) { if (BN_CLICKED == HIWORD(wParam)) { switch (LOWORD(wParam)) { case IDC_DEVDRV_DETAILS: { // // We first need to call CDriver::BuildDriverList to build up a list // of drivers for this device. This can take some time so we will put // up the busy cursor. // HCURSOR hCursorOld = SetCursor(LoadCursor(NULL, IDC_WAIT)); CDriver* pDriver; pDriver = m_pDevice->CreateDriver(); if (pDriver) { pDriver->BuildDriverList(NULL); SetCursor(hCursorOld); // // Show driver file details // if (pDriver->GetCount() > 0) { if (pDriver) { CDriverFilesDlg DriverFilesDlg(m_pDevice, pDriver); DriverFilesDlg.DoModal(m_hDlg, (LPARAM)&DriverFilesDlg); } } else { // // No driver files are loaded for this device // String strNoDrivers; strNoDrivers.LoadString(g_hInstance, IDS_DEVDRV_NODRIVERFILE); MessageBox(m_hDlg, strNoDrivers, m_pDevice->GetDisplayName(), MB_OK); return FALSE; } delete pDriver; pDriver = NULL; } break; } case IDC_DEVDRV_UNINSTALL: { BOOL fChanged; BOOL Refresh = (m_pDevice->IsPhantom() || m_pDevice->HasProblem() || !m_pDevice->IsStarted()); if (UninstallDrivers(m_pDevice, m_hDlg, &fChanged) && fChanged) { // // Enable refresh since we disabled it in the beginning. // // We only need to force a refresh here if the device that // was removed was a Phantom device. This is because Phantom // devices don't have kernel mode devnodes and so they won't // generate a WM_DEVICECHANGE like live devnodes will. // if (Refresh) { m_pDevice->m_pMachine->ScheduleRefresh(); } ::DestroyWindow(GetParent(m_hDlg)); } break; } case IDC_DEVDRV_CHANGEDRIVER: { BOOL fChanged; DWORD Reboot = 0; if (UpdateDriver(m_pDevice, m_hDlg, &fChanged, &Reboot) && fChanged) { // // ISSUE: JasonC 2/7/00 // // A refresh on m_pDevice->m_pMachine is necessary here. // Since we are running on a different thread and each // property page may have cached the HDEVINFO and the // SP_DEVINFO_DATA, refresh on the CMachine object can not // be done here. The problem is worsen by the fact that // user can go back to the device tree and work on the tree // while this property sheet is still up. // It would be nice if MMC would support modal dialog boxes! // m_pDevice->PropertyChanged(); m_pDevice->GetClass()->PropertyChanged(); m_pDevice->m_pMachine->DiTurnOnDiFlags(*m_pDevice, DI_PROPERTIES_CHANGE); UpdateControls(); PropSheet_SetTitle(GetParent(m_hDlg), PSH_PROPTITLE, m_pDevice->GetDisplayName()); PropSheet_CancelToClose(GetParent(m_hDlg)); if (Reboot & (DI_NEEDRESTART | DI_NEEDREBOOT)) { m_pDevice->m_pMachine->DiTurnOnDiFlags(*m_pDevice, DI_NEEDREBOOT); } } break; } case IDC_DEVDRV_ROLLBACK: { BOOL fChanged; DWORD Reboot = 0; if (RollbackDriver(m_pDevice, m_hDlg, &fChanged, &Reboot) && fChanged) { // // ISSUE: JasonC 2/7/00 // // A refresh on m_pDevice->m_pMachine is necessary here. // Since we are running on a different thread and each // property page may have cached the HDEVINFO and the // SP_DEVINFO_DATA, refresh on the CMachine object can not // be done here. The problem is worsen by the fact that // user can go back to the device tree and work on the tree // while this property sheet is still up. // It would be nice if MMC would support modal dialog boxes! // m_pDevice->PropertyChanged(); m_pDevice->GetClass()->PropertyChanged(); m_pDevice->m_pMachine->DiTurnOnDiFlags(*m_pDevice, DI_PROPERTIES_CHANGE); UpdateControls(); PropSheet_SetTitle(GetParent(m_hDlg), PSH_PROPTITLE, m_pDevice->GetDisplayName()); PropSheet_CancelToClose(GetParent(m_hDlg)); if (Reboot & (DI_NEEDRESTART | DI_NEEDREBOOT)) { m_pDevice->m_pMachine->DiTurnOnDiFlags(*m_pDevice, DI_NEEDREBOOT); } } break; } default: break; } } return FALSE; } // // This function uninstalls the drivers for the given device // INPUT: // pDevice -- the object represent the device // hDlg -- the property page window handle // pfChanged -- optional buffer to receive if drivers // were uninstalled. // OUTPUT: // TRUE -- function succeeded. // FALSE -- function failed. // BOOL CDeviceDriverPage::UninstallDrivers( CDevice* pDevice, HWND hDlg, BOOL *pfUninstalled ) { BOOL Return = FALSE; int MsgBoxResult; TCHAR szText[MAX_PATH]; CMachine *pMachine; if (pDevice->m_pMachine->m_ParentMachine) { pMachine = pDevice->m_pMachine->m_ParentMachine; } else { pMachine = pDevice->m_pMachine; } if(!pDevice->m_pMachine->IsLocal() || !g_HasLoadDriverNamePrivilege) { // // Must be an admin and on the local machine to remove a device. // return FALSE; } BOOL Refresh = (pDevice->IsPhantom() || pDevice->HasProblem() || !pDevice->IsStarted()); pMachine->EnableRefresh(FALSE); CRemoveDevDlg TheDlg(pDevice); if (IDOK == TheDlg.DoModal(hDlg, (LPARAM) &TheDlg)) { DWORD DiFlags; DiFlags = pDevice->m_pMachine->DiGetFlags(*pDevice); // // We don't check to see if the device manager is connected to the local // machine because if it wasn't we would not have allowed the user to // get this far since we don't allow them to remove a device if it // is not connected to the local machine. // if (PromptForRestart(hDlg, DiFlags, IDS_REMOVEDEV_RESTART) == IDNO) { Refresh = TRUE; } if (Refresh) { pMachine->ScheduleRefresh(); } Return = TRUE; } pMachine->EnableRefresh(TRUE); return Return; } BOOL CDeviceDriverPage::LaunchTroubleShooter( CDevice* pDevice, HWND hDlg, BOOL *pfChanged ) { BOOL fChanged = FALSE; DWORD Status, Problem = 0; CProblemAgent* ProblemAgent; if (pDevice->GetStatus(&Status, &Problem) || pDevice->IsPhantom()) { // // if the device is a phantom device, use the CM_PROB_DEVICE_NOT_THERE // if (pDevice->IsPhantom()) { Problem = CM_PROB_DEVICE_NOT_THERE; Status = DN_HAS_PROBLEM; } // // if the device is not started and no problem is assigned to it // fake the problem number to be failed start. // if (!(Status & DN_STARTED) && !Problem && pDevice->IsRAW()) { Problem = CM_PROB_FAILED_START; } } ProblemAgent = new CProblemAgent(pDevice, Problem, FALSE); if (ProblemAgent) { fChanged = ProblemAgent->FixIt(GetParent(hDlg)); delete ProblemAgent; } if (pfChanged) { *pfChanged = fChanged; } return TRUE; } // // This function updates drivers for the given device // INPUT: // pDevice -- the object represent the device // hDlg -- the property page window handle // pfChanged -- optional buffer to receive if driver changes // have occured. // OUTPUT: // TRUE -- function succeeded. // FALSE -- function failed. // BOOL CDeviceDriverPage::RollbackDriver( CDevice* pDevice, HWND hDlg, BOOL *pfChanged, DWORD *pdwReboot ) { HCURSOR hCursorOld; BOOL RollbackSuccessful = FALSE; DWORD RollbackError = ERROR_CANCELLED; DWORD Status = 0, Problem = 0; // // Verify that the process has Admin credentials and that we are running on the local // machine. // if (!pDevice || !pDevice->m_pMachine->IsLocal() || !g_HasLoadDriverNamePrivilege) { ASSERT(FALSE); return FALSE; } hCursorOld = SetCursor(LoadCursor(NULL, IDC_WAIT)); // // If the device has the DN_WILL_BE_REMOVED flag set and the user is // attempting to roll back the driver then we will prompt them for a // reboot and include text in the prompt that explains this device // is in the process of being removed. // if (pDevice->GetStatus(&Status, &Problem) && (Status & DN_WILL_BE_REMOVED)) { if (PromptForRestart(m_hDlg, DI_NEEDRESTART, IDS_WILL_BE_REMOVED_NO_ROLLBACK_DRIVER) == IDYES) { ::DestroyWindow(GetParent(m_hDlg)); } return FALSE; } // // First check to see if there are any drivers to Rollback // CSafeRegistry regRollback; TCHAR RollbackSubkeyName[MAX_PATH + 1]; TCHAR ReinstallString[MAX_PATH]; BOOL bFoundMatch = FALSE; int index = 0; ReinstallString[0] = TEXT('\0'); RollbackSubkeyName[0] = TEXT('\0'); if (regRollback.Open(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Reinstall"))) { DWORD SubkeySize = ARRAYLEN(RollbackSubkeyName); while (!bFoundMatch && regRollback.EnumerateSubkey(index, RollbackSubkeyName, &SubkeySize)) { CSafeRegistry regRollbackSubkey; if (regRollbackSubkey.Open(regRollback, RollbackSubkeyName)) { DWORD regType, cbSize; LPTSTR DeviceInstanceIds; cbSize = 0; if (regRollbackSubkey.GetValue(TEXT("DeviceInstanceIds"), &regType, NULL, &cbSize)) { // // Allocate memory to hold the DeviceInstanceIds // DeviceInstanceIds = (LPTSTR)LocalAlloc(LPTR, cbSize); if (DeviceInstanceIds) { ZeroMemory(DeviceInstanceIds, cbSize); if (regRollbackSubkey.GetValue(TEXT("DeviceInstanceIds"), &regType, (PBYTE)DeviceInstanceIds, &cbSize)) { // // Compare the list of DeviceInstanceIds in this registry key with this // devices DeviceInstanceId // for (LPTSTR p = DeviceInstanceIds; *p; p += (lstrlen(p) + 1)) { if (!lstrcmpi(p, pDevice->GetDeviceID())) { bFoundMatch = TRUE; cbSize = sizeof(ReinstallString); regRollbackSubkey.GetValue(TEXT("ReinstallString"), &regType, (PBYTE)ReinstallString, &cbSize); break; } } } LocalFree(DeviceInstanceIds); } } } SubkeySize = ARRAYLEN(RollbackSubkeyName); index++; } } if (bFoundMatch) { // // Check the ReinstallString path to verify that a backup directory actually exists. // We first need to strip the INF name off of the end of the path. // PTSTR p; // // Assume that the directory does NOT exist // bFoundMatch = FALSE; if (ReinstallString[0] != TEXT('\0')) { p = StrRChr(ReinstallString, NULL, TEXT('\\')); if (p) { *p = 0; WIN32_FIND_DATA findData; HANDLE FindHandle; UINT OldMode; OldMode = SetErrorMode(SEM_FAILCRITICALERRORS); FindHandle = FindFirstFile(ReinstallString, &findData); if(FindHandle != INVALID_HANDLE_VALUE) { FindClose(FindHandle); bFoundMatch = TRUE; } else { // // The directory does not exist. Make sure we clean out the registry key // regRollback.DeleteSubkey(RollbackSubkeyName); } SetErrorMode(OldMode); } } } if (bFoundMatch) { // // We found a match, lets ask the user if they want to rollback the drivers // String strYesRollback; strYesRollback.LoadString(g_hInstance, IDS_DEVDRV_YESROLLBACK); if (MessageBox(hDlg, strYesRollback, pDevice->GetDisplayName(), MB_YESNO) == IDYES) { RollbackSuccessful = pDevice->m_pMachine->RollbackDriver(hDlg, RollbackSubkeyName, 0x3, pdwReboot); if (!RollbackSuccessful) { RollbackError = GetLastError(); } } } else { // // We could not find a drivers backup for this device. Lets ask the user if they want // to start the troubleshooter. // String strNoRollback; strNoRollback.LoadString(g_hInstance, IDS_DEVDRV_NOROLLBACK); if (MessageBox(hDlg, strNoRollback, pDevice->GetDisplayName(), MB_YESNO) == IDYES) { LaunchTroubleShooter(pDevice, hDlg, pfChanged); } } if (hCursorOld) { SetCursor(hCursorOld); } // // We will assume that something changed when we called InstallDevInst() // unless it returned FALSE and GetLastError() == ERROR_CANCELLED // if (pfChanged) { *pfChanged = TRUE; if (!bFoundMatch || (!RollbackSuccessful && (ERROR_CANCELLED == RollbackError))) { *pfChanged = FALSE; } } return TRUE; } // // This function updates drivers for the given device // INPUT: // pDevice -- the object represent the device // hDlg -- the property page window handle // pfChanged -- optional buffer to receive if driver changes // have occured. // OUTPUT: // TRUE -- function succeeded. // FALSE -- function failed. // BOOL CDeviceDriverPage::UpdateDriver( CDevice* pDevice, HWND hDlg, BOOL *pfChanged, DWORD *pdwReboot ) { BOOL Installed = FALSE; DWORD InstallError = ERROR_SUCCESS; DWORD Status = 0, Problem = 0; // // Must be an admin and on the local machine to update a device. // if (!pDevice || !pDevice->m_pMachine->IsLocal() || !g_HasLoadDriverNamePrivilege) { ASSERT(FALSE); return FALSE; } // // If the device has the DN_WILL_BE_REMOVED flag set and the user is // attempting to update the driver then we will prompt them for a // reboot and include text in the prompt that explains this device // is in the process of being removed. // if (pDevice->GetStatus(&Status, &Problem) && (Status & DN_WILL_BE_REMOVED)) { if (PromptForRestart(m_hDlg, DI_NEEDRESTART, IDS_WILL_BE_REMOVED_NO_UPDATE_DRIVER) == IDYES) { ::DestroyWindow(GetParent(m_hDlg)); } return FALSE; } Installed = pDevice->m_pMachine->InstallDevInst(hDlg, pDevice->GetDeviceID(), TRUE, pdwReboot); if (!Installed) { InstallError = GetLastError(); } // // We will assume that something changed when we called InstallDevInst() // unless it returned FALSE and GetLastError() == ERROR_CANCELLED // if (pfChanged) { *pfChanged = TRUE; if (!Installed && (ERROR_CANCELLED == InstallError)) { *pfChanged = FALSE; } } return TRUE; } void CDeviceDriverPage::InitializeDriver() { if (m_pDriver) { delete m_pDriver; m_pDriver = NULL; } m_pDriver = m_pDevice->CreateDriver(); } void CDeviceDriverPage::UpdateControls( LPARAM lParam ) { if (lParam) { m_pDevice = (CDevice*) lParam; } try { // // Calling PropertyChanged() will update the display name for the device. We need // to do this in case a 3rd party property sheet did something that could change // the device's display name. // m_pDevice->PropertyChanged(); // // If we are not running locally then don't bother showing the driver // details since we can't get a list of the drivers and we can't get // any information about the driver. // if (!m_pDevice->m_pMachine->IsLocal()) { ::EnableWindow(GetControl(IDC_DEVDRV_DETAILS), FALSE); ::EnableWindow(GetControl(IDC_DEVDRV_DETAILS_TEXT), FALSE); } // // can not change driver on remote machine or the user // has no Administrator privilege. // if (!m_pDevice->m_pMachine->IsLocal() || !g_HasLoadDriverNamePrivilege) { ::EnableWindow(GetControl(IDC_DEVDRV_CHANGEDRIVER), FALSE); ::EnableWindow(GetControl(IDC_DEVDRV_CHANGEDRIVER_TEXT), FALSE); ::EnableWindow(GetControl(IDC_DEVDRV_ROLLBACK), FALSE); ::EnableWindow(GetControl(IDC_DEVDRV_ROLLBACK_TEXT), FALSE); ::EnableWindow(GetControl(IDC_DEVDRV_UNINSTALL), FALSE); ::EnableWindow(GetControl(IDC_DEVDRV_UNINSTALL_TEXT), FALSE); } // // Hide the uninstall button if the device cannot be uninstalled // else if (!m_pDevice->IsUninstallable()) { ::EnableWindow(GetControl(IDC_DEVDRV_UNINSTALL), FALSE); ::EnableWindow(GetControl(IDC_DEVDRV_UNINSTALL_TEXT), FALSE); } HICON hIconOld; m_IDCicon = IDC_DEVDRV_ICON; // Save for cleanup in OnDestroy. hIconOld = (HICON)SendDlgItemMessage(m_hDlg, IDC_DEVDRV_ICON, STM_SETICON, (WPARAM)(m_pDevice->LoadClassIcon()), 0 ); if (hIconOld) { DestroyIcon(hIconOld); } InitializeDriver(); SetDlgItemText(m_hDlg, IDC_DEVDRV_DESC, m_pDevice->GetDisplayName()); String strDriverProvider, strDriverDate, strDriverVersion, strDriverSigner; m_pDevice->GetProviderString(strDriverProvider); SetDlgItemText(m_hDlg, IDC_DEVDRV_DRIVERPROVIDER, strDriverProvider); m_pDevice->GetDriverDateString(strDriverDate); SetDlgItemText(m_hDlg, IDC_DEVDRV_DRIVERDATE, strDriverDate); m_pDevice->GetDriverVersionString(strDriverVersion); SetDlgItemText(m_hDlg, IDC_DEVDRV_DRIVERVERSION, strDriverVersion); if (m_pDriver) { m_pDriver->GetDriverSignerString(strDriverSigner); } // // If we could not get a digital signature string or then just display // Unknown for the Digital Signer. // if (strDriverSigner.IsEmpty()) { strDriverSigner.LoadString(g_hInstance, IDS_UNKNOWN); } SetDlgItemText(m_hDlg, IDC_DEVDRV_DRIVERSIGNER, strDriverSigner); AddToolTips(m_hDlg, IDC_DEVDRV_DRIVERSIGNER, (LPTSTR)strDriverSigner, &m_hwndDigitalSignerTip); } catch (CMemoryException* e) { e->Delete(); // report memory error MsgBoxParam(m_hDlg, 0, 0, 0); } } BOOL CDeviceDriverPage::OnHelp( LPHELPINFO pHelpInfo ) { WinHelp((HWND)pHelpInfo->hItemHandle, DEVMGR_HELP_FILE_NAME, HELP_WM_HELP, (ULONG_PTR)g_a106HelpIDs); return FALSE; } BOOL CDeviceDriverPage::OnContextMenu( HWND hWnd, WORD xPos, WORD yPos ) { WinHelp(hWnd, DEVMGR_HELP_FILE_NAME, HELP_CONTEXTMENU, (ULONG_PTR)g_a106HelpIDs); return FALSE; } ////////////////////////////////////////////////////////////////////////////////////////// // // Driver Files // const DWORD g_a110HelpIDs[]= { IDC_DRIVERFILES_ICON, IDH_DISABLEHELP, // Driver: "" (Icon) IDC_DRIVERFILES_DESC, IDH_DISABLEHELP, // Driver: "" (Static) IDC_DRIVERFILES_FILES, IDH_DISABLEHELP, // Driver: "Provider:" (Static) IDC_DRIVERFILES_FILELIST, idh_devmgr_driver_driver_files, // Driver: "" (ListBox) IDC_DRIVERFILES_TITLE_PROVIDER, idh_devmgr_driver_provider, // Driver: "Provider:" (Static) IDC_DRIVERFILES_PROVIDER, idh_devmgr_driver_provider, // Driver: "" (Static) IDC_DRIVERFILES_TITLE_COPYRIGHT,idh_devmgr_driver_copyright, // Driver: "Copyright:" (Static) IDC_DRIVERFILES_COPYRIGHT, idh_devmgr_driver_copyright, // Driver: "" (Static) IDC_DRIVERFILES_TITLE_DIGITALSIGNER, IDH_DISABLEHELP, IDC_DRIVERFILES_DIGITALSIGNER, IDH_DISABLEHELP, IDC_DRIVERFILES_TITLE_VERSION, idh_devmgr_driver_file_version, // Driver: "Version:" (Static) IDC_DRIVERFILES_VERSION, idh_devmgr_driver_file_version, // Driver: "File Version:" (Static) 0, 0 }; BOOL CDriverFilesDlg::OnInitDialog() { int SignedIndex = 0, BlankIndex = 0, DriverBlockIndex = 0; try { HICON hIcon; hIcon = (HICON)SendDlgItemMessage(m_hDlg, IDC_DRIVERFILES_ICON, STM_SETICON, (WPARAM)(m_pDevice->LoadClassIcon()), 0); if (hIcon) { DestroyIcon(hIcon); } SetDlgItemText(m_hDlg, IDC_DRIVERFILES_DESC, m_pDevice->GetDisplayName()); // // Create the ImageList that contains the signed and blank images. // // NOTE: On BiDi builds we need to set the ILC_MIRROR flag so that the // signed/unsigned icons are not mirrored. // m_ImageList = ImageList_Create(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), ILC_MASK | (GetWindowLong(GetParent(m_hDlg), GWL_EXSTYLE) & WS_EX_LAYOUTRTL) ? ILC_MIRROR : 0, 1, 1 ); if (m_ImageList) { ImageList_SetBkColor(m_ImageList, GetSysColor(COLOR_WINDOW)); if ((hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_BLANK))) != NULL) { BlankIndex = ImageList_AddIcon(m_ImageList, hIcon); DestroyIcon(hIcon); } if ((hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_SIGNED))) != NULL) { SignedIndex = ImageList_AddIcon(m_ImageList, hIcon); DestroyIcon(hIcon); } if ((hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_DRIVERBLOCK))) != NULL) { DriverBlockIndex = ImageList_AddIcon(m_ImageList, hIcon); DestroyIcon(hIcon); } } // //Initialize the list of drivers // LV_COLUMN lvcCol; LV_ITEM lviItem; CDriverFile* pDrvFile; PVOID Context; HWND hwndFileList = GetDlgItem(m_hDlg, IDC_DRIVERFILES_FILELIST); // // Insert a single column for this list. // lvcCol.mask = LVCF_FMT | LVCF_WIDTH; lvcCol.fmt = LVCFMT_LEFT; lvcCol.iSubItem = 0; ListView_InsertColumn(hwndFileList, 0, (LV_COLUMN FAR *)&lvcCol); ListView_SetExtendedListViewStyle(hwndFileList, LVS_EX_FULLROWSELECT | LVS_EX_LABELTIP); if (m_ImageList) { ListView_SetImageList(hwndFileList, m_ImageList, LVSIL_SMALL); } ListView_DeleteAllItems(hwndFileList); if (m_pDriver && m_pDriver->GetFirstDriverFile(&pDrvFile, Context)) { do { ASSERT(pDrvFile); LPCTSTR pFullPathName; pFullPathName = pDrvFile->GetFullPathName(); if (pFullPathName) { lviItem.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; lviItem.iSubItem = 0; lviItem.lParam = (LPARAM)pDrvFile; lviItem.iItem = ListView_GetItemCount(hwndFileList); lviItem.pszText = (LPTSTR)pFullPathName; if (m_ImageList) { if (pDrvFile->IsDriverBlocked()) { // // If the driver is blocked then it gets a special // icon. // lviItem.iImage = DriverBlockIndex; } else { // // If the driver is not blocked then show an icon // if the driver is digitally signed. // lviItem.iImage = (pDrvFile->GetWin32Error() == NO_ERROR) ? SignedIndex : BlankIndex; } } ListView_InsertItem(hwndFileList, &lviItem); } } while (m_pDriver->GetNextDriverFile(&pDrvFile, Context)); if (ListView_GetItemCount(hwndFileList) >= 1) { ListView_SetItemState(hwndFileList, 0, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED ); ListView_EnsureVisible(hwndFileList, 0, FALSE); ListView_SetColumnWidth(hwndFileList, 0, LVSCW_AUTOSIZE_USEHEADER); ShowCurDriverFileDetail(); } else { // // nothing on the driver file list, disable it // ::EnableWindow(GetControl(IDC_DRIVERFILES_FILELIST), FALSE); } } } catch (CMemoryException* e) { e->Delete(); return FALSE; } return TRUE; } void CDriverFilesDlg::OnCommand( WPARAM wParam, LPARAM lParam ) { if (BN_CLICKED == HIWORD(wParam)) { if (IDOK == LOWORD(wParam)) { EndDialog(m_hDlg, IDOK); } else if (IDCANCEL == LOWORD(wParam)) { EndDialog(m_hDlg, IDCANCEL); } } } BOOL CDriverFilesDlg::OnNotify( LPNMHDR pnmhdr ) { switch (pnmhdr->code) { case LVN_ITEMCHANGED: ShowCurDriverFileDetail(); break; case NM_RETURN: case NM_CLICK: if (pnmhdr->idFrom == IDS_DRIVERFILES_BLOCKDRIVERLINK) { LaunchHelpForBlockedDriver(); } break; } return FALSE; } BOOL CDriverFilesDlg::OnDestroy() { HICON hIcon; if(hIcon = (HICON)SendDlgItemMessage(m_hDlg, IDC_DRIVERFILES_ICON, STM_GETICON, 0, 0)) { DestroyIcon(hIcon); } if (m_ImageList) { ImageList_Destroy(m_ImageList); } return FALSE; } BOOL CDriverFilesDlg::OnHelp( LPHELPINFO pHelpInfo ) { WinHelp((HWND)pHelpInfo->hItemHandle, DEVMGR_HELP_FILE_NAME, HELP_WM_HELP, (ULONG_PTR)g_a110HelpIDs); return FALSE; } BOOL CDriverFilesDlg::OnContextMenu( HWND hWnd, WORD xPos, WORD yPos ) { WinHelp(hWnd, DEVMGR_HELP_FILE_NAME, HELP_CONTEXTMENU, (ULONG_PTR)g_a110HelpIDs); return FALSE; } void CDriverFilesDlg::ShowCurDriverFileDetail() { HWND hwndFileList = GetDlgItem(m_hDlg, IDC_DRIVERFILES_FILELIST); LVITEM lvItem; LPCTSTR pString; lvItem.mask = LVIF_PARAM; lvItem.iSubItem = 0; lvItem.iItem = ListView_GetNextItem(hwndFileList, -1, LVNI_SELECTED ); if (lvItem.iItem != -1) { try { ListView_GetItem(hwndFileList, &lvItem); CDriverFile* pDrvFile = (CDriverFile*)lvItem.lParam; ASSERT(pDrvFile); TCHAR TempString[LINE_LEN]; LPCTSTR pFullPathName; pFullPathName = pDrvFile->GetFullPathName(); if (!pFullPathName || (pDrvFile->GetAttributes() == 0xFFFFFFFF)) { // // This is the case when the file is not present on the system // LoadResourceString(IDS_NOT_PRESENT, TempString, ARRAYLEN(TempString)); SetDlgItemText(m_hDlg, IDC_DRIVERFILES_VERSION, TempString); SetDlgItemText(m_hDlg, IDC_DRIVERFILES_PROVIDER, TempString); SetDlgItemText(m_hDlg, IDC_DRIVERFILES_COPYRIGHT, TempString); SetDlgItemText(m_hDlg, IDC_DRIVERFILES_DIGITALSIGNER, TempString); ShowWindow(GetControl(IDS_DRIVERFILES_BLOCKDRIVERLINK), FALSE); } else { if (!pDrvFile->HasVersionInfo()) { // // This is the case when the file is present but it does not have // version information. // LoadResourceString(IDS_UNKNOWN, TempString, ARRAYLEN(TempString)); SetDlgItemText(m_hDlg, IDC_DRIVERFILES_VERSION, TempString); SetDlgItemText(m_hDlg, IDC_DRIVERFILES_PROVIDER, TempString); SetDlgItemText(m_hDlg, IDC_DRIVERFILES_COPYRIGHT, TempString); } else { // // Show the file version information. // TempString[0] = _T('\0'); pString = pDrvFile->GetVersion(); if (!pString && _T('\0') == TempString[0]) { LoadResourceString(IDS_NOT_AVAILABLE, TempString, ARRAYLEN(TempString)); pString = TempString; } SetDlgItemText(m_hDlg, IDC_DRIVERFILES_VERSION, (LPTSTR)pString); pString = pDrvFile->GetProvider(); if (!pString && _T('\0') == TempString[0]) { LoadResourceString(IDS_NOT_AVAILABLE, TempString, ARRAYLEN(TempString)); pString = TempString; } SetDlgItemText(m_hDlg, IDC_DRIVERFILES_PROVIDER, (LPTSTR)pString); pString = pDrvFile->GetCopyright(); if (!pString && _T('\0') == TempString[0]) { LoadResourceString(IDS_NOT_AVAILABLE, TempString, ARRAYLEN(TempString)); pString = TempString; } SetDlgItemText(m_hDlg, IDC_DRIVERFILES_COPYRIGHT, (LPTSTR)pString); } // // Show the digital signer if the file is signed. // pString = pDrvFile->GetDigitalSigner(); if (!pString) { TempString[0] = _T('\0'); LoadResourceString(((pDrvFile->GetWin32Error() != 0) && (pDrvFile->GetWin32Error() != 0xFFFFFFFF) && (pDrvFile->GetWin32Error() != ERROR_DRIVER_BLOCKED)) ? IDS_NO_DIGITALSIGNATURE : IDS_NOT_AVAILABLE, TempString, ARRAYLEN(TempString)); pString = TempString; } SetDlgItemText(m_hDlg, IDC_DRIVERFILES_DIGITALSIGNER, (LPTSTR)pString); // // Show the block driver link if this driver is blocked and it // has a block driver html help ID. // ShowWindow(GetControl(IDS_DRIVERFILES_BLOCKDRIVERLINK), pDrvFile->GetBlockedDriverHtmlHelpID() ? TRUE : FALSE); } } catch (CMemoryException* e) { e->Delete(); // report memory error MsgBoxParam(m_hDlg, 0, 0, 0); } } else { // no selection SetDlgItemText(m_hDlg, IDC_DRIVERFILES_VERSION, TEXT("")); SetDlgItemText(m_hDlg, IDC_DRIVERFILES_PROVIDER, TEXT("")); SetDlgItemText(m_hDlg, IDC_DRIVERFILES_COPYRIGHT, TEXT("")); SetDlgItemText(m_hDlg, IDC_DRIVERFILES_DIGITALSIGNER, TEXT("")); } } void CDriverFilesDlg::LaunchHelpForBlockedDriver() { HWND hwndFileList = GetDlgItem(m_hDlg, IDC_DRIVERFILES_FILELIST); LVITEM lvItem; LPCTSTR pHtmlHelpID; String strHcpLink; lvItem.mask = LVIF_PARAM; lvItem.iSubItem = 0; lvItem.iItem = ListView_GetNextItem(hwndFileList, -1, LVNI_SELECTED ); if (lvItem.iItem != -1) { try { ListView_GetItem(hwndFileList, &lvItem); CDriverFile* pDrvFile = (CDriverFile*)lvItem.lParam; ASSERT(pDrvFile); if ((pHtmlHelpID = pDrvFile->GetBlockedDriverHtmlHelpID()) != NULL) { strHcpLink.Format(TEXT("HELPCTR.EXE -url %s"), pHtmlHelpID); TRACE((TEXT("launching %s"), pHtmlHelpID)); ShellExecute(m_hDlg, TEXT("open"), TEXT("HELPCTR.EXE"), (LPTSTR)strHcpLink, NULL, SW_SHOWNORMAL); } } catch (CMemoryException* e) { e->Delete(); // report memory error MsgBoxParam(m_hDlg, 0, 0, 0); } } }
[ "112426112@qq.com" ]
112426112@qq.com
e87af1f2c4637d166bb53aa87dbedd60b0a25ec4
8126291334a4288f51b1116ea31e953debf07039
/SRC/engine/outputval.swg
cb605da5546df755a623e442db318168d398f9bb
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
jumpingyu/OOF2
846a7dd506f029535153834607b698ce32dc155d
31a25398b046c1963859dd96785329d2a9af8681
refs/heads/master
2020-05-21T09:12:07.013560
2019-04-02T21:05:49
2019-04-02T21:05:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,406
swg
// -*- C++ -*- /* This software was produced by NIST, an agency of the U.S. government, * and by statute is not subject to copyright in the United States. * Recipients of this software assume all responsibilities associated * with its operation, modification and maintenance. However, to * facilitate maintenance we ask that before distributing modified * versions of this software, you first contact the authors at * oof_manager@nist.gov. */ #ifndef OUTPUTVAL_SWG #define OUTPUTVAL_SWG %module outputval %include "engine/typemaps.swg" %extern "engine/fieldindex.swg" %pragma(python) include="outputval.spy" %pragma(python) code="from ooflib.SWIG.engine.fieldindex import IndexPPtr" %pragma(python) code="from ooflib.SWIG.engine.fieldindex import IteratorPPtr" %{ #include "engine/outputval.h" #include "common/tostring.h" %} %typemap(python, out) OutputVal* { // typemap(python, out) OutputVal* $target = $source->pythonObject(); if(!$target) return 0; } class OutputVal { public: ~OutputVal(); IndexP getIndex(char *); IteratorP getIterator(); int dim(); %new OutputVal *clone(); %new OutputVal *zero(); %new OutputVal *one(); void component_pow(int); void component_square(); void component_sqrt(); %new DoubleList *value_list(); %addmethods { double __getitem__(const IndexP &i) const { return (*self)[i]; } } }; class ScalarOutputVal : public OutputVal { public: ScalarOutputVal(double); double value(); // Arithmetic operations -- it's convenient to have // Python-accessible wrapped versions of the addto/subtractfrom // operations, which don't mess up the ownership. These are not // substitutes for __add__, __sub__, etc. -- they're called by // them. %addmethods { %new const string *__repr__() const { return new std::string(to_string( self->value() )); } void _add(const ScalarOutputVal &other) { (*self) += other; } void _sub(const ScalarOutputVal &other) { (*self) -= other; } void _mul(double other) { (*self) *= other; } double __float__() const { return self->value(); } } }; class VectorOutputVal : public OutputVal { public: int size(); VectorOutputVal(int); %addmethods { %new const string *__repr__() const { std::string *res = new std::string("["); *res += to_string( (*self)[0] ); for(unsigned int i=1; i<self->size(); i++) *res += ", " + to_string( (*self)[i] ); *res += "]"; return res; } // Arithmetic operations -- see comment in ScalarOutputVal, above. void _add(const VectorOutputVal &other) { (*self) += other; } void _sub(const VectorOutputVal &other) { (*self) -= other; } void _mul(double other) { (*self) *= other; } } %addmethods { double __getitem__(const IndexP &i) const { return (*self)[i]; } void __setitem__(const IndexP &i, double x) { (*self)[i] = x; } } }; class OutputValue { public: ~OutputValue(); OutputVal *valuePtr(); OutputValue(const OutputValue&); int dim(); %new OutputVal *valueClone(); %addmethods { double __getitem__(const IndexP &i) const { return (*self)[i]; } void _add(const OutputValue &other) { (*self) += other; } void _mul(double other) { (*self) *= other; } } }; #endif // OUTPUTVAL_SWG
[ "lnz5@rosie.nist.gov" ]
lnz5@rosie.nist.gov
39c7a7585f4d774a9b9958799a339c6e208cce8b
74c6d9b244d4aefb0e2f7c7905f8bd84359a7f0b
/rozwiazania/61/rozw2_zle.cpp
edc519f5635f2e15fcca495adb01f69e12b97e72
[]
no_license
toomec2105/maturaZbiorZadan
36cf643986a841d32ed06092e9247addbb75983b
fb8902dc78173942a1a9f8d2aa6e646dbac5577a
refs/heads/master
2022-11-19T13:07:27.153873
2020-07-19T15:59:36
2020-07-19T15:59:36
280,900,379
0
0
null
null
null
null
UTF-8
C++
false
false
750
cpp
// Bledne rozwiazania zadania 2 - wypisuje wszystkie szesciany, nie tylko najwiekszy w kazdym ciagu. #include <fstream> #include <algorithm> using namespace std; const int N = 100; bool szescian(int liczba) { for(int x = 1; x <= 100; x++) if (x*x*x == liczba) return true; return false; } int main() { ifstream in("ciagi.txt"); ofstream out("wynik2_zle.txt"); int koniec7 = 0; int calk7 = 0; for(int q = 0; q < N; q++) { int dlugosc; in >> dlugosc; for(int i = 0; i < dlugosc; i++) { int liczba; in >> liczba; if (szescian(liczba)) out << liczba << endl; } } }
[ "tomec2105@interia.pl" ]
tomec2105@interia.pl
da32423541f371a3b2d150a202d7488ad0828d79
41a885c80090739ebdd90e8944e4f0552562bbbf
/coordinator/coordinator.cc
6a584a5ef305e6f1853240daa1c3eb0983200df4
[ "BSD-3-Clause" ]
permissive
Kangmo/HyperDex
0dbb67f8153cd1c71da21b213e5a53444304d39f
192d66cb633c56967a02e9c2bd1e155350e5c5a1
refs/heads/master
2021-01-17T20:02:58.595256
2013-11-21T16:41:13
2013-11-21T16:41:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
49,837
cc
// Copyright (c) 2012-2013, Cornell University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of HyperDex nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // STL #include <algorithm> #include <sstream> // Replicant #include <replicant_state_machine.h> // HyperDex #include "common/configuration_flags.h" #include "common/serialization.h" #include "coordinator/coordinator.h" #include "coordinator/transitions.h" #include "coordinator/util.h" #define ALARM_INTERVAL 30 using hyperdex::coordinator; using hyperdex::region; using hyperdex::region_intent; using hyperdex::server; using hyperdex::transfer; // ASSUME: I'm assuming only one server ever changes state at a time for a // given transition. If you violate this assumption, fixup // converge_intent. namespace { std::string to_string(const po6::net::location& loc) { std::ostringstream oss; oss << loc; return oss.str(); } template <typename T> void shift_and_pop(size_t idx, std::vector<T>* v) { for (size_t i = idx + 1; i < v->size(); ++i) { (*v)[i - 1] = (*v)[i]; } v->pop_back(); } template <typename T> void remove(const T& t, std::vector<T>* v) { for (size_t i = 0; i < v->size(); ) { if ((*v)[i] == t) { shift_and_pop(i, v); } else { ++i; } } } template <class T, class TID> bool find_id(const TID& id, std::vector<T>& v, T** found) { for (size_t i = 0; i < v.size(); ++i) { if (v[i].id == id) { *found = &v[i]; return true; } } return false; } template <class T, class TID> void remove_id(const TID& id, std::vector<T>* v) { for (size_t i = 0; i < v->size(); ) { if ((*v)[i].id == id) { shift_and_pop(i, v); } else { ++i; } } } } // namespace coordinator :: coordinator() : m_cluster(0) , m_counter(1) , m_version(0) , m_flags(0) , m_servers() , m_permutation() , m_spares() , m_desired_spares(0) , m_spaces() , m_intents() , m_deferred_init() , m_offline() , m_transfers() , m_config_ack_through(0) , m_config_ack_barrier() , m_config_stable_through(0) , m_config_stable_barrier() , m_checkpoint(0) , m_checkpoint_stable_through(0) , m_checkpoint_gc_through(0) , m_checkpoint_stable_barrier() , m_latest_config() { assert(m_config_ack_through == m_config_ack_barrier.min_version()); assert(m_config_stable_through == m_config_stable_barrier.min_version()); assert(m_checkpoint_stable_through == m_checkpoint_stable_barrier.min_version()); } coordinator :: ~coordinator() throw () { } void coordinator :: init(replicant_state_machine_context* ctx, uint64_t token) { FILE* log = replicant_state_machine_log_stream(ctx); if (m_cluster != 0) { fprintf(log, "cannot initialize HyperDex cluster with id %lu " "because it is already initialized to %lu\n", token, m_cluster); // we lie to the client and pretend all is well return generate_response(ctx, COORD_SUCCESS); } replicant_state_machine_alarm(ctx, "alarm", ALARM_INTERVAL); fprintf(log, "initializing HyperDex cluster with id %lu\n", token); m_cluster = token; generate_next_configuration(ctx); return generate_response(ctx, COORD_SUCCESS); } void coordinator :: read_only(replicant_state_machine_context* ctx, bool ro) { FILE* log = replicant_state_machine_log_stream(ctx); uint64_t old_flags = m_flags; if (ro) { if ((m_flags & HYPERDEX_CONFIG_READ_ONLY)) { fprintf(log, "cluster already in read-only mode\n"); } else { fprintf(log, "putting cluster into read-only mode\n"); } m_flags |= HYPERDEX_CONFIG_READ_ONLY; } else { if ((m_flags & HYPERDEX_CONFIG_READ_ONLY)) { fprintf(log, "putting cluster into read-write mode\n"); } else { fprintf(log, "cluster already in read-write mode\n"); } uint64_t mask = HYPERDEX_CONFIG_READ_ONLY; mask = ~mask; m_flags &= mask; } if (old_flags != m_flags) { generate_next_configuration(ctx); } return generate_response(ctx, COORD_SUCCESS); } void coordinator :: server_register(replicant_state_machine_context* ctx, const server_id& sid, const po6::net::location& bind_to) { FILE* log = replicant_state_machine_log_stream(ctx); server* srv = get_server(sid); if (srv) { std::string str(to_string(srv->bind_to)); fprintf(log, "cannot register server(%lu) because the id belongs to " "server(%lu, %s)\n", sid.get(), srv->id.get(), str.c_str()); return generate_response(ctx, hyperdex::COORD_DUPLICATE); } srv = new_server(sid); srv->state = server::ASSIGNED; srv->bind_to = bind_to; fprintf(log, "registered server(%lu)\n", sid.get()); generate_next_configuration(ctx); return generate_response(ctx, COORD_SUCCESS); } void coordinator :: server_online(replicant_state_machine_context* ctx, const server_id& sid, const po6::net::location* bind_to) { FILE* log = replicant_state_machine_log_stream(ctx); server* srv = get_server(sid); if (!srv) { fprintf(log, "cannot bring server(%lu) online because " "the server doesn't exist\n", sid.get()); return generate_response(ctx, hyperdex::COORD_NOT_FOUND); } if (srv->state != server::ASSIGNED && srv->state != server::NOT_AVAILABLE && srv->state != server::SHUTDOWN && srv->state != server::AVAILABLE) { fprintf(log, "cannot bring server(%lu) online because the server is " "%s\n", sid.get(), server::to_string(srv->state)); return generate_response(ctx, hyperdex::COORD_NO_CAN_DO); } bool changed = false; if (bind_to && srv->bind_to != *bind_to) { std::string from(to_string(srv->bind_to)); std::string to(to_string(*bind_to)); for (size_t i = 0; i < m_servers.size(); ++i) { if (m_servers[i].id != sid && m_servers[i].bind_to == *bind_to) { fprintf(log, "cannot change server(%lu) to %s " "because that address is in use by " "server(%lu)\n", sid.get(), to.c_str(), m_servers[i].id.get()); return generate_response(ctx, hyperdex::COORD_DUPLICATE); } } fprintf(log, "changing server(%lu)'s address from %s to %s\n", sid.get(), from.c_str(), to.c_str()); srv->bind_to = *bind_to; changed = true; } if (srv->state != server::AVAILABLE) { fprintf(log, "changing server(%lu) from %s to %s\n", sid.get(), server::to_string(srv->state), server::to_string(server::AVAILABLE)); srv->state = server::AVAILABLE; if (!in_permutation(sid)) { add_permutation(sid); } rebalance_replica_sets(ctx); changed = true; } if (changed) { generate_next_configuration(ctx); } return generate_response(ctx, COORD_SUCCESS); } void coordinator :: server_offline(replicant_state_machine_context* ctx, const server_id& sid) { FILE* log = replicant_state_machine_log_stream(ctx); server* srv = get_server(sid); if (!srv) { fprintf(log, "cannot bring server(%lu) offline because " "the server doesn't exist\n", sid.get()); return generate_response(ctx, hyperdex::COORD_NOT_FOUND); } if (srv->state != server::ASSIGNED && srv->state != server::NOT_AVAILABLE && srv->state != server::AVAILABLE && srv->state != server::SHUTDOWN) { fprintf(log, "cannot bring server(%lu) offline because the server is " "%s\n", sid.get(), server::to_string(srv->state)); return generate_response(ctx, hyperdex::COORD_NO_CAN_DO); } if (srv->state != server::NOT_AVAILABLE && srv->state != server::SHUTDOWN) { fprintf(log, "changing server(%lu) from %s to %s\n", sid.get(), server::to_string(srv->state), server::to_string(server::NOT_AVAILABLE)); srv->state = server::NOT_AVAILABLE; remove_permutation(sid); rebalance_replica_sets(ctx); generate_next_configuration(ctx); } return generate_response(ctx, COORD_SUCCESS); } void coordinator :: server_shutdown(replicant_state_machine_context* ctx, const server_id& sid) { FILE* log = replicant_state_machine_log_stream(ctx); server* srv = get_server(sid); if (!srv) { fprintf(log, "cannot shutdown server(%lu) because " "the server doesn't exist\n", sid.get()); return generate_response(ctx, hyperdex::COORD_NOT_FOUND); } if (srv->state != server::ASSIGNED && srv->state != server::NOT_AVAILABLE && srv->state != server::AVAILABLE && srv->state != server::SHUTDOWN) { fprintf(log, "cannot shutdown server(%lu) because the server is " "%s\n", sid.get(), server::to_string(srv->state)); return generate_response(ctx, hyperdex::COORD_NO_CAN_DO); } if (srv->state != server::SHUTDOWN) { fprintf(log, "changing server(%lu) from %s to %s\n", sid.get(), server::to_string(srv->state), server::to_string(server::SHUTDOWN)); srv->state = server::SHUTDOWN; rebalance_replica_sets(ctx); generate_next_configuration(ctx); } return generate_response(ctx, COORD_SUCCESS); } void coordinator :: server_kill(replicant_state_machine_context* ctx, const server_id& sid) { FILE* log = replicant_state_machine_log_stream(ctx); server* srv = get_server(sid); if (!srv) { fprintf(log, "cannot kill server(%lu) because " "the server doesn't exist\n", sid.get()); return generate_response(ctx, hyperdex::COORD_NOT_FOUND); } if (srv->state != server::KILLED) { fprintf(log, "changing server(%lu) from %s to %s\n", sid.get(), server::to_string(srv->state), server::to_string(server::KILLED)); srv->state = server::KILLED; remove_permutation(sid); remove_offline(sid); rebalance_replica_sets(ctx); generate_next_configuration(ctx); } return generate_response(ctx, COORD_SUCCESS); } void coordinator :: server_forget(replicant_state_machine_context* ctx, const server_id& sid) { FILE* log = replicant_state_machine_log_stream(ctx); server* srv = get_server(sid); if (!srv) { fprintf(log, "cannot forget server(%lu) because " "the server doesn't exist\n", sid.get()); return generate_response(ctx, hyperdex::COORD_NOT_FOUND); } for (size_t i = 0; i < m_servers.size(); ++i) { if (m_servers[i].id == sid) { std::swap(m_servers[i], m_servers[m_servers.size() - 1]); m_servers.pop_back(); } } std::stable_sort(m_servers.begin(), m_servers.end()); remove_permutation(sid); remove_offline(sid); rebalance_replica_sets(ctx); generate_next_configuration(ctx); return generate_response(ctx, COORD_SUCCESS); } void coordinator :: server_suspect(replicant_state_machine_context* ctx, const server_id& sid, uint64_t version) { if (m_version == version) { server_offline(ctx, sid); } return generate_response(ctx, COORD_SUCCESS); } void coordinator :: space_add(replicant_state_machine_context* ctx, const space& _s) { FILE* log = replicant_state_machine_log_stream(ctx); if (!_s.validate()) { fprintf(log, "could not add space \"%s\" because the space does not validate\n", _s.name); return generate_response(ctx, COORD_MALFORMED); } if (m_spaces.find(std::string(_s.name)) != m_spaces.end()) { fprintf(log, "could not add space \"%s\" because there is already a space with that name\n", _s.name); return generate_response(ctx, COORD_DUPLICATE); } // Assign unique ids throughout the space std::tr1::shared_ptr<space> s(new space(_s)); s->id = space_id(m_counter); ++m_counter; for (size_t i = 0; i < s->subspaces.size(); ++i) { s->subspaces[i].id = subspace_id(m_counter); ++m_counter; for (size_t j = 0; j < s->subspaces[i].regions.size(); ++j) { s->subspaces[i].regions[j].id = region_id(m_counter); ++m_counter; s->subspaces[i].regions[j].replicas.clear(); } } m_spaces.insert(std::make_pair(std::string(s->name), s)); fprintf(log, "successfully added space \"%s\" with space(%lu)\n", s->name, s->id.get()); initial_space_layout(ctx, s.get()); generate_next_configuration(ctx); return generate_response(ctx, COORD_SUCCESS); } void coordinator :: space_rm(replicant_state_machine_context* ctx, const char* name) { FILE* log = replicant_state_machine_log_stream(ctx); space_map_t::iterator it; it = m_spaces.find(std::string(name)); if (it == m_spaces.end()) { fprintf(log, "could not remove space \"%s\" because it doesn't exist\n", name); return generate_response(ctx, COORD_NOT_FOUND); } else { space_id sid(it->second->id.get()); fprintf(log, "successfully removed space \"%s\"/space(%lu)\n", name, sid.get()); std::vector<region_id> rids; regions_in_space(it->second, &rids); std::sort(rids.begin(), rids.end()); m_spaces.erase(it); for (size_t i = 0; i < m_intents.size(); ) { if (std::binary_search(rids.begin(), rids.end(), m_intents[i].id)) { std::swap(m_intents[i], m_intents.back()); m_intents.pop_back(); } else { ++i; } } for (size_t i = 0; i < m_transfers.size(); ) { if (std::binary_search(rids.begin(), rids.end(), m_transfers[i].rid)) { std::swap(m_transfers[i], m_transfers.back()); m_transfers.pop_back(); } else { ++i; } } remove(sid, &m_deferred_init); generate_next_configuration(ctx); return generate_response(ctx, COORD_SUCCESS); } } void coordinator :: transfer_go_live(replicant_state_machine_context* ctx, uint64_t version, const transfer_id& xid) { FILE* log = replicant_state_machine_log_stream(ctx); transfer* xfer = get_transfer(xid); if (!xfer) { if (version < m_version) { return; } fprintf(log, "cannot make transfer(%lu) live because it doesn't exist\n", xid.get()); return generate_response(ctx, COORD_SUCCESS); } region* reg = get_region(xfer->rid); if (!reg) { fprintf(log, "cannot make transfer(%lu) live because it doesn't exist\n", xid.get()); INVARIANT_BROKEN("transfer refers to nonexistent region"); return generate_response(ctx, COORD_SUCCESS); } // If the transfer is already live if (reg->replicas.size() > 1 && reg->replicas[reg->replicas.size() - 2].si == xfer->src && reg->replicas[reg->replicas.size() - 1].si == xfer->dst) { return generate_response(ctx, COORD_SUCCESS); } if (reg->replicas.empty() || reg->replicas.back().si != xfer->src) { INVARIANT_BROKEN("transfer in a bad state"); return generate_response(ctx, COORD_SUCCESS); } reg->replicas.push_back(replica(xfer->dst, xfer->vdst)); fprintf(log, "transfer(%lu) is live\n", xid.get()); generate_next_configuration(ctx); return generate_response(ctx, COORD_SUCCESS); } void coordinator :: transfer_complete(replicant_state_machine_context* ctx, uint64_t version, const transfer_id& xid) { FILE* log = replicant_state_machine_log_stream(ctx); transfer* xfer = get_transfer(xid); if (!xfer) { if (version < m_version) { return; } fprintf(log, "cannot complete transfer(%lu) because it doesn't exist\n", xid.get()); return generate_response(ctx, COORD_SUCCESS); } region* reg = get_region(xfer->rid); if (!reg) { fprintf(log, "cannot complete transfer(%lu) because it doesn't exist\n", xid.get()); INVARIANT_BROKEN("transfer refers to nonexistent region"); return generate_response(ctx, COORD_SUCCESS); } if (!(reg->replicas.size() > 1 && reg->replicas[reg->replicas.size() - 2].si == xfer->src && reg->replicas[reg->replicas.size() - 1].si == xfer->dst)) { fprintf(log, "cannot complete transfer(%lu) because it is not live\n", xid.get()); return generate_response(ctx, COORD_SUCCESS); } del_transfer(xfer->id); fprintf(log, "transfer(%lu) is complete\n", xid.get()); converge_intent(ctx, reg); generate_next_configuration(ctx); return generate_response(ctx, COORD_SUCCESS); } void coordinator :: config_get(replicant_state_machine_context* ctx) { assert(m_cluster != 0 && m_version != 0); assert(m_latest_config.get()); const char* output = reinterpret_cast<const char*>(m_latest_config->data()); size_t output_sz = m_latest_config->size(); replicant_state_machine_set_response(ctx, output, output_sz); } void coordinator :: config_ack(replicant_state_machine_context* ctx, const server_id& sid, uint64_t version) { m_config_ack_barrier.pass(version, sid); check_ack_condition(ctx); } void coordinator :: config_stable(replicant_state_machine_context* ctx, const server_id& sid, uint64_t version) { m_config_stable_barrier.pass(version, sid); check_stable_condition(ctx); } void coordinator :: checkpoint(replicant_state_machine_context* ctx) { FILE* log = replicant_state_machine_log_stream(ctx); uint64_t cond_state = 0; if (replicant_state_machine_condition_broadcast(ctx, "checkp", &cond_state) < 0) { fprintf(log, "could not broadcast on \"checkp\" condition\n"); } ++m_checkpoint; fprintf(log, "establishing checkpoint %lu\n", m_checkpoint); assert(cond_state == m_checkpoint); assert(m_checkpoint_stable_through <= m_checkpoint); std::vector<server_id> sids; servers_in_configuration(&sids); m_checkpoint_stable_barrier.new_version(m_checkpoint, sids); check_checkpoint_stable_condition(ctx); } void coordinator :: checkpoint_stable(replicant_state_machine_context* ctx, const server_id& sid, uint64_t config, uint64_t number) { if (config < m_version) { return generate_response(ctx, COORD_NO_CAN_DO); } m_checkpoint_stable_barrier.pass(number, sid); check_checkpoint_stable_condition(ctx); generate_response(ctx, COORD_SUCCESS); } void coordinator :: alarm(replicant_state_machine_context* ctx) { replicant_state_machine_alarm(ctx, "alarm", ALARM_INTERVAL); checkpoint(ctx); } void coordinator :: debug_dump(replicant_state_machine_context* ctx) { FILE* log = replicant_state_machine_log_stream(ctx); fprintf(log, "=== begin debug dump ===========================================================\n"); fprintf(log, "permutation:\n"); for (size_t i = 0; i < m_permutation.size(); ++i) { fprintf(log, " - %lu\n", m_permutation[i].get()); } fprintf(log, "spares (desire %lu):\n", m_desired_spares); for (size_t i = 0; i < m_spares.size(); ++i) { fprintf(log, " - %lu\n", m_spares[i].get()); } fprintf(log, "intents:\n"); for (size_t i = 0; i < m_intents.size(); ++i) { fprintf(log, " - region=%lu, checkpoint=%lu replicas=[", m_intents[i].id.get(), m_intents[i].checkpoint); for (size_t j = 0; j < m_intents[i].replicas.size(); ++j) { if (j == 0) { fprintf(log, "%lu", m_intents[i].replicas[j].get()); } else { fprintf(log, ", %lu", m_intents[i].replicas[j].get()); } } fprintf(log, "]\n"); } fprintf(log, "transfers:\n"); for (size_t i = 0; i < m_transfers.size(); ++i) { fprintf(log, " - id=%lu rid=%lu src=%lu vsrc=%lu dst=%lu vdst=%lu\n", m_transfers[i].id.get(), m_transfers[i].rid.get(), m_transfers[i].src.get(), m_transfers[i].vsrc.get(), m_transfers[i].dst.get(), m_transfers[i].vdst.get()); } fprintf(log, "offline servers:\n"); for (size_t i = 0; i < m_offline.size(); ++i) { fprintf(log, " - rid=%lu sid=%lu\n", m_offline[i].id.get(), m_offline[i].sid.get()); } fprintf(log, "config ack through: %lu\n", m_config_ack_through); fprintf(log, "config stable through: %lu\n", m_config_stable_through); fprintf(log, "checkpoint: latest=%lu, stable=%lu, gc=%lu\n", m_checkpoint, m_checkpoint_stable_through, m_checkpoint_gc_through); fprintf(log, "=== end debug dump =============================================================\n"); } coordinator* coordinator :: recreate(replicant_state_machine_context* ctx, const char* data, size_t data_sz) { std::auto_ptr<coordinator> c(new coordinator()); if (!c.get()) { fprintf(replicant_state_machine_log_stream(ctx), "memory allocation failed\n"); return NULL; } e::unpacker up(data, data_sz); up = up >> c->m_cluster >> c->m_counter >> c->m_version >> c->m_flags >> c->m_servers >> c->m_permutation >> c->m_spares >> c->m_desired_spares >> c->m_intents >> c->m_deferred_init >> c->m_offline >> c->m_transfers >> c->m_config_ack_through >> c->m_config_ack_barrier >> c->m_config_stable_through >> c->m_config_stable_barrier >> c->m_checkpoint >> c->m_checkpoint_stable_through >> c->m_checkpoint_gc_through >> c->m_checkpoint_stable_barrier; while (!up.error() && up.remain()) { e::slice name; space_ptr ptr(new space()); up = up >> name >> *ptr; c->m_spaces[std::string(reinterpret_cast<const char*>(name.data()), name.size())] = ptr; } if (up.error()) { fprintf(replicant_state_machine_log_stream(ctx), "unpacking failed\n"); return NULL; } c->generate_cached_configuration(ctx); replicant_state_machine_alarm(ctx, "alarm", ALARM_INTERVAL); return c.release(); } void coordinator :: snapshot(replicant_state_machine_context* /*ctx*/, const char** data, size_t* data_sz) { size_t sz = sizeof(m_cluster) + sizeof(m_counter) + sizeof(m_version) + sizeof(m_flags) + pack_size(m_servers) + pack_size(m_permutation) + pack_size(m_spares) + sizeof(m_desired_spares) + pack_size(m_intents) + pack_size(m_deferred_init) + pack_size(m_offline) + pack_size(m_transfers) + sizeof(m_config_ack_through) + pack_size(m_config_ack_barrier) + sizeof(m_config_stable_through) + pack_size(m_config_stable_barrier) + sizeof(m_checkpoint) + sizeof(m_checkpoint_stable_through) + sizeof(m_checkpoint_gc_through) + pack_size(m_checkpoint_stable_barrier); for (space_map_t::iterator it = m_spaces.begin(); it != m_spaces.end(); ++it) { e::slice name(it->first); sz += pack_size(name) + pack_size(*it->second); } std::auto_ptr<e::buffer> buf(e::buffer::create(sz)); e::buffer::packer pa = buf->pack_at(0); pa = pa << m_cluster << m_counter << m_version << m_flags << m_servers << m_permutation << m_spares << m_desired_spares << m_intents << m_deferred_init << m_offline << m_transfers << m_config_ack_through << m_config_ack_barrier << m_config_stable_through << m_config_stable_barrier << m_checkpoint << m_checkpoint_stable_through << m_checkpoint_gc_through << m_checkpoint_stable_barrier; for (space_map_t::iterator it = m_spaces.begin(); it != m_spaces.end(); ++it) { e::slice name(it->first); pa = pa << name << (*it->second); } char* ptr = static_cast<char*>(malloc(buf->size())); *data = ptr; *data_sz = buf->size(); if (*data) { memmove(ptr, buf->data(), buf->size()); } } server* coordinator :: new_server(const server_id& sid) { size_t idx = m_servers.size(); m_servers.push_back(server(sid)); for (; idx > 0; --idx) { if (m_servers[idx - 1].id < m_servers[idx].id) { break; } std::swap(m_servers[idx - 1], m_servers[idx]); } return &m_servers[idx]; } server* coordinator :: get_server(const server_id& sid) { for (size_t i = 0; i < m_servers.size(); ++i) { if (m_servers[i].id == sid) { return &m_servers[i]; } } return NULL; } bool coordinator :: in_permutation(const server_id& sid) { for (size_t i = 0; i < m_permutation.size(); ++i) { if (m_permutation[i] == sid) { return true; } } for (size_t i = 0; i < m_spares.size(); ++i) { if (m_spares[i] == sid) { return true; } } return false; } void coordinator :: add_permutation(const server_id& sid) { if (m_spares.size() < m_desired_spares) { m_spares.push_back(sid); } else { m_permutation.push_back(sid); } } void coordinator :: remove_permutation(const server_id& sid) { remove(sid, &m_spares); for (size_t i = 0; i < m_permutation.size(); ++i) { if (m_permutation[i] != sid) { continue; } if (m_spares.empty()) { shift_and_pop(i, &m_permutation); } else { m_permutation[i] = m_spares.back(); m_spares.pop_back(); } break; } } namespace { bool compare_space_ptr_by_r_p(const std::tr1::shared_ptr<hyperdex::space>& lhs, const std::tr1::shared_ptr<hyperdex::space>& rhs) { if (lhs->fault_tolerance < rhs->fault_tolerance) { return true; } else if (lhs->fault_tolerance == rhs->fault_tolerance) { return lhs->predecessor_width < rhs->predecessor_width; } else { return false; } } } // namespace void coordinator :: rebalance_replica_sets(replicant_state_machine_context* ctx) { uint64_t R = 0; uint64_t P = 0; std::vector<server_id> replica_storage; std::vector<replica_set> replica_sets; std::vector<space_ptr> spaces; spaces.reserve(m_spaces.size()); for (space_map_t::iterator it = m_spaces.begin(); it != m_spaces.end(); ++it) { spaces.push_back(it->second); } std::sort(spaces.begin(), spaces.end(), compare_space_ptr_by_r_p); for (size_t i = 0; i < spaces.size(); ++i) { if (std::find(m_deferred_init.begin(), m_deferred_init.end(), spaces[i]->id) != m_deferred_init.end()) { remove(spaces[i]->id, &m_deferred_init); initial_space_layout(ctx, spaces[i].get()); continue; } if (spaces[i]->fault_tolerance + 1 != R || spaces[i]->predecessor_width != P) { R = spaces[i]->fault_tolerance + 1; P = spaces[i]->predecessor_width; compute_replica_sets(R, P, m_permutation, m_servers, &replica_storage, &replica_sets); } setup_intents(ctx, replica_sets, spaces[i].get(), false); } } void coordinator :: initial_space_layout(replicant_state_machine_context* ctx, space* s) { if (m_permutation.empty()) { m_deferred_init.push_back(s->id); return; } uint64_t R = s->fault_tolerance + 1; uint64_t P = s->predecessor_width; std::vector<server_id> replica_storage; std::vector<replica_set> replica_sets; compute_replica_sets(R, P, m_permutation, m_servers, &replica_storage, &replica_sets); setup_intents(ctx, replica_sets, s, true); } region* coordinator :: get_region(const region_id& rid) { for (space_map_t::iterator it = m_spaces.begin(); it != m_spaces.end(); ++it) { space& s(*it->second); for (size_t i = 0; i < s.subspaces.size(); ++i) { subspace& ss(s.subspaces[i]); for (size_t j = 0; j < ss.regions.size(); ++j) { if (ss.regions[j].id == rid) { return &ss.regions[j]; } } } } return NULL; } void coordinator :: setup_intents(replicant_state_machine_context* ctx, const std::vector<replica_set>& replica_sets, space* s, bool skip_transfers) { if (replica_sets.size() == 0) { return; } for (size_t ss_idx = 0; ss_idx < s->subspaces.size(); ++ss_idx) { subspace& ss(s->subspaces[ss_idx]); for (size_t reg_idx = 0; reg_idx < ss.regions.size(); ++reg_idx) { region* reg = &ss.regions[reg_idx]; size_t idx = (reg_idx * replica_sets.size()) / ss.regions.size(); assert(idx < replica_sets.size()); bool need_change = replica_sets[idx].size() != reg->replicas.size(); for (size_t i = 0; !need_change && i < replica_sets[idx].size(); ++i) { need_change = replica_sets[idx][i] != reg->replicas[i].si; } if (!need_change) { del_region_intent(reg->id); transfer* xfer = get_transfer(reg->id); // delete the transfer if we're OK with 0 replicas, or the // transfer is adding a replica (that is, it's not gone-live // yet). if (xfer && (reg->replicas.empty() || xfer->dst != reg->replicas.back().si)) { del_transfer(xfer->id); } continue; } if (skip_transfers) { assert(reg->replicas.empty()); for (size_t i = 0; i < replica_sets[idx].size(); ++i) { reg->replicas.push_back(replica(replica_sets[idx][i], virtual_server_id(m_counter))); ++m_counter; } } else { region_intent* ri = get_region_intent(reg->id); if (!ri) { ri = new_region_intent(reg->id); } ri->replicas.resize(replica_sets[idx].size()); ri->checkpoint = 0; for (size_t i = 0; i < replica_sets[idx].size(); ++i) { ri->replicas[i] = replica_sets[idx][i]; } converge_intent(ctx, reg, ri); } } } } void coordinator :: converge_intent(replicant_state_machine_context* ctx, region* reg) { region_intent* ri = get_region_intent(reg->id); if (ri) { converge_intent(ctx, reg, ri); } } void coordinator :: converge_intent(replicant_state_machine_context* ctx, region* reg, region_intent* ri) { FILE* log = replicant_state_machine_log_stream(ctx); // if there is a transfer transfer* xfer = get_transfer(reg->id); if (xfer) { for (size_t i = 0; i < ri->replicas.size(); ++i) { // there's already a transfer in progress that's helping this region // converge to the region_intent if (xfer->dst == ri->replicas[i]) { return; } } del_transfer(xfer->id); xfer = NULL; } // there are no transfers for this region at this point if (!reg->replicas.empty() && !((m_flags & HYPERDEX_CONFIG_READ_ONLY) && m_version == m_config_stable_through)) { remove_offline(reg->id); } // remove every server that is not AVAILABLE for (size_t i = 0; i < reg->replicas.size(); ) { server* s = get_server(reg->replicas[i].si); if (!s) { INVARIANT_BROKEN("server referenced but not found"); continue; } if (s->state != server::AVAILABLE) { if ((reg->replicas.size() == 1 || ((m_flags & HYPERDEX_CONFIG_READ_ONLY) && m_version == m_config_stable_through)) && s->state == server::SHUTDOWN) { m_offline.push_back(offline_server(reg->id, s->id)); } else if (reg->replicas.size() == 1) { fprintf(log, "refusing to remove the last server from " "region(%lu) because it was not a clean shutdown\n", reg->id.get()); return; } fprintf(log, "removing server(%lu) from region(%lu) " "because it is in state %s\n", reg->replicas[i].si.get(), reg->id.get(), server::to_string(s->state)); shift_and_pop(i, &reg->replicas); } else { ++i; } } // now remove any excess replicas for (size_t i = 0; i < reg->replicas.size(); ) { // no excess exist yet if (reg->replicas.size() <= ri->replicas.size()) { break; } // if we don't intend to converge with this replica, remove it if (std::find(ri->replicas.begin(), ri->replicas.end(), reg->replicas[i].si) == ri->replicas.end()) { if (reg->replicas.size() == 1) { fprintf(log, "refusing to remove the last server from " "region(%lu) because we need it to transfer data\n", reg->id.get()); return; } fprintf(log, "removing server(%lu) from region(%lu) " "to make progress toward desired state\n", reg->replicas[i].si.get(), reg->id.get()); shift_and_pop(i, &reg->replicas); } else { ++i; } } if (reg->replicas.empty() && ri->replicas.empty()) { del_region_intent(reg->id); return; } if (reg->replicas.empty()) { for (size_t i = 0; i < m_offline.size(); ++i) { if (m_offline[i].id != reg->id) { continue; } server* s = get_server(m_offline[i].sid); if (s && s->state == server::AVAILABLE) { reg->replicas.push_back(replica(m_offline[i].sid, virtual_server_id(m_counter))); ++m_counter; fprintf(log, "restoring offline server(%lu) to region(%lu)\n", m_offline[i].sid.get(), reg->id.get()); remove_offline(reg->id); break; } } } if (reg->replicas.empty()) { fprintf(log, "cannot transfer state to new servers in " "region(%lu) because all servers are offline\n", reg->id.get()); return; } // add up to one server from the region_intent for (size_t i = 0; i < ri->replicas.size(); ++i) { bool found = false; for (size_t j = 0; j < reg->replicas.size(); ++j) { if (ri->replicas[i] == reg->replicas[j].si) { found = true; break; } } if (found) { continue; } xfer = new_transfer(reg, ri->replicas[i]); assert(xfer); fprintf(log, "adding server(%lu) to region(%lu) " "copying from server(%lu)/virtual_server(%lu) " "using transfer(%lu)/virtual_server(%lu)\n", xfer->dst.get(), reg->id.get(), xfer->src.get(), xfer->vsrc.get(), xfer->id.get(), xfer->vdst.get()); return; } if (ri->checkpoint == 0) { ri->checkpoint = m_checkpoint > 0 ? m_checkpoint : 1; } // now shuffle to make the order consistent with ri->replicas for (size_t i = 1; i < reg->replicas.size(); ++i) { server_id* start = &ri->replicas[0]; server_id* limit = start + ri->replicas.size(); // idx1 is the index of reg->replicas[i - 1] in ri->replicas size_t idx1 = std::find(start, limit, reg->replicas[i - 1].si) - start; // idx2 is the index of reg->replicas[i - 0] in ri->replicas size_t idx2 = std::find(start, limit, reg->replicas[i - 0].si) - start; if (idx1 < idx2) { continue; } if (ri->checkpoint >= m_checkpoint_stable_through) { fprintf(log, "postponing convergence until after checkpoint %lu is stable\n", ri->checkpoint); return; } // grab the server id server_id sid = reg->replicas[i - 1].si; // remove the idx1 replica shift_and_pop(i - 1, &reg->replicas); // now do a transfer to roll it to the end ri->checkpoint = 0; xfer = new_transfer(reg, sid); assert(xfer); fprintf(log, "rolling server(%lu) to the back of region(%lu) " "using transfer(%lu)/virtual_server(%lu)\n", xfer->dst.get(), reg->id.get(), xfer->id.get(), xfer->vdst.get()); return; } del_region_intent(reg->id); } region_intent* coordinator :: new_region_intent(const region_id& rid) { size_t idx = m_intents.size(); m_intents.push_back(region_intent(rid)); for (; idx > 0; --idx) { if (m_intents[idx - 1].id < m_intents[idx].id) { break; } std::swap(m_intents[idx - 1], m_intents[idx]); } return &m_intents[idx]; } region_intent* coordinator :: get_region_intent(const region_id& rid) { for (size_t i = 0; i < m_intents.size(); ++i) { if (m_intents[i].id == rid) { return &m_intents[i]; } } return NULL; } void coordinator :: del_region_intent(const region_id& rid) { remove_id(rid, &m_intents); } void coordinator :: remove_offline(const region_id& rid) { for (size_t i = 0; i < m_offline.size(); ) { if (m_offline[i].id == rid) { shift_and_pop(i, &m_offline); } else { ++i; } } } void coordinator :: remove_offline(const server_id& sid) { for (size_t i = 0; i < m_offline.size(); ) { if (m_offline[i].sid == sid) { shift_and_pop(i, &m_offline); } else { ++i; } } } transfer* coordinator :: new_transfer(region* reg, const server_id& sid) { assert(!reg->replicas.empty()); m_transfers.push_back(transfer()); transfer* t = &m_transfers.back(); t->id = transfer_id(m_counter); ++m_counter; t->rid = reg->id; t->src = reg->replicas.back().si; t->vsrc = reg->replicas.back().vsi; t->dst = sid; t->vdst = virtual_server_id(m_counter); ++m_counter; return t; } transfer* coordinator :: get_transfer(const region_id& rid) { for (size_t i = 0; i < m_transfers.size(); ++i) { if (m_transfers[i].rid == rid) { return &m_transfers[i]; } } return NULL; } transfer* coordinator :: get_transfer(const transfer_id& xid) { for (size_t i = 0; i < m_transfers.size(); ++i) { if (m_transfers[i].id == xid) { return &m_transfers[i]; } } return NULL; } void coordinator :: del_transfer(const transfer_id& xid) { for (size_t i = 0; i < m_transfers.size(); ++i) { if (m_transfers[i].id != xid) { continue; } for (size_t j = i + 1; j < m_transfers.size(); ++j) { m_transfers[j - 1] = m_transfers[j]; } m_transfers.pop_back(); break; } } void coordinator :: check_ack_condition(replicant_state_machine_context* ctx) { if (m_config_ack_through < m_config_ack_barrier.min_version()) { FILE* log = replicant_state_machine_log_stream(ctx); fprintf(log, "acked through version %lu\n", m_config_ack_barrier.min_version()); } while (m_config_ack_through < m_config_ack_barrier.min_version()) { replicant_state_machine_condition_broadcast(ctx, "ack", &m_config_ack_through); } } void coordinator :: check_stable_condition(replicant_state_machine_context* ctx) { if (m_config_stable_through < m_config_stable_barrier.min_version()) { FILE* log = replicant_state_machine_log_stream(ctx); fprintf(log, "stable through version %lu\n", m_config_stable_barrier.min_version()); } while (m_config_stable_through < m_config_stable_barrier.min_version()) { replicant_state_machine_condition_broadcast(ctx, "stable", &m_config_stable_through); } } void coordinator :: generate_next_configuration(replicant_state_machine_context* ctx) { FILE* log = replicant_state_machine_log_stream(ctx); uint64_t cond_state; if (replicant_state_machine_condition_broadcast(ctx, "config", &cond_state) < 0) { fprintf(log, "could not broadcast on \"config\" condition\n"); } ++m_version; fprintf(log, "issuing new configuration version %lu\n", m_version); assert(cond_state == m_version); std::vector<server_id> sids; servers_in_configuration(&sids); m_config_ack_barrier.new_version(m_version, sids); m_config_stable_barrier.new_version(m_version, sids); check_ack_condition(ctx); check_stable_condition(ctx); generate_cached_configuration(ctx); } void coordinator :: generate_cached_configuration(replicant_state_machine_context*) { m_latest_config.reset(); size_t sz = 7 * sizeof(uint64_t); for (size_t i = 0; i < m_servers.size(); ++i) { sz += pack_size(m_servers[i]); } for (std::map<std::string, std::tr1::shared_ptr<space> >::iterator it = m_spaces.begin(); it != m_spaces.end(); ++it) { sz += pack_size(*it->second); } for (size_t i = 0; i < m_transfers.size(); ++i) { sz += pack_size(m_transfers[i]); } std::auto_ptr<e::buffer> new_config(e::buffer::create(sz)); e::buffer::packer pa = new_config->pack_at(0); pa = pa << m_cluster << m_version << m_flags << uint64_t(m_servers.size()) << uint64_t(m_spaces.size()) << uint64_t(m_transfers.size()); for (size_t i = 0; i < m_servers.size(); ++i) { pa = pa << m_servers[i]; } for (std::map<std::string, std::tr1::shared_ptr<space> >::iterator it = m_spaces.begin(); it != m_spaces.end(); ++it) { pa = pa << *it->second; } for (size_t i = 0; i < m_transfers.size(); ++i) { pa = pa << m_transfers[i]; } m_latest_config = new_config; } void coordinator :: servers_in_configuration(std::vector<server_id>* sids) { for (std::map<std::string, std::tr1::shared_ptr<space> >::iterator it = m_spaces.begin(); it != m_spaces.end(); ++it) { space& s(*it->second); for (size_t i = 0; i < s.subspaces.size(); ++i) { subspace& ss(s.subspaces[i]); for (size_t j = 0; j < ss.regions.size(); ++j) { region& reg(ss.regions[j]); for (size_t k = 0; k < reg.replicas.size(); ++k) { sids->push_back(reg.replicas[k].si); } } } } for (size_t i = 0; i < m_transfers.size(); ++i) { sids->push_back(m_transfers[i].src); sids->push_back(m_transfers[i].dst); } std::sort(sids->begin(), sids->end()); std::vector<server_id>::iterator sit; sit = std::unique(sids->begin(), sids->end()); sids->resize(sit - sids->begin()); } void coordinator :: regions_in_space(space_ptr s, std::vector<region_id>* rids) { for (size_t i = 0; i < s->subspaces.size(); ++i) { subspace& ss(s->subspaces[i]); for (size_t j = 0; j < ss.regions.size(); ++j) { rids->push_back(ss.regions[j].id); } } } #define OUTSTANDING_CHECKPOINTS 120 void coordinator :: check_checkpoint_stable_condition(replicant_state_machine_context* ctx) { FILE* log = replicant_state_machine_log_stream(ctx); assert(m_checkpoint_stable_through <= m_checkpoint); if (m_checkpoint_stable_through < m_checkpoint_stable_barrier.min_version()) { fprintf(log, "checkpoint %lu done\n", m_checkpoint_stable_barrier.min_version()); } bool stabilized = false; while (m_checkpoint_stable_through < m_checkpoint_stable_barrier.min_version()) { stabilized = true; replicant_state_machine_condition_broadcast(ctx, "checkps", &m_checkpoint_stable_through); } bool gc = false; while (m_checkpoint_gc_through + OUTSTANDING_CHECKPOINTS < m_checkpoint_stable_barrier.min_version()) { gc = true; replicant_state_machine_condition_broadcast(ctx, "checkpgc", &m_checkpoint_gc_through); } if (gc && m_checkpoint_gc_through > 0) { fprintf(log, "garbage collect <= checkpoint %lu\n", m_checkpoint_gc_through); } assert(m_checkpoint_stable_through <= m_checkpoint); assert(m_checkpoint_gc_through + OUTSTANDING_CHECKPOINTS <= m_checkpoint || m_checkpoint <= OUTSTANDING_CHECKPOINTS); if (stabilized) { std::vector<region_id> rids; rids.reserve(m_intents.size()); // two pass because converge_intent can alter m_intents for (size_t i = 0; i < m_intents.size(); ++i) { if (m_intents[i].checkpoint > 0 && m_intents[i].checkpoint < m_checkpoint_stable_through) { rids.push_back(m_intents[i].id); } } for (size_t i = 0; i < rids.size(); ++i) { region* reg = get_region(rids[i]); converge_intent(ctx, reg); } if (!rids.empty()) { generate_next_configuration(ctx); } } }
[ "me@robescriva.com" ]
me@robescriva.com
f07ebbc7b0b1d4987943eab742bbcbe8b175679e
31247135e30b58985098ecb4b47553f0923a2f64
/Play/Source/s3stream/S3ObjectStream.h
90e1ff9127026c157a096d483e6b614cc8cfa1a1
[ "BSD-2-Clause" ]
permissive
johnny-mac/play
7cba594a70f1be115bb444549e5a7f54de398ffb
256348891e0a652e8b5e4b6feb9ee97957a95533
refs/heads/master
2020-03-28T18:17:05.775478
2018-09-15T04:05:01
2018-09-15T04:05:01
148,868,025
0
0
null
null
null
null
UTF-8
C++
false
false
715
h
#pragma once #include "Stream.h" #include "boost_filesystem_def.h" class CS3ObjectStream : public Framework::CStream { public: CS3ObjectStream(const char*, const char*); uint64 Read(void*, uint64) override; uint64 Write(const void*, uint64) override; void Seek(int64, Framework::STREAM_SEEK_DIRECTION) override; uint64 Tell() override; bool IsEOF() override; private: static boost::filesystem::path GetCachePath(); std::string GenerateReadCacheKey(const std::pair<uint64, uint64>&) const; void GetObjectInfo(); std::string m_bucketName; std::string m_bucketRegion; std::string m_objectName; //Object Metadata uint64 m_objectSize = 0; std::string m_objectEtag; uint64 m_objectPosition = 0; };
[ "kk199469@gmail.com" ]
kk199469@gmail.com
43a79b9983a8d89a7d845477b19ee9bcccc33191
aaf8bc7c8113795e97e7c6f13bc33ab8e709ff89
/ARClassProject/BlockWalls.cpp
f6b4cac139bf644fa58f78777d7144749d912835
[ "MIT" ]
permissive
Atsu30/GorillaBeat
6e9a83c20b4b878f9ff236183bae0957d7ebc479
ebd56849858fa65f2c767fb8083e01f8a00124e4
refs/heads/master
2020-05-27T22:32:12.974690
2019-06-08T08:11:10
2019-06-08T08:11:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
656
cpp
// // BlockWalls.cpp // ARClassProject // // Created by Xia Yu on 2019/06/07. // Copyright © 2019 森敦史. All rights reserved. // #include "BlockWalls.hpp" #include "DrawPrimitives.h" void BlockWalls::draw(float* resultTransposedMatrix){ glLoadIdentity(); glLoadMatrixf( resultTransposedMatrix); //glTranslatef((float) pos.x, (float) pos.y, 0); glColor4f(0,0,0,1); drawCube(0.01, 0.05, 0.01); pos.x=resultTransposedMatrix[12]; pos.y=resultTransposedMatrix[13]; pos.z=resultTransposedMatrix[14]; std::cout << pos << std:: endl; length = 0.01; height = 0.05; width = 0.01; }
[ "yu.xia@ar.c.titech.ac.jp" ]
yu.xia@ar.c.titech.ac.jp
c805aa3586ca7d0df9d4a4ce2fbe60335a945f73
b53795b88ab0201e48c5dc5737e97dfd27e07b22
/source/server/game/src/fifo_allocator.h
6ebd6177068eb43abd5e3d6dad4b3f015aadeb44
[]
no_license
davidkm2/globalmetin
9cc63395974eb74b5784a1bf5e733622c7303aa4
d1a21b549c68e311416544e03ca6218351e12d2f
refs/heads/main
2023-05-27T08:10:08.506239
2021-05-24T01:57:37
2021-05-24T01:57:37
370,181,109
2
1
null
null
null
null
UTF-8
C++
false
false
1,678
h
#ifndef _FIFO_ALLOCATOR_H_ #define _FIFO_ALLOCATOR_H_ #include <deque> #include <unordered_map> // Allocator implementation detail with simple FIFO grow-only pool. // It relies on default CRT malloc/free. class FifoAllocator { public: FifoAllocator() {} ~FifoAllocator() {} void SetUp() {} void TearDown() { CleanUp(); // deallocate pooled blocks } void* Alloc(size_t size) { void* p = NULL; PoolType& pool = pool_map_[size]; if (pool.size() < kWatermark) { p = ::malloc(size); } else { p = pool.front(); pool.pop_front(); } if (p != NULL) { alloc_map_[p] = size; } return p; } void Free(void* p) { if (p == NULL) { return; } AllocMapType::iterator it = alloc_map_.find(p); if (it == alloc_map_.end()) { return; } size_t size = it->second; alloc_map_.erase(it); PoolMapType::iterator it2 = pool_map_.find(size); if (it2 == pool_map_.end()) { return; } PoolType& pool = it2->second; pool.push_back(p); } private: void CleanUp() { PoolMapType::iterator it = pool_map_.begin(), end = pool_map_.end(); for ( ; it != end; ++it) { PoolType& pool = it->second; PoolType::iterator it2 = pool.begin(), end2 = pool.end(); for ( ; it2 != end2; ++it2) { ::free(*it2); } pool.clear(); } pool_map_.clear(); } typedef std::deque<void*> PoolType; typedef std::unordered_map<size_t, PoolType> PoolMapType; typedef std::unordered_map<void*, size_t> AllocMapType; static const size_t kWatermark = 4; // FIFO enforcement level PoolMapType pool_map_; AllocMapType alloc_map_; }; #endif // _FIFO_ALLOCATOR_H_
[ "davidkm2012@gmail.com" ]
davidkm2012@gmail.com
3941f07bdb578a4b87749bf9d92b0fe113ae1f94
7d71fa3604d4b0538f19ed284bc5c7d8b52515d2
/Clients/AG/Shared/File.h
85b37e3a888f340ce7d628db5ebd7bdaa7d69710
[]
no_license
lineCode/ArchiveGit
18e5ddca06330018e4be8ab28c252af3220efdad
f9cf965cb7946faa91b64e95fbcf8ad47f438e8b
refs/heads/master
2020-12-02T09:59:37.220257
2016-01-20T23:55:26
2016-01-20T23:55:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,625
h
// File.h: interface for the CXFile class. // ////////////////////////////////////////////////////////////////////// #if !defined FILE_WTL_H #define FILE_WTL_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #pragma warning( disable : 4290 ) // a function is declared using exception specification, // which Visual C++ accepts but does not implement #include "Exception.h" //----------------------------------------------------------------------------- // Class CXFile implements basic nonbuffered file access that is a wrapper // around the Windows file APIs. //----------------------------------------------------------------------------- class CXFile { public: enum SeekPosition { begin = 0x0, current = 0x1, end = 0x2 }; // Constructors, destructor CXFile(); CXFile(HANDLE hFile); virtual ~CXFile(); // Attributes HANDLE m_hFile; // Operations virtual DWORD GetPosition() const throw(CXFileException); virtual string GetFileName() const; virtual string GetFilePath() const; virtual void SetFilePath(string strNewName); virtual void Open(string strFileName, DWORD dwAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSA, DWORD dwCreationDisposition, DWORD dwAttributes, HANDLE hTemplateFile) throw(CXFileException); static void Rename(string strOldName, string strNewName) throw(CXFileException); static void Remove(string strFileName) throw(CXFileException); DWORD SeekToEnd() throw(CXFileException); DWORD SeekToBegin() throw(CXFileException); virtual CXFile * Duplicate() const throw(CXFileException); virtual DWORD Seek(LONG lOff, UINT nFrom) throw(CXFileException); virtual void SetLength(DWORD dwNewLen) throw(CXFileException); virtual DWORD GetLength() const throw(CXFileException); virtual DWORD Read(void* lpBuf, DWORD nCount, LPOVERLAPPED lpOverlapped = NULL) throw(CXFileException); virtual void Write(const void* lpBuf, DWORD nCount) throw(CXFileException); void WriteEndOfLine() throw(CXFileException); virtual void LockRange(DWORD dwPos, DWORD dwCount) throw(CXFileException); virtual void UnlockRange(DWORD dwPos, DWORD dwCount) throw(CXFileException); virtual void Abort() throw(); virtual void Flush() throw(CXFileException); virtual void Close() throw(CXFileException); enum BufferCommand { bufferRead, bufferWrite, bufferCommit, bufferCheck, bufferBlocking, bufferDirect }; virtual UINT GetBufferPtr(UINT nCommand, UINT nCount = 0, void** ppBufStart = NULL, void** ppBufMax = NULL); protected: string m_strFileName; // stores the file name for the current file }; #endif // !defined FILE_WTL_H
[ "jim@facetofacesoftware.com" ]
jim@facetofacesoftware.com
8c7db3c1eb3b75c31ba0eb74012ccd834dd233cd
5a19f0763cccd59abe5617d842301e4e7fe25a13
/source/hougfx/include/hou/gfx/glyph.hpp
a5f559354eeb67e2ce81fd607c86be10ab5eabba
[ "MIT" ]
permissive
DavideCorradiDev/houzi-game-engine
6bfec0a8580ff4e33defaa30b1e5b490a4224fba
d704aa9c5b024300578aafe410b7299c4af4fcec
refs/heads/master
2020-03-09T01:34:13.718230
2019-02-02T09:53:24
2019-02-02T09:53:24
128,518,126
2
0
null
null
null
null
UTF-8
C++
false
false
2,011
hpp
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #ifndef HOU_GFX_GLYPH_HPP #define HOU_GFX_GLYPH_HPP #include "hou/gfx/gfx_config.hpp" #include "hou/gfx/glyph_metrics.hpp" #include "hou/sys/image.hpp" #include <iostream> namespace hou { /** Class describing a glyph, including its metrics and its bitmap image. */ class HOU_GFX_API glyph { public: /** default constructor. * * The image is empty and the metrics are all null. * * \throws std::bad_alloc. */ glyph(); /** Creates a glyph object with the given image and metrics. * * \param im the image. * * \param metrics the metrics. * * \throws std::bad_alloc. */ glyph(const image2_r& im, const glyph_metrics& metrics); /** Gets the image. * * \return the image. */ const image2_r& get_image() const noexcept; /** Sets the image. * * \param im the image. */ void set_image(const image2_r& im); /** Gets the metrics. * * \return the metrics. */ const glyph_metrics& get_metrics() const noexcept; /** Sets the metrics. * * \param metrics the metrics. */ void set_metrics(const glyph_metrics& metrics) noexcept; private: image2_r m_image; glyph_metrics m_metrics; }; /** Checks if two glyph objects are equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return true if the two objects are equal, */ HOU_GFX_API bool operator==(const glyph& lhs, const glyph& rhs) noexcept; /** Checks if two glyph objects are not equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return true if the two objects are not equal, */ HOU_GFX_API bool operator!=(const glyph& lhs, const glyph& rhs) noexcept; /** Writes a glyph object into a stream. * * \param os the output stream. * * \param gm the object. * * \return a reference to os. */ HOU_GFX_API std::ostream& operator<<(std::ostream& os, const glyph& gm); } // namespace hou #endif
[ "davide.corradi.dev@gmail.com" ]
davide.corradi.dev@gmail.com
96669108416f5ebb02ea8c920a1b356862dd6210
3fc907bfd5493d4054380c1db9bff50444cb8f04
/EinfBV/src/Graphics2D/PrimitiveRectangle.cpp
49d893a6b0805734beb845b09016e1bb61f5ba65
[]
no_license
kallegonzales/Bildverarbeitung
717843f7398ec086755c7fee1c7a223b0ab65023
5bcdfe8b923c3ccee7abc71106bd442869960923
refs/heads/master
2020-06-14T07:15:32.037817
2016-11-29T22:13:12
2016-11-29T22:13:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
445
cpp
#include "PrimitiveRectangle.hh" #include <iostream> using namespace std; PrimitiveRectangle:: PrimitiveRectangle(const Color &color, const Float2D &topLeft, const Float2D &bottomRight) : PrimitivePolygon(color, 4) { SetPoint(0, topLeft); SetPoint(1, Float2D(bottomRight[0], topLeft[1])); SetPoint(2, bottomRight); SetPoint(3, Float2D(topLeft[0], bottomRight[1])); } PrimitiveRectangle::~PrimitiveRectangle() { }
[ "stu126998@informatik.uni-kiel.de" ]
stu126998@informatik.uni-kiel.de
b289bdb13c46e7b66bc3238805988caddf1b007a
3c5c1e3836edf3e9627a64600785503d1814df51
/build/Android/Debug/app/src/main/include/Fuse.Drawing.ISurfaceDrawable.h
d2ef947f42315958e88cc70b6edb451437680921
[]
no_license
fypwyt/wytcarpool
70a0c9ca12d0f2981187f2ea21a8a02ee4cbcbd4
4fbdeedf261ee8ecd563260816991741ec701432
refs/heads/master
2021-09-08T10:32:17.612628
2018-03-09T05:24:54
2018-03-09T05:24:54
124,490,692
0
0
null
null
null
null
UTF-8
C++
false
false
1,393
h
// This file was generated based on C:/Users/Brian/AppData/Local/Fusetools/Packages/Fuse.Drawing.Surface/1.6.0/Surface.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Fuse{namespace Drawing{struct Surface;}}} namespace g{namespace Uno{struct Float2;}} namespace g{ namespace Fuse{ namespace Drawing{ // public abstract interface ISurfaceDrawable :168 // { uInterfaceType* ISurfaceDrawable_typeof(); struct ISurfaceDrawable { void(*fp_Draw)(uObject*, ::g::Fuse::Drawing::Surface*); void(*fp_get_ElementSize)(uObject*, ::g::Uno::Float2*); void(*fp_get_IsPrimary)(uObject*, bool*); static void Draw(const uInterface& __this, ::g::Fuse::Drawing::Surface* surface) { __this.VTable<ISurfaceDrawable>()->fp_Draw(__this, surface); } static ::g::Uno::Float2 ElementSize(const uInterface& __this); static bool IsPrimary(const uInterface& __this) { bool __retval; return __this.VTable<ISurfaceDrawable>()->fp_get_IsPrimary(__this, &__retval), __retval; } }; }}} // ::g::Fuse::Drawing #include <Uno.Float2.h> namespace g{ namespace Fuse{ namespace Drawing{ inline ::g::Uno::Float2 ISurfaceDrawable::ElementSize(const uInterface& __this) { ::g::Uno::Float2 __retval; return __this.VTable<ISurfaceDrawable>()->fp_get_ElementSize(__this, &__retval), __retval; } // } }}} // ::g::Fuse::Drawing
[ "s1141120@studentdmn.ouhk.edu.hk" ]
s1141120@studentdmn.ouhk.edu.hk
40cfb79307b192fbc11f4e97d3468725bad7424e
51b58a4373a4134ec5a13223a82a0b6b8823404f
/code/header/Game.h
944936d8a624971af4f5ce3659b2838916c1bc99
[]
no_license
mariaviolaki/vamp-man
f4eebc4ffd4c46a91e3e736f600f29c2c2319771
47047c4b9b4a7c96dbed779915a851ebff7356ad
refs/heads/master
2022-11-08T02:31:16.250840
2020-06-29T04:04:16
2020-06-29T04:04:16
275,660,699
0
0
null
null
null
null
UTF-8
C++
false
false
1,147
h
#ifndef GAME_H #define GAME_H #include "../header/Map.h" #include "../header/Player.h" #include "../header/Garlic.h" #include "../header/MessageManager.h" #include "../header/CollisionManager.h" #include "SDL2/SDL.h" #include <string> #include <memory> // Forward class declaration class MessageManager; class Game { public: // Constructor / Destructor Game(); ~Game(); // Accessors / Mutators bool IsRunning() const; // Typical behavior methods void Init(std::string title, int width, int height, bool fullscreen); void HandleInput(); void Update(); void Render(); // Static variables of the class static const int sWindowWidth; static const int sWindowHeight; static SDL_Renderer* sRenderer; private: SDL_Window* pWindow; bool mIsRunning; // Unique pointers std::unique_ptr<Map> pMap; std::unique_ptr<Player> pPlayer; std::unique_ptr<Garlic> pGarlic1; std::unique_ptr<Garlic> pGarlic2; std::unique_ptr<Garlic> pGarlic3; std::unique_ptr<CollisionManager> pCollisionManager; std::unique_ptr<MessageManager> pMessageManager; }; #endif // GAME_H
[ "mariaviolaki@outlook.com" ]
mariaviolaki@outlook.com
c076c53469f805141a790d5bb6e5ae9f76d0849e
beaeefee8412d35e8afee2643098dbc3870d47bc
/src/EAWebkit/Webkit-owb/BAL/OWBAL/Concretizations/Types/WK/BCRefPtrWK.h
52f108ad31d0309c0c57874973ecf0267ee31179
[]
no_license
weimingtom/duibrowser
831d13626c8560b2b4c270dcc8d2bde746fe8dba
74f4b51f741978f5a9d3b3509e6267fd261e9d3f
refs/heads/master
2021-01-10T01:36:36.573836
2012-05-11T16:38:17
2012-05-11T16:38:17
43,038,328
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
6,554
h
// -*- mode: c++; c-basic-offset: 4 -*- /* * Copyright (C) 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ /* * This file was modified by Electronic Arts Inc Copyright © 2009-2010 */ #ifndef WTF_RefPtr_h #define WTF_RefPtr_h #include <wtf/FastAllocBase.h> #include <algorithm> #include "AlwaysInline.h" namespace WTF { enum PlacementNewAdoptType { PlacementNewAdopt }; template <typename T> class PassRefPtr; enum HashTableDeletedValueType { HashTableDeletedValue }; template <typename T> class RefPtr/*: public WTF::FastAllocBase*/ { public: RefPtr() : m_ptr(0) { } RefPtr(T* ptr) : m_ptr(ptr) { if (ptr) ptr->ref(); } RefPtr(const RefPtr& o) : m_ptr(o.m_ptr) { if (T* ptr = m_ptr) ptr->ref(); } // see comment in PassRefPtr.h for why this takes const reference template <typename U> RefPtr(const PassRefPtr<U>&); // Special constructor for cases where we overwrite an object in place. RefPtr(PlacementNewAdoptType) { } // Hash table deleted values, which are only constructed and never copied or destroyed. RefPtr(HashTableDeletedValueType) : m_ptr(hashTableDeletedValue()) { } bool isHashTableDeletedValue() const { return m_ptr == hashTableDeletedValue(); } ~RefPtr() { if (T* ptr = m_ptr) ptr->deref(); } template <typename U> RefPtr(const RefPtr<U>& o) : m_ptr(o.get()) { if (T* ptr = m_ptr) ptr->ref(); } T* get() const { return m_ptr; } void clear() { if (T* ptr = m_ptr) ptr->deref(); m_ptr = 0; } PassRefPtr<T> release() { PassRefPtr<T> tmp = adoptRef(m_ptr); m_ptr = 0; return tmp; } T& operator*() const { return *m_ptr; } ALWAYS_INLINE T* operator->() const { return m_ptr; } bool operator!() const { return !m_ptr; } // This conversion operator allows implicit conversion to bool but not to other integer types. typedef T* RefPtr::*UnspecifiedBoolType; operator UnspecifiedBoolType() const { return m_ptr ? &RefPtr::m_ptr : 0; } RefPtr& operator=(const RefPtr&); RefPtr& operator=(T*); RefPtr& operator=(const PassRefPtr<T>&); template <typename U> RefPtr& operator=(const RefPtr<U>&); template <typename U> RefPtr& operator=(const PassRefPtr<U>&); void swap(RefPtr&); private: static T* hashTableDeletedValue() { return reinterpret_cast<T*>(-1); } T* m_ptr; }; template <typename T> template <typename U> inline RefPtr<T>::RefPtr(const PassRefPtr<U>& o) : m_ptr(o.releaseRef()) { } template <typename T> inline RefPtr<T>& RefPtr<T>::operator=(const RefPtr<T>& o) { T* optr = o.get(); if (optr) optr->ref(); T* ptr = m_ptr; m_ptr = optr; if (ptr) ptr->deref(); return *this; } template <typename T> template <typename U> inline RefPtr<T>& RefPtr<T>::operator=(const RefPtr<U>& o) { T* optr = o.get(); if (optr) optr->ref(); T* ptr = m_ptr; m_ptr = optr; if (ptr) ptr->deref(); return *this; } template <typename T> inline RefPtr<T>& RefPtr<T>::operator=(T* optr) { if (optr) optr->ref(); T* ptr = m_ptr; m_ptr = optr; if (ptr) ptr->deref(); return *this; } template <typename T> inline RefPtr<T>& RefPtr<T>::operator=(const PassRefPtr<T>& o) { T* ptr = m_ptr; m_ptr = o.releaseRef(); if (ptr) ptr->deref(); return *this; } template <typename T> template <typename U> inline RefPtr<T>& RefPtr<T>::operator=(const PassRefPtr<U>& o) { T* ptr = m_ptr; m_ptr = o.releaseRef(); if (ptr) ptr->deref(); return *this; } template <class T> inline void RefPtr<T>::swap(RefPtr<T>& o) { std::swap(m_ptr, o.m_ptr); } template <class T> inline void swap(RefPtr<T>& a, RefPtr<T>& b) { a.swap(b); } template <typename T, typename U> inline bool operator==(const RefPtr<T>& a, const RefPtr<U>& b) { return a.get() == b.get(); } template <typename T, typename U> inline bool operator==(const RefPtr<T>& a, U* b) { return a.get() == b; } template <typename T, typename U> inline bool operator==(T* a, const RefPtr<U>& b) { return a == b.get(); } template <typename T, typename U> inline bool operator!=(const RefPtr<T>& a, const RefPtr<U>& b) { return a.get() != b.get(); } template <typename T, typename U> inline bool operator!=(const RefPtr<T>& a, U* b) { return a.get() != b; } template <typename T, typename U> inline bool operator!=(T* a, const RefPtr<U>& b) { return a != b.get(); } template <typename T, typename U> inline RefPtr<T> static_pointer_cast(const RefPtr<U>& p) { return RefPtr<T>(static_cast<T*>(p.get())); } template <typename T, typename U> inline RefPtr<T> const_pointer_cast(const RefPtr<U>& p) { return RefPtr<T>(const_cast<T*>(p.get())); } template <typename T> inline T* getPtr(const RefPtr<T>& p) { return p.get(); } } // namespace WTF using WTF::RefPtr; using WTF::static_pointer_cast; using WTF::const_pointer_cast; #endif // WTF_RefPtr_h
[ "achellies@hotmail.com" ]
achellies@hotmail.com
8609b601696fbc839dcbd1dba9f485016aef7a68
2dfdbc7f2f8695b510c2a5ecc82b4bd82d47ecce
/main.cpp
abc8ea3b1e7214c6042045e093905a95d94d42b7
[]
no_license
bvisness/GraphicsAssignment05
3625a1800e925686aa6e601efe428ff73a65d9da
36ae8d92e167b6b077bc741dd712a883b4d82ba5
refs/heads/master
2021-01-16T21:45:01.321622
2015-11-24T02:29:45
2015-11-24T02:29:45
46,010,573
0
0
null
null
null
null
UTF-8
C++
false
false
5,538
cpp
// // OpenGL 3.2 Template for Mac // Ben Visness // // Suppress GLUT deprecated warnings on Mac #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include "VisnessGL.h" #include "Scene.h" #include "Camera.h" #include "Sphere.h" #include "PLYGameObject.h" #include <math.h> #pragma comment(lib, "glew32.lib") #pragma comment(lib,"ILUT.lib") #pragma comment(lib,"DevIL.lib") #pragma comment(lib,"ILU.lib") #include <stdio.h> //store window width and height int ww = 1000, wh = 700; int mouseX = 0; int mouseY = 0; int mouseXDelta = 0; int mouseYDelta = 0; bool mouseLeftPressed = false; bool mouseRightPressed = false; Scene* scene; Sphere* earth; Sphere* clouds; Texture2D* earthDiffuseTex; Texture2D* earthSpecTex; Texture2D* earthNormalMap; Texture2D* earthCloudsTex; GameObject* cameraAnchor; Camera* mainCam; float cameraAnchorRotVelocity = 0; float cameraAnchorRotFriction = 0.01; void display(void) { /*clear all pixels*/ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GLenum error = glGetError(); if (error != GL_NO_ERROR) { #ifdef __APPLE__ printf("%s\n", gluErrorString(error)); #else // printf("%s\n", glewErrorString(error)); #endif } scene->draw(); glutSwapBuffers(); } void mouseClick(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON) { mouseLeftPressed = (state == GLUT_DOWN); } if (button == GLUT_RIGHT_BUTTON) { mouseRightPressed = (state == GLUT_DOWN); } } void mouseMove(int x, int y) { y = -y; mouseXDelta = x - mouseX; mouseYDelta = y - mouseY; mouseX = x; mouseY = y; if (mouseLeftPressed) { cameraAnchorRotVelocity = -mouseXDelta * 0.25; cameraAnchor->rotation.y += cameraAnchorRotVelocity; } } void keyboard(unsigned char key, int x, int y) { if (key == 27) { exit(0); } if (key == 'd') { if (earth->material.diffuseTexture == nullptr) { earth->material.diffuseTexture = earthDiffuseTex; } else { earth->material.diffuseTexture = nullptr; } } if (key == 's') { if (earth->material.specTexture == nullptr) { earth->material.specTexture = earthSpecTex; } else { earth->material.specTexture = nullptr; } } if (key == 'n') { if (earth->material.normalMap == nullptr) { earth->material.normalMap = earthNormalMap; } else { earth->material.normalMap = nullptr; } } if (key == 'c') { clouds->visible = !clouds->visible; } } void keyboardUp(unsigned char key, int x, int y) { } void special(int key, int x, int y) { } void specialUp(int key, int x, int y) { } void createObjects() { scene = new Scene(); Image* earthDiffuseImage = new Image("images/earth.png"); earthDiffuseTex = new Texture2D(earthDiffuseImage->getInfo()); Image* earthSpecImage = new Image("images/EarthSpec.png"); earthSpecTex = new Texture2D(earthSpecImage->getInfo()); Image* earthNormImage = new Image("images/EarthNormal.png"); earthNormalMap = new Texture2D(earthNormImage->getInfo()); Image* earthCloudsImage = new Image("images/earthcloudmap.png"); earthCloudsTex = new Texture2D(earthCloudsImage->getInfo()); earth = new Sphere(2, 64, Vector4(1, 1, 1, 1)); earth->material.diffuseTexture = earthDiffuseTex; earth->material.specTexture = earthSpecTex; earth->material.normalMap = earthNormalMap; earth->material.specularExponent = 500; scene->addGameObject(earth); clouds = new Sphere(2.01, 64, Vector4(1, 1, 1, 1)); clouds->material.diffuseTexture = earthCloudsTex; scene->addGameObject(clouds); mainCam = new Camera(); mainCam->position.z = 30; mainCam->setFOV(10); mainCam->setTarget(earth); scene->addGameObject(mainCam); cameraAnchor = new GameObject(); cameraAnchor->addChild(mainCam); Light* light = new Light(); light->type = LIGHT_DIRECTIONAL; light->rotation = Vector3(0, 120, 0); light->color = Vector4(1, 1, 0.9, 1); scene->addLight(light); scene->addGameObject(light); scene->ambientLightColor = Vector4(0.05, 0.05, 0.05, 1); scene->setActiveCamera(mainCam); } void init() { glClearColor(0.0, 0.0, 0.0, 0.0); createObjects(); scene->init(); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_MULTISAMPLE); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); } void reshape(int width, int height){ ww= width; wh = height; scene->setAspectRatio((float)width, (float)height); glViewport(0, 0, width, height); } void timer(GLint v) { earth->rotation.y += 0.2; clouds->rotation.y += 0.18; if (!mouseLeftPressed) { cameraAnchor->rotation.y += cameraAnchorRotVelocity; cameraAnchorRotVelocity *= 0.95; } glutPostRedisplay(); glutTimerFunc(1000 / v, timer, v); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowPosition(0, 0); glutInitWindowSize(ww, wh); #ifdef __APPLE__ glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_3_2_CORE_PROFILE); #else glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE); #endif glutCreateWindow("OpenGL 3.2"); #ifndef __APPLE__ glewExperimental = GL_TRUE; glewInit(); #endif init(); glutDisplayFunc(display); glutMouseFunc(mouseClick); glutMotionFunc(mouseMove); glutPassiveMotionFunc(mouseMove); glutKeyboardFunc(keyboard); glutKeyboardUpFunc(keyboardUp); glutSpecialFunc(special); glutSpecialUpFunc(specialUp); glutReshapeFunc(reshape); glutTimerFunc(0, timer, 60); glutMainLoop(); return 0; }
[ "bvisness@gmail.com" ]
bvisness@gmail.com
79f5d47089a1b609e68e0da96a961ef440ac2de5
f5f94d670be5169e86b116288fab28d9540e570a
/processing/colloid/functions/DOSlog.cpp
bff28bbfd0140d0ea42bb4f0c150d3f6715b48dc
[]
no_license
Bradleydi/processing
af6df07c130e97940d4fded1ec0af88860bb92fc
e4d874e6f0a46bb5784ef9e78906b331fd1fc3ad
refs/heads/master
2020-07-10T19:49:22.459601
2016-08-28T07:41:04
2016-08-28T07:41:04
66,753,910
0
0
null
null
null
null
UTF-8
C++
false
false
679
cpp
#include "colloid_base.h" #include "normalmode.h" #include <cstdio> #include <cstdlib> using namespace std; void phelp(); int main (int argc, char *argv[]) { if (argc==1) phelp(); if (argc==2) DOS_log(argv[1]); else phelp(); return 0; } void phelp() { printf("Usage:\n"); printf("\tnormal_mode gdf_data_file [a0] [remove_drift]\n"); printf("Parameters:\n"); printf("\tgdf_data_file\n"); printf("\t\ttracked data\n"); printf("\ta0\n"); printf("\t\tpixel per unit length, usually chosen as lattice constant\n"); printf("\t\tobtained by radial distribution function g(r)\n"); printf("\tremove_drift\n"); printf("\t\t-r remove the drift\n"); exit (0); }
[ "zhoudi2014@163.com" ]
zhoudi2014@163.com
cf35aa2f5620cab5c1f482d15d5e520e1b8135a9
07149121ce4292d1bead18e284047227fbe9c573
/Source/Drivers/PS1080/Sensor/XnDataProcessor.cpp
df7b57ca9607d2acf8e3f84647ae02349bddd68e
[ "IJG", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
PersonifyInc/OpenNI2
4f4ff3069fc57aecb28b88506789639cb32286f7
a9fec0e8662dd06b0a379dd0d6d190f8cc4fa639
refs/heads/master
2020-04-05T22:45:24.632490
2020-02-14T09:27:38
2020-02-14T09:27:38
10,258,048
1
1
Apache-2.0
2020-02-14T09:27:40
2013-05-24T02:47:24
C++
UTF-8
C++
false
false
9,485
cpp
/***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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. * * * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include "XnDataProcessor.h" #include <XnProfiling.h> #include "XnSensor.h" //--------------------------------------------------------------------------- // Code //--------------------------------------------------------------------------- XnDataProcessor::XnDataProcessor(XnDevicePrivateData* pDevicePrivateData, const XnChar* csName) : m_pDevicePrivateData(pDevicePrivateData), m_nBytesReceived(0), m_nLastPacketID(0), m_csName(csName), m_bUseHostTimestamps(FALSE) { m_TimeStampData.csStreamName = csName; m_TimeStampData.bFirst = TRUE; m_bUseHostTimestamps = pDevicePrivateData->pSensor->ShouldUseHostTimestamps(); } XnDataProcessor::~XnDataProcessor() {} XnStatus XnDataProcessor::Init() { return (XN_STATUS_OK); } void XnDataProcessor::ProcessData(const XnSensorProtocolResponseHeader* pHeader, const XnUChar* pData, XnUInt32 nDataOffset, XnUInt32 nDataSize) { XN_PROFILING_START_SECTION("XnDataProcessor::ProcessData") // count these bytes m_nBytesReceived += nDataSize; // check if we start a new packet if (nDataOffset == 0) { // make sure no packet was lost if (pHeader->nPacketID != m_nLastPacketID+1 && pHeader->nPacketID != 0) { xnLogWarning(XN_MASK_SENSOR_PROTOCOL, "%s: Expected %x, got %x", m_csName, m_nLastPacketID+1, pHeader->nPacketID); OnPacketLost(); } m_nLastPacketID = pHeader->nPacketID; // log packet arrival XnUInt64 nNow; xnOSGetHighResTimeStamp(&nNow); xnDumpFileWriteString(m_pDevicePrivateData->MiniPacketsDump, "%llu,0x%hx,0x%hx,0x%hx,%u\n", nNow, pHeader->nType, pHeader->nPacketID, pHeader->nBufSize, pHeader->nTimeStamp); } ProcessPacketChunk(pHeader, pData, nDataOffset, nDataSize); XN_PROFILING_END_SECTION } void XnDataProcessor::OnPacketLost() {} XnUInt64 XnDataProcessor::CreateTimestampFromDevice(XnUInt32 nDeviceTimeStamp) { XnUInt64 nNow; xnOSGetHighResTimeStamp(&nNow); // we register the first TS calculated as time-zero. Every stream's TS data will be // synchronized with it if (m_pDevicePrivateData->nGlobalReferenceTS == 0) { xnOSEnterCriticalSection(&m_pDevicePrivateData->hEndPointsCS); if (m_pDevicePrivateData->nGlobalReferenceTS == 0) { m_pDevicePrivateData->nGlobalReferenceTS = nDeviceTimeStamp; m_pDevicePrivateData->nGlobalReferenceOSTime = nNow; } xnOSLeaveCriticalSection(&m_pDevicePrivateData->hEndPointsCS); } const XnUInt64 nWrapPoint = ((XnUInt64)XN_MAX_UINT32) + 1; XnUInt64 nResultInTicks; const XnUInt32 nDumpCommentMaxLength = 200; XnChar csDumpComment[nDumpCommentMaxLength] = ""; XnBool bCheckSanity = TRUE; if (m_TimeStampData.bFirst) { /* This is a bit tricky, as we need to synchronize the first timestamp of different streams. We somehow need to translate 32-bit tick counts to 64-bit timestamps. The device timestamps wrap-around every ~71.5 seconds (for PS1080 @ 60 MHz). Lets assume the first packet of the first stream got timestamp X. Now we get the first packet of another stream with a timestamp Y. We need to figure out what is the relation between X and Y. We do that by analyzing the following scenarios: 1. Y is after X, in the same period (no wraparound yet). 2. Y is after X, in a different period (one or more wraparounds occurred). 3. Y is before X, in the same period (might happen due to race condition). 4. Y is before X, in a different period (this can happen if X is really small, and Y is almost at wraparound). The following code tried to handle all those cases. It uses an OS timer to try and figure out how many wraparounds occurred. */ // estimate the number of wraparound that occurred using OS time XnUInt64 nOSTime = nNow - m_pDevicePrivateData->nGlobalReferenceOSTime; // calculate wraparound length XnDouble fWrapAroundInMicroseconds = nWrapPoint / (XnDouble)m_pDevicePrivateData->fDeviceFrequency; // perform a rough estimation XnInt32 nWraps = (XnInt32)(nOSTime / fWrapAroundInMicroseconds); // now fix the estimation by clipping TS to the correct wraparounds XnInt64 nEstimatedTicks = nWraps * nWrapPoint + // wraps time nDeviceTimeStamp - m_pDevicePrivateData->nGlobalReferenceTS; XnInt64 nEstimatedTime = (XnInt64)(nEstimatedTicks / (XnDouble)m_pDevicePrivateData->fDeviceFrequency); if (nEstimatedTime < nOSTime - 0.5 * fWrapAroundInMicroseconds) nWraps++; else if (nEstimatedTime > nOSTime + 0.5 * fWrapAroundInMicroseconds) nWraps--; // handle the two special cases - 3 & 4 in which we get a timestamp which is // *before* global TS (meaning before time 0) if (nWraps < 0 || // case 4 (nWraps == 0 && nDeviceTimeStamp < m_pDevicePrivateData->nGlobalReferenceTS)) // case 3 { nDeviceTimeStamp = m_pDevicePrivateData->nGlobalReferenceTS; nWraps = 0; } m_TimeStampData.nReferenceTS = m_pDevicePrivateData->nGlobalReferenceTS; m_TimeStampData.nTotalTicksAtReferenceTS = nWrapPoint * nWraps; m_TimeStampData.nLastDeviceTS = 0; m_TimeStampData.bFirst = FALSE; nResultInTicks = 0; bCheckSanity = FALSE; // no need. sprintf(csDumpComment, "Init. Total Ticks in Ref TS: %llu", m_TimeStampData.nTotalTicksAtReferenceTS); } if (nDeviceTimeStamp > m_TimeStampData.nLastDeviceTS) // this is the normal case { nResultInTicks = m_TimeStampData.nTotalTicksAtReferenceTS + nDeviceTimeStamp - m_TimeStampData.nReferenceTS; } else // wrap around occurred { // add the passed time to the reference time m_TimeStampData.nTotalTicksAtReferenceTS += (nWrapPoint + nDeviceTimeStamp - m_TimeStampData.nReferenceTS); // mark reference timestamp m_TimeStampData.nReferenceTS = nDeviceTimeStamp; sprintf(csDumpComment, "Wrap around. Refernce TS: %u / TotalTicksAtReference: %llu", m_TimeStampData.nReferenceTS, m_TimeStampData.nTotalTicksAtReferenceTS); nResultInTicks = m_TimeStampData.nTotalTicksAtReferenceTS; } m_TimeStampData.nLastDeviceTS = nDeviceTimeStamp; // calculate result in microseconds // NOTE: Intel compiler does too much optimization, and we loose up to 5 milliseconds. We perform // the entire calculation in XnDouble as a workaround XnDouble dResultTimeMicroSeconds = (XnDouble)nResultInTicks / (XnDouble)m_pDevicePrivateData->fDeviceFrequency; XnUInt64 nResultTimeMilliSeconds = (XnUInt64)(dResultTimeMicroSeconds / 1000.0); XnBool bIsSane = TRUE; // perform sanity check if (bCheckSanity && (nResultTimeMilliSeconds > (m_TimeStampData.nLastResultTime + XN_SENSOR_TIMESTAMP_SANITY_DIFF*1000))) { bIsSane = FALSE; xnOSStrAppend(csDumpComment, ",Didn't pass sanity. Will try to re-sync.", nDumpCommentMaxLength); } XnUInt64 nResult = (XnUInt64)dResultTimeMicroSeconds; // dump it xnDumpFileWriteString(m_pDevicePrivateData->TimestampsDump, "%llu,%s,%u,%llu,%s\n", nNow, m_TimeStampData.csStreamName, nDeviceTimeStamp, nResult, csDumpComment); if (bIsSane) { m_TimeStampData.nLastResultTime = nResultTimeMilliSeconds; return (nResult); } else { // sanity failed. We lost sync. restart m_TimeStampData.bFirst = TRUE; return CreateTimestampFromDevice(nDeviceTimeStamp); } } XnUInt64 XnDataProcessor::GetHostTimestamp() { XnUInt64 nNow; xnOSGetHighResTimeStamp(&nNow); // we register the first TS calculated as time-zero. Every stream's TS data will be // synchronized with it if (m_pDevicePrivateData->nGlobalReferenceTS == 0) { xnOSEnterCriticalSection(&m_pDevicePrivateData->hEndPointsCS); if (m_pDevicePrivateData->nGlobalReferenceTS == 0) { m_pDevicePrivateData->nGlobalReferenceTS = (XnUInt32)nNow; m_pDevicePrivateData->nGlobalReferenceOSTime = nNow; } xnOSLeaveCriticalSection(&m_pDevicePrivateData->hEndPointsCS); } XnUInt64 nResultTimeMicroseconds = nNow - m_pDevicePrivateData->nGlobalReferenceOSTime; return nResultTimeMicroseconds; }
[ "eddie.cohen@primesense.com" ]
eddie.cohen@primesense.com
78708bc5b8cde0021162a4c8decc56cdfbbcebe2
4abad86fbe6349c8587e14135f73b1f805137f32
/Project 2/Test/D.h
3e85122cdc64107bee69d6499db096496b228c89
[]
no_license
ashx2611/ObjectOrientedDesign
6f3b52a561fc2255f9293e5cb812a0e1eb9287cc
e456237e47fa9af8a8edc0a8f58322fc42be39fd
refs/heads/master
2021-01-23T21:47:50.229161
2017-09-08T21:29:19
2017-09-08T21:29:19
102,905,031
0
0
null
null
null
null
UTF-8
C++
false
false
111
h
#pragma once class D{ public: void displayD(); }; void D::displayD() { std::cout << "\nHi!!I am D!!\n"; }
[ "ashwiniphadke1@gmail.com" ]
ashwiniphadke1@gmail.com
cf108dd4f6ddd3b26b5f39faa4e250536e19d3df
8c1dbeb23cb2bcf0fe44b62f703486dcc99f79a4
/v2/Reader/src/structure/IPLookUpTable.h
482eb97262d8ddf130511c0abf72687efeefe7c8
[]
no_license
JefGrailet/treenet
0e2bf104ea347ec0efd221e3b91f738d69ca90e8
10cfdcd7e94d73ab29c129ccffb07c4ba6dbcadd
refs/heads/master
2020-12-24T06:42:31.569006
2019-10-14T10:06:17
2019-10-14T10:06:17
34,863,160
10
5
null
null
null
null
UTF-8
C++
false
false
2,371
h
/* * IPLookUpTable.h * * Created on: Sep 29, 2015 * Author: grailet * * IPLookUpTable is a particular structure built to quickly look up for an IP address and see * which protocol should be used to probe it (other usages could be added in the future, like * obtaining the distance in TTL). All target IPs at the beginning of the program should be probed * to determine which protocol they should be probed with during the next steps to maximize the * amount of responsive IPs. IPs that are not responsive are not stored within the table for the * sake of simplicity (and memory usage). * * The structure is made of a 8 Mio array of lists which are indexed from 0 to 2^X. An IP is * stored in the structure by adding it to the list at the index which matches its X first bits. * This implies that each list can contain at most 2^(32 - X) items, thanks to which the storage * and look-up can be achieved in O(1) as long as X is great enough. * * The choice of X is free. By default, it is 20, which leads to a 8 Mio array of lists where each * lists can contain up to 4096 elements. X can be adapted to benefit from large memory amounts in * better computers. * * Note (Jan 5, 2016): this class is copy-pasted from TreeNET "full". * Note (Jan 21, 2016): some addition to speed-up parsing of an IP dictionnary (i.e., no check * for collision). */ #ifndef IPLOOKUPTABLE_H_ #define IPLOOKUPTABLE_H_ #include <list> using std::list; #include "IPTableEntry.h" class IPLookUpTable { public: // X = 20 const static unsigned int SIZE_TABLE = 1048576; // Constructor, destructor IPLookUpTable(unsigned short nbIPIDs); ~IPLookUpTable(); // Creation and look-up methods IPTableEntry *create(InetAddress needle); // NULL if already existed IPTableEntry *lookUp(InetAddress needle); // NULL if not found /* * Creation method without check for collision nor sorting, because if we have set(s) with IPs * already in order that does not overlap between each other, there is no need for it. */ IPTableEntry *createAnyway(InetAddress needle); // Output methods void outputDictionnary(string filename); void outputFingerprints(string filename); private: list<IPTableEntry*> *haystack; unsigned short nbIPIDs; }; #endif /* IPLOOKUPTABLE_H_ */
[ "Jean-Francois.Grailet@student.ulg.ac.be" ]
Jean-Francois.Grailet@student.ulg.ac.be
bf62ce00a817596f39af40380f740e24a7285daa
8232bf93f6a3b0375d34003bdad26f5bfa93095c
/PAT/Advanced/1038.cpp
b2959dda2334d48fa4fc6322934f9e4c890f3643
[]
no_license
ZIFANS/Algorithm_Code
e7ee8c6ab5be8047f5ebe98993c4ce317018a63e
c973274ca86ba0c94fc31476559e0f17f91d1b94
refs/heads/master
2021-11-12T23:07:51.943328
2021-11-06T08:21:17
2021-11-06T08:21:17
232,075,346
0
0
null
null
null
null
UTF-8
C++
false
false
481
cpp
#include <iostream> #include <algorithm> using namespace std; bool cmp(string a,string b) { return a+b<b+a; } int main () { int n; scanf("%d",&n); string s[n]; string ans=""; for(int i=0;i<n;++i) { cin>>s[i]; } sort(s,s+n,cmp); for(int i=0;i<n;++i) { ans+=s[i]; } while(ans.size()!=0 &&ans[0]=='0') { ans.erase(ans.begin()); } if(ans.size()==0) cout<<0; cout<<ans; return 0; }
[ "903953451@qq.com" ]
903953451@qq.com
dfa432f15e2f39dc6bc70df27ef8aaa2d111e5e3
e02b707ea716398ffecb2638eb5b8302610a73a0
/soundtouch/src/main/cpp/soundtouch/PeakFinder.h
9fe66adac5f6a95e21d5efef575b13f931b9386e
[ "Apache-2.0" ]
permissive
Hero2000/AudioSDK
88d1a553cf59d5540bb26a64ba8174706ea3d57e
3aed13d196d156d5743c0f66baa75ef1d3966089
refs/heads/main
2022-12-27T23:58:18.369513
2020-10-17T09:25:05
2020-10-17T09:25:05
305,993,755
0
1
Apache-2.0
2020-10-21T10:52:24
2020-10-21T10:52:23
null
UTF-8
C++
false
false
3,986
h
//////////////////////////////////////////////////////////////////////////////// /// /// The routine detects highest value on an array of values and calculates the /// precise peak location as a mass-center of the 'hump' around the peak value. /// /// Author : Copyright (c) Olli Parviainen /// Author e-mail : oparviai 'at' iki.fi /// SoundTouch WWW: http://www.surina.net/soundtouch /// //////////////////////////////////////////////////////////////////////////////// // // License : // // SoundTouch audio processing library // Copyright (c) Olli Parviainen // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////// #ifndef _PeakFinder_H_ #define _PeakFinder_H_ namespace soundtouch { class PeakFinder { protected: /// Min, max allowed peak positions within the data vector int minPos, maxPos; /// Calculates the mass center between given vector items. double calcMassCenter(const float *data, ///< Data vector. int firstPos, ///< Index of first vector item belonging to the peak. int lastPos ///< Index of last vector item belonging to the peak. ) const; /// Finds the data vector index where the monotoniously decreasing signal crosses the /// given level. int findCrossingLevel(const float *data, ///< Data vector. float level, ///< Goal crossing level. int peakpos, ///< Peak position index within the data vector. int direction /// Direction where to proceed from the peak: 1 = right, -1 = left. ) const; // Finds real 'top' of a peak hump from neighnourhood of the given 'peakpos'. int findTop(const float *data, int peakpos) const; /// Finds the 'ground' level, i.e. smallest level between two neighbouring peaks, to right- /// or left-hand side of the given peak position. int findGround(const float *data, /// Data vector. int peakpos, /// Peak position index within the data vector. int direction /// Direction where to proceed from the peak: 1 = right, -1 = left. ) const; /// get exact center of peak near given position by calculating local mass of center double getPeakCenter(const float *data, int peakpos) const; public: /// Constructor. PeakFinder(); /// Detect exact peak position of the data vector by finding the largest peak 'hump' /// and calculating the mass-center location of the peak hump. /// /// \return The location of the largest base harmonic peak hump. double detectPeak(const float *data, /// Data vector to be analyzed. The data vector has /// to be at least 'maxPos' items long. int minPos, ///< Min allowed peak location within the vector data. int maxPos ///< Max allowed peak location within the vector data. ); }; } #endif // _PeakFinder_H_
[ "jeffmony@163.com" ]
jeffmony@163.com
d0d5ebc36250d85d93bb6e29429dc7569459727a
e217eaf05d0dab8dd339032b6c58636841aa8815
/IfcBridge/src/OpenInfraPlatform/IfcBridge/entity/include/IfcReinforcingElement.h
c86122fcb5ad717eddca9a244294ce1d76b4804b
[]
no_license
bigdoods/OpenInfraPlatform
f7785ebe4cb46e24d7f636e1b4110679d78a4303
0266e86a9f25f2ea9ec837d8d340d31a58a83c8e
refs/heads/master
2021-01-21T03:41:20.124443
2016-01-26T23:20:21
2016-01-26T23:20:21
57,377,206
0
1
null
2016-04-29T10:38:19
2016-04-29T10:38:19
null
UTF-8
C++
false
false
4,550
h
/*! \verbatim * \copyright Copyright (c) 2014 Julian Amann. All rights reserved. * \date 2014-02-15 23:00 * \author Julian Amann <julian.amann@tum.de> (https://www.cms.bgu.tum.de/en/team/amann) * \brief This file is part of the BlueFramework. * \endverbatim */ #pragma once #include <vector> #include <map> #include <sstream> #include <string> #include "../../model/shared_ptr.h" #include "../../model/IfcBridgeObject.h" #include "IfcElementComponent.h" namespace OpenInfraPlatform { namespace IfcBridge { class IfcLabel; //ENTITY class IfcReinforcingElement : public IfcElementComponent { public: IfcReinforcingElement(); IfcReinforcingElement( int id ); ~IfcReinforcingElement(); // method setEntity takes over all attributes from another instance of the class virtual void setEntity( shared_ptr<IfcBridgeEntity> other ); virtual void getStepLine( std::stringstream& stream ) const; virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const; virtual void readStepData( std::vector<std::string>& args, const std::map<int,shared_ptr<IfcBridgeEntity> >& map ); virtual void setInverseCounterparts( shared_ptr<IfcBridgeEntity> ptr_self ); virtual void unlinkSelf(); virtual const char* classname() const { return "IfcReinforcingElement"; } // IfcRoot ----------------------------------------------------------- // attributes: // shared_ptr<IfcGloballyUniqueId> m_GlobalId; // shared_ptr<IfcOwnerHistory> m_OwnerHistory; //optional // shared_ptr<IfcLabel> m_Name; //optional // shared_ptr<IfcText> m_Description; //optional // IfcObjectDefinition ----------------------------------------------------------- // inverse attributes: // std::vector<weak_ptr<IfcRelAssigns> > m_HasAssignments_inverse; // std::vector<weak_ptr<IfcRelNests> > m_Nests_inverse; // std::vector<weak_ptr<IfcRelNests> > m_IsNestedBy_inverse; // std::vector<weak_ptr<IfcRelDeclares> > m_HasContext_inverse; // std::vector<weak_ptr<IfcRelAggregates> > m_IsDecomposedBy_inverse; // std::vector<weak_ptr<IfcRelAggregates> > m_Decomposes_inverse; // std::vector<weak_ptr<IfcRelAssociates> > m_HasAssociations_inverse; // IfcObject ----------------------------------------------------------- // attributes: // shared_ptr<IfcLabel> m_ObjectType; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelDefinesByObject> > m_IsDeclaredBy_inverse; // std::vector<weak_ptr<IfcRelDefinesByObject> > m_Declares_inverse; // std::vector<weak_ptr<IfcRelDefinesByType> > m_IsTypedBy_inverse; // std::vector<weak_ptr<IfcRelDefinesByProperties> > m_IsDefinedBy_inverse; // IfcProduct ----------------------------------------------------------- // attributes: // shared_ptr<IfcObjectPlacement> m_ObjectPlacement; //optional // shared_ptr<IfcProductRepresentation> m_Representation; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelAssignsToProduct> > m_ReferencedBy_inverse; // IfcElement ----------------------------------------------------------- // attributes: // shared_ptr<IfcIdentifier> m_Tag; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelFillsElement> > m_FillsVoids_inverse; // std::vector<weak_ptr<IfcRelConnectsElements> > m_ConnectedTo_inverse; // std::vector<weak_ptr<IfcRelInterferesElements> > m_IsInterferedByElements_inverse; // std::vector<weak_ptr<IfcRelInterferesElements> > m_InterferesElements_inverse; // std::vector<weak_ptr<IfcRelProjectsElement> > m_HasProjections_inverse; // std::vector<weak_ptr<IfcRelReferencedInSpatialStructure> > m_ReferencedInStructures_inverse; // std::vector<weak_ptr<IfcRelVoidsElement> > m_HasOpenings_inverse; // std::vector<weak_ptr<IfcRelConnectsWithRealizingElements> > m_IsConnectionRealization_inverse; // std::vector<weak_ptr<IfcRelSpaceBoundary> > m_ProvidesBoundaries_inverse; // std::vector<weak_ptr<IfcRelConnectsElements> > m_ConnectedFrom_inverse; // std::vector<weak_ptr<IfcRelContainedInSpatialStructure> > m_ContainedInStructure_inverse; // IfcElementComponent ----------------------------------------------------------- // IfcReinforcingElement ----------------------------------------------------------- // attributes: shared_ptr<IfcLabel> m_SteelGrade; //optional }; } // end namespace IfcBridge } // end namespace OpenInfraPlatform
[ "planung.cms.bv@tum.de" ]
planung.cms.bv@tum.de
df1ed0fc092773d40e2af2a83e989a33179b3555
a8a5997cfc6f268fca1d682ce6fad90b386640d8
/GRT/PreProcessingModules/DeadZone.cpp
ed4dd4a9bdbf06a9710d3fd9cc167a26c3cbc045
[ "MIT" ]
permissive
damellis/grt
45845e4c53f1367418e7640fe33a79f0d97484ae
e1cd0b57e401f4ec52ead679fb9926225585cf98
refs/heads/master
2021-01-19T07:01:53.234078
2016-08-10T21:35:01
2016-08-10T21:35:01
46,379,605
5
3
null
2015-11-17T22:30:59
2015-11-17T22:30:59
null
UTF-8
C++
false
false
8,689
cpp
/* GRT MIT License Copyright (c) <2012> <Nicholas Gillian, Media Lab, MIT> 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 "DeadZone.h" namespace GRT{ //Register the DeadZone module with the PreProcessing base class RegisterPreProcessingModule< DeadZone > DeadZone::registerModule("DeadZone"); DeadZone::DeadZone(double lowerLimit,double upperLimit,UINT numDimensions){ classType = "DeadZone"; preProcessingType = classType; debugLog.setProceedingText("[DEBUG DeadZone]"); errorLog.setProceedingText("[ERROR DeadZone]"); warningLog.setProceedingText("[WARNING DeadZone]"); init(lowerLimit,upperLimit,numDimensions); } DeadZone::DeadZone(const DeadZone &rhs){ this->lowerLimit = rhs.lowerLimit; this->upperLimit = rhs.upperLimit; classType = "DeadZone"; preProcessingType = classType; debugLog.setProceedingText("[DEBUG DeadZone]"); errorLog.setProceedingText("[ERROR DeadZone]"); warningLog.setProceedingText("[WARNING DeadZone]"); copyBaseVariables( (PreProcessing*)&rhs ); } DeadZone::~DeadZone(){ } DeadZone& DeadZone::operator=(const DeadZone &rhs){ if(this!=&rhs){ this->lowerLimit = rhs.lowerLimit; this->upperLimit = rhs.upperLimit; copyBaseVariables( (PreProcessing*)&rhs ); } return *this; } bool DeadZone::deepCopyFrom(const PreProcessing *preProcessing){ if( preProcessing == NULL ) return false; if( this->getPreProcessingType() == preProcessing->getPreProcessingType() ){ DeadZone *ptr = (DeadZone*)preProcessing; //Clone the DeadZone values this->lowerLimit = ptr->lowerLimit; this->upperLimit = ptr->upperLimit; //Clone the base class variables return copyBaseVariables( preProcessing ); } errorLog << "clone(const PreProcessing *preProcessing) - PreProcessing Types Do Not Match!" << endl; return false; } bool DeadZone::process(const VectorDouble &inputVector){ if( !initialized ){ errorLog << "process(const VectorDouble &inputVector) - Not initialized!" << endl; return false; } if( inputVector.size() != numInputDimensions ){ errorLog << "process(const VectorDouble &inputVector) - The size of the inputVector (" << inputVector.size() << ") does not match that of the filter (" << numInputDimensions << ")!" << endl; return false; } filter( inputVector ); if( processedData.size() == numOutputDimensions ) return true; return false; } bool DeadZone::reset(){ return true; } bool DeadZone::saveModelToFile(string filename) const{ if( !initialized ){ errorLog << "saveModelToFile(string filename) - The DeadZone has not been initialized" << endl; return false; } std::fstream file; file.open(filename.c_str(), std::ios::out); if( !saveModelToFile( file ) ){ file.close(); return false; } file.close(); return true; } bool DeadZone::saveModelToFile(fstream &file) const{ if( !file.is_open() ){ errorLog << "saveModelToFile(fstream &file) - The file is not open!" << endl; return false; } file << "GRT_DEAD_ZONE_FILE_V1.0" << endl; file << "NumInputDimensions: " << numInputDimensions << endl; file << "NumOutputDimensions: " << numOutputDimensions << endl; file << "LowerLimit: " << lowerLimit << endl; file << "UpperLimit: " << upperLimit << endl; return true; } bool DeadZone::loadModelFromFile(string filename){ std::fstream file; file.open(filename.c_str(), std::ios::in); if( !loadModelFromFile( file ) ){ file.close(); initialized = false; return false; } file.close(); return true; } bool DeadZone::loadModelFromFile(fstream &file){ if( !file.is_open() ){ errorLog << "loadModelFromFile(fstream &file) - The file is not open!" << endl; return false; } string word; //Load the header file >> word; if( word != "GRT_DEAD_ZONE_FILE_V1.0" ){ errorLog << "loadModelFromFile(fstream &file) - Invalid file format!" << endl; return false; } //Load the number of input dimensions file >> word; if( word != "NumInputDimensions:" ){ errorLog << "loadModelFromFile(fstream &file) - Failed to read NumInputDimensions header!" << endl; return false; } file >> numInputDimensions; //Load the number of output dimensions file >> word; if( word != "NumOutputDimensions:" ){ errorLog << "loadModelFromFile(fstream &file) - Failed to read NumOutputDimensions header!" << endl; return false; } file >> numOutputDimensions; //Load the lower limit file >> word; if( word != "LowerLimit:" ){ errorLog << "loadModelFromFile(fstream &file) - Failed to read LowerLimit header!" << endl; return false; } file >> lowerLimit; file >> word; if( word != "UpperLimit:" ){ errorLog << "loadModelFromFile(fstream &file) - Failed to read UpperLimit header!" << endl; return false; } file >> upperLimit; //Init the deadzone module to ensure everything is initialized correctly return init(lowerLimit,upperLimit,numInputDimensions); } bool DeadZone::init(double lowerLimit,double upperLimit,UINT numDimensions){ initialized = false; if( numDimensions == 0 ){ errorLog << "init(double lowerLimit,double upperLimit,UINT numDimensions) - NumDimensions must be greater than 0!" << endl; return false; } if( lowerLimit >= upperLimit ){ errorLog << "init(double lowerLimit,double upperLimit,UINT numDimensions) - The lower limit must be less than the upperlimit!" << endl; return false; } this->lowerLimit = lowerLimit; this->upperLimit = upperLimit; this->numInputDimensions = numDimensions; this->numOutputDimensions = numDimensions; processedData.clear(); processedData.resize(numOutputDimensions,0); initialized = true; return true; } double DeadZone::filter(const double x){ VectorDouble y = filter(VectorDouble(1,x)); if( y.size() == 0 ) return 0; return y[0]; } VectorDouble DeadZone::filter(const VectorDouble &x){ if( !initialized ){ errorLog << "filter(const VectorDouble &x) - Not Initialized!" << endl; return VectorDouble(); } if( x.size() != numInputDimensions ){ errorLog << "filter(const VectorDouble &x) - The Number Of Input Dimensions (" << numInputDimensions << ") does not match the size of the input vector (" << x.size() << ")!" << endl; return VectorDouble(); } for(UINT n=0; n<numInputDimensions; n++){ if( x[n] > lowerLimit && x[n] < upperLimit ){ processedData[n] = 0; }else{ if( x[n] >= upperLimit ) processedData[n] = x[n] - upperLimit; else processedData[n] = x[n] - lowerLimit; } } return processedData; } bool DeadZone::setLowerLimit(double lowerLimit){ this->lowerLimit = lowerLimit; return true; } bool DeadZone::setUpperLimit(double upperLimit){ this->upperLimit = upperLimit; return true; } }//End of namespace GRT
[ "nickgillian@googlemail.com" ]
nickgillian@googlemail.com
c886322202b52bf95145ace3c951b6a99fe1768b
5d7c0ce7713e33384d6f9768ee7d70747d1502a7
/Arduino/epd2in13b_V2/epd2in13b_V2.cpp
4ddc256e40159b81bcc182fb9f7db6829543e0a0
[]
no_license
schmiddim/e-Paper
0e9b33bc21913639af9b6ac04cb0f4e831f8ed12
22032b7cc1ed1669a914c6177017c718ce9d1218
refs/heads/master
2022-12-06T17:18:24.289681
2020-08-21T20:33:09
2020-08-21T20:33:09
289,359,248
1
0
null
null
null
null
UTF-8
C++
false
false
5,749
cpp
/** * @filename : epd2in9b.cpp * @brief : Implements for Dual-color e-paper library * @author : Yehui from Waveshare * * Copyright (C) Waveshare August 10 2017 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documnetation 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 * furished 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 OR 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 <stdlib.h> #include "epd2in13b_V2.h" Epd::~Epd() { }; Epd::Epd() { reset_pin = RST_PIN; dc_pin = DC_PIN; cs_pin = CS_PIN; busy_pin = BUSY_PIN; width = EPD_WIDTH; height = EPD_HEIGHT; }; int Epd::Init(void) { /* this calls the peripheral hardware interface, see epdif */ if (IfInit() != 0) { return -1; } /* EPD hardware init start */ Reset(); SendCommand(0x04); WaitUntilIdle();//waiting for the electronic paper IC to release the idle signal SendCommand(0x00);//panel setting SendData(0x0f);//LUT from OTP,128x296 SendData(0x89);//Temperature sensor, boost and other related timing settings SendCommand(0x61);//resolution setting SendData (0x68); SendData (0x00); SendData (0xD4); SendCommand(0X50);//VCOM AND DATA INTERVAL SETTING SendData(0x77);//WBmode:VBDF 17|D7 VBDW 97 VBDB 57 //WBRmode:VBDF F7 VBDW 77 VBDB 37 VBDR B7; return 0; } /** * @brief: basic function for sending commands */ void Epd::SendCommand(unsigned char command) { DigitalWrite(dc_pin, LOW); SpiTransfer(command); } /** * @brief: basic function for sending data */ void Epd::SendData(unsigned char data) { DigitalWrite(dc_pin, HIGH); SpiTransfer(data); } /** * @brief: Wait until the busy_pin goes HIGH */ void Epd::WaitUntilIdle(void) { SendCommand(0x71); while(DigitalRead(busy_pin) == 0) { //0: busy, 1: idle SendCommand(0x71); DelayMs(50); } DelayMs(200); } /** * @brief: module reset. * often used to awaken the module in deep sleep, * see Epd::Sleep(); */ void Epd::Reset(void) { DigitalWrite(reset_pin, HIGH); DelayMs(200); DigitalWrite(reset_pin, LOW); DelayMs(10); DigitalWrite(reset_pin, HIGH); DelayMs(200); this->count = 0; } /** * @brief: refresh and displays the frame */ void Epd::DisplayFrame(const unsigned char* frame_buffer_black, const unsigned char* frame_buffer_red) { if (frame_buffer_black != NULL) { SendCommand(0x10); for (int i = 0; i < this->width * this->height / 8; i++) { SendData(pgm_read_byte(&frame_buffer_black[i])); } DelayMs(2); } if (frame_buffer_red != NULL) { SendCommand(0x13); for (int i = 0; i < this->width * this->height / 8; i++) { SendData(pgm_read_byte(&frame_buffer_red[i])); } } SendCommand(0x12); DelayMs(100); WaitUntilIdle(); this->count = 0; } void Epd::Display(const unsigned char* frame_buffer) { // 1378 if(this->count == 0){ SendCommand(0x10); this->count++; }else if(this->count > 0 && this->count < 4 ){ this->count++; }else if(this->count == 4){ SendCommand(0x13); this->count++; }else if(this->count > 4 && this->count < 8 ){ this->count++; } for(int i = 0; i < this->width * this->height / 8 / 4; i++){ SendData(frame_buffer[i]); } if(this->count == 8){ SendCommand(0x12); DelayMs(100); WaitUntilIdle(); this->count = 0; } } /** * @brief: clear the frame data from the SRAM, this won't refresh the display */ void Epd::ClearFrame(void) { SendCommand(0x10); for(int i = 0; i < width * height / 8; i++) { SendData(0xFF); } DelayMs(2); SendCommand(0x13); for(int i = 0; i < width * height / 8; i++) { SendData(0xFF); } SendCommand(0x12); DelayMs(100); WaitUntilIdle(); this->count = 0; } /** * @brief: This displays the frame data from SRAM */ void Epd::DisplayFrame(void) { this->count = 0; SendCommand(0x12); DelayMs(100); WaitUntilIdle(); } /** * @brief: After this command is transmitted, the chip would enter the deep-sleep mode to save power. * The deep sleep mode would return to standby by hardware reset. The only one parameter is a * check code, the command would be executed if check code = 0xA5. * You can use Epd::Reset() to awaken and use Epd::Init() to initialize. */ void Epd::Sleep() { SendCommand(0X50); SendData(0xf7); SendCommand(0X02);//power off WaitUntilIdle();//waiting for the electronic paper IC to release the idle signal SendCommand(0X07);//deep sleep SendData(0xA5); this->count = 0; } /* END OF FILE */
[ "hnwangkg@qq.com" ]
hnwangkg@qq.com
a910564c682e14e8e68b052ebb390d7d5252ec68
e5b7cd1203d13fa2c1d9c084f255e4c5a6580bd7
/modtronix_im4OLED/mx_gfx.cpp
f91fdf84c9bc1d0b678c6fc46f892544887957e8
[]
no_license
jobitjoseph/devkit_sx1276
6b109a7cb29412fe2018a0b2c5df5c04bad1cc5a
bc54a7660e3aa8287fc531283c05d6623a1d6fdc
refs/heads/master
2022-02-25T00:58:53.929523
2016-09-22T22:57:33
2016-09-22T22:57:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,924
cpp
/*********************************** This is a our graphics core library, for all our displays. We'll be adapting all the existing libaries to use this core to make updating, support and upgrading easier! Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, check license.txt for more information All text above must be included in any redistribution ****************************************/ /* * Modified by Neal Horman 7/14/2012 for use in mbed */ #include "mbed.h" #include "mx_gfx.h" #include "mx_gfx_font.h" #if (GFX_ENABLE_ABSTRACTS==1) // draw a circle outline void MxGfx::drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; drawPixel(x0, y0+r, color); drawPixel(x0, y0-r, color); drawPixel(x0+r, y0, color); drawPixel(x0-r, y0, color); while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; drawPixel(x0 + x, y0 + y, color); drawPixel(x0 - x, y0 + y, color); drawPixel(x0 + x, y0 - y, color); drawPixel(x0 - x, y0 - y, color); drawPixel(x0 + y, y0 + x, color); drawPixel(x0 - y, y0 + x, color); drawPixel(x0 + y, y0 - x, color); drawPixel(x0 - y, y0 - x, color); } } void MxGfx::drawCircleHelper( int16_t x0, int16_t y0, int16_t r, uint8_t cornername, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x4) { drawPixel(x0 + x, y0 + y, color); drawPixel(x0 + y, y0 + x, color); } if (cornername & 0x2) { drawPixel(x0 + x, y0 - y, color); drawPixel(x0 + y, y0 - x, color); } if (cornername & 0x8) { drawPixel(x0 - y, y0 + x, color); drawPixel(x0 - x, y0 + y, color); } if (cornername & 0x1) { drawPixel(x0 - y, y0 - x, color); drawPixel(x0 - x, y0 - y, color); } } } void MxGfx::fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color) { drawFastVLine(x0, y0-r, 2*r+1, color); fillCircleHelper(x0, y0, r, 3, 0, color); } // used to do circles and roundrects! void MxGfx::fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, int16_t delta, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x1) { drawFastVLine(x0+x, y0-y, 2*y+1+delta, color); drawFastVLine(x0+y, y0-x, 2*x+1+delta, color); } if (cornername & 0x2) { drawFastVLine(x0-x, y0-y, 2*y+1+delta, color); drawFastVLine(x0-y, y0-x, 2*x+1+delta, color); } } } #endif #if defined(GFX_ENABLE_ABSTRACTS) || (GFX_SIZEABLE_TEXT==1) // bresenham's algorithm - thx wikpedia void MxGfx::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color) { int16_t steep = abs(y1 - y0) > abs(x1 - x0); if (steep) { swap(x0, y0); swap(x1, y1); } if (x0 > x1) { swap(x0, x1); swap(y0, y1); } int16_t dx, dy; dx = x1 - x0; dy = abs(y1 - y0); int16_t err = dx / 2; int16_t ystep; if (y0 < y1) ystep = 1; else ystep = -1; for (; x0<=x1; x0++) { if (steep) drawPixel(y0, x0, color); else drawPixel(x0, y0, color); err -= dy; if (err < 0) { y0 += ystep; err += dx; } } } void MxGfx::drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { // stupidest version - update in subclasses if desired! drawLine(x, y, x, y+h-1, color); } /** Draw and fill a rectangle. The rectangle starts at given point, and extends DOWN(h) and RIGHTH(w) * @note GFX_ENABLE_ABSTRACTS or GFX_SIZEABLE_TEXT must be defined in im4oled_config.h * * @param x X coordinate, a value from 0 - (width-1) * @param y Y coordinate, a value from 0 - (height-1) * @param w Width from given x,y coordinate. Extends to the Right of given x,y * @param h Height from given x,y coordinate. Extends Down of given x,y * @param color For monochrome display, 0=off, 1=on */ void MxGfx::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { // stupidest version - update in subclasses if desired! for (int16_t i=x; i<x+w; i++) drawFastVLine(i, y, h, color); } #endif #if (GFX_ENABLE_ABSTRACTS==1) // draw a rectangle void MxGfx::drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { drawFastHLine(x, y, w, color); drawFastHLine(x, y+h-1, w, color); drawFastVLine(x, y, h, color); drawFastVLine(x+w-1, y, h, color); } void MxGfx::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { // stupidest version - update in subclasses if desired! drawLine(x, y, x+w-1, y, color); } void MxGfx::fillScreen(uint16_t color) { fillRect(0, 0, _width, _height, color); } // draw a rounded rectangle! void MxGfx::drawRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint16_t color) { // smarter version drawFastHLine(x+r , y , w-2*r, color); // Top drawFastHLine(x+r , y+h-1, w-2*r, color); // Bottom drawFastVLine( x , y+r , h-2*r, color); // Left drawFastVLine( x+w-1, y+r , h-2*r, color); // Right // draw four corners drawCircleHelper(x+r , y+r , r, 1, color); drawCircleHelper(x+w-r-1, y+r , r, 2, color); drawCircleHelper(x+w-r-1, y+h-r-1, r, 4, color); drawCircleHelper(x+r , y+h-r-1, r, 8, color); } // fill a rounded rectangle! void MxGfx::fillRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint16_t color) { // smarter version fillRect(x+r, y, w-2*r, h, color); // draw four corners fillCircleHelper(x+w-r-1, y+r, r, 1, h-2*r-1, color); fillCircleHelper(x+r , y+r, r, 2, h-2*r-1, color); } // draw a triangle! void MxGfx::drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color) { drawLine(x0, y0, x1, y1, color); drawLine(x1, y1, x2, y2, color); drawLine(x2, y2, x0, y0, color); } // fill a triangle! void MxGfx::fillTriangle ( int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color) { int16_t a, b, y, last; // Sort coordinates by Y order (y2 >= y1 >= y0) if (y0 > y1) swap(y0, y1); swap(x0, x1); if (y1 > y2) swap(y2, y1); swap(x2, x1); if (y0 > y1) swap(y0, y1); swap(x0, x1); if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing a = b = x0; if(x1 < a) a = x1; else if(x1 > b) b = x1; if(x2 < a) a = x2; else if(x2 > b) b = x2; drawFastHLine(a, y0, b-a+1, color); return; } int16_t dx01 = x1 - x0, dy01 = y1 - y0, dx02 = x2 - x0, dy02 = y2 - y0, dx12 = x2 - x1, dy12 = y2 - y1, sa = 0, sb = 0; // For upper part of triangle, find scanline crossings for segments // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 // is included here (and second loop will be skipped, avoiding a /0 // error there), otherwise scanline y1 is skipped here and handled // in the second loop...which also avoids a /0 error here if y0=y1 // (flat-topped triangle). if(y1 == y2) last = y1; // Include y1 scanline else last = y1-1; // Skip it for(y=y0; y<=last; y++) { a = x0 + sa / dy01; b = x0 + sb / dy02; sa += dx01; sb += dx02; /* longhand: a = x0 + (x1 - x0) * (y - y0) / (y1 - y0); b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); */ if(a > b) swap(a,b); drawFastHLine(a, y, b-a+1, color); } // For lower part of triangle, find scanline crossings for segments // 0-2 and 1-2. This loop is skipped if y1=y2. sa = dx12 * (y - y1); sb = dx02 * (y - y0); for(; y<=y2; y++) { a = x1 + sa / dy12; b = x0 + sb / dy02; sa += dx12; sb += dx02; /* longhand: a = x1 + (x2 - x1) * (y - y1) / (y2 - y1); b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); */ if(a > b) swap(a,b); drawFastHLine(a, y, b-a+1, color); } } void MxGfx::drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color) { uint8_t mask; for (int16_t j=0; j<h; j++) { for (int16_t i=0; i<w; i++ ) { mask = 0x01 << (j%8); if (bitmap[i + (j/8)*w] & mask) drawPixel(x+i, y+j, color); } } } #endif size_t MxGfx::writeChar(uint8_t c) { if (c == '\n') { cursor_y += textsize*8; cursor_x = 0; } else if (c == '\r') cursor_x = 0; else { drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); cursor_x += textsize*6; if (wrap && (cursor_x > (_width - textsize*6))) { cursor_y += textsize*8; cursor_x = 0; } } return 1; } // draw a character void MxGfx::drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color, uint16_t bg, uint8_t size) { if( (x >= _width) || // Clip right (y >= _height) || // Clip bottom ((x + 5 * size - 1) < 0) || // Clip left ((y + 8 * size - 1) < 0) // Clip top ) return; for (int8_t i=0; i<6; i++ ) { uint8_t line = 0; if (i == 5) line = 0x0; else line = font5x7[(c*5)+i]; for (int8_t j = 0; j<8; j++) { if (line & 0x1) { #if (GFX_ENABLE_ABSTRACTS==1) || (GFX_SIZEABLE_TEXT==1) if (size == 1) // default size drawPixel(x+i, y+j, color); else // big size fillRect(x+(i*size), y+(j*size), size, size, color); #else drawPixel(x+i, y+j, color); #endif } else if (bg != color) { #if (GFX_ENABLE_ABSTRACTS==1) || (GFX_SIZEABLE_TEXT==1) if (size == 1) // default size drawPixel(x+i, y+j, bg); else // big size fillRect(x+i*size, y+j*size, size, size, bg); #else drawPixel(x+i, y+j, bg); #endif } line >>= 1; } } } void MxGfx::setRotation(uint8_t x) { x %= 4; // cant be higher than 3 rotation = x; switch (x) { case 0: case 2: _width = _rawWidth; _height = _rawHeight; break; case 1: case 3: _width = _rawHeight; _height = _rawWidth; break; } }
[ "git1@modtronix.com" ]
git1@modtronix.com
f038fecac5e9b07b0315355c41a77f17d3e8af78
73f88b9d8055c1bc5ed408319ffed9fa72af628b
/include/Pomdog/Graphics/InputClassification.hpp
1ed1154baae1672433195981c1695124ad9992d5
[ "MIT" ]
permissive
Mourtz/pomdog
3841c015012f0bb8f4e45c3524a66ced11abd448
b3f678033b2b41ec5bbf9c5079810b1082aa293d
refs/heads/master
2020-12-25T04:01:47.810430
2015-09-10T11:57:25
2015-09-10T11:57:25
38,495,875
1
0
null
2015-07-07T09:48:00
2015-07-03T14:12:26
C++
UTF-8
C++
false
false
413
hpp
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_INPUTCLASSIFICATION_478EFF1D_HPP #define POMDOG_INPUTCLASSIFICATION_478EFF1D_HPP #include <cstdint> namespace Pomdog { enum class InputClassification : std::uint8_t { InputPerVertex, InputPerInstance, }; } // namespace Pomdog #endif // POMDOG_INPUTCLASSIFICATION_478EFF1D_HPP
[ "mogemimi@enginetrouble.net" ]
mogemimi@enginetrouble.net
c403160200d0bf2be8b9736a1a9a7c70ebfcc688
4367853a6433bcf52bf8501849d444380b3fc3d4
/14730/main.cpp
4b1f1fdbe1f3d70eb926aaf26dac3eedb314c236
[]
no_license
ywh3589/BOJ
df21332f9db6df979d5859ab45973390e763f3e7
3e7cb25857d038b89c3109b6c7cadd1035863c4a
refs/heads/master
2021-05-07T09:04:38.779603
2017-10-20T09:44:26
2017-10-20T09:44:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
193
cpp
#include <cstdio> #include <cstring> using namespace std; int main() { int N, a, b, sum = 0; scanf("%d", &N); while (N--) { scanf("%d %d", &a, &b); sum += a*b; } printf("%d", sum); }
[ "schezwan.daum.net" ]
schezwan.daum.net
857c5f1697e9643635af2148e2ddb34e59d40ee0
ce1c059321e09200ab4f055cbd957e37f08334bf
/c/api/tqapi_ffi_dapi.cpp
a7bf772de1b0352d2c16674292e36983917cdfd6
[]
no_license
xutiezhu/tqapi
3023586e528f532c0b6539f2ed9afdb06b2b6d1e
5c41dbfac3aa4c873819101a196174f95aa1ceb6
refs/heads/master
2022-02-22T04:17:20.380605
2022-02-14T16:19:40
2022-02-14T16:19:40
140,737,151
2
0
null
2018-07-12T16:13:51
2018-07-12T16:13:50
null
UTF-8
C++
false
false
8,538
cpp
#include <iostream> #include "tquant_api.h" #include "tqapi_ffi.h" #include "myutils/stringutils.h" using namespace std; static_assert(sizeof(MarketQuote) == sizeof(tquant::api::RawMarketQuote), "Wrong MarketQuote size"); static_assert(sizeof(Bar) == sizeof(tquant::api::RawBar), "Wrong Bar size"); static_assert(sizeof(DailyBar) == sizeof(tquant::api::RawDailyBar), "Wrong DailyBar size"); struct DataApi : public tquant::api::DataApi_Callback { tquant::api::DataApi* instance; DataApiCallback* cb; bool is_owner; virtual void on_market_quote(shared_ptr<const tquant::api::MarketQuote> quote) override { if (cb) cb->on_quote(cb->obj, (const MarketQuote*)quote.get()); } virtual void on_bar(const string& cycle, shared_ptr<const tquant::api::Bar> bar) override { if (cb) cb->on_bar(cb->obj, cycle.c_str(), (const Bar*)bar.get()); } }; extern "C" { DataApi* tqapi_create_data_api(const char* addr) { auto inst = tquant::api::create_data_api(addr); if (inst == nullptr) { return nullptr; } auto dapi = new DataApi(); dapi->instance = inst; dapi->cb = nullptr; dapi->is_owner = true; inst->set_callback(dapi); return dapi; } void tqapi_free_data_api(DataApi* dapi) { if (dapi && dapi->is_owner) { dapi->instance->set_callback(nullptr); delete dapi->instance; delete dapi; } } DataApi* tqapi_dapi_from(tquant::api::DataApi* inst) { auto dapi = new DataApi(); dapi->instance = inst; dapi->cb = nullptr; dapi->is_owner = true; inst->set_callback(dapi); return dapi; } DataApiCallback* tqapi_dapi_set_callback(DataApi* dapi, DataApiCallback* callback) { auto old = dapi->cb; dapi->cb = callback; return old; } struct GetTickResultData { tquant::api::CallResult<const tquant::api::MarketQuoteArray> result; }; GetTickResult* tqapi_dapi_get_ticks(DataApi* dapi, const char* code, int trade_date, int number) { auto r = dapi->instance->tick(code, trade_date, number); //dapi->cb->on_quote(nullptr, dapi->cb->user_data); // for (int i = 0; i < r.value->size(); i++) { // dapi->cb->on_quote((const MarketQuote*)&r.value->at(i), dapi->cb->user_data); // } auto gtr = new GetTickResult; gtr->data = new GetTickResultData; gtr->data->result = r; if (gtr->data->result.value) { auto& tmp = gtr->data->result.value; gtr->array = (MarketQuote*)tmp->_data; gtr->array_length = tmp->_size; gtr->element_size = tmp->_type_size; gtr->msg = nullptr; } else { gtr->msg = gtr->data->result.msg.c_str(); gtr->array = nullptr; gtr->array_length = 0; gtr->element_size = 0; } return gtr; } void tqapi_dapi_free_get_ticks_result(DataApi* dapi, GetTickResult* result) { if (result) { delete result->data; delete result; } } struct GetBarResultData { tquant::api::CallResult<const tquant::api::BarArray> result; }; GetBarResult* tqapi_dapi_get_bars(DataApi* dapi, const char* code, const char* cycle, int trade_date, int align, int number) { auto r = dapi->instance->bar(code, cycle, trade_date, align, number); auto gbr = new GetBarResult; gbr->data = new GetBarResultData; gbr->data->result = r; if (gbr->data->result.value) { auto& tmp = gbr->data->result.value; gbr->array = (Bar*)tmp->_data; gbr->array_length = tmp->_size; gbr->element_size = tmp->_type_size; gbr->msg = nullptr; } else { gbr->msg = gbr->data->result.msg.c_str(); gbr->array = nullptr; gbr->array_length = 0; gbr->element_size = 0; } return gbr; } void tqapi_dapi_free_get_bars_result(DataApi* dapi, GetBarResult* result) { if (result) { delete result->data; delete result; } } struct GetDailyBarResultData { tquant::api::CallResult<const tquant::api::DailyBarArray> result; }; GetDailyBarResult* tqapi_dapi_get_dailybars(DataApi* dapi, const char* code, const char* price_type, int align, int number) { auto r = dapi->instance->daily_bar(code, price_type, align, number); auto gbr = new GetDailyBarResult; gbr->data = new GetDailyBarResultData; gbr->data->result = r; if (gbr->data->result.value) { auto& tmp = gbr->data->result.value; gbr->array = (DailyBar*)tmp->_data; gbr->array_length = tmp->_size; gbr->element_size = tmp->_type_size; gbr->msg = nullptr; } else { gbr->msg = gbr->data->result.msg.c_str(); gbr->array = nullptr; gbr->array_length = 0; gbr->element_size = 0; } return gbr; } void tqapi_dapi_free_get_dailybars_result(DataApi* dapi, GetDailyBarResult* result) { if (result) { delete result->data; delete result; } } struct GetQuoteResultData { tquant::api::CallResult<const tquant::api::MarketQuote> result; }; GetQuoteResult* tqapi_dapi_get_quote(DataApi* dapi, const char* code) { auto r = dapi->instance->quote(code); auto gbr = new GetQuoteResult; gbr->_data = new GetQuoteResultData; gbr->_data->result = r; if (gbr->_data->result.value) { gbr->quote = (const MarketQuote*)gbr->_data->result.value.get(); gbr->msg = nullptr; } else { gbr->msg = gbr->_data->result.msg.c_str(); gbr->quote = nullptr; } return gbr; } void tqapi_dapi_free_get_quote_result(DataApi* dapi, GetQuoteResult* result) { if (result) { delete result->_data; delete result; } } struct SubscribeResultData { string codes; string msg; }; SubscribeResult* tqapi_dapi_subscribe(DataApi* dapi, const char*codes) { vector<string> ss; split(codes, ",", &ss); // for (auto& s : ss) // std::cout << "sub: " << s << endl; auto r = dapi->instance->subscribe(ss); SubscribeResult* result = new SubscribeResult(); result->_data = new SubscribeResultData(); if (r.value) { stringstream ss; for(auto s : *(r.value)) ss << s << ","; result->_data->codes = ss.str(); result->_data->codes.resize(result->_data->codes.size()-1); result->codes = result->_data->codes.c_str(); result->msg = nullptr; } else { result->_data->msg = r.msg; result->msg = nullptr; result->codes = nullptr; } return result; } void tqapi_dapi_free_subscribe_result(DataApi* dapi, SubscribeResult* result) { if (result) { delete result->_data; delete result; } } struct UnSubscribeResultData { string codes; string msg; }; UnSubscribeResult* tqapi_dapi_unsubscribe(DataApi* dapi, const char*codes) { vector<string> ss; split(codes, ",", &ss); auto r = dapi->instance->subscribe(ss); auto result = new UnSubscribeResult(); result->_data = new UnSubscribeResultData(); if (r.value) { stringstream ss; for(auto s : *(r.value)) ss << s << ","; result->_data->codes = ss.str(); result->_data->codes.resize(result->_data->codes.size()-1); result->codes = result->_data->codes.c_str(); result->msg = nullptr; } else { result->_data->msg = r.msg; result->msg = nullptr; result->codes = nullptr; } return result; } void tqapi_dapi_free_unsubscribe_result(DataApi* dapi, UnSubscribeResult* result) { if (result) { delete result->_data; delete result; } } }
[ "xutiezhu@gmail.com" ]
xutiezhu@gmail.com
d22627030746c476623997766027da0e00af4030
9412b0e50cbb32af1027008fde12c48bb7f79ab3
/version_2_webcam/intensity.cpp
8e1b6a1f55cb3391bf6918418ad20579cb1fc8df
[]
no_license
drbinzhao/OpenCV-Saliency-Stack
588981e1b9e486ada31210ba1150b95356f6ad9d
107e0fdcd092267f2b6537c68fb65fd80f74120c
refs/heads/master
2021-01-15T18:21:43.498371
2015-08-05T15:18:07
2015-08-05T15:18:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
922
cpp
#include "common.hpp" #include "saliency_common.hpp" #include "intensity.hpp" //Generates Intensity Image Mat Get_Intensity_Image(Mat inputImage) { #ifdef GPU_MODE gpu::GpuMat d_src(inputImage); Mat retImage; gpu::GpuMat gputemp; vector<gpu::GpuMat> d_vec; gpu::split(d_src, d_vec); gpu::addWeighted(d_vec[0], 1.0/3, d_vec[1], 1.0/3, 0.0, gputemp, -1); gpu::addWeighted(gputemp, 1, d_vec[2], 1.0/3, 0.0, gputemp, -1); gputemp.download(retImage); asdf #else vector<Mat> rgb; Mat cputemp; Mat retImage; split(inputImage, rgb); addWeighted(rgb[0], 1.0/3, rgb[1], 1.0/3, 0.0, cputemp, -1); addWeighted(cputemp, 1, rgb[2], 1.0/3, 0.0, retImage, -1); #endif return retImage; } //Does gaussian pyramid and center surround for intensity map vector<Mat> Pyr_CenSur(Mat intensityImg) { vector<Mat> IntPyr, retmap; IntPyr = Get_GaussianPyramid(intensityImg); retmap = censur_maps(IntPyr); return retmap; }
[ "sethu002@e.ntu.edu.sg" ]
sethu002@e.ntu.edu.sg
4d926f3675fefdad24854d77ae47f9d60988ace1
0995c448ad10f024371a99c5a5b872919b586a48
/Kattis/batterup.cpp
daff164f984dc483c782356ce4172a86329c13a6
[]
no_license
ChrisMaxheart/Competitive-Programming
fe9ebb079f30f34086ec97efdda2967c5e7c7fe0
2c749a3bc87a494da198f2f81f975034a8296f32
refs/heads/master
2021-06-14T13:48:39.671292
2021-03-27T10:34:46
2021-03-27T10:34:46
179,540,634
2
0
null
null
null
null
UTF-8
C++
false
false
460
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; bool reversecompare(int a, int b) { return a > b; } int main () { ios::sync_with_stdio(false); cin.tie(nullptr); double x; double total; int N, slug; cin >> N; slug = 0; total = 0; while (N--) { cin >> x; if (x >= 0) { slug++; total += x; } } cout << setprecision(15) << total/slug << endl; return 0; }
[ "samuelhenrykurniawan@yahoo.com" ]
samuelhenrykurniawan@yahoo.com
f6a7961b93648c9ee0e76dfa2410f2a3e336dcd3
a9366152822731b506c90aedbb668ef64b9222d7
/ProyectoBD2Qt/ProyectoQt/gui.h
fcf223d87a3a457e6c1a0becd4c83729650603e7
[]
no_license
XChanitoX/Proyecto1_BD2
940f3cc5bf756b8028675e8f69732a3562c9d46e
d858349acec99fd20aa6cf0cd4c93c581bc16cbf
refs/heads/main
2023-08-24T11:28:29.551370
2021-10-20T14:40:31
2021-10-20T14:40:31
416,148,567
0
0
null
null
null
null
UTF-8
C++
false
false
816
h
#ifndef GUI_H #define GUI_H #include <QMainWindow> #include <QStandardItemModel> #include <QWidget> #include <QAbstractTableModel> #include "Librerias.h" #include "Record.h" QT_BEGIN_NAMESPACE namespace Ui { class GUI; } QT_END_NAMESPACE class GUI : public QMainWindow { Q_OBJECT public: GUI(QWidget *parent = nullptr); ~GUI(); private: Ui::GUI *ui; QStandardItemModel *csvModel; string metodo; private slots: void setValueAt(int ix, int jx, const QString &value); void leyendoConsulta(); void Insertar(); void Remove(); void RangeSearch(); void Search(); void llenarTabla(vector<RecordEdu> registros); void Hash(string indicacion, vector<RecordEdu> &registros); void Sequential(string indicacion, vector<RecordEdu> &registros); }; #endif // GUI_H
[ "40049050+XChanitoX@users.noreply.github.com" ]
40049050+XChanitoX@users.noreply.github.com
05b701106fe21673d9a5baba2b3b8c3373343885
7845f47ba91c5ed7c7ded3957acf7e73b86f4a2f
/samp2_3/main.cpp
d6e44b6928e07b7202d1d029fa16b3e83130340c
[]
no_license
SongVei/QtStudy
e31c80194d383b2d61d35e3f167bbb8c751c6e3e
66e13604a787fb4a99ac5248d0bfb1d006ffcf59
refs/heads/master
2022-12-06T05:30:00.777974
2020-09-03T08:55:47
2020-09-03T08:55:47
290,382,306
0
0
null
null
null
null
UTF-8
C++
false
false
173
cpp
#include "qwdlgmanual.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QWDlgManual w; w.show(); return a.exec(); }
[ "1017500323@qq.com" ]
1017500323@qq.com
f17d9d766107335fb01ee53176f42a14393e5ec1
e93f3edda0b4671bee6925afb7efbb80991e3fcc
/LiuRen.h
433708304331f11aad00c68f387ffdfd0ac2b1f2
[]
no_license
JelloHuang/shushulib
ea88a0d7da17a465e76a1e6dfe1452426b8b14ec
e2d9a96f2eaa556a347a1ae913c6e513c46dec5f
refs/heads/master
2020-05-14T14:10:12.178395
2013-02-25T16:02:30
2013-02-25T16:02:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
613
h
#pragma once #include "month.h" #include <boost/shared_ptr.hpp> class LiuRen { public: LiuRen(int month, int time, int riGan, int riZhi); ~LiuRen(); static void formatPan(boost::shared_ptr<DiZhi> pdz); void diPan(); void tianPan(); void siKe(); void sanChuan(); void printSanChuan(bool isGan); void duanKe(); void doAll(); private: int walk(int start,int end); int tianpan[12]; int kelow[4]; int kehigh[4]; int sanchuan[3]; int month; int time; int riGan; int riZhi; boost::shared_ptr<TianGan> pRiGan; boost::shared_ptr<DiZhi> pRiZhi; int ike; int izei; int ike_he; int izei_he; };
[ "lusing@gmail.com" ]
lusing@gmail.com
825ef63a5c7144a3db0c17028352e73fecddbe45
feb8a44472202cd0a75ffc129e83f1728184e714
/src/scheduler.h
ba12a01419fca06904e4af57ebe24fd40899c890
[ "MIT" ]
permissive
bitalley/BitAlley-Core
9ec7fe02a3f5ca9aa31d7b752fce89ec0517ae57
f92f5366988553cba423b6f534206fef41b5b666
refs/heads/master
2020-03-25T08:27:04.591960
2018-12-30T20:04:08
2018-12-30T20:04:08
143,613,026
0
0
null
null
null
null
UTF-8
C++
false
false
2,929
h
// Copyright (c) 2015 The Bitcoin Core developers // Copyright (c) 2017 The PIVX developers // Copyright (c) 2018 The BITALLEY developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_SCHEDULER_H #define BITCOIN_SCHEDULER_H // // NOTE: // boost::thread / boost::function / boost::chrono should be ported to // std::thread / std::function / std::chrono when we support C++11. // #include <boost/function.hpp> #include <boost/chrono/chrono.hpp> #include <boost/thread.hpp> #include <map> // // Simple class for background tasks that should be run // periodically or once "after a while" // // Usage: // // CScheduler* s = new CScheduler(); // s->scheduleFromNow(doSomething, 11); // Assuming a: void doSomething() { } // s->scheduleFromNow(boost::bind(Class::func, this, argument), 3); // boost::thread* t = new boost::thread(boost::bind(CScheduler::serviceQueue, s)); // // ... then at program shutdown, clean up the thread running serviceQueue: // t->interrupt(); // t->join(); // delete t; // delete s; // Must be done after thread is interrupted/joined. // class CScheduler { public: CScheduler(); ~CScheduler(); typedef boost::function<void(void)> Function; // Call func at/after time t void schedule(Function f, boost::chrono::system_clock::time_point t); // Convenience method: call f once deltaSeconds from now void scheduleFromNow(Function f, int64_t deltaSeconds); // Another convenience method: call f approximately // every deltaSeconds forever, starting deltaSeconds from now. // To be more precise: every time f is finished, it // is rescheduled to run deltaSeconds later. If you // need more accurate scheduling, don't use this method. void scheduleEvery(Function f, int64_t deltaSeconds); // To keep things as simple as possible, there is no unschedule. // Services the queue 'forever'. Should be run in a thread, // and interrupted using boost::interrupt_thread void serviceQueue(); // Tell any threads running serviceQueue to stop as soon as they're // done servicing whatever task they're currently servicing (drain=false) // or when there is no work left to be done (drain=true) void stop(bool drain=false); // Returns number of tasks waiting to be serviced, // and first and last task times size_t getQueueInfo(boost::chrono::system_clock::time_point &first, boost::chrono::system_clock::time_point &last) const; private: std::multimap<boost::chrono::system_clock::time_point, Function> taskQueue; boost::condition_variable newTaskScheduled; mutable boost::mutex newTaskMutex; int nThreadsServicingQueue; bool stopRequested; bool stopWhenEmpty; bool shouldStop() { return stopRequested || (stopWhenEmpty && taskQueue.empty()); } }; #endif
[ "alonewolf2ksk@gmail.com" ]
alonewolf2ksk@gmail.com
d7a17e7174989b750f0202b11c69d94463338946
04b1803adb6653ecb7cb827c4f4aa616afacf629
/third_party/blink/renderer/core/editing/state_machines/backspace_state_machine_test.cc
0b724da1dea9445bec467df93ff1efd7edb2f752
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
46,721
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 "third_party/blink/renderer/core/editing/state_machines/backspace_state_machine.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/wtf/text/unicode.h" namespace blink { namespace backspace_state_machine_test { const TextSegmentationMachineState kNeedMoreCodeUnit = TextSegmentationMachineState::kNeedMoreCodeUnit; const TextSegmentationMachineState kFinished = TextSegmentationMachineState::kFinished; TEST(BackspaceStateMachineTest, DoNothingCase) { BackspaceStateMachine machine; EXPECT_EQ(0, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(0, machine.FinalizeAndGetBoundaryOffset()); } TEST(BackspaceStateMachineTest, SingleCharacter) { BackspaceStateMachine machine; EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('a')); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); machine.Reset(); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('-')); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); machine.Reset(); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('\t')); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); machine.Reset(); // U+3042 HIRAGANA LETTER A. EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(0x3042)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); } TEST(BackspaceStateMachineTest, SurrogatePair) { BackspaceStateMachine machine; // U+20BB7 is \uD83D\uDDFA in UTF-16. const UChar kLeadSurrogate = 0xD842; const UChar kTrailSurrogate = 0xDFB7; EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kTrailSurrogate)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kLeadSurrogate)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Edge cases // Unpaired trailing surrogate. Delete only broken trail surrogate. machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kTrailSurrogate)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kTrailSurrogate)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('a')); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kTrailSurrogate)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kTrailSurrogate)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Unpaired leading surrogate. Delete only broken lead surrogate. machine.Reset(); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kLeadSurrogate)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); } TEST(BackspaceStateMachineTest, CRLF) { BackspaceStateMachine machine; EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('\r')); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit('\n')); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit('\n')); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(' ')); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // CR LF should be deleted at the same time. machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit('\n')); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('\r')); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); } TEST(BackspaceStateMachineTest, KeyCap) { BackspaceStateMachine machine; const UChar kKeycap = 0x20E3; const UChar kVs16 = 0xFE0F; const UChar kNotKeycapBaseLead = 0xD83C; const UChar kNotKeycapBaseTrail = 0xDCCF; // keycapBase + keycap machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKeycap)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('0')); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // keycapBase + VS + keycap machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKeycap)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('0')); EXPECT_EQ(-3, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-3, machine.FinalizeAndGetBoundaryOffset()); // Followings are edge cases. Remove only keycap character. // Not keycapBase + keycap machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKeycap)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('a')); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Not keycapBase + VS + keycap machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKeycap)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('a')); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Not keycapBase(surrogate pair) + keycap machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKeycap)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kNotKeycapBaseTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kNotKeycapBaseLead)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Not keycapBase(surrogate pair) + VS + keycap machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKeycap)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kNotKeycapBaseTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kNotKeycapBaseLead)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Sot + keycap machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKeycap)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Sot + VS + keycap machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKeycap)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); } TEST(BackspaceStateMachineTest, EmojiModifier) { BackspaceStateMachine machine; const UChar kEmojiModifierLead = 0xD83C; const UChar kEmojiModifierTrail = 0xDFFB; const UChar kEmojiModifierBase = 0x261D; const UChar kEmojiModifierBaseLead = 0xD83D; const UChar kEmojiModifierBaseTrail = 0xDC66; const UChar kNotEmojiModifierBaseLead = 0xD83C; const UChar kNotEmojiModifierBaseTrail = 0xDCCF; const UChar kVs16 = 0xFE0F; // EMOJI_MODIFIER_BASE + EMOJI_MODIFIER machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kEmojiModifierBase)); EXPECT_EQ(-3, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-3, machine.FinalizeAndGetBoundaryOffset()); // EMOJI_MODIFIER_BASE(surrogate pairs) + EMOJI_MODIFIER machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierBaseTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kEmojiModifierBaseLead)); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); // EMOJI_MODIFIER_BASE + VS + EMOJI_MODIFIER machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kEmojiModifierBase)); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); // EMOJI_MODIFIER_BASE(surrogate pairs) + VS + EMOJI_MODIFIER machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierBaseTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kEmojiModifierBaseLead)); EXPECT_EQ(-5, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-5, machine.FinalizeAndGetBoundaryOffset()); // Followings are edge cases. Remove only emoji modifier. // Not EMOJI_MODIFIER_BASE + EMOJI_MODIFIER machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('a')); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Not EMOJI_MODIFIER_BASE(surrogate pairs) + EMOJI_MODIFIER machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kNotEmojiModifierBaseTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kNotEmojiModifierBaseLead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Not EMOJI_MODIFIER_BASE + VS + EMOJI_MODIFIER machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('a')); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Not EMOJI_MODIFIER_BASE(surrogate pairs) + VS + EMOJI_MODIFIER machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kNotEmojiModifierBaseTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kNotEmojiModifierBaseLead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Sot + EMOJI_MODIFIER machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Sot + VS + EMOJI_MODIFIER machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); } TEST(BackspaceStateMachineTest, RegionalIndicator) { BackspaceStateMachine machine; const UChar kRegionalIndicatorULead = 0xD83C; const UChar kRegionalIndicatorUTrail = 0xDDFA; const UChar kRegionalIndicatorSLead = 0xD83C; const UChar kRegionalIndicatorSTrail = 0xDDF8; const UChar kNotRegionalIndicatorLead = 0xD83C; const UChar kNotRegionalIndicatorTrail = 0xDCCF; // Not RI + RI + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('a')); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); // Not RI(surrogate pairs) + RI + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kNotRegionalIndicatorTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kNotRegionalIndicatorLead)); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); // Sot + RI + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); // Not RI + RI + RI + RI + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('a')); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); // Not RI(surrogate pairs) + RI + RI + RI + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kNotRegionalIndicatorTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kNotRegionalIndicatorLead)); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); // Sot + RI + RI + RI + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); // Followings are edge cases. Delete last regional indicator only. // Not RI + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('a')); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Not RI(surrogate pairs) + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kNotRegionalIndicatorTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kNotRegionalIndicatorLead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Sot + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Not RI + RI + RI + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit('a')); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Not RI(surrogate pairs) + RI + RI + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kNotRegionalIndicatorTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kNotRegionalIndicatorLead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Sot + RI + RI + RI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorSLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorUTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kRegionalIndicatorULead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); } TEST(BackspaceStateMachineTest, VariationSequencec) { BackspaceStateMachine machine; UChar vs01 = 0xFE00; UChar vs01_base = 0xA85E; UChar vs01_base_lead = 0xD802; UChar vs01_base_trail = 0xDEC6; UChar vs17_lead = 0xDB40; UChar vs17_trail = 0xDD00; UChar vs17_base = 0x3402; UChar vs17_base_lead = 0xD841; UChar vs17_base_trail = 0xDC8C; UChar mongolian_vs = 0x180B; UChar mongolian_vs_base = 0x1820; // Variation selectors can't be a base of variation sequence. UChar notvs_base = 0xFE00; UChar notvs_base_lead = 0xDB40; UChar notvs_base_trail = 0xDD01; // VS_BASE + VS machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs01)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(vs01_base)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // VS_BASE + VS(surrogate pairs) machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_trail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_lead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(vs17_base)); EXPECT_EQ(-3, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-3, machine.FinalizeAndGetBoundaryOffset()); // VS_BASE(surrogate pairs) + VS machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs01)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs01_base_trail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(vs01_base_lead)); EXPECT_EQ(-3, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-3, machine.FinalizeAndGetBoundaryOffset()); // VS_BASE(surrogate pairs) + VS(surrogate pairs) machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_trail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_lead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_base_trail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(vs17_base_lead)); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-4, machine.FinalizeAndGetBoundaryOffset()); // mongolianVsBase + mongolianVs machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(mongolian_vs)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(mongolian_vs_base)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Followings are edge case. Delete only variation selector. // Not VS_BASE + VS machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs01)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(notvs_base)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Not VS_BASE + VS(surrogate pairs) machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_trail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_lead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(notvs_base)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Not VS_BASE(surrogate pairs) + VS machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs01)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(notvs_base_trail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(notvs_base_lead)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Not VS_BASE(surrogate pairs) + VS(surrogate pairs) machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_trail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_lead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(notvs_base_trail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(notvs_base_lead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Not VS_BASE + MONGOLIAN_VS machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(mongolian_vs)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(notvs_base)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Not VS_BASE(surrogate pairs) + MONGOLIAN_VS machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(mongolian_vs)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(notvs_base_trail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(notvs_base_lead)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Sot + VS machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs01)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Sot + VS(surrogate pair) machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_trail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(vs17_lead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Sot + MONGOLIAN_VS machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(mongolian_vs)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); } TEST(BackspaceStateMachineTest, ZWJSequence) { BackspaceStateMachine machine; const UChar kZwj = 0x200D; const UChar kEyeLead = 0xD83D; const UChar kEyeTrail = 0xDC41; const UChar kLeftSpeachBubbleLead = 0xD83D; const UChar kLeftSpeachBubbleTrail = 0xDDE8; const UChar kManLead = 0xD83D; const UChar kManTrail = 0xDC68; const UChar kBoyLead = 0xD83D; const UChar kBoyTrail = 0xDC66; const UChar kHeart = 0x2764; const UChar kKissLead = 0xD83D; const UChar kKillTrail = 0xDC8B; const UChar kVs16 = 0xFE0F; const UChar kOther = 'a'; const UChar kOtherLead = 0xD83C; const UChar kOtherTrail = 0xDCCF; // Followings are chosen from valid zwj sequcne. // See http://www.unicode.org/Public/emoji/2.0//emoji-zwj-sequences.txt // others + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI // As an example, use EYE + ZWJ + LEFT_SPEACH_BUBBLE machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kLeftSpeachBubbleTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kLeftSpeachBubbleLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEyeTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEyeLead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOther)); EXPECT_EQ(-5, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-5, machine.FinalizeAndGetBoundaryOffset()); // others(surrogate pairs) + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI // As an example, use EYE + ZWJ + LEFT_SPEACH_BUBBLE machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kLeftSpeachBubbleTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kLeftSpeachBubbleLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEyeTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEyeLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kOtherTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOtherLead)); EXPECT_EQ(-5, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-5, machine.FinalizeAndGetBoundaryOffset()); // Sot + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI // As an example, use EYE + ZWJ + LEFT_SPEACH_BUBBLE machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kLeftSpeachBubbleTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kLeftSpeachBubbleLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEyeTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEyeLead)); EXPECT_EQ(-5, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-5, machine.FinalizeAndGetBoundaryOffset()); // others + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI // As an example, use MAN + ZWJ + heart + ZWJ + MAN machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOther)); EXPECT_EQ(-7, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-7, machine.FinalizeAndGetBoundaryOffset()); // others(surrogate pairs) + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI // As an example, use MAN + ZWJ + heart + ZWJ + MAN machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kOtherTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOtherLead)); EXPECT_EQ(-7, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-7, machine.FinalizeAndGetBoundaryOffset()); // Sot + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI // As an example, use MAN + ZWJ + heart + ZWJ + MAN machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(-7, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-7, machine.FinalizeAndGetBoundaryOffset()); // others + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + VS + ZWJ + ZWJ_EMOJI // As an example, use MAN + ZWJ + heart + vs16 + ZWJ + MAN machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOther)); EXPECT_EQ(-8, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-8, machine.FinalizeAndGetBoundaryOffset()); // others(surrogate pairs) + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + VS + ZWJ + // ZWJ_EMOJI // As an example, use MAN + ZWJ + heart + vs16 + ZWJ + MAN machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kOtherTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOtherLead)); EXPECT_EQ(-8, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-8, machine.FinalizeAndGetBoundaryOffset()); // Sot + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + VS + ZWJ + ZWJ_EMOJI // As an example, use MAN + ZWJ + heart + vs16 + ZWJ + MAN machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(-8, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-8, machine.FinalizeAndGetBoundaryOffset()); // others + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI // As an example, use MAN + ZWJ + MAN + ZWJ + boy + ZWJ + BOY machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOther)); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); // others(surrogate pairs) + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + // ZWJ + ZWJ_EMOJI // As an example, use MAN + ZWJ + MAN + ZWJ + boy + ZWJ + BOY machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kOtherTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOtherLead)); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); // Sot + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI // As an example, use MAN + ZWJ + MAN + ZWJ + boy + ZWJ + BOY machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBoyLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); // others + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + VS + ZWJ + ZWJ_EMOJI + ZWJ + // ZWJ_EMOJI // As an example, use MAN + ZWJ + heart + VS + ZWJ + KISS + ZWJ + MAN machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKillTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKissLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOther)); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); // others(surrogate pairs) + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + VS + ZWJ + // ZWJ_EMOJI + ZWJ + ZWJ_EMOJI // As an example, use MAN + ZWJ + heart + VS + ZWJ + KISS + ZWJ + MAN machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKillTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKissLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kOtherTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOtherLead)); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); // Sot + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI + VS + ZWJ + ZWJ_EMOJI + ZWJ + ZWJ_EMOJI // As an example, use MAN + ZWJ + heart + VS + ZWJ + KISS + ZWJ + MAN machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKillTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kKissLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kVs16)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-11, machine.FinalizeAndGetBoundaryOffset()); // Sot + EMOJI_MODIFIER_BASE + EMOJI_MODIFIER + ZWJ + ZWJ_EMOJI // As an example, use WOMAN + MODIFIER + ZWJ + BRIEFCASE const UChar kWomanLead = 0xD83D; const UChar kWomanTrail = 0xDC69; const UChar kEmojiModifierLead = 0xD83C; const UChar kEmojiModifierTrail = 0xDFFB; const UChar kBriefcaseLead = 0xD83D; const UChar kBriefcaseTrail = 0xDCBC; machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBriefcaseTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kBriefcaseLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kEmojiModifierLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kWomanTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kWomanLead)); EXPECT_EQ(-7, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-7, machine.FinalizeAndGetBoundaryOffset()); // Followings are not edge cases but good to check. // If leading character is not zwj, delete only ZWJ_EMOJI. // other + ZWJ_EMOJI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOther)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // other(surrogate pairs) + ZWJ_EMOJI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kOtherTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOtherLead)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // Sot + ZWJ_EMOJI machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kHeart)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); // other + ZWJ_EMOJI(surrogate pairs) machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOther)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // other(surrogate pairs) + ZWJ_EMOJI(surrogate pairs) machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kOtherTrail)); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kOtherLead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Sot + ZWJ_EMOJI(surrogate pairs) machine.Reset(); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManTrail)); EXPECT_EQ(kNeedMoreCodeUnit, machine.FeedPrecedingCodeUnit(kManLead)); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); EXPECT_EQ(-2, machine.FinalizeAndGetBoundaryOffset()); // Followings are edge case. // It is hard to list all edge case patterns. Check only over deleting by ZWJ. // any + ZWJ: should delete only last ZWJ. machine.Reset(); EXPECT_EQ(kFinished, machine.FeedPrecedingCodeUnit(kZwj)); EXPECT_EQ(-1, machine.FinalizeAndGetBoundaryOffset()); } } // namespace backspace_state_machine_test } // namespace blink
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
b64d8fc65bd43f1cd7fc4eebda64473062532ee8
783f30286a5e485bfc0f594087f34bfd9ea222a8
/workspace/WiFiClient/WiFiClient.ino
50de750455106e0865dac3a4d630915f3d104b29
[]
no_license
lootr5858/Arduino
c8a9db73065005b8f39897ee2c7825dae47320c9
2b62aea4552f58f2ba7a086a22306730db1f6e0b
refs/heads/master
2022-09-07T16:43:05.924800
2020-05-31T11:20:56
2020-05-31T11:20:56
267,212,414
0
0
null
null
null
null
UTF-8
C++
false
false
2,241
ino
/* * This sketch sends data via HTTP GET requests to data.sparkfun.com service. * * You need to get streamId and privateKey at data.sparkfun.com and paste them * below. Or just customize this script to talk to other HTTP servers. * */ #include <WiFi.h> const char* ssid = "SINGTEL-2A1A"; const char* password = "ikeequaiph"; const char* host = "data.sparkfun.com"; const char* streamId = "...................."; const char* privateKey = "...................."; void setup() { Serial.begin(115200); delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } int value = 0; void loop() { delay(5000); ++value; Serial.print("connecting to "); Serial.println(host); // Use WiFiClient class to create TCP connections WiFiClient client; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } // We now create a URI for the request String url = "/input/"; url += streamId; url += "?private_key="; url += privateKey; url += "&value="; url += value; Serial.print("Requesting URL: "); Serial.println(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); unsigned long timeout = millis(); while (client.available() == 0) { if (millis() - timeout > 5000) { Serial.println(">>> Client Timeout !"); client.stop(); return; } } // Read all the lines of the reply from server and print them to Serial while(client.available()) { String line = client.readStringUntil('\r'); Serial.print(line); } Serial.println(); Serial.println("closing connection"); }
[ "lootr5858@gmail.com" ]
lootr5858@gmail.com
de57c7f877ff60cca8b26fb304b408124db561ad
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE191_Integer_Underflow/s01/CWE191_Integer_Underflow__char_min_sub_81_bad.cpp
90fd560fdada62d3499fa57769dba7f657dc102e
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
1,098
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__char_min_sub_81_bad.cpp Label Definition File: CWE191_Integer_Underflow.label.xml Template File: sources-sinks-81_bad.tmpl.cpp */ /* * @description * CWE: 191 Integer Underflow * BadSource: min Set data to the min value for char * GoodSource: Set data to a small, non-zero number (negative two) * Sinks: sub * GoodSink: Ensure there will not be an underflow before subtracting 1 from data * BadSink : Subtract 1 from data, which can cause an Underflow * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE191_Integer_Underflow__char_min_sub_81.h" namespace CWE191_Integer_Underflow__char_min_sub_81 { void CWE191_Integer_Underflow__char_min_sub_81_bad::action(char data) const { { /* POTENTIAL FLAW: Subtracting 1 from data could cause an underflow */ char result = data - 1; printHexCharLine(result); } } } #endif /* OMITBAD */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
917318ad8602b1839fedbec3856a8cdc451c24ec
875c93415211ff5f1fbaa92fffe008cb5856e985
/xi/flow_of_control_assignment/ques-2_ascii.cpp
91baab82f9796cc815e320901f41582e0a8cdd1f
[]
no_license
Uchiha-Senju/practicals
384774c5db544f7b1bcabe7f952eabb4fbed91cd
f18a5d7df14ced5bb93306eda210d3c4c860a211
refs/heads/master
2022-04-05T18:23:02.522784
2020-01-28T15:59:03
2020-01-28T16:01:02
151,337,483
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
/*##################################### ## ## To output an ASCII character given ## the code and vice versa ## ## By Varad Mahashabde ## Copyright 2018 ## #####################################*/ #include <iostream> using namespace std; int main() { int ch; char choice; cout << "Ascii2Num (1) or Num2Ascii(2) ? "; cin >> choice; if (choice == '1') { cout << "Input ASCII character : "; cin >> choice; cout << "The corresponding ASCII code for \'" << choice << "\' is " << int(choice) << endl; } else if (choice == '2') { cout << "Input ASCII code : "; cin >> ch; cout << "The corresponding ASCII character for " << ch << " is \'" << char(ch) << '\'' << endl; } else return 1; while (getchar() != '\n'); getchar(); return 0; }
[ "Uchiha-Senju@users.noreply.github.com" ]
Uchiha-Senju@users.noreply.github.com
74092b2718fac72e2c3dce9dd9b8f6cfbeb5c34c
a2647c9e2f90c11b724b3bdfffac0566b6025add
/planszasamuraj.h
2e7162b7203edbd34e32c8dbb9a5d753c2031cc0
[]
no_license
skworzecrafal/Sudoku
ddef165ae8c0aa0a04f9a6dfd35504fb5a9ab4b1
20c662bd1b79cc0bb09e3f22ab75e75a7335e9fc
refs/heads/master
2016-09-06T11:58:08.168070
2014-02-12T10:46:41
2014-02-12T10:46:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
333
h
#ifndef PLANSZASAMURAJ_H #define PLANSZASAMURAJ_H #include "komorkas.h" #include <QFrame> #include <QWidget> class PlanszaSamuraj:public QWidget { public: PlanszaSamuraj(QWidget *parent=0); ~PlanszaSamuraj(); Komorkas tab[5][9][9]; void zerujPola(); private: QFrame* linie[40]; }; #endif // PLANSZASAMURAJ_H
[ "skworzecrafa@gmail.com" ]
skworzecrafa@gmail.com
f2deaa62761eca263200c8fd9b0e06fc65b0a150
954ceac52dfe831ed7c2b302311a20bb92452727
/include/tvm/relax/attrs/nn.h
694a510706839e4e12f2fc2ec440fa1b80f9ff9e
[ "Apache-2.0", "LLVM-exception", "LicenseRef-scancode-unknown-license-reference", "MIT", "Zlib", "Unlicense", "BSD-3-Clause", "BSD-2-Clause" ]
permissive
tqchen/tvm
a0e4aefe8b8dccbdbe6f760549bed6e9545ad4a1
678d01dd4a4e75ef6186ce356bb1a20e584a7b24
refs/heads/main
2023-08-10T02:21:48.092636
2023-02-25T18:22:10
2023-02-25T18:22:10
100,638,323
23
8
Apache-2.0
2023-02-20T16:28:46
2017-08-17T19:30:37
Python
UTF-8
C++
false
false
7,989
h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file tvm/relax/attrs/nn.h * \brief Attributes for neural network operators. */ #ifndef TVM_RELAX_ATTRS_NN_H_ #define TVM_RELAX_ATTRS_NN_H_ #include <tvm/relax/expr.h> namespace tvm { namespace relax { /*! \brief Attributes used in Conv2d operator */ struct Conv2DAttrs : public tvm::AttrsNode<Conv2DAttrs> { Array<IntImm> strides; Array<IntImm> padding; Array<IntImm> dilation; int groups; String data_layout; String kernel_layout; String out_layout; DataType out_dtype; TVM_DECLARE_ATTRS(Conv2DAttrs, "relax.attrs.Conv2DAttrs") { TVM_ATTR_FIELD(strides).describe("Specifies the strides of the convolution."); TVM_ATTR_FIELD(padding).describe( "If padding is non-zero, then the input is implicitly zero-padded" "Padding support both symmetric and asymmetric as" "one int : same padding used on all sides" "two int : bottom, right will use same padding as top, left" "four int : padding width in the order of (top, left, bottom, right)"); TVM_ATTR_FIELD(dilation).describe( "Specifies the dilation rate to use for dilated convolution."); TVM_ATTR_FIELD(groups).describe( "Number of groups to split the input into for grouped convolution. The number of input and " "output channels should be divisible by the number of groups."); TVM_ATTR_FIELD(data_layout) .describe( "Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc." "'N', 'C', 'H', 'W' stands for batch, channel, height, and width" "dimensions respectively. Convolution is applied on the 'H' and" "'W' dimensions."); TVM_ATTR_FIELD(kernel_layout) .describe( "Dimension ordering of weight. Can be 'OIHW', 'OIHW16o16i', etc." "'O', 'I', 'H', 'W' stands for num_filter, input_channel, height, and width" "dimensions respectively."); TVM_ATTR_FIELD(out_layout) .describe( "Dimension ordering of output. Can be 'NCHW', 'NHWC', etc." "'N', 'C', 'H', 'W' stands for batch, channel, height, and width" "dimensions respectively. Default to be same as input layout."); TVM_ATTR_FIELD(out_dtype).describe( "Output data type, set to explicit type under mixed precision setting"); } }; // struct Conv2dAttrs /*! \brief Attributes used in max_pool2d operator */ struct MaxPool2DAttrs : public tvm::AttrsNode<MaxPool2DAttrs> { Array<IntImm> pool_size; Array<IntImm> strides; Array<IntImm> padding; Array<IntImm> dilation; bool ceil_mode; String layout; String out_layout; TVM_DECLARE_ATTRS(MaxPool2DAttrs, "relax.attrs.MaxPool2DAttrs") { TVM_ATTR_FIELD(pool_size).describe("Size of the pooling windows."); TVM_ATTR_FIELD(strides).describe("Specifies the strides of the convolution."); TVM_ATTR_FIELD(dilation).describe("Specifies the dilation of the convolution."); TVM_ATTR_FIELD(padding).describe( "If padding is non-zero, then the input is implicitly zero-padded" "Padding support both symmetric and asymmetric as" "one int : same padding used on all sides" "two int : bottom, right will use same padding as top, left" "four int : padding width in the order of (top, left, bottom, right)"); TVM_ATTR_FIELD(ceil_mode).describe( "A boolean indicating if use ceil or floor to compute the output shape. By using ceil, " "every element in the input tensor will be covered by a sliding window."); TVM_ATTR_FIELD(layout).describe( "Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc." "'N', 'C', 'H', 'W' stands for batch, channel, height, and width" "dimensions respectively. Pooling is applied on the 'H' and" "'W' dimensions."); TVM_ATTR_FIELD(out_layout) .describe( "Dimension ordering of output data. Can be 'NCHW', 'NHWC', etc." "'N', 'C', 'H', 'W' stands for batch, channel, height, and width" "dimensions respectively. Pooling is applied on the 'H' and" "'W' dimensions."); } }; // struct MaxPool2dAttrs /*! \brief Attributes for 2d adaptive pool operator */ struct AdaptivePool2DAttrs : public tvm::AttrsNode<AdaptivePool2DAttrs> { Optional<Array<IntImm>> output_size; String layout; String out_layout; TVM_DECLARE_ATTRS(AdaptivePool2DAttrs, "relax.attrs.AdaptivePool2DAttrs") { TVM_ATTR_FIELD(output_size).describe("Output height and width."); TVM_ATTR_FIELD(layout).describe( "Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc." "'N', 'C', 'H', 'W' stands for batch, channel, height, and width" "dimensions respectively. Pooling is applied on the 'H' and" "'W' dimensions."); TVM_ATTR_FIELD(out_layout) .describe( "Dimension ordering of output data. Can be 'NCHW', 'NHWC', etc." "'N', 'C', 'H', 'W' stands for batch, channel, height, and width" "dimensions respectively. Pooling is applied on the 'H' and" "'W' dimensions."); } }; // struct AdaptivePool2DAttrs /*! \brief Attributes used in softmax operators */ struct SoftmaxAttrs : public tvm::AttrsNode<SoftmaxAttrs> { int axis; TVM_DECLARE_ATTRS(SoftmaxAttrs, "relax.attrs.SoftmaxAttrs") { TVM_ATTR_FIELD(axis).describe("The axis to sum over when computing softmax."); } }; /*! \brief Attributes used in batch_norm operator */ struct BatchNormAttrs : public tvm::AttrsNode<BatchNormAttrs> { int axis; double epsilon; bool center; bool scale; TVM_DECLARE_ATTRS(BatchNormAttrs, "relax.attrs.BatchNormAttrs") { TVM_ATTR_FIELD(axis).describe("The axis along which the normalization is applied."); TVM_ATTR_FIELD(epsilon).describe("Small float added to variance to avoid dividing by zero"); TVM_ATTR_FIELD(center).describe( "Indicating if the beta offset will be added to the normalized tensor."); TVM_ATTR_FIELD(scale).describe("Indicating if the gamma scale will be multiplied."); } }; // struct BatchNormAttrs /*! \brief Attributes used in layer_norm operator */ struct LayerNormAttrs : public tvm::AttrsNode<LayerNormAttrs> { Array<Integer> axes; double epsilon; bool center; bool scale; TVM_DECLARE_ATTRS(LayerNormAttrs, "relax.attrs.LayerNormAttrs") { TVM_ATTR_FIELD(axes).describe("The axes that along which the normalization is applied."); TVM_ATTR_FIELD(epsilon).describe("Small float added to variance to avoid dividing by zero"); TVM_ATTR_FIELD(center).describe( "Indicating if the beta offset will be added to the normalized tensor."); TVM_ATTR_FIELD(scale).describe("Indicating if the gamma scale will be multiplied."); } }; // struct LayerNormAttrs /*! \brief Attributes used in dropout operator */ struct DropoutAttrs : public tvm::AttrsNode<DropoutAttrs> { double rate; TVM_DECLARE_ATTRS(DropoutAttrs, "relax.attrs.DropoutAttrs") { TVM_ATTR_FIELD(rate).describe( "Fraction of the input that gets dropped out during training time"); } }; // struct DropoutAttrs } // namespace relax } // namespace tvm #endif // TVM_RELAX_ATTRS_NN_H_
[ "tianqi.tchen@gmail.com" ]
tianqi.tchen@gmail.com
793e3e6570dcd4b174e4ccb6b4e4c083134d154c
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_3363.cpp
407fdec268f9a0c49a3ee609f0b1c195c4f9d739
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
181
cpp
{ fprintf ( stderr, "%s: supplied filename is suspiciously (>= %d chars) long. Bye!\n", progName, (int)strlen(argv[1]) ); exit(1); }
[ "993273596@qq.com" ]
993273596@qq.com
f4bad6152752d21906e28b563e041092247b9765
d68882e66da6a5eb61ac1e8745c05eb520ce42d2
/w02_h01_xenoFollowing/src/customCircle.h
8eccaad47315ea0cecc9d6d21de49650112b88e7
[]
no_license
Doreenduo/DuoXu_OFanimation2015
dfa10cc3c3cac585a87876193f64289388dcf5ee
52e4c3ab607bc497884bf059716077c86c22e0ba
refs/heads/master
2016-09-05T11:48:45.021778
2015-05-12T21:59:22
2015-05-12T21:59:22
30,620,473
0
0
null
null
null
null
UTF-8
C++
false
false
459
h
// // customCircle.h // 01_xenoFollowing // // Created by XuDuo on 15/2/10. // // #ifndef ___1_xenoFollowing__customCircle__ #define ___1_xenoFollowing__customCircle__ #include <stdio.h> #endif /* defined(___1_xenoFollowing__customCircle__) */ #include "ofMain.h" class customCircle{ public: void setup(); void update(ofVec2f _dest); void draw(); ofVec2f pos; ofColor circleColor; int i; };
[ "duoxu.interaction@gmail.com" ]
duoxu.interaction@gmail.com
bfcc24ef9577d59d3fc637fbee70ad03a3658700
884c41edb91b958c2250a05f3d03fe38002233c7
/lib/ledger/core/api/Configuration.hpp
047b222081e832194255f54638754acec0e71146
[]
no_license
teams2ua/lib-core-cmd
1639071f90ba567be79be9a14dfbf0060e1d9c5b
8d4274bb44624469bc6cc3c50d3156800bdc08c4
refs/heads/master
2021-07-10T03:27:48.073834
2020-07-15T10:21:01
2020-07-15T10:21:01
171,478,879
1
1
null
null
null
null
UTF-8
C++
false
false
1,923
hpp
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from configuration.djinni #ifndef DJINNI_GENERATED_CONFIGURATION_HPP #define DJINNI_GENERATED_CONFIGURATION_HPP #include <string> #ifndef LIBCORE_EXPORT #if defined(_MSC_VER) #include <libcore_export.h> #else #define LIBCORE_EXPORT #endif #endif namespace ledger { namespace core { namespace api { /** Overall configuration. */ class LIBCORE_EXPORT Configuration { public: virtual ~Configuration() {} /** Selects the keychain engine (P2PKH, P2SH...). */ static std::string const KEYCHAIN_ENGINE; /** Sets the derivation scheme for the KEYCHAIN (defaults 44'/<coin_type>'/<account>'/<node>/<address>). */ static std::string const KEYCHAIN_DERIVATION_SCHEME; /** Sets the observable range for HD keychains (BIP32 based). */ static std::string const KEYCHAIN_OBSERVABLE_RANGE; /** Selects the blockchain explorer engine (Ledger's API, Electrum server, RPC): */ static std::string const BLOCKCHAIN_EXPLORER_ENGINE; /** Sets the API endpoint for API based engine (Ledger's API). */ static std::string const BLOCKCHAIN_EXPLORER_API_ENDPOINT; /** Sets the API version. */ static std::string const BLOCKCHAIN_EXPLORER_VERSION; /** Selects the blockchain observer engine (Ledger's API). */ static std::string const BLOCKCHAIN_OBSERVER_ENGINE; /** Selects the blockchain observer engine (Ledger's API; Websocket version). */ static std::string const BLOCKCHAIN_OBSERVER_WS_ENDPOINT; /** Selects the synchronization engine. */ static std::string const SYNCHRONIZATION_ENGINE; /** Sets the half batch size (default: 20). */ static std::string const SYNCHRONIZATION_HALF_BATCH_SIZE; /** Operation trust. */ static std::string const TRUST_LIMIT; }; } } } // namespace ledger::core::api #endif //DJINNI_GENERATED_CONFIGURATION_HPP
[ "andrii.korol@ledger.fr" ]
andrii.korol@ledger.fr
4a2b7566b05ca9eededf8e929cb31c430dbe96f9
6196eb853e2166bc0789e282113146c658af33e1
/src/core/search/DocRanker.cpp
5e5d36c11121fcc0fd87ae44c2c9ea6231d18c15
[ "MIT" ]
permissive
zxs-learn/Skilo
b6d4e5ef995653653078f8b8d09cefeca344f7dc
adc73692dfa41c11b74ce02bfc657a5692156187
refs/heads/master
2023-04-13T05:45:13.357540
2021-03-10T10:47:17
2021-03-10T10:47:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
688
cpp
#include "DocRanker.h" #include <iostream> namespace Skilo { namespace Search { DocRanker::DocRanker():_scorer_num(0) { } void DocRanker::add_scorer(std::unique_ptr<Scorer> scorer) { if(_scorer_num==MaxRankCriteriaCount){ return; } _scorers[_scorer_num++]=std::move(scorer); } std::vector<number_t> DocRanker::rank(const MatchContext &ctx) const { std::vector<number_t> rank_scores; for(size_t i=0;i<_scorer_num;i++){ number_t score=_scorers[i]->get_score(ctx); rank_scores.push_back(score); } return rank_scores; } size_t DocRanker::rank_criteria_num() const { return _scorer_num; } } //namespace search } //namespace skilo
[ "793626853@qq.com" ]
793626853@qq.com
5c26a5663fb89079b9d220b95e52fa895addc4e8
6d0cdaf53056b6611b0e01ee6397ac79ac8d357a
/Find Bunker/SFML5/StateStack.h
43d22bd8a4efd04ea39223038154a096f2115126
[]
no_license
kko2017/FindBunkerGame
cdb139e43c96466d15714cb2045744529054e06d
18997b995814785446c9b6c057ecad0b74a1f420
refs/heads/master
2023-02-21T21:54:15.072088
2021-01-29T06:15:02
2021-01-29T06:15:02
178,708,541
0
0
null
null
null
null
UTF-8
C++
false
false
4,138
h
/** * @file * StateStack.h * @author * Kwangeun Oh * @version 1.0 * * * @DESCRIPTION * This is the Find Bunker game * * @section LICENSE * * * Copyright 2019 * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * @section Academic Integrity * I certify that this work is solely my own and complies with * NBCC Academic Integrity Policy (policy 1111) */ #pragma once #include "StateIdentifier.h" #include "State.h" #include <functional> #include <cassert> // Turning the active state into a stack means that the current state is not a individual state anymore. // For instance, the pause screen is not only displayed on the screen. // The game screen is still shown in the background without motion, even if the pause screen is activated. // To manage states efficiently and in an easy way, we create StateStack class. namespace sf { class Event; class RenderWindow; } namespace GEX { class StateStack { public: enum class Action { // Action enum class is a scoped enumeration. Push, pop and clear are inside of the scope Push, Pop, Clear }; public: explicit StateStack(State::Context context); // Contstructor has Context as parameter. In order to prevent from implicit conversion and copy initialization // use explicit keyword ~StateStack(); // Default Destructor template <typename T> void registerState(GEX::StateID stateID); // This function registers the derived state class void update(sf::Time dt); // The update function void draw(); // The draw function void handleEvent(const sf::Event& event); // This function handles event void pushState(GEX::StateID stateID); // This function is for adding states void popState(); // This function is for removing states void clearStates(); // This function is for clearing states bool isEmpty() const; // This function checks if the stack is empty private: State::Ptr createState(GEX::StateID stateID); // This method takes an ID of a state, and returns a smart pointer to a newly created object of the corresponding state class void applyPendingChanges(); // This method applys pendingChanges to the stack private: struct PendingChange { // PendingChange struct is made for delayed processing operations done explicit PendingChange(Action action, // Constructor has Action and StateID as a parameter StateID stateID = GEX::StateID::None); // and use keyword explicit for prevention from implicit convention and copy intialization Action action; GEX::StateID stateID; }; private: std::vector<State::Ptr> stack_; std::vector<PendingChange> pendingList_; State::Context context_; std::map < GEX::StateID, std::function<State::Ptr()>> factories_; }; template <typename T> // Template parameter T is the derived class we want to register void StateStack::registerState(GEX::StateID stateID) { // This member function inserts mappings factories_[stateID] = [this]() { // Lamda expression acts like a factory for the state // This lamda is assigned to the corresponding stateID in the map return State::Ptr(new T(*this, context_)); // It creates an object of the derived class T by passing StateStack and Context to its constructor }; // This object is wrapped into a unique pointer and returned as a base class pointer } }
[ "kwangeunoh1@gmail.com" ]
kwangeunoh1@gmail.com
b2a5987460d926a2626c6ef51552aaeb707fa3c2
1caa5e47fab729499276924e8dcc8e42f0f6e6f6
/bwn-modules/console-tests/include/DistormWrapper.h
9b53b5a555d44c29508cb46df4e45260a5233c1b
[]
no_license
luedos/console-tests
5de35fd30bf4ed22d47d004fbe53dc60705758d8
00925587507ce8f684d48d89f9f07f6863d8109e
refs/heads/master
2020-08-10T05:43:38.605935
2019-12-04T13:51:55
2019-12-04T13:51:55
214,272,084
1
0
null
2019-11-26T20:57:29
2019-10-10T19:47:54
C++
UTF-8
C++
false
false
233
h
#pragma once #include <string> #include <vector> #include "distorm.h" std::vector<_DInst> GetInstructions(const std::string& code, const std::vector<unsigned int>& relocs = {}, size_t prologSize = 0, size_t epilogSize = 0);
[ "vlad.ol.berd@gmail.com" ]
vlad.ol.berd@gmail.com
cd2c90ef71183424687ffdd41b4dcc96df470fd7
bf75f9916f2c9645a01bc4a9d38bb471095e669e
/NaturalEngine/Engine/BaseShader.cpp
bcbd8019310962a75b97695a8e3c73ad07024844
[]
no_license
jjzhang166/NaturalEngine
860ea8355b4cec8c1733c4ec2f291a3369b53664
12fb7b5da2df376a666d7a59ed16a537a7626df7
refs/heads/master
2023-04-16T12:41:56.556786
2019-12-26T01:17:13
2019-12-26T01:17:13
null
0
0
null
null
null
null
GB18030
C++
false
false
3,052
cpp
#include "BaseShader.h" #include <iostream> #include <fstream> #include <sstream> BaseShader::BaseShader(const char * shaderPath) { path = std::string(shaderPath); std::string shaderCode = loadShaderFromFile(shaderPath); const char* shaderString = shaderCode.c_str(); shadtype = getShaderType(shaderPath); shad = glCreateShader(shadtype.type); glShaderSource(shad, 1, &shaderString, NULL); glCompileShader(shad); checkCompileErrors(shad, shadtype.name.c_str(), getShaderName(shaderPath)); } BaseShader::~BaseShader() { //glDeleteShader(shad); } bool checkCompileErrors(unsigned int shader, std::string type, std::string shaderName) { int success; char infoLog[1024]; if (type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR: SHADER " << shaderName << " COMPILATION ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetShaderiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR: PROGRAM_LINK_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } return success; } std::string BaseShader::loadShaderFromFile(const char * shaderPath) { std::string shaderCode; std::ifstream shaderFile; //const char * shaderSource = 0; shaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { // 打开文件 shaderFile.open(shaderPath); std::stringstream shaderStream; // 将文件的缓冲区内容读入流 shaderStream << shaderFile.rdbuf(); // 关闭文件 shaderFile.close(); //shaderFile.clear(); // 将流转换为字符串 shaderCode = shaderStream.str(); //shaderSource = shaderCode.c_str(); } catch (std::ifstream::failure e) { std::cout << "ERROR: SHADER " << getShaderName(shaderPath) << " FILE_NOT_SUCCESSFULLY_READ" << std::endl; } return shaderCode; } std::string getShaderName(const char * path) { std::string pathstr = std::string(path); const size_t last_slash_idx = pathstr.find_last_of("/"); if (std::string::npos != last_slash_idx) { pathstr.erase(0, last_slash_idx + 1); } return pathstr; } ShaderType getShaderType(const char * path) { std::string type = getShaderName(path); const size_t last_slash_idx = type.find_last_of("."); if (std::string::npos != last_slash_idx) { type.erase(0, last_slash_idx + 1); } if (type == "vert") return ShaderType(GL_VERTEX_SHADER, "VERTEX"); if (type == "frag") return ShaderType(GL_FRAGMENT_SHADER, "FRAGMENT"); if (type == "tes") return ShaderType(GL_TESS_EVALUATION_SHADER, "TESS_EVALUATION"); if (type == "tcs") return ShaderType(GL_TESS_CONTROL_SHADER, "TESS_CONTROL"); if (type == "geom") return ShaderType(GL_GEOMETRY_SHADER, "GEOMETRY"); if (type == "comp") return ShaderType(GL_COMPUTE_SHADER, "COMPUTE"); }
[ "1335138813@qq.com" ]
1335138813@qq.com
dd62a62d84db85a0c9771c35a4d888defd27cb44
74c4a7b5bbd9271afa830815aee142d4cb61cc8b
/163_sum_of_two_numbers_without_plus_sign.cpp
70006f5615408543bab05680b0589fead79eacb4
[]
no_license
hg3994/code.cpp
62df8365077642ec674163e853141cd3f0e77fb9
c8c4ccb61423178a293bb0d2da8e9cdbfa93a916
refs/heads/master
2021-12-15T16:16:12.541844
2021-12-07T09:48:55
2021-12-07T09:48:55
153,646,964
0
0
null
null
null
null
UTF-8
C++
false
false
4,225
cpp
/* Harshit Gupta | 30th July, 2021 --------------------------------- Problem Statement: Given two integers a and b, return the sum of the two integers without using the operators + and -. Example 1: Input: a = 1, b = 2 Output: 3 Example 2: Input: a = 2, b = 3 Output: 5 ------ Solution: First of all, there are too many use cases here: both aa and bb could be positive or negative, abs(a) could be greater or less than abs(b). In total, that results = 2×2×2=8 use cases. Let's start by reducing the problem down to two simple cases: Sum of two positive integers: x + y, where x > y. Difference of two positive integers: x - y, where x > y. Addition: XOR is a key as well because it's a sum of two integers in the binary form without taking carry into account. In other words, XOR is a sum of bits of x and y where at least one of the bits is not set. The next step is to find the carry. It contains the common set bits of x and y, shifted one bit to the left. i.e. it's logical AND of two input numbers, shifted one bit to the left: carry = (x & y) << 1 Technically, it's the same problem: to sum two numbers, and hence one could solve it in a loop with the condition statement "while carry is not equal to zero". Substraction: XOR is a difference of two integers without taking borrow into account. The next step is to find the borrow. It contains common set bits of y and unset bits of x, i.e. borrow = ((∼x)&y)<<1. The problem is reduced down to the subtraction of the borrow from the answer without borrow. As for the sum, it could be solved recursively or in a loop with the condition statement "while borrow is not equal to zero". TC: O(1) because each integer contains 3232 bits. SC: O(1) --- Solution: We know that log10(10^a) = a log10((10^a)*(10^b)) = a+b This is also right but log is a very expensive operation. Paradigm: Bit Manipulation. --- NOTE: 1. MUST READ FOR BIT MANIPULATION: https://leetcode.com/problems/sum-of-two-integers/discuss/84278/A-summary%3A-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently 2. A few Bi Maipulation Tricks: Set union A | B Set intersection A & B Set subtraction A & ~B Set negation ALL_BITS ^ A or ~A Set bit A |= 1 << bit Clear bit A &= ~(1 << bit) Test bit (A & 1 << bit) != 0 Extract last bit A&-A or A&~(A-1) or x^(x&(x-1)) Remove last bit A&(A-1) Get all 1-bits ~0 Similar Questions: TODO 1. https://leetcode.com/articles/single-number-ii/ 2. https://leetcode.com/articles/single-number-iii/ 3. https://leetcode.com/articles/maximum-xor-of-two-numbers-in-an-array/ 4. https://leetcode.com/articles/repeated-dna-sequences/ 5. https://leetcode.com/articles/maximum-product-of-word-lengths/ */ class Solution { public: int getSum(int a, int b) { int x = abs(a); int y = abs(b); // ensure that abs(a) >= abs(b) if(x<y) return getSum(b, a); // abs(a) >= abs(b) . This means 'a' determines the sign // 1. a > 0 && b > 0 => Both are positive so normal sum = (a+b) // 2. a > 0 && b < 0 => sum = (a-b) [Since a>b, so a determines the sign. This is the reason why we took a below in sign] // 3. a < 0 && b < 0 => Both negative so sum = -(a+b) // 4. a < 0 && b > 0 => Won't happen since a > b int sign = a > 0 ? 1: -1; // Case 1 and 3 if (a*b >= 0){ // sum of two positive integers x + y where x > y while(y != 0) { int answer = x^y; int carry = (x&y) << 1; x = answer; y = carry; } } // Case 2 else { // difference of two positive integers x - y where x > y while(y != 0) { int answer = x^y; int borrow = ((~x)&y) << 1; x = answer; y = borrow; } } return x * sign; } }; // Recursive Implementation: int getSum(int a, int b) { return b==0? a:getSum(a^b, (a&b)<<1); //be careful about the terminating condition; }
[ "hg3994@gmail.com" ]
hg3994@gmail.com
3489cb8a8c24389954e4f955ffb0ba9ebe4236f3
9b0655a98507d706c3f98bc1ccfbaf3218bad3f9
/Lecture9STLandAlgorithms/Algorithm/heap.cpp
d2d4838e27cb1d4650864e4cbb66bd022277ce7e
[]
no_license
NCCA/CFGAA
f408a4e47c9b949ca9a45cbe67a93404e771c83b
964fc5db1f6474a513c7f40220d8f944a532fd0e
refs/heads/master
2023-03-25T23:30:21.806677
2023-03-07T09:44:57
2023-03-07T09:44:57
235,330,178
1
1
null
null
null
null
UTF-8
C++
false
false
648
cpp
#include <iostream> #include <vector> #include <algorithm> void printFunc(int i) { std::cout<<i<<"\n"; } int main() { std::vector <int> data; data.push_back(2); data.push_back(4); data.push_back(5); data.push_back(6); data.push_back(2); std::for_each(data.begin(),data.end(),printFunc); std::make_heap (data.begin(),data.end()); std::cout << "max heap : " << data.front() << std::endl; std::sort_heap (data.begin(),data.end()); std::for_each(data.begin(),data.end(),printFunc); std::cout<<"doing push back\n"; data.push_back(99); std::push_heap (data.begin(),data.end()); std::for_each(data.begin(),data.end(),printFunc); }
[ "jmacey@bournemouth.ac.uk" ]
jmacey@bournemouth.ac.uk
e586c7ac620c8155938b18fa85e0e94c4dcece73
3371510b9bfb3afb15f0e0855cda1ad49eb1dd67
/URI-EN/AD-HOC/1105 - Sub-prime.cpp
49d3559a569da280773dd63b21cdc5e3b9ed131d
[]
no_license
felipesdias/Extractor-URI-Online-Judge
30d031dbf8d55b62a83124e7b20d121ff98fee92
74717bd2e51939e7be67b552802b1a1b9612849e
refs/heads/master
2021-08-17T08:20:54.696524
2017-11-21T00:23:33
2017-11-21T00:23:33
111,474,664
0
0
null
null
null
null
UTF-8
C++
false
false
737
cpp
// Author: Felipe Souza Dias <felipe.s.dias@outlook.com> // Name: Sub-prime // Level: 2 // Category: AD-HOC // URL: https://www.urionlinejudge.com.br/judge/en/problems/view/1105 #include <cstdio> int main() { int b, n, d, c, v, rend[25]; bool possivel; scanf("%d %d", &b, &n); while(b && n) { possivel = true; for(int i=1; i<=b; i++) { scanf("%d", &d); rend[i] = d; } for(int i=0; i<n; i++) { scanf("%d %d %d", &d, &c, &v); rend[d] -= v; rend[c] += v; } for(int i=1; i<=b; i++) { if(rend[i] < 0) { possivel = false; break; } } if(possivel) printf("S\n"); else printf("N\n"); scanf("%d %d", &b, &n); } return 0; }
[ "felipe@dinnisoft.com.br" ]
felipe@dinnisoft.com.br
4ec3e30171a00eb5f5f235a0b04bbacc3b7d3b1e
605f930419e09f883eb2d933f043742f86a4c4be
/Classes/AbstractClasses/CAbstractProtectiveUnit.h
d7c24de6b8337f8a2e7e4e6ff23e2fedb3ca2c2c
[]
no_license
jasesuperhero/TowerDefence
7e781330a1ce93927ef5ab394c2834e9a3399fe5
835cfe81130bc308092b303d33fba24131d63b9d
refs/heads/master
2016-08-04T21:35:03.516797
2013-12-18T20:48:10
2013-12-18T20:48:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,252
h
// // CAbstractProtectiveUnit.h // HelloCpp // // Created by Daniel on 05.11.13. // // #ifndef __HelloCpp__CAbstractProtectiveUnit__ #define __HelloCpp__CAbstractProtectiveUnit__ // Кастомные #include "CAbstractUnit.h" class CLandscape; class CAbstractProtectiveUnit : public CAbstractUnit { protected: int _health; int _maxHealth; int _cost; bool _alive; // Графика Animate* _deadAnimation; /** Дополнительные методы */ virtual void killUnit(); public: /** Конструкторы */ CAbstractProtectiveUnit(); /** GET методы */ int getHealth(); int getMaxHealth(); int getCost(); bool getAlive(); Animate* getDeadAnimation(); /** SET методы */ CAbstractProtectiveUnit& setHealth(int new_health); CAbstractProtectiveUnit& setMaxHealth(int new_max_health); CAbstractProtectiveUnit& setCost(int new_cost); CAbstractProtectiveUnit& setAlive(bool new_alive); CAbstractProtectiveUnit& setDeadAnimation(Animate* new_dead_animation); /** Дополнительные методы */ bool getDemaged(int damage); }; #endif /* defined(__HelloCpp__CAbstractProtectiveUnit__) */
[ "jase.siperhero@gmail.com" ]
jase.siperhero@gmail.com
98d07e02fe0b2693980c1b778a36bf7f55196263
8fcc9ed2c42e8f1f7ad61eb790b818381cb8bbef
/StripUtils.cpp
07f29645ce3355f2f2e06535e99cb31fe5635571
[]
no_license
EugeneFeingold/Hat2
02ec8d2753758aee58b6dd7a238a19e6ddb83c3b
f97310a8e463b041e949dc200a9e8d339916d7a5
refs/heads/master
2020-04-06T04:02:26.796760
2012-12-31T00:43:03
2012-12-31T00:43:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,549
cpp
#include "StripUtils.h" uint32_t StripUtils::getColor(byte r, byte g, byte b) { uint32_t c; c = g; c <<= 8; c |= r; c <<= 8; c |= b; return c; }; uint32_t StripUtils::getColor(float brightness, byte r, byte g, byte b) { brightness = min(brightness, 1.0); float fr = brightness * r; float fg = brightness * g; float fb = brightness * b; return getColor ((uint8_t)fr, (uint8_t)fg, (uint8_t)fb); }; uint32_t StripUtils::getWheelColor(float brightness, byte WheelPos) { WheelPos = WheelPos & 0x7F; if (WheelPos < 42) { return getColor(brightness, WheelPos * 3, 127 - WheelPos * 3, 0); } else if (WheelPos < 85) { WheelPos -= 42; return getColor(brightness, 127 - WheelPos * 3, 0, WheelPos * 3); } else { WheelPos -= 85; return getColor(brightness, 0, WheelPos * 3, 127 - WheelPos * 3); } } uint32_t StripUtils::getRandomColor(float brightness) { return getColor(brightness, random(128), random(128), random(128)); } uint32_t StripUtils::getRandomBalancedColor(float brightness) { unsigned int r = random(128); unsigned int g = random(128); return getColor(brightness, r, g, 128-(r + g)/2); } uint32_t StripUtils::getIntermediateColor(uint32_t first, uint32_t second, float frac) { //color order is grb uint8_t r1 = first >> 8; uint8_t g1 = first >> 16; uint8_t b1 = first ; uint8_t r2 = second >> 8; uint8_t g2 = second >> 16; uint8_t b2 = second; return getColor(r1 + (r2 - r1) * frac, g1 + (g2 - g1) * frac, b1 + (b2 - b1) * frac); }
[ "eugene.feingold@gmail.com" ]
eugene.feingold@gmail.com
7bd74428ce35d59ca4cc2370a4fc29408e32d6b0
bc7abdc6168c11eaca6fc1c4dd0e5b69595ad694
/src/reactivision/common/FingerObject.h
6ae755e809492c0ff9def29333058c7ccf8c6230
[]
no_license
internaut/iReacTIVision
d7d608d333e7242ec45a9d19b5c2aaf50ada8710
84712f8bbe0f77246067a3273ca6558a5e82816c
refs/heads/master
2016-09-06T03:33:54.770479
2014-05-12T13:51:52
2014-05-12T13:51:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,321
h
/* reacTIVision fiducial tracking framework FingerObject.h Copyright (C) 2005-2008 Martin Kaltenbrunner <mkalten@iua.upf.edu> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef FINGEROBJECT_H #define FINGEROBJECT_H #ifdef WIN32 #include <windows.h> #else #include <sys/time.h> #endif #include <sstream> #include <string> #include "TuioServer.h" #ifndef DISABLE_MIDISERVER #include "MidiServer.h" #endif #include "PortVideoSDL.h" #include "math.h" #include "stdio.h" #include "stdlib.h" #define DOUBLEPI 6.283185307179586 #define FINGER_CANDIDATE 0 #define FINGER_ALIVE 1 #define FINGER_ADDED 2 #define FINGER_REMOVED 3 #define FINGER_EXPIRED 4 #define FINGER_LOST 0 #define FINGER_FOUND 1 struct cframe { float xpos,ypos; float raw_xpos, raw_ypos; float motion_speed, motion_accel; float motion_speed_x, motion_speed_y; float pressure; long time; }; class FingerObject { public: bool alive; int unsent; int session_id; int state; float smallest_area; private: bool updated; int lost_frames; float width; float height; cframe current, last; long total_frames; void positionFilter(); void computeSpeedAccel(); bool removalFilter(); void saveLastFrame(); long getCurrentTime(); public: FingerObject(int width, int height); ~FingerObject(); void update(float xpos, float ypos, float area); std::string addSetMessage(TuioServer *tserver); void redundantSetMessage(TuioServer *server); std::string getStatistics (); int checkStatus(int s_id); float distance(float x, float y); void reset(); float getX() { return current.xpos; }; float getY() { return current.ypos; }; }; #endif
[ "post@mkonrad.net" ]
post@mkonrad.net
31976c1e16d69a32219226b6407d0c01865d0187
6653d52fa13ade5b240bc65401a97b45e80881ce
/IDE/Contents/Include/PolycodeEditorManager.h
1e99b28da23752f3eefc839cdceff575e4e55e18
[ "MIT" ]
permissive
bope/Polycode
1c0d5619bf9e68af39c887ce437e07ca7dde313f
03aafbc12b8ddc03226e0945c167827a3de5c373
refs/heads/master
2021-01-16T00:46:39.623509
2013-03-17T18:14:31
2013-03-17T18:14:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,761
h
/* Copyright (C) 2012 by Ivan Safrin 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. */ #pragma once #include "Polycode.h" #include "PolycodeEditor.h" using namespace Polycode; class PolycodeEditorManager { public: PolycodeEditorManager(); ~PolycodeEditorManager(); PolycodeEditor *getEditorForPath(String path); PolycodeEditor *createEditorForExtension(String extension); void registerEditorFactory(PolycodeEditorFactory *editorFactory); void setCurrentEditor(PolycodeEditor *editor) { currentEditor = editor; } PolycodeEditor *getCurrentEditor() { return currentEditor; } // int close protected: PolycodeEditor *currentEditor; std::vector<PolycodeEditor*> openEditors; std::vector<PolycodeEditorFactory*> editorFactories; };
[ "ivansafrin@gmail.com" ]
ivansafrin@gmail.com
71b43ca2894117aad7635771eff7e7ed64185f98
5a3ff25304ee2fd2d5fee54a07ce0c5bc1ea37de
/BattlecodeBots/JoshBot/Structure.cpp
942efe535c28c2052ffb81cef4b2565130821305
[]
no_license
Wesxdz/battlecode-2018
29b105af484cf46523a4eb021c2af8e043893a1e
87ecf0aa7e52124303be08aaac7a35ff49eaf215
refs/heads/master
2021-03-16T08:41:36.825260
2018-01-28T19:43:35
2018-01-28T19:43:35
116,757,703
0
0
null
null
null
null
UTF-8
C++
false
false
1,409
cpp
#include "Structure.h" #include "Robot.h" #include "GameController.h" namespace units { Structure::Structure() { } Structure::~Structure() { } uint32_t Structure::Cost() { return bc_UnitType_blueprint_cost(type); } uint8_t Structure::IsBuilt() { return bc_Unit_structure_is_built(self); } uintptr_t Structure::MaxCapacity() { return bc_Unit_structure_max_capacity(self); } std::vector<std::shared_ptr<Robot>> Structure::Garrison() { auto garrison = std::vector<std::shared_ptr<units::Robot>>(); bc_VecUnitID* inside = bc_Unit_structure_garrison(self); for (int i = 0; i < bc_VecUnitID_len(inside); i++) { // Use static_pointer_cast to make types more specific garrison.push_back(std::static_pointer_cast<units::Robot>(GameController::Unit((GameController::gc, bc_VecUnitID_index(inside, i))))); } delete_bc_VecUnitID(inside); return garrison; } uint8_t Structure::CanLoad(std::shared_ptr<Robot> robot) { return bc_GameController_can_load(GameController::gc, id, robot->id); } void Structure::Load(std::shared_ptr<Robot> robot) { bc_GameController_load(GameController::gc, id, robot->id); } uint8_t Structure::CanUnload(bc_Direction direction) { return bc_GameController_can_unload(GameController::gc, id, direction); } void Structure::Unload(bc_Direction direction) { bc_GameController_unload(GameController::gc, id, direction); } }
[ "cyberbrat326@yahoo.com" ]
cyberbrat326@yahoo.com
a6e6317bb126b4468fb5d59f4a7f6b1062628ce8
8e0d0720aba78d84367f70377c2924e648831413
/UE3SDKGen/SingleItemWriter.h
95110038482149b8f5df6ed02e69ba072cbc177e
[]
no_license
webdes27/UE3SDKGen
c1443dd46e00d8ffa0c12b862ec05d82559eb46d
6784140ff91e4bd43637eb6612a5b9e91045f0fa
refs/heads/master
2021-06-10T13:17:39.831532
2017-01-27T16:55:15
2017-01-27T16:55:15
264,675,318
0
1
null
2020-05-17T13:39:36
2020-05-17T13:39:36
null
UTF-8
C++
false
false
148
h
#pragma once #include "IndentationWriter.h" template<typename T> class SingleItemWriter { public: void WriteCode(IndentationWriter &iw, T t); };
[ "chris.m@live.nl" ]
chris.m@live.nl
8b4a7fb19ad23ce406b1e1bca0039e6a2c0a9297
d5400d1bfeb469b38cbec7ae1f71bfe412715c8d
/SList.cpp
e499be644a6af8168386c9a4eeb34e0bfbc763c1
[]
no_license
130000002947823457136193789891/SList
f860e6882a871461fb2ed7b307cfcec955eb1ee9
82b206adc9acb035f6ac25a3e0c5fe435a797fa6
refs/heads/master
2020-03-30T06:24:07.657828
2018-09-29T11:33:44
2018-09-29T11:33:44
150,855,034
0
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
#include<iostream> #define MAXSIZE 100 typedef int DataType; using namespace std; class SequenList { public: friend void Part(SequenList &L); private: DataType data[MAXSIZE]; int len; }; void Part(SequenList &L) { int i,j; DataType a; a=L.data [0]; i=0; j=L.len-1; while(i<j) { while((i<j)&&(L.data[j]>=a))j--; L.data [i]=L.data [j]; while ((i<j)&&(L.data [i]<=a))i++; L.data [j]=L.data [i]; } L.data [i]=a; } int main () { return 0; }
[ "1677080339@qq.com" ]
1677080339@qq.com
e241d4cef35bf5e1e8b3436d645a7e120234ef86
00aff7b9bbb5903d368fa524c0562c3b8046edb2
/9/9_3.cpp
e3be99053db4f4f310e2b255c3c784bf30a626e6
[]
no_license
ImaGe0401/AOJ
20c3c90f404313b80adfd478cf071c5d29b3afef
53dac0182237fc192a0e1ba04c1368a091796dff
refs/heads/main
2023-08-06T00:20:56.815740
2021-10-01T14:42:46
2021-10-01T14:42:46
409,249,763
0
0
null
null
null
null
UTF-8
C++
false
false
2,674
cpp
//include //------------------------------------------ #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <ctime> #include <bits/stdc++.h> #include<queue> #include <numeric> using namespace std; //conversion //------------------------------------------ inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;} template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();} //math //------------------------------------------- template<class T> inline T sqr(T x) {return x*x;} template<class T>bool chmin(T &a, const T &b) { if (b<a) { a = b; return 1; } return 0; } //typedef //------------------------------------------ typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; typedef pair<int, int> PII; typedef long long LL; //container util //------------------------------------------ #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(), (a).rend() #define PB push_back #define MP make_pair #define SZ(a) int((a).size()) #define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i) #define EXIST(s,e) ((s).find(e)!=(s).end()) #define SORT(c) sort((c).begin(),(c).end()) //repetition //------------------------------------------ #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define fore(i,a) for(auto &i:a) //constant //-------------------------------------------- const double EPS = 1e-10; const double PI = acos(-1.0); //clear memory #define CLR(a) memset((a), 0 ,sizeof(a)) //debug #define dump(x) cerr << #x << " = " << (x) << endl; #define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl; //https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_9_B #define MAX 20000000 int H, A[MAX + 1]; void maxHeapify(int i){ int l, r, largest; l = 2 * i; r = 2 * i + 1; if (l <= H && A[l] > A[i]) largest = l; else largest = i; if(r <= H && A[r] > A[largest]) largest = r; if(largest != i){ swap(A[i], A[largest]); maxHeapify(largest); } } int main(){ cin >> H; for (int i = 1; i <= H; ++i) cin >> A[i]; for (int i = H / 2; i >= 1; --i) maxHeapify(i); for (int i = 1; i <= H; ++i){ cout << " " << A[i]; } cout << endl; return 0; }
[ "fesespecialist@gmail.com" ]
fesespecialist@gmail.com
9545bc88b5bf4c86412bca2ed384d311a7dfe98d
e4292ab5dfb57c4d50cc514c369456b7d6715af4
/cpp/NumberRanges/tests/test_MultiRange.h
000e46a91fbbe2f693c49f89dabef913ebb70513
[ "MIT" ]
permissive
tsmanner/sandbox
e80d4f9213b436b2b0a7da12bc29fdc50e5fec6b
53b07c49b8cb5d2fb86cec5c1464a02fd1f4c673
refs/heads/master
2021-07-25T05:23:53.944411
2020-08-05T18:44:27
2020-08-05T18:44:27
205,987,288
0
0
null
null
null
null
UTF-8
C++
false
false
4,268
h
#include "MultiRange.h" TEST_CASE("MultiRange Constructor", "[MultiRange]") { auto mr = MultiRange(); CHECK(mr.getRanges().size() == 0); } TEST_CASE("MultiRange addRange", "[MultiRange][addRange]") { auto mr = MultiRange(); auto originalRange = Range(-1, 1); mr.addRange(originalRange); // Make sure there's only 1 thing in there CHECK(mr.getRanges().size() == 1); // Make sure that 1 thing is the RIGHT thing auto beginRange = *mr.getRanges().begin(); CHECK(originalRange.getLowerBound() == beginRange.getLowerBound()); CHECK(originalRange.getUpperBound() == beginRange.getUpperBound()); } TEST_CASE("MultiRange covers", "[MultiRange][covers]") { auto mr = MultiRange(); CHECK(!mr.covers(0)); mr.addRange(Range(-1, 1)); CHECK(mr.covers(0)); mr.addRange(Range(3, 5)); CHECK(!mr.covers(2)); mr.addRange(Range(LowerBound(), -5)); CHECK(mr.covers(-20)); CHECK(mr.covers(LowerBound())); mr.addRange(Range(10, UpperBound())); CHECK(mr.covers(20)); CHECK(mr.covers(UpperBound())); } TEST_CASE("MultiRange optimize", "[MultiRange][optimize]") { auto mr = MultiRange(); mr.addRange(Range(-1, 1)); mr.addRange(Range(3, 5)); CHECK(mr.getRanges().size() == 2); CHECK(!mr.covers(2)); mr.addRange(Range(2, 2)); CHECK(mr.getRanges().size() == 1); CHECK(mr.covers(-1)); CHECK(mr.covers(5)); mr.addRange(Range(7, 10)); CHECK(mr.getRanges().size() == 2); mr.addRange(Range(12, 15)); CHECK(mr.getRanges().size() == 3); mr.addRange(Range(14, 20)); CHECK(mr.getRanges().size() == 3); } TEST_CASE("Disjunction of one RangeSet", "[MultiRange][RangeSet][disjunction]") { auto rs = MultiRange::RangeSet(); rs.insert(Range(-1, 1)); rs.insert(Range(3, 5)); rs = MultiRange::disjunction(rs); CHECK(rs.size() == 2); rs.insert(Range(2, 2)); rs = MultiRange::disjunction(rs); CHECK(rs.size() == 1); CHECK(rs.begin()->getLowerBound() == -1); CHECK(rs.begin()->getUpperBound() == 5); } TEST_CASE("Conjunction of one RangeSet", "[MultiRange][RangeSet][conjunction]") { auto rs = MultiRange::RangeSet(); rs.insert(Range(-1, 1)); rs.insert(Range(3, 5)); rs = MultiRange::conjunction(rs); CHECK(rs.size() == 0); rs.insert(Range(-1, 1)); rs.insert(Range(1, 3)); rs = MultiRange::conjunction(rs); CHECK(rs.size() == 1); CHECK(rs.begin()->getLowerBound() == 1); CHECK(rs.begin()->getUpperBound() == 1); } TEST_CASE("Disjunction of two MultiRanges", "[MultiRange][disjunction]") { auto lhs = MultiRange(); lhs.addRange(Range(-1, 1)); lhs.addRange(Range(3, 5)); auto rhs = MultiRange(); rhs.addRange(Range(-1, -1)); rhs.addRange(Range(1, 1)); rhs.addRange(Range(4, 4)); rhs.addRange(Range(7, 8)); auto disjunction = MultiRange::disjunction(lhs, rhs); CHECK(!disjunction.covers(-2)); CHECK( disjunction.covers(-1)); CHECK( disjunction.covers( 0)); CHECK( disjunction.covers( 1)); CHECK(!disjunction.covers( 2)); CHECK( disjunction.covers( 3)); CHECK( disjunction.covers( 4)); CHECK( disjunction.covers( 5)); CHECK(!disjunction.covers( 6)); CHECK( disjunction.covers( 7)); CHECK( disjunction.covers( 8)); CHECK(!disjunction.covers( 9)); } TEST_CASE("Conjunction of two MultiRanges", "[MultiRange][conjunction]") { auto lhs = MultiRange(); lhs.addRange(Range(-1, 1)); lhs.addRange(Range(3, 5)); auto rhs = MultiRange(); rhs.addRange(Range(-1, -1)); rhs.addRange(Range(1, 1)); rhs.addRange(Range(4, 4)); auto conjunction = MultiRange::conjunction(lhs, rhs); CHECK( conjunction.covers(-1)); CHECK(!conjunction.covers( 0)); CHECK( conjunction.covers( 1)); CHECK(!conjunction.covers( 2)); CHECK(!conjunction.covers( 3)); CHECK( conjunction.covers( 4)); CHECK(!conjunction.covers( 5)); } TEST_CASE("MultiRange stream operator") { auto mr = MultiRange(); mr.addRange(Range(-1, 1)); mr.addRange(Range(3, 5)); std::stringstream ss; ss << mr; CHECK(ss.str() == "([-1:1], [3:5])"); } TEST_CASE("MultiRange size") { auto mr = MultiRange(); mr.addRange(Range(-1, 1)); mr.addRange(Range(3, 5)); CHECK(mr.size() == 6); } TEST_CASE("MultiRange draw") { auto mr = MultiRange(); mr.addRange(Range(-1, 1)); mr.addRange(Range(3, 5)); CHECK(mr.covers(mr.draw())); }
[ "tsmanner@us.ibm.com" ]
tsmanner@us.ibm.com
7354be8ea69e705781c84f2903219bc6020e2a40
ebabdda85c71fb3cd85a0cc07357a3a7ebc575ff
/Contest1221/H.cpp
ec7c6030dad8c90b53f19d76fb66e78fb02d6458
[]
no_license
xiaji/NOIP2018FS
c732da0b30237c0bddef75fe232e06f7c42ef21c
6902b89251924e261190bb9d77a75240bc99f6f2
refs/heads/master
2020-07-24T08:19:26.279164
2018-11-09T23:18:55
2018-11-09T23:18:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
#include <bits/stdc++.h> using namespace std; int main() { vector<int> F(1, 1); for (int i = 2; i <= 9; i++) { F.push_back(F[F.size() - 1] * i); } int T; cin >> T; while (T--) { int n; cin >> n; for (int i = F.size() - 1; i >= 0; i--) { if (F[i] <= n) { n -= F[i]; } } if (n == 0) { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }
[ "zj@webturing.com" ]
zj@webturing.com
0632775425c4b1ce48fe7297fd2641809035019e
7fa83125d4d2fb8ec13d5ef458eee48ff86c3835
/066_type_punning/HelloWorld/HelloWorld/src/Main.cpp
5b8c67042a8f5b54fef256f505aae850cd823114
[ "MIT" ]
permissive
christopher-besch/cpp_reference
40e071c01bc62075648e4364b2b6bf0f60e88585
ec84f2391697f58ff27668c27d14824eb542067e
refs/heads/master
2023-02-09T12:16:43.146488
2021-01-03T18:29:31
2021-01-03T18:29:31
276,929,189
10
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
#include <iostream> #define LOG(msg) std::cout << msg << std::endl class Entity { public: int x, y; }; int main() { int a = 50; // implicit conversion double value = a; // same as // double value = double(a); // or // double value = (double)a; LOG(value); // type punning // converting int pointer into double pointer and dereferencing it // not good because int is smaller than double double a_as_double = *(double*)&a; // or as reference // double& a_as_double = *(double*)&a; LOG(a_as_double); Entity e = { 5, 8 }; int* position = (int*)&e; LOG(position[0]); LOG(((int*)&e)[0]); // ridiculous!!! LOG(*(int*)((char*)&e + 4)); std::cin.get(); } /* * C++ is a strongly typed language -> except for auto there is a type system * type punning -> treat memory as a different type */
[ "christopher.besch@gmx.de" ]
christopher.besch@gmx.de
b7befd0bf498ba5e7afea0549cc9cf0c85d45301
d0fb46aecc3b69983e7f6244331a81dff42d9595
/dataworks-public/src/model/GetQualityEntityResult.cc
716587be573ea16d70ec8c52194a167b3ef10ec3
[ "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
4,183
cc
/* * 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. */ #include <alibabacloud/dataworks-public/model/GetQualityEntityResult.h> #include <json/json.h> using namespace AlibabaCloud::Dataworks_public; using namespace AlibabaCloud::Dataworks_public::Model; GetQualityEntityResult::GetQualityEntityResult() : ServiceResult() {} GetQualityEntityResult::GetQualityEntityResult(const std::string &payload) : ServiceResult() { parse(payload); } GetQualityEntityResult::~GetQualityEntityResult() {} void GetQualityEntityResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allDataNode = value["Data"]["EntityDto"]; for (auto valueDataEntityDto : allDataNode) { EntityDto dataObject; if(!valueDataEntityDto["RelativeNode"].isNull()) dataObject.relativeNode = valueDataEntityDto["RelativeNode"].asString(); if(!valueDataEntityDto["OnDutyAccountName"].isNull()) dataObject.onDutyAccountName = valueDataEntityDto["OnDutyAccountName"].asString(); if(!valueDataEntityDto["Task"].isNull()) dataObject.task = std::stoi(valueDataEntityDto["Task"].asString()); if(!valueDataEntityDto["TableName"].isNull()) dataObject.tableName = valueDataEntityDto["TableName"].asString(); if(!valueDataEntityDto["Followers"].isNull()) dataObject.followers = valueDataEntityDto["Followers"].asString(); if(!valueDataEntityDto["OnDuty"].isNull()) dataObject.onDuty = valueDataEntityDto["OnDuty"].asString(); if(!valueDataEntityDto["MatchExpression"].isNull()) dataObject.matchExpression = valueDataEntityDto["MatchExpression"].asString(); if(!valueDataEntityDto["CreateTime"].isNull()) dataObject.createTime = std::stol(valueDataEntityDto["CreateTime"].asString()); if(!valueDataEntityDto["ProjectName"].isNull()) dataObject.projectName = valueDataEntityDto["ProjectName"].asString(); if(!valueDataEntityDto["HasRelativeNode"].isNull()) dataObject.hasRelativeNode = valueDataEntityDto["HasRelativeNode"].asString() == "true"; if(!valueDataEntityDto["EnvType"].isNull()) dataObject.envType = valueDataEntityDto["EnvType"].asString(); if(!valueDataEntityDto["EntityLevel"].isNull()) dataObject.entityLevel = std::stoi(valueDataEntityDto["EntityLevel"].asString()); if(!valueDataEntityDto["ModifyUser"].isNull()) dataObject.modifyUser = valueDataEntityDto["ModifyUser"].asString(); if(!valueDataEntityDto["Sql"].isNull()) dataObject.sql = std::stoi(valueDataEntityDto["Sql"].asString()); if(!valueDataEntityDto["Id"].isNull()) dataObject.id = std::stol(valueDataEntityDto["Id"].asString()); if(!valueDataEntityDto["ModifyTime"].isNull()) dataObject.modifyTime = std::stol(valueDataEntityDto["ModifyTime"].asString()); data_.push_back(dataObject); } if(!value["HttpStatusCode"].isNull()) httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString()); if(!value["ErrorMessage"].isNull()) errorMessage_ = value["ErrorMessage"].asString(); if(!value["ErrorCode"].isNull()) errorCode_ = value["ErrorCode"].asString(); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } int GetQualityEntityResult::getHttpStatusCode()const { return httpStatusCode_; } std::vector<GetQualityEntityResult::EntityDto> GetQualityEntityResult::getData()const { return data_; } std::string GetQualityEntityResult::getErrorCode()const { return errorCode_; } std::string GetQualityEntityResult::getErrorMessage()const { return errorMessage_; } bool GetQualityEntityResult::getSuccess()const { return success_; }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
54b1cf61425ed9246af1a98f1134a1ad76d4019c
9e1e09ea61632e80465f371a083625d03b1e5ab2
/src/WalletLegacy/WalletUnconfirmedTransactions.cpp
7fc89f76191e5b42b53233016ae97a0a14c2393b
[ "MIT" ]
permissive
bitcoin-note/bitcoin-note
0f93c5a04dda2df6ff838187d894a0c4af633649
7be1e60f327b7ce1f995fee97f80131dcb934e70
refs/heads/master
2021-05-11T19:50:51.485229
2018-01-18T00:05:24
2018-01-18T00:05:24
117,895,059
3
2
null
null
null
null
UTF-8
C++
false
false
4,128
cpp
// Copyright (c) 2018, The Bitcoin Note Developers. // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "WalletUnconfirmedTransactions.h" #include "WalletLegacy/WalletLegacySerialization.h" #include "CryptoNoteCore/CryptoNoteTools.h" #include "Serialization/ISerializer.h" #include "Serialization/SerializationOverloads.h" using namespace Crypto; namespace CryptoNote { inline TransactionOutputId getOutputId(const TransactionOutputInformation& out) { return std::make_pair(out.transactionPublicKey, out.outputInTransaction); } WalletUnconfirmedTransactions::WalletUnconfirmedTransactions(uint64_t uncofirmedTransactionsLiveTime): m_uncofirmedTransactionsLiveTime(uncofirmedTransactionsLiveTime) { } bool WalletUnconfirmedTransactions::serialize(ISerializer& s) { s(m_unconfirmedTxs, "transactions"); if (s.type() == ISerializer::INPUT) { collectUsedOutputs(); } return true; } bool WalletUnconfirmedTransactions::findTransactionId(const Hash& hash, TransactionId& id) { auto it = m_unconfirmedTxs.find(hash); if (it == m_unconfirmedTxs.end()) { return false; } id = it->second.transactionId; return true; } void WalletUnconfirmedTransactions::erase(const Hash& hash) { auto it = m_unconfirmedTxs.find(hash); if (it == m_unconfirmedTxs.end()) { return; } deleteUsedOutputs(it->second.usedOutputs); m_unconfirmedTxs.erase(it); } void WalletUnconfirmedTransactions::add(const Transaction& tx, TransactionId transactionId, uint64_t amount, const std::list<TransactionOutputInformation>& usedOutputs) { UnconfirmedTransferDetails& utd = m_unconfirmedTxs[getObjectHash(tx)]; utd.amount = amount; utd.sentTime = time(nullptr); utd.tx = tx; utd.transactionId = transactionId; uint64_t outsAmount = 0; // process used outputs utd.usedOutputs.reserve(usedOutputs.size()); for (const auto& out : usedOutputs) { auto id = getOutputId(out); utd.usedOutputs.push_back(id); m_usedOutputs.insert(id); outsAmount += out.amount; } utd.outsAmount = outsAmount; } void WalletUnconfirmedTransactions::updateTransactionId(const Hash& hash, TransactionId id) { auto it = m_unconfirmedTxs.find(hash); if (it != m_unconfirmedTxs.end()) { it->second.transactionId = id; } } uint64_t WalletUnconfirmedTransactions::countUnconfirmedOutsAmount() const { uint64_t amount = 0; for (auto& utx: m_unconfirmedTxs) amount+= utx.second.outsAmount; return amount; } uint64_t WalletUnconfirmedTransactions::countUnconfirmedTransactionsAmount() const { uint64_t amount = 0; for (auto& utx: m_unconfirmedTxs) amount+= utx.second.amount; return amount; } bool WalletUnconfirmedTransactions::isUsed(const TransactionOutputInformation& out) const { return m_usedOutputs.find(getOutputId(out)) != m_usedOutputs.end(); } void WalletUnconfirmedTransactions::collectUsedOutputs() { UsedOutputsContainer used; for (const auto& kv : m_unconfirmedTxs) { used.insert(kv.second.usedOutputs.begin(), kv.second.usedOutputs.end()); } m_usedOutputs = std::move(used); } void WalletUnconfirmedTransactions::reset() { m_unconfirmedTxs.clear(); m_usedOutputs.clear(); } void WalletUnconfirmedTransactions::deleteUsedOutputs(const std::vector<TransactionOutputId>& usedOutputs) { for (const auto& output: usedOutputs) { m_usedOutputs.erase(output); } } std::vector<TransactionId> WalletUnconfirmedTransactions::deleteOutdatedTransactions() { std::vector<TransactionId> deletedTransactions; uint64_t now = static_cast<uint64_t>(time(nullptr)); assert(now >= m_uncofirmedTransactionsLiveTime); for (auto it = m_unconfirmedTxs.begin(); it != m_unconfirmedTxs.end();) { if (static_cast<uint64_t>(it->second.sentTime) <= now - m_uncofirmedTransactionsLiveTime) { deleteUsedOutputs(it->second.usedOutputs); deletedTransactions.push_back(it->second.transactionId); it = m_unconfirmedTxs.erase(it); } else { ++it; } } return deletedTransactions; } } /* namespace CryptoNote */
[ "bitnotecurrency@gmail.com" ]
bitnotecurrency@gmail.com
ff7d471fc93cc2d95502d29bd7059d5e47c321c1
07a7045c925395d1c188d65300a228a9ca0c8ed5
/149. Max Points on a Line.cpp
dbe9f5c7e441bf3f2af206f24458b30e5a7053f5
[]
no_license
hu18yuanwai/leetcode
1063766a751b228526e6c243e5791631c5b2b3c5
b00f638fa3c3628eebba560621694ff2e6a8fb87
refs/heads/master
2020-04-06T07:02:18.549489
2017-06-20T02:44:09
2017-06-20T02:44:09
63,048,648
0
0
null
null
null
null
UTF-8
C++
false
false
4,495
cpp
/** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */ class Solution { public: int maxPoints(vector<Point>& points) { if (points.size() < 3) { return points.size(); } sort(points.begin(), points.end(), [](Point &pt1, Point &pt2) { return pt1.x == pt2.x ? pt1.y < pt2. y : pt1.x < pt2.x; }); int maxPts = 0; for (int i = 0; i < points.size(); i++) { if (i > 0 && samePoint(points[i], points[i - 1])) // pass duplicates. { continue; } unordered_map<double, int> ptsOnLines; int originPts = 1; for (int j = i + 1; j < points.size(); j++) { if (samePoint(points[i], points[j])) { originPts++; } else if (verticleLine(points[i], points[j])) { ptsOnLines[numeric_limits<double>::infinity()]++; } else { ptsOnLines[slope(points[i], points[j])]++; } } using T = unordered_map<double, int>::value_type; auto itr = max_element(ptsOnLines.begin(), ptsOnLines.end(), [](const T &p1, const T &p2) { return p1.second < p2.second; }); maxPts = max(maxPts, originPts + (itr == ptsOnLines.end() ? 0 : itr->second)); } return maxPts; } private: inline bool samePoint(const Point &pt1, const Point &pt2) { return pt1.x == pt2.x && pt1.y == pt2.y; } inline bool verticleLine(const Point &pt1, const Point &pt2) { return pt1.x == pt2.x && pt1.y != pt2.y; } inline double slope(const Point &pt1, const Point &pt2) { return ((double) pt2.y - pt1.y) / (pt2.x - pt1.x); } }; class Solution { public: int maxPoints(vector<Point>& points) { if(points.size()<3) return points.size(); int ret=0; for(int i=0;i<points.size();i++){ int maxc=1; map<double,int> count; int coincide=0; int vnt=0; for(int j=0;j<points.size();i++){ // there is not i, fucking >>>>>>>>>>>>>>>>>>>>> if(i!=j){ double x1=points[i].x-points[j].x; double x2=points[i].y-points[j].y; if(x1==0 && x2==0) coincide++; else if( x1==0){ if(vnt==0) vnt=2; else vnt++; maxc=max(maxc,vnt); } else{ double k=x2/x1; if(count.find(k)==count.end()) count[k]=2; else count[k]++; maxc=max(maxc,count[k]); } } } ret=max(ret,maxc+coincide); } return ret; } }; // the worry solution #define DBL_MAX 1.7976931348623158e+308 class Solution { public: int maxPoints(vector<Point>& points) { map<Line,int> count; for(int i=0;i<points.size();i++){ for(int j=0;j<points.size();j++){ if(i!=j){ double k,b; double x1=points[i].x; double y1=points[i].y; double x2=points[j].x; double y2=points[j].y; if(x1==x2){ k=DBL_MAX; b=x1; } else{ k=(y2-y1)/(x2*1.0-x1); b=(y1*x2-y2*x1)/(x2*1.0-x1); } Line line(k,b); if(count.find(line)!=count.end()){ count[line]++; } else{ count[line]=0; } } } } int max=INT_MAX; for(map<Line,int>::iterator mapi=count.begin();mapi!=count.end();mapi++){ if(max<mapi->second) max=mapi->second; } return max; } private: struct Line{ double a; double b; Line():a(0.),b(0.){} Line(double x,double y):a(x),b(y){} bool operator =(Line l2){ if(dCmp(this.x,l2.x)==0 && dCmp(this.y,l2.y)==0) return 1; return 0; } int dCmp(double a, double b){ if (a < b - DBL_EPSILON) return -1; else if (a > b + DBL_EPSILON) return 1; else return 0; } }; };
[ "hu18yuanwai@gmail.com" ]
hu18yuanwai@gmail.com
b2415818750f0c17daac085c49d7c5c91b7b5536
f9b7dcbd841a0b3dd0fcd2f0941d498346f88599
/components/viz/common/features.h
f28c1096570a067e6ecd85a3a5406d6abc229801
[ "BSD-3-Clause" ]
permissive
browser-auto/chromium
58bace4173da259625cb3c4725f9d7ec6a4d2e03
36d524c252b60b059deaf7849fb6b082bee3018d
refs/heads/master
2022-11-16T12:38:05.031058
2019-11-18T12:28:56
2019-11-18T12:28:56
222,449,220
1
0
BSD-3-Clause
2019-11-18T12:55:08
2019-11-18T12:55:07
null
UTF-8
C++
false
false
1,255
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_VIZ_COMMON_FEATURES_H_ #define COMPONENTS_VIZ_COMMON_FEATURES_H_ #include "components/viz/common/viz_common_export.h" #include "base/feature_list.h" namespace features { VIZ_COMMON_EXPORT extern const base::Feature kEnableVizHitTestSurfaceLayer; VIZ_COMMON_EXPORT extern const base::Feature kUseSkiaForGLReadback; VIZ_COMMON_EXPORT extern const base::Feature kUseSkiaRenderer; VIZ_COMMON_EXPORT extern const base::Feature kRecordSkPicture; VIZ_COMMON_EXPORT extern const base::Feature kVizDisplayCompositor; VIZ_COMMON_EXPORT extern const base::Feature kDisableDeJelly; VIZ_COMMON_EXPORT extern const base::Feature kVizForWebView; VIZ_COMMON_EXPORT bool IsVizDisplayCompositorEnabled(); VIZ_COMMON_EXPORT bool IsVizHitTestingDebugEnabled(); VIZ_COMMON_EXPORT bool IsVizHitTestingSurfaceLayerEnabled(); VIZ_COMMON_EXPORT bool IsUsingSkiaForGLReadback(); VIZ_COMMON_EXPORT bool IsUsingSkiaRenderer(); VIZ_COMMON_EXPORT bool IsRecordingSkPicture(); VIZ_COMMON_EXPORT bool IsUsingVizForWebView(); } // namespace features #endif // COMPONENTS_VIZ_COMMON_FEATURES_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
4397496455e8030db1c0d107c1d938733741184e
35613a63c2dcf790adc2dcd025a9021a95f9762d
/resources/texture.h
931eab24866b30389fbb6fc70fb9ff2f002f297a
[]
no_license
fromasmtodisasm/xrRenderPC_VK
37bda9ff60c98a4de82999af0f2775d508dd094d
07ef9bbc0a0ab21605423189b4e2952ae8d9c400
refs/heads/master
2022-03-24T11:42:53.270351
2019-12-21T08:06:03
2019-12-21T08:06:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,362
h
#ifndef RESOURCES_TEXTURE_H_ #define RESOURCES_TEXTURE_H_ #include <functional> #include <memory> #include <string> #include <vector> #include "xrEngine/xrTheora_Surface.h" #include "backend/streams.h" class Texture : public xr_resource_named { enum class TextureType { Unknown, Normal, Theora, Avi, Sequence }; TextureType type = TextureType::Unknown; struct Flags { bool user = false; bool loaded = false; ///< Indicates that texture is already loaded bool staging = false; ///< Defer image uploading until pipeline binding bool cycled = false; ///< Cycled anitmation } flags; std::uint32_t ms_per_frame; ///< Milliseconds per frame in animation sequence std::vector<std::shared_ptr<StreamImage>> sequence_frames; ///< Animation frames std::unique_ptr<CTheoraSurface> theora_; ///< Theora surface std::shared_ptr<StreamImage> TextureLoad(const std::string &file_name); void ApplyLoad(); void ApplyTheora(); void ApplyAvi(); void ApplySequence(); void ApplyNormal(); public: Texture(); ~Texture(); void Preload(); void Load(); void Postload(); std::function<void(void)> Loader; std::shared_ptr<StreamImage> image; vk::ImageView view; }; #endif // RESOURCES_TEXTURE_H_
[ "vtrubiloff@gmail.com" ]
vtrubiloff@gmail.com
ae35218eb6db4f61a3b77875a09655db8d617320
7d026f691c39b7ca54f624475f2253f3c57d8879
/arduino/dmp/inv_mpu.cpp
d7ef83947e64e8059c5c2b63241e0b904145b00f
[]
no_license
iverasp/unity3d_imu
bcd44ec24569b244948df44c097a1effdeab972d
21637d74b224dfe86543c2cc4ec22d82bb4fdd1f
refs/heads/master
2020-04-17T20:16:21.936872
2016-11-02T11:59:33
2016-11-02T11:59:33
66,857,512
1
0
null
null
null
null
UTF-8
C++
false
false
81,456
cpp
/* $License: Copyright (C) 2011-2012 InvenSense Corporation, All Rights Reserved. See included License.txt for License information. $ */ /** * @addtogroup DRIVERS Sensor Driver Layer * @brief Hardware drivers to communicate with sensors via I2C. * * @{ * @file inv_mpu.c * @brief An I2C-based driver for Invensense gyroscopes. * @details This driver currently works for the following devices: * MPU6050 * MPU6500 * MPU9150 (or MPU6050 w/ AK8975 on the auxiliary bus) * MPU9250 (or MPU6500 w/ AK8963 on the auxiliary bus) */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "inv_mpu.h" /* The following functions must be defined for this platform: * i2c_write(unsigned char slave_addr, unsigned char reg_addr, * unsigned char length, unsigned char const *data) * i2c_read(unsigned char slave_addr, unsigned char reg_addr, * unsigned char length, unsigned char *data) * delay_ms(unsigned long num_ms) * get_ms(unsigned long *count) * reg_int_cb(void (*cb)(void), unsigned char port, unsigned char pin) * labs(long x) * fabsf(float x) * min(int a, int b) */ #define i2c_write !I2Cdev::writeBytes #define i2c_read !I2Cdev::readBytes #define delay_ms delay static inline int reg_int_cb(struct int_param_s *int_param) { } #define min(a,b) ((a<b)?a:b) #define MPU9250 #if !defined MPU6050 && !defined MPU9150 && !defined MPU6500 && !defined MPU9250 #error Which gyro are you using? Define MPUxxxx in your compiler options. #endif /* Time for some messy macro work. =] * #define MPU9150 * is equivalent to.. * #define MPU6050 * #define AK8975_SECONDARY * * #define MPU9250 * is equivalent to.. * #define MPU6500 * #define AK8963_SECONDARY */ #if defined MPU9150 #ifndef MPU6050 #define MPU6050 #endif /* #ifndef MPU6050 */ #if defined AK8963_SECONDARY #error "MPU9150 and AK8963_SECONDARY cannot both be defined." #elif !defined AK8975_SECONDARY /* #if defined AK8963_SECONDARY */ #define AK8975_SECONDARY #endif /* #if defined AK8963_SECONDARY */ #elif defined MPU9250 /* #if defined MPU9150 */ #ifndef MPU6500 #define MPU6500 #endif /* #ifndef MPU6500 */ #if defined AK8975_SECONDARY #error "MPU9250 and AK8975_SECONDARY cannot both be defined." #elif !defined AK8963_SECONDARY /* #if defined AK8975_SECONDARY */ #define AK8963_SECONDARY #endif /* #if defined AK8975_SECONDARY */ #endif /* #if defined MPU9150 */ #if defined AK8975_SECONDARY || defined AK8963_SECONDARY #define AK89xx_SECONDARY #else /* #warning "No compass = less profit for Invensense. Lame." */ #endif static int set_int_enable(unsigned char enable); /* Hardware registers needed by driver. */ struct gyro_reg_s { unsigned char who_am_i; unsigned char rate_div; unsigned char lpf; unsigned char prod_id; unsigned char user_ctrl; unsigned char fifo_en; unsigned char gyro_cfg; unsigned char accel_cfg; unsigned char accel_cfg2; unsigned char lp_accel_odr; unsigned char motion_thr; unsigned char motion_dur; unsigned char fifo_count_h; unsigned char fifo_r_w; unsigned char raw_gyro; unsigned char raw_accel; unsigned char temp; unsigned char int_enable; unsigned char dmp_int_status; unsigned char int_status; unsigned char accel_intel; unsigned char pwr_mgmt_1; unsigned char pwr_mgmt_2; unsigned char int_pin_cfg; unsigned char mem_r_w; unsigned char accel_offs; unsigned char i2c_mst; unsigned char bank_sel; unsigned char mem_start_addr; unsigned char prgm_start_h; #if defined AK89xx_SECONDARY unsigned char s0_addr; unsigned char s0_reg; unsigned char s0_ctrl; unsigned char s1_addr; unsigned char s1_reg; unsigned char s1_ctrl; unsigned char s4_ctrl; unsigned char s0_do; unsigned char s1_do; unsigned char i2c_delay_ctrl; unsigned char raw_compass; /* The I2C_MST_VDDIO bit is in this register. */ unsigned char yg_offs_tc; #endif }; /* Information specific to a particular device. */ struct hw_s { unsigned char addr; unsigned short max_fifo; unsigned char num_reg; unsigned short temp_sens; short temp_offset; unsigned short bank_size; #if defined AK89xx_SECONDARY unsigned short compass_fsr; #endif }; /* When entering motion interrupt mode, the driver keeps track of the * previous state so that it can be restored at a later time. * TODO: This is tacky. Fix it. */ struct motion_int_cache_s { unsigned short gyro_fsr; unsigned char accel_fsr; unsigned short lpf; unsigned short sample_rate; unsigned char sensors_on; unsigned char fifo_sensors; unsigned char dmp_on; }; /* Cached chip configuration data. * TODO: A lot of these can be handled with a bitmask. */ struct chip_cfg_s { /* Matches gyro_cfg >> 3 & 0x03 */ unsigned char gyro_fsr; /* Matches accel_cfg >> 3 & 0x03 */ unsigned char accel_fsr; /* Enabled sensors. Uses same masks as fifo_en, NOT pwr_mgmt_2. */ unsigned char sensors; /* Matches config register. */ unsigned char lpf; unsigned char clk_src; /* Sample rate, NOT rate divider. */ unsigned short sample_rate; /* Matches fifo_en register. */ unsigned char fifo_enable; /* Matches int enable register. */ unsigned char int_enable; /* 1 if devices on auxiliary I2C bus appear on the primary. */ unsigned char bypass_mode; /* 1 if half-sensitivity. * NOTE: This doesn't belong here, but everything else in hw_s is const, * and this allows us to save some precious RAM. */ unsigned char accel_half; /* 1 if device in low-power accel-only mode. */ unsigned char lp_accel_mode; /* 1 if interrupts are only triggered on motion events. */ unsigned char int_motion_only; struct motion_int_cache_s cache; /* 1 for active low interrupts. */ unsigned char active_low_int; /* 1 for latched interrupts. */ unsigned char latched_int; /* 1 if DMP is enabled. */ unsigned char dmp_on; /* Ensures that DMP will only be loaded once. */ unsigned char dmp_loaded; /* Sampling rate used when DMP is enabled. */ unsigned short dmp_sample_rate; #ifdef AK89xx_SECONDARY /* Compass sample rate. */ unsigned short compass_sample_rate; unsigned char compass_addr; short mag_sens_adj[3]; #endif }; /* Information for self-test-> */ struct test_s { unsigned long gyro_sens; unsigned long accel_sens; unsigned char reg_rate_div; unsigned char reg_lpf; unsigned char reg_gyro_fsr; unsigned char reg_accel_fsr; unsigned short wait_ms; unsigned char packet_thresh; float min_dps; float max_dps; float max_gyro_var; float min_g; float max_g; float max_accel_var; }; /* Gyro driver state variables. */ struct gyro_state_s { const struct gyro_reg_s *reg; const struct hw_s *hw; struct chip_cfg_s chip_cfg; const struct test_s *test; }; /* Filter configurations. */ enum lpf_e { INV_FILTER_256HZ_NOLPF2 = 0, INV_FILTER_188HZ, INV_FILTER_98HZ, INV_FILTER_42HZ, INV_FILTER_20HZ, INV_FILTER_10HZ, INV_FILTER_5HZ, INV_FILTER_2100HZ_NOLPF, NUM_FILTER }; /* Full scale ranges. */ enum gyro_fsr_e { INV_FSR_250DPS = 0, INV_FSR_500DPS, INV_FSR_1000DPS, INV_FSR_2000DPS, NUM_GYRO_FSR }; /* Full scale ranges. */ enum accel_fsr_e { INV_FSR_2G = 0, INV_FSR_4G, INV_FSR_8G, INV_FSR_16G, NUM_ACCEL_FSR }; /* Clock sources. */ enum clock_sel_e { INV_CLK_INTERNAL = 0, INV_CLK_PLL, NUM_CLK }; /* Low-power accel wakeup rates. */ enum lp_accel_rate_e { #if defined MPU6050 INV_LPA_1_25HZ, INV_LPA_5HZ, INV_LPA_20HZ, INV_LPA_40HZ #elif defined MPU6500 INV_LPA_0_3125HZ, INV_LPA_0_625HZ, INV_LPA_1_25HZ, INV_LPA_2_5HZ, INV_LPA_5HZ, INV_LPA_10HZ, INV_LPA_20HZ, INV_LPA_40HZ, INV_LPA_80HZ, INV_LPA_160HZ, INV_LPA_320HZ, INV_LPA_640HZ #endif }; #define BIT_I2C_MST_VDDIO (0x80) #define BIT_FIFO_EN (0x40) #define BIT_DMP_EN (0x80) #define BIT_FIFO_RST (0x04) #define BIT_DMP_RST (0x08) #define BIT_FIFO_OVERFLOW (0x10) #define BIT_DATA_RDY_EN (0x01) #define BIT_DMP_INT_EN (0x02) #define BIT_MOT_INT_EN (0x40) #define BITS_FSR (0x18) #define BITS_LPF (0x07) #define BITS_HPF (0x07) #define BITS_CLK (0x07) #define BIT_FIFO_SIZE_1024 (0x40) #define BIT_FIFO_SIZE_2048 (0x80) #define BIT_FIFO_SIZE_4096 (0xC0) #define BIT_RESET (0x80) #define BIT_SLEEP (0x40) #define BIT_S0_DELAY_EN (0x01) #define BIT_S2_DELAY_EN (0x04) #define BITS_SLAVE_LENGTH (0x0F) #define BIT_SLAVE_BYTE_SW (0x40) #define BIT_SLAVE_GROUP (0x10) #define BIT_SLAVE_EN (0x80) #define BIT_I2C_READ (0x80) #define BITS_I2C_MASTER_DLY (0x1F) #define BIT_AUX_IF_EN (0x20) #define BIT_ACTL (0x80) #define BIT_LATCH_EN (0x20) #define BIT_ANY_RD_CLR (0x10) #define BIT_BYPASS_EN (0x02) #define BITS_WOM_EN (0xC0) #define BIT_LPA_CYCLE (0x20) #define BIT_STBY_XA (0x20) #define BIT_STBY_YA (0x10) #define BIT_STBY_ZA (0x08) #define BIT_STBY_XG (0x04) #define BIT_STBY_YG (0x02) #define BIT_STBY_ZG (0x01) #define BIT_STBY_XYZA (BIT_STBY_XA | BIT_STBY_YA | BIT_STBY_ZA) #define BIT_STBY_XYZG (BIT_STBY_XG | BIT_STBY_YG | BIT_STBY_ZG) #if defined AK8975_SECONDARY #define SUPPORTS_AK89xx_HIGH_SENS (0x00) #define AK89xx_FSR (9830) #elif defined AK8963_SECONDARY #define SUPPORTS_AK89xx_HIGH_SENS (0x10) #define AK89xx_FSR (4915) #endif #ifdef AK89xx_SECONDARY #define AKM_REG_WHOAMI (0x00) #define AKM_REG_ST1 (0x02) #define AKM_REG_HXL (0x03) #define AKM_REG_ST2 (0x09) #define AKM_REG_CNTL (0x0A) #define AKM_REG_ASTC (0x0C) #define AKM_REG_ASAX (0x10) #define AKM_REG_ASAY (0x11) #define AKM_REG_ASAZ (0x12) #define AKM_DATA_READY (0x01) #define AKM_DATA_OVERRUN (0x02) #define AKM_OVERFLOW (0x80) #define AKM_DATA_ERROR (0x40) #define AKM_BIT_SELF_TEST (0x40) #define AKM_POWER_DOWN (0x00 | SUPPORTS_AK89xx_HIGH_SENS) #define AKM_SINGLE_MEASUREMENT (0x01 | SUPPORTS_AK89xx_HIGH_SENS) #define AKM_FUSE_ROM_ACCESS (0x0F | SUPPORTS_AK89xx_HIGH_SENS) #define AKM_MODE_SELF_TEST (0x08 | SUPPORTS_AK89xx_HIGH_SENS) #define AKM_WHOAMI (0x48) #endif struct gyro_reg_s regArray[MPU_MAX_DEVICES]; struct hw_s hwArray[MPU_MAX_DEVICES]; struct test_s testArray[MPU_MAX_DEVICES]; struct gyro_state_s gyroArray[MPU_MAX_DEVICES]; // These variables are set by the mpu_delect_device function struct gyro_reg_s *reg; struct hw_s *hw; struct test_s *test; struct gyro_state_s *st; static int deviceIndex = 0; int mpu_select_device(int device) { if ((device < 0) || (device >= MPU_MAX_DEVICES)) return -1; deviceIndex = device; reg = regArray + device; hw = hwArray + device; test = testArray + device; st = gyroArray + device; return 0; } #if defined MPU6050 void mpu_init_structures() { reg->who_am_i = 0x75; reg->rate_div = 0x19; reg->lpf = 0x1A; reg->prod_id = 0x0C; reg->user_ctrl = 0x6A; reg->fifo_en = 0x23; reg->gyro_cfg = 0x1B; reg->accel_cfg = 0x1C; reg->motion_thr = 0x1F; reg->motion_dur = 0x20; reg->fifo_count_h = 0x72; reg->fifo_r_w = 0x74; reg->raw_gyro = 0x43; reg->raw_accel = 0x3B; reg->temp = 0x41; reg->int_enable = 0x38; reg->dmp_int_status = 0x39; reg->int_status = 0x3A; reg->pwr_mgmt_1 = 0x6B; reg->pwr_mgmt_2 = 0x6C; reg->int_pin_cfg = 0x37; reg->mem_r_w = 0x6F; reg->accel_offs = 0x06; reg->i2c_mst = 0x24; reg->bank_sel = 0x6D; reg->mem_start_addr = 0x6E; reg->prgm_start_h = 0x70; #ifdef AK89xx_SECONDARY reg->raw_compass = 0x49; reg->yg_offs_tc = 0x01; reg->s0_addr = 0x25; reg->s0_reg = 0x26; reg->s0_ctrl = 0x27; reg->s1_addr = 0x28; reg->s1_reg = 0x29; reg->s1_ctrl = 0x2A; reg->s4_ctrl = 0x34; reg->s0_do = 0x63; reg->s1_do = 0x64; reg->i2c_delay_ctrl = 0x67; #endif switch (deviceIndex) { case 0: hw->addr = 0x68; break; case 1: hw->addr = 0x69; break; } hw->max_fifo = 1024; hw->num_reg = 118; hw->temp_sens = 340; hw->temp_offset = -521; hw->bank_size = 256; #if defined AK89xx_SECONDARY hw->compass_fsr = AK89xx_FSR; #endif test->gyro_sens = 32768/250; test->accel_sens = 32768/16; test->reg_rate_div = 0; /* 1kHz. */ test->reg_lpf = 1; /* 188Hz. */ test->reg_gyro_fsr = 0; /* 250dps. */ test->reg_accel_fsr = 0x18; /* 16g. */ test->wait_ms = 50; test->packet_thresh = 5; /* 5% */ test->min_dps = 10.f; test->max_dps = 105.f; test->max_gyro_var = 0.14f; test->min_g = 0.3f; test->max_g = 0.95f; test->max_accel_var = 0.14f; st->reg = reg; st->hw = hw; st->test = test; }; #elif defined MPU6500 void mpu_init_structures() { reg->who_am_i = 0x75; reg->rate_div = 0x19; reg->lpf = 0x1A; reg->prod_id = 0x0C; reg->user_ctrl = 0x6A; reg->fifo_en = 0x23; reg->gyro_cfg = 0x1B; reg->accel_cfg = 0x1C; reg->accel_cfg2 = 0x1D; reg->lp_accel_odr = 0x1E; reg->motion_thr = 0x1F; reg->motion_dur = 0x20; reg->fifo_count_h = 0x72; reg->fifo_r_w = 0x74; reg->raw_gyro = 0x43; reg->raw_accel = 0x3B; reg->temp = 0x41; reg->int_enable = 0x38; reg->dmp_int_status = 0x39; reg->int_status = 0x3A; reg->accel_intel = 0x69; reg->pwr_mgmt_1 = 0x6B; reg->pwr_mgmt_2 = 0x6C; reg->int_pin_cfg = 0x37; reg->mem_r_w = 0x6F; reg->accel_offs = 0x77; reg->i2c_mst = 0x24; reg->bank_sel = 0x6D; reg->mem_start_addr = 0x6E; reg->prgm_start_h = 0x70; #ifdef AK89xx_SECONDARY reg->raw_compass = 0x49; reg->yg_offs_tc = 0x01; reg->s0_addr = 0x25; reg->s0_reg = 0x26; reg->s0_ctrl = 0x27; reg->s1_addr = 0x28; reg->s1_reg = 0x29; reg->s1_ctrl = 0x2A; reg->s4_ctrl = 0x34; reg->s0_do = 0x63; reg->s1_do = 0x64; reg->i2c_delay_ctrl = 0x67; #endif switch (deviceIndex) { case 0: hw->addr = 0x68; break; case 1: hw->addr = 0x69; break; } hw->max_fifo = 1024; hw->num_reg = 128; hw->temp_sens = 321; hw->temp_offset = 0; hw->bank_size = 256; #if defined AK89xx_SECONDARY hw->compass_fsr = AK89xx_FSR; #endif test->gyro_sens = 32768/250; test->accel_sens = 32768/16; test->reg_rate_div = 0; /* 1kHz. */ test->reg_lpf = 1; /* 188Hz. */ test->reg_gyro_fsr = 0; /* 250dps. */ test->reg_accel_fsr = 0x18; /* 16g. */ test->wait_ms = 50; test->packet_thresh = 5; /* 5% */ test->min_dps = 10.f; test->max_dps = 105.f; test->max_gyro_var = 0.14f; test->min_g = 0.3f; test->max_g = 0.95f; test->max_accel_var = 0.14f; st->reg = reg; st->hw = hw; st->test = test; }; #endif #define MAX_PACKET_LENGTH (12) #ifdef AK89xx_SECONDARY static int setup_compass(void); #define MAX_COMPASS_SAMPLE_RATE (100) #endif /** * @brief Enable/disable data ready interrupt. * If the DMP is on, the DMP interrupt is enabled. Otherwise, the data ready * interrupt is used. * @param[in] enable 1 to enable interrupt. * @return 0 if successful. */ static int set_int_enable(unsigned char enable) { unsigned char tmp; if (st->chip_cfg.dmp_on) { if (enable) tmp = BIT_DMP_INT_EN; else tmp = 0x00; if (i2c_write(st->hw->addr, st->reg->int_enable, 1, &tmp)) return -1; st->chip_cfg.int_enable = tmp; } else { if (!st->chip_cfg.sensors) return -1; if (enable && st->chip_cfg.int_enable) return 0; if (enable) tmp = BIT_DATA_RDY_EN; else tmp = 0x00; if (i2c_write(st->hw->addr, st->reg->int_enable, 1, &tmp)) return -1; st->chip_cfg.int_enable = tmp; } return 0; } /** * @brief Register dump for testing. * @return 0 if successful. */ int mpu_reg_dump(void) { unsigned char ii; unsigned char data; for (ii = 0; ii < st->hw->num_reg; ii++) { if (ii == st->reg->fifo_r_w || ii == st->reg->mem_r_w) continue; if (i2c_read(st->hw->addr, ii, 1, &data)) return -1; // log_i("%#5x: %#5x\r\n", ii, data); } return 0; } /** * @brief Read from a single register. * NOTE: The memory and FIFO read/write registers cannot be accessed. * @param[in] reg Register address. * @param[out] data Register data. * @return 0 if successful. */ int mpu_read_reg(unsigned char reg, unsigned char *data) { if (reg == st->reg->fifo_r_w || reg == st->reg->mem_r_w) return -1; if (reg >= st->hw->num_reg) return -1; return i2c_read(st->hw->addr, reg, 1, data); } /** * @brief Initialize hardware. * Initial configuration:\n * Gyro FSR: +/- 2000DPS\n * Accel FSR +/- 2G\n * DLPF: 42Hz\n * FIFO rate: 50Hz\n * Clock source: Gyro PLL\n * FIFO: Disabled.\n * Data ready interrupt: Disabled, active low, unlatched. * @param[in] int_param Platform-specific parameters to interrupt API. * @return 0 if successful. */ int mpu_init(struct int_param_s *int_param) { unsigned char data[6], rev; int errCode; /* Reset device. */ data[0] = BIT_RESET; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, data)) return -1; delay_ms(100); /* Wake up chip. */ data[0] = 0x00; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, data)) return -2; #if defined MPU6050 /* Check product revision. */ if (i2c_read(st->hw->addr, st->reg->accel_offs, 6, data)) return -3; rev = ((data[5] & 0x01) << 2) | ((data[3] & 0x01) << 1) | (data[1] & 0x01); if (rev) { /* Congrats, these parts are better. */ if (rev == 1) st->chip_cfg.accel_half = 1; else if (rev == 2) st->chip_cfg.accel_half = 0; else { #ifdef MPU_DEBUG Serial.print("Unsupported software product rev: "); Serial.println(rev); #endif return -4; } } else { if (i2c_read(st->hw->addr, st->reg->prod_id, 1, data)) return -5; rev = data[0] & 0x0F; if (!rev) { #ifdef MPU_DEBUG Serial.println("Product ID read as 0 indicates device is either incompatible or an MPU3050"); #endif return -6; } else if (rev == 4) { #ifdef MPU_DEBUG Serial.println("Half sensitivity part found."); #endif st->chip_cfg.accel_half = 1; } else st->chip_cfg.accel_half = 0; } #elif defined MPU6500 #define MPU6500_MEM_REV_ADDR (0x17) if (mpu_read_mem(MPU6500_MEM_REV_ADDR, 1, &rev)) return -7; if (rev == 0x1) st->chip_cfg.accel_half = 0; else { #ifdef MPU_DEBUG Serial.print("Unsupported software product rev: "); Serial.println(rev); #endif return -8; } /* MPU6500 shares 4kB of memory between the DMP and the FIFO. Since the * first 3kB are needed by the DMP, we'll use the last 1kB for the FIFO. */ data[0] = BIT_FIFO_SIZE_1024 | 0x8; if (i2c_write(st->hw->addr, st->reg->accel_cfg2, 1, data)) return -9; #endif /* Set to invalid values to ensure no I2C writes are skipped. */ st->chip_cfg.sensors = 0xFF; st->chip_cfg.gyro_fsr = 0xFF; st->chip_cfg.accel_fsr = 0xFF; st->chip_cfg.lpf = 0xFF; st->chip_cfg.sample_rate = 0xFFFF; st->chip_cfg.fifo_enable = 0xFF; st->chip_cfg.bypass_mode = 0xFF; #ifdef AK89xx_SECONDARY st->chip_cfg.compass_sample_rate = 0xFFFF; #endif /* mpu_set_sensors always preserves this setting. */ st->chip_cfg.clk_src = INV_CLK_PLL; /* Handled in next call to mpu_set_bypass. */ st->chip_cfg.active_low_int = 1; st->chip_cfg.latched_int = 0; st->chip_cfg.int_motion_only = 0; st->chip_cfg.lp_accel_mode = 0; memset(&st->chip_cfg.cache, 0, sizeof(st->chip_cfg.cache)); st->chip_cfg.dmp_on = 0; st->chip_cfg.dmp_loaded = 0; st->chip_cfg.dmp_sample_rate = 0; if (mpu_set_gyro_fsr(2000)) return -10; if (mpu_set_accel_fsr(2)) return -11; if (mpu_set_lpf(42)) return -12; if (mpu_set_sample_rate(50)) return -13; if (mpu_configure_fifo(0)) return -14; if (int_param) reg_int_cb(int_param); #ifdef AK89xx_SECONDARY #ifdef MPU_DEBUG Serial.println("Setting up compass"); #endif errCode = setup_compass(); if (errCode != 0) { #ifdef MPU_DEBUG Serial.print("Setup compass failed: "); Serial.println(errCode); #endif } if (mpu_set_compass_sample_rate(10)) return -15; #else /* Already disabled by setup_compass. */ if (mpu_set_bypass(0)) return -16; #endif mpu_set_sensors(0); return 0; } /** * @brief Enter low-power accel-only mode. * In low-power accel mode, the chip goes to sleep and only wakes up to sample * the accelerometer at one of the following frequencies: * \n MPU6050: 1.25Hz, 5Hz, 20Hz, 40Hz * \n MPU6500: 1.25Hz, 2.5Hz, 5Hz, 10Hz, 20Hz, 40Hz, 80Hz, 160Hz, 320Hz, 640Hz * \n If the requested rate is not one listed above, the device will be set to * the next highest rate. Requesting a rate above the maximum supported * frequency will result in an error. * \n To select a fractional wake-up frequency, round down the value passed to * @e rate. * @param[in] rate Minimum sampling rate, or zero to disable LP * accel mode. * @return 0 if successful. */ int mpu_lp_accel_mode(unsigned char rate) { unsigned char tmp[2]; if (rate > 40) return -1; if (!rate) { mpu_set_int_latched(0); tmp[0] = 0; tmp[1] = BIT_STBY_XYZG; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 2, tmp)) return -1; st->chip_cfg.lp_accel_mode = 0; return 0; } /* For LP accel, we automatically configure the hardware to produce latched * interrupts. In LP accel mode, the hardware cycles into sleep mode before * it gets a chance to deassert the interrupt pin; therefore, we shift this * responsibility over to the MCU. * * Any register read will clear the interrupt. */ mpu_set_int_latched(1); #if defined MPU6050 tmp[0] = BIT_LPA_CYCLE; if (rate == 1) { tmp[1] = INV_LPA_1_25HZ; mpu_set_lpf(5); } else if (rate <= 5) { tmp[1] = INV_LPA_5HZ; mpu_set_lpf(5); } else if (rate <= 20) { tmp[1] = INV_LPA_20HZ; mpu_set_lpf(10); } else { tmp[1] = INV_LPA_40HZ; mpu_set_lpf(20); } tmp[1] = (tmp[1] << 6) | BIT_STBY_XYZG; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 2, tmp)) return -1; #elif defined MPU6500 /* Set wake frequency. */ if (rate == 1) tmp[0] = INV_LPA_1_25HZ; else if (rate == 2) tmp[0] = INV_LPA_2_5HZ; else if (rate <= 5) tmp[0] = INV_LPA_5HZ; else if (rate <= 10) tmp[0] = INV_LPA_10HZ; else if (rate <= 20) tmp[0] = INV_LPA_20HZ; else if (rate <= 40) tmp[0] = INV_LPA_40HZ; else if (rate <= 80) tmp[0] = INV_LPA_80HZ; else if (rate <= 160) tmp[0] = INV_LPA_160HZ; else if (rate <= 320) tmp[0] = INV_LPA_320HZ; else tmp[0] = INV_LPA_640HZ; if (i2c_write(st->hw->addr, st->reg->lp_accel_odr, 1, tmp)) return -1; tmp[0] = BIT_LPA_CYCLE; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, tmp)) return -1; #endif st->chip_cfg.sensors = INV_XYZ_ACCEL; st->chip_cfg.clk_src = 0; st->chip_cfg.lp_accel_mode = 1; mpu_configure_fifo(0); return 0; } /** * @brief Read raw gyro data directly from the registers. * @param[out] data Raw data in hardware units. * @param[out] timestamp Timestamp in milliseconds. Null if not needed. * @return 0 if successful. */ int mpu_get_gyro_reg(short *data, unsigned long *timestamp) { unsigned char tmp[6]; if (!(st->chip_cfg.sensors & INV_XYZ_GYRO)) return -1; if (i2c_read(st->hw->addr, st->reg->raw_gyro, 6, tmp)) return -1; data[0] = (tmp[0] << 8) | tmp[1]; data[1] = (tmp[2] << 8) | tmp[3]; data[2] = (tmp[4] << 8) | tmp[5]; if (timestamp) get_ms(timestamp); return 0; } /** * @brief Read raw accel data directly from the registers. * @param[out] data Raw data in hardware units. * @param[out] timestamp Timestamp in milliseconds. Null if not needed. * @return 0 if successful. */ int mpu_get_accel_reg(short *data, unsigned long *timestamp) { unsigned char tmp[6]; if (!(st->chip_cfg.sensors & INV_XYZ_ACCEL)) return -1; if (i2c_read(st->hw->addr, st->reg->raw_accel, 6, tmp)) return -1; data[0] = (tmp[0] << 8) | tmp[1]; data[1] = (tmp[2] << 8) | tmp[3]; data[2] = (tmp[4] << 8) | tmp[5]; if (timestamp) get_ms(timestamp); return 0; } /** * @brief Read temperature data directly from the registers. * @param[out] data Data in q16 format. * @param[out] timestamp Timestamp in milliseconds. Null if not needed. * @return 0 if successful. */ int mpu_get_temperature(long *data, unsigned long *timestamp) { unsigned char tmp[2]; short raw; if (!(st->chip_cfg.sensors)) return -1; if (i2c_read(st->hw->addr, st->reg->temp, 2, tmp)) return -1; raw = (tmp[0] << 8) | tmp[1]; if (timestamp) get_ms(timestamp); data[0] = (long)((35 + ((raw - (float)st->hw->temp_offset) / st->hw->temp_sens)) * 65536L); return 0; } /** * @brief Push biases to the accel bias registers. * This function expects biases relative to the current sensor output, and * these biases will be added to the factory-supplied values. * @param[in] accel_bias New biases. * @return 0 if successful. */ int mpu_set_accel_bias(const long *accel_bias) { unsigned char data[6]; short accel_hw[3]; short got_accel[3]; short fg[3]; if (!accel_bias) return -1; if (!accel_bias[0] && !accel_bias[1] && !accel_bias[2]) return 0; if (i2c_read(st->hw->addr, 3, 3, data)) return -1; fg[0] = ((data[0] >> 4) + 8) & 0xf; fg[1] = ((data[1] >> 4) + 8) & 0xf; fg[2] = ((data[2] >> 4) + 8) & 0xf; accel_hw[0] = (short)(accel_bias[0] * 2 / (64 + fg[0])); accel_hw[1] = (short)(accel_bias[1] * 2 / (64 + fg[1])); accel_hw[2] = (short)(accel_bias[2] * 2 / (64 + fg[2])); if (i2c_read(st->hw->addr, 0x06, 6, data)) return -1; got_accel[0] = ((short)data[0] << 8) | data[1]; got_accel[1] = ((short)data[2] << 8) | data[3]; got_accel[2] = ((short)data[4] << 8) | data[5]; accel_hw[0] += got_accel[0]; accel_hw[1] += got_accel[1]; accel_hw[2] += got_accel[2]; data[0] = (accel_hw[0] >> 8) & 0xff; data[1] = (accel_hw[0]) & 0xff; data[2] = (accel_hw[1] >> 8) & 0xff; data[3] = (accel_hw[1]) & 0xff; data[4] = (accel_hw[2] >> 8) & 0xff; data[5] = (accel_hw[2]) & 0xff; if (i2c_write(st->hw->addr, 0x06, 6, data)) return -1; return 0; } /** * @brief Reset FIFO read/write pointers. * @return 0 if successful. */ int mpu_reset_fifo(void) { unsigned char data; if (!(st->chip_cfg.sensors)) return -1; data = 0; if (i2c_write(st->hw->addr, st->reg->int_enable, 1, &data)) return -1; if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, &data)) return -1; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &data)) return -1; if (st->chip_cfg.dmp_on) { data = BIT_FIFO_RST | BIT_DMP_RST; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &data)) return -1; delay_ms(50); data = BIT_DMP_EN | BIT_FIFO_EN; if (st->chip_cfg.sensors & INV_XYZ_COMPASS) data |= BIT_AUX_IF_EN; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &data)) return -1; if (st->chip_cfg.int_enable) data = BIT_DMP_INT_EN; else data = 0; if (i2c_write(st->hw->addr, st->reg->int_enable, 1, &data)) return -1; data = 0; if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, &data)) return -1; } else { data = BIT_FIFO_RST; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &data)) return -1; if (st->chip_cfg.bypass_mode || !(st->chip_cfg.sensors & INV_XYZ_COMPASS)) data = BIT_FIFO_EN; else data = BIT_FIFO_EN | BIT_AUX_IF_EN; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &data)) return -1; delay_ms(50); if (st->chip_cfg.int_enable) data = BIT_DATA_RDY_EN; else data = 0; if (i2c_write(st->hw->addr, st->reg->int_enable, 1, &data)) return -1; if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, &st->chip_cfg.fifo_enable)) return -1; } return 0; } /** * @brief Get the gyro full-scale range. * @param[out] fsr Current full-scale range. * @return 0 if successful. */ int mpu_get_gyro_fsr(unsigned short *fsr) { switch (st->chip_cfg.gyro_fsr) { case INV_FSR_250DPS: fsr[0] = 250; break; case INV_FSR_500DPS: fsr[0] = 500; break; case INV_FSR_1000DPS: fsr[0] = 1000; break; case INV_FSR_2000DPS: fsr[0] = 2000; break; default: fsr[0] = 0; break; } return 0; } /** * @brief Set the gyro full-scale range. * @param[in] fsr Desired full-scale range. * @return 0 if successful. */ int mpu_set_gyro_fsr(unsigned short fsr) { unsigned char data; if (!(st->chip_cfg.sensors)) return -1; switch (fsr) { case 250: data = INV_FSR_250DPS << 3; break; case 500: data = INV_FSR_500DPS << 3; break; case 1000: data = INV_FSR_1000DPS << 3; break; case 2000: data = INV_FSR_2000DPS << 3; break; default: return -1; } if (st->chip_cfg.gyro_fsr == (data >> 3)) return 0; if (i2c_write(st->hw->addr, st->reg->gyro_cfg, 1, &data)) return -1; st->chip_cfg.gyro_fsr = data >> 3; return 0; } /** * @brief Get the accel full-scale range. * @param[out] fsr Current full-scale range. * @return 0 if successful. */ int mpu_get_accel_fsr(unsigned char *fsr) { switch (st->chip_cfg.accel_fsr) { case INV_FSR_2G: fsr[0] = 2; break; case INV_FSR_4G: fsr[0] = 4; break; case INV_FSR_8G: fsr[0] = 8; break; case INV_FSR_16G: fsr[0] = 16; break; default: return -1; } if (st->chip_cfg.accel_half) fsr[0] <<= 1; return 0; } /** * @brief Set the accel full-scale range. * @param[in] fsr Desired full-scale range. * @return 0 if successful. */ int mpu_set_accel_fsr(unsigned char fsr) { unsigned char data; if (!(st->chip_cfg.sensors)) return -1; switch (fsr) { case 2: data = INV_FSR_2G << 3; break; case 4: data = INV_FSR_4G << 3; break; case 8: data = INV_FSR_8G << 3; break; case 16: data = INV_FSR_16G << 3; break; default: return -1; } if (st->chip_cfg.accel_fsr == (data >> 3)) return 0; if (i2c_write(st->hw->addr, st->reg->accel_cfg, 1, &data)) return -1; st->chip_cfg.accel_fsr = data >> 3; return 0; } /** * @brief Get the current DLPF setting. * @param[out] lpf Current LPF setting. * 0 if successful. */ int mpu_get_lpf(unsigned short *lpf) { switch (st->chip_cfg.lpf) { case INV_FILTER_188HZ: lpf[0] = 188; break; case INV_FILTER_98HZ: lpf[0] = 98; break; case INV_FILTER_42HZ: lpf[0] = 42; break; case INV_FILTER_20HZ: lpf[0] = 20; break; case INV_FILTER_10HZ: lpf[0] = 10; break; case INV_FILTER_5HZ: lpf[0] = 5; break; case INV_FILTER_256HZ_NOLPF2: case INV_FILTER_2100HZ_NOLPF: default: lpf[0] = 0; break; } return 0; } /** * @brief Set digital low pass filter. * The following LPF settings are supported: 188, 98, 42, 20, 10, 5. * @param[in] lpf Desired LPF setting. * @return 0 if successful. */ int mpu_set_lpf(unsigned short lpf) { unsigned char data; if (!(st->chip_cfg.sensors)) return -1; if (lpf >= 188) data = INV_FILTER_188HZ; else if (lpf >= 98) data = INV_FILTER_98HZ; else if (lpf >= 42) data = INV_FILTER_42HZ; else if (lpf >= 20) data = INV_FILTER_20HZ; else if (lpf >= 10) data = INV_FILTER_10HZ; else data = INV_FILTER_5HZ; if (st->chip_cfg.lpf == data) return 0; if (i2c_write(st->hw->addr, st->reg->lpf, 1, &data)) return -1; st->chip_cfg.lpf = data; return 0; } /** * @brief Get sampling rate. * @param[out] rate Current sampling rate (Hz). * @return 0 if successful. */ int mpu_get_sample_rate(unsigned short *rate) { if (st->chip_cfg.dmp_on) return -1; else rate[0] = st->chip_cfg.sample_rate; return 0; } /** * @brief Set sampling rate. * Sampling rate must be between 4Hz and 1kHz. * @param[in] rate Desired sampling rate (Hz). * @return 0 if successful. */ int mpu_set_sample_rate(unsigned short rate) { unsigned char data; if (!(st->chip_cfg.sensors)) return -1; if (st->chip_cfg.dmp_on) return -1; else { if (st->chip_cfg.lp_accel_mode) { if (rate && (rate <= 40)) { /* Just stay in low-power accel mode. */ mpu_lp_accel_mode(rate); return 0; } /* Requested rate exceeds the allowed frequencies in LP accel mode, * switch back to full-power mode. */ mpu_lp_accel_mode(0); } if (rate < 4) rate = 4; else if (rate > 1000) rate = 1000; data = 1000 / rate - 1; if (i2c_write(st->hw->addr, st->reg->rate_div, 1, &data)) return -1; st->chip_cfg.sample_rate = 1000 / (1 + data); #ifdef AK89xx_SECONDARY mpu_set_compass_sample_rate(min(st->chip_cfg.compass_sample_rate, MAX_COMPASS_SAMPLE_RATE)); #endif /* Automatically set LPF to 1/2 sampling rate. */ mpu_set_lpf(st->chip_cfg.sample_rate >> 1); return 0; } } /** * @brief Get compass sampling rate. * @param[out] rate Current compass sampling rate (Hz). * @return 0 if successful. */ int mpu_get_compass_sample_rate(unsigned short *rate) { #ifdef AK89xx_SECONDARY rate[0] = st->chip_cfg.compass_sample_rate; return 0; #else rate[0] = 0; return -1; #endif } /** * @brief Set compass sampling rate. * The compass on the auxiliary I2C bus is read by the MPU hardware at a * maximum of 100Hz. The actual rate can be set to a fraction of the gyro * sampling rate. * * \n WARNING: The new rate may be different than what was requested. Call * mpu_get_compass_sample_rate to check the actual setting. * @param[in] rate Desired compass sampling rate (Hz). * @return 0 if successful. */ int mpu_set_compass_sample_rate(unsigned short rate) { #ifdef AK89xx_SECONDARY unsigned char div; if (!rate || rate > st->chip_cfg.sample_rate || rate > MAX_COMPASS_SAMPLE_RATE) return -1; div = st->chip_cfg.sample_rate / rate - 1; if (i2c_write(st->hw->addr, st->reg->s4_ctrl, 1, &div)) return -1; st->chip_cfg.compass_sample_rate = st->chip_cfg.sample_rate / (div + 1); return 0; #else return -1; #endif } /** * @brief Get gyro sensitivity scale factor. * @param[out] sens Conversion from hardware units to dps. * @return 0 if successful. */ int mpu_get_gyro_sens(float *sens) { switch (st->chip_cfg.gyro_fsr) { case INV_FSR_250DPS: sens[0] = 131.f; break; case INV_FSR_500DPS: sens[0] = 65.5f; break; case INV_FSR_1000DPS: sens[0] = 32.8f; break; case INV_FSR_2000DPS: sens[0] = 16.4f; break; default: return -1; } return 0; } /** * @brief Get accel sensitivity scale factor. * @param[out] sens Conversion from hardware units to g's. * @return 0 if successful. */ int mpu_get_accel_sens(unsigned short *sens) { switch (st->chip_cfg.accel_fsr) { case INV_FSR_2G: sens[0] = 16384; break; case INV_FSR_4G: sens[0] = 8092; break; case INV_FSR_8G: sens[0] = 4096; break; case INV_FSR_16G: sens[0] = 2048; break; default: return -1; } if (st->chip_cfg.accel_half) sens[0] >>= 1; return 0; } /** * @brief Get current FIFO configuration. * @e sensors can contain a combination of the following flags: * \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO * \n INV_XYZ_GYRO * \n INV_XYZ_ACCEL * @param[out] sensors Mask of sensors in FIFO. * @return 0 if successful. */ int mpu_get_fifo_config(unsigned char *sensors) { sensors[0] = st->chip_cfg.fifo_enable; return 0; } /** * @brief Select which sensors are pushed to FIFO. * @e sensors can contain a combination of the following flags: * \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO * \n INV_XYZ_GYRO * \n INV_XYZ_ACCEL * @param[in] sensors Mask of sensors to push to FIFO. * @return 0 if successful. */ int mpu_configure_fifo(unsigned char sensors) { unsigned char prev; int result = 0; /* Compass data isn't going into the FIFO. Stop trying. */ sensors &= ~INV_XYZ_COMPASS; if (st->chip_cfg.dmp_on) return 0; else { if (!(st->chip_cfg.sensors)) return -1; prev = st->chip_cfg.fifo_enable; st->chip_cfg.fifo_enable = sensors & st->chip_cfg.sensors; if (st->chip_cfg.fifo_enable != sensors) /* You're not getting what you asked for. Some sensors are * asleep. */ result = -1; else result = 0; if (sensors || st->chip_cfg.lp_accel_mode) set_int_enable(1); else set_int_enable(0); if (sensors) { if (mpu_reset_fifo()) { st->chip_cfg.fifo_enable = prev; return -1; } } } return result; } /** * @brief Get current power state. * @param[in] power_on 1 if turned on, 0 if suspended. * @return 0 if successful. */ int mpu_get_power_state(unsigned char *power_on) { if (st->chip_cfg.sensors) power_on[0] = 1; else power_on[0] = 0; return 0; } /** * @brief Turn specific sensors on/off. * @e sensors can contain a combination of the following flags: * \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO * \n INV_XYZ_GYRO * \n INV_XYZ_ACCEL * \n INV_XYZ_COMPASS * @param[in] sensors Mask of sensors to wake. * @return 0 if successful. */ int mpu_set_sensors(unsigned char sensors) { unsigned char data; #ifdef AK89xx_SECONDARY unsigned char user_ctrl; #endif if (sensors & INV_XYZ_GYRO) data = INV_CLK_PLL; else if (sensors) data = 0; else data = BIT_SLEEP; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, &data)) { st->chip_cfg.sensors = 0; return -1; } st->chip_cfg.clk_src = data & ~BIT_SLEEP; data = 0; if (!(sensors & INV_X_GYRO)) data |= BIT_STBY_XG; if (!(sensors & INV_Y_GYRO)) data |= BIT_STBY_YG; if (!(sensors & INV_Z_GYRO)) data |= BIT_STBY_ZG; if (!(sensors & INV_XYZ_ACCEL)) data |= BIT_STBY_XYZA; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_2, 1, &data)) { st->chip_cfg.sensors = 0; return -1; } if (sensors && (sensors != INV_XYZ_ACCEL)) /* Latched interrupts only used in LP accel mode. */ mpu_set_int_latched(0); #ifdef AK89xx_SECONDARY #ifdef AK89xx_BYPASS if (sensors & INV_XYZ_COMPASS) mpu_set_bypass(1); else mpu_set_bypass(0); #else if (i2c_read(st->hw->addr, st->reg->user_ctrl, 1, &user_ctrl)) return -1; /* Handle AKM power management. */ if (sensors & INV_XYZ_COMPASS) { data = AKM_SINGLE_MEASUREMENT; user_ctrl |= BIT_AUX_IF_EN; } else { data = AKM_POWER_DOWN; user_ctrl &= ~BIT_AUX_IF_EN; } if (st->chip_cfg.dmp_on) user_ctrl |= BIT_DMP_EN; else user_ctrl &= ~BIT_DMP_EN; if (i2c_write(st->hw->addr, st->reg->s1_do, 1, &data)) return -1; /* Enable/disable I2C master mode. */ if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &user_ctrl)) return -1; #endif #endif st->chip_cfg.sensors = sensors; st->chip_cfg.lp_accel_mode = 0; delay_ms(50); return 0; } /** * @brief Read the MPU interrupt status registers. * @param[out] status Mask of interrupt bits. * @return 0 if successful. */ int mpu_get_int_status(short *status) { unsigned char tmp[2]; if (!st->chip_cfg.sensors) return -1; if (i2c_read(st->hw->addr, st->reg->dmp_int_status, 2, tmp)) return -1; status[0] = (tmp[0] << 8) | tmp[1]; return 0; } /** * @brief Get one packet from the FIFO. * If @e sensors does not contain a particular sensor, disregard the data * returned to that pointer. * \n @e sensors can contain a combination of the following flags: * \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO * \n INV_XYZ_GYRO * \n INV_XYZ_ACCEL * \n If the FIFO has no new data, @e sensors will be zero. * \n If the FIFO is disabled, @e sensors will be zero and this function will * return a non-zero error code. * @param[out] gyro Gyro data in hardware units. * @param[out] accel Accel data in hardware units. * @param[out] timestamp Timestamp in milliseconds. * @param[out] sensors Mask of sensors read from FIFO. * @param[out] more Number of remaining packets. * @return 0 if successful. */ int mpu_read_fifo(short *gyro, short *accel, unsigned long *timestamp, unsigned char *sensors, unsigned char *more) { /* Assumes maximum packet size is gyro (6) + accel (6). */ unsigned char data[MAX_PACKET_LENGTH]; unsigned char packet_size = 0; unsigned short fifo_count, index = 0; if (st->chip_cfg.dmp_on) return -1; sensors[0] = 0; if (!st->chip_cfg.sensors) return -2; if (!st->chip_cfg.fifo_enable) return -3; if (st->chip_cfg.fifo_enable & INV_X_GYRO) packet_size += 2; if (st->chip_cfg.fifo_enable & INV_Y_GYRO) packet_size += 2; if (st->chip_cfg.fifo_enable & INV_Z_GYRO) packet_size += 2; if (st->chip_cfg.fifo_enable & INV_XYZ_ACCEL) packet_size += 6; if (i2c_read(st->hw->addr, st->reg->fifo_count_h, 2, data)) return -4; if (fifo_count < packet_size) return 1; // log_i("FIFO count: %hd\n", fifo_count); if (fifo_count > (st->hw->max_fifo >> 1)) { /* FIFO is 50% full, better check overflow bit. */ if (i2c_read(st->hw->addr, st->reg->int_status, 1, data)) return -5; if (data[0] & BIT_FIFO_OVERFLOW) { mpu_reset_fifo(); return 2; } } if (timestamp) get_ms((unsigned long*)timestamp); if (i2c_read(st->hw->addr, st->reg->fifo_r_w, packet_size, data)) return -7; more[0] = fifo_count / packet_size - 1; sensors[0] = 0; if ((index != packet_size) && st->chip_cfg.fifo_enable & INV_XYZ_ACCEL) { accel[0] = (data[index+0] << 8) | data[index+1]; accel[1] = (data[index+2] << 8) | data[index+3]; accel[2] = (data[index+4] << 8) | data[index+5]; sensors[0] |= INV_XYZ_ACCEL; index += 6; } if ((index != packet_size) && st->chip_cfg.fifo_enable & INV_X_GYRO) { gyro[0] = (data[index+0] << 8) | data[index+1]; sensors[0] |= INV_X_GYRO; index += 2; } if ((index != packet_size) && st->chip_cfg.fifo_enable & INV_Y_GYRO) { gyro[1] = (data[index+0] << 8) | data[index+1]; sensors[0] |= INV_Y_GYRO; index += 2; } if ((index != packet_size) && st->chip_cfg.fifo_enable & INV_Z_GYRO) { gyro[2] = (data[index+0] << 8) | data[index+1]; sensors[0] |= INV_Z_GYRO; index += 2; } return 0; } /** * @brief Get one unparsed packet from the FIFO. * This function should be used if the packet is to be parsed elsewhere. * @param[in] length Length of one FIFO packet. * @param[in] data FIFO packet. * @param[in] more Number of remaining packets. */ int mpu_read_fifo_stream(unsigned short length, unsigned char *data, unsigned char *more) { unsigned char tmp[2]; unsigned short fifo_count; if (!st->chip_cfg.dmp_on) return -1; if (!st->chip_cfg.sensors) return -2; if (i2c_read(st->hw->addr, st->reg->fifo_count_h, 2, tmp)) return -3; fifo_count = (tmp[0] << 8) | tmp[1]; if (fifo_count < length) { more[0] = 0; return 1; } if (fifo_count > (st->hw->max_fifo >> 1)) { /* FIFO is 50% full, better check overflow bit. */ if (i2c_read(st->hw->addr, st->reg->int_status, 1, tmp)) return -5; if (tmp[0] & BIT_FIFO_OVERFLOW) { mpu_reset_fifo(); return 2; } } if (i2c_read(st->hw->addr, st->reg->fifo_r_w, length, data)) return -7; more[0] = fifo_count / length - 1; return 0; } /** * @brief Set device to bypass mode. * @param[in] bypass_on 1 to enable bypass mode. * @return 0 if successful. */ int mpu_set_bypass(unsigned char bypass_on) { unsigned char tmp; if (st->chip_cfg.bypass_mode == bypass_on) return 0; if (bypass_on) { if (i2c_read(st->hw->addr, st->reg->user_ctrl, 1, &tmp)) return -1; tmp &= ~BIT_AUX_IF_EN; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &tmp)) return -1; delay_ms(3); tmp = BIT_BYPASS_EN; if (st->chip_cfg.active_low_int) tmp |= BIT_ACTL; if (st->chip_cfg.latched_int) tmp |= BIT_LATCH_EN | BIT_ANY_RD_CLR; if (i2c_write(st->hw->addr, st->reg->int_pin_cfg, 1, &tmp)) return -1; } else { /* Enable I2C master mode if compass is being used. */ if (i2c_read(st->hw->addr, st->reg->user_ctrl, 1, &tmp)) return -1; if (st->chip_cfg.sensors & INV_XYZ_COMPASS) tmp |= BIT_AUX_IF_EN; else tmp &= ~BIT_AUX_IF_EN; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &tmp)) return -1; delay_ms(3); if (st->chip_cfg.active_low_int) tmp = BIT_ACTL; else tmp = 0; if (st->chip_cfg.latched_int) tmp |= BIT_LATCH_EN | BIT_ANY_RD_CLR; if (i2c_write(st->hw->addr, st->reg->int_pin_cfg, 1, &tmp)) return -1; } st->chip_cfg.bypass_mode = bypass_on; return 0; } /** * @brief Set interrupt level. * @param[in] active_low 1 for active low, 0 for active high. * @return 0 if successful. */ int mpu_set_int_level(unsigned char active_low) { st->chip_cfg.active_low_int = active_low; return 0; } /** * @brief Enable latched interrupts. * Any MPU register will clear the interrupt. * @param[in] enable 1 to enable, 0 to disable. * @return 0 if successful. */ int mpu_set_int_latched(unsigned char enable) { unsigned char tmp; if (st->chip_cfg.latched_int == enable) return 0; if (enable) tmp = BIT_LATCH_EN | BIT_ANY_RD_CLR; else tmp = 0; if (st->chip_cfg.bypass_mode) tmp |= BIT_BYPASS_EN; if (st->chip_cfg.active_low_int) tmp |= BIT_ACTL; if (i2c_write(st->hw->addr, st->reg->int_pin_cfg, 1, &tmp)) return -1; st->chip_cfg.latched_int = enable; return 0; } #ifdef MPU_MAXIMAL #ifdef MPU6050 static int get_accel_prod_shift(float *st_shift) { unsigned char tmp[4], shift_code[3], ii; if (i2c_read(st->hw->addr, 0x0D, 4, tmp)) return 0x07; shift_code[0] = ((tmp[0] & 0xE0) >> 3) | ((tmp[3] & 0x30) >> 4); shift_code[1] = ((tmp[1] & 0xE0) >> 3) | ((tmp[3] & 0x0C) >> 2); shift_code[2] = ((tmp[2] & 0xE0) >> 3) | (tmp[3] & 0x03); for (ii = 0; ii < 3; ii++) { if (!shift_code[ii]) { st_shift[ii] = 0.f; continue; } /* Equivalent to.. * st_shift[ii] = 0.34f * powf(0.92f/0.34f, (shift_code[ii]-1) / 30.f) */ st_shift[ii] = 0.34f; while (--shift_code[ii]) st_shift[ii] *= 1.034f; } return 0; } static int accel_self_test(long *bias_regular, long *bias_st) { int jj, result = 0; float st_shift[3], st_shift_cust, st_shift_var; get_accel_prod_shift(st_shift); for(jj = 0; jj < 3; jj++) { st_shift_cust = labs(bias_regular[jj] - bias_st[jj]) / 65536.f; if (st_shift[jj]) { st_shift_var = st_shift_cust / st_shift[jj] - 1.f; if (fabs(st_shift_var) > test->max_accel_var) result |= 1 << jj; } else if ((st_shift_cust < test->min_g) || (st_shift_cust > test->max_g)) result |= 1 << jj; } return result; } static int gyro_self_test(long *bias_regular, long *bias_st) { int jj, result = 0; unsigned char tmp[3]; float st_shift, st_shift_cust, st_shift_var; if (i2c_read(st->hw->addr, 0x0D, 3, tmp)) return 0x07; tmp[0] &= 0x1F; tmp[1] &= 0x1F; tmp[2] &= 0x1F; for (jj = 0; jj < 3; jj++) { st_shift_cust = labs(bias_regular[jj] - bias_st[jj]) / 65536.f; if (tmp[jj]) { st_shift = 3275.f / test->gyro_sens; while (--tmp[jj]) st_shift *= 1.046f; st_shift_var = st_shift_cust / st_shift - 1.f; if (fabs(st_shift_var) > test->max_gyro_var) result |= 1 << jj; } else if ((st_shift_cust < test->min_dps) || (st_shift_cust > test->max_dps)) result |= 1 << jj; } return result; } #ifdef AK89xx_SECONDARY static int compass_self_test(void) { unsigned char tmp[6]; unsigned char tries = 10; int result = 0x07; short data; mpu_set_bypass(1); tmp[0] = AKM_POWER_DOWN; if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp)) return 0x07; tmp[0] = AKM_BIT_SELF_TEST; if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_ASTC, 1, tmp)) goto AKM_restore; tmp[0] = AKM_MODE_SELF_TEST; if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp)) goto AKM_restore; do { delay_ms(10); if (i2c_read(st->chip_cfg.compass_addr, AKM_REG_ST1, 1, tmp)) goto AKM_restore; if (tmp[0] & AKM_DATA_READY) break; } while (tries--); if (!(tmp[0] & AKM_DATA_READY)) goto AKM_restore; if (i2c_read(st->chip_cfg.compass_addr, AKM_REG_HXL, 6, tmp)) goto AKM_restore; result = 0; data = (short)(tmp[1] << 8) | tmp[0]; if ((data > 100) || (data < -100)) result |= 0x01; data = (short)(tmp[3] << 8) | tmp[2]; if ((data > 100) || (data < -100)) result |= 0x02; data = (short)(tmp[5] << 8) | tmp[4]; if ((data > -300) || (data < -1000)) result |= 0x04; AKM_restore: tmp[0] = 0 | SUPPORTS_AK89xx_HIGH_SENS; i2c_write(st->chip_cfg.compass_addr, AKM_REG_ASTC, 1, tmp); tmp[0] = SUPPORTS_AK89xx_HIGH_SENS; i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp); mpu_set_bypass(0); return result; } #endif #endif static int get_st_biases(long *gyro, long *accel, unsigned char hw_test) { unsigned char data[MAX_PACKET_LENGTH]; unsigned char packet_count, ii; unsigned short fifo_count; data[0] = 0x01; data[1] = 0; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 2, data)) return -1; delay_ms(200); data[0] = 0; if (i2c_write(st->hw->addr, st->reg->int_enable, 1, data)) return -1; if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, data)) return -1; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, data)) return -1; if (i2c_write(st->hw->addr, st->reg->i2c_mst, 1, data)) return -1; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, data)) return -1; data[0] = BIT_FIFO_RST | BIT_DMP_RST; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, data)) return -1; delay_ms(15); data[0] = st->test->reg_lpf; if (i2c_write(st->hw->addr, st->reg->lpf, 1, data)) return -1; data[0] = st->test->reg_rate_div; if (i2c_write(st->hw->addr, st->reg->rate_div, 1, data)) return -1; if (hw_test) data[0] = st->test->reg_gyro_fsr | 0xE0; else data[0] = st->test->reg_gyro_fsr; if (i2c_write(st->hw->addr, st->reg->gyro_cfg, 1, data)) return -1; if (hw_test) data[0] = st->test->reg_accel_fsr | 0xE0; else data[0] = test->reg_accel_fsr; if (i2c_write(st->hw->addr, st->reg->accel_cfg, 1, data)) return -1; if (hw_test) delay_ms(200); /* Fill FIFO for test->wait_ms milliseconds. */ data[0] = BIT_FIFO_EN; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, data)) return -1; data[0] = INV_XYZ_GYRO | INV_XYZ_ACCEL; if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, data)) return -1; delay_ms(test->wait_ms); data[0] = 0; if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, data)) return -1; if (i2c_read(st->hw->addr, st->reg->fifo_count_h, 2, data)) return -1; fifo_count = (data[0] << 8) | data[1]; packet_count = fifo_count / MAX_PACKET_LENGTH; gyro[0] = gyro[1] = gyro[2] = 0; accel[0] = accel[1] = accel[2] = 0; for (ii = 0; ii < packet_count; ii++) { short accel_cur[3], gyro_cur[3]; if (i2c_read(st->hw->addr, st->reg->fifo_r_w, MAX_PACKET_LENGTH, data)) return -1; accel_cur[0] = ((short)data[0] << 8) | data[1]; accel_cur[1] = ((short)data[2] << 8) | data[3]; accel_cur[2] = ((short)data[4] << 8) | data[5]; accel[0] += (long)accel_cur[0]; accel[1] += (long)accel_cur[1]; accel[2] += (long)accel_cur[2]; gyro_cur[0] = (((short)data[6] << 8) | data[7]); gyro_cur[1] = (((short)data[8] << 8) | data[9]); gyro_cur[2] = (((short)data[10] << 8) | data[11]); gyro[0] += (long)gyro_cur[0]; gyro[1] += (long)gyro_cur[1]; gyro[2] += (long)gyro_cur[2]; } #ifdef EMPL_NO_64BIT gyro[0] = (long)(((float)gyro[0]*65536.f) / test->gyro_sens / packet_count); gyro[1] = (long)(((float)gyro[1]*65536.f) / test->gyro_sens / packet_count); gyro[2] = (long)(((float)gyro[2]*65536.f) / test->gyro_sens / packet_count); if (has_accel) { accel[0] = (long)(((float)accel[0]*65536.f) / test->accel_sens / packet_count); accel[1] = (long)(((float)accel[1]*65536.f) / test->accel_sens / packet_count); accel[2] = (long)(((float)accel[2]*65536.f) / test->accel_sens / packet_count); /* Don't remove gravity! */ accel[2] -= 65536L; } #else gyro[0] = (long)(((long long)gyro[0]<<16) / test->gyro_sens / packet_count); gyro[1] = (long)(((long long)gyro[1]<<16) / test->gyro_sens / packet_count); gyro[2] = (long)(((long long)gyro[2]<<16) / test->gyro_sens / packet_count); accel[0] = (long)(((long long)accel[0]<<16) / test->accel_sens / packet_count); accel[1] = (long)(((long long)accel[1]<<16) / test->accel_sens / packet_count); accel[2] = (long)(((long long)accel[2]<<16) / test->accel_sens / packet_count); /* Don't remove gravity! */ if (accel[2] > 0L) accel[2] -= 65536L; else accel[2] += 65536L; #endif return 0; } /** * @brief Trigger gyro/accel/compass self-test-> * On success/error, the self-test returns a mask representing the sensor(s) * that failed. For each bit, a one (1) represents a "pass" case; conversely, * a zero (0) indicates a failure. * * \n The mask is defined as follows: * \n Bit 0: Gyro. * \n Bit 1: Accel. * \n Bit 2: Compass. * * \n Currently, the hardware self-test is unsupported for MPU6500. However, * this function can still be used to obtain the accel and gyro biases. * * \n This function must be called with the device either face-up or face-down * (z-axis is parallel to gravity). * @param[out] gyro Gyro biases in q16 format. * @param[out] accel Accel biases (if applicable) in q16 format. * @return Result mask (see above). */ int mpu_run_self_test(long *gyro, long *accel) { #ifdef MPU6050 const unsigned char tries = 2; long gyro_st[3], accel_st[3]; unsigned char accel_result, gyro_result; #ifdef AK89xx_SECONDARY unsigned char compass_result; #endif int ii; #endif int result; unsigned char accel_fsr, fifo_sensors, sensors_on; unsigned short gyro_fsr, sample_rate, lpf; unsigned char dmp_was_on; if (st->chip_cfg.dmp_on) { mpu_set_dmp_state(0); dmp_was_on = 1; } else dmp_was_on = 0; /* Get initial settings. */ mpu_get_gyro_fsr(&gyro_fsr); mpu_get_accel_fsr(&accel_fsr); mpu_get_lpf(&lpf); mpu_get_sample_rate(&sample_rate); sensors_on = st->chip_cfg.sensors; mpu_get_fifo_config(&fifo_sensors); /* For older chips, the self-test will be different. */ #if defined MPU6050 for (ii = 0; ii < tries; ii++) if (!get_st_biases(gyro, accel, 0)) break; if (ii == tries) { /* If we reach this point, we most likely encountered an I2C error. * We'll just report an error for all three sensors. */ result = 0; goto restore; } for (ii = 0; ii < tries; ii++) if (!get_st_biases(gyro_st, accel_st, 1)) break; if (ii == tries) { /* Again, probably an I2C error. */ result = 0; goto restore; } accel_result = accel_self_test(accel, accel_st); gyro_result = gyro_self_test(gyro, gyro_st); result = 0; if (!gyro_result) result |= 0x01; if (!accel_result) result |= 0x02; #ifdef AK89xx_SECONDARY compass_result = compass_self_test(); if (!compass_result) result |= 0x04; #endif restore: #elif defined MPU6500 /* For now, this function will return a "pass" result for all three sensors * for compatibility with current test applications. */ get_st_biases(gyro, accel, 0); result = 0x7; #endif /* Set to invalid values to ensure no I2C writes are skipped. */ st->chip_cfg.gyro_fsr = 0xFF; st->chip_cfg.accel_fsr = 0xFF; st->chip_cfg.lpf = 0xFF; st->chip_cfg.sample_rate = 0xFFFF; st->chip_cfg.sensors = 0xFF; st->chip_cfg.fifo_enable = 0xFF; st->chip_cfg.clk_src = INV_CLK_PLL; mpu_set_gyro_fsr(gyro_fsr); mpu_set_accel_fsr(accel_fsr); mpu_set_lpf(lpf); mpu_set_sample_rate(sample_rate); mpu_set_sensors(sensors_on); mpu_configure_fifo(fifo_sensors); if (dmp_was_on) mpu_set_dmp_state(1); return result; } #endif // MPU_MAXIMAL /** * @brief Write to the DMP memory. * This function prevents I2C writes past the bank boundaries. The DMP memory * is only accessible when the chip is awake. * @param[in] mem_addr Memory location (bank << 8 | start address) * @param[in] length Number of bytes to write. * @param[in] data Bytes to write to memory. * @return 0 if successful. */ int mpu_write_mem(unsigned short mem_addr, unsigned short length, unsigned char *data) { unsigned char tmp[2]; if (!data) return -1; if (!st->chip_cfg.sensors) return -2; tmp[0] = (unsigned char)(mem_addr >> 8); tmp[1] = (unsigned char)(mem_addr & 0xFF); /* Check bank boundaries. */ if (tmp[1] + length > st->hw->bank_size) return -3; if (i2c_write(st->hw->addr, st->reg->bank_sel, 2, tmp)) return -4; if (i2c_write(st->hw->addr, st->reg->mem_r_w, length, data)) return -5; return 0; } /** * @brief Read from the DMP memory. * This function prevents I2C reads past the bank boundaries. The DMP memory * is only accessible when the chip is awake. * @param[in] mem_addr Memory location (bank << 8 | start address) * @param[in] length Number of bytes to read. * @param[out] data Bytes read from memory. * @return 0 if successful. */ int mpu_read_mem(unsigned short mem_addr, unsigned short length, unsigned char *data) { unsigned char tmp[2]; if (!data) return -1; if (!st->chip_cfg.sensors) return -1; tmp[0] = (unsigned char)(mem_addr >> 8); tmp[1] = (unsigned char)(mem_addr & 0xFF); /* Check bank boundaries. */ if (tmp[1] + length > st->hw->bank_size) return -1; if (i2c_write(st->hw->addr, st->reg->bank_sel, 2, tmp)) return -1; if (i2c_read(st->hw->addr, st->reg->mem_r_w, length, data)) return -1; return 0; } /** * @brief Load and verify DMP image. * @param[in] length Length of DMP image. * @param[in] firmware DMP code. * @param[in] start_addr Starting address of DMP code memory. * @param[in] sample_rate Fixed sampling rate used when DMP is enabled. * @return 0 if successful. */ int mpu_load_firmware(unsigned short length, const unsigned char *firmware, unsigned short start_addr, unsigned short sample_rate) { unsigned short ii; unsigned short this_write; int errCode; uint8_t *progBuffer; /* Must divide evenly into st->hw->bank_size to avoid bank crossings. */ #define LOAD_CHUNK (16) unsigned char cur[LOAD_CHUNK], tmp[2]; if (st->chip_cfg.dmp_loaded) /* DMP should only be loaded once. */ return -1; if (!firmware) return -2; progBuffer = (uint8_t *)malloc(LOAD_CHUNK); for (ii = 0; ii < length; ii += this_write) { this_write = min(LOAD_CHUNK, length - ii); for (int progIndex = 0; progIndex < this_write; progIndex++) #ifdef __SAM3X8E__ progBuffer[progIndex] = firmware[ii + progIndex]; #else progBuffer[progIndex] = pgm_read_byte(firmware + ii + progIndex); #endif if ((errCode = mpu_write_mem(ii, this_write, progBuffer))) { #ifdef MPU_DEBUG Serial.print("fimrware write failed: "); Serial.println(errCode); #endif return -3; } if (mpu_read_mem(ii, this_write, cur)) return -4; if (memcmp(progBuffer, cur, this_write)) { #ifdef MPU_DEBUG Serial.print("Firmware compare failed addr "); Serial.println(ii); for (int i = 0; i < 10; i++) { Serial.print(progBuffer[i]); Serial.print(" "); } Serial.println(); for (int i = 0; i < 10; i++) { Serial.print(cur[i]); Serial.print(" "); } Serial.println(); #endif return -5; } } /* Set program start address. */ tmp[0] = start_addr >> 8; tmp[1] = start_addr & 0xFF; if (i2c_write(st->hw->addr, st->reg->prgm_start_h, 2, tmp)) return -6; st->chip_cfg.dmp_loaded = 1; st->chip_cfg.dmp_sample_rate = sample_rate; #ifdef MPU_DEBUG Serial.println("Firmware loaded"); #endif return 0; } /** * @brief Enable/disable DMP support. * @param[in] enable 1 to turn on the DMP. * @return 0 if successful. */ int mpu_set_dmp_state(unsigned char enable) { unsigned char tmp; if (st->chip_cfg.dmp_on == enable) return 0; if (enable) { if (!st->chip_cfg.dmp_loaded) return -1; /* Disable data ready interrupt. */ set_int_enable(0); /* Disable bypass mode. */ mpu_set_bypass(0); /* Keep constant sample rate, FIFO rate controlled by DMP. */ mpu_set_sample_rate(st->chip_cfg.dmp_sample_rate); /* Remove FIFO elements. */ tmp = 0; i2c_write(st->hw->addr, 0x23, 1, &tmp); st->chip_cfg.dmp_on = 1; /* Enable DMP interrupt. */ set_int_enable(1); mpu_reset_fifo(); } else { /* Disable DMP interrupt. */ set_int_enable(0); /* Restore FIFO settings. */ tmp = st->chip_cfg.fifo_enable; i2c_write(st->hw->addr, 0x23, 1, &tmp); st->chip_cfg.dmp_on = 0; mpu_reset_fifo(); } return 0; } /** * @brief Get DMP state. * @param[out] enabled 1 if enabled. * @return 0 if successful. */ int mpu_get_dmp_state(unsigned char *enabled) { enabled[0] = st->chip_cfg.dmp_on; return 0; } /* This initialization is similar to the one in ak8975.c. */ static int setup_compass(void) { #ifdef AK89xx_SECONDARY unsigned char data[4], akm_addr; mpu_set_bypass(1); /* Find compass. Possible addresses range from 0x0C to 0x0F. */ for (akm_addr = 0x0C; akm_addr <= 0x0F; akm_addr++) { int result; result = i2c_read(akm_addr, AKM_REG_WHOAMI, 1, data); if (!result && (data[0] == AKM_WHOAMI)) break; } if (akm_addr > 0x0F) { /* TODO: Handle this case in all compass-related functions. */ #ifdef MPU_DEBUG Serial.println("Compass not found."); #endif return -1; } st->chip_cfg.compass_addr = akm_addr; data[0] = AKM_POWER_DOWN; if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, data)) return -2; delay_ms(1); data[0] = AKM_FUSE_ROM_ACCESS; if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, data)) return -3; delay_ms(1); /* Get sensitivity adjustment data from fuse ROM. */ if (i2c_read(st->chip_cfg.compass_addr, AKM_REG_ASAX, 3, data)) return -4; st->chip_cfg.mag_sens_adj[0] = (long)data[0] + 128; st->chip_cfg.mag_sens_adj[1] = (long)data[1] + 128; st->chip_cfg.mag_sens_adj[2] = (long)data[2] + 128; #ifdef MPU_DEBUG Serial.print("Compass sens: "); Serial.print(st->chip_cfg.mag_sens_adj[0]); Serial.print(" "); Serial.print(st->chip_cfg.mag_sens_adj[1]); Serial.print(" "); Serial.print(st->chip_cfg.mag_sens_adj[2]); Serial.println(); #endif data[0] = AKM_POWER_DOWN; if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, data)) return -5; delay_ms(1); mpu_set_bypass(0); /* Set up master mode, master clock, and ES bit. */ data[0] = 0x40; if (i2c_write(st->hw->addr, st->reg->i2c_mst, 1, data)) return -6; /* Slave 0 reads from AKM data registers. */ data[0] = BIT_I2C_READ | st->chip_cfg.compass_addr; if (i2c_write(st->hw->addr, st->reg->s0_addr, 1, data)) return -7; /* Compass reads start at this register. */ data[0] = AKM_REG_ST1; if (i2c_write(st->hw->addr, st->reg->s0_reg, 1, data)) return -8; /* Enable slave 0, 8-byte reads. */ data[0] = BIT_SLAVE_EN | 8; if (i2c_write(st->hw->addr, st->reg->s0_ctrl, 1, data)) return -9; /* Slave 1 changes AKM measurement mode. */ data[0] = st->chip_cfg.compass_addr; if (i2c_write(st->hw->addr, st->reg->s1_addr, 1, data)) return -10; /* AKM measurement mode register. */ data[0] = AKM_REG_CNTL; if (i2c_write(st->hw->addr, st->reg->s1_reg, 1, data)) return -11; /* Enable slave 1, 1-byte writes. */ data[0] = BIT_SLAVE_EN | 1; if (i2c_write(st->hw->addr, st->reg->s1_ctrl, 1, data)) return -12; /* Set slave 1 data. */ data[0] = AKM_SINGLE_MEASUREMENT; if (i2c_write(st->hw->addr, st->reg->s1_do, 1, data)) return -13; /* Trigger slave 0 and slave 1 actions at each sample. */ data[0] = 0x03; if (i2c_write(st->hw->addr, st->reg->i2c_delay_ctrl, 1, data)) return -14; #ifdef MPU9150 /* For the MPU9150, the auxiliary I2C bus needs to be set to VDD. */ data[0] = BIT_I2C_MST_VDDIO; if (i2c_write(st->hw->addr, st->reg->yg_offs_tc, 1, data)) return -15; #endif return 0; #else return -16; #endif } /** * @brief Read raw compass data. * @param[out] data Raw data in hardware units. * @param[out] timestamp Timestamp in milliseconds. Null if not needed. * @return 0 if successful. */ int mpu_get_compass_reg(short *data, unsigned long *timestamp) { #ifdef AK89xx_SECONDARY unsigned char tmp[9]; if (!(st->chip_cfg.sensors & INV_XYZ_COMPASS)) return -1; #ifdef AK89xx_BYPASS if (i2c_read(st->chip_cfg.compass_addr, AKM_REG_ST1, 8, tmp)) return -2; tmp[8] = AKM_SINGLE_MEASUREMENT; if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp+8)) return -3; #else if (i2c_read(st->hw->addr, st->reg->raw_compass, 8, tmp)) return -4; #endif #if defined AK8975_SECONDARY /* AK8975 doesn't have the overrun error bit. */ if (!(tmp[0] & AKM_DATA_READY)) return -5; if ((tmp[7] & AKM_OVERFLOW) || (tmp[7] & AKM_DATA_ERROR)) return -6; #elif defined AK8963_SECONDARY /* AK8963 doesn't have the data read error bit. */ if (!(tmp[0] & AKM_DATA_READY) || (tmp[0] & AKM_DATA_OVERRUN)) return -7; if (tmp[7] & AKM_OVERFLOW) return -8; #endif data[0] = ((unsigned short)tmp[2] << 8) | (unsigned short)tmp[1]; data[1] = ((unsigned short)tmp[4] << 8) | (unsigned short)tmp[3]; data[2] = ((unsigned short)tmp[6] << 8) | (unsigned short)tmp[5]; data[0] = ((long)data[0] * st->chip_cfg.mag_sens_adj[0]) >> 8; data[1] = ((long)data[1] * st->chip_cfg.mag_sens_adj[1]) >> 8; data[2] = ((long)data[2] * st->chip_cfg.mag_sens_adj[2]) >> 8; if (timestamp) get_ms(timestamp); return 0; #else return -9; #endif } /** * @brief Get the compass full-scale range. * @param[out] fsr Current full-scale range. * @return 0 if successful. */ int mpu_get_compass_fsr(unsigned short *fsr) { #ifdef AK89xx_SECONDARY fsr[0] = st->hw->compass_fsr; return 0; #else return -1; #endif } /** * @brief Enters LP accel motion interrupt mode. * The behavior of this feature is very different between the MPU6050 and the * MPU6500. Each chip's version of this feature is explained below. * * \n MPU6050: * \n When this mode is first enabled, the hardware captures a single accel * sample, and subsequent samples are compared with this one to determine if * the device is in motion. Therefore, whenever this "locked" sample needs to * be changed, this function must be called again. * * \n The hardware motion threshold can be between 32mg and 8160mg in 32mg * increments. * * \n Low-power accel mode supports the following frequencies: * \n 1.25Hz, 5Hz, 20Hz, 40Hz * * \n MPU6500: * \n Unlike the MPU6050 version, the hardware does not "lock in" a reference * sample. The hardware monitors the accel data and detects any large change * over a short period of time. * * \n The hardware motion threshold can be between 4mg and 1020mg in 4mg * increments. * * \n MPU6500 Low-power accel mode supports the following frequencies: * \n 1.25Hz, 2.5Hz, 5Hz, 10Hz, 20Hz, 40Hz, 80Hz, 160Hz, 320Hz, 640Hz * * \n\n NOTES: * \n The driver will round down @e thresh to the nearest supported value if * an unsupported threshold is selected. * \n To select a fractional wake-up frequency, round down the value passed to * @e lpa_freq. * \n The MPU6500 does not support a delay parameter. If this function is used * for the MPU6500, the value passed to @e time will be ignored. * \n To disable this mode, set @e lpa_freq to zero. The driver will restore * the previous configuration. * * @param[in] thresh Motion threshold in mg. * @param[in] time Duration in milliseconds that the accel data must * exceed @e thresh before motion is reported. * @param[in] lpa_freq Minimum sampling rate, or zero to disable. * @return 0 if successful. */ int mpu_lp_motion_interrupt(unsigned short thresh, unsigned char time, unsigned char lpa_freq) { unsigned char data[3]; if (lpa_freq) { unsigned char thresh_hw; #if defined MPU6050 /* TODO: Make these const/#defines. */ /* 1LSb = 32mg. */ if (thresh > 8160) thresh_hw = 255; else if (thresh < 32) thresh_hw = 1; else thresh_hw = thresh >> 5; #elif defined MPU6500 /* 1LSb = 4mg. */ if (thresh > 1020) thresh_hw = 255; else if (thresh < 4) thresh_hw = 1; else thresh_hw = thresh >> 2; #endif if (!time) /* Minimum duration must be 1ms. */ time = 1; #if defined MPU6050 if (lpa_freq > 40) #elif defined MPU6500 if (lpa_freq > 640) #endif /* At this point, the chip has not been re-configured, so the * function can safely exit. */ return -1; if (!st->chip_cfg.int_motion_only) { /* Store current settings for later. */ if (st->chip_cfg.dmp_on) { mpu_set_dmp_state(0); st->chip_cfg.cache.dmp_on = 1; } else st->chip_cfg.cache.dmp_on = 0; mpu_get_gyro_fsr(&st->chip_cfg.cache.gyro_fsr); mpu_get_accel_fsr(&st->chip_cfg.cache.accel_fsr); mpu_get_lpf(&st->chip_cfg.cache.lpf); mpu_get_sample_rate(&st->chip_cfg.cache.sample_rate); st->chip_cfg.cache.sensors_on = st->chip_cfg.sensors; mpu_get_fifo_config(&st->chip_cfg.cache.fifo_sensors); } #ifdef MPU6050 /* Disable hardware interrupts for now. */ set_int_enable(0); /* Enter full-power accel-only mode. */ mpu_lp_accel_mode(0); /* Override current LPF (and HPF) settings to obtain a valid accel * reading. */ data[0] = INV_FILTER_256HZ_NOLPF2; if (i2c_write(st->hw->addr, st->reg->lpf, 1, data)) return -1; /* NOTE: Digital high pass filter should be configured here. Since this * driver doesn't modify those bits anywhere, they should already be * cleared by default. */ /* Configure the device to send motion interrupts. */ /* Enable motion interrupt. */ data[0] = BIT_MOT_INT_EN; if (i2c_write(st->hw->addr, st->reg->int_enable, 1, data)) goto lp_int_restore; /* Set motion interrupt parameters. */ data[0] = thresh_hw; data[1] = time; if (i2c_write(st->hw->addr, st->reg->motion_thr, 2, data)) goto lp_int_restore; /* Force hardware to "lock" current accel sample. */ delay_ms(5); data[0] = (st->chip_cfg.accel_fsr << 3) | BITS_HPF; if (i2c_write(st->hw->addr, st->reg->accel_cfg, 1, data)) goto lp_int_restore; /* Set up LP accel mode. */ data[0] = BIT_LPA_CYCLE; if (lpa_freq == 1) data[1] = INV_LPA_1_25HZ; else if (lpa_freq <= 5) data[1] = INV_LPA_5HZ; else if (lpa_freq <= 20) data[1] = INV_LPA_20HZ; else data[1] = INV_LPA_40HZ; data[1] = (data[1] << 6) | BIT_STBY_XYZG; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 2, data)) goto lp_int_restore; st->chip_cfg.int_motion_only = 1; return 0; #elif defined MPU6500 /* Disable hardware interrupts. */ set_int_enable(0); /* Enter full-power accel-only mode, no FIFO/DMP. */ data[0] = 0; data[1] = 0; data[2] = BIT_STBY_XYZG; if (i2c_write(st->hw->addr, st->reg->user_ctrl, 3, data)) goto lp_int_restore; /* Set motion threshold. */ data[0] = thresh_hw; if (i2c_write(st->hw->addr, st->reg->motion_thr, 1, data)) goto lp_int_restore; /* Set wake frequency. */ if (lpa_freq == 1) data[0] = INV_LPA_1_25HZ; else if (lpa_freq == 2) data[0] = INV_LPA_2_5HZ; else if (lpa_freq <= 5) data[0] = INV_LPA_5HZ; else if (lpa_freq <= 10) data[0] = INV_LPA_10HZ; else if (lpa_freq <= 20) data[0] = INV_LPA_20HZ; else if (lpa_freq <= 40) data[0] = INV_LPA_40HZ; else if (lpa_freq <= 80) data[0] = INV_LPA_80HZ; else if (lpa_freq <= 160) data[0] = INV_LPA_160HZ; else if (lpa_freq <= 320) data[0] = INV_LPA_320HZ; else data[0] = INV_LPA_640HZ; if (i2c_write(st->hw->addr, st->reg->lp_accel_odr, 1, data)) goto lp_int_restore; /* Enable motion interrupt (MPU6500 version). */ data[0] = BITS_WOM_EN; if (i2c_write(st->hw->addr, st->reg->accel_intel, 1, data)) goto lp_int_restore; /* Enable cycle mode. */ data[0] = BIT_LPA_CYCLE; if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, data)) goto lp_int_restore; /* Enable interrupt. */ data[0] = BIT_MOT_INT_EN; if (i2c_write(st->hw->addr, st->reg->int_enable, 1, data)) goto lp_int_restore; st->chip_cfg.int_motion_only = 1; return 0; #endif } else { /* Don't "restore" the previous state if no state has been saved. */ int ii; char *cache_ptr = (char*)&st->chip_cfg.cache; for (ii = 0; ii < sizeof(st->chip_cfg.cache); ii++) { if (cache_ptr[ii] != 0) goto lp_int_restore; } /* If we reach this point, motion interrupt mode hasn't been used yet. */ return -1; } lp_int_restore: /* Set to invalid values to ensure no I2C writes are skipped. */ st->chip_cfg.gyro_fsr = 0xFF; st->chip_cfg.accel_fsr = 0xFF; st->chip_cfg.lpf = 0xFF; st->chip_cfg.sample_rate = 0xFFFF; st->chip_cfg.sensors = 0xFF; st->chip_cfg.fifo_enable = 0xFF; st->chip_cfg.clk_src = INV_CLK_PLL; mpu_set_sensors(st->chip_cfg.cache.sensors_on); mpu_set_gyro_fsr(st->chip_cfg.cache.gyro_fsr); mpu_set_accel_fsr(st->chip_cfg.cache.accel_fsr); mpu_set_lpf(st->chip_cfg.cache.lpf); mpu_set_sample_rate(st->chip_cfg.cache.sample_rate); mpu_configure_fifo(st->chip_cfg.cache.fifo_sensors); if (st->chip_cfg.cache.dmp_on) mpu_set_dmp_state(1); #ifdef MPU6500 /* Disable motion interrupt (MPU6500 version). */ data[0] = 0; if (i2c_write(st->hw->addr, st->reg->accel_intel, 1, data)) goto lp_int_restore; #endif st->chip_cfg.int_motion_only = 0; return 0; } /** * @} */
[ "iverasp@gmail.com" ]
iverasp@gmail.com
583836ab57dd92755dd5761e2e6426153688073c
52711c8a7483ed1fd968e78751ddf0f68ef67666
/20160301/vector.cc
3dfc49a1b5347052e963f77921c064171daaa629
[]
no_license
patrickbiao/C-
e3b3d74b3a577a7d872904422052727710ba309a
7eb0ab2951f7a75690666ae05236e833b0ba9c85
refs/heads/master
2021-01-10T05:26:57.445960
2016-03-14T14:06:04
2016-03-14T14:06:04
52,513,300
0
0
null
null
null
null
UTF-8
C++
false
false
1,405
cc
/// /// @file vector.cc /// @author patrick(730557219@qq.com) /// @date 2016-03-02 22:00:17 /// #include <iostream> #include <vector> using std::cout; using std::endl; using std::string; void printfVector(std::vector<int> & vecInt)//传他的引用 { cout << "vector's size :" << vecInt.size() << endl;//类似于strlen cout << "vector's capacity:" << vecInt.capacity() << endl; } int main(void) { std::vector<int> vecInt;//整体是一个类名,尖括号为数组存放的类型 vecInt.reserve(100);//先开好一个固定数量的空间 printfVector(vecInt); vecInt.push_back(1);//表示在尾部进行添加 printfVector(vecInt); vecInt.push_back(2); printfVector(vecInt); vecInt.push_back(3); printfVector(vecInt); vecInt.push_back(4); printfVector(vecInt); vecInt.push_back(5); printfVector(vecInt); vecInt.push_back(6); printfVector(vecInt); //通过迭代器遍历数组 std::vector<int>::iterator it = vecInt.begin(); for(;it != vecInt.end();++it)//从第一个位置开始一点点遍历 { cout << *it << endl;//通过指针去访问数据 } for(int idx = 0; idx != vecInt.size(); ++idx) { cout << vecInt[idx] << endl;//因为是数组,通过下标法访问 } //C++ 11的方式 //编译时需要加编译选项 -std=c++11 for(auto elem : vecInt)//自动遍历容器,数据都用elem来存储 { cout << elem << endl; } return 0; }
[ "730557219@qq.com" ]
730557219@qq.com
08026232008dcbe946fcc2f14e05859cf0e852c2
0528b84f8160ff52f8af068a1dc3c27488a21940
/StateCompare.h
95d5f61af7f8cca03b07e5130e1a1b1f8864d770
[]
no_license
YairHanimov/Searching_Algorithm_Server
e2c683a179bd25a2ed836614be8c5b8799cb7286
ca0ad9f853140deee0be93ffb7761fbb91eb9fef
refs/heads/master
2020-12-09T19:49:04.038346
2020-01-27T13:04:41
2020-01-27T13:04:41
233,403,309
0
0
null
null
null
null
UTF-8
C++
false
false
402
h
// // Created by eyal on 19.1.2020. // #ifndef SEARCHING_ALGORITHM_SERVER_STATECOMPARE_H #define SEARCHING_ALGORITHM_SERVER_STATECOMPARE_H #include "State.h" using namespace std; template<class T> class StateCompare { public: bool operator()(State<T> *first, State<T>* second) { return first->getCost() > second->getCost(); } }; #endif //SEARCHING_ALGORITHM_SERVER_STATECOMPARE_H
[ "eyalgolan96@gmail.com" ]
eyalgolan96@gmail.com
a1ac86f87dc8ebf1ee8034312010d37c936197f3
cd4a7f03a2a62ffe260bcd8ec5e72313956afb6e
/Source/TPE/Public/TPE_CharacterWidget.h
f99b8c68b90b45998b29adb4339d2a9e33673a04
[ "MIT" ]
permissive
ssapo/TPE_Darksouls
07536100a0ef8d94faa71c0cde7682b60eac1fdb
4d1c883e19076d4c403a0c6b745dc0c225280fea
refs/heads/master
2020-03-31T08:23:28.446128
2019-07-04T14:38:18
2019-07-04T14:38:18
152,054,771
10
1
MIT
2019-07-04T14:38:19
2018-10-08T09:39:33
C++
UTF-8
C++
false
false
1,194
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "TPE.h" #include "Blueprint/UserWidget.h" #include "TPE_CharacterWidget.generated.h" /** * */ UCLASS() class TPE_API UTPE_CharacterWidget : public UUserWidget { GENERATED_BODY() public: void BindCharacterStat(class UTPECharacterStatComponent* NewCharacterStat, bool bPlayer); protected: virtual void NativeConstruct() override; virtual void NativeTick(const FGeometry& MyGeometry, float InDeltaTime) override; void UpdateHPWidget(); void UpdateDamageWidget(int32 NewDamaged); void UpdateStaminaWidget(); void UpdateBackWidget(class UProgressBar* BackProgressBar, float FrontProgressBarPercent, float InDeltaTime); private: TWeakObjectPtr<class UTPECharacterStatComponent> CurrentCharacterStat; UPROPERTY() class UProgressBar* HPProgressBar; UPROPERTY() class UProgressBar* HPBackProgressBar; UPROPERTY() class UProgressBar* StaminaProgressBar; UPROPERTY() class UProgressBar* StaminaBackProgressBar; UPROPERTY() class UMultiLineEditableText* DamageEditableText; FTimerHandle TimerHandle; int32 HPDamaged = 0; bool bDamagedVisiblity = false; };
[ "songsiyoon@gmail.com" ]
songsiyoon@gmail.com
ae99a4a4053c7abc9c51545aae34000662ea4cc0
b11b2b488d94ae20f58cfe40bae0987c32b5945e
/LEMOS-2.3.x/libLEMOS-2.3.x/turbulenceModels/incompressible/PANS/turbulentPrandtlModels/zeroTransportModel/zeroTransportModel.H
2057b512fb77967702d3dd2eaef56731564b6147
[]
no_license
jamesjguthrie/mayerTestCase
93dbd9230e16a0f061cec97c7ddf6cb5303e1c95
9279ad56b62efa1507ff8b1bcd96e3ce2daceb56
refs/heads/master
2021-03-30T18:20:33.641846
2019-06-25T12:55:07
2019-06-25T12:55:07
26,530,210
0
0
null
null
null
null
UTF-8
C++
false
false
4,049
h
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | Unsupported Contributions for OpenFOAM \\ / O peration | \\ / A nd | Copyright (C) 2014 LEMOS, University Rostock \\/ M anipulation | ------------------------------------------------------------------------------- License This file is a derivative work of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Namespace Foam::incompressible::zeroTransportModels:zeroTransportModels Group grpIcoPANSModels Description Namespace for incompressible turbulent Prandtl models. Class Foam::incompressible::zeroTransportModel Description Zero transport model SourceFiles zeroTransportModel.C \*---------------------------------------------------------------------------*/ #ifndef zeroTransportModel_H #define zeroTransportModel_H #include "incompressible/turbulenceModel/turbulenceModel.H" #include "volFields.H" #include "surfaceFields.H" #include "fvc.H" #include "fvMatrices.H" #include "incompressible/transportModel/transportModel.H" #include "IOdictionary.H" #include "Switch.H" #include "bound.H" #include "autoPtr.H" #include "runTimeSelectionTables.H" #include "turbulentPrandtlModel.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { namespace incompressible { namespace PANSModels { namespace turbulentPrandtlModels { /*---------------------------------------------------------------------------*\ Class zeroTransportModel Declaration \*---------------------------------------------------------------------------*/ class zeroTransportModel : public turbulentPrandtlModel { protected: // Protected data // Protected Member Functions //- Print model coefficients //virtual void printCoeffs(); private: // Private Member Functions //- Disallow default bitwise copy construct zeroTransportModel(const zeroTransportModel&); //- Disallow default bitwise assignment void operator=(const zeroTransportModel&); public: //- Runtime type information TypeName("zeroTransportModel"); // Constructors //- Construct from components zeroTransportModel ( const volVectorField& U, const surfaceScalarField& phi, const word& param, const word& turbulenceModelName = turbulenceModel::typeName ); //- Destructor virtual ~zeroTransportModel() {} // Member Functions // Access //- virtual tmp<volScalarField> sigmaEps() const ; //- virtual tmp<volScalarField> sigmaK() const; //- virtual tmp<volScalarField> sigmaOmega() const; //- Solve the turbulence equations and correct the turbulence viscosity virtual void correct(); //- Read turbulentPrandtlProperties dictionary virtual bool read(); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace turbulentPrandtlModels } // End namespace PANSModels } // End namespace incompressible } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
[ "james@heyjimmy.net" ]
james@heyjimmy.net
832486ef165f680ff57f29de6782157931bbad7d
9666b15d376c6adc51ad27e963189ad8e1aba20c
/NN/Input.h
e71d61bb4741e4d44a8cf8e59a69198746824c75
[]
no_license
wooshe/NNWithGA
91e12793f6f90d848293f7d4279c8bd3a8e6b9b4
b8d9fe506612b077203a585f24e613a9682955f9
refs/heads/master
2020-09-18T07:19:00.031966
2019-11-26T08:14:58
2019-11-26T08:14:58
224,136,895
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
205
h
//Класс для описания входов ИНС class Input { public: //Значение входа double Value; }; //Имя Output будет совпадать с Input typedef Input Output;
[ "j_g_g@list.ru" ]
j_g_g@list.ru
160ea5199afaabf33668de9b459d03a1268b1f23
eb06e0e1d0ac4f9c34cac24fb2c78daa8857d73e
/plugintracker.h
cb45221424e9d9a1a92c63b75fe1e69d37d0a974
[]
no_license
avsej/kismet
6521f36d455e2df824fb9e3eabe62a5bbae86fb2
36c91fcfbca4d28cb37405715cd51e67e5b77ec0
refs/heads/master
2021-01-23T23:12:33.380383
2017-09-09T20:52:09
2017-09-09T20:52:09
102,956,241
1
0
null
2017-09-09T13:19:35
2017-09-09T13:19:35
null
UTF-8
C++
false
false
9,124
h
/* This file is part of Kismet Kismet is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kismet is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Kismet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PLUGINTRACKER_H__ #define __PLUGINTRACKER_H__ // Plugin handler // // Plugins are installed into [LIB_LOC]/kismet/[plugin-name]/ or // ~/.kismet/[plugins]/[plugin-name]/ // // A plugin directory should contain: // // httpd/ // Any HTTP content the plugin serves, this will be made available // on the webserver as /plugin/[plugin-name]/ // // foo.so // A shared object containing the plugin code, if this plugin requires // code. If the plugin contains HTTP data only a manifest is sufficient // // manifest.conf // A manifest file containing information about the plugin to be loaded // See docs/dev/plugin.md for more information about the format of the // manifest file // // // Plugins are responsible for completing the record passed to them // from Kismet and filling in the PluginRegistrationData record // // Plugins must define two core functions, in the C name space: // // int kis_plugin_version_check(struct plugin_server_info *) // // will be passed an empty plugin_server_info struct and is expected // to fill in all fields available. // // Plugins should return negative on failure, non-negative on success // // and // // int kis_plugin_activate(GlobalRegistry *) // // which is responsible for activating the plugin and registering it // with the system. // // Plugins should return negative on failure, non-negative on success // // Plugins which need system components which may not be active at plugin // activation time may include a third function: // // int kis_plugin_finalize(GloablRegistry *) // // which will be called at the final stage of Kismet initialization before // entry into the main loop. // // Even when including a kis_plugin_finalize function, plugins MUST // return success during initial activation to receive the finalization // event. // // Plugins should return negative on failure, non-negative on success. // // // Kismet plugins are first-order citizens in the ecosystem - a plugin // is passed the global registry and is able to look up and interact // with all registered components, including other plugins. // // This is a blessing and a curse - plugins are very tied to the kismet // ABI, but are equally capable of performing ANYTHING kismet can // do already. // // A secondary, abstracted plugin interface may come in the future to // provide a more stable plugin interface. #include "config.h" #include <stdio.h> #include <time.h> #include <list> #include <map> #include <vector> #include <algorithm> #include <string> #include <sys/types.h> #include <dlfcn.h> #include <dirent.h> #include "globalregistry.h" #include "trackedelement.h" #include "kis_net_microhttpd.h" // The registration object is created by the plugintracker and given to // a Kismet plugin; the plugin fills in the relevant information during // the registration process class PluginRegistrationData : public tracker_component { public: PluginRegistrationData(GlobalRegistry *in_globalreg, int in_id) : tracker_component(in_globalreg, in_id) { register_fields(); reserve_fields(NULL); dlfile = NULL; } PluginRegistrationData(GlobalRegistry *in_globalreg, int in_id, SharedTrackerElement e) : tracker_component(in_globalreg, in_id) { register_fields(); reserve_fields(e); dlfile = NULL; } virtual ~PluginRegistrationData() { if (dlfile != NULL) dlclose(dlfile); } virtual SharedTrackerElement clone_type() { return SharedTrackerElement(new PluginRegistrationData(globalreg, get_id())); } __Proxy(plugin_name, string, string, string, plugin_name); __Proxy(plugin_description, string, string, string, plugin_description); __Proxy(plugin_author, string, string, string, plugin_author); __Proxy(plugin_version, string, string, string, plugin_version); __Proxy(plugin_so, string, string, string, plugin_so); __Proxy(plugin_dirname, string, string, string, plugin_dirname); __Proxy(plugin_path, string, string, string, plugin_path); __Proxy(plugin_js, string, string, string, plugin_js); void set_plugin_dlfile(void *in_dlfile) { dlfile = in_dlfile; } void *get_plugin_dlfile() { return dlfile; } protected: virtual void register_fields() { tracker_component::register_fields(); RegisterField("kismet.plugin.name", TrackerString, "plugin name", &plugin_name); RegisterField("kismet.plugin.description", TrackerString, "plugin description", &plugin_description); RegisterField("kismet.plugin.author", TrackerString, "plugin author", &plugin_author); RegisterField("kismet.plugin.version", TrackerString, "plugin version", &plugin_version); RegisterField("kismet.plugin.shared_object", TrackerString, "plugin shared object filename", &plugin_so); RegisterField("kismet.plugin.dirname", TrackerString, "plugin directory name", &plugin_dirname); RegisterField("kismet.plugin.path", TrackerString, "path to plugin content", &plugin_path); RegisterField("kismet.plugin.jsmodule", TrackerString, "Plugin javascript module", &plugin_js); } SharedTrackerElement plugin_name; SharedTrackerElement plugin_author; SharedTrackerElement plugin_description; SharedTrackerElement plugin_version; SharedTrackerElement plugin_so; SharedTrackerElement plugin_dirname; SharedTrackerElement plugin_path; SharedTrackerElement plugin_js; void *dlfile; }; typedef shared_ptr<PluginRegistrationData> SharedPluginData; // Plugin activation and final activation function typedef int (*plugin_activation)(GlobalRegistry *); #define KIS_PLUGINTRACKER_VERSION 1 // Server information record // The plugin should fill in this data and return it in the kis_plugin_version_check // callback. It will be given a plugin_api_version which it must respect. struct plugin_server_info { // V1 server info // Plugin API version; plugins can not expect fields to be present // in this struct from a future version of the plugin revision. This // value is unlikely to change, but it may become necessary in the // future to expand the versioning unsigned int plugin_api_version; string kismet_major; string kismet_minor; string kismet_tiny; // End V1 info }; // Plugin function called with an allocated plugin_server_info which complies with // the version specified in plugin_api_version. // // Plugins should fill in all fields relevant to that version, or if there is a // version mismatch, immediately return -1. typedef int (*plugin_version_check)(plugin_server_info *); // Plugin management class class Plugintracker : public LifetimeGlobal, public Kis_Net_Httpd_CPPStream_Handler { public: static shared_ptr<Plugintracker> create_plugintracker(GlobalRegistry *in_globalreg) { shared_ptr<Plugintracker> mon(new Plugintracker(in_globalreg)); in_globalreg->RegisterLifetimeGlobal(mon); in_globalreg->InsertGlobal("PLUGINTRACKER", mon); return mon; } private: Plugintracker(GlobalRegistry *in_globalreg); public: static void Usage(char *name); virtual ~Plugintracker(); // Look for plugins int ScanPlugins(); // First-pass at activating plugins int ActivatePlugins(); // Final chance at activating plugins int FinalizePlugins(); // Shut down the plugins and close the shared files int ShutdownPlugins(); // HTTP API virtual bool Httpd_VerifyPath(const char *path, const char *method); virtual void Httpd_CreateStreamResponse(Kis_Net_Httpd *httpd, Kis_Net_Httpd_Connection *connection, const char *url, const char *method, const char *upload_data, size_t *upload_data_size, std::stringstream &stream); protected: pthread_mutex_t plugin_lock; GlobalRegistry *globalreg; int plugins_active; int ScanDirectory(DIR *in_dir, string in_path); // Final vector of registered activated plugins SharedTrackerElement plugin_registry; TrackerElementVector plugin_registry_vec; // List of plugins before they're loaded vector<SharedPluginData> plugin_preload; }; #endif
[ "dragorn@kismetwireless.net" ]
dragorn@kismetwireless.net
c8f49c00de0d15203aa1aa015efe9d8e7b676aaa
38240e3d2088ce2ed5d099121cc203044e911caf
/src/UI.cpp
08e8b90ed9234451d9f37c4900019d53a602e045
[]
no_license
Ria-0617/work
3348554bc3e899b9d3a72a1b1a51df434a9b1f2e
319b7812cf96a2de69bba7b52e83d57e15788a17
refs/heads/master
2020-03-23T12:15:47.379215
2018-10-02T20:14:52
2018-10-02T20:14:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,308
cpp
#include "UI.h" using namespace ci; using namespace ci::app; using namespace std; UI::UI(int windowWidth, int windowHeght) { score = 0; timer = 3600; uiCamera = CameraOrtho(0.f, windowWidth, windowHeght, 0.f, -1.f, 1.f); uiCamera.setEyePoint(Vec3f(0.f, 0.f, 0.f)); uiCamera.setCenterOfInterestPoint(Vec3f(0.f, 0.f, -1.f)); customFont = Font(loadAsset("AndrewsQueen.ttf"), 48.f); } UI::~UI() { } gl::Texture UI::TextSetUp(string txt, TextBox::Alignment centerPos, Vec2i size) { TextBox tBox = TextBox().alignment(centerPos).font(customFont).size(Vec2i(size)).text(txt); tBox.setColor(Color(1.f, 1.f, 1.f)); tBox.setBackgroundColor(ColorA(0.f, 0.f, 0.f, 0.f)); return gl::Texture(tBox.render()); } void UI::UpDate() { if (timer > 0) timer -= 1; scoreText = "Score : " + std::to_string(score); scoreTexture = TextSetUp(scoreText, TextBox::LEFT, Vec2i(getWindowWidth(), /*size = */100)); timerText = std::to_string(timer / 60); timerTexture = TextSetUp(timerText, TextBox::CENTER, Vec2i(getWindowWidth(), /*size = */100)); } void UI::Draw() { gl::enableAlphaBlending(); gl::color(Color(1.f, 1.f, 1.f)); gl::setMatrices(uiCamera); if (scoreTexture) gl::draw(scoreTexture, Vec2i(0, 0)); if (timerTexture) gl::draw(timerTexture, Vec2i(0, 0)); gl::disableAlphaBlending(); }
[ "kyelese0617@gmail.com" ]
kyelese0617@gmail.com
fa3b7b92370726e24615c7702c7ef58c697e17b6
e1b8c74bf1b98f800ad6ed21752699666ca70319
/Parser/Parser.h
1a49248230a4ac171a81c4b518c76b76a55685c9
[]
no_license
NickSifniotis/N
107d1cc6cdf4d90de900cfa3afcbfbc75e101316
3409839af119f9eeda44124c3b5002dcbe917009
refs/heads/master
2016-08-12T15:52:03.574649
2015-12-16T03:20:46
2015-12-16T03:20:46
48,010,377
0
0
null
null
null
null
UTF-8
C++
false
false
876
h
#ifndef PARSER_H #define PARSER_H #include "Tokeniser.h" #include "Token.h" #include "ExpressionTree.h" #include "ProgramStatement.h" #include <vector> #include <string> class Parser { public: Parser(); virtual ~Parser(); std::vector<ProgramStatement*> *parse(std::string filename); protected: private: std::string readFile(std::string f); ProgramStatement *get_statement(Tokeniser *tk); ProgramStatement *get_assignment(Tokeniser *tk, std::string var_name); ProgramStatement *get_declaration(Tokeniser *tk, std::string var_type); ProgramStatement *get_function_call(Tokeniser *tk, std::string func_name); ExpressionTreeNode *get_expression(Tokeniser *tk); ExpressionTreeNode *get_term(Tokeniser *tk); ExpressionTreeNode *get_factor(Tokeniser *tk); }; #endif // PARSER_H
[ "u5809912@anu.edu.au" ]
u5809912@anu.edu.au
efb8fc22d6904b57dff8975b1b66a7e527d6bfd8
e5b98edd817712e1dbcabd927cc1fee62c664fd7
/Classes/common/Dialog/ServerLoadingLayer.h
df372a923cc00e07bc962fb1680f72d6eaf2c252
[]
no_license
yuangu/project
1a49092221e502bd5f070d7de634e4415c6a2314
cc0b354aaa994c0ee2d20d1e3d74da492063945f
refs/heads/master
2020-05-02T20:09:06.234554
2018-12-18T01:56:36
2018-12-18T01:56:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,065
h
// // ServerLoadingLayer.h // SuiTang // // Created by zhangxiaobin on 15/1/14. //服务器通讯loaing 不让玩家重复操作 // #ifndef __SuiTang__ServerLoadingLayer__ #define __SuiTang__ServerLoadingLayer__ #include "cocos2d.h" USING_NS_CC; #include "../../module/BaseLayer.h" class ServerLoadingLayer:public BaseLayer { public: ServerLoadingLayer(); ~ServerLoadingLayer(); virtual bool init(float timess); static ServerLoadingLayer* create(float timess); virtual void onEnter(); virtual void onExit(); virtual void onExitTransitionDidStart(); virtual void onEnterTransitionDidFinish(); bool isShowReLogin;//如果服务器没返回,是否显示重连 private: void leftHandHit(); void rightHandHit(); void initLoading(); void setLoadingDot(); void onDelay(float dt); void onDialogEvent(Node* pSender); private: int TAG_CONNECTWORD; float delayTimes; Node* m_dotContainer; int TAG_LEFTHAND; int TAG_RIGHTHAND; }; #endif /* defined(__SuiTang__ServerLoadingLayer__) */
[ "chenyanbin@ixianlai.com" ]
chenyanbin@ixianlai.com
bf5a0efcda4b4ca7a2beb4f96b00da5897893881
950ec9dd55dc32975c46b3b61b98434edc9b2d0c
/Render/Camera.h
90c16b40d7be2dad8e85e291d7b86223c386ba1b
[]
no_license
aSaul2006/GameEngineProject
a99bb0f73d74388f99758c84ca1215093eba972f
3b3c5ada569aa1fc86383f90a078ecd439247ad1
refs/heads/master
2021-01-10T14:41:14.269844
2013-03-04T15:58:13
2013-03-04T15:58:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,516
h
/************************************************************************ * Program Name: Lighting.h * Name: GSP420 Rendering Core - Jesse Goldan, Mike Murrell * * Date: January 28th - February 1st * Description: A class that lets you do all functions that a camera would do * Created by Jesse and slightly modified by Mike * Update: February 8, 2013 ************************************************************************/ #ifndef CAMERA_HPP #define CAMERA_HPP #include <d3dx9.h> #pragma once //Camera class class Camera { public: Camera(); void SetPosition(D3DXVECTOR3& position); void SetRotation(D3DXVECTOR3& rotation); void SetTarget (D3DXVECTOR3& target); const D3DXVECTOR3& GetPosition() const; const D3DXVECTOR3& GetRotation() const; const D3DXVECTOR3& GetTarget() const; D3DXMATRIX& GetProjection(); const D3DXMATRIX& GetView() const; void Move (D3DXVECTOR3& move); void Rotate (D3DXVECTOR3& rotate); void SetFOV(float fov); float GetFOV() const; void SetAspectRatio(float aspectRatio); float GetAspectRatio() const; void SetNearValue(float nearValue); float GetNearValue() const; void SetFarValue(float farValue); float GetFarValue() const; virtual void Render(); private: float m_FOV; float m_NearValue; float m_FarValue; float m_AspectRatio; D3DXVECTOR3 m_Position; D3DXVECTOR3 m_Rotation; D3DXVECTOR3 m_Target; D3DXMATRIX m_m4Proj; D3DXMATRIX m_m4View; }; #endif
[ "aaron.saul@PEND-2370.cayusetechnologies.com" ]
aaron.saul@PEND-2370.cayusetechnologies.com
4befac443bac5bcb581d1c40bdb4c81bad4fccae
e3a9881388760aa08e470632dc8375b1f09f0f1f
/main.cpp
29175f400d533eaf2d524e23cf735e01c286f061
[]
no_license
changnet/GameProxy
1a96657ad414944700c09e01c52528ad332a208f
0936a7e29f3a4a44357c2bc5d6a3f698b76c0392
refs/heads/master
2020-09-13T13:21:14.853473
2015-10-27T02:27:18
2015-10-27T02:27:18
31,811,022
1
0
null
null
null
null
UTF-8
C++
false
false
6,276
cpp
#include <iostream> #include <ev++.h> #include <unistd.h> #include <cstdlib> #include <cstdio> #include <signal.h> #include "CProxySession.h" #include "CSetting.h" #include "CBackend.h" #include "CPool.h" #include "gslog.h" using namespace std; void start_session(const char *file); void write_config(const char *file); void usage(); void thanks(); void become_daemon(); void sig_hold(); void sig_set(int32 signum, int32 sa_flag); void sig_handler(int32 signum); /** * @brief main * @return * 程序入口 */ int main(int argc,char **argv) { if ( argc < 3) { usage(); return 0; } if ( 0 == strcmp( "-s",argv[1] ) ) { thanks(); become_daemon(); start_session( argv[2] ); } else if ( 0 == strcmp( "-c",argv[1] ) ) write_config( argv[2] ); else usage(); /* 销毁单例内存 */ CPool<CTcpSession>::uninstance(); CBackend::uninstance(); return 0; } /** * @brief start_session * @param file * 开启网关 */ void start_session( const char *file ) { bool is_ok = true; CSetting setting; if ( !setting.read_config(file) ) { std::cerr << "read config file fail:" << file << std::endl; return; } int32 session_count = setting.get_session_count(); std::cout << "start with config file [" << file << "],"<< session_count << " session found:" << std::endl; CProxySession* p = new CProxySession[session_count]; for ( int32 i = 0;i < session_count;i ++ ) { int32 lp = setting.get_session_listen_port(i); int32 sp = setting.get_session_server_port(i); const char *url = setting.get_session_server_url(i); std::cout << " " << "listen port:" << lp << ",server_url:" << url << ",server port:" << sp << "."; (p+i)->set_session( url,sp,lp); if ( (p+i)->start() ) std::cout << "OK" << std::endl; else { std::cout << "FAIL" << std::endl; is_ok = false; } } if ( is_ok ) { std::cout << "done ..." << std::endl; sig_hold();/* 进入守护进程,监听必要信号 */ CBackend::instance()->start(); } else std::cout << "session start fail,exit..." << std::endl; delete []p; } /** * @brief write_config * @param file * 写入样本配置 */ void write_config( const char *file ) { CSetting setting; setting.write_config_sample( 2,file ); std::cout << "write config to " << file << " done." << std::endl; } void usage() { std::cout << "usage:gameproxy [command] [config]" << std::endl; std::cout << std::endl; std::cout << "command:" << std::endl; std::cout << " -s start session" << std::endl; std::cout << " -c write config sample" << std::endl; std::cout << std::endl; std::cout << "config:" << std::endl; std::cout << " the config file path" << std::endl; std::cout << std::endl; std::cout << "example:" << std::endl; std::cout << "./gameproxy -c session.json" << std::endl; std::cout << "./gameproxy -s session.json" << std::endl; } /** * @brief become_daemon * 转化为守护进程 */ void become_daemon() { pid_t pid =fork(); if ( pid<0 ) { ERROR( "fork error" ); exit( 0 ); return; } else if ( pid > 0 ) //父进程退出,子进程脱离终端shell,ctrl+c或关闭终端shell不会终止程序 exit( 0 ); //在Qt creator开启的shell中仍会终止掉程序,在用户终端则不会 setsid(); //创建新会话,当前会话结束(用户登出)程序也不会终止 /* * 当一个会话产生(如用户登录),会有一个默认的mask权限值,该值决定了在此会话中对文件操作的权限 * umask(0)就是设置允许当前进程创建文件或者目录最大可操作的权限,比如这里设置为0,它的意思就是0 * 取反再创建文件时权限相与,也就是:(~0) & mode 等于八进制的值0777 & mode了 * 如果不需要,可以不设置,用继承的即可 * */ //umask(0); // 设置权限掩码 //chdir("/"); // 设置工作目录,没必要 /* * 关闭文件描述符,这里还是需要用到std::cout std::cerr * 可以关闭std::cin * 没什么必要 for (int fd=0;fd < getdtablesize();fd++ ) { close(fd); } */ close( STDIN_FILENO ); } /** * @brief thanks * 鸣谢相关开源软件 */ void thanks() { std::cout << "game proxy 1.0" << std::endl; std::cout << "thanks:" << std::endl; std::cout << " GNU http://www.gnu.org" << std::endl; std::cout << " libev http://software.schmorp.de/pkg/libev.html" << std::endl; std::cout << " parson https://github.com/kgabis/parson" << std::endl; std::cout << std::endl; } /** * @brief sig_set * @param signum * @param sa_flag * 设置单个信号 */ void sig_set( int32 signum,int32 sa_flag ) { struct sigaction sa; sa.sa_handler = sig_handler; sigemptyset( &sa.sa_mask ); /* will not block any other signal */ sa.sa_flags = sa_flag; /* usually SA_RESTART or SA_RESETHAND,man sigaction for more */ sigaction( signum,&sa,0 ); } /** * @brief sig_handler * @param signum * 处理信号回调 */ void sig_handler(int32 signum ) { char buff[256]; snprintf( buff,256,"catch signal %d:%s",signum,strsignal( signum ) ); ERROR( buff ); switch ( signum ) { case SIGHUP : case SIGINT : case SIGQUIT : case SIGCONT : case SIGTSTP : case SIGUSR1 : case SIGUSR2 : return; break; case SIGILL : case SIGABRT : case SIGSEGV : case SIGPIPE : case SIGCHLD : case SIGTTIN : case SIGTTOU : case SIGXCPU : case SIGXFSZ : case SIGPWR : break; case SIGTERM : //正常关闭 ERROR( "exit normal..." ); /* ev_break( EV_DEFAULT,EVBREAK_ALL ); no effect */ CBackend::instance()->stop(); break; } } /** * @brief sig_hold * 设置所需要捕捉的信号 */ void sig_hold() { sig_set( SIGCONT,SA_RESTART ); sig_set( SIGTERM,SA_RESTART ); }
[ "940477049@qq.com" ]
940477049@qq.com
61021ed6e3f00e2ab524d28a7e9cf1363c2c673e
e969be9b8a0067e6e7a9e84974d79b4aa68f1dec
/code/aoce/media/MediaHelper.hpp
c2bdb459d06811b83670d92b263ed51b4f8da52e
[ "MIT" ]
permissive
sandman555/aoce
479850e2c04505289bab32a2c4ca02d3cdc7dc40
c1895d7ecc784354744886fb6db4174f211d81d1
refs/heads/master
2023-08-15T19:06:57.094702
2021-10-13T15:14:47
2021-10-13T15:14:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
186
hpp
#pragma once #include "../Aoce.hpp" namespace aoce { ACOE_EXPORT MediaSourceType getMediaType(const std::string& str); ACOE_EXPORT std::string getAvformat(const std::string& uri); }
[ "mfjt55@163.com" ]
mfjt55@163.com
93ad293c2f5c241283a55cb732c68369aefe754e
9c43b6bb941b1f5f92dd6d4aa9a7afa4e7f0e4f0
/Proyecto final.cpp
6962633e7a713926fb2cf24739cc9f79b8c80b16
[]
no_license
do9900/cine-C
a712d47336f0b14121286630a791d1787d626b58
0ce696d40f20d82fec2f25fd5b69bfc331eb694c
refs/heads/main
2023-01-24T10:08:05.013061
2020-11-19T17:26:23
2020-11-19T17:26:23
314,320,424
0
0
null
null
null
null
ISO-8859-1
C++
false
false
25,581
cpp
/* SISTEMA CINE Este proyecto está basado en una representación de un cine, en donde, en un principio, se debe registrar la cartelera (listado de peliculas), cada cual con un precio unitario y el número de peliculas que dispone la cartelera, esta lista de peliculas se guarda utilizando archivos para asi utilizarla en cada una de las ventas posteriores generadas por cada cliente. Además estos productos incluidos en la lista, pueden ser eliminados, y/o modificados, según sea deseado. En cada compra se deberá ingresar el nombre del cliente.Luego de esta acción se procederá a escoger la opción de mostrar el reporte de compra, que asemeja a una boleta; aquí se muestra el código de la pelicula, su nombre, la cantidad de boletos comprados, el precio unitario, el costo total de toda la operación, incluyendo el IGV, además el nombre del cliente y se solicita que el cliente firme la boleta. AUTOR: DIEGO JAVIER HUAREZ AREVALO */ #include<iostream> #include<stdio.h> #include<stdlib.h> #include <iomanip> #include <string.h> using namespace std; #define archivo "c:Datos.dat" #define temporal "c:temporal.dat" struct Pelicula { char name[30]; int codigo; //codigo de la sala en la que se proyectara la pelicula char sinopsis[100]; char genero[15]; int duracion; //en minutos float precio=0; int capacidad=0; float total=0; }; struct Fecha{ int dia; int mes; int anio; }; struct persona { int dni; char nombre[30]; char apellidoPaterno[15]; char apellidoMaterno[15]; char correo[25]; Fecha fecha_nac; }; persona data,t; Pelicula datos,temp[50]; FILE *f; FILE *g; FILE *temprl; //========================================================= INTRODUCCION ========================================================= void intro(char mensaje[]) { cout<<"\n\n\n\n\n\n\n\n\n\t\t\t\t ********** "<<mensaje<<" **********\n\n"<<endl; system("pause"); system("cls"); } //========================================================= SALIDA ========================================================= void salida(char mensaje[]) { cout<<"\n\n\n\n\n\n\n\n\n\ ******************** "<<mensaje<<" ********************\n"<<endl; system("pause"); system("cls"); } //========================================================= RESPUESTA ========================================================= char continuar(char mensaje[]) {char opcion; do {cout<<mensaje; cin>>opcion; if(opcion!='S'&& opcion!='N') cout<<"RESPUESTA NO VALIDA, POR FAVOR INGRESE DE NUEVO SU RESPUESTA"; }while(opcion!='S'&& opcion!='N'); return opcion; } //========================================================= REPORTE INDIVIDUAL ========================================================= void mostrarpel() {cout<<"\n\t |CODIGO ==> "<<setw(44)<<datos.codigo<<"|"<<endl; cout<<"\t |NOMBRE ==> "<<setw(44)<<datos.name<<"|"<<endl; cout<<"\t |SINOPSIS ==> "<<setw(42)<<datos.sinopsis<<"|"<<endl; cout<<"\t |GENERO ==> "<<setw(42)<<datos.genero<<"|"<<endl; cout<<"\t |DURACION ==> "<<setw(42)<<datos.duracion<<"|"<<endl; cout<<"\t |CANTIDAD ==> "<<setw(42)<<datos.capacidad<<"|"<<endl; cout<<"\t |PRECIO ==> "<<setw(44)<<datos.precio<<"|"<<endl; } //========================================================= MENU Pelicula ========================================================= int menu() {int op4; do {system("cls"); cout<<"\n\t\t ____________________________________"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|********** PELICULA **********|"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|INGRESAR DATOS de la Pelicula [1] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|CONSULTA de la Pelicula [2] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|MODIFICAR DATOS de la Pelicula [3] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|ELIMINAR Pelicula [4] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|REPORTE (CARTELERA) [5] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|SALIR [6] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|____________________________________|"<<endl; cout<<"\n\n\n\t\t ____________________________________"<<endl; cout<<"\t\t|INGRESE SU OPCION ==> [ ]|\b\b\b";cin>>op4; cout<<"\t\t| |"; }while(op4<1||op4>6); return op4; } //========================================================= MENU CLIENTE========================================================= int menu2() {int op3; do {system("cls"); cout<<"\n\t\t ____________________________________"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|********** MENU PRINCIPAL **********|"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|INGRESAR DATOS DEL CLIENTE [1] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|Peliculas EN LA CARTELERA [2] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|COMPRAR [3] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|LISTA DE COMPRA [4] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|FACTURAR [5] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|____________________________________|"<<endl; cout<<"\n\n\t\t ____________________________________"<<endl; cout<<"\t\t|INGRESE SU OPCION ==> [ ]|\b\b\b";cin>>op3; cout<<"\t\t| |"; }while(op3<1||op3>5); return op3; } //========================================================= LECTURA ========================================================= void insertar() {system("cls"); char resp; int cod; do {system("cls"); cout<<"\t\t********** INGRESO DE DATOS **********"<<endl; cout<<"\t\t======================================"<<endl; cout<<"CODIGO: "; cin>>cod; f=fopen(archivo,"a+"); if (f==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE\n"; system("pause"); exit(1); } fread(&datos,sizeof(datos),1,f); while(!feof(f)) {if(datos.codigo==cod) {cout << "\n\n REGISTRO DUPLICADO"<<endl; fclose(f); system("pause"); return; } fread(&datos,sizeof(datos),1,f); } datos.codigo=cod; //Guarda el valor del codigo ingresado en el struct datos cout<<"NOMBRE de la Pelicula: "; fflush(stdin); gets(datos.name); cout<<"SIPNOSIS: "; gets(datos.sinopsis); cout<<"GENERO: "; fflush(stdin); gets(datos.genero); cout<<"DURACION: "; cin>>datos.duracion; do {cout<<"PRECIO de la Pelicula: "; cin>>datos.precio; if(datos.precio<0) cout<<"ERROR!!!! PRECIO NO VALIDO, POR FAVOR INGRESE OTRO"<<endl; }while(datos.precio<0); do {cout<<"Capacidad de la Pelicula: "; cin>>datos.capacidad; if(datos.capacidad<0) cout<<"ERROR!!!! CAPACIDAD NO VALIDA, POR FAVOR INGRESE OTRA"<<endl; }while(datos.capacidad<0); fwrite(&datos,sizeof(datos),1,f); cout<<"\n\n\t--- REGISTRO ARCHIVADO CON EXITO --- \n"; fclose(f); resp=continuar("\nDESEA INGRESAR otra Pelicula (S/N) ==> "); }while(resp=='S'); } //========================================================= REPORTE ========================================================= void reporte() {system("cls"); cout<<"\t\t******************** REPORTE ********************"<<endl; cout<<"\t\t================================================="<<endl<<endl; f=fopen(archivo,"r"); if(f==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE"<<endl; system("pause"); exit(1); } cout<<" _____________________________________________________________________________"<<endl; cout<<setw(30)<<"|=============================================================================|"<<endl; cout<<"|"<<setw(10)<<"CODIGO "<<setw(20)<<" NOMBRE"<<setw(20)<<"CAPC."<<setw(10)<<"PRECIO"<<" |"<<endl; cout<<setw(30)<<"|=============================================================================|"<<endl; fread(&datos,sizeof(datos),1,f); while(!feof(f)) { if(datos.codigo!=0){ cout<<"|"<<setw(10)<<datos.codigo<<setw(20)<<datos.name<<setw(20)<<datos.capacidad<<setw(10)<<datos.precio<<" |"<<endl; } fread(&datos,sizeof(datos),1,f); } cout<<setw(30)<<"|=============================================================================|"<<endl; cout<<"|_____________________________________________________________________________|"<<endl; fclose(f); cout<<"\n"; system("pause"); } //========================================================= CONSULTA (BUSQ. POR CODIGO) ========================================================= void consulta() {int bcod; char resp; int enc=0; do {system("cls"); cout<<"\t\t********** BUSQUEDA POR CODIGO **********"<<endl; cout<<"\t\t========================================="<<endl; f=fopen(archivo,"r+"); if(f==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE\n"; system("pause"); exit(1); } cout<<"INGRESE UN CODIGO VALIDO PARA SU BUSQUEDA: "; cin>>bcod; cout<<"\n\n\t\t********** DATOS DE LA BUSQUEDA **********"<<endl; cout<<"\t\t=========================================="<<endl; fread(&datos,sizeof(datos),1,f); cout<<"\t _______________________________________________________"<<endl; cout<<setw(30)<<"\t |=======================================================|"; while(!feof(f)) {if((datos.codigo==bcod)&&enc!=1) {mostrarpel(); enc=1; } fread(&datos,sizeof(datos),1,f); } cout<<setw(30)<<"\t |=======================================================|"; cout<<"\n\t |_______________________________________________________|"<<endl; if(enc==0) cout<<"\n\t--- NO EXISTE una Pelicula REGISTRADA CON ESTE CODIGO ---"<<endl; fclose(f); resp=continuar("\nDESEA REALIZAR OTRA BUSQUEDA (S/N) ==> "); enc=0; }while(resp=='S'); cout<<"\n --- FIN DE LA BUSQUEDA ---"<<endl; system("pause"); return; } //========================================================= MODIFICAR ========================================================= void modificar() {int op1; int cod; char resp; int enc=0; system("cls"); cout<<"\t\t********** MODIFICAR DATOS **********"<<endl; cout<<"\t\t====================================="<<endl<<endl; f=fopen(archivo,"r+"); if(f==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE"<<endl; system("pause"); exit(1); } g=fopen(temporal,"a+"); if(g==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE"<<endl; exit(1); system("pause"); } cout<<"INGRESE UN CODIGO VALIDO PARA SU BUSQUEDA: "; cin>>cod; fread(&datos,sizeof(datos),1,f); cout<<"\t _______________________________________________________"<<endl; cout<<setw(30)<<"\t |=======================================================|"; while(!feof(f)) {if(datos.codigo==cod) {mostrarpel(); cout<<setw(30)<<"\t |=======================================================|"; cout<<"\n\t |_______________________________________________________|"<<endl; system("pause"); do {do {system("cls"); cout<<"\n\t\t __________________________________________"<<endl; cout<<"\t\t|==========================================|"<<endl; cout<<"\t\t|********** ¿QUE DESEA MODIFICAR **********|"<<endl; cout<<"\t\t|==========================================|"<<endl; cout<<"\t\t|CODIGO [1] |"<<endl; cout<<"\t\t|==========================================|"<<endl; cout<<"\t\t|NOMBRE [2] |"<<endl; cout<<"\t\t|==========================================|"<<endl; cout<<"\t\t|CAPACIDAD [3] |"<<endl; cout<<"\t\t|==========================================|"<<endl; cout<<"\t\t|PRECIO [4] |"<<endl; cout<<"\t\t|==========================================|"<<endl; cout<<"\t\t|__________________________________________|"<<endl; cout<<"\n\n\n\t\t ____________________________________"<<endl; cout<<"\t\t|INGRESE SU OPCION ==> [ ]|\b\b\b";cin>>op1; cout<<"\t\t| |"; }while(op1<1||op1>4); switch(op1) {case 1: system("cls"); cout<<"\n\nNUEVO CODIGO: "; cin>>cod; f=fopen(archivo,"a+"); if (f==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE\n"; system("pause"); exit(1); } fread(&datos,sizeof(datos),1,f); while(!feof(f)) {if(datos.codigo==cod) {cout << "\n\n REGISTRO DUPLICADO"<<endl; fclose(f); system("pause"); return; } fread(&datos,sizeof(datos),1,f); } datos.codigo=cod; break; case 2:system("cls"); cout<<"\n\nNUEVO NOMBRE: "; fflush(stdin); gets(datos.name); break; case 3:do {system("cls"); cout<<"\n\nACTUALIZAR CAPACIDAD: "; cin>>datos.capacidad; }while(datos.capacidad<0); break; case 4:do {system("cls"); cout<<"\n\nNUEVO PRECIO: "; cin>>datos.precio; }while(datos.precio<0); break; } resp=continuar("\n\nDESEA MODIFICAR OTRO CAMPO (S/N) ==> "); }while(resp=='S'); enc=1; fwrite(&datos,sizeof(datos),1,g); } else fwrite(&datos,sizeof(datos),1,g); fread(&datos,sizeof(datos),1,f); } fclose(f); fclose(g); remove(archivo); rename(temporal, archivo); if(enc==0) cout<<"\n\t--- NO EXISTE una Pelicula REGISTRADA CON ESTE CODIGO ---"<<endl; else cout<<"\n\t--- REGISTRO ACTUALIZADO CON EXITO ---"<<endl; system("pause"); } //========================================================= ELIMINAR ========================================================= void eliminar() {system("cls"); int cod; char resp; cout<<"\t\t********** ELIMINACION **********"<<endl; cout<<"\t\t================================="<<endl; f=fopen(archivo,"r+"); if(f==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE"<<endl; system("pause"); exit(1); } cout<<"INGRESE UN CODIGO VALIDO PARA SU BUSQUEDA: "; cin>>cod; fread(&datos,sizeof(datos),1,f); cout<<"\t _______________________________________________________"<<endl; cout<<setw(30)<<"\t |=======================================================|"; while(!feof(f)) {if(datos.codigo==cod) {mostrarpel(); cout<<setw(30)<<"\t |=======================================================|"; cout<<"\n\t |_______________________________________________________|"<<endl; system("pause"); datos.codigo=0; strcpy(datos.name,""); datos.capacidad=0; datos.precio=0; resp=continuar("\nESTA SEGURO DE QUE DESEA ELIMINAR ESTE REGISTRO (S/N) ==> "); if(resp=='S') {fseek(f,ftell(f)-sizeof(datos),SEEK_SET); fwrite(&datos,sizeof(datos),1,f); cout<<"\n\t--- REGISTRO ELIMINADO CON EXITO ---"<<endl; } fclose(f); system("pause"); return; } fread(&datos,sizeof(datos),1,f); } cout <<"\n\rNO SE ENCUENTRA REGISTRO!!!\n"; fclose(f); system("pause"); return; } //========================================================= CINE ========================================================= void cine() {Pelicula datos[50]; int n=0,op; system("cls"); intro("ADMINISTRACION: CINE X"); do {op=menu(); switch(op) {case 1:insertar(); break; case 2:consulta(); break; case 3:modificar(); break; case 4:eliminar(); break; case 5:reporte(); break; } }while(op!=6); system("cls"); salida("REGISTRO COMPLETO"); } //========================================================= DATOS DEL CLIENTE ========================================================= void informacion(int &num) {system("cls"); char resp; system("cls"); cout<<"\t\t********** INGRESO DE DATOS DEL CLIENTE **********"<<endl; cout<<"\t\t=================================================="<<endl; cout<<"DNI: "; cin>>data.dni; cout<<"NOMBRE DEL CLIENTE: "; fflush(stdin); gets(data.nombre); cout<<"APELLIDO PATERNO: "; gets(data.apellidoPaterno); cout<<"APELLIDO PATERNO: "; gets(data.apellidoMaterno); cout<<"CORREO: "; fflush(stdin); gets(data.correo); cout<<"FECHA DE NACIMIENTO:\n"; do{ cout<<"Dia: "; cin>>data.fecha_nac.dia; }while(data.fecha_nac.dia<1||data.fecha_nac.dia>31); do{ cout<<"Mes: "; cin>>data.fecha_nac.mes; }while(data.fecha_nac.mes<1||data.fecha_nac.mes>12); do{ cout<<"Anio: "; cin>>data.fecha_nac.anio; }while(data.fecha_nac.anio<1900); cout<<"\n\n\t--- YA PUEDE PROCEDER --- \n"; num=1; //puntero que varia su valor con cada cliente q se registre system("pause"); } //========================================================= COMPROBADOR ========================================================= int comp(int cantd,char nom[30]) {int dat=0; int ind; int enc; f=fopen(archivo,"r+"); enc=0; if(f==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE"; system("pause"); exit(1); } fread(&datos,sizeof(datos),1,f); while(!feof(f)) {if(strcmp(nom,datos.name)==0&&enc!=1) {dat=datos.capacidad; enc=1; } fread(&datos,sizeof(datos),1,f); } fclose(f); if(enc==0) {cout<<"\n\t--- NO EXISTE UN PRODUCTO REGISTRADO CON ESTE NOMBRE ---"<<endl; return 2; } if(dat<cantd) {ind=0; } else ind=1; return ind; } //========================================================= COMPRAR ========================================================= void comprar(int &cont,float &tototal) {char bname[30]; char resp; int enc,ind; int cantd; int i; do {system("cls"); cout<<"\t\t********** COMPRAR **********"<<endl; cout<<"\t\t============================="<<endl; enc=0; cout<<"INGRESE EL NOMBRE de la Pelicula: "; fflush(stdin); gets(bname); do {cout<<"INGRESE LA CANTIDAD QUE DESEA COMPRAR: "; cin>>cantd; }while(cantd<0); ind=comp(cantd,bname); if(ind==0) {cout<<"\n\nLO SENTIMOS, NO CONTAMOS CON SUFICIENTES Entradas"<<endl; cout<<"POR FAVOR REVISE LA OPCION [2] PARA MAS INFORMACION\n"<<endl; system("pause"); return; } if(ind==2) {return; } f=fopen(archivo,"r+"); if(f==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE\n"; system("pause"); exit(1); } fread(&datos,sizeof(datos),1,f); while(!feof(f)) {if((strcmp(bname,datos.name)==0)&&enc!=1) //Almacena los datos del archivo en un array local para trabajar con la cantidad de entradas { temp[cont]=datos; temp[cont].capacidad=0; temp[cont].capacidad=temp[cont].capacidad+cantd; temp[cont].total=0; temp[cont].total=temp[cont].total+temp[cont].capacidad*temp[cont].precio; cont++; enc=1; } fread(&datos,sizeof(datos),1,f); } fclose(f); f=fopen(archivo,"r+"); if(f==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE"<<endl; system("pause"); exit(1); } g=fopen(temporal,"a+"); if(g==NULL) {cout<<"\n\n ERROR: EL ARCHIVO NO EXISTE"<<endl; exit(1); system("pause"); } fread(&datos,sizeof(datos),1,f); while(!feof(f)) {if(strcmp(datos.name,bname)==0) { {datos.capacidad=datos.capacidad-cantd; } fwrite(&datos,sizeof(datos),1,g); } else fwrite(&datos,sizeof(datos),1,g); fread(&datos,sizeof(datos),1,f); } fclose(f); fclose(g); remove(archivo); rename(temporal, archivo); if(enc==0) cout<<"\n\t--- NO EXISTE una Pelicula CON ESTE NOMBRE en la TAQUILLA ---"<<endl; fclose(f); resp=continuar("\nDESEA REALIZAR OTRA COMPRA (S/N) ==> "); }while(resp=='S'); cout<<"\n --- FIN DE LA COMPRA ---"<<endl; system("pause"); return; } //========================================================= LISTA COMPRAS ========================================================= void lista(char mensaje[50],int cont,float tototal,float &tot,float &igv) {system("cls"); int i; for(i=0;i<cont;i++) {tototal=tototal+temp[i].total; } cout<<"\t******************** "<<mensaje<<" ********************"<<endl; cout<<"\t=========================================================="<<endl<<endl; cout<<" _____________________________________________________________________________"<<endl; cout<<setw(30)<<"|=============================================================================|"<<endl; cout<<"|"<<setw(10)<<"CODIGO "<<setw(20)<<" NOMBRE"<<setw(20)<<"CANT."<<setw(10)<<"PRECIO"<<setw(10)<<"TOTAL"<<" |"<<endl; cout<<setw(30)<<"|=============================================================================|"<<endl; for(i=0;i<cont;i++) { cout<<"|"<<setw(10)<<temp[i].codigo<<setw(20)<<temp[i].name<<setw(20)<<temp[i].capacidad<<setw(10)<<temp[i].precio<<setw(10)<<temp[i].total<<setw(8)<<"|"<<endl; } cout<<setw(30)<<"|=============================================================================|"<<endl; cout<<"|"<<setw(10)<<"TOTAL: "<<setw(60)<<tototal<<" |"<<endl; cout<<"|_____________________________________________________________________________|"<<endl; system("pause"); tot=tototal; igv=tot*0.18; } //========================================================= VERIFICA ========================================================= int ver(int num) {system("cls"); if(num==0) {cout<<"\n\n\nPOR FAVOR INSERTE SU INFORMACION EN LA CASILLA [1], PARA CONTINUAR\n"<<endl; system("pause"); } return num; } //========================================================= FACTURA ========================================================= void factura(int cont,float tototal,float tot,float igv,int num,int &op) {system("cls"); int n; lista(" FACTURA",cont,tototal,tot,igv); cout<<setw(30)<<"|=============================================================================|"<<endl; cout<<setw(30)<<"|================================= CINE TECHIES :v ================================|"<<endl; cout<<setw(30)<<"|=============================================================================|"<<endl; cout<<"|"<<setw(8)<<"NOMBRE: "<<setw(69)<<data.nombre<<"|"<<endl; cout<<"|"<<setw(8)<<"A. PATERNO: "<<setw(66)<<data.apellidoPaterno<<"|"<<endl; cout<<"|"<<setw(8)<<"A. MATERNO: "<<setw(66)<<data.apellidoMaterno<<"|"<<endl; cout<<"|"<<setw(10)<<"FIRMA: ........................."<<setw(46)<<"|"<<endl; cout<<"|"<<setw(7)<<"CORREO: "<<setw(70)<<data.correo<<"|"<<endl; cout<<"|"<<setw(5)<<"IGV: "<<setw(66)<<igv<<" SOLES"<<"|"<<endl; cout<<"|"<<setw(10)<<"TOTAL A PAGAR: "<<setw(56)<<tot+igv<<" SOLES"<<"|"<<endl; cout<<"|_____________________________________________________________________________|"<<endl; system("pause"); op=6; } //========================================================= CLIENTE ========================================================= void cliente() {persona data[50]; Pelicula datos[50]; int op; int cont=0; float tototal=0; float igv=0,tot=0; int num=0; int n=0; system("cls"); intro("BIENVENIDO AL CINE X"); do {op=menu2(); switch(op) {case 1:informacion(num); break; case 2:reporte(); break; case 3:comprar(cont,tototal); break; case 4:lista("LISTA DE COMPRAS",cont,tototal,tot,igv); break; case 5:n=ver(num); if(n==0) break; factura(cont,tototal,tot,igv,num,op); } }while(op!=6); system("cls"); salida("GRACIAS POR SU PREFERENCIA"); } //========================================================= SELECCION ========================================================= int seleccion(int &n) {int op; {if(n==0) intro("PROYECTO DE CINE"); n++; } do {system("cls"); cout<<"\n\n\n\t\t ____________________________________"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|********** MENU PRINCIPAL **********|"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|MODO ADMINISTRACION [1] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|MODO CLIENTE [2] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|SALIR [3] |"<<endl; cout<<"\t\t|====================================|"<<endl; cout<<"\t\t|____________________________________|"<<endl; cout<<"\n\n\n\t\t ____________________________________"<<endl; cout<<"\t\t|INGRESE SU OPCION ==> [ ]|\b\b\b";cin>>op; cout<<"\t\t| |"; }while(op<1||op>3); return op; } //========================================================= PRINCIPAL ========================================================= int main() {Pelicula datos[50]; int n=0,op,tam,sel; float comp,total; do {sel=seleccion(n); switch(sel) {case 1:cine(); break; case 2:cliente(); break; } }while(sel!=3); system("cls"); salida("GRACIAS POR USAR EL PROGRAMA"); return 0; }
[ "diegohuarez123@gmail.com" ]
diegohuarez123@gmail.com
2cee8d2bb8ff300e6d477a21a4dbd004dddd5789
85c10166e26f633bf61ea32277e980d5b16325a5
/Arduino Kurs 2016/_9_Mapping/_9_Mapping_Loesung.ino
ba045f8b6d71fd3853e281d7488e7689b79fa35f
[]
no_license
khinsberger/ASL-GoKart
b21d3c540ce9680dd158082635f80137e8f17884
071b388506ea4013792cb3ef05b2d6a75b6d0952
refs/heads/master
2020-12-17T04:46:12.711368
2016-10-11T17:03:31
2016-10-11T17:03:31
51,257,081
1
0
null
null
null
null
UTF-8
C++
false
false
552
ino
/* * Mini-Projekt 9: LED mit einem Potentiometer steuern * Loesung */ // Variablen für die Pins initialisieren const int potiPin = A0; const int ledPin = 11; void setup() { // Pins deklarieren: pinMode(potiPin, INPUT); pinMode(ledPin, OUTPUT); } void loop() { // Wert des Potentiometers auslesen und in einer Variablen speichern int potiStatus = analogRead(potiPin); // Helligkeit durch "Mapping" berechnen int helligkeit = map(potiStatus, 0, 1024, 0, 255); // Helligkeit an die LED ausgeben analogWrite(ledPin, helligkeit); }
[ "k.hinsberger@googlemail.com" ]
k.hinsberger@googlemail.com
eb8d0931a347d12f9b285fab8c97aae4f3e1bb6b
d156e0359e72405a4387146d054f8a2db8ec726c
/MinoI.cpp
f05de9cdae434882c505382d7fdedbc590234a70
[]
no_license
mystery110/CPP_Practice_Inheritance
a6a670e50ccf1d140e8a13436399299660171f25
a8058ef024bf4f0ccd652aa9c30ddd48097a530f
refs/heads/master
2020-04-25T17:16:26.457430
2019-02-27T15:34:31
2019-02-27T15:34:31
172,941,429
0
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
#include"MinoI.h" char I_arr [2][4][4] = {{{'0','0','1','0'}, {'0','0','1','0'}, {'0','0','1','0'}, {'0','0','1','0'}}, {{'0','0','0','0'}, {'0','0','0','0'}, {'1','1','1','1'}, {'0','0','0','0'}}}; MinoI::MinoI():Mino(1){} void MinoI::paint(){ for(int i=0;i<4;++i){ for(int j=0;j<4;++j) cout << I_arr[R_I][i][j]; cout << endl;}} //MinoI::~MinoI(){ // delete this;}
[ "f74067094@mail.ncku.edu.tw" ]
f74067094@mail.ncku.edu.tw
0fcb76d4b76e147be51dd24556e601c8df73a921
f24fddf2415ed31237068039f9db992832ff0bf7
/lib/DHParam/src/DHParam.h
d51fffbe1cf4010517a12400213e88266f2a49d5
[]
no_license
boernworst/6dof_robot_arm-self
bf93a124efd602ac0aa33baad8499f7eb41a70c9
4e82329e2ea779e7c9cd4b2c9e6e8d745854bfa1
refs/heads/master
2022-11-21T20:50:44.163926
2020-07-15T00:03:49
2020-07-15T00:03:49
279,721,949
0
0
null
null
null
null
UTF-8
C++
false
false
615
h
/*   DHParam.h - Library for implementing Denavit-Hartenberg Parameters.   Created by Nathan Rukavina, July 17, 2017.   Released into the public domain. */ #ifndef DHParam_h #define DHParam_h #include "Arduino.h" class DHParam { public: DHParam(float theta_, float a_, float d_, float alpha_); void getTransformation(float arr[4][4], DHParam from); void setTheta(float theta_); void setA(float a_); void setD(float d_); void setAlpha(float alpha_); float getTheta(); float getA(); float getD(); float getAlpha(); private: float theta; float a; float d; float alpha; }; #endif
[ "basjfellinger@gmail.com" ]
basjfellinger@gmail.com
4245e698ac41ab9c6e5c1abcbf4f0879a60397f3
fc0a25351fa839c241e28be0f640301056f1ec20
/gucc-build-desktop-Qt_4_8_1_in_PATH__System__Release/gucc-build-desktop-Qt_4_8_1_in_PATH__System__Release/.ui/ui_GMainWindow.h
17604499ea8f9ccdec559ab3a4fc5843fae9bb0e
[]
no_license
Pulkit13/Code-Counting-Toolset
11896b32a26388a0780b7c4bd1c159149e6c9c72
d52fc5ab2a809618c34911dae0c6407aa4822a4b
refs/heads/master
2016-09-11T08:00:41.487871
2013-09-11T07:11:59
2013-09-11T07:11:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,815
h
/******************************************************************************** ** Form generated from reading UI file 'GMainWindow.ui' ** ** Created: Tue Apr 16 17:18:32 2013 ** by: Qt User Interface Compiler version 4.8.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_GMAINWINDOW_H #define UI_GMAINWINDOW_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QCheckBox> #include <QtGui/QFormLayout> #include <QtGui/QGroupBox> #include <QtGui/QHBoxLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> #include <QtGui/QListWidget> #include <QtGui/QMainWindow> #include <QtGui/QMenu> #include <QtGui/QMenuBar> #include <QtGui/QProgressBar> #include <QtGui/QPushButton> #include <QtGui/QSpacerItem> #include <QtGui/QStatusBar> #include <QtGui/QTextEdit> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_GMainWindowClass { public: QAction *actionFile_Open; QAction *actionExit; QAction *actionExtensions; QAction *actionUser_Manual; QAction *actionAbout; QAction *actionEdit_Extensions; QWidget *centralwidget; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout_4; QFormLayout *formLayout; QLabel *lblFilesA; QListWidget *lwFileListA; QListWidget *lwExtensionListA; QHBoxLayout *horizontalLayout_6; QPushButton *btnAddFileA; QLabel *lblAddFileA; QPushButton *btnRemoveFileA; QLabel *lblRemoveFileA; QPushButton *btnAddFolderA; QLabel *lblAddFolderA; QSpacerItem *horizontalSpacer; QFormLayout *formLayout_2; QLabel *lblFilesB; QListWidget *lwFileListB; QListWidget *lwExtensionListB; QHBoxLayout *horizontalLayout_2; QPushButton *btnAddFileB; QLabel *lblAddFileB; QPushButton *btnRemoveFileB; QLabel *lblRemoveFileB; QPushButton *btnAddFolderB; QLabel *lblAddFolderB; QSpacerItem *verticalSpacer_2; QGroupBox *grpbArguments; QHBoxLayout *horizontalLayout; QCheckBox *chkDifferencing; QCheckBox *chkAsciiOut; QCheckBox *chkNoComplex; QCheckBox *chkNoDup; QCheckBox *chkLegacyOut; QCheckBox *chkModThreshold; QLineEdit *txtModThreshold; QCheckBox *chkDupThreshold; QLineEdit *txtDupThreshold; QCheckBox *chkTruncThreshold; QLineEdit *txtTruncThreshold; QCheckBox *chkExtensionFile; QPushButton *btnCount; QSpacerItem *verticalSpacer; QHBoxLayout *horizontalLayout_3; QLabel *lblLog; QTextEdit *txtLog; QProgressBar *progressBar; QMenuBar *menubar; QMenu *menuAbout; QMenu *menuHelp; QStatusBar *statusbar; void setupUi(QMainWindow *GMainWindowClass) { if (GMainWindowClass->objectName().isEmpty()) GMainWindowClass->setObjectName(QString::fromUtf8("GMainWindowClass")); GMainWindowClass->resize(976, 557); QIcon icon; icon.addFile(QString::fromUtf8(":/images/gucc.png"), QSize(), QIcon::Normal, QIcon::Off); GMainWindowClass->setWindowIcon(icon); actionFile_Open = new QAction(GMainWindowClass); actionFile_Open->setObjectName(QString::fromUtf8("actionFile_Open")); actionExit = new QAction(GMainWindowClass); actionExit->setObjectName(QString::fromUtf8("actionExit")); actionExtensions = new QAction(GMainWindowClass); actionExtensions->setObjectName(QString::fromUtf8("actionExtensions")); actionUser_Manual = new QAction(GMainWindowClass); actionUser_Manual->setObjectName(QString::fromUtf8("actionUser_Manual")); actionAbout = new QAction(GMainWindowClass); actionAbout->setObjectName(QString::fromUtf8("actionAbout")); actionEdit_Extensions = new QAction(GMainWindowClass); actionEdit_Extensions->setObjectName(QString::fromUtf8("actionEdit_Extensions")); centralwidget = new QWidget(GMainWindowClass); centralwidget->setObjectName(QString::fromUtf8("centralwidget")); verticalLayout = new QVBoxLayout(centralwidget); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); horizontalLayout_4 = new QHBoxLayout(); horizontalLayout_4->setObjectName(QString::fromUtf8("horizontalLayout_4")); formLayout = new QFormLayout(); formLayout->setObjectName(QString::fromUtf8("formLayout")); lblFilesA = new QLabel(centralwidget); lblFilesA->setObjectName(QString::fromUtf8("lblFilesA")); formLayout->setWidget(0, QFormLayout::LabelRole, lblFilesA); lwFileListA = new QListWidget(centralwidget); lwFileListA->setObjectName(QString::fromUtf8("lwFileListA")); lwFileListA->setSelectionMode(QAbstractItemView::MultiSelection); formLayout->setWidget(1, QFormLayout::LabelRole, lwFileListA); lwExtensionListA = new QListWidget(centralwidget); lwExtensionListA->setObjectName(QString::fromUtf8("lwExtensionListA")); lwExtensionListA->setSelectionMode(QAbstractItemView::ExtendedSelection); formLayout->setWidget(1, QFormLayout::FieldRole, lwExtensionListA); horizontalLayout_6 = new QHBoxLayout(); horizontalLayout_6->setObjectName(QString::fromUtf8("horizontalLayout_6")); btnAddFileA = new QPushButton(centralwidget); btnAddFileA->setObjectName(QString::fromUtf8("btnAddFileA")); QIcon icon1; icon1.addFile(QString::fromUtf8(":/images/plus_sign.png"), QSize(), QIcon::Normal, QIcon::Off); btnAddFileA->setIcon(icon1); btnAddFileA->setIconSize(QSize(22, 22)); horizontalLayout_6->addWidget(btnAddFileA); lblAddFileA = new QLabel(centralwidget); lblAddFileA->setObjectName(QString::fromUtf8("lblAddFileA")); horizontalLayout_6->addWidget(lblAddFileA); btnRemoveFileA = new QPushButton(centralwidget); btnRemoveFileA->setObjectName(QString::fromUtf8("btnRemoveFileA")); btnRemoveFileA->setEnabled(true); QIcon icon2; icon2.addFile(QString::fromUtf8(":/images/minus_sign.png"), QSize(), QIcon::Normal, QIcon::Off); btnRemoveFileA->setIcon(icon2); btnRemoveFileA->setIconSize(QSize(22, 22)); horizontalLayout_6->addWidget(btnRemoveFileA); lblRemoveFileA = new QLabel(centralwidget); lblRemoveFileA->setObjectName(QString::fromUtf8("lblRemoveFileA")); horizontalLayout_6->addWidget(lblRemoveFileA); btnAddFolderA = new QPushButton(centralwidget); btnAddFolderA->setObjectName(QString::fromUtf8("btnAddFolderA")); QIcon icon3; icon3.addFile(QString::fromUtf8(":/images/add_folder.png"), QSize(), QIcon::Normal, QIcon::Off); btnAddFolderA->setIcon(icon3); btnAddFolderA->setIconSize(QSize(22, 22)); horizontalLayout_6->addWidget(btnAddFolderA); lblAddFolderA = new QLabel(centralwidget); lblAddFolderA->setObjectName(QString::fromUtf8("lblAddFolderA")); horizontalLayout_6->addWidget(lblAddFolderA); formLayout->setLayout(2, QFormLayout::SpanningRole, horizontalLayout_6); horizontalLayout_4->addLayout(formLayout); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_4->addItem(horizontalSpacer); formLayout_2 = new QFormLayout(); formLayout_2->setObjectName(QString::fromUtf8("formLayout_2")); lblFilesB = new QLabel(centralwidget); lblFilesB->setObjectName(QString::fromUtf8("lblFilesB")); formLayout_2->setWidget(0, QFormLayout::LabelRole, lblFilesB); lwFileListB = new QListWidget(centralwidget); lwFileListB->setObjectName(QString::fromUtf8("lwFileListB")); formLayout_2->setWidget(1, QFormLayout::LabelRole, lwFileListB); lwExtensionListB = new QListWidget(centralwidget); lwExtensionListB->setObjectName(QString::fromUtf8("lwExtensionListB")); formLayout_2->setWidget(1, QFormLayout::FieldRole, lwExtensionListB); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); btnAddFileB = new QPushButton(centralwidget); btnAddFileB->setObjectName(QString::fromUtf8("btnAddFileB")); btnAddFileB->setIcon(icon1); btnAddFileB->setIconSize(QSize(22, 22)); horizontalLayout_2->addWidget(btnAddFileB); lblAddFileB = new QLabel(centralwidget); lblAddFileB->setObjectName(QString::fromUtf8("lblAddFileB")); horizontalLayout_2->addWidget(lblAddFileB); btnRemoveFileB = new QPushButton(centralwidget); btnRemoveFileB->setObjectName(QString::fromUtf8("btnRemoveFileB")); btnRemoveFileB->setEnabled(true); btnRemoveFileB->setIcon(icon2); btnRemoveFileB->setIconSize(QSize(22, 22)); horizontalLayout_2->addWidget(btnRemoveFileB); lblRemoveFileB = new QLabel(centralwidget); lblRemoveFileB->setObjectName(QString::fromUtf8("lblRemoveFileB")); horizontalLayout_2->addWidget(lblRemoveFileB); btnAddFolderB = new QPushButton(centralwidget); btnAddFolderB->setObjectName(QString::fromUtf8("btnAddFolderB")); btnAddFolderB->setIcon(icon3); btnAddFolderB->setIconSize(QSize(22, 22)); horizontalLayout_2->addWidget(btnAddFolderB); lblAddFolderB = new QLabel(centralwidget); lblAddFolderB->setObjectName(QString::fromUtf8("lblAddFolderB")); horizontalLayout_2->addWidget(lblAddFolderB); formLayout_2->setLayout(2, QFormLayout::SpanningRole, horizontalLayout_2); horizontalLayout_4->addLayout(formLayout_2); verticalLayout->addLayout(horizontalLayout_4); verticalSpacer_2 = new QSpacerItem(20, 28, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer_2); grpbArguments = new QGroupBox(centralwidget); grpbArguments->setObjectName(QString::fromUtf8("grpbArguments")); horizontalLayout = new QHBoxLayout(grpbArguments); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); chkDifferencing = new QCheckBox(grpbArguments); chkDifferencing->setObjectName(QString::fromUtf8("chkDifferencing")); horizontalLayout->addWidget(chkDifferencing); chkAsciiOut = new QCheckBox(grpbArguments); chkAsciiOut->setObjectName(QString::fromUtf8("chkAsciiOut")); horizontalLayout->addWidget(chkAsciiOut); chkNoComplex = new QCheckBox(grpbArguments); chkNoComplex->setObjectName(QString::fromUtf8("chkNoComplex")); horizontalLayout->addWidget(chkNoComplex); chkNoDup = new QCheckBox(grpbArguments); chkNoDup->setObjectName(QString::fromUtf8("chkNoDup")); horizontalLayout->addWidget(chkNoDup); chkLegacyOut = new QCheckBox(grpbArguments); chkLegacyOut->setObjectName(QString::fromUtf8("chkLegacyOut")); horizontalLayout->addWidget(chkLegacyOut); chkModThreshold = new QCheckBox(grpbArguments); chkModThreshold->setObjectName(QString::fromUtf8("chkModThreshold")); chkModThreshold->setEnabled(false); horizontalLayout->addWidget(chkModThreshold); txtModThreshold = new QLineEdit(grpbArguments); txtModThreshold->setObjectName(QString::fromUtf8("txtModThreshold")); txtModThreshold->setEnabled(false); horizontalLayout->addWidget(txtModThreshold); chkDupThreshold = new QCheckBox(grpbArguments); chkDupThreshold->setObjectName(QString::fromUtf8("chkDupThreshold")); horizontalLayout->addWidget(chkDupThreshold); txtDupThreshold = new QLineEdit(grpbArguments); txtDupThreshold->setObjectName(QString::fromUtf8("txtDupThreshold")); txtDupThreshold->setEnabled(false); horizontalLayout->addWidget(txtDupThreshold); chkTruncThreshold = new QCheckBox(grpbArguments); chkTruncThreshold->setObjectName(QString::fromUtf8("chkTruncThreshold")); horizontalLayout->addWidget(chkTruncThreshold); txtTruncThreshold = new QLineEdit(grpbArguments); txtTruncThreshold->setObjectName(QString::fromUtf8("txtTruncThreshold")); txtTruncThreshold->setEnabled(false); horizontalLayout->addWidget(txtTruncThreshold); chkExtensionFile = new QCheckBox(grpbArguments); chkExtensionFile->setObjectName(QString::fromUtf8("chkExtensionFile")); horizontalLayout->addWidget(chkExtensionFile); btnCount = new QPushButton(grpbArguments); btnCount->setObjectName(QString::fromUtf8("btnCount")); QIcon icon4; icon4.addFile(QString::fromUtf8(":/images/start.png"), QSize(), QIcon::Normal, QIcon::Off); btnCount->setIcon(icon4); btnCount->setIconSize(QSize(60, 60)); horizontalLayout->addWidget(btnCount); verticalLayout->addWidget(grpbArguments); verticalSpacer = new QSpacerItem(20, 28, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3")); lblLog = new QLabel(centralwidget); lblLog->setObjectName(QString::fromUtf8("lblLog")); horizontalLayout_3->addWidget(lblLog); txtLog = new QTextEdit(centralwidget); txtLog->setObjectName(QString::fromUtf8("txtLog")); txtLog->setEnabled(false); horizontalLayout_3->addWidget(txtLog); verticalLayout->addLayout(horizontalLayout_3); progressBar = new QProgressBar(centralwidget); progressBar->setObjectName(QString::fromUtf8("progressBar")); progressBar->setValue(0); verticalLayout->addWidget(progressBar); GMainWindowClass->setCentralWidget(centralwidget); menubar = new QMenuBar(GMainWindowClass); menubar->setObjectName(QString::fromUtf8("menubar")); menubar->setGeometry(QRect(0, 0, 976, 25)); menubar->setProperty("windowicon", QVariant(icon)); menuAbout = new QMenu(menubar); menuAbout->setObjectName(QString::fromUtf8("menuAbout")); menuHelp = new QMenu(menubar); menuHelp->setObjectName(QString::fromUtf8("menuHelp")); GMainWindowClass->setMenuBar(menubar); statusbar = new QStatusBar(GMainWindowClass); statusbar->setObjectName(QString::fromUtf8("statusbar")); GMainWindowClass->setStatusBar(statusbar); menubar->addAction(menuAbout->menuAction()); menubar->addAction(menuHelp->menuAction()); menuAbout->addAction(actionFile_Open); menuAbout->addSeparator(); menuAbout->addAction(actionExtensions); menuAbout->addAction(actionEdit_Extensions); menuAbout->addSeparator(); menuAbout->addAction(actionExit); menuHelp->addAction(actionUser_Manual); menuHelp->addAction(actionAbout); retranslateUi(GMainWindowClass); QMetaObject::connectSlotsByName(GMainWindowClass); } // setupUi void retranslateUi(QMainWindow *GMainWindowClass) { GMainWindowClass->setWindowTitle(QApplication::translate("GMainWindowClass", "Unified Code Counter (UCC)", 0, QApplication::UnicodeUTF8)); actionFile_Open->setText(QApplication::translate("GMainWindowClass", "File Open", 0, QApplication::UnicodeUTF8)); actionExit->setText(QApplication::translate("GMainWindowClass", "Exit", 0, QApplication::UnicodeUTF8)); actionExtensions->setText(QApplication::translate("GMainWindowClass", "View Extensions", 0, QApplication::UnicodeUTF8)); actionUser_Manual->setText(QApplication::translate("GMainWindowClass", "User Manual", 0, QApplication::UnicodeUTF8)); actionAbout->setText(QApplication::translate("GMainWindowClass", "About", 0, QApplication::UnicodeUTF8)); actionEdit_Extensions->setText(QApplication::translate("GMainWindowClass", "Edit Extensions", 0, QApplication::UnicodeUTF8)); lblFilesA->setText(QApplication::translate("GMainWindowClass", "Files To Count:", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP btnAddFileA->setToolTip(QApplication::translate("GMainWindowClass", "Add File", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP btnAddFileA->setText(QString()); lblAddFileA->setText(QApplication::translate("GMainWindowClass", "Add File", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP btnRemoveFileA->setToolTip(QApplication::translate("GMainWindowClass", "Remove File", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP btnRemoveFileA->setText(QString()); lblRemoveFileA->setText(QApplication::translate("GMainWindowClass", "Remove File", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP btnAddFolderA->setToolTip(QApplication::translate("GMainWindowClass", "Add Folder", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP btnAddFolderA->setText(QString()); lblAddFolderA->setText(QApplication::translate("GMainWindowClass", "Add Folder", 0, QApplication::UnicodeUTF8)); lblFilesB->setText(QApplication::translate("GMainWindowClass", "File Set B to Differentiate:", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP btnAddFileB->setToolTip(QApplication::translate("GMainWindowClass", "Add File", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP btnAddFileB->setText(QString()); lblAddFileB->setText(QApplication::translate("GMainWindowClass", "Add File", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP btnRemoveFileB->setToolTip(QApplication::translate("GMainWindowClass", "Remove File", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP btnRemoveFileB->setText(QString()); lblRemoveFileB->setText(QApplication::translate("GMainWindowClass", "Remove File", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP btnAddFolderB->setToolTip(QApplication::translate("GMainWindowClass", "Add Folder", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP btnAddFolderB->setText(QString()); lblAddFolderB->setText(QApplication::translate("GMainWindowClass", "Add Folder", 0, QApplication::UnicodeUTF8)); grpbArguments->setTitle(QApplication::translate("GMainWindowClass", "Command Line Arguments", 0, QApplication::UnicodeUTF8)); chkDifferencing->setText(QApplication::translate("GMainWindowClass", "Differencing", 0, QApplication::UnicodeUTF8)); chkAsciiOut->setText(QApplication::translate("GMainWindowClass", "-ascii", 0, QApplication::UnicodeUTF8)); chkNoComplex->setText(QApplication::translate("GMainWindowClass", "-nocomplex", 0, QApplication::UnicodeUTF8)); chkNoDup->setText(QApplication::translate("GMainWindowClass", "-nodup", 0, QApplication::UnicodeUTF8)); chkLegacyOut->setText(QApplication::translate("GMainWindowClass", "-legacy", 0, QApplication::UnicodeUTF8)); chkModThreshold->setText(QApplication::translate("GMainWindowClass", "-t#", 0, QApplication::UnicodeUTF8)); txtModThreshold->setText(QApplication::translate("GMainWindowClass", "60", 0, QApplication::UnicodeUTF8)); chkDupThreshold->setText(QApplication::translate("GMainWindowClass", "-tdup #", 0, QApplication::UnicodeUTF8)); txtDupThreshold->setText(QApplication::translate("GMainWindowClass", "0", 0, QApplication::UnicodeUTF8)); chkTruncThreshold->setText(QApplication::translate("GMainWindowClass", "-trunc #", 0, QApplication::UnicodeUTF8)); txtTruncThreshold->setText(QApplication::translate("GMainWindowClass", "10000", 0, QApplication::UnicodeUTF8)); chkExtensionFile->setText(QApplication::translate("GMainWindowClass", "extFile", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP btnCount->setToolTip(QApplication::translate("GMainWindowClass", "Run Code Count", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP btnCount->setText(QString()); lblLog->setText(QApplication::translate("GMainWindowClass", "Log:", 0, QApplication::UnicodeUTF8)); menuAbout->setTitle(QApplication::translate("GMainWindowClass", "File", 0, QApplication::UnicodeUTF8)); menuHelp->setTitle(QApplication::translate("GMainWindowClass", "Help", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class GMainWindowClass: public Ui_GMainWindowClass {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_GMAINWINDOW_H
[ "pulkit.maheshwari13@yahoo.com" ]
pulkit.maheshwari13@yahoo.com
59c54ac452f0410e50d4ac1d59425e4af158124d
41b3dc19df92c63a34ac4d0965557f8bc8e11b3c
/Algorithms/Dynamic Programming/LCS_TopDown.cpp
087e0915c9cb234dee33d5d0e2c616a50af068de
[]
no_license
AyushSri19-777/Coding-2020
6153228dad129f8bdbb8923bfe4c9ffacafb2e98
8585c2ec2573871a182c72183f372416039019e7
refs/heads/master
2022-12-24T20:46:49.235973
2020-10-01T18:39:33
2020-10-01T18:39:33
259,876,021
0
3
null
2020-10-01T18:39:34
2020-04-29T09:02:41
C++
UTF-8
C++
false
false
742
cpp
#include <iostream> #include <string.h> using namespace std; int LCS(string x,string y,int n,int m) { int t[n+1][m+1]; for(int i=0;i<n+1;i++) { for(int j=0;j<m+1;j++) { if(i==0||j==0) t[i][j]=0; } } for(int i=1;i<n+1;i++) { for(int j=1;j<m+1;j++) { if(x[i-1]==y[j-1]) t[i][j]=1+t[i-1][j-1]; else { t[i][j]=max(t[i-1][j],t[i][j-1]); } } } return t[n][m]; } int main() { string x,y; int n,m; cout<<"Enter two strings\n"; cin>>x>>y; n=x.length(); m=y.length(); cout<<"The length of longest common subsequence= "<<LCS(x,y,n,m); }
[ "sri.ayush777@gmail.com" ]
sri.ayush777@gmail.com
ac870ac7cb1b7f221bcfec1ebb2f92bf4a5964eb
26eb0ecee7e9ae0fa75793a57fc51cc7659b5971
/Amid-summer.cpp
ef7f1a78d9a0d265f4256e11608092663fa4d953
[]
no_license
RalphVita/ProgramacaoCompetitiva
74c1bf47a840b3c139b56438a86e668307b4f3e2
04b62136f97146873de52a928ef90e2ff135a571
refs/heads/main
2023-01-30T09:26:46.280163
2020-12-14T16:10:16
2020-12-14T16:10:16
300,580,281
0
0
null
null
null
null
UTF-8
C++
false
false
2,089
cpp
#include <iostream> #include <algorithm> #include <vector> #include <map> #include <utility> #include <set> #include <numeric> using namespace std; int Minimizar(vector<int> &v, int a, map<int,pair<set<int>,int>> &map, int &minSum){ int sum = 0; for (auto x: v){ sum += abs(x-a); } //A partir do momento que a soma é maior, todas outras serão if(sum > minSum) return 0; map[sum].first.insert(a);//Registra A ordernado nessa soma map[sum].second++;//Quantas vezes deu essa soma minSum = min(sum,minSum); return 1; } void Minimizar(vector<int> v){ map<int,pair<set<int>,int>> map; int A, countA = 0, totalA; int sum = 0, minSum = INT32_MAX; //Reparei que as minimas somas estão em torno da média int mean = std::accumulate(v.begin(), v.end(), 0.0)/v.size(); //E se for interando A do minimo até o máximo, as somas vão diminuindo, //em torna da média é minima, e depois aumenta //Busca da média pra cima, e para quando acha uma soma maior que a minima for (int a = mean; a <= *max_element(v.begin(),v.end()) ; ++a) { if(!Minimizar(v,a,map,minSum)) break; } //Busca da média pra baixo e para quando acha uma soma maior que a minima for (int a = mean-1; a >= *min_element(v.begin(),v.end()); --a) { if(!Minimizar(v,a,map,minSum)) break; } //Menor A A = *map.begin()->second.first.begin(); //Quantos da entrada tem a soma minima for (auto s: map.begin()->second.first) countA += count(v.begin(), v.end(),s); //Quantos inteiros satisfazem A totalA = map.begin()->second.second; cout << A << " " << countA << " " << totalA << endl; } int main(){ int n,x; vector<int> v; while (!cin.eof()) { if(cin >> n){ for (int i = 0; i < n; ++i) { cin >> x; v.push_back(x); } Minimizar(v); v.clear(); } } }
[ "ralph.vita@gmail.com" ]
ralph.vita@gmail.com
f404c204fcd942835dba16926a36283ada90d480
39e348a6cfdc365a49b03695a3a86f92aa72fd2b
/C++/chapter18/ex1809/EX1809.cpp
5b3953d685d33682877b66bfde05d1f465812f8b
[]
no_license
qiuyongchen/code_saver
fd646e969774b190d764f709c4233e6283af84f1
afbec799e72901e85e9434bbe3cc745d9735fc6f
refs/heads/master
2021-01-10T04:48:00.349287
2016-02-21T04:18:52
2016-02-21T04:18:52
45,052,084
1
0
null
null
null
null
UTF-8
C++
false
false
730
cpp
// read in several strings and print only those ending in 'r' or 'ay', // only lowercase letter should be consider. #include <iostream> #include <string> using namespace std; int main() { string str; cout << "how many strings do you want to check out? :\n"; int n; cin >> n; while (n--) { cout << "input the string:\n"; cin >> str; if (str[str.length() - 1] == 'r') { cout << "this string is ok: " << str << endl; } else if (str[str.length() - 1] == 'y' && str[str.length() - 2] == 'a') { cout << "this string is ok: " << str << endl; } else { cout << "this string is not ok" << endl; } } return 0; }
[ "qiuych3@mail2.sysu.edu.cn" ]
qiuych3@mail2.sysu.edu.cn
8a8ac7eec7f20439523dc2818f806b1d2004b4e6
06954096d7b4d0732379f6354f8a355af6070831
/src/game/shared/swarm/asw_weapon_railgun_shared.cpp
d55cb0317e9f50bfc544096c72b972ba61b6dc52
[]
no_license
Nightgunner5/Jastian-Summer
9ee590bdac8d5cf281f844d1be3f1f5709ae4b91
22749cf0839bbb559bd13ec7e6a5af4458b8bdb7
refs/heads/master
2016-09-06T15:55:32.938564
2011-04-16T17:57:12
2011-04-16T17:57:12
1,446,629
1
1
null
null
null
null
UTF-8
C++
false
false
22,548
cpp
#include "cbase.h" #include "asw_weapon_railgun_shared.h" #include "in_buttons.h" #ifdef CLIENT_DLL #define CASW_Weapon C_ASW_Weapon #define CASW_Marine C_ASW_Marine #define CBasePlayer C_BasePlayer #include "c_asw_player.h" #include "c_asw_weapon.h" #include "c_asw_marine.h" #include "c_asw_railgun_beam.h" #include "iviewrender_beams.h" #include "c_asw_marine_resource.h" #include "precache_register.h" #include "c_te_effect_dispatch.h" #else #include "asw_lag_compensation.h" #include "asw_marine.h" #include "asw_player.h" #include "asw_weapon.h" #include "npcevent.h" #include "shot_manipulator.h" #include "te_effect_dispatch.h" #include "asw_marine_resource.h" #include "asw_marine_speech.h" #include "decals.h" #include "ammodef.h" #include "asw_weapon_ammo_bag_shared.h" #include "asw_rocket.h" #endif #include "asw_marine_skills.h" #include "asw_weapon_parse.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //#define ASW_RAILGUN_SWEEP_STYLE 1 // makes railgun do hull sweep style damage //#define ASW_RAILGUN_WIDE_SWEEP 1 // makes railgun do a wide low damage sweep in addition to the above #define ASW_RAILGUN_BURST_COUNT 3 // how many bullets are fired in each burst #define ASW_RAILGUN_BURST_INTERVAL 0.12f // time between each bullet in a burst IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Weapon_Railgun, DT_ASW_Weapon_Railgun ) BEGIN_NETWORK_TABLE( CASW_Weapon_Railgun, DT_ASW_Weapon_Railgun ) #ifdef CLIENT_DLL // recvprops RecvPropTime( RECVINFO( m_fSlowTime ) ), RecvPropInt(RECVINFO(m_iRailBurst)), #else // sendprops SendPropTime( SENDINFO( m_fSlowTime ) ), SendPropInt( SENDINFO(m_iRailBurst), Q_log2( ASW_RAILGUN_BURST_COUNT ) + 1, SPROP_UNSIGNED ), #endif END_NETWORK_TABLE() #ifdef CLIENT_DLL BEGIN_PREDICTION_DATA( CASW_Weapon_Railgun ) DEFINE_PRED_FIELD_TOL( m_fSlowTime, FIELD_FLOAT, FTYPEDESC_INSENDTABLE, TD_MSECTOLERANCE ), DEFINE_PRED_FIELD( m_iRailBurst, FIELD_INTEGER, FTYPEDESC_INSENDTABLE ) END_PREDICTION_DATA() #endif LINK_ENTITY_TO_CLASS( asw_weapon_railgun, CASW_Weapon_Railgun ); PRECACHE_WEAPON_REGISTER(asw_weapon_railgun); extern ConVar asw_weapon_max_shooting_distance; ConVar asw_railgun_force_scale("asw_railgun_force_scale", "60.0f", FCVAR_REPLICATED, "Force of railgun shots"); #ifndef CLIENT_DLL extern ConVar asw_debug_marine_damage; //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CASW_Weapon_Railgun ) END_DATADESC() #else //Precache the effects PRECACHE_REGISTER_BEGIN( GLOBAL, ASWPrecacheEffectRailgun ) PRECACHE( MATERIAL, "swarm/effects/railgun" ) PRECACHE_REGISTER_END() #endif /* not client */ CASW_Weapon_Railgun::CASW_Weapon_Railgun() { m_fSlowTime = 0; m_iRailBurst = 0; } CASW_Weapon_Railgun::~CASW_Weapon_Railgun() { } void CASW_Weapon_Railgun::Precache() { PrecacheModel("swarm/effects/railgun.vmt"); PrecacheScriptSound("ASW_Railgun.Single"); BaseClass::Precache(); } #define MAX_GLASS_PENETRATION_DEPTH 16.0f extern short g_sModelIndexFireball; // (in combatweapon.cpp) holds the index for the smoke cloud void CASW_Weapon_Railgun::PrimaryAttack() { // If my clip is empty (and I use clips) start reload if ( UsesClipsForAmmo1() && !m_iClip1 ) { Reload(); return; } CASW_Player *pPlayer = GetCommander(); CASW_Marine *pMarine = GetMarine(); if (!pMarine) // firing from a marine return; #ifndef CLIENT_DLL //Msg("[S] Railgun PrimaryAttack time=%f\n", gpGlobals->curtime); #else //Msg("[C] Railgun PrimaryAttack time=%f\n", gpGlobals->curtime); #endif m_iRailBurst = 1; // disable burst firing.. //if (m_iRailBurst <= 0) //m_iRailBurst = ASW_RAILGUN_BURST_COUNT; // MUST call sound before removing a round from the clip of a CMachineGun WeaponSound(SINGLE); m_bIsFiring = true; // tell the marine to tell its weapon to draw the muzzle flash pMarine->DoMuzzleFlash(); // sets the animation on the weapon model iteself SendWeaponAnim( GetPrimaryAttackActivity() ); // sets the animation on the marine holding this weapon //pMarine->SetAnimation( PLAYER_ATTACK1 ); #ifdef GAME_DLL // check for turning on lag compensation if (pPlayer && pMarine->IsInhabited()) { CASW_Lag_Compensation::RequestLagCompensation( pPlayer, pPlayer->GetCurrentUserCommand() ); } #endif FireBulletsInfo_t info; info.m_vecSrc = pMarine->Weapon_ShootPosition( ); if ( pPlayer && pMarine->IsInhabited() ) { info.m_vecDirShooting = pPlayer->GetAutoaimVectorForMarine(pMarine, GetAutoAimAmount(), GetVerticalAdjustOnlyAutoAimAmount()); // 45 degrees = 0.707106781187 } else { #ifdef CLIENT_DLL Msg("Error, clientside firing of a weapon that's being controlled by an AI marine\n"); #else info.m_vecDirShooting = pMarine->GetActualShootTrajectory( info.m_vecSrc ); #endif } // To make the firing framerate independent, we may have to fire more than one bullet here on low-framerate systems, // especially if the weapon we're firing has a really fast rate of fire. info.m_iShots = 0; float fireRate = GetFireRate(); if (m_iRailBurst > 1) fireRate = ASW_RAILGUN_BURST_INTERVAL; //float current_attack_time = m_flNextPrimaryAttack; //float attack_delta = gpGlobals->curtime - current_attack_time; while ( m_flNextPrimaryAttack <= gpGlobals->curtime ) { if (m_iRailBurst == 0) // this loop could fire all our burst rounds in one go, se chcek for resetting it up m_iRailBurst = ASW_RAILGUN_BURST_COUNT; m_flNextPrimaryAttack = m_flNextPrimaryAttack + fireRate; #ifndef CLIENT_DLL //Msg("[S] Set m_flNextPrimaryAttack to %f Firerate=%f curtime=%f\n", m_flNextPrimaryAttack.Get(), fireRate, gpGlobals->curtime); #else //Msg("[C] Set m_flNextPrimaryAttack to %f Firerate=%f curtime=%f\n", m_flNextPrimaryAttack.Get(), fireRate, gpGlobals->curtime); #endif info.m_iShots++; m_iRailBurst--; // recalc the fire rate as our burst var can change it fireRate = GetFireRate(); if (m_iRailBurst > 1) fireRate = ASW_RAILGUN_BURST_INTERVAL; if ( !fireRate ) break; } // Make sure we don't fire more than the amount in the clip if ( UsesClipsForAmmo1() ) { info.m_iShots = MIN( info.m_iShots, m_iClip1 ); m_iClip1 -= info.m_iShots; #ifdef GAME_DLL CASW_Marine *pMarine = GetMarine(); if (pMarine && m_iClip1 <= 0 && pMarine->GetAmmoCount(m_iPrimaryAmmoType) <= 0 ) { // check he doesn't have ammo in an ammo bay CASW_Weapon_Ammo_Bag* pAmmoBag = dynamic_cast<CASW_Weapon_Ammo_Bag*>(pMarine->GetASWWeapon(0)); if (!pAmmoBag) pAmmoBag = dynamic_cast<CASW_Weapon_Ammo_Bag*>(pMarine->GetASWWeapon(1)); if (!pAmmoBag || !pAmmoBag->CanGiveAmmoToWeapon(this)) pMarine->OnWeaponOutOfAmmo(true); } #endif } else { info.m_iShots = MIN( info.m_iShots, pMarine->GetAmmoCount( m_iPrimaryAmmoType ) ); pMarine->RemoveAmmo( info.m_iShots, m_iPrimaryAmmoType ); } info.m_flDistance = asw_weapon_max_shooting_distance.GetFloat(); info.m_iAmmoType = m_iPrimaryAmmoType; info.m_iTracerFreq = 1; info.m_flDamage = GetWeaponDamage(); #ifndef CLIENT_DLL if (asw_debug_marine_damage.GetBool()) Msg("Weapon dmg = %f\n", info.m_flDamage); info.m_flDamage *= pMarine->GetMarineResource()->OnFired_GetDamageScale(); #endif info.m_vecSpread = pMarine->GetActiveWeapon()->GetBulletSpread(); info.m_flDamageForceScale = asw_railgun_force_scale.GetFloat(); //float max_dist = asw_weapon_max_shooting_distance.GetFloat(); //inline void UTIL_TraceLine( const Vector& vecAbsStart, const Vector& vecAbsEnd, unsigned int mask, //const IHandleEntity *ignore, int collisionGroup, trace_t *ptr ) // find impact point of the RG shot #ifdef ASW_RAILGUN_SWEEP_STYLE trace_t tr; UTIL_TraceLine(info.m_vecSrc, info.m_vecSrc + info.m_vecDirShooting * max_dist, MASK_SOLID_BRUSHONLY, pMarine, COLLISION_GROUP_NONE, &tr); if (!tr.startsolid) { #ifndef CLIENT_DLL bool bHitGlass = false; if ( tr.m_pEnt != NULL ) { Msg("trace hit something\n"); surfacedata_t *psurf = physprops->GetSurfaceData( tr.surface.surfaceProps ); if (psurf != NULL) { Msg("psurf isn't null. mat = %d glass = %d class = %s match = %d\n", psurf->game.material, CHAR_TEX_GLASS, tr.m_pEnt->GetClassname(), tr.m_pEnt->ClassMatches( "CBreakableSurface" )); } if ( ( psurf != NULL ) && ( psurf->game.material == CHAR_TEX_GLASS ) && ( tr.m_pEnt->ClassMatches( "CBreakableSurface" ) ) ) { Msg("so this is a glass hit\n"); bHitGlass = true; } } int glassCount = 10; while (bHitGlass && glassCount > 0) { Msg("hit glass\n"); bHitGlass = false; glassCount--; // Move through the glass until we're at the other side Vector testPos = tr.endpos + ( info.m_vecDirShooting * MAX_GLASS_PENETRATION_DEPTH ); CEffectData data; data.m_vNormal = tr.plane.normal; data.m_vOrigin = tr.endpos; DispatchEffect( "GlassImpact", data ); trace_t penetrationTrace; UTIL_TraceLine(testPos, tr.endpos, MASK_SHOT, pMarine, COLLISION_GROUP_NONE, &penetrationTrace); // See if we found the surface again if ( !penetrationTrace.startsolid && tr.fraction != 0.0f && penetrationTrace.fraction != 1.0f ) { // Impact the other side (will look like an exit effect) DoImpactEffect( penetrationTrace, GetAmmoDef()->DamageType(info.m_iAmmoType) ); data.m_vNormal = penetrationTrace.plane.normal; data.m_vOrigin = penetrationTrace.endpos; DispatchEffect( "GlassImpact", data ); // continue trace past the glass UTIL_TraceLine(penetrationTrace.endpos, penetrationTrace.endpos + info.m_vecDirShooting * max_dist, MASK_SOLID_BRUSHONLY, pMarine, COLLISION_GROUP_NONE, &tr); if ( tr.m_pEnt != NULL ) { surfacedata_t *psurf = physprops->GetSurfaceData( tr.surface.surfaceProps ); if ( ( psurf != NULL ) && ( psurf->game.material == CHAR_TEX_GLASS ) && ( tr.m_pEnt->ClassMatches( "func_breakable" ) ) ) { bHitGlass = true; } } } } Vector vecEndPos = tr.endpos; trace_t ptr; //CTakeDamageInfo( CBaseEntity *pInflictor, CBaseEntity *pAttacker, float flDamage, int bitsDamageType, int iKillType = 0 ); //CTakeDamageInfo( CBaseEntity *pInflictor, CBaseEntity *pAttacker, const Vector &damageForce, const Vector &damagePosition, float flDamage, int bitsDamageType, int iKillType = 0, Vector *reportedPosition = NULL ); // do close high damage FF damaging trace CTakeDamageInfo dmg(this, pMarine, Vector(0,0,0), GetAbsOrigin(), GetWeaponDamage(), DMG_SONIC); // | DMG_ALWAYSGIB CTraceFilterRG traceFilter( pMarine, COLLISION_GROUP_NONE, &dmg, true ); Vector vecMin(-3, -3, -3); Vector vecMax(3, 3, 3); UTIL_TraceHull( info.m_vecSrc, vecEndPos, vecMin, vecMax, CONTENTS_MONSTER, &traceFilter, &ptr ); // do wide less damaging sweep #ifdef ASW_RAILGUN_WIDE_SWEEP CTakeDamageInfo wdmg(this, pMarine, Vector(0,0,0), GetAbsOrigin(), GetWeaponDamage() * 0.33f, DMG_SONIC); // | DMG_ALWAYSGIB CTraceFilterRG wtraceFilter( pMarine, COLLISION_GROUP_NONE, &wdmg, false ); Vector vecWMin(-15, -15, -15); Vector vecWMax(15, 15, 15); UTIL_TraceHull( info.m_vecSrc, vecEndPos, vecWMin, vecWMax, CONTENTS_MONSTER, &wtraceFilter, &ptr ); #endif // ASW_RAILGUN_WIDE_SWEEP #endif // CLIENT_DLL //CreateRailgunBeam(GetAbsOrigin(), tr.endpos); } #else //trace_t tr; //UTIL_TraceLine(info.m_vecSrc, info.m_vecSrc + info.m_vecDirShooting * max_dist, MASK_SHOT, pMarine, COLLISION_GROUP_NONE, &tr); //Vector vecExplosionPos = tr.endpos; //CPASFilter filter( vecExplosionPos ); /*te->Explosion( filter, 0.1, // IRecipientFilter& filter, float delay &vecExplosionPos, // pos g_sModelIndexFireball, // modelindex 0.1, // scale 1, // framerate TE_EXPLFLAG_NONE, // flags 0.5, // radius 0.5 ); // magnitude */ if ( m_bSafetyEnabled ) { info.m_flDamage = -1; // We can't use 0 because it means "I don't give a crap how much" } pMarine->FirePenetratingBullets( info, 10, 1.0f, 0, true, NULL, false ); //pMarine->FireBullets( info ); #endif // ASW_RAILGUN_SWEEP_STYLE // increment shooting stats #ifndef CLIENT_DLL if (pMarine && pMarine->GetMarineResource()) { pMarine->GetMarineResource()->UsedWeapon(this, info.m_iShots); pMarine->OnWeaponFired( this, info.m_iShots ); } #endif if (!m_iClip1 && pMarine->GetAmmoCount(m_iPrimaryAmmoType) <= 0) { // HEV suit - indicate out of ammo condition if (pPlayer) pPlayer->SetSuitUpdate("!HEV_AMO0", FALSE, 0); } m_fSlowTime = gpGlobals->curtime + 0.1f; } // creates a translucent beam effect coming out from the gun void CASW_Weapon_Railgun::CreateRailgunBeam( const Vector &vecStartPoint, const Vector &vecEndPoint ) { //Vector vecEndPoint = info.m_vecSrc + info.m_vecDirShooting * 1000; //Vector vecStartPoint = GetAbsOrigin(); CASW_Marine* pOwner = GetMarine(); if (!pOwner) return; CEffectData data; data.m_vStart = vecStartPoint; data.m_vOrigin = vecEndPoint; data.m_fFlags |= TRACER_FLAG_USEATTACHMENT; data.m_nAttachmentIndex = LookupAttachment("muzzle"); #ifdef CLIENT_DLL data.m_hEntity = this; #else data.m_nEntIndex = entindex(); #endif CPASFilter filter( data.m_vOrigin ); #ifndef CLIENT_DLL if (gpGlobals->maxClients > 1 && pOwner->IsInhabited() && pOwner->GetCommander()) { // multiplayer game, where this marine is currently being controlled by a client, who will spawn his own effect // so just make the beam effect for all other clients filter.RemoveRecipient(pOwner->GetCommander()); } #endif DispatchEffect(filter, 0.0, "RailgunBeam", data ); return; /* #ifdef CLIENT_DLL QAngle muzzleAngles; GetAttachment( LookupAttachment("muzzle"), vecStartPoint, muzzleAngles ); // create a railgun beam (it'll fade out and kill itself after a short period) C_ASW_Railgun_Beam *pBeam = new C_ASW_Railgun_Beam(); if (pBeam) { if (pBeam->InitializeAsClientEntity( NULL, false )) { pBeam->InitBeam(vecStartPoint, vecEndPoint); } else { pBeam->Release(); } }*/ /* // Draw a beam BeamInfo_t beamInfo; beamInfo.m_pStartEnt = this; beamInfo.m_nStartAttachment = 1; beamInfo.m_pEndEnt = NULL; beamInfo.m_nEndAttachment = -1; beamInfo.m_vecStart = vec3_origin; beamInfo.m_vecEnd = vecEndPoint; beamInfo.m_pszModelName = "swarm/effects/railgun.vmt"; beamInfo.m_flHaloScale = 0.0f; beamInfo.m_flLife = 0.1f; beamInfo.m_flWidth = 12.0f; beamInfo.m_flEndWidth = 4.0f; beamInfo.m_flFadeLength = 0.0f; beamInfo.m_flAmplitude = 0; beamInfo.m_flBrightness = 255.0; beamInfo.m_flSpeed = 0.0f; beamInfo.m_nStartFrame = 0.0; beamInfo.m_flFrameRate = 0.0; beamInfo.m_flRed = 255.0; beamInfo.m_flGreen = 255.0; beamInfo.m_flBlue = 255.0; beamInfo.m_nSegments = 16; beamInfo.m_bRenderable = true; beamInfo.m_nFlags = FBEAM_ONLYNOISEONCE | FBEAM_SOLID; beams->CreateBeamEntPoint( beamInfo ); */ /* #else CASW_Marine* pOwner = GetMarine(); if (!pOwner) return; CEffectData data; data.m_vStart = vecStartPoint; data.m_vOrigin = vecEndPoint; data.m_fFlags |= TRACER_FLAG_USEATTACHMENT; data.m_nAttachmentIndex = LookupAttachment("muzzle"); data.m_nEntIndex = entindex(); CPASFilter filter( data.m_vOrigin ); if (gpGlobals->maxClients > 1 && pOwner->IsInhabited() && pOwner->GetCommander()) { // multiplayer game, where this marine is currently being controlled by a client, who will spawn his own effect // so just make the beam effect for all other clients filter.RemoveRecipient(pOwner->GetCommander()); } te->DispatchEffect( filter, 0.0, data.m_vOrigin, "RailgunBeam", data ); #endif*/ } bool CASW_Weapon_Railgun::ShouldMarineMoveSlow() { return BaseClass::ShouldMarineMoveSlow(); //return m_fSlowTime > gpGlobals->curtime; } float CASW_Weapon_Railgun::GetMovementScale() { return ShouldMarineMoveSlow() ? 0.75f : 1.0f; } bool CASW_Weapon_Railgun::Reload() { m_iRailBurst = 0; bool bReloaded = ASWReload( GetMaxClip1(), GetMaxClip2(), ACT_VM_RELOAD ); // skip reload chatter on the railgun, since it reloads after every shot /* if (bReloaded) { #ifdef GAME_DLL CASW_Marine *pMarine = GetMarine(); if (pMarine) { if (pMarine->IsAlienNear()) { //Msg("potentially reload chattering as there is an alien near\n"); pMarine->GetMarineSpeech()->Chatter(CHATTER_RELOADING); } else { //Msg("Not reload chattering as there's no aliens near\n"); } } #endif } */ return bReloaded; } bool CASW_Weapon_Railgun::Holster( CBaseCombatWeapon *pSwitchingTo ) { m_iRailBurst = 0; return BaseClass::Holster( pSwitchingTo ); } void CASW_Weapon_Railgun::GetButtons(bool& bAttack1, bool& bAttack2, bool& bReload, bool& bOldReload, bool& bOldAttack1 ) { BaseClass::GetButtons(bAttack1, bAttack2, bReload, bOldReload, bOldAttack1 ); // make sure the fire button stays held down until our burst is clear CASW_Marine *pMarine = GetMarine(); if (m_iRailBurst > 0 && !(pMarine && pMarine->GetFlags() & FL_FROZEN)) bAttack1 = true; } bool CASW_Weapon_Railgun::SupportsBayonet() { return true; } float CASW_Weapon_Railgun::GetWeaponDamage() { //float flDamage = 35.0f; float flDamage = GetWeaponInfo()->m_flBaseDamage; if ( GetMarine() ) { flDamage += MarineSkills()->GetSkillBasedValueByMarine(GetMarine(), ASW_MARINE_SKILL_ACCURACY, ASW_MARINE_SUBSKILL_ACCURACY_RAILGUN_DMG); } //CALL_ATTRIB_HOOK_FLOAT( flDamage, mod_damage_done ); return flDamage; } int CASW_Weapon_Railgun::ASW_SelectWeaponActivity(int idealActivity) { switch( idealActivity ) { case ACT_WALK: idealActivity = ACT_WALK_AIM_RIFLE; break; case ACT_RUN: idealActivity = ACT_RUN_AIM_RIFLE; break; case ACT_IDLE: idealActivity = ACT_IDLE_RIFLE; break; case ACT_RELOAD: idealActivity = ACT_RELOAD; break; default: break; } return idealActivity; } #ifndef CLIENT_DLL bool CTraceFilterRG::ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask ) { if ( !StandardFilterRules( pHandleEntity, contentsMask ) ) return false; if ( !PassServerEntityFilter( pHandleEntity, m_pPassEnt ) ) return false; // Don't test if the game code tells us we should ignore this collision... CBaseEntity *pEntity = EntityFromEntityHandle( pHandleEntity ); if ( pEntity ) { if ( !pEntity->ShouldCollide( m_collisionGroup, contentsMask ) ) return false; if ( !g_pGameRules->ShouldCollide( m_collisionGroup, pEntity->GetCollisionGroup() ) ) return false; if ( pEntity->m_takedamage == DAMAGE_NO ) return false; Vector attackDir = pEntity->WorldSpaceCenter() - m_dmgInfo->GetAttacker()->WorldSpaceCenter(); VectorNormalize( attackDir ); CTakeDamageInfo info = (*m_dmgInfo); CalculateMeleeDamageForce( &info, attackDir, info.GetAttacker()->WorldSpaceCenter(), 1.0f ); CBaseCombatCharacter *pBCC = info.GetAttacker()->MyCombatCharacterPointer(); CBaseCombatCharacter *pVictimBCC = pEntity->MyCombatCharacterPointer(); // Only do these comparisons between NPCs if ( pBCC && pVictimBCC ) { // Can only damage other NPCs that we hate if ( m_bFFDamage || pBCC->IRelationType( pEntity ) == D_HT ) { if ( info.GetDamage() ) { pEntity->TakeDamage( info ); } // Put a combat sound in CSoundEnt::InsertSound( SOUND_COMBAT, info.GetDamagePosition(), 200, 0.2f, info.GetAttacker() ); m_pHit = pEntity; return true; } } else { // Make sure if the player is holding this, he drops it Pickup_ForcePlayerToDropThisObject( pEntity ); // Otherwise just damage passive objects in our way if ( info.GetDamage() ) { pEntity->TakeDamage( info ); } } } return false; } #endif void CASW_Weapon_Railgun::SecondaryAttack() { // Only the player fires this way so we can cast CASW_Player *pPlayer = GetCommander(); if (!pPlayer) return; CASW_Marine *pMarine = GetMarine(); if (!pMarine) return; // dry fire - no secondary enabled on RG (below rocket stuff is an experiment) SendWeaponAnim( ACT_VM_DRYFIRE ); BaseClass::WeaponSound( EMPTY ); m_flNextSecondaryAttack = gpGlobals->curtime + 0.5f; return; //Must have ammo - temp comment //bool bUsesSecondary = UsesSecondaryAmmo(); bool bUsesClips = UsesClipsForAmmo2(); //int iAmmoCount = pMarine->GetAmmoCount(m_iSecondaryAmmoType); //bool bInWater = ( pMarine->GetWaterLevel() == 3 ); /* if ( (bUsesSecondary && ( ( bUsesClips && m_iClip2 <= 0) || ( !bUsesClips && iAmmoCount<=0 ) ) ) || bInWater || m_bInReload ) { SendWeaponAnim( ACT_VM_DRYFIRE ); BaseClass::WeaponSound( EMPTY ); m_flNextSecondaryAttack = gpGlobals->curtime + 0.5f; return; } */ // MUST call sound before removing a round from the clip of a CMachineGun BaseClass::WeaponSound( SPECIAL1 ); Vector vecSrc = pMarine->Weapon_ShootPosition(); Vector vecThrow; // Don't autoaim on grenade tosses vecThrow = pPlayer->GetAutoaimVectorForMarine(pMarine, GetAutoAimAmount(), GetVerticalAdjustOnlyAutoAimAmount()); // 45 degrees = 0.707106781187 QAngle angGrenFacing; VectorAngles(vecThrow, angGrenFacing); VectorScale( vecThrow, 1000.0f, vecThrow ); #ifndef CLIENT_DLL //Create the grenade /* float fGrenadeDamage = MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_DMG); float fGrenadeRadius = MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_RADIUS); if (asw_debug_marine_damage.GetBool()) { Msg("Grenade damage = %f radius = %f\n", fGrenadeDamage, fGrenadeRadius); } CASW_Grenade_PRifle::PRifle_Grenade_Create( fGrenadeDamage, fGrenadeRadius, vecSrc, angGrenFacing, vecThrow, AngularImpulse(0,0,0), pMarine ); */ const int num_rockets = 5; const int fan_spread = 90; for (int i=0;i<num_rockets;i++) { int angle = (-fan_spread * 0.5f) + float(fan_spread) * (float(i) / float(num_rockets)); QAngle vecRocketAngle = angGrenFacing; vecRocketAngle[YAW] += angle; //CASW_Rocket::Create(vecSrc, vecRocketAngle, GetMarine()); } #endif SendWeaponAnim( ACT_VM_SECONDARYATTACK ); if ( bUsesClips ) { m_iClip2 -= 1; } else { pMarine->RemoveAmmo( 1, m_iSecondaryAmmoType ); } // Can shoot again immediately m_flNextPrimaryAttack = gpGlobals->curtime + 0.5f; // Can blow up after a short delay (so have time to release mouse button) m_flNextSecondaryAttack = gpGlobals->curtime + 1.0f; } float CASW_Weapon_Railgun::GetFireRate() { //float flRate = 0.1f; float flRate = GetWeaponInfo()->m_flFireRate; //CALL_ATTRIB_HOOK_FLOAT( flRate, mod_fire_rate ); return flRate; }
[ "nightgunner5@llamaslayers.net" ]
nightgunner5@llamaslayers.net
66fbcbf45532b22a929c055ba30db2fa70768ea9
9c451121eaa5e0131110ad0b969d75d9e6630adb
/Luogu/P2078 朋友.cpp
4289709871c8953d83508727ad773914feb44b6d
[]
no_license
tokitsu-kaze/ACM-Solved-Problems
69e16c562a1c72f2a0d044edd79c0ab949cc76e3
77af0182401904f8d2f8570578e13d004576ba9e
refs/heads/master
2023-09-01T11:25:12.946806
2023-08-25T03:26:50
2023-08-25T03:26:50
138,472,754
5
1
null
null
null
null
UTF-8
C++
false
false
758
cpp
#include <bits/stdc++.h> using namespace std; const int MAX=1e4+10; struct Disjoint_Set_Union { int pre[MAX],sz[MAX]; void init(int n) { int i; for(i=1;i<=n;i++) { pre[i]=i; sz[i]=1; } } int find(int x) { if(pre[x]!=x) pre[x]=find(pre[x]); return pre[x]; } bool merge(int a,int b) { int ra,rb; ra=find(a); rb=find(b); if(ra!=rb) { pre[ra]=rb; sz[rb]+=sz[ra]; return 1; } return 0; } }da,db; int main() { int n,m,p,q,i,a,b,ra,rb; scanf("%d%d%d%d",&n,&m,&p,&q); da.init(n); db.init(m); while(p--) { scanf("%d%d",&a,&b); da.merge(a,b); } while(q--) { scanf("%d%d",&a,&b); a=-a; b=-b; db.merge(a,b); } ra=da.sz[da.find(1)]; rb=db.sz[db.find(1)]; printf("%d\n",min(ra,rb)); return 0; }
[ "861794979@qq.com" ]
861794979@qq.com
66ae398629e125081e92336d200710d12dc33613
a0e695b8b8d46dc9615e7314fcc8458a21f2a6ac
/examples/Queue/Queue.ino
35c0f6688c3d597325761b51135526658067216a
[ "MIT" ]
permissive
Floessie/frt
769bf0753120214b69b7828550118f04bd5cf56f
a4278d9bd119834924a3c64edefccbf93266d53b
refs/heads/master
2021-05-11T19:57:14.657162
2020-12-07T17:19:06
2020-12-07T17:19:06
117,427,334
22
9
MIT
2018-02-04T16:29:16
2018-01-14T12:17:24
C++
UTF-8
C++
false
false
3,056
ino
#include <frt.h> namespace { // This is the data shared between producer and consumer task struct Data { int value; unsigned long timestamp; }; // This is our queue, which can store 10 elements of Data frt::Queue<Data, 10> queue; // This is the mutex to protect our output from getting mixed up frt::Mutex serial_mutex; // The producer task class ProducerTask final : public frt::Task<ProducerTask, 100> { public: bool run() { // We push the analog value and the current timestamp queue.push({analogRead(0), millis()}); // Note that there is no msleep() here, so this task runs // "full throttle" and will only yield if either preempted // by a higher priority task on the next scheduler tick or // the queue being full. return true; } }; // The consumer task class ConsumerTask final : public frt::Task<ConsumerTask, 150> { public: bool run() { Data data; // Get the (possibly old) data from the queue queue.pop(data); // This variant of pop() will wait forever for data to // arrive. If you ever plan to stop this task, use a // variant with timeout, so run() is left once in a while. const unsigned long now = millis(); // If you dare, try to remove the mutex and see what happens serial_mutex.lock(); Serial.print(F("Got value ")); Serial.print(data.value); Serial.print(F(" at ")); Serial.print(now); Serial.print(F(" which was queued at ")); Serial.println(data.timestamp); serial_mutex.unlock(); // Again, no msleep() here return true; } }; // Instances of the above tasks ProducerTask producer_task; ConsumerTask consumer_task; // The high priority monitoring task class MonitoringTask final : public frt::Task<MonitoringTask> { public: bool run() { msleep(1000, remainder); serial_mutex.lock(); Serial.print(F("Queue fill level: ")); Serial.println(queue.getFillLevel()); Serial.print(F("Producer stack used: ")); Serial.println(producer_task.getUsedStackSize()); Serial.print(F("Consumer stack used: ")); Serial.println(consumer_task.getUsedStackSize()); serial_mutex.unlock(); return true; } private: unsigned int remainder = 0; }; // Instance of the above task MonitoringTask monitoring_task; } void setup() { Serial.begin(9600); while (!Serial); monitoring_task.start(3); // As the consumer task is started with lower priority first, the // moment the producer starts, it will fill the queue completely // and stall. The consumer will wake and pop one element, then the // producer will kick in again filling the queue (only one item). // Only then the consumer will print out its line. It continues into // run() and pops one item, and so on. // You should play a bit with the start sequence and priorities here // to get a feeling on what's going on. consumer_task.start(1); producer_task.start(2); } void loop() { // As both producer and consumer are always runnable, you will // never see the next line. Serial.println(F("IDLE")); }
[ "floessie.mail@gmail.com" ]
floessie.mail@gmail.com
4c70b3ae1f116df6b78f541838af66623b684610
04ed83d07f5e2e4712f25669759c32a428a28cd3
/src/dhtnetgraph.cc
ab83da3de6d25161251d8b27f9997a517bec8135
[]
no_license
hmatuschek/ovlclient
64d9033610b2fce3eb8d8d7ad0e85048b087ef52
3f87dae3ec181a9d3361825e6941f3dfeda0de4a
refs/heads/master
2021-01-17T14:52:33.791994
2016-07-14T13:31:22
2016-07-14T13:31:22
52,441,399
1
1
null
null
null
null
UTF-8
C++
false
false
1,163
cc
#include "dhtnetgraph.hh" #include <QPainter> #include <QPen> #include <QBrush> #include <QColor> DHTNetGraph::DHTNetGraph(QWidget *parent) : QWidget(parent) { setMinimumWidth(300); setMinimumHeight(75); update(QList< QPair<double, bool> >()); } void DHTNetGraph::update(const QList<QPair<double, bool> > &nodes) { _nodes = nodes; QWidget::update(); } void DHTNetGraph::paintEvent(QPaintEvent *evt) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.fillRect(rect(), "white"); int margin = 10; // Draw axis painter.setPen(QPen(Qt::black, 3)); painter.drawLine(margin, height()/2, width()-2*margin, height()/2); painter.setBrush(QBrush(Qt::black)); painter.drawEllipse(QPoint(margin,height()/2), 5,5); // Draw nodes painter.setPen(QPen(Qt::black, 2)); QList< QPair<double, bool> >::iterator item = _nodes.begin(); for (; item != _nodes.end(); item++) { if (item->second) { painter.setBrush(QBrush(Qt::blue)); } else { painter.setBrush(QBrush(Qt::gray)); } int x = margin+(width()-2*margin)*item->first; painter.drawEllipse(QPoint(x,height()/2), 5,5); } }
[ "hmatuschek@gmail.com" ]
hmatuschek@gmail.com
2e6a6df95ab669b9d9de0222e79656fe48838c8b
a5c2bcbd0298b743ef86b046a37e1c303dc7ade8
/C++/Inheritance/00_Inheritance_Introduction.cpp
b75b20bcefeb2a75560d4ef6d09f34ebdff4a393
[]
no_license
lvoneduval/hackerrank
911c140d9e25ef39b7cfb5c3e8afb1e6634bdd33
be0ae48282d71fbac876962c9b0a636621615aa2
refs/heads/master
2021-09-14T09:37:52.676172
2018-05-11T12:11:59
2018-05-11T12:11:59
111,906,441
0
0
null
null
null
null
UTF-8
C++
false
false
608
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; class Triangle{ public: void triangle(){ cout<<"I am a triangle\n"; } }; class Isosceles : public Triangle{ public: void description() { cout << "In an isosceles triangle two sides are equal\n"; } void isosceles(){ cout<<"I am an isosceles triangle\n"; } //Write your code here. }; int main(){ Isosceles isc; isc.isosceles(); isc.description(); isc.triangle(); return 0; }
[ "lionel.duval@etu.umontpellier.fr" ]
lionel.duval@etu.umontpellier.fr
9c50ac98e7017f7ac0bc37473c505fbd5428448b
43a54d76227b48d851a11cc30bbe4212f59e1154
/cwp/include/tencentcloud/cwp/v20180228/model/DescribeReverseShellEventsRequest.h
f59f48d117fea24737d69dff064c94a32a067d56
[ "Apache-2.0" ]
permissive
make1122/tencentcloud-sdk-cpp
175ce4d143c90d7ea06f2034dabdb348697a6c1c
2af6954b2ee6c9c9f61489472b800c8ce00fb949
refs/heads/master
2023-06-04T03:18:47.169750
2021-06-18T03:00:01
2021-06-18T03:00:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,692
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 TENCENTCLOUD_CWP_V20180228_MODEL_DESCRIBEREVERSESHELLEVENTSREQUEST_H_ #define TENCENTCLOUD_CWP_V20180228_MODEL_DESCRIBEREVERSESHELLEVENTSREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/cwp/v20180228/model/Filter.h> namespace TencentCloud { namespace Cwp { namespace V20180228 { namespace Model { /** * DescribeReverseShellEvents请求参数结构体 */ class DescribeReverseShellEventsRequest : public AbstractModel { public: DescribeReverseShellEventsRequest(); ~DescribeReverseShellEventsRequest() = default; std::string ToJsonString() const; /** * 获取返回数量,默认为10,最大值为100。 * @return Limit 返回数量,默认为10,最大值为100。 */ uint64_t GetLimit() const; /** * 设置返回数量,默认为10,最大值为100。 * @param Limit 返回数量,默认为10,最大值为100。 */ void SetLimit(const uint64_t& _limit); /** * 判断参数 Limit 是否已赋值 * @return Limit 是否已赋值 */ bool LimitHasBeenSet() const; /** * 获取偏移量,默认为0。 * @return Offset 偏移量,默认为0。 */ uint64_t GetOffset() const; /** * 设置偏移量,默认为0。 * @param Offset 偏移量,默认为0。 */ void SetOffset(const uint64_t& _offset); /** * 判断参数 Offset 是否已赋值 * @return Offset 是否已赋值 */ bool OffsetHasBeenSet() const; /** * 获取过滤条件。 <li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li> * @return Filters 过滤条件。 <li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li> */ std::vector<Filter> GetFilters() const; /** * 设置过滤条件。 <li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li> * @param Filters 过滤条件。 <li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li> */ void SetFilters(const std::vector<Filter>& _filters); /** * 判断参数 Filters 是否已赋值 * @return Filters 是否已赋值 */ bool FiltersHasBeenSet() const; private: /** * 返回数量,默认为10,最大值为100。 */ uint64_t m_limit; bool m_limitHasBeenSet; /** * 偏移量,默认为0。 */ uint64_t m_offset; bool m_offsetHasBeenSet; /** * 过滤条件。 <li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li> */ std::vector<Filter> m_filters; bool m_filtersHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CWP_V20180228_MODEL_DESCRIBEREVERSESHELLEVENTSREQUEST_H_
[ "tencentcloudapi@tenent.com" ]
tencentcloudapi@tenent.com
98422d4c86fc485da33d34a7fbb61977824ff427
d3d1429da6d94ec4b3c003db06607bc9daa35804
/vendor/github.com/cockroachdb/c-rocksdb/internal/table/full_filter_block_test.cc
51ce1aaa9970249ae835b5cb3d9bea69e81df421
[ "ISC", "BSD-3-Clause" ]
permissive
zipper-project/zipper
f61a12b60445dfadf5fd73d289ff636ce958ae23
c9d2d861e1b920ed145425e63d019d6870bbe808
refs/heads/master
2021-05-09T14:48:04.286860
2018-05-25T05:52:46
2018-05-25T05:52:46
119,074,801
97
75
ISC
2018-03-01T10:18:22
2018-01-26T16:23:40
Go
UTF-8
C++
false
false
5,736
cc
// Copyright (c) 2011-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 "table/full_filter_block.h" #include "rocksdb/filter_policy.h" #include "util/coding.h" #include "util/hash.h" #include "util/logging.h" #include "util/testharness.h" #include "util/testutil.h" namespace rocksdb { class TestFilterBitsBuilder : public FilterBitsBuilder { public: explicit TestFilterBitsBuilder() {} // Add Key to filter virtual void AddKey(const Slice& key) override { hash_entries_.push_back(Hash(key.data(), key.size(), 1)); } // Generate the filter using the keys that are added virtual Slice Finish(std::unique_ptr<const char[]>* buf) override { uint32_t len = static_cast<uint32_t>(hash_entries_.size()) * 4; char* data = new char[len]; for (size_t i = 0; i < hash_entries_.size(); i++) { EncodeFixed32(data + i * 4, hash_entries_[i]); } const char* const_data = data; buf->reset(const_data); return Slice(data, len); } private: std::vector<uint32_t> hash_entries_; }; class TestFilterBitsReader : public FilterBitsReader { public: explicit TestFilterBitsReader(const Slice& contents) : data_(contents.data()), len_(static_cast<uint32_t>(contents.size())) {} virtual bool MayMatch(const Slice& entry) override { uint32_t h = Hash(entry.data(), entry.size(), 1); for (size_t i = 0; i + 4 <= len_; i += 4) { if (h == DecodeFixed32(data_ + i)) { return true; } } return false; } private: const char* data_; uint32_t len_; }; class TestHashFilter : public FilterPolicy { public: virtual const char* Name() const override { return "TestHashFilter"; } virtual void CreateFilter(const Slice* keys, int n, std::string* dst) const override { for (int i = 0; i < n; i++) { uint32_t h = Hash(keys[i].data(), keys[i].size(), 1); PutFixed32(dst, h); } } virtual bool KeyMayMatch(const Slice& key, const Slice& filter) const override { uint32_t h = Hash(key.data(), key.size(), 1); for (unsigned int i = 0; i + 4 <= filter.size(); i += 4) { if (h == DecodeFixed32(filter.data() + i)) { return true; } } return false; } virtual FilterBitsBuilder* GetFilterBitsBuilder() const override { return new TestFilterBitsBuilder(); } virtual FilterBitsReader* GetFilterBitsReader(const Slice& contents) const override { return new TestFilterBitsReader(contents); } }; class PluginFullFilterBlockTest : public testing::Test { public: BlockBasedTableOptions table_options_; PluginFullFilterBlockTest() { table_options_.filter_policy.reset(new TestHashFilter()); } }; TEST_F(PluginFullFilterBlockTest, PluginEmptyBuilder) { FullFilterBlockBuilder builder( nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); Slice block = builder.Finish(); ASSERT_EQ("", EscapeString(block)); FullFilterBlockReader reader( nullptr, true, block, table_options_.filter_policy->GetFilterBitsReader(block), nullptr); // Remain same symantic with blockbased filter ASSERT_TRUE(reader.KeyMayMatch("foo")); } TEST_F(PluginFullFilterBlockTest, PluginSingleChunk) { FullFilterBlockBuilder builder( nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); builder.Add("foo"); builder.Add("bar"); builder.Add("box"); builder.Add("box"); builder.Add("hello"); Slice block = builder.Finish(); FullFilterBlockReader reader( nullptr, true, block, table_options_.filter_policy->GetFilterBitsReader(block), nullptr); ASSERT_TRUE(reader.KeyMayMatch("foo")); ASSERT_TRUE(reader.KeyMayMatch("bar")); ASSERT_TRUE(reader.KeyMayMatch("box")); ASSERT_TRUE(reader.KeyMayMatch("hello")); ASSERT_TRUE(reader.KeyMayMatch("foo")); ASSERT_TRUE(!reader.KeyMayMatch("missing")); ASSERT_TRUE(!reader.KeyMayMatch("other")); } class FullFilterBlockTest : public testing::Test { public: BlockBasedTableOptions table_options_; FullFilterBlockTest() { table_options_.filter_policy.reset(NewBloomFilterPolicy(10, false)); } ~FullFilterBlockTest() {} }; TEST_F(FullFilterBlockTest, EmptyBuilder) { FullFilterBlockBuilder builder( nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); Slice block = builder.Finish(); ASSERT_EQ("", EscapeString(block)); FullFilterBlockReader reader( nullptr, true, block, table_options_.filter_policy->GetFilterBitsReader(block), nullptr); // Remain same symantic with blockbased filter ASSERT_TRUE(reader.KeyMayMatch("foo")); } TEST_F(FullFilterBlockTest, SingleChunk) { FullFilterBlockBuilder builder( nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); builder.Add("foo"); builder.Add("bar"); builder.Add("box"); builder.Add("box"); builder.Add("hello"); Slice block = builder.Finish(); FullFilterBlockReader reader( nullptr, true, block, table_options_.filter_policy->GetFilterBitsReader(block), nullptr); ASSERT_TRUE(reader.KeyMayMatch("foo")); ASSERT_TRUE(reader.KeyMayMatch("bar")); ASSERT_TRUE(reader.KeyMayMatch("box")); ASSERT_TRUE(reader.KeyMayMatch("hello")); ASSERT_TRUE(reader.KeyMayMatch("foo")); ASSERT_TRUE(!reader.KeyMayMatch("missing")); ASSERT_TRUE(!reader.KeyMayMatch("other")); } } // namespace rocksdb int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "2539373634@qq.com" ]
2539373634@qq.com
f055619d38239c61275956bb79e17faa1dd6723a
5f17573507d160aa087b02d0f00d97be7a603f6c
/308B.cpp
3a0a353116310f25e2f366d4f7fb331b433c31bd
[]
no_license
nishnik/Competitive-Programming
33590ea882e449947befc36594fd20c720c05049
cab12301ca7343b6e5f4464fcfbb84b437379da8
refs/heads/master
2021-01-10T05:43:44.252506
2016-02-23T14:14:03
2016-02-23T14:14:03
52,363,354
0
0
null
null
null
null
UTF-8
C++
false
false
1,464
cpp
#include <bits/stdc++.h> //usage getline(cin,str_name); #define rep(i, n) for(__typeof(n) i = 0; i < (n); i++) #define rrep(i, n) for(__typeof(n) i = (n) - 1; i >= 0; --i) #define rep1(i, n) for(__typeof(n) i = 1; i <= (n); i++) #define FOR(i, a, b) for(__typeof(b) i = (a); i <= (b); i++) #define forstl(i, s) for (__typeof ((s).end ()) i = (s).begin (); i != (s).end (); ++i) #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define ll long long #define vi vector<int> #define vvi vector<vi > #define vl vector<long> #define vvl vector<vl > #define vll vector<long long> #define vvll vector<vll > /* Usage: Just create an instance of it at the start of the block of which you want to measure running time. Reliable up to millisecond scale. You don't need to do anything else, even works with freopen. */ class TimeTracker { clock_t start, end; public: TimeTracker() { start = clock(); } ~TimeTracker() { end = clock(); //fprintf(stderr, "%.3lf s\n", (double)(end - start) / CLOCKS_PER_SEC); } }; using namespace std; int main() { ios::sync_with_stdio(false); //cin.tie(0);cout.tie(0); long n; cin>>n; long long sum=0; //cout<<std::fixed<<(n+1)*floorl(log10(10*n))-(pow(10,floorl(log10(10*n)))-1)/9<<std::fixed; long long a=1,b=9; while(n>b) { n-=b; sum+=b*a; a++; b*=10; } sum+=n*a; cout<<sum; } //
[ "nishantiam@gmail.com" ]
nishantiam@gmail.com
c768240383e45bc9d0f47970677b707cf145b666
a90020def1ea505bfb3a2fc152f853997cf5ca4a
/RangeQueries/dynamic_min.cpp
ce095e2a276fefe7c74d4ef90f5671894cb29059
[]
no_license
AYUSHNSUT/CSES
43f9d5d9fb9d027294cac6fb03ee66420462e710
e7cebbb65f8ee6214ca58fa80ec9ea2c9a3bac40
refs/heads/master
2023-05-27T19:08:15.622538
2021-06-07T11:31:16
2021-06-07T11:31:16
296,012,570
0
0
null
null
null
null
UTF-8
C++
false
false
3,877
cpp
#include<bits/stdc++.h> using namespace std; #define DEBUG(x) cerr << '>' << #x << ':' << x << endl; #define REP(i,n) for(int i=0;i<(n);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) #define all(c) c.begin(),c.end() #define M 1000000007 typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<string, string> pss; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<pii> vii; typedef vector<ll> vl; typedef vector<vl> vvl; #define mp make_pair #define pb push_back inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; } inline int two(int n) { return 1 << n; } inline int test(int n, int b) { return (n>>b)&1; } inline void set_bit(int & n, int b) { n |= two(b); } inline void unset_bit(int & n, int b) { n &= ~two(b); } inline int last_bit(int n) { return n & (-n); } inline int ones(int n) { int res = 0; while(n && ++res) n-=n&(-n); return res; } template<class T> void chmax(T & a, const T & b) { a = max(a, b); } template<class T> void chmin(T & a, const T & b) { a = min(a, b); } #define fast_cin() std::ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// class segmentMin{ ll n; vl t; void makeTree(vl &a , ll v, ll tl , ll tr){ if(tl > tr) return; if(tl == tr){ // DEBUG(v); // DEBUG(tl); // DEBUG(a[tl]); t[v] = a[tl]; return; } ll tm = (tl + tr) / 2; makeTree(a,2*v, tl, tm); makeTree(a,2*v + 1, tm + 1, tr); t[v] = min(t[2*v], t[2*v + 1]); // DEBUG(v); // DEBUG(t[v]); // DEBUG(tl); // DEBUG(tr); } ll findMin(ll v, ll tl , ll tr, ll a, ll b){ if(a>b || tl > b || tr < a){ return LLONG_MAX; } if(a== tl && b == tr){ return t[v]; } ll tm = (tl + tr) / 2; return min(findMin(2*v,tl, tm , a, min(b, tm)),findMin(2*v+1,tm+1, tr , max(a,tm+1), b) ); } void updateNodez(ll v, ll tl, ll tr, ll pos, ll newVal){ if(tl > tr) return; if(tl == tr){ t[v] = newVal; return; } ll tm = (tl + tr) / 2; if(pos <= tm){ updateNodez(2*v, tl, tm, pos,newVal); } else{ updateNodez(2*v + 1, tm + 1, tr, pos,newVal); } t[v] = min(t[2*v], t[2*v+1]); } public: segmentMin(ll n) : n(n){ t.resize(4*n, LLONG_MAX); } void generate(vl &a){ ll v = 1; makeTree(a,v,0,n-1); // REP(i,4*n){ // DEBUG(i); // DEBUG(t[i]); // } } ll getMin(ll a , ll b){ return findMin(1,0,n-1,a,b); } void update(ll pos, ll newVal){ ll tl = 0; ll tr = n-1; updateNodez(1,tl,tr,pos, newVal); } }; void solve(){ ll n ,q; cin >> n>>q; vl a(n); REP(i,n){ cin >> a[i]; // DEBUG(a[i]); } segmentMin S(n); S.generate(a); REP(i,q){ ll a,b,c; cin >> a >> b >> c; if(a==1){ S.update(b-1,c); } else{ cout << S.getMin(b-1,c-1) << "\n"; } } } int main(){ #ifdef mishrable // for getting input from input.txt freopen("input.txt", "r", stdin); // for writing output to output.txt freopen("output.txt", "w", stdout); #endif fast_cin(); int t =1; // cin >> t; while(t--){ solve(); } }
[ "ayushm1906@gmail.com" ]
ayushm1906@gmail.com
4ccea86036dd235f91c3c02531a8cef753637972
4aeec3f6db28fe3ab4337777a19a50151bf58394
/rd_framework_cpp/src/main/base/ext/RdExtBase.cpp
c54310595ef30a9673f22b469c41a5fbb0832f03
[]
no_license
operasfantom/rd_cpp
11053df1e8e309db70d72d1167048747caaf2cba
ce38dd043727784901748814c1d40ff65b2e1752
refs/heads/master
2021-07-18T07:47:46.421402
2018-11-14T16:16:34
2018-11-14T16:16:34
140,456,027
2
0
null
null
null
null
UTF-8
C++
false
false
3,182
cpp
// // Created by jetbrains on 24.07.2018. // #include "Lifetime.h" #include "RdPropertyBase.h" #include "RdExtBase.h" #include "Protocol.h" const IProtocol *const RdExtBase::get_protocol() const { return extProtocol ? extProtocol.get() : RdReactiveBase::get_protocol(); } void RdExtBase::init(Lifetime lifetime) const { // Protocol.initializationLogger.traceMe { "binding" } auto parentProtocol = RdReactiveBase::get_protocol(); std::shared_ptr<IWire> parentWire = parentProtocol->wire; // serializersOwner.registry(parentProtocol.serializers); auto sc = parentProtocol->scheduler; extWire->realWire = parentWire.get(); lifetime->bracket( [&]() { extProtocol = std::make_shared<Protocol>(parentProtocol->identity, sc, std::dynamic_pointer_cast<IWire>(extWire)); }, [this]() { extProtocol = nullptr; } ); parentWire->advise(lifetime, this); //it's critical to advise before 'Ready' is sent because we advise on SynchronousScheduler lifetime->bracket( [this, parentWire]() { sendState(*parentWire, ExtState::Ready); }, [this, parentWire]() { sendState(*parentWire, ExtState::Disconnected); } ); //todo make it smarter for (auto const &[name, child] : this->bindableChildren) { bindPolymorphic(*child, lifetime, this, name); } traceMe(Protocol::initializationLogger, "created and bound :: ${printToString()}"); } void RdExtBase::on_wire_received(Buffer buffer) const { ExtState remoteState = buffer.readEnum<ExtState>(); traceMe(logReceived, "remote: " + to_string(remoteState)); switch (remoteState) { case ExtState::Ready : { sendState(*extWire->realWire, ExtState::ReceivedCounterpart); extWire->connected.set(true); break; } case ExtState::ReceivedCounterpart : { extWire->connected.set(true); //don't set anything if already set break; } case ExtState::Disconnected : { extWire->connected.set(false); break; } } int64_t counterpartSerializationHash = buffer.read_pod<int64_t>(); /*if (serializationHash != counterpartSerializationHash) { //need to queue since outOfSyncModels is not synchronized RdReactiveBase::get_protocol()->scheduler->queue([this](){ RdReactiveBase::get_protocol().outOfSyncModels.add(this) }); // error("serializationHash of ext '$location' doesn't match to counterpart: maybe you forgot to generate models?") }*/ } void RdExtBase::sendState(IWire const &wire, RdExtBase::ExtState state) const { wire.send(rdid, [&](Buffer const &buffer) { // logSend.traceMe(state); buffer.writeEnum<ExtState>(state); buffer.write_pod<int64_t>(serializationHash); }); } void RdExtBase::traceMe(const Logger &logger, std::string const &message) const { logger.trace("ext " + location.toString() + " " + rdid.toString() + ":: " + message); }
[ "operasfantom@gmail.com" ]
operasfantom@gmail.com
cd87fa7c5a10b5259a6f5b992040276243f0e0e0
bc8848baeada90d427fb4130099abf11e38fa12c
/SSORT
70c111f2dcf7cb195ebc068c0580f45781c17d3a
[]
no_license
atharva-sarage/Codechef-Competitive-Programming
5e2699928bfca7190bca225ee69a731f058c3619
39e880ad877422f66272d1eb59dab77e9b423f1b
refs/heads/master
2020-06-09T21:57:38.731845
2019-07-17T06:14:35
2019-07-17T06:14:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,060
#include<bits/stdc++.h> #define mx 1005 using namespace std; int n,sum,min1,final,size; int visited[mx]; int par[mx]; int a[mx],b[mx],c[mx]; vector <int> vec; void dfs(int u,int parent) { visited[u]=true; par[u]=parent; if(visited[b[u]]) { int v=b[u]; sum=v; min1=v; while(u!=v) { size++; sum+=u; min1=min(min1,u); u=par[u]; } size++; return; } else dfs(b[u],u); } void DFS() { for(int i=1;i<=n;i++) { if(!visited[a[i]]) { sum=0; size=0; dfs(a[i],-1); //cout<<sum<<endl; if(size==1) { continue; } final+=(sum+min1*(size-2)); if(c[1]-min1*size+3*min1+c[1]*size<0) final+=c[1]-min1*size+3*min1+c[1]*size; } } } int main() { cin>>n; int count=1; while(n!=0) { final=0; memset(visited,false,sizeof(visited)); memset(b,-1,sizeof(b)); for(int i=1;i<=n;i++) { cin>>a[i]; c[i]=a[i]; } sort(c+1,c+n+1); for(int i=1;i<=n;i++) { b[c[i]]=a[i]; } //cout<<b[1]<<" "<<b[2]<<" "<<b[4]<<endl; DFS(); cout<<"Case "<<count<<":"<<" "<<final<<endl; cin>>n; count++; } }
[ "atharva.sarage@gmail.com" ]
atharva.sarage@gmail.com
910e8dd8ebca3b32a06c7ccc82355b0e3b611595
7d047b3755c8f1e81b1473c2d89c6741cdc55835
/Search & Sort/Merge_Sort.cpp
978f4e2bdea10eb14a1714e1940f9b689546371c
[ "MIT" ]
permissive
yashika66011/Daily-DSA-Coding
f44b4076ed9ce1ce6ee99dcd655ee40cb19bb366
af8dddb0e062abe8576b390e5d338aaf3e598c29
refs/heads/main
2023-07-13T02:51:45.657529
2021-08-18T16:23:27
2021-08-18T16:23:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,337
cpp
#include<iostream> #include<algorithm> using namespace std; int * mergeTwoArrays(int as[], int bs[]) { int *a = as; int *b = bs; int n = sizeof(a)/sizeof(a[0]); int m = sizeof(a)/sizeof(a[0]); int *c = new int(n+m); int k = 0; for(int i=0, j=0; i<n && j<m;) { if(a[i] < b[j]) c[k++] = a[i++]; else if(a[i] > b[j]) c[k++] = b[j++]; else { c[k++] = a[i++]; c[k++] = b[j++]; } } if(n < m) { for(int i = n-1; i<m;) c[k++] = b[i++]; } else { for(int i = m-1; i<n;) c[k++] = a[i++]; } return c; } int * mergeSort(int arr[], int start, int end) { if(start == end) { int *a = new int(1); a[0] = start; return a; } int mid = (start + end)/2; int *f1 = mergeSort(arr, start, mid); int *f2 = mergeSort(arr, mid+1, end); int *f3 = mergeTwoArrays(f1, f2); return f3; } void printArray(int arr[], int n) { for(int i=0; i<n; i++) cout<<arr[i]<<" "; } int main() { int arr[] = {7, 4, 1, 3, 6, 8, 2, 5}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"Array: "; printArray(arr, n); // mergeSort(arr, 0, n-1); cout<<"\nSorted Array: "; printArray(mergeSort(arr, 0, n-1), n); return 0; }
[ "sethidaksh02@gmail.com" ]
sethidaksh02@gmail.com
9aa174e6ba12c2f7e959c6820bdd66ead7fb6e65
c67e2f5a8c34025762ebcc1d2c9a1c6201efc4a2
/displace.cpp
8eae8a73d4d00ebcbc0a8b63ae81976a60a4f28c
[]
no_license
cmwilli5/Project_Gunner
0fa0e8dec4abba0947fc1c4f7d89ae17e6762f04
ce3b3ea3b2b04298cf0205e7b8270efd53b8362f
refs/heads/master
2020-04-13T21:55:33.395442
2017-03-23T02:03:37
2017-03-23T02:03:37
50,155,647
0
0
null
null
null
null
UTF-8
C++
false
false
568
cpp
#include "displace.h" #include <iostream> #include <locale> const std::string Position::name{"position"}; template<> Position buildFromLua<Position>(sol::object& obj) { Position p; sol::table tbl = obj; p.pastPosX = p.posX = tbl["x"].get_or(0.0f); p.pastPosY = p.posY = tbl["y"].get_or(0.0f); return p; } const std::string Velocity::name{"velocity"}; template<> Velocity buildFromLua<Velocity>(sol::object& obj) { Velocity v; sol::table tbl = obj; v.velX = tbl["x"].get_or(0.0f); v.velY = tbl["y"].get_or(0.0f); return v; }
[ "corithianmw96@gmail.com" ]
corithianmw96@gmail.com