blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
255b42b24ddfc460044d40b4a00d3ceb98a570ec
|
4f43007f1dc4d2c85fae06b1e94568cd79693307
|
/cat/main.cpp
|
ad9e640556e0b9c832be5a72d843939298203b49
|
[] |
no_license
|
AtMiraz/progra2
|
7bd298058301763751a069e80487f541bc172446
|
409ad0b92f97436b21ec49002fda99a97954ef36
|
refs/heads/master
| 2021-01-18T03:59:59.910782
| 2017-03-23T22:31:18
| 2017-03-23T22:31:18
| 85,772,651
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,132
|
cpp
|
main.cpp
|
#include "./includes/bootscat.h"
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
// Father class.
cat fatherCat = cat();
fatherCat.setName("IDK");
fatherCat.setColour("Brown");
fatherCat.setFood("cat's food lmao");
fatherCat.setTailLength(15);
bootscat maybeACat = bootscat();
// Inherited class.
maybeACat.setName("This an inherited name");
maybeACat.setColour("This is an inherited colour");
maybeACat.setFood("This is an inherited food");
maybeACat.setTailLength(20);
maybeACat.setBootBrand("stuff aasdasd");
maybeACat.setBootSize("12");
// Printing all the stuff
cout << "Father's cat data." << '\n';
cout << fatherCat.getName();
cout << '\n';
cout << fatherCat.getColour();
cout << '\n';
cout << fatherCat.getFood();
cout << '\n';
cout << fatherCat.getTailLength();
cout << "Children's data";
cout << '\n';
cout << maybeACat.getName();
cout << '\n';
cout << maybeACat.getColour();
cout << '\n';
cout << maybeACat.getFood();
cout << '\n';
cout << maybeACat.getBootBrand();
cout << '\n';
cout << maybeACat.getBootSize();
cout << '\n';
return 0;
}
|
d2c1cde215cf33dfac9b8327efa264274236f481
|
26d0a3e00d1e26765262ef51a94801d333034b28
|
/Framework/SM4topsSS3L/Root/LeptonVectorDecorator.cxx
|
5a87c2b3e40033fab96ef804cdb16b051ef6d1d1
|
[] |
no_license
|
sen-sourav/common-framework
|
f0d4a61ccda53dfca4adf649c93a579de3df8619
|
474383ba7f30d19a2836e19d8bc028b7d1f83f9a
|
refs/heads/master
| 2020-04-01T06:24:09.210670
| 2019-06-06T17:37:47
| 2019-06-06T17:37:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,013
|
cxx
|
LeptonVectorDecorator.cxx
|
#include "SM4topsSS3L/LeptonVectorDecorator.h"
#include <algorithm>
#include <sstream>
#include "TopEvent/EventTools.h"
#include "AsgTools/AsgTool.h"
#include "AsgTools/ToolHandle.h"
#include "../TTHbbAnalysis/TTHbbLeptonic/TTHbbLeptonic/EventSaverHelper.h"
#include "../TTHbbAnalysis/TTHbbObjects/TTHbbObjects/Event.h"
namespace SM4topsSS3L {
LeptonVectorDecorator::LeptonVectorDecorator(std::string params,
std::shared_ptr<top::TopConfig> config) {
auto* esh = EventSaverHelper::get();
m_indices = {0, 1, 2, 3};
std::vector<std::pair<std::string, TTHbb::DecorationType>> variables = {
std::make_pair("pt", TTHbb::DecorationType::Float),
std::make_pair("eta", TTHbb::DecorationType::Float),
std::make_pair("phi", TTHbb::DecorationType::Float),
std::make_pair("e", TTHbb::DecorationType::Float),
std::make_pair("charge", TTHbb::DecorationType::Float),
std::make_pair("pdgId", TTHbb::DecorationType::Int),
std::make_pair("isTight", TTHbb::DecorationType::Char),
std::make_pair("origIndex", TTHbb::DecorationType::Int)};
for (auto var : variables) {
for (auto ind : m_indices) {
esh->addVariableToBeSaved(getVarName(ind, var.first), var.second, false,
"LeptonVectorDecorator");
}
}
}
bool LeptonVectorDecorator::apply(const top::Event& event) const {
if (!event.m_info->isAvailable<std::shared_ptr<TTHbb::Event>>("TTHbbEventVariables")) {
std::cout << "LeptonVectorDecorator: TTHbbEventVariables (TTHbb::Event*) "
"object not found"
<< std::endl;
std::cout << "------> aborting :-( " << std::endl;
abort();
}
std::shared_ptr<TTHbb::Event> tthevt =
event.m_info->auxdecor<std::shared_ptr<TTHbb::Event>>("TTHbbEventVariables");
std::vector<Lepton> leptons = {};
for (unsigned int iel = 0; iel < event.m_electrons.size(); iel++) {
if (event.m_electrons.at(iel)->auxdataConst<char>("passPreORSelection")) {
struct Lepton lep = {event.m_electrons.at(iel)->pt(),
event.m_electrons.at(iel)->eta(),
event.m_electrons.at(iel)->phi(),
event.m_electrons.at(iel)->e(),
event.m_electrons.at(iel)->charge(),
11,
static_cast<char>(1),
iel};
leptons.emplace_back(lep);
}
}
for (unsigned int imu = 0; imu < event.m_muons.size(); imu++) {
if (event.m_muons.at(imu)->auxdataConst<char>("passPreORSelection")) {
struct Lepton lep = {event.m_muons.at(imu)->pt(),
event.m_muons.at(imu)->eta(),
event.m_muons.at(imu)->phi(),
event.m_muons.at(imu)->e(),
event.m_muons.at(imu)->charge(),
13,
static_cast<char>(1),
imu};
leptons.emplace_back(lep);
}
}
if (!leptons.empty()) {
std::sort(leptons.begin(), leptons.end(),
[](Lepton const& a, Lepton const& b) { return a.pt > b.pt; });
}
for (auto& ind : m_indices) {
if (ind < leptons.size()) {
tthevt->floatVariable(getVarName(ind, "pt")) = leptons[ind].pt;
tthevt->floatVariable(getVarName(ind, "eta")) = leptons[ind].eta;
tthevt->floatVariable(getVarName(ind, "phi")) = leptons[ind].phi;
tthevt->floatVariable(getVarName(ind, "e")) = leptons[ind].e;
tthevt->floatVariable(getVarName(ind, "charge")) = leptons[ind].charge;
tthevt->intVariable(getVarName(ind, "pdgId")) = leptons[ind].pdgId;
tthevt->charVariable(getVarName(ind, "isTight")) = leptons[ind].isTight;
tthevt->intVariable(getVarName(ind, "origIndex")) = leptons[ind].origIndex;
} else {
tthevt->floatVariable(getVarName(ind, "pt")) = -std::numeric_limits<float>::max();
tthevt->floatVariable(getVarName(ind, "eta")) = -std::numeric_limits<float>::max();
tthevt->floatVariable(getVarName(ind, "phi")) = -std::numeric_limits<float>::max();
tthevt->floatVariable(getVarName(ind, "e")) = -std::numeric_limits<float>::max();
tthevt->floatVariable(getVarName(ind, "charge")) = -std::numeric_limits<float>::max();
tthevt->intVariable(getVarName(ind, "pdgId")) = -std::numeric_limits<int>::max();
tthevt->charVariable(getVarName(ind, "isTight")) = -std::numeric_limits<char>::max();
tthevt->intVariable(getVarName(ind, "origIndex")) = -std::numeric_limits<int>::max();
}
}
return true;
}
std::string LeptonVectorDecorator::name() const { return "SM4topsSS3LLeptonVectorDecorator"; }
std::string LeptonVectorDecorator::getVarName(const unsigned int& index,
const std::string& varName) const {
return std::string("lep_") + std::to_string(index) + std::string("_") + varName;
}
} // namespace SM4topsSS3L
|
6b70156f4f229dbbe0802dcd6424f05da4aea1c5
|
b6bc85c6cc86a1ad9b8b06239762f79772c8db7e
|
/cpp.func.handbook/ch05/5-3-1-10.cpp
|
58313cd7451c6d24c9b967fa741badf232ebe76b
|
[] |
no_license
|
hexu1985/cpp_book_code
|
bacdfb7b9c1abff446f18dee33e8df451d18ec45
|
101c20ff87b89402262a8c74482871968cfc0464
|
refs/heads/master
| 2021-08-20T04:46:03.274538
| 2021-06-07T07:08:45
| 2021-06-07T07:10:11
| 150,828,290
| 0
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 198
|
cpp
|
5-3-1-10.cpp
|
#include <string>
#include <iostream>
using namespace std;
int main( )
{
string str("abcd");
const char *ptr;
ptr=str.data();
cout<<"ptr = "<<ptr<<endl;
return 0;
}
|
7757bd047307994eec7810c94b08c47085dc972b
|
4bc8b4a8acf86ad9b98fa07b079aa47eb0e7d6d5
|
/machinelearning/study/lintcode/C++_solutions/C++_solutions/C++_solutions/Jewels_and_Stones.cpp
|
1845e17647d93e9a64ee0f29eff1ae345f72dcbb
|
[] |
no_license
|
Arctanxy/learning_notes
|
6aeadc856c30fd0f0d53993fa601210b6010e793
|
8c52e3a927b537c34a9d196cc2eda78251eb6a5a
|
refs/heads/master
| 2021-05-25T09:15:05.548009
| 2020-02-22T12:45:54
| 2020-02-22T12:45:54
| 126,953,925
| 11
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 520
|
cpp
|
Jewels_and_Stones.cpp
|
//https://leetcode.com/problems/jewels-and-stones/description/
#include <iostream>
#include <string.h>
using namespace std;
//最简单的O(N^2)复杂度算法
int numJewelsInStones(char* J, char* S) {
int num = 0;
for (int i = 0; i < strlen(J); i++) {
for (int j = 0; j < strlen(S); j++) {
if (S[j] == J[i]) {
num++;
}
}
}
return num;
}
int main()
{
char J[50], S[50];
cout << "input J";
cin >> J;
cout << "input S";
cin >> S;
cout << endl << numJewelsInStones(J, S);
return 0;
}
|
33dc52f31975648c897ef7c1026ea1175708d6c0
|
5f5c12ec8afd76d4bd4552efed87025bcb42c2ae
|
/AhmiSimulator_v1.1.0/AHMI/Widget/DynamicTexClass.cpp
|
b2407987f4e768186f15397cd160f0ba3179383a
|
[] |
no_license
|
radtek/czy
|
6ec52f38f6228b95f97d54baa635b32b4e4d0147
|
a11cd605a09f403a8cf59176a006891d3f049f71
|
refs/heads/master
| 2021-09-20T18:34:56.319020
| 2018-07-05T08:37:45
| 2018-07-05T08:38:06
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 13,043
|
cpp
|
DynamicTexClass.cpp
|
////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer: AHMI小组成员
//
// Create Date: 2016/03/21
// File Name: CanvasClass.cpp
// Project Name: AHMISimulator
//
// Revision:
// Revision 3.00 - File Created 2016/04/13 by 于春营
// Additional Comments:
//
//
////////////////////////////////////////////////////////////////////////////////
#include "publicInclude.h"
#include "AHMIBasicDefine.h"
#include "aniamtion.h"
#include "DynamicTexClass.h"
#include "drawImmediately_cd.h"
#ifdef AHMI_CORE
extern TagClassPtr TagPtr;
extern DynamicPageClassPtr gPagePtr;
extern u16 WorkingPageID;
//extern QueueHandle_t RefreshQueue;
extern QueueHandle_t ActionInstructionQueue;
//-----------------------------
// 函数名: DynamicTexClass
// 构造函数
// 参数列表:
//
// 备注(各个版本之间的修改):
// 无
//-----------------------------
DynamicTexClass::DynamicTexClass()
{
}
//-----------------------------
// 函数名: ~DynamicTexClass
// 析构函数
// 参数列表:
//
// 备注(各个版本之间的修改):
// 无
//-----------------------------
DynamicTexClass::~DynamicTexClass()
{
}
//-----------------------------
// 函数名: DynamicTexClass::initWidget
// 初始化并绘制该控件,如果是全屏刷新,先根据所绑定的tag刷新该控件,在绘制该控件
// @param WidgetClassPtr p_wptr, //控件指针
// @param u32 *u32p_sourceShift, //sourceb
// @param u8 u8_pageRefresh, //页面刷新
// @param TileBoxClassPtr pTileBox //包围盒
// 备注(各个版本之间的修改):
// 无
//-----------------------------
funcStatus DynamicTexClass::initWidget(
WidgetClassPtr p_wptr, //控件指针
u32 *u32p_sourceShift, //sourcebuffer指针
u8 u8_pageRefresh, //页面刷新
u8 RefreshType , //绘制的动画类型,根据动画类型改变绘制控件的包围盒
TileBoxClassPtr pTileBox, //包围盒
u8 staticTextureEn //是否绘制到静态存储空间
)
{
TagClassPtr bindTag;
ActionTriggerClass tagtrigger;
WidgetClassInterface myWidgetClassInterface;
if((NULL == p_wptr) || (NULL == u32p_sourceShift) || (NULL == pTileBox))
return AHMI_FUNC_FAILURE;
bindTag = &TagPtr[p_wptr->BindTagID];
if(u8_pageRefresh)
{
tagtrigger.mTagPtr = bindTag;
tagtrigger.mInputType = ACTION_TAG_SET_VALUE;
if(widgetCtrl(p_wptr,&tagtrigger,1) == AHMI_FUNC_FAILURE)
return AHMI_FUNC_FAILURE;
}
if(myWidgetClassInterface.drawTexture(p_wptr,u32p_sourceShift,RefreshType,pTileBox,staticTextureEn) == AHMI_FUNC_FAILURE)
return AHMI_FUNC_FAILURE;
return AHMI_FUNC_SUCCESS;
}
//*****************************
//动态纹理
//只有一张纹理,但是有多个Slice
//tag的值代表focusedSlice标号
//WidgetAttr标识:
//15-8 : 保留
//5-7 : 动态纹理的类型:0:多张纹理切换 1:单张纹理旋转 2:单张纹理移动 3:半透明纹理
//4-0 : 控件类型,动态纹理应为0x0
//*****************************
funcStatus DynamicTexClass::widgetCtrl(
WidgetClassPtr p_wptr, //控件指针
ActionTriggerClassPtr ActionPtr,
u8 u8_pageRefresh //页面刷新
)
{
s32 value;
s32 value_temp = 0;
RefreshMsg refreshMsg;
TextureClassPtr texturePtr, preTexturePtr;
u8 movingDir = 0;
u8 dynamicType = 0;
u16 angle = 0;
u32 actionAddr;
s32 sValue;
s32 maxValue;
s32 minValue;
u32 curValue;
s32 lowAlarmValue;
s32 highAlarmValue;
u32 oldValue = 0;
s32 sOldValue = 0;
u16 oldValueinit = 0;
if((NULL == p_wptr) || (NULL == ActionPtr) || NULL == ActionPtr->mTagPtr || NULL == gPagePtr->pBasicTextureList){
ERROR_PRINT("ERROR: for NULL pointer");
return AHMI_FUNC_FAILURE;
}
if( (s16)(p_wptr->WidgetOffsetX) > MAX_WIDTH_AND_HEIGHT ||
(s16)(p_wptr->WidgetOffsetY) > MAX_WIDTH_AND_HEIGHT ||
(s16)(p_wptr->WidgetOffsetX) < -MAX_WIDTH_AND_HEIGHT ||
(s16)(p_wptr->WidgetOffsetY) < -MAX_WIDTH_AND_HEIGHT ||
p_wptr->WidgetWidth > MAX_WIDTH_AND_HEIGHT ||
p_wptr->WidgetHeight > MAX_WIDTH_AND_HEIGHT ||
p_wptr->WidgetWidth == 0 ||
p_wptr->WidgetHeight == 0)
{
ERROR_PRINT("ERROR: when drawing clock widght, the offset\\width\\height exceeds the boundary");
return AHMI_FUNC_FAILURE;
}
dynamicType = (p_wptr->WidgetAttr & DYNAMIC_TYPE_BIT) >> 5;
value = (s32)(ActionPtr->mTagPtr->mValue);
curValue = (p_wptr->CurValueH << 16) + p_wptr->CurValueL;
maxValue = (s32)((p_wptr->MaxValueH << 16) + p_wptr->MaxValueL);
minValue = (s32)((p_wptr->MinValueH << 16) + p_wptr->MinValueL);
lowAlarmValue = (s32)((p_wptr->LowAlarmValueH << 16) + p_wptr->LowAlarmValueL);
highAlarmValue = (s32)((p_wptr->HighAlarmValueH << 16) + p_wptr->HighAlarmValueL);
if(dynamicType == 0) //多张纹理切换
{
if((u32)value > (u32)maxValue)
{
value_temp = value;
value = (u32)maxValue;
}
else if((u32)value < (u32)minValue)
value = (u32)minValue;
if(p_wptr->NumOfLine == 1)
{
texturePtr = &gPagePtr[WorkingPageID].pBasicTextureList[p_wptr->StartNumofTex];
if((u32)value_temp > (u32)value)
texturePtr->mTexAttr &= ~(DRAWING);
else
texturePtr->mTexAttr |= (DRAWING);
preTexturePtr = texturePtr;
}
else if(p_wptr->NumOfLine == 2)
{
if(u8_pageRefresh)
{
p_wptr->PreviousTexturePtrFlag = 0;
texturePtr = &(gPagePtr[WorkingPageID].pBasicTextureList[p_wptr->StartNumofTex]);
preTexturePtr = &(gPagePtr[WorkingPageID].pBasicTextureList[p_wptr->StartNumofTex+1]);
}
else if((p_wptr->PreviousTexturePtrFlag == 0) || (p_wptr->PreviousTexturePtrFlag == 0xCCCC))
{
p_wptr->PreviousTexturePtrFlag = 1;
texturePtr = &(gPagePtr[WorkingPageID].pBasicTextureList[p_wptr->StartNumofTex + 1]);
preTexturePtr = &(gPagePtr[WorkingPageID].pBasicTextureList[p_wptr->StartNumofTex]);
}
else if(p_wptr->PreviousTexturePtrFlag == 1)
{
p_wptr->PreviousTexturePtrFlag = 0;
texturePtr = &(gPagePtr[WorkingPageID].pBasicTextureList[p_wptr->StartNumofTex]);
preTexturePtr = &(gPagePtr[WorkingPageID].pBasicTextureList[p_wptr->StartNumofTex + 1]);
}
}
else
return AHMI_FUNC_FAILURE;
//texturePtr->FocusedSlice = Value;//设置要显示的Slice
//判断平移方向
if(p_wptr->NumOfLine != 1)
{
if((u32)value > curValue)
{
//上移
movingDir = 0;
}
else if((u32)value < curValue)
{
//下移
movingDir = 1;
}
else
{
//不移动
if(u8_pageRefresh == 0)
return AHMI_FUNC_SUCCESS;
}
}
//操作纹理的值
texturePtr->FocusedSlice = (u16)value;
if(u8_pageRefresh)
preTexturePtr->FocusedSlice = (u16)value;
//操作纹理的位置
if(p_wptr->NumOfLine == 2 && !u8_pageRefresh)
{
if(movingDir == 0) //上移
{
texturePtr->OffsetY = (p_wptr->WidgetOffsetY + p_wptr->WidgetHeight) << 4;
preTexturePtr->OffsetY = (p_wptr->WidgetOffsetY) << 4;
}
else if(movingDir == 1)//下移
{
texturePtr->OffsetY = (p_wptr->WidgetOffsetY - p_wptr->WidgetHeight) << 4;
preTexturePtr->OffsetY = (p_wptr->WidgetOffsetY) << 4;
}
}
// if(u8_pageRefresh == 0)
// {
// //更新此控件
//#ifdef STATIC_BUFFER_EN
//#ifdef DEBUG
// ERROR_PRINT("sending the refresh static buffer cmd");
//#endif
// refreshMsg.mElementType = ANIMAITON_REFRESH_STATIC_BUFFER;
// refreshMsg.mElementPtr.pageptr = gPagePtr + WorkingPageID;
// sendToRefreshQueue(&refreshMsg);
//#endif
// }
}
else if(dynamicType == CENTRAL_ROTATE) //单张纹理旋转
{
texturePtr = &gPagePtr[WorkingPageID].pBasicTextureList[p_wptr->StartNumofTex];
sValue = (s32)value;
//value取绝对值
if(sValue < 0)
value = -sValue;
//value计算角度
if(value > 360)
value %= 360;
if(value > maxValue)
value = maxValue;
if(value < minValue)
value = minValue;
//if(sValue < 0)
// angle = p_wptr->DynamicTexMinAngle - value;
//else
// angle = p_wptr->DynamicTexMinAngle + value;
angle = value;
texturePtr[0].RotateAngle = angle * 16;
texturePtr[0].mTexAttr |= TEXTURE_CENTRAL_ROTATE;
texturePtr[0].mTexAttr |= TEXTURE_USING_WIDGET_BOX;
//重新计算包围盒
texturePtr[0].RenewRotateTextureSourceBox();
if(u8_pageRefresh == 0)
{
//更新此控件
if(oldValueinit)
{
oldValue = (p_wptr->OldValueH << 16) + p_wptr->OldValueL;
if(dynamicType == 0)
{
if(p_wptr->EnterLowAlarmAction && oldValue > (u32)lowAlarmValue && (u32)value <= (u32)lowAlarmValue)
{
//进入低值预警
if(p_wptr->EnterLowAlarmAction <= gPagePtr[WorkingPageID].mActionInstructionsSize)
{
actionAddr = (u32)(gPagePtr[WorkingPageID].pActionInstructions + p_wptr->EnterLowAlarmAction);
xQueueSendToBack(ActionInstructionQueue,&actionAddr,portMAX_DELAY);
}
}
else if(p_wptr->LeaveLowAlarmAction && oldValue <= (u32)lowAlarmValue && (u32)value > (u32)lowAlarmValue)
{
//离开低值预警
if(p_wptr->LeaveLowAlarmAction <= gPagePtr[WorkingPageID].mActionInstructionsSize)
{
actionAddr = (u32)(gPagePtr[WorkingPageID].pActionInstructions + p_wptr->LeaveLowAlarmAction);
xQueueSendToBack(ActionInstructionQueue,&actionAddr,portMAX_DELAY);
}
}
if(p_wptr->EnterHighAlarmAction && oldValue < (u32)highAlarmValue && (u32)value >= (u32)highAlarmValue)
{
//进入高值预警
if(p_wptr->EnterHighAlarmAction <= gPagePtr[WorkingPageID].mActionInstructionsSize)
{
actionAddr = (u32)(gPagePtr[WorkingPageID].pActionInstructions + p_wptr->EnterHighAlarmAction);
xQueueSendToBack(ActionInstructionQueue,&actionAddr,portMAX_DELAY);
}
}
else if(p_wptr->LeaveHighAlarmAction && oldValue >= (u32)highAlarmValue && (u32)value < (u32)highAlarmValue)
{
//离开高值预警
if(p_wptr->LeaveHighAlarmAction <= gPagePtr[WorkingPageID].mActionInstructionsSize)
{
actionAddr = (u32)(gPagePtr[WorkingPageID].pActionInstructions + p_wptr->LeaveHighAlarmAction);
xQueueSendToBack(ActionInstructionQueue,&actionAddr,portMAX_DELAY);
}
}
}
if(dynamicType == 1)
{
sOldValue = (u32)oldValue;
if(p_wptr->EnterLowAlarmAction && sOldValue > (s32)lowAlarmValue && (s32)value <= (s32)lowAlarmValue)
{
//进入低值预警
if(p_wptr->EnterLowAlarmAction <= gPagePtr[WorkingPageID].mActionInstructionsSize)
{
actionAddr = (u32)(gPagePtr[WorkingPageID].pActionInstructions + p_wptr->EnterLowAlarmAction);
xQueueSendToBack(ActionInstructionQueue,&actionAddr,portMAX_DELAY);
}
}
else if(p_wptr->LeaveLowAlarmAction && sOldValue <= (s32)lowAlarmValue && (s32)value > (s32)lowAlarmValue)
{
//离开低值预警
if(p_wptr->LeaveLowAlarmAction <= gPagePtr[WorkingPageID].mActionInstructionsSize)
{
actionAddr = (u32)(gPagePtr[WorkingPageID].pActionInstructions + p_wptr->LeaveLowAlarmAction);
xQueueSendToBack(ActionInstructionQueue,&actionAddr,portMAX_DELAY);
}
}
if(p_wptr->EnterHighAlarmAction && sOldValue < (s32)highAlarmValue && (s32)value >= (s32)highAlarmValue)
{
//进入高值预警
if(p_wptr->EnterHighAlarmAction <= gPagePtr[WorkingPageID].mActionInstructionsSize)
{
actionAddr = (u32)(gPagePtr[WorkingPageID].pActionInstructions + p_wptr->EnterHighAlarmAction);
xQueueSendToBack(ActionInstructionQueue,&actionAddr,portMAX_DELAY);
}
}
else if(p_wptr->LeaveHighAlarmAction && sOldValue >= (s32)highAlarmValue && (s32)value < (s32)highAlarmValue)
{
//离开高值预警
if(p_wptr->LeaveHighAlarmAction <= gPagePtr[WorkingPageID].mActionInstructionsSize)
{
actionAddr = (u32)(gPagePtr[WorkingPageID].pActionInstructions + p_wptr->LeaveHighAlarmAction);
xQueueSendToBack(ActionInstructionQueue,&actionAddr,portMAX_DELAY);
}
}
}
}
p_wptr->WidgetAttr |= 0x8000;
p_wptr->OldValueL = (u16)value;
p_wptr->OldValueH = (u16)(value >> 16);
}
}
else if(dynamicType == TRANSLATION) //张纹理移动
{
}
else if(dynamicType == DIM) //亮暗
{
if(value > maxValue)
value = maxValue;
if(value < minValue)
value = minValue;
//tag表示的是alpha纹理的focused slice
texturePtr = &gPagePtr[WorkingPageID].pBasicTextureList[p_wptr->StartNumofTex];
texturePtr->FocusedSlice = value;
//不是页面刷新则更新
if(u8_pageRefresh == 0)
{
//send refresh message
#ifdef STATIC_BUFFER_EN
#ifdef AHMI_DEBUG
ERROR_PRINT("sending the refresh static buffer cmd");
#endif
// refreshMsg.mElementType = ANIMAITON_REFRESH_STATIC_BUFFER;
// refreshMsg.mElementPtr.pageptr = gPagePtr + WorkingPageID;
// sendToRefreshQueue(&refreshMsg);
#endif
#ifndef WHOLE_TRIBLE_BUFFER
refreshMsg.mElementType = ANIMATION_REFRESH_WIDGET;
refreshMsg.mElementPtr.wptr = p_wptr;
sendToRefreshQueue(&refreshMsg);
#endif
return AHMI_FUNC_SUCCESS;
}
}
else
return AHMI_FUNC_FAILURE;
return AHMI_FUNC_SUCCESS;
}
#endif
|
247ac416c81adf00e1b894a402d06756343fa582
|
9edf9b93c0f316d2ec4ecc14391e2c6d06472402
|
/gr-cognitive_radio/lib/noise_average_sink_impl.cc
|
611ce91e8d3225878074747ddbe0cd8a4da4b6f3
|
[
"MIT"
] |
permissive
|
n0p/my_GNURadio
|
bca14be18e02899990945ff339b8f1b3fa6f2ad4
|
2fc84cbc3e921daa1d3ab8cfa078788f6e1f709a
|
refs/heads/master
| 2021-01-17T21:19:06.770729
| 2017-03-06T06:28:02
| 2017-03-06T06:28:02
| 84,174,143
| 1
| 0
| null | 2017-03-07T08:27:55
| 2017-03-07T08:27:55
| null |
UTF-8
|
C++
| false
| false
| 3,752
|
cc
|
noise_average_sink_impl.cc
|
/*
* Copyright 2016 <+YOU OR YOUR COMPANY+>.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This software 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 software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gnuradio/io_signature.h>
#include "noise_average_sink_impl.h"
using namespace std;
namespace gr {
namespace cognitive_radio {
noise_average_sink::sptr
noise_average_sink::make(int slots, int consecutive, int veclen)
{
return gnuradio::get_initial_sptr
(new noise_average_sink_impl(slots,consecutive,veclen));
}
/*
* The private constructor
*/
noise_average_sink_impl::noise_average_sink_impl(int slots,int consecutive,int veclen)
: gr::block("noise_average_sink",
gr::io_signature::make(2, 2, veclen*sizeof(float)),//veclen*sizeof(short)),
gr::io_signature::make(0, 0, 0))
//d_slots(slots), d_consecutive(consecutive), d_veclen(veclen)
{
noise.resize(d_veclen);
average = new float [d_veclen];
current_slots = new int [d_veclen];
memset(average, 0, d_veclen*sizeof(float));
memset(current_slots, 0, d_veclen*sizeof(int));
for(int i=0;i<d_veclen; i++)
noise[i] = 25e-9;
}
/*
* Our virtual destructor.
*/
noise_average_sink_impl::~noise_average_sink_impl()
{
delete [] average;
delete [] current_slots;
}
std::vector<float> noise_average_sink_impl::get_noise() {
return noise;
}
float noise_average_sink_impl::get_noise_subband() {
return noise[0];
}
void noise_average_sink_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required)
{
/* <+forecast+> e.g. ninput_items_required[0] = noutput_items */
}
int noise_average_sink_impl::general_work (int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
const float *in0 = (const float *) input_items[0];
const short *in1 = (const short *) input_items[1];
int z=0;
while (z< noutput_items)
{
for(int i=0;i<d_veclen;i++)
{
if(in1[i]==0)
{
average[i]+=in0[i];
current_slots[i]++;
if(current_slots[i]==d_slots)
{
noise[i]=average[i]/d_slots;
current_slots[i]=0;
average[i]=0.0;
}
}
else
{
if(d_consecutive==1)
{
average[i]=0.0;
current_slots[i]=0;
}
}
}
in0+=d_veclen;
in1 +=d_veclen;
z++;
}
//<+OTYPE+> *out = (<+OTYPE+> *) output_items[0];
// Do <+signal processing+>
// Tell runtime system how many input items we consumed on
// each input stream.
//consume_each (noutput_items);
// Tell runtime system how many output items we produced.
return noutput_items;
}
} /* namespace cognitive_radio */
} /* namespace gr */
|
8e845818fce29ad32f294323af5b4bf74e4fe6fa
|
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
|
/app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir8254/dir8444/dir8556/file8604.cpp
|
52c65096f3f60e4bb0146cda4408f7d3ea229992
|
[] |
no_license
|
tgeng/HugeProject
|
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
|
4488d3b765e8827636ce5e878baacdf388710ef2
|
refs/heads/master
| 2022-08-21T16:58:54.161627
| 2020-05-28T01:54:03
| 2020-05-28T01:54:03
| 267,468,475
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 111
|
cpp
|
file8604.cpp
|
#ifndef file8604
#error "macro file8604 must be defined"
#endif
static const char* file8604String = "file8604";
|
2277221e4d8cb0e2216951fb16c3d820c7a33337
|
a3a90043a4586a31c5887a65a17c250cb969685c
|
/DSA-Sheet/String/65-find-next-permutation.cpp
|
bfe6f4256fd48e34d42bb799445bda97f9abf4c2
|
[] |
no_license
|
SuryankDixit/Problem-Solving
|
b400caf5a28ad378339ab823f017a3fe430fc301
|
931e33ad5ec6d4fec587cbffd968872f7785dc58
|
refs/heads/master
| 2023-08-12T05:11:00.241191
| 2021-10-13T08:11:12
| 2021-10-13T08:11:12
| 207,796,551
| 9
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,156
|
cpp
|
65-find-next-permutation.cpp
|
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
public:
vector<int> nextPermutation(int N, vector<int> arr){
// code here
int idx=-1;
int idx2=-1;
for(int i=N-1;i>=1;i--){
if(arr[i]>arr[i-1]){
idx=i-1;
break;
}
}
if(idx==-1){
reverse(arr.begin(),arr.end());
return arr;
}
for(int i=N-1;i>idx;i--){
if(arr[i]>arr[idx]){
idx2=i;
break;
}
}
swap(arr[idx],arr[idx2]);
reverse(arr.begin()+idx+1,arr.end());
return arr;
}
};
// { Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int N;
cin>>N;
vector<int> arr(N);
for(int i = 0;i < N;i++)
cin>>arr[i];
Solution ob;
vector<int> ans = ob.nextPermutation(N, arr);
for(int u: ans)
cout<<u<<" ";
cout<<"\n";
}
return 0;
} // } Driver Code Ends
|
ef7d9673baed22af145cf4b2d4df85a5de0f0220
|
fcdea24e6466d4ec8d7798555358a9af8acf9b35
|
/Tools/XEditor/SkyBoxDlg.h
|
c08ced61daa6ab9c3989e0a4b02d83588ab01fe2
|
[] |
no_license
|
yingzhang536/mrayy-Game-Engine
|
6634afecefcb79c2117cecf3e4e635d3089c9590
|
6b6fcbab8674a6169e26f0f20356d0708620b828
|
refs/heads/master
| 2021-01-17T07:59:30.135446
| 2014-11-30T16:10:54
| 2014-11-30T16:10:54
| 27,630,181
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 930
|
h
|
SkyBoxDlg.h
|
#pragma once
#include "afxwin.h"
// CSkyBoxDlg dialog
using namespace mray;
class CSkyBoxDlg : public CDialog
{
DECLARE_DYNAMIC(CSkyBoxDlg)
struct SkyInfo
{
core::string name;
core::string path;
core::string ext;
};
std::map<core::string,SkyInfo> m_skiesInfo;
void RefreshList();
public:
CSkyBoxDlg(CWnd* pParent = NULL); // standard constructor
virtual ~CSkyBoxDlg();
// Dialog Data
enum { IDD = IDD_SKYBOX_DLG };
core::string selectedSky;
virtual void OnExportLevelXML(xml::XMLElement*e);
virtual bool OnImportLevelXML(xml::XMLElement*e);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedOk();
public:
afx_msg void OnBnClickedLoadskybox();
public:
CEdit NameTxt;
public:
CListBox SkyboxLst;
public:
afx_msg void OnShowWindow(BOOL bShow, UINT nStatus);
};
|
45231ed570aed2137911f377bc159127935e9f4c
|
0f88d73baf435d2d07171122bd283213a24e0550
|
/extern/tlv.hpp
|
f97ceeff53c570bb74b32af383631b188e5e47b1
|
[
"MIT"
] |
permissive
|
phylib/pips-scenario
|
eb732ffbf6f6d1f0be6773c6d5f95d23b4bea54d
|
d152ae492a2bdf63be1340c1c9da91069a0460d9
|
refs/heads/master
| 2020-12-02T21:20:27.954059
| 2017-10-10T11:50:45
| 2017-10-10T11:50:45
| 96,297,617
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,083
|
hpp
|
tlv.hpp
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2013-2015 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
* ndn-cxx 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.
*
* ndn-cxx 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 copies of the GNU General Public License and GNU Lesser
* General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of ndn-cxx authors and contributors.
*/
#ifndef NDN_ENCODING_TLV_HPP
#define NDN_ENCODING_TLV_HPP
#include <stdexcept>
#include <iostream>
#include <iterator>
#include <limits>
#include "buffer.hpp"
#include "endian.hpp"
namespace ndn {
/** @brief practical limit of network layer packet size
*
* If a packet is longer than this size, library and application MAY drop it.
*/
const size_t MAX_NDN_PACKET_SIZE = 8800;
/**
* @brief Namespace defining NDN-TLV related constants and procedures
*/
namespace tlv {
/** @brief represents an error in TLV encoding or decoding
*
* Element::Error SHOULD inherit from this Error class.
*/
class Error : public std::runtime_error
{
public:
explicit
Error(const std::string& what)
: std::runtime_error(what)
{
}
};
enum {
Interest = 5,
Data = 6,
Name = 7,
ImplicitSha256DigestComponent = 1,
NameComponent = 8,
Selectors = 9,
Nonce = 10,
// <Unassigned> = 11,
InterestLifetime = 12,
MinSuffixComponents = 13,
MaxSuffixComponents = 14,
PublisherPublicKeyLocator = 15,
Exclude = 16,
ChildSelector = 17,
MustBeFresh = 18,
Any = 19,
MetaInfo = 20,
Content = 21,
SignatureInfo = 22,
SignatureValue = 23,
ContentType = 24,
FreshnessPeriod = 25,
FinalBlockId = 26,
SignatureType = 27,
KeyLocator = 28,
KeyDigest = 29,
LinkPreference = 30,
LinkDelegation = 31,
SelectedDelegation = 32,
MessageType = 33,
RequesterName = 34,
QCI = 35,
AppPrivateBlock1 = 128,
AppPrivateBlock2 = 32767
};
enum SignatureTypeValue {
DigestSha256 = 0,
SignatureSha256WithRsa = 1,
// <Unassigned> = 2,
SignatureSha256WithEcdsa = 3
};
/** @brief TLV codes for SignatureInfo features
* @sa docs/tutorials/certificate-format.rst
*/
enum {
// SignatureInfo TLVs
ValidityPeriod = 253,
NotBefore = 254,
NotAfter = 255,
AdditionalDescription = 258,
DescriptionEntry = 512,
DescriptionKey = 513,
DescriptionValue = 514
};
/** @brief indicates a possible value of ContentType field
*/
enum ContentTypeValue {
/** @brief indicates content is the actual data bits
*/
ContentType_Blob = 0,
/** @brief indicates content is another name which identifies actual data content
*/
ContentType_Link = 1,
/** @brief indicates content is a public key
*/
ContentType_Key = 2,
/** @brief indicates a producer generated NACK
* @warning Experimental. Not defined in NDN-TLV spec.
*/
ContentType_Nack = 3
};
/**
* @brief Read VAR-NUMBER in NDN-TLV encoding
*
* @param [in] begin Begin (pointer or iterator) of the buffer
* @param [in] end End (pointer or iterator) of the buffer
* @param [out] number Read number
*
* @throws This call never throws exception
*
* @return true if number successfully read from input, false otherwise
*/
template<class InputIterator>
inline bool
readVarNumber(InputIterator& begin, const InputIterator& end, uint64_t& number);
/**
* @brief Read TLV Type
*
* @param [in] begin Begin (pointer or iterator) of the buffer
* @param [in] end End (pointer or iterator) of the buffer
* @param [out] type Read type number
*
* @throws This call never throws exception
*
* This call is largely equivalent to tlv::readVarNumber, but exception will be thrown if type
* is larger than 2^32-1 (type in this library is implemented as uint32_t)
*/
template<class InputIterator>
inline bool
readType(InputIterator& begin, const InputIterator& end, uint32_t& type);
/**
* @brief Read VAR-NUMBER in NDN-TLV encoding
*
* @throws This call will throw ndn::tlv::Error (aka std::runtime_error) if number cannot be read
*
* Note that after call finished, begin will point to the first byte after the read VAR-NUMBER
*/
template<class InputIterator>
inline uint64_t
readVarNumber(InputIterator& begin, const InputIterator& end);
/**
* @brief Read TLV Type
*
* @throws This call will throw ndn::tlv::Error (aka std::runtime_error) if number cannot be read
*
* This call is largely equivalent to tlv::readVarNumber, but exception will be thrown if type
* is larger than 2^32-1 (type in this library is implemented as uint32_t)
*/
template<class InputIterator>
inline uint32_t
readType(InputIterator& begin, const InputIterator& end);
/**
* @brief Get number of bytes necessary to hold value of VAR-NUMBER
*/
inline size_t
sizeOfVarNumber(uint64_t varNumber);
/**
* @brief Write VAR-NUMBER to the specified stream
*/
inline size_t
writeVarNumber(std::ostream& os, uint64_t varNumber);
/**
* @brief Read nonNegativeInteger in NDN-TLV encoding
*
* This call will throw ndn::tlv::Error (aka std::runtime_error) if number cannot be read
*
* Note that after call finished, begin will point to the first byte after the read VAR-NUMBER
*
* How many bytes will be read is directly controlled by the size parameter, which can be either
* 1, 2, 4, or 8. If the value of size is different, then an exception will be thrown.
*/
template<class InputIterator>
inline uint64_t
readNonNegativeInteger(size_t size, InputIterator& begin, const InputIterator& end);
/**
* @brief Get number of bytes necessary to hold value of nonNegativeInteger
*/
inline size_t
sizeOfNonNegativeInteger(uint64_t varNumber);
/**
* @brief Write nonNegativeInteger to the specified stream
*/
inline size_t
writeNonNegativeInteger(std::ostream& os, uint64_t varNumber);
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Inline implementations
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
template<class InputIterator>
inline bool
readVarNumber(InputIterator& begin, const InputIterator& end, uint64_t& number)
{
if (begin == end)
return false;
uint8_t firstOctet = *begin;
++begin;
if (firstOctet < 253)
{
number = firstOctet;
}
else if (firstOctet == 253)
{
if (end - begin < 2)
return false;
uint16_t value = *reinterpret_cast<const uint16_t*>(&*begin);
begin += 2;
number = be16toh(value);
}
else if (firstOctet == 254)
{
if (end - begin < 4)
return false;
uint32_t value = *reinterpret_cast<const uint32_t*>(&*begin);
begin += 4;
number = be32toh(value);
}
else // if (firstOctet == 255)
{
if (end - begin < 8)
return false;
uint64_t value = *reinterpret_cast<const uint64_t*>(&*begin);
begin += 8;
number = be64toh(value);
}
return true;
}
template<class InputIterator>
inline bool
readType(InputIterator& begin, const InputIterator& end, uint32_t& type)
{
uint64_t number = 0;
bool isOk = readVarNumber(begin, end, number);
if (!isOk || number > std::numeric_limits<uint32_t>::max())
{
return false;
}
type = static_cast<uint32_t>(number);
return true;
}
template<class InputIterator>
inline uint64_t
readVarNumber(InputIterator& begin, const InputIterator& end)
{
if (begin == end)
BOOST_THROW_EXCEPTION(Error("Empty buffer during TLV processing"));
uint64_t value;
bool isOk = readVarNumber(begin, end, value);
if (!isOk)
BOOST_THROW_EXCEPTION(Error("Insufficient data during TLV processing"));
return value;
}
template<>
inline bool
readVarNumber<std::istream_iterator<uint8_t>>(std::istream_iterator<uint8_t>& begin,
const std::istream_iterator<uint8_t>& end,
uint64_t& value)
{
if (begin == end)
return false;
uint8_t firstOctet = *begin;
++begin;
if (firstOctet < 253)
{
value = firstOctet;
}
else if (firstOctet == 253)
{
value = 0;
size_t count = 0;
for (; begin != end && count < 2; ++count)
{
value = ((value << 8) | *begin);
begin++;
}
if (count != 2)
return false;
}
else if (firstOctet == 254)
{
value = 0;
size_t count = 0;
for (; begin != end && count < 4; ++count)
{
value = ((value << 8) | *begin);
begin++;
}
if (count != 4)
return false;
}
else // if (firstOctet == 255)
{
value = 0;
size_t count = 0;
for (; begin != end && count < 8; ++count)
{
value = ((value << 8) | *begin);
begin++;
}
if (count != 8)
return false;
}
return true;
}
template<class InputIterator>
inline uint32_t
readType(InputIterator& begin, const InputIterator& end)
{
uint64_t type = readVarNumber(begin, end);
if (type > std::numeric_limits<uint32_t>::max())
{
BOOST_THROW_EXCEPTION(Error("TLV type code exceeds allowed maximum"));
}
return static_cast<uint32_t>(type);
}
size_t
sizeOfVarNumber(uint64_t varNumber)
{
if (varNumber < 253) {
return 1;
}
else if (varNumber <= std::numeric_limits<uint16_t>::max()) {
return 3;
}
else if (varNumber <= std::numeric_limits<uint32_t>::max()) {
return 5;
}
else {
return 9;
}
}
inline size_t
writeVarNumber(std::ostream& os, uint64_t varNumber)
{
if (varNumber < 253) {
os.put(static_cast<char>(varNumber));
return 1;
}
else if (varNumber <= std::numeric_limits<uint16_t>::max()) {
os.put(static_cast<char>(253));
uint16_t value = htobe16(static_cast<uint16_t>(varNumber));
os.write(reinterpret_cast<const char*>(&value), 2);
return 3;
}
else if (varNumber <= std::numeric_limits<uint32_t>::max()) {
os.put(static_cast<char>(254));
uint32_t value = htobe32(static_cast<uint32_t>(varNumber));
os.write(reinterpret_cast<const char*>(&value), 4);
return 5;
}
else {
os.put(static_cast<char>(255));
uint64_t value = htobe64(varNumber);
os.write(reinterpret_cast<const char*>(&value), 8);
return 9;
}
}
template<class InputIterator>
inline uint64_t
readNonNegativeInteger(size_t size, InputIterator& begin, const InputIterator& end)
{
switch (size) {
case 1:
{
if (end - begin < 1)
BOOST_THROW_EXCEPTION(Error("Insufficient data during TLV processing"));
uint8_t value = *begin;
begin++;
return value;
}
case 2:
{
if (end - begin < 2)
BOOST_THROW_EXCEPTION(Error("Insufficient data during TLV processing"));
uint16_t value = *reinterpret_cast<const uint16_t*>(&*begin);
begin += 2;
return be16toh(value);
}
case 4:
{
if (end - begin < 4)
BOOST_THROW_EXCEPTION(Error("Insufficient data during TLV processing"));
uint32_t value = *reinterpret_cast<const uint32_t*>(&*begin);
begin += 4;
return be32toh(value);
}
case 8:
{
if (end - begin < 8)
BOOST_THROW_EXCEPTION(Error("Insufficient data during TLV processing"));
uint64_t value = *reinterpret_cast<const uint64_t*>(&*begin);
begin += 8;
return be64toh(value);
}
}
BOOST_THROW_EXCEPTION(Error("Invalid length for nonNegativeInteger (only 1, 2, 4, and 8 are allowed)"));
}
template<>
inline uint64_t
readNonNegativeInteger<std::istream_iterator<uint8_t> >(size_t size,
std::istream_iterator<uint8_t>& begin,
const std::istream_iterator<uint8_t>& end)
{
switch (size) {
case 1:
{
if (begin == end)
BOOST_THROW_EXCEPTION(Error("Insufficient data during TLV processing"));
uint64_t value = *begin;
begin++;
return value;
}
case 2:
{
uint64_t value = 0;
size_t count = 0;
for (; begin != end && count < 2; ++count)
{
value = ((value << 8) | *begin);
begin++;
}
if (count != 2)
BOOST_THROW_EXCEPTION(Error("Insufficient data during TLV processing"));
return value;
}
case 4:
{
uint64_t value = 0;
size_t count = 0;
for (; begin != end && count < 4; ++count)
{
value = ((value << 8) | *begin);
begin++;
}
if (count != 4)
BOOST_THROW_EXCEPTION(Error("Insufficient data during TLV processing"));
return value;
}
case 8:
{
uint64_t value = 0;
size_t count = 0;
for (; begin != end && count < 8; ++count)
{
value = ((value << 8) | *begin);
begin++;
}
if (count != 8)
BOOST_THROW_EXCEPTION(Error("Insufficient data during TLV processing"));
return value;
}
}
BOOST_THROW_EXCEPTION(Error("Invalid length for nonNegativeInteger (only 1, 2, 4, and 8 are allowed)"));
}
inline size_t
sizeOfNonNegativeInteger(uint64_t varNumber)
{
if (varNumber < 253) {
return 1;
}
else if (varNumber <= std::numeric_limits<uint16_t>::max()) {
return 2;
}
else if (varNumber <= std::numeric_limits<uint32_t>::max()) {
return 4;
}
else {
return 8;
}
}
inline size_t
writeNonNegativeInteger(std::ostream& os, uint64_t varNumber)
{
if (varNumber < 253) {
os.put(static_cast<char>(varNumber));
return 1;
}
else if (varNumber <= std::numeric_limits<uint16_t>::max()) {
uint16_t value = htobe16(static_cast<uint16_t>(varNumber));
os.write(reinterpret_cast<const char*>(&value), 2);
return 2;
}
else if (varNumber <= std::numeric_limits<uint32_t>::max()) {
uint32_t value = htobe32(static_cast<uint32_t>(varNumber));
os.write(reinterpret_cast<const char*>(&value), 4);
return 4;
}
else {
uint64_t value = htobe64(varNumber);
os.write(reinterpret_cast<const char*>(&value), 8);
return 8;
}
}
} // namespace tlv
} // namespace ndn
#endif // NDN_ENCODING_TLV_HPP
|
aa301d12e70e78efab157099f53ac265de09752b
|
34c36d86b4ec705cf9c0fb3c7f2d6b2d5b36b1ff
|
/Framework/Input/DIXInputListener.h
|
1e49767077fda2680d4a01a726b51fdd3f7516e3
|
[] |
no_license
|
totoki-kei/tgp
|
dd0be1ece5fbf3c98515a8afef6f93a4a3f5bd02
|
38b7f67d7be50af147414daa8898411b709df4ec
|
refs/heads/master
| 2020-04-01T09:35:45.970201
| 2015-04-19T05:32:47
| 2015-04-19T05:32:47
| 15,510,784
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 258
|
h
|
DIXInputListener.h
|
#pragma once
#include "DIHeader.h"
class DIXInputListener;
enum class DIXInputType{
Button,
Axis,
};
class DIXInputListener
{
int padId;
bool lastStatus;
public:
DIXInputListener(int padId);
~DIXInputListener();
void Update(XINPUT_STATE&);
};
|
da03c0a9d177f18dd9f621ff394f2e48faab5f1d
|
aff1abb26ceba8c63a0ea1751b7790a05bf4bdb3
|
/qnc/src/utils.h
|
c3066ffc984c5fd4bc2310e42e039e66b4c51272
|
[
"MIT"
] |
permissive
|
yang123vc/abandoned
|
e9036bf160d3305061e689566080c4cdebd7a485
|
c0af4108c30990203ab45436e2a92671598b8bac
|
refs/heads/master
| 2020-05-07T05:47:59.657827
| 2015-08-13T12:52:05
| 2015-08-13T12:52:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 183
|
h
|
utils.h
|
#ifndef UTILS_H
#define UTILS_H
#include <QString>
class Utils
{
Utils() {} // static class
public:
static QString formatFileSize(qint64 fileSize);
};
#endif // UTILS_H
|
4460c5a1ac9abd4c538531cb2fa38c55bfee50d5
|
f48b9f128d005d8a4d6550b51c042aac97436709
|
/platformio/registration_translator/src/sketch.ino
|
aec48347f8a9595866d906559692fc8eae336cdb
|
[] |
no_license
|
DefProc/made-invaders
|
384b3cb2bbf1f59c6406125538a663ecb9aeb313
|
32c6b11426a14e9a89a6bcb9e0815685749b7b33
|
refs/heads/master
| 2021-06-20T11:22:26.906143
| 2017-07-24T20:52:56
| 2017-07-24T20:52:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,580
|
ino
|
sketch.ino
|
/* Registration Translation
This sketch translates the relavent game messages back to the expected
format for Node Red to understand:
* Game start: 0,<rfid-key>,<game_uid>
* Take photograph: 1,<rfid-key>,<game_uid>
* Game end: 2,<rfid-key>,<game_uid>,<score>
* Target Hit: 3,<rfid-key>,<game_uid>,<target_id>,<timestamp>,<score>
* Get Ready: 4,<rfid-key>,<game_uid>
*/
#include <RFM69.h>
#include <SPI.h>
#include "constants.h"
#include "secrets.h"
#define NODEID REG_STN
RFM69 radio;
Payload theData;
void setup() {
// start the serial monitor
Serial.begin(9600);
// initialize the radio
radio.initialize(FREQUENCY,NODEID,NETWORKID);
#ifdef IS_RFM69HW
radio.setHighPower();
#endif
radio.encrypt(ENCRYPTKEY);
//radio.promiscuous(true);
}
void loop() {
// check any incoming radio messages
// and pass them to serial
if (radio.receiveDone()) {
// check if we're getting hit data
if (radio.DATALEN = sizeof(Payload)) {
theData = *(Payload*)radio.DATA;
switch (theData.message_id) {
case GAME_START:
Serial.print("0,");
printRfid_num();
Serial.print(",");
Serial.print(theData.game_uid);
Serial.println();
break;
case TAKE_PHOTO:
Serial.print("1,");
printRfid_num();
Serial.print(",");
Serial.print(theData.game_uid);
Serial.println();
break;
case GAME_END:
Serial.print("2,");
printRfid_num();
Serial.print(",");
Serial.print(theData.game_uid);
Serial.print(",");
Serial.print(theData.score);
Serial.println();
break;
case HIT:
Serial.print("3,");
printRfid_num();
Serial.print(",");
Serial.print(theData.game_uid);
Serial.print(",");
Serial.print(radio.SENDERID);
Serial.print(",");
Serial.print(theData.timestamp);
Serial.print(",");
Serial.print(theData.score);
Serial.print(",");
Serial.println();
case GET_READY:
Serial.print("4,");
printRfid_num();
Serial.print(",");
Serial.print(theData.game_uid);
Serial.println();
break;
}
}
if (radio.ACKRequested() && radio.TARGETID == NODEID) {
uint8_t theNodeID = radio.SENDERID;
radio.sendACK();
}
}
}
void printRfid_num() {
for (int i=0; i<RFID_DIGITS; i++) {
Serial.write(theData.rfid_num[i]);
}
}
|
be5872ed0216ffd9efbc449643e1b018b9cc81ac
|
7e7b21cd30c91e9b7a44e3a07b0c8c72fe26dcea
|
/Engine/Include/Quartz2/Vec3.hpp
|
21bdbd776d8f3aceff7133b47e6d5ca369b02da2
|
[
"BSD-3-Clause"
] |
permissive
|
apachano/Phoenix
|
a80a5f0956d6abcce27265d63ccdf7eb6e24a99c
|
88242e4d3768bb878083121cc2a93106b699cd97
|
refs/heads/develop
| 2021-11-27T03:11:03.164468
| 2019-12-20T22:26:52
| 2019-12-20T22:26:52
| 229,603,884
| 1
| 1
|
BSD-3-Clause
| 2020-10-19T15:59:14
| 2019-12-22T17:21:30
| null |
UTF-8
|
C++
| false
| false
| 7,096
|
hpp
|
Vec3.hpp
|
// Copyright 2019 Genten Studios
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <cmath>
#include <ostream>
namespace q2
{
template <typename T>
class TVec3
{
public:
using ValueType = T;
using ValueReference = T &;
using ConstValueReference = const T &;
static constexpr int SIZE = 3;
static constexpr int size() { return SIZE; }
union {
T data[SIZE];
struct
{
T x;
T y;
T z;
};
struct
{
T r;
T g;
T b;
};
};
constexpr TVec3() : x(), y(), z() {}
template <typename X>
explicit constexpr TVec3(X val)
: x(static_cast<T>(val)), y(static_cast<T>(val)),
z(static_cast<T>(val))
{
}
template <typename X, typename Y, typename Z>
constexpr TVec3(X x, Y y, Z z)
: x(static_cast<T>(x)), y(static_cast<T>(y)),
z(static_cast<T>(z))
{
}
template <typename X>
TVec3(const TVec3<X>& other)
{
x = static_cast<T>(other.x);
y = static_cast<T>(other.y);
z = static_cast<T>(other.z);
}
template <typename X>
TVec3& operator=(const TVec3<X>& other)
{
x = static_cast<T>(other.x);
y = static_cast<T>(other.y);
z = static_cast<T>(other.z);
return *this;
}
template <typename NewType>
explicit constexpr operator TVec3<NewType>() const
{
TVec3<NewType> vec;
vec.x = static_cast<NewType>(x);
vec.y = static_cast<NewType>(y);
vec.z = static_cast<NewType>(z);
return vec;
}
void floor()
{
std::floor(x);
std::floor(y);
std::floor(z);
}
void ceil()
{
std::ceil(x);
std::ceil(y);
std::ceil(z);
}
void normalize()
{
const float magnitude = std::sqrt(dotProduct(*this, *this));
x /= magnitude;
y /= magnitude;
z /= magnitude;
}
static TVec3 normalize(const TVec3& vec)
{
const float magnitude = std::sqrt(dotProduct(vec, vec));
return TVec3(vec.x / magnitude, vec.y / magnitude,
vec.z / magnitude);
}
static TVec3 cross(const TVec3& vec1, const TVec3& vec2)
{
return TVec3(vec1.y * vec2.z - vec1.z * vec2.y,
vec1.z * vec2.x - vec1.x * vec2.z,
vec1.x * vec2.y - vec1.y * vec2.x);
}
static float dotProduct(const TVec3& vec1,
const TVec3& vec2)
{
return vec1.x * vec2.x + vec1.y * vec2.y + vec1.z * vec2.z;
}
bool operator==(const TVec3& rhs) const
{
return (x == rhs.x && y == rhs.y && z == rhs.z);
}
bool operator!=(const TVec3& rhs) const
{
return (x != rhs.x && y != rhs.y && z != rhs.z);
}
bool operator>(const TVec3& rhs) const
{
return (x > rhs.x && y > rhs.y && z > rhs.z);
}
bool operator<(const TVec3& rhs) const
{
return (x < rhs.x && y < rhs.y && z < rhs.z);
}
bool operator>=(const TVec3& rhs) const
{
return (x >= rhs.x && y >= rhs.y && z >= rhs.z);
}
bool operator<=(const TVec3& rhs) const
{
return (x <= rhs.x && y <= rhs.y && z <= rhs.z);
}
TVec3 operator+(const TVec3& rhs) const
{
return TVec3(x + rhs.x, y + rhs.y, z + rhs.z);
}
TVec3 operator-(const TVec3& rhs) const
{
return TVec3(x - rhs.x, y - rhs.y, z - rhs.z);
}
TVec3 operator*(const TVec3& rhs) const
{
return TVec3(x * rhs.x, y * rhs.y, z * rhs.z);
}
TVec3 operator/(const TVec3& rhs) const
{
return TVec3(x / rhs.x, y / rhs.y, z / rhs.z);
}
void operator+=(const TVec3& rhs)
{
x += rhs.x, y += rhs.y;
z += rhs.z;
}
void operator-=(const TVec3& rhs)
{
x -= rhs.x, y -= rhs.y;
z -= rhs.z;
}
void operator*=(const TVec3& rhs)
{
x *= rhs.x, y *= rhs.y;
z *= rhs.z;
}
void operator/=(const TVec3& rhs)
{
x /= rhs.x, y /= rhs.y;
z /= rhs.z;
}
TVec3 operator+(const T& rhs) const
{
return TVec3(x + rhs, y + rhs, z + rhs);
}
TVec3 operator-(const T& rhs) const
{
return TVec3(x - rhs, y - rhs, z - rhs);
}
TVec3 operator*(const T& rhs) const
{
return TVec3(x * rhs, y * rhs, z * rhs);
}
TVec3 operator/(const T& rhs) const
{
return TVec3(x / rhs, y / rhs, z / rhs);
}
void operator+=(const T& rhs)
{
x += rhs, y += rhs;
z += rhs;
}
void operator-=(const T& rhs)
{
x -= rhs, y -= rhs;
z -= rhs;
}
void operator*=(const T& rhs)
{
x *= rhs, y *= rhs;
z *= rhs;
}
void operator/=(const T& rhs)
{
x /= rhs, y /= rhs;
z /= rhs;
}
TVec3& operator++()
{
++x;
++y;
++z;
return *this;
}
TVec3 operator++(int)
{
TVec3 result(*this);
++(*this);
return result;
}
TVec3& operator--()
{
--x;
--y;
--z;
return *this;
}
TVec3 operator--(int)
{
TVec3 result(*this);
--(*this);
return result;
}
friend std::ostream& operator<<(std::ostream& os,
const TVec3& vec)
{
os << "(" << vec.x << ", " << vec.y << ", " << vec.z << ")";
return os;
}
};
using Vec3 = TVec3<float>;
using Vec3f = TVec3<float>;
using Vec3d = TVec3<double>;
using Vec3i = TVec3<int>;
using Vec3u = TVec3<unsigned int>;
} // namespace q2
template <typename T>
q2::TVec3<T> operator-(
const q2::TVec3<T>& left,
const q2::TVec3<T>& right)
{
return { left.x - right.x, left.y - right.y, left.z - right.z };
}
template <typename T>
q2::TVec3<T> operator+(
const q2::TVec3<T>& left,
const q2::TVec3<T>& right)
{
return { left.x + right.x, left.y + right.y, left.z + right.z };
}
template <typename T>
q2::TVec3<T> operator*(
const q2::TVec3<T>& left,
const q2::TVec3<T>& right)
{
return { left.x * right.x, left.y * right.y, left.z * right.z };
}
template <typename T>
q2::TVec3<T> operator/(
const q2::TVec3<T>& left,
const q2::TVec3<T>& right)
{
return { left.x / right.x, left.y / right.y, left.z / right.z };
}
|
ca945d9cada33c6b3f872ad779b021bf7e6bf9b3
|
5cbb6f03a7ee11223095d641329e53e5f2fd676f
|
/src/clustering/cluster.h
|
716765ffd2dabae59b90350cd940109623291815
|
[] |
no_license
|
aabin/DAGSfM
|
300e5caf92d74b80b6579a1dbb917ac4304ef25c
|
158646b9b554c5c7a0abf37016f243d37b987078
|
refs/heads/master
| 2022-11-08T07:12:26.793358
| 2020-06-24T09:14:38
| 2020-06-24T09:14:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,017
|
h
|
cluster.h
|
#ifndef SRC_CLUSTERING_CLUSTER_H_
#define SRC_CLUSTERING_CLUSTER_H_
#include <glog/logging.h>
#include <igraph/igraph.h>
#include <cstdio>
#include <unordered_map>
#include "util/types.h"
using namespace colmap;
namespace DAGSfM {
enum ClusterType { NCUT, KMEANS, SPECTRAL, COMMUNITY_DETECTION, HYBRID };
class Cluster {
protected:
std::unordered_map<int, int> labels_;
igraph_t igraph_;
igraph_vector_t i_edges_;
igraph_vector_t i_weights_;
std::vector<int> nodes_;
int cluster_num_;
public:
Cluster();
~Cluster();
virtual std::unordered_map<int, int> ComputeCluster(
const std::vector<std::pair<int, int>>& edges,
const std::vector<int>& weights, const int num_partitions) = 0;
int ClusterNum() const;
bool InitIGraph(const std::vector<std::pair<int, int>>& edges,
const std::vector<int>& weights);
bool OutputIGraph(const std::string graph_dir,
const std::string image_path = "") const;
};
} // namespace DAGSfM
#endif
|
f02744abe02e773f7b2625851b94f9a809c1798b
|
891eca7ee0570cdadad46576dbd38b579b2339a1
|
/tryOuts/stackWithDefaultParams.hpp
|
b70f86f82cd4e596cd05d2d2abf1434c2ffd018d
|
[] |
no_license
|
girim/cplusplusPrimerExamples
|
c5caa0b47630c4afb221a1db78bbd492c9ae2f48
|
87223e8273d2fdebf91571a794038cfe5a483ec3
|
refs/heads/master
| 2021-01-17T20:43:12.655554
| 2018-09-08T11:07:50
| 2019-02-17T18:30:22
| 65,602,150
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,657
|
hpp
|
stackWithDefaultParams.hpp
|
#ifndef __StackD_WITH_DEFAULT_PARAMS_HPP__
#define __StackD_WITH_DEFAULT_PARAMS_HPP__
#include <cassert>
#include <iostream>
template<typename T, typename Container = std::vector<T>>
class StackD
{
public:
StackD();
~StackD();
void push(const T& element);
void pop();
const T& top() const;
bool empty();
void displayContents(std::ostream&);
friend std::ostream& operator<<(std::ostream& os, StackD<T, Container> &st)
{
st.displayContents(os);
}
private:
Container elements_;
};
template<typename T, typename Container>
StackD<T, Container>::StackD()
{
std::cout << "StackD constructed: " << std::endl;
};
template<typename T, typename Container>
StackD<T, Container>::~StackD()
{
std::cout << "StackD destructed: " << std::endl;
};
template<typename T, typename Container>
bool StackD<T, Container>::empty()
{
return elements_.empty();
}
template<typename T, typename Container>
void StackD<T, Container>::push(const T& element)
{
elements_.push_back(element);
}
template<typename T, typename Container>
void StackD<T, Container>::pop()
{
assert(!empty());
elements_.pop_back();
}
template<typename T, typename Container>
const T& StackD<T,Container>::top() const
{
assert(!empty());
elements_.back();
}
template<typename T, typename Container>
void StackD<T, Container>::displayContents(std::ostream& os)
{
for (auto iter = elements_.crbegin(); iter != elements_.crend(); ++iter)
os << "(" << *iter << ")" << std::endl;
os << std::endl;
};
#endif //__StackD_WITH_DEFAULT_PARAMS_HPP__
|
3163c1ef1c67502f1bf072de7226e98bf562ae30
|
23f2d77b6867cf053f50bedf107a453db3f1471c
|
/oi2/sze.cpp
|
e35d733a7fd0aeca9fc001668735de765f7d16d1
|
[] |
no_license
|
jbhayven/oi_solutions
|
ecf71e84330373c7d59a7b9399c57773e7a6fa99
|
9e099d11b5235b208b43e76645932fdaf13f37ac
|
refs/heads/master
| 2023-07-15T09:34:52.896147
| 2021-08-25T12:59:38
| 2021-08-25T12:59:38
| 257,976,717
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 389
|
cpp
|
sze.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector< pair<double, int> > acts(n);
for(int i = 0; i < n; i++) {
double a, b;
cin >> a >> b;
acts[i] = make_pair(b / a, i + 1);
}
sort(acts.begin(), acts.end());
for(auto pair : acts)
cout << pair.second << endl;
return 0;
}
|
fbf2bb7ad0b29c2deaf18116615f44d7fe8bc79b
|
cb613a172c1a5675270682a6c42cb7abd5f5fc1e
|
/build-NtrestandChill-Desktop_Qt_6_0_2_MinGW_64_bit-Debug/ui_createAccount.h
|
4c280809c204873fcb411422650a9dc633e86091
|
[] |
no_license
|
umustdye/NtrestandChill
|
fde71d26d6b59db1aba65423f2e781009d92d352
|
b413f75caf4ec8bae314db84700e54b6ad7f8586
|
refs/heads/main
| 2023-04-10T13:07:40.679525
| 2021-04-11T19:04:18
| 2021-04-11T19:04:18
| 356,664,597
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,889
|
h
|
ui_createAccount.h
|
/********************************************************************************
** Form generated from reading UI file 'createAccount.ui'
**
** Created by: Qt User Interface Compiler version 6.0.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_CREATEACCOUNT_H
#define UI_CREATEACCOUNT_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDialog>
QT_BEGIN_NAMESPACE
class Ui_CreateAccount
{
public:
void setupUi(QDialog *CreateAccount)
{
if (CreateAccount->objectName().isEmpty())
CreateAccount->setObjectName(QString::fromUtf8("CreateAccount"));
CreateAccount->resize(783, 515);
QPalette palette;
QBrush brush(QColor(255, 255, 255, 255));
brush.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Base, brush);
QBrush brush1(QColor(81, 93, 93, 255));
brush1.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Window, brush1);
palette.setBrush(QPalette::Inactive, QPalette::Base, brush);
palette.setBrush(QPalette::Inactive, QPalette::Window, brush1);
palette.setBrush(QPalette::Disabled, QPalette::Base, brush1);
palette.setBrush(QPalette::Disabled, QPalette::Window, brush1);
CreateAccount->setPalette(palette);
retranslateUi(CreateAccount);
QMetaObject::connectSlotsByName(CreateAccount);
} // setupUi
void retranslateUi(QDialog *CreateAccount)
{
CreateAccount->setWindowTitle(QCoreApplication::translate("CreateAccount", "Dialog", nullptr));
} // retranslateUi
};
namespace Ui {
class CreateAccount: public Ui_CreateAccount {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_CREATEACCOUNT_H
|
b811f025affb3def9c887b96d10a735a2efb4279
|
76fc0bf14b6ae4d962dbad694ffdb1c8f9e82d54
|
/201104/HookNet/HookNet/HookNet.cpp
|
9c5d6d18bc965343eed73ac3e47c516b047a51ab
|
[] |
no_license
|
SquallATF/zghlibrary
|
a7884d7cd7a3935d9e9567c802ecb1aeef33494e
|
52703f9fd14ec66a99b99c48aad97bb74062c0bc
|
refs/heads/master
| 2016-06-15T21:47:43.219189
| 2012-11-30T08:11:35
| 2012-11-30T08:11:35
| 46,103,249
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 227
|
cpp
|
HookNet.cpp
|
// HookNet.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "HookNet.h"
// This is an example of an exported function.
HOOKNET_API int fnHookNet(void)
{
return 42;
}
|
1242dd3951cef26eaab532929dde62fbfb4be9e9
|
fe0a4b4e71dc79420544ef0025432e091e69ed85
|
/10-Memory/DemoPointers/src/ex_ptr.cpp
|
8655f62f3edace7797a6054972f2d3a070c05be9
|
[] |
no_license
|
avelana/cpp-examples
|
cc338a68efdf1fc06f7a2d58b68258a56ee09569
|
f83068f378ec64c9545eca19e0bcc4db8e7a3dfb
|
refs/heads/master
| 2022-12-21T20:53:04.830890
| 2022-12-18T19:03:13
| 2022-12-18T19:03:13
| 209,393,492
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,190
|
cpp
|
ex_ptr.cpp
|
//
// Created by volha on 28.10.2019.
//
// EX1
// #include <iostream>
//
// void doAnything(int *ptr)
//{
// if (ptr)
// std::cout << "You passed in " << *ptr << '\n';
// else
// std::cout << "You passed in a null pointer\n";
// }
//
// int main()
//{
// doAnything(nullptr); // теперь аргумент является точно нулевым указателем, а не целочисленным
// значением
//
// return 0;
// }
#include <cstddef> // для std::nullptr_t
#include <iostream>
void doAnything(std::nullptr_t ptr) {
std::cout << "in doAnything()\n";
}
int main() {
doAnything(nullptr); // вызов функции doAnything с аргументом типа std::nullptr_t
const int kN = 5;
const int kM = 7;
int** arr = new int*[kN];
// Пример. Создание двумерного динамического массива
for (int i = 0; i < kN; i++) {
arr[i] = new int[kM];
}
// Удаление двумерного динамического массива из памяти
for (int i = 0; i < kN; i++)
delete[] arr[i];
delete[] arr;
return 0;
}
|
3cd28e79b27ae5ed86ca42211f5335d48a6bf314
|
34c51434f890d387c07b6543c2ced9eb20883798
|
/gtest_example.cpp
|
c9af83695d63d68e7c04e946bd8eed79f1cc0725
|
[] |
no_license
|
Eason-Sun/Breadth-First-Search
|
4add7a506234188a8a60b5709a822723f7668686
|
36164d87af48eacacece6f34cf1f6b9d9d2eab9b
|
refs/heads/master
| 2020-07-09T03:41:13.491951
| 2019-08-22T20:34:05
| 2019-08-22T20:34:05
| 203,865,771
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,623
|
cpp
|
gtest_example.cpp
|
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
#include "Vertex.h"
#include "Graph.h"
#include <iostream>
#include <limits>
using namespace std;
TEST_CASE("1. isRemoved") {
CHECK(isRemoved('<'));
CHECK(isRemoved('>'));
CHECK(isRemoved('{'));
CHECK(isRemoved('}'));
}
TEST_CASE("2. inputParser") {
string input = "E {<2,6>,<2,8>,<2,5>,<6,5>,<5,8>,<6,10>,<10,8>}";
vector<int> outputVector {2,6,2,8,2,5,6,5,5,8,6,10,10,8};
CHECK(inputParser(input) == outputVector);
}
TEST_CASE("3. Vertex::Vertex")
{
int id = 5;
Vertex v = Vertex(id);
CHECK(v.getId() == id);
CHECK(v.getColor() == Vertex::white);
CHECK(v.getDistance() == numeric_limits<int>::max());
CHECK(v.getPredecessor() == nullptr);
}
TEST_CASE("4. Vertex::setColor")
{
int id = 5;
Vertex v = Vertex(id);
v.setColor(Vertex::black);
CHECK(v.getColor() == Vertex::black);
}
TEST_CASE("5. Vertex::setDistance")
{
int id = 5;
Vertex v = Vertex(id);
v.setDistance(2);
CHECK(v.getDistance() == 2);
}
TEST_CASE("6 Vertex::setPredecessor")
{
int id = 5;
Vertex v = Vertex(id);
int id_ = 10;
Vertex v_ = Vertex(id_);
v.setPredecessor(&v_);
CHECK(v.getPredecessor() == &v_);
}
TEST_CASE("7. ToString")
{
int a = 1;
CHECK(ToString<int>(a) == "1");
}
TEST_CASE("8. Graph::shortestPath")
{
string configV = "V 11";
Graph g = Graph(atoi((configV.substr(2)).c_str()));
string configE = "E {<2,6>,<2,8>,<2,5>,<6,5>,<5,8>,<6,10>,<10,8>}";
g.setM(inputParser(configE));
g.configVertexVect();
g.updateVertexVect(10);
string output = g.shortestPath(2, 10);
CHECK(output == "2-6-10");
}
|
5e3f2ec4c7fe258a02df948ac64310292f54095b
|
e26036d8c26ab28a13d7c5803a95225c1d5a9df5
|
/tmp.cpp
|
2e4b421a07cf10e252923f44b14997d2e48f3bd4
|
[] |
no_license
|
Lurh/PAT_A-code
|
308e34155136b93a5d565b844516abf2191562ae
|
dcf7ade32fdbbbc9fb78e0fc949dac47fa4ae236
|
refs/heads/master
| 2021-09-18T10:35:34.321456
| 2018-07-13T03:51:08
| 2018-07-13T03:51:08
| 120,162,376
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 879
|
cpp
|
tmp.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int findDuplicate(vector<int>& nums) {
int i,j,sum=0,tmp=0,ans=0;
for(i=0;i<nums.size();i++)
{
sum+=i;
tmp+=nums[i];
}
tmp-=sum;
for(i=max(int(tmp+sum/nums.size()),int(sum/nums.size()));i>=0;i--)
{
ans = 0;
for(j=0;j<nums.size();j++)
if(nums[j]==i)
{
ans++;
if(ans>1)
return nums[j];
}
}
}
int main()
{
vector<int> ans;
ans.push_back(8);
ans.push_back(1);
ans.push_back(1);
ans.push_back(1);
ans.push_back(2);
ans.push_back(7);
ans.push_back(4);
ans.push_back(3);
ans.push_back(1);
ans.push_back(1);
cout<<findDuplicate(ans)<<endl;
return 0;
}
|
a8b912fba095c9c0c508ec95270729e52b81d305
|
efb711d2f0f15e1489b9ad239071b97641cc035c
|
/Topics/2015_02_01/multiplstrings.cpp
|
af3f38d9881fd0de339511f23666c6c3dc7bd597
|
[
"MIT"
] |
permissive
|
TelerikAcademy/CPP-Beginner
|
42cac061cb803b052c066dd4a757ff9105dac901
|
a4d5a8beb870da910f74da41362b02f0d754ee51
|
refs/heads/master
| 2021-01-20T19:06:10.364957
| 2016-08-03T09:00:51
| 2016-08-03T09:00:51
| 64,829,458
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 274
|
cpp
|
multiplstrings.cpp
|
#include <iostream>
#include <cstring>
using namespace std;
int main () {
char A[100], B[100], C[100];
strcpy(A, strcpy(B, strcpy(C, "Zdrawvey") ));
/// A=B=C="Zdrawvey";
cout << A << endl;
cout << B << endl;
cout << C << endl;
return 0;
}
|
9abea3e32aecf236a536f70ddf31f718e8428f9e
|
d028fd7bd940a7e1d092cb6a321bdf358966db98
|
/src/enigma2/extract/EpisodeSeasonPattern.h
|
34809d784e3a1a2b3a103fae9a7bbe33bf0f4930
|
[] |
no_license
|
phunkyfish/pvr.vuplus
|
5d59f609c61e10e507f69207510ea54351e5e028
|
457a28df62f8f2a6cecb8b92a7e256f8d418402e
|
refs/heads/Matrix
| 2023-02-28T13:04:02.586274
| 2019-08-24T07:00:57
| 2019-08-24T07:00:57
| 183,883,619
| 2
| 0
| null | 2021-07-14T13:20:42
| 2019-04-28T09:01:46
|
C++
|
UTF-8
|
C++
| false
| false
| 878
|
h
|
EpisodeSeasonPattern.h
|
#pragma once
#include <regex>
namespace enigma2
{
namespace extract
{
struct EpisodeSeasonPattern
{
EpisodeSeasonPattern(const std::string &masterPattern, const std::string &seasonPattern, const std::string &episodePattern)
{
m_masterRegex = std::regex(masterPattern);
m_seasonRegex = std::regex(seasonPattern);
m_episodeRegex = std::regex(episodePattern);
m_hasSeasonRegex = true;
}
EpisodeSeasonPattern(const std::string &masterPattern, const std::string &episodePattern)
{
m_masterRegex = std::regex(masterPattern);
m_episodeRegex = std::regex(episodePattern);
m_hasSeasonRegex = false;
}
std::regex m_masterRegex;
std::regex m_seasonRegex;
std::regex m_episodeRegex;
bool m_hasSeasonRegex;
};
} //namespace extract
} //namespace enigma2
|
9c3036b2ada21069253eaae332d2158e55bf9e75
|
31b99ef8b34063938415c72f8d6d82df17fcd720
|
/src/queue/queue.cpp
|
9fad8a04a24972329f0029db7a15ceab127a95bc
|
[] |
no_license
|
kod3r/grape
|
5efc86825285ef6fe2dd2328d6e02651cf1d715e
|
ae397689a6cbf285124077bb11d564c8c2353e37
|
refs/heads/master
| 2021-01-17T16:48:41.637348
| 2013-07-15T18:52:43
| 2013-07-15T18:52:43
| 14,078,015
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,243
|
cpp
|
queue.cpp
|
#include <cocaine/framework/logging.hpp>
#include "grape/rapidjson/document.h"
#include "grape/rapidjson/prettywriter.h"
#include "grape/rapidjson/stringbuffer.h"
#include "grape/rapidjson/filestream.h"
#include "queue.hpp"
namespace {
//DEBUG: only for debug ioremap::elliptics::sessions
std::shared_ptr<cocaine::framework::logger_t> __grape_queue_private_log;
#define LOG_INFO(...) COCAINE_LOG_INFO(__grape_queue_private_log, __VA_ARGS__)
#define LOG_ERROR(...) COCAINE_LOG_ERROR(__grape_queue_private_log, __VA_ARGS__)
#define LOG_DEBUG(...) COCAINE_LOG_DEBUG(__grape_queue_private_log, __VA_ARGS__)
}
// externally accessible function to set cocaine logger object
void grape_queue_module_set_logger(std::shared_ptr<cocaine::framework::logger_t> logger) {
__grape_queue_private_log = logger;
}
// externally accessible function to get cocaine logger object
std::shared_ptr<cocaine::framework::logger_t> grape_queue_module_get_logger() {
return __grape_queue_private_log;
}
namespace ioremap { namespace grape {
const int DEFAULT_MAX_CHUNK_SIZE = 10000;
queue::queue(const std::string &queue_id)
: m_chunk_max(DEFAULT_MAX_CHUNK_SIZE)
, m_queue_id(queue_id)
, m_queue_state_id(m_queue_id + ".state")
, m_last_timeout_check_time(0)
{
}
void queue::initialize(const std::string &config)
{
memset(&m_statistics, 0, sizeof(m_statistics));
rapidjson::Document doc;
m_client = elliptics_client_state::create(config, doc);
LOG_INFO("init: elliptics client created");
if (doc.HasMember("chunk-max-size"))
m_chunk_max = doc["chunk-max-size"].GetInt();
memset(&m_state, 0, sizeof(m_state));
try {
ioremap::elliptics::data_pointer d = m_client.create_session().read_data(m_queue_state_id, 0, 0).get_one().file();
auto *state = d.data<queue_state>();
m_state.chunk_id_push = state->chunk_id_push;
m_state.chunk_id_ack = state->chunk_id_ack;
LOG_INFO("init: queue meta found: chunk_id_ack %d, chunk_id_push %d",
m_state.chunk_id_ack, m_state.chunk_id_push
);
} catch (const ioremap::elliptics::not_found_error &) {
LOG_INFO("init: no queue meta found, starting in pristine state");
}
// load metadata of existing chunk into memory
ioremap::elliptics::session tmp = m_client.create_session();
for (int i = m_state.chunk_id_ack; i <= m_state.chunk_id_push; ++i) {
auto p = std::make_shared<chunk>(tmp, m_queue_id, i, m_chunk_max);
m_chunks.insert(std::make_pair(i, p));
p->load_meta();
}
LOG_INFO("init: queue started");
}
void queue::write_state()
{
m_client.create_session().write_data(m_queue_state_id,
ioremap::elliptics::data_pointer::from_raw(&m_state, sizeof(queue_state)),
0);
m_statistics.state_write_count++;
}
void queue::clear()
{
LOG_INFO("clearing queue");
LOG_INFO("erasing state");
queue_state state = m_state;
memset(&m_state, 0, sizeof(m_state));
write_state();
LOG_INFO("removing chunks, from %d to %d", state.chunk_id_ack, state.chunk_id_push);
std::map<int, shared_chunk> remove_list;
remove_list.swap(m_chunks);
remove_list.insert(m_wait_ack.cbegin(), m_wait_ack.cend());
m_wait_ack.clear();
for (auto i = remove_list.cbegin(); i != remove_list.cend(); ++i) {
int chunk_id = i->first;
auto chunk = i->second;
chunk->remove();
}
remove_list.clear();
LOG_INFO("dropping statistics");
clear_counters();
LOG_INFO("queue cleared");
}
void queue::push(const ioremap::elliptics::data_pointer &d)
{
auto found = m_chunks.find(m_state.chunk_id_push);
if (found == m_chunks.end()) {
// create new empty chunk
ioremap::elliptics::session tmp = m_client.create_session();
auto p = std::make_shared<chunk>(tmp, m_queue_id, m_state.chunk_id_push, m_chunk_max);
auto inserted = m_chunks.insert(std::make_pair(m_state.chunk_id_push, p));
found = inserted.first;
}
int chunk_id = found->first;
auto chunk = found->second;
if (chunk->push(d)) {
LOG_INFO("chunk %d filled", chunk_id);
++m_state.chunk_id_push;
write_state();
chunk->add(&m_statistics.chunks_pushed);
}
++m_statistics.push_count;
}
ioremap::elliptics::data_pointer queue::peek(entry_id *entry_id)
{
check_timeouts();
ioremap::elliptics::data_pointer d;
*entry_id = {-1, -1};
while (true) {
auto found = m_chunks.begin();
if (found == m_chunks.end()) {
break;
}
int chunk_id = found->first;
auto chunk = found->second;
entry_id->chunk = chunk_id;
d = chunk->pop(&entry_id->pos);
LOG_INFO("popping entry %d-%d (%ld)'%s'", entry_id->chunk, entry_id->pos, d.size(), d.to_string());
if (!d.empty()) {
m_statistics.pop_count++;
// set or reset timeout timer for the chunk
update_chunk_timeout(chunk_id, chunk);
}
if (chunk_id == m_state.chunk_id_push) {
break;
}
if (chunk->expect_no_more()) {
//FIXME: this could happen to be called many times for the same chunk
// (between queue restarts or because of chunk replaying)
chunk->add(&m_statistics.chunks_popped);
LOG_INFO("chunk %d exhausted, dropped from the popping line", chunk_id);
// drop chunk from the pop list
m_chunks.erase(found);
}
break;
}
return d;
}
void queue::update_chunk_timeout(int chunk_id, shared_chunk chunk)
{
// add chunk to the waiting list and postpone its deadline time
m_wait_ack.insert({chunk_id, chunk});
//TODO: make acking timeout value configurable
chunk->reset_time(5.0);
}
void queue::check_timeouts()
{
struct timeval tv;
gettimeofday(&tv, NULL);
// check no more then once in 1 second
//TODO: make timeout check interval configurable
if ((tv.tv_sec - m_last_timeout_check_time) < 1) {
return;
}
m_last_timeout_check_time = tv.tv_sec;
LOG_INFO("checking timeouts: %ld waiting chunks", m_wait_ack.size());
auto i = m_wait_ack.begin();
while (i != m_wait_ack.end()) {
int chunk_id = i->first;
auto chunk = i->second;
if (chunk->get_time() > tv.tv_sec) {
++i;
continue;
}
// Time passed but chunk still is not complete
// so we must replay unacked items from it.
LOG_ERROR("chunk %d timed out, returning back to the popping line, current time: %ld, chunk expiration time: %f",
chunk_id, tv.tv_sec, chunk->get_time());
// There are two cases when chunk can still be in m_chunks
// while experiencing a timeout:
// 1) if it's a single chunk in the queue (and serves both
// as a push and a pop/ack target)
// 2) if iteration of this chunk was preempted by other timed out chunk
// and then later this chunk timed out in its turn
// Timeout requires switch chunk's iteration into the replay mode.
auto inserted = m_chunks.insert({chunk_id, chunk});
if (!inserted.second) {
LOG_INFO("chunk %d is already in popping line", chunk_id);
} else {
LOG_INFO("chunk %d inserted back to the popping line anew", chunk_id);
}
chunk->reset_iteration();
auto hold = i;
++i;
m_wait_ack.erase(hold);
// number of popped but still unacked entries
m_statistics.timeout_count += (chunk->meta().low_mark() - chunk->meta().acked());
}
}
void queue::ack(const entry_id id)
{
auto found = m_wait_ack.find(id.chunk);
if (found == m_wait_ack.end()) {
LOG_ERROR("ack for chunk %d (pos %d) which is not in waiting list", id.chunk, id.pos);
return;
}
auto chunk = found->second;
chunk->ack(id.pos);
if (chunk->meta().acked() == chunk->meta().low_mark()) {
// Real end of the chunk's lifespan, all popped entries are acked
m_wait_ack.erase(found);
chunk->add(&m_statistics.chunks_popped);
// Chunk would be uncomplete here only if its the only chunk in the queue
// (filled partially and serving both as a push and a pop/ack target)
if (chunk->meta().complete()) {
chunk->remove();
LOG_INFO("chunk %d complete", id.chunk);
}
// Set chunk_id_ack to the lowest active chunk
//NOTE: its important to have m_chunks and m_wait_ack both sorted
m_state.chunk_id_ack = m_state.chunk_id_push;
if (!m_chunks.empty()) {
m_state.chunk_id_ack = std::min(m_state.chunk_id_ack, m_chunks.begin()->first);
}
if (!m_wait_ack.empty()) {
m_state.chunk_id_ack = std::min(m_state.chunk_id_ack, m_wait_ack.begin()->first);
}
write_state();
}
++m_statistics.ack_count;
}
ioremap::elliptics::data_pointer queue::pop()
{
entry_id id;
ioremap::elliptics::data_pointer d = peek(&id);
if (!d.empty()) {
ack(id);
}
return d;
}
data_array queue::pop(int num)
{
data_array d = peek(num);
if (!d.empty()) {
ack(d.ids());
}
return d;
}
data_array queue::peek(int num)
{
check_timeouts();
data_array ret;
while (num > 0) {
auto found = m_chunks.begin();
if (found == m_chunks.end()) {
break;
}
int chunk_id = found->first;
auto chunk = found->second;
data_array d = chunk->pop(num);
LOG_INFO("chunk %d, popping %d entries", chunk_id, d.sizes().size());
if (!d.empty()) {
m_statistics.pop_count += d.sizes().size();
ret.extend(d);
// set or reset timeout timer for the chunk
update_chunk_timeout(chunk_id, chunk);
}
if (chunk_id == m_state.chunk_id_push) {
break;
}
if (chunk->expect_no_more()) {
//FIXME: this could happen to be called many times for the same chunk
// (between queue restarts or because of chunk replaying)
chunk->add(&m_statistics.chunks_popped);
LOG_INFO("chunk %d exhausted, dropped from the popping line", chunk_id);
// drop chunk from the pop list
m_chunks.erase(found);
}
num -= d.sizes().size();
}
return ret;
}
void queue::ack(const std::vector<entry_id> &ids)
{
for (auto i = ids.begin(); i != ids.end(); ++i) {
const entry_id &id = *i;
ack(id);
}
}
void queue::reply(const ioremap::elliptics::exec_context &context,
const ioremap::elliptics::data_pointer &d, ioremap::elliptics::exec_context::final_state state)
{
m_client.create_session().reply(context, d, state);
}
void queue::final(const ioremap::elliptics::exec_context &context, const ioremap::elliptics::data_pointer &d)
{
reply(context, d, ioremap::elliptics::exec_context::final);
}
const std::string &queue::queue_id() const
{
return m_queue_id;
}
const queue_state &queue::state()
{
return m_state;
}
const queue_statistics &queue::statistics()
{
return m_statistics;
}
void queue::clear_counters()
{
memset(&m_statistics, 0, sizeof(m_statistics));
}
}} // namespace ioremap::grape
|
8aa1aa68bc2acdd4ae5c30856949f0f4acb6d5bb
|
f01adc16b5c18eba4f236b2e4e693fcbf76c25b6
|
/lab_03/Drawer/DrawerFactory/BaseDrawerCreator.h
|
5f755215d4e046d532a114334d58b9aabc3d57e3
|
[] |
no_license
|
katya-varlamova/4-sem-oop
|
e1812702c3e50b2e12ca0796133fab077999a9f9
|
366efce823e2de2a00f72a599d485dfc535f56fc
|
refs/heads/master
| 2023-06-03T10:30:59.124017
| 2021-06-22T13:05:21
| 2021-06-22T13:05:21
| 346,469,846
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 240
|
h
|
BaseDrawerCreator.h
|
#ifndef ABSTRACTDRAWFACTORY_H
#define ABSTRACTDRAWFACTORY_H
#include <memory>
#include "Drawer/BaseDrawer.h"
class BaseDrawerCreator
{
public:
virtual std::shared_ptr<BaseDrawer> createDrawer() = 0;
};
#endif // ABSTRACTDRAWFACTORY_H
|
b6b45b99d82d21e9b616f1365fcd76cfd9fc5a7b
|
075e6aad4b930c3a4ec61e0247db6b46e0248aa6
|
/Muon_Counter_ino.ino
|
1cb7c9e29e1830cd26396301e8b1f635cca14102
|
[] |
no_license
|
jmoon2610/Muon-Arduino-Code
|
6bb70f8791ca147596a1d5f85e98e513914c4d94
|
0f1241bc65647b4784150f2f4e76430f59533c4e
|
refs/heads/master
| 2021-01-10T09:53:25.476799
| 2015-12-12T19:56:39
| 2015-12-12T19:56:39
| 47,891,960
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,192
|
ino
|
Muon_Counter_ino.ino
|
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <OzOLED.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
int inputPin = 11;
int resetPin = 12;
int val = 0;
long int count = 0;
int current = 0;
int previous = 0;
static const unsigned char PROGMEM logo16_glcd_bmp[] =
{ B00000000, B11000000,
B00000001, B11000000,
B00000001, B11000000,
B00000011, B11100000,
B11110011, B11100000,
B11111110, B11111000,
B01111110, B11111111,
B00110011, B10011111,
B00011111, B11111100,
B00001101, B01110000,
B00011011, B10100000,
B00111111, B11100000,
B00111111, B11110000,
B01111100, B11110000,
B01110000, B01110000,
B00000000, B00110000 };
void setup() {
Serial.begin(9600);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.display();
delay(1000);
display.clearDisplay();
pinMode (inputPin,INPUT);
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
}
void loop() {
val = digitalRead(inputPin);
if (val == HIGH) {
current = 1;
}
else { current = 0; }
if (current != previous && current == 1) {
count +=1;
}
long int time = millis()/1000;
int seconds = time % 60;
int minutes = time/60 % 60;
int hours = time/3600;
float stdev = sqrt(count)/time;
float average = (float)count/time;
display.clearDisplay();
String currentcountstr = "Total Count:";
String currentcount = currentcountstr + " " + count ;
String runtimestr = "Run Time ";
String runtime = runtimestr + hours + ":" + minutes + ":" + seconds;
String ratestr = "Rate: ";
String pm = "+/-";
char tmp[15];
dtostrf(average,1,2,tmp);
char tmp2[15];
dtostrf(stdev,1,2,tmp2);
String rate = ratestr + tmp + " " + pm + " " + tmp2;
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println(currentcount);
display.println(runtime);
display.println("");
display.println(rate);
display.display();
previous = current;
}
|
9570609a0122a021e6b0f6f23b1999927656d9c6
|
e093de3afa04c5117290dbc05fac8c39ff144756
|
/lc/46.permutations.cpp
|
e6cd5c62776bc81afed8064d52d70a64c648f059
|
[] |
no_license
|
njzhangyifei/oj
|
25cef36f0cb1484c94ee5adf91628c7c1fef81be
|
4d0b461f5c5c7dd36af0ff3f22a39a9e8d741f9c
|
refs/heads/master
| 2020-05-30T08:46:12.255693
| 2019-08-01T02:06:21
| 2019-08-01T02:06:21
| 82,627,911
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 528
|
cpp
|
46.permutations.cpp
|
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
perm(res, nums, 0);
return res;
}
void perm(vector<vector<int>> & res, vector<int> & nums, int begin) {
if (begin >= nums.size()) {
res.push_back(nums);
return;
}
for (int i = begin; i < nums.size(); ++i) {
swap(nums[i], nums[begin]);
perm(res, nums, begin+1);
swap(nums[i], nums[begin]);
}
}
};
|
c0a8522408672f88f592466ba9b53d5892f6f8e8
|
f43ee54e7f09e81fb4af11040f314c5d6476f4d1
|
/example/FaceRecognition/KNNFaceRecognizer.cpp
|
64e6beb5095f30ab2eb8f55b1bbc49534a33256d
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
SKTT1Ryze/ML-FinalProject
|
ef7ba134a47a693cb3bb5e83a4edcb3136ebd143
|
4f0120849aaa7cdceb539e6203271155cd371f2b
|
refs/heads/master
| 2022-11-09T18:25:03.593493
| 2020-06-25T14:06:41
| 2020-06-25T14:06:41
| 268,500,151
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 82,570
|
cpp
|
KNNFaceRecognizer.cpp
|
/*
* test cpp file for SeetaFace2
* 2020/5/28
* hustccc
* Manjaro
*/
#pragma warning(disable : 4819)
#include <stdio.h>
#include <stdlib.h>
#include <seeta/FaceDetector.h>
#include <seeta/FaceLandmarker.h>
#include <seeta/FaceDatabase.h>
#include <seeta/FaceRecognizer.h>
#include <seeta/FaceEngine.h>
#include <seeta/Struct_cv.h>
#include <seeta/Struct.h>
#include <seeta/QualityAssessor.h>
//#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
//#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <array>
#include <map>
#include <iostream>
#include <fstream>
#include <ctime>
#include <vector>
#include <sys/io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <math.h>
#include <algorithm>
using namespace std;
#define K 1
#define MaxTrainImageNum 200
#define MulRate 20
#define Parameter_A 2.00
#define Parameter_C 3.00
#define Parameter_D 4
#define Parameter_gama 0.1f
#define Parameter_R 3.00
#define L 40
#define M 100
#define TRAINREADNUM 4000
#define TESTREADNUM 780
#define LFW_MAX_TRAIN_NUM 5000
#define LFW_MAX_TEST_NUM 1000
//function declartion
void HelpMenu();
void printFeature(float *feature, int size);
int WorkMode(int argc, char *argv[]);
int Mode_1();
int Mode_1_x();
int Mode_2(string predictImagePath);
int Mode_3(string option_1, string option_2);
int Mode_4();
int Mode_GUI();
int Mode_LFW();
int Mode_LFW_x();
int getAbsoluteFiles(string directory, vector<string> &filesAbsolutePath);
int compareLabel(vector<int> x, vector<int> y);
double KernelDist_1(float *x, float *y, float c, int length);
double KernelDist_2(float *x, float *y, float a, float c, int d, int length);
double KernelDist_3(float *x, float *y, float gama, int length);
double KernelDist_4(float *x, float *y, float gama, float r, int length);
double EuclideanDist(float *x, float *y, int lenght);
double ManhanttenDist(float *x, float *y, int length);
double LinearKernel(float *x, float *y, float c, int length);
double PolynomialKernel(float *x, float *y, float a, float c, int d, int length);
double RadialBasisKernel(float *x, float *y, float gama, int length);
double SigmoidKernel(float *x, float *y, float gama, float r, int length);
vector<string> KNNClassifier(vector<float *> train_data, vector<string> train_label, vector<float *> test_data, int feature_length, int k);
vector<vector<int>> KNNClassifier_x(vector<float *> train_data, vector<vector<int>> train_label, vector<float *> test_data, int feature_length, int k);
vector<int> KNNClassifier_lfw(vector<float *> train_data, vector<int> train_label, vector<float *> test_data, int feature_length, int k);
vector<int> GetKMinIndex(vector<double> distlist, int k);
int main(int argc, char *argv[])
{
int mode = WorkMode(argc, argv);
int return_status;
printf("Mode ID: [%d]\n", mode);
switch (mode)
{
case 0:
exit(-1);
return_status = -1;
break;
case -1:
HelpMenu();
return_status = -1;
break;
case 1:
printf("search\n");
//return_status = Mode_1();
return_status = Mode_1_x();
break;
case 2:
printf("Run bat\n");
return_status = Mode_2(argv[1]);
break;
case 3:
printf("calculate similarity\n");
return_status = Mode_3(argv[1], argv[2]);
break;
case -2:
return_status = Mode_GUI();
case -3:
return_status = Mode_LFW_x();
default:
exit(-1);
break;
}
printf("main exit.\n");
return return_status;
}
int WorkMode(int argc, char *argv[])
{
string help = "--help";
string gui = "--GUI";
string lfw = "--LFW";
switch (argc)
{
case 0:
printf("Error\n");
exit(-1);
return 0;
break;
case 1:
printf("Mode [1]\n");
return 1;
break;
case 2:
if (help.compare(argv[1]) == 0)
{
printf("help menu\n");
return -1;
}
else if (gui.compare(argv[1]) == 0)
{
printf("GUI Mode\n");
return -2;
}
else if (lfw.compare(argv[1]) == 0)
{
printf("LFW Mode\n");
return -3;
}
else
{
printf("Mode [2]\n");
return 2;
}
break;
case 3:
printf("Mode [3]\n");
return 3;
break;
default:
printf("too many parameter: %d\n", argc);
break;
}
return 0;
}
void HelpMenu()
{
printf("=====>help menu\n");
}
int Mode_LFW()
{
//Mode LFW
int i = 0;
int j = 0;
seeta::ModelSetting::Device device = seeta::ModelSetting::CPU;
int id = 0;
seeta::ModelSetting FD_model("./model/fd_2_00.dat", device, id);
seeta::ModelSetting PD_model("./model/pd_2_00_pts5.dat", device, id);
seeta::ModelSetting FR_model("./model/fr_2_10.dat", device, id);
seeta::FaceEngine engine(FD_model, PD_model, FR_model, 2, 16);
clock_t s, t;
double time_cost;
//prepare image store
printf("prepare pictures store...\n");
s = clock();
string ImageStoreDir = "/home/hustccc/Pictures/FaceImage/LFW_Face_DataSet/lfw/";
vector<string> TrainImagePath;
vector<int> TrainImgPathLabels;
vector<int> TrainLabels;
fstream f1("/home/hustccc/Pictures/FaceImage/LFW_Face_DataSet/TrainImgPath");
string templine;
i = 0;
while (getline(f1, templine))
{
if (templine.compare("#") == 0)
{
i++;
continue;
}
TrainImagePath.push_back(ImageStoreDir + templine);
TrainImgPathLabels.push_back(i);
}
cout << "size of train image: " << TrainImagePath.size() << endl;
cout << "first train img path: " << TrainImagePath.at(0) << endl;
vector<seeta::cv::ImageData> TrainImageList;
vector<SeetaFaceInfo> TrainFaceList;
vector<SeetaFaceInfo> tempface;
j = 0;
for (i = 0; (i < TrainImagePath.size()) && (TrainFaceList.size() < LFW_MAX_TRAIN_NUM); i++)
{
//cout << "read image: " << TrainImagePath.at(i) << endl;
TrainImageList.push_back(cv::imread(TrainImagePath.at(i)));
tempface = engine.DetectFaces(TrainImageList.at(TrainImageList.size() - 1));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TrainFaceList.push_back(tempface.at(0));
TrainLabels.push_back(TrainImgPathLabels.at(i));
}
cout << "Train Image List size: " << TrainImageList.size() << endl;
cout << "Train Faces List size: " << TrainFaceList.size() << endl;
cout << "Train Labels size: " << TrainLabels.size() << endl;
cout << "the first label: " << TrainLabels.at(0) << endl;
cout << "the second label: " << TrainLabels.at(1) << endl;
if (TrainImageList.size() != TrainFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TrainPointList;
for (i = 0; i < TrainImageList.size(); i++)
{
TrainPointList.push_back(engine.DetectPoints(TrainImageList.at(i), TrainFaceList.at(i)));
}
cout << "Train Points List size: " << TrainPointList.size() << endl;
cout << "the size of first points: " << TrainPointList.at(0).size() << endl;
//get features of image in store
printf("get features of image in store...\n");
seeta::FaceRecognizer FR(seeta::ModelSetting("./model/fr_2_10.dat"));
vector<float *> TrainFeatureList;
float *temp_float;
for (i = 0; i < TrainPointList.size(); i++)
{
temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
TrainFeatureList.push_back(temp_float);
}
for (i = 0; i < TrainPointList.size(); i++)
{
FR.Extract(TrainImageList.at(i), TrainPointList.at(i).data(), TrainFeatureList.at(i));
}
//cout << "Train Features List size: " << TrainFeatureList.size() << endl;
//cout << "the first train feature:" << endl;
//printFeature(TrainFeatureList.at(0), FR.GetExtractFeatureSize());
//cout << "the second train feature:" << endl;
//printFeature(TrainFeatureList.at(1), FR.GetExtractFeatureSize());
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare train image finish, cost: %f\n", time_cost);
s = clock();
//read test image
printf("read test image...\n");
vector<string> TestImagePath;
vector<int> TestImgPathLabels;
vector<int> TestLabels;
fstream f2("/home/hustccc/Pictures/FaceImage/LFW_Face_DataSet/TestImgPath");
i = 0;
while (getline(f2, templine))
{
TestImagePath.push_back(ImageStoreDir + templine);
TestImgPathLabels.push_back(i);
i++;
}
cout << "size of test image: " << TestImagePath.size() << endl;
cout << "first test img path: " << TestImagePath.at(0) << endl;
vector<seeta::cv::ImageData> TestImageList;
vector<SeetaFaceInfo> TestFaceList;
j = 0;
for (i = 0; (i < TestImagePath.size()) && (TestFaceList.size() < LFW_MAX_TEST_NUM); i++)
{
//cout << "read image: " << TestImagePath.at(i) << endl;
TestImageList.push_back(cv::imread(TestImagePath.at(i)));
tempface = engine.DetectFaces(TestImageList.at(j++));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TestImageList.pop_back();
j--;
cout << "read image: " << TestImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TestImageList.pop_back();
j--;
cout << "read image: " << TestImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TestFaceList.push_back(tempface.at(0));
TestLabels.push_back(TestImgPathLabels.at(i));
}
cout << "Test Image List size: " << TestImageList.size() << endl;
cout << "Test Faces List size: " << TestFaceList.size() << endl;
cout << "Test Labels size: " << TestLabels.size() << endl;
cout << "the first label: " << TestLabels.at(0) << endl;
cout << "the second label: " << TestLabels.at(1) << endl;
if (TestImageList.size() != TestFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TestPointList;
for (i = 0; i < TestImageList.size(); i++)
{
TestPointList.push_back(engine.DetectPoints(TestImageList.at(i), TestFaceList.at(i)));
}
cout << "Test Points List size: " << TestPointList.size() << endl;
cout << "the size of first points: " << TestPointList.at(0).size() << endl;
//get features of test image
printf("get features of test image...\n");
vector<float *> TestFeatureList;
for (i = 0; i < TestPointList.size(); i++)
{
temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
TestFeatureList.push_back(temp_float);
}
for (i = 0; i < TestPointList.size(); i++)
{
FR.Extract(TestImageList.at(i), TestPointList.at(i).data(), TestFeatureList.at(i));
}
//cout << "Test Features List size: " << TestFeatureList.size() << endl;
//cout << "the first test feature:" << endl;
//printFeature(TestFeatureList.at(0), FR.GetExtractFeatureSize());
//printFeature(TestFeatureList.at(1), FR.GetExtractFeatureSize());
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare test image finish, cost: %f\n", time_cost);
//printFeature(TrainFeatureList.at(0),10);
//predict with knn
/*
printf("train labels:\n");
for (i = 0; i < TrainLabels.size(); i++)
cout << TrainLabels.at(i) << " ";
cout << endl;
*/
printf("predict with knn...\n");
s = clock();
vector<int> PredictResult;
int k = 3;
PredictResult = KNNClassifier_lfw(TrainFeatureList, TrainLabels, TestFeatureList, FR.GetExtractFeatureSize(), k);
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
cout << "predict finish , cost: " << time_cost << endl;
cout << "predict result: " << endl;
for (i = 0; i < PredictResult.size(); i++)
{
cout << "[" << i << "] " << PredictResult.at(i) << " ";
if ((i + 1) % 10 == 0)
printf("\n");
}
printf("\n");
//print result
float accuracy = 0;
j = 0;
for (i = 0; i < TestLabels.size(); i++)
if (PredictResult.at(i) == TestLabels.at(i))
j++;
else
cout << "not recoginzed: " << i << " " << TestLabels.at(i) << endl;
//printf("%d %d\n",j,TestLabels.size());
accuracy = (float)j / (float)TestLabels.size();
printf("accuracy: %f\%\n", accuracy * 100);
return 0;
}
int Mode_LFW_x()
{
//Mode LFW
int i = 0;
int j = 0;
seeta::ModelSetting::Device device = seeta::ModelSetting::CPU;
int id = 0;
seeta::ModelSetting FD_model("./model/fd_2_00.dat", device, id);
seeta::ModelSetting PD_model("./model/pd_2_00_pts5.dat", device, id);
seeta::ModelSetting FR_model("./model/fr_2_10.dat", device, id);
seeta::FaceEngine engine(FD_model, PD_model, FR_model, 2, 16);
clock_t s, t;
double time_cost;
//prepare image store
printf("prepare pictures store...\n");
s = clock();
string ImageStoreDir = "/home/hustccc/Pictures/FaceImage/LFW_Face_DataSet/lfw/";
vector<string> TrainImagePath;
vector<string> TrainLabels;
fstream f1("/home/hustccc/Pictures/FaceImage/LFW_Face_DataSet/TrainImgPath");
string templine;
i = 0;
while (getline(f1, templine))
{
if (templine.compare("#") == 0)
{
i++;
continue;
}
TrainImagePath.push_back(ImageStoreDir + templine);
}
cout << "size of train image: " << TrainImagePath.size() << endl;
cout << "first train img path: " << TrainImagePath.at(0) << endl;
vector<seeta::cv::ImageData> TrainImageList;
vector<SeetaFaceInfo> TrainFaceList;
vector<SeetaFaceInfo> tempface;
int temp_index_1;
int temp_index_2;
j = 0;
for (i = 0; (i < TrainImagePath.size()) && (TrainFaceList.size() < LFW_MAX_TRAIN_NUM); i++)
{
//cout << "read image: " << TrainImagePath.at(i) << endl;
TrainImageList.push_back(cv::imread(TrainImagePath.at(i)));
tempface = engine.DetectFaces(TrainImageList.at(TrainImageList.size() - 1));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TrainFaceList.push_back(tempface.at(0));
temp_index_1 = TrainImagePath.at(i).find_last_of("/");
temp_index_2 = TrainImagePath.at(i).find_first_of("_", temp_index_1);
TrainLabels.push_back(TrainImagePath.at(i).substr(temp_index_1 + 1, temp_index_2 - temp_index_1 - 1));
}
cout << "Train Image List size: " << TrainImageList.size() << endl;
cout << "Train Faces List size: " << TrainFaceList.size() << endl;
cout << "Train Labels size: " << TrainLabels.size() << endl;
cout << "the first label: " << TrainLabels.at(0) << endl;
cout << "the second label: " << TrainLabels.at(1) << endl;
for (i = 0; i < TrainLabels.size(); i++)
{
cout << "[" << i << "]"
<< " " << TrainLabels.at(i) << "\t";
if ((i % 10 == 0) && (i != 0))
printf("\n");
}
if (TrainImageList.size() != TrainFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TrainPointList;
for (i = 0; i < TrainImageList.size(); i++)
{
TrainPointList.push_back(engine.DetectPoints(TrainImageList.at(i), TrainFaceList.at(i)));
}
cout << "Train Points List size: " << TrainPointList.size() << endl;
cout << "the size of first points: " << TrainPointList.at(0).size() << endl;
//get features of image in store
printf("get features of image in store...\n");
seeta::FaceRecognizer FR(seeta::ModelSetting("./model/fr_2_10.dat"));
vector<float *> TrainFeatureList;
float *temp_float;
for (i = 0; i < TrainPointList.size(); i++)
{
temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
TrainFeatureList.push_back(temp_float);
}
for (i = 0; i < TrainPointList.size(); i++)
{
FR.Extract(TrainImageList.at(i), TrainPointList.at(i).data(), TrainFeatureList.at(i));
}
//cout << "Train Features List size: " << TrainFeatureList.size() << endl;
//cout << "the first train feature:" << endl;
//printFeature(TrainFeatureList.at(0), FR.GetExtractFeatureSize());
//cout << "the second train feature:" << endl;
//printFeature(TrainFeatureList.at(1), FR.GetExtractFeatureSize());
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare train image finish, cost: %f\n", time_cost);
s = clock();
//read test image
printf("read test image...\n");
vector<string> TestImagePath;
vector<string> TestLabels;
fstream f2("/home/hustccc/Pictures/FaceImage/LFW_Face_DataSet/TestImgPath");
i = 0;
while (getline(f2, templine))
{
TestImagePath.push_back(ImageStoreDir + templine);
i++;
}
cout << "size of test image: " << TestImagePath.size() << endl;
cout << "first test img path: " << TestImagePath.at(0) << endl;
vector<seeta::cv::ImageData> TestImageList;
vector<SeetaFaceInfo> TestFaceList;
j = 0;
for (i = 0; (i < TestImagePath.size()) && (TestFaceList.size() < LFW_MAX_TEST_NUM); i++)
{
//cout << "read image: " << TestImagePath.at(i) << endl;
TestImageList.push_back(cv::imread(TestImagePath.at(i)));
tempface = engine.DetectFaces(TestImageList.at(j++));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TestImageList.pop_back();
j--;
cout << "read image: " << TestImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TestImageList.pop_back();
j--;
cout << "read image: " << TestImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TestFaceList.push_back(tempface.at(0));
temp_index_1 = TestImagePath.at(i).find_last_of("/");
temp_index_2 = TestImagePath.at(i).find_first_of("_", temp_index_1);
TestLabels.push_back(TestImagePath.at(i).substr(temp_index_1 + 1, temp_index_2 - temp_index_1 - 1));
}
cout << "Test Image List size: " << TestImageList.size() << endl;
cout << "Test Faces List size: " << TestFaceList.size() << endl;
cout << "Test Labels size: " << TestLabels.size() << endl;
cout << "the first label: " << TestLabels.at(0) << endl;
cout << "the second label: " << TestLabels.at(1) << endl;
for (i = 0; i < TestLabels.size(); i++)
{
cout << "[" << i << "]"
<< " " << TestLabels.at(i) << "\t";
if ((i % 10 == 0) && (i != 0))
printf("\n");
}
if (TestImageList.size() != TestFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TestPointList;
for (i = 0; i < TestImageList.size(); i++)
{
TestPointList.push_back(engine.DetectPoints(TestImageList.at(i), TestFaceList.at(i)));
}
cout << "Test Points List size: " << TestPointList.size() << endl;
cout << "the size of first points: " << TestPointList.at(0).size() << endl;
//get features of test image
printf("get features of test image...\n");
vector<float *> TestFeatureList;
for (i = 0; i < TestPointList.size(); i++)
{
temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
TestFeatureList.push_back(temp_float);
}
for (i = 0; i < TestPointList.size(); i++)
{
FR.Extract(TestImageList.at(i), TestPointList.at(i).data(), TestFeatureList.at(i));
}
//cout << "Test Features List size: " << TestFeatureList.size() << endl;
//cout << "the first test feature:" << endl;
//printFeature(TestFeatureList.at(0), FR.GetExtractFeatureSize());
//printFeature(TestFeatureList.at(1), FR.GetExtractFeatureSize());
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare test image finish, cost: %f\n", time_cost);
//printFeature(TrainFeatureList.at(0),10);
//predict with knn
/*
printf("train labels:\n");
for (i = 0; i < TrainLabels.size(); i++)
cout << TrainLabels.at(i) << " ";
cout << endl;
*/
printf("predict with knn...\n");
s = clock();
vector<string> PredictResult;
int k = K;
PredictResult = KNNClassifier(TrainFeatureList, TrainLabels, TestFeatureList, FR.GetExtractFeatureSize(), k);
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
cout << "predict finish , cost: " << time_cost << endl;
cout << "predict result: " << endl;
for (i = 0; i < PredictResult.size(); i++)
{
cout << "[" << i << "] " << PredictResult.at(i) << " ";
if ((i + 1) % 10 == 0)
printf("\n");
}
printf("\n");
//print result
float accuracy = 0;
j = 0;
for (i = 0; i < TestLabels.size(); i++)
if (PredictResult.at(i) == TestLabels.at(i))
j++;
else
cout << "not recoginzed: " << i << " " << TestLabels.at(i) << endl;
//printf("%d %d\n",j,TestLabels.size());
accuracy = (float)j / (float)TestLabels.size();
printf("accuracy: %f\%\n", accuracy * 100);
return 0;
}
int Mode_GUI()
{
int i, j;
seeta::ModelSetting::Device device = seeta::ModelSetting::CPU;
int id = 0;
seeta::ModelSetting FD_model("./model/fd_2_00.dat", device, id);
seeta::ModelSetting PD_model("./model/pd_2_00_pts5.dat", device, id);
seeta::ModelSetting FR_model("./model/fr_2_10.dat", device, id);
seeta::FaceEngine engine(FD_model, PD_model, FR_model, 2, 16);
seeta::QualityAssessor QA;
clock_t s, t;
double time_cost;
// recognization threshold
float threshold = 0.7f;
//set face detector's min face size
engine.FD.set(seeta::FaceDetector::PROPERTY_MIN_FACE_SIZE, 80);
//prepare image store
printf("prepare pictures store...\n");
s = clock();
string ImageStoreDir = "/home/hustccc/Pictures/FaceImage/Train_01/";
vector<string> TrainImagePath;
vector<string> TrainLabels;
if (getAbsoluteFiles(ImageStoreDir, TrainImagePath) != 0)
{
printf("read train image error\n");
exit(-1);
}
//log
//cout << "size of train image: " << TrainImagePath.size() << endl;
//cout << "the first train image: " << TrainImagePath.at(0) << endl;
vector<seeta::cv::ImageData> TrainImageList;
vector<SeetaFaceInfo> TrainFaceList;
vector<SeetaFaceInfo> tempface;
j = 0;
for (i = 0; i < TrainImagePath.size(); i++)
{
//cout << "read image: " << TrainImagePath.at(i) << endl;
TrainImageList.push_back(cv::imread(TrainImagePath.at(i)));
tempface = engine.DetectFaces(TrainImageList.at(TrainImageList.size() - 1));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TrainFaceList.push_back(tempface.at(0));
//TrainLabels.push_back(TrainImagePath.at(i).substr(TrainImagePath.at(i).size() - 7, 3));
TrainLabels.push_back(TrainImagePath.at(i).substr(TrainImagePath.at(i).size() - 6, 2));
}
cout << "train data size: " << TrainFaceList.size() << endl;
/*
cout << "Train Image List size: " << TrainImageList.size() << endl;
cout << "Train Faces List size: " << TrainFaceList.size() << endl;
cout << "Train Labels size: " << TrainLabels.size() << endl;
cout << "the first label: " << TrainLabels.at(0) << endl;
cout << "the second label: " << TrainLabels.at(1) << endl;
*/
if (TrainImageList.size() != TrainFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TrainPointList;
for (i = 0; i < TrainImageList.size(); i++)
{
TrainPointList.push_back(engine.DetectPoints(TrainImageList.at(i), TrainFaceList.at(i)));
}
//cout << "Train Points List size: " << TrainPointList.size() << endl;
//cout << "the size of first points: " << TrainPointList.at(0).size() << endl;
//get features of image in store
printf("get features of image in store...\n");
seeta::FaceRecognizer FR(seeta::ModelSetting("./model/fr_2_10.dat"));
vector<float *> TrainFeatureList;
float *temp_float;
for (i = 0; i < TrainPointList.size(); i++)
{
temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
TrainFeatureList.push_back(temp_float);
}
for (i = 0; i < TrainPointList.size(); i++)
{
FR.Extract(TrainImageList.at(i), TrainPointList.at(i).data(), TrainFeatureList.at(i));
}
//cout << "Train Features List size: " << TrainFeatureList.size() << endl;
/*
cout << "the first train feature:" << endl;
printFeature(TrainFeatureList.at(0), FR.GetExtractFeatureSize());
cout << "the second train feature:" << endl;
printFeature(TrainFeatureList.at(1), FR.GetExtractFeatureSize());
*/
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare train image finish, cost: %f\n", time_cost);
printf("open camera...\n");
cv::VideoCapture capture;
capture.open(0);
cv::Mat frame;
vector<string> PredictResult;
string predictName;
while (capture.isOpened())
{
capture >> frame;
if (frame.empty())
continue;
seeta::cv::ImageData predictImage = frame;
vector<SeetaFaceInfo> predictfaces = engine.DetectFaces(predictImage);
if (predictfaces.size() != 1)
{
printf("no face or have more than one faces...continue...\n");
continue;
}
vector<SeetaPointF> predictpoints = engine.DetectPoints(predictImage, predictfaces.at(0));
int64_t index = -1;
cv::rectangle(frame, cv::Rect(predictfaces.at(0).pos.x, predictfaces.at(0).pos.y, predictfaces.at(0).pos.width, predictfaces.at(0).pos.height), CV_RGB(128, 128, 255), 3);
for (i = 0; i < predictpoints.size(); i++)
{
auto &point = predictpoints[i];
cv::circle(frame, cv::Point(int(point.x), int(point.y)), 2, CV_RGB(128, 255, 128), -1);
}
//get features fo predictImage
//seeta::FaceRecognizer FR(seeta::ModelSetting("./model/fr_2_10.dat"));
vector<float *> predictFeature;
predictFeature.push_back((float *)malloc(sizeof(float) * FR.GetExtractFeatureSize()));
FR.Extract(predictImage, predictpoints.data(), predictFeature.at(0));
int k = 1;
PredictResult = KNNClassifier(TrainFeatureList, TrainLabels, predictFeature, FR.GetExtractFeatureSize(), k);
//cout<<"predict result: "<<PredictResult.at(0)<<endl;
if (PredictResult.at(0) == "00")
{
predictName = "chechunchi";
}
else if (PredictResult.at(0) == "01")
{
predictName = "Messi";
}
else if (PredictResult.at(0) == "02")
{
predictName = "Faker";
}
else if (PredictResult.at(0) == "03")
{
predictName = "theshy";
}
else if (PredictResult.at(0) == "04")
{
predictName = "777";
}
else if (PredictResult.at(0) == "05")
{
predictName = "knight";
}
else if (PredictResult.at(0) == "06")
{
predictName = "uzi";
}
else if (PredictResult.at(0) == "07")
{
predictName = "scout";
}
else if (PredictResult.at(0) == "08")
{
predictName = "smlz";
}
else if (PredictResult.at(0) == "09")
{
predictName = "jackelove";
}
else if (PredictResult.at(0) == "10")
{
predictName = "luweiqin";
}
else if (PredictResult.at(0) == "11")
{
predictName = "cheqixian";
}
else
{
predictName = "None";
}
cv::putText(frame, predictName, cv::Point(predictfaces.at(0).pos.x, predictfaces.at(0).pos.y - 5), 3, 1, CV_RGB(255, 128, 128));
cv::imshow("Frame", frame);
PredictResult.clear();
auto key = cv::waitKey(20);
if (key == 27)
{
break;
}
}
return 0;
}
int Mode_1()
{
//Mode 1
int i = 0;
int j = 0;
seeta::ModelSetting::Device device = seeta::ModelSetting::CPU;
int id = 0;
seeta::ModelSetting FD_model("./model/fd_2_00.dat", device, id);
seeta::ModelSetting PD_model("./model/pd_2_00_pts5.dat", device, id);
seeta::ModelSetting FR_model("./model/fr_2_10.dat", device, id);
seeta::FaceEngine engine(FD_model, PD_model, FR_model, 2, 16);
clock_t s, t;
double time_cost;
//prepare image store
printf("prepare pictures store...\n");
s = clock();
string ImageStoreDir = "/home/hustccc/Pictures/FaceImage/Train_01/";
vector<string> TrainImagePath;
vector<string> TrainLabels;
if (getAbsoluteFiles(ImageStoreDir, TrainImagePath) != 0)
{
printf("read train image error\n");
exit(-1);
}
//log
//cout << "size of train image: " << TrainImagePath.size() << endl;
//cout << "the first train image: " << TrainImagePath.at(0) << endl;
vector<seeta::cv::ImageData> TrainImageList;
vector<SeetaFaceInfo> TrainFaceList;
vector<SeetaFaceInfo> tempface;
j = 0;
for (i = 0; i < TrainImagePath.size(); i++)
{
//cout << "read image: " << TrainImagePath.at(i) << endl;
TrainImageList.push_back(cv::imread(TrainImagePath.at(i)));
tempface = engine.DetectFaces(TrainImageList.at(TrainImageList.size() - 1));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TrainFaceList.push_back(tempface.at(0));
//TrainLabels.push_back(TrainImagePath.at(i).substr(TrainImagePath.at(i).size() - 7, 3));
TrainLabels.push_back(TrainImagePath.at(i).substr(TrainImagePath.at(i).size() - 6, 2));
}
cout << "train data size: " << TrainFaceList.size() << endl;
/*
cout << "Train Image List size: " << TrainImageList.size() << endl;
cout << "Train Faces List size: " << TrainFaceList.size() << endl;
cout << "Train Labels size: " << TrainLabels.size() << endl;
cout << "the first label: " << TrainLabels.at(0) << endl;
cout << "the second label: " << TrainLabels.at(1) << endl;
*/
if (TrainImageList.size() != TrainFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TrainPointList;
for (i = 0; i < TrainImageList.size(); i++)
{
TrainPointList.push_back(engine.DetectPoints(TrainImageList.at(i), TrainFaceList.at(i)));
}
//cout << "Train Points List size: " << TrainPointList.size() << endl;
//cout << "the size of first points: " << TrainPointList.at(0).size() << endl;
//get features of image in store
printf("get features of image in store...\n");
seeta::FaceRecognizer FR(seeta::ModelSetting("./model/fr_2_10.dat"));
vector<float *> TrainFeatureList;
float *temp_float;
for (i = 0; i < TrainPointList.size(); i++)
{
temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
TrainFeatureList.push_back(temp_float);
}
for (i = 0; i < TrainPointList.size(); i++)
{
FR.Extract(TrainImageList.at(i), TrainPointList.at(i).data(), TrainFeatureList.at(i));
}
//cout << "Train Features List size: " << TrainFeatureList.size() << endl;
/*
cout << "the first train feature:" << endl;
printFeature(TrainFeatureList.at(0), FR.GetExtractFeatureSize());
cout << "the second train feature:" << endl;
printFeature(TrainFeatureList.at(1), FR.GetExtractFeatureSize());
*/
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare train image finish, cost: %f\n", time_cost);
s = clock();
//read test image
printf("read test image...\n");
string TestImageDir = "/home/hustccc/Pictures/FaceImage/Test_01/";
vector<string> TestImagePath;
vector<string> TestLabels;
if (getAbsoluteFiles(TestImageDir, TestImagePath) != 0)
{
printf("read test image error\n");
exit(-1);
}
//log
//cout << "size of test image: " << TestImagePath.size() << endl;
//cout << "the first test image: " << TestImagePath.at(0) << endl;
vector<seeta::cv::ImageData> TestImageList;
vector<SeetaFaceInfo> TestFaceList;
j = 0;
for (i = 0; i < TestImagePath.size(); i++)
{
//cout << "read image: " << TestImagePath.at(i) << endl;
TestImageList.push_back(cv::imread(TestImagePath.at(i)));
tempface = engine.DetectFaces(TestImageList.at(j++));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TestImageList.pop_back();
j--;
cout << "read image: " << TestImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TestImageList.pop_back();
j--;
cout << "read image: " << TestImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TestFaceList.push_back(tempface.at(0));
//TestLabels.push_back(TestImagePath.at(i).substr(TestImagePath.at(i).size() - 7, 3));
TestLabels.push_back(TestImagePath.at(i).substr(TestImagePath.at(i).size() - 6, 2));
//cout<<"["<<j-1<<"] "<<TestImagePath.at(i)<<endl;
}
cout << "test data size: " << TestFaceList.size() << endl;
//cout << "Test Image List size: " << TestImageList.size() << endl;
//cout << "Test Faces List size: " << TestFaceList.size() << endl;
if (TestImageList.size() != TestFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TestPointList;
for (i = 0; i < TestImageList.size(); i++)
{
TestPointList.push_back(engine.DetectPoints(TestImageList.at(i), TestFaceList.at(i)));
}
//cout << "Train Points List size: " << TestPointList.size() << endl;
//cout << "the size of first points: " << TestPointList.at(0).size() << endl;
//get features of test image
printf("get features of test image...\n");
vector<float *> TestFeatureList;
for (i = 0; i < TestPointList.size(); i++)
{
temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
TestFeatureList.push_back(temp_float);
}
for (i = 0; i < TestPointList.size(); i++)
{
FR.Extract(TestImageList.at(i), TestPointList.at(i).data(), TestFeatureList.at(i));
}
//cout << "Test Features List size: " << TestFeatureList.size() << endl;
/*
cout << "the first test feature:" << endl;
printFeature(TestFeatureList.at(0), FR.GetExtractFeatureSize());
printFeature(TestFeatureList.at(1), FR.GetExtractFeatureSize());
*/
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare test image finish, cost: %f\n", time_cost);
//printFeature(TrainFeatureList.at(0),10);
//predict with knn
/*
printf("train labels:\n");
for (i = 0; i < TrainLabels.size(); i++)
cout << TrainLabels.at(i) << " ";
cout << endl;
*/
printf("predict with knn...\n");
s = clock();
vector<string> PredictResult;
int k = 3;
PredictResult = KNNClassifier(TrainFeatureList, TrainLabels, TestFeatureList, FR.GetExtractFeatureSize(), k);
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
cout << "predict finish , cost: " << time_cost << endl;
cout << "predict result: " << endl;
for (i = 0; i < PredictResult.size(); i++)
{
cout << "[" << i << "] " << PredictResult.at(i) << " ";
if ((i + 1) % 10 == 0)
printf("\n");
}
printf("\n");
//print result
float accuracy = 0;
j = 0;
for (i = 0; i < TestLabels.size(); i++)
if (PredictResult.at(i) == TestLabels.at(i))
j++;
else
cout << "not recoginzed: " << i << " " << TestLabels.at(i) << endl;
//printf("%d %d\n",j,TestLabels.size());
accuracy = (float)j / (float)TestLabels.size();
printf("accuracy: %f\%\n", accuracy * 100);
return 0;
}
int Mode_1_x()
{
//Mode 1 x
int i = 0;
int j = 0;
seeta::ModelSetting::Device device = seeta::ModelSetting::CPU;
int id = 0;
seeta::ModelSetting FD_model("./model/fd_2_00.dat", device, id);
seeta::ModelSetting PD_model("./model/pd_2_00_pts5.dat", device, id);
seeta::ModelSetting FR_model("./model/fr_2_10.dat", device, id);
seeta::FaceEngine engine(FD_model, PD_model, FR_model, 2, 16);
clock_t s, t;
double time_cost;
//prepare image store
printf("prepare pictures store...\n");
s = clock();
string ImageStoreDir = "/home/hustccc/Pictures/FaceImage/CelebA/img_align_celeba/";
vector<string> TrainImagePath;
//vector<string> TrainLabels;
//cout << "size of train image: " << TrainImagePath.size() << endl;
//cout << "the first train image: " << TrainImagePath.at(0) << endl;
char trainfilename[M] = "/home/hustccc/Pictures/FaceImage/CelebA/celeba_train_labels";
//char trainfilename[M] = "/home/hustccc/Pictures/FaceImage/CelebA/trainLabels";
char temp[M] = {};
char block;
vector<vector<int>> TrainLabels;
vector<int> line;
FILE *fp = fopen(trainfilename, "r");
for (i = 0; i < TRAINREADNUM; i++)
{
line.clear();
//cout<<"i: "<<i<<endl;
for (j = 0; j < 41; j++)
{
if (j == 0)
{
fread(temp, sizeof(char), 10, fp); //read image name
TrainImagePath.push_back(temp);
//fread(&block,sizeof(char),1,fp); //read block
}
else
{
fread(temp, sizeof(char), 1, fp);
if (temp[0] == 49)
{
//printf("1 ");
line.push_back(1);
}
else
{
//printf("0 ");
line.push_back(0);
}
//fread(&block,sizeof(char),1,fp); //read block
}
}
fread(&block, sizeof(char), 2, fp); //read block
TrainLabels.push_back(line);
}
fclose(fp);
cout << endl;
cout << "ImagePathList size: " << TrainImagePath.size() << endl;
cout << "LabelsList size: " << TrainLabels.size() << endl;
cout << "line size: " << TrainLabels.at(0).size() << endl;
for (i = 0; i < TRAINREADNUM; i++)
{
cout << TrainImagePath.at(i) << ": ";
for (j = 0; j < 40; j++)
{
cout << TrainLabels.at(i).at(j) << " ";
}
printf("\n");
}
printf("\n");
vector<seeta::cv::ImageData> TrainImageList;
vector<SeetaFaceInfo> TrainFaceList;
vector<SeetaFaceInfo> tempface;
j = 0;
for (i = 0; i < TrainImagePath.size(); i++)
{
//cout << "read image: " << TrainImagePath.at(i) << endl;
TrainImageList.push_back(cv::imread(ImageStoreDir + TrainImagePath.at(i)));
tempface = engine.DetectFaces(TrainImageList.at(TrainImageList.size() - 1));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TrainFaceList.push_back(tempface.at(0));
//TrainLabels.push_back(TrainImagePath.at(i).substr(TrainImagePath.at(i).size() - 7, 3));
//TrainLabels.push_back(TrainImagePath.at(i).substr(TrainImagePath.at(i).size() - 5, 1));
}
cout << "train data size: " << TrainFaceList.size() << endl;
cout << "Train Image List size: " << TrainImageList.size() << endl;
cout << "Train Faces List size: " << TrainFaceList.size() << endl;
if (TrainImageList.size() != TrainFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TrainPointList;
for (i = 0; i < TrainImageList.size(); i++)
{
TrainPointList.push_back(engine.DetectPoints(TrainImageList.at(i), TrainFaceList.at(i)));
}
//cout << "Train Points List size: " << TrainPointList.size() << endl;
//cout << "the size of first points: " << TrainPointList.at(0).size() << endl;
//get features of image in store
printf("get features of image in store...\n");
//seeta::FaceRecognizer FR(seeta::ModelSetting("./model/fr_2_10.dat"));
seeta::FaceRecognizer FR(FR_model);
vector<float *> TrainFeatureList;
float *temp_float;
for (i = 0; i < TrainPointList.size(); i++)
{
//temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
temp_float = new float[sizeof(float) * FR.GetExtractFeatureSize()];
if (temp_float == NULL)
{
printf("new space error\n");
exit(-1);
}
TrainFeatureList.push_back(temp_float);
}
for (i = 0; i < TrainPointList.size(); i++)
{
FR.Extract(TrainImageList.at(i), TrainPointList.at(i).data(), TrainFeatureList.at(i));
}
cout << "Train Features List size: " << TrainFeatureList.size() << endl;
//cout << "the first train feature:" << endl;
//printFeature(TrainFeatureList.at(0), FR.GetExtractFeatureSize());
//cout << "the second train feature:" << endl;
//printFeature(TrainFeatureList.at(1), FR.GetExtractFeatureSize());
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare train image finish, cost: %f\n", time_cost);
//prepare test image
printf("prepare test image...\n");
s = clock();
vector<string> TestImagePath;
char testfilename[M] = "/home/hustccc/Pictures/FaceImage/CelebA/celeba_test_labels";
//char testfilename[M] = "/home/hustccc/Pictures/FaceImage/CelebA/testLabels";
vector<vector<int>> TestLabels;
FILE *fb = fopen(testfilename, "r");
for (i = 0; i < TESTREADNUM; i++)
{
line.clear();
//cout<<"i: "<<i<<endl;
for (j = 0; j < 41; j++)
{
if (j == 0)
{
fread(temp, sizeof(char), 10, fb); //read image name
TestImagePath.push_back(temp);
//fread(&block,sizeof(char),1,fp); //read block
}
else
{
fread(temp, sizeof(char), 1, fb);
if (temp[0] == 49)
{
printf("1 ");
line.push_back(1);
}
else
{
printf("0 ");
line.push_back(0);
}
//fread(&block,sizeof(char),1,fp); //read block
}
}
fread(&block, sizeof(char), 2, fb); //read block
TestLabels.push_back(line);
}
fclose(fb);
cout << endl;
cout << "ImagePathList size: " << TestImagePath.size() << endl;
cout << "LabelsList size: " << TestLabels.size() << endl;
cout << "line size: " << TestLabels.at(0).size() << endl;
/*
for (i = 0; i < TESTREADNUM; i++)
{
cout << TestImagePath.at(i) << ": ";
for (j = 0; j < 40; j++)
{
cout << TestLabels.at(i).at(j) << " ";
}
printf("\n");
}*/
printf("\n");
vector<seeta::cv::ImageData> TestImageList;
vector<SeetaFaceInfo> TestFaceList;
j = 0;
for (i = 0; i < TestImagePath.size(); i++)
{
//cout << "read image: " << TestImagePath.at(i) << endl;
TestImageList.push_back(cv::imread(ImageStoreDir + TestImagePath.at(i)));
tempface = engine.DetectFaces(TestImageList.at(TestImageList.size() - 1));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TestImageList.pop_back();
j--;
cout << "read image: " << TestImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TestImageList.pop_back();
j--;
cout << "read image: " << TestImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TestFaceList.push_back(tempface.at(0));
}
cout << "test data size: " << TestFaceList.size() << endl;
cout << "Test Image List size: " << TestImageList.size() << endl;
cout << "Test Faces List size: " << TestFaceList.size() << endl;
if (TestImageList.size() != TestFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TestPointList;
for (i = 0; i < TestImageList.size(); i++)
{
TestPointList.push_back(engine.DetectPoints(TestImageList.at(i), TestFaceList.at(i)));
}
cout << "Test Points List size: " << TestPointList.size() << endl;
cout << "the size of first points: " << TestPointList.at(0).size() << endl;
//get features of test image
printf("get features of test image ...\n");
//seeta::FaceRecognizer FM(seeta::ModelSetting("./model/fr_2_10.dat"));
seeta::FaceRecognizer FM(FR_model);
//cout<<FM.GetExtractFeatureSize()<<endl;
vector<float *> TestFeatureList;
for (j = 0; j < TestPointList.size(); j++)
{
//temp_float = (float *)malloc(sizeof(float) * FM.GetExtractFeatureSize());
temp_float = new float[FM.GetExtractFeatureSize() * sizeof(float)];
if (temp_float == NULL)
{
printf("new space error\n");
exit(-1);
}
TestFeatureList.push_back(temp_float);
}
for (i = 0; i < TestPointList.size(); i++)
{
FM.Extract(TestImageList.at(i), TestPointList.at(i).data(), TestFeatureList.at(i));
}
cout << "Test Features List size: " << TestFeatureList.size() << endl;
//cout << "the first test feature:" << endl;
//printFeature(TestFeatureList.at(0), FM.GetExtractFeatureSize());
//cout << "the second test feature:" << endl;
//printFeature(TestFeatureList.at(1), FM.GetExtractFeatureSize());
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare test image finish, cost: %f\n", time_cost);
printf("predict with knn...\n");
s = clock();
vector<vector<int>> PredictResult;
int k = K;
PredictResult = KNNClassifier_x(TrainFeatureList, TrainLabels, TestFeatureList, FM.GetExtractFeatureSize(), k);
printf("ok here\n");
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
cout << "predict finish , cost: " << time_cost << endl;
cout << "predict result: " << endl;
/*
for (i = 0; i < PredictResult.size(); i++)
{
cout << "[" << i << "] ";
for (j = 0; j < PredictResult.at(i).size(); j++)
cout << PredictResult.at(i).at(j) << " ";
printf("\n");
}*/
printf("\n");
//print result
float accuracy = 0;
j = 0;
int num = 0;
cout << "PredictResult size: " << PredictResult.size() << endl;
for (i = 0; i < PredictResult.size(); i++)
num += compareLabel(PredictResult.at(i), TestLabels.at(i));
printf("num: %d\n", num);
accuracy = (float)num / (float)(PredictResult.size() * PredictResult.at(0).size());
printf("accuracy: %f\%\n", accuracy * 100);
/*
for(i=0;i<PredictResult.size();i++)
{
if(compareLabel(PredictResult.at(i),TestLabels.at(i))>=35)
num++;
}
accuracy=(float)num/(float)PredictResult.size();
printf("accuracy: %f\%\n", accuracy * 100);*/
exit(-1);
return 0;
}
int Mode_2(string predictImagePath)
{
//Mode 2
//Mode 1 x
int i = 0;
int j = 0;
seeta::ModelSetting::Device device = seeta::ModelSetting::CPU;
int id = 0;
seeta::ModelSetting FD_model("./model/fd_2_00.dat", device, id);
seeta::ModelSetting PD_model("./model/pd_2_00_pts81.dat", device, id);
seeta::ModelSetting FR_model("./model/fr_2_10.dat", device, id);
seeta::FaceEngine engine(FD_model, PD_model, FR_model, 2, 16);
clock_t s, t;
double time_cost;
//prepare image store
printf("prepare pictures store...\n");
s = clock();
string ImageStoreDir = "/home/hustccc/Pictures/FaceImage/CelebA/img_align_celeba/";
vector<string> TrainImagePath;
//vector<string> TrainLabels;
//cout << "size of train image: " << TrainImagePath.size() << endl;
//cout << "the first train image: " << TrainImagePath.at(0) << endl;
char trainfilename[M] = "/home/hustccc/Pictures/FaceImage/CelebA/celeba_train_labels";
char temp[M] = {};
char block;
vector<vector<int>> TrainLabels;
vector<int> line;
FILE *fp = fopen(trainfilename, "r");
for (i = 0; i < TRAINREADNUM; i++)
{
line.clear();
//cout<<"i: "<<i<<endl;
for (j = 0; j < 41; j++)
{
if (j == 0)
{
fread(temp, sizeof(char), 10, fp); //read image name
TrainImagePath.push_back(temp);
//fread(&block,sizeof(char),1,fp); //read block
}
else
{
fread(temp, sizeof(char), 1, fp);
if (temp[0] == 49)
{
printf("1 ");
line.push_back(1);
}
else
{
printf("0 ");
line.push_back(0);
}
//fread(&block,sizeof(char),1,fp); //read block
}
}
fread(&block, sizeof(char), 2, fp); //read block
TrainLabels.push_back(line);
}
fclose(fp);
cout << endl;
cout << "ImagePathList size: " << TrainImagePath.size() << endl;
cout << "LabelsList size: " << TrainLabels.size() << endl;
cout << "line size: " << TrainLabels.at(0).size() << endl;
for (i = 0; i < TRAINREADNUM; i++)
{
cout << TrainImagePath.at(i) << ": ";
for (j = 0; j < 40; j++)
{
cout << TrainLabels.at(i).at(j) << " ";
}
printf("\n");
}
printf("\n");
vector<seeta::cv::ImageData> TrainImageList;
vector<SeetaFaceInfo> TrainFaceList;
vector<SeetaFaceInfo> tempface;
j = 0;
for (i = 0; i < TrainImagePath.size(); i++)
{
//cout << "read image: " << TrainImagePath.at(i) << endl;
TrainImageList.push_back(cv::imread(ImageStoreDir + TrainImagePath.at(i)));
tempface = engine.DetectFaces(TrainImageList.at(TrainImageList.size() - 1));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TrainFaceList.push_back(tempface.at(0));
//TrainLabels.push_back(TrainImagePath.at(i).substr(TrainImagePath.at(i).size() - 7, 3));
//TrainLabels.push_back(TrainImagePath.at(i).substr(TrainImagePath.at(i).size() - 5, 1));
}
cout << "train data size: " << TrainFaceList.size() << endl;
cout << "Train Image List size: " << TrainImageList.size() << endl;
cout << "Train Faces List size: " << TrainFaceList.size() << endl;
if (TrainImageList.size() != TrainFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TrainPointList;
for (i = 0; i < TrainImageList.size(); i++)
{
TrainPointList.push_back(engine.DetectPoints(TrainImageList.at(i), TrainFaceList.at(i)));
}
//cout << "Train Points List size: " << TrainPointList.size() << endl;
//cout << "the size of first points: " << TrainPointList.at(0).size() << endl;
//get features of image in store
printf("get features of image in store...\n");
//seeta::FaceRecognizer FR(seeta::ModelSetting("./model/fr_2_10.dat"));
seeta::FaceRecognizer FR(FR_model);
vector<float *> TrainFeatureList;
float *temp_float;
for (i = 0; i < TrainPointList.size(); i++)
{
//temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
temp_float = new float[sizeof(float) * FR.GetExtractFeatureSize()];
if (temp_float == NULL)
{
printf("new space error\n");
exit(-1);
}
TrainFeatureList.push_back(temp_float);
}
for (i = 0; i < TrainPointList.size(); i++)
{
FR.Extract(TrainImageList.at(i), TrainPointList.at(i).data(), TrainFeatureList.at(i));
}
cout << "Train Features List size: " << TrainFeatureList.size() << endl;
//cout << "the first train feature:" << endl;
//printFeature(TrainFeatureList.at(0), FR.GetExtractFeatureSize());
//cout << "the second train feature:" << endl;
//printFeature(TrainFeatureList.at(1), FR.GetExtractFeatureSize());
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare train image finish, cost: %f\n", time_cost);
//prepare test image
printf("prepare predict image...\n");
s = clock();
seeta::cv::ImageData predictImage;
vector<SeetaFaceInfo> predictFace;
predictImage = cv::imread(predictImagePath);
predictFace = engine.DetectFaces(predictImage);
if (predictFace.size() != 1)
{
printf("no face or more than one face...exit...\n");
exit(-1);
}
//vector<vector<SeetaPointF>> predictPoint;
//predictPoint.push_back(engine.DetectPoints(predictImage,predictFace.at(0)));
vector<SeetaPointF> predictPoint;
predictPoint = engine.DetectPoints(predictImage, predictFace.at(0));
//get features of test image
printf("get features of predict image ...\n");
seeta::FaceRecognizer FM(FR_model);
vector<float *> predictFeatureList;
temp_float = new float[FM.GetExtractFeatureSize() * sizeof(float)];
if (temp_float == NULL)
{
printf("new space error\n");
exit(-1);
}
predictFeatureList.push_back(temp_float);
FM.Extract(predictImage, predictPoint.data(), predictFeatureList.at(0));
cout << "Test Features List size: " << predictFeatureList.size() << endl;
//cout << "the first test feature:" << endl;
//printFeature(TestFeatureList.at(0), FM.GetExtractFeatureSize());
//cout << "the second test feature:" << endl;
//printFeature(TestFeatureList.at(1), FM.GetExtractFeatureSize());
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare predict image finish, cost: %f\n", time_cost);
printf("predict with knn...\n");
s = clock();
vector<vector<int>> PredictResult;
int k = 3;
PredictResult = KNNClassifier_x(TrainFeatureList, TrainLabels, predictFeatureList, FM.GetExtractFeatureSize(), k);
//printf("ok here\n");
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
cout << "predict finish , cost: " << time_cost << endl;
cout << "predict result: " << endl;
for (j = 0; j < PredictResult.at(0).size(); j++)
cout << PredictResult.at(0).at(j) << " ";
printf("\n");
vector<string> LabelsList = {"5_o_Clock_Shadow", "Arched_Eyebrows", "Attractive", "Bags_Under_Eyes", "Bald", "Bangs", "Big_Lips", "Big_Nose", "Black_Hair", "Blond_Hair", "Blurry", "Brown_Hair", " Bushy_Eyebrows", "Chubby", "Double_Chin", "Eyeglasses", "Goatee", "Gray_Hair", "Heavy_Makeup", "High_Cheekbones", "Male", "Mouth_Slightly_Open", "Mustache", "Narrow_Eyes", "No_Beard", "Oval_Face", "Pale_Skin", "Pointy_Nose", "Receding_Hairline", "Rosy_Cheeks", "Sideburns", "Smiling", "Straight_Hair", "Wavy_Hair", "Wearing_Earrings", "Wearing_Hat", "Wearing_Lipstick", "Wearing_Necklace", "Wearing_Necktie", "Young"};
cout << "LabelsList size: " << LabelsList.size() << endl;
for (i = 0; i < LabelsList.size(); i++)
{
if (PredictResult.at(0).at(i))
cout << LabelsList.at(i) << " ";
}
printf("\n");
exit(-1);
return 0;
}
int Mode_3(string option_1, string option_2)
{
//Mode 3
int i = 0;
int j = 0;
seeta::ModelSetting::Device device = seeta::ModelSetting::CPU;
int id = 0;
seeta::ModelSetting FD_model("./model/fd_2_00.dat", device, id);
seeta::ModelSetting PD_model("./model/pd_2_00_pts5.dat", device, id);
seeta::ModelSetting FR_model("./model/fr_2_10.dat", device, id);
seeta::FaceEngine engine(FD_model, PD_model, FR_model, 2, 16);
clock_t s, t;
double time_cost;
//prepare image store
printf("prepare pictures store...\n");
s = clock();
string ImageStoreDir = "/home/hustccc/Pictures/FaceImage/" + option_1 + "/";
vector<string> TrainImagePath;
vector<string> TrainLabels;
if (getAbsoluteFiles(ImageStoreDir, TrainImagePath) != 0)
{
printf("read train image error\n");
exit(-1);
}
//log
//cout << "size of train image: " << TrainImagePath.size() << endl;
//cout << "the first train image: " << TrainImagePath.at(0) << endl;
vector<seeta::cv::ImageData> TrainImageList;
vector<SeetaFaceInfo> TrainFaceList;
vector<SeetaFaceInfo> tempface;
j = 0;
for (i = 0; i < TrainImagePath.size(); i++)
{
//cout << "read image: " << TrainImagePath.at(i) << endl;
TrainImageList.push_back(cv::imread(TrainImagePath.at(i)));
tempface = engine.DetectFaces(TrainImageList.at(TrainImageList.size() - 1));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TrainImageList.pop_back();
j--;
cout << "read image: " << TrainImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TrainFaceList.push_back(tempface.at(0));
//TrainLabels.push_back(TrainImagePath.at(i).substr(TrainImagePath.at(i).size() - 7, 3));
TrainLabels.push_back(TrainImagePath.at(i).substr(TrainImagePath.at(i).size() - 5, 1));
}
cout << "train data size: " << TrainFaceList.size() << endl;
/*
cout << "Train Image List size: " << TrainImageList.size() << endl;
cout << "Train Faces List size: " << TrainFaceList.size() << endl;
cout << "Train Labels size: " << TrainLabels.size() << endl;
cout << "the first label: " << TrainLabels.at(0) << endl;
cout << "the second label: " << TrainLabels.at(1) << endl;
*/
if (TrainImageList.size() != TrainFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TrainPointList;
for (i = 0; i < TrainImageList.size(); i++)
{
TrainPointList.push_back(engine.DetectPoints(TrainImageList.at(i), TrainFaceList.at(i)));
}
//cout << "Train Points List size: " << TrainPointList.size() << endl;
//cout << "the size of first points: " << TrainPointList.at(0).size() << endl;
//get features of image in store
printf("get features of image in store...\n");
seeta::FaceRecognizer FR(seeta::ModelSetting("./model/fr_2_10.dat"));
vector<float *> TrainFeatureList;
float *temp_float;
for (i = 0; i < TrainPointList.size(); i++)
{
temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
TrainFeatureList.push_back(temp_float);
}
for (i = 0; i < TrainPointList.size(); i++)
{
FR.Extract(TrainImageList.at(i), TrainPointList.at(i).data(), TrainFeatureList.at(i));
}
//cout << "Train Features List size: " << TrainFeatureList.size() << endl;
/*
cout << "the first train feature:" << endl;
printFeature(TrainFeatureList.at(0), FR.GetExtractFeatureSize());
cout << "the second train feature:" << endl;
printFeature(TrainFeatureList.at(1), FR.GetExtractFeatureSize());
*/
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare train image finish, cost: %f\n", time_cost);
s = clock();
//read test image
printf("read test image...\n");
string TestImageDir = "/home/hustccc/Pictures/FaceImage/" + option_2 + "/";
vector<string> TestImagePath;
vector<string> TestLabels;
if (getAbsoluteFiles(TestImageDir, TestImagePath) != 0)
{
printf("read test image error\n");
exit(-1);
}
//log
//cout << "size of test image: " << TestImagePath.size() << endl;
//cout << "the first test image: " << TestImagePath.at(0) << endl;
vector<seeta::cv::ImageData> TestImageList;
vector<SeetaFaceInfo> TestFaceList;
j = 0;
for (i = 0; i < TestImagePath.size(); i++)
{
//cout << "read image: " << TestImagePath.at(i) << endl;
TestImageList.push_back(cv::imread(TestImagePath.at(i)));
tempface = engine.DetectFaces(TestImageList.at(j++));
//cout << "tempface size: " << tempface.size() << endl;
if (tempface.size() > 1)
{
TestImageList.pop_back();
j--;
cout << "read image: " << TestImagePath.at(i) << "... ";
printf("more than one face in an image, continue...\n");
continue;
}
else if (tempface.size() == 0)
{
TestImageList.pop_back();
j--;
cout << "read image: " << TestImagePath.at(i) << "... ";
printf("no face , continue...\n");
continue;
}
TestFaceList.push_back(tempface.at(0));
//TestLabels.push_back(TestImagePath.at(i).substr(TestImagePath.at(i).size() - 7, 3));
TestLabels.push_back(TestImagePath.at(i).substr(TestImagePath.at(i).size() - 5, 1));
//cout<<"["<<j-1<<"] "<<TestImagePath.at(i)<<endl;
}
cout << "test data size: " << TestFaceList.size() << endl;
//cout << "Test Image List size: " << TestImageList.size() << endl;
//cout << "Test Faces List size: " << TestFaceList.size() << endl;
if (TestImageList.size() != TestFaceList.size())
{
printf("something wrong...exit\n");
exit(-1);
}
vector<vector<SeetaPointF>> TestPointList;
for (i = 0; i < TestImageList.size(); i++)
{
TestPointList.push_back(engine.DetectPoints(TestImageList.at(i), TestFaceList.at(i)));
}
//cout << "Train Points List size: " << TestPointList.size() << endl;
//cout << "the size of first points: " << TestPointList.at(0).size() << endl;
//get features of test image
printf("get features of test image...\n");
vector<float *> TestFeatureList;
for (i = 0; i < TestPointList.size(); i++)
{
temp_float = (float *)malloc(sizeof(float) * FR.GetExtractFeatureSize());
TestFeatureList.push_back(temp_float);
}
for (i = 0; i < TestPointList.size(); i++)
{
FR.Extract(TestImageList.at(i), TestPointList.at(i).data(), TestFeatureList.at(i));
}
//cout << "Test Features List size: " << TestFeatureList.size() << endl;
/*
cout << "the first test feature:" << endl;
printFeature(TestFeatureList.at(0), FR.GetExtractFeatureSize());
cout << "the second test feature:" << endl;
printFeature(TestFeatureList.at(1), FR.GetExtractFeatureSize());
*/
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
printf("prepare test image finish, cost: %f\n", time_cost);
//printFeature(TrainFeatureList.at(0),10);
//predict with knn
/*
printf("train labels:\n");
for (i = 0; i < TrainLabels.size(); i++)
cout << TrainLabels.at(i) << " ";
cout << endl;
*/
printf("predict with knn...\n");
s = clock();
vector<string> PredictResult;
int k = 3;
PredictResult = KNNClassifier(TrainFeatureList, TrainLabels, TestFeatureList, FR.GetExtractFeatureSize(), k);
t = clock();
time_cost = (double)(t - s) / CLOCKS_PER_SEC;
cout << "predict finish , cost: " << time_cost << endl;
cout << "predict result: " << endl;
for (i = 0; i < PredictResult.size(); i++)
{
cout << "[" << i << "] " << PredictResult.at(i) << "\t";
if ((i % 10 == 0) && (i != 0))
printf("\n");
}
printf("\n");
float accuracy = 0;
j = 0;
for (i = 0; i < TestLabels.size(); i++)
if (PredictResult.at(i) == TestLabels.at(i))
j++;
else
cout << "not recoginzed: " << i << " " << TestLabels.at(i) << "\t";
//printf("%d %d\n",j,TestLabels.size());
accuracy = (float)j / (float)TestLabels.size();
printf("accuracy: %f\%\n", accuracy * 100);
return 0;
}
int Mode_4()
{
//Mode 4
return 0;
}
vector<string> KNNClassifier(vector<float *> train_data, vector<string> train_label, vector<float *> test_data, int feature_length, int k)
{
//printf("Run KNN Classifier..\n");
int i, j, m;
int predictLabelIndex;
float a = Parameter_A;
float c = Parameter_C;
int d = Parameter_D;
float gama = Parameter_gama;
float r = Parameter_R;
vector<double> LabelCount;
for (i = 0; i < k; i++)
LabelCount.push_back(0);
vector<int> kMinIndex;
//feature*MulRate
for (i = 0; i < train_data.size(); i++)
for (j = 0; j < feature_length; j++)
*(train_data.at(i) + j) *= MulRate;
for (i = 0; i < test_data.size(); i++)
for (j = 0; j < feature_length; j++)
*(test_data.at(i) + j) *= MulRate;
vector<string> predict_result;
vector<vector<double>> DistList;
vector<double> zerodist;
//init DistList
for (i = 0; i < train_data.size(); i++)
zerodist.push_back(0);
for (i = 0; i < test_data.size(); i++)
DistList.push_back(zerodist);
for (i = 0; i < test_data.size(); i++)
for (j = 0; j < train_data.size(); j++)
DistList.at(i).at(j) = EuclideanDist(test_data.at(i), train_data.at(j), feature_length);
//DistList.at(i).at(j) = ManhanttenDist(test_data.at(i), train_data.at(j), feature_length);
//DistList.at(i).at(j) = KernelDist_1(test_data.at(i), train_data.at(j), c, feature_length);
//DistList.at(i).at(j) = KernelDist_2(test_data.at(i), train_data.at(j), a,c,d, feature_length);
//DistList.at(i).at(j) = KernelDist_3(test_data.at(i), train_data.at(j), gama, feature_length);
//DistList.at(i).at(j) = KernelDist_4(test_data.at(i), train_data.at(j), gama, r, feature_length);
for (i = 0; i < DistList.size(); i++)
{
kMinIndex = GetKMinIndex(DistList.at(i), k);
//cout<<"KMindex size: "<<kMinIndex.size()<<endl;
for (j = 0; j < k; j++)
LabelCount.at(j) = 0;
for (j = 0; j < k; j++)
for (m = 0; m < k; m++)
if (train_label.at(kMinIndex.at(j)) == train_label.at(kMinIndex.at(m)))
//LabelCount.at(j)++;
LabelCount.at(j) += 100 / DistList.at(i).at(kMinIndex.at(m));
predictLabelIndex = kMinIndex.at(max_element(LabelCount.begin(), LabelCount.end()) - LabelCount.begin());
predict_result.push_back(train_label.at(predictLabelIndex));
}
return predict_result;
}
vector<vector<int>> KNNClassifier_x(vector<float *> train_data, vector<vector<int>> train_label, vector<float *> test_data, int feature_length, int k)
{
printf("Run KNN Classifier_x..\n");
int i, j, m;
int predictLabelIndex;
float a = Parameter_A;
float c = Parameter_C;
int d = Parameter_D;
float gama = Parameter_gama;
float r = Parameter_R;
vector<double> LabelCount;
for (i = 0; i < k; i++)
LabelCount.push_back(0);
vector<int> kMinIndex;
//feature*MulRate
for (i = 0; i < train_data.size(); i++)
for (j = 0; j < feature_length; j++)
*(train_data.at(i) + j) *= MulRate;
for (i = 0; i < test_data.size(); i++)
for (j = 0; j < feature_length; j++)
*(test_data.at(i) + j) *= MulRate;
vector<vector<int>> predict_result;
//printFeature(train_data.at(0),10);
vector<vector<double>> DistList;
vector<double> zerodist;
//init DistList
for (i = 0; i < train_data.size(); i++)
zerodist.push_back(0);
for (i = 0; i < test_data.size(); i++)
DistList.push_back(zerodist);
//cout<<"zerodist size: "<<zerodist.size()<<endl;
//cout<<"DistList size: "<<DistList.size()<<endl;
for (i = 0; i < test_data.size(); i++)
for (j = 0; j < train_data.size(); j++)
//DistList.at(i).at(j) = EuclideanDist(test_data.at(i), train_data.at(j), feature_length);
//DistList.at(i).at(j) = ManhanttenDist(test_data.at(i), train_data.at(j), feature_length);
//DistList.at(i).at(j) = KernelDist_1(test_data.at(i), train_data.at(j),c, feature_length);
//DistList.at(i).at(j) = KernelDist_2(test_data.at(i), train_data.at(j), a,c,d, feature_length);
//DistList.at(i).at(j) = KernelDist_3(test_data.at(i), train_data.at(j), gama, feature_length);
DistList.at(i).at(j) = KernelDist_4(test_data.at(i), train_data.at(j), gama, r, feature_length);
//printf("log\n");
for (i = 0; i < DistList.size(); i++)
{
kMinIndex = GetKMinIndex(DistList.at(i), k);
//cout<<"KMindex size: "<<kMinIndex.size()<<endl;
for (j = 0; j < k; j++)
LabelCount.at(j) = 0;
for (j = 0; j < k; j++)
for (m = 0; m < k; m++)
if (train_label.at(kMinIndex.at(j)) == train_label.at(kMinIndex.at(m)))
//LabelCount.at(j)++; //no weight
LabelCount.at(j) += 100 / DistList.at(i).at(kMinIndex.at(m)); //have weight
predictLabelIndex = kMinIndex.at(max_element(LabelCount.begin(), LabelCount.end()) - LabelCount.begin());
predict_result.push_back(train_label.at(predictLabelIndex));
}
/*
for (i = 0; i < test_data.size(); i++)
{
for (j = 0; j < train_label.size(); j++)
{
cout << DistList.at(i).at(j) << " ";
}
cout << endl;
}
*/
//printf("predict finish\n");
return predict_result;
}
vector<int> KNNClassifier_lfw(vector<float *> train_data, vector<int> train_label, vector<float *> test_data, int feature_length, int k)
{
printf("Run KNN Classifier lfw..\n");
int i, j, m;
int predictLabelIndex;
float a = Parameter_A;
float c = Parameter_C;
int d = Parameter_D;
float gama = Parameter_gama;
float r = Parameter_R;
vector<double> LabelCount;
for (i = 0; i < k; i++)
LabelCount.push_back(0);
vector<int> kMinIndex;
//feature*MulRate
for (i = 0; i < train_data.size(); i++)
for (j = 0; j < feature_length; j++)
*(train_data.at(i) + j) *= MulRate;
for (i = 0; i < test_data.size(); i++)
for (j = 0; j < feature_length; j++)
*(test_data.at(i) + j) *= MulRate;
vector<int> predict_result;
//printFeature(train_data.at(0),10);
vector<vector<double>> DistList;
vector<double> zerodist;
//init DistList
for (i = 0; i < train_data.size(); i++)
zerodist.push_back(0);
for (i = 0; i < test_data.size(); i++)
DistList.push_back(zerodist);
//cout<<"zerodist size: "<<zerodist.size()<<endl;
//cout<<"DistList size: "<<DistList.size()<<endl;
for (i = 0; i < test_data.size(); i++)
for (j = 0; j < train_data.size(); j++)
//DistList.at(i).at(j) = EuclideanDist(test_data.at(i), train_data.at(j), feature_length);
//DistList.at(i).at(j) = ManhanttenDist(test_data.at(i), train_data.at(j), feature_length);
DistList.at(i).at(j) = KernelDist_1(test_data.at(i), train_data.at(j), c, feature_length);
//DistList.at(i).at(j) = KernelDist_2(test_data.at(i), train_data.at(j), a,c,d, feature_length);
//DistList.at(i).at(j) = KernelDist_3(test_data.at(i), train_data.at(j), gama, feature_length);
//DistList.at(i).at(j) = KernelDist_4(test_data.at(i), train_data.at(j), gama, r, feature_length);
//printf("log\n");
for (i = 0; i < DistList.size(); i++)
{
kMinIndex = GetKMinIndex(DistList.at(i), k);
//cout<<"KMindex size: "<<kMinIndex.size()<<endl;
for (j = 0; j < k; j++)
LabelCount.at(j) = 0;
for (j = 0; j < k; j++)
for (m = 0; m < k; m++)
if (train_label.at(kMinIndex.at(j)) == train_label.at(kMinIndex.at(m)))
//LabelCount.at(j)++;
LabelCount.at(j) += 100 / DistList.at(i).at(kMinIndex.at(m));
predictLabelIndex = kMinIndex.at(max_element(LabelCount.begin(), LabelCount.end()) - LabelCount.begin());
predict_result.push_back(train_label.at(predictLabelIndex));
}
/*
for (i = 0; i < test_data.size(); i++)
{
for (j = 0; j < train_label.size(); j++)
{
cout << DistList.at(i).at(j) << " ";
}
cout << endl;
}
*/
//printf("predict finish\n");
return predict_result;
}
vector<int> GetKMinIndex(vector<double> distlist, int k)
{
//printf("get k min index...\n");
vector<int> ResultIndex;
int tempIndex;
int i, j;
//cout<<"distlist size: "<<distlist.size()<<endl;
for (i = 0; i < distlist.size(); i++)
ResultIndex.push_back(i);
for (i = 0; i < distlist.size(); i++)
for (j = 0; j < distlist.size() - i - 1; j++)
{
if (distlist.at(ResultIndex.at(j)) > distlist.at(ResultIndex.at(j + 1)))
{
tempIndex = ResultIndex.at(j);
ResultIndex.at(j) = ResultIndex.at(j + 1);
ResultIndex.at(j + 1) = tempIndex;
}
}
//printf("soft finish\n");
//cout<<"ResultIndex size: "<<ResultIndex.size()<<endl;
//ResultIndex.erase(ResultIndex.begin()+k,ResultIndex.end()+ResultIndex.size());
for (i = 0; i < ResultIndex.size() - k; i++)
ResultIndex.pop_back();
//printf("get k min index finish\n");
return ResultIndex;
}
int getAbsoluteFiles(string directory, vector<string> &filesAbsolutePath) //参数1[in]要变量的目录 参数2[out]存储文件名
{
DIR *dir = opendir(directory.c_str()); //打开目录 DIR-->类似目录句柄的东西
if (dir == NULL)
{
cout << directory << " is not a directory or not exist!" << endl;
return -1;
}
struct dirent *d_ent = NULL; //dirent-->会存储文件的各种属性
char fullpath[128] = {0};
char dot[3] = "."; //linux每个下面都有一个 . 和 .. 要把这两个都去掉
char dotdot[6] = "..";
while ((d_ent = readdir(dir)) != NULL) //一行一行的读目录下的东西,这个东西的属性放到dirent的变量中
{
if ((strcmp(d_ent->d_name, dot) != 0) && (strcmp(d_ent->d_name, dotdot) != 0)) //忽略 . 和 ..
{
if (d_ent->d_type == DT_DIR) //d_type可以看到当前的东西的类型,DT_DIR代表当前都到的是目录,在usr/include/dirent.h中定义的
{
string newDirectory = directory + string("/") + string(d_ent->d_name); //d_name中存储了子目录的名字
if (directory[directory.length() - 1] == '/')
{
newDirectory = directory + string(d_ent->d_name);
}
if (-1 == getAbsoluteFiles(newDirectory, filesAbsolutePath)) //递归子目录
{
return -1;
}
}
else //如果不是目录
{
string absolutePath = directory + string("/") + string(d_ent->d_name); //构建绝对路径
if (directory[directory.length() - 1] == '/') //如果传入的目录最后是/--> 例如a/b/ 那么后面直接链接文件名
{
absolutePath = directory + string(d_ent->d_name); // /a/b/1.txt
}
filesAbsolutePath.push_back(absolutePath);
}
}
}
closedir(dir);
return 0;
}
int compareLabel(vector<int> x, vector<int> y)
{
int i = 0;
int result = 0;
for (i = 0; i < x.size(); i++)
if (x.at(i) == y.at(i))
result++;
return result;
}
void printFeature(float *feature, int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
printf("%.10f ", *(feature + i));
if (i % 10 == 0)
printf("\n");
}
printf("\n");
}
double EuclideanDist(float *x, float *y, int lenght)
{
int i = 0;
double result = 0;
for (i = 0; i < lenght; i++)
result += pow(*(x + i) - *(y + i), 2);
return result;
}
double ManhanttenDist(float *x, float *y, int length)
{
int i = 0;
double result = 0;
for (i = 0; i < length; i++)
result += fabs(*(x + i) - *(y + i));
return result;
}
double KernelDist_1(float *x, float *y, float c, int length)
{
return LinearKernel(x, x, c, length) - LinearKernel(x, y, c, length) * 2 + LinearKernel(y, y, c, length);
}
double KernelDist_2(float *x, float *y, float a, float c, int d, int length)
{
return PolynomialKernel(x, x, a, c, d, length) - PolynomialKernel(x, y, a, c, d, length) * 2 + PolynomialKernel(y, y, a, c, d, length);
}
double KernelDist_3(float *x, float *y, float gama, int length)
{
return RadialBasisKernel(x, x, gama, length) - RadialBasisKernel(x, y, gama, length) * 2 + RadialBasisKernel(y, y, gama, length);
}
double KernelDist_4(float *x, float *y, float gama, float r, int length)
{
return SigmoidKernel(x, x, gama, r, length) - SigmoidKernel(x, y, gama, r, length) * 2 + SigmoidKernel(y, y, gama, r, length);
}
double LinearKernel(float *x, float *y, float c, int length)
{
int i = 0;
double temp = 0;
for (i = 0; i < length; i++)
temp += (*(x + i)) * (*(y + i));
return temp + c;
}
double PolynomialKernel(float *x, float *y, float a, float c, int d, int length)
{
int i = 0;
double temp = 0;
for (i = 0; i < length; i++)
temp += (*(x + i)) * (*(y + i));
temp = pow(temp * a + c, d);
return temp;
}
double RadialBasisKernel(float *x, float *y, float gama, int length)
{
int i = 0;
double temp = 0;
for (i = 0; i < length; i++)
temp += pow(*(x + i) - *(y + i), 2);
temp = temp * gama * (-1);
//temp = temp * gama ;
temp = exp(temp);
return temp;
}
double SigmoidKernel(float *x, float *y, float gama, float r, int length)
{
int i = 0;
double temp;
for (i = 0; i < length; i++)
temp += (*(x + i)) * (*(y + i));
temp *= gama;
temp += r;
temp = tanh(temp);
return temp;
}
|
1547aedfc3329ef0d00c54a6b29e70237345a5f7
|
649242b5dc401b2626c1d2b8de09656867299b0e
|
/modules/trees/test/test_trees.cpp
|
dc8b6579155de2753ad3be0e55821d1612589a64
|
[
"CC-BY-4.0"
] |
permissive
|
LuckyDmitry/devtools-course-practice
|
45db4f988b38c08365ed8b96f2b6cf3ae8414ae6
|
2384acf591161b8a90c3548929b2425a72d93c50
|
refs/heads/master
| 2022-10-06T03:50:15.806822
| 2020-06-07T17:42:39
| 2020-06-07T17:42:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,391
|
cpp
|
test_trees.cpp
|
// Copyright 2020 Yasakova Anastasia & Sinitsina Maria
#include <gtest/gtest.h>
#include "include/trees.h"
TEST(TreesTest, Constructor_TreeNode) {
// Arrange and Act
TreeNode* node = new TreeNode(4);
// Assert
ASSERT_EQ(4, node->GetData());
}
TEST(TreesTest, Constructor_Tree) {
// Arrange and Act
Tree tree(0);
// Assert
ASSERT_EQ(0, tree.GetDataRoot());
}
TEST(TreesTest, Add_Element) {
// Arrange
Tree tree(0);
// Act
tree.AddElem(5);
// Assert
ASSERT_EQ(2, tree.GetAmount());
}
TEST(TreesTest, Initializer_List_Constructor) {
// Arrange
Tree tree1(10);
tree1.AddElem(5);
tree1.AddElem(15);
tree1.AddElem(7);
tree1.AddElem(20);
// Act
Tree tree2 = { 10, 5, 15, 7, 20 };
// Assert
ASSERT_EQ(1, tree1 == tree2);
}
TEST(TreesTest, Initializer_List_Constructor_Existing_Elem) {
// Act, Arrange and Assert
ASSERT_ANY_THROW(Tree tree({ 10, 5, 15, 7, 20, 5 }));
}
TEST(TreesTest, Equality) {
// Arrange
Tree tree1 = { 20, 10, 30, 5, 15, 25, 35 };
Tree tree2 = { 20, 10, 30, 5, 15, 25, 35 };
// Act and Assert
ASSERT_TRUE(tree1 == tree2);
}
TEST(TreesTest, Not_Equality_Amount) {
// Arrange
Tree tree1 = { 20, 10, 32, 5, 15, 27};
Tree tree2 = { 20, 10, 30, 5, 15, 25, 35 };
// Act and Assert
ASSERT_FALSE(tree1 == tree2);
}
TEST(TreesTest, Not_Equality) {
// Arrange
Tree tree1 = { 20, 10, 32, 5, 15, 27, 35 };
Tree tree2 = { 20, 10, 30, 5, 15, 25, 35 };
// Act and Assert
ASSERT_FALSE(tree1 == tree2);
}
TEST(TreesTest, Not_Equality_Structure_1) {
// Arrange
Tree tree1 = { 20, 10, 30, 5, 15, 27, 35 };
Tree tree2 = { 20, 10, 30, 15, 25, 35, 17 };
// Act and Assert
ASSERT_FALSE(tree1 == tree2);
}
TEST(TreesTest, Not_Equality_Structure_2) {
// Arrange
Tree tree1 = { 20, 10, 30, 5, 15, 27, 35, 7 };
Tree tree2 = { 20, 10, 30, 5, 15, 25, 35, 40 };
// Act and Assert
ASSERT_FALSE(tree1 == tree2);
}
TEST(TreesTest, Add_Existing_Element) {
// Arrange
Tree tree = { 20, 10, 30, 5, 15, 25, 35 };
// Act and Assert
ASSERT_ANY_THROW(tree.AddElem(5));
}
TEST(TreesTest, Copy_Constructor_Tree) {
// Arrange
Tree tree1 = { 20, 10, 30, 5, 15, 25, 35 };
// Act
Tree tree2(tree1);
// Assert
ASSERT_TRUE(tree1 == tree2);
}
TEST(TreesTest, Find_Elem_Return_Data) {
// Arrange
Tree tree = { 20, 10, 30, 5, 15, 25, 35 };
// Act and Assert
ASSERT_TRUE(tree.FindElemData(10));
}
TEST(TreesTest, Not_Find_Elem) {
// Arrange
Tree tree = { 20, 10, 30, 5, 15, 25, 35 };
// Act and Assert
ASSERT_FALSE(tree.FindElemData(17));
}
TEST(TreesTest, Find_Elem_Return_Node) {
// Arrange
Tree tree = { 20, 10, 30, 5, 15, 25, 35 };
// Act and Assert
ASSERT_EQ(10, (tree.FindElemNode(10))->GetData());
}
TEST(TreesTest, Del_Left_Leaf) {
// Arrange
Tree tree1 = { 20, 10, 30, 5, 15, 25, 35 };
Tree tree2 = { 20, 10, 30, 5, 15, 35 };
// Act
tree1.DelElem(25);
// Assert
ASSERT_TRUE(tree1 == tree2);
}
TEST(TreesTest, Del_Right_Leaf) {
// Arrange
Tree tree1 = { 20, 10, 30, 5, 15, 25, 35 };
Tree tree2 = { 20, 10, 30, 5, 15, 25 };
// Act
tree1.DelElem(35);
// Assert
ASSERT_TRUE(tree1 == tree2);
}
TEST(TreesTest, Del_Node) {
// Arrange
Tree tree1 = { 20, 10, 30, 5, 15, 25, 35, 22, 27, 7 };
Tree tree2 = { 20, 7, 30, 5, 15, 25, 35, 22, 27 };
// Act
tree1.DelElem(10);
// Assert
ASSERT_TRUE(tree1 == tree2);
}
TEST(TreesTest, Del_Nonexistent_Elem) {
// Arrange
Tree tree1 = { 20, 10, 30, 5, 15, 25, 35 };
Tree tree2 = { 20, 10, 30, 5, 15, 25, 35 };
// Act
tree1.DelElem(40);
// Assert
ASSERT_TRUE(tree1 == tree2);
}
TEST(TreesTest, Del_Root) {
// Arrange
Tree tree1 = { 20, 10, 30, 5, 15, 25, 35 };
Tree tree2 = { 15, 10, 30, 5, 25, 35 };
// Act
tree1.DelElem(20);
// Assert
ASSERT_TRUE(tree1 == tree2);
}
TEST(TreesTest, Some_Tests_To_Del) {
// Arrange
Tree tree1 = { 20, 10, 30, 5, 15, 25, 35, 22, 32, 21, 7, 17 };
Tree tree2 = { 20, 10, 25, 7, 17, 32, 21 };
// Act
tree1.DelElem(30);
tree1.DelElem(5);
tree1.DelElem(15);
tree1.DelElem(22);
tree1.DelElem(35);
// Assert
ASSERT_TRUE(tree1 == tree2);
}
|
acd5f1c7022a92fd6387973194ed006dc90bee52
|
e046dd9c2921c03b097104d74890795f54565f1d
|
/Schedule.h
|
ed2bb23d4eb49a7984884488285032397b6daed2
|
[] |
no_license
|
SakshamSharma1/Timetable-automation-using-genetic-algorithm
|
c8e21c7ba0e8ecbee73f7da7d0f8628d8d2e4303
|
8ed8f783d91e956b08f1170198a1e628491e1736
|
refs/heads/master
| 2020-05-21T06:37:16.750521
| 2019-05-10T08:30:13
| 2019-05-10T08:30:13
| 185,949,066
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,350
|
h
|
Schedule.h
|
#include <bits/stdc++.h>
#include "CourseClass.h"
using namespace std;
using namespace stdext;
class CChildView;
class Schedule;
class Algorithm;
#define DAY_HOURS 12
#define DAYS_NUM 5
enum AlgorithmState
{
AS_USER_STOPED,
AS_CRITERIA_STOPPED,
AS_RUNNING
};
class Schedule
{
friend class ScheduleObserver;
private:
int _numberOfCrossoverPoints;
int _mutationSize;
int _crossoverProbability;
int _mutationProbability;
float _fitness;
vector<bool> _criteria;
vector<list<CourseClass*>> _slots;
hash_map<CourseClass*, int> _classes;
public:
Schedule(int numberOfCrossoverPoints, int mutationSize,
int crossoverProbability, int mutationProbability);
Schedule(const Schedule& c, bool setupOnly);
Schedule* MakeCopy(bool setupOnly) const;
Schedule* MakeNewFromPrototype() const;
Schedule* Crossover(const Schedule& parent2) const;
void Mutation();
void CalculateFitness();
float GetFitness() const { return _fitness; }
inline const hash_map<CourseClass*, int>& GetClasses() const { return _classes; }
inline const vector<bool>& GetCriteria() const { return _criteria; }
inline const vector<list<CourseClass*>>& GetSlots() const { return _slots; }
};
class Algorithm
{
private:
vector<Schedule*> _chromosomes;
vector<bool> _bestFlags;
vector<int> _bestChromosomes;
int _currentBestSize;
int _replaceByGeneration;
ScheduleObserver* _observer;
Schedule* _prototype;
int _currentGeneration;
AlgorithmState _state;
CCriticalSection _stateSect;
static Algorithm* _instance;
static CCriticalSection _instanceSect;
public:
static Algorithm& GetInstance();
static void FreeInstance();
Algorithm(int numberOfChromosomes, int replaceByGeneration, int trackBest,
Schedule* prototype, ScheduleObserver* observer);
~Algorithm();
void Start();
void Stop();
Schedule* GetBestChromosome() const;
inline int GetCurrentGeneration() const { return _currentGeneration; }
inline ScheduleObserver* GetObserver() const { return _observer; }
private:
void AddToBest(int chromosomeIndex);
bool IsInBest(int chromosomeIndex);
void ClearBest();
};
|
f587ef22caf6e77f2296283a35a960924235e712
|
fc3f9e3676cb1d167bb2b7ed3ef166ba3e4aa860
|
/Practice Algorithms/LeetCode/MaximumSubArray/main.cpp
|
ce65a6ef72d30b45e91f0b2a6ae3ab4175300f25
|
[] |
no_license
|
hiepdangnguyendai/competitive-programming
|
e503cc1b7bf6d8da0fbfc5b1c6b21e83978f90e8
|
d5b33684c673efe3bf472c89dd8863fb5c428c43
|
refs/heads/master
| 2021-08-19T17:38:04.526610
| 2017-11-27T03:27:42
| 2017-11-27T03:27:42
| 112,141,894
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 417
|
cpp
|
main.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std ;
int maxSubArray (vector<int>& nums){
if (nums.size() ==0){return 0 ;}
int maxs = nums[0];
int sum = nums[0];
for (int i = 1 ; i< nums.size() ; i++){
if (sum<0){sum = nums[i];}
else {
sum += nums[i];
}
maxs = max(maxs,sum);
}
return maxs ;
}
int main() {
return 0;
}
|
9768b7d35fc7a64aeb131eb66cc6b31c025909e6
|
d18c0e0b35e03bdc5f5259b88c4226efa5c669ea
|
/include/algorithm/rnn/Layer.h
|
37c0019603ae30389b1d0c3c76204f7cafe0bfaa
|
[] |
no_license
|
zhangkai26/ccma
|
871698682584cfc9a16bf8dbed8add24a12e12b5
|
557a14502c83d1ae73c3defcafe21624ca958d84
|
refs/heads/master
| 2020-04-27T04:34:57.725614
| 2017-07-20T09:53:34
| 2017-07-20T09:53:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,833
|
h
|
Layer.h
|
/***********************************************
* Author: Jun Jiang - jiangjun4@sina.com
* Create: 2017-06-20 16:23
* Last modified : 2017-06-20 16:23
* Filename : Layer.h
* Description : RNN network Layer
**********************************************/
#ifndef _CCMA_ALGORITHM_RNN_LAYER_H_
#define _CCMA_ALGORITHM_RNN_LAYER_H_
#include <vector>
#include "algebra/BaseMatrix.h"
namespace ccma{
namespace algorithm{
namespace rnn{
class Layer{
public:
Layer(uint hidden_dim,
uint bptt_truncate){
_hidden_dim = hidden_dim;
_bptt_truncate = bptt_truncate;
}
~Layer() = default;
void feed_farward(ccma::algebra::BaseMatrixT<real>* train_seq_data,
ccma::algebra::BaseMatrixT<real>* weight,
ccma::algebra::BaseMatrixT<real>* pre_weight,
ccma::algebra::BaseMatrixT<real>* act_weight,
ccma::algebra::BaseMatrixT<real>* state,
ccma::algebra::BaseMatrixT<real>* activation,
bool debug = false);
void back_propagation(ccma::algebra::BaseMatrixT<real>* train_seq_data,
ccma::algebra::BaseMatrixT<real>* train_seq_label,
ccma::algebra::BaseMatrixT<real>* weight,
ccma::algebra::BaseMatrixT<real>* pre_weight,
ccma::algebra::BaseMatrixT<real>* act_weight,
ccma::algebra::BaseMatrixT<real>* derivate_weight,
ccma::algebra::BaseMatrixT<real>* derivate_pre_weight,
ccma::algebra::BaseMatrixT<real>* derivate_act_weight,
bool debug = false);
private:
uint _hidden_dim;
uint _bptt_truncate;
};//class Layer
}//namespace rnn
}//namespace algorithm
}//namespace ccma
#endif
|
300f5aea2e9dd84c733594cd8c88d8df34a60349
|
2ad8f53725ef867feb6820a329ec8ea947cb3e37
|
/SCWF/main.cpp
|
d809d4a866a784af3a4f54278d5cc0d9158e55b7
|
[] |
no_license
|
ilmuk/SCFW
|
902d50c7ecbed02f2426d75355806b19d5f209ce
|
dd567620d90f608ef5d7e54bb3d6314b7a9cafe9
|
refs/heads/master
| 2021-01-22T10:18:35.839171
| 2015-01-11T11:28:28
| 2015-01-11T11:28:28
| 29,088,808
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 579
|
cpp
|
main.cpp
|
#include <iostream>
#include "systemc.h"
#include "parser.cpp"
#include <regex>
using namespace std;
/*
SC_MODULE(test){
sc_in<sc_logic> input;
sc_out<sc_logic> output;
void p1(){
while(true)
{
wait(input.negedge_event());
}
}
}*/
void main(int &argc,char &argv)
{
char c;
//const string text="entity shiftreg is\n\tport (clk : in std_logic;\n reset : in std_logic;\n din : in std_logic;\n\ dout : out std_logic);\nend shiftreg;";
VHDLParser prs("VHDL.txt",0);
string tmp;
prs.MakeModel();
scanf("%c",&c);
return;
}
|
bfc34a08ec7dcc631a6fbdc6cc79648e934c94ad
|
34560ec30d1cd3b557939078ac78fc714dbbbb81
|
/Scale.h
|
9d4dd61586b20db42af92e67402a530732aac591
|
[] |
no_license
|
jonasbru/kimiya-engine
|
6aaedb36c9e63095211a1c6753bd00d3deb0505d
|
b8ec874f9ee68e15d2ad90ab18037cd49a8ddedc
|
refs/heads/master
| 2016-09-06T13:03:06.134314
| 2014-10-12T20:32:09
| 2014-10-12T20:32:09
| 25,130,482
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,387
|
h
|
Scale.h
|
/*
* File: Scale.h
* Author: jonas
*
* Created on 22 juillet 2009, 22:01
*/
/**
* \class Scale
*
* \ingroup ke
*
* \brief Handle scale effects.
*
* \author Jonas BRU
*
*/
#ifndef _SCALE_H
#define _SCALE_H
#include "IntervalActionTransformation.h"
namespace ke {
class Scale : public ke::IntervalActionTransformation{
public:
/**
* Constructor
*
* \param title : title of Scale.
* \param x : scale x.
* \param y : scale y.
*/
Scale(std::string title, float x, float y);
/**
* Constructor
*
* \param title : title of Scale.
* \param duration : duration of the scale.
* \param x : scale x.
* \param y : scale y.
*/
Scale(std::string title, float duration, float x, float y);
/**
* Destructor
*/
virtual ~Scale();
/**
* Sets the scale at the end of the action.
*
* \param x : scale x.
* \param y : scale y.
*/
void setFinalScale(float x, float y);
/**
* Shouldn't be called by yourself.
*/
void play();
private:
float scaleX;
float scaleY;
float startX;
float startY;
virtual void doNextStep();
};
}
#endif /* _SCALE_H */
|
227b7c0e997e91df9dff168ebd5754b3770d0b24
|
4c46aeea5a27e09559063e352d53f03894489457
|
/misc/deleteMatchingFiles.cpp
|
d01e6fdc45143dd541a8958a32b7641d5d9f72d8
|
[] |
no_license
|
md81544/snippets
|
5fbacceea054866d341a1e4e231e9d4fd856cb7f
|
d38c77cd967449958669bfc78fc626990de8c6e2
|
refs/heads/master
| 2018-12-26T03:28:58.179781
| 2018-11-26T20:44:22
| 2018-11-26T20:44:22
| 112,035,381
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 557
|
cpp
|
deleteMatchingFiles.cpp
|
// Requires boost filesystem and regex
void DeleteMatchingFiles(
const std::string& directory,
const std::string& regexString
)
{
namespace fs = boost::filesystem;
fs::path localDir( directory );
fs::directory_iterator itEnd;
const boost::regex rgx( regexString, boost::regex::icase );
for ( fs::directory_iterator it( localDir); it != itEnd; ++it )
{
auto file = (*it).path().filename().string();
if ( boost::regex_match( file, rgx ) )
{
fs::remove((*it).path());
}
}
}
|
d861fe5dddbe3b48fd33abe9017580c2d885e887
|
5241a49fc86a3229e1127427146b5537b3dfd48f
|
/src/Sparrow/Sparrow/Resources/Am1/STO-6G.cpp
|
55085aa7421da0c630b1f8e1d3492f200e9688ab
|
[
"BSD-3-Clause"
] |
permissive
|
qcscine/sparrow
|
05fb1e53ce0addc74e84251ac73d6871f0807337
|
f1a1b149d7ada9ec9d5037c417fbd10884177cba
|
refs/heads/master
| 2023-05-29T21:58:56.712197
| 2023-05-12T06:56:50
| 2023-05-12T06:56:50
| 191,568,488
| 68
| 14
|
BSD-3-Clause
| 2021-12-15T08:19:47
| 2019-06-12T12:39:30
|
C++
|
UTF-8
|
C++
| false
| false
| 13,692
|
cpp
|
STO-6G.cpp
|
/**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*
* @note This file was generated by the Embed binary from runtime values.
* Prefer improving the generator over editing this file whenever possible.
*
* This file contains functions generating runtime values. It was
* generated from runtime values of its return type. It is not intended to be
* human-readable. A small guide: Return values are directly brace-initialized
* in deep nesting to keep file size to a minimum. Types are annotated only when
* necessary. Floating point values are represented in hexadecimal (see
* std::hexfloat) to ensure serialization does not cause loss of accuracy.
*
* The functions defined here might be declared and called elsewhere entirely.
*
*/
#include "Utils/DataStructures/AtomicGtos.h"
#include <unordered_map>
namespace Scine {
namespace Sparrow {
namespace Sto6g {
std::unordered_map<int, Utils::AtomicGtos> am1() {
// clang-format off
return {
{20, {Utils::GtoExpansion {0, {{{0, 0x1.1e847b67c63aep+2, 0x1.8b450738bff94p-9}, {0, 0x1.ff504cbaabf12p-2, -0x1.2c8ef2852abbp-5}, {0, 0x1.e735d05b1b90fp-3, -0x1.374f05b68c40fp-4}, {0, 0x1.2b5b53d6e45ep-4, 0x1.4096a4cf4321fp-4}, {0, 0x1.66dd78d4da586p-5, 0x1.eac493fc6d216p-6}, {0, 0x1.a934745a5555bp-6, 0x1.2c767c1958233p-10}}}}, Utils::GtoExpansion {1, {{{1, 0x1.f05bc2ac07b5dp+1, -0x1.a76c3fe1aa00ap-7}, {1, 0x1.4ab4db1d50cf2p+0, -0x1.0a8ca8f3114b2p-5}, {1, 0x1.1bc548a030306p-1, -0x1.4cba75f59b3a6p-5}, {1, 0x1.260692a92613p-3, 0x1.a2408ab01382cp-5}, {1, 0x1.498dbe2612cb5p-4, 0x1.0fe594daafb2bp-5}, {1, 0x1.76756c9bfaa8dp-5, 0x1.dbd241335cf0cp-9}}}}, boost::none}},
{19, {Utils::GtoExpansion {0, {{{0, 0x1.4ba02ca1e4482p+2, 0x1.b9142d694fdefp-9}, {0, 0x1.27e80b9e41773p-1, -0x1.4f64223a33db2p-5}, {0, 0x1.19f512fa801e3p-2, -0x1.5b6327fef15bfp-4}, {0, 0x1.5a7c7cd4b26d6p-4, 0x1.65be18c516a96p-4}, {0, 0x1.9f5d08f7fac8bp-5, 0x1.11d284fe75637p-5}, {0, 0x1.ec25c022a8b69p-6, 0x1.4f48d60848466p-10}}}}, Utils::GtoExpansion {1, {{{1, 0x1.175246e5bea75p+1, -0x1.9cc0c6e44bc09p-8}, {1, 0x1.743452106b9d3p-1, -0x1.03d52acc75918p-6}, {1, 0x1.3f6100c80044bp-2, -0x1.44580d611baf6p-6}, {1, 0x1.4aebb86a89f57p-4, 0x1.97b66cd951595p-6}, {1, 0x1.72e82d04749c3p-5, 0x1.090b97e1c71ep-6}, {1, 0x1.a5725d89af0b5p-6, 0x1.cfd4c35b4e0dcp-10}}}}, boost::none}},
{18, {Utils::GtoExpansion {0, {{{0, 0x1.867d58b977fc9p+1, 0x1.287584ba7df46p-9}, {0, 0x1.5c6e1fb286e03p-2, -0x1.c2d9140accd9cp-6}, {0, 0x1.4c014d0892061p-3, -0x1.d2f94929b79a7p-5}, {0, 0x1.97fcee1482f59p-5, 0x1.e0e4cccf98d26p-5}, {0, 0x1.e917468ed3e38p-6, 0x1.70159a5fa62adp-6}, {0, 0x1.21c08a70b3a4p-6, 0x1.c2b46231b30dap-11}}}}, Utils::GtoExpansion {1, {{{1, 0x1.645d7cdd81661p+7, -0x1.8b84b86a402e9p+1}, {1, 0x1.7860d94782dp+5, -0x1.3f1dfd9a5803p+1}, {1, 0x1.f8ef40f05a937p+2, 0x1.8b81789672938p+1}, {1, 0x1.fc506ab31d027p+1, 0x1.cac6753c8a9aap+1}, {1, 0x1.10eaf23fdbaefp+1, 0x1.6f7ee4c6344d7p+0}, {1, 0x1.29d1edefec8e7p+0, 0x1.056802373dc6bp-3}}}}, boost::none}},
{17, {Utils::GtoExpansion {0, {{{0, 0x1.5949f7fec1a25p+5, -0x1.4d123bd1667b9p-4}, {0, 0x1.843f757bd61ep+3, -0x1.0b8d0e2aee115p-2}, {0, 0x1.2f43c5543ad1ap+2, -0x1.742dfe2be81e9p-2}, {0, 0x1.238fa466d9af7p+0, 0x1.bd4e25738207p-2}, {0, 0x1.43e75b52dfc6ap-1, 0x1.03a3bae0c6717p-2}, {0, 0x1.6fee9c2a543a3p-2, 0x1.87758e89afe8bp-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.5e6daeb342976p+4, -0x1.cc944797ca557p-3}, {1, 0x1.721bb14e17fdcp+2, -0x1.739c3ceed8fdap-3}, {1, 0x1.f085d699ead5fp-1, 0x1.cc907eef2727ep-3}, {1, 0x1.f3d896aa4330dp-2, 0x1.0b1ee70a1d367p-2}, {1, 0x1.0c5f05cc2821p-2, 0x1.abf26511daefbp-4}, {1, 0x1.24dbcdd4cc0e4p-3, 0x1.306802c9761cfp-7}}}}, boost::none}},
{16, {Utils::GtoExpansion {0, {{{0, 0x1.2548c4f4c370fp+4, -0x1.5e72cf3e98c23p-5}, {0, 0x1.49c5e799e735dp+2, -0x1.1982872ac39d6p-3}, {0, 0x1.0196e2d09e4d3p+1, -0x1.8798e8f4d50edp-3}, {0, 0x1.ef4c0564a0398p-2, 0x1.d489bee9219ccp-3}, {0, 0x1.131eb336cc175p-2, 0x1.112f892a8cee7p-3}, {0, 0x1.38845dd00b99ep-3, 0x1.9be1f9d9835ddp-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.c3b2d07cfbde6p+3, -0x1.09f7a95c358c6p-3}, {1, 0x1.dd10c158b6411p+1, -0x1.ad2eaeec3f2b7p-4}, {1, 0x1.40019b32d7ee8p-1, 0x1.09f579fee441bp-3}, {1, 0x1.4225e902c875ap-2, 0x1.34812efcb5e4ep-3}, {1, 0x1.59ed74ca4b428p-3, 0x1.ee3f349171feap-5}, {1, 0x1.797dd90f9181ap-4, 0x1.5f91138249f62p-8}}}}, boost::none}},
{15, {Utils::GtoExpansion {0, {{{0, 0x1.9b245f996d089p+3, -0x1.0c75ad7838274p-5}, {0, 0x1.ce4b4b1b0dba3p+1, -0x1.af4c8fc80d22dp-4}, {0, 0x1.691a622233844p+0, -0x1.2bfb48ad6d0bap-3}, {0, 0x1.5b2ad61220c83p-2, 0x1.66ebf7b4566efp-3}, {0, 0x1.81ada631d01d4p-3, 0x1.a28baf6c2b479p-4}, {0, 0x1.b61a8b46fdda7p-4, 0x1.3b856965b8472p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.1dae8522a68f6p+4, -0x1.64c94d045833bp-3}, {1, 0x1.2db9af579e698p+2, -0x1.1fdde84c1c859p-3}, {1, 0x1.94c874ad0ba77p-1, 0x1.64c65ea5f967cp-3}, {1, 0x1.977e0480e577fp-2, 0x1.9dd93a295e8aap-3}, {1, 0x1.b5924a1c1ea61p-3, 0x1.4b81fd14d4b28p-4}, {1, 0x1.dd7f5b266eb8ap-4, 0x1.d79d68435a35bp-8}}}}, boost::none}},
{1, {Utils::GtoExpansion {0, {{{0, 0x1.04e285bddafdcp+5, 0x1.6d0d66ab706e6p-4}, {0, 0x1.7ea9e2e0586e2p+2, 0x1.137d80eb4360cp-3}, {0, 0x1.ac38d280a5bfcp+0, 0x1.69d5b8cef649dp-3}, {0, 0x1.26362b999231ep-1, 0x1.64faf46021125p-3}, {0, 0x1.c900ff8e66eep-3, 0x1.8abf31e7ccd57p-4}, {0, 0x1.78705adb3465p-4, 0x1.fc10893520fa3p-7}}}}, boost::none, boost::none}},
{14, {Utils::GtoExpansion {0, {{{0, 0x1.5f05638ae790ap+3, -0x1.dce2ee5a5275fp-6}, {0, 0x1.8ab172854db42p+1, -0x1.7f1357b86c86bp-4}, {0, 0x1.344c9856c8be8p+0, -0x1.0a70cf5121244p-3}, {0, 0x1.2866ba5e0e71p-2, 0x1.3eca6dda11d62p-3}, {0, 0x1.4947e4b02303ap-3, 0x1.73bf83059f95ap-4}, {0, 0x1.760a427769445p-4, 0x1.183e24bd7e849p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.0c4be333d32d5p+3, -0x1.155fd4743cf51p-4}, {1, 0x1.1b5d1bee23ba1p+1, -0x1.bf96db65fe35p-5}, {1, 0x1.7c265859786b3p-2, 0x1.155d8d196c0bap-4}, {1, 0x1.7eb1b32f3baebp-3, 0x1.41bc62b9e4eb8p-4}, {1, 0x1.9af15e559cc18p-4, 0x1.01b8e00145346p-5}, {1, 0x1.c0706d7bf765fp-5, 0x1.6ea51334926b2p-9}}}}, boost::none}},
{2, {Utils::GtoExpansion {0, {{{0, 0x1.bd7dd6dbe5692p+6, 0x1.ca8ddb69161c2p-3}, {0, 0x1.46b8b81bfd663p+4, 0x1.5a0d611549a45p-2}, {0, 0x1.6d9ea2edc034ep+2, 0x1.c68334f7a27fap-2}, {0, 0x1.f666a19267362p+0, 0x1.c06a205f16b59p-2}, {0, 0x1.8631a65be1b9dp-1, 0x1.efdab7b8a358p-3}, {0, 0x1.416825ebb4d06p-2, 0x1.3f1925b4fa08fp-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.177d7ecc1c1c8p+8, 0x1.9d0d8625cd265p+3}, {1, 0x1.238a9d0dc89dap+6, 0x1.f3b0881b3296ep+3}, {1, 0x1.a143e740c9105p+4, 0x1.fe52128c814a5p+3}, {1, 0x1.5cd985db2d70bp+3, 0x1.6dec8acb04b8p+3}, {1, 0x1.3f0923202411fp+2, 0x1.10a49d18a2e96p+2}, {1, 0x1.2da85aeb697a9p+1, 0x1.c04ed5f72eaa1p-2}}}}, boost::none}},
{3, {Utils::GtoExpansion {0, {{{0, 0x1.199e39278ba5bp+4, -0x1.a08cd1e4dc151p-6}, {0, 0x1.9d2ac7c7646e4p+1, -0x1.229fe7b62991p-5}, {0, 0x1.d06f7c163fa26p-1, -0x1.177ec84192011p-5}, {0, 0x1.09a945ecbcccp-3, 0x1.a649ffcb30158p-5}, {0, 0x1.e24b29e2b8554p-5, 0x1.883f35626e8a1p-5}, {0, 0x1.cc0195d43e05fp-6, 0x1.1264bdad1cb2cp-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.334d207f8144dp+2, 0x1.48d7a6ed0935bp-4}, {1, 0x1.408d3bed9a3ap+0, 0x1.8dd0f3d971d55p-4}, {1, 0x1.cac92a70e4a8ep-2, 0x1.9647a4d4488b2p-4}, {1, 0x1.7f8ffe1d9da74p-3, 0x1.235265cf61a2bp-4}, {1, 0x1.5ec822c803d16p-4, 0x1.b21de5b9eeb35p-6}, {1, 0x1.4bacabed40408p-5, 0x1.64e8f1a19ae26p-9}}}}, boost::none}},
{4, {Utils::GtoExpansion {0, {{{0, 0x1.e87199966fce4p+3, -0x1.7655b8e7c1d54p-6}, {0, 0x1.664d6eb3635e3p+1, -0x1.052bdab6478bep-5}, {0, 0x1.92c34d3294d2dp-1, -0x1.f656f379a222fp-6}, {0, 0x1.ccc49596765dbp-4, 0x1.7b7e01fc5587fp-5}, {0, 0x1.a23fe7bcb6c71p-5, 0x1.607ea3b58cce2p-5}, {0, 0x1.8eebf91dae484p-6, 0x1.ed2b96f489dc6p-8}}}}, Utils::GtoExpansion {1, {{{1, 0x1.ea7406b3ed8a1p+1, 0x1.f00bbe166f23bp-5}, {1, 0x1.ff99d55f56453p-1, 0x1.2c0b8b5f9cf78p-4}, {1, 0x1.6e1c823581d6ep-2, 0x1.326dba9bb0515p-4}, {1, 0x1.321545b38d5ddp-3, 0x1.b77297abececbp-5}, {1, 0x1.17ec90b473ec4p-4, 0x1.476c90eccb376p-6}, {1, 0x1.08ad2c755d0c7p-5, 0x1.0d313ca79428fp-9}}}}, boost::none}},
{6, {Utils::GtoExpansion {0, {{{0, 0x1.6a4285497614cp+6, -0x1.63c5ae1ab4cfcp-4}, {0, 0x1.09bd3509c1f02p+4, -0x1.f070c34a915b5p-4}, {0, 0x1.2ab6b31233ab1p+2, -0x1.dd6def7646d54p-4}, {0, 0x1.55bbd6a5b1b2cp-1, 0x1.68ac7ea66b6d3p-3}, {0, 0x1.363317bfbea35p-2, 0x1.4f03d9a1b95e1p-3}, {0, 0x1.27dd671e3250ap-3, 0x1.d4b6f9d334091p-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.0a9e6d030e01dp+4, 0x1.8569d5498402fp-2}, {1, 0x1.161d770d30f3ap+2, 0x1.d71783b637e54p-2}, {1, 0x1.8e0c8685b494cp+0, 0x1.e11d4c815a4dep-2}, {1, 0x1.4cc8bc23e9802p-1, 0x1.58fb578e2c27dp-2}, {1, 0x1.3057d7f478e44p-2, 0x1.010a15ce47a2dp-3}, {1, 0x1.1fc3f0fa009c4p-3, 0x1.a6a69e15b8ee8p-7}}}}, boost::none}},
{7, {Utils::GtoExpansion {0, {{{0, 0x1.28d8522437ae6p+7, -0x1.01a8e836c6846p-3}, {0, 0x1.b381c08ba11dcp+4, -0x1.67891a35c5fa4p-3}, {0, 0x1.e98c1a3bf9352p+2, -0x1.59c46a3aa9ee9p-3}, {0, 0x1.18067fe57b261p+0, 0x1.0535ad780926dp-2}, {0, 0x1.fc5ef83ec62a9p-2, 0x1.e540fa10edd08p-3}, {0, 0x1.e4e0e4c7bad82p-3, 0x1.5374b1ac16015p-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.b53ae2f76b521p+4, 0x1.6954a6371ff49p-1}, {1, 0x1.c8153237a9208p+2, 0x1.b51e6b0b44831p-1}, {1, 0x1.4661acad68faap+1, 0x1.be6b2b6c8a6b5p-1}, {1, 0x1.10de10edd6973p+0, 0x1.401a6f79a432ap-1}, {1, 0x1.f318266f9eb2bp-2, 0x1.dd0177b1664bep-3}, {1, 0x1.d7e88bef1b576p-3, 0x1.882bd179753bep-6}}}}, boost::none}},
{8, {Utils::GtoExpansion {0, {{{0, 0x1.0b6ed5434a0ccp+8, -0x1.90b66e382b17p-3}, {0, 0x1.885b199cf7ad3p+5, -0x1.17932e3e6e83cp-2}, {0, 0x1.b90ab656d39e9p+3, -0x1.0cde62094962ep-2}, {0, 0x1.f88f48c369b87p+0, 0x1.963bc037d39a2p-2}, {0, 0x1.ca001d8cfc959p-1, 0x1.79555e4217fa7p-2}, {0, 0x1.b4d5ed69fb53p-2, 0x1.07f5ff7e55811p-4}}}}, Utils::GtoExpansion {1, {{{1, 0x1.2b1589c8bc304p+5, 0x1.0b4f92c53e08fp+0}, {1, 0x1.37faf10299371p+3, 0x1.4360eaa36ccp+0}, {1, 0x1.be849c4ad819cp+1, 0x1.4a422f9f9280ap+0}, {1, 0x1.754e5e4daf82ap+0, 0x1.d99f3988c0ebbp-1}, {1, 0x1.5566e845ecfa6p-1, 0x1.60e30187e45aep-2}, {1, 0x1.42ce3d4420534p-2, 0x1.22206274c9d88p-5}}}}, boost::none}},
{9, {Utils::GtoExpansion {0, {{{0, 0x1.89802f26e6cedp+8, -0x1.0babb981e9affp-2}, {0, 0x1.20a7f7c7e0ae6p+6, -0x1.75813a9d038f8p-2}, {0, 0x1.447971df5d212p+4, -0x1.67339844bd84cp-2}, {0, 0x1.733458204c383p+1, 0x1.0f5bcddd30dedp-1}, {0, 0x1.50f36a0aca918p+0, 0x1.f81b8fedadef3p-2}, {0, 0x1.4161412139a4dp-1, 0x1.60a518ea69da5p-4}}}}, Utils::GtoExpansion {1, {{{1, 0x1.242a1d60fc8c8p+5, 0x1.039a4918df879p+0}, {1, 0x1.30c322f7513cap+3, 0x1.3a0dbca0a0f4cp+0}, {1, 0x1.b42ff6370fac4p+1, 0x1.40bc37ed242ccp+0}, {1, 0x1.6cab5746b63b6p+0, 0x1.cbf6f2e08ee24p-1}, {1, 0x1.4d80d7b38db1ap-1, 0x1.56b5ff4103ba5p-2}, {1, 0x1.3b56514e299fcp-2, 0x1.19c2abee64de1p-5}}}}, boost::none}},
{10, {Utils::GtoExpansion {0, {{{0, 0x1.d70fc860cfdcep+6, -0x1.618cd15f8d026p-3}, {0, 0x1.08d592ddeb143p+5, -0x1.1c0057b99749fp-1}, {0, 0x1.9dbadf962c92fp+3, -0x1.8b10261ccb59dp-1}, {0, 0x1.8dc364f5c1ef1p+1, 0x1.d8af4f07cfba1p-1}, {0, 0x1.b9e3062875c4p+0, 0x1.139a7d8d574eep-1}, {0, 0x1.f5f3def9768dep-1, 0x1.9f872ce4db5b1p-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.982894ed5e9ffp+6, 0x1.d4e3230f305a8p+1}, {1, 0x1.a9c1fd3769496p+4, 0x1.1b9e18a2d7d0bp+2}, {1, 0x1.30ae2cf60f46fp+3, 0x1.21a6cf0d840f5p+2}, {1, 0x1.fd72e9d0c6f65p+1, 0x1.9f63455988b1ep+1}, {1, 0x1.d1e8d2a25146ep+0, 0x1.357f5f5cdb91ep+0}, {1, 0x1.b887f6ed60069p-1, 0x1.fce8720a26afcp-4}}}}, boost::none}},
{11, {Utils::GtoExpansion {0, {{{0, 0x1.04cf57bf416f5p+1, -0x1.0ddce810b3d7fp-7}, {0, 0x1.25422ada864acp-1, -0x1.b18db00fbe32ep-6}, {0, 0x1.ca22878a69534p-3, -0x1.2d8cb14da0fe3p-5}, {0, 0x1.b874593aa71f4p-5, 0x1.68cc3eaa898f8p-5}, {0, 0x1.e9505174ef764p-6, 0x1.a4bbbeef5ff43p-6}, {0, 0x1.15e9c47847e73p-6, 0x1.3d2b9d33487bp-9}}}}, Utils::GtoExpansion {1, {{{1, 0x1.a658eaaad33c2p+2, -0x1.9b4531dae20f4p-5}, {1, 0x1.be10e25a8520fp+0, -0x1.4bd385b05102fp-5}, {1, 0x1.2b3660a19c8cep-2, 0x1.9b41d0e6415cdp-5}, {1, 0x1.2d370d896c4edp-3, 0x1.dd0bdc8a91209p-5}, {1, 0x1.4373086d21f1dp-4, 0x1.7e21aa140387fp-6}, {1, 0x1.60f65d4a459bdp-5, 0x1.0fd1276ef7f44p-9}}}}, boost::none}},
{12, {Utils::GtoExpansion {0, {{{0, 0x1.add20fe8619b2p+1, -0x1.8885fa6ac191cp-7}, {0, 0x1.e34be4b7c3116p-1, -0x1.3b4ed79e805ap-5}, {0, 0x1.79821af230a92p-2, -0x1.b69ccdc1bfa1bp-5}, {0, 0x1.6af07b635c7a1p-4, 0x1.066538c43484fp-4}, {0, 0x1.9333300e20291p-5, 0x1.31fc00c0fad66p-5}, {0, 0x1.ca01cd9d33488p-6, 0x1.cd555987c5bd5p-9}}}}, Utils::GtoExpansion {1, {{{1, 0x1.c460b5c031e92p+2, -0x1.c024a2a314696p-5}, {1, 0x1.ddc86aa7f3f0bp+0, -0x1.699391f373b9ep-5}, {1, 0x1.407ccd800e1e3p-2, 0x1.c020f42210cb9p-5}, {1, 0x1.42a1ee663bc86p-3, 0x1.03e87e7b1a1c7p-4}, {1, 0x1.5a72a1c56cd8fp-4, 0x1.a064505b6f1bep-6}, {1, 0x1.7a0f2cd7cdb63p-5, 0x1.282fdfef7c52bp-9}}}}, boost::none}},
{13, {Utils::GtoExpansion {0, {{{0, 0x1.e1cd3affc9d0cp+2, -0x1.67941fba8a4bdp-6}, {0, 0x1.0edf55481afccp+1, -0x1.20d80e8608ee1p-4}, {0, 0x1.a729b16c207f6p-1, -0x1.91ccaa926b522p-4}, {0, 0x1.96d505634f5ccp-3, 0x1.e0bea879e4b36p-4}, {0, 0x1.c3f62fd727d47p-4, 0x1.184d8be17786p-4}, {0, 0x1.00b2cf62b54ap-4, 0x1.a69d0697eef8ep-8}}}}, Utils::GtoExpansion {1, {{{1, 0x1.154e0d0655199p+3, -0x1.211079e4aef71p-4}, {1, 0x1.24e0c8cec98b3p+1, -0x1.d273fc5fa3c4dp-5}, {1, 0x1.88e9f3ee72152p-2, 0x1.210e19f3f033bp-4}, {1, 0x1.8b8b2d89e6d56p-3, 0x1.4f4ba84748822p-4}, {1, 0x1.a8bda9124050cp-4, 0x1.0c957d7b9618fp-5}, {1, 0x1.cf7f05b2c8436p-5, 0x1.7e18e0ccc77cep-9}}}}, boost::none}},
};
// clang-format on
}
} // namespace Sto6g
} // namespace Sparrow
} // namespace Scine
|
66ef7f9645596b696748685e2e6309eed3694d9b
|
0c27b7d43c21f70dfd6bead802a79e5def0ae743
|
/BattlezoneClone/Enemy.cpp
|
03f51f29c64c80f3c61249f7acd4d3031fc9ee4e
|
[] |
no_license
|
adamcumiskey/BattleZone
|
730544f9d231d15057633c714713ea52f6ba0acd
|
364419801fd534345f1562d33658716e0d49fb0a
|
refs/heads/develop
| 2020-05-20T23:52:23.796337
| 2015-03-30T00:49:02
| 2015-03-30T00:49:02
| 14,189,439
| 0
| 0
| null | 2015-03-30T00:49:02
| 2013-11-07T00:07:24
|
C++
|
UTF-8
|
C++
| false
| false
| 4,104
|
cpp
|
Enemy.cpp
|
//
// Enemy.cpp
// BattlezoneClone
//
// Created by Adam Cumiskey on 11/23/13.
// Copyright (c) 2013 Adam Cumiskey. All rights reserved.
//
#include "Enemy.h"
#include "BoundingBox.h"
#include <math.h>
#define SQR(x) (x*x)
#define PIdiv180 M_PI/180.0f
#ifdef __APPLE__
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif
#define TANK_SPEED 0.02f
#define TURN_SPEED 1.0f
#define MAX_ROTATION 40.0f
#pragma mark - Constructors
Enemy::Enemy(float x, float y, float z) : MovableObject(x, y, z)
{
_AIState = AI_NONE;
distanceMoved = 0;
angleTurned = 0;
currentDirection = -1;
// Store the object in a displayList
GLuint index = glGenLists(1);
glNewList(index, GL_COMPILE);
glColor3f(1.0, 0.0, 0.0);
glRotated(90, 0, 1, 0);
// Base of the tank
glPushMatrix();
glTranslated(0, -.25, 0);
glScalef(2, .5, 1.25);
glutWireCube(1.0);
glPopMatrix();
// Top of the tank
glPushMatrix();
glTranslatef(0, .2, 0);
glScalef(1.25, .4, .75);
glutWireCube(1);
glPopMatrix();
// Cannon
glPushMatrix();
glRotatef(90, 0, 1, 0);
glTranslatef(0, .3, 1.12);
glScalef(.1, .1, 1);
glutWireCube(1);
glPopMatrix();
glEndList();
_displayList = index;
}
#pragma mark - Public methods
void Enemy::render()
{
glPushMatrix();
glTranslatef(Position.x, Position.y, Position.z);
glRotated(RotatedY, 0, 1, 0);
glCallList(_displayList);
glPopMatrix();
}
void Enemy::setAIState(EnemyState newState)
{
_AIState = newState;
// reset the params
distanceMoved = 0;
angleTurned = 0;
currentDirection = -1;
}
EnemyState Enemy::getAIState()
{
return _AIState;
}
#pragma mark - AI Methods
void Enemy::move()
{
MoveForward(-TANK_SPEED);
distanceMoved += TANK_SPEED;
}
void Enemy::reverse()
{
MoveForward(TANK_SPEED);
distanceMoved += TANK_SPEED;
}
void Enemy::turn()
{
if (currentDirection == LEFT) {
RotateY(TURN_SPEED);
} else {
RotateY(-TURN_SPEED);
}
angleTurned += TURN_SPEED;
}
// NOTE: Doesn't work very well
void Enemy::aim(SF3dVector targetPosition)
{
// Get the vector between the tank and the player
SF3dVector targetVector = F3dVector(targetPosition.x-Position.x,
targetPosition.y-Position.y,
targetPosition.z-Position.z);
// normalize the vector
float length = sqrtf(SQR(targetVector.x) + SQR(targetVector.y) + SQR(targetVector.z));
targetVector.x = targetVector.x/length;
targetVector.y = targetVector.y/length;
targetVector.z = targetVector.z/length;
// find the dot product
float dotProduct = (targetVector.x*ViewDir.x +
targetVector.y*ViewDir.y +
targetVector.z*ViewDir.z);
float angle = (acosf(dotProduct)*(180/M_PI));
if (!(angle <= 5) && !(angle <= -5)) {
if (targetVector.x < ViewDir.x || targetVector.z < ViewDir.z) {
turn();
} else if (targetVector.x > ViewDir.x || targetVector.z > ViewDir.z) {
turn();
}
}
}
void Enemy::fire()
{
}
void Enemy::setTurnDirection(Direction direction)
{
currentDirection = direction;
}
float Enemy::getDistanceMoved()
{
return distanceMoved;
}
float Enemy::getAngleTurned()
{
return angleTurned;
}
#pragma mark - Collision methods
BoundingBox Enemy::bounds()
{
Point2d center = createPoint2d(Position.x, Position.z);
Point2d topRight = createPoint2d(center.x+.65, center.y+1);
Point2d bottomLeft = createPoint2d(center.x-.65, center.y-1);
return BoundingBox(topRight, bottomLeft);
}
void Enemy::renderBounds()
{
BoundingBox bounds = Enemy::bounds();
glPushMatrix();
glColor3f(1, 1, 1);
glTranslatef(0, .01, 0);
glRotated(90, 1, 0, 0);
glRectd(bounds.getTopRight().x,
bounds.getTopRight().y,
bounds.getBottomLeft().x,
bounds.getBottomLeft().y);
glPopMatrix();
}
|
6aeda20f2ccf88934ee4798c71a6c111f3c62287
|
012f0800c635f23d069f0c400768bc58cc1a0574
|
/hhvm/hhvm-3.17/hphp/runtime/base/stat-cache.cpp
|
7875558e68d40dd1923cdd2771669e346ca8d1ad
|
[
"Zend-2.0",
"BSD-3-Clause",
"PHP-3.01"
] |
permissive
|
chrispcx/es-hhvm
|
c127840387ee17789840ea788e308b711d3986a1
|
220fd9627b1b168271112d33747a233a91e8a268
|
refs/heads/master
| 2021-01-11T18:13:42.713724
| 2017-02-07T02:02:10
| 2017-02-07T02:02:10
| 79,519,670
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 30,115
|
cpp
|
stat-cache.cpp
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/base/stat-cache.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/param.h>
#include <vector>
#include <folly/MapUtil.h>
#include <folly/portability/Unistd.h>
#include "hphp/util/trace.h"
#include "hphp/util/logger.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/vm/jit/hooks.h"
#include "hphp/util/text-util.h"
#include "hphp/runtime/base/file-util.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
TRACE_SET_MOD(stat);
UNUSED static std::string statToString(const struct stat* buf) {
std::ostringstream os;
os << "struct stat {";
os << "dev=" << buf->st_dev << ", ";
os << "ino=" << buf->st_ino << ", ";
os << "mode=0" << std::oct << buf->st_mode << std::dec << ", ";
os << "nlink=" << buf->st_nlink << ", ";
os << "uid=" << buf->st_uid << ", ";
os << "gid=" << buf->st_gid << ", ";
os << "rdev=" << buf->st_rdev << ", ";
os << "size=" << buf->st_size << ", ";
#ifndef _MSC_VER
os << "blksize=" << buf->st_blksize << ", ";
os << "blocks=" << buf->st_blocks << ", ";
#endif
os << "atime=" << buf->st_atime << ", ";
os << "mtime=" << buf->st_mtime << ", ";
os << "ctime=" << buf->st_ctime;
os << "}";
return os.str();
}
UNUSED static bool statEquiv(const struct stat* stA, const struct stat* stB) {
return (stA->st_dev == stB->st_dev
&& stA->st_ino == stB->st_ino
&& stA->st_mode == stB->st_mode
&& stA->st_nlink == stB->st_nlink
&& stA->st_uid == stB->st_uid
&& stA->st_gid == stB->st_gid
&& stA->st_rdev == stB->st_rdev
&& stA->st_size == stB->st_size
#ifndef _MSC_VER
&& stA->st_blksize == stB->st_blksize
&& stA->st_blocks == stB->st_blocks
#endif
/* Intentionally omitted:
&& stA->st_atime == stB->st_atime
*/
&& stA->st_mtime == stB->st_mtime
&& stA->st_ctime == stB->st_ctime);
}
#ifdef __linux__
UNUSED static std::string eventToString(const struct inotify_event* ie) {
bool first = true;
std::ostringstream os;
os << "struct inotify_event {wd=" << ie->wd << ", mask=(";
#define EVENT(e) do { \
if (ie->mask & e) { \
if (first) { \
first = false; \
} else { \
os << "|"; \
} \
os << #e; \
} \
} while (0)
EVENT(IN_ACCESS);
EVENT(IN_MODIFY);
EVENT(IN_ATTRIB);
EVENT(IN_CLOSE_WRITE);
EVENT(IN_CLOSE_NOWRITE);
EVENT(IN_OPEN);
EVENT(IN_MOVED_FROM);
EVENT(IN_MOVED_TO);
EVENT(IN_CREATE);
EVENT(IN_DELETE);
EVENT(IN_DELETE_SELF);
EVENT(IN_MOVE_SELF);
EVENT(IN_UNMOUNT);
EVENT(IN_Q_OVERFLOW);
EVENT(IN_IGNORED);
EVENT(IN_ISDIR);
#undef EVENT
os << ")";
if (ie->cookie != 0) os << ", cookie=" << ie->cookie;
if (ie->len != 0) os << ", name='" << ie->name << "'";
os << "}";
return os.str();
}
#endif
static int statSyscall(const std::string& path, struct stat* buf) {
int ret = ::stat(path.c_str(), buf);
if (ret == 0) {
TRACE(5, "StatCache: stat '%s' %s\n",
path.c_str(), statToString(buf).c_str());
} else {
TRACE(5, "StatCache: stat '%s' --> error\n", path.c_str());
}
return ret;
}
static int lstatSyscall(const std::string& path, struct stat* buf) {
int ret = ::lstat(path.c_str(), buf);
if (ret == 0) {
TRACE(5, "StatCache: lstat '%s' %s\n",
path.c_str(), statToString(buf).c_str());
} else {
TRACE(5, "StatCache: lstat '%s' --> error\n", path.c_str());
}
return ret;
}
static std::string readlinkSyscall(const std::string& path) {
char lbuf[PATH_MAX + 1];
ssize_t llen = ::readlink(path.c_str(), lbuf, sizeof(lbuf) - 1);
if (llen == -1) {
TRACE(5, "StatCache: readlink('%s') --> error\n", path.c_str());
return "";
}
lbuf[llen] = '\0';
TRACE(5, "StatCache: readlink('%s') --> '%s'\n", path.c_str(), lbuf);
return lbuf;
}
static std::string realpathLibc(const char* path) {
char buf[PATH_MAX];
std::string ret;
if (!::realpath(path, buf)) {
TRACE(5, "StatCache: realpath('%s') --> error\n", path);
return ret;
}
TRACE(5, "StatCache: realpath('%s') --> '%s'\n", path, buf);
ret = buf;
return ret;
}
//==============================================================================
// StatCache::Node.
StatCache::Node::Node(StatCache& statCache, int wd /* = -1 */)
: m_statCache(statCache),
m_lock(false /*reentrant*/, RankStatCacheNode),
m_wd(wd), m_valid(false), m_inExpirePaths(false) { }
void StatCache::Node::atomicRelease() {
if (m_wd != -1) {
m_statCache.removeWatch(m_wd);
}
touchLocked<true>();
detachLocked();
TRACE(1, "StatCache: delete node '%s'\n", m_path.c_str());
delete this;
}
template <bool removePaths>
void StatCache::Node::touchLocked(bool invalidate /* = true */) {
TRACE(1, "StatCache: touch %snode '%s'%s\n",
m_valid ? "" : "invalid ",
m_path.c_str(), removePaths ? " (remove paths)" : "");
if ((invalidate && m_valid) || removePaths) {
// Call path invalidation callback once for each path associated with this
// node and/or remove paths.
for (NameMap::const_iterator it = m_paths.begin(); it != m_paths.end();
++it) {
if (invalidate && m_valid) {
TRACE(1, "StatCache: invalidate path '%s'\n", it->first.c_str());
HPHP::invalidatePath(it->first);
}
if (removePaths) {
m_statCache.removePath(it->first, this);
}
}
for (NameMap::const_iterator it = m_lpaths.begin(); it != m_lpaths.end();
++it) {
if (invalidate && m_valid) {
// Avoid duplicate invalidations.
NameMap::const_iterator it2 = m_paths.find(it->first);
if (it2 == m_paths.end()) {
TRACE(1, "StatCache: invalidate link path '%s'\n", it->first.c_str());
HPHP::invalidatePath(it->first);
}
}
if (removePaths) {
m_statCache.removeLPath(it->first, this);
}
}
if (removePaths) {
m_paths.clear();
m_lpaths.clear();
}
}
m_link.clear();
m_valid = false;
}
void StatCache::Node::touch(bool invalidate /* = true */) {
SimpleLock lock(m_lock);
touchLocked<false>(invalidate);
}
void StatCache::Node::detachLocked() {
m_children.clear();
m_lChildren.clear();
}
void StatCache::Node::expirePaths(bool invalidate /* = true */) {
NameNodeMap children, lChildren;
{
SimpleLock lock(m_lock);
if (m_inExpirePaths) {
// Terminate loop in recursion.
return;
}
touchLocked<true>(invalidate);
children = m_children;
lChildren = m_lChildren;
// expirePaths() is only called in situations where the entire subtree
// needs to be completely invalidated. If there were call for a 'touch'
// operation, then the detachLocked() call would need to be omitted.
detachLocked();
m_inExpirePaths = true;
}
for (NameNodeMap::const_iterator it = children.begin(); it != children.end();
++it) {
it->second->expirePaths(invalidate);
}
for (NameNodeMap::const_iterator it = lChildren.begin();
it != lChildren.end(); ++it) {
// Only recurse if this node differs from the equivalent one in children,
// in order to keep recursion from being of exponential complexity.
NameNodeMap::const_iterator it2 = children.find(it->first);
if (it2 == children.end() || it->second.get() != it2->second.get()) {
it->second->expirePaths(invalidate);
}
}
SimpleLock lock(m_lock);
m_inExpirePaths = false;
}
bool StatCache::Node::validate(const std::string& path, bool& cached) {
if (!m_valid) {
if (statSyscall(path, &m_stat) == -1) {
TRACE(4, "StatCache: stat '%s' --> error (node=%p)\n",
path.c_str(), this);
return true;
}
TRACE(4, "StatCache: stat '%s' %s (node=%p)\n",
path.c_str(), statToString(&m_stat).c_str(), this);
if (lstatSyscall(path, &m_lstat) == -1) {
TRACE(4, "StatCache: lstat '%s' --> error (node=%p)\n",
path.c_str(), this);
return true;
}
TRACE(4, "StatCache: lstat '%s' %s (node=%p)\n",
path.c_str(), statToString(&m_lstat).c_str(), this);
m_valid = true;
cached = false;
} else {
TRACE(4, "StatCache: stat '%s' (node=%p, cached)\n", path.c_str(), this);
TRACE(4, "StatCache: lstat '%s' (node=%p, cached)\n", path.c_str(), this);
cached = true;
}
setPath(path);
return false;
}
void StatCache::Node::sanityCheck(const std::string& path, bool isStat,
const struct stat* buf, time_t lastRefresh) {
struct stat tbuf;
int err = isStat ? statSyscall(path, &tbuf) : lstatSyscall(path, &tbuf);
if (err != -1 && !statEquiv(buf, &tbuf)) {
if (lastRefresh == 0) {
lastRefresh = m_statCache.lastRefresh();
}
// stat info has changed since it was cached. If the changes were all made
// prior to the most recent refresh (excluding atime, since IN_ACCESS
// events aren't being processed), then they generally should have been
// merged into the cache during the refresh. Reality is a bit messier
// because inotify is asynchronous; the delay between a filesystem
// modification and the availability of a corresponding inotify event makes
// it possible for the most recent refresh to have missed in-flight
// notifications.
if (tbuf.st_mtime < lastRefresh && tbuf.st_ctime < lastRefresh) {
TRACE(0, "StatCache: suspect cached %s '%s' %s (node=%p);"
" actual %s; last refresh %lu\n", isStat ? "stat" : "lstat",
path.c_str(),
statToString(buf).c_str(), this,
statToString(&tbuf).c_str(), (unsigned long)lastRefresh);
}
}
}
int StatCache::Node::stat(const std::string& path, struct stat* buf,
time_t lastRefresh /* = 0 */) {
bool cached;
{
SimpleLock lock(m_lock);
if (validate(path, cached)) {
return -1;
}
m_paths.insert(std::make_pair(path, this));
memcpy(buf, &m_stat, sizeof(struct stat));
}
if (debug && cached) {
sanityCheck(path, true, buf, lastRefresh);
}
return 0;
}
int StatCache::Node::lstat(const std::string& path, struct stat* buf,
time_t lastRefresh /* = 0 */) {
bool cached;
{
SimpleLock lock(m_lock);
if (validate(path, cached)) {
return -1;
}
m_lpaths.insert(std::make_pair(path, this));
memcpy(buf, &m_lstat, sizeof(struct stat));
}
if (debug && cached) {
sanityCheck(path, false, buf, lastRefresh);
}
return 0;
}
bool StatCache::Node::isLinkLocked() {
m_lock.assertOwnedBySelf();
return S_ISLNK(m_lstat.st_mode);
}
bool StatCache::Node::isLink() {
SimpleLock lock(m_lock);
return isLinkLocked();
}
std::string StatCache::Node::readlink(const std::string& path,
time_t lastRefresh /* = 0 */) {
std::string link;
bool cached;
struct stat buf;
{
SimpleLock lock(m_lock);
if (validate(path, cached) || !isLinkLocked()) {
return "";
}
if (debug && cached) {
memcpy(&buf, &m_lstat, sizeof(struct stat));
}
if (m_link.size() == 0) {
m_link = readlinkSyscall(path);
}
link = m_link;
}
if (debug && cached) {
sanityCheck(path, false, &buf, lastRefresh);
}
return link;
}
void StatCache::Node::insertChild(const std::string& childName,
StatCache::NodePtr child, bool follow) {
auto& map = follow ? m_children : m_lChildren;
if (!map.insert(std::make_pair(childName, child)).second) {
assert(0); // should not already exist in the map here.
}
}
void StatCache::Node::removeChild(const std::string& childName) {
if (m_children.count(childName)) {
m_children.erase(childName);
}
if (m_lChildren.count(childName)) {
m_lChildren.erase(childName);
}
}
StatCache::NodePtr StatCache::Node::getChild(const std::string& childName,
bool follow) {
return folly::get_default(follow ? m_children : m_lChildren, childName);
}
//==============================================================================
// StatCache.
StatCache::StatCache()
: m_lock(false /*reentrant*/, RankStatCache), m_ifd(-1),
m_lastRefresh(time(nullptr)) {
}
StatCache::~StatCache() {
clear();
}
bool StatCache::init() {
// inotify_init1() directly supports the fcntl() settings, but it's only
// available starting in Linux 2.6.27.
#ifdef __linux__
if ((m_ifd = inotify_init()) == -1
|| fcntl(m_ifd, F_SETFD, FD_CLOEXEC) == -1
|| fcntl(m_ifd, F_SETFL, O_NONBLOCK) == -1
|| (m_root = getNode("/", false)).get() == nullptr) {
clear();
return true;
}
return false;
#else
return true;
#endif
}
void StatCache::clear() {
if (m_ifd != -1) {
close(m_ifd);
m_ifd = -1;
}
m_watch2Node.clear();
// It's unsafe to reset() m_path2Node / m_lpath2Node while concurrent
// accessors might be touching it. Recursively letting them remove
// themselves via expiry will remove them one by one via erase(). The call
// to expirePaths() cannot be safely omitted, because it would otherwise be
// possible for a symlink-induced cycle to keep some or all of the node tree
// alive.
if (m_root.get()) {
m_root->expirePaths();
}
m_root = nullptr;
assert(m_path2Node.size() == 0);
assert(m_lpath2Node.size() == 0);
}
void StatCache::reset() {
clear();
init();
}
StatCache::NodePtr StatCache::getNode(const std::string& path, bool follow) {
#ifdef __linux__
int wd = inotify_add_watch(m_ifd, path.c_str(),
0
| IN_MODIFY
| IN_ATTRIB
| IN_MOVED_FROM
| IN_MOVED_TO
| IN_CREATE
| IN_DELETE
| (follow ? 0 : IN_DONT_FOLLOW)
| IN_ONLYDIR);
if (wd == -1 && errno != ENOTDIR) {
TRACE(2, "StatCache: getNode('%s', follow=%s) failed\n",
path.c_str(), follow ? "true" : "false");
return NodePtr(nullptr);
}
NodePtr node;
if (wd != -1) {
node = folly::get_default(m_watch2Node, wd);
if (!node.get()) {
node = new Node(*this, wd);
if (!m_watch2Node.insert(std::make_pair(wd, node)).second) {
assert(0); // should not already exist in the map
}
TRACE(2, "StatCache: getNode('%s', follow=%s) --> %p (wd=%d)\n",
path.c_str(), follow ? "true" : "false", node.get(), wd);
} else {
TRACE(3, "StatCache: getNode('%s', follow=%s) --> alias %p (wd=%d)\n",
path.c_str(), follow ? "true" : "false", node.get(), wd);
}
} else {
node = new Node(*this);
TRACE(3, "StatCache: getNode('%s', follow=%s) --> %p\n",
path.c_str(), follow ? "true" : "false", node.get());
}
node->setPath(path);
return node;
#else
return NodePtr(nullptr);
#endif
}
bool StatCache::mergePath(const std::string& path, bool follow) {
String canonicalPath = FileUtil::canonicalize(path);
std::vector<std::string> pvec;
folly::split('/', canonicalPath.slice(), pvec);
assert((pvec[0].size() == 0)); // path should be absolute.
// Lazily initialize so that if StatCache never gets used, no kernel
// resources are consumed.
if (m_ifd == -1 && init()) {
return true;
}
NodePtr curNode = m_root;
std::string curPath = "/";
for (unsigned i = 1; i < pvec.size(); ++i) {
// Follow links unless 'follow' is false and this is the last path
// component.
bool curFollow = (follow || i + 1 < pvec.size());
curPath += pvec[i];
NodePtr child = curNode->getChild(pvec[i], curFollow);
if (child.get() == nullptr) {
child = getNode(curPath, curFollow);
if (child.get() == nullptr) {
return true;
}
curNode->insertChild(pvec[i], child, curFollow);
}
curNode = child;
curPath += "/";
}
NameNodeMap::accessor acc;
NameNodeMap& p2n = follow ? m_path2Node : m_lpath2Node;
if (p2n.insert(acc, path)) {
acc->second = curNode;
TRACE(1, "StatCache: merge '%s' --> %p (follow=%s)\n",
path.c_str(), curNode.get(), follow ? "true" : "false");
}
return false;
}
#ifdef __linux__
bool StatCache::handleEvent(const struct inotify_event* event) {
if (event->mask & IN_Q_OVERFLOW) {
// The event queue overflowed, so all bets are off. Start over.
TRACE(0, "StatCache: event queue overflowed\n");
reset();
return true;
}
assert(event->wd != -1);
NodePtr node = folly::get_default(m_watch2Node, event->wd);
if (!node.get()) {
TRACE(1, "StatCache: inotify event (obsolete) %s\n",
eventToString(event).c_str());
return false;
}
TRACE(1, "StatCache: inotify event for '%s': %s\n",
node->path().c_str(), eventToString(event).c_str());
if (event->mask & (IN_MODIFY|IN_ATTRIB)) {
bool touched = false;
NodePtr child = node->getChild(event->name, true);
if (child.get() != nullptr) {
if ((event->mask & IN_MODIFY) && child->isLink()) {
// A modified link is logically equivalent to IN_MOVED_FROM.
child->expirePaths();
node->removeChild(event->name);
} else {
child->touch();
}
touched = true;
}
child = node->getChild(event->name, false);
if (child.get() != nullptr) {
// The follow=false child is equivalent to the follow=true child unless
// it's a link. Avoid duplicate invalidations for non-links.
child->touch(!touched || child->isLink());
}
}
if (event->mask & (IN_MOVED_FROM|IN_MOVED_TO|IN_CREATE|IN_DELETE)) {
// The directory itself was modified, so invalidate its cached stat
// structure.
node->touch();
// Recursively invalidate the cached paths rooted at "node/name".
bool expired = false;
NodePtr child = node->getChild(event->name, true);
if (child.get() != nullptr) {
child->expirePaths();
expired = true;
}
child = node->getChild(event->name, false);
if (child.get() != nullptr) {
// The follow=false child is equivalent to the follow=true child unless
// it's a link. Avoid duplicate invalidations for non-links.
child->expirePaths(!expired || child->isLink());
expired = true;
}
if (expired) {
node->removeChild(event->name);
}
}
if (event->mask & IN_IGNORED) {
// The kernel removed the directory watch, either as a side effect of
// directory deletion, or because inotify_rm_watch() was explicitly called
// during Node destruction. Delete the corresponding entry from
// m_watch2Node. Removal should always succeed here because no other code
// performs removal.
m_watch2Node.erase(event->wd);
}
return false;
}
#endif
void StatCache::removeWatch(int wd) {
#ifdef __linux__
inotify_rm_watch(m_ifd, wd);
#endif
}
void StatCache::removePath(const std::string& path, Node* node) {
NameNodeMap::accessor acc;
if (m_path2Node.find(acc, path) && acc->second.get() == node) {
TRACE(1, "StatCache: remove path '%s'\n", path.c_str());
m_path2Node.erase(acc);
}
}
void StatCache::removeLPath(const std::string& path, Node* node) {
NameNodeMap::accessor acc;
if (m_lpath2Node.find(acc, path) && acc->second.get() == node) {
TRACE(1, "StatCache: remove link path '%s'\n", path.c_str());
m_lpath2Node.erase(acc);
}
}
void StatCache::refresh() {
#ifdef __linux__
SimpleLock lock(m_lock);
if (m_ifd == -1) {
return;
}
while (true) {
int nread = read(m_ifd, m_readBuf, kReadBufSize);
if (nread == -1) {
// No pending events.
assert(errno == EAGAIN);
// Record the last refresh time *after* processing the event queue, in
// order to assure that once the event queue has been merged into the
// cache state, all cached values have timestamps older than
// m_lastRefresh (assuming no timestamps are ever set into the future).
m_lastRefresh = time(nullptr);
TRACE(1, "StatCache: refresh time %lu\n", (unsigned long)m_lastRefresh);
return;
}
for (char* p = m_readBuf; p < m_readBuf + nread;) {
struct inotify_event* event = (struct inotify_event*) p;
if (handleEvent(event)) {
return;
}
p += sizeof(struct inotify_event) + event->len;
}
}
#endif
}
time_t StatCache::lastRefresh() {
SimpleLock lock(m_lock);
return m_lastRefresh;
}
int StatCache::statImpl(const std::string& path, struct stat* buf) {
// Punt if path is relative.
if (path.size() == 0 || path[0] != '/') {
return statSyscall(path, buf);
}
{
NameNodeMap::const_accessor acc;
if (m_path2Node.find(acc, path)) {
return acc->second->stat(path, buf);
}
}
{
SimpleLock lock(m_lock);
if (mergePath(path, true)) {
return statSyscall(path, buf);
}
{
NameNodeMap::const_accessor acc;
if (m_path2Node.find(acc, path)) {
return acc->second->stat(path, buf, m_lastRefresh);
}
}
}
not_reached();
}
int StatCache::lstatImpl(const std::string& path, struct stat* buf) {
// Punt if path is relative.
if (path.size() == 0 || path[0] != '/') {
return statSyscall(path, buf);
}
{
NameNodeMap::const_accessor acc;
if (m_lpath2Node.find(acc, path)) {
return acc->second->lstat(path, buf);
}
}
{
SimpleLock lock(m_lock);
if (mergePath(path, false)) {
return lstatSyscall(path, buf);
}
{
NameNodeMap::const_accessor acc;
if (m_lpath2Node.find(acc, path)) {
return acc->second->lstat(path, buf, m_lastRefresh);
}
}
}
not_reached();
}
std::string StatCache::readlinkImpl(const std::string& path) {
// Punt if path is relative.
if (path.size() == 0 || path[0] != '/') {
return readlinkSyscall(path);
}
{
NameNodeMap::const_accessor acc;
if (m_lpath2Node.find(acc, path)) {
return acc->second->readlink(path);
}
}
{
SimpleLock lock(m_lock);
if (mergePath(path, false)) {
return readlinkSyscall(path);
}
{
NameNodeMap::const_accessor acc;
if (m_lpath2Node.find(acc, path)) {
return acc->second->readlink(path, m_lastRefresh);
}
}
}
not_reached();
}
// StatCache::realpath() is based on the realpath(3) implementation that is
// part of FreeBSD's libc. The following license applies:
/*
* Copyright (c) 2003 Constantin S. Svintsoff <kostik@iclub.nsu.ru>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The names of the authors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
#if 0
__FBSDID("$FreeBSD: src/lib/libc/stdlib/realpath.c,v 1.24 2011/11/04 19:56:34 ed Exp $");
#endif
// Find the real name of path, by removing all ".", ".." and symlink
// components. Returns the resolved path on success, or "" on failure,
std::string StatCache::realpathImpl(const char* path) {
std::string resolved;
assert(path != nullptr);
if (path[0] != '/') {
return realpathLibc(path);
}
struct stat sb;
unsigned symlinks;
std::string left, next_token, symlink;
size_t left_pos;
symlinks = 0;
resolved += "/";
if (path[1] == '\0') {
TRACE(4, "StatCache: realpath('%s') --> '%s'\n", path, resolved.c_str());
return resolved;
}
left = path;
left_pos = 0;
// Iterate over path components in `left'.
while (left.size() - left_pos != 0) {
// Extract the next path component and adjust `left' and its length.
size_t pos = left.find_first_of('/', left_pos);
next_token = left.substr(left_pos, pos - left_pos);
left_pos += next_token.size();
if (pos != std::string::npos) {
++left_pos;
}
if (resolved[resolved.size() - 1] != '/') {
resolved += "/";
}
if (next_token.size() == 0) {
continue;
} else if (next_token.compare(".") == 0) {
continue;
} else if (next_token.compare("..") == 0) {
// Strip the last path component except when we have single "/".
if (resolved.size() > 1) {
resolved.erase(resolved.size() - 1);
resolved.erase(resolved.find_last_of('/') + 1);
}
continue;
}
// Append the next path component and lstat() it. If lstat() fails we still
// can return successfully if there are no more path components left.
resolved += next_token;
if (lstatImpl(resolved, &sb) != 0) {
if (errno == ENOENT && pos == std::string::npos) {
TRACE(4, "StatCache: realpath('%s') --> '%s'\n",
path, resolved.c_str());
return resolved;
}
TRACE(4, "StatCache: realpath('%s') --> error\n", path);
return "";
}
if (S_ISLNK(sb.st_mode)) {
if (symlinks++ > MAXSYMLINKS) {
TRACE(4, "StatCache: realpath('%s') --> error\n", path);
return "";
}
symlink = readlinkImpl(resolved);
if (symlink.size() == 0) {
TRACE(4, "StatCache: realpath('%s') --> error\n", path);
return "";
}
if (symlink[0] == '/') {
resolved.erase(1);
} else if (resolved.size() > 1) {
// Strip the last path component.
resolved.erase(resolved.size() - 1);
resolved.erase(resolved.find_last_of('/') + 1);
}
// If there are any path components left, then append them to symlink.
// The result is placed in `left'.
if (pos != std::string::npos) {
if (symlink[symlink.size() - 1] != '/') {
symlink += "/";
}
symlink += left.substr(left_pos);
}
left = symlink;
left_pos = 0;
}
}
// Remove trailing slash except when the resolved pathname is a single "/".
if (resolved.size() > 1 && resolved[resolved.size() - 1] == '/') {
resolved.erase(resolved.size() - 1);
}
TRACE(4, "StatCache: realpath('%s') --> '%s'\n", path, resolved.c_str());
return resolved;
}
StatCache StatCache::s_sc;
void StatCache::requestInit() {
if (!RuntimeOption::ServerStatCache) return;
s_sc.refresh();
}
int StatCache::stat(const std::string& path, struct stat* buf) {
if (!RuntimeOption::ServerStatCache) return statSyscall(path, buf);
return s_sc.statImpl(path, buf);
}
int StatCache::lstat(const std::string& path, struct stat* buf) {
if (!RuntimeOption::ServerStatCache) return lstatSyscall(path, buf);
return s_sc.lstatImpl(path, buf);
}
std::string StatCache::readlink(const std::string& path) {
if (!RuntimeOption::ServerStatCache) return readlinkSyscall(path);
return s_sc.readlinkImpl(path);
}
std::string StatCache::realpath(const char* path) {
if (!RuntimeOption::ServerStatCache) return realpathLibc(path);
return s_sc.realpathImpl(path);
}
///////////////////////////////////////////////////////////////////////////////
}
|
bd87856c0ac3fe00ae582964a9f9e66786cda483
|
b22c189f38b8da715e70b76be3d9c0f3bb921f63
|
/DATA STRUCTURES AND ALGORITHMS/Prirority_queues/inplace_heap_sort.cpp
|
fef79073c39fbfe038b0d1e73584c379131178bd
|
[] |
no_license
|
Bikubisw/Coding
|
108f1048bc54bbd526f2f3abea21bd17bb8e7975
|
274c50caab15f10663a83ad352fc5ddb04b9e236
|
refs/heads/master
| 2023-04-20T11:09:32.555814
| 2021-05-22T20:29:45
| 2021-05-22T20:29:45
| 280,332,695
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,277
|
cpp
|
inplace_heap_sort.cpp
|
#include<iostream>
using namespace std;
void inplaceHeapsort(int* input,int n){
for(int i=1;i<n;i++){
int childindex=i;
while(childindex>0){
int parentindex=(childindex-1)/2;
if(input[childindex]<input[parentindex]){
int temp=input[childindex];
input[childindex]=input[parentindex];
input[parentindex]=temp;
}
else{
break;
}
childindex=parentindex;
}
}
int size=n;
while(size>1){
int temp=input[0];
input[0]=input[size-1];
input[size-1]=temp;
size--;
int parentindex=0;
int leftindex=2*parentindex+1;
int rightindex=2*parentindex+2;
while(leftindex<size){
int minindex=parentindex;
if(input[minindex]>input[leftindex]){
minindex=leftindex;
}
if(input[minindex]>input[rightindex]&& rightindex<size){
minindex=rightindex;
}
if(minindex==parentindex){
break;
}
int temp=input[minindex];
input[minindex]=input[parentindex];
input[parentindex]=temp;
parentindex=minindex;
leftindex=2*parentindex+1;
rightindex=2*parentindex+2;
}
}
}
int main(){
int size;
cin>>size;
int *input=new int[size+1];
for(int i=0;i<size;i++){
cin>>input[i];
}
inplaceHeapsort(input,size);
for(int i=0;i<size;i++){
cout<<input[i]<<" ";
}
delete [] input;
}
|
d3e2ccfed0270e8dad7225c54325214fa842b205
|
00adc3d26ece42c6626680b0526e737adf23eb35
|
/src/api/dto/error_response.h
|
1f0cc698fc64292bb4a647853914c8cb766afea6
|
[
"MIT"
] |
permissive
|
i96751414/torrest-cpp
|
2fa14fae6b03226ea90498f0c7588b484102648d
|
21348e7d9cf952c49556ef1dcf08eb91b859bee1
|
refs/heads/master
| 2023-08-03T06:56:58.975473
| 2023-06-17T13:55:47
| 2023-06-17T13:55:47
| 354,607,307
| 10
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 585
|
h
|
error_response.h
|
#ifndef TORREST_ERROR_RESPONSE_H
#define TORREST_ERROR_RESPONSE_H
#include "api/dto/utils.h"
namespace torrest { namespace api {
#include OATPP_CODEGEN_BEGIN(DTO)
class ErrorResponse : public oatpp::DTO {
DTO_INIT(ErrorResponse, DTO)
FIELD(String, error, "Error message")
static oatpp::data::mapping::type::DTOWrapper<ErrorResponse> create(const oatpp::String &pError) {
auto response = ErrorResponse::createShared();
response->error = pError;
return response;
}
};
#include OATPP_CODEGEN_END(DTO)
}}
#endif //TORREST_ERROR_RESPONSE_H
|
9f5e9934bfaeefa48bb8d2159def019cc2dd3b0c
|
93e22e4c66f0b5d7407e1bd7ef881ae18ad8dab1
|
/Contests/IV Escola de Inverno da Unifei/Intermediário - Dia 2/1799Gabriel.cpp
|
b5057c41563f91afd3c1c77f0ece45ffe782bd4e
|
[] |
no_license
|
gustavochermout/maratona-final
|
b34325e3b986ac61f47bfb3cb7dbbc99440bee40
|
26f3a86827cc19e083f2b0d7ff368e0a91feafa6
|
refs/heads/master
| 2021-01-16T00:42:46.220626
| 2020-06-11T22:33:46
| 2020-06-11T22:33:46
| 99,975,191
| 0
| 0
| null | 2017-08-11T00:20:20
| 2017-08-11T00:20:20
| null |
UTF-8
|
C++
| false
| false
| 982
|
cpp
|
1799Gabriel.cpp
|
/*input
10 11
B A
Entrada A
B GT
GT H
H *
B *
* C
C I
I D
C D
D Saida
*/
#include <bits/stdc++.h>
using namespace std;
#define all(v) (v).begin(), (v).end()
#define pb push_back
#define fst first
#define snd second
#define debug(x) cout << #x << " = " << x << endl;
typedef long long ll;
typedef pair<int, int> ii;
int n, m;
vector<int> graph[5000];
int bfs(int s, int d){
vector<int> dist(n, 1<<30);
dist[s] = 0;
queue<int> q;
q.push(s);
while(!q.empty()){
int u = q.front(); q.pop();
for(auto v : graph[u]){
if(dist[v] == 1<<30){
dist[v] = dist[u] + 1;
q.push(v);
}
}
}
return dist[d];
}
int main(){
cin >> n >> m;
map<string, int> mp;
int idx = 0;
string s1, s2;
while(m--){
cin >> s1 >> s2;
if(mp.find(s1) == mp.end())
mp[s1] = idx++;
if(mp.find(s2) == mp.end())
mp[s2] = idx++;
graph[mp[s1]].pb(mp[s2]);
graph[mp[s2]].pb(mp[s1]);
}
cout << bfs(mp["Entrada"], mp["*"]) + bfs(mp["*"], mp["Saida"]) << endl;
return 0;
}
|
5bd36a9642dacfab37813b06da9cd13a04667c89
|
389dcada03249a7665550a9e05bb49dd38b0163e
|
/initiation_and_control.cpp
|
961729b62fc28a20bcf4720f85fad6e72457c4d9
|
[] |
no_license
|
dprefontaine/shrimpyrevenge
|
3dba7b910c5637aaaf1685fbc78c1c359f7e91b7
|
766dddb72b73ac5d568f241aecfc9a6c7da21c7b
|
refs/heads/master
| 2021-08-05T10:56:03.435892
| 2021-07-01T08:17:19
| 2021-07-01T08:17:19
| 167,265,845
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,510
|
cpp
|
initiation_and_control.cpp
|
#include <initiation_and_control.h>
//CODE OF INITIATION AND CLOSING PROCEDURES, AS WELL AS GENERAL CONTROL PROCEDURES DURING THE GAME
//
bool initialize(){
//INITIATION FLAG
bool init_flag = true;
for (int i = 0; i < TOTAL_FONTS; i++)
fonts[i] = NULL;
//START BY INITIALIZING BASE SDL
//
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) < 0){
std::cout << "Failed to initialize: " << SDL_GetError() << std::endl;
init_flag = false;
} else {
//INITIALIZING WINDOW
//
if (!(window.init(SCREEN_NAME))){
std::cout << "Failed to create window: " << SDL_GetError() << std::endl;
init_flag = false;
} else {
//INITIALIZE RENDERER AND OTHER ELEMENTS
//
renderer = window.create_renderer();
if (renderer == NULL){
std::cout << "Failed to create renderer: " << SDL_GetError() << std::endl;
init_flag = false;
} else {
SDL_SetRenderDrawColor(renderer,0x00,0x00,0x00,0xFF);
SDL_RenderClear(renderer);
//INITIALIZING IMAGE LIBRARY
//
int png_flag = IMG_INIT_PNG;
if (!(IMG_Init(png_flag) & png_flag)){
std::cout << "Failed to load png images: " << IMG_GetError() << std::endl;
}
}
//INITIALIZING TRUETYPEFONTS
//
if (TTF_Init() == -1){
std::cout << "Failed to initialize TTF: " << TTF_GetError() << std::endl;
} else {
fonts[1] = TTF_OpenFont("fonts/ANDYFISH.ttf",64);
fonts[2] = TTF_OpenFont("fonts/fishsausages.ttf",23);
}
//INITIALIZING MIXER
//
if (Mix_OpenAudio(44100,MIX_DEFAULT_FORMAT,2,2048) < 0){
std::cout << "Failed to initiate sound mixer!" << Mix_GetError() << std::endl;
init_flag = false;
}
SDL_EnableScreenSaver();
SDL_StartTextInput();
}
}
return init_flag;
}
void close(){
//Clear window
//
std::cout << "Clearing window........";
window.free();
window.~m_window();
std::cout << "successfully closed!" << std::endl;
//Clear renderer
//
std::cout << "Clearing renderer........";
SDL_DestroyRenderer(renderer);
renderer = NULL;
std::cout << "successfully closed!" << std::endl;
////ENDING SDL ACTIVITIES
//
std::cout << "Ending SDL activities........";
SDL_DisableScreenSaver();
SDL_StopTextInput();
std::cout << " successfully closed!" << std::endl;
//
std::cout << "Quitting SDL resources........" << std::endl;
Mix_Quit();
std::cout << "Mixer successfully closed!" << std::endl;
TTF_Quit();
std::cout << "TTF successfully closed!" << std::endl;
IMG_Quit();
std::cout << "IMG successfully closed!" << std::endl;
std::cout << "Quitting SDL........";
SDL_Quit();
std::cout << " successfully closed!" << std::endl;
}
bool load_rooms(){
bool room_flag = true;
for (int i = 0; i < ROOM_TOTAL; i++){
std::cout << "Room #" << i;
room_flag = rooms[i].load_room(i);
if (room_flag)
std::cout << " successfully loaded!" << std::endl;
else
std::cout << " failed to load: " << SDL_GetError() << std::endl;
}
return room_flag;
}
|
d5710c8f51053d5f57c0fd966f139c2582a434fc
|
aeca35cd0be358ac5a5fa7d9564a6170d942b7c1
|
/task1.cpp
|
5e9eb9bd1918bc7615322e7c83c5c8a4d2016b29
|
[] |
no_license
|
Margo-V/tasks-for-training-functions
|
1ea15058ff6c3ccf30c4ea703b629439926df58c
|
44114bc98900a8e006413dfe6c1f9b1b4c191dfe
|
refs/heads/master
| 2023-03-06T14:24:07.564985
| 2021-02-22T15:24:57
| 2021-02-22T15:24:57
| 341,243,056
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 14,416
|
cpp
|
task1.cpp
|
#include "task1.h"
int leapYear1(int y1_1, int m1_1, int d1_1, int *days1_1, int *daysToYear1_1) {
if (y1_1 % 4 == 0) {
*days1_1 = 0, * daysToYear1_1 = 0;
cout << y1_1 << " - високосный год" << endl;
if (m1_1 == 1) {
*days1_1 = 31 - d1_1;
*daysToYear1_1 = *days1_1 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31;
return *daysToYear1_1;
}
else if (m1_1 == 2) {
*days1_1 = 29 - d1_1;
*daysToYear1_1 = *days1_1 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31;
return *daysToYear1_1;
}
}
}
int leapYear2(int *y2_1, int *m2_1, int *d2_1, int *days2_1, int *daysAfterYear2_1) {
if (*y2_1 % 4 == 0) {
cout << *y2_1 << " - високосный год" << endl;
*days2_1 = 0, * daysAfterYear2_1 = 0;
switch (*m2_1) {
case 1:
if (*d2_1 > 0 && *d2_1 < 32) {
*days2_1 = 31 - *d2_1;
*daysAfterYear2_1 += *d2_1;
}
else {
cout << "В январе 31 день, введите корректную дату" << endl;
}
break;
case 2:
if (*d2_1 > 0 && *d2_1 < 30) {
*days2_1 = 29 - *d2_1;
*daysAfterYear2_1 = 31 + *d2_1;
}
else {
cout << "В феврале 28 или 29 день, введите корректную дату" << endl;
}
break;
case 3:
if (*d2_1 > 0 && *d2_1 < 32) {
*days2_1 = 31 - *d2_1;
*daysAfterYear2_1 = 31 + 29 + *d2_1;
}
else {
cout << "В марте 31 день, введите корректную дату" << endl;
}
break;
case 4:
if (*d2_1 > 0 && *d2_1 < 31) {
*days2_1 = 30 - *d2_1;
*daysAfterYear2_1 = 31 + 29 + 31 + *d2_1;
}
else {
cout << "В апреле 30 день, введите корректную дату" << endl;
}
break;
case 5:
if (*d2_1 > 0 && *d2_1 < 32) {
*days2_1 = 31 - *d2_1;
*daysAfterYear2_1 = 31 + 29 + 31 + 30 + *d2_1;
}
else {
cout << "В мае 31 день, введите корректную дату" << endl;
}
break;
case 6:
if (*d2_1 > 0 && *d2_1 < 31) {
*days2_1 = 30 - *d2_1;
*daysAfterYear2_1 = 31 + 29 + 31 + 30 + 31 + *d2_1;
}
else {
cout << "В июне 30 день, введите корректную дату" << endl;
}
break;
case 7:
if (*d2_1 > 0 && *d2_1 < 32) {
*days2_1 = 31 - *d2_1;
*daysAfterYear2_1 = 31 + 29 + 31 + 30 + 31 + 30 + *d2_1;
}
else {
cout << "В миюле 31 день, введите корректную дату" << endl;
}
break;
case 8:
if (*d2_1 > 0 && *d2_1 < 32) {
*days2_1 = 31 - *d2_1;
*daysAfterYear2_1 = 31 + 29 + 31 + 30 + 31 + 30 + 31 + *d2_1;
}
else {
cout << "В августе 31 день, введите корректную дату" << endl;
}
break;
case 9:
if (*d2_1 > 0 && *d2_1 < 31) {
*days2_1 = 30 - *d2_1;
*daysAfterYear2_1 = 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + *d2_1;
}
else {
cout << "В сентябре 30 день, введите корректную дату" << endl;
}
break;
case 10:
if (*d2_1 > 0 && *d2_1 < 32) {
*days2_1 = 31 - *d2_1;
*daysAfterYear2_1 = 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + *d2_1;
}
else {
cout << "В октябре 31 день, введите корректную дату" << endl;
}
break;
case 11:
if (*d2_1 > 0 && *d2_1 < 31) {
*days2_1 = 30 - *d2_1;
*daysAfterYear2_1 = 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + *d2_1;
}
else {
cout << "В ноябре 30 день, введите корректную дату" << endl;
}
break;
case 12:
if (*d2_1 > 0 && *d2_1 < 32) {
*days2_1 = 31 - *d2_1;
*daysAfterYear2_1 = 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + *d2_1;
}
else {
cout << "В декабре 31 день, введите корректную дату" << endl;
}
break;
default:
cout << "Введите корректный месяц: " << endl;
}
}
return 0;
}
int date(int m1, int d1, int y1, int d2, int m2, int y2 ) {
enum months { January = 1, February, Martch, April, May, June, July, August, September, October, November, December };
int daysInYear = 365;
int userMonth;
int days1 = 0;
int days2 = 0;
int daysToYear = 0;
int daysAfterYear = 0;
switch (m1) {
case 1:
if (d1 > 0 && d1 < 32) {
days1 = 31 - d1;
daysToYear = days1 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31;
}
else {
cout << "В январе 31 день, введите корректную дату" << endl;
}
break;
case 2:
if (d1 > 0 && d1 < 30) {
days1 = 28 - d1;
cout << " " << endl;
daysToYear = days1 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31;
}
else {
cout << "В феврале 28 или 29 день, введите корректную дату" << endl;
}
break;
case 3:
if (d1 > 0 && d1 < 32) {
days1 = 31 - d1;
daysToYear = days1 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31;
}
else {
cout << "В марте 31 день, введите корректную дату" << endl;
}
break;
case 4:
if (d1 > 0 && d1 < 31) {
days1 = 30 - d1;
daysToYear = days1 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31;
}
else {
cout << "В апреле 30 день, введите корректную дату" << endl;
}
break;
case 5:
if (d1 > 0 && d1 < 32) {
days1 = 31 - d1;
daysToYear = days1 + 30 + 31 + 31 + 30 + 31 + 30 + 31;
}
else {
cout << "В мае 31 день, введите корректную дату" << endl;
}
break;
case 6:
if (d1 > 0 && d1 < 31) {
days1 = 30 - d1;
daysToYear = days1 + 31 + 31 + 30 + 31 + 30 + 31;
}
else {
cout << "В июне 30 день, введите корректную дату" << endl;
}
break;
case 7:
if (d1 > 0 && d1 < 32) {
days1 = 31 - d1;
daysToYear = days1 + 31 + 30 + 31 + 30 + 31;
}
else {
cout << "В июле 31 день, введите корректную дату" << endl;
}
break;
case 8:
if (d1 > 0 && d1 < 32) {
days1 = 31 - d1;
daysToYear = days1 + 30 + 31 + 30 + 31;
}
else {
cout << "В августе 31 день, введите корректную дату" << endl;
}
break;
case 9:
if (d1 > 0 && d1 < 31) {
days1 = 30 - d1;
daysToYear = days1 + 31 + 30 + 31;
}
else {
cout << "В сентябре 30 день, введите корректную дату" << endl;
}
break;
case 10:
if (d1 > 0 && d1 < 32) {
days1 = 31 - d1;
daysToYear = days1 + 30 + 31;
}
else {
cout << "В октябре 31 день, введите корректную дату" << endl;
}
break;
case 11:
if (d1 > 0 && d1 < 31) {
days1 = 30 - d1;
daysToYear = days1 + 31;
}
else {
cout << "В ноябре 30 день, введите корректную дату" << endl;
}
break;
case 12:
if (d1 > 0 && d1 < 32) {
days1 = 31 - d1;
daysToYear = days1;
}
else {
cout << "В декабре 31 день, введите корректную дату" << endl;
}
break;
default:
cout << "Введите корректный месяц: " << endl;
}
leapYear1(y1, m1, d1, &days1, &daysToYear);
leapYear2(&y2, &m2, &d2, &days2, &daysAfterYear);
int result = 0;
if (y1 == y2) {
if (y1 % 4 == 0) {
result = daysAfterYear - (366 - daysToYear);
}
else {
result = daysAfterYear - (365 - daysToYear);
}
return result;
}
else {
int year1_1 = y1;
int year2_2 = y2 -1;
while (year1_1 < year2_2) {
year1_1++;
if (year1_1 % 4 == 0) {
daysToYear += 366;
}
else {
daysToYear += 365;
}
}
}
switch (m2) {
case 1:
if (d2 > 0 && d2 < 32) {
days2 = 31 - d2;
daysAfterYear += d2;
}
else {
cout << "В январе 31 день, введите корректную дату" << endl;
}
break;
case 2:
if (d2 > 0 && d2 < 30) {
days2 = 28 - d2;
daysAfterYear = 31 + d2;
}
else {
cout << "В феврале 28 или 29 день, введите корректную дату" << endl;
}
break;
case 3:
if (d2 > 0 && d2 < 32) {
days2 = 31 - d2;
daysAfterYear = 31 + 28 + days2;
}
else {
cout << "В марте 31 день, введите корректную дату" << endl;
}
break;
case 4:
if (d2 > 0 && d2 < 31) {
days2 = 30 - d2;
daysAfterYear = 31 + 28 + 31 + d2;
}
else {
cout << "В апреле 30 день, введите корректную дату" << endl;
}
break;
case 5:
if (d2 > 0 && d2 < 32) {
days2 = 31 - d2;
daysAfterYear = 31 + 28 + 31 + 30 + d2;
}
else {
cout << "В мае 31 день, введите корректную дату" << endl;
}
break;
case 6:
if (d2 > 0 && d2 < 31) {
days2 = 30 - d2;
daysAfterYear = 31 + 28 + 31 + 30 + 31 + d2;
}
else {
cout << "В июне 30 день, введите корректную дату" << endl;
}
break;
case 7:
if (d2 > 0 && d2 < 32) {
days2 = 31 - d2;
daysAfterYear = 31 + 28 + 31 + 30 + 31 + 30 + d2;
}
else {
cout << "В миюле 31 день, введите корректную дату" << endl;
}
break;
case 8:
if (d2 > 0 && d2 < 32) {
days2 = 31 - d2;
daysAfterYear = 31 + 28 + 31 + 30 + 31 + 30 + 31 + d2;
}
else {
cout << "В августе 31 день, введите корректную дату" << endl;
}
break;
case 9:
if (d2 > 0 && d2 < 31) {
days2 = 30 - d2;
daysAfterYear = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + d2;
}
else {
cout << "В сентябре 30 день, введите корректную дату" << endl;
}
break;
case 10:
if (d2 > 0 && d2 < 32) {
days2 = 31 - d2;
daysAfterYear = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + d2;
}
else {
cout << "В октябре 31 день, введите корректную дату" << endl;
}
break;
case 11:
if (d2 > 0 && d2 < 31) {
days2 = 30 - d2;
daysAfterYear = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + d2;
}
else {
cout << "В ноябре 30 день, введите корректную дату" << endl;
}
break;
case 12:
if (d2 > 0 && d2 < 32) {
days2 = 31 - d2;
daysAfterYear = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + d2;
}
else {
cout << "В декабре 31 день, введите корректную дату" << endl;
}
break;
default:
cout << "Введите корректный месяц: " << endl;
}
leapYear2( &y2, &m2, &d2, &days2, &daysAfterYear);
daysToYear += daysAfterYear;
return daysToYear;
}
int task1()
{
int day1, day2, month1, month2, year1, year2;
int days1, days2;
int daysToYear = 0;
int daysAfterYear = 0;
int month = 0;
int year = 0;
cout << "Введите сначала меньшую дату, затем позднюю" << endl;
cout << "Введите первую дату - число дня: " << endl;
cin >> day1;
cout << "Номер месяца: " << endl;
cin >> month1;
cout << "Год: " << endl;
cin >> year1;
cout << "Введите вторую дату - число дня: " << endl;
cin >> day2;
cout << "Номер месяца: " << endl;
cin >> month2;
cout << "Год: " << endl;
cin >> year2;
cout << date(month1, day1, year1, day2, month2, year2) << " - Всего дней между " << day1 << "." << month1 << "." << year1 << " и " << day2 << "." << month2 << "." << year2 << endl;
return 0;
}
|
2128481658658d6f9ae5282489a4d7a767866f42
|
2bb2f325610c917432d6b0586b2ed4cf40cdc499
|
/source/AdaBoost/AdaBoost.h
|
b9d96a1758d83938c1a3a372111eb6a62bb8b147
|
[] |
no_license
|
skp2140/CliqueLib
|
bd077c4cfd4abc9c8430503755c971528faa7ce3
|
d8e54bc10746ced5bf2b7bdd9317292607fde6c2
|
refs/heads/master
| 2021-01-23T01:26:24.787938
| 2017-05-02T00:28:38
| 2017-05-02T00:28:38
| 85,907,608
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,109
|
h
|
AdaBoost.h
|
//============================================================================
// Name : AdaBoost.h
// Author : CliqueLib
// Version :
// Copyright :
// Description : CliqueLib AdaBoost definition
//============================================================================
#ifndef __ADABOOST_H__
#define __ADABOOST_H__
#pragma once
#include <iostream>
#include <memory>
#include <armadillo>
#include "Stump.h"
#include "BaseClassifier.h"
class AdaBoost : public BaseClassifier
{
private:
std::vector<std::shared_ptr<Stump>> weakClassifiers; /*!< A sequence of decision stumps trained on different dimension of data
*/
std::vector<double> weights; /*!< Sequence of weights learnt during training for each of the weak classifier
*/
public:
AdaBoost() {}
void train(const arma::mat&, const arma::colvec&, arma::uword); /**< The train function accepts a matrix of sample inputs,
a column vector of labels representing the ground truth,
and number of Stumps to create for training and prediction.
*/
void predict(const arma::mat&, arma::colvec&); /**< The predict function accepts a matrix of inputs
and a reference to an empty column vector which
shall be filled with the predicted labels
*/
std::shared_ptr<Stump> buildStump(const arma::mat&, const arma::colvec&, const arma::colvec&); /**< buildStump Optimally selects dimensions to built
decision stumps over.
*/
};
#endif
|
00557a6c1539e9dd460a489ed81b5a97d1d3200c
|
4ac90bd6405fe26285b351eb1bbdc904a6d542c3
|
/taichi/backends/vulkan/vulkan_memory.cpp
|
c176db1a5d1108ad3c56309c595a4851ccbf993d
|
[
"MIT"
] |
permissive
|
JVL2020LVJ/taichi
|
0a51934c8e5294e1c51ea402dbdf8b86e622fbfc
|
899707f46a1b7f28efd927122104d59f02f7f5ec
|
refs/heads/master
| 2023-07-12T01:06:10.831394
| 2021-08-16T16:02:00
| 2021-08-16T16:02:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,910
|
cpp
|
vulkan_memory.cpp
|
#include "taichi/backends/vulkan/vulkan_memory.h"
#include "taichi/math/arithmetic.h"
#include "taichi/backends/vulkan/vulkan_common.h"
#include "taichi/common/logging.h"
#include "vk_mem_alloc.h"
namespace taichi {
namespace lang {
namespace vulkan {
namespace {
static constexpr VkDeviceSize kAlignment = 256;
VkDeviceSize roundup_aligned(VkDeviceSize size) {
return iroundup(size, kAlignment);
}
} // namespace
VkBufferWithMemory::VkBufferWithMemory(VmaAllocator &allocator,
size_t size,
VkBufferUsageFlags usage,
bool host_write,
bool host_read,
bool sparse)
: allocator_(allocator), size_(size) {
TI_ASSERT(size_ > 0);
VkBufferCreateInfo buffer_info{};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.pNext = nullptr;
buffer_info.size = size;
buffer_info.usage = usage;
VmaAllocationCreateInfo alloc_info{};
if (host_read && host_write) {
// This should be the unified memory on integrated GPUs
alloc_info.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
alloc_info.preferredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
} else if (host_read) {
alloc_info.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
} else if (host_write) {
alloc_info.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
} else {
alloc_info.usage = VMA_MEMORY_USAGE_GPU_ONLY;
}
vmaCreateBuffer(allocator_, &buffer_info, &alloc_info, &buffer_, &allocation_,
&alloc_info_);
}
VkBufferWithMemory::~VkBufferWithMemory() {
if (buffer_ != VK_NULL_HANDLE) {
vmaDestroyBuffer(allocator_, buffer_, allocation_);
}
}
} // namespace vulkan
} // namespace lang
} // namespace taichi
|
f2113f58ec8a80dad95f5b1adcab89dced75830f
|
9e24f0fb937cc11c00946751ca64870c9419cb2a
|
/ZhangYiming/Problems/61-Rotate List/solution.cpp
|
84326d87fcb29494d0bd347dbc34220a0d56a2c2
|
[] |
no_license
|
zym-ustc/leetcode
|
6aa4a2b7680edac59cf3471e234d7651ad825602
|
391d2c3dabe66740daee44cc626f6101218fffdd
|
refs/heads/master
| 2021-01-02T08:34:03.320304
| 2017-05-17T08:04:58
| 2017-05-17T08:04:58
| 78,598,455
| 2
| 6
| null | 2017-04-13T06:01:20
| 2017-01-11T03:19:00
|
Java
|
UTF-8
|
C++
| false
| false
| 748
|
cpp
|
solution.cpp
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head == NULL) return head;
int length = 1;
ListNode *rear = head;
while(rear->next != NULL){
rear = rear->next;
length ++;
}
int find = length - k % length;
if(find == length) return head;
ListNode *p = head;
while(find > 1){
p = p->next;
find --;
}
rear->next = head;
head = p->next;
p->next = NULL;
return head;
}
};
|
b1e7d1d202a62a3157f735fb06e6be4e7f45df86
|
fa274ec4f0c66c61d6acd476e024d8e7bdfdcf54
|
/Resoluções OJ/codeforces/Rounds/2017 Just Programming Contest 3.0/f.cpp
|
a42992669c55bca8d53ec39aa6d2b6fc8dc4cba8
|
[] |
no_license
|
luanaamorim04/Competitive-Programming
|
1c204b9c21e9c22b4d63ad425a98f4453987b879
|
265ad98ffecb304524ac805612dfb698d0a419d8
|
refs/heads/master
| 2023-07-13T03:04:51.447580
| 2021-08-11T00:28:57
| 2021-08-11T00:28:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 779
|
cpp
|
f.cpp
|
#include <bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);
#define i64 long long
#define INF 0x3f3f3f3f
#define MAX (100123)
#define fs first
#define sc second
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define vvi vector<vi>
#define eb emplace_back
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define lsb(x) (x & -x)
using namespace std;
int t,n,q,pref[MAX],l,r;
i64 a;
int main(){
for (scanf("%i",&t); t--;){
scanf("%i %i",&n,&q);
pref[0] = 0;
for (int i = 1; i<=n; ++i){
scanf("%I64d",&a);
pref[i] = 0;
while (a>1LL){
pref[i] += ((a&1LL)+1);
a >>= 1;
}
pref[i] += pref[i-1];
}
while (q--){
scanf("%i %i",&l,&r);
printf("%i\n",pref[r] - pref[l-1]);;
}
}
return 0;
}
|
709acd8a2c80d01fc3552e1118fa1d17f0fd718c
|
b9264aa2552272b19ca393ba818f9dcb8d91da10
|
/hashmap/lib/seqan3/test/snippet/search/dream_index/interleaved_bloom_filter_constructor.cpp
|
4b19a26d5a374467371704ad9f815fe5caf8a851
|
[
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain",
"CC0-1.0",
"CC-BY-4.0",
"MIT"
] |
permissive
|
eaasna/low-memory-prefilter
|
c29b3aeb76f70afc4f26da3d9f063b0bc2e251e0
|
efa20dc8a95ce688d2a9d08773d120dff4cccbb6
|
refs/heads/master
| 2023-07-04T16:45:05.817237
| 2021-08-12T12:01:11
| 2021-08-12T12:01:11
| 383,427,746
| 0
| 0
|
BSD-3-Clause
| 2021-07-06T13:24:31
| 2021-07-06T10:22:54
|
C++
|
UTF-8
|
C++
| false
| false
| 629
|
cpp
|
interleaved_bloom_filter_constructor.cpp
|
#include <seqan3/search/dream_index/interleaved_bloom_filter.hpp>
int main()
{
// Construct an Interleaved Bloom Filter that contains 43 bins, each using 8192 bits, and 3 hash functions.
seqan3::interleaved_bloom_filter ibf{seqan3::bin_count{43u},
seqan3::bin_size{8192u},
seqan3::hash_function_count{3}};
// Construct an Interleaved Bloom Filter that contains 43 bins, each using 256 KiBits,
// and the default of 2 hash functions.
seqan3::interleaved_bloom_filter ibf2{seqan3::bin_count{43}, seqan3::bin_size{1ULL<<20}};
}
|
0f29867099008cd0ddd961096e5ab8f61f2fd2ce
|
ad71ef02dcbea4f684dbc87119e860b7a4ae1ebb
|
/GeeksForGeeks/Algorithms/Searching Algorithms/07.K_Largest_Elements.cpp
|
a06fd1988711e1c1da602f8a6a79d2246b062244
|
[] |
no_license
|
Bab95/Programs
|
851e46a8f7be0b6bde412caf405102c562dde2e0
|
79ed28bb487bdab3b72fa12d56c2d62f2bc6a683
|
refs/heads/master
| 2022-09-30T00:41:32.631053
| 2022-08-27T09:42:57
| 2022-08-27T09:42:57
| 228,459,568
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 726
|
cpp
|
07.K_Largest_Elements.cpp
|
#include <bits/stdc++.h>
using namespace std;
void input(vector<int>& arr,int n){
for(int i=0;i<n;i++){
cin>>arr[i];
}
}
void solve(){
int n,k;
cin>>n>>k;
vector<int> arr(n);
input(arr,n);
priority_queue<int,vector<int>,greater<int> > pq;
for(int i=0;i<k;i++){
pq.push(arr[i]);
}
for(int i=k;i<n;i++){
if(arr[i]>pq.top()){
pq.pop();
pq.push(arr[i]);
}
}
vector<int> ans;
while(!pq.empty()){
ans.push_back(pq.top());
pq.pop();
}
for(int i=ans.size()-1;i>=0;i--){
cout<<ans[i]<<" ";
}
cout<<endl;
}
int main() {
//code
int t;
cin>>t;
while(t--){
solve();
}
return 0;
}
|
dddae768010d6531fb07c9a5d55e9ed1d0293cfd
|
992df6ff3b49fddf01babb2a04ded03109da7ab7
|
/4.0/Demo/WebsocketProtocol/WebsocketContext.cpp
|
362591ea7780abd421df296c2828c4b434d140d3
|
[
"BSL-1.0"
] |
permissive
|
charfeddine-ahmed/PushFramework
|
abf187bc30bdd0f702929c4e571af49279278d56
|
ed9804ffc5148e180cb95bafe13aa2e0f3903147
|
refs/heads/master
| 2021-12-08T15:22:19.895640
| 2021-12-01T14:04:08
| 2021-12-01T14:04:08
| 92,851,089
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 273
|
cpp
|
WebsocketContext.cpp
|
#include "stdafx.h"
#include "WebsocketContext.h"
WebsocketContext::WebsocketContext()
{
currentContinuationOpCode = -1;
}
WebsocketContext::~WebsocketContext(void)
{
}
void WebsocketContext::recycle()
{
bufferedContent.release();
currentContinuationOpCode = -1;
}
|
7a9838c9cc25cd13fedc2ed61344220c57708a4b
|
f4647d8b8dc5e8581903b5f78ba669dff9fa7733
|
/reverse.cpp
|
f745ba59b44a086f8006527d1488e1482299c8ba
|
[] |
no_license
|
keerthna-manikandan/dsa-arrays
|
892253a7b890f19f17c8e977f843e3043d5af6e4
|
b624e82892ee3e6233331cdd0fca921b77e7fd43
|
refs/heads/main
| 2023-06-20T22:58:02.855214
| 2021-07-27T10:34:13
| 2021-07-27T10:34:13
| 383,679,559
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 517
|
cpp
|
reverse.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter size of the array: ";
cin>>n;
int a[n];
cout<<"Enter the elements: ";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int j=n-1,i=0,x;
for(;i<j;i++,j--)
{
x=a[i];
a[i]=a[j];
a[j]=x;
}
cout<<"Reverse using iterative method: ";
for(i=0;i<n;i++)cout<<a[i]<<" ";
cout<<"\nReverse using stl function: ";
reverse(a,a+n);
for(i=0;i<n;i++)cout<<a[i]<<" ";
}
|
57e1442d4a1c92fba7986d17f9b1e450800bd526
|
99c91cef7cd0f6225338752fe654507d25db541b
|
/OpenGLTest/ui.h
|
6d44ec5139dfb333878bc64f0eed8cc2c271cd6d
|
[] |
no_license
|
Elekrisk/OpenGLTest
|
b52fafee57d677cd23034067f978bc2c31eb4a0a
|
2fc5e2005cd93b202662a02d696a15e85c53b4b9
|
refs/heads/master
| 2021-09-15T01:04:00.617334
| 2018-05-23T11:07:48
| 2018-05-23T11:07:48
| 119,383,171
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 5,595
|
h
|
ui.h
|
#pragma once
#include "MessageBus.h"
#include <memory>
#include "ImageConstructor.h"
class UIElement;
class UIGroup;
// Klass som hanterar UI:n. Ej helt implementerad än.
class UI
{
// Den messageBus som UI:n ska lyssna på.
MessageBus *m_messageBus;
// Skalör för storleken på UI:n
float m_uiScale;
// Alla elementgrupper i UI:n. En elementgrupp är en grupp UI-element som hör till varandra och kan gömmas tillsammans.
// Detta kan t ex vara ett UI-fönster, som en inventory-panel.
std::vector<UIGroup> m_elementGroups;
public:
// Konstruktör som binder UI:n till messageBusen
UI(MessageBus &messageBus);
// De olika callbacksen (svengelska :D) som används av UI:n.
bool eventCallback(MessageBus::EventType et, const std::string &info);
bool keyboardCallback(MessageBus::KeyboardInput it, int key);
bool textCallback(unsigned int codepoint);
bool mouseCallback(MessageBus::MouseInput it, int key, int x, int y);
// Funktion som returnerar alla elementgrupper
std::vector<UIGroup> *getElementGroups();
// Enumeration för hur ett fönster ska reagera på olika skärmupplösningar.
enum AnchorPoint
{
UPPER_LEFT,
UPPER_RIGHT,
LOWER_LEFT,
LOWER_RIGHT,
EDGE_LEFT,
EDGE_RIGHT,
EDGE_UP,
EDGE_DOWN
};
};
// En klass som representerar en UI-elementgrupp.
class UIGroup
{
// Ifall gruppen ska renderas och reagera på interaktioner.
bool m_enabled{ false };
// Var den renderas i z-led, vilket bestämmer ifall den kommer renderas framför eller bakom andra grupper.
int m_zIndex;
// Alla element som ingår i denna grupp.
std::vector<std::unique_ptr<UIElement>> m_elements;
// Dess anchor, som beskrivs i UI-klassen
UI::AnchorPoint m_anchor;
// Jämför z-index.
bool operator<(const UIGroup &group) const;
public:
// Funktioner för att sätta på eller stänga av gruppen.
void enable();
void disable();
// Bestämmer z-index och returnerar z-index respektivt.
void setZIndex(int index);
int getZIndex();
// Returnerar en pekare till en vector med alla elementen i gruppen.
std::vector<std::unique_ptr<UIElement>> *getElements();
// Renturnerar och bestämmer gruppens anchor.
UI::AnchorPoint getAnchor();
void setAnchor(UI::AnchorPoint);
};
// En klass som representerar ett UI-element
class UIElement
{
protected:
// Dess position, storlek och z-index
float m_posX;
float m_posY;
int m_width;
int m_height;
int m_zIndex;
// Ifall UI-elementet har uppdaterats eller om det måste byggas om
bool m_refreshed{ false };
// Elementets OpenGL-textur
unsigned int m_texture;
// Bygg elementet. Jag är osäker på om jag kommer att använda denna funktion eller enbart använda refresh()
void construct();
public:
UIElement();
// Sätter m_refreshed = true
bool shouldRefresh();
// Bygg om elementet.
void refresh();
};
// En klass som representerar en bild, som huvudsakligt kommer att användas som bakgrund till andra element.
class UIBackground : public UIElement
{
protected:
// Den bild som bakgrunden använder
Image m_img;
void construct();
public:
UIBackground();
// Returnerar bilden och bestämmer bilden.
const Image *getImage();
void setImage(const Image &img);
void refresh();
};
// En klass som representerar text.
class UIText : public UIElement
{
// Den text som kommer att renderas till en bild.
std::string m_text;
// Den bild som renderingen spottar ut
Image m_imgCompiled;
void construct();
public:
UIText();
// Returnerar texten och bestämmer texten
const std::string *getText();
void setText(const std::string &text);
// Returnerar den kompilerade bilden
const Image *getImage();
void refresh();
};
// En klass som representerar en knapp.
class UIButton : public UIElement
{
protected:
// Den funktion som anropas när knappen aktiveras.
std::function<int(int id)> m_function;
void construct();
public:
UIButton();
// Bestämmer respektive returnerar funktionen.
void setFunction(std::function<int(int id)> function);
std::function<int(int id)> getFunction();
// Aktivera knappen.
int activate(int id);
};
// En knapp som har bilder som representerar dess tilstånd.
class UIImageButton : public UIButton
{
protected:
// Bilder som visas när knappen är normal, blir hovrad över respektive är nedtryckt.
Image m_normalImg;
Image m_hoverImg;
Image m_clickedImg;
// Vilket tillstånd knappen är i
int m_state;
void construct();
public:
UIImageButton();
// Returnerar respektive bestämmer bilderna
void setImage(int imageState, const Image &image);
const Image *getImage(int imageState);
// Bestämmer respektive returnerar knappens tillstånd
void setState(int imageState);
int getState();
};
// Samma som ovan plus text
class UITextButton : public UIImageButton
{
protected:
std::string m_text;
// Kompilerade bilder
Image m_normalImgCompiled;
Image m_hoverImgCompiled;
Image m_clickedImgCompiled;
void construct();
public:
UITextButton();
const Image *getCompiledImage(int imageState);
void setText(const std::string &text);
const std::string *getText();
};
// Representerar ett redigerbart textfält
class UIField : public UIElement
{
protected:
// Bakgrundsbilder för texten, och själva texten
Image m_normalImg;
Image m_selectedImg;
std::string m_text;
// Ifall fältet har uppdateras sedan användaren redigerade texten.
bool m_updated;
// De kompilerade bilderna.
Image m_normalImgCompiled;
Image m_selectedImgCompiled;
void construct();
public:
UIField();
void setImage(int imageState, const Image &image);
const Image *getImage(int imageState);
const Image *getCompiledImage(int imageState);
};
|
d6db61101dab64730dfcd23b9c349e415a614b5e
|
1bc3a3bfe53bb450b5fe009c9a890be4e00c3afc
|
/Math/17087.cpp
|
d8cd5f9cf7cd21e293c4bd3f4d77a9339761c0c5
|
[] |
no_license
|
juno7803/Algorithm
|
8d4d2d1bf7230b6c6aa0d0fcb2decd03b15b96d0
|
004d3e2e52f0bf4b26c14d562d8d39923258f692
|
refs/heads/master
| 2020-12-06T14:46:54.338275
| 2020-10-06T14:33:31
| 2020-10-06T14:33:31
| 232,488,984
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 497
|
cpp
|
17087.cpp
|
#include<iostream>
#include<vector>
using namespace std;
int gcd(int x, int y) {
if (y == 0) {
return x;
}
else {
return gcd(y, x % y);
}
}
int main() {
int n; // 1<= b <= 10^5
int s; // 1<= s <= 10^9
cin >> n >> s;
vector<int>a;
for (int i = 0; i < n; i++) {
int tmp;
cin >> tmp;
int abnum = abs(tmp - s);
a.push_back(abnum);
}
int D = a.at(0);
for (int i = 1; i < n; i++) {
D = gcd(D, a.at(i));
}
cout << D << "\n";
return 0;
}
|
e05a6bf0c2cd5d0e4396dc4a14af432a0fc66a3c
|
0cf04e613e2c16a8355441cbc6c6f902d8073aa8
|
/CS450/FinalSubmission/Debug/Sphere.h
|
742845c72197bf40d9081c219dbb69175640b158
|
[] |
no_license
|
Gwolff97/SchoolWork
|
8193b8d56638c6bb2536fa6482f788b81dffad31
|
aca46fcc0f26dfa1f5302301683994d085fab30b
|
refs/heads/master
| 2020-05-25T07:58:20.377024
| 2019-05-20T19:26:32
| 2019-05-20T19:26:32
| 187,698,797
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 643
|
h
|
Sphere.h
|
#ifndef SPHERE_H
#define SPHERE_H
#include <cstring>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
#include <thread>
#include <chrono>
#include "glm/glm.hpp" // NOTE: Need to compile, hence the quotes
#include "glm/gtx/string_cast.hpp"
class Sphere {
public:
Sphere();
Sphere(glm::vec3 center, double radius);
glm::vec3 getCenter();
double getRadius();
std::string toString();
void read(std::string data);
void setMaterialIndex(int matIndex);
int getMaterialIndex();
private:
glm::vec3 position;
double radiusP;
int Material_index;
};
#endif // !SPHERE_H
|
fb671cff73c592be444de786e1f290909c6f64c9
|
c4d0e6aaa0b3f756a64df06469d44c7b9f3b6a31
|
/include/net_ip/net_entity.hpp
|
caf71263caa8ee319a65d27c1c61f82836806c9f
|
[
"BSL-1.0"
] |
permissive
|
connectivecpp/chops-net-ip
|
d35850a0af0d7626472a3121b565f19036094feb
|
6a1fd59945fdc495da3ad390a1cc5f428f73ebe7
|
refs/heads/master
| 2020-04-28T06:23:23.682015
| 2020-03-30T20:17:59
| 2020-03-30T20:17:59
| 175,055,942
| 10
| 3
|
BSL-1.0
| 2020-03-30T20:18:01
| 2019-03-11T18:00:54
|
C++
|
UTF-8
|
C++
| false
| false
| 23,006
|
hpp
|
net_entity.hpp
|
/** @file
*
* @ingroup net_ip_module
*
* @brief @c net_entity class and related functionality.
*
* @author Cliff Green
*
* Copyright (c) 2017-2019 by Cliff Green
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
#ifndef NET_ENTITY_HPP_INCLUDED
#define NET_ENTITY_HPP_INCLUDED
#include <memory> // std::shared_ptr, std::weak_ptr
#include <cstddef> // std::size_t
#include <utility> // std::move, std::forward
#include <variant>
#include <type_traits> // std::is_invocable
#include <system_error> // std::make_error, std::error_code
#include <string_view>
#include "nonstd/expected.hpp"
#include "net_ip/net_ip_error.hpp"
#include "net_ip/detail/tcp_acceptor.hpp"
#include "net_ip/detail/tcp_connector.hpp"
#include "net_ip/detail/udp_entity_io.hpp"
#include "net_ip/detail/wp_access.hpp"
#include "net_ip/io_type_decls.hpp"
#include "utility/overloaded.hpp"
namespace chops {
namespace net {
// Cliff note: when C++ 20 lambda templates are available much of this code can be simplified,
// since most of it is generic (just doesn't have the specific type parameter available as
// needed in the right place). Stating it another way, there is waaaaaaay too much boilerplate
// code (it may be possible to simplify with C++17 techniques that I don't know yet).
/**
* @brief The @c net_entity class provides the primary application interface
* into the TCP acceptor, TCP connector, and UDP entity functionality.
*
* The @c net_entity class provides methods to start and stop processing
* on an underlying network entity, such as a TCP acceptor or TCP connector or
* UDP entity (which may be a UDP unicast sender or receiver, or a UDP
* multicast receiver).
*
* Calling the @c stop method on a @c net_entity object will shutdown the
* associated network resource. At this point, other @c net_entity objects
* copied from the original will be affected.
*
* The @c net_entity class is a lightweight value class, designed to be easy
* and efficient to copy and store. Internally it uses a @c std::weak_ptr to
* refer to the actual network entity.
*
* A @c net_entity object is either associated with a network entity
* (i.e. the @c std::weak pointer is good), or not. The @c is_valid method queries
* if the association is present.
*
* Applications can default construct a @c net_entity object, but it is not
* useful until a valid @c net_entity object is assigned to it (as provided in the
* @c make methods of the @c net_ip class).
*
* Appropriate comparison operators are provided to allow @c net_entity objects
* to be used in associative or sequence containers.
*
* All @c net_entity methods are safe to call concurrently from multiple
* threads.
*
*/
class net_entity {
private:
using udp_wp = detail::udp_entity_io_weak_ptr;
using acc_wp = detail::tcp_acceptor_weak_ptr;
using conn_wp = detail::tcp_connector_weak_ptr;
private:
std::variant<udp_wp, acc_wp, conn_wp> m_wptr;
private:
friend class net_ip;
public:
/**
* @brief Default construct a @c net_entity object.
*
* A @c net_entity object is not useful until an active @c net_entity is assigned
* into it.
*
*/
net_entity () = default;
net_entity(const net_entity&) = default;
net_entity(net_entity&&) = default;
net_entity& operator=(const net_entity&) = default;
net_entity& operator=(net_entity&&) = default;
/**
* @brief Construct with a shared weak pointer to an internal net entity, this is an
* internal constructor only and not to be used by application code.
*/
template <typename ET>
explicit net_entity (const std::shared_ptr<ET>& p) noexcept : m_wptr(p) { }
/**
* @brief Query whether an internal net entity is associated with this object.
*
* If @c true, a net entity (TCP acceptor or TCP connector or UDP entity) is associated.
*
* @return @c true if associated with a net entity.
*/
bool is_valid() const noexcept {
return std::visit([] (const auto& wp) { return !wp.expired(); }, m_wptr);
}
/**
* @brief Query whether the associated net entity is in a started or stopped state.
*
* @return @c nonstd::expected - @c bool on success, specifying whether @c start has been
* called (if @c false, the network entity has not been started or is in a stopped state);
* on error (if no associated IO handler), a @c std::error_code is returned.
*/
auto is_started() const ->
nonstd::expected<bool, std::error_code> {
return std::visit(chops::overloaded {
[] (const udp_wp& wp) -> nonstd::expected<bool, std::error_code> {
return detail::wp_access<bool>(wp,
[] (detail::udp_entity_io_shared_ptr sp) { return sp->is_started(); } );
},
[] (const acc_wp& wp) -> nonstd::expected<bool, std::error_code> {
return detail::wp_access<bool>(wp,
[] (detail::tcp_acceptor_shared_ptr sp) { return sp->is_started(); } );
},
[] (const conn_wp& wp) -> nonstd::expected<bool, std::error_code> {
return detail::wp_access<bool>(wp,
[] (detail::tcp_connector_shared_ptr sp) { return sp->is_started(); } );
},
}, m_wptr);
}
/**
* @brief Call an application supplied function object with a reference to the associated
* net entity @c asio socket.
*
* The function object must have one of the following signatures, depending on the entity
* type:
*
* @code
* void (asio::ip::tcp::socket&); // TCP connector
* void (asio::ip::tcp::acceptor&) // TCP acceptor
* void (asio::ip::udp::socket&); // UDP entity
* @endcode
*
* Within the function object socket options can be queried or modified or any valid
* socket method called.
*
* @return @c nonstd::expected - socket has been visited on success; on error (if no
* associated IO handler), a @c std::error_code is returned.
*/
template <typename F>
auto visit_socket(F&& func) const ->
nonstd::expected<void, std::error_code> {
return std::visit(chops::overloaded {
[&func] (const udp_wp& wp) -> nonstd::expected<void, std::error_code> {
if constexpr (std::is_invocable_v<F, asio::ip::udp::socket&>) {
return detail::wp_access_void(wp,
[&func] (detail::udp_entity_io_shared_ptr sp) { sp->visit_socket(func); return std::error_code(); } );
}
return nonstd::make_unexpected(std::make_error_code(net_ip_errc::functor_variant_mismatch));
},
[&func] (const acc_wp& wp) -> nonstd::expected<void, std::error_code> {
if constexpr (std::is_invocable_v<F, asio::ip::tcp::acceptor&>) {
return detail::wp_access_void(wp,
[&func] (detail::tcp_acceptor_shared_ptr sp) { sp->visit_socket(func); return std::error_code(); } );
}
return nonstd::make_unexpected(std::make_error_code(net_ip_errc::functor_variant_mismatch));
},
[&func] (const conn_wp& wp) -> nonstd::expected<void, std::error_code> {
if constexpr (std::is_invocable_v<F, asio::ip::tcp::socket&>) {
return detail::wp_access_void(wp,
[&func] (detail::tcp_connector_shared_ptr sp) { sp->visit_socket(func); return std::error_code(); } );
}
return nonstd::make_unexpected(std::make_error_code(net_ip_errc::functor_variant_mismatch));
},
}, m_wptr);
}
/**
* @brief Call an application supplied function object with all @c basic_io_output objects
* that are active on associated IO handlers for this net entity.
*
* A TCP connector will have 0 or 1 active IO handlers, depending on connection state, while
* a TCP acceptor will have 0 to N active IO handlers, depending on the number of
* accepted incoming connections. A UDP entity will either have 0 or 1 active IO handlers
* depending on whether it has been started or not.
*
* The function object must have one of the following signatures, depending on TCP or UDP:
*
* @code
* void (chops::net::tcp_io_output); // TCP
* void (chops::net::udp_io_output); // UDP
* @endcode
*
* The function object will be called 0 to N times depending on active IO handlers. An
* IO handler is active if @c start_io has been called on it.
*
* @return @c nonstd::expected - on success returns number of times function object has
* been called; on error (if no associated IO handler), a @c std::error_code is returned.
*/
template <typename F>
auto visit_io_output(F&& func) const ->
nonstd::expected<std::size_t, std::error_code> {
return std::visit(chops::overloaded {
[&func] (const udp_wp& wp)-> nonstd::expected<std::size_t, std::error_code> {
if constexpr (std::is_invocable_v<F, chops::net::udp_io_output>) {
return detail::wp_access<std::size_t>(wp,
[&func] (detail::udp_entity_io_shared_ptr sp) { return sp->visit_io_output(func); } );
}
return nonstd::make_unexpected(std::make_error_code(net_ip_errc::functor_variant_mismatch));
},
[&func] (const acc_wp& wp)-> nonstd::expected<std::size_t, std::error_code> {
if constexpr (std::is_invocable_v<F, chops::net::tcp_io_output>) {
return detail::wp_access<std::size_t>(wp,
[&func] (detail::tcp_acceptor_shared_ptr sp) { return sp->visit_io_output(func); } );
}
return nonstd::make_unexpected(std::make_error_code(net_ip_errc::functor_variant_mismatch));
},
[&func] (const conn_wp& wp)-> nonstd::expected<std::size_t, std::error_code> {
if constexpr (std::is_invocable_v<F, chops::net::tcp_io_output>) {
return detail::wp_access<std::size_t>(wp,
[&func] (detail::tcp_connector_shared_ptr sp) { return sp->visit_io_output(func); } );
}
return nonstd::make_unexpected(std::make_error_code(net_ip_errc::functor_variant_mismatch));
},
}, m_wptr);
}
/**
* @brief Start network processing on the associated net entity with the application
* providing IO state change and error function objects.
*
* Once a net entity (TCP acceptor, TCP connector, UDP entity) is created through
* a @c net_ip @c make method, calling @c start on the @c net_entity causes local port
* binding and other processing (e.g. TCP listen, TCP connect) to occur.
*
* Input and output processing does not start until the @c basic_io_interface @c start_io
* method is called.
*
* The application provides two function objects to @c start (the second can be defaulted
* to a "do nothing" function object):
*
* 1) An IO state change callback function object. This callback object is invoked when a
* TCP connection is created or a UDP socket opened, and then invoked when the TCP connection
* is destroyed or the UDP socket closed. A @c basic_io_interface object is provided to the
* callback which allows IO processing to commence through the @c start_io method call (when
* a TCP connection is created or UDP socket opened).
*
* 2) An error function object which is invoked whenever an error occurs or when
* important processing is performed within an IO handler or network entity.
*
* The @c start method call can only be called once. In other words, once started and stopped,
* a net entity cannot be restarted (future enhancements may allow restarting a net entity).
*
* @param io_state_chg_func A function object with the following signature:
*
* @code
* // TCP:
* void (chops::net::tcp_io_interface, std::size_t, bool);
* // UDP:
* void (chops::net::udp_io_interface, std::size_t, bool);
* @endcode
*
* The parameters are as follows:
*
* 1) A @c basic_io_interface object providing @c start_io access (and @c stop_io access if
* needed) to the underlying IO handler.
*
* 2) A count of the underlying IO handlers associated with this net entity. For
* a TCP connector or a UDP entity the number is 1 when starting and 0 when stopping, and for
* a TCP acceptor the number is 0 to N, depending on the number of accepted connections.
*
* 3) If @c true, the @c basic_io_interface has just been created (i.e. a TCP connection
* has been created or a UDP socket is ready), and if @c false, the connection or socket
* has been destroyed or closed.
*
* In both IO state change function object callback invocations the @c basic_io_interface object
* is valid (@c is_valid returns @c true). For the second invocation no @c basic_io_interface
* methods should be called (since the IO handler is in the process of shutting down), but
* the @c basic_io_interface object can be used for associative lookups (if needed).
*
* The IO state change function object must be copyable (it will be stored in a
* @c std::function).
*
* @param err_func A function object with the following signature:
*
* @code
* // TCP:
* void (chops::net::tcp_io_interface, std::error_code);
* // UDP:
* void (chops::net::udp_io_interface, std::error_code);
* @endcode
*
* The parameters are as follows:
*
* 1) A @c basic_io_interface object, which may or may not be valid (i.e @c is_valid may
* return either @c true or @c false), depending on the context of the error. No methods
* on the @c basic_io_interface object should be called, as the underlying handler, if
* present, may be in the process of shutting down. The @c basic_io_interface object is
* provided as a key to associate multiple error codes to the same handler.
*
* 2) The error code associated with the invocation. There are error codes associated
* with application initiated closes, shutdowns, and other state changes as well as error
* codes for network or system errors.
*
* The @c err_func callback may be invoked in contexts other than a network IO error - for
* example, if a TCP acceptor or UDP entity cannot bind to a local port, a system error
* code will be provided. It is also used to notify important state changes, such as
* a message handler shutdown or TCP connector state changes.
*
* The error function object must be copyable (it will be stored in a @c std::function).
*
* For use cases that don't care about error codes, a function named @c empty_error_func
* is available.
*
* @return @c nonstd::expected - on success network entity is started; on error, a
* @c std::error_code is returned.
*/
template <typename F1, typename F2>
auto start(F1&& io_state_chg_func, F2&& err_func) ->
nonstd::expected<void, std::error_code> {
return std::visit(chops::overloaded {
[&io_state_chg_func, &err_func] (const udp_wp& wp)->nonstd::expected<void, std::error_code> {
if constexpr (std::is_invocable_v<F1, udp_io_interface, std::size_t, bool> &&
std::is_invocable_v<F2, udp_io_interface, std::error_code>) {
return detail::wp_access_void(wp,
[&io_state_chg_func, &err_func] (detail::udp_entity_io_shared_ptr sp)
{ return sp->start(io_state_chg_func, err_func); } );
}
return nonstd::make_unexpected(std::make_error_code(net_ip_errc::functor_variant_mismatch));
},
[&io_state_chg_func, &err_func] (const acc_wp& wp)->nonstd::expected<void, std::error_code> {
if constexpr (std::is_invocable_v<F1, tcp_io_interface, std::size_t, bool> &&
std::is_invocable_v<F2, tcp_io_interface, std::error_code>) {
return detail::wp_access_void(wp,
[&io_state_chg_func, &err_func] (detail::tcp_acceptor_shared_ptr sp)
{ return sp->start(io_state_chg_func, err_func); } );
}
return nonstd::make_unexpected(std::make_error_code(net_ip_errc::functor_variant_mismatch));
},
[&io_state_chg_func, &err_func] (const conn_wp& wp)->nonstd::expected<void, std::error_code> {
if constexpr (std::is_invocable_v<F1, tcp_io_interface, std::size_t, bool> &&
std::is_invocable_v<F2, tcp_io_interface, std::error_code>) {
return detail::wp_access_void(wp,
[&io_state_chg_func, &err_func] (detail::tcp_connector_shared_ptr sp)
{ return sp->start(io_state_chg_func, err_func); } );
}
return nonstd::make_unexpected(std::make_error_code(net_ip_errc::functor_variant_mismatch));
},
}, m_wptr);
}
/**
* @brief Stop network processing on the associated network entity.
*
* Internally, the network entity will call @c stop_io (or equivalent) on each associated
* IO handler.
*
* Stopping the network processing may involve closing connections, deallocating
* resources, unbinding from ports, and invoking application provided state change function
* object callbacks.
*
* @return @c nonstd::expected - on success network entity is stopped; on error, a
* @c std::error_code is returned.
*/
auto stop() ->
nonstd::expected<void, std::error_code> {
return std::visit(chops::overloaded {
[] (const udp_wp& wp)->nonstd::expected<void, std::error_code> {
return detail::wp_access_void(wp,
[] (detail::udp_entity_io_shared_ptr sp) { return sp->stop(); } );
},
[] (const acc_wp& wp)->nonstd::expected<void, std::error_code> {
return detail::wp_access_void(wp,
[] (detail::tcp_acceptor_shared_ptr sp) { return sp->stop(); } );
},
[] (const conn_wp& wp)->nonstd::expected<void, std::error_code> {
return detail::wp_access_void(wp,
[] (detail::tcp_connector_shared_ptr sp) { return sp->stop(); } );
},
}, m_wptr);
}
/**
* @brief Provide a display string of the internal type, whether for logging or
* debugging purposes.
*
* @return A @c std::string_view containing the network entity type, either
* UDP, TCP acceptor, or TCP connector.
*
*/
std::string_view stream_out() const noexcept {
return std::visit(chops::overloaded {
[] (const udp_wp& wp) { return "[UDP network entity]"; },
[] (const acc_wp& wp) { return "[TCP acceptor network entity]"; },
[] (const conn_wp& wp) { return "[TCP connector network entity]"; },
}, m_wptr);
}
friend bool operator==(const net_entity&, const net_entity&) noexcept;
friend bool operator<(const net_entity&, const net_entity&) noexcept;
};
/**
* @brief Compare two @c net_entity objects for equality.
*
* If the @ net_entity objects are not both pointing to the same type of network entity
* (TCP connector, TCP acceptor, etc), then they are not equal. If both are the same
* type of network entity, then both are checked to be valid (i.e. the internal @c weak_ptr
* is valid). If both are valid, then a @c std::shared_ptr comparison is made.
*
* If both @c net_entity objects are invalid (and both same type of network entity), @c true
* is returned (this implies that all invalid @c net_entity objects are equivalent). If one
* is valid and the other invalid, @c false is returned.
*
* @return As described in the comments.
*/
inline bool operator==(const net_entity& lhs, const net_entity& rhs) noexcept {
return std::visit(chops::overloaded {
[] (const net_entity::udp_wp& lwp, const net_entity::udp_wp& rwp) {
return lwp.lock() == rwp.lock();
},
[] (const net_entity::udp_wp& lwp, const net_entity::acc_wp& rwp) {
return false;
},
[] (const net_entity::udp_wp& lwp, const net_entity::conn_wp& rwp) {
return false;
},
[] (const net_entity::acc_wp& lwp, const net_entity::acc_wp& rwp) {
return lwp.lock() == rwp.lock();
},
[] (const net_entity::acc_wp& lwp, const net_entity::udp_wp& rwp) {
return false;
},
[] (const net_entity::acc_wp& lwp, const net_entity::conn_wp& rwp) {
return false;
},
[] (const net_entity::conn_wp& lwp, const net_entity::conn_wp& rwp) {
return lwp.lock() == rwp.lock();
},
[] (const net_entity::conn_wp& lwp, const net_entity::udp_wp& rwp) {
return false;
},
[] (const net_entity::conn_wp& lwp, const net_entity::acc_wp& rwp) {
return false;
},
}, lhs.m_wptr, rhs.m_wptr);
}
/**
* @brief Compare two @c net_entity objects for ordering purposes.
*
* Arbitrarily, a UDP network entity compares less than a TCP acceptor which compares
* less than a TCP connector. If both network entities are the same then the
* @c std::shared_ptr ordering is returned.
*
* All invalid @c net_entity objects (of the same network entity type) are less than valid
* ones. If both @c net_entity objects are invalid and the same network entity type,
* they are considered equal, so @c operator< returns @c false.
*
* @return As described in the comments.
*/
inline bool operator<(const net_entity& lhs, const net_entity& rhs) noexcept {
return std::visit(chops::overloaded {
[] (const net_entity::udp_wp& lwp, const net_entity::udp_wp& rwp) {
return lwp.lock() < rwp.lock();
},
[] (const net_entity::udp_wp& lwp, const net_entity::acc_wp& rwp) {
return true;
},
[] (const net_entity::udp_wp& lwp, const net_entity::conn_wp& rwp) {
return true;
},
[] (const net_entity::acc_wp& lwp, const net_entity::acc_wp& rwp) {
return lwp.lock() < rwp.lock();
},
[] (const net_entity::acc_wp& lwp, const net_entity::udp_wp& rwp) {
return false;
},
[] (const net_entity::acc_wp& lwp, const net_entity::conn_wp& rwp) {
return true;
},
[] (const net_entity::conn_wp& lwp, const net_entity::conn_wp& rwp) {
return lwp.lock() < rwp.lock();
},
[] (const net_entity::conn_wp& lwp, const net_entity::udp_wp& rwp) {
return false;
},
[] (const net_entity::conn_wp& lwp, const net_entity::acc_wp& rwp) {
return false;
},
}, lhs.m_wptr, rhs.m_wptr);
}
/**
* @brief A "do nothing" error function template that can be used in the
* @c net_entity @c start method.
*
* @relates net_entity
*/
template <typename IOT>
void empty_error_func(basic_io_interface<IOT>, std::error_code) { }
/**
* @brief A "do nothing" error function used in the @c net_entity @c start
* method, for TCP @c basic_io_interface objects.
*
* @relates net_entity
*/
inline void tcp_empty_error_func(tcp_io_interface, std::error_code) { }
/**
* @brief A "do nothing" error function used in the @c net_entity @c start
* method, for UDP @c basic_io_interface objects.
*
* @relates net_entity
*/
inline void udp_empty_error_func(udp_io_interface, std::error_code) { }
} // end net namespace
} // end chops namespace
#endif
|
8fe78afe90dfd8db0f13c2de9fca66a8cb384941
|
9cc85c4b112763b09faa44df585957a1a7c36e4a
|
/renderer.h
|
f64b5c6d7290d6bb42ec1e95ecb44187e0225389
|
[] |
no_license
|
m-iDev-0792/TinyRayTracingRenderer
|
ab6ed31c81d780922a3cd1d8382e1a3c2005ffd4
|
221ba86da8ff65108b96ec03d09663d6dd082db7
|
refs/heads/master
| 2020-03-18T13:53:32.861602
| 2019-04-02T06:40:52
| 2019-04-02T06:40:52
| 134,815,635
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,254
|
h
|
renderer.h
|
#ifndef RENDERER_H
#define RENDERER_H
#include <QObject>
#include <cmath>
#include <QPixmap>
#include <QImage>
#include <QDebug>
#include "utility.h"
struct Vec {//定义向量类型
double x, y, z;
Vec(double xx = 0, double yy = 0, double zz = 0) {
x = xx;
y = yy;
z = zz;
}
Vec operator +(const Vec &b) const {
return Vec(x + b.x, y + b.y, z + b.z);
}
Vec operator -(const Vec &b) const {
return Vec(x - b.x, y - b.y, z - b.z);
}
Vec operator *(double b) const {
return Vec(x * b, y * b, z * b);
}
Vec mult(const Vec &b) const {
return Vec(x * b.x, y * b.y, z * b.z);
} //向量分量相乘
Vec &norm() {
return *this = *this * (1 / sqrt(x * x + y * y + z * z));
} //单位化本向量
double dot(const Vec &b) const {
return x * b.x + y * b.y + z * b.z;
} //点乘,
Vec operator %(Vec &b) {
return Vec(y * b.z - z * b.y, z * b.x - x * b.z, x * b.y - y * b.x);
} //叉乘
};
struct Ray {
Vec o, d;
Ray(Vec o_, Vec d_) : o(o_), d(d_) {
}
};
enum Refl_t {//材质定义
DIFF, SPEC, REFR
};
struct Sphere {//定义圆数据结构
double rad;
Vec p, e, c; // 位置,发射亮度,颜色
Refl_t refl; // 材质类型
Sphere(double rad_, Vec p_, Vec e_, Vec c_, Refl_t refl_) :
rad(rad_), p(p_), e(e_), c(c_), refl(refl_) {
}
//测试光线与圆是否相交,未相交返回0
double intersect(Ray &r) {
Vec op = p - r.o;
double t, eps = 1e-4, b = op.dot(r.d), det = b * b - op.dot(op) + rad * rad;
if (det < 0) return 0; else det = sqrt(det);
return (t = b - det) > eps ? t : ((t = b + det) > eps ? t : 0);
}
};
class Renderer : public QObject
{
Q_OBJECT
public:
explicit Renderer(QObject *parent = nullptr);
QImage resultImg;
//场景内的圆,墙面实际 用一个很大的圆模拟,参数依次是:半径,位置,发射光,颜色,材质类型
Sphere spheres[12] = {
Sphere(1e5, Vec(1e5 + 1, 40.8, 81.6), Vec(), Vec(.75, .25, .25), DIFF), //左
Sphere(1e5, Vec(-1e5 + 99, 40.8, 81.6), Vec(), Vec(.25, .25, .75), DIFF), //右
Sphere(1e5, Vec(50, 40.8, 1e5), Vec(), Vec(.75, .75, .75), DIFF), //后
Sphere(1e5, Vec(50, 40.8, -1e5 + 170), Vec(), Vec(), DIFF), //前
Sphere(1e5, Vec(50, 1e5, 81.6), Vec(), Vec(.75, .75, .75), DIFF), //底部
Sphere(1e5, Vec(50, -1e5 + 81.6, 81.6), Vec(), Vec(.75, .75, .75), DIFF), //顶部
Sphere(16.5, Vec(27, 16.5, 47), Vec(), Vec(1, 1, 1) * .999, SPEC), //镜面球
Sphere(16.5, Vec(50, 50, 47), Vec(), Vec(1, 1, 1) * .999, SPEC), //镜面球
Sphere(16.5, Vec(73, 16.5, 78), Vec(), Vec(1, 1, 1) * .999, REFR), //玻璃球
Sphere(8, Vec(27, 8, 90), Vec(), Vec(0.5, 0.5, 0.5), DIFF), //漫反射
Sphere(5, Vec(35, 5, 100), Vec(), Vec(0.125, 0.84, 0.553), DIFF), //漫反射
Sphere(600, Vec(50, 681.6 - .27, 81.6), Vec(12, 12, 12), Vec(), DIFF) //光源
};
inline double clamp(double x) {
return x < 0 ? 0 : x > 1 ? 1 : x;
}
inline int toInt(double x) {
return int(pow(clamp(x), 1 / 2.2) * 255 + .5);
}
inline bool intersect(Ray &r, double &t, int &id) {
double n = sizeof(spheres) / sizeof(Sphere), d, inf = t = 1e20;
for (int i = int(n); i--; )
if ((d = spheres[i].intersect(r)) && d < t) {
t = d;
id = i;
}
return t < inf;
}
Vec radiance(Ray &&r, int depth, unsigned short *Xi);
Vec radiance(Ray &r, int depth, unsigned short *Xi);
signals:
void newLineRendered(QImage image);
void renderState(int progress,int remain);
public slots:
void renderScene(int sample,int width,int height);
};
#endif // RENDERER_H
|
5ead05ebd1621d39cec66045c7c494dfb61540a9
|
6da62dacf463fde32b9bf85d87dc82fb1b87d876
|
/Nasledqvane_Comunity_Member/Nasledqvane_Comunity_Member/main.cpp
|
d5130ca09cd82276cf3f2d4c85795e533802d78b
|
[] |
no_license
|
PetyrEftimov/GitHubPetyrEftimov
|
df90acfc4d398489643d5c1d517beab167a088d1
|
a77b5d2c352c5c5c9e4251294bcf9933798d1eec
|
refs/heads/master
| 2021-01-20T13:56:50.077544
| 2017-06-24T11:29:10
| 2017-06-24T11:29:10
| 90,543,799
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 918
|
cpp
|
main.cpp
|
//
// main.cpp
// Nasledqvane_Comunity_Member
//
// Created by Pepi on 4/22/17.
// Copyright © 2017 Pepi. All rights reserved.
//
#include "Employee.hpp"
#include "ComunityMember.hpp"
#include "Student.hpp"
#include "Staff.hpp"
#include <iostream>
#include <string>
#include <vector>
#include "Adress.hpp"
using namespace std;
int main(){
Adress adres1(12,"street" , 7);
Adress adres2(13,"bulevard", 5);
ComunityMember firstComun("ivan","ivanov",1998,3200, adres1);
int year = firstComun.calculateSalary();
cout << year<<":::"<<endl;
firstComun.printInfo();
// Employee firsEmpl("lubomir" , "petrov" , 1986,2400,1 ,adres2);
// firsEmpl.employeePrintInfo();
Student student1("gogo", "ivanov" , 1999, " informatika" ,4 );
// student1.printInfo();
// Staff staff1("ivo", "ivov",1889,3,1200);
// staff1.printInfo();
// firstComun.printInfo();
return 0;
}
|
835202e8ffab35116eef30a95c09dc7f926c1b5e
|
343e6980be403c6ef38072b785fcb66c431c4aa2
|
/Pacman/Classes/View/WorldScene.cpp
|
26033a42c70a68679eb5de754779c7f474eb473f
|
[] |
no_license
|
BeemoLin/pac-man-cocos2dx
|
9d8886812d6b69ed1beb49307e5fca7671126205
|
4daca26b4e134068d971d03f19853e059c40b01a
|
refs/heads/master
| 2020-12-11T05:45:10.867726
| 2014-09-15T21:20:14
| 2014-09-15T21:20:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,400
|
cpp
|
WorldScene.cpp
|
#include "View\WorldScene.h"
#include "Model\ReadLevel.h"
#include "SimpleAudioEngine.h"
#include "MainMenuScene.h"
WorldScene* WorldScene::create(std::string levelName) {
WorldScene* scene = new WorldScene();
if(scene && scene->init(levelName)){
return (WorldScene*)scene->autorelease();
}
CC_SAFE_DELETE(scene);
return scene;
}
bool WorldScene::init(std::string levelName) {
if ( !Layer::init() ) {
return false;
}
worldController_ = new WorldController();
isSound_ = CCUserDefault::sharedUserDefault()->getBoolForKey("SOUND", false);
worldController_->setRecord(CCUserDefault::sharedUserDefault()->getIntegerForKey("RECORD",0));
if(isSound_){
CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic("audio/sirensound.wav");
CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("audio/sirensound.wav", true);
}
worldController_->setDirection(LEFT);
isPause_ = false;
readLevel_ = new ReadLevel();
readLevel_->readFile(levelName);
int size = readLevel_->getLevel()->bricks->size();
world_ = new World(readLevel_->getLevel());
worldController_->init(world_);
auto touchListener = EventListenerTouchOneByOne::create();
touchListener->onTouchBegan = CC_CALLBACK_2(WorldScene::TouchBegan,this);
touchListener->onTouchMoved = CC_CALLBACK_2(WorldScene::TouchMoved, this);
touchListener->onTouchEnded = CC_CALLBACK_2(WorldScene::TouchEnded,this);
getEventDispatcher()->addEventListenerWithFixedPriority(touchListener, 100);
setTouchMode(kCCTouchesOneByOne);
for(int i=0; i < size; i++){
this->addChild(readLevel_->getLevel()->bricks->get(i)->getTexture(), 0);
}
this->addChild(worldController_->getLabelRecord(), 1);
this->addChild(worldController_->getLabelScore(), 1);
this->addChild(world_->getPlayer()->getTexture(),2);
for(int i=0; i < world_->spirits->size(); i++){
this->addChild(world_->spirits->get(i)->getTexture(),2);
}
this->setKeyboardEnabled(true);
this->schedule(schedule_selector(WorldScene::updatePlayer),0.05f);
this->schedule(schedule_selector(WorldScene::updateWorld),0.07f);
this->schedule(schedule_selector(WorldScene::timerTask),1.0f);
this->schedule(schedule_selector(WorldScene::speedTask),0.03f);
scene_ = Scene::create();
scene_->addChild(this);
return true;
}
void WorldScene::timerTask(float dt){
worldController_->timerTask(dt);
}
void WorldScene::speedTask(float dt){
worldController_->speedTask(dt);
}
void WorldScene::updatePlayer(float dt){
worldController_->updatePlayer(dt);
}
void WorldScene::updateWorld(float dt){
worldController_->updateWorld(dt);
}
bool WorldScene::TouchBegan(Touch *touch, Event *event){
worldController_->setTouch(touch->getLocation().x, touch->getLocation().y);
return true;
}
void WorldScene::TouchMoved(Touch* touch, CCEvent* event){
worldController_->TouchMoved(touch->getLocation().x,touch->getLocation().y);
}
void WorldScene::TouchEnded(Touch* touch, Event* event){
worldController_->TouchEnded(touch->getLocation().x,touch->getLocation().y);
}
void WorldScene::onKeyReleased(EventKeyboard::KeyCode keyCode, Event *event){
if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID){
CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();
CocosDenshion::SimpleAudioEngine::getInstance()->stopAllEffects();
Director::getInstance()->pushScene(MainMenuScene::create()->getScene());
}
}
|
5d08ef00af5dd69214dcb585bd92b7633b5d0c63
|
2124d0b0d00c3038924f5d2ad3fe14b35a1b8644
|
/source/GamosCore/GamosGenerator/src/GmIsotopeDecay.cc
|
3b066976adc67c47ed9224ba77b69d55e2162bdc
|
[] |
no_license
|
arceciemat/GAMOS
|
2f3059e8b0992e217aaf98b8591ef725ad654763
|
7db8bd6d1846733387b6cc946945f0821567662b
|
refs/heads/master
| 2023-07-08T13:31:01.021905
| 2023-06-26T10:57:43
| 2023-06-26T10:57:43
| 21,818,258
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,416
|
cc
|
GmIsotopeDecay.cc
|
#include "GmIsotopeDecay.hh"
#include "GmGenerVerbosity.hh"
#include "GamosCore/GamosUtils/include/GmGenUtils.hh"
#include "G4ParticleTable.hh"
#include "G4tgrUtils.hh"
GmIsotopeDecay::GmIsotopeDecay( const G4String& energy, const G4String& prob, const G4String& product )
{
if( !GmGenUtils::IsNumber( energy ) ){
G4Exception("GmIsotopeDecay::GmIsotopeDecay",
"Wrong argument",
FatalErrorInArgument,
G4String("Energy should be given as a number " + energy).c_str());
}
theEnergy = G4tgrUtils::GetDouble( energy, CLHEP::keV);
if( !GmGenUtils::IsNumber( prob ) ){
G4Exception("GmIsotopeDecay::GmIsotopeDecay",
"Wrong argument",
FatalErrorInArgument,
G4String("Probability should be given as a number " + prob).c_str());
}
theProbability = GmGenUtils::GetValue( prob );
G4ParticleTable* partTable = G4ParticleTable::GetParticleTable();
theProduct = partTable->FindParticle(product);
if( !theProduct ) {
G4Exception("GmIsotopeDecay::GmIsotopeDecay","Error in argument",FatalErrorInArgument,(" particle does not exist: " + product).c_str() );
}
#ifndef GAMOS_NO_VERBOSE
if( GenerVerb(infoVerb) ) G4cout << " GmIsotopeDecay::GmIsotopeDecay product " << theProduct->GetParticleName() << " energy " << theEnergy << " prob " << theProbability << G4endl;
#endif
}
G4String GmIsotopeDecay::GetProductName() const
{
return theProduct->GetParticleName();
}
|
fd823788c18f0f1ac53d187b8d813ed94bb102fc
|
09ce52bdf2052b1b4627d03aaec5c1e40761488b
|
/src/app/rbj_filter.h
|
1f475676165898af5169efe5180abcbf0d81cc6e
|
[
"BSD-3-Clause"
] |
permissive
|
flit/bass.slab
|
5d077d8350c0922a4252c175df9011aaf79ea787
|
9b2d47545ef0045999c9e7a4aa94ba1ddab7fb1a
|
refs/heads/master
| 2021-01-09T20:40:44.537711
| 2016-12-23T20:04:12
| 2016-12-23T20:04:12
| 61,446,654
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,151
|
h
|
rbj_filter.h
|
/*
* Copyright (c) 2015 Immo Software
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if !defined(_RBJ_FILTER_H_)
#define _RBJ_FILTER_H_
#include "audio_filter.h"
#include <stdint.h>
//------------------------------------------------------------------------------
// Definitions
//------------------------------------------------------------------------------
namespace slab {
/*!
* This filter class wraps up and makes it easy to use filter from the
* cookbook by Robert Bristow-Johnson. The single class CRBJFilter provides
* all types of filters described in his cookbook (well, all those I've
* implemented so far).
*
* The filter type is set either in the constructor or using the
* \c SetFilterType() member function. If no filter type is set in the
* constructor, the filter will default to low pass.
*
* Because this class is based on \c CAudioUtilityBase, you must set the
* sample rate using the member function \c SetSampleRate() before the
*
*/
class RBJFilter : public AudioFilter
{
public:
typedef enum {
kLowPass, //!< low pass filter
kHighPass, //!< high pass filter
kBandPass, //!< band pass filter
kNotch, //!< notch filter
kAllPass //!< second-order allpass filter
} FilterType;
RBJFilter(FilterType theType = kLowPass);
virtual ~RBJFilter() {}
//! Resets the sample history
void reset();
//! Changes the filter type. You must call \c RecomputeCoefficients()
//! for the change to take effect on filtered samples.
void set_filter_type(FilterType theType) { mType = theType; }
FilterType get_filter_type() { return mType; } //!< Returns the current filter type.
//! Sets the filter frequency. This value is in samples per second, and
//! should not be higher than the Nyquist frequency, or half the
//! sampling rate.
void set_frequency(float f) { frequency = f; }
float get_frequency() { return frequency; } //!< Returns the current cutoff frequency.
//! Sets the filter bandwidth. The filter can use either bandwidth or
//! Q but not both. Setting the bandwidth sets a flag indicating to use
//! the bandwidth instead of Q..
//! \sa SetQ()
void set_bandwidth(float b) { bandwidth = b; useQ = false; }
float get_bandwidth() { return bandwidth; } //!< Returns the current bandwidth.
//! Sets the filter Q, or resonance. Setting Q sets the flag saying to use
//! Q instead of bandwidth.
//! \sa SetBandwidth()
void set_q(float theQ) { q = theQ; useQ = true; }
float get_q() { return q; } //!< Returns the current Q value.
//! Recalculates coefficients. Does not reset the sample history, so
//! the filter parameters can be changed in the middle of processing.
void recompute_coefficients();
//! Returns the input sample run through the filter.
//! \param inputSample An input sample.
//! \result The filtered sample.
float tick(float inputSample);
//! Specifies an array containing values for the filter cutoff frequency
//! to be used during Process(). This must be called before each call
//! to Process(), because the value array is reset once it is used.
void set_frequency_values(float* f, uint32_t count) { freqValues = f; freqValueCount = count; }
protected:
FilterType mType;
float frequency, bandwidth, q;
float omega, xsin, xcos, alpha;
float b0, b1, b2, a0, a1, a2;
float in1, in2, out1, out2;
float b0a0, b1a0, b2a0, a1a0, a2a0;
float *freqValues;
uint32_t freqValueCount;
bool useQ;
virtual void _process(float * samples, uint32_t count);
};
} // namespace slab
#endif // _RBJ_FILTER_H_
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
|
9b22757aaf4940eb46ad093e43860ee72c7b798e
|
26c3e3c441c021dd0138afef886ef802b451fced
|
/include/tools/config.h
|
7676664afedf9d8131d03b3892d5b1ba2e6e7633
|
[] |
no_license
|
chxj1980/firstproject
|
1b25543db4e4b3d1ba636a03d2f3d9d8c8fef69f
|
effadd90087a0894a84e5a90924935c6d492eada
|
refs/heads/master
| 2021-09-15T20:24:09.870832
| 2018-06-10T11:17:18
| 2018-06-10T11:17:18
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,327
|
h
|
config.h
|
#pragma once
#include "utility/noncopyable.h"
#include "tools/xtXml.h"
#include <string>
#include <map>
#include <wtypes.h>
using namespace std;
class config:private utility::noncopyable
{
private:
config(void);
~config(void);
public:
static config* instance()
{
return &self;
}
typedef pair<string, string> mutex_type;
xtXmlNodePtr get_router();
xtXmlNodePtr get_system();
int break_monitor(int val_default);
int break_monitor_time(int val_default);
int check_len(int val_default);
int check_timeout(int val_default);
int link_center(int val_default);
string xt_dbtype(string val_default);
int copy_send(int val_default);
int link_type(int val_default);
int chan_num(int val_default);
string local_sndip(string val_default);
int snd_port(int val_default);
int demux_s(int val_default);
string mul_ip(string val_default);
int tcp_listenprt(int val_default);
int xtmsg_listenprt(int val_default);
int rtsp_listenprt(int val_default);
string center_ip(string val_default);
string local_ip(string val_default);
string local_name(string val_default);
int center_port(int val_default);
int center_id(int val_default);
private:
// xml
xtXml m_config;
// 文件路径
std::string m_fPath;
// 命名内核
map<string, string> m_mapMutex;
HANDLE m_hMutex;
static config self;
};
|
68138d54509d6a47071cd17ece133baf40b8b0f0
|
a4a52b549ac1bf9266ecbe58c1e8388331c947bf
|
/src/types/tenv.cpp
|
0cdd5efd242f489a2f9f69de73e2b5eec851211a
|
[
"MIT"
] |
permissive
|
vimlord/Lomda
|
56074de148351ddddf8845320b7926f98e3de5fb
|
70cb7a9616c50fde3af62400fdcf945c63fad810
|
refs/heads/master
| 2021-10-18T05:13:37.569775
| 2019-02-08T04:27:32
| 2019-02-08T18:05:57
| 114,925,147
| 5
| 1
|
MIT
| 2019-02-14T02:17:59
| 2017-12-20T19:49:35
|
C++
|
UTF-8
|
C++
| false
| false
| 3,094
|
cpp
|
tenv.cpp
|
#include "types.hpp"
#include "proof.hpp"
using namespace std;
string TypeEnv::next_id = "a";
TypeEnv::~TypeEnv() {
for (auto it : types)
delete it.second;
for (auto it : mgu)
delete it.second;
}
Type* TypeEnv::apply(string x) {
if (types.find(x) == types.end()) {
// We need to instantiate this type to be a new variable type
auto V = make_tvar();
types[x] = V;
}
return types[x]->clone();
}
bool TypeEnv::hasVar(string x) {
return types.find(x) != types.end();
}
int TypeEnv::set(string x, Type* v) {
int res = 0;
if (types.find(x) != types.end()) {
delete types[x];
res = 1;
}
types[x] = v;
return res;
}
Tenv TypeEnv::clone() {
Tenv env = new TypeEnv;
for (auto it : types)
env->set(it.first, it.second->clone());
for (auto it : mgu)
env->set_tvar(it.first, it.second->clone());
env->next_id = next_id;
return env;
}
Type* TypeEnv::get_tvar(string v) {
if (mgu.find(v) != mgu.end())
return mgu[v];
else {
mgu[v] = new VarType(v);
return mgu[v];
}
}
void TypeEnv::set_tvar(string v, Type *t) {
rem_tvar(v); mgu[v] = t;
}
void TypeEnv::rem_tvar(string v) {
if (mgu.find(v) != mgu.end()) {
delete mgu[v];
mgu.erase(v);
}
}
Type* TypeEnv::make_tvar() {
// Create a brand new type variable.
auto V = new VarType(next_id);
mgu[next_id] = V;
show_proof_step("Let " + next_id + " be a fresh type variable.");
show_proof_step("This extends the tenv to " + toString() + ".");
// Increment the next_id var
int i;
for (i = next_id.length()-1; i >= 0 && next_id[i] == 'z'; i--)
next_id[i] = 'a';
if (i < 0)
next_id = "a" + next_id;
else
next_id[i]++;
return V->clone();
}
Tenv TypeEnv::unify(Tenv other, Tenv scope) {
Tenv tenv = new TypeEnv;;
// Merge the MGUs
for (auto it : mgu) {
string s = it.first;
if (other->mgu.find(s) != other->mgu.end()) {
auto T = it.second->unify(other->mgu[s], scope);
if (!T) {
delete tenv;
return NULL;
} else
tenv->types[s] = T;
} else {
tenv->types[s] = it.second->clone();
}
}
for (auto it : other->mgu) {
string s = it.first;
if (tenv->mgu.find(s) != tenv->mgu.end()) {
tenv->types[s] = it.second->clone();
}
}
// Merge the types
for (auto it : types) {
string s = it.first;
if (other->hasVar(s)) {
auto T = it.second->unify(other->types[s], scope);
if (!T) {
delete tenv;
return NULL;
} else
tenv->types[s] = T;
} else {
tenv->types[s] = it.second->clone();
}
}
for (auto it : other->types) {
string s = it.first;
if (!tenv->hasVar(s)) {
tenv->types[s] = it.second->clone();
}
}
return tenv;
}
|
4a8bbd6ed69ff1fbf78bb8a685f8dbe6c3721dc5
|
a7a1402b69773eadb7ddded20725f5aa9b52d0f1
|
/Chapter4/4.3-IOStream.h
|
093023f18d6786963db3741af712d93d614c9a7d
|
[] |
no_license
|
theOtherWorld/Learning-Cplusplus
|
0194a52652e768085ef42de67ab772060fc6b2d3
|
62ff7ec69bdf0fc3b3a040ea43e5d310e52b7334
|
refs/heads/master
| 2021-07-06T03:59:12.718122
| 2017-09-30T10:21:47
| 2017-09-30T10:21:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,056
|
h
|
4.3-IOStream.h
|
//
// Created by xl on 2017/8/25.
//
/**
* io 数据流
*/
#ifndef C_PROGRAMMING_LANGUAGE_4_3_IOSTREAM_H
#define C_PROGRAMMING_LANGUAGE_4_3_IOSTREAM_H
#include <string>
#include <iostream>
#include <ios>
using namespace std;
namespace i_o_s{
/**
* 用户自定义类型的I/O
*/
struct Entry{
string name;
int number;
};
ostream& operator<< (ostream& os, const Entry& e){
return os<<"{"<<e.name<<","<<e.number<<"}";
}
istream& operator>> (istream& is, Entry& e){
char c1,c2;
if(is>>c1 && c1 == '{' && is >>c2 && c2 == '"'){
string name;
while(is.get(c1) && c1 != '"') name += c1;
if(is>>c2 && c2 == ','){
int num = 0;
if(is>>num>>c2 && c2 == '}'){
e = {name,num};
return is;
}
}
}
is.setstate(ios_base::failbit); // 置输入流状态为失败
return is;
}
}
#endif //C_PROGRAMMING_LANGUAGE_4_3_IOSTREAM_H
|
975c0eb1883f66db8dd491376cae8c2a76457269
|
39df52e86e7c99948731751eeb84d50debcebfb8
|
/NEBeauty/PC/personcall-1v1_nertc_beauty/source/src/call_widget.cpp
|
d8980e500d9747b77cf3777b92eec69417827641
|
[
"MIT"
] |
permissive
|
tk2241998613/Advanced-Video
|
759de2627431900ac857fae06cc354cfa5d8c0fa
|
f006d18ac9703d4ba13ae402dd44733957e2b934
|
refs/heads/master
| 2023-08-20T23:08:40.656844
| 2021-10-26T08:13:19
| 2021-10-26T08:13:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,907
|
cpp
|
call_widget.cpp
|
#include <QApplication>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMoveEvent>
#include <QDebug>
#include "json/json.h"
#include "call_widget.h"
#include "engine.h"
#include "video_widget.h"
#include "room_button.h"
#include "beauty_tabwidget.h"
CallWidget::CallWidget(Engine* engine, QWidget *parent /*= nullptr*/)
:engine_(engine)
,QWidget(parent)
{
setUi();
room_button_ = new RoomButton(this);
beauty_tabwidget_ = new BeautyTabWidget(this);
nertc_beauty_tabwidget_ = new BeautyTabWidget(this);
connect(engine_, &Engine::sigJoinChannel, this, &CallWidget::onJoinChannel);
connect(engine_, &Engine::sigUserJoined, this, &CallWidget::onUserJoin);
connect(engine_, &Engine::sigUserVideoStart, this, &CallWidget::onUserVideoStart);
connect(engine_, &Engine::sigUserLeft, this, &CallWidget::onUserLeft);
//
connect(room_button_, &RoomButton::sigStartBeauty, this, &CallWidget::onStartBeauty);
connect(room_button_, &RoomButton::sigNertcBeautySetting, this, [=] {nertc_beauty_tabwidget_->show(); });
connect(nertc_beauty_tabwidget_, &BeautyTabWidget::sigBautyEnable, this, &CallWidget::onBeautyEnable);
connect(nertc_beauty_tabwidget_, &BeautyTabWidget::sigBeautyMirror, this, &CallWidget::onBeautyMirror);
connect(nertc_beauty_tabwidget_, &BeautyTabWidget::sigBeautyMakeup, this, &CallWidget::onBeautyMakeup);
connect(nertc_beauty_tabwidget_, &BeautyTabWidget::sigItemStickerChanged, this, &CallWidget::onItemStickerChanged);
connect(nertc_beauty_tabwidget_, &BeautyTabWidget::sigFilterChanged, this, &CallWidget::onFilterChanged);
connect(nertc_beauty_tabwidget_, &BeautyTabWidget::sigBeautyChanged, this, &CallWidget::onBeautyChanged);
}
CallWidget::~CallWidget()
{
qDebug() << "~CallWidget~CallWidget~CallWidget";
}
int CallWidget::JoinChannel(const JoinInfo &join_info)
{
//Init engine
QString log_dir_path = qApp->applicationDirPath() + "\\NERTC";
bool init = engine_->Init(log_dir_path.toStdString().c_str());
if (true == init)
{
engine_->EnableVideo(join_info.open_camera_);
engine_->EnableAudio(join_info.open_mic_);
if (true == join_info.open_1v1_)
{
Json::Value values;
values["channel_1v1_mode_enabled"] = true; //1v1
Json::FastWriter writer;
std::string parameters = writer.write(values);
engine_->SetParameters(parameters.c_str());
}
// 设置自己的渲染窗口
void* hwnd = (void*)local_video_widget_->GetVideoHwnd();
engine_->SetupLocalVideo(hwnd);
return engine_->JoinChannel(join_info.channel_name_.toStdString(), join_info.uid_.toStdString());
}
}
void CallWidget::resizeEvent(QResizeEvent* event)
{
QPoint p(this->rect().left(), this->rect().bottom());
p = mapToGlobal(p);
room_button_->move(p.x() + this->width() / 2 - room_button_->width() / 2, p.y() - 92);
return QWidget::resizeEvent(event);
}
void CallWidget::moveEvent(QMoveEvent* event)
{
room_button_->move(event->pos().x() + this->width() / 2 - room_button_->width() / 2, event->pos().y() + this->rect().bottom() - 92);
return QWidget::moveEvent(event);
}
void CallWidget::setUi()
{
this->setMinimumSize(QSize(1366, 718));
QWidget* video_page = new QWidget();
QVBoxLayout* main_layout = new QVBoxLayout(video_page);
main_layout->setSpacing(0);
main_layout->setContentsMargins(0, 0, 0, 0);
QWidget* central_widget = new QWidget(video_page);
central_widget->setStyleSheet("QWidget{background-color: rgb(0, 0, 0);}");
vertical_layout_ = new QVBoxLayout(central_widget);
vertical_layout_->setSpacing(2);
vertical_layout_->setContentsMargins(58, 8, 58, 8);
video_hlayout_ = new QHBoxLayout();
vertical_layout_->addLayout(video_hlayout_);
main_layout->addWidget(central_widget);
QHBoxLayout* h_layout = new QHBoxLayout(this);
h_layout->setSpacing(0);
h_layout->setContentsMargins(0, 0, 0, 0);
h_layout->addWidget(video_page);
local_video_widget_ = new VideoWidget(this);
video_hlayout_->addWidget(local_video_widget_);
remote_video_widget_ = new VideoWidget(this);
remote_video_widget_->setVisible(false);
}
void CallWidget::adjustVideoLayout()
{
clearLayout();
video_hlayout_->addWidget(local_video_widget_);
local_video_widget_->setVisible(true);
if (2 == user_count_)
{
video_hlayout_->addWidget(remote_video_widget_);
remote_video_widget_->setVisible(true);
}
}
void CallWidget::clearLayout()
{
while (video_hlayout_->count())
{
video_hlayout_->itemAt(0)->widget()->setParent(nullptr);
}
local_video_widget_->setVisible(false);
remote_video_widget_->setVisible(false);
}
void CallWidget::onJoinChannel(const int& reson)
{
qDebug() << "CallWidget::onJoinChannel:" << reson;
this->showNormal();
this->resize(1184, 666);
room_button_->setVisible(true);
}
void CallWidget::onUserJoin(const quint64& uid, const QString& name)
{
if (nullptr == remote_video_widget_)
{
remote_video_widget_ = new VideoWidget(this);
}
void* hwnd = remote_video_widget_->GetVideoHwnd();
engine_->SetupRemoteVideo(uid, hwnd);
user_count_++;;
adjustVideoLayout();
}
void CallWidget::onUserVideoStart(const quint64& uid, const int& profile)
{
qDebug() << "NECallWidget::onUserVideoStart: uid:" << uid << ", profile: " << profile;
int ret = engine_->SubscribeRemoteVideoStream(uid, nertc::kNERtcRemoteVideoStreamTypeHigh, true);
if (ret)
{
qDebug() << "can not subscribe remote video stream! ret: " << ret;
}
}
void CallWidget::onUserLeft(const quint64& uid, const int& result)
{
qDebug() << "CallWidget::onUserLeft";
user_count_--;
adjustVideoLayout();
engine_->SetupRemoteVideo(uid, nullptr);
}
void CallWidget::onBeautyChanged(const int& id, const int &val)
{
engine_->SetBeautyEffect(id, val / 100.f);
}
void CallWidget::onFilterChanged(const QString& path, const int &val)
{
engine_->SelectBeautyFilter(std::string(path.toLocal8Bit()), val);
}
void CallWidget::onItemStickerChanged(const std::string &str)
{
engine_->SelectBeautySticker(str);
}
void CallWidget::onStartBeauty(const bool& start_enabled)
{
if (true == start_enabled)
{
int ret = engine_->StartBeauty();
qDebug() << "ret:" << ret;
}
else
{
engine_->StopBeauty();
}
}
void CallWidget::onBeautyEnable(const bool& enable)
{
qDebug() << "CallWidget::onBeautyEnable:" << enable;
engine_->EnableNertcBeauty(enable);
}
void CallWidget::onBeautyMirror(const bool& enable)
{
qDebug() << "CallWidget::onBeautyMirror:" << enable;
engine_->EnableNertcMirror(enable);
}
void CallWidget::onBeautyMakeup(const bool& enable)
{
engine_->EnableNertcMakeup(enable);
}
|
8223276d89f609b8c7baa6a4a9c9237a067e213b
|
3928dbd2997763bccd77dbec2c55a1e3a84a57be
|
/SpringMass/src/ofApp.cpp
|
6e1c4f440f28ee1d369a7eddce128655a4c1f395
|
[] |
no_license
|
JanSnieg/ModelowanieFizyczne
|
1ed84031c861d4e3aa20905a68e01abe69dc9ae1
|
01123249dfe578e81de2dd179e11265b569ac6f7
|
refs/heads/master
| 2021-09-05T16:48:08.345793
| 2018-01-29T18:40:49
| 2018-01-29T18:40:49
| 111,568,270
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,354
|
cpp
|
ofApp.cpp
|
#include "ofApp.hpp"
//--------------------------------------------------------------
void ofApp::setup()
{
gui.setup();
gui.add(rectangleMass.setup("Rectangle mass",10,10,300));
ofSetFrameRate(30);
ofBackground(35, 42, 70);
}
//--------------------------------------------------------------
void ofApp::update()
{
moveRectangle();
moveTrampoline();
rectangle.setMass(rectangleMass);
}
//--------------------------------------------------------------
void ofApp::draw()
{
trampoline.draw();
rectangle.drawRectangle();
gui.draw();
}
void ofApp::moveRectangle()
{
rectangle.updatePosition();
rectangle.updateVelocity();
rectangle.updateForce();
}
void ofApp::moveTrampoline()
{
// for (int i=0; i<trampoline.pointsVector.size(); i++)
// {
//// float x = trampoline.pointsVector[i].getPosition().x[1] - rectangle.getPosition().x;
//// float y = rectangle.getPosition().y + rectangle.side - trampoline.pointsVector[i].getPosition().y[1];
//// float distance = sqrt((x * x) + (y * y));
// if (y == 0)
// {
// float forceX = trampoline.pointsVector[i].getForce().x;
// float forceY = trampoline.pointsVector[i].getForce().y;
// trampoline.pointsVector[i].setPosiotion(rectangle.getPosition().x, rectangle.getPosition().y, 1);
// trampoline.pointsVector[i].setForce(forceX + rectangle.getForce().x, forceY + rectangle.getForce().y);
// }
// }
// if (rectangle.getPosition().y - trampoline.pointsVector[7].getPosition().y[1] >= 1)
// {
// float forceX = trampoline.pointsVector[7].getForce().x;
// float forceY = trampoline.pointsVector[7].getForce().y;
// trampoline.pointsVector[7].setPosiotion(rectangle.getPosition().x, rectangle.getPosition().y, 1);
//// trampoline.pointsVector[7].setForce(forceX + rectangle.getForce().x, forceY + rectangle.getForce().y);
// float force = rectangle.getForce().y;
// force -= trampoline.pointsVector[7].getForce().y;;
// rectangle.setForce(0, force);
// }
trampoline.updateAll();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
|
28328adac09b267cf61f0b9f40c80bd8f26ceac8
|
90e2f09587cac69b1f4a76f3f090d1c02ef78391
|
/src/modes/open/openLogMode.h
|
b65222dd8a66bc2859ac9c4932c1d56d026e226e
|
[
"BSD-3-Clause"
] |
permissive
|
KDE/ksystemlog
|
70fa55a30bb960c6954e6d01f7c7d286a33f24eb
|
6ba2eb3ed81390fda48b091b114610d5c747b8a3
|
refs/heads/master
| 2023-08-16T18:26:34.352481
| 2023-08-06T01:54:13
| 2023-08-06T01:54:13
| 42,737,002
| 13
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 652
|
h
|
openLogMode.h
|
/*
SPDX-FileCopyrightText: 2007 Nicolas Ternisien <nicolas.ternisien@gmail.com>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#pragma once
/**
* Open Log Mode Identifier
*/
#define OPEN_LOG_MODE_ID "openLogMode"
/**
* System Log Icon
*/
#define OPEN_MODE_ICON "document-open"
#include "logFile.h"
#include "logMode.h"
class QWidget;
class OpenLogMode : public LogMode
{
Q_OBJECT
public:
explicit OpenLogMode(QWidget *parent);
~OpenLogMode() override;
Analyzer *createAnalyzer(const QVariant &options = QVariant()) override;
QVector<LogFile> createLogFiles() override;
private:
QWidget *const mParent;
};
|
46ea7e5e8b3aec9c5056fc0395b4ee421d1da22a
|
5d83739af703fb400857cecc69aadaf02e07f8d1
|
/Archive2/dd/11b605dc696b94/main.cpp
|
9d2dcb9fe7307a8f238f7b10d0a812b3b32efc32
|
[] |
no_license
|
WhiZTiM/coliru
|
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
|
2c72c048846c082f943e6c7f9fa8d94aee76979f
|
refs/heads/master
| 2021-01-01T05:10:33.812560
| 2015-08-24T19:09:22
| 2015-08-24T19:09:22
| 56,789,706
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,583
|
cpp
|
main.cpp
|
#include <cstddef>
#include <type_traits>
#include <initializer_list>
#include <algorithm>
namespace Furrovine {
template <typename T, std::size_t n, std::size_t a = std::alignment_of<T>::value>
class fixed_vector {
public:
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
typedef T* pointer_type;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef pointer_type iterator;
typedef const pointer_type const_iterator;
private:
typename std::aligned_storage<sizeof( T ) * n, a>::type items;
std::size_t len;
T* ptrat ( std::size_t idx ) {
return static_cast<T*>( static_cast<void*>( &items ) ) + idx;
}
const T* ptrat( std::size_t idx ) const {
return static_cast<const T*>( static_cast<const void*>( &items ) ) + idx;
}
T& refat ( std::size_t idx ) {
return *ptrat( idx );
}
const T& refat ( std::size_t idx ) const {
return *ptrat( idx );
}
void move_space_into( std::size_t idx ) {
for ( std::size_t i = idx + 1; i < len; ++i ) {
std::swap( refat( i - 1 ), refat( i ) );
}
}
void free_space_at( std::true_type, std::size_t idx ) {
for ( std::size_t i = len; i > idx; --i ) {
refat( i ) = std::move( refat( i - 1 ) );
}
}
void free_space_at( std::false_type, std::size_t idx ) {
for ( std::size_t i = len; i > idx; --i ) {
refat( i ) = refat( i - 1 );
}
}
void prepare_insert( std::size_t idx ) {
if ( idx >= len )
throw std::out_of_range( "requested index is out of bounds" );
if ( len == capacity( ) )
throw std::out_of_range( "max capacity reached" );
free_space_at( std::is_move_assignable<T>(), idx );
}
public:
static const std::size_t max_size () {
return n;
}
fixed_vector( ) : len( 0 ) {
}
fixed_vector( fixed_vector&& mov ) : len( 0 ) {
for ( std::size_t i = 0; i < mov.size( ); ++i )
push_back( std::move( mov[ i ] ) );
mov.clear( );
}
fixed_vector( const fixed_vector& mov ) : len( 0 ) {
for ( std::size_t i = 0; i < mov.size( ); ++i )
push_back( mov[ i ] );
}
fixed_vector& operator=( fixed_vector&& mov ) {
clear( );
for ( std::size_t i = 0; i < mov.size( ); ++i )
push_back( std::move( mov[ i ] ) );
mov.clear( );
return *this;
}
fixed_vector& operator=( const fixed_vector& mov ) {
clear( );
for ( std::size_t i = 0; i < mov.size( ); ++i )
push_back( mov[ i ] );
mov.clear( );
return *this;
}
fixed_vector( std::size_t sz ) : len( std::min( n, sz ) ) {
if ( sz > capacity( ) )
throw std::out_of_range( "requested size is beyond fixed capacity" );
}
template <std::size_t c>
fixed_vector( const T( &arr )[ c ] ) : len( c ) {
static_assert( c < n, "Array too large to initialize fixed_vector" );
std::copy( std::addressof( arr[ 0 ] ), std::addressof( arr[ c ] ), data( ) );
}
fixed_vector( std::initializer_list<T> initializer ) : len( std::min( n, initializer.size( ) ) ) {
if ( initializer.size( ) > capacity( ) )
throw std::out_of_range( "requested size is beyond fixed capacity" );
std::copy( initializer.begin( ), initializer.begin( ) + len, data( ) );
}
bool empty () const {
return len < 1;
}
bool not_empty () const {
return len > 0;
}
bool full () const {
return len >= n;
}
void push_back ( const T& item ) {
if ( len == capacity( ) )
throw std::out_of_range( "max capacity reached" );
new( ptrat( len ) ) T( item );
len++;
}
void push_back ( T&& item ) {
if ( len == capacity( ) )
throw std::out_of_range( "max capacity reached" );
new( ptrat( len ) ) T( std::move( item ) );
len++;
}
template <typename ...Tn>
void emplace_back ( Tn&&... argn ) {
if ( len == capacity( ) )
throw std::out_of_range( "max capacity reached" );
new( ptrat( len ) ) T( std::forward<Tn>( argn )... );
len++;
}
void pop_back ( ) {
if ( len == 0 )
return;
T& addr = refat( len - 1 );
addr.~T();
--len;
}
void clear () {
for ( ; len > 0; ) {
pop_back();
}
}
void erase( std::size_t idx ) {
if ( idx >= len )
throw std::out_of_range( "requested index is out of bounds" );
T& erased = refat( idx );
erased.~T( );
move_space_into( idx );
--len;
}
void insert( std::size_t idx, const T& item ) {
prepare_insert( idx );
new( ptrat( idx ) ) T( item );
len++;
}
void insert( std::size_t idx, T&& item ) {
prepare_insert( idx );
new( ptrat( idx ) ) T( std::move( item ) );
len++;
}
template <typename... Tn>
void emplace( std::size_t idx, Tn&&... argn ) {
prepare_insert( idx );
new( ptrat( idx ) ) T( std::forward<Tn>( argn )... );
len++;
}
std::size_t size () const {
return len;
}
std::size_t capacity () const {
return n;
}
void resize ( std::size_t sz ) {
if ( sz > capacity( ) )
throw std::out_of_range( "requested size is beyond fixed capacity" );
len = sz;
}
T* data () {
return ptrat( 0 );
}
const T* data () const {
return ptrat( 0 );
}
T& at ( std::size_t idx ) {
if ( idx >= len )
throw std::out_of_range( "requested index is out of bounds" );
return refat( idx );
}
const T& at ( std::size_t idx ) const {
if ( idx >= len )
throw std::out_of_range( "requested index is out of bounds" );
return refat( idx );
}
T& operator[] ( std::size_t idx ) {
return refat( idx );
}
const T& operator[] ( std::size_t idx ) const {
return refat( idx );
}
T& front () {
return refat( 0 );
}
T& back () {
return refat( len - 1 );
}
const T& front () const {
return refat( 0 );
}
const T& back () const {
return refat( len - 1 );
}
T* begin () {
return data();
}
const T* cbegin () {
return data();
}
const T* begin () const {
return data();
}
const T* cbegin () const {
return data();
}
T* end( ) {
return data( ) + len;
}
const T* cend( ) {
return data( ) + len;
}
const T* end( ) const {
return data( ) + len;
}
const T* cend( ) const {
return data( ) + len;
}
std::reverse_iterator<iterator> rbegin( ) {
return std::reverse_iterator<iterator>( end( ) );
}
const std::reverse_iterator<iterator> crbegin( ) {
return std::reverse_iterator<iterator>( cend( ) );
}
const std::reverse_iterator<iterator> rbegin( ) const {
return std::reverse_iterator<iterator>( end( ) );
}
const std::reverse_iterator<iterator> crbegin( ) const {
return std::reverse_iterator<iterator>( cend( ) );
}
std::reverse_iterator<iterator> rend( ) {
return std::reverse_iterator<iterator>( begin( ) );
}
const std::reverse_iterator<iterator> crend( ) {
return std::reverse_iterator<iterator>( cbegin( ) );
}
const std::reverse_iterator<iterator> rend( ) const {
return std::reverse_iterator<iterator>( begin( ) );
}
const std::reverse_iterator<iterator> crend( ) const {
return std::reverse_iterator<iterator>( cbegin() );
}
};
}
#include <iostream>
template <typename T, std::size_t n, std::size_t a>
void print ( Furrovine::fixed_vector<T, n, a>& fv ) {
for ( auto& i : fv )
std::cout << i << " ";
std::cout << std::endl << std::endl;
}
int main( ) {
using namespace Furrovine;
fixed_vector<int, 5> fv = { 1, 2, 3, 4, 5 };
fv.erase( 0 );
print( fv );
fv.emplace( 0, 10 );
print( fv );
fv.erase( 4 );
print( fv );
fv.insert( 0, 11 );
print( fv );
fv.erase( 2 );
print( fv );
fv.insert( 2, 12 );
print( fv );
}
|
f1f8824246983d195d403687232d68d49057f09a
|
f90e8e7edcd58bc332af9cd91a57b88cb5e0b804
|
/OS1 Projekat/src/kernel.cpp
|
800b1400be02a92dc94f99b46db41af6d37b0aac
|
[] |
no_license
|
denkoRa/OS-Kernel
|
5927c4b78915999a0f691a8020c832bba8489524
|
66628460b07f497d8eab7bc3f7e0440b3bc68fc8
|
refs/heads/master
| 2021-01-12T16:03:22.979415
| 2016-10-25T18:43:17
| 2016-10-25T18:43:17
| 71,927,848
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,334
|
cpp
|
kernel.cpp
|
/*
* kernel.cpp
*
* Created on: May 19, 2015
* Author: OS1
*/
#include "kernel.h"
#include <iostream.h>
#include <schedule.h>
#include <dos.h>
#include <stdlib.h>
typedef void interrupt (*InterPtr)(...);
InterPtr Kernel::oldTimer;
unsigned* Kernel::kernelStack = new unsigned [4096];
KernelList* Kernel::kernelList = new KernelList();
SleepList* Kernel::sleepList = new SleepList();
int Kernel::doScheduling = 0;
int Kernel::putIntoScheduler = 0;
PCB* Kernel::Idle = new PCB(1024, 1);
KernelList::KernelList() {
first = last = 0;
}
void Kernel::initSystem() {
#ifndef BCC_BLOCK_IGNORE
oldTimer = getvect(0x08);
setvect(0x60, oldTimer);
setvect(0x08, newTimer);
setvect(0x61, SysCall);
#endif
Kernel::Idle->startIdle(Kernel::emptyRun);
PCB::running = new PCB(2048, 2);
}
void Kernel::restoreSystemAndClear() {
#ifndef BCC_BLOCK_IGNORE
setvect(0x08, oldTimer);
#endif
delete Kernel::kernelStack;
delete Kernel::kernelList;
delete Kernel::sleepList;
}
void Kernel::emptyRun() {
while (1) {
}
}
int KernelList::size() {
Elem * cur = first;
int ret = 0;
while (cur != 0) {
ret++;
cur = cur->next;
}
return ret;
}
void KernelList::write(int id) {
Elem * cur = first;
while (cur != 0 && cur->id != id) cur = cur->next;
}
void KernelList::add(void* ptr, int id) {
Elem* newElem = new Elem(ptr, id, 0);
if (first) {
last->next = newElem;
last = newElem;
} else {
first = last = newElem;
}
}
void KernelList::remove(int id) {
Elem * cur = first;
if (cur->id == id) {
first = first->next;
delete cur;
if (first == 0) last = 0;
return;
}
Elem * prev = first;
cur = cur->next;
while (cur->id != id) {
cur = cur->next;
prev = prev->next;
}
prev->next = cur->next;
delete cur;
}
void* KernelList::find(int id) {
Elem * cur = first;
while (cur != 0 && cur->id != id) cur = cur->next;
return cur->genPtr;
}
KernelList::~KernelList() { //To be done
Elem * cur = first;
while (cur != 0) {
Elem * old = cur;
cur = cur->next;
delete old;
}
}
SleepList::SleepList() {
first = last = 0;
}
SleepList::~SleepList() {
Elem* cur = first;
while (cur != 0) {
Elem* old = cur;
cur = cur->next;
delete old;
}
}
int SleepList::timeLeft() {
return first->timeToSleep;
}
void SleepList::decreaseTime() {
first->timeToSleep--;
}
void SleepList::putInDreams(PCB* pcb, int timeToSleep) {
if (first){
if (timeToSleep < timeLeft()) {
Elem* newElem = new Elem(pcb, timeToSleep, 0, 0);
newElem->next = first;
first->timeBehind = timeLeft() - timeToSleep;
first = newElem;
} else {
Elem* newElem = new Elem(pcb, timeToSleep, 0, 0);
Elem *cur, *prev;
prev = first;
timeToSleep -= first->timeToSleep;
for (cur = first->next; cur != 0; cur = cur->next) {
if (timeToSleep - cur->timeBehind <= 0) break;
else timeToSleep -= cur->timeBehind;
prev = prev->next;
}
newElem->timeBehind = timeToSleep;
cur->timeBehind -= newElem->timeBehind;
newElem->next = cur;
prev->next = newElem;
}
} else {
first = new Elem(pcb, timeToSleep, 0, 0);
}
}
void SleepList::wakeUp() {
Elem* cur = first;
while (cur != 0 && cur->timeBehind == 0) {
Scheduler::put(cur->pcb);
Elem* old = cur;
cur = cur->next;
delete old;
}
first = cur;
first->timeToSleep = first->timeBehind;
first->timeBehind = 0;
}
|
70734dfa21cd0d59f9fa57f064f062c9c9b540a3
|
e149e4ed7e7634ab0fb1e87c26d1a6bc4fcfe3a1
|
/leetcode_vscode/leetcode_25/leetcode_25.cpp
|
e1ed22dc0407524b9f979c561f52b18d5d6d4f6a
|
[] |
no_license
|
sailor-ux/mycodes
|
9291c78c4af2ffa8a4cd593184837a41b288e1ee
|
92f6b6338376daaec2d35a508845077fdcf4c25c
|
refs/heads/main
| 2023-08-31T13:29:36.675819
| 2023-08-20T16:19:05
| 2023-08-20T16:19:05
| 214,383,672
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,822
|
cpp
|
leetcode_25.cpp
|
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) { // 这里也想到递归
ListNode* dummyHead = new ListNode(-1, head);
int count = 0;
while (head) {
if (++count == k) {
break;
}
head = head->next;
}
if (!head) { // 考虑最后不足k个的情况,head==nullptr或者count<k都说明不足k个
return dummyHead->next;
}
ListNode* nextHead = reverseKGroup(head->next, k);
head->next = nullptr;
ListNode* newHead = reverseList(dummyHead->next);
dummyHead->next->next = nextHead;
return newHead;
}
ListNode* reverseList(ListNode* head) { // 反转链表递归法
if (!head->next) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head; // 反转
head->next = nullptr; // 置空
return newHead;
}
};
int main() {
vector<int> arr{1, 2, 3, 4, 5, 6};
ListNode *head = new ListNode(arr[0]), *dummyHead = new ListNode(-1, head);
for (int i = 1; i < arr.size(); i++) {
head->next = new ListNode(arr[i]);
head = head->next;
}
head = dummyHead->next;
while (head) {
cout << head->val << ' ';
head = head->next;
}
cout << endl;
Solution sol;
head = sol.reverseKGroup(dummyHead->next, 2);
while (head) {
cout << head->val << ' ';
head = head->next;
}
system("pause");
return 0;
}
|
dd4e33c178779af9f49d1edd28d421186d66502b
|
23b3fe726bc41c2af5e38645f39d11ebb8cfb773
|
/ProjectEuler/Problem-29-Distinct-powers.cpp
|
84d7dfda3cafaca5f958506cd277a3621bbfb4b4
|
[] |
no_license
|
vmichal/Competitive
|
f4106deb6a786aa3203841b6f3ac5e5390b3ecf2
|
e357a20c1365176f25343c5f9fd88edc2e1db4e9
|
refs/heads/master
| 2020-12-23T21:02:57.635998
| 2020-08-09T15:52:22
| 2020-08-09T15:52:22
| 237,273,916
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,024
|
cpp
|
Problem-29-Distinct-powers.cpp
|
#include <iostream>
#include "BigInteger.h"
#define MAX 100
int main() {
std::vector<BigInteger*> cisla;
cisla.reserve(10'000);
for (int i = 2; i <= MAX; i++) {
BigInteger *a = new BigInteger(i*i);
for (int j = 2; j < MAX; j++) {
cisla.push_back(a);
a = new BigInteger(*a*i);
}
cisla.push_back(a);
}
std::vector<BigInteger*>::iterator konec = --cisla.end(), nejvetsi, iterator;
while (konec != cisla.begin()) {
for (iterator = nejvetsi = cisla.begin(); iterator <= konec; iterator++)
if (**iterator > **nejvetsi)
nejvetsi = iterator;
if (**konec != **nejvetsi) {
BigInteger *tmp = *konec;
*konec = *nejvetsi;
*nejvetsi = tmp;
}
konec--;
}
uint32_t count = 0;
for (auto iterator = cisla.begin(); iterator != cisla.end(); iterator++) {
count++;
while (iterator < cisla.end() - 1 && **(iterator + 1) == **iterator)
iterator++;
}
for (BigInteger* ref : cisla)
delete ref;
std::cout << count << std::endl;
std::cin.get();
}
|
bb7e4a45f5cfab3e092deb80a653d6416ffedb70
|
c9868cc566f422da064c350288d1070a4a5659b7
|
/c++ part/query.cpp
|
96551a2a41495a7e0067b6e463e39570c829f6e8
|
[] |
no_license
|
Zestinc/Bachelor-Graduate-Project
|
0b70e19f7a4a647b06a34836aea4dfd9c6321d40
|
962f76a39a1fc86c9810fac1b96b6dbd5c9a659c
|
refs/heads/master
| 2021-01-10T14:41:14.568713
| 2016-02-18T09:43:21
| 2016-02-18T09:43:21
| 50,314,756
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,350
|
cpp
|
query.cpp
|
////
//// query.cpp
//// test
////
//// Created by Zestinc on 15/1/4.
//// Copyright (c) 2015年 Zestinc. All rights reserved.
////
//
//#include "query.h"
//#include <stdio.h>
//#include <iostream>
//#include "test/cmysql/mysql.h"
//#include <string>
//using namespace std;
//
////初始化 & 连接MySQL
//MYSQL initsql()
//{
// MYSQL *connection, mysql;
// mysql_init(&mysql);
// connection = mysql_real_connect(&mysql, "localhost:8888", "root", "123456", "go", 0, 0, 0);
// printf((!connection) ? "connect errors\n" : "Connected\n");
// return mysql;
//}
//
////返回某一个查询得到的结果的拼接(即合成到一个字符串里
//)
//string getResult(MYSQL &mysql)
//{
// string re, s, sql;
// MYSQL_RES *result;
// result = mysql_store_result(&mysql);
// if(!result)
// {
// cerr<<"no result"<<endl;
// exit(-1);
// }
// MYSQL_ROW row;
// unsigned int num_fields;
// unsigned int i;
// num_fields = mysql_num_fields(result);
// while ((row = mysql_fetch_row(result)))
// {
// unsigned long *lengths;
// lengths = mysql_fetch_lengths(result);
// for(i = 0; i < num_fields; i++)
// {
// printf("[%.*s]", (int) lengths[i], row[i] ? row[i] : "NULL");
// }
// printf("\n");
// }
//
//
// return re;
//}
|
9580a83d9c81b09f74d78247e38971456a7318bd
|
508f595b141d5dec80da087202f1ccbb0323fec6
|
/libs/util/include/hades/detail/utility.inl
|
93057087dd51c05507f92a52442eceaceee97832
|
[] |
no_license
|
cyanskies/hades
|
7bc44b7bad27be5104c4b79c131535f025c946dd
|
402b93e6694e524b5d3c600ab35470feb4c85e3f
|
refs/heads/master
| 2023-08-31T02:00:40.645910
| 2022-05-25T08:33:25
| 2022-05-25T08:33:25
| 66,844,618
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,916
|
inl
|
utility.inl
|
#include "hades/utility.hpp"
#include <cassert>
#include <functional>
#include <random>
namespace hades
{
template<typename Float,
typename std::enable_if_t<std::is_floating_point_v<Float>, int>>
constexpr Float lerp(Float a, Float b, Float t) noexcept
{
//algorithm recommended for consistancy in P0811R2 : https://wg21.link/p0811r2
if (a <= 0 && b >= 0 ||
a >= 0 && b <= 0)
return t * b + (1.f - t) * a;
if (float_near_equal(t, 1.f)) return b;
const auto x = a + t * (b - a);
return t > 1 == b > a ? std::max(b, x) : std::min(b, x);
}
//based on logic from
//here: http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
template<typename Float, std::enable_if_t<std::is_floating_point_v<Float>, int>>
inline bool float_near_equal(Float a, Float b, int32 ulp) noexcept
{
return std::abs(a - b) <= std::numeric_limits<Float>::epsilon() * std::abs(a + b) * ulp
// unless the result is subnormal
|| std::abs(a - b) < std::numeric_limits<Float>::min();
}
template<typename Float, std::enable_if_t<std::is_floating_point_v<Float>, int>>
bool float_rounded_equal(Float a, Float b, detail::round_nearest_t) noexcept
{
return std::round(a) == std::round(b);
}
template<typename Float, std::enable_if_t<std::is_floating_point_v<Float>, int>>
bool float_rounded_equal(Float a, Float b, detail::round_down_t) noexcept
{
return std::floor(a) == std::floor(b);
}
template<typename Float, std::enable_if_t<std::is_floating_point_v<Float>, int>>
bool float_rounded_equal(Float a, Float b, detail::round_up_t) noexcept
{
return std::ceil(a) == std::ceil(b);
}
template<typename Float, std::enable_if_t<std::is_floating_point_v<Float>, int>>
bool float_rounded_equal(Float a, Float b, detail::round_towards_zero_t) noexcept
{
return std::trunc(a) == std::trunc(b);
}
namespace detail
{
template<typename Integral, typename Float, typename T>
constexpr Integral integral_do_cast(Float f, T) noexcept
{
static_assert(is_round_tag_v<T>);
if constexpr(std::is_same_v<round_nearest_t, T>)
return static_cast<Integral>(std::round(f));
else if constexpr(std::is_same_v<round_down_t, T>)
return static_cast<Integral>(std::floor(f));
else if constexpr (std::is_same_v<round_up_t, T>)
return static_cast<Integral>(std::ceil(f));
else if constexpr (std::is_same_v<round_towards_zero_t, T>)
return static_cast<Integral>(f);
}
}
template<typename Integral, typename Float, typename RoundingTag,
std::enable_if_t<std::is_integral_v<Integral>
&& std::is_arithmetic_v<Float>
&& detail::is_round_tag_v<RoundingTag>, int>>
constexpr Integral integral_cast(Float f, RoundingTag t)
{
if constexpr (std::is_integral_v<Float>)
return integer_cast<Integral>(f);
else
{
if (f > static_cast<Float>(std::numeric_limits<Integral>::max()))
throw overflow_error{ "overflow_error value is larger than target type can hold" };
else if constexpr (std::is_signed_v<Integral>)
{
if (f < static_cast<Float>(std::numeric_limits<Integral>::min()))
throw overflow_error{ "overflow_error value is smaller than target type can hold" };
}
return detail::integral_do_cast<Integral>(f, t);
}
}
template<typename Integral, typename Float, typename RoundingTag,
std::enable_if_t<std::is_integral_v<Integral>
&& std::is_arithmetic_v<Float>
&& detail::is_round_tag_v<RoundingTag>, int>>
constexpr Integral integral_clamp_cast(Float f, RoundingTag t) noexcept
{
if constexpr (std::is_integral_v<Float>)
return integer_clamp_cast<Integral>(f);
else
{
if (f > static_cast<Float>(std::numeric_limits<Integral>::max()))
return std::numeric_limits<Integral>::max();
else if constexpr (std::is_signed_v<Integral>)
{
if (f < static_cast<Float>(std::numeric_limits<Integral>::min()))
return std::numeric_limits<Integral>::min();
}
return detail::integral_do_cast<Integral>(f, t);
}
}
template<typename Float, typename T, std::enable_if_t<std::is_floating_point_v<Float> &&
std::is_arithmetic_v<T>, int>>
constexpr Float float_cast(T t)
{
// handle different float type sizes
if constexpr (std::is_floating_point_v<T> && sizeof(Float) < sizeof(T))
{
if(t > static_cast<T>(std::numeric_limits<Float>::max()))
throw overflow_error{ "overflow_error value is larger than target type can hold" };
else if (t < static_cast<T>(std::numeric_limits<Float>::lower()))
throw overflow_error{ "overflow_error value is smaller than target type can hold" };
}
// all intergrals fit in all floats
return static_cast<Float>(t);
}
template<typename Float, typename T, std::enable_if_t<std::is_floating_point_v<Float> &&
std::is_arithmetic_v<T>, int>>
constexpr Float float_clamp_cast(T t) noexcept
{
// handle different float type sizes
if constexpr (std::is_floating_point_v<T> && sizeof(Float) < sizeof(T))
{
if (t > static_cast<T>(std::numeric_limits<Float>::max()))
return std::numeric_limits<Float>::max();
else if (t < static_cast<T>(std::numeric_limits<Float>::lower()))
return std::numeric_limits<Float>::min();
}
// all intergrals fit in all floats
return static_cast<Float>(t);
}
template<typename T>
constexpr std::make_unsigned_t<T> unsigned_cast(T value)
{
using U = std::make_unsigned_t<T>;
if constexpr (std::is_unsigned_v<T>)
return value;
else if (value >= T{})
return static_cast<U>(value);
else
throw overflow_error{ "overflow_error; tried to cast a negative value to unsigned" };
}
template<typename T>
constexpr std::make_unsigned_t<T> unsigned_clamp_cast(T value) noexcept
{
using U = std::make_unsigned_t<T>;
if constexpr (std::is_unsigned_v<T>)
return value;
else if (value > T{})
return static_cast<U>(value);
else
return U{};
}
template<typename T>
constexpr std::make_signed_t<T> signed_cast(T value)
{
using S = std::make_signed_t<T>;
if constexpr (std::is_signed_v<T>)
return value;
else if (value > static_cast<T>(std::numeric_limits<S>::max()))
throw overflow_error{ "overflow_error; value was too large for signed type" };
else
return static_cast<S>(value);
}
template<typename T>
constexpr std::make_signed_t<T> signed_clamp_cast(T value) noexcept
{
using S = std::make_signed_t<T>;
if constexpr (std::is_signed_v<T>)
return value;
else if (value > static_cast<T>(std::numeric_limits<S>::max()))
return std::numeric_limits<S>::max();
else
return static_cast<S>(value);
}
template<typename T>
constexpr auto sign_swap_cast(T value)
{
if constexpr (std::is_signed_v<T>)
return unsigned_cast(value);
else
return signed_cast(value);
}
template<typename T>
constexpr auto sign_swap_clamp_cast(T value) noexcept
{
if constexpr (std::is_signed_v<T>)
return unsigned_clamp_cast(value);
else
return signed_clamp_cast(value);
}
template<typename T, typename U>
constexpr T size_cast(U i)
{
static_assert(std::is_integral_v<T> && std::is_integral_v<U>,
"size_cast only supports integers");
static_assert(std::is_signed_v<T> == std::is_signed_v<U>,
"size_cast integers must both be signed, or both unsigned");
if constexpr (sizeof(T) >= sizeof(U))
return i;
else
{
//only need to check min value if integer types are signed
if constexpr (std::is_signed_v<T>)
if (i < static_cast<U>(std::numeric_limits<T>::min()))
throw overflow_error{ "overflow_error value is smaller than target type can hold" };
//check max value
if (i > static_cast<U>(std::numeric_limits<T>::max()))
throw overflow_error{ "overflow_error value is larger than target type can hold" };
return static_cast<T>(i);
}
}
template<typename T, typename U>
constexpr T size_clamp_cast(U i) noexcept
{
static_assert(std::is_integral_v<T> && std::is_integral_v<U>,
"size_cast only supports integers");
static_assert(std::is_signed_v<T> == std::is_signed_v<U>,
"size_cast integers must both be signed, or both unsigned");
if constexpr (sizeof(T) >= sizeof(U))
return i;
else
{
//only need to check min value if integer types are signed
if constexpr (std::is_signed_v<T>)
if (i < static_cast<U>(std::numeric_limits<T>::min()))
return std::numeric_limits<T>::min();
//check max value
if (i > static_cast<U>(std::numeric_limits<T>::max()))
return std::numeric_limits<T>::max();
return static_cast<T>(i);
}
}
template<typename T, typename U>
constexpr T integer_cast(U i)
{
static_assert(std::is_integral_v<T> && std::is_integral_v<U>,
"integer_cast only supports integers");
if constexpr (std::is_same_v<T, U>)
return i;
else if constexpr (std::is_signed_v<T> == std::is_signed_v<U>)
return size_cast<T>(i);
else
return size_cast<T>(sign_swap_cast(i));
}
template<typename T, typename U>
constexpr T integer_clamp_cast(U i) noexcept
{
static_assert(std::is_integral_v<T> && std::is_integral_v<U>,
"integer_clamp_cast only supports integers");
if constexpr (std::is_same_v<T, U>)
return i;
else if constexpr (std::is_signed_v<T> == std::is_signed_v<U>)
return size_clamp_cast<T>(i);
else
return size_clamp_cast<T>(sign_swap_clamp_cast(i));
}
namespace detail
{
struct random_data
{
std::random_device rd{};
// TODO: PCG random engine
std::default_random_engine random_generator{ rd() };
};
thread_local extern random_data random_runtime_data;
template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>
T random(T min, T max)
{
std::uniform_int_distribution<T> random{ min, max };
return random(random_runtime_data.random_generator);
}
template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
T random(T min, T max)
{
std::uniform_real_distribution<T> random{ min, max };
return random(random_runtime_data.random_generator);
}
}
template<typename T>
T random(T min, T max)
{
if (min > max)
return detail::random(max, min);
return detail::random(min, max);
}
template<typename Iter>
typename Iter random_element(Iter first, const Iter last)
{
if (first == last)
return first;
const auto dist = std::distance(first, last) - 1;
const auto target = detail::random(decltype(dist){}, dist);
std::advance(first, target);
return first;
}
template<typename Index2D, typename T>
constexpr T to_1d_index(Index2D pos, T array_width)
{
return to_1d_index({ integer_cast<T>(pos.x), integer_cast<T>(pos.y) }, array_width);
}
template<typename T>
constexpr T to_1d_index(std::pair<T, T> index, T w)
{
if constexpr (std::is_signed_v<T>)
{
if (index.first < 0 || index.second < 0)
throw std::invalid_argument{ "cannot caculate 1d index in negative space" };
}
return index.second * w + index.first;
}
template<typename Index2D, typename T>
constexpr Index2D to_2d_index(T i, T w)
{
assert(w != 0);
return Index2D{
i % w,
i / w
};
}
template<typename T>
constexpr std::pair<T, T> to_2d_index(T i, T w)
{
return to_2d_index<std::pair<T, T>>(i, w);
}
template<typename Enum, std::enable_if_t<std::is_enum_v<Enum>, int>>
constexpr std::underlying_type_t<Enum> enum_type(Enum e) noexcept
{
return static_cast<std::underlying_type_t<Enum>>(e);
}
template<typename Enum, std::enable_if_t<std::is_enum_v<Enum>, int>>
constexpr Enum next(Enum e) noexcept
{
return Enum{ enum_type(e) + 1 };
}
inline bool random()
{
return random(0, 1) != 0;
}
template<typename Func>
finally_t<Func> make_finally(Func&& f)
{
static_assert(std::is_nothrow_invocable_v<Func>,
"make_finally only accepts a callable that accepts no arguments and is noexcept");
return finally_t<Func>{std::forward<Func>(f)};
}
template<typename Container>
decltype(auto) remove_duplicates(Container &cont)
{
return remove_duplicates(cont,
std::less<typename Container::value_type>{});
}
template<typename Container, typename Less>
decltype(auto) remove_duplicates(Container &cont, Less less)
{
return remove_duplicates(cont, less,
std::equal_to<typename Container::value_type>{});
}
template<typename Container, typename Less, typename Equal>
decltype(auto) remove_duplicates(Container &cont, Less less, Equal equal)
{
return remove_duplicates(cont, std::begin(cont), std::end(cont), less, equal);
}
template<typename Container, typename Iter>
Iter remove_duplicates(Container &cont, Iter first, Iter last)
{
return remove_duplicates(cont, first, last, std::less<std::iterator_traits<Iter>::value_type>{}, std::equal_to<std::iterator_traits<Iter>::value_type>{});
}
template<typename Container, typename Iter, typename Less, typename Equal>
Iter remove_duplicates(Container &cont, Iter first, Iter last, Less less, Equal equal)
{
std::stable_sort(first, last, less);
const auto last_unique = std::unique(first, last, equal);
return cont.erase(last_unique, last);
}
}
|
5499b62eae5b43978d235d89a2a19dd378066d88
|
261ff029c1355a8a1f74a46f76155bc44ca2f44b
|
/Engine/Resources/Codes/DynamicMesh.cpp
|
9f22221b91049a1a5b7719fcb779a1f0a3ac7fbd
|
[] |
no_license
|
bisily/DirectX3D_Personal_-portfolio
|
39aa054f60228e703a6d942a7df94a9faaa7a00a
|
e06878690793d103273f2b50213a92bdfb923b33
|
refs/heads/master
| 2022-11-26T11:51:29.985373
| 2020-08-04T09:17:09
| 2020-08-04T09:17:09
| 284,932,529
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 7,509
|
cpp
|
DynamicMesh.cpp
|
#include "DynamicMesh.h"
USING(Engine)
Engine::CDynamicMesh::CDynamicMesh(LPDIRECT3DDEVICE9 pGraphicDev)
: Engine::CMesh(pGraphicDev)
{
}
Engine::CDynamicMesh::CDynamicMesh(const CDynamicMesh & rhs)
: Engine::CMesh(rhs)
, m_pRootFrame(rhs.m_pRootFrame)
, m_pLoader(rhs.m_pLoader)
, m_MeshContainerList(rhs.m_MeshContainerList)
, m_vecBoreNames(rhs.m_vecBoreNames)
{
m_pAniCtrl = CAnimationCtrl::Create(*rhs.m_pAniCtrl);
}
Engine::CDynamicMesh::~CDynamicMesh()
{
}
_double CDynamicMesh::Get_Position()
{
return m_pAniCtrl->Get_Position();
}
HRESULT Engine::CDynamicMesh::Ready_Meshes(const _tchar* pFilePath, const _tchar* pFileName)
{
_tchar szFullPath[128] = L"";
lstrcpy(szFullPath, pFilePath);
lstrcat(szFullPath, pFileName);
m_pLoader = CHierachyLoader::Create(m_pGraphicDev, pFilePath);
NULL_CHECK_RETURN(m_pLoader, E_FAIL);
LPD3DXANIMATIONCONTROLLER pAniCtrl = nullptr;
if (FAILED(D3DXLoadMeshHierarchyFromX(szFullPath,
D3DXMESH_MANAGED,
m_pGraphicDev,
m_pLoader,
nullptr,
&m_pRootFrame,
&pAniCtrl)))
{
return E_FAIL;
}
m_pAniCtrl = CAnimationCtrl::Create(pAniCtrl);
NULL_CHECK_RETURN(m_pAniCtrl, E_FAIL);
Engine::Safe_Release(pAniCtrl);
_matrix matTemp;
D3DXMatrixIdentity(&matTemp);
Update_FrameMatrices((D3DXFRAME_DERIVED*)m_pRootFrame, &matTemp);
SetUp_FrameMatrices((D3DXFRAME_DERIVED*)m_pRootFrame);
return S_OK;
}
void Engine::CDynamicMesh::Render_Mesh()
{
for(auto iter : m_MeshContainerList)
{
D3DXMESHCONTAINER_DERIVED* pMeshContainer = (iter);
for (_ulong i = 0; i < pMeshContainer->dwNumBones; ++i)
pMeshContainer->pRenderingMatices[i] =
pMeshContainer->pFrameOffsetMatrix[i] * (*pMeshContainer->ppFrameCombinedMatrix[i]);
void* pSrcVertices = nullptr;
void* pDestVertices = nullptr;
pMeshContainer->pOriMesh->LockVertexBuffer(0, &pSrcVertices);
pMeshContainer->MeshData.pMesh->LockVertexBuffer(0, &pDestVertices);
// 소프트웨어 스키닝을 수행하는 함수(스키닝 뿐만 아니라 애니메이션 변경, 뼈대들과 정점 정보들의 정보 변경을 동시에 수행해주기도 한다)
pMeshContainer->pSkinInfo->UpdateSkinnedMesh(pMeshContainer->pRenderingMatices, // 뼈의 변환 상태
NULL, // 원래로 돌리기 위한 상태 행렬(원래는 1인자의 역 행렬을 구해서 넣어줘야 함, 굳이 안 넣어줘도 됨)
pSrcVertices, // 변하지 않는 원본 메쉬의 정점 정보
pDestVertices); // 변환된 정보를 저장하고 있는 정점 정보
for (_ulong i = 0; i < pMeshContainer->NumMaterials; ++i)
{
m_pGraphicDev->SetTexture(0, pMeshContainer->ppTexture[i]);
pMeshContainer->MeshData.pMesh->DrawSubset(i);
}
pMeshContainer->pOriMesh->UnlockVertexBuffer();
pMeshContainer->MeshData.pMesh->UnlockVertexBuffer();
}
}
void CDynamicMesh::Render_Mesh(LPD3DXEFFECT pEffect)
{
pEffect->AddRef();
auto iter = m_MeshContainerList.begin();
auto iter_end = m_MeshContainerList.end();
for (; iter != iter_end; ++iter)
{
D3DXMESHCONTAINER_DERIVED* pMeshContainer = (*iter);
for (_ulong i = 0; i < pMeshContainer->dwNumBones; ++i)
pMeshContainer->pRenderingMatices[i] =
pMeshContainer->pFrameOffsetMatrix[i] * (*pMeshContainer->ppFrameCombinedMatrix[i]);
void* pSrcVertices = nullptr;
void* pDestVertices = nullptr;
pMeshContainer->pOriMesh->LockVertexBuffer(0, &pSrcVertices);
pMeshContainer->MeshData.pMesh->LockVertexBuffer(0, &pDestVertices);
// 소프트웨어 스키닝을 수행하는 함수(스키닝 뿐만 아니라 애니메이션 변경, 뼈대들과 정점 정보들의 정보 변경을 동시에 수행해주기도 한다)
pMeshContainer->pSkinInfo->UpdateSkinnedMesh(pMeshContainer->pRenderingMatices, // 뼈의 변환 상태
NULL, // 원래로 돌리기 위한 상태 행렬(원래는 1인자의 역 행렬을 구해서 넣어줘야 함, 굳이 안 넣어줘도 됨)
pSrcVertices, // 변하지 않는 원본 메쉬의 정점 정보
pDestVertices); // 변환된 정보를 저장하고 있는 정점 정보
for (_ulong i = 0; i < pMeshContainer->NumMaterials; ++i)
{
pEffect->SetTexture("g_BaseTexture", pMeshContainer->ppTexture[i]);
pEffect->CommitChanges();
pMeshContainer->MeshData.pMesh->DrawSubset(i);
}
pMeshContainer->pOriMesh->UnlockVertexBuffer();
pMeshContainer->MeshData.pMesh->UnlockVertexBuffer();
}
Engine::Safe_Release(pEffect);
}
void CDynamicMesh::Set_AnimationSet(const _uint & iIdx)
{
m_pAniCtrl->Set_AnimationSet(iIdx);
}
void CDynamicMesh::Play_AnimationSet(const _float & fTimeDelta)
{
m_pAniCtrl->Play_AnimationSet(fTimeDelta);
_matrix matTemp;
D3DXMatrixIdentity(&matTemp);
Update_FrameMatrices((D3DXFRAME_DERIVED*)m_pRootFrame, &matTemp);
}
_double CDynamicMesh::Get_Period()
{
return m_pAniCtrl->Get_Period();
}
_double CDynamicMesh::Get_AccTime()
{
return m_pAniCtrl->Get_AccTime();
}
_double CDynamicMesh::Get_Percent()
{
return m_pAniCtrl->Get_Percent();
}
void Engine::CDynamicMesh::Update_FrameMatrices(D3DXFRAME_DERIVED * pFrame, const _matrix * pParentMatrix)
{
NULL_CHECK(pFrame);
pFrame->CombinedTransformationMatrix = pFrame->TransformationMatrix * (*pParentMatrix);
// 형제 뼈가 있다면
if (nullptr != pFrame->pFrameSibling)
{
Update_FrameMatrices(((D3DXFRAME_DERIVED*)pFrame->pFrameSibling), pParentMatrix);
}
// 자식의 뼈가 있다면
if (nullptr != pFrame->pFrameFirstChild)
{
Update_FrameMatrices(((D3DXFRAME_DERIVED*)pFrame->pFrameFirstChild), &pFrame->CombinedTransformationMatrix);
}
}
void Engine::CDynamicMesh::SetUp_FrameMatrices(D3DXFRAME_DERIVED * pFrame)
{
if (nullptr != pFrame->pMeshContainer)
{
D3DXMESHCONTAINER_DERIVED* pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)pFrame->pMeshContainer;
for (_ulong i = 0; i < pMeshContainer->dwNumBones; ++i)
{
const char* pBoneName = pMeshContainer->pSkinInfo->GetBoneName(i);
D3DXFRAME_DERIVED* pFrame = (D3DXFRAME_DERIVED*)D3DXFrameFind(m_pRootFrame, pBoneName);
pMeshContainer->ppFrameCombinedMatrix[i] = &pFrame->CombinedTransformationMatrix;
// const char* -> wstring
wstring strTemp;
wchar_t* pszTmp = NULL; // 와이드만자열로 변경해서 저장될 주소
int iLen = strlen(pFrame->Name) + 1;
pszTmp = new wchar_t[iLen];
MultiByteToWideChar(CP_ACP, 0, pFrame->Name, -1, pszTmp, iLen);
strTemp = pszTmp;
delete[] pszTmp;
m_vecBoreNames.push_back(strTemp);
}
m_MeshContainerList.push_back(pMeshContainer);
}
if (nullptr != pFrame->pFrameSibling)
SetUp_FrameMatrices((D3DXFRAME_DERIVED*)pFrame->pFrameSibling);
if (nullptr != pFrame->pFrameFirstChild)
SetUp_FrameMatrices((D3DXFRAME_DERIVED*)pFrame->pFrameFirstChild);
}
CDynamicMesh * Engine::CDynamicMesh::Create(LPDIRECT3DDEVICE9 pGraphicDev, wstring pFilePath, wstring pFileName)
{
CDynamicMesh* pInstance = new CDynamicMesh(pGraphicDev);
const _tchar* szFilePath = (LPCTSTR)pFilePath.c_str();
const _tchar* szFileName = (LPCTSTR)pFileName.c_str();
if (FAILED(pInstance->Ready_Meshes(szFilePath, szFileName)))
{
ERR_BOX(L"Dynamic Mesh Create Failed");
Engine::Safe_Release(pInstance);
}
return pInstance;
}
CResources * Engine::CDynamicMesh::Clone()
{
return new CDynamicMesh(*this);
}
void Engine::CDynamicMesh::Free()
{
Engine::CMesh::Free();
Engine::Safe_Release(m_pAniCtrl);
if (false == m_bClone)
{
m_pLoader->DestroyFrame(m_pRootFrame);
Engine::Safe_Release(m_pLoader);
}
m_MeshContainerList.clear();
}
|
f59c11a142dc4b5fc60c1c8cf1ae660537fe5c39
|
f1f40e4ee90cdb01ae22b8597dd8da40b8705fd2
|
/LIB_SENSORS/BMP180I2CDigitalSensor.h
|
cbeee9c56d3482a350bbb78af8d7d458faf15046
|
[] |
no_license
|
CaptFrank/sensor-node
|
fe7db954756205805357f4526b3d243bee4ef750
|
f6a8f536bb7b79204c22c7facd6490e133713a23
|
refs/heads/master
| 2020-05-04T16:00:55.585620
| 2014-10-22T22:49:36
| 2014-10-22T22:49:36
| 32,990,730
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,298
|
h
|
BMP180I2CDigitalSensor.h
|
/*
* BMP180I2CDigitalSensor.h
*
* Created on: Jun 20, 2014
* Author: Administrator
*/
#ifndef BMP180I2CDIGITALSENSOR_H_
#define BMP180I2CDIGITALSENSOR_H_
// -------------------------------------------------------------------------------
// Includes
// Standards
extern "C" {
#include <math.h>
}
// The base I2C Device
#include "I2CBaseDriver.h"
// -------------------------------------------------------------------------------
// Defines
/**
* These are the registers that are used within the context of this class.
*/
enum BMP180_registers_t {
// Address
BMP180_I2CADDR = 0x77, //!< BMP180_I2CADDR
// Registers
BMP180_REG_CONTROL = 0xF4, //!< BMP180_REG_CONTROL
BMP180_REG_RESULT = 0xF6 //!< BMP180_REG_RESULT
};
/**
* These are the various commands that are possible.
*/
enum BMP180_commands_t {
// Commands
BMP180_COMMAND_TEMPERATURE = 0x2E, //!< BMP180_COMMAND_TEMPERATURE
BMP180_COMMAND_PRESSURE0 = 0x34, //!< BMP180_COMMAND_PRESSURE0
BMP180_COMMAND_PRESSURE1 = 0x74, //!< BMP180_COMMAND_PRESSURE1
BMP180_COMMAND_PRESSURE2 = 0xB4, //!< BMP180_COMMAND_PRESSURE2
BMP180_COMMAND_PRESSURE3 = 0xF4 //!< BMP180_COMMAND_PRESSURE3
};
/**
* BMP180 Internals - Monitoring
*/
struct BMP180_driver_context_t{
// Measurments
unsigned int pressure;
unsigned int pressure_baseline;
unsigned int altitude;
unsigned int sea_level;
unsigned int temperature;
};
/**
* The BMP180 sensor data struct
*/
struct BMP180_measurments_t{
unsigned int pressure;
unsigned int pressure_baseline;
unsigned int altitude;
unsigned int sea_level;
unsigned int temperature;
};
// -------------------------------------------------------------------------------
// Main code
/**
* This is the BMP180 sensor driver and handler. We use this to access the data
* registers from the I2C device. We also use it to control the device and its
* applications. This class extends the @see I2C_Base_Driver
*/
class BMP180_I2C_Digital_Sensor : public I2C_Base_Driver {
// Public Context
public:
// -----------------------------------------
// Setup methods
/**
* This is the default constructor for the class.
*
* @param context - the sys tem context
* @param master_address - the master address
* @param device_map - the device map
* @param device_address - the device address
*/
BMP180_I2C_Digital_Sensor(System_Context* context, I2C_address master_address,
I2C_address device_address = BMP180_I2CADDR);
/**
* This is the default begin method for the class. it returns the status
* of hte initialization.
*
* @return success - the success of the steup method
*/
bool begin();
/**
* The default run method
*/
static void run(void* object_pointer, void* _data){
// Convert our pointer
BMP180_I2C_Digital_Sensor* ptr = (BMP180_I2C_Digital_Sensor*)object_pointer;
BMP180_measurments_t* data = (BMP180_measurments_t*) _data;
// Get the data
// Temperature
char delay = ptr->start_temperature();
MAP_UtilsDelay(delay *10);
ptr->_measurements.temperature = (unsigned int)(ptr->get_temperature()*10);
// Pressure
delay = ptr->start_pressure(3);
MAP_UtilsDelay(delay *10);
ptr->_measurements.pressure = (unsigned int)(ptr->get_pressure()*10);
// Altitude and sea level
ptr->_measurements.altitude = (unsigned int)(ptr->altitude(ptr->_measurements.pressure,
ptr->_measurements.pressure_baseline)*10);
ptr->_measurements.sea_level = (unsigned int)(ptr->sea_level(ptr->_measurements.pressure,
ptr->_measurements.altitude)*10);
// Memcopy the data
memcpy(data, &ptr->_measurements, sizeof(ptr->_measurements));
}
// -----------------------------------------
// Temperature methods
/**
* This starts the temperature measurments. It returns the number of
* ms to wait.
*
* @return ms - the ms to wait
*/
char start_temperature(void);
/**
* This gets the temperature measurment. Returns 0 if the measurment has
* failed.
*
* @return results - the measured value
*/
double get_temperature();
// -----------------------------------------
// Pressure methods
/**
* This starts the pressure measurements.
*
* @param oversampling - the oversampling setting
* @return delay - the delay
*/
char start_pressure(char oversampling);
/**
* This gets the pressure (mbar) value given the temperature value
*
* @return pressure - the calculated pressure value
*/
double get_pressure();
// -----------------------------------------
// Calculations methods
/**
* This converts the absolute pressure to sea level pressure.
*
* @param pressure - pressure value
* @param altitude - altitude value
*
* @return sea-level pressure - the sea-level pressure
*/
double sea_level(double pressure, double altitude);
/**
* This converts the pressure measurements to an altitude.
*
* @param pressure - the calculated pressure
* @param initial_pressure - the initial pressure
* @return altitude - the calculated altitude (m)
*/
double altitude(double pressure, double initial_pressure);
// Private Context
private:
//! The device address
I2C_address _device_address;
/**
* This is the read integer method.
*
* @param register - the register to read
* @return register - the register value
*/
int _read_int(int reg);
/**
* This is the write integrer method.
*
* @param reg - the register to write to
* @param value - the value to write
*/
void _write_int(int reg, int value);
//! Internal register values
int AC1, AC2, AC3, VB1, VB2, MB, MC, MD;
unsigned int AC4, AC5, AC6;
double c5, c6, mc, md, x0, x1, x2, y0, y1, y2, p0, p1, p2;
//! The internal measurements
BMP180_measurments_t _measurements;
};
#endif /* BMP180I2CDIGITALSENSOR_H_ */
|
1b659a319bc60d4e0d7628df0d8e466161e6d213
|
bfa3b192288ceed44ed30792d8857c3c1d72b4b2
|
/Temp/CyberLink4CC/include/cybergarage/soap/SOAPRequest.h
|
b8a97a5ac9eebf011a2b9f342df83ac3c4a95f66
|
[
"BSD-3-Clause"
] |
permissive
|
Crawping/fishjam-template-library
|
a886ac50f807c4386ce37a89563b8da23024220f
|
46b4b3048a38034772d7c8a654d372907d7e024d
|
refs/heads/master
| 2020-12-24T09:44:22.596675
| 2015-03-18T10:50:43
| 2015-03-18T10:50:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,549
|
h
|
SOAPRequest.h
|
/******************************************************************
*
* CyberSOAP for C++
*
* Copyright (C) Satoshi Konno 2002-2003
*
* File: SOAPRequest.h
*
* Revision;
*
* 05/21/03
* - first revision
*
******************************************************************/
#ifndef _CSOAP_SOAPREQUEST_H_
#define _CSOAP_SOAPREQUEST_H_
#include <uhttp/http/HTTPRequest.h>
#include <uhttp/http/HTTPResponse.h>
#include <uhttp/http/CHTTP.h>
#include <cybergarage/soap/SOAP.h>
#include <cybergarage/soap/SOAPResponse.h>
#include <cybergarage/xml/Node.h>
namespace CyberSOAP {
const char SOAPACTION[] = "SOAPACTION";
class SOAPRequest : public uHTTP::HTTPRequest {
CyberXML::Node *rootNode;
SOAPResponse soapRes;
////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////
public:
SOAPRequest();
SOAPRequest(uHTTP::HTTPRequest *httpReq);
~SOAPRequest();
////////////////////////////////////////////////
// SOAPACTION
////////////////////////////////////////////////
public:
void setSOAPAction(const std::string &action) {
setStringHeader(SOAPACTION, action);
}
const char *getSOAPAction(std::string &buf) {
return getStringHeaderValue(SOAPACTION, buf);
}
bool isSOAPAction(const std::string &value);
////////////////////////////////////////////////
// Header
////////////////////////////////////////////////
public:
const char *getHeader(std::string &buf) {
return SOAP::GetHeader(getContent(), buf);
}
////////////////////////////////////////////////
// Encoding
////////////////////////////////////////////////
public:
const char *getEncording(std::string &buf) {
return SOAP::GetEncording(getContent(), buf);
}
bool isEncording(const std::string &encType) {
return SOAP::IsEncording(getContent(), encType);
}
////////////////////////////////////////////////
// post
////////////////////////////////////////////////
private:
CyberXML::Node *parseMessage(const std::string &content, size_t contentLen);
public:
SOAPResponse *postMessage(const std::string &host, int port, SOAPResponse *soapRes);
SOAPResponse *postMessage(const std::string &host, int port) {
return postMessage(host, port, &soapRes);
}
////////////////////////////////////////////////
// Node
////////////////////////////////////////////////
private:
void setRootNode(CyberXML::Node *node) {
rootNode = node;
}
CyberXML::Node *getRootNode();
////////////////////////////////////////////////
// XML
////////////////////////////////////////////////
public:
void setEnvelopeNode(CyberXML::Node *node) {
setRootNode(node);
}
CyberXML::Node *getEnvelopeNode() {
return getRootNode();
}
CyberXML::Node *getBodyNode() {
CyberXML::Node *envNode = getEnvelopeNode();
if (envNode == NULL)
return NULL;
if (envNode->hasNodes() == false)
return NULL;
return envNode->getNode(0);
}
////////////////////////////////////////////////
// SOAP UPnP
////////////////////////////////////////////////
public:
void setContent(CyberXML::Node *node);
////////////////////////////////////////////////
// print
////////////////////////////////////////////////
/*
public void print() {
System.out.println(toString());
if (hasContent() == true)
return;
Node rootElem = getRootNode();
if (rootElem == null)
return;
System.out.println(rootElem.toString());
}
*/
};
}
#endif
|
06bcfc9ff14627e7ad0a9ad9326a2e4d6f770c82
|
3466c2193223e00505d7fefaeb0dd51424017a63
|
/chapter-l/rand.cpp
|
fa56ef8144679c9c702e1a54261f3b8e059530c2
|
[] |
no_license
|
ohduran/reviewcpp
|
6c7a9a9cb131eec192f4e9359398dc42faa8f14f
|
30018d98cd0789791b829c48ff908ccaadfece9b
|
refs/heads/master
| 2023-01-19T00:25:38.347885
| 2020-11-09T06:55:18
| 2020-11-09T06:55:18
| 301,610,156
| 0
| 0
| null | 2020-12-11T11:28:00
| 2020-10-06T04:07:46
|
C++
|
UTF-8
|
C++
| false
| false
| 597
|
cpp
|
rand.cpp
|
#include <iostream>
#include <cstdlib> // for std::rand and std::srand
#include <ctime> // for std::time
int getRandomNumber(int min, int max)
{
static const double fraction = 1.0 / (RAND_MAX + 1.0); // so that rand * fraction in [0, 1)
return min + static_cast<int>((max - min + 1) * (std::rand() * fraction));
}
int main()
{
unsigned int clock = std::time(nullptr);
std::srand(clock);
std::rand();
for (int i = 1; i <= 100; i++)
{
std::cout << getRandomNumber(1, 6) << '\t';
if (i % 5 == 0)
std::cout << "\n";
}
return 0;
}
|
c6ef58c6b9e36041ce78d0e94b370b6c119842ff
|
7895353724d6bbc57e45eec7aa0db3d4220f84ca
|
/src/网络编程/multi_process/client.cpp
|
f416ed6a90485b63d7413d8a07511b558d647a75
|
[] |
no_license
|
averyboy/skills
|
e8309ae835ad48d9f17c13b63047141589617f51
|
a825feee50bc2b6faafe4580d543d8bb619a94d3
|
refs/heads/master
| 2020-04-23T16:04:41.494831
| 2019-03-27T13:45:29
| 2019-03-27T13:45:29
| 171,285,846
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 942
|
cpp
|
client.cpp
|
#include<bits/stdc++.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/time.h>
#include<unistd.h>
const int TCP_PORT=6666;
const int BUF_SIZE=1024;
using namespace std;
int main()
{
int sockfd=socket(AF_INET,SOCK_STREAM,0);
sockaddr_in cliaddr;
memset(&cliaddr,0,sizeof(cliaddr));
cliaddr.sin_family=AF_INET;
cliaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
cliaddr.sin_port=htons(TCP_PORT);
socklen_t len=sizeof(cliaddr);
if(connect(sockfd,(sockaddr*)&cliaddr,len)<0)
{
cout<<"connnect failed!"<<endl;
exit(0);
}
char s[]="over";
while(true)
{
char buf[BUF_SIZE];
cin>>buf;
int sz=send(sockfd,buf,strlen(buf)+1,0);
cout<<"sz:"<<sz<<endl;
if(strcmp(buf,s)==0)
{
cout<<"over!"<<endl;
break;
}
}
close(sockfd);
return 0;
}
|
efb2372d9bf7a6e298fa275a9f977b4ebfa6e54a
|
4b1808f0e6fa6d19d3050e53f2960c28cf71e092
|
/main_window.cpp
|
4b9de18eb4d039e09dbcd923f40ff7f1469a9cec
|
[] |
no_license
|
zhanghai/optical-system-qt
|
8feb1ea56bd6c0e8062b4aea77215161080ed40b
|
fd7cf6fc1a849aced4e1619930e9fb3e3f9276cd
|
refs/heads/master
| 2021-06-21T21:48:20.266329
| 2017-07-12T06:00:21
| 2017-07-12T06:34:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,324
|
cpp
|
main_window.cpp
|
/*
* Copyright (c) 2017 Zhang Hai <Dreaming.in.Code.ZH@Gmail.com>
* All Rights Reserved.
*/
#include <QtWidgets/QMessageBox>
#include "main_window.h"
#include "ui_main_window.h"
#include "core.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
on_infiniteObjectDistanceCheck_stateChanged(
ui->infiniteObjectDistanceCheck->checkState());
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::on_infiniteObjectDistanceCheck_stateChanged(int state) {
bool isInfinite = isObjectDistanceInfinite();
ui->fieldAngleSpin->setEnabled(isInfinite);
ui->objectDistanceSpin->setEnabled(!isInfinite);
ui->objectHeightSpin->setEnabled(!isInfinite);
}
void MainWindow::on_computeButton_clicked() {
bool isInfinite = isObjectDistanceInfinite();
char *error = core(isInfinite ? 1 : 0, ui->fieldAngleSpin->value(),
ui->objectDistanceSpin->value(), ui->objectHeightSpin->value());
if (error == NULL) {
QMessageBox::information(this, windowTitle(), "计算成功");
} else {
QMessageBox::critical(this, windowTitle(), error);
}
}
bool MainWindow::isObjectDistanceInfinite() {
return ui->infiniteObjectDistanceCheck->checkState()
!= Qt::CheckState::Unchecked;
}
|
bfc155acc1ded93e330878e5e3d4b62e54dce8f0
|
ae43081be77fc0cd94a151f28f0107298014ce76
|
/Classes/Weapon.h
|
03e915a7a72233ed03029c5039dcbe1a961333e7
|
[] |
no_license
|
Stals/RotateGame
|
aa092f61528ff5e59876a9699f92b85686dd4129
|
c74b19bc17b8a58b6452b197fcb99744ecd4b1aa
|
refs/heads/master
| 2020-04-15T02:18:55.499091
| 2013-08-19T19:24:54
| 2013-08-19T19:24:54
| 10,866,926
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 1,712
|
h
|
Weapon.h
|
#pragma once
#include "AppMacros.h"
#include "../external/Box2D/Box2D.h"
#include "EntityType.h"
class GameLayer;
// Отвечает за отправление пули в определенную точку с определенной скоростью
// Note: пока будет тупо прозрачным, но в теории у него могут быть анимации при выстреле и тд
class Weapon : public cocos2d::CCSprite
{
public:
// TODO возможно gamelayer нужно для того чтобы добавить пулю на него.
// Либо было бы круто если бы можно было для расчетов тупо конвернуть её положение toWorld чтобы указать где она длля box2d
// Просто тогда я мог бы крутить корабль с оружиями одновременно крутя и лазер
// а внутри update лазера постоянно менять его положения и засекать пересечения с противником
// cooldown - время в секундах через которое можно стрелять
Weapon(b2World *world, GameLayer *gameLayer, float cooldown);
// Раз в какой промежуток может стрелять
float getCooldown();
// выстрелит в том направлении
// это точка на GameLayer
void shoot(cocos2d::CCPoint p);
void setObjectType(EntityType type);
private:
b2World *world;
GameLayer *gameLayer;
float cooldown;
EntityType type;
// returns angle in degrees
float getAngle(cocos2d::CCPoint p1, cocos2d::CCPoint p2);
};
|
1e7decbdbeea288648500d67e8ad66d7ad59814e
|
51be8db88a49f7bebeefddf431faff6048ac4f37
|
/xpcc/src/xpcc/architecture/platform/avr/atxmega/spi/spi_f.hpp
|
0b2bedbbfae7b0da34b59a44946731ad3d3ce8aa
|
[
"MIT"
] |
permissive
|
jrahlf/3D-Non-Contact-Laser-Profilometer
|
0a2cee1089efdcba780f7b8d79ba41196aa22291
|
912eb8890442f897c951594c79a8a594096bc119
|
refs/heads/master
| 2016-08-04T23:07:48.199953
| 2014-07-13T07:09:31
| 2014-07-13T07:09:31
| 17,915,736
| 6
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,529
|
hpp
|
spi_f.hpp
|
// coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2011, Roboterclub Aachen e.V.
* 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 Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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.
*/
// ----------------------------------------------------------------------------
/*
* WARNING: This file is generated automatically, do not edit!
* Please modify the corresponding *.in file instead and rebuild this file.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC_ATXMEGA__SPI_F_HPP
#define XPCC_ATXMEGA__SPI_F_HPP
#include <stdint.h>
#include <avr/io.h>
#include "spi.hpp"
#include <xpcc/driver/connectivity/spi/spi_master.hpp>
#include <xpcc/architecture/utils.hpp>
namespace xpcc
{
namespace atxmega
{
#if defined(SPIF) || defined(__DOXYGEN__)
/**
* \brief SPI Master for Port F
*
* This module only supports DMA read transfers in slave mode, however
* slave mode is not implemented here.
*
* \author Niklas hauser
* \ingroup atxmega_spi
*/
class SpiMasterF : public SpiMaster
{
public:
static void
initialize(spi::Prescaler prescaler=spi::PRESCALER_16,
spi::Mode mode=spi::MODE_0);
inline static void
setDataOrder(bool lsbFirst=true)
{
SPIF_CTRL = (SPIF_CTRL & ~SPI_DORD_bm) | (lsbFirst ? SPI_DORD_bm : 0);
}
static uint8_t
write(uint8_t data);
static bool
setBuffer(uint16_t length,
uint8_t* transmit=0, uint8_t* receive=0,
BufferIncrease bufferIncrease=BUFFER_INCR_BOTH);
static bool
transfer(TransferOptions options=TRANSFER_SEND_BUFFER_SAVE_RECEIVE);
static ALWAYS_INLINE bool
transferSync(TransferOptions options=TRANSFER_SEND_BUFFER_SAVE_RECEIVE);
static bool
isFinished();
inline static SPI_t&
getModuleBase()
{
return SPIF;
}
};
#endif // SPIF
#if defined(USARTF0) || defined(__DOXYGEN__)
/**
* \brief UART0 in SPI master mode
*
* The USART pins are mapped like this MOSI=>TXO, MISO=>RXI, SCK=>XCK.
* Be aware that this module has no SS pin, so no slave mode is possible.
*
* This module supports DMA transfers between memory (SRAM) and DATA
* register by defining which DMA channel to use for write/read.
* (SPI0_TX_DMA_CHANNEL, SPI0_RX_DMA_CHANNEL)
* In typical use, the DMA channels gets configured once and then several
* transfers get triggered, without CPU interference.
*
* \author Niklas Hauser
* \ingroup atxmega_spi
*/
class UartSpiMasterF0 : public SpiMaster
{
public:
/**
* Sets pins and calculates the bsel value of the UART module.
* The parameter has to be constant at compile time, so that
* the compiler can do the calculation, and not the uC.
* The DMA channel is configured with a Burst Length of one byte,
* reloading of source address after block transfer completion,
* incr./decr. of source address after each byte transfer,
* no reloading of fixed destination address (=UART DATA register).
*
* \warning The bitrate must be less than half F_CPU.
* \param bitrate SPI frequency in Hz
*/
static void
initialize(uint32_t const bitrate=2000000);
static uint8_t
write(uint8_t data);
static bool
setBuffer(uint16_t length,
uint8_t* transmit=0, uint8_t* receive=0,
BufferIncrease bufferIncrease=BUFFER_INCR_BOTH);
static bool
transfer(TransferOptions options=TRANSFER_SEND_BUFFER_SAVE_RECEIVE);
static bool
transferSync(TransferOptions options=TRANSFER_SEND_BUFFER_SAVE_RECEIVE);
static bool
isFinished();
inline static USART_t&
getModuleBase()
{
return USARTF0;
}
inline static void
setDataOrder(bool lsbFirst=true)
{
USARTF0_CTRLC = (USARTF0_CTRLC & ~USART_CHSIZE2_bm) | (lsbFirst ? USART_CHSIZE2_bm : 0);
}
private:
static bool
isBusy();
};
#endif // USARTF0
#if defined(USARTF1) || defined(__DOXYGEN__)
/**
* \brief UART1 in SPI master mode
*
* The USART pins are mapped like this MOSI=>TXO, MISO=>RXI, SCK=>XCK.
* Be aware that this module has no SS pin, so no slave mode is possible.
*
* This module supports DMA transfers between memory (SRAM) and DATA
* register by defining which DMA channel to use for write/read.
* (SPI1_TX_DMA_CHANNEL, SPI1_RX_DMA_CHANNEL)
* In typical use, the DMA channels gets configured once and then several
* transfers get triggered, without CPU interference.
*
* \author Niklas Hauser
* \ingroup atxmega_spi
*/
class UartSpiMasterF1 : public SpiMaster
{
public:
/**
* Sets pins and calculates the bsel value of the UART module.
* The parameter has to be constant at compile time, so that
* the compiler can do the calculation, and not the uC.
* The DMA channel is configured with a Burst Length of one byte,
* reloading of source address after block transfer completion,
* incr./decr. of source address after each byte transfer,
* no reloading of fixed destination address (=UART DATA register).
*
* \warning The bitrate must be less than half F_CPU.
* \param bitrate SPI frequency in Hz
*/
static void
initialize(uint32_t const bitrate=2000000);
static uint8_t
write(uint8_t data);
static bool
setBuffer(uint16_t length,
uint8_t* transmit=0, uint8_t* receive=0,
BufferIncrease bufferIncrease=BUFFER_INCR_BOTH);
static bool
transfer(TransferOptions options=TRANSFER_SEND_BUFFER_SAVE_RECEIVE);
static bool
transferSync(TransferOptions options=TRANSFER_SEND_BUFFER_SAVE_RECEIVE);
static bool
isFinished();
inline static USART_t&
getModuleBase()
{
return USARTF1;
}
inline static void
setDataOrder(bool lsbFirst=true)
{
USARTF1_CTRLC = (USARTF1_CTRLC & ~USART_CHSIZE2_bm) | (lsbFirst ? USART_CHSIZE2_bm : 0);
}
private:
static bool
isBusy();
};
#endif // USARTF1
}
}
#endif // XPCC_ATXMEGA__SPI_F_HPP
|
984dac7c52c23724d60a0dda965b81aa4aba7b66
|
4b2741a424993dd2fdc4169995e64c9981246c77
|
/C++/2_AddTwoNumbers.cpp
|
381803e0763fa1828ab90122c8bafaae51dfb9b3
|
[] |
no_license
|
UrMagicIsMine/LeetCode-Sol
|
6828507e733e1267369ba1b484dc4ef1b4c193ce
|
b5fe858adfd22d0084975a74a7b4f39c4e5b7d3d
|
refs/heads/master
| 2021-04-30T14:14:26.361993
| 2020-09-20T23:47:44
| 2020-09-20T23:47:44
| 121,192,645
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,452
|
cpp
|
2_AddTwoNumbers.cpp
|
/* You are given two non-empty linked lists representing two non-negative integers.
* The digits are stored in reverse order and each of their nodes contain a single
* digit. Add the two numbers and return it as a linked list.
*
* You may assume the two numbers do not contain any leading zero, except the number
* 0 itself.
*
* Example
*
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
* Explanation: 342 + 465 = 807.
*/
#include <vector>
#include <cassert>
using namespace std;
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode * pNode = &dummy;
int carry = 0;
while (l1 || l2 || carry) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
carry = sum > 9 ? 1 : 0;
pNode->next = new ListNode(sum % 10);
l1 = l1 ? l1->next : nullptr;
l2 = l2 ? l2->next : nullptr;
pNode = pNode->next;
}
return dummy.next;
}
int main()
{
vector<ListNode> nums1 = { 2, 7, 3, 9 };
vector<ListNode> nums2 = { 1, 1, 1, 1 };
vector<int> ans = { 3,8,4,0,1 };
for (int i = 0; i < (int)nums1.size() - 1; i++) {
nums1[i].next = &nums1[i + 1];
nums2[i].next = &nums2[i + 1];
}
ListNode* pNode = addTwoNumbers(&nums1[0], &nums2[0]);
vector<int> resl;
while (pNode) {
resl.push_back(pNode->val);
pNode = pNode->next;
}
assert(resl == ans);
return 0;
}
|
742c163fcc22c295a0852c73a18fbeb03b5f1a04
|
f54f816c39b45c5d925352b5d50dd81990b4ad0e
|
/include/model/equip/Weapon.h
|
f5d7b4d7f3e4aea9223795931e6454ed93b099ca
|
[] |
no_license
|
mdportnov/DungeonGame
|
f5d7f00f37726076f49ca4424e30fc8f3d7c767e
|
1068771891fbef2b3ff956c4c4db28e308396d16
|
refs/heads/master
| 2023-04-13T17:40:43.476762
| 2021-04-11T13:31:37
| 2021-04-11T13:31:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 478
|
h
|
Weapon.h
|
#pragma once
#include <include/model/Item.h>
/**
* Класс оружия
*/
class Weapon : public Item {
public:
Weapon(Level &level, string &fileName, string &name, string &type, string &subType,
float x, float y, float w, float h, int layer, int state, float damage);
/**
* Вычисляет урон
*/
float calculateDamage() const;
void draw(RenderWindow &window) override;
virtual ~Weapon();
private:
float damage;
};
|
dfcb51bea68a64896785bb2e3b4faf69ac520721
|
39bcafc5f6b1672f31f0f6ea9c8d6047ee432950
|
/src/planner/logical_operator.cpp
|
75501f7156a4da42b41ee5a1a00ca77705f9a06c
|
[
"MIT"
] |
permissive
|
duckdb/duckdb
|
315270af6b198d26eb41a20fc7a0eda04aeef294
|
f89ccfe0ec01eb613af9c8ac7c264a5ef86d7c3a
|
refs/heads/main
| 2023-09-05T08:14:21.278345
| 2023-09-05T07:28:59
| 2023-09-05T07:28:59
| 138,754,790
| 8,964
| 986
|
MIT
| 2023-09-14T18:42:49
| 2018-06-26T15:04:45
|
C++
|
UTF-8
|
C++
| false
| false
| 13,707
|
cpp
|
logical_operator.cpp
|
#include "duckdb/planner/logical_operator.hpp"
#include "duckdb/common/field_writer.hpp"
#include "duckdb/common/printer.hpp"
#include "duckdb/common/serializer/buffered_deserializer.hpp"
#include "duckdb/common/string_util.hpp"
#include "duckdb/common/tree_renderer.hpp"
#include "duckdb/parser/parser.hpp"
#include "duckdb/planner/operator/list.hpp"
#include "duckdb/planner/operator/logical_extension_operator.hpp"
#include "duckdb/planner/operator/logical_dependent_join.hpp"
#include "duckdb/common/serializer/binary_serializer.hpp"
#include "duckdb/common/serializer/binary_deserializer.hpp"
namespace duckdb {
const uint64_t PLAN_SERIALIZATION_VERSION = 1;
LogicalOperator::LogicalOperator(LogicalOperatorType type)
: type(type), estimated_cardinality(0), has_estimated_cardinality(false) {
}
LogicalOperator::LogicalOperator(LogicalOperatorType type, vector<unique_ptr<Expression>> expressions)
: type(type), expressions(std::move(expressions)), estimated_cardinality(0), has_estimated_cardinality(false) {
}
LogicalOperator::~LogicalOperator() {
}
vector<ColumnBinding> LogicalOperator::GetColumnBindings() {
return {ColumnBinding(0, 0)};
}
string LogicalOperator::GetName() const {
return LogicalOperatorToString(type);
}
string LogicalOperator::ParamsToString() const {
string result;
for (idx_t i = 0; i < expressions.size(); i++) {
if (i > 0) {
result += "\n";
}
result += expressions[i]->GetName();
}
return result;
}
void LogicalOperator::ResolveOperatorTypes() {
types.clear();
// first resolve child types
for (auto &child : children) {
child->ResolveOperatorTypes();
}
// now resolve the types for this operator
ResolveTypes();
D_ASSERT(types.size() == GetColumnBindings().size());
}
vector<ColumnBinding> LogicalOperator::GenerateColumnBindings(idx_t table_idx, idx_t column_count) {
vector<ColumnBinding> result;
result.reserve(column_count);
for (idx_t i = 0; i < column_count; i++) {
result.emplace_back(table_idx, i);
}
return result;
}
vector<LogicalType> LogicalOperator::MapTypes(const vector<LogicalType> &types, const vector<idx_t> &projection_map) {
if (projection_map.empty()) {
return types;
} else {
vector<LogicalType> result_types;
result_types.reserve(projection_map.size());
for (auto index : projection_map) {
result_types.push_back(types[index]);
}
return result_types;
}
}
vector<ColumnBinding> LogicalOperator::MapBindings(const vector<ColumnBinding> &bindings,
const vector<idx_t> &projection_map) {
if (projection_map.empty()) {
return bindings;
} else {
vector<ColumnBinding> result_bindings;
result_bindings.reserve(projection_map.size());
for (auto index : projection_map) {
D_ASSERT(index < bindings.size());
result_bindings.push_back(bindings[index]);
}
return result_bindings;
}
}
string LogicalOperator::ToString() const {
TreeRenderer renderer;
return renderer.ToString(*this);
}
void LogicalOperator::Verify(ClientContext &context) {
#ifdef DEBUG
// verify expressions
for (idx_t expr_idx = 0; expr_idx < expressions.size(); expr_idx++) {
auto str = expressions[expr_idx]->ToString();
// verify that we can (correctly) copy this expression
auto copy = expressions[expr_idx]->Copy();
auto original_hash = expressions[expr_idx]->Hash();
auto copy_hash = copy->Hash();
// copy should be identical to original
D_ASSERT(expressions[expr_idx]->ToString() == copy->ToString());
D_ASSERT(original_hash == copy_hash);
D_ASSERT(Expression::Equals(expressions[expr_idx], copy));
for (idx_t other_idx = 0; other_idx < expr_idx; other_idx++) {
// comparison with other expressions
auto other_hash = expressions[other_idx]->Hash();
bool expr_equal = Expression::Equals(expressions[expr_idx], expressions[other_idx]);
if (original_hash != other_hash) {
// if the hashes are not equal the expressions should not be equal either
D_ASSERT(!expr_equal);
}
}
D_ASSERT(!str.empty());
// verify that serialization + deserialization round-trips correctly
if (expressions[expr_idx]->HasParameter()) {
continue;
}
BufferedSerializer serializer;
// We are serializing a query plan
try {
expressions[expr_idx]->Serialize(serializer);
} catch (NotImplementedException &ex) {
// ignore for now (FIXME)
continue;
}
auto data = serializer.GetData();
auto deserializer = BufferedContextDeserializer(context, data.data.get(), data.size);
PlanDeserializationState state(context);
auto deserialized_expression = Expression::Deserialize(deserializer, state);
// format (de)serialization of expressions
try {
auto blob = BinarySerializer::Serialize(*expressions[expr_idx], true);
bound_parameter_map_t parameters;
auto result = BinaryDeserializer::Deserialize<Expression>(context, parameters, blob.data(), blob.size());
result->Hash();
} catch (SerializationException &ex) {
// pass
}
// FIXME: expressions might not be equal yet because of statistics propagation
continue;
D_ASSERT(Expression::Equals(expressions[expr_idx], deserialized_expression));
D_ASSERT(expressions[expr_idx]->Hash() == deserialized_expression->Hash());
}
D_ASSERT(!ToString().empty());
for (auto &child : children) {
child->Verify(context);
}
#endif
}
void LogicalOperator::AddChild(unique_ptr<LogicalOperator> child) {
D_ASSERT(child);
children.push_back(std::move(child));
}
idx_t LogicalOperator::EstimateCardinality(ClientContext &context) {
// simple estimator, just take the max of the children
if (has_estimated_cardinality) {
return estimated_cardinality;
}
idx_t max_cardinality = 0;
for (auto &child : children) {
max_cardinality = MaxValue(child->EstimateCardinality(context), max_cardinality);
}
has_estimated_cardinality = true;
estimated_cardinality = max_cardinality;
return estimated_cardinality;
}
void LogicalOperator::Print() {
Printer::Print(ToString());
}
void LogicalOperator::Serialize(Serializer &serializer) const {
FieldWriter writer(serializer);
writer.WriteField<LogicalOperatorType>(type);
writer.WriteSerializableList(children);
Serialize(writer);
writer.Finalize();
}
unique_ptr<LogicalOperator> LogicalOperator::Deserialize(Deserializer &deserializer, PlanDeserializationState &gstate) {
unique_ptr<LogicalOperator> result;
FieldReader reader(deserializer);
auto type = reader.ReadRequired<LogicalOperatorType>();
auto children = reader.ReadRequiredSerializableList<LogicalOperator>(gstate);
LogicalDeserializationState state(gstate, type, children);
switch (type) {
case LogicalOperatorType::LOGICAL_PROJECTION:
result = LogicalProjection::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_FILTER:
result = LogicalFilter::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY:
result = LogicalAggregate::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_WINDOW:
result = LogicalWindow::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_UNNEST:
result = LogicalUnnest::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_LIMIT:
result = LogicalLimit::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_ORDER_BY:
result = LogicalOrder::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_TOP_N:
result = LogicalTopN::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_COPY_TO_FILE:
result = LogicalCopyToFile::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_DISTINCT:
result = LogicalDistinct::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_SAMPLE:
result = LogicalSample::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_LIMIT_PERCENT:
result = LogicalLimitPercent::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_GET:
result = LogicalGet::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_CHUNK_GET:
result = LogicalColumnDataGet::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_DELIM_GET:
result = LogicalDelimGet::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_EXPRESSION_GET:
result = LogicalExpressionGet::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_DUMMY_SCAN:
result = LogicalDummyScan::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_EMPTY_RESULT:
result = LogicalEmptyResult::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_CTE_REF:
result = LogicalCTERef::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_JOIN:
throw InternalException("LogicalJoin deserialize not supported");
case LogicalOperatorType::LOGICAL_ASOF_JOIN:
case LogicalOperatorType::LOGICAL_DELIM_JOIN:
case LogicalOperatorType::LOGICAL_COMPARISON_JOIN:
result = LogicalComparisonJoin::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_ANY_JOIN:
result = LogicalAnyJoin::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_CROSS_PRODUCT:
result = LogicalCrossProduct::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_POSITIONAL_JOIN:
result = LogicalPositionalJoin::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_UNION:
result = LogicalSetOperation::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_EXCEPT:
result = LogicalSetOperation::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_INTERSECT:
result = LogicalSetOperation::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_RECURSIVE_CTE:
result = LogicalRecursiveCTE::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE:
result = LogicalMaterializedCTE::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_INSERT:
result = LogicalInsert::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_DELETE:
result = LogicalDelete::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_UPDATE:
result = LogicalUpdate::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_CREATE_TABLE:
result = LogicalCreateTable::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_CREATE_INDEX:
result = LogicalCreateIndex::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_CREATE_SEQUENCE:
result = LogicalCreate::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_CREATE_VIEW:
result = LogicalCreate::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_CREATE_SCHEMA:
result = LogicalCreate::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_CREATE_MACRO:
result = LogicalCreate::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_PRAGMA:
result = LogicalPragma::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_CREATE_TYPE:
result = LogicalCreate::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_EXPLAIN:
result = LogicalExplain::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_SHOW:
result = LogicalShow::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_PREPARE:
result = LogicalPrepare::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_EXECUTE:
result = LogicalExecute::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_EXPORT:
result = LogicalExport::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_SET:
result = LogicalSet::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_RESET:
result = LogicalReset::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_ALTER:
case LogicalOperatorType::LOGICAL_VACUUM:
case LogicalOperatorType::LOGICAL_LOAD:
case LogicalOperatorType::LOGICAL_ATTACH:
case LogicalOperatorType::LOGICAL_TRANSACTION:
case LogicalOperatorType::LOGICAL_DROP:
case LogicalOperatorType::LOGICAL_DETACH:
result = LogicalSimple::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_EXTENSION_OPERATOR:
result = LogicalExtensionOperator::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_PIVOT:
result = LogicalPivot::Deserialize(state, reader);
break;
case LogicalOperatorType::LOGICAL_DEPENDENT_JOIN:
case LogicalOperatorType::LOGICAL_INVALID:
/* no default here to trigger a warning if we forget to implement deserialize for a new operator */
throw SerializationException("Invalid type for operator deserialization");
}
reader.Finalize();
result->children = std::move(children);
return result;
}
vector<idx_t> LogicalOperator::GetTableIndex() const {
return vector<idx_t> {};
}
unique_ptr<LogicalOperator> LogicalOperator::Copy(ClientContext &context) const {
BufferedSerializer logical_op_serializer;
try {
this->Serialize(logical_op_serializer);
} catch (NotImplementedException &ex) {
throw NotImplementedException("Logical Operator Copy requires the logical operator and all of its children to "
"be serializable: " +
std::string(ex.what()));
}
auto data = logical_op_serializer.GetData();
auto logical_op_deserializer = BufferedContextDeserializer(context, data.data.get(), data.size);
PlanDeserializationState state(context);
auto op_copy = LogicalOperator::Deserialize(logical_op_deserializer, state);
return op_copy;
}
} // namespace duckdb
|
352d2a80d81733ab7a5334f0389f572e5e36b83e
|
951a249ac9ed63674e4aca2775e8105dd0914911
|
/character/ThreeStarXiaoQiao.h
|
f8bd42a14ac648d6db3225f4c5a48a1d8eb4c96a
|
[] |
no_license
|
wwp1122/shuaituzhibing
|
bfb84460bc548e17c738a69c6d98a108312e35df
|
798ccb0af01b06141f88573418cf9969f3d9b448
|
refs/heads/master
| 2022-11-15T06:45:06.038815
| 2022-10-31T02:28:09
| 2022-10-31T02:28:09
| 174,478,077
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 415
|
h
|
ThreeStarXiaoQiao.h
|
#pragma once
#include "character.h"
//10% (one) (spell damage)
class ThreeStarXiaoQiao :public Character
{
public:
ThreeStarXiaoQiao();
~ThreeStarXiaoQiao();
void initValue();
void normalAttack(int& attackP);
void launchSkill(int& strategyP);
void getName(QString& name);
void setBloodVolume(int BloodV);
void getBloodVolume(int& bloodV);
void getDefensivePower(int& defensiveP);
};
|
a7fbae3d3566c723d9b2cf78478830f00045f2a1
|
857938ac2024b1e37f32a6631e85e179ae04b601
|
/src/Persistence_representations/concept/Real_valued_topological_data.h
|
12aceab4dc9de9c629e489fad900e9c53af424a0
|
[
"MIT"
] |
permissive
|
GUDHI/gudhi-devel
|
a2b08232a2ea66047b7a626d85dff0d50decc71c
|
2f76d9416e145282adcd8264438480008bd59f77
|
refs/heads/master
| 2023-08-31T13:44:17.776336
| 2023-08-29T20:20:16
| 2023-08-29T20:20:16
| 174,304,137
| 212
| 69
|
MIT
| 2023-09-14T15:34:48
| 2019-03-07T08:34:04
|
C++
|
UTF-8
|
C++
| false
| false
| 1,307
|
h
|
Real_valued_topological_data.h
|
/* This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
* See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
* Author(s): Pawel Dlotko
*
* Copyright (C) 2016 Inria
*
* Modification(s):
* - YYYY/MM Author: Description of the modification
*/
#ifndef CONCEPT_REAL_VALUED_TOPOLOGICAL_DATA_H_
#define CONCEPT_REAL_VALUED_TOPOLOGICAL_DATA_H_
namespace Gudhi {
namespace Persistence_representations {
/** \brief The concept Real_valued_topological_data describes the requirements
* for a type to implement a container that allows computations of its projections to R.
*/
class Real_valued_topological_data {
public:
/**
* Typically there are various ways data can be projected to R. This function gives us the number of functions for
* vectorization provided by a given class.
**/
size_t number_of_projections_to_R();
/**
* This is a function to compute the projection from this container to reals. The parameter of a function have to
* be between 0 and the value returned by number_of_projections_to_R().
**/
double project_to_R(size_t number_of_projection);
};
} // namespace Persistence_representations
} // namespace Gudhi
#endif // CONCEPT_REAL_VALUED_TOPOLOGICAL_DATA_H_
|
32e12727af550f9a722cc5bed5750d4e2b189a52
|
8e6e8d6e28a14316089974386a6b481c7ac59a63
|
/CCF/201812-4.cc
|
ff5d922aa4175c39c237684c4a648475c233d5a9
|
[] |
no_license
|
sqwlly/ACM-solved-problem
|
2301627e9cf7e8accbd731936cc494c2fd3d31f1
|
3509242792ea7bbd7d0a5989aeff712be57a4348
|
refs/heads/master
| 2021-06-05T03:02:46.655724
| 2020-02-19T04:58:32
| 2020-02-19T04:58:32
| 147,011,925
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,231
|
cc
|
201812-4.cc
|
/*************************************************************************
> File Name: 201812-4.cc
> Author: sqwlly
> Mail: sqw.lucky@gmail.com
> Created Time: 2019年03月14日 星期四 13时32分01秒
************************************************************************/
#include<bits/stdc++.h>
#define DEBUG(x) std::cerr << #x << '=' << x << std::endl
using namespace std;
const int N = 5E4+100;
int f[N];
vector<pair<int,pair<int,int>>> E;
int getf(int v)
{
if(f[v] == v) return v;
return f[v] = getf(f[v]);
}
void merge(int u,int v)
{
int p = getf(u);
int q = getf(v);
if(p != q) f[p] = q;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.in","r",stdin);
#endif
ios::sync_with_stdio(false); cin.tie(0);
int n,m,rt,u,v,w;
cin >> n >> m >> rt;
for(int i = 1; i <= n; ++i) f[i] = i;
for(int i = 0; i < m; ++i) {
cin >> u >> v >> w;
E.push_back(make_pair(w,make_pair(u,v)));
}
sort(E.begin(), E.end());
int ans = 0, cnt = 0;
for(int i = 0; i < m; ++i) {
int u = E[i].second.first, v = E[i].second.second;
int w = E[i].first;
if(getf(u) != getf(v)) {
cnt++;
merge(u,v);
ans = max(ans, w);
}
if(cnt == n - 1) break;
}
cout << ans << endl;
return 0;
}
|
f6a276e950984c752c7d82debe31d6d76e345128
|
b0284628709544ae4edc53317617e3303e554f43
|
/LEDServer/C++/ColorCalculator.cpp
|
fa5b03134a838c2f2fae5c9f5c06521881566836
|
[
"MIT"
] |
permissive
|
nordicway/Calamarity
|
f676a45f7e95278e2ae510c79b27ff65994a2bf1
|
8cac2afb3ac20144ddcc468cdaf4bcdd2dd000a2
|
refs/heads/master
| 2021-04-29T09:19:51.446565
| 2016-12-29T19:14:48
| 2016-12-29T19:14:48
| 77,634,320
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 276
|
cpp
|
ColorCalculator.cpp
|
#include "stdafx.h"
#include "ColorCalculator.h"
ColorCalculator::ColorCalculator(void)
{
}
ColorCalculator::~ColorCalculator(void)
{
}
std::vector<unsigned char> ColorCalculator::calc(RGBLED* rgbLED, float value)
{
return std::vector<unsigned char>();
}
|
73e1e521ce60b6374bd228d09b7d0b1c4baf9842
|
f7ba06442157af01c455e7714ce91d4b3ce96043
|
/POTD/autograderTest53/main.cpp
|
93a02d94dc9d427cf89229105b0ccfc6f2da6b94
|
[] |
no_license
|
Kennylixinran/cs225
|
3f870f84181bbe3daee72e78ff6ad675c662038e
|
2edc746b6b66623e3913d1a6206f32ca83fedbe6
|
refs/heads/master
| 2021-05-08T04:34:22.500790
| 2017-10-26T13:41:33
| 2017-10-26T13:41:33
| 108,416,638
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 65
|
cpp
|
main.cpp
|
#include "mystery.h"
int main(){
mystery();
return 0;
}
|
166f9f9bbb99e989fe0257b6f6943845b4ca1367
|
51560818f665eb20abf806b5b06cedb1b904b39f
|
/src/visual/Renderer.cpp
|
86b1b757ace907df80cee3ddc34e9556296a98a8
|
[
"BSD-3-Clause"
] |
permissive
|
zakrent/SDL-JUMP-GAME
|
bab7795dfbf661fa946daa0da484b7736f12944c
|
a28803dbf933d308338390e34c531e1339b983f5
|
refs/heads/master
| 2021-04-28T03:00:07.261023
| 2018-03-09T17:25:22
| 2018-03-09T17:25:22
| 122,128,820
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,296
|
cpp
|
Renderer.cpp
|
//
// Created by zakrent on 2/19/18.
//
#include <math.h>
#include "Renderer.h"
#include "../Game.h"
Renderer::Renderer() {
}
Renderer::~Renderer() {
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
}
void Renderer::createWindow() {
Game* game = Game::get();
if(!game->settingsManager->checkIfSettingExists("resx") || !game->settingsManager->checkIfSettingExists("resy")){
perror("Failed to load resolution settings!\n");
exit(-1);
}
int resX = game->settingsManager->getSetting("resx");
int resY = game->settingsManager->getSetting("resy");
if(SDL_CreateWindowAndRenderer(resX, resY, NULL, &window, &renderer) < 0){
perror("Failed to create window!\n");
exit(-1);
}
fontTexture = new TextureWrapper(renderer, const_cast<char *>("textures/font.bmp"));
}
void Renderer::startRendering() {
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
if(!Game::get()->settingsManager->checkIfSettingExists("resx")){
perror("Failed to get screen res settings\n");
exit(-1);
}
camera.x -= convertToWorldCord(Game::get()->settingsManager->getSetting("resx"))/2;
}
void Renderer::swapBuffers() {
SDL_RenderPresent(renderer);
}
int Renderer::convertToPixCord(double cord) {
if(!Game::get()->settingsManager->checkIfSettingExists("upixsize")){
perror("Failed to get unit pixel size!");
exit(-1);
}
return (int)(cord*Game::get()->settingsManager->getSetting("upixsize"));
}
double Renderer::convertToWorldCord(int cord) {
if(!Game::get()->settingsManager->checkIfSettingExists("upixsize")){
perror("Failed to get unit pixel size!");
exit(-1);
}
return (1.0*cord/Game::get()->settingsManager->getSetting("upixsize"));
}
void Renderer::renderRectangle(Vector2 root, double width, double height) {
Vector2 screenPos = root - camera;
SDL_Rect rect{};
rect.x = convertToPixCord(static_cast<double>(screenPos.x));
rect.y = convertToPixCord(static_cast<double>(screenPos.y));
rect.w = convertToPixCord(width);
rect.h = convertToPixCord(height);
if((int)root.x % 2 == 0)
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
else
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
SDL_RenderFillRect(renderer, &rect);
}
void Renderer::renderCirlce(Vector2 root, double radius) {
Vector2 screenPos = root- camera;
SDL_Point points[360];
for(int i = 0; i < 360; i++){
points[i].x = convertToPixCord((double)screenPos.x);
points[i].y = convertToPixCord((double)screenPos.y);
points[i].x += static_cast<int>(cos(i * M_PI / 180)*convertToPixCord(radius));
points[i].y += static_cast<int>(sin(i * M_PI / 180)*convertToPixCord(radius));
}
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderDrawLines(renderer, points, 360);
}
void Renderer::renderTriangle(Vector2 x1, Vector2 x2, Vector2 x3) {
SDL_Point points[4];
x1 -= camera;
x2 -= camera;
x3 -= camera;
points[0] = SDL_Point{convertToPixCord(static_cast<double>(x1.x)), convertToPixCord(static_cast<double>(x1.y))};
points[1] = SDL_Point{convertToPixCord(static_cast<double>(x2.x)), convertToPixCord(static_cast<double>(x2.y))};
points[2] = SDL_Point{convertToPixCord(static_cast<double>(x3.x)), convertToPixCord(static_cast<double>(x3.y))};
points[3] = points[0];
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderDrawLines(renderer, points, 4);
}
void Renderer::renderChar(char c, int x, int y) {
if(c < 'a') {
c -= 1;
}
int xFontPos = ((c%16))*32;
int yFontPos = (c/16)*32;
SDL_Rect srcrect{xFontPos, yFontPos, 32, 32};
SDL_Rect dstrect{x, y, 16, 16};
SDL_RenderCopyEx(renderer, fontTexture->getTexturePointer(), &srcrect,
&dstrect, 0, nullptr, SDL_FLIP_NONE);
}
void Renderer::renderString(std::string s, Vector2 pos) {
int x = convertToPixCord((double)pos.x);
int y = convertToPixCord((double)pos.y);
int i = 0;
int j = 0;
for(char c : s){
if(c == '\n'){
j++;
i = 0;
}
else {
renderChar(c, x + i*16, y + j*16);
i++;
}
}
}
|
36bd697b56b7c9c398a6aa6e02e552bc033914eb
|
4bc8592399529c9cdd7a6334720c6a13c829ec5a
|
/game sfml/game sfml/main.cpp
|
3c813daa8a8913c4d7228b9147a5c52861b2ba5a
|
[] |
no_license
|
KuR0uSaGi/game-sfml
|
9d44ae35b0fd6c664a027bc8d6d0f242e4c6f087
|
8564fd7ae26e00736b618079231981ed9d51b420
|
refs/heads/main
| 2023-01-12T13:59:29.101541
| 2020-11-16T07:19:04
| 2020-11-16T07:19:04
| 313,219,238
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,995
|
cpp
|
main.cpp
|
#include <SFML/Graphics.hpp>
#include<SFML/Window.hpp>
#include <iostream>
int main()
{
int a = 0;
/*const float gravity = 1;
int groundHeight = 630;
float moveSpeed = 0.05f, jumpSpeed = 0.1f;*/
sf::Vector2f velocity(sf::Vector2f(0, 0));
//
sf::RenderWindow window(sf::VideoMode(1080, 720), "Game from scratch!", sf::Style::Close | sf::Style::Resize);
///rectangle
sf::RectangleShape squarecollision(sf::Vector2f(600.0f, 90.0f));
squarecollision.setPosition({ 600.f, 500.f });
squarecollision.setFillColor(sf::Color::Blue);
///rectangle
sf::RectangleShape squarecollision1(sf::Vector2f(250.0f, 60.0f));
squarecollision1.setPosition({ 270.f, 570.f });
squarecollision1.setFillColor(sf::Color::Green);
///rectangle
sf::RectangleShape squarecollision2(sf::Vector2f(230.0f, 60.0f));
squarecollision2.setPosition({ 100.f, 640.f });
squarecollision2.setFillColor(sf::Color::White);
///rectangle
sf::RectangleShape squarecollision3(sf::Vector2f(230.0f, 60.0f));
squarecollision3.setPosition({ 0.f, 300.f });
squarecollision3.setFillColor(sf::Color::Blue);
///rectangle
sf::RectangleShape squarecollisionred(sf::Vector2f(30.0f, 10.0f));
squarecollisionred.setPosition({ 160.f, 630.f });
squarecollisionred.setFillColor(sf::Color::Red);
///rectangle
sf::RectangleShape squarecollision4(sf::Vector2f(150.0f, 80.0f));
squarecollision4.setPosition({ 0.f, 300.f });
squarecollision4.setFillColor(sf::Color::Cyan);
///rectangle
sf::RectangleShape squarecollision5(sf::Vector2f(150.0f, 60.0f));
squarecollision5.setPosition({ 0.f, 100.f });
squarecollision5.setFillColor(sf::Color::Yellow);
////// Circle
sf::CircleShape circlecollision(10.f);
circlecollision.setPosition({ 220.f, 200.f });
circlecollision.setFillColor(sf::Color::Red);
///circle
sf::CircleShape circlecollision1(10.f);
circlecollision1.setPosition({ 100.f, 680.f });
circlecollision1.setFillColor(sf::Color::Red);
////// Texture
sf::Texture playerTexture;
if (!playerTexture.loadFromFile("penguin.png"))
{
std::cout << "Load failed" << std::endl;
}
////// Sprite
sf::Sprite shapeSprite;
shapeSprite.setTexture(playerTexture);
int spriteSizeX = playerTexture.getSize().x / 3;
int spriteSizeY = playerTexture.getSize().y / 9;
shapeSprite.setTextureRect(sf::IntRect(0, 0, spriteSizeX, spriteSizeY));
sf::Vector2f spawnPoint = { 0.f, 600.f };
shapeSprite.setPosition(spawnPoint);
///key
sf::Texture keyTexture;
if (!keyTexture.loadFromFile("goldkeys.png"))
{
std::cout << "Load failed" << std::endl;
}
sf::Sprite keySprite;
keySprite.setTexture(keyTexture);
int keyspriteSizeX = keyTexture.getSize().x;
int keyspriteSizeY = keyTexture.getSize().y;
keySprite.setTextureRect(sf::IntRect(0, 0, keyspriteSizeX, keyspriteSizeY));
sf::Vector2f spawnKey = { 1000.f, 640.f };
keySprite.setPosition(spawnKey);
///delete
sf::Vector2f deletespawn = { 1000.f,1000.f };
///coin
sf::Texture coinTexture;
if (!coinTexture.loadFromFile("coinss.png"))
{
std::cout << "Load failed" << std::endl;
}
sf::Sprite coinSprite;
coinSprite.setTexture(coinTexture);
int coinspriteSizeX = coinTexture.getSize().x;
int coinspriteSizeY = coinTexture.getSize().y;
coinSprite.setTextureRect(sf::IntRect(0, 0, coinspriteSizeX, coinspriteSizeY));
sf::Vector2f spawncoin = { 350.f, 660.f };
coinSprite.setPosition(spawncoin);
///door
///
sf::Texture doorTexture;
if (!doorTexture.loadFromFile("door1.png"))
{
std::cout << "Load failed" << std::endl;
}
sf::Sprite doorSprite;
doorSprite.setTexture(doorTexture);
int doorspriteSizeX = doorTexture.getSize().x;
int doorspriteSizeY = doorTexture.getSize().y;
doorSprite.setTextureRect(sf::IntRect(0, 0, doorspriteSizeX, doorspriteSizeY));
sf::Vector2f spawndoor = { 50.f, 50.f };
doorSprite.setPosition(spawndoor);
//score
int score = 0;
sf::Text font1;
if (!font1.loadFromFile("font1.ttf"))
{
std::cout << "Load failed" << std::endl;
}
std::ostringstream ssScore;
ssScore << "Score: " << score;
sf::Text lblscore;
lblscore.setCharacterSize(30);
lblscore.setPosition(680.f,20.f);
lblscore.setFont(font1);
lblscore.setString(ssScore.str());
///level2
///rectangle
sf::RectangleShape squarecollision6(sf::Vector2f(60.0f, 300.0f));
squarecollision6.setPosition({ 920.f, 500.f });
squarecollision6.setFillColor(sf::Color::Blue);
///rectangle
sf::RectangleShape squarecollision7(sf::Vector2f(250.0f, 60.0f));
squarecollision7.setPosition({ 270.f, 570.f });
squarecollision7.setFillColor(sf::Color::Green);
///rectangle
sf::RectangleShape squarecollision8(sf::Vector2f(230.0f, 60.0f));
squarecollision8.setPosition({ 100.f, 640.f });
squarecollision8.setFillColor(sf::Color::White);
///rectangle
sf::RectangleShape squarecollision9(sf::Vector2f(230.0f, 60.0f));
squarecollision9.setPosition({ 0.f, 350.f });
squarecollision9.setFillColor(sf::Color::Blue);
///rectangle
sf::RectangleShape squarecollision10(sf::Vector2f(150.0f, 80.0f));
squarecollision10.setPosition({ 0.f, 300.f });
squarecollision10.setFillColor(sf::Color::Cyan);
///rectangle
sf::RectangleShape squarecollision11(sf::Vector2f(150.0f, 60.0f));
squarecollision11.setPosition({ 0.f, 100.f });
squarecollision11.setFillColor(sf::Color::Yellow);
///rectangle
sf::RectangleShape squarecollision12(sf::Vector2f(30.0f, 10.0f));
squarecollision12.setPosition({ 300.f, 660.f });
squarecollision12.setFillColor(sf::Color::Red);
///rectangle
sf::RectangleShape squarecollision13(sf::Vector2f(600.0f, 90.0f));
squarecollision13.setPosition({ 600.f, 500.f });
squarecollision13.setFillColor(sf::Color::Blue);
///redtangle
sf::RectangleShape squarecollisionred1(sf::Vector2f(30.0f, 10.0f));
squarecollisionred1.setPosition({ 160.f, 630.f });
squarecollisionred1.setFillColor(sf::Color::Red);
////// Circle
sf::CircleShape circlecollision2(10.f);
circlecollision2.setPosition({ 220.f, 200.f });
circlecollision2.setFillColor(sf::Color::Red);
///circle
sf::CircleShape circlecollision3(10.f);
circlecollision3.setPosition({ 100.f, 680.f });
circlecollision3.setFillColor(sf::Color::Red);
int animationFrame = 0;
//
int i = 0;
while (window.isOpen())
{
window.draw(shapeSprite);
window.draw(keySprite);
window.draw(coinSprite);
window.draw(squarecollision);
window.draw(squarecollision1);
window.draw(squarecollision2);
window.draw(squarecollision3);
window.draw(squarecollisionred);
window.draw(circlecollision);
window.draw(circlecollision1);
window.draw(lblscore);
//window.draw(doorSprite);
if (a == 1)
{ window.draw(doorSprite);
}
window.display();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
shapeSprite.move(.1f, 0.f);
shapeSprite.setTextureRect(sf::IntRect(spriteSizeX * animationFrame, spriteSizeY * 1, spriteSizeX, spriteSizeY));
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
shapeSprite.move(-.1f, 0.f);
shapeSprite.setTextureRect(sf::IntRect(spriteSizeX * animationFrame, spriteSizeY * 3, spriteSizeX, spriteSizeY));
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
shapeSprite.move(0.f, -.1f);
shapeSprite.setTextureRect(sf::IntRect(spriteSizeX * animationFrame, 0, spriteSizeX, spriteSizeY));
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
shapeSprite.move(0.f, .1f);
shapeSprite.setTextureRect(sf::IntRect(spriteSizeX * animationFrame, spriteSizeY * 4, spriteSizeX, spriteSizeY));
}
//Left
if (shapeSprite.getPosition().x < 0.f)
shapeSprite.setPosition(0.f, shapeSprite.getPosition().y);
//Top
if (shapeSprite.getPosition().y < 0.f)
shapeSprite.setPosition(shapeSprite.getPosition().x,0.f);
//Right
if (shapeSprite.getPosition().x+shapeSprite.getGlobalBounds().width > 1080)
shapeSprite.setPosition(1080-shapeSprite.getGlobalBounds().width, shapeSprite.getPosition().y);
//Bottom
if (shapeSprite.getPosition().y + shapeSprite.getGlobalBounds().height > 720)
shapeSprite.setPosition(shapeSprite.getPosition().x,720 - shapeSprite.getGlobalBounds().height);
//
/*if(squarecollisionred.getPosition().y>=620)
squarecollisionred.move(.0f, -0.2f);
//
if (squarecollisionred.getPosition().y <= 300)
squarecollisionred.move(.0f, -0.2f);*/
/*if (squarecollisionred.getGlobalBounds().intersects(squarecollision2.getGlobalBounds())) {
squarecollisionred.move(.0f, -.2f);
}*/
if (squarecollisionred.getGlobalBounds().intersects(squarecollision3.getGlobalBounds())) {
squarecollisionred.move(.0f, 300.0f);
}
squarecollisionred.move(.0f, -0.2f);
circlecollision.move(0.5f,0.8f);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
window.close();
}
animationFrame++;
if (animationFrame >= 2) {
animationFrame = 0;
}
//level 1
if (circlecollision.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
score -= 1;
printf("score = %d", score);
}
if (circlecollision1.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
score -= 1;
printf("score = %d", score);
}
if (squarecollision.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollision1.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollision2.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollision3.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollisionred.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
score -= 1;
}
if (keySprite.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
//shapeSprite.setPosition(spawnPoint)
a+=1;
printf("%d", a);
keySprite.setPosition(deletespawn);
}
if (coinSprite.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
//shapeSprite.setPosition(spawnPoint)
score += 1;
printf("score = %d", score);
coinSprite.setPosition(deletespawn);
}
if (doorSprite.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
//doorSprite.setPosition(spawnPoint);
system("cls");
//level2
int i = 0;
/*window.draw(shapeSprite);
window.draw(keySprite);
window.draw(coinSprite);*/
window.draw(squarecollision6);
window.draw(squarecollision7);
window.draw(squarecollision8);
window.draw(squarecollision9);
window.draw(squarecollision10);
window.draw(squarecollision11);
window.draw(squarecollision12);
window.draw(squarecollision13);
window.draw(squarecollisionred1);
window.draw(circlecollision2);
window.draw(circlecollision3);
window.display();
if (circlecollision2.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
score -= 1;
printf("score = %d", score);
}
if (circlecollision3.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
score -= 1;
printf("score = %d", score);
}
if (squarecollision6.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollision7.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollision8.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollision9.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollision10.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollision11.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollision12.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollision13.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
}
if (squarecollisionred1.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
shapeSprite.setPosition(spawnPoint);
score -= 1;
}
if (keySprite.getGlobalBounds().intersects(shapeSprite.getGlobalBounds())) {
//shapeSprite.setPosition(spawnPoint)
i += 1;
printf("%d", i);
keySprite.setPosition(deletespawn);
}
}
window.clear();
}
return 0;
}
|
a938d2a346e66d4841513fc2aa828fabd6d67b36
|
2dd89c3ba974cdb609dc2c7d0bf4c1322b23fdf7
|
/codeforces/294.2/A/A.cpp
|
d3a9b7bf8f4a88dc3af3ee0bcc644a80a8dc51ee
|
[] |
no_license
|
KawashiroNitori/ACM_Problems
|
7f69b6d200679ba32a9728b23b9c9cbc7668fc9a
|
2e814843452dd6f4f595be005160ebef19ce2ca9
|
refs/heads/master
| 2016-09-05T12:06:47.391273
| 2015-09-01T14:47:13
| 2015-09-01T14:47:13
| 41,744,238
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,119
|
cpp
|
A.cpp
|
#include <iostream>
using namespace std;
int main()
{
int white=0,black=0;
char ch;
for (int i=1;i<=8;i++)
for (int j=1;j<=8;j++)
{
cin>>ch;
switch (ch)
{
case 'Q':
{
white+=9;
break;
}
case 'R':
{
white+=5;
break;
}
case 'B':
{
white+=3;
break;
}
case 'N':
{
white+=3;
break;
}
case 'P':
{
white+=1;
break;
}
case 'K':
{
break;
}
case 'q':
{
black+=9;
break;
}
case 'r':
{
black+=5;
break;
}
case 'b':
{
black+=3;
break;
}
case 'n':
{
black+=3;
break;
}
case 'p':
{
black+=1;
break;
}
case 'k':
{
break;
}
}
}
if (white>black)
cout<<"White"<<endl;
if (white==black)
cout<<"Draw"<<endl;
if (white<black)
cout<<"Black"<<endl;
return 0;
}
|
270daa8f771d8ba2dd37b5426e1c4d548cc7f4e2
|
ffff2a4fb72a163e4d42b01cefa1f5566784990f
|
/codeforces/contests/662div2/q4.cpp
|
050fa1f9d4f5d307bb1fb83cb6c7dc33836ba3ff
|
[] |
no_license
|
sanyamdtu/competitive_programming
|
d5b4bb6a1b46c56ebe2fe684f4a7129fe5fb8e86
|
5a810bbbd0c2119a172305b16d7d7aab3f0ed95e
|
refs/heads/master
| 2021-10-25T07:11:47.431312
| 2021-10-06T07:37:25
| 2021-10-06T07:37:25
| 238,703,031
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 547
|
cpp
|
q4.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define mod 1000000007
#define INF 1e18
typedef long long ll;
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t;
cin >> t;
while (t--)
{
int n,q;
cin>>n>>q;
ll arr[n];
vector<vector<int>> g(n+1);
for (int i = 0; i < n; ++i)
{
cin>>arr[i];
}
for (int i = 0; i < n-1; ++i)
{
int u,v;
cin>>u>>v;
g[u].pb(v);
g[v].pb(u);
}
for (int i = 0; i < q; ++i)
{
int a,b;
cin>>a>>b;
}
}
return 0;
}
1-2-4
| |
3 5
|
22ae8795abae9a898201c56edd6c52324b1b3a6e
|
3b4696f5353468e08377283726ff8ac3b44a1f62
|
/driver/canbus_driver/CML/CanDriver/CML_Equipment.h
|
f1a535ba5b01cb46f8e4ff158bc18812709d927f
|
[] |
no_license
|
hmguan/grace
|
7b8e14b07b35eb12c153765ba9f2189230fcd224
|
d4da5ec4b668720be6ff5c9b88a9d92d040e8bc1
|
refs/heads/master
| 2020-03-26T20:56:00.460868
| 2018-08-20T11:21:58
| 2018-08-20T11:21:58
| 145,356,104
| 0
| 0
| null | 2018-08-20T02:27:21
| 2018-08-20T02:27:21
| null |
UTF-8
|
C++
| false
| false
| 825
|
h
|
CML_Equipment.h
|
#ifndef _EQUIPMENT_
#define _EQUIPMENT_
#include "CML_Reference.h"
#include "CML_EventMap.h"
CML_NAMESPACE_START()
class EquipmentError: public Error
{
public:
static const EquipmentError NoParent;
protected:
EquipmentError( uint16 id, const char *desc ): Error( id, desc ){}
};
class Equipment: public RefObj
{
uint32 childRef_[CML_MAX_CHILD_PER_EQPT];
uint8 childIdx_;
uint32 parentRef_;
uint8 eqptID_;
// Semaphore startSema_;
Mutex mtx_;
public:
Equipment(Equipment *parent = 0);
virtual ~Equipment();
// virtual void run( void ) = 0;
void attachEqpt(Equipment *eqpt, uint8 &id);
void detachEqpt(Equipment *eqpt, uint8 id);
private:
Equipment( const Equipment & );
Equipment &operator=( const Equipment & );
};
CML_NAMESPACE_END()
#endif //_EQUIPMENT_
|
2d7e4cf5cbf9b030482a8377e3d37111aa2946b6
|
0dedbe330b2039f0f079ed30abeabb385b335f87
|
/piercingfactory.h
|
c3158bc0622ea8881b6163a8f84f395685692539
|
[] |
no_license
|
craig95/flyingbadger
|
d7f62442b9200513caa910eb39ab6c2a24aa010e
|
439fe90313357cc4ecb3590a908cfe08ca314b8f
|
refs/heads/master
| 2021-01-10T13:17:34.672003
| 2015-09-29T08:01:22
| 2015-09-29T08:01:22
| 43,293,325
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 181
|
h
|
piercingfactory.h
|
#ifndef PIERCINGFACTORY_H
#define PIERCINGFACTORY_H
#include "unitfactory.h"
class PiercingFactory: public UnitFactory
{
public:
void createPlayer();
void createMob();
}
#endif
|
dd24c5bb71c29576a90b3a0af13153feceac9cb9
|
4b4564dbb0748d5f3fe588df98aee21ffbc8417e
|
/src/Dialog_Prompt.cpp
|
e91d0e092bd6970651f607749d4b749df8d9e4c8
|
[] |
no_license
|
Openhologram/OpenholoRefAppGUI
|
08863739d09ee17489af2aba1d2c262c88192bc2
|
f8d10b7c4e3d49a470fab3457316eb30301ffbcf
|
refs/heads/master
| 2022-01-23T08:42:10.428399
| 2022-01-07T04:36:04
| 2022-01-07T04:36:04
| 207,519,048
| 8
| 8
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,135
|
cpp
|
Dialog_Prompt.cpp
|
// Dialog_Prompt.cpp: 구현 파일
//
#include "stdafx.h"
#include "OpenholoRefAppGUI.h"
#include "Dialog_Prompt.h"
#include "afxdialogex.h"
// Dialog_Prompt 대화 상자
IMPLEMENT_DYNAMIC(Dialog_Prompt, CDialogEx)
Dialog_Prompt::Dialog_Prompt(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_DLG_PROMPT, pParent)
{
}
Dialog_Prompt::~Dialog_Prompt()
{
}
void Dialog_Prompt::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_STATIC, m_szPrompt);
DDX_Text(pDX, IDC_EDIT_ANSWER, m_szAnswer);
}
BEGIN_MESSAGE_MAP(Dialog_Prompt, CDialogEx)
END_MESSAGE_MAP()
// Dialog_Prompt 메시지 처리기
BOOL Dialog_Prompt::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: 여기에 추가 초기화 작업을 추가합니다.
m_szPrompt = L"반복 할 테스트 수를 입력하시오.";
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// 예외: OCX 속성 페이지는 FALSE를 반환해야 합니다.
}
CString Dialog_Prompt::GetInputString()
{
return m_szAnswer;
}
int Dialog_Prompt::GetInputInteger()
{
return _ttoi(m_szAnswer);
}
|
674d5eca4068fab973d46d4f99a31170d37d12b7
|
3b45c6dc53371ce94614b2d163f434a61e445d82
|
/include/dark/dll/dll.hpp
|
2b0b2db65344ba160f77be5c89eb6ec22cb68b49
|
[] |
no_license
|
zephyrer/dark-filter
|
b00ade216365d6abeb9b654691233314f35b9c27
|
e69352f260c164c65576ead5983674f10f8d1c55
|
refs/heads/master
| 2021-01-23T11:02:57.067035
| 2014-06-10T04:23:48
| 2014-06-10T04:23:48
| 40,067,643
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 501
|
hpp
|
dll.hpp
|
#ifndef _DARK_DLL_
#define _DARK_DLL_
namespace dark
{
namespace dll
{
class SetResourceHandle
{
public:
HINSTANCE old;
//構造設置資源句柄
SetResourceHandle()
{
old = AfxGetResourceHandle();
}
SetResourceHandle(HINSTANCE hinstance)
{
old = AfxGetResourceHandle();
AfxSetResourceHandle(hinstance);
}
//析構恢復資源句柄
~SetResourceHandle()
{
AfxSetResourceHandle(old);
}
};
}
}
#endif //dll
|
f7c60314befb361daa1484e56eea7e70f2496b8f
|
4c6af3fefc086a82d07dc6dabfc6c0215822f485
|
/main.cpp
|
960a9c5f858925827b14345fb696a957ea61d590
|
[] |
no_license
|
DavidLiuGit/Synthagram
|
ee10344ca7e196c2a7f4a70cbf44684bc5c677a7
|
f59a33e288f217d75ab4e4fb082c29d9331a9f6f
|
refs/heads/master
| 2021-01-10T18:04:40.876497
| 2016-05-11T03:39:53
| 2016-05-11T03:39:53
| 49,257,255
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 802
|
cpp
|
main.cpp
|
#include <cstdlib>
#include <string>
#include <iostream>
#define PATH "Dictionary/dictionary.txt"
#include "dictionary.h"
#define V1 1
#define V2 1
using namespace std;
void help();
void parser(dictionary *ref);
// About synthagram
void about(){
cout << "Synthagram is a console application that finds anagrams based on user input." << endl;
cout << "Current version: " << (unsigned int)V1 << '.' << (unsigned int)V2 << endl;
//cout << "This program uses C++2011" << endl << endl;
cout << "The default dictionary uses English spelling instead of American (favour, colour, etc.)" << endl;
}
int main(int argc, char** argv) {
if (argc == 2)
about();
dictionary *ref = new dictionary( (string) PATH );
parser(ref);
delete ref;
return 0;
}
|
54d9a93f8eaa29b01eb6993e888f4faaaa734c66
|
10ccc1739ad2a391e76b1c52b216e273babbf3bc
|
/src/mearly.h
|
2e9a250bbba9e4a7f292c2c1cc4ce35a572b276a
|
[] |
no_license
|
mattearly/TheOnlyEscapeIsESC
|
44f5890f8d2f34e677cbb053063d7a15b685567c
|
8ec561f0c65d7bde596dd8a10ccf013af747923b
|
refs/heads/main
| 2023-01-28T00:28:21.893529
| 2023-01-25T00:35:09
| 2023-01-25T00:35:09
| 161,948,918
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 521
|
h
|
mearly.h
|
/*
~ Utility Functions
~ built by Matthew Early
*/
#include <random>
#include <chrono>
namespace mearly
{
///
/// \brief ZTOR Zero-To-One-Random uses MersenneTwister seeded on a high precision
/// timestamp seed for a true feeling of randomness
/// \return double between 0.0 and 1.0
///
double ZTOR();
///
/// \brief ZOOR Zero-Or-One-Random
/// \return 0 or 1
///
int ZOOR();
///
/// \brief NTKR N-To-K-Random
/// \return an random integer in the range N to K;
///
int NTKR(int n, int k);
} //end namespace mearly
|
156e03aad8122d48e0d75e8db3ead600961b4737
|
a43bf399b62b9ca17eb95c80c99067b925fdd2ad
|
/C++ Console/2015/T8/任务三 动物类/任务三 动物类/animal.h
|
7b20a3a569a2f7e3aabd1267a691b71acc90c73b
|
[] |
no_license
|
imjinghun/university
|
d4bdf80ae6ed3d5a88c5a8b38c7640f19b0efe2c
|
1f5e9c0301ab4d38e4504d6c9cae4b5a187ce26b
|
refs/heads/master
| 2021-01-01T16:13:34.426161
| 2017-09-11T13:00:40
| 2017-09-11T13:00:40
| 97,788,115
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 258
|
h
|
animal.h
|
#pragma once
#include<iostream>
#include<string>
using namespace std;
class animal
{
protected:
string ani;
public:
animal(void);
animal(string ani)
{
this->ani=ani;
}
~animal(void);
virtual void speak()
{
cout<<"My name is animal!"<<endl;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.