blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b280728aa00cc773c440ab70001bb4dab5140028 | 04c0f4652bebe27bc7c931c2199d54462c175e8c | /BurndownExt/BurndownStruct.cpp | 2dc43b5ac9145041d950f4e4bdbce284936171d4 | [] | no_license | layerfsd/ToDoList_Dev | bdd5b892e988281b99b6167d6c64b6fe8466a8b8 | d9bb3c8999ee72bf85a92cc29f0d6aa14d3f3b35 | refs/heads/master | 2021-09-07T13:16:05.508224 | 2018-02-23T10:31:21 | 2018-02-23T10:31:32 | 125,009,385 | 2 | 2 | null | 2018-03-13T07:22:51 | 2018-03-13T07:22:51 | null | UTF-8 | C++ | false | false | 8,630 | cpp | // BurndownWnd.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "BurndownExt.h"
#include "BurndownWnd.h"
#include "..\shared\mapex.h"
#include "..\shared\misc.h"
#include "..\shared\themed.h"
#include "..\shared\graphicsmisc.h"
#include "..\shared\dialoghelper.h"
#include "..\shared\datehelper.h"
#include "..\shared\holdredraw.h"
#include "..\shared\enstring.h"
#include "..\Interfaces\ipreferences.h"
#include <float.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
STATSITEM::STATSITEM()
:
dwTaskID(0),
dTimeEst(0.0),
nTimeEstUnits(TDCU_DAYS),
dTimeSpent(0.0),
nTimeSpentUnits(TDCU_DAYS)
{
CDateHelper::ClearDate(dtStart);
CDateHelper::ClearDate(dtDone);
}
STATSITEM::~STATSITEM()
{
}
BOOL STATSITEM::HasStart() const
{
return CDateHelper::IsDateSet(dtStart);
}
BOOL STATSITEM::IsDone() const
{
return CDateHelper::IsDateSet(dtDone);
}
void STATSITEM::MinMax(COleDateTime& dtMin, COleDateTime& dtMax) const
{
MinMax(dtStart, dtMin, dtMax);
MinMax(dtDone, dtMin, dtMax);
}
void STATSITEM::MinMax(const COleDateTime& date, COleDateTime& dtMin, COleDateTime& dtMax)
{
if (CDateHelper::IsDateSet(date))
{
if (CDateHelper::IsDateSet(dtMin))
dtMin = min(dtMin, date);
else
dtMin = date;
if (CDateHelper::IsDateSet(dtMax))
dtMax = max(dtMax, date);
else
dtMax = date;
}
}
double STATSITEM::CalcTimeSpentInDays(const COleDateTime& date, int nDaysInWeek, double dHoursInDay) const
{
// Ignore tasks with no time spent
if (dTimeSpent == 0.0)
return 0.0;
double dTimeSpentDays = CalcTimeInDays(dTimeSpent, nTimeSpentUnits, nDaysInWeek, dHoursInDay);
BOOL bHasStart = HasStart();
double dDays = 0.0;
double dProportion = 0.0;
if (IsDone())
{
if (date >= dtDone)
{
dProportion = 1.0;
}
else if (bHasStart && (date > dtStart))
{
dProportion = (date.m_dt - dtStart.m_dt) / (dtDone.m_dt - dtStart.m_dt);
}
}
else if (bHasStart && (date > dtStart))
{
COleDateTime dtNow(COleDateTime::GetCurrentTime());
dProportion = (date.m_dt - dtStart.m_dt) / (dtNow.m_dt - dtStart.m_dt);
}
dProportion = max(0.0, min(dProportion, 1.0));
dDays += (dTimeSpentDays * dProportion);
return dDays;
}
double STATSITEM::CalcTimeEstimateInDays(int nDaysInWeek, double dHoursInDay) const
{
return CalcTimeInDays(dTimeEst, nTimeEstUnits, nDaysInWeek, dHoursInDay);
}
double STATSITEM::CalcTimeInDays(double dTime, TDC_UNITS nUnits, int nDaysInWeek, double dHoursInDay)
{
switch (nUnits)
{
case TDCU_WEEKDAYS:
case TDCU_DAYS:
return dTime;
}
// all the rest
TH_UNITS nTHUnits = MapUnitsToTHUnits(nUnits);
CTimeHelper th(dHoursInDay, nDaysInWeek);
return th.GetTime(dTime, nTHUnits, THU_WEEKDAYS);
}
TH_UNITS STATSITEM::MapUnitsToTHUnits(TDC_UNITS nUnits)
{
switch (nUnits)
{
case TDCU_NULL: return THU_NULL;
case TDCU_MINS: return THU_MINS;
case TDCU_HOURS: return THU_HOURS;
case TDCU_DAYS: return THU_DAYS;
case TDCU_WEEKDAYS: return THU_WEEKDAYS;
case TDCU_WEEKS: return THU_WEEKS;
case TDCU_MONTHS: return THU_MONTHS;
case TDCU_YEARS: return THU_YEARS;
}
// all else
ASSERT(0);
return THU_NULL;
}
/////////////////////////////////////////////////////////////////////////////
CStatsItemArray::CStatsItemArray()
{
}
CStatsItemArray::~CStatsItemArray()
{
RemoveAll();
}
STATSITEM* CStatsItemArray::AddItem(DWORD dwTaskID)
{
if (HasItem(dwTaskID))
{
ASSERT(0);
return NULL;
}
STATSITEM* pSI = new STATSITEM();
pSI->dwTaskID = dwTaskID;
Add(pSI);
m_setTaskIDs.Add(dwTaskID);
return pSI;
}
STATSITEM* CStatsItemArray::operator[](int nIndex) const
{
return CArray<STATSITEM*, STATSITEM*>::operator[](nIndex);
}
BOOL CStatsItemArray::HasItem(DWORD dwTaskID) const
{
return m_setTaskIDs.Has(dwTaskID);
}
int CStatsItemArray::FindItem(DWORD dwTaskID) const
{
if (!HasItem(dwTaskID))
return -1;
int nIndex = GetSize();
while (nIndex--)
{
const STATSITEM* pSI = GetAt(nIndex);
if (pSI->dwTaskID == dwTaskID)
return nIndex;
}
// not found
ASSERT(0);
return -1;
}
STATSITEM* CStatsItemArray::GetItem(DWORD dwTaskID) const
{
int nFind = FindItem(dwTaskID);
if (nFind == -1)
return NULL;
return GetAt(nFind);
}
int CStatsItemArray::GetSize() const
{
return CArray<STATSITEM*, STATSITEM*>::GetSize();
}
BOOL CStatsItemArray::IsEmpty() const
{
return (GetSize() == 0);
}
void CStatsItemArray::RemoveAll()
{
int nIndex = GetSize();
while (nIndex--)
{
STATSITEM* pSI = GetAt(nIndex);
delete pSI;
}
CArray<STATSITEM*, STATSITEM*>::RemoveAll();
m_setTaskIDs.RemoveAll();
}
void CStatsItemArray::RemoveAt(int nIndex, int nCount)
{
ASSERT(nIndex >= 0 && nIndex < GetSize());
ASSERT(nCount > 0);
nIndex += nCount;
while (nIndex--)
{
STATSITEM* pSI = GetAt(nIndex);
m_setTaskIDs.RemoveKey(pSI->dwTaskID);
delete pSI;
CArray<STATSITEM*, STATSITEM*>::RemoveAt(nIndex);
}
}
void CStatsItemArray::Sort()
{
if (!IsSorted())
{
qsort(GetData(), GetSize(), sizeof(STATSITEM*), CompareItems);
}
}
BOOL CStatsItemArray::IsSorted() const
{
int nNumItems = GetSize();
if (nNumItems < 2)
return TRUE;
const STATSITEM* pSI = GetAt(0);
ASSERT(pSI);
COleDateTime dtPrev = pSI->dtStart;
for (int nItem = 1; nItem < nNumItems; nItem++)
{
const STATSITEM* pSI = GetAt(nItem);
ASSERT(pSI);
if (pSI->HasStart())
{
// Stop if the preceding task has no start date
// OR the preceding task has a later date
if (!CDateHelper::IsDateSet(dtPrev) || (pSI->dtStart < dtPrev))
{
return FALSE;
}
}
dtPrev = pSI->dtStart;
}
return TRUE;
}
int CStatsItemArray::CompareItems(const void* pV1, const void* pV2)
{
typedef STATSITEM* LPSTATSITEM;
const STATSITEM* pSI1 = *(static_cast<const LPSTATSITEM*>(pV1));
const STATSITEM* pSI2 = *(static_cast<const LPSTATSITEM*>(pV2));
ASSERT(pSI1 && pSI2 && (pSI1 != pSI2));
// Sort by start date
// Tasks without a start date come last to optimise searching
BOOL bStart1 = CDateHelper::IsDateSet(pSI1->dtStart);
BOOL bStart2 = CDateHelper::IsDateSet(pSI2->dtStart);
if (bStart1 != bStart2)
{
return (bStart1 ? -1 : 1);
}
else if (!bStart1 && !bStart2)
{
return 0;
}
if (pSI1->dtStart < pSI2->dtStart)
return -1;
if (pSI1->dtStart > pSI2->dtStart)
return 1;
return 0;
}
double CStatsItemArray::CalcTimeSpentInDays(const COleDateTime& date, int nDaysInWeek, double dHoursInDay) const
{
int nNumItems = GetSize();
double dDays = 0;
for (int nItem = 0; nItem < nNumItems; nItem++)
{
const STATSITEM* pSI = GetAt(nItem);
// We can stop as soon as we pass a task's start date
if (pSI->HasStart() && (pSI->dtStart >= date))
break;
dDays += pSI->CalcTimeSpentInDays(date, nDaysInWeek, dHoursInDay);
}
return dDays;
}
double CStatsItemArray::CalcTotalTimeEstimateInDays(int nDaysInWeek, double dHoursInDay) const
{
double dDays = 0;
int nItem = GetSize();
while (nItem--)
{
dDays += GetAt(nItem)->CalcTimeEstimateInDays(nDaysInWeek, dHoursInDay);
}
return dDays;
}
void CStatsItemArray::GetDataExtents(COleDateTime& dtEarliestDate, COleDateTime& dtLatestDate) const
{
if (GetSize())
{
CDateHelper::ClearDate(dtEarliestDate);
CDateHelper::ClearDate(dtLatestDate);
int nItem = GetSize();
while (nItem--)
GetAt(nItem)->MinMax(dtEarliestDate, dtLatestDate);
}
else
{
dtEarliestDate = dtLatestDate = COleDateTime::GetCurrentTime();
}
}
int CStatsItemArray::CalculateIncompleteTaskCount(const COleDateTime& date, int nItemFrom, int& nNextItemFrom) const
{
int nNumItems = GetSize();
int nNumNotDone = 0;
int nEarliestNotDone = -1, nLatestDone = -1;
for (int nItem = nItemFrom; nItem < nNumItems; nItem++)
{
const STATSITEM* pSI = GetAt(nItem);
if (pSI->dtStart > date)
break;
if (!pSI->IsDone() || (pSI->dtDone > date))
{
nNumNotDone++;
if ((nEarliestNotDone == -1) && pSI->HasStart())
nEarliestNotDone = nItem;
}
else if (nLatestDone == -1)
{
nLatestDone = nItem;
}
else if (pSI->dtDone > GetAt(nLatestDone)->dtDone)
{
nLatestDone = nItem;
}
}
// If the earliest incomplete task in the sequence starts before
// the very last completed task then in the next iteration we need
// only process tasks beginning with the earliest incomplete task
// because we have proved that all tasks starting before this
// task have also been completed
if ((nEarliestNotDone != -1) && (nLatestDone != -1) && (nEarliestNotDone > nLatestDone))
nNextItemFrom = nEarliestNotDone;
return nNumNotDone;
}
| [
"[email protected]"
] | |
402ebbce2ce2f97524e4493fbe0fe57d960de539 | bfc9e59bccad0a22e6198c2116ce595cbd75bddf | /CS256-Cpp/day2.cpp | ddae9ee498f3b1c30c22386913dea2af308a1c64 | [] | no_license | jarodNakamoto/College-CS-Courses | 2927cccec1aa4ef88592d37c173c4e44bdba1882 | c5040daf1dd927c8a168a472ca6a2ddb6eb1b5ff | refs/heads/master | 2021-06-05T00:08:47.206622 | 2017-11-30T22:36:36 | 2017-11-30T22:36:36 | 58,011,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 251 | cpp | #include <iostream>
#include <string>
using namespace std;
int main()
{
int x = 40;
int max = 30;
int y = 35;
// equivalent statement
if(x > y)
max = x;
else
max = y;
// conditional operator
max = (x>y)?x:y;
}
| [
"[email protected]"
] | |
4cf409d8622e0fd05ff2be6c5755b2d115869183 | b8376621d63394958a7e9535fc7741ac8b5c3bdc | /lib/lib_mech/src/server/TServer/TCommonClient/protocal/GameServer/G_ERROR.hpp | 5766929f7aed605521485ca176803453b170d890 | [] | no_license | 15831944/job_mobile | 4f1b9dad21cb7866a35a86d2d86e79b080fb8102 | ebdf33d006025a682e9f2dbb670b23d5e3acb285 | refs/heads/master | 2021-12-02T10:58:20.932641 | 2013-01-09T05:20:33 | 2013-01-09T05:20:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,013 | hpp |
#ifndef GameServer___G_ERROR__
#define GameServer___G_ERROR__
#ifndef GameServer_jNOTUSE_PACKET_JXDEFINE
jxDECL_GameServer(GameServer);
jxDECL_GameServer(G_ERROR);
#endif //GameServer_jNOTUSE_PACKET_JXDEFINE
namespace nMech { namespace nNET { namespace nGameServer
{
const int pk_G_ERROR = /*nMech::nNET::EProtocal_jINet_OGS_END+*/3000+2;
/* jErrorInfo ei;*/
struct S_G_ERROR;
bool READ_G_ERROR(jIPacketSocket_IOCP* pS,uint16 data_size,BYTE *buffer, S_G_ERROR ¶m);
struct S_G_ERROR
{
jErrorInfo ei;
#ifndef jNOT_USE_PACKET_SET_GET_FUNC_GameServer
#endif //jNOT_USE_PACKET_SET_GET_FUNC_GameServer
#ifndef jNOT_USE_DebugPrint_GameServer
void DebugPrint(bool isPrintAll)
{
using namespace nMech::nInterface;
jLOG(_T("< G_ERROR > ="));
if(!isPrintAll)return;
jDebugPrint(_T("ei"),ei);
}
#endif //jNOT_USE_DebugPrint_
void ReadPacket(jIPacketSocket_IOCP* pS,jPacket_Base* pk)
{
READ_G_ERROR(pS,pk->GetLen(),pk->buf,*this);
}
};
#ifndef jNOT_USE_PACKET_READ_FUNC_GameServer
inline bool READ_G_ERROR(jIPacketSocket_IOCP* pS,uint16 data_size , BYTE *buffer, S_G_ERROR ¶m)
{
try{
nMech::nNET::nStream::jNetStreamRead st(buffer,data_size);
nStream::Read(st,param.ei);
#ifndef jNOT_USE_DebugPrint_GameServer
if(pS)pS->DebugPrint();
param.DebugPrint(true);
#endif
if(st.GetCurrPos()>data_size) throw _T("st.GetCurrPos()>data_size");
}catch(tcstr sz){jWARN_T("G_ERROR : %s (data_size=%u " , sz,data_size); return false;}
return true;
}
#endif //jNOT_USE_PACKET_READ_FUNC_GameServer
#ifndef jNOT_USE_PACKET_WRITE_FUNC_GameServer
inline jPacket_Base WRITE_G_ERROR(nNET::nStream::_jNetStreamWriteBufferBase &buffer, S_G_ERROR ¶m)
{
try{
nMech::nNET::nStream::jNetStreamWrite st(buffer);
nStream::Write(st,param.ei);
if(st.size()>st.capacity() ) throw _T("st.size()>st.capacity");
jPacket_Base pk; pk.num = pk_G_ERROR;
pk.buf=st.GetBuffer(); pk.len=(jPacketNum_t)st.size(); return pk;
}catch(tcstr sz){ jERROR(_T(" G_ERROR :data overflow: %s"),sz); }
catch(nStream::jNetStreamWrite_error i){ jERROR(_T(" G_ERROR :overflow: (curr=%d,capa=%d,size=%d)"),i.currLen,i.capa , i.isize); }
jPacket_Base pk;pk.buf=0;pk.len=0;pk.num=0;return pk;
};
inline jPacket_Base WRITE_G_ERROR(nNET::nStream::_jNetStreamWriteBufferBase &buffer , const jErrorInfo &_ei)
{
try{
nMech::nNET::nStream::jNetStreamWrite st(buffer);
nStream::Write(st,_ei);
if(st.size()>st.capacity() ) throw _T("st.size()>st.capacity");
jPacket_Base pk; pk.num = pk_G_ERROR;
pk.buf=st.GetBuffer(); pk.len=(jPacketNum_t)st.size(); return pk;
}catch(tcstr sz){ jERROR(_T(" G_ERROR :data overflow: %s"),sz); }
catch(nStream::jNetStreamWrite_error i){ jERROR(_T(" G_ERROR :overflow: (curr=%d,capa=%d,size=%d)"),i.currLen,i.capa , i.isize); }
jPacket_Base pk;pk.buf=0;pk.len=0;pk.num=0;return pk;
};
#endif //jNOT_USE_PACKET_WRITE_FUNC_GameServer
}/*nGameServer */ }/* nNET*/ } //nMech
#endif //GameServer___G_ERROR__ | [
"[email protected]"
] | |
3a9b16aba34c1400e998c52e5f7fbbbb07bf3267 | 89cf7930fc4d4e448afbec07fa226967bcea1b01 | /DLL430_v3/src/TI/DLL430/EM/TriggerCondition/AddressRangeCondition430.h | ee0f235bf6276fa5a1d49391f12670f312e9d92f | [] | no_license | jck/mspds | 4b384de769a0fbd6e8cd16207e72b9b9fb67cfd3 | d8d099e7274db434475f99723bb2d234f2ff6dfb | refs/heads/master | 2020-03-30T03:08:17.944317 | 2015-01-15T06:29:33 | 2015-01-15T06:29:33 | 29,283,923 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,999 | h | /*
* AddressRangeCondition430.h
*
* Implementation of address range trigger conditions for 430
*
* Copyright (C) 2007 - 2011 Texas Instruments Incorporated - http://www.ti.com/
*
*
* 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 Texas Instruments Incorporated 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.
*/
#pragma once
#include "TriggerCondition430.h"
#include "IInstructionRangeCondition.h"
#include "IAddressRangeCondition.h"
namespace TI { namespace DLL430 {
class Trigger430;
class AddressRangeCondition430 : public TriggerCondition430, public IInstructionRangeCondition, public IAddressRangeCondition
{
public:
AddressRangeCondition430(TriggerManager430Ptr triggerManager, uint32_t minAddress, uint32_t maxAddress,
uint32_t minMask = 0xffffffff, uint32_t maxMask = 0xffffffff, AccessType = AT_FETCH, bool outside = false);
virtual void setAccessType(AccessType accessType);
virtual void setInside();
virtual void setOutside();
virtual void setMinAddress(uint32_t address, uint32_t mask = 0xffffffff);
virtual void setMaxAddress(uint32_t address, uint32_t mask = 0xffffffff);
virtual void addReaction(TriggerReaction reaction) { TriggerCondition430::addReaction(reaction); }
virtual void removeReaction(TriggerReaction reaction) { TriggerCondition430::removeReaction(reaction); }
virtual void combine(TriggerConditionPtr condition) { TriggerCondition430::combine(condition); }
virtual uint32_t getId() const { return TriggerCondition430::getId(); }
private:
Trigger430 *minTrigger_;
Trigger430 *maxTrigger_;
};
}}
| [
"[email protected]"
] | |
af285b3d87e8c13aeee3a76efcebbfac80c8c8ca | 97fbb9bd450080bca4f0eef0ec313322ac7c3dc0 | /cmake/test.cpp | a75dc8f4e0e24949e0c42cf41672b4288e7a95fd | [] | no_license | danieleTrimarchi/sandbox | 81dc77d6dfb23d6aae85f761ebd3b1984393938b | 05762a412da2bb7d7abcc3a18c5563e07bb60fb8 | refs/heads/master | 2023-03-30T02:56:52.680396 | 2021-03-15T14:43:30 | 2021-03-15T14:43:30 | 281,438,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 689 | cpp | #include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
void main(int argc, char** argv){
std::cout << "Hello,world\n";
std::cout << "argv[0]= "<< argv[0] << std::endl;
char basePath[255] = "";
_fullpath(basePath, argv[0], sizeof(basePath));
std::cout << "basePath= " << basePath << std::endl;
// Get the executable path without the executable name
fs::path absPath(fs::absolute(fs::path(argv[0])));
std::cout << "fsPath2= " << absPath << std::endl;
while (true) {
}
try {
throw("Some message!");
}
catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
catch (...) {
std::cout << "unknown exception caught" << std::endl;
}
}
| [
"[email protected]"
] | |
326a048114e4377919c5393a1850aedd486500f3 | 1fdbb7e551cf8b52b43359cf406bedd969b5f59f | /source/server/pkmodserver/pkmodbusdata_eview/ForwardAccessor.cpp | 5a2ed7dce264cdf7023c63aabf29d3f2ba092b6c | [] | no_license | trigrass2/eview-server | 1292958416ebe772ff4ce0b1f1639c65ca13ce92 | a5e452016a730af79a1d402a3d918403eb6073aa | refs/heads/master | 2023-06-17T09:38:25.004889 | 2021-07-15T09:45:56 | 2021-07-15T09:45:56 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,836 | cpp | /**************************************************************
* Filename: CC_GEN_DRVCFG.CPP
* Copyright: Shanghai Peak InfoTech Co., Ltd.
*
* Description: $().
*
**************************************************************/
#include "../pkmodserver/include/modbusdataapi.h"
#include "pkdata/pkdata.h"
#include "pklog/pklog.h"
#include "json/json.h"
CPKLog g_logger;
#ifdef _WIN32
#define MODBUSDATAAPI_EXPORTS extern "C" __declspec(dllexport)
#else //_WIN32
#define MODBUSDATAAPI_EXPORTS extern "C"
#endif //_WIN32
PKHANDLE g_hPKData = NULL;
MODBUSDATAAPI_EXPORTS int Init(ModbusTagVec &modbusTagVec)
{
string strTagNames;
vector<ModbusTag *>::iterator itTag = modbusTagVec.begin(); // 是按照每个tag点对应的起始地址排序的。
for(itTag = modbusTagVec.begin(); itTag != modbusTagVec.end(); itTag ++)
{
ModbusTag *pTag = *itTag;
if(strTagNames.empty())
strTagNames = pTag->szName;
else
strTagNames = strTagNames + ", " + pTag->szName;
}
g_logger.LogMessage(PK_LOGLEVEL_NOTICE, "modbuspkdata, Init(count=%d), tag:%s",modbusTagVec.size(), strTagNames.c_str());
g_hPKData = pkInit(NULL,NULL,NULL);
if(g_hPKData == NULL)
{
g_logger.LogMessage(PK_LOGLEVEL_ERROR, "modbuspkdata, Init(count=%d) failed,g_hPKData == NULL",modbusTagVec.size());
return -1;
}
g_logger.LogMessage(PK_LOGLEVEL_NOTICE, "modbuspkdata, Init(count=%d) success,g_hPKData == %ld",modbusTagVec.size(), (long)g_hPKData);
return 0;
}
// 读取tag点的值,并保存回tag点中
MODBUSDATAAPI_EXPORTS int ReadTags(ModbusTagVec &modbusTagVec)
{
if(g_hPKData == NULL)
{
g_logger.LogMessage(PK_LOGLEVEL_ERROR, "modbuspkdata, must inited first,g_hPKData == NULL,ReadTags,count=%d",modbusTagVec.size());
return -2;
}
else
g_logger.LogMessage(PK_LOGLEVEL_INFO, "modbuspkdata, ReadTags,count=%d",modbusTagVec.size());
if(modbusTagVec.size() <= 0)
return 0;
PKDATA *pkDatas = new PKDATA[modbusTagVec.size()]();
// 组织批量读取接口
int iTag = 0;
vector<ModbusTag *>::iterator itTag = modbusTagVec.begin(); // 是按照每个tag点对应的起始地址排序的。
for(itTag = modbusTagVec.begin(); itTag != modbusTagVec.end(); itTag ++)
{
ModbusTag *pTag = *itTag;
memset(pTag->szValue, 0, sizeof(pTag->szValue));
vector<string> vecObjPropField = PKStringHelper::StriSplit(pTag->szName, "."); // object.prop.field(picchose.value)---->picchose value
string strTagName = vecObjPropField[0]; // tag名称
string strField = "";
if (vecObjPropField.size() >= 2)
strField = vecObjPropField[vecObjPropField.size() - 1]; // 取最后一段
for (int i = 1; i < vecObjPropField.size() - 1; i++)
{
strTagName = strTagName + "." + vecObjPropField[i];
}
//暂时认为一定是value
if (PKStringHelper::StriCmp(strField.c_str(), "value") != 0 && PKStringHelper::StriCmp(strField.c_str(), "v") != 0) // 如果最后一段不是value,tag名为picchose.text
{
strField = "v";
if (strField.length() >= 1)
strTagName = strTagName + "." + strField;
strField = "v"; // 取最后一段, 使用v而不是value
}
else
{
strField = "v"; // 取最后一段v而不是value
}
PKStringHelper::Safe_StrNCpy(pkDatas[iTag].szObjectPropName, strTagName.c_str(), sizeof(pkDatas[iTag].szObjectPropName)); // field
PKStringHelper::Safe_StrNCpy(pkDatas[iTag].szFieldName, strField.c_str(), sizeof(pkDatas[iTag].szFieldName)); // field
iTag ++;
}
int nRet = pkMGet(g_hPKData, pkDatas, modbusTagVec.size());
if(nRet != 0)
{
g_logger.LogMessage(PK_LOGLEVEL_ERROR, "pkMGet failed(count=%d),ret:%d", modbusTagVec.size(), nRet);
}
// 将结果一个一个赋值
iTag = 0;
for(itTag = modbusTagVec.begin(); itTag != modbusTagVec.end(); itTag ++)
{
ModbusTag *pTag = *itTag;
if(nRet == 0 && pkDatas[iTag].nStatus == 0)
{
PKStringHelper::Safe_StrNCpy(pTag->szValue, pkDatas[iTag].szData, sizeof(pTag->szValue));
pTag->nStatus = 0;
/*
Json::Reader jsonReader;
Json::Value root;
if(jsonReader.parse(pkDatas[iTag].szData, root, false) == false)
{
g_logger.LogMessage(PK_LOGLEVEL_ERROR, "ReadTags,tag=%s,value=%s,not json format!", pkDatas[iTag].szName, pkDatas[iTag].szData);
pTag->nStatus = -100;
}
else
{
if(root["v"].isNull())
{
g_logger.LogMessage(PK_LOGLEVEL_ERROR, "ReadTags,tag=%s,value=%s, not found v or v invalid", pkDatas[iTag].szName, pkDatas[iTag].szData);
pTag->nStatus = -200;
}
else
{
strncpy(pTag->szValue, root["v"].asString().c_str(), sizeof(pTag->szValue) - 1);
pTag->nStatus = 0;
}
}*/
}
else
{
// 错误时将值置为空字符串
pTag->szValue[0] = '\0';
if(pkDatas[iTag].nStatus != 0)
pTag->nStatus = pkDatas[iTag].nStatus;
else
pTag->nStatus = 0;
}
iTag ++;
}
delete [] pkDatas;
pkDatas = NULL;
return nRet;
}
MODBUSDATAAPI_EXPORTS int WriteTags(ModbusTagVec &modbusTagVec)
{
if(g_hPKData == NULL)
{
g_logger.LogMessage(PK_LOGLEVEL_ERROR, "modbuspkdata, must inited first,g_hPKData == NULL,on WriteTags count=%d=",modbusTagVec.size());
return -2;
}
else
g_logger.LogMessage(PK_LOGLEVEL_INFO, "modbuspkdata, WriteTags(from pkdata),count=%d",modbusTagVec.size());
if(modbusTagVec.size() <= 0)
return 0;
PKDATA *pkDatas = new PKDATA[modbusTagVec.size()]();
// 组织批量接口
string strTagFields = "";
int iTag = 0;
vector<ModbusTag *>::iterator itTag = modbusTagVec.begin(); // 是按照每个tag点对应的起始地址排序的。
for(itTag = modbusTagVec.begin(); itTag != modbusTagVec.end(); itTag ++)
{
ModbusTag *pTag = *itTag;
vector<string> vecObjPropField = PKStringHelper::StriSplit(pTag->szName,"."); // object.prop.field(picchose.value)---->picchose value
string strField = vecObjPropField[vecObjPropField.size() - 1]; // 取最后一段
string strTagName = vecObjPropField[0];
for (int i = 1; i < vecObjPropField.size() - 1; i++)
{
strTagName = strTagName + "." + vecObjPropField[i];
}
//暂时认为一定是value
if (PKStringHelper::StriCmp(strField.c_str(), "value") != 0) // 如果最后一段不是value,tag名为picchose.text
{
strTagName = strTagName + "." + vecObjPropField[vecObjPropField.size() - 1];
strField = "value"; // 取最后一段
}
else
{
strField = "value"; // 取最后一段
}
memset(pkDatas[iTag].szObjectPropName, 0, sizeof(pkDatas[iTag].szObjectPropName)); // tagname
PKStringHelper::Safe_StrNCpy(pkDatas[iTag].szObjectPropName, strTagName.c_str(), sizeof(pkDatas[iTag].szObjectPropName)); // field
PKStringHelper::Safe_StrNCpy(pkDatas[iTag].szFieldName, strField.c_str(), sizeof(pkDatas[iTag].szFieldName)); // field
memset(pkDatas[iTag].szData, 0, pkDatas[iTag].nDataBufLen);
PKStringHelper::Safe_StrNCpy(pkDatas[iTag].szData, pTag->szValue, pkDatas[iTag].nDataBufLen);
pkDatas[iTag].nStatus = 0;// 写入时设置为GOOD
if (itTag == modbusTagVec.begin()) // 第一个
strTagFields = pkDatas[iTag].szFieldName;
else
strTagFields = strTagFields + ";" + pkDatas[iTag].szFieldName;
iTag ++;
}
int nRet = pkMControl(g_hPKData, pkDatas, modbusTagVec.size());
if(nRet != 0)
{
g_logger.LogMessage(PK_LOGLEVEL_ERROR, "pkMControl(tagcount=%d,tagfield:%s) failed,ret:%d", modbusTagVec.size(), strTagFields.c_str(), nRet);
}
else
g_logger.LogMessage(PK_LOGLEVEL_NOTICE, "pkMControl(tagcount=%d,tagfield:%s) success",modbusTagVec.size(), strTagFields.c_str());
// 将结果一个一个赋值
iTag = 0;
for(itTag = modbusTagVec.begin(); itTag != modbusTagVec.end(); itTag ++)
{
ModbusTag *pTag = *itTag;
pkDatas[iTag].nStatus = nRet;
iTag ++;
}
delete [] pkDatas;
pkDatas = NULL;
return nRet;
}
MODBUSDATAAPI_EXPORTS int UnInit(ModbusTagVec &modbusTagVec)
{
if(g_hPKData != NULL)
pkExit(g_hPKData);
g_hPKData = NULL;
return 0;
}
| [
"[email protected]"
] | |
c89874ac24afb87505ea913028909a5d7cf5c837 | 1240d45f343bad61d28064bf21d42579182ca499 | /lib/DigitalInputConfigurations.cpp | 55817c78b9dd0002809f1f3d604fabb2b90e7ace | [] | no_license | michael-christen/digilent-simplified | 3720bfc2950b94e030862de7262a8f462bc6e4b8 | 76ddc6a22928729e9604595b1504a9c008a55b3a | refs/heads/master | 2020-12-29T19:03:47.161837 | 2015-12-19T23:19:04 | 2015-12-19T23:19:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,626 | cpp | /* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
* File Name : DigitalInputConfigurations.cpp
* Purpose :
* Creation Date : 28-09-2015
* Created By : Michael Christen
_._._._._._._._._._._._._._._._._._._._._.*/
#include "DigitalInputConfigurations.h"
namespace dwf{
IMPL_SET_CONFIG_ALL(DigitalInClockSource, DwfDigitalInClockSource);
DigitalInDivider::DigitalInDivider(HDWF d)
: ContinuousRangeConfiguration<unsigned int>(d) {
range.min = 1;
DWF(DigitalInDividerInfo(device, &(range.max)));
}
IMPL_CONFIG_GETNSET(DigitalInDivider, unsigned int);
DigitalInSampleFormat::DigitalInSampleFormat(HDWF d)
: SetConfiguration<int>(d) {
//options.insert(8);
options.insert(DIGITAL_DATA_SIZE);
//options.insert(32);
}
IMPL_CONFIG_GETNSET(DigitalInSampleFormat, int);
DigitalInBufferSize::DigitalInBufferSize(HDWF d)
: ContinuousRangeConfiguration<int>(d) {
//BufferSize info changes with sampleFormat, so don't change format
range.min = 1;
DWF(DigitalInBufferSizeInfo(device, &(range.max)));
}
IMPL_CONFIG_GETNSET(DigitalInBufferSize, int);
IMPL_SET_CONFIG_ALL(DigitalInSampleMode, DwfDigitalInSampleMode);
IMPL_SET_CONFIG_ALL(DigitalInAcquisitionMode, ACQMODE);
IMPL_SET_CONFIG_ALL(DigitalInTriggerSource, TRIGSRC);
DigitalInTriggerPosition::DigitalInTriggerPosition(HDWF d)
: ContinuousRangeConfiguration<unsigned int>(d) {
range.min = 0;
DWF(DigitalInTriggerPositionInfo(device, &(range.max)));
}
IMPL_CONFIG_GETNSET(DigitalInTriggerPosition, unsigned int);
IMPL_DR_CONFIG_ALL(DigitalInTriggerAutoTimeout, double);
DigitalInTrigger::DigitalInTrigger(HDWF d)
: BitSetConfiguration<DigitalInTriggerStruct>(d) {
DWF(DigitalInTriggerInfo(device,
&(bitmask.levelLow),
&(bitmask.levelHigh),
&(bitmask.edgeRise),
&(bitmask.edgeFall)));
}
void DigitalInTrigger::setImpl(DigitalInTriggerStruct val) {
DWF(DigitalInTriggerSet(device,
val.levelLow,
val.levelHigh,
val.edgeRise,
val.edgeFall));
}
DigitalInTriggerStruct DigitalInTrigger::getImpl() {
DigitalInTriggerStruct val;
DWF(DigitalInTriggerGet(device,
&(val.levelLow),
&(val.levelHigh),
&(val.edgeRise),
&(val.edgeFall)));
return val;
}
std::ostream& operator<<(std::ostream& os, const DigitalInTriggerStruct& obj) {
os << "LL: " << obj.levelLow << "\n"
<< "LH: " << obj.levelHigh << "\n"
<< "ER: " << obj.edgeRise << "\n"
<< "EF: " << obj.edgeFall;
return os;
}
}
| [
"[email protected]"
] | |
301e90cb3a8440343576d7b31130911bcc78d90c | 569e079f8cc8bc4a1b6918137c951c0a049ea593 | /src/scn/nodes/CParticleEmitterBox.cpp | e147b1aef1d07dfc46c2b2df47ca6d84a05342ab | [] | no_license | zdementor/my-base | c741daee7f032408fa47f02f715f9066f1f9871f | 2635462c0a57bd423551251f04da10bada277821 | refs/heads/master | 2021-01-10T01:43:03.318268 | 2020-11-19T18:18:32 | 2020-11-19T18:18:32 | 51,708,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,143 | cpp | //|-------------------------------------------------------------------------
//| File: CParticleEmitterBox.cpp
//|
//| Descr: This file is a part of the 'MyEngine'
//| Author: Zhuk 'zdementor' Dmitry (aka ZDimitor)
//| Email: [email protected], [email protected]
//|
//| Copyright (c) 2004-2009 by Zhuk Dmitry, Krasnoyarsk - Moscow
//| All Rights Reserved.
//|-------------------------------------------------------------------------
#include "CParticleEmitterBox.h"
//----------------------------------------------------------------------------
namespace my {
namespace scn {
//----------------------------------------------------------------------------
CParticleBoxEmitter::CParticleBoxEmitter(
core::aabbox3df box,
core::vector3df direction, u32 minParticlesPerSecond,
u32 maxParticlePerSecond, img::SColor minStartColor,
img::SColor maxStartColor, u32 lifeTimeMin, u32 lifeTimeMax,
s32 maxAngleDegrees)
: CParticleEmitter(
box, direction,
minParticlesPerSecond, maxParticlePerSecond,
minStartColor, maxStartColor, lifeTimeMin, lifeTimeMax,
maxAngleDegrees)
{
#if MY_DEBUG_MODE
IUnknown::setClassName("CParticleBoxEmitter");
#endif
}
//----------------------------------------------------------------------------
s32 CParticleBoxEmitter::emitt(
u32 now, u32 timeSinceLastCall, const core::matrix4 &transformation,
const core::vector3df& horiz_normalized, const core::vector3df& vert_normalized)
{
if (m_Particles.size() > 16386)
return 0;
s32 amount = 0;
if (m_Enabled)
{
m_Time += timeSinceLastCall;
u32 pps = (m_MaxParticlesPerSecond - m_MinParticlesPerSecond);
f32 perSecond = pps ?
(f32)m_MinParticlesPerSecond + (core::math::Random() % pps) :
m_MinParticlesPerSecond;
f32 everyWhatMillisecond = 1000.0f / (perSecond==0 ? 0.000001f : perSecond);
if (m_Time > everyWhatMillisecond)
{
img::SColor min_start_solor, max_start_solor;
if (m_GL)
{
min_start_solor = m_MinStartColor.toOpenGLColor();
max_start_solor = m_MaxStartColor.toOpenGLColor();
}
else
{
min_start_solor = m_MinStartColor;
max_start_solor = m_MaxStartColor;
}
amount = (s32)((m_Time / everyWhatMillisecond) + 0.5f);
m_Time = 0;
core::vector3df extend = m_AppearVolume.getExtend();
if (amount > (s32)m_MaxParticlesPerSecond*2)
amount = m_MaxParticlesPerSecond * 2;
f64 len = m_Direction.getLength();
for (s32 i = 0; i < amount; ++i)
{
SParticle *p = new SParticle();
p->pos.X = m_AppearVolume.MinEdge.X + fmodf((f32)core::math::Random(), extend.X);
p->pos.Y = m_AppearVolume.MinEdge.Y + fmodf((f32)core::math::Random(), extend.Y);
p->pos.Z = m_AppearVolume.MinEdge.Z + fmodf((f32)core::math::Random(), extend.Z);
transformation.transformVect(p->pos);
p->startTime = now;
p->vector = m_Direction;
if (m_MaxAngleDegrees)
{
core::vector3df tgt = m_Direction;
tgt.rotateXYByDegrees(
(core::math::Random() % (m_MaxAngleDegrees*2)) - m_MaxAngleDegrees,
core::vector3df(0,0,0));
tgt.rotateYZByDegrees(
(core::math::Random()%(m_MaxAngleDegrees*2)) - m_MaxAngleDegrees,
core::vector3df(0,0,0));
p->vector = tgt;
}
if (m_MaxLifeTime - m_MinLifeTime == 0)
p->endTime = now + m_MinLifeTime;
else
p->endTime = now + m_MinLifeTime + (core::math::Random() % (m_MaxLifeTime - m_MinLifeTime));
p->color = min_start_solor.getInterpolated(
max_start_solor, (core::math::Random() % 100) / 100.0f);
p->startColor = p->color;
p->startVector = p->vector;
m_Particles.push_back(p);
}
}
}
CParticleEmitter::emitt(
now, timeSinceLastCall, transformation, horiz_normalized, vert_normalized);
return amount;
}
//----------------------------------------------------------------------------
} // end namespace scn
} // end namespace my
//----------------------------------------------------------------------------
| [
"[email protected]"
] | |
b61b24e20e3b3cc95f71226f7ad7ef3339a8177d | d625eb0f2e675d6e40b0849d1e5f20b1aef4c406 | /codeforce/Codeforce_Rating_Round/Alpha_Round_20/c_test.cpp | 70e0b1c9ebf2d8bfcb0f2b9246fde04210945bf9 | [] | no_license | aseem01/Competitive_Programming | b5a57c7b10b731ea2b03288c500dd85c8f5fda2c | ad7354c56cada964b2c5331f15424d580febe2b6 | refs/heads/master | 2021-01-25T11:28:57.402352 | 2018-11-09T06:59:46 | 2018-11-09T06:59:46 | 93,930,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,060 | cpp | //----->|try=0; while(!success) try++;|<------
//----->|Belief Yourself,Respect Yourself|<----
//----->|Be Proud Of Yourself,You're Doing Your best|<-----
#include<bits/stdc++.h>
using namespace std;
#define uniq(x) x.erase(unique(x.begin(),x.end()), x.end()) //Unique value find from vector
#define upper(arr,n,fixed) upper_bound(arr,arr+n,fixed)-arr //Upper value search;
#define lower(arr,n,fixed) upper_bound(arr,arr+n,fixed)-arr //Lower value search;
#define max3(a,b,c) max(max(a,b),c)//maximum value find three value;
#define min3(a,b,c) min(min(a,b),c)//minimum value find three value;
#define rep(i, n) for(int i = 0; i < n; ++i)
#define REP(i, n) for(int i = 1; i <= n; ++i)
#define rep1(i,start,n) for(int i=start;i<n;++i)
#define PI acos(-1.0)//PI Calculation
#define LL long long
#define AND(a,b) ((a) & (b))
#define OR(a,b) ((a)|(b))
#define XOR(a,b) ((a) ^ (b))
#define MP make_pair
#define sqr(x) ((x)*(x))
#define sqrt(x) sqrt(1.0*(x))
#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define MX 20010
#define MOD 1000000007
#define inf 200000000
template<typename T> T POW(T b,T p) //Pow calculation
{
T r=1;
while(p)
{
if(p&1)r=(r*b);
b=(b*b);
p>>=1;
}
return r;
}
template<typename T> T BigMod(T b,T p,T m) //BigMod Calculation
{
T r=1;
while(p)
{
if(p&1)r=(r*b)%m;
b=(b*b)%m;
p>>=1;
}
return r;
}
//||--------------------------->||Main_Code_Start_From_Here||<---------------------------------||
struct data
{
int u;
LL w;
data(int a,LL b)
{
u=a;
w=b;
}
bool operator<(const data& p) const
{
return w>p.w;
}
};
int par[MX];
LL dist[MX];
vector<pair<int,int> > adj[MX];
LL dijkstra(int start,int desti,int end)
{
for(int i=0;i<=end;i++) dist[i]=inf;
memset(par,-1,sizeof(par));
dist[start]=0;
priority_queue<data>q;
q.push(data(start,0));
while(!q.empty())
{
int u=q.top().u;
int w=q.top().w;
q.pop();
if(u==desti) return (dist[desti]);
//if(dist[u]<w) continue;
for(int i=0;i<(int)adj[u].size();i++)
{
int v=adj[u][i].first;
int wsec=adj[u][i].second;
if(dist[v]>w+wsec) //continue;
{
par[v]=u;
dist[v]=w+wsec;
q.push(data(v,dist[v]));
}
}
}
return inf;
}
int main()
{
//freopen("a.in", "r", stdin);
//freopen("a.out", "w", stdout);
int i,j,k,v,e,u1,u2,w,test,bb,end,start,t=1;
cin>>test;
rep(i,test)
{
cin>>v>>e>>start>>end;
for(int j=0;j<=v;j++) adj[j].clear();
for(int j=0;j<e;j++)
{
cin>>u1>>u2>>w;
adj[u1].push_back(make_pair(u2,w));
adj[u2].push_back(make_pair(u1,w));
}
LL res=dijkstra(start,end,v);
//cout<<"res = "<<res<<endl;
if(res==inf) cout<<"Case #"<<t++<<": unreachable"<<endl;
else cout<<"Case #"<<t++<<": "<<res<<endl;
}
}
| [
"[email protected]"
] | |
95fce26e4f50e212248f04a1979ff1ed2b932c30 | a887bcb55f320475dc04bdde3a95a261925e69db | /Libraries/LibGUI/GAction.h | 009fa45a96a9e4bd3949af43cb1e705e2740cdb1 | [
"BSD-2-Clause"
] | permissive | CrociDB/serenity | 17071fa269ce413514f0c6a3128f8df972bf7e62 | 9d2c4d223a9eb0c9cbe488f7f36e42c8d84b1578 | refs/heads/master | 2020-07-21T11:46:36.970519 | 2019-09-13T21:56:37 | 2019-09-13T21:56:37 | 206,854,493 | 0 | 0 | BSD-2-Clause | 2019-09-06T18:42:54 | 2019-09-06T18:42:53 | null | UTF-8 | C++ | false | false | 3,983 | h | #pragma once
#include <AK/String.h>
#include <AK/Badge.h>
#include <AK/Function.h>
#include <AK/HashTable.h>
#include <AK/NonnullRefPtr.h>
#include <AK/RefCounted.h>
#include <AK/WeakPtr.h>
#include <AK/Weakable.h>
#include <LibDraw/GraphicsBitmap.h>
#include <LibGUI/GShortcut.h>
#include <LibGUI/GWindow.h>
class GAction;
class GActionGroup;
class GButton;
class GMenuItem;
class GWidget;
namespace GCommonActions {
NonnullRefPtr<GAction> make_cut_action(Function<void()>, GWidget* widget);
NonnullRefPtr<GAction> make_copy_action(Function<void()>, GWidget* widget);
NonnullRefPtr<GAction> make_paste_action(Function<void()>, GWidget* widget);
NonnullRefPtr<GAction> make_quit_action(Function<void()>);
};
class GAction : public RefCounted<GAction>
, public Weakable<GAction> {
public:
enum class ShortcutScope {
None,
ApplicationGlobal,
WidgetLocal,
};
static NonnullRefPtr<GAction> create(const StringView& text, Function<void(GAction&)> callback, GWidget* widget = nullptr)
{
return adopt(*new GAction(text, move(callback), widget));
}
static NonnullRefPtr<GAction> create(const StringView& text, RefPtr<GraphicsBitmap>&& icon, Function<void(GAction&)> callback, GWidget* widget = nullptr)
{
return adopt(*new GAction(text, move(icon), move(callback), widget));
}
static NonnullRefPtr<GAction> create(const StringView& text, const GShortcut& shortcut, Function<void(GAction&)> callback, GWidget* widget = nullptr)
{
return adopt(*new GAction(text, shortcut, move(callback), widget));
}
static NonnullRefPtr<GAction> create(const StringView& text, const GShortcut& shortcut, RefPtr<GraphicsBitmap>&& icon, Function<void(GAction&)> callback, GWidget* widget = nullptr)
{
return adopt(*new GAction(text, shortcut, move(icon), move(callback), widget));
}
~GAction();
GWidget* widget() { return m_widget.ptr(); }
const GWidget* widget() const { return m_widget.ptr(); }
String text() const { return m_text; }
GShortcut shortcut() const { return m_shortcut; }
const GraphicsBitmap* icon() const { return m_icon.ptr(); }
void set_icon(const GraphicsBitmap* icon) { m_icon = icon; }
Function<void(GAction&)> on_activation;
void activate();
bool is_enabled() const { return m_enabled; }
void set_enabled(bool);
bool is_checkable() const { return m_checkable; }
void set_checkable(bool checkable) { m_checkable = checkable; }
bool is_checked() const
{
ASSERT(is_checkable());
return m_checked;
}
void set_checked(bool);
void register_button(Badge<GButton>, GButton&);
void unregister_button(Badge<GButton>, GButton&);
void register_menu_item(Badge<GMenuItem>, GMenuItem&);
void unregister_menu_item(Badge<GMenuItem>, GMenuItem&);
const GActionGroup* group() const { return m_action_group.ptr(); }
void set_group(Badge<GActionGroup>, GActionGroup*);
private:
GAction(const StringView& text, Function<void(GAction&)> = nullptr, GWidget* = nullptr);
GAction(const StringView& text, const GShortcut&, Function<void(GAction&)> = nullptr, GWidget* = nullptr);
GAction(const StringView& text, const GShortcut&, RefPtr<GraphicsBitmap>&& icon, Function<void(GAction&)> = nullptr, GWidget* = nullptr);
GAction(const StringView& text, RefPtr<GraphicsBitmap>&& icon, Function<void(GAction&)> = nullptr, GWidget* = nullptr);
template<typename Callback>
void for_each_toolbar_button(Callback);
template<typename Callback>
void for_each_menu_item(Callback);
String m_text;
RefPtr<GraphicsBitmap> m_icon;
GShortcut m_shortcut;
bool m_enabled { true };
bool m_checkable { false };
bool m_checked { false };
ShortcutScope m_scope { ShortcutScope::None };
HashTable<GButton*> m_buttons;
HashTable<GMenuItem*> m_menu_items;
WeakPtr<GWidget> m_widget;
WeakPtr<GActionGroup> m_action_group;
};
| [
"[email protected]"
] | |
3cf3eafc49830904bacb1f6a3015b782dc6b2fc0 | 2b2aab59bb9b56c0956928e6e89f75a8b7fdd46e | /TinyFrame.cpp | 2eb8a1efbfd7df91d4ff6c301a161e8b7ce6b284 | [] | no_license | afbayonac/TinyFrame | 3302f00f5ccdf0fada5e514d366830e688120913 | 7f61a49e7ecf3e123a9db30bc8d9e0c57c6d40f7 | refs/heads/master | 2020-04-02T14:49:58.209650 | 2018-11-26T19:58:58 | 2018-11-26T19:58:58 | 154,540,733 | 0 | 2 | null | 2018-11-02T00:53:49 | 2018-10-24T17:24:38 | null | UTF-8 | C++ | false | false | 2,754 | cpp | #include "TinyFrame.h"
const uint8_t FLAG = 0x7e;
const uint8_t SCAPE = 0x7d;
const uint8_t INVERT_BIT = 0x20;
const uint8_t CONTROL = 0x03;
const uint8_t BROADCAST = 0xff;
bool scaped = false;
TinyFrame::TinyFrame(handler_response handler): TinyFrame(handler, BROADCAST) {}
TinyFrame::TinyFrame(handler_response handler, uint8_t dire) {
this->_handler = handler;
this->_dire = dire;
this->_maxLength = 64; // buffer Arduino
}
#ifdef TINYFRAME_DEBUG_TEENSY
bool TinyFrame::begin(HardwareSerial* port, usb_serial_class* DEBUG, unsigned long baud) {
this->begin(port, baud);
this->_DEBUG = DEBUG;
(*_DEBUG).println("~ [ DEBUG MODE TINY FRAME ] ~");
return true;
}
#endif
#ifdef TINYFRAME_DEBUG
bool TinyFrame::begin(HardwareSerial* port, HardwareSerial* DEBUG, unsigned long baud) {
this->begin(port, baud);
this->_DEBUG = DEBUG;
(*_DEBUG).println("~ [ DEBUG MODE TINY FRAME ] ~");
return true;
}
#endif
bool TinyFrame::begin(HardwareSerial* port, unsigned long baud) {
this->_port = port;
(*port).begin(baud);
while (!(*port));
return true;
}
void TinyFrame::collect() {
if (!this->_port->available()) return;
#if defined(TINYFRAME_DEBUG_TEENSY) || defined(TINYFRAME_DEBUG)
this->_DEBUG->print(" ");
this->_DEBUG->print(this->_port->peek(), HEX);
#endif
uint8_t data = this->_port->read();
if (data == FLAG || this->_position == this->_maxLength - 1) {
// validate an pass a handler
if (this->_position >= 4 &&
(this->_buffer[0] == 0xff || this->_buffer[0] == this->_dire ) &&
this->_buffer[1] == CONTROL &&
true ){
#if defined(TINYFRAME_DEBUG_TEENSY) || defined(TINYFRAME_DEBUG)
this->_DEBUG->println(" [CALL HANDLER] ");
#endif
this->_handler(&this->_buffer[2], this->_position - 4);
}
this->_scaped = false;
this->_buffer = (uint8_t *) malloc(this->_maxLength * sizeof(uint8_t));
this->_position = 0;
this->collect();
return;
}
if(this->_scaped){
this->_scaped = false;
data ^= INVERT_BIT;
}
if (data == SCAPE) {
this->_scaped = true;
this->collect();
return;
}
this->_buffer[this->_position] = data;
this->_position++;
this->collect();
return;
}
bool TinyFrame::write(const uint8_t* data, uint16_t length) {
#if defined(TINYFRAME_DEBUG_TEENSY) || defined(TINYFRAME_DEBUG)
this->_DEBUG->print(" [ SEND DATA ] ");
#endif
uint16_t count = 0;
this->_port->write(FLAG);
this->_port->write(BROADCAST);
this->_port->write(CONTROL);
while(length--) this->_scape(data[count++]);
this->_port->write(0xCC);
this->_port->write(0xCC);
this->_port->write(FLAG);
return true;
}
void TinyFrame::_scape(uint8_t data) {
if (data == CONTROL || data == FLAG || data == SCAPE){
this->_port->write(SCAPE);
data ^= INVERT_BIT;
}
this->_port->write(SCAPE);
}
| [
"[email protected]"
] | |
4b5146ad19bd59da12e59fad313ed126f9af3202 | 0017c2513b58f1c4912443a15bfa35dbf4f697ca | /renderer_modules/libsExt/transfer/Base64Transfer.h | 6de22f1ccbfa3dbb6df8087582942f20f8921c27 | [
"BSD-2-Clause"
] | permissive | yang123vc/NCUI | d1977396421a98f9be83d614cfffe1497db8d1b0 | a3b315ebf97d9903766efdafa42c24d4212d5ad6 | refs/heads/master | 2020-04-28T09:30:22.627744 | 2018-11-20T15:23:36 | 2018-11-20T15:23:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,098 | h | // Created by amoylel on 12/01/2017.
// Copyright (c) 2017 amoylel All rights reserved.
#ifndef AMO_BASE64TRANSFER_H__
#define AMO_BASE64TRANSFER_H__
#include <transfer/RunnableTransfer.hpp>
#include <amo/singleton.hpp>
namespace amo {
/*!
* @class base64
*
* @chapter extend
*
* @extend Runnable
*
* @brief Base64 编解码.<br>
* 工作线程**Renderer线程**
*
*/
class Base64Transfer
: public RunnableTransfer
, public amo::singleton<Base64Transfer> {
public:
Base64Transfer();
virtual std::string getClass() const override;
virtual Transfer* getInterface(const std::string& name) override;
/*!
* @fn Any Base64Transfer::decode(IPCMessage::SmartType msg);
*
* @tag static sync
*
* @brief Base64 解码.
*
* @param #String 需要解码的字符串.
*
* @return #String 解码后的字符串.
* @example
*
```
include('base64');
console.assert(base64.decode('TkNVSQ==') == 'NCUI');
```
*/
Any decode(IPCMessage::SmartType msg);
/*!
* @fn Any Base64Transfer::encode(IPCMessage::SmartType msg);
*
* @tag static sync
*
* @brief Base64 编码.
*
* @param #String 需要编码的字符串.
*
* @return #String 编码后的字符串.
* @example
*
```
include('base64');
console.assert(base64.encode('NCUI') == 'TkNVSQ==');
```
*/
Any encode(IPCMessage::SmartType msg);
AMO_CEF_MESSAGE_TRANSFER_BEGIN(Base64Transfer, RunnableTransfer)
AMO_CEF_MESSAGE_TRANSFER_FUNC(decode, TransferFuncStatic | TransferExecSync)
AMO_CEF_MESSAGE_TRANSFER_FUNC(encode, TransferFuncStatic | TransferExecSync)
AMO_CEF_MESSAGE_TRANSFER_END()
};
}
#endif // AMO_BASE64TRANSFER_H__
| [
"[email protected]"
] | |
e6814916dedb17334e0b2ddb6aac4c4274229a1a | 0de3ff33c6098ef2d7461b99c17fe000f75edd9d | /GetLowEngine.Engine/SceneManager.h | 545bae4681f9344914c8fa6b4b75866fe64bb9fc | [
"MIT"
] | permissive | ticticboooom/GetLowEngine | 0e1ca507937a91eaf1eb4342cd2319729ea583de | 3303bc414a8b89c605161193d7284b6f91c4a5b6 | refs/heads/master | 2023-06-26T22:22:59.266248 | 2021-07-31T16:55:17 | 2021-07-31T16:55:17 | 215,819,241 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 915 | h | #pragma once
#include <map>
#include "PSOManager.h"
#include "RootSignatureManager.h"
#include "Scene.h"
class SceneManager : public GameMain
{
public:
SceneManager() {}
static std::shared_ptr<SceneManager> GetInstance();
void AddScene(std::string key, std::shared_ptr<Scene> scene);
void SetScene(std::string name);
void CreateRenderers() override;
void Init() override;
void Update() override;
void Render() override;
void OnWindowSizeChanged() override;
void OnSuspending() override;
void OnResuming() override;
void OnDeviceRemoved() override;
std::shared_ptr<RootSignatureManager> CreateRootSignatures(
const std::shared_ptr<DX::DeviceResources>& deviceResources) const;
private:
std::shared_ptr<PSOManager> psoManager;
static std::shared_ptr<SceneManager> instance;
std::shared_ptr<Scene> currentScene;
std::map<std::string, std::shared_ptr<Scene>> scenes;
D3D12_RECT m_scissorRect;
};
| [
"[email protected]"
] | |
c7d8629a6a3e2ad5bb9bf3660100eb8ecc26b188 | d009b283faa7ac112f87e930e75ad7aa0621d292 | /robot-sensor/src/robotSensor.cpp | fc333c169d9b76bcdc9b6cedfee31f0ca8379643 | [] | no_license | mato00/Interactive-robot | b22686af934f4a3d3fbca24f1ab9e1efeade8f32 | 0044a3989cbc715c6df81dd7df0965e245de9e26 | refs/heads/master | 2021-01-01T06:08:51.923559 | 2017-08-17T12:12:00 | 2017-08-17T12:12:00 | 97,369,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,341 | cpp | #include <Arduino.h>
#include <Servo.h>
#include <SR04.h>
#include <IRDistance.h>
#include <MPU9250.h>
#include <ros.h>
#include <ros/time.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/Range.h>
#include <sensor_msgs/Imu.h>
// 舵机
Servo Myservo1;
// 舵机角度
int angle1 = 0;
// 红外测距
IRDistance IRSensor(A0); // 前方红外测距
const int ir_sensor = A0; //分配激光传感器
const int xoy_val = 7;
float xoyDistance[xoy_val]; //存储xoy平面每30度的距离信息
// ros节点声明
ros::NodeHandle nh;
// 定义传感器msg
sensor_msgs::LaserScan scan;
sensor_msgs::Range ir_range_msg;
sensor_msgs::Range ultra_left_msg;
sensor_msgs::Range ultra_right_msg;
sensor_msgs::Range ultra_along_msg;
// 定义传感器publisher
ros::Publisher scan_range("scan", &scan);
ros::Publisher ir_range( "ir_data", &ir_range_msg);
unsigned long range_timer;
void irScanRange(){
float ir_range[xoy_val];
for(angle1 = 0; angle1 < 181; angle1 += 30)
{
Myservo1.write(angle1);
delay(500);
ir_range[angle1/30] = IRSensor.Distance()/100;
delay(500);
}
Myservo1.write(90);
delay(500);
// 填充红外测距数据
scan.header.stamp = nh.now();
for(unsigned int i = 0; i < xoy_val; i++){
scan.ranges[i] = ir_range[i];
}
scan_range.publish(&scan);
}
//红外正前方测距
void irPowRange(){
ir_range_msg.range = IRSensor.Distance()/100;
ir_range_msg.header.stamp = nh.now();
ir_range.publish(&ir_range_msg);
}
void setup(){
Serial.begin(115200);
nh.getHardware()->setBaud(115200);
nh.initNode();
nh.spinOnce();
// nh.advertise(scan_range);
// nh.spinOnce();
// delay(1000);
nh.advertise(ir_range);
nh.spinOnce();
delay(500);
scan.header.frame_id = "/ir_scan";
scan.angle_min = 0;
scan.angle_max = 3.14;
scan.angle_increment = 3.14 / xoy_val;
scan.time_increment = 7 / xoy_val;
scan.range_min = 0.2;
scan.range_max = 1.5;
ir_range_msg.radiation_type = sensor_msgs::Range::INFRARED;
ir_range_msg.header.frame_id = "/ir_range";
ir_range_msg.field_of_view = 0.01;
ir_range_msg.min_range = 0.2;
ir_range_msg.max_range = 1.5;
// 初始化舵机
Myservo1.attach(10);
Myservo1.write(90);
}
void loop(){
if((millis() - range_timer) > 50){
irPowRange();
range_timer = millis();
}
nh.spinOnce();
delay(500);
}
| [
"[email protected]"
] | |
9c4400e3741f6af54058223101e7938afadaa2f8 | 367f4e99ea6a99b98d6955650b6146b7c535b27b | /example/src/main.cpp | 9de88e83df33f2c47e56d3f4adef8d3dbd27548e | [] | no_license | hautetechnique/ofxGrowl | bac39ec7383b11f3f5c87bc8c89c010faa6c703c | 6709c05ee35fdea441ecda258394e7fb0036af05 | refs/heads/master | 2016-08-04T18:58:26.816367 | 2012-04-26T10:14:09 | 2012-04-26T10:14:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp | #include "ofMain.h"
#include "testApp.h"
#include "ofAppGlutWindow.h"
//========================================================================
int main( ){
ofAppGlutWindow window;
ofSetupOpenGL(&window, 250,200, OF_WINDOW); // <-------- setup the GL context
// this kicks off the running of my app
// can be OF_WINDOW or OF_FULLSCREEN
// pass in width and height too:
ofRunApp( new testApp());
}
| [
"[email protected]"
] | |
53d97ed792e97aa05ac2bde4aa2b092fcd2b0229 | a8ca5c8fc67ff451481687530e793f64cdd9ecd2 | /src/winsys/common.hh | dc82c844157b0c70ef015ae1c88bfbf6b7f02ff2 | [
"BSD-2-Clause"
] | permissive | deurzen/kranewm | c002cfb4bf039be34d62f5eb7960249563a75f8e | be918e057c3b6f2199d23ce39d4334379165ff41 | refs/heads/master | 2022-06-23T19:33:04.951564 | 2022-06-19T21:57:39 | 2022-06-19T21:57:39 | 173,928,993 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | hh | #ifndef __WINSYS_COMMON_H_GUARD__
#define __WINSYS_COMMON_H_GUARD__
#include <cstddef>
typedef std::size_t Ident;
typedef std::size_t Index;
namespace winsys
{
typedef unsigned Pid;
enum class Toggle
{
On,
Off,
Reverse
};
}
#endif//__WINSYS_COMMON_H_GUARD__
| [
"[email protected]"
] | |
3fafe93972dc06cc79f607b63d6d8b1df6759b0a | 0eaf516d53dba02495771e0add05999229182ae1 | /src/controller/include/asset_update_handler.h | 2185a2495a8c0c02c25e56fff61eb98a67e8a9c4 | [
"Apache-2.0"
] | permissive | AO-StreetArt/CrazyIvan | f1455bfdcb6d974d8495e8bab022c6f7c780b130 | 9398f3c88ae847c0789da91b09b409459f09f4e2 | refs/heads/v2 | 2021-01-12T08:35:50.820558 | 2019-04-17T05:26:12 | 2019-04-17T05:26:12 | 76,621,743 | 3 | 1 | NOASSERTION | 2019-01-12T21:18:12 | 2016-12-16T04:37:45 | C++ | UTF-8 | C++ | false | false | 4,039 | h | /*
Apache2 License Notice
Copyright 2017 Alex Barry
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.
*/
// This implements the Configuration Manager
// This takes in a Command Line Interpreter, and based on the options provided,
// decides how the application needs to be configured. It may configure either
// from a configuration file, or from a Consul agent
#include <iostream>
#include <boost/cstdint.hpp>
#include "scene_base_handler.h"
#include "user/include/account_manager_interface.h"
#include "model/include/scene_factory.h"
#include "model/include/scene_interface.h"
#include "api/include/scene_list_factory.h"
#include "api/include/scene_list_interface.h"
#include "app/include/ivan_utils.h"
#include "proc/processor/include/processor_interface.h"
#include "aossl/core/include/kv_store_interface.h"
#include "rapidjson/document.h"
#include "rapidjson/error/en.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Logger.h"
#ifndef SRC_CONTROLLER_INCLUDE_ASSET_UPDATE_HANDLER_H_
#define SRC_CONTROLLER_INCLUDE_ASSET_UPDATE_HANDLER_H_
class AssetUpdateRequestHandler: public Poco::Net::HTTPRequestHandler {
ProcessorInterface *proc = NULL;
AOSSL::KeyValueStoreInterface *config = NULL;
std::string scene_key;
std::string asset_key;
int msg_type = -1;
SceneListFactory scene_list_factory;
SceneFactory scene_factory;
public:
AssetUpdateRequestHandler(AOSSL::KeyValueStoreInterface *conf, ProcessorInterface *processor, std::string &scene, std::string& asset, int mtype) \
{config=conf;proc=processor;scene_key.assign(scene);asset_key.assign(asset);msg_type=mtype;}
void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) {
Poco::Logger::get("Controller").debug("Responding to Asset Update Request");
response.setChunkedTransferEncoding(true);
response.setContentType("application/json");
SceneListInterface *response_body = scene_list_factory.build_json_scene();
// Set up the input for the message processor
SceneListInterface *update_body = scene_list_factory.build_json_scene();
update_body->set_msg_type(SCENE_UPD);
if (msg_type == ASSET_ADD) {
update_body->set_op_type(APPEND);
} else if (msg_type == ASSET_DEL) {
update_body->set_op_type(REMOVE);
}
SceneInterface *update_scene = scene_factory.build_scene();
update_scene->set_key(scene_key);
update_scene->add_asset(asset_key);
update_body->add_scene(update_scene);
// Process the scene update
ProcessResult *result = proc->process_update_message(update_body);
// Set up the response
if (result->successful()) {
SceneInterface *key_scn = scene_factory.build_scene();
response_body->set_msg_type(SCENE_UPD);
response_body->set_err_code(NO_ERROR);
key_scn->set_key(result->get_return_string());
response_body->add_scene(key_scn);
} else {
response_body->set_msg_type(SCENE_UPD);
response_body->set_err_code(result->get_error_code());
response_body->set_err_msg(result->get_error_description());
}
// Send the response
std::ostream& ostr = response.send();
std::string response_body_string;
response_body->to_msg_string(response_body_string);
ostr << response_body_string;
ostr.flush();
delete result;
delete response_body;
delete update_body;
}
};
#endif // SRC_CONTROLLER_INCLUDE_ASSET_UPDATE_HANDLER_H_
| [
"[email protected]"
] | |
a7aa028b6c9ed741293e92914432e5cb252ccf6e | 5226ed61ade0863387dedc909430f09fb5b260a7 | /DataFormats/interface/PhotonCorr.h | d7bd380dfec1e3625bb8e115251fcb5b36f73d3d | [] | no_license | prafullasaha/EgammaIdCorrection | 0da2c46d2b296e67ea771d1cb0bee17a62d48182 | 98c40d1b614e8c84c1c260196af88fdeed2e54da | refs/heads/main | 2023-06-13T05:55:48.740183 | 2021-07-03T12:17:37 | 2021-07-03T12:17:37 | 313,722,574 | 0 | 0 | null | 2021-07-03T12:17:38 | 2020-11-17T19:32:55 | C++ | UTF-8 | C++ | false | false | 1,920 | h | #ifndef DataFormats_PhotonCorr_h
#define DataFormats_PhotonCorr_h
#include "DataFormats/EgammaCandidates/interface/Photon.h"
#include "DataFormats/PatCandidates/interface/Photon.h"
#include "DataFormats/PatCandidates/interface/PackedGenParticle.h"
#include "FWCore/Utilities/interface/EDMException.h"
#include "DataFormats/PatCandidates/interface/PackedCandidate.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h"
#include "DataFormats/Common/interface/RefToPtr.h"
#include <map>
#include <string>
#include <set>
class PhotonCorr : public pat::Photon
{
public:
PhotonCorr();
PhotonCorr(const pat::Photon & );
~PhotonCorr();
virtual PhotonCorr *clone() const;
void ZeroVariables();
void setSipip( float val ) {sipip_ = val;};
void setSieip( float val ) {sieip_ = val;};
void setS4( float val ) {S4_ = val;};
void setpfPhoIso04( float val ) {pfPhoIso04_ = val;};
void setpfPhoIso03( float val ) {pfPhoIso03_ = val;};
void setpfPhoIso03Corr( float val ) {pfPhoIso03Cor_ = val;};
float const sipip() const {return sipip_;};
float const sieip() const {return sieip_;};
float const s4() const {return S4_;};
float const pfPhoIso04() const {return pfPhoIso04_;};
float const pfPhoIso03() const {return pfPhoIso03_;};
float const pfPhoIso03Corr() const {return pfPhoIso03Cor_;};
static bool vetoPackedCand( const pat::Photon &photon, const edm::Ptr<pat::PackedCandidate> &pfcand );
float pfCaloIso( const pat::Photon &,
const std::vector<edm::Ptr<pat::PackedCandidate> > &,
float, float, float, float, float, float, float, reco::PFCandidate::ParticleType, const reco::Vertex* &vtx );
private:
float sipip_;
float sieip_;
float S4_;
float pfPhoIso04_;
float pfPhoIso03_;
float pfPhoIso03Cor_;
};
#endif
| [
"[email protected]"
] | |
6eebe13b786c28d79177947dc4bfb5ed944c45fc | cf8a3f9331d465fb71b6603698ebe16aa5396eea | /1000计算A+B(C++).cpp | 18f6b9b821b8cd0ddb0ed5c19420abe428ac7e93 | [] | no_license | Atom66/KaoyanOnlineJudge | 095df9b68c5d348e7b1a543391eb5f6f863c5795 | 5fbcd5a26faf16645c284f7fd1316ff8efa95c5c | refs/heads/master | 2021-09-11T12:43:45.487071 | 2018-04-07T06:51:15 | 2018-04-07T06:51:15 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 330 | cpp | /*
题目描述:
求整数a,b的和。
输入:
测试案例有多行,每行为a,b的值。
输出:
输出多行,对应a+b的结果。
样例输入:
1 2
4 5
6 9
样例输出:
3
9
15
*/
#include<iostream>
using namespace std;
int main(){
int a,b;
while(cin >> a >> b){
cout << a + b << endl;
}
return 0;
}
| [
"[email protected]"
] | |
20cf8256766c91f89171f731d275519c5869af76 | 30fe760333a4fe87863b8f7a6cea035e236b869b | /数据结构与算法/算法笔记/Ch8/8_2/coedup_8_2_D.cpp | baebe05db54d7edb50d6977c516fe9a14781a36c | [] | no_license | Floral/Study | 782e1028abed4eba6c7dcc773b01834752fe32f1 | e023fe907a9a1e5330d5283f81ed3e5af0d8f124 | refs/heads/master | 2021-12-15T00:03:44.412499 | 2021-11-23T13:37:43 | 2021-11-23T13:37:43 | 184,597,375 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,419 | cpp | #include<cstdio>
#include<string>
#include<queue>
#include<map>
using namespace std;
struct Node
{
int board[2][4];
int step = 0;
string path;
};
char dir[3] = {'A', 'B', 'C'};
Node nextNode(const Node &pre, char op)
{
Node ret = pre;
if (op=='A')
{
for (int i = 0; i < 4; i++)
{
ret.board[0][i] = pre.board[1][i];
ret.board[1][i] = pre.board[0][i];
}
}else if (op=='B')
{
for (int i = 0; i < 4; i++)
{
ret.board[0][i] = pre.board[0][(i+3)%4];
ret.board[1][i] = pre.board[1][(i+3)%4];
}
}else if (op=='C')
{
ret.board[0][1] = pre.board[1][1];
ret.board[1][1] = pre.board[1][2];
ret.board[1][2] = pre.board[0][2];
ret.board[0][2] = pre.board[0][1];
}
ret.path = pre.path+op;
ret.step = pre.step+1;
return ret;
}
int board2int(const int board[2][4])
{
int ans=0;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 4; j++)
ans = ans*10+board[i][j];
return ans;
}
int bfs(Node pre,Node &aim)
{
int ans = 0;
queue<Node> q;
map<int, bool> hashMp;
q.push(pre);
hashMp[board2int(pre.board)] = true;
int aimFlag = board2int(aim.board);
while (!q.empty())
{
pre = q.front();
q.pop();
if (board2int(pre.board)==aimFlag)
{
aim.path = pre.path;
aim.step = pre.step;
return pre.step;
}
for (int i = 0; i < 3; i++)
{
Node next = nextNode(pre, dir[i]);
int key = board2int(next.board);
if (hashMp[key]==false)
{
hashMp[key] = true;
q.push(next);
}
}
}
return ans;
}
int main()
{
Node init, aim;
for (int i = 0; i < 4; i++)
{
scanf("%d", &aim.board[0][i]);
init.board[0][i] = i+1;
}
for (int i = 3; i >= 0; i--)
{
scanf("%d", &aim.board[1][i]);
init.board[1][i] = 8-i;
}
int ans = bfs(init, aim);
printf("%d\n", ans);
int left = aim.step;
int startPos = 0;
while (left >= 60)
{
printf("%s\n", aim.path.substr(startPos, 60).c_str());
startPos+=60;
left-=60;
}
if (left>0)
printf("%s\n", aim.path.substr(startPos, left).c_str());
return 0;
} | [
"[email protected]"
] | |
348d914e4eeafe3aafda37e3e4fe318ff4b7bd20 | 12617ea743c04de9697695286101ee704b9e35de | /Labs/src/Model.h | 5b5e64713ae9e99b8ea83be2ae39db8a2b6b2cf0 | [] | no_license | Devineadz/christmas-wheels-on-the-bus | 7b5b9a273de1ef1bac53eb86c1eaa288fb25d9f1 | e546213661d8b0fcc79c1d9dadcc970d2cafee77 | refs/heads/master | 2023-03-08T04:37:02.810757 | 2021-02-27T19:37:54 | 2021-02-27T19:37:54 | 262,841,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,267 | h | //
// COMP 371 Assignment Framework
//
// Created by Nicolas Bergeron on 8/7/14.
// Updated by Gary Chang on 14/1/15
//
// Copyright (c) 2014-2019 Concordia University. All rights reserved.
//
#pragma once
#include <vector>
#include <glm/glm.hpp>
#include <GL/glew.h>
#include <string>
class Model
{
public:
Model(std::string name, int vao, int vertexCount, int shaderProgram);
~Model();
void Update(float dt);
void Accelerate(glm::vec3 force, float dt);
//void Angulate(glm::vec3 torque, float dt);
void Draw(int shaderi);
//void Load(ci_istringstream& iss);
glm::mat4 GetWorldMatrix() const;
void SetPosition(glm::vec3 position);
void SetScaling(glm::vec3 scaling);
void SetRotation(glm::vec3 axis, float angleDegrees);
void SetVelocity(glm::vec3 velocity);
//void SetAngularVelocity(glm::vec3 axis, float angleDegrees);
glm::vec3 GetPosition() const { return position; }
glm::vec3 GetScaling() const { return scaling; }
glm::vec3 GetRotationAxis() const { return rotationAxis; }
float GetRotationAngle() const { return rotationAngleInDegrees; }
//ci_string GetName() { return mName; }
//glm::vec3 GetVelocity() const { return mVelocity; }
//float GetMass() const { return mMass; }
//virtual bool ContainsPoint(glm::vec3 position) = 0;//Whether or not the given point is withing the model. For collisions.
//virtual bool IntersectsPlane(glm::vec3 planePoint, glm::vec3 planeNormal) = 0;
//virtual float IntersectsRay(glm::vec3 rayOrigin, glm::vec3 rayDirection) = 0; //Returns a strictly positive value if an intersection occurs
//void BounceOffGround();
//virtual bool isSphere() = 0; //This is not at all object-oriented, but somewhat necessary due to need for a simple double-dispatch mechanism
static GLuint createVAO(int& vertexCount, std::vector<glm::vec3> positions, std::vector<glm::vec3> normals, std::vector<glm::vec2> uvs);
//virtual bool ParseLine(const std::vector<ci_string>& token) = 0;
private:
int vao, shader;
int vertexCount;
std::string name; // The model name is mainly for debugging
glm::vec3 position;
glm::vec3 scaling;
glm::vec3 rotationAxis;
float rotationAngleInDegrees;
glm::vec3 velocity;
glm::vec3 angularAxis;
float angularVelocityInDegrees;
};
| [
"[email protected]"
] | |
5dd9159e13c48880935413d5e34b99ce99adb668 | 2be0edf2aea6f2ee06bf146d199263098770c98c | /ship_0/main3dwindow.h | e47e718e9c01ce5ed67ba55cbc6c336ec1d15cf9 | [] | no_license | Romario0983/sayhi | ff6ae243c550cc153d37432a432de51257d36199 | 1bbda5454fcef186cd7ecae69706db624a791231 | refs/heads/master | 2020-03-24T00:16:47.387248 | 2018-08-13T12:42:21 | 2018-08-13T12:42:21 | 142,283,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 432 | h | #ifndef MAIN3DWINDOW_H
#define MAIN3DWINDOW_H
#include <Qt3DExtras/Qt3DWindow>
#include <QDebug>
class Main3DWindow : public Qt3DExtras::Qt3DWindow
{
Q_OBJECT
public:
Main3DWindow();
public slots:
void logCameraVector(const QVector3D &vector);
void logCameraMatrix(const QMatrix4x4 &projectionMatrix);
void positionChanged(const QVector3D &position);
};
#endif // MAIN3DWINDOW_H
| [
"[email protected]"
] | |
a45d547e0ee0eb6ed82849b038093b8ff2946243 | 876791108da023418a63c2aa12c77d2b745d1078 | /old/old/old/old/old/old/Comment.cpp | 9ec9a4ec219e6cd1b6ce747089fef07598dac861 | [] | no_license | bgoktugozdemir/1.-Sinif-2.-Donem-2.-Proje | b2d45cf46ea078b8c40a6fa5c65afdcd095b0ab9 | 467329311fc60a412a26b57cda08d97130973eba | refs/heads/master | 2021-01-19T19:45:51.177404 | 2017-04-27T00:25:39 | 2017-04-27T00:25:39 | 88,442,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,001 | cpp | #include "Comment.h"
Comment::Comment(int CommentId, time_t CommentTime, string comment, User* UserId)
{
this->CommentId = CommentId;
this->CommentTime = CommentTime;
this->comment = comment;
this->UserId = UserId;
}
Comment::Comment()
{
this->CommentId = 0;
this->CommentTime = NULL;
this->comment = "";
}
Comment::~Comment()
{
}
void Comment::addComment()
{
DosyayaYaz();
}
void Comment::deleteComment()
{
}
void Comment::editComment()
{
}
void Comment::showComment()
{
}
void Comment::DosyayaYaz()
{
ofstream dosyaYaz("Comments.txt", ios::app);
dosyaYaz << CommentId << " " << UserId->UserId << " " << CommentTime << " " << comment << " " << endl;
dosyaYaz.close();
}
void Comment::DosyayiOku()
{
ifstream dosyaOku("Comments.txt");
if (dosyaOku.is_open())
{
while (!dosyaOku.eof())
{
dosyaOku >> CommentId >> UserId->UserId >> CommentTime >> comment;
cout << CommentId << " " << UserId->UserId << " " << CommentTime << " " << comment << " " << endl;
}
}
} | [
"[email protected]"
] | |
79193615c35716a003630eae4608740b4de5e55f | 2f0ca47cccf57a608a81d734de75a5de6e0e570f | /Demo示例/1- MFC综合示例/DlgWallCfgUniform.cpp | a5625f696e3c58402f99a26d2797f1a1face6b9c | [] | no_license | chsword/CH-HCNetSDK | 7e6a8df345cd0ce3d885693a39a19501e242e514 | 5e84ea655c477adf4940cf32b9639f3d11ab324c | refs/heads/master | 2021-07-16T23:30:17.564391 | 2017-10-24T03:56:50 | 2017-10-24T03:56:50 | 108,074,305 | 5 | 5 | null | null | null | null | GB18030 | C++ | false | false | 30,094 | cpp | // DlgWallCfgUniform.cpp : implementation file
//
#include "stdafx.h"
#include "clientdemo.h"
#include "DlgWallCfgUniform.h"
#include "DlgWallWinVideoWall.h"
#include "DlgWallVirLED.h"
#include "DlgWallControl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDlgWallCfg_Uniform dialog
CDlgWallCfg_Uniform::CDlgWallCfg_Uniform(CWnd* pParent /*=NULL*/)
: CDialog(CDlgWallCfg_Uniform::IDD, pParent)
{
//{{AFX_DATA_INIT(CDlgWallCfg_Uniform)
m_bEnable = FALSE;
m_bDzd = FALSE;
m_bFgb = FALSE;
m_bQgyz = FALSE;
m_byBrightness = 0;
m_byContrast = 0;
m_byGray = 0;
m_byHue = 0;
m_bySaturation = 0;
m_bySharpness = 0;
m_byWallNo = 1;
m_dwOutputNum = 0;
m_dwDisplayNoC = 0;
m_BShowC = FALSE;
m_BAllDisplayNo = FALSE;
//}}AFX_DATA_INIT
}
void CDlgWallCfg_Uniform::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgWallCfg_Uniform)
DDX_Control(pDX, IDC_COMB_VWSC_CHANTYPE, m_CmChanTypeC);
DDX_Control(pDX, IDC_COMB_VIDEOWALL_VIDEOFORMAT, m_combVideoFormat);
DDX_Control(pDX, IDC_COMB_VIDEOWALL_BACKGROUND, m_combBackGround);
DDX_Control(pDX, IDC_COMB_VIDEOWALL_DISPLAYMODE, m_combDisplayMode);
DDX_Control(pDX, IDC_COMBO_RESOLUTION, m_comboResolution);
DDX_Control(pDX, IDC_COMBO_OUTPUT, m_comboOutput);
DDX_Control(pDX, IDC_COMBO_LEVEL, m_comboLevel);
DDX_Control(pDX, IDC_LIST_SCREEN, m_listScreen);
DDX_Control(pDX, IDC_COMBO_Y, m_comboY);
DDX_Control(pDX, IDC_COMBO_X, m_comboX);
DDX_Check(pDX, IDC_CHK_ENABLE, m_bEnable);
DDX_Check(pDX, IDC_CHK_DZD, m_bDzd);
DDX_Check(pDX, IDC_CHK_FGB, m_bFgb);
DDX_Check(pDX, IDC_CHK_QGYZ, m_bQgyz);
DDX_Text(pDX, IDC_EDIT_BRIGHTNESS, m_byBrightness);
DDX_Text(pDX, IDC_EDIT_CONTRAST, m_byContrast);
DDX_Text(pDX, IDC_EDIT_GRAY, m_byGray);
DDX_Text(pDX, IDC_EDIT_HUE, m_byHue);
DDX_Text(pDX, IDC_EDIT_SATURATION, m_bySaturation);
DDX_Text(pDX, IDC_EDIT_SHARPNESS, m_bySharpness);
DDX_Text(pDX, IDC_EDT_VIDEOWALL_WALLNO, m_byWallNo);
DDX_Text(pDX, IDC_EDT_VIDEOWALL_OUTPUTNUM, m_dwOutputNum);
DDX_Text(pDX, IDC_EDT_VWSC_DISPLAYNO, m_dwDisplayNoC);
DDX_Check(pDX, IDC_CHK_VWSC_ENABLE, m_BShowC);
DDX_Check(pDX, IDC_CHK_VWS_ALLDISPLAYNO, m_BAllDisplayNo);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgWallCfg_Uniform, CDialog)
//{{AFX_MSG_MAP(CDlgWallCfg_Uniform)
ON_BN_CLICKED(IDC_BTN_SAVE, OnBtnSave)
ON_BN_CLICKED(IDC_BTN_SET, OnBtnSet)
ON_BN_CLICKED(IDC_BTN_EXIT, OnBtnExit)
ON_NOTIFY(NM_CLICK, IDC_LIST_SCREEN, OnClickListScreen)
ON_BN_CLICKED(IDC_BTN_GET_ALL, OnBtnGetAll)
ON_BN_CLICKED(IDC_BTN_SAVE_CFG, OnBtnSaveCfg)
ON_BN_CLICKED(IDC_BTN_SET_CFG, OnBtnSetCfg)
ON_BN_CLICKED(IDC_BTN_GET_CFG, OnBtnGetCfg)
ON_CBN_SELCHANGE(IDC_COMBO_OUTPUT, OnSelchangeComboOutput)
ON_BN_CLICKED(IDC_BTN_UPDATE_OUTPUT, OnBtnUpdateOutput)
ON_BN_CLICKED(IDC_BTN_VIDEOWALL_GET, OnBtnGet)
ON_BN_CLICKED(IDC_BUT_VIDEOWALL_CONTROL, OnButVideowallControl)
ON_BN_CLICKED(IDC_BUT_VWSC_SEND, OnButVwscSend)
ON_BN_CLICKED(IDC_CHK_VWS_ALLDISPLAYNO, OnChkVwsAlldisplayno)
ON_WM_CANCELMODE()
ON_WM_CAPTURECHANGED()
ON_BN_CLICKED(IDC_BUT_DISPLAYPARAM_ALLSAME, OnButDispParamAllSame)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgWallCfg_Uniform message handlers
BOOL CDlgWallCfg_Uniform::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
m_dwCount = 0;
m_dwDispNum = 0;
m_iCurSel = -1;
m_iDeviceIndex = g_pMainDlg->GetCurDeviceIndex();
memset(m_ModifyChan, 0, sizeof(m_ModifyChan));
memset(m_lDispChan, 0, sizeof(m_lDispChan));
memset(m_lDispChanSet, 0, sizeof(m_lDispChanSet));
memset(m_dwStatus, 0, sizeof(m_dwStatus));
memset(m_struWallParam, 0, sizeof(m_struWallParam));
memset(&m_struAblity, 0, sizeof(m_struAblity));
memset(&m_struWallParamSet, 0, sizeof(m_struWallParamSet));
m_lPapamCount = 0;
m_lRecordCount = 0;
memset(&m_struOutput, 0, sizeof(m_struOutput));
memset(&m_struOutputSet, 0, sizeof(m_struOutputSet));
memset(&m_lDispOutputSet, 0, sizeof(m_lDispOutputSet));
memset(m_dwRecordPapam, 0, sizeof(m_dwRecordPapam));
m_dwOutputSet = 0;
CString tmp;
int i = 0;
int ChanNo = -1;
char szLan[128] = {0};
m_listScreen.SetExtendedStyle(LVS_EX_GRIDLINES |LVS_EX_FULLROWSELECT);
g_StringLanType(szLan, "显示输出号", "DispChan No.");
m_listScreen.InsertColumn(0, szLan, LVCFMT_LEFT,80, -1);
g_StringLanType(szLan, "墙号", "VideoWall No.");
m_listScreen.InsertColumn(1, szLan,LVCFMT_LEFT,80, -1);
m_listScreen.InsertColumn(2, "X",LVCFMT_LEFT,80,-1);
m_listScreen.InsertColumn(3, "Y",LVCFMT_LEFT,80,-1);
g_StringLanType(szLan, "使能", "Enable");
m_listScreen.InsertColumn(4, szLan,LVCFMT_LEFT,80,-1);
g_StringLanType(szLan, "连接模式", "LinkMode");
m_listScreen.InsertColumn(5, szLan,LVCFMT_LEFT,120,-1);
// OnBtnGetAll();
i = 0;
m_comboResolution.AddString("SVGA_60HZ");
m_comboResolution.SetItemData(i++, SVGA_60HZ);
m_comboResolution.AddString("SVGA_75HZ");
m_comboResolution.SetItemData(i++, SVGA_75HZ);
m_comboResolution.AddString("XGA_60HZ");
DWORD test = XGA_60HZ;
m_comboResolution.SetItemData(i++, XGA_60HZ);
m_comboResolution.AddString("XGA_75HZ");
m_comboResolution.SetItemData(i++, XGA_75HZ);
m_comboResolution.AddString("SXGA_60HZ");
m_comboResolution.SetItemData(i++, SXGA_60HZ);
m_comboResolution.AddString("SXGA2_60HZ");
m_comboResolution.SetItemData(i++, SXGA2_60HZ);
m_comboResolution.AddString("_720P_60HZ");
m_comboResolution.SetItemData(i++, _720P_60HZ);
m_comboResolution.AddString("_720P_50HZ");
m_comboResolution.SetItemData(i++, _720P_50HZ);
m_comboResolution.AddString("_1080I_60HZ");
m_comboResolution.SetItemData(i++, _1080I_60HZ);
m_comboResolution.AddString("_1080I_50HZ");
m_comboResolution.SetItemData(i++, _1080I_50HZ);
m_comboResolution.AddString("_1080P_60HZ");
m_comboResolution.SetItemData(i++, _1080P_60HZ);
m_comboResolution.AddString("_1080P_50HZ");
m_comboResolution.SetItemData(i++, _1080P_50HZ);
m_comboResolution.AddString("_1080P_30HZ");
m_comboResolution.SetItemData(i++, _1080P_30HZ);
m_comboResolution.AddString("_1080P_25HZ");
m_comboResolution.SetItemData(i++, _1080P_25HZ);
m_comboResolution.AddString("_1080P_24HZ");
m_comboResolution.SetItemData(i++, _1080P_24HZ);
m_comboResolution.AddString("UXGA_60HZ");
m_comboResolution.SetItemData(i++, UXGA_60HZ);
m_comboResolution.AddString("UXGA_30HZ");
m_comboResolution.SetItemData(i++, UXGA_30HZ);
m_comboResolution.AddString("WSXGA_60HZ");
m_comboResolution.SetItemData(i++, WSXGA_60HZ);
m_comboResolution.AddString("WUXGA_60HZ");
m_comboResolution.SetItemData(i++, WUXGA_60HZ);
m_comboResolution.AddString("WUXGA_30HZ");
m_comboResolution.SetItemData(i++, WUXGA_30HZ);
m_combDisplayMode.SetCurSel(0);
InitOutputLinkMode();
OnBtnGetAll();
OnBtnUpdateOutput();
m_CmChanTypeC.SetCurSel(0);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CDlgWallCfg_Uniform::OnBtnSave()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
char szLan[128] = {0};
if (m_comboX.GetCurSel() == CB_ERR || m_comboY.GetCurSel() == CB_ERR)
{
g_StringLanType(szLan, "请选择坐标", "Please select Coordinate");
AfxMessageBox(szLan);
return;
}
NET_DVR_VIDEOWALLDISPLAYPOSITION struDisplayPos ={0};
UpdateDisplayPos(struDisplayPos);
UpdateOutputNum(struDisplayPos);
DrawList();
UpdateData(FALSE);
}
void CDlgWallCfg_Uniform::OnBtnSet()
{
// TODO: Add your control notification handler code here
memset(m_dwStatus, 0, sizeof(m_dwStatus));
LPNET_DVR_VIDEOWALLDISPLAYPOSITION lpDisplayPos = GetModifyDisplayPos();
LONG * lDisplayChan = GetModifyChan();
char csError[1024]={0};
char csNum[128] = {0};
if (!NET_DVR_SetDeviceConfig(m_lUserID, NET_DVR_SET_VIDEOWALLDISPLAYPOSITION, m_dwCount, lDisplayChan, 4 * m_dwCount, m_dwStatus, lpDisplayPos, m_dwCount * sizeof(NET_DVR_VIDEOWALLDISPLAYPOSITION)))
{
sprintf(csError, "设置修改失败, Error code: %d", NET_DVR_GetLastError());
AfxMessageBox(csError);
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_SET_VIDEOWALLDISPLAYPOSITION");
return;
}
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_SET_VIDEOWALLDISPLAYPOSITION");
int i = 0;
BOOL bOneFail = FALSE;
for (i = 0; i <m_dwCount; i++)
{
if (m_dwStatus[i] > 0)
{
sprintf(csNum, "%d ", lpDisplayPos[i].dwDisplayNo);
strcat(csError, csNum);
bOneFail = TRUE;
}
}
if (bOneFail)
{
// sprintf(csError, "the outputnum failed to set: %s ", csError);
AfxMessageBox(csError);
return ;
}
OnBtnGetAll();
}
//输出号位置获取
void CDlgWallCfg_Uniform::OnBtnGet()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
POSITION iPos = m_listScreen.GetFirstSelectedItemPosition();
if (iPos == NULL)
{
return;
}
NET_DVR_VIDEOWALLDISPLAYPOSITION struDisplayPos={0};
struDisplayPos.dwSize = sizeof(struDisplayPos);
DWORD dwDispChan = m_dwOutputNum;
CString csTemp;
char szLan[128]={0};
if (!NET_DVR_GetDeviceConfig(m_lUserID, NET_DVR_GET_VIDEOWALLDISPLAYPOSITION, 1, &dwDispChan, sizeof(dwDispChan), NULL, &struDisplayPos, sizeof(NET_DVR_VIDEOWALLDISPLAYPOSITION)))
{
sprintf(szLan, "刷新该项失败, Error code %d",NET_DVR_GetLastError());
AfxMessageBox(szLan);
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_VIDEOWALLDISPLAYPOSITION");
//return;
}
else
{
NewOutputNum(struDisplayPos);
DrawList();
}
}
void CDlgWallCfg_Uniform::OnBtnExit()
{
// TODO: Add your control notification handler code here
CDialog::OnCancel();
}
void CDlgWallCfg_Uniform::DrawList()
{
m_listScreen.DeleteAllItems();
int i = 0;
int j = 0;
char szLan[128] = {0};
for(i = 0; i < m_dwDispNum; i++)
{
sprintf(szLan, "%d_%d_%d", m_struWallParam[i].dwDisplayNo>>24, (m_struWallParam[i].dwDisplayNo>>16) &0xff, (m_struWallParam[i].dwDisplayNo&0xffff));
m_listScreen.InsertItem(i, szLan);
sprintf(szLan, "%d", (m_struWallParam[i].dwVideoWallNo>>24));
m_listScreen.SetItemText(i, 1, szLan);
sprintf(szLan, "%d", m_struWallParam[i].struRectCfg.dwXCoordinate);
m_listScreen.SetItemText(i, 2, szLan);
sprintf(szLan, "%d", m_struWallParam[i].struRectCfg.dwYCoordinate);
m_listScreen.SetItemText(i, 3, szLan);
if (m_struWallParam[i].byEnable == 0)
{
sprintf(szLan, "Disable");
}
else
{
sprintf(szLan, "Enable");
}
m_listScreen.SetItemText(i, 4, szLan);
m_listScreen.SetItemData(i, m_struWallParam[i].dwDisplayNo);
//从现在位置寻找循环,可能快点
int j=i;
BYTE byLinkMode=0xff;
do
{
if (m_struDisplayCfg.struDisplayParam[j].dwDisplayNo == m_struWallParam[i].dwDisplayNo)
{
byLinkMode = m_struDisplayCfg.struDisplayParam[j].byDispChanType;
}
j++;
} while ((j%MAX_DISPLAY_NUM) != i);
switch (byLinkMode)
{
case 1:
sprintf(szLan, "BNC");
break;
case 2:
sprintf(szLan, "VGA");
break;
case 3:
sprintf(szLan, "HDMI");
break;
case 4:
sprintf(szLan, "DVI");
break;
case 0xff:
sprintf(szLan, "无效");
break;
default:
sprintf(szLan, "");
}
m_listScreen.SetItemText(i, 5, szLan);
}
}
void CDlgWallCfg_Uniform::OnClickListScreen(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
POSITION iPos = m_listScreen.GetFirstSelectedItemPosition();
if (iPos == NULL)
{
return;
}
m_iCurSel = m_listScreen.GetNextSelectedItem(iPos);
m_dwOutputNum = m_struWallParam[m_iCurSel].dwDisplayNo;
m_bEnable = m_struWallParam[m_iCurSel].byEnable;
m_byWallNo = (BYTE)(m_struWallParam[m_iCurSel].dwVideoWallNo>>24);
m_comboX.SetCurSel(m_struWallParam[m_iCurSel].struRectCfg.dwXCoordinate/WIDTH);
m_comboY.SetCurSel(m_struWallParam[m_iCurSel].struRectCfg.dwYCoordinate/HEIGHT);
UpdateData(FALSE);
*pResult = 0;
}
void CDlgWallCfg_Uniform::OnBtnGetAll()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
int i = 0;
BOOL bOneFail = FALSE;
char cs[1024] = {0};
CString csTemp;
char *pTemp = new char[4 + MAX_COUNT * sizeof(NET_DVR_VIDEOWALLDISPLAYPOSITION)];
memset(pTemp, 0, 4 + MAX_COUNT * sizeof(NET_DVR_VIDEOWALLDISPLAYPOSITION));
// if (!NET_DVR_GetDeviceConfig(m_lUserID, NET_DVR_GET_VIDEOWALLDISPLAYPOSITION, 0xffffffff, NULL, 0, NULL, pTemp, 4 + MAX_COUNT * sizeof(NET_DVR_VIDEOWALLDISPLAYPOSITION)))
// {
// sprintf(cs, "获取所有位置失败, Error code: %d", NET_DVR_GetLastError());
// AfxMessageBox(cs);
// g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_VIDEOWALLDISPLAYPOSITION");
// //return;
// }
DWORD dwWallNo = m_byWallNo;
dwWallNo <<= 24;
if (!NET_DVR_GetDeviceConfig(m_lUserID, NET_DVR_GET_VIDEOWALLDISPLAYPOSITION, 0xffffffff, &dwWallNo, sizeof(DWORD), NULL, pTemp, 4 + MAX_COUNT * sizeof(NET_DVR_VIDEOWALLDISPLAYPOSITION)))
{
sprintf(cs, "获取墙所有输出位置失败, Error code: %d", NET_DVR_GetLastError());
AfxMessageBox(cs);
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_VIDEOWALLDISPLAYPOSITION");
//return;
}
else
{
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_GET_VIDEOWALLDISPLAYPOSITION");
m_dwDispNum = *((DWORD*)pTemp);
memcpy(m_struWallParam, pTemp + 4, m_dwDispNum * sizeof(NET_DVR_VIDEOWALLDISPLAYPOSITION));
memset(m_dwStatus, 0, sizeof(m_dwStatus));
ClearModify();
m_comboOutput.ResetContent();
for (i = 0; i<m_dwDispNum; i++)
{
m_lDispChan[i] = m_struWallParam[i].dwDisplayNo;
sprintf(cs, "%d", m_lDispChan[i]);
m_comboOutput.AddString(cs);
m_comboOutput.SetItemData(i, m_lDispChan[i]);
}
m_lPapamCount = m_dwDispNum;
}
delete []pTemp;
//m_listScreen.DeleteAllItems();
DrawList();
m_listScreen.UpdateData(FALSE);
m_listScreen.SetItemState(m_iCurSel, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
}
void CDlgWallCfg_Uniform::OnBtnSaveCfg()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
char szLan[128];
int iSel = m_comboOutput.GetCurSel();
int j = 0;
if (iSel == -1)
{
g_StringLanType(szLan, "请选择显示输出号", "please select output No.");
AfxMessageBox(szLan);
return;
}
if (m_comboResolution.GetCurSel() == CB_ERR)
{
g_StringLanType(szLan, "请选择分辨率", "please select resolution");
AfxMessageBox(szLan);
return;
}
NET_DVR_WALLOUTPUTPARAM struOuputPapam={0};
UpdateOutputPapam(struOuputPapam);
//增加修改记录
for(j=0; j<m_lRecordCount; j++)
{
if (m_dwRecordPapam[j] == iSel)
{
break;
}
}
if (j>=m_lRecordCount)
{
m_dwRecordPapam[j] = iSel;
m_lRecordCount ++;
}
m_struOutput[iSel] = struOuputPapam;
}
void CDlgWallCfg_Uniform::OnBtnSetCfg()
{
// TODO: Add your control notification handler code here
char cs[2048] = {0};
BOOL bOneFail = FALSE;
CString csTemp;
int i = 0;
int j = 0;
LPNET_DVR_WALLOUTPUTPARAM lpOutputPapma = GetModifyPapam();
LPDWORD lpModifyOutputNO = (LPDWORD)GetModifyPapamChan();
if (!NET_DVR_SetDeviceConfig(m_lUserID, NET_DVR_WALLOUTPUT_SET, m_lRecordCount, lpModifyOutputNO, 4 * m_lRecordCount, m_dwStatus, lpOutputPapma, m_lRecordCount * sizeof(NET_DVR_WALLOUTPUTPARAM)))
{
sprintf(cs, "设置修改失败, Error code: %d", NET_DVR_GetLastError());
AfxMessageBox(cs);
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_WALLOUTPUT_SET");
return;
}
sprintf(cs, "Not succeed:\n");
for (i = 0; i < m_lRecordCount; i++)
{
if (m_dwStatus[i] > 0)
{
csTemp = m_listScreen.GetItemText(i, 0);
sprintf(cs, "%sDispchan: %s\n", cs, csTemp);
bOneFail = TRUE;
}
}
if (bOneFail)
{
AfxMessageBox(cs);
}
OnBtnUpdateOutput();
}
//单个输出号的参数获取
void CDlgWallCfg_Uniform::OnBtnGetCfg()
{
// TODO: Add your control notification handler code here
char szLan[128] = {0};
if (m_comboOutput.GetCurSel() == CB_ERR)
{
g_StringLanType(szLan, "请选择显示输出号", "please select output channel No.");
AfxMessageBox(szLan);
return;
}
DWORD dwStatus = 0;
int i = 0;
DWORD dwOutputNum = m_comboOutput.GetItemData(m_comboOutput.GetCurSel());
NET_DVR_WALLOUTPUTPARAM struTemp = {0};
CString csError;
if (!NET_DVR_GetDeviceConfig(m_lUserID, NET_DVR_WALLOUTPUT_GET, 1, &dwOutputNum, 4, &dwStatus, &struTemp, sizeof(struTemp)))
{
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_WALLOUTPUT_GET");
csError.Format("获取输出参数失败, Error Code %d" , NET_DVR_GetLastError());
MessageBox(csError);
}
else
{
for(int i = 0; i<m_comboResolution.GetCount(); i++)
{
if (struTemp.dwResolution == m_comboResolution.GetItemData(i))
{
m_comboResolution.SetCurSel(i);
break;
}
}
m_byBrightness = struTemp.struRes.byBrightnessLevel;
m_byContrast = struTemp.struRes.byContrastLevel;
m_bySharpness = struTemp.struRes.bySharpnessLevel;
m_bySaturation = struTemp.struRes.bySaturationLevel;
m_byHue = struTemp.struRes.byHueLevel;
m_bFgb = struTemp.struRes.byEnableFunc & 0x01;
m_bDzd = struTemp.struRes.byEnableFunc & 0x02;
m_bQgyz = struTemp.struRes.byEnableFunc & 0x04;
m_comboLevel.SetCurSel(struTemp.struRes.byLightInhibitLevel);
m_byGray = struTemp.struRes.byGrayLevel;
m_combVideoFormat.SetCurSel(struTemp.byVideoFormat);
if (struTemp.byDisplayMode == 0xff)
{
m_combDisplayMode.SetCurSel(4);
}
else
m_combDisplayMode.SetCurSel(struTemp.byDisplayMode-1);
m_combBackGround.SetCurSel(struTemp.byBackgroundColor);
memcpy(&m_struOutput[m_comboOutput.GetCurSel()], &struTemp, sizeof(NET_DVR_WALLOUTPUTPARAM));
RemovePapamRecord(m_lDispChan[m_comboOutput.GetCurSel()]);
UpdateData(FALSE);
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_WALLOUTPUT_GET");
}
}
void CDlgWallCfg_Uniform::OnSelchangeComboOutput()
{
// TODO: Add your control notification handler code here
int iSel = m_comboOutput.GetCurSel();
if (iSel == CB_ERR)
{
return;
}
int i = 0;
for(i = 0; i<m_comboResolution.GetCount(); i++)
{
if (m_struOutput[iSel].dwResolution == m_comboResolution.GetItemData(i))
{
m_comboResolution.SetCurSel(i);
break;
}
}
m_byBrightness = m_struOutput[iSel].struRes.byBrightnessLevel;
m_byContrast = m_struOutput[iSel].struRes.byContrastLevel;
m_bySharpness = m_struOutput[iSel].struRes.bySharpnessLevel;
m_bySaturation = m_struOutput[iSel].struRes.bySaturationLevel;
m_byHue = m_struOutput[iSel].struRes.byHueLevel;
m_bFgb = m_struOutput[iSel].struRes.byEnableFunc & 0x01;
m_bDzd = m_struOutput[iSel].struRes.byEnableFunc & 0x02;
m_bQgyz = m_struOutput[iSel].struRes.byEnableFunc & 0x04;
m_comboLevel.SetCurSel(m_struOutput[iSel].struRes.byLightInhibitLevel);
m_byGray = m_struOutput[iSel].struRes.byGrayLevel;
m_combVideoFormat.SetCurSel(m_struOutput[iSel].byVideoFormat);
if (m_struOutput[iSel].byDisplayMode == 0xff )
{
m_combDisplayMode.SetCurSel(4); //4 对应无效
}
else
{
m_combDisplayMode.SetCurSel(m_struOutput[iSel].byDisplayMode + 1);
}
m_combBackGround.SetCurSel(m_struOutput[iSel].byBackgroundColor);
m_byWallNo = m_byInitWallNo;
UpdateData(FALSE);
}
//获取所有
void CDlgWallCfg_Uniform::OnBtnUpdateOutput()
{
// TODO: Add your control notification handler code here
int i = 0;
BOOL bOneFail = FALSE;
char cs[128] = {0};
CString csTemp;
if (!NET_DVR_GetDeviceConfig(m_lUserID, NET_DVR_WALLOUTPUT_GET, m_dwDispNum, m_lDispChan, m_dwDispNum * 4, m_dwStatus, m_struOutput, m_dwDispNum * sizeof(NET_DVR_WALLOUTPUTPARAM)))
{
sprintf(cs, "获取所有属性失败, Error code: %d", NET_DVR_GetLastError());
AfxMessageBox(cs);
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_WALLOUTPUT_GET");
return;
}
for (i = 0; i < m_dwDispNum; i++)
{
if (m_dwStatus[i] > 0)
{
sprintf(cs, "%sDispchan: %d\n", cs, m_lDispChan[i]);
bOneFail = TRUE;
}
}
if (bOneFail)
{
AfxMessageBox(cs);
m_dwOutputSet = 0;
memset(m_dwStatus, 0, sizeof(m_dwStatus));
}
else
{
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_WALLOUTPUT_GET");
m_dwCount = 0;
memset(m_dwStatus, 0, sizeof(m_dwStatus));
}
//DrawList();
OnSelchangeComboOutput();
}
//更新项记录
BOOL CDlgWallCfg_Uniform::UpdateOutputNum(const NET_DVR_VIDEOWALLDISPLAYPOSITION &struDisplayPos)
{
//判断是否新修改项
int i=0;
int j = 0;
for (i=0; i<m_dwDispNum; i++)
{
if ( struDisplayPos.dwDisplayNo == m_struWallParam[i].dwDisplayNo)
{
break;
}
}
m_struWallParam[i] = struDisplayPos;
if (i >= m_dwDispNum)
{
//新项
m_dwDispNum ++;
//添加修改记录
m_lDispChanSet[m_dwCount] = i;
m_dwCount ++;
}
else
{
//原有项
// 判断是否添加修改记录
for( j=0; j<m_dwCount; j++)
{
if (m_lDispChanSet[j] == i)
{
break;
}
}
if(j>=m_dwCount)
{
m_lDispChanSet[m_dwCount] = i;
m_dwCount ++;
}
}
return TRUE;
}
//更新界面数值到变量
BOOL CDlgWallCfg_Uniform::UpdateDisplayPos(NET_DVR_VIDEOWALLDISPLAYPOSITION &struDisplayPos)
{
UpdateData(TRUE);
struDisplayPos.dwSize = sizeof(struDisplayPos);
struDisplayPos.byEnable = m_bEnable;
struDisplayPos.dwDisplayNo = m_dwOutputNum;
struDisplayPos.dwVideoWallNo = m_byWallNo;
struDisplayPos.dwVideoWallNo <<= 24; //墙号是占高字节
struDisplayPos.struRectCfg.dwXCoordinate = WIDTH * m_comboX.GetCurSel();
struDisplayPos.struRectCfg.dwYCoordinate = HEIGHT * m_comboY.GetCurSel();
return TRUE;
}
BOOL CDlgWallCfg_Uniform::NewOutputNum(const NET_DVR_VIDEOWALLDISPLAYPOSITION &struDisplayPos)
{
int i=0;
for (i=0; i<m_dwDispNum; i++)
{
if ( struDisplayPos.dwDisplayNo == m_struWallParam[i].dwDisplayNo)
{
break;
}
}
m_struWallParam[i] = struDisplayPos;
if (i >= m_dwDispNum)
{
//新项
m_dwDispNum ++;
}
else
{
//原有项
//判断是否添加修改记录 删除修改记录
int j;
int iCount = m_dwCount;
for(j=0; j<iCount; j++)
{
if (m_lDispChanSet[j] == i)
{
break;
}
}
for ( ; j<iCount; j++)
{
m_lDispChanSet[j] = m_lDispChanSet[j+1];
}
if ( m_dwCount )
{
m_dwCount --;
}
}
return TRUE;
}
//获取修改过项
LPNET_DVR_VIDEOWALLDISPLAYPOSITION CDlgWallCfg_Uniform::GetModifyDisplayPos()
{
memset(m_struWallParamSet, 0, sizeof(m_struWallParamSet));
for (int i=0; i<m_dwCount; i++)
{
m_struWallParamSet[i] = m_struWallParam[m_lDispChanSet[i]];
m_ModifyChan[i] = m_struWallParamSet[i].dwDisplayNo;
}
return m_struWallParamSet;
}
LONG * CDlgWallCfg_Uniform::GetModifyChan() //获取修改过显示输出号数组
{
memset(m_ModifyChan, 0, sizeof(m_ModifyChan));
for (int i=0; i<m_dwCount; i++)
{
m_ModifyChan[i] = m_struWallParam[m_lDispChanSet[i] ].dwDisplayNo ;
}
return m_ModifyChan;
}
BOOL CDlgWallCfg_Uniform::ClearModify()
{
memset(m_struWallParamSet, 0, sizeof(m_struWallParamSet));
m_dwCount = 0;
memset(m_ModifyChan, 0, sizeof(m_ModifyChan));
return TRUE;
}
BOOL CDlgWallCfg_Uniform::UpdateOutputPapam(NET_DVR_WALLOUTPUTPARAM &struOutputPapam)
{
UpdateData(TRUE);
struOutputPapam.dwSize = sizeof(struOutputPapam);
struOutputPapam.dwResolution = m_comboResolution.GetItemData(m_comboResolution.GetCurSel());
struOutputPapam.struRes.byBrightnessLevel = m_byBrightness;
struOutputPapam.struRes.byContrastLevel = m_byContrast;
struOutputPapam.struRes.bySharpnessLevel = m_bySharpness;
struOutputPapam.struRes.bySaturationLevel = m_bySaturation;
struOutputPapam.struRes.byHueLevel = m_byHue;
struOutputPapam.struRes.byEnableFunc = (BYTE)(m_bFgb | (m_bDzd << 1) | (m_bQgyz << 2));
if (m_comboLevel.GetCurSel() != CB_ERR)
{
struOutputPapam.struRes.byLightInhibitLevel = m_comboLevel.GetCurSel() + 1;
}
struOutputPapam.struRes.byGrayLevel = m_byGray;
struOutputPapam.byVideoFormat = m_combVideoFormat.GetCurSel();
int iSel = m_combDisplayMode.GetCurSel();
struOutputPapam.byDisplayMode = (iSel == 4)? 0xff : iSel+1;
struOutputPapam.byBackgroundColor = m_combDisplayMode.GetCurSel()+1;
return TRUE;
}
BOOL CDlgWallCfg_Uniform::RemovePapamRecord(DWORD dwOutputNO)
{
int i=0;
for (i=0; i<m_dwCount; i++)
{
if (dwOutputNO == m_lDispChan[m_dwRecordPapam[i] ])
{
break;
}
}
if (i<m_dwCount)
{
for ( ; i<m_dwCount-1; i++)
{
m_dwRecordPapam[i] = m_dwRecordPapam[i+1];
}
m_dwCount --;
}
return TRUE;
}
BOOL CDlgWallCfg_Uniform::UpdatePapams(DWORD dwOutputNO, NET_DVR_WALLOUTPUTPARAM &struOutputPapam)
{
return TRUE;
}
LPNET_DVR_WALLOUTPUTPARAM CDlgWallCfg_Uniform::GetModifyPapam()
{
memset(m_struOutputSet, 0, sizeof(m_struOutputSet));
for (int i=0; i<m_lRecordCount; i++)
{
m_struOutputSet[i] = m_struOutput[m_dwRecordPapam[i] ];
}
return m_struOutputSet;
}
LONG * CDlgWallCfg_Uniform::GetModifyPapamChan()
{
memset(m_ModifyChan, 0, sizeof(m_ModifyChan));
for (int i=0; i<m_lRecordCount; i++)
{
m_ModifyChan[i] = m_lDispChan[m_dwRecordPapam[i] ];
}
return m_ModifyChan;
}
void CDlgWallCfg_Uniform::InitOutputLinkMode()
{
memset(&m_struDisplayCfg, 0, sizeof(m_struDisplayCfg));
m_struDisplayCfg.dwSize = sizeof(m_struDisplayCfg);
char szLan[128] = {0};
DWORD dwRet;
if (!NET_DVR_GetDVRConfig(m_lUserID, NET_DVR_GET_VIDEOWALLDISPLAYNO, 0, &m_struDisplayCfg, sizeof(m_struDisplayCfg), &dwRet))
{
g_StringLanType(szLan, "获取显示输出号状态失败", "Failed to get Output Num");
sprintf(szLan, "%s Error Code %d", szLan, NET_DVR_GetLastError());
AfxMessageBox(szLan);
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_VIDEOWALLDISPLAYNO");
}
}
void CDlgWallCfg_Uniform::OnButVideowallControl()
{
// TODO: Add your control notification handler code here
CDlgWallControl dlg;
// LONG m_lUserID;
// LONG m_iDeviceIndex;
// dlg.m_lUserID = m_lUserID;
// dlg.m_iDeviceIndex = m_iDeviceIndex;
dlg.DoModal();
}
void CDlgWallCfg_Uniform::OnButVwscSend()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
char szLan[128] = {0};
NET_DVR_SHOW_CONTROL_INFO struControlInfo = {0};
struControlInfo.dwSize = sizeof(struControlInfo);
struControlInfo.byChanType = m_CmChanTypeC.GetCurSel() + 1;
struControlInfo.byEnable = m_BShowC;
struControlInfo.dwDisplayNo = (m_BAllDisplayNo)?0xffffffff : m_dwDisplayNoC;
struControlInfo.dwWallNo = m_byWallNo;
struControlInfo.dwWallNo <<= 24 ;
if (! NET_DVR_RemoteControl(m_lUserID, NET_DVR_DISPLAY_CHANNO_CONTROL, &struControlInfo, sizeof(struControlInfo)))
{
g_StringLanType(szLan, "发送编号显示控制失败", "Failed to send Display Show Control");
sprintf(szLan, "%s Error Code %d", szLan, NET_DVR_GetLastError());
AfxMessageBox(szLan);
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_DISPLAY_CHANNO_CONTROL");
}
}
void CDlgWallCfg_Uniform::OnChkVwsAlldisplayno()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
if (m_BAllDisplayNo)
{
GetDlgItem(IDC_EDT_VWSC_DISPLAYNO)->EnableWindow(FALSE);
}
else
{
GetDlgItem(IDC_EDT_VWSC_DISPLAYNO)->EnableWindow(TRUE);
}
}
void CDlgWallCfg_Uniform::OnButDispParamAllSame()
{
// TODO: Add your control notification handler code here
NET_DVR_WALLOUTPUTPARAM struOuputPapam={0};
UpdateOutputPapam(struOuputPapam);
char szLan[128];
int iSelData = m_comboOutput.GetItemData(m_comboOutput.GetCurSel());
// if (iSel == -1)
// {
// g_StringLanType(szLan, "请选择显示输出号", "please select output No.");
// AfxMessageBox(szLan);
// return;
// }
DWORD dwDispNo = (iSelData & 0xff000000) + 0xffffff;
if (!NET_DVR_SetDeviceConfig(m_lUserID, NET_DVR_WALLOUTPUT_SET, 0xffffffff, &dwDispNo, sizeof(DWORD), NULL, &struOuputPapam, sizeof(NET_DVR_WALLOUTPUTPARAM)))
{
sprintf(szLan, "设置修改失败, Error code: %d", NET_DVR_GetLastError());
AfxMessageBox(szLan);
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_WALLOUTPUT_SET");
return;
}
g_pMainDlg->AddLog(m_iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_WALLOUTPUT_SET");
// OnBtnUpdateOutput();
}
| [
"[email protected]"
] | |
dad721a8534f1c917209d74b610e2ad6771f3281 | 737c1336dade196da076ac11df449d23eab68f27 | /main.cpp | c571f64420f7484571d634b62ac9e1c8bea7f12e | [] | no_license | coolws/forFun | 4b04afd274e4bce3f56ffc4a4cbe7f6021f5c4d1 | fb320b88639bd3296dd89c220411e5535238ae35 | refs/heads/master | 2021-03-12T23:38:36.671444 | 2015-03-11T03:24:58 | 2015-03-11T03:24:58 | 18,791,462 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,800 | cpp | // 求数组各数开根号后累加和
// 方法: 一个数组让多个进程模拟,各自开根号求和后,传送给0号进程
// 0号进程求各个进程的累加,即为答案
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "mpi.h"
#define N 1002
// MPI_Send (buf, count, datatype, dest, tag, comm) : 发送一个消息
// MPI_Recv (buf, count, datatype, source, tag, comm, status) : 接受消息
// size: 进程数,rank:指定进程的ID
// comm:指定一个通信组(communicator)
// Dest:目标进程号,source:源进程标识号,tag:消息标签
int main(int argc,char * argv[])
{
int myid , numprocs , source;
int C=0;
double data[N],sqrtsum=0.0;
double d;
char message[100];
MPI_Status status;
for(int i=0;i<N;i++)
data[i]=i;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
MPI_Comm_size(MPI_COMM_WORLD,& numprocs);
numprocs--; //分配时除去0号节点
if(myid == 0) //0号主节点,主要负责数据分发和结果收集
{
for(int i=0;i<N;i++) //数据分发:0
MPI_Send(&(data[i]),1,MPI_DOUBLE, i%numprocs+1 , 1 ,MPI_COMM_WORLD);
for(int source=1;source<=numprocs;source++) //结果收集
{
MPI_Recv(&d,1,MPI_DOUBLE,source,99,MPI_COMM_WORLD,&status);
sqrtsum +=d;
}
}
else
{
for(int i=(myid-1);i<N;i=i+numprocs) //各子节点接受数据计算开平方,本地累加
{
MPI_Recv(&d,1,MPI_DOUBLE,0,1,MPI_COMM_WORLD,&status);
sqrtsum += sqrt(d);
//printf("%d %f\n",myid,sqrt(d));
C++;
}
MPI_Send(&sqrtsum,1,MPI_DOUBLE,0,99,MPI_COMM_WORLD); //本地累加结果送回主节点
}
printf("I am process %d. I receive total %d from process 0, and SqrtSum=%f.\n", myid, C, sqrtsum);
MPI_Finalize();
return 0;
} | [
"[email protected]"
] | |
309236a55f21c8277156e62371387d98037e5c85 | d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3 | /Examples/RegistrationITKv3/ImageRegistration20.cxx | fde52c6a6b446ae7cd5eeda9c92197934f75953b | [
"SMLNJ",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"NTP",
"IJG",
"GPL-1.0-or-later",
"libtiff",
"BSD-4.3TAHOE",
"Zlib",
"MIT",
"LicenseRef-scancode-proprietary-license",
"Spencer-86",
"Apache-2.0",
"FSFUL",
"LicenseRef-scancode-public-domain",
"Libpng",
"BSD-2-Clause"
] | permissive | nalinimsingh/ITK_4D | 18e8929672df64df58a6446f047e6ec04d3c2616 | 95a2eacaeaffe572889832ef0894239f89e3f303 | refs/heads/master | 2020-03-17T18:58:50.953317 | 2018-10-01T20:46:43 | 2018-10-01T21:21:01 | 133,841,430 | 0 | 0 | Apache-2.0 | 2018-05-17T16:34:54 | 2018-05-17T16:34:53 | null | UTF-8 | C++ | false | false | 16,367 | cxx | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {brainweb1e1a10f20.mha}
// INPUTS: {brainweb1e1a10f20Rot10Tx15.mha}
// ARGUMENTS: ImageRegistration20Output.mhd
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the use of the \doxygen{AffineTransform}
// for performing registration in $3D$.
//
// \index{itk::AffineTransform}
//
// Software Guide : EndLatex
#include "itkImageRegistrationMethod.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkRegularStepGradientDescentOptimizer.h"
#include "itkCenteredTransformInitializer.h"
// Software Guide : BeginLatex
//
// Let's start by including the header file of the AffineTransform.
//
// \index{itk::AffineTransform!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkAffineTransform.h"
// Software Guide : EndCodeSnippet
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkSubtractImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
//
// The following piece of code implements an observer
// that will monitor the evolution of the registration process.
//
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {};
public:
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef const OptimizerType * OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
OptimizerPointer optimizer = static_cast< OptimizerPointer >( object );
if( ! itk::IterationEvent().CheckEvent( &event ) )
{
return;
}
std::cout << optimizer->GetCurrentIteration() << " ";
std::cout << optimizer->GetValue() << " ";
std::cout << optimizer->GetCurrentPosition() << std::endl;
}
};
int main( int argc, char *argv[] )
{
if( argc < 4 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " fixedImageFile movingImageFile " << std::endl;
std::cerr << " outputImagefile [differenceBeforeRegistration] " << std::endl;
std::cerr << " [differenceAfterRegistration] " << std::endl;
std::cerr << " [stepLength] [maxNumberOfIterations] "<< std::endl;
return EXIT_FAILURE;
}
// Software Guide : BeginLatex
//
// We define then the types of the images to be registered.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 3;
typedef float PixelType;
typedef itk::Image< PixelType, Dimension > FixedImageType;
typedef itk::Image< PixelType, Dimension > MovingImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The transform type is instantiated using the code below. The template
// parameters of this class are the representation type of the space
// coordinates and the space dimension.
//
// \index{itk::AffineTransform!Instantiation}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::AffineTransform<
double,
Dimension > TransformType;
// Software Guide : EndCodeSnippet
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef itk::MeanSquaresImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
typedef itk:: LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
MetricType::Pointer metric = MetricType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
registration->SetMetric( metric );
registration->SetOptimizer( optimizer );
registration->SetInterpolator( interpolator );
// Software Guide : BeginLatex
//
// The transform object is constructed below and passed to the registration
// method.
//
// \index{itk::AffineTransform!New()}
// \index{itk::AffineTransform!Pointer}
// \index{itk::RegistrationMethod!SetTransform()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::Pointer transform = TransformType::New();
registration->SetTransform( transform );
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;
typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;
FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();
MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();
fixedImageReader->SetFileName( argv[1] );
movingImageReader->SetFileName( argv[2] );
registration->SetFixedImage( fixedImageReader->GetOutput() );
registration->SetMovingImage( movingImageReader->GetOutput() );
fixedImageReader->Update();
registration->SetFixedImageRegion(
fixedImageReader->GetOutput()->GetBufferedRegion() );
// Software Guide : BeginLatex
//
// In this example, we again use the
// \doxygen{CenteredTransformInitializer} helper class in order to compute
// a reasonable value for the initial center of rotation and the
// translation. The initializer is set to use the center of mass of each
// image as the initial correspondence correction.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::CenteredTransformInitializer<
TransformType, FixedImageType,
MovingImageType > TransformInitializerType;
TransformInitializerType::Pointer initializer
= TransformInitializerType::New();
initializer->SetTransform( transform );
initializer->SetFixedImage( fixedImageReader->GetOutput() );
initializer->SetMovingImage( movingImageReader->GetOutput() );
initializer->MomentsOn();
initializer->InitializeTransform();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now we pass the parameters of the current transform as the initial
// parameters to be used when the registration process starts.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
registration->SetInitialTransformParameters(
transform->GetParameters() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Keeping in mind that the scale of units in scaling, rotation and
// translation are quite different, we take advantage of the scaling
// functionality provided by the optimizers. We know that the first $N
// \times N$ elements of the parameters array correspond to the rotation
// matrix factor, and the last $N$ are the components of the translation to
// be applied after multiplication with the matrix is performed.
//
// Software Guide : EndLatex
double translationScale = 1.0 / 1000.0;
if( argc > 8 )
{
translationScale = atof( argv[8] );
}
// Software Guide : BeginCodeSnippet
typedef OptimizerType::ScalesType OptimizerScalesType;
OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() );
optimizerScales[0] = 1.0;
optimizerScales[1] = 1.0;
optimizerScales[2] = 1.0;
optimizerScales[3] = 1.0;
optimizerScales[4] = 1.0;
optimizerScales[5] = 1.0;
optimizerScales[6] = 1.0;
optimizerScales[7] = 1.0;
optimizerScales[8] = 1.0;
optimizerScales[9] = translationScale;
optimizerScales[10] = translationScale;
optimizerScales[11] = translationScale;
optimizer->SetScales( optimizerScales );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We also set the usual parameters of the optimization method. In this
// case we are using an
// \doxygen{RegularStepGradientDescentOptimizer}. Below, we define the
// optimization parameters like initial step length, minimal step length
// and number of iterations. These last two act as stopping criteria for
// the optimization.
//
// Software Guide : EndLatex
double steplength = 0.1;
if( argc > 6 )
{
steplength = atof( argv[6] );
}
unsigned int maxNumberOfIterations = 300;
if( argc > 7 )
{
maxNumberOfIterations = atoi( argv[7] );
}
// Software Guide : BeginCodeSnippet
optimizer->SetMaximumStepLength( steplength );
optimizer->SetMinimumStepLength( 0.0001 );
optimizer->SetNumberOfIterations( maxNumberOfIterations );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We also set the optimizer to do minimization by calling the
// \code{MinimizeOn()} method.
//
// \index{itk::Regular\-Step\-Gradient\-Descent\-Optimizer!MinimizeOn()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
optimizer->MinimizeOn();
// Software Guide : EndCodeSnippet
// Create the Command observer and register it with the optimizer.
//
CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
optimizer->AddObserver( itk::IterationEvent(), observer );
// Software Guide : BeginLatex
//
// Finally we trigger the execution of the registration method by calling
// the \code{Update()} method. The call is placed in a \code{try/catch}
// block in case any exceptions are thrown.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
try
{
registration->Update();
std::cout << "Optimizer stop condition: "
<< registration->GetOptimizer()->GetStopConditionDescription()
<< std::endl;
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Once the optimization converges, we recover the parameters from the
// registration method. This is done with the
// \code{GetLastTransformParameters()} method. We can also recover the
// final value of the metric with the \code{GetValue()} method and the
// final number of iterations with the \code{GetCurrentIteration()}
// method.
//
// \index{itk::RegistrationMethod!GetValue()}
// \index{itk::RegistrationMethod!GetCurrentIteration()}
// \index{itk::RegistrationMethod!GetLastTransformParameters()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
OptimizerType::ParametersType finalParameters =
registration->GetLastTransformParameters();
const unsigned int numberOfIterations = optimizer->GetCurrentIteration();
const double bestValue = optimizer->GetValue();
// Software Guide : EndCodeSnippet
// Print out results
//
std::cout << "Result = " << std::endl;
std::cout << " Iterations = " << numberOfIterations << std::endl;
std::cout << " Metric value = " << bestValue << std::endl;
// The following code is used to dump output images to files.
// They illustrate the final results of the registration.
// We will resample the moving image and write out the difference image
// before and after registration. We will also rescale the intensities of the
// difference images, so that they look better!
typedef itk::ResampleImageFilter<
MovingImageType,
FixedImageType > ResampleFilterType;
TransformType::Pointer finalTransform = TransformType::New();
finalTransform->SetParameters( finalParameters );
finalTransform->SetFixedParameters( transform->GetFixedParameters() );
ResampleFilterType::Pointer resampler = ResampleFilterType::New();
resampler->SetTransform( finalTransform );
resampler->SetInput( movingImageReader->GetOutput() );
FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();
resampler->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );
resampler->SetOutputOrigin( fixedImage->GetOrigin() );
resampler->SetOutputSpacing( fixedImage->GetSpacing() );
resampler->SetOutputDirection( fixedImage->GetDirection() );
resampler->SetDefaultPixelValue( 100 );
typedef unsigned char OutputPixelType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::CastImageFilter<
FixedImageType,
OutputImageType > CastFilterType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
CastFilterType::Pointer caster = CastFilterType::New();
writer->SetFileName( argv[3] );
caster->SetInput( resampler->GetOutput() );
writer->SetInput( caster->GetOutput() );
writer->Update();
typedef itk::SubtractImageFilter<
FixedImageType,
FixedImageType,
FixedImageType > DifferenceFilterType;
DifferenceFilterType::Pointer difference = DifferenceFilterType::New();
difference->SetInput1( fixedImageReader->GetOutput() );
difference->SetInput2( resampler->GetOutput() );
WriterType::Pointer writer2 = WriterType::New();
typedef itk::RescaleIntensityImageFilter<
FixedImageType,
OutputImageType > RescalerType;
RescalerType::Pointer intensityRescaler = RescalerType::New();
intensityRescaler->SetInput( difference->GetOutput() );
intensityRescaler->SetOutputMinimum( 0 );
intensityRescaler->SetOutputMaximum( 255 );
writer2->SetInput( intensityRescaler->GetOutput() );
resampler->SetDefaultPixelValue( 1 );
// Compute the difference image between the
// fixed and resampled moving image.
if( argc > 5 )
{
writer2->SetFileName( argv[5] );
writer2->Update();
}
typedef itk::IdentityTransform< double, Dimension > IdentityTransformType;
IdentityTransformType::Pointer identity = IdentityTransformType::New();
// Compute the difference image between the
// fixed and moving image before registration.
if( argc > 4 )
{
resampler->SetTransform( identity );
writer2->SetFileName( argv[4] );
writer2->Update();
}
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
7dab3ee9343878e54c9af0262e8f344f1f4f324b | 58375b805731876f912194c6cca15981f85b8a19 | /modulus/formal_power_series.yukicoder-1145.test.cpp | 07468487f9d1e96c169b07fd29d6aa51011511c6 | [
"MIT"
] | permissive | kmyk/competitive-programming-library | 5562391793dc03691ec999f73ed38a40c6d78e7a | 77efa23a69f06202bb43f4dc6b0550e4cdb48e0b | refs/heads/master | 2021-11-20T11:41:45.804307 | 2021-08-29T21:10:41 | 2021-08-29T21:10:41 | 60,465,111 | 66 | 13 | null | 2016-10-29T08:14:29 | 2016-06-05T14:50:46 | C++ | UTF-8 | C++ | false | false | 1,077 | cpp | #define PROBLEM "https://yukicoder.me/problems/no/1145"
#include <cstdio>
#include <vector>
#include "../utils/macros.hpp"
#include "../modulus/mint.hpp"
#include "../modulus/formal_power_series.hpp"
using namespace std;
constexpr int MOD = 998244353;
vector<mint<MOD> > solve(int n, int m, const vector<mint<MOD> > & a) {
auto go = [&](auto && go, int l, int r) {
if (r - l == 0) return formal_power_series<mint<MOD> >{ 1 };
if (r - l == 1) return formal_power_series<mint<MOD> >{ 1, - a[l] };
int m_ = (l + r) / 2;
return (go(go, l, m_) * go(go, m_, r)).modulo_x_to(m + 2);
};
vector<mint<MOD> > ans = (- go(go, 0, n).log(m + 2)).data();
ans.resize(m + 1);
REP3 (k, 1, m + 1) {
ans[k] *= k;
}
return ans;
}
int main() {
int n, m; scanf("%d%d", &n, &m);
vector<mint<MOD> > a(n);
REP (i, n) {
scanf("%d", &a[i].value);
}
auto ans = solve(n, m, a);
assert (ans[0] == 0);
REP (i, m) {
printf("%d%c", ans[i + 1].value, i + 1 < m ? ' ' : '\n');
}
return 0;
}
| [
"[email protected]"
] | |
5fe8e05c99cb81568cfef41af7218add1ebcf982 | 8813ca7807341e1f07bb35c831e6ae82c208322a | /src/test3/avx2_gemm.h | d7ab4b21f7fbea8a97a60061e0d76a7cd7249260 | [] | no_license | huangjq0617/MKL_perf_test | 39e35c00c52cad1c086b16ef4047c1a24166e939 | 5f45d32990961a722f262b23fa35a94e322da6df | refs/heads/master | 2020-04-08T14:56:44.849928 | 2020-03-25T03:20:13 | 2020-03-25T03:20:13 | 159,458,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,541 | h | #pragma once
#include <cassert>
#include <emmintrin.h>
#include <immintrin.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tmmintrin.h>
#include <xmmintrin.h>
#include <malloc.h>
#include <time.h>
#include "avx_common.h"
namespace avx256 {
void Unquantize(const float * input, __m256i * output, float quant_mult, int num_rows, int width) {
}
class QuantizedMatrix16 {
QuantizedMatrix16(const QuantizedMatrix16&);
public:
QuantizedMatrix16() {}
~QuantizedMatrix16() {}
void init(float quant_mult, int num_rows, int width) {
init(nullptr, quant_mult, num_rows, width);
}
void init(const float * input, float quant_mult, int num_rows, int width) {
M_ = num_rows;
N_ = width;
quant_mult_ = quant_mult;
if (quantized_) {
free(quantized_);
quantized_ = nullptr;
}
quantized_ = (__m256i*)aligned_alloc(32, sizeof(__m256i) * M_ * N_ / 16);
if (input) {
Quantize(input, quantized_, quant_mult, num_rows, width);
}
else {
}
}
float quant_mult() const {
return quant_mult_;
}
int M() const {
return M_;
}
int N() const {
return N_;
}
int MN() const {
return M_ * N_;
}
void Mult(const QuantizedMatrix16* B, QuantizedMatrix16* C) {
}
static void MatrixMult(const __m256i * A, const __m256i * B, __m256i * C, int num_A_rows, int num_B_rows, int width) {
}
static void MatrixMult2(const __m256i * A, const __m256i * B, float * C, float unquant_mult, int num_A_rows, int num_B_rows, int width) {
const int sse_width = width / 16;
__m128 unquant_mults = _mm_set1_ps(unquant_mult);
memset(C, 0, sizeof(float)*num_A_rows*num_B_rows);
for (int j = 0; j < num_B_rows; j += 4) {
const __m256i * B1_row = B + j * sse_width;
const __m256i * B2_row = B1_row + sse_width;
const __m256i * B3_row = B2_row + sse_width;
const __m256i * B4_row = B3_row + sse_width;
for (int i = 0; i < num_A_rows; i++) {
const __m256i * A_row = A + i * sse_width;
__m256i sum1 = _mm256_setzero_si256();
__m256i sum2 = _mm256_setzero_si256();
__m256i sum3 = _mm256_setzero_si256();
__m256i sum4 = _mm256_setzero_si256();
/*
why unrolling 4*4? That is because _mm256_madd_epi16's latency is 5, unroll 4*4 only waste 1 cycles.
*/
#define UNROLL_K__INT16__ 1
for (int k = 0; k < sse_width; k+= UNROLL_K__INT16__) {
const __m256i& a = *(A_row + k);
const __m256i& b1 = *(B1_row + k);
const __m256i& b2 = *(B2_row + k);
const __m256i& b3 = *(B3_row + k);
const __m256i& b4 = *(B4_row + k);
#if UNROLL_K__INT16__ == 4
const __m256i& a_1 = *(A_row + k + 1);
const __m256i& a_2 = *(A_row + k + 2);
const __m256i& a_3 = *(A_row + k + 3);
const __m256i& b1_1 = *(B1_row + k + 1);
const __m256i& b1_2 = *(B1_row + k + 2);
const __m256i& b1_3 = *(B1_row + k + 3);
const __m256i& b2_1 = *(B2_row + k + 1);
const __m256i& b2_2 = *(B2_row + k + 2);
const __m256i& b2_3 = *(B2_row + k + 3);
const __m256i& b3_1 = *(B3_row + k + 1);
const __m256i& b3_2 = *(B3_row + k + 2);
const __m256i& b3_3 = *(B3_row + k + 3);
const __m256i& b4_1 = *(B4_row + k + 1);
const __m256i& b4_2 = *(B4_row + k + 2);
const __m256i& b4_3 = *(B4_row + k + 3);
#endif
__m256i b1xa = _mm256_madd_epi16(b1, a);
__m256i b2xa = _mm256_madd_epi16(b2, a);
__m256i b3xa = _mm256_madd_epi16(b3, a);
__m256i b4xa = _mm256_madd_epi16(b4, a);
#if UNROLL_K__INT16__ == 4
__m256i b1_1xa_1 = _mm256_madd_epi16(b1_1, a_1);
__m256i b2_1xa_1 = _mm256_madd_epi16(b2_1, a_1);
__m256i b3_1xa_1 = _mm256_madd_epi16(b3_1, a_1);
__m256i b4_1xa_1 = _mm256_madd_epi16(b4_1, a_1);
__m256i b1_2xa_2 = _mm256_madd_epi16(b1_2, a_2);
__m256i b2_2xa_2 = _mm256_madd_epi16(b2_2, a_2);
__m256i b3_2xa_2 = _mm256_madd_epi16(b3_2, a_2);
__m256i b4_2xa_2 = _mm256_maddubs_epi16(b4_2, a_2);
__m256i b1_3xa_3 = _mm256_madd_epi16(b1_3, a_3);
__m256i b2_3xa_3 = _mm256_madd_epi16(b2_3, a_3);
__m256i b3_3xa_3 = _mm256_madd_epi16(b3_3, a_3);
__m256i b4_3xa_3 = _mm256_madd_epi16(b4_3, a_3);
sum1 = _mm256_add_epi32(sum1, b1_1xa_1);
sum2 = _mm256_add_epi32(sum2, b2_1xa_1);
sum3 = _mm256_add_epi32(sum3, b3_1xa_1);
sum4 = _mm256_add_epi32(sum4, b4_1xa_1);
sum1 = _mm256_add_epi32(sum1, b1_2xa_2);
sum2 = _mm256_add_epi32(sum2, b2_2xa_2);
sum3 = _mm256_add_epi32(sum3, b3_2xa_2);
sum4 = _mm256_add_epi32(sum4, b4_2xa_2);
sum1 = _mm256_add_epi32(sum1, b1_3xa_3);
sum2 = _mm256_add_epi32(sum2, b2_3xa_3);
sum3 = _mm256_add_epi32(sum3, b3_3xa_3);
sum4 = _mm256_add_epi32(sum4, b4_3xa_3);
#endif
sum1 = _mm256_add_epi32(sum1, b1xa);
sum2 = _mm256_add_epi32(sum2, b2xa);
sum3 = _mm256_add_epi32(sum3, b3xa);
sum4 = _mm256_add_epi32(sum4, b4xa);
}
__m128i sum;
HADD4(sum1, sum2, sum3, sum4, sum);
__m128 f_sum = _mm_cvtepi32_ps(sum);
#if 1
float * C1 = C + i*num_B_rows + j;
f_sum = _mm_mul_ps(f_sum, unquant_mults);
f_sum = _mm_add_ps(f_sum, _mm_load_ps(C1));
_mm_store_ps(C1, f_sum);
#else
float * C1 = C + i*num_B_rows + j;
float * C2 = C + i*num_B_rows + j+1;
float * C3 = C + i*num_B_rows + j+2;
float * C4 = C + i*num_B_rows + j+3;
_mm_storeu_ps(extractSum, f_sum);
*(C1) += extractSum[0] * unquant_mult;
*(C2) += extractSum[1] * unquant_mult;
*(C3) += extractSum[2] * unquant_mult;
*(C4) += extractSum[3] * unquant_mult;
#endif
}
}
}
static void MatrixMult(const __m256i * A, const __m256i * B, float * C, float unquant_mult, int num_A_rows, int num_B_rows, int width) {
assert(num_A_rows % 4 == 0);
assert(width % 16 == 0);
int sse_width = width / 16;
__m128 unquant_mults = _mm_set1_ps(unquant_mult);
float extractSum[4];
// We do loop unrolling over A. This is *significantly* faster
// since B can live in the registers. We are assuming that
// A is a multiple of 4, but we can add extra code to handle values of 1, 2, 3.
//
// We could also do loop unrolling over B, which adds some additional speedup.
// We don't do that for the sake of clarity.
//
// There are other memory access patterns we could do, e.g., put B on the outer loop.
// The justification is that A is typically small enough that it can live in L1 cache.
// B is usually a larger weight matrix, so it might not be able to. However, we are using
// each element of B four times while it's still in a register, so caching is not as important.
for (int i = 0; i < num_A_rows; i += 4) {
const __m256i * A1_row = A + (i + 0)*sse_width;
const __m256i * A2_row = A + (i + 1)*sse_width;
const __m256i * A3_row = A + (i + 2)*sse_width;
const __m256i * A4_row = A + (i + 3)*sse_width;
for (int j = 0; j < num_B_rows; j++) {
const __m256i * B_row = B + j*sse_width;
__m256i sum1 = _mm256_setzero_si256();
__m256i sum2 = _mm256_setzero_si256();
__m256i sum3 = _mm256_setzero_si256();
__m256i sum4 = _mm256_setzero_si256();
// This is just a simple dot product, unrolled four ways.
for (int k = 0; k < sse_width; k++) {
const __m256i& b = *(B_row + k);
const __m256i& a1 = *(A1_row + k);
const __m256i& a2 = *(A2_row + k);
const __m256i& a3 = *(A3_row + k);
const __m256i& a4 = *(A4_row + k);
// _mm_madd_epi16 does multiply add on 8 16-bit integers and accumulates into a four 32-bit register.
// E.g.,
// a1 = [f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, fa, fb, fc, fd, fe, ff] (16-bit ints)
// b1 = [h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, ha, hb, hc, hd, he, hf] (16-bit ints)
// result = [f0*h0 + f1*h1, f2*h2+f3*h3,..., fe*he, + ff* hf] (32-bit ints)
// Then _mm256_add_epi32 just effectively does a += on these 32-bit integers.
sum1 = _mm256_add_epi32(sum1, _mm256_madd_epi16(b, a1));
sum2 = _mm256_add_epi32(sum2, _mm256_madd_epi16(b, a2));
sum3 = _mm256_add_epi32(sum3, _mm256_madd_epi16(b, a3));
sum4 = _mm256_add_epi32(sum4, _mm256_madd_epi16(b, a4));
}
__m128i sum;
HADD4(sum1, sum2, sum3, sum4, sum);
float * C1 = C + (i + 0)*num_B_rows + j;
float * C2 = C + (i + 1)*num_B_rows + j;
float * C3 = C + (i + 2)*num_B_rows + j;
float * C4 = C + (i + 3)*num_B_rows + j;
__m128 f_sum = _mm_cvtepi32_ps(sum);
f_sum = _mm_mul_ps(f_sum, unquant_mults);
_mm_storeu_ps(extractSum, f_sum);
*(C1) = extractSum[0];
*(C2) = extractSum[1];
*(C3) = extractSum[2];
*(C4) = extractSum[3];
}
}
}
static int martix_index_to_m256(int n) {
/*
dst[15:0] := Saturate_Int32_To_Int16 (a[31:0]) #0 0
dst[31:16] := Saturate_Int32_To_Int16 (a[63:32]) # 1 1
dst[47:32] := Saturate_Int32_To_Int16 (a[95:64]) # 2 2
dst[63:48] := Saturate_Int32_To_Int16 (a[127:96]) # 3 3
dst[79:64] := Saturate_Int32_To_Int16 (b[31:0]) # 8 4
dst[95:80] := Saturate_Int32_To_Int16 (b[63:32]) # 9 5
dst[111:96] := Saturate_Int32_To_Int16 (b[95:64]) # 10 6
dst[127:112] := Saturate_Int32_To_Int16 (b[127:96]) # 11 7
dst[143:128] := Saturate_Int32_To_Int16 (a[159:128]) # 4 8
dst[159:144] := Saturate_Int32_To_Int16 (a[191:160]) # 5 9
dst[175:160] := Saturate_Int32_To_Int16 (a[223:192]) # 6 10
dst[191:176] := Saturate_Int32_To_Int16 (a[255:224]) # 7 11
dst[207:192] := Saturate_Int32_To_Int16 (b[159:128]) # 12 12
dst[223:208] := Saturate_Int32_To_Int16 (b[191:160]) # 13 13
dst[239:224] := Saturate_Int32_To_Int16 (b[223:192]) # 14 14
dst[255:240] := Saturate_Int32_To_Int16 (b[255:224]) # 15 15
*/
static const int g_indexs[] = { 0, 1, 2, 3, 8, 9, 10, 11, 4, 5, 6, 7, 12, 13, 14, 15};
return g_indexs[n];
}
static void Unquantize(const __m256i * input, float * output, float quant_mult, int num_rows, int width)
{
quant_mult = 1.0f / quant_mult;
__m256 m_quant_mult = _mm256_set_ps(quant_mult, quant_mult, quant_mult, quant_mult, quant_mult, quant_mult, quant_mult, quant_mult);
const int num_output_chunks = width / PerfInt16OneVector;
for (int i = 0; i < num_rows; i++) {
float * output_row = output + i * width;
const __m256i * input_row = input + i * num_output_chunks;
for (int j = 0; j < num_output_chunks; j++) {
float * x = output_row + j * PerfInt16OneVector;
const __m256i * y = input_row + j;
const __m128i* a1 = (const __m128i*)y;
const __m128i* a2 = a1 + 1;
__m256i a32_1 = _mm256_cvtepu16_epi32(*a1);
__m256i a32_2 = _mm256_cvtepu16_epi32(*a2);
__m256 f_1 = _mm256_cvtepi32_ps(a32_1);
__m256 f_2 = _mm256_cvtepi32_ps(a32_2);
f_1 = _mm256_mul_ps(f_1, m_quant_mult);
f_2 = _mm256_mul_ps(f_2, m_quant_mult);
const __m128* f_128_1 = (const __m128*)&f_1;
const __m128* f_128_2 = (const __m128*)&f_2;
_mm_store_ps(&x[0], *f_128_1);
_mm_store_ps(&x[8], *(f_128_1 + 1));
_mm_store_ps(&x[4], *f_128_2);
_mm_store_ps(&x[12], *(f_128_2 + 1));
/*
x[0] = f_1.m256_f32[0];
x[1] = f_1.m256_f32[1];
x[2] = f_1.m256_f32[2];
x[3] = f_1.m256_f32[3];
x[8] = f_1.m256_f32[4];
x[9] = f_1.m256_f32[5];
x[10] = f_1.m256_f32[6];
x[11] = f_1.m256_f32[7];
x[4] = f_2.m256_f32[0];
x[5] = f_2.m256_f32[1];
x[6] = f_2.m256_f32[2];
x[7] = f_2.m256_f32[3];
x[12] = f_2.m256_f32[4];
x[13] = f_2.m256_f32[5];
x[14] = f_2.m256_f32[6];
x[15] = f_2.m256_f32[7];
*/
}
}
}
static void Quantize(const float * input, __m256i * output, float quant_mult, int num_rows, int width) {
//static_assert(PerfSize == 16);
assert(width % PerfInt16OneVector == 0);
assert(PerfInt16OneVector == 16);
const int num_input_chunks = width / PerfInt16OneVector;
__m256 sse_quant_mult = _mm256_set_ps(quant_mult, quant_mult, quant_mult, quant_mult, quant_mult, quant_mult, quant_mult, quant_mult);
for (int i = 0; i < num_rows; i++) {
const float * input_row = input + i * width;
__m256i * output_row = output + i * num_input_chunks;
for (int j = 0; j < num_input_chunks; j++) {
const float * x = input_row + j * PerfInt16OneVector;
// Process 16 floats at once, since each __m256i can contain 16 16-bit integers.
__m256 f_0 = _mm256_loadu_ps(x);
__m256 f_1 = _mm256_loadu_ps(x + PerfFloatOneVector);
// Multiply by quantization factor (e.g., if quant_mult = 1000.0, 0.34291 --> 342.21)
__m256 m_0 = _mm256_mul_ps(f_0, sse_quant_mult);
__m256 m_1 = _mm256_mul_ps(f_1, sse_quant_mult);
// Cast float to 32-bit int (e.g., 342.21 --> 342)
__m256i i_0 = _mm256_cvtps_epi32(m_0);
__m256i i_1 = _mm256_cvtps_epi32(m_1);
// Cast 32-bit int to 16-bit int. You must ensure that these fit into the 16-bit range
// by clipping values during training.
/*
dst[15:0] := Saturate_Int32_To_Int16 (a[31:0]) #0
dst[31:16] := Saturate_Int32_To_Int16 (a[63:32]) # 1
dst[47:32] := Saturate_Int32_To_Int16 (a[95:64]) # 2
dst[63:48] := Saturate_Int32_To_Int16 (a[127:96]) # 3
dst[79:64] := Saturate_Int32_To_Int16 (b[31:0]) # 8
dst[95:80] := Saturate_Int32_To_Int16 (b[63:32]) # 9
dst[111:96] := Saturate_Int32_To_Int16 (b[95:64]) # 10
dst[127:112] := Saturate_Int32_To_Int16 (b[127:96]) # 11
dst[143:128] := Saturate_Int32_To_Int16 (a[159:128]) # 4
dst[159:144] := Saturate_Int32_To_Int16 (a[191:160]) # 5
dst[175:160] := Saturate_Int32_To_Int16 (a[223:192]) # 6
dst[191:176] := Saturate_Int32_To_Int16 (a[255:224]) # 7
dst[207:192] := Saturate_Int32_To_Int16 (b[159:128]) # 12
dst[223:208] := Saturate_Int32_To_Int16 (b[191:160]) # 13
dst[239:224] := Saturate_Int32_To_Int16 (b[223:192]) # 14
dst[255:240] := Saturate_Int32_To_Int16 (b[255:224]) # 15
*/
*(output_row + j) = _mm256_packs_epi32(i_0, i_1);
}
}
}
private:
int M_ = 0;
int N_ = 0;
float quant_mult_ = 1.0f;
__m256i* quantized_ = nullptr;
};
}
| [
"[email protected]"
] | |
7cf2fecf82031a47c9b94af1c85085675fe514a1 | 3cfb604ec36bd0131781875ef237e2278f4df2be | /Polynomial.h | 761f3348ccd6fd142f8d34a26a8eaf21b413a2e5 | [] | no_license | kikichan1212/Proj2 | a08f2a7e19bfde03c25730a88d06e1897822fbea | 91254b502c9e3c79986bf87a270349881100bc1a | refs/heads/master | 2021-01-18T21:09:15.391021 | 2017-04-02T19:26:54 | 2017-04-02T19:26:54 | 87,009,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | h | /* -----------------------------------------------------------------------------
FILE: Polynomial.H
DESCRIPTION:
COMPILER: g++ compiler for C++ 11
NOTES:
MODIFICATION HISTORY:
Author Date Version
--------------- ---------- --------------
Keegan Phillips 2017-03-29 1.0
Version 1.0:
TBD
----------------------------------------------------------------------------- */
#ifndef POLYNOMIAL_H_
#define POLYNOMIAL_H_
#include<cmath>
#include<iostream>
#define NUM_COEFF 11
class Polynomial
{
private:
// We don't wan't to inadvertantly manipulate these attributes,
// thus we make them accessible via member functions rather than
// via direct access. This ensures that the program is more likely
// to run as intended, especially when if the class is used by
// other programmers
int degree;
int coeff[NUM_COEFF];
public:
// Enter public attributes and member functions here
// Basic overloaded operators with ADT Polynomial
// Then the () and == operators
// Polynomial() is the default constructor
Polynomial();
}
| [
"[email protected]"
] | |
c2a39ae3079dcbbc3ca52a3686cb1b8f4d9bb189 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.cc | 6e260f58fb0aafbf1396d91e9ebe29e6487c5654 | [
"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 | 5,384 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.h"
#include <memory>
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/task/post_task.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/fileapi/async_file_util.h"
#include "chrome/browser/chromeos/drive/fileapi/fileapi_worker.h"
#include "chrome/browser/chromeos/drive/fileapi/webkit_file_stream_reader_impl.h"
#include "chrome/browser/chromeos/drive/fileapi/webkit_file_stream_writer_impl.h"
#include "components/drive/chromeos/file_system_interface.h"
#include "components/drive/drive_api_util.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "storage/browser/fileapi/async_file_util.h"
#include "storage/browser/fileapi/file_stream_reader.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "storage/browser/fileapi/file_system_url.h"
using content::BrowserThread;
namespace drive {
namespace {
// Called on the UI thread after GetRedirectURLForContentsOnUIThread. Obtains
// the browser URL from |entry|. |callback| will be called on the IO thread.
void GetRedirectURLForContentsOnUIThreadWithResourceEntry(
const storage::URLCallback& callback,
FileError error,
std::unique_ptr<ResourceEntry> entry) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
GURL url;
if (error == FILE_ERROR_OK && entry->has_file_specific_info() &&
entry->file_specific_info().is_hosted_document()) {
url = GURL(entry->alternate_url());
}
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(callback, url));
}
// Called on the UI thread after
// FileSystemBackendDelegate::GetRedirectURLForContents. Requestes to obtain
// ResourceEntry for the |url|.
void GetRedirectURLForContentsOnUIThread(
const storage::FileSystemURL& url,
const storage::URLCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
FileSystemInterface* const file_system =
fileapi_internal::GetFileSystemFromUrl(url);
if (!file_system) {
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(callback, GURL()));
return;
}
const base::FilePath file_path = util::ExtractDrivePathFromFileSystemUrl(url);
if (file_path.empty()) {
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(callback, GURL()));
return;
}
file_system->GetResourceEntry(
file_path,
base::BindOnce(&GetRedirectURLForContentsOnUIThreadWithResourceEntry,
callback));
}
} // namespace
FileSystemBackendDelegate::FileSystemBackendDelegate()
: async_file_util_(new internal::AsyncFileUtil) {
}
FileSystemBackendDelegate::~FileSystemBackendDelegate() = default;
storage::AsyncFileUtil* FileSystemBackendDelegate::GetAsyncFileUtil(
storage::FileSystemType type) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK_EQ(storage::kFileSystemTypeDrive, type);
return async_file_util_.get();
}
std::unique_ptr<storage::FileStreamReader>
FileSystemBackendDelegate::CreateFileStreamReader(
const storage::FileSystemURL& url,
int64_t offset,
int64_t max_bytes_to_read,
const base::Time& expected_modification_time,
storage::FileSystemContext* context) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK_EQ(storage::kFileSystemTypeDrive, url.type());
base::FilePath file_path = util::ExtractDrivePathFromFileSystemUrl(url);
if (file_path.empty())
return std::unique_ptr<storage::FileStreamReader>();
return std::unique_ptr<storage::FileStreamReader>(
new internal::WebkitFileStreamReaderImpl(
base::Bind(&fileapi_internal::GetFileSystemFromUrl, url),
context->default_file_task_runner(), file_path, offset,
expected_modification_time));
}
std::unique_ptr<storage::FileStreamWriter>
FileSystemBackendDelegate::CreateFileStreamWriter(
const storage::FileSystemURL& url,
int64_t offset,
storage::FileSystemContext* context) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK_EQ(storage::kFileSystemTypeDrive, url.type());
base::FilePath file_path = util::ExtractDrivePathFromFileSystemUrl(url);
// Hosted documents don't support stream writer.
if (file_path.empty() || util::HasHostedDocumentExtension(file_path))
return std::unique_ptr<storage::FileStreamWriter>();
return std::unique_ptr<storage::FileStreamWriter>(
new internal::WebkitFileStreamWriterImpl(
base::Bind(&fileapi_internal::GetFileSystemFromUrl, url),
context->default_file_task_runner(), file_path, offset));
}
storage::WatcherManager* FileSystemBackendDelegate::GetWatcherManager(
storage::FileSystemType type) {
NOTIMPLEMENTED();
return nullptr;
}
void FileSystemBackendDelegate::GetRedirectURLForContents(
const storage::FileSystemURL& url,
const storage::URLCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(&GetRedirectURLForContentsOnUIThread, url, callback));
}
} // namespace drive
| [
"[email protected]"
] | |
f4f6055676d026de1f7eff6b3dc8a22e3d9bbafb | 6a6984544a4782e131510a81ed32cc0c545ab89c | /src/rootwriter/.svn/pristine/f4/f4f6055676d026de1f7eff6b3dc8a22e3d9bbafb.svn-base | 437e945806671b06483eeef111271cef36ff4489 | [] | no_license | wardVD/IceSimV05 | f342c035c900c0555fb301a501059c37057b5269 | 6ade23a2fd990694df4e81bed91f8d1fa1287d1f | refs/heads/master | 2020-11-27T21:41:05.707538 | 2016-09-02T09:45:50 | 2016-09-02T09:45:50 | 67,210,139 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,183 | /*
* copyright (C) 2010
* The Icecube Collaboration
*
* $Id$
*
* @version $Revision$
* @date $LastChangedDate$
* @author Fabian Kislat <[email protected]> Last changed by: $LastChangedBy$
*/
#ifndef ROOTWRITER_I3ROOTBRANCHWRAPPER_H_INCLUDED
#define ROOTWRITER_I3ROOTBRANCHWRAPPER_H_INCLUDED
#include <icetray/I3PointerTypedefs.h>
#include <boost/shared_ptr.hpp>
#include <cassert>
#include <vector>
I3_FORWARD_DECLARATION(I3TableRow);
struct I3Datatype;
class TBranch;
class TTree;
class I3ROOTBranchWrapper {
public:
I3ROOTBranchWrapper();
I3ROOTBranchWrapper(TTree *tree, unsigned int index, size_t arrayLength = 1,
bool multirow = false);
I3ROOTBranchWrapper(const I3ROOTBranchWrapper &rhs);
virtual ~I3ROOTBranchWrapper();
virtual void Fill(const I3TableRowConstPtr &data) = 0;
const TBranch *Branch() const { return branch_; }
TBranch* Branch() { return branch_; }
protected:
TTree *tree_;
TBranch *branch_;
unsigned int index_;
size_t arrayLength_;
bool multirow_;
void SetBranch(TBranch *branch) { branch_ = branch; }
};
I3_POINTER_TYPEDEFS(I3ROOTBranchWrapper);
#endif // ROOTWRITER_I3ROOTBRANCHWRAPPER_H_INCLUDED
| [
"[email protected]"
] | ||
1f0abe178eaee4e7d2d166c24fd986aa81a9d15a | 3062c8b8c05793b33b699c6800334c7ec07779d1 | /automotive/can/1.0/default/libnl++/include/libnl++/Attributes.h | a438a69932ca1a55be3e9074ae0726fd6f12b74e | [
"Apache-2.0"
] | permissive | crdroidandroid/android_hardware_interfaces | d195f4fbd01ff8db36428667f73faff79a17b6e9 | 3ecf0495de1b1d20d42a0486ac3f742fc2758c5b | refs/heads/13.0 | 2023-08-18T19:30:51.587761 | 2023-08-12T18:01:14 | 2023-08-12T18:01:14 | 103,736,402 | 3 | 31 | null | 2023-07-29T14:54:17 | 2017-09-16T08:08:52 | C++ | UTF-8 | C++ | false | false | 6,585 | h | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <android-base/logging.h>
#include <libnl++/Buffer.h>
#include <libnl++/types.h>
#include <utils/Mutex.h>
#include <map>
namespace android::nl {
/**
* Netlink attribute map.
*
* This is a C++-style, memory safe(r) implementation of linux/netlink.h macros accessing Netlink
* message attributes. The class doesn't own the underlying data, so the instance is valid as long
* as the source buffer is allocated and unmodified.
*
* WARNING: this class is NOT thread-safe (it's safe to be used in multithreaded application, but
* a single instance can only be used by a single thread - the one owning the underlying buffer).
*/
class Attributes : private Buffer<nlattr> {
public:
/**
* Constructs empty attribute map.
*/
Attributes();
/**
* Construct attribute map from underlying buffer.
*
* \param buffer Source buffer pointing at the first attribute.
*/
Attributes(Buffer<nlattr> buffer);
/**
* Checks, if the map contains given attribute type (key).
*
* \param attrtype Attribute type (such as IFLA_IFNAME).
* \return true if attribute is in the map, false otherwise.
*/
bool contains(nlattrtype_t attrtype) const;
/**
* Fetches attribute of a given type by copying it.
*
* While this is quite efficient for simple types, fetching nested attribute creates a new copy
* of child attribute map. This may be costly if you calculate the index for child maps multiple
* times. Examples below.
*
* BAD:
* ```
* const auto flags = msg->attributes.
* get<nl::Attributes>(IFLA_AF_SPEC).
* get<nl::Attributes>(AF_INET6). // IFLA_AF_SPEC index lazy-calculated
* get<uint32_t>(IFLA_INET6_FLAGS); // AF_INET6 index lazy-calculated
* const auto& cacheinfo = msg->attributes.
* get<nl::Attributes>(IFLA_AF_SPEC). // new instance of IFLA_AF_SPEC index
* get<nl::Attributes>(AF_INET6). // IFLA_AF_SPEC index calculated again
* getStruct<ifla_cacheinfo>(IFLA_INET6_CACHEINFO); // AF_INET6 calculated again
* ```
*
* GOOD:
* ```
* const auto inet6 = msg->attributes.
* get<nl::Attributes>(IFLA_AF_SPEC).
* get<nl::Attributes>(AF_INET6);
* const auto flags = inet6.get<uint32_t>(IFLA_INET6_FLAGS); // AF_INET6 index lazy-calculated
* const auto& cache = inet6.getStruct<ifla_cacheinfo>(IFLA_INET6_CACHEINFO); // index reused
* ```
*
* If the attribute doesn't exists, default value of a given type is returned and warning
* spawned into the log. To check for attribute existence, \see contains(nlattrtype_t).
*
* \param attrtype Attribute to fetch.
* \return Attribute value.
*/
template <typename T>
T get(nlattrtype_t attrtype) const {
const auto buffer = getBuffer(attrtype);
if (!buffer.has_value()) {
LOG(WARNING) << "Netlink attribute is missing: " << attrtype;
return T{};
}
return parse<T>(*buffer);
}
/**
* Fetches underlying buffer of a given attribute.
*
* This is a low-level access method unlikely to be useful in most cases. Please consider
* using #get instead.
*
* \param attrtype Attribute to fetch
* \return Attribute buffer.
*/
std::optional<Buffer<nlattr>> getBuffer(nlattrtype_t attrtype) const {
const auto& ind = index();
const auto it = ind.find(attrtype);
if (it == ind.end()) return std::nullopt;
return it->second;
}
/**
* Fetches a reference to a given attribute's data.
*
* This method is intended for arbitrary structures not specialized with get(nlattrtype_t)
* template and slightly more efficient for larger payloads due to not copying its data.
*
* If the attribute doesn't exists, a reference to empty value of a given type is returned and
* warning spawned into the log. To check for attribute existence, \see contains(nlattrtype_t).
*
* \param attrtype Attribute to fetch.
* \return Reference to the attribute's data.
*/
template <typename T>
const T& getStruct(nlattrtype_t attrtype) const {
const auto& ind = index();
const auto it = ind.find(attrtype);
if (it == ind.end()) {
LOG(WARNING) << "Netlink attribute is missing: " << attrtype;
static const T empty = {};
return empty;
}
const auto& [ok, val] = it->second.data<T>().getFirst();
if (!ok) LOG(WARNING) << "Can't fetch structure of size " << sizeof(T);
return val;
}
private:
using Index = std::map<nlattrtype_t, Buffer<nlattr>>;
/**
* Attribute index.
*
* Since this field is not protected by mutex, the use of \see index() dependent methods
* (such as \see get(nlattrtype_t)) is not thread-safe. This is a compromise made based on the
* following assumptions:
*
* 1. Most (or even all) use-cases involve attribute parsing in the same thread as where the
* buffer was allocated. This is partly forced by a dependence of nlmsg lifecycle on the
* underlying data buffer.
*
* 2. Index calculation and access would come with performance penalty never justified in most
* or all use cases (see the previous point). Since Index is not a trivially assignable data
* structure, it's not possible to use it with atomic types only and avoid mutexes.
*/
mutable std::optional<Index> mIndex;
/**
* Lazy-calculate and cache index.
*
* \return Attribute index.
*/
const Index& index() const;
/**
* Parse attribute data into a specific type.
*
* \param buf Raw attribute data.
* \return Parsed data.
*/
template <typename T>
static T parse(Buffer<nlattr> buf);
};
} // namespace android::nl
| [
"[email protected]"
] | |
f8f393f07480cc46212ef1095fcb0fff5b56d9b2 | d630f0c916ae70ac8f4bcdf0640a1f3e95e279af | /FakeMods/src/FakeObject.cc | 0d5d3cdb15534cac565f1f9eac531e9c882e5fc5 | [] | no_license | BambuPhysics/MitPhysics | 63e0f199b1ee1005921c7c96b4b632ff069fa48e | 90bb883f74e8e60c074f9789ef91c1c5c2f8ee45 | refs/heads/master | 2021-01-12T20:38:58.201944 | 2016-10-25T04:19:23 | 2016-10-25T04:19:23 | 38,641,608 | 0 | 7 | null | 2016-10-25T04:19:24 | 2015-07-06T19:38:35 | C++ | UTF-8 | C++ | false | false | 97 | cc | // $Id: $
#include "MitPhysics/FakeMods/interface/FakeObject.h"
ClassImp(mithep::FakeObject)
| [
""
] | |
d4484a61a1cdb27609af908d967da6e8212f5744 | ff28a0226ae36bed47de587bca583dc9c1d3086d | /mips implementation_computer architecture/instruction.cpp | 776705bfb0ca59d79eb4e706ae3da2ed08dae47b | [] | no_license | varunkvn/courseProjects | 22d43bb07a43c8b2757333fd43e2a92fe66fa833 | 623e6b77e212cf15f498fc12a13f0acc8787eb44 | refs/heads/master | 2021-01-10T02:09:11.218892 | 2017-06-02T20:18:51 | 2017-06-02T20:18:51 | 55,561,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,194 | cpp | #include <cassert>
#include "instruction.h"
void Instruction::init(InstructionType _type, RegisterType _arg1, RegisterType _arg2, RegisterType _arg3,
int _immidiate, int _address) {
type = _type;
arg1 = _arg1;
arg2 = _arg2;
arg3 = _arg3;
immidiate = _immidiate;
address = _address;
A = B = 0;
aluOut = 0;
loadMemData = 0;
fetchedAtCycle = 0;
srcCycle1 = 0;
srcCycle2 = 0;
}
Instruction::Instruction() {
init(NOP, R0, R0, R0, 0, 0);
}
Instruction::Instruction(InstructionType _type, int _address) {
init(_type, R0, R0, R0, 0, _address);
}
Instruction::Instruction(InstructionType _type, RegisterType _arg1, int _immidiate, int _address) {
init(_type, _arg1, R0, R0, _immidiate, _address);
}
Instruction::Instruction(InstructionType _type, RegisterType _arg1, RegisterType _arg2,
int _immidiate, int _address) {
init(_type, _arg1, _arg2, R0, _immidiate, _address);
}
Instruction::Instruction(InstructionType _type, RegisterType _arg1, RegisterType _arg2,
RegisterType _arg3, int _address) {
init(_type, _arg1, _arg2, _arg3, 0, _address);
}
Instruction::Instruction(Instruction& inst) {
init(inst.type, inst.arg1, inst.arg2, inst.arg3, inst.immidiate, inst.address);
A = inst.A;
B = inst.B;
aluOut = inst.aluOut;
loadMemData = inst.loadMemData;
fetchedAtCycle = inst.fetchedAtCycle;
srcCycle1 = inst.srcCycle1;
srcCycle2 = inst.srcCycle2;
}
Instruction& Instruction::operator=(Instruction& rhs) {
if (this == &rhs)
return *this;
init(rhs.type, rhs.arg1, rhs.arg2, rhs.arg3, rhs.immidiate, rhs.address);
A = rhs.A;
B = rhs.B;
aluOut = rhs.aluOut;
loadMemData = rhs.loadMemData;
fetchedAtCycle = rhs.fetchedAtCycle;
srcCycle1 = rhs.srcCycle1;
srcCycle2 = rhs.srcCycle2;
return *this;
}
void Instruction::clear() {
init(NOP, R0, R0, R0, 0, 0);
}
// Returns whether dest instruction is data dependent on src
// This should be used for detecting hazard between in ID stage
// instruction and later stage instruction
bool Instruction::isDataDependent(Instruction& src, Instruction& dest) {
return false;
}
Instruction::~Instruction() {
}
| [
"[email protected]"
] | |
4c7974a99a0e86839dd36c6a24c477ff9c769a87 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE762_Mismatched_Memory_Management_Routines/s05/CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_84_bad.cpp | 91b2648da6de070db2fd6cc39325a203cfabac9c | [] | 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,634 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_84_bad.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_delete.label.xml
Template File: sources-sinks-84_bad.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: Allocate data using new []
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using delete []
* BadSink : Deallocate data using delete
* Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_84.h"
namespace CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_84
{
CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_84_bad::CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_84_bad(int64_t * dataCopy)
{
data = dataCopy;
/* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */
data = new int64_t[100];
}
CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_84_bad::~CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_84_bad()
{
/* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
* require a call to delete [] to deallocate the memory */
delete data;
}
}
#endif /* OMITBAD */
| [
"[email protected]"
] | |
6428d1576726413b63a0cafd202dd8806a7a71c3 | d41906f66f2548bae601601d0861e4e3b2a54d1a | /HelloWorldDebugCompile/greeter.h | 2346188aed1e89c18f4182d3ed78d1cb907bedc4 | [] | no_license | c0desBym3ta/GeneralBegginersExamples | a6967851c76c2251a91508177cd66bb0c0f64934 | b3552c7cd0b092e828774ca302d0a6920fecbf4f | refs/heads/master | 2021-01-21T14:44:29.178141 | 2017-06-25T00:22:37 | 2017-06-25T00:22:37 | 95,329,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 197 | h | //
// Created by root on 4/5/17.
//
#ifndef HELLOWORLDDEBUGCOMPILE_GREETER_H
#define HELLOWORLDDEBUGCOMPILE_GREETER_H
class greeter {
greet();
};
#endif //HELLOWORLDDEBUGCOMPILE_GREETER_H
| [
"[email protected]"
] | |
13087b552b3650ab7b61e14f69654763b4194c26 | 7f0c996ece3093205de65b7fb0277f665ad3b171 | /src/chainparams.h | 63aee719077b8ba8606c83f8b28bac252fab2746 | [
"MIT"
] | permissive | 5erendipity/SDX-1.3.3.6 | 5524af9874ad50c3c435cb5838f17eaf4c11ac10 | 5a816dc80c2f2800745386ba0de236cc41cfaa90 | refs/heads/main | 2023-02-21T02:57:25.776040 | 2021-01-24T02:19:18 | 2021-01-24T02:19:18 | 332,348,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,367 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_CHAIN_PARAMS_H
#define BITCOIN_CHAIN_PARAMS_H
#include "bignum.h"
#include "uint256.h"
#include "util.h"
#include <vector>
#define MESSAGE_START_SIZE 4
typedef unsigned char MessageStartChars[MESSAGE_START_SIZE];
class CAddress;
class CBlock;
struct CDNSSeedData {
std::string name, host;
CDNSSeedData(const std::string &strName, const std::string &strHost) : name(strName), host(strHost) {}
};
/**
* CChainParams defines various tweakable parameters of a given instance of the
* Bitcoin system. There are three: the main network on which people trade goods
* and services, the public test network which gets reset from time to time and
* a regression test mode which is intended for private networks only. It has
* minimal difficulty to ensure that blocks can be found instantly.
*/
class CChainParams
{
public:
enum Network {
MAIN,
TESTNET,
REGTEST,
MAX_NETWORK_TYPES
};
enum Base58Type {
PUBKEY_ADDRESS,
SCRIPT_ADDRESS,
SECRET_KEY,
STEALTH_ADDRESS,
EXT_PUBLIC_KEY,
EXT_SECRET_KEY,
EXT_KEY_HASH,
EXT_ACC_HASH,
EXT_PUBLIC_KEY_BTC,
EXT_SECRET_KEY_BTC,
MAX_BASE58_TYPES
};
const uint256& HashGenesisBlock() const { return hashGenesisBlock; }
const MessageStartChars& MessageStart() const { return pchMessageStart; }
const std::vector<unsigned char>& AlertKey() const { return vAlertPubKey; }
int GetDefaultPort() const { return nDefaultPort; }
const bool IsProtocolV2(int nHeight) const { return nHeight > nFirstPosv2Block; }
const CBigNum& ProofOfWorkLimit() const { return bnProofOfWorkLimit; }
const CBigNum& ProofOfStakeLimit(int nHeight) const { return IsProtocolV2(nHeight) ? bnProofOfStakeLimitV2 : bnProofOfStakeLimit; }
virtual const CBlock& GenesisBlock() const = 0;
virtual bool RequireRPCPassword() const { return true; }
const std::string& DataDir() const { return strDataDir; }
virtual Network NetworkID() const = 0;
const std::vector<CDNSSeedData>& DNSSeeds() const { return vSeeds; }
const std::vector<unsigned char> &Base58Prefix(Base58Type type) const { return base58Prefixes[type]; }
virtual const std::vector<CAddress>& FixedSeeds() const = 0;
std::string NetworkIDString() const { return strNetworkID; }
int RPCPort() const { return nRPCPort; }
int BIP44ID() const { return nBIP44ID; }
int LastPOWBlock() const { return nLastPOWBlock; }
int LastFairLaunchBlock() const { return nLastFairLaunchBlock; }
int64_t GetProofOfWorkReward(int nHeight, int64_t nFees) const;
int64_t GetProofOfStakeReward(int64_t nCoinAge, int64_t nFees) const;
protected:
CChainParams() {};
uint256 hashGenesisBlock;
MessageStartChars pchMessageStart;
// Raw pub key bytes for the broadcast alert signing key.
std::vector<unsigned char> vAlertPubKey;
std::string strNetworkID;
int nDefaultPort;
int nRPCPort;
int nBIP44ID;
int nFirstPosv2Block;
CBigNum bnProofOfWorkLimit;
CBigNum bnProofOfStakeLimit;
CBigNum bnProofOfStakeLimitV2;
std::string strDataDir;
std::vector<CDNSSeedData> vSeeds;
std::vector<unsigned char> base58Prefixes[MAX_BASE58_TYPES];
int nLastPOWBlock;
int nLastFairLaunchBlock;
};
/**
* Return the currently selected parameters. This won't change after app startup
* outside of the unit tests.
*/
const CChainParams &Params();
/**
* Return the testnet parameters.
*/
const CChainParams &TestNetParams();
/**
* Return the mainnet parameters.
*/
const CChainParams &MainNetParams();
/** Sets the params returned by Params() to those for the given network. */
void SelectParams(CChainParams::Network network);
/**
* Looks for -regtest or -testnet and then calls SelectParams as appropriate.
* Returns false if an invalid combination is given.
*/
bool SelectParamsFromCommandLine();
inline bool TestNet() {
// Note: it's deliberate that this returns "false" for regression test mode.
return Params().NetworkID() == CChainParams::TESTNET;
}
#endif
| [
"[email protected]"
] | |
1a5866af10a32f1c3011c268535f9f54bb0b1c14 | 60472fe9ec8d7226641ffc4e69c5941105c30175 | /EngineLuke/src/ML_ENGINE/ML_ENGINE/Test/LinearRegressionTest.h | e168c8dc2bc28fad06daf4cdf28ac3cbc1b55e1c | [
"MIT"
] | permissive | Sandy4321/team.luke | 35abd84e06250c383eedbf787eccc18589096778 | 6354d8237227276316a8f1e4bb10486a9ab968bf | refs/heads/master | 2021-01-21T06:30:24.589220 | 2016-12-02T23:15:16 | 2016-12-02T23:15:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | h | #pragma once
#include "ML\Dataframe\Dataframe.h"
#include "ML\Regression\LinearRegression.h"
class LinearRegressionTest
{
public:
LinearRegressionTest(Dataframe *_dataframe);
~LinearRegressionTest(void);
void Answer(std::vector<Equation>& bestfits, std::vector<double>& errors, size_t& max, size_t& min);
private:
Dataframe *m_Dataframe;
}; | [
"[email protected]"
] | |
6d4436b773b5fc19f7a6c64de3041d95fa5bc1ba | 1a59395cea911fe01688ca42a84f2661e42a0b9d | /Tutorial07/Tutorial07.cpp | 116ff15590450e91e7cb9a4c891691b18489498d | [] | no_license | RamsesGA/Repositorio_Graficas | cbf93d557b61d298a466c436b58dcfebbb9ebbe4 | d075090bff415d0a2530a88c8946267d451209e6 | refs/heads/master | 2020-12-11T19:23:06.431970 | 2020-08-27T00:54:29 | 2020-08-27T00:54:29 | 233,924,707 | 1 | 1 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 59,892 | cpp | #include "resource.h"
#include "Encabezados/Defines.h"
///
/// Ramses´s libraries
///
#include "Camera.h"
#include "FirstCamera.h"
#include <fstream>
#include <iostream>
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <vector>
#include "Encabezados/ClaseDevice.h"
#include "Encabezados/ClaseDeviceContext.h"
#include "Encabezados/ClaseSwapChain.h"
#include "Encabezados/ClaseRenderTargetView.h"
#include "Encabezados/ClaseRenderTarget.h"
#include "Encabezados/ClaseSampleState.h"
#include "Encabezados/ClaseDepthStencil.h"
#include "Encabezados/ClaseViewport.h"
#include "Encabezados/ClaseShader.h"
#include "Encabezados/ClaseVertexBuffer.h"
#include "Encabezados/ClaseTexture2D.h"
#include "imgui/imgui.h"
#include "imgui/imgui_impl_win32.h"
#include "imgui/imgui_impl_dx11.h"
//API
#include "Encabezados/GraphicApi.h"
#include "Encabezados/SceneManager.h"
#include "Encabezados/ClaseOpenGL.h"
//Libreria Pass
#include "Encabezados/CPass.h"
//--------------------------------------------------------------------------------------
extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
/// Global Variables
#ifdef D3D11
/// in pixel shader derived from shader class
//ID3D11PixelShader* g_pPixelShader = NULL;
/// in material class or shader Resources
ID3D11ShaderResourceView* g_pTextureRV = NULL;
ID3D11ShaderResourceView* G_InactiveSRV = NULL;
#endif
HINSTANCE g_hInst = NULL;
HWND g_hWnd = NULL;
mathfu::float4x4 g_World;
mathfu::float4x4 g_Projection;
mathfu::float4 g_vMeshColor(0.7f, 0.7f, 0.7f, 1.0f);
/// Ramses´s global variables
ClaseDevice CDev;
ClaseDeviceContext CDevCont;
ClaseSwapChain CSwap;
ClaseRenderTargetView CRendTarView;
RenderTarget CRendTar;
ClaseSampleState CSampleS;
ClaseDepthStencil CDepthStencilView;
ClaseViewport CView;
ClaseShader CShader;
ClaseBuffer FCNeverChange;
ClaseBuffer FCOnResize;
ClaseBuffer FCChangeEveryFrame;
ClaseVertexBuffer CVertexBuffer;
ClaseVertexBuffer CIndexBuffer;
FirstCamera FreeCamera;
FirstCamera FPSCamera;
ClaseBuffer FPCNeverChange;
ClaseBuffer FPCOnResize;
ClaseBuffer FPCChangeEveryFrame;
ClaseTextura2D InactiveTexture;
ClaseTextura2D G_DepthStencil;
ClaseRenderTargetView InactiveRTV;
Camera* MainCamera = NULL;
Camera* SecondCamera = NULL;
Camera CamaraLibre;
Camera CamaraPrimeraPersona;
///
/// API
///
SCENEMANAGER G_SceneManager;
SCENEMANAGER g_screenAligneQuadSM;
SCENEMANAGER g_skyboxSM;
GraphicApi G_GraphicApi;
#if defined(D3D11)
ID3D11Device* ptrDEV;
IDXGISwapChain* ptrSwap;
ID3D11DeviceContext* ptrDevCont;
#endif
int SwitchCamera = -1;
UINT width;
UINT height;
//Nuevas variables, sexto cuatrimestrte :D
mathfu::float4 g_DirLight = { -1.0f, 0.0f, 0.0f, 0.0f };
mathfu::float4 g_lightPointPos = { -1.0f, -1.0f, -1.0f, 0.0f };
mathfu::float4 g_lightPointAt = {1.0f, 0.0f, 0.0f, 0.0f};
ClaseBuffer g_Lights;
Lights g_sLights;
ClaseShader g_pixelShader;
//Animaciones
ClaseBuffer g_boneBuffer;
long long g_startTime;
#ifdef D3D11
Assimp::Importer* g_myImporter = new Assimp::Importer();
const aiScene* g_myScene;
#endif
//CPass
CPass g_pass; //Buffer
CPass g_superSamplingAmbientOclussion;
CPass g_skyBox;
//Faltan mas pases por implementar
//Buffers
ClaseBuffer g_superSamplingAmbientOclussionBuffer;
/// OpenGl variables
unsigned int g_ColorShaderID;
ClaseOpenGL g_OpenGlObj;
/// Function for resize in DIRECTX
void Resize(){
#ifdef D3D11
if (CDevCont.g_pImmediateContextD3D11 != nullptr) {
/// Get new window dimensions
RECT rc;
GetClientRect(g_hWnd, &rc);
UINT width = rc.right - rc.left;
UINT height = rc.bottom - rc.top;
/// Regenerate world matrix as identity
g_World = g_World.Identity();
///Set w and h for camera
MainCamera->SetHeight(height);
MainCamera->SetWidht(width);
/// Update projection matrix with new params
MainCamera->UpdateVM();
/// Update CB
CBChangeOnResize cbChangesOnResize;
cbChangesOnResize.mProjection = MainCamera->GetProjection();
ptrDevCont->UpdateSubresource(MainCamera->g_pCBChangeOnResizeCamera.m_BufferD3D11, 0, NULL, &cbChangesOnResize, 0, 0);
/// inactive camera
SecondCamera->SetHeight(height);
SecondCamera->SetWidht(width);
SecondCamera->UpdateVM();
CBChangeOnResize cbChangesOnResize2;
cbChangesOnResize2.mProjection = SecondCamera->GetProjection();
ptrDevCont->UpdateSubresource(SecondCamera->g_pCBChangeOnResizeCamera.m_BufferD3D11, 0, NULL, &cbChangesOnResize2, 0, 0);
if (ptrSwap) {
HRESULT h;
/// Release inactive camera texture, SRV and RTV
InactiveTexture.m_TextureD3D11->Release();
G_InactiveSRV->Release();
InactiveRTV.g_pRenderTargetViewD3D11->Release();
/// Resize inactive camera texture
Texture2Desc TD;
ZeroMemory(&TD, sizeof(TD));
TD.Width = width;
TD.Height = height;
TD.MipLevels = TD.ArraySize = 1;
TD.Format = FORMAT_R8G8B8A8_UNORM;
TD.SampleDesc.My_Count = 1;
TD.Usage = USAGE_DEFAULT;
TD.BindFlags = 8 | 32; // D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
TD.CPUAccessFlags = 65536; //D3D11_CPU_ACCESS_WRITE;
TD.MiscFlags = 0;
InactiveTexture.Init(TD);
h = ptrDEV->CreateTexture2D(&InactiveTexture.m_TextDescD3D11, NULL, &InactiveTexture.m_TextureD3D11);
RenderTargetViewDesc RTVD;
ZeroMemory(&RTVD, sizeof(RTVD));
RTVD.Format = TD.Format;
RTVD.ViewDimension = RTV_DIMENSION_TEXTURE2D;
RTVD.Texture2D.My_MipSlice = 0;
InactiveRTV.Init(RTVD);
h = ptrDEV->CreateRenderTargetView(InactiveTexture.m_TextureD3D11, &InactiveRTV.m_renderTVD3D11, &InactiveRTV.g_pRenderTargetViewD3D11);
D3D11_SHADER_RESOURCE_VIEW_DESC SRV;
ZeroMemory(&SRV, sizeof(SRV));
SRV.Format = (DXGI_FORMAT)TD.Format;
SRV.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
SRV.Texture2D.MostDetailedMip = 0;
SRV.Texture2D.MipLevels = 1;
h = ptrDEV->CreateShaderResourceView(InactiveTexture.m_TextureD3D11, &SRV, &G_InactiveSRV);
/// Camara activa
CDevCont.g_pImmediateContextD3D11->OMSetRenderTargets(0, 0, 0);
CRendTarView.g_pRenderTargetViewD3D11->Release();
h = ptrSwap->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
ClaseBuffer tempBack;
h = ptrSwap->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&tempBack.m_BufferD3D11);
h = ptrDEV->CreateRenderTargetView(tempBack.m_BufferD3D11, NULL, &CRendTarView.g_pRenderTargetViewD3D11);
tempBack.m_BufferD3D11->Release();
Texture2Desc DepthDesc;
ZeroMemory(&DepthDesc, sizeof(DepthDesc));
DepthDesc.Width = width;
DepthDesc.Height = height;
DepthDesc.MipLevels = 1;
DepthDesc.ArraySize = 1;
DepthDesc.Format = FORMAT_D24_UNORM_S8_UINT;
DepthDesc.SampleDesc.My_Count = 1;
DepthDesc.SampleDesc.My_Quality = 0;
DepthDesc.Usage = USAGE_DEFAULT;
DepthDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
DepthDesc.CPUAccessFlags = 0;
DepthDesc.MiscFlags = 0;
G_DepthStencil.Init(DepthDesc);
h = ptrDEV->CreateTexture2D(&G_DepthStencil.m_TextDescD3D11, NULL, &G_DepthStencil.m_TextureD3D11);
DepthStencilViewDesc DSVD;
ZeroMemory(&DSVD, sizeof(DSVD));
DSVD.Format = CDepthStencilView.m_DepthDesc.Format;
DSVD.ViewDimension = DSV_DIMENSION_TEXTURE2D;
DSVD.Texture2D.My_MipSlice = 0;
CDepthStencilView.g_pDepthStencilViewD3D11->Release();
CDepthStencilView.Init(DSVD);
h = ptrDEV->CreateDepthStencilView(G_DepthStencil.m_TextureD3D11, &CDepthStencilView.descDepthViewD3D11, &CDepthStencilView.g_pDepthStencilViewD3D11);
ptrDevCont->OMSetRenderTargets(1, &CRendTarView.g_pRenderTargetViewD3D11, CDepthStencilView.g_pDepthStencilViewD3D11);
ViewportDesc VD;
ZeroMemory(&VD, sizeof(VD));
VD.Width = width;
VD.Height = height;
VD.MinDepth = 0.f;
VD.MaxDepth = 1.f;
VD.TopLeftX = 0;
VD.TopLeftY = 0;
ClaseViewport ViewPort;
ViewPort.Init(VD);
ptrDevCont->RSSetViewports(1, &ViewPort.vpD3D11);
}
}
#endif
}
/// Function to initialize cameras
void InitCameras() {
CameraDescriptor FirstCamera;
FirstCamera.s_At = { 10,0,0 };
FirstCamera.s_Eye = { 0,0,0 };
FirstCamera.s_Up = { 0,1,0 };
FirstCamera.s_Far = 1000;
FirstCamera.s_Near = 0.01;
#ifdef D3D11
FirstCamera.s_FoV = XM_PIDIV4;
#endif
FirstCamera.s_Height = height;
FirstCamera.s_Widht = width;
FreeCamera.Init(FirstCamera);
FPSCamera.Init(FirstCamera);
MainCamera = &FPSCamera;
SecondCamera = &FreeCamera;
}
/// Function to activate the console
void activateConsole()
{
/// Create a console for this application
AllocConsole();
/// Get STDOUT handle
HANDLE ConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
int SystemOutput = _open_osfhandle(intptr_t(ConsoleOutput), _O_TEXT);
FILE* COutputHandle = _fdopen(SystemOutput, "w");
/// Get STDERR handle
HANDLE ConsoleError = GetStdHandle(STD_ERROR_HANDLE);
int SystemError = _open_osfhandle(intptr_t(ConsoleError), _O_TEXT);
FILE* CErrorHandle = _fdopen(SystemError, "w");
/// Get STDIN handle
HANDLE ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
int SystemInput = _open_osfhandle(intptr_t(ConsoleInput), _O_TEXT);
FILE* CInputHandle = _fdopen(SystemInput, "r");
/// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well
std::ios::sync_with_stdio(true);
/// Redirect the CRT standard input, output, and error handles to the console
freopen_s(&CInputHandle, "CONIN$", "r", stdin);
freopen_s(&COutputHandle, "CONOUT$", "w", stdout);
freopen_s(&CErrorHandle, "CONOUT$", "w", stderr);
/// Clear the error state for each of the C++ standard stream objects. We need to do this, as attempts to access the standard streams before they refer to a valid target will cause the
/// iostream objects to enter an error state. In versions of Visual Studio after 2005, this seems to always occur during startup regardless of whether anything has been read from or written to
/// the console or not.
std::wcout.clear();
std::cout.clear();
std::wcerr.clear();
std::cerr.clear();
std::wcin.clear();
std::cin.clear();
}
/// Forward declarations
///
///
HRESULT InitWindow(HINSTANCE hInstance, int nCmdShow);
HRESULT InitDevice();
void CleanupDevice();
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void Render();
long long GetCurrentTimeMS();
float GetRunnningTime();
//void Update();
/// Entry point to the program. Initializes everything and goes into a message processing, loop. Idle time is used to render the scene.
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
if (FAILED(InitWindow(hInstance, nCmdShow)))
return 0;
#ifdef D3D11
if (FAILED(InitDevice()))
{
CleanupDevice();
return 0;
}
#endif // D3D11
/// Main message loop
MSG msg = { 0 };
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
#ifdef D3D11
//-----------------------------------
ImVec2 ScreenImGui(200, 200);
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
//ImGui::Begin("Change Cameras");
//if (ImGui::Button("Click"))
//{
// Camera* Temporal = SecondCamera;
// SecondCamera = MainCamera;
// MainCamera = Temporal;
//}
//ImGui::End();
//-----------------------------------
//ImGui::Begin("Shader from Camera");
//ImGui::Image(G_InactiveSRV, ScreenImGui);
//ImGui::GetIO().FontGlobalScale;
//ImGui::End();
//-----------------------------------
//ImGui::Begin("Directional Light");
//ImGui::SliderFloat("Direction X", &g_DirLight.x, -1, 1);
//ImGui::SliderFloat("Direction Y", &g_DirLight.y, -1, 1);
//ImGui::SliderFloat("Direction Z", &g_DirLight.z, -1, 1);
//ImGui::End();
//-----------------------------------
//ImGui::Begin("Position Light");
//ImGui::SliderFloat("Position X", &g_lightPointPos.x, -1000, 1000);
//ImGui::SliderFloat("Position Y", &g_lightPointPos.y, -1000, 1000);
//ImGui::SliderFloat("Position Z", &g_lightPointPos.z, -1000, 1000);
//ImGui::End();
//-----------------------------------
//ImGui::Begin("Att Light");
//ImGui::SliderFloat("Atenuacion X", &g_lightPointAt.x, 0.01, 2);
//ImGui::End();
//-----------------------------------
ImGui::Begin("Pase - GBuffer");
for (int i = 0; i < g_pass.m_saveTextures2D.size(); i++) {
ImGui::Image(g_pass.m_saveTextures2D[i], ScreenImGui);
}
ImGui::End();
//-----------------------------------
ImGui::Begin("Pase - SSAO");
for (int i = 0; i < g_superSamplingAmbientOclussion.m_saveTextures2D.size(); i++) {
ImGui::Image(g_superSamplingAmbientOclussion.m_saveTextures2D[i], ScreenImGui);
}
ImGui::End();
//-----------------------------------
ImGui::Begin("Pase - Skybox");
for (int i = 0; i < g_skyBox.m_saveTextures2D.size(); i++) {
ImGui::Image(g_skyBox.m_saveTextures2D[i], ScreenImGui);
}
ImGui::End();
//-----------------------------------
Render();
#endif // D3D11
}
}
CleanupDevice();
//LevelMap("Mapa.txt");
return (int)msg.wParam;
}
/// Register class and create window
HRESULT InitWindow(HINSTANCE hInstance, int nCmdShow){
activateConsole();
#ifdef D3D11
//Register class
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_TUTORIAL1);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = L"TutorialWindowClass";
wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_TUTORIAL1);
if (!RegisterClassEx(&wcex))
return E_FAIL;
// Create window
g_hInst = hInstance;
RECT rc = { 0, 0, 800, 800 };
AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
g_hWnd = CreateWindow(L"TutorialWindowClass", L"Direct3D 11 Tutorial 7", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance,
NULL);
if (!g_hWnd)
return E_FAIL;
ShowWindow(g_hWnd, nCmdShow);
#endif // D3D11
#ifdef OPENGL
g_OpenGlObj.WindowGLFW();
#endif // OPENGL
return S_OK;
}
/// Helper for compiling shaders with D3DX11
#ifdef D3D11
HRESULT CompileShaderFromFile(WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut)
{
HRESULT hr = S_OK;
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
#if defined( DEBUG ) || defined( _DEBUG )
/// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
/// Setting this flag improves the shader debugging experience, but still allows the shaders to be optimized and to run exactly the way they will run in
/// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif
/// Un buffer que va a contener el resultado del shader.
ID3DBlob* pErrorBlob;
hr = D3DX11CompileFromFile(szFileName, NULL, NULL, szEntryPoint, szShaderModel,
dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL);
if (FAILED(hr))
{
if (pErrorBlob != NULL)
OutputDebugStringA((char*)pErrorBlob->GetBufferPointer());
if (pErrorBlob) pErrorBlob->Release();
return hr;
}
if (pErrorBlob) pErrorBlob->Release();
return S_OK;
}
#endif
/// Dentro de la interfaz y en ni desc del input layout debo pedir el blob TO
#ifdef D3D11
HRESULT CreateInputLayoutDescFromVertexShaderSignature(ID3DBlob* pShaderBlob, ID3D11Device* pD3DDevice, ID3D11InputLayout** pInputLayout)
{
/// Reflect shader info
ID3D11ShaderReflection* pVertexShaderReflection = NULL;
if (FAILED(D3DReflect(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pVertexShaderReflection)))
{
return S_FALSE;
}
/// Get shader info
D3D11_SHADER_DESC shaderDesc;
pVertexShaderReflection->GetDesc(&shaderDesc);
/// Read input layout description from shader info
std::vector<D3D11_INPUT_ELEMENT_DESC> inputLayoutDesc;
int offset = 0;
for (int i = 0; i < shaderDesc.InputParameters; i++)
{
D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
pVertexShaderReflection->GetInputParameterDesc(i, ¶mDesc);
/// Fill out input element desc
D3D11_INPUT_ELEMENT_DESC elementDesc;
elementDesc.SemanticName = paramDesc.SemanticName;
elementDesc.SemanticIndex = paramDesc.SemanticIndex;
elementDesc.InputSlot = 0;
elementDesc.AlignedByteOffset = offset;
elementDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
elementDesc.InstanceDataStepRate = 0;
/// Determine DXGI format
if (paramDesc.Mask == 1)
{
if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32_UINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32_SINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32_FLOAT;
}
else if (paramDesc.Mask <= 3)
{
if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32_UINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32_SINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32_FLOAT;
}
else if (paramDesc.Mask <= 15)
{
if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_UINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_SINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT; offset += 12;
}
else if (paramDesc.Mask <= 7)
{
if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
}
/// save element desc
inputLayoutDesc.push_back(elementDesc);
}
/// Try to create Input Layout
HRESULT hr = pD3DDevice->CreateInputLayout(&inputLayoutDesc[0], inputLayoutDesc.size(), pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), pInputLayout);
/// Free allocation shader reflection memory
pVertexShaderReflection->Release();
return hr;
}
#endif
#ifdef D3D11
HRESULT CompileShaders(WCHAR* _shaderfile, const char* _vertexEntryPoint, const char* _pixelEntryPoint, ClaseShader& _shader){
//Compilar el vertex shader
HRESULT hr = CompileShaderFromFile(_shaderfile, _vertexEntryPoint, "vs_4_0", &_shader.m_pVSBlobD3D11);
if (FAILED(hr)){
MessageBox(NULL,L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
//Creamos el vertex shader nuevo
hr = CDev.g_pd3dDeviceD3D11->CreateVertexShader(_shader.m_pVSBlobD3D11->GetBufferPointer(), _shader.m_pVSBlobD3D11->GetBufferSize(), NULL, &_shader.g_pVertexShaderD3D11);
if (FAILED(hr)){
_shader.m_pVSBlobD3D11->Release();
return hr;
}
//Creamos el input layout del vertex shader
hr = CreateInputLayoutDescFromVertexShaderSignature(_shader.m_pVSBlobD3D11, CDev.g_pd3dDeviceD3D11, &_shader.LayoutD3D11);
if (FAILED(hr)) {
return hr;
}
// Compile the pixel shader
hr = CompileShaderFromFile(_shaderfile, _pixelEntryPoint, "ps_4_0", &_shader.pPSBlob);
if (FAILED(hr)){
MessageBox(NULL,L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
// Create the pixel shader
hr = CDev.g_pd3dDeviceD3D11->CreatePixelShader(_shader.pPSBlob->GetBufferPointer(), _shader.pPSBlob->GetBufferSize(), NULL, &_shader.pPixelShader);
_shader.pPSBlob->Release();
if (FAILED(hr)) {
return hr;
}
}
#endif
/// Create Direct3D device and swap chain
#ifdef D3D11
HRESULT InitDevice()
{
HRESULT hr = S_OK;
RECT rc;
GetClientRect(g_hWnd, &rc);
width = rc.right - rc.left;
height = rc.bottom - rc.top;
UINT createDeviceFlags = 0;
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE,
/// Work in combination
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = ARRAYSIZE(driverTypes);
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
UINT numFeatureLevels = ARRAYSIZE(featureLevels);
/// Mis movimientos
DeviceDescriptor objDev;
objDev.g_driverType = DRIVER_TYPE_NULL;
CDev.g_pd3dDeviceD3D11 = NULL;
objDev.s_createDeviceFlags = 2;
objDev.s_numFeatureLevels = 3;
CDev.Init(objDev);
SwapChainDescriptor objSd;
objSd.BufferCount = 1;
objSd.BufferDesc.My_Width = width;
objSd.BufferDesc.My_Height = height;
objSd.BufferDesc.My_Format = FORMAT_R8G8B8A8_UNORM;
objSd.BufferDesc.My_RefreshRate.My_Numerator = 60;
objSd.BufferDesc.My_RefreshRate.My_Denominator = 1;
objSd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
objSd.OutputWindow = g_hWnd;
objSd.SampleDesc.My_Count = 1;
objSd.SampleDesc.My_Quality = 0;
objSd.Windowed = TRUE;
CSwap.Init(objSd);
for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
{
CDev.g_driverTypeD3D11 = driverTypes[driverTypeIndex];
hr = D3D11CreateDeviceAndSwapChain(NULL, CDev.g_driverTypeD3D11, NULL, objDev.s_createDeviceFlags, featureLevels, objDev.s_numFeatureLevels,
D3D11_SDK_VERSION, &CSwap.sdD3D11, &CSwap.g_pSwapChainD3D11, &CDev.g_pd3dDeviceD3D11, &CDev.g_featureLevelD3D11, &CDevCont.g_pImmediateContextD3D11);
if (SUCCEEDED(hr))
break;
}
ptrDEV = static_cast<ID3D11Device*>(CDev.GetDev());
ptrDevCont = static_cast<ID3D11DeviceContext*>(CDevCont.GetDevCont());
ptrSwap = static_cast<IDXGISwapChain*>(CSwap.GetSwap());
if (FAILED(hr))
return hr;
/// Create a render target view
ID3D11Texture2D* pBackBuffer = NULL;
hr = CSwap.g_pSwapChainD3D11->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
if (FAILED(hr))
return hr;
hr = CDev.g_pd3dDeviceD3D11->CreateRenderTargetView(pBackBuffer, NULL, &CRendTarView.g_pRenderTargetViewD3D11);
pBackBuffer->Release();
if (FAILED(hr))
return hr;
/// Create depth stencil texture
D3D11_TEXTURE2D_DESC descDepth;
ZeroMemory(&descDepth, sizeof(descDepth));
descDepth.Width = width;
descDepth.Height = height;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
descDepth.SampleDesc.Count = 1;
descDepth.SampleDesc.Quality = 0;
descDepth.Usage = D3D11_USAGE_DEFAULT;
descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;
hr = CDev.g_pd3dDeviceD3D11->CreateTexture2D(&descDepth, NULL, &CRendTar.g_pDepthStencilD3D11);
if (FAILED(hr))
return hr;
/// Create the depth stencil view
D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
ZeroMemory(&descDSV, sizeof(descDSV));
descDSV.Format = descDepth.Format;
descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
descDSV.Texture2D.MipSlice = 0;
hr = CDev.g_pd3dDeviceD3D11->CreateDepthStencilView(CRendTar.g_pDepthStencilD3D11, &descDSV, &CDepthStencilView.g_pDepthStencilViewD3D11);
if (FAILED(hr))
return hr;
CDevCont.g_pImmediateContextD3D11->OMSetRenderTargets(1, &CRendTarView.g_pRenderTargetViewD3D11, CDepthStencilView.g_pDepthStencilViewD3D11);
/// Setup the viewport
ViewportDesc vp2;
vp2.Width = (FLOAT)width;
vp2.Height = (FLOAT)height;
vp2.MinDepth = 0.0f;
vp2.MaxDepth = 1.0f;
vp2.TopLeftX = 0;
vp2.TopLeftY = 0;
CView.Init(vp2);
CDevCont.g_pImmediateContextD3D11->RSSetViewports(1, &CView.vpD3D11);
//Definimos la estructura
PassDX sPassDx;
//-----------------------------------------------------------------------------------------------------------------------
/// Compile the vertex shader (PROXIMAMENTE MÁS VECES)
hr = CompileShaderFromFile(L"ShaderGbuffer.fx", "vs_main", "vs_4_0", &CShader.m_pVSBlobD3D11);
if (FAILED(hr))
{
MessageBox(NULL,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
/// Create the vertex shader
hr = CDev.g_pd3dDeviceD3D11->CreateVertexShader(CShader.m_pVSBlobD3D11->GetBufferPointer(), CShader.m_pVSBlobD3D11->GetBufferSize(), NULL, &CShader.g_pVertexShaderD3D11);
if (FAILED(hr))
{
CShader.m_pVSBlobD3D11->Release();
return hr;
}
/// Define the input layout
/// Create input layout from compiled VS
hr = CreateInputLayoutDescFromVertexShaderSignature(CShader.m_pVSBlobD3D11, CDev.g_pd3dDeviceD3D11, &CShader.LayoutD3D11);
if (FAILED(hr))
return hr;
/// Create the input layout
/// Set the input layout
CDevCont.g_pImmediateContextD3D11->IASetInputLayout(CShader.LayoutD3D11);
//-----------------------------------------------------------------------------------------------------------------------
/// Compile the pixel shader
//ID3DBlob* pPSBlob = NULL;
hr = CompileShaderFromFile(L"ShaderGbuffer.fx", "ps_main", "ps_4_0", &g_pixelShader.pPSBlob);
if (FAILED(hr))
{
MessageBox(NULL,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
/// Create the pixel shader
hr = CDev.g_pd3dDeviceD3D11->CreatePixelShader(g_pixelShader.pPSBlob->GetBufferPointer(), g_pixelShader.pPSBlob->GetBufferSize(), NULL, &g_pixelShader.pPixelShader);
g_pixelShader.pPSBlob->Release();
if (FAILED(hr))
return hr;
/// Create vertex buffer
SimpleVertex vertices[] =
{
{ mathfu::float3(-1.0f, 1.0f, -1.0f), mathfu::float2(0.0f, 0.0f) },
{ mathfu::float3(1.0f, 1.0f, -1.0f), mathfu::float2(1.0f, 0.0f) },
{ mathfu::float3(1.0f, 1.0f, 1.0f), mathfu::float2(1.0f, 1.0f) },
{ mathfu::float3(-1.0f, 1.0f, 1.0f), mathfu::float2(0.0f, 1.0f) },
{ mathfu::float3(-1.0f, -1.0f, -1.0f),mathfu::float2(0.0f, 0.0f) },
{ mathfu::float3(1.0f, -1.0f, -1.0f), mathfu::float2(1.0f, 0.0f) },
{ mathfu::float3(1.0f, -1.0f, 1.0f), mathfu::float2(1.0f, 1.0f) },
{ mathfu::float3(-1.0f, -1.0f, 1.0f), mathfu::float2(0.0f, 1.0f) },
{ mathfu::float3(-1.0f, -1.0f, 1.0f), mathfu::float2(0.0f, 0.0f) },
{ mathfu::float3(-1.0f, -1.0f, -1.0f),mathfu::float2(1.0f, 0.0f) },
{ mathfu::float3(-1.0f, 1.0f, -1.0f), mathfu::float2(1.0f, 1.0f) },
{ mathfu::float3(-1.0f, 1.0f, 1.0f), mathfu::float2(0.0f, 1.0f) },
{ mathfu::float3(1.0f, -1.0f, 1.0f), mathfu::float2(0.0f, 0.0f) },
{ mathfu::float3(1.0f, -1.0f, -1.0f), mathfu::float2(1.0f, 0.0f) },
{ mathfu::float3(1.0f, 1.0f, -1.0f), mathfu::float2(1.0f, 1.0f) },
{ mathfu::float3(1.0f, 1.0f, 1.0f), mathfu::float2(0.0f, 1.0f) },
{ mathfu::float3(-1.0f, -1.0f, -1.0f),mathfu::float2(0.0f, 0.0f) },
{ mathfu::float3(1.0f, -1.0f, -1.0f), mathfu::float2(1.0f, 0.0f) },
{ mathfu::float3(1.0f, 1.0f, -1.0f), mathfu::float2(1.0f, 1.0f) },
{ mathfu::float3(-1.0f, 1.0f, -1.0f), mathfu::float2(0.0f, 1.0f) },
{ mathfu::float3(-1.0f, -1.0f, 1.0f), mathfu::float2(0.0f, 0.0f) },
{ mathfu::float3(1.0f, -1.0f, 1.0f), mathfu::float2(1.0f, 0.0f) },
{ mathfu::float3(1.0f, 1.0f, 1.0f), mathfu::float2(1.0f, 1.0f) },
{ mathfu::float3(-1.0f, 1.0f, 1.0f), mathfu::float2(0.0f, 1.0f) },
};
BufferDescriptor bd2;
ZeroMemory(&bd2, sizeof(bd2));
bd2.Usage = USAGE_DEFAULT;
bd2.ByteWidth = sizeof(SimpleVertex) * 24;
bd2.BindFlags = BIND_VERTEX_BUFFER;
bd2.CPUAccessFlags = 0;
SUBRESOURCE_DATA initData2;
ZeroMemory(&initData2, sizeof(initData2));
initData2.My_pSysMem = vertices;
CVertexBuffer.Init(initData2, bd2);
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&CVertexBuffer.m_Buffer.m_BufferDescD3D11, &CVertexBuffer.m_SubDataD3D11, &CVertexBuffer.m_Buffer.m_BufferD3D11);
if (FAILED(hr))
return hr;
/// Set vertex buffer
UINT stride = sizeof(SimpleVertex);
UINT offset = 0;
CDevCont.g_pImmediateContextD3D11->IASetVertexBuffers(0, 1, &CVertexBuffer.m_Buffer.m_BufferD3D11, &stride, &offset);
/// Create index buffer
WORD indices[] =
{
3,1,0,
2,1,3,
6,4,5,
7,4,6,
11,9,8,
10,9,11,
14,12,13,
15,12,14,
19,17,16,
18,17,19,
22,20,21,
23,20,22
};
bd2.Usage = USAGE_DEFAULT;
bd2.ByteWidth = sizeof(WORD) * 36;
bd2.BindFlags = BIND_INDEX_BUFFER;
bd2.CPUAccessFlags = 0;
initData2.My_pSysMem = indices;
CIndexBuffer.Init(initData2, bd2);
/// Set index buffer
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&CIndexBuffer.m_Buffer.m_BufferDescD3D11, &CIndexBuffer.m_SubDataD3D11, &CIndexBuffer.m_Buffer.m_BufferD3D11);
if (FAILED(hr))
return hr;
/// Set index bufferUINT stride = sizeof(SimpleVertex);
CDevCont.g_pImmediateContextD3D11->IASetIndexBuffer(CIndexBuffer.m_Buffer.m_BufferD3D11, DXGI_FORMAT_R16_UINT, 0);
/// Set primitive topology
CDevCont.g_pImmediateContextD3D11->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
/// Create the constant buffers
bd2.Usage = USAGE_DEFAULT;
bd2.ByteWidth = sizeof(CBNeverChanges);
bd2.BindFlags = BIND_CONSTANT_BUFFER;
bd2.CPUAccessFlags = 0;
FreeCamera.g_pCBNeverChangesCamera.Init(bd2);
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&FreeCamera.g_pCBNeverChangesCamera.m_BufferDescD3D11, NULL, &FreeCamera.g_pCBNeverChangesCamera.m_BufferD3D11);
if (FAILED(hr))
return hr;
/// Inicialización NeverChange FirstPersonCamera
FPSCamera.g_pCBNeverChangesCamera.Init(bd2);
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&FPSCamera.g_pCBNeverChangesCamera.m_BufferDescD3D11, NULL, &FPSCamera.g_pCBNeverChangesCamera.m_BufferD3D11);
if (FAILED(hr))
return hr;
/// bd.ByteWidth = sizeof(CBChangeOnResize);
bd2.ByteWidth = sizeof(CBChangeOnResize);
FreeCamera.g_pCBChangeOnResizeCamera.Init(bd2);
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&FreeCamera.g_pCBChangeOnResizeCamera.m_BufferDescD3D11, NULL, &FreeCamera.g_pCBChangeOnResizeCamera.m_BufferD3D11);
if (FAILED(hr))
return hr;
/// Inicialización Resize FirstPersonCamera
FPSCamera.g_pCBChangeOnResizeCamera.Init(bd2);
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&FPSCamera.g_pCBChangeOnResizeCamera.m_BufferDescD3D11, NULL, &FPSCamera.g_pCBChangeOnResizeCamera.m_BufferD3D11);
if (FAILED(hr))
return hr;
/// bd.ByteWidth = sizeof(CBChangesEveryFrame);
bd2.ByteWidth = sizeof(CBChangesEveryFrame);
FreeCamera.g_pCBChangesEveryFrameCamera.Init(bd2);
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&FreeCamera.g_pCBChangesEveryFrameCamera.m_BufferDescD3D11, NULL, &FreeCamera.g_pCBChangesEveryFrameCamera.m_BufferD3D11);
if (FAILED(hr))
return hr;
/// Inicialización ChangeEveryFrame FirstPersonCamera
FPSCamera.g_pCBChangesEveryFrameCamera.Init(bd2);
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&FPSCamera.g_pCBChangesEveryFrameCamera.m_BufferDescD3D11, NULL, &FPSCamera.g_pCBChangesEveryFrameCamera.m_BufferD3D11);
if (FAILED(hr))
return hr;
//Inicialización de las luces
bd2.ByteWidth = sizeof(Lights);
g_Lights.Init(bd2);
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&g_Lights.m_BufferDescD3D11, NULL, &g_Lights.m_BufferD3D11);
if (FAILED(hr))
return hr;
bd2.ByteWidth = sizeof(ConstBufferBones);
g_boneBuffer.Init(bd2);
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&g_boneBuffer.m_BufferDescD3D11, NULL, &g_boneBuffer.m_BufferD3D11);
/// Load the Texture
hr = D3DX11CreateShaderResourceViewFromFile(CDev.g_pd3dDeviceD3D11, L"seafloor.dds", NULL, NULL, &g_pTextureRV, NULL);
if (FAILED(hr))
return hr;
/// Create the sample state
SampleStateDesc sampDesc2;
sampDesc2.Filter = FILTER_MIN_MAG_MIP_LINEAR;
sampDesc2.AddressU = TEXTURE_ADDRESS_WRAP;
sampDesc2.AddressV = TEXTURE_ADDRESS_WRAP;
sampDesc2.AddressW = TEXTURE_ADDRESS_WRAP;
sampDesc2.ComparisonFunc = COMPARISON_NEVER;
sampDesc2.MinLOD = 0;
sampDesc2.MaxLOD = D3D11_FLOAT32_MAX;
CSampleS.Init(sampDesc2);
hr = CDev.g_pd3dDeviceD3D11->CreateSamplerState(&CSampleS.sampDescD3D11, &CSampleS.g_pSamplerLinearD3D11);
if (FAILED(hr))
return hr;
/// Initialize the world matrices
g_World = g_World.Identity();
/// Initialize the view matrix
mathfu::Vector<float, 4> Eye(0.0f, 3.0f, -6.0f, 0.0f);
mathfu::Vector<float, 4> At(0.0f, 1.0f, 0.0f, 0.0f);
mathfu::Vector<float, 4> Up(0.0f, 1.0f, 0.0f, 0.0f);
InitCameras();
CBNeverChanges cbNeverChanges;
cbNeverChanges.mView = FPSCamera.GetView();
CDevCont.g_pImmediateContextD3D11->UpdateSubresource(FPSCamera.g_pCBNeverChangesCamera.m_BufferD3D11, 0, NULL, &cbNeverChanges, 0, 0);
cbNeverChanges.mView = FreeCamera.GetView();
CDevCont.g_pImmediateContextD3D11->UpdateSubresource(FreeCamera.g_pCBNeverChangesCamera.m_BufferD3D11, 0, NULL, &cbNeverChanges, 0, 0);
/// Initialize the projection matrix
CBChangeOnResize cbChangesOnResize;
cbChangesOnResize.mProjection = FPSCamera.GetProjection();
CDevCont.g_pImmediateContextD3D11->UpdateSubresource(FPSCamera.g_pCBChangeOnResizeCamera.m_BufferD3D11, 0, NULL, &cbChangesOnResize, 0, 0);
cbChangesOnResize.mProjection = FreeCamera.GetProjection();
CDevCont.g_pImmediateContextD3D11->UpdateSubresource(FreeCamera.g_pCBChangeOnResizeCamera.m_BufferD3D11, 0, NULL, &cbChangesOnResize, 0, 0);
//Seteamos los valores de la estructura de luz
Lights sLights;
sLights.mLightDir = g_DirLight;
sLights.lightPointPos = g_lightPointPos;
sLights.lightPointAtt = g_lightPointAt;
CDevCont.g_pImmediateContextD3D11->UpdateSubresource(g_Lights.m_BufferD3D11, 0, NULL, &sLights, 0, 0);
Texture2Desc T;
ZeroMemory(&T, sizeof(T));
T.Width = width;
T.Height = height;
T.MipLevels = T.ArraySize = 1;
T.Format = FORMAT_R16G16B16A16_FLOAT;
T.SampleDesc.My_Count = 1;
T.Usage = USAGE_DEFAULT;
T.BindFlags = 8 | 32;
T.CPUAccessFlags = 65536; //enum
T.MiscFlags = 0;
InactiveTexture.Init(T);
hr = CDev.g_pd3dDeviceD3D11->CreateTexture2D(&InactiveTexture.m_TextDescD3D11, NULL, &InactiveTexture.m_TextureD3D11);
if (FAILED(hr)) {
return hr;
}
RenderTargetViewDesc RTVDesc;
ZeroMemory(&RTVDesc, sizeof(RTVDesc));
RTVDesc.Format = T.Format;
RTVDesc.ViewDimension = RTV_DIMENSION_TEXTURE2D;
RTVDesc.Texture2D.My_MipSlice = 0;
InactiveRTV.Init(RTVDesc);
hr = CDev.g_pd3dDeviceD3D11->CreateRenderTargetView(InactiveTexture.m_TextureD3D11, &InactiveRTV.m_renderTVD3D11, &InactiveRTV.g_pRenderTargetViewD3D11);
if (FAILED(hr)) {
return hr;
}
D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
SRVDesc.Format = (DXGI_FORMAT)T.Format;
SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Texture2D.MostDetailedMip = 0;
SRVDesc.Texture2D.MipLevels = 1;
hr = CDev.g_pd3dDeviceD3D11->CreateShaderResourceView(InactiveTexture.m_TextureD3D11, &SRVDesc, &G_InactiveSRV);
if (FAILED(hr)) {
return hr;
}
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplWin32_Init(g_hWnd);
ImGui_ImplDX11_Init(CDev.g_pd3dDeviceD3D11, CDevCont.g_pImmediateContextD3D11);
ImGui::StyleColorsDark();
InitCameras();
/// API GRAPHIC
//G_GraphicApi.ChargeMesh("EscenaDelMaestro/Model/Scene/Scene.fbx", &G_SceneManager, G_GraphicApi.m_Model, CDevCont, G_GraphicApi.m_Importer, &CDev);
G_GraphicApi.ChargeMesh("PistolaOBJ/drakefire_pistol_low.fbx", &G_SceneManager, G_GraphicApi.m_Model, CDevCont, g_myImporter, &CDev, "PistolaOBJ/base_albedo.png", "PistolaOBJ/base_normal.png", "PistolaOBJ/base_metallic.png" );
G_GraphicApi.ChargeMesh("ModelRenderMonkey/ScreenAlignedQuad.3ds", &g_screenAligneQuadSM, G_GraphicApi.m_Model, CDevCont, g_myImporter, &CDev, "", "", "");
G_GraphicApi.ChargeMesh("ModelRenderMonkey/Sphere.3ds", &g_skyboxSM, G_GraphicApi.m_Model, CDevCont, g_myImporter, &CDev, "", "", "");
//g_myScene = G_GraphicApi.ChargeMesh("ugandan/Knuckles.fbx", &G_SceneManager, G_GraphicApi.m_Model, CDevCont, g_myImporter, &CDev);
PassDX gBufferStruct;
gBufferStruct.s_device = &CDev;
gBufferStruct.s_deviceContext = &CDevCont;
gBufferStruct.s_renderTargetViewAccountant = 4;
gBufferStruct.s_texture2Desc = T;
ZeroMemory(&gBufferStruct.s_rasterizer, sizeof(gBufferStruct.s_rasterizer));
gBufferStruct.s_rasterizer.FillMode = D3D11_FILL_SOLID;
gBufferStruct.s_rasterizer.CullMode = D3D11_CULL_FRONT;
gBufferStruct.s_rasterizer.FrontCounterClockwise = true;
CompileShaders(L"ShaderGbuffer.fx", "vs_main", "ps_main", g_pass.m_InputLayoutVertexShaderPixelShader);
g_pass.Init(gBufferStruct);
//AmbientOclussion
gBufferStruct.s_renderTargetViewAccountant = 1;
gBufferStruct.s_rasterizer.CullMode = D3D11_CULL_NONE;
CompileShaders(L"ShaderSSAO.fx", "vs_main", "ps_main", g_superSamplingAmbientOclussion.m_InputLayoutVertexShaderPixelShader);
g_superSamplingAmbientOclussion.Init(gBufferStruct);
BufferDescriptor ssaoBuffer;
ssaoBuffer.Usage = USAGE_DEFAULT;
ssaoBuffer.ByteWidth = sizeof(SuperSamplerAmbientOclussion);
ssaoBuffer.BindFlags = 4;
ssaoBuffer.CPUAccessFlags = 0;
g_superSamplingAmbientOclussionBuffer.Init(ssaoBuffer);
hr = CDev.g_pd3dDeviceD3D11->CreateBuffer(&g_superSamplingAmbientOclussionBuffer.m_BufferDescD3D11, NULL, &g_superSamplingAmbientOclussionBuffer.m_BufferD3D11);
if (FAILED(hr)) {
return hr;
}
SuperSamplerAmbientOclussion superSamplerDesc;
superSamplerDesc.s_bias = 0.1f;
superSamplerDesc.s_intensity = 8.2f;
superSamplerDesc.s_sample = 2.4f;
superSamplerDesc.s_scale = 0.5f;
CDevCont.g_pImmediateContextD3D11->UpdateSubresource(g_superSamplingAmbientOclussionBuffer.m_BufferD3D11, 0, NULL, &superSamplerDesc, 0, 0);
g_superSamplingAmbientOclussion.SetShaderResource(&CDev, g_pass.m_texture2D.at(2));
g_superSamplingAmbientOclussion.SetShaderResource(&CDev, g_pass.m_texture2D.at(0));
//Skybox
CompileShaders(L"ShaderSkybox.fx", "vs_main", "ps_main", g_skyBox.m_InputLayoutVertexShaderPixelShader);
g_skyBox.Init(gBufferStruct);
D3DX11_IMAGE_LOAD_INFO loadImageInfo;
loadImageInfo.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
ID3D11Texture2D* texture2D;
hr = D3DX11CreateTextureFromFile(CDev.g_pd3dDeviceD3D11, L"ModelRenderMonkey/grace_cube.dds", &loadImageInfo, 0, (ID3D11Resource**)&texture2D, 0);
if (FAILED(hr)) {
return hr;
}
D3D11_TEXTURE2D_DESC textureDesc;
texture2D->GetDesc(&textureDesc);
D3D11_SHADER_RESOURCE_VIEW_DESC cheiderDesc;
ZeroMemory(&cheiderDesc, sizeof(cheiderDesc));
cheiderDesc.Format = textureDesc.Format;
cheiderDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
cheiderDesc.TextureCube.MipLevels = textureDesc.MipLevels;
cheiderDesc.TextureCube.MostDetailedMip = 0;
hr = CDev.g_pd3dDeviceD3D11->CreateShaderResourceView(texture2D, &cheiderDesc, &g_skyboxSM.GetMesh(0)->m_Materials->m_TexDif);
if (FAILED(hr)) {
return hr;
}
return S_OK;
}
#endif // D3D11
/// Clean up the objects we've created
void CleanupDevice()
{
#ifdef D3D11
if (CDevCont.g_pImmediateContextD3D11) CDevCont.g_pImmediateContextD3D11->ClearState();
if (CSampleS.g_pSamplerLinearD3D11) CSampleS.g_pSamplerLinearD3D11->Release();
if (g_pTextureRV) g_pTextureRV->Release();
if (FCNeverChange.m_BufferD3D11)FCNeverChange.m_BufferD3D11->Release();
if (FCOnResize.m_BufferD3D11)FCOnResize.m_BufferD3D11->Release();
if (FCChangeEveryFrame.m_BufferD3D11)FCChangeEveryFrame.m_BufferD3D11->Release();
if (CVertexBuffer.m_Buffer.m_BufferD3D11)CVertexBuffer.m_Buffer.m_BufferD3D11->Release();
if (CIndexBuffer.m_Buffer.m_BufferD3D11)CIndexBuffer.m_Buffer.m_BufferD3D11->Release();
if (CShader.LayoutD3D11) CShader.LayoutD3D11->Release();
if (CShader.g_pVertexShaderD3D11) CShader.g_pVertexShaderD3D11->Release();
if (g_pixelShader.pPixelShader) g_pixelShader.pPixelShader->Release();
if (CRendTar.g_pDepthStencilD3D11) CRendTar.g_pDepthStencilD3D11->Release();
if (CDepthStencilView.g_pDepthStencilViewD3D11) CDepthStencilView.g_pDepthStencilViewD3D11->Release();
if (CRendTarView.g_pRenderTargetViewD3D11) CRendTarView.g_pRenderTargetViewD3D11->Release();
if (CSwap.g_pSwapChainD3D11) CSwap.g_pSwapChainD3D11->Release();
if (CDevCont.g_pImmediateContextD3D11) CDevCont.g_pImmediateContextD3D11->Release();
if (CDev.g_pd3dDeviceD3D11) CDev.g_pd3dDeviceD3D11->Release();
if (FPCNeverChange.m_BufferD3D11)FPCNeverChange.m_BufferD3D11->Release();
if (FPCOnResize.m_BufferD3D11)FPCOnResize.m_BufferD3D11->Release();
if (FPCChangeEveryFrame.m_BufferD3D11)FPCChangeEveryFrame.m_BufferD3D11->Release();
if (InactiveTexture.m_TextureD3D11) InactiveTexture.m_TextureD3D11->Release();
if (InactiveRTV.g_pRenderTargetViewD3D11) InactiveRTV.g_pRenderTargetViewD3D11->Release();
if (G_InactiveSRV)G_InactiveSRV->Release();
#endif
}
/// Called every time the application receives a message
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
if (io.WantCaptureMouse){
ImGui_ImplWin32_WndProcHandler(hWnd, message, wParam, lParam);
return true;
}
PAINTSTRUCT ps;
HDC hdc;
POINT Temp;
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
/// WM_SIZE: It is sent to a window after its size has changed.
case WM_SIZE: {
Resize();
break;
}
/// WM_KEYDOWN: A window receives keyboard input in the form of keystroke messages and character messages.
case WM_KEYDOWN: {
MainCamera->inputs(wParam);
CBNeverChanges cb;
cb.mView = MainCamera->GetView();
#if defined(D3D11)
CDevCont.g_pImmediateContextD3D11->UpdateSubresource(MainCamera->g_pCBNeverChangesCamera.m_BufferD3D11, 0, NULL, &cb, 0, 0);
#endif
break;
}
/// WM_LBUTTONDOWN: Posted when the user presses the left mouse button while the cursor is in the client area of a window.
case WM_LBUTTONDOWN:
GetCursorPos(&Temp);
//MainCamera->SetOriginalMousePos(Temp.x, Temp.y);c
MainCamera->OriginalMousePos = mathfu::float2(Temp.x, Temp.y);
MainCamera->m_ClickPressed = true;
break;
case WM_MOUSEMOVE:
#ifdef D3D11
if (MainCamera->m_ClickPressed)
{
MainCamera->SetOriginalMousePos(MainCamera->OriginalMousePos.x, MainCamera->OriginalMousePos.y);
MainCamera->MouseRotation();
CBNeverChanges cb;
cb.mView = MainCamera->GetView();
CDevCont.g_pImmediateContextD3D11->UpdateSubresource(MainCamera->g_pCBNeverChangesCamera.m_BufferD3D11, 0, NULL, &cb, 0, 0);
}
#endif // D3D11
break;
/// WM_LBUTTONUP: Posted when the user releases the left mouse button while the cursor is in the client area of a window.
case WM_LBUTTONUP:
MainCamera->m_ClickPressed = false;
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
/// Render a frame
#ifdef D3D11
void Render()
{
//G_SceneManager.Update();
//
///// Update our time
//static float t = 0.0f;
//if (CDev.m_DescDevice.g_driverType == D3D_DRIVER_TYPE_REFERENCE){
//
// t += (float)XM_PI * 0.0125f;
//}
//else{
//
// static DWORD dwTimeStart = 0;
// DWORD dwTimeCur = GetTickCount();
// if (dwTimeStart == 0)
// dwTimeStart = dwTimeCur;
// t = (dwTimeCur - dwTimeStart) / 1000.0f;
//}
//
//Animación
//
/// Clear the back buffer
float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; // red, green, blue, alpha
g_pass.SetPass(&CDepthStencilView);
g_pass.ClearWindow(ClearColor, &CDepthStencilView);
//std::vector<mathfu::float4x4> transforms;
//
//float runningTime = GetRunnningTime();
//
//G_GraphicApi.BoneTransform(runningTime, transforms, g_myScene, &G_SceneManager);
//
//ConstBufferBones cBBone;
//
//for (int i = 0; i < transforms.size(); i++) {
//
// if (i < 100) {
//
// cBBone.bones[i] = transforms[i];
// }
//}
//
//CDevCont.g_pImmediateContextD3D11->UpdateSubresource(g_boneBuffer.m_BufferD3D11, 0 , NULL, &cBBone, 0, 0);
/*Lights sLights;
sLights.mLightDir = g_DirLight;
sLights.lightPointPos = g_lightPointPos;
sLights.lightPointAtt = g_lightPointAt;
CDevCont.g_pImmediateContextD3D11->UpdateSubresource(g_Lights.m_BufferD3D11, 0, NULL, &sLights, 0, 0);*/
//CDevCont.g_pImmediateContextD3D11->ClearRenderTargetView(InactiveRTV.g_pRenderTargetViewD3D11, ClearColor);
// CDevCont.g_pImmediateContextD3D11->ClearRenderTargetView(CRendTarView.g_pRenderTargetViewD3D11, ClearColor);
/// Clear the depth buffer to 1.0 (max depth)
//CDevCont.g_pImmediateContextD3D11->ClearDepthStencilView(CDepthStencilView.g_pDepthStencilViewD3D11, D3D11_CLEAR_DEPTH, 1.0f, 0);
CDevCont.g_pImmediateContextD3D11->PSSetSamplers(0, 1, &CSampleS.g_pSamplerLinearD3D11);
CBChangesEveryFrame m_MeshData;
m_MeshData.mWorld = {
1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1
};
// m_MeshData.vMeshColor = { 1,1,1,1 };
// m_MeshData.vViewPos = { MainCamera->GetEye().x, MainCamera->GetEye().y, MainCamera->GetEye().z, 0};
//CDevCont.g_pImmediateContextD3D11->UpdateSubresource(SecondCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11, 0, NULL, &m_MeshData, 0, 0);
CDevCont.g_pImmediateContextD3D11->UpdateSubresource(MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11, 0, NULL, &m_MeshData, 0, 0);
CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(0, 1, &MainCamera->g_pCBNeverChangesCamera.m_BufferD3D11);
CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(1, 1, &MainCamera->g_pCBChangeOnResizeCamera.m_BufferD3D11);
CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(2, 1, &MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers(2, 1, &MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
g_pass.Draw(&G_SceneManager, sizeof(SimpleVertex));
//g_pass.Render(CRendTarView, CDepthStencilView, &CDevCont, G_SceneManager, MainCamera, &g_Lights);
/*
//g_World = g_World.FromTranslationVector(mathfu::Vector<float, 3>(3.0f, 0.0f, 0.0f));
/// Modify the color
//g_vMeshColor.x = (sinf(t * 1.0f) + 1.0f) * 0.5f;
//g_vMeshColor.y = (cosf(t * 3.0f) + 1.0f) * 0.5f;
//g_vMeshColor.z = (sinf(t * 5.0f) + 1.0f) * 0.5f;
//CDevCont.g_pImmediateContextD3D11->OMSetRenderTargets (1, &InactiveRTV.g_pRenderTargetViewD3D11, CDepthStencilView.g_pDepthStencilViewD3D11);
/// Update variables that change once per frame
/// Render the cube
//UINT stride = sizeof(SimpleVertex);
//UINT offset = 0;
//CDevCont.g_pImmediateContextD3D11->IASetVertexBuffers (0, 1, &CVertexBuffer.m_Buffer.m_BufferD3D11, &stride, &offset);
//CDevCont.g_pImmediateContextD3D11->IASetIndexBuffer (CIndexBuffer.m_Buffer.m_BufferD3D11, DXGI_FORMAT_R16_UINT, 0);
//CDevCont.g_pImmediateContextD3D11->PSSetShader (g_pPixelShader, NULL, 0);
//CDevCont.g_pImmediateContextD3D11->VSSetShader (CShader.g_pVertexShaderD3D11, NULL, 0);
//Nuevo
//CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers (0, 1, &MainCamera->g_pCBNeverChangesCamera.m_BufferD3D11);
//CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers (0, 1, &MainCamera->g_pCBNeverChangesCamera.m_BufferD3D11);
//Nuevo
//CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers (1, 1, &MainCamera->g_pCBChangeOnResizeCamera.m_BufferD3D11);
//CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers (1, 1, &MainCamera->g_pCBChangeOnResizeCamera.m_BufferD3D11);
//CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers (2, 1, &MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
//Nuevo
//CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers (2, 1, &MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
//Nuevo
//CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers (3, 1, &g_Lights.m_BufferD3D11);
//CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers (3, 1, &g_Lights.m_BufferD3D11);
//
//CDevCont.g_pImmediateContextD3D11->PSSetShaderResources (0, 1, &g_pTextureRV);
//Nuevo
//m_MeshData.vViewPos = { SecondCamera->GetEye().x, SecondCamera->GetEye().y, SecondCamera->GetEye().z, 0.0f};
//CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(2, 1, &SecondCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
//CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers(2, 1, &SecondCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
//for (size_t i = 0; i < G_SceneManager.m_MeshInScene.size(); i++)
//{
// CDevCont.g_pImmediateContextD3D11->PSSetShaderResources(0, 1, &G_SceneManager.m_MeshInScene[i]->m_Materials->m_TexDif);
// UINT stride = sizeof(SimpleVertex);
// UINT offset = 0;
//
// CDevCont.g_pImmediateContextD3D11->IASetVertexBuffers
// (
// 0,
// /// number of buffers we are using
// 1,
// /// pointer to the buffers list
// &G_SceneManager.m_MeshInScene[i]->m_VertexBuffer->m_BufferD3D11,
// /// a uint indicating the size of a single vertex
// &stride,
// &offset
// );//un uint que indica el numero del byte en el vertice del que se quiere comenzar a pintar
//
// CDevCont.g_pImmediateContextD3D11->IASetIndexBuffer
// (
// G_SceneManager.m_MeshInScene[i]->m_Index->m_BufferD3D11,
// DXGI_FORMAT_R16_UINT,
// 0
// );
//
// /// Tipo de topologia
// /// Draws the vertex buffer in the back buffer
// CDevCont.g_pImmediateContextD3D11->DrawIndexed(G_SceneManager.m_MeshInScene[i]->m_IndexNum, 0, 0);
//}
//CDevCont.g_pImmediateContextD3D11->OMSetRenderTargets (1, &CRendTarView.g_pRenderTargetViewD3D11, CDepthStencilView.g_pDepthStencilViewD3D11);
//CDevCont.g_pImmediateContextD3D11->ClearRenderTargetView(CRendTarView.g_pRenderTargetViewD3D11, ClearColor);
//CDevCont.g_pImmediateContextD3D11->ClearDepthStencilView(CDepthStencilView.g_pDepthStencilViewD3D11, D3D11_CLEAR_DEPTH, 1.0f, 0);
//CDevCont.g_pImmediateContextD3D11->IASetVertexBuffers(0, 1, &CVertexBuffer.m_Buffer.m_BufferD3D11, &stride, &offset);
//CDevCont.g_pImmediateContextD3D11->IASetIndexBuffer(CIndexBuffer.m_Buffer.m_BufferD3D11, DXGI_FORMAT_R16_UINT, 0);
//
//m_MeshData.mWorld = {
// 1,0,0,0,
// 0,1,0,0,
// 0,0,1,0,
// 0,0,0,1
//};
//Nuevo
//m_MeshData.vViewPos = { SecondCamera->GetEye().x, SecondCamera->GetEye().y, SecondCamera->GetEye().z, 0.0f };
//CDevCont.g_pImmediateContextD3D11->UpdateSubresource(g_Lights.m_BufferD3D11, 0, NULL, &sLights, 0, 0);
//CDevCont.g_pImmediateContextD3D11->UpdateSubresource(MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11, 0, NULL, &m_MeshData, 0, 0);
//CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(2, 1, &MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
//CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers(2, 1, &MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
//Nuevo
//CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(0, 1, &MainCamera->g_pCBNeverChangesCamera.m_BufferD3D11);
//CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers(0, 1, &MainCamera->g_pCBNeverChangesCamera.m_BufferD3D11);
//Nuevo
//CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(1, 1, &MainCamera->g_pCBChangeOnResizeCamera.m_BufferD3D11);
//CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers(1, 1, &MainCamera->g_pCBChangeOnResizeCamera.m_BufferD3D11);
//CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(2, 1, &MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
//Nuevo
//CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers(2, 1, &MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
//Nuevo
//CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers(3, 1, &g_Lights.m_BufferD3D11);
//CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(3, 1, &g_Lights.m_BufferD3D11);
//for (size_t i = 0; i < G_SceneManager.m_MeshInScene.size(); i++)
//{
// CDevCont.g_pImmediateContextD3D11->PSSetShaderResources(0, 1, &G_SceneManager.m_MeshInScene[i]->m_Materials->m_TexDif);
// UINT stride = sizeof(SimpleVertex);
// UINT offset = 0;
//
// CDevCont.g_pImmediateContextD3D11->IASetVertexBuffers
// (
// 0,
// /// number of buffers we are using
// 1,
// /// pointer to the buffers list
// &G_SceneManager.m_MeshInScene[i]->m_VertexBuffer->m_BufferD3D11,
// /// a uint indicating the size of a single vertex
// &stride,
// &offset
// );//un uint que indica el numero del byte en el vertice del que se quiere comenzar a pintar
//
// CDevCont.g_pImmediateContextD3D11->IASetIndexBuffer
// (
// G_SceneManager.m_MeshInScene[i]->m_Index->m_BufferD3D11,
// DXGI_FORMAT_R16_UINT,
// 0
// );
//
// /// Tipo de topologia
// /// Draws the vertex buffer in the back buffer
// CDevCont.g_pImmediateContextD3D11->DrawIndexed(G_SceneManager.m_MeshInScene[i]->m_IndexNum, 0, 0);
//}
/// Present our back buffer to our front buffer
*/
//SSAO
ClearColor[0] = 0.0f;
ClearColor[1] = 0.0f;
ClearColor[2] = 0.0f;
ClearColor[3] = 0.0f;
g_superSamplingAmbientOclussion.SetPass(&CDepthStencilView);
g_superSamplingAmbientOclussion.ClearWindow(ClearColor, &CDepthStencilView);
CDevCont.g_pImmediateContextD3D11->PSSetConstantBuffers(0,1, &g_superSamplingAmbientOclussionBuffer.m_BufferD3D11);
g_superSamplingAmbientOclussion.Draw(&g_screenAligneQuadSM , sizeof(SimpleVertex));
//Skybots
g_skyBox.SetPass(&CDepthStencilView);
g_skyBox.ClearWindow(ClearColor, &CDepthStencilView);
CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(0, 1, &MainCamera->g_pCBNeverChangesCamera.m_BufferD3D11);
CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(1, 1, &MainCamera->g_pCBChangeOnResizeCamera.m_BufferD3D11);
CDevCont.g_pImmediateContextD3D11->VSSetConstantBuffers(2, 1, &MainCamera->g_pCBChangesEveryFrameCamera.m_BufferD3D11);
g_skyBox.Draw(&g_skyboxSM , sizeof(SimpleVertex));
CDevCont.g_pImmediateContextD3D11->OMSetRenderTargets(1, &CRendTarView.g_pRenderTargetViewD3D11, CDepthStencilView.g_pDepthStencilViewD3D11);
CDevCont.g_pImmediateContextD3D11->ClearRenderTargetView(CRendTarView.g_pRenderTargetViewD3D11, ClearColor);
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
/// Present our back buffer to our front buffer
CSwap.g_pSwapChainD3D11->Present(0, 0);
}
#endif
long long GetCurrentTimeMS() {
#ifdef WIN32
return GetTickCount();
#endif
}
float GetRunnningTime() {
float runningTime = (float)((double)GetCurrentTimeMS() - (double)g_startTime) / 1000.0f;
return runningTime;
} | [
"[email protected]"
] | |
4944e7f82f625b42142a2e0ee3ab8e22bbe3826b | bc18d10f510ec9f3d4165172da61afb357626826 | /hw2/Graph_1132.hpp | be2521dbe2f2846c6f9e608b23099a1d66a078d7 | [] | no_license | RaphAbb/peercode | 3cb48f73a1c673f714ba8416fc6be43271f89054 | 01c11cfc2247fa900577efee3fbed40d545b518f | refs/heads/master | 2020-04-26T15:59:42.030818 | 2019-02-20T03:56:40 | 2019-02-20T03:56:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,561 | hpp | #ifndef CME212_GRAPH_HPP
#define CME212_GRAPH_HPP
/** @file Graph.hpp
* @brief An undirected graph type
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <cassert>
#include <unordered_map>
#include <unordered_set>
#include "CME212/Util.hpp"
#include "CME212/Point.hpp"
/** @class Graph
* @brief A template for 3D undirected graphs.
*
* Users can add and retrieve nodes and edges. Edges are unique (there is at
* most one edge between any pair of distinct nodes).
*/
template <typename V, typename E>
class Graph {
private:
struct NodeInfo;
struct EdgeInfo;
public:
//
// PUBLIC TYPE DEFINITIONS
//
/** type of Node value. */
using node_value_type = V ;
using edge_value_type = E ;
/** Type of this graph. */
using graph_type = Graph;
/** Predeclaration of Node type. */
class Node;
/** Synonym for Node (following STL conventions). */
using node_type = Node;
/** Predeclaration of Edge type. */
class Edge;
/** Synonym for Edge (following STL conventions). */
using edge_type = Edge;
/** Type of node iterators, which iterate over all graph nodes. */
class NodeIterator;
/** Synonym for NodeIterator */
using node_iterator = NodeIterator;
/** Type of edge iterators, which iterate over all graph edges. */
class EdgeIterator;
/** Synonym for EdgeIterator */
using edge_iterator = EdgeIterator;
/** Type of incident iterators, which iterate incident edges to a node. */
class IncidentIterator;
/** Synonym for IncidentIterator */
using incident_iterator = IncidentIterator;
/** Type of indexes and sizes.
Return type of Graph::Node::index(), Graph::num_nodes(),
Graph::num_edges(), and argument type of Graph::node(size_type) */
using size_type = unsigned;
//
// CONSTRUCTORS AND DESTRUCTOR
//
/** Construct an empty graph. */
Graph() {
}
/** Default destructor */
~Graph() = default;
//
// NODES
//
/** @class Graph::Node
* @brief Class representing the graph's nodes.
*
* Node objects are used to access information about the Graph's nodes.
*/
class Node : private totally_ordered<Node> {
public:
/** Construct an invalid node.
*
* Valid nodes are obtained from the Graph class, but it
* is occasionally useful to declare an @i invalid node, and assign a
* valid node to it later. For example:
*
* @code
* Graph::node_type x;
* if (...should pick the first node...)
* x = graph.node(0);
* else
* x = some other node using a complicated calculation
* do_something(x);
* @endcode
*/
Node() {
graph_n = nullptr;
}
/** Return this node's position. */
const Point& position() const {
return graph_n->nodes[n_uid].position;
}
/** Return this node's position, modifiable. */
Point& position() {
return graph_n->nodes[n_uid].position;
}
/** Return this node's index, a number in the range [0, graph_size). */
size_type index() const {
return graph_n->nodes[n_uid].idx;
}
/** Test whether this node and @a n are equal.
*
* Equal nodes have the same graph and the same index.
*/
bool operator==(const Node& n) const {
return (graph_n->has_node(n) && index() == n.index());
}
/** Test whether this node is less than @a n in a global order.
*
* This ordering function is useful for STL containers such as
* std::map<>. It need not have any geometric meaning.
*
* The node ordering relation must obey trichotomy: For any two nodes x
* and y, exactly one of x == y, x < y, and y < x is true.
*/
bool operator<(const Node& n) const {
if (graph_n != n.graph_n)
return true;
return (n_uid < n.n_uid);
}
/** Return this node's value. */
node_value_type& value() {
return graph_n->nodes[n_uid].node_value;
}
/** Return this node's value. */
const node_value_type& value() const {
return graph_n->nodes[n_uid].node_value;
}
/** Return this node's degree. */
size_type degree () const {
return graph_n->adj_uid[n_uid].size();
}
/** Return the incident_iterator, as the first edge. */
incident_iterator edge_begin () const {
return incident_iterator(graph_n, index(), 0);
}
/** Return the incident_iterator, as the (last+1) edge. */
incident_iterator edge_end () const {
return incident_iterator(graph_n, index(),
graph_n->adj_uid[n_uid].size());
}
private:
// Allow Graph to access Node's private member data and functions.
friend class Graph;
graph_type* graph_n;
size_type n_uid;
Node(const graph_type* graph, size_type i)
: graph_n(const_cast<graph_type*>(graph)), n_uid(i) {
}
};
/** Return the number of nodes in the graph.
*
* Complexity: O(1).
*/
size_type size() const {
return ni2nu.size();
}
/** Synonym for size(). */
size_type num_nodes() const {
return ni2nu.size();
}
/** Add a node to the graph, returning the added node.
* @param[in] position The new node's position
* @post new num_nodes() == old num_nodes() + 1
* @post result_node.index() == old num_nodes()
*
* Complexity: O(1) amortized operations.
*/
Node add_node(const Point& position,
const node_value_type& node_value = node_value_type()) {
NodeInfo new_node{position, (unsigned int)ni2nu.size(), node_value};
nodes.push_back(new_node);
ni2nu.push_back(nodes.size() - 1);
adj_uid.push_back(std::vector<id_pair> ());
return Node(this, nodes.size() - 1);
}
/** Determine if a Node belongs to this Graph
* @return True if @a n is currently a Node of this Graph
*
* Complexity: O(1).
*/
bool has_node(const Node& n) const {
return (this == n.graph_n &&
n.n_uid == ni2nu[n.index()]);
}
/** Return the node ith index @a i.
* @pre 0 <= @a i < num_nodes()
* @post result_node.index() == i
*
* Complexity: O(1).
*/
Node node(size_type i) const {
assert(i < ni2nu.size());
return Node(this, ni2nu[i]);
}
/** Remove the given node and all the edges that are incident to it.
* @param[in] n The target node for removal.
* @result 0 or 1 (0 means @a n is not in the graph,
* 1 means @a n is in the graph).
* @post if @a n is not in the graph, 0 is returned;
* if @a n is in the graph, ni2nu[@a n.index()]=ni2nu[ni2nu.size()-1],
* the last element of ni2nu is pop_backed,
* new ni2nu size = old ni2nu size - 1,
* all the edges that are incident to @a n are removed,
* 1 is returned.
* Complexity: O(num_local_edges * num_edges()).
* Can invalidate parts of containers related to nodes.
* for ni2nu, [n.index(), end()) would be invalidated.
* for nodes, the element with position ni2nu[n.index()] is modified
*
*/
size_type remove_node(const Node& n) {
if (!has_node(n))
return 0;
size_type n_uid = ni2nu[n.index()];
std::vector<id_pair> n_edges = adj_uid[n_uid];
// remove edges that are incident to the node
for (unsigned int i = 0; i < n_edges.size(); ++i) {
auto no_use = remove_edge(n, Node(this, n_edges[i].n_uid));
(void) no_use;
}
ni2nu[n.index()] = ni2nu[ni2nu.size() - 1];
ni2nu.pop_back();
nodes[ni2nu[n.index()]].idx = n.index();
return 1;
}
//
// EDGES
//
/** @class Graph::Edge
* @brief Class representing the graph's edges.
*
* Edges are order-insensitive pairs of nodes. Two Edges with the same nodes
* are considered equal if they connect the same nodes, in either order.
*/
class Edge : private totally_ordered<Edge> {
public:
/** Construct an invalid Edge. */
Edge() {
graph_e = nullptr;
}
/** Return a node of this Edge */
Node node1() const {
return Node(graph_e, n1_uid);
}
/** Return the other node of this Edge */
Node node2() const {
return Node(graph_e, n2_uid);
}
double length() const {
return norm(node1().position() - node2().position());
}
/** Test whether this edge and @a e are equal.
*
* Equal edges represent the same undirected edge between two nodes.
*/
bool operator==(const edge_type& e) const {
if ((node1() == e.node1() && node2() == e.node2()) ||
(node1() == e.node2() && node2() == e.node1()))
return true;
return false;
}
/** Test whether this edge is less than @a e in a global order.
*
* This ordering function is useful for STL containers such as
* std::map<>. It need not have any interpretive meaning.
*/
bool operator<(const edge_type& e) const {
if (graph_e != e.graph_e)
return true;
return ((node1().index() + node2().index()) <
(e.node1().index() + e.node1().index()));
}
edge_value_type& value() {
return graph_e->edges[e_uid].edge_value;
}
const edge_value_type& value() const {
return graph_e->edges[e_uid].edge_value;
}
private:
// Allow Graph to access Edge's private member data and functions.
friend class Graph;
size_type n1_uid;
size_type n2_uid;
size_type e_uid;
graph_type* graph_e;
Edge(const graph_type* graph, size_type n1, size_type n2, size_type i)
: graph_e(const_cast<graph_type*>(graph)) {
assert(n1 < graph_e->nodes.size() && n2 < graph_e->nodes.size());
n1_uid = n1;
n2_uid = n2;
e_uid = i;
}
};
/** Return the total number of edges in the graph.
*
* Complexity: No more than O(num_nodes() + num_edges()), hopefully less
*/
size_type num_edges() const {
return ei2eu.size();
}
/** Return the edge with index @a i.
* @pre 0 <= @a i < num_edges()
*
* Complexity: No more than O(num_nodes() + num_edges()), hopefully less
*/
Edge edge(size_type i) const {
assert(i < ei2eu.size());
return Edge(this, edges[ei2eu[i]].n1_uid, edges[ei2eu[i]].n2_uid, ei2eu[i]);
}
/** Test whether two nodes are connected by an edge.
* @pre @a a and @a b are valid nodes of this graph
* @return True if for some @a i, edge(@a i) connects @a a and @a b.
*
* Complexity: No more than O(num_nodes() + num_edges()), hopefully less
*/
bool has_edge(const Node& a, const Node& b) const {
assert (has_node(a) && has_node(b));
size_type a_uid = ni2nu[a.index()];
size_type b_uid = ni2nu[b.index()];
std::vector<id_pair> a_edge = adj_uid[a_uid];
for (unsigned int i = 0; i < a_edge.size(); ++i) {
if (a_edge[i].n_uid == b_uid)
return true;
}
return false;
}
/** Add an edge to the graph, or return the current edge if it already exists.
* @pre @a a and @a b are distinct valid nodes of this graph
* @return an Edge object e with e.node1() == @a a and e.node2() == @a b
* @post has_edge(@a a, @a b) == true
* @post If old has_edge(@a a, @a b), new num_edges() == old num_edges().
* Else, new num_edges() == old num_edges() + 1.
*
* Can invalidate edge indexes -- in other words, old edge(@a i) might not
* equal new edge(@a i). Must not invalidate outstanding Edge objects.
*
* Complexity: No more than O(num_nodes() + num_edges()), hopefully less
*/
Edge add_edge(const node_type& a, const node_type& b) {
assert (has_node(a) && has_node(b));
assert (! (a == b));
size_type a_uid = ni2nu[a.index()];
size_type b_uid = ni2nu[b.index()];
std::vector<id_pair> a_edge = adj_uid[a_uid];
for (unsigned int i = 0; i < a_edge.size(); ++i) {
if (a_edge[i].n_uid == b_uid)
return Edge(this, a_uid, b_uid, a_edge[i].e_uid);
}
edge_type new_edge(this, a_uid, b_uid, edges.size());
edges.push_back(EdgeInfo{a_uid, b_uid, edge_value_type()});
ei2eu.push_back(edges.size() - 1);
adj_uid[a_uid].push_back(id_pair{b_uid, (unsigned int)edges.size() - 1});
adj_uid[b_uid].push_back(id_pair{a_uid, (unsigned int)edges.size() - 1});
return new_edge;
}
/** Remove an edge with 2 given nodes in the graph
* @param[in] n1 One node of the target edge
* @param[in] n2 The other node of the target edge
* @result 0 or 1 (0 means the edge is not in the graph
* 1 means the edge is successfully removed)
* @post if @a n1 or @a n2 or the edge constructed by @a n1 and @a n2 is not
* in the graph, 0 is returned;
* if the edge constructed by @a n1 and @a n2 is in the graph,
* 1 is returned,
* the connection of nodes of @a e is deleted in adj_uid,
* ei2eu[k] = e.e_uid,
* for any i, 0 <= i < k, ei2eu[i] is unchanged,
* for any j, k <= j < ei2eu.size()-1, ei2eu[i] = ei2eu[i+1]
* ei2eu[ei2eu.size()-1] is deleted.
* @post for 0 <= i < j < ei2eu.size(), ei2eu[i] < ei2eu[j].
* Complexity: O(num_edges())
* Can invalidate edge indices of the index of @a e and all after that.
*/
size_type remove_edge(const Node& n1, const Node& n2) {
if (!has_edge(n1, n2))
return 0;
return remove_edge(add_edge(n1, n2));
}
/** Remove a given edge in the graph
* @param[in] e The edge that should be removed
* @result 0 or 1 (0 means the edge is not in the graph
* 1 means the edge is successfully removed)
* @post if @a e is not in the graph, 0 is returned;
* if @a e is in the graph, 1 is returned,
* the connection of nodes of @a e is deleted in adj_uid,
* ei2eu[k] = e.e_uid,
* for any i, 0 <= i < k, ei2eu[i] is unchanged,
* for any j, k <= j < ei2eu.size()-1, ei2eu[i] = ei2eu[i+1]
* ei2eu[ei2eu.size()-1] is deleted.
* @post for 0 <= i < j < ei2eu.size(), ei2eu[i] < ei2eu[j].
* Complexity: O(num_edges())
* Can invalidate edge indices of the index of @a e and all after that.
*/
size_type remove_edge(const Edge& e) {
size_type e_uid = e.e_uid;
size_type n1_uid = ni2nu[e.node1().index()];
size_type n2_uid = ni2nu[e.node2().index()];
auto nedges = adj_uid[n1_uid].size();
for (unsigned int i = 0; i < nedges; ++i) {
if (adj_uid[n1_uid][i].n_uid==n2_uid && adj_uid[n1_uid][i].e_uid==e_uid){
adj_uid[n1_uid][i].n_uid = adj_uid[n1_uid][nedges-1].n_uid;
adj_uid[n1_uid][i].e_uid = adj_uid[n1_uid][nedges-1].e_uid;
adj_uid[n1_uid].pop_back();
}
}
if (nedges == adj_uid[n1_uid].size()) // e is not in the graph
return 0;
auto nedges2 = adj_uid[n2_uid].size();
for (unsigned int i = 0; i < nedges2; ++i) {
if (adj_uid[n2_uid][i].n_uid==n1_uid && adj_uid[n2_uid][i].e_uid==e_uid){
adj_uid[n2_uid][i].n_uid = adj_uid[n2_uid][nedges2-1].n_uid;
adj_uid[n2_uid][i].e_uid = adj_uid[n2_uid][nedges2-1].e_uid;
adj_uid[n2_uid].pop_back();
}
}
for (unsigned int i = 0; i < ei2eu.size() - 1; ++i) {
if (ei2eu[i] >= e.e_uid)
ei2eu[i] = ei2eu[i+1];
}
ei2eu.pop_back();
return 1;
}
/** Remove all nodes and edges from this graph.
* @post num_nodes() == 0 && num_edges() == 0
*
* Invalidates all outstanding Node and Edge objects.
*/
void clear() {
adj_uid.clear();
edges.clear();
nodes.clear();
ei2eu.clear();
ni2nu.clear();
}
//
// Node Iterator
//
/** @class Graph::NodeIterator
* @brief Iterator class for nodes. A forward iterator. */
class NodeIterator : private totally_ordered<NodeIterator> {
public:
// These type definitions let us use STL's iterator_traits.
using value_type = Node; // Element type
using pointer = Node*; // Pointers to elements
using reference = Node&; // Reference to elements
using difference_type = std::ptrdiff_t; // Signed difference
using iterator_category = std::input_iterator_tag; // Weak Category, Proxy
/** Construct an invalid NodeIterator. */
NodeIterator() {
graph_ni = nullptr;
}
/** Construct the node that the current iterator points to. */
Node operator*() const {
return Node(graph_ni, graph_ni->ni2nu[curr_idx]);
}
/** Construct a node iterator points to the next one. */
NodeIterator& operator++() {
curr_idx++;
return *this;
}
/** Equivalence check. */
bool operator==(const NodeIterator& ni) const {
return (graph_ni == ni.graph_ni && curr_idx == ni.curr_idx);
}
private:
friend class Graph;
graph_type* graph_ni;
size_type curr_idx;
NodeIterator(const graph_type* graph, size_type i)
: graph_ni(const_cast<graph_type*>(graph)), curr_idx(i) {
}
};
/** construct a node iterator points to the node with index of 0. */
node_iterator node_begin() const {
return node_iterator(this, 0);
}
/** construct a node iterator points to the (last + 1) node */
node_iterator node_end() const {
return node_iterator(this, ni2nu.size());
}
/** Remove the node cooreponding to the given node iterator
* and all the edges that are incident to it.
* @param[in] n_it The node iterator of target node for removal.
* @result 0 or 1 (0 means @a (*n_it) is not in the graph,
* 1 means @a (*n_it) is in the graph).
* @post if @a n is not in the graph, 0 is returned;
* if @a n is in the graph, ni2nu[@a n.index()]=ni2nu[ni2nu.size()-1],
* the last element of ni2nu is pop_backed,
* new ni2nu size = old ni2nu size - 1,
* all the edges that are incident to @a n are removed,
* 1 is returned.
* Complexity: O(num_local_edges * num_edges()).
* Can invalidate iterators [n.index(), end()).
* With the implementation of remove_node(const Node&), only iterators at
* n.index() and end() - 1 would be invalidated.
*
*/
node_iterator remove_node(node_iterator n_it) {
auto node = *n_it;
auto idx = node.index();
remove_node(node);
return node_iterator(this, idx);
}
//
// Incident Iterator
//
/** @class Graph::IncidentIterator
* @brief Iterator class for edges incident to a node. A forward iterator. */
class IncidentIterator : private totally_ordered<IncidentIterator> {
public:
// These type definitions let us use STL's iterator_traits.
using value_type = Edge; // Element type
using pointer = Edge*; // Pointers to elements
using reference = Edge&; // Reference to elements
using difference_type = std::ptrdiff_t; // Signed difference
using iterator_category = std::input_iterator_tag; // Weak Category, Proxy
/** Construct an invalid IncidentIterator. */
IncidentIterator() {
graph_ii = nullptr;
}
/** Construct the edge that the current iterator points to. */
Edge operator*() const {
size_type n1 = graph_ii->ni2nu[node_idx];
return Edge(graph_ii, n1, graph_ii->adj_uid[n1][curr_edge].n_uid,
graph_ii->adj_uid[n1][curr_edge].e_uid);
}
/** Construct an incident iterator points to the next one. */
IncidentIterator& operator++() {
curr_edge++;
return *this;
}
/** Equaivalence check. */
bool operator==(const IncidentIterator& ii) const {
return (graph_ii == ii.graph_ii &&
node_idx == ii.node_idx &&
curr_edge == ii.curr_edge);
}
private:
friend class Graph;
// HW1 #3: YOUR CODE HERE
graph_type* graph_ii;
size_type node_idx;
size_type curr_edge;
IncidentIterator(const graph_type* graph, size_type idx, size_type i)
: graph_ii(const_cast<graph_type*>(graph)), node_idx(idx), curr_edge(i){
}
};
//
// Edge Iterator
//
/** @class Graph::EdgeIterator
* @brief Iterator class for edges. A forward iterator. */
class EdgeIterator : private totally_ordered<EdgeIterator> {
public:
// These type definitions let us use STL's iterator_traits.
using value_type = Edge; // Element type
using pointer = Edge*; // Pointers to elements
using reference = Edge&; // Reference to elements
using difference_type = std::ptrdiff_t; // Signed difference
using iterator_category = std::input_iterator_tag; // Weak Category, Proxy
/** Construct an invalid EdgeIterator. */
EdgeIterator() {
}
/** Construct the edge that current iterator points to. */
Edge operator*() const {
size_type n1 = graph_ei->edges[graph_ei->ei2eu[edge_idx]].n1_uid;
size_type n2 = graph_ei->edges[graph_ei->ei2eu[edge_idx]].n2_uid;
return Edge(graph_ei, n1, n2, graph_ei->ei2eu[edge_idx]);
}
/** Construct a iterator that points to the next one. */
EdgeIterator& operator++() {
edge_idx++;
return *this;
}
/** Equivalence check. */
bool operator==(const EdgeIterator& ei) const {
return (graph_ei == ei.graph_ei &&
edge_idx == ei.edge_idx);
}
private:
friend class Graph;
graph_type* graph_ei;
size_type edge_idx;
EdgeIterator(const graph_type* graph, size_type idx)
: graph_ei(const_cast<graph_type*>(graph)), edge_idx(idx){
}
};
/** Construct an edge iterator points to the edge with index 0. */
edge_iterator edge_begin() const {
return EdgeIterator(this, 0);
}
/** Construct an edge iterator points to the (last + 1) edge. */
edge_iterator edge_end() const {
return EdgeIterator(this, ei2eu.size());
}
/** Remove an edge coorespoping to the given edge iterator in the graph.
* @param[in] e_it The edge iterator of the target edge for removal.
* @result edge iterator of this graph with the same edge index.
* @pre @a e_it is the iterator in this graph.
* @pre @a e_it.edge_idx < ei2eu.size().
* @post new ei2eu.size() <= old ei2eu.size()
* Complexity: O(num_edges()), depends on remove_edge(*e_it).
* Can invalidate edge indices of the index of @a e_it and all after that.
*/
edge_iterator remove_edge(edge_iterator e_it) {
assert(this == e_it.graph_ei);
assert(e_it.edge_idx < ei2eu.size());
size_type idx = e_it.edge_idx;
remove_edge(*e_it);
return edge_iterator(this, idx);
}
private:
struct NodeInfo {
Point position;
size_type idx;
node_value_type node_value;
};
struct EdgeInfo {
size_type n1_uid;
size_type n2_uid;
edge_value_type edge_value;
};
struct id_pair {
size_type n_uid;
size_type e_uid;
};
std::vector<EdgeInfo> edges; // order in e_uid
std::vector<NodeInfo> nodes; // order in n_uid
std::vector<size_type> ei2eu; // e_idx to e_uid
std::vector<size_type> ni2nu; // n_idx to n_uid
std::vector<std::vector<id_pair> > adj_uid; // check edge existence
};
#endif // CME212_GRAPH_HPP
| [
"[email protected]"
] | |
efd56d14d384e33d452a102177ed20ea2ca92d21 | 4de204252e875fd568a0171d369bbe10f634dd75 | /pi2jamma-fe/src/core/Result.hpp | 196afdaf82ce9e4c57120b565d6702892b79995f | [] | no_license | timothyehinds/archadia | 8655734bb52c7d4dbd7bc77ad565ddcc33925e69 | 53afaa99fa7a0c78c3fc91c9cd92545ea7a4fca6 | refs/heads/main | 2023-03-06T03:14:27.202595 | 2021-02-09T06:58:51 | 2021-02-09T06:58:51 | 334,577,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,746 | hpp | #pragma once
#include "debug.hpp"
#include <functional>
#include <string>
#include <variant>
struct Success{};
template<typename T>
class Result final
{
public:
using InfoFunction = std::function<const char*(std::string&)>;
Result(T&&);
Result(const T&);
Result(Result&&) = default;
Result(const Result&) = default;
Result(InfoFunction&& infoFunction);
Result& operator=(const Result& result) = default;
Result& operator=(Result&& rhs) = default;
static Result makeSuccess(T&& t);
static Result makeFailureWithStringLiteral(const char* msg);
static Result makeFailureWithString(std::string msg);
static Result makeFailureNotImplemented();
~Result();
void catastrophic();
const char* getMessage();
const T& operator->();
const T& operator*();
T&& moveResult();
InfoFunction&& moveError();
explicit operator bool();
private:
std::variant<T, InfoFunction> m_variant;
};
template<typename T>
inline Result<T> Result<T>::makeSuccess(T && t)
{
return
Result(std::forward<T&&>(t));
}
template<typename T>
inline Result<T> Result<T>::makeFailureWithStringLiteral(const char* msg)
{
return
Result(
[msg](std::string& workArea) {
return msg;
} );
}
template<typename T>
inline Result<T> Result<T>::makeFailureWithString(std::string msg)
{
return
Result(
[m = std::move(msg)](std::string& workArea) {
return m.c_str();
} );
}
template<typename T>
inline Result<T> Result<T>::makeFailureNotImplemented()
{
return makeFailureWithStringLiteral("Not Implemented.");
}
template<typename T>
inline Result<T>::~Result()
{
}
template<typename T>
inline void Result<T>::catastrophic()
{
ASSERTMSG(*this, getMessage());
}
template<typename T>
inline const char* Result<T>::getMessage()
{
if (std::holds_alternative<InfoFunction>(m_variant))
{
std::string workArea;
return std::get<InfoFunction>(m_variant)(workArea);
}
return "Success";
}
template<typename T>
const T& Result<T>::operator->()
{
return std::get<T>(m_variant);
}
template<typename T>
const T& Result<T>::operator*()
{
return std::get<T>(m_variant);
}
template<typename T>
T&& Result<T>::moveResult()
{
return std::get<T>(m_variant);
}
template<typename T>
typename Result<T>::InfoFunction&& Result<T>::moveError()
{
return std::move(std::get<InfoFunction>(m_variant));
}
template<typename T>
inline Result<T>::Result(T&& t)
: m_variant{std::move(t)}
{
}
template<typename T>
inline Result<T>::Result(const T& t)
: m_variant{t}
{
}
template<typename T>
inline Result<T>::Result(InfoFunction&& infoFunction)
: m_variant(std::move(infoFunction))
{
PRINTFMT("Result error: %s\n", getMessage());
}
template<typename T>
inline Result<T>::operator bool()
{
return std::holds_alternative<T>(m_variant);
} | [
"[email protected]"
] | |
8dea3d1188e670dab94b8d2aa0dcd939aebb6f8e | de54a1dc133971bc48747fa021d61895b029f4bc | /osexp_5/exp5.cpp | 1ef26757e15e16b3acfe4f60991cb5306550bcf0 | [] | no_license | emon100/os_exps | 9a16183c2a99b25770d2ea93c695043219ff81d6 | c5656f9744ecc2bda0e4be3e4a4d927bcc08a5c9 | refs/heads/main | 2023-06-03T08:44:26.704044 | 2021-06-20T09:55:02 | 2021-06-20T09:55:02 | 378,611,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | cpp | #include "unistd.h"
#include <iostream>
#include <cstdlib>
#define TOTAL_INS 10
#define PAGE_NUM_LIMIT 5
#define PAGE_TABLE_LIMIT 3
int access_series[TOTAL_INS];
struct PageTableEntry {
};
void LRU(){
int
}
void CLOCK(){
}
int main(){
for(int i=0;i<10;++i){
access_series[i]=rand()%PAGE_NUM_LIMIT;
std::cout<<access_series[i];
}
LRU();
CLOCK();
}
| [
"[email protected]"
] | |
940500b0f1cf5e650fd91cbe89262f5b4e2a5b6a | 86a489fa8ea5e4f75280c3ff286c74ed4562cf04 | /torch/csrc/autograd/VariableTypeUtils.h | 4082c79c72f8da6039ec9d88fabcda9075ba1b37 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | MarcelRaschke/pytorch-1 | 54de3d5dc2977118cb332a924945226da7ea3572 | 4b9add2dec5903cfc845945636a7ebf8d9e1d9be | refs/heads/master | 2022-07-08T05:45:02.352221 | 2018-11-22T14:45:18 | 2018-11-22T14:45:18 | 157,880,106 | 2 | 0 | NOASSERTION | 2022-01-01T00:57:54 | 2018-11-16T14:41:37 | C++ | UTF-8 | C++ | false | false | 5,974 | h | #include "torch/csrc/autograd/generated/VariableType.h"
#include "torch/csrc/autograd/variable.h"
#include "torch/csrc/autograd/function.h"
#include "torch/csrc/autograd/edge.h"
#include "torch/csrc/autograd/grad_mode.h"
#include "torch/csrc/autograd/saved_variable.h"
#include "torch/csrc/autograd/generated/Functions.h"
#include "torch/csrc/autograd/functions/tensor.h"
#include "torch/csrc/autograd/functions/basic_ops.h"
#include "torch/csrc/jit/tracer.h"
#include "torch/csrc/jit/constants.h"
#include "torch/csrc/jit/symbolic_variable.h"
#include "torch/csrc/jit/ir.h"
#include "torch/csrc/utils/variadic.h"
#include "torch/csrc/autograd/functions/utils.h"
#include <ATen/core/VariableHooksInterface.h>
#include <array>
#include <cstddef>
#include <functional>
#include <initializer_list>
#include <memory>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#ifdef _MSC_VER
#ifdef Type
#undef Type
#endif
#endif
using namespace at;
using namespace torch::autograd::generated;
namespace torch { namespace autograd {
extern std::vector<std::unique_ptr<Type>> type_to_variable_type;
inline void check_inplace(const Tensor& tensor) {
auto& var = static_cast<const Variable&>(tensor);
if (var.requires_grad() && var.is_leaf() && GradMode::is_enabled()) {
AT_ERROR(
"a leaf Variable that requires grad has been used in an in-place operation.");
}
}
inline void throw_error_out_requires_grad(const char* name) {
AT_ERROR(
name, "(): functions with out=... arguments don't support automatic differentiation, "
"but one of the arguments requires grad.");
}
// TODO: Blegh, bare references
inline void rebase_history(Variable& var, std::shared_ptr<Function> grad_fn) {
if (grad_fn && var.defined()) {
grad_fn->add_input_metadata(var);
var.rebase_history({std::move(grad_fn), 0});
}
}
inline void rebase_history(std::vector<Variable>&& vars, std::shared_ptr<Function> grad_fn) {
if (grad_fn) {
for (auto& var : vars) {
if (var.defined()) {
// TODO: eliminate const_cast
auto output_nr = grad_fn->add_input_metadata(var);
var.rebase_history({grad_fn, output_nr});
} else {
grad_fn->add_input_metadata(Function::undefined_input());
}
}
}
}
inline void increment_version(Tensor & t) {
as_variable_ref(t).bump_version();
}
inline bool isFloatingPoint(ScalarType s) {
return s == kFloat || s == kDouble || s == kHalf;
}
struct Flatten : IterArgs<Flatten> {
Flatten(variable_list& out) : out(out) {}
variable_list& out;
void operator()(const at::Tensor& x) { out.emplace_back(x); }
void operator()(at::ArrayRef<at::Tensor> xs) {
out.insert(out.end(), xs.begin(), xs.end());
}
};
template<typename... Args> inline variable_list flatten_tensor_args(Args&&... args) {
variable_list out;
out.reserve(count_tensors(std::forward<Args>(args)...));
Flatten(out).apply(std::forward<Args>(args)...);
return out; // RVO
}
// See NOTE [ Autograd View Variables ] for details.
inline Tensor as_view(const Tensor & base, Tensor tensor, bool is_differentiable = true) {
auto base_var = Variable(base);
if (base_var.is_view()) {
base_var = base_var.base();
}
return make_variable_view(std::move(base_var), std::move(tensor), is_differentiable);
}
// See NOTE [ Autograd View Variables ] for details.
inline std::vector<Tensor> as_view(const Tensor & base, std::vector<Tensor> tensors,
bool is_differentiable = true) {
auto base_var = Variable(base);
if (base_var.is_view()) {
base_var = base_var.base();
}
for(Tensor &tensor : tensors) {
tensor = make_variable_view(base_var, std::move(tensor), is_differentiable);
}
return tensors;
}
inline void check_no_requires_grad(const Tensor& tensor, const char* name) {
auto& var = static_cast<const Variable&>(tensor);
if (var.defined() && var.requires_grad()) {
std::string msg = "the derivative for '";
msg += name;
msg += "' is not implemented";
throw std::runtime_error(msg);
}
}
// Assumed that saved tensor lists are never inplace outputs
inline std::vector<SavedVariable> make_saved_variable_list(TensorList tensors) {
return fmap(tensors, [](const Tensor& tensor) -> SavedVariable {
return SavedVariable{tensor, false /* is output */}; });
}
inline Tensor as_variable(Tensor tensor) {
return make_variable(std::move(tensor), /*requires_grad=*/false);
}
inline std::vector<Tensor> as_variable(TensorList tl) {
return fmap(tl, [](const Tensor& t) -> Tensor {
return make_variable(std::move(t), /*requires_grad=*/false);
});
}
template <typename... Tensors, size_t... Is>
std::tuple<Tensors...> as_variable_impl(
std::tuple<Tensors...> tensors,
Indices<Is...>) {
// Expand the integer parameter pack into a sequence of Variable
// constructions. This turns into (boolean omitted):
// Variable(std::get<0>(tensors)), Variable(std::get<1>(tensors)), ...
return std::tuple<Tensors...>(
as_variable(std::get<Is>(tensors))...);
}
// NB: Because this was not forward declared, recursive std::tuple won't work.
// You can probably rejigger this to make it supported if you really need it.
template <typename... Tensors>
std::tuple<Tensors...> as_variable(std::tuple<Tensors...> tensors) {
// `sizeof...(Tensors)` gets us the size of the `Tensors` parameter pack at
// compile time. We use it to parameterize a `MakeIndices` class, which will
// expand into an Indices object containing the numbers 0 to
// sizeof...(Tensors) - 1.
return as_variable_impl(
tensors, typename MakeIndices<sizeof...(Tensors)>::indices());
}
inline std::vector<std::vector<int64_t>> to_args_sizes(TensorList tensors) {
std::vector<std::vector<int64_t>> args_sizes(tensors.size());
for (size_t i = 0; i < tensors.size(); ++i) {
args_sizes[i] = tensors[i].sizes().vec();
}
return args_sizes;
}
}} // namespace torch::autograd
| [
"[email protected]"
] | |
d055dbbd04ff6b9beca2fbbbea651882446ac94e | aae39e9d635545033ead58137a8348896a1f9ca7 | /TestEnumeratedType.cpp | fcfcce34f85324ec32c6b579370127b7d8dbf34b | [] | no_license | wffett/cpp_exercises | 7b39cde138f307dacf254f3f6a2593ffb9a536df | 0242dc6aa46bf8794a94ba4c1cddd79ae72e2fc3 | refs/heads/master | 2021-10-14T08:17:13.786817 | 2019-02-03T03:40:13 | 2019-02-03T03:40:13 | 69,849,865 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | cpp | #include <iostream>
using namespace std;
void TestEnumeratedType()
{
enum Day {MONDAY =1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY} day;
cout << "Enter a day (1 for Monday, 2 for Tuesday, etc): ";
int dayNumber;
cin >> dayNumber;
switch(dayNumber)
{
case MONDAY:
cout << "Play soccer" << endl;
break;
case TUESDAY:
cout << "Piano lesson" << endl;
break;
case WEDNESDAY:
cout << "Math team" << endl;
break;
default:
cout << "Go houme" << endl;
}
}
| [
"[email protected]"
] | |
ebc5ee85387bc6bbc1059045ecf5e2ca22679dde | df3e0551ed23478ab80fc672dd00952d35ad198d | /Half_pyramid_using_numbers.cpp | c73b5c52c899d839b0611da9e6632565eacc096b | [] | no_license | yashsharm884/C-Placement-Oriented-Work | 3cf4077d751de8ecfbd1847d232889daa9ccd70d | 5370f2eff450d8302139ba30a179424086403670 | refs/heads/master | 2023-05-18T12:39:50.962267 | 2021-06-16T07:48:58 | 2021-06-16T07:48:58 | 376,458,984 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 428 | cpp | /*
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int row;
cin>>row;
for(int i = 1; i <= row; i++) // printing rows.
{
for(int j = 1; j <= i; j++) // print number i in the ith rows ith times.
{
cout<<i<<" ";
}
cout<<endl;
}
return 0;
} | [
"[email protected]"
] | |
a3383f28b91ad8e1e8b0ba3889f46c22572dbc95 | 0abef26a612ddfad627000e3280f310a978e8d04 | /ARPhysics-master/Demo App/Demos/WreckingBall.h | 78863bedca8380f285a6c9b45acf18433f3a19fc | [
"MIT"
] | permissive | AugustRush/2017demo | 98fef3954c325029e65ac48fd29f778869a62af6 | 79070ea13fd9813fb0904511ef89c8f01ff86ef6 | refs/heads/master | 2021-01-20T12:51:52.335872 | 2017-09-21T06:59:58 | 2017-09-21T06:59:58 | 101,727,546 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 608 | h | //
// WreckingBall.h
// Drawing
//
// Created by Adrian Russell on 14/04/2014.
// Copyright (c) 2014 Adrian Russell. All rights reserved.
//
#ifndef __Drawing__WreckingBall__
#define __Drawing__WreckingBall__
#include "PhysicsDemo.h"
class WreckingBall : public PhysicsDemo
{
public:
WreckingBall();
~WreckingBall();
std::string name() { return "Wrecking Ball"; };
void mouseMoved(int x, int y);
void mouseEvent(int button, int state, int x, int y);
protected:
Body *mouseBody;
Spring *mouseSpring;
};
#endif /* defined(__Drawing__WreckingBall__) */
| [
"[email protected]"
] | |
44445c4bac27e7661dc46e4983b33f1554de91cd | 5c609e889a27c711da1ab27e3034e95e012cb1a9 | /linked_queue.h | 124d1ed805ea8937bd19b6df7578cf7dd881ceae | [] | no_license | matheuslc/car-system-2000 | 21abdb2773a979fe628e432d64015bc8895bc99c | f28e7421791b2027157fd29629eb8095140723de | refs/heads/master | 2020-03-12T12:40:11.585980 | 2018-04-25T02:05:32 | 2018-04-25T02:05:32 | 130,623,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | h | // Copyright 2018
#ifndef STRUCTURES_LINKED_QUEUE_H
#define STRUCTURES_LINKED_QUEUE_H
#include <cstdint> // std::size_t
#include <stdexcept> // C++ exceptions
#include "linked_list.h"
template<typename T>
class LinkedQueue {
public:
LinkedQueue(): linkedList_{}
{}
~LinkedQueue() {}
void clear() {
linkedList_.clear();
}
void enqueue(const T& data) {
linkedList_.push_back(data);
}
T dequeue() {
return linkedList_.pop_front();
}
T& front() const {
return linkedList_.at(0);
}
T& back() const {
return linkedList_.at(size()-1);
}
bool empty() const {
return linkedList_.empty();
}
std::size_t size() const {
return linkedList_.size();
}
private:
LinkedList<T> linkedList_;
};
#endif | [
"[email protected]"
] | |
32d914f5aeb6435592339f5560d3b31ae081d6ce | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/CLPCapabilities/UNIX_CLPCapabilities.cpp | 23f216d0c6310ec6a305a72643104b94f7282033 | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,267 | cpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#include "UNIX_CLPCapabilities.h"
#if defined(PEGASUS_OS_HPUX)
# include "UNIX_CLPCapabilities_HPUX.hxx"
# include "UNIX_CLPCapabilities_HPUX.hpp"
#elif defined(PEGASUS_OS_LINUX)
# include "UNIX_CLPCapabilities_LINUX.hxx"
# include "UNIX_CLPCapabilities_LINUX.hpp"
#elif defined(PEGASUS_OS_DARWIN)
# include "UNIX_CLPCapabilities_DARWIN.hxx"
# include "UNIX_CLPCapabilities_DARWIN.hpp"
#elif defined(PEGASUS_OS_AIX)
# include "UNIX_CLPCapabilities_AIX.hxx"
# include "UNIX_CLPCapabilities_AIX.hpp"
#elif defined(PEGASUS_OS_FREEBSD)
# include "UNIX_CLPCapabilities_FREEBSD.hxx"
# include "UNIX_CLPCapabilities_FREEBSD.hpp"
#elif defined(PEGASUS_OS_SOLARIS)
# include "UNIX_CLPCapabilities_SOLARIS.hxx"
# include "UNIX_CLPCapabilities_SOLARIS.hpp"
#elif defined(PEGASUS_OS_ZOS)
# include "UNIX_CLPCapabilities_ZOS.hxx"
# include "UNIX_CLPCapabilities_ZOS.hpp"
#elif defined(PEGASUS_OS_VMS)
# include "UNIX_CLPCapabilities_VMS.hxx"
# include "UNIX_CLPCapabilities_VMS.hpp"
#elif defined(PEGASUS_OS_TRU64)
# include "UNIX_CLPCapabilities_TRU64.hxx"
# include "UNIX_CLPCapabilities_TRU64.hpp"
#else
# include "UNIX_CLPCapabilities_STUB.hxx"
# include "UNIX_CLPCapabilities_STUB.hpp"
#endif
Boolean UNIX_CLPCapabilities::validateKey(CIMKeyBinding &kb) const
{
/* Keys */
//InstanceID
CIMName name = kb.getName();
if (name.equal(PROPERTY_INSTANCE_ID)
)
return true;
return false;
}
void UNIX_CLPCapabilities::setScope(CIMName scope)
{
currentScope = CIMName(scope.getString());
}
void UNIX_CLPCapabilities::setCIMOMHandle(CIMOMHandle &ch)
{
_cimomHandle = ch;
}
| [
"[email protected]"
] | |
009585869e43f99641784e00f6ae7ca6de147991 | 1ad542b1283755b7a92a61290b36b7d728968d9b | /BigIntHomework/bigInt/bigInt/bigInt.h | 782967ca8c2b8251cb6be823197c3b774121e337 | [] | no_license | SheefaliT/DS2700 | dac4afb3d2a84b609e0bd24c9c0629bc805f2ec3 | 7cfae9ac4a0118d598166cd0d5ffe0a5bc3ea30f | refs/heads/master | 2021-01-22T09:12:49.991527 | 2013-12-06T18:04:36 | 2013-12-06T18:04:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,828 | h | #ifndef BIGINT_H
#define BIGINT_H
#include <iostream>
class bigInt
{
public:
//constructors
//default sets it to 0 with an array of size 1
bigInt(); //
//passes in a char array to initialize value
bigInt(const char initialValue []); //
//passes in an integer
bigInt (int initialValue); //
//passes in a double
bigInt (double initialValue); //
//copy constructor
bigInt (const bigInt& toCopyFrom);//
//destructor
~bigInt();
//Getter
//returns a pointer to a COPY of our array of char*'s
char* getBigIntArray() const;//
//operators += -=
void operator += (const bigInt& intToAdd); //
void operator -= (const bigInt& intToSubtract);
void operator =(const bigInt& toEqual);//
//nonmember friends istream and ostream
friend std::istream& operator >>(std::istream& ins, bigInt& target);//
friend std::ostream& operator <<(std::ostream& outs, const bigInt& source);//
private:
//numDigits-- returns current number of digits
//private members
char* bigIntArray; //where all our numbers reside
};
//NONMEMBERS
//operator+
bigInt operator +(const bigInt &firstInt, const bigInt &secondInt); //
//operator-
bigInt operator -(const bigInt &firstInt, const bigInt &secondInt);
//operator==
bool operator ==(const bigInt &firstInt, const bigInt &secondInt);
//operator !=
bool operator !=(const bigInt &firstInt, const bigInt &secondInt);
//operator <=
bool operator <=(const bigInt &firstInt, const bigInt &secondInt);
//operator >=
bool operator >=(const bigInt &firstInt, const bigInt &secondInt);
//operator <
bool operator <(const bigInt &firstInt, const bigInt &secondInt);
//operator >
bool operator >(const bigInt &firstInt, const bigInt &secondInt);
bigInt operator *(const bigInt &firstInt, const bigInt &secondInt);
bigInt operator /(const bigInt &firstInt, const bigInt &secondInt);
#endif | [
"[email protected]"
] | |
b32af5a085ea034c9eff3ea4c1a2e20d971268e3 | 22add52ae44f25c5cd221c7b2807f77b5ac58acf | /V_1.3/App42_Cocos2dX_3.0_SDK/EmailService/App42EmailResponse.cpp | 8af2a6e7439dcf8e94739fedfc6dd882b124c580 | [] | no_license | RajeevRShephertz/App42_Cocos2dX_SDK | ebe97bae17005bec2578c2bca4067cac2c39c345 | 745317a878cd659de7b56ae0654f680fcb5ab184 | refs/heads/master | 2021-01-13T01:58:21.032200 | 2014-04-09T07:38:52 | 2014-04-09T07:38:52 | 18,548,352 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,485 | cpp | //
// App42EmailResponse.cpp
// App42Cocos2dX3.0Sample
//
// Created by Rajeev Ranjan on 08/04/14.
//
//
#include "App42EmailResponse.h"
#include "Common.h"
App42EmailResponse::App42EmailResponse(App42CallBack *pTarget, SEL_App42CallFuncND pSelector)
:App42Response(pTarget,pSelector)
{
}
App42EmailResponse::~App42EmailResponse()
{
}
void App42EmailResponse::onComplete(cocos2d::Node *sender, void *data)
{
App42Response::onComplete(sender, data);
init();
if (_app42Target && _app42Selector)
{
(_app42Target->*_app42Selector)((App42CallBack *)_app42Target, this);
}
}
void App42EmailResponse::init()
{
if(_result != 200)
{
Util::app42Trace("App42EmailResult failed result is %d", _result);
buildErrorMessage();
return;
}
// parse the body
cJSON *ptrBody = cJSON_Parse(_body.c_str());
cJSON* ptrApp42 = Util::getJSONChild("app42", ptrBody);
cJSON* ptrResponse = Util::getJSONChild("response", ptrApp42);
cJSON* ptrEmail = Util::getJSONChild("email", ptrResponse);
if (ptrEmail)
{
from = Util::getJSONString("from", ptrEmail);
to = Util::getJSONString("to", ptrEmail);
subject = Util::getJSONString("subject", ptrEmail);
body = Util::getJSONString("body", ptrEmail);
cJSON* ptrConfigurations = Util::getJSONChild("configurations", ptrEmail);
if(ptrConfigurations)
{
cJSON* ptrConfig = Util::getJSONChild("config", ptrConfigurations);
if (ptrConfig)
{
cJSON* childConfig = ptrConfig;
if(childConfig->type == cJSON_Array)
{
childConfig = childConfig->child;
}
while(childConfig != NULL && childConfig->type == cJSON_Object)
{
App42Configuration config;
config.emailId = Util::getJSONString("emailId", childConfig);
config.host = Util::getJSONString("host", childConfig);
config.ssl = Util::getJSONBool("ssl", childConfig);
config.port = Util::getJSONInt("port", childConfig);
configurationArray.push_back(config);
childConfig = childConfig->next;
}
}
}
}
else
{
setTotalRecords();
}
cJSON_Delete(ptrBody);
} | [
"[email protected]"
] | |
b42d42eea81b381b14eca4c84cdcbf005dce6188 | 575731c1155e321e7b22d8373ad5876b292b0b2f | /examples/native/ios/Pods/boost-for-react-native/boost/spirit/home/karma/auxiliary/attr_cast.hpp | 7a9a82df07a87ed8ba000de87f2dea4ca1b6e2cf | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | Nozbe/zacs | 802a84ffd47413a1687a573edda519156ca317c7 | c3d455426bc7dfb83e09fdf20781c2632a205c04 | refs/heads/master | 2023-06-12T20:53:31.482746 | 2023-06-07T07:06:49 | 2023-06-07T07:06:49 | 201,777,469 | 432 | 10 | MIT | 2023-01-24T13:29:34 | 2019-08-11T14:47:50 | JavaScript | UTF-8 | C++ | false | false | 4,629 | hpp | // Copyright (c) 2001-2011 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(SPIRIT_KARMA_ATTR_CAST_SEP_26_2009_0348PM)
#define SPIRIT_KARMA_ATTR_CAST_SEP_26_2009_0348PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/karma/meta_compiler.hpp>
#include <boost/spirit/home/karma/generator.hpp>
#include <boost/spirit/home/karma/domain.hpp>
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/support/info.hpp>
#include <boost/spirit/home/support/common_terminals.hpp>
#include <boost/spirit/home/karma/detail/attributes.hpp>
#include <boost/spirit/home/support/auxiliary/attr_cast.hpp>
namespace boost { namespace spirit
{
///////////////////////////////////////////////////////////////////////////
// enables attr_cast<>() pseudo generator
template <typename Expr, typename Exposed, typename Transformed>
struct use_terminal<karma::domain
, tag::stateful_tag<Expr, tag::attr_cast, Exposed, Transformed> >
: mpl::true_ {};
}}
namespace boost { namespace spirit { namespace karma
{
#ifndef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
using spirit::attr_cast;
#endif
///////////////////////////////////////////////////////////////////////////
// attr_cast_generator consumes the attribute of subject generator without
// generating anything
///////////////////////////////////////////////////////////////////////////
template <typename Exposed, typename Transformed, typename Subject>
struct attr_cast_generator
: unary_generator<attr_cast_generator<Exposed, Transformed, Subject> >
{
typedef typename result_of::compile<karma::domain, Subject>::type
subject_type;
typedef mpl::int_<subject_type::properties::value> properties;
typedef typename mpl::eval_if<
traits::not_is_unused<Transformed>
, mpl::identity<Transformed>
, traits::attribute_of<subject_type> >::type
transformed_attribute_type;
attr_cast_generator(Subject const& subject)
: subject(subject)
{
// If you got an error_invalid_expression error message here,
// then the expression (Subject) is not a valid spirit karma
// expression.
BOOST_SPIRIT_ASSERT_MATCH(karma::domain, Subject);
}
// If Exposed is given, we use the given type, otherwise all we can do
// is to guess, so we expose our inner type as an attribute and
// deal with the passed attribute inside the parse function.
template <typename Context, typename Unused>
struct attribute
: mpl::if_<traits::not_is_unused<Exposed>, Exposed
, transformed_attribute_type>
{};
template <typename OutputIterator, typename Context, typename Delimiter
, typename Attribute>
bool generate(OutputIterator& sink, Context& ctx, Delimiter const& d
, Attribute const& attr) const
{
typedef traits::transform_attribute<
Attribute const, transformed_attribute_type, domain>
transform;
return compile<karma::domain>(subject).generate(
sink, ctx, d, transform::pre(attr));
}
template <typename Context>
info what(Context& context) const
{
return info("attr_cast"
, compile<karma::domain>(subject).what(context));
}
Subject subject;
};
///////////////////////////////////////////////////////////////////////////
// Generator generator: make_xxx function (objects)
///////////////////////////////////////////////////////////////////////////
template <typename Expr, typename Exposed, typename Transformed
, typename Modifiers>
struct make_primitive<
tag::stateful_tag<Expr, tag::attr_cast, Exposed, Transformed>, Modifiers>
{
typedef attr_cast_generator<Exposed, Transformed, Expr> result_type;
template <typename Terminal>
result_type operator()(Terminal const& term, unused_type) const
{
typedef tag::stateful_tag<
Expr, tag::attr_cast, Exposed, Transformed> tag_type;
using spirit::detail::get_stateful_data;
return result_type(get_stateful_data<tag_type>::call(term));
}
};
}}}
#endif
| [
"[email protected]"
] | |
fb782161281fffa62c38da55716d959a0a5fdde5 | b2301ef8446dd654efda30c5d5373b63e5604fc3 | /src/StringTable.cc | 6b14e97cf1e2140c05389bb29e4f2117cc7208bc | [
"Apache-2.0"
] | permissive | pierotofy/klogo | a29faf797073cded6db1ccd8baee6e2a0a1d24cb | f1924cedcc336522c3a19d5cadf63bf99993d57a | refs/heads/master | 2020-05-26T20:06:48.957930 | 2014-12-03T16:08:23 | 2014-12-03T16:08:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | cc | /*
* StringTable.cc
*
* Created on: Feb 8, 2011
* Author: toffa006
*/
#include "StringTable.hh"
StringTable::StringTable(){
}
void StringTable::Add(const string &key, int token){
assert(!IsEntryInTable(key));
data[key] = new StringTableEntry(key, token);
}
StringTableEntry* StringTable::GetEntry(const string &key){
StringTableEntry *result = data[key];
assert(result != 0);
return result;
}
/* Is an item already in our string table? */
bool StringTable::IsEntryInTable(const string &key){
return (data.count(key) > 0);
}
| [
"[email protected]"
] | |
38f7a7d0ee493a6064afb66faac1ebbcaff0df24 | 8e7359a53b768fa85792234e046e24984b655a75 | /Bronze_Level_Test2/7-5.cpp | 8799c8bc3b7ffcbef3912a2c350a7ea2711f4b03 | [] | no_license | Bachzart/PTA_Practice | dbf053888b40b73ee0ed30a89eff2840e9e8fdfd | d60d6fade38d3272b4dfde9b396d88165d33c9ba | refs/heads/master | 2023-04-03T04:28:33.901914 | 2023-03-19T10:04:27 | 2023-03-19T10:04:27 | 193,300,567 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 253 | cpp | #include <cstdio>
#include <cmath>
int main() {
double weight, height, res;
scanf("%lf %lf", &weight, &height);
res = weight / pow(height, 2);
printf("%.1lf\n", res);
if(res > 25) printf("PANG");
else printf("Hai Xing");
return 0;
}
| [
"[email protected]"
] | |
efe9f0b3d1b987740ad68a3d0cb9bc38c2d91e40 | 8654435d89790e32f8e4c336e91f23250da0acb0 | /bullet3/src/BulletCollision/BroadphaseCollision/btBroadphaseProxy.cpp | 632c478547ab52cda7552cd97e4ec747dd0690ea | [
"Zlib"
] | permissive | takamtd/deepmimic | 226ca68860e5ef206f50d77893dd19af7ac40e46 | b0820fb96ee76b9219bce429fd9b63de103ba40a | refs/heads/main | 2023-05-09T16:48:16.554243 | 2021-06-07T05:04:47 | 2021-06-07T05:04:47 | 373,762,616 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,188 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btBroadphaseProxy.h"
BT_NOT_EMPTY_FILE // fix warning LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
| [
"[email protected]"
] | |
a6f524ff8354db9a9c6c32940609b42947225a97 | d7dce7d8cf9cc805f982d1b84765546f7349887b | /src/stats/nas_stats_vlan_subintf.cpp | 550f16c63d9a10cbe3a3d591795a6a716f87108e | [
"CC-BY-4.0"
] | permissive | Tejaswi-Goel/opx-nas-interface | 07a5a7de8bf1a6ddc918b7b72abacdcc00d9380f | 56417817984e3f0a0bed66e2477fe71efb44cfc6 | refs/heads/master | 2020-04-09T20:31:06.544148 | 2018-12-13T22:10:22 | 2018-12-13T22:10:22 | 160,576,265 | 0 | 0 | null | 2018-12-05T20:44:17 | 2018-12-05T20:44:16 | null | UTF-8 | C++ | false | false | 6,940 | cpp | /*
* Copyright (c) 2018 Dell Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
/*
* filename: nas_stats_vlan_subintf.cpp
*/
#include "dell-base-if.h"
#include "dell-interface.h"
#include "ietf-interfaces.h"
#include "interface/nas_interface_map.h"
#include "hal_if_mapping.h"
#include "interface/nas_interface_vlan.h"
#include "cps_api_key.h"
#include "cps_api_object_key.h"
#include "cps_class_map.h"
#include "cps_api_operation.h"
#include "event_log.h"
#include "nas_ndi_plat_stat.h"
#include "nas_stats.h"
#include "nas_ndi_vlan.h"
#include "ds_common_types.h"
#include "nas_switch.h"
#include "interface_obj.h"
#include "nas_ndi_1d_bridge.h"
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <stdint.h>
#include <time.h>
static const auto vlan_subintf_stat_ids = new std::vector<ndi_stat_id_t> {
DELL_IF_IF_INTERFACES_STATE_INTERFACE_STATISTICS_IN_PKTS,
DELL_IF_IF_INTERFACES_STATE_INTERFACE_STATISTICS_OUT_PKTS,
IF_INTERFACES_STATE_INTERFACE_STATISTICS_IN_OCTETS,
IF_INTERFACES_STATE_INTERFACE_STATISTICS_OUT_OCTETS
};
static bool _fill_vlan_sub_intf_info(cps_api_object_t obj, NAS_VLAN_INTERFACE * &vlan_obj,
interface_ctrl_t & intf_ctrl){
cps_api_object_attr_t _if_name_attr = cps_api_get_key_data(obj,IF_INTERFACES_STATE_INTERFACE_NAME);
if(!_if_name_attr){
_if_name_attr = cps_api_get_key_data(obj,DELL_IF_CLEAR_COUNTERS_INPUT_INTF_CHOICE_IFNAME_CASE_IFNAME);
}
if(!_if_name_attr){
EV_LOGGING(INTERFACE,ERR,"NAS-STAT","No Interface name passed to get vlan sub interface stat");
return false;
}
const char * _if_name = (const char *)cps_api_object_attr_data_bin(_if_name_attr);
std::string vlan_name = std::string(_if_name);
vlan_obj = dynamic_cast<NAS_VLAN_INTERFACE *>(nas_interface_map_obj_get(vlan_name));
if(!vlan_obj){
EV_LOGGING(INTERFACE,ERR,"NAS-VLAN-SUB-INTF-STAT","No object for vlan sub intf %s exist",_if_name);
return false;
}
memset(&intf_ctrl, 0, sizeof(interface_ctrl_t));
intf_ctrl.q_type = HAL_INTF_INFO_FROM_IF_NAME;
memcpy(intf_ctrl.if_name,vlan_obj->parent_intf_name.c_str(),sizeof(intf_ctrl.if_name));
if (dn_hal_get_interface_info(&intf_ctrl) != STD_ERR_OK) {
EV_LOGGING(INTERFACE,ERR,"NAS-STAT","Failed to find interface information for bridge %s",_if_name);
return false;
}
return true;
}
static cps_api_return_code_t if_stats_get (void * context, cps_api_get_params_t * param,
size_t ix) {
cps_api_object_t obj = cps_api_object_list_get(param->filters,ix);
NAS_VLAN_INTERFACE *vlan_obj=nullptr;
interface_ctrl_t intf_ctrl;
if(!_fill_vlan_sub_intf_info(obj,vlan_obj,intf_ctrl)){
return cps_api_ret_code_ERR;
}
uint64_t stat_val[vlan_subintf_stat_ids->size()];
if ((intf_ctrl.int_type == nas_int_type_PORT)){
if(ndi_bridge_port_stats_get(intf_ctrl.npu_id,intf_ctrl.port_id,vlan_obj->vlan_id,
(ndi_stat_id_t *)&vlan_subintf_stat_ids->at(0),
stat_val,vlan_subintf_stat_ids->size()) != STD_ERR_OK) {
EV_LOGGING(INTERFACE,ERR,"NAS-STAT","Failed to get bridge stat for %s",vlan_obj->if_name.c_str());
return cps_api_ret_code_ERR;
}
} else if ((intf_ctrl.int_type == nas_int_type_LAG)){
if(ndi_lag_bridge_port_stats_get(intf_ctrl.npu_id,intf_ctrl.lag_id,vlan_obj->vlan_id,
(ndi_stat_id_t *)&vlan_subintf_stat_ids->at(0),
stat_val,vlan_subintf_stat_ids->size()) != STD_ERR_OK) {
EV_LOGGING(INTERFACE,ERR,"NAS-STAT","Failed to get bridge stat for %s",vlan_obj->if_name.c_str());
return cps_api_ret_code_ERR;
}
}
cps_api_object_t _r_obj = cps_api_object_list_create_obj_and_append(param->list);
if(_r_obj == nullptr){
EV_LOGGING(INTERFACE,ERR,"NAS-STAT","Failed to allocate object memory");
return cps_api_ret_code_ERR;
}
for(unsigned int ix = 0 ; ix < vlan_subintf_stat_ids->size() ; ++ix ){
cps_api_object_attr_add_u64(_r_obj, vlan_subintf_stat_ids->at(ix), stat_val[ix]);
}
cps_api_object_attr_add_u32(_r_obj,DELL_BASE_IF_CMN_IF_INTERFACES_STATE_INTERFACE_STATISTICS_TIME_STAMP,time(NULL));
return cps_api_ret_code_OK;
}
cps_api_return_code_t nas_vlan_sub_intf_stat_clear(cps_api_object_t obj){
NAS_VLAN_INTERFACE * vlan_obj=nullptr;
interface_ctrl_t intf_ctrl;
if(!_fill_vlan_sub_intf_info(obj,vlan_obj,intf_ctrl)){
return cps_api_ret_code_ERR;
}
if ((intf_ctrl.int_type == nas_int_type_PORT)){
if(ndi_bridge_port_stats_clear(intf_ctrl.npu_id,intf_ctrl.port_id,vlan_obj->vlan_id,
(ndi_stat_id_t *)&vlan_subintf_stat_ids->at(0),
vlan_subintf_stat_ids->size()) != STD_ERR_OK) {
EV_LOGGING(INTERFACE,ERR,"NAS-STAT","Failed to clear stat for %s",vlan_obj->if_name.c_str());
return cps_api_ret_code_ERR;
}
}
else if ((intf_ctrl.int_type == nas_int_type_LAG)){
if(ndi_lag_bridge_port_stats_clear(intf_ctrl.npu_id,intf_ctrl.lag_id,vlan_obj->vlan_id,
(ndi_stat_id_t *)&vlan_subintf_stat_ids->at(0),
vlan_subintf_stat_ids->size()) != STD_ERR_OK) {
EV_LOGGING(INTERFACE,ERR,"NAS-STAT","Failed to clear stat for %s",vlan_obj->if_name.c_str());
return cps_api_ret_code_ERR;
}
}
return cps_api_ret_code_OK;
}
static cps_api_return_code_t if_stats_set (void * context, cps_api_transaction_params_t * param,
size_t ix) {
return cps_api_ret_code_ERR;
}
t_std_error nas_stats_vlan_sub_intf_init(cps_api_operation_handle_t handle) {
if (intf_obj_handler_registration(obj_INTF_STATISTICS, nas_int_type_VLANSUB_INTF,
if_stats_get, if_stats_set) != STD_ERR_OK) {
EV_LOG(ERR,INTERFACE, 0,"NAS-STAT", "Failed to register vlab sub interface stats CPS handler");
return STD_ERR(INTERFACE,FAIL,0);
}
return STD_ERR_OK;
}
| [
"[email protected]"
] | |
817df9954f35f34df66573473a22c8d7248b6772 | 68fc9340d24679e4fa480ef156d4899cf97b0e27 | /src/websocketpp_02/test/basic/uri_perf.cpp | 0c621f5b821c0f52303aeb2739b2f7f153acaecf | [
"BSD-3-Clause",
"ISC",
"MIT-Wu",
"MIT",
"BSL-1.0"
] | permissive | mtrippled/rippled | 74bd45f1f3a2ede0a63b7b5e772ab94ef9cdad11 | 7bb4ff901e8b255214b3a139f557632507c7e2a2 | refs/heads/develop | 2023-08-26T11:40:40.412094 | 2015-11-13T05:55:48 | 2015-11-13T05:55:48 | 21,549,222 | 0 | 1 | NOASSERTION | 2021-11-09T21:27:19 | 2014-07-06T21:44:01 | C++ | UTF-8 | C++ | false | false | 2,415 | cpp | /*
* Copyright (c) 2011, Peter Thorson. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the WebSocket++ Project 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 PETER THORSON BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <boost/date_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include "../../src/uri.hpp"
int main() {
boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time();
long m = 100000;
long n = 3;
for (long i = 0; i < m; i++) {
websocketpp::uri uri1("wss://thor-websocket.zaphoyd.net:9002/foo/bar/baz?a=b&c=d");
websocketpp::uri uri2("ws://[::1]");
websocketpp::uri uri3("ws://localhost:9000/chat");
}
boost::posix_time::ptime end = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_period period(start,end);
int ms = period.length().total_milliseconds();
std::cout << "Created " << m*n << " URIs in " << ms << "ms" << " (" << (m*n)/(ms/1000.0) << "/s)" << std::endl;
}
| [
"[email protected]"
] | |
d5df37605048991b8da31ab653e68d68b518e7d9 | 107eac33c4043e83b2e5de06d5b39d40ecdb1c92 | /src/player/Player.hpp | 47ee69104a520061865e6ae8d54622598701ba75 | [
"MIT"
] | permissive | acupoftee/Peace-Of-Mind | 755c07d442802a1071c46edaad8e55fa02fd95da | b547bbf988f5d022d517832d43f94ea46da1209c | refs/heads/master | 2021-07-09T15:41:01.141164 | 2017-10-09T00:28:57 | 2017-10-09T00:28:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | hpp | #pragma once
#include <SFML/System.hpp>
#include "map/data/BlockDataBase.hpp"
#include "map/MapBase.hpp"
#include "Camera.hpp"
class Game;
class Player {
public:
Player(Vec3 position, MapBase* map, const Game* const game);
void update(float delta);
Camera getCam();
private:
void updateMouse(float delta);
void updateKeyboard(float delta);
void breakBlock();
void pushBlock(BlockId block);
MapBase* m_map;
Vec3 m_velocity;
Vec3 m_position, m_rotation;
Vec3 m_camPos;
const Game* const m_game;
};
| [
"[email protected]"
] | |
223dacf461594906dbe9be18d169a94f27090e50 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /vod/src/v20180717/model/DescribeImageReviewUsageDataResponse.cpp | 499ed87d33fa6fc2866cb3305c0f7668dbcc28c3 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 4,906 | cpp | /*
* 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.
*/
#include <tencentcloud/vod/v20180717/model/DescribeImageReviewUsageDataResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Vod::V20180717::Model;
using namespace std;
DescribeImageReviewUsageDataResponse::DescribeImageReviewUsageDataResponse() :
m_imageReviewUsageDataSetHasBeenSet(false)
{
}
CoreInternalOutcome DescribeImageReviewUsageDataResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("ImageReviewUsageDataSet") && !rsp["ImageReviewUsageDataSet"].IsNull())
{
if (!rsp["ImageReviewUsageDataSet"].IsArray())
return CoreInternalOutcome(Core::Error("response `ImageReviewUsageDataSet` is not array type"));
const rapidjson::Value &tmpValue = rsp["ImageReviewUsageDataSet"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
ImageReviewUsageDataItem item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_imageReviewUsageDataSet.push_back(item);
}
m_imageReviewUsageDataSetHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string DescribeImageReviewUsageDataResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_imageReviewUsageDataSetHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ImageReviewUsageDataSet";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_imageReviewUsageDataSet.begin(); itr != m_imageReviewUsageDataSet.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
vector<ImageReviewUsageDataItem> DescribeImageReviewUsageDataResponse::GetImageReviewUsageDataSet() const
{
return m_imageReviewUsageDataSet;
}
bool DescribeImageReviewUsageDataResponse::ImageReviewUsageDataSetHasBeenSet() const
{
return m_imageReviewUsageDataSetHasBeenSet;
}
| [
"[email protected]"
] | |
ada1ea70e1307c2e0fb2c1bcbe7c774ba0412a13 | 9aadef0cc641757f4ce18588ee639bf2f211f569 | /src/serialize/src/SerializerInput.h | 32122bb5323caa2d2e96c4ca1049387d1a398eac | [
"BSD-3-Clause"
] | permissive | bcumming/mini-stencil | 525d0f82f3166c67cfa5984b8f12687ef3771358 | 48a40ddd0bc04c8306184659b3b67c0be338e039 | refs/heads/master | 2020-08-04T22:35:14.930495 | 2013-11-21T15:49:21 | 2013-11-21T15:49:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 976 | h | // Created by Andrea Arteaga, MeteoSwiss
// Email: [email protected]
// January 2013
#pragma once
#include "SavePoint.h"
class Serializer;
class SerializerInput
{
public:
/**
* Default constructor
*/
SerializerInput() { }
/**
* Copy constructor
*/
SerializerInput(const SerializerInput& other)
{
*this = other;
}
/**
* Assignment operator
*/
SerializerInput& operator=(const SerializerInput& other)
{
pSerializer_ = other.pSerializer_;
savePoint_ = other.savePoint_;
return *this;
}
inline void Init(Serializer& serializer, std::string savePointName);
inline void set_SavePoint(const SavePoint& other) { savePoint_ = other; }
inline SerializerInput& operator>> (const MetaInfo& info);
template<typename TDataField>
inline SerializerInput& operator>> (TDataField& field);
private:
SavePoint savePoint_;
Serializer* pSerializer_;
};
| [
"[email protected]"
] | |
57546e8fafa274f175a23736818c0ed5ba0ef472 | 8f38a7282e63937602bf5cf3366c6f5ec6ba80c7 | /main.cpp | 9f40bd756f18237f014d22998a31cc1343bb79f3 | [] | no_license | wrlife/Colvis | 921938a66efe50780e0a6983ad625c9dbf8e7694 | 3dcc91841c46342285d7c02e8d26851892b6733d | refs/heads/master | 2021-05-03T16:22:55.252683 | 2017-05-05T18:40:26 | 2017-05-05T18:40:26 | 69,426,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | cpp | #include <vtkAutoInit.h>
#include "mainwindow.h"
#include <QApplication>
#include <QVTKWidget.h>
VTK_MODULE_INIT(vtkRenderingOpenGL2);
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
//w.resize(800,600);
w.show();
w.addlight();
return a.exec();
}
| [
"[email protected]"
] | |
5abbea681fda06eb0db572a1a5e4f15f180db780 | f128a6e6c7b64dbd74c6efda530dbb556d586439 | /Advanced/WaterMirror/C++/IslandMaterial.cpp | 380e944681452a40dfd6d246146d4b91ddfb7609 | [] | no_license | Houssk/Synthese-d-images-avec-OpenGL | 0b87b20906caf71c602fed78ece4a154d4f4a586 | b49ae26985d7cd49be959bd05049de9b426b64db | refs/heads/master | 2020-08-04T23:05:06.643696 | 2018-12-04T11:05:11 | 2018-12-04T11:05:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,267 | cpp | #include <GL/glew.h>
#include <GL/gl.h>
#include <iostream>
#include <sstream>
#include <utils.h>
#include <IslandMaterial.h>
/**
* Cette fonction définit la classe IslandMaterial pour dessiner le terrain.
* @param heightmap : nom d'un fichier image contenant le relief
* @param hmax : float qui donne la hauteur relative du terrain par rapport à ses dimensions, ex: 0.4
* @param delta : float qui indique la distance pour calculer la normale, dépend de la résolution de l'image
*/
IslandMaterial::IslandMaterial(std::string heightmap, float hmax, float delta) : Material("IslandMaterial")
{
// charger la texture donnant le relief
m_TxHeightmap = new Texture2D(heightmap);
m_TxHeightmapLoc = -1;
// charger les textures diffuses
m_TxDiffuse1 = new Texture2D("data/models/TerrainHM/terrain_tx.jpg", GL_LINEAR, GL_REPEAT);
m_TxDiffuse1Loc = -1;
m_TxDiffuse2 = new Texture2D("data/textures/sols/79798.jpg", GL_LINEAR, GL_REPEAT);
m_TxDiffuse2Loc = -1;
m_HMax = hmax;
m_Delta = delta;
// compiler le shader
compileShader();
}
/**
* retourne le source du Vertex Shader
*/
std::string IslandMaterial::getVertexShader()
{
std::ostringstream srcVertexShader;
srcVertexShader << "#version 300 es\n";
srcVertexShader << "\n";
srcVertexShader << "// attributs de sommets\n";
srcVertexShader << "in vec3 glVertex;\n";
srcVertexShader << "in vec2 glTexCoord;\n";
srcVertexShader << "\n";
srcVertexShader << "// paramètres du matériau\n";
srcVertexShader << "const float delta = "<<m_Delta<<";\n";
srcVertexShader << "const float hmax = "<<m_HMax<<";\n";
srcVertexShader << "uniform sampler2D txHeightmap;\n";
srcVertexShader << "\n";
srcVertexShader << "// interpolation pour le fragment shader\n";
srcVertexShader << "out vec2 frgTexCoord;\n";
srcVertexShader << "out float frgElevation;\n";
srcVertexShader << "out vec4 frgPosition;\n";
srcVertexShader << "out vec3 frgNormal;\n";
srcVertexShader << "\n";
srcVertexShader << "// matrices de transformation\n";
srcVertexShader << "uniform mat4 mat4ModelView;\n";
srcVertexShader << "uniform mat4 mat4Projection;\n";
srcVertexShader << "uniform mat3 mat3Normal;\n";
srcVertexShader << "\n";
srcVertexShader << "void main()\n";
srcVertexShader << "{\n";
srcVertexShader << " // transformation du point par la heightmap\n";
srcVertexShader << " vec3 position = glVertex;\n";
srcVertexShader << " float height = texture(txHeightmap, glTexCoord).g * hmax;\n";
srcVertexShader << " position.y += height;\n";
srcVertexShader << " frgElevation = position.y;\n";
srcVertexShader << " // position du fragment par rapport à la caméra et projection écran\n";
srcVertexShader << " frgPosition = mat4ModelView * vec4(position, 1.0);\n";
srcVertexShader << " gl_Position = mat4Projection * frgPosition;\n";
srcVertexShader << " // détermination de la normale\n";
srcVertexShader << " float heightN = texture(txHeightmap, glTexCoord+vec2(0.0,+delta)).g;\n";
srcVertexShader << " float heightS = texture(txHeightmap, glTexCoord+vec2(0.0,-delta)).g;\n";
srcVertexShader << " float heightE = texture(txHeightmap, glTexCoord+vec2(+delta,0.0)).g;\n";
srcVertexShader << " float heightW = texture(txHeightmap, glTexCoord+vec2(-delta,0.0)).g;\n";
srcVertexShader << " float dX = (heightE - heightW) * hmax;\n";
srcVertexShader << " float dZ = (heightS - heightN) * hmax;\n";
srcVertexShader << " vec3 N = vec3(-dX, 2.0*delta, -dZ);\n";
srcVertexShader << " frgNormal = mat3Normal * N;\n";
srcVertexShader << " // coordonnées de texture\n";
srcVertexShader << " frgTexCoord = glTexCoord;\n";
srcVertexShader << "}";
return srcVertexShader.str();
}
/**
* retourne le source du Fragment Shader
*/
std::string IslandMaterial::getFragmentShader()
{
std::ostringstream srcFragmentShader;
srcFragmentShader.setf(std::ios::fixed, std::ios::floatfield);
srcFragmentShader << "#version 300 es\n";
srcFragmentShader << "\n";
srcFragmentShader << "// textures diffuses\n";
srcFragmentShader << "uniform sampler2D txDiffuse1;\n";
srcFragmentShader << "uniform sampler2D txDiffuse2;\n";
srcFragmentShader << "\n";
srcFragmentShader << "// données interpolées venant du vertex shader\n";
srcFragmentShader << "precision mediump float;\n";
srcFragmentShader << "in vec2 frgTexCoord;\n";
srcFragmentShader << "in float frgElevation;\n";
srcFragmentShader << "in vec4 frgPosition;\n";
srcFragmentShader << "in vec3 frgNormal;\n";
srcFragmentShader << "out vec4 glFragData[4];\n";
srcFragmentShader << "\n";
srcFragmentShader << "// plan de coupe\n";
srcFragmentShader << "uniform vec4 ClipPlane;\n";
srcFragmentShader << "\n";
srcFragmentShader << "void main()\n";
srcFragmentShader << "{\n";
srcFragmentShader << " // plan de coupe\n";
srcFragmentShader << " if (dot(frgPosition, ClipPlane) < 0.0) discard;\n";
srcFragmentShader << "\n";
srcFragmentShader << " // couleur diffuse\n";
srcFragmentShader << " vec4 Kd1 = texture(txDiffuse1, frgTexCoord);\n";
srcFragmentShader << " vec4 Kd2 = texture(txDiffuse2, frgTexCoord * 4.0);\n";
srcFragmentShader << " vec4 Kd = mix(Kd2, Kd1, smoothstep(-0.05, 0.05, frgElevation));\n";
srcFragmentShader << "\n";
srcFragmentShader << " // calcul du vecteur normal\n";
srcFragmentShader << " vec3 N = normalize(frgNormal);\n";
srcFragmentShader << "\n";
srcFragmentShader << " // remplir les buffers MRT avec les informations nécessaires pour Phong plus tard\n";
srcFragmentShader << " glFragData[0] = Kd;\n";
srcFragmentShader << " glFragData[1] = vec4(0.0);\n";
srcFragmentShader << " glFragData[2] = vec4(frgPosition.xyz, 1.0);\n";
srcFragmentShader << " glFragData[3] = vec4(N, 0.0);\n";
srcFragmentShader << "}";
return srcFragmentShader.str();
}
/**
* recompile le shader du matériau
*/
void IslandMaterial::compileShader()
{
// appeler la méthode de la superclasse
Material::compileShader();
// déterminer où sont les variables uniform
m_TxDiffuse1Loc = glGetUniformLocation(m_ShaderId, "txDiffuse1");
m_TxDiffuse2Loc = glGetUniformLocation(m_ShaderId, "txDiffuse2");
m_TxHeightmapLoc = glGetUniformLocation(m_ShaderId, "txHeightmap");
}
/**
* crée et retourne un VBOset pour ce matériau, afin qu'il soit rempli par un maillage
* @return le VBOset du matériau
*/
VBOset* IslandMaterial::createVBOset()
{
// créer le VBOset et spécifier les noms des attribute nécessaires à ce matériau
VBOset* vboset = Material::createVBOset();
vboset->addAttribute(MeshVertex::ID_ATTR_TEXCOORD, Utils::VEC2, "glTexCoord");
return vboset;
}
/**
* Cette méthode active le matériau : met en place son shader,
* fournit les variables uniform qu'il demande
* @param mat4Projection : mat4 contenant la projection
* @param mat4ModelView : mat4 contenant la transformation vers la caméra
*/
void IslandMaterial::enable(mat4 mat4Projection, mat4 mat4ModelView)
{
// appeler la méthode de la superclasse
Material::enable(mat4Projection, mat4ModelView);
// activer la texture d'altitude sur l'unité 0
m_TxHeightmap->setTextureUnit(GL_TEXTURE0, m_TxHeightmapLoc);
// activer la texture diffuse1 sur l'unité 1
m_TxDiffuse1->setTextureUnit(GL_TEXTURE1, m_TxDiffuse1Loc);
// activer la texture diffuse2 sur l'unité 2
m_TxDiffuse2->setTextureUnit(GL_TEXTURE2, m_TxDiffuse2Loc);
}
/**
* Cette méthode désactive le matériau
* NB: le shader doit être activé
*/
void IslandMaterial::disable()
{
// désactiver les textures
m_TxHeightmap->setTextureUnit(GL_TEXTURE0);
m_TxDiffuse1->setTextureUnit(GL_TEXTURE1);
m_TxDiffuse2->setTextureUnit(GL_TEXTURE2);
// appeler la méthode de la superclasse
Material::disable();
}
/**
* Cette méthode supprime les ressources allouées
*/
IslandMaterial::~IslandMaterial()
{
delete m_TxDiffuse1;
delete m_TxDiffuse2;
delete m_TxHeightmap;
}
| [
"[email protected]"
] | |
dbc108a742bfe6f5172815e4248ebe860acaa6dc | e8f36f48a12b0f1fb88ae59cb28c15a6470d6ee2 | /src/program/game/ShadowMap.cpp | 4f7878fbb905427b13f2a99744440e13ea23f208 | [] | no_license | Adanos020/PAhAom-Old | f13ec29cde66669cd6d43599ab49b2bb29082ce1 | 610ccafaf39aa4c97a0a2268234e1418f28b0a85 | refs/heads/master | 2021-06-11T14:21:59.213500 | 2017-02-20T22:18:56 | 2017-02-20T22:18:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,205 | cpp | /**
* @file src/program/game/ShadowMap.cpp
* @author Adam 'Adanos' Gąsior
* Used library: SFML
*/
#include <iostream>
#include "../funcs/files.hpp"
#include "../Resources.hpp"
#include "ShadowMap.hpp"
namespace rr
{
ShadowMap::ShadowMap(sf::Vector2i size) :
m_size(size)
{
m_shadowImage.create(m_size.x*3, m_size.y*3, sf::Color::Black);
m_shadowTexture.loadFromImage(m_shadowImage);
m_shadowTexture.setSmooth(true);
m_shadowSprite.resize(4);
m_shadowSprite.setPrimitiveType(sf::Quads);
m_shadowSprite[0].position = sf::Vector2f(0 , 0 );
m_shadowSprite[1].position = sf::Vector2f(80*size.x, 0 );
m_shadowSprite[2].position = sf::Vector2f(80*size.x, 80*size.y);
m_shadowSprite[3].position = sf::Vector2f(0 , 80*size.y);
m_shadowSprite[0].texCoords = sf::Vector2f(0 , 0 );
m_shadowSprite[1].texCoords = sf::Vector2f(3*size.x, 0 );
m_shadowSprite[2].texCoords = sf::Vector2f(3*size.x, 3*size.y);
m_shadowSprite[3].texCoords = sf::Vector2f(0 , 3*size.y);
for (int i = 0; i < m_size.x*m_size.y; ++i)
{
m_discovered[i] = false;
}
for (int i = 0; i < m_size.x*m_size.y*9; ++i)
{
m_cellIDs[i] = 0;
}
}
bool
ShadowMap::isFilled(int x, int y, unsigned char id) const
{
if ( x < 0 || x > m_size.x-1
|| y < 0 || y > m_size.y-1
) return false;
int tx = 3*x, ty = 3*y;
bool filled = true;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
if (m_cellIDs[tx+i + (ty+j)*m_size.x*3] == id)
{
filled = false;
break;
}
}
if (!filled)
break;
}
return filled;
}
void
ShadowMap::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.texture = &m_shadowTexture;
target.draw(m_shadowSprite, states);
}
void
ShadowMap::setLit(int x, int y)
{
m_discovered[x + y*m_size.x] = true;
int tx = 3*x + 1, ty = 3*y + 1;
m_cellIDs[tx + ty*m_size.x*3] = 2;
m_lastlyLit.push_back(sf::Vector2i(tx, ty));
if (x < m_size.x-1)
{
if (y > 0)
{
if (m_cellIDs[tx+3 + (ty-3)*m_size.x*3] == 2) // TOP RIGHT
{
m_cellIDs[tx+1 + (ty-1)*m_size.x*3] = 2;
m_cellIDs[tx+1 + ( ty )*m_size.x*3] = 2;
m_cellIDs[ tx + (ty-1)*m_size.x*3] = 2;
m_cellIDs[tx+2 + (ty-2)*m_size.x*3] = 2;
m_lastlyLit.push_back(sf::Vector2i(tx+1, ty-1));
m_lastlyLit.push_back(sf::Vector2i(tx+1, ty ));
m_lastlyLit.push_back(sf::Vector2i( tx , ty-1));
m_lastlyLit.push_back(sf::Vector2i(tx+2, ty-2));
}
}
if (y < m_size.y-1)
{
if (m_cellIDs[tx+3 + (ty+3)*m_size.x*3] == 2) // BOTTOM RIGHT
{
m_cellIDs[tx+1 + (ty+1)*m_size.x*3] = 2;
m_cellIDs[tx+1 + ( ty )*m_size.x*3] = 2;
m_cellIDs[ tx + (ty+1)*m_size.x*3] = 2;
m_cellIDs[tx+2 + (ty+2)*m_size.x*3] = 2;
m_lastlyLit.push_back(sf::Vector2i(tx+1, ty+1));
m_lastlyLit.push_back(sf::Vector2i(tx+1, ty ));
m_lastlyLit.push_back(sf::Vector2i( tx , ty+1));
m_lastlyLit.push_back(sf::Vector2i(tx+2, ty+2));
}
}
if (m_cellIDs[tx+3 + ty*m_size.x*3] == 2) // RIGHT
{
m_cellIDs[tx+1 + ty*m_size.x*3] = 2;
m_cellIDs[tx+2 + ty*m_size.x*3] = 2;
m_lastlyLit.push_back(sf::Vector2i(tx+1, ty));
m_lastlyLit.push_back(sf::Vector2i(tx+2, ty));
}
}
if (x > 0)
{
if (y > 0)
{
if (m_cellIDs[tx-3 + (ty-3)*m_size.x*3] == 2) // TOP LEFT
{
m_cellIDs[tx-1 + (ty-1)*m_size.x*3] = 2;
m_cellIDs[tx-1 + ( ty )*m_size.x*3] = 2;
m_cellIDs[ tx + (ty-1)*m_size.x*3] = 2;
m_cellIDs[tx-2 + (ty-2)*m_size.x*3] = 2;
m_lastlyLit.push_back(sf::Vector2i(tx-1, ty-1));
m_lastlyLit.push_back(sf::Vector2i(tx-1, ty ));
m_lastlyLit.push_back(sf::Vector2i( tx , ty-1));
m_lastlyLit.push_back(sf::Vector2i(tx-2, ty-2));
}
}
if (y < m_size.y-1)
{
if (m_cellIDs[tx-3 + (ty+3)*m_size.x*3] == 2) // BOTTOM LEFT
{
m_cellIDs[tx-1 + (ty+1)*m_size.x*3] = 2;
m_cellIDs[tx-1 + ( ty )*m_size.x*3] = 2;
m_cellIDs[ tx + (ty+1)*m_size.x*3] = 2;
m_cellIDs[tx-2 + (ty+2)*m_size.x*3] = 2;
m_lastlyLit.push_back(sf::Vector2i(tx-1, ty+1));
m_lastlyLit.push_back(sf::Vector2i(tx-1, ty ));
m_lastlyLit.push_back(sf::Vector2i( tx , ty+1));
m_lastlyLit.push_back(sf::Vector2i(tx-2, ty+2));
}
}
if (m_cellIDs[tx-3 + ty*m_size.x*3] == 2) // LEFT
{
m_cellIDs[tx-1 + ty*m_size.x*3] = 2;
m_cellIDs[tx-2 + ty*m_size.x*3] = 2;
m_lastlyLit.push_back(sf::Vector2i(tx-1, ty));
m_lastlyLit.push_back(sf::Vector2i(tx-2, ty));
}
}
if (y > 0)
{
if (m_cellIDs[tx + (ty-3)*m_size.x*3] == 2) // TOP
{
m_cellIDs[tx + (ty-1)*m_size.x*3] = 2;
m_cellIDs[tx + (ty-2)*m_size.x*3] = 2;
m_lastlyLit.push_back(sf::Vector2i(tx, ty-1));
m_lastlyLit.push_back(sf::Vector2i(tx, ty-2));
}
}
if (y < m_size.y-1)
{
if (m_cellIDs[tx + (ty+3)*m_size.x*3] == 2) // BOTTOM
{
m_cellIDs[tx + (ty+1)*m_size.x*3] = 2;
m_cellIDs[tx + (ty+2)*m_size.x*3] = 2;
m_lastlyLit.push_back(sf::Vector2i(tx, ty+1));
m_lastlyLit.push_back(sf::Vector2i(tx, ty+2));
}
}
// CORRECTING THE FINAL SHAPE OF THE SHADOWS
if (isFilled(x, y, 2))
return;
if ( isFilled(x-1, y-1, 2)
&& isFilled( x , y-1, 2)
&& isFilled(x+1, y-1, 2)
&& isFilled(x+1, y , 2)
&& isFilled(x+1, y+1, 2)
&& isFilled( x , y+1, 2)
&& isFilled(x-1, y+1, 2)
&& isFilled(x-1, y , 2)
) return;
std::vector<unsigned char> neighbors;
if (x > 0)
{
if (y > 0) neighbors.push_back(1);
if (y < m_size.y-1) neighbors.push_back(7);
neighbors.push_back(8);
}
if (x < m_size.x-1)
{
if (y > 0) neighbors.push_back(3);
if (y < m_size.y-1) neighbors.push_back(5);
neighbors.push_back(4);
}
if (y > 0) neighbors.push_back(2);
if (y < m_size.y-1) neighbors.push_back(6);
for (unsigned i = 0; i < neighbors.size(); ++i)
{
switch (neighbors[i])
{ // here we switch between the central cell and the cells next to it
case 0: tx = 3*( x ) + 1; ty = 3*( y ) + 1; break; // CENTER
case 1: tx = 3*(x-1) + 1; ty = 3*(y-1) + 1; break; // TOP LEFT
case 2: tx = 3*( x ) + 1; ty = 3*(y-1) + 1; break; // TOP
case 3: tx = 3*(x+1) + 1; ty = 3*(y-1) + 1; break; // TOP RIGHT
case 4: tx = 3*(x+1) + 1; ty = 3*( y ) + 1; break; // RIGHT
case 5: tx = 3*(x+1) + 1; ty = 3*(y+1) + 1; break; // BOTTOM RIGHT
case 6: tx = 3*( x ) + 1; ty = 3*(y+1) + 1; break; // BOTTOM
case 7: tx = 3*(x-1) + 1; ty = 3*(y+1) + 1; break; // BOTTOM LEFT
case 8: tx = 3*(x-1) + 1; ty = 3*( y ) + 1; break; // LEFT
}
if ( m_cellIDs[tx-1 + ( ty )*m_size.x*3] == 2 // IF LEFT
&& m_cellIDs[ tx + (ty-1)*m_size.x*3] == 2) // AND TOP ARE TRANSPARENT
{
m_cellIDs[tx-1 + (ty-1)*m_size.x*3] = 2; // THEN SET TOP LEFT TO TRANSPARENT
m_lastlyLit.push_back(sf::Vector2i(tx-1, ty-1));
}
if ( m_cellIDs[tx-1 + ( ty )*m_size.x*3] == 2 // IF LEFT
&& m_cellIDs[ tx + (ty+1)*m_size.x*3] == 2) // AND BOTTOM ARE TRANSPARENT
{
m_cellIDs[tx-1 + (ty+1)*m_size.x*3] = 2; // THEN SET BOTTOM LEFT TO TRANSPARENT
m_lastlyLit.push_back(sf::Vector2i(tx-1, ty+1));
}
if ( m_cellIDs[tx+1 + ( ty )*m_size.x*3] == 2 // IF RIGHT
&& m_cellIDs[ tx + (ty-1)*m_size.x*3] == 2) // AND TOP ARE TRANSPARENT
{
m_cellIDs[tx+1 + (ty-1)*m_size.x*3] = 2; // THEN SET TOP RIGHT TO TRANSPARENT
m_lastlyLit.push_back(sf::Vector2i(tx+1, ty-1));
}
if ( m_cellIDs[tx+1 + ( ty )*m_size.x*3] == 2 // IF RIGHT
&& m_cellIDs[ tx + (ty+1)*m_size.x*3] == 2) // AND BOTTOM ARE TRANSPARENT
{
m_cellIDs[tx+1 + (ty+1)*m_size.x*3] = 2; // THEN SET BOTTOM RIGHT TO TRANSPARENT
m_lastlyLit.push_back(sf::Vector2i(tx+1, ty+1));
}
if ( m_cellIDs[tx-1 + (ty-1)*m_size.x*3] == 2 // IF TOP LEFT
&& m_cellIDs[tx-1 + (ty+1)*m_size.x*3] == 2) // AND BOTTOM LEFT ARE TRANSPARENT
{
m_cellIDs[tx-1 + ( ty )*m_size.x*3] = 2; // THEN SET LEFT TO TRANSPARENT
m_lastlyLit.push_back(sf::Vector2i(tx-1, ty));
}
if ( m_cellIDs[tx-1 + (ty-1)*m_size.x*3] == 2 // IF TOP LEFT
&& m_cellIDs[tx+1 + (ty-1)*m_size.x*3] == 2) // AND TOP RIGHT ARE TRANSPARENT
{
m_cellIDs[ tx + (ty-1)*m_size.x*3] = 2; // THEN SET TOP TO TRANSPARENT
m_lastlyLit.push_back(sf::Vector2i(tx, ty-1));
}
if ( m_cellIDs[tx+1 + (ty+1)*m_size.x*3] == 2 // IF BOTTOM RIGHT
&& m_cellIDs[tx+1 + (ty-1)*m_size.x*3] == 2) // AND TOP RIGHT ARE TRANSPARENT
{
m_cellIDs[tx+1 + ( ty )*m_size.x*3] = 2; // THEN SET RIGHT TO TRANSPARENT
m_lastlyLit.push_back(sf::Vector2i(tx+1, ty));
}
if ( m_cellIDs[tx+1 + (ty+1)*m_size.x*3] == 2 // IF BOTTOM RIGHT
&& m_cellIDs[tx-1 + (ty+1)*m_size.x*3] == 2) // AND BOTTOM LEFT ARE TRANSPARENT
{
m_cellIDs[ tx + (ty+1)*m_size.x*3] = 2; // THEN SET BOTTOM TO TRANSPARENT
m_lastlyLit.push_back(sf::Vector2i(tx, ty+1));
}
}
}
void
ShadowMap::darken()
{
for (unsigned i = 0; i < m_lastlyLit.size(); ++i)
{
m_cellIDs[m_lastlyLit[i].x + m_lastlyLit[i].y*m_size.x*3] = 1;
}
m_lastlyLit.clear();
}
void
ShadowMap::update()
{
for (int x=0; x<3*m_size.x; ++x)
{
for (int y=0; y<3*m_size.y; ++y)
{
if (m_cellIDs[x + y*3*m_size.x] == 1) m_shadowImage.setPixel(x, y, sf::Color(0, 0, 0, 200));
else if (m_cellIDs[x + y*3*m_size.x] == 2) m_shadowImage.setPixel(x, y, sf::Color(0, 0, 0, 0));
}
}
m_shadowTexture.update(m_shadowImage);
}
std::ifstream&
ShadowMap::operator<<(std::ifstream& file)
{
try
{
for (int x = 0; x < m_size.x; ++x)
{
for (int y = 0; y < m_size.y; ++y)
{
readFile <bool> (file, m_discovered[x + y*m_size.x]);
if (m_discovered[x + y*m_size.x])
setLit(x, y);
}
}
}
catch (std::invalid_argument ex)
{
std::cerr << ex.what() << '\n';
}
return file;
}
std::ofstream&
ShadowMap::operator>>(std::ofstream& file)
{
for (int x = 0; x < m_size.x; ++x)
{
for (int y = 0; y < m_size.y; ++y)
{
file << m_discovered[x + y*m_size.x] << ' ';
}
file << '\n';
}
return file;
}
}
| [
"[email protected]"
] | |
5f7912daf0b071f1aeabf8c92b590a353b08a3f8 | 6f033854765eab225a227550616e7e6eeffb804e | /cp/c.cpp | 87566e8fc785cfc4170b249dfb24e1d228c301f5 | [] | no_license | 0x1h0b/git-test | 150e1a39759d2e8ee9eeb68c7706997da2d298dd | dbd59c75920cb67f2df9d1e5c7aba862271c76d7 | refs/heads/master | 2023-08-19T21:31:40.304112 | 2021-10-03T17:37:04 | 2021-10-03T17:37:04 | 372,818,871 | 0 | 1 | null | 2021-10-03T17:37:05 | 2021-06-01T12:17:34 | C++ | UTF-8 | C++ | false | false | 644 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int n,a;
cin>>n>>a;
int ar[n];
for(int i=0;i<n;i++) cin>>ar[i];
a--;
int dist=0,cnt=0;
while(dist<n){
int idx1=dist+a , idx2=a-dist;
bool f_found=false, b_found=false;
if(idx1<n && ar[idx1]==1){
f_found=true;
}
if(idx2>=0 && ar[idx2]==1){
b_found=true;
}
if(f_found && b_found){
if(idx1==idx2) cnt++;
else cnt+=2;
}
else if(f_found && idx2<0) cnt++;
else if(b_found && idx1>=n) cnt++;
// cout<<"b_found : "<<b_found<<" f_found : "<<f_found;
// cout<<" dist : "<<dist<<" cnt: "<<cnt<<endl;
dist++;
}
cout<<cnt<<endl;
return 0;
}
| [
"[email protected]"
] | |
7a2c0825a3edad699fc5eb57b6af8fedf266ddae | 8db795799862f768bbe3239eafbd95444776607e | /GameEngine/GlassPlankObj.h | 5dea1b0c395b464059e2483ffd7887997c50606b | [] | no_license | PeterCat12/AngryBirds | 0f0eed746015deaf57cfe69a1c3f831e85c65c52 | 445864fac4ada986f38603fa58717c7b2740336a | refs/heads/master | 2021-01-18T13:49:12.460293 | 2015-03-03T00:59:36 | 2015-03-03T00:59:36 | 31,569,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | h | #ifndef GLASS_PLANK_OBJECT_H
#define GLASS_PLANK_OBJECT_H
#include "GameSprite.h"
#include "BoxSprite.h"
#include "Box2D.h"
#include "GameObject.h"
#include "GlassSounds.h"
class b2Body;
class GlassPlankObj : public IGameObject
{
public:
GlassPlankObj(Rect centerArea,b2World *pWorld, float angle, SpriteName::Name sName, ImageName::Name iName);
~GlassPlankObj();
virtual void update( b2Vec2 posInMeters, float angleInRadians );
virtual void InitilizeBody();
virtual GameSprite *getGameSprite();
virtual float getPosX();
virtual float getPosY();
virtual void updateHealth(float dmg);
virtual ImageName::Name getNextImageName( GameObjectName::Name currName,HealthStatus HStatus );
virtual bool updateGame();
virtual void zeroHealth();
virtual b2Body *getBody();
virtual void setBody(b2Body *body);
virtual GameObjectName::Name getObjectName();
BoxSprite *pBoxSprite;
b2Body *pBody;
float angle;
GameObjectName::Name gameObjName;
private:
float width;
float height;
float maxHealth;
float centerX;
float centerY;
float health;
bool destory;
ImageName::Name Iname;
HealthStatus hStatus;
HealthStatus oldHStatus;
BoxSprite *pDebugSprite;
GameSprite *pGameSprite;
b2World *pWorld;
void decideGameObjectName(ImageName::Name name);
};
#endif | [
"[email protected]"
] | |
89e9ca2479554f3b914dc523bd59e9ea33fc741a | 8584afff21c31c843f520bd28587a741e6ffd402 | /AtCoder/ABC/051/a.cpp | 6f79d591f1e2dc52bcfa17a26680a0a5dd641226 | [] | no_license | YuanzhongLi/CompetitiveProgramming | 237e900f1c906c16cbbe3dd09104a1b7ad53862b | f9a72d507d4dda082a344eb19de22f1011dcee5a | refs/heads/master | 2021-11-20T18:35:35.412146 | 2021-08-25T11:39:32 | 2021-08-25T11:39:32 | 249,442,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,481 | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i,s,n) for (int i = (int)s; i < (int)n; i++)
#define ll long long
#define pb push_back
#define eb emplace_back
#define All(x) x.begin(), x.end()
#define Range(x, i, j) x.begin() + i, x.begin() + j
#define lbidx(x, y) lower_bound(x.begin(), x.end(), y) - x.begin()
#define ubidx(x, y) upper_bound(x.begin(), x.end(), y) - x.begin()
#define llbidx(x, y, z) lower_bound(x.begin(), x.end(), z) - lower_bound(x.begin(), x.end(), y) // 二要素間の距離
#define deg2rad(deg) ((((double)deg)/((double)360)*2*M_PI))
#define rad2deg(rad) ((((double)rad)/(double)2/M_PI)*(double)360)
#define Find(set, element) set.find(element) != set.end()
#define Decimal(x) printf("%.10f\n", x) // 小数点を10桁まで表示
// debug用
#define PrintVec(x) for (auto elementPrintVec: x) { cout << elementPrintVec << " "; } cout << endl;
typedef pair<int, int> PI;
typedef pair<ll, ll> PLL;
int POWINT(int x, int n) {
int ret = 1;
rep(i, 0, n) ret *= x;
return ret;
};
ll POWLL(int x, int n) {
ll ret = 1;
rep(i, 0, n) ret *= x;
return ret;
};
template<class T>
inline bool chmax(T &a, T b) {
if(a < b) {
a = b;
return true;
}
return false;
};
template<class T>
inline bool chmin(T &a, T b) {
if(a > b) {
a = b;
return true;
}
return false;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
string s;
cin >> s;
s[5] = ' ';
s[13] = ' ';
cout << s << endl;
return 0;
};
| [
"[email protected]"
] | |
3b569f4426b642dbf84ad7c9cbca4ec29444a738 | 5dd112c8d6a31d10c26e0f59b94e37595b5e2db9 | /contrib/libs/tcmalloc/tcmalloc/huge_page_filler_test.cc | c1c149ddbe35415a91ae0568a7b19292fabcd936 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | kizill/catboost | 4433dd467f48120793a397b3485355ccb59d08bf | 3f3597bf7691a3b4e49d5b41309f57edaf4f2f19 | refs/heads/master | 2021-11-02T08:34:14.084130 | 2021-08-09T15:50:07 | 2021-08-09T15:50:07 | 116,815,185 | 0 | 0 | Apache-2.0 | 2019-02-01T19:51:07 | 2018-01-09T12:47:08 | C++ | UTF-8 | C++ | false | false | 106,878 | cc | // Copyright 2019 The TCMalloc Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "tcmalloc/huge_page_filler.h"
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <cstdint>
#include <iterator>
#include <memory>
#include <new>
#include <random>
#include <string>
#include <thread> // NOLINT(build/c++11)
#include <utility>
#include <vector>
#include "benchmark/benchmark.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/algorithm/container.h"
#include "absl/base/internal/sysinfo.h"
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/flags/flag.h"
#include "absl/memory/memory.h"
#include "absl/random/bernoulli_distribution.h"
#include "absl/random/random.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/synchronization/blocking_counter.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "tcmalloc/common.h"
#include "tcmalloc/huge_pages.h"
#include "tcmalloc/internal/logging.h"
#include "tcmalloc/pages.h"
#include "tcmalloc/stats.h"
ABSL_FLAG(tcmalloc::Length, page_tracker_defrag_lim, tcmalloc::Length(32),
"Max allocation size for defrag test");
ABSL_FLAG(tcmalloc::Length, frag_req_limit, tcmalloc::Length(32),
"request size limit for frag test");
ABSL_FLAG(tcmalloc::Length, frag_size, tcmalloc::Length(512 * 1024),
"target number of pages for frag test");
ABSL_FLAG(uint64_t, frag_iters, 10 * 1000 * 1000, "iterations for frag test");
ABSL_FLAG(double, release_until, 0.01,
"fraction of used we target in pageheap");
ABSL_FLAG(uint64_t, bytes, 1024 * 1024 * 1024, "baseline usage");
ABSL_FLAG(double, growth_factor, 2.0, "growth over baseline");
namespace tcmalloc {
namespace {
// This is an arbitrary distribution taken from page requests from
// an empirical driver test. It seems realistic enough. We trim it to
// [1, last].
//
std::discrete_distribution<size_t> EmpiricalDistribution(Length last) {
std::vector<size_t> page_counts = []() {
std::vector<size_t> ret(12289);
ret[1] = 375745576;
ret[2] = 59737961;
ret[3] = 35549390;
ret[4] = 43896034;
ret[5] = 17484968;
ret[6] = 15830888;
ret[7] = 9021717;
ret[8] = 208779231;
ret[9] = 3775073;
ret[10] = 25591620;
ret[11] = 2483221;
ret[12] = 3595343;
ret[13] = 2232402;
ret[16] = 17639345;
ret[21] = 4215603;
ret[25] = 4212756;
ret[28] = 760576;
ret[30] = 2166232;
ret[32] = 3021000;
ret[40] = 1186302;
ret[44] = 479142;
ret[48] = 570030;
ret[49] = 101262;
ret[55] = 592333;
ret[57] = 236637;
ret[64] = 785066;
ret[65] = 44700;
ret[73] = 539659;
ret[80] = 342091;
ret[96] = 488829;
ret[97] = 504;
ret[113] = 242921;
ret[128] = 157206;
ret[129] = 145;
ret[145] = 117191;
ret[160] = 91818;
ret[192] = 67824;
ret[193] = 144;
ret[225] = 40711;
ret[256] = 38569;
ret[257] = 1;
ret[297] = 21738;
ret[320] = 13510;
ret[384] = 19499;
ret[432] = 13856;
ret[490] = 9849;
ret[512] = 3024;
ret[640] = 3655;
ret[666] = 3963;
ret[715] = 2376;
ret[768] = 288;
ret[1009] = 6389;
ret[1023] = 2788;
ret[1024] = 144;
ret[1280] = 1656;
ret[1335] = 2592;
ret[1360] = 3024;
ret[1536] = 432;
ret[2048] = 288;
ret[2560] = 72;
ret[3072] = 360;
ret[12288] = 216;
return ret;
}();
Length lim = last;
auto i = page_counts.begin();
// remember lim might be too big (in which case we use the whole
// vector...)
auto j = page_counts.size() > lim.raw_num() ? i + (lim.raw_num() + 1)
: page_counts.end();
return std::discrete_distribution<size_t>(i, j);
}
class PageTrackerTest : public testing::Test {
protected:
PageTrackerTest()
: // an unlikely magic page
huge_(HugePageContaining(reinterpret_cast<void*>(0x1abcde200000))),
tracker_(huge_, absl::base_internal::CycleClock::Now()) {}
~PageTrackerTest() override { mock_.VerifyAndClear(); }
struct PAlloc {
PageId p;
Length n;
};
void Mark(PAlloc a, size_t mark) {
EXPECT_LE(huge_.first_page(), a.p);
size_t index = (a.p - huge_.first_page()).raw_num();
size_t end = index + a.n.raw_num();
EXPECT_LE(end, kPagesPerHugePage.raw_num());
for (; index < end; ++index) {
marks_[index] = mark;
}
}
class MockUnbackInterface {
public:
void Unback(void* p, size_t len) {
CHECK_CONDITION(actual_index_ < kMaxCalls);
actual_[actual_index_] = {p, len};
++actual_index_;
}
void Expect(void* p, size_t len) {
CHECK_CONDITION(expected_index_ < kMaxCalls);
expected_[expected_index_] = {p, len};
++expected_index_;
}
void VerifyAndClear() {
EXPECT_EQ(expected_index_, actual_index_);
for (size_t i = 0, n = std::min(expected_index_, actual_index_); i < n;
++i) {
EXPECT_EQ(expected_[i].ptr, actual_[i].ptr);
EXPECT_EQ(expected_[i].len, actual_[i].len);
}
expected_index_ = 0;
actual_index_ = 0;
}
private:
struct CallArgs {
void* ptr{nullptr};
size_t len{0};
};
static constexpr size_t kMaxCalls = 10;
CallArgs expected_[kMaxCalls] = {};
CallArgs actual_[kMaxCalls] = {};
size_t expected_index_{0};
size_t actual_index_{0};
};
static void MockUnback(void* p, size_t len);
typedef PageTracker<MockUnback> TestPageTracker;
// strict because release calls should only happen when we ask
static MockUnbackInterface mock_;
void Check(PAlloc a, size_t mark) {
EXPECT_LE(huge_.first_page(), a.p);
size_t index = (a.p - huge_.first_page()).raw_num();
size_t end = index + a.n.raw_num();
EXPECT_LE(end, kPagesPerHugePage.raw_num());
for (; index < end; ++index) {
EXPECT_EQ(mark, marks_[index]);
}
}
size_t marks_[kPagesPerHugePage.raw_num()];
HugePage huge_;
TestPageTracker tracker_;
void ExpectPages(PAlloc a) {
void* ptr = a.p.start_addr();
size_t bytes = a.n.in_bytes();
mock_.Expect(ptr, bytes);
}
PAlloc Get(Length n) {
absl::base_internal::SpinLockHolder l(&pageheap_lock);
PageId p = tracker_.Get(n).page;
return {p, n};
}
void Put(PAlloc a) {
absl::base_internal::SpinLockHolder l(&pageheap_lock);
tracker_.Put(a.p, a.n);
}
Length ReleaseFree() {
absl::base_internal::SpinLockHolder l(&pageheap_lock);
return tracker_.ReleaseFree();
}
void MaybeRelease(PAlloc a) {
absl::base_internal::SpinLockHolder l(&pageheap_lock);
tracker_.MaybeRelease(a.p, a.n);
}
};
void PageTrackerTest::MockUnback(void* p, size_t len) { mock_.Unback(p, len); }
PageTrackerTest::MockUnbackInterface PageTrackerTest::mock_;
TEST_F(PageTrackerTest, AllocSane) {
Length free = kPagesPerHugePage;
auto n = Length(1);
std::vector<PAlloc> allocs;
// This should work without fragmentation.
while (n <= free) {
ASSERT_LE(n, tracker_.longest_free_range());
EXPECT_EQ(kPagesPerHugePage - free, tracker_.used_pages());
EXPECT_EQ(free, tracker_.free_pages());
PAlloc a = Get(n);
Mark(a, n.raw_num());
allocs.push_back(a);
free -= n;
++n;
}
// All should be distinct
for (auto alloc : allocs) {
Check(alloc, alloc.n.raw_num());
}
}
TEST_F(PageTrackerTest, ReleasingReturn) {
static const Length kAllocSize = kPagesPerHugePage / 4;
PAlloc a1 = Get(kAllocSize - Length(3));
PAlloc a2 = Get(kAllocSize);
PAlloc a3 = Get(kAllocSize + Length(1));
PAlloc a4 = Get(kAllocSize + Length(2));
Put(a2);
Put(a4);
// We now have a hugepage that looks like [alloced] [free] [alloced] [free].
// The free parts should be released when we mark the hugepage as such,
// but not the allocated parts.
ExpectPages(a2);
ExpectPages(a4);
ReleaseFree();
mock_.VerifyAndClear();
// Now we return the other parts, and they *should* get released.
ExpectPages(a1);
ExpectPages(a3);
MaybeRelease(a1);
Put(a1);
MaybeRelease(a3);
Put(a3);
}
TEST_F(PageTrackerTest, ReleasingRetain) {
static const Length kAllocSize = kPagesPerHugePage / 4;
PAlloc a1 = Get(kAllocSize - Length(3));
PAlloc a2 = Get(kAllocSize);
PAlloc a3 = Get(kAllocSize + Length(1));
PAlloc a4 = Get(kAllocSize + Length(2));
Put(a2);
Put(a4);
// We now have a hugepage that looks like [alloced] [free] [alloced] [free].
// The free parts should be released when we mark the hugepage as such,
// but not the allocated parts.
ExpectPages(a2);
ExpectPages(a4);
ReleaseFree();
mock_.VerifyAndClear();
// Now we return the other parts, and they shouldn't get released.
Put(a1);
Put(a3);
mock_.VerifyAndClear();
// But they will if we ReleaseFree.
ExpectPages(a1);
ExpectPages(a3);
ReleaseFree();
mock_.VerifyAndClear();
}
TEST_F(PageTrackerTest, Defrag) {
absl::BitGen rng;
const Length N = absl::GetFlag(FLAGS_page_tracker_defrag_lim);
auto dist = EmpiricalDistribution(N);
std::vector<PAlloc> allocs;
std::vector<PAlloc> doomed;
while (tracker_.longest_free_range() > Length(0)) {
Length n;
do {
n = Length(dist(rng));
} while (n > tracker_.longest_free_range());
PAlloc a = Get(n);
(absl::Bernoulli(rng, 1.0 / 2) ? allocs : doomed).push_back(a);
}
for (auto d : doomed) {
Put(d);
}
static const size_t kReps = 250 * 1000;
std::vector<double> frag_samples;
std::vector<Length> longest_free_samples;
frag_samples.reserve(kReps);
longest_free_samples.reserve(kReps);
for (size_t i = 0; i < kReps; ++i) {
const Length free = kPagesPerHugePage - tracker_.used_pages();
// Ideally, we'd like all of our free space to stay in a single
// nice little run.
const Length longest = tracker_.longest_free_range();
double frag = free > Length(0)
? static_cast<double>(longest.raw_num()) / free.raw_num()
: 1;
if (i % (kReps / 25) == 0) {
printf("free = %zu longest = %zu frag = %f\n", free.raw_num(),
longest.raw_num(), frag);
}
frag_samples.push_back(frag);
longest_free_samples.push_back(longest);
// Randomly grow or shrink (picking the only safe option when we're either
// full or empty.)
if (tracker_.longest_free_range() == Length(0) ||
(absl::Bernoulli(rng, 1.0 / 2) && !allocs.empty())) {
size_t index = absl::Uniform<int32_t>(rng, 0, allocs.size());
std::swap(allocs[index], allocs.back());
Put(allocs.back());
allocs.pop_back();
} else {
Length n;
do {
n = Length(dist(rng));
} while (n > tracker_.longest_free_range());
allocs.push_back(Get(n));
}
}
std::sort(frag_samples.begin(), frag_samples.end());
std::sort(longest_free_samples.begin(), longest_free_samples.end());
{
const double p10 = frag_samples[kReps * 10 / 100];
const double p25 = frag_samples[kReps * 25 / 100];
const double p50 = frag_samples[kReps * 50 / 100];
const double p75 = frag_samples[kReps * 75 / 100];
const double p90 = frag_samples[kReps * 90 / 100];
printf("Fragmentation quantiles:\n");
printf("p10: %f p25: %f p50: %f p75: %f p90: %f\n", p10, p25, p50, p75,
p90);
// We'd like to prety consistently rely on (75% of the time) reasonable
// defragmentation (50% of space is fully usable...)
// ...but we currently can't hit that mark consistently.
// The situation is worse on ppc with larger huge pages:
// pass rate for test is ~50% at 0.20. Reducing from 0.2 to 0.07.
// TODO(b/127466107) figure out a better solution.
EXPECT_GE(p25, 0.07);
}
{
const Length p10 = longest_free_samples[kReps * 10 / 100];
const Length p25 = longest_free_samples[kReps * 25 / 100];
const Length p50 = longest_free_samples[kReps * 50 / 100];
const Length p75 = longest_free_samples[kReps * 75 / 100];
const Length p90 = longest_free_samples[kReps * 90 / 100];
printf("Longest free quantiles:\n");
printf("p10: %zu p25: %zu p50: %zu p75: %zu p90: %zu\n", p10.raw_num(),
p25.raw_num(), p50.raw_num(), p75.raw_num(), p90.raw_num());
// Similarly, we'd really like for there usually (p25) to be a space
// for a large allocation (N - note that we've cooked the books so that
// the page tracker is going to be something like half empty (ish) and N
// is small, so that should be doable.)
// ...but, of course, it isn't.
EXPECT_GE(p25, Length(4));
}
for (auto a : allocs) {
Put(a);
}
}
TEST_F(PageTrackerTest, Stats) {
struct Helper {
static void Stat(const TestPageTracker& tracker,
std::vector<Length>* small_backed,
std::vector<Length>* small_unbacked, LargeSpanStats* large,
double* avg_age_backed, double* avg_age_unbacked) {
SmallSpanStats small;
*large = LargeSpanStats();
PageAgeHistograms ages(absl::base_internal::CycleClock::Now());
tracker.AddSpanStats(&small, large, &ages);
small_backed->clear();
small_unbacked->clear();
for (auto i = Length(0); i < kMaxPages; ++i) {
for (int j = 0; j < small.normal_length[i.raw_num()]; ++j) {
small_backed->push_back(i);
}
for (int j = 0; j < small.returned_length[i.raw_num()]; ++j) {
small_unbacked->push_back(i);
}
}
*avg_age_backed = ages.GetTotalHistogram(false)->avg_age();
*avg_age_unbacked = ages.GetTotalHistogram(true)->avg_age();
}
};
LargeSpanStats large;
std::vector<Length> small_backed, small_unbacked;
double avg_age_backed, avg_age_unbacked;
const PageId p = Get(kPagesPerHugePage).p;
const PageId end = p + kPagesPerHugePage;
PageId next = p;
Put({next, kMaxPages + Length(1)});
next += kMaxPages + Length(1);
absl::SleepFor(absl::Milliseconds(10));
Helper::Stat(tracker_, &small_backed, &small_unbacked, &large,
&avg_age_backed, &avg_age_unbacked);
EXPECT_THAT(small_backed, testing::ElementsAre());
EXPECT_THAT(small_unbacked, testing::ElementsAre());
EXPECT_EQ(1, large.spans);
EXPECT_EQ(kMaxPages + Length(1), large.normal_pages);
EXPECT_EQ(Length(0), large.returned_pages);
EXPECT_LE(0.01, avg_age_backed);
++next;
Put({next, Length(1)});
next += Length(1);
absl::SleepFor(absl::Milliseconds(20));
Helper::Stat(tracker_, &small_backed, &small_unbacked, &large,
&avg_age_backed, &avg_age_unbacked);
EXPECT_THAT(small_backed, testing::ElementsAre(Length(1)));
EXPECT_THAT(small_unbacked, testing::ElementsAre());
EXPECT_EQ(1, large.spans);
EXPECT_EQ(kMaxPages + Length(1), large.normal_pages);
EXPECT_EQ(Length(0), large.returned_pages);
EXPECT_LE(((kMaxPages + Length(1)).raw_num() * 0.03 + 1 * 0.02) /
(kMaxPages + Length(2)).raw_num(),
avg_age_backed);
EXPECT_EQ(0, avg_age_unbacked);
++next;
Put({next, Length(2)});
next += Length(2);
absl::SleepFor(absl::Milliseconds(30));
Helper::Stat(tracker_, &small_backed, &small_unbacked, &large,
&avg_age_backed, &avg_age_unbacked);
EXPECT_THAT(small_backed, testing::ElementsAre(Length(1), Length(2)));
EXPECT_THAT(small_unbacked, testing::ElementsAre());
EXPECT_EQ(1, large.spans);
EXPECT_EQ(kMaxPages + Length(1), large.normal_pages);
EXPECT_EQ(Length(0), large.returned_pages);
EXPECT_LE(((kMaxPages + Length(1)).raw_num() * 0.06 + 1 * 0.05 + 2 * 0.03) /
(kMaxPages + Length(4)).raw_num(),
avg_age_backed);
EXPECT_EQ(0, avg_age_unbacked);
++next;
Put({next, Length(3)});
next += Length(3);
ASSERT_LE(next, end);
absl::SleepFor(absl::Milliseconds(40));
Helper::Stat(tracker_, &small_backed, &small_unbacked, &large,
&avg_age_backed, &avg_age_unbacked);
EXPECT_THAT(small_backed,
testing::ElementsAre(Length(1), Length(2), Length(3)));
EXPECT_THAT(small_unbacked, testing::ElementsAre());
EXPECT_EQ(1, large.spans);
EXPECT_EQ(kMaxPages + Length(1), large.normal_pages);
EXPECT_EQ(Length(0), large.returned_pages);
EXPECT_LE(((kMaxPages + Length(1)).raw_num() * 0.10 + 1 * 0.09 + 2 * 0.07 +
3 * 0.04) /
(kMaxPages + Length(7)).raw_num(),
avg_age_backed);
EXPECT_EQ(0, avg_age_unbacked);
ExpectPages({p, kMaxPages + Length(1)});
ExpectPages({p + kMaxPages + Length(2), Length(1)});
ExpectPages({p + kMaxPages + Length(4), Length(2)});
ExpectPages({p + kMaxPages + Length(7), Length(3)});
EXPECT_EQ(kMaxPages + Length(7), ReleaseFree());
absl::SleepFor(absl::Milliseconds(100));
Helper::Stat(tracker_, &small_backed, &small_unbacked, &large,
&avg_age_backed, &avg_age_unbacked);
EXPECT_THAT(small_backed, testing::ElementsAre());
EXPECT_THAT(small_unbacked,
testing::ElementsAre(Length(1), Length(2), Length(3)));
EXPECT_EQ(1, large.spans);
EXPECT_EQ(Length(0), large.normal_pages);
EXPECT_EQ(kMaxPages + Length(1), large.returned_pages);
EXPECT_EQ(0, avg_age_backed);
EXPECT_LE(0.1, avg_age_unbacked);
}
TEST_F(PageTrackerTest, b151915873) {
// This test verifies, while generating statistics for the huge page, that we
// do not go out-of-bounds in our bitmaps (b/151915873).
// While the PageTracker relies on FindAndMark to decide which pages to hand
// out, we do not specify where in the huge page we get our allocations.
// Allocate single pages and then use their returned addresses to create the
// desired pattern in the bitmaps, namely:
//
// | | kPagesPerHugePage - 2 | kPagesPerHugePages - 1 |
// | .... | not free | free |
//
// This causes AddSpanStats to try index = kPagesPerHugePage - 1, n=1. We
// need to not overflow FindClear/FindSet.
std::vector<PAlloc> allocs;
allocs.reserve(kPagesPerHugePage.raw_num());
for (int i = 0; i < kPagesPerHugePage.raw_num(); i++) {
allocs.push_back(Get(Length(1)));
}
std::sort(allocs.begin(), allocs.end(),
[](const PAlloc& a, const PAlloc& b) { return a.p < b.p; });
Put(allocs.back());
allocs.erase(allocs.begin() + allocs.size() - 1);
ASSERT_EQ(tracker_.used_pages(), kPagesPerHugePage - Length(1));
SmallSpanStats small;
LargeSpanStats large;
PageAgeHistograms ages(absl::base_internal::CycleClock::Now());
tracker_.AddSpanStats(&small, &large, &ages);
EXPECT_EQ(small.normal_length[1], 1);
EXPECT_THAT(0,
testing::AllOfArray(&small.normal_length[2],
&small.normal_length[kMaxPages.raw_num()]));
}
class BlockingUnback {
public:
static void Unback(void* p, size_t len) {
if (!mu_) {
return;
}
if (counter) {
counter->DecrementCount();
}
mu_->Lock();
mu_->Unlock();
}
static void set_lock(absl::Mutex* mu) { mu_ = mu; }
static absl::BlockingCounter* counter;
private:
static thread_local absl::Mutex* mu_;
};
thread_local absl::Mutex* BlockingUnback::mu_ = nullptr;
absl::BlockingCounter* BlockingUnback::counter = nullptr;
class FillerTest : public testing::TestWithParam<FillerPartialRerelease> {
protected:
// Allow tests to modify the clock used by the cache.
static int64_t FakeClock() { return clock_; }
static double GetFakeClockFrequency() {
return absl::ToDoubleNanoseconds(absl::Seconds(2));
}
static void Advance(absl::Duration d) {
clock_ += absl::ToDoubleSeconds(d) * GetFakeClockFrequency();
}
static void ResetClock() { clock_ = 1234; }
static void Unback(void* p, size_t len) {}
// Our templating approach lets us directly override certain functions
// and have mocks without virtualization. It's a bit funky but works.
typedef PageTracker<BlockingUnback::Unback> FakeTracker;
// We have backing of one word per (normal-sized) page for our "hugepages".
std::vector<size_t> backing_;
// This is space efficient enough that we won't bother recycling pages.
HugePage GetBacking() {
intptr_t i = backing_.size();
backing_.resize(i + kPagesPerHugePage.raw_num());
intptr_t addr = i << kPageShift;
CHECK_CONDITION(addr % kHugePageSize == 0);
return HugePageContaining(reinterpret_cast<void*>(addr));
}
size_t* GetFakePage(PageId p) { return &backing_[p.index()]; }
void MarkRange(PageId p, Length n, size_t mark) {
for (auto i = Length(0); i < n; ++i) {
*GetFakePage(p + i) = mark;
}
}
void CheckRange(PageId p, Length n, size_t mark) {
for (auto i = Length(0); i < n; ++i) {
EXPECT_EQ(mark, *GetFakePage(p + i));
}
}
HugePageFiller<FakeTracker> filler_;
FillerTest()
: filler_(GetParam(),
Clock{.now = FakeClock, .freq = GetFakeClockFrequency}) {
ResetClock();
}
~FillerTest() override { EXPECT_EQ(NHugePages(0), filler_.size()); }
struct PAlloc {
FakeTracker* pt;
PageId p;
Length n;
size_t mark;
};
void Mark(const PAlloc& alloc) { MarkRange(alloc.p, alloc.n, alloc.mark); }
void Check(const PAlloc& alloc) { CheckRange(alloc.p, alloc.n, alloc.mark); }
size_t next_mark_{0};
HugeLength hp_contained_{NHugePages(0)};
Length total_allocated_{0};
absl::InsecureBitGen gen_;
void CheckStats() {
EXPECT_EQ(hp_contained_, filler_.size());
auto stats = filler_.stats();
const uint64_t freelist_bytes = stats.free_bytes + stats.unmapped_bytes;
const uint64_t used_bytes = stats.system_bytes - freelist_bytes;
EXPECT_EQ(total_allocated_.in_bytes(), used_bytes);
EXPECT_EQ((hp_contained_.in_pages() - total_allocated_).in_bytes(),
freelist_bytes);
}
PAlloc AllocateRaw(Length n, bool donated = false) {
EXPECT_LT(n, kPagesPerHugePage);
PAlloc ret;
ret.n = n;
ret.mark = ++next_mark_;
bool success = false;
if (!donated) { // Donated means always create a new hugepage
absl::base_internal::SpinLockHolder l(&pageheap_lock);
success = filler_.TryGet(n, &ret.pt, &ret.p);
}
if (!success) {
ret.pt =
new FakeTracker(GetBacking(), absl::base_internal::CycleClock::Now());
{
absl::base_internal::SpinLockHolder l(&pageheap_lock);
ret.p = ret.pt->Get(n).page;
}
filler_.Contribute(ret.pt, donated);
++hp_contained_;
}
total_allocated_ += n;
return ret;
}
PAlloc Allocate(Length n, bool donated = false) {
CHECK_CONDITION(n <= kPagesPerHugePage);
PAlloc ret = AllocateRaw(n, donated);
ret.n = n;
Mark(ret);
CheckStats();
return ret;
}
// Returns true iff the filler returned an empty hugepage.
bool DeleteRaw(const PAlloc& p) {
FakeTracker* pt;
{
absl::base_internal::SpinLockHolder l(&pageheap_lock);
pt = filler_.Put(p.pt, p.p, p.n);
}
total_allocated_ -= p.n;
if (pt != nullptr) {
EXPECT_EQ(kPagesPerHugePage, pt->longest_free_range());
EXPECT_TRUE(pt->empty());
--hp_contained_;
delete pt;
return true;
}
return false;
}
// Returns true iff the filler returned an empty hugepage
bool Delete(const PAlloc& p) {
Check(p);
bool r = DeleteRaw(p);
CheckStats();
return r;
}
Length ReleasePages(Length desired, absl::Duration d = absl::ZeroDuration()) {
absl::base_internal::SpinLockHolder l(&pageheap_lock);
return filler_.ReleasePages(desired, d, false);
}
Length HardReleasePages(Length desired) {
absl::base_internal::SpinLockHolder l(&pageheap_lock);
return filler_.ReleasePages(desired, absl::ZeroDuration(), true);
}
// Generates an "interesting" pattern of allocations that highlights all the
// various features of our stats.
std::vector<PAlloc> GenerateInterestingAllocs();
private:
static int64_t clock_;
};
int64_t FillerTest::clock_{1234};
TEST_P(FillerTest, Density) {
absl::BitGen rng;
// Start with a really annoying setup: some hugepages half
// empty (randomly)
std::vector<PAlloc> allocs;
std::vector<PAlloc> doomed_allocs;
static const HugeLength kNumHugePages = NHugePages(64);
for (auto i = Length(0); i < kNumHugePages.in_pages(); ++i) {
ASSERT_EQ(i, filler_.pages_allocated());
if (absl::Bernoulli(rng, 1.0 / 2)) {
allocs.push_back(Allocate(Length(1)));
} else {
doomed_allocs.push_back(Allocate(Length(1)));
}
}
for (auto d : doomed_allocs) {
Delete(d);
}
EXPECT_EQ(kNumHugePages, filler_.size());
// We want a good chance of touching ~every allocation.
size_t n = allocs.size();
// Now, randomly add and delete to the allocations.
// We should converge to full and empty pages.
for (int j = 0; j < 6; j++) {
absl::c_shuffle(allocs, rng);
for (int i = 0; i < n; ++i) {
Delete(allocs[i]);
allocs[i] = Allocate(Length(1));
ASSERT_EQ(Length(n), filler_.pages_allocated());
}
}
EXPECT_GE(allocs.size() / kPagesPerHugePage.raw_num() + 1,
filler_.size().raw_num());
// clean up, check for failures
for (auto a : allocs) {
Delete(a);
ASSERT_EQ(Length(--n), filler_.pages_allocated());
}
}
TEST_P(FillerTest, Release) {
static const Length kAlloc = kPagesPerHugePage / 2;
PAlloc p1 = Allocate(kAlloc - Length(1));
PAlloc p2 = Allocate(kAlloc + Length(1));
PAlloc p3 = Allocate(kAlloc - Length(2));
PAlloc p4 = Allocate(kAlloc + Length(2));
// We have two hugepages, both full: nothing to release.
ASSERT_EQ(Length(0), ReleasePages(kMaxValidPages));
Delete(p1);
Delete(p3);
// Now we should see the p1 hugepage - emptier - released.
ASSERT_EQ(kAlloc - Length(1), ReleasePages(kAlloc - Length(1)));
EXPECT_EQ(kAlloc - Length(1), filler_.unmapped_pages());
ASSERT_TRUE(p1.pt->released());
ASSERT_FALSE(p3.pt->released());
// We expect to reuse p1.pt.
PAlloc p5 = Allocate(kAlloc - Length(1));
ASSERT_TRUE(p1.pt == p5.pt || p3.pt == p5.pt);
Delete(p2);
Delete(p4);
Delete(p5);
}
TEST_P(FillerTest, Fragmentation) {
absl::BitGen rng;
auto dist = EmpiricalDistribution(absl::GetFlag(FLAGS_frag_req_limit));
std::vector<PAlloc> allocs;
Length total;
while (total < absl::GetFlag(FLAGS_frag_size)) {
auto n = Length(dist(rng));
total += n;
allocs.push_back(AllocateRaw(n));
}
double max_slack = 0.0;
const size_t kReps = absl::GetFlag(FLAGS_frag_iters);
for (size_t i = 0; i < kReps; ++i) {
auto stats = filler_.stats();
double slack = static_cast<double>(stats.free_bytes) / stats.system_bytes;
max_slack = std::max(slack, max_slack);
if (i % (kReps / 40) == 0) {
printf("%zu events: %zu allocs totalling %zu slack %f\n", i,
allocs.size(), total.raw_num(), slack);
}
if (absl::Bernoulli(rng, 1.0 / 2)) {
size_t index = absl::Uniform<int32_t>(rng, 0, allocs.size());
std::swap(allocs[index], allocs.back());
DeleteRaw(allocs.back());
total -= allocs.back().n;
allocs.pop_back();
} else {
auto n = Length(dist(rng));
allocs.push_back(AllocateRaw(n));
total += n;
}
}
EXPECT_LE(max_slack, 0.05);
for (auto a : allocs) {
DeleteRaw(a);
}
}
TEST_P(FillerTest, PrintFreeRatio) {
// This test is sensitive to the number of pages per hugepage, as we are
// printing raw stats.
if (kPagesPerHugePage != Length(256)) {
GTEST_SKIP();
}
// Allocate two huge pages, release one, verify that we do not get an invalid
// (>1.) ratio of free : non-fulls.
// First huge page
PAlloc a1 = Allocate(kPagesPerHugePage / 2);
PAlloc a2 = Allocate(kPagesPerHugePage / 2);
// Second huge page
constexpr Length kQ = kPagesPerHugePage / 4;
PAlloc a3 = Allocate(kQ);
PAlloc a4 = Allocate(kQ);
PAlloc a5 = Allocate(kQ);
PAlloc a6 = Allocate(kQ);
Delete(a6);
ReleasePages(kQ);
Delete(a5);
std::string buffer(1024 * 1024, '\0');
{
TCMalloc_Printer printer(&*buffer.begin(), buffer.size());
filler_.Print(&printer, /*everything=*/true);
buffer.erase(printer.SpaceRequired());
}
if (GetParam() == FillerPartialRerelease::Retain) {
EXPECT_THAT(
buffer,
testing::StartsWith(
R"(HugePageFiller: densely pack small requests into hugepages
HugePageFiller: 2 total, 1 full, 0 partial, 1 released (1 partially), 0 quarantined
HugePageFiller: 64 pages free in 2 hugepages, 0.1250 free
HugePageFiller: among non-fulls, 0.2500 free
HugePageFiller: 128 used pages in subreleased hugepages (128 of them in partially released)
HugePageFiller: 1 hugepages partially released, 0.2500 released
HugePageFiller: 0.6667 of used pages hugepageable)"));
} else {
EXPECT_THAT(
buffer,
testing::StartsWith(
R"(HugePageFiller: densely pack small requests into hugepages
HugePageFiller: 2 total, 1 full, 0 partial, 1 released (0 partially), 0 quarantined
HugePageFiller: 0 pages free in 2 hugepages, 0.0000 free
HugePageFiller: among non-fulls, 0.0000 free
HugePageFiller: 128 used pages in subreleased hugepages (0 of them in partially released)
HugePageFiller: 1 hugepages partially released, 0.5000 released
HugePageFiller: 0.6667 of used pages hugepageable)"));
}
// Cleanup remaining allocs.
Delete(a1);
Delete(a2);
Delete(a3);
Delete(a4);
}
static double BytesToMiB(size_t bytes) { return bytes / (1024.0 * 1024.0); }
using testing::AnyOf;
using testing::Eq;
using testing::StrEq;
TEST_P(FillerTest, HugePageFrac) {
// I don't actually care which we get, both are
// reasonable choices, but don't report a NaN/complain
// about divide by 0s/ give some bogus number for empty.
EXPECT_THAT(filler_.hugepage_frac(), AnyOf(Eq(0), Eq(1)));
static const Length kQ = kPagesPerHugePage / 4;
// These are all on one page:
auto a1 = Allocate(kQ);
auto a2 = Allocate(kQ);
auto a3 = Allocate(kQ - Length(1));
auto a4 = Allocate(kQ + Length(1));
// As are these:
auto a5 = Allocate(kPagesPerHugePage - kQ);
auto a6 = Allocate(kQ);
EXPECT_EQ(1, filler_.hugepage_frac());
// Free space doesn't affect it...
Delete(a4);
Delete(a6);
EXPECT_EQ(1, filler_.hugepage_frac());
// Releasing the hugepage does.
ASSERT_EQ(kQ + Length(1), ReleasePages(kQ + Length(1)));
EXPECT_EQ((3.0 * kQ.raw_num()) / (6.0 * kQ.raw_num() - 1.0),
filler_.hugepage_frac());
// Check our arithmetic in a couple scenarios.
// 2 kQs on the release and 3 on the hugepage
Delete(a2);
EXPECT_EQ((3.0 * kQ.raw_num()) / (5.0 * kQ.raw_num() - 1),
filler_.hugepage_frac());
// This releases the free page on the partially released hugepage.
ASSERT_EQ(kQ, ReleasePages(kQ));
EXPECT_EQ((3.0 * kQ.raw_num()) / (5.0 * kQ.raw_num() - 1),
filler_.hugepage_frac());
// just-over-1 kQ on the release and 3 on the hugepage
Delete(a3);
EXPECT_EQ((3 * kQ.raw_num()) / (4.0 * kQ.raw_num()), filler_.hugepage_frac());
// This releases the free page on the partially released hugepage.
ASSERT_EQ(kQ - Length(1), ReleasePages(kQ - Length(1)));
EXPECT_EQ((3 * kQ.raw_num()) / (4.0 * kQ.raw_num()), filler_.hugepage_frac());
// All huge!
Delete(a1);
EXPECT_EQ(1, filler_.hugepage_frac());
Delete(a5);
}
// Repeatedly grow from FLAG_bytes to FLAG_bytes * growth factor, then shrink
// back down by random deletion. Then release partial hugepages until
// pageheap is bounded by some fraction of usage.
// Measure the effective hugepage fraction at peak and baseline usage,
// and the blowup in VSS footprint.
//
// This test is a tool for analyzing parameters -- not intended as an actual
// unit test.
TEST_P(FillerTest, DISABLED_ReleaseFrac) {
absl::BitGen rng;
const Length baseline = LengthFromBytes(absl::GetFlag(FLAGS_bytes));
const Length peak = baseline * absl::GetFlag(FLAGS_growth_factor);
const Length free_target = baseline * absl::GetFlag(FLAGS_release_until);
std::vector<PAlloc> allocs;
while (filler_.used_pages() < baseline) {
allocs.push_back(AllocateRaw(Length(1)));
}
while (true) {
while (filler_.used_pages() < peak) {
allocs.push_back(AllocateRaw(Length(1)));
}
const double peak_frac = filler_.hugepage_frac();
// VSS
const size_t footprint = filler_.size().in_bytes();
std::shuffle(allocs.begin(), allocs.end(), rng);
size_t limit = allocs.size();
while (filler_.used_pages() > baseline) {
--limit;
DeleteRaw(allocs[limit]);
}
allocs.resize(limit);
while (filler_.free_pages() > free_target) {
ReleasePages(kMaxValidPages);
}
const double baseline_frac = filler_.hugepage_frac();
printf("%.3f %.3f %6.1f MiB\n", peak_frac, baseline_frac,
BytesToMiB(footprint));
}
}
TEST_P(FillerTest, ReleaseAccounting) {
const Length N = kPagesPerHugePage;
auto big = Allocate(N - Length(2));
auto tiny1 = Allocate(Length(1));
auto tiny2 = Allocate(Length(1));
auto half1 = Allocate(N / 2);
auto half2 = Allocate(N / 2);
Delete(half1);
Delete(big);
ASSERT_EQ(NHugePages(2), filler_.size());
// We should pick the [empty big][full tiny] hugepage here.
EXPECT_EQ(N - Length(2), ReleasePages(N - Length(2)));
EXPECT_EQ(N - Length(2), filler_.unmapped_pages());
// This shouldn't trigger a release
Delete(tiny1);
if (GetParam() == FillerPartialRerelease::Retain) {
EXPECT_EQ(N - Length(2), filler_.unmapped_pages());
// Until we call ReleasePages()
EXPECT_EQ(Length(1), ReleasePages(Length(1)));
}
EXPECT_EQ(N - Length(1), filler_.unmapped_pages());
// As should this, but this will drop the whole hugepage
Delete(tiny2);
EXPECT_EQ(Length(0), filler_.unmapped_pages());
EXPECT_EQ(NHugePages(1), filler_.size());
// This shouldn't trigger any release: we just claim credit for the
// releases we did automatically on tiny2.
if (GetParam() == FillerPartialRerelease::Retain) {
EXPECT_EQ(Length(1), ReleasePages(Length(1)));
} else {
EXPECT_EQ(Length(2), ReleasePages(Length(2)));
}
EXPECT_EQ(Length(0), filler_.unmapped_pages());
EXPECT_EQ(NHugePages(1), filler_.size());
// Check subrelease stats
EXPECT_EQ(N / 2, filler_.used_pages());
EXPECT_EQ(Length(0), filler_.used_pages_in_any_subreleased());
EXPECT_EQ(Length(0), filler_.used_pages_in_partial_released());
EXPECT_EQ(Length(0), filler_.used_pages_in_released());
// Now we pick the half/half hugepage
EXPECT_EQ(N / 2, ReleasePages(kMaxValidPages));
EXPECT_EQ(N / 2, filler_.unmapped_pages());
// Check subrelease stats
EXPECT_EQ(N / 2, filler_.used_pages());
EXPECT_EQ(N / 2, filler_.used_pages_in_any_subreleased());
EXPECT_EQ(Length(0), filler_.used_pages_in_partial_released());
EXPECT_EQ(N / 2, filler_.used_pages_in_released());
// Check accounting for partially released hugepages with partial rerelease
if (GetParam() == FillerPartialRerelease::Retain) {
// Allocating and deallocating a small object causes the page to turn from
// a released hugepage into a partially released hugepage.
auto tiny3 = Allocate(Length(1));
auto tiny4 = Allocate(Length(1));
Delete(tiny4);
EXPECT_EQ(N / 2 + Length(1), filler_.used_pages());
EXPECT_EQ(N / 2 + Length(1), filler_.used_pages_in_any_subreleased());
EXPECT_EQ(N / 2 + Length(1), filler_.used_pages_in_partial_released());
EXPECT_EQ(Length(0), filler_.used_pages_in_released());
Delete(tiny3);
}
Delete(half2);
EXPECT_EQ(NHugePages(0), filler_.size());
EXPECT_EQ(Length(0), filler_.unmapped_pages());
}
TEST_P(FillerTest, ReleaseWithReuse) {
const Length N = kPagesPerHugePage;
auto half = Allocate(N / 2);
auto tiny1 = Allocate(N / 4);
auto tiny2 = Allocate(N / 4);
Delete(half);
ASSERT_EQ(NHugePages(1), filler_.size());
// We should be able to release the pages from half1.
EXPECT_EQ(N / 2, ReleasePages(kMaxValidPages));
EXPECT_EQ(N / 2, filler_.unmapped_pages());
// Release tiny1, release more.
Delete(tiny1);
EXPECT_EQ(N / 4, ReleasePages(kMaxValidPages));
EXPECT_EQ(3 * N / 4, filler_.unmapped_pages());
// Repopulate, confirm we can't release anything and unmapped pages goes to 0.
tiny1 = Allocate(N / 4);
EXPECT_EQ(Length(0), ReleasePages(kMaxValidPages));
EXPECT_EQ(N / 2, filler_.unmapped_pages());
// Continue repopulating.
half = Allocate(N / 2);
EXPECT_EQ(Length(0), ReleasePages(kMaxValidPages));
EXPECT_EQ(Length(0), filler_.unmapped_pages());
EXPECT_EQ(NHugePages(1), filler_.size());
// Release everything and cleanup.
Delete(half);
Delete(tiny1);
Delete(tiny2);
EXPECT_EQ(NHugePages(0), filler_.size());
EXPECT_EQ(Length(0), filler_.unmapped_pages());
}
TEST_P(FillerTest, AvoidArbitraryQuarantineVMGrowth) {
const Length N = kPagesPerHugePage;
// Guarantee we have a ton of released pages go empty.
for (int i = 0; i < 10 * 1000; ++i) {
auto half1 = Allocate(N / 2);
auto half2 = Allocate(N / 2);
Delete(half1);
ASSERT_EQ(N / 2, ReleasePages(N / 2));
Delete(half2);
}
auto s = filler_.stats();
EXPECT_GE(1024 * 1024 * 1024, s.system_bytes);
}
TEST_P(FillerTest, StronglyPreferNonDonated) {
// We donate several huge pages of varying fullnesses. Then we make several
// allocations that would be perfect fits for the donated hugepages, *after*
// making one allocation that won't fit, to ensure that a huge page is
// contributed normally. Finally, we verify that we can still get the
// donated huge pages back. (I.e. they weren't used.)
std::vector<PAlloc> donated;
ASSERT_GE(kPagesPerHugePage, Length(10));
for (auto i = Length(1); i <= Length(3); ++i) {
donated.push_back(Allocate(kPagesPerHugePage - i, /*donated=*/true));
}
std::vector<PAlloc> regular;
for (auto i = Length(4); i >= Length(1); --i) {
regular.push_back(Allocate(i));
}
for (const PAlloc& alloc : donated) {
// All the donated huge pages should be freeable.
EXPECT_TRUE(Delete(alloc));
}
for (const PAlloc& alloc : regular) {
Delete(alloc);
}
}
TEST_P(FillerTest, ParallelUnlockingSubrelease) {
if (GetParam() == FillerPartialRerelease::Retain) {
// When rerelease happens without going to Unback(), this test
// (intentionally) deadlocks, as we never receive the call.
return;
}
// Verify that we can deallocate a partial huge page and successfully unlock
// the pageheap_lock without introducing race conditions around the metadata
// for PageTracker::released_.
//
// Currently, HPAA unbacks *all* subsequent deallocations to a huge page once
// we have broken up *any* part of it.
//
// If multiple deallocations are in-flight, we need to leave sufficient
// breadcrumbs to ourselves (PageTracker::releasing_ is a Length, not a bool)
// so that one deallocation completing does not have us "forget" that another
// deallocation is about to unback other parts of the hugepage.
//
// If PageTracker::releasing_ were a bool, the completion of "t1" and
// subsequent reallocation of "a2" in this test would mark the entirety of the
// page as full, so we would choose to *not* unback a2 (when deallocated) or
// a3 (when deallocated by t3).
constexpr Length N = kPagesPerHugePage;
auto a1 = AllocateRaw(N / 2);
auto a2 = AllocateRaw(Length(1));
auto a3 = AllocateRaw(Length(1));
// Trigger subrelease. The filler now has a partial hugepage, so subsequent
// calls to Delete() will cause us to unback the remainder of it.
EXPECT_GT(ReleasePages(kMaxValidPages), Length(0));
auto m1 = absl::make_unique<absl::Mutex>();
auto m2 = absl::make_unique<absl::Mutex>();
m1->Lock();
m2->Lock();
absl::BlockingCounter counter(2);
BlockingUnback::counter = &counter;
std::thread t1([&]() {
BlockingUnback::set_lock(m1.get());
DeleteRaw(a2);
});
std::thread t2([&]() {
BlockingUnback::set_lock(m2.get());
DeleteRaw(a3);
});
// Wait for t1 and t2 to block.
counter.Wait();
// At this point, t1 and t2 are blocked (as if they were on a long-running
// syscall) on "unback" (m1 and m2, respectively). pageheap_lock is not held.
//
// Allocating a4 will complete the hugepage, but we have on-going releaser
// threads.
auto a4 = AllocateRaw((N / 2) - Length(2));
EXPECT_EQ(NHugePages(1), filler_.size());
// Let one of the threads proceed. The huge page consists of:
// * a1 (N/2 ): Allocated
// * a2 ( 1): Unbacked
// * a3 ( 1): Unbacking (blocked on m2)
// * a4 (N/2-2): Allocated
m1->Unlock();
t1.join();
// Reallocate a2. We should still consider the huge page partially backed for
// purposes of subreleasing.
a2 = AllocateRaw(Length(1));
EXPECT_EQ(NHugePages(1), filler_.size());
DeleteRaw(a2);
// Let the other thread proceed. The huge page consists of:
// * a1 (N/2 ): Allocated
// * a2 ( 1): Unbacked
// * a3 ( 1): Unbacked
// * a4 (N/2-2): Allocated
m2->Unlock();
t2.join();
EXPECT_EQ(filler_.used_pages(), N - Length(2));
EXPECT_EQ(filler_.unmapped_pages(), Length(2));
EXPECT_EQ(filler_.free_pages(), Length(0));
// Clean up.
DeleteRaw(a1);
DeleteRaw(a4);
BlockingUnback::counter = nullptr;
}
TEST_P(FillerTest, SkipSubrelease) {
// This test is sensitive to the number of pages per hugepage, as we are
// printing raw stats.
if (kPagesPerHugePage != Length(256)) {
GTEST_SKIP();
}
// Generate a peak, wait for time interval a, generate a trough, subrelease,
// wait for time interval b, generate another peak.
const auto peak_trough_peak = [&](absl::Duration a, absl::Duration b,
absl::Duration peak_interval,
bool expected_subrelease) {
const Length N = kPagesPerHugePage;
PAlloc half = Allocate(N / 2);
PAlloc tiny1 = Allocate(N / 4);
PAlloc tiny2 = Allocate(N / 4);
// To force a peak, we allocate 3/4 and 1/4 of a huge page. This is
// necessary after we delete `half` below, as a half huge page for the peak
// would fill into the gap previously occupied by it.
PAlloc peak1a = Allocate(3 * N / 4);
PAlloc peak1b = Allocate(N / 4);
EXPECT_EQ(filler_.used_pages(), 2 * N);
Delete(peak1a);
Delete(peak1b);
Advance(a);
Delete(half);
EXPECT_EQ(expected_subrelease ? N / 2 : Length(0),
ReleasePages(10 * N, peak_interval));
Advance(b);
PAlloc peak2a = Allocate(3 * N / 4);
PAlloc peak2b = Allocate(N / 4);
PAlloc peak3a = Allocate(3 * N / 4);
PAlloc peak3b = Allocate(N / 4);
Delete(tiny1);
Delete(tiny2);
Delete(peak2a);
Delete(peak2b);
Delete(peak3a);
Delete(peak3b);
EXPECT_EQ(filler_.used_pages(), Length(0));
EXPECT_EQ(filler_.unmapped_pages(), Length(0));
EXPECT_EQ(filler_.free_pages(), Length(0));
EXPECT_EQ(expected_subrelease ? N / 2 : Length(0), ReleasePages(10 * N));
};
{
SCOPED_TRACE("peak-trough-peak 1");
peak_trough_peak(absl::Minutes(2), absl::Minutes(2), absl::Minutes(3),
false);
}
Advance(absl::Minutes(30));
{
SCOPED_TRACE("peak-trough-peak 2");
peak_trough_peak(absl::Minutes(2), absl::Minutes(7), absl::Minutes(3),
false);
}
Advance(absl::Minutes(30));
{
SCOPED_TRACE("peak-trough-peak 3");
peak_trough_peak(absl::Minutes(5), absl::Minutes(3), absl::Minutes(2),
true);
}
Advance(absl::Minutes(30));
// This captures a corner case: If we hit another peak immediately after a
// subrelease decision (in the same time series epoch), do not count this as
// a correct subrelease decision.
{
SCOPED_TRACE("peak-trough-peak 4");
peak_trough_peak(absl::Milliseconds(10), absl::Milliseconds(10),
absl::Minutes(2), false);
}
Advance(absl::Minutes(30));
// Ensure that the tracker is updated.
auto tiny = Allocate(Length(1));
Delete(tiny);
std::string buffer(1024 * 1024, '\0');
{
TCMalloc_Printer printer(&*buffer.begin(), buffer.size());
filler_.Print(&printer, true);
}
buffer.resize(strlen(buffer.c_str()));
EXPECT_THAT(buffer, testing::HasSubstr(R"(
HugePageFiller: Since the start of the execution, 4 subreleases (512 pages) were skipped due to recent (120s) peaks.
HugePageFiller: 25.0000% of decisions confirmed correct, 0 pending (25.0000% of pages, 0 pending).
)"));
}
class FillerStatsTrackerTest : public testing::Test {
private:
static int64_t clock_;
static int64_t FakeClock() { return clock_; }
static double GetFakeClockFrequency() {
return absl::ToDoubleNanoseconds(absl::Seconds(2));
}
protected:
static constexpr absl::Duration kWindow = absl::Minutes(10);
using StatsTrackerType = tcmalloc::FillerStatsTracker<16>;
StatsTrackerType tracker_{
Clock{.now = FakeClock, .freq = GetFakeClockFrequency}, kWindow,
absl::Minutes(5)};
void Advance(absl::Duration d) {
clock_ += static_cast<int64_t>(absl::ToDoubleSeconds(d) *
GetFakeClockFrequency());
}
// Generates four data points for the tracker that represent "interesting"
// points (i.e., min/max pages demand, min/max hugepages).
void GenerateInterestingPoints(Length num_pages, HugeLength num_hugepages,
Length num_free_pages);
// Generates a data point with a particular amount of demand pages, while
// ignoring the specific number of hugepages.
void GenerateDemandPoint(Length num_pages, Length num_free_pages);
};
int64_t FillerStatsTrackerTest::clock_{0};
void FillerStatsTrackerTest::GenerateInterestingPoints(Length num_pages,
HugeLength num_hugepages,
Length num_free_pages) {
for (int i = 0; i <= 1; ++i) {
for (int j = 0; j <= 1; ++j) {
StatsTrackerType::FillerStats stats;
stats.num_pages = num_pages + Length((i == 0) ? 4 : 8 * j);
stats.free_pages = num_free_pages + Length(10 * i + j);
stats.unmapped_pages = Length(10);
stats.used_pages_in_subreleased_huge_pages = num_pages;
stats.huge_pages[StatsTrackerType::kRegular] =
num_hugepages + ((i == 1) ? NHugePages(4) : NHugePages(8) * j);
stats.huge_pages[StatsTrackerType::kDonated] = num_hugepages;
stats.huge_pages[StatsTrackerType::kPartialReleased] = NHugePages(i);
stats.huge_pages[StatsTrackerType::kReleased] = NHugePages(j);
tracker_.Report(stats);
}
}
}
void FillerStatsTrackerTest::GenerateDemandPoint(Length num_pages,
Length num_free_pages) {
HugeLength hp = NHugePages(1);
StatsTrackerType::FillerStats stats;
stats.num_pages = num_pages;
stats.free_pages = num_free_pages;
stats.unmapped_pages = Length(0);
stats.used_pages_in_subreleased_huge_pages = Length(0);
stats.huge_pages[StatsTrackerType::kRegular] = hp;
stats.huge_pages[StatsTrackerType::kDonated] = hp;
stats.huge_pages[StatsTrackerType::kPartialReleased] = hp;
stats.huge_pages[StatsTrackerType::kReleased] = hp;
tracker_.Report(stats);
}
// Tests that the tracker aggregates all data correctly. The output is tested by
// comparing the text output of the tracker. While this is a bit verbose, it is
// much cleaner than extracting and comparing all data manually.
TEST_F(FillerStatsTrackerTest, Works) {
// Ensure that the beginning (when free pages are 0) is outside the 5-min
// window the instrumentation is recording.
GenerateInterestingPoints(Length(1), NHugePages(1), Length(1));
Advance(absl::Minutes(5));
GenerateInterestingPoints(Length(100), NHugePages(5), Length(200));
Advance(absl::Minutes(1));
GenerateInterestingPoints(Length(200), NHugePages(10), Length(100));
Advance(absl::Minutes(1));
// Test text output (time series summary).
{
std::string buffer(1024 * 1024, '\0');
TCMalloc_Printer printer(&*buffer.begin(), buffer.size());
{
tracker_.Print(&printer);
buffer.erase(printer.SpaceRequired());
}
EXPECT_THAT(buffer, StrEq(R"(HugePageFiller: time series over 5 min interval
HugePageFiller: minimum free pages: 110 (100 backed)
HugePageFiller: at peak demand: 208 pages (and 111 free, 10 unmapped)
HugePageFiller: at peak demand: 26 hps (14 regular, 10 donated, 1 partial, 1 released)
HugePageFiller: at peak hps: 208 pages (and 111 free, 10 unmapped)
HugePageFiller: at peak hps: 26 hps (14 regular, 10 donated, 1 partial, 1 released)
HugePageFiller: Since the start of the execution, 0 subreleases (0 pages) were skipped due to recent (0s) peaks.
HugePageFiller: 0.0000% of decisions confirmed correct, 0 pending (0.0000% of pages, 0 pending).
HugePageFiller: Subrelease stats last 10 min: total 0 pages subreleased, 0 hugepages broken
)"));
}
// Test pbtxt output (full time series).
{
std::string buffer(1024 * 1024, '\0');
TCMalloc_Printer printer(&*buffer.begin(), buffer.size());
{
PbtxtRegion region(&printer, kTop, /*indent=*/0);
tracker_.PrintInPbtxt(®ion);
}
buffer.erase(printer.SpaceRequired());
EXPECT_THAT(buffer, StrEq(R"(
filler_skipped_subrelease {
skipped_subrelease_interval_ms: 0
skipped_subrelease_pages: 0
correctly_skipped_subrelease_pages: 0
pending_skipped_subrelease_pages: 0
skipped_subrelease_count: 0
correctly_skipped_subrelease_count: 0
pending_skipped_subrelease_count: 0
}
filler_stats_timeseries {
window_ms: 37500
epochs: 16
min_free_pages_interval_ms: 300000
min_free_pages: 110
min_free_backed_pages: 100
measurements {
epoch: 6
timestamp_ms: 0
min_free_pages: 11
min_free_backed_pages: 1
num_pages_subreleased: 0
num_hugepages_broken: 0
at_minimum_demand {
num_pages: 1
regular_huge_pages: 5
donated_huge_pages: 1
partial_released_huge_pages: 1
released_huge_pages: 0
used_pages_in_subreleased_huge_pages: 1
}
at_maximum_demand {
num_pages: 9
regular_huge_pages: 5
donated_huge_pages: 1
partial_released_huge_pages: 1
released_huge_pages: 1
used_pages_in_subreleased_huge_pages: 1
}
at_minimum_huge_pages {
num_pages: 5
regular_huge_pages: 1
donated_huge_pages: 1
partial_released_huge_pages: 0
released_huge_pages: 0
used_pages_in_subreleased_huge_pages: 1
}
at_maximum_huge_pages {
num_pages: 5
regular_huge_pages: 9
donated_huge_pages: 1
partial_released_huge_pages: 0
released_huge_pages: 1
used_pages_in_subreleased_huge_pages: 1
}
}
measurements {
epoch: 14
timestamp_ms: 300000
min_free_pages: 210
min_free_backed_pages: 200
num_pages_subreleased: 0
num_hugepages_broken: 0
at_minimum_demand {
num_pages: 100
regular_huge_pages: 9
donated_huge_pages: 5
partial_released_huge_pages: 1
released_huge_pages: 0
used_pages_in_subreleased_huge_pages: 100
}
at_maximum_demand {
num_pages: 108
regular_huge_pages: 9
donated_huge_pages: 5
partial_released_huge_pages: 1
released_huge_pages: 1
used_pages_in_subreleased_huge_pages: 100
}
at_minimum_huge_pages {
num_pages: 104
regular_huge_pages: 5
donated_huge_pages: 5
partial_released_huge_pages: 0
released_huge_pages: 0
used_pages_in_subreleased_huge_pages: 100
}
at_maximum_huge_pages {
num_pages: 104
regular_huge_pages: 13
donated_huge_pages: 5
partial_released_huge_pages: 0
released_huge_pages: 1
used_pages_in_subreleased_huge_pages: 100
}
}
measurements {
epoch: 15
timestamp_ms: 337500
min_free_pages: 110
min_free_backed_pages: 100
num_pages_subreleased: 0
num_hugepages_broken: 0
at_minimum_demand {
num_pages: 200
regular_huge_pages: 14
donated_huge_pages: 10
partial_released_huge_pages: 1
released_huge_pages: 0
used_pages_in_subreleased_huge_pages: 200
}
at_maximum_demand {
num_pages: 208
regular_huge_pages: 14
donated_huge_pages: 10
partial_released_huge_pages: 1
released_huge_pages: 1
used_pages_in_subreleased_huge_pages: 200
}
at_minimum_huge_pages {
num_pages: 204
regular_huge_pages: 10
donated_huge_pages: 10
partial_released_huge_pages: 0
released_huge_pages: 0
used_pages_in_subreleased_huge_pages: 200
}
at_maximum_huge_pages {
num_pages: 204
regular_huge_pages: 18
donated_huge_pages: 10
partial_released_huge_pages: 0
released_huge_pages: 1
used_pages_in_subreleased_huge_pages: 200
}
}
}
)"));
}
}
TEST_F(FillerStatsTrackerTest, InvalidDurations) {
// These should not crash.
tracker_.min_free_pages(absl::InfiniteDuration());
tracker_.min_free_pages(kWindow + absl::Seconds(1));
tracker_.min_free_pages(-(kWindow + absl::Seconds(1)));
tracker_.min_free_pages(-absl::InfiniteDuration());
}
TEST_F(FillerStatsTrackerTest, ComputeRecentPeaks) {
GenerateDemandPoint(Length(3000), Length(1000));
Advance(absl::Minutes(1.25));
GenerateDemandPoint(Length(1500), Length(0));
Advance(absl::Minutes(1));
GenerateDemandPoint(Length(100), Length(2000));
Advance(absl::Minutes(1));
GenerateDemandPoint(Length(200), Length(3000));
GenerateDemandPoint(Length(200), Length(3000));
FillerStatsTracker<>::FillerStats stats =
tracker_.GetRecentPeak(absl::Minutes(3));
EXPECT_EQ(stats.num_pages, Length(1500));
EXPECT_EQ(stats.free_pages, Length(0));
FillerStatsTracker<>::FillerStats stats2 =
tracker_.GetRecentPeak(absl::Minutes(5));
EXPECT_EQ(stats2.num_pages, Length(3000));
EXPECT_EQ(stats2.free_pages, Length(1000));
Advance(absl::Minutes(4));
GenerateDemandPoint(Length(200), Length(3000));
FillerStatsTracker<>::FillerStats stats3 =
tracker_.GetRecentPeak(absl::Minutes(4));
EXPECT_EQ(stats3.num_pages, Length(200));
EXPECT_EQ(stats3.free_pages, Length(3000));
Advance(absl::Minutes(5));
GenerateDemandPoint(Length(200), Length(3000));
FillerStatsTracker<>::FillerStats stats4 =
tracker_.GetRecentPeak(absl::Minutes(5));
EXPECT_EQ(stats4.num_pages, Length(200));
EXPECT_EQ(stats4.free_pages, Length(3000));
}
TEST_F(FillerStatsTrackerTest, TrackCorrectSubreleaseDecisions) {
// First peak (large)
GenerateDemandPoint(Length(1000), Length(1000));
// Incorrect subrelease: Subrelease to 1000
Advance(absl::Minutes(1));
GenerateDemandPoint(Length(100), Length(1000));
tracker_.ReportSkippedSubreleasePages(Length(900), Length(1000),
absl::Minutes(3));
// Second peak (small)
Advance(absl::Minutes(1));
GenerateDemandPoint(Length(500), Length(1000));
EXPECT_EQ(tracker_.total_skipped().pages, Length(900));
EXPECT_EQ(tracker_.total_skipped().count, 1);
EXPECT_EQ(tracker_.correctly_skipped().pages, Length(0));
EXPECT_EQ(tracker_.correctly_skipped().count, 0);
EXPECT_EQ(tracker_.pending_skipped().pages, Length(900));
EXPECT_EQ(tracker_.pending_skipped().count, 1);
// Correct subrelease: Subrelease to 500
Advance(absl::Minutes(1));
GenerateDemandPoint(Length(500), Length(100));
tracker_.ReportSkippedSubreleasePages(Length(50), Length(550),
absl::Minutes(3));
GenerateDemandPoint(Length(500), Length(50));
tracker_.ReportSkippedSubreleasePages(Length(50), Length(500),
absl::Minutes(3));
GenerateDemandPoint(Length(500), Length(0));
EXPECT_EQ(tracker_.total_skipped().pages, Length(1000));
EXPECT_EQ(tracker_.total_skipped().count, 3);
EXPECT_EQ(tracker_.correctly_skipped().pages, Length(0));
EXPECT_EQ(tracker_.correctly_skipped().count, 0);
EXPECT_EQ(tracker_.pending_skipped().pages, Length(1000));
EXPECT_EQ(tracker_.pending_skipped().count, 3);
// Third peak (large, too late for first peak)
Advance(absl::Minutes(1));
GenerateDemandPoint(Length(1100), Length(1000));
Advance(absl::Minutes(5));
GenerateDemandPoint(Length(1100), Length(1000));
EXPECT_EQ(tracker_.total_skipped().pages, Length(1000));
EXPECT_EQ(tracker_.total_skipped().count, 3);
EXPECT_EQ(tracker_.correctly_skipped().pages, Length(100));
EXPECT_EQ(tracker_.correctly_skipped().count, 2);
EXPECT_EQ(tracker_.pending_skipped().pages, Length(0));
EXPECT_EQ(tracker_.pending_skipped().count, 0);
}
TEST_F(FillerStatsTrackerTest, SubreleaseCorrectnessWithChangingIntervals) {
// First peak (large)
GenerateDemandPoint(Length(1000), Length(1000));
Advance(absl::Minutes(1));
GenerateDemandPoint(Length(100), Length(1000));
tracker_.ReportSkippedSubreleasePages(Length(50), Length(1000),
absl::Minutes(4));
Advance(absl::Minutes(1));
// With two correctness intervals in the same epoch, take the maximum
tracker_.ReportSkippedSubreleasePages(Length(100), Length(1000),
absl::Minutes(1));
tracker_.ReportSkippedSubreleasePages(Length(200), Length(1000),
absl::Minutes(7));
Advance(absl::Minutes(5));
GenerateDemandPoint(Length(1100), Length(1000));
Advance(absl::Minutes(10));
GenerateDemandPoint(Length(1100), Length(1000));
EXPECT_EQ(tracker_.total_skipped().pages, Length(350));
EXPECT_EQ(tracker_.total_skipped().count, 3);
EXPECT_EQ(tracker_.correctly_skipped().pages, Length(300));
EXPECT_EQ(tracker_.correctly_skipped().count, 2);
EXPECT_EQ(tracker_.pending_skipped().pages, Length(0));
EXPECT_EQ(tracker_.pending_skipped().count, 0);
}
std::vector<FillerTest::PAlloc> FillerTest::GenerateInterestingAllocs() {
PAlloc a = Allocate(Length(1));
EXPECT_EQ(ReleasePages(kMaxValidPages), kPagesPerHugePage - Length(1));
Delete(a);
// Get the report on the released page
EXPECT_EQ(ReleasePages(kMaxValidPages), Length(1));
// Use a maximally-suboptimal pattern to get lots of hugepages into the
// filler.
std::vector<PAlloc> result;
static_assert(kPagesPerHugePage > Length(7),
"Not enough pages per hugepage!");
for (auto i = Length(0); i < Length(7); ++i) {
result.push_back(Allocate(kPagesPerHugePage - i - Length(1)));
}
// Get two released hugepages.
EXPECT_EQ(ReleasePages(Length(7)), Length(7));
EXPECT_EQ(ReleasePages(Length(6)), Length(6));
// Fill some of the remaining pages with small allocations.
for (int i = 0; i < 9; ++i) {
result.push_back(Allocate(Length(1)));
}
// Finally, donate one hugepage.
result.push_back(Allocate(Length(1), /*donated=*/true));
return result;
}
// Test the output of Print(). This is something of a change-detector test,
// but that's not all bad in this case.
TEST_P(FillerTest, Print) {
if (kPagesPerHugePage != Length(256)) {
// The output is hardcoded on this assumption, and dynamically calculating
// it would be way too much of a pain.
return;
}
auto allocs = GenerateInterestingAllocs();
std::string buffer(1024 * 1024, '\0');
{
TCMalloc_Printer printer(&*buffer.begin(), buffer.size());
filler_.Print(&printer, /*everything=*/true);
buffer.erase(printer.SpaceRequired());
}
EXPECT_THAT(
buffer,
StrEq(R"(HugePageFiller: densely pack small requests into hugepages
HugePageFiller: 8 total, 3 full, 3 partial, 2 released (0 partially), 0 quarantined
HugePageFiller: 261 pages free in 8 hugepages, 0.1274 free
HugePageFiller: among non-fulls, 0.3398 free
HugePageFiller: 499 used pages in subreleased hugepages (0 of them in partially released)
HugePageFiller: 2 hugepages partially released, 0.0254 released
HugePageFiller: 0.7187 of used pages hugepageable
HugePageFiller: Since startup, 269 pages subreleased, 3 hugepages broken, (0 pages, 0 hugepages due to reaching tcmalloc limit)
HugePageFiller: fullness histograms
HugePageFiller: # of regular hps with a<= # of free pages <b
HugePageFiller: < 0<= 3 < 1<= 1 < 2<= 0 < 3<= 0 < 4<= 1 < 16<= 0
HugePageFiller: < 32<= 0 < 48<= 0 < 64<= 0 < 80<= 0 < 96<= 0 <112<= 0
HugePageFiller: <128<= 0 <144<= 0 <160<= 0 <176<= 0 <192<= 0 <208<= 0
HugePageFiller: <224<= 0 <240<= 0 <252<= 0 <253<= 0 <254<= 0 <255<= 0
HugePageFiller: # of donated hps with a<= # of free pages <b
HugePageFiller: < 0<= 0 < 1<= 0 < 2<= 0 < 3<= 0 < 4<= 0 < 16<= 0
HugePageFiller: < 32<= 0 < 48<= 0 < 64<= 0 < 80<= 0 < 96<= 0 <112<= 0
HugePageFiller: <128<= 0 <144<= 0 <160<= 0 <176<= 0 <192<= 0 <208<= 0
HugePageFiller: <224<= 0 <240<= 0 <252<= 0 <253<= 0 <254<= 0 <255<= 1
HugePageFiller: # of partial released hps with a<= # of free pages <b
HugePageFiller: < 0<= 0 < 1<= 0 < 2<= 0 < 3<= 0 < 4<= 0 < 16<= 0
HugePageFiller: < 32<= 0 < 48<= 0 < 64<= 0 < 80<= 0 < 96<= 0 <112<= 0
HugePageFiller: <128<= 0 <144<= 0 <160<= 0 <176<= 0 <192<= 0 <208<= 0
HugePageFiller: <224<= 0 <240<= 0 <252<= 0 <253<= 0 <254<= 0 <255<= 0
HugePageFiller: # of released hps with a<= # of free pages <b
HugePageFiller: < 0<= 0 < 1<= 0 < 2<= 0 < 3<= 0 < 4<= 2 < 16<= 0
HugePageFiller: < 32<= 0 < 48<= 0 < 64<= 0 < 80<= 0 < 96<= 0 <112<= 0
HugePageFiller: <128<= 0 <144<= 0 <160<= 0 <176<= 0 <192<= 0 <208<= 0
HugePageFiller: <224<= 0 <240<= 0 <252<= 0 <253<= 0 <254<= 0 <255<= 0
HugePageFiller: # of regular hps with a<= longest free range <b
HugePageFiller: < 0<= 3 < 1<= 1 < 2<= 0 < 3<= 0 < 4<= 1 < 16<= 0
HugePageFiller: < 32<= 0 < 48<= 0 < 64<= 0 < 80<= 0 < 96<= 0 <112<= 0
HugePageFiller: <128<= 0 <144<= 0 <160<= 0 <176<= 0 <192<= 0 <208<= 0
HugePageFiller: <224<= 0 <240<= 0 <252<= 0 <253<= 0 <254<= 0 <255<= 0
HugePageFiller: # of partial released hps with a<= longest free range <b
HugePageFiller: < 0<= 0 < 1<= 0 < 2<= 0 < 3<= 0 < 4<= 0 < 16<= 0
HugePageFiller: < 32<= 0 < 48<= 0 < 64<= 0 < 80<= 0 < 96<= 0 <112<= 0
HugePageFiller: <128<= 0 <144<= 0 <160<= 0 <176<= 0 <192<= 0 <208<= 0
HugePageFiller: <224<= 0 <240<= 0 <252<= 0 <253<= 0 <254<= 0 <255<= 0
HugePageFiller: # of released hps with a<= longest free range <b
HugePageFiller: < 0<= 0 < 1<= 0 < 2<= 0 < 3<= 0 < 4<= 2 < 16<= 0
HugePageFiller: < 32<= 0 < 48<= 0 < 64<= 0 < 80<= 0 < 96<= 0 <112<= 0
HugePageFiller: <128<= 0 <144<= 0 <160<= 0 <176<= 0 <192<= 0 <208<= 0
HugePageFiller: <224<= 0 <240<= 0 <252<= 0 <253<= 0 <254<= 0 <255<= 0
HugePageFiller: # of regular hps with a<= # of allocations <b
HugePageFiller: < 1<= 1 < 2<= 1 < 3<= 1 < 4<= 2 < 5<= 0 < 17<= 0
HugePageFiller: < 33<= 0 < 49<= 0 < 65<= 0 < 81<= 0 < 97<= 0 <113<= 0
HugePageFiller: <129<= 0 <145<= 0 <161<= 0 <177<= 0 <193<= 0 <209<= 0
HugePageFiller: <225<= 0 <241<= 0 <253<= 0 <254<= 0 <255<= 0 <256<= 0
HugePageFiller: # of partial released hps with a<= # of allocations <b
HugePageFiller: < 1<= 0 < 2<= 0 < 3<= 0 < 4<= 0 < 5<= 0 < 17<= 0
HugePageFiller: < 33<= 0 < 49<= 0 < 65<= 0 < 81<= 0 < 97<= 0 <113<= 0
HugePageFiller: <129<= 0 <145<= 0 <161<= 0 <177<= 0 <193<= 0 <209<= 0
HugePageFiller: <225<= 0 <241<= 0 <253<= 0 <254<= 0 <255<= 0 <256<= 0
HugePageFiller: # of released hps with a<= # of allocations <b
HugePageFiller: < 1<= 2 < 2<= 0 < 3<= 0 < 4<= 0 < 5<= 0 < 17<= 0
HugePageFiller: < 33<= 0 < 49<= 0 < 65<= 0 < 81<= 0 < 97<= 0 <113<= 0
HugePageFiller: <129<= 0 <145<= 0 <161<= 0 <177<= 0 <193<= 0 <209<= 0
HugePageFiller: <225<= 0 <241<= 0 <253<= 0 <254<= 0 <255<= 0 <256<= 0
HugePageFiller: time series over 5 min interval
HugePageFiller: minimum free pages: 0 (0 backed)
HugePageFiller: at peak demand: 1774 pages (and 261 free, 13 unmapped)
HugePageFiller: at peak demand: 8 hps (5 regular, 1 donated, 0 partial, 2 released)
HugePageFiller: at peak hps: 1774 pages (and 261 free, 13 unmapped)
HugePageFiller: at peak hps: 8 hps (5 regular, 1 donated, 0 partial, 2 released)
HugePageFiller: Since the start of the execution, 0 subreleases (0 pages) were skipped due to recent (0s) peaks.
HugePageFiller: 0.0000% of decisions confirmed correct, 0 pending (0.0000% of pages, 0 pending).
HugePageFiller: Subrelease stats last 10 min: total 269 pages subreleased, 3 hugepages broken
)"));
for (const auto& alloc : allocs) {
Delete(alloc);
}
}
// Test the output of PrintInPbtxt(). This is something of a change-detector
// test, but that's not all bad in this case.
TEST_P(FillerTest, PrintInPbtxt) {
if (kPagesPerHugePage != Length(256)) {
// The output is hardcoded on this assumption, and dynamically calculating
// it would be way too much of a pain.
return;
}
auto allocs = GenerateInterestingAllocs();
std::string buffer(1024 * 1024, '\0');
TCMalloc_Printer printer(&*buffer.begin(), buffer.size());
{
PbtxtRegion region(&printer, kTop, /*indent=*/0);
filler_.PrintInPbtxt(®ion);
}
buffer.erase(printer.SpaceRequired());
EXPECT_THAT(buffer, StrEq(R"(
filler_full_huge_pages: 3
filler_partial_huge_pages: 3
filler_released_huge_pages: 2
filler_partially_released_huge_pages: 0
filler_free_pages: 261
filler_used_pages_in_subreleased: 499
filler_used_pages_in_partial_released: 0
filler_unmapped_bytes: 0
filler_hugepageable_used_bytes: 10444800
filler_num_pages_subreleased: 269
filler_num_hugepages_broken: 3
filler_num_pages_subreleased_due_to_limit: 0
filler_num_hugepages_broken_due_to_limit: 0
filler_tracker {
type: REGULAR
free_pages_histogram {
lower_bound: 0
upper_bound: 0
value: 3
}
free_pages_histogram {
lower_bound: 1
upper_bound: 1
value: 1
}
free_pages_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
free_pages_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
free_pages_histogram {
lower_bound: 4
upper_bound: 15
value: 1
}
free_pages_histogram {
lower_bound: 16
upper_bound: 31
value: 0
}
free_pages_histogram {
lower_bound: 32
upper_bound: 47
value: 0
}
free_pages_histogram {
lower_bound: 48
upper_bound: 63
value: 0
}
free_pages_histogram {
lower_bound: 64
upper_bound: 79
value: 0
}
free_pages_histogram {
lower_bound: 80
upper_bound: 95
value: 0
}
free_pages_histogram {
lower_bound: 96
upper_bound: 111
value: 0
}
free_pages_histogram {
lower_bound: 112
upper_bound: 127
value: 0
}
free_pages_histogram {
lower_bound: 128
upper_bound: 143
value: 0
}
free_pages_histogram {
lower_bound: 144
upper_bound: 159
value: 0
}
free_pages_histogram {
lower_bound: 160
upper_bound: 175
value: 0
}
free_pages_histogram {
lower_bound: 176
upper_bound: 191
value: 0
}
free_pages_histogram {
lower_bound: 192
upper_bound: 207
value: 0
}
free_pages_histogram {
lower_bound: 208
upper_bound: 223
value: 0
}
free_pages_histogram {
lower_bound: 224
upper_bound: 239
value: 0
}
free_pages_histogram {
lower_bound: 240
upper_bound: 251
value: 0
}
free_pages_histogram {
lower_bound: 252
upper_bound: 252
value: 0
}
free_pages_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
free_pages_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
free_pages_histogram {
lower_bound: 255
upper_bound: 255
value: 0
}
longest_free_range_histogram {
lower_bound: 0
upper_bound: 0
value: 3
}
longest_free_range_histogram {
lower_bound: 1
upper_bound: 1
value: 1
}
longest_free_range_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
longest_free_range_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
longest_free_range_histogram {
lower_bound: 4
upper_bound: 15
value: 1
}
longest_free_range_histogram {
lower_bound: 16
upper_bound: 31
value: 0
}
longest_free_range_histogram {
lower_bound: 32
upper_bound: 47
value: 0
}
longest_free_range_histogram {
lower_bound: 48
upper_bound: 63
value: 0
}
longest_free_range_histogram {
lower_bound: 64
upper_bound: 79
value: 0
}
longest_free_range_histogram {
lower_bound: 80
upper_bound: 95
value: 0
}
longest_free_range_histogram {
lower_bound: 96
upper_bound: 111
value: 0
}
longest_free_range_histogram {
lower_bound: 112
upper_bound: 127
value: 0
}
longest_free_range_histogram {
lower_bound: 128
upper_bound: 143
value: 0
}
longest_free_range_histogram {
lower_bound: 144
upper_bound: 159
value: 0
}
longest_free_range_histogram {
lower_bound: 160
upper_bound: 175
value: 0
}
longest_free_range_histogram {
lower_bound: 176
upper_bound: 191
value: 0
}
longest_free_range_histogram {
lower_bound: 192
upper_bound: 207
value: 0
}
longest_free_range_histogram {
lower_bound: 208
upper_bound: 223
value: 0
}
longest_free_range_histogram {
lower_bound: 224
upper_bound: 239
value: 0
}
longest_free_range_histogram {
lower_bound: 240
upper_bound: 251
value: 0
}
longest_free_range_histogram {
lower_bound: 252
upper_bound: 252
value: 0
}
longest_free_range_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
longest_free_range_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
longest_free_range_histogram {
lower_bound: 255
upper_bound: 255
value: 0
}
allocations_histogram {
lower_bound: 1
upper_bound: 1
value: 1
}
allocations_histogram {
lower_bound: 2
upper_bound: 2
value: 1
}
allocations_histogram {
lower_bound: 3
upper_bound: 3
value: 1
}
allocations_histogram {
lower_bound: 4
upper_bound: 4
value: 2
}
allocations_histogram {
lower_bound: 5
upper_bound: 16
value: 0
}
allocations_histogram {
lower_bound: 17
upper_bound: 32
value: 0
}
allocations_histogram {
lower_bound: 33
upper_bound: 48
value: 0
}
allocations_histogram {
lower_bound: 49
upper_bound: 64
value: 0
}
allocations_histogram {
lower_bound: 65
upper_bound: 80
value: 0
}
allocations_histogram {
lower_bound: 81
upper_bound: 96
value: 0
}
allocations_histogram {
lower_bound: 97
upper_bound: 112
value: 0
}
allocations_histogram {
lower_bound: 113
upper_bound: 128
value: 0
}
allocations_histogram {
lower_bound: 129
upper_bound: 144
value: 0
}
allocations_histogram {
lower_bound: 145
upper_bound: 160
value: 0
}
allocations_histogram {
lower_bound: 161
upper_bound: 176
value: 0
}
allocations_histogram {
lower_bound: 177
upper_bound: 192
value: 0
}
allocations_histogram {
lower_bound: 193
upper_bound: 208
value: 0
}
allocations_histogram {
lower_bound: 209
upper_bound: 224
value: 0
}
allocations_histogram {
lower_bound: 225
upper_bound: 240
value: 0
}
allocations_histogram {
lower_bound: 241
upper_bound: 252
value: 0
}
allocations_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
allocations_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
allocations_histogram {
lower_bound: 255
upper_bound: 255
value: 0
}
allocations_histogram {
lower_bound: 256
upper_bound: 256
value: 0
}
}
filler_tracker {
type: DONATED
free_pages_histogram {
lower_bound: 0
upper_bound: 0
value: 0
}
free_pages_histogram {
lower_bound: 1
upper_bound: 1
value: 0
}
free_pages_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
free_pages_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
free_pages_histogram {
lower_bound: 4
upper_bound: 15
value: 0
}
free_pages_histogram {
lower_bound: 16
upper_bound: 31
value: 0
}
free_pages_histogram {
lower_bound: 32
upper_bound: 47
value: 0
}
free_pages_histogram {
lower_bound: 48
upper_bound: 63
value: 0
}
free_pages_histogram {
lower_bound: 64
upper_bound: 79
value: 0
}
free_pages_histogram {
lower_bound: 80
upper_bound: 95
value: 0
}
free_pages_histogram {
lower_bound: 96
upper_bound: 111
value: 0
}
free_pages_histogram {
lower_bound: 112
upper_bound: 127
value: 0
}
free_pages_histogram {
lower_bound: 128
upper_bound: 143
value: 0
}
free_pages_histogram {
lower_bound: 144
upper_bound: 159
value: 0
}
free_pages_histogram {
lower_bound: 160
upper_bound: 175
value: 0
}
free_pages_histogram {
lower_bound: 176
upper_bound: 191
value: 0
}
free_pages_histogram {
lower_bound: 192
upper_bound: 207
value: 0
}
free_pages_histogram {
lower_bound: 208
upper_bound: 223
value: 0
}
free_pages_histogram {
lower_bound: 224
upper_bound: 239
value: 0
}
free_pages_histogram {
lower_bound: 240
upper_bound: 251
value: 0
}
free_pages_histogram {
lower_bound: 252
upper_bound: 252
value: 0
}
free_pages_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
free_pages_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
free_pages_histogram {
lower_bound: 255
upper_bound: 255
value: 1
}
longest_free_range_histogram {
lower_bound: 0
upper_bound: 0
value: 0
}
longest_free_range_histogram {
lower_bound: 1
upper_bound: 1
value: 0
}
longest_free_range_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
longest_free_range_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
longest_free_range_histogram {
lower_bound: 4
upper_bound: 15
value: 0
}
longest_free_range_histogram {
lower_bound: 16
upper_bound: 31
value: 0
}
longest_free_range_histogram {
lower_bound: 32
upper_bound: 47
value: 0
}
longest_free_range_histogram {
lower_bound: 48
upper_bound: 63
value: 0
}
longest_free_range_histogram {
lower_bound: 64
upper_bound: 79
value: 0
}
longest_free_range_histogram {
lower_bound: 80
upper_bound: 95
value: 0
}
longest_free_range_histogram {
lower_bound: 96
upper_bound: 111
value: 0
}
longest_free_range_histogram {
lower_bound: 112
upper_bound: 127
value: 0
}
longest_free_range_histogram {
lower_bound: 128
upper_bound: 143
value: 0
}
longest_free_range_histogram {
lower_bound: 144
upper_bound: 159
value: 0
}
longest_free_range_histogram {
lower_bound: 160
upper_bound: 175
value: 0
}
longest_free_range_histogram {
lower_bound: 176
upper_bound: 191
value: 0
}
longest_free_range_histogram {
lower_bound: 192
upper_bound: 207
value: 0
}
longest_free_range_histogram {
lower_bound: 208
upper_bound: 223
value: 0
}
longest_free_range_histogram {
lower_bound: 224
upper_bound: 239
value: 0
}
longest_free_range_histogram {
lower_bound: 240
upper_bound: 251
value: 0
}
longest_free_range_histogram {
lower_bound: 252
upper_bound: 252
value: 0
}
longest_free_range_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
longest_free_range_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
longest_free_range_histogram {
lower_bound: 255
upper_bound: 255
value: 1
}
allocations_histogram {
lower_bound: 1
upper_bound: 1
value: 1
}
allocations_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
allocations_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
allocations_histogram {
lower_bound: 4
upper_bound: 4
value: 0
}
allocations_histogram {
lower_bound: 5
upper_bound: 16
value: 0
}
allocations_histogram {
lower_bound: 17
upper_bound: 32
value: 0
}
allocations_histogram {
lower_bound: 33
upper_bound: 48
value: 0
}
allocations_histogram {
lower_bound: 49
upper_bound: 64
value: 0
}
allocations_histogram {
lower_bound: 65
upper_bound: 80
value: 0
}
allocations_histogram {
lower_bound: 81
upper_bound: 96
value: 0
}
allocations_histogram {
lower_bound: 97
upper_bound: 112
value: 0
}
allocations_histogram {
lower_bound: 113
upper_bound: 128
value: 0
}
allocations_histogram {
lower_bound: 129
upper_bound: 144
value: 0
}
allocations_histogram {
lower_bound: 145
upper_bound: 160
value: 0
}
allocations_histogram {
lower_bound: 161
upper_bound: 176
value: 0
}
allocations_histogram {
lower_bound: 177
upper_bound: 192
value: 0
}
allocations_histogram {
lower_bound: 193
upper_bound: 208
value: 0
}
allocations_histogram {
lower_bound: 209
upper_bound: 224
value: 0
}
allocations_histogram {
lower_bound: 225
upper_bound: 240
value: 0
}
allocations_histogram {
lower_bound: 241
upper_bound: 252
value: 0
}
allocations_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
allocations_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
allocations_histogram {
lower_bound: 255
upper_bound: 255
value: 0
}
allocations_histogram {
lower_bound: 256
upper_bound: 256
value: 0
}
}
filler_tracker {
type: PARTIAL
free_pages_histogram {
lower_bound: 0
upper_bound: 0
value: 0
}
free_pages_histogram {
lower_bound: 1
upper_bound: 1
value: 0
}
free_pages_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
free_pages_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
free_pages_histogram {
lower_bound: 4
upper_bound: 15
value: 0
}
free_pages_histogram {
lower_bound: 16
upper_bound: 31
value: 0
}
free_pages_histogram {
lower_bound: 32
upper_bound: 47
value: 0
}
free_pages_histogram {
lower_bound: 48
upper_bound: 63
value: 0
}
free_pages_histogram {
lower_bound: 64
upper_bound: 79
value: 0
}
free_pages_histogram {
lower_bound: 80
upper_bound: 95
value: 0
}
free_pages_histogram {
lower_bound: 96
upper_bound: 111
value: 0
}
free_pages_histogram {
lower_bound: 112
upper_bound: 127
value: 0
}
free_pages_histogram {
lower_bound: 128
upper_bound: 143
value: 0
}
free_pages_histogram {
lower_bound: 144
upper_bound: 159
value: 0
}
free_pages_histogram {
lower_bound: 160
upper_bound: 175
value: 0
}
free_pages_histogram {
lower_bound: 176
upper_bound: 191
value: 0
}
free_pages_histogram {
lower_bound: 192
upper_bound: 207
value: 0
}
free_pages_histogram {
lower_bound: 208
upper_bound: 223
value: 0
}
free_pages_histogram {
lower_bound: 224
upper_bound: 239
value: 0
}
free_pages_histogram {
lower_bound: 240
upper_bound: 251
value: 0
}
free_pages_histogram {
lower_bound: 252
upper_bound: 252
value: 0
}
free_pages_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
free_pages_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
free_pages_histogram {
lower_bound: 255
upper_bound: 255
value: 0
}
longest_free_range_histogram {
lower_bound: 0
upper_bound: 0
value: 0
}
longest_free_range_histogram {
lower_bound: 1
upper_bound: 1
value: 0
}
longest_free_range_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
longest_free_range_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
longest_free_range_histogram {
lower_bound: 4
upper_bound: 15
value: 0
}
longest_free_range_histogram {
lower_bound: 16
upper_bound: 31
value: 0
}
longest_free_range_histogram {
lower_bound: 32
upper_bound: 47
value: 0
}
longest_free_range_histogram {
lower_bound: 48
upper_bound: 63
value: 0
}
longest_free_range_histogram {
lower_bound: 64
upper_bound: 79
value: 0
}
longest_free_range_histogram {
lower_bound: 80
upper_bound: 95
value: 0
}
longest_free_range_histogram {
lower_bound: 96
upper_bound: 111
value: 0
}
longest_free_range_histogram {
lower_bound: 112
upper_bound: 127
value: 0
}
longest_free_range_histogram {
lower_bound: 128
upper_bound: 143
value: 0
}
longest_free_range_histogram {
lower_bound: 144
upper_bound: 159
value: 0
}
longest_free_range_histogram {
lower_bound: 160
upper_bound: 175
value: 0
}
longest_free_range_histogram {
lower_bound: 176
upper_bound: 191
value: 0
}
longest_free_range_histogram {
lower_bound: 192
upper_bound: 207
value: 0
}
longest_free_range_histogram {
lower_bound: 208
upper_bound: 223
value: 0
}
longest_free_range_histogram {
lower_bound: 224
upper_bound: 239
value: 0
}
longest_free_range_histogram {
lower_bound: 240
upper_bound: 251
value: 0
}
longest_free_range_histogram {
lower_bound: 252
upper_bound: 252
value: 0
}
longest_free_range_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
longest_free_range_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
longest_free_range_histogram {
lower_bound: 255
upper_bound: 255
value: 0
}
allocations_histogram {
lower_bound: 1
upper_bound: 1
value: 0
}
allocations_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
allocations_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
allocations_histogram {
lower_bound: 4
upper_bound: 4
value: 0
}
allocations_histogram {
lower_bound: 5
upper_bound: 16
value: 0
}
allocations_histogram {
lower_bound: 17
upper_bound: 32
value: 0
}
allocations_histogram {
lower_bound: 33
upper_bound: 48
value: 0
}
allocations_histogram {
lower_bound: 49
upper_bound: 64
value: 0
}
allocations_histogram {
lower_bound: 65
upper_bound: 80
value: 0
}
allocations_histogram {
lower_bound: 81
upper_bound: 96
value: 0
}
allocations_histogram {
lower_bound: 97
upper_bound: 112
value: 0
}
allocations_histogram {
lower_bound: 113
upper_bound: 128
value: 0
}
allocations_histogram {
lower_bound: 129
upper_bound: 144
value: 0
}
allocations_histogram {
lower_bound: 145
upper_bound: 160
value: 0
}
allocations_histogram {
lower_bound: 161
upper_bound: 176
value: 0
}
allocations_histogram {
lower_bound: 177
upper_bound: 192
value: 0
}
allocations_histogram {
lower_bound: 193
upper_bound: 208
value: 0
}
allocations_histogram {
lower_bound: 209
upper_bound: 224
value: 0
}
allocations_histogram {
lower_bound: 225
upper_bound: 240
value: 0
}
allocations_histogram {
lower_bound: 241
upper_bound: 252
value: 0
}
allocations_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
allocations_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
allocations_histogram {
lower_bound: 255
upper_bound: 255
value: 0
}
allocations_histogram {
lower_bound: 256
upper_bound: 256
value: 0
}
}
filler_tracker {
type: RELEASED
free_pages_histogram {
lower_bound: 0
upper_bound: 0
value: 0
}
free_pages_histogram {
lower_bound: 1
upper_bound: 1
value: 0
}
free_pages_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
free_pages_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
free_pages_histogram {
lower_bound: 4
upper_bound: 15
value: 2
}
free_pages_histogram {
lower_bound: 16
upper_bound: 31
value: 0
}
free_pages_histogram {
lower_bound: 32
upper_bound: 47
value: 0
}
free_pages_histogram {
lower_bound: 48
upper_bound: 63
value: 0
}
free_pages_histogram {
lower_bound: 64
upper_bound: 79
value: 0
}
free_pages_histogram {
lower_bound: 80
upper_bound: 95
value: 0
}
free_pages_histogram {
lower_bound: 96
upper_bound: 111
value: 0
}
free_pages_histogram {
lower_bound: 112
upper_bound: 127
value: 0
}
free_pages_histogram {
lower_bound: 128
upper_bound: 143
value: 0
}
free_pages_histogram {
lower_bound: 144
upper_bound: 159
value: 0
}
free_pages_histogram {
lower_bound: 160
upper_bound: 175
value: 0
}
free_pages_histogram {
lower_bound: 176
upper_bound: 191
value: 0
}
free_pages_histogram {
lower_bound: 192
upper_bound: 207
value: 0
}
free_pages_histogram {
lower_bound: 208
upper_bound: 223
value: 0
}
free_pages_histogram {
lower_bound: 224
upper_bound: 239
value: 0
}
free_pages_histogram {
lower_bound: 240
upper_bound: 251
value: 0
}
free_pages_histogram {
lower_bound: 252
upper_bound: 252
value: 0
}
free_pages_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
free_pages_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
free_pages_histogram {
lower_bound: 255
upper_bound: 255
value: 0
}
longest_free_range_histogram {
lower_bound: 0
upper_bound: 0
value: 0
}
longest_free_range_histogram {
lower_bound: 1
upper_bound: 1
value: 0
}
longest_free_range_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
longest_free_range_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
longest_free_range_histogram {
lower_bound: 4
upper_bound: 15
value: 2
}
longest_free_range_histogram {
lower_bound: 16
upper_bound: 31
value: 0
}
longest_free_range_histogram {
lower_bound: 32
upper_bound: 47
value: 0
}
longest_free_range_histogram {
lower_bound: 48
upper_bound: 63
value: 0
}
longest_free_range_histogram {
lower_bound: 64
upper_bound: 79
value: 0
}
longest_free_range_histogram {
lower_bound: 80
upper_bound: 95
value: 0
}
longest_free_range_histogram {
lower_bound: 96
upper_bound: 111
value: 0
}
longest_free_range_histogram {
lower_bound: 112
upper_bound: 127
value: 0
}
longest_free_range_histogram {
lower_bound: 128
upper_bound: 143
value: 0
}
longest_free_range_histogram {
lower_bound: 144
upper_bound: 159
value: 0
}
longest_free_range_histogram {
lower_bound: 160
upper_bound: 175
value: 0
}
longest_free_range_histogram {
lower_bound: 176
upper_bound: 191
value: 0
}
longest_free_range_histogram {
lower_bound: 192
upper_bound: 207
value: 0
}
longest_free_range_histogram {
lower_bound: 208
upper_bound: 223
value: 0
}
longest_free_range_histogram {
lower_bound: 224
upper_bound: 239
value: 0
}
longest_free_range_histogram {
lower_bound: 240
upper_bound: 251
value: 0
}
longest_free_range_histogram {
lower_bound: 252
upper_bound: 252
value: 0
}
longest_free_range_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
longest_free_range_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
longest_free_range_histogram {
lower_bound: 255
upper_bound: 255
value: 0
}
allocations_histogram {
lower_bound: 1
upper_bound: 1
value: 2
}
allocations_histogram {
lower_bound: 2
upper_bound: 2
value: 0
}
allocations_histogram {
lower_bound: 3
upper_bound: 3
value: 0
}
allocations_histogram {
lower_bound: 4
upper_bound: 4
value: 0
}
allocations_histogram {
lower_bound: 5
upper_bound: 16
value: 0
}
allocations_histogram {
lower_bound: 17
upper_bound: 32
value: 0
}
allocations_histogram {
lower_bound: 33
upper_bound: 48
value: 0
}
allocations_histogram {
lower_bound: 49
upper_bound: 64
value: 0
}
allocations_histogram {
lower_bound: 65
upper_bound: 80
value: 0
}
allocations_histogram {
lower_bound: 81
upper_bound: 96
value: 0
}
allocations_histogram {
lower_bound: 97
upper_bound: 112
value: 0
}
allocations_histogram {
lower_bound: 113
upper_bound: 128
value: 0
}
allocations_histogram {
lower_bound: 129
upper_bound: 144
value: 0
}
allocations_histogram {
lower_bound: 145
upper_bound: 160
value: 0
}
allocations_histogram {
lower_bound: 161
upper_bound: 176
value: 0
}
allocations_histogram {
lower_bound: 177
upper_bound: 192
value: 0
}
allocations_histogram {
lower_bound: 193
upper_bound: 208
value: 0
}
allocations_histogram {
lower_bound: 209
upper_bound: 224
value: 0
}
allocations_histogram {
lower_bound: 225
upper_bound: 240
value: 0
}
allocations_histogram {
lower_bound: 241
upper_bound: 252
value: 0
}
allocations_histogram {
lower_bound: 253
upper_bound: 253
value: 0
}
allocations_histogram {
lower_bound: 254
upper_bound: 254
value: 0
}
allocations_histogram {
lower_bound: 255
upper_bound: 255
value: 0
}
allocations_histogram {
lower_bound: 256
upper_bound: 256
value: 0
}
}
filler_skipped_subrelease {
skipped_subrelease_interval_ms: 0
skipped_subrelease_pages: 0
correctly_skipped_subrelease_pages: 0
pending_skipped_subrelease_pages: 0
skipped_subrelease_count: 0
correctly_skipped_subrelease_count: 0
pending_skipped_subrelease_count: 0
}
filler_stats_timeseries {
window_ms: 1000
epochs: 600
min_free_pages_interval_ms: 300000
min_free_pages: 0
min_free_backed_pages: 0
measurements {
epoch: 599
timestamp_ms: 0
min_free_pages: 0
min_free_backed_pages: 0
num_pages_subreleased: 269
num_hugepages_broken: 3
at_minimum_demand {
num_pages: 0
regular_huge_pages: 0
donated_huge_pages: 0
partial_released_huge_pages: 0
released_huge_pages: 0
used_pages_in_subreleased_huge_pages: 0
}
at_maximum_demand {
num_pages: 1774
regular_huge_pages: 5
donated_huge_pages: 1
partial_released_huge_pages: 0
released_huge_pages: 2
used_pages_in_subreleased_huge_pages: 499
}
at_minimum_huge_pages {
num_pages: 0
regular_huge_pages: 0
donated_huge_pages: 0
partial_released_huge_pages: 0
released_huge_pages: 0
used_pages_in_subreleased_huge_pages: 0
}
at_maximum_huge_pages {
num_pages: 1774
regular_huge_pages: 5
donated_huge_pages: 1
partial_released_huge_pages: 0
released_huge_pages: 2
used_pages_in_subreleased_huge_pages: 499
}
}
}
)"));
for (const auto& alloc : allocs) {
Delete(alloc);
}
}
// Testing subrelase stats: ensure that the cumulative number of released
// pages and broken hugepages is no less than those of the last 10 mins
TEST_P(FillerTest, CheckSubreleaseStats) {
// Get lots of hugepages into the filler.
Advance(absl::Minutes(1));
std::vector<PAlloc> result;
static_assert(kPagesPerHugePage > Length(10),
"Not enough pages per hugepage!");
for (int i = 0; i < 10; ++i) {
result.push_back(Allocate(kPagesPerHugePage - Length(i + 1)));
}
// Breaking up 2 hugepages, releasing 19 pages due to reaching limit,
EXPECT_EQ(HardReleasePages(Length(10)), Length(10));
EXPECT_EQ(HardReleasePages(Length(9)), Length(9));
Advance(absl::Minutes(1));
SubreleaseStats subrelease = filler_.subrelease_stats();
EXPECT_EQ(subrelease.total_pages_subreleased, Length(0));
EXPECT_EQ(subrelease.total_hugepages_broken.raw_num(), 0);
EXPECT_EQ(subrelease.num_pages_subreleased, Length(19));
EXPECT_EQ(subrelease.num_hugepages_broken.raw_num(), 2);
EXPECT_EQ(subrelease.total_pages_subreleased_due_to_limit, Length(19));
EXPECT_EQ(subrelease.total_hugepages_broken_due_to_limit.raw_num(), 2);
// Do some work so that the timeseries updates its stats
for (int i = 0; i < 5; ++i) {
result.push_back(Allocate(Length(1)));
}
subrelease = filler_.subrelease_stats();
EXPECT_EQ(subrelease.total_pages_subreleased, Length(19));
EXPECT_EQ(subrelease.total_hugepages_broken.raw_num(), 2);
EXPECT_EQ(subrelease.num_pages_subreleased, Length(0));
EXPECT_EQ(subrelease.num_hugepages_broken.raw_num(), 0);
EXPECT_EQ(subrelease.total_pages_subreleased_due_to_limit, Length(19));
EXPECT_EQ(subrelease.total_hugepages_broken_due_to_limit.raw_num(), 2);
// Breaking up 3 hugepages, releasing 21 pages (background thread)
EXPECT_EQ(ReleasePages(Length(8)), Length(8));
EXPECT_EQ(ReleasePages(Length(7)), Length(7));
EXPECT_EQ(ReleasePages(Length(6)), Length(6));
subrelease = filler_.subrelease_stats();
EXPECT_EQ(subrelease.total_pages_subreleased, Length(19));
EXPECT_EQ(subrelease.total_hugepages_broken.raw_num(), 2);
EXPECT_EQ(subrelease.num_pages_subreleased, Length(21));
EXPECT_EQ(subrelease.num_hugepages_broken.raw_num(), 3);
EXPECT_EQ(subrelease.total_pages_subreleased_due_to_limit, Length(19));
EXPECT_EQ(subrelease.total_hugepages_broken_due_to_limit.raw_num(), 2);
Advance(absl::Minutes(10)); // This forces timeseries to wrap
// Do some work
for (int i = 0; i < 5; ++i) {
result.push_back(Allocate(Length(1)));
}
subrelease = filler_.subrelease_stats();
EXPECT_EQ(subrelease.total_pages_subreleased, Length(40));
EXPECT_EQ(subrelease.total_hugepages_broken.raw_num(), 5);
EXPECT_EQ(subrelease.num_pages_subreleased, Length(0));
EXPECT_EQ(subrelease.num_hugepages_broken.raw_num(), 0);
EXPECT_EQ(subrelease.total_pages_subreleased_due_to_limit, Length(19));
EXPECT_EQ(subrelease.total_hugepages_broken_due_to_limit.raw_num(), 2);
std::string buffer(1024 * 1024, '\0');
{
TCMalloc_Printer printer(&*buffer.begin(), buffer.size());
filler_.Print(&printer, /*everything=*/true);
buffer.erase(printer.SpaceRequired());
}
ASSERT_THAT(
buffer,
testing::HasSubstr(
"HugePageFiller: Since startup, 40 pages subreleased, 5 hugepages "
"broken, (19 pages, 2 hugepages due to reaching tcmalloc "
"limit)"));
ASSERT_THAT(buffer, testing::EndsWith(
"HugePageFiller: Subrelease stats last 10 min: total "
"21 pages subreleased, 3 hugepages broken\n"));
for (const auto& alloc : result) {
Delete(alloc);
}
}
TEST_P(FillerTest, ConstantBrokenHugePages) {
// Get and Fill up many huge pages
const HugeLength kHugePages = NHugePages(10 * kPagesPerHugePage.raw_num());
absl::BitGen rng;
std::vector<PAlloc> alloc;
alloc.reserve(kHugePages.raw_num());
std::vector<PAlloc> dead;
dead.reserve(kHugePages.raw_num());
std::vector<PAlloc> alloc_small;
alloc_small.reserve(kHugePages.raw_num() + 2);
for (HugeLength i; i < kHugePages; ++i) {
auto size =
Length(absl::Uniform<size_t>(rng, 2, kPagesPerHugePage.raw_num() - 1));
alloc_small.push_back(Allocate(Length(1)));
alloc.push_back(Allocate(size - Length(1)));
dead.push_back(Allocate(kPagesPerHugePage - size));
}
ASSERT_EQ(filler_.size(), kHugePages);
for (int i = 0; i < 2; ++i) {
for (auto& a : dead) {
Delete(a);
}
ReleasePages(filler_.free_pages());
ASSERT_EQ(filler_.free_pages(), Length(0));
alloc_small.push_back(
Allocate(Length(1))); // To force subrelease stats to update
std::string buffer(1024 * 1024, '\0');
{
TCMalloc_Printer printer(&*buffer.begin(), buffer.size());
filler_.Print(&printer, /*everything=*/false);
buffer.erase(printer.SpaceRequired());
}
ASSERT_THAT(buffer, testing::HasSubstr(absl::StrCat(kHugePages.raw_num(),
" hugepages broken")));
if (i == 1) {
// Number of pages in alloc_small
ASSERT_THAT(buffer, testing::HasSubstr(absl::StrCat(
kHugePages.raw_num() + 2,
" used pages in subreleased hugepages")));
// Sum of pages in alloc and dead
ASSERT_THAT(buffer,
testing::HasSubstr(absl::StrCat(
kHugePages.raw_num() * kPagesPerHugePage.raw_num() -
kHugePages.raw_num(),
" pages subreleased")));
}
dead.swap(alloc);
alloc.clear();
}
// Clean up
for (auto& a : alloc_small) {
Delete(a);
}
}
// Confirms that a timeseries that contains every epoch does not exceed the
// expected buffer capacity of 1 MiB.
TEST_P(FillerTest, CheckBufferSize) {
const int kEpochs = 600;
const absl::Duration kEpochLength = absl::Seconds(1);
PAlloc big = Allocate(kPagesPerHugePage - Length(4));
for (int i = 0; i < kEpochs; i += 2) {
auto tiny = Allocate(Length(2));
Advance(kEpochLength);
Delete(tiny);
Advance(kEpochLength);
}
Delete(big);
std::string buffer(1024 * 1024, '\0');
TCMalloc_Printer printer(&*buffer.begin(), buffer.size());
{
PbtxtRegion region(&printer, kTop, /*indent=*/0);
filler_.PrintInPbtxt(®ion);
}
// We assume a maximum buffer size of 1 MiB. When increasing this size, ensure
// that all places processing mallocz protos get updated as well.
size_t buffer_size = printer.SpaceRequired();
printf("HugePageFiller buffer size: %zu\n", buffer_size);
EXPECT_LE(buffer_size, 1024 * 1024);
}
TEST_P(FillerTest, ReleasePriority) {
// Fill up many huge pages (>> kPagesPerHugePage). This relies on an
// implementation detail of ReleasePages buffering up at most
// kPagesPerHugePage as potential release candidates.
const HugeLength kHugePages = NHugePages(10 * kPagesPerHugePage.raw_num());
// We will ensure that we fill full huge pages, then deallocate some parts of
// those to provide space for subrelease.
absl::BitGen rng;
std::vector<PAlloc> alloc;
alloc.reserve(kHugePages.raw_num());
std::vector<PAlloc> dead;
dead.reserve(kHugePages.raw_num());
absl::flat_hash_set<FakeTracker*> unique_pages;
unique_pages.reserve(kHugePages.raw_num());
for (HugeLength i; i < kHugePages; ++i) {
Length size(absl::Uniform<size_t>(rng, 1, kPagesPerHugePage.raw_num() - 1));
PAlloc a = Allocate(size);
unique_pages.insert(a.pt);
alloc.push_back(a);
dead.push_back(Allocate(kPagesPerHugePage - size));
}
ASSERT_EQ(filler_.size(), kHugePages);
for (auto& a : dead) {
Delete(a);
}
// As of 5/2020, our release priority is to subrelease huge pages with the
// fewest used pages. Bucket unique_pages by that used_pages().
std::vector<std::vector<FakeTracker*>> ordered(kPagesPerHugePage.raw_num());
for (auto* pt : unique_pages) {
// None of these should be released yet.
EXPECT_FALSE(pt->released());
ordered[pt->used_pages().raw_num()].push_back(pt);
}
// Iteratively release random amounts of free memory--until all free pages
// become unmapped pages--and validate that we followed the expected release
// priority.
Length free_pages;
while ((free_pages = filler_.free_pages()) > Length(0)) {
Length to_release(absl::LogUniform<size_t>(rng, 1, free_pages.raw_num()));
Length released = ReleasePages(to_release);
ASSERT_LE(released, free_pages);
// Iterate through each element of ordered. If any trackers are released,
// all previous trackers must be released.
bool previous_all_released = true;
for (auto l = Length(0); l < kPagesPerHugePage; ++l) {
bool any_released = false;
bool all_released = true;
for (auto* pt : ordered[l.raw_num()]) {
bool released = pt->released();
any_released |= released;
all_released &= released;
}
if (any_released) {
EXPECT_TRUE(previous_all_released) << [&]() {
// On mismatch, print the bitmap of released states on l-1/l.
std::vector<bool> before;
if (l > Length(0)) {
before.reserve(ordered[l.raw_num() - 1].size());
for (auto* pt : ordered[l.raw_num() - 1]) {
before.push_back(pt->released());
}
}
std::vector<bool> after;
after.reserve(ordered[l.raw_num()].size());
for (auto* pt : ordered[l.raw_num()]) {
after.push_back(pt->released());
}
return absl::StrCat("before = {", absl::StrJoin(before, ";"),
"}\nafter = {", absl::StrJoin(after, ";"), "}");
}();
}
previous_all_released = all_released;
}
}
// All huge pages should be released.
for (auto* pt : unique_pages) {
EXPECT_TRUE(pt->released());
}
for (auto& a : alloc) {
Delete(a);
}
}
INSTANTIATE_TEST_SUITE_P(All, FillerTest,
testing::Values(FillerPartialRerelease::Return,
FillerPartialRerelease::Retain));
} // namespace
} // namespace tcmalloc
| [
"[email protected]"
] | |
fdea2e82f72234317ce0d632be503a1c99f21c35 | e115894155a078af864067b1f2e6fdb3ccf627c4 | /tests/annotatortester.h | 22b426f41771fcc51e06d1d50ffdde9efb096867 | [] | no_license | Gnomorian/youtube-annotator | cfc4632017b0752df925e330db0218113146955a | 646cad256376df6631a1028a9ebf4839087ac51d | refs/heads/master | 2023-04-24T03:37:36.052249 | 2021-05-07T10:46:45 | 2021-05-07T10:46:45 | 365,189,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | h | #ifndef ANNOTATORTESTER_H
#define ANNOTATORTESTER_H
#include <QObject>
class AnnotatorTester : public QObject
{
Q_OBJECT
public:
explicit AnnotatorTester(QObject *parent = nullptr);
private slots:
void initTestCase();
void cleanupTestCase();
// JavascriptParamBuilder tests
void test_javascriptparambuilder_one_parameter();
void test_javascriptparambuilder_string_parameters();
void test_javascriptparambuilder_exception_on_non_convertable_string();
void test_javascriptparambuilder_many_params();
// TextTemplateConstructor tests
void test_texttemplateconstructor_single_param();
void test_texttemplateconstructor_multiple_params();
};
#endif // ANNOTATORTESTER_H
| [
"[email protected]"
] | |
b291204eb03e20ef0bf53410a17b4ecf0207eecc | 074f451aa1f63436ff0335438e844d0a703177ee | /src/procMySQL.cpp | 79f8ce5e9adb491a7a37ca165bf99c865db74900 | [] | no_license | xinll/virtualhost | b55a84157433ae416b31100ae2da5b3e12c9416c | a2218c048840e71f0ff4c7dfa127a4a97e0f9ba1 | refs/heads/master | 2021-01-10T21:11:52.077431 | 2013-11-14T10:05:29 | 2013-11-14T10:05:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,793 | cpp | /*************************************************************************
> File Name: ../src/procMySQL.cpp
> Author: xinll
> Mail: [email protected]
> Created Time: 2013年09月24日 星期二 13时42分44秒
************************************************************************/
#include "procMySQL.h"
#include "defines.h"
#include "ftp.h"
#include <string.h>
#include <stdlib.h>
#include "tools.h"
#include <mysql/mysql.h>
#include "log.h"
#include <sys/stat.h>
#include "config.h"
static char *category = "backupMysqlLog";
extern pthread_mutex_t mutex;
bool MySQLBack(vector<pair<string,string> > &vt_param,string &errInfo)
{
WriteParam(category,vt_param,"");
if(vt_param.size() < 5)
{
errInfo.append("too less param.");
return false;
}
string ftpUserName = GetValue(FTPUSER,vt_param);
string ftpPw = GetValue(FTPPW,vt_param);
string mySQLUserName =GetValue(MYSQLUSER,vt_param);
string mySQLPw = GetValue(MYSQLPW,vt_param);
int ftpPort = 21;
string ftpServer = GetValue(FTPSERVER,vt_param);
string mySQLServer = "127.0.0.1";
string ftpDir = GetValue(FTPDIR,vt_param);
string bakFileName = GetValue(MYSQLBAKNAME,vt_param);
string strPort = GetValue(FTPPORT,vt_param);
if(ValidateParamEmpty(strPort.c_str()))
{
ftpPort = atoi(strPort.c_str());
}
string mySQLDataBase = mySQLUserName;
if(ftpUserName.empty() || mySQLUserName.empty() || mySQLDataBase.empty())
{
//参数错误
errInfo.append("ftpUserName or mySQLUserName or mySQLDataBase not valid.");
WriteLog(category,ERROR,"ftpUserName or mySQLUserName or mySQLDataBase not valid");
return false;
}
string dir = "/tmp";
chdir(dir.c_str());
char cmdBuf[1024];
sprintf(cmdBuf,"mysqldump -u%s -p%s -h%s %s > \'%s\'",mySQLUserName.c_str(),mySQLPw.c_str(),mySQLServer.c_str(),mySQLDataBase.c_str(),bakFileName.c_str());
int ret = system(cmdBuf);
if(ret != -1 && WIFEXITED(ret) && WEXITSTATUS(ret) == 0)
{
char tmp[256];
sprintf(tmp,"backup MySQL %s success",mySQLUserName.c_str());
WriteLog(category,INFO,tmp);
}
else
{
char tmp[256];
sprintf(tmp,"backup MySQL %s failed",mySQLUserName.c_str());
errInfo.append(tmp);
WriteLog(category,INFO,tmp);
return false;
}
CFTP ftpClient;
int err = ftpClient.ftp_connect(ftpServer.c_str(),(short)ftpPort);
if(err)
{
//连接ftp错误
errInfo.append("can't connect the ftp server");
unlink(bakFileName.c_str());
chdir("/");
return false;
}
err = ftpClient.ftp_login(ftpUserName.c_str(),ftpPw.c_str());
if(err)
{
//登陆错误
errInfo.append("can't login the ftp server");
unlink(bakFileName.c_str());
chdir("/");
return false;
}
err = ftpClient.ftp_upload(bakFileName.c_str(),ftpDir.c_str(),bakFileName.c_str());
unlink(bakFileName.c_str());
chdir("/");
if(err)
{
//上传文件错
errInfo.append("upload the file failed");
return false;
}
ftpClient.ftp_quit();
WriteParam(category,vt_param,"success");
return true;
}
bool MySQLRestore(vector<pair<string,string> > &vt_param,string &errInfo)
{
WriteParam(category,vt_param,"");
int ftpPort = 21;
string mySQLServer = "127.0.0.1";
string ftpUserName = GetValue(FTPUSER,vt_param);
string ftpPw = GetValue(FTPPW,vt_param);
string mySQLUserName = GetValue(MYSQLUSER,vt_param);
string mySQLPw = GetValue(MYSQLPW,vt_param);
string ftpServer = GetValue(FTPSERVER,vt_param);
string bakFileName = GetValue(MYSQLBAKNAME,vt_param);
string strPort = GetValue(FTPPORT,vt_param);
if(ValidateParamEmpty(strPort.c_str()))
{
ftpPort = atoi(strPort.c_str());
}
string ftpDir = GetValue(FTPDIR,vt_param);
string dbStrSize = GetValue(MYSQLSIZE,vt_param);
if(ftpUserName.empty() || mySQLUserName.empty() || bakFileName.empty())
{
//参数错误
errInfo.append("the param is not valid.");
WriteLog(category,ERROR,"ftpUserName or mySQLUserName or bakFileName not valid");
return false;
}
CFTP ftpClient;
int err = ftpClient.ftp_connect(ftpServer.c_str(),(short)ftpPort);
if(err)
{
//连接ftp错误
errInfo.append("can't connect the ftp server.");
return false;
}
err = ftpClient.ftp_login(ftpUserName.c_str(),ftpPw.c_str());
if(err)
{
//登陆错误
errInfo.append("can't login the ftp server.");
return false;
}
string dir = "/tmp/";
err = ftpClient.ftp_cd(ftpDir.c_str());
if(err)
{
errInfo.append("can't open the directory");
return false;
}
chdir(dir.c_str());
err = ftpClient.ftp_download(bakFileName.c_str(),bakFileName.c_str());
if(err)
{
//上传文件错误
errInfo.append("can't download the file.");
chdir("/");
return false;
}
ftpClient.ftp_quit();
char cmdBuf[1024];
sprintf(cmdBuf,"mysql -u%s -p%s -h%s %s < \'%s\'",mySQLUserName.c_str(),mySQLPw.c_str(),mySQLServer.c_str(),mySQLUserName.c_str(),bakFileName.c_str());
int ret = system(cmdBuf);
unlink(bakFileName.c_str());
chdir("/");
if(ret != -1 && WIFEXITED(ret) && WEXITSTATUS(ret) == 0)
{
WriteLog(category,INFO,"success to restore the database");
WriteParam(category,vt_param,"success");
if(!dbStrSize.empty())
{
long long dbSize = strtoll(dbStrSize.c_str(),NULL,10);
string pwd = GetEnvVar("MYSQLPWD");
if(!LimitMySQLSize("localhost","root",pwd,mySQLUserName,mySQLUserName,dbSize))
{
errInfo.append("limit the size failed");
return false;
}
}
return true;
}
else
{
errInfo.append("failed to restore the database");
WriteParam(category,vt_param,"failed");
return false;
}
}
//读取数据库大小
long long GetDataBaseSize(string host,string user,string pwd,string db,string &errInfo,unsigned int port)
{
MYSQL mysql;
mysql_init(&mysql);
if(!mysql_real_connect(&mysql,host.c_str(),user.c_str(),pwd.c_str(),db.c_str(),port,NULL,0))
{
//连接数据库失败
char err[1024];
sprintf(err,"can't connect the mysql server:%s",mysql_error(&mysql));
errInfo.append(err);
WriteLog(category,ERROR,err);
return -1;
}
string query = "SHOW TABLE STATUS";
if(mysql_query(&mysql,query.c_str()))
{
errInfo.append("can't execute sql");
mysql_close(&mysql);
return -1;
}
MYSQL_RES *result = mysql_store_result(&mysql);
if(result == NULL)
{
mysql_close(&mysql);
return -1;
}
long long size = 0;
MYSQL_ROW row;
MYSQL_FIELD *fields = mysql_fetch_fields(result);
while((row = mysql_fetch_row(result)))
{
if(row[6] != NULL)
size += strtoll(row[6],NULL,0);
if(row[8] != NULL)
size += strtoll(row[8],NULL,0);
}
mysql_free_result(result);
mysql_close(&mysql);
return size/(1024*1024);
}
bool LimitMySQLSize(string host,string user,string pwd,string ftpName,string db,long long maxsize)
{
MYSQL mysql;
mysql_init(&mysql);
if(!mysql_real_connect(&mysql,host.c_str(),user.c_str(),pwd.c_str(),db.c_str(),0,NULL,0))
{
char err[1024];
sprintf(err,"can't connect the mysql server:%s",mysql_error(&mysql));
//errInfo.append(err);
WriteLog(category,ERROR,err);
return false;
}
string query = "SHOW TABLE STATUS";
if(mysql_query(&mysql,query.c_str()))
{
mysql_close(&mysql);
WriteLog(category,ERROR,"SHOW TABLE STATUS FAILED");
return false;
}
MYSQL_RES *result = mysql_store_result(&mysql);
if(result == NULL)
{
WriteLog(category,ERROR,"Store Result Failed");
mysql_close(&mysql);
return false;
}
long long size = 0;
MYSQL_ROW row;
MYSQL_FIELD *fields = mysql_fetch_fields(result);
while((row = mysql_fetch_row(result)))
{
if(row[6] != NULL)
size += strtoll(row[6],NULL,0);
if(row[8] != NULL)
size += strtoll(row[8],NULL,0);
}
mysql_free_result(result);
bool success = false;
if(size/(1024*1024) >= maxsize) //转化为M
{
char tmpName[256];
char tmpdb[256];
mysql_real_escape_string(&mysql,tmpName,ftpName.c_str(),ftpName.size());
mysql_real_escape_string(&mysql,tmpdb,db.c_str(),db.size());
char tmpQuery[1024];
sprintf(tmpQuery,"REVOKE INSERT, UPDATE ON %s.* from %s",tmpdb,tmpName);
if(mysql_query(&mysql,tmpQuery) == 0)
{
strcat(tmpQuery," success");
WriteLog(category,INFO,tmpQuery);
success = true;
}
else
{
strcat(tmpQuery," failed");
WriteLog(category,ERROR,tmpQuery);
}
}
else
{
char tmpName[256];
char tmpdb[256];
mysql_real_escape_string(&mysql,tmpName,ftpName.c_str(),ftpName.size());
mysql_real_escape_string(&mysql,tmpdb,db.c_str(),db.size());
char tmpQuery[1024];
sprintf(tmpQuery,"GRANT INSERT, UPDATE ON %s.* to %s",tmpdb,tmpName);
if(mysql_query(&mysql,tmpQuery) == 0)
{
strcat(tmpQuery," success");
WriteLog(category,INFO,tmpQuery);
success = true;
}
else
{
char err[256];
sprintf(err,"%s",mysql_error(&mysql));
WriteLog(category,ERROR,err);
strcat(tmpQuery," failed");
WriteLog(category,ERROR,tmpQuery);
}
}
mysql_close(&mysql);
return success;
}
bool RecordLimit(vector<pair<string,string> >&vt_param,string &errInfo,bool check)
{
struct stat buf;
static vector<string> vt_conf;
string db = GetValue(DBNAME,vt_param);
string size = GetValue(MYSQLSIZE,vt_param);
string ip = "localhost";
WriteParam(category,vt_param,"");
if(vt_param.size() < 4 && !check)
{
errInfo.append("too less params.");
return false;
}
else if(vt_param.size() < 3 && check)
{
errInfo.append("too less params.");
return false;
}
if(check)
{
pthread_mutex_lock(&mutex);
if(vt_conf.size() == 0)
{
if(!ReadFile(&vt_conf,"/usr/local/apache_conf/mysql.size"))
{
errInfo.append("read /usr/local/apache_conf/mysql.size failed.");
WriteLog(category,ERROR,"read /usr/local/apache_conf/mysql.size failed");
pthread_mutex_unlock(&mutex);
WriteParam(category,vt_param,"failed");
return false;
}
}
pthread_mutex_unlock(&mutex);
vector<string>::iterator it = vt_conf.begin();
vector<string> vt_tmp;
bool success = false;
for(;it != vt_conf.end();it++)
{
vt_tmp.clear();
Split((*it),vt_tmp);
if(vt_tmp.size() < 2)
{
continue;
}
if(vt_tmp[0].compare(db) == 0)
{
long long dbSize = strtoll(vt_tmp[1].c_str(),NULL,10);
string pwd = GetEnvVar("MYSQLPWD");
success = LimitMySQLSize(ip,"root",pwd,db,db,dbSize);
break;
}
}
if(!success)
{
errInfo.append("revoke or grant failed.");
WriteParam(category,vt_param,"failed");
}
else
{
WriteParam(category,vt_param,"success");
}
return success;
}
else
{
pthread_mutex_lock(&mutex);
int ret = stat("/usr/local/apache_conf/mysql.size",&buf);
string param;
param.append(db);
param.append(" ");
param.append(size);
param.append(NEWLINE);
if(ret != 0)
{
FILE *fp = fopen("/usr/local/apache_conf/mysql.size","a+");
if(NULL == fp)
{
pthread_mutex_unlock(&mutex);
return false;
}
fwrite(param.c_str(),param.size(),1,fp);
fclose(fp);
vt_conf.push_back(param);
}
else
{
if(vt_conf.size() == 0)
{
if(!ReadFile(&vt_conf,"/usr/local/apache_conf/mysql.size"))
{
errInfo.append("read /usr/local/apache_conf/mysql.size failed.");
WriteLog(category,ERROR,"read /usr/local/apache_conf/mysql.size failed");
pthread_mutex_unlock(&mutex);
return false;
}
}
vector<string> vt_tmp;
vector<string>::iterator it = vt_conf.begin();
for(;it != vt_conf.end();)
{
vt_tmp.clear();
Split((*it),vt_tmp);
if(vt_tmp.size() < 2)
{
it++;
continue;
}
if(vt_tmp[0].compare(db) == 0)
{
vt_conf.erase(it);
continue;
}
else
it++;
}
vt_conf.push_back(param);
if(!WriteFile(&vt_conf,"/usr/local/apache_conf/mysql.size"))
{
errInfo.append("write /usr/local/apache_conf/mysql.size failed.");
WriteLog(category,ERROR,"write /usr/local/apache_conf/mysql.size failed");
pthread_mutex_unlock(&mutex);
return false;
}
}
pthread_mutex_unlock(&mutex);
WriteParam(category,vt_param,"success");
return true;
}
}
| [
"[email protected]"
] | |
9d28193c56d6f1f0f3c4c5b5bf923d518d0f9c2b | 27b3eb6587104c2ffe2c759f764d00f8b406a80c | /Box.cpp | c36e579a1226c39444cade81de4cd7660ba15d94 | [] | no_license | TIN2539/Bejeweled | 7a0f175da95f4ed9520900e5aec5850864055e21 | 3363994534cb4a7d0ff3075c566693eb54e55212 | refs/heads/master | 2021-04-06T01:25:48.990086 | 2018-03-09T01:10:19 | 2018-03-09T01:10:19 | 124,468,161 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | cpp | #include "Box.h"
Box::Box():
Box(0,0)
{
}
Box::Box(int X, int Y)
{
pos_box.SetX(X);
pos_box.SetY(Y);
color = ConsoleColor(rand() % 7 + 9);
super_var = 0;
}
Box::Box(int X, int Y, int lvl)
{
pos_box.SetX(X);
pos_box.SetY(Y);
color = ConsoleColor(rand() % (7 + lvl) + (9 - lvl));
super_var = 0;
}
void Box::Print()
{
switch (super_var)
{
case 1:
SetColor(Black, color);
for (int i = 0; i < 2; i++)
{
WriteChar(pos_box.GetX(), pos_box.GetY() + i, 17);
WriteChar(pos_box.GetX() + 1, pos_box.GetY() + i, 18);
WriteChar(pos_box.GetX() + 2, pos_box.GetY() + i, 16);
}
SetColor(White, Black);
break;
case 2:
SetColor(Black, color);
for (int i = 0; i < 2; i++)
{
WriteChar(pos_box.GetX(), pos_box.GetY() + i, 4);
WriteChar(pos_box.GetX() + 1, pos_box.GetY() + i, ' ');
WriteChar(pos_box.GetX() + 2, pos_box.GetY() + i, 4);
}
SetColor(White, Black);
break;
default:
SetColor(Black, color);
for (int i = 0; i < 2; i++)
{
WriteChars(pos_box.GetX(), pos_box.GetY() + i, ' ', 3);
}
SetColor(White, Black);
break;
/*SetColor(Black, color);
for (int i = 0; i < 2; i++)
{
WriteChar(pos_box.GetX(), pos_box.GetY() + i, 1);
WriteChar(pos_box.GetX() + 1, pos_box.GetY() + i, ' ');
WriteChar(pos_box.GetX() + 2, pos_box.GetY() + i, 1);
}
SetColor(White, Black);
break;*/
}
}
ConsoleColor Box::GetColor()
{
return color;
}
void Box::ChangeColor(ConsoleColor src_clr)
{
color = src_clr;
}
void Box::SetSupervar(int k)
{
switch (k)
{
case 4:
super_var = 0;
break;
case 5:
super_var = 1;
break;
case 6:
super_var = 2;
break;
default:
super_var = 0;
break;
}
}
int Box::GetSupervar()
{
return super_var;
}
| [
"[email protected]"
] | |
14245e8f6c53697c47e317cd43c6a91f46eec812 | 21553f6afd6b81ae8403549467230cdc378f32c9 | /arm/cortex/Spansion/MB9AFA3xN/include/arch/reg/mfs0.hpp | 0a658fad8cf469dcdaa50d7d6b352ad64e072f5f | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | digint/openmptl-reg-arm-cortex | 3246b68dcb60d4f7c95a46423563cab68cb02b5e | 88e105766edc9299348ccc8d2ff7a9c34cddacd3 | refs/heads/master | 2021-07-18T19:56:42.569685 | 2017-10-26T11:11:35 | 2017-10-26T11:11:35 | 108,407,162 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,237 | hpp | /*
* OpenMPTL - C++ Microprocessor Template Library
*
* This program is a derivative representation of a CMSIS System View
* Description (SVD) file, and is subject to the corresponding license
* (see "License.txt" in the parent directory).
*
* 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.
*/
////////////////////////////////////////////////////////////////////////
//
// Import from CMSIS-SVD: "Spansion/MB9AFA3xN.svd"
//
// name: MB9AFA3xN
// version: 1.7
// description: MB9AFA3xN
// --------------------------------------------------------------------
//
// C++ Header file, containing architecture specific register
// declarations for use in OpenMPTL. It has been converted directly
// from a CMSIS-SVD file.
//
// https://digint.ch/openmptl
// https://github.com/posborne/cmsis-svd
//
#ifndef ARCH_REG_MFS0_HPP_INCLUDED
#define ARCH_REG_MFS0_HPP_INCLUDED
#warning "using untested register declarations"
#include <register.hpp>
namespace mptl {
/**
* Multi-function Serial Interface 0
*/
struct MFS0
{
static constexpr reg_addr_t base_addr = 0x40038000;
/**
* Serial Control Register
*/
struct UART_SCR
: public reg< uint8_t, base_addr + 0x1, rw, 0x00 >
{
using type = reg< uint8_t, base_addr + 0x1, rw, 0x00 >;
using UPCL = regbits< type, 7, 1 >; /**< Programmable Clear bit */
using RIE = regbits< type, 4, 1 >; /**< Received interrupt enable bit */
using TIE = regbits< type, 3, 1 >; /**< Transmit interrupt enable bit */
using TBIE = regbits< type, 2, 1 >; /**< Transmit bus idle interrupt enable bit */
using RXE = regbits< type, 1, 1 >; /**< Received operation enable bit */
using TXE = regbits< type, 0, 1 >; /**< Transmission operation enable bit */
};
/**
* Serial Mode Register
*/
struct UART_SMR
: public reg< uint8_t, base_addr + 0x0, rw, 0x00 >
{
using type = reg< uint8_t, base_addr + 0x0, rw, 0x00 >;
using MD = regbits< type, 5, 3 >; /**< Operation mode set bit */
using WUCR = regbits< type, 4, 1 >; /**< Wake-up control bit */
using SBL = regbits< type, 3, 1 >; /**< Stop bit length select bit */
using BDS = regbits< type, 2, 1 >; /**< Transfer direction select bit */
using SOE = regbits< type, 0, 1 >; /**< Serial data output enable bit */
};
/**
* Serial Status Register
*/
struct UART_SSR
: public reg< uint8_t, base_addr + 0x5, rw, 0x03 >
{
using type = reg< uint8_t, base_addr + 0x5, rw, 0x03 >;
using REC = regbits< type, 7, 1 >; /**< Received error flag clear bit */
using PE = regbits< type, 5, 1 >; /**< Parity error flag bit (only functions in operation mode 0) */
using FRE = regbits< type, 4, 1 >; /**< Framing error flag bit */
using ORE = regbits< type, 3, 1 >; /**< Overrun error flag bit */
using RDRF = regbits< type, 2, 1 >; /**< Received data full flag bit */
using TDRE = regbits< type, 1, 1 >; /**< Transmit data empty flag bit */
using TBI = regbits< type, 0, 1 >; /**< Transmit bus idle flag */
};
/**
* Extended Communication Control Register
*/
struct UART_ESCR
: public reg< uint8_t, base_addr + 0x4, rw, 0x00 >
{
using type = reg< uint8_t, base_addr + 0x4, rw, 0x00 >;
using FLWEN = regbits< type, 7, 1 >; /**< Flow control enable bit */
using ESBL = regbits< type, 6, 1 >; /**< Extension stop bit length select bit */
using INV = regbits< type, 5, 1 >; /**< Inverted serial data format bit */
using PEN = regbits< type, 4, 1 >; /**< Parity enable bit (only functions in operation mode 0) */
using P = regbits< type, 3, 1 >; /**< Parity select bit (only functions in operation mode 0) */
using L = regbits< type, 0, 3 >; /**< Data length select bit */
};
/**
* Received Data Register
*/
struct UART_RDR
: public reg< uint16_t, base_addr + 0x8, ro, 0x0000 >
{
};
/**
* Transmit Data Register
*/
struct UART_TDR
: public reg< uint16_t, base_addr + 0x8, wo, 0x01FF >
{
};
/**
* Baud Rate Generator Registers
*/
struct UART_BGR
: public reg< uint16_t, base_addr + 0xc, rw, 0x0000 >
{
using type = reg< uint16_t, base_addr + 0xc, rw, 0x0000 >;
using EXT = regbits< type, 15, 1 >; /**< External clock select bit */
using BGR1 = regbits< type, 8, 7 >; /**< Baud Rate Generator Registers 1 */
using BGR0 = regbits< type, 0, 8 >; /**< Baud Rate Generator Registers 0 */
};
/**
* Serial Control Register
*/
struct CSIO_SCR
: public reg< uint8_t, base_addr + 0x1, rw, 0x00 >
{
using type = reg< uint8_t, base_addr + 0x1, rw, 0x00 >;
using UPCL = regbits< type, 7, 1 >; /**< Programmable clear bit */
using MS = regbits< type, 6, 1 >; /**< Master/Slave function select bit */
using SPI = regbits< type, 5, 1 >; /**< SPI corresponding bit */
using RIE = regbits< type, 4, 1 >; /**< Received interrupt enable bit */
using TIE = regbits< type, 3, 1 >; /**< Transmit interrupt enable bit */
using TBIE = regbits< type, 2, 1 >; /**< Transmit bus idle interrupt enable bit */
using RXE = regbits< type, 1, 1 >; /**< Data received enable bit */
using TXE = regbits< type, 0, 1 >; /**< Data transmission enable bit */
};
/**
* Serial Mode Register
*/
struct CSIO_SMR
: public reg< uint8_t, base_addr + 0x0, rw, 0x00 >
{
using type = reg< uint8_t, base_addr + 0x0, rw, 0x00 >;
using MD = regbits< type, 5, 3 >; /**< Operation mode set bits */
using WUCR = regbits< type, 4, 1 >; /**< Wake-up control bit */
using SCINV = regbits< type, 3, 1 >; /**< Serial clock invert bit */
using BDS = regbits< type, 2, 1 >; /**< Transfer direction select bit */
using SCKE = regbits< type, 1, 1 >; /**< Master mode serial clock output enable bit */
using SOE = regbits< type, 0, 1 >; /**< Serial data output enable bit */
};
/**
* Serial Status Register
*/
struct CSIO_SSR
: public reg< uint8_t, base_addr + 0x5, rw, 0x03 >
{
using type = reg< uint8_t, base_addr + 0x5, rw, 0x03 >;
using REC = regbits< type, 7, 1 >; /**< Received error flag clear bit */
using ORE = regbits< type, 3, 1 >; /**< Overrun error flag bit */
using RDRF = regbits< type, 2, 1 >; /**< Received data full flag bit */
using TDRE = regbits< type, 1, 1 >; /**< Transmit data empty flag bit */
using TBI = regbits< type, 0, 1 >; /**< Transmit bus idle flag bit */
};
/**
* Extended Communication Control Register
*/
struct CSIO_ESCR
: public reg< uint8_t, base_addr + 0x4, rw, 0x00 >
{
using type = reg< uint8_t, base_addr + 0x4, rw, 0x00 >;
using SOP = regbits< type, 7, 1 >; /**< Serial output pin set bit */
using WT = regbits< type, 3, 2 >; /**< Data transmit/received wait select bits */
using L = regbits< type, 0, 3 >; /**< Data length select bits */
};
/**
* Received Data Register
*/
struct CSIO_RDR
: public reg< uint16_t, base_addr + 0x8, ro, 0x0000 >
{
};
/**
* Transmit Data Register
*/
struct CSIO_TDR
: public reg< uint16_t, base_addr + 0x8, wo, 0x01FF >
{
};
/**
* Baud Rate Generator Registers
*/
struct CSIO_BGR
: public reg< uint16_t, base_addr + 0xc, rw, 0x0000 >
{
using type = reg< uint16_t, base_addr + 0xc, rw, 0x0000 >;
using BGR1 = regbits< type, 8, 7 >; /**< Baud Rate Generator Registers 1 */
using BGR0 = regbits< type, 0, 8 >; /**< Baud Rate Generator Registers 0 */
};
/**
* I2C Bus Control Register
*/
struct I2C_IBCR
: public reg< uint8_t, base_addr + 0x1, rw, 0x00 >
{
using type = reg< uint8_t, base_addr + 0x1, rw, 0x00 >;
using MSS = regbits< type, 7, 1 >; /**< Master/slave select bit */
using ACT_SCC = regbits< type, 6, 1 >; /**< Operation flag/iteration start condition generation bit */
using ACKE = regbits< type, 5, 1 >; /**< Data byte acknowledge enable bit */
using WSEL = regbits< type, 4, 1 >; /**< Wait selection bit */
using CNDE = regbits< type, 3, 1 >; /**< Condition detection interrupt enable bit */
using INTE = regbits< type, 2, 1 >; /**< Interrupt enable bit */
using BER = regbits< type, 1, 1 >; /**< Bus error flag bit */
using INT = regbits< type, 0, 1 >; /**< interrupt flag bit */
};
/**
* Serial Mode Register
*/
struct I2C_SMR
: public reg< uint8_t, base_addr + 0x0, rw, 0x00 >
{
using type = reg< uint8_t, base_addr + 0x0, rw, 0x00 >;
using MD = regbits< type, 5, 3 >; /**< operation mode set bits */
using WUCR = regbits< type, 4, 1 >; /**< Wake-up control bit */
using RIE = regbits< type, 3, 1 >; /**< Received interrupt enable bit */
using TIE = regbits< type, 2, 1 >; /**< Transmit interrupt enable bit */
};
/**
* I2C Bus Status Register
*/
struct I2C_IBSR
: public reg< uint8_t, base_addr + 0x4, rw, 0x00 >
{
using type = reg< uint8_t, base_addr + 0x4, rw, 0x00 >;
using FBT = regbits< type, 7, 1 >; /**< First byte bit */
using RACK = regbits< type, 6, 1 >; /**< Acknowledge flag bit */
using RSA = regbits< type, 5, 1 >; /**< Reserved address detection bit */
using TRX = regbits< type, 4, 1 >; /**< Data direction bit */
using AL = regbits< type, 3, 1 >; /**< Arbitration lost bit */
using RSC = regbits< type, 2, 1 >; /**< Iteration start condition check bit */
using SPC = regbits< type, 1, 1 >; /**< Stop condition check bit */
using BB = regbits< type, 0, 1 >; /**< Bus state bit */
};
/**
* Serial Status Register
*/
struct I2C_SSR
: public reg< uint8_t, base_addr + 0x5, rw, 0x03 >
{
using type = reg< uint8_t, base_addr + 0x5, rw, 0x03 >;
using REC = regbits< type, 7, 1 >; /**< Received error flag clear bit */
using TSET = regbits< type, 6, 1 >; /**< Transmit empty flag set bit */
using DMA = regbits< type, 5, 1 >; /**< DMA mode enable bit */
using TBIE = regbits< type, 4, 1 >; /**< Transmit bus idle interrupt enable bit (Effective only when DMA mode is enabled) */
using ORE = regbits< type, 3, 1 >; /**< Overrun error flag bit */
using RDRF = regbits< type, 2, 1 >; /**< Received data full flag bit */
using TDRE = regbits< type, 1, 1 >; /**< Transmit data empty flag bit */
using TBI = regbits< type, 0, 1 >; /**< Transmit bus idle flag bit (Effective only when DMA mode is enabled) */
};
/**
* Received Data Register
*/
struct I2C_RDR
: public reg< uint16_t, base_addr + 0x8, ro, 0x0000 >
{
};
/**
* Transmit Data Register
*/
struct I2C_TDR
: public reg< uint16_t, base_addr + 0x8, wo, 0x00FF >
{
};
/**
* 7-bit Slave Address Mask Register
*/
struct I2C_ISMK
: public reg< uint8_t, base_addr + 0x11, rw, 0x7F >
{
using type = reg< uint8_t, base_addr + 0x11, rw, 0x7F >;
using EN = regbits< type, 7, 1 >; /**< I2C interface operation enable bit */
using SM = regbits< type, 0, 7 >; /**< Slave address mask bits */
};
/**
* 7-bit Slave Address Register
*/
struct I2C_ISBA
: public reg< uint8_t, base_addr + 0x10, rw, 0x00 >
{
using type = reg< uint8_t, base_addr + 0x10, rw, 0x00 >;
using SAEN = regbits< type, 7, 1 >; /**< Slave address enable bit */
using SA = regbits< type, 0, 7 >; /**< 7-bit slave address */
};
/**
* Baud Rate Generator Registers
*/
struct I2C_BGR
: public reg< uint16_t, base_addr + 0xc, rw, 0x0000 >
{
using type = reg< uint16_t, base_addr + 0xc, rw, 0x0000 >;
using BGR1 = regbits< type, 8, 7 >; /**< Baud Rate Generator Registers 1 */
using BGR0 = regbits< type, 0, 8 >; /**< Baud Rate Generator Registers 0 */
};
/**
* Extension I2C Bus Control Register
*/
struct I2C_EIBCR
: public reg< uint8_t, base_addr + 0x1d, rw, 0x0C >
{
using type = reg< uint8_t, base_addr + 0x1d, rw, 0x0C >;
using SDAS = regbits< type, 5, 1 >; /**< SDA status bit */
using SCLS = regbits< type, 4, 1 >; /**< SCL status bit */
using SDAC = regbits< type, 3, 1 >; /**< SDA output control bit */
using SCLC = regbits< type, 2, 1 >; /**< SCL output control bit */
using SOCE = regbits< type, 1, 1 >; /**< Serial output enabled bit */
using BEC = regbits< type, 0, 1 >; /**< Bus error control bit */
};
};
} // namespace mptl
#endif // ARCH_REG_MFS0_HPP_INCLUDED
| [
"[email protected]"
] | |
0e6122981eaa0acaac3aa027952a69e01e6e5a18 | 81e2bc6848ca7e8dbdd5c7f040b8ce1d57f11922 | /code/upload/upload_jzt_handle.cpp | 10d65e8f89636230af903c274e5a6eaf475ac06a | [] | no_license | codingsf/archive_cpp_server | 4d751056793dff9d6845fa69a62bc271b6d26f90 | e508ba0dad4ed11281681f37bab555b04608f326 | refs/heads/master | 2021-01-19T06:20:37.679093 | 2016-12-06T06:20:53 | 2016-12-06T06:20:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,302 | cpp | /*
//
// Last Modify Date: 2016-10-28
// Author: zengpw
// History:
// 2016-09-27 zengpw created
// File Property: private
// Future:
// I. 九州通消息分析和入库
//
//
*/
#include "upload_jzt_handle.h"
session::HANDLE_RTN UploadHandle::jztPush(const char* key, const char* value, const int length)
{
if(this->rc_jzt->redis_rpush(key, value, length) != 0)
{
LOG_DEBUG("redis push occur serious error, please check redis!");
return session::HANDLE_RTN_STOP;
}
return session::HANDLE_RTN_CONTINUE;
}
session::HANDLE_RTN UploadHandle::cidManageLbs(const protocol::PacketIn* in, protocol::PacketOut* out)
{
bool error = false;
if(mode == 0)
{
stringstream ss;
TlvHandle th;
DbInterface di;
TLVGroupPtr pTlvGrp = in->getTLVGroup();
LOG_DEBUG("========= cidManageLbs processing begin, pTlvGrp->size() = " << pTlvGrp->size());
for(TLVGroupIter iter = pTlvGrp->begin(); iter != pTlvGrp->end(); ++iter)
{
if(iter->type _EQ_ TID_MANAGE_LBS)
{
TLV_MANAGE_LBS m_lbs;
TLV_HANDLE_MANAGE_LBS m_lbs_handle;
if(sizeof(m_lbs) != iter->len)
{
LOG_DEBUG("dev_id = " << in->getDevId() << ", protocol = lbs_manage, version error!");
continue;
}
memset(&m_lbs, 0, sizeof(m_lbs));
memcpy(&m_lbs, iter->value, iter->len);
m_lbs_handle.dev_id = in->getDevId();
int rtn = th.tlv_manage_lbs_handle(m_lbs, m_lbs_handle);
if(rtn _NEQ_ THR_OK)
{
error = true;
continue;
}
rtn = di.manage_lbs_update(db, m_lbs_handle);
if(rtn _NEQ_ THR_TRUE)
{
error = true;
continue;
}
}
}
}
LOG_DEBUG("========= cidManageLbs processing end.");
if(error)
return session::HANDLE_RTN_CONTINUE;
else
return session::HANDLE_RTN_REMOVE;
}
session::HANDLE_RTN UploadHandle::cidParameter(const protocol::PacketIn* in, protocol::PacketOut* out)
{
bool error = false;
if(mode == 0)
{
TlvHandle th;
DbInterface di;
TLVGroupPtr pTlvGrp = in->getTLVGroup();
LOG_DEBUG("========= cidParameter processing begin, pTlvGrp->size() = " << pTlvGrp->size());
for(TLVGroupIter iter = pTlvGrp->begin(); iter != pTlvGrp->end(); ++iter)
{
if(iter->type _EQ_ TID_RTN)
{
TLV_RTN sending_data;
TLV_HANDLE_PARAMETER_RTN parameter_handle;
if(sizeof(sending_data) != iter->len)
{
LOG_DEBUG("dev_id = " << in->getDevId() << ", protocol = parameter, version error!");
continue;
}
memset(&sending_data, 0, sizeof(sending_data));
memcpy(&sending_data, iter->value, iter->len);
parameter_handle.dev_id = in->getDevId();
int rtn = th.tlv_parameter_handle(sending_data, parameter_handle);
if(rtn _NEQ_ THR_OK)
{
error = true;
continue;
}
rtn = di.parameter_update(db, parameter_handle);
if(rtn _NEQ_ THR_TRUE)
{
error = true;
continue;
}
}
}
}
LOG_DEBUG("========= cidParameter processing end.");
if(error)
return session::HANDLE_RTN_CONTINUE;
else
return session::HANDLE_RTN_REMOVE;
}
session::HANDLE_RTN UploadHandle::cidParameterVersion(const protocol::PacketIn* in, protocol::PacketOut* out)
{
bool error = false;
if(mode == 0)
{
TlvHandle th;
DbInterface di;
TLVGroupPtr pTlvGrp = in->getTLVGroup();
LOG_DEBUG("========= cidParameterVersion processing begin, pTlvGrp->size() = " << pTlvGrp->size());
for(TLVGroupIter iter = pTlvGrp->begin(); iter != pTlvGrp->end(); ++iter)
{
if(iter->type _EQ_ TID_RTN)
{
TLV_RTN sending_data;
TLV_HANDLE_VERSION_RTN ver_handle;
if(sizeof(sending_data) != iter->len)
{
LOG_DEBUG("dev_id = " << in->getDevId() << ", protocol = parameter_version, version error!");
continue;
}
memset(&sending_data, 0, sizeof(sending_data));
memcpy(&sending_data, iter->value, iter->len);
ver_handle.dev_id = in->getDevId();
int rtn = th.tlv_version_handle(sending_data, ver_handle);
if(rtn _NEQ_ THR_OK)
{
error = true;
continue;
}
rtn = di.version_update(db, ver_handle);
if(rtn _NEQ_ THR_TRUE)
{
error = true;
continue;
}
}
}
}
LOG_DEBUG("========= cidParameterVersion processing end.");
if(error)
return session::HANDLE_RTN_CONTINUE;
else
return session::HANDLE_RTN_REMOVE;
}
session::HANDLE_RTN UploadHandle::cidJztDev(const protocol::PacketIn* in, protocol::PacketOut* out)
{
bool error = false;
stringstream ss;
TlvHandle th;
TLVGroupPtr pTlvGrp = in->getTLVGroup();
LOG_DEBUG("========= cidAutoJztDev processing begin, pTlvGrp->size() = " << pTlvGrp->size());
for(TLVGroupIter iter = pTlvGrp->begin(); iter != pTlvGrp->end(); ++iter)
{
if(iter->type _EQ_ TID_JZT_DEV)
{
TLV_JZT_DEV jzt_dev;
TLV_HANDLE_JZT_DEV jzt_dev_handle;
if(sizeof(jzt_dev) != iter->len)
{
LOG_DEBUG("dev_id = " << in->getDevId() << ", protocol = jzt_dev, version error!");
continue;
}
memset(&jzt_dev, 0, sizeof(jzt_dev));
memcpy(&jzt_dev, iter->value, iter->len);
jzt_dev_handle.dev_id = in->getDevId();
int rtn = th.tlv_jzt_dev_handle(jzt_dev, jzt_dev_handle);
if(rtn _NEQ_ THR_OK)
{
error = true;
continue;
}
// char buf[1024];
// memset(buf, 0, sizeof(buf));
// string msg = "{\"fdDeviceId\":\"%s\",\"fdCurrEnergy\":\"%s\",\"fdUpdateDate\":\"%s\"}";
// sprintf(buf, msg.c_str(), jzt_dev_handle.dev_id.c_str(), jzt_dev_handle.voltage.c_str(), jzt_dev_handle.datetime.c_str());
// if(this->jztPush("Coglink_DeviceStatus", buf, strlen(buf)) != session::HANDLE_RTN_CONTINUE)
// {
// error = true;
// }
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject();
writer.Key("fdDeviceId");
writer.String(jzt_dev_handle.dev_id.c_str());
writer.Key("fdCurrEnergy");
writer.String(jzt_dev_handle.voltage.c_str());
writer.Key("fdUpdateDate");
writer.String(jzt_dev_handle.datetime.c_str());
writer.EndObject();
if(this->jztPush("Coglink_DeviceStatus", s.GetString(), strlen(s.GetString())) != session::HANDLE_RTN_CONTINUE)
{
error = true;
}
}
}
LOG_DEBUG("========= cidAutoJztDev processing end.");
if(error)
return session::HANDLE_RTN_CONTINUE;
else
return session::HANDLE_RTN_REMOVE;
}
session::HANDLE_RTN UploadHandle::cidJztLbs(const protocol::PacketIn* in, protocol::PacketOut* out)
{
bool error = false;
stringstream ss;
TlvHandle th;
TLVGroupPtr pTlvGrp = in->getTLVGroup();
LOG_DEBUG("========= cidJztLbs processing begin, pTlvGrp->size() = " << pTlvGrp->size());
for(TLVGroupIter iter = pTlvGrp->begin(); iter != pTlvGrp->end(); ++iter)
{
if(iter->type _EQ_ TID_JZT_LBS)
{
TLV_JZT_LBS lbs;
TLV_HANDLE_JZT_LBS lbs_handle;
if(sizeof(lbs) != iter->len)
{
LOG_DEBUG("dev_id = " << in->getDevId() << ", protocol = jzt_lbs, version error!");
continue;
}
memset(&lbs, 0, sizeof(lbs));
memcpy(&lbs, iter->value, iter->len);
lbs_handle.dev_id = in->getDevId();
int rtn = th.tlv_jzt_lbs_handle(lbs, lbs_handle);
if(rtn _NEQ_ THR_OK)
{
error = true;
continue;
}
// char buf[1024];
// memset(buf, 0, sizeof(buf));
// string msg = "{\"fdDeviceId\":\"%s\",\"fdUpdateDate\":\"%s\",\"fdGoodsGpsLong\":\"%s\",\"fdGoodsGpsLat\":\"%s\"}";
// sprintf(buf, msg.c_str(), lbs_handle.dev_id.c_str(), lbs_handle.datetime.c_str(), lbs_handle.longitude.c_str(), lbs_handle.latitude.c_str());
// if(this->jztPush("Coglink_Gps", buf, strlen(buf)) != session::HANDLE_RTN_CONTINUE)
// {
// error = true;
// }
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject();
writer.Key("fdDeviceId");
writer.String(lbs_handle.dev_id.c_str());
writer.Key("fdUpdateDate");
writer.String(lbs_handle.datetime.c_str());
writer.Key("fdGoodsGpsLong");
writer.String(lbs_handle.longitude.c_str());
writer.Key("fdGoodsGpsLat");
writer.String(lbs_handle.latitude.c_str());
writer.EndObject();
if(this->jztPush("Coglink_Gps", s.GetString(), strlen(s.GetString())) != session::HANDLE_RTN_CONTINUE)
{
error = true;
}
}
}
LOG_DEBUG("========= cidJztLbs processing end.");
if(error)
return session::HANDLE_RTN_CONTINUE;
else
return session::HANDLE_RTN_REMOVE;
}
session::HANDLE_RTN UploadHandle::cidJztTh2(const protocol::PacketIn* in, protocol::PacketOut* out)
{
bool error = false;
stringstream ss;
TlvHandle th;
TLVGroupPtr pTlvGrp = in->getTLVGroup();
LOG_DEBUG("========= cidJztTh2 processing begin, pTlvGrp->size() = " << pTlvGrp->size());
for(TLVGroupIter iter = pTlvGrp->begin(); iter != pTlvGrp->end(); ++iter)
{
if(iter->type _EQ_ TID_JZT_TH2)
{
TLV_JZT_TH2 th_data;
TLV_HANDLE_JZT_TH2 th_handle;
if(sizeof(th_data) != iter->len)
{
LOG_DEBUG("dev_id = " << in->getDevId() << ", protocol = jzt_th2, version error!");
continue;
}
memset(&th_data, 0, sizeof(th_data));
memcpy(&th_data, iter->value, iter->len);
th_handle.dev_id = in->getDevId();
int rtn = th.tlv_jzt_th2_handle(th_data, th_handle);
if(rtn _NEQ_ THR_OK)
{
error = true;
continue;
}
// char buf[1024];
// memset(buf, 0, sizeof(buf));
// string msg = "{\"fdDeviceId\":\"%s\",";
// msg += "\"fdUpdateDate\":\"%s\",";
// msg += "\"fdFlag\":\"%s\",";
// msg += "\"fdGoodsTemperature1\":\"%s\",";
// msg += "\"fdGoodsTemperature2\":\"%s\",";
// msg += "\"fdGoodsHumidity1\":\"%s\",";
// msg += "\"fdGoodsHumidity2\":\"%s\",";
// msg += "\"fdInfoId\":\"%s\"}";
// sprintf(buf, msg.c_str(), th_handle.dev_id.c_str(), th_handle.datetime.c_str(), th_handle.alarm.c_str(),
// th_handle.t0.c_str(), th_handle.t1.c_str(), th_handle.h0.c_str(), th_handle.h1.c_str(), th_handle.datetime_gps.c_str());
// if(this->jztPush("Coglink_Humiture", buf, strlen(buf)) != session::HANDLE_RTN_CONTINUE)
// {
// error = true;
// }
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject();
writer.Key("fdDeviceId");
writer.String(th_handle.dev_id.c_str());
writer.Key("fdUpdateDate");
writer.String(th_handle.datetime.c_str());
writer.Key("fdFlag");
writer.String(th_handle.alarm.c_str());
writer.Key("fdGoodsTemperature1");
writer.String(th_handle.t0.c_str());
writer.Key("fdGoodsTemperature2");
writer.String(th_handle.t1.c_str());
writer.Key("fdGoodsHumidity1");
writer.String(th_handle.h0.c_str());
writer.Key("fdGoodsHumidity2");
writer.String(th_handle.h1.c_str());
writer.Key("fdInfoId");
writer.String(th_handle.datetime_gps.c_str());
writer.EndObject();
if(this->jztPush("Coglink_Humiture", s.GetString(), strlen(s.GetString())) != session::HANDLE_RTN_CONTINUE)
{
error = true;
}
}
}
LOG_DEBUG("========= cidJztTh2 processing end.");
if(error)
return session::HANDLE_RTN_CONTINUE;
else
return session::HANDLE_RTN_REMOVE;
}
| [
"[email protected]"
] | |
3f9f26d6bc8353d1e861bdbda2a2b89c7802543d | d94814b3c47638926ba395381c3980fd567a66fc | /lock/lock.cpp | 522a16608baca6639988295ecc47de036a7588b1 | [] | no_license | mcydy/MyTest | ac9c68b0cc505602a779f921d142aa4cebf70ad3 | 119f5a0186fc250e8f94296163e0e51afedbd233 | refs/heads/master | 2020-12-24T21:00:48.743132 | 2020-06-24T07:11:45 | 2020-06-24T07:11:45 | 59,257,164 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 936 | cpp | #include <thread>
#include <mutex>
#include <stdio.h>
#include <unistd.h>
int g_i = 0;
std::mutex g_i_mutex; // protects g_i
void safe_increment()
{
printf("00000\n");
std::lock_guard<std::mutex> lock(g_i_mutex);
char *p = (char *)malloc(100000);
while(1){
++g_i;
printf("+++++++++%d------\n",g_i);
// g_i_mutex is automatically released when lock
// goes out of scope
sleep(10);
printf("pthread exit\n");
// break;
return;
}
}
void safe_increment1()
{
printf("1111\n");
std::lock_guard<std::mutex> lock(g_i_mutex);
while(1){
++g_i;
printf("----------%d------\n",g_i);
// g_i_mutex is automatically released when lock
// goes out of scope
sleep(1);
// break;
}
}
int main()
{
std::thread t1(safe_increment);
// t1.join();
t1.detach();
printf("join end\n");
sleep(20);
// std::thread t2(safe_increment1);
// t1.join();
// t2.join();
}
| [
"[email protected]"
] | |
854d859b86a70bb2c734f22b2aa92fc40d0ec665 | c3c2b42100eac79aab0ca0cb12f5bd178112a652 | /src/PinyinFormatter.cc | 5142a8858bbbec84a8f30fc98aef9524cf857d42 | [
"Apache-2.0"
] | permissive | Qinsam/pinyin4cpp | fe3eabfc6b75fb83eac579ec9b0abf7a42676eb1 | 035c7000bc27119f0a3f2bec6987892727632e0d | refs/heads/master | 2020-06-18T03:51:20.752488 | 2019-07-22T07:43:03 | 2019-07-22T07:43:03 | 196,155,558 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,348 | cc | #include <algorithm>
#include <boost/algorithm/string.hpp>
#include "PinyinFormatter.h"
String PinyinFormatter::formatHanyuPinyin(const String &pinyinStr,const String &tone,const HanyuPinyinOutputFormat &outputFormat) {
String res=L"";
if(pinyinStr.size()==0) {
return res;
}
if(HanyuPinyinToneType::WITH_TONE_MARK == outputFormat.getToneType() &&
((HanyuPinyinVCharType::WITH_V == outputFormat.getVCharType()) ||
(HanyuPinyinVCharType::WITH_U_AND_COLON == outputFormat.getVCharType()))) {
std::cerr<<"tone marks cannot be added to v or u:";
return res;
}
if(HanyuPinyinSpellType::FIRST_LETTER == outputFormat.getSpellType()) {
res.push_back(pinyinStr[0]);
}else {
if(HanyuPinyinToneType::WITH_TONE_NUMBER == outputFormat.getToneType()) {
res=pinyinStr + tone;
}else {
res=pinyinStr;
}
}
if(HanyuPinyinVCharType::WITH_U_AND_COLON == outputFormat.getVCharType()) {
boost::algorithm::replace_all(res,L"u:",L"ü");
}else if(HanyuPinyinVCharType::WITH_V == outputFormat.getVCharType()) {
boost::algorithm::replace_all(res,L"u:",L"v");
}
if(HanyuPinyinCaseType::UPPERCASE == outputFormat.getCaseType()) {
transform(res.begin(),res.end(),res.begin(),::toupper);
}
return res;
}
| [
"[email protected]"
] | |
ecf99785c91273c99409dc0b99b22fd8d8a9388e | 948d555823c2d123601ff6c149869be377521282 | /SDK/SoT_BP_fod_WildSplash_03_MuddyRaw_00_a_ItemDesc_classes.hpp | c777d4cd964613df85d54d67e38625714f798af6 | [] | no_license | besimbicer89/SoT-SDK | 2acf79303c65edab01107ab4511e9b9af8ab9743 | 3a4c6f3b77c1045b7ef0cddd064350056ef7d252 | refs/heads/master | 2022-04-24T01:03:37.163407 | 2020-04-27T12:45:47 | 2020-04-27T12:45:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | hpp | #pragma once
// SeaOfThieves (1.6.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_fod_WildSplash_03_MuddyRaw_00_a_ItemDesc.BP_fod_WildSplash_03_MuddyRaw_00_a_ItemDesc_C
// 0x0000 (0x0130 - 0x0130)
class UBP_fod_WildSplash_03_MuddyRaw_00_a_ItemDesc_C : public UItemDesc
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_fod_WildSplash_03_MuddyRaw_00_a_ItemDesc.BP_fod_WildSplash_03_MuddyRaw_00_a_ItemDesc_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
42247d0b10dbad39afdb73236e10e2a252e64423 | 7af636ce4845911d9257f2ea372828fba33d5411 | /cameracalibration.h | f0ee6c5e88a6f7be346d890325125b469c8a019b | [] | no_license | as-python/PanoGen | 040044ef123071eef8b7f676c2b142c430fdc83d | 41c11eb8334379e86e2b44048a23ea3c5faee39f | refs/heads/master | 2016-08-12T03:31:03.912378 | 2016-04-19T09:18:38 | 2016-04-19T09:18:38 | 54,962,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,557 | h | #ifndef CAMERACALIBRATION_H
#define CAMERACALIBRATION_H
#include <QObject>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <QTime>
#include <QMessageBox>
#include <QCoreApplication>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace cv;
using namespace std;
class CameraCalibration : public QObject
{
Q_OBJECT
public:
enum Pattern { NOT_EXISTING, CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID };
enum InputType {INVALID, CAMERA, VIDEO_FILE, IMAGE_LIST};
private:
enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };
Size boardSize; // The size of the board -> Number of items by width and height
Pattern calibrationPattern; // One of the Chessboard, circles, or asymmetric circle pattern
float squareSize; // The size of a square in your defined unit (point, millimeter,etc).
int nrFrames; // The number of frames to use from the input for calibration
float aspectRatio; // The aspect ratio
int delay; // In case of a video input
bool bwritePoints; // Write detected feature points
bool bwriteExtrinsics; // Write extrinsic parameters
bool calibZeroTangentDist; // Assume zero tangential distortion
bool calibFixPrincipalPoint; // Fix the principal point at the center
string outputFileName; // The name of the file where to write
bool showUndistorsed; // Show undistorted images after calibration
bool saveUndistorsed; // save undistorted images after calibration
string input; // The input ->
string output_mapfile_name; // The name of the output Map file
static bool goodInput;
int cameraID;
vector<string> imageList;
int atImageList;
VideoCapture inputCapture;
InputType inputType;
int flag;
string path;
public:
explicit CameraCalibration(QObject *parent = 0);
void write(FileStorage& fs) const; //Write serialization for this class
bool calibrate();
void interprate();
bool readStringList( const string& filename, vector<string>& l );
Mat nextImage();
void addDelay(int mSec);
bool runCalibrationAndSave(Size imageSize, Mat& cameraMatrix, Mat& distCoeffs,vector<vector<Point2f> > imagePoints );
bool runCalibration( Size& imageSize, Mat& cameraMatrix, Mat& distCoeffs, vector<vector<Point2f> > imagePoints,
vector<Mat>& rvecs, vector<Mat>& tvecs, vector<float>& reprojErrs, double& totalAvgErr);
static void calcBoardCornerPositions(Size boardSize, float squareSize, vector<Point3f>& corners, CameraCalibration::Pattern patternType );
static double computeReprojectionErrors( const vector<vector<Point3f> >& objectPoints, const vector<vector<Point2f> >& imagePoints, const vector<Mat>& rvecs,
const vector<Mat>& tvecs, const Mat& cameraMatrix , const Mat& distCoeffs, vector<float>& perViewErrors);
void saveCameraParams( Size& imageSize, Mat& cameraMatrix, Mat& distCoeffs, const vector<Mat>& rvecs, const vector<Mat>& tvecs,
const vector<float>& reprojErrs, const vector<vector<Point2f> >& imagePoints, double totalAvgErr );
bool save_camera_maps(Size imageSize, Mat map1, Mat map2);
bool performCalibAndSave(string inputVideoFile, string mapFile, string outputVideoFile);
/* void read(const FileNode& node, CameraCalibration& x, const CameraCalibration& default_value = CameraCalibration());
bool onlineCalibAndSaveVideo(string path);*/
/*** Setter methods ***/
void setBoardSize(const Size &value);
void setCalibrationPattern(const Pattern &value);
void setNrFrames(int value);
void setOutputFileName(const string &value);
void setOutput_mapfile_name(const string &value);
void setInputType(const InputType &value);
void setSquareSize(float value);
void setAspectRatio(float value);
void setDelay(int value);
void setBwritePoints(bool value);
void setBwriteExtrinsics(bool value);
void setShowUndistorsed(bool value);
void setInput(const string &value);
void setSaveUndistorsed(bool value);
void setCalibZeroTangentDist(bool value);
void setCalibFixPrincipalPoint(bool value);
void setPath(const string &value);
signals:
void signal_ChangeImage(Mat);
void signal_ChangeTitleText(QString);
void signal_ChangeImageCounterText(QString);
};
#endif // CAMERACALIBRATION_H
| [
"[email protected]"
] | |
2f9226c5f6bc9c2092b91054e4dc14353e414e57 | 32c1b50492a18e4d76e79316dc066ede99b463fc | /devel/include/my_robot_tut3/OddEvenCheckRequest.h | fd16f6207244ebd9c13bf5c5f9284fecfb8c828f | [
"BSD-3-Clause"
] | permissive | Slightowl/ros-basic-framework | 07b3a8c6cca1bdced84e7237e5acc5bcc1399ead | 6cadbab71913d91f0afa64f74f2f20ed7009d7db | refs/heads/main | 2023-04-05T20:45:49.742015 | 2021-05-11T19:59:53 | 2021-05-11T19:59:53 | 364,405,898 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,071 | h | // Generated by gencpp from file my_robot_tut3/OddEvenCheckRequest.msg
// DO NOT EDIT!
#ifndef MY_ROBOT_TUT3_MESSAGE_ODDEVENCHECKREQUEST_H
#define MY_ROBOT_TUT3_MESSAGE_ODDEVENCHECKREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace my_robot_tut3
{
template <class ContainerAllocator>
struct OddEvenCheckRequest_
{
typedef OddEvenCheckRequest_<ContainerAllocator> Type;
OddEvenCheckRequest_()
: number(0) {
}
OddEvenCheckRequest_(const ContainerAllocator& _alloc)
: number(0) {
(void)_alloc;
}
typedef int32_t _number_type;
_number_type number;
typedef boost::shared_ptr< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> const> ConstPtr;
}; // struct OddEvenCheckRequest_
typedef ::my_robot_tut3::OddEvenCheckRequest_<std::allocator<void> > OddEvenCheckRequest;
typedef boost::shared_ptr< ::my_robot_tut3::OddEvenCheckRequest > OddEvenCheckRequestPtr;
typedef boost::shared_ptr< ::my_robot_tut3::OddEvenCheckRequest const> OddEvenCheckRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator==(const ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator1> & lhs, const ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator2> & rhs)
{
return lhs.number == rhs.number;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator!=(const ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator1> & lhs, const ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator2> & rhs)
{
return !(lhs == rhs);
}
} // namespace my_robot_tut3
namespace ros
{
namespace message_traits
{
template <class ContainerAllocator>
struct IsMessage< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> >
{
static const char* value()
{
return "2474488a3908093ec1307bdd5b35815e";
}
static const char* value(const ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x2474488a3908093eULL;
static const uint64_t static_value2 = 0xc1307bdd5b35815eULL;
};
template<class ContainerAllocator>
struct DataType< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> >
{
static const char* value()
{
return "my_robot_tut3/OddEvenCheckRequest";
}
static const char* value(const ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> >
{
static const char* value()
{
return "int32 number\n"
;
}
static const char* value(const ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.number);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct OddEvenCheckRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::my_robot_tut3::OddEvenCheckRequest_<ContainerAllocator>& v)
{
s << indent << "number: ";
Printer<int32_t>::stream(s, indent + " ", v.number);
}
};
} // namespace message_operations
} // namespace ros
#endif // MY_ROBOT_TUT3_MESSAGE_ODDEVENCHECKREQUEST_H
| [
"[email protected]"
] | |
e87be7f9cad969f7a80cbe5b5a3fa1d3314675d4 | 485faf9d4ec7def9a505149c6a491d6133e68750 | /include/util/JMSPublisher.H | a902276b8adc140eed7bade03752c566a55b32eb | [
"LicenseRef-scancode-warranty-disclaimer",
"ECL-2.0"
] | permissive | ohlincha/ECCE | af02101d161bae7e9b05dc7fe6b10ca07f479c6b | 7461559888d829338f29ce5fcdaf9e1816042bfe | refs/heads/master | 2020-06-25T20:59:27.882036 | 2017-06-16T10:45:21 | 2017-06-16T10:45:21 | 94,240,259 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,687 | h | ///////////////////////////////////////////////////////////////////////////////
// HEADER FILENAME: JMSPublisher.H
//
//
// CLASS SYNOPSIS:
// Provides an interface to the Java Messaging Service (JMS) using
// the Java Native Interface (JNI).
//
// EXPORTED TYPES:
// Class JMSPublisher
//
// DESCRIPTION:
// User can publish messages via JMS. Caches publishers.
//
//
///////////////////////////////////////////////////////////////////////////////
#ifndef JMSPUBLISHER_HH
#define JMSPUBLISHER_HH
// System includes
#include <string>
// Library includes:
// Portability for SGI/linux build:
using std::string;
class JMSMessage;
class Target;
class JMSPublisher {
public:
// Constructors
JMSPublisher(const string& toolName); // use this to identify yourself
// Virtual Destructor
virtual ~JMSPublisher(void);
// ACCESSORS
string getMyName() const;
string getMyID() const;
// PUBLISH METHODS
// publish a regular message - no reply
bool publish(const string& topic,
const JMSMessage& message) const;
bool invoke(JMSMessage& msg,
const string& appName,
int forcenew,
const string& url="",
const string& actionTopic="");
bool test();
// MESSAGE FACTORY methods:
// Use this to create new messages - it will stamp your sender info
JMSMessage* newMessage() const;
JMSMessage* newMessage(const Target& target) const;
private:
// Data:
// Tool info used to stamp messages:
string p_toolName;
static bool p_messagingEnabled;
}; // JMSPublisher
#endif /* JMSPUBLISHER_HH */
| [
"[email protected]"
] | |
2dbea740fec983d9a18d3e5f6fff436e0227ed13 | 5a27ea4e8330ad987f00abb51e2a91c45c00ec7d | /include/boost/hof/detail/make.hpp | afc9e4b1f4e08d1b51d9de6566b9d5afe6c9b748 | [] | no_license | danieljames/higherorderfunctions | 3c65a0cd256395d14cd7177d33849a4ca30f0025 | 56f8b91205e003a202b5835dede200167c2c2780 | refs/heads/master | 2021-04-29T17:36:40.853924 | 2018-02-15T19:01:15 | 2018-02-15T19:01:15 | 21,376,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | hpp | /*=============================================================================
Copyright (c) 2015 Paul Fultz II
make.h
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef BOOST_HOF_GUARD_MAKE_H
#define BOOST_HOF_GUARD_MAKE_H
#include <boost/hof/detail/move.hpp>
#include <boost/hof/detail/join.hpp>
#include <boost/hof/detail/delegate.hpp>
namespace boost { namespace hof { namespace detail {
template<template<class...> class Adaptor>
struct make
{
constexpr make() noexcept
{}
template<class... Fs, class Result=BOOST_HOF_JOIN(Adaptor, Fs...)>
constexpr Result operator()(Fs... fs) const BOOST_HOF_NOEXCEPT_CONSTRUCTIBLE(Result, Fs&&...)
{
return Result(static_cast<Fs&&>(fs)...);
}
};
}}} // namespace boost::hof
#endif
| [
"[email protected]"
] | |
b57661b3911359cd8e1165314fcc7b6cfe8ac640 | e17c43db9488f57cb835129fa954aa2edfdea8d5 | /Libraries/IFC/IFC4/include/IfcPileTypeEnum.h | 8b4d002537955b9e5fa789fa9e2ced13314bfa67 | [] | no_license | claudioperez/Rts | 6e5868ab8d05ea194a276b8059730dbe322653a7 | 3609161c34f19f1649b713b09ccef0c8795f8fe7 | refs/heads/master | 2022-11-06T15:57:39.794397 | 2020-06-27T23:00:11 | 2020-06-27T23:00:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,195 | h | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "IfcPPBasicTypes.h"
#include "IfcPPObject.h"
#include "IfcPPGlobal.h"
// TYPE IfcPileTypeEnum = ENUMERATION OF (BORED ,DRIVEN ,JETGROUTING ,COHESION ,FRICTION ,SUPPORT ,USERDEFINED ,NOTDEFINED);
class IFCPP_EXPORT IfcPileTypeEnum : virtual public IfcPPObject
{
public:
enum IfcPileTypeEnumEnum
{
ENUM_BORED,
ENUM_DRIVEN,
ENUM_JETGROUTING,
ENUM_COHESION,
ENUM_FRICTION,
ENUM_SUPPORT,
ENUM_USERDEFINED,
ENUM_NOTDEFINED
};
IfcPileTypeEnum();
IfcPileTypeEnum( IfcPileTypeEnumEnum e ) { m_enum = e; }
~IfcPileTypeEnum();
virtual const char* className() const { return "IfcPileTypeEnum"; }
virtual shared_ptr<IfcPPObject> getDeepCopy( IfcPPCopyOptions& options );
virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
virtual const std::wstring toString() const;
static shared_ptr<IfcPileTypeEnum> createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<IfcPPEntity> >& map );
IfcPileTypeEnumEnum m_enum;
};
| [
"[email protected]"
] | |
5ede05453ddc1cf19effe34697e859ef8fecff5c | 737b5c951f7985c8e42d765920ec0def7f3debe1 | /src/services/pcn-nat/src/serializer/RuleDnatAppendOutputJsonObject.cpp | 769c0282c12bf1d6b2d9c4fa21ff722e1a7941a2 | [
"Apache-2.0"
] | permissive | mbertrone/polycube | e3bd8db976abdf820863bcbe72f133802cd79ed4 | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | refs/heads/master | 2020-04-15T04:58:34.309749 | 2019-02-21T23:01:40 | 2019-02-21T23:01:40 | 164,404,243 | 2 | 0 | NOASSERTION | 2019-01-07T08:53:22 | 2019-01-07T08:53:21 | null | UTF-8 | C++ | false | false | 2,779 | cpp | /**
* nat API
* NAT Service
*
* OpenAPI spec version: 1.0
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/polycube-network/swagger-codegen.git
* branch polycube
*/
/* Do not edit this file manually */
#include "RuleDnatAppendOutputJsonObject.h"
#include <regex>
namespace io {
namespace swagger {
namespace server {
namespace model {
RuleDnatAppendOutputJsonObject::RuleDnatAppendOutputJsonObject() {
m_idIsSet = false;
}
RuleDnatAppendOutputJsonObject::~RuleDnatAppendOutputJsonObject() {}
void RuleDnatAppendOutputJsonObject::validateKeys() {
}
void RuleDnatAppendOutputJsonObject::validateMandatoryFields() {
}
void RuleDnatAppendOutputJsonObject::validateParams() {
}
nlohmann::json RuleDnatAppendOutputJsonObject::toJson() const {
nlohmann::json val = nlohmann::json::object();
if (m_idIsSet) {
val["id"] = m_id;
}
return val;
}
void RuleDnatAppendOutputJsonObject::fromJson(nlohmann::json& val) {
for(nlohmann::json::iterator it = val.begin(); it != val.end(); ++it) {
std::string key = it.key();
bool found = (std::find(allowedParameters_.begin(), allowedParameters_.end(), key) != allowedParameters_.end());
if (!found) {
throw std::runtime_error(key + " is not a valid parameter");
return;
}
}
if (val.find("id") != val.end()) {
setId(val.at("id"));
}
}
nlohmann::json RuleDnatAppendOutputJsonObject::helpKeys() {
nlohmann::json val = nlohmann::json::object();
return val;
}
nlohmann::json RuleDnatAppendOutputJsonObject::helpElements() {
nlohmann::json val = nlohmann::json::object();
val["id"]["name"] = "id";
val["id"]["type"] = "leaf"; // Suppose that type is leaf
val["id"]["simpletype"] = "integer";
val["id"]["description"] = R"POLYCUBE()POLYCUBE";
val["id"]["example"] = R"POLYCUBE()POLYCUBE";
return val;
}
nlohmann::json RuleDnatAppendOutputJsonObject::helpWritableLeafs() {
nlohmann::json val = nlohmann::json::object();
val["id"]["name"] = "id";
val["id"]["simpletype"] = "integer";
val["id"]["description"] = R"POLYCUBE()POLYCUBE";
val["id"]["example"] = R"POLYCUBE()POLYCUBE";
return val;
}
nlohmann::json RuleDnatAppendOutputJsonObject::helpComplexElements() {
nlohmann::json val = nlohmann::json::object();
return val;
}
std::vector<std::string> RuleDnatAppendOutputJsonObject::helpActions() {
std::vector<std::string> val;
return val;
}
uint32_t RuleDnatAppendOutputJsonObject::getId() const {
return m_id;
}
void RuleDnatAppendOutputJsonObject::setId(uint32_t value) {
m_id = value;
m_idIsSet = true;
}
bool RuleDnatAppendOutputJsonObject::idIsSet() const {
return m_idIsSet;
}
void RuleDnatAppendOutputJsonObject::unsetId() {
m_idIsSet = false;
}
}
}
}
}
| [
"[email protected]"
] | |
a2dab7b9ad707e63b147ed0c509f3a8787768e65 | 32fa941f03cb19da8893ca66b7860886cbbb4936 | /src/MxEMOps.h | e01e0a9cb571be6f75e0ee39173cd7ba5c32f587 | [
"MIT"
] | permissive | Tech-XCorp/maxwell | 258d5b1d77921a2d4bab0f4ffa0a9b60ca0923d2 | 0a9d7885f707349515adb1189c91246dc3a8237d | refs/heads/master | 2021-01-21T14:33:25.597757 | 2017-06-28T00:09:00 | 2017-06-28T00:09:00 | 95,301,907 | 0 | 0 | null | 2017-06-24T14:15:52 | 2017-06-24T14:15:51 | null | UTF-8 | C++ | false | false | 2,953 | h | #ifndef MX_EM_OPS
#define MX_EM_OPS
#include <vector>
#include <string>
#include "MxTypes.h"
#include "MxGrid.h"
#include "MxGridField.hpp"
#include "MxCrsMatrix.hpp"
#include "MxEMSim.h"
#include "Teuchos_ParameterList.hpp"
template<size_t DIM, typename Scalar>
class MxEMOps {
public:
MxEMOps();
//~MxEMOps();
void printRCPs();
MxEMOps(RCP<MxEMSim<DIM> > sim, bool initSingleOps = true);
void setSim(RCP<MxEMSim<DIM> > sim) {mSim = sim;}
/**
* Constructs single operators automatically based on simulation
* requirements. Operators constructed are (if necessary):
*
* curlB, curlE, divB, gradPsi, invEps, mu, dmL, dmA, dmVInv,
* invMuCellAve, invEpsCellAve
*
*/
void setSingleOps(RCP<MxEMSim<DIM> > sim);
void setSingleOps() {setSingleOps(mSim);}
/**
* name must be one of:
*
* curlE, curlB, divB, gradPsi, invEps, mu
*
*/
void setSingleOp(RCP<MxEMSim<DIM> > sim, std::string name) {};
/**
* Less typing if MxEMSim is already set for this object. Invokes
* the above with the previously-provided MxEMSim. Will crash if
* MxEMSim hasn't already been given.
*
*/
void setSingleOp(std::string name) {setSingleOp(mSim, name);}
RCP<MxCrsMatrix<Scalar> > getOp(std::string name) const;
void gatherOps(std::vector<std::string> const & names,
std::vector<RCP<MxCrsMatrix<Scalar> > > & mats) const;
/**
* Make a new operator by multiplying existing operators.
* Domain of the first operator in the list is the domain of the
* resultant operator; range of result is range of last operator in list.
* Optionally stores result under 'newName.'
*
* Several things could fail: operator in list could not exist,
* operators
* may not have compatible domain/range maps.
*
*/
RCP<MxCrsMatrix<Scalar> > multiplyOps(std::vector<std::string> names,
std::vector<bool> transposes, bool fillComplete, bool store = true,
std::string name = std::string(""));
/**
* Make a new operator by adding existing operators.
* Domain and ranges of all operators in list must be identical.
* Stores result under 'newName.'
*
* Several things could fail: operator in list could not exist,
* operators
* may not have compatible domain/range maps.
*
*/
RCP<MxCrsMatrix<Scalar> > addOps(std::vector<std::string> names,
std::vector<Scalar> coeffs, bool store, std::string name);
/**
Saves all operators to MatrixMarket files.
*/
void saveOps() const;
void setMagVecLapl();
void setPsiScaLapl();
Teuchos::RCP<Epetra_CrsMatrix> getMagVecLapl() const;
private:
int pid;
const MxGrid<DIM> * grid;
Teuchos::ParameterList pList;
RCP<MxEMSim<DIM> > mSim;
typename std::map<std::string, RCP<MxCrsMatrix<Scalar> > > mOps;
};
#endif
| [
"[email protected]"
] | |
013978047c0094476c4e4fa70e1f78400fccddbc | a0cf07ca26fe6a5e6ac1c5c691064e256140f06d | /SegmentTree.cpp | c29aa7faf6759cffcc6e08c367f4fb3634cfd6f7 | [] | no_license | taiseiKMC/CompetitivePrograming | f7f89c4a1a9ca56e45fa8f1bcce10881f2c2c710 | 897a56c9a3188a7487239dc004f6eee5b1d476d5 | refs/heads/master | 2020-05-21T12:33:59.398767 | 2019-07-11T20:05:41 | 2019-07-11T20:05:41 | 47,779,060 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,706 | cpp | /*
usage:
SegmentTree<T> tree(array, PLUS) で(array, +, 1)のセグツリーができる
update: 更新
fold: 畳み込み
*/
#include <bits/stdc++.h>
using namespace std;
template<typename T>
struct SegmentTree
{
const int SIZE;
int tree_size, leaf_number;
const function<T(T,T)> op;
const T e;
vector<T> node;
SegmentTree(const vector<T> &ary, const function<T(T,T)> f, const T e_);
const int child_l(const int k) const
{
return k*2+1;
}
const int child_r(const int k) const
{
return k*2+2;
}
const int parent(const int k) const
{
return (k-1)/2;
}
const int least_square(const int k) const
{
if(k==0) return 0;
int tmp=k-1;
for(int i=1; 64>i; i<<=1)
tmp |= (tmp >> i);
return tmp+1;
}
const T init(const int k);
const void update(const int k, const T x);
const T fold(const int a, const int b, const int k, const int l, const int r) const;
const T fold(const int a,const int b) const
{
return fold(a, b, 0, 0, leaf_number);
}
/*const void print() const
{
REP(i, tree_size)
cout<<node[i]<<" \n"[i==tree_size-1];
}*/
};
template<typename T>
SegmentTree<T>::SegmentTree(const vector<T> &ary, const function<T(T,T)> f, const T e_):SIZE(ary.size()),op(f),e(e_)
{
tree_size=SIZE;
leaf_number=least_square(tree_size);
tree_size=leaf_number*2;
node=vector<T>(tree_size);
tree_size--;
for(int i=0;i<leaf_number;i++)
if(i<SIZE)
node[i+leaf_number-1]=ary[i];
else
node[i+leaf_number-1]=e;
init(0);
}
template<typename T>
const T SegmentTree<T>::init(const int k)
{
if(k>=leaf_number-1) return node[k];
return node[k]=op(init(child_l(k)),init(child_r(k)));
}
template<typename T>
const void SegmentTree<T>::update(const int k, const T x)
{
int tmp = k+leaf_number-1;
node[tmp]=x;
while(tmp > 0)
{
tmp=parent(tmp);
node[tmp]=op(node[child_l(tmp)], node[child_r(tmp)]);
}
}
template<typename T>
const T SegmentTree<T>::fold(const int a, const int b, const int k, const int l, const int r) const
{
if(r <= a || b <= l)
return e; //[a,b)と[l,r)が交わらない
if(a <= l && r <= b)
return node[k]; //[a,b)が[l,r)を含む
return op(fold(a,b,child_l(k),l,(l+r)/2), fold(a,b,child_r(k),(l+r)/2, r));
}
#define PLUS [](int p,int q){return p+q;},0
#define MULT [](int p,int q){return p*q;},1
#define MAX [](int p,int q){return max(p,q);},INT_MIN
#define MIN [](int p,int q){return min(p,q);},INT_MAX
| [
"[email protected]"
] | |
d5136be27c92df46a8e9e003a2b80266530263a1 | 0811f888e26379bf461aa53df13f83ccce61e02b | /lib/Ntreev.Windows.Forms.Grid/ToolTip.h | d589acaa9b8f26e28da2c5cf1e7a6dc900e10be0 | [
"MIT"
] | permissive | NtreevSoft/GridControl | 8c4410edf132e5ca79c22bbf8d7fe0d2e0ab556e | decb1169d9b230ce93be1f0e96305161f2a8d655 | HEAD | 2018-10-24T23:10:11.638230 | 2014-03-18T09:21:39 | 2014-03-18T09:21:39 | 2,064,313 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,384 | h | //=====================================================================================================================
// Ntreev Grid for .Net 2.0.5190.32793
// https://github.com/NtreevSoft/GridControl
//
// Released under the MIT License.
//
// Copyright (c) 2010 Ntreev Soft co., Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//=====================================================================================================================
#pragma once
#include "GridObject.h"
namespace Ntreev { namespace Windows { namespace Forms { namespace Grid
{
/// <summary>
/// 툴팁을 보이거나 감추는 기능을 제공합니다.
/// </summary>
public ref class ToolTip : GridObject
{
private: // classes
ref class ToolTipItem
{
public:
ToolTipItem();
void Show(System::String^ text, System::IntPtr handle);
void Hide();
private:
void* m_tooltip;
bool m_created;
};
ref class ToolTipItemCollection : System::Collections::Generic::List<ToolTipItem^>
{
public: // methods
ToolTipItemCollection();
void MoveNext();
public: // properties
property ToolTipItem^ Current
{
ToolTipItem^ get();
}
property ToolTipItem^ Previous
{
ToolTipItem^ get();
}
private: // variables
int m_previousIndex;
int m_currentIndex;
} m_toolTips;
public: // methods
/// <summary>
/// 툴팁을 표시합니다.
/// </summary>
/// <remarks>
/// 툴팁의 내용은 현재 마우스 커서 기준으로 표시 됩니다.
/// </remarks>
/// <param name="text">툴팁에 표시할 문자열입니다.</param>
void Show(System::String^ text);
/// <summary>
/// 툴팁을 감춥니다.
/// </summary>
void Hide();
internal: // methods
ToolTip(_GridControl^ gridControl, int count);
private: // variables
bool m_showed;
};
} /*namespace Grid*/ } /*namespace Forms*/ } /*namespace Windows*/ } /*namespace Ntreev*/ | [
"[email protected]"
] | |
c0910c662a7be56bb992c71419bbd388839ee0bf | 088011030da62f3f70cfcf61ec9ff48e2d820af0 | /Polynomial/Polynomial/main.cpp | 145b60c4e99bf8538ae40a5de044db0fb9161041 | [] | no_license | ShenJiahuan/EI239-source-code | 352f54b0dd0e975e201c019a182ec6ac9dff6a45 | 82c1a617f428734ee9f4a0ef1ebc0a39d545187d | refs/heads/master | 2020-04-11T11:25:25.861969 | 2019-01-11T11:01:18 | 2019-01-11T11:01:18 | 161,747,387 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | cpp | //
// main.cpp
// Polynomial
//
// Created by 沈嘉欢 on 2018/10/10.
// Copyright © 2018 沈嘉欢. All rights reserved.
//
#include <iostream>
#include "Polynomial.hpp"
int main(int argc, const char * argv[]) {
using std::cin;
using std::cout;
using std::endl;
Polynomial poly1, poly2;
cin >> poly1 >> poly2;
cout << poly1 + poly2 << endl;
cout << poly1 - poly2 << endl;
cout << poly1 * poly2 << endl;
cout << poly1.derivative() << endl;
cout << poly2.derivative() << endl;
return 0;
}
| [
"[email protected]"
] | |
e372193fa9631251ff27fffe9fd21276219f6ea4 | d2244dc530ce05ebc8d8e654c4bcf0dae991e78b | /android_art-xposed-lollipop-mr1/compiler/sea_ir/types/type_inference_visitor.cc | 6adf251a6864c4e7c3185a1c436c6a9000e97c63 | [
"NCSA",
"Apache-2.0"
] | permissive | java007hf/Dynamicloader | 6fe4b1de14de751247ecd1b9bda499e100f4ec75 | 474427de20057b9c890622bb168810a990591573 | refs/heads/master | 2021-09-05T21:19:30.482850 | 2018-01-31T03:10:39 | 2018-01-31T03:10:39 | 119,626,890 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,926 | cc | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "scoped_thread_state_change.h"
#include "sea_ir/types/type_inference_visitor.h"
#include "sea_ir/types/type_inference.h"
#include "sea_ir/ir/sea.h"
namespace sea_ir {
void TypeInferenceVisitor::Visit(SeaGraph* graph) {
FunctionTypeInfo fti(graph_, type_cache_);
const Type* return_type = fti.GetReturnValueType();
crt_type_.push_back(return_type);
}
void TypeInferenceVisitor::Visit(SignatureNode* parameter) {
FunctionTypeInfo fti(graph_, type_cache_);
std::vector<const Type*> arguments = fti.GetDeclaredArgumentTypes();
DCHECK_LT(parameter->GetPositionInSignature(), arguments.size())
<< "Signature node position not present in signature.";
crt_type_.push_back(arguments.at(parameter->GetPositionInSignature()));
}
void TypeInferenceVisitor::Visit(UnnamedConstInstructionNode* instruction) {
crt_type_.push_back(&type_cache_->Integer());
}
void TypeInferenceVisitor::Visit(PhiInstructionNode* instruction) {
std::vector<const Type*> types_to_merge = GetOperandTypes(instruction);
const Type* result_type = MergeTypes(types_to_merge);
crt_type_.push_back(result_type);
}
void TypeInferenceVisitor::Visit(AddIntInstructionNode* instruction) {
std::vector<const Type*> operand_types = GetOperandTypes(instruction);
for (std::vector<const Type*>::const_iterator cit = operand_types.begin();
cit != operand_types.end(); cit++) {
if (*cit != NULL) {
DCHECK((*cit)->IsInteger());
}
}
crt_type_.push_back(&type_cache_->Integer());
}
void TypeInferenceVisitor::Visit(MoveResultInstructionNode* instruction) {
std::vector<const Type*> operand_types = GetOperandTypes(instruction);
const Type* operand_type = operand_types.at(0);
crt_type_.push_back(operand_type);
}
void TypeInferenceVisitor::Visit(InvokeStaticInstructionNode* instruction) {
FunctionTypeInfo fti(graph_, instruction, type_cache_);
const Type* result_type = fti.GetReturnValueType();
crt_type_.push_back(result_type);
}
std::vector<const Type*> TypeInferenceVisitor::GetOperandTypes(
InstructionNode* instruction) const {
std::vector<InstructionNode*> sources = instruction->GetSSAProducers();
std::vector<const Type*> types_to_merge;
for (std::vector<InstructionNode*>::const_iterator cit = sources.begin(); cit != sources.end();
cit++) {
const Type* source_type = type_data_->FindTypeOf((*cit)->Id());
if (source_type != NULL) {
types_to_merge.push_back(source_type);
}
}
return types_to_merge;
}
const Type* TypeInferenceVisitor::MergeTypes(std::vector<const Type*>& types) const {
const Type* type = NULL;
if (types.size() > 0) {
type = *(types.begin());
if (types.size() > 1) {
for (std::vector<const Type*>::const_iterator cit = types.begin();
cit != types.end(); cit++) {
if (!type->Equals(**cit)) {
type = MergeTypes(type, *cit);
}
}
}
}
return type;
}
const Type* TypeInferenceVisitor::MergeTypes(const Type* t1, const Type* t2) const {
DCHECK(t2 != NULL);
DCHECK(t1 != NULL);
art::ScopedObjectAccess soa(art::Thread::Current());
const Type* result = &(t1->Merge(*t2, type_cache_));
return result;
}
} // namespace sea_ir
| [
"[email protected]"
] | |
1b3ad34f594a6ffc1d7289b5f2c0884ee1a73bbb | 0b65e4f9bc902d1faa51bdd4016a19332a9316d8 | /src/joint_types/vel_joint.cpp | 78eafebd3e582fa837b863bfa97687061296f6a1 | [
"Apache-2.0"
] | permissive | FRC900/steered_wheel_base_controller | e03d5bea231184a72481eea6f259575fe28f08f2 | b19fb4d02b4b18da2116bcbc1e2f0d52f7917ae3 | refs/heads/master | 2021-01-20T10:00:44.431753 | 2017-10-13T13:19:37 | 2017-10-13T13:19:37 | 90,316,174 | 1 | 1 | null | 2018-01-25T17:43:10 | 2017-05-04T22:45:43 | C++ | UTF-8 | C++ | false | false | 371 | cpp | #include "steered_wheel_base_controller/joint_types/vel_joint.h"
using ros::Duration;
namespace SWBC
{
namespace joint_types
{
// Stop this joint's motion.
void VelJoint::stop()
{
handle_.setCommand(0);
}
// Specify this joint's velocity.
void VelJoint::setVel(const double vel, const Duration& /* period */)
{
handle_.setCommand(vel);
}
}
}
| [
"[email protected]"
] | |
287e481e5d201fc0691f76eebc6fde571cd0dfce | 7d611a339b5a018b68348c8e331d8f71960544e5 | /glmTest/tecgraf/Msh2D/Arb/ArbMshCleanup.cpp | c3616cbee5464e2f89436f43d2c3dfb3f05490da | [] | no_license | AndradeB91/PreprocessedFiltering | 1231e94df1c1bf3744fd18545ada213201c12b34 | 20dbf69bfbbfef01c8b9a63ed74fe61f4cc205b9 | refs/heads/master | 2020-03-16T12:18:25.397483 | 2018-05-08T20:59:35 | 2018-05-08T20:59:35 | 132,663,859 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,962 | cpp | //
// Copyright -
// (c) Fracture Analysis Consultants, Inc. 1999,2000
// All rights reserved
//
// Revision -
// $Revision: 1.12 $ $Date: 2002/07/26 14:11:59 $ $Author: wash $
//
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include "ArbMsh.hpp"
#include "ArbMshRegion2D.hpp"
#include "ArbMshEdgeList.hpp"
#include "ArbMshTopo2D.hpp"
#include "ArbArray.hpp"
#ifdef MEMDEBUG
#include "MemDbg.hpp"
#define new new(__FILE__,__LINE__)
#endif
#define BIG_CTV 1000.0
/* ------------------------------------------------------------
TopoVariance - compute a measure of topological variance
from an optimal connection to 4 nodes
*/
static double TopoVariance(int num_adj)
{
switch (num_adj)
{
case 2: return(4.0) ; break ;
case 3: return(0.444444) ; break ;
case 4: return(0.0) ; break ;
case 5: return(0.16) ; break ;
case 6: return(0.444444) ; break ;
}
double t0 = 360.0 / num_adj ;
return(((t0*t0)/2025.0) - (t0/11.25) + 4.0) ;
}
/* ------------------------------------------------------------
DoCollapse - do a collapse of a quad element
*/
static int DoCollapse(CArbMshTopo2D *quad_topo,int *nodes,
CArbHashTable<int,ArbIntNode> *node_table,
bool do_1_3)
{
CArbArray<CArbMshRegion2D::SeamElemCache> elem_cache ;
int nd0,nd1,i ;
quad_topo->DeleteElement(4,nodes) ;
// determine which node to remove (nd0) by checking
// if any of the nodes are on the boundary
if (do_1_3) {
ArbIntNode *ndp = node_table->Fetch(nodes[3]) ;
if (ndp->motion != ARB_FIXED) {
nd0 = nodes[3] ;
nd1 = nodes[1] ;
} else {
ndp = node_table->Fetch(nodes[1]) ;
if (ndp->motion != ARB_FIXED) {
nd0 = nodes[1] ;
nd1 = nodes[3] ;
} else {
return(-1) ;
}
}
} else {
ArbIntNode *ndp = node_table->Fetch(nodes[2]) ;
if (ndp->motion != ARB_FIXED) {
nd0 = nodes[2] ;
nd1 = nodes[0] ;
} else {
ndp = node_table->Fetch(nodes[0]) ;
if (ndp->motion != ARB_FIXED) {
nd0 = nodes[0] ;
nd1 = nodes[2] ;
} else {
return(-1) ;
}
}
}
CArbTopoAdjVtxIterator iter(quad_topo,nd0) ;
for (iter.First() ; iter.More() ; ++iter) {
if (iter.CcwElem() != NO_ELEM) {
CArbMshRegion2D::SeamElemCache edata ;
edata.elem = iter.CcwElem() ;
quad_topo->GetElemNodes(iter.CcwElem(),
nd0,&edata.num_nodes,edata.nodes) ;
elem_cache.InsertAtEnd(edata) ;
}
}
for (i=0 ; i<elem_cache.NumEntries() ; ++i) {
quad_topo->DeleteElement(elem_cache[i].num_nodes,
elem_cache[i].nodes) ;
}
for (i=0 ; i<elem_cache.NumEntries() ; ++i) {
elem_cache[i].nodes[0] = nd1 ;
quad_topo->InsertElement(elem_cache[i].elem,
elem_cache[i].num_nodes,
elem_cache[i].nodes) ;
}
return(nd1) ;
}
/* ------------------------------------------------------------
QuadTwoEdge - search for nodes that are adjacent to only
two edges
This routine looks for internal nodes that are adjacent
to only two edges. These nodes are deleted and the two
adjacent elements are collapsed into one.
# * where:
/|\ / \ # indicates nodes connected
/ | \ / \ to more than 4 nodes, and
* o * ==> * *
\ | / \ / o indicates nodes connected
\|/ \ / to less than 4 nodes.
# *
*/
static bool QuadTwoEdge(CArbMshTopo2D *quad_topo,
CArbHashTable<int,ArbIntNode> *node_table)
{
bool updates = false ;
int num_nodes = quad_topo->NumNodes() ;
int *nodes = quad_topo->GetNodeList() ;
for (int i=0 ; i<num_nodes ; ++i) {
int elems[3] ;
int num = 0 ;
CArbTopoAdjVtxIterator iter(quad_topo,nodes[i]) ;
for (iter.First() ; iter.More() ; ++iter) {
if (iter.CcwElem() == NO_ELEM) {
num = 0 ;
break ;
}
elems[num] = iter.CcwElem() ;
++num ;
if (num > 2) break ;
}
if (num == 2) {
int num0,num1,nodes0[4],nodes1[4] ;
quad_topo->GetElemNodes(elems[0],nodes[i],&num0,nodes0) ;
quad_topo->GetElemNodes(elems[1],nodes[i],&num1,nodes1) ;
if ((num0 != 4) || (num1 != 4)) continue ;
quad_topo->DeleteElement(num0,nodes0) ;
quad_topo->DeleteElement(num1,nodes1) ;
ArbIntNode *nd0 = node_table->Fetch(nodes0[1]) ;
ArbIntNode *nd1 = node_table->Fetch(nodes0[2]) ;
ArbIntNode *nd2 = node_table->Fetch(nodes1[2]) ;
if ((nd0->motion == ARB_FIXED) &&
(nd1->motion == ARB_FIXED) &&
(nd2->motion == ARB_FIXED)) {
quad_topo->InsertElement(elems[0],3,&nodes0[1]) ;
quad_topo->InsertElement(elems[1],3,&nodes1[1]) ;
} else {
ArbIntNode *nd0 = node_table->Fetch(nodes1[1]) ;
ArbIntNode *nd1 = node_table->Fetch(nodes1[2]) ;
ArbIntNode *nd2 = node_table->Fetch(nodes0[2]) ;
if ((nd0->motion == ARB_FIXED) &&
(nd1->motion == ARB_FIXED) &&
(nd2->motion == ARB_FIXED)) {
quad_topo->InsertElement(elems[0],3,&nodes0[1]) ;
quad_topo->InsertElement(elems[1],3,&nodes1[1]) ;
} else {
nodes0[0] = nodes1[2] ;
quad_topo->InsertElement(elems[0],4,nodes0) ;
}
}
updates = true ;
}
}
delete [] nodes ;
return(updates) ;
}
/* ------------------------------------------------------------
QuadCollapse - search for quads to collapse
This routine looks for quads that are candidates for
being collapsed. If two of the nodes are connected to
more than 4 nodes, and two are connected to less than
4 nodes, then the element is collapsed.
# * where:
/ \ | # indicates nodes connected
/ \ | to more than 4 nodes, and
o o ==> *
\ / | o indicates nodes connected
\ / | to less than 4 nodes.
# *
*/
static bool QuadCollapse(CArbMshTopo2D *quad_topo,
CArbHashTable<int,ArbIntNode> *node_table)
{
bool updates = false ;
int num_elems = quad_topo->NumElements() ;
int *elems = quad_topo->GetElemList() ;
for (int i=0 ; i<num_elems ; ++i) {
int num, nodes[4] ;
quad_topo->GetElemNodes(elems[i],&num,nodes) ;
if (num == 4) {
if (quad_topo->BoundaryNode(nodes[0])) continue ;
if (quad_topo->BoundaryNode(nodes[1])) continue ;
if (quad_topo->BoundaryNode(nodes[2])) continue ;
if (quad_topo->BoundaryNode(nodes[3])) continue ;
int n0 = quad_topo->NumAdjElems(nodes[0]) ;
if (n0 > 4) {
int n2 = quad_topo->NumAdjElems(nodes[2]) ;
if (n2 > 4) {
int n1 = quad_topo->NumAdjElems(nodes[1]) ;
if (n1 < 4) {
int n3 = quad_topo->NumAdjElems(nodes[3]) ;
if (n3 < 4) {
if (DoCollapse(quad_topo,nodes,node_table,true) != -1)
updates = true ;
}
}
}
} else if (n0 < 4) {
int n2 = quad_topo->NumAdjElems(nodes[2]) ;
if (n2 < 4) {
int n1 = quad_topo->NumAdjElems(nodes[1]) ;
if (n1 > 4) {
int n3 = quad_topo->NumAdjElems(nodes[3]) ;
if (n3 > 4) {
if (DoCollapse(quad_topo,nodes,node_table,false) != -1)
updates = true ;
}
}
}
}
}
}
delete [] elems ;
return(updates) ;
}
/* ------------------------------------------------------------
QuadOpen - search for places to open a node and create
a new quad
This routine looks for nodes that are candidates for
being opened. If a node is connected to 5 or more
nodes, and one or more of the adjacent nodes are
is connected to less than 4 nodes, then the node is
split and an new element is added.
o * where:
| / \ # indicates nodes connected
| / \ to more than 4 nodes, and
# ==> * *
| \ / o indicates nodes connected
| \ / to less than 4 nodes.
* *
*/
static bool QuadOpen(CArbMshTopo2D *quad_topo,
CArbMshRegion2D *region)
{
bool updates = false ;
int num_nodes = quad_topo->NumNodes() ;
int *nodes = quad_topo->GetNodeList() ;
for (int i=0 ; i<num_nodes ; ++i) {
CArbArray<int> node_cache ;
CArbTopoAdjVtxIterator iter(quad_topo,nodes[i]) ;
int num = 0 ;
for (iter.First() ; iter.More() ; ++iter) {
if (iter.CcwElem() == NO_ELEM) {
num = 0 ;
break ;
}
node_cache.InsertAtEnd(iter.AdjVtx()) ;
++num ;
}
if (num > 4) {
// now we have a candidate node for openning,
// find out how many elements are adjacent to
// to the adjacent nodes
CArbArray<int> num_adj ;
CArbArray<double> topo_var ;
CArbArray<bool> bdry_flg ;
double ctv_orig = TopoVariance(num) ;
for (int ii=0 ; ii<num ; ++ii) {
double tv ;
int nadj = quad_topo->NumAdjElems(node_cache[ii]) ;
if (quad_topo->BoundaryNode(node_cache[ii])) {
bdry_flg[ii] = true ;
nadj += 2 ;
// tv = TopoVariance(nadj) + 0.8 ;
} else {
bdry_flg[ii] = false ;
// tv = TopoVariance(nadj) ;
}
tv = TopoVariance(nadj) ;
num_adj.InsertAtEnd(nadj) ;
topo_var.InsertAtEnd(tv) ;
ctv_orig += tv ;
}
ctv_orig /= num+1 ;
// here we look for a special case that can cause
// run away refinement around a hole. This pattern
// is a node with 5 adjacent nodes. 4 of the nodes
// are adjacent to 4 nodes and one is adjancent to 3.
if (num == 5) {
int num3 = 0 ;
int num4 = 0 ;
for (int k=0 ; k<5 ; ++k) {
if (num_adj[k] == 3) {
++num3 ;
} else if (num_adj[k] == 4) {
++num4 ;
} else {
break ;
}
}
if ((num3 == 1) && (num4 == 4)) continue ;
}
// now we look at all the possible split options
// and rank them
int top = 0, bot = 0 ;
double ctv_min = BIG_CTV ;
if ((num % 2) == 0) {
for (int j=0 ; j<num ; ++j) {
if (bdry_flg[j] ||
bdry_flg[(j + num/2) % num]) continue ;
double ctv = TopoVariance(num_adj[j]+1) ;
for (int k=1 ; k<num ; ++k) {
if (k == num/2)
ctv += TopoVariance(num_adj[(j+k) % num]+1) ;
else
ctv += topo_var[(j+k) % num] ;
}
if (ctv < ctv_min) {
top = j ;
bot = (j + num/2) % num ;
ctv_min = ctv ;
}
}
ctv_min += 2 * TopoVariance(num-2) ;
ctv_min /= num+2 ;
} else {
for (int j=0 ; j<num ; ++j) {
if (bdry_flg[j]) continue ;
double ctv0 = TopoVariance(num_adj[j]+1) ;
double ctv1 = ctv0 ;
for (int k=1 ; k<num ; ++k) {
if (k == num/2) {
ctv0 += TopoVariance(num_adj[(j+k) % num]+1) ;
ctv1 += topo_var[(j+k) % num] ;
} if (k == (num/2)+1) {
ctv0 += topo_var[(j+k) % num] ;
ctv1 += TopoVariance(num_adj[(j+k) % num]+1) ;
} else {
ctv0 += topo_var[(j+k) % num] ;
ctv1 += topo_var[(j+k) % num] ;
}
}
if ((ctv0 < ctv_min) &&
!bdry_flg[(j + num/2) % num]) {
top = j ;
bot = (j + num/2) % num ;
ctv_min = ctv0 ;
}
if ((ctv1 < ctv_min) &&
!bdry_flg[(j + (num/2) + 1) % num]) {
top = j ;
bot = (j + (num/2) + 1) % num ;
ctv_min = ctv1 ;
}
}
ctv_min += TopoVariance(num-2) + TopoVariance(num-1) ;
ctv_min /= num+2 ;
}
// now we do the split
if (ctv_min < ctv_orig) {
int new_node = region->DuplicateNode(nodes[i]) ;
int new_elem = region->NewElemNum() ;
int nnum, lnodes[4] ;
int l = top ;
while (l != bot) {
int elem =
quad_topo->GetCCWElem(nodes[i],node_cache[l]) ;
quad_topo->GetElemNodes(elem,nodes[i],&nnum,lnodes) ;
quad_topo->DeleteElement(nnum,lnodes) ;
lnodes[0] = new_node ;
quad_topo->InsertElement(elem,nnum,lnodes) ;
++l ;
if (l >= num) l = 0 ;
}
lnodes[0] = node_cache[top] ;
lnodes[1] = new_node ;
lnodes[2] = node_cache[bot] ;
lnodes[3] = nodes[i] ;
quad_topo->InsertElement(new_elem,4,lnodes) ;
updates = true ;
}
}
}
delete [] nodes ;
return(updates) ;
}
/* ------------------------------------------------------------
DiagSwap - improve the topology with a diagonal swap
This routine looks for places where the local topological
connectivity can be improved by a diagonal swap. For
example
#-----* *-----* where:
/ \ \ / \ # indicates nodes connected
/ \ \ / \ to more than 4 nodes, and
o \ o ==> *-----------*
\ \ / \ / o indicates nodes connected
\ \ / \ / to less than 4 nodes.
*-----# *-----*
*/
static bool DiagSwap(CArbMshTopo2D *quad_topo)
{
bool updates = false ;
int num_nodes = quad_topo->NumNodes() ;
int *nodes = quad_topo->GetNodeList() ;
for (int i=0 ; i<num_nodes ; ++i) {
// note that we only consider nodes with a number
// greater than the current. That way each edge
// is only considered once.
int num = quad_topo->NumAdjElems(nodes[i]) ;
if ((num > 4) && !quad_topo->BoundaryNode(nodes[i])) {
CArbTopoAdjVtxIterator iter(quad_topo,nodes[i]) ;
for (iter.First() ; iter.More() ; ++iter) {
int nadj = quad_topo->NumAdjElems(iter.AdjVtx()) ;
if ((nadj > 4) && !quad_topo->BoundaryNode(iter.AdjVtx())) {
int cw0, ccw0, cw1, ccw1 ;
int ncw0, nccw0, ncw1, nccw1 ;
cw0 = quad_topo->GetCWNode(nodes[i],iter.AdjVtx()) ;
cw1 = quad_topo->GetCWNode(iter.AdjVtx(),nodes[i]) ;
ccw0 = quad_topo->GetCCWNode(nodes[i],iter.AdjVtx()) ;
ccw1 = quad_topo->GetCCWNode(iter.AdjVtx(),nodes[i]) ;
ncw0 = quad_topo->NumAdjElems(cw0) ;
ncw1 = quad_topo->NumAdjElems(cw1) ;
nccw0 = quad_topo->NumAdjElems(ccw0) ;
nccw1 = quad_topo->NumAdjElems(ccw0) ;
double ctv_cur_cw = TopoVariance(num) +
TopoVariance(nadj) +
TopoVariance(ncw0) +
TopoVariance(ncw1) ;
double ctv_cur_ccw = TopoVariance(num) +
TopoVariance(nadj) +
TopoVariance(nccw0) +
TopoVariance(nccw1) ;
double ctv_cw = TopoVariance(num-1) +
TopoVariance(nadj-1) +
TopoVariance(ncw0+1) +
TopoVariance(ncw1+1) ;
if (quad_topo->BoundaryNode(cw0) ||
quad_topo->BoundaryNode(cw1)) ctv_cw = BIG_CTV ;
double ctv_ccw = TopoVariance(num-1) +
TopoVariance(nadj-1) +
TopoVariance(nccw0+1) +
TopoVariance(nccw1+1) ;
if (quad_topo->BoundaryNode(ccw0) ||
quad_topo->BoundaryNode(ccw1)) ctv_ccw = BIG_CTV ;
if ((ctv_cw < ctv_cur_cw) ||
(ctv_ccw < ctv_cur_ccw)) {
int elem0,elem1,num0,num1,nodes0[4],nodes1[4] ;
elem0 = quad_topo->GetCCWElem(nodes[i],iter.AdjVtx()) ;
elem1 = quad_topo->GetCCWElem(iter.AdjVtx(),nodes[i]) ;
quad_topo->GetElemNodes(elem0,nodes[i],&num0,nodes0) ;
quad_topo->GetElemNodes(elem1,iter.AdjVtx(),&num1,nodes1) ;
if ((num0 != 4) || (num1 != 4)) break ;
quad_topo->DeleteElement(num0,nodes0) ;
quad_topo->DeleteElement(num1,nodes1) ;
if (ctv_cw < ctv_ccw) {
nodes0[1] = nodes1[2] ;
nodes1[1] = nodes0[2] ;
} else {
nodes0[0] = nodes1[3] ;
nodes1[0] = nodes0[3] ;
}
quad_topo->InsertElement(elem0,num0,nodes0) ;
quad_topo->InsertElement(elem1,num1,nodes1) ;
updates = true ;
break ;
}
}
}
}
}
delete [] nodes ;
return(updates) ;
}
/* ------------------------------------------------------------
ThreeEdgeInterior - improve the topology with a diagonal swap
This routine looks for places in the topology where there
are two adjacent three-edge interior nodes. It then makes
one of the modifications shown below if it will improve
the topological variance.
*--------*
/ \ / \ case 0
/ \ / \
* *--* * ==> *--*-----*--*
\ / \ /
\ / \ /
*--------*
*--------* *-----*
/ \ / \ case 1 / \ \
/ \ / \ / \ \
* *--* * ==> * \ *
\ / \ / \ \ /
\ / \ / \ \ /
*--------* *-----*
*--------* *-----*
/ \ / \ case 2 / / \
/ \ / \ / / \
* *--* * ==> * / *
\ / \ / \ / /
\ / \ / \ / /
*--------* *-----*
*/
static bool ThreeEdgeInterior(CArbMshTopo2D *quad_topo,
CArbHashTable<int,ArbIntNode> *node_table)
{
bool updates = false ;
int num_nodes = quad_topo->NumNodes() ;
int *nodes = quad_topo->GetNodeList() ;
for (int i=0 ; i<num_nodes ; ++i) {
// note that we only consider nodes with a number
// greater than the current. That way each edge
// is only considered once.
int num = quad_topo->NumAdjElems(nodes[i]) ;
if ((num == 3) && !quad_topo->BoundaryNode(nodes[i])) {
CArbTopoAdjVtxIterator iter(quad_topo,nodes[i]) ;
for (iter.First() ; iter.More() ; ++iter) {
int nadj = quad_topo->NumAdjElems(iter.AdjVtx()) ;
if ((nadj == 3) && !quad_topo->BoundaryNode(iter.AdjVtx())) {
/* Nodes and elems are numbered as follows:
*
* 3 2
* *--------*
* / \ (0) / \
* /(1)\ / \
* 4 * 0 *--* 1 * 7
* \ / \(3)/
* \ / (2) \ /
* *--------*
* 5 6
*/
int lnodes[8], ncon[8] ;
int elems[4], ennum, enodes[4] ;
lnodes[0] = nodes[i] ;
lnodes[1] = iter.AdjVtx() ;
elems[0] = quad_topo->GetCCWElem(lnodes[0],lnodes[1]) ;
if (elems[0] == NO_ELEM) break ;
quad_topo->GetElemNodes(elems[0],lnodes[0],&ennum,enodes) ;
if (ennum != 4) break ;
lnodes[2] = enodes[2] ;
lnodes[3] = enodes[3] ;
elems[1] = quad_topo->GetCCWElem(lnodes[0],lnodes[3]) ;
if (elems[1] == NO_ELEM) break ;
quad_topo->GetElemNodes(elems[1],lnodes[0],&ennum,enodes) ;
if (ennum != 4) break ;
lnodes[4] = enodes[2] ;
lnodes[5] = enodes[3] ;
elems[2] = quad_topo->GetCCWElem(lnodes[0],lnodes[5]) ;
if (elems[2] == NO_ELEM) break ;
quad_topo->GetElemNodes(elems[2],lnodes[0],&ennum,enodes) ;
if (ennum != 4) break ;
lnodes[6] = enodes[2] ;
elems[3] = quad_topo->GetCCWElem(lnodes[1],lnodes[6]) ;
if (elems[3] == NO_ELEM) break ;
quad_topo->GetElemNodes(elems[3],lnodes[1],&ennum,enodes) ;
if (ennum != 4) break ;
lnodes[7] = enodes[2] ;
// find the number connected to each node and
// the the current ctv
double ctv_cur = 0.0 ;
for (int ii=0 ; ii<8 ; ++ii) {
ncon[ii] = quad_topo->NumAdjElems(lnodes[ii]) ;
ctv_cur += TopoVariance(ncon[ii]) ;
}
ctv_cur /= 8 ;
// find the ctv for the three cases
double ctv_0 = (TopoVariance(ncon[4]-1) +
TopoVariance(ncon[7]-1) +
TopoVariance(ncon[3]+ncon[5]-4) +
TopoVariance(ncon[2]+ncon[6]-4)) / 4 ;
double ctv_1 = (TopoVariance(ncon[2]-1) +
TopoVariance(ncon[3]) +
TopoVariance(ncon[4]) +
TopoVariance(ncon[5]-1) +
TopoVariance(ncon[6]) +
TopoVariance(ncon[7])) / 6 ;
double ctv_2 = (TopoVariance(ncon[2]) +
TopoVariance(ncon[3]-2) +
TopoVariance(ncon[4]) +
TopoVariance(ncon[5]) +
TopoVariance(ncon[6]-2) +
TopoVariance(ncon[7])) / 6 ;
if ((ctv_0 < ctv_cur) || (ctv_1 < ctv_cur) ||
(ctv_2 < ctv_cur)) {
// now make sure that nodes 4 and 7 are between
// the lines 2 -> 3 and 5 -> 6
ArbIntNode *nd4 = node_table->Fetch(lnodes[4]) ;
ArbIntNode *nd7 = node_table->Fetch(lnodes[7]) ;
ArbIntNode *nd2 = node_table->Fetch(lnodes[2]) ;
ArbIntNode *nd3 = node_table->Fetch(lnodes[3]) ;
CArbCoord2D delt = (nd3->coord-nd2->coord).Normalize() ;
CArbCoord2D norm = CArbCoord2D(-delt.y(),delt.x()) ;
if ((norm * (nd7->coord-nd2->coord)) < 0.0) break ;
if ((norm * (nd4->coord-nd2->coord)) < 0.0) break ;
ArbIntNode *nd5 = node_table->Fetch(lnodes[5]) ;
ArbIntNode *nd6 = node_table->Fetch(lnodes[6]) ;
delt = (nd6->coord-nd5->coord).Normalize() ;
norm = CArbCoord2D(-delt.y(),delt.x()) ;
if ((norm * (nd7->coord-nd5->coord)) < 0.0) break ;
if ((norm * (nd4->coord-nd5->coord)) < 0.0) break ;
// case 1 or 2
if ((ctv_0 < ctv_1) && (ctv_0 < ctv_2)) {
int nds[4] ;
nds[0] = lnodes[0] ;
nds[1] = lnodes[3] ;
nds[2] = lnodes[4] ;
nds[3] = lnodes[5] ;
lnodes[3] = DoCollapse(quad_topo,nds,node_table,true) ;
if (lnodes[3] == -1) break ;
nds[0] = lnodes[1] ;
nds[1] = lnodes[2] ;
nds[2] = lnodes[3] ;
nds[3] = lnodes[0] ;
quad_topo->DeleteElement(4,nds) ;
nds[0] = lnodes[1] ;
nds[1] = lnodes[0] ;
nds[2] = lnodes[3] ;
nds[3] = lnodes[6] ;
quad_topo->DeleteElement(4,nds) ;
nds[0] = lnodes[1] ;
nds[1] = lnodes[6] ;
nds[2] = lnodes[7] ;
nds[3] = lnodes[2] ;
quad_topo->DeleteElement(4,nds) ;
nds[0] = lnodes[7] ;
nds[1] = lnodes[2] ;
nds[2] = lnodes[0] ;
nds[3] = lnodes[6] ;
quad_topo->InsertElement(elems[0],4,nds) ;
DoCollapse(quad_topo,nds,node_table,true) ;
} else {
// case 0
int nds[4] ;
nds[0] = lnodes[0] ;
nds[1] = lnodes[1] ;
nds[2] = lnodes[2] ;
nds[3] = lnodes[3] ;
quad_topo->DeleteElement(4,nds) ;
nds[1] = lnodes[3] ;
nds[2] = lnodes[4] ;
nds[3] = lnodes[5] ;
quad_topo->DeleteElement(4,nds) ;
nds[1] = lnodes[5] ;
nds[2] = lnodes[6] ;
nds[3] = lnodes[1] ;
quad_topo->DeleteElement(4,nds) ;
nds[0] = lnodes[1] ;
nds[1] = lnodes[6] ;
nds[2] = lnodes[7] ;
nds[3] = lnodes[2] ;
quad_topo->DeleteElement(4,nds) ;
if (ctv_1 < ctv_2) {
nds[0] = lnodes[3] ;
nds[1] = lnodes[4] ;
nds[2] = lnodes[5] ;
nds[3] = lnodes[6] ;
quad_topo->InsertElement(elems[0],4,nds) ;
nds[0] = lnodes[6] ;
nds[1] = lnodes[7] ;
nds[2] = lnodes[2] ;
nds[3] = lnodes[3] ;
quad_topo->InsertElement(elems[1],4,nds) ;
} else {
nds[0] = lnodes[2] ;
nds[1] = lnodes[3] ;
nds[2] = lnodes[4] ;
nds[3] = lnodes[5] ;
quad_topo->InsertElement(elems[0],4,nds) ;
nds[0] = lnodes[5] ;
nds[1] = lnodes[6] ;
nds[2] = lnodes[7] ;
nds[3] = lnodes[2] ;
quad_topo->InsertElement(elems[1],4,nds) ;
}
}
updates = true ;
break ;
}
}
}
}
}
delete [] nodes ;
return(updates) ;
}
// #include "ArbMshSmooth2D.hpp"
//
// static void DebugCleanupSmooth(CArbMshTopo2D *quad_topo,
// CArbHashTable<int,ArbIntNode> *node_table)
// {
// CArbHashTable<int,ArbMshElement2D> elem_table ;
// CArbTopoElemIterator iter(quad_topo) ;
// for (iter.First() ; iter.More() ; ++iter) {
// int num,nodes[4] ;
// quad_topo->GetElemNodes(*iter,&num,nodes) ;
// ArbMshElement2D elem ;
// elem.elem_id = *iter ;
// elem.mat_id = 1 ;
// elem.num_nodes = num ;
// for (int i=0 ; i<num ; ++i) elem.nodes[i] = nodes[i] ;
// elem_table.Store(*iter,elem) ;
// }
// CArbMshSmooth2D smooth(node_table,&elem_table) ;
// smooth.SmoothNodesWinslow() ;
// }
// %(CArbMshRegion2D::QuadCleanup-void-|-CArbMshTopo2D-|*)
/* ++ ----------------------------------------------------------
**
** QuadCleanup - do topological cleanups
**
** void QuadCleanup(CArbMshTopo2D *quad_topo)
**
** quad_topo - (in) quad mesh topology
**
** Description: This method performs topological cleanups on a
** quadrilateral mesh.
**
**
** -- */
void CArbMshRegion2D::QuadCleanup(CArbMshTopo2D *quad_topo)
{
bool updates = true ;
while (updates) {
updates = false ;
updates |= QuadTwoEdge(quad_topo,pnode_table) ;
// DebugCleanupSmooth(quad_topo,pnode_table) ;
// DoPrint(quad_topo) ;
// printf("a After QuadTwoEdge\n") ;
// printf("n\n") ;
updates |= QuadCollapse(quad_topo,pnode_table) ;
// DebugCleanupSmooth(quad_topo,pnode_table) ;
// DoPrint(quad_topo) ;
// printf("a After QuadCollapse\n") ;
// printf("n\n") ;
updates |= QuadOpen(quad_topo,this) ;
// DebugCleanupSmooth(quad_topo,pnode_table) ;
// DoPrint(quad_topo) ;
// printf("a After QuadOpen\n") ;
// printf("n\n") ;
// diagonal swaps can go on forever so we don't
// check the return status on these.
DiagSwap(quad_topo) ;
// DebugCleanupSmooth(quad_topo,pnode_table) ;
// DoPrint(quad_topo) ;
// printf("a After DiagSwap\n") ;
// printf("n\n") ;
updates |= ThreeEdgeInterior(quad_topo,pnode_table) ;
// DebugCleanupSmooth(quad_topo,pnode_table) ;
// DoPrint(quad_topo) ;
// printf("a After ThreeEdgeInterior\n") ;
// printf("n\n") ;
}
}
/* ++ ----------------------------------------------------------
**
** QuadAngleCheck - do quadrilateral angle checks
**
** void QuadAngleChecks(CArbMshTopo2D *quad_topo)
**
** quad_topo - (in) quad mesh topology
**
** Description: Look for quadrilateral elements that have
** angle that are out of limits and replace them with
** two triangles.
**
**
** -- */
#define PI 3.14159265359
void CArbMshRegion2D::QuadAngleChecks()
{
// loop through all elements and find the nodes
CArbArray<int> invalid ;
CArbHashTableIterator<int,ArbMshElement2D> elems(pelem_table) ;
for (elems.First() ; elems.More() ; ++elems) {
int i ;
ArbMshElement2D *elem = elems.Entry() ;
int num_node = ((elem->num_nodes == 3) ||
(elem->num_nodes == 6)) ? 3 : 4 ;
if (num_node != 4) continue ;
// get the nodes coordinates
ArbIntNode *nd[4] ;
for (i=0 ; i<4 ; ++i) {
nd[i] = pnode_table->Fetch(elem->nodes[i]) ;
}
// if we are doing node checks, loop through the nodes
// and check the angles.
if (QuadAngleLocation == AT_NODES) {
for (i=0 ; i<4 ; ++i) {
int j = i==3 ? 0 : i+1 ;
int k = i==0 ? 3 : i-1 ;
double angle = Angle2Pi(nd[i]->coord,nd[j]->coord,
nd[k]->coord) ;
if ((angle < MinQuadAngle) || (angle > MaxQuadAngle)) {
invalid.InsertAtEnd(elem->elem_id) ;
break ;
}
}
} else {
// compute the components of the jacobian at the guass
// points (many values precomputed).
double val0 = 0.211325 ;
double val1 = 0.788675 ;
double dxdr[4], dxds[4], dydr[4], dyds[4] ;
dxdr[0] = -val1*nd[0]->coord[0] + val1*nd[1]->coord[0] +
val0*nd[2]->coord[0] - val0*nd[3]->coord[0] ;
dydr[0] = -val1*nd[0]->coord[1] + val1*nd[1]->coord[1] +
val0*nd[2]->coord[1] - val0*nd[3]->coord[1] ;
dxds[0] = -val1*nd[0]->coord[0] - val0*nd[1]->coord[0] +
val0*nd[2]->coord[0] + val1*nd[3]->coord[0] ;
dyds[0] = -val1*nd[0]->coord[1] - val0*nd[1]->coord[1] +
val0*nd[2]->coord[1] + val1*nd[3]->coord[1] ;
dxdr[1] = dxdr[0] ;
dydr[1] = dydr[0] ;
dxds[1] = -val0*nd[0]->coord[0] - val1*nd[1]->coord[0] +
val1*nd[2]->coord[0] + val0*nd[3]->coord[0] ;
dyds[1] = -val0*nd[0]->coord[1] - val1*nd[1]->coord[1] +
val1*nd[2]->coord[1] + val0*nd[3]->coord[1] ;
dxdr[2] = -val0*nd[0]->coord[0] + val0*nd[1]->coord[0] +
val1*nd[2]->coord[0] - val1*nd[3]->coord[0] ;
dydr[2] = -val0*nd[0]->coord[1] + val0*nd[1]->coord[1] +
val1*nd[2]->coord[1] - val1*nd[3]->coord[1] ;
dxds[2] = dxds[1] ;
dyds[2] = dyds[1] ;
dxdr[3] = dxdr[2] ;
dydr[3] = dydr[2] ;
dxds[3] = dxds[0] ;
dyds[3] = dyds[0] ;
for (i=0 ; i<4 ; ++i) {
double dot = dxdr[i]*dxds[i] + dydr[i]*dyds[i] ;
double mag0 = sqrt(dxdr[i]*dxdr[i] + dydr[i]*dydr[i]) ;
double mag1 = sqrt(dxds[i]*dxds[i] + dyds[i]*dyds[i]) ;
double cos_angle = dot / (mag0*mag1) ;
if (cos_angle > 1.0) cos_angle = 1.0 ;
if (cos_angle < -1.0) cos_angle = -1.0 ;
double angle = acos(cos_angle) ;
if ((angle < MinQuadAngle) || (angle > MaxQuadAngle)) {
invalid.InsertAtEnd(elem->elem_id) ;
break ;
}
angle = PI - angle ;
if ((angle < MinQuadAngle) || (angle > MaxQuadAngle)) {
invalid.InsertAtEnd(elem->elem_id) ;
break ;
}
}
}
}
// loop through the invalid elements and replace with triangles.
int i ;
for (i=0 ; i<invalid.NumEntries() ; ++i) {
ArbMshElement2D elem = *(pelem_table->Fetch(invalid[i])) ;
pelem_table->Remove(invalid[i]) ;
ArbIntNode *nd[4] ;
for (int j=0 ; j<4 ; ++j) {
nd[j] = pnode_table->Fetch(elem.nodes[j]) ;
}
// determine which of the two possible triangular
// patterns to add
double sm0 = TriMetric(nd[0]->coord,nd[1]->coord,
nd[2]->coord ) ;
double sm1 = TriMetric(nd[0]->coord,nd[2]->coord,
nd[3]->coord ) ;
double sm_case0 = sm0 < sm1 ? sm0 : sm1 ;
double sm2 = TriMetric(nd[0]->coord,nd[1]->coord,
nd[3]->coord ) ;
double sm3 = TriMetric(nd[3]->coord,nd[1]->coord,
nd[2]->coord ) ;
double sm_case1 = sm2 < sm3 ? sm2 : sm3 ;
ArbMshElement2D new_elem ;
new_elem.mat_id = elem.mat_id ;
if (sm_case1 < sm_case0) {
if (elem.num_nodes == 4) {
new_elem.elem_id = elem.elem_id ;
new_elem.num_nodes = 3 ;
new_elem.nodes[0] = elem.nodes[0] ;
new_elem.nodes[1] = elem.nodes[1] ;
new_elem.nodes[2] = elem.nodes[2] ;
pelem_table->Store(new_elem.elem_id,new_elem) ;
new_elem.elem_id = NewElemNum() ;
new_elem.num_nodes = 3 ;
new_elem.nodes[0] = elem.nodes[0] ;
new_elem.nodes[1] = elem.nodes[2] ;
new_elem.nodes[2] = elem.nodes[3] ;
pelem_table->Store(new_elem.elem_id,new_elem) ;
} else {
CArbCoord2D pos = 0.5*(nd[0]->coord + nd[2]->coord) ;
int new_node = NewNode(pos.x(),pos.y(),
INTERIOR,ARB_FLOATING,false) ;
new_elem.elem_id = elem.elem_id ;
new_elem.num_nodes = 6 ;
new_elem.nodes[0] = elem.nodes[0] ;
new_elem.nodes[1] = elem.nodes[1] ;
new_elem.nodes[2] = elem.nodes[2] ;
new_elem.nodes[3] = elem.nodes[4] ;
new_elem.nodes[4] = elem.nodes[5] ;
new_elem.nodes[5] = new_node ;
pelem_table->Store(new_elem.elem_id,new_elem) ;
new_elem.elem_id = NewElemNum() ;
new_elem.num_nodes = 6 ;
new_elem.nodes[0] = elem.nodes[0] ;
new_elem.nodes[1] = elem.nodes[2] ;
new_elem.nodes[2] = elem.nodes[3] ;
new_elem.nodes[3] = new_node ;
new_elem.nodes[4] = elem.nodes[6] ;
new_elem.nodes[5] = elem.nodes[7] ;
pelem_table->Store(new_elem.elem_id,new_elem) ;
}
} else {
if (elem.num_nodes == 4) {
new_elem.elem_id = elem.elem_id ;
new_elem.num_nodes = 3 ;
new_elem.nodes[0] = elem.nodes[0] ;
new_elem.nodes[1] = elem.nodes[1] ;
new_elem.nodes[2] = elem.nodes[3] ;
pelem_table->Store(new_elem.elem_id,new_elem) ;
new_elem.elem_id = NewElemNum() ;
new_elem.num_nodes = 3 ;
new_elem.nodes[0] = elem.nodes[3] ;
new_elem.nodes[1] = elem.nodes[1] ;
new_elem.nodes[2] = elem.nodes[2] ;
pelem_table->Store(new_elem.elem_id,new_elem) ;
} else {
CArbCoord2D pos = 0.5*(nd[1]->coord + nd[3]->coord) ;
int new_node = NewNode(pos.x(),pos.y(),
INTERIOR,ARB_FLOATING,false) ;
new_elem.elem_id = elem.elem_id ;
new_elem.num_nodes = 6 ;
new_elem.nodes[0] = elem.nodes[0] ;
new_elem.nodes[1] = elem.nodes[1] ;
new_elem.nodes[2] = elem.nodes[3] ;
new_elem.nodes[3] = elem.nodes[4] ;
new_elem.nodes[4] = new_node ;
new_elem.nodes[5] = elem.nodes[7] ;
pelem_table->Store(new_elem.elem_id,new_elem) ;
new_elem.elem_id = NewElemNum() ;
new_elem.num_nodes = 6 ;
new_elem.nodes[0] = elem.nodes[3] ;
new_elem.nodes[1] = elem.nodes[1] ;
new_elem.nodes[2] = elem.nodes[2] ;
new_elem.nodes[3] = new_node ;
new_elem.nodes[4] = elem.nodes[5] ;
new_elem.nodes[5] = elem.nodes[6] ;
pelem_table->Store(new_elem.elem_id,new_elem) ;
}
}
}
}
| [
"[email protected]"
] | |
6e75444033efb5025bac1bdfc97f3d8af9ceb2c0 | 1c330e9395fbc8bb35dd4c837dea010d29e6e7ff | /numeric/numericfwd.hpp | 5671c5809add59e992cbf19e6213bac13cd00361 | [] | no_license | luk036/lineda | 4e613cb8e3d9f4b18cb073a10663c9bc0f27103e | 905cb898e5af4222f25299ea030136cc3d2be428 | refs/heads/master | 2021-01-17T05:19:32.255858 | 2019-10-04T05:02:42 | 2019-10-04T05:02:42 | 3,990,632 | 0 | 0 | null | 2019-10-04T05:02:43 | 2012-04-11T05:54:33 | C++ | UTF-8 | C++ | false | false | 405 | hpp | #ifndef NUMERIC_FWD_HPP
#define NUMERIC_FWD_HPP
/** Forward declarations */
namespace numeric {
template <typename _Tp> class interval;
template <typename _Tp> struct vector2;
template <typename _Tp> struct matrix2;
template <typename _Tp> class polynomial;
template <typename _Tp> class triple;
template <typename _Tp> inline interval<_Tp> make_interval(_Tp x, _Tp y);
class bad_polynomial;
}
#endif
| [
"[email protected]"
] | |
ec9c853e7abc54cfc7d71869819debcdf35ee15e | 329226dbea3c6b6d93d236aa8e656f2afa440368 | /HOMEWORK/ASSIGNMENT 5 Chap 5 and 7/Savitch_9thEd_Chap7_Proj19_SecretPinPassword/main.cpp | a30ab7e7d705239096a179045c86d6539e9173af | [] | no_license | Armando437121/OrnelasArmado_CIS5_SUMMER2016 | cfaa023a0aa5eb41fce9132421b296ae1112325b | 5980025151d8da709f35b69e0ca1f9bd43ca884f | refs/heads/master | 2020-04-02T06:21:37.441099 | 2016-07-26T20:17:21 | 2016-07-26T20:17:21 | 64,250,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,962 | cpp | /*
* File: main.cpp
* Author: Armando Ornelas
* Created on July 24, 2016, 12:00 PM
* Purpose: Enter in a 5 digit pin converted to a code.
*/
//System Libraries
#include <iostream> //Input/ Output Stream Library
#include <cstdlib>
#include <ctime>
using namespace std; //Namespace of the System Libraries
//User Libraries
//Global Constants
//Function Prototypes
void getPin(int[],int);
void gnerate(int[],int);
void getCode(int[],int);
void compare(int[],int[],int[]);
//Execution
int main(int argc, char** argv) {
//Set Random seed
srand(static_cast<unsigned int>(time(0)));
//Variables
const int SIZE=10;
const int PIN=5; //5 digit pin
int pin[PIN];
int num[SIZE];
int guess[PIN];
char ans;
//Input and Process Data
getPin(pin,PIN);
do{
cout<<endl<<"PIN: 0 1 2 3 4 5 6 7 8 9\n"
"NUM: ";
gnerate(num,SIZE);
for(int i=0;i<SIZE;i++){
cout<<num[i]<<" ";
}
getCode(guess,PIN);
//Output Data
compare(pin,guess,num);
cout<<"If you wish to log in again input a 1."
" Anything else to quit."<<endl;
cin>>ans;
}while(ans=='1');
return 0;
}
void getPin(int a[],int size){
cout<<"Input your 5 digit PIN seperated with spaces"<<endl;
for(int i=0;i<size;i++){
cin>>a[i];
}
}
void gnerate(int a[],int size){
for(int i=0;i<size;i++){
a[i]=(rand()%3+1);
}
}
void getCode(int a[],int size){
cout<<endl<<"Input the 5 Numbers that correspond to your PIN separated by spaces"<<endl;
for(int i=0;i<size;i++){
cin>>a[i];
}
}
void compare(int pin[],int guess[],int num[]){
bool correct=true;
for(int i=0;i<5&&correct==true;i++){
if(guess[i]==num[(pin[i])])correct=true;
else correct=false;
}
if(correct)cout<<"Authentication Process Complete"<<endl;
else cout<<"Incorrect PIN"<<endl;
} | [
"[email protected]"
] | |
99d27b0d45cc8ba4e3a0bc84a06c449e35bd4cbb | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /media/base/mime_util.h | 0ff67036d80d8837fd5d966adc10345f009505b6 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 4,603 | h | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MEDIA_BASE_MIME_UTIL_H_
#define MEDIA_BASE_MIME_UTIL_H_
#include <string>
#include <vector>
#include "media/base/audio_codecs.h"
#include "media/base/media_export.h"
#include "media/base/video_codecs.h"
namespace media {
// Check to see if a particular MIME type is in the list of
// supported/recognized MIME types.
MEDIA_EXPORT bool IsSupportedMediaMimeType(const std::string& mime_type);
// Splits various codecs into |codecs_out|, conditionally stripping the profile
// and level info when |strip| == true. For example, passed "aaa.b.c,dd.eee", if
// |strip| == true |codecs_out| will contain {"aaa", "dd"}, if |strip| == false
// |codecs_out| will contain {"aaa.b.c", "dd.eee"}.
// See http://www.ietf.org/rfc/rfc4281.txt.
MEDIA_EXPORT void SplitCodecsToVector(const std::string& codecs,
std::vector<std::string>* codecs_out,
bool strip);
// Returns true if successfully parsed the given |mime_type| and |codec_id|,
// setting |out_*| arguments to the parsed video codec, profile, and level.
// |out_is_ambiguous| will be true when the codec string is incomplete such that
// some guessing was required to decide the codec, profile, or level.
// Returns false if parsing fails (invalid string, or unrecognized video codec),
// in which case values for |out_*| arguments are undefined.
MEDIA_EXPORT bool ParseVideoCodecString(const std::string& mime_type,
const std::string& codec_id,
bool* out_is_ambiguous,
VideoCodec* out_codec,
VideoCodecProfile* out_profile,
uint8_t* out_level,
VideoColorSpace* out_colorspace);
// Returns true if successfully parsed the given |mime_type| and |codec_id|,
// setting |out_audio_codec| to found codec. |out_is_ambiguous| will be true
// when the codec string is incomplete such that some guessing was required to
// decide the codec.
// Returns false if parsing fails (invalid string, or unrecognized audio codec),
// in which case values for |out_*| arguments are undefined.
MEDIA_EXPORT bool ParseAudioCodecString(const std::string& mime_type,
const std::string& codec_id,
bool* out_is_ambiguous,
AudioCodec* out_codec);
// Indicates that the MIME type and (possible codec string) are supported.
enum SupportsType {
// The given MIME type and codec combination is not supported.
IsNotSupported,
// The given MIME type and codec combination is supported.
IsSupported,
// There's not enough information to determine if the given MIME type and
// codec combination can be rendered or not before actually trying to play it.
MayBeSupported
};
// Checks the |mime_type| and |codecs| against the MIME types known to support
// only a particular subset of codecs.
// * Returns IsSupported if the |mime_type| is supported and all the codecs
// within the |codecs| are supported for the |mime_type|.
// * Returns MayBeSupported if the |mime_type| is supported and is known to
// support only a subset of codecs, but |codecs| was empty. Also returned if
// all the codecs in |codecs| are supported, but additional codec parameters
// were supplied (such as profile) for which the support cannot be decided.
// * Returns IsNotSupported if either the |mime_type| is not supported or the
// |mime_type| is supported but at least one of the codecs within |codecs| is
// not supported for the |mime_type|.
MEDIA_EXPORT SupportsType
IsSupportedMediaFormat(const std::string& mime_type,
const std::vector<std::string>& codecs);
// Similar to the above, but for encrypted formats.
MEDIA_EXPORT SupportsType
IsSupportedEncryptedMediaFormat(const std::string& mime_type,
const std::vector<std::string>& codecs);
// Test only method that removes proprietary media types and codecs from the
// list of supported MIME types and codecs. These types and codecs must be
// removed to ensure consistent layout test results across all Chromium
// variations.
MEDIA_EXPORT void RemoveProprietaryMediaTypesAndCodecsForTests();
} // namespace media
#endif // MEDIA_BASE_MIME_UTIL_H_
| [
"[email protected]"
] | |
3ec07dc4f48341c77f6d37186adecce3f534f56a | 07a5787ae40f09ebe704e88814c502c189b49c72 | /librssoft/src/GF8_test.cpp | a3d4647785160b6c09e2fa6ae36c2833f5bbbe85 | [] | no_license | xdcesc/rssoft | 075c8427ec96b1712bf77a31909419bf71fc9175 | 493b7909eeff04583d02b0ced6157b47b1bdd36e | refs/heads/master | 2021-03-12T22:43:45.461804 | 2013-09-18T21:56:31 | 2013-09-18T21:56:31 | 40,472,370 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,631 | cpp | /*
Copyright 2013 Edouard Griffiths <f4exb at free dot fr>
This file is part of RSSoft. A Reed-Solomon Soft Decoding library
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Boston, MA 02110-1301 USA
Original from Arash Partow (see original copytight notice).
Modified and included in RSSoft in gf sub-namespace.
Tests of Galois Field sub-library on GF(8) and GF(8)[X]
*/
#include <iostream>
#include <utility>
#include <stdlib.h>
#include <stdio.h>
#include "GFq.h"
#include "GFq_Element.h"
#include "GFq_Polynomial.h"
#include "GF2_Element.h"
#include "GF2_Polynomial.h"
/*
P(X) = X^3+X+1
p(x) = 1x^3+0x^2+1x^1+1x^0
1 0 1 1 <-MSB
*/
rssoft::gf::GF2_Element ppe[4] = {1,1,0,1};
rssoft::gf::GF2_Polynomial ppoly(4,ppe);
/*
A Galois Field of type GF(2^3)
*/
rssoft::gf::GFq gf8(3,ppoly);
// ================================================================================================
template <typename T>
std::ostream& operator <<(std::ostream& os, const std::vector<T>& vec)
{
os << "[";
typename std::vector<T>::const_iterator it = vec.begin();
for (;it != vec.end(); ++ it)
{
os << (it == vec.begin() ? "" : ", ");
os << *it;
}
os << "]";
return os;
}
// ================================================================================================
int main(int argc, char *argv[])
{
std::cout << gf8;
rssoft::gf::GFq_Element test(gf8), def_e(gf8), one(gf8,1);
test = def_e^2;
std::cout << test << std::endl;
std::cout << one << std::endl;
rssoft::gf::GFq_Element pe[4] = {
rssoft::gf::GFq_Element(gf8,gf8.alpha(4)),
rssoft::gf::GFq_Element(gf8,gf8.alpha(1)),
rssoft::gf::GFq_Element(gf8,gf8.alpha(2)),
rssoft::gf::GFq_Element(gf8,gf8.alpha(3)),
};
size_t pe_sz = sizeof(pe)/sizeof(rssoft::gf::GFq_Element);
rssoft::gf::GFq_Element qe[3] = {
rssoft::gf::GFq_Element(gf8,1),
rssoft::gf::GFq_Element(gf8,0),
rssoft::gf::GFq_Element(gf8,1),
};
size_t qe_sz = sizeof(qe)/sizeof(rssoft::gf::GFq_Element);
rssoft::gf::GFq_Element qz[1] = {
rssoft::gf::GFq_Element(gf8,1),
};
size_t qz_sz = sizeof(qz)/sizeof(rssoft::gf::GFq_Element);
std::cout << gf8.pwr() << std::endl;
rssoft::gf::GFq_Polynomial P(gf8,pe_sz,pe);
std::cout << "P(x) = " << P << " deg=" << P.deg() << std::endl;
P.set_alpha_format(true);
std::cout << "P(x) = " << P << std::endl;
rssoft::gf::GFq_Polynomial Pc(P);
std::cout << "Pc(x) = " << Pc << " deg=" << Pc.deg() << std::endl;
Pc.set_alpha_format(false);
std::cout << "Pc(x) = " << Pc << std::endl;
rssoft::gf::GFq_Polynomial Q(gf8,qe_sz,qe);
std::cout << "Q(x) = " << Q << " deg=" << Q.deg() << std::endl;
Q.set_alpha_format(true);
std::cout << "Q(x) = " << Q << std::endl;
std::cout << "Q(a) = " << Q(gf8.alpha(1)) << std::endl;
rssoft::gf::GFq_Polynomial S=P+Q;
std::cout << "S(x) = " << S << std::endl;
S.set_alpha_format(false);
std::cout << "S(x) = " << S << std::endl;
rssoft::gf::GFq_Polynomial M=P*Q;
std::cout << "M(x) = " << M << std::endl;
M.set_alpha_format(false);
std::cout << "M(x) = " << M << std::endl;
P.set_alpha_format(false);
Q.set_alpha_format(false);
const std::pair<rssoft::gf::GFq_Polynomial,rssoft::gf::GFq_Polynomial>& divres = div(P,Q);
std::cout << "q(x) = " << divres.first << std::endl;
std::cout << "r(x) = " << divres.second << std::endl;
std::cout << "q(x)*Q(x)+r(x) = " << divres.first*Q+divres.second << std::endl;
std::cout << "P(x)/Q(x) = " << P/Q << std::endl;
std::cout << "P(x)%Q(x) = " << P%Q << std::endl;
rssoft::gf::GFq_Polynomial Z(gf8,qz_sz,qz);
std::cout << "Z(x) = " << Z << " deg=" << Z.deg() << std::endl;
std::cout << "P(x)/Z(x) = " << P/Z << std::endl;
rssoft::gf::GFq_Polynomial G=gcd(P,Q);
std::cout << std::endl;
std::cout << "gcd(P,Q)(x) = " << G << std::endl;
rssoft::gf::GFq_Element ae[3] = {
rssoft::gf::GFq_Element(gf8,0),
rssoft::gf::GFq_Element(gf8,1),
rssoft::gf::GFq_Element(gf8,1),
};
size_t ae_sz = sizeof(ae)/sizeof(rssoft::gf::GFq_Element);
rssoft::gf::GFq_Polynomial A(gf8,ae_sz,ae);
rssoft::gf::GFq_Element be[2] = {
rssoft::gf::GFq_Element(gf8,1),
rssoft::gf::GFq_Element(gf8,1),
};
size_t be_sz = sizeof(be)/sizeof(rssoft::gf::GFq_Element);
rssoft::gf::GFq_Polynomial B(gf8,be_sz,be);
std::cout << "gcd(A,B)(x) = " << gcd(A,B) << std::endl;
std::cout << "P'(x) = " << P.derivative() << std::endl;
std::cout << std::endl;
std::cout << "P(x)<<1 = " << (P<<1) << std::endl;
std::cout << "P(x)>>1 = " << (P>>1) << std::endl;
std::cout << "P(x)<<2 = " << (P<<2) << std::endl;
std::cout << "P(x)>>2 = " << (P>>2) << std::endl;
std::cout << "P(x)<<3 = " << (P<<3) << std::endl;
std::cout << "P(x)>>3 = " << (P>>3) << std::endl;
const std::vector<rssoft::gf::GFq_Element>& rootsP = rootex(P);
std::cout << std::endl;
std::cout << "roots(P) = " << rootsP << std::endl;
const std::vector<rssoft::gf::GFq_Element>& rootsQ = rootex(Q);
std::cout << "roots(Q) = " << rootsQ << std::endl;
std::vector<rssoft::gf::GFq_Element> rootsChienP;
P.rootChien(rootsChienP);
std::cout << "(Chien's) roots(P) = " << rootsChienP << std::endl;
std::vector<rssoft::gf::GFq_Element> rootsChienQ;
Q.rootChien(rootsChienQ);
std::cout << "(Chien's) roots(Q) = " << rootsChienQ << std::endl;
rssoft::gf::GFq_Element ce[2] = {
rssoft::gf::GFq_Element(gf8,6),
rssoft::gf::GFq_Element(gf8,1),
};
size_t ce_sz = sizeof(ce)/sizeof(rssoft::gf::GFq_Element);
rssoft::gf::GFq_Polynomial C(gf8,ce_sz,ce);
const std::pair<rssoft::gf::GFq_Polynomial,rssoft::gf::GFq_Polynomial>& divpc = div(P,C);
std::cout << "P(X) = (" << C << ")*(" << divpc.first << ") + (" << divpc.second << ")" << std::endl;
const std::vector<rssoft::gf::GFq_Element>& rootsPC = rootex(divpc.first);
std::cout << "roots(P/C) = " << rootsPC << std::endl;
ce[0]=rssoft::gf::GFq_Element(gf8,1);
rssoft::gf::GFq_Polynomial C1(gf8,ce_sz,ce);
ce[0]=rssoft::gf::GFq_Element(gf8,2);
rssoft::gf::GFq_Polynomial C2(gf8,ce_sz,ce);
ce[0]=rssoft::gf::GFq_Element(gf8,3);
rssoft::gf::GFq_Polynomial C3(gf8,ce_sz,ce);
const std::vector<rssoft::gf::GFq_Element>& rootsMCi = rootex(C*C1*C2*C3);
std::cout << "roots(C*C1*C2*C3) = " << rootsMCi << std::endl;
std::vector<rssoft::gf::GFq_Element> rootsChienMCi;
(C*C1*C2*C3).rootChien(rootsChienMCi);
std::cout << "(Chien's) roots(C*C1*C2*C3) = " << rootsChienMCi << std::endl;
rssoft::gf::GFq_Polynomial D=P;
const rssoft::gf::GFq_Element d_lead = D.make_monic();
std::cout << std::endl;
std::cout << "P.make_monic(X)) = " << D << " lead : " << d_lead << std::endl;
rssoft::gf::GFq_Element d_lead2(D.field());
D = get_monic(P, d_lead2);
std::cout << "get_monic(P(X)) = " << D << " lead : " << d_lead2 << std::endl;
std::cout << std::endl;
std::cout << "P (D) square free decomposition: " << square_free_decomposition(D) << std::endl;
rssoft::gf::GFq_Polynomial Cx = C*C1*C2*C3;
Cx.make_monic();
std::cout << "C*C1*C2*C3(X) (monic) = " << Cx << std::endl;
std::cout << "C*C1*C2*C3 square free decomposition: " << square_free_decomposition(Cx) << std::endl;
rssoft::gf::GFq_Element x1e[2] = {
rssoft::gf::GFq_Element(gf8,0),
rssoft::gf::GFq_Element(gf8,1),
};
size_t x1e_sz = sizeof(x1e)/sizeof(rssoft::gf::GFq_Element);
rssoft::gf::GFq_Polynomial X1(gf8,x1e_sz,x1e);
std::cout << std::endl;
std::cout << "X1(X) = " << X1 << std::endl;
std::cout << "X1(X)^4 = " << (X1^4) << std::endl;
exit(EXIT_SUCCESS);
return true;
}
| [
"[email protected]"
] | |
da24ddd4105c7c1b39d45a1442e03ce4a3fae18b | 42fabacc87225cff569e8ce698e4a5010d6593ad | /C/msg/comm/msgrcv_cmd.h | 78766c7af02b46c7479fc4169b3b3672060ba75d | [] | no_license | maquanhong/emacs | 476de8d791e717c4e54a223d97b3d093937a7bbe | 3a3f6fe27d8a78284ffff02156bd488f5dc1c427 | refs/heads/master | 2020-12-25T06:46:44.725956 | 2013-08-06T08:55:36 | 2013-08-06T08:55:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,071 | h | /*
* =====================================================================================
*
* Filename: msgrcv_cmd.h
*
* Description: Header file of Msgrcv_cmd.cpp
*
* Version: 1.0
* Created: 06/22/2013 04:22:17 PM
* Revision: none
* Compiler: g++
*
* Author: david.zhao
* Company: Beijing Ding Qing Soft Co. Ltd.
*
* =====================================================================================
*/
#ifndef __MSGRECV_H_
#define __MSGRECV_H_
#include <deque>
#include "Thread.h"
#include "message.h"
using std::string;
class Msg_recv : public Thread {
public:
Msg_recv();
Msg_recv(const string&);
virtual ~Msg_recv();
virtual void* run();
void cache_msg(const MsgCmd& new_msg);
MsgCmd& get_cur_msg();
bool msg_is_empty();
private:
std::deque<MsgCmd> msg_queue;
};
inline void Msg_recv::cache_msg(const MsgCmd& new_msg) {
msg_queue.push_back(new_msg);
}
inline bool Msg_recv::msg_is_empty() {
return msg_queue.empty();
}
#endif //__MSGRECV_H_
| [
"weishijian@weishijian-MacUbuntu.(none)"
] | weishijian@weishijian-MacUbuntu.(none) |
ae0db6d729ae9e50a4e6d10fa2d2f0b507eefd65 | 0b508c21b3a219f0c9f05e7457f34517fd31a119 | /CodeForces/136A/13757395_AC_62ms_3440kB.cpp | 604f7ef3bbf77c9452b8337c8e67f768bba14ca8 | [] | no_license | shiningflash/Online-Judge-Solutions | fa7402d37f8ca3238012d7cff76255dec3e9e2b0 | fc267f87b6c0551d5bdf41f2e160fce58b136ba9 | refs/heads/master | 2021-06-11T20:52:16.777025 | 2021-03-31T12:52:54 | 2021-03-31T12:52:54 | 164,604,423 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, input;
cin >> n;
int a[n+1];
for (int i = 1; i <= n; i++) {
cin >> input;
a[input] = i;
}
cout << a[1];
for (int i = 2; i <= n; i++)
cout << " " << a[i];
cout << endl;
return 0;
} | [
"[email protected]"
] | |
14c1123d2ecf98fd0b348ac16c9a58785c84cbbc | 99d63d4916e4cf2a86199c50a10d0ccca3cb88b7 | /frameworks/native/include/gui/BufferQueueConsumer.h | 3b681ee0da85a96f2a31b5e3ff0a58ada6b9909f | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | hyongbai/aosp-lite-7 | 3a3062de4f0dbbd01ea5391194a89241fc804061 | e1e68989c3b95060a467928bba2c0a9638201b0f | refs/heads/master | 2023-08-18T21:51:21.006920 | 2021-10-14T08:43:14 | 2021-10-14T08:43:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,532 | h | /*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_GUI_BUFFERQUEUECONSUMER_H
#define ANDROID_GUI_BUFFERQUEUECONSUMER_H
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <gui/BufferQueueDefs.h>
#include <gui/IGraphicBufferConsumer.h>
namespace android {
class BufferQueueCore;
class BufferQueueConsumer : public BnGraphicBufferConsumer {
public:
BufferQueueConsumer(const sp<BufferQueueCore>& core);
virtual ~BufferQueueConsumer();
// acquireBuffer attempts to acquire ownership of the next pending buffer in
// the BufferQueue. If no buffer is pending then it returns
// NO_BUFFER_AVAILABLE. If a buffer is successfully acquired, the
// information about the buffer is returned in BufferItem. If the buffer
// returned had previously been acquired then the BufferItem::mGraphicBuffer
// field of buffer is set to NULL and it is assumed that the consumer still
// holds a reference to the buffer.
//
// If expectedPresent is nonzero, it indicates the time when the buffer
// will be displayed on screen. If the buffer's timestamp is farther in the
// future, the buffer won't be acquired, and PRESENT_LATER will be
// returned. The presentation time is in nanoseconds, and the time base
// is CLOCK_MONOTONIC.
virtual status_t acquireBuffer(BufferItem* outBuffer,
nsecs_t expectedPresent, uint64_t maxFrameNumber = 0) override;
// See IGraphicBufferConsumer::detachBuffer
virtual status_t detachBuffer(int slot);
// See IGraphicBufferConsumer::attachBuffer
virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer);
// releaseBuffer releases a buffer slot from the consumer back to the
// BufferQueue. This may be done while the buffer's contents are still
// being accessed. The fence will signal when the buffer is no longer
// in use. frameNumber is used to indentify the exact buffer returned.
//
// If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
// any references to the just-released buffer that it might have, as if it
// had received a onBuffersReleased() call with a mask set for the released
// buffer.
//
// Note that the dependencies on EGL will be removed once we switch to using
// the Android HW Sync HAL.
virtual status_t releaseBuffer(int slot, uint64_t frameNumber,
const sp<Fence>& releaseFence, EGLDisplay display,
EGLSyncKHR fence);
// connect connects a consumer to the BufferQueue. Only one
// consumer may be connected, and when that consumer disconnects the
// BufferQueue is placed into the "abandoned" state, causing most
// interactions with the BufferQueue by the producer to fail.
// controlledByApp indicates whether the consumer is controlled by
// the application.
//
// consumerListener may not be NULL.
virtual status_t connect(const sp<IConsumerListener>& consumerListener,
bool controlledByApp);
// disconnect disconnects a consumer from the BufferQueue. All
// buffers will be freed and the BufferQueue is placed in the "abandoned"
// state, causing most interactions with the BufferQueue by the producer to
// fail.
virtual status_t disconnect();
// getReleasedBuffers sets the value pointed to by outSlotMask to a bit mask
// indicating which buffer slots have been released by the BufferQueue
// but have not yet been released by the consumer.
//
// This should be called from the onBuffersReleased() callback.
virtual status_t getReleasedBuffers(uint64_t* outSlotMask);
// setDefaultBufferSize is used to set the size of buffers returned by
// dequeueBuffer when a width and height of zero is requested. Default
// is 1x1.
virtual status_t setDefaultBufferSize(uint32_t width, uint32_t height);
// see IGraphicBufferConsumer::setMaxBufferCount
virtual status_t setMaxBufferCount(int bufferCount);
// setMaxAcquiredBufferCount sets the maximum number of buffers that can
// be acquired by the consumer at one time (default 1). This call will
// fail if a producer is connected to the BufferQueue.
virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers);
// setConsumerName sets the name used in logging
virtual void setConsumerName(const String8& name);
// setDefaultBufferFormat allows the BufferQueue to create
// GraphicBuffers of a defaultFormat if no format is specified
// in dequeueBuffer. The initial default is HAL_PIXEL_FORMAT_RGBA_8888.
virtual status_t setDefaultBufferFormat(PixelFormat defaultFormat);
// setDefaultBufferDataSpace allows the BufferQueue to create
// GraphicBuffers of a defaultDataSpace if no data space is specified
// in queueBuffer.
// The initial default is HAL_DATASPACE_UNKNOWN
virtual status_t setDefaultBufferDataSpace(
android_dataspace defaultDataSpace);
// setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
// These are merged with the bits passed to dequeueBuffer. The values are
// enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
virtual status_t setConsumerUsageBits(uint32_t usage);
// setTransformHint bakes in rotation to buffers so overlays can be used.
// The values are enumerated in window.h, e.g.
// NATIVE_WINDOW_TRANSFORM_ROT_90. The default is 0 (no transform).
virtual status_t setTransformHint(uint32_t hint);
// Retrieve the sideband buffer stream, if any.
virtual sp<NativeHandle> getSidebandStream() const;
// See IGraphicBufferConsumer::discardFreeBuffers
virtual status_t discardFreeBuffers() override;
// dump our state in a String
virtual void dump(String8& result, const char* prefix) const;
// Functions required for backwards compatibility.
// These will be modified/renamed in IGraphicBufferConsumer and will be
// removed from this class at that time. See b/13306289.
virtual status_t releaseBuffer(int buf, uint64_t frameNumber,
EGLDisplay display, EGLSyncKHR fence,
const sp<Fence>& releaseFence) {
return releaseBuffer(buf, frameNumber, releaseFence, display, fence);
}
virtual status_t consumerConnect(const sp<IConsumerListener>& consumer,
bool controlledByApp) {
return connect(consumer, controlledByApp);
}
virtual status_t consumerDisconnect() { return disconnect(); }
// End functions required for backwards compatibility
private:
sp<BufferQueueCore> mCore;
// This references mCore->mSlots. Lock mCore->mMutex while accessing.
BufferQueueDefs::SlotsType& mSlots;
// This is a cached copy of the name stored in the BufferQueueCore.
// It's updated during setConsumerName.
String8 mConsumerName;
}; // class BufferQueueConsumer
} // namespace android
#endif
| [
"[email protected]"
] | |
ce30b905e6e77160dd25a2d32e656640ac590b16 | 42a072d3c53cd78c1ce82b974442d998298284cc | /libalgo/source/algorithms/graticule2/Graticule.hpp | caec8268994eafe39debabf4dc74318dda294a9f | [] | no_license | bayertom/detectproj | b359991e2457aa91cb8adf22b585215f768ccf12 | 1ba138ae9a1541ab504e000d5961a4ca3c5cec51 | refs/heads/master | 2021-01-23T03:05:33.525489 | 2017-01-02T00:06:41 | 2017-01-02T00:06:41 | 19,872,193 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,266 | hpp | // Description: Create projection graticule given by the lat/lon intervals
// Copyright (c) 2015 - 2016
// Tomas Bayer
// Charles University in Prague, Faculty of Science
// [email protected]
// 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 3 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, see <http://www.gnu.org/licenses/>.
// 2
#ifndef Graticule_HPP
#define Graticule_HPP
#include <math.h>
#include <algorithm>
#include <iterator>
#include "libalgo/source/structures/point/Point3DCartesian.h"
#include "libalgo/source/algorithms/round/Round.h"
#include "libalgo/source/exceptions/MathException.h"
template <typename T>
void Graticule::createGraticule ( const std::shared_ptr <Projection <T> > proj, const TInterval<T> lat_extent, const TInterval<T> lon_extent, const T lat_step, const T lon_step, const T d_lat, const T d_lon, const T alpha, TVector <Meridian <T> > &meridians, TVector2D <Point3DCartesian <T> > & meridians_proj, TVector <Parallel <T> > ¶llels, TVector2D <Point3DCartesian <T> > ¶llels_proj )
{
//Compute graticule given by meridians and parallels
TInterval <T> lat_interval_part, lon_interval_part;
//Parameters of the projection
const T latp = proj->getCartPole().getLat();
const T lonp = proj->getCartPole().getLon();
const T lon0 = proj->getLon0();
//Get size of the interval
const T lat_interval_width = lat_extent.max - lat_extent.min;
const T lon_interval_width = lon_extent.max - lon_extent.min;
//Generate meridians and parallels
if ( lat_step <= lat_interval_width || lon_step <= lon_interval_width )
{
//Create lat and lon intervals to avoid basic singular points
TList <TInterval<T>> lat_intervals, lon_intervals;
createLatIntervals ( lat_extent, latp, lat_intervals );
const T lon_break = CartTransformation::redLon0(lonp, -lon0);
createLonIntervals(lon_extent, lon_break, lon_intervals);
//Process all meridians and parallels: automatic detection of additional singular points
unsigned int split_amount = 0;
//Process all lat intervals
for ( typename TList <TInterval<T>>::iterator i_lat_intervals = lat_intervals.begin(); i_lat_intervals != lat_intervals.end(); i_lat_intervals ++ )
{
//std::cout << "lat: <" << i_lat_intervals->min << ", " << i_lat_intervals->max << "> \n";
//Process all lon intervals
for ( typename TList <TInterval<T>>::iterator i_lon_intervals = lon_intervals.begin() ; i_lon_intervals != lon_intervals.end(); )
{
//std::cout << " lon: <" << i_lon_intervals->min << ", " << i_lon_intervals->max << "> \n";
//Create temporary meridians and parallels
TVector <Meridian <T> > meridians_temp;
TVector <Parallel <T> > parallels_temp;
TVector2D <Point3DCartesian<T> > meridians_temp_proj, parallels_temp_proj;
//Compute meridians and parallels
T lat_error = 0.0, lon_error = 0.0;
try
{
//Compute meridians and parallels
createMeridians ( proj, *i_lat_intervals, *i_lon_intervals, lon_step, d_lat, alpha, meridians_temp, meridians_temp_proj, lat_error, lon_error );
createParallels(proj, *i_lat_intervals, *i_lon_intervals, lat_step, d_lon, alpha, parallels_temp, parallels_temp_proj, lat_error, lon_error);
//Copy temporary meridians and parallels to the output data structure
std::copy(meridians_temp.begin(), meridians_temp.end(), std::inserter(meridians, meridians.begin()));
std::copy(parallels_temp.begin(), parallels_temp.end(), std::inserter(parallels, parallels.begin()));
//Copy temporary projected meridians and parallels to the output data structure
std::copy(meridians_temp_proj.begin(), meridians_temp_proj.end(), std::inserter(meridians_proj, meridians_proj.begin()));
std::copy(parallels_temp_proj.begin(), parallels_temp_proj.end(), std::inserter(parallels_proj, parallels_proj.begin()));
//Increment lon intervals only if computation was successful
i_lon_intervals ++;
}
//Exception
catch ( MathException <T> &error )
{
//Too many splits, projection is suspected, stop computations
if ( split_amount > 100 )
{
meridians.clear(); parallels.clear();
meridians_proj.clear(); parallels_proj.clear();
return;
}
//Empty lat interval, delete
if (fabs((*i_lat_intervals).max - (*i_lat_intervals).min) < 10 * GRATICULE_LAT_LON_SHIFT)
{
i_lat_intervals = lat_intervals.erase(i_lat_intervals);
++i_lat_intervals;
}
//Lat value is lower bound: shift lower bound
else if ((fabs((*i_lat_intervals).min - lat_error) < 2 * GRATICULE_LAT_LON_SHIFT) && (fabs((*i_lat_intervals).max - (*i_lat_intervals).min) > 10 * GRATICULE_LAT_LON_SHIFT))
{
(*i_lat_intervals).min += 2 * GRATICULE_LAT_LON_SHIFT;
}
//Lat value is upper bound: shift upper bound
else if ((fabs((*i_lat_intervals).max - lat_error) < 2 * GRATICULE_LAT_LON_SHIFT) && (fabs((*i_lat_intervals).max - (*i_lat_intervals).min) > 10 * GRATICULE_LAT_LON_SHIFT))
{
(*i_lat_intervals).max -= 2 * GRATICULE_LAT_LON_SHIFT;
}
//Lat value inside interval: split intervals
else if ((((*i_lat_intervals).min) < lat_error) && ((*i_lat_intervals).max > lat_error))
{
splitIntervals(lat_intervals, i_lat_intervals, lat_error);
//Increment split amount
split_amount++;
}
//Empty lon interval, delete
if (fabs((*i_lon_intervals).max - (*i_lon_intervals).min) < 10 * GRATICULE_LAT_LON_SHIFT)
{
i_lon_intervals = lon_intervals.erase(i_lon_intervals);
++i_lon_intervals;
}
//Lon value is lower bound : shift lower bound
else if ((fabs((*i_lon_intervals).min - lon_error) < 2 *GRATICULE_LAT_LON_SHIFT) && (fabs((*i_lon_intervals).max - (*i_lon_intervals).min) > 10 * GRATICULE_LAT_LON_SHIFT))
{
(*i_lon_intervals).min += 2 * GRATICULE_LAT_LON_SHIFT;
}
//Lon value is upper bound: shift upper bound
else if ((fabs((*i_lon_intervals).max - lon_error) < 2 * GRATICULE_LAT_LON_SHIFT) && (fabs((*i_lon_intervals).max - (*i_lon_intervals).min) > 10 * GRATICULE_LAT_LON_SHIFT))
{
(*i_lon_intervals).max -= 2 * GRATICULE_LAT_LON_SHIFT;
}
//Lon value inside interval: split intervals
else if (((( *i_lon_intervals ).min ) < lon_error ) && (( *i_lon_intervals ).max > lon_error ))
{
splitIntervals ( lon_intervals, i_lon_intervals, lon_error );
//Increment split amount
split_amount++;
}
//std::cout << (*i_lat_intervals).min << " " << (*i_lat_intervals).max << '\n';
//std::cout << (*i_lon_intervals).min << " " << (*i_lon_intervals).max << '\n';
}
//Other than math error: error in equation or in parser
catch ( Exception &error )
{
//Clear meridians and parallels
meridians.clear(); parallels.clear();
return;
}
}
}
}
}
template <typename T>
void Graticule:: createLatIntervals ( const TInterval <T> &lat_extent, const T latp, TList <TInterval<T>> &lat_intervals )
{
//Split the geographic extent into several sub-intervals
TInterval <T> lat_interval_part;
//First lat interval ( -90, latp )
lat_interval_part.min = std::max ( MIN_LAT, lat_extent.min );
lat_interval_part.max = std::min ( latp, lat_extent.max );
//Test interval and add to the list
if ( lat_interval_part.max > lat_interval_part.min )
lat_intervals.push_back ( lat_interval_part );
//Second lat interval ( latp, 90 )
lat_interval_part.min = std::max ( latp, lat_extent.min );
lat_interval_part.max = std::min ( lat_extent.max, MAX_LAT );
//Test interval and add to the list
if ( lat_interval_part.max > lat_interval_part.min )
lat_intervals.push_back ( lat_interval_part );
}
template <typename T>
void Graticule::createLonIntervals ( const TInterval <T> &lon_extent, const T lonp, TList <TInterval<T>> &lon_intervals )
{
//Split the geographic extent into several sub-intervals
TInterval <T> lon_interval_part;
//Split given interval into sub intervals: lonp >=0
if ( lonp >= 0 )
{
//First interval <-180, lonp - 180)
lon_interval_part.min = std::max ( MIN_LON, lon_extent.min );
lon_interval_part.max = std::min ( lonp - 180.0, lon_extent.max );
//Test first interval and add to the list
if ( lon_interval_part.max > lon_interval_part.min )
lon_intervals.push_back ( lon_interval_part );
//Second interval (lonp - 180, lonp>
lon_interval_part.min = std::max ( lonp - 180.0, lon_extent.min );
lon_interval_part.max = std::min ( lonp, lon_extent.max );
//Test second interval and add to the list
if ( lon_interval_part.max > lon_interval_part.min )
lon_intervals.push_back ( lon_interval_part );
//Third interval (lonp, MAX_LON>
lon_interval_part.min = std::max ( lonp, lon_extent.min );
lon_interval_part.max = std::min ( MAX_LON, lon_extent.max );
//Test third interval and add to the list
if ( lon_interval_part.max > lon_interval_part.min )
lon_intervals.push_back ( lon_interval_part );
}
//Split given interval into sub intervals: lonp < 0
else
{
//First interval <-180, lonp >
lon_interval_part.min = std::max ( MIN_LON, lon_extent.min );
lon_interval_part.max = std::min ( lonp, lon_extent.max );
//Test first interval and add to the list
if ( lon_interval_part.max > lon_interval_part.min )
lon_intervals.push_back ( lon_interval_part );
//Second interval <lonp, lonp + 180>
lon_interval_part.min = std::max ( lonp, lon_extent.min );
lon_interval_part.max = std::min ( lonp + 180.0, lon_extent.max );
//Test second interval and add to the list
if ( lon_interval_part.max > lon_interval_part.min )
lon_intervals.push_back ( lon_interval_part );
//Third interval (lonp + 180, 180>
lon_interval_part.min = std::max ( lonp + 180.0, lon_extent.min );
lon_interval_part.max = std::min ( MAX_LON, lon_extent.max );
//Test third interval and add to the list
if ( lon_interval_part.max > lon_interval_part.min )
lon_intervals.push_back ( lon_interval_part );
}
}
template <typename T>
void Graticule::splitIntervals ( TList <TInterval<T>> &intervals, typename TList <TInterval<T>>::iterator i_intervals, const T error )
{
//Split one interval in 2
const T max_val = ( *i_intervals ).max;
//Resize old interval <min, max> to <min, error)
( *i_intervals ).max = error;
//Create new interval (error, max>
TInterval <T> interval_temp{ error, max_val };
//Add the new interval to the list
intervals.insert ( i_intervals, interval_temp );
//Move iterator to the previous item
i_intervals--;
}
template <typename T, typename Point>
void Graticule::createMeridians (const std::shared_ptr <Projection <T> > proj, const TInterval<T> &lat_interval, const TInterval<T> &lon_interval, const T lon_step, const T d_lat, const T alpha, TVector <Meridian <T> > &meridians, TVector2D <Point> & meridians_proj, T &lat_error, T &lon_error )
{
//Set start value of the longitude as a multiplier of lon_step
const T lon_start = Round::roundToMultipleFloor(lon_interval.min, lon_step) + lon_step;
const T lon_end = Round::roundToMultipleCeil(lon_interval.max, lon_step) - lon_step;
T lon = std::max(std::min(lon_interval.min + GRATICULE_LAT_LON_SHIFT, MAX_LON), MIN_LON);
try
{
//Create first meridian (lower bound of the interval, not lower than MIN_LON)
Meridian <T> m1(lon, lat_interval, d_lat, GRATICULE_LAT_LON_SHIFT, GRATICULE_LAT_LON_SHIFT);
TVector <Point> m1_proj;
m1.project(proj, alpha, m1_proj);
//Add meridian and projected meridian to the list
meridians.push_back(m1);
meridians_proj.push_back(m1_proj);
//Create intermediate meridians
for (lon = lon_start; lon <= lon_end; lon += lon_step)
{
Meridian <T> m2(lon, lat_interval, d_lat, GRATICULE_LAT_LON_SHIFT, GRATICULE_LAT_LON_SHIFT);
TVector <Point> m2_proj;
m2.project(proj, alpha, m2_proj);
//Add meridian and projected meridian to the list
meridians.push_back(m2);
meridians_proj.push_back(m2_proj);
}
//Create last meridian (upper bound of the interval, not higher than MAX_LON)
lon = std::max(std::min(lon_interval.max - GRATICULE_LAT_LON_SHIFT, MAX_LON), MIN_LON);
Meridian <T> m3(lon, lat_interval, d_lat, GRATICULE_LAT_LON_SHIFT, GRATICULE_LAT_LON_SHIFT);
TVector <Point> m3_proj;
m3.project(proj, alpha, m3_proj);
//Add meridian and projected meridian to the list
meridians.push_back(m3);
meridians_proj.push_back(m3_proj);
}
//Throw math exception: get error values
catch (MathException <T> &error)
{
//Get possible error values
lat_error = error.getArg();
lon_error = lon;
//Throw exception
throw;
}
//Throw other exception: error in parser or incorrect equation
catch (Exception &error)
{
throw;
}
}
template <typename T, typename Point>
void Graticule::createParallels ( const std::shared_ptr <Projection <T> > proj, const TInterval<T> &lat_interval, const TInterval<T> &lon_interval, const T lat_step, const T d_lon, const T alpha, TVector <Parallel <T> > ¶llels, TVector2D <Point> & parallels_proj, T &lat_error, T &lon_error )
{
//Set start value of the longitude as a multiplier of lon_step
const T lat_start = Round::roundToMultipleFloor(lat_interval.min, lat_step) + lat_step;
const T lat_end = Round::roundToMultipleCeil(lat_interval.max, lat_step) - lat_step;
T lat = std::max(std::min(lat_interval.min + GRATICULE_LAT_LON_SHIFT, MAX_LAT), MIN_LAT);
try
{
//Create first parallel (lower bound of the interval, nor lower than MIN_LAT)
Parallel <T> p1(lat, lon_interval, d_lon, GRATICULE_LAT_LON_SHIFT, GRATICULE_LAT_LON_SHIFT);
TVector <Point> p1_proj;
p1.project(proj, alpha, p1_proj);
//Add parallel and projected parallel to the list
parallels.push_back(p1);
parallels_proj.push_back(p1_proj);
//Create intermediate parallels
for (lat = lat_start; lat <= lat_end; lat += lat_step)
{
Parallel <T> p2(lat, lon_interval, d_lon, GRATICULE_LAT_LON_SHIFT, GRATICULE_LAT_LON_SHIFT);
TVector <Point> p2_proj;
p2.project(proj, alpha, p2_proj);
//Add parallel and projected parallel to the list
parallels.push_back(p2);
parallels_proj.push_back(p2_proj);
}
//Create last parallel (upper bound of the interval, not greater than MAX_LAT)
lat = std::max(std::min(lat_interval.max - GRATICULE_LAT_LON_SHIFT, MAX_LAT), MIN_LAT);
Parallel <T> p3(lat, lon_interval, d_lon, GRATICULE_LAT_LON_SHIFT, GRATICULE_LAT_LON_SHIFT);
TVector <Point> p3_proj;
p3.project(proj, alpha, p3_proj);
//Add parallel and projected parallel to the list
parallels.push_back(p3);
parallels_proj.push_back(p3_proj);
}
//Throw math exception: get error values
catch (MathException <T> &error)
{
//Get possible error values
lat_error = lat;
lon_error = error.getArg();
//Throw exception
throw;
}
//Throw other exception: error in parser or incorrect equation
catch (Exception &error)
{
throw;
}
}
#endif
| [
"[email protected]"
] | |
24675de0b4515b4d9a346a0bd6147625f579586a | 328aaaa971efddfd240f944734ce4392febd6a5c | /Sort/bubble.cpp | 9fcb1213113e3320045ed5e02db1f5b5a312893c | [] | no_license | donggoolosori/data_structure | 8aa316d807415038fd054054ee9c6b4fc53fd478 | 4a7868b53f2db59659fb55291a63e4b90966cc54 | refs/heads/master | 2023-06-11T13:18:51.882152 | 2021-07-06T11:44:53 | 2021-07-06T11:44:53 | 370,371,744 | 1 | 0 | null | 2021-05-24T14:17:07 | 2021-05-24T14:00:31 | C++ | UTF-8 | C++ | false | false | 523 | cpp | #include <iostream>
#include <vector>
using namespace std;
// 오름차순 버블 정렬
void bubble_sort(vector<int> &arr) {
int size = arr.size();
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - 1 - i; j++) {
if (arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]);
}
}
}
// 모든 원소 출력
void print(vector<int> &arr) {
for (const int &n : arr) cout << n << ' ';
}
int main() {
vector<int> arr = {9, 7, 3, 5, 1, 10, 2, 6, 8, 4};
bubble_sort(arr);
print(arr);
return 0;
} | [
"[email protected]"
] | |
7bf699fb10e7071c26c03c3030d6db22d8bb9032 | 8044628c57fedd254faca3aa94ee92f85b4692f5 | /Src/Eni/Terminal/TerminalNrf.h | b3c2d2a6ed49c790489d050e8100c40469351e2c | [
"MIT"
] | permissive | vlad230596/Eni | 8a54467f14d804b29c5a59dbca3a2836b72b3b8e | a41c956630cc030f6b24dce1c9d1fe1658defe90 | refs/heads/master | 2023-01-19T19:00:38.970873 | 2023-01-14T00:18:11 | 2023-01-14T00:18:11 | 105,810,151 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 189 | h |
#include <EniConfig.h>
#if defined(ENI_TERMINAL)
#include <cstdint>
#include <cstring>
#include "Terminal.h"
namespace Eni::Terminal {
bool init(uint32_t nativePinId);
}
#endif
| [
"[email protected]"
] | |
613dfc9bcfd38f30570c63dbbe8afb21f9b11117 | ca1cc40382fb978b3e1682319da19102b8b4209a | /src/scroller.cpp | 1ad10d13147046232270df58b53398fe296d92dc | [
"MIT"
] | permissive | Kampbell/git-tui | 57b98d8a13357815714df85fe1448c3efec6a2c3 | 125d11d720debaca430322259d2f3756be521594 | refs/heads/master | 2023-05-24T15:34:49.857526 | 2021-06-04T13:39:02 | 2021-06-04T13:39:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,403 | cpp | #include "scroller.hpp"
#include <algorithm> // for max, min
#include <ftxui/component/component_base.hpp> // for ComponentBase
#include <ftxui/component/event.hpp> // for Event, Event::ArrowDown, Event::ArrowUp
#include <memory> // for shared_ptr, allocator, __shared_ptr_access
#include <utility> // for move
#include "ftxui/component/component.hpp" // for Component, Make
#include "ftxui/component/mouse.hpp" // for Mouse, Mouse::WheelDown, Mouse::WheelUp
#include "ftxui/dom/elements.hpp" // for operator|, text, Element, size, vbox, EQUAL, HEIGHT, dbox, reflect, focus, inverted, nothing, select, yflex, yframe
#include "ftxui/dom/node.hpp" // for Node
#include "ftxui/dom/requirement.hpp" // for Requirement
#include "ftxui/screen/box.hpp" // for Box
namespace ftxui {
class ScrollerBase : public ComponentBase {
public:
ScrollerBase(Component child) { Add(child); }
private:
Element Render() final {
auto focused = Focused() ? focus : ftxui::select;
auto style = Focused() ? inverted : nothing;
Element background = ComponentBase::Render();
background->ComputeRequirement();
size_ = background->requirement().min_y;
return dbox({
std::move(background),
vbox({
text(L"") | size(HEIGHT, EQUAL, selected_),
text(L"") | style | focused,
}),
}) |
yframe | yflex | reflect(box_);
}
bool OnEvent(Event event) final {
if (event.is_mouse() && box_.Contain(event.mouse().x, event.mouse().y))
TakeFocus();
int selected_old = selected_;
if (event == Event::ArrowUp || event == Event::Character('k') ||
(event.is_mouse() && event.mouse().button == Mouse::WheelUp)) {
selected_--;
}
if ((event == Event::ArrowDown || event == Event::Character('j') ||
(event.is_mouse() && event.mouse().button == Mouse::WheelDown))) {
selected_++;
}
selected_ = std::max(0, std::min(size_ - 1, selected_));
return selected_old != selected_;
}
int selected_ = 0;
int size_ = 0;
Box box_;
};
Component Scroller(Component child) {
return Make<ScrollerBase>(std::move(child));
}
} // namespace ftxui
// Copyright 2021 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
| [
"[email protected]"
] | |
3c6b007901a219067a62c1df8d65f94ce557a104 | 4cdba7c6034867350543e7bd99b689ae3eda6652 | /lab/lab5/lab5/lab5p1.cpp | 15d33fe3823ef5add37a98833800e31c914236ba | [] | no_license | ShaocongDong/CS2106-Operating-System | b02855e1aae45073bfd57d2808e2830c326d4014 | 993681e142ccb4cecfde5b1d7baaf0d128ad7408 | refs/heads/master | 2020-03-29T05:41:42.726024 | 2018-04-27T02:06:33 | 2018-04-27T02:06:33 | 149,593,746 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,314 | cpp | #include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include "buffer.h"
#define NUM_THREADS 32
TBuffer buffer;
void *serialSendThread(void *p)
{
// This thread simulates sending a character over a 115200 bps serial link, e.g.
// e.g. over a 433 MHz radio to a remote system. 115200 bps transmission
// transmits one character every 70 microseconds.
while(1)
{
char data[ENTRY_SIZE];
int len = deq(&buffer, data);
if(len >= 0)
{
int i;
for(i=0; i<len; i++)
{
// This printf simulates a send over a 115200 bps data link
printf("%c", data[i]);
// Sleep 70 microseconds for data to be sent out by the serial link
usleep(70);
}
}
}
}
void *senderThreads(void *p)
{
int threadNum = (long) p;
int count=0;
while(1)
{
char data[ENTRY_SIZE];
sprintf(data, "Thread %d entry %d\n", threadNum, count);
enq(&buffer, data, strlen(data)+1);
count++;
}
}
int main()
{
pthread_t _thr[NUM_THREADS];
pthread_t _serialSend;
initBuffer(&buffer);
int i;
pthread_create(&_serialSend, NULL, serialSendThread, NULL);
pthread_detach(_serialSend);
for(i=0; i<NUM_THREADS;i++)
{
pthread_create(&_thr[i], NULL, senderThreads, (void *) i);
pthread_detach(_thr[i]);
}
// Infinite loop to prevent parent from exiting
while(1);
}
| [
"[email protected]"
] | |
db69087e31875ebe7b218dbd49a935dff5ad6af8 | 85ff5e5db7365c431720b6d79808795d371d6d42 | /routines/level1/dot.cc | 6ecffc8a0bbf72c2c95cb3b93833bfba79a6ce65 | [
"MIT"
] | permissive | vgire/nblas | 8b47b304de6a4c348d5896d1822501827ee5198b | eda6cd1cafaf9a56c5184f1e1ce43f8858b8e01a | refs/heads/master | 2021-01-17T10:00:12.990955 | 2016-08-26T14:19:47 | 2016-08-26T14:19:47 | 66,596,639 | 0 | 0 | null | 2016-08-25T22:08:39 | 2016-08-25T22:08:38 | null | UTF-8 | C++ | false | false | 1,063 | cc | #include "cblas.h"
#include "routines.h"
void ddot(const v8::FunctionCallbackInfo<v8::Value>& info) {
const int n = info[0]->Uint32Value();
const double *x = reinterpret_cast<double*>(info[1].As<v8::Float64Array>()->Buffer()->GetContents().Data());
const int inc_x = info[2]->Uint32Value();
const double *y = reinterpret_cast<double*>(info[3].As<v8::Float64Array>()->Buffer()->GetContents().Data());
const int inc_y = info[4]->Uint32Value();
info.GetReturnValue().Set(
v8::Number::New(info.GetIsolate(), cblas_ddot(n, x, inc_x, y, inc_y))
);
}
void sdot(const v8::FunctionCallbackInfo<v8::Value>& info) {
const int n = info[0]->Uint32Value();
const float *x = reinterpret_cast<float*>(info[1].As<v8::Float32Array>()->Buffer()->GetContents().Data());
const int inc_x = info[2]->Uint32Value();
const float *y = reinterpret_cast<float*>(info[3].As<v8::Float32Array>()->Buffer()->GetContents().Data());
const int inc_y = info[4]->Uint32Value();
info.GetReturnValue().Set(
v8::Number::New(info.GetIsolate(), cblas_sdot(n, x, inc_x, y, inc_y))
);
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.