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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
398dab00ef8e33b8106f7c386504020ce57cd7ae
|
a1809f8abdb7d0d5bbf847b076df207400e7b08a
|
/Simpsons Hit&Run/game/libs/radcore/src/radmemory/memoryspaceps2.hpp
|
cf53bff3cfb92ab0ae325aafee2a276a967ce5a8
|
[] |
no_license
|
RolphWoggom/shr.tar
|
556cca3ff89fff3ff46a77b32a16bebca85acabf
|
147796d55e69f490fb001f8cbdb9bf7de9e556ad
|
refs/heads/master
| 2023-07-03T19:15:13.649803
| 2021-08-27T22:24:13
| 2021-08-27T22:24:13
| 400,380,551
| 8
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,691
|
hpp
|
memoryspaceps2.hpp
|
//=============================================================================
// Copyright (c) 2002 Radical Games Ltd. All rights reserved.
//=============================================================================
//=============================================================================
//
// File: memoryspaceps2.hpp
//
// Subsystem: Foundation Technologies - Memory Operation Services
//
// Description: This file contains the ps2 implementation of the
// remote memory space operations
//
// Revisions: 13-Oct-2001 Creation Rob
//
//=============================================================================
#ifndef MEMORYSPACEPS2_HPP
#define MEMORYSPACEPS2_HPP
//============================================================================
// Include Files
//============================================================================
#include <radmemory.hpp>
#include <radtime.hpp>
#include <sifrpc.h>
//============================================================================
// Forward Declarations
//============================================================================
// Internal init done by radMemoryInitialize( )
void radMemorySpaceInitialize( unsigned int maxRequests );
void radMemorySpaceTerminate( void );
struct MemorySpaceAsyncRequest_CopyEeToEe;
struct MemorySpaceAsyncRequest_CopyEeToIop;
struct MemorySpaceAsyncRequest_CopyIopToEe;
//============================================================================
// struct MemorySpaceAsyncRequest_CopyEeToEe
//============================================================================
struct MemorySpaceAsyncRequest_CopyEeToEe
:
public IRadMemorySpaceCopyRequest
{
public:
MemorySpaceAsyncRequest_CopyEeToEe( void );
~MemorySpaceAsyncRequest_CopyEeToEe( void );
virtual void AddRef( void );
virtual void Release( void );
virtual bool IsDone( void );
private:
unsigned int m_RefCount;
};
//============================================================================
// struct MemorySpaceAsyncRequest
//============================================================================
struct MemorySpaceAsyncRequest : public radObject, public IRadMemorySpaceCopyRequest
{
MemorySpaceAsyncRequest( void );
virtual ~MemorySpaceAsyncRequest( void );
void Implement_AddRef( void ) { m_RefCount++; }
void Implement_Release( void ) { rAssert( m_RefCount > 0 ); m_RefCount--; if ( m_RefCount == 0 ) { delete this; } }
void * operator new( size_t size, const char * pIdentifier );
void operator delete( void * pMemory );
static void ServiceHead( void );
static void QueueRequest( MemorySpaceAsyncRequest * pRequest );
protected:
virtual void DoRequest( void ) = 0;
virtual bool Service( void ) = 0; // true - finished, false - more to do
private:
MemorySpaceAsyncRequest * m_pRequest_Next;
static MemorySpaceAsyncRequest * s_pRequest_Head;
unsigned int m_RefCount;
};
//============================================================================
// struct MemorySpaceAsyncRequest_CopyEeToIop
//============================================================================
struct MemorySpaceAsyncRequest_CopyEeToIop
:
public MemorySpaceAsyncRequest
{
public:
IMPLEMENT_BASEOBJECT( "MemorySpaceAsyncRequest_CopyEeToIop" )
MemorySpaceAsyncRequest_CopyEeToIop( void * pDest, const void * pSrc, unsigned int bytes );
~MemorySpaceAsyncRequest_CopyEeToIop( void );
virtual void AddRef( void ) { Implement_AddRef( ); }
virtual void Release( void ) { Implement_Release( ); }
virtual bool IsDone( void );
protected:
virtual void DoRequest( );
private:
bool Service( void );
unsigned int m_TransactionId;
void * m_pDest;
const void * m_pSource;
unsigned int m_Bytes;
enum State { Queued, Waiting, Started, Done } m_State;
};
//============================================================================
// struct MemorySpaceAsyncRequest_CopyIopToEe
//============================================================================
struct MemorySpaceAsyncRequest_CopyIopToEe
:
public MemorySpaceAsyncRequest
{
public:
IMPLEMENT_BASEOBJECT( "MemorySpaceAsyncRequest_CopyIopToEe" )
MemorySpaceAsyncRequest_CopyIopToEe( void * pDest, const void * pSrc, unsigned int bytes );
~MemorySpaceAsyncRequest_CopyIopToEe( void );
virtual void AddRef( void ) { Implement_AddRef( ); }
virtual void Release( void ) { Implement_Release( ); }
virtual bool IsDone( void );
protected:
virtual void DoRequest( );
private:
bool Service( void );
sceSifReceiveData m_ReceiveData;
void * m_pDest;
const void * m_pSource;
unsigned int m_Bytes;
enum State { Queued, Waiting, Started, Done } m_State;
};
//============================================================================
// struct MemorySpaceAsyncRequest_CopyIopToIop
//============================================================================
struct MemorySpaceAsyncRequest_CopyIopToIop
:
public MemorySpaceAsyncRequest
{
public:
static void Initialize( unsigned int transferBufferSize );
static void Terminate( void );
// IRadMemorySpaceCopyRequest
virtual void AddRef( void ) { Implement_AddRef( ); }
virtual void Release( void ) { Implement_Release( ); }
virtual bool IsDone( void );
IMPLEMENT_BASEOBJECT( "MemorySpaceAsyncRequest_CopyIopToIop" )
MemorySpaceAsyncRequest_CopyIopToIop( void * pDest, const void * pSrc, unsigned int bytes );
~MemorySpaceAsyncRequest_CopyIopToIop( void );
virtual void DoRequest( );
bool Service( void );
private:
unsigned int m_SourceAddress; // Src in Iop Memory
unsigned int m_DestinationAddress; // Destination in Iop memory
unsigned int m_BytesToCopy;
unsigned int m_BytesCopied;
unsigned int m_BytesCopying;
enum State { Queued, Waiting, Started, IopToEe, IopToEeDone, EeToIop, EeToIopDone, Done } m_State;
sceSifReceiveData m_ReceiveData; // Sony struct for IOP -> EE transfer
int m_TransactionId; // Sony handle for EE -> IOP transfer
static char * s_pTransferBuffer;
static unsigned int s_TransferBufferSize;
};
#endif // MEMORYSPACEPS2_HPP
|
e13be0410e4bfd2a17ec1f60a86e5205e448f65d
|
dbdc638b28c0bd2275a7b09cec5479e1fa6a6f6f
|
/matrix.cpp
|
becd6c30f805090d87e9c461b54b65705a5967ed
|
[] |
no_license
|
shift4/ptrace
|
eed979931fb7e9f85c6cc664d3f611b6f6b6d46d
|
03825c4dab745afe3b85523538af8a396c5a2cae
|
refs/heads/master
| 2023-03-20T00:58:34.765510
| 2023-03-08T07:30:39
| 2023-03-08T07:30:39
| 110,398,370
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 304
|
cpp
|
matrix.cpp
|
#include<iostream>
typedef int arrT[5];
arrT* makearray()
{
int a[5] = {1};
std::cout << &a << std::endl;
return &a;
}
int main()
{
arrT *p = makearray();
std::cout << p << std::endl;
for(int i = 0; i < 5; i++){
std::cout << (*p)[0] << std::endl;
}
return 0;
}
|
d2c6827ffc80a3330f639211beb8669916c584cf
|
6c013d5d70b692e6b5250f3ab8405e1a1ef32055
|
/UIWidgets/GeneralInformationWidgetR2D.cpp
|
3c8a2e0a02388b2dcbae5b89a3663c57b4f040fb
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
NHERI-SimCenter/R2DTool
|
a667afb17a5ac6df07966ee5b98cf1975dfe6ddf
|
b3fa98e018bdf71caccd97277d81307ac051a1c1
|
refs/heads/master
| 2023-08-19T07:48:07.775861
| 2023-07-28T15:16:17
| 2023-07-28T15:16:17
| 329,111,097
| 5
| 18
|
NOASSERTION
| 2023-09-14T21:52:20
| 2021-01-12T21:00:33
|
C++
|
UTF-8
|
C++
| false
| false
| 13,118
|
cpp
|
GeneralInformationWidgetR2D.cpp
|
/* *****************************************************************************
Copyright (c) 2016-2021, The Regents of the University of California (Regents).
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS
PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*************************************************************************** */
// Written by: Stevan Gavrilovic, Frank McKenna
#include "GeneralInformationWidgetR2D.h"
#include "sectiontitle.h"
#include "SimCenterPreferences.h"
#include "SimCenterUnitsCombo.h"
#include <QCheckBox>
#include <QComboBox>
#include <QDebug>
#include <QFormLayout>
#include <QGridLayout>
#include <QGroupBox>
#include <QJsonArray>
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
#include <QList>
#include <QMetaEnum>
#include <QPushButton>
GeneralInformationWidgetR2D::GeneralInformationWidgetR2D(QWidget *parent)
: SimCenterWidget(parent)
{
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->setMargin(0);
QHBoxLayout *theHeaderLayout = new QHBoxLayout();
SectionTitle *label = new SectionTitle();
label->setText(QString("General Information"));
label->setMinimumWidth(150);
theHeaderLayout->addWidget(label);
QSpacerItem *spacer = new QSpacerItem(50,0);
theHeaderLayout->addItem(spacer);
theHeaderLayout->addStretch(1);
auto infoLayout = this->getInfoLayout();
mainLayout->addLayout(theHeaderLayout);
mainLayout->addLayout(infoLayout);
mainLayout->addStretch();
this->setMaximumWidth(750);
}
GeneralInformationWidgetR2D::~GeneralInformationWidgetR2D()
{
}
bool GeneralInformationWidgetR2D::outputToJSON(QJsonObject &jsonObj)
{
auto runDir = SimCenterPreferences::getInstance()->getLocalWorkDir();
// auto appDir = SimCenterPreferences::getInstance()->getAppDir();
jsonObj.insert("Name", nameEdit->text());
jsonObj.insert("Author", "SimCenter");
jsonObj.insert("WorkflowType", "Parametric Study");
jsonObj.insert("runDir", runDir);
//jsonObj.insert("localAppDir", appDir);
QJsonObject unitsObj;
unitsObj["force"] = unitsForceCombo->getCurrentUnitString();
unitsObj["length"] = unitsLengthCombo->getCurrentUnitString();
unitsObj["time"] = unitsTimeCombo->getCurrentUnitString();
QJsonObject outputsObj;
outputsObj.insert("EDP", EDPCheckBox->isChecked());
outputsObj.insert("DM", DMCheckBox->isChecked());
outputsObj.insert("DV", DVCheckBox->isChecked());
outputsObj.insert("every_realization", realizationCheckBox->isChecked());
outputsObj.insert("AIM", AIMCheckBox->isChecked());
outputsObj.insert("IM", IMCheckBox->isChecked());
QJsonObject assetsObj;
assetsObj.insert("buildings", buildingsCheckBox->isChecked());
assetsObj.insert("soil", soilCheckBox->isChecked());
assetsObj.insert("gas", gasCheckBox->isChecked());
assetsObj.insert("water", waterCheckBox->isChecked());
assetsObj.insert("waste", sewerCheckBox->isChecked());
assetsObj.insert("transportation", transportationCheckBox->isChecked());
jsonObj.insert("units",unitsObj);
jsonObj.insert("outputs",outputsObj);
jsonObj.insert("assets",assetsObj);
return true;
}
bool GeneralInformationWidgetR2D::inputFromJSON(QJsonObject &jsonObject){
if (jsonObject.contains("Name"))
nameEdit->setText(jsonObject["Name"].toString());
if (jsonObject.contains("units")) {
QJsonObject unitsObj=jsonObject["units"].toObject();
QJsonValue unitsForceValue = unitsObj["force"];
if(!unitsForceValue.isNull())
{
unitsForceCombo->setCurrentUnitString(unitsForceValue.toString());
}
QJsonValue unitsLengthValue = unitsObj["length"];
if(!unitsLengthValue.isNull())
{
unitsLengthCombo->setCurrentUnitString(unitsLengthValue.toString());
}
QJsonValue unitsTimeValue = unitsObj["time"];
if(!unitsTimeValue.isNull())
{
unitsTimeCombo->setCurrentUnitString(unitsTimeValue.toString());
}
}
if (jsonObject.contains("outputs")) {
QJsonObject outObj=jsonObject["outputs"].toObject();
EDPCheckBox->setChecked(outObj["EDP"].toBool());
DMCheckBox->setChecked(outObj["DM"].toBool());
DVCheckBox->setChecked(outObj["DV"].toBool());
realizationCheckBox->setChecked(outObj["every_realization"].toBool());
AIMCheckBox->setChecked(outObj["AIM"].toBool());
IMCheckBox->setChecked(outObj["IM"].toBool());
}
if (jsonObject.contains("assets")) {
QJsonObject outObj=jsonObject["assets"].toObject();
buildingsCheckBox->setChecked(outObj["buildings"].toBool());
soilCheckBox->setChecked(outObj["soil"].toBool());
gasCheckBox->setChecked(outObj["gas"].toBool());
waterCheckBox->setChecked(outObj["water"].toBool());
sewerCheckBox->setChecked(outObj["waste"].toBool());
transportationCheckBox->setChecked(outObj["transportation"].toBool());
}
return true;
}
QString GeneralInformationWidgetR2D::getAnalysisName(void)
{
return nameEdit->text();
}
QGridLayout* GeneralInformationWidgetR2D::getInfoLayout(void)
{
// Analysis information
nameEdit = new QLineEdit();
QGroupBox* analysisGroupBox = new QGroupBox("Analysis Name");
analysisGroupBox->setContentsMargins(0,5,0,0);
QFormLayout* analysisLayout = new QFormLayout(analysisGroupBox);
analysisLayout->addRow(tr("Name"), nameEdit);
analysisLayout->setAlignment(Qt::AlignLeft);
analysisLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
analysisLayout->setRowWrapPolicy(QFormLayout::DontWrapRows);
nameEdit->setText("R2D Analysis");
unitsForceCombo = new SimCenterUnitsCombo(SimCenter::Unit::FORCE,"force");
unitsLengthCombo = new SimCenterUnitsCombo(SimCenter::Unit::LENGTH,"length");
unitsTimeCombo = new SimCenterUnitsCombo(SimCenter::Unit::TIME,"time");
// Units
QGroupBox* unitsGroupBox = new QGroupBox("Units");
unitsGroupBox->setContentsMargins(0,5,0,0);
QFormLayout* unitsFormLayout = new QFormLayout(unitsGroupBox);
unitsFormLayout->addRow(tr("Force"), unitsForceCombo);
unitsFormLayout->addRow(tr("Length"), unitsLengthCombo);
unitsFormLayout->addRow(tr("Time"), unitsTimeCombo);
unitsFormLayout->setAlignment(Qt::AlignLeft);
unitsFormLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
unitsFormLayout->setRowWrapPolicy(QFormLayout::DontWrapRows);
// Assets
buildingsCheckBox = new QCheckBox("Buildings");
soilCheckBox = new QCheckBox("Soil");
gasCheckBox = new QCheckBox("Gas Network");
waterCheckBox = new QCheckBox("Water Network");
sewerCheckBox = new QCheckBox("Waste Network");
transportationCheckBox = new QCheckBox("Transportation Network");
soilCheckBox->setCheckable(false);
gasCheckBox->setCheckable(true);
waterCheckBox->setCheckable(true);
sewerCheckBox->setCheckable(false);
transportationCheckBox->setCheckable(true);
soilCheckBox->setEnabled(false);
gasCheckBox->setEnabled(false);
waterCheckBox->setEnabled(true);
sewerCheckBox->setEnabled(false);
transportationCheckBox->setEnabled(true);
connect(buildingsCheckBox, &QCheckBox::stateChanged, this, [=](){
emit assetChanged("Buildings",buildingsCheckBox->isChecked());
});
connect(soilCheckBox, &QCheckBox::stateChanged, this, [=](){
emit assetChanged("Soil",soilCheckBox->isChecked());
});
connect(gasCheckBox, &QCheckBox::stateChanged, this, [=](){
emit assetChanged("Gas Network",gasCheckBox->isChecked());
});
connect(waterCheckBox, &QCheckBox::stateChanged, this, [=](){
emit assetChanged("Water Network",waterCheckBox->isChecked());
});
connect(sewerCheckBox, &QCheckBox::stateChanged, this, [=](){
emit assetChanged("Sewer Network",sewerCheckBox->isChecked());
});
connect(transportationCheckBox, &QCheckBox::stateChanged, this, [=](){
emit assetChanged("Transportation Network",transportationCheckBox->isChecked());
});
QGroupBox* assetGroupBox = new QGroupBox("Asset Layers");
assetGroupBox->setContentsMargins(0,5,0,0);
QVBoxLayout* assetLayout = new QVBoxLayout(assetGroupBox);
assetLayout->addWidget(buildingsCheckBox);
assetLayout->addWidget(soilCheckBox);
assetLayout->addWidget(gasCheckBox);
assetLayout->addWidget(waterCheckBox);
assetLayout->addWidget(sewerCheckBox);
assetLayout->addWidget(transportationCheckBox);
// Outputs
EDPCheckBox = new QCheckBox("Engineering demand parameters (EDP)");
DMCheckBox = new QCheckBox("Damage measures (DM)");
DVCheckBox = new QCheckBox("Decision variables (DV)");
realizationCheckBox = new QCheckBox("Output EDP, DM, and DV every sampling realization");
AIMCheckBox = new QCheckBox("Output Asset Information Model (AIM)");
IMCheckBox = new QCheckBox("Output site IM");
EDPCheckBox->setChecked(true);
DMCheckBox->setChecked(true);
DVCheckBox->setChecked(true);
realizationCheckBox->setChecked(false);
AIMCheckBox->setChecked(false);
IMCheckBox->setChecked(false);
QGroupBox* outputGroupBox = new QGroupBox("Output Settings");
outputGroupBox->setContentsMargins(0,5,0,0);
QVBoxLayout* outputLayout = new QVBoxLayout(outputGroupBox);
outputLayout->addWidget(EDPCheckBox);
outputLayout->addWidget(DMCheckBox);
outputLayout->addWidget(DVCheckBox);
outputLayout->addWidget(realizationCheckBox);
outputLayout->addWidget(AIMCheckBox);
outputLayout->addWidget(IMCheckBox);
/*
QGroupBox* regionalMappingGroupBox = new QGroupBox("Regional Mapping", this);
regionalMappingGroupBox->setContentsMargins(0,5,0,0);
regionalMappingGroupBox->setLayout(theRegionalMappingWidget->layout());
// regionalMappingGroupBox->addWidget(theRegionalMappingWidget);
*/
QSpacerItem *spacer = new QSpacerItem(0,20);
// Layout the UI components
QGridLayout* layout = new QGridLayout();
layout->addWidget(analysisGroupBox,0,0);
layout->addItem(spacer,1,0);
layout->addWidget(unitsGroupBox,2,0);
layout->addItem(spacer,3,0);
layout->addWidget(assetGroupBox,4,0);
layout->addItem(spacer,5,0);
layout->addWidget(outputGroupBox,6,0);
layout->addItem(spacer,7,0);
//layout->addWidget(regionalMappingGroupBox,8,0);
return layout;
}
bool GeneralInformationWidgetR2D::setAssetTypeState(QString assetType, bool checkedStatus){
if (assetType == "Buildings")
buildingsCheckBox->setChecked(checkedStatus);
return true;
}
void GeneralInformationWidgetR2D::clear(void)
{
nameEdit->clear();
unitsForceCombo->setCurrentUnit(SimCenter::Unit::lb);
unitsLengthCombo->setCurrentUnit(SimCenter::Unit::ft);
unitsTimeCombo->setCurrentUnit(SimCenter::Unit::sec);
buildingsCheckBox->setChecked(true);
soilCheckBox->setChecked(false);
waterCheckBox->setChecked(false);
sewerCheckBox->setChecked(false);
gasCheckBox->setChecked(false);
transportationCheckBox->setChecked(false);
EDPCheckBox->setChecked(false);
DMCheckBox->setChecked(false);
DVCheckBox->setChecked(false);
realizationCheckBox->setChecked(false);
AIMCheckBox->setChecked(false);
IMCheckBox->setChecked(false);
}
|
ef29552e905a4985e29373c0cdad763b7a7b3f74
|
f9b2b183bb2c1d621f36417fffd5d5c19b36cbd5
|
/Code/WeSalon/ReplyDlg.cpp
|
768700e4bd1814ec0be523d921faec65d8535712
|
[
"MIT"
] |
permissive
|
takuyara/WeSalon-Application
|
33699fa87bb001e7aee45ac2fe11efaa3f85bffd
|
31fbcaedf13d792f72f444fd4efbf68379f7d187
|
refs/heads/master
| 2023-05-14T14:43:01.495059
| 2021-06-01T05:35:11
| 2021-06-01T05:35:11
| 372,712,680
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,477
|
cpp
|
ReplyDlg.cpp
|
//Pionniers du TJ, benissiez-moi par votre Esprits Saints!
//It rained on us at 4am.
#include "pch.h"
#include "WeSalon.h"
#include "ReplyDlg.h"
#include "afxdialogex.h"
#include "dbif.h"
// ReplyDlg 对话框
IMPLEMENT_DYNAMIC(ReplyDlg, CDialogEx)
ReplyDlg::ReplyDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_REPLY, pParent)
{
}
ReplyDlg::~ReplyDlg()
{
}
void ReplyDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(ReplyDlg, CDialogEx)
ON_BN_CLICKED(IDB_REPLYTRUE1, &ReplyDlg::OnBnClickedReplytrue1)
END_MESSAGE_MAP()
// ReplyDlg 消息处理程序
BOOL ReplyDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: 在此添加额外的初始化
editf.CreatePointFont(150, _T("Comic Sans MS"));
butf.CreatePointFont(120, _T("Comic Sans MS"));
GetDlgItem(IDS_REPLYTOWHOM)->SetFont(&editf);
GetDlgItem(IDE_REPLYCONTENT1)->SetFont(&butf);
GetDlgItem(IDB_REPLYTRUE1)->SetFont(&editf);
GetDlgItem(IDS_REPLYTOWHOM)->SetWindowText(GetReplyString());
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
void ReplyDlg::OnBnClickedReplytrue1()
{
// TODO: 在此添加控件通知处理程序代码
CString s;
GetDlgItem(IDE_REPLYCONTENT1)->GetWindowText(s);
Reply crep;
crep.act = curreply->act;
crep.content = s;
crep.replyto = curreply->uuid;
InsertReply(crep);
MessageBox(_T("Reply established!"));
CDialogEx::EndDialog(0);
}
|
8072b8b19afc28d08dcd8b8fbb96495dced81849
|
1fa43a183a4ddb1458da1d6d8c63658b9e720230
|
/黑马程序员/04 程序流程结构/04 程序流程结构/11 练习水仙花数.cpp
|
835daefd84d8d60efde95bb11939afa90b47eeb0
|
[] |
no_license
|
Xgcczs/Cpp-Primer-Plus
|
22ca68c1e3ef27b2d0032f4dda371aeb99de67b8
|
8ba80480156c4ce0e8dca2319508a37852db51ce
|
refs/heads/main
| 2023-09-01T22:10:17.991329
| 2021-10-31T08:10:44
| 2021-10-31T08:10:44
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,394
|
cpp
|
11 练习水仙花数.cpp
|
#include<iostream>
using namespace std;
#include<math.h>
int main11()
{
// 水仙花数:是三位数,且每个位的数字的立方之和等于该数
// 例如: 1^3+5^3+3^3 = 153
// 使用do...while 结构
int num=100;
int num1, num2, num3;
int shuixian=0, Num=0;
//num1 = num / 100;
//num2 = (num % 100) / 10;
//num3 = (num % 100) % 10;
//Num = pow(num1,3)+ pow(num2, 3)+ pow(num3, 3);
//shuixian = num1 * 100 + num2 * 10 + num3;
//cout <<"num1=" << num1 << endl;
//cout << "num2=" << num2 << endl;
//cout << "num3=" << num3 << endl;
//cout << "Num=" << Num << endl;
//cout << "shuixian=" << shuixian << endl;
cout << "使用do...while循环输出水仙花数为:" << endl;
do
{
num1 = num / 100;
num2 = (num % 100) / 10;
num3 = (num % 100) % 10;
Num = pow(num1, 3) + pow(num2, 3) + pow(num3, 3);
shuixian = num1 * 100 + num2 * 10 + num3;
if (Num == shuixian)
{
cout<< Num << endl;
}
num++;
} while (num <= 999);
/*cout << "使用while循环输出水仙花数为:" << endl;
while(num<=999)
{
num1 = num / 100;
num2 = (num % 100) / 10;
num3 = (num % 100) % 10;
Num = pow(num1, 3) + pow(num2, 3) + pow(num3, 3);
shuixian = num1 * 100 + num2 * 10 + num3;
if (Num == shuixian)
{
cout << Num << endl;
}
num++;
}*/
system("pause");
return 0;
}
|
0d320c491fcebdb71d603871c6bd429c4bcee2aa
|
7e65b476c99f903b054b7517717cff58a036ab15
|
/118. Pascal's Triangle.cpp
|
29a4cc0c6ef304f41094c900fa3d0459541ef881
|
[] |
no_license
|
violet73/leetcode101
|
a0a8120b4e3d7d891fad6a5dbaa96e21d8ce597e
|
bc5b9d803f6507c14d5a6129af6da347cf75abc9
|
refs/heads/master
| 2023-07-14T07:56:27.569860
| 2021-08-26T02:49:23
| 2021-08-26T02:49:23
| 368,235,085
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,260
|
cpp
|
118. Pascal's Triangle.cpp
|
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> gen(int numRows) {
vector<vector<int>> res;
if(numRows == 1) {
vector<int> nums;
nums.push_back(1);
res.push_back(nums);
return res;
}
if(numRows == 2) {
vector<int> nums1, nums2;
nums1.push_back(1);
nums2.push_back(1);
nums2.push_back(1);
res.push_back(nums1);
res.push_back(nums2);
return res;
}
res = gen(numRows - 1);
vector<int> newVec;
newVec.push_back(1);
for(int i = 0;i<res[res.size() - 1].size()-1;i++) {
newVec.push_back(res[res.size() - 1][i] + res[res.size() - 1][i+1]);
}
newVec.push_back(1);
res.push_back(newVec);
return res;
}
vector<vector<int>> generate(int numRows) {
return gen(numRows);
}
};
int main() {
Solution s;
vector<vector<int>> res = s.generate(5);
for(auto r : res) {
for(auto rr : r) {
cout << rr << " ,";
}
cout << endl;
}
return 0;
}
|
063c9fe93af03d619cff6676f8b5c6fe3f8d32d1
|
445d6fce837cacdf98444f69003b259702d4dee9
|
/lab9/Source/Character.h
|
fd20d2b6a53921f1b443eed8736fd1be101f6eda
|
[] |
no_license
|
jasonulloa/ITP485-2017
|
3a827f525c58917846f78a058092ad5539a796aa
|
a2b8509c1519c500d863a4eecd314fe6e9ce43c0
|
refs/heads/master
| 2020-03-12T03:32:54.382027
| 2018-04-21T02:05:21
| 2018-04-21T02:05:21
| 130,426,525
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 715
|
h
|
Character.h
|
// Character.h
// Character actor
#pragma once
#include "Actor.h"
#include "Texture.h"
#include "CharacterMoveComponent.h"
#include "SkeletalMeshComponent.h"
#include "Skeleton.h"
class Character : public Actor
{
DECL_ACTOR(Character, Actor);
public:
Character(Game& game);
void BeginPlay() override;
void Tick(float deltaTime) override;
void EndPlay() override;
void BeginTouch(Actor& other) override;
void OnRespawn();
void SetProperties(const rapidjson::Value& properties) override;
private:
Vector3 mRespawnPosition;
// Need pointer to my sprite component to change texture
CharacterMoveComponentPtr mCharMove;
SkeletalMeshComponentPtr mMesh;
SkeletonPtr mSkeleton;
};
DECL_PTR(Character);
|
d54ca9a174b59cfffc88d936efb1269863a4b427
|
03222be2d4e5fb8a8d57f8e4c5c77f94f4577e70
|
/BubbleSort.cpp
|
3a384cf2748625f0ee7ad59055e5c9e0c3746e8c
|
[] |
no_license
|
sharmasubash/SortingInCpp
|
6815b02f0807399af4280d829c8f0c1fff7572de
|
d456db15a9a91b3ab5de6d20f5b69e5b6c8b32c7
|
refs/heads/master
| 2020-04-11T22:37:01.443012
| 2018-12-17T14:27:55
| 2018-12-17T14:27:55
| 162,142,052
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,687
|
cpp
|
BubbleSort.cpp
|
#include <iostream>
using namespace std;
// a[5] = [23,2,4,1,7];
void BubbleSort(int a[],int n){
// input passed BubbleSort(a[5],5)
for (int pass=n-1;pass>=0;pass--){
// 1st iteration starts with 4
// (pass = 4; 4 >0, pass = 4-1)
for (int i=0;i<=pass-1;i++){
//here pass = 4, i is iterator
// second iteration with pass = 3
// third iteration with pass = 2
// fourth and last iteration with pass = 1
if( a[i] > a[i+1]){
// ------ pass 4 ----------------
// i's 1st iteration a[0]>a[1] or 23 > 2 No ( yes , swap positions)
// i's 2nd iteration a[1]>a[2] or 23 > 4 (yes, swap positions)
// i's 3rd iteration a[2]>a[3] or 23 > 1 (yes, swap positions)
// i's 4th iteration a[3]>a[4] or 23 > 7 (yes, swap positions)
// ------ pass 3 -----------------
// i's 1st iteration a[0]>a[1] or 2>4 (No, No Changes)
// i's 2nd iteration a[1]>a[2] or 4>1 (yes, positions)
// i's 3rd iteration a[2]>a[3] or 4>7 (No, No Changes)
// ------ pass 2 -----------------
// i's 1st iteration a[0]>a[1] or 2>1 (yes, swap positions)
//i's 2nd iteration a[1]>a[2] or 2>4 (No, No Changes)
// --------pass 1-----------------
// i's 1st iteration a[0]>a[1] or 1>2 (No, No Changes)
// -------- end ------------------
int temp = a[i];
a[i]=a[i+1];
a[i+1]=temp;
// --------pass 4----------------
// list after first iteration of i a[5]=[2,23,4,1,7]
// list after second iteration of i a[5]=[2,4,23,1,7]
// list after third iteration of i a[5]=[2,4,1,23,7]
// list after fourth iteration of i a[5]=[2,4,1,7,23]
// --------pass 3----------------
// list after first iteration of i a[5]=[2,4,1,7,23]
// list after second iteration of i a[5]=[2,1,4,7,23]
// list after third iteration of i a[5]=[2,1,4,7,23]
// --------pass 2-----------------
// list after 1st iteration of i a[5]=[1,2,4,7,23]
// list after 2nd iteration of i a[5]=[1,2,4,7,23]
// --------pass ------------------
// list after 1st iteration of i a[5]=[1,2,4,7,23]
}
}
}
}
int main()
{
cout<<"Hello World\n";
int a[5] {23,2,3,4,5};
BubbleSort(a, 5);
for (int i = 0; i <5 ; i++){
cout << a[i] << endl;
}
|
0a19a6ec15ee5ff11c150dd1cfbaacd7612d9cb4
|
6d36f647f5118d7170d5a6c0add13550870292f5
|
/include/utils/TimeHelper.h
|
a347b7af8b8e2612d5a6355466f33759ba9cb55c
|
[] |
no_license
|
MarkusWende/JnRMaker
|
9b84368ee6e1a469b5b78e77a28a2e8e66326f1f
|
a8c8aac83c337c7d3c2b223b7f54786526c1ba05
|
refs/heads/master
| 2023-07-15T04:57:04.913746
| 2023-07-03T19:36:14
| 2023-07-03T19:36:14
| 240,896,758
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,546
|
h
|
TimeHelper.h
|
/****************************************************************************
* Copyright (C) 2019 Kirsch-Audio GmbH <software@kirsch-audio.com>
* All rights reserved.
*
* This file is part of ANCMonitor
*
* SoundIMP is a software for creating sound immission predictions.
*
* Unauthorized copying of this file, via any medium is strictly
* prohibited
*
* Proprietary and confidential.
****************************************************************************/
/**
* @file TimeHelper.h
* @brief Time helper namespace.
*
* @author Markus Wende
* https://github.com/MarkusWende
*/
#pragma once
#include <string>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <chrono>
#include <sstream>
#ifdef WIN32
#define localtime_r(_Time, _Tm) localtime_s(_Tm, _Time)
#endif
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds milliseconds;
typedef std::chrono::microseconds microseconds;
typedef std::chrono::seconds seconds;
typedef std::chrono::nanoseconds nanoseconds;
static Clock::time_point timeZero = Clock::now();
namespace TimeHelper
{
/**
* @brief Get the local time as a string.
* @return Return the formnated local time as a string.
*/
inline std::string GetTimeinfo()
{
tm localTime;
std::chrono::system_clock::time_point t = std::chrono::system_clock::now();
time_t now = std::chrono::system_clock::to_time_t(t);
localtime_r(&now, &localTime);
const std::chrono::duration<double> tse = t.time_since_epoch();
std::chrono::seconds::rep milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(tse).count() % 1000;
std::stringstream ss;
ss << (1900 + localTime.tm_year) << '-'
<< std::setfill('0') << std::setw(2) << (localTime.tm_mon + 1) << '-'
<< std::setfill('0') << std::setw(2) << localTime.tm_mday << ' '
<< std::setfill('0') << std::setw(2) << localTime.tm_hour << ':'
<< std::setfill('0') << std::setw(2) << localTime.tm_min << ':'
<< std::setfill('0') << std::setw(2) << localTime.tm_sec << '.'
<< std::setfill('0') << std::setw(3) << milliseconds;
return ss.str();
}
inline long long tic()
{
timeZero = Clock::now();
nanoseconds ns = std::chrono::duration_cast<nanoseconds>(timeZero.time_since_epoch());
return ns.count();
//
}
inline std::string toc(int format = 0)
{
// int delta = 0;
Clock::time_point timeNow = Clock::now();
std::stringstream msg;
if (format == 0)
{
microseconds us = std::chrono::duration_cast<microseconds>(timeNow - timeZero);
msg << "\tTime elapsed " << us.count() << " us\n";
//std::cout << msg.str().c_str() << "\n";
// delta = (int)us.count();
}
else if (format == 1)
{
milliseconds ms = std::chrono::duration_cast<milliseconds>(timeNow - timeZero);
msg << "\tTime elapsed " << ms.count() << " ms\n";
//std::cout << msg.str().c_str() << "\n";
// delta = (int)ms.count();
}
else if (format == 2)
{
seconds s = std::chrono::duration_cast<seconds>(timeNow - timeZero);
msg << "\tTime elapsed " << s.count() << " s\n";
//std::cout << msg.str().c_str() << "\n";
// delta = (int)s.count();
}
else if (format == 3)
{
nanoseconds ns = std::chrono::duration_cast<nanoseconds>(timeNow - timeZero);
msg << "\tTime elapsed " << ns.count() << " ns\n";
//std::cout << msg.str().c_str() << "\n";
// delta = (int)ns.count();
}
return msg.str();
}
}
|
508391eb465f9675c4bb485e26ee61c004e7fc43
|
373035950bdc8956cc0b74675aea2d1857263129
|
/cpp/test-harness/ta3/pub-sub-gen/num-predicate-generators.cc
|
254f5b6e9b1ba2a61ca167c560ac69f7f4673306
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
limkokholefork/SPARTA
|
5d122cd2e920775d61a5404688aabbafa164f22e
|
6eeb28b2dd147088b6e851876b36eeba3e700f16
|
refs/heads/master
| 2021-11-11T21:09:38.366985
| 2017-06-02T16:21:48
| 2017-06-02T16:21:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,722
|
cc
|
num-predicate-generators.cc
|
//*****************************************************************
// Copyright 2013 MIT Lincoln Laboratory
// Project: SPAR
// Authors: OMD
// Description: Implmentation of the num predicate generators
//
// Modifications:
// Date Name Modification
// ---- ---- ------------
// 29 Jan 2013 omd Original Version
//*****************************************************************
#include "num-predicate-generators.h"
#include <algorithm>
#include "common/check.h"
TruncatedPoissonNumGenerator::TruncatedPoissonNumGenerator(
int mean, int seed) : rng_(seed), dist_(mean) {
}
int TruncatedPoissonNumGenerator::operator()(int max) {
int value = dist_(rng_);
value = std::max(value, 1);
value = std::min(value, max);
return value;
}
int TruncatedPoissonNumGenerator::operator()() {
int value = dist_(rng_);
value = std::max(value, 1);
return value;
}
ConstantNumGenerator::ConstantNumGenerator(
int value) : value_(value) {
}
int ConstantNumGenerator::operator()(int max) {
DCHECK(value_ <= max);
return value_;
}
int ConstantNumGenerator::operator()() {
return value_;
}
CoinTossNumGenerator::CoinTossNumGenerator(
int heads, int tails, float prob, int seed) :
rng_(seed), dist_(0.0, 1.0),
heads_(heads), tails_(tails), prob_(prob) {
}
int CoinTossNumGenerator::operator()(int max) {
DCHECK(heads_ <= max);
DCHECK(tails_ <= max);
float value = dist_(rng_);
if (value <= prob_) {
return heads_;
} else {
return tails_;
}
}
int CoinTossNumGenerator::operator()() {
float value = dist_(rng_);
if (value <= prob_) {
return heads_;
} else {
return tails_;
}
}
|
bf14f0c6f78fb3f1da07eb10ada5d34a49653dd2
|
7d1979a1638273fca2d8b3b6db570811dd0b8d66
|
/src/Postprocess.cpp
|
39ec1800732ca09c2c8a07ee60f605d6b6ce13b7
|
[] |
no_license
|
mkloczko/cube
|
36c128186f1d6d1e65403015197ba4cd5f03cf0e
|
ce2ebda9728585cd7083064b1ab600b3263ffce8
|
refs/heads/master
| 2022-07-23T08:50:21.970891
| 2022-07-16T15:35:14
| 2022-07-16T15:35:14
| 131,104,620
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,668
|
cpp
|
Postprocess.cpp
|
#include "Postprocess.hpp"
using std::function;
constexpr GLfloat canvas_vertices[6*2] = {
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0
};
constexpr char vertex_shader[] = "#version 300 es\n"
"in highp vec2 in_position;\n"
"out highp vec2 tex_coord;\n"
"\n"
"void main(void){\n"
" tex_coord = in_position;\n"
" highp vec2 pos = (in_position - vec2(0.5,0.5))*2.0;\n;"
" gl_Position = vec4(pos,0.0,1.0);\n"
"}\n";
constexpr char fragment_shader[] = "#version 300 es\n"
"in highp vec2 tex_coord;\n"
"out highp vec4 outColor;\n"
"uniform highp sampler2D tex;\n"
"uniform highp float pixel_x;\n"
"uniform highp float pixel_y;\n"
"\n"
"void main(void){\n"
" highp vec3 color = vec3(0.0);\n"
" for(int x = 0; x < 3; x++){\n"
" for(int y = 0; y < 3; y++){\n"
" highp float xf = float(x);\n"
" highp float yf = float(y);\n"
" color += texture(tex, tex_coord + vec2( pixel_x*xf, pixel_y*yf)).xyz;\n"
" color += texture(tex, tex_coord + vec2(-pixel_x*xf, pixel_y*yf)).xyz;\n"
" color += texture(tex, tex_coord + vec2( pixel_x*xf, -pixel_y*yf)).xyz;\n"
" color += texture(tex, tex_coord + vec2(-pixel_x*xf, -pixel_y*yf)).xyz;\n"
" }\n"
" }\n"
" color = color/36.0;\n"
" outColor = vec4(color,1.0);\n"
"}\n";
bool Postprocess::initialize(){
glGenFramebuffers(1, &framebuffer);
glGenTextures(1, &tex_color_buffer);
glGenRenderbuffers(1, &renderbuffer);
glGenVertexArrays(1,&canvas_vao);
glGenBuffers(1,&canvas_vb);
glBindVertexArray(canvas_vao);
glBindBuffer(GL_ARRAY_BUFFER,canvas_vb);
glBufferData(GL_ARRAY_BUFFER,6*2*sizeof(GLfloat), canvas_vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindVertexArray(0);
if(program == 0){
program = setShaders(vertex_shader,fragment_shader);
//Set texture positions
GLuint texture_id;
texture_id = glGetUniformLocation(program, "tex");
glUniform1i(texture_id, 0);
glUseProgram(0);
return program != 0;
}
return true;
}
void Postprocess::resize(int x, int y) {
glBindTexture(GL_TEXTURE_2D, tex_color_buffer);
glBindFramebuffer(GL_FRAMEBUFFER,framebuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGB, x, y, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, x, y);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_color_buffer,0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderbuffer);
glUseProgram(program);
GLuint location;
location = glGetUniformLocation(program, "pixel_x");
glUniform1f(location, (1.0/(GLfloat)x));
location = glGetUniformLocation(program, "pixel_y");
glUniform1f(location, (1.0/(GLfloat)y));
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
}
void Postprocess::render(const function<void()>& drawer){
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
drawer();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void Postprocess::draw(){
GLuint location;
glUseProgram(program);
getErr("Postprocess::draw() - enable program");
glBindVertexArray(canvas_vao);
getErr("Postprocess::draw() - bind vao");
glBindBuffer(GL_ARRAY_BUFFER,canvas_vb);
getErr("Postprocess::draw() - bind vb");
location = glGetAttribLocation(program, "in_position");
getErr("Postprocess::draw() - no location for vb");
glVertexAttribPointer(location, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(location);
getErr("Postprocess::draw() - get vb");
glDisable(GL_DEPTH_TEST);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_color_buffer);
getErr("Postprocess::draw() - bind texture");
glDrawArrays(GL_TRIANGLES,0,6);
getErr("Postprocess::draw() - draw arrays call");
glBindBuffer(GL_ARRAY_BUFFER,0);
getErr("Postprocess::draw() - unbind array buffer");
glBindVertexArray(0);
getErr("Postprocess::draw() - unbind vao");
glUseProgram(0);
}
|
7fcb62edc28d67bc88170fbfcefc71f62a007479
|
630e9438530e5b15353cc9b7c013889fa0f7e80d
|
/C++/CS1570/hw9/activist.h
|
912dcc2608e86bf57a14c1fc244799690cabd4f2
|
[] |
no_license
|
dmgardiner25/CS-Classes
|
0402c1d04c4d3cc50a91d7f1d27a7b7d291f0c5e
|
b6eaa2101db532ab986aefb48e531308d795d4bd
|
refs/heads/master
| 2021-06-02T07:44:32.878122
| 2017-11-01T16:13:04
| 2017-11-01T16:13:04
| 80,837,900
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,826
|
h
|
activist.h
|
//Programmer: DAVID GARDINER Date: 11/14/16
//File: activist.h Class: CS1570 A
//Purpose: Definition of the activist class.
#ifndef ACTIVIST_H
#define ACTIVIST_H
#include <string>
#include "town.h"
using namespace std;
//Min and max toxicity allowed
const float MIN_TOXICITY = 0.0;
const float MAX_TOXICITY = 3.0;
//Min and max dignity allowed
const short MIN_DIGNITY = 0;
const short MAX_DIGNITY = 100;
//Default values
const float DEF_TOX = 0.05;
const short DEF_DIG = 100;
const short DEF_X_ACT = -1;
const short DEF_Y_ACT = -1;
const short DEF_STATE = 0;
class activist
{
private:
float toxicity; //Holds the toxicity of the object
short dignity; //Holds the dignity of the object
short xLocation; //Current x-coordinate of the object
short yLocation; //Current y-coordinate of the object
char sprite; //The sprite to represent the object
short state; //-1 is gone, 0 is normal, 1 is cool
string name; //Holds the name of the object
public:
//Description: Default constructor for the activist class.
//Pre: None.
//Post: toxicity has been set to DEF_TOX, dignity has been set to DEF_DIG,
// xLocation has been set to DEF_X_ACT, yLocation has been set to
// DEF_Y_ACT, sprite has been set to spr, and name has been set to n.
activist(const char spr, const string n);
//Description: The setToxicity() function sets toxicity to f.
//Pre: f must be within MIN_TOXICITY and MAX_TOXICITY.
//Post: toxicity is set to f or the program exits.
void setToxicity(float f);
//Description: The setDignity() function sets dignity to s.
//Pre: s must be within MIN_DIGNITY and MAX_DIGNITY.
//Post: dignity is set to s or the program exits.
void setDignity(short s);
//Description: The place_me() function sets the location of and places the
// object in the middle of the town, based on the size of the
// town.
//Pre: None.
//Post: The location of the object is set to the middle of the town and the
// object is placed in the town.
void place_me(town & t);
//Description: The rand_move() function chooses a random direction to move
// in, avoids walls and other objects, and udpates the
// location of the object.
//Pre: None
//Post: The object moves in a random direction, avoiding other entities.
void rand_walk(town & t);
//Description: The operator<<() function displays the object's name,
// toxicity, dignity, location, and state.
//Pre: None.
//Post: The object's name, toxicity, dignity, location, and state are
// output to the screen.
friend ostream& operator<<(ostream & o, const activist & a);
};
#endif
|
a985aefc3d4d700b3861ea4c58579cc2017b38e3
|
a565eef51e8445b519288ac32affbd7adca874d3
|
/libgringo/gringo/output/aggregates.hh
|
2b14bb0316e1b0f514c80c6990ddb753723c24f5
|
[
"MIT"
] |
permissive
|
CaptainUnbrauchbar/clingo
|
b28a9b5218552240ea03444e157a21079fc77019
|
58cb702db83c23aedea28b26a617102fae9b557a
|
refs/heads/master
| 2023-02-27T23:53:44.566739
| 2021-02-01T18:36:10
| 2021-02-01T18:36:10
| 290,831,881
| 1
| 0
|
MIT
| 2021-02-01T18:36:11
| 2020-08-27T16:53:18
|
C++
|
UTF-8
|
C++
| false
| false
| 4,458
|
hh
|
aggregates.hh
|
// {{{ MIT License
// Copyright 2017 Roland Kaminski
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// }}}
#ifndef _GRINGO_OUTPUT_AGGREGATES_HH
#define _GRINGO_OUTPUT_AGGREGATES_HH
#include <gringo/terms.hh>
#include <gringo/domain.hh>
#include <gringo/intervals.hh>
#include <gringo/output/literal.hh>
namespace Gringo { namespace Output {
struct TupleId;
using BodyAggregateElements = UniqueVec<std::pair<TupleId, Formula>, HashFirst<TupleId>, EqualToFirst<TupleId>>;
using HeadFormula = std::vector<std::pair<LiteralId, ClauseId>>;
using HeadAggregateElements = UniqueVec<std::pair<TupleId, HeadFormula>, HashFirst<TupleId>, EqualToFirst<TupleId>>;
using DisjunctiveBounds = IntervalSet<Symbol>;
using Interval = DisjunctiveBounds::Interval;
using ConjunctiveBounds = std::vector<std::pair<Interval, Interval>>;
using PlainBounds = std::vector<std::pair<Relation, Symbol>>;
using LitValVec = std::vector<std::pair<LiteralId, Symbol>>;
using LitUintVec = std::vector<std::pair<LiteralId, unsigned>>;
struct AggregateAnalyzer {
enum Monotonicity { MONOTONE, ANTIMONOTONE, CONVEX, NONMONOTONE };
enum WeightType { MIXED, POSITIVE, NEGATIVE };
enum Truth { True, False, Open };
using ConjunctiveBounds = std::vector<std::pair<Interval, Interval>>;
AggregateAnalyzer(DomainData &data, NAF naf, DisjunctiveBounds const &disjunctiveBounds, AggregateFunction fun, Interval range, BodyAggregateElements const &elems);
void print(std::ostream &out);
LitValVec translateElems(DomainData &data, Translator &x, AggregateFunction fun, BodyAggregateElements const &bdElems, bool incomplete);
Monotonicity monotonicity;
WeightType weightType;
Truth truth;
ConjunctiveBounds bounds;
Interval range;
};
inline Symbol getNeutral(AggregateFunction fun) {
switch (fun) {
case AggregateFunction::COUNT:
case AggregateFunction::SUMP:
case AggregateFunction::SUM: { return Symbol::createNum(0); }
case AggregateFunction::MIN: { return Symbol::createSup(); }
case AggregateFunction::MAX: { return Symbol::createInf(); }
}
assert(false);
return {};
}
LiteralId getEqualClause(DomainData &data, Translator &x, std::pair<Id_t, Id_t> clause, bool conjunctive, bool equivalence);
LiteralId getEqualFormula(DomainData &data, Translator &x, Formula const &formula, bool conjunctive, bool equivalence);
LiteralId getEqualAggregate(DomainData &data, Translator &x, AggregateFunction fun, NAF naf, DisjunctiveBounds const &bounds, Interval const &range, BodyAggregateElements const &bdElems, bool recursive);
class MinMaxTranslator {
public:
LiteralId translate(DomainData &data, Translator &x, AggregateAnalyzer &res, bool isMin, LitValVec &&elems, bool incomplete);
};
struct SumTranslator {
SumTranslator() { }
void addLiteral(DomainData &data, LiteralId const &lit, Potassco::Weight_t weight, bool recursive);
void translate(DomainData &data, Translator &x, LiteralId const &head, Potassco::Weight_t bound, LitUintVec const &litsPosRec, LitUintVec const &litsNegRec, LitUintVec const &litsPosStrat, LitUintVec const &litsNegStrat);
LiteralId translate(DomainData &data, Translator &x, ConjunctiveBounds &bounds, bool convex, bool invert);
LitUintVec litsPosRec;
LitUintVec litsNegRec;
LitUintVec litsPosStrat;
LitUintVec litsNegStrat;
};
} } // namespace Output Gringo
#endif // _GRINGO_OUTPUT_AGGREGATES_HH
|
b54a5675818808c62a9be922c94fed136db69646
|
53b9221c49c159beeddc62c79b034e1e55998003
|
/Cyanide/Cyanide-Core/source/core/FSM.cpp
|
66ba58bd829a799ee2bfc42d950d1e8bf2283586
|
[] |
no_license
|
Jukaio/CPP-Programming
|
9879f53956393f4171f20e7d69911c4823354bce
|
834074f646b62d88e8d927ebe7fb19f55fb647cf
|
refs/heads/master
| 2023-01-28T21:58:25.498709
| 2023-01-24T19:34:45
| 2023-01-24T19:34:45
| 293,497,837
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,021
|
cpp
|
FSM.cpp
|
// FSM.cpp
#include "core/FSM.h"
#include "core/state.h"
#include <SDL.h>
#include <assert.h>
FSM::FSM()
: m_current(nullptr)
{
}
FSM::~FSM()
{
}
void FSM::set_renderer(SDL_Renderer* p_renderer)
{
m_renderer = p_renderer;
}
void FSM::run(int p_ms)
{
if(!m_current)
return;
bool swap = !m_current->core_update(p_ms);
m_current->core_render(m_renderer);
if(swap)
set_state(m_current->get_next());
}
void FSM::add_state(state* p_state)
{
if(p_state)
m_cache.add(p_state->get_id(), p_state);
}
void FSM::remove_state(int p_id)
{
if(m_cache.exists(p_id))
m_cache.remove(p_id);
}
void FSM::set_state(int p_id)
{
if(m_cache.exists(p_id))
{
if(m_current)
m_current->exit();
m_current = m_cache.get(p_id);
m_current->enter(m_renderer);
return;
}
assert(!("Could not switch from %d to %d", m_current->get_id(), p_id));
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not switch from %d to %d", m_current->get_id(), p_id);
}
void FSM::shut_down()
{
if(m_current)
m_current->exit();
}
|
17e86de0be7c8305fefeaa127b9c79bf5bef61bb
|
a3cb407b74d87f8c15fb6f21710175ce37bbe2db
|
/LesPaulToUnoJoy.ino
|
b9a6d8d1e32566ce6f5fc7b7fc1dfe2f478a45fb
|
[] |
no_license
|
laka3000/LesPaulToUnoJoy
|
f6b3e8013916fe40008794c6873dcdf5a07f7f13
|
961720fd1a0ed5192b13b7acca545789497d8273
|
refs/heads/main
| 2023-07-15T18:23:09.243042
| 2021-08-20T13:25:51
| 2021-08-20T13:25:51
| 398,094,157
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,001
|
ino
|
LesPaulToUnoJoy.ino
|
#include "UnoJoy.h"
typedef void (* CallbackArray)(int);
const byte GreenPin = 2;
const byte RedPin = 3;
const byte YellowPin = 4;
const byte BluePin = 5;
const byte OrangePin = 6;
const byte DownPin = 7;
const byte UpPin = 8;
const byte SelectPin = 12;
const byte StartPin = 13;
const byte RedLed = 9;
const byte GreenLed = 10;
const byte BlueLed = 11;
const byte frets[] = {GreenPin, RedPin, YellowPin, BluePin, OrangePin};
const byte inputs[] = {UpPin, DownPin, SelectPin, StartPin};
byte buttons[sizeof(frets) + sizeof(inputs)];
const byte outputPins[3] = {RedLed, GreenLed, BlueLed};
void setup(){
mergeInputs();
setupInputs();
setupLeds();
setupUnoJoy();
}
void mergeInputs() {
memcpy(buttons, frets, sizeof(frets));
memcpy(&buttons[sizeof(frets)], inputs, sizeof(inputs));
}
void setupInputs(void){
for (int i = 0; i < sizeof(buttons); i++){
pinMode(buttons[i], INPUT);
digitalWrite(buttons[i], HIGH);
}
pinMode(A0, INPUT);
digitalWrite(A0, HIGH);
}
void setupLeds() {
for (int i = 0; i < sizeof(outputPins); i++){
pinMode(outputPins[i], OUTPUT);
}
}
void loop(){
dataForController_t controllerData = getControllerData();
setControllerData(controllerData);
setLeds();
}
void setLeds() {
CallbackArray callbacks[] = {
lightGreen,
lightRed,
lightYellow,
lightBlue,
lightOrange
};
for (int pin = sizeof(frets) - 1; pin >= 0; pin--){
if (digitalRead(frets[pin]) == LOW) {
callbacks[pin](NULL);
return;
}
}
lightWhite();
}
void lightGreen() {
digitalWrite(RedLed, LOW);
digitalWrite(GreenLed, HIGH);
digitalWrite(BlueLed, LOW);
}
void lightRed() {
digitalWrite(RedLed, HIGH);
digitalWrite(GreenLed, LOW);
digitalWrite(BlueLed, LOW);
}
void lightYellow() {
analogWrite(RedLed, 200);
analogWrite(GreenLed, 255);
digitalWrite(BlueLed, LOW);
}
void lightBlue() {
digitalWrite(RedLed, LOW);
digitalWrite(GreenLed, LOW);
digitalWrite(BlueLed, HIGH);
}
void lightOrange() {
analogWrite(RedLed, 240);
analogWrite(GreenLed, 255);
digitalWrite(BlueLed, LOW);
}
void lightWhite() {
analogWrite(RedLed, 127);
analogWrite(GreenLed, 255);
analogWrite(BlueLed, 255);
}
dataForController_t getControllerData(void){
dataForController_t controllerData = getBlankDataForController();
controllerData.squareOn = !digitalRead(GreenPin);
controllerData.crossOn = !digitalRead(RedPin);
controllerData.circleOn = !digitalRead(YellowPin);
controllerData.triangleOn = !digitalRead(BluePin);
controllerData.l1On = !digitalRead(OrangePin);
controllerData.dpadUpOn = !digitalRead(UpPin);
controllerData.dpadDownOn = !digitalRead(DownPin);
controllerData.selectOn = !digitalRead(SelectPin);
controllerData.startOn = !digitalRead(StartPin);
controllerData.leftStickX = analogRead(A0) >> 2;
return controllerData;
}
|
a55e85c9d7eef3b4bdf6a58fc8d11ec69c6ba54b
|
f4a0a9788e83ffd186d9520d4f8491e1183cd3b6
|
/Assignment2_luint.cpp
|
63ad43a53d97b559e4b7926c51f6fbe3010b8627
|
[] |
no_license
|
saikiranpalimpati/Algorithm-Analysis
|
a5d18bb9adecaf1bbe81f9795710f98a640fb02d
|
1e38246ddbc57dd73d557dafc672af01447c4bc3
|
refs/heads/master
| 2020-04-02T15:02:33.313329
| 2018-10-24T18:49:40
| 2018-10-24T18:49:40
| 154,549,662
| 0
| 0
| null | 2018-10-31T17:22:09
| 2018-10-24T18:33:10
|
C++
|
UTF-8
|
C++
| false
| false
| 2,728
|
cpp
|
Assignment2_luint.cpp
|
#include "luint.h"
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
luint::luint()
{
}
luint::~luint()
{
}
//*******************************************************************
// Method:parameterized constructor
// Parameters: unsigned int
// Taking an unsigned int and storing them in a vector
//********************************************************************
luint::luint(unsigned int v)
{
unsigned int nsz = pow(10, dpn) + .5;
while (v != 0)
{
num.push_back(v % nsz);
v = v / nsz;
}
}
//*******************************************************************
// Method:operator+
// Parameters: two objects
//Taking two objects and then adding them
//********************************************************************
luint operator+(const luint & obj1, const luint & obj2)
{
luint tempobject;
int carry = 0;
vector<unsigned int>::const_iterator pointer1 = obj1.num.begin();
vector<unsigned int>::const_iterator pointer2 = obj2.num.begin();
int minimumsize = min(obj1.num.size(), obj2.num.size());
int nsz = pow(10, tempobject.dpn) + .5;
int i = 0;
while (i < minimumsize)
{
tempobject.num.push_back((carry + *pointer1 + *pointer2) % nsz);
carry = (carry + *pointer1 + *pointer2) / nsz;
pointer1++;
pointer2++;
i++;
}
// object1 has more values than object2
while (pointer1 != obj1.num.end()) {
// a has some values left maybe
tempobject.num.push_back((*pointer1 + carry) % nsz);
carry = (carry + *pointer1) / nsz;
pointer1++;
}
// object2 has more values than object1
while (pointer2 != obj2.num.end()) {
tempobject.num.push_back((*pointer2 + carry) % nsz);
carry = (carry + *pointer2) / nsz;
pointer2++;
}
//rest digits as carry to be pushed
if (carry != 0)
{
tempobject.num.push_back(carry);
}
return tempobject;
}
//*******************************************************************
// Method:operator*
// Parameters: two objects
//Taking two objects and then multiplying them
//********************************************************************
luint operator*(const luint & obj1, const luint & obj2) {
luint ans;
int carry = 0;
//list<unsigned int>::const_iterator tptr
int nsz = pow(10, ans.dpn) + .5;
for (vector<unsigned int>::const_reverse_iterator it1 = obj1.num.rbegin(); it1 != obj1.num.rend(); it1++)
{
for (vector<unsigned int>::const_reverse_iterator it2 = obj2.num.rbegin(); it2 != obj2.num.rend(); it2++)
{
ans.num.push_back((carry + (*it1 * *it2)) % nsz);
carry = (carry + (*it1 * *it2)) / nsz;
}
}
if (carry != 0)
{
ans.num.push_back(carry);
}
return ans;
}
|
b8c48ff51032dc73e85841f21c6a07a87abf0a45
|
2fc013d8c5dbc5c36ab9135e2a03a49710bc29f1
|
/main.cpp
|
161d19131391773ae4d1a456cb9ec4cd43b74b10
|
[] |
no_license
|
arashparnia/GA
|
da6e012e995b07906aa41955e34d90e3ec3458d1
|
38df9e48f51350499edc257477570c3ef535dff3
|
refs/heads/master
| 2021-01-11T07:23:26.299454
| 2016-10-25T18:07:08
| 2016-10-25T18:07:08
| 71,832,208
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,024
|
cpp
|
main.cpp
|
#include <iostream>
#include "Chromosome.h"
#include "Population.h"
int main() {
// float a1[] = {1.1,4.5,8.6,9.2};
// float a2[] = {4.2,6.7,2.8,5.3};
//
// Chromosome* c1 = new Chromosome(4);
// Chromosome* c2 = new Chromosome(4);
//
// c1->setChromosome(a1);
// c2->setChromosome(a2);
//
// for (int i = 0; i < c1->getlength(); ++i) {
// std::cout << " "<< c1->getChromosomeAtIndex(i);
// }
// std::cout<< ""<< std::endl;
//
// for (int i = 0; i < c2->getlength(); ++i) {
// std::cout << " "<< c2->getChromosomeAtIndex(i);
// }
Population *pop = new Population(100);
for (int j = 0; j < 100; ++j) {
pop->insertChromosomeToPopulation(pop->CreateRandomChromosome());
}
std::vector<Chromosome *> v = pop->getPop();
for (int k = 0; k < v.size(); ++k) {
for (int i = 0; i < v.at(k)->getlength(); ++i) {
std::cout << " " << v.at(k)->getChromosomeAtIndex(i);
}
std::cout << std::endl;
}
return 0;
}
|
2eb33c98e4db2b0ee96a1a6dfbedc8f71b6d1465
|
c2484df95f009d516bf042dca93857b43a292333
|
/codeforces/round314/b/main.cpp
|
15f139c6f4f21d27bcda75f3d30237d9ccb42245
|
[
"Apache-2.0"
] |
permissive
|
seirion/code
|
545a78c1167ca92776070d61cd86c1c536cd109a
|
a59df98712c7eeceabc98f6535f7814d3a1c2c9f
|
refs/heads/master
| 2022-12-09T19:48:50.444088
| 2022-12-06T05:25:38
| 2022-12-06T05:25:38
| 17,619,607
| 14
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 653
|
cpp
|
main.cpp
|
// codeforces round314
// http://codeforces.com/contest/567/problem/B
#include <iostream>
#include <cstdio>
#include <set>
using namespace std;
int main() {
set<int> s;
char c;
int n, in, maxi = 0;
scanf("%d\n", &n);
for (int i = 0; i < n; i++) {
scanf("%c %d\n", &c, &in);
if (c == '+') {
s.insert(in);
maxi = max(maxi, (int)s.size());
}
else { // '-'
if (s.find(in) == s.end()) { // not found
maxi++;
}
else { // found
s.erase(in);
}
}
}
printf("%d\n", maxi);
return 0;
}
|
55f15e83e9e254c4c49d9ce9e304030290868b7e
|
1ee4d0cfe6d309cea35f0e658c7f1c31b4ec9669
|
/Source/LabelledSlider.h
|
5ab235598b4e8619217e2e59fd8c678152910c1d
|
[
"MIT"
] |
permissive
|
iomeone/WeirdDrums
|
53417416f4a0850af4bbe664a792623c5faeae69
|
6b2cd2525913109d05ab08bcaf559189b8ea529d
|
refs/heads/master
| 2020-06-07T02:46:21.198856
| 2019-04-12T09:46:22
| 2019-04-12T09:46:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 800
|
h
|
LabelledSlider.h
|
/*
==============================================================================
LabelledSlider.h
Created: 5 Mar 2019 8:38:02am
Author: dfila
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
class LabelledSlider : public Component
{
public:
//==============================================================================
LabelledSlider (juce::String label);
~LabelledSlider();
//==============================================================================
void paint(Graphics&) override = 0;
void resized() override = 0;
//==============================================================================
Slider* getSlider();
protected:
Slider m_slider;
Label m_nameLabel;
};
|
461fd394329a67555f46a2173a99c3fe08b05bca
|
fa04d2f56c8d4ebfb931968392811a127a4cb46c
|
/trunk/Cities3D/src/StandardRules/DrawRobberObject.cpp
|
0259a6376e0930098d59398d40fbbfc1f4430973
|
[] |
no_license
|
andrewlangemann/Cities3D
|
9ea8b04eb8ec43d05145e0b91d1c542fa3163ab3
|
58c6510f609a0c8ef801c77f5be9ea622e338f9a
|
refs/heads/master
| 2022-10-04T10:44:51.565770
| 2020-06-03T23:44:07
| 2020-06-03T23:44:07
| 268,979,591
| 0
| 0
| null | 2020-06-03T03:25:54
| 2020-06-03T03:25:53
| null |
UTF-8
|
C++
| false
| false
| 8,766
|
cpp
|
DrawRobberObject.cpp
|
/*
* Cities3D - Copyright (C) 2001-2009 Jason Fugate (saladyears@gmail.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
#include "stdwx.h"
#include "style.h" //READ THIS BEFORE MAKING ANY CHANGES TO THIS FILE!!!
//---------------------------- SYSTEM INCLUDES -----------------------------//
//---------------------------- USER INCLUDES -----------------------------//
#include "DrawRobberObject.h"
#include "RobberObject.h"
#include "GLTextures.h"
#include "GLMaterial.h"
#include "RuleSetDatabase.h"
#include "ConfigDatabase.h"
#include "define/defineGL.h"
#include "UtilityGL.h"
//---------------------------- TYPEDEFS -----------------------------//
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
//---------------------------- STATICS -----------------------------//
namespace
{
//display lists
const wxInt32 NUM_LISTS_ROBBER = 2;
GLuintArray sLists_Robber;
enum
{
Robber = 0,
RobberGouraud ,
};
//robber dimensions
const wxInt32 GL_ROBBER_SLICE = 15;
const wxInt32 GL_ROBBER_STACK = 20;
GLUquadricObj *sQuad_Robber;
//gouraud normals
Vector sNormals[GL_ROBBER_STACK][GL_ROBBER_SLICE];
double sRadii[GL_ROBBER_STACK];
double sHeight = 3.0;
Vector calcGouraudVector(wxInt32 i, wxInt32 j)
{
wxInt32 k;
wxInt32 iNum = 2;
Vector normal;
//set wrap
k = (j == 0) ? GL_ROBBER_SLICE - 1 : j - 1;
//get lower faces
if(i > 0)
{
normal += sNormals[i - 1][j];
normal += sNormals[i - 1][k];
iNum = 4;
}
//get upper faces
normal += sNormals[i][j];
normal += sNormals[i][k];
//average
normal /= iNum;
//normalize
normal.Normalize();
return normal;
}
//the robber
void buildRobber(GLuint id)
{
wxInt32 i, j, k;
double dTwoPi = 360 * D2R;
double dH;
double dT;
Vector v1, v2;
Vector points[GL_ROBBER_STACK][GL_ROBBER_SLICE];
Vector gouraud;
sRadii[19] = 0.0;
sRadii[18] = 0.33;
sRadii[17] = 0.42;
sRadii[16] = 0.47;
sRadii[15] = 0.5;
sRadii[14] = 0.47;
sRadii[13] = 0.40;
//start increase for thick middle part
sRadii[12] = 0.49;
sRadii[11] = 0.57;
sRadii[10] = 0.65;
sRadii[9] = 0.67;
sRadii[8] = 0.69;
sRadii[7] = 0.70;
sRadii[6] = 0.69;
sRadii[5] = 0.67;
sRadii[4] = 0.61;
sRadii[3] = 0.52;
sRadii[2] = 0.4;
sRadii[1] = 0.55;
sRadii[0] = 0.55;
//create points
for(i = 0; i < GL_ROBBER_STACK; i++)
{
//calculate height
dH = (sHeight / GL_ROBBER_STACK) * i;
for(j = 0; j < GL_ROBBER_SLICE; j++)
{ //calculate theta
dT = (dTwoPi / GL_ROBBER_SLICE) * j;
//create point
points[i][j] = Vector(sRadii[i] * cos(dT), dH,
sRadii[i] * sin(dT));
}
}
//create face normals
for(i = 0; i < GL_ROBBER_STACK - 1; i++)
{
for(j = 0; j < GL_ROBBER_SLICE; j++)
{
//set wrap around
k = (j < GL_ROBBER_SLICE - 1) ? j : -1;
//create face vectors
v1 = points[i][j] - points[i][k + 1];
v2 = points[i + 1][k + 1] - points[i][k + 1];
//create face normal
sNormals[i][j] = CrossProduct(v1, v2);
sNormals[i][j].Normalize();
}
}
//build the robber
glNewList(id, GL_COMPILE);
//draw
for(i = 0; i < GL_ROBBER_STACK - 1; i++)
{
for(j = 0; j < GL_ROBBER_SLICE; j++)
{
//set wrap around
k = (j < GL_ROBBER_SLICE - 1) ? j : -1;
glBegin(GL_QUADS);
//normal
glNormal3d(sNormals[i][j].x, sNormals[i][j].y,
sNormals[i][j].z);
//two bottom points
glVertex3d(points[i][j].x, points[i][j].y, points[i][j].z);
glVertex3d(points[i][k + 1].x, points[i][k + 1].y,
points[i][k + 1].z);
//two top points
glVertex3d(points[i + 1][k + 1].x, points[i + 1][k + 1].y,
points[i + 1][k + 1].z);
glVertex3d(points[i + 1][j].x, points[i + 1][j].y,
points[i + 1][j].z);
glEnd();
}
}
//finish up
glEndList();
//build gouraud robber
glNewList(id + 1, GL_COMPILE);
//draw
for(i = 0; i < GL_ROBBER_STACK - 1; i++)
{
for(j = 0; j < GL_ROBBER_SLICE; j++)
{
//set wrap around
k = (j < GL_ROBBER_SLICE - 1) ? j : -1;
glBegin(GL_QUADS);
//two bottom points
gouraud = calcGouraudVector(i, j);
glNormal3d(gouraud.x, gouraud.y, gouraud.z);
glVertex3d(points[i][j].x, points[i][j].y,
points[i][j].z);
gouraud = calcGouraudVector(i, j + 1);
glNormal3d(gouraud.x, gouraud.y, gouraud.z);
glVertex3d(points[i][k + 1].x, points[i][k + 1].y,
points[i][k + 1].z);
//two top points
gouraud = calcGouraudVector(i + 1, j + 1);
glNormal3d(gouraud.x, gouraud.y, gouraud.z);
glVertex3d(points[i + 1][k + 1].x, points[i + 1][k + 1].y,
points[i + 1][k + 1].z);
gouraud = calcGouraudVector(i + 1, j);
glNormal3d(gouraud.x, gouraud.y, gouraud.z);
glVertex3d(points[i + 1][j].x, points[i + 1][j].y,
points[i + 1][j].z);
glEnd();
}
}
//finish up
glEndList();
}
void obtainPrivate_RobberObject()
{
//display lists
sLists_Robber.reset(new GLuint[NUM_LISTS_ROBBER]);
//generate
for(wxInt32 i = 0; i < NUM_LISTS_ROBBER; i++)
{
sLists_Robber[i] = glGenLists(1);
}
//create the lists
buildRobber(sLists_Robber[Robber]);
sQuad_Robber = gluNewQuadric();
//turn on textures
gluQuadricTexture(sQuad_Robber, GL_TRUE);
gluQuadricOrientation(sQuad_Robber, GLU_OUTSIDE);
}
void releasePrivate_RobberObject()
{
//clear out display lists
glDeleteLists(sLists_Robber[0], NUM_LISTS_ROBBER);
gluDeleteQuadric(sQuad_Robber);
}
void drawRobber()
{
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glScaled(1.2, 1.2, 1.2);
if(TRUE == CONFIG.read<wxInt32>(swConfigSectionOpenGL,
swRobberGouraud, TRUE))
{
glCallList(sLists_Robber[RobberGouraud]);
}
else
{
glCallList(sLists_Robber[Robber]);
}
glPopMatrix();
glEnable(GL_TEXTURE_2D);
}
void drawRobberOutline()
{
float rad = sRadii[GL_ROBBER_STACK / 2] * 1.2;
//top ring
glPushMatrix();
glTranslated(0.0, sHeight / 2.0f, 0.0);
glRotated(90.0, 1.0, 0.0, 0.0);
gluDisk(sQuad_Robber, rad, rad + 0.1, 20, 5);
glPopMatrix();
}
}
//---------------------------- PUBLIC -----------------------------//
IMPLEMENT_DRAW_OBJECT(DrawRobberObject, RobberObject, STANDARD);
DrawRobberObject::DrawRobberObject(const GameObjectPtr &object)
: DrawObject(object, 10)
{
}
DrawRobberObject::~DrawRobberObject()
{
}
bool DrawRobberObject::CanSelect(const Vector &origin, const Vector &ray,
float &distance, wxInt32 &id, bool popup)
{
bool hit = false;
IGameObject *object = GetObject();
if( (NULL != object) &&
((object->isset(IGameObject::Select)) ||
(true == popup)))
{
float rayLength;
Vector plane;
const Vector &o = object->coords();
const float slice = sHeight / GL_ROBBER_STACK;
// Go through each of the robber slices, seeing if we intersect.
for(wxInt32 i = 0; i < GL_ROBBER_STACK; ++i)
{
// Determine height at this point.
float height = slice * i;
float radSquared = sRadii[i] * sRadii[i];
float localDist, xDist, zDist;
UtilityGL::planeCoords(height, origin, ray, plane, rayLength);
xDist = o.x - plane.x;
zDist = o.z - plane.z;
localDist = (xDist * xDist) + (zDist * zDist);
// If it's within the radius amount, it's a hit.
if(radSquared >= localDist)
{
id = object->id();
distance = rayLength;
hit = true;
break;
}
}
}
return hit;
}
void DrawRobberObject::Obtain()
{
obtainPrivate_RobberObject();
}
void DrawRobberObject::Release()
{
releasePrivate_RobberObject();
}
void DrawRobberObject::PopupFunction(wxString& name, wxString&,
wxBitmap&, bool &, ColorType&)
{
name = stRobber;
}
void DrawRobberObject::RenderOutline() const
{
}
void DrawRobberObject::RenderSelection() const
{
DrawObject::material(Selection).UseMaterial();
drawRobberOutline();
}
void DrawRobberObject::RenderModel(const wxInt32) const
{
GLfloat amb[] = {0.0f, 0.0f, 0.0f, 0.0f};
GLfloat dif[] = {0.25f, 0.25f, 0.25f, 0.0f};
glMaterialfv(GL_FRONT, GL_AMBIENT, amb);
glMaterialfv(GL_FRONT, GL_DIFFUSE, dif);
drawRobber();
DrawObject::material(White).UseMaterial();
}
//---------------------------- PROTECTED -----------------------------//
//---------------------------- PRIVATE -----------------------------//
|
7c9456ace5749557a5d3fffe7f1ad8775703aa09
|
88f1ecced6c151aa8f313db7d457ebd4aec5ec7f
|
/MultipleFileClass/MultipleFileClass/Graph.cpp
|
dc9e9ac4aa49e0486c59a2c1660cce6479402e67
|
[] |
no_license
|
kalyanramu/LocalGitRepo
|
a99f239a4d3bb71fe820f67064bf265fbbe47a53
|
d73c4c95b07988ac1ba3b1093c24efd0c05b37cd
|
refs/heads/master
| 2021-01-19T11:03:09.682042
| 2013-11-06T17:38:43
| 2013-11-06T17:38:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,092
|
cpp
|
Graph.cpp
|
#include "Graph.h"
//Graph Building Functions
Graph::Graph()
{
numEdges = 0;
}
Graph::Graph(std::ifstream& infile)
{
//std::ifstream infile;
//Create vector of vertices
std::list<edge> temp;
G.push_back(temp); //Dummy Node at Index 0
numEdges =0;
std::string line;
while(getline(infile,line))
UpdateGraph(line);
numEdges/=2; //Since it is an undirected graph
infile.close();
}
void Graph::UpdateGraph(std::string line)
{
std::stringstream linestream(line);
int Vertex1, Vertex2,cost;
int iter=0;
std::string sub;
while(!linestream.eof())
{
linestream >> sub;
if (iter++ ==0)
{
Vertex1 = std::stoi(sub);
std::list<edge> temp;
G.push_back(temp);
//std::cout << Vertex1 << "--";
}
else
{
std::stringstream edgeinfo(sub);
edgeinfo >> Vertex2;
//std::cout << Vertex2 << ",";
edgeinfo.ignore(); //Ignore ","
edgeinfo >> cost;
//std::cout << cost<<"\t";
add_edge(Vertex1,Vertex2);
set_edge_value(Vertex1,Vertex2,cost);
}
};
//std::cout << std::endl;
}
Graph::~Graph()
{
}
//Create a Graph with N vertice and no edges
void Graph::create_graph(int numVertices)
{
//Node Vertex Numbering Starts from 1, so leave the first vertex and don't do anything on it.
std::list<edge> temp;
//Revserve space for vertices+1 to increase performance
G.reserve(numVertices+1);
//Create vector of vertices
G.push_back(temp); //Dummy Node at Index 0
for(int i=1; i< numVertices+1; i++)
G.push_back(temp);
}
void Graph::create_random_graph(int numVertices, double density) // Create a random graph with N vertices
{
//srand(time(NULL));
double cost;
//Create a graph with vertices and no edges
create_graph(numVertices);
numEdges =0;
//Create Edges in the Graph
for (int i = 1; i < numVertices+1; i++)
for (int j=i+1; j < numVertices+1; j++)
{
if( getRandomNumber(0.0,1.0)<= density)
{
add_edge(i,j);
add_edge(j,i);
cost = getRandomNumber(1.0,10.0);//Get a number between 1 and 10;
set_edge_value(i,j,cost);
set_edge_value(j,i,cost);
numEdges++; //Update NumEdges
}
}
}
// Adds to G the edge from x to y, if it is not there.
void Graph::add_edge (int source, int dest)
{
//Check if the source, dest exist
//Check if the edge exists
if (FindEdgeInList(G[source], dest) == G[source].end())
{
//If edge doesn't exist, add it to the list
edge E1(dest);
edge E2(source);
G[source].push_back(E1);
//G[dest].push_back(E2);
numEdges++;
}
}
// removes the edge from x to y, if it is there
void Graph::delete_edge (int source, int dest){
//Check if edge exist (check source, vertex exist
//Check if the edge exists
if (FindEdgeInList(G[source], dest) != G[source].end())
{
edge E1(dest);
edge E2(source);
G[source].remove(E1);
G[dest].remove(E2);
numEdges --;
}
}
//Property Nodes
// sets the value associated with the node N to value.
void Graph::set_node_value(int node, int value)
{
}
// get_node_value: returns the value associated with the node x.
int Graph::get_node_value (int node)
{
return 0;
}
//get_edge_value: returns the value associated to the edge (x,y).
double Graph::get_edge_value(int source, int dest)
{
//Check if edge exists
//If exists, get the value
std::list<edge>::iterator it;
//Find iterator the destination vertex and replace cost of the edge
it = FindEdgeInList(G[source], dest);
if (it != G[source].end())
return (*it).edgeCost;
else
return std::numeric_limits<double>::infinity();
}
// set_edge_value: sets the value associated to the edge (x,y) to v.
void Graph::set_edge_value (int source, int dest, double value)
{
//Check if edge exists
//If exists, get the value
std::list<edge>::iterator it;
//Find iterator the destination vertex, if you don't find it add it to the list
it = FindEdgeInList(G[source], dest);
if (it == G[source].end())
{
add_edge (source,dest);
//iterator is at the end of the list, decrement it by 1 to point to the
// newly add value
it--;
}
//Replace cost of the edge
(*it).edgeCost = value;
}
//Vertices: returns the number of vertices in the graph
int Graph::num_vertices()
{
return G.size()-1; //Remove 1 as vertex indexing starts from 1
}
//Edges: returns the number of edges in the graph
int Graph::num_edges()
{
return numEdges;
}
// IsAdjacent: tests whether there is an edge from node source to node dest.
bool Graph::is_adjacent (int source, int dest)
{
std::list<edge>::iterator it = FindEdgeInList(G[source],dest);
if (it == G[source].end())
return false;
else
return true;
}
// Neighbors:lists all nodes y such that there is an edge from source to dest
std::list<edge> Graph::neighbors (int source)
{
return G[source];
}
//Find the iterator to destination vertex in the edge list
std::list<edge>::iterator Graph::FindEdgeInList(std::list<edge>& edges, int destVertex)
{
std::list<edge>::iterator it = edges.begin();
std::list<edge>::iterator end = edges.end();
edge temp;
while (it != end)
{
temp = *it;
if ( temp.destVertexId == destVertex)
return it;
it++;
}
return end; //End will equivalent to null pointer
}
void Graph::printGraph(std::ostream& out)
{
}
std::ostream& operator << (std::ostream& out, Graph& Gr)
{
out << "Printing Graph" << std::endl;
std::list<edge> Edges;
std::list<edge>::iterator it;
std::list<edge>::iterator begin;
std::list<edge>::iterator end;
size_t numRows= Gr.num_vertices()+1;
for (size_t row=1; row < numRows ; row++ )
{
out << row;
Edges = Gr.neighbors(row);
begin = Edges.begin();
end = Edges.end();
if(begin !=end)
{
for (it = begin; it != end; it++)
out << "->" << it->destVertexId;
}
out << std::endl;
}
return out;
}
inline double Graph::getRandomNumber(double low, double high)
{
return ((double)rand()) / RAND_MAX * (high-low) + low;
}
|
75ae0ca1d48e931be01950af9f418c2d2397a865
|
bb136f87f824362abba620f5cb131f5ed77d7c3c
|
/Galactic Wars/Enemy.h
|
d30400418fb4912354d3ae96e2fcd4fa0690e5ac
|
[] |
no_license
|
Matematyk0606/Galactic-Wars
|
7f2d546af756d1f2d8968bb1534ccfe9339e34ac
|
6009a5e18b59335146585b2a2cf63742a68b843d
|
refs/heads/master
| 2021-06-24T12:00:27.411445
| 2020-10-16T15:26:53
| 2020-10-16T15:26:53
| 141,497,922
| 0
| 0
| null | null | null | null |
WINDOWS-1250
|
C++
| false
| false
| 591
|
h
|
Enemy.h
|
#pragma once
#include <SFML/Graphics.hpp>
#include "GraphicsController.h"
#include "Animation.h"
#include "Weapon.h"
using namespace std;
using namespace sf;
class Enemy : public Sprite
{
public:
Enemy();
Enemy(string texturePath, unsigned int HP);
~Enemy();
int getHP();
float getSpeed();
void setHP(int newHP);
void setSpeed(float newSpeed);
void fireTheBullet(); // Wystrzał pocisku
static vector<Enemy*> getEnemiesList();
Weapon weapon;
Animation a_death; // Animacja śmierci, a_ = animation
private:
int HP;
float speed;
static vector<Enemy*> enemiesList;
};
|
280407e65af6f60e33ef2f54504d3cc25107e916
|
75db4c12f2fc91bbcb2e51ea570a51d2c4b411b1
|
/448. Find All Numbers Disappeared in an Array.cpp
|
432db385df616b69d1ebb2bdb30bf72bd7c7bb7b
|
[] |
no_license
|
OnlyCaptain/leetcode
|
1465a8400755faaa23543920ead1c4e439f9107e
|
4726e9c5619f0972d82aabe73257a9af857f86e6
|
refs/heads/master
| 2021-06-14T03:47:04.660278
| 2021-03-30T13:26:33
| 2021-03-30T13:26:33
| 176,669,597
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 604
|
cpp
|
448. Find All Numbers Disappeared in an Array.cpp
|
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
for (int i = 0; i < nums.size(); i ++) {
if (nums[i] == 0) continue;
int last = nums[i], tmp;
while (last != 0) {
tmp = nums[last-1];
nums[last-1] = 0;
last = tmp;
}
}
vector<int> ans;
for (int i = 0; i < nums.size(); i ++) {
if (nums[i] != 0) ans.push_back(i+1);
}
return ans;
}
};
int main() {
}
|
f23fdc09a5aef93a64091627891f2392fc51c04b
|
6ea344a7d8a7daab89f78f60a12b2b6a9b338796
|
/src/gc.cc
|
be91d100d62bab4a29bfb1bbaeba9996fa13d1bf
|
[
"MIT"
] |
permissive
|
diogogmt/candor
|
f65cdcc27de00a724e6277ebb93897fabc2a2a35
|
3ed508733748287d2b28d7f7f5658194264b4177
|
refs/heads/master
| 2020-04-08T04:51:34.966423
| 2012-03-09T21:19:53
| 2012-03-09T21:19:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,716
|
cc
|
gc.cc
|
#include "gc.h"
#include "heap.h"
#include "heap-inl.h"
#include <sys/types.h> // off_t
#include <stdlib.h> // NULL
#include <assert.h> // assert
namespace candor {
namespace internal {
void GC::GCValue::Relocate(char* address) {
if (slot_ != NULL) {
*slot_ = address;
}
if (!value()->IsGCMarked()) value()->SetGCMark(address);
}
void GC::CollectGarbage(char* stack_top) {
assert(grey_items()->length() == 0);
assert(black_items()->length() == 0);
// __$gc() isn't setting needs_gc() attribute
if (heap()->needs_gc() == Heap::kGCNone) {
heap()->needs_gc(Heap::kGCNewSpace);
}
// Select space to GC
Space* space = heap()->needs_gc() == Heap::kGCNewSpace ?
heap()->new_space()
:
heap()->old_space();
// Temporary space which will contain copies of all visited objects
Space tmp_space(heap(), space->page_size());
// Add referenced in C++ land values to the grey list
ColourHandles();
// Colour on-stack registers
ColourStack(stack_top);
while (grey_items()->length() != 0) {
GCValue* value = grey_items()->Shift();
// Skip unboxed address
if (value->value() == NULL || HValue::IsUnboxed(value->value()->addr())) {
continue;
}
if (!value->value()->IsGCMarked()) {
// Object is in not in current space, don't move it
if (!IsInCurrentSpace(value->value())) {
if (!value->value()->IsSoftGCMarked()) {
// Set soft mark and add item to black list to reset mark later
value->value()->SetSoftGCMark();
black_items()->Push(value);
GC::VisitValue(value->value());
}
continue;
}
HValue* hvalue;
if (heap()->needs_gc() == Heap::kGCNewSpace) {
// New space GC
hvalue = value->value()->CopyTo(heap()->old_space(), &tmp_space);
} else {
// Old space GC
hvalue = value->value()->CopyTo(&tmp_space, heap()->new_space());
}
value->Relocate(hvalue->addr());
GC::VisitValue(hvalue);
} else {
value->Relocate(value->value()->GetGCMark());
}
}
// Reset marks for items from external space
while (black_items()->length() != 0) {
GCValue* value = black_items()->Shift();
assert(value->value()->IsSoftGCMarked());
value->value()->ResetSoftGCMark();
}
// Visit all weak references and call callbacks if some of them are dead
HandleWeakReferences();
space->Swap(&tmp_space);
// Reset GC flag
heap()->needs_gc(Heap::kGCNone);
}
void GC::ColourHandles() {
HValueRefList::Item* item = heap()->references()->head();
while (item != NULL) {
HValueReference* ref = item->value();
grey_items()->Push(
new GCValue(ref->value(), reinterpret_cast<char**>(ref->reference())));
grey_items()->Push(
new GCValue(ref->value(), reinterpret_cast<char**>(ref->valueptr())));
item = item->next();
}
}
void GC::ColourStack(char* stack_top) {
// Go through the stack
char** top = reinterpret_cast<char**>(stack_top);
for (; top != NULL; top++) {
// Once found enter frame signature
// skip stack entities until last exit frame position (or NULL)
while (top != NULL && *reinterpret_cast<uint32_t*>(top) == 0xFEEDBEEF) {
top = *reinterpret_cast<char***>(top + 1);
}
if (top == NULL) break;
// Skip rbp as well
if (HValue::GetTag(*(top + 1)) == Heap::kTagCode) {
top++;
continue;
}
char* value = *top;
// Skip NULL pointers, non-pointer values and rbp pushes
if (value == NULL || HValue::IsUnboxed(value)) continue;
// Ignore return addresses
HValue* hvalue = HValue::Cast(value);
if (hvalue == NULL || hvalue->tag() == Heap::kTagCode) continue;
grey_items()->Push(new GCValue(hvalue, top));
}
}
void GC::HandleWeakReferences() {
HValueWeakRefList::Item* item = heap()->weak_references()->head();
while (item != NULL) {
HValueWeakRef* ref = item->value();
if (!ref->value()->IsGCMarked()) {
if (IsInCurrentSpace(ref->value())) {
// Value is in GC space and wasn't marked
// call callback as it was GCed
ref->callback()(ref->value());
HValueWeakRefList::Item* current = item;
item = item->next();
heap()->weak_references()->Remove(current);
continue;
}
} else {
// Value wasn't GCed, but was moved
ref->value(reinterpret_cast<HValue*>(ref->value()->GetGCMark()));
}
item = item->next();
}
}
bool GC::IsInCurrentSpace(HValue* value) {
return (heap()->needs_gc() == Heap::kGCOldSpace &&
value->Generation() >= Heap::kMinOldSpaceGeneration) ||
(heap()->needs_gc() == Heap::kGCNewSpace &&
value->Generation() < Heap::kMinOldSpaceGeneration);
}
void GC::VisitValue(HValue* value) {
switch (value->tag()) {
case Heap::kTagContext:
return VisitContext(value->As<HContext>());
case Heap::kTagFunction:
return VisitFunction(value->As<HFunction>());
case Heap::kTagObject:
return VisitObject(value->As<HObject>());
case Heap::kTagArray:
return VisitArray(value->As<HArray>());
case Heap::kTagMap:
return VisitMap(value->As<HMap>());
// String and numbers ain't referencing anyone
case Heap::kTagString:
case Heap::kTagNumber:
case Heap::kTagBoolean:
case Heap::kTagCData:
return;
default:
UNEXPECTED
}
}
void GC::VisitContext(HContext* context) {
if (context->has_parent()) {
grey_items()->Push(
new GCValue(HValue::Cast(context->parent()), context->parent_slot()));
}
for (uint32_t i = 0; i < context->slots(); i++) {
if (!context->HasSlot(i)) continue;
HValue* value = context->GetSlot(i);
grey_items()->Push(new GCValue(value, context->GetSlotAddress(i)));
}
}
void GC::VisitFunction(HFunction* fn) {
// TODO: Use const here
if (fn->parent_slot() != NULL &&
fn->parent() != reinterpret_cast<char*>(0x0DEF0DEF)) {
grey_items()->Push(new GCValue(
HValue::Cast(fn->parent()), fn->parent_slot()));
}
if (fn->root_slot() != NULL) {
grey_items()->Push(new GCValue(HValue::Cast(fn->root()), fn->root_slot()));
}
}
void GC::VisitObject(HObject* obj) {
grey_items()->Push(new GCValue(HValue::Cast(obj->map()), obj->map_slot()));
}
void GC::VisitArray(HArray* arr) {
grey_items()->Push(new GCValue(HValue::Cast(arr->map()), arr->map_slot()));
}
void GC::VisitMap(HMap* map) {
uint32_t size = map->size() << 1;
for (uint32_t i = 0; i < size; i++) {
if (map->GetSlot(i) != NULL) {
grey_items()->Push(new GCValue(map->GetSlot(i),
map->GetSlotAddress(i)));
}
}
}
} // namespace internal
} // namespace candor
|
431bd61677d8420b33f3fcd953bb5b39ff4c9e48
|
f198fa595f780616ca302c07a249009556e0795b
|
/2.adder/monitor.cpp
|
cad5435badc1674de47024df68b5cf22e8b88600
|
[] |
no_license
|
fluency03/SystemC
|
8a71eaee4ac2f9fe464ad27b2293e7df57a6b923
|
6a546e4bc71e71051085a1241b82d8606dd16d4f
|
refs/heads/master
| 2021-01-10T11:42:03.956221
| 2015-11-04T10:51:08
| 2015-11-04T10:51:08
| 41,821,236
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 197
|
cpp
|
monitor.cpp
|
// monitor.cpp
#include "monitor.h"
void Monitor::printout(){
while (true) {
wait();
cout << "a = " << a << "; ";
cout << "b = " << b << "; ";
cout << "c = " << c << "; " << endl;
}
}
|
22cbe185b839999e425fbdd5fd85383e5d7e254a
|
3fad361d88f16393b4688cb23ac894d1d72e958c
|
/Product/Implementation/product.cpp
|
964548203cad72027abeb762e93e452a9aa0f8bc
|
[] |
no_license
|
Gardahadi/Engisfarm
|
86ed39813605587d8d6a9b91881acafc7fa77812
|
b2d40bb3f5014d093d556af0ff44d2ccd0f2dc03
|
refs/heads/master
| 2020-05-07T14:36:27.047163
| 2019-04-10T14:45:29
| 2019-04-10T14:45:29
| 180,601,506
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 116
|
cpp
|
product.cpp
|
#include "../Header/product.h"
int Product::getHarga(){
return harga;
}
int Product::getID(){
return id;
}
|
535ae3d5d2d94dc9796d5433dcef459f921e7e63
|
a0dce37339bf2e60d7ddff5b1b9346e364a04bc8
|
/myq5.cpp
|
bcdcc2040bcdd343e70c9ed84696bbc6be3e8598
|
[] |
no_license
|
archiver/spoj
|
c0dfdc2bfea0c4d811ee0b95dce83c720bea3eae
|
ac78437594b4ff062db886d03db2a7192478b603
|
refs/heads/master
| 2020-05-18T00:58:53.697941
| 2013-01-18T22:00:38
| 2013-01-18T22:00:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 461
|
cpp
|
myq5.cpp
|
#include <stdio.h>
using namespace std;
#define N 1001
#define PRIME 1000000007
typedef unsigned long long ull;
ull comb[N][N];
ull sumb[N][N];
void compute()
{
int i,j;
for(j=0;j<N;++j)
{
for(i=0;i<j;++i)
sumb[i][j]=1L;
}
for(j=1;j<N;++j) //value of k
{
for(i=j;i<N;++i) //value of n
{
comb[i][j]= sumb[i-j][j];
sumb[i][j]=(sumb[i-1][j]+comb[i][j])%PRIME;
}
}
}
int main()
{
compute();
return 0;
}
|
aa9645ba2f8371570fa3804fbd6f43e4e22edc86
|
66b72447770c0848f8f9b89c2d4c2473fb9a0581
|
/0551.student_attendance_record_i_E.cpp
|
771874c11ba5593b71ab66720dfcea086d9d55ed
|
[] |
no_license
|
zvant/LeetCodeSolutions
|
5d27a25dbc0ec522bde61d436f88e81c67e1367a
|
ca2c7959c3ea8912abc0be5575272479a5ef3cb0
|
refs/heads/master
| 2022-09-21T06:26:17.520429
| 2022-09-08T02:40:16
| 2022-09-08T02:40:16
| 140,584,965
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 703
|
cpp
|
0551.student_attendance_record_i_E.cpp
|
/**
* https://leetcode.com/problems/student-attendance-record-i/description/
* 2017/05
* 3 ms
*/
class Solution
{
public:
bool checkRecord(string s)
{
int len = s.length();
int absent = 0;
for(int idx = 0; idx < len; idx ++)
{
if(s[idx] == 'A')
{
absent ++;
if(absent > 1)
{
return false;
}
}
if(s[idx] == 'L')
{
if(idx <= len - 3 && s[idx + 1] == 'L' && s[idx + 2] == 'L')
{
return false;
}
}
}
return true;
}
};
|
778ae2b340e6de5173bd8628e2dfc72cb42b3bd0
|
d8dde07d7c9cf75f7f18a91ab1dd74a4a261a9e7
|
/contest/TheWaySoFar-Training/2011-Daejeon/J.cpp
|
7fb753101d62fc284e4da4b4bf70d41a4093ce9a
|
[] |
no_license
|
tiankonguse/ACM
|
349109d3804e5b1a1de109ec48a2cb3b0dceaafc
|
ef70b8794c560cb87a6ba8f267e0cc5e9d06c31b
|
refs/heads/master
| 2022-10-09T19:58:38.805515
| 2022-09-30T06:59:53
| 2022-09-30T06:59:53
| 8,998,504
| 82
| 51
| null | 2020-11-09T05:17:09
| 2013-03-25T04:04:26
|
C++
|
UTF-8
|
C++
| false
| false
| 1,469
|
cpp
|
J.cpp
|
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
map <int,int> m1,m2;
const int MAXN=1000002;
typedef map<int,int>::iterator IT;
typedef pair<int,int> point;
point c1[MAXN],c2[MAXN];
int main(){
int T;
//freopen("1.txt","r",stdin);
scanf("%d",&T);
for (;T ; --T){
int n;
scanf("%d",&n);
m1.clear();
m2.clear();
for (int i=0; i<n; ++i)
scanf("%d%d",&c1[i].second,&c1[i].first);
int m;
scanf("%d",&m);
for (int i=0; i<m; ++i)
scanf("%d%d",&c2[i].second,&c2[i].first);
sort(c1,c1+n);
sort(c2,c2+m);
int ans=10000000;
for (int i=0; i<m; ++i) ++m1[c2[i].first+c2[i].second];
for (int i=0, j=0; i<n; ++i){
while (j<m && c2[j].first<c1[i].first){
int k=c2[j].first+c2[j].second;
if (--m1[k]==0) m1.erase(k);
++m2[c2[j].second-c2[j].first];
++j;
}
if (m1.size()){
IT t=m1.begin();
int k=t->first;
// cout<<k-c1[i].first-c1[i].second<<endl;
ans=min(ans,k-c1[i].first-c1[i].second);
}
if (m2.size()){
IT t=m2.begin();
int k=t->first;
ans=min(ans,k-(c1[i].second-c1[i].first));
}
}
printf("%d\n",ans);
}
}
|
bbcdc982e143979daab18895cd3dfb89ebdbe3b6
|
f5d86f2d06ef811a934b9d9d6d2b9a9ad0e59e76
|
/src/Lattice/CSELatticeNode.cpp
|
09d5c2d56e5a2ce79e97d0872ac92c6cd9db5b5f
|
[] |
no_license
|
XavierWang/llvm
|
cc48e9f8ed61872286259c76bd8a85712020ce4c
|
4dfe2781fe6f3368ad53321750b3d2657ae6e5d3
|
refs/heads/master
| 2021-01-14T08:54:48.855122
| 2015-12-13T03:30:49
| 2015-12-13T03:30:49
| 47,491,322
| 0
| 0
| null | 2015-12-06T09:55:06
| 2015-12-06T09:55:05
| null |
UTF-8
|
C++
| false
| false
| 1,955
|
cpp
|
CSELatticeNode.cpp
|
#include "../../include/Lattice/CSELatticeNode.h"
LatticeNode* CSELatticeNode::join(LatticeNode* node){
if (node->isBottom){
return this;
}
if (this->isBottom){
return node;
}
CSELatticeNode* cseNode = dyn_cast<CSELatticeNode>(node);
map<Value*, Instruction*> statements1 = this->statements;
map<Value*, Instruction*> statements2 = cseNode->statements;
map<Value*, Instruction*> new_statements;
for(map<Value*, Instruction*>::iterator iter = statements1.begin(); iter != statements1.end(); iter++){
if(statements2.find(iter->first) != statements2.end()){
if(statements2[iter->first] == statements1[iter->first])
new_statements[iter->first] = iter->second;
}
}
CSELatticeNode* new_node = new CSELatticeNode(false, false, new_statements);
return new_node;
}
bool CSELatticeNode::equal(LatticeNode* node){
CSELatticeNode* cseNode = dyn_cast<CSELatticeNode>(node);
// errs() << "CSELatticeNode equal function\n";
map<Value*, Instruction*> statements1 = this->statements;
map<Value*, Instruction*> statements2 = cseNode->statements;
if(this->isBottom == true || cseNode->isBottom == true)
return this->isBottom == cseNode->isBottom;
if(this->isTop == true || cseNode->isTop == true)
return this->isTop == cseNode->isTop;
for(map<Value*, Instruction*>::iterator iter = statements1.begin(); iter != statements1.end(); iter++){
if(statements2.find(iter->first) != statements2.end()){
if(statements2[iter->first] != statements1[iter->first])
return false;
}else{
return false;
}
}
// errs() << "CSELatticeNode equal function\n";
return true;
}
void CSELatticeNode::print(){
errs() << "---CSELatticeNode Info---\n";
errs() << "Bottom:" <<this->isBottom << " Top:" << this->isTop << "\n";
for(map<Value*, Instruction*>::iterator iter = statements.begin(); iter != statements.end(); iter++){
errs() << *iter->first << "->"<<*(iter->second)<< "(" <<iter->second<<")" << "\n";
}
errs() << "\n";
}
|
a68b5a3cac8f0f25d47831f47a03d86b2227170a
|
8cdb51622a7f330968293dcd82db5e18cd376b9c
|
/include/CPVFramework/Http/ApiDocs.hpp
|
c71378eb8379c0c62bf033a434bfa501b3c9e04e
|
[
"MIT"
] |
permissive
|
Lwelch45/cpv-framework
|
90930d4ffc75bfe3e6f9f6271a2556fb750adcca
|
11f3e882cd3bdec1c4a590f09148c21705b21f60
|
refs/heads/master
| 2020-03-18T23:11:31.042662
| 2018-05-16T00:58:43
| 2018-05-16T01:43:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 81
|
hpp
|
ApiDocs.hpp
|
#pragma once
#include "./Server/api_docs.hpp"
#include "./Server/json_path.hpp"
|
bf49d7f6181b0d9d868378f6cadc48483856bc87
|
17e9a5bbf3f3500e90e305d98d4d49e46428c455
|
/library/messageutils.cpp
|
be1da980c7570edfbd17e5578bc966dc1e5332eb
|
[] |
no_license
|
thundercat/challenge0
|
cc41491930d13f3a94dc51f0b998cabaf4d4a813
|
44f5047c1f44eb513262471f1ed84e5079c03f94
|
refs/heads/master
| 2021-05-17T23:10:35.036891
| 2020-03-29T09:36:19
| 2020-03-29T09:36:19
| 250,995,306
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 26
|
cpp
|
messageutils.cpp
|
#include "messageutils.h"
|
f7a9c7e7b482d60b9e1b77c2e29d75b3944ac7f4
|
bb92586c3accb07b99b5004d719434fd018bd135
|
/Algorithm/sorting/radix_sort.hh
|
eedfcf0d902ebce6af0793c570d0c5176253dab6
|
[] |
no_license
|
lc19890306/Exercise
|
4a6070296aadb021d35dfae54d9352c289b9c2db
|
153f73c015a9c64aa35aa440fce926c1d26f76c8
|
refs/heads/master
| 2021-07-17T21:01:15.881080
| 2021-02-19T15:34:55
| 2021-02-19T15:34:55
| 40,798,802
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 932
|
hh
|
radix_sort.hh
|
#ifndef RADIX_SORT_HH
#define RADIX_SORT_HH
#include "functions.hh"
#include <vector>
template <typename ForwardIt>
int
maxBit(ForwardIt first, ForwardIt last) {
auto it(max_element(first, last));
if (it != last) {
auto largest(*it);
auto max_bit(0);
while (largest > 0) {
largest /= 10;
++max_bit;
}
return max_bit;
}
return 0;
}
template <typename RandomIt>
void
radix_sort(RandomIt first, RandomIt last) {
typedef typename std::iterator_traits<RandomIt>::value_type T;
auto max_bit(maxBit(first, last));
int radix(1);
std::vector<std::vector<T> > buckets(10);
for (int i(0); i != max_bit; ++i) {
for (auto it(first); it != last; ++it)
buckets[(*it / radix) % 10].push_back(*it);
auto it(first);
for (auto &&bucket : buckets) {
for (auto &&element : bucket)
*it++ = element;
bucket.clear();
}
radix *= 10;
}
}
#endif // RADIX_SORT_HH
|
b74b87d028918bf6e2dbd1fee1a94153d8bbb80a
|
75510162401dd325cfd244049a710df7171edbe6
|
/Message/Message/poruka.cpp
|
706759e3abb5cfec546c0d81b543dad4549109d3
|
[] |
no_license
|
bornajelic/Cpp-Projects
|
9e4131e3329c6fd281173226bb86df9ab7fabc50
|
ae3831243fb2c8a29c365ffa53e2fdb86dc9fdd1
|
refs/heads/master
| 2020-04-09T00:34:41.375655
| 2019-07-17T13:13:15
| 2019-07-17T13:13:15
| 159,872,944
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,266
|
cpp
|
poruka.cpp
|
#include "Poruka.h"
#include <iostream>
#include <algorithm>
#include <sstream>
Kategorija::Kategorija(std::string const &opis){
mOpis = opis;
}
Kategorija::~Kategorija()
{
}
void Kategorija::dodaj_poruku(Poruka *p) { //ova funkcija mora biti pozvana automatski sa funkcijojm Poruka::dodaj()
this -> mPorukeSet.insert(p);
}
void Kategorija::ukloni_poruku(Poruka *p) {
std::set<Poruka*>::iterator to_delete = this->mPorukeSet.begin();
for (to_delete; to_delete != mPorukeSet.end(); ++to_delete) {
if (*to_delete == p) {
this->mPorukeSet.erase(to_delete);
//delete *to_delete;
break;
}
}
}
std::set<Poruka*> Kategorija::getMPorukeSet() {
return mPorukeSet;
}
//class Poruka
Poruka::Poruka(std::string const &sadrzaj) {
mSadrzaj = sadrzaj;
}
Poruka::Poruka(Poruka const &p) {
std::cout << "Poruka copy constr..\n";
mSadrzaj = p.mSadrzaj;
mKategorijeSet = p.mKategorijeSet;
}
Poruka::Poruka(Poruka &&p) { //??
std::cout << "Poruka move constr..\n";
this->mKategorijeSet = p.mKategorijeSet;
this->mSadrzaj = p.mSadrzaj;
}
Poruka& Poruka::operator=(Poruka const &p) { //rvalue reference(assigment op)
std::cout << "Poruka assigment operator..\n";
if (this != &p) { //sto znaci *this = p
this->mSadrzaj = p.mSadrzaj;
this->mKategorijeSet = p.mKategorijeSet;
}
return *this;
}
Poruka& Poruka::operator=(Poruka &&p) { //?? mora se i micati iz seta, odnosno promijeniti
std::cout << "Poruka MOVE assigment operator..\n";
if (this != &p) {
*this = p;
}
return *this;
}
Poruka::~Poruka()
{
std::cout << "DELETE\n";
}
void Poruka::dodaj(Kategorija &k) { //dodaj poruku u danu kategoriju
k.dodaj_poruku(this);
Kategorija *pk = &k;
mKategorijeSet.insert(pk);
}
void Poruka::ukloni(Kategorija &k) { //ukloni poruku iz dane kategorije
this->mKategorijeSet.erase(&k);
k.ukloni_poruku(this);
}
std::string Poruka::kategorije() const {
std::string tmp;
std::stringstream ss;
std::set<Kategorija*>::iterator it_outer;
for (it_outer = mKategorijeSet.begin(); it_outer != mKategorijeSet.end(); ++it_outer) {
std::string str = "";
ss << (*it_outer)->opis() << " ";
}
tmp = ss.str();
return tmp;
}
|
da41eaa3e3be8e9769185a504079675cd7c6d0d4
|
7227c3ea8c7532fec6a0fdcddd280ca9c37e1ffb
|
/BaekJoon/2178_.cpp
|
bb6493e6da82fbd6eddbd1c8c846de3ccd10d821
|
[] |
no_license
|
Ju-nic2/Algorithm
|
e326a6ddde9a3a65d4b4d5617be46a39e1d9b65f
|
e7a1d3023f3a8eb1356475bfee77c9b7f5830d6a
|
refs/heads/master
| 2023-07-11T20:52:41.002233
| 2021-08-23T15:05:23
| 2021-08-23T15:05:23
| 384,132,461
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,648
|
cpp
|
2178_.cpp
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
class maze_search
{
private:
vector<string> map;
vector<vector<int>> visit;
public:
maze_search(const int& x, const int& y)
{
for(int i = 0; i < y; i++)
{
visit.push_back(vector<int>(x,0));
}
visit[0][0] = 1;
}
void inputMap(const string str)
{
map.push_back(str);
}
void walkRoute(int x, int y)
{
for(int d = 0; d < 4; d++)
{
int nextx = x + dx[d];
int nexty = y + dy[d];
if(nextx >= 0 && nextx < map[0].size() && nexty >= 0 && nexty < map.size())
{
if(map[nexty][nextx] == '1' && visit[nexty][nextx] < 1){
visit[nexty][nextx] = visit[y][x] + 1;
walkRoute(nextx,nexty);
}else if(map[nexty][nextx] == '1' && visit[nexty][nextx] > 1)
{
if(visit[nexty][nextx] > visit[y][x]){
visit[nexty][nextx] = visit[y][x] + 1;
walkRoute(nextx,nexty);
}
}
}
}
}
void getMinRoute(const int x, const int y)
{
cout << visit[y][x];
}
};
int main()
{
int n, m;
cin >> n >> m;
maze_search ms(m,n);
string str;
for(int i = 0; i < n; i ++){
cin >> str;
ms.inputMap(str);
}
ms.walkRoute(0,0);
ms.getMinRoute(m-1,n-1);
}
|
0ad1f1bf62ee86188a0ce8108513da9709aa339e
|
7b4b7201bba88f886b07cb550288220a7d47fbb1
|
/유기농 배추.cpp
|
639dae2760f0e085907cdc0dcdb53d9de2919a6e
|
[] |
no_license
|
blockyu/algorithm
|
57db1fe5c9aef18b496207904acb7e7e6ff76fd4
|
481156db0961eb583c506c4ff5839caa8a1cb4b7
|
refs/heads/master
| 2022-09-30T14:18:00.319087
| 2020-06-06T07:41:34
| 2020-06-06T07:41:34
| 269,906,444
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,102
|
cpp
|
유기농 배추.cpp
|
#include <iostream>
#include <algorithm>
using namespace std;
int N;
int ROW,COL,K, res;
int arr[51][51];
bool vis[51][51];
int moveR[] = {1,0,-1,0};
int moveC[] = {0,1,0,-1};
void check(int c, int r) {
if(r==ROW || c==COL) return ;
vis[c][r]=true;
for(int i=0; i<4; i++) {
int nextC=c+moveC[i];
int nextR=r+moveR[i];
if(nextC<0 || nextC==COL) continue;
if(nextR<0 || nextR==ROW) continue;
if(arr[nextC][nextR]>0 && !vis[nextC][nextR]) {
check(nextC, nextR);
}
}
}
int main() {
cin>>N;
for(int i=0; i<N; i++) {
cin>>ROW>>COL>>K;
for(int j=0; j<K; j++) {
int r, c;
cin>>r>>c;
arr[c][r] = 1;
}
for(int c=0; c<COL; c++) {
for(int r=0; r<ROW; r++) {
if(arr[c][r]>0 && !vis[c][r]) {
check(c,r);
res++;
}
}
}
cout<<res<<endl;
res=0;
fill(&arr[0][0], &arr[COL][ROW], 0);
fill(&vis[0][0], &vis[COL][ROW], false);
}
}
|
dff4324fb801f3e27d92acfadaada68127969a2b
|
558b60baaa3379323f123cf784cd83e2c423ccab
|
/code/rotate.cpp
|
48eecaddb13730cd95e3fd0dde1a0765a79680d5
|
[] |
no_license
|
RoseHuRan/Multi-functional-Image-Editing
|
acc7d733d019b111d65c19588b9d746247918880
|
8436198c349109b77c22a8a7636d7d467e70e4db
|
refs/heads/master
| 2020-04-15T16:46:59.985813
| 2019-10-23T04:05:53
| 2019-10-23T04:05:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 842
|
cpp
|
rotate.cpp
|
#include "rotate.h"
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdio.h>
#include <iostream>
using namespace cv;
using namespace std;
Mat rotate(Mat src, int mode) {
Mat dst, dst2, dst3;
switch(mode){
case 1: // Left rotate.
transpose(src, dst);
flip(dst, dst2, 0);
return dst2;
break;
case 2: // Right rotate
transpose(src, dst);
flip(dst, dst2, 1);
return dst2;
break;
case 3: // Horizontal flip
flip(src, dst, 1);
return dst;
break;
case 4: // Vertical flip.
flip(src, dst, 0);
return dst;
break;
case 5: // Diagonal flip.
flip(src, dst, -1);
return dst;
break;
default:
break;
}
}
|
e2f571aa9c1aeb87b11a9ccf00ae24845ea36345
|
f3d7f88c6d006a2cac39cc45c06fe70d6b3868d8
|
/MockSensor.cpp
|
73e20b60e2519e239a82c9c14cfe4ca173c550d7
|
[] |
no_license
|
supox/sprinkler_arm
|
1ec45625ac9cda4a99b0d35ffc22e90f977a3a8e
|
dc4557fdd282c813b987f7e10b63568bb28193a2
|
refs/heads/master
| 2020-05-20T00:43:42.117886
| 2013-05-01T19:19:15
| 2013-05-01T19:19:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 415
|
cpp
|
MockSensor.cpp
|
#include "MockSensor.h"
#include <stdlib.h>
MockSensor::MockSensor(const int id, const int port_index, const double sensor_value, ISensorListener* listener) : Sensor(id, port_index, sensor_value, listener)
{
}
MockSensor::~MockSensor()
{
}
SensorType MockSensor::GetType()
{
return MOCK;
}
bool MockSensor::ReadSensorFromHardware(double &value)
{
// TODO!
value = (double)(rand() % 10 + 1);
return true;
}
|
48c8d2c0b569b16065c954ac12013e4072d2fc43
|
e2629d6fa6060d99463710d6a2b3bdcf5aa8f0b3
|
/Day 8 Handheld Halting/d8_2.cpp
|
a01c36cb0a4562b44c98be27813402e6d926578b
|
[] |
no_license
|
zigmars/advent-of-code
|
2bc5aa96aad48e72dfa3d6bb70eae3c96d62e606
|
4873b073aa81a8bdcfb118074a428ce3e1c9e68b
|
refs/heads/main
| 2023-02-03T08:49:25.584224
| 2020-12-16T10:47:36
| 2020-12-16T10:53:36
| 320,833,119
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,265
|
cpp
|
d8_2.cpp
|
#include <iostream>
#include <sstream>
#include <set>
#include <vector>
using namespace std;
struct instr {
char op;
int val;
};
using ull = unsigned long long;
struct state {
ull acc;
int pc;
};
vector<instr> program;
set<int> visited;
state s({.acc=0, .pc=0});
bool programTerminates(vector<instr> program){
while(!visited.contains(s.pc) && s.pc < program.size()){
visited.insert(s.pc);
instr i = program[s.pc];
//cout << i.op << " " << (i.val >= 0 ? string("+") : string("")) << i.val << endl;
switch(i.op){
case 'j':
s.pc += i.val;
break;
case 'a':
s.acc += i.val;
s.pc += 1;
break;
case 'n':
s.pc += 1;
break;
}
}
return (s.pc == program.size());
}
int main(){
string line;
while(getline(cin, line)){
string op;
int val;
stringstream ss(line);
ss >> op >> val;
program.push_back({.op=op[0], .val=val});
}
/*
for(int i = 0; i < program.size(); i++){
switch(program[i].op){
case 'j':
cout << "jmp ";
break;
case 'a':
cout << "acc ";
break;
case 'n':
cout << "nop ";
break;
}
if(program[i].val >= 0){
cout << "+";
}
cout << program[i].val << endl;
}
*/
bool endConditionDone = false;
auto endCondition = [](){
instr i = program[s.pc];
return (i.op == 'n' && i.val + s.pc == program.size()) || (i.op == 'j' && s.pc == program.size()-1);
};
for(int modPc = 0; modPc < program.size(); modPc++){
vector<instr> modProgram(program);
if(program[modPc].op == 'a'){
continue;
}
modProgram[modPc].op ^= ('j' ^ 'n');
s = {.acc=0, .pc=0};
visited.clear();
bool terminated = programTerminates(modProgram);
if(terminated){
cout << "modPc = " << modPc << endl;
cout << s.pc << " " << s.acc << endl;
//break;
}
}
//cout << "acc = " << s.acc << endl;
return 0;
}
|
0a48bad96c8bafe220d98e4ed862a55fd1e388b1
|
19ccfd6806c5054679dab3f275822302206b222f
|
/src/game/shared/voice_status.cpp
|
201425268a84631432848f7b2b32f3956a536702
|
[
"Apache-2.0"
] |
permissive
|
BenLubar/SwarmDirector2
|
425441d5ac3fd120c998379ddc96072b2c375109
|
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
|
refs/heads/master
| 2021-01-17T22:14:37.146323
| 2015-07-09T19:18:03
| 2015-07-09T19:18:03
| 20,357,966
| 4
| 1
|
Apache-2.0
| 2018-08-30T13:37:22
| 2014-05-31T15:00:51
|
C++
|
WINDOWS-1252
|
C++
| false
| false
| 16,319
|
cpp
|
voice_status.cpp
|
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "basetypes.h"
#include "hud.h"
#include <string.h>
#include <stdio.h>
#include "voice_status.h"
#include "r_efx.h"
#include <vgui_controls/TextImage.h>
#include <vgui/mousecode.h>
#include "cdll_client_int.h"
#include "hud_macros.h"
#include "c_playerresource.h"
#include "cliententitylist.h"
#include "c_baseplayer.h"
#include "materialsystem/imesh.h"
#include "view.h"
#include "convar.h"
#include <vgui_controls/Controls.h>
#include <vgui/IScheme.h>
#include <vgui/ISurface.h>
#include "vgui_BitmapImage.h"
#include "materialsystem/imaterial.h"
#include "tier0/dbg.h"
#include "cdll_int.h"
#include <vgui/IPanel.h>
#include "con_nprint.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
extern int cam_thirdperson;
#define VOICE_MODEL_INTERVAL 0.3
#define SQUELCHOSCILLATE_PER_SECOND 2.0f
ConVar voice_modenable( "voice_modenable", "1", FCVAR_ARCHIVE | FCVAR_CLIENTCMD_CAN_EXECUTE, "Enable/disable voice in this mod." );
ConVar voice_clientdebug( "voice_clientdebug", "0" );
ConVar voice_head_icon_size( "voice_head_icon_size", "6", FCVAR_NONE, "Size of voice icon over player heads in inches" );
ConVar voice_head_icon_height( "voice_head_icon_height", "20", FCVAR_NONE, "Voice icons are this many inches over player eye positions" );
ConVar voice_local_icon( "voice_local_icon", "0", FCVAR_NONE, "Draw local player's voice icon" );
ConVar voice_all_icons( "voice_all_icons", "0", FCVAR_NONE, "Draw all players' voice icons" );
// ---------------------------------------------------------------------- //
// The voice manager for the client.
// ---------------------------------------------------------------------- //
static CVoiceStatus *g_VoiceStatus = NULL;
CVoiceStatus* GetClientVoiceMgr()
{
if ( !g_VoiceStatus )
{
ClientVoiceMgr_Init();
}
return g_VoiceStatus;
}
void ClientVoiceMgr_Init()
{
if ( g_VoiceStatus )
return;
g_VoiceStatus = new CVoiceStatus();
}
void ClientVoiceMgr_Shutdown()
{
delete g_VoiceStatus;
g_VoiceStatus = NULL;
}
void ClientVoiceMgr_LevelInit()
{
if ( g_VoiceStatus )
{
g_VoiceStatus->LevelInit();
}
}
void ClientVoiceMgr_LevelShutdown()
{
if ( g_VoiceStatus )
{
g_VoiceStatus->LevelShutdown();
}
}
// ---------------------------------------------------------------------- //
// CVoiceStatus.
// ---------------------------------------------------------------------- //
static CVoiceStatus *g_pInternalVoiceStatus = NULL;
void __MsgFunc_VoiceMask(bf_read &msg)
{
if(g_pInternalVoiceStatus)
g_pInternalVoiceStatus->HandleVoiceMaskMsg(msg);
}
void __MsgFunc_RequestState(bf_read &msg)
{
if(g_pInternalVoiceStatus)
g_pInternalVoiceStatus->HandleReqStateMsg(msg);
}
// ---------------------------------------------------------------------- //
// CVoiceStatus.
// ---------------------------------------------------------------------- //
CVoiceStatus::CVoiceStatus()
{
m_nControlSize = 0;
m_bBanMgrInitialized = false;
m_LastUpdateServerState = 0;
for ( int k = 0; k < MAX_SPLITSCREEN_CLIENTS; ++ k )
{
m_bTalking[k] = false;
m_bServerAcked[k] = false;
m_bAboveThreshold[k] = false;
m_bAboveThresholdTimer[k].Invalidate();
}
m_bServerModEnable = -1;
m_pHeadLabelMaterial = NULL;
m_bHeadLabelsDisabled = false;
}
CVoiceStatus::~CVoiceStatus()
{
if ( m_pHeadLabelMaterial )
{
m_pHeadLabelMaterial->DecrementReferenceCount();
}
g_pInternalVoiceStatus = NULL;
const char *pGameDir = engine->GetGameDirectory();
if( pGameDir )
{
if(m_bBanMgrInitialized)
{
m_BanMgr.SaveState( pGameDir );
}
}
}
int CVoiceStatus::Init(
IVoiceStatusHelper *pHelper,
VPANEL pParentPanel)
{
const char *pGameDir = engine->GetGameDirectory();
if( pGameDir )
{
m_BanMgr.Init( pGameDir );
m_bBanMgrInitialized = true;
}
Assert(!g_pInternalVoiceStatus);
g_pInternalVoiceStatus = this;
m_pHeadLabelMaterial = materials->FindMaterial( "voice/icntlk_pl", TEXTURE_GROUP_VGUI );
m_pHeadLabelMaterial->IncrementReferenceCount();
m_bInSquelchMode = false;
m_pHelper = pHelper;
m_pParentPanel = pParentPanel;
for ( int hh = 0; hh < MAX_SPLITSCREEN_PLAYERS; ++hh )
{
ACTIVE_SPLITSCREEN_PLAYER_GUARD( hh );
HOOK_MESSAGE(VoiceMask);
HOOK_MESSAGE(RequestState);
}
return 1;
}
BitmapImage* vgui_LoadMaterial( vgui::VPANEL pParent, const char *pFilename )
{
return new BitmapImage( pParent, pFilename );
}
void CVoiceStatus::VidInit()
{
}
void CVoiceStatus::LevelInit( void )
{
for ( int k = 0; k < MAX_SPLITSCREEN_CLIENTS; ++ k )
{
m_bTalking[k] = false;
m_bAboveThreshold[k] = false;
m_bAboveThresholdTimer[k].Invalidate();
}
}
void CVoiceStatus::LevelShutdown( void )
{
for ( int k = 0; k < MAX_SPLITSCREEN_CLIENTS; ++ k )
{
m_bTalking[k] = false;
m_bAboveThreshold[k] = false;
m_bAboveThresholdTimer[k].Invalidate();
}
}
void CVoiceStatus::Frame(double frametime)
{
// check server banned players once per second
if (gpGlobals->curtime - m_LastUpdateServerState > 1)
{
UpdateServerState(false);
}
}
float g_flHeadOffset = 35;
void CVoiceStatus::SetHeadLabelOffset( float offset )
{
g_flHeadOffset = offset;
}
float CVoiceStatus::GetHeadLabelOffset( void ) const
{
return g_flHeadOffset;
}
void CVoiceStatus::DrawHeadLabels()
{
if ( voice_all_icons.GetBool() )
{
for(int i=0; i < VOICE_MAX_PLAYERS; i++)
{
IClientNetworkable *pClient = cl_entitylist->GetClientEntity( i+1 );
// Don't show an icon if the player is not in our PVS.
if ( !pClient || pClient->IsDormant() )
continue;
m_VoicePlayers[i] = voice_all_icons.GetInt() > 0;
}
}
else if ( voice_local_icon.GetBool() )
{
C_BasePlayer *localPlayer = C_BasePlayer::GetLocalPlayer();
m_VoicePlayers[ localPlayer->entindex() - 1 ] = IsLocalPlayerSpeakingAboveThreshold( localPlayer->GetSplitScreenPlayerSlot() );
}
if ( m_bHeadLabelsDisabled )
return;
if( !m_pHeadLabelMaterial )
return;
CMatRenderContextPtr pRenderContext( materials );
for(int i=0; i < VOICE_MAX_PLAYERS; i++)
{
if ( !m_VoicePlayers[i] )
continue;
IClientNetworkable *pClient = cl_entitylist->GetClientEntity( i+1 );
// Don't show an icon if the player is not in our PVS.
if ( !pClient || pClient->IsDormant() )
continue;
C_BasePlayer *pPlayer = dynamic_cast<C_BasePlayer*>(pClient);
if( !pPlayer )
continue;
// Don't show an icon for dead or spectating players (ie: invisible entities).
if( pPlayer->IsPlayerDead() )
continue;
// Place it a fixed height above his head.
Vector vOrigin = pPlayer->EyePosition( );
vOrigin.z += voice_head_icon_height.GetFloat();
// Align it so it never points up or down.
Vector vUp( 0, 0, 1 );
Vector vRight = CurrentViewRight();
if ( fabs( vRight.z ) > 0.95 ) // don't draw it edge-on
continue;
vRight.z = 0;
VectorNormalize( vRight );
float flSize = voice_head_icon_size.GetFloat();
pRenderContext->Bind( pPlayer->GetHeadLabelMaterial() );
IMesh *pMesh = pRenderContext->GetDynamicMesh();
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_QUADS, 1 );
meshBuilder.Color3f( 1.0, 1.0, 1.0 );
meshBuilder.TexCoord2f( 0,0,0 );
meshBuilder.Position3fv( (vOrigin + (vRight * -flSize) + (vUp * flSize)).Base() );
meshBuilder.AdvanceVertex();
meshBuilder.Color3f( 1.0, 1.0, 1.0 );
meshBuilder.TexCoord2f( 0,1,0 );
meshBuilder.Position3fv( (vOrigin + (vRight * flSize) + (vUp * flSize)).Base() );
meshBuilder.AdvanceVertex();
meshBuilder.Color3f( 1.0, 1.0, 1.0 );
meshBuilder.TexCoord2f( 0,1,1 );
meshBuilder.Position3fv( (vOrigin + (vRight * flSize) + (vUp * -flSize)).Base() );
meshBuilder.AdvanceVertex();
meshBuilder.Color3f( 1.0, 1.0, 1.0 );
meshBuilder.TexCoord2f( 0,0,1 );
meshBuilder.Position3fv( (vOrigin + (vRight * -flSize) + (vUp * -flSize)).Base() );
meshBuilder.AdvanceVertex();
meshBuilder.End();
pMesh->Draw();
}
}
void CVoiceStatus::UpdateSpeakerStatus(int entindex, int iSsSlot, bool bTalking)
{
if( !m_pParentPanel )
return;
if( voice_clientdebug.GetInt() == 1 )
{
Msg( "CVoiceStatus::UpdateSpeakerStatus: ent %d ss[%d] talking = %d\n",
entindex, iSsSlot, bTalking );
}
else if ( voice_clientdebug.GetInt() == 2 )
{
con_nprint_t np;
np.index = 0;
np.color[0] = 1.0f;
np.color[1] = 1.0f;
np.color[2] = 1.0f;
np.time_to_live = 2.0f;
np.fixed_width_font = true;
int numActiveChannels = VOICE_MAX_PLAYERS;
engine->Con_NXPrintf ( &np, "Total Players: %i", numActiveChannels);
for ( int i = 1; i <= numActiveChannels; i++ )
{
np.index++;
np.color[0] = np.color[1] = np.color[2] = ( i % 2 == 0 ? 0.9f : 0.7f );
if ( !IsPlayerBlocked( i ) && IsPlayerAudible( i ) && IsPlayerSpeaking( i ) )
{
np.color[0] = 0.0f;
np.color[1] = 1.0f;
np.color[2] = 0.0f;
}
engine->Con_NXPrintf ( &np, "%02i enabled(%s) blocked(%s) audible(%s) speaking(%s)",
i,
m_VoiceEnabledPlayers[ i - 1 ] != 0 ? "YES" : " NO",
IsPlayerBlocked( i ) ? "YES" : " NO",
IsPlayerAudible( i ) ? "YES" : " NO",
IsPlayerSpeaking( i ) ? "YES" : " NO" );
}
np.color[0] = 1.0f;
np.color[1] = 1.0f;
np.color[2] = 1.0f;
np.index += 2;
numActiveChannels = MAX_SPLITSCREEN_CLIENTS;
engine->Con_NXPrintf ( &np, "Local Players: %i", numActiveChannels);
for ( int i = 0; i < numActiveChannels; i++ )
{
np.index++;
np.color[0] = np.color[1] = np.color[2] = ( i % 2 == 0 ? 0.9f : 0.7f );
if ( IsLocalPlayerSpeaking( i ) && IsLocalPlayerSpeakingAboveThreshold( i ) )
{
np.color[0] = 0.0f;
np.color[1] = 1.0f;
np.color[2] = 0.0f;
}
engine->Con_NXPrintf ( &np, "%02i speaking(%s) above_threshold(%s)",
i,
IsLocalPlayerSpeaking( i ) ? "YES" : " NO",
IsLocalPlayerSpeakingAboveThreshold( i ) ? "YES" : " NO" );
}
}
// Is it the local player talking?
if( entindex == -1 && iSsSlot >= 0 )
{
m_bTalking[ iSsSlot ] = !!bTalking;
if( bTalking )
{
// Enable voice for them automatically if they try to talk.
char chClientCmd[0xFF];
Q_snprintf( chClientCmd, sizeof( chClientCmd ),
"cmd%d voice_modenable 1", iSsSlot + 1 );
engine->ClientCmd( chClientCmd );
}
}
if( entindex == -2 && iSsSlot >= 0 )
{
m_bServerAcked[ iSsSlot ] = !!bTalking;
}
if ( entindex == -3 && iSsSlot >= 0 )
{
m_bAboveThreshold[ iSsSlot ] = !!bTalking;
if ( bTalking )
{
const float AboveThresholdMinDuration = 0.5f;
m_bAboveThresholdTimer[ iSsSlot ].Start( AboveThresholdMinDuration );
}
}
if( entindex > 0 && entindex <= VOICE_MAX_PLAYERS )
{
int iClient = entindex - 1;
if(iClient < 0)
return;
if(bTalking)
{
m_VoicePlayers[iClient] = true;
m_VoiceEnabledPlayers[iClient] = true;
}
else
{
m_VoicePlayers[iClient] = false;
}
}
}
void CVoiceStatus::UpdateServerState(bool bForce)
{
// Can't do anything when we're not in a level.
if( !g_bLevelInitialized )
{
if( voice_clientdebug.GetInt() == 1 )
{
Msg( "CVoiceStatus::UpdateServerState: g_bLevelInitialized\n" );
}
return;
}
int bCVarModEnable = !!voice_modenable.GetInt();
if(bForce || m_bServerModEnable != bCVarModEnable)
{
m_bServerModEnable = bCVarModEnable;
char str[256];
Q_snprintf(str, sizeof(str), "VModEnable %d", m_bServerModEnable);
{
HACK_GETLOCALPLAYER_GUARD( "CVoiceStatus::UpdateServerState" );
engine->ServerCmd(str);
}
if( voice_clientdebug.GetInt() == 1 )
{
Msg( "CVoiceStatus::UpdateServerState: Sending '%s'\n", str );
}
}
char str[2048];
Q_strncpy(str,"vban",sizeof(str));
bool bChange = false;
for(unsigned long dw=0; dw < VOICE_MAX_PLAYERS_DW; dw++)
{
unsigned long serverBanMask = 0;
unsigned long banMask = 0;
for(unsigned long i=0; i < 32; i++)
{
int playerIndex = ( dw * 32 + i );
if ( playerIndex >= MAX_PLAYERS )
break;
player_info_t pi;
if ( !engine->GetPlayerInfo( i+1, &pi ) )
continue;
if ( m_BanMgr.GetPlayerBan( pi.guid ) )
{
banMask |= 1 << i;
}
if ( m_ServerBannedPlayers[playerIndex] )
{
serverBanMask |= 1 << i;
}
}
if ( serverBanMask != banMask )
{
bChange = true;
}
// Ok, the server needs to be updated.
char numStr[512];
Q_snprintf(numStr,sizeof(numStr), " %x", banMask);
Q_strncat(str, numStr, sizeof(str), COPY_ALL_CHARACTERS);
}
if(bChange || bForce)
{
if( voice_clientdebug.GetInt() == 1 )
{
Msg( "CVoiceStatus::UpdateServerState: Sending '%s'\n", str );
}
engine->ServerCmd( str, false ); // Tell the server..
}
else
{
if( voice_clientdebug.GetInt() == 1 )
{
Msg( "CVoiceStatus::UpdateServerState: no change\n" );
}
}
m_LastUpdateServerState = gpGlobals->curtime;
}
void CVoiceStatus::HandleVoiceMaskMsg(bf_read &msg)
{
unsigned long dw;
for(dw=0; dw < VOICE_MAX_PLAYERS_DW; dw++)
{
m_AudiblePlayers.SetDWord(dw, (unsigned long)msg.ReadLong());
m_ServerBannedPlayers.SetDWord(dw, (unsigned long)msg.ReadLong());
if( voice_clientdebug.GetInt() == 1 )
{
Msg("CVoiceStatus::HandleVoiceMaskMsg\n");
Msg(" - m_AudiblePlayers[%d] = %lu\n", dw, m_AudiblePlayers.GetDWord(dw));
Msg(" - m_ServerBannedPlayers[%d] = %lu\n", dw, m_ServerBannedPlayers.GetDWord(dw));
}
}
m_bServerModEnable = msg.ReadByte();
}
void CVoiceStatus::HandleReqStateMsg(bf_read &msg)
{
if( voice_clientdebug.GetInt() == 1 )
{
Msg("CVoiceStatus::HandleReqStateMsg\n");
}
UpdateServerState(true);
}
void CVoiceStatus::StartSquelchMode()
{
if(m_bInSquelchMode)
return;
m_bInSquelchMode = true;
m_pHelper->UpdateCursorState();
}
void CVoiceStatus::StopSquelchMode()
{
m_bInSquelchMode = false;
m_pHelper->UpdateCursorState();
}
bool CVoiceStatus::IsInSquelchMode()
{
return m_bInSquelchMode;
}
void SetOrUpdateBounds(
vgui::Panel *pPanel,
int left, int top, int wide, int tall,
bool bOnlyUpdateBounds, int &topCoord, int &bottomCoord )
{
if ( bOnlyUpdateBounds )
{
if ( top < topCoord )
topCoord = top;
if ( (top+tall) >= bottomCoord )
bottomCoord = top+tall;
}
else
{
pPanel->SetBounds( left, top, wide, tall );
}
}
//-----------------------------------------------------------------------------
// Purpose: returns true if the target client has been banned
// Input : playerID -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CVoiceStatus::IsPlayerBlocked(int iPlayer)
{
player_info_t pi;
if ( !engine->GetPlayerInfo( iPlayer, &pi ) )
return false;
return m_BanMgr.GetPlayerBan( pi.guid );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Purpose: blocks/unblocks the target client from being heard
// Input : playerID -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
void CVoiceStatus::SetPlayerBlockedState(int iPlayer, bool blocked)
{
if ( voice_clientdebug.GetInt() == 1 )
{
Msg( "CVoiceStatus::SetPlayerBlockedState part 1\n" );
}
player_info_t pi;
if ( !engine->GetPlayerInfo( iPlayer, &pi ) )
return;
if ( voice_clientdebug.GetInt() == 1 )
{
Msg( "CVoiceStatus::SetPlayerBlockedState part 2\n" );
}
// Squelch or (try to) unsquelch this player.
if ( voice_clientdebug.GetInt() == 1 )
{
Msg("CVoiceStatus::SetPlayerBlockedState: setting player %d ban to %d\n", iPlayer, !m_BanMgr.GetPlayerBan(pi.guid));
}
m_BanMgr.SetPlayerBan(pi.guid, !m_BanMgr.GetPlayerBan(pi.guid));
UpdateServerState(false);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CVoiceStatus::SetHeadLabelMaterial( const char *pszMaterial )
{
if ( m_pHeadLabelMaterial )
{
m_pHeadLabelMaterial->DecrementReferenceCount();
m_pHeadLabelMaterial = NULL;
}
m_pHeadLabelMaterial = materials->FindMaterial( pszMaterial, TEXTURE_GROUP_VGUI );
m_pHeadLabelMaterial->IncrementReferenceCount();
}
|
607dc75375bf0fec5548400d89f1e919ba55f56a
|
147382a3cdeb93be8df2109cdce43095a7fbccf2
|
/trees/958_check_completeness_of_a_binary_tree.cpp
|
2dcdc38f25b1ea7b4324433104a5df26ba314ee1
|
[
"MIT"
] |
permissive
|
rspezialetti/leetcode
|
e41803c1e410e7e2327c3e41b935f43e5439b729
|
4614ffe2a4923aae02f93096b6200239e6f201c1
|
refs/heads/master
| 2020-05-05T00:09:22.753046
| 2019-05-13T14:31:06
| 2019-05-13T14:31:06
| 179,567,170
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 999
|
cpp
|
958_check_completeness_of_a_binary_tree.cpp
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isCompleteTree(TreeNode* root)
{
if(!root)
return false;
bool res = true;
queue<TreeNode*> nodes;
nodes.push(root);
while(!nodes.empty())
{
TreeNode* current = nodes.front();
nodes.pop();
if(current->left && current->right || current->left)
{
res = true;
nodes.push(current->left);
if(current->right)
nodes.push(current->right);
}
else if(!(!current->left && !current->right))
res = false;
if(!res)
break;
}
return res;
}
};
|
e8969cd375e0cd4f6b556c7c68be0f327053561e
|
4bcc9806152542ab43fc2cf47c499424f200896c
|
/tensorflow/tsl/platform/intrusive_ptr.h
|
3793ba3e8610ee5f8a93e1a1c9329d1361c8eee1
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] |
permissive
|
tensorflow/tensorflow
|
906276dbafcc70a941026aa5dc50425ef71ee282
|
a7f3934a67900720af3d3b15389551483bee50b8
|
refs/heads/master
| 2023-08-25T04:24:41.611870
| 2023-08-25T04:06:24
| 2023-08-25T04:14:08
| 45,717,250
| 208,740
| 109,943
|
Apache-2.0
| 2023-09-14T20:55:50
| 2015-11-07T01:19:20
|
C++
|
UTF-8
|
C++
| false
| false
| 2,808
|
h
|
intrusive_ptr.h
|
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_TSL_PLATFORM_INTRUSIVE_PTR_H_
#define TENSORFLOW_TSL_PLATFORM_INTRUSIVE_PTR_H_
#include <algorithm>
namespace tsl {
namespace core {
// A utility for managing the lifetime of ref-counted objects.
//
// Generally used for objects that derive from `tensorflow::RefCounted`.
template <class T>
class IntrusivePtr {
public:
// add_ref=false indicates that IntrusivePtr owns the underlying pointer.
//
// In most cases, we expect this to be called with add_ref=false, except in
// special circumstances where the lifetime of the underlying RefCounted
// object needs to be externally managed.
IntrusivePtr(T* h, bool add_ref) { reset(h, add_ref); }
IntrusivePtr(const IntrusivePtr& o) { reset(o.handle_, /*add_ref=*/true); }
IntrusivePtr(IntrusivePtr&& o) { *this = std::move(o); }
IntrusivePtr() {}
void reset(T* h, bool add_ref) {
if (h != handle_) {
if (add_ref && h) h->Ref();
if (handle_) handle_->Unref();
handle_ = h;
}
}
IntrusivePtr& operator=(const IntrusivePtr& o) {
reset(o.handle_, /*add_ref=*/true);
return *this;
}
IntrusivePtr& operator=(IntrusivePtr&& o) {
if (handle_ != o.handle_) {
// Must clear o.handle_ before calling reset to capture the case where
// handle_->member == o. In this case, calling handle_->Unref first would
// delete o.handle_ so we clear it out first.
reset(o.detach(), /*add_ref=*/false);
}
return *this;
}
bool operator==(const IntrusivePtr& o) const { return handle_ == o.handle_; }
T* operator->() const { return handle_; }
T& operator*() const { return *handle_; }
explicit operator bool() const noexcept { return get(); }
T* get() const { return handle_; }
// Releases ownership of the pointer without unreffing. Caller is responsible
// for calling Unref on the returned pointer.
T* detach() {
T* handle = handle_;
handle_ = nullptr;
return handle;
}
~IntrusivePtr() {
if (handle_) handle_->Unref();
}
private:
T* handle_ = nullptr;
};
} // namespace core
} // namespace tsl
#endif // TENSORFLOW_TSL_PLATFORM_INTRUSIVE_PTR_H_
|
59167eeeb0f63de3ae5c20e38da4780ec9262ea0
|
79a634d9357a750cbd0efea04d932938e1b7f632
|
/Contest/ACM/2010_bak/MULTIPLE_2010/MU Training Host by UESTC 2/MU Training Host by UESTC 2/Imaginary Date/sol_totalfrank.cpp
|
9155193fff00c4182b8c18c4fd26716f761ed255
|
[] |
no_license
|
hphp/Algorithm
|
5f42fe188422427a7762dbbe7af539b89fa796ed
|
ccbb368a37eed1b0cb37356026b299380f9c008b
|
refs/heads/master
| 2016-09-06T02:24:43.141927
| 2014-05-27T00:49:44
| 2014-05-27T00:49:44
| 14,009,913
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 464
|
cpp
|
sol_totalfrank.cpp
|
#include <stdio.h>
#include <string.h>
#define MAXN 1000
int a[MAXN];
int main(){
freopen("f:\\1.in", "r", stdin);
freopen("f:\\1.out", "w", stdout);
int t_case = 1, cases;
scanf("%d", &cases);
while(cases--){
int n, m, k, sum = 0;
scanf("%d%d%d", &n, &m, &k);
for(int i = 0; i < n; ++i){
scanf("%d", a + i);
sum += a[i];
}
double res = (double)sum / n * m;
printf("Case %d: %.5f\n", t_case++, res);
}
return 0;
}
|
f9147a9d56ef46a52e68ca1e1210eea2b169f734
|
296cd54ecfc92b89799451fc7aae6064db2a2fc1
|
/CInputHandle.cpp
|
5fd4711434bd219c5d49b83b4e6fd1e6fa7ad30b
|
[] |
no_license
|
Super-Karl/SDL_Practice
|
f8b739ad6e70331cce22fb2fbb18c6e2bae229f5
|
f9001eff2d5143c971c386787c18696154865212
|
refs/heads/master
| 2022-12-22T19:05:24.590975
| 2020-09-23T08:15:17
| 2020-09-23T08:15:17
| 297,859,695
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 26
|
cpp
|
CInputHandle.cpp
|
#include "CInputHandle.h"
|
7dcf65b997c668a352736165fa96bfe0f64c786d
|
95e7032edd93613c860f2507f2f210bbf74db26e
|
/Algoritmos_Grafos/main.cpp
|
68b62b3b71bd30c84b311ef4c955357f38bab74b
|
[] |
no_license
|
Dchengg/Algoritmos_Grafos
|
6fb938d54a9e26b760bab9f89cb26a3b4af9169e
|
c1e33e127f6612fb2411680dc475bfe37dabe4b5
|
refs/heads/master
| 2020-04-08T12:43:39.844424
| 2018-11-28T04:27:37
| 2018-11-28T04:27:37
| 159,359,046
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,822
|
cpp
|
main.cpp
|
#include <QCoreApplication>
#include <algoritmos.cpp>
#include <QFile>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
while(1){
qDebug()<<"ingrese el path del archivo que contiene la matriz : ";
string input;
std::cin >> input;
QString path = QString::fromStdString(input);
QFile* file = new QFile();
file->setFileName(path);
if(file->exists()){
if(!file->open(QIODevice::ReadWrite)) {
qDebug()<<"No se pudo abrir el archivo ";
}else{
QTextStream in(file);
int fila = 0;
qDebug()<<"Ingrese las filas de la matriz ";
int tam;
std::cin >> tam;
Grafo* g = new Grafo(tam);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList edge = line.split(",");
for(int col = 0; col<edge.size();col++)
g->addEdge(fila, col ,edge[col].toInt());
fila++;
}
while(!in.atEnd()) {
QString line = in.readLine();
QStringList edge = line.split(",");
for(int col = 0; col<edge.size();col++)
g->addEdge(fila, col ,edge[col].toInt());
fila++;
}
g->printGraph();
qDebug()<< "------Dijkstra---------";
dijkstra(g,0);
qDebug()<< "------Prim---------";
primMST(g);
qDebug()<< "------Kruskal---------";
kruskalMST(g);
}
}else
qDebug()<<"El archivo ingresado no existe";
}
return a.exec();
}
|
055ee327565287ed7edf53f9478438ae2b24fb88
|
ff5b783d7dd6bc66345c119f091f60149e3dc283
|
/pthreads/mutex.cc
|
e99ab16c660de91698f4af933d3bf92ed669cee2
|
[] |
no_license
|
wp4613/tests
|
0faa85ebde5b58538c181f5f22c21fb6d738e1ec
|
20489062e503c1162a23e1d1bed77d39e762905b
|
refs/heads/master
| 2020-03-18T13:36:53.311579
| 2015-12-23T19:45:48
| 2015-12-23T19:45:48
| 134,795,700
| 1
| 0
| null | 2018-05-25T02:57:53
| 2018-05-25T02:57:53
| null |
UTF-8
|
C++
| false
| false
| 745
|
cc
|
mutex.cc
|
#include <pthread.h>
#include <string.h>
#include <iostream>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char *argv[])
{
int rc = pthread_mutex_lock(&mutex);
if (rc != 0) {
std::cout << "error locking mutex: " << rc << "; system message: " << strerror(rc) << std::endl;
return 1;
}
rc = pthread_mutex_unlock(&mutex);
if (rc != 0) {
std::cout << "error (1) unlocking mutex: " << rc << "; system message: " << strerror(rc) << std::endl;
return 1;
}
rc = pthread_mutex_unlock(&mutex);
if (rc != 0) {
std::cout << "error (2) unlocking mutex: " << rc << "; system message: " << strerror(rc) << std::endl;
return 1;
}
return 0;
}
|
301374eb7cf4f0c43b313cb9cabd5056311d9b7e
|
f61bb2133a9f149febae0dac34e00f7e627822a9
|
/Graficos II/DLL/Shape.cpp
|
8ab7e91318f10969f1c5b2a03798736895d631f3
|
[] |
no_license
|
Lithiot/Graficos-II
|
35673d328693294462608414b01d1260c5dd90cc
|
3330eefe5d9e362f4ec27dea5b8a24d5cc503c89
|
refs/heads/master
| 2021-06-29T18:15:48.682390
| 2019-08-06T03:54:22
| 2019-08-06T03:54:22
| 144,927,528
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 852
|
cpp
|
Shape.cpp
|
#include "Shape.h"
Shape::Shape(Renderer* rend) : Entity(rend)
{
material = NULL;
vertexes = NULL;
vertexColors = NULL;
vertexUVTexture = NULL;
vertexBufferID = -1;
colorBufferID = -1;
textureBufferId = - 1;
textureUVBufferId = -1;
shouldDispose = true;
}
Shape::~Shape()
{
}
void Shape::SetVertex(float* vertex, int cant)
{
Dispose();
shouldDispose = true;
vertexBufferID = renderer->GenVertexBuffer(vertex, sizeof(float) * cant* 3);
}
void Shape::SetColors(float* vColor, int cant)
{
colorBufferID = renderer->GenColorBuffer(vColor, sizeof(float) * cant * 3);
}
void Shape::SetMaterial(Material* mat)
{
material = mat;
}
void Shape::Dispose()
{
if(shouldDispose)
{
renderer->DeleteBuffers(vertexBufferID);
renderer->DeleteBuffers(colorBufferID);
shouldDispose = false;
}
}
|
5f148236ae046b5353132ddb4da2eeb5832110b7
|
78ad8daf752bde132b03ea25640a94a86bd212cf
|
/boiler.ino
|
8ca5b943a10b79a765e44abe08adff66ce9acd81
|
[
"MIT"
] |
permissive
|
nsadovskiy/boiler
|
69d7c244d5ffcc0da6416e0c7be9635854904559
|
24985e2759476c66d62597afdfb490436a541f0d
|
refs/heads/master
| 2020-04-02T09:19:04.939006
| 2018-10-23T10:48:08
| 2018-10-23T10:48:08
| 154,287,152
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,095
|
ino
|
boiler.ino
|
#include "LiquidCrystal_I2C.h"
#include "cactus_io_DS18B20.h"
#include "settings.h"
#include "heater_mode.h"
#include "temp_range.h"
#include "pipe.h"
#include "electro_regime.h"
#include "coal_regime.h"
#include "electro_heater.h"
volatile int wait_tick = 0;
DS18B20 ds(9);
LiquidCrystal_I2C lcd(0x27, 16, 2);
pipe_t pipe(RELAY_PIN);
heater_mode_t heater_mode;
electro_heater_t electro_heater(heater_mode);
temp_range_t temp_range(HEATER_HYSTERESIS, HEATER_MIN_TEMP, HEATER_MAX_TEMP, POT_MIN_VALUE, POT_MAX_VALUE);
electro_regime_t electro_heating(temp_range, pipe, electro_heater);
coal_regime_t coal_heating(pipe, PIPE_LOW_TEMPERATURE, PIPE_HIGH_TEMPERATURE, electro_heater);
void on_press_button() {
if (wait_tick == 0) {
heater_mode.switch_mode();
wait_tick = static_cast<int>(static_cast<float>(300)/static_cast<float>(REFRESH_PERIOD));
}
}
void setup() {
pipe.init();
lcd.init();
lcd.backlight();
pinMode(2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), on_press_button, FALLING);
}
void lcd_out(float current_temp) {
lcd.setCursor(0, 0);
lcd.print(String(current_temp, 1));
lcd.print((char)223);
lcd.setCursor(0, 1);
lcd.print(String(temp_range.get_min_value()));
lcd.print("-");
lcd.print(String(temp_range.get_max_value()));
lcd.print(" ");
lcd.print(heater_mode.get_mode());
}
void loop() {
ds.readSensor();
float current_temp = ds.getTemperature_C();
temp_range.set_pot_value(analogRead(TEMP_POT_PIN));
abstract_regime_t & heater = heater_mode.is_on() ? static_cast<abstract_regime_t &>(electro_heating) : static_cast<abstract_regime_t &>(coal_heating);
heater.process_temperature(current_temp);
lcd_out(current_temp);
// dtostrf(ds.getTemperature_C(), 4, 2, currentTemp);
//sprintf(line1, "%5s C", String(ds.getTemperature_C(), 1).c_str());
//lcd.setCursor(0, 0);
// lcd.print(String(ds.getTemperature_C(), 1));
//lcd.print(line1);
// lcd.print(String(val-5));
// lcd.print("-");
// lcd.print(String(val));
if (wait_tick > 0) {
--wait_tick;
};
delay(REFRESH_PERIOD);
}
|
9d7babbca0af49381c1fae166fd520cc65a1548d
|
94ccd13d597dcdc844e6af80fd1ed5665bcbd059
|
/Prophecy/Prophecy/src/Prophecy/Core/Base.h
|
ece7f7b62ba86592f52ae4b120f782ef8171a83d
|
[] |
no_license
|
johnnymast/Prophecy
|
4ec3796e9d82c75f64e7abf861bcf2531570107a
|
3025faeeb0b3df216b05771bdc783e7246687caa
|
refs/heads/master
| 2022-11-26T10:04:08.117201
| 2020-06-30T02:12:23
| 2020-06-30T02:12:23
| 272,237,842
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 643
|
h
|
Base.h
|
#pragma once
#include <memory>
#define BIT(x) (1 << x)
#define HZ_BIND_EVENT_FN(fn) std::bind(&fn, this, std::placeholders::_1)
namespace Prophecy {
template<typename T>
using Scope = std::unique_ptr<T>;
template<typename T, typename ... Args>
constexpr Scope<T> CreateScope(Args&& ... args)
{
return std::make_unique<T>(std::forward<Args>(args)...);
}
template<typename T>
using Ref = std::shared_ptr<T>;
template<typename T, typename ... Args>
constexpr Ref<T> CreateRef(Args&& ... args)
{
return std::make_shared<T>(std::forward<Args>(args)...);
}
}
#include "Log.h"
|
3b72d457f8f1ac2e962bb03b13bb18a63c3d3166
|
10f91ad3a4b7f273ef7d981c113ad17c218745b7
|
/src/placeable/placeable.h
|
3b601f4c70716d72becc3d8a4ff76c0989f0b2f6
|
[] |
no_license
|
VictorCarlquist/RedMoon
|
74a28a1e8b1273f89212e3852d23c8e5534da3b4
|
ea1eddf3a29f68d760980c2a42c554afe32afbc8
|
refs/heads/master
| 2021-01-02T08:56:46.158397
| 2014-02-02T00:52:37
| 2014-02-02T00:52:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 847
|
h
|
placeable.h
|
#include <lua5.2/lua.hpp>
#ifndef __placeable_H__
#define __placeable_H__
namespace red
{
class Rplaceable
{
public:
Rplaceable(){
this->lx = this->ly = this->lz = 0;
this->rx = this->ry = this->rz = 0;
}
void setLoc(float x,float y,float z);
void setLocX(float x);
void setLocY(float y);
void setLocZ(float z);
float* getLoc();
float getLocX();
float getLocY();
float getLocZ();
void setRot(float x,float y,float z);
void setRotX(float x);
void setRotY(float y);
void setRotZ(float z);
float getRotX();
float getRotY();
float getRotZ();
void moveAt(float x, float y, float z);
private:
float lx,ly,lz;
float rx,ry,rz;
};
void RegisterRplaceable(lua_State *l);
}
#endif
|
c83934ca90d3035097f0c2b85bfdd2143e9712f3
|
e0548caf7bd8153f8d991b7d7c1bed487402f0bc
|
/semestr-2/Programowanie/2020/podstawy-programowania-5/ćwiczenia/zad01.cpp
|
2bc126adbecd7f80f30079a7eac06e8f51fd91c1
|
[] |
no_license
|
Ch3shireDev/WIT-Zajecia
|
58d9ca03617ba07bd25ce439aeeca79533f0bcb6
|
3cd4f7dea6abdf7126c44a1d856ca5b6002813ca
|
refs/heads/master
| 2023-09-01T11:32:12.636305
| 2023-08-28T16:48:03
| 2023-08-28T16:48:03
| 224,985,239
| 19
| 24
| null | 2023-07-02T20:54:18
| 2019-11-30T08:57:27
|
C
|
UTF-8
|
C++
| false
| false
| 1,211
|
cpp
|
zad01.cpp
|
// Zadanie 1
// Napisz program który sortuje bąbelkowo dowolną podaną ilość liczb rzeczywistych. podawanie liczb kończy naciśniecie klawisza "esc". Posortowane liczby zapisuje do pliku i dodatkowo wyświetla je na ekranie za pomocą printf.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template <typename T>
string show(vector<T> tab)
{
string str;
for (auto it = tab.begin(); it != tab.end(); it++)
{
str += " "+to_string(*it);
}
return str;
}
template <typename T>
void sort(vector<T> &tab){
for(auto it1 = tab.begin();it1!=tab.end();it1++){
for(auto it2 = tab.begin();it2!=tab.end()-1;it2++){
T a = *it2;
T b = *(it2+1);
if(a>b){
*(it2+1) = a;
*(it2) = b;
}
}
}
}
int main()
{
vector<double> tab = vector<double>();
double in;
cout << "Podaj zestaw liczb. Zakończ kombinacją CTRL+D: ";
while (cin >> in)
{
tab.push_back(in);
}
cout << "Podane liczby: " << show(tab) << endl;
cout<<"Sortowanie..."<<endl;
sort(tab);
cout<<"Posortowane liczby: "<<show(tab)<<endl;
return 0;
}
|
918c89a3fd1318e697bd484cf64d1429fde1f26f
|
6bcc59b991641987630b4b729d2ea86492e53854
|
/vulkan-solar-system/src/engine/Application.h
|
b35ad7d08ca3d38d2bc5af0efcd59ab187dce6a4
|
[
"MIT"
] |
permissive
|
LucidSigma/vulkan-solar-system
|
302d60fbc7c63cfd6a2a195e99ed17dd5b65ef4c
|
b30d36049be177575501d9d6274eb3b80241f7bd
|
refs/heads/master
| 2022-10-08T20:56:51.869448
| 2020-06-02T08:36:26
| 2020-06-02T08:36:26
| 268,712,098
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,278
|
h
|
Application.h
|
#pragma once
#include "utility/interfaces/INoncopyable.h"
#include "utility/interfaces/INonmovable.h"
#include <cstdint>
#include <json/json.hpp>
#include "graphics/renderer/Renderer.h"
#include "input/InputManager.h"
#include "scene/Scene.h"
#include "utility/Config.h"
#include "utility/SceneManager.h"
#include "window/Window.h"
class Application final
: private INoncopyable, private INonmovable
{
private:
std::unique_ptr<Window> m_window = nullptr;
std::unique_ptr<Renderer> m_renderer = nullptr;
bool m_hasFocus = true;
bool m_isRunning = true;
std::uint64_t m_ticksCount = 0;
InputManager m_inputManager;
Config m_config;
SceneManager m_sceneManager;
bool m_isCurrentSceneFinished = false;
public:
Application();
~Application() noexcept;
void Run();
void FinishCurrentScene();
inline const Window& GetWindow() const noexcept { return *m_window; }
inline Renderer& GetRenderer() noexcept { return *m_renderer; }
inline const Config& GetConfig() const noexcept { return m_config; }
inline SceneManager& GetSceneManager() noexcept { return m_sceneManager; }
private:
void Initialise();
void PollEvents(SDL_Event& event);
void ProcessInput();
void Update();
void Render() const;
void UpdateSceneQueue();
float CalculateDeltaTime();
};
|
b752d1647af03c376d1648433dff3a738e0b1b21
|
154170bb6acb3e17a863dfae5c6c4411665daec5
|
/tests/runtime_tests/SExpressionTests.cpp
|
2ff0ede11f6721d5c4773a51fa8ca82530f6e958
|
[
"Apache-2.0"
] |
permissive
|
smacdo/Shiny
|
8d076824013d0fb7d94bdf351e10aee18013f61b
|
580f8bb240b3ece72d7181288bacaba5ecd7071e
|
refs/heads/master
| 2021-07-11T21:59:43.263042
| 2021-04-11T18:25:37
| 2021-04-11T18:25:37
| 23,687,447
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,254
|
cpp
|
SExpressionTests.cpp
|
#include "runtime/SExpression.h"
#include <catch2/catch.hpp>
using namespace Shiny;
TEST_CASE("Default initialize atom S-Expression", "[SExpression]") {
SExprAtom a{};
REQUIRE(a.value().isEmptyList());
}
TEST_CASE("Create a atom S-Expression with a value", "[SExpression]") {
SExprAtom a{Value{23}};
REQUIRE(Value{23} == a.value());
const SExprAtom b{Value{-25}};
REQUIRE(Value{-25} == b.value());
}
TEST_CASE("Set an atom S-Expression with a new value", "[SExpression]") {
SExprAtom a{Value{123}};
REQUIRE(Value{123} == a.value());
a.setValue(Value{'~'});
REQUIRE(Value{'~'} == a.value());
}
TEST_CASE("Create a list S-Expression node", "[SExpression") {
auto child = std::make_unique<SExprAtom>(Value{32});
auto sibling = std::make_unique<SExprAtom>(Value{-7});
auto node = std::make_unique<SExprList>(std::move(child), std::move(sibling));
auto c = dynamic_cast<SExprAtom*>(node->firstChild());
auto s = dynamic_cast<SExprAtom*>(node->nextSibling());
REQUIRE(Value{32} == c->value());
REQUIRE(Value{-7} == s->value());
}
TEST_CASE("Test if list S-Expression has a child", "[SExpression") {
SECTION("when constructed with a child") {
auto child = std::make_unique<SExprAtom>(Value{32});
auto sibling = std::make_unique<SExprAtom>(Value{-7});
auto node =
std::make_unique<SExprList>(std::move(child), std::move(sibling));
auto cNode = static_cast<const SExprList*>(node.get());
REQUIRE(node->hasChild());
REQUIRE(cNode->hasChild());
}
SECTION("when constructed without a child") {
auto child = nullptr;
auto sibling = std::make_unique<SExprAtom>(Value{-7});
auto node =
std::make_unique<SExprList>(std::move(child), std::move(sibling));
auto cNode = static_cast<const SExprList*>(node.get());
REQUIRE_FALSE(node->hasChild());
REQUIRE_FALSE(cNode->hasChild());
}
}
TEST_CASE("Test if list S-Expression has a sibling", "[SExpression") {
SECTION("when constructed with a sibling") {
auto child = std::make_unique<SExprAtom>(Value{32});
auto sibling = std::make_unique<SExprAtom>(Value{-7});
auto node =
std::make_unique<SExprList>(std::move(child), std::move(sibling));
auto cNode = static_cast<const SExprList*>(node.get());
REQUIRE(node->hasNextSibling());
REQUIRE(cNode->hasNextSibling());
}
SECTION("when constructed without a sibling") {
auto child = std::make_unique<SExprAtom>(Value{32});
auto sibling = nullptr;
auto node =
std::make_unique<SExprList>(std::move(child), std::move(sibling));
auto cNode = static_cast<const SExprList*>(node.get());
REQUIRE_FALSE(node->hasNextSibling());
REQUIRE_FALSE(cNode->hasNextSibling());
}
}
TEST_CASE("Set first child on list S-Expression", "[SExpression") {
SECTION("when initially null") {
auto node = std::make_unique<SExprList>();
auto cNode = static_cast<const SExprList*>(node.get());
REQUIRE(nullptr == node->firstChild());
REQUIRE(nullptr == cNode->firstChild());
node->setFirstChild(std::make_unique<SExprAtom>(Value{'c'}));
auto c = dynamic_cast<SExprAtom*>(node->firstChild());
REQUIRE(Value{'c'} == c->value());
}
SECTION("replaces previously set first child") {
auto node = std::make_unique<SExprList>();
auto cNode = static_cast<const SExprList*>(node.get());
REQUIRE(nullptr == node->firstChild());
REQUIRE(nullptr == cNode->firstChild());
node->setFirstChild(std::make_unique<SExprAtom>(Value{'c'}));
node->setFirstChild(std::make_unique<SExprAtom>(Value{-100}));
auto c = dynamic_cast<SExprAtom*>(node->firstChild());
REQUIRE(Value{-100} == c->value());
}
}
TEST_CASE("Set next sibling on list S-Expression", "[SExpression") {
SECTION("when initially null") {
auto node = std::make_unique<SExprList>();
auto cNode = static_cast<const SExprList*>(node.get());
REQUIRE(nullptr == node->nextSibling());
REQUIRE(nullptr == cNode->nextSibling());
node->setNextSibling(std::make_unique<SExprAtom>(Value{'c'}));
auto c = dynamic_cast<SExprAtom*>(node->nextSibling());
REQUIRE(Value{'c'} == c->value());
}
SECTION("replaces previously set next sibling") {
auto node = std::make_unique<SExprList>();
auto cNode = static_cast<const SExprList*>(node.get());
REQUIRE(nullptr == node->nextSibling());
REQUIRE(nullptr == cNode->nextSibling());
node->setNextSibling(std::make_unique<SExprAtom>(Value{'c'}));
node->setNextSibling(std::make_unique<SExprAtom>(Value{-100}));
auto c = dynamic_cast<SExprAtom*>(node->nextSibling());
REQUIRE(Value{-100} == c->value());
}
}
TEST_CASE("Visit an atom S-Expression", "[SExpression]") {
SExprAtom a{Value{88888}};
SECTION("with regular visitor") {
class SCustomVisitor : public SExpressionVisitor {
public:
SCustomVisitor(Value* resultOut) : resultOut_(resultOut) {
REQUIRE(nullptr != resultOut);
}
void visit(SExprAtom& sexpr) override { *resultOut_ = sexpr.value(); }
void visit(SExprList& sexpr) override { FAIL(); }
private:
Value* resultOut_;
};
SExprAtom a{Value{321}};
SExprAtom b{Value{false}};
Value result;
SCustomVisitor v{&result};
a.accept(v);
REQUIRE(Value{321} == result);
b.accept(v);
REQUIRE(Value{false} == result);
}
SECTION("with const visitor") {
class SCustomVisitor : public ConstSExpressionVisitor {
public:
SCustomVisitor(Value* resultOut) : resultOut_(resultOut) {
REQUIRE(nullptr != resultOut);
}
void visit(const SExprAtom& sexpr) override {
*resultOut_ = sexpr.value();
}
void visit(const SExprList& sexpr) override { FAIL(); }
private:
Value* resultOut_;
};
const SExprAtom a{Value{5}};
SExprAtom b{Value{'X'}};
Value result;
SCustomVisitor v{&result};
a.accept(v);
REQUIRE(Value{5} == result);
b.accept(v);
REQUIRE(Value{'X'} == result);
}
}
TEST_CASE("Visit a list S-Expression", "[SExpression]") {
SECTION("with regular visitor") {
class SCustomVisitor : public SExpressionVisitor {
public:
SCustomVisitor(Value* childOut, Value* siblingOut)
: childOut_(childOut),
siblingOut_(siblingOut) {
REQUIRE(nullptr != childOut);
REQUIRE(nullptr != siblingOut);
}
void visit(SExprAtom& sexpr) override { FAIL(); }
void visit(SExprList& sexpr) override {
*childOut_ = dynamic_cast<SExprAtom*>(sexpr.firstChild())->value();
*siblingOut_ = dynamic_cast<SExprAtom*>(sexpr.nextSibling())->value();
}
private:
Value* childOut_;
Value* siblingOut_;
};
auto child = std::make_unique<SExprAtom>(Value{'C'});
auto sibling = std::make_unique<SExprAtom>(Value{'s'});
auto node =
std::make_unique<SExprList>(std::move(child), std::move(sibling));
Value childValue, siblingValue;
SCustomVisitor v{&childValue, &siblingValue};
node->accept(v);
REQUIRE(Value{'C'} == childValue);
REQUIRE(Value{'s'} == siblingValue);
}
SECTION("with const visitor") {
class SCustomVisitor : public ConstSExpressionVisitor {
public:
SCustomVisitor(Value* childOut, Value* siblingOut)
: childOut_(childOut),
siblingOut_(siblingOut) {
REQUIRE(nullptr != childOut);
REQUIRE(nullptr != siblingOut);
}
void visit(const SExprAtom& sexpr) override { FAIL(); }
void visit(const SExprList& sexpr) override {
*childOut_ =
dynamic_cast<const SExprAtom*>(sexpr.firstChild())->value();
*siblingOut_ =
dynamic_cast<const SExprAtom*>(sexpr.nextSibling())->value();
}
private:
Value* childOut_;
Value* siblingOut_;
};
auto child = std::make_unique<SExprAtom>(Value{'C'});
auto sibling = std::make_unique<SExprAtom>(Value{'s'});
auto node =
std::make_unique<const SExprList>(std::move(child), std::move(sibling));
Value childValue, siblingValue;
SCustomVisitor v{&childValue, &siblingValue};
node->accept(v);
REQUIRE(Value{'C'} == childValue);
REQUIRE(Value{'s'} == siblingValue);
}
}
|
7e21294f5841bd6d7dd51d8bf31dcdcae77729e0
|
d40cd56de69419989761e01255b868f36bcb5caa
|
/include/mapdrawer.h
|
5dc698f8c55d637802f8a6e62de3f0780852e195
|
[] |
no_license
|
koval4/DarkAsteroids
|
974f31ab1f382928ed6cff51ae4939e5d7392e0c
|
62d09bae6cfba2f08a92cbff31a3abba0d4aa8ff
|
refs/heads/master
| 2020-05-21T04:35:58.485559
| 2018-07-21T11:06:34
| 2018-07-21T11:06:34
| 56,937,818
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 339
|
h
|
mapdrawer.h
|
#ifndef MAPDRAWER_H
#define MAPDRAWER_H
#include "ui/screen.h"
#include "ui/gui.h"
#include "tile.h"
#include "map.h"
class MapDrawer {
private:
const uint8_t tiles_horizntally;
const uint8_t tiles_vertically;
public:
MapDrawer();
void draw_map(Tile::ptr center) const;
};
#endif // MAPDRAWER_H
|
250d8bef6ff62ff0f794d67a5232948bcf15956a
|
fe6c1528174ee96ad662fbdf52fb2ebd072bc55c
|
/Turbo/Camera.cpp
|
91fe6846fe672d13c893121bd33c8b74ec2a64c3
|
[] |
no_license
|
just3obad/Turbo-Final
|
ae8973bee1f5872df86e99c45e14a8090fcede68
|
5902206b515913d68665fc1e7f44190e6c3a0b0d
|
refs/heads/master
| 2021-01-10T09:32:16.355090
| 2016-02-08T21:25:24
| 2016-02-08T21:25:24
| 51,302,618
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 951
|
cpp
|
Camera.cpp
|
// #include "stdafx.h"
#include "Camera.h"
#include "gtc/matrix_transform.hpp"
Camera::Camera()
{
_position = glm::vec3(1, 0, 0);
_up = glm::vec3(0, 1, 0);
_look = glm::vec3(0, 0, 0);
_near = 0.1f;
_far = 5000.0f;
_xang = 0.5f;
_yang = 0.0f;
_fov = 45.f;
_aspect = 4.0f / 3.0f;
}
glm::mat4 Camera::getCamera()
{
glm::mat4 camera = glm::perspective(glm::radians(_fov), _aspect, _near, _far) * glm::lookAt(_position, _look, _up);;
return camera;
}
glm::vec3 Camera::getUp()
{
return glm::vec3(0.0, 1.0, 0.0);
}
glm::vec3 Camera::getRight()
{
return glm::normalize(glm::cross(getDirection(), _up));
}
glm::vec3 Camera::getPosition()
{
return _position;
}
void Camera::setPosition(glm::vec3 inVec)
{
_position = inVec;
}
glm::vec3 Camera::getDirection()
{
return glm::normalize(_look - _position);
}
glm::vec3 Camera::getLookat()
{
return _look;
}
void Camera::setLockat(glm::vec3 inVec)
{
_look = inVec;
}
Camera::~Camera()
{
}
|
26e0c7cf266c4538e1d80aa3f5f7218d30bd4de2
|
dfd413672b1736044ae6ca2e288a69bf9de3cfda
|
/chrome/common/temp_scaffolding_stubs.cc
|
936e35bf3306f5531dc1b3c2cecd57bc3c597bc3
|
[
"BSD-3-Clause"
] |
permissive
|
cha63506/chromium-capsicum
|
fb71128ba218fec097265908c2f41086cdb99892
|
b03da8e897f897c6ad2cda03ceda217b760fd528
|
HEAD
| 2017-10-03T02:40:24.085668
| 2010-02-01T15:24:05
| 2010-02-01T15:24:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,871
|
cc
|
temp_scaffolding_stubs.cc
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/temp_scaffolding_stubs.h"
#include <vector>
#include "base/gfx/rect.h"
#include "base/logging.h"
#include "chrome/browser/automation/automation_provider.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/fonts_languages_window.h"
#include "chrome/browser/memory_details.h"
//--------------------------------------------------------------------------
void AutomationProvider::GetAutocompleteEditForBrowser(
int browser_handle,
bool* success,
int* autocomplete_edit_handle) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::GetAutocompleteEditText(int autocomplete_edit_handle,
bool* success,
std::wstring* text) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::SetAutocompleteEditText(int autocomplete_edit_handle,
const std::wstring& text,
bool* success) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::AutocompleteEditGetMatches(
int autocomplete_edit_handle,
bool* success,
std::vector<AutocompleteMatchData>* matches) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::AutocompleteEditIsQueryInProgress(
int autocomplete_edit_handle,
bool* success,
bool* query_in_progress) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::OnMessageFromExternalHost(
int handle, const std::string& message, const std::string& origin,
const std::string& target) {
NOTIMPLEMENTED();
}
void InstallJankometer(const CommandLine&) {
// http://code.google.com/p/chromium/issues/detail?id=8077
}
void UninstallJankometer() {
// http://code.google.com/p/chromium/issues/detail?id=8077
}
void BrowserList::AllBrowsersClosed() {
// TODO(port): Close any dependent windows if necessary when the last browser
// window is closed.
}
//--------------------------------------------------------------------------
bool DockInfo::GetNewWindowBounds(gfx::Rect* new_window_bounds,
bool* maximize_new_window) const {
// TODO(pinkerton): Implement on Mac.
// http://crbug.com/9274
return true;
}
void DockInfo::AdjustOtherWindowBounds() const {
// TODO(pinkerton): Implement on Mac.
// http://crbug.com/9274
}
//------------------------------------------------------------------------------
void ShowFontsLanguagesWindow(gfx::NativeWindow window,
FontsLanguagesPage page,
Profile* profile) {
NOTIMPLEMENTED();
}
|
6f1c2228904ebab9741dee16d761de895bf52447
|
8097da7acfa8fb56dd8d4df9a68f6557a62821cc
|
/BACnet/ISO 8859-1.cpp
|
6bdadab81d6ae0065628f035009713ef20dbba07
|
[] |
no_license
|
rtsking117/BACnet
|
367453aac59721f0cafad77a5227f1a3c11031d2
|
ff70361244a0d692ae3fd852d1290fd97d89070e
|
refs/heads/master
| 2020-03-16T12:34:20.112602
| 2018-11-05T04:46:01
| 2018-11-05T04:46:01
| 132,669,956
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 789
|
cpp
|
ISO 8859-1.cpp
|
#include "ISO 8859-1.h"
//This table is actually Windows-1252. We interpret C1 control
//characters as their Windows-1252 counterparts, as they are rarely
//used in text, and more commonly text labeled as 8859-1 is actually
//Windows 1252 (enough such that HTML 5 mandates Windows 1252 instead
//of ISO 8859-1, even when labeled as such).
//array starts at 0x80.
CodePoint C1Map[] = {
0x20AC,
129,
0x201A,
0x0192,
0x201E,
0x2026,
0x2020,
0x2021,
0x02C6,
0x2030,
0x0160,
0x2039,
0x0152,
141,
0x017D,
143,
144,
0x2018,
0x2019,
0x201C,
0x201D,
0x2022,
0x2013,
0x2014,
0x02DC,
0x2122,
0x0161,
0x203A,
0x0153,
157,
0x017E,
0x0178,
};
CodePoint ConvertISOCharToCodePoint(U8 ch)
{
if(ch >= 0x80 && ch < 0xA0)
{
return C1Map[ch];
}
return (CodePoint)ch;
}
|
2eec45059be7b77b06ab82d0b19f3a467de85c3b
|
eda03521b87da8bdbef6339b5b252472a5be8d23
|
/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/AST/AST.h
|
77df78963f64baabe102376a7464dbac38356ca2
|
[
"GPL-1.0-or-later",
"BSD-2-Clause"
] |
permissive
|
SerenityOS/serenity
|
6ba3ffb242ed76c9f335bd2c3b9a928329cd7d98
|
ef9b6c25fafcf4ef0b44a562ee07f6412aeb8561
|
refs/heads/master
| 2023-09-01T13:04:30.262106
| 2023-09-01T08:06:28
| 2023-09-01T10:45:38
| 160,083,795
| 27,256
| 3,929
|
BSD-2-Clause
| 2023-09-14T21:00:04
| 2018-12-02T19:28:41
|
C++
|
UTF-8
|
C++
| false
| false
| 6,853
|
h
|
AST.h
|
/*
* Copyright (c) 2023, Dan Klishch <danilklishch@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/RefCounted.h>
#include <AK/RefPtr.h>
#include <AK/Vector.h>
#include "Forward.h"
namespace JSSpecCompiler {
template<typename T>
RefPtr<T> as(NullableTree const& tree)
{
return dynamic_cast<T*>(tree.ptr());
}
// ===== Generic nodes =====
class Node : public RefCounted<Node> {
public:
virtual ~Node() = default;
void format_tree(StringBuilder& builder);
virtual bool is_type() { return false; }
protected:
template<typename... Parameters>
void dump_node(StringBuilder& builder, AK::CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters);
virtual void dump_tree(StringBuilder& builder) = 0;
};
class ErrorNode : public Node {
public:
ErrorNode() { }
protected:
void dump_tree(StringBuilder& builder) override;
};
inline Tree const error_tree = make_ref_counted<ErrorNode>();
// ===== Concrete evaluatable nodes =====
class MathematicalConstant : public Node {
public:
MathematicalConstant(i64 number)
: m_number(number)
{
}
// TODO: This should be able to hold arbitrary number
i64 m_number;
protected:
void dump_tree(StringBuilder& builder) override;
};
class StringLiteral : public Node {
public:
StringLiteral(StringView literal)
: m_literal(literal)
{
}
StringView m_literal;
protected:
void dump_tree(StringBuilder& builder) override;
};
#define ENUMERATE_UNARY_OPERATORS(F) \
F(Invalid) \
F(Minus) \
F(AssertCompletion)
#define ENUMERATE_BINARY_OPERATORS(F) \
F(Invalid) \
F(CompareLess) \
F(CompareGreater) \
F(CompareNotEqual) \
F(CompareEqual) \
F(Assignment) \
F(Declaration) \
F(Plus) \
F(Minus) \
F(Multiplication) \
F(Division) \
F(Comma) \
F(MemberAccess) \
F(FunctionCall) \
F(ArraySubscript)
#define NAME(name) name,
#define STRINGIFY(name) #name##sv,
enum class UnaryOperator {
ENUMERATE_UNARY_OPERATORS(NAME)
};
inline constexpr StringView unary_operator_names[] = {
ENUMERATE_UNARY_OPERATORS(STRINGIFY)
};
enum class BinaryOperator {
#define NAME(name) name,
ENUMERATE_BINARY_OPERATORS(NAME)
};
inline constexpr StringView binary_operator_names[] = {
ENUMERATE_BINARY_OPERATORS(STRINGIFY)
};
#undef NAME
#undef STRINGIFY
class BinaryOperation : public Node {
public:
BinaryOperation(BinaryOperator operation, Tree left, Tree right)
: m_operation(operation)
, m_left(left)
, m_right(right)
{
}
BinaryOperator m_operation;
Tree m_left;
Tree m_right;
protected:
void dump_tree(StringBuilder& builder) override;
};
class UnaryOperation : public Node {
public:
UnaryOperation(UnaryOperator operation, Tree operand)
: m_operation(operation)
, m_operand(operand)
{
}
UnaryOperator m_operation;
Tree m_operand;
protected:
void dump_tree(StringBuilder& builder) override;
};
class IsOneOfOperation : public Node {
public:
IsOneOfOperation(Tree operand, Vector<Tree>&& compare_values)
: m_operand(operand)
, m_compare_values(move(compare_values))
{
}
Tree m_operand;
Vector<Tree> m_compare_values;
protected:
void dump_tree(StringBuilder& builder) override;
};
class UnresolvedReference : public Node {
public:
UnresolvedReference(StringView name)
: m_name(name)
{
}
StringView m_name;
protected:
void dump_tree(StringBuilder& builder) override;
};
class ReturnExpression : public Node {
public:
ReturnExpression(Tree return_value)
: m_return_value(return_value)
{
}
Tree m_return_value;
protected:
void dump_tree(StringBuilder& builder) override;
};
class AssertExpression : public Node {
public:
AssertExpression(Tree condition)
: m_condition(condition)
{
}
Tree m_condition;
protected:
void dump_tree(StringBuilder& builder) override;
};
class IfBranch : public Node {
public:
IfBranch(Tree condition, Tree branch)
: m_condition(condition)
, m_branch(branch)
{
}
Tree m_condition;
Tree m_branch;
protected:
void dump_tree(StringBuilder& builder) override;
};
class ElseIfBranch : public Node {
public:
ElseIfBranch(Optional<Tree> condition, Tree branch)
: m_condition(condition)
, m_branch(branch)
{
}
Optional<Tree> m_condition;
Tree m_branch;
protected:
void dump_tree(StringBuilder& builder) override;
};
class TreeList : public Node {
public:
TreeList(Vector<Tree>&& expressions_)
: m_expressions(move(expressions_))
{
}
Vector<Tree> m_expressions;
protected:
void dump_tree(StringBuilder& builder) override;
};
class RecordDirectListInitialization : public Node {
public:
struct Argument {
Tree name;
Tree value;
};
RecordDirectListInitialization(Tree type_reference, Vector<Argument>&& arguments)
: m_type_reference(type_reference)
, m_arguments(move(arguments))
{
}
Tree m_type_reference;
Vector<Argument> m_arguments;
protected:
void dump_tree(StringBuilder& builder) override;
};
class FunctionCall : public Node {
public:
FunctionCall(Tree name, Vector<Tree>&& arguments)
: m_name(name)
, m_arguments(move(arguments))
{
}
Tree m_name;
Vector<Tree> m_arguments;
protected:
void dump_tree(StringBuilder& builder) override;
};
class SlotName : public Node {
public:
SlotName(StringView member_name)
: m_member_name(member_name)
{
}
StringView m_member_name;
protected:
void dump_tree(StringBuilder& builder) override;
};
class Variable : public Node {
public:
Variable(StringView variable_name)
: m_name(variable_name)
{
}
StringView m_name;
protected:
void dump_tree(StringBuilder& builder) override;
};
class FunctionPointer : public Node {
public:
FunctionPointer(StringView function_name)
: m_function_name(function_name)
{
}
StringView m_function_name;
protected:
void dump_tree(StringBuilder& builder) override;
};
}
namespace AK {
template<>
struct Formatter<JSSpecCompiler::Tree> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, JSSpecCompiler::Tree const& tree)
{
tree->format_tree(builder.builder());
return {};
}
};
}
|
42c4847772ec2664316b0e3a9b8c49fa69c51eb2
|
bcce0782e6f2d2ac2c9589370886d7e2d2fd4643
|
/jump.h
|
ac5e61c3963efa3b8b49fc5daa783efcdd7e4aed
|
[] |
no_license
|
janmal8359/practice_TeamMonster
|
d5b46916e88d6d01e3dd94ebd1bb0f1c9b7daf2a
|
927633aeb50a6ad4151b8f7f88e5456e35b4e630
|
refs/heads/master
| 2023-07-05T06:57:14.154679
| 2021-07-29T08:41:59
| 2021-07-29T08:41:59
| 388,361,904
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 356
|
h
|
jump.h
|
#pragma once
#include "stateManager.h"
#define JUMPPOWER 12.0f
#define GRAVITy 0.08f
class jump : public stateManager
{
private:
public:
virtual HRESULT init(); //초기화 함수
virtual void release(); //메모리 해제 함슈
virtual void update(); //연산하는 함수
virtual void render(); //그리기 함수
virtual void move();
};
|
8ce16008452bc72d943563b0534d2d729727d13d
|
1472dcb5a3244a51154f798666d0330ff32c68f5
|
/src/taSerializeHistogram.h
|
7b10bfef655dc01de5ffe14a470aaff720db623e
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
Osprey-DPD/osprey-dpd
|
3961ca5c0fe89514299812ded9c8c16a5f049987
|
d6e9bb6771e36c36811ef2d9405f9e287bb5f1c5
|
refs/heads/main
| 2023-06-11T08:49:06.866378
| 2023-06-08T14:23:39
| 2023-06-08T14:23:39
| 308,352,022
| 22
| 3
|
NOASSERTION
| 2023-06-08T14:23:41
| 2020-10-29T14:23:30
|
C++
|
UTF-8
|
C++
| false
| false
| 2,072
|
h
|
taSerializeHistogram.h
|
// taSerializeHistogram.h: interface for the taSerializeHistogram class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_TASERIALIZEHISTOGRAM_H__C98CF226_94E1_4607_9670_655AF9E0EBDF__INCLUDED_)
#define AFX_TASERIALIZEHISTOGRAM_H__C98CF226_94E1_4607_9670_655AF9E0EBDF__INCLUDED_
// Forward declarations
class taHistogramDecorator;
#include "taFileLabel.h"
class taSerializeHistogram : public taFileLabel
{
public:
// ****************************************
// Construction/Destruction
public:
taSerializeHistogram(const zString fileName, const zString label,
CCommandTargetNode* const pDec);
virtual ~taSerializeHistogram();
// ****************************************
// Global functions, static member functions and variables
public:
static const zString GetType(); // return the target's type
private:
static const zString m_Type;
// ****************************************
// PVFs that must be implemented by all instantiated derived classes
public:
const zString GetTargetType() const; // return the target's type
// Implementation of the ISerialiseInclusiveRestartState interface
// to allow this class to read/write data that can be modified
// for restarts.
virtual zInStream& Read(zInStream& is);
virtual zOutStream& Write(zOutStream& is) const;
bool Serialize();
// ****************************************
// Public access functions
public:
void SetHistogram(taHistogramDecorator* const pHistogram);
// ****************************************
// Protected local functions
protected:
// ****************************************
// Implementation
// ****************************************
// Private functions
private:
// ****************************************
// Data members
protected:
private:
taHistogramDecorator* m_pHistogram; // Pointer to the histogram whose data is to be serialized
};
#endif // !defined(AFX_TASERIALIZEHISTOGRAM_H__C98CF226_94E1_4607_9670_655AF9E0EBDF__INCLUDED_)
|
5339394bbec8b66c7075c8faadc174d377c201af
|
daf28dc6c26d812e0d0e36294390a3d33ac0afae
|
/src/libraries/serial_test_lisai.hpp
|
85aafd23eaedbdaba0f67047b3afb54c26473ead
|
[] |
no_license
|
Ashes17b/NIST_tests
|
2dd8746cc367219305744f5aac2218a4d0d11700
|
dfe9281dfeea5fc19da1ffa35346e585aa050b6a
|
refs/heads/master
| 2020-05-25T17:01:18.487951
| 2019-06-08T17:12:54
| 2019-06-08T17:12:54
| 187,899,547
| 0
| 0
| null | 2019-06-08T16:55:57
| 2019-05-21T19:19:02
|
C++
|
UTF-8
|
C++
| false
| false
| 972
|
hpp
|
serial_test_lisai.hpp
|
#pragma once
#include "serial_test.hpp"
#include "cephes.h"
namespace serial_test {
using bytes = std::vector<uint8_t>;
class Serial_test_lisai : public Serial_test {
public:
Serial_test_lisai() = default;
Serial_test_lisai(const Serial_test_lisai &serial_test_lisai) = default;
Serial_test_lisai(Serial_test_lisai &&serial_test_lisai) = default;
Serial_test_lisai& operator=(const Serial_test_lisai &serial_test_lisai) = default;
Serial_test_lisai& operator=(Serial_test_lisai &&serial_test_lisai) = default;
~Serial_test_lisai() = default;
void read(std::string filename = "", int param_m = 2) override;
std::pair<double, double> run_test(int param_m = 2) const override;
private:
double psi2(bytes epsilon, int m, int n) const;
std::size_t get_size_file(std::string filename) const;
bytes _buffer;
};
} //namespace serial_test
|
52576a0a1d9f1cd2915135fb2a158727fd8e4489
|
1c657691b0a0a7c871fb51ba1ed676aa7c2ac7b1
|
/Allocator/Blod_test.cpp
|
20d8e97474f3d146aa373b5fe65c6b07b17a06b4
|
[] |
no_license
|
chenyu1927/hello-world
|
d15fa125b08ec4c49219a8a91284c195f1302730
|
382556c394b4748836136d6bcbb7fa0c99229157
|
refs/heads/master
| 2021-03-19T11:22:58.154780
| 2016-09-28T07:36:40
| 2016-09-28T07:36:40
| 27,222,531
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 409
|
cpp
|
Blod_test.cpp
|
#include <iostream>
#include "Blod.hpp"
using std::cout;
using std::endl;
int main(void)
{
Blod<int> i = {4, 6, 7, 8, 9};
cout << "size=" << i.size() << endl;
try
{
cout << i[5] << endl;
}
catch (std::out_of_range& e)
{
cout << e.what() << endl;
}
std::vector<int> vec(5, 6);
Blod<int> v(vec.begin(), vec.end());
cout << "v.size=" <<v.size() << endl;
// cout << i[3] << endl;
return 0;
}
|
444a32a70ea29b331b360c6a38648c2544c57044
|
4296ad62fc2d1c0111af5e9c9ef5b8336256674e
|
/src/dwango_2015_prelims3/c.cpp
|
05420310705ed45a4021e2b2aa1cbaf16b18a90a
|
[] |
no_license
|
emakryo/cmpro
|
8aa50db1d84fb85e515546f37e675121be9de5c2
|
81db478cc7da06a9b99a7888e39952ddb82cdbe5
|
refs/heads/master
| 2023-02-09T12:36:47.893287
| 2023-01-23T12:07:03
| 2023-01-23T12:07:03
| 79,899,196
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,490
|
cpp
|
c.cpp
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
template<typename T>
ostream& operator<<(ostream &os, vector<T> &v){
string sep = " ";
if(v.size()) os << v[0];
for(int i=1; i<v.size(); i++) os << sep << v[i];
return os;
}
#ifdef DBG
void debug_(){ cout << endl; }
template<typename T, typename... Args>
void debug_(T&& x, Args&&... xs){
cout << x << " "; debug_(forward<Args>(xs)...);
}
#define dbg(...) debug_(__VA_ARGS__);
#else
#define dbg(...)
#endif
int main() {
ios_base::sync_with_stdio(false);
cout << setprecision(20) << fixed;
int n; cin >> n;
vector<double> ans(n+1);
vector<vector<double>> comb(105, vector<double>(105));
comb[0][0]=1;
comb[1][0]=1;
comb[1][1]=1;
for(int i=0; i<105; i++){
comb[i][0] = 1;
comb[i][i] = 1;
}
for(int i=2; i<105; i++){
for(int j=1; j<i; j++){
comb[i][j] = comb[i-1][j] + comb[i-1][j-1];
}
}
vector<double> pow3(105);
pow3[0] = 1;
for(int i=1; i<105; i++) pow3[i] = pow3[i-1]*3;
for(int i=2; i<=n; i++){
double a = 0;
double b = 0;
for(int p=0; p<=i; p++){
for(int q=0; p+q<=i; q++){
int r = i-p-q;
double m = comb[i][p]*comb[i-p][q];
if(p==q&&q==r){
a += m;
} else if(p==q&&q==0||q==r&&r==0||r==p&&p==0){
a += m;
} else {
vector<int> s{p, q, r};
sort(s.begin(), s.end());
if(s[0]==0) b += m*ans[s[1]];
else b += m*ans[s[0]];
}
}
}
ans[i] = pow3[i]/(pow3[i]-a)*(1+b/pow3[i]);
}
cout << ans[n] << endl;
return 0;
}
|
e8bb15f8a6cb57114dfe97c178641c7a7223b3fa
|
7c8f7ee315e10a719a39d90dd6b8b39978820049
|
/globals.hpp
|
99ceed9f18ccf136ed24645594b53d9d1e8bb58e
|
[] |
no_license
|
wldarden/Auto
|
9e7087f8696645b7899240bfa16e05aa8e6d39cf
|
7dc34384bcd706f504059f6459abdf43cc8efde5
|
refs/heads/master
| 2020-05-21T10:12:25.540425
| 2016-11-22T19:36:03
| 2016-11-22T19:36:03
| 70,082,593
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 245
|
hpp
|
globals.hpp
|
//
// globals.hpp
//
//
// Created by Will Darden on 10/3/16.
//
//
#ifndef globals_hpp
#define globals_hpp
enum Menu { MAIN, CREATE, REPORT, SAVE, LOAD };
enum Part_type { ARM, BATTERY, HEAD, LOCOMOTOR, TORSO };
#endif /* globals_hpp */
|
2e7f26d573751ea6425c278688570268b9eab56f
|
1dbf007249acad6038d2aaa1751cbde7e7842c53
|
/dds/include/huaweicloud/dds/v3/model/AddReadonlyNodeRequestBody.h
|
36a6b320320183745a3b3c1e1885f8aeacae6d4f
|
[] |
permissive
|
huaweicloud/huaweicloud-sdk-cpp-v3
|
24fc8d93c922598376bdb7d009e12378dff5dd20
|
71674f4afbb0cd5950f880ec516cfabcde71afe4
|
refs/heads/master
| 2023-08-04T19:37:47.187698
| 2023-08-03T08:25:43
| 2023-08-03T08:25:43
| 324,328,641
| 11
| 10
|
Apache-2.0
| 2021-06-24T07:25:26
| 2020-12-25T09:11:43
|
C++
|
UTF-8
|
C++
| false
| false
| 2,511
|
h
|
AddReadonlyNodeRequestBody.h
|
#ifndef HUAWEICLOUD_SDK_DDS_V3_MODEL_AddReadonlyNodeRequestBody_H_
#define HUAWEICLOUD_SDK_DDS_V3_MODEL_AddReadonlyNodeRequestBody_H_
#include <huaweicloud/dds/v3/DdsExport.h>
#include <huaweicloud/core/utils/ModelBase.h>
#include <huaweicloud/core/http/HttpResponse.h>
#include <string>
namespace HuaweiCloud {
namespace Sdk {
namespace Dds {
namespace V3 {
namespace Model {
using namespace HuaweiCloud::Sdk::Core::Utils;
using namespace HuaweiCloud::Sdk::Core::Http;
/// <summary>
///
/// </summary>
class HUAWEICLOUD_DDS_V3_EXPORT AddReadonlyNodeRequestBody
: public ModelBase
{
public:
AddReadonlyNodeRequestBody();
virtual ~AddReadonlyNodeRequestBody();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
bool fromJson(const web::json::value& json) override;
/////////////////////////////////////////////
/// AddReadonlyNodeRequestBody members
/// <summary>
/// 资源规格编码。获取方法请参见[查询数据库规格](x-wc://file=zh-cn_topic_0000001321087266.xml)中参数“spec_code”的值。 示例:dds.mongodb.c6.xlarge.2.shard
/// </summary>
std::string getSpecCode() const;
bool specCodeIsSet() const;
void unsetspecCode();
void setSpecCode(const std::string& value);
/// <summary>
/// 待新增只读节点个数。 取值范围:1-5。
/// </summary>
int32_t getNum() const;
bool numIsSet() const;
void unsetnum();
void setNum(int32_t value);
/// <summary>
/// 同步延迟时间。取值范围:0~1200毫秒。默认取值为0。
/// </summary>
int32_t getDelay() const;
bool delayIsSet() const;
void unsetdelay();
void setDelay(int32_t value);
/// <summary>
/// 扩容包年包月实例的存储容量时可指定,表示是否自动从账户中支付,此字段不影响自动续订的支付方式。 - true,表示自动从账户中支付。 - false,表示手动从账户中支付,默认为该方式。
/// </summary>
bool isIsAutoPay() const;
bool isAutoPayIsSet() const;
void unsetisAutoPay();
void setIsAutoPay(bool value);
protected:
std::string specCode_;
bool specCodeIsSet_;
int32_t num_;
bool numIsSet_;
int32_t delay_;
bool delayIsSet_;
bool isAutoPay_;
bool isAutoPayIsSet_;
};
}
}
}
}
}
#endif // HUAWEICLOUD_SDK_DDS_V3_MODEL_AddReadonlyNodeRequestBody_H_
|
97ec5ae06e91273a1c5af3794362277315be6db5
|
e9959db2910d129964a4c445acf03c3a029a3839
|
/geakit/src/api/grepositoryapi.h
|
6b23f85f6bc01240075baf4b148f68623e29cd9a
|
[] |
no_license
|
ypvk/geakit
|
f5f6abc027d3e4cb99eaf8630d6900db2ad11ec5
|
664d78d1839f1b1d1a51a2f92d6d547bf8444701
|
HEAD
| 2016-09-05T14:15:59.239285
| 2012-09-28T08:06:00
| 2012-09-28T08:06:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 963
|
h
|
grepositoryapi.h
|
#ifndef GREPOSITORYAPI_H
#define GREPOSITORYAPI_H
#include <QObject>
#include <QHash>
#include <parser.h>
#include <serializer.h>
class QNetworkAccessManager;
class QNetworkReply;
class QTimer;
class GRepositoryAPI : public QObject
{
Q_OBJECT
public:
typedef enum {SUCCESSFUL, ERROR, TIMEOUT} ResultCode;
public:
explicit GRepositoryAPI(QNetworkAccessManager* manager = 0);
~GRepositoryAPI();
void startConnect();
void setUsername(const QString& username);
int getReposNum() const;
QHash<QString, QString> getRepos() const;
private slots:
void parseFinished(QNetworkReply* reply);
void onTimeout();
signals:
void complete(GRepositoryAPI::ResultCode result);
private:
QNetworkAccessManager* m_manager;
QJson::Parser* m_parser;
QJson::Serializer* m_serializer;
QTimer* m_timeout;
QString m_username;
int m_reposNum;
QHash<QString, QString> m_repos;
};
#endif/*GREPOSITORY_H*/
|
7b24ca0f496fabd0de769e26203d5612fdeac5b3
|
3d02679788bdcde3ad2ecfea7bb2f66e37c1e270
|
/space Shooter/space Shooter/Player.cpp
|
cb58bb8205b89c91aca33d505fa8371d1077231d
|
[] |
no_license
|
prabhs226c/space-shooter
|
f31fc21e60666fb2917cdfbb9096daecde95b3a5
|
8c8dd3a2866efb32e47f01b441aef19c3d4ebaa5
|
refs/heads/master
| 2020-07-23T17:41:00.676449
| 2019-09-10T20:02:32
| 2019-09-10T20:02:32
| 207,651,669
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 737
|
cpp
|
Player.cpp
|
#include "Player.h"
Player::Player(int _score) :Ship(10, 3, "A",100, 100) {
int score = _score;
}
void Player::detectInput() {
int step = 1;
char key = ' ';
getInput(&key);
//x = UIKit::whereX();
//y = UIKit::whereY();
if (key == 'D' || key == 'd') { // move right
if (xPos < 210) {
move(1, 0);
}
}
if (key == 'A' || key == 'a') { // move left
if (xPos > 1) {
move(-1, 0);
}
}
/* else if (key == ' ') { // shoot
//new Bullet();
UIKit::gotoXY(x, ++y);
cout << "*";
}*/
}
bool Player::getInput(char* c)
{
if (_kbhit())
{
*c = _getch();
return true; // Key Was Hit
}
return false; // No keys were pressed
}
|
6d6416f4d120adbdbd63fe50931bd9d6d8b4c685
|
082b362705c6c23f5f29dacdff7aa8bc397b6e37
|
/GeoTempCore/Source/GeoTempLoaders/Public/OSM/IParserOsm.h
|
b23a8434a0c472565612f9c4a565a77e3971a83c
|
[
"MIT"
] |
permissive
|
interactivevislab/GeoTempPlugins
|
eeabb2728bedee96bd54fbfa75535e4fe1578794
|
5c650769cbdb22931fc0e221bd7a3233a56c202a
|
refs/heads/master
| 2021-04-20T10:55:33.651759
| 2020-05-20T22:20:55
| 2020-05-20T22:20:55
| 249,676,605
| 9
| 0
|
MIT
| 2020-05-28T11:27:13
| 2020-03-24T10:21:23
|
C++
|
UTF-8
|
C++
| false
| false
| 533
|
h
|
IParserOsm.h
|
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "OsmReader.h"
#include "IParserOsm.generated.h"
UINTERFACE(BlueprintType)
class GEOTEMPLOADERS_API UParserOsm : public UInterface
{
GENERATED_BODY()
};
/**
* \class IParserOsm
* \brief Interface for parsing OSM data.
*
* @see UOsmReader
*/
class GEOTEMPLOADERS_API IParserOsm
{
GENERATED_BODY()
public:
/** Sets UOsmReader as data source. */
UFUNCTION(BlueprintCallable, BlueprintNativeEvent)
void SetOsmReader(UOsmReader* inOsmReader);
};
|
c4a63afe46fd2ba4708a92c6b3e0e72e1f79fcc6
|
5fd2cc9da56f8645651f8a264aad0dc771998283
|
/DroneSphere/Weather.h
|
0a5d5ed1d128ae4ec40524108c0c1b03a81e51e4
|
[
"MIT"
] |
permissive
|
wamsai1096/DroneSphere
|
5e388634be0a0c30adbf36d41c589681de598dad
|
f9c285424771b26f2f4a8b655d3c2904f80f8d7c
|
refs/heads/master
| 2021-06-18T16:28:26.797833
| 2017-07-03T02:41:22
| 2017-07-03T02:41:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 483
|
h
|
Weather.h
|
#pragma once
#include <iostream>
#include <string>
#include "thing.h"
using namespace std;
void Weather_Test();
class WeatherOperation
{
public:
virtual string GetName() = 0;
virtual void SetAlias(string alias) = 0;
virtual string GetAlias() = 0;
};
class Weather : public Thing, public WeatherOperation
{
public:
Weather();
virtual ~Weather();
virtual string GetName() override;
virtual void SetAlias(string alias) override;
virtual string GetAlias() override;
};
|
340585b87d571f748393e8c7508137eeded5caf9
|
f73eca356aba8cbc5c0cbe7527c977f0e7d6a116
|
/Glop/glop3d/Camera.h
|
efd0e665b1f9dad6c8722995944deda31f15d158
|
[
"BSD-3-Clause"
] |
permissive
|
zorbathut/glop
|
40737587e880e557f1f69c3406094631e35e6bb5
|
762d4f1e070ce9c7180a161b521b05c45bde4a63
|
refs/heads/master
| 2016-08-06T22:58:18.240425
| 2011-10-20T04:22:20
| 2011-10-20T04:22:20
| 710,818
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,563
|
h
|
Camera.h
|
// The most basic tools for rendering in 3d.
//
// Camera - A viewpoint combined with field of view and near+far planes.
// CameraFrame - A GlopFrame that executes the virtual function Render3d after setting up the
// view matrices for rendering a 3d scene.
#ifndef GLOP_GLOP3D_CAMERA_H__
#define GLOP_GLOP3D_CAMERA_H__
#ifndef GLOP_LEAN_AND_MEAN
// Includes
#include "Point3.h"
#include "../Color.h"
#include "../GlopFrameBase.h"
// Class declarations
class GlopWindow;
// Camera class definition
class Camera: public Viewpoint {
public:
// Constructors - field_of_view is the vertical angle spanned by the top and bottom planes seen.
Camera(const Viewpoint &view_point = Viewpoint())
: Viewpoint(view_point),
near_plane_(0.1f),
far_plane_(150.0f),
field_of_view_(60.0f) {}
const Camera &operator=(const Camera &rhs) {
Viewpoint::operator=(rhs);
near_plane_ = rhs.near_plane_;
far_plane_ = rhs.far_plane_;
field_of_view_ = rhs.field_of_view_;
return rhs;
}
Camera(const Camera &rhs) {
operator=(rhs);
}
// Accessors/mutators. Field of view is in degrees.
float GetFieldOfView() const {return field_of_view_;}
void SetFieldOfView(float degrees) {field_of_view_ = degrees;}
float GetNearPlane() const {return near_plane_;}
void SetNearPlane(float dist) {near_plane_ = dist;}
float GetFarPlane() const {return far_plane_;}
void SetFarPlane(float dist) {far_plane_ = dist;}
// Moves and rotates the camera so it is looking directly at the plane spanned by the given
// points, and such that the top and bottom are the topmost and bottommost points visible on
// the plane. The left and right bounds are used to center the camera, but we cannot guarantee
// they will be the exact leftmost and rightmost bounds until we know the aspect ratio to render
// in. The top and left edges should be perpendicular.
void LookAt(const Point3 &top_left, const Point3 &top_right, const Point3 &bottom_left);
private:
float near_plane_, far_plane_, field_of_view_;
};
// CameraFrame class definition
class CameraFrame: public GlopFrame {
public:
CameraFrame(const Camera &camera = Camera())
: aspect_ratio_(-1), camera_(camera), is_fog_enabled_(false) {}
// Switches between 3d coordinates and screen coordinates.
void Project(const Point3 &val, int *x, int *y) const;
Point3 Unproject(int x, int y, float depth) const;
// This function can be used to ensure the CameraFrame maintains an aspect ratio (width / height)
// as given. LookAt uses this to ensure the CameraFrame views precisely the given rectangle
// without distortion.
void FixAspectRatio(float aspect_ratio) {
aspect_ratio_ = aspect_ratio;
DirtySize();
}
void LookAt(const Point3 &top_left, const Point3 &top_right, const Point3 &bottom_left,
float field_of_view);
void LookAt(const Point3 &top_left, const Point3 &top_right, const Point3 &bottom_left);
// Rendering. Render3d should be overloaded, NOT render.
void Render() const;
// Camera control
const Camera &GetCamera() const {return camera_;}
void SetCamera(const Camera &camera) {
camera_ = camera;
UpdateNormals();
}
// Fog control
bool IsFogEnabled() const {return is_fog_enabled_;}
const Color &GetFogColor() const {return fog_color_;}
float GetFogStartDistance() const {return fog_start_;}
float GetFogEndDistance() const {return fog_end_;}
void SetFog(const Color &color, float start_distance, float end_distance) {
is_fog_enabled_ = true;
fog_color_ = color;
fog_start_ = start_distance;
fog_end_ = end_distance;
}
void ClearFog() {is_fog_enabled_ = false;}
// Frustum info
bool IsInFrustum(const Point3 ¢er, float radius) const;
const Vec3 &GetFrontNormal() const {return front_normal_;}
const Vec3 &GetBackNormal() const {return back_normal_;}
const Vec3 &GetLeftNormal() const {return left_normal_;}
const Vec3 &GetRightNormal() const {return right_normal_;}
const Vec3 &GetTopNormal() const {return top_normal_;}
const Vec3 &GetBottomNormal() const {return bottom_normal_;}
protected:
virtual void Render3d() const = 0;
void RecomputeSize(int rec_width, int rec_height);
private:
void UpdateNormals();
float aspect_ratio_;
Camera camera_;
bool is_fog_enabled_;
float fog_start_, fog_end_;
Color fog_color_;
Vec3 front_normal_, back_normal_, left_normal_, right_normal_, top_normal_, bottom_normal_;
DISALLOW_EVIL_CONSTRUCTORS(CameraFrame);
};
#endif // GLOP_LEAN_AND_MEAN
#endif // GLOP_GLOP3D_CAMERA_H__
|
817ad22e8962d51a30e8ce32b6fd680757e192a5
|
ac82758a30d9b440473209e35e40e3ccf364444f
|
/Übungsaufgaben/A08/Code/6_c.cpp
|
c18e7ce73491f917a178812596227c1a4645ffe1
|
[] |
no_license
|
PaulOxxx1/DSAL-Arbeitsverzeichnis
|
e2eacb68ec07e6a10f240b67aa595244eff52b77
|
72442f472f0505571e8fa1c65de27ed95bdf6f8c
|
refs/heads/master
| 2021-11-11T05:40:45.426744
| 2021-10-28T12:33:07
| 2021-10-28T12:33:07
| 129,533,636
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 157
|
cpp
|
6_c.cpp
|
void function(int n) {
a = 1;
b = 1;
for (int i=0;i<n;i++) {
a = a*3;
b = b*n;
}
k = a + b;
for (int i=0;i<k;i++) {
print();
}
}
|
43879c2570707d8b8c4ae647a40891cf1b40fd94
|
61d564820f8a0ee90aba330ceb26f11cca789004
|
/367ValidPerfectSquare/main.cpp
|
7dfae406df82e844931719f10dc8536b15df923a
|
[] |
no_license
|
xiaoniaoyou/leetcode
|
37bd48af36d29e1c8b01632bcf899b59245fcd11
|
56871a3eea53c85bfd892e87b268bf4535df3816
|
refs/heads/master
| 2020-04-29T03:58:12.807119
| 2019-03-26T09:26:11
| 2019-03-26T09:26:11
| 175,830,500
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 982
|
cpp
|
main.cpp
|
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
// bool isPerfectSquare(int num) {
// int left = 1;
// int right = num / 2 + 1;
// while (left <= right) {
// if (left * left == num || right * right == num) {
// return true;
// }
// ++ left;
// -- right;
// }
// return false;
// }
bool isPerfectSquare(int num) {
int left = 1;
int right = num / 2 + 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid * mid == num) {
return true;
} else if (mid * mid < num) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
Solution a;
cout << a.isPerfectSquare(2147483647) << endl;
return 0;
}
|
5d3a1e423ef92209f9c78cbc569b76b61f294dfc
|
eed8026f1f9d9f56c4d536b9403d1ff50567af8a
|
/JzOffer/栈的压入、弹出序列.cpp
|
3354329c17ca79b9b338c651477d8180b864505d
|
[] |
no_license
|
atmqq1990/JzOffer
|
f1ef36749e58f57b2e0159b3e9e697ce853bc0a0
|
ba240e91b44f9473364d97f28863700622c3af8e
|
refs/heads/master
| 2021-01-10T21:23:43.621669
| 2015-08-11T09:33:10
| 2015-08-11T09:33:10
| 40,455,544
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 755
|
cpp
|
栈的压入、弹出序列.cpp
|
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
class Solution {
public:
bool IsPopOrder(vector<int> pushV, vector<int> popV) {
stack<int> st;
int len = pushV.size();
if (len == 0)
return false;
int pushindex = 0;
int popindex = 0;
while (popindex < len)
{
while (st.empty() || pushindex<len && st.top()!=popV[popindex])
{
st.push(pushV[pushindex]);
pushindex++;
}
if (st.top() != popV[popindex])
return false;
st.pop();
popindex++;
}
return true;
}
};
/*
int main(int argc, char** args)
{
Solution so;
vector<int> pushV = {1,2,3,4,5};
vector<int> popV = {4,3,5,1,2};
bool res = so.IsPopOrder(pushV,popV);
cout << res << endl;
system("pause");
return 0;
}
*/
|
2a0e16386c02c12767814ae6cb991d1589e7f0dc
|
2f2b6d74fff26bbecb37be2df79cae6c2e0a4650
|
/PControl.h
|
38ff658a71fbae7efd274ee2b6bd0bc977ddee80
|
[] |
no_license
|
Svalburg/OpenVPN-FuzzTool
|
4f775f61e72e9a28706cda5002b110928f9793b3
|
233dac47c4a32f34605f03c42a47db7214fcf3dd
|
refs/heads/master
| 2020-03-19T00:51:51.054528
| 2018-05-30T23:09:57
| 2018-05-30T23:09:57
| 135,506,372
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,389
|
h
|
PControl.h
|
#ifndef PCONTROL_H
#define PCONTROL_H
#include <stdio.h>
using namespace std;
class PControl
{
public:
PControl(unsigned char packet[]);
void toPacket(unsigned char* buff);
int packetSize();
void setLength(unsigned short newLength);
unsigned short getLength();
void setOPcode(unsigned short newOPcode);
unsigned short getOPcode();
void setKeyID(unsigned short newKeyID);
unsigned short getKeyID();
void setLocalSessionID(unsigned long long newLocalSessionID);
unsigned long long getLocalSessionID();
void setRemoteSessionID(unsigned long long newRemoteSessionID);
unsigned long long getRemoteSessionID();
void setMessagePacketID(unsigned long newMessagePacketID);
unsigned long getMessagePacketID();
void setAckLength(unsigned short newAckLength);
unsigned short getAckLength();
void setAckIDs(unsigned char newIDs[], int length);
unsigned char* getAckIDs();
void setTLSPayload(unsigned char newPayload[], int length);
unsigned char* getTLSPayload();
private:
unsigned short length;
unsigned short opcode;
unsigned short keyID;
unsigned long long localSessionID;
unsigned short ackLength;
unsigned char ackIDs[20];
unsigned long long remoteSessionID;
unsigned long messagePacketID;
unsigned int tlsLength; //NOTE: this field is not included in the network packet
unsigned char tlsPayload[1200];
};
#endif //PCONTROL_H
|
443ee64d3e3dd015393dc927888ef4b975422c08
|
0ef2d152ff5d5ef919c4f918d595bd0b0139fdce
|
/src/loop011.cpp
|
f32f287bb635f9037f06d5e313db34d31b84728f
|
[
"MIT"
] |
permissive
|
TannerRogalsky/Demoloops
|
db576caade9d59c33a1caa449a9f511eb2ae9700
|
13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5
|
refs/heads/master
| 2021-01-11T01:02:11.887620
| 2018-03-18T19:11:58
| 2018-03-18T19:11:58
| 70,442,271
| 4
| 0
|
MIT
| 2018-03-18T15:38:48
| 2016-10-10T01:47:02
|
C++
|
UTF-8
|
C++
| false
| false
| 1,735
|
cpp
|
loop011.cpp
|
#include <numeric>
#include "demoloop.h"
#include "graphics/3d_primitives.h"
#include <glm/gtx/rotate_vector.hpp>
#include "hsl.h"
using namespace std;
using namespace demoloop;
static const uint16_t NUM_VERTS = 60;
const uint32_t CYCLE_LENGTH = 3;
static const float RADIUS = 0.3;
class Loop11 : public Demoloop {
public:
Loop11() : Demoloop(CYCLE_LENGTH, 150, 150, 150), mesh(icosahedron(0, 0, 0, RADIUS)) {
gl.getProjection() = glm::perspective((float)DEMOLOOP_M_PI / 4.0f, (float)width / (float)height, 0.1f, 100.0f);
iota(mesh.mIndices.begin(), mesh.mIndices.end(), 0);
}
void Update() {
const float cycle_ratio = getCycleRatio();
for (int i = 0; i < NUM_VERTS; ++i) {
const float t = i;
const float interval_cycle_ratio = fmod(t / NUM_VERTS + cycle_ratio, 1);
auto color = hsl2rgb(interval_cycle_ratio, 1, 0.5);
Vertex &v = mesh.mVertices[i];
v.r = color.r;
v.g = color.g;
v.b = color.b;
v.a = 255;
}
gl.pushTransform();
const float cameraX = 0;//sin(cycle_ratio * DEMOLOOP_M_PI * 2) * 3;
// const float cameraY = pow(sin(cycle_ratio * DEMOLOOP_M_PI * 2), 2);
const float cameraY = cos(cycle_ratio * DEMOLOOP_M_PI * 2) * 3;
const float cameraZ = 3;//cos(cycle_ratio * DEMOLOOP_M_PI * 2) * 3;
gl.getTransform() = glm::lookAt(glm::vec3(cameraX, cameraY, cameraZ), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
mesh.buffer();
mesh.draw();
glm::mat4 m;
m = glm::translate(m, {0, sinf(cycle_ratio * DEMOLOOP_M_PI * 2) * RADIUS * 4, 0});
m = glm::scale(m, {0.5, 0.5, 0.5});
mesh.draw(m);
gl.popTransform();
}
private:
Mesh mesh;
};
int main(int, char**){
Loop11 test;
test.Run();
return 0;
}
|
af97b527ca60baf63ae57913cdb09dda53dcf506
|
9e4a00de1ec07e7e88872ef60c42a49bf65dc2b0
|
/Code/Projects/Eld/src/SDPs/sdpeldhudcalibration.h
|
d89906537168fd1a8286f9af4f24614867d08a4d
|
[
"Zlib"
] |
permissive
|
ptitSeb/Eldritch
|
6a5201949b13f6cd95d3d75928e375bdf785ffca
|
3cd6831a4eebb11babec831e2fc59361411ad57f
|
refs/heads/master
| 2021-07-10T18:45:05.892756
| 2021-04-25T14:16:19
| 2021-04-25T14:16:19
| 39,091,718
| 6
| 4
|
NOASSERTION
| 2021-04-25T14:16:20
| 2015-07-14T18:03:07
|
C
|
UTF-8
|
C++
| false
| false
| 403
|
h
|
sdpeldhudcalibration.h
|
#ifndef SDPELDHUDCALIBRATION_H
#define SDPELDHUDCALIBRATION_H
#include "SDPs/sdpeldhud.h"
class SDPEldHUDCalibration : public SDPEldHUD
{
public:
SDPEldHUDCalibration();
virtual ~SDPEldHUDCalibration();
DEFINE_SDP_FACTORY( EldHUDCalibration );
virtual void SetShaderParameters( IRenderer* const pRenderer, Mesh* const pMesh, const View& CurrentView ) const;
};
#endif // SDPELDHUDCALIBRATION_H
|
e94ed1eca0c4562f3583cfc56d21a9388424dda2
|
4b60702bd7494f3e818d80238449742696a440ae
|
/nbproject/classes/Market.h
|
4dd6517abe87278574adea0568fbe5f339736ecb
|
[] |
no_license
|
allada/BitcoinTradeEngine
|
ef06a38a575839bb31c44ae42d3aa28204c5acf3
|
fc735645ef2e4a0344d8149a5a22c7970e8a59aa
|
refs/heads/master
| 2021-01-13T01:46:09.598002
| 2014-06-21T21:46:25
| 2014-06-21T21:46:25
| 14,997,366
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 958
|
h
|
Market.h
|
/*
* File: Market.h
* Author: allada
*
* Created on December 6, 2013, 5:44 PM
*/
#ifndef MARKET_H
#define MARKET_H
#define ORDER_SORT_GROUP_COUNT 20
class Market;
#include <vector>
#include <iostream>
#include <string>
//#include "ClassList.h"
#include "Currency.h"
#include "Transaction.h"
#include "Order.h"
class Order;
class Market {
public:
static std::vector<Market *> markets;
u_int16_t market_id;
Currency *currency1;
Currency *currency2;
std::vector<Order *> buyOrders;
std::vector<Order *> sellOrders;
u_int64_t buyOrderGroups[ORDER_SORT_GROUP_COUNT];
u_int64_t sellOrderGroups[ORDER_SORT_GROUP_COUNT];
std::string getName() { return this->currency1->name + '_' + this->currency2->name; }
Market(u_int8_t market_id, Currency *currency1, Currency *currency2);
bool addOrder(Order *addOrder);
void removeOrder(Order *order);
static void addMarket(Market *market);
virtual ~Market();
private:
};
#endif /* MARKET_H */
|
33deb2984a6389521d401fe53eaf5d407f0e796c
|
8b0f051f8a3f01a9a0346cd25c509bd3dbf5c44d
|
/SGui/Color.h
|
394aacede2617f6bff92dedae7e474620ea1b0af
|
[] |
no_license
|
southor/torso-gui
|
feddcc599d85a5c012b6bb5e390a5c4102ad8c27
|
7cbce9266fbc81a30a2e3c14607a0066e6d79940
|
refs/heads/master
| 2021-06-06T06:38:20.678921
| 2020-04-26T20:14:52
| 2020-04-26T20:14:52
| 34,624,748
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,289
|
h
|
Color.h
|
#ifndef _STATE_GUI_COLOR_H_
#define _STATE_GUI_COLOR_H_
#include "functions.h"
namespace SGui
{
template <typename T> struct Color3
{
typedef T value_type;
T r, g, b;
Color3();
Color3(const T& bw);
Color3(const T& r, const T& g, const T& b);
Color3(const char *str);
explicit Color3(const T* p);
operator T* ();
operator const T* () const;
Color3<T>& operator=(const Color3<T>& rhs);
Color3<T>& operator+=(const Color3<T>& c);
Color3<T>& operator-=(const Color3<T>& c);
Color3<T>& operator*=(const T& s);
Color3<T>& operator/=(const T& s);
};
template <typename T> struct Color4
{
typedef T value_type;
T r, g, b, a;
Color4();
Color4(const T& bw, const T& a);
Color4(const T& r, const T& g, const T& b, const T& a);
Color4(const char *str);
explicit Color4(const T* p);
operator T* ();
operator const T* () const;
Color4<T>& operator=(const Color4<T>& rhs);
Color4<T>& operator+=(const Color4<T>& c);
Color4<T>& operator-=(const Color4<T>& c);
Color4<T>& operator*=(const T& s);
Color4<T>& operator/=(const T& s);
};
//
//
// Color3
//
//
template <typename T>
Color3<T>::Color3()
{
}
template <typename T>
Color3<T>::Color3(const T& r, const T& g, const T& b)
: r(r), g(g), b(b)
{
}
template <typename T>
Color3<T>::Color3(const T& bw)
: r(bw), g(bw), b(bw)
{
}
template <typename T>
Color3<T>::Color3(const T* p)
: r(p[0]), g(p[1]), b(p[2])
{
}
template <typename T>
Color3<T>::Color3(const char *str)
{
r = readHexByte(str+0);
g = readHexByte(str+2);
b = readHexByte(str+4);
}
template <typename T>
Color3<T>::operator T* ()
{
return (T *) &r;
}
template <typename T>
Color3<T>::operator const T* () const
{
return (const T *) &r;
}
template <typename T>
Color3<T>& Color3<T>::operator =(const Color3<T>& rhs)
{
r = rhs.r;
g = rhs.g;
b = rhs.b;
return *this;
}
template <typename T>
Color3<T>& Color3<T>::operator +=(const Color3<T>& c)
{
r += c.r;
g += c.g;
b += c.b;
return *this;
}
template <typename T>
Color3<T>& Color3<T>::operator -=(const Color3<T>& c)
{
r -= c.r;
g -= c.g;
b -= c.b;
return *this;
}
template <typename T>
Color3<T>& Color3<T>::operator *=(const T& s)
{
r *= s;
g *= s;
b *= s;
return *this;
}
template <typename T>
Color3<T>& Color3<T>::operator /=(const T& s)
{
return *this *= (1/s);
}
//
//
// Color4
//
//
template <typename T>
Color4<T>::Color4()
{
}
template <typename T>
Color4<T>::Color4(const T& r, const T& g, const T& b, const T& a)
: r(r), g(g), b(b), a(a)
{
}
template <typename T>
Color4<T>::Color4(const T& bw, const T& a)
: r(bw), g(bw), b(bw), a(a)
{
}
template <typename T>
Color4<T>::Color4(const T* p)
: r(p[0]), g(p[1]), b(p[2]), a(p[3])
{
}
template <typename T>
Color4<T>::Color4(const char *str)
{
r = readHexByte(str+0);
g = readHexByte(str+2);
b = readHexByte(str+4);
a = readHexByte(str+6);
}
//template <typename T>
//Color4<T>::Color4(const Color3<T>& color3)
// : r(color3.r), g(color3.r), b(color3.r), a(FULL_VALUE)
//{
//}
template <typename T>
Color4<T>::operator T* ()
{
return (T *) &r;
}
template <typename T>
Color4<T>::operator const T* () const
{
return (const T *) &r;
}
template <typename T>
Color4<T>& Color4<T>::operator =(const Color4<T>& rhs)
{
r = rhs.r;
g = rhs.g;
b = rhs.b;
a = rhs.a;
return *this;
}
template <typename T>
Color4<T>& Color4<T>::operator +=(const Color4<T>& c)
{
r += c.r;
g += c.g;
b += c.b;
a += c.a;
return *this;
}
template <typename T>
Color4<T>& Color4<T>::operator -=(const Color4<T>& c)
{
r -= c.r;
g -= c.g;
b -= c.b;
a -= c.a;
return *this;
}
template <typename T>
Color4<T>& Color4<T>::operator *=(const T& s)
{
r *= s;
g *= s;
b *= s;
a *= s;
return *this;
}
template <typename T>
Color4<T>& Color4<T>::operator /=(const T& s)
{
return *this *= (1/s);
}
};
#endif
|
6beed9c52e4427b12cfbb4844ce057859cdb7b4e
|
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
|
/cpp/C/D/A/A/C/ACDAAC.h
|
5fee7d53f102a550d1fdbe5610a285248c1ca931
|
[] |
no_license
|
devsisters/2021-NDC-ICECREAM
|
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
|
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
|
refs/heads/master
| 2023-03-19T06:29:03.216461
| 2021-03-10T02:53:14
| 2021-03-10T02:53:14
| 341,872,233
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 67
|
h
|
ACDAAC.h
|
#ifndef ACDAAC_H
namespace ACDAAC {
std::string run();
}
#endif
|
3a33d334689ac5ba8e3955410d604f0cacd9ad0d
|
81262b0a5975e4e63d431cfdf9946f8a6e12475a
|
/CodeFiles/CodeBank/TreeQuesAma.cpp
|
bdfa453ac661fafcb611dde6e48ed658f5f80700
|
[] |
no_license
|
IsCoelacanth/CodeBase
|
90c9f129e45ea9e9450ac145a57176b2919f918d
|
b57baf87f0c2c02006b5b2d3d62dec8b8a007483
|
refs/heads/master
| 2021-01-18T13:16:36.240464
| 2017-09-13T14:48:21
| 2017-09-13T14:48:21
| 100,374,361
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,595
|
cpp
|
TreeQuesAma.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef vector<ll> vll;
typedef vector<int> vint;
typedef vector<vector<int> > vvint;
typedef vector<vector<ll> > vvll;
typedef pair<int,int> pint;
typedef map<int,int> mint;
#define MOD 1000000007
struct Node
{
int val;
Node *left, *right;
};
Node *new_node(int x)
{
Node *nnode = new Node();
nnode->val = x;
nnode->left = NULL;
nnode->right = NULL;
return nnode;
}
Node *insert(Node *troot, int x)
{
if(troot == NULL)
troot = new_node(x);
else if(x <= troot->val)
troot->left = insert(troot->left,x);
else if(x > troot->val)
troot->right = insert(troot->right,x);
return troot;
}
Node* findMinAdd(Node *troot)
{
if(troot -> left == NULL)
{
return troot;
}
return findMinAdd(troot->left);
}
Node *Delete(Node *troot, int x)
{
if(troot == NULL)
return troot;
else if(x< troot->val)
troot->left = Delete(troot->left,x);
else if(x> troot->val)
troot->right = Delete(troot->right,x);
else
{
if(troot->left == NULL && troot->right == NULL)
{
delete troot;
troot = NULL;
}
else if(troot->left == NULL)
{
Node *temp = troot;
troot = troot->right;
delete temp;
}
else if(troot->right == NULL)
{
Node *temp = troot;
troot = troot->left;
delete temp;
}
else
{
Node *temp = findMinAdd(troot->right);
troot->val = temp->val;
troot->right = Delete(troot->right,temp->val);
}
}
return troot;
}
void Print_Pre_Order(Node *root)
{
if (root == NULL)
{
return;
}
cout<<root -> val <<" ";
Print_Pre_Order(root -> left);
Print_Pre_Order(root -> right);
}
void Print_In_Order(Node *root)
{
if (root == NULL)
{
return;
}
Print_In_Order(root -> left);
cout<<root -> val <<" ";
Print_In_Order(root -> right);
}
void Print_Post_Order(Node *root)
{
if (root == NULL)
return;
Print_Post_Order(root -> left);
Print_Post_Order(root -> right);
cout<<root -> val <<" ";
}
int height(Node *troot)
{
if(troot == NULL)
return -1;
return max(height(troot->left),height(troot->right)) + 1;
}
Node *make_tree(Node *root, vll vec, int l, int r)
{
if(l>r)
return NULL;
int mid = l + (r-l)/2;
root = insert(root, vec[mid]);
make_tree(root,vec,l,mid-1);
make_tree(root,vec,mid+1,r);
return root;
}
bool checkBalance(Node *root)
{
return (abs(height(root->left)-height(root->right)) < 2 );
}
Node *LCA(Node *root, int n1, int n2)
{
if(root == NULL)
return NULL;
if(root->val == n1 || root->val == n2)
return root;
Node *l = LCA(root->left,n1,n2);
Node *r = LCA(root->right,n1,n2);
if(l != NULL && r != NULL)
return root;
return l != NULL ? l:r;
}
void printSpiralIter(Node *root)
{
if(root == NULL)
return;
stack<Node *> s1;
stack<Node *> s2;
s1.push(root);
while(!s1.empty() || !s2.empty())
{
while(!s1.empty())
{
Node *temp = s1.top();
s1.pop();
cout<<temp->val<<' ';
if(temp->left)
s2.push(temp->left);
if(temp->right)
s2.push(temp->right);
}
while(!s2.empty())
{
Node *temp = s2.top();
s2.pop();
cout<<temp->val<<' ';
if(temp->left)
s1.push(temp->left);
if(temp->right)
s1.push(temp->right);
}
}
}
int diameter(Node *troot, int *Height)
{
int lh = 0, rh = 0;
if(troot == NULL)
{
*Height = 0;
return 0;
}
int ldia = diameter(troot->left, &lh);
int rdia = diameter(troot->right, &rh);
*Height = max(lh,rh)+1;
return max((lh+rh+1), max(ldia,rdia));
}
int minHeight(Node *troot)
{
if(troot == NULL)
return -1;
return min(height(troot->left),height(troot->right)) + 1;
}
int search(vint arr, int strt, int en, int value)
{
int i;
for (i = strt; i <= en; i++)
{
if (arr[i] == value)
break;
}
return i;
}
Node* build(vint in, vint post, int inStrt, int inEnd, int *pIndex)
{
if (inStrt > inEnd)
return NULL;
Node *node = new_node(post[*pIndex]);
(*pIndex)--;
if (inStrt == inEnd)
return node;
int iIndex = search(in, inStrt, inEnd, node->val);
node->right= build(in, post, iIndex+1, inEnd, pIndex);
node->left = build(in, post, inStrt, iIndex-1, pIndex);
return node;
}
Node *buildTree(vint in,vint post,int K)
{
int pin = K-1;
build(in,post,0,K-1,&pin);
}
int main()
{
Node *root = NULL;
vint in;
vint post;
int N;
cin>>N;
for (int i = 0; i < N; ++i)
{
int tmp;
cin>>tmp;
in.push_back(tmp);
}
for (int i = 0; i < N; ++i)
{
int tmp;
cin>>tmp;
post.push_back(tmp);
}
root = buildTree(in,post,N);
Print_In_Order(root);
}
|
fe8b87418177aba536c9a5dc2c5da83e07d65512
|
967cca660f2aa06f1cefff8f5696435a228d18ce
|
/NetworkInterface.cpp
|
16136dcc208c37d0a9bba2d480863bec6efd1707
|
[] |
no_license
|
smjiang/server
|
2b3e3f71c8c0ceccc8a9d0cfb093fa3e8a252c94
|
bdee5cf03d9ed63f5f342bdfe565de4f3e6c242b
|
refs/heads/master
| 2021-01-01T15:31:29.823350
| 2015-09-18T06:01:08
| 2015-09-18T06:01:08
| 38,676,972
| 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 34,696
|
cpp
|
NetworkInterface.cpp
|
#include <unistd.h>
#include <errno.h>
#include "NetworkInterface.h"
#include "IniFileParser.h"
#include "Log.h"
#include "Tools.h"
#include "Json/json.h"
#include "PeerGroup.h"
#define MAXEVENT 100000
CNetworkInterface* CNetworkInterface::m_instance = NULL;
CNetworkInterface::CNetworkInterface()
{
}
CNetworkInterface::~CNetworkInterface()
{
}
CNetworkInterface* CNetworkInterface::Instance()
{
if(NULL == m_instance)
{
m_instance = new CNetworkInterface();
}
return m_instance;
}
void CNetworkInterface::FreeInstance()
{
if(m_instance)
{
delete m_instance;
m_instance = NULL;
}
}
int CNetworkInterface::Init()
{
m_status = true;
m_tcplistenport = 8088;
m_threadNum = 1;
m_httpClientSock = -1;
m_httpServerSock = -1;
unsigned int localip = GetLocalIP();
char strip[16] = {0};
IpInt2Str(localip,strip);
CLog::getInstance()->info("Local IP %s",strip);
CIniFileParser iniParser;
int result = iniParser.init("server.ini");
if(-1 == result)
{
CLog::getInstance()->error("can't open config file,use default parameters");
}
else
{
m_tcplistenport = iniParser.get_int("SERVER:tcplistenport",8087);
CLog::getInstance()->info("read listen port %d",m_tcplistenport);
m_threadNum = iniParser.get_int("SERVER:threadnum",1);
CLog::getInstance()->info("read thread number %d",m_threadNum);
if(m_threadNum == 0)
m_threadNum = 1;
}
m_epfd = epoll_create(100000);
if(-1 == m_epfd)
{
return -1;
}
m_tcplistensock = CreateTCPSocket();
int reuseaddr = 1;
int res = setsockopt(m_tcplistensock, SOL_SOCKET, SO_REUSEADDR, (char*)&reuseaddr, sizeof(reuseaddr));
if(res != 0)
{
return -1;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(m_tcplistenport);
addr.sin_addr.s_addr = INADDR_ANY;
if(0 != bind(m_tcplistensock,(sockaddr*)&addr,sizeof(addr)))
{
CLog::getInstance()->error("bind port %d fail: %s",m_tcplistenport,strerror(errno));
return -1;
}
if(listen(m_tcplistensock,4096) != 0)
{
return -1;
}
CLog::getInstance()->info("listen on port %d",m_tcplistenport);
CLog::getInstance()->info("thread number %d",m_threadNum);
if(pthread_create(&m_threadid,NULL,AcceptThread,this) != 0)
{
return -1;
}
m_threads = new THREAD[m_threadNum];
if(NULL == m_threads)
{
return -1;
}
for(int i=0; i < m_threadNum; i++)
{
int fds[2];
if(pipe(fds))
{
return -1;
}
m_threads[i].rfd = fds[0];
m_threads[i].sfd = fds[1];
m_threads[i].idx = i;
m_threads[i].epfd = m_epfd;
m_threads[i].serv = this;
pthread_create(&m_threads[i].pid,NULL,ProcessThread,m_threads+i);
usleep(200);
}
if(pthread_create(&m_threadMsg,NULL,SendMsg2WXThread,this) != 0)
{
return -1;
}
return 0;
}
void CNetworkInterface::DispatchNewConn(int sock,int idx)
{
THREAD* thd = m_threads + idx;
thd->newconn.push(sock);
write(thd->sfd,"",1);
}
void CNetworkInterface::DoAccept()
{
while(true)
{
sockaddr_in addr;
socklen_t len = sizeof(addr);
int ns = accept(m_tcplistensock, (sockaddr*)&addr, &len);
if(-1 == ns)
{
if(EMFILE == errno || errno == EINTR)//EMFILE:too many open files
{
CLog::getInstance()->error("accept sock fail %d: %s",errno, strerror(errno));
}
//CLog::getInstance()->error("2accept sock fail %d: %s",errno, strerror(errno));
return;
}
SetNonblocking(ns);
int optint = 1;
setsockopt(ns, SOL_SOCKET, SO_KEEPALIVE, (char *)&optint, sizeof(optint));
setsockopt(ns, IPPROTO_TCP, TCP_NODELAY, (char *)&optint, sizeof(optint));
struct epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = ns;
if(epoll_ctl(m_epfd,EPOLL_CTL_ADD,ns,&ev) != 0)
{
CLog::getInstance()->error("epoll_ctl add sock fail %d: %s",errno, strerror(errno));
close(ns);
return;
}
CLog::getInstance()->info("accept a sock %d",ns);
m_sockLock.Lock();
SOCKINFO info;
info.datapos = 0;
info.recvbuf[0] = '\0';
info.ip = addr.sin_addr.s_addr;
info.port = addr.sin_port;
info.updatetime = time(NULL);
info.deviceID = "";
map<int,SOCKINFO>::iterator itr = m_sockMap.find(ns);
if(m_sockMap.end() != itr)
{
CLog::getInstance()->error("sock %d already in map",ns);
m_sockMap.erase(itr);
}
m_sockMap.insert(make_pair(ns,info));
m_sockLock.Unlock();
}
}
void CNetworkInterface::DoRecv()
{
struct epoll_event events[MAXEVENT];
int fdnum = epoll_wait(m_epfd,events,MAXEVENT,10);
for(int i=0; i < fdnum; i++)
{
int cfd = events[i].data.fd;
if(cfd > 0)
{
int idx = cfd%m_threadNum;
CLog::getInstance()->info("dispatch thread %d",idx);
DispatchNewConn(cfd,idx);
}
}
}
void CNetworkInterface::DoProcess(int sock)
{
pthread_t pid = pthread_self();
SOCKINFO& info = m_sockMap[sock];
info.updatetime = time(NULL);
int ret = recv(sock,info.recvbuf+info.datapos, SOCK_RECVBUF_SIZE-info.datapos,0);
if(0 == ret)
{
CloseSock(sock);
return ;
}
else if (ret < 0)
{
struct epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = sock;
epoll_ctl(m_epfd,EPOLL_CTL_MOD,sock,&ev);
return ;
}
while(ret > 0)
{
info.datapos += ret;
info.recvbuf[info.datapos] = '\0';
//CLog::getInstance()->info("pid %d sock %d recv %s",pid,sock,info.recvbuf);
ret = recv(sock,info.recvbuf+info.datapos, SOCK_RECVBUF_SIZE-info.datapos,0);
}
if(info.datapos < 4)
{
return;
}
const char* respFmt = "{\"errcode\":\"%d\",\"errmsg\":\"%s\",\"data\":[%s]}";
const char* sendfmt = "HTTP/1.1 200 OK\r\nContent-Type: text/json\r\nContent-Length: %d\r\nConnection: keep-alive\r\n\r\n%s";
char* buf = info.recvbuf;
MsgHead* head = (MsgHead*)buf;
if(0x0101 == htons(head->cmd))
{
unsigned int len = htons(head->len);
if(info.datapos < len+4)
{
CLog::getInstance()->info("pid %d sock %d recvfrom equipment,msg not finish:%d,recved %d",pid,sock,len,info.datapos);
return;
}
char respBuf[1024] = {0};
MsgHead* respHead = (MsgHead*)respBuf;
char* pResp = respBuf + 4;
respHead->cmd = htons(0x0101);
const char* respJson = "{\"cmd\":\"%s\",\"result\":\"%s\",\"code\":\"%d\"}";
unsigned short jsonLen = 0;
Json::Reader reader;
Json::Value value;
if(reader.parse(buf+4,value,false))
{
CLog::getInstance()->info("pid %d sock %d recv %s",pid,sock,buf+4);
Json::Value cmd = value.get("cmd","");
string strCmd = cmd.toStyledString_t();
Json::Value deviceID = value.get("device_id","");
string strDeviceID = deviceID.toStyledString_t();
if("login" == strCmd)
{
CLog::getInstance()->info("msg from equipment : %s,device id %s",strCmd.c_str(),strDeviceID.c_str());
info.deviceID = strDeviceID;
ChannelInfo cInfo;
cInfo.sock = sock;
cInfo.updatetime = time(NULL);
if(CPeerGroup::Instance()->IsChannelExist(strDeviceID))
{
CPeerGroup::Instance()->UpdateChannel(strDeviceID,cInfo);
snprintf(pResp,1000,respJson,strCmd.c_str(),"fail",1);
}
else
{
CPeerGroup::Instance()->AddChannel(strDeviceID,cInfo);
snprintf(pResp,1000,respJson,strCmd.c_str(),"ok",0);
}
jsonLen = strlen(pResp);
respHead->len = htons(jsonLen);
send(sock,respBuf,jsonLen+4,0);
CLog::getInstance()->info("send %s",respBuf+4);
}
else if("send_voice" == strCmd)
{
Json::Value voiceurl = value.get("voice_uri","");
string strVoiceUrl = voiceurl.toStyledString_t();
Json::Value valueContactID = value.get("contact_id","");
string strContactID = valueContactID.toStyledString_t();
vector<WXUserInfo> openIDs;
CLog::getInstance()->info("msg from equipment : %s,deviceID %s,contactID %s,voiceurl %s",strCmd.c_str(),strDeviceID.c_str(),strContactID.c_str(),strVoiceUrl.c_str());
ret = ProcessGetWXByDeviceID(strDeviceID.c_str(),openIDs);
if(0 == ret || openIDs.size() > 0)
{
vector<WXUserInfo>::iterator itr = openIDs.begin();
while(openIDs.end() != itr)
{
if((*itr).nickname == strContactID)
{
break;
}
itr++;
}
if(openIDs.end() != itr)
{
snprintf(pResp,1000,respJson,strCmd.c_str(),"ok",0);
IMMSG immsg;
immsg.openID = (*itr).openID;//"o0ojGwbrZZtuGknGZvMhrtbOOOos";//openID;
immsg.voiceUrl = strVoiceUrl;
m_msgQueLock.Lock();
m_msgQue.push(immsg);
m_msgQueLock.Unlock();
}
else
{
snprintf(pResp,1000,respJson,strCmd.c_str(),"fail",3);
}
}
else if(openIDs.size() == 0)
{
snprintf(pResp,1000,respJson,strCmd.c_str(),"fail",2);
}
else
{
snprintf(pResp,1000,respJson,strCmd.c_str(),"fail",1);
}
jsonLen = strlen(pResp);
respHead->len = htons(jsonLen);
int sendres = send(sock,respBuf,jsonLen+4,0);
CLog::getInstance()->info("send len %d: %s,%d",sendres,respBuf+4,errno);
}
else if("play_voice" == strCmd || "play_music" == strCmd)
{
CLog::getInstance()->info("msg from equipment response : %s",strCmd.c_str());
}
else if("play_status" == strCmd || "list_file" == strCmd)
{
CLog::getInstance()->info("msg from equipment : %s",strCmd.c_str());
if(m_httpServerSock > 0)
{
snprintf(respBuf,sizeof(respBuf),respFmt,0,"Success",buf+4);
char sendbuf[1024] = {0};
snprintf(sendbuf,sizeof(respBuf),sendfmt, strlen(respBuf),respBuf);
ret = send(m_httpServerSock, sendbuf, strlen(sendbuf), 0);
m_httpServerSock = -1;
CLog::getInstance()->info("send weixin %s %d Byte: %s",strCmd.c_str(),ret,respBuf);
}
}
else if("question_answer" == strCmd)
{
Json::Value valueSeqNum = value.get("seq_num","");
string strSeqNum = valueSeqNum.toStyledString_t();
Json::Value valueQuestion = value.get("question","");
string strQuestion = valueQuestion.toStyledString_t();
string strAnswer;
int type;
ProcessGetAnswer(strQuestion.c_str(),strAnswer,type);
const char* sndFmt = "{\"cmd\":\"question_answer\",\"device_id\":\"%s\",\"seq_num\":\"%s\",\"type\":\"%s\",\"result\":\"%s\"}";
snprintf(pResp,1000,sndFmt,strDeviceID.c_str(),strSeqNum.c_str(),"uri",strAnswer.c_str());
jsonLen = strlen(pResp);
respHead->len = htons(jsonLen);
ret = send(sock,respBuf,jsonLen+4,0);
CLog::getInstance()->info("%s send device %d: %s",strCmd.c_str(),ret,pResp);
}
else if("get_contact" == strCmd)
{
CLog::getInstance()->info("msg from equipment : %s,deviceID %s",strCmd.c_str(),strDeviceID.c_str());
vector<WXUserInfo> openIDs;
ProcessGetWXByDeviceID(strDeviceID.c_str(),openIDs);
vector<WXUserInfo>::iterator itr = openIDs.begin();
Json::FastWriter jsonWriter;
Json::Value root;
root["cmd"] = Json::Value("get_contact");
root["device_id"] = Json::Value((char*)strDeviceID.c_str());
if(openIDs.end() == itr)
{
root["result"].append("");
}
while(openIDs.end() != itr)
{
Json::Value valueResult;
WXUserInfo wxUser = *itr;
valueResult["openID"] = Json::Value(wxUser.openID.c_str());
valueResult["nickname"] = Json::Value(wxUser.nickname.c_str());
root["result"].append(valueResult);
itr++;
}
strncpy(pResp,jsonWriter.write(root).c_str(),1000);
jsonLen = strlen(pResp);
respHead->len = htons(jsonLen);
ret = send(sock,respBuf,jsonLen+4,0);
CLog::getInstance()->info("get_contact send device %d,errno %d: %s",ret,errno,pResp);
}
else if("set_vol" == strCmd || "power_off" == strCmd)
{
CLog::getInstance()->info("msg from equipment response : %s",strCmd.c_str());
}
else
{
CLog::getInstance()->error("msg from equipment unknown cmd %s",strCmd.c_str());
snprintf(pResp,1000,respJson,strCmd.c_str(),"fail",1);
jsonLen = strlen(pResp);
respHead->len = htons(jsonLen);
send(sock,respBuf,jsonLen+4,0);
}
}
else
{
CLog::getInstance()->error("msg from equipment format invalid: %s",buf+4);
snprintf(pResp,1000,respJson,"unknown","fail",1);
jsonLen = strlen(pResp);
respHead->len = htons(jsonLen);
send(sock,respBuf,jsonLen+4,0);
}
int leftlen = info.datapos-len-4;
if(leftlen > 0)
{
memmove(info.recvbuf,info.recvbuf+info.datapos,leftlen);
}
info.datapos = leftlen;
info.recvbuf[leftlen] = '\0';
return;
}
char* pos = strstr(buf,"\r\n\r\n");
if(NULL == pos)
{
if(info.datapos > 4096)
{
CloseSock(sock);
}
return;
}
CLog::getInstance()->info("pid %d sock %d recv %s",pid,sock,info.recvbuf);
const char* errmsg = "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 13\r\nConnection: close\r\n\r\n404 Not Found";
if(memcmp(buf,"GET ",4) == 0 || memcmp(buf,"POST ",5) == 0)
{
if(pos)
{
pos += 4;
//pos = "{\"openId\":\"asdfasdf\",\"msgType\":\"operation\",\"msgContent\":\"12312312\",\"operationType\":\"bind\"}";
Json::Reader reader;
Json::Value value;
if(reader.parse(pos,value,false))
{
ret = 0;
char respBuf[1024] = {0};
Json::Value openID = value.get("openId","");
string strOpenID = openID.toStyledString_t();
Json::Value msgtype = value.get("msgType","");
string strMsgType = msgtype.toStyledString_t();
Json::Value msgcontent = value.get("msgContent","");
string strMsgContent = msgcontent.toStyledString_t();
CLog::getInstance()->info("get openID %s, msgType %s, msgContent %s",strOpenID.c_str(),strMsgType.c_str(),strMsgContent.c_str());
Json::Value deviceID = value.get("deviceID","");
string strDeviceID = deviceID.toStyledString_t();
if("txt" == strMsgType)
{
}
else if("audio" == strMsgType)
{
strMsgContent = "";
Json::Value audiourl = value.get("url","");
string strAudioUrl = audiourl.toStyledString_t();
int ret = ProcessGetDeviceIDByWX(strOpenID.c_str(),strDeviceID);
if(0 == ret)
{
const char* audioJsonFmt = "{\"cmd\":\"play_voice\",\"device_id\":\"%s\",\"contact_id\":\"%s\",\"voice_uri\":\"%s\"}";
char sendAudioBuf[1024] = {0};
string nickname = "¸¸Ä¸";
ProcessGetNickName(strOpenID.c_str(),nickname);
snprintf(sendAudioBuf,1023,audioJsonFmt,strDeviceID.c_str(),nickname.c_str(),strAudioUrl.c_str());
SendMsgToDevice(strDeviceID.c_str(),sendAudioBuf);
}
else
{
CLog::getInstance()->info("send audio fail : no bind device");
ret = -4;
}
}
else if("operation" == strMsgType)
{
Json::Value operationType = value.get("operationType","");
string strOperationType = operationType.toStyledString_t();
if("bind" == strOperationType)
{
vector<WXUserInfo> users;
ProcessGetWXByDeviceID(strDeviceID.c_str(),users);
int bAdmin = 0;
if(users.size() == 0)
{
bAdmin = 1;
}
ret = ProcessBind(strOpenID.c_str(),strDeviceID.c_str(),strMsgContent.c_str(), bAdmin);
if(ret > 0)
{
ret = -4;
}
strMsgContent = "";
}
else if("unbind" == strOperationType)
{
ret = ProcessUnbind(strOpenID.c_str());
if(0 != ret)
{
ret = -4;
}
strMsgContent = "";
}
else if("bindlist" == strOperationType)
{
ret = ProcessGetBind(strOpenID.c_str(),strMsgContent);
if(0 != ret)
{
ret = -4;
}
string tmp = "\"";
tmp += strMsgContent;
tmp += "\"";
strMsgContent = tmp;
}
else if("contentPlay" == strOperationType)
{
Json::Value audiourl = value.get("url","");
string strAudioUrl = audiourl.toStyledString_t();
ret = ProcessGetDeviceIDByWX(strOpenID.c_str(),strDeviceID);
if(0 == ret)
{
const char* audioJsonFmt = "{\"cmd\":\"play_music\",\"device_id\":\"%s\",\"voice_uri\":\"%s\"}";
char sendPlayBuf[1024] = {0};
snprintf(sendPlayBuf,1023,audioJsonFmt,strDeviceID.c_str(),strAudioUrl.c_str());
if(SendMsgToDevice(strDeviceID.c_str(),sendPlayBuf) < 0)
{
ret = -3;
}
}
else
{
CLog::getInstance()->info("send play music fail : no bind device");
ret = -4;
}
strMsgContent = "";
}
else if("userlist" == strOperationType)//query weixin users binding the same toy
{
vector<WXUserInfo> openIDs;
ret = ProcessGetWXByDeviceID(strDeviceID.c_str(),openIDs);
if(0 != ret)
{
ret = -4;
}
vector<WXUserInfo>::iterator itr = openIDs.begin();
char idBuf[1024] = {0};
strMsgContent = "";
const char* idFmt = "{\"openID\":\"%s\",\"nickname\":\"%s\",\"bAdmin\":\"%s\"}";
if(openIDs.end() != itr)
{
snprintf(idBuf,sizeof(idBuf), idFmt, (*itr).openID.c_str(), (*itr).nickname.c_str(), (*itr).bAdmin.c_str());
strMsgContent = idBuf;
itr++;
}
while(openIDs.end() != itr)
{
snprintf(idBuf,sizeof(idBuf), idFmt, (*itr).openID.c_str(), (*itr).nickname.c_str(), (*itr).bAdmin.c_str());
strMsgContent += ",";
strMsgContent += idBuf;
itr++;
}
}
else if("deleteuser" == strOperationType)//administrator delete other weixin user
{
if(IsWXUserAdmin(strOpenID.c_str()))
{
ret = ProcessDelWXUser(strMsgContent.c_str());
if(0 != ret)
{
ret = -4;
}
}
else
{
ret = -2;
}
strMsgContent = "";
}
else if("setuser" == strOperationType)//set weixin user to be administrator
{
if(IsWXUserAdmin(strOpenID.c_str()))
{
ret = ProcessSetWXUserAdmin(strMsgContent.c_str());
if(0 != ret)
{
ret = -4;
}
}
else
{
ret = -2;
}
strMsgContent = "";
}
else if("setname" == strOperationType)//set weixin user's nickname
{
ret = ProcessSetWXUserNickName(strOpenID.c_str(),strMsgContent.c_str());
if(0 != ret)
{
ret = -4;
}
strMsgContent = "";
}
else if("setvoice" == strOperationType)
{
if(strDeviceID.c_str() == 0)
{
ProcessGetDeviceIDByWX(strOpenID.c_str(),strDeviceID);
}
if(strDeviceID.c_str() > 0)
{
const char* jsonFmt = "{\"cmd\":\"set_vol\",\"device_id\":\"%s\",\"volume\":\"%s\"}";
char sendVolBuf[1024] = {0};
snprintf(sendVolBuf,1023,jsonFmt,strDeviceID.c_str(),strMsgContent.c_str());
if(SendMsgToDevice(strDeviceID.c_str(),sendVolBuf) < 0)
{
ret = -3;
}
}
strMsgContent = "";
}
else if("playstatus" == strOperationType)
{
const char* jsonFmt = "{\"cmd\":\"play_status\",\"device_id\":\"%s\"}";
char statusBuf[256] = {0};
snprintf(statusBuf,255,jsonFmt,strDeviceID.c_str());
if(SendMsgToDevice(strDeviceID.c_str(),statusBuf) > 0)
{
info.datapos = 0;
info.recvbuf[0] = '\0';
m_httpServerSock = sock;
return;
}
ret = -3;//query fail
strMsgContent = "";
}
else if("defineQA" == strOperationType)
{
Json::Value audiourl = value.get("url","");
string strAudioUrl = audiourl.toStyledString_t();
int answerType = 1;//txt
size_t pos = strAudioUrl.find("http://");
if(string::npos != pos)
{
answerType = 2;//audio
}
ret = ProcessInsertQuestion(strMsgContent.c_str(),strAudioUrl.c_str(),answerType);
strMsgContent = "";
}
else if("locallist" == strOperationType)
{
ret = ProcessGetDeviceIDByWX(strOpenID.c_str(),strDeviceID);
if(0 == ret)
{
const char* jsonFmt = "{\"cmd\":\"list_file\",\"device_id\":\"%s\",\"page_num\":\"%s\"}";
char sendListBuf[1024] = {0};
snprintf(sendListBuf,1023,jsonFmt,strDeviceID.c_str(),strMsgContent.c_str());
if(SendMsgToDevice(strDeviceID.c_str(),sendListBuf) > 0)
{
info.datapos = 0;
info.recvbuf[0] = '\0';
m_httpServerSock = sock;
return;
}
ret = -3;
}
else
{
CLog::getInstance()->info("send list file fail : no bind device");
ret = -4;
}
strMsgContent = "";
}
else if("poweroff" == strOperationType)
{
if(strDeviceID.c_str() == 0)
{
ProcessGetDeviceIDByWX(strOpenID.c_str(),strDeviceID);
}
if(strDeviceID.c_str() > 0)
{
const char* jsonFmt = "{\"cmd\":\"power_off\",\"device_id\":\"%s\"}";
char sendOffBuf[1024] = {0};
snprintf(sendOffBuf,1023,jsonFmt,strDeviceID.c_str());
if(SendMsgToDevice(strDeviceID.c_str(),sendOffBuf) < 0)
{
ret = -3;
}
}
strMsgContent = "";
}
else
{
ret = 2;//unknown Operation
}
}
else
{
ret = 1;//unknown msgType
CLog::getInstance()->info("Unknown msgType %s",strMsgType.c_str());
}
if(0 == ret)
{
snprintf(respBuf,1024,respFmt,ret,"Success",strMsgContent.c_str());
}
else if(-1 == ret)
{
snprintf(respBuf,1024,respFmt,ret,"Repeated Bind","");
}
else if(-2 == ret)
{
snprintf(respBuf,1024,respFmt,ret,"Not Administrator","");
}
else if(-3 == ret)
{
snprintf(respBuf,1024,respFmt,ret,"Device Not Online","");
}
else if(-4 == ret)
{
snprintf(respBuf,1024,respFmt,ret,"Database Error","");
}
else if(1 == ret)
{
snprintf(respBuf,1024,respFmt,ret,"Fail","Unknown Operation");
}
else
{
snprintf(respBuf,1024,respFmt,ret,"Fail","");
}
char sendbuf[1024] = {0};
snprintf(sendbuf,1024,sendfmt,strlen(respBuf),respBuf);
send(sock,sendbuf,strlen(sendbuf),0);
CLog::getInstance()->info("send weixin response %s",respBuf);
info.datapos = 0;
info.recvbuf[0] = '\0';
return;
}
}
}
send(sock,errmsg,strlen(errmsg),0);
CLog::getInstance()->info("pid %d send errmsg %s",pid,errmsg);
info.datapos = 0;
info.recvbuf[0] = '\0';
}
int CNetworkInterface::ProcessBind(const char * openID,const char * equipmentID,const char* nickname,int bAdmin)
{
int ret = CDbInterface::Instance()->InsertWX2UserTable(openID,equipmentID,nickname,bAdmin);
if(0 == ret)
{
//insert success
return ret;
}
else if(1062 == ret)
{
//already exist
return -1;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->InsertWX2UserTable(openID,equipmentID,nickname,bAdmin);
if(0 == ret)
{
//insert success
}
}
}
return ret;
}
int CNetworkInterface::ProcessUnbind(const char * openID)
{
int ret = CDbInterface::Instance()->DelWX2UserTable((char*)openID);
if(0 == ret)
{
//success
return ret;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->DelWX2UserTable((char*)openID);
}
}
return ret;
}
int CNetworkInterface::ProcessGetBind(const char * openID,string& uuid)
{
int ret = CDbInterface::Instance()->GetUserIDByWX((char*)openID,uuid);
if(0 == ret)
{
//success
return ret;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->GetUserIDByWX((char*)openID,uuid);
}
}
return ret;
}
int CNetworkInterface::ProcessGetWXByDeviceID(const char* eID,vector<WXUserInfo>& openIDs)
{
int ret = CDbInterface::Instance()->GetWXByUserID(eID,openIDs);
if(0 == ret)
{
//success
return ret;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->GetWXByUserID(eID,openIDs);
}
}
return ret;
}
int CNetworkInterface::ProcessGetDeviceIDByWX(const char * openID,string& deviceID)
{
int ret = CDbInterface::Instance()->GetUserIDByWX(openID,deviceID);
if(0 == ret)
{
//success
return ret;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->GetUserIDByWX(openID,deviceID);
}
}
return ret;
}
bool CNetworkInterface::IsWXUserAdmin(const char *openID)
{
int admin = 0;
int ret = CDbInterface::Instance()->IsWXAdmin(openID, admin);
if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->IsWXAdmin(openID, admin);
}
}
if(0 == ret)
{
return admin>0?true:false;
}
return false;
}
int CNetworkInterface::ProcessDelWXUser(const char *openID)
{
int ret = CDbInterface::Instance()->DelWX2UserTable(openID);
if(0 == ret)
{
//success
return ret;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->DelWX2UserTable(openID);
}
}
return ret;
}
int CNetworkInterface::ProcessSetWXUserAdmin(const char *openID)
{
int ret = CDbInterface::Instance()->SetWXAdmin(openID);
if(0 == ret)
{
//success
return ret;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->SetWXAdmin(openID);
}
}
return ret;
}
int CNetworkInterface::ProcessSetWXUserNickName(const char *openID, const char* nickname)
{
int ret = CDbInterface::Instance()->SetWXNickName(openID, nickname);
if(0 == ret)
{
//success
return ret;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->SetWXNickName(openID, nickname);
}
}
return ret;
}
int CNetworkInterface::ProcessGetNickName(const char *openID, string& nickname)
{
int ret = CDbInterface::Instance()->GetWXNickName(openID, nickname);
if(0 == ret)
{
//success
return ret;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->GetWXNickName(openID, nickname);
}
}
return ret;
}
int CNetworkInterface::ProcessInsertQuestion(const char * question,const char * answer,int type)
{
int ret = CDbInterface::Instance()->InsertQuestionTable(question,answer,type);
if(0 == ret)
{
//insert success
return ret;
}
else if(1062 == ret)
{
//already exist
return -1;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->InsertQuestionTable(question,answer,type);
if(0 == ret)
{
//insert success
}
}
}
return ret;
}
int CNetworkInterface::ProcessGetAnswer(const char * question,string& answer,int& type)
{
int ret = CDbInterface::Instance()->GetAnswerByQuestion(question,answer,type);
if(0 == ret)
{
//success
return ret;
}
else if(2006 == ret || 2013 == ret)
{
//mysql disconnect
CDbInterface::Instance()->DBDisConnect();
if(CDbInterface::Instance()->DBConnect())
{
ret = CDbInterface::Instance()->GetAnswerByQuestion(question,answer,type);
}
}
return ret;
}
int CNetworkInterface::SendMsgToWX(const char *openID,const char * msgurl)
{
int ret = 0;
if(-1 == m_httpClientSock)
{
hostent *pHost = gethostbyname("aistoy.com");
unsigned int ip = 0;
if( pHost != NULL )
{
memcpy(&ip,pHost->h_addr_list[0],sizeof(int));
}
struct sockaddr_in serv;
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = ip;
serv.sin_port = htons(80);
m_httpClientSock = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
if(-1 == m_httpClientSock)
{
return -1;
}
struct timeval timeout;
timeout.tv_sec=3;
timeout.tv_usec=0;
setsockopt(m_httpClientSock, SOL_SOCKET,SO_RCVTIMEO, (char*)&timeout,sizeof(timeout));
setsockopt(m_httpClientSock, SOL_SOCKET,SO_SNDTIMEO, (char*)&timeout,sizeof(timeout));
ret = connect(m_httpClientSock,(struct sockaddr*)&serv,sizeof(serv));
if(ret != 0)
{
close(m_httpClientSock);
m_httpClientSock = -1;
CLog::getInstance()->info("can NOT connect to weixin server");
return -1;
}
}
const char* fmt = "POST /welcome/aist HTTP/1.1\r\nHost: aistoy.com\r\nContent-Length: %d\r\n\r\n%s";
const char* jsonfmt = "{\"openId\":\"%s\",\"msgType\":\"audio\",\"url\":\"%s\"}";
char buf[1024] = {0};
char jsonbuf[1024] = {0};
snprintf(jsonbuf,1023,jsonfmt,openID,msgurl);
snprintf(buf,1023,fmt,strlen(jsonbuf),jsonbuf);
ret = send(m_httpClientSock,buf,strlen(buf),0);
if(ret < 0)
{
close(m_httpClientSock);
m_httpClientSock = -1;
CLog::getInstance()->info("send to weixin server fail %d: %s",errno,buf);
return -1;
}
CLog::getInstance()->info("send to weixin %s",buf);
ret = recv(m_httpClientSock,buf,1023,0);
if(ret <= 0)
{
close(m_httpClientSock);
m_httpClientSock = -1;
CLog::getInstance()->info("recv from weixin %d",errno);
return -1;
}
close(m_httpClientSock);
m_httpClientSock = -1;
buf[ret] = '\0';
CLog::getInstance()->info("recv from weixin %s",buf);
return 0;
}
int CNetworkInterface::SendMsgToDevice(const char *deviceID,const char *msgurl)
{
ChannelInfo info;
if(CPeerGroup::Instance()->GetChannel(deviceID,info))
{
int sock = info.sock;
if(sock > 0)
{
MsgHead pMsgHead;
pMsgHead.cmd = htons(0x0101);
int jlen = strlen(msgurl);
pMsgHead.len = htons(jlen);
int ret = send(sock,(char*)&pMsgHead,sizeof(pMsgHead),0);
ret = send(sock,msgurl,jlen,0);
CLog::getInstance()->info("send audio to device sock %d len %d: %s",sock,ret,msgurl);
return ret;
}
else
{
CLog::getInstance()->info("send audio fail : socket not exist");
return -1;
}
}
else
{
CLog::getInstance()->info("send audio fail : device NOT online");
return -2;
}
}
void CNetworkInterface::DelTimeout()
{
map<int,SOCKINFO>::iterator itr = m_sockMap.begin();
time_t curtime = time(NULL);
while(m_sockMap.end() != itr)
{
if(itr->second.updatetime+600 < curtime)
{
int sock = itr->first;
CLog::getInstance()->info("Del Timeout sock %d",sock);
epoll_ctl(m_epfd,EPOLL_CTL_DEL,sock,NULL);
close(sock);
m_sockMap.erase(itr++);
continue;
}
itr++;
}
}
void CNetworkInterface::CloseSock(int sock)
{
epoll_ctl(m_epfd,EPOLL_CTL_DEL,sock,NULL);
close(sock);
CLog::getInstance()->info("close sock %d",sock);
map<int,SOCKINFO>::iterator itr = m_sockMap.find(sock);
if(m_sockMap.end() != itr)
{
CPeerGroup::Instance()->DelChannel(itr->second.deviceID);
m_sockMap.erase(itr);
}
}
void CNetworkInterface::DoSendMsg2WX()
{
m_msgQueLock.Lock();
if(m_msgQue.empty())
{
m_msgQueLock.Unlock();
usleep(10000);
return;
}
IMMSG& msg = m_msgQue.front();
string openid = msg.openID;
string url = msg.voiceUrl;
m_msgQue.pop();
m_msgQueLock.Unlock();
SendMsgToWX(openid.c_str(),url.c_str());
}
void* CNetworkInterface::AcceptThread(void *para)
{
CLog::getInstance()->info("AcceptThread start");
CNetworkInterface* pNetwork = (CNetworkInterface*)para;
while(pNetwork->m_status)
{
pNetwork->DoAccept();
pNetwork->DoRecv();
pNetwork->DelTimeout();
}
CLog::getInstance()->info("AcceptThread exit");
return NULL;
}
void* CNetworkInterface::SendMsg2WXThread(void *para)
{
CLog::getInstance()->info("SendMsg2WXThread start");
CNetworkInterface* pNetwork = (CNetworkInterface*)para;
while(pNetwork->m_status)
{
pNetwork->DoSendMsg2WX();
}
CLog::getInstance()->info("SendMsg2WXThread exit");
return NULL;
}
void* CNetworkInterface::ProcessThread(void * para)
{
THREAD* req = (THREAD*)para;
CNetworkInterface* pNetwork = (CNetworkInterface*)req->serv;
CLog::getInstance()->info("ProcessThread %d start",req->idx);
SetNonblocking(req->rfd);
while(pNetwork->m_status)
{
char buf[1];
//CLog::getInstance()->info("ProcessThread read 1");
if(read(req->rfd,buf,1) != 1)
{
usleep(10000);
//CLog::getInstance()->info("ProcessThread read 2");
continue;
}
int cfd = req->newconn.front();
CLog::getInstance()->info("ProcessThread read sock %d",cfd);
if(cfd > 0)
{
pNetwork->DoProcess(cfd);
}
req->newconn.pop();
}
CLog::getInstance()->info("ProcessThread %d start",req->idx);
return NULL;
}
void CNetworkInterface::Stop()
{
m_status = false;
pthread_join(m_threadid,NULL);
if(m_threads)
{
for(int i=0; i < m_threadNum; i++)
{
pthread_join(m_threads[i].pid,NULL);
}
delete[] m_threads;
}
pthread_join(m_threadMsg,NULL);
CLog::getInstance()->info("network stop");
}
int CNetworkInterface::CreateUDPSocket()
{
int s = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
return s;
}
int CNetworkInterface::CreateTCPSocket()
{
int s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
SetNonblocking(s);
int optint = 1;
int keepIdle = 30;
int keepInterval = 5;
int keepCount = 3;
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&optint, sizeof(optint));
setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char *)&optint, sizeof(optint));
setsockopt(s, SOL_TCP, TCP_KEEPIDLE, (void *)&keepIdle, sizeof(keepIdle));
setsockopt(s, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval));
setsockopt(s, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount));
return s;
}
|
9cb586a282244085afc37f338bf57cecf0466a22
|
5c87811a523d0b9e1ab968a3dcddf58af875fa84
|
/engine/enginecode/include/platform/windows/winTimer.h
|
31d461908e7819881e5726a568ebef7db71a4958
|
[] |
no_license
|
tinitis0/Game-Engine-Architecture
|
d548e314e0e37b7753227f457cdd10c0d8d65deb
|
30339088ad7ac0c08acef4cb1fa6347bd5c9d06f
|
refs/heads/main
| 2023-06-21T04:04:38.806144
| 2021-07-21T21:55:55
| 2021-07-21T21:55:55
| 388,253,458
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,026
|
h
|
winTimer.h
|
/*! \file winTimer.h */
#pragma once
#include <Windows.h>
#include "core/timer.h"
namespace Engine
{
/** \file WinTimer.h
* Windows specific timer which use queryPerformanceCount
*/
class WinTimer : public Timer
{
public:
virtual void start() override
{
QueryPerformanceFrequency(&m_frequency);
QueryPerformanceCounter(&m_startTime);
}; //!< starts the timer
virtual inline void reset() override { QueryPerformanceCounter(&m_startTime); }; //!< resets the timer
virtual float getElapsedTime() override
{
QueryPerformanceCounter(&m_endTime);
float result = (m_endTime.QuadPart - m_startTime.QuadPart) * 1000.0 / m_frequency.QuadPart; //!< calculates the result
result /= 1000.f; //!< divides the result by 1000
return result; //!< returns the result after dividing it
} //!< gets the elasped time
private:
LARGE_INTEGER m_startTime; //!< Start time for the timer
LARGE_INTEGER m_endTime; //!< End time for the timer
LARGE_INTEGER m_frequency; //!< Ticks per second of CPU
};
}
|
95cbafd6e844b78ec14f208c261939a912848ef3
|
38a80dd6d1cc52c623d3ac05a113f181ca39611e
|
/engine/flyai.h
|
8d2bebfdcf1d9ebd8145efdb328fc71c462a6881
|
[] |
no_license
|
StanislavKraev/fliezzz
|
cc374958e1f829e372d8ece037647d5262253b5b
|
1cfbb95ed7ecf57d8bf657fe561b3df81f260ccc
|
refs/heads/master
| 2020-05-18T11:30:26.876552
| 2015-05-22T21:17:37
| 2015-05-22T21:17:37
| 35,785,254
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,782
|
h
|
flyai.h
|
#ifndef FLYAI_H
#define FLYAI_H
#include <QObject>
#include "engine/creatureai.h"
#include "engine/movedirection.h"
class QStateMachine;
class QState;
class QFinalState;
namespace engine
{
class IGameDataProvider;
class IMovesHolder;
class FlyAI: public QObject, public CreatureAI
{
Q_OBJECT
public:
const double MinThinkElaps = 0.7;
public:
FlyAI(double maxAge, double maxVelocity, double maxAlt, double maxThinkTime, const Creature::CreatureState &state,
IGameDataProvider *gameDataProvider, IMovesHolder *movesHolder);
virtual ~FlyAI();
public:
bool isMoving() const;
void stop();
int getSimpleState() const;
public:
virtual void init();
public slots:
void advance(double dt);
private slots:
void advanceThinking();
void advanceFlying();
void advanceLanding();
void advanceFalling();
void onFlyingEnter();
void onFallingEnter();
void onDeadEnter();
void onThinkingEnter();
void onLandingEnter();
private:
void changeRoute();
double angleFromDirection(MoveDirection dir) const;
signals:
void maxAgeReached();
void maxFlyingDistanceReached();
void almostArrived();
void landed();
void thinkTimeout();
void advanceSignal();
void stopped();
private:
QStateMachine *m_fsm;
QState* m_thinkingState;
QState* m_flyingState;
QState* m_landingState;
QState* m_fallingState;
QFinalState* m_deadState;
QState* m_curState;
double m_flyingDuration;
IGameDataProvider *m_gameDataProvider;
double m_thinkingTime;
double m_maxThinkTime;
MoveDirection m_choosenMove;
QPoint m_targetSpot;
QPointF m_targetSpotPart;
QPointF m_takeOffPt;
double m_dt;
IMovesHolder *m_movesHolder;
};
}
#endif // FLYAI_H
|
1e502e823311ac985e3bac1cac276a0fabdb0372
|
dada0dd0f3004fe5178c752a633c8f027e92dec9
|
/Codeforces/Ladder-A/1453a.cpp
|
ff92f6a588b09a0310fa07aea981bb28d8f04381
|
[] |
no_license
|
scortier/Snippets
|
0a64d72a1ab1d3d2e15730b608f49c259b4dc6de
|
51a3be8eb1cc3eb5688c431efe37bb6fd862b5e7
|
refs/heads/master
| 2023-06-29T00:38:59.232780
| 2021-08-04T13:26:25
| 2021-08-04T13:26:25
| 261,730,451
| 6
| 1
| null | 2020-09-30T19:15:57
| 2020-05-06T10:52:42
|
C++
|
UTF-8
|
C++
| false
| false
| 1,576
|
cpp
|
1453a.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define test int tt;cin>>tt;while(tt--)
#define fl(i,a,b) for( int i=a;i<b;i++)
#define bfl(i,a,b) for( int i=b-1;i>=a;i--)
#define ll long long int
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define MOD 1000000007
#define PI acos(-1.0)
#define assign(x,val) memset(x,val,sizeof(x))
#define prec(val, dig) fixed << setprecision(dig) << val
#define pi pair < int , int >
#define pr(gg) cout<<gg<<endl
#define mk(arr,n,type) type *arr=new type[n];
void lage_rho() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
/**********=============########################============***********/
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Function to find LCM
int findlcm(int a, int b)
{
int gc = gcd(a, b);
return a * b / gc;
}
int CountCommon(int arr1[], int arr2[],
int m, int n)
{
int diff1 = arr1[1] - arr1[0];
int diff2 = arr2[1] - arr2[0];
int lcm = findlcm(diff1, diff2);
int ans1 = (arr1[m - 1] - arr1[0]) / lcm;
int ans2 = (arr2[n - 1] - arr2[0]) / lcm;
int ans = min(ans1, ans2);
return ans ;
}
void solve()
{
int n, m;
cin >> n >> m;
int a[n], b[m];
fl(i, 0, n) cin >> a[i];
fl(i, 0, m) cin >> b[i];
cout << CountCommon(a, b, n, m) << endl;
}
int32_t main()
{
lage_rho();
test
solve();
return 0;
}
|
9599229ee8a7266261651708e71f046fba6c7a32
|
433277e9e2599864ff6c0370b3c543dab92c478d
|
/C++/54_Spiral_matrix.cpp
|
a707d6db48090a868c45f2aa2aa77f8566e9f673
|
[] |
no_license
|
MihawkHu/leetcode
|
1d0619624d9b0e9c8cf6320bc7763485e8610402
|
37e17b5b26b692214fe5b7660b19367c0876a461
|
refs/heads/master
| 2021-01-14T07:55:26.479252
| 2017-02-27T15:23:06
| 2017-02-27T15:23:06
| 81,967,938
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,359
|
cpp
|
54_Spiral_matrix.cpp
|
class Solution {
public:
void zyj(vector<vector<int>>& matrix, vector<int>& ans, int x, int y, int k) {
if (2*k == matrix.size() || 2*k == matrix[0].size()) return;
if (2*k+1 == matrix.size()) {
for (int i = 0; i < matrix[0].size() - 2*k; ++i) {
ans.push_back(matrix[x][y+i]);
}
return;
}
if (2*k+1 == matrix[0].size()) {
for (int i = 0; i < matrix.size() - 2*k; ++i) {
ans.push_back(matrix[x+i][y]);
}
return;
}
for (int i = 0; i < matrix[0].size() - 2*k; ++i) {
ans.push_back(matrix[x][y+i]);
}
for (int i = 0; i < matrix.size() - 2*(k+1); ++i) {
ans.push_back(matrix[x+i+1][y+matrix[0].size()-2*k-1]);
}
for (int i = 0; i < matrix[0].size() - 2*k; ++i) {
ans.push_back(matrix[x+matrix.size()-2*k-1][y+matrix[0].size()-2*k-1-i]);
}
for (int i = 0; i < matrix.size() - 2*(k+1); ++i) {
ans.push_back(matrix[x+matrix.size()-2*(k+1)-i][y]);
}
zyj(matrix, ans, x+1, y+1, k+1);
}
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
if (matrix.size() == 0) return ans;
zyj(matrix, ans, 0, 0, 0);
return ans;
}
};
|
188197bad92f5cf9d921636d009fbc88b926ab80
|
30315827c02c257bc98407d61fcd0251fcea351c
|
/tinyserver/src/utils/common_tool.cpp
|
9013b60f671ad417ec07db7e0d39d2baa94968ba
|
[] |
no_license
|
aihao1007/tinyserver
|
9b79f26bed002e8f84cdcedf48d9143b183812f0
|
b91cc82e31748970e3182c7e8c38e9013ee91466
|
refs/heads/master
| 2022-01-10T12:55:57.612708
| 2019-05-05T12:47:39
| 2019-05-05T12:47:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 463
|
cpp
|
common_tool.cpp
|
//
// Created by hhk on 18-12-19.
//
#include "utils/common_tool.h"
long WebServer::get_file_size(FILE *f) {
long size = -1;
long cur = ftell(f);
if (f != nullptr) {
fseek (f, 0, SEEK_END);
size = ftell (f);
fseek (f, cur, SEEK_SET);
}
return size;
}
long WebServer::get_file_size(const std::string &path) {
auto f = fopen(path.c_str(), "rb");
auto size = get_file_size(f);
fclose(f);
return size;
}
|
59fd4b577269869513bb2345922379bb5289c4fe
|
7d048d2b11062bb016662ba4a8bf9646b471c7fc
|
/source_trunk/source/Algorithms/RandomForest/GPURandomForest/GPURandomForest.h
|
29eb48413f21845468639fb8a649af55283bf99c
|
[
"MIT"
] |
permissive
|
KarlJansson/GPU_tree-ensembles
|
d414f227ca5aea17dc4247b758d9eb61096360d5
|
531d0e49db7d4c0102a999314c172c722249d8e8
|
refs/heads/master
| 2021-01-02T08:33:07.284509
| 2017-06-14T08:06:42
| 2017-06-14T08:06:42
| 13,192,291
| 4
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,056
|
h
|
GPURandomForest.h
|
#pragma once
#include "IAlgorithm.h"
namespace DataMiner{
class GPURandomForest : public IAlgorithm{
public:
GPURandomForest(GraphicsManagerPtr gfxMgr);
~GPURandomForest();
struct SharedBuffer{
unsigned int cb_numTrees;
unsigned int cb_numFeatures;
unsigned int cb_maxDepth;
unsigned int cb_currentDepth;
unsigned int cb_availableNodes;
unsigned int cb_nodeBufferStart;
unsigned int cb_nodeBufferEnd;
unsigned int cb_maxInstInNodes;
unsigned int cb_instanceCount;
unsigned int cb_attributeCount;
unsigned int cb_nodeIdFlip;
};
struct ConstantBufferBagging{
unsigned int cb_treeOffset;
unsigned int cb_instanceCount;
unsigned int cb_nodeBufferEnd;
bool cb_baggingActivated;
};
struct ConstantBufferClassify{
unsigned int cb_numTrees;
unsigned int cb_treeOffset;
unsigned int cb_nodeBufferEnd;
unsigned int cb_majorityClass;
unsigned int cb_instanceCount;
unsigned int cb_attributeCount;
};
enum KernelID {KID_Bagging = 0, KID_Build, KID_KeplerBuild, KID_Sort, KID_FindSplit, KID_Split, KID_EvaluateSplit, KID_Classify, KID_ExtremeFindSplit, KID_ExtremeCreateNodes, KID_ExtremeMakeSplit};
struct ConstantUpdate{
ConstantUpdate(void* content, int id):m_content(content),m_id(id){}
void* m_content;
int m_id;
};
protected:
void run();
void calculateMaxNodes(int devId);
void writeOutputStream();
void runBaggingProcess();
void runClassificationProcess(unsigned int trees);
void getResultsFromGPU();
void getVotesFromGPU();
void evaluateTrees();
void initResources();
void initResourceBatch(bool updateOnly);
void updateResourceBatchGPU();
void cleanResources();
void setBufferSettings();
void quickSort(std::vector<Value::v_precision> &vals, std::vector<unsigned int> &index, int left, int right);
int partition(std::vector<Value::v_precision> &vals, std::vector<unsigned int> &index, int l, int r);
void quickSort(std::vector<Value::v_precision> &vals, std::vector<int> &index, int left, int right, std::vector<unsigned int>& sortBuff);
int partition(std::vector<Value::v_precision> &vals, std::vector<int> &index, int l, int r, std::vector<unsigned int>& sortBuff);
GraphicsManagerPtr m_gfxMgr;
std::map<std::string,int>
m_gpuFunctionIds,
m_bufferIds;
std::map<std::string,GraphicsManager::ResourceType> m_resourceTypeIds;
std::vector<int>
m_setBufferIdsBuild,
m_setBufferIdsBagging,
m_setBufferIdsSort,
m_setBufferIdsDist,
m_setBufferIdsEval,
m_setBufferIdsSplit,
m_setBufferIdsClassify,
m_setBufferIdsKeplerBuild,
m_setBufferIdsExFindSplit,
m_setBufferIdsExMakeSplit,
m_setBufferIdsExCreateNodes;
std::vector<GraphicsManager::ResourceType>
m_setResourceTypesBuild,
m_setResourceTypesBagging,
m_setResourceTypesSort,
m_setResourceTypesDist,
m_setResourceTypesEval,
m_setResourceTypesSplit,
m_setResourceTypesClassify,
m_setResourceTypesKeplerBuild,
m_setResourceTypesExFindSplit,
m_setResourceTypesExMakeSplit,
m_setResourceTypesExCreateNodes;
unsigned int
m_MaxDepth,
m_KValue,
m_numTrees,
m_numFeatures,
m_maxNodesPerIteration,
m_maxTreesPerIteration,
m_indVecSize,
m_seed,
m_depth,
m_clCorrect[2],
m_clWrong[2],
m_internalNodes,
m_leafNodes;
int m_maxInstInNodes,
m_version;
SharedBuffer m_constants;
ConstantBufferBagging m_constantsBagging;
ConstantBufferClassify m_constantsClassify;
std::vector<Value::v_precision>
m_splitPointsVec,
m_classProbVec;
std::vector<int>
m_attributeVec;
std::vector<unsigned int>
m_childVec,
m_baseIndVec,
m_testSetClassVec,
m_testSetVotes;
std::map<std::wstring,double> m_kernelTimes;
double
m_baggingTime,
m_buildTime,
m_classificationTime,
m_totalTime,
m_accuracy,
m_enrichCl1,
m_enrichCl2,
m_maxEnrichCl1,
m_maxEnrichCl2,
m_auc;
bool
m_saveModel,
m_kernelSpecificTimings;
int m_devId;
std::vector<GPURandomForestPtr> m_forests;
};
}
|
aeb32928ffb21b52ab02dbcc90b92f96165aa960
|
7aa75d5591937fc1e4bf10d3f676038bc9a77bb3
|
/rsp/FileList.h
|
c5401eeee901c14d73c4ca27bedf492c13245f10
|
[
"MIT"
] |
permissive
|
lsycool/rsp
|
45fbc90d1dc0c2e3070f83ebb8bc2dd15ac600a1
|
b4bc62b19679291338fd7516709911c6fed23e5a
|
refs/heads/master
| 2020-04-15T19:47:42.808615
| 2016-09-14T02:22:26
| 2016-09-14T02:22:26
| 68,163,290
| 3
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,134
|
h
|
FileList.h
|
#pragma once
using namespace std;
// CFileList 对话框
class CFileList : public CDialogEx
{
DECLARE_DYNAMIC(CFileList)
public:
CFileList(CWnd* pParent = NULL); // 标准构造函数
virtual ~CFileList();
CString filename;//记录文件名
CString projection;//投影
int bandcount;//波段数
float pixel;//分辨率
BOOL isAdded;//是否已经添加
vector<CString> pathname;//存储文件名
CMenu* pMenu;
// 对话框数据
enum { IDD = IDD_DIALOG_FILELIST };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
// //显示信息
void setMessage(CString filepath,CString projection,CString cordin,CString datum,int bandcount,int sizex,int sizey,double gt1=0,double gt2=0,double gt3=0,double gt4=0,double gt5=0,double gt6=0);
CTreeCtrl m_TreeFile;
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedButtonAddfile();
afx_msg void OnBnClickedButtonDelfile();
CMFCMenuButton m_menubutton;
afx_msg void OnBnClickedMfcmenubuttonWdowdisp();
afx_msg void OnBnClickedButtonMg();
afx_msg void OnBnClickedCancel();
};
|
8651caf2517a766499e7623c284b5b1f6b0415f6
|
56ea93b31bea2467a39b4814bd0a12b822797e9b
|
/common/src/combatnode.hpp
|
2f1a7ad9fa17daa5f5f499de39f2f6231d9f1672
|
[] |
no_license
|
etorth/mir2x
|
924ff4f76fec2bce502cd8cdc12c7a607b99c2f7
|
f31ce2a12dfa3fc64fb8e002f30562f964cbd43e
|
refs/heads/master
| 2023-08-08T11:44:08.509299
| 2023-07-24T04:54:17
| 2023-07-24T04:54:17
| 59,230,985
| 294
| 159
| null | 2022-06-09T21:55:56
| 2016-05-19T18:17:03
|
C++
|
UTF-8
|
C++
| false
| false
| 1,537
|
hpp
|
combatnode.hpp
|
#pragma once
#include <array>
#include <utility>
#include <cstdint>
#include <cstdlib>
#include <cinttypes>
#include "serdesmsg.hpp"
#include "protocoldef.hpp"
struct CombatNode
{
int dc[2] = {0, 0};
int mc[2] = {0, 0};
int sc[2] = {0, 0};
int ac[2] = {0, 0};
int mac[2] = {0, 0};
int dcHit = 0;
int mcHit = 0;
int dcDodge = 0;
int mcDodge = 0;
int speed = 0;
int comfort = 0;
int luckCurse = 0;
struct AddElem
{
int fire = 0;
int ice = 0;
int light = 0;
int wind = 0;
int holy = 0;
int dark = 0;
int phantom = 0;
};
AddElem dcElem {};
AddElem acElem {};
struct AddLoad
{
int body = 0;
int weapon = 0;
int inventory = 0;
}
load {};
int randPickDC() const;
int randPickMC() const;
int randPickSC() const;
int minDC() const { return std::min<int>(dc[0], dc[1]); }
int maxDC() const { return std::max<int>(dc[0], dc[1]); }
int minMC() const { return std::min<int>(mc[0], mc[1]); }
int maxMC() const { return std::max<int>(mc[0], mc[1]); }
int minSC() const { return std::min<int>(sc[0], sc[1]); }
int maxSC() const { return std::max<int>(sc[0], sc[1]); }
};
// server/client uses same CombatNode calculation
// player's other attributes may affect how CombatNode -> DamageNode, but shall not affect CombatNode itself
CombatNode getCombatNode(const SDWear &, const SDLearnedMagicList &, uint64_t, int);
|
fea63a8125b5f8f7e2ae0b6e42c315960ed6d962
|
20c86d7c831ab9c0fca389d494a1e15825b71160
|
/C/syntax/SyntaxToken.cpp
|
1223167d1c8a8b9ccad9804a33be4c69deaa0ef7
|
[
"BSD-3-Clause"
] |
permissive
|
ltcmelo/psychec
|
a747d0eb08806fcc6d054c91635b198d6c3ac25c
|
fe1dabb6e85c4cabf0c623721d82f665b7d94216
|
refs/heads/master
| 2022-07-28T03:20:15.250911
| 2022-07-23T19:38:16
| 2022-07-23T19:38:16
| 73,128,877
| 503
| 39
|
BSD-3-Clause
| 2022-07-23T19:33:29
| 2016-11-07T23:02:46
|
C++
|
UTF-8
|
C++
| false
| false
| 10,071
|
cpp
|
SyntaxToken.cpp
|
// Copyright (c) 2016/17/18/19/20/21/22 Leandro T. C. Melo <ltcmelo@gmail.com>
// Copyright (c) 2008 Roberto Raggi <roberto.raggi@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "SyntaxToken.h"
#include "SyntaxLexeme_ALL.h"
#include "SyntaxTree.h"
#include <iostream>
namespace psy {
namespace C {
const char* tokenNames[] =
{
// ----------------------------------------------------------------- //
// These must be ordered as according to the SyntaxKind enumerators. //
// ----------------------------------------------------------------- //
"EOF",
"#error#",
"<multiline comment>",
"<documentation multiline comment>",
"<comment>",
"<documentation comment>",
"<identifier>",
"<integer constant>",
"<floating constant>",
"<imaginary integer constant>",
"<imaginary floating constant>",
"<character constant>",
"<L character constant>",
"<u character constant>",
"<U character constant>",
"<string literal>",
"<L string literal>",
"<u8 string literal>",
"<u string literal>",
"<U string literal>",
"...",
"{",
"}",
"[",
"]",
"(",
")",
"#",
"##",
";",
"auto",
"break",
"case",
"char",
"const",
"continue",
"default",
"do",
"double",
"else",
"enum",
"extern",
"float",
"for",
"goto",
"if",
"inline",
"int",
"long",
"register",
"restrict",
"return",
"short",
"signed",
"static",
"struct",
"switch",
"typedef",
"union",
"unsigned",
"void",
"volatile",
"while",
"->",
".",
"++",
"--",
"*",
"&",
"+",
"-",
"~",
"/",
"%",
"<<",
">>",
"|",
"^",
"!",
"&&",
"||",
"<",
"<=",
">",
">=",
"==",
"!=",
":",
"?",
"=",
"*=",
"/=",
"%=",
"+=",
"-=",
"<<=",
">>=",
"&=",
"^=",
"|=",
",",
"sizeof",
"wchar_t",
"_Bool",
"_Complex",
"__func__",
"_Alignas",
"_Alignof",
"_Atomic",
"_Generic",
"_Noreturn",
"_Static_assert",
"_Thread_local",
"char16_t",
"char32_t",
"false",
"true",
"NULL",
"nullptr",
"<R string literal>",
"<LR string literal>",
"<u8R string literal>",
"<uR string literal>",
"<UR string literal>",
"__attribute__",
"__thread",
"__typeof__",
"__extension__",
"asm",
"__builtin_va_arg",
"__builtin_offsetof",
"__builtin_tgmath",
"__builtin_choose_expr",
"__FUNCTION__",
"__PRETTY_FUNCTION__",
"__complex__",
"__real__",
"__imag__",
"va_arg",
"offsetof",
"_Template",
"_Forall",
"_Exists",
"<psychec marker>"
};
} // C
} // psy
using namespace psy;
using namespace C;
SyntaxToken::SyntaxToken(SyntaxTree* tree)
: tree_(tree)
, rawSyntaxK_(0)
, byteSize_(0)
, charSize_(0)
, byteOffset_(0)
, charOffset_(0)
, matchingBracket_(0)
, BF_all_(0)
, lineno_(0)
, column_(0)
, lexeme_(nullptr)
{
if (!tree_)
BF_.missing_ = true;
}
SyntaxToken::~SyntaxToken()
{}
void SyntaxToken::setup()
{
rawSyntaxK_ = 0;
byteSize_ = 0;
charSize_ = 0;
byteOffset_ = 0;
charOffset_ = 0;
matchingBracket_ = 0;
BF_all_ = 0;
lexeme_ = nullptr;
}
bool SyntaxToken::isComment() const
{
return rawSyntaxK_ == MultiLineCommentTrivia
|| rawSyntaxK_ == MultiLineDocumentationCommentTrivia
|| rawSyntaxK_ == SingleLineCommentTrivia
|| rawSyntaxK_ == SingleLineDocumentationCommentTrivia
|| rawSyntaxK_ == Keyword_ExtPSY_omission;
}
Location SyntaxToken::location() const
{
LinePosition lineStart(lineno_, column_);
LinePosition lineEnd(lineno_, column_ + byteSize_ - 1); // TODO: Account for joined tokens.
FileLinePositionSpan fileLineSpan(tree_->filePath(), lineStart, lineEnd);
return Location::create(fileLineSpan);
}
SyntaxToken::Category SyntaxToken::category() const
{
return category(SyntaxKind(rawSyntaxK_));
}
SyntaxToken::Category SyntaxToken::category(SyntaxKind k)
{
switch (k) {
case IdentifierToken:
return Category::Identifiers;
case IntegerConstantToken:
case FloatingConstantToken:
case CharacterConstantToken:
case CharacterConstant_L_Token:
case CharacterConstant_u_Token:
case CharacterConstant_U_Token:
case ImaginaryIntegerConstantToken:
case ImaginaryFloatingConstantToken:
return Category::Constants;
case StringLiteralToken:
case StringLiteral_L_Token:
case StringLiteral_u8_Token:
case StringLiteral_u_Token:
case StringLiteral_U_Token:
case StringLiteral_R_Token:
case StringLiteral_LR_Token:
case StringLiteral_u8R_Token:
case StringLiteral_uR_Token:
case StringLiteral_UR_Token:
return Category::StringLiterals;
case EllipsisToken:
case OpenBraceToken:
case CloseBraceToken:
case OpenBracketToken:
case CloseBracketToken:
case OpenParenToken:
case CloseParenToken:
case HashToken:
case HashHashToken:
case SemicolonToken:
case ArrowToken:
case DotToken:
case PlusPlusToken:
case MinusMinusToken:
case AsteriskToken:
case AmpersandToken:
case PlusToken:
case MinusToken:
case TildeToken:
case SlashToken:
case PercentToken:
case LessThanLessThanToken:
case GreaterThanGreaterThanToken:
case BarToken:
case CaretToken:
case ExclamationToken:
case AmpersandAmpersandToken:
case BarBarToken:
case LessThanToken:
case LessThanEqualsToken:
case GreaterThanToken:
case GreaterThanEqualsToken:
case EqualsEqualsToken:
case ExclamationEqualsToken:
case ColonToken:
case QuestionToken:
case EqualsToken:
case AsteriskEqualsToken:
case SlashEqualsToken:
case PercentEqualsToken:
case PlusEqualsToken:
case MinusEqualsToken:
case LessThanLessThanEqualsToken:
case GreaterThanGreaterThanEqualsToken:
case AmpersandEqualsToken:
case CaretEqualsToken:
case BarEqualsToken:
case CommaToken:
return Category::Punctuators;
default:
if (k > STARTof_KeywordOrPunctuatorToken
&& k <= ENDof_KeywordOrPunctuatorToken)
return Category::Keywords;
return Category::Unrecognized;
}
}
SyntaxLexeme* SyntaxToken::valueLexeme() const
{
return lexeme_;
}
std::string SyntaxToken::valueText() const
{
return valueText_c_str();
}
const char* SyntaxToken::valueText_c_str() const
{
switch (rawSyntaxK_) {
case IdentifierToken:
case IntegerConstantToken:
case FloatingConstantToken:
case CharacterConstantToken:
case CharacterConstant_L_Token:
case CharacterConstant_u_Token:
case CharacterConstant_U_Token:
case ImaginaryIntegerConstantToken:
case ImaginaryFloatingConstantToken:
case StringLiteralToken:
case StringLiteral_L_Token:
case StringLiteral_u8_Token:
case StringLiteral_u_Token:
case StringLiteral_U_Token:
case StringLiteral_R_Token:
case StringLiteral_LR_Token:
case StringLiteral_u8R_Token:
case StringLiteral_uR_Token:
case StringLiteral_UR_Token:
return lexeme_->c_str();
default:
return tokenNames[rawSyntaxK_];
}
}
bool SyntaxToken::isValid() const
{
return tree_ != nullptr;
}
TextSpan SyntaxToken::span() const
{
return TextSpan(charStart(), charEnd());
}
SyntaxToken SyntaxToken::invalid()
{
return SyntaxToken(nullptr);
}
namespace psy {
namespace C {
bool operator==(const SyntaxToken& a, const SyntaxToken& b)
{
return a.tree_ == b.tree_
&& a.rawSyntaxK_ == b.rawSyntaxK_
&& a.byteOffset_ == b.byteOffset_
&& a.byteSize_ == b.byteSize_;
}
bool operator!=(const SyntaxToken& a, const SyntaxToken& b)
{
return !(a == b);
}
std::string to_string(SyntaxToken::Category category)
{
switch (category) {
case SyntaxToken::Category::Keywords:
return "[keywords]";
case SyntaxToken::Category::Identifiers:
return "[identifiers]";
case SyntaxToken::Category::Constants:
return "[constants]";
case SyntaxToken::Category::StringLiterals:
return "[string literals]";
case SyntaxToken::Category::Punctuators:
return "[punctuators]";
default:
return "[unrecognized]";
}
}
} // C
} // psy
|
a3f237577014df5187307c989c52930cd392b973
|
3f609d4009fdb13324ce2f8ae45dc2b81308a645
|
/include/Motor.h
|
0639d790bb0240a151797b5c9d32f57025dc3af6
|
[] |
no_license
|
milossekulic/Rent-A-Car
|
71c707f9b47652923fa172c431e2122185da16f4
|
4247f0d9985e3f27930fe24aecf6d6f6318b721d
|
refs/heads/main
| 2022-12-30T02:49:59.278616
| 2020-10-13T19:51:33
| 2020-10-13T19:51:33
| 303,813,233
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 256
|
h
|
Motor.h
|
#pragma once
#include"Automobil.h"
class Motor : public Vozilo {
private:
int ubrzanje;
public:
Motor(string nazivVozila, string markaVozila, int ubrzanje, int cenaIzdavanja);
int getUbrzanje();
void setUbrzanje();
};
|
b5391c32fc64fb41a3d9582fd0a26e8d2f3fcad3
|
a8aee5f44a2302da7109b456094b811e9b298b5d
|
/src/node_red.cpp
|
5dbaf188fa516e1d7c3d4c8bf1a448fed9a338b0
|
[] |
no_license
|
AlexandreRio/garden-watering
|
f7d986cc77d97b6f1e66b222cd47accfe73fcbe8
|
9818e92f7da15383c1f86fda984fe87c73a352c2
|
refs/heads/master
| 2022-04-22T01:01:59.294329
| 2020-04-26T15:34:08
| 2020-04-26T15:34:08
| 259,067,113
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,602
|
cpp
|
node_red.cpp
|
#include "node_red.h"
/**
* Water the plants for a given duration
* @param duration : Duration to water in second
*/
void water(unsigned long duration)
{
Serial.println("Begin to water");
digitalWrite(16, LOW);
digitalWrite(5, HIGH);
delay(duration*1000);
digitalWrite(16, HIGH);
digitalWrite(5, LOW);
Serial.println("Done watering");
}
/**
*
*/
String queryServer(const char* host, const int httpAction, const char* path, const char* param, const char* fingerprint)
{
WiFiClientSecure client;
Serial.print("Querying ");
Serial.println(host);
String line = "";
client.setFingerprint(fingerprint);
if (!client.connect(host, 443)) {
Serial.println("connection failed");
}
else {
String action;
if (httpAction == GET) { // yeah it should !httpAction
action = String("GET");
} else /* if (httpAction == 1)*/ {
action = String("POST");
}
Serial.println(action);
client.print(action + " /" + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: GardenMonitorESP8266\r\n" +
"X-Data: " + param + "\r\n"+
"Connection: close\r\n\r\n");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");
break;
}
}
line = client.readStringUntil('\n');
Serial.println("reply was:");
Serial.println("==========");
Serial.println(line);
Serial.println("==========");
Serial.println("closing connection");
}
return line;
}
|
b951b136c6369747d07a3683c1e4bee604b9b207
|
9cef10603a76280976732d899773efc5f72bbda6
|
/beaker/type.hpp
|
41e83d6dead7d19493764d5411d771f398b15c76
|
[
"Apache-2.0"
] |
permissive
|
thehexia/beaker
|
f02be601aa22d50cc55456ed9fe37606adee4630
|
ca6c563c51be4a08d78e4eda007967bc4ae812a2
|
refs/heads/master
| 2020-12-26T03:33:00.746911
| 2015-11-23T20:32:50
| 2015-11-23T20:32:50
| 45,311,808
| 0
| 0
| null | 2015-10-31T17:42:04
| 2015-10-31T17:42:04
| null |
UTF-8
|
C++
| false
| false
| 4,101
|
hpp
|
type.hpp
|
// Copyright (c) 2015 Andrew Sutton
// All rights reserved
#ifndef BEAKER_TYPE_HPP
#define BEAKER_TYPE_HPP
#include "prelude.hpp"
// The Type class represents the set of all types in the
// language.
//
// t ::= bool -- boolean type
// int -- integer type
// (t1, ..., tn) -> t -- function types
// ref t -- reference types
//
// Note that types are not mutable. Once created, a type
// cannot be changed. The reason for this is that we
// internally canonicalize (most) types when they are
// created.
//
// The "type" type (or kind) denotes the type user-defined
// types. Although it describes the higher-level kind
// system, we include it with the type system for
// convenience.
struct Type
{
struct Visitor;
virtual ~Type() { }
virtual void accept(Visitor&) const = 0;
virtual Type const* ref() const;
virtual Type const* nonref() const;
};
struct Type::Visitor
{
virtual void visit(Id_type const*) = 0;
virtual void visit(Boolean_type const*) = 0;
virtual void visit(Integer_type const*) = 0;
virtual void visit(Function_type const*) = 0;
virtual void visit(Reference_type const*) = 0;
virtual void visit(Record_type const*) = 0;
};
// A type named by an identifier. These are Essentially
// placeholders to be determined during initialization.
struct Id_type : Type
{
Id_type(Symbol const* s)
: sym_(s)
{ }
void accept(Visitor& v) const { v.visit(this); };
Symbol const* symbol() const { return sym_; }
Symbol const* sym_;
};
// The type bool.
struct Boolean_type : Type
{
void accept(Visitor& v) const { v.visit(this); };
};
// The type int.
struct Integer_type : Type
{
void accept(Visitor& v) const { v.visit(this); };
};
// Represents function types (t1, ..., tn) -> t.
struct Function_type : Type
{
Function_type(Type_seq const& t, Type const* r)
: first(t), second(r)
{ }
void accept(Visitor& v) const { v.visit(this); };
Type_seq const& parameter_types() const { return first; }
Type const* return_type() const { return second; }
Type_seq first;
Type const* second;
};
// The type of an expression that refers to an object.
struct Reference_type : Type
{
Reference_type(Type const* t)
: first(t)
{ }
void accept(Visitor& v) const { v.visit(this); };
virtual Type const* ref() const;
virtual Type const* nonref() const;
Type const* type() const { return first; }
Type const* first;
};
// A record type is the type introduced by a
// record declaration.
struct Record_type : Type
{
Record_type(Decl const* d)
: decl_(d)
{ }
void accept(Visitor& v) const { v.visit(this); };
Record_decl const* declaration() const;
Decl const* decl_;
};
// -------------------------------------------------------------------------- //
// Type accessors
Type const* get_type_kind();
Type const* get_id_type(Symbol const*);
Type const* get_boolean_type();
Type const* get_integer_type();
Type const* get_function_type(Type_seq const&, Type const*);
Type const* get_function_type(Decl_seq const&, Type const*);
Type const* get_reference_type(Type const*);
Type const* get_record_type(Record_decl const*);
// -------------------------------------------------------------------------- //
// Generic visitors
template<typename F, typename T>
struct Generic_type_visitor : Type::Visitor, lingo::Generic_visitor<F, T>
{
Generic_type_visitor(F fn)
: lingo::Generic_visitor<F, T>(fn)
{ }
void visit(Id_type const* t) { this->invoke(t); }
void visit(Boolean_type const* t) { this->invoke(t); }
void visit(Integer_type const* t) { this->invoke(t); }
void visit(Function_type const* t) { this->invoke(t); }
void visit(Reference_type const* t) { this->invoke(t); }
void visit(Record_type const* t) { this->invoke(t); }
};
template<typename F, typename T = typename std::result_of<F(Boolean_type const*)>::type>
inline T
apply(Type const* t, F fn)
{
Generic_type_visitor<F, T> v(fn);
return accept(t, v);
}
#endif
|
1a265ec5d1548a6bf29d434a07d4780ea8b84652
|
daa0e9d968884202e2d4cc6769a8a1fe060e5e84
|
/GfG_Codes_C++/Searching/11_Two_Pointer2.cpp
|
ca8f292fe6b333144d981da6c7e6ccf2ed6d8370
|
[] |
no_license
|
Ankit1dubey/Hacktoberfest-Accepted
|
03ecab59d10f934b8b5ed6f2d65c9a64692e2cff
|
cd2d8a55b7c62d8d56165a74e717ab4733bcdae7
|
refs/heads/main
| 2023-08-22T07:24:14.105087
| 2021-10-30T16:42:51
| 2021-10-30T16:42:51
| 422,935,434
| 2
| 0
| null | 2021-10-30T16:36:39
| 2021-10-30T16:36:39
| null |
UTF-8
|
C++
| false
| false
| 1,252
|
cpp
|
11_Two_Pointer2.cpp
|
#include <bits/stdc++.h>
using namespace std;
/* bool isPair(int arr[], int l, int r, int x)
{
while(l < r)
{
if(arr[l] + arr[r] == x)
return true;
else if(arr[l] + arr[r] > x)
r--;
else
l++;
}
return false;
}
bool find3Number(int arr[], int n, int x)
{
sort(arr, arr + n);
for(int i=0; i<n-2; i++)
{
if(isPair(arr, i+1, n-1, x-arr[i]))
return true;
}
return false;
} */
// also make this type of this function
bool find3Number(int arr[], int n, int x)
{
sort(arr, arr + n);
for (int i = 0; i < n - 2; i++)
{
int l = 0, r = n - 1;
while (l < r)
{
if (arr[i] + arr[l] + arr[r] == x)
{
cout << "Your Ans. is " << arr[i] << " + " << arr[l] << " + " << arr[r] << " = " << x << endl;
return true;
}
else if (arr[i] + arr[l] + arr[r] > x)
r--;
else
l++;
}
}
return false;
}
int main()
{
int arr[] = {1, 4, 45, 6, 10, 8};
int x = 22; // x = sum of numbers
int n = (sizeof(arr) / sizeof(arr[0]));
cout << find3Number(arr, n, x);
return 0;
}
|
415434cab61cd25da2bb75912d3562af4c028fb3
|
346c0fa613484c9561f8f409b8640b6027b27ec8
|
/Non_static_usual/include/maxmixture_factor.h
|
44ba71c42775c8892356e373a992d6f1b88f1267
|
[] |
no_license
|
CSautier/SLAM
|
e845a8ff1edd2662db2fe7033a865b01c5b3d703
|
da18e6a8446dd1d020ccdc45488026385418d53a
|
refs/heads/master
| 2020-05-24T17:17:44.430271
| 2019-05-18T16:29:16
| 2019-05-18T16:29:16
| 187,380,451
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,348
|
h
|
maxmixture_factor.h
|
/**
* Copyright 2019 Massachusetts Institute of Technology
*
* @file maxmixture_factor.h
* @author Kevin Doherty
*/
#pragma once
#include <vector>
#include <gtsam/nonlinear/NonlinearFactor.h>
#include <math.h>
#include <algorithm>
namespace maxmixture {
/**
* @brief GTSAM implementation of a max-mixture factor
*
* r(x) = min_i -log(w_i) + r_i(x)
*
* The error returned from this factor is the minimum error + weight
* over all of the component factors
* See Olson and Agarwal RSS 2012 for details
*/
template <class T>
class MaxMixtureFactor : public gtsam::NonlinearFactor {
private:
std::vector<T> factors_;
std::vector<double> log_weights_;
public:
using Base = gtsam::NonlinearFactor;
MaxMixtureFactor() = default;
explicit MaxMixtureFactor(const std::vector<T> factors,
const std::vector<double> weights) :
Base(factors[0].keys()) {
factors_ = factors;
for (int i = 0; i < weights.size(); i++) {
log_weights_.push_back(log(weights[i]));
}
}
MaxMixtureFactor& operator=(const MaxMixtureFactor& rhs) {
Base::operator=(rhs);
this->factors_ = rhs.factors_;
this->log_weights_ = rhs.log_weights_;
}
virtual ~MaxMixtureFactor() = default;
double error(const gtsam::Values& values) const override {
double min_error = std::numeric_limits<double>::infinity();
for (int i = 0; i < factors_.size(); i++) {
double error = factors_[i].error(values) - log_weights_[i];
if (error < min_error) {
min_error = error;
}
}
return min_error;
}
size_t dim() const override {
if (factors_.size() > 0) {
return factors_[0].dim();
}
else {
return 0;
}
}
boost::shared_ptr<gtsam::GaussianFactor> linearize(const gtsam::Values& x) const override {
double min_error = std::numeric_limits<double>::infinity();
int idx_min = -1;
for (int i = 0; i < factors_.size(); i++) {
double error = factors_[i].error(x) - log_weights_[i];
if (error < min_error) {
min_error = error;
idx_min = i;
}
}
return factors_[idx_min].linearize(x);
}
/* size_t dim() const override { return 1; } */
};
} // Namespace maxmixture
|
2a3b97dde96ffcc7d03a689dd25c4c61e0bb98f5
|
0e5e0239f8c0b7ccacc19fb746a046981952cc30
|
/Render.UWP/EnumDescriptionCoverter.cpp
|
df4e0667d085ff125d000a9699b82cf7fa8ec469
|
[] |
no_license
|
vivekbhadra/Computational-Finance
|
612948b003276f3b1e4cc7ff0e24850bc922b30c
|
b9f7103ccbdcc8a1971e32d8e1d83bf28aa10c7d
|
refs/heads/master
| 2023-03-20T06:51:29.602424
| 2018-12-30T15:36:01
| 2018-12-30T15:36:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 646
|
cpp
|
EnumDescriptionCoverter.cpp
|
#include "pch.h"
#include "EnumDescriptionCoverter.h"
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Globalization::NumberFormatting;
using namespace RenderEngine::Converters;
EnumDescriptionCoverter::EnumDescriptionCoverter()
{
}
EnumDescriptionCoverter::~EnumDescriptionCoverter()
{
}
Object^ EnumDescriptionCoverter::Convert(Object^ value, TypeName targetType, Object^ parameter, String^ language)
{
return 0;
}
Object^ EnumDescriptionCoverter::ConvertBack(Object^ value, TypeName targetType, Object^ parameter, String^ language)
{
return 0;
}
|
eff5dc2831cb06455c85708ee8291921b1889c93
|
27c2e2a0e336f8918bc3b42340c1931366306ce5
|
/plugins/agent_plan/Plan1.cpp
|
4d49b4b9309656a1255c24a82c929f326fcc22ef
|
[] |
no_license
|
jackbergus/socialsim
|
0da12fdabeef77dffbc19d76d57452ed9a5cc628
|
3dffa1c360eed9698934153d64a7f4cf80e17915
|
refs/heads/master
| 2016-09-06T05:40:51.804313
| 2014-07-14T12:18:53
| 2014-07-14T12:18:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,596
|
cpp
|
Plan1.cpp
|
/*
* Plan1.cpp
* This file is part of socialsim
*
* Copyright (C) 2014 - Giacomo Bergami, Elena Tea Russo
*
* socialsim is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* socialsim 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 socialsim; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#include "agent_plan.h"
#include <math.h>
#include <string>
#include <iostream>
#include <memory>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
class Plan1 : public Plan {
public:
Plan1() {}; //Costruttore base
std::string getName() { return "Plan1"; } //Nome del piano
//int process(json::Object* state, Message msg) <<--- XXX questa era la versione vecchia
int process(json::Object* state, Message msg,double NormalDistributionValue) { //Nome di *ogni* azione
std::cout << "In Plan1" << std::endl;
std::cout << "horror" << NormalDistributionValue << std::endl;
//Se nessuno ha inviato il messaggio, ma è quello di "inizio computazione"
if (msg.getAgentSender() == nullptr) {
std::cout << "NULL" <<std::endl;
//Semplicemente inoltro il mio stato
doSend(state,0);
//Esco dal ragionamento
return 50;
}
//Ottiene l'opinione su di un determinato tipo di argomento, sul tipo del messaggio
double opinion = getOpinionType(state,msg.getType());
//Ottengo l'opinione del mittente sull'argomento
double op_msg = msg.getOpinion();
//Ottengo il valore della plagiabilità
double plagiability = getPlagiability(state);
// Introduco l'errore per la valutazione
std::cout << "valerror=" << NormalDistributionValue << std::endl; // Già corretto prima
//Valutazione
double valutation;
double reputation = getSenderReputation(state,msg);
double rad=0;
std::cout << "RADICANDO: " << 0.5 << "*(1-" << abs(op_msg-opinion) << "+"<< reputation <<") +" << NormalDistributionValue << std::endl;
rad=0.5*(1 - abs(op_msg-opinion) + reputation) + NormalDistributionValue ;
if(rad>=1.) rad=1.;
if(rad<=0) rad=0;
valutation= sqrt( rad );
std::cout << "VALUTATION : " << valutation << std::endl;
//modifica dell'opinione nello stato interno
std::cout << "OPINION +=:(( " << op_msg << "-" << opinion << ")*" << plagiability << "*" << "*" << valutation << std::endl;
opinion += ((op_msg - opinion)* plagiability *valutation);
std::cout << "New Opinion: " << opinion << std::endl;
std::cout << "Reputation: " << reputation << std::endl;
setOpinionType(state,msg.getType(),opinion);
//mando un messaggio di tipo prefissato
//Con questo comando però non invio ancora il messaggio,
//questo verrà veramente inviato solamente alla fine del
//processo di ragionamento
doSend(state,msg.getType());
//Per non inviare un messaggio: notSend(state)
return 50; //Salto al piano in posizione 50 dalla corrente (andando in avanti o indietro)
};
};
MAKE_PLUGIN(Plan1,Plan); //Creazione di un plugin
|
ce0fd2083bb0ec1dd3bbe3ff4cf1cdee57686036
|
2c5c5d92271e15cc203b999a7078496072277839
|
/SDS011_DHTxx/SDS011_DHTxx.ino
|
01b6fa48aee14d58371abc4dbd3f4467a8f0e84f
|
[] |
no_license
|
Colkerr/Mobile-Air-Sensor
|
7473126ce8124c4060002a7ff39f1d26fc7bc6c7
|
1e91ee566a0c80727e1d287218fbbc7d0fb99191
|
refs/heads/master
| 2020-06-26T16:31:51.718216
| 2019-08-20T16:28:11
| 2019-08-20T16:28:11
| 199,686,149
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,853
|
ino
|
SDS011_DHTxx.ino
|
//Save sensor readings to flash memory until reboot when broadcast wifi to allow ftp, deletion and date/time input
//Using Deep Sleep so wakes evey time into setup() and any only persistence is by using RTC memory
#define Sensor_User "sensor_user" //<<<<<<<<<<<<<<<<<<< NOTE change these and possibly others below <<<<<<<<<<
#define Sensor_Password "password" //>>>> WARNING password may have to be at least 8 characters or WiFI.softAP(..) fails.
#define DHTTYPE DHT11
int iCycleSecs=60; //value input on set up and stored in EEPROM
int iWarmUpSecs=30; // ditto
long waitForSetUp = 2 * 60 * 1000; // time out wait for setup
long extendWaitForSetUp = 20 * 60 * 1000; // once setup started extend to 20 minutes
int rxPin = D5; // SDS011 sensor pins on Nodemcu
int txPin = D6;
int DHTPin = D7; // pin for temp/humidity
//------------------above may need to be changed especially Sensor_User and Sensor_Password
extern "C" { // this is for the RTC memory read/write functions
#include "user_interface.h"
}
typedef struct { // this is for the RTC memory read/write functions
char cycleState; //?=begin, 1=warm up, 2=rest (cycle-warmup)
byte fixTime; //units of 0.1%
char spare[3]; //make up to 4 bytes
int iYr; //4 bytes
int iMnth;
int iDay;
int iHr;
int iMin;
int iSec;
int timings[2]; //Cycle time and warm up time in seconds
} rtcStore;
rtcStore rtcMem;
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <FS.h> // Include the SPIFFS library
#include <EEPROM.h>
#include "ESP8266FtpServer.h"
#include "SdsDustSensor.h"
#include "DHT.h"
DHT dht(DHTPin, DHTTYPE);
SdsDustSensor sds(rxPin, txPin);
int Temperature;
int Humidity;
ESP8266WebServer server(80); // Create a webserver object that listens for HTTP request on port 80
FtpServer ftpSrv;
bool handleFileRead(String path); // send the right file to the client (if it exists)
unsigned long previousMillis = 0;
String fname = "SensorFile";
void setup() {
Serial.begin(57600);
EEPROM.begin(3);
system_rtc_mem_read(64, &rtcMem, sizeof(rtcMem)); //all variables lost after sleep, restore from RTC memory
byte checkcyclestate=rtcMem.cycleState;
if (rtcMem.cycleState=='1') { //>>>>>>>>>>>>>Start WARM UP then sleep<<<<<<<<<<<<<
Serial.println("state 1, Warm up ");
sds.wakeup();
rtcMem.cycleState='2';
system_rtc_mem_write(64, &rtcMem, sizeof(rtcMem));
Serial.println("SLEEP state 1");
delay(100);
ESP.deepSleep(rtcMem.timings[1] * 1e6, WAKE_RF_DISABLED); //sleep for warm up seconds
} else if (rtcMem.cycleState=='2') { //>>>>>>>>>>>>>READ SENSORS THEN SLEEP<<<<<<<<<<<<<
pinMode(DHTPin, INPUT);
sds.begin();
Serial.println(sds.setQueryReportingMode().toString()); // ensures sensor is in 'query' reporting mode
Serial.println("state 2, read sensors ");
rtcMem.cycleState='1'; //next state
readSensors(); //and save data to SPIFFS
long adjustedCycle= ( 1e6 + 1000*(rtcMem.fixTime-100) ) * rtcMem.timings[0]; //fixTime in 0.1% units
maintainClock(adjustedCycle);
system_rtc_mem_write(64, &rtcMem, sizeof(rtcMem));
Serial.println(" Sleep until state 1");
ESP.deepSleep( adjustedCycle - ( rtcMem.timings[1] ) * 1e6, WAKE_RF_DISABLED); //sleep remainder of cycle
} else {
delay(3000);
Serial.println("Initialise start up -> setup ");
rtcMem.timings[0]=EEPROM.read(0);
rtcMem.timings[1]=EEPROM.read(1);
delay(100);
WiFi.begin();
WiFi.forceSleepWake();
Serial.println("wifi started");
if (!WiFi.softAP(Sensor_User, Sensor_Password)) {Serial.println("false returned from WiFi.softAP() "); } // Start the access point
Serial.print("Access Point started IP adress = ");
Serial.println(WiFi.softAPIP()); // Show IP address
sds.begin();
if (SPIFFS.begin()) {
Serial.println("SPIFFS opened!");
saveRecord("YYYY-MM-DD hh:mm,Temp,Humid,PM2.5,PM10"); //heading and mark file if rebooted without set up
ftpSrv.begin(Sensor_User, Sensor_Password); // port 21
}
server.on("/setup", showSetup);
server.on("/setuptimes", setCycleTimes);
server.on("/setupclockadjust", setClockAdjust);
server.on("/set_date_time", setDateTime);
server.on("/delete_all_records", deleteAllRecords);
server.onNotFound([]() { // If the client requests any URI
if (!handleFileRead(server.uri())) // send it if it exists
server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error
});
server.begin();
Serial.println("HTTP server started");
delay(10);
}
}
//only here when power off reboot until set up completed or times out and reverts to logging
//broadcast wifi, handle FTP and server Clients
void loop(void) {
if ( millis() > waitForSetUp ) {
Serial.println("End of wait time"); //start cycling
rtcMem.cycleState='1'; //next state
readSensors(); //and save data to SPIFFS
long adjustedCycle= ( 1e6 + 1000*(rtcMem.fixTime-100) ) * rtcMem.timings[0]; //fixTime in 0.1% units
rtcMem.iYr=0;rtcMem.iMnth=0;rtcMem.iDay=0;rtcMem.iHr=0;rtcMem.iMin=0;rtcMem.iSec=0; //default when not set explicitly
system_rtc_mem_write(64, &rtcMem, sizeof(rtcMem));
WiFi.mode(WIFI_OFF);
Serial.println(" Sleep until state 1");
delay(10);
ESP.deepSleep( adjustedCycle - ( rtcMem.timings[1] ) * 1e6, WAKE_RF_DISABLED); //sleep remainder of cycle
} else {
ftpSrv.handleFTP();
server.handleClient();
}
delay(10);
}
String readSensors() { //and save to file
dht.begin();
Serial.println("read the sensors");
PmResult pm = sds.queryPm();
if (pm.isOk()) {
Serial.print("PM2.5 = " + String(pm.pm25) );
Serial.print(", PM10 = " + String(pm.pm10) );
} else {
Serial.println("Sensor problem, reason: " + pm.statusToString());
}
Temperature = dht.readTemperature();
Humidity = dht.readHumidity();
String output = sFormInt(rtcMem.iYr,4,'0') + "-" + sFormInt(rtcMem.iMnth, 2, '0') + "-" + sFormInt(rtcMem.iDay, 2, '0');
output = output + " " + sFormInt(rtcMem.iHr, 2, '0') + ":" + sFormInt(rtcMem.iMin, 2, '0') + ":" + sFormInt(rtcMem.iSec, 2, '0');
output = output + "," + String(Temperature) + "," + String(Humidity) + "," + String(pm.pm25) + "," + String(pm.pm10);
sds.sleep();
Serial.println(output);
saveRecord(output);
return(output); // for html if called from setDateTime()
}
void showSetup() {
waitForSetUp = extendWaitForSetUp; //must be intended restart so allow longer
server.send(200, "text/html", "<h1>SETUP</h1>"
"Logging will commence immediately the date is set or the later of "
"<br> >>> 2 minutes after boot-up."
"<br> >>> 20 minutes from this screen opening."
"<br> >>> Only submit 1) & 2) if changing values."
"<br><br>"
"1) Cycle and warm up times (secs): "
"<form method='post' action='/setuptimes'/> "
" <input type='number' name='CycleTime' min='15' max='255' size='3' value='" + String(EEPROM.read(0)) + "'/>"
" <input type='number' name='WarmUp' min='5' max='30' size='3' value='" + String( EEPROM.read(1)) + "'/>"
" <input type='submit' value='Submit' /> </form> "
"2) Adjust clock in ( units of 0.1% ): "
"<form method='post' action='/setupclockadjust'/> "
" <input type='number' name='ClockAdjust' min= '-100' max= '100' size='3' value='" + String( EEPROM.read(2) - 100 ) + "'/>"
" <input type='submit' value='Submit' /> </form> "
"3) Complete File Transfer. <br><br>"
"4) Delete existing records. <br>"
"<form method='post' name='delete' action='/delete_all_records'>"
"<p><input type='submit' value='Delete All Records' />"
"</form>"
"5) Set the Date & Time and show first record. <br>"
"<form method='post' name='frm' action='/set_date_time'> "
"<p><input type='submit' value='Set Date & Time' /> "
"<input type='text' name='product' size='45' /> "
"</form> <br> "
"<script>document.frm.product.value=Date(); </script>"
);
}
void setCycleTimes() {
rtcMem.timings[0] = server.arg(0).toInt(); //complete cycle in seconds
rtcMem.timings[1] = server.arg(1).toInt(); //warmup in seconds
Serial.println(String(iCycleSecs) + " " + String(iWarmUpSecs)) ;
if ( EEPROM.read(0)!=rtcMem.timings[0] ) EEPROM.write(0, rtcMem.timings[0]); //store for reboot on power outage
if ( EEPROM.read(1)!=rtcMem.timings[1] ) EEPROM.write(1, rtcMem.timings[1]);
EEPROM.commit();
showSetup();
}
void setClockAdjust() {
rtcMem.fixTime= server.arg(0).toInt() + 100 ;
Serial.print("fix time " );Serial.println(rtcMem.fixTime);
EEPROM.write(2, rtcMem.fixTime);
Serial.println(EEPROM.read(2));
EEPROM.commit();
showSetup();
}
void setDateTime() {
String message = server.arg(0) + "\n";
Serial.println(message);
rtcMem.iMnth = month2Number(message.substring(4, 7));
rtcMem.iYr = message.substring(11, 15).toInt();
rtcMem.iDay = message.substring(8, 10).toInt();
rtcMem.iHr = message.substring(16, 18).toInt();
rtcMem.iMin = message.substring(19, 21).toInt();
rtcMem.iSec = message.substring(22, 24).toInt();
//readSensors in following statement will also save first reacord to file
server.send(200, "text/html", "Date & Time is " + sFormInt(rtcMem.iYr, 4, '0') + "/" + sFormInt(rtcMem.iMnth, 2, '0') + "/" + sFormInt(rtcMem.iDay, 2, '0') +
" " + sFormInt(rtcMem.iHr, 2, '0') + ":" + sFormInt(rtcMem.iMin, 2, '0') + ":" + sFormInt(rtcMem.iSec, 2, '0') +
"<br>First record = " + readSensors() + "<br>"
"<h3>Sensor logging starts now. </h3>"
);
delay(100);
rtcMem.cycleState='1';
system_rtc_mem_write(64, &rtcMem, sizeof(rtcMem));
Serial.print("SLEEP after set date time ");
Serial.println(rtcMem.timings[1]);
delay(100);
ESP.deepSleep(rtcMem.timings[1] * 1e6, WAKE_RF_DISABLED); //sleep for remainder of cycle
}
void maintainClock(long adjustedCycle) {
rtcMem.iSec += adjustedCycle;
if (rtcMem.iSec >=60) {
rtcMem.iSec=rtcMem.iSec % 60;
if (++rtcMem.iMin >= 60) {
rtcMem.iMin = 0;
if (++rtcMem.iHr >= 24) {
rtcMem.iHr = 0;
if (++rtcMem.iDay > daysInMonth(rtcMem.iYr,rtcMem.iDay,rtcMem.iMnth)) {
rtcMem.iDay = 0;
if (rtcMem.iDay==31 && rtcMem.iMnth==12) {
++rtcMem.iYr;
}
}
}
}
}
}
void deleteAllRecords() { // When URI / is requested, send a web page with a button to toggle the LED
bool deleteStatus = true;
Serial.println("handle delete");
Dir dir = SPIFFS.openDir("/");
while (dir.next()) {
String fname = dir.fileName();
Serial.print(fname + " ");
File f = dir.openFile("r");
Serial.println(f.size());
f.close();
deleteStatus = deleteStatus && SPIFFS.remove(fname);
}
saveRecord("YYYY-MM-DD hh:mm,Temp,Humid,PM2.5,PM10"); //heading
server.send(200, "text/html", "<h2>Data has " + String(deleteStatus ? " " : "NOT " ) + "been deleted.</h2> <h3><a href='/setup'>Return</a></h3>" );
}
void saveRecord(String output) {
if (SPIFFS.begin() ) {
File sensorData = SPIFFS.open("/" + fname + ".csv", "a");
if (!sensorData) {
Serial.println("file open failed");
} else {
sensorData.println(output);
delay(100);
Serial.println("written to file ");
sensorData.close();
}
} else {
Serial.println("SPIFFS begin failed");
}
}
bool handleFileRead(String path) { // send the right file to the client (if it exists)
Serial.println("handleFileRead: " + path);
// if (path.endsWith("/")) path += "index.html"; // If a folder is requested, send the index file
// String contentType = getContentType(path); // Get the MIME type
if (SPIFFS.exists(path)) { // If the file exists
Serial.println("file exists");
File file = SPIFFS.open(path, "r"); // Open it
size_t sent = server.streamFile(file, "text/plain"); // And send it to the client
file.close(); // Then close the file again
return true;
}
Serial.println("\tFile Not Found");
return false; // If the file doesn't exist, return false
}
int month2Number(String sMonth) {
String sMonths[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int i = 0;
while (sMonths[i] != sMonth) {
i += 1;
}
return i + 1;
}
int daysInMonth(int iYr,int iMnth, int iDay) {
int daysInMonths[12] = {31, 28, 31, 30, 31, 30, 31, 30, 31, 31, 30, 31};
int numDays = daysInMonths[iMnth - 1];
if (iMnth = 2) {
if (iYr % 4 == 0) {
if (iYr % 100 != 0) {
numDays = 29;
} else {
if (iYr % 400 == 0) {
numDays = 29;
}
}
}
}
return numDays;
}
//////////////////////Format integer
String sFormInt(int n, int i, char sP) { //n to be formatted as i digits, leading sP
String sN = String(n);
int j = i - sN.length();
for (int k = 0; k < j; k++) {
sN = sP + sN;
}
return sN;
}
|
396789e33fcd2bcbf91124064d825c406cc973c6
|
34b228253c19b156af54ed332daab7a24c20daf0
|
/CString/CString.cpp
|
247fa0d77ba0472b39b13c787073000f8ee96168
|
[] |
no_license
|
xTCry/CString
|
83b35ed6275236f1da1eb4ffc4fa90b019db7524
|
641570f8103aae568a564e58a382cfc68883a4e0
|
refs/heads/master
| 2023-01-11T22:37:15.532742
| 2020-11-18T10:02:38
| 2020-11-18T10:02:38
| 313,891,149
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,243
|
cpp
|
CString.cpp
|
#include "CString.h"
CString::CString() : pStr(new char[1]) {
pStr[0] = '\0';
}
CString::CString(char* str) {
pStr = new char[strlen(str) + 1];
if (str == nullptr) {
pStr[0] = '\0';
}
else {
// копируем символы в pStr из str[] используя strcpy_s
strcpy_s(pStr, strlen(str) + 1, str);
}
}
int CString::getLength() {
return strlen(pStr);
}
CString::CString(CString&& source) {
pStr = source.pStr;
source.pStr = nullptr;
}
CString::CString(const CString& source) {
// копируем строку из источника
pStr = new char[strlen(source.pStr) + 1];
strcpy_s(pStr, strlen(source.pStr) + 1, source.pStr);
}
char* CString::GetCopy() {
// если строки нету, то возвращаем пустую строку
if (pStr == nullptr) {
return new char[] {'\0'};
}
// создаем копию строки и возвращаем её
char* ret = new char[strlen(pStr) + 1];
strcpy_s(ret, strlen(pStr) + 1, pStr);
return ret;
}
CString& CString::operator=(const CString& rhs) {
// если текущий экземпляр класса эквивалентен правому классу,
// то возвращаем обратно указатель на это же экземпляр класса
if (this == &rhs) {
return *this;
}
// удаляем текущую строку
delete[] pStr;
// копируем содержимое из правой части в текущий экземпляр класса
pStr = new char[strlen(rhs.pStr) + 1];
strcpy_s(pStr, strlen(rhs.pStr) + 1, rhs.pStr);
// возвращаем обратно указатель на это же экземпляр класса
return *this;
}
CString& CString::operator=(const char*& rhs) {
// если строки эквивалентны,
// то возвращаем обратно указатель на это же экземпляр класса
if (strcmp(this->GetCopy(), rhs) == 0) {
return *this;
}
// удаляем текущую строку
delete[] pStr;
// копируем содержимое из правой части в текущий экземпляр класса
pStr = new char[strlen(rhs) + 1];
strcpy_s(pStr, strlen(rhs) + 1, rhs);
// возвращаем обратно указатель на это же экземпляр класса
return *this;
}
// Переопределение оператора записи потока
std::istream& operator>>(std::istream& is, CString& obj) {
/// А) железно выделим 1Кб для записи (не практично)
/*
char* buff = new char[1024];
// Записываем из потока в буфер
is >> buff;
// устанавливаем для obj новый экземпляр класса с buff[]
obj = CString{ buff };
// удаляем временный buff[]
delete[] buff;
*/
/// Б) автоматически выделять память (тоже не особо практично - нужен алгоритм...)
int size = 1;
// выделяем память для строки в 1 символ
char* buff = (char*)malloc(size);
// поулчаем символы из потока
// и по нажатию на Enter (\n) ввод завершается
for (char ch; is.get(ch) && ch != '\n';) {
buff[size - 1] = ch;
// увеличиваем размер буффера для нового символа
buff = (char*)realloc(buff, ++size);
}
// если символы были введены,
// то устанавливаем экземпляр класса с новой строкой
if (size > 1) {
buff[size - 1] = '\0';
obj = CString{ buff };
}
// удаляем временный buff[]
delete[] buff;
return is;
}
// Переопределение оператора вывода потока
std::ostream& operator<<(std::ostream& os, const CString& obj) {
// выводим содержимое строки в поток
os << obj.pStr;
return os;
}
CString operator+(const CString& lhs, const CString& rhs) {
// длина новой строки
int length = strlen(lhs.pStr) + strlen(rhs.pStr);
char* buff = new char[length + 1];
// копируем левую строку в buff[]
strcpy_s(buff, length + 1, lhs.pStr);
// дописываем правую строку в buff[]
strcat_s(buff, length + 1, rhs.pStr);
// создаем временный класс для возврата с buff[]
CString temp{ buff };
// удаляем временный buff[]
delete[] buff;
// возвращаем класс с объединенными строками
return temp;
}
CString& CString::WriteToFile(std::string path) {
std::ofstream writer(path, std::ios::out);
//writer.write(reinterpret_cast<char*>(pStr), getLength());
writer << pStr;
writer.close();
return *this;
}
CString& CString::ReadFromFile(std::string path) {
/*std::ifstream in(path);
if (!in) {
std::cout << "Cannot open input file\n";
return *this;
}
int fsize = 1024;
char* buff = (char*)malloc(fsize + 1);
fread(string, fsize, 1, in);
fclose(f);
in.close();*/
// Открываем файл
FILE* file;
if (fopen_s(&file, path.c_str(), "rb") != 0) {
std::cout << "Cannot open input file\n";
return *this;
}
// Переходим в конец файла
fseek(file, 0, SEEK_END);
// Получаем длину строки файла
long length = ftell(file);
// Возвращаем курсор в начало файла
fseek(file, 0, SEEK_SET);
// Выделяем память для буфера с нужным размером
char* buff = (char*)malloc(length + 1);
fread(buff, length, 1, file);
fclose(file);
buff[length] = 0;
pStr = buff;
return *this;
}
|
dab318543d2c7fdbc2fbc792c1812d34c141ed18
|
bc7651210ee5a59ba79f95e038185fe235418c4f
|
/um+younghan.cpp
|
6bfd7368314869e7f65516a13d98853e2e74fcc1
|
[] |
no_license
|
seoyh0812/TeamLaunge2
|
3f81b2eed4ee32c771d979e77c84fdd6b9e6080f
|
e1498ee31dde3cfc8e853ca97f273b390551f009
|
refs/heads/master
| 2023-03-21T09:38:27.688056
| 2021-03-22T01:11:02
| 2021-03-22T01:11:02
| 332,584,817
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 85
|
cpp
|
um+younghan.cpp
|
#include "stdafx.h"
#include "unitManager.h"
void unitManager::younghanUpdate()
{
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.