text
stringlengths 8
6.88M
|
|---|
#include "gb_int.h"
#include "gb_cpu.h"
#include "gb_memory.h"
void Interrupt::vblank(void) {
mem->write_short_to_stack(cpu->registers.sp, cpu->registers.pc);
cpu->registers.sp -= 2;
// jump to vblank irq
cpu->registers.pc = 0x0040;
}
void Interrupt::lcdc_stat(void) {
mem->write_short_to_stack(cpu->registers.sp, cpu->registers.pc);
cpu->registers.sp -= 2;
// jump to lcdc status irq
cpu->registers.pc = 0x0048;
}
void Interrupt::timer_of(void) {
mem->write_short_to_stack(cpu->registers.sp, cpu->registers.pc);
cpu->registers.sp -= 2;
// jump to timer overflow irq
cpu->registers.pc = 0x0050;
}
void Interrupt::sio_tx(void) {
std::cout << "unimplemented sio transfer int" << std::endl;
cpu->stop = true;
// mem->write_short_to_stack(cpu->registers.sp, cpu->registers.pc);
// cpu->registers.sp -= 2;
//
// //jump to sio tx/rx irq
// cpu->registers.pc = 0x0058;
}
void Interrupt::hi_lo(void) {
std::cout << "unimplemented hilo int" << std::endl;
cpu->stop = true;
// mem->write_short_to_stack(cpu->registers.sp, cpu->registers.pc);
// cpu->registers.sp -= 2;
//
// //jump to hilo p10-p13
// cpu->registers.pc = 0x0060;
}
void Interrupt::step(void) {
// resume exec if interrupt occurs, even if not enabled or IME is false
if (flags & (VBLANK | LCDC_STAT | TIMER_OF | SIO_TX | HI_LO)) {
cpu->halted = false;
}
if (ime_flag) {
// if any enabled interrupts are set
if (flags & en)
ime_flag = false;
// can only process one interrupt at a time
if (flags & en & VBLANK) { // Priority 1
flags &= ~VBLANK;
vblank();
} else if (flags & en & LCDC_STAT) {
flags &= ~LCDC_STAT;
lcdc_stat();
} else if (flags & en & TIMER_OF) {
flags &= ~TIMER_OF;
timer_of();
} else if (flags & en & SIO_TX) {
flags &= ~SIO_TX;
sio_tx();
} else if (flags & en & HI_LO) {
flags &= ~HI_LO;
hi_lo();
}
}
}
void Interrupt::init(GB_Sys *gb_sys) {
mem = gb_sys->mem;
cpu = gb_sys->cpu;
}
|
#include "odb/mess/request.hh"
#include <cstdint>
#include <string>
#include <type_traits>
#include <vector>
#include "odb/mess/db-client.hh"
#include "odb/mess/request-handler.hh"
#include "odb/server/fwd.hh"
// @xtra I had issues of ambigious call using enable_uf
#define RAW_SERIAL(Ty) \
template <> void sb_serialize(SerialOutBuff &os, const Ty &x) { \
sb_serial_raw<Ty>(os, x); \
} \
\
template <> void sb_unserialize(SerialInBuff &is, Ty &x) { \
x = sb_unserial_raw<Ty>(is); \
}
#if 0
template <class T>
std::enable_if_t<std::is_integral_v<T>> sb_serialize(SerialOutBuff &os,
const T &x) {
sb_serial_raw<T>(os, x);
}
template <class T>
std::enable_if_t<std::is_integral_v<T>> sb_unserialize(SerialInBuff &is, T &x) {
x = sb_unserial_raw<T>(is);
}
#endif
namespace odb {
template <> void prepare_request(RequestHandler &h, ReqConnect &r) {
h.object_out(r.out_infos);
h.object_out(r.out_udp);
}
template <> void prepare_request(RequestHandler &, ReqStop &) {}
template <> void prepare_request(RequestHandler &h, ReqCheckStopped &r) {
h.object_out(r.out_udp);
}
template <> void prepare_request(RequestHandler &h, ReqGetRegs &r) {
h.object_in(r.nregs);
h.object_in(r.reg_size);
h.buffer_in(r.ids, r.nregs);
h.buffer_2d_out(r.out_bufs, r.nregs, r.reg_size);
}
template <> void prepare_request(RequestHandler &h, ReqGetRegsVar &r) {
h.object_in(r.nregs);
h.buffer_in(r.in_ids, r.nregs);
h.buffer_in(r.in_regs_size, r.nregs);
h.buffer_2dvar_out(r.out_bufs, r.nregs, r.in_regs_size);
}
template <> void prepare_request(RequestHandler &h, ReqSetRegs &r) {
h.object_in(r.nregs);
h.object_in(r.reg_size);
h.buffer_in(r.in_ids, r.nregs);
h.buffer_2d_in(r.in_bufs, r.nregs, r.reg_size);
}
template <> void prepare_request(RequestHandler &h, ReqSetRegsVar &r) {
h.object_in(r.nregs);
h.buffer_in(r.in_ids, r.nregs);
h.buffer_in(r.in_regs_size, r.nregs);
h.buffer_2dvar_in(r.in_bufs, r.nregs, r.in_regs_size);
}
template <> void prepare_request(RequestHandler &h, ReqGetRegsInfos &r) {
h.object_in(r.nregs);
h.buffer_in(r.ids, r.nregs);
h.buffer_out(r.out_infos, r.nregs);
}
template <> void prepare_request(RequestHandler &h, ReqFindRegsIds &r) {
h.object_in(r.nregs);
h.buffer_2d_in_cstr(r.in_bufs, r.nregs);
h.buffer_out(r.out_ids, r.nregs);
}
template <> void prepare_request(RequestHandler &h, ReqReadMem &r) {
h.object_in(r.nbufs);
h.object_in(r.buf_size);
h.buffer_in(r.in_addrs, r.nbufs);
h.buffer_2d_out(r.out_bufs, r.nbufs, r.buf_size);
}
template <> void prepare_request(RequestHandler &h, ReqReadMemVar &r) {
h.object_in(r.nbufs);
h.buffer_in(r.in_addrs, r.nbufs);
h.buffer_in(r.in_bufs_size, r.nbufs);
h.buffer_2dvar_out(r.out_bufs, r.nbufs, r.in_bufs_size);
}
template <> void prepare_request(RequestHandler &h, ReqWriteMem &r) {
h.object_in(r.nbufs);
h.object_in(r.buf_size);
h.buffer_in(r.in_addrs, r.nbufs);
h.buffer_2d_in(r.in_bufs, r.nbufs, r.buf_size);
}
template <> void prepare_request(RequestHandler &h, ReqWriteMemVar &r) {
h.object_in(r.nbufs);
h.buffer_in(r.in_addrs, r.nbufs);
h.buffer_in(r.in_bufs_size, r.nbufs);
h.buffer_2dvar_in(r.in_bufs, r.nbufs, r.in_bufs_size);
}
template <> void prepare_request(RequestHandler &h, ReqGetSymsByIds &r) {
h.object_in(r.nsyms);
h.buffer_in(r.in_ids, r.nsyms);
h.buffer_out(r.out_infos, r.nsyms);
}
template <> void prepare_request(RequestHandler &h, ReqGetSymsByAddr &r) {
h.object_in(r.addr);
h.object_in(r.size);
h.object_out(r.out_infos);
}
template <> void prepare_request(RequestHandler &h, ReqGetSymsByNames &r) {
h.object_in(r.nsyms);
h.buffer_2d_in_cstr(r.in_names, r.nsyms);
h.buffer_out(r.out_infos, r.nsyms);
}
template <> void prepare_request(RequestHandler &h, ReqGetCodeText &r) {
h.object_in(r.addr);
h.object_in(r.nins);
h.object_out(r.out_text);
h.object_out(r.out_sizes);
}
template <> void prepare_request(RequestHandler &h, ReqAddBkps &r) {
h.object_in(r.size);
h.buffer_in(r.in_addrs, r.size);
}
template <> void prepare_request(RequestHandler &h, ReqDelBkps &r) {
h.object_in(r.size);
h.buffer_in(r.in_addrs, r.size);
}
template <> void prepare_request(RequestHandler &h, ReqResume &r) {
h.object_in(r.type);
}
template <> void prepare_request(RequestHandler &h, ReqErr &r) {
h.object_out(r.msg);
}
RAW_SERIAL(char)
RAW_SERIAL(std::uint8_t)
RAW_SERIAL(std::uint16_t)
RAW_SERIAL(std::uint32_t)
RAW_SERIAL(std::uint64_t)
RAW_SERIAL(std::int8_t)
RAW_SERIAL(std::int16_t)
RAW_SERIAL(std::int32_t)
RAW_SERIAL(std::int64_t)
template <> void sb_serialize(SerialOutBuff &os, const ReqType &ty) {
sb_serial_raw(os, static_cast<std::int8_t>(ty));
}
template <> void sb_unserialize(SerialInBuff &is, ReqType &ty) {
ty = static_cast<ReqType>(sb_unserial_raw<std::int8_t>(is));
}
template <> void sb_serialize(SerialOutBuff &os, const std::string &s) {
sb_serial_raw<std::uint64_t>(os, s.size());
os.write(s.c_str(), s.size());
}
template <> void sb_unserialize(SerialInBuff &is, std::string &s) {
auto size = sb_unserial_raw<std::uint64_t>(is);
s.resize(size);
is.read(&s[0], size);
}
template <class T>
void sb_serialize(SerialOutBuff &os, const std::vector<T> &v) {
sb_serial_raw<std::uint64_t>(os, v.size());
for (std::size_t i = 0; i < v.size(); ++i)
os << v[i];
}
// @extra doesn't work if T have no default constructor
template <class T> void sb_unserialize(SerialInBuff &is, std::vector<T> &v) {
auto size = sb_unserial_raw<std::uint64_t>(is);
v.resize(size);
for (std::size_t i = 0; i < v.size(); ++i)
is >> v[i];
}
template <> void sb_serialize(SerialOutBuff &os, const VMInfos &infos) {
os << infos.name << infos.regs_count << infos.regs_general
<< infos.regs_program_counter << infos.regs_stack_pointer
<< infos.regs_base_pointer << infos.regs_flags << infos.memory_size
<< infos.symbols_count << infos.pointer_size << infos.integer_size;
sb_serial_raw<std::uint8_t>(os, infos.use_opcode);
}
template <> void sb_unserialize(SerialInBuff &is, VMInfos &infos) {
is >> infos.name >> infos.regs_count >> infos.regs_general >>
infos.regs_program_counter >> infos.regs_stack_pointer >>
infos.regs_base_pointer >> infos.regs_flags >> infos.memory_size >>
infos.symbols_count >> infos.pointer_size >> infos.integer_size;
infos.use_opcode = sb_unserial_raw<std::uint8_t>(is);
}
template <> void sb_serialize(SerialOutBuff &os, const StoppedState &e) {
sb_serial_raw(os, static_cast<std::int8_t>(e));
}
template <> void sb_unserialize(SerialInBuff &is, StoppedState &e) {
e = static_cast<StoppedState>(sb_unserial_raw<std::int8_t>(is));
}
template <> void sb_serialize(SerialOutBuff &os, const CallInfos &ci) {
os << ci.caller_start_addr << ci.call_addr;
}
template <> void sb_unserialize(SerialInBuff &is, CallInfos &ci) {
is >> ci.caller_start_addr >> ci.call_addr;
}
template <> void sb_serialize(SerialOutBuff &os, const DBClientUpdate &udp) {
os << udp.vm_state;
sb_serial_raw<std::uint8_t>(os, udp.stopped);
os << udp.addr;
os << udp.stack;
}
template <> void sb_unserialize(SerialInBuff &is, DBClientUpdate &udp) {
is >> udp.vm_state;
udp.stopped = sb_unserial_raw<std::uint8_t>(is);
is >> udp.addr;
is >> udp.stack;
}
template <> void sb_serialize(SerialOutBuff &os, const RegKind &e) {
sb_serial_raw(os, static_cast<std::int8_t>(e));
}
template <> void sb_unserialize(SerialInBuff &is, RegKind &e) {
e = static_cast<RegKind>(sb_unserial_raw<std::int8_t>(is));
}
template <> void sb_serialize(SerialOutBuff &os, const RegInfos ®) {
os << reg.idx << reg.name << reg.size << reg.kind;
}
template <> void sb_unserialize(SerialInBuff &is, RegInfos ®) {
is >> reg.idx >> reg.name >> reg.size >> reg.kind;
}
template <> void sb_serialize(SerialOutBuff &os, const SymbolInfos &sym) {
os << sym.idx << sym.name << sym.addr;
}
template <> void sb_unserialize(SerialInBuff &is, SymbolInfos &sym) {
is >> sym.idx >> sym.name >> sym.addr;
}
template <> void sb_serialize(SerialOutBuff &os, const ResumeType &e) {
sb_serial_raw(os, static_cast<std::int8_t>(e));
}
template <> void sb_unserialize(SerialInBuff &is, ResumeType &e) {
e = static_cast<ResumeType>(sb_unserial_raw<std::int8_t>(is));
}
} // namespace odb
|
// BHNavigator.cpp: implementation of the CBHNavigator class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "BrowserHooker.h"
#include "BHNavigator.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define ID_PROPERTIES 0x332
#define ID_CLASSVIEW 0x333
#define ID_NEWFOLDER 0x334
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CBHNavigator::CBHNavigator()
{
}
CBHNavigator::~CBHNavigator()
{
}
BEGIN_MESSAGE_MAP(CBHNavigator, CGuiControlBar)
ON_WM_CREATE()
ON_COMMAND(ID_PROPERTIES, Onproperties)
ON_COMMAND(ID_NEWFOLDER, OnNewFolder)
END_MESSAGE_MAP()
int CBHNavigator::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CGuiControlBar::OnCreate(lpCreateStruct) == -1)
return -1;
//creamos el tab
if (!m_TabControlPanel.Create(WS_VISIBLE|WS_CHILD,CRect(0,0,0,0),this,0x9999))
return -1;
const DWORD dwStyle = WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS ;
if (!m_TreeResourceView.Create(dwStyle, CRect(0,0,0,0), &m_TabControlPanel, 2))
return -1;
m_imgList.Create (IDB_DBPROJECTS, 16, 20, RGB (255, 0, 0));
CreatContExplorer();
if (!m_TreeControlPanel.Create(dwStyle, CRect(0,0,0,0), &m_ctControlPanel, 2))
return -1;
CreatContClassView();
if (!m_TreeClassView.Create(dwStyle, CRect(0,0,0,0), &m_ctClassView, 2))
return -1;
m_TreeControlPanel.SetImageList(&m_imgList,TVSIL_NORMAL);
m_TreeClassView.SetImageList(&m_imgList,TVSIL_NORMAL);
m_TabControlPanel.SetImageList(IDB_DBPROJECTS, 16,21, RGB (255, 0, 0));
m_TabControlPanel.Addtab(&m_ctControlPanel,"Solution Explorer",0);
m_TabControlPanel.Addtab(&m_ctClassView,"Class View",1);
m_TabControlPanel.Addtab(&m_TreeResourceView,"Resource View",2);
FillerControlPanel();
FillTreeClassView();
m_ctControlPanel.AddComponen(&m_TreeControlPanel);
m_ctClassView.AddComponen(&m_TreeClassView);
SetIcon(IDB_BITMAPHELP,16,4,RGB(255,0,0),1);
return 0;
}
void CBHNavigator::Onproperties()
{
AfxMessageBox("Properties");
}
void CBHNavigator::OnNewFolder()
{
AfxMessageBox("New Folder");
}
BOOL CBHNavigator::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT *pResult){
return FALSE;
}
int CBHNavigator::CreatContClassView()
{
if (!m_ctClassView.Create(WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),&m_TabControlPanel,124))
return -1;
m_ctClassView.AddComponen(&m_miClassView);
m_miClassView.AlingButtons(CGuiMiniTool::ALIGN_LEFT);
m_miClassView.SetImageList(IDB_DBPROJECTS, 16,24, RGB (255, 0, 0));
m_miClassView.AddButton(22,ID_CLASSVIEW,NULL,_T(""),"Class View Sort by Type");
m_miClassView.AddButton(23,ID_NEWFOLDER,NULL,_T(""),"New Folder");
m_miClassView.AutoSize(FALSE);
//m_miClassView.SetColor(GuiDrawLayer::GetRGBColorXP());
return 1;
}
int CBHNavigator::CreatContExplorer()
{
//CGuiContainer m_ctClassView;
//CGuiMiniTool m_miClassView;
if (!m_ctControlPanel.Create(WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),&m_TabControlPanel,124))
return -1;
m_ctControlPanel.AddComponen(&m_miControlPanel);
m_miControlPanel.AlingButtons(CGuiMiniTool::ALIGN_LEFT);
m_miControlPanel.SetImageList(IDB_DBPROJECTS, 16,22, RGB (255, 0, 0));
m_miControlPanel.AddButton(21,ID_PROPERTIES,NULL,_T(""),"properties");
m_miControlPanel.AutoSize(FALSE);
// m_miControlPanel.SetColor(GuiDrawLayer::GetRGBColorXP());
return 0;
}
void CBHNavigator::FillerControlPanel()
{
HTREEITEM hRoot = m_TreeControlPanel.InsertItem (_T("Solution \'GuiLib\'(2 projects)"), 0, 0);
HTREEITEM hProject = m_TreeControlPanel.InsertItem (_T("Gui_DevStudio"), 10, 10, hRoot);
m_TreeControlPanel.SetItemState (hProject, TVIS_BOLD, TVIS_BOLD);
HTREEITEM hSrc = m_TreeControlPanel.InsertItem (_T("Source Files"), 11, 12, hProject);
m_TreeControlPanel.InsertItem (_T("ChildFrm.cpp"), 13, 13, hSrc);
m_TreeControlPanel.InsertItem (_T("Gui_DevStudio.cpp"), 13, 13, hSrc);
m_TreeControlPanel.InsertItem (_T("Gui_DevStudio.rc"), 13, 13, hSrc);
m_TreeControlPanel.InsertItem (_T("Gui_DevStudioDoc.cpp"), 13, 13, hSrc);
m_TreeControlPanel.InsertItem (_T("Gui_DevStudioView.cpp"), 13, 13, hSrc);
m_TreeControlPanel.InsertItem (_T("GuiHelp.cpp"), 13, 13, hSrc);
m_TreeControlPanel.InsertItem (_T("MainFrm.cpp"), 13, 13, hSrc);
m_TreeControlPanel.InsertItem (_T("StdAfx.cpp"), 13, 13, hSrc);
HTREEITEM hInc = m_TreeControlPanel.InsertItem (_T("Header Files"), 11, 12, hProject);
m_TreeControlPanel.InsertItem (_T("ChildFrm.h"), 14, 14, hInc);
m_TreeControlPanel.InsertItem (_T("Gui_DevStudio.h"), 14, 14, hInc);
m_TreeControlPanel.InsertItem (_T("Gui_DevStudioDoc.h"), 14, 14, hInc);
m_TreeControlPanel.InsertItem (_T("Gui_DevStudioView.h"), 14, 14, hInc);
m_TreeControlPanel.InsertItem (_T("GuiHelp.h"), 14, 14, hInc);
m_TreeControlPanel.InsertItem (_T("MainFrm.h"), 14, 14, hInc);
m_TreeControlPanel.InsertItem (_T("StdAfx.h"), 14, 14, hInc);
HTREEITEM hRes = m_TreeControlPanel.InsertItem (_T("Resource Files"), 11, 12, hProject);
m_TreeControlPanel.InsertItem (_T("dbproject.bmp"), 14, 14, hRes);
m_TreeControlPanel.InsertItem (_T("Gui_DevStudio.ico"), 14, 14, hRes);
m_TreeControlPanel.InsertItem (_T("Gui_DevStudio.rc2"), 14, 14, hRes);
m_TreeControlPanel.InsertItem (_T("Toolbar.bmp"), 2, 2, hRes);
m_TreeControlPanel.Expand (hProject, TVE_EXPAND);
m_TreeControlPanel.Expand (hRoot, TVE_EXPAND);
m_TreeControlPanel.Expand (hSrc, TVE_EXPAND);
m_TreeControlPanel.Expand (hInc, TVE_EXPAND);
m_TreeControlPanel.Expand (hRes, TVE_EXPAND);
}
void CBHNavigator::FillTreeClassView()
{
HTREEITEM hRoot =m_TreeClassView.InsertItem (_T("Gui_DevStudio"), 0, 0);
HTREEITEM hGlobal = m_TreeClassView.InsertItem (_T("Global Functions and Variables"), 16, 16, hRoot);
m_TreeClassView.InsertItem (_T("indicators"), 18, 18, hGlobal);
m_TreeClassView.InsertItem (_T("theApp"), 18, 18, hGlobal);
m_TreeClassView.InsertItem (_T("THIS_FILE"), 18, 18, hGlobal);
m_TreeClassView.InsertItem (_T("THIS_FILE"), 18, 18, hGlobal);
m_TreeClassView.InsertItem (_T("THIS_FILE"), 18, 18, hGlobal);
m_TreeClassView.InsertItem (_T("THIS_FILE"), 18, 18, hGlobal);
m_TreeClassView.InsertItem (_T("THIS_FILE"), 18, 18, hGlobal);
HTREEITEM hMacros = m_TreeClassView.InsertItem (_T("Macros and Constants"), 20, 20, hRoot);
m_TreeClassView.InsertItem (_T("AFX_CHILDFRM_H_AF42DC2C"), 20, 20, hMacros);
m_TreeClassView.InsertItem (_T("AFX_GUI_DEVSTUDIO_H"), 20, 20, hMacros);
m_TreeClassView.InsertItem (_T("AFX_GUI_DECSTUDIOVIEW_H"), 20, 20, hMacros);
m_TreeClassView.InsertItem (_T("AFX_MAINFRM_H"), 20, 20, hMacros);
m_TreeClassView.InsertItem (_T("_APS_3D_CONTROLS"), 20, 20, hMacros);
m_TreeClassView.InsertItem (_T("_APS_NEXT_COMMAND_VALUE"), 20, 20, hMacros);
m_TreeClassView.InsertItem (_T("IDB_DBPROJECTS"), 20, 20, hMacros);
m_TreeClassView.InsertItem (_T("IDR_MAINFRAME"), 20, 20, hMacros);
m_TreeClassView.InsertItem (_T("new"), 20, 20, hMacros);
HTREEITEM hDlg = m_TreeClassView.InsertItem (_T("CAboutDlg"), 15, 15, hRoot);
m_TreeClassView.InsertItem (_T("Bases and Interfaces"), 15, 15, hDlg);
m_TreeClassView.InsertItem (_T("Maps"), 15, 15, hDlg);
m_TreeClassView.InsertItem (_T("_unnamed_d4099230_1"), 15, 15, hDlg);
m_TreeClassView.InsertItem (_T("CAboutDlg(void)"), 15, 15, hDlg);
HTREEITEM hChild = m_TreeClassView.InsertItem (_T("CChilFrame"), 15, 15, hRoot);
HTREEITEM hChild1 = m_TreeClassView.InsertItem (_T("CGui_DevStudioApp"), 15, 15, hRoot);
HTREEITEM hChild2 = m_TreeClassView.InsertItem (_T("CGui_DevStudioView"), 15, 15, hRoot);
m_TreeClassView.Expand (hRoot, TVE_EXPAND);
m_TreeClassView.Expand (hGlobal, TVE_EXPAND);
m_TreeClassView.Expand (hMacros, TVE_EXPAND);
m_TreeClassView.Expand (hDlg, TVE_EXPAND);
}
|
#include <vector>
class ParkingLot {
public:
class ParkingSpace {};
private:
std::vector<ParkingSpace> spaces;
};
|
#include "modes.h"
namespace lab
{
// the timing mode emits timing updates with the current time
// whenever the mode's update() is called.
//
// things like the timeline listen to the timing mode and update
// their status accordingly
//
extern event<void(std::chrono::steady_clock::time_point&)> evt_timing_update;
class TimingMode : public MinorMode
{
public:
virtual const char * name() const override { return "timing"; }
virtual void update(lab::GraphicsRootWindow&);
};
} // lab
|
#include "inputhandler.hpp"
#include "messages.hpp"
InputHandler::InputHandler(fea::MessageBus& bus, fea::InputHandler& handler):
mHandler(handler),
mBus(bus)
{
}
std::vector<Action> InputHandler::process()
{
std::vector<Action> actions;
fea::Event event;
while(mHandler.pollEvent(event))
{
if(event.type == fea::Event::KEYPRESSED)
{
if(event.key.code == fea::Keyboard::ESCAPE)
mBus.send(QuitMessage());
else if(event.key.code == fea::Keyboard::W)
mDirectionResolver1.upActive(true);
else if(event.key.code == fea::Keyboard::S)
mDirectionResolver1.downActive(true);
else if(event.key.code == fea::Keyboard::A)
mDirectionResolver1.leftActive(true);
else if(event.key.code == fea::Keyboard::D)
mDirectionResolver1.rightActive(true);
else if(event.key.code == fea::Keyboard::I)
mDirectionResolver2.upActive(true);
else if(event.key.code == fea::Keyboard::K)
mDirectionResolver2.downActive(true);
else if(event.key.code == fea::Keyboard::J)
mDirectionResolver2.leftActive(true);
else if(event.key.code == fea::Keyboard::L)
mDirectionResolver2.rightActive(true);
mBus.send(KeyPressedMessage{event.key.code});
}
if(event.type == fea::Event::KEYRELEASED)
{
if(event.key.code == fea::Keyboard::W)
mDirectionResolver1.upActive(false);
else if(event.key.code == fea::Keyboard::S)
mDirectionResolver1.downActive(false);
else if(event.key.code == fea::Keyboard::A)
mDirectionResolver1.leftActive(false);
else if(event.key.code == fea::Keyboard::D)
mDirectionResolver1.rightActive(false);
else if(event.key.code == fea::Keyboard::I)
mDirectionResolver2.upActive(false);
else if(event.key.code == fea::Keyboard::K)
mDirectionResolver2.downActive(false);
else if(event.key.code == fea::Keyboard::J)
mDirectionResolver2.leftActive(false);
else if(event.key.code == fea::Keyboard::L)
mDirectionResolver2.rightActive(false);
}
else if(event.type == fea::Event::CLOSED)
{
mBus.send(QuitMessage());
}
else if(event.type == fea::Event::RESIZED)
{
mBus.send(ResizeMessage{{event.size.width, event.size.height}});
}
else if(event.type == fea::Event::MOUSEBUTTONPRESSED)
{
mBus.send(MouseClickMessage{{event.mouseButton.x, event.mouseButton.y}});
}
else if(event.type == fea::Event::MOUSEBUTTONRELEASED)
{
mBus.send(MouseReleaseMessage{{event.mouseButton.x, event.mouseButton.y}});
}
else if(event.type == fea::Event::MOUSEMOVED)
{
mBus.send(MouseMoveMessage{{event.mouseMove.x, event.mouseMove.y}});
}
}
auto direction = mDirectionResolver1.getDirection();
if(direction.y < 0.0f)
actions.emplace_back(Action{0, ActionType::AIM_UP});
else if(direction.y > 0.0f)
actions.emplace_back(Action{0, ActionType::AIM_DOWN});
if(direction.x < 0.0f)
actions.emplace_back(Action{0, ActionType::WALK_LEFT});
else if(direction.x > 0.0f)
actions.emplace_back(Action{0, ActionType::WALK_RIGHT});
direction = mDirectionResolver2.getDirection();
if(direction.y < 0.0f)
actions.emplace_back(Action{1, ActionType::AIM_UP});
else if(direction.y > 0.0f)
actions.emplace_back(Action{1, ActionType::AIM_DOWN});
if(direction.x < 0.0f)
actions.emplace_back(Action{1, ActionType::WALK_LEFT});
else if(direction.x > 0.0f)
actions.emplace_back(Action{1, ActionType::WALK_RIGHT});
return actions;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domstylesheets/stylesheet.h"
#include "modules/dom/src/domstylesheets/medialist.h"
#include "modules/dom/src/domcore/element.h"
#include "modules/logdoc/htm_elm.h"
DOM_StyleSheet::DOM_StyleSheet(DOM_Node *owner_node)
: owner_node(owner_node)
{
}
/* virtual */ ES_GetState
DOM_StyleSheet::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
HTML_Element *element = ((DOM_Element *) owner_node)->GetThisElement();
BOOL is_imported = (element->GetInserted() == HE_INSERTED_BY_CSS_IMPORT);
switch (property_name)
{
case OP_ATOM_href:
if (element->Type() == HE_STYLE)
{
DOMSetNull(value);
return GET_SUCCESS;
}
/* fall through */
case OP_ATOM_disabled:
case OP_ATOM_title:
case OP_ATOM_type:
if (value)
DOMSetString(value, element->DOMGetAttribute(GetEnvironment(), DOM_AtomToHtmlAttribute(property_name), NULL, NS_IDX_DEFAULT, FALSE, TRUE));
return GET_SUCCESS;
case OP_ATOM_media:
if (value)
{
ES_GetState result = DOMSetPrivate(value, DOM_PRIVATE_media);
if (result != GET_FAILED)
return result;
DOM_MediaList *medialist;
GET_FAILED_IF_ERROR(DOM_MediaList::Make(medialist, this));
GET_FAILED_IF_ERROR(PutPrivate(DOM_PRIVATE_media, *medialist));
DOMSetObject(value, medialist);
}
return GET_SUCCESS;
case OP_ATOM_ownerNode:
if (!is_imported)
DOMSetObject(value, owner_node);
else
DOMSetNull(value);
return GET_SUCCESS;
case OP_ATOM_parentStyleSheet:
if (value)
if (is_imported)
{
DOM_Node *node;
GET_FAILED_IF_ERROR(GetEnvironment()->ConstructNode(node, element->Parent(), owner_node->GetOwnerDocument()));
return node->GetName(OP_ATOM_sheet, value, origining_runtime);
}
else
DOMSetNull(value);
return GET_SUCCESS;
default:
return GET_FAILED;
}
}
/* virtual */ ES_PutState
DOM_StyleSheet::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_name == OP_ATOM_disabled)
return owner_node->PutName(property_name, value, origining_runtime);
else if (DOM_StyleSheet::GetName(property_name, value, origining_runtime) == GET_SUCCESS)
return PUT_READ_ONLY;
else
return PUT_FAILED;
}
/* virtual */ void
DOM_StyleSheet::GCTrace()
{
GCMark(owner_node);
}
|
#ifndef ROOM_H_
#define ROOM_H_
#include <QMainWindow>
#include <string>
#include <map>
#include <string>
#include <vector>
#include "item.h"
using namespace std;
using std::vector;
class Room {
private:
string description;
string itemDescription;
map<string, Room*> exits;
string roomSetting;
vector <Item> itemsInRoom;
public:
string exitString();
Room(string description, string roomSetting);
void setExits(Room *forward, Room *backward, Room *right, Room *left);
Room* nextRoom(string direction);
string shortDescription();
void deleteItem(int index);
string longDescription();
string getItem();
string getRoomSetting();
string getRoomItem();
string roomDesc();
void addItem(Item *item);
string displayItem();
string showItemInInventory();
int isItemInRoom(string inString);
int numberOfItems();
string itemDesc();
};
#endif
|
/*
191216
- 백준 #7576 : 토마토
*/
#include <iostream>
#include <queue>
using namespace std;
#define MAX 1000+1
int M, N;
int arr[MAX][MAX]={0,};
int visited[MAX][MAX]={0,};
typedef struct {
int x;
int y;
int day;
}POS;
queue<POS> q;
int front = -1;
int rear = -1;
int days = 0;
int riped = 0;
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
void bfs() {
while(!q.empty()) {
POS cur=q.front();
q.pop();
int cur_x = cur.x;
int cur_y = cur.y;
int cur_day = cur.day;
visited[cur_x][cur_y]=1;
for(int i=0; i<4; i++) {
int nx = cur_x + dx[i];
int ny = cur_y + dy[i];
if ( nx<0 || nx>=N || ny<0 || ny>=M || visited[nx][ny])
continue;
if ( arr[nx][ny]==0 ) {
arr[nx][ny] = 1;
q.push({nx,ny,cur_day+1});
}
}
days = (days<cur_day) ? cur_day : days;
}
}
void solve() {
bfs();
for(int i=0; i<N; i++) {
for(int j=0; j<M; j++) {
if ( arr[i][j]==0 ) {
days = -1;
break;
}
}
}
}
int main() {
cin>>M>>N;
for(int i=0; i<N; i++) {
for(int j=0; j<M; j++) {
cin>>arr[i][j];
if ( arr[i][j]==1 ) {
q.push({i,j,0});
}
}
}
solve();
cout<<days<<endl;
return 0;
}
|
#include <iostream>
#include <unordered_set>
#include "jump_mesh.hpp"
#define SimpleMesh JumpMesh
using namespace std;
void print_header() {
cout << "\n\t\tSIMPLE_MESH TEST\n" << endl;
cout << "All tests should print 1 if successful." << endl;
cout << "When mesh graphic is output, it needs visual confirmation.\n\n" << endl;
}
bool test_Point2D_out() {
Point2D point(3,2);
cout << point << endl;
return true; //Assume that if it reaches here, then everything's okay
}
bool test_Point2D_equality() {
Point2D point1(3,2);
Point2D point2(3,2);
Point2D point3(3,3);
return (point1 == point2 && point1 != point3);
}
bool test_Point2D_assignment() {
Point2D point1(3,3);
Point2D point2(2,2);
Point2D point3(3,3);
point2 = point3;
return (point1 == point2);
}
/* Test a - b. As it's defined in terms of c(a), c-=b, it also tests -= and copy-construct*/
bool test_Point2D_subtract() {
Point2D point1(3,2);
Point2D point2(2,1);
Point2D point3(-1,-1);
return (point2 - point1 == point3);
}
bool test_Point2D_add() {
Point2D point1(3,2);
Point2D point2(2,1);
Point2D point3(5,3);
return (point1 + point2 == point3);
}
bool test_Point2D_manhattan() {
Point2D point1(-3,2);
Point2D point2(2,1);
int expected = 6;
return (manhattanDist(point1, point2) == expected);
}
bool test_Point2D_euclidean() {
Point2D point1(-3,2);
Point2D point2(2,1);
float expected = 5.0990195135;
float result = euclideanDist(point1, point2);
return (result == expected);
}
/* Test creation of SimpleMesh.
Tests creation, obstacle addition and removal, getArrayValue and output.
*/
bool test_SimpleMesh_creation() {
SimpleMesh mesh(15, 10);
mesh.addObstacle({3, 3}, {8, 5}); // Implicit constructor of Point2D in arguments.
mesh.removeObstacle(Point2D(4, 4), Point2D(5, 3));
printMesh(mesh);
cout << endl;
return true; //Assume that reaching here is success. Validate output visually.
}
bool test_SimpleMesh_getShape() {
SimpleMesh mesh(15, 10);
return (mesh.getShape() == Point2D(15, 10));
}
void test_SimpleMesh_isAccessible() {
SimpleMesh mesh(15, 10);
cout << "\t\tTesting bounds checking:" << endl;
/* Check that out-of-bounds checking works */
Point2D point(0, 0);
cout << "\t\t" << point << " : " << mesh.isAccessible(point) << endl;
point = {14, 9}; // Implicit constructor again
cout << "\t\t" << point << " : " << mesh.isAccessible(point) << endl;
point = Point2D(-1, 0);
cout << "\t\t" << point << " : " << !mesh.isAccessible(point) << endl;
point = Point2D(15, 0);
cout << "\t\t" << point << " : " << !mesh.isAccessible(point) << endl;
point = Point2D(0, -1);
cout << "\t\t" << point << " : " << !mesh.isAccessible(point) << endl;
point = Point2D(0, 10);
cout << "\t\t" << point << " : " << !mesh.isAccessible(point) << endl;
point = Point2D(15, 10);
cout << "\t\t" << point << " : " << !mesh.isAccessible(point) << endl;
/* Check that obstacle checking works */
cout << "\t\tTesting obstacle checking:" << endl;
mesh.addObstacle(Point2D(0,0), Point2D(1,1));
point = Point2D(0, 0);
cout << "\t\t" << point << " : " << !mesh.isAccessible(point) << endl;
}
void test_SimpleMesh_getDistance() {
SimpleMesh mesh(15, 10);
Point2D from(0, 0);
Point2D to(0, 0);
cout << "\t\t" << from << to << " : " << (mesh.getDistance(from, to) == 0) << endl;
to = Point2D(-1, 0);
cout << "\t\t" << from << to << " : " << (mesh.getDistance(from, to) == 1) << endl;
to = Point2D(1, 0);
cout << "\t\t" << from << to << " : " << (mesh.getDistance(from, to) == 1) << endl;
to = Point2D(0, -1);
cout << "\t\t" << from << to << " : " << (mesh.getDistance(from, to) == 1) << endl;
to = Point2D(0, 1);
cout << "\t\t" << from << to << " : " << (mesh.getDistance(from, to) == 1) << endl;
to = Point2D(1, 1);
cout << "\t\t" << from << to << " : " << (mesh.getDistance(from, to) - 1.414213562 < 0.00001) << endl;
to = Point2D(-1, -1);
cout << "\t\t" << from << to << " : " << (mesh.getDistance(from, to) - 1.414213562 < 0.00001) << endl;
to = Point2D(-2, -4); //Point2D euclideanDist
cout << "\t\t" << from << to << " : " << (mesh.getDistance(from, to) - 4.472135954 < 0.00001) << endl;
}
bool test_SimpleMesh_getHeuristic() {
SimpleMesh mesh(15, 10);
Point2D from(0, 0);
Point2D to(-2, -4);
return (mesh.getDistance(from, to) - 4.472135954 < 0.00001);
}
bool test_SimpleMesh_getNeighbours() {
SimpleMesh mesh(15, 10);
mesh.addObstacle(Point2D(0, 1), Point2D(1,1));
std::vector<Point2D> expected1({Point2D(1, 0)});
std::vector<Point2D> neighbours1(mesh.getNeighbours(Point2D(0, 0)));
std::vector<Point2D> expected2({Point2D(6, 4), Point2D(6, 6), Point2D(5, 5), Point2D(7, 5)});
std::vector<Point2D> neighbours2(mesh.getNeighbours(Point2D(6, 5)));
return (expected1 == neighbours1 && expected2 == neighbours2);
}
void test_SimpleMesh_isVisible() {
SimpleMesh mesh(15, 10);
mesh.addObstacle(Point2D(3,3), Point2D(1,3));
mesh.addObstacle(Point2D(0,7), Point2D(3,1));
printMesh(mesh);
Point2D from(2, 5);
Point2D to(2, 5);
cout << "\t\tSelf-visibility" << endl;
cout << "\t\t" << from << to << " : " << (mesh.isVisible(from, to)) << endl;
from = Point2D(3, 5);
to = Point2D(3, 5);
cout << "\t\t" << from << to << " : " << (mesh.isVisible(from, to)) << endl;
cout << "\t\tNon-accessible" << endl;
from = Point2D(2, 5);
to = Point2D(-2, 5);
cout << "\t\t" << from << to << " : " << !(mesh.isVisible(from, to)) << endl;
to = Point2D(3, 5);
cout << "\t\t" << from << to << " : " << !(mesh.isVisible(from, to)) << endl;
cout << "\t\tObstacle visibility" << endl;
to = Point2D(4, 4);
cout << "\t\t" << from << to << " : " << !(mesh.isVisible(from, to)) << endl;
to = Point2D(4, 6);
cout << "\t\t" << from << to << " : " << (mesh.isVisible(from, to)) << endl;
to = Point2D(1, 8);
cout << "\t\t" << from << to << " : " << !(mesh.isVisible(from, to)) << endl;
to = Point2D(3, 8);
cout << "\t\t" << from << to << " : " << (mesh.isVisible(from, to)) << endl;
cout << "\t\tObstacle visibility" << endl;
from = Point2D(4, 4);
to = Point2D(2, 5);
cout << "\t\t" << from << to << " : " << !(mesh.isVisible(from, to)) << endl;
from = Point2D(4, 6);
cout << "\t\t" << from << to << " : " << (mesh.isVisible(from, to)) << endl;
from = Point2D(1, 8);
cout << "\t\t" << from << to << " : " << !(mesh.isVisible(from, to)) << endl;
from = Point2D(3, 8);
cout << "\t\t" << from << to << " : " << (mesh.isVisible(from, to)) << endl;
}
int main(){
print_header();
cout << "Testing Point2D:" << endl;
cout << "\tPoint2D output: " << test_Point2D_out() << endl;
cout << "\tPoint2D equality: " << test_Point2D_equality() << endl;
cout << "\tPoint2D assignment: " << test_Point2D_assignment() << endl;
cout << "\tPoint2D subtract and copy-construct: " << test_Point2D_subtract() << endl;
cout << "\tPoint2D add: " << test_Point2D_add() << endl;
cout << "\tPoint2D manhattanDist: " << test_Point2D_manhattan() << endl;
cout << "\tPoint2D euclideanDist: " << test_Point2D_euclidean() << endl;
cout << "Done Point2D.\n" << endl;
cout << "Testing SimpleMesh:" << endl;
cout << "\tSimpleMesh creation: " << test_SimpleMesh_creation() << endl;
cout << "\tSimpleMesh getShape: " << test_SimpleMesh_getShape() << endl;
cout << "\tSimpleMesh isAccessible:" << endl;
test_SimpleMesh_isAccessible();
cout << "\tSimpleMesh getDistance:" << endl;
test_SimpleMesh_getDistance();
cout << "\tSimpleMesh getHeuristic: " << test_SimpleMesh_getHeuristic() << endl;
cout << "\tSimpleMesh getNeighbours: " << test_SimpleMesh_getNeighbours() << endl;
cout << "\tSimpleMesh isVisible:" << endl;
test_SimpleMesh_isVisible();
}
|
/*
* Copyright (c) 2017-2018 Morwenn
* SPDX-License-Identifier: MIT
*/
#include <algorithm>
#include <functional>
#include <iterator>
#include <vector>
#include <catch2/catch.hpp>
#include <cpp-sort/adapters.h>
#include <cpp-sort/fixed_sorters.h>
#include <cpp-sort/sorters/merge_sorter.h>
#include <cpp-sort/sorters/poplar_sorter.h>
#include <cpp-sort/sorters/selection_sorter.h>
#include <testing-tools/algorithm.h>
#include <testing-tools/distributions.h>
#include <testing-tools/internal_compare.h>
TEST_CASE( "test most adapters with a pointer to member function comparison",
"[adapters][as_function]" )
{
std::vector<internal_compare<int>> collection;
collection.reserve(65);
auto distribution = dist::shuffled{};
distribution(std::back_inserter(collection), 65, 0);
SECTION( "counting_adapter" )
{
using sorter = cppsort::counting_adapter<
cppsort::selection_sorter
>;
// Sort and check it's sorted
std::size_t res = sorter{}(collection, &internal_compare<int>::compare_to);
CHECK( res == 2080 );
CHECK( std::is_sorted(std::begin(collection), std::end(collection)) );
}
SECTION( "hybrid_adapter" )
{
using sorter = cppsort::hybrid_adapter<
cppsort::merge_sorter,
cppsort::poplar_sorter
>;
sorter{}(collection, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(collection), std::end(collection)) );
}
SECTION( "indirect_adapter" )
{
using sorter = cppsort::indirect_adapter<
cppsort::poplar_sorter
>;
sorter{}(collection, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(collection), std::end(collection)) );
}
SECTION( "out_of_place_adapter" )
{
using sorter = cppsort::out_of_place_adapter<
cppsort::poplar_sorter
>;
sorter{}(collection, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(collection), std::end(collection)) );
std::list<internal_compare<int>> li;
distribution(std::back_inserter(li), 65, 0);
sorter{}(li, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(li), std::end(li)) );
}
SECTION( "schwartz_adapter" )
{
using sorter = cppsort::schwartz_adapter<
cppsort::poplar_sorter
>;
sorter{}(collection, &internal_compare<int>::compare_to, std::negate<>{});
CHECK( std::is_sorted(std::begin(collection), std::end(collection), std::greater<>{}) );
}
SECTION( "self_sort_adapter" )
{
using sorter = cppsort::self_sort_adapter<
cppsort::poplar_sorter
>;
sorter{}(collection, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(collection), std::end(collection)) );
std::list<internal_compare<int>> li;
distribution(std::back_inserter(li), 65, 0);
sorter{}(li, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(li), std::end(li)) );
}
SECTION( "stable_adapter<self_sort_adapter>" )
{
using sorter = cppsort::stable_adapter<
cppsort::self_sort_adapter<cppsort::poplar_sorter>
>;
sorter{}(collection, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(collection), std::end(collection)) );
std::list<internal_compare<int>> li;
distribution(std::back_inserter(li), 65, 0);
sorter{}(li, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(li), std::end(li)) );
}
SECTION( "small_array_adapter" )
{
using namespace cppsort;
std::array<internal_compare<int>, 6> arr = {{ {4}, {3}, {2}, {5}, {6}, {1} }};
auto to_sort = arr;
small_array_adapter<low_comparisons_sorter>{}(to_sort, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(to_sort), std::end(to_sort)) );
to_sort = arr;
small_array_adapter<low_moves_sorter>{}(to_sort, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(to_sort), std::end(to_sort)) );
to_sort = arr;
small_array_adapter<sorting_network_sorter>{}(to_sort, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(to_sort), std::end(to_sort)) );
}
SECTION( "stable_adapter" )
{
using sorter = cppsort::stable_adapter<
cppsort::poplar_sorter
>;
sorter{}(collection, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(collection), std::end(collection)) );
}
SECTION( "verge_adapter" )
{
using sorter = cppsort::verge_adapter<
cppsort::poplar_sorter
>;
sorter{}(collection, &internal_compare<int>::compare_to);
CHECK( std::is_sorted(std::begin(collection), std::end(collection)) );
}
}
|
#include<<constream.h>>
class Physics and technology(){
public:
void computer tech(){
cout<<"computer tech" <<endl;
}
void electronics(){
cout<<"electronic " <<endl;
}
void telecom(){
cout<<"telecommunication" <<endl;
}
void lab(){
cout<<"labortory" <<endl;
}
};
class IIT:Physics and technology{
public:
void IT(){
cout<<"IT" <<endl;
}
void soft engg(){
cout<<"soft engg" <<endl;
}
void electronics(){
cout<<"electronics" <<endl;
}
void telecom(){
cout<<"telecom4year" <<endl;
}
};
void main(){
clrscr();
IIT ob;
ob.IT();
ob.soft engg();
ob.lab();
ob.computer tech();
ob.electronics();
getch();
}
|
#ifndef BATTLE_H
#define BATTLE_H
#include "Scene.h"
#include "Arena.h"
#include "xil_types.h"
class Battle : public Scene
{
public:
Battle(uint32_t axi_arena_base_addr, uint32_t axi_bomber_info_base_addr, Scene *endgame, uint8_t id);
void Init(uint8_t info) override;
void HandleInput(uint8_t key) override;
void Update(float dt) override;
uint8_t Info() const override;
private:
Arena arena;
uint8_t bomber_inputs[2];
uint32_t * const axi_arena_data;
uint32_t * const axi_bombers_text;
uint8_t KeyToCode(uint8_t key) const;
void UpdateBombersText();
};
#endif
|
class Category_603 {
duplicate = 486;
};
class Category_638 {
duplicate = 486;
};
|
#include <TimerOne.h>
#include <avr/pgmspace.h>
#include "pitches.h"
//#include "songs.h"
#include "songs2.h"
#include <avr/sleep.h>
const int PowerLedPin = 15; // the number of the LED pin
const int ledPin = 2; // the number of the LED pin
const int anode_pins[] = {9, 10, 11, 5, 6, 7, 8, 12}; // アノードに接続するArduinoのピン
//const int digits[] = {
volatile int digits[] = {
0b01000000, // 0
0b01110011, // 1
0b00100100, // 2
0b00100001, // 3
0b00010011, // 4
0b00001001, // 5
0b00001000, // 6
0b01000011, // 7
0b00000000, // 8
0b00000001, // 9
};
volatile int bootDigits[] = {
// 0b11111011, // 4
// 0b11111101, // 5
// 0b11111110, // 6
// 0b10111111, // 0
// 0b11110111, // 3
// 0b11101111, // 2
// 0b11011111, // 1
// 0b10111111, // 0
// 0b11111011, // 4
0b11111101, // 5
0b11111100, // 6
0b10111110, // 0
0b10110111, // 3
0b11100111, // 2
0b11001111, // 1
0b10011111, // 0
0b10111011, // 4
0b11111001, // 5
0b11111101, // 5
};
const int buttonPin = 3; // the number of the pushbutton pin
int buttonState = 0; // the current reading from the input pin
const int upButtonPin = 13; // the number of the pushbutton pin
int upButtonState; // the current reading from the input pin
int lastUpButtonState = LOW; // the current reading from the input pin
unsigned long upButtonDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
const int downButtonPin = 4; // the number of the pushbutton pin
int downButtonState; // the current reading from the input pin
int lastDownButtonState = LOW; // the current reading from the input pin
unsigned long downButtonDebounceTime = 0; // the last time the output pin was toggled
unsigned long downDebounceDelay = 50; // the debounce time; increase if the output flickers
int autoPlay = 0;
volatile int currentSong = 0;
int currentPosition = 0;
int readyTone = 1;
int nowNote;
int nowNoteDuration;
int tempo;
unsigned long sleepTime = 300000;
unsigned long sleepTimeCount = millis();
void ledBlink() {
static boolean output = LOW; // プログラム起動前に1回だけHIGH(1)で初期化される
digitalWrite(PowerLedPin, output); // 13番ピン(LED)に出力する(HIGH>ON LOW>OFF)
if(output){
for (int i = 0; i < (sizeof(anode_pins) / sizeof(anode_pins[0])); i++) {
digitalWrite(anode_pins[i], digits[currentSong] & (1 << i) ? HIGH : LOW);
}
} else {
for (int i = 0; i < (sizeof(anode_pins) / sizeof(anode_pins[0])); i++) {
digitalWrite(anode_pins[i], HIGH);
}
}
output = !output; // 現在のoutput内容を反転(HIGH→LOW/LOW→HIGH)させoutputにセットする
}
void setup() {
pinMode(PowerLedPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
digitalWrite(12, HIGH);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
PORTD = B11100000;
for(int n = 0; n < 3; n++){
for(int j = 0; j < (sizeof(bootDigits) / sizeof(bootDigits[0])); j++){
for (int i = 0; i < (sizeof(anode_pins) / sizeof(anode_pins[0])); i++) {
digitalWrite(anode_pins[i], bootDigits[j] & (1 << i) ? HIGH : LOW);
}
delay(30);
}
}
// digitalWrite(PowerLedPin, HIGH);
// Timer1.initialize(1000000); //マイクロ秒単位で設定
Timer1.initialize(13000); //マイクロ秒単位で設定
Timer1.attachInterrupt(ledBlink);
pinMode(buttonPin, INPUT);
pinMode(upButtonPin, INPUT);
pinMode(downButtonPin, INPUT);
Serial.begin(9600);
Serial.println("Hello!! We are The-MenZ!!");
}
void loop() {
int buttonState = digitalRead(buttonPin);
int reading = digitalRead(upButtonPin);
if (reading != lastUpButtonState) {
upButtonDebounceTime = millis();
// スリープカウントリセット
sleepTimeCount = millis();
}
int downButtonReading = digitalRead(downButtonPin);
if (downButtonReading != lastDownButtonState) {
downButtonDebounceTime = millis();
// スリープカウントリセット
sleepTimeCount = millis();
}
// ボタンプッシュで曲選択
if ((millis() - upButtonDebounceTime) > debounceDelay) {
if (reading != upButtonState) {
upButtonState = reading;
if (upButtonState == HIGH) {
//曲の頭出し
currentPosition = 0;
currentSong++;
if(currentSong >= songNum) currentSong = 0;
}
}
}
// ボタンプッシュで自動演奏
if ((millis() - downButtonDebounceTime) > downDebounceDelay) {
if (downButtonReading != downButtonState) {
// Serial.println("DEBUG DEBUG DEBUG downButton: ");
downButtonState = downButtonReading;
autoPlay = 1;
}
}
// 自動演奏モード
if(autoPlay == 1){
// Serial.println("DEBUG DEBUG DEBUG autoPlay: ");
nowNote = pgm_read_word(&melody[currentSong][currentPosition]);
tempo = pgm_read_word(&tempoList[currentSong]);
nowNoteDuration = pgm_read_float(¬eDurations[currentSong][currentPosition]);
// Serial.print("tempo: ");
// Serial.println(tempo);
// Serial.print("nowNoteDuration: ");
// Serial.println(nowNoteDuration);
nowNoteDuration = (int)(((60000 / tempo) * 4)/ nowNoteDuration);
// 最後の音まで来たらリセット
if(nowNote == 0) {
// Serial.print("if currentPosition: ");
// Serial.println(currentPosition);
currentPosition = 0;
nowNote = pgm_read_word(&melody[currentSong][currentPosition]);
autoPlay = 0;
// Serial.println("DEBUG DEBUG DEBUG reset: ");
} else {
// Serial.print("nowNoteDuration: ");
// Serial.println(nowNoteDuration);
if (nowNote > 1) {
tone(14, nowNote);
}
delay(nowNoteDuration);
noTone(14);
currentPosition++;
}
}
// ONされて一回だけ実行
if(buttonState == 1 && readyTone == 1){
digitalWrite(ledPin, HIGH);
nowNote = pgm_read_word(&melody[currentSong][currentPosition]);
autoPlay = 0;
// 1はスキップ
if(nowNote == 1){
currentPosition++;
nowNote = pgm_read_word(&melody[currentSong][currentPosition]);
}
// 最後の音まで来たらリセット
if(nowNote == 0){
// Serial.print("if currentPosition: ");
// Serial.println(currentPosition);
currentPosition = 0;
nowNote = pgm_read_word(&melody[currentSong][currentPosition]);
}
tone(14, nowNote);
// Serial.print("tone: ");
// Serial.println(nowNote);
// Serial.print("currentPosition: ");
// Serial.println(currentPosition);
// ifを何度も実行しないようにフラグを立てる
readyTone = 0;
// スリープカウントリセット
sleepTimeCount = millis();
}
// OFFされて一回だけ実行
if (buttonState == 0 && readyTone == 0) {
digitalWrite(ledPin, LOW);
currentPosition++;
noTone(14);
delay(50);
readyTone = 1;
}
lastUpButtonState = reading;
lastDownButtonState = downButtonReading;
// スリープチェック
if ((millis() - sleepTimeCount) > sleepTime) {
for (int i = 0; i < (sizeof(anode_pins) / sizeof(anode_pins[0])); i++) {
digitalWrite(anode_pins[i], HIGH);
}
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_mode();
}
}
|
#include <iostream>
#include <conio.h>
using namespace std;
struct Nodo{
int valor;
Nodo *Anterior;
Nodo *Siguiente;
};
void agregar(int);
void mostrar();
void mostrar_an();
struct Nodo *lista=NULL;
int main(int argc, char** argv) {
int option,agreg,num;
while(option!=3){
cout<<":-:-:LISTA DOBLEMEMNTE ENLAZADA:-:-:"<<endl;
cout<<"1.- Ingresar valores de la lista"<<endl;
cout<<"2.- Mostrar los valores de la lista"<<endl;
cout<<"3.- Salir"<<endl;
cin>>option;
switch (option){
case 1:
cout<<"Ingrese el numero de datos que desea agregar"<<endl;
cin>>num;
for (int i=1;i<=num;i++){
cout<<"Ingrese los datos"<<endl;
cin>>agreg;
agregar(agreg);
}
break;
case 2:
cout<<"Mostrar los datos de la lista"<<endl;
cout<<" "" "<<endl;
mostrar();
cout<<" "" "<<endl;
mostrar_an();
cout<<" "" "<<endl;
break;
case 3:
cout<<"Salir";
default:
cout<<"Gracias por usar este programa"<<endl;
break;
}
}
return 0;
}
void agregar(int agreg)
{
Nodo *nuevo= new Nodo;
nuevo->Siguiente=NULL;
nuevo->Anterior=NULL;
nuevo->valor=agreg;
if(lista==NULL)lista=nuevo;
else{
Nodo *aux=lista;
while(aux->Siguiente!=NULL){
aux=aux->Siguiente;
}
aux->Siguiente=nuevo;
nuevo->Anterior=aux;
}
}
void mostrar(){
Nodo *aux=lista;
while(aux!=NULL){
cout<<aux->valor<<" -> ";
aux=aux->Siguiente;
}
}
void mostrar_an()
{
Nodo *aux=lista;
while(aux->Siguiente!=NULL){
aux=aux->Siguiente;
}
while(aux!=NULL){
cout<<aux->valor<<" -> ";
aux=aux->Anterior;
}
}
|
#include "stdafx.h"
#include "Prof-UIS.h"
extern "C" __declspec(dllexport) HWND WINAPI UISalPageContainerCreate(HWND parentWindow, UINT controlID, int x, int y, int width, int height, DWORD pageContainerStyle, DWORD windowStyle)
{
// access parent window
CWnd* parentWindowClass = NULL;
if (parentWindow != NULL)
{
parentWindowClass = CWnd::FromHandlePermanent(parentWindow);
}
// create Page Container
CExtPageContainerWnd* pageContainer = new CExtPageContainerWnd();
pageContainerStyle = ((pageContainerStyle == 0) ? __EPCWS_STYLES_DEFAULT : 0);
windowStyle = ((windowStyle == 0) ? WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS : 0);
pageContainer->Create(parentWindowClass, controlID, CRect(x, y, width, height), pageContainerStyle, windowStyle, NULL);
// test
/*
if (pageContainer != NULL)
{
HWND page = NULL;
pageContainer->PageInsert(page, -1, L"Page 1", NULL, false, 0, true, false, false);
pageContainer->PageInsert(page, -1, L"Page 2", NULL, false, 0, false, false, false);
pageContainer->PageInsert(page, -1, L"Page 3", NULL, false, 0, false, false, true);
}
*/
return ((pageContainer == NULL) ? NULL : pageContainer->GetSafeHwnd());
}
|
#include <gtest/gtest.h>
#include "shoc/ecc/crc.h"
using namespace shoc;
static constexpr auto test_data = "123456789";
static constexpr auto test_size = 9;
template<class T, T poly, T init, T xorout, bool refin, bool refout>
static constexpr auto check_fast_and_slow(T exp)
{
EXPECT_EQ(exp, (crc_slow<T, poly, init, xorout, refin, refout>(test_data, test_size)));
EXPECT_EQ(exp, (crc_fast<T, poly, init, xorout, refin, refout>(test_data, test_size)));
}
template<uint8_t poly, uint8_t init, uint8_t xorout, bool refin, bool refout>
static constexpr auto check_fast_and_slow_8(uint8_t exp)
{
return check_fast_and_slow<uint8_t, poly, init, xorout, refin, refout>(exp);
}
template<uint16_t poly, uint16_t init, uint16_t xorout, bool refin, bool refout>
static constexpr auto check_fast_and_slow_16(uint16_t exp)
{
return check_fast_and_slow<uint16_t, poly, init, xorout, refin, refout>(exp);
}
template<uint32_t poly, uint32_t init, uint32_t xorout, bool refin, bool refout>
static constexpr auto check_fast_and_slow_32(uint32_t exp)
{
return check_fast_and_slow<uint32_t, poly, init, xorout, refin, refout>(exp);
}
template<uint64_t poly, uint64_t init, uint64_t xorout, bool refin, bool refout>
static constexpr auto check_fast_and_slow_64(uint64_t exp)
{
return check_fast_and_slow<uint64_t, poly, init, xorout, refin, refout>(exp);
}
TEST(Ecc, Crc8)
{
check_fast_and_slow_8<0x2f, 0xff, 0xff, 0, 0>(0xdf); // CRC-8/AUTOSAR
check_fast_and_slow_8<0xa7, 0x00, 0x00, 1, 1>(0x26); // CRC-8/BLUETOOTH
check_fast_and_slow_8<0x9b, 0xff, 0x00, 0, 0>(0xda); // CRC-8/CDMA2000
check_fast_and_slow_8<0x39, 0x00, 0x00, 1, 1>(0x15); // CRC-8/DARC
check_fast_and_slow_8<0xd5, 0x00, 0x00, 0, 0>(0xbc); // CRC-8/DVB-S2
check_fast_and_slow_8<0x1d, 0x00, 0x00, 0, 0>(0x37); // CRC-8/GSM-A
check_fast_and_slow_8<0x49, 0x00, 0xff, 0, 0>(0x94); // CRC-8/GSM-B
check_fast_and_slow_8<0x1d, 0xff, 0x00, 0, 0>(0xb4); // CRC-8/HITAG
check_fast_and_slow_8<0x07, 0x00, 0x55, 0, 0>(0xa1); // CRC-8/I-432-1
check_fast_and_slow_8<0x1d, 0xfd, 0x00, 0, 0>(0x7e); // CRC-8/I-CODE
check_fast_and_slow_8<0x9b, 0x00, 0x00, 0, 0>(0xea); // CRC-8/LTE
check_fast_and_slow_8<0x31, 0x00, 0x00, 1, 1>(0xa1); // CRC-8/MAXIM-DOW
check_fast_and_slow_8<0x1d, 0xc7, 0x00, 0, 0>(0x99); // CRC-8/MIFARE-MAD
check_fast_and_slow_8<0x31, 0xff, 0x00, 0, 0>(0xf7); // CRC-8/NRSC-5
check_fast_and_slow_8<0x2f, 0x00, 0x00, 0, 0>(0x3e); // CRC-8/OPENSAFETY
check_fast_and_slow_8<0x07, 0xff, 0x00, 1, 1>(0xd0); // CRC-8/ROHC
check_fast_and_slow_8<0x1d, 0xff, 0xff, 0, 0>(0x4b); // CRC-8/SAE-J1850
check_fast_and_slow_8<0x07, 0x00, 0x00, 0, 0>(0xf4); // CRC-8/SMBUS
check_fast_and_slow_8<0x1d, 0xff, 0x00, 1, 1>(0x97); // CRC-8/TECH-3250
check_fast_and_slow_8<0x9b, 0x00, 0x00, 1, 1>(0x25); // CRC-8/WCDMA
}
TEST(Ecc, Crc16)
{
check_fast_and_slow_16<0x8005, 0x0000, 0x0000, 1, 1>(0xbb3d); // CRC-16/ARC
check_fast_and_slow_16<0xc867, 0xffff, 0x0000, 0, 0>(0x4c06); // CRC-16/CDMA2000
check_fast_and_slow_16<0x8005, 0xffff, 0x0000, 0, 0>(0xaee7); // CRC-16/CMS
check_fast_and_slow_16<0x8005, 0x800d, 0x0000, 0, 0>(0x9ecf); // CRC-16/DDS-110
check_fast_and_slow_16<0x0589, 0x0000, 0x0001, 0, 0>(0x007e); // CRC-16/DECT-R
check_fast_and_slow_16<0x0589, 0x0000, 0x0000, 0, 0>(0x007f); // CRC-16/DECT-X
check_fast_and_slow_16<0x3d65, 0x0000, 0xffff, 1, 1>(0xea82); // CRC-16/DNP
check_fast_and_slow_16<0x3d65, 0x0000, 0xffff, 0, 0>(0xc2b7); // CRC-16/EN-13757
check_fast_and_slow_16<0x1021, 0xffff, 0xffff, 0, 0>(0xd64e); // CRC-16/GENIBUS
check_fast_and_slow_16<0x1021, 0x0000, 0xffff, 0, 0>(0xce3c); // CRC-16/GSM
check_fast_and_slow_16<0x1021, 0xffff, 0x0000, 0, 0>(0x29b1); // CRC-16/IBM-3740
check_fast_and_slow_16<0x1021, 0xffff, 0xffff, 1, 1>(0x906e); // CRC-16/IBM-SDLC
check_fast_and_slow_16<0x1021, 0xc6c6, 0x0000, 1, 1>(0xbf05); // CRC-16/ISO-IEC-14443-3-A
check_fast_and_slow_16<0x1021, 0x0000, 0x0000, 1, 1>(0x2189); // CRC-16/KERMIT
check_fast_and_slow_16<0x6f63, 0x0000, 0x0000, 0, 0>(0xbdf4); // CRC-16/LJ1200
check_fast_and_slow_16<0x5935, 0xffff, 0x0000, 0, 0>(0x772b); // CRC-16/M17
check_fast_and_slow_16<0x8005, 0x0000, 0xffff, 1, 1>(0x44c2); // CRC-16/MAXIM-DOW
check_fast_and_slow_16<0x1021, 0xffff, 0x0000, 1, 1>(0x6f91); // CRC-16/MCRF4XX
check_fast_and_slow_16<0x8005, 0xffff, 0x0000, 1, 1>(0x4b37); // CRC-16/MODBUS
check_fast_and_slow_16<0x080b, 0xffff, 0x0000, 1, 1>(0xa066); // CRC-16/NRSC-5
check_fast_and_slow_16<0x5935, 0x0000, 0x0000, 0, 0>(0x5d38); // CRC-16/OPENSAFETY-A
check_fast_and_slow_16<0x755b, 0x0000, 0x0000, 0, 0>(0x20fe); // CRC-16/OPENSAFETY-B
check_fast_and_slow_16<0x1dcf, 0xffff, 0xffff, 0, 0>(0xa819); // CRC-16/PROFIBUS
check_fast_and_slow_16<0x1021, 0xb2aa, 0x0000, 1, 1>(0x63d0); // CRC-16/RIELLO
check_fast_and_slow_16<0x1021, 0x1d0f, 0x0000, 0, 0>(0xe5cc); // CRC-16/SPI-FUJITSU
check_fast_and_slow_16<0x8bb7, 0x0000, 0x0000, 0, 0>(0xd0db); // CRC-16/T10-DIF
check_fast_and_slow_16<0xa097, 0x0000, 0x0000, 0, 0>(0x0fb3); // CRC-16/TELEDISK
check_fast_and_slow_16<0x1021, 0x89ec, 0x0000, 1, 1>(0x26b1); // CRC-16/TMS37157
check_fast_and_slow_16<0x8005, 0x0000, 0x0000, 0, 0>(0xfee8); // CRC-16/UMTS
check_fast_and_slow_16<0x8005, 0xffff, 0xffff, 1, 1>(0xb4c8); // CRC-16/USB
check_fast_and_slow_16<0x1021, 0x0000, 0x0000, 0, 0>(0x31c3); // CRC-16/XMODEM
}
TEST(Ecc, Crc32)
{
check_fast_and_slow_32<0x814141ab, 0x00000000, 0x00000000, 0, 0>(0x3010bf7f); // CRC-32/AIXM
check_fast_and_slow_32<0xf4acfb13, 0xffffffff, 0xffffffff, 1, 1>(0x1697d06a); // CRC-32/AUTOSAR
check_fast_and_slow_32<0xa833982b, 0xffffffff, 0xffffffff, 1, 1>(0x87315576); // CRC-32/BASE91-D
check_fast_and_slow_32<0x04c11db7, 0xffffffff, 0xffffffff, 0, 0>(0xfc891918); // CRC-32/BZIP2
check_fast_and_slow_32<0x8001801b, 0x00000000, 0x00000000, 1, 1>(0x6ec2edc4); // CRC-32/CD-ROM-EDC
check_fast_and_slow_32<0x04c11db7, 0x00000000, 0xffffffff, 0, 0>(0x765e7680); // CRC-32/CKSUM
check_fast_and_slow_32<0x1edc6f41, 0xffffffff, 0xffffffff, 1, 1>(0xe3069283); // CRC-32/ISCSI
check_fast_and_slow_32<0x04c11db7, 0xffffffff, 0xffffffff, 1, 1>(0xcbf43926); // CRC-32/ISO-HDLC
check_fast_and_slow_32<0x04c11db7, 0xffffffff, 0x00000000, 1, 1>(0x340bc6d9); // CRC-32/JAMCRC
check_fast_and_slow_32<0x741b8cd7, 0xffffffff, 0x00000000, 1, 1>(0xd2c22f51); // CRC-32/MEF
check_fast_and_slow_32<0x04c11db7, 0xffffffff, 0x00000000, 0, 0>(0x0376e6e7); // CRC-32/MPEG-2
check_fast_and_slow_32<0x000000af, 0x00000000, 0x00000000, 0, 0>(0xbd0be338); // CRC-32/XFER
}
TEST(Ecc, Crc64)
{
check_fast_and_slow_64<0x42f0e1eba9ea3693, 0x0000000000000000, 0x0000000000000000, 0, 0>(0x6c40df5f0b497347); // CRC-64/ECMA-182
check_fast_and_slow_64<0x000000000000001b, 0xffffffffffffffff, 0xffffffffffffffff, 1, 1>(0xb90956c775a41001); // CRC-64/GO-ISO
check_fast_and_slow_64<0x259c84cba6426349, 0xffffffffffffffff, 0x0000000000000000, 1, 1>(0x75d4b74f024eceea); // CRC-64/MS
check_fast_and_slow_64<0x42f0e1eba9ea3693, 0xffffffffffffffff, 0xffffffffffffffff, 0, 0>(0x62ec59e3f1a4f00a); // CRC-64/WE
check_fast_and_slow_64<0x42f0e1eba9ea3693, 0xffffffffffffffff, 0xffffffffffffffff, 1, 1>(0x995dc9bbdf1939fa); // CRC-64/XZ
}
|
#include <sstream>
#include "gtest/gtest.h"
#include "opennwa/Nwa.hpp"
#include "opennwa/NwaParser.hpp"
#include "Tests/unit-tests/Source/opennwa/fixtures.hpp"
#include "Tests/unit-tests/Source/opennwa/class-NWA/supporting.hpp"
using namespace opennwa;
#define NUM_ELEMENTS(array) (sizeof(array)/sizeof((array)[0]))
namespace opennwa {
void
expect_nwa_is_idempotent(Nwa const & nwa)
{
std::stringstream output;
nwa.print(output);
NwaRefPtr again_nwa = read_nwa(output);
std::stringstream again_output;
again_nwa->print(again_output);
EXPECT_EQ(nwa, *again_nwa);
EXPECT_EQ(output.str(), again_output.str());
}
TEST(opennwa$$print$and$read_nwa$, printAndread_nwaAreIdempotent)
{
Nwa const nwas[] = {
Nwa(),
AcceptsBalancedOnly().nwa,
AcceptsStrictlyUnbalancedLeft().nwa,
AcceptsPossiblyUnbalancedLeft().nwa,
AcceptsStrictlyUnbalancedRight().nwa,
AcceptsPossiblyUnbalancedRight().nwa,
AcceptsPositionallyConsistentString().nwa
};
const unsigned num_nwas = NUM_ELEMENTS(nwas);
for (unsigned nwa = 0; nwa < num_nwas; ++nwa) {
std::stringstream ss;
ss << "Testing NWA " << nwa;
SCOPED_TRACE(ss.str());
expect_nwa_is_idempotent(nwas[nwa]);
}
}
}
|
#include "widget.h"
#include <QVBoxLayout>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
le = new QLineEdit(this);
btn = new QPushButton("OK", this);
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(le);
vbox->addWidget(btn);
setLayout(vbox);
connect(btn, SIGNAL(clicked()), this, SLOT(btnPush()));
}
Widget::~Widget()
{
}
|
#include <string.h>
#include "base/base.h"
#include "mysqlengine.h"
MysqlEngine::MysqlEngine(const std::string & host, uint16_t port)
: m_Host( host ),
m_Port( port ),
m_DBHandler( NULL ){}
MysqlEngine::~MysqlEngine(){}
void MysqlEngine::selectdb(const std::string & database) {
m_Database = database;
if (m_DBHandler != NULL) {
mysql_select_db(m_DBHandler, m_Database.c_str());
}
}
void MysqlEngine::setCharsets(const std::string & charsets) {
m_Charsets = charsets;
}
void MysqlEngine::setToken(const std::string & user, const std::string & passwd) {
m_Username = user;
m_Password = passwd;
}
bool MysqlEngine::initialize() {
// 初始化句柄
m_DBHandler = mysql_init(NULL);
if (m_DBHandler == NULL) {
return false;
}
// 设置属性
bool flags = true;
int32_t timeout = 0;
// 尝试重新连接
mysql_options(m_DBHandler, MYSQL_OPT_RECONNECT, (const char *)&flags);
// 设置字符集
mysql_options(m_DBHandler, MYSQL_SET_CHARSET_NAME, m_Charsets.c_str());
// 连接超时
timeout = eMysqlEngine_ConnectTimeout;
mysql_options(m_DBHandler, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
// 读超时
timeout = eMysqlEngine_ReadTimeout;
mysql_options(m_DBHandler, MYSQL_OPT_READ_TIMEOUT, (const char *)&timeout);
// 写超时
timeout = eMysqlEngine_WriteTimeout;
mysql_options(m_DBHandler, MYSQL_OPT_WRITE_TIMEOUT, (const char *)&timeout);
// 连接MySQL服务器
if (mysql_real_connect(m_DBHandler, m_Host.c_str(), m_Username.c_str(), m_Password.c_str(), m_Database.c_str(), m_Port, NULL, 0) == NULL) {
mysql_close(m_DBHandler);
m_DBHandler = NULL;
return false;
}
return true;
}
void MysqlEngine::finalize() {
if (m_DBHandler != NULL) {
mysql_close( m_DBHandler );
m_DBHandler = NULL;
}
}
void MysqlEngine::keepalive() {
int32_t rc = 0;
rc = mysql_ping(m_DBHandler);
if (rc != 0) {
LOG_ERROR("MysqlEngine::keepalive() : Result:%d, Error:(%d,'%s') .\n", rc, mysql_errno(m_DBHandler), mysql_error(m_DBHandler));
}
}
void MysqlEngine::escape(const std::string & src, std::string & dst) {
// 重置dst长度
dst.resize(src.size() * 2 + 1);
char * to = const_cast<char *>(dst.data());
size_t len = mysql_real_escape_string(
m_DBHandler,
to, (const char *)src.data(), src.size());
dst.resize(len);
}
bool MysqlEngine::insert(const std::string & sqlcmd, uint64_t & insertid) {
int32_t rc = 0;
rc = mysql_real_query(m_DBHandler, sqlcmd.data(), sqlcmd.size());
if (rc != 0) {
LOG_ERROR("MysqlEngine::insert(SQLCMD:'%s') : Result:%d, Error:(%d,'%s') .\n",
sqlcmd.c_str(), rc, mysql_errno(m_DBHandler), mysql_error(m_DBHandler));
return false;
}
// 获取返回的自增ID
insertid = mysql_insert_id(m_DBHandler);
LOG_TRACE( "MysqlEngine::insert(SQLCMD:'%s') : InsertID:%lu .\n", sqlcmd.c_str(), insertid );
return true;
}
bool MysqlEngine::query(const std::string & sqlcmd, Results & results) {
int32_t rc = 0;
rc = mysql_real_query(m_DBHandler, sqlcmd.data(), sqlcmd.size());
if ( rc != 0 ) {
LOG_ERROR("MysqlEngine::query(SQLCMD:'%s') : Result:%d, Error:(%d,'%s') .\n",
sqlcmd.c_str(), rc, mysql_errno(m_DBHandler), mysql_error(m_DBHandler));
return false;
}
MYSQL_RES * result = mysql_store_result(m_DBHandler);
if ( result == NULL ) {
LOG_ERROR("MysqlEngine::query(SQLCMD:'%s') : Store Result Failed .\n", sqlcmd.c_str());
return false;
}
MYSQL_ROW row;
uint32_t nfields = mysql_num_fields( result );
while ((row = mysql_fetch_row(result)) != NULL) {
Result tmpresult;
uint64_t * lengths = mysql_fetch_lengths(result);
for ( uint32_t i = 0; i < nfields; ++i ) {
tmpresult.push_back(std::string(row[i], lengths[i]));
}
results.push_back(tmpresult);
}
mysql_free_result(result);
LOG_TRACE("MysqlEngine::query(SQLCMD:'%s') : ResultCount:%lu .\n", sqlcmd.c_str(), results.size());
return true;
}
bool MysqlEngine::update(const std::string & sqlcmd, uint32_t & naffected) {
int32_t rc = 0;
rc = mysql_real_query(m_DBHandler, sqlcmd.data(), sqlcmd.size());
if (rc != 0) {
LOG_ERROR("MysqlEngine::update(SQLCMD:'%s') : Result:%d, Error:(%d,'%s') .\n",
sqlcmd.c_str(), rc, mysql_errno(m_DBHandler), mysql_error(m_DBHandler));
return false;
}
// 获取影响的行数
naffected = mysql_affected_rows(m_DBHandler);
LOG_TRACE("MysqlEngine::update(SQLCMD:'%s') : AffectedRows:%u .\n", sqlcmd.c_str(), naffected);
return true;
}
bool MysqlEngine::remove(const std::string & sqlcmd, uint32_t & naffected) {
int32_t rc = 0;
rc = mysql_real_query( m_DBHandler, sqlcmd.data(), sqlcmd.size() );
if ( rc != 0 ) {
LOG_ERROR("MysqlEngine::remove(SQLCMD:'%s') : Result:%d, Error:(%d,'%s') .\n",
sqlcmd.c_str(), rc, mysql_errno(m_DBHandler), mysql_error(m_DBHandler));
return false;
}
// 获取影响的行数
naffected = mysql_affected_rows(m_DBHandler);
LOG_TRACE("MysqlEngine::remove(SQLCMD:'%s') : AffectedRows:%u .\n", sqlcmd.c_str(), naffected);
return true;
}
|
#include "global.h"
int main() {
init();
parse();
return 0;
}
|
// 4.13.1View.cpp: CMy4131View 类的实现
//
#include "pch.h"
#include "framework.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义,并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "4.13.1.h"
#endif
#include "4.13.1Doc.h"
#include "4.13.1View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMy4131View
IMPLEMENT_DYNCREATE(CMy4131View, CView)
BEGIN_MESSAGE_MAP(CMy4131View, CView)
ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()
// CMy4131View 构造/析构
CMy4131View::CMy4131View() noexcept
{
// TODO: 在此处添加构造代码
rect.SetRect(200, 300, 500, 500);
}
CMy4131View::~CMy4131View()
{
}
BOOL CMy4131View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return CView::PreCreateWindow(cs);
}
// CMy4131View 绘图
void CMy4131View::OnDraw(CDC* pDC)
{
CMy4131Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
pDC->Rectangle(rect);
}
// CMy4131View 诊断
#ifdef _DEBUG
void CMy4131View::AssertValid() const
{
CView::AssertValid();
}
void CMy4131View::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CMy4131Doc* CMy4131View::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMy4131Doc)));
return (CMy4131Doc*)m_pDocument;
}
#endif //_DEBUG
// CMy4131View 消息处理程序
void CMy4131View::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CView::OnMouseMove(nFlags, point);
if (nFlags)
{
rect.top = point.y-100;
rect.bottom = point.y + 100;
rect.left = point.x - 150;
rect.right = point.x + 150;
Invalidate();
}
}
|
// Created on: 1998-04-21
// Created by: Stephanie HUMEAU
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GeomFill_LocationDraft_HeaderFile
#define _GeomFill_LocationDraft_HeaderFile
#include <Adaptor3d_Surface.hxx>
#include <gp_Mat.hxx>
#include <gp_Dir.hxx>
#include <Standard_Real.hxx>
#include <Standard_Integer.hxx>
#include <TColgp_HArray1OfPnt2d.hxx>
#include <Standard_Boolean.hxx>
#include <GeomFill_LocationLaw.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <TColgp_Array1OfVec2d.hxx>
#include <GeomAbs_Shape.hxx>
#include <TColStd_Array1OfReal.hxx>
class GeomFill_DraftTrihedron;
DEFINE_STANDARD_HANDLE(GeomFill_LocationDraft, GeomFill_LocationLaw)
class GeomFill_LocationDraft : public GeomFill_LocationLaw
{
public:
Standard_EXPORT GeomFill_LocationDraft(const gp_Dir& Direction, const Standard_Real Angle);
Standard_EXPORT void SetStopSurf (const Handle(Adaptor3d_Surface)& Surf);
Standard_EXPORT void SetAngle (const Standard_Real Angle);
//! calculation of poles on locking surfaces (the intersection between the generatrixand the surface at the cross - section points myNbPts)
//! @return Standard_True in case if execution end correctly
Standard_EXPORT virtual Standard_Boolean SetCurve (const Handle(Adaptor3d_Curve)& C) Standard_OVERRIDE;
Standard_EXPORT virtual const Handle(Adaptor3d_Curve)& GetCurve() const Standard_OVERRIDE;
Standard_EXPORT virtual void SetTrsf (const gp_Mat& Transfo) Standard_OVERRIDE;
Standard_EXPORT virtual Handle(GeomFill_LocationLaw) Copy() const Standard_OVERRIDE;
//! compute Location
Standard_EXPORT virtual Standard_Boolean D0 (const Standard_Real Param, gp_Mat& M, gp_Vec& V) Standard_OVERRIDE;
//! compute Location and 2d points
Standard_EXPORT virtual Standard_Boolean D0 (const Standard_Real Param, gp_Mat& M, gp_Vec& V, TColgp_Array1OfPnt2d& Poles2d) Standard_OVERRIDE;
//! compute location 2d points and associated
//! first derivatives.
//! Warning : It used only for C1 or C2 approximation
Standard_EXPORT virtual Standard_Boolean D1 (const Standard_Real Param, gp_Mat& M, gp_Vec& V, gp_Mat& DM, gp_Vec& DV, TColgp_Array1OfPnt2d& Poles2d, TColgp_Array1OfVec2d& DPoles2d) Standard_OVERRIDE;
//! compute location 2d points and associated
//! first and seconde derivatives.
//! Warning : It used only for C2 approximation
Standard_EXPORT virtual Standard_Boolean D2 (const Standard_Real Param, gp_Mat& M, gp_Vec& V, gp_Mat& DM, gp_Vec& DV, gp_Mat& D2M, gp_Vec& D2V, TColgp_Array1OfPnt2d& Poles2d, TColgp_Array1OfVec2d& DPoles2d, TColgp_Array1OfVec2d& D2Poles2d) Standard_OVERRIDE;
//! Say if the first restriction is defined in this class.
//! If it is true the first element of poles array in
//! D0,D1,D2... Correspond to this restriction.
//! Returns Standard_False (default implementation)
Standard_EXPORT virtual Standard_Boolean HasFirstRestriction() const Standard_OVERRIDE;
//! Say if the last restriction is defined in this class.
//! If it is true the last element of poles array in
//! D0,D1,D2... Correspond to this restriction.
//! Returns Standard_False (default implementation)
Standard_EXPORT virtual Standard_Boolean HasLastRestriction() const Standard_OVERRIDE;
//! Give the number of trace (Curves 2d which are not restriction)
//! Returns 1 (default implementation)
Standard_EXPORT virtual Standard_Integer TraceNumber() const Standard_OVERRIDE;
//! Returns the number of intervals for continuity
//! <S>.
//! May be one if Continuity(me) >= <S>
Standard_EXPORT virtual Standard_Integer NbIntervals (const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Stores in <T> the parameters bounding the intervals
//! of continuity <S>.
//!
//! The array must provide enough room to accommodate
//! for the parameters. i.e. T.Length() > NbIntervals()
Standard_EXPORT virtual void Intervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Sets the bounds of the parametric interval on
//! the function
//! This determines the derivatives in these values if the
//! function is not Cn.
Standard_EXPORT virtual void SetInterval (const Standard_Real First, const Standard_Real Last) Standard_OVERRIDE;
//! Gets the bounds of the parametric interval on
//! the function
Standard_EXPORT virtual void GetInterval (Standard_Real& First, Standard_Real& Last) const Standard_OVERRIDE;
//! Gets the bounds of the function parametric domain.
//! Warning: This domain it is not modified by the
//! SetValue method
Standard_EXPORT virtual void GetDomain (Standard_Real& First, Standard_Real& Last) const Standard_OVERRIDE;
//! Returns the resolutions in the sub-space 2d <Index>
//! This information is usfull to find an good tolerance in
//! 2d approximation.
//! Warning: Used only if Nb2dCurve > 0
Standard_EXPORT virtual void Resolution (const Standard_Integer Index, const Standard_Real Tol, Standard_Real& TolU, Standard_Real& TolV) const Standard_OVERRIDE;
//! Get the maximum Norm of the matrix-location part. It
//! is usful to find an good Tolerance to approx M(t).
Standard_EXPORT virtual Standard_Real GetMaximalNorm() Standard_OVERRIDE;
//! Get average value of M(t) and V(t) it is usfull to
//! make fast approximation of rational surfaces.
Standard_EXPORT virtual void GetAverageLaw (gp_Mat& AM, gp_Vec& AV) Standard_OVERRIDE;
//! Say if the Location Law, is an translation of Location
//! The default implementation is " returns False ".
Standard_EXPORT virtual Standard_Boolean IsTranslation (Standard_Real& Error) const Standard_OVERRIDE;
//! Say if the Location Law, is a rotation of Location
//! The default implementation is " returns False ".
Standard_EXPORT virtual Standard_Boolean IsRotation (Standard_Real& Error) const Standard_OVERRIDE;
Standard_EXPORT virtual void Rotation (gp_Pnt& Center) const Standard_OVERRIDE;
//! Say if the generatrice interset the surface
Standard_EXPORT Standard_Boolean IsIntersec() const;
Standard_EXPORT gp_Dir Direction() const;
DEFINE_STANDARD_RTTIEXT(GeomFill_LocationDraft,GeomFill_LocationLaw)
protected:
Handle(TColgp_HArray1OfPnt2d) myPoles2d;
private:
Standard_EXPORT void Prepare();
gp_Mat Trans;
Handle(GeomFill_DraftTrihedron) myLaw;
Handle(Adaptor3d_Surface) mySurf;
Handle(Adaptor3d_Curve) myCurve;
Handle(Adaptor3d_Curve) myTrimmed;
gp_Dir myDir;
Standard_Real myAngle;
Standard_Integer myNbPts;
Standard_Boolean Intersec;
Standard_Boolean WithTrans;
};
#endif // _GeomFill_LocationDraft_HeaderFile
|
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <cellogram/common.h>
#include <cellogram/point_source_detection.h>
#include <Eigen/Dense>
#include <vector>
////////////////////////////////////////////////////////////////////////////////
namespace cellogram {
class Mesh {
public:
Mesh() { }
Eigen::MatrixXd detected; // detected (unmoved) point positions
DetectionParams params; // parameters of detected
Eigen::MatrixXd moved; // manually moved point from detected positions
Eigen::MatrixXd points; // relaxed point positions
Eigen::VectorXi boundary; // list of vertices on the boundary
Eigen::MatrixXi triangles; // triangular mesh
std::vector<std::vector<int>> adj; // adjacency list of triangular mesh
std::vector<std::vector<int>> vertex_to_tri;
Eigen::Matrix<bool, Eigen::Dynamic, 1> solved_vertex;
Eigen::VectorXi vertex_status_fixed;
Eigen::VectorXi added_by_untangler;
Eigen::MatrixXd deleted_by_untangler;
// bool load(const std::string &path);
bool load(const nlohmann::json &data);
void relax_with_lloyd(const int lloyd_iterations, const Eigen::MatrixXd &hull_vertices, const Eigen::MatrixXi &hull_faces, const bool fix_regular_regions);
void vertex_degree(Eigen::VectorXi °ree);
void detect_vertices(const Eigen::MatrixXd &V, const DetectionParams ¶ms);
void delete_vertex(const int index, bool recompute_triangulation = true);
void add_vertex(Eigen::Vector3d &new_point, bool reset = true);
void local_update(Eigen::VectorXi &local2global, Eigen::MatrixXd &new_points, Eigen::MatrixXi &new_triangles, Eigen::VectorXi & old_triangles);
void local_update(Eigen::VectorXi & local2global, const int global_to_remove, Eigen::MatrixXi & new_triangles);
void update_triangles_from_split(const Eigen::VectorXi & t_old, const Eigen::MatrixXi & t1, const Eigen::MatrixXi & t2);
void mark_vertex_as_solved(const Eigen::VectorXi & region_interior);
void get_physical_bounding_box(double scaling, Eigen::Vector2d &min, Eigen::Vector2d &max) const;
// Return a triangle mesh embedded in the physical bounding box of the input mesh,
// where each point is associated a scalar field = norm of the points displacements
void get_background_mesh(double scaling, Eigen::MatrixXd &V, Eigen::MatrixXi &F, Eigen::VectorXd &S, double padding = 0) const;
void final_relax(const Eigen::VectorXi & expanded_boundary);
void generate_vertex_to_tri();
void reset();
bool untangle();
void clear();
// void save(const std::string &path);
void save(nlohmann::json &data);
private:
void compute_triangulation();
};
} // namespace cellogram
|
#include<iostream>
using namespace std;
class Terms
{
public:
int coeff;
int exp;
};
class Poly
{
private:
int n;
Terms *t;
public:
Poly(int n)
{
this->n = n;
t = new Terms[n];
}
~Poly(){
delete [] t;
}
Poly operator+(Poly &p);
friend istream & operator>>(istream &is,Poly &p);
friend ostream & operator<<(ostream &os,Poly &p);
};
istream & operator>>(istream &is,Poly &p){
cout<<"ENTER ALL TERMS"<<endl;
for(int i=0;i<p.n;i++){
cin>>p.t[i].coeff>>p.t[i].exp;
}
return is;
}
ostream & operator<<(ostream &os,Poly &p){
for(int i=0;i<p.n;i++){
cout<<p.t[i].coeff<<"x^"<<p.t[i].exp;
if(i<p.n-1){
cout<<"+";
}
}
cout<<endl;
return os;
}
Poly Poly::operator+(Poly &p){
Poly *sum = new Poly(n+p.n);
int i,j,k;
i=j=k=0;
while(i<n&&j<p.n)
{
if(t[i].exp>p.t[j].exp)
{
sum->t[k++] = t[i++];
}
else if(t[i].exp<p.t[j].exp)
{
sum->t[k++] = p.t[j++];
}
else
{
sum->t[k] = t[i];
sum->t[k++].coeff = t[i++].coeff+p.t[j++].coeff;
}
}
for(;i<n;i++)
{
sum->t[k++] = t[i];
}
for(;j<n;j++)
{
sum->t[k++] = p.t[j];
}
sum->n = k;
return *sum;
}
int main()
{
Poly p1(4),p2(4);
cin>>p1;
cin>>p2;
cout<<" FIRST EXPRESSION IS::"<<endl;
cout<<p1;
cout<<" SECOND EXPRESSION IS::"<<endl;
cout<<p2;
Poly sum = p1+p2;
cout<<" FINAL EXPRESSION IS::"<<endl;
cout<<sum;
return 0;
}
|
#include <iostream>
#include "Connector.h"
#include "Keyboard.h"
namespace Control {
const short default_axis_1_key_up = KEY_LEFT;
const short default_axis_1_key_down = KEY_RIGHT;
const short default_axis_2_key_up = KEY_UP;
const short default_axis_2_key_down = KEY_DOWN;
const short default_axis_3_key_up = KEY_Q;
const short default_axis_3_key_down = KEY_E;
const short default_movement_left_key = KEY_A;
const short default_movement_right_key = KEY_D;
const short default_movement_forward_key = KEY_W;
const short default_movement_backward_key = KEY_S;
const short movement_stop = 0;
const short movement_forward = 1;
const short movement_backward = 2;
const short movement_left = 4;
const short movement_right = 8;
const short movement_left_forward = 5;
const short movement_right_forward = 9;
const short movement_left_backward = 6;
const short movement_right_backward = 10;
const int movement_frame_size = 3;
struct movement_control{
int right;
int left;
};
struct manipulator_control{
int axis_1;
int axis_2;
int axis_3;
};
class Controler{
public:
short movement_left_key = default_movement_left_key;
short movement_right_key = default_movement_right_key;
short movement_forward_key = default_movement_forward_key;
short movement_backward_key = default_movement_backward_key;
short axis_1_key_up = default_axis_1_key_up;
short axis_1_key_down = default_axis_1_key_down;
short axis_2_key_up = default_axis_2_key_up;
short axis_2_key_down = default_axis_2_key_down;
short axis_3_key_up = default_axis_3_key_up;
short axis_3_key_down = default_axis_3_key_down;
private:
ET_Connection::Connector* connector;
Keyboard_State keyboard;
void async_remote_control(void);
void calculate_movement_control(movement_control* controls, short keys);
void send_robot_movement_frame(movement_control controls);
public:
Controler();
Controler(ET_Connection::Connector* connector);
~Controler();
void Control();
};
}
|
// Created on: 1993-01-11
// Created by: CKY / Contract Toubro-Larsen ( Arun MENON )
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESAppli_DrilledHole_HeaderFile
#define _IGESAppli_DrilledHole_HeaderFile
#include <Standard.hxx>
#include <Standard_Integer.hxx>
#include <Standard_Real.hxx>
#include <IGESData_IGESEntity.hxx>
class IGESAppli_DrilledHole;
DEFINE_STANDARD_HANDLE(IGESAppli_DrilledHole, IGESData_IGESEntity)
//! defines DrilledHole, Type <406> Form <6>
//! in package IGESAppli
//! Identifies an entity representing a drilled hole
//! through a printed circuit board.
class IGESAppli_DrilledHole : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESAppli_DrilledHole();
//! This method is used to set the fields of the class
//! DrilledHole
//! - nbPropVal : Number of property values = 5
//! - aSize : Drill diameter size
//! - anotherSize : Finish diameter size
//! - aPlating : Plating indication flag
//! False = not plating
//! True = is plating
//! - aLayer : Lower numbered layer
//! - anotherLayer : Higher numbered layer
Standard_EXPORT void Init (const Standard_Integer nbPropVal, const Standard_Real aSize, const Standard_Real anotherSize, const Standard_Integer aPlating, const Standard_Integer aLayer, const Standard_Integer anotherLayer);
//! is always 5
Standard_EXPORT Standard_Integer NbPropertyValues() const;
//! returns the drill diameter size
Standard_EXPORT Standard_Real DrillDiaSize() const;
//! returns the finish diameter size
Standard_EXPORT Standard_Real FinishDiaSize() const;
//! Returns Plating Status :
//! False = not plating / True = is plating
Standard_EXPORT Standard_Boolean IsPlating() const;
//! returns the lower numbered layer
Standard_EXPORT Standard_Integer NbLowerLayer() const;
//! returns the higher numbered layer
Standard_EXPORT Standard_Integer NbHigherLayer() const;
DEFINE_STANDARD_RTTIEXT(IGESAppli_DrilledHole,IGESData_IGESEntity)
protected:
private:
Standard_Integer theNbPropertyValues;
Standard_Real theDrillDiaSize;
Standard_Real theFinishDiaSize;
Standard_Integer thePlatingFlag;
Standard_Integer theNbLowerLayer;
Standard_Integer theNbHigherLayer;
};
#endif // _IGESAppli_DrilledHole_HeaderFile
|
#include "hardware.h"
#include "util.h"
#include <string>
#include <fstream>
#include <stdlib.h>
#include <unistd.h>
#include <linux/kernel.h>
#include <sys/sysinfo.h>
#include <sys/utsname.h>
namespace libzinlidac {
// throws a `SysconfError` both if the implementation does not impose a limit, and in case of an error
unsigned long get_cpus_number() {
// https://www.gnu.org/software/libc/manual/html_node/Sysconf.html
return hardware::get_result_using_sysconf(_SC_NPROCESSORS_ONLN, "_SC_NPROCESSORS_ONLN");
}
// throws a `SysconfError` both if the implementation does not impose a limit, and in case of an error
unsigned long get_cpu_clock_ticks_per_time() {
// https://www.gnu.org/software/libc/manual/html_node/Sysconf.html
return hardware::get_result_using_sysconf(_SC_NPROCESSORS_ONLN, "_SC_NPROCESSORS_ONLN");
}
// throws a `SysconfError` both if the implementation does not impose a limit, and in case of an error
unsigned long get_word_bit() {
// https://www.gnu.org/software/libc/manual/html_node/Sysconf.html
return hardware::get_result_using_sysconf(_SC_NPROCESSORS_ONLN, "_SC_NPROCESSORS_ONLN");
}
long get_boot_time() noexcept {
struct sysinfo info;
// return -1 if `&info` is not a valid address, which is impossible
sysinfo(&info);
long boot_time = info.uptime;
return boot_time;
}
// throws a `FileReadError` if cannot open /proc/cpuinfo
std::string get_cpuinfo() {
auto cpuinfo_file = std::ifstream("/proc/cpuinfo");
if (cpuinfo_file.is_open()) {
// see https://stackoverflow.com/a/2912614/10005095
return std::string((std::istreambuf_iterator<char>(cpuinfo_file)), (std::istreambuf_iterator<char>()));
} else {
throw hardware::FileReadError("/proc/cpuinfo");
}
}
// throws a `FileReadError` if cannot open /proc/stat
std::string get_cpu_stat() {
auto cpustat_file = std::ifstream("/proc/stat");
if (cpustat_file.is_open()) {
// see https://stackoverflow.com/a/2912614/10005095
return std::string((std::istreambuf_iterator<char>(cpustat_file)), (std::istreambuf_iterator<char>()));
} else {
throw hardware::FileReadError("/proc/stat");
}
}
std::string get_hardware_type() noexcept {
struct utsname unix_name;
// No errors are defined
uname(&unix_name);
return std::string(unix_name.machine);
}
}
|
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
int main()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int t;
std::cin >> t;
for (int i = 0; i < t; ++i)
{
int m, n, k;
std::cin >> m >> n >> k;
std::vector<std::vector<int>> map(n, std::vector<int>(m, 0));
std::vector<std::vector<bool>> check(n, std::vector<bool>(m, false));
for (int j = 0; j < k; ++j)
{
int x, y;
std::cin >> x >> y;
map[y][x] = 1;
}
int ans{};
for (int y = 0; y < n; ++y)
{
for (int x = 0; x < m; ++x)
{
if (map[y][x] != 1 || check[y][x])
{
continue;
}
++ans;
std::queue<std::pair<int, int>> q;
q.emplace(x, y);
check[y][x] = true;
constexpr int dx[] = { -1, 0, 1, 0 };
constexpr int dy[] = { 0, -1, 0, 1 };
while (!q.empty())
{
auto [x, y] = q.front();
q.pop();
for (int p = 0; p < 4; ++p)
{
int nx = x + dx[p];
int ny = y + dy[p];
if (nx >= 0 && ny >= 0 && nx < m && ny < n &&
map[ny][nx] == 1 && !check[ny][nx])
{
q.emplace(nx, ny);
check[ny][nx] = true;
}
}
}
}
}
std::cout << ans << '\n';
}
return 0;
}
|
/*
Petar 'PetarV' Velickovic
Algorithm: Quickselect
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#define MAX_N 1000001
using namespace std;
typedef long long lld;
int n, k;
int niz[MAX_N];
//Quickselect algoritam za nalazenje k-tog elementa u nizu
//Slozenost: O(n)
int qselect(int left, int right, int k)
{
if (left < right)
{
int pivotIndex = left;
int pivot = niz[(left+right)/2];
swap(niz[(left+right)/2], niz[right]);
for (int i=left;i<right;i++)
{
if (niz[i] < pivot)
{
swap(niz[pivotIndex], niz[i]);
pivotIndex++;
}
}
swap(niz[pivotIndex], niz[right]);
if (pivotIndex == k) return niz[pivotIndex];
else if (k < pivotIndex) return qselect(left, pivotIndex-1, k);
else return qselect(pivotIndex+1, right, k);
}
else return niz[left];
}
int main()
{
n = 5, k = 3;
niz[0] = 4;
niz[1] = 2;
niz[2] = 5;
niz[3] = 1;
niz[4] = 3;
printf("%d\n",qselect(0, n-1, k));
return 0;
}
|
#pragma once
#include "EGLRenderSystem.h"
#include <sstream>
#include "FrameListener.h"
#include "Timer.h"
#include "Logger.h"
#include <thread>
#include <chrono>
#include "App_SSS.h"
#include "Config.h"
using namespace std;
class PCFrameWork
{
public:
PCFrameWork()
{
rendersys = NULL;
}
void Init() {
Config::instance().Load();
renderer = new app_SSS;
createEGLDisplay();
renderer->render = rendersys;
renderer->Init();
}
void Loop() {
Go();
}
virtual void createEGLDisplay()
{
Logger::WriteLog("Create EGLDisplay()");
if (NULL == rendersys)
{
auto eglrender = new EGLRenderSystem;
rendersys = eglrender;
int w = 1024, h = 1024;
if (Config::instance().valid) {
w = Config::instance().width;
h = Config::instance().height;
}
rendersys->SetWandH(w, h);
}
rendersys->Initialize();
rendersys->GetWandH(renderer->w, renderer->h);
}
void Go()
{
MSG msg;
while (true)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
break;
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
auto start = std::chrono::steady_clock().now();
renderer->Render();
//LogCameraPosition();
//calc fps
static int frame = 0;
static auto elpased = chrono::nanoseconds(0);
elpased += std::chrono::steady_clock().now() - start;
frame++;
if (chrono::duration_cast<std::chrono::milliseconds>(elpased).count() > 1000) {
elpased = chrono::nanoseconds(0);
cout << "fps_" << frame << endl;
//Logger::WriteAndroidInfoLog("fps _ %d", frame);
frame = 0;
}
renderer->sysentry->getRenderSystem()->BufferSwap();
//calculatedFPS();
////limit fps
//int max_fps = 30;
//float frametime = 1000.0 / max_fps;
//auto end = std::chrono::steady_clock().now();
//auto delta = end - start;
//auto ms = chrono::duration_cast<std::chrono::milliseconds>(delta);
//auto sleeptime = frametime - ms.count();
//if (sleeptime > 0)
// std::this_thread::sleep_for(std::chrono::milliseconds(int(sleeptime)));
}
}
}
void term_display()
{
Logger::WriteLog(" app term display");
if (NULL != rendersys)
{
rendersys->term_display();
Logger::WriteLog(" egl context release");
}
}
void destroy()
{
term_display();
}
virtual void calculatedFPS()
{
static int frame = 0;
frame++;
double elapsed = timer.elapsed();
if (elapsed > 1000.0)
{
Logger::WriteLog("FPS %d", frame);
timer.restart();
frame = 0;
}
}
~PCFrameWork()
{
destroy();
Logger::close();
}
public:
Timer timer;
RenderSystem * rendersys;
app_SSS* renderer;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/doc/imageprogresshandler.h"
#include "modules/hardcore/mh/messages.h"
#include "modules/hardcore/mh/mh.h"
#ifdef ASYNC_IMAGE_DECODERS_EMULATION
#include "modules/img/src/imagemanagerimp.h"
#endif // ASYNC_IMAGE_DECODERS_EMULATION
ImageProgressHandler* ImageProgressHandler::Create()
{
ImageProgressHandler* handler = OP_NEW(ImageProgressHandler, ());
if (handler != NULL)
{
if (OpStatus::IsError(g_main_message_handler->SetCallBack(handler, MSG_IMG_CONTINUE_DECODING, 0)))
{
OP_DELETE(handler);
return NULL;
}
}
return handler;
}
ImageProgressHandler::~ImageProgressHandler()
{
g_main_message_handler->UnsetCallBacks(this);
}
void ImageProgressHandler::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
m_pending_progress = FALSE;
OP_ASSERT(msg == MSG_IMG_CONTINUE_DECODING);
if (msg == MSG_IMG_CONTINUE_DECODING
#ifdef ASYNC_IMAGE_DECODERS_EMULATION
&& par1 == 0
#endif // ASYNC_IMAGE_DECODERS_EMULATION
)
{
imgManager->Progress();
}
#ifdef ASYNC_IMAGE_DECODERS_EMULATION
else if (msg == MSG_IMG_CONTINUE_DECODING && par1 == 1)
{
((ImageManagerImp*)imgManager)->MoreBufferedData();
}
else if (msg == MSG_IMG_CONTINUE_DECODING && par1 == 2)
{
((ImageManagerImp*)imgManager)->MoreDeletedDecoders();
}
#endif // ASYNC_IMAGE_DECODERS_EMULATION
}
void ImageProgressHandler::OnProgress()
{
if (!m_pending_progress)
{
m_pending_progress = TRUE;
g_main_message_handler->PostMessage(MSG_IMG_CONTINUE_DECODING, 0, 0);
}
}
#ifdef ASYNC_IMAGE_DECODERS_EMULATION
void ImageProgressHandler::OnMoreBufferedData()
{
g_main_message_handler->PostMessage(MSG_IMG_CONTINUE_DECODING, 1, 0);
}
void ImageProgressHandler::OnMoreDeletedDecoders()
{
g_main_message_handler->PostMessage(MSG_IMG_CONTINUE_DECODING, 2, 0);
}
#endif // ASYNC_IMAGE_DECODERS_EMULATION
ImageProgressHandler::ImageProgressHandler()
: m_pending_progress(FALSE)
{
}
|
#include <stdio.h>
void Print_Factorial ( const int N );
int main()
{
int N;
scanf("%d", &N);
Print_Factorial(N);
return 0;
}
void Print_Factorial ( const int N ){
if ( N < 0 ) {
printf("0\n");
return ;
}
unsigned long long res = 1;
for(unsigned int i = 2; i < N+1; i++){
res *= i;
}
printf("%lld\n", res);
}
|
#include "Team.h"
#include "BaseEntity.h"
#include "GamePlay.h"
#include "Timer.h"
int Team::m_iNextValidId = 0;
Team::Team() :
m_iCurrentDmgUpgrade(0),
m_iCurrentHpUpgrade(0),
m_fFactorUpDmg(/*theTuning.GetFloat("Tower_FactorUpgradeDamage")*/0.4f),
m_fFactorUpHp(/*theTuning.GetFloat("Tower_FactorUpgradeHealth")*/0.2f),
m_iUpDmgCost(/*theTuning.GetFloat("Tower_UpgradeDamageCost")*/1000),
m_iUpHpCost(/*theTuning.GetFloat("Tower_UpgradeHealthCost")*/1000),
m_iMineral(/*theTuning.GetInt("Team_InitMineral")*/ 500),
m_fFactorMineral(0.2f),
m_iTowerMinCost(500),
m_fTimeBuiding(2),
m_fNnextTimeBulding(0),
m_fNextMineralAvailable(Clock->getCurrentTime()),
m_fAccumulateMin(0),
m_fRateMineralEarned(0.5)
{
SetID(m_iNextValidId);
}
//----------------------------- SetID -----------------------------------------
//
// this must be called within each constructor to make sure the ID is set
// correctly. It verifies that the value passed to the method is greater
// or equal to the next valid ID, before setting the ID and incrementing
// the next valid ID
//-----------------------------------------------------------------------------
void Team::SetID(int val)
{
//make sure the val is equal to or greater than the next available ID
//assert ( (val >= m_iNextValidID) && "<BaseGameTeam::SetID>: invalid ID");
if (val < m_iNextValidId)
return;
m_IdGroup = val;
m_iNextValidId = m_IdGroup + 1;
}
//------------------------- GetTeamFromID -----------------------------------
//-----------------------------------------------------------------------------
BaseEntity* Team::GetEntityFromID(int id)const
{
//find the Team
TeamMap::const_iterator ent = m_TeamMap.find(id);
//assert that the Team is a member of the map
//assert ( (ent != m_TeamMap.end()) && "<TeamManager::GetTeamFromID>: invalid ID");
return ent->second;
}
//--------------------------- RemoveTeam ------------------------------------
//-----------------------------------------------------------------------------
void Team::RemoveEntity(BaseEntity* pTeam)
{
m_TeamMap.erase(m_TeamMap.find(pTeam->ID()));
}
//---------------------------- RegisterTeam ---------------------------------
//-----------------------------------------------------------------------------
void Team::RegisterEntity(BaseEntity* NewTeam)
{
NewTeam->setGroup(m_IdGroup);
m_TeamMap.insert(std::make_pair(NewTeam->ID(), NewTeam));
}
void Team::updateMineralEarned(int mineral)
{
// find all tower
m_fNextMineralAvailable = Clock->getCurrentTime() + 1.0 / m_fRateMineralEarned;
m_iMineral += mineral;
}
void Team::updateMineralEarned()
{
// find all tower
m_fNextMineralAvailable = Clock->getCurrentTime() + 1.0 / m_fRateMineralEarned;
m_iMineral += m_fAccumulateMin;
}
bool Team::isReadyForIncreaseMineral()
{
if (Clock->getCurrentTime() < m_fNextMineralAvailable)
return false;
//find all tower
return true;
}
//---------------------------UpgradeHpCost---------------------
// this function is used to determine the new value
// of next level upgrade's health
//-------------------------------------------------------------
void Team::ComputeUpgradeHpCost()
{
m_iUpHpCost += (int)(m_iUpHpCost*m_fFactorUpHp);
}
//---------------------------UpgradeDmgCost---------------------
// this function is used to determine the new value
// of next level upgrade's damage
//-------------------------------------------------------------
void Team::ComputeUpgradeDmgCost()
{
m_iUpDmgCost += (int)(m_iUpDmgCost*m_fFactorUpDmg);
}
void Team::setMineral(int m){ m_iMineral = m; }
// incrrase the mineral
void Team::IncreaseMinerals(int received){ m_iMineral += received; }
void Team::IncreaseMinerals(){ m_iMineral += 100; }
void Team::ReduceMinerals(int val){ m_iMineral -= val; }
void Team::IncreaseLevelDmg()
{
m_iCurrentDmgUpgrade++;
}
void Team::IncreaseLevelHp()
{
m_iCurrentHpUpgrade++;
}
int Team::GetLevelDamageUpg()
{
return m_iCurrentDmgUpgrade;
}
int Team::GetLevelHealthUpg()
{
return m_iCurrentHpUpgrade;
}
int Team::GetUpgradeHealthCost()
{
return m_iUpHpCost;
}
int Team::GetUpgradeDmgCost()
{
return m_iUpDmgCost;
}
int Team::Mineral()
{
return m_iMineral;
}
void Team::Reset() {
m_TeamMap.clear();
}
int Team::ID() const
{
return m_IdGroup;
}
|
/*******************************************************************\
Module:
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#include <std_types.h>
#include "c_types.h"
#include "config.h"
/*******************************************************************\
Function: index_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet index_type()
{
// same as signed size type
return signedbv_typet(config.ansi_c.pointer_width);
}
/*******************************************************************\
Function: enum_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet enum_type()
{
return signedbv_typet(config.ansi_c.int_width);
}
/*******************************************************************\
Function: int_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet int_type()
{
typet result=signedbv_typet(config.ansi_c.int_width);
result.set(ID_C_c_type, ID_int);
return result;
}
/*******************************************************************\
Function: uint_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet uint_type()
{
typet result=unsignedbv_typet(config.ansi_c.int_width);
result.set(ID_C_c_type, ID_unsigned_int);
return result;
}
/*******************************************************************\
Function: size_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet size_type()
{
return unsignedbv_typet(config.ansi_c.pointer_width);
}
/*******************************************************************\
Function: signed_size_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet signed_size_type()
{
return signedbv_typet(config.ansi_c.pointer_width);
}
/*******************************************************************\
Function: long_int_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet long_int_type()
{
typet result=signedbv_typet(config.ansi_c.long_int_width);
result.set(ID_C_c_type, ID_signed_long_int);
return result;
}
/*******************************************************************\
Function: long_long_int_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet long_long_int_type()
{
typet result=signedbv_typet(config.ansi_c.long_long_int_width);
result.set(ID_C_c_type, ID_signed_long_long_int);
return result;
}
/*******************************************************************\
Function: long_uint_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet long_uint_type()
{
typet result=unsignedbv_typet(config.ansi_c.long_int_width);
result.set(ID_C_c_type, ID_unsigned_long_int);
return result;
}
/*******************************************************************\
Function: long_long_uint_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet long_long_uint_type()
{
typet result=unsignedbv_typet(config.ansi_c.long_long_int_width);
result.set(ID_C_c_type, ID_unsigned_long_long_int);
return result;
}
/*******************************************************************\
Function: c_bool_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet c_bool_type()
{
typet result=unsignedbv_typet(config.ansi_c.bool_width);
result.set(ID_C_c_type, ID_bool);
return result;
}
/*******************************************************************\
Function: char_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet char_type()
{
typet result;
if(config.ansi_c.char_is_unsigned)
result=unsignedbv_typet(config.ansi_c.char_width);
else
result=signedbv_typet(config.ansi_c.char_width);
result.set(ID_C_c_type, ID_char);
return result;
}
/*******************************************************************\
Function: uchar_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet uchar_type()
{
return unsignedbv_typet(config.ansi_c.char_width);
}
/*******************************************************************\
Function: wchar_t_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet wchar_t_type()
{
typet result;
if(config.ansi_c.wchar_t_is_unsigned)
result=unsignedbv_typet(config.ansi_c.wchar_t_width);
else
result=signedbv_typet(config.ansi_c.wchar_t_width);
result.set(ID_C_c_type, ID_wchar_t);
return result;
}
/*******************************************************************\
Function: char16_t_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet char16_t_type()
{
typet result;
/*
if(config.ansi_c.wchar_t_is_unsigned)
result=unsignedbv_typet(config.ansi_c.wchar_t_width);
else
result=signedbv_typet(config.ansi_c.wchar_t_width);
*/
result=unsignedbv_typet(16);
//result.set(ID_C_c_type, ID_wchar_t);
return result;
}
/*******************************************************************\
Function: char32_t_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet char32_t_type()
{
typet result;
/*
if(config.ansi_c.wchar_t_is_unsigned)
result=unsignedbv_typet(config.ansi_c.wchar_t_width);
else
result=signedbv_typet(config.ansi_c.wchar_t_width);
*/
result=unsignedbv_typet(32);
//result.set(ID_C_c_type, ID_wchar_t);
return result;
}
/*******************************************************************\
Function: float_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet float_type()
{
typet result;
if(config.ansi_c.use_fixed_for_float)
{
fixedbv_typet tmp;
tmp.set_width(config.ansi_c.single_width);
tmp.set_integer_bits(config.ansi_c.single_width/2);
result=tmp;
}
else
result=ieee_float_spect::single_precision().to_type();
result.set(ID_C_c_type, ID_float);
return result;
}
/*******************************************************************\
Function: double_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet double_type()
{
typet result;
if(config.ansi_c.use_fixed_for_float)
{
fixedbv_typet tmp;
tmp.set_width(config.ansi_c.double_width);
tmp.set_integer_bits(config.ansi_c.double_width/2);
result=tmp;
}
else
result=ieee_float_spect::double_precision().to_type();
result.set(ID_C_c_type, ID_double);
return result;
}
/*******************************************************************\
Function: long_double_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet long_double_type()
{
typet result;
if(config.ansi_c.use_fixed_for_float)
{
fixedbv_typet tmp;
tmp.set_width(config.ansi_c.long_double_width);
tmp.set_integer_bits(config.ansi_c.long_double_width/2);
result=tmp;
}
else
{
if(config.ansi_c.long_double_width==128)
result=ieee_float_spect::quadruple_precision().to_type();
else if(config.ansi_c.long_double_width==64)
result=ieee_float_spect::double_precision().to_type();
else if(config.ansi_c.long_double_width==96)
result=ieee_float_spect(80, 15).to_type();
// not quite right. Intel's extended precision isn't IEEE.
else
assert(false);
}
result.set(ID_C_c_type, ID_long_double);
return result;
}
/*******************************************************************\
Function: pointer_diff_type
Inputs:
Outputs:
Purpose:
\*******************************************************************/
typet pointer_diff_type()
{
return signedbv_typet(config.ansi_c.pointer_width);
}
|
// Copyright 2021 The XLS Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "xls/codegen/block_conversion.h"
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "xls/codegen/vast.h"
#include "xls/ir/channel.h"
#include "xls/ir/function_builder.h"
#include "xls/ir/node.h"
#include "xls/ir/node_iterator.h"
#include "xls/ir/node_util.h"
#include "xls/ir/nodes.h"
#include "xls/ir/type.h"
#include "xls/ir/value_helpers.h"
#include "xls/passes/dce_pass.h"
#include "xls/passes/tuple_simplification_pass.h"
namespace xls {
namespace verilog {
namespace {
// Suffixes for ready/valid ports for streaming channels.
char kReadySuffix[] = "_rdy";
char kValidSuffix[] = "_vld";
} // namespace
absl::StatusOr<Block*> FunctionToBlock(Function* f,
absl::string_view block_name) {
Block* block = f->package()->AddBlock(
absl::make_unique<Block>(block_name, f->package()));
// A map from the nodes in 'f' to their corresponding node in the block.
absl::flat_hash_map<Node*, Node*> node_map;
// Emit the parameters first to ensure the their order is preserved in the
// block.
for (Param* param : f->params()) {
XLS_ASSIGN_OR_RETURN(
node_map[param],
block->AddInputPort(param->GetName(), param->GetType(), param->loc()));
}
for (Node* node : TopoSort(f)) {
if (node->Is<Param>()) {
continue;
}
std::vector<Node*> new_operands;
for (Node* operand : node->operands()) {
new_operands.push_back(node_map.at(operand));
}
XLS_ASSIGN_OR_RETURN(Node * block_node,
node->CloneInNewFunction(new_operands, block));
node_map[node] = block_node;
}
// TODO(meheff): 2021-03-01 Allow port names other than "out".
XLS_RETURN_IF_ERROR(
block->AddOutputPort("out", node_map.at(f->return_value())).status());
return block;
}
// Returns pipeline-stage prefixed signal name for the given node. For
// example: p3_foo.
static std::string PipelineSignalName(Node* node, int64_t stage) {
return absl::StrFormat("p%d_%s", stage, SanitizeIdentifier(node->GetName()));
}
absl::StatusOr<Block*> FunctionToPipelinedBlock(
const PipelineSchedule& schedule, Function* f,
absl::string_view block_name) {
Block* block = f->package()->AddBlock(
absl::make_unique<Block>(block_name, f->package()));
XLS_RETURN_IF_ERROR(block->AddClockPort("clk"));
// A map from the nodes in 'f' to their corresponding node in the block.
absl::flat_hash_map<Node*, Node*> node_map;
// Emit the parameters first to ensure the their order is preserved in the
// block.
for (Param* param : f->params()) {
XLS_ASSIGN_OR_RETURN(
node_map[param],
block->AddInputPort(param->GetName(), param->GetType(), param->loc()));
}
for (int64_t stage = 0; stage < schedule.length(); ++stage) {
for (Node* function_node : schedule.nodes_in_cycle(stage)) {
if (function_node->Is<Param>()) {
continue;
}
std::vector<Node*> new_operands;
for (Node* operand : function_node->operands()) {
new_operands.push_back(node_map.at(operand));
}
XLS_ASSIGN_OR_RETURN(
Node * node, function_node->CloneInNewFunction(new_operands, block));
node_map[function_node] = node;
}
// Add pipeline registers. A register is needed for each node which is
// scheduled at or before this cycle and has a use after this cycle.
for (Node* function_node : f->nodes()) {
if (schedule.cycle(function_node) > stage) {
continue;
}
auto is_live_out_of_stage = [&](Node* n) {
if (stage == schedule.length() - 1) {
return false;
}
if (n == f->return_value()) {
return true;
}
for (Node* user : n->users()) {
if (schedule.cycle(user) > stage) {
return true;
}
}
return false;
};
Node* node = node_map.at(function_node);
if (is_live_out_of_stage(function_node)) {
XLS_ASSIGN_OR_RETURN(Register * reg,
block->AddRegister(PipelineSignalName(node, stage),
node->GetType()));
XLS_RETURN_IF_ERROR(
block
->MakeNode<RegisterWrite>(node->loc(), node,
/*load_enable=*/absl::nullopt,
/*reset=*/absl::nullopt, reg->name())
.status());
XLS_ASSIGN_OR_RETURN(
node_map[function_node],
block->MakeNode<RegisterRead>(node->loc(), reg->name()));
}
}
}
// TODO(https://github.com/google/xls/issues/448): 2021-03-01 Allow port names
// other than "out".
XLS_RETURN_IF_ERROR(
block->AddOutputPort("out", node_map.at(f->return_value())).status());
return block;
}
namespace {
// Data structures holding the data and (optional) predicate nodes representing
// streaming inputs (receive over streaming channel) and streaming outputs (send
// over streaming channel) in the generated block.
struct StreamingInput {
InputPort* port;
absl::optional<Node*> predicate;
};
struct StreamingOutput {
OutputPort* port;
absl::optional<Node*> predicate;
};
struct StreamingIo {
std::vector<StreamingInput> inputs;
std::vector<StreamingOutput> outputs;
};
// Clones every node in the given proc into the given block. Some nodes are
// handled specially:
//
// * Proc token parameter becomes an operandless AfterAll operation in the
// block.
// * Proc state parameter (which must be an empty tuple) becomes a Literal
// operation in theblock.
// * Receive operations become InputPorts.
// * Send operations become OutputPorts.
//
// Returns vectors containing the InputPorts and OutputPorts created from
// Send/Receive operations of streaming channels.
//
// Example input proc:
//
// chan x_ch(bits[32], kind=streaming, flow_control=single_value, id=0, ...)
// chan y_ch(bits[32], kind=streaming, flow_control=single_value, id=1, ...)
//
// proc foo(tkn: token, st: (), init=42) {
// rcv_x: (token, bits[32]) = receive(tkn, channel_id=0)
// rcv_x_token: token = tuple_index(rcv_x, index=0)
// x: bits[32] = tuple_index(rcv_x, index=1)
// not_x: bits[32] = not(x)
// snd_y: token = send(rcv_x_token, not_x, channel_id=1)
// next (tkn, snd_y)
// }
//
// Resulting block:
//
// block (x: bits[32], y: bits[32]) {
// x: bits[32] = input_port(name=x)
// not_x: bits[32] = not(x)
// y: bits[32] = output_port(not_x, name=x)
// }
//
// Ready/valid flow control including inputs ports and output ports are added
// later.
absl::StatusOr<StreamingIo> CloneProcNodesIntoBlock(Proc* proc, Block* block) {
// Gather the inputs and outputs from streaming channels.
StreamingIo result;
// A map from the nodes in `proc` to their corresponding node in the block.
absl::flat_hash_map<Node*, Node*> node_map;
for (Node* node : TopoSort(proc)) {
// Replace token parameter with zero operand AfterAll.
if (node == proc->TokenParam()) {
XLS_ASSIGN_OR_RETURN(
node_map[node],
block->MakeNode<AfterAll>(node->loc(), std::vector<Node*>()));
continue;
}
// Replace state parameter with Literal empty tuple.
if (node == proc->StateParam()) {
XLS_ASSIGN_OR_RETURN(node_map[node], block->MakeNode<xls::Literal>(
node->loc(), Value::Tuple({})));
continue;
}
XLS_RET_CHECK(!node->Is<Param>());
// Don't clone Receive operations. Instead replace with a tuple
// containing the Receive's token operand and an InputPort operation.
if (node->Is<Receive>()) {
Receive* receive = node->As<Receive>();
XLS_ASSIGN_OR_RETURN(Channel * channel, GetChannelUsedByNode(node));
XLS_ASSIGN_OR_RETURN(
InputPort * input_port,
block->AddInputPort(channel->name(), channel->type()));
XLS_ASSIGN_OR_RETURN(
node_map[node],
block->MakeNode<Tuple>(
node->loc(),
std::vector<Node*>({node_map.at(node->operand(0)), input_port})));
if (channel->kind() == ChannelKind::kSingleValue) {
continue;
}
XLS_RET_CHECK_EQ(channel->kind(), ChannelKind::kStreaming);
XLS_RET_CHECK_EQ(down_cast<StreamingChannel*>(channel)->flow_control(),
FlowControl::kReadyValid);
StreamingInput streaming_input;
streaming_input.port = input_port;
if (receive->predicate().has_value()) {
streaming_input.predicate = node_map.at(receive->predicate().value());
}
result.inputs.push_back(streaming_input);
continue;
}
// Don't clone Send operations. Instead replace with an OutputPort
// operation in the block.
if (node->Is<Send>()) {
XLS_ASSIGN_OR_RETURN(Channel * channel, GetChannelUsedByNode(node));
Send* send = node->As<Send>();
XLS_ASSIGN_OR_RETURN(
OutputPort * output_port,
block->AddOutputPort(channel->name(), node_map.at(send->data())));
// Map the Send node to the token operand of the Send in the
// block.
node_map[node] = node_map.at(send->token());
if (channel->kind() == ChannelKind::kSingleValue) {
continue;
}
XLS_RET_CHECK_EQ(channel->kind(), ChannelKind::kStreaming);
XLS_RET_CHECK_EQ(down_cast<StreamingChannel*>(channel)->flow_control(),
FlowControl::kReadyValid);
StreamingOutput streaming_output;
streaming_output.port = output_port;
if (send->predicate().has_value()) {
streaming_output.predicate = node_map.at(send->predicate().value());
}
result.outputs.push_back(streaming_output);
continue;
}
// Clone the operation from the proc to the block as is.
std::vector<Node*> new_operands;
for (Node* operand : node->operands()) {
new_operands.push_back(node_map.at(operand));
}
XLS_ASSIGN_OR_RETURN(node_map[node],
node->CloneInNewFunction(new_operands, block));
}
return result;
}
// Adds ready/valid ports for each of the given streaming inputs/outputs. Also,
// adds logic which propagates ready and valid signals through the block.
absl::Status AddFlowControl(absl::Span<const StreamingInput> streaming_inputs,
absl::Span<const StreamingOutput> streaming_outputs,
Block* block) {
// Add a ready input port for each streaming output. Gather the ready signals
// into a vector. Ready signals from streaming outputs generated from Send
// operations are conditioned upon the optional predicate value.
std::vector<Node*> active_readys;
for (const StreamingOutput& streaming_output : streaming_outputs) {
XLS_ASSIGN_OR_RETURN(
Node * ready,
block->AddInputPort(
absl::StrFormat("%s_rdy", streaming_output.port->GetName()),
block->package()->GetBitsType(1)));
if (streaming_output.predicate.has_value()) {
// Logic for the active ready signal for a Send operation with a
// predicate `pred`.
//
// active = !pred | pred && ready
// = !pred | ready
XLS_ASSIGN_OR_RETURN(
Node * not_pred,
block->MakeNode<UnOp>(absl::nullopt,
streaming_output.predicate.value(), Op::kNot));
std::vector<Node*> operands = {not_pred, ready};
XLS_ASSIGN_OR_RETURN(
Node * active_ready,
block->MakeNode<NaryOp>(absl::nullopt, operands, Op::kOr));
active_readys.push_back(active_ready);
} else {
active_readys.push_back(ready);
}
}
// And reduce all the active ready signals. This signal is true iff all active
// outputs are ready.
Node* all_active_outputs_ready;
if (active_readys.empty()) {
XLS_ASSIGN_OR_RETURN(
all_active_outputs_ready,
block->MakeNode<xls::Literal>(absl::nullopt, Value(UBits(1, 1))));
} else {
XLS_ASSIGN_OR_RETURN(
all_active_outputs_ready,
block->MakeNode<NaryOp>(absl::nullopt, active_readys, Op::kAnd));
}
// Add a valid input port for each streaming input. Gather the valid signals
// into a vector. Valid signals from streaming inputs generated from Receive
// operations are conditioned upon the optional predicate value.
std::vector<Node*> active_valids;
for (const StreamingInput& streaming_input : streaming_inputs) {
XLS_ASSIGN_OR_RETURN(
Node * valid,
block->AddInputPort(
absl::StrFormat("%s%s", streaming_input.port->name(), kValidSuffix),
block->package()->GetBitsType(1)));
if (streaming_input.predicate.has_value()) {
// Logic for the active valid signal for a Receive operation with a
// predicate `pred`.
//
// active = !pred | pred && valid
// = !pred | valid
XLS_ASSIGN_OR_RETURN(
Node * not_pred,
block->MakeNode<UnOp>(absl::nullopt,
streaming_input.predicate.value(), Op::kNot));
std::vector<Node*> operands = {not_pred, valid};
XLS_ASSIGN_OR_RETURN(
Node * active_valid,
block->MakeNode<NaryOp>(absl::nullopt, operands, Op::kOr));
active_valids.push_back(active_valid);
} else {
active_valids.push_back(valid);
}
}
// And reduce all the active valid signals. This signal is true iff all active
// inputs are valid.
Node* all_active_inputs_valid;
if (active_valids.empty()) {
XLS_ASSIGN_OR_RETURN(
all_active_inputs_valid,
block->MakeNode<xls::Literal>(absl::nullopt, Value(UBits(1, 1))));
} else {
XLS_ASSIGN_OR_RETURN(
all_active_inputs_valid,
block->MakeNode<NaryOp>(absl::nullopt, active_valids, Op::kAnd));
}
// Make output valid output ports. A valid signal is asserted iff all active
// inputs valid signals are asserted and the predicate of the data channel (if
// any) is asserted.
for (const StreamingOutput& streaming_output : streaming_outputs) {
Node* valid;
if (streaming_output.predicate.has_value()) {
std::vector<Node*> operands = {streaming_output.predicate.value(),
all_active_inputs_valid};
XLS_ASSIGN_OR_RETURN(
valid, block->MakeNode<NaryOp>(absl::nullopt, operands, Op::kAnd));
} else {
valid = all_active_inputs_valid;
}
XLS_RETURN_IF_ERROR(
block
->AddOutputPort(
absl::StrFormat("%s_vld", streaming_output.port->GetName()),
valid)
.status());
}
// Make output ready output ports. A ready signal is asserted iff all active
// output ready signals are asserted and the predicate of the data channel (if
// any) is asserted.
for (const StreamingInput& streaming_input : streaming_inputs) {
Node* ready;
if (streaming_input.predicate.has_value()) {
std::vector<Node*> operands = {streaming_input.predicate.value(),
all_active_outputs_ready};
XLS_ASSIGN_OR_RETURN(
ready, block->MakeNode<NaryOp>(absl::nullopt, operands, Op::kAnd));
} else {
ready = all_active_outputs_ready;
}
XLS_RETURN_IF_ERROR(
block
->AddOutputPort(
absl::StrFormat("%s%s", streaming_input.port->GetName(),
kReadySuffix),
ready)
.status());
}
return absl::OkStatus();
}
// Send/receive nodes are not cloned from the proc into the block, but the
// network of tokens connecting these send/receive nodes *is* cloned. This
// function removes the token operations.
absl::Status RemoveDeadTokenNodes(Block* block) {
// Receive nodes produce a tuple of a token and a data value. In the block
// this becomes a tuple of a token and an InputPort. Run tuple simplification
// to disintangle the tuples so DCE can do its work and eliminate the token
// network.
PassResults pass_results;
XLS_RETURN_IF_ERROR(
TupleSimplificationPass()
.RunOnFunctionBase(block, PassOptions(), &pass_results)
.status());
XLS_RETURN_IF_ERROR(
DeadCodeEliminationPass()
.RunOnFunctionBase(block, PassOptions(), &pass_results)
.status());
for (Node* node : block->nodes()) {
// Nodes like cover and assume have token types and will cause a failure
// here. Ultimately these operations should *not*
// have tokens and instead are handled as side-effecting operations.
XLS_RET_CHECK(!TypeHasToken(node->GetType()));
}
return absl::OkStatus();
}
} // namespace
absl::StatusOr<Block*> ProcToCombinationalBlock(Proc* proc,
absl::string_view block_name) {
XLS_VLOG(3) << "Converting proc to combinational block:";
XLS_VLOG_LINES(3, proc->DumpIr());
// In a combinational module, the proc cannot have any state to avoid
// combinational loops. That is, the loop state must be an empty tuple.
if (proc->StateType() != proc->package()->GetTupleType({})) {
return absl::InvalidArgumentError(
absl::StrFormat("Proc must have no state (state type is empty tuple) "
"when lowering to "
"a combinational block. Proc state is: %s",
proc->StateType()->ToString()));
}
Block* block = proc->package()->AddBlock(
absl::make_unique<Block>(block_name, proc->package()));
XLS_ASSIGN_OR_RETURN(StreamingIo streaming_io,
CloneProcNodesIntoBlock(proc, block));
XLS_RETURN_IF_ERROR(
AddFlowControl(streaming_io.inputs, streaming_io.outputs, block));
XLS_RETURN_IF_ERROR(RemoveDeadTokenNodes(block));
XLS_VLOG_LINES(3, block->DumpIr());
return block;
}
} // namespace verilog
} // namespace xls
|
#include "stdafx.h"
#include "Totem.h"
Totem::Totem(int pos) : totemCondition(IDLE), attackTimer(0, 3), lazerTimer(0, 1), damageTimer(0, .1f), isAttack(false), isAlive(true), i(1)
// attackTimer : 5초동안 가만히 있다가
// lazerTimer : 1초동안 레이저 파바ㅏㅏ바ㅏ박
{
enemyType = TOTEM;
health = 150;
totemAttack = new ZeroSprite("Resource/Enemy/Totem/Attack/totem_attack.png");
totemIdle = new ZeroAnimation(3.0f);
for (int i = 1; i <= 2; i++) {
totemIdle->PushSprite("Resource/Enemy/Totem/Idle/totem_idle_%d.png", i);
}
lazer = new ZeroAnimation(7.0f);
for (int i = 1; i <= 4; i++) {
lazer->PushSprite("Resource/Enemy/Totem/Lazer/lazer_%d.png", i);
}
if (pos % 2 == 0)
{
totemIdle->SetScalingCenter(totemIdle->Width() * .5f);
totemAttack->SetScalingCenter(totemIdle->Width() * .5f);
lazer->SetScalingCenter(lazer->Width() * .5f);
totemIdle->SetScale(-1, 1);
totemAttack->SetScale(-1, 1);
lazer->SetScale(-0.9, 0.9);
lazer->SetPosX(-totemAttack->Width() + 100);
}
else
{
lazer->SetPosX(totemAttack->Width() - 50);
lazer->SetScale(0.9, 0.9);
}
PushScene(totemAttack);
PushScene(totemIdle);
PushScene(lazer);
lazer->SetScalingCenter(1, lazer->Height() * 2.0f);
this->pos = pos % 2;
}
void Totem::Update(float eTime)
{
ZeroIScene::Update(eTime);
Attack(eTime);
if (health <= 0)
isAlive = false;
}
void Totem::Render()
{
ZeroIScene::Render();
switch (totemCondition)
{
case IDLE:
totemIdle->Render();
break;
case ATTACK:
lazer->Render();
totemAttack->Render();
break;
}
}
void Totem::Damage(PlayerCharacter * player, float eTime)
{
if (lazer->IsOverlapped(player->collider) && isAttack && isAlive)
{
damageTimer.first += eTime;
if (damageTimer.first >= damageTimer.second)
{
player->health -= 2;
damageTimer.first = 0;
}
}
else if ((totemIdle->IsOverlapped(player->collider) || totemAttack->IsOverlapped(player->collider)) && player->isAttack)
{
health -= player->attackPower;
isDamaged = true;
damagedTimer.first += eTime;
if (damagedTimer.first >= damagedTimer.second && !player->isAttack)
isDamaged = false;
}
}
void Totem::Attack(float eTime)
{
attackTimer.first += eTime;
if (attackTimer.first >= attackTimer.second)
{
isAttack = true;
lazerTimer.first += eTime;
switch (i)
{
case 0:
if(pos == 0)
totemCondition = ATTACK;
if (lazerTimer.first >= lazerTimer.second)
{
isAttack = false;
lazerTimer.first = 0;
attackTimer.first = 0;
totemCondition = IDLE;
i = 1;
}
break;
case 1:
if(pos == 1)
totemCondition = ATTACK;
if (lazerTimer.first >= lazerTimer.second)
{
isAttack = false;
lazerTimer.first = 0;
attackTimer.first = 0;
totemCondition = IDLE;
i = 0;
}
}
}
}
|
#include "serialization.h"
#include "assertion.h"
#include <fstream>
void SaveJson(const nlohmann::json& data, const std::string& name) {
std::ofstream file(name);
if (!file) {
THROWERROR("Cannot open file " + name);
}
file << data;
}
nlohmann::json LoadJson(const std::string& name) {
nlohmann::json res;
std::ifstream file(name);
if (!file.good()) {
THROWERROR("Cannot open file " + name);
}
file >> res;
return res;
}
|
#include <iostream>
#include <fstream>
#include <array>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <climits>
struct Point {
int x, y;
Point() : Point(0, 0) {}
Point(int x, int y) : x(x), y(y) {}
bool operator==(const Point& rhs) const {
return x == rhs.x && y == rhs.y;
}
bool operator!=(const Point& rhs) const {
return !operator==(rhs);
}
Point operator+(const Point& rhs) const {
return Point(x + rhs.x, y + rhs.y);
}
Point operator-(const Point& rhs) const {
return Point(x - rhs.x, y - rhs.y);
}
};
struct Node {
Point point;
//int hvalue;
double hvalue;
};
//what you are can be black = 1, white = 2
int player;
const int SIZE = 8;
// the board that u took from the main.cpp
std::array<std::array<int, SIZE>, SIZE> board;
// valid spots right now that u got from the game
std::vector<Point> next_valid_spots;
// disc count I added from the main, it's a bit useless but I try to keep track of the disc count
std::array<int, 3> disc_count;
//directions useful on the flip function (copied frm main
const std::array<Point, 8> directions{ {
Point(-1, -1), Point(-1, 0), Point(-1, 1),
Point(0, -1), /*{0, 0}, */Point(0, 1),
Point(1, -1), Point(1, 0), Point(1, 1)
} };
// get who is the next turn plater
int get_next_player(int cur_player) {
return 3 - cur_player;
}
// border of the board
bool is_spot_on_board(Point p) {
return 0 <= p.x && p.x < SIZE && 0 <= p.y && p.y < SIZE;
}
// get_disc if it's black or white at point P
int get_disc(Point p, std::array<std::array<int, SIZE>, SIZE> currStateBoard) {
return currStateBoard[p.x][p.y];
}
// set the disc blakc or white on point p
void set_disc(Point p, int disc, std::array<std::array<int, SIZE>, SIZE> &currStateBoard) {
currStateBoard[p.x][p.y] = disc;
}
// is disc at point p connected to is spot valid and flip disc
bool is_disc_at(Point p, int disc, std::array<std::array<int, SIZE>, SIZE> currStateBoard) {
//if out or border then u quickly return false
if (!is_spot_on_board(p))
return false;
if (get_disc(p, currStateBoard) != disc)
return false;
// e.g black turn if this point point is not white then return false, if it is white thentrue
return true;
}
bool is_spot_valid(Point center, int cur_player, std::array<std::array<int, SIZE>, SIZE> currStateBoard) {
if (get_disc(center, currStateBoard) != 0)
return false;
for (Point dir : directions) {
// Move along the direction while testing.
Point p = center + dir;
if (!is_disc_at(p, get_next_player(cur_player), currStateBoard))
continue;
p = p + dir;
while (is_spot_on_board(p) && get_disc(p, currStateBoard) != 0) {
if (is_disc_at(p, cur_player, currStateBoard))
return true;
p = p + dir;
}
}
return false;
}
// for flipping disc and update board state
void flip_discs(Point center, int cur_player, std::array<std::array<int, SIZE>, SIZE> &currStateBoard) {
for (Point dir : directions) {
// Move along the direction while testing.
Point p = center + dir;
if (!is_disc_at(p, get_next_player(cur_player), currStateBoard))
continue;
std::vector<Point> discs({ p });
p = p + dir;
while (is_spot_on_board(p) && get_disc(p, currStateBoard) != 0) {
if (is_disc_at(p, cur_player, currStateBoard)) {
for (Point s : discs) {
set_disc(s, cur_player, currStateBoard);
}
disc_count[cur_player] += discs.size();
disc_count[get_next_player(cur_player)] -= discs.size();
break;
}
discs.push_back(p);
p = p + dir;
}
}
}
// get all the valid spots for the current player
std::vector<Point> get_valid_spots(int cur_player, std::array<std::array<int, SIZE>, SIZE> currStateBoard){
std::vector<Point> valid_spots;
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
Point p = Point(i, j);
// if there's a disc already then continue to the next point
if (currStateBoard[i][j] != 0)
continue;
// else check if the ' u can put there as in the rule of othello ' if yes push_back
if (is_spot_valid(p, cur_player, currStateBoard))
valid_spots.push_back(p);
}
}
// return whole vector
return valid_spots;
}
std::array<std::array<int, SIZE>, SIZE> copy_board(std::array<std::array<int, SIZE>, SIZE> currStateBoard) {
std::array<std::array<int, SIZE>, SIZE> temp;
for (long long unsigned int i = 0; i < SIZE; i++) {
for (long long unsigned int j = 0; j < SIZE; j++) {
temp[i][j] = currStateBoard[i][j];
}
}
return temp;
}
double greedy_heuristic_evaluation_function(std::array<std::array<int, SIZE>, SIZE> currStateBoard) {
std::array<int, 3> currStateDiskCount = {};
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (currStateBoard[i][j] == 1) {
currStateDiskCount[1]++;
}
else if (currStateBoard[i][j] == 2) {
currStateDiskCount[2]++;
}
else {
currStateDiskCount[0]++;
}
}
}
double piece_diff = currStateDiskCount[player] - currStateDiskCount[get_next_player(player)];
return piece_diff;
}
double mobility_heuristic_evaluation_function(std::array<std::array<int, SIZE>, SIZE> currStateBoard/*, int currPlayer*/) {
int my_tiles = 0, opp_tiles = 0;
double m_player = 0, m_opp = 0;
//mobility
if (currStateBoard[0][0] == player) my_tiles++;
if (currStateBoard[0][7] == player) my_tiles++;
if (currStateBoard[7][0] == player) my_tiles++;
if (currStateBoard[7][7] == player) my_tiles++;
if (currStateBoard[0][0] == get_next_player(player)) opp_tiles++;
if (currStateBoard[0][7] == get_next_player(player)) opp_tiles++;
if (currStateBoard[7][0] == get_next_player(player)) opp_tiles++;
if (currStateBoard[7][7] == get_next_player(player)) opp_tiles++;
//get the valid spot of the player right now
std::vector<Point> temp = get_valid_spots(player, currStateBoard);
m_player = temp.size();
temp = get_valid_spots(get_next_player(player), currStateBoard);
m_opp = temp.size();
double heuristic = 10 * (my_tiles - opp_tiles) + ((m_player - m_opp) / (m_player + m_opp));
return heuristic;
}
Node minimax(std::array<std::array<int, SIZE>, SIZE> currStateBoard, int currPlayer, int depth , double alpha, double beta/*, std::array<int, 3> disc_count_state*/){
// valid move of every player with different board state every function call
std::vector<Point> availablePoint = get_valid_spots(currPlayer, currStateBoard);
if (disc_count[0] > 14) {
if (depth == 6 ) {
Node temp = { {0, 0}, mobility_heuristic_evaluation_function(currStateBoard) };
return temp;
}
else if (availablePoint.empty() && depth != 6) {
Node temp = { {0, 0}, mobility_heuristic_evaluation_function(currStateBoard) };
return temp;
}
}
else if(disc_count[0] <= 14) {
//change heuristic when empty <= 14
if (depth == 14) {
Node temp = { {0, 0}, greedy_heuristic_evaluation_function(currStateBoard};
return temp;
}
else if (availablePoint.empty() && depth != 14) {
Node temp = { {0, 0}, greedy_heuristic_evaluation_function(currStateBoard)};
return temp;
}
}
if (currPlayer == player) {
double maxScore = -1e9;
Point maxPoint = {-1, -1};
for (unsigned long long int i = 0; i < availablePoint.size(); i++) {
Point avaPoint = availablePoint[i];
std::array<std::array<int, SIZE>, SIZE> temp = copy_board(currStateBoard);
// update board
set_disc(avaPoint, currPlayer, currStateBoard/*, disc_count_state*/);
flip_discs(avaPoint, currPlayer, currStateBoard);
Node result = minimax(currStateBoard, get_next_player(currPlayer), depth + 1, alpha, beta);
currStateBoard = temp;
if (maxScore < result.hvalue) {
maxScore = result.hvalue;
maxPoint = avaPoint;
}
alpha = std::max(alpha, maxScore);
if (beta <= alpha) break;
}
return {maxPoint, maxScore};
}
else {
// opponent plays optimally takes the minimum score
double minScore = 1e9;
Point minPoint = { -1, -1 };
for (unsigned long long int i = 0; i < availablePoint.size(); i++) {
Point avaPoint = availablePoint[i];
std::array<std::array<int, SIZE>, SIZE> temp = copy_board(currStateBoard);
//update board
set_disc(avaPoint, currPlayer, currStateBoard);
flip_discs(avaPoint, currPlayer, currStateBoard);
Node result = minimax(currStateBoard, get_next_player(currPlayer), depth + 1, alpha, beta);
currStateBoard = temp;
if (minScore > result.hvalue) {
minScore = result.hvalue;
minPoint = avaPoint;
}
beta = std::min(beta, minScore);
if (beta <= alpha)break;
}
return { minPoint, minScore };
}
}
void read_board(std::ifstream& fin) {
fin >> player;
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
fin >> board[i][j];
if (board[i][j] == 1) {
// 1 is black
disc_count[1]++;
}
else if (board[i][j] == 2) {
// 2 is white
disc_count[2]++;
}
else {
// no black/ white
disc_count[0]++;
}
}
}
}
void read_valid_spots(std::ifstream& fin) {
int n_valid_spots;
// read valid spots
fin >> n_valid_spots;
int x, y;
for (int i = 0; i < n_valid_spots; i++) {
fin >> x >> y;
next_valid_spots.push_back({x, y});
}
}
void write_valid_spot(std::ofstream& fout) {
srand(time(NULL));
Node bestMove = minimax(board, player, 0, -1e9, 1e9);
Point p = bestMove.point;
// Remember to flush the output to ensure the last action is written to file.
fout << p.x << " " << p.y << std::endl;
fout.flush();
}
int main(int, char** argv) {
std::ifstream fin(argv[1]);
std::ofstream fout(argv[2]);
read_board(fin);
read_valid_spots(fin);
write_valid_spot(fout);
fin.close();
fout.close();
return 0;
}
|
#include "subject.hpp"
#include <iomanip>
class ProgressBar : public Observer {
public:
void update(int val) {
// progress logic
std::cout << "\rProgress: [";
for (int i=0; i<val; i++)
std::cout << "#";
std::cout << std::setw(11 - val) << "]";
std::cout << std::flush;
}
};
class TerminalVal : public Observer {
public:
void update(int val) {
std::cout << " status: [" << std::setw(4) << val*10 << "%]" << std::flush;
}
};
class MainForm {
private:
ProgressBar pb;
TerminalVal tv;
DownloadStatus ds;
public:
MainForm() {
ds.addObserver(&pb);
ds.addObserver(&tv);
}
void click() {
ds.download();
}
};
int main(int argc, char const *argv[])
{
MainForm mf;
mf.click();
return 0;
}
|
#include "RenderTarget.h"
#include "VertexArray.h"
#include "Texture2D.h"
#include "Buffer.h"
#include "OpenGLDebug.h"
#include <iostream>
RenderTarget::RenderTarget(glm::ivec2 dimensions)
{
_bound = false;
_dimensions = dimensions;
_fboID = 0;
_rboID = 0;
clearAttachments();
GLfloat rectVerts[] =
{
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
};
_screenQuad = std::make_unique<VertexArray>();
_screenQuad->bind();
Buffer meshData(GL_ARRAY_BUFFER, 24 * sizeof(GLfloat), rectVerts, GL_STATIC_DRAW);
meshData.bind();
_screenQuad->setVertexSize(6);
_screenQuad->attach(GL_FLOAT, 2, 4 * sizeof(GLfloat), 0, false);
_screenQuad->attach(GL_FLOAT, 2, 4 * sizeof(GLfloat), 2 * sizeof(GLfloat), false);
_screenQuad->unbind();
}
RenderTarget::~RenderTarget()
{
clearAttachments();
if (_fboID) { glDeleteFramebuffers(1, &_fboID); glCheckError(); }
}
void RenderTarget::addColorAttachment()
{
if (_colorAttachmentCount < 3)
{
std::shared_ptr<Texture2D> color = std::make_shared<Texture2D>(nullptr, _dimensions, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, false);
_colorAttachments[_colorAttachmentCount++] = color;
}
}
void RenderTarget::addColorAttachment(std::shared_ptr<Texture2D> color)
{
if(_colorAttachmentCount < 3)_colorAttachments[_colorAttachmentCount++] = color;
}
void RenderTarget::addDepthAttachment(bool depthStencil)
{
if (_rboID) { glDeleteRenderbuffers(1, &_rboID); glCheckError(); }
_rboID = 0;
std::shared_ptr<Texture2D> depth = std::make_shared<Texture2D>(nullptr, _dimensions,
(_depthStencil) ? GL_DEPTH24_STENCIL8 : GL_DEPTH_COMPONENT32F,
(_depthStencil) ? GL_DEPTH_STENCIL : GL_DEPTH_COMPONENT, GL_FLOAT, false);
_depthAttachment = depth;
}
void RenderTarget::addDepthAttachment(std::shared_ptr<Texture2D> depth, bool depthStencil)
{
if (_rboID) { glDeleteRenderbuffers(1, &_rboID); glCheckError(); }
_rboID = 0;
_depthAttachment = depth;
_depthStencil = depthStencil;
}
void RenderTarget::addRenderBuffer(bool depthStencil)
{
_depthAttachment = nullptr;
_depthStencil = depthStencil;
createRenderBuffer();
}
void RenderTarget::bindAttachments()
{
if (_fboID == 0)
{
glGenFramebuffers(1, &_fboID); glCheckError();
}
bind();
if (_colorAttachmentCount > 0)
{
for (int i = 0; i < _colorAttachmentCount; i++)
{
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, _colorAttachments[i]->textureId(), 0); glCheckError();
}
unsigned int attachments[4] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; glCheckError();
glDrawBuffers(_colorAttachmentCount, attachments);
}
else
{
glDrawBuffer(GL_NONE); glCheckError();
glReadBuffer(GL_NONE); glCheckError();
}
if (_depthAttachment != nullptr)
{
glFramebufferTexture2D(GL_FRAMEBUFFER, (_depthStencil) ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _depthAttachment->textureId(), 0); glCheckError();
}
else if (_rboID)
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, (_depthStencil) ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _rboID); glCheckError();
}
unbind();
}
void RenderTarget::clearAttachments()
{
if (_rboID) { glDeleteRenderbuffers(1, &_rboID); glCheckError(); }
_colorAttachmentCount = 0;
_rboID = 0;
_depthStencil = false;
_colorAttachments[0] = nullptr;
_colorAttachments[1] = nullptr;
_colorAttachments[2] = nullptr;
_colorAttachments[3] = nullptr;
_depthAttachment = nullptr;
}
std::shared_ptr<Texture2D> RenderTarget::getColorAttachment(unsigned int colorAttachId)
{
return (colorAttachId < 4)? _colorAttachments[colorAttachId] : nullptr;
}
std::shared_ptr<Texture2D> RenderTarget::getDepthAttachment()
{
return _depthAttachment;
}
glm::ivec2 RenderTarget::getDimensions()
{
return _dimensions;
}
unsigned int RenderTarget::getFrameBufferId()
{
return _fboID;
}
void RenderTarget::renderToTarget()
{
if(!_bound)bind();
_screenQuad->draw();
}
void RenderTarget::resize(glm::ivec2 dimensions)
{
_dimensions = dimensions;
for (int i = 0; i < _colorAttachmentCount; i++)
{
_colorAttachments[i]->resize(dimensions);
}
if(_depthAttachment)_depthAttachment->resize(dimensions);
if (_rboID)addRenderBuffer(_depthStencil);
}
void RenderTarget::readPixel(glm::ivec2 coord, unsigned int colorAttachId, void* pixelData)
{
if (_colorAttachments[colorAttachId] == nullptr)
{
throw std::runtime_error("ERROR: ColorAttachment does not exist!");
}
bind();
glReadBuffer(GL_COLOR_ATTACHMENT0 + colorAttachId);
glReadPixels(coord.x, coord.y, 1, 1, _colorAttachments[colorAttachId]->getFormat(), _colorAttachments[colorAttachId]->getDataType(), &pixelData);
glReadBuffer(GL_NONE);
unbind();
}
void RenderTarget::blitToTarget(std::shared_ptr<RenderTarget> src, GLbitfield mask, GLenum filter)
{
glBindFramebuffer(GL_READ_FRAMEBUFFER, src->getFrameBufferId());
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _fboID);
glBlitFramebuffer(0, 0, src->getDimensions().x, src->getDimensions().y, 0, 0, _dimensions.x, _dimensions.y, mask, filter);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}
void RenderTarget::bind()
{
_bound = true;
glViewport(0, 0, _dimensions.x, _dimensions.y); glCheckError();
glBindFramebuffer(GL_FRAMEBUFFER, _fboID); glCheckError();
}
void RenderTarget::unbind()
{
_bound = false;
glBindFramebuffer(GL_FRAMEBUFFER, 0); glCheckError();
}
void RenderTarget::clear()
{
if (!_bound)bind();
(_depthStencil)?
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT) :
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glCheckError();
}
void RenderTarget::clearColor(glm::vec4 color)
{
if (!_bound)bind();
glClearColor(color.r, color.g, color.b, color.a);
glClear(GL_COLOR_BUFFER_BIT); glCheckError();
}
void RenderTarget::clearDepth(float depth)
{
if (!_bound)bind();
glClearDepth(depth);
glClear(GL_DEPTH_BUFFER_BIT); glCheckError();
}
void RenderTarget::clearStencil(int stencil)
{
if (!_bound)bind();
glClearStencil(stencil);
glClear(GL_STENCIL_BUFFER_BIT); glCheckError();
}
void RenderTarget::createRenderBuffer()
{
if (_rboID) { glDeleteRenderbuffers(1, &_rboID); glCheckError(); }
bind();
glGenRenderbuffers(1, &_rboID); glCheckError();
glBindRenderbuffer(GL_RENDERBUFFER, _rboID); glCheckError();
glRenderbufferStorage(GL_RENDERBUFFER, (_depthStencil) ? GL_DEPTH24_STENCIL8 : GL_DEPTH_COMPONENT32F, _dimensions.x, _dimensions.y); glCheckError();
glBindRenderbuffer(GL_RENDERBUFFER, 0); glCheckError();
unbind();
}
|
/***********************************************************
Starter code for Assignment 3
This code was originally written by Jack Wang for
CSC418, SPRING 2005
implements light_source.h
***********************************************************/
#include <cmath>
#include "light_source.h"
void PointLight::shade( Ray3D& ray ) {
// TODO: implement this function to fill in values for ray.col
// using phong shading. Make sure your vectors are normalized, and
// clamp colour values to 1.0.
//
// It is assumed at this point that the intersection information in ray
// is available. So be sure that traverseScene() is called on the ray
// before this function.
// Remember that every vector needs to be normalized.
// When we discuss diffusivity and specularity, we care about the angle
// at which the light strikes the surface. We also have the values of
// dot products be < 1, which prevents our colours from maxing out.
// If we do not normalize, we take magnitudes into account as well, which is incorrect,
// since we max out the colours.
//Get the normal
Vector3D normal = ray.intersection.normal;
normal.normalize();
// Get the ray from intersection point to light
Point3D light_pos = get_position();
Vector3D light_ray = light_pos - ray.intersection.point;
light_ray.normalize();
// Get the reflected ray following formula 2*(n.s)*n - s
double n_dot_light = normal.dot(light_ray);
Vector3D reflected_ray = 2 * n_dot_light * normal - light_ray;
reflected_ray.normalize();
double specular_dot_product = reflected_ray.dot((-1)*ray.dir);
double ambient_intensity = 1.0;
double diffuse_intensity = 1.0;
double specular_intensity = 1.2;
double spec_shininess = ray.intersection.mat->specular_exp;
// Need to use std::max to make sure we never have a negative colour value.
// Our surface is characterized by the material's diffusivity and specularity components
Colour light_ambient = ambient_intensity * ray.intersection.mat->ambient;
Colour light_diffuse = std::max(0.0, n_dot_light)*diffuse_intensity*ray.intersection.mat->diffuse;
Colour light_specular = pow(std::max(0.0, specular_dot_product),spec_shininess)*specular_intensity*ray.intersection.mat->specular;
// Colour material_ambient
// Colour material_diffuse
// Colour material_specular
ray.col = light_ambient;
if (n_dot_light < 0) {
return;
}
ray.col = ray.col + light_diffuse + light_specular;
ray.col.clamp();
// ray.col = ray.col +
return;
}
|
#pragma once
#include"Anyinclude.h"
class Menu
{
public:
Menu(float width, float height);
~Menu();
void draw(sf::RenderWindow& window);
void Moveup();
void Movedown();
int GetPressedItem() { return selectedItem; }
int selectedItem = 0;
private:
sf::Texture menuTexture[Max_Items];
sf::Sprite menupic[Max_Items];
};
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
// Our alarm system is intended to keep intruders from
// entering at the front door
// of a square room, crossing the room, and then exiting
// through the back door. It
// consists of noise sensors located at various points on the
// floor of the room.
// Each sensor has its own threshold sound level -- it will
// warn us if the
// sound level at the sensor exceeeds its threshold.
//
// The sound generated by an intruder attenuates according to
// an inverse square
// law. Specifically, at a distance r from an intruder, the
// sound level will be
// A/r2, where A is the noisiness of the intruder.
//
// The room is square, with each side of length 100.0. The
// coordinates of the
// southwest corner are (x=0,y=0) and the coordinates of the
// northeast corner are
// (x=100,y=100). The intruder will enter at (50,0) and exit
// at (50,100).
//
// Given vector <int>s x, y, and threshold return the largest
// value of A that will allow an
// intruder to walk through the room without setting off an
// alarm.
// The i-th sensor is described by the ith elements of x, y,
// and threshold. Note
// that we cannot expect an intruder to limit his path to
// integer coordinates!
//
//
//
// DEFINITION
// Class:Alarmed
// Method:noise
// Parameters:vector <int>, vector <int>, vector <int>
// Returns:double
// Method signature:double noise(vector <int> x, vector <int>
// y, vector <int> threshold)
//
//
// NOTES
// -A return value with either an absolute or relative error
// of less than 1.0E-9 is considered correct.
//
//
// CONSTRAINTS
// -x will contain between 1 and 50 elements, inclusive.
// -x, y and threshold will contain the same number of
// elements.
// -All sensor locations will be distinct.
// -Each element of x and y will be between 1 and 99,
// inclusive.
// -Each element of threshold will be between 1 and 10,000,
// inclusive.
//
//
// EXAMPLES
//
// 0)
// {50}
// {2}
// {87}
//
// Returns: 347.99999999999994
//
//
//
// Here there is one sensor, very close to the front door.
// The intruder can
// move along the wall where he enters and continue to
// follow the walls until
// he gets to the exit door. The closest he will get to
// the one sensor is at the
// point where he enters the room which is a distance of 2
// away. If A is 348 the
// alarm will not sound, since 348/(2*2), the largest
// sound level at the
// sensor, does not exceed the threshold of the sensor,
// but any bigger value
// of A will sound the alarm.
//
//
//
// 1)
// {1,99}
// {50,50}
// {1,1}
//
// Returns: 2400.9999999999995
//
//
//
// There are two very sensitive sensors located near the
// east wall and the
// west wall. The best path for an intruder is straight
// through the room. Then
// the closest he will get to a sensor is a distance of
// 49, and the crucial value
// of A will be 49*49 = 2401.0.
//
//
// 2)
// {3,11,2,62,91}
// {90,10,75,25,50}
// {5,4,3,2,1}
//
// Returns: 1537.9999999999998
//
//
//
//
// 3)
// { 1,99}
// { 50,50}
// { 1, 2}
//
// Returns: 3295.5717878751793
//
//
//
// END CUT HERE
#line 128 "Alarmed.cpp"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
#define SQR(x) (x)*(x)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
bool to[55][55];
bool ok(VI &x, VI &y, VI&t, double a) {
memset(to,0,sizeof(to));
fi(x.size()) {
to[i][i]=true;
f(j,i+1,x.size()) {
double dist = SQR(x[i]-x[j]) + SQR(y[i]-y[j]);
if (sqrt(dist) < sqrt(a/t[i]) + sqrt(a/t[j])) {
to[i][j]=true;
to[j][i]=true;
}
}
double dist = SQR(x[i]-50) + SQR(y[i]);
if (a/dist >= t-1e9) return false;
}
}
class Alarmed
{
public:
double noise(vector <int> x, vector <int> y, vector <int> t)
{
double low = 0.0;
double high = 2.0e9;
fi(100){
double mid = (low + high) / 2.0;
if (ok(x,y,t,mid)) {
low = mid;
} else high = mid;
}
return low;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {50}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {87}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); double Arg3 = 347.99999999999994; verify_case(0, Arg3, noise(Arg0, Arg1, Arg2)); }
void test_case_1() { int Arr0[] = {1,99}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {50,50}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1,1}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); double Arg3 = 2400.9999999999995; verify_case(1, Arg3, noise(Arg0, Arg1, Arg2)); }
void test_case_2() { int Arr0[] = {3,11,2,62,91}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {90,10,75,25,50}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {5,4,3,2,1}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); double Arg3 = 1537.9999999999998; verify_case(2, Arg3, noise(Arg0, Arg1, Arg2)); }
void test_case_3() { int Arr0[] = { 1,99}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 50,50}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 1, 2}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); double Arg3 = 3295.5717878751793; verify_case(3, Arg3, noise(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
Alarmed ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include "stdafx.h"
#include "Random.h"
using namespace pure; using namespace std;
Random::Random():
m_rd(),
m_mez(m_rd())
{
}
Random::~Random()
{
}
float Random::operator()(float min, float max) const
{
uniform_real_distribution<> rand(min, max);
return (float)rand(m_mez);
}
float Random::operator()(float max) const
{
uniform_real_distribution<> rand(0, max);
return (float)rand(m_mez);
}
double Random::operator()(double min, double max) const
{
uniform_real_distribution<> rand(min, max);
return rand(m_mez);
}
double Random::operator()(double max) const
{
uniform_real_distribution<> rand(0, max);
return rand(m_mez);
}
int Random::operator()(int min, int max) const
{
uniform_int_distribution<> rand(min, max);
return rand(m_mez);
}
int Random::operator()(int max) const
{
uniform_int_distribution<> rand(0, max);
return rand(m_mez);
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
//
// Copyright (C) 1995-2004 Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
#ifndef BT_DOWNLOAD_H
#define BT_DOWNLOAD_H
// ----------------------------------------------------
#include "adjunct/m2/src/util/buffer.h"
# include "modules/util/OpHashTable.h"
# include "modules/util/adt/opvector.h"
#include "bt-info.h"
#include "bt-util.h"
#include "dl-base.h"
#include "bt-client.h"
#include "bt-globals.h"
#include "connection.h"
#include "bt-packet.h"
#include "bt-tracker.h"
class DownloadTransfer;
class DownloadTransferBT;
class UploadTransferBT;
class BTClient;
class BTPacket;
class P2PBlockFile;
class P2PFilePart;
class P2PFile;
#define HASH_NULL 0
#define HASH_TORRENT 1
// these represent bits
#define NotSeeding (1 << 1) // not currently seeding/checking files
#define PreSeeding (1 << 2) // seeding before any download/upload is initiated
#define PostSeeding (1 << 3) // seeding after download has been completed
#define PostSeedingDone (1 << 4) // post seeding done if bit is set
#define PreSeedingDone (1 << 5) // set when the pre-seeding is done
struct BTBlock
{
UINT32 block; // block number
UINT32 block_count; // number of occurences of this block in the swarm
};
class BTCompactPeer
{
public:
BTCompactPeer() {}
BTCompactPeer(OpString& peer, UINT32 port)
{
OpStatus::Ignore(m_peer.Set(peer.CStr()));
m_port = port;
}
OpString m_peer;
UINT32 m_port;
};
class BTDownload :
public DownloadBase,
public OpTimerListener
{
// Construction
public:
BTDownload();
virtual ~BTDownload();
public:
// BOOL m_torrentRequested;
// BOOL m_torrentStarted;
time_t m_torrentTracker;
time_t m_torrentPeerExchange;
UINT64 m_torrentUploaded;
UINT64 m_torrentDownloaded;
BOOL m_torrentEndgame;
BOOL m_trackerError;
OpString m_torrentTrackerError;
UINT32 m_blocknumber;
UINT32 m_blocklength;
UINT32 m_totalSeeders; // total number of peers with the complete file ("seeders")
UINT32 m_totalPeers; // total number of peers without the complete file ("leechers")
BTTracker::TrackerState m_tracker_state;
protected:
UINT64 m_volume;
UINT64 m_total;
byte* m_torrentBlock;
UINT32 m_torrentBlockSize;
UINT32 m_torrentSize;
UINT32 m_torrentSuccess;
OpAutoPtr<OpTimer> m_seed_timer;
UINT32 m_seeding_stage; // are we seeding or not
BOOL m_create_files;
UINT64 m_create_offset;
BOOL m_checking_file;
BOOL m_checking_file_queued;
BOOL m_first_block; // set to TRUE on the first block checked
UINT32 m_checking_delay; // delay to use for the next checking cycle
BTBlock *m_available_block_count; // array with a count of the available block in the swarm
OpP2PVector<UploadTransferBT> m_unchokes;
OpP2PVector<UploadTransferBT> m_chokes;
// OpTimerListener.
virtual void OnTimeOut(OpTimer* timer);
private:
// OpVector<UploadTransferBT> m_torrentUploads;
time_t m_torrentChoke;
time_t m_torrentChokeRefresh;
time_t m_torrentSources;
P2PFile *m_verifyfile;
P2PFile *m_verify_block_file;
BOOL m_initial_ramp_up; // if TRUE, we want to connect to 10+ peers fast to ramp up
// the download speed in the beginning
BTClientConnectors m_BTClientConnectors;
public:
BTClientConnectors * ClientConnectors() { return &m_BTClientConnectors; }
// OpVector<UploadTransferBT> *GetUploads() { return &m_torrentUploads; }
OP_STATUS CheckExistingFile();
void StartRampUp() { m_initial_ramp_up = TRUE; }
void Clear();
void Pause();
void Resume();
void Remove(BOOL bDelete = FALSE);
BOOL IsPaused() { return m_paused; }
BOOL IsMoving() { return ( m_file == NULL ); }
BOOL IsCompleted() { return m_complete; }
BOOL IsStarted() { return(GetVolumeComplete() > 0); }
BOOL IsDownloading() { return(GetTransferCount() > 0); }
BOOL IsBoosted() { return m_boosted; }
BOOL CheckSource(DownloadSource* pSource) const;
void ClearSources();
BOOL AddSourceBT(SHAStruct* pGUID, OpString& pAddress, WORD nPort, BOOL from_pex, OpString& pex_address);
void ChokeTorrent(time_t tNow = 0);
BTPacket* CreateBitfieldPacket();
OP_STATUS SetTorrent(BTInfoImpl* pTorrent);
BOOL RunTorrent(time_t tNow);
void OnTrackerEvent(BOOL success, OpString& tracker_url, char *reason = NULL);
void OnRun();
BOOL StartTransfersIfNeeded(time_t tNow);
void SubtractHelper(P2PFilePart** ppCorrupted, byte* block, UINT64 nBlock, UINT64 size);
void OnDownloaded();
BOOL VerifyTorrentFiles(BOOL first);
virtual UINT64 GetVolumeUploaded() { return m_torrentUploaded; }
BOOL VerifyTorrentBlock(UINT32 block);
OP_STATUS UpdateAvailableBlockCount(UINT32 block, BOOL increment = TRUE);
void GetRarestBlocks(BTBlock *dest_blocks, UINT32 block_count);
void SortAvailableBlockCount();
BOOL IsUnchokable(UploadTransferBT *transfer, BOOL allow_snubbed, BOOL allow_not_interested = FALSE);
void ResetFileCheckState();
OP_STATUS StringToPeerlist(OpString& compact_peers, OpVector<BTCompactPeer>& peers);
OP_STATUS CompactStringToPeer(unsigned short* compact_peer, OpString& peer, UINT32& port);
OP_STATUS PeerToString(BTCompactPeer& peer, OpByteBuffer& compact_peer);
virtual INT32 GetTransferCount(int state = -1, OpString* pAddress = NULL);
/**
* Get any unchokes that should be performed immediately.
*
* max_to_unchoke - maximum number of peers allowed to be unchoked
* all_peers - list of peers to choose from
* returns peers to unchoke
*/
void GetImmediateUnchokes(UINT32 max_to_unchoke, OpVector<UploadTransferBT> *unchoke_peers);
/**
* Perform peer choke, unchoke and optimistic calculations
*
* max_to_unchoke - maximum number of peers allowed to be unchoked
* all_peers - list of peers to choose from
* force_refresh - force a refresh of optimistic unchokes
*/
void CalculateUnchokes( UINT32 max_to_unchoke, BOOL force_refresh);
void GetChokes(OpVector<UploadTransferBT> *chokes);
void GetUnchokes(OpVector<UploadTransferBT> *unchokes);
static void UpdateLargestValueFirstSort(double new_value, OpVector<double> *values, UploadTransferBT *new_item, OpVector<UploadTransferBT> *items, int start_pos );
static void UpdateSmallestValueFirstSort(double new_value, OpVector<double> *values, UploadTransferBT *new_item, OpVector<UploadTransferBT> *items, int start_pos );
UploadTransferBT *GetNextOptimisticPeer(BOOL factor_reciprocated, BOOL allow_snubbed, BOOL allow_not_interested = FALSE);
BOOL IsPeerInterestedInMe(BTClientConnector *client);
P2PUploads *GetUploads() { return &m_Uploads; }
void RefreshInterest();
protected:
virtual BOOL FindMoreSources();
// BOOL SeedTorrent(char *target);
void CloseTorrent();
inline BOOL IsSeeding() const { return m_seeding; }
float GetRatio() const;
void SortSource(DownloadSource* pSource, BOOL bTop);
void SortSource(DownloadSource* pSource);
void RemoveOverlappingSources(UINT64 nOffset, UINT64 nLength);
void StopTrying();
void RestrictUploadBandwidth();
protected:
BOOL GenerateTorrentDownloadID(); //Generate Peer ID
void OnFinishedTorrentBlock(UINT32 nBlock);
void CloseTorrentUploads();
OP_STATUS CreateCheckTimer();
public:
friend class DownloadSource;
friend class DownloadTransferBT;
friend class Downloads;
};
class DownloadTransferBT : public DownloadTransfer
{
// Construction
public:
DownloadTransferBT(DownloadSource* source, BTClientConnector* client);
virtual ~DownloadTransferBT();
// Attributes
public:
BTClientConnector* m_client;
BOOL m_choked;
BOOL m_interested;
public:
byte* m_available;
P2PFilePart* m_requested;
INT32 m_requestedCount;
time_t m_runthrottle;
time_t m_sourcerequest;
private:
BTBlock *m_rareblocks;
BOOL m_snubbed;
bool m_sending;
bool m_close_requested; // true -> Close when Send returns
TRISTATE m_close_arg;
// Operations
public:
virtual BOOL Initiate();
virtual void Close(TRISTATE bKeepSource);
virtual void Boost();
virtual UINT32 GetAverageSpeed();
virtual UINT32 GetMeasuredSpeed();
// virtual BOOL OnRun();
virtual BOOL OnConnected();
virtual OP_STATUS SubtractRequested(P2PFilePart** ppFragments);
virtual OP_STATUS UnrequestRange(UINT64 offset, UINT64 length);
BOOL HasCompleteBlock(UINT32 block);
void OnReceivedPiece(UINT64 offset, UINT64 length);
void StartClosing();
BOOL IsSnubbed() { return m_snubbed; }
void SetSnubbed(BOOL snubbed) { m_snubbed = snubbed; }
public:
OP_STATUS OnBitfield(BTPacket* packet);
OP_STATUS OnHave(BTPacket* packet);
OP_STATUS OnChoked(BTPacket* packet);
OP_STATUS OnUnchoked(BTPacket* packet);
OP_STATUS OnPiece(BTPacket* packet);
void SendFinishedBlock(UINT32 block);
OP_STATUS SendRequests();
OP_STATUS OnSnubbed();
void DecrementAvailableBlockCountOnDisconnect();
protected:
void Send(BTPacket* packet, BOOL release = TRUE);
void Send(OpByteBuffer *buffer);
void ShowInterest();
OP_STATUS SelectFragment(P2PFilePart* possible, UINT64* offset, UINT64* length);
friend class BTDownload;
};
#endif // BT_DOWNLOAD_H
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
LL ans1 = 0, ans2 = 0;
int n, m, a[55555], was[55555], w[55555], total;
vector<int> g[55555];
void dfst(int x) {
was[x] = 2;
total += a[x];
for (int i = 0; i < (int)g[x].size(); ++i) {
if (was[g[x][i]] != 2) {
dfst(g[x][i]);
}
}
}
void dfs(int x) {
was[x] = 1;
LL sum = 0;
for (int i = 0; i < (int)g[x].size(); ++i) {
if (was[g[x][i]] != 1) {
dfs(g[x][i]);
sum += LL(a[x]) * a[g[x][i]];
a[x] += a[g[x][i]];
}
}
if (sum > 0 || (total > a[x] && a[x] > 0)) ++ans2;
ans1 += sum;
}
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
}
for (int i = 0; i < m; ++i) {
int x, y;
scanf("%d%d", &x, &y);
g[x].push_back(y);
g[y].push_back(x);
}
for (int i = 1; i <= n; ++i)
if (!was[i]) {
total = 0;
dfst(i);
dfs(i);
}
cout << ans1 << " " << ans2 << endl;
return 0;
}
|
#ifndef GAME_H
#define GAME_H
#include <common/scene.h>
#include <common/client.h>
#include <common/server.h>
class Game : public Scene
{
public:
Game();
~Game();
void Initialize();
int port;
int updatenumber;
Client client;
sf::Vector2f prevPosition;
virtual void Update(sf::Event event);
void ClientUpdate();
private:
};
#endif
|
#include<iostream>
#include<utility>
#include<vector>
using namespace std;
int main(){
int n, e, u, v, ans;
cin >> n >> e;
vector <pair<int, int>> nodes = vector <pair<int, int>>(n); //first is root second is num of childern
for(int i = 0; i < n; i++){
nodes[i].first = -1;
nodes[i].second = 1;
}
for(int i = 0; i < e;i++){
cin >> u >> v;
nodes[u-1].first = v -1 ;
}
// from the end of the tree go on adding number of the children to parent
for(int i = n -1; i >-1; i--)
if(nodes[i].first != -1)
nodes[nodes[i].first].second += nodes[i].second;
// calculate the ones which have even children in subtree
ans = 0;
for(int i = 0; i < n; i++)
if(nodes[i].first != -1 && nodes[i].second % 2 == 0)
ans++;
cout << ans << endl;
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
//
// Copyright (C) 1995-2007 Opera Software ASA. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Patricia Aas
//
#include "core/pch.h"
#include "adjunct/desktop_util/handlers/FileContainer.h"
#include "modules/pi/OpSystemInfo.h"
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
FileContainer::FileContainer(OpString * file_name,
OpString * file_path,
OpString * file_ext,
OpBitmap * file_thumbnail)
: DownloadManager::Container(file_name,
file_thumbnail)
{
Init(file_path, file_ext);
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
FileContainer::FileContainer(OpString * file_name,
OpString * file_path,
OpString * file_ext,
Image &file_thumbnail)
: DownloadManager::Container(file_name,
file_thumbnail)
{
Init(file_path, file_ext);
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void FileContainer::Init(OpString * file_name,
OpString * file_path,
OpString * file_ext,
OpBitmap * file_thumbnail)
{
InitContainer(file_name, file_thumbnail); //superclass init
Init(file_path, file_ext);
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void FileContainer::Init(OpString * file_name,
OpString * file_path,
OpString * file_ext,
Image &file_thumbnail)
{
InitContainer(file_name, file_thumbnail); //superclass init
Init(file_path, file_ext);
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void FileContainer::Empty()
{
EmptyContainer();
m_file_path_name.Empty();
m_file_extension.Empty();
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void FileContainer::Init(OpString * file_path,
OpString * file_ext)
{
OpString name;
name.Set(GetName().CStr());
m_executable = g_op_system_info->GetIsExecutable(&name);
if(file_path)
{
m_file_path_name.Set(file_path->CStr());
}
if(file_ext)
{
m_file_extension.Set(file_ext->CStr());
}
}
|
//
// main.cpp
// Recursividad
//
// Created by Daniel on 21/08/14.
// Copyright (c) 2014 Gotomo. All rights reserved.
//
#include <iostream>
using namespace std;
#include<iostream>
int MCD;
int euclides(int m, int n);
int main(int argc, const char *argv[]){
int m,n;
cout<<"Entre un numero"<<endl;
cin>>m;
cout<<"SEgundo numero"<<endl;
cin>>n;
cout<<"El MCD de:"<<m<<" y "<<n<<" es:"<<euclides(m, n)<<endl;
return 0;
}
int euclides(int m,int n){
int r;
if(n>m){
r = m;
m = n;
n = r;
}
r = m%n;
if(r==0){
return n;
}
else{
return euclides(n,r);
}
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
for(int i = 1; i <= n+1; i++){
int p = pow(i, 3);
int result = p + 2*i;
cout<<result<<" ";
}
return 0;
}
|
// Created on: 1993-01-11
// Created by: CKY / Contract Toubro-Larsen ( TCD )
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESDraw_NetworkSubfigure_HeaderFile
#define _IGESDraw_NetworkSubfigure_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <gp_XYZ.hxx>
#include <Standard_Integer.hxx>
#include <IGESDraw_HArray1OfConnectPoint.hxx>
#include <IGESData_IGESEntity.hxx>
class IGESDraw_NetworkSubfigureDef;
class TCollection_HAsciiString;
class IGESGraph_TextDisplayTemplate;
class IGESDraw_ConnectPoint;
class IGESDraw_NetworkSubfigure;
DEFINE_STANDARD_HANDLE(IGESDraw_NetworkSubfigure, IGESData_IGESEntity)
//! defines IGES Network Subfigure Instance Entity,
//! Type <420> Form Number <0> in package IGESDraw
//!
//! Used to specify each instance of Network Subfigure
//! Definition Entity (Type 320, Form 0).
class IGESDraw_NetworkSubfigure : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESDraw_NetworkSubfigure();
//! This method is used to set the fields of the class
//! NetworkSubfigure
//! - aDefinition : Network Subfigure Definition Entity
//! - aTranslation : Translation data relative to the model
//! space or the definition space
//! - aScaleFactor : Scale factors in the definition space
//! - aTypeFlag : Type flag
//! - aDesignator : Primary reference designator
//! - aTemplate : Primary reference designator Text
//! display Template Entity
//! - allConnectPoints : Associated Connect Point Entities
Standard_EXPORT void Init (const Handle(IGESDraw_NetworkSubfigureDef)& aDefinition, const gp_XYZ& aTranslation, const gp_XYZ& aScaleFactor, const Standard_Integer aTypeFlag, const Handle(TCollection_HAsciiString)& aDesignator, const Handle(IGESGraph_TextDisplayTemplate)& aTemplate, const Handle(IGESDraw_HArray1OfConnectPoint)& allConnectPoints);
//! returns Network Subfigure Definition Entity specified by this entity
Standard_EXPORT Handle(IGESDraw_NetworkSubfigureDef) SubfigureDefinition() const;
//! returns Translation Data relative to either model space or to
//! the definition space of a referring entity
Standard_EXPORT gp_XYZ Translation() const;
//! returns the Transformed Translation Data relative to either model
//! space or to the definition space of a referring entity
Standard_EXPORT gp_XYZ TransformedTranslation() const;
//! returns Scale factor in definition space(x, y, z axes)
Standard_EXPORT gp_XYZ ScaleFactors() const;
//! returns Type Flag which implements the distinction between Logical
//! design and Physical design data,and is required if both are present.
//! Type Flag = 0 : Not specified (default)
//! = 1 : Logical
//! = 2 : Physical
Standard_EXPORT Standard_Integer TypeFlag() const;
//! returns the primary reference designator
Standard_EXPORT Handle(TCollection_HAsciiString) ReferenceDesignator() const;
//! returns True if Text Display Template Entity is specified,
//! else False
Standard_EXPORT Standard_Boolean HasDesignatorTemplate() const;
//! returns primary reference designator Text Display Template Entity,
//! or null. If null, no Text Display Template Entity specified
Standard_EXPORT Handle(IGESGraph_TextDisplayTemplate) DesignatorTemplate() const;
//! returns the number of associated Connect Point Entities
Standard_EXPORT Standard_Integer NbConnectPoints() const;
//! returns the Index'th associated Connect point Entity
//! raises exception if Index <= 0 or Index > NbConnectPoints()
Standard_EXPORT Handle(IGESDraw_ConnectPoint) ConnectPoint (const Standard_Integer Index) const;
DEFINE_STANDARD_RTTIEXT(IGESDraw_NetworkSubfigure,IGESData_IGESEntity)
protected:
private:
Handle(IGESDraw_NetworkSubfigureDef) theSubfigureDefinition;
gp_XYZ theTranslation;
gp_XYZ theScaleFactor;
Standard_Integer theTypeFlag;
Handle(TCollection_HAsciiString) theDesignator;
Handle(IGESGraph_TextDisplayTemplate) theDesignatorTemplate;
Handle(IGESDraw_HArray1OfConnectPoint) theConnectPoints;
};
#endif // _IGESDraw_NetworkSubfigure_HeaderFile
|
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
#include "pbaf_protocol_service.h"
int main(int argc, char** args)
{
if(argc < 3)
{
cout << "Usage: hang <host> <port>" << endl;
return 1;
}
pbaf_server serv;
serv.address = string(args[1]);
serv.port = atoi(args[2]);
pbaf_proto_connect(&serv);
cout << "Intentionally hanging for 7 seconds..." << endl;
std::this_thread::sleep_for(std::chrono::seconds(7));
// check connection
const int comm_result = recv(serv.sock, nullptr, 0, 0);
if(comm_result < 0)
cout << "Failed to send to " << serv.address << endl;
if(comm_result == 0)
cout << serv.address << " closed the connection (took too long)." << endl;
else
{
cout << "The connection to " << serv.address << " is still open." << endl;
cout << "Sent " << comm_result << " bytes." << endl;
pbaf_proto_disconnect(&serv);
}
close(serv.sock);
return 0;
}
|
// Created on: 2001-02-26
// Created by: Peter KURNEV
// Copyright (c) 2001-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IntTools_EdgeFace_HeaderFile
#define _IntTools_EdgeFace_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TopoDS_Edge.hxx>
#include <Standard_Real.hxx>
#include <Standard_Integer.hxx>
#include <BRepAdaptor_Curve.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <Standard_Boolean.hxx>
#include <IntTools_SequenceOfCommonPrts.hxx>
#include <IntTools_Range.hxx>
class IntTools_Context;
class gp_Pnt;
class IntTools_CommonPrt;
//! The class provides Edge/Face intersection algorithm to determine
//! common parts between edge and face in 3-d space.
//! Common parts between Edge and Face can be:
//! - Vertices - in case of intersection or touching;
//! - Edge - in case of full coincidence of the edge with the face.
class IntTools_EdgeFace
{
public:
DEFINE_STANDARD_ALLOC
public: //! @name Constructors
//! Empty Constructor
Standard_EXPORT IntTools_EdgeFace();
public: //! @name Setters/Getters
//! Sets the edge for intersection
void SetEdge(const TopoDS_Edge& theEdge)
{
myEdge = theEdge;
}
//! Returns the edge
const TopoDS_Edge& Edge() const
{
return myEdge;
}
//! Sets the face for intersection
void SetFace(const TopoDS_Face& theFace)
{
myFace = theFace;
}
//! Returns the face
const TopoDS_Face& Face() const
{
return myFace;
}
//! Sets the boundaries for the edge.
//! The algorithm processes edge inside these boundaries.
void SetRange(const IntTools_Range& theRange)
{
myRange = theRange;
}
//! Sets the boundaries for the edge.
//! The algorithm processes edge inside these boundaries.
void SetRange(const Standard_Real theFirst, const Standard_Real theLast)
{
myRange.SetFirst(theFirst);
myRange.SetLast(theLast);
}
//! Returns intersection range of the edge
const IntTools_Range& Range() const
{
return myRange;
}
//! Sets the intersection context
void SetContext(const Handle(IntTools_Context)& theContext)
{
myContext = theContext;
}
//! Returns the intersection context
const Handle(IntTools_Context)& Context() const
{
return myContext;
}
//! Sets the Fuzzy value
void SetFuzzyValue(const Standard_Real theFuzz)
{
myFuzzyValue = Max(theFuzz, Precision::Confusion());
}
//! Returns the Fuzzy value
Standard_Real FuzzyValue() const
{
return myFuzzyValue;
}
//! Sets the flag for quick coincidence check.
//! It is safe to use the quick check for coincidence only if both
//! of the following conditions are met:
//! - The vertices of edge are lying on the face;
//! - The edge does not intersect the boundaries of the face on the given range.
void UseQuickCoincidenceCheck(const Standard_Boolean theFlag)
{
myQuickCoincidenceCheck = theFlag;
}
//! Returns the flag myQuickCoincidenceCheck
Standard_Boolean IsCoincidenceCheckedQuickly()
{
return myQuickCoincidenceCheck;
}
public: //! @name Performing the operation
//! Launches the process
Standard_EXPORT void Perform();
public: //! @name Checking validity of the intersection
//! Returns TRUE if computation was successful.
//! Otherwise returns FALSE.
Standard_Boolean IsDone() const
{
return myIsDone;
}
//! Returns the code of completion:
//! 0 - means successful completion;
//! 1 - the process was not started;
//! 2,3 - invalid source data for the algorithm;
//! 4 - projection failed.
Standard_Integer ErrorStatus() const
{
return myErrorStatus;
}
public: //! @name Obtaining results
//! Returns resulting common parts
const IntTools_SequenceOfCommonPrts& CommonParts() const
{
return mySeqOfCommonPrts;
}
//! Returns the minimal distance found between edge and face
Standard_Real MinimalDistance() const
{
return myMinDistance;
}
protected: //! @name Protected methods performing the intersection
Standard_EXPORT static Standard_Boolean IsEqDistance (const gp_Pnt& aP, const BRepAdaptor_Surface& aS, const Standard_Real aT, Standard_Real& aD);
Standard_EXPORT void CheckData();
Standard_EXPORT Standard_Boolean IsProjectable (const Standard_Real t) const;
Standard_EXPORT Standard_Real DistanceFunction (const Standard_Real t);
Standard_EXPORT Standard_Integer MakeType (IntTools_CommonPrt& aCP);
Standard_EXPORT Standard_Boolean CheckTouch (const IntTools_CommonPrt& aCP, Standard_Real& aTX);
Standard_EXPORT Standard_Boolean CheckTouchVertex (const IntTools_CommonPrt& aCP, Standard_Real& aTX);
//! Checks if the edge is in the face really.
Standard_EXPORT Standard_Boolean IsCoincident();
protected:
TopoDS_Edge myEdge;
TopoDS_Face myFace;
Standard_Real myFuzzyValue;
BRepAdaptor_Curve myC;
BRepAdaptor_Surface myS;
Standard_Real myCriteria;
Standard_Boolean myIsDone;
Standard_Integer myErrorStatus;
Handle(IntTools_Context) myContext;
IntTools_SequenceOfCommonPrts mySeqOfCommonPrts;
IntTools_Range myRange;
Standard_Boolean myQuickCoincidenceCheck;
Standard_Real myMinDistance; //!< Minimal distance found
};
#endif // _IntTools_EdgeFace_HeaderFile
|
#include "include/InitApp.h"
Functions InitApp::funs = Functions();
Reduces InitApp::reduces = Reduces();
/*
E→E+T
E→E-T
E→T
T→T*T'
T→T/T'
T→T^T'
T→T%T'
T→T'
T'→-T'
T'→F!
T'→F
F→fun(G)
F→F'
F→num
F'→(E)
F'→|E|
G→G,E
G→E
*/
Reduces& InitApp::load_reduces(Reduces& rs)
{
rs["E→E+T"] = [](vector<Symbol> symbols) -> Symbol {
double* v1 = (double*)symbols[0].getValue();
double* v2 = (double*)symbols[2].getValue();
*v1 = *v1 + *v2;
Symbol symbol("E", v1);
delete v2;
return symbol;
};
rs["E→E-T"] = [](vector<Symbol> symbols) -> Symbol {
double* v1 = (double*)symbols[0].getValue();
double* v2 = (double*)symbols[2].getValue();
*v1 = *v1 - *v2;
Symbol symbol("E", v1);
delete v2;
return symbol;
};
rs["E→T"] = [](vector<Symbol> symbols) -> Symbol {
Symbol symbol("E", symbols[0].getValue());
return symbol;
};
rs["T→T*T'"] = [](vector<Symbol> symbols) -> Symbol {
double* v1 = (double*)symbols[0].getValue();
double* v2 = (double*)symbols[2].getValue();
*v1 = *v1 * *v2;
Symbol symbol("T", v1);
delete v2;
return symbol;
};
rs["T→T/T'"] = [](vector<Symbol> symbols) -> Symbol {
double* v1 = (double*)symbols[0].getValue();
double* v2 = (double*)symbols[2].getValue();
*v1 = *v1 / *v2;
Symbol symbol("T", v1);
delete v2;
return symbol;
};
rs["T→T^T'"] = [](vector<Symbol> symbols) -> Symbol {
double* v1 = (double*)symbols[0].getValue();
double* v2 = (double*)symbols[2].getValue();
*v1 = pow(*v1, *v2);
Symbol symbol("T", v1);
delete v2;
return symbol;
};
rs["T→T%T'"] = [](vector<Symbol> symbols) -> Symbol {
double* v1 = (double*)symbols[0].getValue();
double* v2 = (double*)symbols[2].getValue();
*v1 = fmod(*v1, *v2);
Symbol symbol("T", v1);
delete v2;
return symbol;
};
rs["T→T'"] = [](vector<Symbol> symbols) -> Symbol {
Symbol symbol("T", symbols[0].getValue());
return symbol;
};
rs["T'→-T'"] = [](vector<Symbol> symbols) -> Symbol {
double* v1 = (double*)symbols[1].getValue();
*v1 = -*v1;
Symbol symbol("T'", v1);
return symbol;
};
rs["T'→F!"] = [](vector<Symbol> symbols) -> Symbol {
double* v1 = (double*)symbols[0].getValue();
double num = 1;
size_t v = (int)abs(*v1);
for (size_t i = 2; i <= v; i++)
{
num *= i;
}
Symbol symbol("T'", new double(num));
delete v1;
return symbol;
};
rs["T'→F"] = [](vector<Symbol> symbols) -> Symbol {
Symbol symbol("T'", symbols[0].getValue());
return symbol;
};
rs["F→fun(G)"] = [](vector<Symbol> symbols) -> Symbol {
string* v1 = (string*)symbols[0].getValue();
vector<double>* v2 = (vector<double>*)symbols[2].getValue();
double(*fun)(vector<double>) = funs[*v1];
if (!fun)
{
throw "没有此函数: " + *v1;
}
Symbol symbol("F", new double(fun(*v2)));
delete v1;
delete v2;
return symbol;
};
rs["F→F'"] = [](vector<Symbol> symbols) -> Symbol {
Symbol symbol("F", symbols[0].getValue());
return symbol;
};
rs["F→num"] = [](vector<Symbol> symbols) -> Symbol {
string* v1 = (string*)symbols[0].getValue();
Symbol symbol("F", new double(atof(v1->c_str())));
delete v1;
return symbol;
};
rs["F'→(E)"] = [](vector<Symbol> symbols) -> Symbol {
Symbol symbol("F'", symbols[1].getValue());
return symbol;
};
rs["F'→|E|"] = [](vector<Symbol> symbols) -> Symbol {
double* v1 = (double*)symbols[1].getValue();
*v1 = abs(*v1);
Symbol symbol("F'", v1);
return symbol;
};
rs["G→G,E"] = [](vector<Symbol> symbols) -> Symbol {
vector<double>* v1 = (vector<double>*)symbols[0].getValue();
double* v2 = (double*)symbols[2].getValue();
v1->push_back(*v2);
delete v2;
Symbol symbol("G", v1);
return symbol;
};
rs["G→E"] = [](vector<Symbol> symbols) -> Symbol {
vector<double>* v = new vector<double>();
double* v1 = (double*)symbols[0].getValue();
v->push_back(*v1);
delete v1;
Symbol symbol("G", v);
return symbol;
};
return rs;
}
void InitApp::init()
{
load_funs(funs);
load_reduces(reduces);
}
void InitApp::check_arg(string fname, size_t args_size, size_t need_size)
{
if (args_size != need_size)
{
cerr << fname << "函数参数不正确,需要" << need_size << "个参数" << endl;
exit(EXIT_FAILURE);
}
}
Functions& InitApp::load_funs(Functions& fs)
{
fs["sin"] = [](vector<double> args) -> double {
check_arg("sin", args.size(), 1);
return sin(args[0]);
};
fs["cos"] = [](vector<double> args) -> double {
check_arg("cos", args.size(), 1);
return cos(args[0]);
};
fs["tan"] = [](vector<double> args) -> double {
check_arg("tan", args.size(), 1);
return tan(args[0]);
};
fs["ceil"] = [](vector<double> args) -> double {
check_arg("ceil", args.size(), 1);
return ceil(args[0]);
};
fs["floor"] = [](vector<double> args) -> double {
check_arg("floor", args.size(), 1);
return floor(args[0]);
};
fs["asin"] = [](vector<double> args) -> double {
check_arg("asin", args.size(), 1);
return asin(args[0]);
};
fs["acos"] = [](vector<double> args) -> double {
check_arg("acos", args.size(), 1);
return acos(args[0]);
};
fs["atan"] = [](vector<double> args) -> double {
check_arg("atan", args.size(), 1);
return atan(args[0]);
};
fs["sinh"] = [](vector<double> args) -> double {
check_arg("sinh", args.size(), 1);
return sinh(args[0]);
};
fs["cosh"] = [](vector<double> args) -> double {
check_arg("cosh", args.size(), 1);
return cosh(args[0]);
};
fs["tanh"] = [](vector<double> args) -> double {
check_arg("tanh", args.size(), 1);
return tanh(args[0]);
};
fs["ln"] = [](vector<double> args) -> double {
check_arg("ln", args.size(), 1);
return log(args[0]);
};
fs["log"] = [](vector<double> args) -> double {
if (args.size() == 1)
{
return log10(args[0]);
}
if (args.size() == 2)
{
return log(args[0]) / log(args[1]);
}
cerr << "log函数参数不正确,需要1或2个参数" << endl;
exit(EXIT_FAILURE);
};
return fs;
}
|
#pragma once
#include <iostream>
namespace sj
{
enum LOG_LEVEL
{
LL_DEBUG,
LL_TRACE,
LL_INFO,
LL_ERROR,
LL_FATAL,
};
class logger
{
public:
static logger & GetInstance()
{
static logger _instance;
return _instance;
};
LOG_LEVEL& GetLogLevel()
{
return _log_level;
}
void SetLogLevel(LOG_LEVEL ll)
{
_log_level = ll;
}
template < class... ARGS >
void __LogDebug(ARGS... args)
{
__Log(LL_DEBUG, std::cout, args...);
}
template < class... ARGS >
void __LogTrace(ARGS... args)
{
__Log(LL_TRACE, std::cout, args...);
}
template < class... ARGS >
void __LogInfo(ARGS... args)
{
__Log(LL_INFO, std::cout, args...);
}
template < class... ARGS >
void __LogError(ARGS... args)
{
__Log(LL_ERROR, std::cout, args...);
}
template < class... ARGS >
void __LogFatal(ARGS... args)
{
__Log(LL_FATAL, std::cout, args...);
}
private:
template < class OS , class ARG >
void __LogImp(OS& os, ARG arg)
{
os << arg << '\n';
}
template < class OS, class ARG, class... ARGS>
void __LogImp(OS& os, ARG arg, ARGS... args)
{
os << arg;
__LogImp(os, args...);
}
template < class OS, class... ARGS>
void __Log(LOG_LEVEL ll, OS& os, ARGS... args)
{
if (ll < GetLogLevel())
{
return;
}
__LogImp(os, args...);
}
private:
logger() : _log_level(LL_DEBUG) {}
logger(const logger &);
logger & operator= (const logger &);
private:
LOG_LEVEL _log_level;
};
#define LOG_DEBUG sj::logger::GetInstance().__LogDebug
#define LOG_TRACE sj::logger::GetInstance().__LogTrace
#define LOG_INFO sj::logger::GetInstance().__LogInfo
#define LOG_ERROR sj::logger::GetInstance().__LogError
#define LOG_FATAL sj::logger::GetInstance().__LogFatal
}
|
class server
{
private:
/* data */
public:
server(/* args */);
~server();
};
server::server(/* args */)
{
}
server::~server()
{
}
|
#include "stdafx.h"
#include "material.h"
#include <cassert>
vec3 material::reflect(const vec3 & in, const vec3 & normal)
{
return in - 2 * (in * normal) * normal;
}
bool material::refract(const vec3 &in, const vec3 &n, float ni_over_nt, vec3 &refracted) {
vec3 uv = in.normalized();
float dt = uv * n;
float discriminant = 1.0f - ni_over_nt * ni_over_nt * (1.0f - dt * dt);
if (discriminant < 0) {
return false;
}
refracted = ni_over_nt * (uv - n * dt) - n * sqrt(discriminant);
return true;
}
float material::schlick(float cosine, float ref_idx)
{
float r0 = (1.0f - ref_idx) / (1.0f + ref_idx);
r0 *= r0;
return r0 + (1.0f - r0) * pow(1.0f - cosine,5);
}
float material::blinnPhong(const vec3 viewerDir, const vec3 lightSourceDir, const vec3 normal, float specCoeff)
{
vec3 halfWay = (viewerDir + lightSourceDir).normalized();
float dotPr = halfWay * normal;
return pow(std::max(dotPr, 0.0f), specCoeff);
}
|
/*Assignment 2 for CS 1337.013
*Programmer: Medha Aiyah
*Description: This file is used to program the constructors, destructors, and the member functions for the Question
* class and the Trivia Game class.
*/
#include <iostream>
#include "assignment2.h"
using namespace std;
//This Question constructor is used to initialize the question, possible answers, and the correct number for the answer
Question::Question()
{
questionTxt = "";
for(int i=0; i < MAX_SIZE; i++)
{
possibleAnswers[i] = "";
}
answerCorrectNum = 0;
}
//This question constructor will get the question text, the 4 possible answers, and the answer number of the correct answer
Question::Question(fstream &file)
{
getline(file, questionTxt, '\n');
for(int i=0; i < MAX_SIZE; i++)
{
getline(file, possibleAnswers[i],'\n');
numPossibleAns++;
}
file.clear();
file >> answerCorrectNum;
file.ignore(100, '\n');
}
//The Question destructor will set the variables used in the constructor to null or zero values
Question::~Question()
{
questionTxt = "";
for(int i=0; i < MAX_SIZE; i++)
{
possibleAnswers[i] = "";
}
answerCorrectNum = 0;
}
//This function is used to return the number of the possible answers available
unsigned int Question::numPossibleAnswers() const
{
return numPossibleAns;
}
//This function is used to return the correct answer number for the specific question
unsigned int Question::numCorrectAnswers() const
{
return answerCorrectNum;
}
//This function is used to return the text of the question
string Question::questionText() const
{
return questionTxt;
}
//This function is used to return the text for the 4 possible answers
string Question::answerText(unsigned int choice) const
{
return possibleAnswers[choice];
}
//This constructor is supposed to read in the input file and build all of the questions based on the information in
//the input file.
TriviaGame::TriviaGame(fstream &file)
{
//This is what will happen if the file is unable to open
if (file.fail())
{
cout << "This file is unable to open." << endl;
}
//If the file successfully opens, it will access the ptr and it will store the question, possible answers, and the
//correct answer that was stored in the Question constructor.
else
{
file >> numQuestion;
cout << "This is the number of questions." << numQuestion << endl;
index1 = 0;
index2 = numQuestion / 2;
file.ignore(100, '\n');
ptr = new Question[numQuestion];
for (int i =0; i < numQuestion; i++)
{
ptr[i] = Question(file);
}
}
}
//This destructor is used to delete values in the array
TriviaGame::~TriviaGame()
{
delete [] ptr;
}
//This function is used to return the number of questions
unsigned int TriviaGame::numOfQuestions()
{
return numQuestion;
}
//This function is created to return the next question for a given player
//This should return a const reference to the next Question object for the given player
const Question & TriviaGame::nextQuestionPlayer1()
{
return ptr[index1++];
}
const Question & TriviaGame::nextQuestionPlayer2()
{
return ptr[index2++];
}
//This function is used to validate whether or not player one put down the right answer
bool TriviaGame::correctAnswerPlayer1(Question question, unsigned int answerPlayer1)
{
if (answerPlayer1 == question.numCorrectAnswers()) //the user answer is equal to the right answer of the question
{
validityPlayer1 = true;
}
else
{
validityPlayer1 = false;
}
return validityPlayer1;
}
//This function is used to validate whether or not player two put down the right answer
bool TriviaGame::correctAnswerPlayer2(Question question, unsigned int answerPlayer2)
{
if (answerPlayer2 == question.numCorrectAnswers()) //the user answer is equal to the right answer of the question
{
validityPlayer2 = true;
}
else
{
validityPlayer2 = false;
}
return validityPlayer2;
}
//This function is used to increment the points for player 1
void TriviaGame::additionPointsPlayer1()
{
if(validityPlayer1)
{
pointsPlayer1++;
}
}
//This function is used to increment the points for player 2
void TriviaGame::additionPointsPlayer2()
{
if(validityPlayer2)
{
pointsPlayer2++;
}
}
|
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include "PascalAnnotation.h"
#include "ImageDatabase.h"
using namespace std;
static const char *SIGNATURE = "ImageDataset";
// Image Database class
ImageDatabase::ImageDatabase():
_positivesCount(0),
_negativesCount(0)
{
}
ImageDatabase::ImageDatabase(const string &dbFilename, const string category):
_positivesCount(0),
_negativesCount(0)
{
_category = category;
load(dbFilename);
}
ImageDatabase::ImageDatabase(const vector<vector<Detection> > &dets,
const vector<string> &fnames):
_detections(dets),
_filenames(fnames),
_positivesCount(0),
_negativesCount(0)
{
}
vector<Detection> ImageDatabase::getGroundTruth(string imageName)
{
vector<Detection> dets;
vector<string> parts;
boost::split(parts,imageName,boost::is_any_of("/."),boost::token_compress_on);
string annotationsPath = "/Users/david/Documents/Development/VOC2007/VOCdevkit/VOC2007/Annotations/";
string annotationsFilename = annotationsPath + parts[parts.size()-2] + ".xml";
pascal_annotation annotation;
annotation.load(annotationsFilename);
for(int i = 0; i < annotation.objects.size(); ++i){
if(boost::iequals(annotation.objects[i].name,_category))
{
cv::Rect r(annotation.objects[i].bndbox.xmin,
annotation.objects[i].bndbox.ymin,
annotation.objects[i].bndbox.xmax - annotation.objects[i].bndbox.xmin,
annotation.objects[i].bndbox.ymax - annotation.objects[i].bndbox.ymin);
Detection det(r,1);
dets.push_back(det);
}
}
return dets;
}
void ImageDatabase::load(const string &dbFilename)
{
string imagePath = "/Users/david/Documents/Development/VOC2007/VOCdevkit/VOC2007/JPEGImages/";
_dbFilename = dbFilename;
ifstream f(dbFilename.c_str());
if(!f.is_open()) {
throw std::runtime_error("Could not open file " + dbFilename + " for reading");
}
else
{
string line;
while(getline(f, line)){
vector<string> parts;
boost::split(parts, line, boost::is_any_of(" "), boost::token_compress_on);
string imageName = imagePath + parts[0] + ".jpg";
_filenames.push_back(imageName);
vector<Detection> detections = getGroundTruth(imageName);
_detections.push_back(detections);
int label = -1;
if(atof(parts[1].c_str()) > 0)
label = 1;
_labels.push_back(label);
if(label < 0) _negativesCount++;
else if(label > 0) _positivesCount++;
}
}
}
void ImageDatabase::save(const string &dbFilename)
{
ofstream f(dbFilename.c_str());
if(!f.is_open()) {
throw std::runtime_error("Could not open file " + dbFilename + " for writing");
}
f << SIGNATURE << "\n";
f << getSize() << "\n";
for(int i = 0; i < getSize(); i++) {
f << _filenames[i] << " ";
f << _detections[i].size() << " ";
for (int j = 0; j < _detections[i].size(); j++) {
f << _detections[i][j] << " ";
}
f << "\n";
}
}
ostream & operator << (ostream &s, const ImageDatabase &db)
{
s << "DATABASE INFO\n"
<< setw(20) << "Original filename:" << " " << db.getDatabaseFilename() << "\n"
<< setw(20) << "Positives:" << setw(5) << right << db.getPositivesCount() << "\n"
<< setw(20) << "Negatives:" << setw(5) << right << db.getNegativesCount() << "\n"
<< setw(20) << "Unlabeled:" << setw(5) << right << db.getUnlabeledCount() << "\n"
<< setw(20) << "Total:" << setw(5) << right << db.getSize() << "\n";
return s;
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* MateriaSource.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Kwillum <daniilxod@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/12 18:58:58 by kwillum #+# #+# */
/* Updated: 2021/01/12 21:32:11 by Kwillum ### ########.fr */
/* */
/* ************************************************************************** */
#include "MateriaSource.hpp"
MateriaSource::MateriaSource() : _alreadyLearned(0)
{
for (int i = 0; i < _memoryVolume; i++)
_materiaSrcs[i] = NULL;
}
MateriaSource::~MateriaSource()
{
for (int i = 0; i < _memoryVolume; i++)
if (_materiaSrcs[i])
delete _materiaSrcs[i];
}
MateriaSource::MateriaSource(const MateriaSource &toCopy) : _alreadyLearned(0)
{
for (int i = 0; i < _memoryVolume; i++)
_materiaSrcs[i] = NULL;
for (int i = 0; i < _memoryVolume; i++)
{
if (toCopy._materiaSrcs[i])
_materiaSrcs[i] = toCopy._materiaSrcs[i]->clone();
if (_materiaSrcs[i])
_alreadyLearned++;
}
}
MateriaSource &MateriaSource::operator=(const MateriaSource &toCopy)
{
if (this == &toCopy)
return (*this);
for (int i = 0; i < _memoryVolume; i++)
if (_materiaSrcs[i])
delete _materiaSrcs[i];
_alreadyLearned = 0;
for (int i = 0; i < _memoryVolume; i++)
{
if (toCopy._materiaSrcs[i])
_materiaSrcs[i] = toCopy._materiaSrcs[i]->clone();
if (_materiaSrcs[i])
_alreadyLearned++;
}
return (*this);
}
void MateriaSource::learnMateria(AMateria *m)
{
if (_alreadyLearned < _memoryVolume && m)
{
for (int i = 0; i < _memoryVolume; i++)
{
if (!_materiaSrcs[i])
{
_materiaSrcs[i] = m;
_alreadyLearned++;
break;
}
}
}
}
AMateria* MateriaSource::createMateria(std::string const & type)
{
for (int i = 0; i < _memoryVolume; i++)
{
if (_materiaSrcs[i])
if (_materiaSrcs[i]->getType() == type)
return (_materiaSrcs[i]->clone());
}
return (NULL);
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t, m, n, i;
unsigned long long num1;
unsigned long long num2;
unsigned long long sum;
while(cin>>m>>n)
{
num1 = 1;
num2 = 1;
for(i=1; i<=m; i++)
{
num1 = num1*i;
}
for(i=1; i<=n; i++)
{
num2 = num2*i;
}
sum = num1+num2;
cout<<sum<<"\n";
}
return 0;
}
|
#include "stdafx.h"
#include "FullTimeEmployee.h"
// Functions' declaration
double FullTimeEmployee::calculatePay() const {
return weekSalary;
}
void FullTimeEmployee::print() const {
Employee::print();
cout << "Weekly Salary: $"<< FullTimeEmployee::calculatePay()<< endl;
}
FullTimeEmployee::~FullTimeEmployee()
{
}
|
// Created on: 1997-04-01
// Created by: Christian CAILLET
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepVisual_MarkerMember_HeaderFile
#define _StepVisual_MarkerMember_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepData_SelectInt.hxx>
#include <Standard_Integer.hxx>
#include <StepVisual_MarkerType.hxx>
class StepVisual_MarkerMember;
DEFINE_STANDARD_HANDLE(StepVisual_MarkerMember, StepData_SelectInt)
//! Defines MarkerType as unique member of MarkerSelect
//! Works with an EnumTool
class StepVisual_MarkerMember : public StepData_SelectInt
{
public:
Standard_EXPORT StepVisual_MarkerMember();
Standard_EXPORT virtual Standard_Boolean HasName() const Standard_OVERRIDE;
Standard_EXPORT virtual Standard_CString Name() const Standard_OVERRIDE;
Standard_EXPORT virtual Standard_Boolean SetName (const Standard_CString name) Standard_OVERRIDE;
Standard_EXPORT virtual Standard_CString EnumText() const Standard_OVERRIDE;
Standard_EXPORT virtual void SetEnumText (const Standard_Integer val, const Standard_CString text) Standard_OVERRIDE;
Standard_EXPORT void SetValue (const StepVisual_MarkerType val);
Standard_EXPORT StepVisual_MarkerType Value() const;
DEFINE_STANDARD_RTTIEXT(StepVisual_MarkerMember,StepData_SelectInt)
protected:
private:
};
#endif // _StepVisual_MarkerMember_HeaderFile
|
#include <iostream>
int main() {
char slash;
char probel;
int year;
int day;
int month;
std::cout << "Enter the date 'yyyy dd/mm'" << std::endl;
std::cin >> year >> probel >> day >> slash >> month;
while (year < 0 || year > 2018 ) {
std::cout << "The year can be a number from 0 to 2018" << std::endl;
std::cin >> year >> probel >> day >> slash >> month;
}
while (day < 0 || day > 31 ) {
std::cout << "The day can be a number from 1 to 31";
std::cin >> year >> probel >> day >> slash >> month;
}
while (month < 1 || month > 12) {
std::cout << "The month can be a number from 1 to 12";
std::cin >> year >> probel >> day >> slash >> month;
}
int reversMonth = day%10 * 10 + (day - day%10) / 10;
int reversDay = month%10 * + (month - month%10) / 10;
if(reversMonth > 12 ) {
std::cout << "The aliens will not visit Winnie" << std::endl;
} else if (reversMonth > month ||
(reversMonth == month && reversDay> day)) {
std::cout << "The aliens will come later" << std::endl;
} else if (reversMonth == month && reversDay == day) {
std::cout << "The aliens will come on time" << std::endl;
} else {
std::cout << "The aliens will come earlier" << std::endl;
}
return 0;
}
|
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <SDL_mixer.h>
#include <stdio.h>
#include <string>
#include <cmath>
#include <BaseTsd.h>
#include <random>
#include <iostream>
#include <vector>
#include <ostream>
#include <sstream>
class LWindow
{
public:
//Intializes internals
LWindow();
//Creates window
bool init();
//Creates renderer from internal window
SDL_Renderer* createRenderer();
//Handles window events
void handleEvent( SDL_Event& e );
//Deallocates internals
void free();
//Window dimensions
int getWidth();
int getHeight();
//Window focii
bool hasMouseFocus();
bool hasKeyboardFocus();
bool isMinimized();
private:
//Window data
SDL_Window* mWindow;
//Window dimensions
int mWidth;
int mHeight;
//Window focus
bool mMouseFocus;
bool mKeyboardFocus;
bool mFullScreen;
bool mMinimized;
};
//Texture wrapper class
class LTexture
{
public:
//Initializes variables
LTexture();
//Deallocates memory
~LTexture();
//Loads image at specified path
bool loadFromFile(std::string path);
//#ifdef _SDL_TTF_H
//Creates image from font string
bool loadFromRenderedText( std::string textureText, SDL_Color textColor );
//#endif
//Deallocates texture
void free();
//Set color modulation
void setColor(Uint8 red, Uint8 green, Uint8 blue);
//Set blending
void setBlendMode(SDL_BlendMode blending);
//Set alpha modulation
void setAlpha(Uint8 alpha);
//Renders texture at given point
void render(
int x,
int y,
SDL_Rect* clip = NULL,
double angle = 0.0,
SDL_Point* center = NULL,
SDL_RendererFlip flip = SDL_FLIP_NONE
);
//Gets image dimensions
int getWidth();
int getHeight();
private:
//The actual hardware texture
SDL_Texture* mTexture;
//Image dimensions
int mWidth;
int mHeight;
};
//The application time based timer
class LTimer
{
public:
//Initializes variables
LTimer();
//The various clock actions
void start();
void stop();
void pause();
void unpause();
//Gets the timer's time
Uint32 getTicks();
//Checks the status of the timer
bool isStarted();
bool isPaused();
private:
//The clock time when the timer started
Uint32 mStartTicks;
//The ticks stored when the timer was paused
Uint32 mPausedTicks;
//The timer status
bool mPaused;
bool mStarted;
};
//The ManPac that will move around on the screen
class ManPac
{
public:
//The dimensions of the ManPac
static const int ManPac_WIDTH = 32;
static const int ManPac_HEIGHT = 32;
//Initializes the variables
ManPac();
//Takes key presses and adjusts the ManPac's velocity
void handleEvent(SDL_Event& e);
//Moves the ManPac
void move();
//Shows the ManPac on the screen
void render();
// private:
//The X and Y offsets of the ManPac
int mPosX, mPosY;
//The velocity of the ManPac
int mVelX, mVelY;
int mRotL, mRotR;
};
class Dots
{
public:
void render();
int mPosX, mPosY;
};
Dots SmallDots[240];
|
/*
kamalsam
*/
#include<iostream>
using namespace std;
int main()
{int t,k;long a,b,v;cin>>t;while(t--){cin>>k>>a>>b;while(a!=b){if(a>b){v=a;a=(a/k);if(v%k>1)a++;}else{v=b;b=(b/k);if(v%k>1)b++;}}cout<<a<<endl;}return 0;}
|
#pragma once
#define STOP_CRITERION 0.001
#include"matrix.h"
class AnalyticSolver
{
public:
void static analyticSolution(matrix &m, int iterations);
double static validate(matrix &m1, matrix &m2);
};
|
// Copyright (c) 2023 ETH Zurich
//
// SPDX-License-Identifier: BSL-1.0
// 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)
/// \file parallel/algorithms/transform_xxx.hpp
#pragma once
#include <pika/config.hpp>
#include <pika/assert.hpp>
#include <pika/async_mpi/mpi_helpers.hpp>
#include <pika/async_mpi/mpi_polling.hpp>
#include <pika/concepts/concepts.hpp>
#include <pika/datastructures/variant.hpp>
#include <pika/debugging/demangle_helper.hpp>
#include <pika/debugging/print.hpp>
#include <pika/execution/algorithms/detail/helpers.hpp>
#include <pika/execution/algorithms/detail/partial_algorithm.hpp>
#include <pika/execution/algorithms/transfer.hpp>
#include <pika/execution_base/any_sender.hpp>
#include <pika/execution_base/receiver.hpp>
#include <pika/execution_base/sender.hpp>
#include <pika/executors/thread_pool_scheduler.hpp>
#include <pika/functional/detail/tag_fallback_invoke.hpp>
#include <pika/functional/invoke.hpp>
#include <pika/mpi_base/mpi.hpp>
#include <exception>
#include <tuple>
#include <type_traits>
#include <utility>
namespace pika::mpi::experimental::detail {
namespace ex = execution::experimental;
// -----------------------------------------------------------------
// route calls through an impl layer for ADL isolation
template <typename Sender, typename F>
struct dispatch_mpi_sender_impl
{
struct dispatch_mpi_sender_type;
};
template <typename Sender, typename F>
using dispatch_mpi_sender =
typename dispatch_mpi_sender_impl<Sender, F>::dispatch_mpi_sender_type;
// -----------------------------------------------------------------
// transform MPI adapter - sender type
template <typename Sender, typename F>
struct dispatch_mpi_sender_impl<Sender, F>::dispatch_mpi_sender_type
{
using is_sender = void;
std::decay_t<Sender> sender;
std::decay_t<F> f;
stream_type stream;
#if defined(PIKA_HAVE_STDEXEC)
using completion_signatures = pika::execution::experimental::completion_signatures<
pika::execution::experimental::set_value_t(MPI_Request)>;
#else
// -----------------------------------------------------------------
// completion signatures
template <template <typename...> class Tuple, template <typename...> class Variant>
using value_types = Variant<Tuple<MPI_Request>>;
template <template <typename...> class Variant>
using error_types = util::detail::unique_t<util::detail::prepend_t<
typename ex::sender_traits<Sender>::template error_types<Variant>, std::exception_ptr>>;
#endif
static constexpr bool sends_done = false;
// -----------------------------------------------------------------
// operation state for an internal receiver
template <typename Receiver>
struct operation_state
{
std::decay_t<Receiver> receiver;
std::decay_t<F> f;
stream_type stream_;
// -----------------------------------------------------------------
// The mpi_receiver receives inputs from the previous sender,
// invokes the mpi call, and sets a callback on the polling handler
struct dispatch_mpi_receiver
{
using is_receiver = void;
operation_state& op_state;
template <typename Error>
friend constexpr void
tag_invoke(ex::set_error_t, dispatch_mpi_receiver r, Error&& error) noexcept
{
ex::set_error(PIKA_MOVE(r.op_state.receiver), PIKA_FORWARD(Error, error));
}
friend constexpr void tag_invoke(
ex::set_stopped_t, dispatch_mpi_receiver r) noexcept
{
ex::set_stopped(PIKA_MOVE(r.op_state.receiver));
}
// receive the MPI function invocable + arguments and add a request,
// then invoke the mpi function with the added request
// if the invocation gives an error, set_error
// otherwise return the request by passing it to set_value
template <typename... Ts,
typename = std::enable_if_t<is_mpi_request_invocable_v<F, Ts...>>>
friend constexpr void
tag_invoke(ex::set_value_t, dispatch_mpi_receiver r, Ts&&... ts) noexcept
{
pika::detail::try_catch_exception_ptr(
[&]() mutable {
using namespace pika::debug::detail;
using invoke_result_type = mpi_request_invoke_result_t<F, Ts...>;
PIKA_DETAIL_DP(mpi_tran<5>,
debug(str<>("dispatch_mpi_recv"), "set_value_t", "stream",
detail::stream_name(r.op_state.stream_)));
#ifdef PIKA_HAVE_APEX
apex::scoped_timer apex_post("pika::mpi::post");
#endif
// init a request
MPI_Request request;
int status = MPI_SUCCESS;
// execute the mpi function call, passing in the request object
if constexpr (std::is_void_v<invoke_result_type>)
{
PIKA_INVOKE(PIKA_MOVE(r.op_state.f), ts..., &request);
}
else
{
static_assert(std::is_same_v<invoke_result_type, int>);
status = PIKA_INVOKE(PIKA_MOVE(r.op_state.f), ts..., &request);
}
PIKA_DETAIL_DP(mpi_tran<7>,
debug(str<>("dispatch_mpi_recv"), "invoke mpi",
detail::stream_name(r.op_state.stream_), ptr(request)));
PIKA_ASSERT_MSG(request != MPI_REQUEST_NULL,
"MPI_REQUEST_NULL returned from mpi invocation");
if (status != MPI_SUCCESS)
{
PIKA_DETAIL_DP(mpi_tran<5>,
debug(str<>("set_error"), "status != MPI_SUCCESS",
detail::error_message(status)));
ex::set_error(PIKA_MOVE(r.op_state.receiver),
std::make_exception_ptr(mpi_exception(status)));
return;
}
if (poll_request(request))
{
#ifdef PIKA_HAVE_APEX
apex::scoped_timer apex_invoke("pika::mpi::trigger");
#endif
PIKA_DETAIL_DP(mpi_tran<7>,
debug(str<>("dispatch_mpi_recv"), "eager poll ok",
detail::stream_name(r.op_state.stream_), ptr(request)));
// calls set_value(request), or set_error(mpi_exception(status))
set_value_error_helper(
status, PIKA_MOVE(r.op_state.receiver), MPI_REQUEST_NULL);
}
else
{
set_value_error_helper(
status, PIKA_MOVE(r.op_state.receiver), request);
}
},
[&](std::exception_ptr ep) {
ex::set_error(PIKA_MOVE(r.op_state.receiver), PIKA_MOVE(ep));
});
}
friend constexpr ex::empty_env tag_invoke(
ex::get_env_t, dispatch_mpi_receiver const&) noexcept
{
return {};
}
};
using operation_state_type =
ex::connect_result_t<std::decay_t<Sender>, dispatch_mpi_receiver>;
operation_state_type op_state;
template <typename Tuple>
struct value_types_helper
{
using type = util::detail::transform_t<Tuple, std::decay>;
};
template <typename Receiver_, typename F_, typename Sender_>
operation_state(Receiver_&& receiver, F_&& f, Sender_&& sender, stream_type s)
: receiver(PIKA_FORWARD(Receiver_, receiver))
, f(PIKA_FORWARD(F_, f))
, stream_{s}
, op_state(ex::connect(PIKA_FORWARD(Sender_, sender), dispatch_mpi_receiver{*this}))
{
using namespace pika::debug::detail;
PIKA_DETAIL_DP(
mpi_tran<5>, debug(str<>("operation_state"), "stream", detail::stream_name(s)));
}
friend constexpr auto tag_invoke(ex::start_t, operation_state& os) noexcept
{
return ex::start(os.op_state);
}
};
template <typename Receiver>
friend constexpr auto
tag_invoke(ex::connect_t, dispatch_mpi_sender_type const& s, Receiver&& receiver)
{
return operation_state<Receiver>(
PIKA_FORWARD(Receiver, receiver), s.f, s.sender, s.stream);
}
template <typename Receiver>
friend constexpr auto
tag_invoke(ex::connect_t, dispatch_mpi_sender_type&& s, Receiver&& receiver)
{
return operation_state<Receiver>(
PIKA_FORWARD(Receiver, receiver), PIKA_MOVE(s.f), PIKA_MOVE(s.sender), s.stream);
}
};
} // namespace pika::mpi::experimental::detail
namespace pika::mpi::experimental {
inline constexpr struct dispatch_mpi_t final
: pika::functional::detail::tag_fallback<dispatch_mpi_t>
{
private:
template <typename Sender, typename F,
PIKA_CONCEPT_REQUIRES_(
pika::execution::experimental::is_sender_v<std::decay_t<Sender>>)>
friend constexpr PIKA_FORCEINLINE auto
tag_fallback_invoke(dispatch_mpi_t, Sender&& sender, F&& f, stream_type s)
{
auto snd1 = detail::dispatch_mpi_sender<Sender, F>{
PIKA_FORWARD(Sender, sender), PIKA_FORWARD(F, f), s};
return pika::execution::experimental::make_unique_any_sender(std::move(snd1));
}
template <typename F>
friend constexpr PIKA_FORCEINLINE auto
tag_fallback_invoke(dispatch_mpi_t, F&& f, stream_type s)
{
return pika::execution::experimental::detail::partial_algorithm<dispatch_mpi_t, F>{
PIKA_FORWARD(F, f), s};
}
} dispatch_mpi{};
} // namespace pika::mpi::experimental
|
#include <Arduino.h>
int decimalPrecision = 2; // decimal places for all values shown in LED Display & Serial Monitor
int ThermistorPin = A2; // The analog input pin for measuring temperature
float voltageDividerR1 = 10000; // Resistor value in R1 for voltage devider method
float BValue = 3470; // The B Value of the thermistor for the temperature measuring range
float RT1 = 10000; // Thermistor resistor rating at based temperature (25 degree celcius)
float T1 = 298.15; /* Base temperature T1 in Kelvin (default should be at 25 degree)*/
float R2 ; /* Resistance of Thermistor (in ohm) at Measuring Temperature*/
float T2 ; /* Measurement temperature T2 in Kelvin */
float a ; /* Use for calculation in Temperature*/
float b ; /* Use for calculation in Temperature*/
float c ; /* Use for calculation in Temperature*/
float d ; /* Use for calculation in Temperature*/
float e = 2.718281828 ; /* the value of e use for calculation in Temperature*/
float tempSampleRead = 0; /* to read the value of a sample including currentOffset1 value*/
float tempLastSample = 0; /* to count time for each sample. Technically 1 milli second 1 sample is taken */
float tempSampleSum = 0; /* accumulation of sample readings */
float tempSampleCount = 0; /* to count number of sample. */
float tempMean ; /* to calculate the average value from all samples, in analog values*/
float readTemp(){
/* 1- Temperature Measurement */
while(true){
float temp;
if(millis() >= tempLastSample + 1) /* every 1 milli second taking 1 reading */
{
tempSampleRead = analogRead(ThermistorPin); /* read analog value from sensor */
tempSampleSum = tempSampleSum+tempSampleRead; /* add all analog value for averaging later*/
tempSampleCount = tempSampleCount+1; /* keep counting the sample quantity*/
tempLastSample = millis(); /* reset the time in order to repeat the loop again*/
}
if(tempSampleCount == 1000) /* after 1000 sample readings taken*/
{
tempMean = tempSampleSum / tempSampleCount; /* find the average analog value from those data*/
R2 = (voltageDividerR1*tempMean)/(1023-tempMean); /* convert the average analog value to resistance value*/
a = 1/T1; /* use for calculation */
b = log10(RT1/R2); /* use for calculation */
c = b / log10(e); /* use for calculation */
d = c / BValue ; /* use for calculation */
T2 = 1 / (a- d);
temp = T2 - 273.15;
/* the measured temperature value based on calculation (in Kelvin) */
tempSampleSum = 0; /* reset all the total analog value back to 0 for the next count */
tempSampleCount = 0;
return temp;/* reset the total number of samples taken back to 0 for the next count*/
}
}
return -1;
}
|
/* leetcode 260
*
*
*
*/
#include <string>
#include <unordered_set>
#include <algorithm>
#include <map>
using namespace std;
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int dif = 0, a = 0, b = 0;
for(int num: nums) {
dif = dif ^ num;
}
int div = 1;
while ((div & dif) == 0) {
div = div << 1;
}
for(int num: nums) {
if((num & div) == 0) {
a = a ^ num;
} else {
b = b ^ num;
}
}
return {a, b};
}
};
/************************** run solution **************************/
vector<int> _solution_run(vector<int>& nums)
{
Solution leetcode_260;
vector<int> ans = leetcode_260.singleNumber(nums);
return ans;
}
#ifdef USE_SOLUTION_CUSTOM
string _solution_custom(TestCases &tc)
{
}
#endif
/************************** get testcase **************************/
#ifdef USE_GET_TEST_CASES_IN_CPP
vector<string> _get_test_cases_string()
{
return {};
}
#endif
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
const int N = 100111;
const int T = 77;
vector< pair<int, int> > g[N];
int p[N][18], d[N], pp[N][T][18], w[N], wei[N], wson[N];
int buf[N*2], pos[N], head[N], bpos = 0;
void build(int x) {
int hd = x;
while (x) {
buf[bpos] = x;
pos[x] = bpos;
head[x] = hd;
bpos += d[wson[x]] - d[x];
x = wson[x];
}
++bpos;
}
void dfs(int x) {
for (int j = 1; p[x][j - 1]; ++j) {
p[x][j] = p[p[x][j - 1]][j - 1];
}
pp[x][1][0] = x;
for (int P = 2; P < T; ++P) {
int pc = pp[x][P - 1][0];
if (pc && d[x] - d[p[pc][0]] <= P) pc = p[pc][0];
if (pc && d[x] - d[p[pc][0]] <= P) pc = p[pc][0];
if (!pc || pc == x) break;
pp[x][P][0] = pc;
for (int j = 1; pp[x][P][j - 1]; ++j) {
pp[x][P][j] = pp[pp[x][P][j - 1]][P][j - 1];
}
}
wei[x] = 1;
for (int i = 0; i < (int)g[x].size(); ++i) {
int y = g[x][i].first;
if (p[x][0] == y) continue;
d[y] = d[x] + g[x][i].second;
w[y] = w[x] + 1;
p[y][0] = x;
dfs(y);
wei[x] += wei[y];
if (wson[x] == 0 || wei[y] > wei[wson[x]]) {
if (wson[x]) build(wson[x]);
wson[x] = y;
}
}
}
int lca(int x, int y) {
for (int i = 17; i >= 0; --i)
if (w[p[x][i]] >= w[y])
x = p[x][i];
for (int i = 17; i >= 0; --i)
if (w[p[y][i]] >= w[x])
y = p[y][i];
if (x == y) return x;
for (int i = 17; i >= 0; --i)
if (p[x][i] != p[y][i]) {
x = p[x][i];
y = p[y][i];
}
return p[x][0];
}
int next(int x, int P) {
do {
if (x == head[x]) {
int up = d[x] - d[p[x][0]];
if (up >= P) {
if (up == P) return p[x][0];
return x;
}
P -= up;
x = p[x][0];
} else {
if (pos[x] - pos[head[x]] >= P) {
if (buf[x - P]) return buf[x - P];
return buf[x - P + 1];
}
P -= pos[x] - pos[head[x]];
x = head[x];
}
} while(x);
return 0;
}
void calc(int x, int P, int y, int& ad, int& ar) {
if (P < T) {
ad = 0;
for (int i = 17; x != y && i >= 0; --i)
if (d[ pp[x][P][i] ] >= d[y]) {
x = pp[x][P][i];
ad += (1 << i);
}
ar = d[x] - d[y];
} else {
ad = 0;
do {
int nx = next(x, P);
if (d[nx] < d[y]) break;
x = nx;
++ad;
} while(true);
ar = d[x] - d[y];
}
}
int main() {
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
//cerr << sizeof(pp) << endl;
int n;
scanf("%d", &n);
for (int i = 1; i < n; ++i) {
int x, y, d;
scanf("%d%d%d", &x, &y, &d);
g[x].push_back(make_pair(y, d));
g[y].push_back(make_pair(x, d));
}
d[0] = w[0] = -1;
dfs(1);
build(1);
int q;
scanf("%d", &q);
while (q--) {
int x, y, p;
scanf("%d%d%d", &x, &y, &p);
int z = lca(x, y);
int d1, d2, r1, r2;
calc(x, p, z, d1, r1);
calc(y, p, z, d2, r2);
printf("%d\n", d1 + d2 + ((r1 + r2) > 0) + ((r1 + r2) > p));
}
return 0;
}
|
#pragma once
#include <vector>
enum TaskPriority {
TP_ENGINE = 10,
TP_GAME = 5
};
class Task
{
friend class Kernel;
public:
Task(void);
~Task(void);
virtual bool init() { return true; };
virtual void pause() { };
virtual bool stop() { return true; };
private:
virtual void run() {};
int state;
int priority;
};
class Kernel
{
public:
Kernel();
~Kernel();
bool AddTask(Task *tNewTask);
bool Init();
void Run();
void Pause(int minPriority);
bool Stop();
private:
std::vector<Task *> tasks;
};
|
#include"food.h"
Food::Food()
{
x = 5;
y = 6;
}
void Food::printfood()
{
gotoxy(x*2, y);
cout << "★";
}
void Food::creatfood()
{
x = rand() % high + 1;
y = rand() % with + 1;
}
void Food::textfood(Snakecoor *head)
{
int T = 0;
Snakecoor *p=head;
while (T < Max)
{
if (x == head->x&&y == head->y)
T++;
else
break;
}
if (T == Max)
setfood(head);
}
void Food::setfood(Snakecoor *head)
{
if (1 == head->x)
{
x = high;
y = head->y;
}
else if (high == head->y)
{
x = 1;
y = head->y;
}
else
x = head->x+1, y = head->y;
}
|
// Copyright (c) 2016-2021 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#pragma once
#include <pika/config.hpp>
#include <pika/async_base/traits/is_launch_policy.hpp>
#include <pika/execution/traits/executor_traits.hpp>
#include <pika/execution_base/execution.hpp>
#include <type_traits>
#include <utility>
namespace pika::parallel::execution {
///////////////////////////////////////////////////////////////////////////
namespace detail {
/// \cond NOINTERNAL
template <typename Category1, typename Category2>
struct is_not_weaker : std::false_type
{
};
template <typename Category>
struct is_not_weaker<Category, Category> : std::true_type
{
};
template <>
struct is_not_weaker<pika::execution::parallel_execution_tag,
pika::execution::unsequenced_execution_tag> : std::true_type
{
};
template <>
struct is_not_weaker<pika::execution::sequenced_execution_tag,
pika::execution::unsequenced_execution_tag> : std::true_type
{
};
template <>
struct is_not_weaker<pika::execution::sequenced_execution_tag,
pika::execution::parallel_execution_tag> : std::true_type
{
};
/// \endcond
} // namespace detail
/// Rebind the type of executor used by an execution policy. The execution
/// category of Executor shall not be weaker than that of ExecutionPolicy.
template <typename ExPolicy, typename Executor, typename Parameters>
struct rebind_executor
{
/// \cond NOINTERNAL
using policy_type = std::decay_t<ExPolicy>;
using executor_type = std::decay_t<Executor>;
using parameters_type = std::decay_t<Parameters>;
using category1 = typename policy_type::execution_category;
using category2 = typename pika::traits::executor_execution_category<executor_type>::type;
static_assert(detail::is_not_weaker<category2, category1>::value,
"detail::is_not_weaker<category2, category1>::value");
/// \endcond
/// The type of the rebound execution policy
using type = typename policy_type::template rebind<executor_type, parameters_type>::type;
};
//////////////////////////////////////////////////////////////////////////
struct create_rebound_policy_t
{
template <typename ExPolicy, typename Executor, typename Parameters>
constexpr decltype(auto)
operator()(ExPolicy&&, Executor&& exec, Parameters&& parameters) const
{
using rebound_type = typename rebind_executor<ExPolicy, Executor, Parameters>::type;
return rebound_type(PIKA_FORWARD(Executor, exec), PIKA_FORWARD(Parameters, parameters));
}
};
inline constexpr create_rebound_policy_t create_rebound_policy{};
} // namespace pika::parallel::execution
|
#include <stdio.h>
int main() {
int sas, nar, menor, maior;
printf("Digite o primeiro valor: ");
scanf("%d", &sas);
printf("Digite o segundo valor: ");
scanf("%d", &nar);
if (sas <= nar) {
menor = sas;
maior = nar;
}
else {
menor = nar;
maior = sas;
}
printf("Os numeros em ordem crescente ficam: %d e %d", menor, maior);
}
|
// Created on: 1998-04-02
// Created by: Christian CAILLET
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESSelect_SignLevelNumber_HeaderFile
#define _IGESSelect_SignLevelNumber_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <IFSelect_Signature.hxx>
#include <Standard_CString.hxx>
class Standard_Transient;
class Interface_InterfaceModel;
class IGESSelect_SignLevelNumber;
DEFINE_STANDARD_HANDLE(IGESSelect_SignLevelNumber, IFSelect_Signature)
//! Gives D.E. Level Number under two possible forms :
//! * for counter : "LEVEL nnnnnnn", " NO LEVEL", " LEVEL LIST"
//! * for selection : "/nnn/", "/0/", "/1/2/nnn/"
//!
//! For matching, giving /nn/ gets any entity attached to level nn
//! whatever simple or in a level list
class IGESSelect_SignLevelNumber : public IFSelect_Signature
{
public:
//! Creates a SignLevelNumber
//! <countmode> True : values are naturally displayed
//! <countmode> False: values are separated by slashes
//! in order to allow selection by signature by Draw or C++
Standard_EXPORT IGESSelect_SignLevelNumber(const Standard_Boolean countmode);
//! Returns the value (see above)
Standard_EXPORT Standard_CString Value (const Handle(Standard_Transient)& ent, const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IGESSelect_SignLevelNumber,IFSelect_Signature)
protected:
private:
Standard_Boolean thecountmode;
};
#endif // _IGESSelect_SignLevelNumber_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Michal Zajaczkowski
*/
#ifndef _ST_ADDITIONCHECKER_H_INCLUDED_
#define _ST_ADDITIONCHECKER_H_INCLUDED_
#ifdef AUTO_UPDATE_SUPPORT
#ifdef SELFTEST
#include "adjunct/autoupdate/additionchecker.h"
#include "adjunct/autoupdate/additioncheckerlistener.h"
class ST_AdditionChecker:
public AdditionChecker,
public AdditionCheckerListener
{
public:
ST_AdditionChecker();
OP_STATUS Init();
OP_STATUS CheckForAddition(UpdatableResource::UpdatableResourceType type, const char* key, BOOL is_resource_expected);
void OnAdditionResolved(UpdatableResource::UpdatableResourceType type, const OpStringC& key, UpdatableResource* resource);
void OnAdditionResolveFailed(UpdatableResource::UpdatableResourceType type, const OpStringC& key);
private:
UpdatableResource::UpdatableResourceType m_expected_type;
OpString m_expected_key;
BOOL m_is_resource_expected;
};
#endif
#endif
#endif
|
/******************************************************************************************************//**
* @file filefilterwindow.cpp
* @brief 后缀名过滤 源文件
*
* 后缀名过滤
* 配置后缀名 保存配置 恢复配置 自定义后缀名
* @author coolweedman
* @version V1.00
* @date 2016-7-13
*********************************************************************************************************/
#include "filefilterwindow.h"
#include "ui_filefilterwindow.h"
#include <QSettings>
#include <QDebug>
/**********************************************************************************************************
宏定义
**********************************************************************************************************/
#define FFW_CFG_FILE_NAME ( "Cfg/FileFilter.ini" )
#define FFW_CFG_FILE_C ( "C" )
#define FFW_CFG_FILE_H ( "H" )
#define FFW_CFG_FILE_CPP ( "CPP" )
#define FFW_CFG_FILE_JAVA ( "JAVA" )
#define FFW_CFG_FILE_CS ( "CS" )
#define FFW_CFG_FILE_TXT ( "TXT" )
#define FFW_CFG_FILE_OTHER ( "OHTER" )
#define FFW_CFG_FILE_TEXT ( "TEXT" )
/**
* @fn FileFilterWindow::FileFilterWindow(QWidget *parent)
* @brief 文件过滤配置 构造函数
* @param [in] parent 父窗口
* @return 无
*/
FileFilterWindow::FileFilterWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::FileFilterWindow)
{
ui->setupUi(this);
mpVecStrFileFilter = new QVector<QString>();
ffwReStore();
}
/**
* @fn FileFilterWindow::~FileFilterWindow()
* @brief 文件过滤配置 析构函数
* @return 无
*/
FileFilterWindow::~FileFilterWindow()
{
ffwSave();
delete mpVecStrFileFilter;
delete ui;
}
/**
* @fn FileFilterWindow::ffwSave(void)
* @brief 文件过滤配置 保存配置
* @return 无
*/
void FileFilterWindow::ffwSave(void)
{
ffwUi2Stru();
ffwStru2Setting();
}
/**
* @fn FileFilterWindow::ffwReStore(void)
* @brief 文件过滤配置 恢复配置
* @return 无
*/
void FileFilterWindow::ffwReStore(void)
{
ffwSetting2Stru();
ffwStru2Ui();
ffwStru2String();
}
/**
* @fn FileFilterWindow::ffwUi2Stru(void)
* @brief 文件过滤配置 UI转结构体
* @return 无
*/
void FileFilterWindow::ffwUi2Stru(void)
{
msFileFilterStru.bC = ui->checkBoxC->isChecked();
msFileFilterStru.bH = ui->checkBoxH->isChecked();
msFileFilterStru.bCpp = ui->checkBoxCpp->isChecked();
msFileFilterStru.bJava = ui->checkBoxJava->isChecked();
msFileFilterStru.bCs = ui->checkBoxCs->isChecked();
msFileFilterStru.bTxt = ui->checkBoxTxt->isChecked();
msFileFilterStru.bOther = ui->checkBoxOther->isChecked();
msFileFilterStru.strOtherText = ui->textEditFilterText->toPlainText();
}
/**
* @fn FileFilterWindow::ffwStru2Ui(void)
* @brief 文件过滤配置 结构体转UI
* @return 无
*/
void FileFilterWindow::ffwStru2Ui(void)
{
ui->checkBoxC->setChecked( msFileFilterStru.bC );
ui->checkBoxH->setChecked( msFileFilterStru.bH );
ui->checkBoxCpp->setChecked( msFileFilterStru.bCpp );
ui->checkBoxJava->setChecked( msFileFilterStru.bJava );
ui->checkBoxCs->setChecked( msFileFilterStru.bCs );
ui->checkBoxTxt->setChecked( msFileFilterStru.bTxt );
ui->checkBoxOther->setChecked( msFileFilterStru.bOther );
ui->textEditFilterText->setEnabled( msFileFilterStru.bOther );
ui->textEditFilterText->setText( msFileFilterStru.strOtherText );
}
/**
* @fn FileFilterWindow::ffwSetting2Stru(void)
* @brief 文件过滤配置 配置转结构体
* @return 无
*/
void FileFilterWindow::ffwSetting2Stru(void)
{
QSettings *pSetting = new QSettings( FFW_CFG_FILE_NAME, QSettings::IniFormat );
msFileFilterStru.bC = pSetting->value(FFW_CFG_FILE_C, true).toBool();
msFileFilterStru.bH = pSetting->value(FFW_CFG_FILE_H, true).toBool();
msFileFilterStru.bCpp = pSetting->value(FFW_CFG_FILE_CPP, true).toBool();
msFileFilterStru.bJava = pSetting->value(FFW_CFG_FILE_JAVA, false).toBool();
msFileFilterStru.bCs = pSetting->value(FFW_CFG_FILE_CS, false).toBool();
msFileFilterStru.bTxt = pSetting->value(FFW_CFG_FILE_TXT, false).toBool();
msFileFilterStru.bOther = pSetting->value(FFW_CFG_FILE_OTHER, false).toBool();
msFileFilterStru.strOtherText = pSetting->value(FFW_CFG_FILE_TEXT, "").toString();
delete pSetting;
}
/**
* @fn FileFilterWindow::ffwStru2Setting(void)
* @brief 文件过滤配置 结构体转配置
* @return 无
*/
void FileFilterWindow::ffwStru2Setting(void)
{
QSettings *pSetting = new QSettings( FFW_CFG_FILE_NAME, QSettings::IniFormat );
pSetting->setValue( FFW_CFG_FILE_C, msFileFilterStru.bC );
pSetting->setValue( FFW_CFG_FILE_H, msFileFilterStru.bH );
pSetting->setValue( FFW_CFG_FILE_CPP, msFileFilterStru.bCpp );
pSetting->setValue( FFW_CFG_FILE_JAVA, msFileFilterStru.bJava );
pSetting->setValue( FFW_CFG_FILE_CS, msFileFilterStru.bCs );
pSetting->setValue( FFW_CFG_FILE_TXT, msFileFilterStru.bTxt );
pSetting->setValue( FFW_CFG_FILE_OTHER, msFileFilterStru.bOther );
pSetting->setValue( FFW_CFG_FILE_TEXT, msFileFilterStru.strOtherText );
delete pSetting;
}
/**
* @fn FileFilterWindow::ffwStru2String(void)
* @brief 文件过滤配置 结构体转过滤字符串
* @return 无
*/
void FileFilterWindow::ffwStru2String(void)
{
mpVecStrFileFilter->clear();
if ( msFileFilterStru.bC ) {
mpVecStrFileFilter->push_back( "*.c" );
}
if ( msFileFilterStru.bH ) {
mpVecStrFileFilter->push_back( "*.h" );
}
if ( msFileFilterStru.bCpp ) {
mpVecStrFileFilter->push_back( "*.cpp" );
}
if ( msFileFilterStru.bJava ) {
mpVecStrFileFilter->push_back( "*.java" );
}
if ( msFileFilterStru.bCs ) {
mpVecStrFileFilter->push_back( "*.cs" );
}
if ( msFileFilterStru.bTxt ) {
mpVecStrFileFilter->push_back( "*.txt" );
}
if ( msFileFilterStru.bOther ) {
mpVecStrFileFilter->clear();
QStringList strList = msFileFilterStru.strOtherText.split( "\n" );
for ( int i=0; i<strList.length(); i++ ) {
mpVecStrFileFilter->push_back( strList.at(i) );
qDebug()<<mpVecStrFileFilter->at(i);
}
}
}
/**
* @fn FileFilterWindow::ffwFilterGet(QStringList &rFilter)
* @brief 文件过滤配置 获取过滤字符串
* @param [out] rFilter 过滤字符串
* @return 无
*/
void FileFilterWindow::ffwFilterGet(QStringList &rFilter)
{
rFilter.clear();
for ( int i=0; i<mpVecStrFileFilter->length(); i++ ) {
rFilter.push_back( mpVecStrFileFilter->at(i) );
}
}
void FileFilterWindow::on_checkBoxOther_toggled(bool checked)
{
ui->textEditFilterText->setEnabled( checked );
}
void FileFilterWindow::on_pushButtonOk_clicked()
{
ffwUi2Stru();
ffwStru2String();
emit ffwFilterSig( *mpVecStrFileFilter );
this->close();
}
void FileFilterWindow::on_pushButtonCancel_clicked()
{
this->close();
}
/**********************************************************************************************************
END FILE
**********************************************************************************************************/
|
// Created on: 1999-06-17
// Created by: data exchange team
// Copyright (c) 1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _ShapeCustom_ConvertToBSpline_HeaderFile
#define _ShapeCustom_ConvertToBSpline_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <ShapeCustom_Modification.hxx>
#include <GeomAbs_Shape.hxx>
class TopoDS_Face;
class Geom_Surface;
class TopLoc_Location;
class TopoDS_Edge;
class Geom_Curve;
class TopoDS_Vertex;
class gp_Pnt;
class Geom2d_Curve;
class ShapeCustom_ConvertToBSpline;
DEFINE_STANDARD_HANDLE(ShapeCustom_ConvertToBSpline, ShapeCustom_Modification)
//! implement a modification for BRepTools
//! Modifier algorithm. Converts Surface of
//! Linear Exctrusion, Revolution and Offset
//! surfaces into BSpline Surface according to
//! flags.
class ShapeCustom_ConvertToBSpline : public ShapeCustom_Modification
{
public:
Standard_EXPORT ShapeCustom_ConvertToBSpline();
//! Sets mode for conversion of Surfaces of Linear
//! extrusion.
Standard_EXPORT void SetExtrusionMode (const Standard_Boolean extrMode);
//! Sets mode for conversion of Surfaces of Revolution.
Standard_EXPORT void SetRevolutionMode (const Standard_Boolean revolMode);
//! Sets mode for conversion of Offset surfaces.
Standard_EXPORT void SetOffsetMode (const Standard_Boolean offsetMode);
//! Sets mode for conversion of Plane surfaces.
Standard_EXPORT void SetPlaneMode (const Standard_Boolean planeMode);
//! Returns Standard_True if the face <F> has been
//! modified. In this case, <S> is the new geometric
//! support of the face, <L> the new location, <Tol>
//! the new tolerance. Otherwise, returns
//! Standard_False, and <S>, <L>, <Tol> are not
//! significant.
Standard_EXPORT Standard_Boolean NewSurface (const TopoDS_Face& F, Handle(Geom_Surface)& S, TopLoc_Location& L, Standard_Real& Tol, Standard_Boolean& RevWires, Standard_Boolean& RevFace) Standard_OVERRIDE;
//! Returns Standard_True if the edge <E> has been
//! modified. In this case, <C> is the new geometric
//! support of the edge, <L> the new location, <Tol>
//! the new tolerance. Otherwise, returns
//! Standard_False, and <C>, <L>, <Tol> are not
//! significant.
Standard_EXPORT Standard_Boolean NewCurve (const TopoDS_Edge& E, Handle(Geom_Curve)& C, TopLoc_Location& L, Standard_Real& Tol) Standard_OVERRIDE;
//! Returns Standard_True if the vertex <V> has been
//! modified. In this case, <P> is the new geometric
//! support of the vertex, <Tol> the new tolerance.
//! Otherwise, returns Standard_False, and <P>, <Tol>
//! are not significant.
Standard_EXPORT Standard_Boolean NewPoint (const TopoDS_Vertex& V, gp_Pnt& P, Standard_Real& Tol) Standard_OVERRIDE;
//! Returns Standard_True if the edge <E> has a new
//! curve on surface on the face <F>.In this case, <C>
//! is the new geometric support of the edge, <L> the
//! new location, <Tol> the new tolerance.
//!
//! Otherwise, returns Standard_False, and <C>, <L>,
//! <Tol> are not significant.
//!
//! <NewE> is the new edge created from <E>. <NewF>
//! is the new face created from <F>. They may be useful.
Standard_EXPORT Standard_Boolean NewCurve2d (const TopoDS_Edge& E, const TopoDS_Face& F, const TopoDS_Edge& NewE, const TopoDS_Face& NewF, Handle(Geom2d_Curve)& C, Standard_Real& Tol) Standard_OVERRIDE;
//! Returns Standard_True if the Vertex <V> has a new
//! parameter on the edge <E>. In this case, <P> is
//! the parameter, <Tol> the new tolerance.
//! Otherwise, returns Standard_False, and <P>, <Tol>
//! are not significant.
Standard_EXPORT Standard_Boolean NewParameter (const TopoDS_Vertex& V, const TopoDS_Edge& E, Standard_Real& P, Standard_Real& Tol) Standard_OVERRIDE;
//! Returns the continuity of <NewE> between <NewF1>
//! and <NewF2>.
//!
//! <NewE> is the new edge created from <E>. <NewF1>
//! (resp. <NewF2>) is the new face created from <F1>
//! (resp. <F2>).
Standard_EXPORT GeomAbs_Shape Continuity (const TopoDS_Edge& E, const TopoDS_Face& F1, const TopoDS_Face& F2, const TopoDS_Edge& NewE, const TopoDS_Face& NewF1, const TopoDS_Face& NewF2) Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(ShapeCustom_ConvertToBSpline,ShapeCustom_Modification)
protected:
private:
Standard_EXPORT Standard_Boolean IsToConvert (const Handle(Geom_Surface)& S, Handle(Geom_Surface)& SS) const;
Standard_Boolean myExtrMode;
Standard_Boolean myRevolMode;
Standard_Boolean myOffsetMode;
Standard_Boolean myPlaneMode;
};
#endif // _ShapeCustom_ConvertToBSpline_HeaderFile
|
#include <iostream>
using namespace std;
//It is probably a good idea to implement Stack as a module,
//like the example from the lecture was done.
//3ICE: No thanks :)
class Stack {
private:
struct Cell {
int data;
Cell* next_ptr;
};
Cell* first_ptr;
public:
//3ICE: Totally not required, default constructor does the same.
Stack():first_ptr{nullptr}{}
//3ICE: Destroy each Cell, deconstructing the chain link by link.
~Stack(){
Cell* p = first_ptr;
while (p != nullptr){
Cell* q = p->next_ptr;
delete p;
p = q;
}
first_ptr = nullptr;
}
// empty will only return true, if there are no elements
// in the stack i.e. the linked list is empty.
bool empty() const{
return first_ptr==nullptr;
}
// push_front will insert the new_value on top of the stack
// i.e. in front of the linked list.
void push_front(int new_value){
Cell* c = new Cell;
c->data=new_value;
c->next_ptr=first_ptr;
first_ptr=c;
}
// pop_front will remove the topmost value from the stack
// i.e. the first element of the linked list. The removed
// value will be stored into removed_value and the return
// value will be true if the removal of an element is successfull.
// If not (i.e. the stack is empty), return value is false.
bool pop_front(int& removed_value){
Cell* t = first_ptr;
first_ptr= first_ptr->next_ptr;
removed_value=t->data;
delete t;
return !this->empty();
}
// Print the elements stored in the stack on top to bottom
// order. This method is mainly for testing purposes.
void print() const{
Cell* p = first_ptr;
while (p != nullptr){
cout << p->data << " ";
p = p->next_ptr;
}
cout<<endl;
}
};
//Of course you also need to implement some sort of
//main function to be able to test your Stack class.
int main(){
cout<<"Hello!"<<endl;
cout<<"Creating a stack, s"<<endl;
Stack s;
if(s.empty()) cout<< "Yes, stack s is empty."<<endl;
s.push_front(3);
cout<<"Added one element to s, my favorite number (3). Here it is:"<<endl;
s.print();
if(!s.empty()) cout<< "And the stack is no longer empty."<<endl;
int x;
s.pop_front(x);
cout<<"Removed element "<<x<<" from stack s."<<endl;
if(s.empty()) cout<< "And stack s is empty again... So, let's fill it up!"<<endl;
for (int i = 0; i <= 10; ++i) {
s.push_front(i);
}
cout<<"All numbers 0-10 pushed into stack s. Here they are:"<<endl;
s.print();
cout<<"Oops, that's in reverse! Luckily we can flip it easily."<<endl;
cout<<"Gotta use two stacks for this... Creating a second stack, t"<<endl;
Stack t;
if(t.empty()) cout<< "Of course, stack t is empty to begin with."<<endl;
cout<<"All elements popped from stack s, pushed to stack t, one by one."<<endl;
for (int i = 0; i <= 10; ++i) {
s.pop_front(x);
t.push_front(x);
}
cout<<"Numbers 0-10 are stored in stack t now. Printing reversed:"<<endl;
t.print();
if(s.empty()) cout<< "And finally, stack s is of course empty again, since we popped everything it had."<<endl;
cout << "Bye!" << endl;
Stack* testing_delete= new Stack;
testing_delete->push_front(1);testing_delete->push_front(2);testing_delete->push_front(3);
testing_delete->print();
delete testing_delete;
cout << "p.s.: Deleting works too, by the way. (If this line is printed.)" << endl;
return 0;
}
|
#include <stdio.h>
#include "peconv.h"
using namespace peconv;
#define VERSION "0.4"
#define PARAM_RAW_TO_VIRTUAL "/r2v"
#define PARAM_OUT_FILE "/out"
#define PARAM_BASE "/base"
#define PARAM_IN_FILE "/in"
#define PARAM_REALIGN_RAW "/vraw"
typedef struct {
std::string in_file;
std::string out_file;
ULONGLONG load_base;
bool mode_r_to_v;
bool realign_raw;
} t_unmapper_params;
void init_params(t_unmapper_params ¶ms)
{
params.in_file = "";
params.out_file = "out.exe";
params.load_base = 0;
params.mode_r_to_v = false;
params.realign_raw = false;
}
bool remap_pe_file(t_unmapper_params ¶ms)
{
if (params.in_file.length() == 0 || params.out_file.length() == 0) return false;
//Read input module:
std::cout << "filename: " << params.in_file << "\n";
size_t in_size = 0;
BYTE* in_buf = peconv::read_from_file(params.in_file.c_str(), in_size);
BYTE* out_buf = nullptr;
size_t out_size = 0;
if (params.mode_r_to_v) {
std::cout << "MODE: Raw -> Virtual\n";
out_buf = peconv::load_pe_module(in_buf, in_size, out_size, false, false);
if (out_buf) {
ULONGLONG base = peconv::get_image_base(out_buf);
if (!relocate_module(out_buf, out_size, (ULONGLONG) base)) {
std::cout << "Could not relocate the module!\n";
}
}
}
else {
std::cout << "MODE: Virtual -> Raw\n";
if (params.realign_raw) {
std::cout << "Realign Raw to Virtual\n";
out_buf = peconv::pe_realign_raw_to_virtual(in_buf, in_size, params.load_base, out_size);
}
else {
out_buf = peconv::pe_virtual_to_raw(in_buf, in_size, params.load_base, out_size, false);
}
}
if (!out_buf) {
std::cerr << "Failed to convert!\n";
peconv::free_pe_buffer(in_buf, in_size);
return false;
}
// Write output
bool isOk = peconv::dump_to_file(params.out_file.c_str(), out_buf, out_size);
if (!isOk) {
std::cerr << "Failed to save file: " << params.out_file << "\n";
}
peconv::free_pe_buffer(in_buf, in_size);
peconv::free_pe_buffer(out_buf, out_size);
return isOk;
}
void print_help()
{
std::cout << "Required: \n";
std::cout << PARAM_IN_FILE;
std::cout << "\t: Input file name\n";
std::cout << PARAM_BASE;
std::cout << "\t: Base address where the image was loaded: in hex\n";
std::cout << "\nOptional: \n";
std::cout << PARAM_OUT_FILE;
std::cout << "\t: Output file name\n";
std::cout << PARAM_RAW_TO_VIRTUAL;
std::cout << "\t: Switch conversion mode: raw input -> virtual output\n";
std::cout << "\t(Default mode: virtual input -> raw output)\n";
std::cout << PARAM_REALIGN_RAW;
std::cout << "\t: Change raw alignment: copy from virtual\n";
}
int main(int argc, char *argv[])
{
t_unmapper_params params;
init_params(params);
if (argc < 3) {
std::cout << "[ pe_unmapper v" << VERSION << "]\n";
print_help();
std::cout << "---" << std::endl;
system("pause");
return 0;
}
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], PARAM_RAW_TO_VIRTUAL)) {
params.mode_r_to_v = true;
}
else if (!strcmp(argv[i], PARAM_REALIGN_RAW)) {
params.realign_raw = true;
}
else if (!strcmp(argv[i], PARAM_OUT_FILE) && (i + 1) < argc) {
params.out_file = argv[i + 1];
}
else if (!strcmp(argv[i], PARAM_IN_FILE) && (i + 1) < argc) {
params.in_file = argv[i + 1];
}
else if (!strcmp(argv[i], PARAM_BASE) && (i + 1) < argc) {
ULONGLONG loadBase = 0;
if (sscanf(argv[i + 1], "%llX", &loadBase) == 0) {
sscanf(argv[i + 1], "%#llX", &loadBase);
}
params.load_base = loadBase;
}
}
if (remap_pe_file(params)) {
std::cout << "Saved output to: " << params.out_file << std::endl;
return 0;
}
return -1;
}
|
#pragma once
#include <string>
using std::string;
using std::to_string;
enum LogLevel { LOG_INFO, LOG_OK, LOG_WARNING, LOG_ERROR };
void logger(LogLevel level, string message);
|
/*
* Stopping Times
* Copyright (C) Leonardo Marchetti 2011 <leonardomarchetti@gmail.com>
*/
template <typename FP>
Functor1D<FP>::Functor1D(){}
template <typename FP>
Functor1D<FP>::~Functor1D(){}
template <typename FP>
FP Functor1D<FP>::operator()(FP x){
return 0.0;
}
|
#include <iostream>
#include <vector>
using namespace std;
void pass_by_value(int x) {
x = 99;
cout << "inside PbV function x = " << x << endl;
}
//notice the different in the definition
void pass_by_reference(int &x) {
x = 10000;
cout << "inside PbR function x = " << x << endl;
}
int main() {
cout << "Pass by Value, direct" << endl;
pass_by_value(10);
cout << endl;
int x = 20;
cout << "Pass by value, variable" << endl;
pass_by_value(x);
cout << "outside PbR function x = " << x << endl;
cout << endl;
cout << "Pass by reference" << endl;
pass_by_reference(x);
cout << "outside PbR function x = " << x << endl;
//the following line cannot be compiled
//because we need reference
//pass_by_reference(20);
}
|
class BankAccount{
private:
double balance;
public:
BankAccount(){
balance = 0;
}
}
|
/*
* Copyright (C) 2011 Thomas Kemmer <tkemmer@computer.org>
*
* http://code.google.com/p/stlencoders/
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef STLENCODERS_BASE64IMPL_HPP
#define STLENCODERS_BASE64IMPL_HPP
#include "decstr.hpp"
#include "dectbl.hpp"
namespace stlencoders {
namespace impl {
template<char C> struct b64 { enum { v = -1 }; };
template<> struct b64<'A'> { enum { v = 0x00 }; };
template<> struct b64<'a'> { enum { v = 0x1a }; };
template<> struct b64<'B'> { enum { v = 0x01 }; };
template<> struct b64<'b'> { enum { v = 0x1b }; };
template<> struct b64<'C'> { enum { v = 0x02 }; };
template<> struct b64<'c'> { enum { v = 0x1c }; };
template<> struct b64<'D'> { enum { v = 0x03 }; };
template<> struct b64<'d'> { enum { v = 0x1d }; };
template<> struct b64<'E'> { enum { v = 0x04 }; };
template<> struct b64<'e'> { enum { v = 0x1e }; };
template<> struct b64<'F'> { enum { v = 0x05 }; };
template<> struct b64<'f'> { enum { v = 0x1f }; };
template<> struct b64<'G'> { enum { v = 0x06 }; };
template<> struct b64<'g'> { enum { v = 0x20 }; };
template<> struct b64<'H'> { enum { v = 0x07 }; };
template<> struct b64<'h'> { enum { v = 0x21 }; };
template<> struct b64<'I'> { enum { v = 0x08 }; };
template<> struct b64<'i'> { enum { v = 0x22 }; };
template<> struct b64<'J'> { enum { v = 0x09 }; };
template<> struct b64<'j'> { enum { v = 0x23 }; };
template<> struct b64<'K'> { enum { v = 0x0a }; };
template<> struct b64<'k'> { enum { v = 0x24 }; };
template<> struct b64<'L'> { enum { v = 0x0b }; };
template<> struct b64<'l'> { enum { v = 0x25 }; };
template<> struct b64<'M'> { enum { v = 0x0c }; };
template<> struct b64<'m'> { enum { v = 0x26 }; };
template<> struct b64<'N'> { enum { v = 0x0d }; };
template<> struct b64<'n'> { enum { v = 0x27 }; };
template<> struct b64<'O'> { enum { v = 0x0e }; };
template<> struct b64<'o'> { enum { v = 0x28 }; };
template<> struct b64<'P'> { enum { v = 0x0f }; };
template<> struct b64<'p'> { enum { v = 0x29 }; };
template<> struct b64<'Q'> { enum { v = 0x10 }; };
template<> struct b64<'q'> { enum { v = 0x2a }; };
template<> struct b64<'R'> { enum { v = 0x11 }; };
template<> struct b64<'r'> { enum { v = 0x2b }; };
template<> struct b64<'S'> { enum { v = 0x12 }; };
template<> struct b64<'s'> { enum { v = 0x2c }; };
template<> struct b64<'T'> { enum { v = 0x13 }; };
template<> struct b64<'t'> { enum { v = 0x2d }; };
template<> struct b64<'U'> { enum { v = 0x14 }; };
template<> struct b64<'u'> { enum { v = 0x2e }; };
template<> struct b64<'V'> { enum { v = 0x15 }; };
template<> struct b64<'v'> { enum { v = 0x2f }; };
template<> struct b64<'W'> { enum { v = 0x16 }; };
template<> struct b64<'w'> { enum { v = 0x30 }; };
template<> struct b64<'X'> { enum { v = 0x17 }; };
template<> struct b64<'x'> { enum { v = 0x31 }; };
template<> struct b64<'Y'> { enum { v = 0x18 }; };
template<> struct b64<'y'> { enum { v = 0x32 }; };
template<> struct b64<'Z'> { enum { v = 0x19 }; };
template<> struct b64<'z'> { enum { v = 0x33 }; };
template<> struct b64<'0'> { enum { v = 0x34 }; };
template<> struct b64<'1'> { enum { v = 0x35 }; };
template<> struct b64<'2'> { enum { v = 0x36 }; };
template<> struct b64<'3'> { enum { v = 0x37 }; };
template<> struct b64<'4'> { enum { v = 0x38 }; };
template<> struct b64<'5'> { enum { v = 0x39 }; };
template<> struct b64<'6'> { enum { v = 0x3a }; };
template<> struct b64<'7'> { enum { v = 0x3b }; };
template<> struct b64<'8'> { enum { v = 0x3c }; };
template<> struct b64<'9'> { enum { v = 0x3d }; };
template<> struct b64<'+'> { enum { v = 0x3e }; };
template<> struct b64<'/'> { enum { v = 0x3f }; };
template<char C> struct b64url: public b64<C> { };
template<> struct b64url<'+'> { enum { v = -1 }; };
template<> struct b64url<'/'> { enum { v = -1 }; };
template<> struct b64url<'-'> { enum { v = 0x3e }; };
template<> struct b64url<'_'> { enum { v = 0x3f }; };
}
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifdef WBXML_SUPPORT
#ifndef WBXML_H
#define WBXML_H
class CharConverter;
class HLDocProfile;
typedef OP_STATUS OP_WXP_STATUS;
/// Dummy class for constants used as return values from the WBXML_Parser
class WXParseStatus : public OpStatus
{
public:
enum
{
OK = 0, ///< guess: everything OK, no special actions required
BUFFER_FULL = USER_SUCCESS + 1, ///< the output buffer is full
NEED_GROW = USER_SUCCESS + 2, ///< no end tag found, need a larger buffer
WRONG_VERSION = USER_ERROR + 1, ///< wrong version given
UNEXPECTED_END = USER_ERROR + 2, ///< end of buffer reached unexpected
NOT_WELL_FORMED = USER_ERROR + 3 ///< the code is not well formed
};
};
/// Elements for the tagstack in the WBXML_Parser
class WBXML_StackElm
{
private:
WBXML_StackElm* m_next; ///< next entry in the stack
public:
WBXML_StackElm() : m_next(NULL) {}
virtual ~WBXML_StackElm() {};
void Precede(WBXML_StackElm *elm) { m_next = elm; }
WBXML_StackElm* GetNext() { return m_next; }
};
class WBXML_TagElm : public WBXML_StackElm
{
private:
uni_char* m_tag; ///< tag string
BOOL m_quote; ///< does the tag need WML style '$' quoting
public:
/// Constructor. \param[in] need_quoting Tells if '$'
/// should be quoted with '$$' WML style
WBXML_TagElm(BOOL need_quoting)
: WBXML_StackElm(),
m_tag(NULL),
m_quote(need_quoting) {};
virtual ~WBXML_TagElm() { OP_DELETEA(m_tag); }
void SetTagNameL(const uni_char *tag);
const uni_char* GetTagName() { return m_tag; }
BOOL GetQuoting() { return m_quote; }
};
class WBXML_AttrElm : public WBXML_StackElm
{
private:
UINT32 m_tok; ///< The token for the current element we are parsing attributes for
BOOL m_start_found; ///< Is the start of a attribute value found
BOOL m_end_found; ///< Is the end of a attribute list found
public:
WBXML_AttrElm() : m_tok(0), m_start_found(FALSE), m_end_found(FALSE) {}
void SetToken(UINT32 token) { m_tok = token; }
UINT32 GetToken() { return m_tok; }
void SetStartFound(BOOL found) { m_start_found = found; }
BOOL GetStartFound() { return m_start_found; }
void SetEndFound(BOOL found) { m_end_found = found; }
BOOL GetEndFound() { return m_end_found; }
};
class WBXML_Parser;
/// Content handler interface used for content that is specific for the
/// different document types. This interface must be implemented for all
/// the document types Opera should handle specifically (like WML).
/// Returns a element tag or attribute for the WBXML tokens in its namespace.
class WBXML_ContentHandler
{
private:
WBXML_Parser *m_parser; ///< pointer back to the parser that uses it
public:
WBXML_ContentHandler(WBXML_Parser *parser) : m_parser(parser) {}
virtual ~WBXML_ContentHandler() {}
/// Secondary constructor. Use if you need to allocate data during construction.
virtual OP_WXP_STATUS Init() { return OpStatus::OK; };
/// Returns a tag string corresponding to the given WBXML element token
virtual const uni_char* TagHandler(UINT32 tok) = 0;
/// Returns an attribute string corresponding to the given WBXML attribute token
virtual const uni_char* AttrStartHandler(UINT32 tok) = 0;
/// Returns an attribute value string corresponding to the given WBXML attribute value token
virtual const uni_char* AttrValueHandler(UINT32 tok) = 0;
/// Returns a string corresponding to the WBXML EXT_* tokens
virtual const uni_char* ExtHandlerL(UINT32 tok, const char **buf) { return 0; }
/// Returns a string corresponding to the WBXML OPAQUE element token
virtual const uni_char* OpaqueTextNodeHandlerL(const char **buf) { return 0; }
/// Returns a string corresponding to the WBXML OPAQUE attribute token
virtual const uni_char* OpaqueAttrHandlerL(const char **buf) { return 0; }
WBXML_Parser* GetParser() { return m_parser; }
};
/// The WBXML parser. Used for parsing data coded as Wireless Binary
/// coded XML (WBXML) into a textual XML document.
class WBXML_Parser
{
public:
/// Numeric type constants indicating the type of document
typedef enum
{
WX_TYPE_UNKNOWN = 0
#ifdef WML_WBXML_SUPPORT
, WX_TYPE_WML ///< A binary coded WML document
#endif // WML_WBXML_SUPPORT
#ifdef SI_WBXML_SUPPORT
, WX_TYPE_SI ///< OMA Service Indication
#endif // SI_WBXML_SUPPORT
#ifdef SL_WBXML_SUPPORT
, WX_TYPE_SL ///< OMA Service Loading
#endif // SL_WBXML_SUPPORT
#ifdef PROV_WBXML_SUPPORT
, WX_TYPE_PROV ///< OMA Provisioning
#endif // PROV_WBXML_SUPPORT
#ifdef DRMREL_WBXML_SUPPORT
, WX_TYPE_DRMREL ///< OMA DRM Rights Expression Language
#endif // DRMREL_WBXML_SUPPORT
#ifdef CO_WBXML_SUPPORT
, WX_TYPE_CO ///< OMA Cache Operation
#endif // CO_WBXML_SUPPORT
#ifdef EMN_WBXML_SUPPORT
, WX_TYPE_EMN ///< OMA E-mail notification
#endif // EMN_WBXML_SUPPORT
} Content_t;
private:
BOOL m_header_parsed; ///< TRUE if the WBXML header is fully parsed
BOOL m_more; ///< TRUE if there is more data waiting in the stream
UINT32 m_code_page; ///< The current token codepage
UINT32 m_version; ///< The WBXML version of the current document
UINT32 m_doc_type; ///< The WBXML doctype used
Content_t m_content_type; ///< Internal type of document
UINT32 m_strtbl_len; ///< Length of the document string table
char *m_strtbl; ///< Pointer to the document string table. Consecutive, nul terminated, strings
const char *m_in_buf_end; ///< Pointer to the first character after the end of the current buffer
const char *m_in_buf_committed; ///< Pointer to the last character committed from the in buffer
uni_char *m_tmp_buf; ///< Temporary buffer, used internally
int m_tmp_buf_len; ///< Length of the temporary buffer
uni_char *m_out_buf; ///< Pointer to the output buffer to append the generated XML code
unsigned m_out_buf_idx; ///< The current position into the output buffer
unsigned m_out_buf_len; ///< Max length of the ouput buffer
unsigned m_out_buf_committed; ///< Position of the last committed out data
uni_char* m_overflow_buf; ///< Buffer used when the outbuffer is full
int m_overflow_buf_len; ///< Length of the overflow buffer
int m_overflow_buf_idx; ///< Current index into the overflow buffer
InputConverter *m_char_conv; ///< Character converter to use for decoding strings
WBXML_StackElm* m_tag_stack; ///< Top of the tag stack used to keep track of open elements
WBXML_StackElm* m_tag_stack_committed; ///< The last committed element, back
WBXML_AttrElm* m_attr_parsing_indicator; ///< Pushed on the stack to indicate that we are parsing attributes
WBXML_ContentHandler **m_content_handlers; ///< Array of content handlers for the different content types
UINT32 SetDocType(UINT32 type); ///< Set the doctype and calculate internal content type
/// Commits the data generated since the last commit. Only committed data will be returned from
/// the parser. The next round of parsing will start at the last commit point.
///\param[in] buf_p The point in the input buffer to commit
void Commit2Buffer(const char *buf_p) { m_in_buf_committed = buf_p; m_out_buf_committed = m_out_buf_idx; m_tag_stack_committed = m_tag_stack; }
/// Will convert a string using the document character decoder and put it in the output buffer
///\param[in] str String to enque, need not be nul terminated
///\param[in] len Length of str
///\param[in] commit_pos
void ConvertAndEnqueueStrL(const char *str, int len, const char* commit_pos);
/// Will look up a string from the string table and convert it using the document character
/// decoder and put it in the output buffer.
///\param[in] index Index into the string table
void LookupAndEnqueueL(UINT32 index, const char* commit_pos);
void ParseHeaderL(const char **buf); ///< Parse the WBXML header
void ParseTreeL(const char **buf); ///< Parse the body of the WBXML document
void ParseAttrsL(const char **buf); ///< Parse the attributes of an element
/// Called for application specific element tokens. \param[in] tok Token
void AppSpecialTagL(UINT32 tok, const char* commit_pos);
/// Called for application specific attribute start tokens. \param[in] tok Token
void AppSpecialAttrStartL(UINT32 tok, BOOL already_in_attr, const char* commit_pos);
/// Called for application specific attribute value tokens. \param[in] tok Token
void AppSpecialAttrValueL(UINT32 tok, const char* commit_pos);
/// Called for application specific extension tokens.
///\param[in] tok Token
///\param[out] buf Pointer to buffer where application specific data can be appended.
void AppSpecialExtL(UINT32 tok, const char **buf);
/// Push a new tag on the stack. Called when start tag parsed
void PushTagL(const uni_char *tag, BOOL need_quoting);
/// Pop the last tag from the stack and put the corresponding endtag in the output buffer
void PopTagAndEnqueueL(const char* commit_pos);
/// Push the current state onto the stack to indicate that we are parsing attributes
///\param[in] tok The current element token
void PushAttrState(UINT32 tok);
/// Pop the current state off the stack when attribute parsing is done
void PopAttrState();
/// Returns TRUE if we are currently parsing attributes
BOOL IsInAttrState() { return m_tag_stack == m_attr_parsing_indicator; }
/// Grows the overflow if it is smaller than wanted_index
///\param[in] wanted_index The position in the overflow buffer you want to store things to
void GrowOverflowBufferIfNeededL(int wanted_index);
public:
WBXML_Parser();
~WBXML_Parser();
/// Secondary constructor. Will allocate memory.
OP_WXP_STATUS Init();
/// Will parse a stream of WBXML data one buffer at a time. The buffer pointer must
/// point to the character after the last parsed on subsequent calls.
///\param[in] out_buf Buffer to put the generated XML in.
///\param[out] out_buf_len Specifies the length of the output buffer in. After the
/// method returns it contains the length of the generated data.
///\param[out] buf Buffer containing raw WBXML data. After the method
/// returns it will point to the first character after the last character parsed.
///\param[in] buf_end First character after the last character in the input buffer
///\param[in] more_buffers TRUE if more data is available from the stream
OP_WXP_STATUS Parse(char *out_buf, int &out_buf_len, const char **buf, const char *buf_end, BOOL more_buffers);
/// Put a string in the output buffer. Will not be returned before a called to Commit2Buffer()
///\param[in] str String to enqueue, need not be nul terminated
///\param[in] len Length of str
///\param[in] need_quoting Will quote non-XML characters as entity references (and '$' in WML)
///\param[in] may_clear_overflow_buffer Never clear overflow buffer if this is false
void EnqueueL(const uni_char *str, int len, const char* commit_pos, BOOL need_quoting = TRUE, BOOL may_clear_overflow_buffer = TRUE);
/// Will look up a string from the string table and return a pointer to it.
///\param[in] index Index into the string table
const char* LookupStr(UINT32 index);
/// Reads the next token from the input buffer.
///\param[out] buf The current buffer pointer, will be incremented
///\param[in] is_mb_value TRUE if a WBXML multibyte value is to be read
UINT32 GetNextTokenL(const char **buf, BOOL is_mb_value = FALSE);
/// Will skip over the next nul terminated string in the input buffer.
///\param[out] buf The current buffer pointer, will be incremented
void PassNextStringL(const char **buf);
/// Checks if there are enough bytes available in the temporary buffer.
/// Will leave if there isn't enough space available.
void EnsureTmpBufLenL(int len);
uni_char* GetTmpBuf() { return m_tmp_buf; }
int GetTmpBufLen() { return m_tmp_buf_len; }
BOOL IsWml();
Content_t GetContentType() { return m_content_type; }
UINT32 GetCodePage() { return m_code_page; } ///< Returns the current codepage
};
#endif // WBXML_H
#endif // WBXML_SUPPORT
|
#include "Number.h"
namespace lispc
{
Number::Number(int val) :
isInteger(true),
intValue(val),
doubleValue((double)val) {}
Number::Number(double val) :
isInteger(false),
intValue((int)val),
doubleValue(val) {}
Number::Number(const Number& other) :
isInteger(other.isInteger),
intValue(other.intValue),
doubleValue(other.doubleValue) {}
Number& Number::operator=(const Number& other)
{
isInteger = other.isInteger;
intValue = other.intValue;
doubleValue = other.doubleValue;
return *this;
}
bool Number::is_int() const
{
return isInteger;
}
int Number::get_int() const
{
return intValue;
}
double Number::get_double() const
{
return doubleValue;
}
Number operator+(const Number& n1, const Number& n2)
{
if (n1.isInteger && n2.isInteger)
{
return Number(n1.intValue + n2.intValue);
}
else
{
return Number(n1.doubleValue + n2.doubleValue);
}
}
Number operator-(const Number& n1, const Number& n2)
{
if (n1.isInteger && n2.isInteger)
{
return Number(n1.intValue - n2.intValue);
}
else
{
return Number(n1.doubleValue - n2.doubleValue);
}
}
Number operator*(const Number& n1, const Number& n2)
{
if (n1.isInteger && n2.isInteger)
{
return Number(n1.intValue * n2.intValue);
}
else
{
return Number(n1.doubleValue * n2.doubleValue);
}
}
Number operator/(const Number& n1, const Number& n2)
{
if (n1.isInteger && n2.isInteger)
{
return Number(n1.intValue / n2.intValue);
}
else
{
return Number(n1.doubleValue / n2.doubleValue);
}
}
Number operator%(const Number& n1, const Number& n2)
{
if (n1.isInteger && n2.isInteger)
{
return Number(n1.intValue % n2.intValue);
}
else
{
return Number(fmod(n1.doubleValue, n2.doubleValue));
}
}
Number operator>(const Number& n1, const Number& n2)
{
if (n1.isInteger && n2.isInteger)
{
return (n1.intValue > n2.intValue) ? Number(1) : Number(0);
}
else
{
return (n1.doubleValue > n2.doubleValue) ? Number(1) : Number(0);
}
}
Number operator<(const Number& n1, const Number& n2)
{
if (n1.isInteger && n2.isInteger)
{
return (n1.intValue < n2.intValue) ? Number(1) : Number(0);
}
else
{
return (n1.doubleValue < n2.doubleValue) ? Number(1) : Number(0);
}
}
Number operator>=(const Number& n1, const Number& n2)
{
if (n1.isInteger && n2.isInteger)
{
return (n1.intValue >= n2.intValue) ? Number(1) : Number(0);
}
else
{
return (n1.doubleValue >= n2.doubleValue) ? Number(1) : Number(0);
}
}
Number operator<=(const Number& n1, const Number& n2)
{
if (n1.isInteger && n2.isInteger)
{
return (n1.intValue <= n2.intValue) ? Number(1) : Number(0);
}
else
{
return (n1.doubleValue <= n2.doubleValue) ? Number(1) : Number(0);
}
}
Number operator==(const Number& n1, const Number& n2)
{
if (n1.isInteger && n2.isInteger)
{
return (n1.intValue == n2.intValue) ? Number(1) : Number(0);
}
else
{
// close enough for me
return (abs(n1.doubleValue - n2.doubleValue) < 1e-6) ? Number(1) : Number(0);
}
}
std::ostream& operator<<(std::ostream& stream, const Number& number)
{
if (number.isInteger)
{
return stream << number.intValue;
}
else
{
return stream << number.doubleValue;
}
}
}
|
// Pg1_raycast_psdeo.cpp :
// CSC-561 Computer Graphics Programming Assignment 1
// Defines the entry point for the application.
#include "tiny_obj_loader.h"
#include "stdafx.h"
#include "Pg1_raycast_psdeo.h"
#include <stdlib.h>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <map>
#define MAX_LOADSTRING 100
#define SMALL_NUM 0.00000001 // anything that avoids division overflow
// dot product (3D) which allows vector operations in arguments
#define dot(u,v) ((u).x * (v).x + (u).y * (v).y + (u).z * (v).z)
//psdeo: Same method as tinyObj has for parsing input file
static inline int parseInt(const char*& token)
{
token += strspn(token, " \t");
int i = atoi(token);
token += strcspn(token, " \t\r");
return i;
}
static HWND sHwnd;
//Color
//static COLORREF redColor = RGB(255, 0, 0);
//static COLORREF blueColor = RGB(0, 0, 255);
//static COLORREF greenColor = RGB(0, 255, 0);
static COLORREF blackColor = RGB(0, 0 , 0);
static COLORREF tempColor;
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_PG1_RAYCAST_PSDEO, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PG1_RAYCAST_PSDEO));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage are only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this function
// so that the application will get 'well formed' small icons associated
// with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PG1_RAYCAST_PSDEO));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_PG1_RAYCAST_PSDEO);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
void SetWindowHandle(HWND hwnd)
{
printf("setwindowhandle");
sHwnd = hwnd;
}
void setPixel(int x, int y, COLORREF& color)
{
printf("setpixel");
if (sHwnd == NULL)
{
exit(0);
}
HDC hdc = GetDC(sHwnd);
SetPixel(hdc, x, y, color);
ReleaseDC(sHwnd, hdc);
return;
}
//_________________________________________________________________________
//psdeo: in order for intersection code to work, some modifications are required
// such as structure definitions & operator overloadings that are assumed
class Point{
public:float x;
public:float y;
public:float z;
Point* operator= (Point p)
{
return (&p);
}
}I , tempPt;
class Vector
{
public:float x;
public:float y;
public:float z;
Vector ()
{
x=0;
y=0;
z=0;
}
Vector(int i)
{
x=i;
y=i;
z=i;
}
Vector (double a,double b,double c)
{
x =a;
y=b;
z=c;
}
Vector operator= (Point p)
{
Vector v;
v.x=p.x;
v.y=p.y;
v.z=p.z;
return v;
}
Vector operator* (float lt[3])
{
Vector v1;
v1.x=x*lt[0];
v1.y=y*lt[1];
v1.z=z*lt[2];
return v1;
}
Vector mult (float r)
{
Vector v;
v.x= x*r;
v.y=y*r;
v.z=z*r;
return v;
}
Vector cross (Vector v)
{
Vector r;
r.x = y*v.z - z*v.y;
r.y = x*v.z - z*v.x;
r.z = x*v.y - y*v.x;
return r;
}
bool operator==(Vector v)
{
if (x== v.x && y==v.y && z==v.z)
return true;
else return false;
}
void normalize()
{
double len = sqrt ((x*x) + (y*y) + (z*z));
x /= len;
y /= len;
z /= len;
}
};
Point operator+ (Vector v,Point p)
{
I.x = v.x+p.x;
I.y = v.y+p.y;
I.z = v.z+p.z;
return(I);
}
Vector operator-(Point p1,Point p2)
{
Vector r;
r.x = p1.x - p2.x;
r.y = p1.y - p2.y;
r.z = p1.z - p2.z;
return r;
}
Vector operator+ (Vector v1,Vector v2)
{
Vector v;
v.x = v1.x + v2.x;
v.y = v1.y +v2.y;
v.z = v1.z + v2.z;
return v;
}
Vector operator- (Vector v1,Point v2)
{
Vector v;
v.x-= v1.x - v.x;
v.y-= v1.y - v.y;
v.z-= v1.z - v.z;
return v;
}
Vector operator-(Point v1, Vector v2)
{
Vector v;
v.x-= v1.x - v.x;
v.y-= v1.y - v.y;
v.z-= v1.z - v.z;
return v;
}
class Ray{
public:Point P0;
public:Point P1;
}R;
class Triangle{
public:Point V0;
public:Point V1;
public:Point V2;
}T;
// Copyright 2001 softSurfer, 2012 Dan Sunday
// This code may be freely used and modified for any purpose
// providing that this copyright notice is included with it.
// SoftSurfer makes no warranty for this code, and cannot be held
// liable for any real or imagined damage resulting from its use.
// Users of this code must verify correctness for their application
// intersect3D_RayTriangle(): find the 3D intersection of a ray with a triangle
// Input: a ray R, and a triangle T
// Output: *I = intersection point (when it exists)
// Return: -1 = triangle is degenerate (a segment or point)
// 0 = disjoint (no intersect)
// 1 = intersect in unique point I1
// 2 = are in the same plane
int intersect3D_RayTriangle( Ray R, Triangle T, Point* I )
{
Vector u, v, n; // triangle vectors
Vector dir, w0, w; // ray vectors
float r, a, b; // params to calc ray-plane intersect
// get triangle edge vectors and plane normal
u = T.V1 - T.V0;
v = T.V2 - T.V0;
n = u.cross(v); // cross product
if (n == (Vector)0) // triangle is degenerate
return -1; // do not deal with this case
dir = R.P1 - R.P0; // ray direction vector
w0 = R.P0 - T.V0;
a = -dot(n,w0);
b = dot(n,dir);
if (fabs(b) < SMALL_NUM) { // ray is parallel to triangle plane
if (a == 0) // ray lies in triangle plane
return 2;
else return 0; // ray disjoint from plane
}
// get intersect point of ray with triangle plane
r = a / b;
if (r < 0.0) // ray goes away from triangle
return 0; // => no intersect
// for a segment, also test if (r > 1.0) => no intersect
dir = dir.mult(r);
*I = dir+ R.P0; // intersect point of ray and plane
// is I inside T?
float uu, uv, vv, wu, wv, D;
uu = dot(u,u);
uv = dot(u,v);
vv = dot(v,v);
w = *I - T.V0;
wu = dot(w,u);
wv = dot(w,v);
D = uv * uv - uu * vv;
// get and test parametric coords
float s, t;
s = (uv * wv - vv * wu) / D;
if (s < 0.0 || s > 1.0) // I is outside T
return 0;
t = (uv * wu - uu * wv) / D;
if (t < 0.0 || (s + t) > 1.0) // I is outside T
return 0;
return 1; // I is in T
}
//Global variables for intensity calculations to work
std::vector<tinyobj::shape_t> shapes;
int tempShape = -1;
Point tempI;
Vector intensity;
Vector calcIntensity(int k, int tempShape, Triangle T,Point tempI)
{
//define light
Vector eye = (0,0,-2);
Vector La[5],Ld[5],Ls[5];
Vector Light1 = (0, 0.8 , 2);
Vector N,L,V,H;
Vector u = T.V1 - T.V0;
Vector v = T.V2 - T.V0;
N = u.cross(v);
L = Light1 - tempI;
V = tempI - eye;
H = L + V;
N.normalize();
L.normalize();
V.normalize();
H.normalize();
La[0] = (1,1,1);
Ld[0] = (1,1,1);
Ls[0] = (1,1,1);
Vector ambient, diffuse, specular;
ambient = La[0] * shapes[k].material.ambient;
diffuse = (Ld[0] * shapes[k].material.diffuse).mult(dot(N,L));
if (diffuse.x < 0) diffuse.x =0;
if (diffuse.y < 0) diffuse.y =0;
if (diffuse.z < 0) diffuse.z =0;
if (diffuse.x > 1) diffuse.x =1;
if (diffuse.y > 1) diffuse.y =1;
if (diffuse.z > 1) diffuse.z =1;
specular= (Ls[0] * shapes[k].material.specular).mult((int)(dot (H,N)) ^ 64);
if (specular.x < 0) specular.x =0;
if (specular.y < 0) specular.y =0;
if (specular.z < 0) specular.z =0;
if (specular.x > 1) specular.x =1;
if (specular.y > 1) specular.y =1;
if (specular.z > 1) specular.z =1;
intensity = ((ambient + diffuse) + specular);
if (intensity.x < 0) intensity.x =0;
if (intensity.y < 0) intensity.y =0;
if (intensity.z < 0) intensity.z =0;
if (intensity.x > 1) intensity.x =1;
if (intensity.y > 1) intensity.y =1;
if (intensity.z > 1) intensity.z =1;
return intensity;
}
void drawColor()
{
std::string inputfile = "./inputs/cube.obj";
std::string err = tinyobj::LoadObj(shapes, inputfile.c_str()); //populate "shapes" struct
unsigned int max=0; // max value among all vertices. required to scale down the image if it's big
// code to scale down large objects to fit in the frustrum
for (int cnt=0;cnt<shapes.size();cnt++)
for (int cnt1=0;cnt1<shapes[cnt].mesh.positions.size();cnt1+=3)
if (((shapes[cnt].mesh.positions[cnt1] * shapes[cnt].mesh.positions[cnt1] )>1)
|| ((shapes[cnt].mesh.positions[cnt1+1] * shapes[cnt].mesh.positions[cnt1+1] )>1))
if (shapes[cnt].mesh.positions[cnt1] > max)
max = shapes[cnt].mesh.positions[cnt1];
if (max > 1)
for (int cnt=0;cnt<shapes.size();cnt++)
for (int cnt1=0;cnt1<shapes[cnt].mesh.positions.size();cnt1++)
shapes[cnt].mesh.positions[cnt1] /= max;
// psdeo: Eye position for current requirement of assignment.
R.P0.x = (float) 0;
R.P0.y = (float) 0;
R.P0.z = (float) -2;
int intersection = 0;
// psdeo: reading window size from window.txt
// referred file redeading code from tinyObjLoader
double winX,winY,len,ht;
std::stringstream err1;
std::ifstream win("window.txt");
if (!win) {
err1 << "Cannot open file window.txt" << std::endl;
return;
}
std::istream& inStream = win;
int maxchars = 100; // window size should not exceed those many digits
std::vector<char> buf(maxchars); // Alloc enough size.
while (inStream.peek() != -1) {
inStream.getline(&buf[0], maxchars);
std::string linebuf(&buf[0]);
// Trim newline '\r\n' or '\n'
if (linebuf.size() > 0) {
if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1);
}
if (linebuf.size() > 0) {
if (linebuf[linebuf.size()-1] == '\r') linebuf.erase(linebuf.size()-1);
}
// Skip if empty line.
if (linebuf.empty()) {
continue;
}
const char* token = linebuf.c_str();
winX = (double) parseInt(token);
winY = (double) parseInt(token);
len = (double) parseInt(token);
ht = (double) parseInt(token);
}
float x[2048] , y[2048];
//to scale the object as per the window
double scaleX, scaleY;
scaleX = winX/ 256;
scaleY = winY/ 256;
for (int i=0;i<winX;i++)
for (int j=0;j<winY;j++)
{
intersection = 0;
for(int k=0;k<shapes.size() && intersection!=1 ;k++)
for(int l=0;l<shapes[k].mesh.indices.size() && intersection!=1 ;l+=3)
{
//write intersection detection algorithm for each pixel as below
//1. find world coordinates of the pixel & do the following for each shape
//2. find if there is an intersection by calling intersect3D_RayTriangle
//3. if not, continue to next pixel for the same triangle;
// if yes, color the pixel acc to obj file
//4. illuminate using data in mtl file
/*________________________________________________________________*/
//STEP 1- FRONT CLIPPING PLANE CENTERED @ (0,0,-1).
// SQUARE OF LENGTH 2
// TOP LEFT = (-1,1,-1), 1 PIXEL = 1/128 UNITS.
// Z COORDINATE WILL ALWAYS BE -1
T.V0.x = shapes[k].mesh.positions[(shapes[k].mesh.indices[l])*3] * scaleX;
T.V0.y = shapes[k].mesh.positions[(shapes[k].mesh.indices[l])*3+1] * scaleY;
T.V0.z = shapes[k].mesh.positions[(shapes[k].mesh.indices[l])*3+2];
T.V1.x = shapes[k].mesh.positions[(shapes[k].mesh.indices[l+1])*3] * scaleX;
T.V1.y = shapes[k].mesh.positions[((shapes[k].mesh.indices[l+1])*3)+1]* scaleY;
T.V1.z = shapes[k].mesh.positions[((shapes[k].mesh.indices[l+1])*3)+2];
T.V2.x = shapes[k].mesh.positions[(shapes[k].mesh.indices[l+2])*3] * scaleX;
T.V2.y = shapes[k].mesh.positions[((shapes[k].mesh.indices[l+2])*3)+1]* scaleY;
T.V2.z = shapes[k].mesh.positions[((shapes[k].mesh.indices[l+2])*3)+2];
x[i] = -1 + ((len/winX) * (i+1));
y[j] = 1 - ((len/winY) * (j+1));
R.P1.x = (float)x[i];
R.P1.y = (float)y[j];
R.P1.z = (float) -1;
/*________________________________________________________________*/
//STEP 2- Intersection determination
intersection = intersect3D_RayTriangle(R,T,&(I));
/*________________________________________________________________*/
//STEP 3- Coloring the pixel
if (intersection == 1)
{
if (tempShape == -1 || I.z < tempI.z) //either its first intersection or foremost yet
{
tempShape = l; // store index of intersecting triangle
tempI = I; // store intersection point
}
intensity = calcIntensity(k,tempShape,T,tempI);
tempColor = RGB((int)(255 * intensity.x),(int) (255 * intensity.y),(int) (255 * intensity.z));
setPixel(i, j, tempColor);
}
else
setPixel(i, j, blackColor); // background is assumed to be black
}
}
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
std::cout<<"wndproc";
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
RECT rt;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
GetClientRect(hWnd, &rt);
SetWindowHandle(hWnd);
drawColor();
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
printf("callback");
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
|
//knapsack problem codechef
#include<iostream>
#include<vector>
#include<algorithm>
#include<stdio.h>
using namespace std;
long long cost[200000+10];
int main()
{
int n,w,c,m,W = 0;
//Separate one and two for even and odd casses
vector<int> one,two,One,Two;
scanf("%d",&n);
for(int i = 0;i<n;i++)
{
scanf("%d %d",&w,&c);
//Insert weight 1 items in one vector
if(w == 1)
one.push_back(c);
//Insert weight 2 items in two vector
else
two.push_back(c);
W += w;
}
//sort the two vectors
sort(one.begin(),one.end());
sort(two.begin(),two.end());
One = one;
Two = two;
long long sum = 0,cur = 0,res = 0;
//even case
for(int i = 2;i<=W;i+=2)
{
//res1 --> when we take atmost two 1 wight items
//res2 --> when we take single 2 weight item
long long res1 = 0, res2 = 0;//calc res2
if(two.size() > 0){
res2 = two[two.size()-1];
}
//calculate res1
if(one.size() > 1)
{
res1 = one[one.size()-1] + one[one.size()-2];
}
else if(one.size() > 0)
{
res1 = one[one.size() - 1];
}
//if res2 > res1 remove the 2 weight item
if(res2 > res1)
{
two.pop_back();
res += res2;
}
//remove at most two 1 weight items
else
{
if(one.size() > 1)
{
one.pop_back();
one.pop_back();
}
else
one.pop_back();
res += res1;}
//update the max cost for weight i
cost[i] = res;
}
//odd case
//subtract 1 to make the weight sum even
res = 0;
//Find the most expensive 1 weight item
//and remove it from the list
if(One.size() > 0)
{
res = One[One.size()-1];
One.pop_back();
}
cost[1] = res;
//Similar to even case
for(int i = 3;i<=W;i+=2)
{
long long res1 = 0, res2 = 0;
if(Two.size() > 0)
{
res2 = Two[Two.size()-1];
}
if(One.size() > 1)
{
res1 = One[One.size()-1] + One[One.size()-2];
}
else if(One.size() > 0)
{
res1 = One[One.size()-1];
}
if(res2 > res1)
{
Two.pop_back();
res += res2;
}
else
{
if(One.size() > 1)
{
One.pop_back();
One.pop_back();
}
else
One.pop_back();
res += res1;
}
cost[i] = res;
}
for (int i = 1; i <= W; i++)
{
if (i > 1) printf(" ");
printf("%lld", cost[i]);
}
printf("\n");
return 0;
}
|
#include <Windows.h>
#include <iostream>
#include "Person.h"
#include "Globals.h"
Person::Person()
{
infected = false;
infectious = false;
timesInfected = 0;
strain = 0;
}
Person::~Person()
{
}
void Person::update(float transmission)
{
if (!infected) {
if (transmission > infectionRate && timesInfected < 1) {
//arbitrarily chosen values atm.
if (rand() % (int)(1/infectionRate - transmission*transmission + timesInfected*1000) == 0) {
//the person is now infected with the sth strain.
infected = true;
}
}
}
//I-> R
if (infected) {
if (rand() % (int)max(1, int(1/progressionRate)) == 0) {
infectious = true;
}
}
//I-> R
if (infectious) {
//probability function taking in transmission value and recovery rate value. higher values of both should make the event true more
if (rand() % (int)max(1, (int)(1 / recoveryRate - timesInfected * 10)) == 0) {
infected = false;
infectious = false;
timesInfected++;
}
}
}
void Person::update(int strainNum, float transmission)
{
if (!infected) {
if (transmission > infectionRate && timesInfected < 1) {
//arbitrarily chosen values atm.
if (rand() % (int)(1 / (infectionRate * pow(cost_of_resistance, strainNum)) - transmission*transmission + timesInfected * 1000) == 0) {
//the person is now infected with the sth strain.
infected = true;
strain = strainNum;
}
}
}
//I-> R
if (infected) {
if (rand() % (int)max(1, int(1 / (progressionRate * pow(cost_of_resistance,strain))) ) == 0) {
infectious = true;
}
}
if (infected) {
//mutate.
if (rand() % (int)max(1, int(1 / mutationRate)) == 0) {
if (strain == 0) strain++;
else if (strain == numStrains) strain--;
else {
if (rand() % 2 == 0) strain++;
else strain--;
}
}
}
//I-> R
if (infectious) {
//probability function taking in transmission value and recovery rate value. higher values of both should make the event true more
if (rand() % (int)max(1, (int)(1 / recoveryRate ) * pow(cost_of_resistance, strain) - timesInfected * 10) == 0) {
infected = false;
infectious = false;
timesInfected++;
}
}
}
void Person::update(float* transmission)
{
//S -> L
if (!infected) {
for (int s = 0; s < numStrains; s++) {
if (transmission[strain] > infectionRate) {
if (rand() % int((1 / infectionRate * 1 / pow(cost_of_resistance, s)) + 1000 * timesInfected) == 0) {
//the person is now infected with the sth strain.
infected = true;
strain = s;
}
}
}
}
// L-> infected.
if (infected) {
//probability function taking in transmission value and recovery rate value. higher values of both should make the event true more
if (rand() % (int)(max(1, (int)(1 / recoveryRate - timesInfected * 10))) == 0) {
infectious = true;
}
}
//I-> R
if (infected) {
//probability function taking in transmission value and recovery rate value. higher values of both should make the event true more
if (rand() % (int)(max(1, (int)(1 / recoveryRate - timesInfected * 10)) ) == 0) {
infected = false;
infectious = false;
}
}
}
void Person::setInfectious(bool S)
{
infected = S;
}
bool Person::isInfectious()
{
return infectious;
}
bool Person::isInfected() {
return infected;
}
int Person::getStrainNum()
{
return strain;
}
|
#include<iostream>
#include<string>
using namespace std;
enum department_t {cleaning, marketing, management, service, sales}; //labels
int main() {
string nameArr[10] = {"Taka", "Tom", "Hannah", "Alex", "Fred", "Nick", "Ethan", "Mario", "Shelly", "Paul"};
double salaryArr[10] = {52000, 53000, 100000, 200000, 60000, 65000, 80000, 92000, 75000, 70000};
department_t departments[10] = {sales, service, management, marketing, cleaning, sales, sales, marketing, cleaning, marketing};
//List of employees
cout << " NAME \t DEPARTMENT \t SALARY \n";
cout << "----------------------------------\n";
for(int i = 0; i < 10; i++) {
cout << nameArr[i] << " \t ";
switch (departments[i]) {
// case 0: cout << "cleaning"; break;
// case 1: cout << "marketing"; break;
// case 2: cout << "management"; break;
// case 3: cout << "service"; break;
// case 4: cout << "sales"; break;
// default: break; //or using labels as following
case cleaning: cout << "Cleaning"; break;
case marketing: cout << "Marketing"; break;
case management: cout << "Management"; break;
case service: cout << "Service"; break;
case sales: cout << "Sales "; break;
default: break;
}
cout<< " \t $" << salaryArr[i] << endl;
}
cout << "\n \n \n";
//List of departments
cout << " No. \t DEPARTMENT \t EMPLOYEES \t PAYMENT \n";
cout << "------------------------------------------------\n";
for (int dep = 0; dep < 5; dep++) { //each department individually
cout << dep + 1 << " \t ";
switch(dep) { //set the department label
case 0: cout << "Cleaning"; break;
case 1: cout << "Marketing"; break;
case 2: cout << "Management"; break;
case 3: cout << "Service"; break;
case 4: cout << "Sales "; break;
default: break;
}
//every single employee
int counter = 0; //should reset dor each department
double payment = 0;
for(int emp = 0; emp < 10; emp++) { //check all tem employees
if(departments[emp] == dep) { //if the department of current employee is same as the current department we are going through
counter++; //number of employees being in current department
payment += salaryArr[emp]; //accumulator to calculate the total salaries of the employees being in current department
}
}
cout << "\t \t " << counter << "\t $" << payment << "\n";
}
cout << "\n \n";
system("pause");
return 0;
}
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#ifndef cmExprParserHelper_h
#define cmExprParserHelper_h
#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
#include "cm_kwiml.h"
class cmExprParserHelper
{
public:
struct ParserType
{
KWIML_INT_int64_t Number;
};
cmExprParserHelper();
~cmExprParserHelper();
int ParseString(const char* str, int verb);
int LexInput(char* buf, int maxlen);
void Error(const char* str);
void SetResult(KWIML_INT_int64_t value);
KWIML_INT_int64_t GetResult() { return this->Result; }
const char* GetError() { return this->ErrorString.c_str(); }
void UnexpectedChar(char c);
std::string const& GetWarning() const { return this->WarningString; }
private:
std::string::size_type InputBufferPos;
std::string InputBuffer;
std::vector<char> OutputBuffer;
int CurrentLine;
int Verbose;
void Print(const char* place, const char* str);
void SetError(std::string errorString);
KWIML_INT_int64_t Result;
const char* FileName;
long FileLine;
std::string ErrorString;
std::string WarningString;
};
#define YYSTYPE cmExprParserHelper::ParserType
#define YYSTYPE_IS_DECLARED
#define YY_EXTRA_TYPE cmExprParserHelper*
#define YY_DECL int cmExpr_yylex(YYSTYPE* yylvalp, yyscan_t yyscanner)
#endif
|
#ifndef ACTION_H
#define ACTION_H
class action
{
public:
action();
};
#endif // ACTION_H
|
#include <iostream>
int main() {
/* 1.variable declaration like java <TYPE> <NAME> = <VALUE>
* 2.Always initialize variables if you can.
* 3.Name must start with a letter
* 4.Google-style: snake_case
*/
int a = 3;
int max_counter = 2;
// Most common variable types:
bool this_is_fun = false; //boolean: true or false
char carret_return = '\n'; // single character
int number = 12; // integer
short smaller_int = 3; // short number
long bigger_int = 64; // Long number
float fraction = 0.01f; // single precision float.
double precise_num = 0.01; // double precision float
//auto type choose type automatic
auto some_int = 13; // automatic type [int]
auto some_float = 13.0f; // automatic type [float]
auto some_double = 13.0; // automatic type [double]
return 0;
}
|
#include <iostream>
#include <malloc.h>
#include <string.h>
using namespace std;
typedef struct node *typeptr;
struct node
{
int angka;
typeptr kiri, kanan;
};
typeptr root, p, b;
void buatPohon()
{
typeptr ptb;
ptb = NULL;
root = ptb;
}
int ptbKosong()
{
if (root == NULL)
return (true);
else
return (false);
}
char *hapusDuplikasi(char str[], int len)
{
int idx = 0;
for (int i = 0; i < len; i++)
{
int j;
for (j = 0; j < i; j++)
if (str[i] == str[j])
break;
if (j == i)
str[idx++] = str[i];
}
return str;
}
void sisipnode(std::string &nim)
{
// parsing nim jadi satuan char
// satu node satu digit.
char ntemp[10];
strcpy(ntemp, nim.c_str());
nim = hapusDuplikasi(ntemp, (sizeof(ntemp) / sizeof(ntemp[0])));
// buat node berdasar string yang telah diparsing
for (int i = 0; i < nim.length(); i++)
{
typeptr node_baru;
node_baru = (node *)malloc(sizeof(node));
node_baru->angka = nim[i] - '0';
node_baru->kiri = NULL;
node_baru->kanan = NULL;
if (ptbKosong())
root = node_baru;
else
{
b = root;
p = root;
//mencari tempat untuk menyisipkan node
while (p != NULL && ((int)nim[i] - '0') != b->angka)
{
b = p;
if (((int)nim[i] - '0') < p->angka)
p = b->kiri;
else
p = b->kanan;
}
if (((int)nim[i] - '0') == b->angka)
cout << "\n\nNode " << nim << " sudah ada !\n\n";
else
{
if (((int)nim[i] - '0') < b->angka)
b->kiri = node_baru;
else
b->kanan = node_baru;
}
}
}
}
void preorder(typeptr root)
{
if (root != NULL)
{
cout << " " << root->angka;
preorder(root->kiri);
preorder(root->kanan);
}
}
void inorder(typeptr root)
{
if (root != NULL)
{
inorder(root->kiri);
cout << " " << root->angka;
inorder(root->kanan);
}
}
void postorder(typeptr root)
{
if (root != NULL)
{
postorder(root->kiri);
postorder(root->kanan);
cout << " " << root->angka;
}
}
void cetak()
{
cout << "\nPre-order : ";
preorder(root);
cout << "\nIn-order : ";
inorder(root);
cout << "\nPost-order: ";
postorder(root);
return;
}
int main()
{
string str = "123190123";
sisipnode(str);
cetak();
return 0;
}
|
// Created on: 2011-10-14
// Created by: Roman KOZLOV
// Copyright (c) 2011-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef __IVTKVTK_VIEW_H__
#define __IVTKVTK_VIEW_H__
#include <IVtk_IView.hxx>
#include <vtkSmartPointer.h>
class vtkRenderer;
class IVtkVTK_View;
DEFINE_STANDARD_HANDLE( IVtkVTK_View, IVtk_IView )
//! @class IVtkVTK_View
//! @brief ICamera implementation for VTK.
//!
//! This class is used for obtaining view transformation parameters.
//! These parameters are used by selection algorithm to compute
//! projections of selectable (active) 3D shapes.
class IVtkVTK_View : public IVtk_IView
{
public:
typedef Handle(IVtkVTK_View) Handle;
Standard_EXPORT IVtkVTK_View (vtkRenderer* theRenderer);
//! Destructor
Standard_EXPORT virtual ~IVtkVTK_View();
//! @return true if this is a perspective view, and false otherwise.
Standard_EXPORT virtual bool IsPerspective() const Standard_OVERRIDE;
//! @return The focal distance of the view
Standard_EXPORT virtual double GetDistance() const Standard_OVERRIDE;
//! @return The world coordinates of the camera position
Standard_EXPORT virtual void GetEyePosition (double& theX, double& theY, double& theZ) const Standard_OVERRIDE;
//! @return The world coordinates of the view position
Standard_EXPORT virtual void GetPosition (double& theX, double& theY, double& theZ) const Standard_OVERRIDE;
//! @return The "view up" direction of the view
Standard_EXPORT virtual void GetViewUp (double& theDx, double& theDy, double& theDz) const Standard_OVERRIDE;
//! @return The projection direction vector of this view
Standard_EXPORT virtual void GetDirectionOfProjection (double& theDx,
double& theDy,
double& theDz) const Standard_OVERRIDE;
//! @return Three doubles containing scale components of the view transformation
Standard_EXPORT virtual void GetScale (double& theX, double& theY, double& theZ) const Standard_OVERRIDE;
//! @return The current view's zoom factor (for parallel projection)
Standard_EXPORT virtual double GetParallelScale() const Standard_OVERRIDE;
//! @return The current view angle (for perspective projection)
Standard_EXPORT virtual double GetViewAngle() const Standard_OVERRIDE;
//! @return The location of the near and far clipping planes along the direction of projection
Standard_EXPORT virtual void GetClippingRange (double& theZNear, double& theZFar) const Standard_OVERRIDE;
//! @return The current view the aspect ratio
Standard_EXPORT virtual double GetAspectRatio() const Standard_OVERRIDE;
//! @return Two doubles containing the display coordinates of the view window center
Standard_EXPORT virtual void GetViewCenter (double& theX, double& theY) const Standard_OVERRIDE;
//! Gets window size in screen coordinates in pixels
Standard_EXPORT virtual void GetWindowSize (int& theX, int& theY) const Standard_OVERRIDE;
//! Gets camera projection and orientation matrices
Standard_EXPORT virtual void GetCamera (Graphic3d_Mat4d& theProj,
Graphic3d_Mat4d& theOrient,
Standard_Boolean& theIsOrtho) const Standard_OVERRIDE;
//! Gets viewport coordinates
Standard_EXPORT virtual void GetViewport (Standard_Real& theX,
Standard_Real& theY,
Standard_Real& theWidth,
Standard_Real& theHeight) const Standard_OVERRIDE;
//! Converts 3D display coordinates into 3D world coordinates.
//! @param [in] theDisplayPnt 2d point of display coordinates
//! @param [out] theWorldPnt 3d point of world coordinates
//! @return true if conversion was successful, false otherwise
Standard_EXPORT virtual bool DisplayToWorld (const gp_XY& theDisplayPnt, gp_XYZ& theWorldPnt) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IVtkVTK_View,IVtk_IView)
private:
vtkSmartPointer<vtkRenderer> myRenderer;
};
#endif // __IVTKVTK_VIEW_H__
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.