text
stringlengths 8
6.88M
|
|---|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "BaseUI.generated.h"
/**
*
*/
UCLASS()
class SPIDERMANPROJECT_API UBaseUI : public UUserWidget
{
GENERATED_BODY()
};
|
#include "pointlistfile.h"
#include "qfile.h"
#include "qstringlist.h"
#include "qtextstream.h"
PointListFile::PointListFile(QObject *parent)
: QObject(parent)
{
}
PointListFile::~PointListFile()
{
}
bool PointListFile::hasLoadedRoute(){
return m_nMapNodeNum == 0 ? true : false;
}
void PointListFile::ResetList(){
m_MapNodeList.clear();
for (int i = 0; i < m_nMapNodeNum; i++){
m_vMap[i].clear();
}
m_nMapEdgeNum = m_nMapNodeNum = 0;
m_mpChk.clear();
}
bool PointListFile::ReadFile(QString& file){
FileName = file;
return ReadFile();
}
bool PointListFile::ReadFile(){
ResetList(); ///<<先清空数据
if (!FileName.isEmpty()){
QString PntLst = FileName + QString(".point");
QString EdgeLst = FileName + QString(".edge");
//QString NameLst = FileName + QString(".name");
QFile* file = new QFile(PntLst);
if (!file->open(QIODevice::ReadWrite | QIODevice::Text)){
return false;
}
QTextStream stream(file);
int index = 0;
///.point文件格式:
/// 假设某一个Ogre::Vector3类型的变量名为V3,那么在文件中关于这个点的记录如下:
///V3.x V3.y V3.z V3的自定义名称1,V3的自定义名称2,...
///每一个点将占一行
while (!stream.atEnd()){
QString temp = stream.readLine();
if (temp.isEmpty()) continue;
QStringList templist = temp.split(" ");
m_MapNodeList.push_back(Ogre::Vector3(templist.at(0).toDouble(),
templist.at(1).toDouble(),templist.at(2).toDouble()));
QStringList namelist = templist.at(3).split(",");
for (int i = 0; i < namelist.size(); i++){
m_mpChk.insert(std::pair<Ogre::String, int>(namelist.at(i).toStdString(), index));
}
//m_mpChk.insert(std::pair<Ogre::String, int>(templist.at(3), index));
index++;
}
m_nMapNodeNum = index;
file->close();
file = new QFile(EdgeLst);
if (!file->open(QIODevice::ReadWrite | QIODevice::Text)){
return false;
}
QTextStream stm(file);
int edgecount = 0;
//index = 0;
///.edge文件格式:
///相对于.point文件中的一个点V3,在.edge文件中记录的一组有向边如下:
///n,m <<<n代表点V3的编号,m代表V3点在m条边上
///to c <<< to表示边的另一个顶点编号,c表示边的权重
///to c <<<
///... <<< 一共重复m行
///to c <<<
while (!stm.atEnd()){
QString strnum = stm.readLine();
if (strnum.isEmpty()) continue;
QStringList l = strnum.split(",");
for (int i = 0; i < l.at(1).toInt(); i++){
QStringList strlist = stm.readLine().split(" ");
Edge tedge;
tedge.to = strlist.at(0).toInt();
tedge.c = strlist.at(1).toInt();
m_vMap[l.at(0).toInt()].push_back(tedge);
edgecount++;
}
//index++;
}
m_nMapEdgeNum = edgecount;
file->close();
return true;
}
return false;
}
bool PointListFile::WriteFile(){
if (!FileName.isEmpty()){
QString PntLst = FileName + QString(".point");
QString EdgeLst = FileName + QString(".edge");
//QString NameLst = FileName + QString(".name");
QString space(" ");
QFile* file = new QFile(PntLst);
if (!file->open(QIODevice::ReadWrite | QIODevice::Text)){
return false;
}
QTextStream stream(file);
///TODO
std::vector<Ogre::Vector3>::iterator it;
int index = 0;
for (it = m_MapNodeList.begin(); it != m_MapNodeList.end(); it++){
stream << QString::number((*it).x) << space <<
QString::number((*it).y) << space <<
QString::number((*it).z) << space;
std::vector < Ogre::String> result;
std::map<Ogre::String, int>::iterator mit = m_mpChk.begin();
bool first = true;
while (mit != m_mpChk.end()){
if (mit->second == index){
if (first){
first = false;
stream << QString::fromStdString(mit->first);
}
else{
stream << QString(",") << QString::fromStdString(mit->first);
}
}
mit++;
}
stream << QString("\n");
index++;
//QString(m_mpChk)
}
file->close();
file = new QFile(EdgeLst);
if (!file->open(QIODevice::ReadWrite | QIODevice::Text)){
return false;
}
QTextStream stm(file);
for (int i = 0; i < m_nMapNodeNum; i++){
stm << QString::number(i) <<QString(",") <<QString::number(m_vMap[i].size()) << QString("\n");
std::vector<Edge>::iterator it;
for (it = m_vMap[i].begin(); it != m_vMap[i].end(); it++){
stm << QString::number(it->to) << space << QString::number(it->c) << QString("\n");
}
}
file->close();
return true;
}
return false;
}
|
#include <Windows.h>
#include "NvIFRToSys.h"
#include "NvIFRHWEnc.h"
#include <d3d11.h>
#include "nvcapture.h"
#include <tchar.h>
#include <stdio.h>
//#include <time.h>
extern "C"{
#include "mp4muxer.h"
}
#define NUMFRAMESINFLIGHT = 1
NvIFRToSys* toSys = NULL;
unsigned char *buffer;
HANDLE gpuEvent;
//hw enc
INvIFRToHWEncoder* toHWEnc = NULL;
#define N_BUFFERS 1
unsigned char * g_pBitStreamBuffer[N_BUFFERS] = {NULL};
HANDLE g_EncodeCompletionEvents[N_BUFFERS] = {NULL};
DWORD WINAPI ThreadFunction(LPVOID lpParam);
HANDLE hThread = NULL;
DWORD dwThreadId = 0;
HANDLE hFile = NULL;
boolean releasedCalled = false;
HANDLE ghMutex;
int pkt_counter = 0;
#define WRITE_H264 0 //if 1, write h264 not mp4
HINSTANCE handleNVIFR = NULL;
static void SetUpTargetBuffers(){
NVIFR_TOSYS_SETUP_PARAMS params = {0};
params.dwVersion = NVIFR_TOSYS_SETUP_PARAMS_VER;
params.eFormat = NVIFR_FORMAT_RGB;
params.eSysStereoFormat = NVIFR_SYS_STEREO_NONE;
params.dwNBuffers = 1;
params.ppPageLockedSysmemBuffers = &buffer;
params.ppTransferCompletionEvents = &gpuEvent;
NVIFRRESULT result = toSys->NvIFRSetUpTargetBufferToSys(¶ms);
}
static void SetUpHwEncTargetBuffers(){
NVIFR_HW_ENC_SETUP_PARAMS params = {0};
params.dwVersion = NVIFR_HW_ENC_SETUP_PARAMS_VER;
//params.configParams.eCodec = NV_HW_ENC_H264;
params.dwNBuffers = N_BUFFERS;
params.dwBSMaxSize = 2048*1024;
//g_pBitStreamBuffer[0] = new unsigned char[params.dwBSMaxSize];
params.ppPageLockedBitStreamBuffers = g_pBitStreamBuffer;//(unsigned char **) (&g_pBitStreamBuffer);
//g_EncodeCompletionEvents[0] = CreateEvent(NULL, TRUE, FALSE, TEXT("Sipvay"));
params.ppEncodeCompletionEvents = g_EncodeCompletionEvents;
NV_HW_ENC_CONFIG_PARAMS encodeConfig = {0};
encodeConfig.dwVersion = NV_HW_ENC_CONFIG_PARAMS_VER;
encodeConfig.eCodec = NV_HW_ENC_H264;
encodeConfig.eStereoFormat = NV_HW_ENC_STEREO_NONE;
encodeConfig.dwProfile = 100;
encodeConfig.dwAvgBitRate = 8000000;//TODO calculate the corect value
encodeConfig.dwFrameRateDen = 1;
encodeConfig.dwFrameRateNum = 30;
encodeConfig.dwPeakBitRate = (encodeConfig.dwAvgBitRate * 12/10); // +20%
encodeConfig.dwGOPLength = 75;
encodeConfig.dwQP = 26 ;
encodeConfig.eRateControl = NV_HW_ENC_PARAMS_RC_CBR;
encodeConfig.bRecordTimeStamps = TRUE;
//encodeConfig.ePresetConfig= NV_HW_ENC_PRESET_LOW_LATENCY_HQ;
//encodeConfig.bEnableAdaptiveQuantization = true;
//! Set Encode Config params.configParams = encodeConfig;
params.configParams = encodeConfig;
NVIFRRESULT res = toHWEnc->NvIFRSetUpHWEncoder(¶ms);
char message[250];
sprintf(message,"NvIFRSetUpHWEncoder res: %d",res);
DebugMessage(message);
}
void InitNvCapture(ID3D11Device *device){
if(handleNVIFR == NULL){
handleNVIFR = ::LoadLibrary(_T("NVIFR64.dll"));
}
if(handleNVIFR == NULL){
char message[250];
sprintf(message,"Couldn't load library NVIFR64.dll !!! error: %d",GetLastError());
DebugMessage(message);
} else {
NvIFR_CreateFunctionExType pfnNVIFR_Create = NULL;
pfnNVIFR_Create = (NvIFR_CreateFunctionExType) GetProcAddress(handleNVIFR, "NvIFR_CreateEx");
if(pfnNVIFR_Create == NULL){
char message[250];
sprintf(message,"Couldn't get NVIFR_CreateEx address !!! error: %d",GetLastError());
DebugMessage(message);
} else {
pkt_counter = 0;
NVIFR_CREATE_PARAMS params = {0};
params.dwVersion = NVIFR_CREATE_PARAMS_VER;
//params.dwInterfaceType = NVIFR_TOSYS;
params.dwInterfaceType = NVIFR_TO_HWENCODER;
params.pDevice = device;
NVIFRRESULT res = pfnNVIFR_Create(¶ms);
if (res == NVIFR_SUCCESS) {
//toSys = (NvIFRToSys *)params.pNvIFR;
toHWEnc = (INvIFRToHWEncoder *)params.pNvIFR;
//SetUpTargetBuffers();
//SetUpHwEncTargetBuffers();
ghMutex = CreateMutex( NULL, FALSE, NULL);
if(g_pBitStreamBuffer[0] == 0){
SetUpHwEncTargetBuffers();
}
#if WRITE_H264
hFile = CreateFile("outputVideoH264", GENERIC_WRITE, 0,NULL,CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(hFile == INVALID_HANDLE_VALUE){
hFile = NULL;
}
#else
mp4_init();
#endif
hThread = CreateThread(NULL, 0, ThreadFunction, NULL, 0, &dwThreadId);
}
}
}
}
void TransferNvCapture(){
if(toSys != NULL){
NVIFRRESULT result = toSys->NvIFRTransferRenderTargetToSys(0);
} else if(toHWEnc != NULL) {
NV_HW_ENC_PIC_PARAMS encodePicParams = {0};
encodePicParams.dwVersion = NV_HW_ENC_PIC_PARAMS_VER;
//NvU64 timestamp = GetTickCount64();
encodePicParams.ulCaptureTimeStamp = pkt_counter++;
char message[250];
sprintf(message,"TransferNvCapture() %ull",encodePicParams.ulCaptureTimeStamp);
DebugMessage(message);
NVIFR_HW_ENC_TRANSFER_RT_TO_HW_ENC_PARAMS params = {0};
params.dwVersion = NVIFR_HW_ENC_TRANSFER_RT_TO_HW_ENC_PARAMS_VER;
int i = 0;//temp
params.dwBufferIndex = i;
params.encodePicParams = encodePicParams;
NVIFRRESULT res = toHWEnc->NvIFRTransferRenderTargetToHWEncoder(¶ms);
/*char message[250];
sprintf(message,"NvIFRTransferRenderTargetToHWEncoder res: %d",res);
DebugMessage(message);*/
}
}
void ReleaseNv(){
releasedCalled = true;
//get mutex
WaitForSingleObject( ghMutex, INFINITE);
if(toSys != NULL){
toSys->NvIFRRelease();
toSys = NULL;
} else if(toHWEnc != NULL) {
toHWEnc->NvIFRRelease();
toHWEnc = NULL;
}
if(g_pBitStreamBuffer[0] != NULL) {
//delete(g_pBitStreamBuffer[0]);
g_pBitStreamBuffer[0] = NULL;
}
if(ghMutex != NULL){
CloseHandle(ghMutex);
ghMutex = NULL;
}
if (hThread != NULL) {
CloseHandle(hThread);
hThread = NULL;
}
if(hFile != NULL){
CloseHandle(hFile);
hFile = NULL;
}
//leave mutex
ReleaseMutex(ghMutex);
#if !WRITE_H264
mp4_release();
#endif
}
DWORD WINAPI ThreadFunction(LPVOID lpParam){
//get mutex
WaitForSingleObject( ghMutex, INFINITE);
if(toSys != NULL){//not implemented(not needed)
WaitForSingleObject(gpuEvent, INFINITE);
} else if(toHWEnc != NULL) {
int i = 0;//temp,only one buffer
while(true){
if(releasedCalled){
//stop ...
releasedCalled = false;
break;
}
DWORD dwRet = WaitForSingleObject(g_EncodeCompletionEvents[i], 100);
ResetEvent(g_EncodeCompletionEvents[i]);
if(dwRet == WAIT_OBJECT_0){
DebugMessage("All good on g_EncodeCompletionEvents!!!");
NVIFR_HW_ENC_GET_BITSTREAM_PARAMS params = {0};
params.dwVersion = NVIFR_HW_ENC_GET_BITSTREAM_PARAMS_VER;
params.bitStreamParams.dwVersion = NV_HW_ENC_GET_BIT_STREAM_PARAMS_VER;
params.dwBufferIndex = i;
NVIFRRESULT res = toHWEnc->NvIFRGetStatsFromHWEncoder(¶ms);
if(res == NVIFR_SUCCESS ) {
//copy to disk params.bitStreamParams.dwByteSize;
#if WRITE_H264
if(hFile != NULL){
#endif
if(params.bitStreamParams.dwByteSize > 0){
DWORD byteSize = 0;
#if WRITE_H264
WriteFile(hFile, g_pBitStreamBuffer[0], params.bitStreamParams.dwByteSize, &byteSize, NULL);
#else
mp4_write_data(g_pBitStreamBuffer[0], params.bitStreamParams.dwByteSize);
#endif
char message[250];
sprintf(message,"params.bitStreamParams.dwByteSize: %d byteSize: %d timestamp: %ull ",params.bitStreamParams.dwByteSize,byteSize,params.bitStreamParams.ulTimeStamp);
DebugMessage(message);
}
#if WRITE_H264
}
#endif
}
} else if(dwRet == WAIT_FAILED){
char message[250];
sprintf(message,"WaitForSingleObject error: %d",GetLastError());
DebugMessage(message);
} else if(dwRet == WAIT_TIMEOUT){
DebugMessage("WaitForSingleObject time out !!!");
}
}
}
//leave mutex
ReleaseMutex(ghMutex);
return 1;
}
|
extern "C" {
#include "cpu.h"
}
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <string.h>
#include <signal.h>
#include "system_controller_cpld.h"
#define RAM_SIZE 16*1024
#define ROM_SIZE 32*1024
#define EXIT_DEBUGGER -1
#define QUIT_APPLICATION -2
#define INVALID_COMMAND 0
#define DBG_CMD_PROCEED 1
#define DBG_CMD_REMAIN 2
//struct termios oldit, newit, oldot, newot;
unsigned char* REN_rombuf;
unsigned char* REN_rambuf;
unsigned char* send_file_data = (unsigned char*)0;
int romsize;
int send_file_size = 0;
int send_file_index = 0;
byte input_register = 0;
byte output_register;
byte uart_register = 0;
byte sending_file = 0;
byte test_value = 0;
int tx_requested = 0;
byte spi_in = 0;
byte spi_out = 0;
int shifter = 0;
word32 last_time = 0;
word32 last_poll = 0;
int debugger_is_on = 0;
int debugger_is_enabled = 0;
int interrupts_enabled = 1;
int step_over_addr = 0xFFFFFFFF;
SystemControllerCPLD* system_controller;
void (*on_spi_complete)(void) = 0;
byte romcode[256] = {
0xA9, 0x00, 0x85, 0xFD, 0xB8, 0xA9, 0xFF, 0x85,
0xFE, 0xA9, 0xFF, 0x85, 0xFF, 0xEA, 0xEA, 0xEA,
0xEA, 0xEA, 0xEA, 0xEA, 0xEA, 0xEA, 0xEA, 0xC6,
0xFF, 0xD0, 0xF2, 0xC6, 0xFE, 0xD0, 0xEA, 0xA5,
0xFD, 0xD0, 0x08, 0xA9, 0xFF, 0x85, 0xFD, 0x18,
0xFB, 0x50, 0xDA, 0xA9, 0x00, 0x85, 0xFD, 0x38,
0xFB, 0x50, 0xD2
};
void EMUL_handleWDM(byte opcode, word32 timestamp) {
return;
}
//int kbhit();
//int getch();
void spi_print();
void add_IRQ(unsigned int mask) {
if(interrupts_enabled)
CPU_addIRQ(mask);
}
int read_line(char* buffer, unsigned int buf_size) {
char temp_char = 0;
unsigned int char_count = 0;
while(1) {
//while(!kbhit());
temp_char = getchar() & 0xFF;
buffer[char_count] = temp_char;
//printf("%c", temp_char); fflush(stdout);
if(temp_char == '\n')
break;
char_count++;
if(char_count == (buf_size - 1)) {
char_count++;
break;
}
}
buffer[char_count] = 0;
return char_count;
}
typedef int (*DebugCommandFunction)(int, char**);
int debug_command_step(int argc, char* argv[]) {
return DBG_CMD_PROCEED;
}
int debug_command_run(int argc, char* argv[]) {
debugger_is_on = 0;
return DBG_CMD_PROCEED;
}
int hex24_to_int(char* hex_string) {
char* ptr;
if(strlen(hex_string) != 6)
return -1;
return strtol(hex_string, &ptr, 16);
}
#define BP_MODE_CHECK 0
#define BP_MODE_INSERT 1
#define BP_MODE_REMOVE -1
#define BP_MODE_COUNT 2
#define BP_MODE_GET 3
#define BP_MODE_CLEAR_ALL 4
int breakpoint_check(int address, int mode) {
static unsigned int bp_count = 0;
static int* bp_entry = (int*)0;
int found_index = -1;
int i;
if(mode == BP_MODE_COUNT) { //Mode 2 == get entry count
return (int)bp_count;
}
if(address > 0xFFFFFF || address < 0)
return -1; //Bad address
if(mode == BP_MODE_GET) { //Mode 3 == get entry at index
if(address >= bp_count)
return 0; //Address not found
return (int)bp_entry[address];
}
if(mode == BP_MODE_CLEAR_ALL) {
bp_count = 0;
if(bp_entry)
free(bp_entry);
bp_entry = (int*)0;
}
for(i = 0; i < bp_count; i++)
if(bp_entry[i] == address) {
found_index = i;
break;
}
if(found_index == -1 && mode == BP_MODE_INSERT) { //mode 1 == insert breakpoint
bp_entry = (int*)realloc((void*)bp_entry, sizeof(int) * (bp_count + 1));
bp_entry[bp_count++] = address;
}
if(found_index != -1 && mode == BP_MODE_REMOVE) { //mode -1 == delete breakpoint
for(i = found_index; i < bp_count - 1; i++)
bp_entry[found_index] = bp_entry[found_index + 1];
bp_count--;
}
return found_index != -1;
}
int debug_command_break(int argc, char* argv[]) {
if(argc != 2 && argc != 1) {
printf("Wrong number of arguments.\nUsage: break <24-bit-hex-address | clear>\n");
fflush(stdout);
return DBG_CMD_REMAIN;
}
if(argc == 1) {
int i;
for(i = 0; i < breakpoint_check(0, BP_MODE_COUNT); i++) {
printf(" [%d] 0x%06X\n", i, breakpoint_check(i, BP_MODE_GET));
fflush(stdout);
}
} else if(!strcmp(argv[1], "clear")) {
breakpoint_check(0, BP_MODE_CLEAR_ALL);
printf("Breakpoints cleared\n");
fflush(stdout);
} else {
int address = hex24_to_int(argv[1]);
if(address < 0) {
printf("Could not parse the given address '%s'\n", argv[1]);
fflush(stdout);
return DBG_CMD_REMAIN;
}
switch(breakpoint_check(address, BP_MODE_INSERT)) {
case 0:
printf("Breakpoint added at %06X\n", address);
fflush(stdout);
break;
case -1:
printf("Bad breakpoint address\n");
fflush(stdout);
break;
default:
breakpoint_check(address, BP_MODE_REMOVE);
printf("Breakpoint at %06X removed\n", address);
fflush(stdout);
break;
}
}
return DBG_CMD_REMAIN;
}
int debug_command_toggleint(int argc, char* argv[]) {
if(argc != 1) {
printf("toggleint takes no arguments\n");
fflush(stdout);
return DBG_CMD_REMAIN;
}
interrupts_enabled = !interrupts_enabled;
printf("interrupts are now %s\n", interrupts_enabled ? "ON" : "OFF");
fflush(stdout);
return DBG_CMD_REMAIN;
}
int debug_command_args(int argc, char* argv[]) {
int i;
for(i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
fflush(stdout);
}
return DBG_CMD_REMAIN;
}
int debug_command_exit(int argc, char* argv[]) {
CPU_quit();
return DBG_CMD_PROCEED;
}
int debug_command_key(int argc, char* argv[]) {
input_register = '!';
return DBG_CMD_REMAIN;
}
int debug_command_send(int argc, char* argv[]) {
if(argc != 2) {
printf("Usage: send <file to send>\n");
return DBG_CMD_REMAIN;
}
send_file_data = (unsigned char*)malloc(send_file_size);
if (!system_controller->StartSendFile(argv[1]))
return DBG_CMD_REMAIN;
return DBG_CMD_REMAIN;
}
int debug_command_exam(int argc, char* argv[]) {
int count = 16;
int address = 0;
int i;
if(argc != 2 && argc != 3) {
printf("Usage: exam [base-address] <count>\n");
fflush(stdout);
return DBG_CMD_REMAIN;
}
if(argc == 3)
count = atoi(argv[2]);
address = hex24_to_int(argv[1]);
if(address < 0) {
printf("Bad address.\n");
fflush(stdout);
return DBG_CMD_REMAIN;
}
printf("%06X: ", address);
fflush(stdout);
for(i = 0; i < count; i++) {
printf("%02X", MEM_readMem((int)address + i, 0, 0));
if(i == count - 1)
printf("\n");
else
printf(" ");
}
return DBG_CMD_REMAIN;
}
char** string_to_argv(char* input_buffer, int* argc) {
char** return_array = (char**)0;
int building = 0;
char read_buffer[256];
int chars_read;
*argc = 0;
while(1) {
if(building) {
if(*input_buffer <= ' ') {
return_array[(*argc) - 1] = (char*)malloc(sizeof(char) * (chars_read + 1));
memcpy((void*)return_array[(*argc) - 1], (void*)read_buffer, chars_read);
return_array[(*argc) - 1][chars_read] = 0;
building = 0;
if(*input_buffer == 0)
break;
continue;
}
read_buffer[chars_read++] = *input_buffer++;
} else {
if(*input_buffer <= ' ') {
if(*input_buffer == 0)
break;
input_buffer++;
continue;
}
return_array = (char**)realloc((void*)return_array, sizeof(char*) * (++(*argc))); //This can fail. That would be bad.
building = 1;
chars_read = 0;
}
}
return return_array;
}
void free_argv_memory(int argc, char* argv[]) {
int i;
for(i = 0; i < argc; i++)
free((void*)argv[i]);
free((void*)argv);
}
int parse_debug_command(char* command_buffer) {
int i;
#define COMMAND_COUNT 9
char* command_entry[COMMAND_COUNT] = {
"step",
"run",
"break",
"args",
"exam",
"toggleint",
"exit",
"key",
"send"
};
DebugCommandFunction command_function[COMMAND_COUNT] = {
debug_command_step,
debug_command_run,
debug_command_break,
debug_command_args,
debug_command_exam,
debug_command_toggleint,
debug_command_exit,
debug_command_key,
debug_command_send
};
int argc;
int retval = 0;
char** argv = string_to_argv(command_buffer, &argc);
if(argc == 0)
return 0;
for(i = 0; i < COMMAND_COUNT; i++)
if(!strcmp(command_entry[i], argv[0])) {
retval = command_function[i](argc, argv); //TODO: Split command buffer into argvals
break;
}
free_argv_memory(argc, argv);
return retval;
}
void do_debugger(void) {
static char in_buf[256] = {0};
int parse_result = 0;
int execution_paused = 1;
CPU_debug();
while(execution_paused) {
printf("dbg>"); fflush(stdout);
read_line(in_buf, 256);
switch(parse_debug_command(in_buf)) {
case DBG_CMD_PROCEED:
execution_paused = 0;
break;
case DBG_CMD_REMAIN:
break;
default:
printf("Unknown debugger command.\n"); fflush(stdout);
break;
}
}
}
void EMUL_hardwareUpdate(word32 timestamp) {
static int oldE = 0;
static double old_timestamp = 0;
static double old_time = 0;
static double timef = 0;
static byte tx_buffer, rx_buffer;
//struct timespec t;
double clocks_elapsed;
double time_elapsed;
static long old_nsecs, new_nsecs, nsec_diff;
static int i_count = 0;
if(breakpoint_check(PC.A, BP_MODE_CHECK) > 0) {
printf("[Breakpoint encountered at %06X]\n", PC.A);
fflush(stdout);
debugger_is_on = 1;
}
debugger_is_on = debugger_is_on || system_controller->Refresh(timestamp);
if(debugger_is_on)
do_debugger();
//I want to do this based on time and not instruction count in the future
//May even be possible to put this into a timer thread so that the interrupt
//in the virtualized system is functionally mapped to an interrupt in the
//host machine
//if(i_count++ > 5000000) {
//i_count = 0;
//printf("[Interrupt fired]\n");
//fflush(stdout);
//CPU_addIRQ(1);
//}
//CPU emulation throttling
//while(1) {
//
// clock_gettime(CLOCK_REALTIME, &t);
// new_nsecs = t.tv_nsec;
//
// if(new_nsecs < old_nsecs)
// nsec_diff = (new_nsecs + 1000000000) - old_nsecs;
// else
// nsec_diff = new_nsecs - old_nsecs;
//
// if(nsec_diff >= 200) {
//
// break;
// }
//}
//old_nsecs = new_nsecs;
/*
clocks_elapsed = timestamp - old_timestamp;
if(clocks_elapsed >= 12000000) {
timef = ((double)t.tv_sec * 1000) + ((double)t.tv_nsec / 1.0e6);
time_elapsed = timef - old_time;
printf("IPS: %f/%f = %f\n", clocks_elapsed, time_elapsed, (1000 * clocks_elapsed)/time_elapsed);
old_time = timef;
old_timestamp = (double)timestamp;
}
*/
}
byte MEM_readMem(word32 address, word32 timestamp, word32 emulFlags) {
byte b = 0;
system_controller->TryReadByte(address, timestamp, emulFlags, b);
return b;
}
void MEM_writeMem(word32 address, byte b, word32 timestamp) {
system_controller->TryWriteByte(address, timestamp, b);
}
//TODO
int input(char* inbuf, int bufsz) {
getchar();
return 0;
}
void int_handler(int value) {
//if(debugger_is_on) {
// exit(0);
//}
debugger_is_on = 1;
}
void spi_print(void) {
static byte rx_count = 0;
static int printing = 0;
if(printing) {
printf("%c", spi_in);
fflush(stdout);
rx_count--;
} else {
if(spi_in) {
//printf("[Found 0x%02X pending chars]\n", spi_in);
rx_count = spi_in;
printing = 1;
}
}
if(rx_count) {
spi_out = 0x00;
tx_requested = 1;
on_spi_complete = spi_print;
last_time = 0;
} else {
printing = 0;
}
}
int main(int argc, char* argv[]) {
//Get args
if(argc > 1) {
int i;
for(i = 1; i < argc; i++) {
if(!strcmp(argv[i], "--debug"))
debugger_is_on = 1;
}
}
//debugger_is_on = debugger_is_enabled;
CPU_reset();
//CPU_setTrace(0)
CPUEvent_initialize();
CPU_setUpdatePeriod(1);
system_controller = new SystemControllerCPLD("boot.rom");
if (!system_controller->GetInitOk()) {
printf("Couldn't bring up the system. Exiting.\n");
return 0;
}
printf("Starting execution\n");
signal(SIGINT, int_handler);
CPU_run();
return 0;
}
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <bitset>
#include <deque>
const long long LINF = (5e18);
const int INF = (1<<29);
#define EPS 1e-6
const int MOD = 1000000007;
using namespace std;
class SentenceDecomposition {
public:
string s;
vector<string> vw;
int dp[200];
int check(string &buf, string &candidate) {
if (buf.size() != candidate.size())
return -1;
string A(buf), B(candidate);
sort(A.begin(), A.end());
sort(B.begin(), B.end());
if (A != B)
return -1;
int res = 0;
int N = (int)buf.size();
for (int i=0; i<N; ++i) {
if (buf[i] != candidate[i]) {
++res;
}
}
return res;
}
int dfs(int len) {
if (dp[len] != -1)
return dp[len];
if (len == 0 )
return 0;
int res = INF;
for (string candidate: vw) {
int len1 = (int)candidate.size();
if (len < len1)
continue;
string buf = s.substr(len - len1, len1);
int diff = check(buf, candidate);
if (diff != -1) {
res = min(res, diff + dfs(len - len1));
}
}
return dp[len] = res;
}
int decompose(string sentence, vector <string> validWords) {
this->s = sentence;
this->vw = validWords;
memset(dp, -1, sizeof(dp));
string buf = "";
int ans = dfs(int(sentence.size()) );
return ans == INF ? -1 : ans;
}
// 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(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); if ((Case == -1) || (Case == 7)) test_case_7(); }
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 int &Expected, const int &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() { string Arg0 = "neotowheret"; string Arr1[] = {"one", "two", "three", "there"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 8; verify_case(0, Arg2, decompose(Arg0, Arg1)); }
void test_case_1() { string Arg0 = "abba"; string Arr1[] = {"ab", "ac", "ad"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; verify_case(1, Arg2, decompose(Arg0, Arg1)); }
void test_case_2() { string Arg0 = "thisismeaningless"; string Arr1[] = {"this", "is", "meaningful"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = -1; verify_case(2, Arg2, decompose(Arg0, Arg1)); }
void test_case_3() { string Arg0 = "ommwreehisymkiml"; string Arr1[] = {"we", "were", "here", "my", "is", "mom", "here", "si", "milk", "where", "si"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 10; verify_case(3, Arg2, decompose(Arg0, Arg1)); }
void test_case_4() { string Arg0 = "ogodtsneeencs"; string Arr1[] = {"go", "good", "do", "sentences", "tense", "scen"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 8; verify_case(4, Arg2, decompose(Arg0, Arg1)); }
void test_case_5() { string Arg0 = "sepawaterords"; string Arr1[] = {"separate","words"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = -1; verify_case(5, Arg2, decompose(Arg0, Arg1)); }
void test_case_6() { string Arg0 = "noonnonnmnnomoonnmooonmnmnnommnomoomommooonommonn"; string Arr1[] = {"mmo", "omon", "mmno", "non", "ono", "nono", "n", "mon", "nomn", "ooonomomnmnmmmnmononmoonomnonnoonoonmonnnmonommon", "mnn", "omom", "moo", "nonn", "oono", "ooo"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 12; verify_case(6, Arg2, decompose(Arg0, Arg1)); }
void test_case_7() { string Arg0 = "asddsaasddsaasddsaasddssdasdadadasddsaasddsaasddsa"; string Arr1[] = {"asddsa", "asd", "asdasdasd", "dsadsadsa", "adsasdasdasd", "dsadasdaaddasdadsa", "asdasdasddas", "dsaadsasddsaasdasd", "dsadsadadsadsadas", "adasdasddsa", "sadasdasdas", "dasdasd", "sdadasda", "aasd", "dadads", "asdad", "asdadasdasd", "asddddd", "sdadadad", "asd", "d", "asd", "asdadsadas", "adasdadada", "adasdadasdsad", "asdasdadasda", "adsadasdasda", "dasdadasdad", "dasadsdasadsdas", "daadsadsads", "das", "sadasdadsdsaads", "dasasdadsads", "asasd", "dasdasdasadsdsa", "dasadsadsds", "adsadssa", "ads", "das", "dasads", "ads", "dasdasdsadsa", "dasadsadsasd", "das", "adsdasasdasdads", "adsadsdasdasdasads", "asdadssadadsasd", "adsdasadsads", "dsadsadsadsadda", "asdasd"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(7, Arg2, decompose(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
SentenceDecomposition ___test;
___test.run_test(-1);
}
// END CUT HERE
|
/***********************************************************************
h£ºIRenderer
desc: transfer data to Graphic memory
and use gpu to render
************************************************************************/
#pragma once
#include "_BaseRenderModule.h"
#include "RenderInfrastructure.h"
#include "Renderer_Atmosphere.h"
#include "Renderer_GraphicObj.h"
#include "Renderer_Mesh.h"
#include "Renderer_Text.h"
#include "Renderer_PostProcessing.h"
namespace Noise3D
{
class /*_declspec(dllexport)*/ IRenderer :
private IFactory<IRenderInfrastructure>,
public IRenderModuleForAtmosphere,
public IRenderModuleForGraphicObject,
public IRenderModuleForMesh,
public IRenderModuleForText,
public IRenderModuleForPostProcessing
{
public:
//explicitly overload 'AddToRenderQueue'
//prevent functions with same names are HIDDEN
void AddToRenderQueue(IMesh* obj);
void AddToRenderQueue(IGraphicObject* obj);
void AddToRenderQueue(IDynamicText* obj);
void AddToRenderQueue(IStaticText* obj);
void SetActiveAtmosphere(IAtmosphere* obj);
void Render();//render object in a fixed order
void ClearBackground(const NVECTOR4& color = NVECTOR4(0, 0, 0, 0.0f));
void PresentToScreen();
UINT GetBackBufferWidth();
UINT GetBackBufferHeight();
HWND GetRenderWindowHWND();
uint32_t GetRenderWindowWidth();
uint32_t GetRenderWindowHeight();
void SwitchToFullScreenMode();
void SwitchToWindowedMode();
//void BakeLightMapForMesh(IMesh* pMesh);//bake light map for static scenes,automatic uv flatten is required.
private:
//extern init by IScene
bool NOISE_MACRO_FUNCTION_EXTERN_CALL mFunction_Init(UINT bufferWidth, UINT bufferHeight, HWND renderWindowHandle);
private:
friend IScene;//for external init
friend IFactory<IRenderer>;
IRenderer();
~IRenderer();
IRenderInfrastructure* m_pRenderInfrastructure;
};
}
|
// Question 2 => Check whether a string is Palindrome or not
#include<iostream>
using namespace std;
int main(){
string str = "LOL";
int sizeee = str.size();
bool check = 1;
for(int i=0; i<sizeee; i++){
if(str[i] != str[sizeee - 1 - i]){
check = 0;
break;
}
}
cout<<check;
}
|
#include <iostream>
using namespace std;
int main(){
int n, res1=0 , res2=0, res;
for (int i=0; i<=9; i++){
cin >> n;
if (i%2==0){
res1= ((res1+n)+abs(res1-n))/2;
}
else {
res2= ((res2+n)+abs(res2-n))/2;
}
}
res = ((res1+res2)-abs(res1-res2))/2;
cout << "2nd largest value: " << res << endl;
return 0;
}
|
#ifndef PROJECTILE_H
#define PROJECTILE_H
#pragma warning (disable:4786)
//-----------------------------------------------------------------------------
//
// Name: Raven_Projectile.h
//
// Author: Mat Buckland (www.ai-junkie.com)
//
// Desc: Base class to define a projectile type. A projectile of the correct
// type is created whnever a weapon is fired. In Raven there are four
// types of projectile: Slugs (railgun), Pellets (shotgun), Rockets
// (rocket launcher ) and Bolts (Blaster)
//-----------------------------------------------------------------------------
#include <list>
#include "cocos2d.h"
#include "BaseEntity.h"
#include "Messages.h"
#include "MessageDispatcher.h"
#include "EntityManager.h"
USING_NS_CC;
class BaseEntity;
class Projectile : public MovingEntity
{
protected:
// if the projectile make splaches,
// this is the maximum entity that
// can be hit
int m_iMaxSplash;
//the ID of the entity that fired this
int m_iShooterID;
//the place the projectile is aimed at
Vec2 m_vTarget;
//a pointer to the world data
//Raven_Game* m_pWorld;
//where the projectile was fired from
Vec2 m_vOrigin;
//how much damage the projectile inflicts
int m_iDamageInflicted;
//is it dead? A dead projectile is one that has come to the end of its
//trajectory and cycled through any explosion sequence. A dead projectile
//can be removed from the world environment and deleted.
bool m_bDead;
//this is set to true as soon as a projectile hits something
bool m_bImpacted;
//the position where this projectile impacts an object
Vec2 m_vImpactPoint;
//this is stamped with the time this projectile was instantiated. This is
//to enable the shot to be rendered for a specific length of time
double m_dTimeOfCreation;
//BaseEntity* GetClosestIntersectingBot(/*Vector2D From,
// Vector2D To*/)const;
BaseEntity* GetClosestIntersectingBot();
std::list<BaseEntity*> GetListOfIntersectingBots(/*Vector2D From,
Vector2D To*/)/*const*/;
// does ot do splash
bool m_bSplash;
// useful for moving
CCAction* m_ActionToDest;
// particle projectile
CCParticleSystemQuad* m_pParticle;
public:
Projectile(Vec2 position, Vec2 target);
Projectile(int shooterId, Vec2 position, Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
virtual void Seek(BaseEntity* owner);
//unimportant for this class unless you want to implement a full state
//save/restore (which can be useful for debugging purposes)
void Write(std::ostream& os)const{}
void Read(std::ifstream& is){}
//must be implemented
virtual void update(float fDelta);
//set to true if the projectile has impacted and has finished any explosion
//sequence. When true the projectile will be removed from the game
bool isDead()const{ return m_bDead; }
//true if the projectile has impacted but is not yet dead (because it
//may be exploding outwards from the point of impact for example)
bool HasImpacted()const{ return m_bImpacted; }
//tests the trajectory of the shell for an impact
virtual void TestForImpact();
// movement + pathfinding
virtual void updateMovement(float fDelta);
void moveTo();
CCAction* getActionTodDest(){ return m_ActionToDest; }
// set the shooter
void setShooterID(int i){ m_iShooterID = i; }
};
// projectile torpedos
class Projectile1 :public Projectile
{
protected:
public:
Projectile1(Vec2 position, Vec2 target);
Projectile1(BaseEntity* shooter, Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
// projectile torpedos
class Projectile2 :public Projectile
{
protected:
public:
Projectile2(Vec2 position, Vec2 target);
Projectile2(BaseEntity* shooter, Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
// projectile alien 1
class Projectile3 :public Projectile
{
protected:
public:
Projectile3(Vec2 position, Vec2 target);
Projectile3(BaseEntity* shooter, Vec2 target);
//Projectile1(BaseEntity* shooter,Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
// projectile alien 1
class Projectile4 :public Projectile
{
protected:
public:
Projectile4(Vec2 position, Vec2 target);
Projectile4(BaseEntity* shooter, Vec2 target);
//Projectile1(BaseEntity* shooter,Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
// projectile alien 1
class Projectile5 :public Projectile
{
protected:
public:
Projectile5(Vec2 position, Vec2 target);
Projectile5(BaseEntity* shooter, Vec2 target);
//Projectile1(BaseEntity* shooter,Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
// projectile alien 1
class Projectile6 :public Projectile
{
protected:
public:
Projectile6(Vec2 position, Vec2 target);
Projectile6(BaseEntity* shooter, Vec2 target);
//Projectile1(BaseEntity* shooter,Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
// projectile alien 5 THIS PROJECTILE WIIL THROW MINISHIP
class Projectile7 :public Projectile
{
protected:
public:
Projectile7(Vec2 position, Vec2 target);
Projectile7(BaseEntity* shooter, Vec2 target);
//Projectile1(BaseEntity* shooter,Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
class Projectile8 :public Projectile
{
protected:
public:
Projectile8(Vec2 position, Vec2 target);
Projectile8(BaseEntity* shooter, Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
class Projectile9 :public Projectile
{
protected:
public:
Projectile9(Vec2 position, Vec2 target);
Projectile9(BaseEntity* shooter, Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
class Projectile10 :public Projectile
{
protected:
public:
Projectile10(Vec2 position, Vec2 target);
Projectile10(BaseEntity* shooter, Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
// for thor
class Projectile11 :public Projectile
{
protected:
public:
Projectile11(Vec2 position, Vec2 target);
Projectile11(BaseEntity* shooter, Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
// for ultralisk
class Projectile12 :public Projectile
{
protected:
public:
Projectile12(Vec2 position, Vec2 target);
Projectile12(BaseEntity* shooter, Vec2 target);
// for this time, only thies mlethod id necessary
virtual void Start();
};
#endif
|
#include <iostream>
#include <math.h>
#include <stdlib.h>
//#define EXPECTED_ARG_COUNT 1
using namespace std;
extern float f(float t);
int main (const int argc, const char * const argv[])
{
if (argc < 2){
cerr << "Error: Expected 1 argument; received " << argc-1 << "; exiting" << endl;
return -1;
}
if (argc > 2){
cerr << "Warning: Expected 1 arguments; received " << argc-1 << "; ignoring extraneous arguments" << endl;
}
const float delta = 0.0001;
float t = atof(argv[1]);
/*float t1 = t - 0.0001;
float t2 = t + 0.0001;*/
float slope = (f(t + delta) - f(t - delta))/(2*delta);
cout << "The slope of f(t) at t = " << t << "is " << slope << endl;
return 0;
}
|
#ifndef ITEM_H_
#define ITEM_H_
#include <string>
#include <vector>
#include <iostream>
#include "gameObjects.h"
#include "../rapidxml/rapidxml.hpp"
#include "../rapidxml/rapidxml_utils.hpp"
#include "../rapidxml/rapidxml_print.hpp"
using namespace std;
using namespace rapidxml;
typedef struct _turn_on{
string print;
string action;
} turn_on;
class Item: public gameObjects{
private:
string writing;
turn_on turnOn;
public:
Item(xml_node<> * itemTag);
void setWriting(string);
string getWriting();
void setTurnOn(string, string);
turn_on getTurnOn();
};
#endif
|
//*************************************************************************************************************
//
// 自作の標準ライブラリのユーティリティ処理 [mystd_utility.h]
// Author : IKUTO SEKINE
//
//*************************************************************************************************************
#pragma once
#ifndef _MYSTD_UTILITY_H_
#define _MYSTD_UTILITY_H_
//-------------------------------------------------------------------------------------------------------------
// インクルードファイル
//-------------------------------------------------------------------------------------------------------------
#include "mystd.h"
//-------------------------------------------------------------------------------------------------------------
// マクロ関数
//-------------------------------------------------------------------------------------------------------------
//#define iif(a, b, c) a ? b : c
//-------------------------------------------------------------------------------------------------------------
// 名前空間定義
//-------------------------------------------------------------------------------------------------------------
_BEGIN_MYSTD
/*
$ constants
*/
// *Can be halved by multiplication
static constexpr f32_t fHalfSize = 0.5f;
// Pi
static constexpr f32_t fPi = 3.141592654f;
// *Half of Pi
static constexpr f32_t fHalf_PI = fPi * fHalfSize;
// Number of polygon vertices
static constexpr u32_t nNumPolygon = 4;
/*
$ functions
*/
// *Prints half the value of the argument set in rsc
template<class outT, class rscT>
inline void Convert_to_half_size(outT& out, rscT& rsc)
{
out = rsc * fHalfSize;
}
_END_MYSTD
#endif
|
#include<bits/stdc++.h>
using namespace std;
#define maxn 1000010
#define maxm 2000010
int N,M;
int fa[maxn];
int mp[1005][1005];
int ind=1;
struct edge{
int x,y,w;
edge(int x=0,int y=0,int w=0):x(x),y(y),w(w){}
}e[maxm];
bool cmp(edge a,edge b){
return a.w<b.w;
}
int getfather(int x){
if(x==fa[x])
return x;
else
return fa[x]=getfather(fa[x]);
}
int kruscal(){
int ans=0;
sort(e+1,e+M+1,cmp);
int cnt=N;
for(int i=1;i<=N;i++)
fa[i]=i;
for(int i=1;i<=M;i++){
int t1=getfather(e[i].x);
int t2=getfather(e[i].y);
if(t1!=t2){
fa[t1]=t2;
ans+=e[i].w;
if(cnt==1)
break;
}
}
return ans;
}
int main(){
int T;
scanf("%d",&T);
int cas=0;
while(T--){
cas++;
ind=1;
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%d",&mp[i][j]);
if(j>1){
e[ind].x=(i-1)*m+j-1;
e[ind].y=(i-1)*m+j;
e[ind].w=abs(mp[i][j]-mp[i][j-1]);
ind++;
}
if(i>1){
e[ind].x=(i-2)*m+j;
e[ind].y=(i-1)*m+j;
e[ind].w=abs(mp[i][j]-mp[i-1][j]);
ind++;
}
}
}
N=n*m;
M=ind-1;
printf("Case #%d:\n",cas);
int ans=kruscal();
printf("%d\n",ans);
}
return 0;
}
|
#pragma once
class PlayerComp;
class GrapplerComp;
/*
Tri Segments:
1. 0 - 2.0944
2. 2.0945 - 4.1887
3. 4.1888 - 6.2832
*/
class AI_RadialPatrol : public Hourglass::IAction
{
public:
void LoadFromXML( tinyxml2::XMLElement* data );
void Start();
void Init( Hourglass::Entity* entity );
IBehavior::Result Update( Hourglass::Entity* entity );
IBehavior* MakeCopy() const;
private:
hg::Motor* m_Motor;
hg::Transform* m_Player;
PlayerComp* m_PlayerComp;
float m_Timer;
float m_IntervalTimer;
uint32_t m_MovingRight : 1;
float m_PatrolDuration;
float m_PatrolRadius;
float m_PatrolSpeed;
Vector3 m_Center;
};
|
#include<iostream>
#include<cstring>
using namespace std;
const int p[]={3,5,7,11,13,17,19,23,29,31,37};
int num[25];
int use[25];
int n;
void order()
{
for (int i = 1;i < n; i++) cout << num[i] << " ";
cout << num[n] << endl;
}
bool prime(int a)
{
for (int i = 0;i < 11;i++)
if (a == p[i]) return true;
return false;
}
void dfs(int k)
{
//1cout << k << " " << num[k] << endl;
if (k == n)
{if ( prime(num[n]+1) ) order();
return;
}
for (int i = 2;i <= n; i++)
if ((!use[i]) && (prime(num[k]+i)))
{use[i]=1;num[k+1]=i;
dfs(k+1);
use[i]=0;
}
}
int main()
{int t=0;
while (cin >> n)
{cout << "Case " << ++t << ":" << endl;
memset(use,0,sizeof(use));
num[1]=1;
dfs(1);
cout << endl;
}
return 0;
}
|
/*
replay
Software Library
Copyright (c) 2010-2019 Marius Elvert
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 replay_lines3_hpp
#define replay_lines3_hpp
#include <limits>
#include <replay/interval.hpp>
#include <replay/vector3.hpp>
namespace replay
{
/** Base class for parametric line-like objects, like lines, rays and segments.
Represents a function \f$R \longrightarrow R^3\f$.
\ingroup Math
*/
class linear_component3
{
public:
/** Origin. Point at parameter 0.
*/
vector3f origin;
/** Direction. Corresponds to a difference of 1 in the parameter.
*/
vector3f direction;
/** Get the point: \f$origin + t * direction\f$.
\param t The parameter to the equation.
*/
vector3f get_point(const float t) const
{
return direction * t + origin;
}
/** Set this by another linear component.
*/
void set(const linear_component3& line)
{
origin = line.origin;
direction = line.direction;
}
/** Set via origin and direction.
*/
void set(const vector3f& origin, const vector3f& direction)
{
this->origin = origin;
this->direction = direction;
}
protected:
/** Create an uninitialized linear component.
*/
linear_component3()
{
}
/** Create a linear component by origin and direction.
*/
linear_component3(const vector3f& origin, const vector3f& direction)
: origin(origin)
, direction(direction)
{
}
};
/** Linear Component that exceeds to infinity in both directions.
\ingroup Math
*/
class line3 : public linear_component3
{
public:
/** Create an uninitialized line.
*/
line3()
{
}
/** Cast a linear component to a line.
*/
explicit line3(const linear_component3& line)
: linear_component3(line)
{
}
/** Create a line from origin and direction.
*/
line3(const vector3f& origin, const vector3f& direction)
: linear_component3(origin, direction)
{
}
/** Create a line from two points on the line.
These points must not be colinear.
*/
static line3 from_points(const vector3f& a, const vector3f& b)
{
return line3(a, b - a);
}
};
/** Linear Component in the \f$[0..\infty)\f$ interval.
\ingroup Math
*/
class ray3 : public linear_component3
{
public:
/** Create and uninitialized ray.
*/
ray3()
{
}
/** Cast a linear component to a ray.
*/
explicit ray3(const linear_component3& line)
: linear_component3(line)
{
}
/** Create a ray from direction and origin.
*/
ray3(const vector3f& origin, const vector3f& direction)
: linear_component3(origin, direction)
{
}
};
/** Linear Component in the \f$[0..1]\f$ interval.
\ingroup Math
*/
class segment3 : public linear_component3
{
public:
/** Create an uninitialized segment.
*/
segment3()
{
}
/** Cast a linear component to a segment.
*/
explicit segment3(const linear_component3& line)
: linear_component3(line)
{
}
/** Create a segment from origin and difference to the second point.
*/
segment3(const vector3f& origin, const vector3f& direction)
: linear_component3(origin, direction)
{
}
};
/** Linear Component with a variable interval.
This is a logical line, ray or segment, depending on whether the interval is unbounded.
\note Althought this class is a little heavier than line, ray and segment, this is a lot better for clipping.
\ingroup Math
*/
class line_interval3 : public linear_component3
{
public:
replay::interval<> interval; /**< begin -> end */
/** Create a unbounded line interval.
*/
line_interval3()
: interval(-std::numeric_limits<float>::max(), std::numeric_limits<float>::max())
{
}
/** Cast a line to an unbounded line interval.
*/
explicit line_interval3(const line3& x)
: linear_component3(x)
, interval(-std::numeric_limits<float>::max(), std::numeric_limits<float>::max())
{
}
/** Cast a segment to a bounded line interval.
*/
explicit line_interval3(const segment3& x)
: linear_component3(x)
, interval(0.f, 1.f)
{
}
/** Cast a ray to a half bounded line interval.
*/
explicit line_interval3(const ray3& x)
: linear_component3(x)
, interval(0.f, std::numeric_limits<float>::max())
{
}
/** Create a line interval from a linear component and a parameter interval.
*/
line_interval3(const linear_component3& x, replay::interval<> const& interval)
: linear_component3(x)
, interval(interval)
{
}
/** Create a line interval from a linear component and a parameter interval.
*/
line_interval3(const linear_component3& x, const float min, const float max)
: linear_component3(x)
, interval(min, max)
{
}
/** Create a line interval from origin, direction and optional interval parameters.
*/
line_interval3(const vector3f& origin,
const vector3f& direction,
const float min = -std::numeric_limits<float>::max(),
const float max = std::numeric_limits<float>::max())
: linear_component3(origin, direction)
, interval(min, max)
{
}
/** Cast a segment to a bounded line interval.
*/
void set_segment(const segment3& x)
{
linear_component3::set(x);
interval.set(0.f, 1.f);
}
/** Cast a ray to a half bounded line interval.
*/
void set_ray(const ray3& x)
{
linear_component3::set(x);
interval.set(0.f, std::numeric_limits<float>::max());
}
/** Cast a line to an unbounded line interval.
*/
void set_line(const line3& x)
{
linear_component3::set(x);
interval.set(-std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
}
/** Get the point on the lower interval border.
*/
vector3f get_min_point() const
{
return direction * interval[0] + origin;
}
/** Get the point on the upper interval border.
*/
vector3f get_max_point() const
{
return direction * interval[1] + origin;
}
/** Set from a linear component and an interval.
*/
void set(const linear_component3& x, replay::interval<> const& interval)
{
linear_component3::set(x);
this->interval = interval;
}
/** Set from a linear component and an interval.
*/
void set(const linear_component3& x, const float min, const float max)
{
linear_component3::set(x);
this->interval.set(min, max);
}
/** Check wether the attached interval is empty.
*/
bool empty() const
{
return interval[0] > interval[1];
}
};
}
#endif // replay_lines3_hpp
|
#ifndef SOPNET_GUI_ERRORS_VIEW_H__
#define SOPNET_GUI_ERRORS_VIEW_H__
#include <sstream>
#include <pipeline/all.h>
#include <gui/TextPainter.h>
#include <sopnet/evaluation/Errors.h>
class ErrorsView : public pipeline::SimpleProcessNode<> {
public:
ErrorsView() {
registerInput(_errors, "errors");
registerInput(_variationOfInformation, "variation of information");
registerOutput(_painter, "painter");
_painter.registerForwardSlot(_sizeChanged);
}
private:
void updateOutputs() {
std::stringstream ss;
ss
<< "false positives: " << _errors->numFalsePositives() << ", "
<< "false negatives: " << _errors->numFalseNegatives() << ", "
<< "false splits: " << _errors->numFalseSplits() << ", "
<< "false merges: " << _errors->numFalseMerges() << " -- "
<< "variation of information: " << *_variationOfInformation << std::endl;
_painter->setText(ss.str());
_sizeChanged(_painter->getSize());
}
pipeline::Input<Errors> _errors;
pipeline::Input<double> _variationOfInformation;
pipeline::Output<gui::TextPainter> _painter;
signals::Slot<const gui::SizeChanged> _sizeChanged;
};
#endif // SOPNET_GUI_ERRORS_VIEW_H__
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int n;
while(cin>>n)
{
int i, j, k, a[100], b[100], x, y, ans=0;
for(k=0; k<n; k++)
{
cin>>x>>y;
a[k] = x;
b[k] = y;
}
for(i=0; i<n; i++){
for(j=0; j<n; j++){
if(i!=j && a[i]==b[j])ans++;
}
}
cout<<ans<<endl;
}
return 0;
}
|
#include <iostream>
#include <boost/random.hpp>
// g++ boost_example_random.cpp -lboost_random
int main() {
// 伯努利分布: 在0/1中随机产生一个数,就像抛硬币,不是0,就是1
// 随机数生成器
boost::random::mt19937 gen(time(nullptr));
// 随机数分布器
boost::random::bernoulli_distribution<> dist;
std::cout << "Test -lboost_random bernoulli_distribution API: \n";
for (int i = 0; i < 10; ++i) {
std::cout << dist(gen) << ' ';
}
std::cout << '\n';
}
|
#include <iostream>
#include <stdio.h>
#include <string>
#include <limits.h>
using namespace std;
int get_cost(int *dim, int num) {
int c[num][num];
int min, cost;
for(int i = 0; i < num; i++)
c[i][i] = 0;
for(int i =0; i < num; i++) {
for(int j = 0; j < num; j++)
printf("%12d", c[i][j]);
printf("\n");
}
for(int s = 0; s < num; s++) {
for(int i = 0; i < num - s; i++) {
min = 0x7fffffff;
int j = i + s;
for(int k = i; k < j; k++) {
printf(" i %d k %d j %d (%d %d) (%d x %d x %d)\n", i, k, j, c[i][k], c[k+1][j], dim[i], dim[k+1], dim[j+1]);
cost = c[i][k] + c[k+1][j] + (dim[i] * dim[k+1] * dim[j+1]);
if (cost < min) {
min = cost;
c[i][j] = min;
}
}
}
}
for(int i =0; i < num; i++) {
for(int j = 0; j < num; j++)
printf("%12d", c[i][j]);
printf("\n");
}
return c[0][num-1];
}
int main() {
int num;
int *dim;
cin >> num;
dim = new int[num+1];
for(int i = 0; i <= num; i++)
cin >> dim[i];
for(int i = 0; i < num+1; i++) cout << dim[i] << " ";
cout << endl;
int cost = get_cost(dim, num);
cout << cost << endl;
return 0;
}
|
#pragma once
#include"ybBasicMacro.h"
NS_YB_BEGIN
#define FORMAT_BMP (1);
class Image;
class FileHandle;
class ImageIO
{
public:
virtual bool Write(Image* img, FileHandle* file) = 0;
virtual Image* Read(FileHandle* name) = 0;
virtual int Format()=0;
};
NS_YB_END
|
#include "../Hardware/Registers.hpp"
#include <avr/pgmspace.h>
#include <util/delay.h>
#pragma once
using namespace Hardware;
#define _str(x) (char*)x
namespace Drivers
{
class Display
{
public:
Display() = delete;
static const uint8_t Width = 84;
static const uint8_t Hight = 48;
enum Color {White = 0, Black=1};
static void init(void);
static void clear(bool color = 0);
static void display(void);
static void drawBorder();
static bool getPoint(uint8_t x, uint8_t y);
static void drawPoint(uint8_t x, uint8_t y, bool color);
static void drawRectangle(uint8_t x, uint8_t y,uint8_t w,uint8_t h, bool color);
static void drawBitmap(uint8_t x, uint8_t y,uint8_t w,uint8_t h, const uint8_t image[], bool invert = false);
static void drawText(uint8_t x, uint8_t y,char* str, bool invert = false, const uint8_t font[] = DefaultFont,uint8_t letterX = 6,uint8_t letterY = 8);
static const uint8_t LeftArrow[] PROGMEM;
static const uint8_t RightArrow[] PROGMEM;
private:
static uint8_t buffor[Width*Hight/8];
private:
enum SendType {Command=0, Data=1};
static void sendByte(uint8_t type, uint8_t data);
private:
// 0-9,:,A-Z
static const uint8_t DefaultFont[] PROGMEM;
private:
typedef Hardware::RegDef<Hardware::RegName::portB> Port;
typedef Hardware::RegDef<Hardware::RegName::ddrB> Ddr;
static constexpr const uint8_t PinCLK = 5;
static constexpr const uint8_t PinDIN = 3;
static constexpr const uint8_t PinCE = 2;
static constexpr const uint8_t PinDC = 1;
static constexpr const uint8_t PinRST = 0;
};
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2008-2010 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef CRYPTO_SIGNATURE_IMPL_H
#define CRYPTO_SIGNATURE_IMPL_H
#ifdef CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION
#include "modules/libcrypto/include/CryptoSignature.h"
#include "modules/libopeay/openssl/cryptlib.h"
#include "modules/libopeay/openssl/x509.h"
#include "modules/libopeay/openssl/x509v3.h"
class CryptoSignature_impl : public CryptoSignature
{
public:
CryptoSignature_impl( CryptoCipherAlgorithm cipher_algorithm, CryptoHashAlgorithm hash_algorithm);
virtual ~CryptoSignature_impl();
virtual OP_STATUS SetPublicKey(const UINT8 *public_key, int key_length);
virtual OP_STATUS VerifyASN1(const UINT8 *hash_reference, int reference_length, UINT8 *signature, int signature_length);
virtual OP_STATUS Verify(const UINT8 *hash_reference, int reference_length, const UINT8 *signature, int signature_length);
private:
CryptoCipherAlgorithm m_cipher_algorithm;
CryptoHashAlgorithm m_hash_algorithm;
EVP_PKEY *m_keyspec;
};
#endif // CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION
#endif /* CRYPTO_SIGNATURE_IMPL_H */
|
/****************************************************************
* TianGong RenderLab *
* Copyright (c) Gaiyitp9. All rights reserved. *
* This code is licensed under the MIT License (MIT). *
*****************************************************************/
#pragma once
#include <cassert>
namespace TG::Math
{
// 对齐数组
template<typename T, int Size, int Alignment = default_alignment<T, Size>>
struct PlainArray
{
alignas(Alignment) T array[Size];
};
// 非对齐数组
template<typename T, int Size>
struct PlainArray<T, Size, 0>
{
T array[Size];
};
// 分配对齐内存
// 手动分配对齐内存的原理: 分配size+alignment的内存空间,分为两部分,后一部分的起始地址与alignment对齐,
// 该地址也是返回的地址;前一部分记录内存地址,用来释放内存块。
// 注: c++标准明确要求动态分配的内存必须满足一定的对齐要求,一般是16字节对齐
// https://stackoverflow.com/questions/59098246/why-is-dynamically-allocated-memory-always-16-bytes-aligned
// 而对齐要求是16或32,所以内存块的前一部分的大小一定大于一个指针的大小
inline void* handmade_aligned_malloc(std::size_t size, std::size_t alignment)
{
assert(alignment >= sizeof(void*) && (alignment & (alignment - 1)) == 0 && "Alignment must be at least sizeof(void*) and a power of 2");
void* original = malloc(size + alignment);
if (original == nullptr)
return nullptr;
void* aligned = reinterpret_cast<void*>((reinterpret_cast<size_t>(original) & ~(size_t(alignment - 1))) + alignment);
*(reinterpret_cast<void**>(original) - 1) = original;
return aligned;
}
// 释放对齐内存
inline void handmade_aligned_free(void* ptr)
{
if (ptr)
free(*(reinterpret_cast<void**>(ptr) - 1));
}
// 根据条件分配动态内存(默认16字节对齐)
template<bool Align>
inline void* conditional_aligned_alloc(size_t size)
{
return malloc(size);
}
template<>
inline void* conditional_aligned_alloc<true>(size_t size)
{
return handmade_aligned_malloc(size, DEFAULT_ALIGN_BYTES);
}
// 根据条件释放内存
template<bool Align>
inline void conditional_aligned_free(void* ptr)
{
if (ptr)
free(ptr);
}
template<>
inline void conditional_aligned_free<true>(void* ptr)
{
handmade_aligned_free(ptr);
}
template<typename T, int Size, int Rows, int Cols>
class Storage
{
public:
Storage()
{
std::memset(m_data.array, 0, Size * sizeof(T));
}
Storage(const Storage& other)
{
std::memcpy(m_data.array, other.m_data.array, Size * sizeof(T));
}
~Storage() = default;
public:
const T& operator[](size_t index) const
{
if (index >= Size)
throw BaseException(L"Index Out of Range");
return m_data.array[index];
}
T& operator[](size_t index)
{
if (index >= Size)
throw BaseException(L"Index Out of Range");
return m_data.array[index];
}
T const* data() const { return m_data.array; }
T* data() { return m_data.array; }
constexpr int rows() const noexcept { return Rows; }
constexpr int cols() const noexcept { return Cols; }
constexpr int size() const noexcept { return Size; }
private:
PlainArray<T, Size> m_data;
};
template<typename T>
class Storage<T, DYNAMIC, DYNAMIC, DYNAMIC>
{
public:
Storage() : m_data(nullptr), m_rows(0), m_cols(0) {}
Storage(const Storage& other)
{
std::memcpy(m_data, other.m_data, m_size * sizeof(T));
}
~Storage() { conditional_aligned_free<SUPPORT_SIMD>(m_data); }
void resize(int size, int rows, int cols)
{
if (size != m_rows * m_cols)
{
conditional_aligned_free<SUPPORT_SIMD>(m_data);
if (size > 0)
m_data = reinterpret_cast<T*>(conditional_aligned_alloc<SUPPORT_SIMD>(sizeof(T) * size));
else
m_data = nullptr;
}
m_rows = rows;
m_cols = cols;
m_size = size;
}
const T& operator[](size_t index) const
{
if(index >= m_size)
throw BaseException(L"Index Out of Range");
return m_data.array[index];
}
T& operator[](size_t index)
{
if (index >= m_size)
throw BaseException(L"Index Out of Range");
return m_data.array[index];
}
T const* data() const noexcept { return m_data; }
T* data() noexcept { return m_data; }
int rows() const noexcept { return m_rows; }
int cols() const noexcept { return m_cols; }
int size() const noexcept { return m_size; }
private:
T* m_data;
int m_rows;
int m_cols;
int m_size;
};
}
|
#include <iostream>
#include <opencv2/opencv.hpp> //头文件
#include <opencv2/xfeatures2d.hpp>
using namespace cv; //包含cv命名空间
using namespace std;
int main()
{
//Create SIFT class pointer
Ptr<Feature2D> f2d = xfeatures2d::SIFT::create();
//读入图片
Mat img_1 = imread("/home/lcy/文档/opencvtest/img/3.jpg");
Mat img_2 = imread("/home/lcy/文档/opencvtest/img/4.jpg");
//Detect the keypoints
vector<KeyPoint> keypoints_1, keypoints_2;
f2d->detect(img_1, keypoints_1);
f2d->detect(img_2, keypoints_2);
//Calculate descriptors (feature vectors)
Mat descriptors_1, descriptors_2;
f2d->compute(img_1, keypoints_1, descriptors_1);
f2d->compute(img_2, keypoints_2, descriptors_2);
cout << descriptors_1.size();
cout << img_1.size();
//Matching descriptor vector using BFMatcher
BFMatcher matcher;
vector<DMatch> matches;
matcher.match(descriptors_1, descriptors_2, matches);
//绘制匹配出的关键点
Mat img_matches;
drawMatches(img_1, keypoints_1, img_2, keypoints_2, matches, img_matches);
imshow("【match图】", img_matches);
//等待任意按键按下
waitKey(0);
}
|
#include <stack>
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
vector<int> Tree[30];
vector<int> reslut;
/*遍历*/
void postOrderTraversal(int fNode)
{
if (Tree[fNode].size() == 1) {
postOrderTraversal(Tree[fNode][0]); //后序遍历的特点
reslut.push_back(fNode);
}
else if (Tree[fNode].size() == 2) {
postOrderTraversal(Tree[fNode][0]);
postOrderTraversal(Tree[fNode][1]);
reslut.push_back(fNode);
}
else {
reslut.push_back(fNode);
}
}
int main()
{
int n, i, val,
root = 0,
popVal = -1;
stack<int> stk;
cin >> n;
string action;
cin >> action;
cin >> root;
stk.push(root);
for (i = 1; i < 2 * n; ++i) {
cin >> action;
if (action == "Push") {
scanf("%d", &val);
if (popVal == -1) {
Tree[stk.top()].push_back(val);
}
else {
Tree[popVal].push_back(val);
}
stk.push(val);
popVal = -1;
}
else if (action == "Pop") {
popVal = stk.top();
stk.pop();
}
}
postOrderTraversal(root);
for (i = 0; i < reslut.size(); ++i) {
cout << reslut[i] << ((i == reslut.size()-1) ? '\n' : ' ');
}
return 0;
}
|
// Created on: 1999-05-14
// Created by: Pavel DURANDIN
// 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 _ShapeUpgrade_ShapeConvertToBezier_HeaderFile
#define _ShapeUpgrade_ShapeConvertToBezier_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Integer.hxx>
#include <ShapeUpgrade_ShapeDivide.hxx>
class TopoDS_Shape;
class ShapeUpgrade_FaceDivide;
class Message_Msg;
//! API class for performing conversion of 3D, 2D curves to bezier curves
//! and surfaces to bezier based surfaces (
//! bezier surface,
//! surface of revolution based on bezier curve,
//! offset surface based on any previous type).
class ShapeUpgrade_ShapeConvertToBezier : public ShapeUpgrade_ShapeDivide
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor.
Standard_EXPORT ShapeUpgrade_ShapeConvertToBezier();
//! Initialize by a Shape.
Standard_EXPORT ShapeUpgrade_ShapeConvertToBezier(const TopoDS_Shape& S);
//! Sets mode for conversion 2D curves to bezier.
void Set2dConversion (const Standard_Boolean mode);
//! Returns the 2D conversion mode.
Standard_Boolean Get2dConversion() const;
//! Sets mode for conversion 3d curves to bezier.
void Set3dConversion (const Standard_Boolean mode);
//! Returns the 3D conversion mode.
Standard_Boolean Get3dConversion() const;
//! Sets mode for conversion surfaces curves to
//! bezier basis.
void SetSurfaceConversion (const Standard_Boolean mode);
//! Returns the surface conversion mode.
Standard_Boolean GetSurfaceConversion() const;
//! Sets mode for conversion Geom_Line to bezier.
void Set3dLineConversion (const Standard_Boolean mode);
//! Returns the Geom_Line conversion mode.
Standard_Boolean Get3dLineConversion() const;
//! Sets mode for conversion Geom_Circle to bezier.
void Set3dCircleConversion (const Standard_Boolean mode);
//! Returns the Geom_Circle conversion mode.
Standard_Boolean Get3dCircleConversion() const;
//! Sets mode for conversion Geom_Conic to bezier.
void Set3dConicConversion (const Standard_Boolean mode);
//! Returns the Geom_Conic conversion mode.
Standard_Boolean Get3dConicConversion() const;
//! Sets mode for conversion Geom_Plane to Bezier
void SetPlaneMode (const Standard_Boolean mode);
//! Returns the Geom_Pline conversion mode.
Standard_Boolean GetPlaneMode() const;
//! Sets mode for conversion Geom_SurfaceOfRevolution to Bezier
void SetRevolutionMode (const Standard_Boolean mode);
//! Returns the Geom_SurfaceOfRevolution conversion mode.
Standard_Boolean GetRevolutionMode() const;
//! Sets mode for conversion Geom_SurfaceOfLinearExtrusion to Bezier
void SetExtrusionMode (const Standard_Boolean mode);
//! Returns the Geom_SurfaceOfLinearExtrusion conversion mode.
Standard_Boolean GetExtrusionMode() const;
//! Sets mode for conversion Geom_BSplineSurface to Bezier
void SetBSplineMode (const Standard_Boolean mode);
//! Returns the Geom_BSplineSurface conversion mode.
Standard_Boolean GetBSplineMode() const;
//! Performs converting and computes the resulting shape
Standard_EXPORT virtual Standard_Boolean Perform (const Standard_Boolean newContext = Standard_True) Standard_OVERRIDE;
protected:
//! Returns the tool for dividing faces.
Standard_EXPORT virtual Handle(ShapeUpgrade_FaceDivide) GetSplitFaceTool() const Standard_OVERRIDE;
Standard_EXPORT virtual Message_Msg GetFaceMsg() const Standard_OVERRIDE;
Standard_EXPORT virtual Message_Msg GetWireMsg() const Standard_OVERRIDE;
//! Returns a message decsribing modification of a shape.
Standard_EXPORT virtual Message_Msg GetEdgeMsg() const Standard_OVERRIDE;
private:
Standard_Boolean my2dMode;
Standard_Boolean my3dMode;
Standard_Boolean mySurfaceMode;
Standard_Boolean my3dLineMode;
Standard_Boolean my3dCircleMode;
Standard_Boolean my3dConicMode;
Standard_Boolean myPlaneMode;
Standard_Boolean myRevolutionMode;
Standard_Boolean myExtrusionMode;
Standard_Boolean myBSplineMode;
Standard_Integer myLevel;
};
#include <ShapeUpgrade_ShapeConvertToBezier.lxx>
#endif // _ShapeUpgrade_ShapeConvertToBezier_HeaderFile
|
#include<iostream>
#include<vector>
#define FOR(i,n) for(i=0;i<n;i++)
using namespace std;
int main()
{
int i,n,m,k,v,temp,temp2;
while(cin>>n)
{
vector<vector<int>> graph(1000000);
cin>>m;
FOR(i,n)
{
cin>>temp;
graph[temp-1].push_back(i);
}
FOR(i,m)
{
cin>>temp>>temp2;
if(temp>graph[temp2-1].size())
cout<<"0\n";
else
{cout<<graph[temp2-1][temp-1]+1;
cout<<endl;}
}
}
return 0;
}
|
//main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <string>
#include "Image.h"
#include "fileActions.h"
#include "Blending.h"
#include "ImageZoom.h"
using namespace std;
int main()
{
cout << "************************************" << endl;
cout << "Image Stacker / Image Scaler" << endl;
cout << "************************************" << endl;
bool valid = true;
// Object for final image
Image result = Image(3264, 2448);
Blending b;
// Read and add images to a vector
b.loadImages();
do {
cout << "--------------------------" << endl;
cout << " Image Stacking " << endl;
cout << "--------------------------" << endl;
// Select blending function for images
int bChoice;
cout << "Enter 1, 2 or 3 regarding how you would like the images to be blended: " << endl;
cout << "1. Mean Blending" << endl;
cout << "2. Median Blending" << endl;
cout << "3. Sigma Clip Blending" << endl;
cin >> bChoice;
valid = true;
switch (bChoice) {
case 1:
b.meanBlend(&result);
result.setMethod("Mean Blending");
break;
case 2:
b.medianBlend(&result);
result.setMethod("Median Blending");
break;
case 3:
b.sigmaClipBlend(&result);
result.setMethod("Sigma Clip Blending");
break;
default:
system("cls");
cout << "Sorry, we did not understand your input, please enter 1, 2 or 3." << endl;
valid = false; // Set answer invalid
break;
}
if (cin.fail()) {
cout << "Incorrect Input, please enter 1, 2 or 3." << endl;
valid = false;
cin.clear();
cin.ignore();
}
} while (valid == false);
FileActions *file = new FileActions();
// Set image values and display information
result.setName("BlendedImage.ppm");
result.setColorDepth(8);
cout << "\nInfo reagrding blended image: " << endl;
result.ImageInfo(result);
//Output the image data to a file for viewing
file->writePPM(result, "BlendedImage.ppm");
// Delete file object while it is not being used
delete file;
// Clear screen for zooming stage
system("pause");
system("cls");
// Image Zooming
ImageZoom * zoom = new ImageZoom();
Image zImage = file->readPPM("Images/Zoom/zIMG_1.ppm");
// Loop through menu process until a valid input is entered
do {
cout << "--------------------------" << endl;
cout << " Image Scaling " << endl;
cout << "--------------------------" << endl;
cout << "Loading small image ..." << endl;
cout << endl << "Select zoom method and scale for image: " << endl << "1. Nearest Neighbour 2x" << endl << "2. Nearest Neighbour 4x" << endl
<< "3. Bilinear Interpolation 2x" << endl << "4. Bilinear Interpolation 4x" << endl << "5. Region of Interest 2x" << endl << "6. Region of Interest 4x" << endl;
// User input
int zChoice;
std::cin >> zChoice;
valid = true;
switch (zChoice) {
case 1:
zoom->zoomImage(&zImage, zImage.w, zImage.h, zImage.w * 2, zImage.h * 2);
zoom->setScaleSize(2);
zImage.setMethod("Nearest Neighbour");
break;
case 2:
zoom->zoomImage(&zImage, zImage.w, zImage.h, zImage.w * 4, zImage.h * 4);
zoom->setScaleSize(4);
zImage.setMethod("Nearest Neighbour");
break;
case 3:
zoom->bilinearZoom(&zImage, zImage.w * 2, zImage.h * 2);
zoom->setScaleSize(2);
zImage.setMethod("Bilinear Interpolation");
break;
case 4:
zoom->bilinearZoom(&zImage, zImage.w * 4, zImage.h * 4);
zoom->setScaleSize(4);
zImage.setMethod("Bilinear Interpolation");
break;
case 5:
zoom->ROI(&zImage, 270, 270);
zoom->bilinearZoom(&zImage, zImage.w * 2, zImage.h * 2);
zoom->setScaleSize(2);
zImage.setMethod("ROI - Bilinear Zoom");
break;
case 6:
zoom->ROI(&zImage, 270, 270);
zoom->bilinearZoom(&zImage, zImage.w * 4, zImage.h * 4);
zoom->setScaleSize(4);
zImage.setMethod("ROI - Bilinear Zoom");
break;
default:
system("cls");
cout << "Sorry, we did not understand your input, please enter a number between 1 and 6." << endl;
valid = false; // Set answer invalid
break;
}
if (cin.fail()) {
cout << "Incorrect Input." << endl;
valid = false;
cin.clear();
cin.ignore();
}
} while (valid != true);
FileActions * zoomFile = new FileActions();
// Set image values and display information
zImage.setName("zoomedImage.ppm");
zImage.setColorDepth(8);
cout << "\nZoomed image info: " << endl;
zoom->ImageInfo(zImage);
file->writePPM(zImage, "zoomedImage.ppm");
// Delete pointer objects to avoid memory leaks
delete zoomFile, zoom;
system("pause");
return 0;
}
//Read ppm files into the code
//They need to be in 'binary' format (P6) with no comments in the header
//The first line is the 'P'number - P6 indicates it is a binary file, then the image dimensions and finally the colour range
//This header is then followed by the pixel colour data
//eg: P6
// 3264 2448
// 255
//Open a .ppm file in notepad++ to see this header (caution: they are large files!)
|
int freq = 440;
int channel = 0;
int resolution = 8;
void setup() {
Serial.begin(115200);
ledcSetup(channel, freq, resolution);
ledcAttachPin(25, channel);
ledcWriteTone(channel, freq);
}
void loop() {
// put your main code here, to run repeatedly:
}
|
//===-- client/db-client-impl-data.hh - DBClientImplData class-*- C++ ---*-===//
//
// ODB Library
// Author: Steven Lariau
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Implementation of DBClient that communicate with serialbuffs
///
//===----------------------------------------------------------------------===//
#pragma once
#include "../mess/db-client-impl.hh"
#include "fwd.hh"
#include <memory>
namespace odb {
// Internal class to avoid include of all the nasty template seralization stuff
class DBClientImplData_Internal;
/// Implementation for the DBClient
/// Send/recv serialbuff objects
/// Serialize commands
/// Use an abstract dataclient responsible for recv/send serialbuffs using any
/// protocol
class DBClientImplData : public DBClientImpl {
public:
DBClientImplData(std::unique_ptr<AbstractDataClient> &&dc);
~DBClientImplData() override;
void connect(VMInfos &infos, DBClientUpdate &udp) override;
void stop() override;
void check_stopped(DBClientUpdate &udp) override;
void get_regs(const vm_reg_t *ids, char **out_bufs,
const vm_size_t *regs_size, std::size_t nregs) override;
void set_regs(const vm_reg_t *ids, const char **in_bufs,
const vm_size_t *regs_size, std::size_t nregs) override;
void get_regs_infos(const vm_reg_t *ids, RegInfos *out_infos,
std::size_t nregs) override;
void find_regs_ids(const char **reg_names, vm_reg_t *out_ids,
std::size_t nregs) override;
void read_mem(const vm_ptr_t *src_addrs, const vm_size_t *bufs_sizes,
char **out_bufs, std::size_t nbuffs) override;
void write_mem(const vm_ptr_t *dst_addrs, const vm_size_t *bufs_sizes,
const char **in_bufs, std::size_t nbuffs) override;
void get_symbols_by_ids(const vm_sym_t *ids, SymbolInfos *out_infos,
std::size_t nsyms) override;
void get_symbols_by_addr(vm_ptr_t addr, vm_size_t size,
std::vector<SymbolInfos> &out_infos) override;
void get_symbols_by_names(const char **names, SymbolInfos *out_infos,
std::size_t nsyms) override;
void get_code_text(vm_ptr_t addr, std::size_t nins,
std::vector<std::string> &out_text,
std::vector<vm_size_t> &out_sizes) override;
void add_breakpoints(const vm_ptr_t *addrs, std::size_t size) override;
void del_breakpoints(const vm_ptr_t *addrs, std::size_t size) override;
void resume(ResumeType type) override;
private:
std::unique_ptr<DBClientImplData_Internal> _impl;
};
} // namespace odb
|
#include "util.h"
/**
* Returns true if 'text' matches regex validation
* @param text
* @param regex
* @return bool
*/
bool is_correct(std::string text , const std::string regex) {
std::regex syntax(regex);
if(std::regex_match(text, syntax)) {
return true;
}
return false;
}
/**
* Displays the contents of the file path passed in
* @param path
*/
void read_file(const std::string path) {
// Fix file path problem
std::ifstream help_menu(path);
if(help_menu.is_open()) {
std::string line;
// Will read line until new line is detected
while(std::getline(help_menu,line)) {
std::cout << line << std::endl;
}
} else {
std::cerr << "Error opening menu file" << std::endl;
}
}
/**
* Returns true if argument matches password
* @param password
* @return bool
*/
bool is_password(std::string password) {
const std::string user_password = "password";
return user_password == password;
}
/**
* Converts string to all upper_case
* @param x
* @return x
*/
std::string upper_case(std::string& x) {
for(auto& c : x) c = toupper(c);
return x;
}
|
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <tuple>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <climits>
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
using namespace std;
using ll = long long;
int main() {
int h, w, k;
cin >> h >> w >> k;
vector<vector<char>> v(h, vector<char>(w));
int s = 0;
rep(i, h) {
rep(j, w) {
cin >> v[i][j];
s += (v[i][j] == '#');
}
}
int ans = 0;
for (int by = 0; by < (1 << h); by++) {
for (int bx = 0; bx < (1 << w); bx++) {
int cnt = 0;
vector<vector<int>> mask(h, vector<int>(w));
rep(i, h) {
if (((by >> i) & 1) == 0) continue;
rep(j, w) mask[i][j] = 1;
}
rep(i, w) {
if (((bx >> i) & 1) == 0) continue;
rep(j, h) mask[j][i] = 1;
}
rep(i, h) {
rep(j, w) cnt += (mask[i][j] && v[i][j] == '#');
}
if ((s - cnt) == k) ans++;
}
}
cout << ans << endl;
}
|
#ifndef CIRCUTIL_H
#define CIRCUTIL_H
#include <ext/hash_map>
// #include <tr1/unordered_map>
// #include <chuffed/circuit/MurmurHash3.h>
#define SEED 0xdeadbeef
extern int stat_count;
// Utility stuff
template <class S>
struct AutoS {
struct eq {
bool operator()(const S& a, const S& b) const {
if (sizeof(S) % sizeof(uint32_t) == 0) {
auto* ap((uint32_t*)&a);
auto* bp((uint32_t*)&b);
for (unsigned int ii = 0; ii < sizeof(S) / sizeof(uint32_t); ii++) {
if (ap[ii] != bp[ii]) {
return false;
}
}
return true;
}
char* ap((char*)&a);
char* bp((char*)&b);
for (unsigned int ii = 0; ii < sizeof(S); ii++) {
if (ap[ii] != bp[ii]) {
return false;
}
}
return true;
}
};
struct hash {
unsigned int operator()(const S& s) const {
uint32_t ret;
MurmurHash3_x86_32(&s, sizeof(S), SEED, &ret);
return ret;
}
};
};
template <class S, class V>
struct AutoC {
typedef __gnu_cxx::hash_map<const S, V, typename AutoS<S>::hash, typename AutoS<S>::eq> cache;
// typedef std::tr1::unordered_map<const S, V, typename AutoS<S>::hash, typename AutoS<S>::eq>
// cache;
};
/*
template<class T>
inline T imax(const T a, const T b)
{
return a < b ? b : a;
}
template<class T>
inline T imin(const T a, const T b)
{
return a < b ? a : b;
}
inline int ceil(int a, int b)
{
return (a % b) ? (a/b)+1 : (a/b);
}
*/
#endif
|
#include "../headers/player.h"
#include "../headers/enemy.h"
#include "../headers/battle.h"
#include "../headers/item.h"
#include "../headers/areas.h"
#include "../headers/party.h"
#include <stdio.h>
#include <stdlib.h>
int main()
{
party Team;
player *Characters[3];
int PlayerNum = 3;
for (int i=0; i<PlayerNum; i++)
{
Characters[i] = new player;
}
enemy BadGuys[4];
int EnemyNum = 4;
int InvNum = 10;
item *Inventory[InvNum];
int EnemyLevel = 5;
for (int i=0; i<InvNum; i++)
Inventory[i] = NULL;
/*
printf("Inventory:\n");
for (int i=0; i<InvNum; i++)
{
if (i < InvNum)
{
item *tmp;
int isel = (rand()%8)+1;
// Inventory[i] = getItem(isel);
tmp = getItem(isel);
int stk = (rand()%4)+1;
// Inventory[i]->setStock(stk);
tmp->setStock(stk);
printf("%s\n", tmp->getName());
// recieveItem(Inventory, InvNum, tmp);
Team.recieveItem(tmp);
}
else
{
Inventory[i] = NULL;
}
}
printf("\n");
*/
int sel;
printf("1. Start New Battle\n2. Load Player Stats\n");
scanf("%d", &sel);
if (sel == 2)
{
/*
FILE *fp;
fp = fopen("./files/Battle_saveFile.txt", "r");
Characters[0]->setPlayer(fp);
Characters[1]->setPlayer(fp);
Characters[2]->setPlayer(fp);
fclose(fp);
*/
Team.loadParty();
for (int i=0; i<PlayerNum; i++)
{
delete Characters[i];
}
}
else
{
Characters[0]->setPlayer("Mr. Warriorguy", 0);
Characters[1]->setPlayer("Senor Tortuga", 1);
Characters[2]->setPlayer("Miss MagicTits", 2);
printf("Inventory:\n");
for (int i=0; i<InvNum; i++)
{
if (i < InvNum)
{
item *tmp;
int isel = (rand()%8)+1;
// Inventory[i] = getItem(isel);
tmp = getItem(isel);
int stk = (rand()%4)+1;
// Inventory[i]->setStock(stk);
// tmp->setStock(stk);
printf("%s\n", tmp->getName());
// recieveItem(Inventory, InvNum, tmp);
Team.recieveItem(tmp);
}
else
{
Inventory[i] = NULL;
}
}
printf("\n");
}
if (sel != 2)
{
for (int i=0; i<PlayerNum; i++)
Team.recievePlayer(Characters[i]);
}
printf("Set Enemy Level? (Default is 5)\n1. Yes\n2. No\n");
scanf("%d", &sel);
if (sel == 1)
{
int temp;
printf("Enter enemy level: ");
scanf("%d", &temp);
if ((temp > 0)&&(temp <= 100))
EnemyLevel = temp;
else
printf("Invalid entry, setting to default level\n");
}
BadGuys[0].setEnemy(1, "Evil Frog", 20, 20, 5, 5, 5, 5, 1);
BadGuys[0].recieveSkill(9);
BadGuys[0].setLevel(EnemyLevel);
BadGuys[1].setEnemy(2, "Man-eating Goat", 65, 30, 3, 7, 2, 6, 1);
BadGuys[1].recieveSkill(10);
BadGuys[1].setLevel(EnemyLevel);
BadGuys[2].setEnemy(3, "Wolf", 50, 60, 7, 3, 6, 4, 1);
BadGuys[2].recieveSkill(9);
BadGuys[2].setLevel(EnemyLevel);
/*
BadGuys[3].setEnemy(4, "Bar Wench", 100, 80, 4, 4, 4, 4, 2);
BadGuys[3].recieveSkill(9);
BadGuys[3].recieveSkill(10);
*/
enemy *temp = getEnemy(4);
BadGuys[3] = *temp;
BadGuys[3].resetSkillLst();
BadGuys[3].setLevel(EnemyLevel);
delete temp;
// Characters[2].recieveExp(999999999);
/*
>----Commenting this out so that you can test out the areas deal by itself----<
battle RandomBattle(BadGuys, EnemyNum, Characters, PlayerNum, Inventory, InvNum);
// RandomBattle.set_enmLvl();
int Vic = RandomBattle.battleLoop();
if (Vic == 0)
RandomBattle.battleAwards();
else if (Vic == 1)
printf("GAME OVER!\n");
*/
areas grass("Grassy Plains", 1, &Team);
areas snow ("Snow-covered Mountains", 2, &Team);
areas fire ("Lava Hell-scape", 3, &Team);
areas random("Random Dungeon", 4, &Team);
areas rand_alt("Random Dun Alt", 5, &Team);
areas file_dungeon("File Dungeon", 6, &Team);
grass.dungeon_loop();
snow.dungeon_loop();
fire.dungeon_loop();
random.dungeon_loop();
rand_alt.dungeon_loop();
file_dungeon.dungeon_loop();
for (int i=0; i<InvNum; i++)
{
if (Inventory != NULL)
delete Inventory[i];
}
/*
for (int i=0; i<PlayerNum; i++)
{
delete Characters[i];
}
*/
return 0;
}
|
#include "polygons.h"
#include "math.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Trapezoid::Trapezoid
/// \param parent
///
Trapezoid::Trapezoid(QObject *parent) :
Figure(parent)
{
// Начальное значение цвета
color = Qt::darkRed;
}
Trapezoid::~Trapezoid()
{
}
void Trapezoid::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QPolygon polygon; // Используем класс полигона, чтобы отрисовать фигуру
// Помещаем координаты точек в полигональную модель
polygon << QPoint(-width/4,-height/4) << QPoint(width/4,-height/4) << QPoint(width/2,height/2) << QPoint(-width/2,height/2);
painter->setBrush(QBrush(color)); // Устанавливаем кисть, которой будем отрисовывать объект
painter->drawPolygon(polygon); // Рисуем треугольник по полигональной модели
Q_UNUSED(option);
Q_UNUSED(widget);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Pentagon::Pentagon
/// \param parent
///
Pentagon::Pentagon(QObject *parent) :
Figure(parent)
{
// Начальное значение цвета
color = Qt::darkGreen;
}
Pentagon::~Pentagon()
{
}
void Pentagon::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
// объявляем координаты точек
int x[NUMB_PENT], y[NUMB_PENT];
QPolygon polygon; // Используем класс полигона, чтобы отрисовать фигуру
// Находим координаты всех точек (xi = x0 + R*sin(Pi + 2*Pi*i/n); yi = y0 + R*cos(Pi + 2*Pi*i/n))
for (int i = 0; i < NUMB_PENT; i++)
{
x[i] = (width/2)*sin(M_PI+2*M_PI*i/NUMB_PENT);
y[i] = (height/2)*cos(M_PI+2*M_PI*i/NUMB_PENT);
polygon << QPoint(x[i],y[i]); // Помещаем координаты точек в полигональную модель
}
painter->setBrush(QBrush(color)); // Устанавливаем кисть, которой будем отрисовывать объект
painter->drawPolygon(polygon); // Рисуем треугольник по полигональной модели
Q_UNUSED(option);
Q_UNUSED(widget);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Dodecagon::Dodecagon
/// \param parent
///
Dodecagon::Dodecagon(QObject *parent) :
Figure(parent)
{
// Начальное значение цвета
color = Qt::darkBlue;
}
Dodecagon::~Dodecagon()
{
}
void Dodecagon::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
// объявляем координаты точек
int x[NUMB_DODEC], y[NUMB_DODEC];
QPolygon polygon; // Используем класс полигона, чтобы отрисовать фигуру
// Находим координаты всех точек (xi = x0 + R*sin(Pi + 2*Pi*i/n); yi = y0 + R*cos(Pi + 2*Pi*i/n))
for (int i = 0; i < NUMB_DODEC; i++)
{
x[i] = (width/2)*sin(M_PI+2*M_PI*i/NUMB_DODEC);
y[i] = (height/2)*cos(M_PI+2*M_PI*i/NUMB_DODEC);
polygon << QPoint(x[i],y[i]); // Помещаем координаты точек в полигональную модель
}
painter->setBrush(QBrush(color)); // Устанавливаем кисть, которой будем отрисовывать объект
painter->drawPolygon(polygon); // Рисуем треугольник по полигональной модели
Q_UNUSED(option);
Q_UNUSED(widget);
}
|
// Created on: 1997-09-30
// Created by: Roman BORISOV
// 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 _Approx_CurveOnSurface_HeaderFile
#define _Approx_CurveOnSurface_HeaderFile
#include <Adaptor2d_Curve2d.hxx>
#include <Adaptor3d_Surface.hxx>
#include <GeomAbs_Shape.hxx>
class Geom_BSplineCurve;
class Geom2d_BSplineCurve;
//! Approximation of curve on surface
class Approx_CurveOnSurface
{
public:
DEFINE_STANDARD_ALLOC
//! This constructor calls perform method. This constructor is deprecated.
Standard_DEPRECATED("This constructor is deprecated. Use other constructor and perform method instead.")
Standard_EXPORT Approx_CurveOnSurface(const Handle(Adaptor2d_Curve2d)& C2D, const Handle(Adaptor3d_Surface)& Surf, const Standard_Real First, const Standard_Real Last, const Standard_Real Tol, const GeomAbs_Shape Continuity, const Standard_Integer MaxDegree, const Standard_Integer MaxSegments, const Standard_Boolean Only3d = Standard_False, const Standard_Boolean Only2d = Standard_False);
//! This constructor does not call perform method.
//! @param theC2D 2D Curve to be approximated in 3D.
//! @param theSurf Surface where 2D curve is located.
//! @param theFirst First parameter of resulting curve.
//! @param theFirst Last parameter of resulting curve.
//! @param theTol Computation tolerance.
Standard_EXPORT Approx_CurveOnSurface(const Handle(Adaptor2d_Curve2d)& theC2D,
const Handle(Adaptor3d_Surface)& theSurf,
const Standard_Real theFirst,
const Standard_Real theLast,
const Standard_Real theTol);
Standard_EXPORT Standard_Boolean IsDone() const;
Standard_EXPORT Standard_Boolean HasResult() const;
Standard_EXPORT Handle(Geom_BSplineCurve) Curve3d() const;
Standard_EXPORT Standard_Real MaxError3d() const;
Standard_EXPORT Handle(Geom2d_BSplineCurve) Curve2d() const;
Standard_EXPORT Standard_Real MaxError2dU() const;
//! returns the maximum errors relatively to the U component or the V component of the
//! 2d Curve
Standard_EXPORT Standard_Real MaxError2dV() const;
//! Constructs the 3d curve. Input parameters are ignored when the input curve is
//! U-isoline or V-isoline.
//! @param theMaxSegments Maximal number of segments in the resulting spline.
//! @param theMaxDegree Maximal degree of the result.
//! @param theContinuity Resulting continuity.
//! @param theOnly3d Determines building only 3D curve.
//! @param theOnly2d Determines building only 2D curve.
Standard_EXPORT void Perform(const Standard_Integer theMaxSegments,
const Standard_Integer theMaxDegree,
const GeomAbs_Shape theContinuity,
const Standard_Boolean theOnly3d = Standard_False,
const Standard_Boolean theOnly2d = Standard_False);
protected:
//! Checks whether the 2d curve is a isoline. It can be represented by b-spline, bezier,
//! or geometric line. This line should have natural parameterization.
//! @param theC2D Trimmed curve to be checked.
//! @param theIsU Flag indicating that line is u const.
//! @param theParam Line parameter.
//! @param theIsForward Flag indicating forward parameterization on a isoline.
//! @return Standard_True when 2d curve is a line and Standard_False otherwise.
Standard_Boolean isIsoLine(const Handle(Adaptor2d_Curve2d) theC2D,
Standard_Boolean& theIsU,
Standard_Real& theParam,
Standard_Boolean& theIsForward) const;
//! Builds 3D curve for a isoline. This method takes corresponding isoline from
//! the input surface.
//! @param theC2D Trimmed curve to be approximated.
//! @param theIsU Flag indicating that line is u const.
//! @param theParam Line parameter.
//! @param theIsForward Flag indicating forward parameterization on a isoline.
//! @return Standard_True when 3d curve is built and Standard_False otherwise.
Standard_Boolean buildC3dOnIsoLine(const Handle(Adaptor2d_Curve2d) theC2D,
const Standard_Boolean theIsU,
const Standard_Real theParam,
const Standard_Boolean theIsForward);
private:
Approx_CurveOnSurface& operator= (const Approx_CurveOnSurface&);
private:
//! Input curve.
const Handle(Adaptor2d_Curve2d) myC2D;
//! Input surface.
const Handle(Adaptor3d_Surface) mySurf;
//! First parameter of the result.
const Standard_Real myFirst;
//! Last parameter of the result.
const Standard_Real myLast;
//! Tolerance.
Standard_Real myTol;
Handle(Geom2d_BSplineCurve) myCurve2d;
Handle(Geom_BSplineCurve) myCurve3d;
Standard_Boolean myIsDone;
Standard_Boolean myHasResult;
Standard_Real myError3d;
Standard_Real myError2dU;
Standard_Real myError2dV;
};
#endif // _Approx_CurveOnSurface_HeaderFile
|
/*
* Copyright (c) 2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#include <forward_list>
#include <vector>
#include <catch2/catch.hpp>
#include <cpp-sort/probes/sus.h>
#include <cpp-sort/utility/size.h>
#include <testing-tools/internal_compare.h>
TEST_CASE( "presortedness measure: sus", "[probe][sus]" )
{
using cppsort::probe::sus;
SECTION( "simple test" )
{
std::forward_list<int> li = { 6, 9, 79, 41, 44, 49, 11, 16, 69, 15 };
CHECK( sus(li) == 3 );
CHECK( sus(li.begin(), li.end()) == 3 );
std::vector<internal_compare<int>> tricky(li.begin(), li.end());
CHECK( sus(tricky, &internal_compare<int>::compare_to) == 3 );
}
SECTION( "upper bound" )
{
// The upper bound should correspond to the size of
// the input sequence minus one
std::forward_list<int> li = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
auto max_n = sus.max_for_size(cppsort::utility::size(li));
CHECK( max_n == 10 );
CHECK( sus(li) == max_n );
CHECK( sus(li.begin(), li.end()) == max_n );
}
}
|
//https://www.patest.cn/contests/gplt/L2-006
//20180331 review
#include<bits/stdc++.h>
using namespace std;
vector<int> inorder(50),postorder(50);
struct tree_node{
tree_node* father = NULL;
tree_node* left_child = NULL;
tree_node* right_child = NULL;
int key = -1, layer = -1;
};
tree_node* tree_store = new tree_node[50];
int count_tree_store = 0;
tree_node* build_tree(int postfrom,int infrom,int length,int layer){
if(length<=0){
return nullptr;
}
int temp = infrom;
while(inorder[temp]!=postorder[postfrom]) ++temp;
tree_node* temp_root = &(tree_store[count_tree_store++]);
temp_root->key = postorder[postfrom];
temp_root->layer = layer;
temp_root->left_child = build_tree(postfrom-(length-(temp-infrom)-1)-1,infrom,temp-infrom,++layer);
temp_root->right_child = build_tree(postfrom-1,temp+1,length-(temp-infrom)-1,++layer);
return temp_root;
}
/*
void swap1(tree_node* change){
if(change->left_child!=nullptr){
swap1(change->left_child);
}
if(change->right_child!=nullptr){
swap1(change->right_child);
}
tree_node* temp = change->left_child;
change->left_child = change->right_child;
change->right_child = temp;
}
*/
int main(){
int n; cin>>n;
for(int i=0;i<n;++i) cin>>postorder[i];
for(int i=0;i<n;++i) cin>>inorder[i];
tree_node* tree_root = build_tree(n-1,0,n,0);
//swap1(tree_root);
vector<tree_node*> result;
result.push_back(tree_root);
for(int i=0;i<result.size();++i){
if(result[i]->left_child!=nullptr){
result.push_back(result[i]->left_child);
}
if(result[i]->right_child!=nullptr){
result.push_back(result[i]->right_child);
}
}
for(int i=0;i<result.size();++i){
cout<<result[i]->key;
if(i!=result.size()-1){
cout<<' ';
}
}
}
/*
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
//treeNode
class treeNode{
public:
treeNode();
treeNode* leftchild;
treeNode* rightchild;
int data;
};
treeNode::treeNode(){
treeNode* leftchild = NULL;
treeNode* rightchild = NULL;
data = 0;
}
int sign=9;
treeNode* treeStore= new treeNode[500100];
int count_treeStore=0;
//构造树函数
treeNode *rebuild(int *postorder,int *inorder,int postfrom,int infrom,int length){
if(length<=0){
return NULL;
}
treeNode *root=&(treeStore[count_treeStore++]);
root->data=postorder[postfrom];
int i,j;
for(i=infrom,j=0;j<length&&inorder[i]!=postorder[postfrom];++i,++j);
if(j==length){
sign=6;
return NULL;
}
root->leftchild=rebuild(postorder,inorder,postfrom-(length-i+infrom-1)-1,infrom,i-infrom);
root->rightchild=rebuild(postorder,inorder,postfrom-1,i+1,length-i+infrom-1);
return root;
}
int main(){
//input
int n;
fscanf(stdin,"%d",&n);
int* postorder=new int[500100];
int* inorder= new int[500100];
for(int i=0;i<n;i++){
fscanf(stdin,"%d",&postorder[i]);
}
for(int i=0;i<n;i++){
fscanf(stdin,"%d",&inorder[i]);
}
//process
treeNode*tree_root=rebuild(postorder,inorder,n-1,0,n);
//output
vector<treeNode*> result;
result.push_back(tree_root);
for(int i=0;i<result.size();++i){
if(result[i]->leftchild!=NULL){
result.push_back((result[i]->leftchild));
}
if(result[i]->rightchild!=NULL){
result.push_back((result[i]->rightchild));
}
}
if(result.size()==0){
return 0;
}else{
cout<<result[0]->data;
}
for(int i=1;i<result.size();++i){
cout<<' '<<result[i]->data;
}
return 0;
}
*/
/*
#include<iostream>
#include<cstdio>
using namespace std;
//treeNode
class treeNode{
public:
treeNode();
treeNode* leftchild;
treeNode* rightchild;
int data;
};
treeNode::treeNode(){
treeNode* leftchild = NULL;
treeNode* rightchild = NULL;
data = 0;
}
int sign=9;
treeNode* treeStore= new treeNode[500100];
int count_treeStore=0;
//构造树函数
treeNode *rebuild(int *postorder,int *inorder,int postfrom,int infrom,int length){
if(length<=0){
return NULL;
}
treeNode *root=&(treeStore[count_treeStore++]);
root->data=postorder[postfrom];
cout<<postorder[postfrom];
int i,j;
for(i=infrom,j=0;j<length&&inorder[i]!=postorder[postfrom];++i,++j);
if(j==length){
sign=6;
return NULL;
}
root->leftchild=rebuild(postorder,inorder,postfrom-(length-i+infrom-1)-1,infrom,i-infrom);
root->rightchild=rebuild(postorder,inorder,postfrom-1,i+1,length-i+infrom-1);
return root;
}
//output函数
int output(treeNode*root){
fprintf(stdout,"%d ",root->data);
if(NULL!=root->leftchild){
output(root->leftchild);
}
if(NULL!=root->rightchild){
output(root->rightchild);
}
return 0;
}
int main(){
//input
int n;
fscanf(stdin,"%d",&n);
int* postorder=new int[500100];
int* inorder= new int[500100];
for(int i=0;i<n;i++){
fscanf(stdin,"%d",&postorder[i]);
}
for(int i=0;i<n;i++){
fscanf(stdin,"%d",&inorder[i]);
}
//process
treeNode*tree_root=rebuild(postorder,inorder,n-1,0,n);
//output
if(sign==9){
output(tree_root);
}else{
fprintf(stdout,"%d ",-1);
}
return 0;
}
*/
|
#include <iostream>
using namespace std;
int main(){
int numB, L, T;
int chu = 0;
cin >> numB >> L >> T;
int a[numB][2];
for (int i = 0; i < numB; i++) {
cin >> a[i][0];
a[i][1] = 1; // 1 右 2 左
}
for (int i = 0; i < T; i++) {
for (int j = 0; j < numB; j++) {
if (a[j][0] == 0) a[j][1] = 1;
if (a[j][0] == L) a[j][1] = 2;
}
for (int m = 0; m < numB-1; m++) {
for (int n = m+1; n < numB; n++) {
if (a[m][0] == a[n][0]) {
int temp = a[m][1];
a[m][1] = a[n][1];
a[n][1] = temp;
}
}
}
for (int j = 0; j < numB; j++) {
if (a[j][1] == 1) a[j][0] ++;
if (a[j][1] == 2) a[j][0] --;
}
}
for (int i = 0; i < numB; i++) {
cout << a[i][0];
if (i != numB-1) cout << " ";
}
return 0;
}
|
#include "_pch.h"
#include "ViewBrowserDVModel.h"
using namespace wh;
//-----------------------------------------------------------------------------
//virtual
unsigned int wxDVTableBrowser::GetColumnCount() const //override
{
return 4;
}
//-----------------------------------------------------------------------------
//virtual
wxString wxDVTableBrowser::GetColumnType(unsigned int col) const //override
{
switch (col)
{
case 0: return "wxDataViewIconText";
default: break;
}
return "string";
}
//-----------------------------------------------------------------------------
//virtual
bool wxDVTableBrowser::HasContainerColumns(const wxDataViewItem& WXUNUSED(item)) const //override
{
return true;
}
//-----------------------------------------------------------------------------
//virtual
bool wxDVTableBrowser::IsContainer(const wxDataViewItem &item)const //override
{
if (!item.IsOk())
return true;
const auto node = static_cast<const IIdent64*> (item.GetID());
const auto cls = dynamic_cast<const ICls64*>(node);
if (mGroupByType
&& cls
&& !IsTop(item)
&& ClsKind::Abstract != cls->GetKind())
return true;
return false;
}
//-----------------------------------------------------------------------------
void wxDVTableBrowser::GetErrorValue(wxVariant &variant, unsigned int col) const
{
if (0 == col)
variant << wxDataViewIconText("*ERROR*", wxNullIcon);
else
variant = "*ERROR*";
return;
}
//-----------------------------------------------------------------------------
void wxDVTableBrowser::GetClsValue(wxVariant &variant, unsigned int col
, const ICls64& cls) const
{
auto mgr = ResMgr::GetInstance();
switch (col)
{
case 0: {
const wxIcon* ico(&wxNullIcon);
switch (cls.GetKind())
{
case ClsKind::Abstract: ico = &mgr->m_ico_type_abstract24; break;
case ClsKind::Single: ico = &mgr->m_ico_type_num24; break;
case ClsKind::QtyByOne:
case ClsKind::QtyByFloat:
default: ico = &mgr->m_ico_type_qty24; break;
}//switch
variant << wxDataViewIconText(cls.GetTitle(), *ico);
}break;
//case 1: variant = wxString("qwe2"); break;
case 2: {
switch (cls.GetKind())
{
case ClsKind::Single: case ClsKind::QtyByOne: case ClsKind::QtyByFloat:
variant = wxString::Format("%s %s", cls.GetObjectsQty(), cls.GetMeasure());
break;
case ClsKind::Abstract:
default: break;
}
}break;
//case 3: variant = wxString("qwe3"); break;
default: {
const auto& idxCol = mActColumns.get<1>();
const auto it = idxCol.find(col);
if (idxCol.end() != it)
{
if (FavAPropInfo::PeriodDay == it->mAInfo)
{
wxString period;
if (cls.GetActPeriod(it->mAid, period))
{
double dperiod;
if (period.ToCDouble(&dperiod))
variant = wxString::Format("%g", dperiod);
}
}
else
{
const auto& aprop_array = cls.GetFavAPropValue();
const auto& idxFAV = aprop_array.get<0>();
auto fit = idxFAV.find(boost::make_tuple(it->mAid, it->mAInfo));
if (idxFAV.end() != fit)
variant = (*fit)->mValue;
}
}//if (idxCol.end() != it)
else
{
auto prop_val = GetPropVal(cls, col);
if (prop_val)
variant = prop_val->mValue;
}
}break;
}//switch (col)
}
//-----------------------------------------------------------------------------
void wxDVTableBrowser::GetObjValue(wxVariant &variant, unsigned int col
, const IObj64& obj) const
{
const wxIcon* ico(&wxNullIcon);
auto mgr = ResMgr::GetInstance();
switch (col)
{
case 0:{
//const wxIcon ico_sel = wxArtProvider::GetIcon(wxART_TICK_MARK, wxART_MENU);
const wxIcon ico_lock_obj("OBJ_LOCK_24", wxBITMAP_TYPE_ICO_RESOURCE, 24, 24);
//if (obj.IsSelected())
// ico = &ico_sel;
if (!obj.GetLockUser().empty())
ico = &ico_lock_obj;
variant << wxDataViewIconText(obj.GetTitle(), *ico);
}break;
case 1: variant = obj.GetCls()->GetTitle(); break;
case 2: {
switch (obj.GetCls()->GetKind())
{
case ClsKind::QtyByOne:
case ClsKind::QtyByFloat:
variant = wxString::Format("%s %s"
, obj.GetQty()
, obj.GetCls()->GetMeasure());
default: break;
}//switch (obj.GetCls()->GetKind())
}break;
case 3: if (obj.GetPath())
variant = obj.GetPath()->AsString();
break;
default: {
const auto& idxCol = mActColumns.get<1>();
const auto it = idxCol.find(col);
if (idxCol.end() != it)
{
switch (it->mAInfo)
{
case FavAPropInfo::PreviosDate: {
wxDateTime dt;
int ret = obj.GetActPrevios(it->mAid, dt);
switch (ret)
{
case 1: {
if (dt.GetDateOnly() == dt)
variant = wxString::Format("%s", dt.Format(format_d));
else
variant = wxString::Format("%s %s", dt.Format(format_d), dt.Format(format_t));
}break;
case -1: {
variant = mActNotExecuted;
}
default: break;
}
}break;
case FavAPropInfo::PeriodDay: if (!mGroupByType) {
wxString period;
if (obj.GetActPeriod(it->mAid, period))
{
double dperiod;
if (period.ToCDouble(&dperiod))
{
variant = wxString::Format("%g", dperiod);
}
}
} break;
case FavAPropInfo::NextDate: {
wxDateTime dt;
int ret = obj.GetActNext(it->mAid, dt);
switch (ret)
{
case 1: {
if (dt.GetDateOnly() == dt)
variant = wxString::Format("%s", dt.Format(format_d));
else
variant = wxString::Format("%s %s", dt.Format(format_d), dt.Format(format_t));
}break;
case -1: {
variant = mActNotExecuted;
}
default: break;
}//switch (ret)
}break;
case FavAPropInfo::LeftDay: {
double left;
int ret = obj.GetActLeft(it->mAid, left);
switch (ret)
{
case 1: {
variant = wxString::Format("%g", left);
}break;
case -1: {
variant = mActNotExecuted;
}break;
default: break;
}//switch (ret)
}break;
default: {
int64_t aid = it->mAid;
FavAPropInfo info = it->mAInfo;
const auto& idxFAV = obj.GetFavAPropValue().get<0>();
auto fit = idxFAV.find(boost::make_tuple(aid, info));
if (idxFAV.end() != fit)
{
const auto str_value = (*fit)->mValue;
if (str_value == "null")
variant = mActNotExecuted;
else
variant = str_value;
}
}break;
}//switch (it->mAInfo)
}//if (idxCol.end() != it)
else
{
auto prop_val = GetPropVal(obj, col);
if (prop_val)
variant = prop_val->mValue;
}
}break;
}//switch (col)
}
//-----------------------------------------------------------------------------
void wxDVTableBrowser::GetValueInternal(wxVariant &variant,
const wxDataViewItem &dvitem, unsigned int col) const
{
if (IsTop(dvitem))
{
const auto mgr = ResMgr::GetInstance();
if (0 == col)
variant << wxDataViewIconText("..", mgr->m_ico_back24);
return;
}
const auto node = static_cast<const IIdent64*> (dvitem.GetID());
const auto ident = node;
const auto cls = dynamic_cast<const ICls64*>(ident);
if (cls)
{
GetClsValue(variant, col, *cls);
return;
}
const auto obj = dynamic_cast<const IObj64*>(ident);
if (obj)
{
GetObjValue(variant, col, *obj);
return;
}
GetErrorValue(variant, col);
}
//-----------------------------------------------------------------------------
//virtual
void wxDVTableBrowser::GetValue(wxVariant &variant,
const wxDataViewItem &dvitem, unsigned int col) const //override
{
GetValueInternal(variant, dvitem, col);
if (variant.IsNull())
variant = "";
}
//-----------------------------------------------------------------------------
//virtual
bool wxDVTableBrowser::GetAttr(const wxDataViewItem &item, unsigned int col,
wxDataViewItemAttr &attr) const //override
{
if (!item.IsOk() || IsTop(item))
return false;
const auto node = static_cast<const IIdent64*> (item.GetID());
const auto obj = dynamic_cast<const IObj64*>(node);
if (obj)
{
switch (col)
{
case 0:{
attr.SetBold(true);
}break;
case 2:{
switch (obj->GetCls()->GetKind())
{
case ClsKind::QtyByOne:
case ClsKind::QtyByFloat:
attr.SetBold(true);
if (mEditableQtyCol)
attr.SetBackgroundColour(wxYELLOW->ChangeLightness(160));
default: break;
}
}break;
case 1:case 3: {
attr.SetColour(*wxBLUE);
return true;
}break;
default: {
const auto& idxCol = mActColumns.get<1>();
const auto it = idxCol.find(col);
if (idxCol.end() != it)
{
switch (it->mAInfo) {
default: break;
case FavAPropInfo::NextDate: { //next
wxDateTime next;
int ret = obj->GetActNext(it->mAid, next);
switch (ret)
{
case 1: {
if (next.IsEarlierThan(wxDateTime::Now() + wxTimeSpan(240, 0, 0, 0)))
{
attr.SetBold(true);
if (next.IsEarlierThan(wxDateTime::Now()))
attr.SetColour(*wxRED);
else
attr.SetColour(wxColour(230, 130, 30));
return true;
}
}break;
case -1: {
attr.SetBold(true);
attr.SetColour(*wxRED);
return true;
}break;
default: break;
}//switch (ret)
}break;
case FavAPropInfo::LeftDay: {
double left;
int ret = obj->GetActLeft(it->mAid, left);
switch (ret)
{
case 1: {
if (left < 10)
{
attr.SetBold(true);
if (left<0)
{
//attr.SetBackgroundColour(wxColour(255, 200, 200));
attr.SetColour(*wxRED);
}
else
{
//attr.SetBackgroundColour(*wxYELLOW);
attr.SetColour(wxColour(230, 130, 30));
}//else if (left<0)
return true;
}
}break;
case -1: {
attr.SetBold(true);
attr.SetColour(*wxRED);
return true;
}break;
default: break;
}//switch (ret)
}break;
}//switch (it->mAInfo)
}//if (idxCol.end() != it)
else
{
auto prop_val = GetPropVal(*obj, col);
if (prop_val && prop_val->mProp->IsLinkOrFile())
{
attr.SetColour(*wxBLUE);
return true;
}
}
}break;
}//switch (col)
return false;
}
const auto cls = dynamic_cast<const ICls64*>(node);
if (cls)
{
auto prop_val = GetPropVal(*cls, col);
if (prop_val && prop_val->mProp->IsLinkOrFile())
{
attr.SetColour(*wxBLUE);
return true;
}
}//if (cls)
return false;
}
//-----------------------------------------------------------------------------
//virtual
bool wxDVTableBrowser::SetValue(const wxVariant &variant, const wxDataViewItem &item,
unsigned int col)//override
{
if(!mEditableQtyCol)
return false;
const auto node = static_cast<const IIdent64*> (item.GetID());
const auto ident = node;
const auto cls = dynamic_cast<const ICls64*>(ident);
if (cls)
return false;
const auto obj = dynamic_cast<const IObj64*>(ident);
if (!obj)
return false;
wxString str_val = variant.GetString();
ObjectKey key(obj->GetId(), obj->GetParentId());
return sigSetQty(key, str_val).operator bool();
}
//-----------------------------------------------------------------------------
//virtual
int wxDVTableBrowser::Compare(const wxDataViewItem &item1, const wxDataViewItem &item2
, unsigned int column, bool ascending) const //override
{
wxVariant value1, value2;
GetValue(value1, item1, column);
GetValue(value2, item2, column);
if (mCurrentRoot)
{
if (static_cast<const IIdent64*>(item1.GetID()) == mCurrentRoot)
return -1;
else if (static_cast<const IIdent64*>(item2.GetID()) == mCurrentRoot)
return 1;
}
if (!ascending)
std::swap(value1, value2);
if (value1.IsNull())
{
if (!value2.IsNull())
return 1;
}
else
if (value2.IsNull())
return -1;
// all columns sorted by TRY FIRST numberic value
if (value1.GetType() == "string" || value1.GetType() == "wxDataViewIconText")
{
wxString str1;
wxString str2;
if (value1.GetType() == "wxDataViewIconText")
{
wxDataViewIconText iconText1, iconText2;
iconText1 << value1;
iconText2 << value2;
str1 = iconText1.GetText();
str2 = iconText2.GetText();
}
else
{
str1 = value1.GetString();
str2 = value2.GetString();
}
//wxRegEx mStartNum = "(^[0-9]+)";
if (mStartNum.Matches(str1))
{
size_t start1;
size_t len1;
double num1;
bool match = mStartNum.GetMatch(&start1, &len1);
if (match && str1.substr(start1, len1).ToDouble(&num1))
{
if (mStartNum.Matches(str2))
{
size_t start2;
size_t len2;
double num2;
match = mStartNum.GetMatch(&start2, &len2);
if (match && str2.substr(start2, len2).ToDouble(&num2))
{
if (num1 < num2)
return -1;
else if (num1 > num2)
return 1;
str1.erase(start1, start1 + len1);
str2.erase(start2, start2 + len2);
}
else
return 1;
}//if (mStartNum.Matches(str2))
}//if (match && str1.substr(start, len).ToLong(&num1))
else
{
if (mStartNum.Matches(str2))
{
size_t start2;
size_t len2;
double num2;
match = mStartNum.GetMatch(&start2, &len2);
if (match && str2.substr(start2, len2).ToDouble(&num2))
return -1;
}//if (mStartNum.Matches(str2))
}//else if (match && str1.substr(start, len).ToLong(&num1))
}//if (mStartNum.Matches(str1))
int res = str1.CmpNoCase(str2);
if (res)
return res;
// items must be different
wxUIntPtr id1 = wxPtrToUInt(item1.GetID()),
id2 = wxPtrToUInt(item2.GetID());
return ascending ? id1 - id2 : id2 - id1;
}//if (value1.GetType() == "string" || value1.GetType() == "wxDataViewIconText")
return wxDataViewModel::Compare(item1, item2, column, ascending);
}
//-----------------------------------------------------------------------------
//virtual
wxDataViewItem wxDVTableBrowser::GetParent(const wxDataViewItem &item) const //override
{
if (!item.IsOk() || IsTop(item))
return wxDataViewItem(nullptr);
if (IsListModel())
return wxDataViewItem(nullptr);
const auto ident = static_cast<const IIdent64*> (item.GetID());
const auto cls = dynamic_cast<const ICls64*>(ident);
if (cls)
return wxDataViewItem(nullptr);
const auto& obj = dynamic_cast<const IObj64*>(ident);
if (obj)
return wxDataViewItem((void*)obj->GetCls().get());
return wxDataViewItem(nullptr);
}
//-----------------------------------------------------------------------------
//virtual
unsigned int wxDVTableBrowser::GetChildren(const wxDataViewItem &parent
, wxDataViewItemArray &arr) const //override
{
if (!parent.IsOk())
{
if (mCurrentRoot && 1 < mCurrentRoot->GetId())
{
wxDataViewItem dvitem((void*)mCurrentRoot);
arr.push_back(dvitem);
}
for (const auto& child_cls : mClsList)
{
wxDataViewItem dvitem((void*)child_cls);
arr.push_back(dvitem);
}
return arr.size();
}
const auto ident = static_cast<const IIdent64*> (parent.GetID());
const auto cls = dynamic_cast<const ICls64*>(ident);
if (mGroupByType && cls)
{
const auto obj_list = cls->GetObjTable();
if (obj_list && obj_list->size())
{
for (const auto& sp_obj : *obj_list)
{
wxDataViewItem dvitem((void*)sp_obj.get());
arr.push_back(dvitem);
}
return arr.size();
}
}
return 0;
}
//-----------------------------------------------------------------------------
//virtual
bool wxDVTableBrowser::IsListModel() const //override
{
return !mGroupByType;
}
//-----------------------------------------------------------------------------
const IIdent64* wxDVTableBrowser::GetCurrentRoot()const
{
return mCurrentRoot;
}
//-----------------------------------------------------------------------------
void wxDVTableBrowser::SetClsList(const std::vector<const IIdent64*>& current
, const IIdent64* curr, bool group_by_type, int mode)
{
mGroupByType = group_by_type;
mCurrentRoot = curr;
mClsList = current;
mMode = mode;
Cleared();
}
//-----------------------------------------------------------------------------
const std::vector<const IIdent64*>& wxDVTableBrowser::GetClsList()const
{
return mClsList;
}
//-----------------------------------------------------------------------------
int wxDVTableBrowser::GetMode()const
{
return mMode;
}
//-----------------------------------------------------------------------------
std::shared_ptr<const PropVal> wxDVTableBrowser::GetPropVal(const IObj64& obj, int col_idx)const
{
const auto& idxOPropCol = mOPropColumns.get<1>();
auto prop_it = idxOPropCol.find(col_idx);
if (idxOPropCol.end() != prop_it)
{
const auto favOPrpop = obj.GetFavOPropValue();
auto val_it = favOPrpop.find(prop_it->mPid);
if (favOPrpop.cend() != val_it)
return *val_it;
}
return nullptr;
}
//-----------------------------------------------------------------------------
std::shared_ptr<const PropVal> wxDVTableBrowser::GetPropVal(const ICls64& cls, int col_idx)const
{
const auto& idxCPropCol = mCPropColumns.get<1>();
auto prop_it = idxCPropCol.find(col_idx);
if (idxCPropCol.end() != prop_it)
{
const auto favCPrpop = cls.GetFavCPropValue();
auto val_it = favCPrpop.find(prop_it->mPid);
if (favCPrpop.cend() != val_it)
return *val_it;
}
return nullptr;
}
//-----------------------------------------------------------------------------
std::shared_ptr<const PropVal> wxDVTableBrowser::GetPropVal(const wxDataViewItem &item, int col_idx)const
{
const auto ident = static_cast<const IIdent64*> (item.GetID());
const auto cls = dynamic_cast<const ICls64*>(ident);
if (cls)
return GetPropVal(*cls, col_idx);
else
{
const auto obj = dynamic_cast<const IObj64*>(ident);
if (obj)
return GetPropVal(*obj, col_idx);
}
return nullptr;
}
//-----------------------------------------------------------------------------
inline bool wxDVTableBrowser::IsTop(const wxDataViewItem &item)const
{
return item.GetID() == mCurrentRoot;
}
|
/* Copyright 2019 Abner Soares e Kallebe Sousa */
#ifndef TU_ENTIDADES_HPP_
#define TU_ENTIDADES_HPP_
#include <string>
#include "../entidades/entidades.hpp"
class TU_Usuario {
protected:
string NOME_INVALIDO;
string NOME_VALIDO;
string TELEFONE_INVALIDO;
string TELEFONE_VALIDO;
string EMAIL_INVALIDO;
string EMAIL_VALIDO;
string SENHA_INVALIDO;
string SENHA_VALIDO;
string CPF_INVALIDO;
string CPF_VALIDO;
Usuario *usuario;
int estado;
void setUp();
void testarCenario();
void tearDown();
public:
TU_Usuario(string nomei, string nomev,
string telefonei, string telefonev,
string emaili, string emailv,
string senhai, string senhav,
string cpfi, string cpfv) {
this->NOME_INVALIDO = nomei;
this->NOME_VALIDO = nomev;
this->TELEFONE_INVALIDO = telefonei;
this->TELEFONE_VALIDO = telefonev;
this->EMAIL_INVALIDO = emaili;
this->EMAIL_VALIDO = emailv;
this->SENHA_INVALIDO = senhai;
this->SENHA_VALIDO = senhav;
this->CPF_INVALIDO = cpfi;
this->CPF_VALIDO = cpfv;
}
static const int SUCESSO = 1;
static const int FALHA = 0;
int run();
};
class TU_Reserva {
protected:
string CODIGO_INVALIDO;
string CODIGO_VALIDO;
string ASSENTO_INVALIDO;
string ASSENTO_VALIDO;
string BAGAGEM_INVALIDO;
string BAGAGEM_VALIDO;
Reserva *reserva;
int estado;
void setUp();
void testarCenario();
void tearDown();
public:
TU_Reserva(string codigoi, string codigov,
string assentoi, string assentov,
string bagagemi, string bagagemv) {
this->CODIGO_INVALIDO = codigoi;
this->CODIGO_VALIDO = codigov;
this->ASSENTO_INVALIDO = assentoi;
this->ASSENTO_VALIDO = assentov;
this->BAGAGEM_INVALIDO = bagagemi;
this->BAGAGEM_VALIDO = bagagemv;
}
static const int SUCESSO = 1;
static const int FALHA = 0;
int run();
};
class TU_Carona {
protected:
string CODIGO_INVALIDO;
string CODIGO_VALIDO;
string CIDADE_ORIGEM_INVALIDO;
string CIDADE_ORIGEM_VALIDO;
string ESTADO_ORIGEM_INVALIDO;
string ESTADO_ORIGEM_VALIDO;
string CIDADE_DESTINO_INVALIDO;
string CIDADE_DESTINO_VALIDO;
string ESTADO_DESTINO_INVALIDO;
string ESTADO_DESTINO_VALIDO;
string DATA_INVALIDO;
string DATA_VALIDO;
string DURACAO_INVALIDO;
string DURACAO_VALIDO;
string VAGAS_INVALIDO;
string VAGAS_VALIDO;
string PRECO_INVALIDO;
string PRECO_VALIDO;
Carona *carona;
int estado;
void setUp();
void testarCenario();
void tearDown();
public:
TU_Carona(string codigoi, string codigov,
string cidade_origemi, string cidade_origemv,
string estado_origemi, string estado_origemv,
string cidade_destinoi, string cidade_destinov,
string estado_destinoi, string estado_destinov,
string datai, string datav,
string duracaoi, string duracaov,
string vagasi, string vagasv,
string precoi, string precov) {
this->CODIGO_INVALIDO = codigoi;
this->CODIGO_VALIDO = codigov;
this->CIDADE_ORIGEM_INVALIDO = cidade_origemi;
this->CIDADE_ORIGEM_VALIDO = cidade_origemv;
this->ESTADO_ORIGEM_INVALIDO = estado_origemi;
this->ESTADO_ORIGEM_VALIDO = estado_origemv;
this->CIDADE_DESTINO_INVALIDO = cidade_destinoi;
this->CIDADE_DESTINO_VALIDO = cidade_destinov;
this->ESTADO_DESTINO_INVALIDO = estado_destinoi;
this->ESTADO_DESTINO_VALIDO = estado_destinov;
this->DATA_INVALIDO = datai;
this->DATA_VALIDO = datav;
this->DURACAO_INVALIDO = duracaoi;
this->DURACAO_VALIDO = duracaov;
this->VAGAS_INVALIDO = vagasi;
this->VAGAS_VALIDO = vagasv;
this->PRECO_INVALIDO = precoi;
this->PRECO_VALIDO = precov;
}
static const int SUCESSO = 1;
static const int FALHA = 0;
int run();
};
class TU_Conta {
protected:
string BANCO_INVALIDO;
string BANCO_VALIDO;
string AGENCIA_INVALIDO;
string AGENCIA_VALIDO;
string NUMERO_INVALIDO;
string NUMERO_VALIDO;
Conta *conta;
int estado;
void setUp();
void testarCenario();
void tearDown();
public:
TU_Conta(string bancoi, string bancov,
string agenciai, string agenciav,
string numeroi, string numerov) {
this->BANCO_INVALIDO = bancoi;
this->BANCO_VALIDO = bancov;
this->AGENCIA_INVALIDO = agenciai;
this->AGENCIA_VALIDO = agenciav;
this->NUMERO_INVALIDO = numeroi;
this->NUMERO_VALIDO = numerov;
}
static const int SUCESSO = 1;
static const int FALHA = 0;
int run();
};
#endif // TU_ENTIDADES_HPP_
|
#include<iostream>
using namespace std;
int main()
{
int ans[20], sum = 0, index = 0, zero = 0;
for(int i = 0; i < 20; i++)
scanf("%d", &ans[i]);
for(int i = 0; i < 20; i++)
if(ans[i] < 0)
index++;
else if(ans[i] > 0)
sum += ans[i];
else
zero++;
float avg = float(sum) /float(20-index-zero);
printf("%d\n", index);
printf("%.2f\n", avg);
return 0;
}
|
#include <OpenCV/OpenCV.h>
#include <cassert>
#include <iostream>
const char * WINDOW_NAME = "Face tracker";
const CFIndex CASCADE_NAME_LEN = 2048;
char CASCADE_NAME[CASCADE_NAME_LEN] = "abc.xml";
using namespace std;
#define DRAWRECT(img, rect, color) \
cvRectangle(img, \
cvPoint((rect)->x, (rect)->y), \
cvPoint((rect)->x + (rect)->width, (rect)->y + (rect)->height),\
color, 1, 8, 0);
int main (int argc, char * const argv[]) {
const int scale = 2,
refreshDelay = 10;
// locate haar cascade from inside application bundle
// (this is the mac way to package application resources)
CFBundleRef mainBundle = CFBundleGetMainBundle();
assert(mainBundle);
CFURLRef cascade_url = CFBundleCopyResourceURL(mainBundle, CFSTR("haarcascade_frontalface_alt"), CFSTR("xml"), NULL);
assert(cascade_url);
if (!CFURLGetFileSystemRepresentation (cascade_url, true, reinterpret_cast<UInt8 *>(CASCADE_NAME), CASCADE_NAME_LEN))
abort();
// create all necessary instances
cvNamedWindow (WINDOW_NAME, CV_WINDOW_AUTOSIZE);
CvCapture * camera = cvCreateCameraCapture (CV_CAP_ANY);
CvHaarClassifierCascade* cascade = (CvHaarClassifierCascade*) cvLoad(CASCADE_NAME, 0, 0, 0);
CvMemStorage* storage = cvCreateMemStorage(0);
assert (storage);
// you do own an iSight, don't you ?!?
if (!camera)
abort();
// did we load the cascade?!?
if (!cascade)
abort();
// get an initial frame and duplicate it for later work
IplImage *current_frame = cvQueryFrame(camera);
IplImage *draw_image = cvCreateImage(cvSize(current_frame->width, current_frame->height), IPL_DEPTH_8U, 3);
IplImage *gray_image = cvCreateImage(cvSize(current_frame->width, current_frame->height), IPL_DEPTH_8U, 1);
IplImage *small_image = cvCreateImage(cvSize(current_frame->width / scale, current_frame->height / scale), IPL_DEPTH_8U, 1);
assert(current_frame && gray_image && draw_image);
// as long as there are images ...
while (current_frame = cvQueryFrame(camera)) {
// convert to gray and downsize
cvCvtColor(current_frame, gray_image, CV_BGR2GRAY);
cvResize(gray_image, small_image, CV_INTER_LINEAR);
// detect
CvSeq *faces = cvHaarDetectObjects(small_image, cascade, storage, 1.1, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(30, 30));
// draw areas
cvFlip(current_frame, draw_image, 1);
for (int i = 0; i < (faces ? faces->total : 0); i++) {
CvRect* r = (CvRect*) cvGetSeqElem (faces, i);
// Draw a circle
/*CvPoint center;
int radius;
center.x = cvRound((small_image->width - r->width*0.5 - r->x) * scale);
center.y = cvRound((r->y + r->height*0.5)*scale);
radius = cvRound((r->width + r->height)*0.25*scale);
cvCircle(draw_image, center, radius, CV_RGB(0,255,0), 3, 8, 0);*/
// Draw a rect
CvRect r2 = cvRect((small_image->width - r->x - r->width)*scale, // x is flipped
r->y*scale, r->width*scale, r->height*scale);
DRAWRECT(draw_image, &r2, CV_RGB(255, 128, 128));
// Draw approx. eyes rect
CvRect r3 = cvRect(r2.x/0.95, r2.y + (r2.height/5.0), r2.width-((r2.x/0.95)-r2.x)*2, r2.height/3.0);
DRAWRECT(draw_image, &r3, CV_RGB(255, 255, 0));
}
// just show the image
cvShowImage(WINDOW_NAME, draw_image);
// wait a tenth of a second for keypress and window drawing
int key = cvWaitKey(refreshDelay);
if (key == 'q' || key == 'Q')
break;
}
// be nice and return no error
return 0;
}
|
#include <iostream>
#include <string>
using namespace std;
int isPatternPresent(string str, string st)
{
int count;
int l1 = str.length();
int l2 = st.length();
for (int x = 0; x < l1 - l2; x++)
{
int y;
for (y = 0; y < l2; y++)
{
if (str[x + y] != st[y])
{
break;
}
}
if (y == l2)
{
count++;
y = 0;
}
}
return count;
}
int main()
{
string str;
cout << "Enter string" << endl;
cin >> str;
int k;
cout << "Enter value of k" << endl;
cin >> k;
string st[k];
for (int x = 0; x < k; x++)
{
cout << "Enter pattern " << x + 1 << endl;
cin >> st[x];
}
for (int x = 0; x < k; x++)
{
cout << isPatternPresent(str, st[x]) << endl;
}
}
|
class Solution {
public:
int threeSumClosest(vector<int> &nums, int target) {
int ret=0;
if (nums.size() < 3) return ret;
sort(nums.begin(), nums.end());
ret = nums[0]+nums[1]+nums[2];
for (auto it = nums.begin(); it < nums.end()-2; ++it) {
auto jt = it+1, kt = nums.end()-1;
while (jt < kt) {
int val = *it + *jt + *kt;
if (val < target) {
++jt;
} else if (val > target) {
--kt;
} else {
ret = target;
break;
++jt; --kt;
}
if (abs(val-target) < abs(ret-target) )
ret = val;
}
}
return ret;
}
};
|
#ifndef _IN_GAME_H_
#define _IN_GAME_H_
#include "GameState.h"
#include <vector>
#include <memory>
#include <chrono/physics/ChSystem.h>
class CObject;
class CText;
class PrimitiveBase;
class CInGame : public CGameState
{
enum PostProcessing
{
Saturation,
HorizontalPass,
VerticalPass,
Blur,
Count
};
public:
CInGame( TestApp* pApp, CAssetsDatabase* pDatabase,
Transition::E init, Transition::E end );
virtual ~CInGame();
virtual void Initialize() override;
virtual void Inputs( sf::Uint32& inputs, const InputsInfo& inputsInfo ) override;
virtual void Update() override;
virtual void RenderTargetDraw( SRenderAttributes& renderAttribs );
virtual void Draw( SRenderAttributes& renderAttribs ) override;
virtual void Destroy() override;
private:
void MeasureFPS();
void ShuffleLights();
private:
std::shared_ptr<chrono::ChSystem> m_pSystem;
std::vector<std::shared_ptr<CObject>> m_gameObjects;
std::shared_ptr<CObject> m_pPlayer;
std::shared_ptr<CText> m_pFPSText;
std::shared_ptr<PrimitiveBase> m_pQuad[5];
std::shared_ptr<PrimitiveBase> m_finalScene;
int m_iFinal;
int m_iRendered;
int m_iLastFPS;
int m_shadowRT;
std::vector<Mat4D::CVector4D> m_vLightsPos;
std::vector<Mat4D::CVector4D> m_vLightsCol;
std::vector<float> m_vAngles;
std::vector<float> m_vSpeed;
std::vector<float> m_vRadius;
CShader* pShaders[PostProcessing::Count];
Camera m_lightCamera;
};
#endif //_IN_GAME_H_
|
#ifndef OwnUnderscore_P_HPP
#define OwnUnderscore_P_HPP
#include <QObject>
class OwnUnderscorePrivate : public QObject
{
Q_OBJECT
public:
OwnUnderscorePrivate();
~OwnUnderscorePrivate();
};
#endif
|
#include <SDL.h>
#include <GL/glew.h>
#include <glm.hpp>
#include <openvr.h>
#include <gtc/matrix_transform.hpp>
#include <gtx/matrix_decompose.hpp>
#include <iostream>
#define TJH_CAMERA_IMPLEMENTATION
#include "tjh/tjh_camera.h"
#include "window.h"
#include "vr_system.h"
#include "scene.h"
#include "point_cloud.h"
#include "imgui/imgui.h"
// TODO:
// - Clear each eye to a diffrent colour
// works when clearing the resolve texture directly
// desn't seem to work when clearing the render texture and blitting to the resolve
//
// - get blitting from multisampled to non multisampled texture working
// - hand tool movements are the wrong scale
// - hand tool rotation is not around the controller
enum class RenderMode { VR, Standard };
void set_gl_attribs();
void draw_gui();
struct AudioData
{
Uint32 length = 0;
Uint8* buffer = nullptr;
};
void audio_callback( void* userdata, Uint8* stream, int length )
{
AudioData* data = (AudioData*)userdata;
if( data->length <= 0 ) return;
length = (length > data->length ? data->length : length);
SDL_MixAudio( stream, data->buffer, data->length, SDL_MIX_MAXVOLUME );
data->buffer += length;
data->length -= length;
}
void test_audio()
{
Uint8* wav_buffer;
AudioData wav_data;
SDL_AudioSpec wav_spec;
if( SDL_LoadWAV( "audio/sound.wav", &wav_spec, &wav_buffer, &wav_data.length) == NULL )
{
std::cout << "ERROR: failed to load wav" << std::endl;
}
else
{
std::cout << "AUDIO: loaded wav file" << std::endl;
}
wav_spec.callback = audio_callback;
wav_spec.userdata = &wav_data;
wav_data.buffer = wav_buffer;
if( SDL_OpenAudio( &wav_spec, nullptr ) )
{
std::cout << "ERROR: could not open audio device" << std::endl;
}
else
{
std::cout << "AUDIO: opened audio device" << std::endl;
}
SDL_PauseAudio( 0 );
while( wav_data.length )
{
SDL_Delay( 100 );
}
SDL_CloseAudio();
SDL_FreeWAV( wav_buffer );
}
int main(int argc, char** argv)
{
// Setup
Window* window;
Camera standard_camera;
VRSystem* vr_system;
Scene scene;
ShaderProgram standard_shader;
ShaderProgram point_light_shader;
RenderMode render_mode = RenderMode::VR;
// First stage initialisation
bool running = true;
window = Window::get();
if( !window ) running = false;
vr_system = VRSystem::get();
if( !vr_system ) running = false;
ImGui::Init( window->SDLWindow() );
// Second stage initialisation
if( running )
{
//test_audio();
// Shaders
standard_shader.init( "colour_shader_vs.glsl", "colour_shader_fs.glsl" );
point_light_shader.init( "point_light_shader_vs.glsl", "point_light_shader_fs.glsl" );
// Tools
//vr_system->pointLightTool()->setTargetShader( point_cloud.activeShaderAddr() );
//vr_system->pointLightTool()->setDeactivateShader( &standard_shader );
//vr_system->pointLightTool()->setActivateShader( &point_light_shader );
vr_system->pointerTool()->setShader( &standard_shader );
vr_system->setPointCloud( scene.pointCloud() );
Sphere::setShader( &standard_shader );
scene.init();
}
float dt = 0.0;
Uint32 ticks = SDL_GetTicks();
Uint32 prev_ticks = ticks;
while( running )
{
SDL_Event sdl_event;
while( SDL_PollEvent( &sdl_event ) )
{
if( sdl_event.type == SDL_QUIT ) running = false;
else if( sdl_event.type == SDL_KEYDOWN )
{
if( sdl_event.key.keysym.scancode == SDL_SCANCODE_ESCAPE ) { running = false; }
else if( sdl_event.key.keysym.scancode == SDL_SCANCODE_GRAVE )
{
if( render_mode == RenderMode::VR ) {
render_mode = RenderMode::Standard;
} else {
render_mode = RenderMode::VR;
}
}
else if( sdl_event.key.keysym.scancode == SDL_SCANCODE_TAB )
{
// Resart the testing phase
scene.init_testing();
std::cout << "Ready for testing" << std::endl;
}
else if( sdl_event.key.keysym.sym == SDLK_h )
{
scene.toggle_spheres();
}
}
ImGui::ProcessEvent( &sdl_event );
}
ImGui::Frame( window->SDLWindow(), vr_system );
// Handle the VR backend
vr_system->processVREvents();
vr_system->manageDevices();
vr_system->updatePoses();
vr_system->updateDevices( dt );
scene.update( dt );
if( render_mode == RenderMode::VR )
{
// Grab matricies from the HMD
glm::mat4 hmd_view_left = vr_system->viewMatrix( vr::Eye_Left );
glm::mat4 hmd_view_right = vr_system->viewMatrix( vr::Eye_Right );
glm::mat4 hmd_projection_left = vr_system->projectionMartix( vr::Eye_Left );
glm::mat4 hmd_projection_right = vr_system->projectionMartix( vr::Eye_Right );
// THE RENDER TEXTURE IS CLEARED WHEN
// - render texture is not multisampled
// - But blitting to the resolve buffer is not working
vr_system->bindEyeTexture( vr::Eye_Left );
//glBindFramebuffer( GL_FRAMEBUFFER, vr_system->resolveEyeTexture( vr::Eye_Left ) );
//glViewport( 0, 0, vr_system->renderTargetWidth(), vr_system->renderTargetHeight() );
set_gl_attribs();
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
scene.render( hmd_view_left, hmd_projection_left );
vr_system->render( hmd_view_left, hmd_projection_left );
draw_gui();
ImGui::Render();
vr_system->bindEyeTexture( vr::Eye_Right );
//glBindFramebuffer( GL_FRAMEBUFFER, vr_system->resolveEyeTexture( vr::Eye_Right ) );
//glViewport( 0, 0, vr_system->renderTargetWidth(), vr_system->renderTargetHeight() );
set_gl_attribs();
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
scene.render( hmd_view_right, hmd_projection_right );
vr_system->render( hmd_view_right, hmd_projection_right );
vr_system->blitEyeTextures();
vr_system->submitEyeTextures();
window->render( vr_system->resolveEyeTexture( vr::Eye_Left ), vr_system->resolveEyeTexture( vr::Eye_Right ) );
}
else if( render_mode == RenderMode::Standard )
{
// Get matricies from the 'traditional' camera
standard_camera.update( dt );
glm::mat4 view = standard_camera.view();
glm::mat4 projection = standard_camera.projection( window->width(), window->height() );
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
set_gl_attribs();
glViewport( 0, 0, window->width(), window->height() );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
scene.render( view, projection );
vr_system->render( view, projection );
draw_gui();
ImGui::Render();
}
window->present();
// Update dt
prev_ticks = ticks;
ticks = SDL_GetTicks();
dt = (ticks - prev_ticks) / 1000.0f;
}
// Cleanup
scene.shutdown();
if( vr_system ) delete vr_system;
if( window ) delete window;
return 0;
}
void set_gl_attribs()
{
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LESS );
glClearColor( 0.01f, 0.01f, 0.01f, 1.0f );
glClearDepth( 1.0f );
}
void draw_gui()
{
VRSystem* system = VRSystem::get();
ImGuiIO& IO = ImGui::GetIO();
IO.MouseDrawCursor = true;
ImGui::SetWindowFontScale( 3.0f );
ImGui::Text( "Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate );
ImGui::Separator();
Controller* controller = VRSystem::get()->leftControler();
if( controller )
{
ImGui::Text( "Touchpad Delta: (%.2f, %.2f)", controller->touchpadDelta().x, controller->touchpadDelta().y );
ImGui::Text( "Trigger: %s", controller->isButtonDown( vr::k_EButton_SteamVR_Trigger ) ? "YES" : "NO" );
}
ImGui::Text( "Translation: %f %f %f", system->moveTool()->translation().x, system->moveTool()->translation().y, system->moveTool()->translation().z );
ImGui::Text( "Rotation: %f %f %f", system->moveTool()->rotation().x, system->moveTool()->rotation().y, system->moveTool()->rotation().z );
//ImGui::Text( "Point light position: %.3f %.3f %.3f", system->pointLightTool()->lightPos().x, system->pointLightTool()->lightPos().y, system->pointLightTool()->lightPos().z );
}
|
#pragma once
#include "Core/Core.h"
#include "Utils/Timestep.h"
#include "Scene/SceneComponent.h"
#include "Scene/SceneNode.h"
#include "Scene/Component/SceneCamera.h"
#include "Scene/Component/EditorCamera.h"
#include "Scene/Component/PlanarMesh.h"
namespace Rocket
{
ENUM(SceneState) { Play = 0, Editor };
class Scene
{
public:
Scene() = default;
Scene(const String& name) : m_Name(name) {}
~Scene() = default;
void OnUpdateRuntime(Timestep ts);
void OnUpdateEditor(Timestep ts);
void OnViewportResize(uint32_t width, uint32_t height);
// TODO : Remove For Development
void SetRenderTarget();
void GetRenderTarget();
void SetNodes(Vec<Scope<SceneNode>>&& nodes);
void AddNode(Scope<SceneNode>&& node);
void AddChild(SceneNode& child);
void AddComponent(Scope<SceneComponent>&& component);
void AddComponent(Scope<SceneComponent>&& component, SceneNode& node);
SceneNode* FindNode(const String& name);
void SetRootNode(SceneNode& node);
SceneNode& GetRootNode();
template <class T>
void SetComponents(Vec<Scope<T>>&& components)
{
Vec<Scope<SceneComponent>> result(components.size());
std::transform(components.begin(), components.end(), result.begin(),
[](Scope<T>& component) -> Scope<SceneComponent> {
return Scope<SceneComponent>(std::move(component));
});
SetComponents(typeid(T), std::move(result));
}
void SetComponents(const std::type_index& type_info, Vec<Scope<SceneComponent>>&& components);
template <class T>
void ClearComponents()
{
SetComponents(typeid(T), {});
}
template <class T>
Vec<T*> GetComponents() const
{
Vec<T*> result;
if (HasComponent(typeid(T)))
{
auto& scene_components = GetComponents(typeid(T));
result.resize(scene_components.size());
std::transform(scene_components.begin(), scene_components.end(), result.begin(),
[](const Scope<SceneComponent>& component) -> T* {
return dynamic_cast<T*>(component.get());
});
}
return result;
}
const Vec<Scope<SceneComponent>>& GetComponents(const std::type_index& type_info) const;
template <class T>
bool HasComponent() const
{
return HasComponent(typeid(T));
}
bool HasComponent(const std::type_index& type_info) const;
inline void SetName(const String& new_name) { m_Name = new_name; }
inline const String& GetName() const { return m_Name; }
inline uint32_t GetViewWidth() const { return m_ViewportWidth; }
inline uint32_t GetViewHeight() const { return m_ViewportHeight; }
inline bool GetSceneChange() const { return m_SceneChange; }
inline void SetSceneChange(bool change) { m_SceneChange = change; }
SceneState GetSceneState() { return m_State; }
// For Debug
void SetPrimaryCamera(const Ref<SceneCamera>& camera) { m_PrimaryCamera = camera; }
void SetEditorCamera(const Ref<EditorCamera>& camera) { m_EditorCamera = camera; }
Ref<SceneCamera>& GetPrimaryCamera() { return m_PrimaryCamera; }
Ref<EditorCamera>& GetEditorCamera() { return m_EditorCamera; }
void SetPrimaryCameraTransform(const Matrix4f& mat) { m_PrimaryCameraTransform = mat; }
void SetEditorCameraTransform(const Matrix4f& mat) { m_EditorCameraTransform = mat; }
Matrix4f& GetPrimaryCameraTransform() { return m_PrimaryCameraTransform; }
Matrix4f& GetEditorCameraTransform() { return m_EditorCameraTransform; }
private:
String m_Name;
uint32_t m_ViewportWidth = 0;
uint32_t m_ViewportHeight = 0;
SceneState m_State = SceneState::Play;
bool m_SceneChange = false;
Matrix4f m_PrimaryCameraTransform = Matrix4f::Identity();
Matrix4f m_EditorCameraTransform = Matrix4f::Identity();
Ref<SceneCamera> m_PrimaryCamera = nullptr;
Ref<EditorCamera> m_EditorCamera = nullptr;
SceneNode* m_Root = nullptr;
Vec<Scope<SceneNode>> m_Nodes;
UMap<std::type_index, Vec<Scope<SceneComponent>>> m_Components;
friend class SceneSerializer;
};
}
|
#include "config.h"
#include <fstream>
#include <filesystem>
Mode Config::getInputMode(){
return inputMode;
}
Mode Config::getOutputMode(){
return outputMode;
}
void Config::setInputMode(Mode mode){
inputMode = mode;
}
void Config::setOutputMode(Mode mode){
outputMode = mode;
}
Config::Config(Mode readMode, Mode writeMode) {
inputMode = readMode;
outputMode = writeMode;
}
Config::Config(string readMode, string writeMode) {
if (readMode == "FILE") {
inputMode = Mode::FILE;
} else if (readMode == "CONSOLE") {
inputMode = Mode::CONSOLE;
}
if (writeMode == "FILE") {
outputMode = Mode::FILE;
} else if (writeMode == "CONSOLE") {
outputMode = Mode::CONSOLE;
}
}
bool isFileExist(const char *fileName)
{
std::ifstream infile(fileName);
return infile.good();
}
Config getConfig() {
try {
if(isFileExist("config.txt")) {
return readConfig();
}
} catch (...) {
error("Error while reading config");
}
return createConfig();
}
Config readConfig() {
ifstream is = ifstream("config.txt");
string readMode, writeMode;
is >> readMode >> writeMode;
is.close();
return Config(readMode, writeMode);
}
Config createConfig() {
ofstream os = ofstream("config.txt");
os << "CONSOLE\nCONSOLE";
os.close();
return readConfig();
}
|
#include "stdafx.h"
#include "SoundGenerator.h"
#define __PI 3.14159265358979323846
class StopRunningException: public std::exception {
int code;
public:
StopRunningException(int code)
{
this->code = code;
}
int GetCode()
{
return code;
}
};
SoundGenerator::SoundGenerator(DWORD SamplesPerSec)
{
format.nSamplesPerSec = SamplesPerSec;
format.nChannels = 1;
format.wBitsPerSample = 16;
format.nBlockAlign = 2;
format.nAvgBytesPerSec = format.nBlockAlign * SamplesPerSec;
format.cbSize = 0;
format.wFormatTag = WAVE_FORMAT_PCM;
MMRESULT result;
result = waveOutOpen((LPHWAVEOUT)&hWaveOut, WAVE_MAPPER, (LPCWAVEFORMATEX)&format, 0, 0, CALLBACK_NULL);
if (result != MMSYSERR_NOERROR)
throw WaveException(std::string("waveOutOpen"), result);
hThread = CreateThread(NULL, NULL, ThreadProc, this, CREATE_SUSPENDED, NULL);
if (NULL == hThread)
{
waveOutClose(hWaveOut);
throw WaveException(std::string("CreateThread"), GetLastError());
}
running = false;
stop_signal = false;
stoped_signal = false;
}
SoundGenerator::~SoundGenerator()
{
if (running)
{
Stop();
}
waveOutClose(hWaveOut);
CloseHandle(hThread);
}
void SoundGenerator::Start()
{
if (stop_signal)
throw std::logic_error("无法启动已停止或正在停止的播放器。");
if (running)
return;
if (-1 == ResumeThread(hThread))
throw WaveException(std::string("ResumeThread"), GetLastError());
running = true;
}
void SoundGenerator::Stop()
{
if (running == false)
return;
stop_signal = true;
while (!stoped_signal)
Sleep(0);
running = false;
}
DWORD SoundGenerator::ThreadProc(LPVOID lpParameter)
{
auto obj = ((SoundGenerator*)lpParameter);
try
{
obj->RunningThread();
}
catch(StopRunningException e)
{
obj->stoped_signal = true;
return e.GetCode();
}
return 0;
}
#define SAMPLE_PER_OUTPUT 10000
void SoundGenerator::RunningThread()
{
const int totalLength = 2 * SAMPLE_PER_OUTPUT;
const double _delta = 2 * __PI / format.nSamplesPerSec;
WAVEHDR header1, header2;
ZeroMemory(&header1, sizeof(WAVEHDR));
ZeroMemory(&header2, sizeof(WAVEHDR));
short* block1((short*)malloc(totalLength));
short* block2((short*)malloc(totalLength));
header1.dwBufferLength = totalLength;
header1.lpData = (LPSTR)(short*)block1;
header2.dwBufferLength = totalLength;
header2.lpData = (LPSTR)(short*)block2;
MMRESULT result;
for (;;)
{
while (!stop_signal && paused)
Sleep(0);
if (stop_signal)
{
while (waveOutUnprepareHeader(hWaveOut, &header1, sizeof(WAVEHDR)) == WAVERR_STILLPLAYING);
while (waveOutUnprepareHeader(hWaveOut, &header2, sizeof(WAVEHDR)) == WAVERR_STILLPLAYING);
free(block1);
free(block2);
throw StopRunningException(0);
}
CalcSound(block1, SAMPLE_PER_OUTPUT, _delta);
while (waveOutUnprepareHeader(hWaveOut, &header1, sizeof(WAVEHDR)) == WAVERR_STILLPLAYING);
result = waveOutPrepareHeader(hWaveOut, &header1, sizeof(WAVEHDR));
if (MMSYSERR_NOERROR != result)
throw WaveException(std::string("waveOutPrepareHeader"), result);
result = waveOutWrite(hWaveOut, &header1, sizeof(WAVEHDR));
if (MMSYSERR_NOERROR != result)
throw WaveException(std::string("waveOutWrite"), result);
CalcSound(block2, SAMPLE_PER_OUTPUT, _delta);
while (waveOutUnprepareHeader(hWaveOut, &header2, sizeof(WAVEHDR)) == WAVERR_STILLPLAYING);
result = waveOutPrepareHeader(hWaveOut, &header2, sizeof(WAVEHDR));
if (MMSYSERR_NOERROR != result)
throw WaveException(std::string("waveOutPrepareHeader"), result);
result = waveOutWrite(hWaveOut, &header2, sizeof(WAVEHDR));
if (MMSYSERR_NOERROR != result)
throw WaveException(std::string("waveOutWrite"), result);
}
}
void SoundGenerator::CalcSound(short * buffer, int count, const double _delta)
{
for (int i = 0; i < count; i++)
{
double complex = 0.0;
try
{
for (auto item = sound.begin(); item != sound.end(); item++)
{
item->phi += _delta*item->frequency;
if (item->phi > 2 * __PI)
item->phi -= 2 * __PI;
switch (item->type)
{
case Sound::Cos:
complex += item->amplitude * cos(item->phi);
break;
case Sound::Square:
if (item->phi < __PI)
complex += item->amplitude;
else
complex -= item->amplitude;
break;
case Sound::Sawtooth:
complex += item->amplitude * item->phi / (2 * __PI);
break;
case Sound::Line:
complex += item->amplitude;
}
}
}
catch (...) {}
buffer[i] = (short)complex;
}
}
|
#include "Generated/W05ScriptIncludes.h"
using namespace myscript;
int main()
{
// VCZH_DEBUG_NO_REFLECTION is on
// so we don't need, and are not allowed, to start reflection
auto myapp = MakePtr<MyApp>();
myapp->CreateScripting()->Execute(L"Gaclib");
// we need to call this because we use generated code from Workflow script
FinalizeGlobalStorage();
}
|
#pragma once
#include "visibility_modifier.h"
#include "local_var_descriptor.h"
namespace ionir {
struct FieldDescriptor : LocalVariableDescriptor {
VisibilityModifier visibility;
};
}
|
#pragma once
#include <iostream>
#include <string>
#include <fstream>
class CodeWriter
{
public:
CodeWriter();
void setFileName(std::string fileName);
std::string outputFileName;
std::string moduleName;
std::ofstream outputFile;
int eqLabelNum;
int gtLabelNum;
int ltLabelNum;
void writeArithmetic(std::string command);
void writePushPop(std::string cmmd, std::string segment, int index);
void incrStack();
void decrStack();
void Close();
~CodeWriter();
};
|
#include<bits/stdc++.h>
using namespace std;
#define maxn 505
int c[maxn];
int n;
int d[maxn][maxn];
int dp(int i,int j){
if(i>j) return 0;
if(i==j) return 1;
if(d[i][j]!=-1) return d[i][j];
int tans=dp(i+1,j)+1;
int t=INT_MAX;
for(int k=i+2;k<=j;k++){
if(c[i]==c[k]){
t=min(t,dp(i+1,k-1)+dp(k+1,j));
// if(i==2&&j==6)
// cout<<"t "<<t<<" "<<k<<" "<<dp(i+1,k-1)<<"\n";
}
}
tans=min(tans,t);
if(c[i]==c[i+1])
tans=min(tans,1+dp(i+2,j));
// cout<<i<<" "<<j<<" "<<tans<<"\n";
return d[i][j]=tans;
}
int main(){
memset(d,-1,sizeof(d));
cin>>n;
for(int i=1;i<=n;i++)
cin>>c[i];
cout<<dp(1,n)<<"\n";
return 0;
}
|
#ifndef ENGIMON_HPP
#define ENGIMON_HPP
#include <string>
#include <list>
#include <vector>
#include <iostream>
#include "Skill.hpp"
using namespace std;
class Engimon
{
protected:
string name;
string species;
list<Skill> skill;
vector<string> element;
int* level;
int* experience;
int* cumulativeExperience;
// string *parent1;
// string *parent2;
string* parent1;
string* parent2;
string message;
public:
Engimon();
Engimon(string nama, string species, vector<string> element);
Engimon(const Engimon &engimon);
~Engimon();
Engimon &operator=(const Engimon &);
bool operator==(const Engimon &engimon) const;
void CheckLevelUp(Engimon engimon);
bool CheckDead(Engimon engimon);
const Skill getHighestMastery();
void showStats();
void AddSkill(Skill skill);
void RemoveSkillByIdx(int skillIdx);
void RemoveSkill(Skill skill);
bool containsSkill(list<Skill> listSkill, string skillName);
Engimon breed(Engimon anotherEngimon);
bool isSkillSizeValid(Engimon engimon);
void addExp(int exp);
//Getters
string getName();
string getSpecies();
string getMessage();
vector<string> getElement();
int getLevel();
int getExperience();
int getCumulativeExperience();
list<Skill> getSkill();
//Setters
void setLevel(int level); // Used for debugging purposes
void pushToParents(Engimon parent);
void setMessage(string newMessage);
void setParent1(string engimon1);
void setParent2(string engimon2);
};
#endif
|
#include "CString.h"
#include "CDate.h"
int main()
{
CString cstring;
CString obj;
obj.display_string();
char s[] = { 'c', 'o', 'd', 'i', 'n', 'g' ,'\0' };
CString obj1(s);
obj1.display_string();
char ch = 'A';
CString obj2(ch, 1);
obj2.display_string();
string temp;
cout << " Enter a String: ";
getline(cin, temp);
cstring.accept_string(temp);
cstring.display_string();
CString obj3(cstring);
obj3.display_string();
CString obj4;
obj4 = cstring;
obj4.display_string();
int day, month, year;
cout << "Enter Employee Join Date info:" << endl;
cout << "Enter Day: " << endl;
cin >> day;
cout << "Enter Month: " << endl;
cin >> month;
cout << "Enter Year: " << endl;
cin >> year;
CDate date;
date.set_CDate(day, month, year);
date.get_CDate();
return 0;
}
|
#include "utils.h"
#include <algorithm>
#include <stdlib.h>
#include <time.h>
static const int BASE = 10;
static int NUM_DIGITS;
static int tempDigits[BASE];
static bool tempUsed[BASE];
bool isNumberValid(int number)
{
if (number < 0) return false;
std::fill(tempUsed, tempUsed + BASE, false);
for (int i = 0; i < NUM_DIGITS; ++i)
{
int dig = number % BASE;
number /= BASE;
if (dig == 0 && i == NUM_DIGITS - 1) return false;
if (tempUsed[dig]) return false;
tempUsed[dig] = true;
}
if (number > 0) return false;
return true;
}
bool isResponseValid(Response response)
{
int b = response.bulls;
int c = response.cows;
return b >= 0 && c >= 0 && b + c <= NUM_DIGITS && (b != NUM_DIGITS - 1 || c != 1);
}
bool isResponseFinal(Response response)
{
return response.bulls == NUM_DIGITS;
}
Response findResponse(int number, int guess)
{
std::fill(tempUsed, tempUsed + BASE, false);
for (int i = 0; i < NUM_DIGITS; ++i)
{
int dig = number % BASE;
number /= BASE;
tempUsed[dig] = true;
tempDigits[i] = dig;
}
int bulls = 0;
int cows = 0;
for (int i = 0; i < NUM_DIGITS; ++i)
{
int dig = guess % BASE;
guess /= BASE;
if (tempDigits[i] == dig) ++bulls;
else if (tempUsed[dig]) ++cows;
}
return {bulls, cows};
}
std::vector<int> findDigits(int number)
{
std::vector<int> digits(NUM_DIGITS);
for (int i = 0; i < NUM_DIGITS; ++i)
{
digits[NUM_DIGITS - i - 1] = number % BASE;
number /= BASE;
}
return digits;
}
int findNumber(const std::vector<int>& digits)
{
int number = 0;
for (int i = 0; i < NUM_DIGITS; ++i)
{
number = number * BASE + digits[i];
}
return number;
}
std::vector<int> validNumbers;
std::vector<Response> validResponses;
std::vector<int> validDigits;
std::vector<int> validPos;
static int responseCodeMap[BASE + 1][BASE + 1];
static void findAllValidNumbers()
{
validNumbers.clear();
int maxNum = 1;
for (int i = 0; i < NUM_DIGITS; ++i)
{
maxNum *= BASE;
}
for (int i = 0; i <= maxNum; ++i)
{
if (isNumberValid(i)) validNumbers.push_back(i);
}
}
static void findAllValidResponses()
{
validResponses.clear();
for (int bulls = 0; bulls <= NUM_DIGITS; ++bulls)
{
for (int cows = 0; cows <= NUM_DIGITS; ++cows)
{
if (isResponseValid({bulls, cows}))
{
responseCodeMap[bulls][cows] = validResponses.size();
validResponses.push_back({bulls, cows});
}
}
}
}
static void findAllValidDigits()
{
validDigits.clear();
for (int i = 0; i < BASE; ++i)
{
validDigits.push_back(i);
}
}
static void findAllValidPos()
{
validPos.clear();
for (int i = 0; i < NUM_DIGITS; ++i)
{
validPos.push_back(i);
}
}
int responseToIndex(Response response)
{
return responseCodeMap[response.bulls][response.cows];
}
int randomNumber()
{
int rng = rand() * (RAND_MAX + 1) + rand();
return validNumbers[rng % validNumbers.size()];
}
void initRandomizer()
{
srand(time(0));
}
void setParams(int numDigits)
{
NUM_DIGITS = numDigits;
findAllValidNumbers();
findAllValidResponses();
findAllValidDigits();
findAllValidPos();
}
|
#include "tipocontroller.h"
#include "tipoviewer.h"
#include "tipodao.h"
TipoController::TipoController()
{
//ctor
}
TipoController::~TipoController()
{
//dtor
}
void TipoController::abm()
{
TipoViewer* tv = new TipoViewer();
bool salir = false;
while (!salir)
{
switch (tv->menu())
{
case 1:
listar();
break;
case 2:
buscar();
break;
case 3:
agregar();
break;
case 4:
modificar();
break;
case 5:
eliminar();
break;
case 6:
salir = true;
break;
}
}
}
void TipoController::listar()
{
(new TipoViewer())->listar((new TipoDAO())->collection());
}
void TipoController::buscar()
{
TipoViewer* tv = new TipoViewer();
tv->mostrar((new TipoDAO())->find(tv->buscar()));
}
void TipoController::agregar()
{
Tipo* tp = new Tipo();
(new TipoViewer())->cargar(tp, "Agregar TIPO");
(new TipoDAO())->add(tp);
}
void TipoController::modificar()
{
Tipo* tp = new Tipo();
TipoViewer* tv = new TipoViewer();
tv->mostrar(tp = (new TipoDAO())->find(tv->buscar()));
(new TipoViewer())->cargar(tp, "Modificar TIPO");
(new TipoDAO())->update(tp);
}
void TipoController::eliminar()
{
Tipo* tp = new Tipo();
TipoViewer* tv = new TipoViewer();
tv->mensaje("Eliminar TIPO");
tv->mostrar(tp = (new TipoDAO())->find(tv->buscar()));
(new TipoDAO())->del(tp);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2006 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Karlsson
*/
#if !defined ACCESSORS_LNG_H && defined PREFS_HAS_LNG
#define ACCESSORS_LNG_H
#include "modules/prefsfile/accessors/prefsaccessor.h"
#include "modules/prefsfile/accessors/ini.h"
/**
* Accessor for 4.0+ language files. This class parses files
* containing language strings in the 4.0+ language file format
* and convert them according to their character encoding
* setting.
*/
class LangAccessor : public IniAccessor
{
public:
LangAccessor() : IniAccessor(TRUE) {};
/**
* Loads and parses the content in the file and
* put the result in the map.
* @param file The file to load.
* @param map The map to put the result in.
*/
virtual OP_STATUS LoadL(OpFileDescriptor *file, PrefsMap *map);
#ifdef UPGRADE_SUPPORT
/**
* Check for valid LNG file formats. Checks the header of the lng
* file to see if it is in a compatible format, and then checks
* the database version number to see if it has a compatible numbering
* scheme.
*/
static BOOL IsRecognizedLanguageFile(OpFileDescriptor *file);
#endif // UPGRADE_SUPPORT
};
#endif // !ACCESSORS_LNG_H && PREFS_HAS_LNG
|
#ifndef CMPRO_DEEP_PROCESS_H
#define CMPRO_DEEP_PROCESS_H
#include <dlib/opencv.h>
#include <opencv2/opencv.hpp>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
//#include "tensorflow/core/public/session.h"
//#include "tensorflow/core/platform/env.h"
#include "configure.h"
#include "coordinate_convert.h"
#include "sequence_convert.h"
#include "shape_processing.h"
#include "model.h"
class DeepProcess {
public:
DeepProcess();
int deep_cal();
void loop_process();
bool is_loop_continue;
Model model_process;
long shape_differ_left;
long shape_differ_top;
long shape_width;
long shape_height;
bool is_updated;
private:
void DimensionCalculation();
CoordinateConvert converter;
SequenceConvert seqconverter;
Configure config;
dlib::full_object_detection detected_shape;
dlib::frontal_face_detector detector;
dlib::shape_predictor pose_model;
cv::Mat showing_image;
int state;
long duration;
//position and size of the selected area
long rfleft, rftop, area_width, area_height;
double score;
clock_t clock_weight ;
clock_t clock_time ;
//各种状态的显示消息
const std::vector<std::string> ctmsg = {"未匹配","重度3","中度2","轻度1","正常0","状态异常"};
const std::vector<std::string> show_msg = {" No-Matching","degree-3","degree-2 ","degree-1","degree-0","Alarming"};
};
#endif //CMPRO_DEEP_PROCESS_H
|
#ifndef wali_util_WEIGHT_CHANGER_GUARD
#define wali_util_WEIGHT_CHANGER_GUARD 1
/**
* @author Akash Lal
*/
#include "wali/Common.hpp"
#include "wali/SemElem.hpp"
namespace wali
{
namespace util
{
/**
* @class WeightChanger
*
* Encapsulates a unary function for changing weights
*
* @see wali::sem_elem_t
*/
class WeightChanger
{
public:
virtual ~WeightChanger() {}
virtual sem_elem_t change_weight( sem_elem_t wt ) = 0;
}; // WeightChanger
} // namespace util
} // namespace wali
#endif // wali_util_WEIGHT_CHANGER_GUARD
|
//Using bipartite graph. Time-0.000s
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define vll vector<ll>
int main()
{
ll n,l,a,b;
while(cin>>n)
{
if(n==0) break;
cin>>l;
vll AdjList[n];
ll color[n];
for(int i=0;i<l;i++)
{
cin>>a>>b;
AdjList[a].push_back(b);
}
queue<int> q; q.push(0);
for(int i=0;i<n;i++)
{
color[i]=-1;
}
color[0] = 0;
bool isBipartite = true; // addition of one boolean flag, initially true
while (!q.empty() && isBipartite) { // similar to the original BFS routine
int u = q.front(); q.pop();
for (int j = 0; j < (int)AdjList[u].size(); j++) {
if (color[AdjList[u][j]] == -1) { // but, instead of recording distance,
color[AdjList[u][j]] = 1 - color[u]; // we just record two colors {0, 1}
q.push(AdjList[u][j]); }
else if (color[AdjList[u][j]] == color[u]) { // u & v.first has same color
isBipartite = false; break; } } } // we have a coloring conflict
if(isBipartite) cout<<"BICOLORABLE.\n";
else cout<<"NOT BICOLORABLE.\n";
}
}
|
#include <iostream>
using namespace std;
class Node{
private:
int idx;
int leftIdx, rightIdx;
public:
Node(int a = -1) : idx(a) {
leftIdx = -1;
rightIdx = -1;
}
void setLchild(int lc);
void setRchild(int rc);
int getLchild();
int getRchild();
int getIdx();
};
void Node::setLchild(int lc){
leftIdx = lc;
}
void Node::setRchild(int rc){
rightIdx = rc;
}
int Node::getLchild(){
return leftIdx;
}
int Node::getRchild(){
return rightIdx;
}
int Node::getIdx(){
return idx;
}
int n;
Node nodes[26];
const char nodeCh[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z'
};
void setNodes(){
for(int i = 0; i < 26; i++){
nodes[i] = i;
}
}
int searchIndex(char ch){
int ret = -1;
for(int i = 0; i < 26; i++){
if(nodeCh[i] == ch){
ret = i;
break;
}
}
return ret;
}
void preCycle(int idx){
if(idx == -1){
return;
}
cout << nodeCh[idx];
preCycle(nodes[idx].getLchild());
preCycle(nodes[idx].getRchild());
}
void midCycle(int idx){
if(idx == -1){
return;
}
midCycle(nodes[idx].getLchild());
cout << nodeCh[idx];
midCycle(nodes[idx].getRchild());
}
void postCycle(int idx){
if(idx == -1){
return;
}
postCycle(nodes[idx].getLchild());
postCycle(nodes[idx].getRchild());
cout << nodeCh[idx];
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
setNodes();
cin >> n;
while(n--){
char rt, lc, rc;
cin >> rt >> lc >> rc;
int rtidx = searchIndex(rt);
int lcidx = searchIndex(lc);
int rcidx = searchIndex(rc);
if(lcidx != -1){
nodes[rtidx].setLchild(lcidx);
}
if(rcidx != -1){
nodes[rtidx].setRchild(rcidx);
}
}
//순회
preCycle(0);
cout << '\n';
midCycle(0);
cout << '\n';
postCycle(0);
return 0;
}
|
/**
* jseb2Controller.cc
* Allocate DMA buffers only once in constructor.
* Do not deallocate buffer at the end of a run
*/
#include <jseb2Controller.h>
bool jseb2Controller::runcompleted = false;
bool jseb2Controller::rcdaqdataready = false;
bool jseb2Controller::dmaallocationsuccess = false; // signal DMA failure
bool jseb2Controller::dmaallocationcompleted = false; // signal DMA allocation done
bool jseb2Controller::forcexit = false;
extern pthread_mutex_t M_cout;
extern pthread_mutex_t DataReadoutDone;
extern pthread_mutex_t DataReadyReset;
jseb2Controller::jseb2Controller()
{
_verbosity = LOG;
verbosity = Dcm2_BaseObject::LOG;
nevents = 0; // default to unlimited events
// default output file name
strcpy(outputfilename,"dcm2jseb2adcoutput.prdf");
exitRequested = false; //
writeFrames = true; // default write to file enabled
// DMA buffer settings
nbytes = 4*1024*1024; // 4 MB buffers
dwDMABufSize = nbytes;
dwOptions = DMA_FROM_DEVICE | DMA_ALLOW_64BIT_ADDRESS;
}
jseb2Controller::~jseb2Controller()
{
//delete controller;
//windriver->Close();
}
void jseb2Controller::freeDMABuffers()
{
// Release DMA buffers
for(unsigned int idma = 0; idma < nbuffers; idma++)
{
WDC_DMABufUnlock(pDma[idma]);
}
} // freeDMABuffers
void jseb2Controller::Close()
{
freeDMABuffers();
delete controller; // added 02042018
windriver->Close();
} // Close
void jseb2Controller::enableWrite2File()
{
writeFrames = true; // write to file enabled
}
void jseb2Controller::disableWrite2File()
{
writeFrames = false; // disable write to file
}
/**
* start_read2file
* returns int thread creation status 0 == success; on error returns pthread error number
*/
int jseb2Controller::start_read2file()
{
int result;
pthread_t tid;
result = pthread_create(&tid, 0, jseb2Controller::read2FileThread, this);
// wait for dma allocation to complete so DMA status test is valid
while(jseb2Controller::dmaallocationcompleted == false)
{
sleep(1);
}
return result;
} // start_read2file
void * jseb2Controller::read2FileThread(void * arg)
{
((jseb2Controller*)arg)->jseb2_seb_read2file();
//cout << "jseb2Controller: end read2FileThread" << endl;
} // read2FileThread
void jseb2Controller::Exit(int command)
{
cout << "jseb2Controller Exit called " << endl;
exitRequested = true;
return;
} // Exit
void jseb2Controller::jseb2_seb_read2file()
{
bool printWords = false;
bool printFrames = false;
jseb2_seb_reader(jseb2, printWords, printFrames, writeFrames);
cout << "jeb2_seb_read2file: returned from jseb2_seb_reader " << endl;
jseb2Controller::runcompleted = true;
} // jseb2_seb_read2file
bool jseb2Controller::Init(string jseb2name)
{
// set name of jseb2 to use
_jseb2name = jseb2name;
//Dcm2_WinDriver *windriver = Dcm2_WinDriver::instance();
windriver = Dcm2_WinDriver::instance();
windriver->SetVerbosity(verbosity);
if(!windriver->Init())
{
cerr << " JSEB2() - Failed to load WinDriver Library" << endl;
windriver->Close();
return 0;
}
//Dcm2_Controller *controller = new Dcm2_Controller();
controller = new Dcm2_Controller();
controller->SetVerbosity(verbosity);
if(!controller->Init())
{
cerr << " JSEB2() - Failed to initialize the controller machine" << endl;
delete controller;
windriver->Close();
return 0;
}
unsigned int njseb2s = controller->GetNJSEB2s();
cout << " A scan of the PCIe bus shows " << njseb2s << " JSEB2(s) installed" << endl;
cout << endl;
jseb2 = controller->GetJSEB2(jseb2name); // uses internal jseb2
jseb2->Init();
//delete controller;
//windriver->Close();
// allocate DMA buffers
allocateDMA();
return true;
} // Init
/**
* setJseb2Name
* sets the name of the jseb2 2 use
* must be called before init
*/
void jseb2Controller::setJseb2Name(string jseb2name)
{
_jseb2name = jseb2name;
} // setJseb2Name
void jseb2Controller::setNumberofEvents(unsigned long numberofevents)
{
nevents = numberofevents;
} // setNumberofEvents
void jseb2Controller::setOutputFilename(string outputdatafilename)
{
strcpy(outputfilename,outputdatafilename.c_str());
cout << "jseb2Controller: using output data file : " << outputfilename << endl;
} // setOutputFilename
const UINT32 * jseb2Controller::getEventData() const
{
return tmpeventbuffer;
}
/*
* getEventSize
* returns the number of words in the event
*/
UINT32 jseb2Controller::getEventSize()
{
return storedeventsize;
}
/**
* allocateDMA
* allocate dma here in place of in jseb2_seb_red2file
*
*/
bool jseb2Controller::allocateDMA()
{
DMAStatus = 0;
for(unsigned int idma = 0; idma < nbuffers; idma++)
{
DMAStatus = WDC_DMAContigBufLock(jseb2->GetHandle(), &pbuff[idma], dwOptions, dwDMABufSize, &pDma[idma]);
pwords[idma] = static_cast<UINT32*>(pbuff[idma]);
if (DMAStatus != WD_STATUS_SUCCESS )
{
cout << "Failed to Allocate DMA for buffer " << idma << endl;
cout << "pDma[0] = " << pDma[0] << " pDma[1] = " << pDma[1] << endl;
cout << "DMA error " << hex << DMAStatus << dec << " reason = " << Stat2Str(DMAStatus) << endl;
jseb2Controller::dmaallocationsuccess = false; // signal DMA failure
jseb2Controller::dmaallocationcompleted = true; // signal DMA allocation done
// write DMA error to log file
FILE * logf;
logf = fopen("/home/phnxrc/desmond/daq/txt_output/dmaerrorinfo.txt","w");
fprintf(logf,"DMA error %x DMA error text: %s\n",DMAStatus,Stat2Str(DMAStatus));
fclose(logf);
return false;
} // DMA success test
} // next dma buffer
jseb2Controller::dmaallocationsuccess = true; // signal DMA success
jseb2Controller::dmaallocationcompleted = true; // signal DMA allocation don
return true;
} // allocateDMA
/**
* jseb2_seb_reader
* copied from jseb2 on 4/11/2017
*/
void jseb2Controller::jseb2_seb_reader(Dcm2_JSEB2 *jseb2, bool printWords, bool printFrames, bool writeFrames)
{
// kill signal capture
//signal(SIGABRT, &jseb2_exit);
//signal(SIGTERM, &jseb2_exit);
//signal(SIGINT, &jseb2_exit);
bool failDetected = false;
bool debugDma = false ;
bool debugEventReadout = false;
bool debugRcdaqEventReadout = false;
bool debugRcdaqEventReadoutCount = true;
bool debugRcdaqEventReadoutLock = false;
printFrames = false;
cout << endl;
PHDWORD *buffer;
oBuffer *ob = 0;
int fd = 0;
int buffer_size = 256*1024*4 ; // makes 4MB (specifies how many dwords, so *4)
buffer = new PHDWORD [buffer_size];
ob = new oamlBuffer (argv[optind+1], buffer, buffer_size);
jseb2->SetReceiverDefaults();
unsigned int rcv = 3;
int MAX_PRINT_ERRORS = 20;
int frame_errors_printed = 0;
if(writeFrames)
{
//cout << " Please enter the name of an output file:" << endl;
//scanf("%s",outputfilename);
cout << "jseb2Controller: Using output data file: " << outputfilename << endl;
//cout << " Please select the desired number of events (0 for unlimited):" << endl;
//scanf("%lu",&nevents);
cout << "jseb2Controller: Collecting " << nevents << " events " << endl;
}
// file output
Jseb2_EventBuffer *filebuffer = new Jseb2_EventBuffer();
string filename(outputfilename);
unsigned long ievent = 0;
UINT32 event_offset = 0;
UINT32 event_number = 0;
if(writeFrames)
{
filebuffer->SetVerbosity(Dcm2_FileBuffer::LOG);
filebuffer->SetRunNumber(0xdcb25eb);
if(!filebuffer->OpenFile(filename))
{
cerr << " Failed to open output file: " << filename << endl;
delete filebuffer;
return;
}
}
// Frame storage
UINT32 *pframe = NULL; // beginning of frame in dma buffer
unsigned int iframe = 0;
unsigned int ioffset = 0;
unsigned int nFrameWords = 0;
unsigned int nFramesPerEvent = 0;
const unsigned int maxFrameWords = 8*Dcm2_FileBuffer::MAX_WORDS_PER_PACKET;
UINT32 frameWords[maxFrameWords];
UINT32 *pframeWords = (UINT32*)&frameWords;
// Prepare for operation
jseb2->EnableHolds(0x2000); // FIFO fills to 16kB then TRX exerts hold
jseb2->AbortDMA(); // Ends previous DMA
jseb2->ClearReceiverFIFO(rcv); // Flushes FIFOs
jseb2->SetUseLock(true); // Lock the JSEB2 use during DMAs
if(!jseb2->WaitForLock(5))
{
cout << " Unable to lock JSEB2, attempting cleanup..." << endl;
jseb2->DestroyLock(); // called in jseb2_cleanup
jseb2->CleanUp(Dcm2_JSEB2::RCV_BOTH);
if(!jseb2->WaitForLock(5))
{
cout << " Still unable to lock JSEB2, exiting..." << endl;
return;
}
// EJD 11/30/17 try reexecuting above jseb2 commands to restart
jseb2->EnableHolds(0x2000); // FIFO fills to 16kB then TRX exerts hold
jseb2->AbortDMA(); // Ends previous DMA
jseb2->ClearReceiverFIFO(rcv); // Flushes FIFOs
jseb2->SetUseLock(true); // Lock the JSEB2 use during DMAs
}
cout << " Locked JSEB2 " << endl;
bool DMAcomplete = false;
UINT32 bytesleftold = nbytes;
UINT32 bytesleftnew = nbytes;
UINT32 receivedbytes = bytesleftold-bytesleftnew;
UINT32 receivedwords = receivedbytes/sizeof(UINT32);
UINT32 status = 0x0;
UINT32 bytesleftrcvr = 0;
unsigned int idma = nbuffers-1;
bool firstpass = true;
UINT64 bytesThroughOptics = 0;
UINT64 bytesThroughDMA = 0;
UINT64 bytesLeftOnJSEB2 = 0;
pthread_mutex_lock( &DataReadyReset ); // re-enable trigger ready test
while(true)
{
// calculate bytes through optics
if(firstpass)
{
bytesThroughOptics = 0;
bytesThroughDMA = 0;
}
else // not first pass
{ // not first pass
if (debugEventReadout)
{
cout << "LINE " << __LINE__ <<" start NEXT pass: " << endl;
}
if(!DMAcomplete)
{
// record progress on previous DMA
bytesleftnew = jseb2->GetBytesLeftToDMA();
if (debugDma)
cout << "LINE " << __LINE__ << " not first pass: DMA NOT complete bytesleftnew = " << bytesleftnew << endl;
// abort the previous DMA
jseb2->AbortDMA();
// sync the processor cache to system memory
WDC_DMASyncIo(pDma[idma]);
}
else
{
// record progress on previous DMA
bytesleftnew = 0;
// sync the processor cache to system memory
WDC_DMASyncIo(pDma[idma]);
}
// update counter for bytes out on DMA
bytesThroughDMA += (nbytes - bytesleftnew);
if (debugEventReadout) {
cout << "LINE " << __LINE__<< "jseb2: DMA done bytesThroughDMA = " << bytesThroughDMA << endl;
cout << "jseb2: bytesleftnew = " << bytesleftnew << " bytesleftold = " << bytesleftold << endl;
}
// print any additional DMAed words since last print...
if(bytesleftnew != bytesleftold)
{
receivedbytes = bytesleftold-bytesleftnew;
receivedwords = receivedbytes/sizeof(UINT32);
//---BEGIN PARSING DATA STREAM------------------------
// print out new words and/or advance dma progress pointer
if(printWords)
{
cout << " (#" << idma << ") ";
for(unsigned int iword = 1; iword < receivedwords+1; iword++)
{
UINT32 u32Data = *pwords[idma];
pwords[idma]++;
cout.width(8); cout.fill('0'); cout << hex << u32Data << dec << " ";
if(iword%8 == 0)
{
cout << endl;
if(iword < receivedwords) cout << " (#" << idma << ") ";
}
}
}
else // just advance pointer
{
for(unsigned int iword = 1; iword < receivedwords+1; iword++)
{
pwords[idma]++;
}
}
// parse new data for frames
if(printFrames || writeFrames)
{
// check for new frame word...
while(pframe < pwords[idma])
{
// copy out length of new frame
if(nFrameWords == 0)
{
nFrameWords = *pframe;
}
// see if this frame has been fully DMAed
UINT32 DMAprogress = pwords[idma] - pframe; // number of words
if(nFrameWords - ioffset < DMAprogress)
{
// put the remainder of this frame into array
for(unsigned int iword = ioffset; iword < nFrameWords; iword++)
{
frameWords[iword] = *pframe;
pframe++;
}
// the first frame will be an empty partitioner frame
if(iframe == 0)
{
if(writeFrames)
{
//pbeginframe = filebuffer->GetBufferPointer();
// if we get the pointer here we need to skip over the
// 8 word frame header and the 8 word dcm2 frame. so
// we could have
//pbeginframe = filebuffer->GetBufferPointer();
//pbeginframe += 16;
filebuffer->StartEvent();
}
// RCDAQ
//pbeginframe = pframe - sizeof(UINT32);
if (debugEventReadout)
cout << "LINE " << __LINE__ << " start event at " << pbeginframe << endl;
unsigned int oldFramesPerEvent = nFramesPerEvent;
nFramesPerEvent = (frameWords[3] >> 16);
if(nFramesPerEvent == 0) nFramesPerEvent = oldFramesPerEvent;
if(printFrames)
{
cout << endl;
cout << " PART3 Frame: ";
for(unsigned int iword = 0; iword < 8; iword++)
{
cout.width(8); cout.fill('0'); cout << hex << frameWords[iword] << dec << " ";
}
cout << endl;
}
if(frameWords[0] != 0x8)
{
cout << "Sync frame has incorrect length " << frameWords[0] << endl;
exitRequested = true; printWords = true;
failDetected = true;
break;
}
if(frameWords[1] != 0xFFFFFF00)
{
cout << "Corrupt or missing frame marker" << endl;
failDetected = true;
exitRequested = true; printWords = true;
break;
}
}
// additional frames will be from each dcm2 board
else
{
// coding around Chi's extra sync frame appearances
if(frameWords[0] != 0x8)
{
if(printFrames)
{
cout << " DCM2 Frame::: ";
for(unsigned int iword = 0; iword < 8; iword++)
{
cout.width(8); cout.fill('0'); cout << hex << frameWords[iword] << dec << " ";
}
cout << "... ";
cout.width(8); cout.fill('0'); cout << hex << frameWords[nFrameWords-1] << dec;
cout << endl;
}
if(frameWords[1] != 0xFFFFFF00)
{
cout << "Corrupt or missing frame marker" << endl;
failDetected = true;
exitRequested = true; printWords = true;
break;
}
if(writeFrames)
{
// get event number
UINT32 prev_event_number = event_number;
event_number = frameWords[6];
if(event_number < prev_event_number)
{
event_offset += prev_event_number;
if(event_number == 0) event_offset++;
}
// set event number
filebuffer->SetEventNumber(event_number+event_offset);
if (debugRcdaqEventReadoutCount)
cout << "LINE " << __LINE__ << " set buffer event number = " << event_number + event_offset<< endl;
//cout << "jseb2: copyFrameIntoBuffer for event " << event_number+event_offset << endl;
//cout << "LINE " << __LINE__<< " copy Frame into Buffer words " << nFrameWords << endl;
// set begin frame where DCM2 frame is written
pbeginframe = filebuffer->GetBufferPointer();
// add frame to file buffer
filebuffer->CopyFrameIntoBuffer(nFrameWords,pframeWords);
rcdaqEventNumber = event_number + event_offset;
if (debugEventReadout)
cout << "LINE " << __LINE__ << " COPY "<< nFrameWords << " words FRAME TO BUFFER " << endl;
if (debugRcdaqEventReadoutCount)
cout << "LINE " << __LINE__ << " copied event to buffer: event number = " << rcdaqEventNumber << endl;
}
}
else
{
cout << "---Skipping spurious sync frame---" << endl;
iframe--;
}
}
ioffset = 0;
nFrameWords = 0;
iframe++;
// end the event when all frames are collected
if(iframe > nFramesPerEvent)
{
if(writeFrames)
{
filebuffer->EndEvent();
filebuffer->CheckBufferSpace();
// RCDAQ
//pendframe = pframe - sizeof(UINT32);
// this should signale the rcdaqTriggerHandler::wait_for_trigger
// to unlock TriggerSem. This will trigger EventLoop to
// execute the put_data on rcdaqTriggerHandler which will read
// the data from rcdaqController. It will use the pointer
// to the beginning of the event
// here unlock to data read program and wait for it to finish
// The data read program waits for TriggerSem and unlocks
// TriggerDone when it is finished
// EJD
//pbeginframe = filebuffer->GetBufferPointer();
//rcdaqEventNumber = *(pbeginframe + 2); // stored event number
storedeventsize = *(pbeginframe); // first word is event size
rcdaqEventNumber = event_number;
if (debugRcdaqEventReadoutCount) {
//cout << "LINE " << __LINE__ << " STORED EVENT DATA " << endl;
//cout << "\t EVENT SIZE = " << storedeventsize << endl;
pthread_mutex_lock(&M_cout);
cout << "\t EVENT NUMBER = " << rcdaqEventNumber << " ievent = " << ievent << endl;
pthread_mutex_unlock(&M_cout);
}
// copy the event data to the tmp event buffer
// tmpeventbuffer stores only 1 event
for (int itmp = 0; itmp < storedeventsize ; itmp++ )
{
// 11/16/17 try offset of 16 to exclude dcm2 header
// 11/17/2017 ; try skipping 12 8 word frame header + 4 word buffer header
tmpeventbuffer[itmp] = *(pbeginframe + (itmp) + 8 ); // add 8 to skip frame header
if (debugRcdaqEventReadout)
{
if (itmp < 8 )
cout << "\t tbuff["<<itmp<<"]= " << hex << tmpeventbuffer[itmp] << dec << endl;
}
}
rcdaqdataready = true; // signal data is available to rcdaq
if (debugRcdaqEventReadoutLock) {
pthread_mutex_lock(&M_cout);
cout << "LINE " << __LINE__ << " set rcdaqdataready TRUE" << endl;
cout << "LINE " << __LINE__ << " jsebreader: wait on DataReadoutDone for data read completion " << endl;
pthread_mutex_unlock(&M_cout);
}
pthread_mutex_lock( &DataReadoutDone ); // wait for rcdaq to read data
if (debugRcdaqEventReadoutLock) {
pthread_mutex_lock(&M_cout);
cout << "LINE " << __LINE__ << " jsebreader: GOT LOCK on DataReadoutDone " << endl;
pthread_mutex_unlock(&M_cout);
}
rcdaqdataready = false;
if (debugRcdaqEventReadoutLock) {
pthread_mutex_lock(&M_cout);
cout << "LINE " << __LINE__ << " set rcdaqdataready FALSE UNLOCK DataReadyReset" << endl;
pthread_mutex_unlock(&M_cout);
}
pthread_mutex_unlock( &DataReadyReset ); // enable trigger ready test
ievent++;
if (debugEventReadout)
{
cout << "LINE1 " << __LINE__ << " got the last frame event # " << ievent << endl;
}
if(nevents != 0)
{
if(ievent > nevents)
{
exitRequested = true;
}
}
if (debugEventReadout)
{
// print out procress
if(ievent < 5)
{
cout << " SEB Readback Events Written = " << ievent << ", Event Number = " << event_number+event_offset << endl;
}
else
{
if(ievent%100 == 0) cout << " SEB Readback Events Written = " << ievent << ", Event Number = " << event_number+event_offset << endl;
}
if(ievent == 5) cout << " Progress will now be updated every 100 events" << endl;
}
}
iframe = 0;
}
} // nFrameWords - ioffset < DMAprogress
else // frame is not fully DMAed
{
// put remaining frame fragment into array
UINT32 frag_begin = ioffset;
UINT32 frag_size = (pwords[idma] - pframe); // gives number of words, not bytes
for(unsigned int iword = 0; iword < frag_size; iword++)
{
frameWords[iword+frag_begin] = *pframe;
pframe++;
ioffset++;
}
} // frame not fully DMAed
if(exitRequested)
{
cout << __LINE__ << " exitRequested is TRUE break " << endl;
//printWords = true;
break;
}
} // pframe < pwords[idma]
} // writeFrames
//---FINISHED PARSING DATA STREAM------------------------
// go back to waiting for new data
bytesleftold = bytesleftnew;
receivedbytes = 0;
receivedwords = 0;
} // bytesleftnew != bytesleftold
if(failDetected) break;
// stress hold-busy chain during swap
//cout << "----pause started (dma swap)----" << endl;
//sleep(2);
//cout << "----pause complete (dma swap)----" << endl;
} // not first pass
// continue with first pass
// round robin on DMA buffers
idma++;
if(idma == nbuffers)
{
idma = 0;
}
if(debugDma)
cout << "jseb2: end firstpass check idma = " << idma << endl;
// Reset Pointer (needed?)
//pwords[idma] = static_cast<UINT32*>(pbuff[idma]);
if(!firstpass)
{
// update counter for bytes into optics
status = jseb2->GetReceiverStatusWord(1);
}
if (debugDma) {
cout << "LINE " << __LINE__ << " start new stream nbytes = " << nbytes << " on jseb2 port " << rcv << endl;
}
// start new receive counter & DMA immediately
jseb2->SetReceiveLength(rcv,nbytes); // this way we don't kill the FIFO data
jseb2->Receive(rcv,nbytes,pDma[idma]); // start new data stream
DMAcomplete = false;
if (debugDma) {
cout << "LINE " << __LINE__ << " FIRST RECEIVE DONE firstpass = " << firstpass << endl;
}
// Reset pointers
pwords[idma] = static_cast<UINT32*>(pbuff[idma]);
pframe = pwords[idma];
// now calculate byte counts
if(!firstpass)
{
bytesleftrcvr = (status & 0x0FFFFFFF);
bytesThroughOptics += (nbytes - bytesleftrcvr);
if (debugDma)
{
cout << "LINE " << __LINE__<< " not FIRST PASS " << endl;
cout << "LINE " << __LINE__<< " bytesThroughOptics = " << bytesThroughOptics << " bytesThroughDMA = " << bytesThroughDMA << endl;
}
bytesLeftOnJSEB2 += bytesThroughOptics - bytesThroughDMA;
bytesThroughOptics = 0;
bytesThroughDMA = 0;
if (debugDma)
{
cout << "LINE " << __LINE__<< " not FIRST PASS " << endl;
cout << "LINE " << __LINE__<< " bytesleftonJSEB2 = " << bytesLeftOnJSEB2 << endl;
} if (debugDma) {
cout << "LINE " << __LINE__ << " start new stream nbytes = " << nbytes << endl;
}
} // not firstpass
// Remaining DMA length
bytesleftold = nbytes; // 4 * 1024 * 1024 = 4194304
bytesleftnew = nbytes;
receivedbytes = bytesleftold-bytesleftnew;
receivedwords = receivedbytes/sizeof(UINT32);
if (debugDma)
{
cout << "LINE " << __LINE__<< "allocate new DMA buffer size = " << nbytes << endl;
}
// New DMA has begun (tell user to start data stream)
if (debugDma)
{
cout << endl;
cout << " |==========================================================================|" << endl;
cout << " | New DMA is running on Buffer #"<< idma << " and JSEB2 is ready to receive words |" << endl;
cout << " |==========================================================================|" << endl;
}
bool bufferOkay = true;
unsigned int iprint = 0;
while(bufferOkay)
{
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " Wait for more data on bufferOkay " << endl;
}
// Wait for data
bool waitingOnData = true;
while(waitingOnData)
{
WDC_Sleep(100, WDC_SLEEP_BUSY);
bytesleftnew = jseb2->GetBytesLeftToDMA();
if(bytesleftnew != bytesleftold)
{
waitingOnData = false;
}
if(exitRequested)
{
//printWords = true;
break;
}
} // while(waitingOnData)
receivedbytes = bytesleftold-bytesleftnew;
receivedwords = receivedbytes/sizeof(UINT32);
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " got data from DMA received words = " << receivedwords << endl;
cout << "LINE " << __LINE__ << " NOW BEGIN PARSING DATA " << endl;
}
if (debugDma)
{
cout << "LINE " << __LINE__<< "got data from DMA " << endl;
cout << "LINE " << __LINE__<< " bytesleftold = " << bytesleftold << " bytesleftnew = " << bytesleftnew << " received bytes = " << receivedbytes << " received words = " << receivedwords << endl;
cout << "jseb2_seb_reader: NOW BEGIN PARSING DATA " << endl;
}
//---BEGIN PARSING DATA STREAM------------------------
// print out new words and/or advance dma progress pointer
if(printWords)
{
cout << "Received words = " << receivedwords << endl;
cout << " (#" << idma << ") ";
for(unsigned int iword = 1; iword < receivedwords+1; iword++)
{
UINT32 u32Data = *pwords[idma];
pwords[idma]++;
cout.width(8); cout.fill('0'); cout << hex << u32Data << dec << " ";
if(iword%8 == 0)
{
cout << endl;
if(iword < receivedwords) cout << " (#" << idma << ") ";
}
}
iprint++;
}
else // just advance pointer
{
for(unsigned int iword = 1; iword < receivedwords+1; iword++)
{
pwords[idma]++;
}
iprint++;
}
// parse new data for frames
if(printFrames || writeFrames)
{
if (debugDma ) {
cout << "LINE " << __LINE__<< " check for new frame word (pframe < pwords) pframe= "<< pframe << " pwords["<< idma<<"] = " << pwords[idma] << endl;
}
// check for new frame word...
while(pframe < pwords[idma])
{
// copy out length of new frame
if(nFrameWords == 0)
{
nFrameWords = *pframe; // first word is the frame size
}
// see if this frame has been fully DMAed
UINT32 DMAprogress = pwords[idma] - pframe ; // number of words
if (debugEventReadout)
{
cout << "LINE " << __LINE__<< " DMAprogress ( #words ) word pointer - frame pointer = " << DMAprogress << endl;
cout << "LINE " << __LINE__<< " Length of frame ( #words ) nFrameWords = " << nFrameWords << endl;
cout << "LINE " << __LINE__<< " Now check if nFrameWords - ioffset of " << ioffset << " is < DMA'd words if not get more data " << endl;
}
if (debugDma)
{
cout << "LINE " << __LINE__<< " iframe ( 0 if first frame ) = " << iframe << " nFrameWords = " << nFrameWords << " ioffset = " << ioffset << " nFrameWords - ioffset = " << nFrameWords - ioffset << endl;
cout << " length of new frame is first word " << hex << *pframe << dec << endl;
}
if(nFrameWords - ioffset < DMAprogress)
{
if (debugDma)
{
cout << "LINE " << __LINE__<< " nFrameWords is less than # DMA'd words - so have complete frame" << endl;
cout << "LINE " << __LINE__<< " COPY frame to frameWords array - increment pframe " << endl;
}
if (debugRcdaqEventReadout)
{
cout << "LINE " << __LINE__ << " nFrameWords = " << nFrameWords << " ioffset = " << ioffset<< endl;
cout << "LINE " << __LINE__ << " write Frame header to frameWords start at "<< ioffset << endl;
}
// put the remainder of this frame into array
for(unsigned int iword = ioffset; iword < nFrameWords; iword++)
{
frameWords[iword] = *pframe;
pframe++;
}
// the first frame will be an empty partitioner frame
if(iframe == 0)
{
if(writeFrames)
{
filebuffer->StartEvent();
//pbeginframe = filebuffer->GetBufferPointer();
}
if (debugRcdaqEventReadout)
{
cout << "LINE " << __LINE__<< " write FIRST frame WROTE START EVENT - added event header " << endl;
// cout << "LINE " << __LINE__<< " SET BEGINFRAME POINTER TO " << pbeginframe << endl;
}
// RCDAQ
rcdaqdataready = false; // signal data is available to rcdaq
if (debugRcdaqEventReadoutLock) {
pthread_mutex_lock(&M_cout);
cout << "LINE " << __LINE__ << " Start New Event set rcdaqdataready FALSE" << endl;
pthread_mutex_unlock(&M_cout);
}
unsigned int oldFramesPerEvent = nFramesPerEvent;
nFramesPerEvent = (frameWords[3] >> 16);
if(nFramesPerEvent == 0) nFramesPerEvent = oldFramesPerEvent;
if(printFrames)
{
cout << endl;
cout << " sync frame " << endl;
cout << " PART3 Frame: ";
for(unsigned int iword = 0; iword < 8; iword++)
{
cout.width(8); cout.fill('0'); cout << hex << frameWords[iword] << dec << " ";
}
cout << endl;
}
if (debugDma)
{
cout << "LINE " << __LINE__<< " check sync frame ( should be 0x8 ) = " << frameWords[0] << endl;
}
if(frameWords[0] != 0x8)
{
cout << "Sync frame has incorrect length... frameWords[0] = 0x " << hex << frameWords[0] << dec << endl;
exitRequested = true; printWords = true;
failDetected = true;
break;
}
if(frameWords[1] != 0xFFFFFF00)
{
cout << "Corrupt or missing frame marker should be 0xFFFFFF00" << endl;
failDetected = true;
exitRequested = true; printWords = true;
break;
}
} // iframie = 0
// additional frames will be from each dcm2 board
else
{ // NOT FIRST FRAME
if (debugRcdaqEventReadout)
cout << "LINE " << __LINE__ << " got frame " << iframe << " NOT the first frame " << endl;
// coding around Chi's extra sync frame appearances
if(frameWords[0] != 0x8)
{
if(printFrames)
{
if (debugRcdaqEventReadout)
{
cout << "LINE " << __LINE__<< " Dcm2 Frame " << endl;
}
cout << " DCM2 Frame:_ ";
for(unsigned int iword = 0; iword < 8; iword++)
{
cout.width(8); cout.fill('0'); cout << hex << frameWords[iword] << dec << " ";
}
cout << "... ";
cout.width(8); cout.fill('0'); cout << hex << frameWords[nFrameWords-1] << dec;
cout << endl;
}
if(frameWords[1] != 0xFFFFFF00)
{
cout << "Corrupt or missing frame marker" << endl;
failDetected = true;
exitRequested = true; printWords = true;
break;
}
if(writeFrames)
{
// get event number
UINT32 prev_event_number = event_number;
event_number = frameWords[6];
if(event_number < prev_event_number)
{
event_offset += prev_event_number;
if(event_number == 0) event_offset++;
}
// set event number
filebuffer->SetEventNumber(event_number+event_offset);
if (debugRcdaqEventReadoutCount)
{
pthread_mutex_lock(&M_cout);
cout << "LINE " << __LINE__ << " set file buffer event number = " << event_number + event_offset<< endl;
pthread_mutex_unlock(&M_cout);
}
if (debugRcdaqEventReadout)
{
cout << "LINE " << __LINE__<< " CopyFrameIntoBuffer words " << nFrameWords << " event# " << event_number+event_offset << endl;
}
// set begin frame where DCM2 frame is written
pbeginframe = filebuffer->GetBufferPointer();
// add frame to file buffer
filebuffer->CopyFrameIntoBuffer(nFrameWords,pframeWords);
rcdaqEventNumber = event_number + event_offset;
if (debugRcdaqEventReadoutCount)
cout << "LINE " << __LINE__ << " copy event to buffer eventcount = " << rcdaqEventNumber << " event words copied to buffer = " << nFrameWords << endl;
} // writeFrames
} // frameWords[0] != 0x8 ; error condition
else
{
cout << "---Skipping spurious sync frame---" << endl;
iframe--;
}
} // not first frame
ioffset = 0;
nFrameWords = 0;
iframe++;
if (debugEventReadout)
{
cout << "LINE " << __LINE__<< " check if this is last frame iframe = " << iframe << " nFramesPerEvent = " << nFramesPerEvent << endl;
}
// end the event when all frames are collected
if(iframe > nFramesPerEvent)
{
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " got the last frame event " << ievent << " iframe " << iframe << " nFramesPerEvent = " << nFramesPerEvent << endl;
}
if(writeFrames)
{
filebuffer->EndEvent();
filebuffer->CheckBufferSpace();
if (debugRcdaqEventReadoutCount)
{
cout << "LINE " << __LINE__ << " WROTE END EVENT " << ievent << " requested events = " << nevents << endl;
}
// RCDAQ+
//pendframe = pframe - sizeof(UINT32);
//rcdaqEventNumber = ievent;
// AT END OF EVENT GET A POINTER TO THE buffer in the data file
//pbeginframe = filebuffer->GetBufferPointer();
//rcdaqEventNumber = *(pbeginframe + 2); // stored event number
storedeventsize = *(pbeginframe); // first word is event size
rcdaqEventNumber = event_number;
if (debugRcdaqEventReadoutCount) {
//cout << "LINE " << __LINE__ << " STORED EVENT DATA size = " << storedeventsize << " event number " << rcdaqEventNumber << endl;
//cout << "\t EVENT SIZE = " << storedeventsize << endl;
cout << "LINE " << __LINE__ << "\t End EVENT NUMBER = " << rcdaqEventNumber << " ievent = " << ievent << endl;
}
// copy the event data to the tmp event buffer
// tmpeventbuffer stores only 1 event
for (int itmp = 0; itmp < storedeventsize ; itmp++ )
{
// 11/16/17 try offset of 16 to exclude dcm2 header
// 11/17/2017 ; try skipping 12 8 word frame header + 4 word buffer header
tmpeventbuffer[itmp] = *(pbeginframe + (itmp) +8 ); // add 8 to skip frame header
if (debugRcdaqEventReadout)
{
if (itmp < 16 )
cout << "\t tbuff["<<itmp<<"]= " << hex << tmpeventbuffer[itmp] << dec << endl;
}
}
/*
// HERE PUT DATA in structure to be retrieved by rcdaq
if (rcdaqEventNumber >= 0 && rcdaqEventNumber < 1000) {
if (debugEventReadout)
cout << "LINE " << __LINE__ << " --STORE DATA IN stored data buffer-- " << endl;
storedeventpointers[rcdaqEventNumber].pbeginframe = pbeginframe;
//*(storedeventpointers[rcdaqEventNumber].pendframe) = *pendframe;
storedeventpointers[rcdaqEventNumber].eventNumber = rcdaqEventNumber;
}
*/
rcdaqdataready = true; // signal data is available to rcdaq
if (debugRcdaqEventReadoutLock) {
pthread_mutex_lock(&M_cout);
cout << "LINE " << __LINE__ << " set rcdaqdataready TRUE" << endl;
pthread_mutex_unlock(&M_cout);
}
// this implements the readout of 1 event only at a time
if (debugRcdaqEventReadoutLock) {
pthread_mutex_lock(&M_cout);
cout << "LINE " << __LINE__ << " jsebreader: WAIT on DataReadoutDone for RCDAQ data read completion " << endl;
pthread_mutex_unlock(&M_cout);
}
// wait for the data to be read out by rcdaq.EventLoop code
pthread_mutex_lock( &DataReadoutDone );
if (debugRcdaqEventReadoutLock) {
pthread_mutex_lock(&M_cout);
cout << "LINE " << __LINE__ << " jsebreader: GOT LOCK on DataReadoutDone " << endl;
pthread_mutex_unlock(&M_cout);
}
rcdaqdataready = false;
if (debugRcdaqEventReadoutLock) {
pthread_mutex_lock(&M_cout);
cout << "LINE " << __LINE__ << " set rcdaqdataready FALSE UNLOCKED DataReadyReset" << endl;
pthread_mutex_unlock(&M_cout);
}
pthread_mutex_unlock( &DataReadyReset ); // enable trigger ready test
ievent++;
if(nevents != 0)
{
if(ievent > nevents)
{
exitRequested = true;
}
}
if (debugEventReadout)
{
// print out procress
if(ievent < 5)
{
cout << " SEB Readback Events Written = " << ievent << ", Event Number = " << event_number+event_offset << endl;
}
else
{
if(ievent%1000 == 0) cout << " SEB Readback Events Written = " << ievent << ", Event Number = " << event_number+event_offset << endl;
}
if(ievent == 5) cout << " Progress will now be updated every 100 events" << endl;
} // debug printout
} // writeFrames
iframe = 0;
} // iframe > nFramesPerEvent
} // nFrameWords < DMAProgress
else // frame is not fully DMAed
{
if (debugEventReadout)
cout << "LINE " << __LINE__ << " Frame NOT fully formed - calc ioffset " << endl;
// put remaining frame fragment into array
UINT32 frag_begin = ioffset;
//UINT32 frag_size = (pwords[idma] - pframe); // gives number of words, not bytes orig
UINT32 frag_size = (pwords[idma] - pframe); // gives number of words, not bytes
if (debugDma) {
cout << "jseb2: frame not fully DMAed " << endl;
cout << "jseb2: dma fragment size ( whats read ) = " << frag_size << endl;
cout << "jseb2: inc frame pointer by " << frag_size << " words " << endl;
cout << " - puts frame pointer to end of frame data " << endl;
}
for(unsigned int iword = 0; iword < frag_size; iword++)
{
frameWords[iword+frag_begin] = *pframe;
pframe++;
ioffset++;
}
if (debugEventReadout)
cout << "LINE " << __LINE__ << " Frame NOT fully formed ioffset = "<< ioffset << endl;
} // not fully dma's frame copied
if(exitRequested)
{
cout << __LINE__ <<" jsebreader: break on exitRequested " << endl;
//printWords = true;
break;
}
} // pframe < pwords[idma]
} // if writeFrames
//---FINISHED PARSING DATA STREAM------------------------
if(debugEventReadout)
cout << "LINE " << __LINE__ << " Done PARSING DATA STREAM " << endl;
// reset counters
bytesleftold = bytesleftnew;
receivedbytes = 0;
receivedwords = 0;
// swap when DMA is complete
if(jseb2->HasDMACompleted())
{
if (debugEventReadout) {
cout << "LINE " << __LINE__ << " : DMA COMPLETED " << endl;
}
if(jseb2->GetBytesLeftToDMA() == 0)
{
//cout << "DMA Complete bit set, NO words left to DMA - set bufferok to false" << endl;
bufferOkay = false;
DMAcomplete = true;
}
else
{
//cout << "Complete bit set, but words left to DMA" << endl;
jseb2->SetFree();
return;
}
} // DMA complete
if (debugDma) {
cout << "jseb2: first pass done bytesleftold = " << bytesleftold << " bytesleftnew = "<< bytesleftnew << endl;
}
// cycle more often for testing...
//if(bytesleftnew < 0.25*nbytes) // if less than 25% space remains switch buffers
// {
// bufferOkay = false;
// }
// cycle more often for testing...
//if(iprint > 5)
// {
// iprint = 0;
// bufferOkay = false;
// }
firstpass = false;
if (forcexit)
{
cout << __FILE__ << " " << __LINE__ << " Force exitRequested = true" << endl;
exitRequested = true;
}
if(exitRequested)
{
cout << __LINE__ <<"jsebreader: break on exitRequested " << endl;
//printWords = true;
break;
}
if (debugEventReadout) {
cout << "LINE " << __LINE__ << " end bufferokay loop " << endl;
}
} // bufferokay
if(exitRequested)
{
//printWords = true;
break;
}
} // while true
//----------------//
// Stop final DMA //
//----------------//
// record progress on previous DMA
bytesleftnew = jseb2->GetBytesLeftToDMA();
if (debugRcdaqEventReadoutCount)
{
cout << "LINE " << __LINE__ << " stop final DMA bytesleftnew = " << bytesleftnew << " bytesleftold = " << bytesleftold << " Abort DMA " << endl;
}
// abort the previous DMA
jseb2->AbortDMA();
// sync the processor cache to system memory
WDC_DMASyncIo(pDma[idma]);
#ifdef GETFINALDMA
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " DMA SyncIo COMPLETE " << endl;
}
// print any additional DMAed words since last print...
if(bytesleftnew != bytesleftold)
{
receivedbytes = bytesleftold-bytesleftnew;
receivedwords = receivedbytes/sizeof(UINT32);
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " ADDITIONAL DMAed words bytes left receivedwords = " << receivedwords << endl;
}
// print out new words...
if(printWords)
{
cout << " (#" << idma << ") ";
for(unsigned int iword = 1; iword < receivedwords+1; iword++)
{
UINT32 u32Data = *pwords[idma]++;
cout.width(8); cout.fill('0'); cout << hex << u32Data << dec << " ";
if(iword%8 == 0)
{
cout << endl;
if(iword < receivedwords) cout << " (#" << idma << ") ";
}
}
}
else
{
for(unsigned int iword = 1; iword < receivedwords+1; iword++)
{
*pwords[idma]++;
}
}
// check for new frame word...
if(printFrames || writeFrames)
{
while(pframe < pwords[idma])
{
if(nFrameWords == 0)
{
nFrameWords = *(pframe);
}
if (debugDma) {
cout << "jseb2: new frame found " << endl;
}
// see if frame has been fully DMAed
if(pframe + nFrameWords - ioffset < pwords[idma])
{
// put frame into array
for(unsigned int iword = ioffset; iword < nFrameWords; iword++)
{
frameWords[iword] = *(pframe++);
}
// the first frame will be an empty partitioner frame
if(iframe == 0)
{
if(writeFrames)
{
pbeginframe = filebuffer->GetBufferPointer();
filebuffer->StartEvent();
}
//pbeginframe = pframe - sizeof(UINT32);
rcdaqdataready = false; // signal data is available to rcdaq
if (debugRcdaqEventReadoutCount) {
pthread_mutex_lock(&M_cout);
cout << "LINE " << __LINE__ << " set rcdaqdataready FALSE" << endl;
pthread_mutex_unlock(&M_cout);
}
unsigned int oldFramesPerEvent = nFramesPerEvent;
nFramesPerEvent = (frameWords[3] >> 16);
if(nFramesPerEvent == 0) nFramesPerEvent = oldFramesPerEvent;
if(printFrames)
{
cout << " PART3 Frame0: ";
for(unsigned int iword = 0; iword < 8; iword++)
{
cout.width(8); cout.fill('0'); cout << hex << frameWords[iword] << dec << " ";
}
cout << endl;
} // printFrames
if(frameWords[0] != 0x8)
{
cout << "Sync frame has incorrect length" << endl;
exitRequested = true;
failDetected = true;
break;
}
if(frameWords[1] != 0xFFFFFF00)
{
cout << "Corrupt or missing frame marker" << endl;
exitRequested = true; printWords = true;
failDetected = true;
break;
}
} // iframe == 0
// additional frames will be frome each dcm2 board
else
{
if(printFrames)
{
cout << " DCM2 Frame:: ";
for(unsigned int iword = 0; iword < 8; iword++)
{
cout.width(8); cout.fill('0'); cout << hex << frameWords[iword] << dec << " ";
}
cout << "... ";
cout.width(8); cout.fill('0'); cout << hex << frameWords[nFrameWords-1] << dec << endl;
} // printFrames
if(frameWords[1] != 0xFFFFFF00)
{
cout << "Corrupt or missing frame marker" << endl;
failDetected = true;
exitRequested = true; printWords = true;
break;
}
if(writeFrames)
{
// get event number
UINT32 prev_event_number = event_number;
event_number = frameWords[6];
if(event_number < prev_event_number)
{
event_offset += prev_event_number;
if(event_number == 0) event_offset++;
}
// set event number
filebuffer->SetEventNumber(event_number+event_offset);
if (debugRcdaqEventReadoutCount)
cout << "LINE " << __LINE__ << " set buffer event number = " << event_number + event_offset<< endl;
// add frame to file buffer
filebuffer->CopyFrameIntoBuffer(nFrameWords,pframeWords);
}
}
ioffset = 0;
nFrameWords = 0;
iframe++;
// end the event when all frames are collected
if(iframe > nFramesPerEvent)
{
if(writeFrames)
{
filebuffer->EndEvent();
filebuffer->CheckBufferSpace();
// RCDAQ
//pendframe = pframe - sizeof(UINT32);
//pbeginframe = filebuffer->GetBufferPointer();
rcdaqEventNumber = event_number+event_offset; // event number
storedeventsize = *(pbeginframe); // first word is event size
if (debugEventReadoutCount) {
cout << "LINE " << __LINE__ << " STORED EVENT DATA " << endl;
cout << "\t EVENT SIZE = " << storedeventsize << endl;
cout << "\t rcdaq EVENT NUMBER = " << rcdaqEventNumber << " ievent = " << ievent << endl;
}
}
iframe = 0;
}
}
else // frame is not fully DMAed
{
// put remaining frame fragment into array
UINT32 frame_write = ioffset;
UINT32 frame_end = pwords[idma] - pframe;
for(unsigned int iword = frame_write; iword < frame_end; iword++)
{
frameWords[iword] = *(pframe++);
ioffset++;
}
}
if(exitRequested)
{
//printWords = true;
break;
}
}
} // printFrames || writeFrames
// go back to waiting for new data
bytesleftold = bytesleftnew;
receivedbytes = 0;
receivedwords = 0;
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " wait for more data " << endl;
}
} // bytesleftnew != bytesleftold
///#ifdef GETFINALDMA
if (debugDma)
{
cout << "jseb2: bytesThroughOptics = " << bytesThroughOptics << " nbytes " << nbytes << " bytesleftrcvr " << bytesleftrcvr << endl;
cout << "jseb2: bytesleftonJSEB2 = " << bytesLeftOnJSEB2 << endl;
}
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " get JSEB Receiver Status " << endl;
}
// update counter for bytes into optics
status = jseb2->GetReceiverStatusWord(1);
bytesleftrcvr = (status & 0x0FFFFFFF);
bytesThroughOptics += (nbytes - bytesleftrcvr);
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " bytesleftrcvr " << bytesleftrcvr << " status = " << hex << status << dec << endl;
cout << "jseb2: bytesThroughOptics = " << bytesThroughOptics << endl;
}
// update counter for bytes out on DMA
bytesThroughDMA += (nbytes - bytesleftnew);
if (debugDma)
{
cout << endl;
cout << " |==========================================================================|" << endl;
cout << " | Final DMA complete, spilling out any remaining words stored on FIFO |" << endl;
cout << " |==========================================================================|" << endl;
}
//cout << " Currently ignoring final event due to FIFO extraction issue" << endl;
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " Final DMA bytesleftonJSEB2 = " << bytesLeftOnJSEB2 << " bytesThroughOptics = " << bytesThroughOptics << " bytesThroughDMA = " << bytesThroughDMA << endl;
}
UINT64 lastbytesThroughDMA = bytesThroughDMA;
bytesLeftOnJSEB2 += bytesThroughOptics - bytesThroughDMA;
bytesThroughOptics = 0;
bytesThroughDMA = 0;
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " bytesleftonJSEB2 = " << bytesLeftOnJSEB2 << " lastbytesThroughDMA = " << lastbytesThroughDMA << " bytesleftrcvr = " << bytesleftrcvr << " bytesleftnew = " << bytesleftnew << endl;
}
// ejd 11/21/16 should this be ( bytesLeftOnJSEB2 > 0 ) ; here bytesleftonJSEB2 is < 0
//if(bytesLeftOnJSEB2 != 0)
if(bytesLeftOnJSEB2 > 0 && bytesLeftOnJSEB2 < lastbytesThroughDMA)
{
// storage for longs on FIFO
UINT64 longsTRX1[1025] = {0xbad};
UINT64 *plongsTRX1 = (UINT64*)&longsTRX1;
UINT64 longsTRX2[1025] = {0xbad};
UINT64 *plongsTRX2 = (UINT64*)&longsTRX2;
// storage for words on FIFO
unsigned int nwordsOnJSEB2 = bytesLeftOnJSEB2/4;
UINT32 wordsOnJSEB2[2049] = {0xbad};
unsigned int nlongsOnJSEB2 = nwordsOnJSEB2/2;
if(nwordsOnJSEB2%2 != 0)
{
nlongsOnJSEB2++;
}
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " read back FIFO nlongsOnJSEB2 = " << nlongsOnJSEB2 << endl;
}
// Read back FIFO
jseb2->SetUseDMA(false);
jseb2->Read(Dcm2_JSEB2::RCV_ONE,nlongsOnJSEB2,plongsTRX1);
jseb2->Read(Dcm2_JSEB2::RCV_TWO,nlongsOnJSEB2,plongsTRX2);
jseb2->SetUseDMA(true);
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " FIFO readback complete nlongs found = " << nlongsOnJSEB2 << endl;
}
for(unsigned int ilong = 0; ilong < nlongsOnJSEB2; ilong++)
{
//cout << "TRX1 & TRX2: ";
//cout.width(16); cout.fill('0'); cout << hex << longsTRX1[ilong] << dec << " ";
//cout.width(16); cout.fill('0'); cout << hex << longsTRX2[ilong] << dec << endl;
UINT64 byteA = ((longsTRX1[ilong] & 0x0000FFFF00000000) >> 32);
UINT64 byteB = (longsTRX1[ilong] & 0x000000000000FFFF);
UINT64 byteC = ((longsTRX2[ilong] & 0xFFFF000000000000) >> 48);
UINT64 byteD = ((longsTRX2[ilong] & 0x0000FFFF00000000) >> 32);
UINT32 word_odd = ((byteD << 16) + byteB);
UINT32 word_even = ((byteC << 16) + byteA);
wordsOnJSEB2[2*ilong] = word_odd;
wordsOnJSEB2[2*ilong+1] = word_even;
}
// print out new words...
if(printWords)
{
cout << " (--) ";
for(unsigned int iword = 1; iword < nwordsOnJSEB2+1; iword++)
{
cout.width(8); cout.fill('0'); cout << hex << wordsOnJSEB2[iword-1] << dec << " ";
if(iword%8 == 0)
{
cout << endl;
if(iword < nwordsOnJSEB2) cout << " (--) ";
}
}
cout << endl;
}
if(printFrames || writeFrames)
{
if (debugEventReadout)
{
cout << "LINE " << __LINE__ << " getting last frame from JSEB " << endl;
}
for(unsigned int iword = 1; iword < nwordsOnJSEB2+1; iword++)
{
frameWords[iword+ioffset-1] = wordsOnJSEB2[iword-1];
}
// the first frame will be an empty partitioner frame
if(iframe == 0)
{
if(writeFrames)
{
//filebuffer->StartEvent();
}
unsigned int oldFramesPerEvent = nFramesPerEvent;
nFramesPerEvent = (frameWords[3] >> 16);
if(nFramesPerEvent == 0) nFramesPerEvent = oldFramesPerEvent;
if (debugEventReadout) {
cout << " PART3 Final Frame: ";
for(unsigned int iword = 0; iword < 8; iword++)
{
cout.width(8); cout.fill('0'); cout << hex << frameWords[iword] << dec << " ";
}
cout << endl;
} // debugDma
/* DONT CHECK SO DATA GETS WRITTEN OUT
if(frameWords[0] != 0x8)
{
cout << "Sync frame has incorrect length" << endl;
exitRequested = true;
failDetected = true;
}
if(frameWords[1] != 0xFFFFFF00)
{
cout << "Corrupt or missing frame marker" << endl;
exitRequested = true;
failDetected = true;
}
*/
} // iframe == 0
// additional frames will be frome each dcm2 board
else
{
if (debugEventReadout && (nFrameWords > 0 ))
{
cout << " DCM2 Frame:__ ";
for(unsigned int iword = 0; iword < 8; iword++)
{
cout.width(8); cout.fill('0'); cout << hex << frameWords[iword] << dec << " ";
}
cout << "... ";
cout.width(8); cout.fill('0'); cout << hex << frameWords[nFrameWords-1] << dec << endl;
} // debug printout additional frames
/** DON'T CHECK
if(frameWords[1] != 0xFFFFFF00)
{
cout << "Corrupt or missing frame marker" << endl;
failDetected = true;
exitRequested = true;
}
**/
if(writeFrames)
{
// get event number
//filebuffer->SetEventNumber(frameWords[6]);
// add frame to file buffer
//filebuffer->CopyFrameIntoBuffer(nFrameWords,pframeWords);
}
} // iframe != 0
ioffset = 0;
nFrameWords = 0;
iframe++;
// end the event when all frames are collected
if(iframe > nFramesPerEvent)
{
if(writeFrames)
{
//filebuffer->EndEvent();
//filebuffer->CheckBufferSpace();
}
iframe = 0;
}
} // printFrames || writeFrames
} // bytesleftOnJSEB2 > 0
#endif
if(writeFrames)
{
cout << " Closing Output File" << endl;
filebuffer->ResetBuffer(); // disable disk write
if(!filebuffer->CloseFile())
{
cerr << " Failed to close file: " << filename << endl;
delete filebuffer;
return;
}
}
/*
cout << endl;
cout << " Releasing DMA buffers" << endl;
// Release DMA buffers
for(unsigned int idma = 0; idma < nbuffers; idma++)
{
WDC_DMABufUnlock(pDma[idma]);
}
*/
cout << " Readout Complete" << endl;
jseb2->SetFree();
return;
} // jseb2_seb_reader
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/ListMyCoupon.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#include <_root.app18_ButtonEntry_icon_Property.h>
#include <_root.app18_ButtonEntry_Value_Property.h>
#include <_root.ButtonEntry.h>
#include <_root.ItemListSelected.h>
#include <_root.ListMyCoupon.h>
#include <_root.ListMyCoupon.Template.h>
#include <_root.Separator.h>
#include <Fuse.Binding.h>
#include <Fuse.Node.h>
#include <Fuse.NodeGroup.h>
#include <Fuse.NodeGroupBase.h>
#include <Fuse.Reactive.BindingMode.h>
#include <Fuse.Reactive.Data.h>
#include <Fuse.Reactive.DataBinding.h>
#include <Fuse.Reactive.IExpression.h>
#include <Uno.Bool.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.Object.h>
#include <Uno.String.h>
#include <Uno.UX.FileSource.h>
#include <Uno.UX.Property.h>
#include <Uno.UX.Property-1.h>
#include <Uno.UX.Selector.h>
static uString* STRINGS[3];
static uType* TYPES[2];
namespace g{
// public partial sealed class ListMyCoupon.Template :50
// {
// static Template() :61
static void ListMyCoupon__Template__cctor__fn(uType* __type)
{
::g::Uno::UX::Selector_typeof()->Init();
ListMyCoupon__Template::__selector0_ = ::g::Uno::UX::Selector__op_Implicit(::STRINGS[0/*"icon"*/]);
ListMyCoupon__Template::__selector1_ = ::g::Uno::UX::Selector__op_Implicit(::STRINGS[1/*"Value"*/]);
}
static void ListMyCoupon__Template_build(uType* type)
{
::STRINGS[0] = uString::Const("icon");
::STRINGS[1] = uString::Const("Value");
::STRINGS[2] = uString::Const("typeCoupon");
::TYPES[0] = ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL);
::TYPES[1] = ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL);
type->SetFields(2,
::g::ListMyCoupon_typeof(), offsetof(ListMyCoupon__Template, __parent1), uFieldFlagsWeak,
::g::ListMyCoupon_typeof(), offsetof(ListMyCoupon__Template, __parentInstance1), uFieldFlagsWeak,
::g::Uno::UX::Property1_typeof()->MakeType(::g::Uno::UX::FileSource_typeof(), NULL), offsetof(ListMyCoupon__Template, temp_icon_inst), 0,
::g::Uno::UX::Property1_typeof()->MakeType(::g::Uno::String_typeof(), NULL), offsetof(ListMyCoupon__Template, temp_Value_inst), 0,
::g::Uno::UX::Selector_typeof(), (uintptr_t)&ListMyCoupon__Template::__selector0_, uFieldFlagsStatic,
::g::Uno::UX::Selector_typeof(), (uintptr_t)&ListMyCoupon__Template::__selector1_, uFieldFlagsStatic);
}
::g::Uno::UX::Template_type* ListMyCoupon__Template_typeof()
{
static uSStrong< ::g::Uno::UX::Template_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.BaseDefinition = ::g::Uno::UX::Template_typeof();
options.FieldCount = 8;
options.ObjectSize = sizeof(ListMyCoupon__Template);
options.TypeSize = sizeof(::g::Uno::UX::Template_type);
type = (::g::Uno::UX::Template_type*)uClassType::New("ListMyCoupon.Template", options);
type->fp_build_ = ListMyCoupon__Template_build;
type->fp_cctor_ = ListMyCoupon__Template__cctor__fn;
type->fp_New1 = (void(*)(::g::Uno::UX::Template*, uObject**))ListMyCoupon__Template__New1_fn;
return type;
}
// public Template(ListMyCoupon parent, ListMyCoupon parentInstance) :54
void ListMyCoupon__Template__ctor_1_fn(ListMyCoupon__Template* __this, ::g::ListMyCoupon* parent, ::g::ListMyCoupon* parentInstance)
{
__this->ctor_1(parent, parentInstance);
}
// public override sealed object New() :64
void ListMyCoupon__Template__New1_fn(ListMyCoupon__Template* __this, uObject** __retval)
{
::g::Fuse::NodeGroup* __self1 = ::g::Fuse::NodeGroup::New2();
::g::ItemListSelected* temp = ::g::ItemListSelected::New6();
__this->temp_icon_inst = ::g::app18_ButtonEntry_icon_Property::New1(temp, ListMyCoupon__Template::__selector0_);
::g::Fuse::Reactive::Data* temp1 = ::g::Fuse::Reactive::Data::New1(::STRINGS[0/*"icon"*/]);
__this->temp_Value_inst = ::g::app18_ButtonEntry_Value_Property::New1(temp, ListMyCoupon__Template::__selector1_);
::g::Fuse::Reactive::Data* temp2 = ::g::Fuse::Reactive::Data::New1(::STRINGS[2/*"typeCoupon"*/]);
::g::Fuse::Reactive::DataBinding* temp3 = ::g::Fuse::Reactive::DataBinding::New1(__this->temp_icon_inst, (uObject*)temp1, 3);
::g::Fuse::Reactive::DataBinding* temp4 = ::g::Fuse::Reactive::DataBinding::New1(__this->temp_Value_inst, (uObject*)temp2, 3);
::g::Separator* temp5 = ::g::Separator::New4();
::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp->Bindings()), ::TYPES[0/*Uno.Collections.ICollection<Fuse.Binding>*/]), temp3);
::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp->Bindings()), ::TYPES[0/*Uno.Collections.ICollection<Fuse.Binding>*/]), temp4);
::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(__self1->Nodes()), ::TYPES[1/*Uno.Collections.ICollection<Fuse.Node>*/]), temp);
::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(__self1->Nodes()), ::TYPES[1/*Uno.Collections.ICollection<Fuse.Node>*/]), temp5);
return *__retval = __self1, void();
}
// public Template New(ListMyCoupon parent, ListMyCoupon parentInstance) :54
void ListMyCoupon__Template__New2_fn(::g::ListMyCoupon* parent, ::g::ListMyCoupon* parentInstance, ListMyCoupon__Template** __retval)
{
*__retval = ListMyCoupon__Template::New2(parent, parentInstance);
}
::g::Uno::UX::Selector ListMyCoupon__Template::__selector0_;
::g::Uno::UX::Selector ListMyCoupon__Template::__selector1_;
// public Template(ListMyCoupon parent, ListMyCoupon parentInstance) [instance] :54
void ListMyCoupon__Template::ctor_1(::g::ListMyCoupon* parent, ::g::ListMyCoupon* parentInstance)
{
ctor_(NULL, false);
__parent1 = parent;
__parentInstance1 = parentInstance;
}
// public Template New(ListMyCoupon parent, ListMyCoupon parentInstance) [static] :54
ListMyCoupon__Template* ListMyCoupon__Template::New2(::g::ListMyCoupon* parent, ::g::ListMyCoupon* parentInstance)
{
ListMyCoupon__Template* obj1 = (ListMyCoupon__Template*)uNew(ListMyCoupon__Template_typeof());
obj1->ctor_1(parent, parentInstance);
return obj1;
}
// }
} // ::g
|
// Name : Angel E Hernandez
// Date : April 17
// CIS 1202.800
// Project name : Inheritance
#pragma once
#ifndef VEHICLE_H
#define VEHICLE_H
#include <string>
using namespace std;
// The vehicle class holds general data
class Vehicle
{
private:
string manufacturer;
int year;
public:
// defaul constructor
Vehicle()
{
manufacturer = " ";
year = 0;
}
// Constructor
Vehicle(string vehicleManf, int vehicleYear)
{
manufacturer = vehicleManf;
year = vehicleYear;
}
// getters
string getManufacturer() const
{
return manufacturer;
}
int getYear()
{
return year;
}
// display info
void displayInfo(); // define in vehicle.cpp
};
#endif
|
//
// Created by 송지원 on 2020/07/04.
//
#include <iostream>
#include <algorithm>
using namespace std;
int arr[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
void swap(int a, int b) {
int temp;
int diff = b-a;
for (int i=0; i<(diff+1)/2; i++) {
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
a++, b--;
}
}
int main() {
int a, b;
for (int i=0; i<10; i++) {
cin >> a >> b;
swap(a-1, b-1);
}
for (auto x : arr){
cout << x << " ";
}
return 0;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
typedef struct node {
int val;
struct node * next;
} node_t;
node *head, *tail;
void print_list(node_t *head) {
node_t *current = head;
while (current != NULL) {
printf("%d\t", current->val);
current = current->next;
}
printf("\n");
}
//int pop(node_t ** head);
int remove_by_value(node_t **head, int val);
void insert_max_elem(node **head, int x);
void sort(node **head);
//void delete_list(node_t *head) {
// node_t *current = head,
// *next = head;
//
// while (current) {
// next = current->next;
// free(current);
// current = next;
// }
//}
void createnode(int value, node **head) {
node *temp = new node;
temp->val=value;
temp->next=NULL;
if (*head==NULL) {
*head=temp;
tail=temp;
temp=NULL;
} else {
tail->next=temp;
tail=temp;
}
}
//
//void change_position(node *first_elem, node *first_prev, node *second_elem, node *second_prev) {
// if (first_elem == second_elem) {
// return;
// }
// node *tmp = first_elem;
// first_elem->next = second_elem->next;
// second_elem->next = tmp->next;
//
// first_prev->next = second_elem;
// second_prev->next = first_elem;
//}
void swap(struct node **Node, int x, int y);
int main(void) {
srand (time(NULL));
int val;
int list_length = 10;
int arr[9] = {63, 98, 13, 48, 39, 75, 49, 41, 19};
for(int i = 1; i < list_length; i++) {
// val = rand() % 100 + 1;
val = arr[i-1];
createnode(val, &head);
}
printf("Print list: \n");
print_list(head);
printf("\n *********** \n");
//
int min_val, max_val;
min_val = max_val = head->val;
node *current = head;
while (current) {
if (current->val < min_val)
min_val = current->val;
if (current->val > max_val)
max_val = current->val;
current = current->next;
}
printf("Min: %d \n", min_val);
printf("Max: %d \n", max_val);
swap(&head, min_val, max_val);
print_list(head);
printf("********** Remove 10 \n");
remove_by_value(&head, 9);
print_list(head);
printf("********** Find next max and insert max \n");
int some_max = 4;
insert_max_elem(&head, some_max);
print_list(head);
printf("********** Sort \n");
sort(&head);
print_list(head);
printf("Adding at the end of list desc list \n");
int array[9] = {1, 2, 3, 1, 2, 3, 3, 2, 1};
for (int l = sizeof(array)/sizeof(array[0]) - 1;l >= 0; l--) {
createnode(array[l], &head);
}
print_list(head);
return 0;
}
void swap(struct node **Node, int x, int y) {
if (x == y) return;
struct node * prevX = NULL, *currX = *Node;
while(currX && currX->val != x) {
prevX = currX;
currX = currX->next;
}
struct node * prevY = NULL, *currY = *Node;
while(currY && currY->val != y) {
prevY = currY;
currY = currY->next;
}
if (prevX != NULL)
prevX->next = currY;
else
*Node = currY;
if (prevY != NULL)
prevY->next = currX;
else
*Node = currX;
struct node *tmp = currY->next;
currY->next = currX->next;
currX->next = tmp;
}
int remove_by_value(node_t **head, int val) {
node_t *previous, *current;
if (*head == NULL) {
return -1;
}
if ((*head)->val == val) {
node *next_node = NULL;
next_node = (*head)->next;
free(*head);
*head = next_node;
}
previous = current = (*head)->next;
while (current) {
if (current->val == val) {
previous->next = current->next;
free(current);
return val;
}
previous = current;
current = current->next;
}
return -1;
}
void insert_max_elem(node **head, int x) {
struct node * prevX = NULL, *next_max = NULL, *currX = *head;
while(currX->next != NULL) {
if (currX->val > x) {
next_max = currX;
break;
}
currX = currX->next;
// printf("\n currX->val < x: %d , x - %d \n", currX->val < x, currX->val );
}
if (currX->next == NULL) {
return;
}
printf("Some text\n");
printf("next_max %d \n", next_max->val);
//TODO find max in head.
// int arr[9] = {96, 21, 85, 8, 15, 18, 22, 73, 47};
struct node *max = *head;
struct node *current = *head;
struct node *previous = *head, *max_prev = NULL;
while (current->next != NULL) {
if (current->val > max->val) {
max_prev = previous;
max = current;
}
previous = current;
current = current->next;
}
printf("max in head %d \n", max->val);
if (max_prev)
printf("prev of max head %d \n", max_prev->val);
// Inserting.
if (next_max == max) {
return;
}
if (max_prev)
{
max_prev->next = max->next;
} else {
*head = next_max;
}
max->next = next_max->next;
next_max->next = max;
}
void sort(node **head) {
struct node *outer = *head, *inner = NULL;
struct node *inner_next = NULL, *inner_last = NULL;
int count = 0;
while (outer != NULL) {
count++;
outer = outer->next;
}
for (int i = 0; i < count; i++) {
inner = *head;
while(inner->next != NULL && inner != inner_last) {
inner_next = inner->next;
if (inner->val > inner_next->val) {
swap(head, inner->val, inner_next->val);
} else {
inner = inner->next;
}
}
if(inner->next == NULL) {
tail = inner;
}
inner_last = inner;
}
}
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2002 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"
#ifdef XSLT_SUPPORT
#include "modules/xslt/src/xslt_choose.h"
#include "modules/xslt/src/xslt_iforwhen.h"
#include "modules/xslt/src/xslt_simple.h"
#include "modules/xslt/src/xslt_compiler.h"
#include "modules/util/adt/opvector.h"
XSLT_Choose::XSLT_Choose ()
: has_when (FALSE),
has_otherwise (FALSE)
{
}
/* virtual */ void
XSLT_Choose::CompileL (XSLT_Compiler *compiler)
{
OpINT32Vector true_jumps;
unsigned index = 0;
// First all |when|s
for (;index < children_count; ++index)
{
XSLT_TemplateContent *child = children[index];
if (child->GetType () == XSLTE_WHEN)
{
unsigned true_target = static_cast<XSLT_IfOrWhen*>(child)->CompileConditionalCodeL(compiler);
OP_ASSERT(true_target > 0 && true_target == (unsigned)(INT32)true_target);
LEAVE_IF_ERROR(true_jumps.Add((INT32)true_target));
}
else if (child->GetType () == XSLTE_OTHERWISE)
break;
}
// Then the |otherwise|
for (;index < children_count; ++index)
{
XSLT_TemplateContent *child = children[index];
if (child->GetType () == XSLTE_OTHERWISE)
{
child->CompileL(compiler);
break;
}
}
for (unsigned block = 0; block < true_jumps.GetCount(); block++)
{
unsigned true_target = (unsigned)true_jumps.Get(block);
compiler->SetJumpDestination(true_target);
}
}
/* virtual */ XSLT_Element *
XSLT_Choose::StartElementL (XSLT_StylesheetParserImpl *parser, XSLT_ElementType type, const XMLCompleteNameN &name, BOOL &ignore_element)
{
if (type == XSLTE_WHEN || type == XSLTE_OTHERWISE)
{
if (type == XSLTE_WHEN)
if (has_otherwise)
{
parser->SignalErrorL ("xsl:when after xsl:otherwise in xsl:choose");
ignore_element = TRUE;
return this;
}
else
has_when = TRUE;
else if (!has_when)
{
parser->SignalErrorL ("xsl:otherwise before xsl:when in xsl:choose");
ignore_element = TRUE;
return this;
}
else if (has_otherwise)
{
parser->SignalErrorL ("too many xsl:otherwise in xsl:choose");
ignore_element = TRUE;
return this;
}
else
has_otherwise = TRUE;
return XSLT_TemplateContent::StartElementL (parser, type, name, ignore_element);
}
else
{
parser->SignalErrorL ("unexpected element");
ignore_element = TRUE;
return this;
}
}
/* virtual */ BOOL
XSLT_Choose::EndElementL (XSLT_StylesheetParserImpl *parser)
{
if (parser)
if (!has_when)
SignalErrorL (parser, "xsl:choose without xsl:when");
return FALSE;
}
/* virtual */ void
XSLT_Choose::AddCharacterDataL (XSLT_StylesheetParserImpl *parser, XSLT_StylesheetParser::CharacterDataType type, const uni_char *value, unsigned value_length)
{
XSLT_Element::AddCharacterDataL (parser, type, value, value_length);
}
#endif // XSLT_SUPPORT
|
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include "sleeper.h"
using namespace std;
/*
int main( ) { //Example usage
rideTime();
cout << "Ride over" << endl;
walkAroundTime();
cout << "Finished walking around " << endl;
}
*/
void rideTime() {
int seconds = (random() % 5) + 1 ;
cout << "Riding for " << seconds << " seconds " <<endl;
sleep (seconds);
}
void walkAroundTime() {
int seconds = (random() % 10) + 1 ;
cout <<"Walking around for "<< seconds << " seconds "<<endl;
sleep (seconds);
}
|
//算法:二分答案/图论
/*
题目要求 经过的所有城市中 最多的 一次收取的费用的 最小值 是多少
根据题目, 显然,答案满足单调性,
即较小答案合法,则比他大的答案都合法
就可以使用二分答案法
二分答案枚举 最多的一次收取的费用的最小值
并将其作为一个参数 x ,传递给子函数
在子函数中,跑一遍SPFA,
以损失的血量尽量少为目的,
同时对于收取费用大于x的城市,不可到达.
跑完一遍后,判断到达n点消耗的血量是否小于最大血量
如果比最大血量大,证明最多的一次收取的费用的最小值为x时,不可到达
否则则可到达
二分得到最后的答案后,再判断此答案是否合法
合法则输出,否则输出AFK
*/
#include<cstdio>
#include<queue>
#include<algorithm>
#define int long long
using namespace std;
const int MARX = 1e6+10;
const int INF = 2147483647;
struct edge
{
int u,v,w,ne;
}a[MARX];
int n,m,b,maxcost;
int num;
int head[MARX],cost[MARX],cost1[MARX],dis[MARX];
bool vis[MARX]={0,1};
struct cmp1//自定义优先级,优化SPFA
{
bool operator ()(const int a,const int b)
{
return dis[a]>dis[b];
}
};
priority_queue <int,vector<int>,cmp1> s;//优先队列优化SPFA
//========================================================================
void add(int u,int v,int w)
{
a[++num].u=u,a[num].v=v,a[num].w=w;
a[num].ne=head[u],head[u]=num;
}
bool judge(int x)//判断是否合法
{
if(cost[1]>x) return 0;//起点花费是否大于x
for(int i=2;i<=n;i++) dis[i]=INF,vis[i]=0;//SPFA
s.push(1);
while(!s.empty())
{
int top=s.top();
s.pop();
vis[top]=0;
for(int i=head[top];i;i=a[i].ne)
{
int v=a[i].v,w=a[i].w;
if(dis[v]>dis[top]+w && cost[v]<=x)//限制一次收取的费用<=x
{
dis[v]=dis[top]+w;
if(!vis[v])
{
s.push(v);
vis[v]=1;
}
}
}
}
return dis[n]<b;
}
signed main()
{
scanf("%lld%lld%lld",&n,&m,&b);
for(int i=1;i<=n;i++)
{
scanf("%lld",&cost[i]);
cost1[i]=cost[i];
}
for(int i=1;i<=m;i++)//建图
{
int u,v,w;
scanf("%lld%lld%lld",&u,&v,&w);
add(u,v,w),add(v,u,w);
}
sort(cost1+1,cost1+n+1);
int le=1,ri=n,mid;
while(le<=ri)//二分答案
{
mid=(le+ri)>>1;
if(judge(cost1[mid])) ri=mid-1;
else le=mid+1;
}
if(!judge(cost1[le]))printf("AFK");//不可到达的情况
else printf("%lld",cost1[le]);
}
|
// Created on: 1993-01-13
// Created by: CKY / Contract Toubro-Larsen ( Deepak PRABHU )
// 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 _IGESDimen_LeaderArrow_HeaderFile
#define _IGESDimen_LeaderArrow_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <gp_XY.hxx>
#include <TColgp_HArray1OfXY.hxx>
#include <IGESData_IGESEntity.hxx>
#include <Standard_Integer.hxx>
class gp_Pnt2d;
class gp_Pnt;
class IGESDimen_LeaderArrow;
DEFINE_STANDARD_HANDLE(IGESDimen_LeaderArrow, IGESData_IGESEntity)
//! defines LeaderArrow, Type <214> Form <1-12>
//! in package IGESDimen
//! Consists of one or more line segments except when
//! leader is part of an angular dimension, with links to
//! presumed text item
class IGESDimen_LeaderArrow : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESDimen_LeaderArrow();
//! This method is used to set the fields of the class
//! LeaderArrow
//! - height : ArrowHead height
//! - width : ArrowHead width
//! - depth : Z Depth
//! - position : ArrowHead coordinates
//! - segments : Segment tail coordinate pairs
Standard_EXPORT void Init (const Standard_Real height, const Standard_Real width, const Standard_Real depth, const gp_XY& position, const Handle(TColgp_HArray1OfXY)& segments);
//! Changes FormNumber (indicates the Shape of the Arrow)
//! Error if not in range [0-12]
Standard_EXPORT void SetFormNumber (const Standard_Integer form);
//! returns number of segments
Standard_EXPORT Standard_Integer NbSegments() const;
//! returns ArrowHead height
Standard_EXPORT Standard_Real ArrowHeadHeight() const;
//! returns ArrowHead width
Standard_EXPORT Standard_Real ArrowHeadWidth() const;
//! returns Z depth
Standard_EXPORT Standard_Real ZDepth() const;
//! returns ArrowHead coordinates
Standard_EXPORT gp_Pnt2d ArrowHead() const;
//! returns ArrowHead coordinates after Transformation
Standard_EXPORT gp_Pnt TransformedArrowHead() const;
//! returns segment tail coordinates.
//! raises exception if Index <= 0 or Index > NbSegments
Standard_EXPORT gp_Pnt2d SegmentTail (const Standard_Integer Index) const;
//! returns segment tail coordinates after Transformation.
//! raises exception if Index <= 0 or Index > NbSegments
Standard_EXPORT gp_Pnt TransformedSegmentTail (const Standard_Integer Index) const;
DEFINE_STANDARD_RTTIEXT(IGESDimen_LeaderArrow,IGESData_IGESEntity)
protected:
private:
Standard_Real theArrowHeadHeight;
Standard_Real theArrowHeadWidth;
Standard_Real theZDepth;
gp_XY theArrowHead;
Handle(TColgp_HArray1OfXY) theSegmentTails;
};
#endif // _IGESDimen_LeaderArrow_HeaderFile
|
/* leetcode 121
*
*
*
*/
#include <vector>
#include <deque>
#include <algorithm>
#include <list>
using namespace std;
class Solution {
public:
// dp
int maxProfit(vector<int>& prices) {
if(prices.empty() || prices.size() < 2) {
return 0;
}
int minPrice = prices[0];
vector<int> dp(prices.size(), 0);
dp[0] = 0;
for (int i = 1; i < prices.size(); i++) {
minPrice = min(minPrice, prices[i]);
dp[i] = max(dp[i - 1], prices[i] - minPrice);
}
return dp.back();
}
// monotone stack
int maxProfit(vector<int>& prices) {
int ans = 0;
vector<int> st;
prices.emplace_back(-1);
for (int i = 0; i < prices.size(); i++) {
while (!st.empty() && st.back() > prices[i]) {
ans = max(ans, st.back() - st.front());
st.pop_back();
}
st.emplace_back(prices[i]);
}
return ans;
}
};
/************************** run solution **************************/
int _solution_run(vector<int>& prices)
{
Solution leetcode_121;
return leetcode_121.maxProfit(prices);
}
#ifdef USE_SOLUTION_CUSTOM
vector<vector<int>> _solution_custom(TestCases &tc)
{
return {};
}
#endif
/************************** get testcase **************************/
#ifdef USE_GET_TEST_CASES_IN_CPP
vector<string> _get_test_cases_string()
{
return {};
}
#endif
|
/* leetcode 151
*
*
*
*/
class Solution {
public:
string reverseWords(string s) {
if (s.empty()) {
string ans;
return ans;
}
stack<string> words;
string currWord;
for (int i = 0; i < s.size(); i++) {
if (s.at(i) == ' ') {
if (!currWord.empty()) {
words.push(currWord);
currWord = {};
}
} else {
currWord.push_back(s.at(i));
}
}
if (!currWord.empty()) {
words.push(currWord);
}
string ans;
if (words.empty()) {
return ans;
}
int wordsNum = words.size();
for (int i = 0; i < wordsNum - 1; i++) {
ans.append(words.top());
ans.append(" ");
words.pop();
}
ans.append(words.top());
return ans;
}
};
/************************** run solution **************************/
string _solution_run(string s)
{
Solution leetcode_151;
return leetcode_151.reverseWords(s);
}
#ifdef USE_SOLUTION_CUSTOM
vector<vector<int>> _solution_custom(TestCases &tc)
{
return {};
}
#endif
/************************** get testcase **************************/
#ifdef USE_GET_TEST_CASES_IN_CPP
vector<string> _get_test_cases_string()
{
return {};
}
#endif
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 <iostream>
#include <vector>
#include "cuehttp.hpp"
using namespace cue::http;
int main(int argc, char** argv) {
cuehttp app;
router route;
app.ws().use(route.all("/get", [](context& ctx) {
std::cout << "5" << std::endl;
ctx.websocket().on_open([&ctx]() {
std::cout << "websocket on_open" << std::endl;
ctx.websocket().send("hello");
});
ctx.websocket().on_close([]() { std::cout << "websocket on_close" << std::endl; });
ctx.websocket().on_message([&ctx](std::string&& msg) {
std::cout << "websocket msg: " << msg << std::endl;
ctx.websocket().send(std::move(msg));
});
}));
router http_route;
http_route.get("/get", [](context& ctx) {
ctx.type("text/html");
ctx.body(R"(<h1>Hello, cuehttp!</h1>)");
ctx.status(200);
});
app.use(http_route);
auto http_server = http::create_server(app.callback());
http_server.listen(10001);
#ifdef ENABLE_HTTPS
auto https_server = https::create_server(app.callback(), "server.key", "server.crt");
https_server.listen(443);
#endif // #ifdef ENABLE_HTTPS
std::cout << "websocket" << std::endl;
std::thread{[&]() {
for (;;) {
// std::cout << "broadcast....." << std::endl;
app.ws().broadcast("broadcast.....");
std::this_thread::sleep_for(std::chrono::seconds{1});
}
}}.detach();
cuehttp::run();
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int fib(int n){
int *ans = new int[n + 1];
ans[0] = 0;
ans[1] = 1;
for(int i=2;i<=n;i++){
ans[i] = ans[i - 1] + ans[i - 2];
}
return ans[n];
}
int main(){
int n;
cin >> n;
cout << fib(n) << endl;
return 0;
}
|
#ifndef AOC_21_H
#define AOC_21_H
namespace AoC_21 {
int A() {
return -1;
}
int B() {
return -1;
}
}
#endif
|
// Prime verification sqrt(N)
bool prime(ll x){
if(x==2) return true;
else if(x==1 or x%2==0) return false;
for(ll i=3;i*i<=x;i+=2)
if(x%i==0)
return false;
return true;
}
|
#pragma once
#include "../../Toolbox/Toolbox.h"
#include "../Context/Context.h"
#include "../Renderer/Renderer.h"
#include "../../TimeManagement/Time/Time.h"
#include "../../Maths/Primitives/TRect.h"
#include "../../Maths/Vector/Vector2.h"
#include <string>
#include <memory>
struct GLFWwindow;
namespace ae
{
/// \ingroup graphics
/// <summary>
/// Style applied to the window.
/// Deternime which buttons it will have and if it will be resizable.
/// </summary>
enum class WindowStyle : Uint8
{
/// <summary>Window will be resizable.</summary>
Resizable = 1,
/// <summary>Window will have borders and close buttons.</summary>
Decorated = 2,
/// <summary>Window will be maximized at creation.</summary>
Maximized = 4,
/// <summary>Default window decorated and resizable.</summary>
Default = Resizable | Decorated,
/// <summary>Window will have nothing.</summary>
None = 0,
};
/// \ingroup graphics
/// <summary>
/// Settings of a new window. <para/>
/// It contains all informations required for window creation.
/// </summary>
class AERO_CORE_EXPORT WindowSettings
{
public:
/// <summary>Default constructor.</summary>
WindowSettings() :
Width( 960 ),
Height( 720 ),
X( 50 ),
Y( 50 ),
Name( "DefaultWindowName" ),
Options( WindowStyle::Default ),
AntiAliasing( 0 ),
FrameRate( 60 ),
VSync( True ),
IsDPIAware( True )
{
}
/// <summary>Window width.</summary>
Uint32 Width;
/// <summary>Window height.</summary>
Uint32 Height;
/// <summary>Window position X.</summary>
Int32 X;
/// <summary>Window position Y.</summary>
Int32 Y;
/// <summary>Window name ( in toolbar and taskbar ).</summary>
std::string Name;
/// <summary>Window style and options ( close, resize, border, etc ).</summary>
WindowStyle Options;
/// <summary>Antialiasing level. 0 disable.</summary>
Uint8 AntiAliasing;
/// <summary>Window frame rate. 0 to ignore it.</summary>
Uint32 FrameRate;
/// <summary>Synchronize the framerate with the monitor refresh frequence ?</summary>
Bool VSync;
/// <summary>Window and UI must be scaled according to the monitor DPI ?</summary>
Bool IsDPIAware;
};
/// \ingroup graphics
/// <summary>
/// Window management (size, style, ...)
/// The OpenGL rendering will be show on it.
/// Catch user interactions.
/// </summary>
class AERO_CORE_EXPORT Window : public Renderer
{
public:
/// <summary>Default constructor.</summary>
Window();
/// <summary> Destructor.</summary>
~Window();
/// <summary>Create a window (render target).</summary>
/// <param name="_Settings">Settings to apply to the window when creating it.</param>
void Create( const WindowSettings& _Settings = WindowSettings() );
/// <summary>Destroy created window.</summary>
void Destroy();
/// <summary>Return True if window is open, false otherwise.</summary>
/// <returns>True if open, false if not.</returns>
Bool IsOpen();
/// <summary>
/// Push the openGL buffer to the screen
/// Then process frame rate.
/// </summary>
void Render() override;
/// <summary>Change the title of the window.</summary>
/// <param name="_Title">New window title.</param>
void SetWindowTitle( const std::string& _Title );
/// <summary>Retrieve the window title.</summary>
/// <returns>Window title.</returns>
const std::string& GetWindowTitle() const;
/// <summary>Set frame rate limit.</summary>
/// <param name="_FrameRate">Target frame rate.</param>
void SetFrameRate( Int8 _FrameRate );
/// <summary>Retrieve frame rate target. ( User setting ).</summary>
/// <returns>Current target frame rate.</returns>
Uint32 GetFrameRate() const;
/// <summary>Get the real frame rate based on frame delta time.</summary>
/// <returns>Frame rate based on delta time.</returns>
Uint32 GetRealFrameRate() const;
/// <summary>Get the last frame time.</summary>
/// <returns>The last frame time.</returns>
Time GetFrameTime() const;
/// <summary>Get the last frame time (computation time without the sleep).</summary>
/// <returns>The last frame time.</returns>
const Time& GetFrameComputeTime() const;
/// <summary>Retrieve window height.</summary>
/// <returns>Window height.</returns>
Uint32 GetHeight() const override;
/// <summary>Retrieve window width.</summary>
/// <returns>Window width.</returns>
Uint32 GetWidth() const override;
/// <summary>Get window rectangle area.</summary>
/// <returns>Window area.</returns>
FloatRect GetWindowRect() const;
/// <summary>Convert a screen position to a position relative to the window.</summary>
/// <param name="_Position">Position to convert.</param>
/// <returns>Position converted.</returns>
Vector2 ScreenToWindowCoordinates( const Vector2& _Position ) const;
/// <summary>Convert a position in the window to screen coordinates.</summary>
/// <param name="_Position">Position to convert.</param>
/// <returns>Position converted.</returns>
Vector2 WindowToScreenCoordinates( const Vector2& _Position ) const;
/// <summary>Gets the rendering context of the window.</summary>
/// <returns>The window context.</returns>
const Context& GetContext() const;
/// <summary>Determines whether this window has focus on messages and keyboard strokes.</summary>
/// <returns>True if the window has the focus, False otherwise.</returns>
Bool HasFocus() const;
/// <summary>
/// Retrieve the focus from operating system.
/// The focus is not imediatly retrieved, you must check after witth HasFocus.
/// </summary>
void RequestFocus() const;
/// <summary>Retrieve the GLFW window.</summary>
/// <returns>GLFW window.</returns>
const GLFWwindow& GetGLFWWindow() const;
/// <summary>Retrieve the GLFW window.</summary>
/// <returns>GLFW window.</returns>
GLFWwindow& GetGLFWWindow();
/// <summary>Process event received by the window, and update inputs.</summary>
void WindowIteration();
/// <summary>Get the scale to apply according the monitor DPI.</summary>
/// <returns>The scale according to the monitor DPI.</returns>
float GetDPIScale() const;
/// <summary>Is the window is resizable ?</summary>
/// <returns>True if resizable, False otherwise.</returns>
Bool IsResizable() const;
/// <summary>Is the window is decorated ?</summary>
/// <returns>True if decorated, False otherwise.</returns>
Bool IsDecorated() const;
/// <summary>Is the window is maximized at its creation ?</summary>
/// <returns>True if maximized at creation, False otherwise.</returns>
Bool IsMaximizedAtCreation() const;
/// <summary>Is the framerate is syncrhonized with the monitor refresh frequence ?</summary>
/// <returns>True if the VSync is active, False otherwise.</returns>
Bool IsVSyncActive() const;
/// <summary>Should the framerate be syncrhonized with the monitor refresh frequence ? </summary>
/// <param name="_ActivateVSync">True to activate the VSync, False to disable it.</param>
void SetVSync( Bool _ActivateVSync );
/// <summary>Is the application scale the window and the UI according the monitor DPI ?</summary>
/// <returns>True if the scale is applied, false otherwise.</returns>
Bool IsDPIAware() const;
private:
/// <summary> GLFW callback when a key is pressed or released.</summary>
/// <param name="_Window">GLFW window receiving the input.</param>
/// <param name="_Key">_Key concerned by the event.</param>
/// <param name="_Scancode">Scan code of the key.</param>
/// <param name="_Action">Action done to the key.</param>
/// <param name="_Mods">Combined key (shift, alt, ...).</param>
static void OnKeyEvent( GLFWwindow* _Window, Int32 _Key, Int32 _Scancode, Int32 _Action, Int32 _Mods );
/// <summary>GLFW event when a character is entered.</summary>
/// <param name="window">GLFW window receiving the input.</param>
/// <param name="_Codepoint">Code of the character.</param>
static void OnKeyCharEvent( GLFWwindow* window, Uint32 _Codepoint );
/// <summary>GLFW callback when a mouse button is pressed or released.</summary>
/// <param name="_Window">GLFW window receiving the input.</param>
/// <param name="_Button">Mouse button concerned.</param>
/// <param name="_Action">Action done to the key.</param>
/// <param name="_Mods">Combined key (shift, alt, ...).</param>
static void OnMouseButtonEvent( GLFWwindow* _Window, Int32 _Button, Int32 _Action, Int32 _Mods );
/// <summary>GLFW callback when a mouse is moved.</summary>
/// <param name="_Window">GLFW window receiving the input.</param>
/// <param name="_PositionX">The new position X of the mouse.</param>
/// <param name="_PositionY">The new position Y of the mouse.</param>
static void OnMouseMoveEvent( GLFWwindow* _Window, double _PositionX, double _PositionY );
/// <summary>GLFW callback when the mouse wheel is used.</summary>
/// <param name="_Window">GLFW window receiving the input.</param>
/// <param name="_DeltaX">The delta on X axis of the wheel since the last callback.</param>
/// <param name="_DeltaY">The delta on Y axis of the wheel since the last callback.</param>
static void OnMouseWheelEvent( GLFWwindow* _Window, double _DeltaX, double _DeltaY );
/// <summary>GLFW callback when the window size is changed.</summary>
/// <param name="_Window">GLFW window resized.</param>
/// <param name="_Width">New width of the window.</param>
/// <param name="_Height">New height of the window.</param>
static void OnWindowSizeChangedEvent( GLFWwindow* _Window, Int32 _Width, Int32 _Height );
/// <summary>GLFW callback when the window is moved.</summary>
/// <param name="_Window">GLFW window moved.</param>
/// <param name="_PositionX">The new position on X axis of the window.</param>
/// <param name="_PositionY">The new position on Y axis of the window.</param>
static void OnWindowMoveEvent( GLFWwindow* _Window, Int32 _PositionX, Int32 _PositionY );
/// <summary>GLFW callback when the focus of the window changed.</summary>
/// <param name="_Window">GLFW window losing or winning focus.</param>
/// <param name="_IsFocus">True if <paramref name="_Window"/> is focus, false otherwise.</param>
static void OnFocusChangedEvent( GLFWwindow* _Window, Int32 _IsFocus );
/// <summary>GLFW callback when the window is closed.</summary>
/// <param name="_Window">GLFW window closed.</param>
static void OnCloseEvent( GLFWwindow* _Window );
/// <summary>Process the scale according the monitor DPI.</summary>
void ProcessDPIScale();
protected:
/// <summary>Init context for opengl rendering.</summary>
void InitContext();
/// <summary>
/// Limit the framerate to the user setting.<para/>
/// Also fill engine DeltaTime value.
/// </summary>
void ProcessFrameRate();
/// <summary>Update the computation time of the frame (without VSync / Sleep ).</summary>
void UpdateFrameTime();
protected:
/// <summary>Handle on GLFW window.</summary>
GLFWwindow* m_GLFWWindow;
/// <summary>If windows is in a valid state.</summary>
Bool m_IsOpen;
/// <summary>OpenGL context.</summary>
Context m_Context;
/// <summary>User info.</summary>
WindowSettings m_WindowUserInfo;
/// <summary>
/// Time marker set a the end of each frame.
/// Used for process framerate and delta time.
/// </summary>
Time m_EndLastFrameTime;
/// <summary>Elapsed time between the end of the last frame and the current frame before the sleep.</summary>
Time m_FrameComputeTime;
/// <summary>Determine if the window has the focus on messages and keyboard strokes.</summary>
Bool m_HasFocus;
/// <summary>Scale to do according to the monitor DPI.</summary>
float m_DPIScale;
};
}
/// <summary>
/// '|' Operator for WindowStyle enum fields.<para/>
/// That allow to do ae::WindowStyle | ae::WindowStyle without casts.<para/>
/// The enum values will cast to Int64 to do the operation.
/// </summary>
/// <param name="_A">First WindowStyle.</param>
/// <param name="_B">Seoncd WindowStyle.</param>
/// <returns>The result of the operator '|' between the two parameter..</returns>
AERO_CORE_EXPORT ae::WindowStyle operator|( ae::WindowStyle _A, ae::WindowStyle _B );
|
#pragma once
#include "utils/ptts.hpp"
#include "proto/config_login_back_ground.pb.h"
using namespace std;
namespace pc = proto::config;
namespace nora {
namespace config {
using login_back_ground_ptts = ptts<pc::login_back_ground>;
login_back_ground_ptts& login_back_ground_ptts_instance();
void login_back_ground_ptts_set_funcs();
}
}
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Пример использования перечислений, пользовательского ввода и структуры
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include<iostream>
#include<string>
using namespace std;
enum class Position{ // Position
manager,
programmer,
director
};
struct tempUserInputEnumStruct {
int id;
string userName;
//Position position;
int age;
};
int main() {
cout << "Enter id: ";
int id;
cin >> id;
cin.ignore(32767, '\n');
cout << "Enter user name: ";
string userName;
getline(cin, userName);
cout << "Enter age: ";
int age;
cin >> age;
cin.ignore(32767, '\n');
tempUserInputEnumStruct alex = {id, userName, age};
cout << "id: "<< alex.id << " name: " << alex.userName << ", age: " << alex.age << endl;
return 0;
}
/* Output:
Enter id: 1
Enter user name: Alex
Enter age: 25
id: 1 name: Alex, age: 25
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
#include "ssBBox.h"
#include "ssVector3.h"
#include "ssRay.h"
#include "ssSphere.h"
#include "ssPlane.h"
namespace ssMath
{
//-----------------------------------------------------------------
BBox Union(const BBox &b, const Point3 &p)
{
BBox tmp = b;
tmp.merge(p);
return tmp;
}
//-----------------------------------------------------------------
BBox Union(const BBox &b, const BBox &b2)
{
BBox tmp = b;
tmp.merge(b2);
return tmp;
}
//-----------------------------------------------------------------
BBox Intersection(const BBox &b1, const BBox &b2)
{
BBox tmp = b1;
tmp.intersection(b2);
return tmp;
}
//-----------------------------------------------------------------
bool BBox::intersect(const Ray &ray, float &hitt0, float &hitt1) const
{
// Initialize parametric interval
float t0 = ray.mint, t1 = ray.maxt;
// Check X slab
float invRayDir = 1.f / ray.D.x;
float tNear = (m_Min.x - ray.O.x) * invRayDir;
float tFar = (m_Max.x - ray.O.x) * invRayDir;
// Update parametric interval
if (tNear > tFar) swap(tNear, tFar);
t0 = max(tNear, t0);
t1 = min(tFar, t1);
if (t0 > t1) return false;
// Check Y slab
invRayDir = 1.f / ray.D.y;
tNear = (m_Min.y - ray.O.y) * invRayDir;
tFar = (m_Max.y - ray.O.y) * invRayDir;
// Update parametric interval
if (tNear > tFar) swap(tNear, tFar);
t0 = max(tNear, t0);
t1 = min(tFar, t1);
if (t0 > t1) return false;
// Check Z slab
invRayDir = 1.f / ray.D.z;
tNear = (m_Min.z - ray.O.z) * invRayDir;
tFar = (m_Max.z - ray.O.z) * invRayDir;
// Update parametric interval
if (tNear > tFar) swap(tNear, tFar);
t0 = max(tNear, t0);
t1 = min(tFar, t1);
if (t0 > t1) return false;
hitt0 = t0;
hitt1 = t1;
return true;
}
//-----------------------------------------------------------------
bool BBox::intersect(const Sphere &sphere) const
{
return sphere.intersect(*this);
}
//-----------------------------------------------------------------
bool BBox::intersect(const Plane &plane) const
{
return (plane.getSide(*this) == Plane::BOTH_SIDE);
}
}
|
#include <iostream>
#include <chrono>
using namespace std;
#define FIRSTDATATYPE unsigned int//32bits
#define SECONDDATATYPE unsigned short//16bits
FIRSTDATATYPE gcd(FIRSTDATATYPE a, FIRSTDATATYPE b) {
return b == 0 ? a : gcd(b, a % b);
}
class RSA {
private:
SECONDDATATYPE p;
SECONDDATATYPE q;
FIRSTDATATYPE d;
public:
FIRSTDATATYPE e;
FIRSTDATATYPE n;
RSA(SECONDDATATYPE p, SECONDDATATYPE q) {
n=((FIRSTDATATYPE)p)*((FIRSTDATATYPE)q); //typecasting to prevent overflow
unsigned long long phi_n = (((FIRSTDATATYPE)p)-1)*(((FIRSTDATATYPE)q)-1); //typecasting to prevent overflow
e = 2; //to able to find the gcd of two numbers both of them must be >=2, else gcd will always be 1
while(1){ //increments e, until gcd(e,phi_n) = 1, meaning e is relatively prime to phi(n)
if( gcd(e , phi_n) != 1){
e++;
}else{
break;
}
}
d = 1;
while(1){ //increments d until d * e = 1 mod phi(n) is reached
if( ((d % (phi_n)) * (e)) % phi_n != 1){ // e is always smaller than phi_n so no need to do e%phi_n, (but d might be bigger than phi_n so modulus is done)
d++;
}else{
break;
}
}
}
FIRSTDATATYPE encrypt(FIRSTDATATYPE m) {
unsigned long long encrypted = m; //the biggest data type is used in order for the program to work even with very large numbers
for(long long i = 1; i < e; i++){ // finds pow(m, e) (mod n)
encrypted = ((encrypted % n) * m) % n; //encryped might be bigger than n so moudlus is taken right away, this also prevents overflow if the multiplication of encrypted * m is too large
}
return encrypted;
}
FIRSTDATATYPE decrypt(FIRSTDATATYPE c) { //same algorithm as RSA::encrypt but used different values for the decryption purpose
unsigned long long decrypted = c; //large data is especially needed for decryption from my expereinces
for(long long i = 1; i < d; i++){ //find pow(c, d) (mod n)
decrypted = ((decrypted % n) * c) % n;
}
return decrypted;
}
FIRSTDATATYPE decrypt_bit(FIRSTDATATYPE c) {
unsigned long long result = 1; //big data type is needed because of the multiplication in the following for loop
unsigned long long tempC = (unsigned long long)c; //typecasting to prevent overflow in the next loop
int iterate = 0;
FIRSTDATATYPE MSB = 1; //idea is simple create 000....0001,
MSB = MSB << 31; //then make it 10000....000 then use this to find 1's by iteration
while(iterate < 32){ //itearets through d, not c!, since d is unsigned int, it is 32 bits!
if((d | MSB) == d){ //if the bit is 1, do this:
result = ((result% n) * (tempC% n)) % n;
}
if(iterate < 31){ //do this operation for each bit except the last bit of d
result = ((result% n) * (result% n)) % n;
}
MSB = MSB >> 1; //shift MSB to right to look for the next bit
iterate++;
}
return result;
}
};
int main () {
RSA rsa(62137, 62141);
//RSA rsa(5, 11);
auto start = std::chrono::system_clock::now();
FIRSTDATATYPE c = rsa.encrypt(15);
auto end = std::chrono::system_clock::now();
chrono::duration<double> elapsed_seconds = end - start;
time_t end_time = std::chrono::system_clock::to_time_t(end);
cout << "Encryption time: " << elapsed_seconds.count() << "s -- " << " ciphertext is " << c << "\n";
start = std::chrono::system_clock::now();
FIRSTDATATYPE m = rsa.decrypt(c);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
end_time = std::chrono::system_clock::to_time_t(end);
cout << "Decryption time: " << elapsed_seconds.count() << "s -- " << " message is " << m << "\n";
start = std::chrono::system_clock::now();
FIRSTDATATYPE m_bit = rsa.decrypt_bit(c);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
end_time = std::chrono::system_clock::to_time_t(end);
cout << "Decryption time: " << elapsed_seconds.count() << "s -- " << " message is " << m_bit << "\n";
return 0;
}
|
#include "Main.hpp"
#ifndef LOADFUNCTIONS_H
#define LOADFUNCTIONS_H
GLuint CompileShadersMakeProgram(const char * vertex_file_path,const char * fragment_file_path);
GLuint loadBMP_custom(const char * imagepath);
GLuint loadDDS(const char * imagepath);
bool loadOBJ(const char * path, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals);
#endif
|
// Copyright (c) 2007-2015 Hartmut Kaiser
// Copyright (c) 2011 Bryce Lelbach
// Copyright (c) 2014 Anuj R. Sharma
//
// 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 error.hpp
#pragma once
#include <pika/config.hpp>
#include <fmt/format.h>
#include <string>
#include <system_error>
///////////////////////////////////////////////////////////////////////////////
namespace pika {
///////////////////////////////////////////////////////////////////////////
/// \brief Possible error conditions
///
/// This enumeration lists all possible error conditions which can be
/// reported from any of the API functions.
enum class error
{
/// The operation was successful
success = 0,
/// The operation failed, but not in an unexpected manner
no_success = 1,
/// The operation is not implemented
not_implemented = 2,
/// The operation caused an out of memory condition
out_of_memory = 3,
/// The operation was executed in an invalid status
invalid_status = 4,
/// One of the supplied parameters is invalid
bad_parameter = 5,
///
lock_error = 6,
///
startup_timed_out = 7,
///
uninitialized_value = 8,
///
bad_response_type = 9,
///
deadlock = 10,
///
assertion_failure = 11,
/// Attempt to invoke a function that requires a pika thread from a non-pika thread
null_thread_id = 12,
///
invalid_data = 13,
/// The yield operation was aborted
yield_aborted = 14,
///
dynamic_link_failure = 15,
/// One of the options given on the command line is erroneous
commandline_option_error = 16,
/// An unhandled exception has been caught
unhandled_exception = 17,
/// The OS kernel reported an error
kernel_error = 18,
/// The task associated with this future object is not available anymore
broken_task = 19,
/// The task associated with this future object has been moved
task_moved = 20,
/// The task associated with this future object has already been started
task_already_started = 21,
/// The future object has already been retrieved
future_already_retrieved = 22,
/// The value for this future object has already been set
promise_already_satisfied = 23,
/// The future object does not support cancellation
future_does_not_support_cancellation = 24,
/// The future can't be canceled at this time
future_can_not_be_cancelled = 25,
/// The future object has no valid shared state
no_state = 26,
/// The promise has been deleted
broken_promise = 27,
///
thread_resource_error = 28,
///
future_cancelled = 29,
///
thread_cancelled = 30,
///
thread_not_interruptable = 31,
/// An unknown error occurred
unknown_error = 32,
/// equivalent of std::bad_function_call
bad_function_call = 33,
/// parallel::task_canceled_exception
task_canceled_exception = 34,
/// task_region is not active
task_block_not_active = 35,
/// Equivalent to std::out_of_range
out_of_range = 36,
/// Equivalent to std::length_error
length_error = 37,
/// \cond NOINTERNAL
last_error,
system_error_flag = 0x4000L,
error_upper_bound = 0x7fffL // force this enum type to be at least 16 bits.
/// \endcond
};
namespace detail {
/// \cond NOINTERNAL
char const* const error_names[] = {
/* 0 */ "success",
/* 1 */ "no_success",
/* 2 */ "not_implemented",
/* 3 */ "out_of_memory",
/* 4 */ "invalid_status",
/* 5 */ "bad_parameter",
/* 6 */ "lock_error",
/* 7 */ "startup_timed_out",
/* 8 */ "uninitialized_value",
/* 9 */ "bad_response_type",
/* 10 */ "deadlock",
/* 11 */ "assertion_failure",
/* 12 */ "null_thread_id",
/* 13 */ "invalid_data",
/* 14 */ "yield_aborted",
/* 15 */ "dynamic_link_failure",
/* 16 */ "commandline_option_error",
/* 17 */ "unhandled_exception",
/* 18 */ "kernel_error",
/* 19 */ "broken_task",
/* 20 */ "task_moved",
/* 21 */ "task_already_started",
/* 22 */ "future_already_retrieved",
/* 23 */ "promise_already_satisfied",
/* 24 */ "future_does_not_support_cancellation",
/* 25 */ "future_can_not_be_cancelled",
/* 26 */ "no_state",
/* 27 */ "broken_promise",
/* 28 */ "thread_resource_error",
/* 29 */ "future_cancelled",
/* 30 */ "thread_cancelled",
/* 31 */ "thread_not_interruptable",
/* 32 */ "unknown_error",
/* 33 */ "bad_function_call",
/* 34 */ "task_canceled_exception",
/* 35 */ "task_block_not_active",
/* 36 */ "out_of_range",
/* 37 */ "length_error",
/* */ ""};
inline bool error_code_has_system_error(int e)
{
return e & static_cast<int>(pika::error::system_error_flag);
}
/// \endcond
} // namespace detail
} // namespace pika
template <>
struct fmt::formatter<pika::error> : fmt::formatter<std::string>
{
template <typename FormatContext>
auto format(pika::error e, FormatContext& ctx)
{
int e_int = static_cast<int>(e);
if (e_int >= static_cast<int>(pika::error::success) &&
e_int < static_cast<int>(pika::error::last_error))
{
return fmt::formatter<std::string>::format(pika::detail::error_names[e_int], ctx);
}
else
{
return fmt::formatter<std::string>::format(
fmt::format("invalid pika::error ({})", e_int), ctx);
}
}
};
/// \cond NOEXTERNAL
namespace std {
// make sure our errors get recognized by the Boost.System library
template <>
struct is_error_code_enum<pika::error>
{
static const bool value = true;
};
template <>
struct is_error_condition_enum<pika::error>
{
static const bool value = true;
};
} // namespace std
/// \endcond
|
// Moduł SOURCE.CPP
// =================
// Funkcje składowe klasy Source.
//
#include "Source.h"
Source::Source(const string& fnam): fn(fnam)
{
istr.open(fn.c_str());
if(!istr)
{ cout<<"Analang: blad odczytu pliku \""<<fn<<"\"\n";
exit(1);
}
cout<<"\nInterpreter Analang, v0.1, zadne prawa niezastrzeżone\n";
cout<<((options&NOLIST)?"Skrócony":"Pełny");
cout<<" raport wykonania dla pliku: \""<<fnam<<"\"\n\n";
etotal = 0;
NextLine(); // Pierwszy wiersz
}
Source::~Source()
{
//LastMessage
cout<<"\nAnalang: koniec raportu. Wykrytych błędów: "<<etotal<<'\n';
istr.close();
}
bool Source::NextLine() // Zwraca true jeśli jest następny wiersz
{
if(istr.eof()) return false;
getline(istr, Line); // Pobiera wiersz (bez znaku '\n')
Line.push_back('\n');
tpos.ln++; // Następny wiersz
tpos.cn=0; // Przed pierwszym znakiem
while(Line[tpos.cn]==' ' || Line[tpos.cn]=='\t') tpos.cn++;
if( (options&NOLIST)==0 ) PrntLine();
einline=0; // 0 błędów w tym wierszu
return true;
}
void Source::Error(int ec,const TextPos&tp,const char*mt,const char*at)
{ etotal++;
if((options&NOLIST) && einline==0) // Jest pierwszy błąd w wierszu
cout<<setw(5)<<tpos.ln<<' '<<Line; // Druk wiersza źródłowego
einline=1;
cout<<setw(2)<<ec<<"*** ";
cout<<setw(tp.cn)<<setfill('-')<<'^'<<setfill(' ')<<mt<<at<<'\n';
}
int Source::NextChar()
{ bool r=true;
if(tpos.cn==Line.size()) r=NextLine();
if(r) return Line[tpos.cn++]; else return EOF;
}
|
#include <iostream>
#include "gtest/gtest.h"
#include "../apps/recognizer/include/intent.h"
TEST(Weather_test_case, basic_test_1)
{
Recognizer rec_intent;
std::stringstream sstr("What is the weather like today?");
EXPECT_EQ("Intent: Get Weather", rec_intent.Get_Intent(sstr));
}
TEST(Weather_test_case, basic_test_Paris)
{
Recognizer rec_intent;
std::stringstream sstr("What is the weather like in Paris today?");
EXPECT_EQ("Intent: Get Weather City ", rec_intent.Get_Intent(sstr));
}
TEST(Weather_test_case, basic_test_New_York)
{
Recognizer rec_intent;
std::stringstream sstr("What is the weather like in New York today?");
EXPECT_EQ("Intent: Get Weather City ", rec_intent.Get_Intent(sstr));
}
TEST(Weather_test_case, advanced_test_Cairo)
{
Recognizer rec_intent;
std::stringstream sstr("What is the weather like in Cairo today?");
EXPECT_EQ("Intent: Get Weather City ", rec_intent.Get_Intent(sstr));
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e17 // 4倍しても(4回足しても)long longを溢れない
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
int main() {
int n,len;
vector<ll> a, sum;
cin >> n;
a = vector<ll>(n);
sum = vector<ll>(n);
len = 3 * n;
rep(i,len) {
cin >> a[i];
}
priority_queue<ll> preque, befque; // 昇順
priority_queue<ll, vector<ll>, greater<ll> > preque_dec, befque_dec;
vector<ll> t(n),s(n);
ll presum = 0, befsum = 0;
ll premax = 0, befmax = 0;
rep(i,n) {
presum += a[i];
preque.push(a[i]);
preque_dec.push(a[i]);
}
premax = presum;
for (int k = n; k <= 2*n; ++k) {
int presize = k - n;
int itr = presum;
if (presize > 0) {
preque.push(a[k-1]);
itr += a[k-1];
preque.pop();
preque_dec.push(a[k-1]);
itr -= preque_dec.top();
preque_dec.pop();
}
presum = itr;
t[k - n] = itr;
}
rep(i,n) {
befsum += a[len - i - 1];
befque.push(a[len - i - 1]);
befque_dec.push(a[len - i - 1]);
}
for (int k = n; k <= 2*n; ++k) {
int befsize = k - n;
int itr = befsum;
if (befsize > 0) {
}
}
}
|
#pragma once
void NewFunction(std::ifstream& file1, std::string& temp, std::vector<std::string>& firstFileLines);
void NewFunction1(std::ifstream& file1, std::string& temp, std::vector<std::string>& firstFileLines);
|
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int t, l, r;
char str[31];
cin >> t;
while(t--)
{
cin >> str;
int n = strlen(str);
for(l=0,r=n-1; l < r; ++l,--r)
{
char tmp = str[l];
str[l] = str[r];
str[r] = tmp;
}
cout<<str<<endl;
}
return 0;
}
|
#pragma once
#include "Seaquence.h"
class Ending:public Seaquence
{
public:
Ending();
~Ending();
Boot* Update(SeaquenceController*);
private:
//エンディングイメージ
int mCount;
};
|
#include "FastIO_v2.h"
bool F_fastRead(const uint8_t pin) {
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
if (pin < 8) return bitRead(PIND, pin);
else if (pin < 14) return bitRead(PINB, pin - 8);
else if (pin < 20) return bitRead(PINC, pin - 14);
#elif defined(__AVR_ATtiny85__) || defined(__AVR_ATtiny13__)
return bitRead(PINB, pin);
#elif defined(AVR)
uint8_t *_pin_reg = portInputRegister(digitalPinToPort(pin));
uint8_t _bit_mask = digitalPinToBitMask(pin);
return bool(*_pin_reg & _bit_mask);
#else
return digitalRead(pin);
#endif
return 0;
}
void F_fastWrite(const uint8_t pin, bool val) {
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
if (pin < 8) bitWrite(PORTD, pin, val);
else if (pin < 14) bitWrite(PORTB, (pin - 8), val);
else if (pin < 20) bitWrite(PORTC, (pin - 14), val);
#elif defined(__AVR_ATtiny85__) || defined(__AVR_ATtiny13__)
bitWrite(PORTB, pin, val);
#elif defined(AVR)
uint8_t *_port_reg = portInputRegister(digitalPinToPort(pin));
uint8_t _bit_mask = digitalPinToBitMask(pin);
_port_reg = portOutputRegister(digitalPinToPort(pin));
_bit_mask = digitalPinToBitMask(pin);
if (val) *_port_reg |= _bit_mask; // HIGH
else *_port_reg &= ~_bit_mask; // LOW
#else
digitalWrite(pin, val);
#endif
}
uint8_t F_fastShiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
#if defined(AVR)
volatile uint8_t *_clk_port = portOutputRegister(digitalPinToPort(clockPin));
volatile uint8_t *_dat_port = portInputRegister(digitalPinToPort(dataPin));
uint8_t _clk_mask = digitalPinToBitMask(clockPin);
uint8_t _dat_mask = digitalPinToBitMask(dataPin);
uint8_t data = 0;
for (uint8_t i = 0; i < 8; i++) {
*_clk_port |= _clk_mask;
if (bitOrder == MSBFIRST) {
data <<= 1;
if (bool(*_dat_port & _dat_mask)) data |= 1;
} else {
data >>= 1;
if (bool(*_dat_port & _dat_mask)) data |= 1 << 7;
}
*_clk_port &= ~_clk_mask;
}
return data;
#else
return shiftIn(dataPin, clockPin, bitOrder);
#endif
}
void F_fastShiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t data) {
#if defined(AVR)
volatile uint8_t *_clk_port = portOutputRegister(digitalPinToPort(clockPin));
volatile uint8_t *_dat_port = portOutputRegister(digitalPinToPort(dataPin));
uint8_t _clk_mask = digitalPinToBitMask(clockPin);
uint8_t _dat_mask = digitalPinToBitMask(dataPin);
for (uint8_t i = 0; i < 8; i++) {
if (bitOrder == MSBFIRST) {
if (data & (1 << 7)) *_dat_port |= _dat_mask;
else *_dat_port &= ~_dat_mask;
data <<= 1;
} else {
if (data & 1) *_dat_port |= _dat_mask;
else *_dat_port &= ~_dat_mask;
data >>= 1;
}
*_clk_port |= _clk_mask;
*_clk_port &= ~_clk_mask;
}
#else
shiftOut(dataPin, clockPin, bitOrder, data);
#endif
}
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QDeclarativeItem>
#include <QDeclarativeView>
#include "sendkey.h"
class MainWindow : public QDeclarativeView
{
Q_OBJECT
public:
MainWindow();
public:
void toggle();
void focusin();
void focusout();
public:
QDeclarativeItem *rootItem;
Keyboard keyboard;
};
#endif
|
//
// CTest.hpp
// HttpSvr
//
// Created by yuzhan on 2016/11/15.
//
//
#ifndef CTest_hpp
#define CTest_hpp
#include <string>
#include "CHttpRequestHandler.h"
class CTest : public CHttpRequestHandler
{
public:
CTest(){}
~CTest(){}
virtual int do_request(const Json::Value& root, char *client_ip, HttpResult& out);
};
#endif /* CTest_hpp */
|
/*
src/malloc.cpp -- Asynchronous memory allocation system + cache
Copyright (c) 2020 Wenzel Jakob <wenzel.jakob@epfl.ch>
All rights reserved. Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
#include "internal.h"
#include "log.h"
#include "util.h"
static_assert(
sizeof(tsl::detail_robin_hash::bucket_entry<AllocUsedMap::value_type, false>) == 24,
"AllocUsedMap: incorrect bucket size, likely an issue with padding/packing!");
const char *alloc_type_name[(int) AllocType::Count] = {
"host", "host-async", "host-pinned",
"device", "managed", "managed-read-mostly"
};
const char *alloc_type_name_short[(int) AllocType::Count] = {
"host ",
"host-async ",
"host-pinned",
"device ",
"managed ",
"managed/rm "
};
// Round an unsigned integer up to a power of two
size_t round_pow2(size_t x) {
x -= 1;
x |= x >> 1; x |= x >> 2;
x |= x >> 4; x |= x >> 8;
x |= x >> 16; x |= x >> 32;
return x + 1;
}
uint32_t round_pow2(uint32_t x) {
x -= 1;
x |= x >> 1; x |= x >> 2;
x |= x >> 4; x |= x >> 8;
x |= x >> 16;
return x + 1;
}
void* jit_malloc(AllocType type, size_t size) {
if (size == 0)
return nullptr;
if ((type != AllocType::Host && type != AllocType::HostAsync) ||
jit_llvm_vector_width < 16) {
// Round up to the next multiple of 64 bytes
size = (size + 63) / 64 * 64;
} else {
size_t packet_size = jit_llvm_vector_width * sizeof(double);
size = (size + packet_size - 1) / packet_size * packet_size;
}
/* Round 'size' to the next larger power of two. This is somewhat
wasteful, but reduces the number of different sizes that an allocation
can have to a manageable amount that facilitates re-use. */
size = round_pow2(size);
AllocInfo ai(size, type, 0);
const char *descr = nullptr;
void *ptr = nullptr;
Stream *stream = active_stream;
if (type == AllocType::HostAsync && stream && !stream->parallel_dispatch)
type = AllocType::Host;
/* Acquire lock protecting stream->release_chain and state.alloc_free */ {
lock_guard guard(state.malloc_mutex);
if (type == AllocType::Device || type == AllocType::HostAsync) {
if (unlikely(!stream))
jit_raise(
"jit_malloc(): you must specify an active device using "
"jit_set_device() before allocating a device/host-async memory!");
else if (unlikely(!stream->cuda == (type == AllocType::Device)))
jit_raise("jit_malloc(): you must specify the right backend "
"via jit_set_device() before allocating a "
"device/host-async memory!");
ai.device = stream->cuda ? stream->device : 0;
}
if (type == AllocType::Device || type == AllocType::HostAsync) {
/* Check for arrays with a pending free operation on the current
stream. This only works for device or host-async memory, as other
allocation flavors (host-pinned, shared, shared-read-mostly) can be
accessed from both CPU & GPU and might still be used. */
ReleaseChain *chain = stream->release_chain;
while (chain) {
auto it = chain->entries.find(ai);
if (it != chain->entries.end()) {
auto &list = it.value();
if (!list.empty()) {
ptr = list.back();
list.pop_back();
descr = "reused local";
break;
}
}
chain = chain->next;
}
}
// Look globally. Are there suitable freed arrays?
if (ptr == nullptr) {
auto it = state.alloc_free.find(ai);
if (it != state.alloc_free.end()) {
std::vector<void *> &list = it.value();
if (!list.empty()) {
ptr = list.back();
list.pop_back();
descr = "reused global";
}
}
}
}
// 3. Looks like we will have to allocate some memory..
if (unlikely(ptr == nullptr)) {
if (type == AllocType::Host || type == AllocType::HostAsync) {
int rv;
/* Temporarily release the main lock */ {
unlock_guard guard(state.mutex);
#if !defined(_WIN32)
rv = posix_memalign(&ptr, 64, ai.size);
#else
ptr = _aligned_malloc(ai.size, 64);
rv = ptr == nullptr ? ENOMEM : 0;
#endif
}
if (rv == ENOMEM) {
jit_malloc_trim();
/* Temporarily release the main lock */ {
unlock_guard guard(state.mutex);
#if !defined(_WIN32)
rv = posix_memalign(&ptr, 64, ai.size);
#else
ptr = _aligned_malloc(ai.size, 64);
rv = ptr == nullptr ? ENOMEM : 0;
#endif
}
}
if (rv != 0)
ptr = nullptr;
} else {
scoped_set_context guard(stream->context);
CUresult (*alloc) (CUdeviceptr *, size_t) = nullptr;
auto cuMemAllocManaged_ = [](CUdeviceptr *ptr_, size_t size_) {
return cuMemAllocManaged(ptr_, size_, CU_MEM_ATTACH_GLOBAL);
};
auto cuMemAllocManagedReadMostly_ = [](CUdeviceptr *ptr_, size_t size_) {
CUresult ret = cuMemAllocManaged(ptr_, size_, CU_MEM_ATTACH_GLOBAL);
if (ret == CUDA_SUCCESS)
cuda_check(cuMemAdvise(*ptr_, size_, CU_MEM_ADVISE_SET_READ_MOSTLY, 0));
return ret;
};
switch (type) {
case AllocType::HostPinned: alloc = (decltype(alloc)) cuMemAllocHost; break;
case AllocType::Device: alloc = cuMemAlloc; break;
case AllocType::Managed: alloc = cuMemAllocManaged_; break;
case AllocType::ManagedReadMostly: alloc = cuMemAllocManagedReadMostly_; break;
default:
jit_fail("jit_malloc(): internal-error unsupported allocation type!");
}
CUresult ret;
/* Temporarily release the main lock */ {
unlock_guard guard(state.mutex);
ret = alloc((CUdeviceptr *) &ptr, ai.size);
}
if (ret != CUDA_SUCCESS) {
jit_malloc_trim();
/* Temporarily release the main lock */ {
unlock_guard guard(state.mutex);
ret = alloc((CUdeviceptr *) &ptr, ai.size);
}
if (ret != CUDA_SUCCESS)
ptr = nullptr;
}
size_t &allocated = state.alloc_allocated[ai.type],
&watermark = state.alloc_watermark[ai.type];
allocated += ai.size;
watermark = std::max(allocated, watermark);
}
descr = "new allocation";
}
if (unlikely(ptr == nullptr))
jit_raise("jit_malloc(): out of memory! Could not "
"allocate %zu bytes of %s memory.",
size, alloc_type_name[ai.type]);
state.alloc_used.emplace(ptr, ai);
if ((AllocType) ai.type == AllocType::Device)
jit_trace("jit_malloc(type=%s, device=%u, size=%zu): " ENOKI_PTR " (%s)",
alloc_type_name[ai.type], (uint32_t) ai.device, (size_t) ai.size,
(uintptr_t) ptr, descr);
else
jit_trace("jit_malloc(type=%s, size=%zu): " ENOKI_PTR " (%s)",
alloc_type_name[ai.type], (size_t) ai.size, (uintptr_t) ptr,
descr);
state.alloc_usage[ai.type] += ai.size;
return ptr;
}
void jit_free(void *ptr) {
if (ptr == nullptr)
return;
auto it = state.alloc_used.find(ptr);
if (unlikely(it == state.alloc_used.end()))
jit_raise("jit_free(): unknown address " ENOKI_PTR "!", (uintptr_t) ptr);
AllocInfo ai = it.value();
if ((AllocType) ai.type == AllocType::Host) {
// Acquire lock protecting 'state.alloc_free'
lock_guard guard(state.malloc_mutex);
state.alloc_free[ai].push_back(ptr);
} else {
Stream *stream = active_stream;
bool cuda = (AllocType) ai.type != AllocType::HostAsync;
if (likely(stream && cuda == stream->cuda)) {
/* Acquire lock protecting 'stream->release_chain' */ {
lock_guard guard(state.malloc_mutex);
ReleaseChain *chain = stream->release_chain;
if (unlikely(!chain))
chain = stream->release_chain = new ReleaseChain();
chain->entries[ai].push_back(ptr);
}
} else {
/* This is bad -- freeing a pointer outside of an active
stream, or with the wrong backend activated. That pointer may
still be used in a kernel that is currently being executed
asynchronously. The only thing we can do at this point is to
flush all streams. */
jit_sync_all_devices();
lock_guard guard(state.malloc_mutex);
state.alloc_free[ai].push_back(ptr);
}
}
if ((AllocType) ai.type == AllocType::Device)
jit_trace("jit_free(" ENOKI_PTR ", type=%s, device=%u, size=%zu)",
(uintptr_t) ptr, alloc_type_name[ai.type],
(uint32_t) ai.device, (size_t) ai.size);
else
jit_trace("jit_free(" ENOKI_PTR ", type=%s, size=%zu)", (uintptr_t) ptr,
alloc_type_name[ai.type], (size_t) ai.size);
state.alloc_usage[ai.type] -= ai.size;
state.alloc_used.erase(it);
}
void jit_free_flush() {
Stream *stream = active_stream;
if (unlikely(!stream))
return;
ReleaseChain *chain = stream->release_chain;
if (chain == nullptr || chain->entries.empty())
return;
size_t n_dealloc = 0;
for (auto &kv: chain->entries)
n_dealloc += kv.second.size();
if (n_dealloc == 0)
return;
ReleaseChain *chain_new = new ReleaseChain();
chain_new->next = chain;
stream->release_chain = chain_new;
jit_trace("jit_free_flush(): scheduling %zu deallocation%s",
n_dealloc, n_dealloc > 1 ? "s" : "");
if (stream->cuda) {
scoped_set_context guard(stream->context);
cuda_check(cuLaunchHostFunc(
stream->handle,
[](void *ptr) -> void {
/* Acquire lock protecting stream->release_chain and
state.alloc_free */
lock_guard guard(state.malloc_mutex);
ReleaseChain *chain0 = (ReleaseChain *) ptr,
*chain1 = chain0->next;
for (auto &kv : chain1->entries) {
const AllocInfo &ai = kv.first;
std::vector<void *> &target = state.alloc_free[ai];
target.insert(target.end(), kv.second.begin(),
kv.second.end());
}
delete chain1;
chain0->next = nullptr;
},
chain_new));
} else if (stream->parallel_dispatch) {
Task *new_task = pool_task_submit(
nullptr, &stream->task, 1, 1,
[](size_t, void *ptr_) {
void *ptr = *((void **) ptr_);
/* Acquire lock protecting stream->release_chain and
state.alloc_free */
lock_guard guard(state.malloc_mutex);
ReleaseChain *chain0 = (ReleaseChain *) ptr,
*chain1 = chain0->next;
for (auto &kv : chain1->entries) {
const AllocInfo &ai = kv.first;
std::vector<void *> &target = state.alloc_free[ai];
target.insert(target.end(), kv.second.begin(),
kv.second.end());
}
delete chain1;
chain0->next = nullptr;
}, &chain_new, sizeof(void *)
);
pool_task_release(stream->task);
stream->task = new_task;
}
}
void* jit_malloc_migrate(void *ptr, AllocType type, int move) {
Stream *stream = active_stream;
if (unlikely(!stream))
jit_raise("jit_malloc_migrate(): you must invoke jitc_set_device() to "
"choose a target device before evaluating expressions using "
"the JIT compiler.");
auto it = state.alloc_used.find(ptr);
if (unlikely(it == state.alloc_used.end()))
jit_raise("jit_malloc_migrate(): unknown address " ENOKI_PTR "!", (uintptr_t) ptr);
AllocInfo ai = it.value();
if (((AllocType) ai.type == AllocType::Host && type == AllocType::HostAsync) ||
((AllocType) ai.type == AllocType::HostAsync && type == AllocType::Host)) {
if (move) {
it.value().type = (uint32_t) type;
return ptr;
}
}
// Maybe nothing needs to be done..
if ((AllocType) ai.type == type && (type != AllocType::Device || ai.device == stream->device))
return ptr;
/// At this point, source or destination is a GPU array, so let's check for CUDA
if (!stream->cuda)
jit_raise(
"jit_malloc_migrate(): you must specify an active CUDA device "
"using jit_set_device() before invoking this function with a "
"device/managed/host-pinned pointer!");
if (type == AllocType::HostAsync || (AllocType) ai.type == AllocType::HostAsync)
jit_raise("jit_malloc_migrate(): migrations between CUDA and "
"host-asynchronous memory are not supported.");
if (type == AllocType::Host) // Upgrade from host to host-pinned memory
type = AllocType::HostPinned;
void *ptr_new = jit_malloc(type, ai.size);
jit_trace("jit_malloc_migrate(" ENOKI_PTR " -> " ENOKI_PTR ", %s -> %s)",
(uintptr_t) ptr, (uintptr_t) ptr_new,
alloc_type_name[ai.type], alloc_type_name[(int) type]);
scoped_set_context guard(stream->context);
if ((AllocType) ai.type == AllocType::Host) {
/// Host -> Device memory, create an intermediate host-pinned array
void *tmp = jit_malloc(AllocType::HostPinned, ai.size);
memcpy(tmp, ptr, ai.size);
cuda_check(cuMemcpyAsync((CUdeviceptr) ptr_new,
(CUdeviceptr) ptr, ai.size,
stream->handle));
jit_free(tmp);
} else {
cuda_check(cuMemcpyAsync((CUdeviceptr) ptr_new,
(CUdeviceptr) ptr, ai.size,
stream->handle));
}
if (move)
jit_free(ptr);
return ptr_new;
}
/// Asynchronously prefetch a memory region
void jit_malloc_prefetch(void *ptr, int device) {
Stream *stream = active_stream;
if (unlikely(!stream || !stream->cuda))
jit_raise(
"jit_malloc_prefetch(): you must specify an active CUDA device "
"using jit_set_device() before invoking this function!");
if (device == -1) {
device = CU_DEVICE_CPU;
} else {
if ((size_t) device >= state.devices.size())
jit_raise("jit_malloc_prefetch(): invalid device ID!");
device = state.devices[device].id;
}
auto it = state.alloc_used.find(ptr);
if (unlikely(it == state.alloc_used.end()))
jit_raise("jit_malloc_prefetch(): unknown address " ENOKI_PTR "!",
(uintptr_t) ptr);
AllocInfo ai = it.value();
if ((AllocType) ai.type != AllocType::Managed &&
(AllocType) ai.type != AllocType::ManagedReadMostly)
jit_raise("jit_malloc_prefetch(): invalid memory type, expected "
"Managed or ManagedReadMostly.");
scoped_set_context guard(stream->context);
if (device == -2) {
for (const Device &d : state.devices)
cuda_check(cuMemPrefetchAsync((CUdeviceptr) ptr, ai.size, d.id,
stream->handle));
} else {
cuda_check(cuMemPrefetchAsync((CUdeviceptr) ptr, ai.size, device,
stream->handle));
}
}
static bool jit_malloc_trim_warned = false;
/// Release all unused memory to the GPU / OS
void jit_malloc_trim(bool warn) {
if (warn && !jit_malloc_trim_warned) {
jit_log(
Warn,
"jit_malloc_trim(): Enoki exhausted the available memory and had "
"to flush its allocation cache to free up additional memory. This "
"is an expensive operation and will have a negative effect on "
"performance. You may want to change your computation so that it "
"uses less memory. This warning will only be displayed once.");
jit_malloc_trim_warned = true;
}
AllocInfoMap alloc_free;
/* Critical section */ {
lock_guard guard(state.malloc_mutex);
alloc_free = std::move(state.alloc_free);
}
// Ensure that all computation using this memory has indeed completed.
jit_sync_all_devices();
size_t trim_count[(int) AllocType::Count] = { 0 },
trim_size [(int) AllocType::Count] = { 0 };
/* Temporarily release the main lock */ {
unlock_guard guard(state.mutex);
for (auto& kv : alloc_free) {
const std::vector<void *> &entries = kv.second;
trim_count[(int) kv.first.type] += entries.size();
trim_size[(int) kv.first.type] += kv.first.size * entries.size();
switch ((AllocType) kv.first.type) {
case AllocType::Device:
case AllocType::Managed:
case AllocType::ManagedReadMostly:
if (state.has_cuda) {
for (void *ptr : entries)
cuda_check(cuMemFree((CUdeviceptr) ptr));
}
break;
case AllocType::HostPinned:
if (state.has_cuda) {
for (void *ptr : entries)
cuda_check(cuMemFreeHost(ptr));
}
break;
case AllocType::Host:
case AllocType::HostAsync:
#if !defined(_WIN32)
for (void *ptr : entries)
free(ptr);
#else
for (void* ptr : entries)
_aligned_free(ptr);
#endif
break;
default:
jit_fail("jit_malloc_trim(): unsupported allocation type!");
}
}
}
for (auto& kv : alloc_free)
state.alloc_allocated[kv.first.type] -= kv.first.size;
size_t total = 0;
for (int i = 0; i < (int) AllocType::Count; ++i)
total += trim_count[i];
if (total > 0) {
jit_log(Debug, "jit_malloc_trim(): freed");
for (int i = 0; i < (int) AllocType::Count; ++i) {
if (trim_count[i] == 0)
continue;
jit_log(Debug, " - %s memory: %s in %zu allocation%s",
alloc_type_name[i], jit_mem_string(trim_size[i]),
trim_count[i], trim_count[i] > 1 ? "s" : "");
}
}
}
/// Query the flavor of a memory allocation made using \ref jit_malloc()
AllocType jit_malloc_type(void *ptr) {
auto it = state.alloc_used.find(ptr);
if (unlikely(it == state.alloc_used.end()))
jit_raise("jit_malloc_type(): unknown address " ENOKI_PTR "!", (uintptr_t) ptr);
return (AllocType) it->second.type;
}
/// Query the device associated with a memory allocation made using \ref jit_malloc()
int jit_malloc_device(void *ptr) {
auto it = state.alloc_used.find(ptr);
if (unlikely(it == state.alloc_used.end()))
jit_raise("jit_malloc_type(): unknown address " ENOKI_PTR "!", (uintptr_t) ptr);
const AllocInfo &ai = it.value();
if (ai.type == (int) AllocType::Host || ai.type == (int) AllocType::HostAsync)
return -1;
else
return ai.device;
}
void jit_malloc_shutdown() {
jit_malloc_trim(false);
size_t leak_count[(int) AllocType::Count] = { 0 },
leak_size [(int) AllocType::Count] = { 0 };
for (auto kv : state.alloc_used) {
leak_count[(int) kv.second.type]++;
leak_size[(int) kv.second.type] += kv.second.size;
}
size_t total = 0;
for (int i = 0; i < (int) AllocType::Count; ++i)
total += leak_count[i];
if (total > 0) {
jit_log(Warn, "jit_malloc_shutdown(): leaked");
for (int i = 0; i < (int) AllocType::Count; ++i) {
if (leak_count[i] == 0)
continue;
jit_log(Warn, " - %s memory: %s in %zu allocation%s",
alloc_type_name[i], jit_mem_string(leak_size[i]),
leak_count[i], leak_count[i] > 1 ? "s" : "");
}
}
}
|
#include <stdio.h>
#define ROW 5
#define COL 9
int chess[ROW][COL] ; //棋盘
int step ; //记录步数
int search(int x1, int y1, int x2, int y2)
//x1和y1分别是当前位置行号和列号
//x2和y2分别是B位置行号和列号
{
int i, j ;
int success = 0 ;
if(x1 == x2 && y1 == y2) //走通
{
for(i = 0; i < ROW; i++)
{
for(j = 0; j < COL; j++)
{
printf("%d ", chess[i][j]) ;
}
printf("\n") ;
}
return 1;
}
//逆时 针顺序 尝试四种走法
//第一种
if(x1+2<ROW && y1+1<COL)
{
step++ ; //步数+1
chess[x1+2][y1+1] = step ;
success = search(x1+2, y1+1, x2, y2) ;
if(success) //从这条路可以走通
return 1 ;
step-- ; //没走通,回退
chess[x1+2][y1+1] = 0 ;
}
//第二种
if(x1+1<ROW && y1+2<COL)
{
step++ ; //步数+1
chess[x1+1][y1+2] = step ;
success = search(x1+1, y1+2, x2, y2) ;
if(success)
return 1 ;
step-- ; //没走通,回退
chess[x1+1][y1+2] = 0 ;
}
//第三种
if(x1-1<ROW && y1+2<COL)
{
step++ ; //步数+1
chess[x1-1][y1+2] = step ;
success = search(x1-1, y1+2, x2, y2) ;
if(success)
return 1 ;
step-- ; //没走通,回退
chess[x1-1][y1+2] = 0 ;
}
//第四种
if(x1-2<ROW && y1+1<COL)
{
step++ ; //步数+1
chess[x1-2][y1+1] = step ;
success = search(x1-2, y1+1, x2, y2) ;
if(success)
return 1 ;
step-- ; //没走通 回退
chess[x1-2][y1+1] = 0 ;
}
return 0 ;
}
int main()
{
int i, j ;
int x, y ;
for(i = 0; i < ROW; i++)
for(j = 0; j < COL; j++)
chess[i][j] = 0 ;
step = 1 ;
printf("请输入起始点(x,y)\n") ;
scanf("%d,%d", &x, &y) ;
chess[x][y] = step ;
if(search(x, y, 0, 8))
printf("共计%d步。\n", step) ;
return 0 ;
}
|
/***********************************************************
File name: AdeeptRemoteControl.ino
Description:
1.Push the left rocker up/forward and the robot will move forward. The farther you push each time, the faster the robot will move.
2.Pull the left rocker down/backward and the robot will move backward. The farther you pull each time, the faster the robot will move.
3.Pull the right rocker to the left and the robot will turn left. The farther you pull each time, the faster the robot will move.
4.Pull the right rocker to the right and the robot will turn right. The farther you pull each time, the faster the robot will move.
5.Press the button A and the robot will stand/squat. After it stands up, the RGB LED will turn into blue (or green); when it squats, this LED will change to red.
Note: The robot will only move after it stands up.
6.Press button B and the robot now enters the remote control mode. At the same time the LED2 on the remote will light up when the LED3 dims. And the RGB LED on the robot's head turns back to blue.
7.Press button C to change into the mode of automatic obstacle avoidance. The LED3 lights up when LED2 goes out. The RGB LED turns into green.
8.Press button D to control the buzzer beep of the module on the robot.
Website: www.adeept.com
E-mail: support@adeept.com
Author: Tom
Date: 2017/08/22
***********************************************************/
#include <SPI.h>
#include "RF24.h"
RF24 radio(9, 10); // define the object to control NRF24L01
byte addresses[5] = "00005"; // define communication address which should correspond to remote control
int data[9]; // define array used to save the communication data
int mode = 0;
const int pot6Pin = 5; // define R6
const int pot5Pin = 4; // define R1
const int led1Pin = 6; // define pin for LED1 which is close to NRF24L01 and used to indicate the state of NRF24L01
const int led2Pin = 7; // define pin for LED2 which is the mode is displayed in the Six foot robots remote control mode
const int led3Pin = 8; // define pin for LED3 which is the mode is displayed in the Six foot robots auto mode
const int APin = 2; // define pin for D2
const int BPin = 3; // define pin for D3
const int CPin = 4; // define pin for D4
const int DPin = 5; // define pin for D5
const int u1XPin = 0; // define pin for direction X of joystick U1
const int u1YPin = 1; // define pin for direction Y of joystick U1
const int u2XPin = 2; // define pin for direction X of joystick U2
const int u2YPin = 3; // define pin for direction Y of joystick U2
void setup() {
radio.begin(); // initialize RF24
radio.setRetries(0, 15); // set retries times
radio.setPALevel(RF24_PA_LOW); // set power
radio.openWritingPipe(addresses); // open delivery channel
radio.stopListening(); // stop monitoring
pinMode(led1Pin, OUTPUT); // set led1Pin to output mode
pinMode(led2Pin, OUTPUT); // set led2Pin to output mode
pinMode(led3Pin, OUTPUT); // set led3Pin to output mode
pinMode(APin, INPUT_PULLUP); // set APin to output mode
pinMode(BPin, INPUT_PULLUP); // set BPin to output mode
pinMode(CPin, INPUT_PULLUP); // set CPin to output mode
pinMode(DPin, INPUT_PULLUP); // set DPin to output mode
data[3] = 0;
data[4] = 1;
}
void loop() {
// put the values of rocker, switch and potentiometer into the array
data[0] = analogRead(u1XPin);
data[1] = analogRead(u1YPin);
if(digitalRead(APin)==LOW){
delay(100);
data[2] = digitalRead(APin);
}else{
data[2] = HIGH;
}
if( digitalRead(BPin)==LOW){//Switch the working mode
mode = 0;
data[3] = 0;
data[4] = 1;
}
if(digitalRead(CPin)==LOW){//Switch the working mode
mode = 1;
data[3] = 1;
data[4] = 0;
}
data[5] = digitalRead(DPin);
data[6] = analogRead(pot5Pin);
data[7] = analogRead(u2YPin);
data[8] = analogRead(u2XPin);
// send array data. If the sending succeeds, open signal LED
if (radio.write( data, sizeof(data) ))
digitalWrite(led1Pin,HIGH);
// delay for a period of time, then turn off the signal LED for next sending
delay(50);
digitalWrite(led1Pin,LOW);
if(mode==0){//LED display status
digitalWrite(led2Pin,HIGH);
digitalWrite(led3Pin,LOW);
}
if(mode==1){//LED display status
digitalWrite(led2Pin,LOW);
digitalWrite(led3Pin,HIGH);
}
}
|
//
// Created by 송지원 on 2020-02-15.
//
#include <iostream>
int main() {
int N;
int five = 5;
int num_of_five = 0;
scanf("%d", &N);
// while (N/five >= 1) {
// num_of_five += (N / five);
// five *= 5;
// }
num_of_five = N/5 + N/25 + N/125;
printf("%d\n", num_of_five);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.