text
stringlengths 8
6.88M
|
|---|
#ifndef module_h
#define module_h
#include <sys/types.h>
#include <assert.h>
#include <cstddef>
#include <iostream>
#define SOCKET_TCP_BUFFER 1024 * 256
#define SOCKET_ERROR -1
#define SOCKET_CLOSE 0
namespace KernelEngine {
/**
* 网络引擎 接口定义
*/
class ITCPNetworkEngine
{
public:
virtual int getCurrentPort() = 0;
public:
// 设置参数
virtual bool setServiceParameter(int nServicePort, size_t nMaxConnect, const std::string &serviceip, const std::string &forwardIp, int nForwardPort) = 0;
public:
// 发送数据
virtual bool sendData(int nSocketID, const void *pData, size_t nDataSize) = 0;
// 开始服务
virtual bool startServices() = 0;
// 结束服务
virtual bool closeServices() = 0;
public:
// 关闭套接字
virtual bool CloseSocket(int nSocketID) = 0;
};
};
#endif /* module_h */
|
#ifndef _D3D_H_
#define _D3D_H_
#include <wrl\client.h>
#include <memory>
#include <Windows.h>
#include <stdio.h>
#include <d3d11.h>
#include <CommonStates.h>
#pragma once
class D3D
{
public:
D3D();
~D3D();
bool Initialize(HWND hwnd, int outputWidth, int outputHeight);
bool Present();
bool Clear();
void updateScreenSize(HWND hwnd, int outputWidth, int outputHeight);
void Reset();
void TurnZBufferOn();
void TurnZBufferOff();
ID3D11Device* getDevice() const { return m_d3dDevice.Get(); };
ID3D11DeviceContext* getContext() const { return m_d3dContext.Get(); };
IDXGISwapChain1* getSwapChain() const { return m_swapChain.Get(); };
ID3D11DepthStencilView* GetDepthStencilView() const { return m_depthStencilView.Get(); };
void SetBackBufferRenderTarget();
int GetOutputWidth() const { return m_outputWidth; };
int GetOutputHeight() const { return m_outputHeight; };
private:
void CreateDevice();
bool CreateContext(HWND hwnd, int outputWidth, int outputHeight);
void CreateDepthStencilBuffer(ID3D11Device* device);
void CreateDepthStencilState(ID3D11Device* device);
void CreateDepthStencilView(ID3D11Device* device);
void CreateRasterState(ID3D11Device* device);
void SetViewport();
private:
int m_outputWidth;
int m_outputHeight;
D3D_FEATURE_LEVEL m_featureLevel;
Microsoft::WRL::ComPtr<ID3D11Device> m_d3dDevice;
Microsoft::WRL::ComPtr<ID3D11DeviceContext> m_d3dContext;
Microsoft::WRL::ComPtr<IDXGISwapChain1> m_swapChain;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_renderTargetView;
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_depthStencilBuffer;
Microsoft::WRL::ComPtr<ID3D11DepthStencilState> m_depthStencilState;
Microsoft::WRL::ComPtr<ID3D11DepthStencilState> m_depthDisabledStencilState;
Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_depthStencilView;
Microsoft::WRL::ComPtr<ID3D11RasterizerState> m_rasterState;
};
#endif
|
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[10] = "aaaa";
char b[5] = "aaaa";
strcat(a, b);
puts(a);
return 0;
}
|
#include "BTTask_UpdateTrackingPosition.h"
#include "Actor/Controller/EnemyController/EnemyController.h"
using namespace EBTNodeResult;
EBTNodeResult::Type UBTTask_UpdateTrackingPosition::ExecuteTask(
UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
Super::ExecuteTask(OwnerComp, NodeMemory);
AEnemyController* enemyController = Cast<AEnemyController>(OwnerComp.GetAIOwner());
if (enemyController->UpdateTrackingPosition())
return Succeeded;
else return Failed;
}
|
#include "ventaviewer.h"
#include "clienteviewer.h"
#include "tipoviewer.h"
#include "articuloviewer.h"
#include "articulodao.h"
VentaViewer::VentaViewer()
{
//ctor
}
VentaViewer::~VentaViewer()
{
//dtor
}
int VentaViewer::menu()
{
int opcion;
cout << endl << endl << "MENU" << endl << endl;
cout << "1. Vender" << endl;
cout << "2. Mostrar Venta" << endl;
cout << endl << "3. Salir" << endl;
cout << endl << "Elija OPCION: ";
cin >> opcion;
return opcion;
}
void VentaViewer::leerFacturayCliente(Venta* venta, ClienteQueue* queue)
{
int factura;
int cliente;
cout << endl << endl << "Nueva VENTA" << endl << endl;
cout << "Ingrese Número de FACTURA: ";
cin >> factura;
venta->setVenID(factura);
cout << "Elija CLIENTE:" << endl;
(new ClienteViewer())->listar(queue);
cout << "Ingrese Número de CLIENTE: ";
cin >> cliente;
venta->setCliID(cliente);
}
void VentaViewer::leerTipoPago(Venta* venta, TipoQueue* queue)
{
int tipo;
cout << "Elija TIPO de PAGO:" << endl;
(new TipoViewer())->listar(queue);
cout << "Ingrese Número de TIPO de PAGO: ";
cin >> tipo;
venta->setTipID(tipo);
}
VentaDetalle* VentaViewer::leerArticuloyCantidad(int venID, ArticuloQueue* queue)
{
int art;
cout << "Elija ARTICULO:" << endl;
(new ArticuloViewer())->listar(queue);
cout << "Ingrese Codigo de ARTICULO (0 para terminar): ";
cin >> art;
if (art == 0)
return NULL;
int cantidad;
cout << "Ingrese Cantidad: ";
cin >> cantidad;
VentaDetalle* vd = new VentaDetalle();
vd->setVenID(venID);
vd->setArtID(art);
vd->setCantidad(cantidad);
return vd;
}
int VentaViewer::leerFactura()
{
int factura;
cout << endl << endl << "Mostrar FACTURA" << endl << endl;
cout << "Ingrese Número de FACTURA: ";
cin >> factura;
return factura;
}
void VentaViewer::mostrarFactura(Venta* venta, Cliente* cliente, Tipo* tipo)
{
cout << "Factura: " << venta->getVenID() << endl;
cout << "Cliente: " << cliente->getNombre() << endl;
cout << "Tipo de Pago: " << tipo->getNombre() << endl;
cout << "Total Venta: " << venta->getImporte() << endl;
}
void VentaViewer::mostrarDetalle(VentaDetalleQueue* queue)
{
VentaDetalle* vd;
Articulo* ar;
cout << endl << "Detalle FACTURA" << endl;
while ((vd = queue->retrieve()) != NULL)
{
ar = (new ArticuloDAO())->find(vd->getArtID());
cout << "Articulo: " << ar->getNombre() << " Cantidad: " << vd->getCantidad() << " Precio: " << ar->getPrecio() << endl;
}
}
|
#include<iostream>
#define FOR0(i,n) for(i=0;i<n;i++)
#define FOR(i,j,n) for(i=j;i<n;i++)
#define FORD(i,j) for(i=j;i>=0;i--)
#define MAX(a,b) (a)>(b)?(a):(b)
using namespace std;
int main()
{
int Mi[2002],Md[2002],A[2002],n,testcases,curri,currd;
int i,j,count;
cin>>testcases;
while(testcases--)
{
cin>>n;
FOR0(i,n)
cin>>A[i];
//LIS & LDS
FORD(i,n-1)
{
Mi[i]=1;
Md[i]=1;
curri=0;currd=0;
FOR(j,i+1,n)
{
if(A[j]>A[i])
if(Mi[j]>curri){curri=Mi[j];Mi[i]=Mi[j]+1;}
if(A[j]<A[i])
if(Md[j]>currd){currd=Md[j];Md[i]=Md[j]+1;}
}
}
int max=0;
FOR0(i,n)
{
max=MAX(max,Md[i]+Mi[i]-1);
}
printf("%d\n",max);
}
}
|
/* Copyright 2016 tgil All Rights Reserved */
#include "ui/Event.hpp"
using namespace ui;
Event::Event() {
// TODO Auto-generated constructor stub
m_type = NONE;
m_objects.object = 0;
}
|
#pragma once
class Maths
{
public:
struct xyz { float x, y, z; };
struct Plane
{
xyz normal; /*the normal to the plane*/
float d; /* the 'd' constant in the equation for this plane*/
};
float Dot(xyz* v1, xyz* v2);
xyz Cross(xyz* v1, xyz* v2);
xyz Normal(xyz* v1, xyz* v2, xyz* v3);
Plane TrianglePlane(xyz* v1, xyz* v2, xyz* v3);
float PointPlane(Plane plane, xyz v);
};
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
// parameters are commented
// string read_month_name(string); // month name
// int print_month(string, string, int, int); // first day, last day, no of days, month name
// void print_heading(int); // year
// int get_starting_day(); // start date
// int get_year(); // year
// int read_num_days(); // num day
ifstream myfile;
int get_year() {
// prompting user to enter year
int Fyear;
cout << "ENTER YEAR -- " << endl;
cin >> Fyear;
return Fyear;
}
int get_starting_day() {
int start_date;
// prompt user to enter start day
cout << "ENTER START DATE <0 = Sun, 1 = Mon, 2 = Tues, 3 = Wed, 4 = Thur, 5 = Fri, 6 = Sat>: ";
cin >> start_date;
return start_date;
}
void print_heading(int Fyear) {
cout << setw(19) << " YEAR " << Fyear << endl;
cout << " " << endl;
}
string read_month_name() {
string month_name;
myfile >> month_name;
return month_name;
}
int read_num_days() {
int num_day;
myfile >> num_day;
return num_day;
}
int print_month(string month_name, int num_day, int start_date) {
cout << setw(20) << month_name;
cout << "\nSun: Mon: Tue: Wed: Thu: Fri: Sat: \n";
string space = "";
if (start_date > 0) {
if (start_date == 1) {
space = " ";
}
if (start_date == 2) {
space = " ";
}
if (start_date == 3) {
space = " ";
}
if (start_date == 4) {
space = " ";
}
if (start_date == 5) {
space = " ";
}
if (start_date == 6) {
space = " ";
}
cout << space;
}
for (int x = 1; x <= num_day; ++x) {
if (x < 10) {
cout << " " << x << " ";
}
if (x > 9) {
cout << " " << x << " ";
}
if (start_date == 6) {
start_date = -1;
cout << "\n";
}
++start_date;
}
cout << "\n" << endl;
return start_date;
}
int main() {
myfile.open("6infile.txt"); // open infile
int input_year = get_year();
int start_date = get_starting_day();
print_heading(input_year);
for (int x = 1; x < 13; x++) {
string month_name = read_month_name();
int num_day = read_num_days();
start_date = print_month(month_name, num_day, start_date);
}
myfile.close();
return 0;
}
// Downloads> cmd /c "lab6-2.cpp"
// ENTER YEAR --
// 2017
// ENTER START DATE <0 = Sun, 1 = Mon, 2 = Tues, 3 = Wednesday, 4 = Thur, 5 = Fri, 6 = Sat>: 0
// YEAR 2017
// JANUARY
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1 2 3 4 5 6 7
// 8 9 10 11 12 13 14
// 15 16 17 18 19 20 21
// 22 23 24 25 26 27 28
// 29 30 31
// FEBRUARY
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1 2 3 4
// 5 6 7 8 9 10 11
// 12 13 14 15 16 17 18
// 19 20 21 22 23 24 25
// 26 27 28
// MARCH
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1 2 3 4
// 5 6 7 8 9 10 11
// 12 13 14 15 16 17 18
// 19 20 21 22 23 24 25
// 26 27 28 29 30 31
// APRIL
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1
// 2 3 4 5 6 7 8
// 9 10 11 12 13 14 15
// 16 17 18 19 20 21 22
// 23 24 25 26 27 28 29
// 30
// MAY
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1 2 3 4 5 6
// 7 8 9 10 11 12 13
// 14 15 16 17 18 19 20
// 21 22 23 24 25 26 27
// 28 29 30 31
// JUNE
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1 2 3
// 4 5 6 7 8 9 10
// 11 12 13 14 15 16 17
// 18 19 20 21 22 23 24
// 25 26 27 28 29 30
// JULY
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1
// 2 3 4 5 6 7 8
// 9 10 11 12 13 14 15
// 16 17 18 19 20 21 22
// 23 24 25 26 27 28 29
// 30 31
// AUGUST
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1 2 3 4 5
// 6 7 8 9 10 11 12
// 13 14 15 16 17 18 19
// 20 21 22 23 24 25 26
// 27 28 29 30 31
// SEPTEMBER
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1 2
// 3 4 5 6 7 8 9
// 10 11 12 13 14 15 16
// 17 18 19 20 21 22 23
// 24 25 26 27 28 29 30
// OCTOBER
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1 2 3 4 5 6 7
// 8 9 10 11 12 13 14
// 15 16 17 18 19 20 21
// 22 23 24 25 26 27 28
// 29 30 31
// NOVEMBER
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1 2 3 4
// 5 6 7 8 9 10 11
// 12 13 14 15 16 17 18
// 19 20 21 22 23 24 25
// 26 27 28 29 30
// DECEMBER
// Sun: Mon: Tue: Wed: Thu: Fri: Sat:
// 1 2
// 3 4 5 6 7 8 9
// 10 11 12 13 14 15 16
// 17 18 19 20 21 22 23
// 24 25 26 27 28 29 30
// 31
|
/*
* Copyright [2017] <Bonn-Rhein-Sieg University>
*
* Author: Torsten Jandt
*
*/
#pragma once
#include <mir_planner_executor/actions/place/base_place_action.h>
#include <actionlib/client/simple_action_client.h>
#include <mir_yb_action_msgs/PlaceObjectAction.h>
class PlaceAction : public BasePlaceAction {
private:
actionlib::SimpleActionClient<mir_yb_action_msgs::PlaceObjectAction> client_;
public:
PlaceAction();
protected:
virtual bool run(std::string& robot, std::string& location, std::string& object);
};
|
//--------------------------------------------------------
// CS 215 - Fall 2018
// Project 3: The New Link Blue
//--------------------------------------------------------
#include <iostream>
#include "userint.h"
int main() {
// create the app and start it!
userint x;
x.go();
system("pause");
return 0;
}
|
// DEMO : https://www.instagram.com/p/CPGtv9Khelz/
// OLED
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 0 // GPIO0
Adafruit_SSD1306 display(OLED_RESET);
#define OLED_w 128
#define OLED_h 64
int cmode = 0;
int counter = 0;
float delta = 0;
float delta_t = 0.1;
void setup()
{
Serial.begin(9600);
Serial.println();
pinMode(D5, INPUT);
pinMode(D6, INPUT);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3C (for the 64x48)
display.display();
delay(2000);
display.clearDisplay();
}
void loop()
{
display.clearDisplay();
if (digitalRead(D5)==1) {
cmode++;
delta = 0;
counter = 0;
}if (digitalRead(D6)==1) {
cmode--;
delta = 0;
counter = 0;
}
delta += 0.005;
for (float t = 0; t < 50; t += delta_t) {
display.drawLine(function1(t), function2(t),function1(t+delta_t), function2(t+delta_t),WHITE);
}
display.display();
}
float function1(float t) {
return OLED_w / 2 + OLED_h / 2 * sin(0.01*counter*t+t) * cos(delta * t);
}
float function2(float t) {
return OLED_h / 2 + OLED_h / 2 * sin(0.04 * cmode * t);
}
|
#include "button.h"
RRG::Button::Button() {
}
RRG::Button::~Button() {
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) Opera Software ASA 1999 - 2006
*
* Data types allocated on the garbage collected heap.
*
* @author Lars T Hansen
*/
#ifndef ES_BOXED_H
#define ES_BOXED_H
/* The data allocated on the GC heap are POD-structs in the sense of
the C++ standard; see excerpts from the standard below. They have
no non-static methods at all. The POD restriction makes their layout
relatively transparent; in particular it ensures that the first
element of each struct is at offset 0 in the struct, always, and that
the address of a union of the structs is the address of each struct.
These conditions are important for the garbage collector. During the
sweep phase of GC, the collector scans the heap from one end to the
other, inspecting the header of each object. It needs to find that
header at the start of the object.
The consequence of using POD-structs is that we cannot use standard
C++ subclassing (because there are no guarantees in the standard about
how a compound class will be laid out, not even for a single inheritance
hierarchy without virtual methods). Instead, we emulate subclassing
by giving groups of types the same initial prefix and using explicit
casts among these types when we need to cast to a "base class".
We also cannot use normal constructors; instead, Initialize() functions
are defined that are called as part of the object construction.
All of this is slightly messy, but not very bad.
The hierarchy of types:
ES_Boxed
ES_Boxed_Array
ES_Compiled_Code
ES_Free
ES_Latent_Arguments
ES_Object
ES_Array
ES_Foreign_Object
ES_Foreign_Function
ES_Global_Object
ES_Function
ES_RegExp
ES_Property_Object
ES_Rib
ES_Lexical_Rib
ES_Reified_Rib
//ES_Double [ES_DOUBLES_ON_THE_HEAP - obsolete; see comment in es_double.h]
JString
JStringStorage
Although the term "POD-struct" seems to imply that "struct" has to be
used, this is not so -- so I use "class" everywhere, with all members
public, to reduce problems of backward compatibility to systems where
ES_Object is declared as a class.
C++ standard section 9
4 A POD-struct is an aggregate class that has no non-static data members of
type pointer to member, non-POD-struct, non-POD-union (or array of such
types) or reference, and has no user-defined copy assignment operator and
no user-defined destructor. Similarly, a POD-union is an aggregate union
that has no non-static data members of type pointer to member, non-POD-struct,
non-POD-union (or array of such types) or reference, and has no user-defined
copy assignment operator and no user-defined destructor. A POD class is a
class that is either a POD-struct or a POD-union.
C++ standard section 9.2
14 Two POD-struct (clause 9) types are layout-compatible
if they have the same number of members, and corresponding
members (in order) have layout-compatible types (3.9).
15 Two POD-union (clause 9) types are layout-compatible
if they have the same number of members, and corresponding
members (in any order) have layout-compatible types (3.9).
16 If a POD-union contains two or more POD-structs
that share a common initial sequence, and if the POD-union
object currently contains one of these POD-structs,
it is permitted to inspect the common initial part
of any of them. Two POD-structs share a common initial
sequence if corresponding members have layout-compatible
types (and, for bitfields, the same widths) for a sequence
of one or more initial members.
17 A pointer to a POD-struct object, suitably converted using a
reinterpret_cast, points to its initial member (or if that
member is a bitfield, then to the unit in which it resides)
and vice versa. [Note: There might therefore be unnamed
padding within a POD-struct object, but not at its beginning,
as necessary to achieve appropriate alignment. ]
*/
#ifdef ES_HEAP_DEBUGGER
extern unsigned *g_ecmaLiveObjects;
#define HEAP_DEBUG_LIVENESS_FOR(heap) g_ecmaLiveObjects = (heap)->live_objects
#else
#define HEAP_DEBUG_LIVENESS_FOR(heap) (void)0
#endif // ES_HEAP_DEBUGGER
class ES_Boxed;
inline unsigned int ObjectSize(const ES_Boxed *b);
class ES_Boxed
{
public:
ES_Header hdr;
#if defined(ES_MOVABLE_OBJECTS) && defined(_DEBUG)
unsigned int trace_number;
#endif // defined(ES_MOVABLE_OBJECTS) && defined(_DEBUG)
inline unsigned Bits() const
{
return hdr.header & ES_Header::MASK_BITS;
}
inline unsigned Size() const
{
return hdr.header >> ES_Header::SIZE_SHIFT;
}
inline void SetSize(unsigned size)
{
OP_ASSERT(size <= UINT16_MAX);
hdr.header = (hdr.header & ES_Header::MASK_BITS) | (size << ES_Header::SIZE_SHIFT);
}
inline void SetHeader(unsigned size, unsigned bits)
{
OP_ASSERT(bits <= UINT16_MAX);
OP_ASSERT(size <= UINT16_MAX);
hdr.header = (size << ES_Header::SIZE_SHIFT) | bits;
}
inline void ClearHeader()
{
hdr.header = 0;
}
inline void
InitHeader(unsigned size)
{
#ifdef _DEBUG
op_memset(this, 0xfe, size);
#endif // _DEBUG
hdr.header = (size < UINT16_MAX ? size : UINT16_MAX) << ES_Header::SIZE_SHIFT;
#ifdef _DEBUG
InitGCTag(GCTAG_UNINITIALIZED);
#endif // _DEBUG
}
inline GC_Tag
GCTag() const
{
return (GC_Tag) (hdr.header & ES_Header::MASK_GCTAG);
}
inline void
InitGCTag(GC_Tag n)
{
ChangeGCTag(n);
}
inline void InitGCTag(GC_Tag n, BOOL need_destroy);
inline void
ChangeGCTag(GC_Tag n)
{
#ifdef ES_HEAP_DEBUGGER
if (GCTag() != GCTAG_free && n != GCTAG_free)
--g_ecmaLiveObjects[GCTag()];
#endif // ES_HEAP_DEBUGGER
hdr.header = (hdr.header & ~ES_Header::MASK_GCTAG) | n;
#ifdef ES_HEAP_DEBUGGER
if (n != GCTAG_free)
++g_ecmaLiveObjects[n];
#endif // ES_HEAP_DEBUGGER
}
inline void SetNeedDestroy();
/** @return non-zero if this box is special property */
inline BOOL
IsSpecial()
{
unsigned gctag = GCTag();
return gctag >= GCTAG_FIRST_SPECIAL && gctag <= GCTAG_LAST_SPECIAL;
}
inline BOOL
IsClass()
{
unsigned gctag = GCTag();
return gctag >= GCTAG_FIRST_CLASS && gctag <= GCTAG_LAST_CLASS;
}
inline BOOL
IsBuiltinString() const
{
return (hdr.header & ES_Header::MASK_IS_BUILTIN_STRING) != 0;
}
inline void
SetBuiltinString()
{
hdr.header |= ES_Header::MASK_IS_BUILTIN_STRING;
}
inline BOOL
IsAllocatedOnLargePage() const
{
return (hdr.header & ES_Header::MASK_ON_LARGE_PAGE) != 0;
}
inline void
SetAllocatedOnLargePage()
{
hdr.header |= ES_Header::MASK_ON_LARGE_PAGE;
}
inline BOOL
IsLargeObject() const
{
return ObjectSize(this) >= LARGE_OBJECT_LIMIT;
}
inline void
SplitAllocation(ES_Boxed *next)
{
OP_ASSERT(ObjectSize(this) != UINT16_MAX);
/* Make sure 'next' is actually included in this allocation. */
OP_ASSERT(reinterpret_cast<char *>(this) + ObjectSize(this) > reinterpret_cast<char *>(next));
/* Make sure 'next' is properly aligned. */
OP_ASSERT(ES_IS_POINTER_PAGE_ALIGNED(next));
OP_ASSERT(ES_IS_SIZE_PAGE_ALIGNED(ObjectSize(this)));
unsigned new_size = reinterpret_cast<char *>(next) - reinterpret_cast<char *>(this);
OP_ASSERT((Size() - new_size) < UINT16_MAX);
next->SetHeader(Size() - new_size, 0);
#if defined(ES_MOVABLE_OBJECTS) && defined(_DEBUG)
next->trace_number = trace_number;
#endif // defined(ES_MOVABLE_OBJECTS) && defined(_DEBUG)
OP_ASSERT(new_size < UINT16_MAX);
SetSize(new_size);
OP_ASSERT(ES_IS_SIZE_PAGE_ALIGNED(ObjectSize(next)));
OP_ASSERT(ES_IS_SIZE_PAGE_ALIGNED(ObjectSize(this)));
}
inline unsigned GetPageOffset();
inline ES_PageHeader *GetPage();
inline const ES_PageHeader *GetPage() const;
};
#if 0
// Hack to kill "dereferencing type-punned pointer will break strict-aliasing
// rules" warning from GCC. Might be better ways.
template<class T> static inline ES_Boxed *&ManglePointerIntoBoxed(T **x)
{
return *reinterpret_cast<ES_Boxed **>(x);
}
template<class T> static inline ES_Boxed *&ManglePointerIntoBoxed(T ***x)
{
return *reinterpret_cast<void **>(x);
}
#define CAST_TO_BOXED_REF(b) ManglePointerIntoBoxed(&b)
#endif // 0
#define CAST_TO_BOXED(b) static_cast<ES_Boxed*>(b)
/* Operations on ES_Boxed */
/** @return size of the object (including the size of the header), in bytes, */
inline unsigned int
ObjectSize(const ES_Boxed *b)
{
unsigned size = b->Size();
return size != UINT16_MAX ? size : b->GetPage()->GetSize();
}
#endif // ES_BOXED_H
|
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Texture.h"
#include "CinderOpenNI.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class SimpleViewerApp : public AppNative {
public:
void prepareSettings(Settings *settings);
void setup();
void mouseDown( MouseEvent event );
void update();
void draw();
void shutdown();
private:
ci::openni::Camera camera;
};
void SimpleViewerApp::prepareSettings(Settings *settings)
{
settings->setWindowSize( 1280, 480 );
settings->setFrameRate( 30 );
}
void SimpleViewerApp::setup()
{
camera.setup( ci::openni::Camera::SENSOR_DEPTH | ci::openni::Camera::SENSOR_COLOR );
}
void SimpleViewerApp::mouseDown( MouseEvent event )
{
}
void SimpleViewerApp::update()
{
camera.update();
}
void SimpleViewerApp::draw()
{
// clear out the window with black
gl::clear( Color( 0, 0, 0 ) );
gl::draw( camera.getDepthTex(), Rectf( 0, 0, 640, 480 ) );
// gl::draw( camera.getRawDepthTex(), Rectf( 0, 0, 640, 480 ) );
// gl::draw( camera.getColorTex(), Rectf( 640, 0, 1280, 480 ) );
}
void SimpleViewerApp::shutdown()
{
console() << "Shutting down" << endl;
camera.close();
camera.shutdown();
}
CINDER_APP_NATIVE( SimpleViewerApp, RendererGl )
|
#include <iostream>
#include <cstdlib>
using namespace std;
// prototype
int* create2DArray(int rows, int columns);
void set(int *arr, int rows, int columns, int desired_row, int desired_column, int val);
int get(int *arr, int rows, int columns, int desired_row, int desired_column);
int main()
{
int rows = 2, columns = 3;
int* ptrToArray = create2DArray(rows, columns);
set(ptrToArray, rows, columns, 2, 1, 4);
cout << get(ptrToArray, rows, columns, 4, 1);
}
int* create2DArray(int rows, int columns)
{
int* ptrToArray;
ptrToArray = new int[rows*columns];
return ptrToArray;
}
void set(int *arr, int rows, int columns, int desired_row, int desired_column, int val)
{
if (desired_row > rows || desired_column > columns)
{
cout << "The indexes you gave are invalid" << endl;
exit(1);
}
int index = (desired_row - 1) * columns + (desired_column - 1);
arr[index] = val;
}
int get(int *arr, int rows, int columns, int desired_row, int desired_column)
{
if (desired_row > rows || desired_column > columns)
{
cout << "The indexes you gave are invalid" << endl;
exit(1);
}
int index = (desired_row - 1) * columns + (desired_column - 1);
return arr[index];
}
|
#pragma once
#include "Score.h"
class PlayersScore {
Score current;
Score score[4][10];
public:
PlayersScore() = default;
~PlayersScore() = default;
void Load();
void Save() const;
void Draw() const;
Score* getScore(int diff);
};
|
int main() {
/// TODO 0.改测例
vector<pair<vector<int>, bool>> test_cases = {
{{0, 1}, false},
{{2, 0, 0}, true},
{{3, 2, 1, 0, 4}, false},
{{2, 3, 1, 1, 4}, true},
};
int passed = 0;
auto solver = Solution();
for (const auto& i : test_cases) {
/// TODO 1. 改tie
vector<int> arr;
bool expected;
tie(arr, expected) = i;
/// TODO 2.改函数调用
auto out = solver.canJump(arr);
if (out != expected) {
printf("in = %s, out = %b, expected = %b", arr, out, expected);
}
else ++passed;
}
printf("total = %d/%d\n", passed, test_cases.size());
return 0;
}
|
/* Um comerciante comprou um produto e quer vendê-lo com lucro de 35% se o valor
da compra for menor que 300,00; caso contrário, o lucro será de 50%.
Entrar com o valor do produto e imprimir o valor da venda. */
#include<stdlib.h>
#include<stdio.h>
main(){
float lucro, produto;
printf("Digite o valor do produto: ");
scanf("%f",&produto);
if ( produto <300 ) {
lucro= produto+ (produto*0.35);
printf("O valor de venda sera: %.1f ",lucro);
}
else if ( produto >=300 ) {
lucro= produto+ (produto*0.50);
printf("O valor de venda sera: %.1f",lucro);
}
}
|
// Created on: 1994-08-25
// Created by: Jacques GOUSSARD
// Copyright (c) 1994-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 _BRepTools_TrsfModification_HeaderFile
#define _BRepTools_TrsfModification_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <gp_Trsf.hxx>
#include <BRepTools_Modification.hxx>
#include <GeomAbs_Shape.hxx>
class TopoDS_Face;
class Geom_Surface;
class TopLoc_Location;
class TopoDS_Edge;
class Geom_Curve;
class TopoDS_Vertex;
class gp_Pnt;
class Geom2d_Curve;
class BRepTools_TrsfModification;
DEFINE_STANDARD_HANDLE(BRepTools_TrsfModification, BRepTools_Modification)
//! Describes a modification that uses a gp_Trsf to
//! change the geometry of a shape. All functions return
//! true and transform the geometry of the shape.
class BRepTools_TrsfModification : public BRepTools_Modification
{
public:
Standard_EXPORT BRepTools_TrsfModification(const gp_Trsf& T);
//! Provides access to the gp_Trsf associated with this
//! modification. The transformation can be changed.
Standard_EXPORT gp_Trsf& Trsf();
//! Sets a flag to indicate the need to copy mesh.
Standard_EXPORT Standard_Boolean& IsCopyMesh();
//! Returns true if the face F has been modified.
//! If the face has been modified:
//! - S is the new geometry of the face,
//! - L is its new location, and
//! - Tol is the new tolerance.
//! RevWires is set to true when the modification
//! reverses the normal of the surface (the wires have to be reversed).
//! RevFace is set to true if the orientation of the
//! modified face changes in the shells which contain it.
//! For this class, RevFace returns true if the gp_Trsf
//! associated with this modification is negative.
Standard_EXPORT Standard_Boolean NewSurface (const TopoDS_Face& F, Handle(Geom_Surface)& S, TopLoc_Location& L, Standard_Real& Tol, Standard_Boolean& RevWires, Standard_Boolean& RevFace) Standard_OVERRIDE;
//! Returns true if the face has been modified according to changed triangulation.
//! If the face has been modified:
//! - T is a new triangulation on the face
Standard_EXPORT Standard_Boolean NewTriangulation(const TopoDS_Face& F, Handle(Poly_Triangulation)& T) Standard_OVERRIDE;
//! Returns true if the edge has been modified according to changed polygon.
//! If the edge has been modified:
//! - P is a new polygon
Standard_EXPORT Standard_Boolean NewPolygon(const TopoDS_Edge& E, Handle(Poly_Polygon3D)& P) Standard_OVERRIDE;
//! Returns true if the edge has been modified according to changed polygon on triangulation.
//! If the edge has been modified:
//! - P is a new polygon on triangulation
Standard_EXPORT Standard_Boolean NewPolygonOnTriangulation(const TopoDS_Edge& E, const TopoDS_Face& F, Handle(Poly_PolygonOnTriangulation)& P) Standard_OVERRIDE;
//! Returns true if the edge E has been modified.
//! If the edge has been modified:
//! - C is the new geometric support of the edge,
//! - L is the new location, and
//! - Tol is the new tolerance.
//! If the edge has not been modified, this function
//! returns false, and the values of C, L and Tol are not significant.
Standard_EXPORT Standard_Boolean NewCurve (const TopoDS_Edge& E, Handle(Geom_Curve)& C, TopLoc_Location& L, Standard_Real& Tol) Standard_OVERRIDE;
//! Returns true if the vertex V has been modified.
//! If the vertex has been modified:
//! - P is the new geometry of the vertex, and
//! - Tol is the new tolerance.
//! If the vertex has not been modified this function
//! returns false, and the values of P and Tol are not significant.
Standard_EXPORT Standard_Boolean NewPoint (const TopoDS_Vertex& V, gp_Pnt& P, Standard_Real& Tol) Standard_OVERRIDE;
//! Returns true if the edge E has a new curve on surface on the face F.
//! If a new curve exists:
//! - C is the new geometric support of the edge,
//! - L is the new location, and
//! - Tol the new tolerance.
//! If no new curve exists, this function returns false, and
//! the values of C, L and Tol are not significant.
Standard_EXPORT Standard_Boolean NewCurve2d (const TopoDS_Edge& E, const TopoDS_Face& F, const TopoDS_Edge& NewE, const TopoDS_Face& NewF, Handle(Geom2d_Curve)& C, Standard_Real& Tol) Standard_OVERRIDE;
//! Returns true if the Vertex V has a new parameter on the edge E.
//! If a new parameter exists:
//! - P is the parameter, and
//! - Tol is the new tolerance.
//! If no new parameter exists, this function returns false,
//! and the values of P and Tol are not significant.
Standard_EXPORT Standard_Boolean NewParameter (const TopoDS_Vertex& V, const TopoDS_Edge& E, Standard_Real& P, Standard_Real& Tol) Standard_OVERRIDE;
//! Returns the continuity of <NewE> between <NewF1>
//! and <NewF2>.
//!
//! <NewE> is the new edge created from <E>. <NewF1>
//! (resp. <NewF2>) is the new face created from <F1>
//! (resp. <F2>).
Standard_EXPORT GeomAbs_Shape Continuity (const TopoDS_Edge& E, const TopoDS_Face& F1, const TopoDS_Face& F2, const TopoDS_Edge& NewE, const TopoDS_Face& NewF1, const TopoDS_Face& NewF2) Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(BRepTools_TrsfModification,BRepTools_Modification)
protected:
private:
gp_Trsf myTrsf;
Standard_Boolean myCopyMesh;
};
#endif // _BRepTools_TrsfModification_HeaderFile
|
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <cwchar>
#include "In.h"
#include "Error.h"
namespace In {
IN getin(wchar_t infile[])
{
IN tempIN;
tempIN.size = 0;
tempIN.lines = 0;
std::ifstream fin;
std::string Buff;
unsigned char textTemp[IN_MAX_LEN_TEXT];
tempIN.ignor = 0;
fin.open(infile);
if (fin.fail())
{
throw ERROR_THROW(110);
}
for (int t = 0;;)
{
getline(fin, Buff);
for (int i = 0; i < Buff.length(); ++i)
{
if (tempIN.code[(unsigned char)Buff[i]] == IN::F)
{
throw ERROR_THROW_IN(111, tempIN.lines, i);
}
else if (tempIN.code[(unsigned char)Buff[i]] == IN::I)
{
tempIN.ignor++;
}
else
{
tempIN.size++;
textTemp[t] = Buff[i];
++t;
}
}
tempIN.lines++;
tempIN.size++;
if (fin.eof())
{
tempIN.lines--;
textTemp[t] = '\0';
break;
}
}
tempIN.text = textTemp;
fin.close();
return tempIN;
}
}
|
#pragma once
#include <QWidget>
#include <QStringList>
#include <QTableWidgetItem>
#include "Entities/Question/Question.h"
#include "Forms/AddPartOfKeyForm/AddPartOfKeyForm.h"
class Scale;
class Key;
namespace Ui {
class ScaleForm;
}
class KeyForm : public QWidget {
Q_OBJECT
public:
explicit KeyForm(Scale *scale,
Questions *questions,
QWidget *parent = 0);
~KeyForm();
signals:
void scaleDeleted(const QString &scaleName);
public slots:
void update();
protected slots:
void onDeleteBtnClicked();
void onKeyDoubleClicked(int row);
protected:
void configureAddForm(AddPartOfKeyForm *addForm);
void configureKeyTable(const QStringList &labels);
void addPartOfKey(const PartOfKey &partOfKey);
virtual void addPartOfKeyOnForm(const PartOfKey &partOfKey) = 0;
void deletePartOfKeyAt(uint index);
QTableWidgetItem *makePoints(const PartOfKey &partOfKey);
Scale *m_scale;
Key *m_key;
Questions *m_questions;
AddPartOfKeyForm *m_addForm;
Ui::ScaleForm *ui;
const char DELETE_BTN = 3;
const char COLUMNS_AMOUNT = 4;
};
|
#include "Unit.hpp"
// Unit class is well implemented, no need to change it
Unit::Unit(SDL_Renderer* rend, SDL_Texture* ast): gRenderer(rend), assets(ast){
}
void Unit::draw(SDL_Rect srcRect, SDL_Rect moverRect){
SDL_RenderCopy(gRenderer, assets, &srcRect, &moverRect);
}
|
//
// LinkedUnsorted.h
//
//
// Created by Luke Winker on 7/20/18.
//
//
#include <stdio.h>
#include "ItemType.h"
struct NodeType
{
ItemType info;
NodeType* next;
};
class LinkedUnsortedType {
public:
LinkedUnsortedType();
~LinkedUnsortedType();
void MakeEmpty();
bool IsFull() const;
int GetLength() const;
ItemType GetItem(ItemType item, bool& found);
void PutItem(ItemType item);
void DeleteItem(ItemType item);
void ResetList();
ItemType GetNextItem();
private:
NodeType* listData;
int length;
NodeType* currentPos;
};
|
#ifndef PILA_H
#define PILA_H
#include "Nodo.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
class Pila
{
private:
Nodo* tope;
public:
Pila(){
tope = NULL;
}
void push(int v){
tope = new Nodo(v,tope);
}
int cima(void){
return tope->dameTuValor();
}
int laPilaEstaVacia(void){
return tope == NULL;
}
int pop(void){
Nodo* aux;
int v;
if(!laPilaEstaVacia()){
aux = tope;
tope = tope->dameTuSiguiente();
v = aux->dameTuValor();
delete(aux);
return v;
}
else{
cout << "La pila esta vacia" << endl;
exit(0);
}
}
~Pila(){
cout << "Destructor Pila" << endl;
while(!laPilaEstaVacia()){
cout << pop() << endl;
}
}
};
#endif // PILA_H
|
#include <iostream>
using std::ostream;
using std::istream;
class Array{
friend ostream &operator<<(ostream &, const Array &);
friend istream &operator>>(istream &, const Array &);
public:
Array(int = 10);
Array(const Array &);
~Array();
int getTamanio() const;
const Array operator=(const Arrayt &);
bool operator
};
|
#ifndef IO_H
# define IO_H
# include "character.h"
class dungeon;
void io_init_terminal(void);
void io_reset_terminal(void);
void io_display(dungeon *d);
void io_handle_input(dungeon *d);
void io_queue_message(const char *format, ...);
int io_select_item(dungeon *d);
void io_list_free_inv(dungeon *d);
void io_list_equip_inv(dungeon *d);
const char *io_get_slot_name(dungeon *d, int slot);
int io_select_equip_item(dungeon *d);
void io_remove_equip(dungeon *d);
void io_drop_item(dungeon *d);
void io_expunge_item(dungeon *d);
void io_item_description(dungeon *d);
void io_look_monster(dungeon *d);
void io_mon_info(character *n);
void mod_redisplay_non_terrain(dungeon *d, pair_t cursor);
#endif
|
#include "Produce.h"
PassengerCar* Produce::create_passenger_car(UserInterface* ui)
{
PassengerCar* car = new PassengerCar;
ui->passenger_car_alert();
double weight;
while (true)
{
ui->vehicle_weight_req();
std::cin >> weight;
if (ui->check_symbols() || weight < 0 || weight > 2500)
{
ui->problem_value();
continue;
}
else
{
car->set_weight(weight);
break;
}
}
double max_speed;
while (true)
{
ui->vehicle_max_speed_req();
std::cin >> max_speed;
if (ui->check_symbols() || max_speed < 0 || max_speed > 200)
{
ui->problem_value();
continue;
}
else
{
car->set_max_speed(max_speed);
break;
}
}
double fuel_consumption;
while (true)
{
ui->vehicle_fuel_consumption_req();
std::cin >> fuel_consumption;
if (ui->check_symbols() || fuel_consumption < 0 || fuel_consumption > 6)
{
ui->problem_value();
continue;
}
else
{
car->set_fuel_consumption(fuel_consumption);
break;
}
}
int passengers;
while (true)
{
ui->passengers_req();
std::cin >> passengers;
if (ui->check_symbols() || passengers < 0 || passengers > 4)
{
ui->problem_value();
continue;
}
else
{
car->set_passengers_number(passengers);
break;
}
}
double max_luggage;
while (true)
{
ui->max_luggage_req();
std::cin >> max_luggage;
if (ui->check_symbols() || max_luggage < 0 || max_luggage > 120)
{
ui->problem_value();
continue;
}
else
{
car->set_max_luggage(max_luggage);
break;
}
}
double max_volume;
while (true)
{
ui->volume_req();
std::cin >> max_volume;
if (ui->check_symbols() || max_volume < 0 || max_volume > 1)
{
ui->problem_value();
continue;
}
else
{
car->set_max_volume(max_volume);
break;
}
}
std::string body_type;
while (true)
{
ui->body_type_req();
std::cin >> body_type;
if (body_type == "sedan" || body_type == "wagon" || body_type == "coupe" || body_type == "crossover")
{
car->set_body_type(body_type);
break;
}
else
{
ui->problem_value();
continue;
}
}
std::string car_class;
while (true)
{
ui->car_class_req();
std::cin >> car_class;
if (car_class == "small" || car_class == "medium" || car_class == "large" || car_class == "premium")
{
car->set_car_class(car_class);
break;
}
else
{
ui->problem_value();
continue;
}
}
std::string seat_type;
while (true)
{
ui->seat_type_req();
std::cin >> seat_type;
if (seat_type == "ordinary" || seat_type == "sports" || seat_type == "comfortable")
{
car->set_seat_type(seat_type);
break;
}
else
{
ui->problem_value();
continue;
}
}
return car;
}
Motorcycle* Produce::create_motorcycle(UserInterface* ui)
{
Motorcycle* mot = new Motorcycle;
ui->motorcycle_alert();
double weight;
while (true)
{
ui->vehicle_weight_req();
std::cin >> weight;
if (ui->check_symbols() || weight < 0 || weight > 300)
{
ui->problem_value();
continue;
}
else
{
mot->set_weight(weight);
break;
}
}
double max_speed;
while (true)
{
ui->vehicle_max_speed_req();
std::cin >> max_speed;
if (ui->check_symbols() || max_speed < 0 || max_speed > 250)
{
ui->problem_value();
continue;
}
else
{
mot->set_max_speed(max_speed);
break;
}
}
double fuel_consumption;
while (true)
{
ui->vehicle_fuel_consumption_req();
std::cin >> fuel_consumption;
if (ui->check_symbols() || fuel_consumption < 0 || fuel_consumption > 5)
{
ui->problem_value();
continue;
}
else
{
mot->set_fuel_consumption(fuel_consumption);
break;
}
}
int passengers;
while (true)
{
ui->passengers_req();
std::cin >> passengers;
if (ui->check_symbols() || passengers < 0 || passengers > 2)
{
ui->problem_value();
continue;
}
else
{
mot->set_passengers_number(passengers);
break;
}
}
double max_luggage;
while (true)
{
ui->max_luggage_req();
std::cin >> max_luggage;
if (ui->check_symbols() || max_luggage < 0 || max_luggage > 10)
{
ui->problem_value();
continue;
}
else
{
mot->set_max_luggage(max_luggage);
break;
}
}
double max_volume;
while (true)
{
ui->volume_req();
std::cin >> max_volume;
if (ui->check_symbols() || max_volume < 0 || max_volume > 0.3)
{
ui->problem_value();
continue;
}
else
{
mot->set_max_volume(max_volume);
break;
}
}
bool carriage;
while (true)
{
ui->motorcycle_carriage_req();
std::cin >> carriage;
if (ui->check_symbols() || carriage != 0 && carriage != 1)
{
ui->problem_operation();
continue;
}
else
{
mot->set_carriage(carriage);
break;
}
}
std::string car_class;
while (true)
{
ui->car_class_req();
std::cin >> car_class;
if (car_class == "small" || car_class == "medium" || car_class == "large" || car_class == "premium")
{
mot->set_car_class(car_class);
break;
}
else
{
ui->problem_value();
continue;
}
}
std::string seat_type;
while (true)
{
ui->seat_type_req();
std::cin >> seat_type;
if (seat_type == "ordinary" || seat_type == "sports" || seat_type == "comfortable")
{
mot->set_seat_type(seat_type);
break;
}
else
{
ui->problem_value();
continue;
}
}
return mot;
}
Truck* Produce::create_truck(UserInterface* ui)
{
Truck* tr = new Truck;
ui->truck_alert();
double weight;
while (true)
{
ui->vehicle_weight_req();
std::cin >> weight;
if (ui->check_symbols() || weight < 0 || weight > 40000)
{
ui->problem_value();
continue;
}
else
{
tr->set_weight(weight);
break;
}
}
double max_speed;
while (true)
{
ui->vehicle_max_speed_req();
std::cin >> max_speed;
if (ui->check_symbols() || max_speed < 0 || max_speed > 110)
{
ui->problem_value();
continue;
}
else
{
tr->set_max_speed(max_speed);
break;
}
}
double fuel_consumption;
while (true)
{
ui->vehicle_fuel_consumption_req();
std::cin >> fuel_consumption;
if (ui->check_symbols() || fuel_consumption < 0 || fuel_consumption > 35)
{
ui->problem_value();
continue;
}
else
{
tr->set_fuel_consumption(fuel_consumption);
break;
}
}
int passengers;
while (true)
{
ui->passengers_req();
std::cin >> passengers;
if (ui->check_symbols() || passengers < 0 || passengers > 2)
{
ui->problem_value();
continue;
}
else
{
tr->set_passengers_number(passengers);
break;
}
}
double carrying;
while (true)
{
ui->truck_carrying_req();
std::cin >> carrying;
if (ui->check_symbols() || carrying < 0 || carrying > 10000)
{
ui->problem_value();
continue;
}
else
{
tr->set_carrying(carrying);
break;
}
}
double max_volume;
while (true)
{
ui->volume_req();
std::cin >> max_volume;
if (ui->check_symbols() || max_volume < 0 || max_volume > 90)
{
ui->problem_value();
continue;
}
else
{
tr->set_max_volume(max_volume);
break;
}
}
return tr;
}
Bus* Produce::create_bus(UserInterface* ui)
{
Bus* bus = new Bus;
ui->bus_alert();
double weight;
while (true)
{
ui->vehicle_weight_req();
std::cin >> weight;
if (ui->check_symbols() || weight < 0 || weight > 15000)
{
ui->problem_value();
continue;
}
else
{
bus->set_weight(weight);
break;
}
}
double max_speed;
while (true)
{
ui->vehicle_max_speed_req();
std::cin >> max_speed;
if (ui->check_symbols() || max_speed < 0 || max_speed > 120)
{
ui->problem_value();
continue;
}
else
{
bus->set_max_speed(max_speed);
break;
}
}
double fuel_consumption;
while (true)
{
ui->vehicle_fuel_consumption_req();
std::cin >> fuel_consumption;
if (ui->check_symbols() || fuel_consumption < 0 || fuel_consumption > 18)
{
ui->problem_value();
continue;
}
else
{
bus->set_fuel_consumption(fuel_consumption);
break;
}
}
int passengers;
while (true)
{
ui->passengers_req();
std::cin >> passengers;
if (ui->check_symbols() || passengers < 0 || passengers > 25)
{
ui->problem_value();
continue;
}
else
{
bus->set_passengers_number(passengers);
break;
}
}
double luggage_pass;
while (true)
{
ui->max_luggage_pass_req();
std::cin >> luggage_pass;
if (ui->check_symbols() || luggage_pass < 0 || luggage_pass > 20)
{
ui->problem_value();
continue;
}
else
{
bus->set_max_luggage_pass(luggage_pass);
break;
}
}
double max_luggage;
while (true)
{
ui->max_luggage_req();
std::cin >> max_luggage;
if (ui->check_symbols() || max_luggage < 0 || max_luggage > 500 || luggage_pass*passengers > max_luggage)
{
ui->problem_value();
continue;
}
else
{
bus->set_max_luggage(max_luggage);
break;
}
}
double max_volume;
while (true)
{
ui->volume_req();
std::cin >> max_volume;
if (ui->check_symbols() || max_volume < 0 || max_volume > 10)
{
ui->problem_value();
continue;
}
else
{
bus->set_max_volume(max_volume);
break;
}
}
bool conditioner;
while (true)
{
ui->conditioner_req();
std::cin >> conditioner;
if (ui->check_symbols() || conditioner != 0 && conditioner != 1)
{
ui->problem_value();
continue;
}
else
{
bus->set_conditioner(conditioner);
break;
}
}
bool reclining_seat;
while (true)
{
ui->reclining_seat_req();
std::cin >> reclining_seat;
if (ui->check_symbols() || reclining_seat != 0 && reclining_seat != 1)
{
ui->problem_value();
continue;
}
else
{
bus->set_reclining_seat(reclining_seat);
break;
}
}
std::string car_class;
while (true)
{
ui->car_class_req();
std::cin >> car_class;
if (car_class == "small" || car_class == "medium" || car_class == "large" || car_class == "premium")
{
bus->set_car_class(car_class);
break;
}
else
{
ui->problem_value();
continue;
}
}
std::string seat_type;
while (true)
{
ui->seat_type_req();
std::cin >> seat_type;
if (seat_type == "ordinary" || seat_type == "sports" || seat_type == "comfortable")
{
bus->set_seat_type(seat_type);
break;
}
else
{
ui->problem_value();
continue;
}
}
return bus;
}
|
#include <fstream>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
//#include <vector.h>
#include <iostream>
#include <string>
#include <string.h>
#include <iomanip>
#include <sstream>
#include "TH2D.h"
#include "TF1.h"
#include "TH1D.h"
#include "TCanvas.h"
#include "TStyle.h"
#include "TRandom3.h"
#include "TVirtualFitter.h"
#include "TList.h"
#include "TStopwatch.h"
#include "TMinuit.h"
#include "TMath.h"
#include "TGraph.h"
#include "TFile.h"
#include "TBranch.h"
#include "TH2F.h"
#include "TLine.h"
#include "TMarker.h"
#include "TTree.h"
#include <stdlib.h>
#include "TAxis.h"
#include "TEventList.h"
#include "time.h"
#include "TProfile.h"
using namespace::std;
class TEventList;
struct Data_t {
Int_t SM;
Int_t time;
Int_t nterm;
Int_t TT;
Int_t xtal;
Float_t temperature;
};
Int_t GetIForMaps(Int_t, Int_t);
Int_t GetJForMaps(Int_t, Int_t);
void GetOutOfRange(float,TH2D*,TH1F*,int,int);
int FromTTVFEToTherm(int,int);
int VFEReturnPos(int,int);
bool CheckBoor(int,int,TTree*,int);
string TFileStr,filename,TFileStrTrend,TFileStrTrendSpread,TFileStr2,TFileStr5,TFileStr6,TFileStr4,TFileStr3;
int mintime;
int maxtime=time(0);
int main(int argc, const char* argv[])
{
string rootline=(string)argv[1];
string dailyoption=(string)argv[2];
istringstream buffer(dailyoption);
int daily;
buffer >> daily;
if (daily==0){
cout<<"Making The anlysis as 2 hours analysis"<<endl;
TFileStr = "/data/ecalod-disk01/dcu-data/Stability/DailyAnalysisEE.root";
filename="/data/ecalod-disk01/dcu-data/Stability/summaryEE.txt";
TFileStrTrend = "/data/ecalod-disk01/dcu-data/Stability/EETrend.png";
TFileStrTrendSpread = "/data/ecalod-disk01/dcu-data/Stability/EETrendSpread.png";
TFileStr2 = "/data/ecalod-disk01/dcu-data/Stability/a.png";
TFileStr5 = "/data/ecalod-disk01/dcu-data/Stability/RMSPlotEEm.png";
TFileStr6 = "/data/ecalod-disk01/dcu-data/Stability/RMSPlotEEp.png";
TFileStr4 = "/data/ecalod-disk01/dcu-data/Stability/RMSPlot2.png";
TFileStr3 = "/data/ecalod-disk01/dcu-data/Stability/EEDiffTherm.png";
mintime=maxtime-(3*3600);
}
if (daily==1){
cout<<"Making The anlysis as Daily analysis"<<endl;
TFileStr = "/data/ecalod-disk01/dcu-data/Stability/Daily/DailyAnalysisEE.root";
filename="/data/ecalod-disk01/dcu-data/Stability/Daily/summaryEE.txt";
TFileStrTrend = "/data/ecalod-disk01/dcu-data/Stability/Daily/EETrend.png";
TFileStrTrendSpread = "/data/ecalod-disk01/dcu-data/Stability/Daily/EETrendSpread.png";
TFileStr2 = "/data/ecalod-disk01/dcu-data/Stability/Daily/a.png";
TFileStr5 = "/data/ecalod-disk01/dcu-data/Stability/Daily/RMSPlotEEm.png";
TFileStr6 = "/data/ecalod-disk01/dcu-data/Stability/Daily/RMSPlotEEp.png";
TFileStr4 = "/data/ecalod-disk01/dcu-data/Stability/Daily/RMSPlot2.png";
TFileStr3 = "/data/ecalod-disk01/dcu-data/Stability/Daily/EEDiffTherm.png";
mintime=maxtime-(1*24*3600);
}
gStyle->SetPalette(1);
TFile *Roottupla = new TFile(rootline.c_str());
TFile *Analysis = new TFile(TFileStr.c_str(), "RECREATE", "DCU data");
Data_t stability;
stringstream numberswap;
bool RMScalculus=true;
bool ThermCorr=true;
TTree *T=(TTree*)Roottupla->Get("T");
TBranch *branch=T->GetBranch("stability");
branch->SetAddress(&stability);
cout<<"retrieving data..."<<T-> GetEntries()<<" events collected"<<endl;
gStyle->SetOptStat(111111);
int totalsector=9;
int maxTT=171;
int EmptySensorList[9][171];
for(int i=0;i<totalsector;i++){
for(int j=0;j<maxTT;j++){
EmptySensorList[i][j]=0;
}
}
int TTNumber[9];
TTNumber[0]=33;
TTNumber[1]=32;
TTNumber[2]=34;
TTNumber[3]=33;
TTNumber[4]=41;//!! a hole into the file!!
TTNumber[5]=33;
TTNumber[6]=34;
TTNumber[7]=32;
TTNumber[8]=33;
EmptySensorList[0][29]=1;//sector 1
EmptySensorList[0][11]=1;
EmptySensorList[1][2]=1;//sector 2
EmptySensorList[1][24]=1;
EmptySensorList[1][31]=1;
EmptySensorList[2][9]=1;
EmptySensorList[2][33]=1;//sector 3
EmptySensorList[3][13]=1;//sector 4
EmptySensorList[3][20]=1;
EmptySensorList[4][2]=1;//sector 5
EmptySensorList[4][5]=1;
EmptySensorList[4][26]=1;
EmptySensorList[4][29]=1;
EmptySensorList[5][13]=1;//sector 6
EmptySensorList[5][20]=1;
EmptySensorList[6][9]=1;//sector 7
EmptySensorList[6][33]=1;
EmptySensorList[7][31]=1;//sector 8
EmptySensorList[7][2]=1;
EmptySensorList[7][24]=1;
EmptySensorList[8][11]=1;//sector 9
EmptySensorList[8][29]=1;
EmptySensorList[0][28]=1;//sector 1
EmptySensorList[0][10]=1;
EmptySensorList[1][1]=1;//sector 2
EmptySensorList[1][23]=1;
EmptySensorList[1][30]=1;
EmptySensorList[2][8]=1;
EmptySensorList[2][32]=1;//sector 3
EmptySensorList[3][12]=1;//sector 4
EmptySensorList[3][19]=1;
EmptySensorList[4][1]=1;//sector 5
EmptySensorList[4][4]=1;
EmptySensorList[4][25]=1;
EmptySensorList[4][28]=1;
EmptySensorList[5][12]=1;//sector 6
EmptySensorList[5][19]=1;
EmptySensorList[6][8]=1;//sector 7
EmptySensorList[6][32]=1;
EmptySensorList[7][30]=1;//sector 8
EmptySensorList[7][1]=1;
EmptySensorList[7][23]=1;
EmptySensorList[8][10]=1;//sector 9
EmptySensorList[8][28]=1;
//Broken
EmptySensorList[7][17]=1;//sector 9
EmptySensorList[7][18]=1;
cout<<"making plots"<<endl;
stringstream smstr,ntstr;
ofstream outputfile2;
ofstream outputfile3;
outputfile2.open(filename.c_str());
if (RMScalculus==true)
{
TCanvas *EETrend = new TCanvas("EETrend","ECAL Barrel Plus side temperature spread",400,20,1200,800);
gPad->SetFillColor(0);
gStyle->SetOptStat("emruo");
TProfile* pippo = new TProfile("pippo","EE+ Dee1",maxtime-mintime,mintime,maxtime,18,19);
TProfile* pippo2 = new TProfile("pippo2","EE+ Dee2",maxtime-mintime,mintime,maxtime,18,19);
TProfile* pippo3 = new TProfile("pippo3","EE- Dee3",maxtime-mintime,mintime,maxtime,18,19);
TProfile* pippo4 = new TProfile("pippo4","EE- Dee4",maxtime-mintime,mintime,maxtime,18,19);
T->Project("pippo","temperature:time","temperature > 10 && temperature < 30 && SM >4");
pippo->GetXaxis()->SetLabelSize(0.03);
pippo->GetYaxis()->SetTitle("Temperature (#circC)");
pippo->GetXaxis()->SetTitle("Timestamps");
pippo->SetMarkerStyle(15);
pippo->SetMarkerSize(0.6);
pippo->GetYaxis()->SetRangeUser(18,19);
pippo->SetMarkerColor(kRed);
pippo->Draw();
T->Project("pippo2","temperature:time","temperature > 10 && temperature < 30 && SM >0 && SM <=4");
pippo2->SetMarkerColor(kBlack);
pippo2->SetMarkerStyle(15);
pippo2->SetMarkerSize(0.6);
pippo2->Draw("SAMES");
T->Project("pippo3","temperature:time","temperature > 10 && temperature < 30 && SM <0 && SM >-4");
pippo3->SetMarkerColor(kBlue);
pippo3->SetMarkerStyle(15);
pippo3->SetMarkerSize(0.6);
pippo3->Draw("SAMES");
T->Project("pippo4","temperature:time","temperature > 10 && temperature < 30 && SM <-4");
pippo4->SetMarkerColor(kGreen);
pippo4->SetMarkerStyle(15);
pippo4->SetMarkerSize(0.6);
pippo4->Draw("SAMES");
EETrend->BuildLegend(0.48,0.28,0.67,0.43);
TLine *linemin2= new TLine(mintime,18.70,maxtime,18.70);
TLine *linemax2= new TLine(mintime,18.65,maxtime,18.65);
linemin2->SetLineColor(2);
linemax2->SetLineColor(2);
linemax2->Draw();
linemin2->Draw();
EETrend->Print(TFileStrTrend.c_str(),"png");
TCanvas *EETrendSpread = new TCanvas("EETrendSpread","ECAL Barrel Plus side temperature spread",400,20,1200,800);
TH1F* pippo5 = new TH1F("pippo5","EE+ Dee1",150,18,19.5);
TH1F* pippo6 = new TH1F("pippo6","EE+ Dee2",150,18,19.5);
TH1F* pippo7 = new TH1F("pippo7","EE- Dee3",150,18,19.5);
TH1F* pippo8 = new TH1F("pippo8","EE- Dee4",150,18,19.5);
gPad->SetFillColor(0);
gStyle->SetOptStat("emr");
T->Project("pippo5","temperature","temperature > 10 && temperature < 30 && SM >4");
pippo5->GetXaxis()->SetLabelSize(0.03);
pippo5->GetXaxis()->SetTitle("Temperature (#circC)");
pippo5->SetFillColor(kRed);
pippo5->SetFillStyle(3005);
pippo5->Draw();
T->Project("pippo6","temperature","temperature > 10 && temperature < 30 && SM >0 && SM <=4");
pippo6->SetFillColor(kBlack);
pippo6->SetFillStyle(3006);
pippo6->Draw("SAMES");
T->Project("pippo7","temperature","temperature > 10 && temperature < 30 && SM <0 && SM >-4");
pippo7->SetFillColor(kBlue);
pippo7->SetFillStyle(3005);
pippo7->Draw("SAMES");
T->Project("pippo8","temperature","temperature > 10 && temperature < 30 && SM <-4");
pippo8->SetFillColor(kGreen);
pippo8->SetFillStyle(3007);
pippo8->Draw("SAMES");
EETrendSpread->BuildLegend(0.15,0.64,0.34,0.80);
EETrendSpread->Print(TFileStrTrendSpread.c_str(),"png");
// // Capsule Stability.Temperature histogram
TCanvas *c1 = new TCanvas("c1","c1",200,10,1000,700);
TH1D * TempHisto = new TH1D("RMS of thermistors EE","RMS of the thermistors EE",500,0,0.5);
float xmax=0.1;
gPad->SetLogy(1);
gPad->SetFillColor(0);
TAxis *x0 = new TAxis();
x0 = TempHisto->GetXaxis();
x0->SetRangeUser(-0.01,(xmax+0.01));
x0->Draw();
TH1F * SwapForRMS = new TH1F("SwapForRMS","SwapForRMS",10000,10,30);
//trying to plot the RMS of the crystals
TH1F * SwapForRMSSec = new TH1F("SwapForRMSSec","SwapForRMSSec",10000,0,1);
TH2D * RMSVsSec = new TH2D("RMSVsSec","RMSVsSec",19,-9,9,100,0,0.1);
TH2F *h[18];
//trying to plot the RMS of the crystals
stringstream smstr,ntstr;
for ( int j = -9; j <= 9; j++ ) {
if(j!=0) { //and incorporates bad thermistors by hand... //setting up things...
stringstream oss;
oss<<j;
string plottitle="RMS distribution for EE"+oss.str();
string plotname="h"+oss.str();
if (j<0) h[j+9] = new TH2F( plotname.c_str(),plottitle.c_str(),34,1,34,1000,0,.1);
if (j>0) h[j+8] = new TH2F( plotname.c_str(),plottitle.c_str(),34,1,34,1000,0,.1);
for ( int i = 1; i <= 34; i++ ) {
if((j==8 && i==19) || (j==-8 && i==22) || (j==3 && i==9) ) { //and incorporates bad thermistors by hand...
cout<<"Thermistor "<<i<<" in EE"<<j<<" excluded by hand because is not working properly"<<endl;
continue;
}
SwapForRMS->Reset();
smstr<<j;
ntstr<<i;
string cut="stability.temperature>10 && stability.temperature<30 && stability.SM=="+smstr.str()+" && stability.nterm=="+ntstr.str();
int points=T->Draw("stability.temperature>>SwapForRMS",cut.c_str(),"goff");
if (points>0) {
SwapForRMSSec->Fill(SwapForRMS->GetRMS());
TempHisto->Fill(SwapForRMS->GetRMS());
}
if (points>0 && SwapForRMS->GetRMS() > 0.1 ) outputfile2<<"RMS for thermister in EE"<<j<<" and number "<<i<<" is RMS="<<SwapForRMS->GetRMS()<<endl;
if (points==0)
{
outputfile2<<"Zero points for thermister number "<<i<<" in EE"<<j<<endl;
}
ntstr.str("");
smstr.str("");
if (j<0) h[j+9]->Fill(i,SwapForRMSSec->GetRMS());
if (j>0) h[j+8]->Fill(i,SwapForRMSSec->GetRMS());
}
if (j<0) h[j+9]->Write();
if (j>0) h[j+8]->Write();
}
RMSVsSec->Fill(j,SwapForRMSSec->GetMean());
SwapForRMSSec->Reset();
}
delete SwapForRMS;
TempHisto-> GetXaxis() -> SetTitle("RMS (#circC)");
int y_max = TempHisto->GetBinContent(TempHisto->GetMaximumBin());
TLine *linemin= new TLine(0,0,0,y_max);
TLine *linemax= new TLine(xmax, 0,xmax,y_max);
linemin->SetLineColor(2);
linemax->SetLineColor(2);
TempHisto-> Draw();
linemax->Draw();
linemin->Draw();
c1->Print(TFileStr2.c_str(),"png");
TCanvas *RMSplotEEm = new TCanvas("RMSplotEEm","RMS of thermistors in EE minus",300,30,1500,1200);
RMSplotEEm->Divide(3,3);
for (int i=0;i<9; i++){
RMSplotEEm->cd(i+1);
gPad->SetFillColor(0);
h[i]->SetMarkerStyle(20);
h[i]->SetMarkerSize(0.5);
stringstream oss;
oss<<i+1;
string label="EE-"+oss.str();
h[i]->SetTitle(label.c_str());
//float y_max = h[i]->GetBinContent(h[i]->GetMaximumBin())
h[i]->GetYaxis()->SetRangeUser(0,y_max);
h[i]->Draw();
oss.str("");
}
RMSplotEEm->Print(TFileStr5.c_str(),"png");
TCanvas *RMSplotEEp = new TCanvas("RMSplotEEp","RMS of thermistors in EE plus",300,30,1500,1200);
RMSplotEEp->Divide(3,3);
for (int i=9;i<=17; i++){
RMSplotEEp->cd(i-8);
gPad->SetFillColor(0);
h[i]->SetMarkerStyle(19);
h[i]->SetMarkerSize(0.5);
stringstream oss;
oss<<(i-8);
string label="EE+"+oss.str();
h[i]->SetTitle(label.c_str());
h[i]->Draw();
oss.str("");
}
RMSplotEEp->Print(TFileStr6.c_str(),"png");
TCanvas *RMSplotC2 = new TCanvas("RMSplotC2","crystal fluctuation for all crystals",300,30,1500,1200);
RMSplotC2->cd();
gStyle->SetOptStat("em");
RMSVsSec->SetMarkerStyle(21);
gPad->SetFillColor(0);
RMSVsSec->SetMarkerSize(1);
RMSVsSec->SetTitle("Endcap RMS sectro by sector");
RMSVsSec->Draw();
RMSplotC2->Print(TFileStr4.c_str(),"png");
}
std::vector<float> TStory;
std::vector<float> TStory2;
std::vector<float> TStory3;
if (ThermCorr==true)
{
cout<<"starting thermisotr correlation "<<endl;
TH1F * SwapForRMS = new TH1F("SwapForRMS","SwapForRMS",10000,10,30);
stringstream sp;
//Making correlation between thermister
TH1F *thermisterStory = new TH1F("thermisterStory","temperature corrected",40000,-20,20);
TH1F *RMSofTherm = new TH1F("RMS of differerence bwtween neighbouring sensors","RMS of the difference between neighbouring thermistors",1500,0,1.5);
thermisterStory->SetFillColor(40);
float xmax=0.1;
TAxis *x0 = new TAxis();
x0 = RMSofTherm->GetXaxis();
x0->SetRangeUser(-0.01,(xmax+0.01));
x0->Draw();
TH1F *entryes= new TH1F("entryes","entryes",100,0,100);
//get data
for(int SMcount=-9;SMcount<=9;SMcount++)
{
if (SMcount != 0){
sp<<SMcount;
for (int trnumb=1; trnumb <(TTNumber[abs(SMcount)-1]-1) ; trnumb++){
for ( int i = 0; i < T-> GetEntries(); i++ ) {
T->GetEvent(i);
if(stability.SM==SMcount && stability.TT==trnumb && stability.temperature>10 && stability.temperature<30){
TStory.push_back(stability.temperature);
}
if(stability.SM==SMcount && stability.TT==trnumb+1 && stability.temperature>10 && stability.temperature<30){
TStory2.push_back(stability.temperature);
}
}
int shortestsize;
if (TStory.size()==TStory2.size()) {
shortestsize=TStory2.size();
}
else
{
shortestsize=0;
}
for(int z=0;z<shortestsize;z++){
thermisterStory->Fill((TStory2[z]-TStory[z]));
}
if((thermisterStory->GetRMS()>0.05 ) && EmptySensorList[abs(SMcount)-1][trnumb-1]==0 && shortestsize>0 )
{
outputfile2<<"Therm diff_RMS for thrmister number "<<trnumb<<" in EB"<<SMcount<<" is "<<thermisterStory->GetRMS()<<" with entries "<<thermisterStory->GetEntries()<<endl; for(int z=0;z<shortestsize;z++){
}
}
if (shortestsize>0 && EmptySensorList[abs(SMcount)-1][trnumb-1]==0) {
entryes->Fill(shortestsize);
RMSofTherm->Fill(thermisterStory->GetRMS());
}
TStory.clear();
TStory2.clear();
thermisterStory->Reset();
}
}
sp.clear();
sp.str("");
}
delete entryes;
delete thermisterStory;
outputfile2.close();
Analysis->Write();
TCanvas *c2 = new TCanvas("c2","c2",200,10,1000,700);
gPad->SetLogy(1);
gPad->SetFillColor(0);
RMSofTherm->Draw();
RMSofTherm->Write();
RMSofTherm-> GetXaxis() -> SetTitle("RMS (#circC)");
int y_max = RMSofTherm->GetBinContent(RMSofTherm->GetMaximumBin());
TLine *linemin= new TLine(0,0,0,y_max);
TLine *linemax= new TLine(xmax, 0,xmax,y_max);
linemin->SetLineColor(2);
linemax->SetLineColor(2);
RMSofTherm-> Draw();
linemax->Draw();
linemin->Draw();
c2->Print(TFileStr3.c_str(),"png");
}
}
//////////////////////////////////////////////////////////////////////////////////
Int_t GetIForMaps(Int_t SM, Int_t xtal) {
if(SM<0){
return (-1+(int(xtal) % 20)+20*(-SM-1));
}
if(SM>0){
return (20-(int(xtal) % 20)+20*(SM-1));
}
}
Int_t GetJForMaps(Int_t SM, Int_t xtal) {
if(SM<0){
return (-int(xtal/20));
}
if(SM>0){
return (1+int(xtal/20));
}
}
void GetOutOfRange(float temp,TH2D* histo,TH1F* spread,int SM,int xtal){
if(temp > 18.5 || temp <17.9){
//cout<<"thermistor "<<xtal<<" in SM "<<SM<<" has T="<<temp<<endl;
histo->Fill(GetIForMaps(SM,xtal),GetJForMaps(SM,xtal),temp);
spread->Fill(temp);
}
return;
}
int FromTTVFEToTherm(int TT,int VFE) {
int therm;
if (TT%2==1)//se TT e' dispari
{
if (VFE==1 || VFE==3 || VFE==5)// deve avere 3 canali se pari
{
therm=((TT/2)*5)+VFEReturnPos(TT,VFE);
// cout<<"therm is "<<therm<<" since VFE is "<<VFEReturnPos(TT,VFE)<<endl;
}
else
{
// cout<<"mismatching VFE/TT"<<endl;
return 0;
}
}
else
{
if (VFE==2 || VFE==4)// deve avere 3 canali se pari
{
therm=((((TT)/2)*5)-2)+VFEReturnPos(TT,VFE);
//cout<<"therm is "<<therm<<endl;
}
else
{
//cout<<"mismatching VFE/TT"<<" since VFE is "<<VFEReturnPos(TT,VFE)<<endl;
return 0;
}
}
return therm;
}
int VFEReturnPos(int TT,int VFE){
if (TT%2==1)//se TT e' dispari
{
if(TT>=61 || (TT>=13 && TT<=20) || (TT>=29 && TT<=36) || (TT>=45 && TT<=52)){
if (VFE==1) return 1;
if (VFE==3) return 2;
if (VFE==5) return 3;
}
else
{
if (VFE==1) return 3;
if (VFE==3) return 2;
if (VFE==5) return 1;
}
}
else
{
if(TT>=61 || (TT>=13 && TT<=20) || (TT>=29 && TT<=36) || (TT>=45 && TT<=52)){
if (VFE==2) return 1;
if (VFE==4) return 2;
}
else
{
if (VFE==2) return 2;
if (VFE==4) return 1;
}
}
}
bool CheckBoor(int nterm,int thresh,TTree *T,int SM){
TH1F * SwapForRMSc = new TH1F("SwapForRMSc","SwapForRMSc",10000,10,30);
TH1F * SwapForRMSsx = new TH1F("SwapForRMSsx","SwapForRMSsx",10000,10,30);
TH1F * SwapForRMSdx = new TH1F("SwapForRMSdx","SwapForRMSdx",10000,10,30);
stringstream smstr,ntstr;
smstr<<SM;
ntstr<<nterm;
float central;
float sx;
float dx;
string cut="stability.temperature>10 && stability.temperature<30 && stability.time>1223912000 && stability.time<1226420000 && stability.SM=="+smstr.str()+" && stability.nterm=="+ntstr.str();
T->Draw("stability.temperature>>SwapForRMSc",cut.c_str(),"goff");
central=SwapForRMSc->GetRMS();
ntstr.str("");
ntstr<<nterm-1;
cut="stability.temperature>10 && stability.temperature<30 && stability.time>1223912000 && stability.time<1226420000 && stability.SM=="+smstr.str()+" && stability.nterm=="+ntstr.str();
T->Draw("stability.temperature>>SwapForRMSsx",cut.c_str(),"goff");
sx=SwapForRMSsx->GetRMS();
ntstr.str("");
ntstr<<nterm+1;
cut="stability.temperature>10 && stability.temperature<30 && stability.time>1223912000 && stability.time<1226420000 && stability.SM=="+smstr.str()+" && stability.nterm=="+ntstr.str();
T->Draw("stability.temperature>>SwapForRMSdx",cut.c_str(),"goff");
dx=SwapForRMSdx->GetRMS();
// cout<<"sx RMS is "<<sx<<" <=== central is "<<central<<" ===> dx RMS is "<<dx<<endl;
delete SwapForRMSc;
delete SwapForRMSsx;
delete SwapForRMSdx;
ntstr.str("");
float sxdiff=fabs(central-sx);
float dxdiff=fabs(central-dx);
if(sx<0.00001 || dx<0.00001) return true;
if( (sxdiff<thresh) && (dxdiff<thresh)){
// cout<<"low difference...channel in same condition"<<endl;
return true;
}
else {
return false;
}
}
|
#ifndef __RECTANGLE_H__
#define __RECTANGLE_H__
// Library Includes
#include <windows.h>
#include <windowsx.h>
#include "shape.h"
class CRectangle : public IShape {
public:
CRectangle();
CRectangle(EBRUSHSTYLE _iBrushStyle, int _iHatchStyle, COLORREF _FillColor, int _iPenWidth, int _iPenStyle, COLORREF _PenColor);
virtual ~CRectangle();
virtual void Draw(HDC _hdc);
void SetBrushStyle(EBRUSHSTYLE _brushStyle);
void SetFillColor(COLORREF _newColor);
void SetPenStyle(int _iPenStyle);
void SetPenColor(COLORREF _newColor);
void SetHatchStyle(int _iHatchStyle);
};
#endif //__RECTANGLE_H__
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e10
#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 MAX 100
int main() {
int a,b,c;
scanf("%d %d %d", &a, &b, &c);
int ans = 0, ans1 = 0;
ans1 = abs(a-b) + abs(b-c);
ans = abs(a-c) + abs(c-b);
ans1 = min(ans,ans1);
ans = abs(b-a) + abs(a-c);
ans1 = min(ans,ans1);
ans = abs(b-c) + abs(c-a);
ans1 = min(ans,ans1);
ans = abs(c-a) + abs(a-b);
ans1 = min(ans,ans1);
ans = abs(c-b) + abs(b-a);
cout << ans1 << endl;
}
|
#include <iostream>
void allocatedMatrix(char**& matrix, int row) {
matrix = new char*[row];
for (int i = 0; i < row; ++i) {
matrix[i] = new char[row];
}
}
void deleteMatrix(char**& array, int size) {
for (int i = 0; i < size; ++i) {
delete[] array[i];
}
delete[] array;
}
void printMatrix(char**& array, int size) {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
}
void initMatrix(char**& array, char symbol, int size) {
allocatedMatrix(array, size);
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++ j) {
array[i][j] = symbol;
if (i > 0 && i < size/2) {
array[i][j] = symbol;
j += size;
}
if (i > size/2 && i < size - 1) {
array[i][j] = symbol;
j += size;
}
}
}
}
int countOfInputedCharacter(char**& array, int size, char inputedCharacter) {
int count = 0;
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
if (inputedCharacter == array[i][j]) {
++count;
}
}
}
return count;
}
void replace(char**& array, int size, char oldCharacter, char newCharacter) {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
if (array[i][j] == oldCharacter) {
array[i][j] = newCharacter;
}
}
}
}
void validNumber(int& number) {
while (std::cin.fail() || 5 > number ||
23 < number || 0 == number % 2) {
std::cout << "Invalid Value: Try again!" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cout << "Please enter the intager number (5, 7, 9, ..., 23): ";
std::cin>> number;
}
}
int main() {
char** arr;
char symbol = ' ';
int size = 0;
bool continueAction = 1;
std::cout << "\nEnter any symbol: ";
std::cin >> symbol;
std::cout << "Enter odd number for size: ";
std::cin >> size;
validNumber(size);
initMatrix(arr, symbol, size);
printMatrix(arr, size);
char inputedSymbol = ' ';
std::cout << "Enter any symbol: ";
std::cin >> inputedSymbol;
std::cout << "Count of " << inputedSymbol << " symbol: "
<< countOfInputedCharacter(arr, size, inputedSymbol) << std::endl;
std::cout << "Enter new symbol: ";
std::cin >> inputedSymbol;
replace(arr, size, symbol, inputedSymbol);
printMatrix(arr, size);
deleteMatrix(arr, size);
return 0;
}
|
#ifndef CARTSCREEN_H
#define CARTSCREEN_H
#include <QDialog>
//#include "usertype.h"
#include "productType.h"
namespace Ui {
class cartscreen;
}
class cartscreen : public QDialog
{
Q_OBJECT
public:
explicit cartscreen(QWidget *parent = nullptr);
~cartscreen();
private slots:
void on_pushButton_clicked();
void on_basicAdd_clicked();
void on_basicAdd_2_clicked();
void on_basicAdd_3_clicked();
void on_proAdd_clicked();
void on_proAdd_2_clicked();
void on_proAdd_3_clicked();
void on_premiiumAdd_clicked();
void on_premiiumAdd_2_clicked();
void on_premiiumAdd_3_clicked();
private:
Ui::cartscreen *ui;
};
#endif // CARTSCREEN_H
|
#include <iostream>
#include "Networking/Auth/SG_AuthServer.h"
#include "Networking/MMO/SG_MmoServer.h"
#include "Networking/Lobby/SG_LobbyServer.h"
#include "Networking/Relay/SG_RelayServer.h"
#include "Networking/Message/SG_MessageServer.h"
#include "Tools/Database/Database.h"
#include "Tools/SG_Logger.h"
#include "SG_Config.h"
#include <boost/smart_ptr/shared_ptr.hpp>
int main(int argc, char *argv[])
{
std::string confpath = "SG_Config.ini";
if (argc < 2) {
//std::cerr << "Usage: " << argv[0] << " <Config path>" << std::endl;
//return 1;
}else
{
confpath = argv[1];
}
int option;
std::cout << "Please select the Server" << std::endl;
std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
std::cout << "1. Auth" << std::endl;
std::cout << "2. MMO" << std::endl;
std::cout << "3. Lobby" << std::endl;
std::cout << "4. Relay" << std::endl;
std::cout << "5. Message" << std::endl;
std::cout << "99. All in one" << std::endl;
std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
std::cout << ">> ";
#ifdef _WIN32
if (IsDebuggerPresent()) //IsDebuggerPresent() isn't available on linux
{
option = 99;
}
else
{
std::cin >> option;
}
std::system("cls"); // For Windows
std::system("title Street Gears Emulator 1.0.2");
#else
std::cin >> option;
std::system("clear"); //For Linux, Mac, Whatever
#endif
boost::shared_ptr<SG_AuthServer> pAuth(new SG_AuthServer());
boost::shared_ptr<SG_MmoServer> pMMO(new SG_MmoServer());
boost::shared_ptr<SG_LobbyServer> pLobby(new SG_LobbyServer());
boost::shared_ptr<SG_RelayServer> pRelay(new SG_RelayServer());
boost::shared_ptr<SG_MessageServer> pMessage(new SG_MessageServer());
boost::shared_ptr<MySQLConnection> pDatabase(new MySQLConnection());
boost::shared_ptr<SG_Config> conf(new SG_Config());
conf->init(confpath);
pDatabase->Connect(conf->host, conf->port, conf->DBUser, conf->DBPass, conf->DBName);
SG_ClientSession::SQLConn = pDatabase.get();
SG_ClientSession::conf = conf.get();
switch(option)
{
case 1:
pAuth->InitServer(conf->AuthIP, conf->AuthPort, 1);
SG_Logger::instance().log("Auth Server started", SG_Logger::kLogLevelInfo);
break;
case 2:
pMMO->InitServer(conf->MMOIP, conf->MMOPort, 1);
SG_Logger::instance().log("MMO Server started", SG_Logger::kLogLevelInfo);
break;
case 3:
pLobby->InitServer(conf->LobbyIP, conf->LobbyPort, 1);
SG_Logger::instance().log("Lobby Server started", SG_Logger::kLogLevelInfo);
break;
case 4:
pRelay->InitServer(conf->relayIP, conf->RelayPort, 1);
SG_Logger::instance().log("Relay Server started", SG_Logger::kLogLevelInfo);
break;
case 5:
pMessage->InitServer(conf->msgIP, conf->MsgPort, 1);
SG_Logger::instance().log("Message Server started", SG_Logger::kLogLevelInfo);
break;
case 99:
pAuth->InitServer(conf->AuthIP, conf->AuthPort, 1);
SG_Logger::instance().log("Auth Server started", SG_Logger::kLogLevelInfo);
pMMO->InitServer(conf->MMOIP, conf->MMOPort, 1);
SG_Logger::instance().log("MMO Server started", SG_Logger::kLogLevelInfo);
pLobby->InitServer(conf->LobbyIP, conf->LobbyPort, 1);
SG_Logger::instance().log("Lobby Server started", SG_Logger::kLogLevelInfo);
pRelay->InitServer(conf->relayIP, conf->RelayPort, 1);
SG_Logger::instance().log("Relay Server started", SG_Logger::kLogLevelInfo);
pMessage->InitServer(conf->msgIP, conf->MsgPort, 1);
SG_Logger::instance().log("Message Server started", SG_Logger::kLogLevelInfo);
break;
default:
std::cout << std::endl << "INVALID NUMBER" << std::endl;
break;
}
while(1)
{
std::cin.get();
#ifdef _WIN32
system("cls");
#else
//system("clear");
#endif
}
}
|
/*!
* \file mpostdialog.cpp
* \author Simon Coakley
* \date 2012
* \copyright Copyright (c) 2012 University of Sheffield
* \brief Implementation of mpost dialog
*/
#include <QtGui>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "./mpostdialog.h"
MpostDialog::MpostDialog(MemoryModel * m, QWidget *parent)
: QDialog(parent) {
// qDebug() << "MpreDialog";
memory = m;
lhsGroup = new QGroupBox(tr("LHS"));
rhsGroup = new QGroupBox(tr("RHS"));
opGroup = new QGroupBox(tr("OP"));
myEnabled = new QCheckBox(tr("Enabled"));
connect(myEnabled, SIGNAL(clicked(bool)), lhsGroup, SLOT(setEnabled(bool)));
connect(myEnabled, SIGNAL(clicked(bool)), rhsGroup, SLOT(setEnabled(bool)));
connect(myEnabled, SIGNAL(clicked(bool)), opGroup, SLOT(setEnabled(bool)));
variable = new QComboBox();
variable2 = new QComboBox();
value = new QSpinBox();
op = new QComboBox();
value2 = new QSpinBox();
operators << "=" << "+=" << "-=" << "*=" << "/=";
op->addItems(operators);
variable->addItems(memory->getNames());
variable2->addItems(memory->getNames());
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok);
connect(this, SIGNAL(setVariableComboBox(int)),
variable, SLOT(setCurrentIndex(int)));
connect(this, SIGNAL(setVariable2ComboBox(int)),
variable2, SLOT(setCurrentIndex(int)));
connect(this, SIGNAL(setOpComboBox(int)), op, SLOT(setCurrentIndex(int)));
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
QVBoxLayout *lhsLayout = new QVBoxLayout;
lhsLayout->addWidget(variable);
lhsGroup->setLayout(lhsLayout);
QVBoxLayout *rhsLayout = new QVBoxLayout;
// rhsLayout->addWidget(value);
rhsLayout->addWidget(variable2);
rhsGroup->setLayout(rhsLayout);
QHBoxLayout *opLayout = new QHBoxLayout;
opLayout->addWidget(op);
opGroup->setLayout(opLayout);
QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->addWidget(myEnabled);
mainLayout->addWidget(lhsGroup);
mainLayout->addWidget(opGroup);
mainLayout->addWidget(rhsGroup);
mainLayout->addWidget(buttonBox);
setLayout(mainLayout);
setWindowTitle(tr("Mpost Editor"));
}
void MpostDialog::setMpost(Mpost m) {
mpost = m;
myEnabled->setChecked(mpost.enabled());
lhsGroup->setEnabled(mpost.enabled());
opGroup->setEnabled(mpost.enabled());
rhsGroup->setEnabled(mpost.enabled());
value->setValue(mpost.value());
// value2->setValue(mpost.value2());
int index = memory->getNames().indexOf(mpost.name());
if (index == -1) index = 0;
emit(setVariableComboBox(index));
index = operators.indexOf(mpost.op());
if (index == -1) index = 0;
emit(setOpComboBox(index));
index = memory->getNames().indexOf(mpost.name2());
if (index == -1) index = 0;
emit(setVariable2ComboBox(index));
}
Mpost MpostDialog::getMpost() {
mpost.setEnabled(myEnabled->isChecked());
mpost.setValue(value->value());
mpost.setName(variable->currentText());
mpost.setOp(op->currentText());
// mpost.setValue2(value2->value());
mpost.setName2(variable2->currentText());
return mpost;
}
|
#include <iostream>
using namespace std;
int mabs(int x){
if(x < 0) return -x;
return x;
}
int find(int x, int *a, int n){
int l = 0;
int r = n - 1;
int m;
while(l < r){
m = (l + r) / 2;
if(x > a[m]) l = m + 1;
else r = m;
}
int d1 = mabs(x - a[m]);
int d2 = mabs(x - a[r]);
int d3 = mabs(x - a[r-1]);
int res;
if(l != m){
if(d1 <= d2) res = a[m];
else res = a[r] ;
}else{
if(d3 <= d2) res = a[r-1];
else res = a[r];
}
return res;
}
int main(){
int n,k,t;
cin >> n >> k;
if(n == 1){
cout << 1/(n-1);
}
int a[n];
for(int i = 0; i < n; ++i){
cin >> a[i];
}
for(int i = 0; i < k; ++i){
cin >> t;
cout << find(t,a,n) << endl;
}
return 0;
}
|
#include<iostream>
#include<algorithm>
#include<cmath>
#include<climits>
#include<cstdio>
#include<cfloat>
using namespace std;
double EPS = 1.0e-6;
struct point{
double x,y;
point(){}
point(double a, double b){x=a;y=b;}
};
double dist(point p){
return sqrt(p.x*p.x + p.y*p.y);
}
bool hits(double d, point p, point v){
if(abs(v.x*p.y-v.y*p.x)<EPS){
double dp = dist(p);
double dv = dist(v);
double dot = v.x*p.x + v.y*p.y;
double D = d+ 5.0;
if (dot > 0) D=2.0-dp;
else if(dot < 0) D=dp;
if(D<d || abs(D-d)<EPS) return true;
return false;
}
return false;
}
int main(){
double d;
while(cin>>d){
if(!d) break;
double px,py,vx,vy;
cin>>px>>py>>vx>>vy;
if(hits(d, point(px,py),point(vx,vy)))
cout<<"possible\n";
else
cout<<"impossible\n";
}
return 0;
}
|
#include <iostream>
using namespace std;
int main()
{
float x1, x2, x3, y1, y2, y3;
float area;
cout << "Bienvenido a este programa, Creado por Seba20xx\n";
cout << "Digite la primera coordenada de x\n";
cin >> x1;
cout << "Digite la primera coordenada de y\n";
cin >> y1;
cout << "Digite la segunda coordenada de x\n";
cin >> x2;
cout << "Digite la segunda coordenada de y\n";
cin >> y2;
cout << "Digite la tercera coordenada de x\n";
cin >> x3;
cout << "Digite la tercera coordenada de y\n";
cin >> y3;
area = ((x1*y2)+(x2*y3)+(x3*y1)-(x1*y3)-(x2*y1)-(x3*y2))/2;
cout << "El area es " << area << endl;
return 0;
}
|
const int pinLed = 9;
const int pinBoton = 3;
const int pinEjeY = A1;
const int pinEjeX = A0;
int estadoBoton =0;
void setup() {
pinMode(pinBoton, INPUT);
digitalWrite(pinBoton, HIGH);
Serial.begin(9600);
}
void loop() {
estadoBoton= digitalRead(pinBoton);
Serial.println(estadoBoton);
if (estadoBoton == LOW){
digitalWrite(pinLed, HIGH);
}
else{
digitalWrite(pinLed, LOW);
}
}
|
#pragma once
#include <iostream>
#include <vector>
#include<list>
#include <math.h>
struct Vector2
{
Vector2() : x(0), y(0){}
Vector2(float X, float Y) : x(X), y(Y) {}
float x;
float y;
float Magnitude()
{
return sqrt(x * x + y * y);
}
};
struct Edge;
namespace Pathfinding
{
struct Node
{
Node() {}
~Node() {}
// User defined data attached to each node.
Vector2 position;
float gScore;
float hScore;
float fScore;
Node* parent;
std::vector< Edge > connections;
bool operator <(Node* node)
{
if (node->fScore > fScore)
{
return true;
}
return false;
}
};
}
struct Edge
{
Pathfinding::Node* target;
float cost;
};
float Heuristic(Pathfinding::Node* _target, Pathfinding::Node* _endNode)
{
Vector2 heuristic(_endNode->position.x - _target->position.x, _endNode->position.y - _target->position.y);
return heuristic.Magnitude();
}
std::list<Pathfinding::Node*> dijkstrasSearch(Pathfinding::Node* startNode, Pathfinding::Node* endNode)
{
using namespace Pathfinding;
// Validate the input
if (startNode == NULL || endNode == NULL)
{
std::cout << "ERROR: NULL INPUTS";
std::runtime_error;
}
if (startNode == endNode)
{
std::cout << "ERROR: LIST HAS LENGTH OF ONE";
std::runtime_error;
}
// Initialise the starting node
startNode->gScore = 0;
startNode->parent = NULL;
// Create our temporary lists for storing nodes we’re visiting/visited
std::list<Node*> openList;
std::list<Node*> closedList;
openList.push_back(startNode);
Node* currentNode;
while (openList.size() != 0)
{
openList.sort(); //sort by fScore
currentNode = openList.front();
// If we visit the endNode, then we can exit early.
// Sorting the openList guarantees the shortest path is found,
// given no negative costs (a prerequisite of the algorithm).
if (currentNode == endNode)
{
break;
}
openList.remove(currentNode);
closedList.push_back(currentNode);
float gScore = 0;
float hScore = 0;
float fScore = 0;
bool nodeFoundCL = false; //CL stands for closed list
bool nodeFoundOL = false; //OL stands for openList
for (Edge c : currentNode->connections)
{
for (Node* node : closedList)//is this target in the closedList
{
if (node == c.target)
{
nodeFoundCL == true; //yes it was found
}
}
if (!nodeFoundCL)
{
gScore = currentNode->gScore + c.cost;
hScore = Heuristic(c.target, endNode);
fScore = gScore + hScore;
// Have not yet visited the node.
// So calculate the Score and update its parent.
// Also add it to the openList for processing.
for (Node* node : openList)//is this target in the openList
{
if (node == c.target)
{
nodeFoundOL = true; //yes it was found
}
}
if (!nodeFoundOL)
{
c.target->gScore = gScore;
c.target->fScore = fScore;
c.target->parent = currentNode;
openList.push_back(c.target);
}
// Node is already in the openList with a valid Score.
// So compare the calculated Score with the existing
// to find the shorter path.
else if (fScore < c.target->fScore)
{
c.target->gScore = gScore;
c.target->fScore = fScore;
c.target->parent = currentNode;
}
}
}
}
// Create Path in reverse from endNode to startNode
std::list<Node*> path;
currentNode = endNode;
while (currentNode != NULL)
{
path.push_front(currentNode);
currentNode = currentNode->parent;
}
// Return the path for navigation between startNode/endNode
return path;
}
|
// Copyright 2012 Yandex
#ifndef LTR_LEARNERS_DECISION_TREE_DECISION_TREE_H_
#define LTR_LEARNERS_DECISION_TREE_DECISION_TREE_H_
#include <map>
#include <cmath>
#include <string>
#include <vector>
#include <stdexcept>
#include "boost/weak_ptr.hpp"
#include "logog/logog.h"
#include "ltr/learners/decision_tree/condition.h"
#include "ltr/utility/shared_ptr.h"
using std::map;
using std::string;
using std::vector;
namespace ltr {
namespace decision_tree {
template <class TValue>
/**
* Vertex is a node in the decision tree. It has a condition, leading in it.
* Condition is a functor, which returns probability for object
* to be decided by this vertex.
* It can have children.
*/
class Vertex : public SerializableFunctor<TValue> {
public:
typedef ltr::utility::shared_ptr<Vertex> Ptr;
typedef boost::weak_ptr<Vertex> WeakPtr;
Vertex() : parent_(0) {}
/**
* This constructor creates a vertex with a condition leading in it.
* @param condition - condition leading in the vertex
*/
explicit Vertex(Condition::Ptr condition)
: condition_(condition),
parent_(0) {}
virtual ~Vertex() {}
/**
* Adds child to the vertex.
* @param child - child to add.
*/
void addChild(Ptr child);
/**
* Returns true, if vertex has a next sibling vertex.
*/
bool hasNextSibling() const;
/**
* Returns true, if vertex has a child.
*/
bool hasChild() const;
/**
* Returns a pointer to its sibling vertex.
*/
Ptr nextSibling() const;
/**
* Returns a pointer to the first child of this vertex.
*/
Ptr firstChild() const;
/**
* Removes child from this vertex.
* @param child - child to remove.
*/
void removeChild(Ptr child);
/**
* Sets a condition leading to this vertex.
* @param condition - condition to set.
*/
void setCondition(Condition::Ptr condition) {condition_ = condition;}
/**
* Returns a condition, leading to the vertex.
*/
Condition::Ptr condition() {return condition_;}
protected:
Ptr first_child_;
Ptr last_child_;
Ptr sibling_;
Vertex<TValue>* parent_;
Condition::Ptr condition_;
};
template<class TValue>
void Vertex<TValue>::removeChild(typename Vertex<TValue>::Ptr child) {
INFO("Removing a child of vertex.");
if (first_child_ == child) {
INFO("first child of vertex is equal to removable child.");
first_child_ = first_child_->nextSibling();
if (first_child_ == NULL)
last_child_ = NULL;
return;
}
typename Vertex<TValue>::Ptr now = first_child_;
while (now != NULL) {
INFO("current child doesn't match with the removable child.")
if (now->nextSibling() == child) {
now->sibling_ = now->nextSibling()->nextSibling();
child->parent_ = NULL;
return;
}
now = now->nextSibling();
}
}
template<class TValue>
bool Vertex<TValue>::hasNextSibling() const {
return (sibling_ != NULL);
}
template<class TValue>
bool Vertex<TValue>::hasChild() const {
return (first_child_ != NULL);
}
template<class TValue>
typename Vertex<TValue>::Ptr Vertex<TValue>::nextSibling() const {
return sibling_;
}
template<class TValue>
typename Vertex<TValue>::Ptr Vertex<TValue>::firstChild() const {
return first_child_;
}
template<class TValue>
void Vertex<TValue>::addChild(typename Vertex<TValue>::Ptr child) {
if (last_child_ == NULL) {
INFO("Last child of vertex is NULL");
first_child_ = last_child_ = child;
} else {
INFO("Last child of vertex is not NULL");
last_child_ = last_child_->sibling_ = child;
}
child->parent_ = this;
}
/**
* Decision tree. It contains a pointer to the root Vertex.
*/
template<class TValue>
class DecisionTree : public SerializableFunctor<TValue> {
public:
typedef typename Vertex<TValue>::Ptr VertexPtr;
/**
* Returns the decision of the tree for the given object.
* @param object - object to decide.
*/
TValue value(const Object& object) const;
/**
* Sets the root vertex.
* @param root - new root of the tree.
*/
void setRoot(VertexPtr root);
/**
* Removes vertex out of the tree.
* @param vertex - vertex to remove.
*/
void removeVertex(VertexPtr vertex);
string generateCppCode(const string& function_name) const;
private:
virtual string getDefaultAlias() const;
VertexPtr root_;
};
template<class TValue>
TValue DecisionTree<TValue>::value(const Object& object) const {
return root_->value(object);
}
template<class TValue>
void DecisionTree<TValue>::setRoot(typename Vertex<TValue>::Ptr root) {
root_ = root;
}
template<class TValue>
void DecisionTree<TValue>::removeVertex(typename Vertex<TValue>::Ptr vertex) {
typename Vertex<TValue>::Ptr v = vertex;
while (v != NULL) {
v = v->parent_;
}
if (v != this->root) {
INFO("Vertex is from another tree.");
throw std::logic_error("can't remove vertex: vertex from another tree");
}
if (vertex == this->root) {
INFO("Vertex is from current tree.");
this->root = typename Vertex<TValue>::Ptr(NULL);
return;
}
vertex->parent_->removeChild(vertex);
}
template<class TValue>
string DecisionTree<TValue>::generateCppCode(
const string& function_name) const {
return root_->generateCppCode(function_name);
}
template<class TValue>
string DecisionTree<TValue>::getDefaultAlias() const {
return "Decision Tree";
}
};
};
#endif // LTR_LEARNERS_DECISION_TREE_DECISION_TREE_H_
|
#pragma once
#include "Render/DrawBasic/BufferLayout.h"
namespace Rocket
{
Interface VertexBuffer
{
public:
virtual ~VertexBuffer() = default;
virtual void Bind() const = 0;
virtual void Unbind() const = 0;
virtual void SetData(const void* data, uint32_t size) = 0;
virtual const BufferLayout& GetLayout() const = 0;
virtual void SetLayout(const BufferLayout& layout) = 0;
};
}
|
/****************************************************************************
** Meta object code from reading C++ file 'newdvrnvrdialog.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/newdvrnvrdialog.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'newdvrnvrdialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.8.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_NewDVRNVRDialog_t {
QByteArrayData data[11];
char stringdata0[134];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_NewDVRNVRDialog_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_NewDVRNVRDialog_t qt_meta_stringdata_NewDVRNVRDialog = {
{
QT_MOC_LITERAL(0, 0, 15), // "NewDVRNVRDialog"
QT_MOC_LITERAL(1, 16, 9), // "newDVRNVR"
QT_MOC_LITERAL(2, 26, 0), // ""
QT_MOC_LITERAL(3, 27, 9), // "DhDevice*"
QT_MOC_LITERAL(4, 37, 10), // "new_dvrnvr"
QT_MOC_LITERAL(5, 48, 6), // "Group*"
QT_MOC_LITERAL(6, 55, 1), // "g"
QT_MOC_LITERAL(7, 57, 11), // "savetomongo"
QT_MOC_LITERAL(8, 69, 17), // "on_accept_clicked"
QT_MOC_LITERAL(9, 87, 17), // "on_cancel_clicked"
QT_MOC_LITERAL(10, 105, 28) // "on_connect_to_device_clicked"
},
"NewDVRNVRDialog\0newDVRNVR\0\0DhDevice*\0"
"new_dvrnvr\0Group*\0g\0savetomongo\0"
"on_accept_clicked\0on_cancel_clicked\0"
"on_connect_to_device_clicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_NewDVRNVRDialog[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
4, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 3, 34, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
8, 0, 41, 2, 0x08 /* Private */,
9, 0, 42, 2, 0x08 /* Private */,
10, 0, 43, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, 0x80000000 | 3, 0x80000000 | 5, QMetaType::Bool, 4, 6, 7,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void NewDVRNVRDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
NewDVRNVRDialog *_t = static_cast<NewDVRNVRDialog *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->newDVRNVR((*reinterpret_cast< DhDevice*(*)>(_a[1])),(*reinterpret_cast< Group*(*)>(_a[2])),(*reinterpret_cast< bool(*)>(_a[3]))); break;
case 1: _t->on_accept_clicked(); break;
case 2: _t->on_cancel_clicked(); break;
case 3: _t->on_connect_to_device_clicked(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (NewDVRNVRDialog::*_t)(DhDevice * , Group * , bool );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&NewDVRNVRDialog::newDVRNVR)) {
*result = 0;
return;
}
}
}
}
const QMetaObject NewDVRNVRDialog::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_NewDVRNVRDialog.data,
qt_meta_data_NewDVRNVRDialog, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *NewDVRNVRDialog::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *NewDVRNVRDialog::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_NewDVRNVRDialog.stringdata0))
return static_cast<void*>(const_cast< NewDVRNVRDialog*>(this));
return QDialog::qt_metacast(_clname);
}
int NewDVRNVRDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 4)
qt_static_metacall(this, _c, _id, _a);
_id -= 4;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 4)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 4;
}
return _id;
}
// SIGNAL 0
void NewDVRNVRDialog::newDVRNVR(DhDevice * _t1, Group * _t2, bool _t3)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
// internal
#include "render_system.hpp"
#include <array>
#include <fstream>
#include "../ext/stb_image/stb_image.h"
// This creates circular header inclusion, that is quite bad.
#include "tiny_ecs_registry.hpp"
// stlib
#include <iostream>
#include <sstream>
// World initialization
bool RenderSystem::init(int width, int height, GLFWwindow* window_arg)
{
this->window = window_arg;
glfwMakeContextCurrent(window);
glfwSwapInterval(1); // vsync
// Load OpenGL function pointers
const int is_fine = gl3w_init();
assert(is_fine == 0);
// Create a frame buffer
frame_buffer = 0;
glGenFramebuffers(1, &frame_buffer);
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer);
gl_has_errors();
// int fb_width, fb_height;
// glfwGetFramebufferSize(window, &fb_width, &fb_height);
// screen_scale = static_cast<float>(fb_width) / width;
// (int)height; // dummy to avoid warning
int frame_buffer_width_px, frame_buffer_height_px;
glfwGetFramebufferSize(window, &frame_buffer_width_px, &frame_buffer_height_px); // Note, this will be 2x the resolution given to glfwCreateWindow on retina displays
if (frame_buffer_width_px != window_width_px)
{
printf("WARNING: retina display! https://stackoverflow.com/questions/36672935/why-retina-screen-coordinate-value-is-twice-the-value-of-pixel-value\n");
printf("glfwGetFramebufferSize = %d,%d\n", frame_buffer_width_px, frame_buffer_height_px);
printf("window width_height = %d,%d\n", window_width_px, window_height_px);
}
// We are not really using VAO's but without at least one bound we will crash in
// some systems.
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
gl_has_errors();
initScreenTexture();
initializeGlTextures();
initializeGlEffects();
initializeGlGeometryBuffers();
return true;
}
void RenderSystem::initializeGlTextures()
{
glGenTextures((GLsizei)texture_gl_handles.size(), texture_gl_handles.data());
for(uint i = 0; i < texture_paths.size(); i++)
{
const std::string& path = texture_paths[i];
ivec2& dimensions = texture_dimensions[i];
stbi_uc* data;
data = stbi_load(path.c_str(), &dimensions.x, &dimensions.y, NULL, 4);
if (data == NULL)
{
const std::string message = "Could not load the file " + path + ".";
fprintf(stderr, "%s", message.c_str());
assert(false);
}
glBindTexture(GL_TEXTURE_2D, texture_gl_handles[i]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, dimensions.x, dimensions.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
gl_has_errors();
stbi_image_free(data);
}
gl_has_errors();
}
void RenderSystem::initializeGlEffects()
{
for(uint i = 0; i < effect_paths.size(); i++)
{
const std::string vertex_shader_name = effect_paths[i] + ".vs.glsl";
const std::string fragment_shader_name = effect_paths[i] + ".fs.glsl";
bool is_valid = loadEffectFromFile(vertex_shader_name, fragment_shader_name, effects[i]);
assert(is_valid && (GLuint)effects[i] != 0);
}
}
// One could merge the following two functions as a template function...
template <class T>
void RenderSystem::bindVBOandIBO(GEOMETRY_BUFFER_ID gid, std::vector<T> vertices, std::vector<uint16_t> indices)
{
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffers[(uint)gid]);
glBufferData(GL_ARRAY_BUFFER,
sizeof(vertices[0]) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
gl_has_errors();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffers[(uint)gid]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(indices[0]) * indices.size(), indices.data(), GL_STATIC_DRAW);
gl_has_errors();
}
void RenderSystem::initializeGlMeshes()
{
for (uint i = 0; i < mesh_paths.size(); i++)
{
// Initialize meshes
GEOMETRY_BUFFER_ID geom_index = mesh_paths[i].first;
std::string name = mesh_paths[i].second;
Mesh::loadFromOBJFile(name,
meshes[(int)geom_index].vertices,
meshes[(int)geom_index].vertex_indices,
meshes[(int)geom_index].original_size);
bindVBOandIBO(geom_index,
meshes[(int)geom_index].vertices,
meshes[(int)geom_index].vertex_indices);
}
}
void RenderSystem::initializeGlGeometryBuffers()
{
// Vertex Buffer creation.
glGenBuffers((GLsizei)vertex_buffers.size(), vertex_buffers.data());
// Index Buffer creation.
glGenBuffers((GLsizei)index_buffers.size(), index_buffers.data());
// Index and Vertex buffer data initialization.
initializeGlMeshes();
//////////////////////////
// Initialize sprite
// The position corresponds to the center of the texture.
std::vector<TexturedVertex> textured_vertices(4);
textured_vertices[0].position = { -1.f/2, +1.f/2, 0.f };
textured_vertices[1].position = { +1.f/2, +1.f/2, 0.f };
textured_vertices[2].position = { +1.f/2, -1.f/2, 0.f };
textured_vertices[3].position = { -1.f/2, -1.f/2, 0.f };
textured_vertices[0].texcoord = { 0.f, 1.f };
textured_vertices[1].texcoord = { 1.f, 1.f };
textured_vertices[2].texcoord = { 1.f, 0.f };
textured_vertices[3].texcoord = { 0.f, 0.f };
// Counterclockwise as it's the default opengl front winding direction.
const std::vector<uint16_t> textured_indices = { 0, 3, 1, 1, 3, 2 };
bindVBOandIBO(GEOMETRY_BUFFER_ID::SPRITE, textured_vertices, textured_indices);
////////////////////////
// Initialize pebble
// std::vector<ColoredVertex> pebble_vertices;
// std::vector<uint16_t> pebble_indices;
// constexpr float z = -0.1f;
// constexpr int NUM_TRIANGLES = 62;
//
// for (int i = 0; i < NUM_TRIANGLES; i++) {
// const float t = float(i) * M_PI * 2.f / float(NUM_TRIANGLES - 1);
// pebble_vertices.push_back({});
// pebble_vertices.back().position = { 0.5 * cos(t), 0.5 * sin(t), z };
// pebble_vertices.back().color = { 0.8, 0.8, 0.8 };
// }
// pebble_vertices.push_back({});
// pebble_vertices.back().position = { 0, 0, 0 };
// pebble_vertices.back().color = { 0.8, 0.8, 0.8 };
// for (int i = 0; i < NUM_TRIANGLES; i++) {
// pebble_indices.push_back((uint16_t)i);
// pebble_indices.push_back((uint16_t)((i + 1) % NUM_TRIANGLES));
// pebble_indices.push_back((uint16_t)NUM_TRIANGLES);
// }
// int geom_index = (int)GEOMETRY_BUFFER_ID::PEBBLE;
// meshes[geom_index].vertices = pebble_vertices;
// meshes[geom_index].vertex_indices = pebble_indices;
// bindVBOandIBO(GEOMETRY_BUFFER_ID::PEBBLE, meshes[geom_index].vertices, meshes[geom_index].vertex_indices);
//////////////////////////////////
// Initialize debug line
std::vector<ColoredVertex> line_vertices;
std::vector<uint16_t> line_indices;
constexpr float depth = 0.5f;
constexpr vec3 red = { 0.8,0.1,0.1 };
// Corner points
line_vertices = {
{{-0.5,-0.5, depth}, red},
{{-0.5, 0.5, depth}, red},
{{ 0.5, 0.5, depth}, red},
{{ 0.5,-0.5, depth}, red},
};
// Two triangles
line_indices = {0, 1, 3, 1, 2, 3};
int geom_index = (int)GEOMETRY_BUFFER_ID::DEBUG_LINE;
meshes[geom_index].vertices = line_vertices;
meshes[geom_index].vertex_indices = line_indices;
bindVBOandIBO(GEOMETRY_BUFFER_ID::DEBUG_LINE, line_vertices, line_indices);
///////////////////////////////////////////////////////
// Initialize screen triangle (yes, triangle, not quad; its more efficient).
std::vector<vec3> screen_vertices(3);
screen_vertices[0] = { -1, -6, 0.f };
screen_vertices[1] = { 6, -1, 0.f };
screen_vertices[2] = { -1, 6, 0.f };
// Counterclockwise as it's the default opengl front winding direction.
const std::vector<uint16_t> screen_indices = { 0, 1, 2 };
bindVBOandIBO(GEOMETRY_BUFFER_ID::SCREEN_TRIANGLE, screen_vertices, screen_indices);
// geometry buffer for help screen
std::vector<TexturedVertex> help_screen_vertices(4);
help_screen_vertices[0].position = { -1.f/2, +1.f/4, 0.f };
help_screen_vertices[1].position = { +1.f/2, +1.f/4, 0.f };
help_screen_vertices[2].position = { +1.f/2, -1.f/4, 0.f };
help_screen_vertices[3].position = { -1.f/2, -1.f/4, 0.f };
help_screen_vertices[0].texcoord = { 0.f, 1.f };
help_screen_vertices[1].texcoord = { 1.f, 1.f };
help_screen_vertices[2].texcoord = { 1.f, 0.f };
help_screen_vertices[3].texcoord = { 0.f, 0.f };
// Counterclockwise as it's the default opengl front winding direction.
const std::vector<uint16_t> help_screen_indices = { 0, 3, 1, 1, 3, 2 };
bindVBOandIBO(GEOMETRY_BUFFER_ID::HELP_SCREEN, help_screen_vertices, help_screen_indices);
std::vector<TexturedVertex> animation_vertices(4);
// Assumes max 4 frames per row and max 4 types per column
const float ANIM_FRAME_WIDTH = 0.25;
const float ANIM_FRAME_HEIGHT = 0.25;
animation_vertices[0].position = { -1.f / 2, +1.f / 2, 0.f };
animation_vertices[1].position = { +1.f / 2, +1.f / 2, 0.f };
animation_vertices[2].position = { +1.f / 2, -1.f / 2, 0.f };
animation_vertices[3].position = { -1.f / 2, -1.f / 2, 0.f };
animation_vertices[3].texcoord = { 0, 0 };
animation_vertices[2].texcoord = { ANIM_FRAME_WIDTH, 0 };
animation_vertices[1].texcoord = { ANIM_FRAME_WIDTH, ANIM_FRAME_HEIGHT };
animation_vertices[0].texcoord = { 0, ANIM_FRAME_HEIGHT };
const std::vector<uint16_t> animation_indices = { 0, 3, 1, 1, 3, 2 };
bindVBOandIBO(GEOMETRY_BUFFER_ID::SPRITE_ANIMATION, animation_vertices, animation_indices);
}
RenderSystem::~RenderSystem()
{
// Don't need to free gl resources since they last for as long as the program,
// but it's polite to clean after yourself.
glDeleteBuffers((GLsizei)vertex_buffers.size(), vertex_buffers.data());
glDeleteBuffers((GLsizei)index_buffers.size(), index_buffers.data());
glDeleteTextures((GLsizei)texture_gl_handles.size(), texture_gl_handles.data());
glDeleteTextures(1, &off_screen_render_buffer_color);
glDeleteRenderbuffers(1, &off_screen_render_buffer_depth);
gl_has_errors();
for(uint i = 0; i < effect_count; i++) {
glDeleteProgram(effects[i]);
}
// delete allocated resources
glDeleteFramebuffers(1, &frame_buffer);
gl_has_errors();
// remove all entities created by the render system
while (registry.renderRequests.entities.size() > 0)
registry.remove_all_components_of(registry.renderRequests.entities.back());
}
// Initialize the screen texture from a standard sprite
bool RenderSystem::initScreenTexture()
{
// registry.screenStates.emplace(screen_state_entity);
int width, height;
glfwGetFramebufferSize(const_cast<GLFWwindow*>(window), &width, &height);
glGenTextures(1, &off_screen_render_buffer_color);
glBindTexture(GL_TEXTURE_2D, off_screen_render_buffer_color);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
gl_has_errors();
glGenRenderbuffers(1, &off_screen_render_buffer_depth);
glBindRenderbuffer(GL_RENDERBUFFER, off_screen_render_buffer_depth);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, off_screen_render_buffer_color, 0);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, off_screen_render_buffer_depth);
gl_has_errors();
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
return true;
}
bool gl_compile_shader(GLuint shader)
{
glCompileShader(shader);
gl_has_errors();
GLint success = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (success == GL_FALSE)
{
GLint log_len;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_len);
std::vector<char> log(log_len);
glGetShaderInfoLog(shader, log_len, &log_len, log.data());
glDeleteShader(shader);
gl_has_errors();
fprintf(stderr, "GLSL: %s", log.data());
return false;
}
return true;
}
bool loadEffectFromFile(
const std::string& vs_path, const std::string& fs_path, GLuint& out_program)
{
// Opening files
std::ifstream vs_is(vs_path);
std::ifstream fs_is(fs_path);
if (!vs_is.good() || !fs_is.good())
{
fprintf(stderr, "Failed to load shader files %s, %s", vs_path.c_str(), fs_path.c_str());
assert(false);
return false;
}
// Reading sources
std::stringstream vs_ss, fs_ss;
vs_ss << vs_is.rdbuf();
fs_ss << fs_is.rdbuf();
std::string vs_str = vs_ss.str();
std::string fs_str = fs_ss.str();
const char* vs_src = vs_str.c_str();
const char* fs_src = fs_str.c_str();
GLsizei vs_len = (GLsizei)vs_str.size();
GLsizei fs_len = (GLsizei)fs_str.size();
GLuint vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vs_src, &vs_len);
GLuint fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fs_src, &fs_len);
gl_has_errors();
// Compiling
if (!gl_compile_shader(vertex))
{
fprintf(stderr, "Vertex compilation failed");
assert(false);
return false;
}
if (!gl_compile_shader(fragment))
{
fprintf(stderr, "Vertex compilation failed");
assert(false);
return false;
}
// Linking
out_program = glCreateProgram();
glAttachShader(out_program, vertex);
glAttachShader(out_program, fragment);
glLinkProgram(out_program);
gl_has_errors();
{
GLint is_linked = GL_FALSE;
glGetProgramiv(out_program, GL_LINK_STATUS, &is_linked);
if (is_linked == GL_FALSE)
{
GLint log_len;
glGetProgramiv(out_program, GL_INFO_LOG_LENGTH, &log_len);
std::vector<char> log(log_len);
glGetProgramInfoLog(out_program, log_len, &log_len, log.data());
gl_has_errors();
fprintf(stderr, "Link error: %s", log.data());
assert(false);
return false;
}
}
// No need to carry this around. Keeping these objects is only useful if we recycle
// the same shaders over and over, which we don't, so no need and this is simpler.
glDetachShader(out_program, vertex);
glDetachShader(out_program, fragment);
glDeleteShader(vertex);
glDeleteShader(fragment);
gl_has_errors();
return true;
}
|
#pragma once
template<typename T>
class RangedFunction
{
public:
virtual T Compute(T argument) const = 0;
virtual T GetMinArgument() const = 0;
virtual T GetMaxArgument() const = 0;
virtual ~RangedFunction() = default;
};
|
/*
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
*
* by Dejan Nedelkovski,
* www.HowToMechatronics.com
*
*/
// defines pins numbers
const int sensorOneTrigPin = 6;
const int sensorOneEchoPin = 7;
const int sensorTwoTrigPin = 9;
const int sensorTwoEchoPin = 10;
// defines variables
long durationOne, durationTwo;
int distanceOne, distanceTwo;
void setup() {
pinMode(sensorOneTrigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(sensorOneEchoPin, INPUT); // Sets the echoPin as an Input
pinMode(sensorTwoTrigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(sensorTwoEchoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(sensorOneTrigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(sensorOneTrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(sensorOneTrigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
durationOne = pulseIn(sensorOneEchoPin, HIGH);
// Calculating the distance
distanceOne= durationOne*0.034/2;
// Clears the trigPin
digitalWrite(sensorTwoTrigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(sensorTwoTrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(sensorTwoTrigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
durationTwo = pulseIn(sensorTwoEchoPin, HIGH);
// Calculating the distance
distanceTwo= durationTwo*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Sensor One Distance: ");
Serial.println(distanceOne);
Serial.print("Sensor Two Distance: ");
Serial.println(distanceTwo);
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using PriorityQueue = std::priority_queue<int, std::vector<int>, std::greater<int>>;
int calculateLoopCount(PriorityQueue &queue) {
int count = 0;
while (queue.size() > 1) {
int num = queue.top();
queue.pop();
num += queue.top();
queue.pop();
count += num;
queue.push(num);
}
return count;
}
int main() {
int n_case = 0;
std::cin >> n_case;
while (n_case--) {
int n_input = 0;
std::cin >> n_input;
PriorityQueue queue;
for (int i = 0; i < n_input; ++i) {
int input = 0;
std::cin >> input;
queue.push(input);
}
std::cout << calculateLoopCount(queue) << std::endl;
}
return 0;
}
|
#pragma once
#include "QsoItem.h"
class Qso;
class DxccCountry;
class Location : public QsoItem
{
public:
Location(Qso* qso);
virtual ~Location();
// Return true if location is valid
// Return false if location is invalid and set error string
bool Validate(const set<string>& validLocations);
void SetDxccCountry(DxccCountry *dxcc) { m_dxccCountry = dxcc; }
DxccCountry *GetDxccCountry() const { return m_dxccCountry; }
private:
Location();
DxccCountry *m_dxccCountry;
};
|
#ifndef __AI_MANAGER_H__
#define __AI_MANAGER_H__
typedef enum {
AITEAM_MARINE,
AITEAM_STROGG,
AITEAM_NUM
} aiTeam_t;
typedef enum {
AITEAMTIMER_ANNOUNCE_TACTICAL, // Tactical change
AITEAMTIMER_ANNOUNCE_SUPPRESSING,
AITEAMTIMER_ANNOUNCE_SUPPRESSED,
AITEAMTIMER_ANNOUNCE_FRIENDLYFIRE, // Shot by a teammate
AITEAMTIMER_ANNOUNCE_ENEMYSTEATH,
AITEAMTIMER_ANNOUNCE_NEWENEMY, // New enemy was aquired
AITEAMTIMER_ANNOUNCE_SNIPER, // Sniper sighted
AITEAMTIMER_ANNOUNCE_CANIHELPYOU, // Player standing in front of a friendly too long
AITEAMTIMER_ANNOUNCE_SIGHT, // First time seeing an enemy
AITEAMTIMER_ACTION_RELAX, // Play relax animation
AITEAMTIMER_ACTION_PEEK, // Play peek animation
AITEAMTIMER_ACTION_TALK, // Able to talk to another person yet?
AITEAMTIMER_MAX
} aiTeamTimer_t;
extern idVec4 aiTeamColor[AITEAM_NUM];
/*
=====================
blockedReach_t
=====================
*/
// cdr: Alternate Routes Bug
typedef struct aiBlocked_s {
idAAS* aas;
idReachability* reach;
int time;
idList< idEntityPtr<idEntity> > blockers;
idList< idVec3 > positions;
} aiBlocked_t;
/*
=====================
aiAvoid_t
=====================
*/
typedef struct aiAvoid_s {
idVec3 origin;
float radius;
int team;
} aiAvoid_t;
/*
===============================================================================
rvAIHelper
===============================================================================
*/
class rvAIHelper : public idEntity {
public:
CLASS_PROTOTYPE( rvAIHelper );
rvAIHelper ( void );
idLinkList<rvAIHelper> helperNode;
void Spawn ( void );
virtual bool IsCombat ( void ) const;
virtual bool ValidateDestination ( const idAI* ent, const idVec3& dest ) const;
idVec3 GetDirection ( const idAI* ent ) const;
protected:
virtual void OnActivate ( bool active );
private:
void Event_Activate ( idEntity *activator );
};
/*
===============================================================================
rvAIManager
===============================================================================
*/
class rvAIManager {
public:
rvAIManager ( void );
~rvAIManager ( void ) {}
/*
===============================================================================
General
===============================================================================
*/
void RunFrame ( void );
void Save ( idSaveGame *savefile ) const;
void Restore ( idRestoreGame *savefile );
void Clear ( void );
bool IsActive ( void );
bool IsSimpleThink ( idAI* ai );
/*
===============================================================================
Navigation
===============================================================================
*/
void UnMarkAllReachBlocked ( void );
void ReMarkAllReachBlocked ( void );
void MarkReachBlocked ( idAAS* aas, idReachability* reach, const idList<idEntity*>& blockers);
bool ValidateDestination ( idAI* ignore, const idVec3& dest, bool skipCurrent = false, idActor* skipActor = NULL ) const;
void AddAvoid ( const idVec3& origin, float range, int team );
/*
===============================================================================
Helpers
===============================================================================
*/
void RegisterHelper ( rvAIHelper* helper );
void UnregisterHelper ( rvAIHelper* helper );
rvAIHelper* FindClosestHelper ( const idVec3& origin );
/*
===============================================================================
Team Management
===============================================================================
*/
void AddTeammate ( idActor* ent );
void RemoveTeammate ( idActor* ent );
idActor* GetAllyTeam ( aiTeam_t team );
idActor* GetEnemyTeam ( aiTeam_t team );
idActor* NearestTeammateToPoint ( idActor* from, idVec3 point, bool nonPlayer = false, float maxRange = 1000.0f, bool checkFOV = false, bool checkLOS = false );
idEntity* NearestTeammateEnemy ( idActor* from, float maxRange=1000.0f, bool checkFOV = false, bool checkLOS = false, idActor** ally = NULL );
bool LocalTeamHasEnemies ( idAI* self, float maxBuddyRange=640.0f, float maxEnemyRange=1024.0f, bool checkPVS=false );
bool ActorIsBehindActor ( idActor* ambusher, idActor* victim );
/*
===============================================================================
Team Timers
===============================================================================
*/
bool CheckTeamTimer ( int team, aiTeamTimer_t timer );
void ClearTeamTimer ( int team, aiTeamTimer_t timer );
void SetTeamTimer ( int team, aiTeamTimer_t timer, int delay );
/*
===============================================================================
Announcements
===============================================================================
*/
void AnnounceKill ( idAI* victim, idEntity* attacker, idEntity* inflictor );
void AnnounceDeath ( idAI* victim, idEntity* attacker );
/*
===============================================================================
Reactions
===============================================================================
*/
void ReactToPlayerAttack ( idPlayer* player, const idVec3 &origOrigin, const idVec3 &origDir );
/*
===============================================================================
Debugging
===============================================================================
*/
idTimer timerFindEnemy;
idTimer timerTactical;
idTimer timerMove;
idTimer timerThink;
int thinkCount;
int simpleThinkCount;
protected:
void UpdateHelpers ( void );
void DebugDraw ( void );
void DebugDrawHelpers ( void );
idList<aiBlocked_t> blockedReaches;
idLinkList<idAI> simpleThink;
idLinkList<rvAIHelper> helpers;
idLinkList<idActor> teams[AITEAM_NUM];
int teamTimers[AITEAM_NUM][AITEAMTIMER_MAX];
idList<aiAvoid_t> avoids;
};
ID_INLINE bool rvAIManager::CheckTeamTimer ( int team, aiTeamTimer_t timer ) {
return gameLocal.time >= teamTimers[team][timer];
}
ID_INLINE void rvAIManager::ClearTeamTimer ( int team, aiTeamTimer_t timer ) {
teamTimers[team][timer] = 0;
}
ID_INLINE void rvAIManager::SetTeamTimer ( int team, aiTeamTimer_t timer, int delay ) {
teamTimers[team][timer] = gameLocal.time + delay;
}
ID_INLINE void rvAIManager::AddAvoid ( const idVec3& origin, float radius, int team ) {
if ( !IsActive ( ) ) {
return;
}
aiAvoid_t& a = avoids.Alloc ( );
a.origin = origin;
a.radius = radius;
a.team = team;
}
extern rvAIManager aiManager;
#endif // __AI_MANAGER_H__
|
// -----------------------------------------------------------------------------
// G4Basic | TrackingAction.h
//
// User run action class.
// -----------------------------------------------------------------------------
#ifndef TRACKING_ACTION_H
#define TRACKING_ACTION_H
#include <G4UserTrackingAction.hh>
class G4Track;
class TrackingAction: public G4UserTrackingAction
{
public:
TrackingAction();
virtual ~TrackingAction();
virtual void PreUserTrackingAction(const G4Track*);
virtual void PostUserTrackingAction(const G4Track*);
};
inline TrackingAction::TrackingAction() {}
inline TrackingAction::~TrackingAction() {}
#endif
|
/** InsanePixels ************************************************************************************/
/* */
/* SOLUTION: InsaneWare */
/* PROJECT: Runtime */
/* FOLDER: Launcher/Windows */
/* FILE: InsaneWareLauncher.cpp */
/* AUTHOR: Fabrizio Giannone (fgiannone@insanepixels.com) */
/* CREATION: 1st november 2018 */
/* NOTES: */
/* */
/************************************************************************************ InsanePixels **/
#include "InsaneWindowsLauncher.h"
/************************************************************************************ InsanePixels **/
INPIX_S32 WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, char *, INPIX_S32 nCmdShow)
{
INPIX_S32 ReturnCode = 0;
return ReturnCode;
}
/************************************************************************************ InsanePixels **/
|
/*!
* \file sortdelegate.cpp
* \author Simon Coakley
* \date 2012
* \copyright Copyright (c) 2012 University of Sheffield
* \brief Implementation of message sort delegate
*/
#include <QtGui>
#include "./sortdelegate.h"
#include "./sortdialog.h"
#include "./messagesort.h"
SortDelegate::SortDelegate(Machine * m, Communication * comm , QObject *parent)
: QItemDelegate(parent) {
machine = m;
communication = comm;
}
void SortDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const {
if (qVariantCanConvert<MessageSort>(index.data())) {
MessageSort sort = qVariantValue<MessageSort>(index.data());
// painter->drawText(option.rect, Comm.toString());
if (option.state & QStyle::State_Selected)
painter->fillRect(option.rect, option.palette.highlight());
/*starRating.paint(painter, option.rect, option.palette,
StarRating::ReadOnly);*/
sort.paint(painter, option.rect, option.palette,
MessageSort::ReadOnly);
} else {
QItemDelegate::paint(painter, option, index);
}
}
QWidget *SortDelegate::createEditor(QWidget */*parent*/,
const QStyleOptionViewItem &/*option*/,
const QModelIndex &index) const {
SortDialog *editor = new SortDialog(machine,
&communication->messageModel->
getMessages()[index.row()].messageType);
connect(editor, SIGNAL(accepted()), this, SLOT(commitAndCloseEditor()));
connect(editor, SIGNAL(rejected()), this, SLOT(commitAndCloseEditor()));
// editor->setParent(windowParent);
editor->setModal(true);
// editor->move(100, 100);
// editor->setWindowFlags(WShowModal);
return editor;
}
void SortDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const {
if (qVariantCanConvert<MessageSort>(index.data())) {
MessageSort sort = qVariantValue<MessageSort>(index.data());
SortDialog *dialog = static_cast<SortDialog*>(editor);
dialog->setSort(sort);
} else {
QItemDelegate::setEditorData(editor, index);
}
}
void SortDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const {
if (qVariantCanConvert<MessageSort>(index.data())) {
SortDialog *dialog = static_cast<SortDialog*>(editor);
model->setData(index, qVariantFromValue(dialog->getSort()));
} else {
QItemDelegate::setModelData(editor, model, index);
}
}
/*void CommDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}*/
void SortDelegate::commitAndCloseEditor() {
SortDialog *editor = qobject_cast<SortDialog *>(sender());
emit commitData(editor);
emit closeEditor(editor);
}
|
#include "position.hpp"
#include <cmath>
position::position(double x, double y, double z)
:
x(x),
y(y),
z(z)
{
}
double position::ETEDist() {
return sqrt(x * x + y * y + z * z);
}
void position::set(double x, double y, double z) {
this->x = x;
this->y = y;
this->z = z;
}
|
// #pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
vector<int> nums{5,-4,5};
vector<int> multipliers{-5};
sort(nums.begin(), nums.end());
sort(multipliers.begin(), multipliers.end());
int l1 = 0;
int r1 = nums.size() - 1;
int l2 = 0;
int r2 = multipliers.size() - 1;
int sum = 0;
while(l1 <= r1 && l2 <= r2) {
if(nums[l1] * multipliers[l2] >= nums[r1] * multipliers[r2]) {
sum += nums[l1]*multipliers[l2];
l1++;l2++;
}
else {
sum += nums[r1]*multipliers[r2];
r1--;r2--;
}
}
cout << sum << " " << endl;
return 0;
}
|
#include "RayTracer.h"
RayTracer::RayTracer() {
}
void RayTracer::createImage() {
cout << "Creating BMP..." << endl;
bmp.createBMP(512, 512, "output");
cout << "Size of BMP: " << bmp.width << " x " << bmp.height << endl;
bmp.setInitialBMPColor(0, 0, 0);
}
void RayTracer::setupCamera() {
cout << "Setting up camera..." << endl;
cam.setAspectRatio(bmp.width, bmp.height);
cam.setFieldOfView(90);
cout << "Camera has " << cam.fieldOfView * (180 / PI) << " degree field of view." << endl;
cam.setCameraOrigin(0, 10, -4);
cam.setCameraPointOfInterest(0, 5, 20);
cam.calculateCameraMatrix();
cam.setThinLensFocalPlaneDistance(12);
cam.setThinLensRadius(1);
cam.setThinLensViewPlaneDistance(1);
}
void RayTracer::setSamples() {
cout << "Initializing samples..." << endl;
sample.setNumberOfSamples(9);
sample.setNumberOfHemisphereSamples(16);
sample.setAmbientAmountToShade(0);
sample.setRoomDepth(5);
cout << "Setting ambient room depth to " << sample.roomDepth << endl;
cout << "Rendering with " << sample.numberOfSamples << " samples per pixel." << endl;
cout << "Rendering with " << sample.numberOfHemisphereSamples << " hemisphere samples per pixel." << endl;
sample.initializeHemisphereSamples();
sample.setE(1);// 2.718281828459 = e, e = 1 = even distribution appearing from the top
}
Material *RayTracer::createPhongMaterial(double ambientCoefficient, double diffuseCoefficient, double specularCoefficient, double phongExponent) {
Material *mat = new Phong;
mat->getAmbientBRDF()->setReflectionCoefficient(ambientCoefficient);
mat->getDiffuseBRDF()->setReflectionCoefficient(diffuseCoefficient);
mat->getSpecularBRDF()->setReflectionCoefficient(specularCoefficient);
mat->getSpecularBRDF()->setPhongExponent(phongExponent);
return mat;
}
Material *RayTracer::createMatteMaterial(double ambientCoefficient, double diffuseCoefficient) {
Material *mat = new Matte;
mat->getAmbientBRDF()->setReflectionCoefficient(ambientCoefficient);
mat->getDiffuseBRDF()->setReflectionCoefficient(diffuseCoefficient);
return mat;
}
void RayTracer::setupLights() {
cout << "Creating lights..." << endl;
createAmbientLight(ambientLight, 1, 1, 1, 1);
//createAreaPointLight(pointLights, 1.5, 4, 1, 1, 1, 2, 12, 10, 2.5);
createRectangleAreaLight(rectangleAreaLights, 0, 15, 10, 3, 3, 36, 0, 1, 1, 1, 0, -1, 0, 4);
}
void RayTracer::createRectangleAreaLight(vector<Light*> &light, double originx, double originy, double originz, double width, double height, int samplePointWidth, double degreeRotation, double r, double g, double b, double x, double y, double z, double i) {
light.push_back(new RectangleAreaLight);
light[light.size() - 1]->setLightColor(r, g, b);
light[light.size() - 1]->setRadianceScalingFactor(i);
light[light.size() - 1]->setLightDirection(x, y, z);
light[light.size() - 1]->setLightOrigin(originx, originy, originz);
light[light.size() - 1]->setRectangleAreaLightMatrix(degreeRotation);
light[light.size() - 1]->setRectangleAreaLightWidthHeight(width, height);
light[light.size() - 1]->setRectangleAreaLightSamplePointAmount(samplePointWidth);
Material *mat = createMatteMaterial(1, 1);
createPlane(mat, objects, width, height, degreeRotation, r * 255, g * 255, b * 255, x, y, z, originx, originy, originz, false, "arealight");
}
void RayTracer::createDirectionalLight(vector<Light*> &light, double r, double g, double b, double x, double y, double z, double i) {
light.push_back(new DirectionalLight);
light[light.size() - 1]->setLightColor(r, g, b);
light[light.size() - 1]->setRadianceScalingFactor(i);
light[light.size() - 1]->setLightDirection(x, y, z);
}
void RayTracer::createAmbientLight(vector<Light*> &light, double r, double g, double b, double i) {
light.push_back(new AmbientLight);
light[light.size() - 1]->setLightColor(r, g, b);
light[light.size() - 1]->setRadianceScalingFactor(i);
}
void RayTracer::createAreaPointLight(vector<Light*> &light, double radius, int samplePointAmount, double r, double g, double b, double x, double y, double z, double i) {
light.push_back(new PointLight);
light[light.size() - 1]->setLightColor(r, g, b);
light[light.size() - 1]->setRadianceScalingFactor(i);
light[light.size() - 1]->setLightOrigin(x, y, z);
light[light.size() - 1]->setPointLightRadius(radius);
light[light.size() - 1]->setAreaPointLightSamplePointAmount(samplePointAmount);
Material *mat = createMatteMaterial(1, 1);
createSphere(mat, objects, r * 255, g * 255, b * 255, x, y, z, radius, "arealight");
}
void RayTracer::createPlane(Material* mat, vector<RaytracingObject*> &objects, double w, double h, double rotation, double r, double g, double b, double nx, double ny, double nz, double px, double py, double pz, bool checkered, string tag) {
objects.push_back(new Plane);
objects[objects.size() - 1]->setPlaneNormal(nx, ny, nz);
objects[objects.size() - 1]->setColor(r, g, b);
objects[objects.size() - 1]->setPointOnPlane(px, py, pz);
objects[objects.size() - 1]->setPlaneMatrix(rotation);
objects[objects.size() - 1]->setPlaneWidthHeight(w, h);
objects[objects.size() - 1]->setCheckered(checkered);
objects[objects.size() - 1]->setMaterial(mat);
objects[objects.size() - 1]->setTag(tag);
}
void RayTracer::createSphere(Material *mat, vector<RaytracingObject*> &objects, double r, double g, double b, double ox, double oy, double oz, double radius, string tag) {
objects.push_back(new Sphere);
objects[objects.size() - 1]->setOrigin(ox, oy, oz);
objects[objects.size() - 1]->setColor(r, g, b);
objects[objects.size() - 1]->setRadius(radius);
objects[objects.size() - 1]->setMaterial(mat);
objects[objects.size() - 1]->setTag(tag);
}
void RayTracer::createGeometricObjects() {
cout << "Loading geometric objects..." << endl;
Material *mat = createPhongMaterial(1, 1, 500, 100);
createSphere(mat, objects, 100, 50, 0, -3, 4, 14, 4);
Material *mat2 = createPhongMaterial(1, 1, 500, 100);
createSphere(mat2, objects, 0, 20, 100, 4, 2, 8, 2);
//Material *mat3 = createMatteMaterial(1, 1);// , 500, 100);
//createPlane(mat3, objects, 11, 11, 0, 100, 100, 100, 0, 0, -1, 0, 10, 20, false);//back wall
Material *mat4 = createMatteMaterial(1, 1);// , 500, 100);
createPlane(mat4, objects, 20, 10, 0, 100, 100, 100, 0, 1, 0, 0, 0, 10, false);//floor
//Material *mat5 = createMatteMaterial(1, 1);// , 500, 100);
//createPlane(mat5, objects, 11, 11, 0, 100, 100, 100, 0, -1, 0, 0, 20, 10, false);//ceiling
//Material *mat6 = createMatteMaterial(1, 1);// , 500, 100);
//createPlane(mat6, objects, 10, 10, 0, 100, 0, 0, 1, 0, 0, -11, 10, 10, false);//left wall
//Material *mat7 = createMatteMaterial(1, 1);// , 500, 100);
//createPlane(mat7, objects, 10, 10, 0, 0, 100, 0, -1, 0, 0, 11, 10, 10, false);//right wall
}
void RayTracer::render() {
srand(NULL);
//loop through pixels and shoot rays into scene
//create clock variable to record miliseconds of rendering time
clock_t begin = clock();
cout << "Rendering image..." << endl;
cout << "Getting initial time estimate. Please wait..." << endl;
int step = bmp.height / 10;
step = bmp.height / step;
for (unsigned int y = 0; y < bmp.height; y++) {
if (y % step == 0) {
cout << int(((double)y / bmp.height) * 100) << " percent complete." << endl;
}
if (y % 100 == 0 && y != 0) { //display time estimate
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
if ((elapsed_secs / y) * (bmp.height - y) * 3 < 60)
std::cout << "Image will be rendered in approximately " << (elapsed_secs / y) * (bmp.height - y) * 3<< " seconds..." << endl;
else
std::cout << "Image will be rendered in approximately " << (elapsed_secs / y) * (bmp.height - y) / 60 * 3 << " minutes..." << endl;
}
for (unsigned int x = 0; x < bmp.width; x++) {
RGB rgb(20, 20, 20);
sample.jittered();
//sample.mapSamplesToDisk();
sample.createHemisphereSamples();
for (unsigned int i = 0; i < rectangleAreaLights.size(); i++) {
rectangleAreaLights[i]->generateSamples();
}
for (unsigned int i = 0; i < pointLights.size(); i++) {
pointLights[i]->generateSamples();
}
//vector<Vector> samplePoints = rectangleAreaLights[0]->getSamplePoints();
//for (int i = 0; i < samplePoints.size(); i++) {
// bmp.setPixelColor(samplePoints[i].x * bmp.width, samplePoints[i].y * bmp.height, 255, 255, 255);
//}
//for (int j = 0; j < sample.numberOfSamples; j++) {
// cout << "x: " << sample.samples[j].x << endl;
// cout << "y: " << sample.samples[j].y << endl;
//}
//for (int i = 0; i < sample.numberOfHemisphereSamples; i++) {
// double y = sample.hemisphereSamples3D[i].y;
// if (y >= 0)
// bmp.setPixelColor(((sample.hemisphereSamples3D[i].x + 1) / 2) * bmp.width, ((sample.hemisphereSamples3D[i].z + 1) / 2)* bmp.height, 255, 255, 255);// , y * 255, y * 255, y * 255);
// else
// bmp.setPixelColor(((sample.hemisphereSamples3D[i].x + 1) / 2) * bmp.width, ((sample.hemisphereSamples3D[i].z + 1) / 2)* bmp.height, 255, 0, 0);
//}
//x = y = 9999;
//sample the image
for (unsigned int i = 0; i < sample.numberOfSamples; i++) {
//bmp.setPixelColor(sample.samples[i].x * bmp.width, sample.samples[i].y * bmp.width, 20, 200, 20);
//bmp.setPixelColor(sample.diskSamples[i].x * bmp.width, sample.diskSamples[i].y * bmp.width, 20, 200, 20);
//bmp.setPixelColor(sample.hemisphereSamples[i].x * bmp.width, sample.hemisphereSamples[i].y * bmp.width, 20, sample.hemisphereSamples[i].z * 255, 20);
Vector rayOrigin;
Vector primaryRay = cam.pinholeCamera(x, y, sample.samples[i].x, sample.samples[i].y, cam, bmp, rayOrigin);
//Vector primaryRay = cam.thinlensCamera(x, y, sample.samples[i].x, sample.samples[i].y, sample.diskSamples[i].x, sample.diskSamples[i].y, cam, bmp, rayOrigin);
//find closest object
RaytracingObject *object = NULL;
double minDepth = DBL_MAX;
double depth = DBL_MAX;
//material used for shading object that ray intersects
Material *material = NULL;
//shade used to collect data for shading such as intersection points
Shade shade;
for (unsigned int i = 0; i < objects.size(); i++) {
objects[i]->intersectRay(depth, primaryRay, rayOrigin);
if (depth < minDepth) {
object = objects[i];
minDepth = depth;
shade.intersectionPoint = rayOrigin + (primaryRay * depth);
}
}
if (object != NULL) {
material = object->getMaterial();
shade.normal = object->getNormal();
shade.wo = primaryRay * -1;
shade.colorOfObject = object->getColor();
shade.sample = &sample;
if (object->getTag() == "arealight") { //if ray hits the area light, then just return a white color for the light its-self
rgb += object->getColor();
}
else {
rgb += shade.performShading(object->getMaterial()->getAmbientBRDF(), object->getMaterial()->getDiffuseBRDF(), object->getMaterial()->getSpecularBRDF(), objects, ambientLight, pointLights, rectangleAreaLights);
}
}
}
rgb /= sample.numberOfSamples;
//clamp rgb (very crude)
double maxNum = max(max(rgb.r, rgb.g), rgb.b);
if (maxNum > 255) {
rgb /= maxNum;
rgb.r *= 255;
rgb.g *= 255;
rgb.b *= 255;
}
bmp.setPixelColor(x, y, (unsigned char)rgb.r, (unsigned char)rgb.g, (unsigned char)rgb.b);
}
}
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
if (elapsed_secs < 60)
std::cout << "Rendered image in: " << elapsed_secs << " seconds." << endl;
else
std::cout << "Rendered image in: " << elapsed_secs / 60 << " minutes." << endl;
}
void RayTracer::saveImage() {
bmp.saveBMP();
}
RayTracer::~RayTracer() {
for (unsigned int i = 0; i < objects.size(); i++) {
delete objects[i];
}
}
|
// Created on: 1995-12-04
// Created by: Laurent BOURESCHE
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GeomFill_CoonsAlgPatch_HeaderFile
#define _GeomFill_CoonsAlgPatch_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <gp_Pnt.hxx>
#include <Standard_Transient.hxx>
#include <Standard_Integer.hxx>
class GeomFill_Boundary;
class Law_Function;
class gp_Vec;
class GeomFill_CoonsAlgPatch;
DEFINE_STANDARD_HANDLE(GeomFill_CoonsAlgPatch, Standard_Transient)
//! Provides evaluation methods on an algorithmic
//! patch (based on 4 Curves) defined by its boundaries and blending
//! functions.
class GeomFill_CoonsAlgPatch : public Standard_Transient
{
public:
//! Constructs the algorithmic patch. By Default the
//! constructed blending functions are linear.
//! Warning: No control is done on the bounds.
//! B1/B3 and B2/B4 must be same range and well oriented.
Standard_EXPORT GeomFill_CoonsAlgPatch(const Handle(GeomFill_Boundary)& B1, const Handle(GeomFill_Boundary)& B2, const Handle(GeomFill_Boundary)& B3, const Handle(GeomFill_Boundary)& B4);
//! Give the blending functions.
Standard_EXPORT void Func (Handle(Law_Function)& f1, Handle(Law_Function)& f2) const;
//! Set the blending functions.
Standard_EXPORT void SetFunc (const Handle(Law_Function)& f1, const Handle(Law_Function)& f2);
//! Computes the value on the algorithmic patch at
//! parameters U and V.
Standard_EXPORT gp_Pnt Value (const Standard_Real U, const Standard_Real V) const;
//! Computes the d/dU partial derivative on the
//! algorithmic patch at parameters U and V.
Standard_EXPORT gp_Vec D1U (const Standard_Real U, const Standard_Real V) const;
//! Computes the d/dV partial derivative on the
//! algorithmic patch at parameters U and V.
Standard_EXPORT gp_Vec D1V (const Standard_Real U, const Standard_Real V) const;
//! Computes the d2/dUdV partial derivative on the
//! algorithmic patch made with linear blending functions
//! at parameter U and V.
Standard_EXPORT gp_Vec DUV (const Standard_Real U, const Standard_Real V) const;
Standard_EXPORT const gp_Pnt& Corner (const Standard_Integer I) const;
Standard_EXPORT const Handle(GeomFill_Boundary)& Bound (const Standard_Integer I) const;
Standard_EXPORT const Handle(Law_Function)& Func (const Standard_Integer I) const;
DEFINE_STANDARD_RTTIEXT(GeomFill_CoonsAlgPatch,Standard_Transient)
protected:
private:
Handle(GeomFill_Boundary) bound[4];
gp_Pnt c[4];
Handle(Law_Function) a[2];
};
#endif // _GeomFill_CoonsAlgPatch_HeaderFile
|
#ifndef CRYPTOVIEW_H
#define CRYPTOVIEW_H
#include "coin.h"
#include <coin_db.h>
#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QLabel>
#include <QMap>
#include <QList>
#include "socketclient.h"
#include "httpclient.h"
#include "candlestickdialog.h"
namespace Ui {
class CryptoView;
}
class CryptoView : public QMainWindow
{
Q_OBJECT
public:
explicit CryptoView(QWidget *parent = 0);
void setCurrencyLabelText(coin& coin, QLabel& imgLabel, QLabel& valueLabel, QLabel& titleLabel );
void pushCoin(coin& coin);
void updatelabel(QString str);
void formLoad();
~CryptoView();
private slots:
void onCoinUpdate(int channelId, CoinData data);
void onNewCoin(int channelId, QString pair);
void onResponse(QNetworkReply *reply);
void on_coin1_btn_clicked();
/* void on_coin2_btn_clicked();
void on_coin3_btn_clicked();
void on_coin4_btn_clicked(); */
private:
Ui::CryptoView *ui;
SocketClient *socketClient;
HTTPClient *httpClient;
QMap<int, QString> channelMap;
QMap<int, QString> coinRankMap;
QMap<QString, coin*> coinMap;
CandleStickDialog *candles;
};
#endif // CRYPTOVIEW_H
|
/*
* Item.cpp
*
* Created on: Aug 16, 2016
* Author: Kevin Koza
*/
#include "Item.h"
#include <iostream>
#include <cstddef>
namespace std {
Item::Item() {
// TODO Auto-generated constructor stub
name = "\0";
}
Item::Item(string n){
name = n;
}
Item::~Item() {
// TODO Auto-generated destructor stub
}
void Item::setName(string n){
name = n;
}
string Item::toString(){
return name;
}
} /* namespace std */
|
//Recurssion+Memoization
int solve(int A, vector<int> & dp){
if(A<0) return 0;
if(A==0) return 1;
if(dp[A]!=-1) return dp[A];
return dp[A]=solve(A-1,dp)+solve(A-2,dp);
}
int Solution::climbStairs(int A) {
if(A<0) return 0;
if(A==0) return 1;
vector<int> dp(A+1,-1);
return solve(A,dp);
}
//Bottom-up
int Solution::climbStairs(int A) {
if(A<0) return 0;
if(A==0) return 1;
vector<int> dp(A+1,-1);
dp[0]=1;
dp[1]=1;
for(int i =2;i<A+1;i++){
dp[i]=dp[i-1]+dp[i-2];
}
return dp[A];
}
|
#pragma once
class unitTest
{
public:
unitTest();
~unitTest();
// true ha a,b,c egyenlőek és d hamis, egyébként hamis
bool functionToTest1(bool a, bool b, bool c, bool d);
// ha a és b és c igaz de d hamis akkor az f2() igaz, egyébként hamis
bool functionToTest2(bool a, bool b, bool c, bool d);
// ha (a és c) vagy (b és d) közül
//legalább az egyik igaz akkor f3() igaz egyébként hamis
bool functionToTest3(bool a, bool b, bool c, bool d);
//igaz, ha a igaz, de b nem igaz, egyébként hamis
bool functionToTest4(bool a, bool b);
//igaz, ha a és c egyenlőek, de b hamis, egyébként hamis
bool functionToTest5(bool a, bool b, bool c, bool d);
//igaz, ha hamis az a és a b is és b egyenlő c-vel
// egyébként hamis
bool functionToTest6(bool a, bool b, bool c, bool d);
void makeInput1(bool &a, bool &b, bool &c, bool &d, int p);
void makeInput2(bool &a, bool &b, bool &c, bool &d, int p);
void printInput();
};
|
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
//基本思想:位运算,将nums中所有元素异或得到的就是所求元素a和b不进位的相加结果x
//那么x的第一个非0位n就是a和b在第n位上互为0和1,所以可以将nums中所有元素在第n位上是0或1分成两类,这两类元素分别异或就得到了a和b值
int a=0,b=0;
int x=0,n;
for(auto num:nums)
x^=num;
for(n=0;n<32;n++)
{
if(x&1)
break;
x>>=1;
}
for(auto num:nums)
{
if(num>>n&1)
a^=num;
else
b^=num;
}
return {a,b};
}
};
int main()
{
Solution solute;
vector<int> nums{1,2,1,3,2,5};
vector<int> res=solute.singleNumber(nums);
cout<<res[0]<<" "<<res[1]<<endl;
return 0;
}
|
/*
* ×î¶ÌÅÅÐò×ÓÊý×é
*/
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
int shortest_sort_subsequence(vector<int> &nums){
if(nums.empty() || nums.size() < 2){
return 0;
}
int left = 0;
int right = nums.size() - 1;
int max = nums[0];
int min = nums[right];
for(int i=0; i<nums.size(); ++i){
if(nums[i] > max){
max = nums[i];
}else{
right = i;
}
}
for(int i=nums.size()-1; i>=0; --i){
if(nums[i] < min){
min = nums[i];
}else{
left = i;
}
}
if(left == right){
return 0;
}
return right - left + 1;
}
};
int main(){
int arr[] = {1,4,6,5,9,10};
vector<int> nums(arr,arr+6);
Solution s;
printf("%d\n",s.shortest_sort_subsequence(nums));
return 0;
}
|
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "ShellState.h"
#include "ShellContext.h"
#include "transport/TTransportException.h"
using namespace std;
using namespace apache::thrift::transport;
const char * PMT = ">> ";
void ShellStateStart::run(ShellContext * c) {
if(!c->ParseInput()) {
c->changeState(ShellStateStop::getInstance());
} else {
c->changeState(ShellStateConnecting::getInstance());
}
}
void ShellStateStop::run(ShellContext * c) {
c->stop();
}
void ShellStateConnecting::run(ShellContext * c) {
try {
c->connect();
} catch (const TTransportException & e) {
cout << e.what() << endl;
c->changeState(ShellStateStop::getInstance());
return;
}
c->changeState(ShellStateConnected::getInstance());
}
void ShellStateConnected::unknownCmd(void) {
cout << "Unknown command!" << endl;
cout << "Use help to list all available commands" << endl;
}
void ShellStateConnected::helpMsg(void) {
cout << "Currently supported commands:" << endl;
cout << "create db" << endl;
cout << "get db key" << endl;
cout << "scan db start_key end_key limit" << endl;
cout << "put db key value" << endl;
cout << "exit/quit" << endl;
}
void ShellStateConnected::handleConError(ShellContext * c) {
cout << "Connection down" << endl;
cout << "Reconnect ? (y/n) :" << endl;
string s;
while(getline(cin, s)) {
if("y" == s) {
c->changeState(ShellStateConnecting::getInstance());
break;
} else if("n" == s) {
c->changeState(ShellStateStop::getInstance());
break;
} else {
cout << "Reconnect ? (y/n) :" << endl;
}
}
}
void ShellStateConnected::run(ShellContext * c) {
string line;
cout << PMT;
getline(cin, line);
istringstream is(line);
vector<string> params;
string param;
while(is >> param) {
params.push_back(param);
}
// empty input line
if(params.empty())
return;
if("quit" == params[0] || "exit" == params[0]) {
c->changeState(ShellStateStop::getInstance());
} else if("get" == params[0]) {
if(params.size() == 3) {
try {
c->get(params[1], params[2]);
} catch (const TTransportException & e) {
cout << e.what() << endl;
handleConError(c);
}
} else {
unknownCmd();
}
} else if("create" == params[0]) {
if(params.size() == 2) {
try {
c->create(params[1]);
} catch (const TTransportException & e) {
cout << e.what() << endl;
handleConError(c);
}
} else {
unknownCmd();
}
}else if("put" == params[0]) {
if(params.size() == 4) {
try {
c->put(params[1], params[2], params[3]);
} catch (const TTransportException & e) {
cout << e.what() << endl;
handleConError(c);
}
} else {
unknownCmd();
}
} else if("scan" == params[0]) {
if(params.size() == 5) {
try {
c->scan(params[1], params[2], params[3], params[4]);
} catch (const TTransportException & e) {
cout << e.what() << endl;
handleConError(c);
}
} else {
unknownCmd();
}
} else if("help" == params[0]) {
helpMsg();
} else {
unknownCmd();
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2008-2009 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 WIDGETS_IMS_SUPPORT
#include "modules/widgets/OpIMSObject.h"
#include "modules/widgets/OpListBox.h"
/**
* Implementation of OpIMSUpdateList for a single select list.
* Only keeps track of one changed item.
*/
class OpIMSUpdateSingle : public OpIMSUpdateList
{
private:
int m_index;
int m_value;
public:
OpIMSUpdateSingle() : m_index(-1), m_value(-1) {}
void Clear(void) { m_index = -1; m_value = -1; }
int GetFirstIndex(void) { return m_index; }
int GetNextIndex(int index) { return -1; }
int GetValueAt(int index) { return m_index == index ? m_value : -1;}
void Update(int index, BOOL value) { m_index = index; m_value = value ? 1 : 0; }
};
/**
* Implementation of OpIMSUpdateList for a multiple select list.
*/
class OpIMSUpdateListMulti : public OpIMSUpdateList
{
struct ImsItem
{
int value;
};
public:
OpIMSUpdateListMulti();
~OpIMSUpdateListMulti();
/** Construct the update list. Must be called after ctor. */
OP_STATUS Construct(int count);
void Clear(void);
int GetFirstIndex(void);
int GetNextIndex(int index);
int GetValueAt(int index);
void Update(int index, BOOL value);
private:
ImsItem* m_items;
int m_count;
};
OpIMSObject::OpIMSObject() :
m_updates(NULL), m_listener(NULL), m_ih(NULL), has_scrollbar(FALSE), m_dropdown(FALSE)
{
}
OpIMSObject::~OpIMSObject()
{
OP_DELETE(m_updates); m_updates = NULL;
}
void OpIMSObject::SetListener(OpIMSListener* listener)
{
m_listener = listener;
}
void OpIMSObject::SetItemHandler(ItemHandler* ih)
{
m_ih = ih;
}
BOOL OpIMSObject::IsIMSActive()
{
return (m_updates != NULL);
}
OP_STATUS OpIMSObject::StartIMS(WindowCommander* windowcommander)
{
if (IsIMSActive())
return OpStatus::ERR;
RETURN_IF_ERROR(CreateUpdatesObject());
OP_STATUS status = windowcommander->GetDocumentListener()->OnIMSRequested(windowcommander, this);
if (status == OpStatus::ERR_NOT_SUPPORTED)
{
OP_DELETE(m_updates); m_updates = NULL;
}
return status;
}
OP_STATUS OpIMSObject::UpdateIMS(WindowCommander* windowcommander)
{
if (!IsIMSActive())
return OpStatus::ERR;
RETURN_IF_ERROR(CreateUpdatesObject());
windowcommander->GetDocumentListener()->OnIMSUpdated(windowcommander, this);
return OpStatus::OK;
}
void OpIMSObject::DestroyIMS(WindowCommander* windowcommander)
{
if (IsIMSActive())
{
OP_DELETE(m_updates); m_updates = NULL;
windowcommander->GetDocumentListener()->OnIMSCancelled(windowcommander, this);
}
}
void OpIMSObject::SetIMSAttribute(IMSAttribute attr, int value)
{
if (attr == HAS_SCROLLBAR)
has_scrollbar = !!value;
if (attr == DROPDOWN)
m_dropdown = !!value;
}
void OpIMSObject::SetRect(const OpRect& rect)
{
m_rect = rect;
}
OP_STATUS OpIMSObject::CreateUpdatesObject()
{
OP_DELETE(m_updates);
if (m_ih->is_multiselectable)
{
m_updates = OP_NEW(OpIMSUpdateListMulti, ());
if (m_updates && OpStatus::IsError(static_cast<OpIMSUpdateListMulti*>(m_updates)->Construct(m_ih->CountItemsAndGroups())))
{
OP_DELETE(m_updates);
m_updates = NULL;
}
}
else
m_updates = OP_NEW(OpIMSUpdateSingle, ());
if (!m_updates)
return OpStatus::ERR_NO_MEMORY;
return OpStatus::OK;
}
/* virtual */
void OpIMSObject::OnCommitIMS()
{
if (IsIMSActive())
{
m_listener->OnCommitIMS(m_updates);
OP_DELETE(m_updates); m_updates = NULL;
}
}
/* virtual */
void OpIMSObject::OnUpdateIMS(int item, BOOL selected)
{
if (IsIMSActive())
m_updates->Update(item, selected);
}
/* virtual */
void OpIMSObject::OnCancelIMS()
{
if (IsIMSActive())
{
m_listener->OnCancelIMS();
OP_DELETE(m_updates); m_updates = NULL;
}
}
int OpIMSObject::GetIMSAttributeAt(int index, IMSItemAttribute attr)
{
if (m_ih == NULL || index < 0 || index >= m_ih->CountItemsAndGroups())
return -1;
OpStringItem* item = m_ih->GetItemAtIndex(index);
switch (attr)
{
case SELECTED:
return item->IsSelected();
case ENABLED:
return item->IsEnabled();
case SEPARATOR:
return item->IsSeperator();
case GROUPSTART:
return item->IsGroupStart();
case GROUPSTOP:
return item->IsGroupStop();
}
return 0;
}
int OpIMSObject::GetItemCount(void)
{
if (m_ih)
return m_ih->CountItemsAndGroups();
return 0;
}
int OpIMSObject::GetFocusedItem()
{
if (m_ih && GetItemCount() > 0)
return m_ih->focused_item;
return -1;
}
int OpIMSObject::GetIMSAttribute(IMSAttribute attr)
{
switch (attr)
{
case HAS_SCROLLBAR:
return has_scrollbar ? 1 : 0;
case MULTISELECT:
return m_ih->is_multiselectable;
case DROPDOWN:
return m_dropdown ? 1 : 0;
}
return -1;
}
const uni_char * OpIMSObject::GetIMSStringAt(int index)
{
if (m_ih == NULL || index < 0 || index >= m_ih->CountItemsAndGroups())
return NULL;
OpStringItem* item = m_ih->GetItemAtIndex(index);
return item->string.Get();
}
OpRect OpIMSObject::GetIMSRect()
{
return m_rect;
}
OpIMSUpdateListMulti::OpIMSUpdateListMulti()
: m_items(NULL), m_count(0)
{
}
OpIMSUpdateListMulti::~OpIMSUpdateListMulti()
{
OP_DELETEA(m_items);
}
OP_STATUS OpIMSUpdateListMulti::Construct(int count)
{
m_count = count;
OP_DELETEA(m_items); m_items = NULL;
m_items = OP_NEWA(ImsItem, count);
if (NULL == m_items)
return OpStatus::ERR_NO_MEMORY;
Clear();
return OpStatus::OK;
}
void OpIMSUpdateListMulti::Clear(void)
{
if (m_items == NULL)
return;
int i;
for (i=0;i<m_count;i++)
m_items[i].value = -1;
}
int OpIMSUpdateListMulti::GetFirstIndex(void)
{
if (m_items == NULL)
return -1;
int i;
for (i=0;i<m_count;i++)
{
if (m_items[i].value != -1)
return i;
}
return -1;
}
int OpIMSUpdateListMulti::GetNextIndex(int index)
{
if (m_items == NULL)
return -1;
int i;
for (i=index+1;i<m_count;i++)
{
if (m_items[i].value != -1)
return i;
}
return -1;
}
int OpIMSUpdateListMulti::GetValueAt(int index)
{
if (m_items == NULL || index < 0 || index >= m_count)
return -1; //TODO OOM
return m_items[index].value;
}
void OpIMSUpdateListMulti::Update(int index, BOOL value)
{
if (m_items == NULL || index < 0 || index >= m_count)
return; //TODO OOM
m_items[index].value = value ? 1 : 0;
}
#endif // WIDGETS_IMS_SUPPORT
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2004-2008 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Yngve N. Pettersen
*/
#include "core/pch.h"
#ifdef SELFTEST
#include "modules/selftest/src/testutils.h"
#include "modules/network_selftest/basicwincom.h"
BasicWindowListener::~BasicWindowListener(){fallback=NULL;}
void BasicWindowListener::OnAuthenticationRequired(OpWindowCommander* commander, OpAuthenticationCallback* callback)
{
fallback->OnAuthenticationRequired(commander, callback);
}
void BasicWindowListener::OnUrlChanged(OpWindowCommander* commander, const uni_char* url)
{
fallback->OnUrlChanged(commander, url);
}
void BasicWindowListener::OnStartLoading(OpWindowCommander* commander)
{
fallback->OnStartLoading(commander);
}
void BasicWindowListener::OnLoadingProgress(OpWindowCommander* commander, const LoadingInformation* info)
{
fallback->OnLoadingProgress(commander,info);
}
void BasicWindowListener::OnLoadingFinished(OpWindowCommander* commander, LoadingFinishStatus status)
{
fallback->OnLoadingFinished(commander,status);
}
void BasicWindowListener::OnStartUploading(OpWindowCommander* commander)
{
fallback->OnStartUploading(commander);
}
void BasicWindowListener::OnUploadingFinished(OpWindowCommander* commander, LoadingFinishStatus status)
{
fallback->OnUploadingFinished(commander,status);
}
BOOL BasicWindowListener::OnLoadingFailed(OpWindowCommander* commander, int msg_id, const uni_char* url)
{
return fallback->OnLoadingFailed(commander,msg_id,url);
}
#ifdef EMBROWSER_SUPPORT
void BasicWindowListener::OnUndisplay(OpWindowCommander* commander)
{fallback->OnUndisplay(commander);
}
void BasicWindowListener::OnLoadingCreated(OpWindowCommander* commander)
{fallback->OnLoadingCreated(commander);
}
#endif // EMBROWSER_SUPPORT
void BasicWindowListener::ReportFailure(URL &url, const char *format, ...)
{
OpString8 tempstring;
va_list args;
va_start(args, format);
if(format == NULL)
format = "";
OP_STATUS op_err = url.GetAttribute(URL::KName_Escaped, tempstring);
if(OpStatus::IsSuccess(op_err))
op_err = tempstring.Append(" :");
if(OpStatus::IsSuccess(op_err))
tempstring.AppendVFormat(format, args);
if(test_manager)
test_manager->ReportTheFailure(OpStatus::IsSuccess(op_err) ? tempstring.CStr() : format);
else
ST_failed(OpStatus::IsSuccess(op_err) ? tempstring.CStr() : format);
va_end(args);
}
#endif // SELFTEST
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
//
// Copyright (C) 2003-2012 Opera Software ASA. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Julien Picalausa
//
#include "platforms/windows_common/utils/proc_loader_headers.h"
//Declaration of types used by LIBRARY_CALL entries below.
//Please, keep track of what uses what. There is no particular order here.
//Used by DrawThemeTextEx and SetWindowThemeAttribute
#include <Uxtheme.h>
//Used by NtSetInformationProcess and NtQuery*
#include "ntstatus.h"
#pragma pack(push, 8)
namespace NtDll {
enum PROCESS_INFORMATION_CLASS {
ProcessBasicInformation = 0,
ProcessDebugPort = 7,
ProcessWow64Information = 26,
ProcessImageFileName = 27,
ProcessExecuteFlags = 34,
};
enum FILE_INFORMATION_CLASS {
FileDirectoryInformation = 1,
FileFullDirectoryInformation = 2,
FileBothDirectoryInformation = 3,
FileBasicInformation = 4,
FileStandardInformation = 5,
FileInternalInformation = 6,
FileEaInformation = 7,
FileAccessInformation = 8,
FileNameInformation = 9,
FileRenameInformation = 10,
FileLinkInformation = 11,
FileNamesInformation = 12,
FileDispositionInformation = 13,
FilePositionInformation = 14,
FileFullEaInformation = 15,
FileModeInformation = 16,
FileAlignmentInformation = 17,
FileAllInformation = 18,
FileAllocationInformation = 19,
FileEndOfFileInformation = 20,
FileAlternateNameInformation = 21,
FileStreamInformation = 22,
FilePipeInformation = 23,
FilePipeLocalInformation = 24,
FilePipeRemoteInformation = 25,
FileMailslotQueryInformation = 26,
FileMailslotSetInformation = 27,
FileCompressionInformation = 28,
FileObjectIdInformation = 29,
FileCompletionInformation = 30,
FileMoveClusterInformation = 31,
FileQuotaInformation = 32,
FileReparsePointInformation = 33,
FileNetworkOpenInformation = 34,
FileAttributeTagInformation = 35,
FileTrackingInformation = 36,
FileIdBothDirectoryInformation = 37,
FileIdFullDirectoryInformation = 38,
FileValidDataLengthInformation = 39,
FileShortNameInformation = 40,
FileMaximumInformatio = 41
};
enum OBJECT_INFORMATION_CLASS {
ObjectBasicInformation = 0,
ObjectNameInformation = 1,
ObjectTypeInformation = 2,
ObjectAllTypesInformation = 3,
ObjectHandleInformation = 4,
ObjectSessionInformation = 5
};
enum SYSTEM_INFORMATION_CLASS { // Size:
SystemBasicInformation = 0, // 0x002C
SystemProcessorInformation, // 0x000C
SystemPerformanceInformation, // 0x0138
SystemTimeOfDayInformation, // 0x0020
SystemPathInformation, // not implemented
SystemProcessInformation, // 0x00F8+ per process
SystemCallInformation, // 0x0018 + (n * 0x0004)
SystemConfigurationInformation, // 0x0018
SystemProcessorPerformanceInformation, // 0x0030 per cpu
SystemGlobalFlag, // 0x0004
SystemCallTimeInformation,
SystemModuleInformation, // 0x0004 + (n * 0x011C)
SystemLockInformation, // 0x0004 + (n * 0x0024)
SystemStackTraceInformation,
SystemPagedPoolInformation, // checked build only
SystemNonPagedPoolInformation, // checked build only
SystemHandleInformation, // 0x0004 + (n * 0x0010)
SystemObjectInformation, // 0x0038+ + (n * 0x0030+)
SystemPagefileInformation, // 0x0018+ per page file
SystemInstemulInformation, // 0x0088
SystemVdmBopInformation,
SystemCacheInformation, // 0x0024
SystemPoolTagInformation, // 0x0004 + (n * 0x001C)
SystemProcessorStatistics, // 0x0000, or 0x0018 per cpu
SystemDpcInformation, // 0x0014
SystemMemoryUsageInformation1, // checked build only
SystemLoadImage, // 0x0018, set mode only
SystemUnloadImage, // 0x0004, set mode only
SystemTimeAdjustmentInformation, // 0x000C, 0x0008 writeable
SystemSummaryMemoryInformation, // checked build only
SystemMirrorMemoryInformation, // checked build only
SystemPerformanceTraceInformation, // checked build only
SystemCrashDumpInformation, // 0x0004
SystemExceptionInformation, // 0x0010
SystemCrashDumpStateInformation, // 0x0008
SystemDebuggerInformation, // 0x0002
SystemThreadSwitchInformation, // 0x0030
SystemRegistryQuotaInformation, // 0x000C
SystemLoadDriver, // 0x0008, set mode only
SystemPrioritySeparationInformation, // 0x0004, set mode only
SystemVerifierAddDriverInformation, // not implemented
SystemVerifierRemoveDriverInformation, // not implemented
SystemProcessorIdleInformation, // invalid info class
SystemLegacyDriverInformation, // invalid info class
SystemTimeZoneInformation, // 0x00AC
SystemLookasideInformation, // n * 0x0020
SystemSetTimeSlipEvent, // set mode only [2]
SystemCreateSession, // WTS*, set mode only [2]
SystemDeleteSession, // WTS*, set mode only [2]
SystemSessionInformation, // invalid info class [2]
SystemRangeStartInformation, // 0x0004 [2]
SystemVerifierInformation, // 0x0068 [2]
SystemAddVerifier, // set mode only [2]
SystemSessionProcessesInformation, // WTS[1] [2]
SystemLoadGdiDriverInSystemSpace,
SystemNumaProcessorMap,
SystemPrefetcherInformation,
SystemExtendedProcessInformation,
SystemRecommendedSharedDataAlignment,
SystemComPlusPackage,
SystemNumaAvailableMemory,
SystemProcessorPowerInformation,
SystemEmulationBasicInformation,
SystemEmulationProcessorInformation,
SystemExtendedHandleInformation,
SystemLostDelayedWriteInformation,
SystemBigPoolInformation,
SystemSessionPoolTagInformation,
SystemSessionMappedViewInformation,
SystemHotpatchInformation,
SystemObjectSecurityMode,
SystemWatchdogTimerHandler,
SystemWatchdogTimerInformation,
SystemLogicalProcessorInformation,
SystemWow64SharedInformation,
SystemRegisterFirmwareTableInformationHandler,
SystemFirmwareTableInformation,
SystemModuleInformationEx,
SystemVerifierTriageInformation,
SystemSuperfetchInformation,
SystemMemoryListInformation,
SystemFileCacheInformationEx,
MaxSystemInfoClass // MaxSystemInfoClass should always be the
};
// [1] Windows Terminal Server
// [2] Info classes specific to Windows 2000
} // namepspace NtDll
struct IO_STATUS_BLOCK {
union {
NTSTATUS status;
PVOID ptr;
};
ULONG_PTR info;
};
//Used by WlanEnumInterfaces
#define WLAN_MAX_NAME_LENGTH 256
typedef enum _WLAN_INTERFACE_STATE
{
wlan_interface_state_not_ready,
wlan_interface_state_connected,
wlan_interface_state_ad_hoc_network_formed,
wlan_interface_state_disconnecting,
wlan_interface_state_disconnected,
wlan_interface_state_associating,
wlan_interface_state_discovering,
wlan_interface_state_authenticating
} WLAN_INTERFACE_STATE, *PWLAN_INTERFACE_STATE;
typedef struct _WLAN_INTERFACE_INFO
{
GUID InterfaceGuid;
WCHAR strInterfaceDescription[WLAN_MAX_NAME_LENGTH];
WLAN_INTERFACE_STATE isState;
} WLAN_INTERFACE_INFO, *PWLAN_INTERFACE_INFO;
typedef struct _WLAN_INTERFACE_INFO_LIST
{
DWORD dwNumberOfItems;
DWORD dwIndex;
WLAN_INTERFACE_INFO InterfaceInfo[1];
} WLAN_INTERFACE_INFO_LIST, *PWLAN_INTERFACE_INFO_LIST;
//Used by WlanGetNetworkBssList
#define DOT11_SSID_MAX_LENGTH 32 // 32 bytes
typedef struct _DOT11_SSID
{
ULONG uSSIDLength;
UCHAR ucSSID[DOT11_SSID_MAX_LENGTH];
} DOT11_SSID, * PDOT11_SSID;
typedef enum _DOT11_BSS_TYPE
{
dot11_BSS_type_infrastructure = 1,
dot11_BSS_type_independent = 2,
dot11_BSS_type_any = 3
} DOT11_BSS_TYPE, * PDOT11_BSS_TYPE;
typedef enum _DOT11_PHY_TYPE
{
dot11_phy_type_unknown = 0,
dot11_phy_type_any = dot11_phy_type_unknown,
dot11_phy_type_fhss = 1,
dot11_phy_type_dsss = 2,
dot11_phy_type_irbaseband = 3,
dot11_phy_type_ofdm = 4,
dot11_phy_type_hrdsss = 5,
dot11_phy_type_erp = 6,
dot11_phy_type_IHV_start = 0x80000000,
dot11_phy_type_IHV_end = 0xffffffff
} DOT11_PHY_TYPE, * PDOT11_PHY_TYPE;
#define DOT11_RATE_SET_MAX_LENGTH 126 // 126 bytes
typedef struct _WLAN_RATE_SET
{
ULONG uRateSetLength;
USHORT usRateSet[DOT11_RATE_SET_MAX_LENGTH];
} WLAN_RATE_SET, * PWLAN_RATE_SET;
typedef UCHAR DOT11_MAC_ADDRESS[6];
typedef struct _WLAN_BSS_ENTRY
{
DOT11_SSID dot11Ssid;
ULONG uPhyId;
DOT11_MAC_ADDRESS dot11Bssid;
DOT11_BSS_TYPE dot11BssType;
DOT11_PHY_TYPE dot11BssPhyType;
LONG lRssi;
ULONG uLinkQuality;
BOOLEAN bInRegDomain;
USHORT usBeaconPeriod;
ULONGLONG ullTimestamp;
ULONGLONG ullHostTimestamp;
USHORT usCapabilityInformation;
ULONG ulChCenterFrequency;
WLAN_RATE_SET wlanRateSet;
// the beginning of the IE blob
// the offset is w.r.t. the beginning of the entry
ULONG ulIeOffset;
// size of the IE blob
ULONG ulIeSize;
} WLAN_BSS_ENTRY, * PWLAN_BSS_ENTRY;
typedef struct _WLAN_BSS_LIST
{
// The total size of the data in BYTE
DWORD dwTotalSize;
DWORD dwNumberOfItems;
WLAN_BSS_ENTRY wlanBssEntries[1];
} WLAN_BSS_LIST, *PWLAN_BSS_LIST;
#pragma pack(pop)
//Used by RegisterPowerSettingNotification and UnegisterPowerSettingNotification
#ifndef HPOWERNOTIFY
typedef PVOID HPOWERNOTIFY;
typedef HPOWERNOTIFY *PHPOWERNOTIFY;
#endif // HPOWERNOTIFY
// Used by GetTouchInputInfo and CloseTouchHandle
#if(WINVER < 0x0601)
/*
* Gesture defines and functions
*/
/*
* Gesture information handle
*/
DECLARE_HANDLE(HGESTUREINFO);
/*
* Gesture flags - GESTUREINFO.dwFlags
*/
#define GF_BEGIN 0x00000001
#define GF_INERTIA 0x00000002
#define GF_END 0x00000004
/*
* Gesture IDs
*/
#define GID_BEGIN 1
#define GID_END 2
#define GID_ZOOM 3
#define GID_PAN 4
#define GID_ROTATE 5
#define GID_TWOFINGERTAP 6
#define GID_PRESSANDTAP 7
#define GID_ROLLOVER GID_PRESSANDTAP
/*
* Gesture information structure
* - Pass the HGESTUREINFO received in the WM_GESTURE message lParam into the
* GetGestureInfo function to retrieve this information.
* - If cbExtraArgs is non-zero, pass the HGESTUREINFO received in the WM_GESTURE
* message lParam into the GetGestureExtraArgs function to retrieve extended
* argument information.
*/
typedef struct tagGESTUREINFO {
UINT cbSize; // size, in bytes, of this structure (including variable length Args field)
DWORD dwFlags; // see GF_* flags
DWORD dwID; // gesture ID, see GID_* defines
HWND hwndTarget; // handle to window targeted by this gesture
POINTS ptsLocation; // current location of this gesture
DWORD dwInstanceID; // internally used
DWORD dwSequenceID; // internally used
ULONGLONG ullArguments; // arguments for gestures whose arguments fit in 8 BYTES
UINT cbExtraArgs; // size, in bytes, of extra arguments, if any, that accompany this gesture
} GESTUREINFO, *PGESTUREINFO;
typedef GESTUREINFO const * PCGESTUREINFO;
/*
* Gesture argument helpers
* - Angle should be a double in the range of -2pi to +2pi
* - Argument should be an unsigned 16-bit value
*/
#define GID_ROTATE_ANGLE_TO_ARGUMENT(_arg_) ((USHORT)((((_arg_) + 2.0 * 3.14159265) / (4.0 * 3.14159265)) * 65535.0))
#define GID_ROTATE_ANGLE_FROM_ARGUMENT(_arg_) ((((double)(_arg_) / 65535.0) * 4.0 * 3.14159265) - 2.0 * 3.14159265)
/*
* Gesture configuration structure
* - Used in SetGestureConfig and GetGestureConfig
* - Note that any setting not included in either GESTURECONFIG.dwWant or
* GESTURECONFIG.dwBlock will use the parent window's preferences or
* system defaults.
*/
typedef struct tagGESTURECONFIG {
DWORD dwID; // gesture ID
DWORD dwWant; // settings related to gesture ID that are to be turned on
DWORD dwBlock; // settings related to gesture ID that are to be turned off
} GESTURECONFIG, *PGESTURECONFIG;
/*
* Gesture configuration flags - GESTURECONFIG.dwWant or GESTURECONFIG.dwBlock
*/
/*
* Common gesture configuration flags - set GESTURECONFIG.dwID to zero
*/
#define GC_ALLGESTURES 0x00000001
/*
* Zoom gesture configuration flags - set GESTURECONFIG.dwID to GID_ZOOM
*/
#define GC_ZOOM 0x00000001
/*
* Pan gesture configuration flags - set GESTURECONFIG.dwID to GID_PAN
*/
#define GC_PAN 0x00000001
#define GC_PAN_WITH_SINGLE_FINGER_VERTICALLY 0x00000002
#define GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY 0x00000004
#define GC_PAN_WITH_GUTTER 0x00000008
#define GC_PAN_WITH_INERTIA 0x00000010
/*
* Rotate gesture configuration flags - set GESTURECONFIG.dwID to GID_ROTATE
*/
#define GC_ROTATE 0x00000001
/*
* Two finger tap gesture configuration flags - set GESTURECONFIG.dwID to GID_TWOFINGERTAP
*/
#define GC_TWOFINGERTAP 0x00000001
/*
* PressAndTap gesture configuration flags - set GESTURECONFIG.dwID to GID_PRESSANDTAP
*/
#define GC_PRESSANDTAP 0x00000001
#define GC_ROLLOVER GC_PRESSANDTAP
#define GESTURECONFIGMAXCOUNT 256 // Maximum number of gestures that can be included
// in a single call to SetGestureConfig / GetGestureConfig
#endif // (WINVER < 0x0601)
//Used by SHGetStockIconInfo
typedef struct _SHSTOCKICONINFO
{
DWORD cbSize;
HICON hIcon;
int iSysImageIndex;
int iIcon;
WCHAR szPath[MAX_PATH];
} SHSTOCKICONINFO;
typedef enum SHSTOCKICONID
{
SIID_DOCNOASSOC = 0, // document (blank page), no associated program
SIID_DOCASSOC = 1, // document with an associated program
SIID_APPLICATION = 2, // generic application with no custom icon
SIID_FOLDER = 3, // folder (closed)
SIID_FOLDEROPEN = 4, // folder (open)
SIID_DRIVE525 = 5, // 5.25" floppy disk drive
SIID_DRIVE35 = 6, // 3.5" floppy disk drive
SIID_DRIVEREMOVE = 7, // removable drive
SIID_DRIVEFIXED = 8, // fixed (hard disk) drive
SIID_DRIVENET = 9, // network drive
SIID_DRIVENETDISABLED = 10, // disconnected network drive
SIID_DRIVECD = 11, // CD drive
SIID_DRIVERAM = 12, // RAM disk drive
SIID_WORLD = 13, // entire network
SIID_SERVER = 15, // a computer on the network
SIID_PRINTER = 16, // printer
SIID_MYNETWORK = 17, // My network places
SIID_FIND = 22, // Find
SIID_HELP = 23, // Help
SIID_SHARE = 28, // overlay for shared items
SIID_LINK = 29, // overlay for shortcuts to items
SIID_SLOWFILE = 30, // overlay for slow items
SIID_RECYCLER = 31, // empty recycle bin
SIID_RECYCLERFULL = 32, // full recycle bin
SIID_MEDIACDAUDIO = 40, // Audio CD Media
SIID_LOCK = 47, // Security lock
SIID_AUTOLIST = 49, // AutoList
SIID_PRINTERNET = 50, // Network printer
SIID_SERVERSHARE = 51, // Server share
SIID_PRINTERFAX = 52, // Fax printer
SIID_PRINTERFAXNET = 53, // Networked Fax Printer
SIID_PRINTERFILE = 54, // Print to File
SIID_STACK = 55, // Stack
SIID_MEDIASVCD = 56, // SVCD Media
SIID_STUFFEDFOLDER = 57, // Folder containing other items
SIID_DRIVEUNKNOWN = 58, // Unknown drive
SIID_DRIVEDVD = 59, // DVD Drive
SIID_MEDIADVD = 60, // DVD Media
SIID_MEDIADVDRAM = 61, // DVD-RAM Media
SIID_MEDIADVDRW = 62, // DVD-RW Media
SIID_MEDIADVDR = 63, // DVD-R Media
SIID_MEDIADVDROM = 64, // DVD-ROM Media
SIID_MEDIACDAUDIOPLUS = 65, // CD+ (Enhanced CD) Media
SIID_MEDIACDRW = 66, // CD-RW Media
SIID_MEDIACDR = 67, // CD-R Media
SIID_MEDIACDBURN = 68, // Burning CD
SIID_MEDIABLANKCD = 69, // Blank CD Media
SIID_MEDIACDROM = 70, // CD-ROM Media
SIID_AUDIOFILES = 71, // Audio files
SIID_IMAGEFILES = 72, // Image files
SIID_VIDEOFILES = 73, // Video files
SIID_MIXEDFILES = 74, // Mixed files
SIID_FOLDERBACK = 75, // Folder back
SIID_FOLDERFRONT = 76, // Folder front
SIID_SHIELD = 77, // Security shield. Use for UAC prompts only.
SIID_WARNING = 78, // Warning
SIID_INFO = 79, // Informational
SIID_ERROR = 80, // Error
SIID_KEY = 81, // Key / Secure
SIID_SOFTWARE = 82, // Software
SIID_RENAME = 83, // Rename
SIID_DELETE = 84, // Delete
SIID_MEDIAAUDIODVD = 85, // Audio DVD Media
SIID_MEDIAMOVIEDVD = 86, // Movie DVD Media
SIID_MEDIAENHANCEDCD = 87, // Enhanced CD Media
SIID_MEDIAENHANCEDDVD = 88, // Enhanced DVD Media
SIID_MEDIAHDDVD = 89, // HD-DVD Media
SIID_MEDIABLURAY = 90, // BluRay Media
SIID_MEDIAVCD = 91, // VCD Media
SIID_MEDIADVDPLUSR = 92, // DVD+R Media
SIID_MEDIADVDPLUSRW = 93, // DVD+RW Media
SIID_DESKTOPPC = 94, // desktop computer
SIID_MOBILEPC = 95, // mobile computer (laptop/notebook)
SIID_USERS = 96, // users
SIID_MEDIASMARTMEDIA = 97, // Smart Media
SIID_MEDIACOMPACTFLASH = 98, // Compact Flash
SIID_DEVICECELLPHONE = 99, // Cell phone
SIID_DEVICECAMERA = 100, // Camera
SIID_DEVICEVIDEOCAMERA = 101, // Video camera
SIID_DEVICEAUDIOPLAYER = 102, // Audio player
SIID_NETWORKCONNECT = 103, // Connect to network
SIID_INTERNET = 104, // Internet
SIID_ZIPFILE = 105, // ZIP file
SIID_SETTINGS = 106, // Settings
// 107-131 are internal Vista RTM icons
// 132-159 for SP1 icons
SIID_DRIVEHDDVD = 132, // HDDVD Drive (all types)
SIID_DRIVEBD = 133, // BluRay Drive (all types)
SIID_MEDIAHDDVDROM = 134, // HDDVD-ROM Media
SIID_MEDIAHDDVDR = 135, // HDDVD-R Media
SIID_MEDIAHDDVDRAM = 136, // HDDVD-RAM Media
SIID_MEDIABDROM = 137, // BluRay ROM Media
SIID_MEDIABDR = 138, // BluRay R Media
SIID_MEDIABDRE = 139, // BluRay RE Media (Rewriable and RAM)
SIID_CLUSTEREDDRIVE = 140, // Clustered disk
// 160+ are for Windows 7 icons
SIID_MAX_ICONS = 174,
} SHSTOCKICONID;
#define SHGSI_ICON SHGFI_ICON
#define SHGSI_SMALLICON SHGFI_SMALLICON
//Used by SHOpenWithDialog
#define OAIF_HIDE_REGISTRATION 0x00000020 // hide the "always use this file" checkbox
#define OAIF_URL_PROTOCOL 0x00000040 // the "extension" passed is actually a protocol, and open with should show apps registered as capable of handling that protocol
#if defined(MEMTOOLS_ENABLE_CODELOC) && defined(MEMTOOLS_NO_DEFAULT_CODELOC) && defined(MEMORY_LOG_USAGE_PER_ALLOCATION_SITE)
//Used by SymFromAddr and SymGetLineFromAddr64
#include <Dbghelp.h>
#endif //defined(MEMTOOLS_ENABLE_CODELOC) && defined(MEMTOOLS_NO_DEFAULT_CODELOC) && defined(MEMORY_LOG_USAGE_PER_ALLOCATION_SITE)
//Please, keep this list ordered:
//The libraries appear in alphabetical order and procedures loaded from them appear under the corresponding library, also sorted alphabetically
//advapi32
LIBRARY_CALL(advapi32, BOOL, WINAPI, CreateProcessWithTokenW, (HANDLE hToken, DWORD dwLogonFlags, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInfo), (hToken, dwLogonFlags, lpApplicationName, lpCommandLine, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInfo), FALSE);
#if defined(MEMTOOLS_ENABLE_CODELOC) && defined(MEMTOOLS_NO_DEFAULT_CODELOC) && defined(MEMORY_LOG_USAGE_PER_ALLOCATION_SITE)
//dbghelp
LIBRARY_CALL(dbghelp, BOOL, WINAPI, SymFromAddr, (HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol), (hProcess, Address, Displacement, Symbol), FALSE);
LIBRARY_CALL(dbghelp, BOOL, WINAPI, SymGetLineFromAddr64, (HANDLE hProcess, DWORD64 dwAddr, PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line), (hProcess, dwAddr, pdwDisplacement, Line), FALSE);
LIBRARY_CALL(dbghelp, BOOL, WINAPI, SymInitialize, (HANDLE hProcess, PCTSTR UserSearchPath, BOOL fInvadeProcess), (hProcess, UserSearchPath, fInvadeProcess), FALSE);
LIBRARY_CALL(dbghelp, DWORD, WINAPI, SymSetOptions, (DWORD SymOptions), (SymOptions), -1);
#endif //defined(MEMTOOLS_ENABLE_CODELOC) && defined(MEMTOOLS_NO_DEFAULT_CODELOC) && defined(MEMORY_LOG_USAGE_PER_ALLOCATION_SITE)
//dwmapi
LIBRARY_CALL(dwmapi, BOOL, WINAPI, DwmDefWindowProc, (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, LRESULT *plResult), (hwnd, msg, wParam, lParam, plResult), FALSE);
LIBRARY_CALL(dwmapi, HRESULT, WINAPI, DwmExtendFrameIntoClientArea, (HWND hWnd, const MARGINS *pMarInset), (hWnd, pMarInset), E_NOTIMPL);
LIBRARY_CALL(dwmapi, HRESULT, WINAPI, DwmInvalidateIconicBitmaps, (HWND hwnd), (hwnd), E_NOTIMPL);
LIBRARY_CALL(dwmapi, HRESULT, WINAPI, DwmSetIconicLivePreviewBitmap, (HWND hwnd, HBITMAP hbmp, POINT *pptClient, DWORD dwSITFlags), (hwnd, hbmp, pptClient, dwSITFlags), E_NOTIMPL);
LIBRARY_CALL(dwmapi, HRESULT, WINAPI, DwmSetIconicThumbnail, (HWND hwnd, HBITMAP hbmp, DWORD dwSITFlags), (hwnd, hbmp, dwSITFlags), E_NOTIMPL);
LIBRARY_CALL(dwmapi, HRESULT, WINAPI, DwmSetWindowAttribute, (HWND hwnd, DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute), (hwnd, dwAttribute, pvAttribute, cbAttribute), E_NOTIMPL);
//kernel32
LIBRARY_CALL(kernel32, int, WINAPI, GetSystemDefaultLocaleName, (LPWSTR lpLocaleName, int cchLocaleName), (lpLocaleName, cchLocaleName), 0);
LIBRARY_CALL(kernel32, BOOL, WINAPI, SetProcessDEPPolicy, (DWORD dwFlags), (dwFlags), FALSE);
//ntdll
LIBRARY_CALL(ntdll, NTSTATUS, WINAPI, NtQueryInformationFile, (HANDLE FileHandle, IO_STATUS_BLOCK* IoStatusBlock, PVOID FileInformation, ULONG Length, NtDll::FILE_INFORMATION_CLASS FileInformationClass), (FileHandle, IoStatusBlock, FileInformation, Length, FileInformationClass), NT_STATUS_NOT_IMPLEMENTED);
LIBRARY_CALL(ntdll, NTSTATUS, WINAPI, NtQueryInformationProcess, (HANDLE ProcessHandle, NtDll::PROCESS_INFORMATION_CLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength), (ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength, ReturnLength), NT_STATUS_NOT_IMPLEMENTED);
LIBRARY_CALL(ntdll, NTSTATUS, WINAPI, NtQueryObject, (HANDLE Handle, NtDll::OBJECT_INFORMATION_CLASS ObjectInformationClass, PVOID ObjectInformation, ULONG ObjectInformationLength, PULONG ReturnLength), (Handle, ObjectInformationClass, ObjectInformation, ObjectInformationLength, ReturnLength), NT_STATUS_NOT_IMPLEMENTED);
LIBRARY_CALL(ntdll, NTSTATUS, WINAPI, NtQuerySystemInformation, (NtDll::SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength), (SystemInformationClass, SystemInformation, SystemInformationLength, ReturnLength), NT_STATUS_NOT_IMPLEMENTED);
LIBRARY_CALL(ntdll, NTSTATUS, WINAPI, NtSetInformationProcess, (HANDLE ProcessHandle, NtDll::PROCESS_INFORMATION_CLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength), (ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength), NT_STATUS_NOT_IMPLEMENTED);
//shell32
LIBRARY_CALL(shell32, HRESULT, WINAPI, SHCreateItemFromParsingName, (PCWSTR pszPath, IBindCtx *pbc, REFIID riid, void **ppv), (pszPath, pbc, riid, ppv), E_NOTIMPL);
LIBRARY_CALL(shell32, HRESULT, WINAPI, SHGetKnownFolderPath, (REFKNOWNFOLDERID rfid, DWORD dwFlags, HANDLE hToken, __out PWSTR *ppszPath), (rfid, dwFlags, hToken, ppszPath), E_NOTIMPL);
LIBRARY_CALL(shell32, HRESULT, WINAPI, SHGetStockIconInfo, (SHSTOCKICONID siid, UINT uFlags, __inout SHSTOCKICONINFO *psii), (siid, uFlags, psii), E_NOTIMPL);
LIBRARY_CALL(shell32, HRESULT, WINAPI, SHOpenWithDialog, (HWND hwndParent, const OPENASINFO *poainfo), (hwndParent, poainfo), E_NOTIMPL);
//user32
LIBRARY_CALL(user32, BOOL, WINAPI, CloseGestureInfoHandle, (HGESTUREINFO hGestureInfo), (hGestureInfo), FALSE);
LIBRARY_CALL(user32, BOOL, WINAPI, GetGestureInfo, (HGESTUREINFO hGestureInfo, PGESTUREINFO pGestureInfo), (hGestureInfo, pGestureInfo), FALSE);
LIBRARY_CALL(user32, HPOWERNOTIFY, WINAPI, RegisterPowerSettingNotification, (HANDLE hRecipient, LPCGUID PowerSettingGuid, DWORD Flags), (hRecipient, PowerSettingGuid, Flags), NULL);
LIBRARY_CALL(user32, BOOL, WINAPI, SetGestureConfig, (HWND hwnd, DWORD dwReserved, UINT cIDs, PGESTURECONFIG pGestureConfig, UINT cbSize), (hwnd, dwReserved, cIDs, pGestureConfig, cbSize), FALSE);
LIBRARY_CALL(user32, BOOL, WINAPI, ShutdownBlockReasonCreate, (HWND hWnd, LPCWSTR pwszReason), (hWnd, pwszReason), FALSE);
LIBRARY_CALL(user32, HPOWERNOTIFY, WINAPI, UnregisterPowerSettingNotification, (HPOWERNOTIFY Handle), (Handle), 0);
//uxtheme
LIBRARY_CALL(uxtheme, HRESULT, WINAPI, DrawThemeTextEx, (HTHEME theme, HDC hdc, int part, int state, LPCWSTR str, int len, DWORD dwFlags, LPRECT pRect, const DTTOPTS *pOptions), (theme, hdc, part, state, str, len, dwFlags, pRect, pOptions), E_NOTIMPL);
LIBRARY_CALL(uxtheme, HRESULT, WINAPI, SetWindowThemeAttribute, (HWND hwnd, enum WINDOWTHEMEATTRIBUTETYPE eAttribute, __in_bcount(cbAttribute) PVOID pvAttribute, DWORD cbAttribute), (hwnd, eAttribute, pvAttribute, cbAttribute), E_NOTIMPL);
LIBRARY_CALL(uxtheme, BOOL, WINAPI, BeginPanningFeedback, (HWND hwnd), (hwnd), FALSE);
LIBRARY_CALL(uxtheme, BOOL, WINAPI, EndPanningFeedback, (HWND hwnd, BOOL fAnimateBack), (hwnd, fAnimateBack), FALSE);
LIBRARY_CALL(uxtheme, BOOL, WINAPI, UpdatePanningFeedback, (HWND hwnd, LONG lTotalOverpanOffsetX, LONG lTotalOverpanOffsetY, BOOL fInInertia), (hwnd, lTotalOverpanOffsetX, lTotalOverpanOffsetY, fInInertia), FALSE);
//wlanapi
LIBRARY_CALL(wlanapi, DWORD, WINAPI, WlanCloseHandle, (HANDLE hClientHandle, PVOID pReserved), (hClientHandle, pReserved), ERROR_NOT_SUPPORTED);
LIBRARY_CALL(wlanapi, DWORD, WINAPI, WlanEnumInterfaces, (HANDLE hClientHandle, PVOID pReserved, PWLAN_INTERFACE_INFO_LIST *ppInterfaceList), (hClientHandle, pReserved, ppInterfaceList), ERROR_NOT_SUPPORTED);
LIBRARY_CALL(wlanapi, VOID, WINAPI, WlanFreeMemory, (PVOID pMemory), (pMemory), );
LIBRARY_CALL(wlanapi, DWORD, WINAPI, WlanGetNetworkBssList, (HANDLE hClientHandle, CONST GUID *pInterfaceGuid, CONST PDOT11_SSID pDot11Ssid, DOT11_BSS_TYPE dot11BssType, BOOL bSecurityEnabled, PVOID pReserved, PWLAN_BSS_LIST *ppWlanBssList), (hClientHandle, pInterfaceGuid, pDot11Ssid, dot11BssType, bSecurityEnabled, pReserved, ppWlanBssList), ERROR_NOT_SUPPORTED);
LIBRARY_CALL(wlanapi, DWORD, WINAPI, WlanOpenHandle, (DWORD dwClientVersion, PVOID pReserved, PDWORD pdwNegotiatedVersion, PHANDLE phClientHandle), (dwClientVersion, pReserved, pdwNegotiatedVersion, phClientHandle), ERROR_INVALID_FUNCTION);
|
#include "StdAfx.h"
#include "Gt2DSequence.h"
GnImplementRTTI(Gt2DSequence, Gn2DSequence);
Gt2DSequence::Gt2DSequence(void)
{
}
Gt2DSequence::~Gt2DSequence(void)
{
}
void Gt2DSequence::ChangeTextureFile(gtuint uiAniIndex, gtuint aniInfoIndex, const char* pcFileName)
{
SetModifed( true );
Gn2DTextureAni* ani = GetTextureAni( uiAniIndex );
Gn2DTextureAni::TextureAniInfo* textureAniInfo =
(Gn2DTextureAni::TextureAniInfo*)ani->GetAniInfo( aniInfoIndex );
textureAniInfo->SetTextureName( pcFileName );
ani->RemoveData();
}
void Gt2DSequence::ChangeTime(gtuint uiAniIndex, float fTime)
{
SetModifed( true );
Gn2DTextureAni* ani = GetTextureAni( uiAniIndex );
ani->SetAniSpeed( fTime );
}
bool Gt2DSequence::SaveData(const gchar* folderName, const gchar* pcBasePath)
{
for( gtuint i = 0 ; i < GetSequence()->GetTextureAnis().GetSize() ; i++ )
{
Gn2DTextureAni* ani = GetSequence()->GetTextureAnis().GetAt( i );
for( gtuint j = 0 ; j < ani->GetAniInfoCount() ; j++ )
{
Gn2DTextureAni::TextureAniInfo* aniInfo = (Gn2DTextureAni::TextureAniInfo*)ani->GetAniInfo( j );
GtNumberString number;
number.SetNumber( 3, GetSequence()->GetID() );
GtConvertString convert = number.GetString().c_str();
convert += _T("_");
gchar name[GN_MAX_PATH] = { 0, };
GnVerify( GnPath::GetFileNameA( aniInfo->GetTextureName(), name, GN_MAX_PATH, true ) );
std::string fileName = name;
if( fileName.find( convert.GetAciiString() ) == std::string::npos )
{
fileName = convert.GetAciiString();
fileName += name;
}
std::string copyFilePath = pcBasePath;
copyFilePath += fileName;
if( GnPath::CheckSamePathA( aniInfo->GetTextureName(), copyFilePath.c_str() ) == false )
{
BOOL ret = CopyFileA( aniInfo->GetTextureName(), copyFilePath.c_str(), false );
ret = TRUE;
}
std::string filePath = gsActorPath;
filePath += folderName;
filePath += "/";
filePath += fileName;
aniInfo->SetTextureName( filePath.c_str() );
}
}
std::string fullFilePath = GtToolSettings::GetWorkPath();
fullFilePath += mFileName.GetAciiString();
GnObjectStream objectStream;
objectStream.InsertRootObjects( mpSequence );
GnVerify( objectStream.Save( fullFilePath.c_str() ) );
objectStream.Close();
return true;
}
void Gt2DSequence::SetObjectName(const gchar* pcVal)
{
GtObject::SetObjectName( pcVal );
mFileName = pcVal;
mFileName += _T(".ga");
}
|
/** Kabuki SDK
@file /.../Source/Kabuki_SDK-Impl/_G/Layer.h
@author Cale McCollough
@copyright Copyright 2016 Cale McCollough ©
@license Read accompanying /.../README.md or online at http://www.boost.org/LICENSE_1_0.txt
*/
#include "Entity.h"
namespace _G {
/** */
struct Layer
{
Entity& Element; //< The element of this layer.
Layer* Prev, //< The previous layer in the pipeline.
* Next; //< The next layer in the pipeline.
/** */
void Remove ();
/** */
void Draw (const Cell& C);
};
}
|
#include "aeResourceManager.h"
namespace aeEngineSDK
{
aeTexture2DResource::aeTexture2DResource()
{
}
aeTexture2DResource::aeTexture2DResource(const aeTexture2DResource &TR)
{
*this = TR;
}
aeTexture2DResource::~aeTexture2DResource()
{
}
void aeTexture2DResource::Release()
{
}
inline void aeTexture2DResource::SetType(AE_TEXTURE_TYPE Type)
{
return m_pTexture->SetType(Type);
}
inline AE_ENGINE_RESOURCE_ID aeTexture2DResource::GetID() const
{
return AE_ENGINE_RESOURCE_ID::AE_ENGINE_RESOURCE_TEXTURE_2D;
}
inline String aeTexture2DResource::GetName() const
{
return m_pTexture->GetName();
}
inline AE_TEXTURE_TYPE aeTexture2DResource::GetType()
{
return m_pTexture->GetType();
}
}
|
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
int visited[51] = {
0,
};
bool wordFind(const string &curStr, const string &nextStr, const int &wSize) {
int overlapCnt = 0;
for (int i = 0; i < wSize; i++) {
if (curStr[i] == nextStr[i]) {
overlapCnt++;
}
}
return overlapCnt == wSize - 1;
}
int solution(string begin, string target, vector<string> words) {
int answer = 0;
int size = words.size();
int wSize = begin.size();
queue<pair<string, int>> q;
q.push(make_pair(begin, 0));
while (!q.empty()) {
string curStr = q.front().first;
int curIdx = q.front().second;
q.pop();
for (int i = 0; i < size; i++) {
if (visited[i] != 0) continue;
if (wordFind(curStr, words[i], wSize)) {
visited[i] = curIdx + 1;
if(words[i].compare(target) == 0){
return visited[i];
}
q.push(make_pair(words[i], visited[i]));
}
}
}
return 0;
}
int main() {
// cout << solution("hit", "cog",
// {"hot", "dot", "dog",
// "lot"
// "log",
// "cog"})
// << '\n';
cout << solution("hit", "cog",
{"hot", "dot", "dog",
"lot"
"log"})
<< '\n';
return 0;
}
|
#include<iostream>
#include<cmath>
class Fraction
{
private:
int numerator, denominator;
public:
Fraction()
{
numerator = 1;
denominator = 1;
}
Fraction(int n, int d)
{
if(d==0){
numerator=0;
denominator=0;
throw "ERROR: ATTEMPTING TO DIVIDE BY ZERO";
}
else
{
numerator = n;
denominator =d;
}
}
Fraction Sum(Fraction otherFraction)
{
int n = numerator * otherFraction.denominator + otherFraction.numerator * denominator;
int d = denominator * otherFraction.denominator;
int tmp=gcd(n,d); return Fraction(n / tmp,d/tmp);
}
Fraction Difference(Fraction otherFraction)
{
int n = numerator * otherFraction.denominator - otherFraction.numerator * denominator;
int d = denominator * otherFraction.denominator;
int tmp=gcd(n,d); return Fraction(n / tmp,d/tmp);
}
Fraction multiplication(Fraction otherFraction)
{
int n = numerator * otherFraction.numerator;
int d = denominator * otherFraction.denominator;
int tmp=gcd(n,d); return Fraction(n / tmp,d/tmp);
}
Fraction Division(Fraction otherFraction)
{
int n = numerator * otherFraction.denominator;
int d = denominator * otherFraction.numerator;
int tmp=gcd(n,d); return Fraction(n / tmp,d/tmp);
}
Fraction NOD(Fraction otherFraction)
{
int n = numerator * otherFraction.denominator;
int d = denominator * otherFraction.numerator;
int remainder;
while (d != 0)
{
remainder = n % d;
n = d;
d = remainder;
}
return Fraction( gcd_1(n, d), gcd_1(n, d));
}
int gcd_1(int n, int d) {
return n ;
}
int gcd(int n, int d)
{
if (n<1){
n =-n;
}
if (d<1){
d =-d;
}
int remainder;
while (d != 0)
{
remainder = n % d;
n = d;
d = remainder;
}
return n;
}
void show()
{
if (denominator == 1)
std::cout << numerator << std::endl;
else
std::cout << numerator << "/" << denominator << std::endl;
}
};
int main()
{
try
{
Fraction a(2, 3);
Fraction b(1, 4);
Fraction c;
Fraction d(4, 6);
Fraction f(1, 1);
a.show(); // Result: 2/3
c = a.Sum(b); // Result: 11/12
c.show();
c = a.Difference(b);
c = c.multiplication(a.Sum(b));
c = c.Division(a.Sum(b)); // Result: 5/12
c.show();
d = d.Division(f); // Result: 2/3
d.show();
}
catch(const char* str)
{
std::cout<<str<<std::endl;
}
return 0;
}
|
#pragma once
#include "ElementSketch.h"
namespace siu {
/**
* Элемент эскиза в виде цельного физического тела.
*/
struct PhysicsSolidES : public ElementSketch {
typedef double density_t;
explicit inline PhysicsSolidES(
const std::string& nick
) :
ElementSketch( nick ),
density( 0.0 )
{
}
inline ~PhysicsSolidES() {
}
/**
* Плотность тела, кг / м^3.
*/
density_t density;
/**
* @return Масса тела.
*/
virtual double mass() const = 0;
/**
* @return Объём тела, м^3.
*/
virtual double volume() const = 0;
};
}
|
/*
Given a binary search tree and data of two nodes, find 'LCA' (Lowest Common Ancestor) of the given two nodes in the BST.
LCA
LCA of two nodes A and B is the lowest or deepest node which has both A and B as its descendants.
Note:
1. If out of 2 nodes only one node is present, return that node.
2. If both are not present, return -1.
Input format:
The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is
separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication
whether the left or right nodes exist, therefore, it will not be a part of the data of any node.
The following line of input contains two integers, denoting the value of data of two nodes of given BST.
Output Format:
The first and only line of output contains the data associated with the lowest common ancestor node.
Constraints:
Time Limit: 1 second
Sample Input 1:
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
2 10
Sample Output 1:
8
Sample Input 2:
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
2 6
Sample Output 2:
5
Sample Input 3:
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
12 78
Sample Output 3:
-1
*/
#include<bits/stdc++.h>
using namespace std;
class BinaryTreeNode{
public:
int data;
BinaryTreeNode* left;
BinaryTreeNode* right;
BinaryTreeNode(int data){
this -> data = data;
this -> left = NULL;
this -> right = NULL;
}
};
int LCAofBST(BinaryTreeNode* root,int n1,int n2){
if(root == NULL){
return -1;
}
if(root -> data == n1 || root -> data == n2){
return root -> data;
}else if(root -> data > n1 && root -> data > n2){
return LCAofBST(root -> left,n1,n2);
}else if(root -> data < n1 && root -> data < n2){
return LCAofBST(root -> right,n1,n2);
}else{
int leftans = LCAofBST(root -> left,n1,n2);
int rightans = LCAofBST(root -> right,n1,n2);
if(leftans == -1 && rightans == -1){
return -1;
}else if(leftans != -1 && rightans == -1){
return leftans;
}else if(leftans == -1 && rightans != -1){
return rightans;
}else{
return root -> data;
}
}
}
int main(){
BinaryTreeNode* root = new BinaryTreeNode(4);
root -> left = new BinaryTreeNode(2);
root -> right = new BinaryTreeNode(6);
root -> left -> left = new BinaryTreeNode(1);
root -> left -> right = new BinaryTreeNode(3);
root -> right -> left = new BinaryTreeNode(5);
root -> right -> right = new BinaryTreeNode(7);
int a,b;
cin >> a >> b;
cout << LCAofBST(root,a,b) << endl;
return 0;
}
|
// https://oj.leetcode.com/problems/spiral-matrix/
class Solution {
void find_order(vector<vector<int> > &matrix, vector<int> &ret,
int row_from, int row_to, int col_from, int col_to) {
if (row_from > row_to || col_from > col_to) {
return;
}
// go right
for (int i = col_from; i <= col_to; i++) {
ret.push_back(matrix[row_from][i]);
}
// go down
for (int i = row_from + 1; i <= row_to; i++) {
ret.push_back(matrix[i][col_to]);
}
// go left
if (row_from < row_to) {
for (int i = col_to - 1; i >= col_from; i--) {
ret.push_back(matrix[row_to][i]);
}
}
// go up
if (col_from < col_to) {
for (int i = row_to - 1; i > row_from; i--) {
ret.push_back(matrix[i][col_from]);
}
}
find_order(matrix, ret, row_from + 1, row_to - 1, col_from + 1, col_to - 1);
}
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> ret;
if (matrix.size() == 0) {
return ret;
}
int m = matrix.size(), n = matrix[0].size();
find_order(matrix, ret, 0, m - 1, 0, n - 1);
return ret;
}
};
|
#include "clockMenus.h"
int clockMenus::checkKeyPress() {
if ((GetAsyncKeyState(0x51) & 0x01)) { // 'q' key for 'quit'
return 0;
}
else if ((GetAsyncKeyState(0x49) & 0x01)) { // 'i' key for 'info'
return 3;
}
else if ((GetAsyncKeyState(0x4C) & 0x01)) {
return 4;
}
else { // nada, keep going
return 1;
}
}
|
#include <iostream>
#include <cstdio>
#include <assert.h>
int main() {
freopen("crypto.in", "r", stdin);
freopen("crypto.out", "w", stdout);
int n, a, b;
long long ans = -1;
int outx, outy;
std::cin >> n >> a >> b;
for (int x = 1; x <= n; ++x) {
for (int y = x; y; y = (y - 1) & x) {
long long t = ((long long)a * x + (long long)b * y) ^ ((long long)a * y + (long long)b * x);
if (t > ans) {
ans = t;
outx = x;
outy = y;
}
}
}
std::cout << outx << " " << outy << "\n";
return 0;
}
|
#pragma once
#include <string>
#include <sstream>
class Converter
{
public:
static std::string intToString(int);
};
|
#include <iostream>
#include "Execute.h"
using namespace std;
char* catalog_path = "catalog";
char* dbfile_dir = "bin/";
char* tpch_dir = "../tables";
int main (int argc, char* argv[]) {
Execute execute;
execute.run();
return 0;
}
|
/*
** EPITECH PROJECT, 2018
** cpp_indie_studio
** File description:
** Map.cpp
*/
#include "Map.hpp"
void Map::createMap(int width, int height)
{
std::vector<MapCase> v;
struct MapCase m;
m._food = 0;
m._stone1 = 0;
m._stone2 = 0;
m._stone3 = 0;
m._stone4 = 0;
m._stone5 = 0;
m._stone6 = 0;
for(int i = 0; i < width; i++) {
v.push_back(m);
}
for(int i = 0; i < height; i++){
_map.push_back(v);
}
}
void Map::updateMap(char **infos)
{
if (!infos[1] || !infos[2] || !infos[3]
|| !infos[4] || !infos[5] || !infos[6]
|| !infos[7] || !infos[8] || !infos[9])
return;
Point point(atoi(infos[1]), atoi(infos[2]));
if (this->isInMap(point)) {
struct MapCase items;
items._food = atoi(infos[3]);
items._stone1 = atoi(infos[4]);
items._stone2 = atoi(infos[5]);
items._stone3 = atoi(infos[6]);
items._stone4 = atoi(infos[7]);
items._stone5 = atoi(infos[8]);
items._stone6 = atoi(infos[9]);
_map[point.y()][point.x()] = items;
}
}
Map::MapCase Map::getCase(Point const & pos) const
{
MapCase DEFAULT_CASE;
DEFAULT_CASE._food = 0;
DEFAULT_CASE._stone1 = 0;
DEFAULT_CASE._stone2 = 0;
DEFAULT_CASE._stone3 = 0;
DEFAULT_CASE._stone4 = 0;
DEFAULT_CASE._stone5 = 0;
DEFAULT_CASE._stone6 = 0;
int x = pos.getX();
int y = pos.getY();
if (y < 0 || y >= static_cast<int>(this->_map.size()))
return DEFAULT_CASE;
else if (x < 0 || x >= static_cast<int>(this->_map[y].size()))
return DEFAULT_CASE;
return this->_map[y][x];
}
void Map::setCase(Point const & pos, MapCase items)
{
if (!this->isInMap(pos)) {
return;
}
_map[pos.y()][pos.x()] = items;
}
std::vector<std::vector<Map::MapCase>> Map::getMapCase() const
{
return _map;
}
bool Map::isInMap(Point pos)
{
if (0 <= pos.getY() && pos.getY() < static_cast<int>(_map.size())) {
if (0 <= pos.getX() && pos.getX() < static_cast<int>(_map[pos.getY()].size()))
return (true);
}
return (false);
}
Map::Map(const std::vector<std::vector<Map::MapCase>> &map)
{
this->_map = map;
}
std::ostream & operator<<(std::ostream & os, Map const & map)
{
auto mymap = map.getMapCase();
os << "Map:\n";
for(size_t i = 0; i < mymap.size(); i++)
{
os << "{\n";
for(size_t j = 0; j < mymap[i].size(); j++)
{
os << "\t{\n";
os << "\t\t" << mymap[i][j]._food << "\n";
os << "\t\t" << mymap[i][j]._stone1 << "\n";
os << "\t\t" << mymap[i][j]._stone2 << "\n";
os << "\t\t" << mymap[i][j]._stone3 << "\n";
os << "\t\t" << mymap[i][j]._stone4 << "\n";
os << "\t\t" << mymap[i][j]._stone5 << "\n";
os << "\t\t" << mymap[i][j]._stone6 << "\n";
os << "\t}\n";
}
os << "}\n";
}
os << "\n";
return os;
}
Point Map::getMapSize(void) const noexcept
{
if (_map.size() <= 0)
return { 0, 0 };
return { (int)_map[0].size(), (int)_map.size() };
}
|
#pragma once
#include "ISceneChanger.h"
#include "object\Object.h"
#include <array>
#include <vector>
#include <memory>
#include "Image.h"
#include "Sound.h"
#include "misc\Input.h"
using namespace std;
class Scene {
protected:
bool CustomObjectActive;
bool IsActive;
int sceneCounter;
ISceneChanger *mChanger;
vector<vector<Object*>> mObjs;
public:
Scene() = delete;
Scene(ISceneChanger *changer, Param ¶m);
virtual ~Scene();
virtual void Init();
virtual void Fin();
virtual void Update();
virtual void Draw() const;
bool IsSceneActive() const;
void SetCustomObjectActive(bool active);
};
|
#include <iostream>
#include <queue>
using namespace std;
struct Node
{
int data;
struct Node *left, *right;
};
void print(Node* root)
{
if (root == nullptr)
return;
// 队列是FIFO,所以能保证按照parent,left,right方式打印
std::queue<Node*> printing_queue;
printing_queue.push(root);
while (!printing_queue.empty())
{
//打印最前面的节点
Node* cur_node = printing_queue.front();
std::cout << cur_node->data << " ";
printing_queue.pop();
if (cur_node->left != nullptr)
{
printing_queue.push(cur_node->left);
}
if (cur_node->right != nullptr)
{
printing_queue.push(cur_node->right);
}
}
std::cout << std::endl;
}
Node* new_node(int data)
{
Node* node = new Node;
node->data = data;
node->left = nullptr;
node->right = nullptr;
return node;
}
int main()
{
Node* root = new_node(1);
root->left = new_node(2);
root->left->left = new_node(3);
root->left->right = new_node(4);
root->left->right->right = new_node(5);
print(root);
return 0;
}
|
#include "CGame.h"
#define VAR_CGame__currArea 0xB72914
__int32& CGame::currArea = *(__int32*)VAR_CGame__currArea;
void CGame::TidyUpMemory(bool arg1, bool arg2)
{
((void (__cdecl *)(bool, bool))0x53C500)(arg1, arg2);
}
|
#include "stdafx.h"
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <vector>
#include "connection.hpp" // Must come before boost/serialization headers.
#include <boost/serialization/vector.hpp>
#include "stock.hpp"
/// The data to be sent to each client.
std::vector<stock> g_stocks;
/// Serves stock quote information to any client that connects to it.
class server
{
public:
/// Constructor opens the acceptor and starts waiting for the first incoming
/// connection.
server(boost::asio::io_service& io_service, unsigned short port)
: acceptor_(io_service,
boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
{
// Start an accept operation for a new connection.
connection_ptr new_conn(new connection(io_service));
acceptor_.async_accept(new_conn->lowest_layer (),
boost::bind(&server::handle_accept, this,
boost::asio::placeholders::error, new_conn));
}
/// Handle completion of a accept operation.
void handle_accept(const boost::system::error_code& error, connection_ptr conn)
{
if (!error)
{
// Successfully accepted a new connection. Send the list of stocks to the
// client. The connection::async_write() function will automatically
// serialize the data structure for us.
conn->async_write(g_stocks,
boost::bind(&server::handle_write, this,
boost::asio::placeholders::error, conn));
// Start an accept operation for a new connection.
connection_ptr new_conn(new connection(acceptor_.io_service()));
acceptor_.async_accept(new_conn->lowest_layer (),
boost::bind(&server::handle_accept, this,
boost::asio::placeholders::error, new_conn));
}
else
{
// An error occurred. Log it and return. Since we are not starting a new
// accept operation the io_service will run out of work to do and the
// server will exit.
std::cerr << error.message() << std::endl;
}
}
/// Handle completion of a write operation.
void handle_write(const boost::system::error_code& e, connection_ptr conn)
{
if(e)
{
std::cerr << e.message() << std::endl;
return;
}
conn->async_write(g_stocks,
boost::bind(&server::handle_write, this,
boost::asio::placeholders::error, conn));
// Nothing to do. The socket will be closed automatically when the last
// reference to the connection object goes away.
}
private:
/// The acceptor object used to accept incoming socket connections.
boost::asio::ip::tcp::acceptor acceptor_;
};
boost::function0<void> console_ctrl_function;
BOOL WINAPI console_ctrl_handler(DWORD ctrl_type)
{
switch (ctrl_type)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_SHUTDOWN_EVENT:
console_ctrl_function();
return TRUE;
default:
return FALSE;
}
}
void init_stocks()
{
// Create the data to be sent to each client.
stock s;
s.code = "ABC";
s.name = "A Big Company";
s.open_price = 4.56;
s.high_price = 5.12;
s.low_price = 4.33;
s.last_price = 4.98;
s.buy_price = 4.96;
s.buy_quantity = 1000;
s.sell_price = 4.99;
s.sell_quantity = 2000;
g_stocks.push_back(s);
s.code = "DEF";
s.name = "Developer Entertainment Firm";
s.open_price = 20.24;
s.high_price = 22.88;
s.low_price = 19.50;
s.last_price = 19.76;
s.buy_price = 19.72;
s.buy_quantity = 34000;
s.sell_price = 19.85;
s.sell_quantity = 45000;
g_stocks.push_back(s);
}
int main(int argc, char* argv[])
{
try
{
// Check command line arguments.
if (argc != 3)
{
std::cerr << "Usage: server <threads> <port>" << std::endl;
return 1;
}
init_stocks();
unsigned short threadcount = boost::lexical_cast<unsigned short>(argv[1]);
unsigned short port = boost::lexical_cast<unsigned short>(argv[2]);
boost::asio::io_service io_service;
server svr(io_service, port);
// Set console control handler to allow server to be stopped.
console_ctrl_function = boost::bind(&boost::asio::io_service::stop, boost::ref(io_service));
SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
boost::thread_group threads_;
for (int i = 0; i!= threadcount; ++i)
threads_.create_thread ( boost::bind( &boost::asio::io_service::run, boost::ref(io_service)) );
threads_.join_all();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
//
// Copyright (C) 1995-2003 Opera Software ASA. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Morten Stenshorne, Espen Sand
//
// Platform dependency: UNIX
#ifndef __EXTERNAL_APPLICATION_H__
#define __EXTERNAL_APPLICATION_H__
#include "modules/util/opstring.h"
#include "modules/util/adt/opvector.h"
/**
* Utility class for starting/handling external applications (email client,
* helper applications, source viewer etc.)
* It is safe to delete an ExternalApp object while the external application
* is running.
*/
class ExternalApplication
{
private:
const BOOL spawn;
uni_char *m_cmdline;
public:
/** Handler for an external command.
* @param cmdline the command line as a single unicode string
* @param disown default is TRUE, meaning processes running the
* command should die quietly when complete; if set to FALSE, the
* process which runs the command will, on exit, send the Opera
* process a SIGCHLD and survive as a defunct process until
* wait()ed for - this enables the Opera process to garner
* information such as its exit status, but obliges the Opera
* process to handle SIGCHLD and wait() for such children.
*/
ExternalApplication(const uni_char* cmdline, BOOL disown=TRUE);
/**
* Destructor. Releases any allocated resources
*/
~ExternalApplication();
/**
* Runs the application, with an optional argument
*
* @param (optional) argument. May be NULL.
* @param fd Filedescriptor for error reporting
*
* @return 0 on success, otherwise -1. The global variable errno will
* hold the error code.
*/
int run( const uni_char* argument, int fd=-1, const char* encoding=0 );
/**
* Runs the application, with argument (not optional)
*
* @param list Argument list.
* @param fd Filedescriptor for error reporting
* @param disown Whether child running application should detach from
* parent. Default is true. If given as false, child will not exit until
* parent process wait()s for it.
*
* @return 0 on success, otherwise -1. The global variable errno will
* hold the error code.
*/
static int run( const OpVector<OpString>& list, int fd=-1, BOOL disown=TRUE, const char* encoding=0 );
/**
* Runs the application, with argument (not optional)
*
* @param argv Argument list.
* @param fd Filedescriptor for error reporting
* @param disown Whether child running application should detach from
* parent. Default is true. If given as false, child will not exit until
* parent process wait()s for it.
*
* @return 0 on success, otherwise -1. The global variable errno will
* hold the error code.
*/
static int run( uni_char **argv, int fd=-1, BOOL disown=TRUE, const char* encoding=0 );
/**
* Parse a command line and split it into argument strings.
* @param cmdline the original command line - e.g. "xterm -e pine"
* @param argument optional argument to the application. May be NULL.
* @return an array of ASCIIZ strings that are meant to be passed to
* an exec() function. IMPORTANT: The caller must delete this string
* array when it's done with it!
* The last element in the array is a NULL pointer
*/
static uni_char **parseCmdLine(const uni_char *cmdline,
const uni_char *argument);
/**
* Delete a string array and all the strings in that array.
* The last array element must be NULL.
*
* @param array the array. May be NULL.
*/
static void deleteArray(uni_char **array);
};
#endif
|
namespace my {
template<typename T>
class complex {
public:
complex(T const& re = T{}, T const& im = T{});
complex(complex const&);
template<typename U>
complex(complex<U> const&);
complex<T> &operator=(complex const&);
complex<T> &operator=(T const&);
complex<T> &operator+=(T const&);
template<typename U>
complex<U> &operator=(complex<U> const&);
};
template<>
class complex<float> {
public:
// ...
complex<float> &operator=(float);
complex<float> &operator+=(float);
};
template<>
class complex<double> {
public:
constexpr complex(double re = 0.0, double im = 0.0);
constexpr complex(complex<float> const&); // safe -> no explicit
explicit constexpr complex(complex<long double> const&); // not safe -> explicit
};
}
|
#include <QHostAddress>
#include "buttonadapter.h"
ButtonAdapter::ButtonAdapter(QObject *parent) : AdapterBase(parent)
{
setDataPort(&m_tcpSocket);
}
void ButtonAdapter::setAddress(QString address)
{
if (m_address == address)
return;
m_tcpSocket.connectToHost(QHostAddress(address), 5555);
if(m_tcpSocket.waitForConnected(2000))
getStatus();
m_address = address;
emit addressChanged(m_address);
}
void ButtonAdapter::setStatus(ButtonState status)
{
if (m_status == status)
return;
MessageParam message;
message.type = MESSAGE_SET_PARAM;
message.paramNb = 0;
message.ui32Value = static_cast<uint32_t>(status);
char *tmp = reinterpret_cast<char*>(&message);
QByteArray result = sendMessage(tmp, sizeof(message));
if(result.length() > 0) {
if(result.length() != sizeof(MessageResult))
return;
MessageResult answer;
memcpy(reinterpret_cast<char*>(&answer), result.data(), sizeof(MessageResult));
if(answer.result == 1)
{
m_status = status;
emit statusChanged(m_status);
}
}
}
void ButtonAdapter::customProcessMessage(QByteArray message)
{
Q_UNUSED(message)
}
void ButtonAdapter::open(QString portName)
{
Q_UNUSED(portName)
}
void ButtonAdapter::close()
{
}
QString ButtonAdapter::address() const
{
return m_address;
}
ButtonAdapter::ButtonState ButtonAdapter::status() const
{
return m_status;
}
QJSValue ButtonAdapter::getStatus()
{
QJSValue status;
MessageCommand message;
message.type = MESSAGE_GET_PARAM;
char *tmp = reinterpret_cast<char*>(&message);
QByteArray result = sendMessage(tmp, sizeof(message));
if(result.length() == 0)
m_errorTransmitCounter++;
else
m_errorTransmitCounter = 0;
setIsConnected(m_errorTransmitCounter < 3);
if(result.length() > 0) {
if(result.length() != sizeof(MessageParam))
return status;
MessageParam answer;
memcpy(reinterpret_cast<char*>(&answer), result.data(), sizeof(MessageParam));
status.setProperty("status", answer.ui32Value);
qDebug() << answer.ui32Value;
setStatus(answer.ui32Value > 0 ? BUTTON_ON : BUTTON_OFF);
return status;
}
return status;
}
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int x):val(x),next(NULL){}
};
void printLL(ListNode* head){
ListNode* temp = head;
while(temp!=NULL){
cout<<temp->val<<"->";
temp = temp->next;
}
}
ListNode* addNode(ListNode* head, int val){
if(head==NULL){
head = new ListNode(val);
}
else{
ListNode* temp = head;
while(temp->next!=NULL){
temp = temp->next;
}
temp->next = new ListNode(val);
}
return head;
}
void print(vector<int>&v){
int n = v.size();
for(int i =0;i<n;i++){
cout<<v[i]<<" ";
}
}
ListNode* merger(ListNode* head1, ListNode* head2){
ListNode* t1 = head1;
ListNode* t2 = head2;
ListNode* head = NULL;
ListNode* curr;
curr = head;
}
int main(){
ListNode *head1 = NULL;
ListNode *head2 = NULL;
ListNode *head;
int n;
cin>>n;
for(int i =0;i<n;i++){
int val;
cin>>val;
head1 = addNode(head1,val);
}
for(int i =0;i<n;i++){
int val;
cin>>val;
head2 = addNode(head2,val);
}
printLL(head1);
printLL(head2);
head = merger(head1,head2);
printLL(head);
}
|
/*
* Robot_Thread.cpp
*
* Created on: 25 janv. 2012
* Author: adrien
*/
#include "Robot_Thread.h"
#include <pthread.h>
#include <math.h>
#include <semaphore.h>
#include <iostream>
sem_t sem_pos;
/* Permet de stocker la position actuelle du robot 1 */
Robot robot1;
/* Permet de stocker la position actuelle du robot 2 */
Robot robot2;
Robot_Thread::Robot_Thread()
{
mq_attr att;
att.mq_maxmsg = 10;
att.mq_msgsize = sizeof(Msg_Com_Robot);
bal_com_robot = mq_open(BAL_COM_ROBOT, O_RDONLY | O_CREAT | O_NONBLOCK, S_IRWXU, &att);
att.mq_msgsize = sizeof(Msg_Vid_Robot);
bal_video_robot = mq_open(BAL_VIDEO_ROBOT, O_RDONLY | O_NONBLOCK | O_CREAT, S_IRWXU, &att);
att.mq_msgsize = sizeof(Msg_Robot_IA);
bal_robot_ia = mq_open(BAL_ROBOT_IA, O_WRONLY | O_CREAT, S_IRWXU, &att);
sem_init(&sem_pos, 0, 1); // TODO Faire ça ailleurs, (il y a des hotels pour ça :D)
}
Robot_Thread::~Robot_Thread()
{
pthread_cancel(thread);
mq_close(bal_com_robot);
mq_close(bal_video_robot);
mq_close(bal_robot_ia);
mq_unlink(BAL_ROBOT_IA);
sem_close(&sem_pos);
}
void Robot_Thread::Launch()
{
pthread_create(&thread, NULL, Robot_Thread::exec, this);
}
void Robot_Thread::run()
{
Msg_Com_Robot msg_com_robot;
Msg_Vid_Robot msg_vid_robot;
timespec delay;
delay.tv_nsec = 1000000; // TODO : Temporaire
delay.tv_sec = 0;
for ( ; ; )
{
bool modified = false;
if (mq_timedreceive(bal_com_robot, (char*)&msg_com_robot, sizeof(Msg_Com_Robot), NULL, &delay) != -1)
{
modified = true;
setNewPosition(robot1, msg_com_robot.robot1);
setNewPosition(robot2, msg_com_robot.robot2);
}
if (mq_receive(bal_video_robot, (char*)&msg_vid_robot, sizeof(Msg_Vid_Robot), NULL) != -1)
{
modified = true;
copyPositions(msg_vid_robot.robot1, msg_vid_robot.robot2, msg_vid_robot.balle);
}
if (modified)
{
Msg_Robot_IA msg_robot_ia;
msg_robot_ia.robot1.angle = robot1.angle;
msg_robot_ia.robot1.pos_x = robot1.pos_x;
msg_robot_ia.robot1.pos_y = robot1.pos_y;
msg_robot_ia.robot2.angle = robot2.angle;
msg_robot_ia.robot2.pos_x = robot2.pos_x;
msg_robot_ia.robot2.pos_y = robot2.pos_y;
msg_robot_ia.balle.pos_x = balle.pos_x;
msg_robot_ia.balle.pos_y = balle.pos_y;
msg_robot_ia.balle.vit_x = balle.vit_x;
msg_robot_ia.balle.vit_y = balle.vit_y;
std::cout << "position robot1 : " << msg_robot_ia.robot1.pos_x << ", " << msg_robot_ia.robot1.pos_y << ", " << msg_robot_ia.robot1.angle << std::endl;
std::cout << "position robot2 : " << msg_robot_ia.robot2.pos_x << ", " << msg_robot_ia.robot2.pos_y << ", " << msg_robot_ia.robot2.angle << std::endl;
mq_send(bal_robot_ia, (char*)&msg_robot_ia, sizeof(Msg_Robot_IA), 0);
}
}
}
void* Robot_Thread::exec(void* robot_thread)
{
Robot_Thread* thread = (Robot_Thread*)robot_thread;
thread->run();
return 0;
}
void Robot_Thread::setNewPosition(Robot& robot, Pas_Robot pas_robot)
{
sem_wait(&sem_pos);
if (pas_robot.pas_droite < pas_robot.pas_gauche)
{
int pas_angle = (pas_robot.pas_gauche - pas_robot.pas_droite) / 2;
robot.pos_x += (pas_robot.pas_droite + pas_angle) * CONVERSION_LONGUEUR * cos(robot.angle * M_PI / 180);
robot.pos_y += (pas_robot.pas_droite + pas_angle) * CONVERSION_LONGUEUR * sin(robot.angle * M_PI / 180);
robot.angle += pas_angle * CONVERSION_ANGLE;
}
else
{
int pas_angle = (pas_robot.pas_droite - pas_robot.pas_gauche) / 2;
robot.pos_x += (pas_robot.pas_gauche + pas_angle) * CONVERSION_LONGUEUR * cos(robot.angle * M_PI / 180);
robot.pos_y += (pas_robot.pas_gauche + pas_angle) * CONVERSION_LONGUEUR * sin(robot.angle * M_PI / 180);
robot.angle += pas_angle * CONVERSION_ANGLE;
}
sem_post(&sem_pos);
}
void Robot_Thread::copyPositions(Robot robot_1, Robot robot_2, Balle balle)
{
sem_wait(&sem_pos);
robot1.pos_x = robot_1.pos_x;
robot1.pos_y = robot_1.pos_y;
robot1.angle = robot_1.angle;
robot2.pos_x = robot_2.pos_x;
robot2.pos_y = robot_2.pos_y;
robot2.angle = robot_2.angle;
sem_post(&sem_pos);
this->balle.pos_x = balle.pos_x;
this->balle.pos_y = balle.pos_y;
this->balle.vit_x = balle.vit_x;
this->balle.vit_y = balle.vit_y;
}
|
#ifndef Scaler_h
#define Scaler_h
#include "Arduino.h"
class Scaler
{
public:
Scaler();
float ScaleAnalogInput(int analogInput);
float VoltToCelsius(float voltage);
private:
int _resolution;
int _maxVolt;
int _minVolt;
int _maxTemp;
int _minTemp;
};
#endif
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <folly/ScopeGuard.h>
#include <quic/dsr/frontend/WriteFunctions.h>
namespace quic {
uint64_t writePacketizationRequest(
QuicServerConnectionState& connection,
const ConnectionId& dstCid,
size_t packetLimit,
const Aead& aead,
TimePoint writeLoopBeginTime) {
DSRStreamFrameScheduler scheduler(connection);
uint64_t packetCounter = 0;
folly::F14FastSet<DSRPacketizationRequestSender*> senders;
SCOPE_EXIT {
for (auto sender : senders) {
if (connection.qLogger) {
connection.qLogger->addTransportStateUpdate("DSR flushing sender");
}
sender->flush();
}
};
if (!writeLoopTimeLimit(writeLoopBeginTime, connection)) {
return packetCounter;
}
while (scheduler.hasPendingData() && packetCounter < packetLimit &&
(packetCounter < connection.transportSettings.maxBatchSize ||
writeLoopTimeLimit(writeLoopBeginTime, connection))) {
auto packetNum = getNextPacketNum(connection, PacketNumberSpace::AppData);
ShortHeader header(ProtectionType::KeyPhaseZero, dstCid, packetNum);
auto writableBytes = std::min(
connection.udpSendPacketLen,
congestionControlWritableBytes(connection));
uint64_t cipherOverhead = aead.getCipherOverhead();
if (writableBytes < cipherOverhead) {
writableBytes = 0;
} else {
writableBytes -= cipherOverhead;
}
DSRPacketBuilder packetBuilder(
writableBytes,
std::move(header),
getAckState(connection, PacketNumberSpace::AppData)
.largestAckedByPeer.value_or(0));
auto schedulerResult = scheduler.writeStream(packetBuilder);
if (!schedulerResult.writeSuccess) {
/**
* Scheduling can fail when we:
* (1) run out of flow control
* (2) there is actually no DSR stream to write - we shouldn't come here
* in the first place though.
* (3) Packet is no space left - e.g., due to CC
* (4) Error in write codec - Can that happen?
*
* At least for (1) and (3), we should flush the sender.
*/
if (schedulerResult.sender) {
senders.insert(schedulerResult.sender);
}
return packetCounter;
}
CHECK(schedulerResult.sender);
auto packet = std::move(packetBuilder).buildPacket();
// The contract is that if scheduler can schedule, builder has to be able to
// build.
CHECK_GT(packet.encodedSize, 0);
bool instructionAddError = false;
for (const auto& instruction : packet.sendInstructions) {
if (!schedulerResult.sender->addSendInstruction(instruction)) {
instructionAddError = true;
break;
}
}
// Similar to the regular write case, if we build, we update connection
// states. The connection states are changed already no matter the result
// of addSendInstruction() call.
updateConnection(
connection,
folly::none /* Packet Event */,
packet.packet,
Clock::now(),
packet.encodedSize + cipherOverhead,
// TODO: (yangchi) Figure out how to calculate the
// packet.encodedBodySize for the DSR case. For now, it's not being
// used, so setting it to 0
0,
true /* isDSRPacket */);
connection.dsrPacketCount++;
if (instructionAddError) {
// TODO: Support empty write loop detection
senders.insert(schedulerResult.sender);
return packetCounter;
}
++packetCounter;
senders.insert(schedulerResult.sender);
}
return packetCounter;
}
} // namespace quic
|
#ifndef _NIHTTPD_TEST_ROUTE_H
#define _NIHTTPD_TEST_ROUTE_H 1
#include <nihttpd/nihttpd.h>
#include <nihttpd/socket.h>
#include <nihttpd/http.h>
namespace nihttpd {
class test_router : public router {
public:
test_router( ) : router( "/", "/srv/http" ){ };
test_router( std::string pref ) : router( pref, "/srv/http" ){ };
virtual void dispatch(http_request req, connection conn);
};
}
#endif
|
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<cstdlib>
#include<cstring>
using namespace std;
char score2grade(int score){
if(score >= 80) return 'A';
if(score >= 70) return 'B';
if(score >= 60) return 'C';
if(score >= 50) return 'D';
else return 'F';
}
string toUpperStr(string x){
string y = x;
for(unsigned i = 0; i < x.size();i++) y[i] = toupper(x[i]);
return y;
}
void importDataFromFile(string filepath , vector<string> &names , vector<int> &scores , vector<char> &grades){
ifstream source(filepath);
string text;
while(getline(source , text)){
char ctext[1000];
strcpy(ctext , text.c_str());
char format[] = "%[^:]: %d %d %d";
char name[1000];
int a , b , c , sum ;
sscanf(ctext , format , name , &a , &b , &c);
sum = a + b + c;
names.push_back(name);
scores.push_back(sum);
if(sum >= 80)
grades.push_back('A');
else if(sum >= 70)
grades.push_back('B');
else if(sum >= 60)
grades.push_back('C');
else if(sum >= 50)
grades.push_back('D');
else
grades.push_back('F');
}
}
void getCommand(string &command , string &key){
string line;
cout << "Please input your command: ";
getline(cin , line);
int L = line.length();
int find = line.find_first_of(" ");
command = line.substr(0 , find);
if(find == -1)
key = "BOBO";
else
key = line.substr(find + 1 , L - find);
}
void searchName(vector<string> names, vector<int> scores, vector<char> grades, string key){
bool found = false;
for(unsigned int i = 0 ; i < names.size() ; ++i){
if(key == toUpperStr(names[i])){
cout << "---------------------------------\n";
cout << names[i] << "'s score = " << scores[i] << endl;
cout << names[i] << "'s grade = " << grades[i] << endl;
cout << "---------------------------------\n";
found = true;
break;
}
}
if(!found){
cout << "---------------------------------\n";
cout << "Cannot found.\n";
cout << "---------------------------------\n";
}
}
void searchGrade(vector<string> names, vector<int> scores, vector<char> grades, string key){
cout << "---------------------------------\n";
for(unsigned int i = 0 ; i < names.size() ; ++i){
if(key[0] == grades[i]){
cout << names[i] << " (" << scores[i] << ")\n";
}
}
cout << "---------------------------------\n";
}
int main(){
string filename = "name_score.txt";
vector<string> names;
vector<int> scores;
vector<char> grades;
importDataFromFile(filename, names, scores, grades);
do{
string command, key;
getCommand(command,key);
command = toUpperStr(command);
key = toUpperStr(key);
if(command == "EXIT") break;
else if(command == "GRADE") searchGrade(names, scores, grades, key);
else if(command == "NAME") searchName(names, scores, grades, key);
else{
cout << "---------------------------------\n";
cout << "Invalid command.\n";
cout << "---------------------------------\n";
}
}while(true);
return 0;
}
|
#include "mutiplex/Timestamp.h"
#include <sys/time.h>
namespace muti
{
#define MICROSECONDS_PER_SECOND (1000 * 1000)
uint64_t Timestamp::current()
{
struct timeval tv;
gettimeofday(&tv, nullptr);
return static_cast<uint64_t>(tv.tv_sec * MICROSECONDS_PER_SECOND + tv.tv_usec);
}
std::string Timestamp::to_string(uint64_t timestamp)
{
struct timeval tm;
tm.tv_sec = timestamp / MICROSECONDS_PER_SECOND;
tm.tv_usec = timestamp % MICROSECONDS_PER_SECOND;
struct tm result;
localtime_r(&tm.tv_sec, &result);
char buf[64];
snprintf(buf,
sizeof(buf),
"%04d-%02d-%02d %02d:%02d:%02d.%06lu",
result.tm_year + 1900,
result.tm_mon + 1,
result.tm_mday,
result.tm_hour,
result.tm_min,
result.tm_sec,
tm.tv_usec);
return buf;
}
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
//
// Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Adam Minchinton
//
#ifndef __COMMANDLINE_MANAGER_H__
#define __COMMANDLINE_MANAGER_H__
#define g_commandline_manager (CommandLineManager::GetInstance())
class CommandLineArgumentHandler;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct CommandLineArgument
{
OpAutoVector<OpString> m_string_list_value;//Holds a list of strings for a list of strings argument
OpString m_string_value; // Holds the string value if it's a string argument
int m_int_value; // Holds the int value if it's a int argument
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class CommandLineStatus : public OpStatus
{
public:
enum
{
/**
* The program needs to exit so just make this
* an error and the rest should take care of itself
*/
CL_HELP = USER_ERROR + 0,
};
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class CommandLineManager
{
public:
// This enum MUST be in sync with the CLArgInfo g_cl_arg_info[] in the source file
enum CLArgument
{
#ifdef WIDGET_RUNTIME_SUPPORT
Widget,
#endif // WIDGET_RUNTIME_SUPPORT
NewWindow,
NewTab,
NewPrivateTab,
ActiveTab,
BackgroundTab,
Fullscreen,
Geometry,
Remote,
WindowId,
WindowName,
NoRaise,
NoSession,
NoMail,
NoARGB,
NoHWAccel,
NoLIRC,
NoWin,
DisplayName,
NoGrab,
#ifdef _DEBUG
DoGrab,
#endif
SyncEvent,
DisableIME,
Version,
FullVersion,
DebugAsyncActivity,
DebugClipboard,
DebugDNS,
DebugFile,
DebugFont,
DebugFontFilter,
DebugKeyboard,
DebugCamera,
DebugLocale,
DebugMouse,
DebugPlugin,
DebugSocket,
DebugAtom,
DebugXError,
DebugShape,
DebugIme,
DebugIwScan,
DebugLibraries,
DebugLIRC,
DebugLayout,
CreateSingleProfile,
PrefsSuffix,
PersonalDirectory,
ShareDirectory,
BinaryDirectory,
ScreenHeight,
ScreenWidth,
StartMail,
Help,
Question,
KioskHelp,
DisableCoreAnimation,
DisableInvalidatingCoreAnimation,
#ifdef _DEBUG
DebugSettings,
#endif
MediaCenter,
Settings,
ReinstallBrowser,
ReinstallMailer,
ReinstallNewsReader,
HideIconsCommand,
ShowIconsCommand,
NoMinMaxButtons,
DebugHelp, // Always on, not to be disabled by _DEBUG ifdef
LIRCHelp,
UrlList,
UrlListLoadTimeout,
#ifdef FEATURE_UI_TEST
UserInterfaceCrawl,
#endif // FEATURE_UI_TEST
UIParserLog,
UIWidgetParserLog,
#ifdef SELFTEST
SourceRootDir,
#endif // SELFTEST
NoCrashHandling,
CrashLog,
CrashLogGpuInfo,
CrashAction,
Session,
AddFirewallException,
ProfilingLog,
DelayShutdown,
WatirTest,
DebugProxy,
DialogTest,
IniDialogTest,
GPUTest,
OWIInstall,
OWIUninstall,
OWIAutoupdate,
OWISilent,
OWIInstallFolder,
OWILanguage,
OWICopyOnly,
OWIAllUsers,
OWISingleProfile,
OWISetDefaultPref,
OWISetFixedPref,
OWISetDefaultBrowser,
OWIStartMenuShortcut,
OWIDesktopShortcut,
OWIQuickLaunchShortcut,
OWIPinToTaskbar,
OWILaunchOpera,
OWIGiveFolderWriteAccess,
OWIGiveWriteAccessTo,
OWIUpdateCountryCode,
OWICountryCode,
DelayCustomizations,
#if defined(_DEBUG) && defined(MEMORY_ELECTRIC_FENCE)
Fence,
#endif // MEMORY_ELECTRIC_FENCE
ARGUMENT_COUNT
};
public:
virtual ~CommandLineManager();
static CommandLineManager *GetInstance();
/** Initialization function, only run other functions if this returns success
*/
OP_STATUS Init();
/** Parse all arguments in argc/argv format so that they can later be retrieved
* @param argc Argument count as given to main()
* @param argv Arguments as given to main()
* @param wargv Like argv, but in wide character format
*/
OP_STATUS ParseArguments(int argc, const char* const* argv, const uni_char* const* wargv = NULL);
/** Get the value of a given command line argument
* @param arg Argument to get
* @return Pointer to value, or NULL if this command line argument wasn't specified
*/
CommandLineArgument *GetArgument(CLArgument arg) const { return m_args[arg]; }
OpVector<OpString> *GetUrls() { return &m_commandline_urls; }
CommandLineArgumentHandler *GetHandler() const { return m_handler;}
// These functions allow the platform to add arguments to be used
// when restarting, in addition to those we got on the command
// line. Note that this doesn't get stored in m_args.
OP_STATUS AddRestartArgument(CLArgument arg);
OP_STATUS AddRestartArgument(CLArgument arg, int value);
OP_STATUS AddRestartArgument(CLArgument arg, const char* value);
// Return the list of arguments to use when restarting Opera
const OpVector<OpString8> & GetRestartArguments() const { return m_restart_arguments; }
// Return path to the Opera binary as used when starting Opera
OpStringC8 GetBinaryPath() const { return m_binary_path; }
private:
CommandLineManager();
OP_STATUS AppendRestartArgument(const char* arg);
CommandLineArgument *m_args[ARGUMENT_COUNT]; // Pointer array for the command line arguments
CommandLineArgumentHandler *m_handler; // Pointer to the argument handling class
OpAutoVector<OpString> m_commandline_urls; // List of urls typed at the command line.
OpAutoVector<OpString8> m_restart_arguments; // Arguments to pass when restarting Opera
OpString8 m_binary_path; // Path to the Opera binary as used when starting Opera
static OpAutoPtr<CommandLineManager> m_commandline_manager;
};
#endif // __COMMANDLINE_MANAGER_H__
|
#include <entt.hpp>
template <typename ...Components, typename Func>
double iterate_view(entt::registry<std::uint64_t> &ecs, int n_iter, Func func) {
double result = 0;
for (int i = 0; i < n_iter; i ++) {
struct timespec start; timespec_gettime(&start);
ecs.view<Components...>().each(func);
double t = timespec_measure(&start);
if (!result || (t < result)) {
result = t;
}
}
return result;
}
template <typename ...Components, typename Func>
double iterate_group(entt::registry<std::uint64_t> &ecs, int n_iter, Func func) {
double result = 0;
for (int i = 0; i < n_iter; i ++) {
struct timespec start; timespec_gettime(&start);
ecs.group<Components...>().each(func);
double t = timespec_measure(&start);
if (!result || (t < result)) {
result = t;
}
}
return result;
}
double bench_create_empty_entt(int n) {
entt::registry<std::uint64_t> ecs;
struct timespec start; timespec_gettime(&start);
for (int i = 0; i < n; i++) {
ecs.create();
}
double result = timespec_measure(&start);
return result;
}
double bench_create_empty_entt_batch(int n) {
entt::registry<std::uint64_t> ecs;
std::vector<entt::registry<std::uint64_t>::entity_type> entities(n);
struct timespec start; timespec_gettime(&start);
ecs.create(entities.begin(), entities.end());
double result = timespec_measure(&start);
return result;
}
double bench_create_1component_entt(int n) {
entt::registry<std::uint64_t> ecs;
struct timespec start; timespec_gettime(&start);
for (int i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
}
double result = timespec_measure(&start);
return result;
}
double bench_create_2component_entt(int n) {
entt::registry<std::uint64_t> ecs;
struct timespec start; timespec_gettime(&start);
for(std::uint64_t i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
}
double result = timespec_measure(&start);
return result;
}
double bench_create_3component_entt(int n) {
entt::registry<std::uint64_t> ecs;
struct timespec start; timespec_gettime(&start);
for(std::uint64_t i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
ecs.assign<Mass>(entity);
}
double result = timespec_measure(&start);
return result;
}
double bench_delete_1component_entt(int n) {
entt::registry<std::uint64_t> ecs;
for(std::uint64_t i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
}
struct timespec start; timespec_gettime(&start);
ecs.each([&ecs](auto entity) {
ecs.destroy(entity);
});
double result = timespec_measure(&start);
return result;
}
double bench_add_one_entt(int n) {
entt::registry<std::uint64_t> ecs;
for (int i = 0; i < n; i++) {
ecs.create();
}
struct timespec start; timespec_gettime(&start);
ecs.each([&ecs](auto entity) {
ecs.assign<Position>(entity);
});
double result = timespec_measure(&start);
return result;
}
double bench_add_two_entt(int n) {
entt::registry<std::uint64_t> ecs;
for (int i = 0; i < n; i++) {
ecs.create();
}
struct timespec start; timespec_gettime(&start);
ecs.each([&ecs](auto entity) {
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
});
double result = timespec_measure(&start);
return result;
}
double bench_add_three_entt(int n) {
entt::registry<std::uint64_t> ecs;
for (int i = 0; i < n; i++) {
ecs.create();
}
struct timespec start; timespec_gettime(&start);
ecs.each([&ecs](auto entity) {
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
ecs.assign<Mass>(entity);
});
double result = timespec_measure(&start);
return result;
}
double bench_add_four_entt(int n) {
entt::registry<std::uint64_t> ecs;
for (int i = 0; i < n; i++) {
ecs.create();
}
struct timespec start; timespec_gettime(&start);
ecs.each([&ecs](auto entity) {
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
ecs.assign<Mass>(entity);
ecs.assign<Color>(entity);
});
double result = timespec_measure(&start);
return result;
}
double bench_remove_one_entt(int n) {
entt::registry<std::uint64_t> ecs;
for (int i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
}
struct timespec start; timespec_gettime(&start);
ecs.each([&ecs](auto entity) {
ecs.remove<Position>(entity);
});
double result = timespec_measure(&start);
return result;
}
double bench_remove_two_entt(int n) {
entt::registry<std::uint64_t> ecs;
for (int i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
}
struct timespec start; timespec_gettime(&start);
ecs.each([&ecs](auto entity) {
ecs.remove<Position>(entity);
ecs.remove<Velocity>(entity);
});
double result = timespec_measure(&start);
return result;
}
double bench_remove_three_entt(int n) {
entt::registry<std::uint64_t> ecs;
for (int i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
ecs.assign<Mass>(entity);
}
struct timespec start; timespec_gettime(&start);
ecs.each([&ecs](auto entity) {
ecs.remove<Position>(entity);
ecs.remove<Velocity>(entity);
ecs.remove<Mass>(entity);
});
double result = timespec_measure(&start);
return result;
}
double bench_iter_one_entt_view(int n, int n_iter) {
entt::registry<std::uint64_t> ecs;
for(std::uint64_t i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
}
return iterate_view<Position>(ecs, n_iter, [](auto &p) {
p.x ++;
p.y ++;
});
}
double bench_iter_two_entt_view(int n, int n_iter) {
entt::registry<std::uint64_t> ecs;
for(std::uint64_t i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
}
return iterate_view<Position, Velocity>(ecs, n_iter, [](auto &p, auto &v) {
p.x += v.x;
p.y += v.y;
});
}
double bench_iter_three_two_types_entt_view(int n, int n_iter) {
entt::registry<std::uint64_t> ecs;
for(std::uint64_t i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
ecs.assign<Mass>(entity);
if (i < n / 2) {
ecs.assign<Rotation>(entity);
}
}
return iterate_view<Position, Velocity, Mass>(ecs, n_iter, [](auto &p, auto &v, auto &m) {
p.x += v.x;
p.y += v.y;
});
}
double bench_iter_two_entt_group(int n, int n_iter) {
entt::registry<std::uint64_t> ecs;
ecs.group<Position, Velocity>();
for(std::uint64_t i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
}
return iterate_group<Position, Velocity>(ecs, n_iter, [](auto &p, auto &v) {
p.x += v.x;
p.y += v.y;
});
}
double bench_iter_three_two_types_entt_group(int n, int n_iter) {
entt::registry<std::uint64_t> ecs;
ecs.group<Position, Velocity, Mass>();
for(std::uint64_t i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
ecs.assign<Mass>(entity);
if (i < n / 2) {
ecs.assign<Rotation>(entity);
}
}
return iterate_group<Position, Velocity, Mass>(ecs, n_iter, [](auto &p, auto &v, auto &m) {
p.x += v.x / m.value;
p.y += v.y / m.value;
});
}
double bench_iter_three_entt_view(int n, int n_iter) {
entt::registry<std::uint64_t> ecs;
for(std::uint64_t i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
ecs.assign<Mass>(entity);
}
return iterate_view<Position, Velocity, Mass>(ecs, n_iter, [](auto &p, auto &v, auto &m) {
p.x += v.x / m.value;
p.y += v.y / m.value;
});
}
double bench_iter_three_entt_group(int n, int n_iter) {
entt::registry<std::uint64_t> ecs;
ecs.group<Position, Velocity, Mass>();
for(std::uint64_t i = 0; i < n; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Velocity>(entity);
ecs.assign<Mass>(entity);
}
return iterate_group<Position, Velocity, Mass>(ecs, n_iter, [](auto &p, auto &v, auto &m) {
p.x += v.x / m.value;
p.y += v.y / m.value;
});
}
void create_eight_types(entt::registry<std::uint64_t> &ecs, std::uint64_t count, bool match_all) {
for(std::uint64_t i = 0; i < count; i++) {
const auto entity = ecs.create();
ecs.assign<Position>(entity);
ecs.assign<Mass>(entity);
ecs.assign<Damage>(entity);
if ((i % 8) == 1) {
ecs.assign<Rotation>(entity);
} else
if ((i % 8) == 2) {
ecs.assign<Color>(entity);
} else
if ((i % 8) == 3) {
ecs.assign<Battery>(entity);
} else
if ((i % 8) == 4) {
ecs.assign<Rotation>(entity);
ecs.assign<Color>(entity);
} else
if ((i % 8) == 5) {
ecs.assign<Rotation>(entity);
ecs.assign<Battery>(entity);
} else
if ((i % 8) == 6) {
ecs.assign<Battery>(entity);
ecs.assign<Color>(entity);
} else
if ((i % 8) == 7) {
ecs.assign<Rotation>(entity);
ecs.assign<Battery>(entity);
ecs.assign<Color>(entity);
}
if (match_all || i % 2) {
ecs.assign<Velocity>(entity);
}
}
}
double bench_iter_two_eight_types_entt_view(int n, int n_iter, bool match_all) {
entt::registry<std::uint64_t> ecs;
int count = n * (2 - match_all);
create_eight_types(ecs, count, match_all);
return iterate_view<Position, Velocity>(ecs, n_iter, [](auto &p, auto &v) {
p.x += v.x;
p.y += v.y;
});
}
double bench_iter_three_eight_types_entt_view(int n, int n_iter, bool match_all) {
entt::registry<std::uint64_t> ecs;
int count = n * (2 - match_all);
create_eight_types(ecs, count, match_all);
return iterate_view<Position, Velocity, Mass>(ecs, n_iter, [](auto &p, auto &v, auto &m) {
p.x += v.x / m.value;
p.y += v.y / m.value;
});
}
double bench_iter_two_eight_types_entt_group(int n, int n_iter, bool match_all) {
entt::registry<std::uint64_t> ecs;
ecs.group<Position, Velocity>();
int count = n * (2 - match_all);
create_eight_types(ecs, count, match_all);
return iterate_group<Position, Velocity>(ecs, n_iter, [](auto &p, auto &v) {
p.x += v.x;
p.y += v.y;
});
}
double bench_iter_three_eight_types_entt_group(int n, int n_iter, bool match_all) {
entt::registry<std::uint64_t> ecs;
ecs.group<Position, Velocity, Mass>();
int count = n * (2 - match_all);
create_eight_types(ecs, count, match_all);
return iterate_group<Position, Velocity, Mass>(ecs, n_iter, [](auto &p, auto &v, auto &m) {
p.x += v.x / m.value;
p.y += v.y / m.value;
});
}
double bench_iter_four_eight_types_entt_view(int n, int n_iter, bool match_all) {
entt::registry<std::uint64_t> ecs;
int count = n * (2 - match_all);
create_eight_types(ecs, count, match_all);
return iterate_view<Position, Velocity, Mass>(ecs, n_iter, [](auto &p, auto &v, auto &m) {
p.x += v.x / m.value;
p.y += v.y / m.value;
});
}
double bench_iter_four_eight_types_entt_group(int n, int n_iter, bool match_all) {
entt::registry<std::uint64_t> ecs;
ecs.group<Position, Velocity, Mass, Damage>();
int count = n * (2 - match_all);
create_eight_types(ecs, count, match_all);
return iterate_group<Position, Velocity, Mass, Damage>(ecs, n_iter, [](auto &p, auto &v, auto &m, auto &d) {
p.x += v.x / m.value / d.value;
p.y += v.y / m.value / d.value;
});
}
void create_pathological(entt::registry<std::uint64_t> &ecs, std::vector< std::vector <int>> entity_list) {
for (std::vector<int> &component_list: entity_list) {
const auto e = ecs.create();
ecs.assign<Position>(e);
ecs.assign<Velocity>(e);
ecs.assign<Mass>(e);
ecs.assign<Damage>(e);
for (int c: component_list) {
switch(c) {
case 0:
ecs.assign<Stamina>(e);
break;
case 1:
ecs.assign<Strength>(e);
break;
case 2:
ecs.assign<Agility>(e);
break;
case 3:
ecs.assign<Intelligence>(e);
break;
case 4:
ecs.assign<Color>(e);
break;
case 5:
ecs.assign<Battery>(e);
break;
case 6:
ecs.assign<Rotation>(e);
break;
case 7:
ecs.assign<Health>(e);
break;
case 8:
ecs.assign<Attack>(e);
break;
case 9:
ecs.assign<Defense>(e);
break;
}
}
}
}
double bench_iter_one_pathological_entt(int n_iter, std::vector< std::vector<int>> entity_list) {
entt::registry<std::uint64_t> ecs;
create_pathological(ecs, entity_list);
return iterate_view<Position>(ecs, n_iter, [](auto &p) {
p.x ++;
p.y ++;
});
}
double bench_iter_two_pathological_entt_view(int n_iter, std::vector< std::vector<int>> entity_list) {
entt::registry<std::uint64_t> ecs;
create_pathological(ecs, entity_list);
return iterate_view<Position, Velocity>(ecs, n_iter, [](auto &p, auto &v) {
p.x += v.x;
p.y += v.y;
});
}
double bench_iter_two_pathological_entt_group(int n_iter, std::vector< std::vector<int>> entity_list) {
entt::registry<std::uint64_t> ecs;
ecs.group<Position, Velocity>();
create_pathological(ecs, entity_list);
return iterate_group<Position, Velocity>(ecs, n_iter, [](auto &p, auto &v) {
p.x += v.x;
p.y += v.y;
});
}
double bench_iter_three_pathological_entt_view(int n_iter, std::vector< std::vector<int>> entity_list) {
entt::registry<std::uint64_t> ecs;
create_pathological(ecs, entity_list);
return iterate_view<Position, Velocity, Mass>(ecs, n_iter, [](auto &p, auto &v, auto &m) {
p.x += v.x / m.value;
p.y += v.y / m.value;
});
}
double bench_iter_three_pathological_entt_group(int n_iter, std::vector< std::vector<int>> entity_list) {
entt::registry<std::uint64_t> ecs;
ecs.group<Position, Velocity, Mass>();
create_pathological(ecs, entity_list);
return iterate_group<Position, Velocity, Mass>(ecs, n_iter, [](auto &p, auto &v, auto &m) {
p.x += v.x / m.value;
p.y += v.y / m.value;
});
}
double bench_iter_four_pathological_entt_view(int n_iter, std::vector< std::vector<int>> entity_list) {
entt::registry<std::uint64_t> ecs;
create_pathological(ecs, entity_list);
return iterate_view<Position, Velocity, Mass, Damage>(ecs, n_iter, [](auto &p, auto &v, auto &m, auto &d) {
p.x += v.x / m.value / d.value;
p.y += v.y / m.value / d.value;
});
}
double bench_iter_four_pathological_entt_group(int n_iter, std::vector< std::vector<int>> entity_list) {
entt::registry<std::uint64_t> ecs;
ecs.group<Position, Velocity, Mass, Damage>();
create_pathological(ecs, entity_list);
return iterate_group<Position, Velocity, Mass, Damage>(ecs, n_iter, [](auto &p, auto &v, auto &m, auto &d) {
p.x += v.x / m.value / d.value;
p.y += v.y / m.value / d.value;
});
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2003 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 DOM2_EVENTS_API
#include "modules/dom/domevents.h"
#include "modules/dom/domenvironment.h"
#include "modules/dom/src/domcore/node.h"
#include "modules/dom/src/domevents/domevent.h"
#include "modules/dom/src/domevents/domeventtarget.h"
/* static */ DOM_EventType
DOM_EventsAPI::GetEventType(const uni_char *type)
{
return DOM_Environment::GetEventType(type);
}
/* static */ const char *
DOM_EventsAPI::GetEventTypeString(DOM_EventType type)
{
return DOM_Environment::GetEventTypeString(type);
}
/* static */ BOOL
DOM_EventsAPI::IsWindowEvent(DOM_EventType type)
{
return DOM_Event::IsWindowEvent(type);
}
/* static */ BOOL
DOM_EventsAPI::IsWindowEventAsBodyAttr(DOM_EventType type)
{
return DOM_Event::IsWindowEventAsBodyAttr(type);
}
/* static */ OP_STATUS
DOM_EventsAPI::GetEventTarget(EventTarget *&event_target, DOM_Object *node)
{
RETURN_IF_ERROR(node->CreateEventTarget());
event_target = node->GetEventTarget();
return OpStatus::OK;
}
#endif // DOM2_EVENTS_API
|
#include <bits/stdc++.h>
using namespace std;
ofstream fout ("loan.out");
ifstream fin ("loan.in");
int main(){
long long N,K,M;
fin>>N>>K>>M;
long long left = 1;
long long right = K;
while(right-left>0){
long long x= ceil((left+right)/2.0);
long long k = 0;
long long cur = N;
while(true){
if(floor(cur/x) <= M){
break;
}
k++;
cur = ceil(1.0*cur*(x-1)/x);
}
if(cur - M*(K-k) <= 0){
left = x;
}
else{
right = x-1;
}
}
fout<<left<<"\n";
}
|
#ifndef TEXTREADER_H
#define TEXTREADER_H
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include "CLArguments.h"
namespace cppag
{
class Textreader
{
public:
Textreader(std::string loc);
bool read ();
std::string getContent ();
~Textreader();
protected:
std::string mLocation;
std::vector<std::string> mContent; //Zeilenweise gespeicherter Inhalt
private:
};
}
#endif // TEXTREADER_H
|
#include "compute.h"
#include "auxCmd.h"
#include "FactoryIO.h"
#include "IO.h"
#include "ColmapIO.h"
#include "JacobianIO.h"
#include "JacobianComposer.h"
#ifdef USE_MATLAB
#include <mex.h>
#include "matlabInterface.h"
#include "uncertainty_mex.h"
#endif
#ifdef _WIN32
#define EXECUTABLE_FILE "uncertainty.exe"
#elif __linux__
#define EXECUTABLE_FILE "uncertainty"
#endif
#ifndef LOAD_CMD_IO_FLAGS
#define LOAD_CMD_IO_FLAGS
DEFINE_string(alg, "/media/xxxxxxxxx/DATA/xxxxxxxxx/data/RedundantSFM/colmap_sparse_reconstruction",
"algorithm for inversion of Schur complement matrix (SVD_QR_ITERATION, SVD_DEVIDE_AND_CONQUER, TAYLOR_EXPANSION)\n");
DEFINE_string(in, "/media/xxxxxxxxx/DATA/xxxxxxxxx/data/RedundantSFM/colmap_sparse_reconstruction",
"path to input scene files (e.g. directory which contains cameras.txt, images.txt, points3D.tx for COLMAP;\n"
" selected file <path_to_file>.jacob for Jacobian, etc. )\n");
DEFINE_string(in_form, "COLMAP",
"the format of input data (e.g. COLMAP, JACOBIAN, OPENMVG ...)\n");
DEFINE_string(out, "/media/xxxxxxxxx/DATA/xxxxxxxxx/data/RedundantSFM/colmap_sparse_reconstruction",
"path to output covariance files\n");
#endif
/*
Main function called from command line: unc.exe
In:
- algorithm: 0 = SVD_QR_ITERATION, 1 = SVD_DEVIDE_AND_CONQUER, 2 = TAYLOR_EXPANSION
- jacobian/openMVG_scene: path to the file without spaces
Example Jacobain: unc.exe 2 input/myFile.jacob
Example OpenMVG: unc.exe 2 input/myFile.[bin,json,xml]
*/
int main(int argc, char* argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
ceres::CRSMatrix jacobian = ceres::CRSMatrix();
cov::Options options = cov::Options();
cov::Statistic statistic = cov::Statistic();
// read input data
IO* io = FactoryIO::createIO(FLAGS_in_form);
if (io->data_type() == SCENE_DATA){
Scene scene = Scene();
if ( !io->read( FLAGS_in, scene ) )
exit(1);
cout << scene;
JacobianComposer jc = JacobianComposer();
jc.scene2Jacobian(scene, jacobian, options);
}else{
std::ifstream file(FLAGS_in, std::ios_base::in);
loadJacobian(file, 2, jacobian, options); // FLAGS_algorithm = 2
}
// TODO: add to the loader
/*#ifdef USE_OPENMVG
std::cout << "Loading a OpenMVG scene: " << input_file << '\n';
openMVG::sfm::SfM_Data sfm_data;
loadSceneOpenMVG(input_file, sfm_data);
openmvgSfM2Jacobian(sfm_data, jacobian, options);
#endif // USE_OPENMVG
*/
options._svdRemoveN = 7;
// alocate output arrays
int num_camera_covar_values = 0.5 * options._camParams * (options._camParams + 1); // save only half of each symmetric matrix
int camUnc_size = num_camera_covar_values * options._numCams;
double* camUnc = (double*)malloc(camUnc_size * sizeof(double));
assert(camUnc != NULL);
double* ptsUnc = (double*)malloc(6 * options._numPoints * sizeof(double));
assert(ptsUnc != NULL);
// COMPUTE COVARIANCES
computeCovariances(options, statistic, jacobian, camUnc, ptsUnc);
// write results to the outut file
saveResults(FLAGS_out, options, statistic, num_camera_covar_values, camUnc, ptsUnc);
std::cout << "Main function... [done]\n";
return 0;
}
/*
Library function foc C++ call: getCovariances( ... )
In:
- options: informations about the reconstruction (numCams, camParams, numPoints, numObs)
- statistic: blank object for the output statistics
- jacobian: sparse matrix (form Ceres-solver) with jacobian ( you can use the output of the computation of jacobian in Ceres as the input )
- h_camUnc: array which contatins covariances for cameras
- h_ptUnc: array which contatins covariances for points
*/
#ifdef _WIN32
extern "C" __declspec(dllexport) void getCovariances(
cov::Options &options,
cov::Statistic &statistic,
ceres::CRSMatrix &jacobian,
double* h_camUnc,
double* h_ptUnc)
{
computeCovariances(options, statistic, jacobian, h_camUnc, h_ptUnc);
}
#elif __linux__
void getCovariances(
cov::Options &options,
cov::Statistic &statistic,
ceres::CRSMatrix &jacobian,
double* h_camUnc,
double* h_ptUnc)
{
computeCovariances(options, statistic, jacobian, h_camUnc, h_ptUnc);
}
#endif
/*
Matlab interface, call in Matlab: unc( .... )
*/
#ifdef USE_MATLAB
void MEX_FUNCTION_NAME(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
cov::Statistic statistic = cov::Statistic();
cov::Options options = cov::Options();
ceres::CRSMatrix jacobian = ceres::CRSMatrix();
// Load and create Jacobian using camera model [angle axis, camera center, focal length, radial distortion]
ceres::examples::BALProblem bal_problem = loadSceneMatlab( prhs );
buildJacobian(&bal_problem, jacobian, options);
// alocate output arrays
int NcamArr = 0.5 * bal_problem.camera_block_size() * (bal_problem.camera_block_size() + 1) * bal_problem.num_cameras();
int NptsArr = 6 * bal_problem.num_points();
double *ptsUnc = (double*)malloc(NptsArr * sizeof(double));
double *camUnc = (double*)malloc(NcamArr * sizeof(double));
plhs[0] = mxCreateDoubleMatrix(NptsArr + NcamArr, 1, mxREAL);
double *outC = mxGetPr(plhs[0]);
// COMPUTE COVARIANCES
computeCovariances(options, statistic, jacobian, camUnc, ptsUnc);
// write results to the output
for (int i = 0; i < NcamArr; i++)
outC[i] = camUnc[i];
for (int i = 0; i < NptsArr; i++)
outC[NcamArr + i] = ptsUnc[i];
free(ptsUnc);
free(camUnc);
mexPrintf("Computation of covariances ... [done]\n\n");
}
#endif
|
// Copyright 2012 Yandex
#ifndef LTR_SERIALIZATION_TEST_GENERATOR_GENERATOR_UTILITY_H_
#define LTR_SERIALIZATION_TEST_GENERATOR_GENERATOR_UTILITY_H_
#include <string>
#include "ltr/data/data_set.h"
#include "ltr/learners/learner.h"
using std::string;
using ltr::DataSet;
using ltr::Object;
using ltr::Learner;
namespace serialization_test {
class Generator {
public:
Generator();
string code() const;
void write(const char* filename) const;
void setScorerTest(Learner<Object>::Ptr learner,
string test_name);
const DataSet<Object> train_data;
const DataSet<Object> test_data;
private:
string setIncludes() const;
string setFixture() const;
string setTestLabelsFunction(string function_name) const;
string setTestCode(int index,
const string& test_name) const;
string setBeginBlockComment(string message) const;
string setEndBlockComment(string message) const;
string tester_code;
int scorers_to_test;
};
};
#endif // LTR_SERIALIZATION_TEST_GENERATOR_GENERATOR_UTILITY_H_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.