text
stringlengths 8
6.88M
|
|---|
//Author: Benjamin Kleinberg
#include "int.h"
#include<iostream>
#include<fstream>
using std::ostream;
using std::istream;
using std::ifstream;
const Int Int::INF(1, 1);
const Int Int::N_INF(-1, 2);
const Int Int::NAN(0, 3);
int Int::displayASCII = 0;
/**
* Private constructor for setting up constants
* @param val the integer value to be set
* @param flags the flags to mark the constant
*/
Int::Int(int val, int flags) {
_val = val;
_flags = flags;
}
/**
* Public constructor to set up a standard integer
* @param nVal the integer value to be set
*/
Int::Int(int nVal) {
_val = nVal;
_flags = 0;
}
/**
* Less than operator
*/
int operator<(const Int &left, const Int &right) {
int retVal = 0;
if(left._flags == 0 && right._flags == 0)
//Standard integer comparison
retVal = left._val < right._val;
else if(left == Int::INF)
//If left is infinity, it is never smaller
retVal = 0;
else if(left == Int::N_INF)
//If left is negative infinity, it is always smaller unless right is also negative infinity
retVal = (right != Int::N_INF);
else if(right == Int::INF)
//If right is infinity, left is always smaller unless it is also infinity
retVal = (left != Int::INF);
else if(right == Int::N_INF)
//If right is negative infinity, left is never smaller
retVal = 0;
return retVal;
}
int operator<(const Int &left, const int &right) {
return left < Int(right);
}
int operator<(const int &left, const Int &right) {
return Int(left) < right;
}
/**
* Less than or equal operator
*/
int operator<=(const Int &left, const Int &right) {
int retVal = 0;
if(left._flags == 0 && right._flags == 0)
//Standard integer comparison
retVal = left._val <= right._val;
else if(left == Int::INF)
//If left is infinity, it is only smaller or equal when right is also infinity
retVal = (right == Int::INF);
else if(left == Int::N_INF)
//If left is negative infinity, it is always smaller or equal
retVal = 1;
else if(right == Int::INF)
//If right is infinity, left is always smaller or equal
retVal = 1;
else if(right == Int::N_INF)
//If right is negative infinity, left is only smaller or equal when it is also negative infinty
retVal = (left == Int::N_INF);
return retVal;
}
int operator<=(const Int &left, const int &right) {
return left <= Int(right);
}
int operator<=(const int &left, const Int &right) {
return Int(left) <= right;
}
/**
* Greater than operator
*/
int operator>(const Int &left, const Int &right) {
int retVal = 0;
if(left._flags == 0 && right._flags == 0)
//Standard integer comparison
retVal = left._val > right._val;
else if(left == Int::INF)
//If left is infinity, it is always larger unless right is also infinity
retVal = (right != Int::INF);
else if(left == Int::N_INF)
//If left is negative infinity, it is never larger
retVal = 0;
else if(right == Int::INF)
//If right is infinity, left is never larger
retVal = 0;
else if(right == Int::N_INF)
//If right is negative infinity, left is larger unless right is also negative infinity
retVal = (left != Int::N_INF);
return retVal;
}
int operator>(const Int &left, const int &right) {
return left > Int(right);
}
int operator>(const int &left, const Int &right) {
return Int(left) > right;
}
/**
* Greater than or equal operator
*/
int operator>=(const Int &left, const Int &right) {
int retVal = 0;
if(left._flags == 0 && right._flags == 0)
//Standard integer comparison
retVal = left._val >= right._val;
else if(left == Int::INF)
//If left is infinity, it is always larger or equal
retVal = 1;
else if(left == Int::N_INF)
//If left is negative infinity, it is only larger or equal when right is also negative infinity
retVal = (right == Int::N_INF);
else if(right == Int::INF)
//If right is infinity, left is only larger or equal when it is also infinity
retVal = (left == Int::INF);
else if(right == Int::N_INF)
//If right is negative infinity, left is always larger or equal
retVal = 1;
return retVal;
}
int operator>=(const Int &left, const int &right) {
return left >= Int(right);
}
int operator>=(const int &left, const Int &right) {
return Int(left) >= right;
}
/**
* Equality operator
* Two integers are equal if they both are the same infinities or are the same regular integers.
*/
int operator==(const Int &left, const Int &right) {
int retVal = 1;
retVal = (left._flags == right._flags);
if(retVal && left._flags == 0)
retVal = (left._val == right._val);
return retVal;
}
int operator==(const Int &left, const int &right) {
return left == Int(right);
}
int operator==(const int &left, const Int &right) {
return Int(left) == right;
}
/**
* Inequality operator
*/
int operator!=(const Int &left, const Int &right) {
return !(left == right);
}
int operator!=(const Int &left, const int &right) {
return left != Int(right);
}
int operator!=(const int &left, const Int &right) {
return Int(left) != right;
}
/**
* Addition operator
* Flags get combined bitwise.
* Infinity + negative infinity = invalid integer.
*/
Int operator+(const Int &left, const Int &right) {
Int retVal;
retVal._val = left._val + right._val;
retVal._flags = left._flags | right._flags;
return retVal;
}
Int operator+(const Int &left, const int &right) {
return left + Int(right);
}
Int operator+(const int &left, const Int &right) {
return Int(left) + right;
}
/**
* Addition and set operator
* Flags get combined bitwise.
* Infinity + negative infinity = invalid integer.
*/
void operator+=(Int &left, const Int &right) {
left._val = left._val + right._val;
left._flags = left._flags | right._flags;
}
void operator+=(Int &left, const int &right) {
left += Int(right);
}
/**
* Subtraction operator
* Flags get reversed and combined bitwise
* Infinity - infinity = invalid integer.
*/
Int operator-(const Int &left, const Int &right) {
Int retVal;
retVal._val = left._val - right._val;
retVal._flags = left._flags;
if(right._flags & 1)
retVal._flags = retVal._flags | 2;
if(right._flags & 2)
retVal._flags = retVal._flags | 1;
return retVal;
}
Int operator-(const Int &left, const int &right) {
return left - Int(right);
}
Int operator-(const int &left, const Int &right) {
return Int(left) - right;
}
/**
* Subtraction and set operator
* Flags get reversed and combined bitwise.
* Infinity - infinity = invalid integer.
*/
void operator-=(Int &left, const Int &right) {
left._val = left._val - right._val;
if(right._flags & 1)
left._flags = left._flags | 2;
if(right._flags & 2)
left._flags = left._flags | 1;
}
void operator-=(Int &left, const int &right) {
left -= Int(right);
}
/**
* Multiplication operator
* Total negatives get added up to determine resulting flag.
*/
Int operator*(const Int &left, const Int &right) {
Int retVal;
if(left._flags || right._flags) {
if(left == Int::NAN || right == Int::NAN)
//Preserve invalid integers
retVal = Int::NAN;
else {
int totalNegatives = 0;
totalNegatives += (left._val < 0 || left._flags == 2);
totalNegatives += (right._val < 0 || right._flags == 2);
retVal._flags = totalNegatives % 2 + 1;
}
}
else
retVal._val = left._val * right._val;
return retVal;
}
Int operator*(const Int &left, const int &right) {
return left * Int(right);
}
Int operator*(const int &left, const Int &right) {
return Int(left) * right;
}
/**
* Division operator
* Divisor cannot be an infinity.
* Total negatives get added up to determine resulting flag.
*/
Int operator/(const Int &left, const Int &right) {
Int retVal;
if(left._flags || right._flags) {
if(left == Int::NAN || right._flags)
//Preserve invalid integers
//Divisor being either infinity is invalid
retVal = Int::NAN;
else {
int totalNegatives = 0;
totalNegatives += (left._val < 0 || left._flags == 2);
totalNegatives += (right._val < 0 || right._flags == 2);
retVal._flags = totalNegatives % 2 + 1;
}
}
else
retVal._val = left._val / right._val;
return retVal;
}
Int operator/(const Int &left, const int &right) {
return left / Int(right);
}
Int operator/(const int &left, const Int &right) {
return Int(left) / right;
}
/**
* Modulus operator
* Divisor cannot be an infinity.
*/
Int operator%(const Int &left, const Int &right) {
Int retVal;
if(left._flags || right._flags) {
if(left == Int::NAN || right._flags)
//Preserve invalid integers
//Divisor being either infinity is invalid
retVal = Int::NAN;
else
//Divident being negative results in a negative infinity
retVal._flags = (left._val < 0 || left._flags == 2) + 1;
}
else
retVal._val = left._val % right._val;
return retVal;
}
Int operator%(const Int &left, const int &right) {
return left % Int(right);
}
Int operator%(const int &left, const Int &right) {
return Int(left) % right;
}
/**
* Insertion operator
*/
ostream& operator<<(ostream& out, const Int& right) {
switch(right._flags) {
case 0: //Standard int
out<< right._val;
break;
case 1: //Infinity
if(Int::displayASCII)
out<< Int::INF_CHAR;
else
out<< "inf";
break;
case 2: //Negative Infinity
if(Int::displayASCII)
out<< '-' << Int::INF_CHAR;
else
out<< "-inf";
break;
default: //Invalid flag
out<< "-nan";
break;
}
return out;
}
/**
* Extraction operator
*/
istream& operator>>(istream& in, Int& right) {
in>> right._val;
right._flags = 0;
return in;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#include "core/pch.h"
#include "adjunct/m2/src/backend/imap/commands/AuthenticationCommand.h"
#include "adjunct/m2/src/backend/imap/commands/MailboxCommand.h"
#include "adjunct/m2/src/util/authenticate.h"
#include "adjunct/m2/src/backend/imap/imapmodule.h"
///////////////////////////////////////////
// Authentication
///////////////////////////////////////////
/***********************************************************************************
**
**
** Authentication::OnFailed
***********************************************************************************/
OP_STATUS ImapCommands::Authentication::OnFailed(IMAP4& protocol, const OpStringC8& failed_msg)
{
// Failed password attempt, ask the user for password
OpString server_msg;
OpStatus::Ignore(server_msg.Set(failed_msg));
protocol.GetBackend().Lock();
protocol.GetBackend().RequestDisconnect();
protocol.GetBackend().OnAuthenticationRequired(server_msg);
return OpStatus::OK;
}
///////////////////////////////////////////
// Authenticate
///////////////////////////////////////////
/***********************************************************************************
**
**
** Authenticate::GetExpandedQueue
***********************************************************************************/
ImapCommandItem* ImapCommands::Authenticate::GetExpandedQueue(IMAP4& protocol)
{
OpAutoPtr<ImapCommandItem> replacement_command;
ImapBackend& backend = protocol.GetBackend();
// Search for an authentication method to use
AccountTypes::AuthenticationType auth_method = backend.GetAuthenticationMethod();
if (auth_method == AccountTypes::AUTOSELECT)
{
auth_method = backend.GetCurrentAuthMethod();
if (auth_method == AccountTypes::AUTOSELECT)
{
// Autoselect of authentication method, check which methods are supported
UINT32 supported_authentication = backend.GetAuthenticationSupported();
if (protocol.GetCapabilities() & ImapFlags::CAP_LOGINDISABLED)
supported_authentication &= ~(1 << AccountTypes::PLAINTEXT);
if (!(protocol.GetCapabilities() & ImapFlags::CAP_AUTH_CRAMMD5))
supported_authentication &= ~(1 << AccountTypes::CRAM_MD5);
if (!(protocol.GetCapabilities() & ImapFlags::CAP_AUTH_LOGIN))
supported_authentication &= ~(1 << AccountTypes::LOGIN);
if (!(protocol.GetCapabilities() & ImapFlags::CAP_AUTH_PLAIN))
supported_authentication &= ~(1 << AccountTypes::PLAIN);
// Get the next in the list
auth_method = backend.GetNextAuthenticationMethod(backend.GetCurrentAuthMethod(), supported_authentication);
backend.SetCurrentAuthMethod(auth_method);
}
}
// Change to correct command
switch (auth_method)
{
case AccountTypes::CRAM_MD5:
replacement_command = OP_NEW(ImapCommands::AuthenticateCramMD5, ());
break;
case AccountTypes::LOGIN:
replacement_command = OP_NEW(ImapCommands::AuthenticateLogin, ());
break;
case AccountTypes::PLAIN:
replacement_command = OP_NEW(ImapCommands::AuthenticatePlain, ());
break;
case AccountTypes::PLAINTEXT:
default:
if (protocol.GetCapabilities() & ImapFlags::CAP_LOGINDISABLED)
return NULL; // Not allowed to do this
replacement_command = OP_NEW(ImapCommands::Login, ());
}
if (!replacement_command.get())
return NULL;
// Create an LSUB command directly following the authentication
ImapCommandItem* lsub = OP_NEW(ImapCommands::Lsub, ());
if (!lsub)
return NULL;
lsub->DependsOn(replacement_command.get(), protocol);
return replacement_command.release();
}
///////////////////////////////////////////
// AuthenticateCramMD5
///////////////////////////////////////////
/***********************************************************************************
** Create the MD5 checksum needed in the response
**
** AuthenticateCramMD5::PrepareContinuation
***********************************************************************************/
OP_STATUS ImapCommands::AuthenticateCramMD5::PrepareContinuation(IMAP4& protocol, const OpStringC8& response_text)
{
m_continuation++;
// Prepare MD5 checksum response
OpAuthenticate info;
RETURN_IF_ERROR(protocol.GetBackend().GetLoginInfo(info, response_text));
return m_md5_response.Set(info.GetResponse());
}
/***********************************************************************************
**
**
** AuthenticateCramMD5::AppendCommand
***********************************************************************************/
OP_STATUS ImapCommands::AuthenticateCramMD5::AppendCommand(OpString8& command, IMAP4& protocol)
{
return command.Append(m_continuation ? m_md5_response.CStr() : "AUTHENTICATE CRAM-MD5");
}
///////////////////////////////////////////
// AuthenticateLogin
///////////////////////////////////////////
/***********************************************************************************
**
**
** AuthenticateLogin::AppendCommand
***********************************************************************************/
OP_STATUS ImapCommands::AuthenticateLogin::AppendCommand(OpString8& command, IMAP4& protocol)
{
OpAuthenticate info;
if (m_continuation > 0)
RETURN_IF_ERROR(protocol.GetBackend().GetLoginInfo(info));
switch (m_continuation)
{
case 0:
return command.Append("AUTHENTICATE LOGIN");
case 1:
return command.Append(info.GetUsername());
case 2:
return command.Append(info.GetPassword());
default:
return OpStatus::ERR;
}
}
///////////////////////////////////////////
// AuthenticatePlain
///////////////////////////////////////////
/***********************************************************************************
**
**
** AuthenticatePlain::AppendCommand
***********************************************************************************/
OP_STATUS ImapCommands::AuthenticatePlain::AppendCommand(OpString8& command, IMAP4& protocol)
{
OpAuthenticate info;
if (m_continuation > 0)
RETURN_IF_ERROR(protocol.GetBackend().GetLoginInfo(info));
return command.Append(m_continuation ? info.GetResponse().CStr() : "AUTHENTICATE PLAIN");
}
///////////////////////////////////////////
// Login
///////////////////////////////////////////
/***********************************************************************************
**
**
** Login::AppendCommand
***********************************************************************************/
OP_STATUS ImapCommands::Login::AppendCommand(OpString8& command, IMAP4& protocol)
{
OpAuthenticate info;
RETURN_IF_ERROR(protocol.GetBackend().GetLoginInfo(info));
return command.AppendFormat("LOGIN %s %s", info.GetUsername().CStr(), info.GetPassword().CStr());
}
|
#ifndef SERVER_AUTHORIZATIONMANAGER_H
#define SERVER_AUTHORIZATIONMANAGER_H
#include <boost/property_tree/ptree.hpp>
#include "BaseManager.h"
#include "src/server/lib/Connection/BaseConnection.h"
class AuthorizationManager: public BaseManager {
public:
~AuthorizationManager() override = default;
boost::property_tree::ptree loginUser(boost::property_tree::ptree ¶ms);
};
#endif //SERVER_AUTHORIZATIONMANAGER_H
|
#include<iostream>
using namespace std;
class base{
public:
base(){
cout<<endl<<"In BASE=1";
}
~base(){
cout<<endl<<"In BASE=1";
}
};
class derived1:public base{
public:
derived1():base(){
cout<<endl<<"In DERIVED=1";
}
~derived1(){
cout<<endl<<"In DERIVED=1";
}
};
class derived2:public derived1{
public:
derived2():derived1(){
cout<<endl<<"In DERIVED=2";
}
~derived2(){
cout<<endl<<"In DERIVED=2";
}
};
int main(){
derived2 d1;
cout<<endl;
return 0;
}
|
#pragma once
#ifndef IMAGIO_IMAGIO_H
#define IMAGIO_IMAGIO_H
namespace imagio {
void init();
int draw();
void draw_main_menu();
}
#endif
|
#include<iostream>
#include<fstream>
using namespace std;
void function(int *arr,int size,ofstream fout)
{
for(int i=0;i<size;i++)
{
cin>>*( arr + i );
}
for(int i=0; i<size-1; i++)
{
for(int j=i+1; j<size; j++)
{
if(arr[j] < arr[i])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i=0;i<size;i++)
{
cout<<*( arr + i );
fout<<*( arr + i );
}
}
int main()
{
ofstream fout;
fout.open("results_l180968.txt");
int size;
cout<<" Enter the size of the array : ";
cin>>size;
int *arr=new int[size];
function(arr,size);
}
|
#ifndef __ModuleSceneWater_H__
#define __ModuleSceneWater_H__
#include "Module.h"
#include "Animation.h"
#include "SDL_mixer/include/SDL_mixer.h"
#pragma comment(lib,"SDL_mixer/libx86/SDL2_mixer.lib")
struct SDL_Texture;
class ModuleSceneWater : public Module
{
public:
ModuleSceneWater();
~ModuleSceneWater();
void CameraPosition();
void CameraStates();
bool Start();
update_status Update();
bool CleanUp();
public:
bool right, left, up, down,down_right, waterfall, stop;
bool jump;
int timer;
float scroll,scroll2;
SDL_Texture * graphics1 = nullptr;
SDL_Texture * graphics2 = nullptr;
SDL_Texture * graphics3 = nullptr;
SDL_Texture * graphics4 = nullptr;
SDL_Texture* orientaljump = nullptr;
SDL_Rect BG_Mountain;
SDL_Rect layer_ocean_1;
SDL_Rect layer_ocean_2;
SDL_Rect layer_ocean_3;
SDL_Rect layer_ocean_4;
SDL_Rect layer_ocean_5;
SDL_Rect static_layers;
SDL_Rect Waterfall_bg;
SDL_Rect scroll_bg;
SDL_Rect sea_bg;
SDL_Rect sea_scroll;
SDL_Rect stone1;
SDL_Rect stone2;
SDL_Rect stone3;
SDL_Rect transition;
Collider * colliderbig;
Animation waterfall1;
Animation waterfall2;
Animation waterfall3;
Animation under_waterfall;
Animation candle1;
Animation candle2;
Animation candle3;
Animation wave;
Animation big_waterfall;
Animation Geniusjump;
Mix_Music* SceneWater = nullptr;
};
#endif // __ModuleSceneWater_H__
|
#include "gb_sdl.h"
#include "gb_cpu.h"
struct timeval t1, t2;
struct display display;
struct sdl_joypad joypad;
Sdl_emu_keys emu_keys;
unsigned int frames;
using namespace std;
unsigned char buttons;
unsigned char direction;
void sdl_init(Sdl_params p) {
/* video init */
SDL_SetMainReady();
SDL_Init(SDL_INIT_VIDEO);
// init window
display.screen = SDL_CreateWindow("GBcon", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, p.scale * LCD_Width,
p.scale * LCD_Height, SDL_WINDOW_OPENGL);
if (display.screen == nullptr) {
cerr << "failed to create sdl window" << endl;
return;
}
// init renderer
display.renderer = SDL_CreateRenderer(display.screen, -1, 0);
if (display.renderer == nullptr) {
cerr << "failed to create sdl renderer" << endl;
return;
}
if (p.scale > 1) {
if (SDL_RenderSetLogicalSize(display.renderer, LCD_Width, LCD_Height) < 0) {
cerr << "failed to set SDL renderer size" << endl;
}
}
// init frameBuffer
display.frameBuffer =
SDL_CreateTexture(display.renderer, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING, LCD_Width, LCD_Height);
if (display.frameBuffer == nullptr) {
cerr << "failed to create sdl texture" << endl;
return;
}
frames = 0;
/* emu keys */
joypad.up = false;
joypad.up = false;
joypad.left = false;
joypad.left = false;
joypad.start = false;
joypad.select = false;
joypad.a = false;
joypad.b = false;
/* emu control keys */
emu_keys.pause = false;
}
void sdl_uninit(void) {
SDL_DestroyTexture(display.frameBuffer);
SDL_DestroyRenderer(display.renderer);
SDL_DestroyWindow(display.screen);
SDL_Quit();
}
void sdl_set_frame(void) {
SDL_UpdateTexture(display.frameBuffer, NULL, display.pixels,
LCD_Width * sizeof(uint32_t));
SDL_RenderClear(display.renderer);
SDL_RenderCopy(display.renderer, display.frameBuffer, NULL, NULL);
SDL_RenderPresent(display.renderer);
}
int sdl_update(void) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
return 1;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_UP:
joypad.up = true;
break;
case SDLK_DOWN:
joypad.down = true;
break;
case SDLK_LEFT:
joypad.left = true;
break;
case SDLK_RIGHT:
joypad.right = true;
break;
case SDLK_RETURN:
joypad.start = true;
break;
case SDLK_RSHIFT:
joypad.select = true;
break;
case SDLK_a:
joypad.a = true;
break;
case SDLK_s:
joypad.b = true;
break;
case SDLK_ESCAPE:
return 1;
}
break;
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_UP:
joypad.up = false;
break;
case SDLK_DOWN:
joypad.down = false;
break;
case SDLK_LEFT:
joypad.left = false;
break;
case SDLK_RIGHT:
joypad.right = false;
break;
case SDLK_RETURN:
joypad.start = false;
break;
case SDLK_RSHIFT:
joypad.select = false;
break;
case SDLK_a:
joypad.a = false;
break;
case SDLK_s:
joypad.b = false;
break;
/* emu control keys */
case SDLK_p:
emu_keys.pause = !(emu_keys.pause);
break;
case SDLK_w:
emu_keys.save_ram = true;
break;
case SDLK_l:
emu_keys.load_ram = true;
break;
case SDLK_ESCAPE:
return 1;
}
break;
}
buttons = (joypad.a << 0) | (joypad.b << 1) | (joypad.select << 2) |
(joypad.start << 3);
direction = (joypad.right << 0) | (joypad.left << 1) | (joypad.up << 2) |
(joypad.down << 3);
if (event.type == SDL_QUIT)
return 1;
}
return 0;
}
void set_sdl_pixels(const unsigned char *gb_pixels) {
for (int i = 0; i < LCD_Width * LCD_Height; i++) {
display.pixels[i] = Palette[gb_pixels[i]];
}
}
|
#ifndef MEETINGGROUP_H
#define MEETINGGROUP_H
class MeetingGroup
{
public:
MeetingGroup();
private:
/* admin
* members list
* calendar
* last date revised
* meet time chosen
*/
};
#endif // MEETINGGROUP_H
|
/********************************************************************************
** Form generated from reading UI file 'fluidpropertywidget.ui'
**
** Created by: Qt User Interface Compiler version 5.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_FLUIDPROPERTYWIDGET_H
#define UI_FLUIDPROPERTYWIDGET_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDoubleSpinBox>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_FluidPropertyWidget
{
public:
QWidget *layout;
QGridLayout *gridLayout_2;
QLabel *surfaceThresholdLabel;
QLabel *viscosityLabel;
QLabel *surfaceTensionLabel;
QDoubleSpinBox *viscosity;
QDoubleSpinBox *gasStiffness;
QLabel *gasStiffnessLabel;
QDoubleSpinBox *surfaceTension;
QDoubleSpinBox *surfaceThreshold;
QFrame *line;
QSpacerItem *verticalSpacer;
void setupUi(QWidget *FluidPropertyWidget)
{
if (FluidPropertyWidget->objectName().isEmpty())
FluidPropertyWidget->setObjectName(QStringLiteral("FluidPropertyWidget"));
FluidPropertyWidget->resize(400, 300);
layout = new QWidget(FluidPropertyWidget);
layout->setObjectName(QStringLiteral("layout"));
layout->setGeometry(QRect(9, 9, 199, 128));
gridLayout_2 = new QGridLayout(layout);
gridLayout_2->setObjectName(QStringLiteral("gridLayout_2"));
surfaceThresholdLabel = new QLabel(layout);
surfaceThresholdLabel->setObjectName(QStringLiteral("surfaceThresholdLabel"));
gridLayout_2->addWidget(surfaceThresholdLabel, 5, 0, 1, 1);
viscosityLabel = new QLabel(layout);
viscosityLabel->setObjectName(QStringLiteral("viscosityLabel"));
gridLayout_2->addWidget(viscosityLabel, 3, 0, 1, 1);
surfaceTensionLabel = new QLabel(layout);
surfaceTensionLabel->setObjectName(QStringLiteral("surfaceTensionLabel"));
gridLayout_2->addWidget(surfaceTensionLabel, 4, 0, 1, 1);
viscosity = new QDoubleSpinBox(layout);
viscosity->setObjectName(QStringLiteral("viscosity"));
viscosity->setSingleStep(0.01);
gridLayout_2->addWidget(viscosity, 3, 1, 1, 1);
gasStiffness = new QDoubleSpinBox(layout);
gasStiffness->setObjectName(QStringLiteral("gasStiffness"));
gasStiffness->setMaximum(1000);
gridLayout_2->addWidget(gasStiffness, 2, 1, 1, 1);
gasStiffnessLabel = new QLabel(layout);
gasStiffnessLabel->setObjectName(QStringLiteral("gasStiffnessLabel"));
gridLayout_2->addWidget(gasStiffnessLabel, 2, 0, 1, 1);
surfaceTension = new QDoubleSpinBox(layout);
surfaceTension->setObjectName(QStringLiteral("surfaceTension"));
surfaceTension->setSingleStep(0.01);
gridLayout_2->addWidget(surfaceTension, 4, 1, 1, 1);
surfaceThreshold = new QDoubleSpinBox(layout);
surfaceThreshold->setObjectName(QStringLiteral("surfaceThreshold"));
gridLayout_2->addWidget(surfaceThreshold, 5, 1, 1, 1);
line = new QFrame(layout);
line->setObjectName(QStringLiteral("line"));
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
gridLayout_2->addWidget(line, 0, 0, 1, 2);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_2->addItem(verticalSpacer, 6, 0, 1, 1);
retranslateUi(FluidPropertyWidget);
QMetaObject::connectSlotsByName(FluidPropertyWidget);
} // setupUi
void retranslateUi(QWidget *FluidPropertyWidget)
{
FluidPropertyWidget->setWindowTitle(QApplication::translate("FluidPropertyWidget", "Form", 0));
surfaceThresholdLabel->setText(QApplication::translate("FluidPropertyWidget", "Surface Threshold", 0));
viscosityLabel->setText(QApplication::translate("FluidPropertyWidget", "Viscosity", 0));
surfaceTensionLabel->setText(QApplication::translate("FluidPropertyWidget", "Surface Tension", 0));
gasStiffnessLabel->setText(QApplication::translate("FluidPropertyWidget", "Gass Stiffness", 0));
} // retranslateUi
};
namespace Ui {
class FluidPropertyWidget: public Ui_FluidPropertyWidget {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_FLUIDPROPERTYWIDGET_H
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
//
// You will be given a vector <int> a and two ints lower and
// upper. Return the number of integers between lower and
// upper, inclusive, that are multiples of all members of a.
//
//
// DEFINITION
// Class:CommonMultiples
// Method:countCommMult
// Parameters:vector <int>, int, int
// Returns:int
// Method signature:int countCommMult(vector <int> a, int
// lower, int upper)
//
//
// CONSTRAINTS
// -a will contain between 1 and 50 elements, inclusive.
// -Each element of a will be between 1 and 100, inclusive.
// -upper will be between 1 and 2000000000 (2*109), inclusive.
// -lower will be between 1 and upper, inclusive.
//
//
// EXAMPLES
//
// 0)
// {1,2,3}
// 5
// 15
//
// Returns: 2
//
// The only numbers between 5 and 15 that are multiples of 1,
// 2 and 3 are 6 and 12.
//
// 1)
// {1,2,4,8,16,32,64}
// 128
// 128
//
// Returns: 1
//
// 128 is a multiple of all smaller powers of 2.
//
// 2)
// {2,3,5,7,11,13,17,19,23,29,31,37,41,43,49}
// 1
// 2000000000
//
// Returns: 0
//
//
//
// 3)
// {1,1,1}
// 1
// 2000000000
//
// Returns: 2000000000
//
//
//
// END CUT HERE
#line 66 "CommonMultiples.cpp"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
long long gcd(long long a,long long b) {
if (a<b) return gcd(b,a);
if (a%b==0) return b;
return gcd(b, a%b);
}
long long lcm(long long a,long long b) {
return a/gcd(a,b)*b;
}
long long get(long long no, long long lim) {
return lim / no;
}
class CommonMultiples
{
public:
int countCommMult(vector <int> a, int lower, int upper)
{
long long lc = 1;
fi(a.size()) {
if (lc > upper) return 0;
lc = lcm(lc, a[i]);
}
return get(lc, upper) - get(lc, lower - 1);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const 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() { int Arr0[] = {1,2,3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 5; int Arg2 = 15; int Arg3 = 2; verify_case(0, Arg3, countCommMult(Arg0, Arg1, Arg2)); }
void test_case_1() { int Arr0[] = {1,2,4,8,16,32,64}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 128; int Arg2 = 128; int Arg3 = 1; verify_case(1, Arg3, countCommMult(Arg0, Arg1, Arg2)); }
void test_case_2() { int Arr0[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,49}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 2000000000; int Arg3 = 0; verify_case(2, Arg3, countCommMult(Arg0, Arg1, Arg2)); }
void test_case_3() { int Arr0[] = {1,1,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 2000000000; int Arg3 = 2000000000; verify_case(3, Arg3, countCommMult(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
CommonMultiples ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include<iostream>
using namespace std;
int main()
{
int p,o,cnt;
cout<<"Enter no. of arrays you want:\n";
cin>>p;
int arr[10];
for(int i=0;i<p;i++)
{
cout<<"\nEnter no. of elements of "<<i+1<<" array:\n";
cin>>o;
cout<<"Enter its elements:\n";
for(int j=0;j<o;j++)
{
cin>>arr[j];
}
cnt=0;
for(int l=0;l<o;l++)
{
int start=arr[l];
for(int m=l;m<o;m++)
{
int end=arr[m];
if(start==1 && end==1)
{
++cnt;
}
}
}
cout<<"\nNo. of subarrays whose starting and end point is 1 of "<<i+1<<" array is: "<<cnt;
}
return 0;
}
|
// Created on: 1999-03-24
// Created by: data exchange team
// Copyright (c) 1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _STEPSelections_AssemblyComponent_HeaderFile
#define _STEPSelections_AssemblyComponent_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <STEPSelections_HSequenceOfAssemblyLink.hxx>
#include <Standard_Transient.hxx>
class StepShape_ShapeDefinitionRepresentation;
class STEPSelections_AssemblyComponent;
DEFINE_STANDARD_HANDLE(STEPSelections_AssemblyComponent, Standard_Transient)
class STEPSelections_AssemblyComponent : public Standard_Transient
{
public:
Standard_EXPORT STEPSelections_AssemblyComponent();
Standard_EXPORT STEPSelections_AssemblyComponent(const Handle(StepShape_ShapeDefinitionRepresentation)& sdr, const Handle(STEPSelections_HSequenceOfAssemblyLink)& list);
Handle(StepShape_ShapeDefinitionRepresentation) GetSDR() const;
Handle(STEPSelections_HSequenceOfAssemblyLink) GetList() const;
void SetSDR (const Handle(StepShape_ShapeDefinitionRepresentation)& sdr);
void SetList (const Handle(STEPSelections_HSequenceOfAssemblyLink)& list);
DEFINE_STANDARD_RTTIEXT(STEPSelections_AssemblyComponent,Standard_Transient)
protected:
private:
Handle(StepShape_ShapeDefinitionRepresentation) mySDR;
Handle(STEPSelections_HSequenceOfAssemblyLink) myList;
};
#include <STEPSelections_AssemblyComponent.lxx>
#endif // _STEPSelections_AssemblyComponent_HeaderFile
|
#ifndef _UpdateMoneyProc_H_
#define _UpdateMoneyProc_H_
#include "../IProcess.h"
class Table;
class Player;
class UpdateMoneyProc : public IProcess
{
public:
UpdateMoneyProc(){};
virtual ~UpdateMoneyProc(){};
virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt ) ;
virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket ,Context* pt ) ;
private:
int sendErrorMsg(ClientHandler* clientHandler, short errcode, char* errmsg);
};
#endif
|
#include "githabic.h"
#include <iostream>
using namespace std;
int task2(){
int a,b;
cout << "Used task 11 (IF) from Abramyan book" << endl;
cout << "Enter A:" << endl;
cin >> a;
cout << "Enter B:" << endl;
cin >> b;
if (a == b) {
a = 0;
b = 0;
}
else {
if (a > b) b = a;
else a = b;
}
cout << "New A = " << a << ". New B = " << b ;
}
|
#include<iostream>
void searchArray (int arr[11],int&,int&,int);
int main () {
std::cout<<"\nUnenq hetevyal zangvacy ";
int arr[11] = {1,3,5,7,9,11,13,15,17,19,21};
for (int i = 0; i < 11; ++i){
std::cout<<arr[i]<<" ";
}
std::cout<<"\n\nGreq tiv cragiry kvoroni ayn zangvaci mej - ";
int arg;
std::cin>>arg;
int f = 0; //first
int l = 10; //last
searchArray(arr,f,l,arg);
}
void searchArray (int arr[11], int &f,int &l, int arg){
int mid = (l + f) / 2;
if (l <= f && arr[l] == arg){
std::cout<<"\nNermucvac tivy gtnvum e zangvaci "<< l <<" hamari indeksum\n\n";
return;
}
if (l <= f && arr[l] != arg){
std::cout<<"\nNermucvac tivy chka zangvaci mej\n\n";
return;
}
if(arg < arr[mid]){
l = mid - 1;
} else if (arg > arr[mid]) {
f = mid + 1;
} else {
std::cout<<"\nNermucvac tivy gtnvum e zangvaci "<< mid <<" hamari indeksum\n\n";
return;
}
searchArray(arr,f,l,arg);
}
|
/**
* ====================================================================
* recorder.h
*
* Copyright (c) 2005 Nokia Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
#include "Python.h"
#include "symbian_python_ext_util.h"
#include <MdaAudioSampleEditor.h>
#include <e32std.h>
#include <Mda\Common\resource.h>
class TPyRecCallBack
{
public:
TInt StateChange(TInt aPreviousState, TInt aCurrentState, TInt aErrorCode);
public:
PyObject* iCb; // Not owned.
};
class CRecorderAdapter : public CBase, public MMdaObjectStateChangeObserver
{
public:
static CRecorderAdapter* NewL();
static CRecorderAdapter* NewLC();
~CRecorderAdapter();
public:
void PlayL(TInt aTimes, const TTimeIntervalMicroSeconds& aDuration);
void Stop();
void RecordL();
void OpenFileL(const TDesC& aFileName);
void CloseFile();
TInt State();
// Calling with larger than GetMaxVolume() or negative panics e.g. 6630
// Value is checked in Python wrapper
void SetVolume(TInt aVolume);
#if SERIES60_VERSION>12
TInt GetCurrentVolume(TInt &aVolume);
#endif /* SERIES60_VERSION */
TInt GetMaxVolume();
void Duration(TTimeIntervalMicroSeconds& aDuration);
void SetPosition(const TTimeIntervalMicroSeconds& aPosition);
void GetCurrentPosition(TTimeIntervalMicroSeconds& aPosition);
void SetCallBack(TPyRecCallBack &aCb);
public: // from MMdaObjectStateChangeObserver
void MoscoStateChangeEvent(CBase* aObject, TInt aPreviousState, TInt aCurrentState, TInt aErrorCode);
private:
void ConstructL();
private:
CMdaAudioRecorderUtility* iMdaAudioRecorderUtility;
TPyRecCallBack iCallMe;
TInt iErrorState;
TBool iCallBackSet;
};
//////////////TYPE DEFINITION
#define REC_type ((PyTypeObject*)SPyGetGlobalString("RECType"))
struct REC_object {
PyObject_VAR_HEAD
CRecorderAdapter* recorder;
TPyRecCallBack myCallBack;
TBool callBackSet;
};
//////////////ASSERTS
/*#define ASSERT_FILEOPEN \
if (self->recorder->State() == CMdaAudioRecorderUtility::ENotReady) { \
PyErr_SetString(PyExc_RuntimeError, "File not open"); \
return NULL; \
}*/
/*#define READY_TO_RECORD_OR_PLAY \
if (self->recorder->State() != CMdaAudioRecorderUtility::EOpen) { \
PyErr_SetString(PyExc_RuntimeError, "file not opened or recording/playing/not ready"); \
return NULL; \
}*/
|
// Copyright (c) Martin Schweiger
// Licensed under the MIT License
//=============================================================================
// VideoTab class
//=============================================================================
#define OAPI_IMPLEMENTATION
#include <windows.h>
#include <commctrl.h>
#include <io.h>
#include "Orbiter.h"
#include "TabVideo.h"
#include "resource.h"
using namespace std;
//-----------------------------------------------------------------------------
// DefVideoTab class
orbiter::DefVideoTab::DefVideoTab (const LaunchpadDialog *lp): LaunchpadTab (lp)
{
}
//-----------------------------------------------------------------------------
void orbiter::DefVideoTab::Create ()
{
hTab = CreateTab (IDD_PAGE_DEV);
static int item[] = {
IDC_VID_STATIC1, IDC_VID_STATIC2, IDC_VID_STATIC3, IDC_VID_STATIC5,
IDC_VID_STATIC6, IDC_VID_STATIC7, IDC_VID_STATIC8, IDC_VID_STATIC9,
IDC_VID_DEVICE, IDC_VID_ENUM, IDC_VID_STENCIL,
IDC_VID_FULL, IDC_VID_WINDOW, IDC_VID_MODE, IDC_VID_BPP, IDC_VID_VSYNC,
IDC_VID_PAGEFLIP, IDC_VID_WIDTH, IDC_VID_HEIGHT, IDC_VID_ASPECT,
IDC_VID_4X3, IDC_VID_16X10, IDC_VID_16X9, IDC_VID_INFO
};
RegisterItemPositions (item, 24);
}
//-----------------------------------------------------------------------------
void orbiter::DefVideoTab::SetConfig (Config *cfg)
{
// retrieve standard parameters from client, if available
oapi::GraphicsClient *gc = pLp->App()->GetGraphicsClient();
if (gc) {
gc->clbkRefreshVideoData();
oapi::GraphicsClient::VIDEODATA *data = gc->GetVideoData();
cfg->CfgDevPrm.bFullscreen = data->fullscreen;
cfg->CfgDevPrm.bNoVsync = data->novsync;
cfg->CfgDevPrm.bPageflip = data->pageflip;
cfg->CfgDevPrm.bTryStencil = data->trystencil;
cfg->CfgDevPrm.bForceEnum = data->forceenum;
cfg->CfgDevPrm.WinW = data->winw;
cfg->CfgDevPrm.WinH = data->winh;
cfg->CfgDevPrm.Device_idx = data->deviceidx;
cfg->CfgDevPrm.Device_mode = data->modeidx;
} else {
// should not be required
cfg->CfgDevPrm.bFullscreen = false;
cfg->CfgDevPrm.bNoVsync = true;
cfg->CfgDevPrm.bPageflip = true;
cfg->CfgDevPrm.bTryStencil = false;
cfg->CfgDevPrm.bForceEnum = true;
cfg->CfgDevPrm.WinW = 400;
cfg->CfgDevPrm.WinH = 300;
cfg->CfgDevPrm.Device_idx = 0;
cfg->CfgDevPrm.Device_mode = 0;
}
cfg->CfgDevPrm.bStereo = false; // not currently set
}
//-----------------------------------------------------------------------------
bool orbiter::DefVideoTab::OpenHelp ()
{
OpenTabHelp ("tab_video");
return true;
}
//-----------------------------------------------------------------------------
INT_PTR orbiter::DefVideoTab::TabProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
// divert video parameters to graphics clients
oapi::GraphicsClient *gc = pLp->App()->GetGraphicsClient();
if (gc)
gc->LaunchpadVideoWndProc (hWnd, uMsg, wParam, lParam);
return FALSE;
}
|
/*
* Copyright (c) 2011 Dan Wilcox <danomatika@gmail.com>
*
* BSD Simplified License.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*
* See https://github.com/danomatika/ofxAppUtils for documentation
*
*/
#pragma once
#include <ofxAppUtils.h>
class ParticleScene : public ofxScene {
public:
// set the scene name through the base class initializer
ParticleScene() : ofxScene("Particles") {
alpha = 255;
particles.setAutoRemove(false); // don't remove particles if dead
// we want setup to be called each time the scene is loaded
setSingleSetup(false);
}
// scene setup
void setup() {
timer.set();
// make some particles
for(unsigned int i = 0; i < s_maxNumParticles/2; ++i) {
particles.addParticle(new Particle());
}
}
// called when scene is entering
void updateEnter() {
// called on first enter update
if(isEnteringFirst()) {
timer.setAlarm(2000);
alpha = 0;
ofLogNotice("ParticleScene") << "update enter";
}
// calc alpha amount based on alarm time diff
alpha = 255*timer.getDiffN();
update();
// call finishedEntering() to indicate scne is done entering
if(timer.alarm()) {
finishedEntering();
alpha = 255;
ofLogNotice("ParticleScene") << "update enter done";
}
}
// normal update
void update() {
particles.update();
}
// called when scene is exiting
void updateExit() {
// called on first exit update
if(isExitingFirst()) {
timer.setAlarm(2000);
alpha = 0;
ofLogNotice("ParticleScene") << "update exit";
}
// calc alpha amount based on alarm time diff
alpha = 255*abs(timer.getDiffN()-1.0);
update();
// call finishedExiting() to indicate scene is done exiting
if(timer.alarm()) {
finishedExiting();
alpha = 0;
ofLogNotice("ParticleScene") << "update exit done";
}
}
// draw
void draw() {
ofEnableAlphaBlending();
ofFill();
ofSetRectMode(OF_RECTMODE_CENTER);
ofSetColor(255, 0, 0, alpha);
particles.draw();
ofDisableAlphaBlending();
}
// cleanup
void exit() {
particles.clear();
}
// add/remove particles
void addOneParticle() {
if(particles.size() < s_maxNumParticles) {
particles.addParticle(new Particle());
}
}
void removeOneParticle() {
if(particles.size() > 1) { // leave 1 lonely particle ...
particles.popNewestParticle();
}
}
// used for fade in and out
ofxTimer timer;
int alpha;
// particle class
class Particle : public ofxParticle {
public:
Particle() {
// get a pointer to the parent app for data access,
// here used to get the size of the render area
// you can also cast the ofxApp reference to your own derived
// class to pass custom data:
//
// TestApp* testApp = (TestApp*) (ofxGetAppPtr());
//
// NOTE: you must use "ofxGetAppPtr()" <-- note the "x",
// this is a replacement for "ofGetAppPtr()" which does not
// return the pointer to the correct app instance
//
app = ofxGetAppPtr();
// ofxParticle is derived from ofRectangle
// so these variables are built in
width = ofRandom(10, 40);
height = width;
x = ofRandom(width/2, app->getRenderWidth());
y = ofRandom(height/2, app->getRenderHeight());
vel.set(ofRandom(-5, 5), ofRandom(-5, 5));
}
void update() {
// calc new pos
x += vel.x;
y += vel.y;
// bounce on x axis
if(x < width/2) {
x = width/2;
vel.x = -vel.x;
}
else if(x > app->getRenderWidth()-width/2) {
x = app->getRenderWidth()-width/2;
vel.x = -vel.x;
}
// bounce on y axis
if(y < height/2) {
y = height/2;
vel.y = -vel.y;
}
else if(y > app->getRenderHeight()-height/2) {
y = app->getRenderHeight()-height/2;
vel.y = -vel.y;
}
}
void draw() {
ofRect(*this); // <- use this object as an ofRectangle
}
ofxApp *app;
ofVec2f vel;
};
// particle manager to wrangle our little ones
ofxParticleManager particles;
// max number of allowed particles
static const int s_maxNumParticles = 100;
};
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
//
// Division is an expensive operation for a computer to
// perform, compared to addition, subtraction, and even
// multiplication.
// The exception is when dividing by powers of 2, because
// this can be done either with a bit shift (for a fixed-
// point value) or by subtracting 1 from the exponent (for a
// floating-point value).
// In this problem, we will approximate the quotient of two
// numbers using only addition, multiplication, and division
// by powers of 2.
//
//
// Consider the following identity:
//
//
//
// 1 1 c^0 c^1 c^2
// --- = ----- = ----- + ----- + ----- + ...
// b t-c t^1 t^2 t^3
//
//
// If t is a power of 2, then the denominator of each term
// will be a power of 2.
//
//
// Given integers a, b, and terms, approximate a/b by
// computing the first terms terms of the identity above, and
// multiplying the result by a.
// Select t to be the smallest power of 2 greater than or
// equal to b.
//
//
// DEFINITION
// Class:ApproximateDivision
// Method:quotient
// Parameters:int, int, int
// Returns:double
// Method signature:double quotient(int a, int b, int terms)
//
//
// NOTES
// -Your return value must have an absolute or relative error
// less than 1e-9.
//
//
// CONSTRAINTS
// -b will be between 1 and 10000, inclusive.
// -a will be between 0 and b, inclusive.
// -terms will be between 1 and 20, inclusive.
//
//
// EXAMPLES
//
// 0)
// 2
// 5
// 2
//
// Returns: 0.34375
//
// In this case t is chosen to be 8, and therefore c is 3.
// The first two terms are 1/8 and 3/64.
//
// 1)
// 7
// 8
// 5
//
// Returns: 0.875
//
// If b is a power of two, the first term is equal to exactly
// 1/b, and all other terms are zero.
//
// 2)
// 1
// 3
// 10
//
// Returns: 0.33333301544189453
//
// 3)
// 1
// 10000
// 2
//
// Returns: 8.481740951538086E-5
//
// 4)
// 1
// 7
// 20
//
// Returns: 0.14285714285714285
//
// 5)
// 0
// 4
// 3
//
// Returns: 0.0
//
//
//
// 6)
// 50
// 50
// 1
//
// Returns: 0.78125
//
//
//
// END CUT HERE
#line 118 "ApproximateDivision.cc"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
class ApproximateDivision
{
public:
double quotient(int a, int b, int terms)
{
long long t = 1;
while (t<b) t<<=1;
long long c = t - b;
long double ans = 0.0;
fi(terms) {
ans += powl((long double)c, (long double)i) / powl((long double)t, (long double)i + 1);
}
return ans * a;
}
// 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(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 2; int Arg1 = 5; int Arg2 = 2; double Arg3 = 0.34375; verify_case(0, Arg3, quotient(Arg0, Arg1, Arg2)); }
void test_case_1() { int Arg0 = 7; int Arg1 = 8; int Arg2 = 5; double Arg3 = 0.875; verify_case(1, Arg3, quotient(Arg0, Arg1, Arg2)); }
void test_case_2() { int Arg0 = 1; int Arg1 = 3; int Arg2 = 10; double Arg3 = 0.33333301544189453; verify_case(2, Arg3, quotient(Arg0, Arg1, Arg2)); }
void test_case_3() { int Arg0 = 1; int Arg1 = 10000; int Arg2 = 2; double Arg3 = 8.481740951538086E-5; verify_case(3, Arg3, quotient(Arg0, Arg1, Arg2)); }
void test_case_4() { int Arg0 = 1; int Arg1 = 7; int Arg2 = 20; double Arg3 = 0.14285714285714285; verify_case(4, Arg3, quotient(Arg0, Arg1, Arg2)); }
void test_case_5() { int Arg0 = 0; int Arg1 = 4; int Arg2 = 3; double Arg3 = 0.0; verify_case(5, Arg3, quotient(Arg0, Arg1, Arg2)); }
void test_case_6() { int Arg0 = 50; int Arg1 = 50; int Arg2 = 1; double Arg3 = 0.78125; verify_case(6, Arg3, quotient(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
ApproximateDivision ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include <vector>
#include <iostream>
#include <limits>
using namespace std;
long long getArea() {
int count;
cin >> count;
long long minX = LLONG_MAX;
long long maxX = LLONG_MIN;
long long minY = LLONG_MAX;
long long maxY = LLONG_MIN;
for (int i = 0; i < count; ++i) {
long long x;
long long y;
cin >> x;
cin >> y;
if (x < minX) {
minX = x;
}
if (maxX < x) {
maxX = x;
}
if (y < minY) {
minY = y;
}
if (maxY < y) {
maxY = y;
}
}
long long diffX = maxX - minX;
long long diffY = maxY - minY;
if (diffX < diffY) {
return diffY * diffY;
}
return diffX * diffX;
}
int main() {
cout << getArea() << endl;
}
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int Q,x,t;
cin>>Q;
set<int> s;
set<int>::iterator itr;
for(int i = 0 ; i < Q ; i++){
cin>>t>>x;
if(t == 1) s.insert(x);
else if(t == 2) s.erase(x);
else if(t == 3)
{
itr = s.find(x);
if(itr == s.end())
cout<<"No\n";
else cout<<"Yes\n";
}
}
return 0;
}
|
#include "Leimaaja.h"
Leimaaja::Leimaaja() // Leimaaja kysyy muodostuessaan linjan numeron, jonka matkoja leimaa.
{
cout << "Anna linjan numero: ";
linja = getIntFromStream();
omistajanNimi = std::deque<string>();
}
void Leimaaja::leimaa(Matkakortti& kortti, Matkatyyppi matkatyyppi) {
if (kortti.matkusta(matkatyyppi))
{
omistajanNimi.push_front(kortti.palautaNimi()); // push_front lisää elementin luettelon etupuolelle
saldo.push_front(kortti.palautaSaldo());
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time(&tm, "%d.%m.%Y %H:%M:%S");
auto str = oss.str();
leimaajaAika.push_front(str); // Ottaa leimaus ajan luetteloon
if (omistajanNimi.size() > 5)
{
omistajanNimi.pop_back(); // pop_back poistaa viimeisen elementin luettelosta
}
if (saldo.size() > 5)
{
saldo.pop_back();
}
if (leimaajaAika.size() > 5)
{
leimaajaAika.pop_back();
}
}
}
Leimaaja &Leimaaja::operator<<(Matkakortti& kortti) // T7
{
leimaa(kortti, SISÄINEN);
return *this;
}
void Leimaaja::tulostaLeimaukset() {
cout << omistajanNimi.size() << " viimeistä leimausta linjalle " << std::to_string(linja) << "ovat;" << endl << endl;
for (int i = 0; i < omistajanNimi.size(); i++)
{
cout << "Omistaja: " << omistajanNimi[i] << ", Saldo: " << saldo[i] << ", Aika: " << leimaajaAika[i] << endl;
}
cout << endl;
}
Leimaaja::~Leimaaja()
{
}
|
#include "Arduino.h"
#define LEN_BUF 32
static uint8_t rxHead , rxTail, rxBuf[LEN_BUF];
Uart Serial;
extern void UART0_IRQHandler(void)
{
uint32_t Status = LPC_USART0->STAT;
if (Status & RXRDY) {
uint8_t p = rxHead;
rxBuf[p++] = LPC_USART0->RXDATA;
if (p >= LEN_BUF) p = 0;
if (p != rxTail)
rxHead = p;
}
}
void Uart::begin(unsigned baudrate, unsigned config)
{
/* Enable clock to USART0 */
LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 14);
/* Reset USART0 */
LPC_SYSCON->PRESETCTRL &= ~(1 << 3);
LPC_SYSCON->PRESETCTRL |= (1 << 3);
/* Set USART0 fractional baud rate generator clock divider */
LPC_SYSCON->UARTCLKDIV = LPC_SYSCON->SYSAHBCLKDIV;
LPC_USART0->CFG = config;
LPC_USART0->BRG = SystemCoreClock/16/baudrate-1;
LPC_SYSCON->UARTFRGDIV = 0xFF;
LPC_SYSCON->UARTFRGMULT = (((SystemCoreClock/16) * (LPC_SYSCON->UARTFRGDIV+1)) / (baudrate*(LPC_USART0->BRG+1))) - (LPC_SYSCON->UARTFRGDIV+1);
/* Clear all status bits */
LPC_USART0->STAT = CTS_DELTA | DELTA_RXBRK;
/* Enable USART0 interrupt */
NVIC_EnableIRQ(UART0_IRQn);
LPC_USART0->INTENSET = RXRDY | DELTA_RXBRK;
LPC_USART0->INTENCLR = TXRDY;
LPC_USART0->CFG |= UART_EN;
rxHead = rxTail = 0;
}
void Uart::end()
{
NVIC_DisableIRQ(UART0_IRQn);
}
int Uart::available()
{
int delta = rxHead - rxTail;
return (delta >= 0)? delta : delta + LEN_BUF;
}
int Uart::peek()
{
return (rxTail != rxHead)? rxBuf[rxTail] : EOF;
}
int Uart::read()
{
int byte = EOF;
if (rxTail != rxHead) {
byte = rxBuf[rxTail++];
if (rxTail >= LEN_BUF)
rxTail = 0;
}
return byte;
}
size_t Uart::write(const uint8_t data)
{
while (!(LPC_USART0->STAT & TXRDY));
LPC_USART0->TXDATA = data;
return 1;
}
void Uart::flush()
{
}
|
#include "drone.h"
#include "gps.h"
GPSSensor *gps_sensor;
Drone *drone;
void setup() {
gps_sensor = new GPSSensor();
drone = new Drone(gps_sensor);
// gps_sensor.initialize();
drone->initialize();
}
void loop() {
drone->update();
}
|
#ifndef UNIT_H
#define UNIT_H
#include <iostream>
#include <string>
#include "../states/UnitState.h"
#include "../states/Observable.h"
#include "../attacks/UnitAttack.h"
class UnitAttack;
class Observable;
class Unit {
private:
std::string unitType;
std::string unitMutation;
UnitState* uState;
UnitAttack* uAttack;
UnitState* alterEgo;
UnitAttack* alterAttack;
Observable* observersList;
public:
Unit(const std::string& type, UnitState* state, UnitAttack* attack, const std::string& mutation = MUTATION::NONE, UnitState* alEgo = nullptr, UnitAttack* alAttack = nullptr);
virtual ~Unit();
bool alterEgoOn;
virtual UnitState& getState() const;
virtual UnitState& getAlterState() const;
UnitAttack& getAttack() const;
const std::string& getUnitType() const;
const std::string& getUnitMutation() const;
Observable* getObserversList() const;
virtual void attack(Unit& enemy);
void counterAttack(Unit& enemy);
void takeDamage(int dmg);
void takeMagicDamage(int dmg);
void takeTreatment(int hp);
void creatureMutation(const std::string& mutation = MUTATION::NONE, UnitState* state = nullptr, UnitAttack* attack = nullptr, UnitState* alEgo = nullptr, UnitAttack* alAttack = nullptr);
void transform();
virtual void notifyObservers(Unit* observable);
virtual void notifyObservable(Unit* observer);
};
std::ostream& operator<<(std::ostream& out, const Unit& unit);
#endif // UNIT_H
|
//
// CarAccumulator.h
// ofApp
//
// Created by Omer Shapira on 31/03/13.
//
//
#ifndef __ofApp__Accumulator__
#define __ofApp__Accumulator__
#include <iostream>
#include "ofMain.h"
#include "ofxCV.h"
#include "Car.h"
using namespace cv;
#endif /* defined(__ofApp__Accumulator__) */
class CarAccumulator {
public:
ofVec2f upVector;
ofPolyline bounds;
void setBounds(ofPolyline newBounds);
void setUpVector (ofVec2f vec);
//tests if 1-epsilon points of a section sample fit within the accumulator.
bool isInBounds(cv::Rect rect , float epsilon, int tries);
bool isWithinAngle(Car& car);
};
|
#include <core/None.h>
#include <core/Union.h>
#include <core/is_in.h>
#include <core/sequence/concat.h>
#include <core/sequence/count.h>
#include <core/to.h>
#include <launcher/extends/core/To.h>
#include <qt/QtCore/QJsonDocument>
#include <qt/QtCore/QJsonObject>
namespace core {
Union<QJsonObject, None, bool, double> apply(QJsonObject const& a, encoding::Utf32 const& i) {
using sequence::count;
decltype(auto) j = QString::fromUcs4(&(i(0)), count(i));
if (a[j].isBool())
return a[j].toBool();
else if (a[j].isDouble())
return a[j].toDouble();
else if (a[j].isObject())
return a[j].toObject();
else
return None {};
}
Union<QJsonObject, None, bool, double> apply(QJsonDocument const& a, encoding::Utf32 const& i) {
return apply(a.object(), i);
}
template<typename ... A, typename B>
B default_val(data::Variant<A ...> const& x, B const& b) {
return is_in<B>(x) ? to<B>(x) : b;
}
launcher::Config To<launcher::Config, For<QJsonDocument>>::operator()(QJsonDocument const& x) const noexcept {
using encoding::Utf32;
auto window = default_val(apply(x, Utf32 {U"window"}), QJsonObject {});
auto window_position = default_val(apply(window, Utf32 {U"position"}), QJsonObject {});
auto window_size = default_val(apply(window, Utf32 {U"size"}), QJsonObject {});
return {
{
default_val(apply(window, Utf32 {U"bypass_window_manager_hint"}), false),
to<int>(default_val(apply(window, Utf32 {U"column_count"}), 7.)),
default_val(apply(window, Utf32 {U"ignore_close_event"}), false),
{{
to<int>(default_val(apply(window_position, Utf32 {U"x"}), 0.)),
to<int>(default_val(apply(window_position, Utf32 {U"y"}), 0.))
}},
{{
to<int>(default_val(apply(window_size, Utf32 {U"width"}), 0.)),
to<int>(default_val(apply(window_size, Utf32 {U"height"}), 0.))
}},
default_val(apply(window, Utf32 {U"translucent_background"}), true)
}
};
}
QByteArray To<QByteArray, For<data::Array<Byte>>>::operator()(data::Array<Byte> const& a) const noexcept {
using sequence::count;
return QByteArray(reinterpret_cast<char const*>(&(a(0))), count(a));
}
QJsonDocument To<QJsonDocument, For<data::Array<Byte>>>::operator()(data::Array<Byte> const& a) const noexcept {
return QJsonDocument::fromJson(to<QByteArray>(a));
}
QString To<QString, For<encoding::Utf32>>::operator()(encoding::Utf32 const& a) const noexcept {
using sequence::count;
return QString::fromUcs4(&(a(0)), count(a));
}
encoding::Utf8 To<encoding::Utf8, For<launcher::cli::error::BatOption>>::operator()(
launcher::cli::error::BatOption const& a
) const noexcept {
using encoding::Utf8;
using sequence::concat;
return concat(Utf8 {u8"bat option \""}, concat(a.option, Utf8 {u8"\""}));
}
encoding::Utf8 To<encoding::Utf8, For<launcher::cli::error::NotEnoughArguments>>::operator()(
launcher::cli::error::NotEnoughArguments const& a
) const noexcept {
using encoding::Utf8;
using sequence::concat;
return concat(Utf8 {u8"not enough arguments for \""}, concat(a.option, Utf8 {u8"\""}));
}
encoding::Utf32 To<encoding::Utf32, For<QString>>::operator()(QString const& a) const noexcept {
using data::Array;
using encoding::Utf32;
using sequence::count;
auto b = Array<char32_t> {to<Size>(a.size())};
for (decltype(auto) i = Size {0}; i < a.size(); i += 1)
b(i) = a.at(i).unicode();
return Utf32 {b};
}
/*
launcher::Config Parse<core::encoding::Json, launcher::Config>::operator()(core::encoding::Json const& x) const noexcept {
using core::encoding::Json;
core_macro_try(decltype(auto) root, Dictionary<String, Json>, x);
core_macro_try(decltype(auto) window, Dictionary<String, Json>, root(String {U"window"}));
core_macro_try(decltype(auto) window_bypass_window_manager_hint, bool, window(String {U"bypass_window_manager_hint"}));
core_macro_try(decltype(auto) window_column_count, double, window(String {U"column_count"}));
core_macro_try(decltype(auto) window_ignore_close_event, bool, window(String {U"ignore_close_event"}));
core_macro_try(decltype(auto) window_position, Array<double>, window(String {U"position"}));
core_macro_try(decltype(auto) window_size, Array<double>, window(String {U"size"}));
core_macro_try(decltype(auto) window_translucent_background, bool, window(String {U"translucent_background"}));
return {
{
window_bypass_window_manager_hint,
window_column_count,
window_ignore_close_event,
{{
window_position(0),
window_position(1),
}},
{{
window_size(0),
window_size(1),
}},
window_translucent_background
}
};
}
*/
}
|
/**
* \file
*
* \brief This file should be at the top of the file hierarchy.
*/
/// A top level structure that should be at the root of the class hierarchy.
struct top_level {
/**
* \brief Creates a top_level structure.
*
* \param name
* The name of this top-level structure. See \ref mName.
*/
top_level(const std::string &name) : mName(name) { }
/// The name of this top-level structure.
std::string mName;
};
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, count = 0, a, count_z = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a;
if (a == 5)
{
count += 1;
}
}
count_z = n - count;
count -= count % 9;
if (count_z > 0 && count > 0)
{
for (int i = 0; i < count; i++)
{
cout << 5;
}
for (int i = 0; i < count_z; i++)
{
cout << 0;
}
}
else if(count_z > 0 && count == 0)
{
cout << 0;
}
else
{
cout<<-1;
}
return 0;
}
|
#ifndef _MSG_0X05_ENTITYEQUIPMENT_STC_H_
#define _MSG_0X05_ENTITYEQUIPMENT_STC_H_
#include "mcprotocol_base.h"
#include "slotdata.h"
namespace MC
{
namespace Protocol
{
namespace Msg
{
class EntityEquipment : public BaseMessage
{
public:
EntityEquipment();
EntityEquipment(int32_t _entityId, int16_t _slot, SlotData _item);
size_t serialize(Buffer& _dst, size_t _offset);
size_t deserialize(const Buffer& _src, size_t _offset);
int32_t getEntityId() const;
int16_t getSlot() const;
SlotData getItem() const;
void setEntityId(int32_t _val);
void setSlot(int16_t _val);
void setItem(SlotData _val);
private:
int32_t _pf_entityId;
int16_t _pf_slot;
SlotData _pf_item;
};
} // namespace Msg
} // namespace Protocol
} // namespace MC
#endif // _MSG_0X05_ENTITYEQUIPMENT_STC_H_
|
/*
写到文件中的时候用另外一个线程来执行
*/
#include "XLog.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <stdarg.h>
#include <assert.h>
#include <thread>
#include <mutex>
#include <assert.h>
#include <ctime>
#include <time.h>
#include <string.h>
#include <fstream>
#ifndef PLATFORM
#if _MSC_VER
#define PLATFORM 0
#include <windows.h>
#include <io.h>
#include <shlwapi.h>
#include <process.h>
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "User32.lib")
#pragma warning(disable:4996)
#else
#define PLATFORM 1
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<pthread.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <semaphore.h>
#endif
#endif
#ifdef __APPLE__
#include <dispatch/dispatch.h>
#include <libproc.h>
#endif
typedef unsigned char uint8;
typedef unsigned short WORD;
namespace Xs
{
#ifndef _MSC_VER
#include <sys/time.h>
unsigned long Now()
{
struct timeval now;
//获得当前精确时间(1970年1月1日到现在的时间),
//执行时间(微秒) = 1000000 * (tv_end.tv_sec - tv_begin.tv_sec) + tv_end.tv_usec - tv_begin.tv_usec;
gettimeofday(&now, NULL);
return 1000 * now.tv_sec + now.tv_usec / 1000;
}
#else
#include <windows.h>
//该函数从0开始计时,返回自设备启动后的毫秒数(不含系统暂停时间)。
unsigned long Now()
{
return ::GetTickCount();
}
int gettimeofday(struct timeval * val, struct timezone *)
{
if (val)
{
LARGE_INTEGER liTime, liFreq;
QueryPerformanceFrequency(&liFreq);
QueryPerformanceCounter(&liTime);
val->tv_sec = (long)(liTime.QuadPart / liFreq.QuadPart);
val->tv_usec = (long)(liTime.QuadPart * 1000000.0 / liFreq.QuadPart - val->tv_sec * 1000000.0);
}
return 0;
}
#endif
};
void worker_write_to_disk(CxLog* _log)
{
}
CxLog* CxLog::_instance = NULL;
void xlog_println(int type, const char* txt)
{
CxLog::_instance->printf(type,"%s\n", txt);
}
//////////////////////////////////////////////////////////////////////////
std::string CxLog::getProcessID()
{
std::string pid = "0";
char buf[260] = { 0 };
#ifdef WIN32
DWORD winPID = GetCurrentProcessId();
_snprintf_s(buf, 255, 255, "%06u", winPID);
pid = buf;
#else
snprintf(buf, sizeof(buf), "%06d", getpid());
pid = buf;
#endif
return pid;
}
std::string CxLog::GetFileContent(const std::string filename)
{
std::string str;
std::ifstream inf(filename.c_str());
if (!inf.good()) return str;
inf.seekg(0, std::ifstream::end);
size_t l = inf.tellg();
inf.seekg(0, std::ifstream::beg);
str.resize(l);
inf.read(&str[0], l);
inf.close();
return str;
}
std::string CxLog::getProcessName(bool val)
{
std::string name;
char buf[260] = { 0 };
#ifdef WIN32
if (GetModuleFileNameA(NULL, buf, 259) > 0)
{
name = buf;
if (val) return name;
}
std::string::size_type pos = name.rfind("\\");
if (pos != std::string::npos)
{
name = name.substr(pos + 1, std::string::npos);
}
pos = name.rfind(".");
if (pos != std::string::npos)
{
name = name.substr(0, pos - 0);
}
#elif defined(__APPLE__)
proc_name(getpid(), buf, 260);
name = buf;
return name;
#else
#if defined(__WINDOWS__)
_snprintf_s(buf, sizeof(buf), 255, "/proc/%d/cmdline", (int)getpid());
#else
snprintf(buf, sizeof(buf), "/proc/%d/cmdline", (int)getpid());
#endif
if (val) {
name = GetFileContent(buf);
//const char** arg=&name.c_str();
//printf("%s\n",arg[0]);
//const char** arg=&(name.c_str());
//printf("%s\n",arg[0]);
//这里取第一个参数然后
//return name;
}
std::string::size_type pos = name.rfind("/");
if (pos != std::string::npos)
{
name = name.substr(pos + 1, std::string::npos);
}
#endif
return name;
}
std::string CxLog::getProcessDir()
{
std::string str = getProcessName(true);
return getPath(str);
}
int CxLog::LocalTime(struct tm* const _Tm, time_t const* const _Time)
{
#if defined(_MSC_VER)
return localtime_s(_Tm, _Time);
#else //linux
localtime_r(_Time, _Tm);
return 0;
#endif
}
CxLog::CxLog()
{
m_level = -1;
m_bDaily = true;
m_prefix = CxLog::getProcessName();
m_worker = NULL;
m_bDestory = false;
m_bFile = false;
m_tail = NULL;
}
CxLog::~CxLog()
{
ResetColor();
m_bDestory = true;
//等待写线程完成
if (m_worker) {
m_worker->join();
}
}
#if(1)
void CxLog::writeToDisk(CxLog* _log)
{
CxLogLine* _m_tail=NULL;
CxLogLine* _m_tail_tmp = NULL;
while (!_log->m_bDestory)
{
//休眠1秒
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
if(_log->m_tail==NULL) continue;
_log->m_mutex.lock();
_m_tail = _log->m_tail;
_log->m_tail = NULL;
_log->m_mutex.unlock();
//打开文件
FILE* _myFile = CxLog::OpenFile(_log->GetLogFilename().c_str());
if (_myFile)
{
while (_m_tail)
{
fwrite(_m_tail->content.c_str(), _m_tail->content.length(), 1, _myFile);
//fwrite("\r\n", 2, 1, _myFile);
_m_tail_tmp = _m_tail;
_m_tail = _m_tail->next;
delete _m_tail_tmp;
}
fclose(_myFile);
}
}
}
#else
void CxLog::writeToDisk(CxLog* _log)
{
while (!_log->m_bDestory)
{
std::queue<std::string>* _active =
_log->activeA ? &_log->logQueueA :
&_log->logQueueB;
_log->m_mutex.lock();
_log->activeA = !_log->activeA;
_log->m_mutex.unlock();
//打开文件
FILE* _myFile = CxLog::OpenFile(_log->GetLogFilename().c_str());
if (_myFile)
{
while (!_active->empty()) {
std::string s = _active->front();
_active->pop();
fwrite(s.c_str(), s.length(), 1, _myFile);
//fwrite("\r\n", 2, 1, _myFile);
}
fclose(_myFile);
}
//休眠1秒
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
#endif
std::string CxLog::GetLogFilename()
{
if (m_prefix.empty()) return getProcessName() + ".log";
if (m_bDaily)
{
char buf[16];
time_t _now = time(NULL);
struct tm tt = { 0 };
CxLog::LocalTime(&tt, &_now);
strftime(buf, 16, "%Y-%m-%d", &tt);
return m_prefix + std::string(buf) + ".log";
}
return m_prefix + ".log";
}
void CxLog::CheckLogFile(struct tm* _tm)
{
return;
//!!! FIXME
// strftime(szDT, 128,"%Y-%m-%d", _tm);
// if (m_logfname.find(szDT) == std::string::npos || m_f==NULL)
// {
// m_logfname = m_prefix + std::string(szDT) + ".log";
// if (m_f) fclose(m_f);
//#ifdef _MSC_VER
// fopen_s(&m_f, m_logfname.c_str(), "a+b");
//#else
// m_f = fopen(m_logfname.c_str(), "a+b");
//
//#endif
// assert(m_f);
// }
}
CxLog* CxLog::Instance()
{
if (_instance == NULL) {
_instance = new CxLog();
}
return _instance;
}
uint16_t NowMilliseconds()
{
#if defined(_MSC_VER)
SYSTEMTIME st;
::GetLocalTime(&st);
return st.wMilliseconds;
#else
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint16_t)(tv.tv_usec / 1000);
#endif
}
void CxLog::printf(int _level, const char* fmt, ...)
{
char buf[4096];
std::string str;
va_list ap;
if (_level < m_level) return; //不记录
//避免多线程冲突问题
std::lock_guard<std::mutex> lck(m_mutex);
//根据级别打印不同的颜色
SetColor(true, GetLevelColor(_level));
time_t _now = time(NULL);
struct tm tt = { 0 };
#if defined(_MSC_VER)
localtime_s(&tt, &_now);
// struct timeval tv;
strftime(buf, 128,
"%Y-%m-%d %H:%M:%S ", &tt);
sprintf(szDT, "[%s] %s :%0.4d ",getProcessID().c_str(),buf, NowMilliseconds());
// strcat(szDT, buf);
#else //linux
localtime_r(&_now, &tt);
//struct timeval tv;
//gettimeofday(&tv, NULL);
//sprintf(buf, ":%.4d ", (int)(tv.tv_usec/1000));
strftime(buf, 128,"%Y-%m-%d %H:%M:%S", &tt);
// strcat(szDT, buf);
sprintf(szDT, "[%s] %s :%0.4d ", getProcessID().c_str(), buf, NowMilliseconds());
#endif
//fprintf(stdout, "%s", szDT);
//va_start(ap, fmt);
//vfprintf(stdout, fmt, ap);
//va_end(ap);
//fflush(stdout);
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
str = std::string(szDT) + std::string(buf)/*+"\n"*/;
std::cout << str;
fflush(stdout);
//保存到准备写的队列中
if (m_bFile)
{
#if(1)
if (m_tail == NULL)
{
m_tail = new CxLogLine(str, NULL);
}
else {
new CxLogLine(str, m_tail);
}
#else
//这里如果队列太长了 就需要
std::queue<std::string>* _myQueue =
activeA ? &logQueueA : &logQueueB;
_myQueue->push(str);
#endif
}
if (_level == LOG_FATAL)
{
#ifdef _DEBUG
exit(-1);
#endif
}
ResetColor();
}
/*
enum Color
{
BLACK,
RED,
GREEN,
BROWN,
BLUE,
MAGENTA,
CYAN,
GREY,
YELLOW,
LRED,
LGREEN,
LBLUE,
LMAGENTA,
LCYAN,
WHITE
};
*/
Color CxLog::GetLevelColor(int _level)
{
switch (_level)
{
case LOG_LEVEL::LOG_TRACE:
return Color::LCYAN;
case LOG_LEVEL::LOG_DEBUG:
return Color::WHITE;
case LOG_LEVEL::LOG_INFO:
return Color::GREY;
case LOG_LEVEL::LOG_WARNING:
return Color::YELLOW;
case LOG_LEVEL::LOG_ERROR:
return Color::MAGENTA;
case LOG_LEVEL::LOG_FATAL:
return Color::RED;
default:
return Color::WHITE;
}
}
FILE* CxLog::OpenFile(const char* fname)
{
std::string sfname;
if (fname == NULL)
{
sfname = getProcessName()+".log"; //FIXME
}
else sfname = fname;
FILE* _myfile = NULL;
//#ifdef _MSC_VER
// fopen_s(&_myfile, sfname.c_str(), "ab");
//#else
// _myfile = fopen(sfname.c_str(), "ab");
//#endif
_myfile = fopen(sfname.c_str(), "ab");
return _myfile;
}
void CxLog::SetEnableDaily(bool _enable, const char* path)
{
SetFilenamePrefix(path ? path : getProcessName(), _enable);
}
void CxLog::SetEnableToFile(bool _enable/*=true*/,const char* path/*=""*/, bool _daily /*= false*/)
{
SetFilenamePrefix(path ? path : getProcessName(), _daily);
if (m_worker)
{
m_bDestory = true;
m_worker->join();
m_bDestory = false;
m_worker = NULL;
}
if (_enable && m_worker==NULL)
{
//打开写文件的线程
m_worker = new std::thread(CxLog::writeToDisk,this);
}
m_bFile = _enable;
}
bool CxLog::SetFilenamePrefix(std::string path,bool _daily)
{
m_bDaily = _daily;
m_prefix = path;
path =CxLog::getPath(path);
return createRecursionDir(path);
}
void CxLog::SetLevel(int _level)
{
m_level = _level;
}
void CxLog::SetColor(bool stdout_stream, int color)
{
#if PLATFORM == PLATFORM_WINDOWS
static WORD WinColorFG[Color_count] =
{
0, // BLACK
FOREGROUND_RED, // RED
FOREGROUND_GREEN, // GREEN
FOREGROUND_RED | FOREGROUND_GREEN, // BROWN
FOREGROUND_BLUE, // BLUE
FOREGROUND_RED | FOREGROUND_BLUE,// MAGENTA
FOREGROUND_GREEN | FOREGROUND_BLUE, // CYAN
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,// WHITE
// YELLOW
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
// RED_BOLD
FOREGROUND_RED | FOREGROUND_INTENSITY,
// GREEN_BOLD
FOREGROUND_GREEN | FOREGROUND_INTENSITY,
FOREGROUND_BLUE | FOREGROUND_INTENSITY, // BLUE_BOLD
// MAGENTA_BOLD
FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
// CYAN_BOLD
FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
// WHITE_BOLD
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY
};
HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
SetConsoleTextAttribute(hConsole, WinColorFG[color]);
#else
enum ANSITextAttr
{
TA_NORMAL = 0,
TA_BOLD = 1,
TA_BLINK = 5,
TA_REVERSE = 7
};
enum ANSIFgTextAttr
{
FG_BLACK = 30, FG_RED, FG_GREEN, FG_BROWN, FG_BLUE,
FG_MAGENTA, FG_CYAN, FG_WHITE, FG_YELLOW
};
enum ANSIBgTextAttr
{
BG_BLACK = 40, BG_RED, BG_GREEN, BG_BROWN, BG_BLUE,
BG_MAGENTA, BG_CYAN, BG_WHITE
};
static uint8 UnixColorFG[Color_count] =
{
FG_BLACK, // BLACK
FG_RED, // RED
FG_GREEN, // GREEN
FG_BROWN, // BROWN
FG_BLUE, // BLUE
FG_MAGENTA, // MAGENTA
FG_CYAN, // CYAN
FG_WHITE, // WHITE
FG_YELLOW, // YELLOW
FG_RED, // LRED
FG_GREEN, // LGREEN
FG_BLUE, // LBLUE
FG_MAGENTA, // LMAGENTA
FG_CYAN, // LCYAN
FG_WHITE // LWHITE
};
fprintf((stdout_stream ? stdout : stderr), "\x1b[%d%sm", UnixColorFG[color], (color >= YELLOW && color < Color_count ? ";1" : ""));
#endif
}
void CxLog::ResetColor(bool stdout_stream)
{
#if PLATFORM == PLATFORM_WINDOWS
HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
#else
fprintf((stdout_stream ? stdout : stderr), "\x1b[0m");
#endif
}
bool CxLog::isDirectory(std::string path)
{
#ifdef WIN32
return PathIsDirectoryA(path.c_str()) ? true : false;
#else
DIR * pdir = opendir(path.c_str());
if (pdir == NULL)
{
return false;
}
else
{
closedir(pdir);
pdir = NULL;
return true;
}
#endif
}
void CxLog::fixPath(std::string &path)
{
if (path.empty()) { return; }
for (std::string::iterator iter = path.begin(); iter != path.end(); ++iter)
{
if (*iter == '\\') { *iter = '/'; }
}
if (path.at(path.length() - 1) != '/') { path.append("/"); }
}
std::string CxLog::getPath(std::string path)
{
if (path.empty()) { return path; }
for (std::string::iterator iter = path.begin(); iter != path.end(); ++iter)
{
if (*iter == '\\') { *iter = '/'; }
}
int pos = (int)path.rfind("/");
if (pos>0) {
path.erase(pos, -1);
}
return path;
}
bool CxLog::createRecursionDir(std::string path)
{
if (path.length() == 0) return true;
std::string sub;
fixPath(path);
std::string::size_type pos = path.find('/');
while (pos != std::string::npos)
{
std::string cur = path.substr(0, pos - 0);
if (cur.length() > 0 && !isDirectory(cur))
{
bool ret = false;
#ifdef WIN32
ret = CreateDirectoryA(cur.c_str(), NULL) ? true : false;
#else
ret = (mkdir(cur.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0);
#endif
if (!ret)
{
return false;
}
}
pos = path.find('/', pos + 1);
}
return true;
}
|
#include <iostream>
using namespace std;
class A
{
public:
virtual void show();
void hao();
};
void A:: show()
{
cout << " in the A" << endl;
}
void A::hao()
{
cout << "hao in the A" << endl;
}
class B: public A
{
public:
virtual void show();
void hao();
};
void B::hao()
{
cout << "hao the B" <<endl;
}
void B::show()
{
cout << "in the B" << endl;
}
class Area
{
public:
int _len;
static Area *_instance;
public:
Area();
static Area *getInstance();
};
Area* Area::getInstance()
{
if(_instance == NULL)
{
_instance = new Area();
return _instance;
}
return _instance;
}
int main(int argc, char** argv)
{
A* c = new B();
c->show();
c->hao();
//A a;
//a.show();
//B b;
//b.show();
return 0;
}
|
#ifndef GAME_COMPONENT_H
#define GAME_COMPONENT_H
class GameComponent
{
public:
GameComponent();
virtual ~GameComponent();
//Function: Initialize GameComponent
//PostCondition: GameComponent Initialize
virtual void Initialize() = 0;
//Function: Update GameComponent
//PostCondition: GameComponent is updated
virtual void Update(float dt) = 0;
virtual void Render() = 0;
//Function: Release Memory
//PostCondition: Memory released
virtual void Release()=0;
private:
static GameComponent* m_instance;
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
char stringPalindrome(string A, string B);
int main(){
int n, m;
cin>>n>>m;
string w, s;
int temp = 0;
string str;
cin>>str;
while(m--){
string s;
cin>>s;
for(int i = 0; s[i] = '\0'; i++){
s[2] = temp;
s[1] = s[2];
temp = s[1];
s = w;
}
}
char ans = stringPalindrome(s, w);
if(ans == 'B'){
cout<<"YES";
}
else{
cout<<"NO";
}
return 0;
}
char stringPalindrome(string A, string B)
{
int countA[MAX_CHAR] = {0};
int countB[MAX_CHAR] = {0};
int l1 = A.length(), l2 = B.length();
for(int i=0; i<l1;i++)
countA[A[i]-'a']++;
for(int i=0; i<l2;i++)
countB[B[i]-'a']++;
for (int i=0 ;i <26;i++)
if ((countA[i] >1 && countB[i] == 0))
return 'A';
return 'B';
}
|
#include<iostream>
#include<stdlib.h>
#include<fstream>
#include<unistd.h>
#include<errno.h>
#include<sys/types.h>
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <sys/mman.h>
#include <sstream>
#include <string.h>
#include <cstring>
#include <netdb.h>
#include <stdio.h>
#include "fancyRW.h"
#include "mapboard.h"
#include <sys/wait.h>
#include<sys/socket.h>
using namespace std;
void serverdaemon() {
int sockfd; //file descriptor for the socket
int status; //for error checking
//change this # between 2000-65k before using
const char* portno="42425";
struct addrinfo hints;
memset(&hints, 0, sizeof(hints)); //zero out everything in structure
hints.ai_family = AF_UNSPEC; //don't care. Either IPv4 or IPv6
hints.ai_socktype=SOCK_STREAM; // TCP stream sockets
hints.ai_flags=AI_PASSIVE; //file in the IP of the server for me
struct addrinfo *servinfo;
if((status=getaddrinfo(NULL, portno, &hints, &servinfo))==-1)
{
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
sockfd=socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
/*avoid "Address already in use" error*/
int yes=1;
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int))==-1)
{
perror("setsockopt");
exit(1);
}
//We need to "bind" the socket to the port number so that the kernel
//can match an incoming packet on a port to the proper process
if((status=bind(sockfd, servinfo->ai_addr, servinfo->ai_addrlen))==-1)
{
perror("bind");
exit(1);
}
//when done, release dynamically allocated memory
freeaddrinfo(servinfo);
if(listen(sockfd,1)==-1)
{
perror("listen");
exit(1);
}
printf("Blocking, waiting for client to connect\n");
struct sockaddr_in client_addr;
socklen_t clientSize=sizeof(client_addr);
int new_sockfd;
do {
new_sockfd=accept(sockfd, (struct sockaddr*) &client_addr, &clientSize);
}while(new_sockfd==-1 && errno==EINTR);
if(new_sockfd==-1 && errno!=EINTR)
{
perror("accept");
exit(1);
}
//read & write to the socket
char buffer[100];
memset(buffer,0,100);
int n;
if((n=read(new_sockfd, buffer, 99))==-1)
{
perror("read is failing");
printf("n=%d\n", n);
}
printf("The client said: %s\n", buffer);
const char* message="These are the times that try men's souls.";
write(new_sockfd, message, strlen(message));
close(sockfd);
close(new_sockfd);
}
int main(int argc, char* argv[]) {
serverdaemon();
return 0;
}
|
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/*
* Runs O(a + b);
* Space O(a);
*
* The book mentions starting from the back, which would provide
* a much better solution that the one implemented below
*
*/
template <typename T>
void merge_sorted(vector<T>& sorted_a, vector<T>& sorted_b) {
queue<T> a_buffer {};
int index_a = 0;
int index_b = 0;
while ((index_a < sorted_a.size()) && (index_b < sorted_b.size())) {
if (sorted_a[index_a] <= sorted_b[index_b]) {
++index_a;
} else if (!a_buffer.empty()
&& (a_buffer.front() <= sorted_b[index_b])) {
a_buffer.push(sorted_a[index_a]);
sorted_a[index_a] = a_buffer.front();
a_buffer.pop();
++index_a;
} else {
a_buffer.push(sorted_a[index_a]);
sorted_a[index_a] = sorted_b[index_b];
++index_a;
++index_b;
}
}
while (!a_buffer.empty() && (index_b < sorted_b.size())) {
if (a_buffer.front() <= sorted_b[index_b]) {
sorted_a.push_back(a_buffer.front());
a_buffer.pop();
} else {
sorted_a.push_back(sorted_b[index_b]);
++index_b;
}
}
while (!a_buffer.empty()) {
sorted_a.push_back(a_buffer.front());
a_buffer.pop();
}
while (index_b < sorted_b.size()) {
sorted_a.push_back(sorted_b[index_b]);
index_b++;
}
}
void run_merge_sorted(vector<int> a, vector<int> b) {
a.reserve(a.size() + b.size());
merge_sorted(a, b);
for (auto& val : a) {
cout << val << ", ";
}
cout << "\n" << endl;
}
int main() {
run_merge_sorted({1, 2, 3, 4, 5}, {2, 2, 4, 4, 6});
run_merge_sorted({}, {1, 2, 3});
run_merge_sorted({1, 2, 3}, {});
}
|
//
// Created by fab on 27/02/2020.
//
#ifndef DUMBERENGINE_CUBE_HPP
#define DUMBERENGINE_CUBE_HPP
class Cube
{
public :
enum CubeType
{
CUBE_HERBE = 1,
CUBE_TERRE,
CUBE_BOIS,
CUBE_PIERRE,
CUBE_EAU,
CUBE_VERRE,
CUBE_PLANCHE_01,
CUBE_PLANCHE_02,
CUBE_PLANCHE_03,
CUBE_PLANCHE_04,
CUBE_PLANCHE_05,
CUBE_PLANCHE_06,
CUBE_BRIQUES,
CUBE_DALLES_01,
CUBE_DALLES_02,
CUBE_DALLES_03,
CUBE_DALLES_04,
CUBE_SABLE_01,
CUBE_SABLE_02,
CUBE_LAINE_01,
CUBE_LAINE_02,
CUBE_LAINE_03,
CUBE_LAINE_04,
CUBE_LAINE_05,
CUBE_LAINE_06,
CUBE_LAINE_07,
CUBE_LAINE_08,
CUBE_LAINE_09,
CUBE_LAINE_10,
CUBE_LAINE_11,
CUBE_LAINE_12,
CUBE_LAINE_13,
CUBE_LAINE_14,
CUBE_LAINE_15,
CUBE_LAINE_16,
CUBE_CUSTOM_IMAGE,
CUBE_LIVRE,
CUBE_TRONC,
CUBE_BRANCHES,
CUBE_AIR,
CUBE_STAIRS,
CUBE_NB_TYPES
}; //Limité à 128 types
static const int CUBE_DRAW_BIT = 0x80;
public :
unsigned char _Code; // only the first part is used, the second part is the flag
public :
static const int CUBE_SIZE = 1;
Cube()
{
setDraw(false);
setType(CUBE_AIR);
}
void setType(CubeType type)
{
bool draw = getDraw();
_Code = (unsigned char) type;
setDraw(draw);
}
CubeType getType()
{
return (CubeType) (_Code & ~CUBE_DRAW_BIT);
}
bool getDraw()
{
return _Code & CUBE_DRAW_BIT ? true : false;
}
void setDraw(bool draw)
{
if (draw)
_Code |= CUBE_DRAW_BIT;
else
_Code &= ~CUBE_DRAW_BIT;
}
bool isSolid()
{
CubeType type = getType();
return (type != CUBE_AIR && type != CUBE_EAU);
}
bool isPickable()
{
CubeType type = getType();
return (type != CUBE_AIR);
}
bool isOpaque()
{
CubeType type = getType();
return (type != CUBE_AIR && type != CUBE_EAU && type != CUBE_VERRE && type != CUBE_BRANCHES);
}
bool isTransparent(void)
{
CubeType type = getType();
return (type == CUBE_AIR || type == CUBE_EAU || type == CUBE_VERRE);
}
bool isCutoff(void)
{
CubeType type = getType();
return (type == CUBE_BRANCHES);
}
bool isGround(void)
{
CubeType type = getType();
return (type == CUBE_HERBE || type == CUBE_TERRE || type == CUBE_EAU || type == CUBE_BOIS ||
type == CUBE_PIERRE);
}
unsigned char getRawCode()
{
return _Code;
}
void setRawCode(unsigned char code)
{
_Code = code;
}
static bool isManipulable(CubeType type)
{
switch (type)
{
case CUBE_HERBE:
case CUBE_TERRE:
case CUBE_BOIS:
case CUBE_PIERRE:
case CUBE_EAU:
case CUBE_VERRE:
case CUBE_STAIRS:
case CUBE_PLANCHE_01:
case CUBE_PLANCHE_02:
case CUBE_PLANCHE_03:
case CUBE_PLANCHE_04:
case CUBE_PLANCHE_05:
case CUBE_PLANCHE_06:
case CUBE_BRIQUES:
case CUBE_DALLES_01:
case CUBE_DALLES_02:
case CUBE_DALLES_03:
case CUBE_DALLES_04:
case CUBE_SABLE_01:
case CUBE_SABLE_02:
case CUBE_LAINE_01:
case CUBE_LAINE_02:
case CUBE_LAINE_03:
case CUBE_LAINE_04:
case CUBE_LAINE_05:
case CUBE_LAINE_06:
case CUBE_LAINE_07:
case CUBE_LAINE_08:
case CUBE_LAINE_09:
case CUBE_LAINE_10:
case CUBE_LAINE_11:
case CUBE_LAINE_12:
case CUBE_LAINE_13:
case CUBE_LAINE_14:
case CUBE_LAINE_15:
case CUBE_LAINE_16:
case CUBE_CUSTOM_IMAGE:
case CUBE_LIVRE:
case CUBE_TRONC:
return true;
}
return false;
}
};
#endif //DUMBERENGINE_CUBE_HPP
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "MWSmoothCameraComponent.h"
#include "Camera/CameraComponent.h"
#include "GameFramework/SpringArmComponent.h"
UMWSmoothCameraComponent::UMWSmoothCameraComponent()
{
PrimaryComponentTick.bCanEverTick = true;
PrimaryComponentTick.bStartWithTickEnabled = true;
// Set our default values
CameraSpeed = 1000.0f;
CameraZoomSpeed = 20.0f;
CameraZoomPerUnit = 300.0f;
MinCameraDistance = 500.0f;
MaxCameraDistance = 2500.0f;
CameraScrollThreshold = 20.0f;
TargetCameraZoomDistance = 1500.0f;
// Create Camera Spring Arm
CameraSpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraArm"));
CameraSpringArm->SetupAttachment(this);
// Camera lag enables smooth panning
CameraSpringArm->bEnableCameraLag = true;
CameraSpringArm->CameraLagSpeed = 10.0;
CameraSpringArm->TargetArmLength = TargetCameraZoomDistance;
// Don't use pawn movement to move the camera, we are overriding all movement on the pawn (pawn will not move on its own)
CameraSpringArm->bInheritPitch = false;
CameraSpringArm->bInheritRoll = false;
CameraSpringArm->bInheritYaw = false;
CameraSpringArm->SetRelativeRotation(FRotator(295,0,0));
// Create Camera
Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
Camera->SetupAttachment(CameraSpringArm, USpringArmComponent::SocketName);
// Overrides motion blur for crisp movement
Camera->PostProcessSettings.bOverride_MotionBlurAmount = true;
Camera->PostProcessSettings.MotionBlurAmount = 0;
Camera->PostProcessSettings.MotionBlurMax = 0;
}
// Called when the game starts
void UMWSmoothCameraComponent::BeginPlay()
{
Super::BeginPlay();
}
/** Sets the axis based on the configured input */
void UMWSmoothCameraComponent::MoveCameraLeftRight(const float Value)
{
CameraLeftRightAxisValue = Value;
}
/** Sets the axis based on the configured input */
void UMWSmoothCameraComponent::MoveCameraUpDown(const float Value)
{
CameraUpDownAxisValue = Value;
}
/** Sets the axis based on the configured input */
void UMWSmoothCameraComponent::ZoomCamera(const float Value)
{
// Axis will be zero when there is no active zoom direction
if (FMath::IsNearlyZero(Value))
{
return;
}
float ZoomAmount;
// Positive value means we are zooming out, while negative value means we are zooming in
if (Value > 0) {
ZoomAmount = CameraZoomPerUnit;
}
else {
ZoomAmount = -CameraZoomPerUnit;
}
// Update the target distance within our bounds
TargetCameraZoomDistance = FMath::Clamp(CameraSpringArm->TargetArmLength + ZoomAmount, MinCameraDistance, MaxCameraDistance);
}
/** Deactivates rotation mode */
void UMWSmoothCameraComponent::RotateCameraReleased()
{
bShouldRotateCamera = false;
}
/** Activates rotation mode and begins tracking mouse position */
void UMWSmoothCameraComponent::RotateCameraPressed()
{
bShouldRotateCamera = true;
APlayerController* PlayerController = GetPlayerControllerForOwningPawn();
if (!ensure(PlayerController != nullptr))
{
return;
}
PlayerController->GetMousePosition(RotateCameraMouseStart.X, RotateCameraMouseStart.Y);
}
APlayerController* UMWSmoothCameraComponent::GetPlayerControllerForOwningPawn() const
{
APawn* Pawn = GetOwningPawn();
if (!ensure(Pawn != nullptr))
{
return nullptr;
}
return Pawn->GetController<APlayerController>();
}
APawn* UMWSmoothCameraComponent::GetOwningPawn() const
{
APawn* Pawn = GetOwner<APawn>();
if (!ensure(Pawn != nullptr))
{
return nullptr;
}
return Pawn;
}
void UMWSmoothCameraComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
APawn* Pawn = GetOwningPawn();
if (!ensure(Pawn != nullptr))
{
return;
}
float MouseX;
float MouseY;
APlayerController* PlayerController = GetPlayerControllerForOwningPawn();
if (!ensure(PlayerController != nullptr))
{
return;
}
int ViewportSizeX, ViewportSizeY;
// Get the current size of the viewport (depending on the game settings, the player might be able to resize the game window while playing)
PlayerController->GetViewportSize(ViewportSizeX,ViewportSizeY);
// Recalculate our right and top borders
const float ScrollBorderRight = ViewportSizeX - CameraScrollThreshold;
const float ScrollBorderTop = ViewportSizeY - CameraScrollThreshold;
// Only respond to viewport edge scrolling if we are not currently rotating the camera
// Value closer to -1.0 or 1.0 means full scroll speed, in between means a slower scroll speed (we start scrolling slowly and then speed up the closer your mouse gets to the edge
if (PlayerController->GetMousePosition(MouseX, MouseY) && !bShouldRotateCamera)
{
// If we are scrolling from left edge
if (MouseX <= CameraScrollThreshold)
{
CameraLeftRightAxisValue -= 1 - (MouseX / CameraScrollThreshold);
}
//If we are scrolling from right edge
else if (MouseX >= ScrollBorderRight)
{
CameraLeftRightAxisValue += (MouseX - ScrollBorderRight) / CameraScrollThreshold;
}
// If we are scrolling from bottom edge
if (MouseY <= CameraScrollThreshold)
{
CameraUpDownAxisValue += 1 - (MouseY / CameraScrollThreshold);
}
// If we are scrolling from top edge
else if (MouseY >= ScrollBorderTop)
{
CameraUpDownAxisValue -= (MouseY - ScrollBorderTop) / CameraScrollThreshold;
}
}
// Keep our values within our axis bounds
CameraLeftRightAxisValue = FMath::Clamp(CameraLeftRightAxisValue, -1.0f, +1.0f);
CameraUpDownAxisValue = FMath::Clamp(CameraUpDownAxisValue, -1.0f, +1.0f);
FVector Location = Pawn->GetActorLocation();
// Update the left/right movement based on the direction to the right of where we are facing
Location += CameraSpringArm->GetRightVector() * CameraSpeed * CameraLeftRightAxisValue * DeltaTime;
// Update the forward/backwards movement based on the yaw rotation, **ignoring pitch** so the camera remains level as it moves (looking down would otherwise pan the camera forward and down)
Location += FRotationMatrix(FRotator(0, CameraSpringArm->GetRelativeRotation().Yaw, 0)).GetScaledAxis(EAxis::X) * CameraSpeed * CameraUpDownAxisValue * DeltaTime;
// TODO add camera bounds to level
//if (!CameraBoundsVolume || CameraBoundsVolume->EncompassesPoint(Location))
//{
// Update the pawn's location and the camera will follow
Pawn->SetActorLocation(Location);
//}
// Zoom in or out as necessary
if (!FMath::IsNearlyEqual(CameraSpringArm->TargetArmLength, TargetCameraZoomDistance, 0.5f))
{
// This allows us to smoothly zoom to our desired target arm length over time
CameraSpringArm->TargetArmLength = FMath::FInterpTo(CameraSpringArm->TargetArmLength, TargetCameraZoomDistance,
DeltaTime, CameraZoomSpeed);
}
// If the middle mouse button is down we will be rotating the camera as the mouse moves
if (bShouldRotateCamera)
{
FVector2D MouseLocation;
PlayerController->GetMousePosition(MouseLocation.X, MouseLocation.Y);
// Get how much we have moved since the last frame/rotate start
const float XPercent = (MouseLocation.X - RotateCameraMouseStart.X) / ViewportSizeX;
const float YPercent = (RotateCameraMouseStart.Y - MouseLocation.Y) / ViewportSizeY;
// Get the current rotation within -180 to 180 degrees, instead of 0-360
const FRotator CurrentRot = CameraSpringArm->GetRelativeRotation().GetNormalized();
// Update our rotation based on 100% movement equals 180 degrees rotation, limiting pitch to near vertical to limit issues at -90 and 90 degrees
CameraSpringArm->SetRelativeRotation(FRotator(FMath::Clamp<float>(CurrentRot.Pitch + (YPercent * 180), -88, 88),
CurrentRot.Yaw + (XPercent * 180), 0));
// Update the "last frame" mouse location
RotateCameraMouseStart = MouseLocation;
}
}
|
//: C15:PureVirtualDestructors.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Czysto wirtualny destruktor
// wymaga zdefiniowania kodu
#include <iostream>
using namespace std;
class Pet {
public:
virtual ~Pet() = 0;
};
Pet::~Pet() {
cout << "~Pet()" << endl;
}
class Dog : public Pet {
public:
~Dog() {
cout << "~Dog()" << endl;
}
};
int main() {
Pet* p = new Dog; // Rzutowanie w gore
delete p; // Wywolanie wirtualnego destruktora
} ///:~
|
#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_set>
using namespace std;
struct Trie
{
Trie* child[26];
string word = "";
Trie() {
for (int i = 0; i < 26; i++)
child[i] = nullptr;
}
};
class Solution {
public:
vector<string> res;
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
//基本思想:前缀树+深度优先搜索递归回溯
//1、前缀树的结构是R个指向子结点的链接,其中每个链接对应字母表数据集中的一个字母,
//和一个字符串字段当截止该节点构成一个单词就将该节点的字符串字段置为该单词,
//这样如果截止该节点字符串字段不为空说明遍历截止该节点构成一个单词可以直接加入res。之前的做法是给dfs额外一个string形参保存当前dfs遍历过的字符,减慢函数调用速度
//2、遍历到当前节点构成一个单词加入res后,置该节点字符串字段为空,这样防止res出现重复单词。之前的做法是设置res为set,不如这个方法好,这个方法可以避免遍历board中重复单词。
//3、对于board中一次dfs已访问过的字符不能再次访问解决方法:置已访问过的board中字符为'*',dfs结束后再恢复。之前做法是设置visited二维数组,这样增加了dfs形参个数占用更多内存。
//4、注意截止当前节点已经构成一个单词后,可以继续dfs搜索其他单词,因为可能出现一个单词是另一个单词的前缀情况,不能提前结束dfs。
Trie* t = new Trie();
//创建前缀树,将words中所有单词加入前缀树
for (int i = 0; i < words.size(); i++)
{
Trie* cur = t;
for (int j = 0; j < words[i].size(); j++)
{
if (cur->child[words[i][j] - 'a'] == nullptr)
cur->child[words[i][j] - 'a'] = new Trie();
cur = cur->child[words[i][j] - 'a'];
}
cur->word = words[i];
}
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[i].size(); j++)
{
dfs(board, t, i, j);
}
}
return res;
}
void dfs(vector<vector<char>>& board, Trie* t,int i ,int j)
{
if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size())
return;
char c = board[i][j];
if (c == '*' || t->child[c-'a']==nullptr)
return;
t = t->child[c - 'a'];
if (t->word != "")
{
res.push_back(t->word);
t->word = "";
}
board[i][j] = '*';
dfs(board, t, i + 1, j);
dfs(board, t, i - 1, j);
dfs(board, t, i, j + 1);
dfs(board, t, i, j - 1);
board[i][j] = c;
return;
}
};
int main()
{
Solution solute;
vector<vector<char>> board = { {'a','b'},{'a','a'} };
vector<string> words = { "aaab","aaa" };
vector<string> res = solute.findWords(board, words);
for_each(res.begin(), res.end(), [](const auto v) {cout << v << endl; });
return 0;
}
|
#ifndef _SCENE_H_
#define _SCENE_H_
#include "triangle.h"
#include <vector>
using namespace std;
class Scene {
public:
void loadScene(char* file);
void loadBlend(const char*file);
void getpoint(string a, int(&b)[3]);
int Scene::getBlend(string name);
void addLight(PointLight light);
vector<Vector> pointList;
vector<Vector> normalList;
vector<Triangle> triangleList;
vector<Blend> blendColor;
vector<PointLight> lightList;
Color amblight;
Sphere sphere;
};
#endif // !_SCENE_H_
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <vector>
#include <algorithm>
#include <math.h>
#define pb push_back
using namespace std;
struct toado {
int h, c;
};
toado huong[8] = {-1, 0
, -1, 1
, 0, 1
, 1, 1
, 1, 0
, 1, -1
, 0, -1
, -1, -1};
vector <toado> vect;
char s[111][111];
int nhang, ncot, ndiem;
int d[111][111];
void input() {
toado temp;
scanf("%d %d %d", &nhang, &ncot, &ndiem);
for (int i = 0; i < nhang; i++) {
scanf("%s", &s[i]);
for (int j = 0; j < ncot; j++) {
printf("%c", s[i][j]);
}
printf("\n");
}
}
toado doMove(toado cur, int hg) {
toado next;
next.h = cur.h + huong[hg].h;
next.c = cur.c + huong[hg].c;
return next;
}
bool isOut(toado cur) {
if (cur.h < 0 || cur.h >= nhang)
return 1;
if (cur.c < 0 || cur.c >= ncot)
return 1;
return 0;
}
void loang(int hang, int cot) {
int dau = -1;
int cuoi = 0;
q[0] = cur;
d[]
}
void solve() {
for (int i = 1; i < nhang; i++) {
for (int j = 1; j < ncot; j++) {
d[i][j] = 0;
}
}
for (int i = 1; i < nhang; i++) {
for (int j = 1; j < ncot; j++) {
if (d[i][j] == 0) {
loang(i, j);
}
}
}
}
void output() {
}
int main()
{
freopen("wesland1.inp", "r", stdin);
int ntest;
scanf("%d", &ntest);
for (int itest = 0; itest < ntest; itest++) {
input();
solve();
output();
}
return 0;
}
|
#include "log_server.hpp"
#include "scene/scened.hpp"
#include "net/stream.hpp"
#include "utils/service_thread.hpp"
#include "utils/exception.hpp"
#define SLOGSERVER_TLOG __TLOG << setw(20) << "[SLOGSERVER] "
#define SLOGSERVER_DLOG __DLOG << setw(20) << "[SLOGSERVER] "
#define SLOGSERVER_ILOG __ILOG << setw(20) << "[SLOGSERVER] "
#define SLOGSERVER_ELOG __ELOG << setw(20) << "[SLOGSERVER] "
namespace nora {
namespace scene {
log_server::log_server(const string& name) : name_(name) {
}
void log_server::static_init() {
}
string log_server::base_name() {
return "log_server";
}
}
}
|
// Copyright Ralf W. Grosse-Kunstleve 2002-2004. 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)
#include <boost/python/class.hpp>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <iostream>
#include <string>
#include <vector>
namespace { // Avoid cluttering the global namespace.
typedef std::vector<int> tvi;
struct Foo
{
int32_t a;
std::string b;
tvi vi;
bool operator==(Foo const& f) const { return f.a == a; }
};
// A friendly class.
typedef std::vector<Foo> VecFoo;
class hello
{
public:
hello(const std::string& country) { this->country = country; }
std::string greet() const { return "Hello from " + country; }
Foo get_foo()const
{
Foo foo;
foo.a = 123;
foo.b = country;
return foo;
}
public:
std::string country;
VecFoo vf;
};
// A function taking a hello object as an argument.
std::string invite(const hello& w) {
return w.greet() + "! Please come soon!";
}
struct FooConvert
{
/*
static PyObject* convert(Foo const & f)
{
//boost::python::object* obj = new boost::python::object(f);
boost::python::list* pylist = new boost::python::list;
pylist->append(f.a);
pylist->append(f.b);
return pylist->ptr();
//return boost::python::incref(pylist.ptr());
}
static PyObject* convert(Foo const & f)
{
boost::python::dict * pydict = new boost::python::dict;
pydict->setdefault("a", f.a);
pydict->setdefault("b", f.b);
return pydict->ptr();
}
*/
static PyObject* convert(Foo const & f)
{
boost::python::object * pyobj = new boost::python::object(f);
return pyobj->ptr();
}
};
}
struct VecFooConvert
{
static PyObject* convert(const VecFoo& vf)
{
boost::python::list pylist;
for(auto& f : vf)
{
pylist.append(f);
}
return boost::python::incref(pylist.ptr());
}
};
struct X // a container element
{
std::string s;
/*
X():s("default") {}
X(std::string s):s(s) {}
std::string repr() const { return s; }
void reset() { s = "reset"; }
void foo() { s = "foo"; }
bool operator!=(X const& x) const { return s != x.s; }
*/
bool operator==(X const& x) const { return s == x.s; }
};
typedef std::vector<X> VecX;
VecFoo getVecFoo()
{
VecFoo vf;
Foo f;
f.a = 1;
f.b = "1";
vf.push_back(f);
f.a = 2;
f.b = "1123";
vf.push_back(f);
return vf;
}
BOOST_PYTHON_MODULE(extending)
{
using namespace boost::python;
class_<tvi>("tvi").def(vector_indexing_suite<tvi>());
//boost::python::to_python_converter<Foo, FooConvert>();
class_<Foo>("Foo")
.def_readwrite("a", &Foo::a)
.def_readwrite("b", &Foo::b)
.def_readwrite("vi", &Foo::vi);
//class_<VecFoo>("VecFoo").def(vector_indexing_suite<VecFoo>());
class_<VecX>("VecX").def(vector_indexing_suite<VecX>());
boost::python::to_python_converter<VecFoo, VecFooConvert>();
def("getVecFoo", getVecFoo);
class_<hello>("hello", init<std::string>())
// Add a regular member function.
.def("greet", &hello::greet)
// Add invite() as a member of hello!
.def("invite", invite)
.def("get_foo", &hello::get_foo)
.def_readwrite("vf", &hello::vf);
;
// Also add invite() as a regular function to the module.
def("invite", invite);
}
|
// Created on: 1997-10-22
// Created by: Philippe MANGIN
// 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 _PLib_HermitJacobi_HeaderFile
#define _PLib_HermitJacobi_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <math_Matrix.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <PLib_Base.hxx>
#include <Standard_Integer.hxx>
#include <GeomAbs_Shape.hxx>
class PLib_JacobiPolynomial;
class PLib_HermitJacobi;
DEFINE_STANDARD_HANDLE(PLib_HermitJacobi, PLib_Base)
//! This class provides method to work with Jacobi Polynomials
//! relatively to an order of constraint
//! q = myWorkDegree-2*(myNivConstr+1)
//! Jk(t) for k=0,q compose the Jacobi Polynomial base relatively to the weigth W(t)
//! iorder is the integer value for the constraints:
//! iorder = 0 <=> ConstraintOrder = GeomAbs_C0
//! iorder = 1 <=> ConstraintOrder = GeomAbs_C1
//! iorder = 2 <=> ConstraintOrder = GeomAbs_C2
//! P(t) = H(t) + W(t) * Q(t) Where W(t) = (1-t**2)**(2*iordre+2)
//! the coefficients JacCoeff represents P(t) JacCoeff are stored as follow:
//! @code
//! c0(1) c0(2) .... c0(Dimension)
//! c1(1) c1(2) .... c1(Dimension)
//!
//! cDegree(1) cDegree(2) .... cDegree(Dimension)
//! @endcode
//! The coefficients
//! @code
//! c0(1) c0(2) .... c0(Dimension)
//! c2*ordre+1(1) ... c2*ordre+1(dimension)
//! @endcode
//! represents the part of the polynomial in the
//! Hermit's base: H(t)
//! @code
//! H(t) = c0H00(t) + c1H01(t) + ...c(iordre)H(0 ;iorder)+ c(iordre+1)H10(t)+...
//! @endcode
//! The following coefficients represents the part of the
//! polynomial in the Jacobi base ie Q(t)
//! @code
//! Q(t) = c2*iordre+2 J0(t) + ...+ cDegree JDegree-2*iordre-2
//! @endcode
class PLib_HermitJacobi : public PLib_Base
{
public:
//! Initialize the polynomial class
//! Degree has to be <= 30
//! ConstraintOrder has to be GeomAbs_C0
//! GeomAbs_C1
//! GeomAbs_C2
Standard_EXPORT PLib_HermitJacobi(const Standard_Integer WorkDegree, const GeomAbs_Shape ConstraintOrder);
//! This method computes the maximum error on the polynomial
//! W(t) Q(t) obtained by missing the coefficients of JacCoeff from
//! NewDegree +1 to Degree
Standard_EXPORT Standard_Real MaxError (const Standard_Integer Dimension, Standard_Real& HermJacCoeff, const Standard_Integer NewDegree) const;
//! Compute NewDegree <= MaxDegree so that MaxError is lower
//! than Tol.
//! MaxError can be greater than Tol if it is not possible
//! to find a NewDegree <= MaxDegree.
//! In this case NewDegree = MaxDegree
Standard_EXPORT void ReduceDegree (const Standard_Integer Dimension, const Standard_Integer MaxDegree, const Standard_Real Tol, Standard_Real& HermJacCoeff, Standard_Integer& NewDegree, Standard_Real& MaxError) const Standard_OVERRIDE;
Standard_EXPORT Standard_Real AverageError (const Standard_Integer Dimension, Standard_Real& HermJacCoeff, const Standard_Integer NewDegree) const;
//! Convert the polynomial P(t) = H(t) + W(t) Q(t) in the canonical base.
Standard_EXPORT void ToCoefficients (const Standard_Integer Dimension, const Standard_Integer Degree, const TColStd_Array1OfReal& HermJacCoeff, TColStd_Array1OfReal& Coefficients) const Standard_OVERRIDE;
//! Compute the values of the basis functions in u
Standard_EXPORT void D0 (const Standard_Real U, TColStd_Array1OfReal& BasisValue) Standard_OVERRIDE;
//! Compute the values and the derivatives values of
//! the basis functions in u
Standard_EXPORT void D1 (const Standard_Real U, TColStd_Array1OfReal& BasisValue, TColStd_Array1OfReal& BasisD1) Standard_OVERRIDE;
//! Compute the values and the derivatives values of
//! the basis functions in u
Standard_EXPORT void D2 (const Standard_Real U, TColStd_Array1OfReal& BasisValue, TColStd_Array1OfReal& BasisD1, TColStd_Array1OfReal& BasisD2) Standard_OVERRIDE;
//! Compute the values and the derivatives values of
//! the basis functions in u
Standard_EXPORT void D3 (const Standard_Real U, TColStd_Array1OfReal& BasisValue, TColStd_Array1OfReal& BasisD1, TColStd_Array1OfReal& BasisD2, TColStd_Array1OfReal& BasisD3) Standard_OVERRIDE;
//! returns WorkDegree
Standard_Integer WorkDegree() const Standard_OVERRIDE;
//! returns NivConstr
Standard_Integer NivConstr() const;
DEFINE_STANDARD_RTTIEXT(PLib_HermitJacobi,PLib_Base)
protected:
private:
//! Compute the values and the derivatives values of
//! the basis functions in u
Standard_EXPORT void D0123 (const Standard_Integer NDerive, const Standard_Real U, TColStd_Array1OfReal& BasisValue, TColStd_Array1OfReal& BasisD1, TColStd_Array1OfReal& BasisD2, TColStd_Array1OfReal& BasisD3);
math_Matrix myH;
Handle(PLib_JacobiPolynomial) myJacobi;
TColStd_Array1OfReal myWCoeff;
};
#include <PLib_HermitJacobi.lxx>
#endif // _PLib_HermitJacobi_HeaderFile
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
#include <map>
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>())
#define debug(x) std::cerr << (x) << std::endl;
#define roll(x) for (auto itr : x) { debug(itr); }
template <class T> inline void chmax(T &ans, T t) { if (t > ans) ans = t;}
template <class T> inline void chmin(T &ans, T t) { if (t < ans) ans = t;}
#include <vector>
using namespace std;
/* Union-Find-Tree */
/* 必ず要素数をコンストラクタに入れること */
template <class T = long long>
class Union_Find {
using size_type = std::size_t;
using _Tp = T;
public:
vector<_Tp> par;
vector<_Tp> rnk;
// 親の根を返す。値の変更は認めない。
const _Tp & operator[] (size_type child) {
find(child);
return par[child];
}
Union_Find (_Tp n) {
par.resize(n), rnk.resize(n);
for (int i = 0; i < n; ++i) {
par[i] = i;
rnk[i] = 0;
}
}
// 木の根を求める
_Tp find(_Tp x) {
if (par[x] == x)
return x;
else
return par[x] = find(par[x]);
}
// xとyの属する集合を併合
void merge(_Tp x, _Tp y) {
x = find(x);
y = find(y);
if (x == y) return;
if (rnk[x] < rnk[y]) {
par[x] = y;
} else {
par[y] = x;
if (rnk[x] == rnk[y]) rnk[x]++;
}
}
// xとyが同じ集合に属するか否か
bool same(_Tp x, _Tp y) {
return find(x) == find(y);
}
};
int main() {
int n,k,l;
cin >> n >> k >> l;
Union_Find<long long> uf_road(n+1), uf_train(n+1);
int r,s;
rep(i,k) {
cin >> r >> s;
uf_road.merge(r, s);
}
rep(i,l) {
cin >> r >> s;
uf_train.merge(r, s);
}
vector<pair<int,int> > com;
map<pair<int,int>, int> mp;
for (int i = 1; i <= n; ++i) {
int a, b;
a = uf_road[i];
b = uf_train[i];
com.push_back(make_pair(a,b));
mp[make_pair(a,b)] += 1;
}
for (int i = 0; i < n; ++i) {
cout << mp[com[i]] << " ";
}
END;
}
|
//: C09:Access.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Funkcje inline jako funkcje udostepniajace
class Access {
int i;
public:
int read() const { return i; }
void set(int ii) { i = ii; }
};
int main() {
Access A;
A.set(100);
int x = A.read();
} ///:~
|
#include <stdio.h>
int main() {
float s;
char k;
printf("Enter R for translation from radians to degrees\n");
printf("Enter D for translation from degrees to radians\n");
scanf("%f%c", &s, &k);
if (k == 'D')
{
s = (s*3.14) / 180;
printf("%f radians\n", s);
}
if (k == 'R')
{
s = (s * 180) / 3.14;
printf("%f degrees\n", s);
}
return(0);
}
|
/*
========================================================================
DEVise Data Visualization Software
(c) Copyright 1992-1996
By the DEVise Development Group
Madison, Wisconsin
All Rights Reserved.
========================================================================
Under no circumstances is this software to be copied, distributed,
or altered in any way without prior permission from the DEVise
Development Group.
*/
/*
$Id: Util.c,v 1.20 1996/12/03 20:24:22 jussi Exp $
$Log: Util.c,v $
Revision 1.20 1996/12/03 20:24:22 jussi
Added readn() and writen().
Revision 1.19 1996/12/02 18:44:35 wenger
Fixed problems dealing with DST in dates (including all date composite
parsers); added more error checking to date composite parsers.
Revision 1.18 1996/11/19 15:23:28 wenger
Minor changes to fix compiles on HP, etc.
Revision 1.17 1996/11/05 18:23:11 wenger
Minor mods to get things to compile on SGI systems.
Revision 1.16 1996/10/18 20:34:08 wenger
Transforms and clip masks now work for PostScript output; changed
WindowRep::Text() member functions to ScaledText() to make things
more clear; added WindowRep::SetDaliServer() member functions to make
Dali stuff more compatible with client/server library.
Revision 1.15 1996/10/09 14:33:45 wenger
Had to make changes to get my new code to compile on HP and Sun.
Revision 1.14 1996/10/07 22:53:50 wenger
Added more error checking and better error messages in response to
some of the problems uncovered by CS 737 students.
Revision 1.13 1996/08/23 16:55:44 wenger
First version that allows the use of Dali to display images (more work
needs to be done on this); changed DevStatus to a class to make it work
better; various minor bug fixes.
Revision 1.12 1996/07/14 20:04:47 jussi
Made code to compile in OSF/1.
Revision 1.11 1996/07/05 14:39:47 jussi
Fixed minor problem with null-termination in DateString().
Revision 1.10 1996/05/20 18:44:42 jussi
Replaced PENTIUM flag with SOLARIS.
Revision 1.9 1996/03/27 17:54:56 wenger
Changes to get DEVise to compile and run on Linux.
Revision 1.8 1996/02/13 16:20:16 jussi
Fixed for AIX.
Revision 1.7 1996/01/10 19:11:17 jussi
Added error checking to CopyString.
Revision 1.6 1995/12/28 18:48:14 jussi
Small fixes to remove compiler warnings.
Revision 1.5 1995/12/14 17:12:38 jussi
Small fixes.
Revision 1.4 1995/10/18 14:55:32 jussi
Changed mask of created directory to 0777 from 0755.
Revision 1.3 1995/10/15 18:36:40 jussi
Added HPUX-specific code.
Revision 1.2 1995/09/05 21:13:13 jussi
Added/updated CVS header.
*/
#include <sys/types.h>
#include <stdio.h>
#include <sys/stat.h>
#if defined (SGI)
#define STAT_BAVAIL f_bfree
#else
#define STAT_BAVAIL f_bavail
#endif
#if defined(SOLARIS)
#include <sys/statvfs.h>
#define STAT_STRUCT statvfs
#define STAT_FUNC statvfs
#define STAT_FRSIZE f_frsize
#elif defined(AIX)
#define _KERNEL
#define _VOPS
#include <sys/vfs.h>
#include <sys/statfs.h>
#define STAT_STRUCT statfs
#define STAT_FUNC VFS_STATFS
#define STAT_FRSIZE f_bsize
#else
// #include <sys/vfs.h>
#define STAT_STRUCT statfs
#define STAT_FUNC statfs
#define STAT_FRSIZE f_bsize
#if defined(SUN)
extern "C" int statfs(const char *, struct statfs *);
#else
#if defined(SGI)
#include <sys/statfs.h>
#endif
#endif
#endif
#if defined(SOLARIS) || defined(HPUX) || defined(AIX)
#include <dirent.h>
#else
//#include <sys/dir.h>
#endif
//#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include "Util.h"
#include "Exit.h"
#include "DevError.h"
long ModTime(char *fname)
{
struct stat sbuf;
if (stat(fname, &sbuf) < 0) {
fprintf(stderr, "Cannot get modtime of %s\n", fname);
Exit::DoExit(2);
}
return (long)sbuf.st_mtime;
}
DevStatus
ReadFile(char *filename, int &size, char *&buffer)
{
DevStatus result = StatusOk;
struct stat sbuf;
if (stat(filename, &sbuf) < 0)
{
reportError("Can't get size of file", errno);
result = StatusFailed;
}
else
{
size = sbuf.st_size;
buffer = new char[size];
if (buffer == NULL)
{
reportError("Out of memory", errno);
result = StatusFailed;
}
else
{
int fd = open(filename, O_RDONLY);
if (fd < 0)
{
reportError("Can't open file", errno);
result = StatusFailed;
}
else
{
if (read(fd, buffer, size) != size)
{
reportError("Error reading file", errno);
result = StatusFailed;
}
if (close(fd) < 0)
{
reportError("Error closing file", errno);
result = StatusWarn;
}
}
if (!result.IsComplete()) delete [] buffer;
}
}
return result;
}
char *CopyString(char *str)
{
if (str == NULL) return str;
char *result = new char[strlen(str) + 1];
if (!result) {
fprintf(stderr, "Insufficient memory for new string\n");
Exit::DoExit(2);
}
strcpy(result, str);
return result;
}
static char dateBuf[21];
char *DateString(time_t tm)
{
#if 0
if (tm < 0) {
char errBuf[1024];
sprintf(errBuf, "Illegal time value %ld\n", tm);
reportErrNosys(errBuf);
}
#endif
char *dateStr = ctime(&tm);
int i;
for(i = 0; i < 7; i++)
dateBuf[i] = dateStr[i + 4];
for(i = 7; i < 11; i++)
dateBuf[i] = dateStr[i + 13];
dateBuf[11] = ' ';
for(i = 12; i < 20; i++)
dateBuf[i] = dateStr[i - 1];
dateBuf[20] = '\0';
return dateBuf;
}
void ClearDir(char *dir)
{
/* clear directory */
DIR *dirp = opendir(dir);
if (dirp != NULL){
#if defined(SOLARIS) || defined(HPUX) || defined(AIX) || defined(LINUX) \
|| defined(OSF)
struct dirent *dp;
#else
struct direct *dp;
#endif
for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)){
#if defined(SOLARIS) || defined(HPUX) || defined(AIX) || defined(LINUX) \
|| defined(OSF)
struct dirent *realdp = (struct dirent *)dp;
#else
struct direct *realdp = dp;
#endif
if (strcmp(realdp->d_name,".") != 0 &&
strcmp(realdp->d_name,"..") != 0 ){
char buf[512];
sprintf(buf,"%s/%s",dir,realdp->d_name);
/*
printf("unlinking %s\n", buf);
*/
unlink(buf);
}
}
closedir(dirp);
}
}
/* Check if directory exists. Make directory if not already exists
Clear directory if clear == true*/
void CheckAndMakeDirectory(char *dir, int clear )
{
struct stat sbuf;
int ret = stat(dir,&sbuf);
if (ret >= 0 ) {
if (!(sbuf.st_mode & S_IFDIR)){
fprintf(stderr,"Init:: %s not a directory\n", dir);
Exit::DoExit(1);
}
if (clear){
ClearDir(dir);
}
} else {
/* make new directory */
int code = mkdir(dir,0777);
if (code < 0 ){
printf("Init::can't make directory %s\n",dir);
perror("");
Exit::DoExit(1);
}
}
}
/* Check whether we have enough space in a given directory. */
void CheckDirSpace(char *dirname, char *envVar, int warnSize, int exitSize)
{
struct STAT_STRUCT stats;
if (STAT_FUNC(dirname, &stats
#if defined(SGI)
, sizeof(stats), 0
#endif
) != 0)
{
reportErrSys("Can't get status of file system");
}
else
{
int bytesFree = stats.STAT_BAVAIL * stats.STAT_FRSIZE;
if (bytesFree < exitSize)
{
char errBuf[1024];
sprintf(errBuf, "%s directory (%s) has less than %d bytes free\n",
envVar, dirname, exitSize);
Exit::DoAbort(errBuf, __FILE__, __LINE__);
}
else if (bytesFree < warnSize)
{
fprintf(stderr,
"Warning: %s directory (%s) has less than %d bytes free\n",
envVar, dirname, warnSize);
}
}
return;
}
//
// Read specified number of bytes. Recover from interrupted system calls.
//
int readn(int fd, char *buf, int nbytes)
{
int nleft = nbytes;
while (nleft > 0) {
int nread = read(fd, buf, nleft);
if (nread < 0) {
if (errno == EINTR)
continue;
perror("read");
return nread;
}
if (nread == 0) // EOF?
break;
nleft -= nread;
buf += nread;
}
return nbytes - nleft;
}
//
// Write specified number of bytes. Recover from interrupted system calls.
//
int writen(int fd, char *buf, int nbytes)
{
int nleft = nbytes;
while (nleft > 0) {
int nwritten = write(fd, buf, nleft);
if (nwritten < 0) {
if (errno == EINTR)
continue;
return nwritten;
}
nleft -= nwritten;
buf += nwritten;
}
return nbytes - nleft;
}
|
// Created on: 1993-07-06
// Created by: Remi LEQUETTE
// 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 _BRepBuilderAPI_EdgeError_HeaderFile
#define _BRepBuilderAPI_EdgeError_HeaderFile
//! Indicates the outcome of the
//! construction of an edge, i.e. whether it has been successful or
//! not, as explained below:
//! - BRepBuilderAPI_EdgeDone No error occurred; The edge is
//! correctly built.
//! - BRepBuilderAPI_PointProjectionFailed No parameters were given but
//! the projection of the 3D points on the curve failed. This
//! happens when the point distance to the curve is greater than
//! the precision value.
//! - BRepBuilderAPI_ParameterOutOfRange
//! The given parameters are not in the parametric range
//! C->FirstParameter(), C->LastParameter()
//! - BRepBuilderAPI_DifferentPointsOnClosedCurve
//! The two vertices or points are the extremities of a closed
//! curve but have different locations.
//! - BRepBuilderAPI_PointWithInfiniteParameter
//! A finite coordinate point was associated with an infinite
//! parameter (see the Precision package for a definition of infinite values).
//! - BRepBuilderAPI_DifferentsPointAndParameter
//! The distance between the 3D point and the point evaluated
//! on the curve with the parameter is greater than the precision.
//! - BRepBuilderAPI_LineThroughIdenticPoints
//! Two identical points were given to define a line (construction
//! of an edge without curve); gp::Resolution is used for the confusion test.
enum BRepBuilderAPI_EdgeError
{
BRepBuilderAPI_EdgeDone,
BRepBuilderAPI_PointProjectionFailed,
BRepBuilderAPI_ParameterOutOfRange,
BRepBuilderAPI_DifferentPointsOnClosedCurve,
BRepBuilderAPI_PointWithInfiniteParameter,
BRepBuilderAPI_DifferentsPointAndParameter,
BRepBuilderAPI_LineThroughIdenticPoints
};
#endif // _BRepBuilderAPI_EdgeError_HeaderFile
|
const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int ledPin1 = 9;
void setup() {
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(ledPin1, OUTPUT);
digitalWrite(buttonPin1,HIGH);
digitalWrite(buttonPin2,HIGH) ;
}
int ledBrightness = 128;
void loop() {
if(digitalRead(buttonPin1) == LOW){
ledBrightness--;
}
else if(digitalRead(buttonPin2) == LOW){
ledBrightness++;
}
ledBrightness = constrain(ledBrightness, 0, 225);
analogWrite(ledPin1, ledBrightness);
delay(20);
}
|
//
// Created by Yevhenii Natalenko on 5/2/17.
//
#ifndef INC_3_KOSARAJU_H
#define INC_3_KOSARAJU_H
#include "GraphFormat.h"
bool compare(int a, int b); // comparator for stable_sort
void add_Edge(std::vector<std::vector<int> >& graph, int v, int w); // manual construction
std::vector<std::vector <int> > reverse_graph(const std::vector<std::vector<int> > &graph); // transposing graph
void print_graph(std::vector<std::vector <int> >& graph);
std::vector<std::vector<int> > convert(const GraphFormat& graph);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//performs usual DFS and creates visiting order of vertices. Order depends on time when each recursive function ends executing.
void DFS_for_SCC(std::vector<std::vector<int> > &graph, int v,
std::vector<bool>& visited,
std::vector<int>& visited_vertices);
// guarantees that all vertices will be visited
void DFS_for_disconnected_graph(std::vector<std::vector<int> > &graph,
std::vector<int>& visited_vertices);
// usual DFS with slight modifications. Recursively creates one SCC per call from DFS_for_reversed_graph()
void DFS_for_SCC_reversed(std::vector<std::vector<int> >& graph, int v,
std::vector<bool>& visited,
std::vector<int> & cur_SCC);
// Slightly modified DFS_for_disconnected_graph(). Runs on a reversed graph. Creates a set of all SCC.
// NOTE: changed order of running DFS. Reversed order that has been created by DFS_for_disconnected_graph().
void DFS_for_reversed_graph(std::vector<std::vector<int> >& graph,
std::vector<int>& visiting_order,
std::vector<std::vector<int> >& result);
// helper function for easy calling.
std::vector<std::vector<int> > all_SCC(std::vector<std::vector<int> > &graph,
std::vector<int>& visiting_order);
//demo function. Graph is generated here
void demo_Kosaraju();
#endif //INC_3_KOSARAJU_H
|
// Created on : Sat May 02 12:41:14 2020
// Created by: Irina KRYLOVA
// Generator: Express (EXPRESS -> CASCADE/XSTEP Translator) V3.0
// Copyright (c) Open CASCADE 2020
//
// 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 _StepKinematics_RigidPlacement_HeaderFile
#define _StepKinematics_RigidPlacement_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <StepData_SelectType.hxx>
#include <Standard_Integer.hxx>
class Standard_Transient;
class StepGeom_Axis2Placement3d;
class StepGeom_SuParameters;
//! Representation of STEP SELECT type RigidPlacement
class StepKinematics_RigidPlacement : public StepData_SelectType
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor
Standard_EXPORT StepKinematics_RigidPlacement();
//! Recognizes a kind of RigidPlacement select type
//! -- 1 -> Axis2Placement3d
//! -- 2 -> SuParameters
Standard_EXPORT Standard_Integer CaseNum (const Handle(Standard_Transient)& ent) const Standard_OVERRIDE;
//! Returns Value as Axis2Placement3d (or Null if another type)
Standard_EXPORT Handle(StepGeom_Axis2Placement3d) Axis2Placement3d() const;
//! Returns Value as SuParameters (or Null if another type)
Standard_EXPORT Handle(StepGeom_SuParameters) SuParameters() const;
};
#endif // _StepKinematics_RigidPlacement_HeaderFile
|
#ifndef PWM_CLASS_H
#define PWM_CLASS_H
class PWM_CLASS
{
public:
PWM_CLASS(int factor_umplere ,int frecventa);
void set (int factor_umplere,int frecventa);
int getDutyCycle();
int getFrequency();
private:
int frecventa;
int factor_umplere;
};
#endif // PWM_CLASS_H
|
//
// Created by Lee on 2019-04-19.
//
#ifndef UBP_CLIENT_CPP_VER_PHOTOVIEWER_H
#define UBP_CLIENT_CPP_VER_PHOTOVIEWER_H
#include <QLabel>
#include <QPixmap>
#include <src/model/Photo.h>
class PhotoViewer : public QLabel {
Q_OBJECT
private:
Photo photo;
public:
explicit PhotoViewer(QWidget * parent = nullptr, Photo * photo = nullptr);
void updatePhoto(Photo * photo);
};
#endif //UBP_CLIENT_CPP_VER_PHOTOVIEWER_H
|
// Created on: 1993-03-23
// Created by: Jean Yves LEBEY
// 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 _TopOpeBRepBuild_LoopSet_HeaderFile
#define _TopOpeBRepBuild_LoopSet_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TopOpeBRepBuild_ListOfLoop.hxx>
#include <TopOpeBRepBuild_ListIteratorOfListOfLoop.hxx>
#include <Standard_Integer.hxx>
#include <Standard_Boolean.hxx>
class TopOpeBRepBuild_Loop;
class TopOpeBRepBuild_LoopSet
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT TopOpeBRepBuild_LoopSet();
Standard_EXPORT virtual ~TopOpeBRepBuild_LoopSet();
Standard_EXPORT TopOpeBRepBuild_ListOfLoop& ChangeListOfLoop();
Standard_EXPORT virtual void InitLoop();
Standard_EXPORT virtual Standard_Boolean MoreLoop() const;
Standard_EXPORT virtual void NextLoop();
Standard_EXPORT virtual Handle(TopOpeBRepBuild_Loop) Loop() const;
protected:
private:
TopOpeBRepBuild_ListOfLoop myListOfLoop;
TopOpeBRepBuild_ListIteratorOfListOfLoop myLoopIterator;
Standard_Integer myLoopIndex;
Standard_Integer myNbLoop;
};
#endif // _TopOpeBRepBuild_LoopSet_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#ifndef MAILTO_H
#define MAILTO_H
/** @brief Generate and parse mailto: URLs as defined in RFC 2368
*/
class MailTo
{
public:
/** Initialize object using a mailto: raw string
* @param url const char * mailto string
*/
OP_STATUS Init(const char * url);
/** Initialize object specifying several attributes
* @param to To header for mail generated by mailto
* @param cc Cc header for mail generated by mailto
* @param bcc Bcc header for mail generated by mailto
* @param subject Subject header for mail generated by mailto
* @param body Body for mail generated by mailto
*/
OP_STATUS Init(const OpStringC& to, const OpStringC& cc, const OpStringC& bcc, const OpStringC& subject, const OpStringC& body);
/** Getters: get data values for this mailto
* @return requested value
*/
const OpStringC8& GetRawMailTo() const { return m_raw_mailto; }
// decoded values:
const OpStringC& GetTo() const { return m_values[MAILTO_TO]; }
const OpStringC& GetCc() const { return m_values[MAILTO_CC]; }
const OpStringC& GetBcc() const { return m_values[MAILTO_BCC]; }
const OpStringC& GetSubject() const { return m_values[MAILTO_SUBJECT]; }
const OpStringC& GetBody() const { return m_values[MAILTO_BODY]; }
// encoded values:
OP_STATUS GetEncodedTo(OpString8& enc_v) const { RETURN_IF_ERROR(EncodeValue(m_values[MAILTO_TO],enc_v)); return OpStatus::OK;}
OP_STATUS GetEncodedCc(OpString8& enc_v) const { RETURN_IF_ERROR(EncodeValue(m_values[MAILTO_CC],enc_v)); return OpStatus::OK;}
OP_STATUS GetEncodedBcc(OpString8& enc_v) const { RETURN_IF_ERROR(EncodeValue(m_values[MAILTO_BCC],enc_v)); return OpStatus::OK;}
OP_STATUS GetEncodedSubject(OpString8& enc_v) const { RETURN_IF_ERROR(EncodeValue(m_values[MAILTO_SUBJECT],enc_v)); return OpStatus::OK;}
OP_STATUS GetEncodedBody(OpString8& enc_v) const { RETURN_IF_ERROR(EncodeValue(m_values[MAILTO_BODY],enc_v)); return OpStatus::OK;}
private:
OP_STATUS RawToAttributes();
OP_STATUS AttributesToRaw();
OP_STATUS EncodeValue(const OpStringC& value, OpString8& encoded) const;
OP_STATUS DecodeValue(const char* value, const char* value_end, OpString& decoded) const;
enum Attribute
{
MAILTO_TO,
MAILTO_CC,
MAILTO_BCC,
MAILTO_SUBJECT,
MAILTO_BODY,
MAILTO_ATTR_COUNT // don't remove, should be last
};
OpString m_values[MAILTO_ATTR_COUNT];
OpString8 m_raw_mailto;
};
#endif // MAILTO_H
|
/**
* 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.
*/
#ifndef CONSUMER_H
#define CONSUMER_H
#include <napi.h>
#include <pulsar/c/client.h>
#include "ConsumerConfig.h"
#include "MessageListener.h"
class Consumer : public Napi::ObjectWrap<Consumer> {
public:
static void Init(Napi::Env env, Napi::Object exports);
static Napi::Value NewInstance(const Napi::CallbackInfo &info, std::shared_ptr<pulsar_client_t> cClient);
static Napi::FunctionReference constructor;
Consumer(const Napi::CallbackInfo &info);
~Consumer();
void SetCConsumer(std::shared_ptr<pulsar_consumer_t> cConsumer);
void SetListenerCallback(MessageListenerCallback *listener);
void Cleanup();
void CleanupListener();
std::string GetTopic();
std::string GetSubscriptionName();
private:
std::shared_ptr<pulsar_consumer_t> cConsumer;
MessageListenerCallback *listener;
Napi::Value Receive(const Napi::CallbackInfo &info);
Napi::Value Acknowledge(const Napi::CallbackInfo &info);
Napi::Value AcknowledgeId(const Napi::CallbackInfo &info);
void NegativeAcknowledge(const Napi::CallbackInfo &info);
void NegativeAcknowledgeId(const Napi::CallbackInfo &info);
Napi::Value AcknowledgeCumulative(const Napi::CallbackInfo &info);
Napi::Value AcknowledgeCumulativeId(const Napi::CallbackInfo &info);
Napi::Value Seek(const Napi::CallbackInfo &info);
Napi::Value SeekTimestamp(const Napi::CallbackInfo &info);
Napi::Value IsConnected(const Napi::CallbackInfo &info);
Napi::Value Close(const Napi::CallbackInfo &info);
Napi::Value Unsubscribe(const Napi::CallbackInfo &info);
};
#endif
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
int main() {
int n,m,q;
int x,y,k;
scanf("%d%d",&n,&m);
for (int i = 1;i <= n; i++) {f[i] = i;dis[i] = 0;}
for (int i = 1;i <= m; i++) {
scanf("%d%d%d",&a[i],b[i],c[i]);
getchar();getchar();
}
scanf("%d",&q);
j = 1;
for (int i = 1;i <= q; i++) {
scanf("%d%d",&x,&y,&k);
for (;j <= k; j++) {
int x = find(a[i]).y = find(b[i]);
f[]
}
}
return 0;
}
|
#pragma once
#include <stack>
#include "IMemoryManager.h"
#include "StdMemoryManager.h"
//bool STD_NEW_DELETE = true;
class MemoryManagerSwitcher {
public:
MemoryManagerSwitcher() : recManager(new(malloc(sizeof(StdMemoryManager))) StdMemoryManager()) {};
MemoryManagerSwitcher(const MemoryManagerSwitcher&) = delete;
MemoryManagerSwitcher& operator=(const MemoryManagerSwitcher&) = delete;
~MemoryManagerSwitcher() {
while (recManager != nullptr) {
IMemoryManager* prev = recManager->prev;
delete recManager;
recManager = prev;
}
};
void pushManager(IMemoryManager*);
void popManager();
void* Alloc(size_t);
void Delete(void*) noexcept;
private:
IMemoryManager* recManager;
};
/*void* operator new(std::size_t size) noexcept(false);
void operator delete(void* ptr) noexcept;
void* operator new(std::size_t size) noexcept;
void* operator new[](std::size_t size) noexcept(false);
void* operator new[](std::size_t size) noexcept;
void operator delete(void* ptr) noexcept;
void operator delete(void* ptr, std::size_t) noexcept;
void operator delete[](void* ptr) noexcept;
void operator delete[](void* ptr) noexcept;
void operator delete[](void* ptr, std::size_t) noexcept;*/
|
// CodeGear C++Builder
// Copyright (c) 1995, 2009 by Embarcadero Technologies, Inc.
// All rights reserved
// (DO NOT EDIT: machine generated header) 'Dcrhexeditorex.pas' rev: 21.00
#ifndef DcrhexeditorexHPP
#define DcrhexeditorexHPP
#pragma delphiheader begin
#pragma option push
#pragma option -w- // All warnings off
#pragma option -Vx // Zero-length empty class member functions
#pragma pack(push,8)
#include <System.hpp> // Pascal unit
#include <Sysinit.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <Sysutils.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <Controls.hpp> // Pascal unit
#include <Forms.hpp> // Pascal unit
#include <Dcrhexeditor.hpp> // Pascal unit
#include <Activex.hpp> // Pascal unit
#include <Graphics.hpp> // Pascal unit
#include <Printers.hpp> // Pascal unit
#include <Stdactns.hpp> // Pascal unit
#include <Clipbrd.hpp> // Pascal unit
#include <Shlobj.hpp> // Pascal unit
#include <Menus.hpp> // Pascal unit
#include <Grids.hpp> // Pascal unit
#include <Stdctrls.hpp> // Pascal unit
#include <Types.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
DECLARE_DINTERFACE_TYPE(IDropTarget)
DECLARE_DINTERFACE_TYPE(IDropSource)
DECLARE_DINTERFACE_TYPE(IEnumFORMATETC)
namespace Dcrhexeditorex
{
//-- type declarations -------------------------------------------------------
#pragma option push -b-
enum TMPHOLEOperation { oleDrop, oleClipboard };
#pragma option pop
typedef DynamicArray<System::Word> TClipFormats;
#pragma option push -b-
enum TMPHPrintFlag { pfSelectionOnly, pfSelectionBold, pfMonochrome, pfUseBackgroundColor, pfCurrentViewOnly, pfIncludeRuler };
#pragma option pop
typedef Set<TMPHPrintFlag, pfSelectionOnly, pfIncludeRuler> TMPHPrintFlags;
typedef StaticArray<System::UnicodeString, 2> TMPHPrintHeaders;
typedef void __fastcall (__closure *TMPHQueryPublicPropertyEvent)(System::TObject* Sender, const System::UnicodeString PropertyName, bool &IsPublic);
class DELPHICLASS TMPHexEditorEx;
class DELPHICLASS TMPHDropTarget;
class DELPHICLASS TMPHPrintOptions;
class PASCALIMPLEMENTATION TMPHexEditorEx : public Dcrhexeditor::TCustomMPHexEditor
{
typedef Dcrhexeditor::TCustomMPHexEditor inherited;
private:
bool FCreateBackups;
System::UnicodeString FBackupFileExt;
bool FOleDragDrop;
TMPHDropTarget* FDropTarget;
StaticArray<System::Word, 2> FOleFormat;
bool FOleDragging;
bool FOleStartDrag;
int FOleDragX;
int FOleDragY;
bool FOleWasTarget;
TMPHPrintOptions* FPrintOptions;
int FPrintPages;
Graphics::TFont* FPrintFont;
bool FUseEditorFontForPrinting;
bool FClipboardAsHexText;
_di_IDataObject FClipData;
bool FFlushClipboardAtShutDown;
bool FSupportsOtherClipFormats;
Menus::TPopupMenu* FOffsetPopupMenu;
bool FZoomOnWheel;
int FPaintUpdateCounter;
TMPHQueryPublicPropertyEvent FOnQueryPublicProperty;
bool FHasDoubleClicked;
bool FBookmarksNoChange;
bool FCreateUndoOnUndoUpdate;
bool FModifiedNoUndo;
void __fastcall SetOleDragDrop(const bool Value);
bool __fastcall OLEHasSupportedFormat(const _di_IDataObject dataObj, System::Word const *Formats, const int Formats_Size, System::Word &Format);
TClipFormats __fastcall GetMyOLEFormats(void);
HIDESBASE MESSAGE void __fastcall WMDestroy(Messages::TWMNoParams &message);
void __fastcall SetPrintOptions(const TMPHPrintOptions* Value);
int __fastcall PrintToCanvas(Graphics::TCanvas* ACanvas, const int APage, const Types::TRect &AMargins);
Types::TRect __fastcall PrinterMarginRect(void);
void __fastcall SetPrintFont(const Graphics::TFont* Value);
void __fastcall SetOffsetPopupMenu(const Menus::TPopupMenu* Value);
Menus::TPopupMenu* __fastcall GetOffsetPopupMenu(void);
System::UnicodeString __fastcall GetBookmarksAsString(void);
void __fastcall SetBookMarksAsString(System::UnicodeString Value);
protected:
virtual bool __fastcall CanCreateUndo(const Dcrhexeditor::TMPHUndoFlag aKind, const __int64 aCount, const __int64 aReplCount);
virtual System::UnicodeString __fastcall GetPropertiesAsString(void);
virtual void __fastcall SetPropertiesAsString(const System::UnicodeString Value);
virtual bool __fastcall IsPropPublic(System::UnicodeString PropName);
virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation);
DYNAMIC void __fastcall DoContextPopup(const Types::TPoint &MousePos, bool &Handled);
DYNAMIC void __fastcall KeyDown(System::Word &Key, Classes::TShiftState Shift);
DYNAMIC bool __fastcall DoMouseWheelDown(Classes::TShiftState Shift, const Types::TPoint &MousePos);
DYNAMIC bool __fastcall DoMouseWheelUp(Classes::TShiftState Shift, const Types::TPoint &MousePos);
virtual void __fastcall PrepareOverwriteDiskFile(void);
DYNAMIC void __fastcall MouseMove(Classes::TShiftState Shift, int X, int Y);
DYNAMIC void __fastcall MouseUp(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y);
DYNAMIC void __fastcall MouseDown(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y);
virtual void __fastcall CreateWnd(void);
HRESULT __fastcall SupportsOLEData(const _di_IDataObject dataObj, const int grfKeyState, const Types::TPoint &pt, int &dwEffect, const TMPHOLEOperation Operation);
HRESULT __fastcall InsertOLEData(const _di_IDataObject dataObj, const int grfKeyState, const Types::TPoint &pt, int &dwEffect, const TMPHOLEOperation Operation);
HRESULT __fastcall ModifyOLEDropEffect(const int grfKeyState, const Types::TPoint &pt, int &dwEffect);
virtual void __fastcall Paint(void);
DYNAMIC void __fastcall DblClick(void);
virtual void __fastcall BookmarkChanged(void);
public:
__fastcall virtual TMPHexEditorEx(Classes::TComponent* AOwner);
__fastcall virtual ~TMPHexEditorEx(void);
virtual void __fastcall WriteBuffer(const void *ABuffer, const __int64 AIndex, const __int64 ACount);
DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action);
virtual bool __fastcall UpdateAction(Classes::TBasicAction* Action);
__property bool CreateUndoOnUndoUpdate = {read=FCreateUndoOnUndoUpdate, write=FCreateUndoOnUndoUpdate, nodefault};
int __fastcall BeginUpdate(void);
int __fastcall EndUpdate(void);
HIDESBASE int __fastcall UndoBeginUpdate(const System::UnicodeString StrUndoDesc = L"");
virtual int __fastcall UndoEndUpdate(void);
void __fastcall CreateRangeUndo(const int aStart, const int aCount, System::UnicodeString sDesc);
bool __fastcall CanPaste(void);
bool __fastcall CanCopy(void);
bool __fastcall CanCut(void);
bool __fastcall CBCopy(void);
bool __fastcall CBCut(void);
bool __fastcall CBPaste(void);
bool __fastcall OwnsClipBoard(void);
void __fastcall ReleaseClipboard(const bool Flush);
void __fastcall Save(void);
bool __fastcall DumpUndoStorage(const System::UnicodeString FileName);
Graphics::TMetafile* __fastcall PrintPreview(const int Page);
void __fastcall Print(const int Page);
int __fastcall PrintNumPages(void);
void __fastcall PasteData(void * P, const int aCount, const System::UnicodeString UndoDesc = L"");
__property System::UnicodeString BookMarksAsString = {read=GetBookmarksAsString, write=SetBookMarksAsString};
__property System::UnicodeString PropertiesAsString = {read=GetPropertiesAsString, write=SetPropertiesAsString};
__published:
__property bool CreateBackup = {read=FCreateBackups, write=FCreateBackups, default=1};
__property System::UnicodeString BackupExtension = {read=FBackupFileExt, write=FBackupFileExt};
__property bool OleDragDrop = {read=FOleDragDrop, write=SetOleDragDrop, default=0};
__property bool ClipboardAsHexText = {read=FClipboardAsHexText, write=FClipboardAsHexText, default=0};
__property bool FlushClipboardAtShutDown = {read=FFlushClipboardAtShutDown, write=FFlushClipboardAtShutDown, default=0};
__property bool SupportsOtherClipFormats = {read=FSupportsOtherClipFormats, write=FSupportsOtherClipFormats, default=1};
__property TMPHPrintOptions* PrintOptions = {read=FPrintOptions, write=SetPrintOptions};
__property Graphics::TFont* PrintFont = {read=FPrintFont, write=SetPrintFont};
__property bool UseEditorFontForPrinting = {read=FUseEditorFontForPrinting, write=FUseEditorFontForPrinting, default=1};
__property Menus::TPopupMenu* OffsetPopupMenu = {read=GetOffsetPopupMenu, write=SetOffsetPopupMenu};
__property bool ZoomOnWheel = {read=FZoomOnWheel, write=FZoomOnWheel, default=1};
__property TMPHQueryPublicPropertyEvent OnQueryPublicProperty = {read=FOnQueryPublicProperty, write=FOnQueryPublicProperty};
__property Align = {default=0};
__property Anchors = {default=3};
__property BiDiMode;
__property BorderStyle = {default=1};
__property Constraints;
__property Ctl3D;
__property DragCursor = {default=-12};
__property DragKind = {default=0};
__property DragMode = {default=0};
__property Enabled = {default=1};
__property Font;
__property ImeMode = {default=3};
__property ImeName;
__property OnClick;
__property OnDblClick;
__property OnDragDrop;
__property OnDragOver;
__property OnEndDock;
__property OnEndDrag;
__property OnEnter;
__property OnExit;
__property OnKeyDown;
__property OnKeyPress;
__property OnKeyUp;
__property OnMouseDown;
__property OnMouseMove;
__property OnMouseUp;
__property OnMouseWheel;
__property OnMouseWheelDown;
__property OnMouseWheelUp;
__property OnStartDock;
__property OnStartDrag;
__property ParentBiDiMode = {default=1};
__property ParentCtl3D = {default=1};
__property ParentFont = {default=1};
__property ParentShowHint = {default=1};
__property PopupMenu;
__property ScrollBars = {default=3};
__property ShowHint;
__property TabOrder = {default=-1};
__property TabStop = {default=1};
__property Visible = {default=1};
__property AutoBytesPerRow = {default=0};
__property BytesPerRow;
__property BytesPerColumn = {default=2};
__property Translation;
__property OffsetFormat;
__property CaretKind = {default=3};
__property Colors;
__property FocusFrame;
__property SwapNibbles = {default=0};
__property MaskChar;
__property NoSizeChange = {default=0};
__property AllowInsertMode = {default=1};
__property DrawGridLines;
__property WantTabs = {default=1};
__property ReadOnlyView = {default=0};
__property HideSelection = {default=0};
__property GraySelectionIfNotFocused = {default=0};
__property GutterWidth = {default=-1};
__property BookmarkBitmap;
__property Version;
__property MaxUndo = {default=1048576};
__property InsertMode = {default=0};
__property HexLowerCase = {default=0};
__property OnProgress;
__property OnInvalidKey;
__property OnTopLeftChanged;
__property OnChange;
__property DrawGutter3D = {default=1};
__property DrawGutterGradient = {default=1};
__property OwnerData = {default=0};
__property ShowRuler = {default=0};
__property BytesPerUnit = {default=1};
__property RulerBytesPerUnit = {default=-1};
__property ShowPositionIfNotFocused = {default=0};
__property OnSelectionChanged;
__property UnicodeChars = {default=0};
__property UnicodeBigEndian = {default=0};
__property OnDrawCell;
__property OnBookmarkChanged;
__property OnGetOffsetText;
__property OnData;
__property BytesPerBlock = {default=-1};
__property SeparateBlocksInCharField = {default=1};
__property FindProgress = {default=0};
__property RulerNumberBase = {default=16};
public:
/* TWinControl.CreateParented */ inline __fastcall TMPHexEditorEx(HWND ParentWindow) : Dcrhexeditor::TCustomMPHexEditor(ParentWindow) { }
};
class PASCALIMPLEMENTATION TMPHDropTarget : public System::TInterfacedObject
{
typedef System::TInterfacedObject inherited;
private:
TMPHexEditorEx* FEditor;
unsigned FEditorHandle;
bool FActive;
void __fastcall SetActive(const bool Value);
public:
__fastcall TMPHDropTarget(TMPHexEditorEx* Editor);
virtual void __fastcall BeforeDestruction(void);
HRESULT __stdcall DragEnter(const _di_IDataObject dataObj, int grfKeyState, const Types::TPoint pt, int &dwEffect);
HRESULT __stdcall DragOver(int grfKeyState, const Types::TPoint pt, int &dwEffect);
HRESULT __stdcall DragLeave(void);
HRESULT __stdcall Drop(const _di_IDataObject dataObj, int grfKeyState, const Types::TPoint pt, int &dwEffect);
__property bool Active = {read=FActive, write=SetActive, nodefault};
public:
/* TObject.Destroy */ inline __fastcall virtual ~TMPHDropTarget(void) { }
private:
void *__IDropTarget; /* IDropTarget */
public:
#if defined(MANAGED_INTERFACE_OPERATORS)
operator _di_IDropTarget()
{
_di_IDropTarget intf;
GetInterface(intf);
return intf;
}
#else
operator IDropTarget*(void) { return (IDropTarget*)&__IDropTarget; }
#endif
};
class PASCALIMPLEMENTATION TMPHPrintOptions : public Classes::TPersistent
{
typedef Classes::TPersistent inherited;
private:
Types::TRect FMargins;
TMPHPrintHeaders FHeaders;
TMPHPrintFlags FFlags;
System::UnicodeString __fastcall GetHeader(const int index);
int __fastcall GetMargin(const int index);
void __fastcall SetHeader(const int index, const System::UnicodeString Value);
void __fastcall SetMargin(const int index, const int Value);
public:
__fastcall TMPHPrintOptions(void);
virtual void __fastcall Assign(Classes::TPersistent* Source);
__published:
__property int MarginLeft = {read=GetMargin, write=SetMargin, index=1, nodefault};
__property int MarginTop = {read=GetMargin, write=SetMargin, index=2, nodefault};
__property int MarginRight = {read=GetMargin, write=SetMargin, index=3, nodefault};
__property int MarginBottom = {read=GetMargin, write=SetMargin, index=4, nodefault};
__property System::UnicodeString PageHeader = {read=GetHeader, write=SetHeader, index=0};
__property System::UnicodeString PageFooter = {read=GetHeader, write=SetHeader, index=1};
__property TMPHPrintFlags Flags = {read=FFlags, write=FFlags, nodefault};
public:
/* TPersistent.Destroy */ inline __fastcall virtual ~TMPHPrintOptions(void) { }
};
//-- var, const, procedure ---------------------------------------------------
extern PACKAGE Types::TRect MPH_DEF_PRINT_MARGINS;
extern PACKAGE void __fastcall MPHSetHexClipboardData(void * Data, int DataSize, System::ShortString &ScrapFileName, bool TextAsHex, bool SwapNibbles);
} /* namespace Dcrhexeditorex */
using namespace Dcrhexeditorex;
#pragma pack(pop)
#pragma option pop
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // DcrhexeditorexHPP
|
#include <iostream>
#include <g2o/core/g2o_core_api.h>
#include <g2o/core/base_vertex.h>
#include <g2o/core/base_unary_edge.h>
#include <g2o/core/block_solver.h>
#include <g2o/core/optimization_algorithm_levenberg.h>
#include <g2o/core/optimization_algorithm_gauss_newton.h>
#include <g2o/core/optimization_algorithm_dogleg.h>
#include <g2o/solvers/dense/linear_solver_dense.h>
#include <Eigen/Core>
#include <opencv2/core/core.hpp>
#include <cmath>
#include <chrono>
using namespace std;
// 曲线模型的顶点,模板参数:优化变量维度和数据类型
class CurveFittingVertex : public g2o::BaseVertex<3, Eigen::Vector3d> {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
// 重置
virtual void setToOriginImpl() override {
_estimate << 0, 0, 0;
}
// 更新
virtual void oplusImpl(const double *update) override {
_estimate += Eigen::Vector3d(update);
}
// 存盘和读盘:留空
virtual bool read(istream &in) {}
virtual bool write(ostream &out) const {}
};
// 误差模型 模板参数:观测值维度,类型,连接顶点类型
class CurveFittingEdge : public g2o::BaseUnaryEdge<1, double, CurveFittingVertex> {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
CurveFittingEdge(double x) : BaseUnaryEdge(), _x(x) {}
// 计算曲线模型误差
virtual void computeError() override {
const CurveFittingVertex *v = static_cast<const CurveFittingVertex *> (_vertices[0]);
const Eigen::Vector3d abc = v->estimate();
_error(0, 0) = _measurement - std::exp(abc(0, 0) * _x * _x + abc(1, 0) * _x + abc(2, 0));
}
// 计算雅可比矩阵
virtual void linearizeOplus() override {
const CurveFittingVertex *v = static_cast<const CurveFittingVertex *> (_vertices[0]);
const Eigen::Vector3d abc = v->estimate();
double y = exp(abc[0] * _x * _x + abc[1] * _x + abc[2]);
_jacobianOplusXi[0] = -_x * _x * y;
_jacobianOplusXi[1] = -_x * y;
_jacobianOplusXi[2] = -y;
}
virtual bool read(istream &in) {}
virtual bool write(ostream &out) const {}
public:
double _x; // x 值, y 值为 _measurement
};
int main(int argc, char **argv) {
double ar = 1.0, br = 2.0, cr = 1.0; // 真实参数值
double ae = 2.0, be = -1.0, ce = 5.0; // 估计参数值
int N = 100; // 数据点
double w_sigma = 1.0; // 噪声Sigma值
double inv_sigma = 1.0 / w_sigma;
cv::RNG rng; // OpenCV随机数产生器
vector<double> x_data, y_data; // 数据
for (int i = 0; i < N; i++) {
double x = i / 100.0;
x_data.push_back(x);
y_data.push_back(exp(ar * x * x + br * x + cr) + rng.gaussian(w_sigma * w_sigma));
}
// 构建图优化,先设定g2o
typedef g2o::BlockSolver<g2o::BlockSolverTraits<3, 1>> BlockSolverType; // 每个误差项优化变量维度为3,误差值维度为1
typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType; // 线性求解器类型
// 梯度下降方法,可以从GN, LM, DogLeg 中选
auto solver = new g2o::OptimizationAlgorithmGaussNewton(
g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));
g2o::SparseOptimizer optimizer; // 图模型
optimizer.setAlgorithm(solver); // 设置求解器
optimizer.setVerbose(true); // 打开调试输出
// 往图中增加顶点
CurveFittingVertex *v = new CurveFittingVertex();
v->setEstimate(Eigen::Vector3d(ae, be, ce));
v->setId(0);
optimizer.addVertex(v);
// 往图中增加边
for (int i = 0; i < N; i++) {
CurveFittingEdge *edge = new CurveFittingEdge(x_data[i]);
edge->setId(i);
edge->setVertex(0, v); // 设置连接的顶点
edge->setMeasurement(y_data[i]); // 观测数值
edge->setInformation(Eigen::Matrix<double, 1, 1>::Identity() * 1 / (w_sigma * w_sigma)); // 信息矩阵:协方差矩阵之逆
optimizer.addEdge(edge);
}
// 执行优化
cout << "start optimization" << endl;
chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
optimizer.initializeOptimization();
optimizer.optimize(10);
chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);
cout << "solve time cost = " << time_used.count() << " seconds. " << endl;
// 输出优化值
Eigen::Vector3d abc_estimate = v->estimate();
cout << "estimated model: " << abc_estimate.transpose() << endl;
return 0;
}
|
#include "Iwriter.h"
#include <iostream>
void Consolewriter::write(std::string data)const
{
std::cout<<m_color.substr(0,7)+data+m_color.substr(11)<<std::endl;
}
void Consolewriter::setColor(std::string color)
{
m_color = color;
}
|
/*****************************************************************************************************************
* File Name : equilibriumIndex.h
* File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\arrays\page06\equilibriumIndex.h
* Created on : Jan 6, 2014 :: 10:17:09 PM
* Author : AVINASH
* Testing Status : TODO
* URL : TODO
*****************************************************************************************************************/
/************************************************ Namespaces ****************************************************/
using namespace std;
using namespace __gnu_cxx;
/************************************************ User Includes *************************************************/
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
#include <programming/ds/tree.h>
#include <programming/ds/linkedlist.h>
#include <programming/utils/treeutils.h>
#include <programming/utils/llutils.h>
/************************************************ User defined constants *******************************************/
#define null NULL
/************************************************* Main code ******************************************************/
#ifndef EQUILIBRIUMINDEX_H_
#define EQUILIBRIUMINDEX_H_
vector<int> equilibriumIndexON2(vector<int> userInput){
vector<int> equilibriumIndexes;
if(userInput.size() == 0){
return equilibriumIndexes;
}
int leftSum,rightSum;
for(unsigned int counter = 0;counter < userInput.size();counter++){
leftSum = 0;
rightSum = 0;
for(unsigned int leftCounter = 0;leftCounter < counter;leftCounter++){
leftSum += userInput[leftCounter];
}
for(unsigned int rightCounter = counter+1;rightCounter < userInput.size();rightCounter++){
rightSum += userInput[rightCounter];
}
if(leftSum == rightSum){
equilibriumIndexes.push_back(counter);
}
}
}
vector<int> equilibriumIndexON(vector<int> userInput){
vector<int> equilibriumIndexes;
if(userInput.size() == 0){
return equilibriumIndexes;
}
vector<int> leftSum;
leftSum[0] = 0;
for(unsigned int counter = 1;counter < userInput.size();counter++){
leftSum[counter] = leftSum[counter-1] + userInput[counter-1];
}
int rightSum = 0;
for(unsigned int counter = userInput.size()-1;counter >= 0;counter--){
if(leftSum[counter] == rightSum){
equilibriumIndexes.push_back(counter);
}
rightSum += userInput[counter];
}
}
#endif /* EQUILIBRIUMINDEX_H_ */
/************************************************* End code *******************************************************/
|
#include "global.h"
float correction_inclined_plane_boundary(float dr,const float &at0,const float &atI,const float &w) {
if (atI <= -1)
return dr;
if (at0 <= atI)
return dr;
float sina = (at0 - atI)*w;
if (abs(sina)>1)
sina = 0;
else
sina = sqrtf(1-SQR(sina));
return dr*sina;
}
float simple_plane_wave_at_boundary(const float &w) {
float atA = max(app.at_A,app.at_B); //to druhe je mensie ako 0 - neurcene
float dst = correction_inclined_plane_boundary(1.f,app.at_Z,atA,w);
dst = correction_inclined_plane_boundary(dst,app.at_Z,app.at_C,w);
return app.at_Z + dst/w;
}
void Bod::sir_at_boundary(const short& si,const short& sj,const short& sk) {
app.prep_arrivals_boundary(s,si,sj,sk);
float w = (v[i][j][0] + v[si][sj][0])/2.f;
if ((app.at_A<0) || (app.at_B<0)) {
t = simple_plane_wave_at_boundary(w);
#ifdef DEBUG
if (t<at[si][sj][sk]) {cout<<"ERR1402051257 FDBND "<<i<<","<<j<<","<<k<<" z "<<si<<","<<sj<<","<<sk<<" "<<t<<" z "<<at[si][sj][sk]<<endl;}
#endif
return;
}
//korekcia rychlosti na dopad zospodu
if (app.at_C>-1) {
if (app.at_C<app.at_Z) {
float sina = (app.at_Z - app.at_C)*w;
if (sina > 0.9f)
sina = 0.9f;
w = w/sqrtf(1-SQR(sina));
if (i==389) if (j==250) if (k==0) {
cout<<"korekcia "<<w<<" "<<sina<<endl;
}
}
}
t = app.find_and_compute_from_virtual_source_boundary(w);
if (t<at[si][sj][sk]) {cout<<"ERR1402051256 SPHBND "<<i<<","<<j<<","<<k<<" z "<<si<<","<<sj<<","<<sk<<" "<<t<<" z "<<at[si][sj][sk]<<endl;}
if (t<at[si][sj][sk]+0.3/w) if (at[si][sj][sk]<at[si][sj][sk+1]) {cout<<"WAR SPHBND "<<i<<","<<j<<","<<k<<" z "<<si<<","<<sj<<","<<sk<<" "<<t<<" z "<<at[si][sj][sk]<<endl;}
if (i==389) if (j==250) if (k==0) {
cout<<"cas "<<t<<" velocity "<<w<<endl;
cout<<app.st<<" "<<app.sx<<" "<<app.sz<<endl;
cout<<"rovinna "<<abs(app.at_A + app.at_B - 2*app.at_Z)<<" "<<w*abs(app.at_A + app.at_B - 2*app.at_Z)<<" vs 0.005"<<endl;
}
#ifdef DEBUG
if (t<at[si][sj][sk]) {cout<<"ERR1402051256 SPHBND "<<i<<","<<j<<","<<k<<" z "<<si<<","<<sj<<","<<sk<<" "<<t<<" z "<<at[si][sj][sk]<<endl;}
#endif
}
float Approximation::find_and_compute_from_virtual_source_boundary(const float &w) {
float ww = SQR(w);
st = at_A + at_B - 2*at_Z;
if (abs(st)*w < 0.005f) { //rovinna vlna
float sina;
if (at_A < at_B) {
sina = (at_Z - at_A) * w/X;
}
else {
sina = (at_Z - at_B) * w/X;
}
if (abs(sina)>1)
return at_Z;
return at_Z + Zn*sqrtf(1 - SQR(sina))/w;
}
st = (SQR(at_A) + SQR(at_B) - 2*SQR(at_Z) - 2*SQR(X)/ww) / (2*st);
sx = -(ww * (at_B*(at_B - 2*st) - at_Z*(at_Z - 2*st)) - SQR(X)) / (2*X);
sz = ww * SQR(at_Z - st) - SQR(sx);
if (sz<0)
sz = 0;
sz = -sqrtf(sz);
if (st > at_Z) {//opacne zakrivenie - chcelo by to spresnit, ale to zakomentene nejak nefunguje
return at_Z + 1.f/w;
/*
sz = -sz;
if (st - sqrtf(SQR(Xn-sx) + SQR(Zn-sz))/w < at_Z) {
return at_Z;
}
return st - sqrtf(SQR(Xn-sx) + SQR(Zn-sz))/w;
*/
}
return st + sqrtf(SQR(Xn-sx) + SQR(Zn-sz))/w;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2004-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef SUPPORT_PROBETOOLS
#include "modules/probetools/probepoints.h"
#include "modules/probetools/src/probe.h"
#include "modules/probetools/src/probehelper.h"
OpProbe::OpProbe(void)
{
}
//Probe constructor without parameter
OpProbe::OpProbe(int lev, unsigned int loc, const char* loc_name, const OpProbeTimestamp &preamble_start) :
preamble_start_ts(preamble_start),
level(lev)
{
// Stamp start of constructor is done by OP_PROBE macro and assigned to preamble_start_ts
//probe_id + edge_id is updated if param is set.
probe_id = OpProbeIdentifier(loc,0);
// If probe is called to early, we ignore it.
OpProbeHelper* probehelper = g_probetools_helper;
if ( !probehelper ) {
probe_id = OpProbeIdentifier(0,0);
callstack_parent = 0;
return;
}
#ifdef PROBETOOLS_LOG_PROBES
probehelper->add_invocation(preamble_start, loc_name, TRUE);
#endif
// Get the interesting stuff from the helper
OpProbeThreadLocalStorage* tls = probehelper->tls();
OpProbeGraph* probegraph = probehelper->get_probe_graph();
if ( !probegraph ) {
probe_id = OpProbeIdentifier(0,0);
callstack_parent = 0;
return;
}
probegraph->probe[probe_id.get_location()].level = lev;
probegraph->probe[probe_id.get_location()].name = loc_name;
// Run startup logic for probe
startup_probe(tls);
// Stamp end of constructor is done by OP_PROBE macro
}
//logic for startup of probe
void OpProbe::startup_probe(OpProbeThreadLocalStorage* tls)
{
// Handle pending destructor
tls->handle_pending_destructor();
// Update probe stackpointer
callstack_parent = tls->update_stack_pointer(this);
// Find edge id
if ( callstack_parent != 0 )
edge_id = OpProbeEdgeIdentifier(callstack_parent->get_id(), get_id());
else
edge_id = OpProbeEdgeIdentifier();//root edge
//probe_id + edge_id is updated if param is set.
//initiate child activity as zero and register our presense at our parent
active_child = 0;
if ( callstack_parent != 0 )
callstack_parent->active_child = probe_id.get_location();
// Zero values populated by children
accumulated_children_total_time_registered_from_children.zero();
accumulated_children_overhead_registered_from_children.zero();
accumulated_children_recursive_self.zero();
accumulated_recursive_child_compansation.zero();
}
OpProbe::~OpProbe(void)
{
// Stamp start of destructor
postamble_start_ts.timestamp_now();
// If probe was called to early, we ignore it //IMPORTANT FOR TESTING STRATEGY
// We also ignore root probes! //IMPORTANT FOR TESTING STRATEGY
OpProbeHelper* probehelper = g_probetools_helper;
if ( !(probehelper && probe_id.get_location() && probe_id.get_location() != OP_PROBE_ROOT) )
return;
// Debug
if ( !probehelper->tls()->verify_probe_stack_pointer( this ) ) {
/*
fprintf(stderr, "ERROR: Messed up profiling stack!!\n");
fprintf(stderr, " Suddenly destroying probe 0x%04x\n", probe_id.get_location());
fflush(stderr);
fprintf(stderr, " Should have destroyed probe 0x%04x\n",
probehelper->tls()->get_stack_pointer_id().get_location());
fflush(stderr);
*/
OP_ASSERT(!"ERROR: Messed up profiling stack!!");
}
// Get the interesting stuff from the helper
OpProbeThreadLocalStorage* tls = probehelper->tls();
OpProbeGraph* probegraph = probehelper->get_probe_graph();
if (!probegraph)
return;
#ifdef PROBETOOLS_LOG_PROBES
probehelper->add_invocation(postamble_start_ts, probegraph->probe[probe_id.get_location()].name, FALSE);
#endif
// Call shutdown probe code
shutdown_probe(tls, probegraph);
// Signal for debugging; this instance is dead!
probe_id = OpProbeIdentifier(0xdead, probe_id.get_index_parameter());
// Stamp end of destructor
tls->register_pending_destructor_final_timestamp();
}
//logic for shutdown of probe
void OpProbe::shutdown_probe(OpProbeThreadLocalStorage* tls, OpProbeGraph* probegraph)
{
// Handle pending destructor
tls->handle_pending_destructor();
// Find edge
OpProbeEdge* edge = probegraph->find_edge(edge_id);
// Count initital overhead
OpProbeTimestamp preamble_overhead = preamble_stop_ts - preamble_start_ts;
edge->add_overhead(preamble_overhead);
// Count the probe times
OpProbeTimestamp edge_total_time = postamble_start_ts
- preamble_stop_ts
- accumulated_children_overhead_registered_from_children;
OpProbeTimestamp edge_self_time = edge_total_time
- accumulated_children_total_time_registered_from_children;
// If we are a recursive probe, count us!
OpProbe* recursive_parent_probe = find_recursive_immediate_parent(this);
if(recursive_parent_probe)
{
edge->count_recursive_edge(edge_self_time);
//if recursive, pass along our accumulated_children_recursive_self
recursive_parent_probe->accumulated_children_recursive_self += edge_self_time + accumulated_children_recursive_self;
//Clear accumulated_children_recursive_self since we are recursive ourself and have passed it to our r_parent
accumulated_children_recursive_self.zero();
//Just pass all our time to our recursive parent, so that its not counted twice
recursive_parent_probe->accumulated_recursive_child_compansation += edge_total_time;
}
// Count the normal part of us!
edge->count_edge(edge_total_time, edge_self_time, accumulated_children_recursive_self, accumulated_recursive_child_compansation);
// Pass stuff to parent
if(callstack_parent){
callstack_parent->accumulated_children_total_time_registered_from_children += edge_total_time;
callstack_parent->accumulated_children_overhead_registered_from_children += preamble_overhead + accumulated_children_overhead_registered_from_children; //postamble overhead will be added later
}
//Register pending destructor so that overhead can be calculated without any overhead
tls->register_pending_destructor(edge, callstack_parent, postamble_start_ts);
//Teardown stack
if ( callstack_parent != 0 )
callstack_parent->active_child = 0; // Closed nicely; we're no longer a child
tls->update_stack_pointer(callstack_parent);
}
//parameter
void OpProbe::set_probe_index_parameter(int index_parameter){
probe_id = OpProbeIdentifier(probe_id.get_location(), index_parameter);
edge_id = OpProbeEdgeIdentifier(callstack_parent->get_id(), get_id());
}
void OpProbe::init_root_probe(void)
{
level = 1;
callstack_parent = 0;
probe_id = OpProbeIdentifier(OP_PROBE_ROOT, 0);
edge_id = OpProbeEdgeIdentifier(0,OP_PROBE_ROOT,0,0);
active_child = 0;
accumulated_children_total_time_registered_from_children.zero();
accumulated_children_overhead_registered_from_children.zero();
}
OpProbe* OpProbe::find_recursive_immediate_parent(OpProbe* child)
{
OpProbe* candidate = child->callstack_parent;
while ( candidate ) {
if ( candidate->get_id().equals( child->get_id() ))
return candidate;
candidate = candidate->callstack_parent;
}
return 0;
}
#endif // SUPPORT_PROBETOOLS
|
#include <iostream>
#include <fstream>
#include <iomanip>
#include "AIM.h"
using namespace std;
int main(int argc, char* argv[]) {
int Lx = 256;
int Ly = 100;
double beta = 1.9;
double eps = 0.;
double rho0 = 6;
double h0 = 0.1;
int t_half = 100;
int n_period = 500;
unsigned long long seed = 5;
run_osc(Lx, beta, eps, rho0, h0, t_half, n_period, seed, false);
//run_reverse(Lx, beta, eps, rho0, h0, 2, 200);
//run_osc(Lx, Ly, beta, eps, rho0, h0, t_half, n_period, seed, true, false);
}
|
#include "quest.hpp"
namespace nora {
namespace scene {
pd::result quest_check_commit(uint32_t pttid, const role& role) {
const auto& ptt = PTTS_GET(quest, pttid);
if (!role.quest_has_accepted(ptt.id())) {
return pd::QUEST_NOT_ACCEPTED;
}
return role.quest_check_commit(ptt.id());
}
pd::event_array quest_commit_to_events(uint32_t pttid, role& role) {
ASSERT(role.quest_has_accepted(pttid));
auto& quest = role.get_accepted_quest(pttid);
pd::event_array events;
for (const auto& i : quest.counters_) {
if (i.type_ == pd::TURN_IN_ITEM) {
ASSERT(i.param_.arg_size() == 1);
auto need = i.param_.need();
if (need > 0) {
auto *e = events.add_events();
e->set_type(pd::event::REMOVE_ITEM);
e->add_arg(i.param_.arg(0));
e->add_arg(to_string(need));
}
} else if (i.type_ == pd::TURN_IN_RESOURCE) {
ASSERT(i.param_.arg_size() == 1);
auto need = i.param_.need();
if (need > 0) {
auto *e = events.add_events();
e->set_type(pd::event::DEC_RESOURCE);
e->add_arg(i.param_.arg(0));
e->add_arg(to_string(need));
}
}
}
event_merge(events, role.get_quest_cur_pass_events(pttid));
role.quest_move_to_next_param(pttid);
role.quest_commit(pttid);
return events;
}
pd::event_res quest_commit(uint32_t pttid, role& role) {
auto events = quest_commit_to_events(pttid, role);
const auto& ptt = PTTS_GET(quest, pttid);
pd::ce_env ce;
ce.set_origin(pd::CO_QUEST_COMMIT);
ce.add_actors(role.get_role_actor()->pttid());
if (ptt.has__everyday_quest()) {
const auto& eq_ptt = PTTS_GET(everyday_quest, ptt._everyday_quest());
ce.set_origin(pd::CO_QUEST_COMMIT_EVERYDAY_QUEST);
event_merge(events, eq_ptt.events());
} else if (ptt._activity_seven_days_fuli_quest()) {
ce.set_origin(pd::CO_ACTIVITY_SEVEN_DAYS_FULI);
} else if (ptt._activity_seven_days_quest()) {
ce.set_origin(pd::CO_ACTIVITY_SEVEN_DAYS_QUEST);
} else if (ptt.has__activity_leiji_recharge_quest()) {
ce.set_origin(pd::CO_ACTIVITY_LEIJI_RECHARGE);
} else if (ptt.has__activity_leiji_consume_quest()) {
ce.set_origin(pd::CO_ACTIVITY_LEIJI_CONSUME);
} else if (ptt.has__activity_festival_recharge_quest()) {
ce.set_origin(pd::CO_ACTIVITY_FESTIVAL_RECHARGE);
} else if (ptt.has__activity_festival_fuli_quest()) {
ce.set_origin(pd::CO_ACTIVITY_FESTIVAL_FULI);
} else if (ptt.has__activity_continue_recharge_quest()) {
ce.set_origin(pd::CO_ACTIVITY_CONTINUE_RECAHRGE);
} else if (ptt.has__activity_limit_play_quest()) {
ce.set_origin(pd::CO_ACTIVITY_LIMIT_PLAY);
} else if (ptt.has__activity_daiyanren_duihuan_quest()) {
ce.set_origin(pd::CO_ACTIVITY_DAIYANREN_DUIHUAN_REWARD);
} else if (ptt.has__activity_daiyanren_fuli_quest()) {
ce.set_origin(pd::CO_ACTIVITY_DAIYANREN_FULI_REWARD);
}
return event_process(events, role, ce);
}
void set_quest_to_events(uint32_t pttid, pd::event_array& events) {
auto *e = events.add_events();
e->set_type(pd::event::ACCEPT_QUEST);
e->add_arg(to_string(pttid));
}
pd::result quest_check_everyday_reward(uint32_t pttid, const role& role) {
const auto& ptt = PTTS_GET(everyday_quest_reward, pttid);
if (role.got_everyday_quest_reward(pttid)) {
return pd::QUEST_ALREADY_GOT_THIS_REWARD;
}
return condition_check(ptt.conditions(), role);
}
pd::event_res quest_everyday_reward(uint32_t pttid, role& role) {
const auto& ptt = PTTS_GET(everyday_quest_reward, pttid);
role.add_got_everyday_quest_reward(pttid);
pd::ce_env ce;
ce.set_origin(pd::CO_QUEST_EVERYDAY_QUEST_REWARD);
return event_process(ptt.events(), role, ce);
}
}
}
|
#pragma once
#include "texture/texture.h"
#include "math/vertex.h"
#include "vfs/vfs.h"
#include "q3shader/q3shader.h"
namespace q3bsp
{
struct BSPFace
{
int type;
int vertex;
int numverts;
int meshvertex;
int nummeshverts;
D3DXVECTOR3 nrm;
int texture;
int lightmap;
int size[2];
};
struct BSPNode
{
int plane;
int front;
int back;
D3DXVECTOR3 min;
D3DXVECTOR3 max;
};
struct BSPLeaf
{
int cluster;
int leafface;
int numleaffaces;
int leafbrush;
int numleafbrushes;
D3DXVECTOR3 min;
D3DXVECTOR3 max;
};
struct BSPPlane
{
D3DXVECTOR3 nrm;
float dst;
};
struct BSPBrush
{
int brushside;
int numbrushsides;
int texture;
};
struct BSPBrushSide
{
int plane;
int texture;
};
struct BSPTexture
{
char name[64];
int flags;
int contents;
};
struct BSPModel
{
float min[3]; // min position for the bounding box
float max[3]; // max position for the bounding box.
int faceIndex; // first face index in the model
int numOfFaces; // number of faces in the model
int brushIndex; // first brush index in the model
int numOfBrushes; // number brushes for the model
};
struct BSPLight
{
byte ambient[3]; // This is the ambient color in RGB
byte directional[3]; // This is the directional color in RGB
byte direction[2]; // The direction of the light: [phi,theta]
};
struct face_sort_t
{
int face_index;
int texture_index;
int lightmap_index;
BSPFace* face_address;
};
class BSP
{
public:
BSP(const string& filename);
~BSP();
public:
int leafFromPoint(const D3DXVECTOR3 &point);
void sortFaces();
public:
int num_verts;
int num_indices;
int num_faces;
int num_nodes;
int num_leafs;
int num_leaffaces;
int num_leafbrushes;
int num_brushes;
int num_brushsides;
int num_planes;
int num_clusters;
int num_textures;
int num_lightmaps;
int num_models;
int num_lights;
int cluster_size;
STDVertex *verts;
int *indices;
BSPFace *faces;
BSPNode *nodes;
BSPLeaf *leafs;
int *leaffaces;
int *leafbrushes;
BSPBrush *brushes;
BSPBrushSide *brushsides;
BSPPlane *planes;
byte *clusters;
BSPTexture *bsptextures;
BSPLight *lights;
BSPModel *models;
D3DXVECTOR3 lightgrid_origin;
D3DXVECTOR3 lightgrid_bounds;
texture::DXTexture** textures;
texture::DXTexture** lightmaps;
q3shader::Q3Shader** shaders;
texture::DXTexture* lightmap;
// render vars
int *sorted_faces;
int *drawn_faces;
int *transparent_faces;
int frame;
int last_texture;
int last_lightmap;
// counters
int frame_faces;
int frame_leafs;
int frame_polys;
int frame_textureswaps;
int frame_lightmapswaps;
int frame_transparent;
};
void R_ColorShiftLightingBytes(byte* in, int shift = 1);
}
|
void setup() {
pinMode(7, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(7, HIGH);
delay(82);
digitalWrite(7, LOW);
delay(30);
digitalWrite(7, HIGH);
delay(82);
digitalWrite(7, LOW);
delay(296);
}
|
#include "stdafx.h"
#include "CLog.h"
#include "IOCPHelper.h"
#include <iostream>
#include <string>
CLog::CLog()
{
m_logfile = "log.txt";
m_bOpened = false;
pData = NULL;
}
CLog::~CLog()
{
CloseLog();
SAFE_DELETE(pData);
}
CLog* CLog::pInstance = NULL;
CLog * CLog::Instance()
{
if (pInstance == NULL)
{
pInstance = new CLog();
}
return pInstance;
}
const HANDLE CLog::GetHanle()
{
return m_fileHandle;
}
bool CLog::Callback(PerIocpData * pData, DWORD size)
{
//Log("callback");
return true;
}
bool CLog::RegIOHandle()
{
return IOCPHelper::Instance()->RegHandle(this);
}
bool CLog::Init()
{
bool initSuccess = false;
m_fileHandle = CreateFile(L"log.txt", GENERIC_WRITE,0,NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED,NULL);
if (m_fileHandle == INVALID_HANDLE_VALUE)
{
Log("OpenFile Error. error code = " << GetLastError());
return false;
}
DWORD dwCurrentFilePosition = SetFilePointer(m_fileHandle, 0, NULL, FILE_END);
pData = new PerIocpData();
if (!pData) return false;
memset(pData, 0, sizeof(PerIocpData));
pData->overlapped.Offset = dwCurrentFilePosition;
initSuccess = RegIOHandle();
if (!initSuccess) return false;
m_bOpened = true;
return true;
}
bool CLog::CloseLog()
{
if(m_bOpened)
{
CloseHandle(m_fileHandle);
}
return true;
}
bool CLog::TranceLog(const char* str, ...)
{
if (m_bOpened == false)
{
return false;
}
va_list var;
va_start(var, str);
int nCount = _vscprintf(str, var);
char *pBuffer = new char[nCount + 1];
memset(pBuffer, 0, nCount + 1);
if (pBuffer)
{
vsprintf_s(pBuffer, nCount + 1, str, var);
}
#ifdef _DEBUG
cout << pBuffer;
#endif // _DEBUG
INT writenLen = 0;
DWORD temp;
while (writenLen < nCount)
{
DWORD lastWriteLen = (nCount - writenLen) >= IOCP_BUFFER_SIZE ? IOCP_BUFFER_SIZE : (nCount - writenLen);
memset(pData->buffer, 0, IOCP_BUFFER_SIZE);
memcpy_s(pData->buffer , IOCP_BUFFER_SIZE, pBuffer + writenLen, lastWriteLen);
BOOL ret = WriteFile(m_fileHandle, pData->buffer, lastWriteLen, &temp, &pData->overlapped);
pData->overlapped.Offset += lastWriteLen;
if (!ret)
{
DWORD retCode = GetLastError();
if (retCode != ERROR_IO_PENDING)
{
Log("write file error: " << retCode);
}
}
writenLen += lastWriteLen;
}
SAFE_DELETE(pBuffer);
return true;
}
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
vector<pair<char,int>> res;
int n,m;
cin>>n>>m;
string s;
cin>>s;
for(int i=0;i<n;i++){
if(res.size()==0){
res.push_back(make_pair(s[i],1));
}
else{
pair<char, int> p =res.back();
if(p.first==s[i]){
res.push_back(make_pair(s[i],p.second+1));
}
else{
if(p.second>=m){
for(int t=0;t<p.second;t++){
res.pop_back();
}
i--;
}
else
res.push_back(make_pair(s[i],1));
}
}
}
int ressize=res.size();
if(ressize==0)
cout<<"CLEAR!";
else{
for(int i=0;i<ressize;i++){
cout<<res[i].first;
}
}
}
|
#include "ThreadPool.hpp"
Elysium::Threading::ThreadPool::ThreadPool()
: Elysium::Core::Object()
{
}
Elysium::Threading::ThreadPool::~ThreadPool()
{
}
|
#include "gromacstoolsdefinition.h"
#include <cstddef>
#include <QFile>
#include <QTextStream>
#include <QDomDocument>
GromacsToolsDefinition & GromacsToolsDefinition::GetInstance()
{
static GromacsToolsDefinition instance;
return instance;
}
GromacsToolsDefinition::GromacsToolsDefinition() :
_globalConfigDir(QDir::homePath() + "/.grog"),
_defaultWorkingDirectory(QDir::home()),
_serizlizationFileName("gromacs_tools_definition.xml"),
_nonGromacsTool(QObject::tr("NA")),
_toolsDefaultValues({
{ToolsInfo("pdb2gmx", "pdb2gmx_config.xml", "pdb2gmx", "1_pdb2gmx" )},
{ToolsInfo("editconf", "editconf_config.xml", "editconf", "2_editconf" )},
{ToolsInfo("genbox", "genbox_config.xml", "genbox", "3_genbox" )},
{ToolsInfo("mdp file generator for energy minimization", "mdp-em_config.xml", _nonGromacsTool, "4_grompp-em")},
{ToolsInfo("grompp (energy minimization)", "grompp-em_config.xml", "grompp", "4_grompp-em")},
{ToolsInfo("mdrun (energy minimization)", "mdrun-em_config.xml", "mdrun", "5_mdrun-em" )},
{ToolsInfo("mdp file generator for position restraints", "mdp-pr_config.xml", _nonGromacsTool, "6_grompp-pr")},
{ToolsInfo("grompp (position restraints)", "grompp-pr_config.xml", "grompp", "6_grompp-pr")},
{ToolsInfo("mdrun (position restraints)", "mdrun-pr_config.xml", "mdrun", "7_mdrun-pr" )},
{ToolsInfo("mdp file generator", "mdp_config.xml", _nonGromacsTool, "8_grompp" )},
{ToolsInfo("grompp", "grompp_config.xml", "grompp", "8_grompp" )},
{ToolsInfo("mdrun", "mdrun_config.xml", "mdrun", "9_mdrun" )}
}),
_toolsDefinition(_toolsDefaultValues)
{
if(_globalConfigDir.exists())
{
FromXML();
}
else
{
qDebug("The global config dir \"%s\" does not exist!", _globalConfigDir.absolutePath().toStdString().c_str());
}
}
bool GromacsToolsDefinition::ToXML()
{
bool exitStatus = true;
QDomDocument document;
QDomProcessingInstruction xmlProcessingInstruction = document.createProcessingInstruction("xml", "");
xmlProcessingInstruction.setData("version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"");
document.appendChild(xmlProcessingInstruction);
QDomElement rootElement = document.createElement("GromacsToolsDefinition");
document.appendChild(rootElement);
QDomElement defaultWorkingDirectoryElement = document.createElement("DefaultWorkingDirectory");
defaultWorkingDirectoryElement.setAttribute("value", _defaultWorkingDirectory.absolutePath());
rootElement.appendChild(defaultWorkingDirectoryElement);
for(unsigned int i = 0; i < _toolsDefinition.size(); ++i)
{
QDomElement gromacsToolElement = document.createElement("GromacsTool");
gromacsToolElement.setAttribute("ToolName", _toolsDefinition[i]._toolName);
gromacsToolElement.setAttribute("ExecName", _toolsDefinition[i]._execName);
gromacsToolElement.setAttribute("WorkingDir", _toolsDefinition[i]._workingDir);
rootElement.appendChild(gromacsToolElement);
}
// TODO: concatenate files/dirs in a better way
QFile configFile(_globalConfigDir.absolutePath() + "/" + _serizlizationFileName);
if(configFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
{
QTextStream textStream(&configFile);
textStream << document.toString(4);
}
else
{
qDebug("Error! Cannot open \"%s\" properly!", configFile.fileName().toStdString().c_str());
exitStatus = false;
}
configFile.close();
return exitStatus;
}
bool GromacsToolsDefinition::FromXML()
{
// TODO: concatenate files/dirs in a better way
QFile configFile(_globalConfigDir.absolutePath() + "/" + _serizlizationFileName);
if(!configFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug("Error! Cannot open \"%s\" properly!", configFile.fileName().toStdString().c_str());
return false;
}
QString errorMessage;
int row, col;
QDomDocument domParser;
if(!domParser.setContent(&configFile, &errorMessage, &row, &col))
{
qDebug("Error at row \"%d\", col \"%d\" - \"%s\"", row, col, errorMessage.toStdString().c_str());
return false;
}
configFile.close();
QDomElement rootElement = domParser.documentElement();
if("GromacsToolsDefinition" != rootElement.tagName())
{
qDebug("The root element is \"%s\", but \"%s\" is expected!",
rootElement.tagName().toStdString().c_str(),
"GromacsToolsDefinition");
return false;
}
for(QDomNode node = rootElement.firstChild(); !node.isNull(); node = node.nextSibling())
{
if("DefaultWorkingDirectory" == node.nodeName())
{
_defaultWorkingDirectory = node.toElement().attribute("value");
}
else if("GromacsTool" == node.nodeName())
{
for(unsigned int i=0; i<_toolsDefinition.size(); ++i)
{
QDomElement element = node.toElement();
if(_toolsDefinition[i]._toolName == element.attribute("ToolName"))
{
_toolsDefinition[i]._execName = element.attribute("ExecName");
_toolsDefinition[i]._workingDir = element.attribute("WorkingDir");
// break;
}
}
}
else
{
qDebug("Warning: unexpected node name!");
}
}
return true;
}
|
/*
*Ultrasonic.h - Library for HC-SR04 Ultrasonic sensor module
*@Author:draon
*@DATA:2013-8-7
*Company website:www.elecfreaks.com
*/
#ifndef _ULTRASONIC_H_
#define _ULTRASONIC_H_
#include <stddef.h>
#if defined(ARDUINO) && ARDUINO >= 100
#include <Arduino.h>
#else
#include <Wprogram.h>
#endif
class Ultrasonic
{
public:
/*
*@param tp:trigger pin
*@param ep:echo pin
*/
Ultrasonic(int tp,int ep);
long timing();//return Ultrasonic sensor send and receive total time
/*
*@param microsec:Ultrasonic sensor send and receive total time
*@param metric:the value decide return value is Centimeters or inches
*@return calculate distance
*/
float CalcDistance(long microsec,int metric);
/*
*@param value:modify divisor value
*@param metric:judge set value is Centimeters divisor value or inches divisor value
*/
void SetDivisor(float value,int metric);
static const int CM = 1;
static const int IN = 0;
private:
int _trigPin;//Trigger Pin
int _EchoPin;//Echo Pin
float _cmDivisor;//centimeter divisor parameter
float _inDivisor;//Inches divisor parameter
};
#endif
|
#include <iostream>
using namespace std;
class complex {
private:
int re, im;
public:
complex(int r, int i): re(r), im(i)
{
cout<< "constructor called" << endl;
}
complex(const complex&);
complex operator+(const complex&);
complex operator*(const complex&);
int operator==(const complex&);
//complex operator=(const complex&);
complex& operator=(const complex&);
void print_complex() const ;
int get_read () const { return re; }
int get_imaginary () const { return im; }
};
/* Copy Constructor */
complex::complex(const complex& var)
{
cout<<"copy constructor called"<<endl;
if (this != &var){
re = var.re;
im = var.im;
}
return;
}
/* Add
* a + ib + c + id = (a+c) + i(b+d)
*/
complex complex::operator+(const complex& var)
{
cout<<"Operator overload + called" << endl;
this->re += var.re;
this->im += var.im;
return (*this);
}
/* Multiply
* (a+ib)*(c+id) = (a*c) + i(a*d + b*c) - (b*d)
*/
complex complex::operator*(const complex& var)
{
cout<<"Operator overload * called" << endl;
this->re = this->re*var.re - this->im*var.im;
this->im = this->re*var.im + this->im*var.re;
return (*this);
}
/* Copy assignment
* complex b = a;
*/
complex& complex::operator=(const complex& var)
{
cout<<"Operator overload = called" << endl;
this->re = var.re;
this->im = var.im;
return (*this);
}
int
complex::operator==(const complex& var)
{
return (re == var.re && im == var.im);
}
void
complex::print_complex () const
{
cout << "Real:"<<re << " Imaginary:"<<im << endl;
}
int main ()
{
complex a = complex(1,3);
complex b = complex(1,3);
if (a==b){
cout << "a and b are same" << endl;
} else {
cout << "a and b are different" << endl;
}
complex c = a+b;
return (0);
}
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "CryptoNoteCore/CryptoNoteBasic.h"
#include "ITransaction.h"
namespace cn {
bool checkInputsKeyimagesDiff(const cn::TransactionPrefix& tx);
// TransactionInput helper functions
size_t getRequiredSignaturesCount(const TransactionInput& in);
uint64_t getTransactionInputAmount(const TransactionInput& in);
transaction_types::InputType getTransactionInputType(const TransactionInput& in);
const TransactionInput& getInputChecked(const cn::TransactionPrefix& transaction, size_t index);
const TransactionInput& getInputChecked(const cn::TransactionPrefix& transaction, size_t index, transaction_types::InputType type);
bool isOutToKey(const crypto::PublicKey& spendPublicKey, const crypto::PublicKey& outKey, const crypto::KeyDerivation& derivation, size_t keyIndex);
// TransactionOutput helper functions
transaction_types::OutputType getTransactionOutputType(const TransactionOutputTarget& out);
const TransactionOutput& getOutputChecked(const cn::TransactionPrefix& transaction, size_t index);
const TransactionOutput& getOutputChecked(const cn::TransactionPrefix& transaction, size_t index, transaction_types::OutputType type);
bool findOutputsToAccount(const cn::TransactionPrefix& transaction, const AccountPublicAddress& addr,
const crypto::SecretKey& viewSecretKey, std::vector<uint32_t>& out, uint64_t& amount);
} //namespace cn
|
// Copyright 2017 Elias Kosunen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
//
// This file is a part of scnlib:
// https://github.com/eliaskosunen/scnlib
//
// The contents of this file are based on utfcpp:
// https://github.com/nemtrif/utfcpp
// Copyright (c) 2006 Nemanja Trifunovic
// Distributed under the Boost Software License, version 1.0
#ifndef SCN_UNICODE_COMMON_H
#define SCN_UNICODE_COMMON_H
#include "../detail/fwd.h"
#include <cstdint>
namespace scn {
SCN_BEGIN_NAMESPACE
/**
* A Unicode code point
*/
enum class code_point : uint32_t {};
template <typename T>
constexpr bool operator==(code_point a, T b)
{
return static_cast<uint32_t>(a) == static_cast<uint32_t>(b);
}
template <typename T>
constexpr bool operator!=(code_point a, T b)
{
return static_cast<uint32_t>(a) != static_cast<uint32_t>(b);
}
template <typename T>
constexpr bool operator<(code_point a, T b)
{
return static_cast<uint32_t>(a) < static_cast<uint32_t>(b);
}
template <typename T>
constexpr bool operator>(code_point a, T b)
{
return static_cast<uint32_t>(a) > static_cast<uint32_t>(b);
}
template <typename T>
constexpr bool operator<=(code_point a, T b)
{
return static_cast<uint32_t>(a) <= static_cast<uint32_t>(b);
}
template <typename T>
constexpr bool operator>=(code_point a, T b)
{
return static_cast<uint32_t>(a) >= static_cast<uint32_t>(b);
}
namespace detail {
static constexpr const uint16_t lead_surrogate_min = 0xd800;
static constexpr const uint16_t lead_surrogate_max = 0xdbff;
static constexpr const uint16_t trail_surrogate_min = 0xdc00;
static constexpr const uint16_t trail_surrogate_max = 0xdfff;
static constexpr const uint16_t lead_offset =
lead_surrogate_min - (0x10000u >> 10);
static constexpr const uint32_t surrogate_offset =
0x10000u - (lead_surrogate_min << 10) - trail_surrogate_min;
static constexpr const uint32_t code_point_max = 0x10ffff;
template <typename Octet>
constexpr uint8_t mask8(Octet o)
{
return static_cast<uint8_t>(0xff & o);
}
template <typename U16>
constexpr uint16_t mask16(U16 v)
{
return static_cast<uint16_t>(0xffff & v);
}
template <typename U16>
constexpr bool is_lead_surrogate(U16 cp)
{
return cp >= lead_surrogate_min && cp <= lead_surrogate_max;
}
template <typename U16>
constexpr bool is_trail_surrogate(U16 cp)
{
return cp >= trail_surrogate_min && cp <= trail_surrogate_max;
}
template <typename U16>
constexpr bool is_surrogate(U16 cp)
{
return cp >= lead_surrogate_min && cp <= trail_surrogate_max;
}
constexpr inline bool is_code_point_valid(code_point cp)
{
return cp <= code_point_max && !is_surrogate(cp);
}
} // namespace detail
template <typename T>
constexpr code_point make_code_point(T ch)
{
return static_cast<code_point>(ch);
}
/**
* Returns `true`, if `cp` is valid, e.g. is less than or equal to the
* maximum value for a code point (U+10FFFF), and is not a surrogate (U+D800
* to U+DFFF).
*/
constexpr inline bool is_valid_code_point(code_point cp)
{
return detail::is_code_point_valid(cp);
}
/**
* Returns `true` if `cp` can be encoded in ASCII as-is (is between U+0 and
* U+7F)
*/
constexpr inline bool is_ascii_code_point(code_point cp)
{
return cp <= 0x7f;
}
SCN_END_NAMESPACE
} // namespace scn
#endif
|
// HashDemo.cc
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <iomanip>
#include <functional>
#include <unordered_set>
#include "hash.h"
void HashTest(){
expression::HashContent plus_op("plus", 2);
expression::HashContent minus_op("minus", 2);
expression::HashContent multiply_op("multiply", 2);
expression::HashContent divide_op("divide", 2);
expression::HashContent exponent_op("exponent", 1);
expression::HashContent polynomial_op("polynomial", 1);
expression::HashContent plus_op_vice = plus_op;
std::cout<<plus_op.getOperation()<<" : "<<plus_op.getValue()<<"\n";
expression::HashContent object = {"convolute", 256};
std::cout<<object.getOperation()<<" : "<<object.getValue()<<"\n";
std::cout<<"plus_op"<<" == "<<"convolute ? "<<(plus_op == object)<<"\n";
std::cout<<"plus_op"<<" == "<<"plus_op_vice ? "<<(plus_op == plus_op_vice)<<"\n";
std::cout<<std::hash<expression::HashContent>{}(object)<<"\n";
/*
std::unordered_set<expression::HashContent> ops = {plus_op,
minus_op,
multiply_op,
divide_op,
exponent_op,
polynomial_op,
plus_op_vice};
for(auto& s: ops){
std::cout<<s.getOperation()<<" "<<s.getValue()<<"\n";
}
*/
}
int main(int args, char **argv){
HashTest();
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/logdoc/src/html5/h5node.h"
#include "modules/logdoc/src/html5/html5attrcopy.h"
#include "modules/logdoc/src/html5/html5tokenwrapper.h"
#include "modules/logdoc/src/html5/html5buffer.h"
#include "modules/stdlib/src/thirdparty_printf/uni_printf.h"
/*virtual*/ H5Node::~H5Node()
{
// gcc has problems with inline destructors
}
H5Node* H5Node::Next() const
{
if (FirstChild())
return FirstChild();
for (const H5Node *leaf = this; leaf; leaf = leaf->Parent())
if (leaf->Suc())
return leaf->Suc();
return NULL;
}
void H5Node::Under(H5Element *parent)
{
m_parent = parent;
if (H5Node *last_child = parent->LastChild())
{
m_pred = last_child;
last_child->m_suc = this;
}
else
m_parent->m_first_child = this;
m_parent->m_last_child = this;
}
void H5Node::Precede(H5Node *node_after)
{
m_parent = node_after->m_parent;
m_pred = node_after->m_pred;
if (m_pred)
m_pred->m_suc = this;
else if (m_parent)
m_parent->m_first_child = this;
m_suc = node_after;
node_after->m_pred = this;
}
void H5Node::Out()
{
if (m_suc)
// If we've a successor, unchain us
m_suc->m_pred = m_pred;
else if (m_parent)
// If we don't, we're the last in the list
static_cast<H5Element*>(m_parent)->m_last_child = m_pred;
if (m_pred)
// If we've a predecessor, unchain us
m_pred->m_suc = m_suc;
else if (m_parent)
// If we don't, we're the first in the list
static_cast<H5Element*>(m_parent)->m_first_child = m_suc;
m_pred = NULL;
m_suc = NULL;
m_parent = NULL;
}
/*virtual*/ H5Element::~H5Element()
{
OP_DELETEA(m_name);
OP_DELETEA(m_attrs);
}
/*virtual*/ BOOL H5Element::Clean()
{
H5Node *child = m_first_child;
while (child)
{
child->Clean();
child = m_first_child;
}
Out();
return TRUE;
}
void H5Element::SetNameL(const uni_char *name, unsigned len)
{
LEAVE_IF_ERROR(UniSetStrN(m_name, name, len));
}
BOOL H5Element::IsNamed(const uni_char *name, Markup::Type type)
{
if (m_elm_type != Markup::HTE_UNKNOWN)
return type == m_elm_type;
return uni_str_eq(name, m_name);
}
void H5Element::InitAttributesL(HTML5TokenWrapper *token)
{
unsigned new_attr_count = token->GetAttrCount();
if (new_attr_count > 0)
{
HTML5AttrCopy* new_attrs = OP_NEWA(HTML5AttrCopy, new_attr_count);
LEAVE_IF_NULL(new_attrs);
ANCHOR_ARRAY(HTML5AttrCopy, new_attrs);
if (token->HasLocalAttrCopies())
{
for (unsigned i = 0; i < new_attr_count; i++)
new_attrs[i].CopyL(token->GetLocalAttrCopy(i));
}
else
{
for (unsigned i = 0; i < new_attr_count; i++)
new_attrs[i].CopyL(token->GetAttribute(i));
}
ANCHOR_ARRAY_RELEASE(new_attrs);
m_attrs = new_attrs;
m_attr_count = new_attr_count;
}
}
const uni_char* H5Element::GetAttribute(const uni_char *name) const
{
for (unsigned i = 0; i < m_attr_count; i++)
{
if (uni_str_eq(name, m_attrs[i].GetName()->GetBuffer()))
return m_attrs[i].GetValue();
}
return NULL;
}
void H5Element::AddAttributeL(HTML5Token *token, unsigned attr_idx)
{
unsigned new_count = m_attr_count + 1;
HTML5AttrCopy *new_attrs = OP_NEWA(HTML5AttrCopy, new_count);
LEAVE_IF_NULL(new_attrs);
ANCHOR_ARRAY(HTML5AttrCopy, new_attrs);
for (unsigned i = 0; i < m_attr_count; i++)
new_attrs[i].CopyL(&m_attrs[i]);
new_attrs[new_count - 1].CopyL(token->GetAttribute(attr_idx));
ANCHOR_ARRAY_RELEASE(new_attrs);
OP_DELETEA(m_attrs);
m_attrs = new_attrs;
m_attr_count = new_count;
}
void H5Element::AddAttributeL(const uni_char *name, unsigned name_len, const uni_char *value, unsigned value_len)
{
unsigned new_count = m_attr_count + 1;
HTML5AttrCopy *new_attrs = OP_NEWA(HTML5AttrCopy, new_count);
LEAVE_IF_NULL(new_attrs);
ANCHOR_ARRAY(HTML5AttrCopy, new_attrs);
for (unsigned i = 0; i < m_attr_count; i++)
new_attrs[i].CopyL(&m_attrs[i]);
new_attrs[new_count - 1].SetNameL(name, name_len);
new_attrs[new_count - 1].SetValueL(value, value_len);
ANCHOR_ARRAY_RELEASE(new_attrs);
OP_DELETEA(m_attrs);
m_attrs = new_attrs;
m_attr_count = new_count;
}
void H5Element::SortAttributes()
{
// Bubble sort FTW!!!!!!
HTML5AttrCopy tmp;
for (unsigned i = 0; i < m_attr_count; i++)
for (unsigned j = i + 1; j < m_attr_count; j++)
{
if (m_attrs[j].GetNs() != Markup::HTML && m_attrs[j].GetNs() < m_attrs[i].GetNs()
|| uni_strcmp(m_attrs[j].GetName()->GetBuffer(), m_attrs[i].GetName()->GetBuffer()) < 0)
{
tmp = m_attrs[i];
m_attrs[i] = m_attrs[j];
m_attrs[j] = tmp;
}
}
// Clear tmp to avoid deletion of the strings
tmp.m_name.ReleaseBuffer();
tmp.m_value = NULL;
}
/*virtual*/ H5Comment::~H5Comment()
{
OP_DELETEA(m_data);
}
/*virtual*/ BOOL H5Comment::Clean()
{
Out();
return TRUE;
}
void H5Comment::InitDataL(HTML5Token *token)
{
unsigned dummy;
token->GetData().GetBufferL(m_data, dummy, TRUE);
}
void H5Comment::SetDataL(const uni_char *data, unsigned len)
{
LEAVE_IF_ERROR(UniSetStrN(m_data, data, len));
}
/*virtual*/ H5Doctype::~H5Doctype()
{
// gcc has problems with inline destructors
}
/*virtual*/ BOOL H5Doctype::Clean()
{
Out();
return TRUE;
}
void H5Doctype::InitL(const uni_char *name, const uni_char *public_id, const uni_char *system_id)
{
LEAVE_IF_ERROR(m_logdoc->SetDoctype(name, public_id, system_id));
}
/*virtual*/ H5Text::~H5Text()
{
// gcc has problems with inline destructors
}
/*virtual*/ BOOL H5Text::Clean()
{
Out();
return TRUE;
}
void H5Text::SetTextL(const uni_char *text, unsigned len)
{
m_text.Clear();
m_text.AppendL(text, len);
}
void H5Text::AppendTextL(const uni_char *text, unsigned len)
{
m_text.AppendL(text, len);
}
|
#ifndef MOVETHING_H
#define MOVETHING_H
#include "direction.h"
#include <QRect>
class MoveThing {
public:
MoveThing();
MoveThing(int x,
int y,
int width,
int height,
int directio_n,
int _moveSpeed);
virtual void initialize();
virtual void returnOriginPos();
virtual void updatePos(int judge_unit);
virtual void confirmPos();
virtual void cancelPos();
virtual void needToChangeMove();
virtual const QRect& getTempPos();
int getDirection() const;
void setDirection(int directio_n);
int getMoveSpeed() const;
protected:
int directio_n;
int _originDirection;
int _moveSpeed;
QRect _tempPos;
};
#endif // MOVETHING_H
|
#pragma once
#include "utils/ptts.hpp"
#include "proto/config_item.pb.h"
using namespace std;
namespace pc = proto::config;
namespace nora {
namespace config {
using item_ptts = ptts<pc::item>;
item_ptts& item_ptts_instance();
void item_ptts_set_funcs();
using item_xinwu_exchange_ptts = ptts<pc::item_xinwu_exchange>;
item_xinwu_exchange_ptts& item_xinwu_exchange_ptts_instance();
void item_xinwu_exchange_ptts_set_funcs();
}
}
|
int Solution::reverse(int A) {
if (A > INT_MAX || A < INT_MIN)
return 0;
int rev = 0;
int a = abs(A);
while (a)
{
int digit = a % 10;
if (rev > (INT_MAX / 10) || (rev == INT_MAX / 10 && digit > INT_MAX % 10))
return 0;
rev *= 10;
rev += digit;
a /= 10;
}
if (A < 0)
rev *= -1;
return rev;
}
|
#ifndef SCC_H
#define SCC_H
/*
* SCC.h
*
* Defines the SCC coprocessor
*
*/
// includes
#include <Coprocessor.h>
#include <Register.h>
#include <vector>
#include <functional>
// forward declaration
class cpu;
// scc: cop0, deals with exception handling and memory management
class scc : public coprocessor
{
// cpu needs to access registers
friend cpu;
/*** REGISTERS ***/
CoprocessorReg data_reg[16];
/*** FUNCTION POINTERS ***/
std::vector<std::function<void(scc*)>> instruction;
public:
scc();
// register transfers
void writeDataReg(word data_in, unsigned dest_reg) override;
word readDataReg(unsigned source_reg) const override;
private:
/*** INSTRUCTIONS ***/
void TLBR();
void TLBWI();
void TLBWR();
void TLBP();
void RFE();
public:
enum
{
INDX = 0,
RAND,
TLBL,
BPC,
CTXT,
BDA,
PIDMASK,
DCIC,
BADV,
BDAM,
TLBH,
BPCM,
SR,
CAUSE,
EPC,
PRID,
ERREG
};
};
#endif
|
/**
* @file filter2D_demo.cpp
* @brief Sample code that shows how to implement your own linear filters by using filter2D function
* @author OpenCV team
*/
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
using namespace cv;
/**
* @function main
*/
int main ( int argc, char** argv )
{
/// Declare variables
Mat src, dst;
Mat kernel;
Point anchor;
double delta;
int ddepth;
int kernel_size;
const char* window_name = "filter2D Demo";
//![load]
String imageName("../data/lena.jpg"); // by default
if (argc > 1)
{
imageName = argv[1];
}
src = imread( imageName, IMREAD_COLOR ); // Load an image
if( src.empty() )
{ return -1; }
//![load]
//![init_arguments]
/// Initialize arguments for the filter
anchor = Point( -1, -1 );
delta = 0;
ddepth = -1;
//![init_arguments]
/// Loop - Will filter the image with different kernel sizes each 0.5 seconds
int ind = 0;
for(;;)
{
char c = (char)waitKey(500);
/// Press 'ESC' to exit the program
if( c == 27 )
{ break; }
//![update_kernel]
/// Update kernel size for a normalized box filter
kernel_size = 3 + 2*( ind%5 );
kernel = Mat::ones( kernel_size, kernel_size, CV_32F )/ (float)(kernel_size*kernel_size);
//![update_kernel]
//![apply_filter]
filter2D(src, dst, ddepth , kernel, anchor, delta, BORDER_DEFAULT );
//![apply_filter]
imshow( window_name, dst );
ind++;
}
return 0;
}
|
/*
Name : Aman Jain
Date : 15-07-2020
Question-> https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
Time complexity : O(n)
Space Complexity : O(1)
*/
#include<bits/stdc++.h>
using namespace std;
long long kandaneAlgo(long long *arr, int n){
long long curr_sum=arr[0];
long long max_sum=arr[0];
long long previous_sum=arr[0];
for(int i=1; i<n ;i++){
curr_sum=previous_sum+arr[i];
previous_sum=max(arr[i],curr_sum);
max_sum=max(previous_sum,max_sum);
}
return max_sum;
}
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
long long arr[n];
for(int i=0 ; i<n ; i++){
cin>>arr[i];
}
cout<<kandaneAlgo(arr,n)<<endl;
}
}
|
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<iostream>
#include<arpa/inet.h>
#define SERVER_PORT 6666
#define BUFFER_SIZE 1024
#define FILE_NAME_MAX_SIZE 512
using namespace std;
int main(int argc, char **argv)
{
if (argc != 2){
cout<<"Usage: ./"<<argv[0]<<"ServerIPAddress"<<endl;
exit(1);
}
struct sockaddr_in client_addr;
bzero(&client_addr, sizeof(client_addr));
client_addr.sin_family = AF_INET;
client_addr.sin_addr.s_addr = htons(INADDR_ANY);
client_addr.sin_port = htons(0);
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket < 0){
cout<<"Create Socket Failed!"<<endl;
exit(1);
}
if (bind(client_socket, (struct sockaddr*)&client_addr, sizeof(client_addr))){
cout<<"Client Bind Port Failed!"<<endl;
exit(1);
}
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
if (inet_aton(argv[1], &server_addr.sin_addr) == 0) {
cout<<"Server IP Address Error!"<<endl;
exit(1);
}
server_addr.sin_port = htons(SERVER_PORT);
socklen_t server_addr_length = sizeof(server_addr);
if (connect(client_socket, (struct sockaddr*)&server_addr, server_addr_length) < 0){
cout<<"Can Not Connect To"<<argv[1]<<"!"<<endl;
exit(1);
}
char file_name[FILE_NAME_MAX_SIZE + 1];
bzero(file_name, sizeof(file_name));
cout<<"The Server File List:"<<endl;
cout<<"1.txt\t2.txt\t3.txt\t4.txt\t5.txt\t6.txt\t7.txt\t8.txt\t9.txt\t10.txt"<<endl;
cout<<"Please Input File Name On Server."<<endl;
cin>>file_name;
char buffer[BUFFER_SIZE];
bzero(buffer, sizeof(buffer));
strncpy(buffer, file_name, strlen(file_name) > BUFFER_SIZE ? BUFFER_SIZE : strlen(file_name));
send(client_socket, buffer, BUFFER_SIZE, 0);
FILE *fp = fopen(file_name, "w");
if (fp == NULL){
printf("File:\t%s Can Not Open To Write!\n", file_name);
exit(1);
}
bzero(buffer, sizeof(buffer));
int length = 0;
while((length = recv(client_socket, buffer, BUFFER_SIZE, 0))){
if (length < 0){
printf("Recieve Data From Server %s Failed!\n", argv[1]);
break;
}
int write_length = fwrite(buffer, sizeof(char), length, fp);
if (write_length < length){
printf("File:\t%s Write Failed!\n", file_name);
break;
}
bzero(buffer, BUFFER_SIZE);
}
printf("Recieve File:\t %s From Server[%s] Finished!\n", file_name, argv[1]);
fclose(fp);
close(client_socket);
return 0;
}
|
/*
* stbst.h
*
* Date Author Notes
* =====================================================
* 2014-04-14 Kempe Initial version
* 2015-04-06 Redekopp Updated formatting and removed
* KeyExistsException
*/
#include <iostream>
#include <exception>
#include <cstdlib>
#include "bst.h"
/* -----------------------------------------------------
* Splay Search Tree
------------------------------------------------------*/
template <class KeyType, class ValueType>
class SplayTree : public BinarySearchTree<KeyType, ValueType>
{
public:
Node<KeyType, ValueType>* find(const KeyType & k)
{
Node<KeyType, ValueType> *curr = internalFind(k);
if (curr) {
splay(curr);
this->root = curr;
}
return curr;
}
void insert (const std::pair<const KeyType, ValueType>& new_item) {
// SplayNode<KeyType, ValueType>* node = new SplayNode<KeyType, ValueType>(new_item.first, new_item.second, NULL);
Node<KeyType, ValueType>* node = new Node<KeyType, ValueType>(new_item.first, new_item.second, NULL);
if (this->root == NULL) {
this->root = node;
}
else {
splay(treeInsert(this->root, node));
this->root = node;
}
}
protected:
Node<KeyType, ValueType>* internalFind(const KeyType& k) {
Node<KeyType, ValueType> *curr = this->root;
while (curr) {
if (curr->getKey() == k) {
return curr;
} else if (k < curr->getKey()) {
curr = curr->getLeft();
} else {
curr = curr->getRight();
}
}
return NULL;
}
Node<KeyType, ValueType>* treeInsert(Node<KeyType, ValueType>* curr, Node<KeyType, ValueType>* n) {
if (curr->getKey() < n->getKey()) {
if (curr->getRight() == NULL) {
curr->setRight(n);
n->setParent(curr);
return n;
}
else {
return treeInsert(curr->getRight(), n);
}
}
else if (n->getKey() < curr->getKey()){
if (curr->getLeft() == NULL) {
curr->setLeft(n);
n->setParent(curr);
return n;
}
else {
return treeInsert(curr->getLeft(), n);
}
}
else {
n->setParent(curr->getParent());
n->setLeft(curr->getLeft());
n->setRight(curr->getRight());
delete curr;
return n;
}
}
Node<KeyType, ValueType>* findMyUncle(Node<KeyType, ValueType>* n) {
if (n->getParent()->getParent()->getRight() == n->getParent()) {
return n->getParent()->getParent()->getLeft();
}
else {
return n->getParent()->getParent()->getRight();
}
}
bool AmIaLeftChild(Node<KeyType, ValueType>* n) {
return n->getParent()->getLeft() == n;
}
void LeftRotate(Node<KeyType, ValueType>* n) {
Node<KeyType, ValueType>* p = n->getParent();
p->setRight(n->getLeft());
if (n->getLeft() != NULL) {
p->getRight()->setParent(p);
}
n->setLeft(p);
n->setParent(p->getParent());
if (p->getParent() != NULL) {
if (AmIaLeftChild(p)) {
p->getParent()->setLeft(n);
}
else {
p->getParent()->setRight(n);
}
}
p->setParent(n);
}
void RightRotate(Node<KeyType, ValueType>* n) {
Node<KeyType, ValueType>* p = n->getParent();
p->setLeft(n->getRight());
if (n->getRight() != NULL) {
p->getLeft()->setParent(p);
}
n->setRight(p);
n->setParent(p->getParent());
if (p->getParent() != NULL) {
if (AmIaLeftChild(p)) {
p->getParent()->setLeft(n);
}
else {
p->getParent()->setRight(n);
}
}
p->setParent(n);
}
void splay(Node<KeyType, ValueType>* n) {
if (n) {
if (n->getParent()) {
if (n->getParent()->getParent()) {
if (AmIaLeftChild(n->getParent())) {
if (AmIaLeftChild(n)) {
RightRotate(n->getParent());
RightRotate(n);
}
else {
LeftRotate(n);
RightRotate(n);
}
}
else {
if (AmIaLeftChild(n)) {
RightRotate(n);
LeftRotate(n);
}
else {
LeftRotate(n->getParent());
LeftRotate(n);
}
}
splay(n);
}
else {
//case 3
if (AmIaLeftChild(n)) {
n->getParent()->setLeft(n->getRight());
if (n->getParent()->getLeft()) {
n->getParent()->getLeft()->setParent(n->getParent());
}
n->setRight(n->getParent());
n->getParent()->setParent(n);
n->setParent(NULL);
}
else {
n->getParent()->setRight(n->getLeft());
if (n->getParent()->getRight()) {
n->getParent()->getRight()->setParent(n->getParent());
}
n->setLeft(n->getParent());
n->getParent()->setParent(n);
n->setParent(NULL);
}
}
}
}
}
};
|
#pragma once
#include "CoreMinimal.h"
#include "Engine/DataTable.h"
#include "Struct/NpcDialogInfo/NpcDialogInfo.h"
#include "NpcInfo.generated.h"
USTRUCT(BlueprintType)
struct ARPG_API FNpcInfo :
public FTableRowBase
{
GENERATED_USTRUCT_BODY()
public:
// Npc 이름
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FText NpcName;
// 기본 대화 정보
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FNpcDialogInfo DefaultDialogInfo;
// 상점 코드
UPROPERTY(EditAnywhere, BLueprintReadWrite)
FName ShopCode;
public :
FORCEINLINE bool IsEmpty() const
{ return NpcName.IsEmpty(); }
FORCEINLINE bool UseShop() const
{ return !ShopCode.IsNone(); }
};
|
/************************************************************************
Class Name: qIFunctionManager
Date: 10/30/02
Purpose: This is the interface for the Function Manager classes, which
are StateManager and ProcessManager. The only thing that differs between
the two classes is the process function, so I decided to just derive
them off this interface.
************************************************************************/
/************************************************************************/
/* Includes */
/************************************************************************/
#pragma once
#define INIT_PURPOSE 0
#define FRAME_PURPOSE 1
#define SHUTDOWN_PURPOSE 2
#include <qEngine/qCommonInclude.h>
/************************************************************************/
/* Class Declarations */
/************************************************************************/
namespace qEngine
{
typedef bool (*qFunctionPtr)(int Purpose);
class qIFunctionManager
{
public:
qIFunctionManager(void);
virtual ~qIFunctionManager(void);
void push(qFunctionPtr fpFunctionHandler);
void pop();
void clear();
UINT numFunctions() { return (UINT)m_vFunctionVector.size(); }
virtual void process(int iPurpose) = 0;
protected:
vector<qFunctionPtr> m_vFunctionVector;
};
}
|
#include <SFML/Window.hpp>
#include <iostream>
#define GLEW_STATIC
#include <GL/glew.h>
using namespace std;
void initGlew();
int main()
{
sf::ContextSettings settings;
settings.depthBits = 24;
settings.stencilBits = 8;
settings.antialiasingLevel = 2;
sf::Window window(sf::VideoMode(800, 600), "OpenGL", sf::Style::Close, settings);
initGlew();
bool running = true;
while (running)
{
sf::Event windowEvent;
while (window.pollEvent(windowEvent))
{
switch (windowEvent.type)
{
case sf::Event::Closed:
running = false;
break;
case sf::Event::KeyPressed:
if (windowEvent.key.code == sf::Keyboard::Escape)
running = false;
break;
default:
break;
}
}
}
return 0;
}
void initGlew()
{
glewExperimental = GL_TRUE;
glewInit();
}
|
/*
plot lines and wind
last modify:2010 10 14
*/
#ifndef _PLOT_PANEL_
#define _PLOT_PANEL_
#include "wx/wx.h"
#include "wx/sizer.h"
#include "wx/listctrl.h"
#include "main-frame.h"
class PlotPanel : public wxPanel
{
wxListCtrl * list1;
wxButton * button1;
MyFrame * pant;
public:
PlotPanel(wxPanel* parent);
void paintEvent(wxPaintEvent & evt);
void paintNow();
void UpdateListTitle();
void DrawWind(wxDC& dc, double posX, double posY, double value, double direction);
// some useful events
/*
void mouseMoved(wxMouseEvent& event);
void mouseWheelMoved(wxMouseEvent& event);
void mouseReleased(wxMouseEvent& event);
void mouseLeftWindow(wxMouseEvent& event);
void keyPressed(wxKeyEvent& event);
void keyReleased(wxKeyEvent& event);
*/
void mouseDown(wxMouseEvent& event);
void rightClick(wxMouseEvent& event);
void SetWind(wxCommandEvent& event);
DECLARE_EVENT_TABLE()
};
#endif //_PLOT_PANEL_
|
/*
* @Description: 从点云中截取一个立方体部分
* @Author: Ren Qian
* @Date: 2020-03-04 20:09:37
*/
#ifndef LIDAR_LOCALIZATION_MODELS_CLOUD_FILTER_BOX_FILTER_HPP_
#define LIDAR_LOCALIZATION_MODELS_CLOUD_FILTER_BOX_FILTER_HPP_
#include <pcl/filters/crop_box.h>
#include "lidar_localization/models/cloud_filter/cloud_filter_interface.hpp"
namespace lidar_localization {
class BoxFilter: public CloudFilterInterface {
public:
BoxFilter(YAML::Node node);
BoxFilter() = default;
bool Filter(const CloudData::CLOUD_PTR& input_cloud_ptr, CloudData::CLOUD_PTR& filtered_cloud_ptr) override;
void SetSize(std::vector<float> size);
void SetOrigin(std::vector<float> origin);
std::vector<float> GetEdge();
private:
void CalculateEdge();
private:
pcl::CropBox<CloudData::POINT> pcl_box_filter_;
std::vector<float> origin_;
std::vector<float> size_;
std::vector<float> edge_;
};
}
#endif
|
#include <string.h>
#include "hitmap.h"
HitMap::HitMap(const struct xfm &xfm_, unsigned x, unsigned y)
: hm_xfm(xfm_)
, dimx(x)
, dimy(y)
{
init_img();
}
HitMap::HitMap(unsigned x, unsigned y)
: dimx(x)
, dimy(y)
{
init_img();
}
HitMap::~HitMap()
{
for (unsigned i = 0; i < dimy; i++) delete img[i];
delete [] img;
}
void HitMap::init_img(void)
{
img = new unsigned char*[dimy];
for (unsigned i = 0; i < dimy; i++) {
img[i] = new unsigned char[dimx];
memset(img[i], 0, dimx);
}
}
void HitMap::inc(double x, double y)
{
unsigned x_img = (unsigned int)((x + hm_xfm.xlateX) * hm_xfm.scaleX);
unsigned y_img = (unsigned int)((y + hm_xfm.xlateY) * hm_xfm.scaleY);
/* out of bounds? */
if (x_img >= dimx || y_img >= dimy)
return;
if (img[y_img][x_img] < 0xff)
img[y_img][x_img]++;
}
unsigned HitMap::get_fill_count(void) const
{
unsigned ret = 0;
for (unsigned y_idx = 0; y_idx < dimy; y_idx++)
for(unsigned x_idx = 0; x_idx < dimx; x_idx++)
if (img[y_idx][x_idx])
ret++;
return ret;
}
|
/*
Copyright (c) 2015, M. Kerber, D. Morozov, A. Nigmetov
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You are under no obligation whatsoever to provide any bug fixes, patches, or
upgrades to the features, functionality or performance of the source code
(Enhancements) to anyone; however, if you choose to make your Enhancements
available either publicly, or directly to copyright holder,
without imposing a separate written license agreement for such Enhancements,
then you hereby grant the following license: a non-exclusive, royalty-free
perpetual license to install, use, modify, prepare derivative works, incorporate
into other computer software, distribute, and sublicense such enhancements or
derivative works thereof, in binary and source code form.
*/
#ifndef AUCTION_ORACLE_KDTREE_RESTRICTED_HPP
#define AUCTION_ORACLE_KDTREE_RESTRICTED_HPP
#include <assert.h>
#include <algorithm>
#include <functional>
#include <iterator>
#include "def_debug_ws.h"
#include "auction_oracle_kdtree_restricted.h"
#ifdef FOR_R_TDA
#undef DEBUG_AUCTION
#endif
namespace hera {
namespace ws {
// *****************************
// AuctionOracleKDTreeRestricted
// *****************************
template <class Real_, class PointContainer_>
std::ostream& operator<<(std::ostream& output, const AuctionOracleKDTreeRestricted<Real_, PointContainer_>& oracle)
{
output << "Oracle " << &oracle << std::endl;
output << "max_val_ = " << oracle.max_val_ << ", ";
output << "best_diagonal_items_computed_ = " << oracle.best_diagonal_items_computed_ << ", ";
output << "best_diagonal_item_value_ = " << oracle.best_diagonal_item_value_ << ", ";
output << "second_best_diagonal_item_idx_ = " << oracle.second_best_diagonal_item_idx_ << ", ";
output << "second_best_diagonal_item_value_ = " << oracle.second_best_diagonal_item_value_ << ", ";
output << "prices = " << format_container_to_log(oracle.prices) << "\n";
output << "diag_items_heap_ = " << losses_heap_to_string(oracle.diag_items_heap_) << "\n";
output << "top_diag_indices_ = " << format_container_to_log(oracle.top_diag_indices_) << "\n";
output << "top_diag_counter_ = " << oracle.top_diag_counter_ << "\n";
output << "top_diag_lookup_ = " << format_container_to_log(oracle.top_diag_lookup_) << "\n";
output << "end of oracle " << &oracle << std::endl;
return output;
}
template<class Real_, class PointContainer_>
AuctionOracleKDTreeRestricted<Real_, PointContainer_>::AuctionOracleKDTreeRestricted(const PointContainer_& _bidders,
const PointContainer_& _items,
const AuctionParams<Real>& params) :
AuctionOracleBase<Real>(_bidders, _items, params),
heap_handles_indices_(_items.size(), k_invalid_index),
kdtree_items_(_items.size(), k_invalid_index),
top_diag_lookup_(_items.size(), k_invalid_index)
{
size_t dnn_item_idx { 0 };
size_t true_idx { 0 };
dnn_points_.clear();
dnn_points_.reserve(this->items.size());
// store normal items in kd-tree
for(const auto& g : this->items) {
if (g.is_normal() ) {
kdtree_items_[true_idx] = dnn_item_idx;
// index of items is id of dnn-point
DnnPoint p(true_idx);
p[0] = g.getRealX();
p[1] = g.getRealY();
dnn_points_.push_back(p);
assert(dnn_item_idx == dnn_points_.size() - 1);
dnn_item_idx++;
}
true_idx++;
}
assert(dnn_points_.size() < _items.size() );
for(size_t i = 0; i < dnn_points_.size(); ++i) {
dnn_point_handles_.push_back(&dnn_points_[i]);
}
DnnTraits traits;
traits.internal_p = params.internal_p;
kdtree_ = new dnn::KDTree<DnnTraits>(traits, dnn_point_handles_, params.wasserstein_power);
size_t handle_idx {0};
for(size_t item_idx = 0; item_idx < _items.size(); ++item_idx) {
if (this->items[item_idx].is_diagonal()) {
heap_handles_indices_[item_idx] = handle_idx++;
diag_heap_handles_.push_back(diag_items_heap_.push(std::make_pair(item_idx, 0.0)));
}
}
max_val_ = 3*getFurthestDistance3Approx<>(_bidders, _items, params.internal_p);
max_val_ = std::pow(max_val_, params.wasserstein_power);
weight_adj_const_ = max_val_;
}
template<class Real_, class PointContainer_>
bool AuctionOracleKDTreeRestricted<Real_, PointContainer_>::is_in_top_diag_indices(const size_t item_idx) const
{
return top_diag_lookup_[item_idx] != k_invalid_index;
}
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::add_top_diag_index(const size_t item_idx)
{
assert(find(top_diag_indices_.begin(), top_diag_indices_.end(), item_idx) == top_diag_indices_.end());
assert(this->items[item_idx].is_diagonal());
top_diag_indices_.push_back(item_idx);
top_diag_lookup_[item_idx] = top_diag_indices_.size() - 1;
}
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::remove_top_diag_index(const size_t item_idx)
{
if (top_diag_indices_.size() > 1) {
// remove item_idx from top_diag_indices after swapping
// it with the last element, update index lookup appropriately
auto old_index = top_diag_lookup_[item_idx];
auto end_element = top_diag_indices_.back();
std::swap(top_diag_indices_[old_index], top_diag_indices_.back());
top_diag_lookup_[end_element] = old_index;
}
top_diag_indices_.pop_back();
top_diag_lookup_[item_idx] = k_invalid_index;
if (top_diag_indices_.size() < 2) {
recompute_second_best_diag();
}
best_diagonal_items_computed_ = not top_diag_indices_.empty();
reset_top_diag_counter();
}
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::increment_top_diag_counter()
{
assert(top_diag_counter_ < top_diag_indices_.size());
++top_diag_counter_;
if (top_diag_counter_ >= top_diag_indices_.size()) {
top_diag_counter_ -= top_diag_indices_.size();
}
assert(top_diag_counter_ < top_diag_indices_.size());
}
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::reset_top_diag_counter()
{
top_diag_counter_ = 0;
}
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::recompute_top_diag_items(bool hard)
{
assert(hard or top_diag_indices_.empty());
if (hard) {
std::fill(top_diag_lookup_.begin(), top_diag_lookup_.end(), k_invalid_index);
top_diag_indices_.clear();
}
auto top_diag_iter = diag_items_heap_.ordered_begin();
best_diagonal_item_value_ = top_diag_iter->second;
add_top_diag_index(top_diag_iter->first);
++top_diag_iter;
// traverse the heap while we see the same value
while(top_diag_iter != diag_items_heap_.ordered_end()) {
if ( top_diag_iter->second != best_diagonal_item_value_) {
break;
} else {
add_top_diag_index(top_diag_iter->first);
}
++top_diag_iter;
}
recompute_second_best_diag();
best_diagonal_items_computed_ = true;
reset_top_diag_counter();
}
template<class Real_, class PointContainer_>
typename AuctionOracleKDTreeRestricted<Real_, PointContainer_>::DebugOptimalBidR
AuctionOracleKDTreeRestricted<Real_, PointContainer_>::get_optimal_bid_debug(IdxType bidder_idx) const
{
auto bidder = this->bidders[bidder_idx];
size_t best_item_idx = k_invalid_index;
size_t second_best_item_idx = k_invalid_index;
Real best_item_value = std::numeric_limits<Real>::max();
Real second_best_item_value = std::numeric_limits<Real>::max();
for(IdxType item_idx = 0; item_idx < static_cast<IdxType>(this->items.size()); ++item_idx) {
auto item = this->items[item_idx];
if (item.type != bidder.type and item_idx != bidder_idx)
continue;
auto item_value = std::pow(dist_lp(bidder, item, this->internal_p, 2), this->wasserstein_power) + this->prices[item_idx];
if (item_value < best_item_value) {
best_item_value = item_value;
best_item_idx = item_idx;
}
}
assert(best_item_idx != k_invalid_index);
for(size_t item_idx = 0; item_idx < this->items.size(); ++item_idx) {
auto item = this->items[item_idx];
if (item.type != bidder.type and static_cast<IdxType>(item_idx) != bidder_idx)
continue;
if (item_idx == best_item_idx)
continue;
auto item_value = std::pow(dist_lp(bidder, item, this->internal_p, 2), this->wasserstein_power) + this->prices[item_idx];
if (item_value < second_best_item_value) {
second_best_item_value = item_value;
second_best_item_idx = item_idx;
}
}
assert(second_best_item_idx != k_invalid_index);
assert(second_best_item_value >= best_item_value);
DebugOptimalBidR result;
result.best_item_idx = best_item_idx;
result.best_item_value = best_item_value;
result.second_best_item_idx = second_best_item_idx;
result.second_best_item_value = second_best_item_value;
return result;
}
template<class Real_, class PointContainer_>
IdxValPair<Real_> AuctionOracleKDTreeRestricted<Real_, PointContainer_>::get_optimal_bid(IdxType bidder_idx)
{
auto bidder = this->bidders[bidder_idx];
// corresponding point is always considered as a candidate
// if bidder is a diagonal point, proj_item is a normal point,
// and vice versa.
size_t best_item_idx { k_invalid_index };
size_t best_diagonal_item_idx { k_invalid_index };
Real best_item_value;
Real second_best_item_value;
size_t proj_item_idx = bidder_idx;
assert( proj_item_idx < this->items.size() );
assert(this->items[proj_item_idx].type != bidder.type);
Real proj_item_value = this->get_value_for_bidder(bidder_idx, proj_item_idx);
if (bidder.is_diagonal()) {
// for diagonal bidder the only normal point has already been added
// the other 2 candidates are diagonal items only, get from the heap
// with prices
if (not best_diagonal_items_computed_) {
recompute_top_diag_items();
}
best_diagonal_item_idx = top_diag_indices_[top_diag_counter_];
increment_top_diag_counter();
if ( proj_item_value < best_diagonal_item_value_) {
best_item_idx = proj_item_idx;
best_item_value = proj_item_value;
second_best_item_value = best_diagonal_item_value_;
} else if (proj_item_value < second_best_diagonal_item_value_) {
best_item_idx = best_diagonal_item_idx;
best_item_value = best_diagonal_item_value_;
second_best_item_value = proj_item_value;
} else {
best_item_idx = best_diagonal_item_idx;
best_item_value = best_diagonal_item_value_;
second_best_item_value = second_best_diagonal_item_value_;
}
} else {
// for normal bidder get 2 best items among non-diagonal points from
// kdtree_
DnnPoint bidder_dnn;
bidder_dnn[0] = bidder.getRealX();
bidder_dnn[1] = bidder.getRealY();
auto two_best_items = kdtree_->findK(bidder_dnn, 2);
size_t best_normal_item_idx { two_best_items[0].p->id() };
Real best_normal_item_value { two_best_items[0].d };
// if there is only one off-diagonal point in the second diagram,
// kd-tree will not return the second candidate.
// Set its value to inf, so it will always lose to the value of the projection
Real second_best_normal_item_value { two_best_items.size() == 1 ? std::numeric_limits<Real>::max() : two_best_items[1].d };
if ( proj_item_value < best_normal_item_value) {
best_item_idx = proj_item_idx;
best_item_value = proj_item_value;
second_best_item_value = best_normal_item_value;
} else if (proj_item_value < second_best_normal_item_value) {
best_item_idx = best_normal_item_idx;
best_item_value = best_normal_item_value;
second_best_item_value = proj_item_value;
} else {
best_item_idx = best_normal_item_idx;
best_item_value = best_normal_item_value;
second_best_item_value = second_best_normal_item_value;
}
}
IdxValPair<Real> result;
assert( second_best_item_value >= best_item_value );
result.first = best_item_idx;
result.second = ( second_best_item_value - best_item_value ) + this->prices[best_item_idx] + this->epsilon;
#ifdef DEBUG_KDTREE_RESTR_ORACLE
auto db = get_optimal_bid_debug(bidder_idx);
assert(fabs(db.best_item_value - best_item_value) < 0.000001);
assert(fabs(db.second_best_item_value - second_best_item_value) < 0.000001);
//std::cout << "bid OK" << std::endl;
#endif
return result;
}
/*
a_{ij} = d_{ij}
value_{ij} = a_{ij} + price_j
*/
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::recompute_second_best_diag()
{
if (top_diag_indices_.size() > 1) {
second_best_diagonal_item_value_ = best_diagonal_item_value_;
second_best_diagonal_item_idx_ = top_diag_indices_[0];
} else {
if (diag_items_heap_.size() == 1) {
second_best_diagonal_item_value_ = std::numeric_limits<Real>::max();
second_best_diagonal_item_idx_ = k_invalid_index;
} else {
auto diag_iter = diag_items_heap_.ordered_begin();
++diag_iter;
second_best_diagonal_item_value_ = diag_iter->second;
second_best_diagonal_item_idx_ = diag_iter->first;
}
}
}
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::set_price(IdxType item_idx,
Real new_price,
const bool update_diag)
{
assert(this->prices.size() == this->items.size());
assert( 0 < diag_heap_handles_.size() and diag_heap_handles_.size() <= this->items.size());
// adjust_prices decreases prices,
// also this variable must be true in reverse phases of FR-auction
bool item_goes_down = new_price > this->prices[item_idx];
this->prices[item_idx] = new_price;
if ( this->items[item_idx].is_normal() ) {
assert(0 <= item_idx and item_idx < static_cast<IdxType>(kdtree_items_.size()));
assert(kdtree_items_[item_idx] < dnn_point_handles_.size());
kdtree_->change_weight( dnn_point_handles_[kdtree_items_[item_idx]], new_price);
} else {
assert(diag_heap_handles_.size() > heap_handles_indices_.at(item_idx));
if (item_goes_down) {
diag_items_heap_.decrease(diag_heap_handles_[heap_handles_indices_[item_idx]], std::make_pair(item_idx, new_price));
} else {
diag_items_heap_.increase(diag_heap_handles_[heap_handles_indices_[item_idx]], std::make_pair(item_idx, new_price));
}
if (update_diag) {
// Update top_diag_indices_ only if necessary:
// normal bidders take their projections, which might not be on top
// also, set_price is called by adjust_prices, and we may have already
// removed the item from top_diag
if (is_in_top_diag_indices(item_idx)) {
remove_top_diag_index(item_idx);
}
if (item_idx == (IdxType)second_best_diagonal_item_idx_) {
recompute_second_best_diag();
}
}
}
}
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::set_prices(const std::vector<Real_>& new_prices)
{
if (new_prices.size() != this->items.size())
throw std::runtime_error("new_prices size mismatch");
for(IdxType item_idx = 0; item_idx < static_cast<IdxType>(this->num_items_); ++item_idx)
set_price(item_idx, new_prices[item_idx]);
}
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::adjust_prices(Real delta)
{
if (delta == 0.0)
return;
for(auto& p : this->prices) {
p -= delta;
}
kdtree_->adjust_weights(delta);
bool price_goes_up = delta < 0;
for(size_t item_idx = 0; item_idx < this->items.size(); ++item_idx) {
if (this->items[item_idx].is_diagonal()) {
auto new_price = this->prices[item_idx];
if (price_goes_up) {
diag_items_heap_.decrease(diag_heap_handles_[heap_handles_indices_[item_idx]], std::make_pair(item_idx, new_price));
} else {
diag_items_heap_.increase(diag_heap_handles_[heap_handles_indices_[item_idx]], std::make_pair(item_idx, new_price));
}
}
}
best_diagonal_item_value_ -= delta;
second_best_diagonal_item_value_ -= delta;
}
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::adjust_prices()
{
auto pr_begin = this->prices.begin();
auto pr_end = this->prices.end();
Real min_price = *(std::min_element(pr_begin, pr_end));
adjust_prices(min_price);
}
template<class Real_, class PointContainer_>
size_t AuctionOracleKDTreeRestricted<Real_, PointContainer_>::get_heap_top_size() const
{
return top_diag_indices_.size();
}
template<class Real_, class PointContainer_>
std::pair<Real_, Real_> AuctionOracleKDTreeRestricted<Real_, PointContainer_>::get_minmax_price() const
{
auto r = std::minmax_element(this->prices.begin(), this->prices.end());
return std::make_pair(*r.first, *r.second);
}
template<class Real_, class PointContainer_>
AuctionOracleKDTreeRestricted<Real_, PointContainer_>::~AuctionOracleKDTreeRestricted()
{
delete kdtree_;
}
template<class Real_, class PointContainer_>
void AuctionOracleKDTreeRestricted<Real_, PointContainer_>::sanity_check()
{
#ifdef DEBUG_KDTREE_RESTR_ORACLE
if (best_diagonal_items_computed_) {
std::vector<Real> diag_items_price_vec;
diag_items_price_vec.reserve(this->items.size());
for(size_t item_idx = 0; item_idx < this->items.size(); ++item_idx) {
if (this->items.at(item_idx).is_diagonal()) {
diag_items_price_vec.push_back(this->prices.at(item_idx));
} else {
diag_items_price_vec.push_back(std::numeric_limits<Real>::max());
}
}
auto best_iter = std::min_element(diag_items_price_vec.begin(), diag_items_price_vec.end());
assert(best_iter != diag_items_price_vec.end());
Real true_best_diag_value = *best_iter;
size_t true_best_diag_idx = best_iter - diag_items_price_vec.begin();
assert(true_best_diag_value != std::numeric_limits<Real>::max());
Real true_second_best_diag_value = std::numeric_limits<Real>::max();
size_t true_second_best_diag_idx = k_invalid_index;
for(size_t item_idx = 0; item_idx < diag_items_price_vec.size(); ++item_idx) {
if (this->items.at(item_idx).is_normal()) {
assert(top_diag_lookup_.at(item_idx) == k_invalid_index);
continue;
}
auto i_iter = std::find(top_diag_indices_.begin(), top_diag_indices_.end(), item_idx);
if (diag_items_price_vec.at(item_idx) == true_best_diag_value) {
assert(i_iter != top_diag_indices_.end());
assert(top_diag_lookup_.at(item_idx) == i_iter - top_diag_indices_.begin());
} else {
assert(top_diag_lookup_.at(item_idx) == k_invalid_index);
assert(i_iter == top_diag_indices_.end());
}
if (item_idx == true_best_diag_idx) {
continue;
}
if (diag_items_price_vec.at(item_idx) < true_second_best_diag_value) {
true_second_best_diag_value = diag_items_price_vec.at(item_idx);
true_second_best_diag_idx = item_idx;
}
}
assert(true_best_diag_value == best_diagonal_item_value_);
assert(true_second_best_diag_idx != k_invalid_index);
assert(true_second_best_diag_value == second_best_diagonal_item_value_);
}
#endif
}
} // ws
} // hera
#endif
|
#pragma once
#include "Pipeline.h"
#include "PreDefine.h"
#include "mathlib.h"
#include <vector>
#include "effect.h"
#include "GbufferPipeline.h"
#include "ShowTexturePipeline.h"
using namespace HW;
class SSAOEffect :public PipelineEffect{
public:
virtual void Init();
virtual void Render();
void createSample();
void createNoise();
void setSampleNum(int num);
float uniform_1d_sample();
void stratified_1d_samples(int n, std::vector<float> &samples);
void stratified_2d_samples(int nx, int ny, vector<Vector2> &samples);
float radicalInverse_VdC(unsigned bits);
Vector2 hammersley2d(unsigned i, unsigned N);
Vector3 sample_hemisphere_uniform(Vector2 u2d);
int num_samples_ssao = 32;
vector<Vector3> samples_ssao;
//param
float radius=0.1;
//input
Texture *depth, *normal;
bool isRendertoMainWindow = true;
//output
Texture* output_ao;
RenderTarget* output_rt = NULL;
private:
Texture* noise_tex;
RenderTarget *mainwindow;
RenderSystem* mRenderSystem;
};
class SSAOEffect2 :public PipelineEffect {
public:
virtual void Init();
virtual void Render();
void createSample();
void createNoise();
void setSampleNum(int num);
int num_samples_ssao = 32;
vector<Vector3> samples_ssao;
bool halfResolution = false;
int w, h;
//param
float radius = 0.1;
//input
Texture *depth, *normal;
bool isRendertoMainWindow = true;
float Near = 0.1;
float Far = 10;
//output
Texture* output_ao,*raw_ao;
RenderTarget* output_rt = NULL;
private:
Texture* noise_tex;
RenderTarget *mainwindow,*rt_raw_ao;
RenderSystem* mRenderSystem;
as_Pass* ssao_pass,*blur_pass;
};
class SSAOPipeline :public Pipeline{
public:
virtual void Init();
virtual void Render();
GBufferEffect effect_gbuf;
SSAOEffect effect_ao;
ShowTextureEffect effect_show_tex;
};
|
#pragma once
#include "formatter.hpp"
namespace elog
{
class PatternFormatter: public Formatter
{
public:
PatternFormatter(const char* pattern = "%+", bool colored = false);
virtual ~PatternFormatter();
std::string format(const Record& record) override;
private:
std::string pattern_;
bool color_;
bool colored_;
const char* abbreviatedWeekdayName(const struct tm& t);
const char* fullWeekdayName(const struct tm& t);
const char* abbreviatedMounthName(const struct tm& t);
const char* fullMonthName(const struct tm& t);
std::string percentString(char c, const Record& record);
};
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef SYSTEM_INPUT_DESKTOP_H
#define SYSTEM_INPUT_DESKTOP_H
#include "modules/hardcore/keys/opkeys.h"
#include "modules/scope/src/scope_service.h"
#include "adjunct/desktop_scope/src/generated/g_scope_system_input_interface.h"
class SystemInputPI;
class OpScopeSystemInput
: public OpScopeSystemInput_SI
{
public:
OpScopeSystemInput();
virtual ~OpScopeSystemInput();
// OpScopeService
virtual OP_STATUS OnServiceEnabled();
// Request/Response functions
OP_STATUS DoClick(const MouseInfo &in);
OP_STATUS DoKeyPress(const KeyPressInfo &in);
OP_STATUS DoKeyUp(const KeyPressInfo &in);
OP_STATUS DoKeyDown(const KeyPressInfo &in);
OP_STATUS DoMouseDown(const MouseInfo &in);
OP_STATUS DoMouseUp(const MouseInfo &in);
OP_STATUS DoMouseMove(const MouseInfo &in);
private:
SystemInputPI *m_system_input_pi;
// Convert from SystemInfo message input enums to Opera enums
MouseButton GetOperaButton(OpScopeSystemInput_SI::MouseInfo::MouseButton button);
ShiftKeyState GetOperaModifier(UINT32 modifier);
};
#endif // SYSTEM_INPUT_DESKTOP_H
|
#include "Door.h"
Door::Door(Connection* c1, Connection* c2)
{
img = QImage(GlobalStats::GetDoorIcon()).mirrored();
this->setPixmap(QPixmap::fromImage(img));
connections[0] = c1;
connections[1] = c2;
c1->addWallItem(this);
c2->addWallItem(this);
vertMirrored = false;
updatePositions();
}
double Door::calculateRotation()
{
return QLineF(connections[0]->getPoint(), connections[1]->getPoint()).angle();
}
void Door::updatePositions()
{
if(vertMirrored)
{
this->setTransformOriginPoint(0, -GlobalStats::GetConnRadius() / 2.0);
this->setRotation(-abs(calculateRotation()));
this->setScale(QLineF(connections[0]->getPoint(), connections[1]->getPoint()).length() / (1.0 * this->pixmap().width()));
double dx = sin(qDegreesToRadians(calculateRotation())) * (double)QLineF(connections[0]->getPoint(), connections[1]->getPoint()).length();
double dy = cos(qDegreesToRadians(calculateRotation())) * (double)QLineF(connections[0]->getPoint(), connections[1]->getPoint()).length();
this->setX(connections[0]->getPoint().x()-dx);
this->setY(connections[0]->getPoint().y()-dy + GlobalStats::GetConnRadius() / 2.0);
}
else
{
this->setX(connections[0]->getPoint().x());
this->setY(connections[0]->getPoint().y());
this->setTransformOriginPoint(0, -GlobalStats::GetConnRadius() / 2.0);
this->setRotation(-abs(calculateRotation()));
this->setScale(QLineF(connections[0]->getPoint(), connections[1]->getPoint()).length() / (1.0 * this->pixmap().width()));
}
connections[0]->show();
connections[1]->show();
this->update();
}
Connection** Door::getConnections()
{
return connections;
}
void Door::deatach()
{
try
{
connections[0]->removeWallItem(this);
}
catch (...)
{
cout << "Error deataching door";
}
try
{
connections[1]->removeWallItem(this);
}
catch(...)
{
cout << "Error deataching door";
}
}
void Door::flipDoorVertically()
{
this->setPixmap(pixmap().transformed(QTransform().scale(1, -1)));
vertMirrored ? vertMirrored = false : vertMirrored = true;
updatePositions();
}
void Door::flipDoorHorizontally()
{
this->setPixmap(pixmap().transformed(QTransform().scale(-1, 1)));
updatePositions();
}
void Door::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
{
if (event->button() != Qt::LeftButton)
{
event->ignore();
return;
}
event->accept();
if(GlobalStats::GetTogglePropertyStatus())
{
GlobalStats::ToggleOffPropertyMenu();
}else
{
GlobalStats::ToggleOnPropertyMenu(new DoorProperty(this));
}
}
Door::~Door()
{
deatach();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.