text
stringlengths 8
6.88M
|
|---|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WNTCONCENTRATION_HPP_
#define WNTCONCENTRATION_HPP_
#include "ChasteSerialization.hpp"
#include "SerializableSingleton.hpp"
#include <boost/serialization/base_object.hpp>
#include <iostream>
#include "AbstractCellPopulation.hpp"
/**
* Possible types of WntConcentration, currently:
* NONE - for testing and to remove Wnt dependence
* LINEAR - for cylindrical crypt model
* RADIAL - for crypt projection model
*/
typedef enum WntConcentrationType_
{
NONE,
LINEAR,
RADIAL,
EXPONENTIAL
} WntConcentrationType;
/**
* Singleton Wnt concentration object.
*/
template<unsigned DIM>
class WntConcentration : public SerializableSingleton<WntConcentration<DIM> >
{
private:
/** Pointer to the singleton instance of WntConcentration */
static WntConcentration* mpInstance;
/**
* The length of the crypt.
*/
double mCryptLength;
/**
* Whether this WntConcentration object has had its crypt length set.
*/
bool mLengthSet;
/**
* The type of WntConcentration current options are
* NONE - returns zero everywhere
* LINEAR - decreases from 1 to zero at height specified by mWntConcentrationParameter
* RADIAL - decreases from 1 to zero at height specified by mWntConcentrationParameter
*/
WntConcentrationType mWntType;
/**
* The cell population in which the WntConcentration occurs.
*/
AbstractCellPopulation<DIM>* mpCellPopulation;
/**
* Whether this WntConcentration object has had its type set.
*/
bool mTypeSet;
/**
* A value to return for testing purposes.
*/
double mConstantWntValueForTesting;
/**
* Whether to return the testing value
* (when false WntConcentration works with CellPopulation).
*/
bool mUseConstantWntValueForTesting;
/**
* For LINEAR or RADIAL Wnt type:
* The proportion of the crypt that has a Wnt gradient.
* The Wnt concentration goes from one at the base to zero at this height up the crypt.
*
* For EXPONENTIAL Wnt type:
* The parameter lambda in the Wnt concentration
* Wnt = exp(-height/lambda)
*/
double mWntConcentrationParameter;
/**
* Parameter a, for use in crypt projection simulations, in which the crypt
* surface is given in cylindrical polar coordinates by z = a*r^b.
* mCryptProjectionParameterA has no units
*/
double mCryptProjectionParameterA;
/**
* Parameter b, for use in crypt projection simulations, in which the crypt
* surface is given in cylindrical polar coordinates by z = a*r^b.
* mCryptProjectionParameterB has no units
*/
double mCryptProjectionParameterB;
/** Needed for serialization. */
friend class boost::serialization::access;
/**
* Archive the object and its member variables.
*
* @param archive the archive
* @param version the current version of this class
*/
template<class Archive>
void serialize(Archive & archive, const unsigned int version)
{
bool is_set_up = IsWntSetUp();
archive & is_set_up;
if (is_set_up)
{
archive & mCryptLength;
archive & mLengthSet;
archive & mWntType;
archive & mpCellPopulation;
archive & mTypeSet;
archive & mConstantWntValueForTesting;
archive & mUseConstantWntValueForTesting;
archive & mWntConcentrationParameter;
archive & mCryptProjectionParameterA;
archive & mCryptProjectionParameterB;
}
}
protected:
/**
* Protected constuctor. Not to be called, use Instance() instead.
*/
WntConcentration();
public:
/**
* Return a pointer to the WntConcentration object.
* The first time this is called, the object is created.
*
* @return A pointer to the singleton WntConcentration object.
*/
static WntConcentration* Instance();
/**
* Destructor - frees up the singleton instance.
*/
virtual ~WntConcentration();
/**
* Destroy the current WntConcentration instance.
* Should be called at the end of a simulation.
*/
static void Destroy();
/**
* Get the Wnt level at a given height in the crypt.
*
* @param height the height of the cell at which we want the Wnt concentration
* @return the Wnt concentration at this height in the crypt (dimensionless)
*/
double GetWntLevel(double height);
/**
* Get the Wnt level at a given cell in the crypt. The crypt
* must be set for this.
*
* @param pCell the cell at which we want the Wnt concentration
* @return the Wnt concentration at this cell
*/
double GetWntLevel(CellPtr pCell);
/**
* @return the Wnt gradient at a given location in the crypt.
*
* @param rLocation the location at which we want the Wnt gradient
*/
c_vector<double, DIM> GetWntGradient(c_vector<double, DIM>& rLocation);
/**
* @return the Wnt gradient at a given cell in the crypt.
*
* @param pCell the cell at which we want the Wnt gradient
*/
c_vector<double, DIM> GetWntGradient(CellPtr pCell);
/**
* Set the crypt. Must be called before GetWntLevel().
*
* @param rCellPopulation reference to the cell population
*/
void SetCellPopulation(AbstractCellPopulation<DIM>& rCellPopulation);
/**
* @return reference to the CellPopulation.
*/
AbstractCellPopulation<DIM>& rGetCellPopulation();
/**
* @return mCryptLength
*/
double GetCryptLength();
/**
* Set mCryptLength. Must be called before GetWntLevel().
*
* @param cryptLength the new value of mCryptLength
*/
void SetCryptLength(double cryptLength);
/**
* @return the type of Wnt concentration.
*/
WntConcentrationType GetType();
/**
* Set the type of Wnt concentration. Must be called before GetWntLevel().
*
* @param type the type of Wnt concentration
*/
void SetType(WntConcentrationType type);
/**
* Force the Wnt concentration to return a given value for all cells.
* Only for testing.
*
* @param value the constant value to set the Wnt concentration to be
*/
void SetConstantWntValueForTesting(double value);
/**
* Whether a Wnt concentration has been set up.
*
* For archiving, and to let a CellBasedSimulation
* find out whether whether a WntConcentration has
* been set up or not, i.e. whether stem cells should
* be motile.
*
* @return whether the Wnt concentration is set up
*/
bool IsWntSetUp();
/**
* @return mWntConcentrationParameter
*/
double GetWntConcentrationParameter();
/**
* Set mWntConcentrationParameter.
*
* @param wntConcentrationParameter the new value of mWntConcentrationParameter
*/
void SetWntConcentrationParameter(double wntConcentrationParameter);
/**
* @return mCryptProjectionParameterA
*/
double GetCryptProjectionParameterA();
/**
* @return mCryptProjectionParameterB
*/
double GetCryptProjectionParameterB();
/**
* Set mCryptProjectionParameterA.
*
* @param cryptProjectionParameterA the new value of mCryptProjectionParameterA
*/
void SetCryptProjectionParameterA(double cryptProjectionParameterA);
/**
* Set mCryptProjectionParameterB.
*
* @param cryptProjectionParameterB the new value of mCryptProjectionParameterB
*/
void SetCryptProjectionParameterB(double cryptProjectionParameterB);
};
#endif /*WNTCONCENTRATION_HPP_*/
|
# include <stdio.h>
# define WEIGHT_A 2
# define WEIGHT_B 3
# define WEIGHT_C 5
int main() {
float A, B, C, avg;
scanf("%f", &A);
scanf("%f", &B);
scanf("%f", &C);
avg = (A * WEIGHT_A + B * WEIGHT_B + C * WEIGHT_C) / (WEIGHT_A + WEIGHT_B + WEIGHT_C);
printf("MEDIA = %.1f\n", avg);
return 0;
}
|
#include <iostream>
#include <iomanip>
float y, x, l[6],t = 0.5; int n;
using namespace std;
int main()
{
setlocale(LC_CTYPE, "Russian");
for (n = 0; n <= 4;n++)
{
printf("Введите x%i: ", n); cin >> x;
l[n] = x;
}
cout << endl;
n = 0;
for (t; t <= 3; t+=0.5)
{
if (t > 2)
{
for (n; n <= 5; n++)
{
y = pow(l[n], 2) + t;
printf("y="); cout << y << endl;
}
cout << endl;
n = 0;
}
if (t <= 2)
{
for (n; n <= 5; n++)
{
y = cos(l[n]);
printf("y="); cout << y << endl;
}
cout << endl;
n = 0;
}
}
}
|
#include <type_traits>
#include <limits>
#include <gtest/gtest.h>
#include <libndgpp/type_traits/char_numeric_type.hpp>
TEST(unsigned_char_type, test)
{
using type = ndgpp::char_numeric_type<unsigned char>::type;
constexpr bool is_same = std::is_same<type, unsigned short>::value;
EXPECT_TRUE(is_same);
}
TEST(signed_char_type, test)
{
using type = ndgpp::char_numeric_type<signed char>::type;
constexpr bool is_same = std::is_same<type, signed short>::value;
EXPECT_TRUE(is_same);
}
TEST(char_type, test)
{
using type = ndgpp::char_numeric_type<char>::type;
constexpr bool is_signed = std::numeric_limits<char>::is_signed;
if (is_signed)
{
constexpr bool is_same = std::is_same<type, signed short>::value;
EXPECT_TRUE(is_same);
}
else
{
constexpr bool is_same = std::is_same<type, unsigned short>::value;
EXPECT_TRUE(is_same);
}
}
|
// TrafficLightDetectionDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "TrafficLightDetection.h"
#include "TrafficLightDetectionDlg.h"
#include "afxdialogex.h"
#include <atlconv.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CTrafficLightDetectionDlg 对话框
CTrafficLightDetectionDlg::CTrafficLightDetectionDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CTrafficLightDetectionDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CTrafficLightDetectionDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
//DDX_Control(pDX, IDC_LIST_DisplayInfo, m_list_DisplayInfo);
DDX_Control(pDX, IDC_LIST_DisplayInfo, m_List_DisplayInfo);
DDX_Control(pDX, IDC_STATIC_ShowImg, m_ShowImg);
DDX_Control(pDX, IDC_STATIC_ShowResultImg, m_DisplayImg);
}
BEGIN_MESSAGE_MAP(CTrafficLightDetectionDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUT_LoadImg, &CTrafficLightDetectionDlg::OnBnClickedButLoadimg)
ON_BN_CLICKED(IDC_BUT_Locate, &CTrafficLightDetectionDlg::OnBnClickedButLocate)
ON_BN_CLICKED(IDC_BUT_Recongnize, &CTrafficLightDetectionDlg::OnBnClickedButRecongnize)
ON_BN_CLICKED(IDC_BUT_UpdateTemplate, &CTrafficLightDetectionDlg::OnBnClickedButUpdatetemplate)
ON_BN_CLICKED(IDC_BUT_Update, &CTrafficLightDetectionDlg::OnBnClickedButUpdate)
ON_BN_CLICKED(IDC_BUT_NEXT, &CTrafficLightDetectionDlg::OnBnClickedButNext)
ON_MESSAGE(WM_SendRect, GetRect)
END_MESSAGE_MAP()
// CTrafficLightDetectionDlg 消息处理程序
BOOL CTrafficLightDetectionDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
m_fileNum = 0;
GetDlgItem(IDC_BUT_NEXT)->ShowWindow(false);
m_bLoatTemplate = false;
CFileFind find;
BOOL isFinded = find.FindFile(_T("templateMat.xml"));
if (isFinded){
FileStorage fs(".\\templateMat.xml", FileStorage::READ);
fs["templateMat"] >> m_templateMat;
}
LPWSTR szColumn[5] = { _T("编号"), _T("图像路径"), _T("输出检测矩形框"), _T("信号灯颜色"), _T("时间") };
m_List_DisplayInfo.SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
LV_COLUMN lvc;
lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
lvc.fmt = LVCFMT_LEFT;
for (int i = 0; i < 5; i++) //插入各列
{
lvc.pszText = szColumn[i];
if (i == 0)
lvc.cx = m_List_DisplayInfo.GetStringWidth(szColumn[0]) + 50; //获取列的宽度
else
lvc.cx = m_List_DisplayInfo.GetStringWidth(szColumn[i]) + 80; //获取列的宽度
lvc.iSubItem = i;
m_List_DisplayInfo.InsertColumn(i, &lvc);
}
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CTrafficLightDetectionDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CTrafficLightDetectionDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CTrafficLightDetectionDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CTrafficLightDetectionDlg::OnBnClickedButLoadimg()
{
m_Img.release();
m_bLoatTemplate = false;
// TODO: 在此添加控件通知处理程序代码
CString fileter = _T("JPG files(*.jpg)|*.jpg|BMP files(*.bmp)|*.bmp|任何文件(*.*)|*.*||");
CFileDialog filedlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, fileter);
filedlg.m_ofn.lpstrTitle = _T("请选择要打开的图像文件");
if (IDOK == filedlg.DoModal())
{
m_Vstrfile.clear();
CString filename = filedlg.GetPathName();
m_Vstrfile.push_back(filename);
USES_CONVERSION;
string str(W2A(filename));
m_Img = imread(str, CV_LOAD_IMAGE_UNCHANGED);
if (m_Img.empty())
return;
CRect rect;
GetDlgItem(IDC_STATIC_ShowImg)->GetClientRect(&rect); // 获取控件大小
resize(m_Img, m_Img, Size(rect.Width(), rect.Height()));// 缩放Mat并备份
//CalcMatHist();
m_ShowImg.DisplayImage(m_Img);
}
}
void CTrafficLightDetectionDlg::OnBnClickedButLocate()
{
// TODO: 在此添加控件通知处理程序代码
if (m_Img.empty())
return;
if (m_templateMat.empty())
AfxMessageBox(_T("请先加载模板"));
rectVec_trafficLights.clear();
Mat redMat, greenMat;
m_trafficLightDetector.extractTrafficLightsRects(m_Img, m_templateMat, rectVec_trafficLights, redMat, greenMat);
m_ShowImg.DisplayImage(redMat);
m_DisplayImg.DisplayImage(greenMat);
}
void CTrafficLightDetectionDlg::OnBnClickedButRecongnize()
{
// TODO: 在此添加控件通知处理程序代码
if (m_Img.empty())
return;
if (rectVec_trafficLights.empty()){
AfxMessageBox(_T("请先点击 定位 按钮~"));
return;
}
Mat resultMat;
m_trafficLightDetector.draw_showResultImg(resultMat, rectVec_trafficLights);
m_ShowImg.DisplayImage(m_Img);
m_DisplayImg.DisplayImage(resultMat);
DisplayTrafficLightsInfo(rectVec_trafficLights);
rectVec_trafficLights.clear();
}
void CTrafficLightDetectionDlg::DisplayTrafficLightsInfo(vector<vector<Rect>>& rectVec_trafficLights)
{
LV_ITEM lvi;
lvi.mask = LVIF_TEXT;
UpdateData();
Rect tmpRect;
int iItemCount;
CString str;
vector<Rect> trafficRedLightRect = rectVec_trafficLights[0];
for (int i = 0; i < trafficRedLightRect.size(); i++) {
tmpRect = trafficRedLightRect[i];
//rectangle(img_result, tmpRect, Scalar(0, 0, 255), 3);
iItemCount = m_List_DisplayInfo.GetItemCount();
m_List_DisplayInfo.InsertItem(iItemCount, _T(""));
str.Format(_T("%d"), iItemCount+1);
m_List_DisplayInfo.SetItemText(iItemCount, 0, str);
int nPos = m_Vstrfile[0].ReverseFind('\\');
CString csFileName = m_Vstrfile[0].Right(m_Vstrfile[0].GetLength() - 1 - nPos); // 获取文件名
m_List_DisplayInfo.SetItemText(iItemCount, 1, csFileName);
char buf[80];
sprintf_s(buf, "(x=%d, y=%d, width=%d, height=%d)", tmpRect.x, tmpRect.y, tmpRect.width, tmpRect.height);
int num = MultiByteToWideChar(0, 0, buf, -1, NULL, 0);
wchar_t *wide = new wchar_t[num];
MultiByteToWideChar(0, 0, buf, -1, wide, num);
m_List_DisplayInfo.SetItemText(iItemCount, 2, wide);
m_List_DisplayInfo.SetItemText(iItemCount, 3, _T("红色"));
CTime tTime = CTime::GetCurrentTime();
CString strTemp = tTime.Format("%Y-%m-%d %H:%M:%S");
//往第iItemCount插入第四列的数据数据,即插入登记时间
m_List_DisplayInfo.SetItemText(iItemCount, 4, strTemp);
}
vector<Rect> trafficGreenLightRect = rectVec_trafficLights[1];
for (int i = 0; i < trafficGreenLightRect.size(); i++) {
tmpRect = trafficGreenLightRect[i];
//rectangle(img_result, tmpRect, Scalar(0, 255, 0), 3);
iItemCount = m_List_DisplayInfo.GetItemCount();
m_List_DisplayInfo.InsertItem(iItemCount, _T(""));
str.Format(_T("%d"), iItemCount+1);
m_List_DisplayInfo.SetItemText(iItemCount, 0, str);
int nPos = m_Vstrfile[0].ReverseFind('\\');
CString csFileName = m_Vstrfile[0].Right(m_Vstrfile[0].GetLength() - 1 - nPos); // 获取文件名
m_List_DisplayInfo.SetItemText(iItemCount, 1, csFileName);
char buf[80];
sprintf_s(buf, "(x=%d, y=%d, width=%d, height=%d)", tmpRect.x, tmpRect.y, tmpRect.width, tmpRect.height);
int num = MultiByteToWideChar(0, 0, buf, -1, NULL, 0);
wchar_t *wide = new wchar_t[num];
MultiByteToWideChar(0, 0, buf, -1, wide, num);
m_List_DisplayInfo.SetItemText(iItemCount, 2, wide);
m_List_DisplayInfo.SetItemText(iItemCount, 3, _T("绿色"));
CTime tTime = CTime::GetCurrentTime();
CString strTemp = tTime.Format("%Y-%m-%d %H:%M:%S");
//往第iItemCount插入第四列的数据数据,即插入登记时间
m_List_DisplayInfo.SetItemText(iItemCount, 4, strTemp);
}
}
void CTrafficLightDetectionDlg::CalcMatHist()
{
// TODO: Add your control notification handler code here
Mat result;
cvtColor(m_Img, result, CV_BGR2HSV);
// Quantize the hue to 30 levels
// and the saturation to 32 levels
int hbins = 30, sbins = 32;
int histSize[] = { hbins, sbins };
// hue varies from 0 to 179, see cvtColor
float hranges[] = { 0, 180 };
// saturation varies from 0 (black-gray-white) to
// 255 (pure spectrum color)
float sranges[] = { 0, 256 };
const float* ranges[] = { hranges, sranges };
MatND hist;
// we compute the histogram from the 0-th and 1-st channels
int channels[] = { 0, 1 };
calcHist(&result, 1, channels, Mat(), // do not use mask
hist, 2, histSize, ranges,
true, // the histogram is uniform
false);
double maxVal = 0;
minMaxLoc(hist, 0, &maxVal, 0, 0);
int scale = 10;
Mat histImg = Mat::zeros(sbins*scale, hbins * 10, CV_8UC3);
for (int h = 0; h < hbins; h++) {
for (int s = 0; s < sbins; s++) {
float binVal = hist.at<float>(h, s);
int intensity = cvRound(binVal * 255 / maxVal);
rectangle(histImg, Point(h*scale, s*scale),
Point((h + 1)*scale - 1, (s + 1)*scale - 1),
Scalar::all(intensity),
CV_FILLED);
}
}
namedWindow("H-S Histogram", 1);
imshow("H-S Histogram", histImg);
}
void CTrafficLightDetectionDlg::OnBnClickedButUpdatetemplate()
{
// TODO: 在此添加控件通知处理程序代码
m_Img.release();
m_vTemplatMat.clear();
m_bLoatTemplate = true;
AfxMessageBox(_T("更新模板步骤:\n 1. 选择包含交通信号灯图像的文件夹 \n 2. 挨个浏览图像,并用鼠标框选交通信号灯黑色边框 \n 3. 点击更新按钮,模板更新"));
m_Vstrfile.clear();
Getfolder();
if (m_Vstrfile.empty())
return;
if (m_Vstrfile.size() > 1)
GetDlgItem(IDC_BUT_NEXT)->ShowWindow(true);
CString filename = m_Vstrfile[0];
USES_CONVERSION;
string str(W2A(filename));
m_Img = imread(str, CV_LOAD_IMAGE_UNCHANGED);
if (m_Img.empty())
return;
CRect rect;
GetDlgItem(IDC_STATIC_ShowImg)->GetClientRect(&rect); // 获取控件大小
resize(m_Img, m_Img, Size(rect.Width(), rect.Height()));// 缩放Mat并备份
//CalcMatHist();
m_ShowImg.DisplayImage(m_Img);
}
void CTrafficLightDetectionDlg::OnBnClickedButNext()
{
// TODO: 在此添加控件通知处理程序代码
m_Img.release();
++m_fileNum;
if (m_fileNum >= m_Vstrfile.size())
return;
if (m_fileNum == m_Vstrfile.size()-1)
GetDlgItem(IDC_BUT_NEXT)->ShowWindow(false);
CString filename = m_Vstrfile[m_fileNum];
USES_CONVERSION;
string str(W2A(filename));
m_Img = imread(str, CV_LOAD_IMAGE_UNCHANGED);
if (m_Img.empty())
return;
CRect rect;
GetDlgItem(IDC_STATIC_ShowImg)->GetClientRect(&rect); // 获取控件大小
resize(m_Img, m_Img, Size(rect.Width(), rect.Height()));// 缩放Mat并备份
//CalcMatHist();
m_ShowImg.DisplayImage(m_Img);
}
void CTrafficLightDetectionDlg::OnBnClickedButUpdate()
{
// TODO: 在此添加控件通知处理程序代码
m_bLoatTemplate = false;
m_templateMat = m_vTemplatMat[0];
for (int i = 1; i < m_vTemplatMat.size(); i++)
{
m_trafficLightDetector.mergeRows(m_templateMat, m_vTemplatMat[i]);
}
FileStorage fs(".\\templateMat.xml", FileStorage::WRITE);
fs << "templateMat" << m_templateMat;
fs.release();
CString str;
str.Format(_T("更新模板成功, %d 个特征向量; \n 以Mat的形式保存在当前路径,templateMat.xml"), m_vTemplatMat.size());
AfxMessageBox(str);
}
void CTrafficLightDetectionDlg::Getfolder()
{
CString strFolderPath(_T(""));
TCHAR szPath[_MAX_PATH];
BROWSEINFO bi;
bi.hwndOwner = GetSafeHwnd();
bi.pidlRoot = NULL;
bi.lpszTitle = _T("选择包含交通信号灯图像的文件夹");
bi.pszDisplayName = szPath;
bi.ulFlags = BIF_RETURNONLYFSDIRS;
bi.lpfn = NULL;
bi.lParam = NULL;
bi.iImage = NULL;
LPITEMIDLIST pItemIDList = SHBrowseForFolder(&bi);
if (pItemIDList)
{
if (SHGetPathFromIDList(pItemIDList, szPath))
{
strFolderPath = szPath;
}
// 防止内存泄露,要使用IMalloc接口
IMalloc*pMalloc;
if (SHGetMalloc(&pMalloc) != NOERROR)
{
TRACE(_T("无法取得外壳程序的IMalloc接口\n"));
}
pMalloc->Free(pItemIDList);
if (pMalloc)
pMalloc->Release();
}
else
{
strFolderPath = _T(""); // 文件夹路径为空
}
Getfilepath(strFolderPath); // 调用遍历文件夹函数
}
void CTrafficLightDetectionDlg::Getfilepath(const CString &strPath)
{
CFileFind file;
CString strfile;
CString strtemp = strPath;
CString strDirectory = strPath + _T("\\") + _T("\\*.*");
BOOL IsFind = file.FindFile(strDirectory);
while (IsFind)
{
IsFind = file.FindNextFile();
// 如果是"." 则不扫描
if (file.IsDots())
{
continue;
}
// 如果是是目录,继续扫描此目录
else
{
if (file.IsDirectory())
{
strfile = file.GetFileName();
strtemp = strtemp + _T("\\") + strfile;
Getfilepath(strtemp);
}
// 文件
else
{
strfile = file.GetFileName();
m_Vstrfile.push_back(strtemp + _T("\\") + strfile); //将文件路径压入容器
}
}
}
file.Close();
}
LRESULT CTrafficLightDetectionDlg::GetRect(WPARAM wparam, LPARAM lparam)
{
Rect showRect = *((Rect*)lparam);
if (!m_bLoatTemplate)
return 0;
m_trafficLightDetector.setMat(m_Img); //set m_inMat
Mat equaled_img;
m_trafficLightDetector.Preprocess_equalizeHist(equaled_img); //set equaled_img
MatND histMat;
m_trafficLightDetector.calcMatROIHist(equaled_img, showRect, histMat);
m_vTemplatMat.push_back(histMat);
//rectangle(m_Img, showRect, Scalar(0, 0, 255), 2);
//m_DisplayImg.DisplayImage(m_Img);
//Mat mat = Mat::eye(Size(12, 12), CV_8UC1);
//FileStorage fs(".\\vocabulary.xml", FileStorage::WRITE);
//fs << "vocabulary" << mat;
//fs.release();
//FileStorage fs(".\\vocabulary.xml", FileStorage::READ);
//Mat mat_vocabulary;
//fs["vocabulary"] >> m_templateMat;
return 0;
}
|
/**
*
* @file MultipleFK.hpp
* @author Naoki Takahashi
*
**/
#pragma once
#include "ForwardProblemSolverBase.hpp"
#include <Tools/Math/Matrix.hpp>
#include "../Parameters.hpp"
#include "../ControlPointMap.hpp"
namespace Kinematics {
namespace ForwardProblemSolvers {
template <typename Scalar>
class MultipleFK : public ForwardProblemSolverBase {
protected :
using ParametersPtr = typename Parameters<Scalar>::Ptr;
using ControlPointMapPtr = typename ControlPointMap<Scalar>::Ptr;
public :
using Ptr = std::unique_ptr<MultipleFK>;
using ForwardProblemSolverBase::ModelPtr;
using VectorX = Tools::Math::VectorX<Scalar>;
MultipleFK(ModelPtr &);
virtual ~MultipleFK();
void register_map(ControlPointMapPtr &);
void register_parameters(ParametersPtr &);
protected :
ParametersPtr parameters;
ControlPointMapPtr control_point_map;
VectorX q;
};
}
}
|
//
// Created by peer23peer on 5/22/20.
//
#ifndef GHERMENEUS_MACHINE_H
#define GHERMENEUS_MACHINE_H
#include <algorithm>
#include <execution>
#include <fstream>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include <range/v3/distance.hpp>
#include <range/v3/range/operations.hpp>
#include <range/v3/view/drop.hpp>
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/split.hpp>
#include <range/v3/view/take.hpp>
#include <range/v3/view/transform.hpp>
#include "GCode.h"
#include "Instruction.h"
#include "Parameters.h"
namespace GHermeneus
{
/*!
* This is the workhorse, here the GCode is processed and converted to different output types,
* such as protobufs, CSV text streams, Numpy objects.
*
* Actual implementation of this abstract type is usually done for each type GCode dialect. A Dialect is a namespace
* such as the GHermeneus::Dialects::Marlin. Here the Machine is defined as:
*
* using MarlinSSV = StateSpaceVector<double, 10>; // n = t, x, y, z, x_dot, y_dot, z_dot, e, e_dot, T
* using MarlinMachine = Machine<MarlinSSV, double>;
*
* Normal usage of a DialectMachine would then be:
*
* using namespace GHermeneus::Dialects::Marlin;
* auto UM3 = MarlinMachine();
* UM3 << gcode;
* std::cout << UM3;
*
* Which will output a CSV formatted array of the instructions (not yet implemented fully)
*
* @brief The workhorse behind this parser it will convert GCode to Instructions and different outputs
* @tparam SSV_T The type of the State Space Vector
* @tparam T The primitive type of the State Space eq. double, int etc
*/
template <typename SSV_T, typename T>
class Machine
{
public:
Machine() : parallel_execution{ true } {};
Machine(Machine<SSV_T, T>&& machine) noexcept = default;
virtual ~Machine() = default;
/*!
* @brief parse the GCode to the machine instruction vector
* @param GCode a string_view containing the GCode
*/
void parse(const std::string_view& GCode)
{
gcode = GCode;
extractLines(GCode); // extract the individual GCode lines
// Extract the Commands from each line
std::vector<std::optional<Instruction<SSV_T, T>>> extractedCmds(lines.size());
if (parallel_execution)
{
std::transform(std::execution::par, lines.begin(), lines.end(), extractedCmds.begin(), extractCmd);
}
else
{
std::transform(std::execution::seq, lines.begin(), lines.end(), extractedCmds.begin(), extractCmd);
}
extractedCmds.erase(std::remove_if(std::execution::seq, extractedCmds.begin(), extractedCmds.end(),
[](const auto& cmd) { return !cmd; }),
extractedCmds.end());
cmdlines.resize(extractedCmds.size());
if (parallel_execution)
{
std::transform(std::execution::par, extractedCmds.begin(), extractedCmds.end(), cmdlines.begin(),
[](const auto& cmd) { return cmd.value(); });
std::sort(std::execution::par, cmdlines.begin(), cmdlines.end());
}
else
{
std::transform(std::execution::seq, extractedCmds.begin(), extractedCmds.end(), cmdlines.begin(),
[](const auto& cmd) { return cmd.value(); });
}
}
/*!
* @brief output the machines instruction vector to an output stream as in CSV format
* @param os Output stream
* @param machine A machine of type Machine<SSV_T, T>
* @return an output stream
*/
friend std::ostream& operator<<(std::ostream& os, const Machine<SSV_T, T>& machine)
{
for (const Instruction<SSV_T, T>& cmdline : machine.cmdlines)
{
os << "line: " << cmdline.line_no << " command: " << cmdline.cmd << " Parameters ->";
for (const Parameter<T>& param : cmdline.params)
{
os << " " << param.param << " = " << std::to_string(param.value);
}
os << std::endl;
}
return os;
};
/*!
* @brief Output the GCode stream to the Machines Instruction Vector
* @param machine The machine of type Machine<SSV_T, T>
* @param GCode the GCode as a string_view stream
* @return A machine of type Machine<SSV_T, T>
*/
friend Machine<SSV_T, T>& operator<<(Machine<SSV_T, T>& machine, const std::string_view& GCode)
{
machine.parse(GCode);
return machine;
};
/*!
* @brief Output the GCode filestream to the Machines Instruction Vector
* @param machine The machine of type Machine<SSV_T, T>
* @param file Text file stream
* @return A machine of type Machine<SSV_T, T>
*/
friend Machine<SSV_T, T>& operator<<(Machine<SSV_T, T>& machine, std::ifstream& file)
{
machine.raw_gcode.assign((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>()));
std::string_view gcode{ machine.raw_gcode };
machine << gcode;
return machine;
}
/*!
* @brief Allow for parallel execution, standard on
* @param parallelExecution true if parallel execution is allowed, false for sequenced execution
*/
void setParallelExecution(bool parallelExecution)
{
Machine::parallel_execution = parallel_execution;
}
private:
/*!
* @brief extract the individual lines from the GCode
* @param GCode a string_view containing the GCode
*/
void extractLines(const std::string_view& GCode)
{
// TODO: keep in mind CRLF and LF
lines = gcode | ranges::views::split('\n') | ranges::views::transform([](auto&& line) {
return std::string_view(&*line.begin(), ranges::distance(line));
})
| ranges::views::enumerate | ranges::to_vector;
};
/*!
* @brief Extract an instruction of type Instruction<SSV_T, T> from a GCode line. If the line contains no
* instruction it is a std::nullopt
* @param GCodeline string_view containing the line with command, the relevant parameters and/or a comment.
* @return an optional instruction of type Instruction<SSV_T, T>
*/
[[nodiscard]] static std::optional<Instruction<SSV_T, T>> extractCmd(const Line& GCodeline)
{
#ifndef NDEBUG
std::cout << GCodeline.first << ": " << GCodeline.second << std::endl; // Todo: Use a proper logger like SPDlog
#endif
auto&& [lineno, gcode] = GCodeline;
// Split line in instruction and comment
auto split_line = gcode | ranges::views::split(';');
// Split the instruction into individual words
auto split_instruction = *split_line.begin() | ranges::views::split(' ');
// Get the Cmd
auto cmd_view = split_instruction | ranges::views::take(1) | ranges::views::transform([&](auto&& c) {
return std::string_view(&*c.begin(), ranges::distance(c));
});
std::string_view cmd = *cmd_view.begin();
if (cmd.empty()) // No cmd nothing to do here Todo: also take into account comments that should be treated as a
// cmd
{
return std::nullopt;
}
// Get the values and parameters
// TODO: use std::from_char instead of copying to string
auto params = split_instruction | ranges::views::drop(1) | ranges::views::transform([](auto&& param) {
auto identifier = param | ranges::views::take(1);
auto val = param | ranges::views::drop(1);
auto value = std::string(&*val.begin(), ranges::distance(val));
return Parameter<T>(std::string_view(&*identifier.begin(), ranges::distance(identifier)),
std::stod(value));
}) // Todo: how to process the conversion of text to different T types
| ranges::to_vector;
return Instruction<SSV_T, T>(lineno, cmd, params);
};
std::string raw_gcode; //!< The raw GCode (needed to store files and make sure the data of \p gcode stays in scope
std::string_view gcode; //!< A string_view with the full gcode
std::vector<Line> lines; //!< A vector of Lines, a Line is a pair with the line number and the string_view
std::vector<Instruction<SSV_T, T>> cmdlines; //!< A vector of instructions converted from the lines
bool parallel_execution; //!< Indicating if parsing should be done in parallel
};
} // namespace GHermeneus
#endif // GHERMENEUS_MACHINE_H
|
#pragma once
#ifndef GLSLPROGRAM_H
#define GLSLPROGRAM_H
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <map>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GL/glew.h>
namespace cg
{
namespace GLSLShader
{
enum GLSLShaderType
{
VERTEX = GL_VERTEX_SHADER,
FRAGMENT = GL_FRAGMENT_SHADER,
GEOMETRY = GL_GEOMETRY_SHADER,
TESS_CONTROL = GL_TESS_CONTROL_SHADER,
TESS_EVALUATION = GL_TESS_EVALUATION_SHADER
};
extern std::map<GLSLShader::GLSLShaderType, std::string> GLSLShaderTypeString;
};
/*
Based on https://github.com/daw42/glslcookbook.
PROTOCOL:
COMPILATION
this->compileShaderFromFile, this->compileShaderFromString // for vertex shader
this->compileShaderFromFile, this->compileShaderFromString // for fragment shader
this->compileShaderFromFile, this->compileShaderFromString // for geometry shader (optional)
this->compileShaderFromFile, this->compileShaderFromString // for tesselation shader (optional)
this->compileShaderFromFile, this->compileShaderFromString // for compute shader (optional)
this->setUniform // uniforms of all shaders
this->bindAttribLocation, this->bindFragDataLocation // in of vertex shader (Attrib), out of fragment shader (FragData)
// connecting in/out pair (Varying) is automatic
LINKING
this->link
USING
this->use // activate program (all bound shaders)
*/
class GLSLProgram
{
private:
GLuint handle; // id/handle of program object
std::string logString; // compile log
std::vector<GLuint> shaders; // ids/handles of shaders
bool linked; // not-linked (still compiling) or linked
bool verbose; // simple error handling: output to console
public:
GLSLProgram(bool verbose = true); // simple error handling: output to console
~GLSLProgram(void);
bool compileShaderFromFile (const char* filename, GLSLShader::GLSLShaderType type);
bool compileShaderFromString(const std::string& source, GLSLShader::GLSLShaderType type);
bool link(void);
void use (void);
std::string log(void) const; // error log
int getHandle(void) const; // program id/handle
bool isLinked(void) const; // still COMPILATION or already LINKED
void bindAttribLocation(GLuint location, const char* name); // location -> attrib in
void bindFragDataLocation(GLuint location, const char* name); // fragData out -> location
void setUniform(const char* name, float x, float y, float z);
void setUniform(const char* name, const glm::vec3& v);
void setUniform(const char* name, const glm::vec4& v);
void setUniform(const char* name, const glm::mat3& m);
void setUniform(const char* name, const glm::mat4& m);
void setUniform(const char* name, float value);
void setUniform(const char* name, int value);
void setUniform(const char* name, bool value);
void setUniform(const char* name, int size, const glm::mat4* value);
void printActiveUniforms(void); // Get OpenGL state: uniform
void printActiveAttribs (void); // Get OpenGL state: attrib
int getUniformLocation (const char* name); // location of uniform by name
private:
bool checkAndCreateProgram(void); // sets this->handle
bool fileExists(const std::string& filename); // internal for this->compileShaderFromFile
};
};
#endif
|
#pragma once
#include <tbb/parallel_for.h>
#include <tbb/blocked_range.h>
#include <tbb/mutex.h>
#include <bits/stdc++.h>
#include <algorithm>
#include "tbb/enumerable_thread_specific.h"
#include "types.h"
//This class groups the elements of the original array locally per Thread.
//The elements are stored in a ThreadLocal vector<vector<number>>(groups): One vector per group which stores all
//elements belonging to the group.
namespace parallel_sample_sort {
template <typename number>
class GroupLocally {
public:
GroupLocally(std::vector<number>& original_array, std::vector<number>& pivots,
ThreadLocalGroupsType<number>& threadLocalGroups)
: threadLocalGroups(threadLocalGroups), original_array(original_array), pivots(pivots){
}
int GetRank(number val) const {
//this is basically std::lower_bound. Implementing it ourself is faster.
int fdx = pivots.size();
int count = pivots.size();
int low = 0;
while(count > 0){
int middle = low + count/2;
if(pivots[middle] <= val){
low = middle+1;
count -= count/2 + 1;
}else{
count = count/2;
}
}
return low;
}
void operator()(const tbb::blocked_range<int>& range) const {
typename ThreadLocalGroupsType<number>::reference local = threadLocalGroups.local();
for (int i = range.begin(); i != range.end(); ++i) {
int rank = GetRank(original_array[i]);
local[rank].push_back(original_array[i]);
}
}
private:
std::vector<number>& original_array;
std::vector<number>& pivots;
ThreadLocalGroupsType<number>& threadLocalGroups;
};
} // namespace parallel_sample_sort
|
//
// Created by Amelia Chady on 11/30/2018.
// Implementation of Utility files
//
#include <string>
#include "List.h"
#include "LinkedList.h"
#include "Util.h"
std::string trim(std::string stringToTrim){
if(stringToTrim.length()==0){
return stringToTrim;
}
while(stringToTrim.length()!=0 &&
(stringToTrim.find(' ',0)==0
||stringToTrim.find('\r')==0
||stringToTrim.find('\n')==0)){
stringToTrim = stringToTrim.substr(1);
}
while(stringToTrim.length()!=0 &&
(stringToTrim.find_last_of(' ')==stringToTrim.length()-1
||stringToTrim.find('\r')==stringToTrim.length()-1
||stringToTrim.find('\n')==stringToTrim.length()-1)){
stringToTrim = stringToTrim.substr(0, stringToTrim.length()-1);
}
return stringToTrim;
}
void split_ErrorCheck(const std::string& stringToSplit, const std::string& delim){
if(stringToSplit.length()==0){
throw std::invalid_argument("stringToSplit is empty");
}
if(delim.length()==0){
throw std::invalid_argument("delim is empty");
}
}
List<std::string>* split(std::string stringToSplit, std::string delim){
split_ErrorCheck(stringToSplit, delim);
trim(stringToSplit);
List<std::string>* splitted = new LinkedList<std::string>();
int delimIndex = stringToSplit.find(delim);
while(delimIndex > -1){
if(delimIndex!=0) {
splitted->insertAtEnd(stringToSplit.substr(0, delimIndex));
}
stringToSplit = stringToSplit.substr(delimIndex+1);
delimIndex = stringToSplit.find(delim);
}
if(stringToSplit.length()!=0){
splitted->insertAtEnd(stringToSplit);
}
if(splitted->itemCount()==0){
std::invalid_argument("stringToSplit only has delimiters");
}
return splitted;
}
|
#include <glm/gtc/matrix_transform.hpp>
#include "Renderer.h"
#include "Model.h"
#include "Utility.h"
#include "HMDInput.h"
using namespace std;
using namespace glm;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
Renderer Private Functions
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/// render single frame for each display, then output to whatever screen
void Renderer::RenderDisplay(shared_ptr<Display> dsp,
shared_ptr<HMDInput> inp) {
dsp->PrepareWindow(mSdr, inp);
if (mTexs.size() == mVAOs.size() && mTexs.size() == mElmBuffs.size()){
for (int i = 0; i < mTexs.size(); i++) {
// set texture and normal map, if exists
mTexs[i]->UseTexture();
if (mTexsNormal[i]) {
mTexsNormal[i]->UseTexture();
mSdr->SetNMap(true);
}
else
mSdr->SetNMap(false);
// render for specific display
glBindVertexArray(mVAOs[i]); GLChkErr;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mElmBuffs[i]); GLChkErr;
dsp->Redraw(mSdr, mIndSizes[i]);
}
}
else
throw WorldException("Texture/VAO mismatch");
// output to screen
dsp->SwapWindows();
}
/// single pass render of shadows
void Renderer::RenderShadowMap() {
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (mTexs.size() == mVAOs.size() && mTexs.size() == mElmBuffs.size()) {
for (int i = 0; i < mTexs.size(); i++) {
glBindVertexArray(mVAOs[i]); GLChkErr;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mElmBuffs[i]); GLChkErr;
glDrawElements(GL_TRIANGLES, mIndSizes[i], GL_UNSIGNED_INT, (void*)0);
}
}
else
throw WorldException("Texture/VAO mismatch");
}
/// collect input from whatever is being used
int Renderer::HandleInput(shared_ptr<HMDInput> input, SDL_Event *event) {
SDL_PollEvent(event);
return input->FieldEvent(*event);
}
/// create usable buffers from models
void Renderer::CreateBuffers() {
mat4 temp = translate(mat4(1.0f), vec3(1, 1, 1));
VMap vertMap = mMdl->GetVertices(mat4(1.0f), temp);
TMap trngMap = mMdl->GetTriangles();
NMap normMap = mMdl->GetNormal();
vector<vector<Vertex>> vertices;
vector<vector<uint>> indices;
int texIdx = 0;
// build Vertex and Indice vectors from Vmap and TMap
for (VMap::iterator it = vertMap.begin(); it != vertMap.end(); it++) {
mTexs.push_back(it->first);
mTexsNormal.push_back(normMap[it->first]);
vector<Vertex> verts;
vector<uint> inds;
list<vector<Vertex>> v = vertMap.at(it->first);
list<TriangleSet> t = trngMap.at(it->first);
if (vertMap.at(it->first).size() == trngMap.at(it->first).size()) {
while (v.size()) {
inds.insert(inds.end(),
t.front().mIndices.begin(), t.front().mIndices.end());
verts.insert(verts.end(), v.front().begin(), v.front().end());
v.pop_front();
t.pop_front();
}
vertices.push_back(verts);
indices.push_back(inds);
mIndSizes.push_back(inds.size());
}
else
throw WorldException("Triangle Mesh and Vertex count are different!");
}
//tangent/bitanget calculation
for (int i = 0; i < mTexs.size(); i++) {
for (int x = 0; x < indices[i].size(); x++) {
Vertex v1 = vertices[i][indices[i][x]];
Vertex v2 = vertices[i][indices[i][x+1]];
Vertex v3 = vertices[i][indices[i][x+2]];
vec3 DP1 = vec3(v2.loc - v1.loc);
vec3 DP2 = vec3(v3.loc - v1.loc);
vec2 DT1 = v2.texLoc - v1.texLoc;
vec2 DT2 = v3.texLoc - v1.texLoc;
float r = 1.0f / (DT1.x * DT2.y - DT1.y * DT2.x);
vec3 tangent = (DP1 * DT2.y - DP2 * DT1.y)*r;
vec3 biTangent = (DT1.x * DP2 - DP1 * DT2.x)*r;
vertices[i][indices[i][x]].tangent = tangent;
vertices[i][indices[i][x+1]].tangent = tangent;
vertices[i][indices[i][x+2]].tangent = tangent;
vertices[i][indices[i][x++]].biTangent = biTangent;
vertices[i][indices[i][x++]].biTangent = biTangent;
vertices[i][indices[i][x]].biTangent = biTangent;
}
}
mVAOs = vector<GLuint>(indices.size());
mElmBuffs = vector<GLuint>(indices.size());
mVBOs = vector<GLuint>(indices.size());
glGenVertexArrays(indices.size(), &mVAOs[0]); GLChkErr;
glGenBuffers(indices.size(), &mElmBuffs[0]); GLChkErr;
glGenBuffers(mVBOs.size(), &mVBOs[0]); GLChkErr;
texIdx = 0; // Current texture, as we progress through the Vertex vectors
for (vector<Vertex> vec : vertices) {
// Bind the VAO
glBindVertexArray(mVAOs[texIdx]); GLChkErr;
glBindBuffer(GL_ARRAY_BUFFER, mVBOs[(texIdx)]); GLChkErr;
glBufferData(GL_ARRAY_BUFFER, vec.size() * sizeof(Vertex),
vec.data(), GL_STATIC_DRAW); GLChkErr;
glVertexAttribPointer
(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); GLChkErr;
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)(4 * sizeof(float))); GLChkErr;
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)(7 * sizeof(float))); GLChkErr;
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)(9 * sizeof(float))); GLChkErr;
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)(12 * sizeof(float))); GLChkErr;
// use the attributes for each array
glEnableVertexAttribArray(0); GLChkErr;
glEnableVertexAttribArray(1); GLChkErr;
glEnableVertexAttribArray(2); GLChkErr;
glEnableVertexAttribArray(3); GLChkErr;
glEnableVertexAttribArray(4); GLChkErr;
glBindVertexArray(mVAOs[texIdx++]); GLChkErr;
}
texIdx = 0;
for (vector<uint> inds : indices) {
// create indice array
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mElmBuffs[texIdx]); GLChkErr;
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
inds.size() * sizeof(uint), inds.data(), GL_STATIC_DRAW); GLChkErr;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mElmBuffs[texIdx]); GLChkErr;
glBindVertexArray(mVAOs[texIdx++]); GLChkErr;
}
}
/// create single instance of shader
void Renderer::CreateShader() {
mSdr = shared_ptr<Shader>(new Shader());
// create multiple light sources (up to five)
vec4 pos(0, 1, 0, 1);
vec3 clr(0.8f, 0.8f, 0.8f);
LightSource light(pos, clr);
mLightSources.push_back(light);
}
/// render single pass shadow map
void Renderer::CreateShadowMap() {
glGenFramebuffers(1, &mShadowMap);
uint shdSize = 1024;
GLuint depthMap;
// set parameters for output texture
glGenTextures(1, &depthMap);
glBindTexture(GL_TEXTURE_2D, depthMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT,
shdSize, shdSize, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
// create frame buffer
glBindFramebuffer(GL_FRAMEBUFFER, mShadowMap);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// bind and set viewport
glViewport(0, 0, shdSize, shdSize);
glBindFramebuffer(GL_FRAMEBUFFER, mShadowMap);
glClear(GL_DEPTH_BUFFER_BIT);
// create camera transformation matrix
float near_plane = 1.0f, far_plane = 10.0f;
mat4 lightProjection = ortho(
-10.0f, 10.0f, -10.0f, 10.0f, near_plane, far_plane);
mat4 lightView = glm::lookAt(
vec3(0 , 5, 2),
vec3(0.0f, 0.0f, 0.0f),
vec3(0.0f, 1.0f, 0.0f));
mLSM = lightProjection * lightView;
mSdr->SetShadowMap(mLSM);
mTexs[0]->UseTexture();
// create shadow map
RenderShadowMap();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// create texture from framebuffer rendering
mDepthTex = shared_ptr<Texture>(new TextureShadow(depthMap, "Shadows"));
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
Renderer Public Functions
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/// set up renderer (buffers, shadow map, shader)
Renderer::Renderer(shared_ptr<Model> mdl, vector<shared_ptr<Display>> displays,
vector<shared_ptr<HMDInput>>input) : mDisplays(displays), mInputs(input),
mMdl(mdl) {
CreateShader();
CreateBuffers();
CreateShadowMap();
}
/// game loop, untied from input and FPS
void Renderer::Run() {
SDL_Event *event = new SDL_Event();
SDL_PollEvent(event);
bool breakESC = true;
mSdr->Configure(mLightSources, mLSM);
mDepthTex->UseTexture();
while (breakESC) {
if (mDisplays.size() == mInputs.size()) {
for (int i = 0; i < mDisplays.size(); i++) {
while (SDL_PollEvent(event))
breakESC = !mInputs[0]->FieldEvent(*event);
RenderDisplay(mDisplays[i], mInputs[i]);
}
}
else
throw WorldException("Triangle Mesh and Vertex count are different!");
}
}
|
#ifndef MENU_CHICKFILA_DISPLAY
#define MENU_CHICKFILA_DISPLAY
#include "../composite/menu_component.hpp"
#include "../composite/menu_burger/header/menu_items_chickfila.hpp"
#include "../composite/menu_burger/header/menu_chickfila.hpp"
class menu_chickfilas_display
{
public:
void display_chickfilas_customer_favorites()
{
menu_component *chickfila_menu_customer_favorites = new menu_chickfila("Chick-Fil-A's Menu, Customer Favorites", "Following Options are the Most Popular Items at Chick-Fil-A");
// REGULAR CHICKEN SANDWICH ENTREE
menu_component *chicken_sandwhich = new menu_items_chickfila(1, "Chicken Sandwich", "A boneless breast of chicken seasoned to perfection, hand-breaded, pressure cooked in 100% refined peanut oil and served on a toasted, buttered bun with dill pickle chips. Gluten-free bun or multigrain bun also available at an additional cost.", 4.29);
//SPICY CHICKEN SANDWICH ENTREE
menu_component *spicy_chicken_sandwhich = new menu_items_chickfila(2, "Spicy Chicken Sandwich", "A boneless breast of chicken seasoned with a spicy blend of peppers, hand-breaded, pressure cooked in 100% refined peanut oil and served on a toasted, buttered bun with dill pickle chips. Gluten-free bun or multigrain bun also available at an additional cost.", 4.65);
// CHICK FIL A NUGGETS (ORIGINAL) 4 PIECE
menu_component *chickfila_nuggets_4_piece = new menu_items_chickfila(3, "Chick-fil-a Nuggets 4 Piece", "Bite-sized pieces of boneless chicken breast, seasoned to perfection, freshly-breaded and pressure cooked in 100% refined peanut oil. Available with choice of dipping sauce.", 2.20);
// CHICK FIL A NUGGETS (ORIGINAL) 8 PIECE
menu_component *chickfila_nuggets_8_piece = new menu_items_chickfila(4, "Chick-fil-a Nuggets 8 Piece", "Bite-sized pieces of boneless chicken breast, seasoned to perfection, freshly-breaded and pressure cooked in 100% refined peanut oil. Available with choice of dipping sauce.", 4.39);
// CHICK FIL A NUGGETS (ORIGINAL) 12 PIECE
menu_component *chickfila_nuggets_12_piece = new menu_items_chickfila(5, "Chick-fil-a Nuggets 12 Piece", "Bite-sized pieces of boneless chicken breast, seasoned to perfection, freshly-breaded and pressure cooked in 100% refined peanut oil. Available with choice of dipping sauce.", 6.29);
//WAFFLE FRIES
menu_component *waffle_fries_small = new menu_items_chickfila(6, "Waffle Potato Fries (Small)", "Waffle-cut potatoes cooked in canola oil until crispy outside and tender inside. Lightly sprinkled with Sea Salt.", 1.95);
menu_component *waffle_fries_medium = new menu_items_chickfila(7, "Waffle Potato Fries (Medium)", "Waffle-cut potatoes cooked in canola oil until crispy outside and tender inside. Lightly sprinkled with Sea Salt.", 2.25);
menu_component *waffle_fries_large = new menu_items_chickfila(8, "Waffle Potato Fries (Large)", "Waffle-cut potatoes cooked in canola oil until crispy outside and tender inside. Lightly sprinkled with Sea Salt.", 2.55);
//MAC & CHEESE
menu_component *mac_and_cheese_small = new menu_items_chickfila(9, "Mac and Cheese (Small)", "A classic macaroni and cheese recipe featuring a special blend of cheeses including Parmesan, Cheddar, and Romano. Baked in-restaurant to form a crispy top layer of baked cheese.", 2.89);
menu_component *mac_and_cheese_medium = new menu_items_chickfila(10, "Mac and Cheese (Medium)", "A classic macaroni and cheese recipe featuring a special blend of cheeses including Parmesan, Cheddar, and Romano. Baked in-restaurant to form a crispy top layer of baked cheese.", 3.65);
chickfila_menu_customer_favorites->add(chicken_sandwhich);
chickfila_menu_customer_favorites->add(spicy_chicken_sandwhich);
chickfila_menu_customer_favorites->add(chickfila_nuggets_4_piece);
chickfila_menu_customer_favorites->add(chickfila_nuggets_8_piece);
chickfila_menu_customer_favorites->add(chickfila_nuggets_12_piece);
chickfila_menu_customer_favorites->add(waffle_fries_small);
chickfila_menu_customer_favorites->add(waffle_fries_medium);
chickfila_menu_customer_favorites->add(waffle_fries_large);
chickfila_menu_customer_favorites->add(mac_and_cheese_small);
chickfila_menu_customer_favorites->add(mac_and_cheese_medium);
chickfila_menu_customer_favorites->print();
}
};
#endif /* MENU_CHICKFILA_DISPLAY */
|
#include<bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<vector<int>> subsets(vector<int> &nums)
{
vector<vector<int>> ans;
if (nums.empty())
return ans;
int n = pow(2, nums.size());
for (int i = 0; i < n; ++i)
{
vector<int> v;
int mask = 1;
for (int j = 0; j < nums.size(); ++j)
{
if (i & (mask << j))
v.push_back(nums[j]);
}
ans.push_back(v);
}
return ans;
}
};
int main() {}
|
#include "threshold.h"
#ifdef PTHREAD
/* c function and struct for pthread */
struct thread_data {
int id;
void *threshold;
};
void*
threadWorker(void *arg)
{
struct thread_data *task = (struct thread_data*) arg;
((Threshold *)task->threshold)->scheduleWork(task->id);
return NULL;
}
#endif
Threshold::Threshold(Config *_config, Tagimage *_tagimage)
{
config = _config;
tagimage = _tagimage;
init();
if(tagimage->isValid()) {
resolveImageScaling();
max_rgb = tagimage->maxRGB();
}
pixdebug = config->CHECK_VISUAL_DEBUG();
if(pixdebug) dbgpixmap = config->DBGPIXMAP;
else dbgpixmap = NULL;
}
Threshold::Threshold(Config *_config, unsigned char *frame, int _frame_width, int _frame_height)
{
config = _config;
init();
frame_width = _frame_width;
frame_height = _frame_height;
if( frame != NULL ){
tagframe = frame;
resolveFrameScaling();
max_rgb = config->WIN_DSHOW_MAXRGB;
}
VIDEO = true;
}
Threshold::~Threshold()
{
}
void
Threshold::init()
{
width = 0;
height = 0;
scale = 1;
span = 0;
max_rgb = 0;
frame_width = 0;
frame_height = 0;
edgemap = NULL;
multi_threaded = false;
VIDEO = false;
pixdebug = false;
#ifndef PTHREAD
config->THREADS = 1; //if no pthread force to single thread
#endif
}
float
Threshold::getScale()
{
return scale;
}
int
Threshold::mapSize()
{
return width*height ;
}
void
Threshold::resolveImageScaling()
{
int tag_width = tagimage->getWidth();
int tag_height = tagimage->getHeight();
assert(tag_width > config->THRESHOLD_WINDOW_SIZE && tag_height > config->THRESHOLD_WINDOW_SIZE);
if( tag_width < config->PIXMAP_SCALE_SIZE &&
tag_height < config->PIXMAP_SCALE_SIZE ) {
width = tag_width;
height = tag_height;
} else if(config->PIXMAP_NATIVE_SCALE ||
config->PIXMAP_SCALE_SIZE < config->THRESHOLD_WINDOW_SIZE) {
width = tag_width;
height = tag_height;
}else{
resolveScaling(tag_width, tag_height);
}
initEdgemap();
}
void
Threshold::resolveFrameScaling()
{
assert(frame_width > config->THRESHOLD_WINDOW_SIZE && frame_height > config->THRESHOLD_WINDOW_SIZE);
if( frame_width < config->PIXMAP_SCALE_SIZE &&
frame_height < config->PIXMAP_SCALE_SIZE ) {
width = frame_width;
height = frame_height;
} else if( config->PIXMAP_SCALE_SIZE < config->THRESHOLD_WINDOW_SIZE) {
width = frame_width;
height = frame_height;
}else{
//FIXME VIDEO SCALING DISABLED
resolveScaling(frame_width, frame_height);
//width = frame_width;
//height = frame_height;
}
initEdgemap();
}
void
Threshold::resolveScaling(int tagwidth, int tagheight)
{
scale = tagwidth > tagheight ?
(float)tagwidth/(float)config->PIXMAP_SCALE_SIZE :
(float)tagheight/(float)config->PIXMAP_SCALE_SIZE ;
width = (int)((float)tagwidth/scale);
height = (int)((float)tagheight/scale);
if(scale > 1) {
//calculate span here once
//instead of everytime at getpixel()
span = (int)(scale/2.0);
//do scaling end edge correction here
//innstead of bounds checks every getPixel() calls
//scaling begin edge correction is at getPixel()
width-=span;
height-=span;
}
if(config->TAG_DEBUG) cout << " tag_width=" << tagwidth << " tag_height=" << tagheight << endl;
}
void
Threshold::initEdgemap()
{
if(config->TAG_DEBUG) cout << "SCALE: native_scale=" << config->PIXMAP_NATIVE_SCALE
<< " jpeg_scale=" << config->JPG_SCALE
<< " fast_scale=" << config->PIXMAP_FAST_SCALE
<< " scale=" << scale << " span=" << span
//<< " tag_width=" << tag_width << " tag_height=" << tag_height
<< " width=" << width << " height=" << height
<< " window=" << config->THRESHOLD_WINDOW_SIZE << endl;
if(config->EDGE_MAP != NULL ){
delete [] config->EDGE_MAP;
config->EDGE_MAP = NULL;
}
config->EDGE_MAP = new bool[width*height];
edgemap = config->EDGE_MAP;
config->GRID_WIDTH = width;
config->GRID_HEIGHT = height;
}
int
Threshold::framePixel(int x, int y)
{
if( scale != 1 ) {
y =(int) ((float)y * scale);
x =(int) ((float)x * scale);
}
if( x <= 0 || y <= 0 ) return 0;
if( x >= frame_width || y >= frame_height ) return 0;
int i = ( (frame_height-y) * frame_width) + x; //FIXME VIDEO proper frame orientation check
RGBBYTE *thispixel = (RGBBYTE*) tagframe + i;
if(thispixel) return ( thispixel->R + thispixel->G + thispixel->B );
return 0;
}
//NOTE: Removed tagimage::getPixel() bounds check for fast common case (scale==1)
// So make sure all bounds check are done before calling tagimage::getPixel()
int
Threshold::getPixel(int x, int y)
{
if(VIDEO) return framePixel(x,y);
//NOTE: tagimage->getPixel(x,y) is same as config->PIXBUF[(y * width) + x];
//no scaling, fastest
if(scale == 1) return config->PIXBUF[(y * width) + x];
//scaling by skipping, faster
if(config->PIXMAP_FAST_SCALE)
return tagimage->getPixel((int)((float)x*scale), (int)((float)y*scale) );
if( x == 0 || y == 0 ) //begin edge bounds check
return tagimage->getPixel((int)((float)x*scale), (int)((float)y*scale) );
//scaling by averaging, slower
int pixel = 0, count = 0;
int ix = (int)((float)x*scale);
int iy = (int)((float)y*scale);
for(int i=0; i<=span*2; i++) {
pixel+=tagimage->getPixel(ix-span+i, iy);
pixel+=tagimage->getPixel(ix, iy-span+i);
count++;
}
assert( count == (span*2)+1 );
return (pixel/count);
}
// parallel access from threads
// do not modify class variable values here without mutex
void
Threshold::scheduleWork(int id)
{
int offset = config->THRESHOLD_OFFSET * tagimage->COLORS * config->THRESHOLD_RGB_FACTOR;
if(id == 0) computeEdgemap(config->THRESHOLD_WINDOW_SIZE, offset, 0, height/2);
else if(id == 1) computeEdgemap(config->THRESHOLD_WINDOW_SIZE, offset, height/2, height);
}
void
Threshold::computeEdgemap()
{
ta = new bool[width*height]; //thresholded pixel on/off array //TODO moving window of (3*width)
for(int x = 0; x < (width*height); x++) edgemap[x] = false;
#ifdef PTHREAD
if( config->THREADS == 2 ){
multi_threaded = true;
pthread_t threads[2];
struct thread_data t_data[2];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(int i = 0; i<2; i++){
t_data[i].id = i;
t_data[i].threshold = this;
if (pthread_create(&threads[i], &attr, threadWorker, (void *)&t_data[i]) != 0) return;
}
pthread_attr_destroy(&attr);
for(int i = 0; i<2; i++){
if (pthread_join(threads[i], NULL) != 0) return;
}
fillEdgemap(); //for multi thread, do it after thresholding loop
} else {
int offset = config->THRESHOLD_OFFSET * tagimage->COLORS * config->THRESHOLD_RGB_FACTOR;
if(scale == 1) computeEdgemapOpt(config->THRESHOLD_WINDOW_SIZE, offset);
else computeEdgemap(config->THRESHOLD_WINDOW_SIZE, offset, 0, height);
}
#else
int offset = 0;
if(VIDEO)
offset = config->THRESHOLD_OFFSET * config->WIN_DSHOW_COLORS * config->THRESHOLD_RGB_FACTOR;
else
offset = config->THRESHOLD_OFFSET * tagimage->COLORS * config->THRESHOLD_RGB_FACTOR;
if(scale == 1) computeEdgemapOpt(config->THRESHOLD_WINDOW_SIZE, offset);
else computeEdgemap(config->THRESHOLD_WINDOW_SIZE, offset, 0, height);
#endif
delete [] ta;
}
/*
* Optimised Local Adapaive Thresholding using the MEAN value
* of pixels in the local neighborhood (block) as the threshold
* and binarizes to on or off pixels based on threshold
*
* Applies edge marking also in the same loop, based on the
* thresholded on/off pixel values
*
* Blocks are selected rows (width wise) starting from top left
*
* x,i,width - are in x plane y,j,height - are in y plane
*
* Neighborhood sums are calculated based on stored deltas from
* the last neighborhood on left and last row of blocks above
*
* All border pixels (x < width, y < w, x > width-radius, y > width-radis)
* have partial neighborhood block size
*
* NOTE: All condition checks are optmised and is order dependent
*
* TODO : Verify if the diagonal above check in edge marking can be removed
* ( check border tracing )
*/
/*
computeEdgemap
- Extra step of getPixel() function call to access Config->PIXBUF[]
- getPixel() handles the span and scale
computeEdgemapOpt
- Directly Access Config->PIXBUF[]
- only if not using span or scale
- Saves only 0.01 second in performance
Identical versions, one for slightly better performance
*** has to maintain both versions as exactly the same ****
*/
void
Threshold::computeEdgemapOpt(int size, int offset)
{
if(VIDEO) return computeEdgemap(size, offset, 0, height); //No optimization yet for video frames
long threshold = 0, lastdelta = 0, di = 0;
bool thispixel = false, epixel = false;
int ex = 0, ey = 0, ei = 0;
int blocksize = size*size, radius = size/2, half_block = blocksize/2;
unsigned char* pixbuf = config->PIXBUF;
int *td = new int[width*height]; //threshold deltas //TODO moving window of (size*width)
int *ts = new int[width]; //threshold sums
for(int x = 0; x < (width*height); x++) td[x] = 0;
for(int x = 0; x < width; x++) ts[x] = 0;
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
if( y >= (height-radius) ){ //partial: bottom rows
ts[x] -= td[((y-radius)*width)+x];
threshold = ts[x] / (size*(radius+height-y));
}else if( y > radius && x == 0 ){ //normal: very first
di = ((y+radius)*width) + x;
for(int i = 0; i < radius; i++) td[di]+=pixbuf[i + width * (y+radius)];
ts[x] += td[di] - td[((y-radius-1)*width)+x];
threshold = ts[x] /half_block;
lastdelta = td[di];
}else if( y > radius && x >= width - radius ){//normal: partial end
di = ((y+radius)*width) + x;
td[di] = lastdelta - pixbuf[(x-radius-1) + width * (y+radius)];
ts[x] += td[di] - td[((y-radius)*width)+x];
threshold = ts[x] / ((width-x+radius)*size);
lastdelta = td[di];
}else if( y > radius && x <=radius ){ //normal: partial begin
di = ((y+radius)*width) + x;
td[di]=lastdelta + pixbuf[(x+radius) + width * (y+radius)];
ts[x]+= td[di] - td[((y-radius)*width)+x];
threshold = ts[x] / ((x+radius)*size);
lastdelta = td[di];
}else if( y > radius ){ //normal: all full (90% of all)
di = ((y+radius)*width) + x;
td[di] = lastdelta + pixbuf[(x+radius) + width * (y+radius)]
- pixbuf[(x-radius-1) + width * (y+radius)];
ts[x] += td[di] - td[((y-radius)*width)+x];
threshold = ts[x] / blocksize;
lastdelta = td[di];
}else if( x == 0 && y == 0 ){ //first top left block
for(int j = 0; j < radius; j++){
di = j*width;
for(int i = 0; i < radius; i++) td[di] += pixbuf[i + width * j];
ts[x] += td[di];
}
threshold = ts[x] /(blocksize/4);
}else if( y == 0 ){ //partial: topmost row all
for(int j = 0; j < radius; j++){
di = (j*width) + x;
td[di] = td[di-1];
if(x > radius) td[di] -= pixbuf[(x-radius-1) + width * j];
if(x <= width-radius) td[di] += pixbuf[(x+radius) + width * j];
ts[x] += td[di];
}
if(x <= radius) threshold = ts[x] / (radius*(x+radius));
else if(x <= width-radius) threshold = ts[x] / half_block;
else threshold = ts[x] / ((width-x+radius)*radius);
}else if( y <= radius && x <= radius){ //partial: top row begin
di = ((y+radius)*width) + x;
for(int i = 0; i < x+radius; i++) td[di]
+= pixbuf[i + width * (y+radius)];
ts[x] += td[di];
threshold = ts[x] / ((x+radius)*(y+radius));
}else if( y <= radius && x >= width -radius){ //partial: top row end
di = ((y+radius)*width) + x;
for(int i = width; i > x-radius; i--) td[di]
+= pixbuf[i + width * (y+radius)];
ts[x] += td[di];
threshold = ts[x] / ((width-x+radius)*(y+radius));
}else if( y <= radius ){ //partial: top row all
di = ((y+radius)*width) + x;
for(int i = 0; i < size; i++) td[di]
+= pixbuf[(x-radius+i) + width * (y+radius)];
ts[x] += td[di];
threshold = ts[x] / (size*(y+radius));
}
threshold-=offset;
thispixel = pixbuf[x + width * y] < threshold ? true : false;
ta[(y*width)+x] = thispixel;
if(pixdebug) thispixel ? d_setPixelFilled(x, y) : d_setPixelBlank(x, y);
if( ! multi_threaded ){ //single thread do it in the thresholding loop
if( y > 2){ //edge marking based on ta[]
ex = x; ey = y-2;
ei = ((ey)*width)+ex;
epixel = ta[ei];
if( epixel ){
if( ex > 0 && ex < width ){
if( epixel ^ ta[(ey*width)+ex-1]
|| epixel ^ ta[(ey*width)+ex+1]
|| epixel ^ ta[((ey-1)*width)+ex]
|| epixel ^ ta[((ey-1)*width)+ex+1]
|| epixel ^ ta[((ey-1)*width)+ex-1]
|| epixel ^ ta[((ey+1)*width)+ex]
|| epixel ^ ta[((ey+1)*width)+ex+1]
|| epixel ^ ta[((ey+1)*width)+ex-1] ){
edgemap[ei] = true;
if(pixdebug) d_setPixelMarked(ex, ey);
}
}
}
}
}
//close out borders on bottom edge
//if((y == height-1) && thispixel) d_setPixelMarked(x, y);
}
//close out borders on right edge
//if((x == width) && thispixel) d_setPixelMarked(x-1, y);
}
delete [] ts;
delete [] td;
}
// parallel access from threads
// do not modify class variable values here without mutex
void
Threshold::computeEdgemap(int size, int offset, int y1, int y2)
{
long threshold = 0, lastdelta = 0, di = 0;
bool thispixel = false, epixel = false;
int ex = 0, ey = 0, ei = 0;
int blocksize = size*size, radius = size/2, half_block = blocksize/2;
//overlapping segment correction
if( y1 > 0 ) y1-=size; //all segments beginning in middle of tagimage
if( y2 < height ) y2+=size; //all segments ending in the middle of tagimage
int new_radius = radius + y1;
int *td = new int[width*height]; //threshold deltas //TODO moving window of (size*width)
int *ts = new int[width]; //threshold sums
for(int x = 0; x < (width*height); x++) td[x] = 0;
for(int x = 0; x < width; x++) ts[x] = 0;
for(int y = y1; y < y2; y++){
if(config->TAG_DEBUG) { //TODO: Remove once threads are final
if(y1 == 0) printf("*");
if(y1 > 0) printf("-");
}
for(int x = 0; x < width; x++){
if( y >= (height-radius) ){ //partial: bottom rows
ts[x] -= td[((y-radius)*width)+x];
threshold = ts[x] / (size*(radius+height-y));
}else if( y > radius && x == 0 ){ //normal: very first
di = ((y+radius)*width) + x;
for(int i = 0; i < radius; i++) td[di]+=getPixel(i, y+radius);
ts[x] += td[di] - td[((y-radius-1)*width)+x];
threshold = ts[x] /half_block;
lastdelta = td[di];
}else if( y > radius && x >= width - radius ){//normal: partial end
di = ((y+radius)*width) + x;
td[di] = lastdelta - getPixel(x-radius-1,y+radius);
ts[x] += td[di] - td[((y-radius)*width)+x];
threshold = ts[x] / ((width-x+radius)*size);
lastdelta = td[di];
}else if( y > radius && x <=radius ){ //normal: partial begin
di = ((y+radius)*width) + x;
td[di]=lastdelta + getPixel(x+radius, y+radius);
ts[x]+= td[di] - td[((y-radius)*width)+x];
threshold = ts[x] / ((x+radius)*size);
lastdelta = td[di];
}else if( y > radius ){ //normal: all full (90% of all)
di = ((y+radius)*width) + x;
td[di] = lastdelta + getPixel(x+radius, y+radius)
- getPixel(x-radius-1,y+radius);
ts[x] += td[di] - td[((y-radius)*width)+x];
threshold = ts[x] / blocksize;
lastdelta = td[di];
}else if( x == 0 && y == 0 ){ //first top left block
for(int j = y1; j < radius; j++){
di = j*width;
for(int i = 0; i < radius; i++) td[di] += getPixel(i, j);
ts[x] += td[di];
}
threshold = ts[x] /(blocksize/4);
}else if( y == y1 ){ //partial: topmost row all
for(int j = y1; j < radius; j++){
di = (j*width) + x;
td[di] = td[di-1];
if(x > radius) td[di] -= getPixel(x-radius-1, j);
if(x <= width-radius) td[di] += getPixel(x+radius, j);
ts[x] += td[di];
}
if(x <= radius) threshold = ts[x] / (radius*(x+radius));
else if(x <= width-radius) threshold = ts[x] / half_block;
else threshold = ts[x] / ((width-x+radius)*radius);
}else if( y <= new_radius && x <= radius){ //partial: top row begin
di = ((y+radius)*width) + x;
for(int i = 0; i < x+radius; i++) td[di]
+= getPixel(i, y+radius);
ts[x] += td[di];
threshold = ts[x] / ((x+radius)*(y+radius));
}else if( y <= new_radius && x >= width -radius){ //partial: top row end
di = ((y+radius)*width) + x;
for(int i = width; i > x-radius; i--) td[di]
+= getPixel(i, y+radius);
ts[x] += td[di];
threshold = ts[x] / ((width-x+radius)*(y+radius));
}else if( y <= new_radius ){ //partial: top row all
di = ((y+radius)*width) + x;
for(int i = 0; i < size; i++) td[di]
+= getPixel((x-radius)+i, y+radius);
ts[x] += td[di];
threshold = ts[x] / (size*(y+radius));
}
//skip overlap only for beginning on the middle
//will be covered by the one above ( applies to multi thread only)
if( y1 == 0 || y > y1+size){
threshold-=offset;
thispixel = getPixel(x, y) < threshold ? true : false;
ta[(y*width)+x] = thispixel;
if(pixdebug) thispixel ? d_setPixelFilled(x, y) : d_setPixelBlank(x, y);
}
if( config->THREADS < 2 ){ //single thread do it in the thresholding loop
if( y > 2){ //edge marking based on ta[]
ex = x; ey = y-2;
ei = ((ey)*width)+ex;
epixel = ta[ei];
if( epixel ){
if( ex > 0 && ex < width ){
if( epixel ^ ta[(ey*width)+ex-1]
|| epixel ^ ta[(ey*width)+ex+1]
|| epixel ^ ta[((ey-1)*width)+ex]
|| epixel ^ ta[((ey-1)*width)+ex+1]
|| epixel ^ ta[((ey-1)*width)+ex-1]
|| epixel ^ ta[((ey+1)*width)+ex]
|| epixel ^ ta[((ey+1)*width)+ex+1]
|| epixel ^ ta[((ey+1)*width)+ex-1] ){
edgemap[ei] = true;
if(pixdebug || config->V_D_PIXDEBUG) d_setPixelMarked(ex, ey);
}else{
if(pixdebug || config->V_D_PIXDEBUG) d_setPixelBlank(ex, ey);
}
}
}else{
//if(VIDEO) d_setPixelBlank(ex, ey);
}
}
}
//close out borders on bottom edge
//if((y == height-1) && thispixel) d_setPixelMarked(x, y);
}
//close out borders on right edge
//if((x == width) && thispixel) d_setPixelMarked(x-1, y);
}
delete [] ts;
delete [] td;
}
void
Threshold::fillEdgemap()
{
int ex = 0, ey = 0, ei = 0;
bool epixel = false;
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
if( y > 2){ //edge marking based on ta[]
ex = x; ey = y-2;
ei = ((ey)*width)+ex;
epixel = ta[ei];
if( epixel ){
if( ex > 0 && ex < width ){
if( epixel ^ ta[(ey*width)+ex-1]
|| epixel ^ ta[(ey*width)+ex+1]
|| epixel ^ ta[((ey-1)*width)+ex]
|| epixel ^ ta[((ey-1)*width)+ex+1]
|| epixel ^ ta[((ey-1)*width)+ex-1]
|| epixel ^ ta[((ey+1)*width)+ex]
|| epixel ^ ta[((ey+1)*width)+ex+1]
|| epixel ^ ta[((ey+1)*width)+ex-1] ){
edgemap[ei] = true;
if(pixdebug) d_setPixelMarked(ex, ey);
}
}
}
}
}
}
}
void
Threshold::d_setPixelMarked(int x, int y) //GREEN
{
if(VIDEO){
y =(int) ((float)y * scale);
x =(int) ((float)x * scale);
int i = ( (frame_height-y) * frame_width) + x; //FIXME VIDEO proper frame orientation check
RGBBYTE *thispixel = (RGBBYTE*) tagframe + i;
thispixel->R = 0;
thispixel->G = 255;
thispixel->B = 0;
}else{
dbgpixmap->setPixel((int)((float)x*scale), (int)((float)y*scale), 0, max_rgb, 0);
}
}
void
Threshold::d_setPixelBlank(int x, int y) //WHITE
{
if(VIDEO){
y =(int) ((float)y * scale);
x =(int) ((float)x * scale);
int i = ( (frame_height-y) * frame_width) + x; //FIXME VIDEO proper frame orientation check
RGBBYTE *thispixel = (RGBBYTE*) tagframe + i;
thispixel->R = 255;
thispixel->G = 0;
thispixel->B = 0;
}else{
dbgpixmap->setPixel((int)((float)x*scale), (int)((float)y*scale), max_rgb, max_rgb, max_rgb);
}
}
void
Threshold::d_setPixelFilled(int x, int y) //BLACK
{
if(VIDEO){
y =(int) ((float)y * scale);
x =(int) ((float)x * scale);
int i = ( (frame_height-y) * frame_width) + x; //FIXME VIDEO proper frame orientation check
RGBBYTE *thispixel = (RGBBYTE*) tagframe + i;
thispixel->R = 0;
thispixel->G = 0;
thispixel->B = 0;
}else{
dbgpixmap->setPixel((int)((float)x*scale), (int)((float)y*scale), 0, 0, 0);
}
}
|
#pragma once
#include "../TCPServer.h"
#include "Parser.h"
#include "Response.h"
namespace
NAMESPACE http {
class HTTPServer {
public:
private:
TcpServer server_;
};
}
|
#include <graphics.h>
#define DELAY 10
int color = 2;
void lineBresenham_1(int x1, int y1, int x2, int y2)
{
int c2, c, Dx, Dy, x, y;
Dx = abs(x2 - x1);
Dy = abs(y2 - y1);
c = Dx - Dy;
c2 = 2 * c;
x = x1;
y = y1;
int x_unit = 1, y_unit = 1;
if (x2 - x1 < 0)
x_unit = -x_unit;
if (y2 - y1 < 0)
y_unit = -y_unit;
putpixel(x, y, GREEN);
if (x1 == x2) // duong thang dung
{
while (y != y2)
{delay(1);
y += y_unit;
putpixel(x, y, GREEN);
}
}
else if (y1 == y2) // duong ngang
{
while (x != x2)
{
x += x_unit;
putpixel(x, y, GREEN);
}
}
else if (x1 != x2 && y1 != y2) // duong xien
{
while (x != x2 + 1)
{
delay(1);
c2 = 2 * c;
if (c2 > -Dy)
{
c = c - Dy;
x = x + x_unit;
}
if (c2 < Dx)
{
c = c + Dx;
y = y + y_unit;
}
putpixel(x, y, GREEN);
}
}
}
int main(){
int x1,y1,x2,y2;
int gd,gm=VGAMAX; gd=DETECT;
initgraph(&gd,&gm,NULL);
lineBresenham_1(250, 300,250,100);
getch();
//delay(2);
closegraph();
return 0;
}
|
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
std::string ver_string(int a, int b, int c) {
std::ostringstream t;
t << a << '.' << b << '.' << c;
return t.str();
}
std::string true_cxx =
#ifdef __clang__
"clang++";
#else
"g++";
#endif
std::string true_cxx_ver =
#ifdef __clang__
ver_string(__clang_major__, __clang_minor__, __clang_patchlevel__);
#else
ver_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
#endif
void showVersion() {
std::cout << true_cxx << ": " << true_cxx_ver << std::endl;
}
int main() {
showVersion();
return 0;
}
|
#include "ItemLadderLR.h"
#include "Mario.h"
ItemLadderLR* ItemLadderLR::create(CCDictionary* dict)
{
ItemLadderLR* ret = new ItemLadderLR;
ret->init(dict);
ret->autorelease();
return ret;
}
bool ItemLadderLR::init(CCDictionary* dict)
{
Item::init();
_type = Item::IT_LadderLR;
setPositionByProperty(dict);
// 梯子的显示
CCTexture2D* texture = CCTextureCache::sharedTextureCache()->addImage("ladder.png");
setTexture(texture);
setTextureRect(CCRectMake(0, 0, texture->getContentSize().width, texture->getContentSize().height));
Common::moveNode(this, ccp(-texture->getContentSize().width / 2, 0));
// 属性
_LorR = 1-dict->valueForKey("LorR")->intValue(); // 一开始向左还是向右
_ladderDis = dict->valueForKey("ladderDis")->intValue(); // 摆动的幅度
// 梯子一个回合已经移动过的距离
_dis = 0;
// 梯子移动速度
_speed = 20;
// 标记mario在我这个梯子上
_marioOnThisLadder = false;
return true;
}
void ItemLadderLR::move(float dt)
{
// 移动
if (_LorR) // 向左
{
Common::moveNode(this, ccp(-dt*_speed, 0));
if (_marioOnThisLadder)
{
Common::moveNode(_mario, ccp(-dt*_speed, 0));
}
}
else
{
Common::moveNode(this, ccp(dt*_speed, 0));
if (_marioOnThisLadder)
{
Common::moveNode(_mario, ccp(dt*_speed, 0));
}
}
// 累加移动的距离,判断转向
_dis += dt*_speed;
if (_dis >= _ladderDis)
{
_LorR = 1 - _LorR;
_dis = 0;
}
}
void ItemLadderLR::collision()
{
CCRect rcMario = _mario->boundingBox();
CCRect rcItem = boundingBox();
if (rcItem.intersectsRect(rcMario))
{
// 脑袋撞上了
if (_mario->_speedUp > 0)
{
_mario->_speedDown = 10;
_mario->_speedUp = 0;
}
else
{
// 刚落地
if (_mario->_status ==Mario::FLY)
{
_mario->_onLadder = true;
_marioOnThisLadder = true;
_mario->setPositionY(rcItem.getMaxY());
}
}
}
else
{
if (_marioOnThisLadder)
{
_marioOnThisLadder = false;
_mario->_onLadder = false;
}
}
}
|
#pragma once
#include "ActionSingleTarget.h"
class FightingCharacter;
class Canvas;
class ActionDefend : public ActionSingleTarget
{
public:
ActionDefend(FightingCharacter *fc):
ActionSingleTarget(fc,NULL)
{
}
virtual void preproccess()
{
}
virtual void postExecute()
{
}
virtual bool isTargetAlive()
{
return true;
}
virtual bool isTargetsMoreThanOne()
{
return false;
}
virtual bool targetIsMonster()
{
return true;
}
virtual int getPriority()
{
// TODO Auto-generated method stub
return ActionSingleTarget::getPriority();
}
virtual bool update(long delta)
{
return false;
}
virtual void draw(Canvas *canvas)
{
}
};
|
#pragma once
#include <string>
#include <Windows.h>
template <typename T>
class Interface
{
public:
typedef void*(*CreateInterfaceFn)(const char*, int*);
static T* Get(const std::string& dllName, const std::string& fullName)
{
static T* intyface = nullptr;
if (intyface)
return intyface;
void* dll = nullptr;
while (true)
{
dll = (void*)GetModuleHandle(dllName.c_str());
if (dll)
break;
}
std::string createInterface("CreateInterface");
CreateInterfaceFn factory = (CreateInterfaceFn)GetProcAddress((HMODULE)dll, createInterface.c_str());
intyface = reinterpret_cast<T*>(factory(fullName.c_str(), nullptr));
return intyface;
}
};
|
//! Bismillahi-Rahamanirahim.
/** ========================================**
** @Author: Md. Abu Farhad ( RUET, CSE'15)
** @Category:
/** ========================================**/
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define scl(n) scanf("%lld", &n)
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
int main()
{
ll m,n,t=1,c,d,i,j,k,x,y,z,l,q,r;
ll cnt=0,sum=0;
scl(n);scl(m);
ll a[n], b[m];
fr1(i,n)cin>>a[i];
fr(i, m)
{
cin>>x;
while(sum+a[t]< x)sum+=a[t++];
cout<<sum<<endl;
printf("%lld %lld\n", t, x-sum);
}
return 0;
}
|
#include <bits/stdc++.h>
#include <cassert>
#define rep(i, N) for (int i = 0; i < (N); ++i)
#define rep2(i, a, b) for (ll i = a; i <= b; ++i)
#define rep3(i, a, b) for (ll i = a; i >= b; --i)
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define all(c) begin(c), end(c)
#define ok() puts(ok ? "Yes" : "No");
template <class T> bool chmax(T &a, const T &b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T> bool chmin(T &a, const T &b) {
if (a > b) {
a = b;
return true;
}
return false;
}
using namespace std;
using ll = long long;
using vi = vector<int>;
using vll = vector<ll>;
using ii = pair<int, int>;
using vvi = vector<vi>;
using vii = vector<ii>;
using gt = greater<int>;
using minq = priority_queue<int, vector<int>, gt>;
using P = pair<ll, ll>;
const ll LINF = 1e18L + 1;
const int INF = 1e9 + 1;
// clang++ -std=c++11 -stdlib=libc++
int H, W, N, M;
int wall[1505][1505];
int used[1505][1505];
int processed[1505][1505][5];
vii lights;
int main() {
cin >> H >> W >> N >> M;
rep(i, N) {
int a, b;
cin >> a >> b;
a--;
b--;
lights.eb(a, b);
}
rep(i, M) {
int a, b;
cin >> a >> b;
a--;
b--;
wall[a][b] = 1;
}
int ans = 0;
rep(i, N) {
auto [y, x] = lights[i];
used[y][x] = 1;
for (int r = x + 1; r < W; r++) {
if (wall[y][r])
break;
used[y][r] = 1;
if (processed[y][r][0])
break;
processed[y][r][0] = 1;
}
for (int l = x - 1; l >= 0; l--) {
if (wall[y][l])
break;
used[y][l] = 1;
if (processed[y][l][1])
break;
processed[y][l][1] = 1;
}
for (int u = y - 1; u >= 0; u--) {
if (wall[u][x])
break;
used[u][x] = 1;
if (processed[u][x][2])
break;
processed[u][x][2] = 1;
}
for (int d = y + 1; d < H; d++) {
if (wall[d][x])
break;
used[d][x] = 1;
if (processed[d][x][3])
break;
processed[d][x][3] = 1;
}
}
rep(i, N) { i++; }
rep(i, H) rep(j, W) if (used[i][j]) ans++;
cout << ans << endl;
return 0;
}
|
#include "test/helpers.h"
#include "test/net/helpers.h"
#include <sstream>
#include <algorithm>
using namespace std;
using namespace inexor::net;
bytes mkpkg(size_t size) {
bytes r(size);
rndcopy(&r[0], size);
return r;
}
bytes mcbytebuffer_encode(bytes &msg) {
stringstream ss; // TODO: Could do this quicker with custom subclass!
MCStreamChopper chop(&ss, NULL);
chop.Send(msg);
string rs = ss.str();
return bytes(rs.begin(), rs.end());
}
|
/* Copyright (C)
* 2019 - Bhargav Dandamudi
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the 'Software'), to deal in the Software without
* restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so,subject to
* the following conditions:
* The above copyright notice and this permission notice shall
* be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED ''AS IS'', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH
* THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
/**
* @file samppoints.h
* @brief Data structure containing all the points with parameters
* stored for calculations
* @author Bhargav Dandamudi
* @version 1
* @date 2019-03-30
*/
#ifndef SAMPPOINTS_H
#define SAMPPOINTS_H
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
#include <vector>
class samppoints {
public:
int n;
std::vector<double> X; // dynamic array ,space is allocated in the constructors
std::vector<double> Y; // dynamic array space is allocated in the constructors
double meanX, meanY;
// constructors for the data class
samppoints();
samppoints(int N);
samppoints(int N, std::vector<double> X, std::vector<double> Y);
// parameter calculation
void means(void);
void center(void);
void scale(void);
// void print(void);
// destructors
~samppoints();
};
#endif // SAMPPOINTS_H
|
#ifndef _RAVE_UTILS_H__
#define _RAVE_UTILS_H__
#include <iostream>
#include <Eigen/Eigen>
using namespace Eigen;
#include <openrave-core.h>
namespace rave = OpenRAVE;
namespace rave_utils {
Matrix4d transform_from_to(rave::RobotBasePtr robot, const Matrix4d& mat_in_ref, std::string ref_link_name, std::string targ_link_name);
void cart_to_joint(rave::RobotBase::ManipulatorPtr manip, const rave::Transform &matrix4,
const std::string &ref_frame, const std::string &targ_frame, std::vector<double> &joint_values,
const int filter_options=0);
rave::Transform transform_relative_pose_for_ik(rave::RobotBase::ManipulatorPtr manip,
const rave::Transform &matrix4, const std::string &ref_frame, const std::string &targ_frame);
void clear_plots(int num=-1);
void plot_point(rave::EnvironmentBasePtr env, rave::Vector pos, rave::Vector color, float size=.01);
void plot_point(rave::EnvironmentBasePtr env, Vector3d pos, Vector3d color, float size=.01);
void plot_segment(rave::EnvironmentBasePtr env, const Vector3d& p0, const Vector3d& p1, Vector3d& color);
void plot_transform(rave::EnvironmentBasePtr env, rave::Transform T, float length=0.1);
void save_view(rave::ViewerBasePtr viewer, std::string file_name);
inline Matrix4d rave_to_eigen(const rave::Transform& rt) {
rave::TransformMatrix rtm(rt);
Matrix4d m = Matrix4d::Identity();
int index = 0;
for(int i=0; i < 3; ++i) {
for(int j=0; j < 4; ++j) {
m(i,j) = rtm.m[index++];
}
}
for(int i=0; i < 3; ++i) {
m(i, 3) = rtm.trans[i];
}
return m;
}
inline rave::Transform eigen_to_rave(const Matrix4d& m) {
rave::TransformMatrix rtm;
int index = 0;
for(int i=0; i < 3; ++i) {
for(int j=0; j < 4; ++j) {
rtm.m[index++] = m(i,j);
}
}
for(int i=0; i < 3; ++i) {
rtm.trans[i] = m(i,3);
}
rave::Transform rt(rtm);
return rt;
}
inline Vector3d rave_to_eigen(const rave::Vector& v) {
return Vector3d(v.x, v.y, v.z);
}
inline rave::Vector eigen_to_rave(const Vector3d& m) {
return rave::Vector(m(0), m(1), m(2));
}
}
#endif
|
#include <particle_structs.hpp>
#include "read_particles.hpp"
#include <stdlib.h>
#include <CSR.hpp>
#include <MemberTypes.h>
#include <MemberTypeLibraries.h>
#include <ppTypes.h>
#include <psMemberType.h>
#include "Distribute.h"
#ifdef PP_USE_CUDA
typedef Kokkos::CudaSpace DeviceSpace;
#else
typedef Kokkos::HostSpace DeviceSpace;
#endif
int comm_rank, comm_size;
//using particle_structs::CSR;
using particle_structs::MemberTypes;
using particle_structs::getLastValue;
using particle_structs::lid_t;
typedef Kokkos::DefaultExecutionSpace exe_space;
typedef MemberTypes<int> Type;
typedef particle_structs::CSR<Type> CSR;
bool rebuildNoChanges(int ne_in, int np_in,int distribution);
bool rebuildNewElems(int ne_in, int np_in,int distribution);
bool rebuildNewPtcls(int ne_in, int np_in,int distribution);
bool rebuildPtclsDestroyed(int ne_in, int np_in,int distribution);
bool rebuildNewAndDestroyed(int ne_in, int np_in,int distribution);
int main(int argc, char* argv[]){
Kokkos::initialize(argc,argv);
MPI_Init(&argc,&argv);
//count of fails
int fails = 0;
//begin Kokkos scope
{
MPI_Comm_rank(MPI_COMM_WORLD,&comm_rank);
MPI_Comm_size(MPI_COMM_WORLD,&comm_size);
if(argc != 4){
printf("[ERROR] Too few command line arguments (%d supplied, 4 required)\n", argc);
return 1;
}
int number_elements = atoi(argv[1]);
int number_particles = atoi(argv[2]);
int distribution = atoi(argv[3]);
printf("Rebuild CSR Test: \nne = %d\nnp = %d\ndistribtuion = %d\n",
number_elements, number_particles, distribution);
///////////////////////////////////////////////////////////////////////////
//Tests to run go here
///////////////////////////////////////////////////////////////////////////
//verify still correct elements and no changes otherwise
fprintf(stderr,"RebuildNoChanges\n");
fails += rebuildNoChanges(number_elements,number_particles,distribution);
//verify all elements are correctly assigned to new elements
fprintf(stderr,"RebuildNewElems\n");
fails += rebuildNewElems(number_elements,number_particles,distribution);
//check new elements are added properly and all elements assgined correct
fprintf(stderr,"RebuildNewPtcls\n");
fails += rebuildNewPtcls(number_elements,number_particles,distribution);
//check for particles that were removed and the rest in their correct loc
fprintf(stderr,"RebuildPtclsDestroyed\n");
fails += rebuildPtclsDestroyed(number_elements,number_particles,distribution);
//complete check of rebuild functionality
fprintf(stderr,"RebuildNewAndDestroyed\n");
fails += rebuildNewAndDestroyed(number_elements,number_particles,distribution);
}
//end Kokkos scope
Kokkos::finalize();
MPI_Finalize();
return fails;
}
//Rebuild test with no changes to structure
bool rebuildNoChanges(int ne_in, int np_in,int distribution){
Kokkos::Profiling::pushRegion("rebuildNoChanges");
int fails = 0;
//Test construction based on SCS testing
int ne = ne_in;
int np = np_in;
int* ptcls_per_elem = new int[ne];
std::vector<int>* ids = new std::vector<int>[ne];
distribute_particles(ne, np, distribution, ptcls_per_elem, ids);
Kokkos::TeamPolicy<exe_space> po(32,Kokkos::AUTO);
CSR::kkLidView ptcls_per_elem_v("ptcls_per_elem_v",ne);
CSR::kkGidView element_gids_v("",0);
particle_structs::hostToDevice(ptcls_per_elem_v,ptcls_per_elem);
//Structure to perform rebuild on
CSR* csr = new CSR(po, ne, np, ptcls_per_elem_v, element_gids_v);
delete [] ptcls_per_elem;
delete [] ids;
CSR::kkLidView new_element("new_element", csr->capacity());
//pID = particle ID
//Gives access to MTV data to set an identifier for each ptcl
auto pID = csr->get<0>();
//Sum of the particles in each element
CSR::kkLidView element_sums("element_sums", csr->nElems());
//Assign values to ptcls to track their movement
auto setSameElement = PS_LAMBDA(const lid_t e, const lid_t p, const bool mask) {
if (mask) {
new_element(p) = e;
Kokkos::atomic_add(&(element_sums(e)), p);
}
else
new_element(p) = -1;
pID(p) = p;
};
ps::parallel_for(csr, setSameElement, "setSameElement");
//Rebuild with no changes (function takes second and third args as optional)
csr->rebuild(new_element);
//(Necessary) updates of pID
pID = csr->get<0>();
if (csr->nPtcls() != np) {
fprintf(stderr, "[ERROR] CSR does not have the correct number of particles after "
"rebuild %d (should be %d)\n", csr->nPtcls(), np);
++fails;
}
//Sum of the particles in each element
CSR::kkLidView new_element_sums("new_element_sums", csr->nElems());
kkLidView failed = kkLidView("failed", 1);
auto checkSameElement = PS_LAMBDA(const lid_t e, const lid_t p, const bool mask) {
const lid_t id = pID(p);
const lid_t dest_elem = new_element(id);
if (mask) {
Kokkos::atomic_add(&(new_element_sums[e]), id);
if (dest_elem != e) {
printf("[ERROR] Particle %d was moved to incorrect element %d "
"(should be in element %d)\n", id, e, dest_elem);
failed(0) = 1;
}
}
};
ps::parallel_for(csr, checkSameElement, "checkSameElement");
fails += getLastValue<lid_t>(failed);
CSR::kkLidView failed2("failed2", 1);
auto checkElementSums = KOKKOS_LAMBDA(const int i) {
const lid_t old_sum = element_sums(i);
const lid_t new_sum = new_element_sums(i);
if (old_sum != new_sum) {
printf("Sum of particle ids on element %d do not match. Old: %d New: %d\n",
i, old_sum, new_sum);
failed2(0) = 1;
}
};
Kokkos::parallel_for(csr->nElems(), checkElementSums, "checkElementSums");
fails += getLastValue<lid_t>(failed);
Kokkos::Profiling::popRegion();
return fails;
}
//Rebuild test with no new particles, but reassigned particle elements
bool rebuildNewElems(int ne_in, int np_in,int distribution){
Kokkos::Profiling::pushRegion("rebuildNewElems");
int fails = 0;
//Test construction based on SCS testing
int ne = ne_in;
int np = np_in;
int* ptcls_per_elem = new int[ne];
std::vector<int>* ids = new std::vector<int>[ne];
distribute_particles(ne, np, distribution, ptcls_per_elem, ids);
Kokkos::TeamPolicy<exe_space> po(32,Kokkos::AUTO);
CSR::kkLidView ptcls_per_elem_v("ptcls_per_elem_v",ne);
CSR::kkGidView element_gids_v("",0);
particle_structs::hostToDevice(ptcls_per_elem_v,ptcls_per_elem);
CSR* csr = new CSR(po, ne, np, ptcls_per_elem_v, element_gids_v);
delete [] ptcls_per_elem;
delete [] ids;
CSR::kkLidView new_element("new_element", csr->capacity());
auto pID = csr->get<0>();
//Sum of the particles in each element
CSR::kkLidView element_sums("element_sums", csr->nElems());
//Assign ptcl identifiers
auto setElement = PS_LAMBDA(const lid_t e, const lid_t p, const bool mask) {
if (mask) {
new_element(p) = (e*3 + p) % ne; //assign to diff elems
Kokkos::atomic_add(&(element_sums(new_element(p))), p);
}
else
new_element(p) = -1;
pID(p) = p;
};
ps::parallel_for(csr, setElement, "setElement");
//Rebuild with no changes
csr->rebuild(new_element);
if (csr->nPtcls() != np) {
fprintf(stderr, "[ERROR] CSR does not have the correct number of particles after "
"rebuild %d (should be %d)\n", csr->nPtcls(), np);
++fails;
}
//(Necessary) update of pID
pID = csr->get<0>();
//Sum of the particles in each element
CSR::kkLidView new_element_sums("new_element_sums", csr->nElems());
kkLidView failed = kkLidView("failed", 1);
auto checkElement = PS_LAMBDA(const lid_t e, const lid_t p, const bool mask) {
const lid_t id = pID(p);
const lid_t dest_elem = new_element(id);
if (mask) {
Kokkos::atomic_add(&(new_element_sums[e]), id);
if (dest_elem != e) {
printf("[ERROR] Particle %d was moved to incorrect element %d "
"(should be in element %d)\n", id, e, dest_elem);
failed(0) = 1;
}
}
};
ps::parallel_for(csr, checkElement, "checkElement");
fails += getLastValue<lid_t>(failed);
CSR::kkLidView failed2("failed2", 1);
auto checkElementSums = KOKKOS_LAMBDA(const int i) {
const lid_t old_sum = element_sums(i);
const lid_t new_sum = new_element_sums(i);
if (old_sum != new_sum) {
printf("Sum of particle ids on element %d do not match. Old: %d New: %d\n",
i, old_sum, new_sum);
failed2(0) = 1;
}
};
Kokkos::parallel_for(csr->nElems(), checkElementSums, "checkElementSums");
fails += getLastValue<lid_t>(failed);
Kokkos::Profiling::popRegion();
return fails;
}
//Rebuild test with new particles added only
bool rebuildNewPtcls(int ne_in, int np_in,int distribution){
Kokkos::Profiling::pushRegion("rebuildNewPtcls");
int fails = 0;
//Test construction based on SCS testing
int ne = ne_in;
int np = np_in;
int* ptcls_per_elem = new int[ne];
std::vector<int>* ids = new std::vector<int>[ne];
distribute_particles(ne, np, distribution, ptcls_per_elem, ids);
Kokkos::TeamPolicy<exe_space> po(32,Kokkos::AUTO);
CSR::kkLidView ptcls_per_elem_v("ptcls_per_elem_v",ne);
CSR::kkGidView element_gids_v("",0);
particle_structs::hostToDevice(ptcls_per_elem_v,ptcls_per_elem);
CSR* csr = new CSR(po, ne, np, ptcls_per_elem_v, element_gids_v);
delete [] ptcls_per_elem;
delete [] ids;
CSR::kkLidView new_element("new_element", csr->capacity());
auto pID = csr->get<0>();
//Assign ptcl identifiers
auto setElement = PS_LAMBDA(const lid_t e, const lid_t p, const bool mask) {
if (mask)
new_element(p) = (e*3 + p + 2) % ne; //assign to diff elems
else
new_element(p) = -1;
pID(p) = p;
};
ps::parallel_for(csr, setElement, "setElement");
//////////////////////////////////////////////////////////////
//Introduce new particles
int nnp = 5; //number new ptcls
CSR::kkLidView new_particle_elements("new_particle_elements", nnp);
auto new_particles = particle_structs::createMemberViews<Type>(nnp);
auto new_particle_access = particle_structs::getMemberView<Type,0>(new_particles);
lid_t cap = csr->capacity();
//Assign new ptcl elements and identifiers
Kokkos::parallel_for("new_particle_elements", nnp,
KOKKOS_LAMBDA (const int& i){
new_particle_elements(i) = i%ne;
new_particle_access(i) = i+cap;
});
//Rebuild with new ptcls
csr->rebuild(new_element, new_particle_elements, new_particles);
if (csr->nPtcls() != np + nnp) {
fprintf(stderr, "[ERROR] CSR does not have the correct number of particles after "
"rebuild with new particles %d (should be %d)\n", csr->nPtcls(), np + nnp);
++fails;
}
pID = csr->get<0>(); //new size
kkLidView failed = kkLidView("failed", 1);
auto checkElement = PS_LAMBDA(const lid_t e, const lid_t p, const bool mask) {
const lid_t id = pID(p);
if (mask) {
if (id < cap) { //Check old particles
const lid_t dest_elem = new_element(id);
if (dest_elem != e) {
printf("[ERROR] Particle %d was moved to incorrect element %d "
"(should be in element %d)\n", id, e, dest_elem);
failed(0) = 1;
}
}
else { //Check new particles
const lid_t i = id - cap;
const lid_t dest_elem = new_particle_elements(i);
if (e != dest_elem) {
printf("[ERROR] New particle %d was added to incorrect element %d "
"(should be in element %d)\n", id, e, dest_elem);
failed(0) = 1;
}
}
}
};
fails += getLastValue<lid_t>(failed);
Kokkos::Profiling::popRegion();
return fails;
}
//Rebuild test with existing particles destroyed only
bool rebuildPtclsDestroyed(int ne_in, int np_in,int distribution){
Kokkos::Profiling::pushRegion("rebuildPtclsDestroyed");
int fails = 0;
//Test construction based on SCS testing
int ne = ne_in;
int np = np_in;
int* ptcls_per_elem = new int[ne];
std::vector<int>* ids = new std::vector<int>[ne];
distribute_particles(ne, np, distribution, ptcls_per_elem, ids);
Kokkos::TeamPolicy<exe_space> po(32,Kokkos::AUTO);
CSR::kkLidView ptcls_per_elem_v("ptcls_per_elem_v",ne);
CSR::kkGidView element_gids_v("",0);
particle_structs::hostToDevice(ptcls_per_elem_v,ptcls_per_elem);
CSR* csr = new CSR(po, ne, np, ptcls_per_elem_v, element_gids_v);
delete [] ptcls_per_elem;
delete [] ids;
CSR::kkLidView new_element("new_element", csr->capacity());
auto pID = csr->get<0>();
CSR::kkLidView num_removed("num_removed", 1);
//Remove every 7th particle, keep other particles in same element
auto assign_ptcl_elems = PS_LAMBDA(const int& e, const int& p, const bool mask){
new_element(p) = e;
if(p%7 == 0) {
new_element(p) = -1;
Kokkos::atomic_add(&(num_removed(0)), 1);
}
pID(p) = p;
};
csr->parallel_for(assign_ptcl_elems, "assing ptcl elems");
int nremoved = pumipic::getLastValue(num_removed);
//Rebuild with particles removed
csr->rebuild(new_element);
if (csr->nPtcls() != np - nremoved) {
fprintf(stderr, "[ERROR] CSR does not have the correct number of particles after "
"rebuild after removing particles %d (should be %d)\n",
csr->nPtcls(), np - nremoved);
++fails;
}
pID = csr->get<0>();
lid_t particles = csr->capacity();
kkLidView failed = kkLidView("failed", 1);
auto checkElement = PS_LAMBDA(const lid_t e, const lid_t p, const bool mask) {
const lid_t id = pID(p);
const lid_t dest_elem = new_element(id);
if (mask) {
if (dest_elem != e) {
printf("[ERROR] Particle %d was moved to incorrect element %d "
"(should be in element %d)\n", id, e, dest_elem);
failed(0) = 1;
}
if (id % 7 == 0) {
printf("[ERROR] Particle %d was not removed during rebuild\n", id);
failed(0) = 1;
}
}
};
ps::parallel_for(csr, checkElement, "checkElement");
fails += getLastValue<lid_t>(failed);
Kokkos::Profiling::popRegion();
return fails;
}
//Rebuild test with particles added and destroyed
bool rebuildNewAndDestroyed(int ne_in, int np_in,int distribution){
Kokkos::Profiling::pushRegion("rebuildNewAndDestroyed");
int fails = 0;
//Test construction based on SCS testing
int ne = ne_in;
int np = np_in;
int* ptcls_per_elem = new int[ne];
std::vector<int>* ids = new std::vector<int>[ne];
distribute_particles(ne, np, distribution, ptcls_per_elem, ids);
Kokkos::TeamPolicy<exe_space> po(32,Kokkos::AUTO);
CSR::kkLidView ptcls_per_elem_v("ptcls_per_elem_v",ne);
CSR::kkGidView element_gids_v("",0);
particle_structs::hostToDevice(ptcls_per_elem_v,ptcls_per_elem);
CSR* csr = new CSR(po, ne, np, ptcls_per_elem_v, element_gids_v);
delete [] ptcls_per_elem;
delete [] ids;
CSR::kkLidView new_element("new_element", csr->capacity());
auto pID = csr->get<0>();
CSR::kkLidView num_removed("num_removed", 1);
//Remove every 7th particle and move others to new element
auto assign_ptcl_elems = PS_LAMBDA(const int& e, const int& p, const bool mask){
if (mask) {
new_element(p) = (3*e+7)%ne;
if(p%7 == 0) {
new_element(p) = -1;
Kokkos::atomic_add(&(num_removed(0)), 1);
}
pID(p) = p;
}
};
csr->parallel_for(assign_ptcl_elems, "assing ptcl elems");
int nremoved = pumipic::getLastValue(num_removed);
//////////////////////////////////////////////////////////////
//Introduce new particles
int nnp = 5;
CSR::kkLidView new_particle_elements("new_particle_elements", nnp);
auto new_particles = particle_structs::createMemberViews<Type>(nnp);
auto new_particle_access = particle_structs::getMemberView<Type,0>(new_particles);
lid_t cap = csr->capacity();
Kokkos::parallel_for("new_particle_elements", nnp,
KOKKOS_LAMBDA (const int& i){
new_particle_elements(i) = i%ne;
new_particle_access(i) = i+cap;
});
//Rebuild with elements removed
csr->rebuild(new_element,new_particle_elements,new_particles);
if (csr->nPtcls() != np + nnp - nremoved) {
fprintf(stderr, "[ERROR] CSR does not have the correct number of particles after "
"rebuild with new and removed particles %d (should be %d)\n",
csr->nPtcls(), np + nnp - nremoved);
++fails;
}
pID = csr->get<0>();
//need variable here bc can't access csr on device
const lid_t new_cap = csr->capacity();
kkLidView failed = kkLidView("failed", 1);
auto checkElement = PS_LAMBDA(const lid_t e, const lid_t p, const bool mask) {
const lid_t id = pID(p);
if (mask) {
if (id < cap) { //Check old particles
const lid_t dest_elem = new_element(id);
if (dest_elem != e) {
printf("[ERROR] Particle %d was moved to incorrect element %d "
"(should be in element %d)\n", id, e, dest_elem);
failed(0) = 1;
}
if (id % 7 == 0) { //Check removed particles
printf("[ERROR] Particle %d was not removed during rebuild\n", id);
failed(0) = 1;
}
}
else { //Check new particles
const lid_t i = id - cap;
const lid_t dest_elem = new_particle_elements(i);
if (e != dest_elem) {
printf("[ERROR] New particle %d was added to incorrect element %d "
"(should be in element %d)\n", id, e, dest_elem);
failed(0) = 1;
}
}
}
};
ps::parallel_for(csr, checkElement, "checkElement");
fails += getLastValue<lid_t>(failed);
Kokkos::Profiling::popRegion();
return fails;
}
|
#define STRICT
#define ORBITER_MODULE
#include <windows.h>
#include <stdio.h>
#include <math.h>
#include <orbitersdk.h>
#include "CruiseMFD.h"
#include <oicominit.h>
int mode; // identifier for new MFD mode
double setpoint=10.; // m/s setpoint for cruise
bool active = false, init=false;
OICOM_PID pid=0, cruisepid; // our plugin ID
DLLCLBK void InitModule (HINSTANCE hDLL)
{
// OICOM initialization
int ret = OICOM::GetOrbiterIntercom();
// this MFD is done very quickly for demonstration purposes
// I didn't want fluff to get in the way of demonstrating how
// the library is supposed to work. But for
// implementations of the MFD that take in account
// mulitple vessel instances (ie. storing mfd internal data, giving each vessel its own MFD)
// you can register the plugin with any naming scheme, like vesselname_oicomCruiseMFD etc etc
pid=OICOM::addPlugin("OicomCruiseMFD");
static char *name = "OICOM Cruise MFD";
MFDMODESPECEX spec;
spec.name = name;
spec.key = OAPI_KEY_C;
spec.context = NULL;
spec.msgproc = CruiseMFD::MsgProc;
mode = oapiRegisterMFDMode (spec);
}
DLLCLBK void ExitModule (HINSTANCE hDLL)
{
oapiUnregisterMFDMode (mode);
}
// get the id for the cruise module
// that module provides the actual "autopilot" code
// this is just the interface
// this should really be done in opcOpenRenderViewport
// but I can't remember the parameter list right now :P
// since the initialization for modules occurs at InitModule,
// this way we are sure the module we are targetting will be initialized
DLLCLBK void opcPreStep (double simt, double simdt, double mjd)
{
if ( !init )
{
// get the plug-in ID for future communication
cruisepid = OICOM::getPlugin("oicomcruisemodule");
// link up state variables
OICOM::sendMessage(cruisepid, "link_state", &active, sizeof(bool));
OICOM::sendMessage(cruisepid, "link_setpoint", &setpoint, sizeof(double*));
init=true;
}
}
CruiseMFD::CruiseMFD (DWORD w, DWORD h, VESSEL *vessel)
: MFD (w, h, vessel)
{
width=w/35;
height=h/24;
}
CruiseMFD::~CruiseMFD ()
{
}
// message parser
int CruiseMFD::MsgProc (UINT msg, UINT mfd, WPARAM wparam, LPARAM lparam)
{
switch (msg) {
case OAPI_MSG_MFD_OPENEDEX: {
MFDMODEOPENSPEC *ospec = (MFDMODEOPENSPEC*)wparam;
return (int)(new CruiseMFD (ospec->w, ospec->h, (VESSEL*)lparam));
}
}
return 0;
}
bool getSetpoint (void *id, char *str, void *data)
{
if ( strlen(str) == 0 )
return false;
setpoint=atof(str);
return true;
}
bool CruiseMFD::ConsumeKeyBuffered (DWORD key)
{
switch (key)
{
case OAPI_KEY_S:
oapiOpenInputBox ("Enter setpoint m/s:", getSetpoint, 0, 20, 0);
return true;
case OAPI_KEY_T:
{
active=!active;
return true;
}
}
return false;
}
bool CruiseMFD::ConsumeButton (int bt, int event)
{
if (!(event & PANEL_MOUSE_LBDOWN)) return false;
static const DWORD btkey[2] = { OAPI_KEY_S, OAPI_KEY_T };
if (bt < 2) return ConsumeKeyBuffered (btkey[bt]);
else return false;
}
char *CruiseMFD::ButtonLabel (int bt)
{
char *label[2] = {"SP", "TGL"};
return (bt < 2 ? label[bt] : 0);
}
int CruiseMFD::ButtonMenu (const MFDBUTTONMENU **menu) const
{
static const MFDBUTTONMENU mnu[2] = {
{"set the setpoint", 0, 'S'},
{"Toggle cruise", 0, 'T'}
};
if (menu) *menu = mnu;
return 2;
}
void CruiseMFD::Update (HDC hDC)
{
Title (hDC, "OICOM Cruise MFD");
int len;
char buffer[256];
int y = height*2;
len = sprintf(buffer, "state: %s", (active?"active":"deactive"));
TextOut(hDC, width, y, buffer, len);
y+=height*1;
len = sprintf(buffer, "sp : %.2f m/s", setpoint);
TextOut(hDC, width, y, buffer, len);
}
|
/***************************************************************************
Copyright (c) 2020 Philip Fortier
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.
***************************************************************************/
#pragma once
#include "ResourceUtil.h"
#include "NonViewHostDocument.h"
class ResourceEntity;
//
// CResourceDocument document
//
// Documents that represent a particular SCI resource should inherit from this.
// It provides saving/export functionality that is common across resource types.
//
class CResourceDocument : public CNonViewHostDocument, public IResourceIdentifier
{
DECLARE_DYNAMIC(CResourceDocument)
public:
CResourceDocument() { _checksum = -1; _fMostRecent = true; _needsResourceSizeUpdate = true; }
BOOL CanCloseFrame(CFrameWnd* pFrameArg);
virtual BOOL SaveModified(); // return TRUE if ok to continue
void OnFileSave();
void OnFileSaveAs();
// This returns a const pointer - we should never manipulate the resource via this.
virtual const ResourceEntity *GetResource() const = 0;
// IResourceIdentifier
int GetPackageHint() const override;
int GetNumber() const override;
uint32_t GetBase36() const override;
ResourceType GetType() const override;
int GetChecksum() const override { return _checksum; }
bool IsMostRecent() const;
void SetModifiedFlag(BOOL bModified = TRUE) override;
private:
afx_msg void OnUpdateFileSave(CCmdUI *pCmdUI) { pCmdUI->Enable(IsModified()) ; }
afx_msg void OnUpdateResSize(CCmdUI *pCmdUI);
BOOL DoPreResourceSave(BOOL fSaveAs);
void OnExportAsResource();
protected:
void OnExportAsBitmap();
BOOL _DoResourceSave(int iPackageNumber, int iResourceNumber, const std::string &name);
void _UpdateTitle();
afx_msg void OnUpdateAlwaysOn(CCmdUI *pCmdUI) { pCmdUI->Enable() ; }
// Override to prevent saving (by returning false)
virtual bool v_DoPreResourceSave() { return true; }
virtual void _OnSuccessfulSave(const ResourceEntity *pResource) {};
virtual ResourceType _GetType() const = 0;
// Disabled until we see what people are doing with this
// virtual PCTSTR _GetFileNameDefault() { return g_resourceInfo[(int)_GetType()].pszFileNameDefault; }
virtual PCTSTR _GetTitleDefault() { return g_resourceInfo[(int)_GetType()].pszTitleDefault; }
virtual std::string _GetFileDialogFilter();
DECLARE_MESSAGE_MAP()
int _checksum;
bool _fMostRecent;
bool _needsResourceSizeUpdate;
std::string _resSize;
};
|
#include "GameWidget.h"
#include <QMouseEvent>
#include <QDebug>
#include <math.h>
#include "Model.h"
#include <QFont>
#include <QKeyEvent>
GameWidget::GameWidget(int width, int height, const Model* model, QWidget *parent) :
QWidget(parent), m_model(model)
{
this->resize(width, height);
m_leftCoordinateBoardX = 974 * width / 1920;
m_leftCoordinateBoardY = 141 * height / 1080;
m_distance = qRound((double) 57 * width / 1920);
m_fishCenter = qRound((double) 27 * width / 1920);
QImage image("images/Game/board.png");
QImage white("images/Game/white.png");
QImage black("images/Game/black.png");
QImage whiteLast("images/Game/white_last.png");
QImage blackLast("images/Game/black_last.png");
m_whiteImage = white;
m_blackImage = black;
m_whiteLastImage = whiteLast;
m_blackLastImage = blackLast;
m_whiteImage = m_whiteImage.scaled(white.size().width() * width / 1920,
white.size().height() * height / 1080,
Qt::KeepAspectRatio);
m_blackImage = m_blackImage.scaled(black.size().width() * width / 1920,
black.size().height() * height / 1080,
Qt::KeepAspectRatio);
m_whiteLastImage = m_whiteLastImage.scaled(whiteLast.size().width() * width / 1920,
whiteLast.size().height() * height / 1080,
Qt::KeepAspectRatio);
m_blackLastImage = m_blackLastImage.scaled(blackLast.size().width() * width / 1920,
blackLast.size().height() * height / 1080,
Qt::KeepAspectRatio);
m_lastMove = 0;
m_background = new QLabel(this);
m_background->setPixmap(QPixmap::fromImage(image.scaled(this->size(),Qt::IgnoreAspectRatio)));
m_whitePlayerLbl = new QLabel(m_background);
m_blackPlayerLbl = new QLabel(m_background);
m_whitePlayerLbl->setPixmap(QPixmap::fromImage(m_whiteImage));
m_blackPlayerLbl->setPixmap(QPixmap::fromImage(m_blackImage));
const int whiteLblX = 20 * width / 1920;
const int whiteLblY = 25 * height / 1080;
const int blackLblX = 20 * width / 1920;
const int blackLblY = 95 * height / 1080;
m_whitePlayerLbl->move(whiteLblX, whiteLblY);
m_blackPlayerLbl->move(blackLblX, blackLblY);
QFont f("Arial", 58 * width / 1920, QFont::DemiBold);
m_clientLogin = new QLabel(m_background);
m_clientLogin->setText(m_model->getLogin());
m_clientLogin->setFont(f);
m_opponentLogin = new QLabel(m_background);
m_opponentLogin->setText(m_model->getOpponentLogin());
m_opponentLogin->setFont(f);
const int loginX = 80 * width / 1920;
const int loginBlackY = 75 * height / 1080;
const int loginWhiteY = 8 * height / 1080;
if (m_model->getFishColor() == BLACK)
{
m_clientLogin->move(loginX,loginBlackY);
m_opponentLogin->move(loginX,loginWhiteY);
}
else
{
m_clientLogin->move(loginX,loginWhiteY);
m_opponentLogin->move(loginX,loginBlackY);
}
m_whitesTimeText = new QLabel(m_background);
m_whitesTimeText->setText(tr("White's time:"));
QFont textFont("Arial", 48 * width / 1920, QFont::Normal);
m_whitesTimeText->setFont(textFont);
m_whitesTimeText->move(20 * width / 1920, 180 * height / 1080);
m_blacksTimeText = new QLabel(m_background);
m_blacksTimeText->setText(tr("Black's time:"));
m_blacksTimeText->setFont(textFont);
m_blacksTimeText->move(490 * width / 1920, 180 * height / 1080);
m_timeWhite = new TimeWidget(280 * width / 1920, 140 * height / 1080, m_model->getMinutesForGame(), m_background);
m_timeWhite->move(20 * width / 1920, 250 * height / 1080);
m_timeBlack = new TimeWidget(280 * width / 1920, 140 * height / 1080, m_model->getMinutesForGame(), m_background);
m_timeBlack->move(540 * width / 1920, 250 * height / 1080);
if (m_model->getFishColor() == WHITE)
{
m_ourTime = m_timeWhite;
m_opponentTime = m_timeBlack;
}
else
{
m_ourTime = m_timeBlack;
m_opponentTime = m_timeWhite;
}
connect(m_opponentTime, SIGNAL(timeout()), this, SLOT(onOpponentTimeOut()));
if (m_model->getStatus() == MOVING)
{
m_ourTime->start();
}
else
{
m_opponentTime->start();
}
m_chat = new QTextEdit(m_background);
m_chat->setReadOnly(true);
m_chat->resize(800 * width / 1920, 400 * height / 1080);
m_chat->move(20 * width / 1920, 400 * height / 1080);
m_chat->setFont(QFont("Times New Roman", 18 * width / 1920, QFont::Normal));
m_chatLine = new QLineEdit(m_background);
m_chatLine->setFont(QFont("Times New Roman", m_chatLine->height() * width / 1920, QFont::Normal));
m_chatLine->resize(800 * width / 1920, 60 * height / 1080);
m_chatLine->move(20* width / 1920, 815 * height / 1080);
connect(m_chatLine, SIGNAL(returnPressed()), this, SLOT(sentMessageToOpponentFromChat()));
//***************************************
// Buttons.
QImage disable("images/Game/disable_chat_1.png");
QImage disableClicked("images/Game/disable_chat_2.png");
const int enterX = 20* width / 1920;
const int enterY = 900 * height / 1080;
m_disableChat = new ButtonLabel(disable.size().width() / 4 * width / 1920, disable.size().height() / 4 * height / 1080,
disable, disableClicked, m_background);
m_disableChat->move(enterX, enterY);
connect(m_disableChat, SIGNAL(clicked()), this, SLOT(disableChat()));
QImage surrender("images/Game/surrender_1.png");
QImage surrenderClicked("images/Game/surrender_2.png");
const int surrenderX = 600* width / 1920;
const int surrenderY = 900* height / 1080;
m_surrender = new ButtonLabel(surrender.size().width() / 4 * width / 1920, surrender.size().height() / 4 * height / 1080,
surrender, surrenderClicked, m_background);
m_surrender->move(surrenderX, surrenderY);
connect(m_surrender, SIGNAL(clicked()), this, SIGNAL(onPlayerSurrender()));
}
GameWidget::~GameWidget()
{
}
void GameWidget::opponentDisabledChat()
{
m_chatLine->setDisabled(true);
m_disableChat->setDisabled(true);
}
void GameWidget::disableChat()
{
m_chatLine->setDisabled(true);
m_disableChat->setDisabled(true);
emit playerDisabledChat();
}
void GameWidget::mousePressEvent(QMouseEvent* ev)
{
if (m_model->getStatus() == WAITING)
return;
int xFromMouse = ev->pos().x();
int yFromMouse = ev->pos().y();
if (xFromMouse >= m_leftCoordinateBoardX && xFromMouse <= (m_leftCoordinateBoardX + m_distance * 14) &&
yFromMouse >= m_leftCoordinateBoardY && yFromMouse <= (m_leftCoordinateBoardY + m_distance * 14))
{
double xPosition = (double) (xFromMouse - m_leftCoordinateBoardX) / m_distance;
double yPosition = (double) (yFromMouse - m_leftCoordinateBoardY) / m_distance;
int xRoundedPosition = (int)qRound(xPosition);
int yRoundedPosition = (int)qRound(yPosition);
if (m_model->getStateOfFish(xRoundedPosition, yRoundedPosition) == EMPTY)
{
emit playerMoved(xRoundedPosition, yRoundedPosition);
}
else
{
qDebug () << "Can't place";
}
}
}
void GameWidget::showEvent(QShowEvent *)
{
m_chatLine->setFocus();
}
void GameWidget::sentMessageToOpponentFromChat()
{
QString msg = m_chatLine->text();
if (msg.isEmpty())
return;
prepareTextEditForPrintingLogin();
m_chat->insertPlainText(m_model->getLogin()+": ");
prepareTextEditForPrintingMessage();
m_chat->insertPlainText(msg+"\n");
m_chat->moveCursor(QTextCursor::End);
m_chatLine->clear();
emit playerSentMessageToOpponent(msg);
}
void GameWidget::prepareTextEditForPrintingLogin()
{
const QColor colorLogin (0,0,255);
const int fontSize = 25;
m_chat->moveCursor(QTextCursor::End);
m_chat->setTextColor(colorLogin);
m_chat->setFontPointSize(fontSize * width() / 1920);
}
void GameWidget::prepareTextEditForPrintingMessage()
{
const QColor colorLogin (0,0,0);
const int fontSize = 20;
m_chat->setTextColor(QColor(0,0,0));
m_chat->setFontPointSize(fontSize * width() / 1920);
}
void GameWidget::move(int x, int y, FishColor color)
{
int xToPlace = (m_leftCoordinateBoardX + x * m_distance) - m_fishCenter;
int yToPlace = (m_leftCoordinateBoardY + y * m_distance) - m_fishCenter;
QLabel* lbl = new QLabel(m_background);
if (m_lastMove)
delete m_lastMove;
if (color == WHITE)
{
lbl->setPixmap(QPixmap::fromImage(m_whiteImage));
m_lastMove = new QLabel(m_background);
m_lastMove->setPixmap(QPixmap::fromImage(m_whiteLastImage));
m_white.push_back(lbl);
}
else if (color == BLACK)
{
lbl->setPixmap(QPixmap::fromImage(m_blackImage));
m_lastMove = new QLabel(m_background);
m_lastMove->setPixmap(QPixmap::fromImage(m_blackLastImage));
m_black.push_back(lbl);
}
lbl->move(xToPlace, yToPlace);
m_lastMove->move(xToPlace, yToPlace);
lbl->show();
m_lastMove->show();
if (m_model->getFishColor() == WHITE)
{
if (m_white.count() == 113)
{
qDebug () << "DRAW";
emit noMorePlace();
}
}
else if (m_model->getFishColor() == BLACK)
{
if (m_black.count() == 113)
{
emit noMorePlace();
qDebug () << "DRAW";
}
}
qDebug () << "White = " << m_white.count();
qDebug () << "Black = " << m_black.count();
}
void GameWidget::opponentMoved(int x, int y)
{
move (x, y, m_model->getOpponentColor());
m_opponentTime->stop();
m_ourTime->start();
}
void GameWidget::myMoveFinshed(int x, int y)
{
move(x, y, m_model->getFishColor());
m_ourTime->stop();
m_opponentTime->start();
}
void GameWidget::messageFromOpponentReceived(const QString &msg)
{
prepareTextEditForPrintingLogin();
m_chat->insertPlainText(m_model->getOpponentLogin()+": ");
prepareTextEditForPrintingMessage();
m_chat->insertPlainText(msg+"\n");
m_chat->moveCursor(QTextCursor::End);
}
void GameWidget::onOpponentTimeOut()
{
m_ourTime->stop();
m_opponentTime->stop();
emit opponentTimeExpired();
}
|
#include<bits/stdc++.h>
using namespace std;
int a[1010], b[1010], dp[1010][15000];
int n, ans, len;
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d %d", &a[i], &b[i]);
for (int i = 0; i <= 1000; ++i)
for (int j = 0; j <= 14000; ++j)
dp[i][j] = 1e9;
dp[0][5000] = 0;
for (int i = 1; i <= n; ++i)
for (int j = -5000; j <= 5000; ++j)
{
len = a[i] - b[i];
dp[i][j + 5000] = min(dp[i - 1][j - len + 5000], dp[i - 1][j + len + 5000] + 1);
}
for (int i = 0; i <= 5000; ++i)
{
ans = min(dp[n][i + 5000], dp[n][5000 - i]);
if (ans <= 1000)
{
printf("%d\n", ans);
break;
}
}
return 0;
}
|
#ifndef CLIENT_MANAGER_H
#define CLIENT_MANAGER_H
#include <netinet/in.h>
#include <string>
class client_manager {
// FIXME:
public:
// TODO: WTF IS THIS???
// O_CLOEXEC (Since Linux 2.6.23)
// Enable the close-on-exec flag for the new file descriptor. Specifying this flag permits a program to avoid additional fcntl(2) F_SETFD
// operations to set the FD_CLOEXEC flag. Additionally, use of this flag is essential in some multithreaded programs since using a separate
// fcntl(2) F_SETFD operation to set the FD_CLOEXEC flag does not suffice to avoid race conditions where one thread
// opens a file descriptor at the same time as another thread does a fork(2) plus execve(2).
constexpr static int ACCEPT_FLAGS = ::SOCK_CLOEXEC;
constexpr static int BUFFER_SIZE = 1024;
int client_fd;
::sockaddr_in client_addr;
char buffer[BUFFER_SIZE];
size_t buffer_size;
public:
client_manager();
int get_fd() const;
void accept(const int server_fd);
size_t read(char* buffer, size_t size);
void read_in_buffer();
void write(const char* buffer, size_t size);
void write(std::string const& text);
void write_from_buffer();
void close();
};
#endif // CLIENT_MANAGER_H
|
#include "Rate.h"
#include <iostream>
#include "EtcFunctions.h"
void Rate::set_const_rate(double v)
{
//if vector is null
if(r.empty()==true && r.empty()==true){
ts.push_back(1.0);
r.push_back(1.0);
}else{
std::vector<double>::iterator it;
for(it=r.begin();it!=r.end();it++)
*it=v;
}
}
void Rate::print() const
{
std::cout << std::fixed;
std::cout.precision(4);
auto iter_r=r.begin();
for(auto iter=ts.begin();iter!=ts.end();iter++){
std::cout << *iter << " " << *iter_r << std::endl;
iter_r++;
}
}
int Rate::getSize() const
{
return r.size();
}
double Rate::getIntpRate(double t) const
{
EtcFunctions f;
return f.intp1d(r,ts,t);
}
std::vector<double> Rate::get_rate() const
{
return r;
}
double Rate::getForward(double t) const
{
double result, drdt;
if(t<=ts.front()){
result=r.front();
return result;
}else if(t>=ts.back()){
result=r.back();
return result;
}
std::vector<double>::const_iterator iter_r=r.begin();
for(std::vector<double>::const_iterator iter=ts.begin();iter!=ts.end()-1;++iter){
if(t < *(iter+1) && t>=*iter){
drdt = (*(iter_r+1) - *iter_r) / (*(iter+1) -*iter);
result = ((t - *iter) * *(iter_r+1) + (*(iter+1) - t) * *iter_r) / (*(iter+1) - *iter);
//result = result + t * drdt;
result = result + drdt * (t + 1 / 365); // d_t=1/365
return result;
}
iter_r++;
}
throw std::logic_error("can't find proper forward");
return 1;
}
//double getForward(double* tenor, double* curve, double nCol, double t)
//{
// double result, drdt;
//
// if (t<=tenor[0])
// {
// result=curve[0];
// return result;
// }
// else if (t>=tenor[(long)nCol-1])
// {
// result=curve[(long)nCol-1];
// return result;
// }
//
// for (long i=0; i<(long)nCol-1; i++)
// {
// if (t < tenor[i + 1] && t >= tenor[i])
// {
// drdt = (curve[i + 1] - curve[i]) / (tenor[i + 1] - tenor[i]);
//result = ((t - tenor[i]) * curve[i + 1] + (tenor[i + 1] - t) * curve[i]) / (tenor[i + 1] - tenor[i]);
// result = result + t * drdt;
// return result;
// }
// }
//
//}
|
/*
* Space.cpp
*
* Created on: 30 Eyl 2019
* Author: keske
*/
#include "Space.h"
const Vehicle& Space::get_content() const {
if(is_empty()){
std::cout << "Empty space reached!!! Check code" << std::endl;
}
return *content;
}
Space::Space(const Vehicle &vec) :
empty(false), content(&vec) {
}
void Space::make_empty() {
empty = true;
content = nullptr;
}
void Space::add(const Vehicle& vec) {
if (is_empty()) {
content = &vec;
empty = false;
} else {
std::cout << "The space already contains " << content << " !"
<< std::endl;
}
}
bool Space::is_empty() const {
return empty;
}
Space::Space() : empty(true), content(nullptr) {
}
bool Space::is_full() const {
return !is_empty();
}
|
#include <iostream>
using namespace std;
int StringToInt(const char *str);
int StringToIntCore(const char *str, bool minus); //字符串转整型核心函数
int StringToInt(const char *str)
{
int num;
if (str != NULL && *str != '\0') //str为空指针或空字符串返回零
{
//处理正负号
bool minus = false;
if (*str == '+')
str++;
else if (*str == '-')
{
str++;
minus = true;
}
if (*str != '\0') //处理输入只有正负号情况
{
num = StringToIntCore(str, minus);
}
}
else
throw std::invalid_argument("Invalid String Input");
return num;
}
int StringToIntCore(const char *str, bool minus)
{
long long num = 0;
while (*str != '\0')
{
if (*str >= '0' && *str <= '9') //转换‘0’~'9'之间的字符
{
int flag = minus ? -1 : 1; //条件运算符
num = num * 10 + flag * (*str - '0');
//判断num是否溢出
if ((!minus && num > 0x7FFFFFFF) || (minus && num < (signed int)0x80000000))
//(signed int)0x80000000为int 型的最小负数,必须加signed int
throw std::overflow_error("Integer Overflow");
str++; //向后移动一位
}
else
{
throw std::invalid_argument("Invalid String Input");
}
}
return (int)num;
}
int main()
{
cout<<StringToInt("111111111111111111")<<endl;
return 0;
}
|
#pragma once
#include "CalendarComponent.h"
using namespace std;
class FullCalendarBuilder;
class CalendarInterface;
class DisplayableDay;
class DisplayableMonth;
class DisplayableYear;
class IncrementalBuilder;
class DisplayableEvent : public CalendarComponent{
friend class DisplayableDay;
friend class DisplayableMonth;
friend class DisplayableYear;
friend FullCalendarBuilder;
friend CalendarInterface;
friend IncrementalBuilder;
friend bool operator<(shared_ptr<DisplayableComponent>, shared_ptr<DisplayableComponent>);
public:
DisplayableEvent(std::tm, std::shared_ptr<DisplayableComponent>, std::string);
virtual void display() override;
std::string name;
};
bool operator<(shared_ptr<DisplayableComponent>, shared_ptr<DisplayableComponent>);
|
//
// fileReader.cpp
// EmbeddedLab_GPS-Decoder
//
// Created by Markus Heupel on 20.12.18.
// Copyright © 2018 Markus Heupel. All rights reserved.
//
#include <iostream>
#include "../includes/fileReader.hpp"
using namespace std;
int read(const char* filename, int* sumSignal){
FILE *fs;
char c;
char buffer[5];
fs = fopen(filename, "r");
if(fs == NULL){
cout << "file empty !!!" << endl;
return -1;
}
// go through file and get every char
int bufferIndex = 0;
int sumIndex = 0;
while(fs != NULL){
c = fgetc(fs);
if(c == EOF){
break;
}
if(c == ' ' ){
sumSignal[sumIndex] = atoi((const char*)buffer); // convert char buffer to int for negative numbers
sumIndex++;
bufferIndex = 0;
bzero(buffer, 5); // clear buffer
}else{
buffer[bufferIndex] = c;
bufferIndex++;
}
}
return 0;
}
|
//
// Created by Nudzejma on 4/2/2018.
//
#include "Node.h"
Node::Node(const Node &node) {
adjacentNodes = {};
adjacentNodes = node.adjacentNodes;
visited = node.visited;
label = node.label;
}
Node::~Node() {
while(!this->adjacentNodes.empty()) {
removeAdjacentNode(this->adjacentNodes[this->adjacentNodes.size()-1]);
}
}
void Node::addAdjacentNode(Node *node) {
adjacentNodes.push_back(node);
node->adjacentNodes.push_back(this);
}
void Node::removeAdjacentNode(Node *node) {
auto removeIt = remove(adjacentNodes.begin(), adjacentNodes.end(), node);
if (removeIt != adjacentNodes.end()) {
adjacentNodes.erase(removeIt);
node->adjacentNodes.erase(remove(node->adjacentNodes.begin(), node->adjacentNodes.end(), this));
}
}
Node& Node::operator=(const Node &node) {
if (this != &node) {
for(auto adjacentNode : adjacentNodes)
delete adjacentNode;
adjacentNodes = {};
adjacentNodes = node.adjacentNodes;
visited = node.visited;
label = node.label;
}
return *this;
}
bool Node::operator==(const Node &node) {
return this->adjacentNodes == node.adjacentNodes && this->visited == node.visited && this->label == node.label;
}
bool Node::operator!=(const Node &node) {
return !(this == &node);
}
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <captGenerator.h>
#include <captFontFile.h>
#include <captRLE.h>
#pragma pack(push, 1)
struct TGA_HEAD // TGA图像文件头
{
unsigned char IdentSize; // 标志域长度 00 无标志域
unsigned char ColorMapType; // 色彩表类型 00 无色彩表
unsigned char ImageType; // 图像类型 02 非压缩RGB图像
unsigned short ColorMapStart; // 第一个色彩表入口 00 00
unsigned short ColorMapLength; // 色彩表长度 00 00
unsigned char ColorMapBits; // 色彩表入口大小 00
unsigned short XStart; // 图像X原点 00 00
unsigned short YStart; // 图像Y原点 00 00
unsigned short Width; // 图像宽度 80 02 图像宽度640 ****
unsigned short Height; // 图像高度 E0 01 图像高度480 ****
unsigned char Bits; // 每个象素位数 20 象素位数RGBA 32位 ****
unsigned char Descriptor; // 图像描述符 08 Alpha通道位数8
// 图像第一个点在左下角
};
#pragma pack(pop)
int main(int argc, char* argv[])
{
if(argc < 3)
{
printf("Usage: captGen [FontFile] [OutputFile]\n");
return 1;
}
FILE* fp = fopen(argv[1], "rb");
if(fp==0)
{
printf("Error, Open font file %s error!\n", argv[1]);
return 1;
}
fseek(fp, 0, SEEK_END);
unsigned int fileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
unsigned char* streamBuf = new unsigned char[fileSize];
fread(streamBuf, 1, fileSize, fp);
fclose(fp); fp=0;
//打开字体文件
libCapt::FontFile fontFile;
if(!fontFile.loadFromDataStream(streamBuf, fileSize))
{
printf("Error, Load font file error!\n");
delete[] streamBuf;
return 0;
}
delete[] streamBuf; streamBuf=0;
//产生一个图灵测试问题
srand((unsigned int)time(0));
libCapt::Question question;
libCapt::Generator generator(&fontFile);
generator.generateQuestion(question);
//------------------------------------------------------------
//将图像内容解压并转换成图片
unsigned char bitBuf[libCapt::Question::IMAGE_BUF_LENGTH];
if(question.isCompressed())
{
unsigned int rleSize = question.getSize();
unsigned int bufSize = libCapt::Question::IMAGE_BUF_LENGTH;
rleDecompress(question.imageBuf, rleSize, libCapt::Question::IMAGE_WIDTH, libCapt::Question::IMAGE_HEIGHT, (unsigned char*)bitBuf, bufSize);
}
else
{
memcpy(bitBuf, question.imageBuf, libCapt::Question::IMAGE_BUF_LENGTH);
}
//生成PBM图像,4bit深度
fp = fopen(argv[2], "wb");
if(fp==0)
{
printf("Open output file %s error!\n", argv[2]);
return 1;
}
TGA_HEAD head;
memset(&head, 0, sizeof(head));
head.ImageType = 2;
head.Width = libCapt::Question::IMAGE_WIDTH;
head.Height = libCapt::Question::IMAGE_HEIGHT;
head.Bits = 24;
fwrite(&head, sizeof(head), 1, fp);
for(int y=0; y<libCapt::Question::IMAGE_HEIGHT; y++)
{
for(int x=0; x<libCapt::Question::IMAGE_WIDTH; x++)
{
unsigned char c = bitBuf[(libCapt::Question::IMAGE_HEIGHT-1-y)*libCapt::Question::IMAGE_PITCH + (x>>1)];
c = (x&1) ? ((c&0xf)<<4) : (c&0xf0);
unsigned char pixel[4]={c,c,c,c};
fwrite(pixel, 1, 3, fp);
}
}
fclose(fp); fp=0;
return 0;
}
|
#include "GpuObject.h"
namespace revel
{
namespace renderer
{
GpuObject::GpuObject()
: m_Identifier(0)
{
}
GpuObject::~GpuObject()
{
}
u32
GpuObject::get_id() const
{
return m_Identifier;
}
bool
GpuObject::is_valid() const
{
return m_Identifier;
}
} // ::revel::renderer
} // ::revel
|
#ifndef __HISTORY_H__
#define __HISTORY_H__
#include <QDialog>
#include <trend.h>
class IoDev;
namespace Ui {
class History;
}
class RHistorySelect: public QDialog
{
Q_OBJECT
public:
RHistorySelect(IoDev &src,struct trendinfo *tp,QWidget *p=NULL);
~RHistorySelect() ;
QString& getNameTrend() {return nameTrend;}
//struct trendinfo* getTrendParam() { return &TrendParam ;}
private slots:
void slotAccept();
protected:
void changeEvent(QEvent *e);
private:
QString nameTrend;
struct trendinfo *TrendParam;
IoDev &s;
Ui::History *m_ui;
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long int;
void solve(){
int n;
cin >> n;
vector<int> cnt(2,0), v(n);
for(int &x : v) cin >> x, cnt[x & 1] ++;
int sim = 0;
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++) sim += abs(v[i] - v[j]) == 1;
}
if(cnt[0] % 2 == 0 and cnt[1] % 2 == 0) cout << "YES\n";
else if( sim ) cout << "YES\n";
else cout <<"NO\n";
}
int main(){
ios::sync_with_stdio(0); cin.tie(0);
int t;
cin >> t;
while(t--){
solve();
}
}
|
//
// DashedRoundRect.h
// SMFrameWork
//
// Created by KimSteve on 2016. 11. 14..
//
//
#ifndef DashedRoundRect_h
#define DashedRoundRect_h
#include <2d/CCSprite.h>
class DashedRoundRect : public cocos2d::Sprite
{
public:
DashedRoundRect();
virtual ~DashedRoundRect();
static DashedRoundRect* create(const std::string& dashedImageFileName="") {
DashedRoundRect * dashedRect = new (std::nothrow)DashedRoundRect();
std::string fileName = dashedImageFileName;
if (fileName.length()==0) {
fileName = "images/dash_line_s.png";
}
if (dashedRect && dashedRect->initWithFile(fileName)) {
dashedRect->initMesh();
dashedRect->autorelease();
dashedRect->_bInit = true;
} else {
CC_SAFE_DELETE(dashedRect);
}
return dashedRect;
};
bool initMesh();
void setLineWidth(const float lineWidth);
void setCornerRadius(const float radius);
virtual void setContentSize(const cocos2d::Size& size) override;
protected:
void applyMesh();
private:
float _thickness;
float _cornerRadius;
bool _bInit;
cocos2d::TrianglesCommand::Triangles _triangles;
};
#endif /* DashedRoundRect_h */
|
#pragma once
namespace GraphicsEngine
{
class RenderTexture
{
public:
RenderTexture() = default;
RenderTexture(ID3D11Device* d3dDevice, UINT width, UINT height, DXGI_FORMAT format);
void SetRenderTargetView(ID3D11DeviceContext* deviceContext, ID3D11DepthStencilView* depthStencilView) const;
void ClearRenderTargetView(ID3D11DeviceContext* deviceContext, ID3D11DepthStencilView* depthStencilView, const DirectX::XMFLOAT4& color) const;
ID3D11ShaderResourceView* GetShaderResourceView() const;
private:
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_texture;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_shaderResourceView;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_renderTargetView;
};
}
|
#pragma once
#include "../pathfinding/obstruction-map.h"
#include "../graphics/GraphicsGrid.h"
class DisplayGrid : public sf::RectangleShape
{
typedef std::map<std::string, sf::Color> ColorIdMap;
static ColorIdMap GridColors; // pair of id and color - TODO change this
GridBool* obsMap;
sf::Color getTileColor(bool) const;
void loadColors(); // Testing only
void draw(sf::RenderTarget &target, sf::RenderStates states) const;
public:
DisplayGrid();
DisplayGrid(GridBool* obsMap);
~DisplayGrid();
void setGrid(GridBool* obsMap);
};
|
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j=10,n;
for(i=1;i<5;i++){
for(j,n=5;n>i;n--,j--){
printf("%d",j);
}
printf("\n");
}
getch();
}
|
/*
// Copyright 2007 Alexandros Panagopoulos
//
// This software is distributed under the terms of the GNU Lesser General Public Licence
//
// This file is part of Be3D library.
//
// Be3D is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Be3D is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Be3D. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _VECTOR2I_H45631_INCLUDED_
#define _VECTOR2I_H45631_INCLUDED_
#pragma once
#include <math.h>
class Vector2i
{
public:
int x, y;
public:
Vector2i() : x(0), y(0) {}
Vector2i(int _x, int _y) : x(_x), y(_y) {}
Vector2i(const Vector2i& v) : x(v.x), y(v.y) {}
Vector2i& operator = (const Vector2i& v) { x=v.x; y=v.y; return *this; }
// vector operators
inline Vector2i& operator += (const Vector2i& v) { x+=v.x; y+=v.y; return *this; };
inline Vector2i& operator -= (const Vector2i& v) { x-=v.x; y-=v.y; return *this; };
friend inline Vector2i operator + (const Vector2i& v1, const Vector2i& v2) { return Vector2i(v1.x+v2.x, v1.y+v2.y); };
friend inline Vector2i operator - (const Vector2i& v1, const Vector2i& v2) { return Vector2i(v1.x-v2.x, v1.y-v2.y); };
inline double length() const { return sqrt((double)(x*x + y*y)); }
inline int length2() const { return x*x + y*y; }
// unary operators
friend inline Vector2i operator - (const Vector2i& v) { return Vector2i(-v.x, -v.y); }
// scalar operators
friend inline Vector2i operator * (const Vector2i& v, float f) { return Vector2i(int(v.x*f), int(v.y*f)); };
friend inline Vector2i operator * (float f, const Vector2i& v) { return Vector2i(int(v.x*f), int(v.y*f)); };
friend inline Vector2i operator / (const Vector2i& v, float f) { return Vector2i(int(v.x/f), int(v.y/f)); };
friend inline Vector2i operator / (float f, const Vector2i& v) { return Vector2i(int(v.x/f), int(v.y/f)); };
inline Vector2i& operator *= (float f) { x=int(x*f); y=int(y*f); return *this; };
inline Vector2i& operator /= (float f) { x=int(x/f); y=int(y/f); return *this; };
// products (not as operators, to avoid confusion)
inline int dot(const Vector2i& v) const { return x*v.x + y*v.y; }
inline float angle(const Vector2i& v) const { return acosf((float)(dot(v)/(length()*v.length()))); }
inline float angleUnitV(const Vector2i& v) const { return acosf((float)dot(v)); } // WORKS ONLY ON UNIT VECTORS
};
#endif
|
#include <catch.hpp>
#include <embr/datapump.hpp>
#include <embr/dataport.hpp>
#include <embr/observer.h>
#include "datapump-test.h"
using namespace embr;
struct synthetic_context
{
int value;
};
// Renamed from StatefulObserver because compiler picked it up as the same class as
// from observer-test --- seems like a bug!
struct DataportStatefulObserver
{
int counter;
DataportStatefulObserver() : counter(0) {}
typedef DataPortEvents<synthetic_datapump> event;
void on_notify(event::receive_queued e, synthetic_context& c)
{
}
void on_notify(event::receive_queued e)
{
}
void on_notify(event::send_queued e)
{
}
};
struct synthetic_transport
{
typedef synthetic_transport_descriptor transport_descriptor_t;
synthetic_transport(void*) {}
bool recv(synthetic_netbuf_type**, int*) { return false; }
void send(synthetic_netbuf_type&, int) {}
};
TEST_CASE("dataport")
{
synthetic_netbuf_type nb;
SECTION("synthetic dataport")
{
// make a 1-count subject/observer binding
auto s = layer1::make_subject(DataportStatefulObserver());
typedef DataPort<synthetic_datapump, synthetic_transport, decltype (s)&> synthetic_dataport;
synthetic_dataport dp(s);
synthetic_context c;
WHEN("receiving")
{
dp.enqueue_from_receive(std::move(nb), 0);
}
WHEN("sending")
{
dp.enqueue_for_send(std::move(nb), 1);
}
dp.service();
}
SECTION("make_dataport")
{
auto s = void_subject();
auto dataport = embr::make_dataport<synthetic_transport>(s);
}
}
|
#include <iostream>
using namespace std;
typedef void (*PFT)(char, int);
void bar(char ch, int i)
{
cout << "bar " << ch << ' ' << i << endl;
return;
}
int main(int argc, char *argv[])
{
// 定义一个函数对象
PFT pft;
pft = bar; // 赋值
// 调用
pft('e', 91);
return 0;
}
|
#ifndef FLOWINFO_H
#define FLOWINFO_H
#include <cstdint>
#include <string>
#include "ndpi_main.h"
#include "global_vars_prefs.h"
class FlowInfo {
const uint8_t MAX_EXTRA_PACKETS_TO_CHECK = 7;
private:
uint32_t hashval;
uint8_t protocol;
uint16_t vlan_id;
uint8_t ip_version;
uint32_t src_ip;
uint32_t dst_ip;
uint16_t src_port;
uint16_t dst_port;
std::string src_name;
std::string dst_name;
bool detection_completed;
bool bidirectional;
bool check_extra_packets;
struct ndpi_flow_struct* ndpi_flow;
int64_t last_seen;
uint64_t src2dst_bytes;
uint64_t dst2src_bytes;
uint32_t src2dst_packets;
uint32_t dst2src_packets;
// result only, not used for flow identification
ndpi_protocol detected_protocol;
char info[96];
char host_server_name[192];
std::string bittorent_hash;
struct {
char client_info[48];
char server_info[48];
} ssh_ssl;
ndpi_ethhdr macs;
struct ndpi_id_struct* src_id;
struct ndpi_id_struct* dst_id;
bool session_complete;
public:
FlowInfo(uint8_t protocol, uint16_t vlan_id, const ndpi_ethhdr* macs,
uint32_t src_ip, uint32_t dst_ip,
std::string src_name, std::string dst_name,
uint16_t src_port, uint16_t dst_port,
uint8_t ip_version, int64_t time);
~FlowInfo();
bool IsSrc2Dst(uint32_t sip, uint32_t dip, uint16_t sport, uint16_t dport);
bool IsDetected();
ndpi_protocol DetectProto(ndpi_detection_module_struct* ndpi_struct,
const uint8_t* packet, const uint ipsize, const bool src2_dst);
// static int cmp(const void* a, const void* b);
static bool Cmp(FlowInfo*& a, FlowInfo*& b);
static int CmpAsNode(const void* a, const void* b);
void AddSrc2Dst(uint bytes)
{
src2dst_packets++;
src2dst_bytes += bytes;
}
void AddDst2Src(uint bytes)
{
dst2src_packets++;
dst2src_bytes += bytes;
}
bool IsBidirectional() const { return bidirectional; }
bool IsSessionComplete(int64_t time) const
{
return time && (time - last_seen) >= AppPrefs::SESSION_TIME;
}
void set_time(int64_t time);
public:
uint32_t get_hash() { return hashval; }
ndpi_protocol get_ndpi_proto() const { return detected_protocol; }
uint16_t get_master_proto() const { return detected_protocol.master_protocol; }
uint16_t get_app_proto() const { return detected_protocol.app_protocol; }
uint8_t get_proto_id() const { return protocol; }
uint16_t get_vlan_id() const { return vlan_id; }
uint8_t get_ip_version() const { return ip_version; }
std::string get_src_name() const { return src_name; }
std::string get_dst_name() const { return dst_name; }
uint16_t get_src_port() const { return src_port; }
uint16_t get_dst_port() const { return dst_port; }
const u_char* get_src_mac() const { return macs.h_source; }
const u_char* get_dst_mac() const { return macs.h_dest; }
uint64_t get_src2dst_bytes() const { return src2dst_bytes; }
uint64_t get_dst2src_bytes() const { return dst2src_bytes; }
uint32_t get_src2dst_packets() const { return src2dst_packets; }
uint32_t get_dst2src_packets() const { return dst2src_packets; }
std::string get_bittorent_hash() const { return bittorent_hash; }
int64_t get_last_seen() const { return last_seen; }
uint32_t get_src_ip() const { return src_ip; }
uint32_t get_dst_ip() const { return dst_ip; }
std::string get_info() const
{
char buf[sizeof(info) + 1] = {};
memcpy(buf, info, sizeof(info));
return std::string(buf);
}
std::string get_host_server_name() const
{
char buf[sizeof(host_server_name) + 1] = {};
memcpy(buf, host_server_name, sizeof(host_server_name));
return std::string(buf);
}
std::string get_ssl_client_info() const
{
char buf[sizeof(ssh_ssl.client_info) + 1] = {};
memcpy(buf, ssh_ssl.client_info, sizeof(ssh_ssl.client_info));
return std::string(buf);
}
std::string get_ssl_server_info() const
{
char buf[sizeof(ssh_ssl.server_info) + 1] = {};
memcpy(buf, ssh_ssl.server_info, sizeof(ssh_ssl.server_info));
return std::string(buf);
}
std::string get_proto_name(ndpi_detection_module_struct* ndpi_struct) const
{
char buf[64];
if(detected_protocol.master_protocol)
return ndpi_protocol2name(ndpi_struct, detected_protocol,
buf, sizeof(buf));
else
return ndpi_get_proto_name(ndpi_struct,
detected_protocol.app_protocol);
}
private:
void ProcessInfo();
};
#endif // FLOWINFO_H
|
#include <QCoreApplication>
#include <QTextStream>
#include <QDir>
#include <QFile>
#include <qhttpserver.hpp>
#include <qhttpserverresponse.hpp>
#include <qhttpserverrequest.hpp>
#include <resty/mux/Router.h>
#include <resty/mux/RouteMatch.h>
#include <iostream>
using namespace resty::mux;
int main(int argc, char** argv) {
QCoreApplication app(argc, argv);
qhttp::server::QHttpServer server(&app);
QString rootDir = ".";
auto router = std::make_shared<Router >();
router->addResourceHandler("/{file}", [rootDir](Request* req, Response* resp) {
QString path = rootDir + req->url().path();
QFile file(path);
if (file.open(QIODevice::ReadOnly)) {
resp->end(file.readAll());
} else {
resp->setStatusCode(qhttp::ESTATUS_NOT_FOUND);
resp->end("Not found");
}
});
router->addResourceHandler("/", [rootDir](Request* req, Response* resp) {
QString path = req->url().path();
QDir dir(rootDir + path);
QString body;
QTextStream stream(&body);
for (const auto& f : dir.entryInfoList()) {
stream << "<a href=\"" << path << f.fileName() << (f.isDir() ? "/" : "") << "\">" << f.fileName() << "</a><br>\n";
}
resp->end(body.toUtf8());
});
// Silly directory eating machine
auto dirRouter = std::make_shared<Router >();
dirRouter->setPrefix("/{dir}");
dirRouter->addSubRouter(dirRouter);
dirRouter->addSubRouter(router);
router->addSubRouter(dirRouter);
server.listen(QHostAddress::Any, 8080, std::ref(*router));
if (!server.isListening()) {
qDebug("failed to listen");
return -1;
}
return app.exec();
}
|
//-----------------------------------------------------------------------------
// Perimeter Map Compiler
// Copyright (c) 2005, Don Reba
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// • Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// • Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// • Neither the name of Don Reba nor the names of his contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#pragma once
#include "error handler.h"
#include "info wnd.h"
#include "file tracker.h"
#include "preview wnd.h"
#include "project tasks.h"
#include "stat wnd.h"
#include "task resources.h"
#include <queue>
#include <boost/array.hpp>
class MainWnd;
//-------------------------------------------------------
// ProjectManager definition
// this class does most of the work, in a separate thread
// the class is not thread-safe;
// it can only be used within the main thread
//-------------------------------------------------------
class ProjectManager : ErrorHandler, TaskCommon::SaveCallback::SaveHandler
{
// callbacks
public:
// toggles busy state
struct TasksLeft {
virtual void operator() (uint task_count) = 0;
};
// callback implementations
private:
struct FileUpdated : FileTracker::FileUpdated
{
FileUpdated(ProjectManager &project_manager);
void operator() (const IdsType &ids);
ProjectManager &project_manager_;
};
struct ZeroLevelChanged : InfoWnd::ZeroLevelChanged {
ZeroLevelChanged(ProjectManager &project_manager);
void operator() ();
ProjectManager &project_manager_;
};
// type definitions
private:
typedef std::queue<Task*> QueueType;
// construction/destruction
public:
ProjectManager(
MainWnd &main_wnd,
InfoWnd &info_wnd,
PreviewWnd &preview_wnd,
StatWnd &stat_wnd
);
~ProjectManager();
// interface
public:
// initialization
bool Initialize();
void Close();
// project management
void CreateProject(LPCTSTR folder_path, LPCTSTR map_name, SIZE map_size, HWND main_hwnd);
void OpenProject(LPCTSTR project_path, HWND main_hwnd, bool new_project = false);
// shrub management
void PackShrub();
bool UnpackShrub(LPCTSTR shrub_path, HWND main_hwnd);
void OnProjectOpen(HWND main_hwnd);
void OnProjectUnpacked(HWND main_hwnd);
void OnResourceCreated(Resource id);
// map management
void InstallMap(LPCTSTR install_path, uint version);
// miscellaneous
void SaveThumbnail();
// data management
void CreateResource(Resource id, HWND main_hwnd);
void ImportScript(LPCTSTR script_path, HWND main_hwnd);
// panel management
void UpdateInfoWnd (IdsType ids);
void UpdatePreviewWnd(IdsType ids);
void UpdateStatWnd (IdsType ids);
void UpdatePanels (IdsType ids);
// settings
void UpdateSettings();
// internal function
private:
static uint __stdcall ProcessorThreadProxy(void *obj);
void AddTask(Task *task);
void FindFileNames();
void ProcessorThread();
void ChangeOpeningCount(int delta);
// SaveHandler
void OnSaveBegin(Resource id);
void OnSaveEnd (Resource id);
// data
private:
// threading
HANDLE processor_thread_;
CRITICAL_SECTION processor_section_;
bool stop_processing_;
QueueType tasks_;
// windows
InfoWnd &info_wnd_;
PreviewWnd &preview_wnd_;
StatWnd &stat_wnd_;
// project
tstring folder_path_;
FileTracker tracker_;
ProjectState project_state_;
int opening_count_;
tstring file_names_[resource_count];
// callback implementation instances
private:
FileUpdated file_updated_;
public:
ZeroLevelChanged zero_level_changed_;
// callbacks
public:
TasksLeft *tasks_left_;
};
|
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node{
int data;
struct node *left;
struct node *right;
};
bool isSumToNos(struct node *,int);
struct node *newnode(int data){
struct node *temp=(struct node *)malloc(sizeof(struct node ));
temp->data=data;
temp->left=NULL;
temp->right=NULL;
return temp;
}
bool isSumToNos(struct node *node ,int sum){
if(node==NULL){
return(sum==0);
}
else{
bool ans=0;
int subsum=sum-node->data;
if(subsum==0 && node->left==NULL && node->right==NULL)
return 1;
if(node->left)
ans=ans || isSumToNos(node->left,subsum);
if(node->right)
ans= ans || isSumToNos(node->right,subsum);
return ans;
}
}
int main()
{
int sum = 14;
/* Constructed binary tree is
10
/ \
8 2
/ \ /
3 5 2
*/
struct node *root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
root->left->right = newnode(5);
root->right->left = newnode(2);
if(isSumToNos(root, sum))
printf("There is a root-to-leaf path with sum %d", sum);
else
printf("There is no root-to-leaf path with sum %d", sum);
getchar();
return 0;
}
|
//
// Created by Apple on 2021/6/9.
//
#include <vector>
// todo, 空间复杂度可以优化,为了利于后续思考,此处不写答案
using namespace std;
/**
* 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
* 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
* 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
* 网格中的障碍物和空位置分别用 1 和 0 来表示。
*
* 分析:dp[i][j]表示从起点到[i, j]的路径数量,对于第一行和第一列,只要前面有一个障碍,则从当前点到这一行(列)后续到所有点都不可到达,
* 对于其他点,则有障碍物的点不可到达,即dp[i][j] = 0
*
* 返回从起点到终点不同路径到数量
*
* https://leetcode-cn.com/problems/unique-paths-ii/
*
* @param obstacleGrid
* @return
*/
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
using LL = long long;
const size_t ROW = obstacleGrid.size();
const size_t COL = obstacleGrid[0].size();
vector<vector<LL>> dp(ROW, vector<LL>(COL, 0));
for (int i = 0; i < ROW && !obstacleGrid[i][0]; ++i) {
dp[i][0] = 1;
}
for (int j = 0; j < COL && !obstacleGrid[0][j]; ++j) {
dp[0][j] = 1;
}
for (int i = 1; i < ROW; ++i) {
for (int j = 1; j < COL; ++j) {
if (obstacleGrid[i][j]) {
dp[i][j] = 0;
} else {
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
}
return static_cast<int>(dp[ROW - 1][COL - 1]);
}
int main() {
return 0;
}
|
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define ok() puts(ok?"Yes":"No");
#define chmax(x,y) x = max(x,y)
#define chmin(x,y) x = min(x,y)
using namespace std;
using ll = long long;
using vi = vector<int>;
using ii = pair<int, int>;
using vvi = vector<vi>;
using vii = vector<ii>;
using gt = greater<int>;
using minq = priority_queue<int, vector<int>, gt>;
using P = pair<ll,ll>;
const ll LINF = 1e18L + 1;
const int INF = 1e9 + 1;
//clang++ -std=c++11 -stdlib=libc++
// abc120d
struct UnionFind {
vector<int> d;
UnionFind(int n=0): d(n,-1) {}
int find(int x) {
if (d[x] < 0) return x;
return d[x] = find(d[x]);
}
bool unite(int x, int y) {
x = find(x); y = find(y);
if (x == y) return false;
if (d[x] > d[y]) swap(x,y);
d[x] += d[y];
d[y] = x;
return true;
}
bool same(int x, int y) { return find(x) == find(y);}
int size(int x) { return -d[find(x)];}
};
int main() {
ll n,m; cin >> n >> m;
UnionFind uf(n);
ll num = (ll) n*(n-1)/2;
vector<ll> ans;
vi A(m), B(m);
rep(i,m) {
cin >> A[i] >> B[i];
A[i]--; B[i]--;
}
reverse(A.begin(), A.end());
reverse(B.begin(), B.end());
rep(i,m) {
ll a = A[i], b=B[i];
ans.push_back(num);
if (!uf.same(a,b)) {
num -= (ll) uf.size(a) * uf.size(b);
}
uf.unite(a, b);
}
reverse(ans.begin(), ans.end());
rep(i,m) cout << ans[i] << endl;
return 0;
}
|
#include <stdio.h>
int n;
int save[101];
const int num = 1000000007;
int func(int rest)
{
if(save[rest] != -1)
return save[rest];
save[rest] = (func(rest-1) + func(rest-2))%num;
return save[rest];
}
int main()
{
int c;
scanf("%d",&c);
for(int i=3;i<101;i++)
save[i] = -1;
save[1] =1;
save[2] =2;
while(c--)
{
scanf("%d",&n);
printf("%d\n",func(n));
}
}
|
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "port/port_posix.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util/logging.h"
#include <sys/time.h>
#include <unistd.h>
#ifdef USE_COMPRESS_EXT
#include "compress/lz4.h"
#include "compress/bmz_codec.h"
bmz::BmzCodec bmc;
#endif
namespace leveldb {
namespace port {
static void PthreadCall(const char* label, int result) {
if (result != 0) {
fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
abort();
}
}
Mutex::Mutex() {
pthread_mutexattr_t attr;
PthreadCall("init mutexattr", pthread_mutexattr_init(&attr));
PthreadCall("set mutexattr", pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
PthreadCall("init mutex", pthread_mutex_init(&mu_, &attr));
PthreadCall("destroy mutexattr", pthread_mutexattr_destroy(&attr));
}
Mutex::~Mutex() { PthreadCall("destroy mutex", pthread_mutex_destroy(&mu_)); }
void Mutex::Lock() { PthreadCall("lock", pthread_mutex_lock(&mu_)); }
void Mutex::Unlock() { PthreadCall("unlock", pthread_mutex_unlock(&mu_)); }
CondVar::CondVar(Mutex* mu)
: mu_(mu) {
PthreadCall("init cv", pthread_cond_init(&cv_, NULL));
}
CondVar::~CondVar() { PthreadCall("destroy cv", pthread_cond_destroy(&cv_)); }
void CondVar::Wait() {
PthreadCall("wait", pthread_cond_wait(&cv_, &mu_->mu_));
}
bool CondVar::Wait(int32_t wait_millisec) {
assert(wait_millisec >= 0);
struct timespec ts;
struct timeval tp;
gettimeofday(&tp, NULL);
uint32_t usec = tp.tv_usec + wait_millisec * 1000;
ts.tv_sec = tp.tv_sec + usec / 1000000;
ts.tv_nsec = (usec % 1000000) * 1000;
return (0 == pthread_cond_timedwait(&cv_, &mu_->mu_, &ts));
}
void CondVar::Signal() {
PthreadCall("signal", pthread_cond_signal(&cv_));
}
void CondVar::SignalAll() {
PthreadCall("broadcast", pthread_cond_broadcast(&cv_));
}
void InitOnce(OnceType* once, void (*initializer)()) {
PthreadCall("once", pthread_once(once, initializer));
}
/////////// Compression Ext ///////////
bool Bmz_Compress(const char* input, size_t input_size,
std::string* output) {
#ifdef USE_COMPRESS_EXT
size_t output_size = input_size * 2;
output->resize(output_size);
if (!bmc.Compress(input, input_size, &(*output)[0], &output_size)
|| output_size == 0 || output_size > input_size) {
return false;
}
output->resize(output_size);
return true;
#else
return false;
#endif
}
bool Bmz_Uncompress(const char* input, size_t input_size,
char* output, size_t* output_size) {
#ifdef USE_COMPRESS_EXT
return bmc.Uncompress(input, input_size, output, output_size);
#else
return false;
#endif
}
bool Lz4_Compress(const char* input, size_t input_size,
std::string* output) {
#ifdef USE_COMPRESS_EXT
output->resize(input_size * 2);
size_t output_size = LZ4LevelDB_compress(input, &(*output)[0], input_size);
if (output_size == 0 || output_size > input_size) {
return false;
}
output->resize(output_size);
return true;
#else
return false;
#endif
}
bool Lz4_Uncompress(const char* input, size_t input_size,
char* output, size_t* output_size) {
#ifdef USE_COMPRESS_EXT
size_t max_output_size = *output_size;
*output_size = LZ4LevelDB_decompress_fast(
input, output, input_size);
return true;
#else
return false;
#endif
}
//////////////////////////////
} // namespace port
} // namespace leveldb
|
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int d, Node* l = nullptr, Node* r = nullptr): data(d), left(l), right(r) { }
};
string serialize(Node* node) {
if (node == nullptr) {
return "()";
}
stringstream res;
res << "(" << node->data << " " <<
serialize(node->left) << " " <<
serialize(node->right) << ")";
return res.str();
}
Node* deserialize(string& s) {
if (s[0] != '(') {
cerr << "expected ( at pos " << 0 << endl;
return nullptr;
}
if (s[1] == ')')
{
s = s.substr(2);
return nullptr;
}
stringstream ss;
ss << s;
// ignore the (
ss.get();
Node* result = new Node(0);
ss >> result->data;
// remove space after data
ss.get();
getline(ss, s);
result->left = deserialize(s);
// remove space after left
s = s.substr(1);
result->right = deserialize(s);
// remove closing )
if (s[0] != ')') {
cerr << "expected )" << endl;
}
s = s.substr(1);
return result;
}
int main()
{
Node* d = new Node{
1,
new Node(2,
new Node(3),
new Node(4)),
new Node(5,
nullptr,
new Node(6))
};
string s = serialize(d);
cout << "Serialized: " << s << endl;
Node* copy = deserialize(s);
cout << "Serialized copy: " << serialize(copy) << endl;
return 0;
}
|
// scene.cpp : Defines the Scene object
//
#include "stdafx.h"
#include "scene.h"
#include <algorithm>
///////////////////////////////////////////////////////////
// Class CScene
CScene::CScene()
{
m_bOn = TRUE;
m_pRenderer = NULL;
m_pCamera = NULL;
m_nOrdinalOffset = 0;
}
CScene::~CScene()
{
if (m_pRenderer) m_pRenderer->Release();
if (m_pCamera) m_pCamera->Release();
}
HRESULT __stdcall CScene::CreateChild(LPOLESTR pLabel, /*[out, retval]*/ IKineNode **p)
{
if (!p) return ERROR(FW_E_POINTER);
ISceneObject *pObject;
HRESULT h = NewObject(pLabel, &pObject);
if (FAILED(h)) return h;
h = pObject->QueryInterface(p);
pObject->Release();
if (FAILED(h)) { (*p)->Release(); return ERROR(FW_E_NOINTERFACE); }
return S_OK;
}
bool _LESS(ISceneRenderee *p1, ISceneRenderee *p2)
{
FWULONG n1, n2;
p1->GetRenderOrdinal(&n1);
p2->GetRenderOrdinal(&n2);
return n1 < n2;
}
HRESULT __stdcall CScene::AddChildEx(LPOLESTR pLabel, IKineChild *p, BOOL bSetParentalDep, IKineNode **ppParentNode, FWULONG *pnId)
{
// call inherited function, ensure an immediate child added successfully
HRESULT h;
if (!ppParentNode)
{
IKineNode *pParentNode = NULL;
h = SCENEBASE::AddChildEx(pLabel, p, bSetParentalDep, &pParentNode, pnId);
pParentNode->Release();
if (FAILED(h) || pParentNode != this) return h;
}
else
{
h = SCENEBASE::AddChildEx(pLabel, p, bSetParentalDep, ppParentNode, pnId);
if (FAILED(h) || *ppParentNode != this) return h;
}
ISceneRenderee *pObj = NULL;
if (SUCCEEDED(p->QueryInterface(&pObj)) && pObj)
{
DISPLIST::iterator pos = std::lower_bound(m_displist.begin(), m_displist.end(), pObj, _LESS);
m_displist.insert(pos, pObj);
pObj->Release();
}
ISceneCamera *pCam = NULL;
if (SUCCEEDED(p->QueryInterface(&pCam)) && pCam)
{
if (m_pCamera) m_pCamera->Release();
m_pCamera = pCam;
}
return h;
}
HRESULT __stdcall CScene::DelChildAt(FWULONG nId)
{
IKineChild *p = NULL;
if (SUCCEEDED(GetChildAt(nId, &p)) && p)
{
ISceneRenderee *pObj = NULL;
ISceneCamera *pCam = NULL;
if (SUCCEEDED(p->QueryInterface(&pCam)) && pCam)
{
if (pCam == m_pCamera) { m_pCamera->Release(); m_pCamera = NULL; }
pCam->Release();
}
if (SUCCEEDED(p->QueryInterface(&pObj)) && pObj)
{
m_displist.remove(pObj);
pObj->Release();
}
p->Release();
}
return SCENEBASE::DelChildAt(nId);
}
/////////////////////////////////////////////////////////////////////////////
// properties
HRESULT CScene::GetRenderer(IRndrGeneric **p)
{
if (p)
{
*p = m_pRenderer;
if (*p) (*p)->AddRef();
}
return S_OK;
}
HRESULT CScene::PutRenderer(IRndrGeneric *p)
{
if (!p) return S_OK;
if (m_pRenderer) m_pRenderer->Release();
m_pRenderer = p;
m_pRenderer->AddRef();
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// Objects
HRESULT CScene::NewObject(FWSTRING pLabel, /*[out, retval]*/ ISceneObject **pObject)
{
HRESULT h = FWDevice()->CreateObject(L"SceneObject", IID_ISceneObject, (IFWUnknown**)pObject);
if (FAILED(h)) return h;
return AddObject(pLabel, *pObject);
}
HRESULT CScene::GetCurrentCamera(ISceneCamera **p)
{
if (!p) return S_OK;
// try to recover a camera if none known....
if (!m_pCamera)
for (DISPLIST::iterator i = m_displist.begin(); i != m_displist.end(); i++)
{
ISceneCamera *pCam = NULL;
if (SUCCEEDED((*i)->QueryInterface(&pCam)) && pCam)
m_pCamera = pCam;
}
if (m_pCamera)
m_pCamera->GetCurrentCamera(p);
else
*p = NULL;
return S_OK;
}
HRESULT CScene::PutCamera(ISceneCamera *p)
{
if (m_pCamera) m_pCamera->Release();
m_pCamera = p;
if (m_pCamera) m_pCamera->AddRef();
if (m_pCamera) m_pCamera->PutVisible(TRUE);
return S_OK;
}
HRESULT CScene::AddObject(FWSTRING pLabel, ISceneObject *pObject)
{
HRESULT h;
if (!m_pRenderer)
return ERROR(FW_E_NOTREADY);
if (!pObject) return ERROR(FW_E_POINTER);
pObject->PutRenderer(m_pRenderer);
h = AddChildEx(pLabel, pObject, TRUE, NULL, NULL);
if (FAILED(h)) return h;
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// rendering
HRESULT CScene::Render(IRndrGeneric *pRenderer)
{
if (!m_bOn || !pRenderer) return S_OK;
BOOL bReset;
pRenderer->GetResetFlag(&bReset);
// first render the current camera
ISceneCamera *pCamera = NULL;
GetCurrentCamera(&pCamera);
if (pCamera)
{
if (pCamera->NeedsRendering(bReset) == S_OK)
pCamera->Render(pRenderer);
pCamera->Release();
}
// render all other objects from the display list
for (DISPLIST::iterator i = m_displist.begin(); i != m_displist.end(); i++)
{
ISceneRenderee *pRenderee = *i;
if (pRenderee->NeedsRendering(bReset) == S_OK)
pRenderee->Render(pRenderer);
}
return S_OK;
}
HRESULT CScene::Turnoff(IRndrGeneric *pRenderer)
{
if (!pRenderer) return S_OK;
for (DISPLIST::iterator i = m_displist.begin(); i != m_displist.end(); i++)
(*i)->Turnoff(pRenderer);
return S_OK;
}
HRESULT _stdcall CScene::SortDisplayList()
{
m_displist.sort(_LESS);
return S_OK;
}
|
/*
* cv_viewer.cpp
*
* Created on: Dec 5, 2018
* Author: ttw2xk
*/
#include "f1_datalogger/f1_datalogger.h"
//#include "image_logging/utils/screencapture_lite_utils.h"
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <sstream>
#include "f1_datalogger/udp_logging/common/multi_threaded_udp_handler.h"
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include "f1_datalogger/controllers/vjoy_interface.h"
namespace fs = boost::filesystem;
namespace po = boost::program_options;
void exit_with_help(po::options_description& desc)
{
std::stringstream ss;
ss << desc << std::endl;
std::printf("%s", ss.str().c_str());
exit(0); // @suppress("Invalid arguments")
}
int main(int argc, char** argv)
{
std::string search_string, output_folder;
double throttle, steering;
unsigned int delay_time;
po::options_description desc("F1 Datalogger Multithreaded Capture. Command line arguments are as follows");
try {
desc.add_options()
("help,h", "Displays options and exits")
("steering_angle,a", po::value<double>(&steering)->required(), "Steering angle to set.")
("search_string,s", po::value<std::string>(&search_string)->default_value("2017"), "Search string for application to capture")
("throttle,t", po::value<double>(&throttle)->default_value(.15), "Throttle setpoint to use.")
("delay_time,d", po::value<unsigned int>(&delay_time)->default_value(3000), "Number of milliseconds to wait before capturing.")
("output_folder,f", po::value<std::string>(&output_folder)->default_value("captured_data"), "UDP Output Folder")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.find("help") != vm.end()) {
exit_with_help(desc);
}
}
catch (boost::exception& e)
{
exit_with_help(desc);
}
std::shared_ptr<deepf1::IF1FrameGrabHandler> frame_handler;
std::shared_ptr<deepf1::MultiThreadedUDPHandler> udp_handler(new deepf1::MultiThreadedUDPHandler(output_folder, 3, true));
std::shared_ptr<deepf1::F1DataLogger> dl(new deepf1::F1DataLogger(search_string, frame_handler, udp_handler));
std::cout << "Created DataLogger" << std::endl;
std::string inp;
deepf1::VJoyInterface vjoy(1);
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
deepf1::F1ControlCommand command;
//command.steering = 0.0;
//command.throttle = 0.0;
//vjoy.setCommands(command);
std::cout << "Enter anything to start capture" << std::endl;
std::cin >> inp;
command.steering = steering;
command.throttle = throttle;
vjoy.setCommands(command);
std::this_thread::sleep_for(std::chrono::milliseconds(delay_time));
dl->start();
std::cout << "Capturing data. Enter any key to end " << std::endl;
std::cin >> inp;
command.steering = 0.0;
command.throttle = 0.0;
vjoy.setCommands(command);
udp_handler->stop();
udp_handler->join();
}
|
#include "Controls.h"
#include <iostream>
void Controls::processInputKeyboard(GLFWwindow* window)
{
//generic part
//this is placeholder camera controls
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
forward -= movementSpeed;
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
forward += movementSpeed;
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
right -= movementSpeed;
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
right += movementSpeed;
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
up += movementSpeed;
if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS)
up -= movementSpeed;
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
roll += movementSpeed * 0.2f;
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
roll -= movementSpeed * 0.2f;
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
void Controls::processInputMouse(GLFWwindow* window, double x, double y)
{
//generic part
if (init)
{
lastX = x;
lastY = y;
init = false;
}
float mousexOffset = (float) ((lastX - x) * sensitivity);
float mouseyOffset = (float) ((lastY - y) * sensitivity);
lastX = x;
lastY = y;
//this is placeholder camera controls
yaw -= mousexOffset * sensitivity;
pitch -= mouseyOffset * sensitivity;
}
|
//
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_UTIL_BASE64_ENCODE_HPP
#define NBDL_UTIL_BASE64_ENCODE_HPP
#include <nbdl/concept/Container.hpp>
#include <array>
#include <cassert>
#include <iterator>
#include <string>
namespace nbdl::util
{
namespace base64_detail
{
static constexpr char const* lookup =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static constexpr int const offsets[4]{ 26, 20, 14, 8 };
template <typename OutputItr>
void encode_fragment(OutputItr& output_itr, uint32_t fragment, int byte_length)
{
if (byte_length == 0) return;
for (int i = 0; i <= byte_length; i++)
{
*output_itr = lookup[(fragment & (0x3F << offsets[i])) >> offsets[i]];
++output_itr;
}
}
inline constexpr int encoding_length_padded(int n)
{
return 4*n/3 + ((4 - ((4*n/3) % 4)) % 4);
}
}
struct base64_encode_fn
{
template <ContiguousByteContainer Buffer>
std::string operator()(Buffer&& buffer) const
{
static_assert(sizeof(uint32_t) == 4);
std::string output(base64_detail::encoding_length_padded(buffer.size()), '=');
auto output_itr = output.begin();
int const length = buffer.size();
int const extra_length = length % 3;
int const round_length = length - extra_length;
int const padding_length = (3 - extra_length) % 3;
(void(padding_length));
for (int i = 0; i < round_length; i += 3)
{
uint32_t const fragment =
buffer[i ] << 24
| buffer[i + 1] << 16
| buffer[i + 2] << 8
;
base64_detail::encode_fragment(output_itr, fragment, 3);
}
uint32_t extras = 0;
for (int i = 0; i < extra_length; i++)
{
extras |= buffer[round_length + i] << (8 * (3 - i));
}
base64_detail::encode_fragment(output_itr, extras, extra_length);
assert(output_itr + padding_length == output.end());
return output;
}
};
constexpr base64_encode_fn base64_encode{};
}
#endif
|
#include "graphics\Singularity.Graphics.h"
namespace Singularity
{
namespace Graphics
{
class VertexPositionNormalTexture
{
private:
#pragma region Static Methods
static VertexDeclaration* GetVertexDeclaration();
#pragma endregion
public:
#pragma region Static Variables
static VertexDeclaration* Declaration;
#pragma endregion
#pragma region Variables
Vector3 position;
Vector3 normal;
Vector2 texCoord;
#pragma endregion
#pragma region Constructors and Finalizers
VertexPositionNormalTexture();
VertexPositionNormalTexture(float x, float y, float z, float nx, float ny, float nz, float u, float v);
VertexPositionNormalTexture(Vector3 pos, Vector3 normal, Vector2 tex);
#pragma endregion
#pragma region Overriden Operator
bool operator== (const VertexPositionNormalTexture &other) const;
#pragma endregion
};
}
}
|
#include <APP_SHARED/app_main.h>
#include <APP_SHARED/fileutil.h>
#include <CORE/BASE/config.h>
#include <CORE/BASE/logging.h>
#include <CORE/VFS/vfs.h>
#include "font_parser.h"
#include <iostream>
#include <string>
using bmfont::FontDef;
using core::util::lexical_cast;
using core::util::files::XmlNode;
FISHY_APPLICATION(BmFontUtil);
core::config::Flag< std::string > g_inputFile("infile", "Input filename", "");
core::config::Flag< std::string >
g_outputFile("outfile", "Output filename", "");
core::config::Flag< bool >
g_exportAsDistanceFont("export_as_distance_font", false);
/**
*
*/
void BmFontUtil::printHelp() {
std::cout << "Usage:" << std::endl;
std::cout << " bmfontutil --infile <i> --outfile <o>" << std::endl;
}
/**
*
*/
void BmFontUtil::init(const char *arg0) {
(void) arg0;
}
/**
*
*/
int BmFontUtil::main() {
g_inputFile.checkSet();
g_outputFile.checkSet();
vfs::Mount("./", "./", std::ios::in | std::ios::out | std::ios::binary);
const vfs::Path filename(g_inputFile.get());
const vfs::Path rootPath(filename.dir());
std::string content;
if (!appshared::parseFileToString(filename, content)) {
Log(LL::Error) << "Unable to open input font set: " << g_inputFile.get();
return eExitCode::BAD_FILE;
}
XmlNode doc;
if (!doc.parse(content)) {
Log(LL::Error) << "Unable to parse XML document.";
return eExitCode::BAD_DATA;
}
size_t nodeIndex;
if (!doc.getChild("font", nodeIndex)) {
Log(LL::Error)
<< "XML is not a valid font file. Missing top level 'font' node.";
return eExitCode::BAD_DATA;
}
FontDef def;
if (!ParseDocument(
def,
rootPath,
doc.getChild(nodeIndex),
g_exportAsDistanceFont.get())) {
return eExitCode::BAD_DATA;
}
if (!appshared::serializeProtoToFile(vfs::Path(g_outputFile.get()), def)) {
Log(LL::Error) << "Unable to write output.";
return eExitCode::EXCEPTION;
}
return eExitCode::OK;
}
|
#include<iostream>
#include<string>
#include <fstream>
#include "Continent.h"
#include "Country.h"
#include "Map.h"
#include <sstream>
#include "MapEditorComponent.h"
using namespace std;
//This function is call when the user add a territory A to the list of adjacent territories of a territory B. This function
//will find the territory A that has been added and will add the territory B to his list of adjacent territories.
Map MapEditorComponent::AddAdjacentEquivalent(Map map, string adjacency, Country* ownTerritory){
vector<Continent> continentList = map.Continents;
for (int i = 0; i < continentList.size(); i++){
vector<Country*> territoryList = continentList.at(i).Country;
for (int j = 0; j < territoryList.size(); j++){
if (territoryList.at(j)->getName() == adjacency){
vector<Country*> adjacencyList = territoryList.at(j)->getBorderingCountries();
adjacencyList.push_back(ownTerritory);
territoryList.at(j)->setBorderingCountries(adjacencyList);
}
}
continentList.at(i).Country = territoryList;
}
map.Continents=continentList;
return map;
}
//This function is call when the user remove a territory A from the list of adjacent territories of a territory B. This function
//will find the territory A that has been removed and will remove the territory B from his list of adjacent territories.
Map MapEditorComponent::DeleteAdjacentEquivalent(Map map, string adjacency, string ownTerritory){
vector<Continent> continentList = map.Continents;
for (int i = 0; i < continentList.size(); i++){
vector<Country*> territoryList = continentList.at(i).Country;
for (int j = 0; j < territoryList.size(); j++){
if (territoryList.at(j)->getName() == adjacency){
vector<Country*> adjacencyList = territoryList.at(j)->getBorderingCountries();
for (int k = 0; k < adjacencyList.size(); k++){
if (adjacencyList.at(k)->getName() == ownTerritory){
adjacencyList.erase(adjacencyList.begin() + k);
}
}
territoryList.at(j)->setBorderingCountries(adjacencyList);
}
}
continentList.at(i).Country= territoryList;
}
map.Continents = continentList;
return map;
}
Map MapEditorComponent::CreateMap(){
string author;
string image;
string wrap;
string scroll;
string warn;
Map map;
//PROMPTS USER FOR ALL ATTRIBUTES OF MAP
cout << "What is the author's name?" << endl;
cin >> author;
cout << "What is the image's extension?" << endl;
cin >> image;
cout << "Is the map wrap?[Y/N]" << endl;
cin >> wrap;
cout << "Is the map vertical or horizontal?[Y/H]" << endl;
cin >> scroll;
cout << "Is the map warn?[Y/N]" << endl;
cin >> warn;
map = Map(author, image, wrap=="Y"?true:false, scroll, warn=="Y"?true:false);
return map;
}
Map MapEditorComponent::EditMap(Map map){
//PROMPTS USER FOR DIFFERENT STUFF TO EDIT
string modification="";
while (modification != "0"){
cout << "What would you like to edit ?[1,2,3,4,5] 0 to exit" << endl;
cout << "1 - Author's Name " << endl;
cout << "2 - Image's Filename " << endl;
cout << "3 - Map's Wrap " << endl;
cout << "4 - Map's Scroll " << endl;
cout << "5 - Map's Warn " << endl;
cout << "0 - Exit" << endl;
cin >> modification;
if (modification == "1"){
cout << "This is the author's name:" << map.getAuthor() << endl;
cout << "Input a new author's name or skip" << endl;
cin.ignore();
getline(cin,modification);
if (modification != "skip"){
map.setAuthor(modification);
}
}
else if (modification == "2"){
cout << "This is the image's filename:" << map.getImage() << endl;
cout << "Input a new image's filename or skip" << endl;
cin.ignore();
getline(cin, modification);
if (modification != "skip"){
map.setImage(modification);
}
}
else if (modification == "3"){
cout << "This is the map's wrap:" << map.getWrap() << endl;
cout << "Input a new map's wrap or skip" << endl;
cin.ignore();
getline(cin, modification);
if (modification != "skip"){
map.setWrap(modification == "true" ? true : false);
}
}
else if (modification == "4"){
cout << "This is the map's scroll:" << map.getScroll() << endl;
cout << "Input a new map's scroll or skip" << endl;
cin.ignore();
getline(cin, modification);
if (modification != "skip"){
map.setScroll(modification);
}
}
else if (modification == "5"){
cout << "This is the map's warn:" << map.getWarn() << endl;
cout << "Input a new map's warn or skip" << endl;
cin.ignore();
getline(cin, modification);
if (modification != "skip"){
map.setWarn(modification == "true" ? true : false);
}
}
else{
break;
}
}
return map;
}
Map MapEditorComponent::EditContinents(Map map){
//PROMPS USER TO DECIDE WHICH CONTINENT TO EDIT
string updateContinentNumber;
cout << "Which continents would you like to edit ? Type exit otherwise" << endl;
for (int i = 0; i < map.Continents.size(); i++)
{
cout << i + 1 << "- " << map.Continents[i].getName() << endl;
}
cin >> updateContinentNumber;
while (updateContinentNumber != "exit"){
string modification = "";
while (modification != "0"){
//ONCE CONTINENT CHOSEN, THE USER CAN MODIFY ANY FIELDS FROM IT
cout << "What would you like to edit ?[1,2] 0 to exit" << endl;
cout << "1 - Continent's Name " << endl;
cout << "2 - Continent's Maximum Number of Units " << endl;
cout << "0 - Exit" << endl;
cin >> modification;
if (modification == "1"){
cout << "This is the continents's name:" << map.Continents[stoi(updateContinentNumber) - 1].getName() << endl;
cout << "Input a new continents's name or skip" << endl;
cin.ignore();
getline(cin, modification);
if (modification != "skip"){
map.Continents[stoi(updateContinentNumber) - 1].setName(modification);
}
}
else if (modification == "2"){
cout << "This is the continents's maximum number of units:" << map.Continents[stoi(updateContinentNumber) - 1].getUnit() << endl;
cout << "Input a new continents's maximum number of units or skip" << endl;
cin >> modification;
if (modification != "skip"){
map.Continents[stoi(updateContinentNumber) - 1].setUnit(stoi(modification));
}
}
else{
break;
}
}
//THE SYSTEM WILL KEEP ON GOING UNTIL THE USER TYPES EXIT
cout << "Which continents would you like to edit ? Type exit otherwise" << endl;
for (int i = 0; i < map.Continents.size(); i++)
{
cout << i + 1 << "- " << map.Continents[i].getName() << endl;
}
cin >> updateContinentNumber;
}
return map;
}
Map MapEditorComponent::EditTerritories(Map map){
string updateTerritoryNumber;
//THE SYSTEM PROMPS THE USER TO DECIDE WHICH TERRITORY HE WOULD LIKE TO EDIT
for (int i = 0; i < map.Continents.size(); i++)
{
cout << "Which territory would you like to edit ? Type next or exit otherwise" << endl;
cout << "These are the territories for " << map.Continents[i].getName() << endl;
for (int j = 0; j < map.Continents[i].Country.size(); j++){
cout << j + 1 << "- " << map.Continents[i].Country[j]->getName() << endl;
}
cin >> updateTerritoryNumber;
if (updateTerritoryNumber == "exit"){
break;
}
while (updateTerritoryNumber != "next"){
//ONCE THE TERRITORY IS CHOSEN, THE USER WILL DECIDE WHICH ATTRIBUTE HE WILL MODIFY
string modification;
cout << "What would you like to edit ?[1,2,3,4,5] 0 to exit" << endl;
cout << "1 - Name " << endl;
cout << "2 - Latitude " << endl;
cout << "3 - Longitude " << endl;
cout << "4 - Continent " << endl;
cout << "5 - Adjacent Territories " << endl;
cout << "0 - Exit" << endl;
cin >> modification;
if(modification == "1"){
cout << "This is the territory's name:" << map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getName() << endl;
cout << "Input a new territory's name" << endl;
cin.ignore();
getline(cin, modification);
if (modification != "skip"){
map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->setName(modification);
}
}
else if(modification == "2"){
cout << "This is the territory's latitude:" << map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getLatitude() << endl;
cout << "Input a new territory's latitude" << endl;
cin >> modification;
if (modification != "skip"){
map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->setLatitude(stoi(modification));
}
}
else if(modification == "3"){
cout << "This is the territory's longitude:" << map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getLongitude() << endl;
cout << "Input a new territory's longitude" << endl;
cin >> modification;
if (modification != "skip"){
map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->setLongitude(stoi(modification));
}
}
else if(modification == "4"){
cout << "This is the territory's continent:" << map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getContinent() << endl;
cout << "Input a new territory's continent" << endl;
cin.ignore();
getline(cin, modification);
if (modification != "skip"){
if (modification != map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getContinent()){
for (int j = 0; j < map.Continents.size(); j++){
//Add to new continent
if (map.Continents[j].getName() == modification){
map.Continents[j].Country.push_back(map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]);
}
}
//Remove from old continent
if (map.Continents[i].getName() == map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getContinent()){
map.Continents[i].Country.erase(map.Continents[i].Country.begin() + stoi(updateTerritoryNumber) - 1);
}
map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->setContinent(modification);
}
}
}
else if (modification == "5"){
cout << "This is the territory's adjacent countries:" << endl;
for(int k=0;k< map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getBorderingCountries().size();k++){
cout << k+1 << "-" << map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getBorderingCountries()[k]->getName() << endl;
}
//ADD AND REMOVE ADJACENT COUNTRIES
cout << "Do you want to add or remove adjacent country?" << endl;
cin >> modification;
if(modification == "add"){
cout << "Type the name of adjacent country you want to add" << endl;
cin >> modification;
bool adjacentExist = false;
Country* c = new Country();
for (int j = 0; j < map.Continents.size(); j++){
for (int k = 0; k < map.Continents[j].Country.size(); k++){
if (modification == map.Continents[j].Country[k]->getName()){
c = map.Continents[j].Country[k];
adjacentExist = true;
}
}
}
if (adjacentExist){
map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getBorderingCountries().push_back(c);
map = MapEditorComponent::AddAdjacentEquivalent(map, modification, map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]);
}
else{
cout << "Adjacent Territory doesn't exist, Please add one that already exists" << endl;
}
}
else if(modification=="remove"){
cout << "Type the name of adjacent country you want to remove" << endl;
cin.ignore();
getline(cin, modification);
Country* c = new Country();
for (int h = 0; h < map.Continents.size(); h++){
for (int m = 0; m < map.Continents[h].Country.size(); m++){
if (modification == map.Continents[h].Country[m]->getName()){
c = map.Continents[h].Country[m];
}
}
}
for(int a=0;a< map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getBorderingCountries().size();a++){
if (map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getBorderingCountries()[a]->getName() == c->getName()){
map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getBorderingCountries().erase(map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getBorderingCountries().begin()+a);
}
}
map = MapEditorComponent::DeleteAdjacentEquivalent(map, modification, map.Continents[i].Country[stoi(updateTerritoryNumber) - 1]->getName());
}
}
else if (modification == "0"){
updateTerritoryNumber = "next";
}
else{
break;
}
}
}
return map;
}
bool MapEditorComponent::ValidateMap(Map map){
vector<Continent> continentList = map.Continents;
for (int i = 0; i < continentList.size(); i++){
string continentName = continentList.at(i).getName();
for (int j = i; j < continentList.size(); j++){
if (continentName == continentList.at(j).getName()){
if (i != j){
return false;
}
}
}
}
for (int i = 0; i < continentList.size(); i++){
vector<Country*> territoryList = continentList.at(i).Country;
for (int j = 0; j < territoryList.size(); j++){
string territoryName = territoryList.at(j)->getName();
for (int k = 0; k < continentList.size(); k++){
for (int l = 0; l < territoryList.size(); l++){
if (i != k && j != l){
if (territoryName == territoryList.at(l)->getName()){
return false;
}
}
}
}
}
}
return true;
}
Map MapEditorComponent::AddTerritory(Map map){
string addTerritory;
string territoryName;
double latitude;
double longitude;
int territoryCount = 1;
string adjacentTerritory;
string continentName;
//PROMPTS USER FOR EVERY DIFFERENT FIELD WHEN CREATING A TERRITORY
cout << "Name your territory #" << territoryCount << endl;
cin.ignore();
getline(cin, territoryName);
cout << "Please specify the latitude of " << territoryName << endl;
cin >> latitude;
cout << "Please specify the longitude of " << territoryName << endl;
cin >> longitude;
vector<Country*> adjacentTerritories;
cout << "Please enter an adjacent territory or stop" << endl;
cin.ignore();
getline(cin, adjacentTerritory);
Country* c = new Country();
for (int i = 0; i < map.Continents.size(); i++){
for (int j = 0; j < map.Continents[i].Country.size(); j++){
if (adjacentTerritory == map.Continents[i].Country[j]->getName()){
c = map.Continents[i].Country[j];
}
}
}
while (adjacentTerritory != "stop"){
adjacentTerritories.push_back(c);
cout << "Please enter an adjacent territory or stop" << endl;
cin.ignore();
getline(cin, adjacentTerritory);
c = new Country();
for (int i = 0; i < map.Continents.size(); i++){
for (int j = 0; j < map.Continents[i].Country.size(); j++){
if (adjacentTerritory == map.Continents[i].Country[j]->getName()){
c = map.Continents[i].Country[j];
}
}
}
}
cout << "Which continent do you want your territory to be added to?" << endl;
getline(cin, continentName);
//CHECK IF TERRITORY ALREADY EXIST
bool territoryAlreadyExists = false;
for (int i = 0; i < map.Continents.size(); i++){
for (int j = 0; j < map.Continents[i].Country.size(); j++){
if (map.Continents[i].Country[j]->getName() == territoryName)
territoryAlreadyExists = true;
}
}
if (territoryAlreadyExists == false)
{
Country* territory = new Country(territoryName, latitude, longitude, continentName, adjacentTerritories);
for (int i = 0; i < map.Continents.size(); i++){
if (map.Continents[i].getName() == continentName){
map.Continents[i].Country.push_back(territory);
}
}
for (int i = 0; i < adjacentTerritories.size(); i++){
map = MapEditorComponent::AddAdjacentEquivalent(map, adjacentTerritories[i]->getName(), territory);
}
}
else{
cout << "Territory already exists, Please create a new one." << endl;
}
return map;
}
Map MapEditorComponent::AddContinentAndTerritories(Map map, string continentName, int continentUnitCount){
string addTerritory;
string territoryName;
double latitude;
double longitude;
int territoryCount = 1;
string adjacentTerritory;
//CHECK IF CONTINENT ALREADY EXISTS
bool continentAlreadyExists = false;
for (int i = 0; i < map.Continents.size(); i++){
if (map.Continents[i].getName() == continentName)
continentAlreadyExists = true;
}
if (continentAlreadyExists == false){
//PROMPTS THE USER TO CREATE TERRITORIES IN ADDITION TO HIS CONTINENT
Continent continent = Continent(continentName, continentUnitCount);
cout << "Do you want to add a territory to " << continentName << " ?" << endl;
cin >> addTerritory;
while (addTerritory == "yes"){
cout << "Name your territory #" << territoryCount << endl;
cin.ignore();
getline(cin, territoryName);
cout << "Please specify the latitude of " << territoryName << endl;
cin >> latitude;
cout << "Please specify the longitude of " << territoryName << endl;
cin >> longitude;
vector<Country*> adjacentTerritories;
cout << "Please enter an adjacent territory or stop" << endl;
cin >> adjacentTerritory;
Country* c = new Country();
for (int i = 0; i < map.Continents.size(); i++){
for (int j = 0; j < map.Continents[i].Country.size(); j++){
if (adjacentTerritory == map.Continents[i].Country[j]->getName()){
c = map.Continents[i].Country[j];
}
}
}
while (adjacentTerritory != "stop"){
adjacentTerritories.push_back(c);
cout << "Please enter an adjacent territory or stop" << endl;
cin.ignore();
getline(cin, adjacentTerritory);
c = new Country();
for (int i = 0; i < map.Continents.size(); i++){
for (int j = 0; j < map.Continents[i].Country.size(); j++){
if (adjacentTerritory == map.Continents[i].Country[j]->getName()){
c = map.Continents[i].Country[j];
}
}
}
}
//CHECK IF TERRITORY ALREADY EXIST
bool territoryAlreadyExists = false;
for (int i = 0; i < map.Continents.size(); i++){
for (int j = 0; j < map.Continents[i].Country.size(); j++){
if (map.Continents[i].Country[j]->getName() == territoryName)
territoryAlreadyExists = true;
}
}
if (territoryAlreadyExists == false)
{
Country* c = new Country();
for (int i = 0; i < map.Continents.size(); i++){
for (int j = 0; j < map.Continents[i].Country.size(); j++){
if (adjacentTerritory == map.Continents[i].Country[j]->getName()){
c = map.Continents[i].Country[j];
}
}
}
Country* territory = new Country(territoryName, latitude, longitude, continentName, adjacentTerritories);
continent.Country.push_back(territory);
territoryCount++;
cout << "Do you want to add a territory to " << continentName << " ?" << endl;
cin >> addTerritory;
}
else{
cout << "Territory already exists, Please create a new one." << endl;
}
}
map.Continents.push_back(continent);
}
else{
cout << "Continent already exists, Please create a new one." << endl;
}
return map;
}
|
/*************************************************************
* > File Name : P3388.cpp
* > Author : Tony
* > Created Time : 2019/09/01 13:46:31
* > Algorithm : Tarjan
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 20010;
struct Edge {
int from, to;
Edge(int u, int v): from(u), to(v) {}
};
vector<Edge> edges;
vector<int> G[maxn];
void add(int u, int v) {
edges.push_back(Edge(u, v));
edges.push_back(Edge(v, u));
int mm = edges.size();
G[v].push_back(mm - 1);
G[u].push_back(mm - 2);
}
bool cut[maxn];
int n, m, num, root, ansi;
int dfn[maxn], low[maxn], s[maxn], ans[maxn];
void tarjan(int x) {
dfn[x] = low[x] = ++num; int flag = 0;
for (int i = 0; i < G[x].size(); ++i) {
Edge& e = edges[G[x][i]];
if (!dfn[e.to]) {
tarjan(e.to);
low[x] = min(low[x], low[e.to]);
if (low[e.to] >= dfn[x]) {
flag++;
if (x != root || flag > 1) {
cut[x] = true;
}
}
} else {
low[x] = min(low[x], dfn[e.to]);
}
}
}
int main() {
n = read(); m = read();
for (int i = 1; i <= m; ++i) {
int u = read(), v = read();
if (u == v) continue;
add(u, v);
}
for (int i = 1; i <= n; ++i) {
if (!dfn[i]) {
root = i;
tarjan(i);
}
}
for (int i = 1; i <= n; ++i) {
if (cut[i]) {
ans[++ansi] = i;
}
}
printf("%d\n", ansi);
for (int i = 1; i <= ansi; ++i) {
printf("%d ", ans[i]);
}
return 0;
}
|
#include "헤더.h"
int main() {
int v1 = 100;
int v2 = 200;
int rs = add(v1, v2);
printf("%d\n", rs);
Person p1;
p1.age = 22;
printf("p1.age : %d\n", p1.age);
//printf("%f\n",pow(2.0,10));
//printf("%f\n", sin(1));
//srand(time(0));
//printf("%d\n", rand() % 10);
return 0;
}
int add(int a, int b) {
return a + b;
}
|
#include "Activity.h"
#include "Utility.h"
Activity::Activity (int stages, int mean)
{
}
void Activity::gen_arr_times (int nums)
{
// generate an array of events and keep them
// in a vector
for (unsigned int i = 0;
i < nums;
i++)
{
Utility::instance ()->gen_erlang_time (this->task_->arr_mean_,
this->task_->arr_stgs_);
}
}
void Activity::gen_arr_stage_times (int nums)
{
// generate an array of events and keep them
// in a vector
for (unsigned int i = 0;
i < nums;
i++)
{
Utility::instance ()->gen_exp_time (this->task_->arr_mean_/this->task_->arr_stgs_);
}
}
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *p1 = head;
int k = 0;
while (head) {
k++;
head = head->next;
}
if (k==n) {
return p1->next;
}
head = p1;
while (k-->(n+1)) {
head = head->next;
}
ListNode *p2 = head->next;
head->next = p2?p2->next:NULL;
return p1;
}
};
|
#include "ServerMessageHandler.hpp"
#include "../../generated/MessageAdapters.hpp"
#include "../Signals.hpp"
#include "../Constants.hpp"
#include "NetPlayerInfo.hpp"
#include "../components/PlayerComponent.hpp"
#include "../components/RenderComponent.hpp"
#include "../components/PositionComponent.hpp"
#include "../components/VelocityComponent.hpp"
#include "../components/InputComponent.hpp"
#include <enet/enet.h>
#include <ecstasy/core/Engine.hpp>
#include <ecstasy/core/Family.hpp>
const int max_size_per_packet = Constants::MAX_MESSAGE_SIZE - sizeof(eznet::MessageType::NUM_TYPES);
ServerMessageHandler::ServerMessageHandler(ENetHost* host, NetPlayerInfos &playerInfos, Engine &engine)
: engine(engine), messageWriter(Constants::MAX_MESSAGE_SIZE), host(host), playerInfos(playerInfos) {
players = engine.getEntitiesFor(Family::all<PlayerComponent, RenderComponent, PositionComponent, VelocityComponent>().get());
connectionScope += engine.entityAdded.connect(this, &ServerMessageHandler::onEntityAdded);
connectionScope += engine.entityAdded.connect(this, &ServerMessageHandler::onEntityRemoved);
connectionScope += Signals::getInstance()->submitChat.connect(this, &ServerMessageHandler::onSubmitChat);
putCallback(this, &ServerMessageHandler::handleHandshakeClientMessage);
putCallback(this, &ServerMessageHandler::handleChatMessage);
putCallback(this, &ServerMessageHandler::handleInputUpdateMessage);
}
ServerMessageHandler::~ServerMessageHandler() { }
void ServerMessageHandler::update(float deltaTime) {
nextBroadcast -= deltaTime;
if(nextBroadcast <= 0) {
nextBroadcast = 0.016f;
broadcastPlayerUpdates();
}
}
void ServerMessageHandler::broadcastPlayerUpdates() {
eznet::UpdatePlayersMessage message;
for(auto entity : *players) {
decltype(message.updates)::value_type entry;
entry.entityId = entity->getId();
entry.packetNumber = entity->get<PlayerComponent>()->packetNumber++;
auto pos = entity->get<PositionComponent>();
entry.x = pos->x;
entry.y = pos->y;
auto vel = entity->get<VelocityComponent>();
entry.velX = vel->x;
entry.velY = vel->y;
if(getMessageSize(message) + getMessageSize(entry)>max_size_per_packet) {
broadcast(NetChannel::WORLD_UNRELIABLE, createPacket(messageWriter, message));
message.updates.clear();
}
message.updates.push_back(std::move(entry));
}
if(!message.updates.empty()) {
broadcast(NetChannel::WORLD_UNRELIABLE, createPacket(messageWriter, message));
}
}
void ServerMessageHandler::onEntityAdded(Entity *entity) {
}
void ServerMessageHandler::onEntityRemoved(Entity *entity) {
}
void ServerMessageHandler::onSubmitChat(const std::string &text) {
eznet::ChatMessage message;
message.message = text;
message.username = playerInfos.slots[0].name;
broadcast(NetChannel::CHAT, createPacket(messageWriter, message));
Signals::getInstance()->chat.emit(message.message, message.username);
}
void ServerMessageHandler::sendCreatePlayers(ENetPeer* peer) {
eznet::CreatePlayersMessage message;
for(auto entity : *players) {
decltype(message.entities)::value_type entry;
entry.entityId = entity->getId();
auto render = entity->get<RenderComponent>();
entry.color = render->color;
entry.size = render->size;
auto pos = entity->get<PositionComponent>();
entry.x = pos->x;
entry.y = pos->y;
auto vel = entity->get<VelocityComponent>();
entry.velX = vel->x;
entry.velY = vel->y;
if(getMessageSize(message) + getMessageSize(entry)>max_size_per_packet) {
send(peer, NetChannel::WORLD_RELIABLE, createPacket(messageWriter, message));
message.entities.clear();
}
message.entities.push_back(std::move(entry));
}
if(!message.entities.empty()) {
send(peer, NetChannel::WORLD_RELIABLE, createPacket(messageWriter, message));
}
}
void ServerMessageHandler::handleHandshakeClientMessage(eznet::HandshakeClientMessage& message, ENetEvent& event) {
NetPlayerInfo* info = static_cast<NetPlayerInfo*>(event.peer->data);
info->status = NetPlayerStatus::CONNECTED;
info->name = message.name;
auto signals = Signals::getInstance();
playerInfos.makeUniqueName(info);
signals->clientConnected.emit(info);
// Create player
auto entity = engine.assembleEntity("player");
auto pos = entity->get<PositionComponent>();
//fixme: pos
pos->x = 0;
pos->y = 0;
auto render = entity->get<RenderComponent>();
render->color = nk_rgb(255,255,255);//fixme: color
// 250, 250, nk_rgba(0,255,0,255)
// 200, 400, nk_rgba(0,0,255,255)
engine.addEntity(entity);
info->entityId = entity->getId();
// Send greeting back
eznet::HandshakeServerMessage reply;
reply.status = status;
reply.entityId = entity->getId();
reply.playerIndex = info->playerIndex;
for (int i=0; i<Constants::MAX_SLOTS; i++) {
auto& info = playerInfos.slots[i];
if(info.status == NetPlayerStatus::CONNECTED) {
reply.playerList.emplace_back();
auto& entry = reply.playerList.back();
entry.name = info.name;
entry.playerIndex = info.playerIndex;
}
}
sendCreatePlayers(event.peer);
send(event.peer, NetChannel::WORLD_RELIABLE, createPacket(messageWriter, reply));
}
void ServerMessageHandler::handleChatMessage(eznet::ChatMessage& message, ENetEvent& event) {
message.username = static_cast<NetPlayerInfo*>(event.peer->data)->name;
broadcast(NetChannel::CHAT, createPacket(messageWriter, message));
Signals::getInstance()->chat.emit(message.message, message.username);
}
void ServerMessageHandler::handleInputUpdateMessage(eznet::InputUpdateMessage& message, ENetEvent& event) {
auto info = static_cast<NetPlayerInfo*>(event.peer->data);
auto entity = engine.getEntity(info->entityId);
if(entity) {
auto input = entity->get<InputComponent>();
if(input) {
input->x = message.moveX;
input->y = message.moveY;
}
}
}
void ServerMessageHandler::send(ENetPeer* peer, NetChannel channel, ENetPacket* packet) {
enet_peer_send(peer, static_cast<uint8_t>(channel), packet);
}
void ServerMessageHandler::broadcast(NetChannel channel, ENetPacket* packet) {
enet_host_broadcast(host, static_cast<uint8_t>(channel), packet);
}
|
#include<bits/stdc++.h>
using namespace std;
int count_ways(int n)
{
int dp[n+1];
dp[0]=dp[1]=1;
dp[2]=2;
for(int i=3;i<=n;i++)
{
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
int main()
{
int n;
cin>>n;
cout<<count_ways(n)<<"\n";
}
|
#include "TShirt.h"
#include "YShirt.h"
#include "Storage.h"
#include <iostream>
int main(int argc, char *argv[])
{
std::shared_ptr<Component> component = std::make_shared<Storage>(
std::make_shared<Decorator>(
std::make_shared<TShirt>()));
std::cout << "[Product]: " << component->product() << std::endl;
std::cout << "[Price]: " << component->price() << std::endl;
return 0;
}
|
#ifndef ROSE_SEMANTICSMODULE_H
#define ROSE_SEMANTICSMODULE_H
#include <stdint.h>
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
static inline int numBytesInAsmType(SgAsmType* ty) {
switch (ty->variantT()) {
case V_SgAsmTypeByte: return 1;
case V_SgAsmTypeWord: return 2;
case V_SgAsmTypeDoubleWord: return 4;
case V_SgAsmTypeQuadWord: return 8;
default: {std::cerr << "Unhandled type " << ty->class_name() << " in numBytesInAsmType" << std::endl; abort();}
}
}
#endif // ROSE_SEMANTICSMODULE_H
|
class Solution {
public:
/*
void rotate(vector<vector<int>>& matrix) {
int widSize = matrix.size(), lenSize = matrix[0].size();
int m = 0, n = 0, i = 0, temp,temp1,x,y;
int sizeMin = lenSize > widSize ? widSize : lenSize;
int widBase = lenSize > widSize ? 0 : widSize -lenSize;
int n_end = widBase, n_start = widSize - 1;
for(m = 0; m < sizeMin/2; m++, n_start--, n_end++) {
for(n = n_start; n > n_end; n--){
y = m; x = n;
temp = matrix[x][y];
for(i = 0; i < 4; i++) {
temp1 = y + widBase;
y = widSize - 1 - x;
x = temp1;
temp1 = matrix[x][y];
matrix[x][y] = temp;
temp = temp1;
}
}
}
if(lenSize > widSize) {
for(m = widSize; m < lenSize; m++){
vector<int> addVec;
for(n = widSize - 1; n > -1; n--) {
addVec.push_back(matrix[n][m]);
}
matrix.push_back(addVec);
}
for(n = 0; n < widSize; n++) {
matrix[n].erase(matrix[n].end() -(lenSize - widSize), matrix[n].end());
}
} else if(lenSize < widSize) {
for(m = widBase - 1; m > -1; m--){
for(n = widBase; n < widSize; n++){
matrix[n].push_back(matrix[m][n-widBase]);
}
}
matrix.erase(matrix.begin(), matrix.begin() + widBase);
}
return;
}*/
public:
void rotate(vector<vector<int>>& matrix) {
reverse(matrix.begin(), matrix.end());
for(int i = 0;i < matrix.size(); i++){
for(int j = i + 1; j < matrix.size(); j++){
swap(matrix[i][j], matrix[j][i]);
}
}
return;
}
};
|
//
// RenderTexture.h
// cheetah
//
// Copyright (c) 2013 cafaxo. All rights reserved.
//
#ifndef cheetah_RenderTexture_h
#define cheetah_RenderTexture_h
#include "RenderTarget.h"
class Texture;
class RenderTexture : public RenderTarget {
public:
RenderTexture();
void attach(Texture &texture);
};
#endif
|
//! @file sound.h
//! @brief SoundControlクラスの宣言
/**
* LynxOPS
*
* Copyright (c) 2015 Nilpaca
*
* Licensed under the MIT License.
* https://github.com/Nilpaca/LynxOPS/blob/master/LICENSE
*/
//--------------------------------------------------------------------------------
//
// OpenXOPS
// Copyright (c) 2014-2015, OpenXOPS Project / [-_-;](mikan) All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the OpenXOPS Project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL OpenXOPS Project 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.
//--------------------------------------------------------------------------------
#ifndef SOUND2_H
#define SOUND2_H
#define MAX_LOADSOUND 24 //!< サウンドを読み込める最大数(ezds.dll)
#define MAX_SOUNDLISTS 100 //!< サウンドを再生する最大数(DirectSound)
#define MAX_SOUNDDIST 335 //!< サウンドを再生する最大距離
#ifndef H_LAYERLEVEL
#define H_LAYERLEVEL 1 //!< Select include file.
#endif
#include "main.h"
#include <windows.h>
// #define SOUND_DIRECTSOUND //!< @brief サウンドの再生ライブラリを選択 @details 定数宣言有効: DirectSound 定数宣言無効(コメント化): ezds.dll
#ifdef SOUND_DIRECTSOUND
#include <dsound.h>
#include <mmsystem.h>
#pragma comment(lib, "dsound.lib")
#pragma comment(lib, "dxguid.lib")
#pragma comment(lib, "winmm.lib")
#define SOUND_CORE "DirectSound" //!< バージョン表示用情報
#else // #ifdef SOUND_DIRECTSOUND
typedef int (*FARPROCH)(HWND); //!< DLL Parameter
typedef int (*FARPROCCI)(char *, int); //!< DLL Parameter
typedef int (*FARPROCIII)(int, int, int); //!< DLL Parameter
typedef int (*FARPROCI)(int); //!< DLL Parameter
#define SOUND_CORE L"ezds" //!< バージョン表示用情報
#endif // #ifdef SOUND_DIRECTSOUND
//! @brief サウンドを再生するクラス
//! @details サウンドの読み込みから再生までを管理します
//! @details 内部では ezds.dll を呼び出して使用しています
//! @details 参考資料: "みかん箱" http://mikan.the-ninja.jp/ ⇒ 技術資料 ⇒ ezds.dllファイル解析資料
class SoundControl
{
#ifdef SOUND_DIRECTSOUND
LPDIRECTSOUND8 pDSound; //!< DIRECTSOUND8のポインタ
LPDIRECTSOUNDBUFFER pDSBuffer[MAX_LOADSOUND][MAX_SOUNDLISTS]; //!< セカンダリーバッファー
LPDIRECTSOUND3DLISTENER8 p3DListener; //!< リスナー
bool CheckSoundFile(wchar_t *filename, int *filesize, int *fileoffset, WAVEFORMATEX **pwfex);
int GetDSVolume(int volume);
public:
SoundControl();
~SoundControl();
int InitSound(WindowControl *WindowCtrl);
void DestroySound();
void SetVolume(float volume);
void SetCamera(float x, float y, float z, float rx);
int LoadSound(wchar_t *filename);
int PlaySound(int id, int volume, int pan);
int Play3DSound(int id, float x, float y, float z, int volume);
void CleanupSound(int id);
#else // #ifdef SOUND_DIRECTSOUND
HINSTANCE lib; //!< DLLファイルのインスタンス
FARPROC DSver; //!< DSver()
FARPROCH DSinit; //!< DSinit()
FARPROC DSend; //!< DSend()
FARPROCCI DSload; //!< DSload()
FARPROCIII DSplay; //!< DSplay()
FARPROCI DSrelease; //!< DSrelease()
bool useflag[MAX_LOADSOUND]; //!< 使用中のサウンド番号を管理する配列
float camera_x; //!< カメラ座標
float camera_y; //!< カメラ座標
float camera_z; //!< カメラ座標
float camera_rx; //!< カメラX軸角度
float mastervolume; //!< 音量
bool CheckSourceDist(float x, float y, float z, bool near, float *out_dist);
int CalculationVolume(int MaxVolume, float dist, bool near);
public:
SoundControl();
~SoundControl();
int InitSound(WindowControl *WindowCtrl);
void DestroySound();
void SetVolume(float volume);
void SetCamera(float x, float y, float z, float rx);
int LoadSound(wchar_t *filename);
int PlaySound(int id, int volume, int pan);
int Play3DSound(int id, float x, float y, float z, int volume);
void CleanupSound(int id);
#endif // #ifdef SOUND_DIRECTSOUND
};
#endif
|
#pragma once
#include <GL\glew.h>
#include "shader.hpp"
#include "texture_2d.hpp"
#include "sprite.hpp"
class MouseEffect
{
private:
Shader* shader;
Texture2D* texture;
GLuint VAO;
GLuint VBO;
GLuint instanceVBO;
glm::mat4 model;
public:
MouseEffect(Shader* shader, Texture2D* texture);
~MouseEffect();
void render(const glm::mat4& view, const glm::mat4& projection);
void update(const glm::vec2& pixiePos, float deltaTime);
private:
void initMouseEffect();
};
|
#include "il2cpp-config.h"
#include "C:\Users\nrewkows\Desktop\COMP776Final\LaparoHololensAppUnity\_build\Il2CppOutputProject\IL2CPP\libil2cpp\debugger\il2cpp-stubs.cpp"
|
#include<iostream>
using namespace std;
void permutation(string s, string ans){
if(s.length()==0){
cout<<ans<<endl;
return;
}
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve(){
ll a,b;
cin>>a>>b;
if(a==b) {
cout<<0<<" "<<0<<"\n";
return;
}
ll p=max(a,b),q=min(a,b);
ll x=p-q;
ll a1 =p/x*x,a2=q/x*x;
ll b1=a1+x,b2=a2+x;
/*ll ans1=LLONG_MAX,ans2=LLONG_MAX;
if(p-a1==q-a2) ans1=p-a1;
if(b1-p==b2-q) ans2=b2-p;*/
ll ans1;
if(p%x==0) ans1=0;
else { ans1 = min(p-p/x*x,(p/x+1)*x-p);}
cout<<x<<" "<<ans1<<"\n";
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("op.txt","w",stdout);
#endif
int t=1;
cin>>t;
while(t--){
solve();
}
}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <string>
#include <string.h>
#include <list>
#include "rapidxml_utils.hpp"
#include "rapidxml.hpp"
#include "rapidxml_print.hpp"
using namespace std;
using namespace rapidxml;
class Status{
public:
string object;
string status;
Status(string object_input, string status_input)
{
object = object_input;
status = status_input;
}
};
|
//program demonstruje działanie funkcji glutMouseFunc()
//Wciskanie przycisków myszy powoduje zmianę kolorów trzech ścian kostki,
//Zwalnianie przycisków przywraca kolory początkowe
#include <windows.h>
#include "freeglut.h"
#include <math.h>
float fovy = 45.0, aspect = 1.0, near_ = 0.1, far_ = 10.0;//parametry dla gluPerspective();
//tablica kolorów do wyboru
float kolory[6][3]={
{1.0, 0.0, 0.0},
{0.0, 1.0, 0.0},
{0.0, 0.0, 1.0},
{1.0, 1.0, 0.0},
{1.0, 0.0, 1.0},
{0.0, 1.0, 1.0}
};
float koloryKostki[6][3];//bieżąca tablica kolorów dla kostki
void ustawKoloryKostki(float c[][3])//inicjacja tablicy kolorów dla kostki
{
for (int i=0; i<6; i++)
for (int j=0; j<3; j++) koloryKostki[i][j]=c[i][j];
}
void ustawKolor(float c[])//ustawienie bieżącego koloru
{
glColor3f(c[0], c[1], c[2]);
}
void zmienKolor(float c1[], float c2[])//zmiana kolorów
{
for (int i=0; i<3; i++) c1[i]=c2[i];
}
void kostka()
{
glBegin(GL_QUADS);
//ściana: y = 0.5
ustawKolor(koloryKostki[0]);
glVertex3f( 0.5, 0.5, 0.5);
glVertex3f( 0.5, 0.5, -0.5);
glVertex3f(-0.5, 0.5, -0.5);
glVertex3f(-0.5, 0.5, 0.5);
//ściana: y = -0.5
ustawKolor(koloryKostki[1]);
glVertex3f( 0.5, -0.5, 0.5);
glVertex3f( 0.5, -0.5, -0.5);
glVertex3f(-0.5, -0.5, -0.5);
glVertex3f(-0.5, -0.5, 0.5);
//ściana: x = 0.5
ustawKolor(koloryKostki[2]);
glVertex3f( 0.5, 0.5, 0.5);
glVertex3f( 0.5, 0.5, -0.5);
glVertex3f( 0.5, -0.5, -0.5);
glVertex3f( 0.5, -0.5, 0.5);
//ściana: x = -0.5
ustawKolor(koloryKostki[3]);
glVertex3f(-0.5, 0.5, 0.5);
glVertex3f(-0.5, 0.5, -0.5);
glVertex3f(-0.5, -0.5, -0.5);
glVertex3f(-0.5, -0.5, 0.5);
//ściana: z = 0.5
ustawKolor(koloryKostki[4]);
glVertex3f( 0.5, 0.5, 0.5);
glVertex3f( 0.5, -0.5, 0.5);
glVertex3f(-0.5, -0.5, 0.5);
glVertex3f(-0.5, 0.5, 0.5);
//ściana: z = -0.5
ustawKolor(kolory[5]);
glVertex3f( 0.5, 0.5, -0.5);
glVertex3f( 0.5, -0.5, -0.5);
glVertex3f(-0.5, -0.5, -0.5);
glVertex3f(-0.5, 0.5, -0.5);
glEnd();
}
void display()
{
glClearColor(1.0,1.0,1.0,1.0);
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluPerspective(fovy, aspect, near_, far_);
gluLookAt(3.0, 3.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
kostka();
glFlush();
glutSwapBuffers();
}
void odrysuj(int szerokosc, int wysokosc){
float h = float(wysokosc), w = float(szerokosc);
glViewport(0, 0, szerokosc, wysokosc);
glLoadIdentity();
gluPerspective(fovy, w/h, near_, far_);
}
void mysz(int przycisk, int stan, int x, int y)
{
if (stan == GLUT_DOWN) {
switch (przycisk) {
case GLUT_LEFT_BUTTON:
zmienKolor(koloryKostki[0],kolory[1]);
glutPostRedisplay();
break;
case GLUT_MIDDLE_BUTTON:
zmienKolor(koloryKostki[2],kolory[3]);
glutPostRedisplay();
break;
case GLUT_RIGHT_BUTTON:
zmienKolor(koloryKostki[4],kolory[5]);
glutPostRedisplay();
break;
}
}
else if (stan == GLUT_UP){
switch (przycisk) {
case GLUT_LEFT_BUTTON:
zmienKolor(koloryKostki[0],kolory[0]);
glutPostRedisplay();
break;
case GLUT_MIDDLE_BUTTON:
zmienKolor(koloryKostki[2],kolory[2]);
glutPostRedisplay();
break;
case GLUT_RIGHT_BUTTON:
zmienKolor(koloryKostki[4],kolory[4]);
glutPostRedisplay();
break;
}
}
}
void main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(400,300);
glutInitWindowPosition(100,100);
glutCreateWindow("Scena testowa");
glutDisplayFunc(display);
glutReshapeFunc(odrysuj);
glutMouseFunc(mysz);
ustawKoloryKostki(kolory);
glutMainLoop();
}
|
// Qt3D documentation : http://doc.qt.io/qt-5/qt3d-basicshapes-cpp-main-cpp.html
#ifndef VISUALIZATION_H
#define VISUALIZATION_H
#include <Qt3DExtras>
#include <QWidget>
#include <QVBoxLayout>
#include "serial/packet.h"
#include "protocol/helper.h"
class Visualization : public QWidget {
Q_OBJECT
public:
explicit Visualization(QWidget *parent = nullptr);
signals:
public slots:
void visualization_state(bool state);
void update_angles(AP_DATA2GCS_struct s);
private:
AP_DATA2GCS_struct _last;
bool _last_is_defined = false;
bool _enabled = false;
Qt3DCore::QEntity *_cube;
Qt3DCore::QTransform *_cuboidTransform;
};
#endif // VISUALIZATION_H
|
#include <iostream>
#include <time.h>
using namespace std;
int main(int argc, char *argv[])
{
int NUMnumbers = atoi(argv[1]);
int seed1 = atoi(argv[2]);
int seed2 = atoi(argv[3]);
int Pid = fork();
if (Pid == -1)
perror("fork failed");
if(Pid == 0) //Child
{
clock_t t = clock();
srand (seed2);
int currentNum = 0;
int numPrime = 0;
int notPrime = 0;
//create random numbers and check if prime
for (int k = 0; k < NUMnumbers; k++)
{
currentNum = rand();
//check prime -----------------------------
int i = 2;
bool Prime = 1;
while (i < currentNum && Prime)
{
if (currentNum % i == 0)
Prime = 0;
i++;
}
if(Prime == 1)
numPrime++;
else
notPrime++;
}
//display
t = clock() - t;
cout << "C id:" << getpid() << " Prime:" << numPrime << " NotPrime:" << notPrime
<< " " << ((float)t)/CLOCKS_PER_SEC << "seconds" << endl;
}
else //Parent
{
clock_t t = clock();
srand (seed1);
int currentNum = 0;
int numPrime = 0;
int notPrime = 0;
//create random numbers and check if prime
for (int k = 0; k < NUMnumbers; k++)
{
currentNum = rand();
//check prime -----------------------------
int i = 2;
bool Prime = 1;
while (i < currentNum && Prime)
{
if (currentNum % i == 0)
Prime = 0;
i++;
}
if(Prime == 1)
numPrime++;
else
notPrime++;
}
//display
t = clock() - t;
cout << "P id:" << getpid() << " Prime:" << numPrime << " NotPrime:" << notPrime
<< " " << ((float)t)/CLOCKS_PER_SEC << "seconds" << endl;
}
}
|
/**
* @file main.cpp
* @date 10.02.2019
* @author jspahl
*/
#include <chrono>
#include <iostream>
#include "autopas/autopasIncludes.h"
#include "autopas/containers/directSum/DirectSumTraversal.h"
#include "autopas/containers/linkedCells/traversals/C01CudaTraversal.h"
#include "autopas/pairwiseFunctors/LJFunctor.h"
using namespace std;
using namespace autopas;
class MyMolecule : public Particle {
public:
MyMolecule() : Particle(), _myvar(0) {}
MyMolecule(std::array<double, 3> r, std::array<double, 3> v, unsigned long i, int myvar)
: Particle(r, v, i), _myvar(myvar) {}
void print() {
cout << "Molecule with position: ";
for (auto &r : getR()) {
cout << r << ", ";
}
cout << "and force: ";
for (auto &f : getF()) {
cout << f << ", ";
}
cout << "ID: " << getID();
cout << " myvar: " << _myvar << endl;
}
// typedef autopas::utils::SoAType<size_t, float, float, float, float, float, float>::Type SoAArraysType;
// typedef autopas::utils::CudaSoAType<size_t, float, float, float, float, float, float>::Type CudaDeviceArraysType;
private:
int _myvar;
};
template <class Container>
void fillSpaceWithGrid(Container &pc, std::array<double, 3> boxMin, std::array<double, 3> boxMax, double gridsize,
int maxN = 10000) {
int i = 0;
for (double x = boxMin[0]; x < boxMax[0]; x += gridsize) {
for (double y = boxMin[1]; y < boxMax[1]; y += gridsize) {
for (double z = boxMin[2]; z < boxMax[2]; z += gridsize) {
std::array<double, 3> arr({x, y, z});
MyMolecule m(arr, {0., 0., 0.}, static_cast<unsigned long>(i), i);
pc.addParticle(m);
if (++i >= maxN) {
return;
}
}
}
}
}
int main(int argc, char **argv) {
autopas::Logger::create();
int maxIterations = 5;
long numParticles = 10000;
std::array<double, 3> boxMin({0., 0., 0.}), boxMax({33., 33., 33.});
double cutoff = 3.0;
double skin = 0.;
double epsilon = 2.0;
double sigma = 0.4;
DirectSum<MyMolecule, FullParticleCell<MyMolecule>> dir(boxMin, boxMax, cutoff, skin);
LinkedCells<MyMolecule, FullParticleCell<MyMolecule>> lc(boxMin, boxMax, cutoff, skin);
fillSpaceWithGrid<>(dir, boxMin, boxMax, 0.8, numParticles);
fillSpaceWithGrid<>(lc, boxMin, boxMax, 0.8, numParticles);
typedef LJFunctor<MyMolecule, FullParticleCell<MyMolecule>> Func;
Func func(cutoff, epsilon, sigma, 0.0);
DirectSumTraversal<FullParticleCell<MyMolecule>, Func, DataLayoutOption::aos, false> traversalAoS(&func);
DirectSumTraversal<FullParticleCell<MyMolecule>, Func, DataLayoutOption::soa, false> traversalSoA(&func);
DirectSumTraversal<FullParticleCell<MyMolecule>, Func, DataLayoutOption::cuda, false> traversalCuda(&func);
DirectSumTraversal<FullParticleCell<MyMolecule>, Func, DataLayoutOption::cuda, true> traversalCudaN3(&func);
C08Traversal<FullParticleCell<MyMolecule>, Func, DataLayoutOption::soa, true> traversalc08N3(
lc.getCellBlock().getCellsPerDimensionWithHalo(), &func);
C01Traversal<FullParticleCell<MyMolecule>, Func, DataLayoutOption::cuda, false> C01Cuda(
lc.getCellBlock().getCellsPerDimensionWithHalo(), &func);
C01CudaTraversal<FullParticleCell<MyMolecule>, Func, DataLayoutOption::cuda, false> traversalLCcuda(
lc.getCellBlock().getCellsPerDimensionWithHalo(), &func);
C01CudaTraversal<FullParticleCell<MyMolecule>, Func, DataLayoutOption::cuda, true> traversalLCcudaN3(
lc.getCellBlock().getCellsPerDimensionWithHalo(), &func);
dir.iteratePairwise(&traversalAoS);
lc.iteratePairwise(&traversalc08N3);
auto start = std::chrono::high_resolution_clock::now();
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<int64_t, micro>::rep duration;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxIterations; ++i) {
dir.iteratePairwise(&traversalAoS);
}
stop = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
cout << "DsAoS: " << maxIterations << " iterations with " << dir.getNumParticles() << " particles took: " << duration
<< " microseconds" << endl;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxIterations; ++i) {
dir.iteratePairwise(&traversalSoA);
}
stop = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
cout << "DsSoA: " << maxIterations << " iterations with " << dir.getNumParticles() << " particles took: " << duration
<< " microseconds" << endl;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxIterations; ++i) {
dir.iteratePairwise(&traversalCuda);
}
stop = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
cout << "DsCuda:" << maxIterations << " iterations with " << dir.getNumParticles() << " particles took: " << duration
<< " microseconds" << endl;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxIterations; ++i) {
dir.iteratePairwise(&traversalCudaN3);
}
stop = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
cout << "DsCudaN3:" << maxIterations << " iterations with " << dir.getNumParticles()
<< " particles took: " << duration << " microseconds" << endl;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxIterations; ++i) {
lc.iteratePairwise(&traversalc08N3);
}
stop = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
cout << "LcSoAN3:" << maxIterations << " iterations with " << lc.getNumParticles() << " particles took: " << duration
<< " microseconds" << endl;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxIterations; ++i) {
lc.iteratePairwise(&C01Cuda);
}
stop = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
cout << "LcCudaN3:" << maxIterations << " iterations with " << lc.getNumParticles() << " particles took: " << duration
<< " microseconds" << endl;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxIterations; ++i) {
lc.iteratePairwise(&traversalLCcuda);
}
stop = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
cout << "LcTraversalCudaNoN3:" << maxIterations << " iterations with " << lc.getNumParticles()
<< " particles took: " << duration << " microseconds" << endl;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxIterations; ++i) {
lc.iteratePairwise(&traversalLCcudaN3);
}
stop = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
cout << "LcTraversalCudaN3:" << maxIterations << " iterations with " << lc.getNumParticles()
<< " particles took: " << duration << " microseconds" << endl;
return EXIT_SUCCESS;
}
|
#ifndef ZOMBIE_EVENT_H
# define ZOMBIE_EVENT_H
# include <iostream>
# include "Zombie.hpp"
class ZombieEvent {
public:
static std::string type;
static void setZombieType(std::string zType);
static Zombie* newZombie(std::string name);
static Zombie* randomChump(void);
};
#endif
|
#include <iostream>
#include <cstdio>
//#include <bits/stdc++.h>
#include <algorithm>
#define Inf 0x3f3f3f3f
#define NeInf 0xc0c0c0c0
using namespace std;
int locate[21],sequence2[21],len[21];
int main()
{
//freopen("..\\file\\input_ascii.txt","r",stdin);
//freopen("..\\file\\output.txt","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for(int i=1;i<=n;++i) cin >> locate[i];
int a;
while(cin >> a){
sequence2[a]=1;
for(int i=2;i<=n;++i){
cin >> a;
sequence2[a]=i;
}
int maxn=1;
for(int i=1;i<=n;++i){
len[i]=1;
for(int j=1;j<i;++j){
if(locate[sequence2[j]]<locate[sequence2[i]])
len[i]=max(len[i],len[j]+1);
}
maxn=max(maxn,len[i]);
}
cout << maxn << "\n";
}
return 0;
}
#include <iostream>
#include <cstdio>
//#include <bits/stdc++.h>
#include <algorithm>
#include <vector>
#define Inf 0x3f3f3f3f
#define NeInf 0xc0c0c0c0
using namespace std;
int locate[21],sequence2[21],len[21];
bool cmp(const int a, const int b){
return locate[a]<locate[b];
}
int main()
{
//freopen("..\\file\\input_ascii.txt","r",stdin);
//freopen("..\\file\\output.txt","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for(int i=1;i<=n;++i) cin >> locate[i];
int a;
while(cin >> a){
sequence2[a]=1;
for(int i=2;i<=n;++i){
cin >> a;
sequence2[a]=i;
}
vector<int> v;
v.push_back(sequence2[1]);
for(int i=2;i<=n;++i){
if(locate[sequence2[i]]>locate[v.back()])
v.push_back(sequence2[i]);
else *lower_bound(v.begin(),v.end(),sequence2[i],cmp)=sequence2[i];
}
cout << v.size() << "\n";
}
return 0;
}
|
// This file has been generated by Py++.
// Header file workaround.hpp
//
// Indexing-specific workarounds for compiler problems.
//
// Copyright (c) 2003 Raoul M. Gough
//
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy
// at http://www.boost.org/LICENSE_1_0.txt)
//
// History
// =======
// 2003/10/21 rmg File creation
// 2008/12/08 Roman Change indexing suite layout
//
// $Id: workaround.hpp,v 1.1.2.3 2003/11/17 19:27:13 raoulgough Exp $
//
#ifndef BOOST_PYTHON_INDEXING_WORKAROUND_HPP
#define BOOST_PYTHON_INDEXING_WORKAROUND_HPP
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
# if (BOOST_WORKAROUND (__GNUC__, < 3))
# // gcc versions before 3 (like 2.95.3) don't have the "at" member
# // function in std::vector or std::deque
# define BOOST_PYTHON_INDEXING_AT operator[]
# else
# define BOOST_PYTHON_INDEXING_AT at
# endif
# if BOOST_WORKAROUND (BOOST_MSVC, <= 1300)
// Workaround the lack of a reset member function in std::auto_ptr
namespace boost { namespace python { namespace indexing {
template<typename T> void reset_auto_ptr (T &aptr, T::element_type *pptr) {
aptr = T (pptr);
}
} } }
# define BOOST_PYTHON_INDEXING_RESET_AUTO_PTR ::boost::python::indexing::reset_auto_ptr
# else
# define BOOST_PYTHON_INDEXING_RESET_AUTO_PTR( aptr, pptr ) (aptr).reset(pptr)
# endif
#endif // BOOST_PYTHON_INDEXING_WORKAROUND_HPP
|
int n,m;
vector<vector<int> > g;
vector<int> vis;
void dfs(int node, int comp)
{
//
// Debugging
cout << "NODE" << " " << node << " " << " COMP" << comp <<"\n";
//
vis[node]=comp;
for(auto v:g[node])
{
if(!vis[v])
{
dfs(v,comp);
}
}
}
void solve()
{
cin>>n>>m;
g.resize(n+1);
vis.assign(n+1,0);
for(lli i=0;i<m;i++)
{
int a,b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
int stComp=0;
for(int i=1;i<=n;i++)
{
if(!vis[i]){
stComp++;
dfs(i,stComp);
}
}
}
|
#include "iostream"
#include "math.h"
#include "stdlib.h"
#include "time.h"
#include "unistd.h"
#include"su_trace_head.h"
#define PI 3.1415926
#define NX 400
#define NZ 400
#define PML 150
#include"model.h"
#include"fd.h"
using namespace std;
int main()
{
//---------------------------------------------//
// 计时器--开始 //
//---------------------------------------------//
clock_t start,finish;
double totaltime;
start=clock();
//---------------------------------------------//
// 正演模拟 //
//---------------------------------------------//
forward();
//---------------------------------------------//
// 反演成像 //
//---------------------------------------------//
//---------------------------------------------//
// 计时器--结束 //
//---------------------------------------------//
finish=clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
printf("\n此程序的运行时间为: %f 秒\n",totaltime);
return 0;
}
|
#ifndef PROJECT2_REPORT_H
#define PROJECT2_REPORT_H
#include <ostream>
class Report {
long double avgWaitingTime = 0;
unsigned long missedFlights = 0;
public:
Report(long double avgWaitingTime, unsigned long missedFlights);
friend std::ostream& operator<<(std::ostream& os, const Report& report);
};
#endif //PROJECT2_REPORT_H
|
//
// Copyright (c) 2009 Rutger ter Borg
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_NUMERIC_BINDINGS_BLAS_COPY_HPP
#define BOOST_NUMERIC_BINDINGS_BLAS_COPY_HPP
#include <boost/numeric/bindings/blas/level1/copy.hpp>
namespace boost {
namespace numeric {
namespace bindings {
namespace blas {
using level1::copy;
}}}} // namespace boost::numeric::bindings::blas
#endif
|
Chapter 3 : Example 4
#include "pch.h"
#include <iostream>
#include "gtest/gtest.h"
using namespace std;
std::ostringstream out;
void PrintVector()
{
std::vector<int> myVector;
for (int i = 0; i < myVector.size(); ++i)
{
out << myVector[i];
}
out << "\n\n";
}
std::string TestCase() {
PrintVector();
return out.str();
}
TEST(Chapter3, Example4) {
EXPECT_EQ("\n\n", TestCase());
}
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Chapter 3 : Example 5
#include "pch.h"
#include <iostream>
#include "gtest/gtest.h"
using namespace std;
std::ostringstream out;
std::vector<int> myVector{ 1, 2, 3, 4, 5 };
void PrintVector()
{
for (int i = 0; i < myVector.size(); ++i)
{
out << myVector[i];
}
out << "\n\n";
}
std::string TestCase() {
myVector.pop_back();
PrintVector();
myVector.push_back(6);
PrintVector();
myVector.erase(myVector.begin() + 1);
PrintVector();
myVector.insert(myVector.begin() + 3, 8);
PrintVector();
return out.str();
}
TEST(Chapter3, Example5) {
EXPECT_EQ("1234\n\n12346\n\n1346\n\n13486\n\n", TestCase());
}
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Chapter 3 : Example 6
#include "pch.h"
#include <iostream>
#include "gtest/gtest.h"
using namespace std;
std::ostringstream out;
class MyClass
{
public:
MyClass()
{
out << "My Class Constructor Called\n";
myPublicInt = 5;
}
int myPublicInt = 0;
~MyClass()
{
out << "My Class Destructor Called\n";
}
};
std::string TestCase() {
{
out << "Application started\n";
MyClass testClass;
out << testClass.myPublicInt << "\n";
}
return out.str();
}
TEST(Chapter3, Example6) {
EXPECT_EQ("Application started\nMy Class Constructor Called\n5\nMy Class Destructor Called\n", TestCase());
}
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Chapter 3 : Example 7
#include "pch.h"
#include <iostream>
#include "gtest/gtest.h"
using namespace std;
std::ostringstream out;
class MyClass
{
public:
int myInt = 0;
bool myBool = false;
std::string GetString()
{
return "Hello World!";
}
};
struct MyStruct
{
int myInt = 0;
int myBool = 0;
std::string GetString()
{
return "Hello World!";
}
};
std::string TestCase() {
MyClass classObject;
out << "classObject::myInt: " << classObject.myInt << "\n";
out << "classObject::myBool: " << classObject.myBool << "\n";
out << "classObject::GetString: " << classObject.GetString() << "\n";
MyStruct structObject;
out << "\nstructObject::myInt: " << structObject.myInt << "\n";
out << "structObject::myBool: " << structObject.myBool << "\n";
out << "structbject::GetString: " << structObject.GetString() << "\n";
return out.str();
}
TEST(Chapter3, Example7) {
EXPECT_EQ("classObject::myInt: 0\nclassObject::myBool: 0\nclassObject::GetString: Hello World!\n\nstructObject::myInt: 0\nstructObject::myBool: 0\nstructbject::GetString: Hello World!\n", TestCase());
}
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Chapter 3 : Example 8
#include "pch.h"
#include <iostream>
#include "gtest/gtest.h"
using namespace std;
std::ostringstream out;
int MyInt()
{
int myInt = 0;
return ++myInt;
}
std::string TestCase() {
for (int i = 0; i < 5; ++i)
{
out << MyInt();
}
return out.str();
}
TEST(Chapter3, Example8) {
EXPECT_EQ("11111", TestCase());
}
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Chapter 3 : Activity
#include "pch.h"
#include <iostream>
#include "gtest/gtest.h"
using namespace std;
struct Person
{
int age = 0;
std::string name = "";
};
std::vector<Person> records;
void AddRecord(std::string newName, int newAge)
{
Person newRecord;
newRecord.name = newName;
newRecord.age = newAge;
records.push_back(newRecord);
};
Person FetchRecord(int userID)
{
return records.at(userID);
};
std::string TestCase(std::string inputString, std::string name, std::string age) {
std::ostringstream out;
// Determine user selection.
switch (std::stoi(inputString))
{
case 1:
{
AddRecord(name, std::stoi(age));
}
break;
case 2:
{
int userID = 0;
userID = std::stoi(name);
Person person;
try
{
person = FetchRecord(userID);
}
catch (const std::out_of_range& oor) {
out << "\nError: Invalid UserID.\n\n";
break;
}
out << "User Name: " << person.name << "\n";
out << "User Age: " << person.age << "\n\n";
}
break;
default:
out << "\n\nError: Invalid option selection.\n\n";
break;
}
return out.str();
}
TEST(Chapter3, Activity) {
EXPECT_EQ("", TestCase("1", "Mukesh", "28"));
EXPECT_EQ("", TestCase("1", "Rakesh", "40"));
EXPECT_EQ("", TestCase("1", "Prakash", "12"));
EXPECT_EQ("User Name: Prakash\nUser Age: 12\n\n", TestCase("2", "2", ""));
EXPECT_EQ("User Name: Mukesh\nUser Age: 28\n\n", TestCase("2", "0", ""));
EXPECT_EQ("\n\nError: Invalid option selection.\n\n", TestCase("5", "Prakash", "12"));
EXPECT_EQ("\nError: Invalid UserID.\n\n", TestCase("2", "10", ""));
}
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
//
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_DEF_BUILDER_ENUMERATE_PROVIDERS_HPP
#define NBDL_DEF_BUILDER_ENUMERATE_PROVIDERS_HPP
#include <mpdef/list.hpp>
#include <mpdef/tree_node.hpp>
#include <nbdl/def/builder/enumerate_access_points.hpp>
#include <nbdl/def/builder/producer_meta.hpp>
#include <nbdl/def/directives.hpp>
namespace nbdl_def {
namespace builder {
struct enumerate_producers_fn
{
template<typename ProducerDefs>
auto helper(ProducerDefs defs) const
{
return hana::unpack(defs,
[](auto... producer_def) {
return mpdef::make_list(builder::make_producer_meta(
hana::second(producer_def)[tag::Type],
hana::find(hana::second(producer_def), tag::Name)
.value_or(hana::second(producer_def)[tag::Type]),
builder::enumerate_access_points(producer_def)
)...);
}
);
}
template<typename Def>
constexpr auto operator()(Def) const
{
constexpr auto children = hana::second(Def{});
constexpr auto single_producer = hana::transform(hana::find(children, tag::Producer),
hana::partial(mpdef::make_tree_node, tag::Producer));
constexpr auto producers = hana::find(children, tag::Producers);
static_assert(hana::value(
((single_producer == hana::nothing) || (producers == hana::nothing))
&& hana::not_(single_producer == hana::nothing && producers == hana::nothing)
), "A definition of a Producer or Producers is required.");
return decltype(
helper(producers.value_or(
hana::maybe(mpdef::make_list(), mpdef::make_list, single_producer)
)
)
){};
}
};
constexpr enumerate_producers_fn enumerate_producers{};
}//builder
}//nbdl_def
#endif
|
/*
给定一个由 n行数字组成的数字三角形如下图所示。试设计一个算法,计算出从三角形
的顶至底的一条路径(每一步可沿左斜线向下或右斜线向下),使该路径经过的数字总和最大。
输入格式:
输入有n+1行:
第 1 行是数字三角形的行数 n,1<=n<=100。
接下来 n行是数字三角形各行中的数字。所有数字在0..99 之间。
输出格式:
输出最大路径的值。
输入样例:
在这里给出一组输入。例如:
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
输出样例:
在这里给出相应的输出。例如:
30
*/
#include <iostream>
#include <algorithm>
using namespace std;
int n;
int dp[50][50]; //记录状态的数组
int num[50][50];
void fun() {
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
dp[i][j] = num[i][j] + max(dp[i + 1][j], dp[i + 1][j + 1]);
} //状态转移方程
}
cout << dp[0][0]; //一直递推到顶端,dp[0][0]就是答案
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
cin >> num[i][j];
}
}
fun();
return 0;
}
|
// Copyright 2020 JD.com, Inc. Galileo 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.
// ==============================================================================
#pragma once
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include "common/types.h"
namespace galileo {
namespace discovery {
struct ShardPath {
uint32_t shard_index;
std::string shard_address; // ip:port
// shard_index#shard_address
bool Serialize(std::string *) const;
bool Deserialize(const std::string &);
bool operator==(const ShardPath &other) const;
private:
bool _Check() const;
};
struct ShardPathHash {
size_t operator()(const ShardPath &sp) const {
std::string sp_str;
sp.Serialize(&sp_str);
return std::hash<std::string>()(sp_str);
}
};
using ShardMeta = galileo::common::ShardMeta;
using ShardCallbacks = galileo::common::ShardCallbacks;
namespace shard_meta {
bool Serialize(const ShardMeta &, std::string *);
bool Deserialize(const std::string &, ShardMeta *);
bool Check(const ShardMeta &);
} // namespace shard_meta
struct ShardCache {
std::unordered_set<std::string> addresses;
std::unordered_set<const ShardCallbacks *> callbacks;
std::shared_ptr<ShardMeta> meta;
};
struct ShardCacheMap {
std::unordered_map<uint32_t, ShardCache> cache;
bool IsShardAvailable();
bool IsShardAvailable(uint32_t);
};
using ShardMap = std::unordered_map<ShardPath, ShardMeta, ShardPathHash>;
} // namespace discovery
} // namespace galileo
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2018 Ryo Suzuki
// Copyright (c) 2016-2018 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/Monitor.hpp>
# if defined(SIV3D_TARGET_WINDOWS)
# include <Siv3D/Windows.hpp>
# include "../Siv3DEngine.hpp"
# include "../Window/IWindow.hpp"
namespace s3d
{
namespace detail
{
// チェック用デバイス名とモニタハンドル
using MonitorCheck = std::pair<const String, HMONITOR>;
static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM userData)
{
MONITORINFOEX monitorInfo;
monitorInfo.cbSize = sizeof(monitorInfo);
::GetMonitorInfoW(hMonitor, &monitorInfo);
Monitor* monitor = (Monitor*)userData;
if (monitor->displayDeviceName.toWstr() == monitorInfo.szDevice)
{
monitor->displayRect.x = monitorInfo.rcMonitor.left;
monitor->displayRect.y = monitorInfo.rcMonitor.top;
monitor->displayRect.w = monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left;
monitor->displayRect.h = monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top;
monitor->workArea.x = monitorInfo.rcWork.left;
monitor->workArea.y = monitorInfo.rcWork.top;
monitor->workArea.w = monitorInfo.rcWork.right - monitorInfo.rcWork.left;
monitor->workArea.h = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top;
return false;
}
return true;
}
static BOOL CALLBACK MonitorCheckProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM userData)
{
MONITORINFOEX monitorInfo;
monitorInfo.cbSize = sizeof(monitorInfo);
::GetMonitorInfoW(hMonitor, &monitorInfo);
MonitorCheck* monitor = (MonitorCheck*)userData;
if (monitor->first.toWstr() == monitorInfo.szDevice)
{
monitor->second = hMonitor;
return false;
}
return true;
}
}
namespace System
{
Array<Monitor> EnumerateActiveMonitors()
{
Array<Monitor> monitors;
DISPLAY_DEVICE displayDevice;
displayDevice.cb = sizeof(displayDevice);
// デスクトップとして割り当てられている仮想ディスプレイを検索
for (int32 deviceIndex = 0; ::EnumDisplayDevicesW(0, deviceIndex, &displayDevice, 0); ++deviceIndex)
{
if (displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP)
{
DISPLAY_DEVICE monitor;
ZeroMemory(&monitor, sizeof(monitor));
monitor.cb = sizeof(monitor);
// デスクトップとして使われているモニターの一覧を取得
for (int32 monitorIndex = 0; ::EnumDisplayDevicesW(displayDevice.DeviceName, monitorIndex, &monitor, 0); ++monitorIndex)
{
if ((monitor.StateFlags & DISPLAY_DEVICE_ACTIVE) &&
!(monitor.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER))
{
Monitor monitorInfo;
monitorInfo.displayDeviceName = Unicode::FromWString(displayDevice.DeviceName);
// モニターの配置とサイズを取得
::EnumDisplayMonitors(nullptr, nullptr, detail::MonitorEnumProc, (LPARAM)&monitorInfo);
// その他の情報を取得
monitorInfo.id = Unicode::FromWString(monitor.DeviceID);
monitorInfo.name = Unicode::FromWString(monitor.DeviceString);
monitorInfo.isPrimary = !!(displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE);
monitors.push_back(monitorInfo);
}
ZeroMemory(&monitor, sizeof(monitor));
monitor.cb = sizeof(monitor);
}
}
ZeroMemory(&displayDevice, sizeof(displayDevice));
displayDevice.cb = sizeof(displayDevice);
}
return monitors;
}
size_t GetCurrentMonitorIndex()
{
const HMONITOR currentMonitor = ::MonitorFromWindow(Siv3DEngine::GetWindow()->getHandle(), MONITOR_DEFAULTTOPRIMARY);
size_t index = 0;
DISPLAY_DEVICE displayDevice;
displayDevice.cb = sizeof(displayDevice);
// デスクトップとして割り当てられている仮想デスクトップを検索
for (int32 deviceIndex = 0; ::EnumDisplayDevicesW(0, deviceIndex, &displayDevice, 0); ++deviceIndex)
{
if (displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP)
{
DISPLAY_DEVICE monitor;
ZeroMemory(&monitor, sizeof(monitor));
monitor.cb = sizeof(monitor);
// デスクトップとして使われているモニターの一覧を取得
for (int32 monitorIndex = 0; ::EnumDisplayDevicesW(displayDevice.DeviceName, monitorIndex, &monitor, 0); ++monitorIndex)
{
if ((monitor.StateFlags & DISPLAY_DEVICE_ACTIVE) &&
!(monitor.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER))
{
detail::MonitorCheck desc = { Unicode::FromWString(displayDevice.DeviceName), nullptr };
// モニターのハンドルを取得
::EnumDisplayMonitors(nullptr, nullptr, detail::MonitorCheckProc, (LPARAM)&desc);
if (desc.second == currentMonitor)
{
return index;
}
++index;
}
ZeroMemory(&monitor, sizeof(monitor));
monitor.cb = sizeof(monitor);
}
}
ZeroMemory(&displayDevice, sizeof(displayDevice));
displayDevice.cb = sizeof(displayDevice);
}
return 0;
}
}
}
# elif defined(SIV3D_TARGET_MACOS)
# include "../../ThirdParty/GLFW/include/GLFW/glfw3.h"
# include <Siv3D/Window.hpp>
namespace s3d
{
namespace System
{
Array<Monitor> EnumerateActiveMonitors()
{
Array<Monitor> results;
int32 numMonitors;
GLFWmonitor** monitors = ::glfwGetMonitors(&numMonitors);
for (int32 i = 0; i < numMonitors; ++i)
{
GLFWmonitor* monitor = monitors[i];
Monitor result;
result.name = Unicode::Widen(::glfwGetMonitorName(monitor));
uint32 displayID, unitNumber;
int32 xPos, yPos, width, height;
int32 wx, wy, ww, wh;
glfwGetMonitorInfo_Siv3D(monitor, &displayID, &unitNumber,
&xPos, &yPos, &width, &height,
&wx, &wy, &ww, &wh);
result.id = Format(displayID);
result.displayDeviceName = Format(unitNumber);
result.displayRect.x = xPos;
result.displayRect.y = yPos;
result.displayRect.w = width;
result.displayRect.h = height;
result.workArea.x = wx;
result.workArea.y = wy;
result.workArea.w = ww;
result.workArea.h = wh;
result.isPrimary = (i == 0);
results.push_back(result);
}
return results;
}
size_t GetCurrentMonitorIndex()
{
const auto& state = Window::GetState();
const Point pos = state.pos;
const Size size = state.windowSize;
const auto monitors = EnumerateActiveMonitors();
int32 bestoverlap = 0;
size_t bestIndex = 0;
for (size_t i = 0; i < monitors.size(); ++i)
{
const auto& monitor = monitors[i];
const Point mPos = monitor.displayRect.pos;
const Size mSize = monitor.displayRect.size;
const int32 overlap =
std::max(0, std::min(pos.x + size.x, mPos.x + mSize.x) - std::max(pos.x, mPos.x)) *
std::max(0, std::min(pos.y + size.y, mPos.y + mSize.y) - std::max(pos.y, mPos.y));
if (bestoverlap < overlap)
{
bestoverlap = overlap;
bestIndex = i;
}
}
return bestIndex;
}
}
}
# elif defined(SIV3D_TARGET_LINUX)
# include "../../ThirdParty/GLFW/include/GLFW/glfw3.h"
# include <Siv3D/Window.hpp>
namespace s3d
{
namespace System
{
Array<Monitor> EnumerateActiveMonitors()
{
Array<Monitor> results;
int32 numMonitors;
GLFWmonitor** monitors = ::glfwGetMonitors(&numMonitors);
for (int32 i = 0; i < numMonitors; ++i)
{
GLFWmonitor* monitor = monitors[i];
Monitor result;
result.name = Unicode::Widen(::glfwGetMonitorName(monitor));
uint32 displayID;
int32 xPos, yPos, width, height;
int32 wx, wy, ww, wh;
char* name = nullptr;
glfwGetMonitorInfo_Siv3D(monitor, &displayID, &name,
&xPos, &yPos, &width, &height,
&wx, &wy, &ww, &wh);
result.id = Format(displayID);
result.displayDeviceName = Unicode::Widen(name);
result.displayRect.x = xPos;
result.displayRect.y = yPos;
result.displayRect.w = width;
result.displayRect.h = height;
result.workArea.x = wx;
result.workArea.y = wy;
result.workArea.w = ww;
result.workArea.h = wh;
result.isPrimary = (i == 0);
results.push_back(result);
::free(name); // free monitor name buffer.
}
return results;
}
size_t GetCurrentMonitorIndex()
{
const auto& state = Window::GetState();
const Point pos = state.pos;
const Size size = state.windowSize;
const auto monitors = EnumerateActiveMonitors();
int32 bestoverlap = 0;
size_t bestIndex = 0;
for (size_t i = 0; i < monitors.size(); ++i)
{
const auto& monitor = monitors[i];
const Point mPos = monitor.displayRect.pos;
const Size mSize = monitor.displayRect.size;
const int32 overlap =
std::max(0, std::min(pos.x + size.x, mPos.x + mSize.x) - std::max(pos.x, mPos.x)) *
std::max(0, std::min(pos.y + size.y, mPos.y + mSize.y) - std::max(pos.y, mPos.y));
if (bestoverlap < overlap)
{
bestoverlap = overlap;
bestIndex = i;
}
}
return bestIndex;
}
}
}
# endif
namespace s3d
{
void Formatter(FormatData& formatData, const Monitor& value)
{
String output;
output += U"Name: " + value.name + U"\n";
output += U"ID: " + value.id + U"\n";
output += U"DisplayDeviceName: " + value.displayDeviceName + U"\n";
output += U"DisplayRect: " + Format(value.displayRect) + U"\n";
output += U"WorkArea: " + Format(value.workArea) + U"\n";
output += U"Primary: " + Format(value.isPrimary);
formatData.string.append(output);
}
}
|
/*
* xDMS v1.3 - Portable DMS archive unpacker - Public Domain
* Written by Andre Rodrigues de la Rocha <adlroc@usa.net>
*
* CRC16 & CheckSum16 calculation functions
* CreateCRC was written (aparently) by Bjorn Stenberg
*
*/
#include "cdata.h"
#include "crc_csum.h"
USHORT dms_Calc_CheckSum(UCHAR *mem, ULONG size){
USHORT u=0;
while(size--) u += *mem++;
return (USHORT)(u & 0xffff);
}
USHORT dms_CreateCRC(UCHAR* mem, ULONG size ){
static const USHORT CRCTab[256]={
0x0000,0xC0C1,0xC181,0x0140,0xC301,0x03C0,0x0280,0xC241,
0xC601,0x06C0,0x0780,0xC741,0x0500,0xC5C1,0xC481,0x0440,
0xCC01,0x0CC0,0x0D80,0xCD41,0x0F00,0xCFC1,0xCE81,0x0E40,
0x0A00,0xCAC1,0xCB81,0x0B40,0xC901,0x09C0,0x0880,0xC841,
0xD801,0x18C0,0x1980,0xD941,0x1B00,0xDBC1,0xDA81,0x1A40,
0x1E00,0xDEC1,0xDF81,0x1F40,0xDD01,0x1DC0,0x1C80,0xDC41,
0x1400,0xD4C1,0xD581,0x1540,0xD701,0x17C0,0x1680,0xD641,
0xD201,0x12C0,0x1380,0xD341,0x1100,0xD1C1,0xD081,0x1040,
0xF001,0x30C0,0x3180,0xF141,0x3300,0xF3C1,0xF281,0x3240,
0x3600,0xF6C1,0xF781,0x3740,0xF501,0x35C0,0x3480,0xF441,
0x3C00,0xFCC1,0xFD81,0x3D40,0xFF01,0x3FC0,0x3E80,0xFE41,
0xFA01,0x3AC0,0x3B80,0xFB41,0x3900,0xF9C1,0xF881,0x3840,
0x2800,0xE8C1,0xE981,0x2940,0xEB01,0x2BC0,0x2A80,0xEA41,
0xEE01,0x2EC0,0x2F80,0xEF41,0x2D00,0xEDC1,0xEC81,0x2C40,
0xE401,0x24C0,0x2580,0xE541,0x2700,0xE7C1,0xE681,0x2640,
0x2200,0xE2C1,0xE381,0x2340,0xE101,0x21C0,0x2080,0xE041,
0xA001,0x60C0,0x6180,0xA141,0x6300,0xA3C1,0xA281,0x6240,
0x6600,0xA6C1,0xA781,0x6740,0xA501,0x65C0,0x6480,0xA441,
0x6C00,0xACC1,0xAD81,0x6D40,0xAF01,0x6FC0,0x6E80,0xAE41,
0xAA01,0x6AC0,0x6B80,0xAB41,0x6900,0xA9C1,0xA881,0x6840,
0x7800,0xB8C1,0xB981,0x7940,0xBB01,0x7BC0,0x7A80,0xBA41,
0xBE01,0x7EC0,0x7F80,0xBF41,0x7D00,0xBDC1,0xBC81,0x7C40,
0xB401,0x74C0,0x7580,0xB541,0x7700,0xB7C1,0xB681,0x7640,
0x7200,0xB2C1,0xB381,0x7340,0xB101,0x71C0,0x7080,0xB041,
0x5000,0x90C1,0x9181,0x5140,0x9301,0x53C0,0x5280,0x9241,
0x9601,0x56C0,0x5780,0x9741,0x5500,0x95C1,0x9481,0x5440,
0x9C01,0x5CC0,0x5D80,0x9D41,0x5F00,0x9FC1,0x9E81,0x5E40,
0x5A00,0x9AC1,0x9B81,0x5B40,0x9901,0x59C0,0x5880,0x9841,
0x8801,0x48C0,0x4980,0x8941,0x4B00,0x8BC1,0x8A81,0x4A40,
0x4E00,0x8EC1,0x8F81,0x4F40,0x8D01,0x4DC0,0x4C80,0x8C41,
0x4400,0x84C1,0x8581,0x4540,0x8701,0x47C0,0x4680,0x8641,
0x8201,0x42C0,0x4380,0x8341,0x4100,0x81C1,0x8081,0x4040
};
USHORT CRC = 0;
while(size--)
CRC = (USHORT) (CRCTab[((CRC ^ *mem++) & 255)] ^ ((CRC >> 8) & 255));
return CRC;
}
|
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "generators/include/python_CEGUI.h"
#include "DefaultLogger.pypp.hpp"
namespace bp = boost::python;
struct DefaultLogger_wrapper : CEGUI::DefaultLogger, bp::wrapper< CEGUI::DefaultLogger > {
DefaultLogger_wrapper( )
: CEGUI::DefaultLogger( )
, bp::wrapper< CEGUI::DefaultLogger >(){
// null constructor
}
virtual void logEvent( ::CEGUI::String const & message, ::CEGUI::LoggingLevel level=::CEGUI::Standard ) {
if( bp::override func_logEvent = this->get_override( "logEvent" ) )
func_logEvent( boost::ref(message), level );
else{
this->CEGUI::DefaultLogger::logEvent( boost::ref(message), level );
}
}
void default_logEvent( ::CEGUI::String const & message, ::CEGUI::LoggingLevel level=::CEGUI::Standard ) {
CEGUI::DefaultLogger::logEvent( boost::ref(message), level );
}
virtual void setLogFilename( ::CEGUI::String const & filename, bool append=false ) {
if( bp::override func_setLogFilename = this->get_override( "setLogFilename" ) )
func_setLogFilename( boost::ref(filename), append );
else{
this->CEGUI::DefaultLogger::setLogFilename( boost::ref(filename), append );
}
}
void default_setLogFilename( ::CEGUI::String const & filename, bool append=false ) {
CEGUI::DefaultLogger::setLogFilename( boost::ref(filename), append );
}
};
void register_DefaultLogger_class(){
{ //::CEGUI::DefaultLogger
typedef bp::class_< DefaultLogger_wrapper, bp::bases< CEGUI::Logger >, boost::noncopyable > DefaultLogger_exposer_t;
DefaultLogger_exposer_t DefaultLogger_exposer = DefaultLogger_exposer_t( "DefaultLogger", "*!\n\
\n\
Default implementation for the Logger class.\n\
If you want to redirect CEGUI logs to some place other than a text file,\n\
implement your own Logger implementation and create a object of the\n\
Logger type before creating the CEGUI.System singleton.\n\
*\n", bp::no_init );
bp::scope DefaultLogger_scope( DefaultLogger_exposer );
DefaultLogger_exposer.def( bp::init< >() );
{ //::CEGUI::DefaultLogger::logEvent
typedef void ( ::CEGUI::DefaultLogger::*logEvent_function_type )( ::CEGUI::String const &,::CEGUI::LoggingLevel ) ;
typedef void ( DefaultLogger_wrapper::*default_logEvent_function_type )( ::CEGUI::String const &,::CEGUI::LoggingLevel ) ;
DefaultLogger_exposer.def(
"logEvent"
, logEvent_function_type(&::CEGUI::DefaultLogger::logEvent)
, default_logEvent_function_type(&DefaultLogger_wrapper::default_logEvent)
, ( bp::arg("message"), bp::arg("level")=::CEGUI::Standard ) );
}
{ //::CEGUI::DefaultLogger::setLogFilename
typedef void ( ::CEGUI::DefaultLogger::*setLogFilename_function_type )( ::CEGUI::String const &,bool ) ;
typedef void ( DefaultLogger_wrapper::*default_setLogFilename_function_type )( ::CEGUI::String const &,bool ) ;
DefaultLogger_exposer.def(
"setLogFilename"
, setLogFilename_function_type(&::CEGUI::DefaultLogger::setLogFilename)
, default_setLogFilename_function_type(&DefaultLogger_wrapper::default_setLogFilename)
, ( bp::arg("filename"), bp::arg("append")=(bool)(false) ) );
}
}
}
|
/* NO WARRANTY
*
* BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO
* WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
* LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS
* AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO
* THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD
* THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
* NECESSARY SERVICING, REPAIR OR CORRECTION.
*
* IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
* WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY
* AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES,
* INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
* DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
* (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
* RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES
* OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
* PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGES.
*/
#include "stdafx.h"
#include "Application\DigitalSimulatorApp.h"
#include "Application\i18n\TranslateDocManager.h"
#include "Application\Dialogs\CommonDialogs\TranslateFileDialog.h"
IMPLEMENT_DYNAMIC(CTranslateDocManager,CDocManager)
//----------------------------------------------------------------------------
static void AppendFilterSuffix(CString& filter, OPENFILENAME& ofn,CDocTemplate* pTemplate, CString* pstrDefaultExt){
//----------------------------------------------------------------------------
PROC_TRACE;
ASSERT_VALID(pTemplate);
ASSERT_KINDOF(CDocTemplate, pTemplate);
CString strFilterExt, strFilterName;
if (pTemplate->GetDocString(strFilterExt, CDocTemplate::filterExt) &&
!strFilterExt.IsEmpty() &&
pTemplate->GetDocString(strFilterName, CDocTemplate::filterName) &&
!strFilterName.IsEmpty())
{
// a file based document template - add to filter list
ASSERT(strFilterExt[0] == '.');
if (pstrDefaultExt != NULL){
// set the default extension
*pstrDefaultExt = ((LPCTSTR)strFilterExt) + 1; // skip the '.'
ofn.lpstrDefExt = (LPTSTR)(LPCTSTR)(*pstrDefaultExt);
ofn.nFilterIndex = ofn.nMaxCustFilter + 1; // 1 based number
}
// add to filter
filter += strFilterName;
ASSERT(!filter.IsEmpty()); // must have a file type name
filter += (TCHAR)'\0'; // next CString please
filter += (TCHAR)'*';
filter += strFilterExt;
filter += (TCHAR)'\0'; // next CString please
ofn.nMaxCustFilter++;
}
}
//----------------------------------------------------------------------------
CTranslateDocManager::CTranslateDocManager(){
//----------------------------------------------------------------------------
PROC_TRACE;
}
//----------------------------------------------------------------------------
CTranslateDocManager::~CTranslateDocManager(){
//----------------------------------------------------------------------------
PROC_TRACE;
}
//----------------------------------------------------------------------------
BOOL CTranslateDocManager::DoPromptFileName(CString& fileName, UINT nIDSTitle, DWORD lFlags, BOOL bOpenFileDialog, CDocTemplate* pTemplate){
//----------------------------------------------------------------------------
PROC_TRACE;
CTranslateFileDialog dlgFile(bOpenFileDialog);
CString title;
VERIFY(title.LoadString(nIDSTitle));
dlgFile.m_ofn.Flags |= lFlags;
CString strFilter;
CString strDefault;
if (pTemplate != NULL){
ASSERT_VALID(pTemplate);
AppendFilterSuffix(strFilter, dlgFile.m_ofn, pTemplate, &strDefault);
}
else{
// do for all doc template
POSITION pos = m_templateList.GetHeadPosition();
BOOL bFirst = TRUE;
while (pos != NULL){
CDocTemplate* pTemplate = (CDocTemplate*)m_templateList.GetNext(pos);
AppendFilterSuffix(strFilter, dlgFile.m_ofn, pTemplate,bFirst ? &strDefault : NULL);
bFirst = FALSE;
}
}
/*
// append the "*.*" all files filter
CString allFilter;
VERIFY(allFilter.LoadString(AFX_IDS_ALLFILTER));
strFilter += allFilter;
strFilter += (TCHAR)'\0'; // next CString please
strFilter += _T("*.*");
strFilter += (TCHAR)'\0'; // last CString
*/
dlgFile.m_ofn.nMaxCustFilter++;
dlgFile.m_ofn.lpstrFilter = strFilter;
dlgFile.m_ofn.lpstrTitle = title;
dlgFile.m_ofn.lpstrFile = fileName.GetBuffer(_MAX_PATH);
BOOL bResult = dlgFile.DoModal() == IDOK ? TRUE : FALSE;
fileName.ReleaseBuffer();
return bResult;
}
//----------------------------------------------------------------------------
void CTranslateDocManager::OnFileNew(){
//----------------------------------------------------------------------------
PROC_TRACE;
if (m_templateList.IsEmpty()) {
TRACE("Error: no document templates registered with CWinApp.\n");
AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);
return;
}
CDocTemplate* pTemplate = (CDocTemplate*)m_templateList.GetHead();
/*
Only create a Simulator File
It is not possible to create a C-Script File in the
Simulator.....do not open a selection-Dialog for File types
if (m_templateList.GetCount() > 1)
{
// more than one document template to choose from
// bring up dialog prompting user
CNewTypeDlg dlg(&m_templateList);
int nID = dlg.DoModal();
if (nID == IDOK)
pTemplate = dlg.m_pSelectedTemplate;
else
return; // none - cancel operation
}
*/
ASSERT(pTemplate != NULL);
ASSERT_KINDOF(CDocTemplate, pTemplate);
pTemplate->OpenDocumentFile(NULL);
// if returns NULL, the user has already been alerted
}
|
#pragma once
#include<SFML/Graphics.hpp>
using namespace sf;
/**
* \brief Klasa reprezentująca przeciwników.
*/
class Enemy
{
private:
Texture texture;
Sprite sprite;
float life = 1.0f;
bool dead = false;
public:
Enemy(float x, float y);
Sprite getSprite();
float right();
float left();
float bottom();
float top();
float firstPositionX;
void isKilled();
bool getDead();
void decreaseLife();
void enemyMovingLeft();
void enemyMovingRight();
void enemyMoving();
float getX();
char direction = 'L';
Clock clock;
Time realtime;
Time retreat;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.