text
stringlengths 8
6.88M
|
|---|
#ifndef ID_STRING_HPP_
#define ID_STRING_HPP_
#include "Text.hpp"
struct ID_OR_STRING
{
WORD m_ID;
std::wstring m_Str;
ID_OR_STRING() : m_ID(0)
{
}
ID_OR_STRING(WORD ID) : m_ID(ID)
{
}
ID_OR_STRING(LPCWSTR Str)
{
if (IS_INTRESOURCE(Str))
{
m_ID = LOWORD(Str);
}
else
{
m_ID = 0;
m_Str = Str;
}
}
const WCHAR *Ptr() const
{
if (m_ID)
return MAKEINTRESOURCEW(m_ID);
return m_Str.c_str();
}
bool is_zero() const
{
return m_ID == 0 && m_Str.empty();
}
bool is_null() const
{
return is_zero();
}
bool empty() const
{
return is_zero();
}
bool is_str() const
{
return (!m_ID && !m_Str.empty());
}
bool is_int() const
{
return !is_str();
}
void clear()
{
m_ID = 0;
m_Str.clear();
}
ID_OR_STRING& operator=(WORD ID)
{
m_ID = ID;
m_Str.clear();
return *this;
}
ID_OR_STRING& operator=(const WCHAR *Str)
{
if (IS_INTRESOURCE(Str))
{
m_ID = LOWORD(Str);
m_Str.clear();
}
else
{
m_ID = 0;
m_Str = Str;
}
return *this;
}
bool operator==(const ID_OR_STRING& id_or_str) const
{
if (id_or_str.m_ID != 0)
{
if (m_ID != 0)
return id_or_str.m_ID == m_ID;
}
else
{
if (m_ID == 0)
return m_Str == id_or_str.m_Str;
}
return false;
}
bool operator==(const WCHAR *psz) const
{
if (IS_INTRESOURCE(psz))
{
if (m_ID != 0)
return LOWORD(psz) == m_ID;
}
else
{
if (m_ID == 0)
return m_Str == psz;
}
return false;
}
bool operator==(const std::wstring& Str) const
{
return *this == Str.c_str();
}
bool operator==(WORD w) const
{
return m_ID == w;
}
bool operator!=(const ID_OR_STRING& id_or_str) const
{
return !(*this == id_or_str);
}
bool operator!=(const WCHAR *psz) const
{
return !(*this == psz);
}
bool operator!=(const std::wstring& Str) const
{
return !(*this == Str);
}
bool operator!=(WORD w) const
{
return m_ID != w;
}
std::wstring wstr() const
{
if (m_ID == 0)
{
if (m_Str.size())
return m_Str;
}
return str_dec(m_ID);
}
std::wstring quoted_wstr() const
{
std::wstring ret;
if (m_ID == 0)
{
if (m_Str.size())
{
ret += L"\"";
ret += str_escape(m_Str);
ret += L"\"";
}
else
{
ret = L"\"\"";
}
}
else
{
ret = str_dec(m_ID);
}
return ret;
}
};
#endif // ndef ID_STRING_HPP_
|
struct Shape
{
virtual float area() const noexcept = 0;
virtual float circ() const noexcept = 0;
};
struct Circle : public Shape
{
float R;
Circle(float r) : R(r){}
virtual float area() const noexcept { return 3.14*R*R; }
virtual float circ() const noexcept { return 2.0*3.14*R; }
};
struct Rect : public Shape
{
float W,H;
Rect(float w, float h) : W(w), H(h){}
virtual float area() const noexcept { return W*H; }
virtual float circ() const noexcept { return 2.0*(W+H); }
};
struct Square : public Shape
{
float W;
Square(float w) : W(w){}
virtual float area() const noexcept { return W*W; }
virtual float circ() const noexcept { return 4.0*W; }
};
int main(int argc, char ** argv)
{
return 0;
}
|
// including the JeeLib (JeeNode library), Ports (JeeNode ports library),
// and the Wire I2C library
#include <JeeLib.h>
#include <Ports.h>
#include <Wire.h>
/* The A2,A1,A0 pins are connected to ground, therefore the address is 0x20
* The address is 0b0100[A2][A1][A0]
*/
#define IOAddress 0x20
// Addresses for the GP0 and GP1 registers in the MCP23016
#define GP0 0x00
#define GP1 0x01
// When set to 1, the port is INPUT, when set to 0, the port is OUTPUT.
#define IODIR0 0x06
#define IODIR1 0x07
// Setting all the pins in a port to either output, or input
#define ALL_OUTPUT 0x00
#define ALL_INPUT 0xFF
// IR sensor structure for the left and the right IR sensors
struct IR_Vals
{
int IR_L;
int IR_R;
};
// Structure that holds the current directions of the I/O expander ports
struct IOState{
// These variables hold the current state of each of the two ports, directions of the I/O
unsigned char GP0CurrentState;
unsigned char GP1CurrentState;
};
// Structure that holds the current values of the I/O expander's output
struct IOPortValues{
// These variables hold the current state of each of the two ports, directions of the I/O
unsigned char IOPort0;
unsigned char IOPort1;
};
// Setting up the 4 JeeNode ports
Port port1 = Port(1);
Port port2 = Port(2);
Port port3 = Port(3);
Port port4 = Port(4);
// This function start the transmission I2C protocol
void Start_I2C(){
Wire.begin();
}
/*
* This function sets the direction of the two I/O ports
* Parameters: GP0State and GP1State are the desired states for the two ports\
* This function updates the two current state parameters
*/
struct IOState MCP_SetDirection(unsigned char GP0State, unsigned char GP1State){
IOState CurrentState;
// Update the two CurrentState parameters
CurrentState.GP0CurrentState = GP0State;
CurrentState.GP1CurrentState = GP1State;
// Start I2C transmission with the device
Wire.beginTransmission(IOAddress);
// Selecting IODIR0 register to write to
Wire.write(IODIR0);
// Setting the state for port0
Wire.write(GP0State);
// Selecting IODIR1 register to write to
Wire.write(IODIR1);
// Setting the state for port1
Wire.write(GP1State);
Wire.write(GP0);
// Setting the state for port0
Wire.write(0x00);
// Selecting IODIR1 register to write to
Wire.write(GP1);
// Setting the state for port1
Wire.write(0x00);
// Ending I2C transmission
Wire.endTransmission();
return CurrentState;
}
/*
* This function writes data to the ports on the I/O expander
* Parameters: port (true for port1, false for port0), data: holds the data desired to be writted
*/
void MCP_WritePort(bool port, unsigned char data){
// Checking if the desired port is 0 or 1
if(port){
// Start the transmission with the device
Wire.beginTransmission(IOAddress);
// Select port1 to write to
Wire.write(GP1);
// Write the data to port1
Wire.write(data);
// End the transmission
Wire.endTransmission();
}else{
// Start the transmission with the device
Wire.beginTransmission(IOAddress);
// Select port0 to write to
Wire.write(GP0);
// Write the data to port0
Wire.write(data);
// End the transmission
Wire.endTransmission();
}
}
/*
* This function reads the data from ports 0 and 1 and returns an array with the data
* Parameters: port (true for port1, false for port0)
* Return: array with data from port0 and port1
*/
struct IOPortValues MCP_ReadPorts(bool port){
IOPortValues result;
// Temporary array to hold he values
unsigned char array[2];
// Temporarily save 0 in both values
array[0]=0x00;
array[1]=0x00;
// Start transmission with the device
Wire.beginTransmission(IOAddress);
// Request the device for the number of bytes, if port1 then the bytes are 2, if port0 then the bytes are 1
Wire.requestFrom(IOAddress, port+1);
// Save the data in the array
for(int i = 0; Wire.available(); i++){
array[i] = Wire.read();
}
result.IOPort0 = array[0];
result.IOPort1 = array[1];
// Return the array
return result;
}
/*
* This function is specific to the H-Bridge used for Group Hotel in ELEC3907 Project
* Parameters: AIN1,AIN2,BIN1,BIN2 are specific for the H-Bridge
*/
void Motor_Directions(bool AIN1, bool AIN2, bool BIN1, bool BIN2){
// Read the current values in the port
IOPortValues values = MCP_ReadPorts(0);
// Save the port in a temporary direction variable
unsigned char directions = values.IOPort1;
// Temporary Direction Variables
unsigned char temp1 = 0x0F;
unsigned char temp2 = 0x00;
// Set AIN1
temp1 |= AIN2 << 7;
temp2 |= AIN2 << 7;
// Set AIN2
temp1 |= AIN1 << 6;
temp2 |= AIN1 << 6;
// Set BIN1
temp1 |= BIN1 << 5;
temp2 |= BIN1 << 5;
// Set BIN2
temp1 |= BIN2 << 4;
temp2 |= BIN2 << 4;
// ANDing the current values with temp1
directions &= temp1;
// ORing the current values with temp2
directions |= temp2;
/*
* Code above does this;
* If current output is 0b10101010, and the desired 4 bits are 0b1100
* Set temp1 to 0b11001111, and temp2 to 0b11000000
* Then when ANDing 0b10101010 & 0b11001111 = 0b10001010
* Then ORing 0b10001010 | 0b11000000 = 11001010
* Therefore direction is now 0b11001010, therefore only the 4 bits changed and the rest remained the same
*/
// Call the write function to write the data to port0
MCP_WritePort(0, directions);
}
// hard right turn function, this function turns the vehicle right with a hard turn
void turnHardRight() {
// Setting the directions of the motors with the I/O expander to forward
Motor_Directions(HIGH,LOW,HIGH,LOW);
// setting the left motor's PWM to be at a higher rate than the right one
port3.anaWrite(255);
// setting the right motor's PWM to be at a lower rate than the left one
port4.anaWrite(110);
}
// hard left turn function, this function turns the vehicle left with a hard turn
void turnHardLeft() {
// Setting the directions of the motors with the I/O expander to forward
Motor_Directions(HIGH,LOW,HIGH,LOW);
// setting the right motor's PWM to be at a higher rate than the left one
port4.anaWrite(255);
// setting the left motor's PWM to be at a lower rate than the right one
port3.anaWrite(150);
}
// right turn function, this function turns the vehicle right with a slower turn
void turnRight() {
// Setting the directions of the motors with the I/O expander to forward
Motor_Directions(HIGH,LOW,HIGH,LOW);
// setting the left motor's PWM to be at a higher rate than the right one
port3.anaWrite(255);
// setting the right motor's PWM to be at a lower rate than the left one
port4.anaWrite(150);
}
// left turn function, this function turns the vehicle left with a slower turn
void turnLeft() {
// Setting the directions of the motors with the I/O expander to forward
Motor_Directions(HIGH,LOW,HIGH,LOW);
// setting the right motor's PWM to be at a higher rate than the left one
port4.anaWrite(255);
// setting the left motor's PWM to be at a lower rate than the right one
port3.anaWrite(190);
}
// stop function to stop the motors from turning
void stops() {
// setting the motor directions to none, therefore stop the motors
Motor_Directions(LOW,LOW,LOW,LOW);
}
// forward function, this function moves the vehicle forward
void forward() {
// Setting the directions of the motors with the I/O expander to forward
Motor_Directions(HIGH,LOW,HIGH,LOW);
// setting both motor's PWM to be the same which means the vehicle will move forward
// setting the right motor's PWM to 240
port4.anaWrite(240);
// setting the left motor's PWM to 240
port3.anaWrite(240);
}
// reverse function, this function moves the vehicle in reverse
void reverse() {
// seeting the directions of the motors with the I/O expander to reverse
Motor_Directions(LOW,HIGH,LOW,HIGH);
// setting both motor's PWM to be the same which means the vehicle will move backward
// setting the right motor's PWM to 240
port4.anaWrite(240);
// setting the left motor's PWM to 240
port3.anaWrite(240);
}
/* This function receives the status from the remote and the directions of the motors
* Paramters; vehicle_status: sent by the remote: 1 means the remote will be controlling the vehicle
* 0 means the vehicle will be autonomous
* direc: the directions of the motors, this will select forward or backward for each motor
* r_motor: the PWM rate of the right motor read from the remote
* l_motor: the PWM rate of the left motor read from the remote
*/
void jeenode_receive(bool *vehicle_status, unsigned char* direc, byte *r_motor,byte *l_motor, int *number)
{
// setting a 3 byte array to hold the data received
byte recv_msg[3];
byte temp;
// checking if data receiving is done
if (rf12_recvDone())
{
// placing the data received in the array
memcpy(&recv_msg, (byte *)rf12_data, sizeof(byte)*3);
temp=recv_msg[0];
// checking the vehicle status based on the MSNibble of the first byte
if ((temp&0xF0) == 0xF0){
*vehicle_status = true;
}else{
*vehicle_status = false;
return;
}
// setting the direction based on the LSNibble of the first byte
*direc = recv_msg[0] & 0x0F;
*direc = *direc << 4;
// setting the right and left motor directions based on the second and third bytes
*r_motor = recv_msg[1];
*l_motor = recv_msg[2];
*number=0;
}else if(*number>15){
// setting the vehicle status to false which means the vehicle is autonomous
*vehicle_status = false;
*number=0;
}
}
/*
* This function is specific to the LED setup used for Group Hotel in ELEC3907 Project
* distance is the status of the 4 LEDs used to show how far the vehicle is
* C1 controls the blue LED (Remote controlled) and C2 controls the red LED (not following)
* distance is either 0x00 (00000000), 0x01 (00000001), 0x03 (00000011), 0x07 (00000111), 0x0F (00001111)
*/
void LEDs_control(unsigned char distance, bool C1, bool C2){
// setting temporary variables to be used
unsigned char trigger=0;
// temp is set to the MSb of the 4 LEDs
unsigned char temp = distance&0x08;
// temp is shifted 2 to the left (bit 5)
temp = temp<<2;
// bits 7 and 6 are set with the C2 and C1 values
trigger |= C2<<7;
trigger |= C1<<6;
// bit 5 is set with the temp value
trigger |= temp;
// temp is set to the 3 MSb
temp = distance&0x07;
// temp is shifted 1 to the left (bits 3,2,1)
temp = temp<<1;
// bits 3,2,1 are set to temp value
trigger |= temp;
// setting the I/O expander port 1 to output the LEDs status
MCP_WritePort(1, trigger);
}
// getting the IR values from the left and right IRs
// Returns a stucture of type IR_Vals
struct IR_Vals IR_Get()
{
//port 1 is left, port 2 is right
int IR_L=0,IR_R=0;
// reading 20 IR values for both left and right
for(int i=0; i<20; i++)
{
// reading the left IR
IR_L += port1.anaRead(); // read from AIO of the “port”
// reading the right IR
IR_R += port2.anaRead(); // read from AIO of the “port"
}
// averaging the IR values
IR_L /= 20;
IR_R /= 20;
// creating an IR structure
struct IR_Vals IR_Values;
// saving the values in the structure
IR_Values.IR_L = IR_L;
IR_Values.IR_R = IR_R;
// returning the structure
return IR_Values;
}
// This function returns the ultrasound distance read
float getUltrasound()
{
// duration variable
long duration = 0;
// distance variable
float distance = 0;
// reading 10 ultrasound values
for(int n=0; n<10 ; n++){
// setting port 2 to be output
port2.mode(OUTPUT);
// setting the output to low
port2.digiWrite(LOW);
// delaying the output by 2 microseconds
delayMicroseconds(2);
// setting the output to high
port2.digiWrite( HIGH);
// leaving the output high for 5 microseconds (5 microseconds pulse)
delayMicroseconds(5);
// turning the output back to low
port2.digiWrite(LOW);
// setting the port to input
port2.mode(INPUT);
// measuring the time the input is high
duration = port2.pulse(HIGH);
// setting the distance based on the formula specified from the duration
distance += (2*(duration/29));
}
// averaging the distance
distance /= 10;
// returning the distance
return (distance);
}
// JeeNode setup function
void setup() {
// initializing RF communications
rf12_initialize(1, RF12_915MHZ, 69);//201,3 for proximity. 69,1 for joystick
// starting I2C
Start_I2C();
// setting the directions of the I/O expander ports to output
IOState CurrentState = MCP_SetDirection(0x00,0x00);
// setting the analog ports to input in port2 1 and 2
port1.mode2(INPUT);
port2.mode2(INPUT);
// setting the digital ports to output in ports 3 and 4
port3.mode(OUTPUT);
port4.mode(OUTPUT);
}
// vehicle status (remote controlled or autonomous)
bool vehicle_status;
// direction for the motors from the remote
unsigned char direc;
// left and right motor values from the remote
byte r_motor;
byte l_motor;
int number=0;
// JeeNode loop function
void loop() {
// receiving the data from the remote
jeenode_receive(&vehicle_status, &direc, &r_motor, &l_motor, &number);
number++;
// setting the I/O expamder directions to be output
IOState CurrentState = MCP_SetDirection(0x00,0x00);
// checking if the vehicle is remote controlled or autonomous
if (vehicle_status == true)
{
// vehicle is remote controlled
// setting the LEDs to display blue for remote controlled
LEDs_control(0x00, vehicle_status,0);
// setting the motor directions from the remote
MCP_WritePort(0, direc);
// setting the right and left motor values from the remote
port4.anaWrite(r_motor);
port3.anaWrite(l_motor);
}
else
{
// temporary variables to hold the IR values and the distance from the ultrasound
int IR_L=0,IR_R=0;
float duration;
// reading the IR values structure and saving the values in the temporary variables earlier
struct IR_Vals values = IR_Get();
IR_L = values.IR_L;
IR_R = values.IR_R;
// getting the ultrasound distance
duration = getUltrasound();
// setting the LEDs depending on the status of the car
if(duration > 100){
// car is far away and not being autonomous
LEDs_control(0x00,0,1);
}else if(duration > 75){
// car is far but following
LEDs_control(0x01,0,0);
}else if(duration > 45){
// car is medium distance and following
LEDs_control(0x03,0,0);
}else if(duration > 25){
// car is closer distance and following
LEDs_control(0x07,0,0);
}else if(duration > 15){
// car is really close and following
LEDs_control(0x0F,0,0);
}else {
// car is too close and not following
LEDs_control(0x0F,0,1);
}
// checking if the car is too close or too far to not follow
if((duration < 15) || (duration > 100)){
// car is either too close or too far and cannot follow the car infront
stops();
}else{
if( (IR_R-70) > IR_L ){
// hard right turn must be performed
turnHardRight();
}else if( (IR_L-70) > IR_R ){
// hard left turn must be performed
turnHardLeft();
}else if( IR_R > IR_L ){
// normal right turn must be performed
turnRight();
}else{
// normal left turn must be performed
turnLeft();
}
}
}
}
|
#include<iostream>
using std::cout; using std::cin; using std::endl;
int main()
{
int result = 12/3 * 4 + 5 *15 + 24%4/2;
cout << result << endl;
return 0;
}
|
#include "common.h"
#include "bintable.h"
#include "pythonutils.h"
#include "numpy.h"
#include "exceptions.h"
#include <vector>
#include <string>
#include <cstdio>
#include <pybind11/pybind11.h>
#include <numpy/arrayobject.h>
namespace py = pybind11;
using namespace NAMESPACE_BINTABLE;
void _delete_columns(std::vector<BinTableColumnData *> &columns)
{
for (BinTableColumnData *column : columns)
{
delete column->name;
delete column;
}
}
void write_table_interface(const py::dict columns_dict, const std::string &path, bool append)
{
std::vector<BinTableColumnData *> columns;
columns.reserve(columns_dict.size());
try
{
for (auto name_data : columns_dict)
{
BinTableColumnData *column = new BinTableColumnData();
column->name = new BinTableString();
python_string_to_table_string(name_data.first.ptr(), *(column->name));
column_data_from_numpy_array((PyArrayObject *)name_data.second.ptr(), *column);
columns.push_back(column);
}
write_table(columns, path, append);
}
catch (const std::exception& ex)
{
_delete_columns(columns);
if (!append)
{
remove(path.c_str());
}
throw;
}
_delete_columns(columns);
}
py::dict read_table_interface(const std::string &path)
{
std::vector<BinTableColumnData *> columns;
read_table(path, columns);
py::dict dict;
for (auto col : columns)
{
auto key = py::reinterpret_steal<py::str>(table_string_to_python_string(*(col->name)));
auto value = py::reinterpret_steal<py::object>(numpy_array_from_column_data(*col));
dict[key] = value;
}
_delete_columns(columns);
return dict;
}
py::dict read_header_interface(const std::string &path)
{
BinTableHeader header = read_header(path);
py::dict dict;
dict["version"] = header.version;
dict["n_rows"] = header.n_rows;
dict["n_columns"] = header.n_columns;
py::dict cols_dict;
for (auto it = header.columns.begin(); it != header.columns.end(); it++)
{
auto &col = *it;
cols_dict[col.name->to_string().c_str()] = DATATYPE_NAME[col.type];
}
dict["columns"] = cols_dict;
return dict;
}
PYBIND11_MODULE(native, m)
{
m.doc() = "Bintable native code"; // optional module docstring
m.attr("USE_LITTLE_ENDIAN") = py::int_(USE_LITTLE_ENDIAN);
m.def("write_table", &write_table_interface, "Function to write table");
m.def("read_table", &read_table_interface, "Function to read table");
m.def("read_header", &read_header_interface, "Function to read header");
py::register_exception<BinTableException>(m, "BinTableException");
}
|
#pragma once
#include <OGLML/Texture2D.h>
#include <OGLML/Shader.h>
#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <array>
namespace oglml
{
class Sprite
{
public:
Sprite();
~Sprite() = default;
void SetTexture(Texture2D& texture);
void SetShader(Shader& shader);
void SetScreenSize(float width, float height);
void SetRotateAngle(float rotate);
void SetColor(const std::array<float, 3>& color);
void SetPosition(const std::array<float, 2>& position);
void SetSize(const std::array<float, 2>& size);
float GetRotateAngle() const;
const glm::vec3& GetColor() const;
const glm::vec2& GetPosition() const;
const glm::vec2& GetSize() const;
const glm::mat4& GetProj() const;
unsigned int GetTextureID() const;
unsigned int GetShaderID() const;
private:
unsigned int m_textureID = 0;
unsigned int m_shaderID = 0;
glm::mat4 m_projection = glm::ortho(0.0f, 800.0f, 600.0f, 0.0f, -1.0f, 1.0f);
glm::vec2 m_position = glm::vec2(0.);
glm::vec2 m_size = glm::vec2(1.);
glm::vec3 m_color = glm::vec3(1.);
float m_rotate = 0.f;
};
}
|
// Created by: Eugeny MALTCHIKOV
// Copyright (c) 2018 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 _BRepAlgoAPI_Defeaturing_HeaderFile
#define _BRepAlgoAPI_Defeaturing_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <BOPAlgo_RemoveFeatures.hxx>
#include <BRepAlgoAPI_Algo.hxx>
//! The BRepAlgoAPI_Defeaturing algorithm is the API algorithm intended for
//! removal of the unwanted parts from the shape. The unwanted parts
//! (or features) can be holes, protrusions, gaps, chamfers, fillets etc.
//! The shape itself is not modified, the new shape is built as the result.
//!
//! The actual removal of the features from the shape is performed by
//! the low-level *BOPAlgo_RemoveFeatures* tool. So the defeaturing algorithm
//! has the same options, input data requirements, limitations as the
//! low-level algorithm.
//!
//! <b>Input data</b>
//!
//! Currently, only the shapes of type SOLID, COMPSOLID, and COMPOUND of Solids
//! are supported. And only the FACEs can be removed from the shape.
//!
//! On the input the algorithm accepts the shape itself and the
//! features which have to be removed. It does not matter how the features
//! are given. It could be the separate faces or the collections
//! of faces. The faces should belong to the initial shape, and those that
//! do not belong will be ignored.
//!
//! <b>Options</b>
//!
//! The algorithm has the following options:
//! - History support;
//!
//! and the options available from base class:
//! - Error/Warning reporting system;
//! - Parallel processing mode.
//!
//! Please note that the other options of the base class are not supported
//! here and will have no effect.
//!
//! For the details on the available options please refer to the description
//! of *BOPAlgo_RemoveFeatures* algorithm.
//!
//! <b>Limitations</b>
//!
//! The defeaturing algorithm has the same limitations as *BOPAlgo_RemoveFeatures*
//! algorithm.
//!
//! <b>Example</b>
//!
//! Here is the example of usage of the algorithm:
//! ~~~~
//! TopoDS_Shape aSolid = ...; // Input shape to remove the features from
//! TopTools_ListOfShape aFeatures = ...; // Features to remove from the shape
//! Standard_Boolean bRunParallel = ...; // Parallel processing mode
//! Standard_Boolean isHistoryNeeded = ...; // History support
//!
//! BRepAlgoAPI_Defeaturing aDF; // De-Featuring algorithm
//! aDF.SetShape(aSolid); // Set the shape
//! aDF.AddFacesToRemove(aFaces); // Add faces to remove
//! aDF.SetRunParallel(bRunParallel); // Define the processing mode (parallel or single)
//! aDF.SetToFillHistory(isHistoryNeeded); // Define whether to track the shapes modifications
//! aDF.Build(); // Perform the operation
//! if (!aDF.IsDone()) // Check for the errors
//! {
//! // error treatment
//! Standard_SStream aSStream;
//! aDF.DumpErrors(aSStream);
//! return;
//! }
//! if (aDF.HasWarnings()) // Check for the warnings
//! {
//! // warnings treatment
//! Standard_SStream aSStream;
//! aDF.DumpWarnings(aSStream);
//! }
//! const TopoDS_Shape& aResult = aDF.Shape(); // Result shape
//! ~~~~
//!
//! The algorithm preserves the type of the input shape in the result shape. Thus,
//! if the input shape is a COMPSOLID, the resulting solids will also be put into a COMPSOLID.
//!
class BRepAlgoAPI_Defeaturing: public BRepAlgoAPI_Algo
{
public:
DEFINE_STANDARD_ALLOC
public: //! @name Constructors
//! Empty constructor
BRepAlgoAPI_Defeaturing()
:
BRepAlgoAPI_Algo(),
myFillHistory(Standard_True)
{}
public: //! @name Setting input data for the algorithm
//! Sets the shape for processing.
//! @param theShape [in] The shape to remove the features from.
//! It should either be the SOLID, COMPSOLID or COMPOUND of Solids.
void SetShape(const TopoDS_Shape& theShape)
{
myInputShape = theShape;
}
//! Returns the input shape
const TopoDS_Shape& InputShape() const
{
return myInputShape;
}
//! Adds the features to remove from the input shape.
//! @param theFace [in] The shape to extract the faces for removal.
void AddFaceToRemove(const TopoDS_Shape& theFace)
{
myFacesToRemove.Append(theFace);
}
//! Adds the faces to remove from the input shape.
//! @param theFaces [in] The list of shapes to extract the faces for removal.
void AddFacesToRemove(const TopTools_ListOfShape& theFaces)
{
TopTools_ListIteratorOfListOfShape it(theFaces);
for (; it.More(); it.Next())
myFacesToRemove.Append(it.Value());
}
//! Returns the list of faces which have been requested for removal
//! from the input shape.
const TopTools_ListOfShape& FacesToRemove() const
{
return myFacesToRemove;
}
public: //! @name Performing the operation
//! Performs the operation
Standard_EXPORT virtual void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE;
public: //! @name History Methods
//! Defines whether to track the modification of the shapes or not.
void SetToFillHistory(const Standard_Boolean theFlag)
{
myFillHistory = theFlag;
}
//! Returns whether the history was requested or not.
Standard_Boolean HasHistory() const { return myFillHistory; }
//! Returns the list of shapes modified from the shape <theS> during the operation.
Standard_EXPORT virtual const TopTools_ListOfShape& Modified(const TopoDS_Shape& theS) Standard_OVERRIDE;
//! Returns the list of shapes generated from the shape <theS> during the operation.
Standard_EXPORT virtual const TopTools_ListOfShape& Generated(const TopoDS_Shape& theS) Standard_OVERRIDE;
//! Returns true if the shape <theS> has been deleted during the operation.
//! It means that the shape has no any trace in the result.
//! Otherwise it returns false.
Standard_EXPORT virtual Standard_Boolean IsDeleted(const TopoDS_Shape& theS) Standard_OVERRIDE;
//! Returns true if any of the input shapes has been modified during operation.
Standard_EXPORT virtual Standard_Boolean HasModified() const;
//! Returns true if any of the input shapes has generated shapes during operation.
Standard_EXPORT virtual Standard_Boolean HasGenerated() const;
//! Returns true if any of the input shapes has been deleted during operation.
Standard_EXPORT virtual Standard_Boolean HasDeleted() const;
//! Returns the History of shapes modifications
Handle(BRepTools_History) History()
{
return myFeatureRemovalTool.History();
}
protected: //! @name Setting the algorithm into default state
virtual void Clear() Standard_OVERRIDE
{
BRepAlgoAPI_Algo::Clear();
myFeatureRemovalTool.Clear();
}
protected: //! @name Fields
TopoDS_Shape myInputShape; //!< Input shape to remove the features from
TopTools_ListOfShape myFacesToRemove; //!< Features to remove from the shape
Standard_Boolean myFillHistory; //!< Defines whether to track the history of
//! shapes modifications or not (true by default)
BOPAlgo_RemoveFeatures myFeatureRemovalTool; //!< Tool for the features removal
};
#endif // _BRepAlgoAPI_Defeaturing_HeaderFile
|
#pragma once
#include <AbstractLogListener.h>
namespace breakout
{
class ConsoleLogListener : public AbstractLogListener
{
public:
ConsoleLogListener(const uint16_t& levelMask, const uint16_t& channelMask);
virtual ~ConsoleLogListener();
protected:
virtual void Write(const std::string& text) override;
};
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MODULES_FORMS_FORMS_MODULE_H
#define MODULES_FORMS_FORMS_MODULE_H
#if defined _SSL_SUPPORT_ && !defined _EXTERNAL_SSL_SUPPORT_ && !defined SSL_DISABLE_CLIENT_CERTIFICATE_INSTALLATION
# define FORMS_KEYGEN_SUPPORT
#endif // defined _SSL_SUPPORT_ && !defined _EXTERNAL_SSL_SUPPORT_
#include "modules/hardcore/opera/module.h"
class FormsHistory;
class FormSubmitter;
/**
* Class for global data in the forms module.
*/
class FormsModule : public OperaModule
{
public:
FormsModule()
{
m_forms_history = NULL;
#ifdef FORMS_KEYGEN_SUPPORT
m_submits_in_progress = NULL;
#endif // FORMS_KEYGEN_SUPPORT
}
virtual void InitL(const OperaInitInfo& info);
virtual void Destroy();
FormsHistory* m_forms_history;
#ifdef FORMS_KEYGEN_SUPPORT
FormSubmitter* m_submits_in_progress; // Submits waiting for UI feedback
#endif // FORMS_KEYGEN_SUPPORT
};
#define g_forms_history g_opera->forms_module.m_forms_history
#define FORMS_MODULE_REQUIRED
#endif // !MODULES_FORMS_FORMS_MODULE_H
|
#include<bits/stdc++.h>
using namespace std;
int stepup(int sc, int start, int end);
int main(){
int end = 1;
cout<<(0, 0, end);
return 0;
}
int stepup(int sc, int start, int end){
if (abs(sc) > (end))
return INT_MAX;
if (sc == end){
return start;
}
int pos = stepup(sc + start + 1,
start + 1, end);
int neg = stepup(sc - start - 1,
start + 1, end);
return min(pos, neg);
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "struc.h"
//alocarea si realocarea memoriei
student* reloc(student *a,int n){
a=(student*)realloc(a,n*sizeof(student));
if(!a){
printf("\a\nNu sa alocat memorie!\n");
system("pause");
exit(1);
}
return a;
}
//Versiunea 1 de citire Manual
void intro1(student *a,int n){
int i;
for(i=0;i<n;i++){
printf("\n****************************************\n\n");
printf("Introdu datele studentului %d\n",i+1);
printf("Numele: ");
scanf("%s",&a[i].num);
printf("Prenumele: ");
scanf("%s",&a[i].pre);
printf("Specialitatea: ");
scanf("%s",&a[i].spec);
printf("Anul de inmatriculare: ");
scanf("%d",&a[i].anu);
printf("Media de intrare: ");
scanf("%f",&a[i].med);
}
}
//Versiunea 2 de citire(Fisier)
student* intro2(char *fname,int *n){
int i=0,m=0;
student *a=NULL;
FILE *demo=fopen(fname,"r"); //deschiderea fisierului din aceeasi mapa, "r" read ,"t" text
if(!demo){
printf("\aFisierul nu exista!\n");
system("pause");
exit(1);
}
while(!feof(demo)){
m++;
a=reloc(a,m);
fscanf(demo,"%s%s%s%d%f",&a[i].num,&a[i].pre,&a[i].spec,&a[i].anu,&a[i].med);
i++;
}
*n=m;
fclose(demo);
return a;
}
//Afisare simpla a datelor
void afisare (student *a,int n){
int i;
for(i=0;i<n;i++){
printf("****************************************\n\n");
printf("Datele studentului: %d\n",i+1);
printf("Numele: %s\n",a[i].num);
printf("Prenumele: %s\n",a[i].pre);
printf("Specialitatea: %s\n",a[i].spec);
printf("Anul de inmatriculare: %d\n",a[i].anu);
printf("Media de intrare: %.2f\n\n",a[i].med);
}
}
//Afisare dupa anul introdus(cautare dupa an)
void afis_an(student *a, int n,int an){
int i,j=0;
printf("Studentii anului: %d\n\n",an);
for(i=0;i<n;i++){
if(a[i].anu==an){
printf("****************************************\n\n");
printf("Nr. de ordine: %d\n",i+1);
printf("Numele: %s\n",a[i].num);
printf("Prenumele: %s\n",a[i].pre);
printf("Specialitatea: %s\n",a[i].spec);
printf("Anul de inmatriculare: %d\n",a[i].anu);
printf("Media de intrare: %.2f\n\n",a[i].med);
j++;
}
}
if(!j){
system("cls");
printf("Nu s-au gasit studenti din anul %d\n\n",an);
}
}
//Functia pentru adaugarea studentilor
void add_std(student *a,int *n,int nr){
int i;
a=reloc(a,*n+nr);
for(i=*n;i<*n+nr;i++){
printf("\n****************************************\n\n");
printf("Introdu datele studentului %d\n",i+1);
printf("Numele: ");
scanf("%s",&a[i].num);
printf("Prenumele: ");
scanf("%s",&a[i].pre);
printf("Specialitatea: ");
scanf("%s",&a[i].spec);
printf("Anul de inmatriculare: ");
scanf("%d",&a[i].anu);
printf("Media de intrare: ");
scanf("%f",&a[i].med);
}
*n=*n+nr;
}
//functia pentru stergere
void del_std(student *a,int *n,int nd){
int i;
*n=*n-1;
if(*n>0){
for(i=nd;i<*n;i++){
a[i]=a[i+1];
}
}else
printf("\nNu mai sunt studenti!\a\n");
a=reloc(a,*n);
}
//functia de salvare
void save(student *a,int n,char *fname){
int i;
FILE *demo=fopen(fname,"wt");
for(i=0;i<n;i++){
fprintf(demo,"%s %s %s %d %.2f",a[i].num,a[i].pre,a[i].spec,a[i].anu,a[i].med);
if(i<n-1)
fprintf(demo,"\n");
}
fclose(demo);
}
//afisarea studentilor in ordine descrescatoare dupa medie
void ord_cr(student *a,int n){
int i,j;
student t;
for(i=0;i<n-1;i++){
for(j=i+1;j<n;j++){
if(a[i].med<a[j].med){
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
afisare(a,n);
}
//modificarea datelor
void std_m(student *a,int nm){
nm=nm-1;
printf("\n****************************************\n\n");
printf("Nr. de ordine: %d\n",nm+1);
printf("Numele: %s\n",a[nm].num);
printf("Prenumele: %s\n",a[nm].pre);
printf("Specialitatea: %s\n",a[nm].spec);
printf("Anul de inmatriculare: %d\n",a[nm].anu);
printf("Media de intrare: %.2f\n\n",a[nm].med);
printf("****************************************\n\n");
printf("Introdu datele studentului pentru modificare:\n");
printf("Numele: ");
scanf("%s",&a[nm].num);
printf("Prenumele: ");
scanf("%s",&a[nm].pre);
printf("Specialitatea: ");
scanf("%s",&a[nm].spec);
printf("Anul de inmatriculare: ");
scanf("%d",&a[nm].anu);
printf("Media de intrare: ");
scanf("%f",&a[nm].med);
}
|
// Created on: 2013-11-11
// Created by: Anastasia BORISOVA
// Copyright (c) 2013-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 Prs3d_DimensionUnits_HeaderFile
#define Prs3d_DimensionUnits_HeaderFile
#include <TCollection_AsciiString.hxx>
//! This class provides units for two dimension groups:
//! - lengths (length, radius, diameter)
//! - angles
class Prs3d_DimensionUnits
{
public:
//! Default constructor. Sets meters as default length units
//! and radians as default angle units.
Prs3d_DimensionUnits()
: myLengthUnits ("m"),
myAngleUnits ("rad")
{}
Prs3d_DimensionUnits (const Prs3d_DimensionUnits& theUnits)
: myLengthUnits (theUnits.GetLengthUnits()),
myAngleUnits (theUnits.GetAngleUnits())
{}
//! Sets angle units
void SetAngleUnits (const TCollection_AsciiString& theUnits) { myAngleUnits = theUnits; }
//! @return angle units
const TCollection_AsciiString& GetAngleUnits() const { return myAngleUnits; }
//! Sets length units
void SetLengthUnits (const TCollection_AsciiString& theUnits) { myLengthUnits = theUnits; }
//! @return length units
const TCollection_AsciiString& GetLengthUnits() const { return myLengthUnits; }
private:
TCollection_AsciiString myLengthUnits;
TCollection_AsciiString myAngleUnits;
};
#endif
|
#pragma once
#include <glm/glm.hpp>
#include "EventHandeling\Event.h"
#include "EventHandeling\EventHandeler.h"
#include <memory>
/*
From learnopengl.com
*/
class Camera : public EventHandeler<MovementEvent>, public EventHandeler<MouseMovementEvent>
{
public:
Camera(glm::ivec2 dimensions, glm::vec3 position, float fov, float near, float far, float rotationSpeed, float movementSpeed);
~Camera();
void setMoveSpeed(float moveSpeed);
void setRotationSpeed(float rotationSpeed);
glm::mat4 ViewMatrix();
glm::mat4 ProjectionMatrix();
glm::mat4 ProjectionViewMatrix();
glm::mat4 InverseProjectionViewMatrix();
void setPitch(float pitch);
void setYaw(float yaw);
//worldSpace -> clipSpace
glm::vec3 project(glm::vec3 worldCoord);
//clipSpace -> worldSpace
glm::vec3 unProject(glm::vec3 clipSpaceCoord);
void shouldUpdate(bool state);
void handle(std::shared_ptr<MovementEvent> e) override;
void handle(std::shared_ptr<MouseMovementEvent> e) override;
private:
void updateCameraVectors();
public:
float Yaw;
float Pitch;
float FOV;
float Near;
float Far;
glm::vec3 Position;
glm::vec3 Front;
glm::vec3 Up;
glm::vec3 Right;
glm::ivec2 Dimensions;
private:
bool _shouldUpdate;
float _moveSpeed;
float _rotationSpeed;
bool _constrainPitch;
};
|
#include "ClientHandler.h"
#ifdef CLIENT_H
int main() {
}
#endif
|
#ifndef BOARD_H
#define BOARD_H
#include "brick.h"
class Brick;
class Board
{
public:
int score;//当前分数
int scoreRank[10];
Brick *brick;//下落的方块
char map[100][100];//保存地图信息
Board();
void addTomap();//将下落到底的块更新到map
bool endJudge();//判断是否游戏结束
};
#endif // BOARD_H
|
#ifndef CPP_2020_RANDOM_FOREST_RANDOM_FOREST_H
#define CPP_2020_RANDOM_FOREST_RANDOM_FOREST_H
#include <iostream>
#include <string>
#include <cstdlib>
#include <queue>
#include <thread>
#include <mutex>
#include <cmath>
#include "data.h"
#include "decision_tree.h"
class tree_queue {
public:
std::queue<Tree> base_queue_m;
std::mutex write_mutex_m;
void push(Tree&& t);
bool pop(Tree& t);
};
class RandomForest {
std::vector<Tree> trees_m;
int max_depth_m;
int random_state_m;
int n_estimators_m;
double entropy_threshold_m = 0.0;
int n_jobs_m;
public:
RandomForest(int n_estimators, double entropy_threshold, int max_depth, int random_state, int n_jobs);
void fit(dataset& tr_ds);
void build_trees(dataset& tr_ds, tree_queue& todo_trees, tree_queue& out_trees);
std::vector<int> generate_subset(int len, random_gen_type& random_gen);
target_type predict(feature_matrix_type& X);
int predict(feature_type& x);
};
#endif //CPP_2020_RANDOM_FOREST_RANDOM_FOREST_H
|
#ifndef PIONEER_H
#define PIONEER_H
#include <iostream>
#include <string>
#include <vector>
#include <QtSql>
#include <QtWidgets>
using namespace std;
class Pioneer
{
public:
Pioneer();
//Default constructor
Pioneer(string pName, string s, int birthY, int deathY, string desc, QByteArray image);
// Constructor without id
Pioneer(int index, string pName, string s, int bYear, int dYear, string desc, QByteArray image);
// Constructor with id
int getId();
// Returns ID of pioneer
string getName();
// Returns name of pioneer
string getSex();
// Returns sex of pioneer
int getByear();
// Returns birth year of pioneer
int getDyear();
// Returns year of death of pioneer
string getDescription();
// Returns description of pioneer
int getYear(int number);
// Returns year of birth if number == 1 / Returns year of death if number == 2
QByteArray getImageByteArray();
// Returns binary array of pioneer's image
private:
int id; // Primary Key of pioneer
string name; // Last Name of pioneer
string sex; // Sex of poineer
int bYear; // Birthyear of pioneer
int dYear; // Deathyear of pioneer
string description; // Description of what the person is famous for
QByteArray imageByteArray; //Image of pioneer
};
#endif // PIONEER_H
|
#include "core/pch.h"
#include "modules/ecmascript/carakan/src/util/es_codegenerator_arm.h"
void Output(ES_CodeGenerator &cg, const char *name)
{
unsigned *code = cg.GetBuffer();
printf("const MachineInstruction cv_%s[] =\n{\n", name);
for (unsigned index = 0; index < cg.GetBufferUsed(); ++index)
printf(" 0x%x%s\n", code[index], index + 1 == cg.GetBufferUsed() ? "" : ",");
printf("};\n");
}
// BOOL StartImpl(OpPseudoThread *thread, OpPseudoThread::Callback callback, unsigned char **original_stack, unsigned char *thread_stack)
void generate_StartImpl()
{
ES_CodeGenerator cg;
cg.PUSH(0x5ff0); // PUSH { R4-R12, LR }
cg.MOV(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R4); // store original_stack in R4 for later use
cg.STR(ES_CodeGenerator::REG_SP, ES_CodeGenerator::REG_R2, 0); // *original_stack = <SP>;
cg.MOV(ES_CodeGenerator::REG_R3, ES_CodeGenerator::REG_SP); // <SP> = thread_stack;
cg.BLX(ES_CodeGenerator::REG_R1); // callback(thread)
cg.LDR(ES_CodeGenerator::REG_R4, 0, ES_CodeGenerator::REG_SP); // restore SP from original_stack (in R4)
cg.MOV(1, ES_CodeGenerator::REG_R0);
cg.POP(0x9ff0); // POP { R4-R12, PC }
Output(cg, "StartImpl");
}
// BOOL ResumeImpl(OpPseudoThread *thread, unsigned char **original_stack, unsigned char *thread_stack)
void generate_ResumeImpl()
{
ES_CodeGenerator cg;
cg.PUSH(0x4ff0); // PUSH { R4-R12, LR }
cg.STR(ES_CodeGenerator::REG_SP, ES_CodeGenerator::REG_R1, 0); // *original_stack = <SP>;
cg.MOV(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_SP); // <SP> = thread_stack;
cg.POP(0x8ff0); // POP { R4-R12, PC }
Output(cg, "ResumeImpl");
}
// BOOL YieldImpl(OpPseudoThread *thread, unsigned char **thread_stack, unsigned char *original_stack)
void generate_YieldImpl()
{
ES_CodeGenerator cg;
cg.PUSH(0x4ff0); // PUSH { R4-R12, LR }
cg.STR(ES_CodeGenerator::REG_SP, ES_CodeGenerator::REG_R1, 0); // *thread_stack = <SP>;
cg.MOV(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_SP); // <SP> = original_stack;
cg.MOV(0, ES_CodeGenerator::REG_R0);
cg.POP(0x8ff0); // POP { R4-R12, PC }
Output(cg, "YieldImpl");
}
// BOOL SuspendImpl(OpPseudoThread *thread, OpPseudoThread::Callback callback, unsigned char *original_stack)
void generate_SuspendImpl()
{
ES_CodeGenerator cg;
cg.PUSH(0x4ff0); // PUSH { R4-R12, LR }
cg.MOV(ES_CodeGenerator::REG_SP, ES_CodeGenerator::REG_R4); // store SP in R4 for later use
cg.MOV(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_SP); // <SP> = original_stack;
cg.BLX(ES_CodeGenerator::REG_R1); // callback(thread)
cg.MOV(ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_SP); // restore SP from R4
cg.POP(0x8ff0); // POP { R4-R12, PC }
Output(cg, "SuspendImpl");
}
// BOOL ReserveImpl(OpPseudoThread *thread, OpPseudoThread::Callback callback, unsigned char *new_stack_ptr)
void generate_ReserveImpl()
{
ES_CodeGenerator cg;
cg.PUSH(0x4ff0); // PUSH { R4-R12, LR }
cg.MOV(ES_CodeGenerator::REG_SP, ES_CodeGenerator::REG_R4); // store SP in R4 for later use
cg.MOV(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_SP); // <SP> = new_stack_ptr;
cg.BLX(ES_CodeGenerator::REG_R1); // callback(thread)
cg.MOV(ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_SP); // restore SP from R4
cg.POP(0x8ff0); // POP { R4-R12, PC }
Output(cg, "ReserveImpl");
}
// BOOL StackSpaceRemainingImpl(unsigned char *bottom)
void generate_StackSpaceRemainingImpl()
{
ES_CodeGenerator cg;
cg.SUB(ES_CodeGenerator::REG_SP, ES_CodeGenerator::REG_R0, ES_CodeGenerator::REG_R0);
cg.BX(ES_CodeGenerator::REG_LR);
Output(cg, "StackSpaceRemainingImpl");
}
int main(int argc, char **argv)
{
generate_StartImpl();
generate_ResumeImpl();
generate_YieldImpl();
generate_SuspendImpl();
generate_ReserveImpl();
generate_StackSpaceRemainingImpl();
return 0;
}
|
// Example 8.1 Operator overloading : class Vec2
#include <iostream>
#include <string>
#include "./Vec2.h"
using namespace std;
//==============================
int main() {
{
cout << "\nVec2 constructor, ==, !=, output :\n\n";
Vec2 a(1.0, 2.0), b(1.0, 2.0), c(2.0, 1.0);
// cout << "Enter vector b :" << endl;
// cin >> b;
// Assignment
Vec2 d;
d = c;
// overloaded <<
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "d = " << d << endl;
// getters
cout << "a.getX() = " << a.getX() << endl;
cout << "a.getY() = " << a.getY() << endl;
// overloaded ==, !=
cout << boolalpha;
cout << "(a == a) is " << (a == a) << endl;
cout << "(a != a) is " << (a != a) << endl;
cout << "(a == b) is " << (a == b) << endl;
cout << "(a != b) is " << (a != b) << endl;
cout << "(a == c) is " << (a == c) << endl;
cout << "(a != c) is " << (a != c) << endl;
}
{
cout << "\nVec2 comparison operators (compare x, then y) :\n\n";
Vec2 a(1.0, 2.0), b(1.0, 1.0), c(2.0, 0.0);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "a < b :" << (a < b) << endl;
cout << "a > b :" << (a > b) << endl;
cout << "a <= b :" << (a <= b) << endl;
cout << "a >= b :" << (a >= b) << endl;
cout << "a <= a :" << (a <= a) << endl;
cout << "a >= a :" << (a >= a) << endl;
cout << "a < a :" << (a < a) << endl;
cout << "a > a :" << (a > a) << endl;
cout << "a < c :" << (a < c) << endl;
cout << "a > c :" << (a > c) << endl;
cout << "a <= c :" << (a <= c) << endl;
cout << "a >= c :" << (a >= c) << endl;
}
{
cout << "\nVec2 arithmetics :\n\n";
Vec2 a(-1, 2), b(2, -1);
a += b; // 1 1
cout << "a = " << a << endl;
a -= b; // Back to -1 2
cout << "a = " << a << endl;
a *= 3.0; // a = -3 6
cout << "a = " << a << endl;
a /= 3.0; // Back to -1 2
cout << "a = " << a << endl;
// More arithmetics
Vec2 c = 2.0*a + b*3.0; // 4 1
cout << "c = " << c << endl;
c = a*3.0 - b/0.5 + 2*Vec2{3, -5}; // -1 -2
cout << "c = " << c << endl;
// Finally, the unary minus
c = -c; // 1 2
cout << "c = " << c << endl;
}
{
cout << "\nVec2 exotics :\n\n";
Vec2 a(-13, -666), b(0,0);
a("A Terrible Evil Vector :"); // Function call (string arg)
// operator[] non-const
a[0] = -4;
a[1] = 3;
// a[2] = 3; // throws out_of_range
// operator[] const
const Vec2 & cA = a;
cout << "cA[0] = " << cA[0] << ", cA[1] = " << cA[1] << endl;
// Length, operator double
// operator double is explicit, explicit casts only !
cout << "a.len() = " << a.len() << endl; // As method
cout << "(double)a = " << (double)a << endl; // As explicit cast
cout << "static_cast<double>(a) = " << static_cast<double>(a) << endl;
// double d = a; // Does not work, as operator double is explicit
// operator bool
// Works in if and ?: even though it's explicit
if (a)
cout << "a is not zero" << endl;
else
cout << "a is zero" << endl;
cout << (b ? "b is not zero" : "b is zero") << endl;
// bool myBool = a; // Error, operator bool is explicit
bool myBool = (bool)a; // OK
}
return 0;
}
|
/*
* Stopping Times
* Copyright (C) Leonardo Marchetti 2011 <leonardomarchetti@gmail.com>
*/
#ifndef _STOPPING_TIMES_H_
#define _STOPPING_TIMES_H_
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <utility>
#include "maximizer.h"
#include "sde.h"
#include "de-solver.h"
#include "maximizer2D.h"
#define EPS 1e-7
namespace StoppingTimes{
/* FP is a template for Floating Point types. */
template <typename FP>
class StoppingTimes
{
public:
~StoppingTimes();
StoppingTimes(boost::function<FP(FP)> mu, boost::function<FP(FP)> sigma, boost::function<FP(FP)> g);
std::pair<FP,FP> getBestInferiorAndSuperiorLimitNew(FP x0, FP rho, int n);
std::pair<FP,FP> getBestInferiorAndSuperiorLimitNewNaive(FP x0, FP rho, int n);
std::pair<FP,FP> getBestInferiorAndSuperiorLimitOld(FP x0, FP rho, int n);
FP getBestSuperiorLimit(FP x0, FP rho, int n);
FP getBestInferiorLimit(FP x0, FP rho, int n);
FP expectedGivenInferiorAndSuperior(FP x0, FP Linf, FP Lsup);
protected:
private:
FP rho_;
SDE<FP> *sde_;
DESolver<FP> solver_;
Maximizer<FP> maximizer_;
boost::function<FP(FP)> A_;
boost::function<FP(FP)> B_;
boost::function<FP(FP)> g_;
FP bestExpectedGainForInferior(FP x0, FP Linf);
};
#include "stoppingTimes.inl"
}
#endif // _STOPPING_TIMES_H_
|
#ifndef SIMGRAPHICS_SIMROOT_H
#define SIMGRAPHICS_SIMROOT_H
#include "include/SimPrerequisites.h"
#include "include/SimSingleton.h"
/*
* @brief Root is used to load modules of the SimEngine ,such as the render module;
*/
namespace sim {
class SIM_ROOT_EXPORT Root : public Singleton<Root>{
public:
// @param init_file: if not NULL, InitEngine() will be called
Root(HINSTANCE instance, const char* init_file = NULL);
~Root();
// @brief load the dlls of the engine, and create renderdevice
void InitEngine(const char* file_name);
// @geter render_device_
RenderDevice* render_device() const{ return render_device_; }
// @geter app_instance_
HINSTANCE app_insance() const { return graphics_dll_; }
// @geter/seter init_file_
void set_init_file(const char* file_name) { init_file_ = file_name;}
const char* init_file() const { return init_file_.c_str(); }
static Root* GetInstancePtr();
static Root& GetInstance();
private:
void CreateDevice(GraphicsAPI api_name);
void Release();
private:
std::string init_file_; // init file name
RenderDevice* render_device_;
HINSTANCE app_instance_;
HMODULE graphics_dll_;
}; // Root
} // sim
#endif
|
// Lexer for Makefile of gmake, nmake, bmake, qmake
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
using namespace Scintilla;
#define MAKE_TYPE_GMAKE 0
#define MAKE_TYPE_NMAKE 1
#define MAKE_TYPE_BMAKE 2
#define MAKE_TYPE_QMAKE 3
static inline bool IsMakeOp(int ch, int chNext) {
return ch == '=' || ch == ':' || ch == '{' || ch == '}' || ch == '(' || ch == ')' || ch == ','
|| ch == '$' || ch == '@' || ch == '%' || ch == '<' || ch == '?' || ch == '^'
|| ch == '|' || ch == '*' || ch == '>' || ch == ';' || ch == '&' || ch == '!'
|| (chNext == '=' && (ch == '+' || ch == '-' || ch == ':'));
}
#define MAX_WORD_LENGTH 15
static void ColouriseMakeDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList keywordLists, Accessor &styler) {
const WordList &keywordsGP = *keywordLists[0]; // gnu make Preprocessor
const WordList &keywordsDP2 = *keywordLists[6];
int state = initStyle;
int ch = 0, chNext = styler[startPos];
styler.StartAt(startPos);
styler.StartSegment(startPos);
Sci_PositionU endPos = startPos + length;
if (endPos == (Sci_PositionU)styler.Length())
++endPos;
int visibleChars = 0;
Sci_Position lineCurrent = styler.GetLine(startPos);
char buf[MAX_WORD_LENGTH + 1] = {0};
int wordLen = 0;
int varCount = 0;
static int makeType = MAKE_TYPE_GMAKE;
for (Sci_PositionU i = startPos; i < endPos; i++) {
const int chPrev = ch;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
const bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
const bool atLineStart = i == (Sci_PositionU)styler.LineStart(lineCurrent);
switch (state) {
case SCE_MAKE_OPERATOR:
styler.ColourTo(i - 1, state);
state = SCE_MAKE_DEFAULT;
break;
case SCE_MAKE_IDENTIFIER:
if (IsMakeOp(ch, chNext) || IsASpace(ch)) {
buf[wordLen] = 0;
if (ch == ':' && chNext == ':') {
styler.ColourTo(i - 1, SCE_MAKE_TARGET);
} else if (makeType == MAKE_TYPE_BMAKE && keywordsDP2.InList(buf)) {
styler.ColourTo(i - 1, SCE_MAKE_PREPROCESSOR);
}
wordLen = 0;
state = SCE_MAKE_DEFAULT;
} else if (wordLen < MAX_WORD_LENGTH) {
buf[wordLen++] = (char)ch;
}
break;
case SCE_MAKE_TARGET:
if (IsMakeOp(ch, chNext) || IsASpace(ch)) {
buf[wordLen] = 0;
if (keywordsGP.InList(buf)) { // gmake
styler.ColourTo(i - 1, SCE_MAKE_PREPROCESSOR);
makeType = MAKE_TYPE_GMAKE;
} else {
Sci_Position pos = i;
while (IsASpace(styler.SafeGetCharAt(pos++)));
if (styler[pos-1] == '=' || styler[pos] == '=') {
styler.ColourTo(i - 1, SCE_MAKE_VARIABLE);
} else if (styler[pos-1] == ':') {
styler.ColourTo(i - 1, SCE_MAKE_TARGET);
} else if (buf[0] == '.' && IsASpace(ch)) { // bmake
styler.ColourTo(i - 1, SCE_MAKE_PREPROCESSOR);
makeType = MAKE_TYPE_BMAKE;
} else {
styler.ColourTo(i - 1, SCE_MAKE_DEFAULT);
}
}
state = SCE_MAKE_DEFAULT;
wordLen = 0;
} else if (wordLen < MAX_WORD_LENGTH) {
buf[wordLen++] = (char)ch;
}
break;
case SCE_MAKE_VARIABLE:
if (!(ch == '$' || iswordchar(ch))) {
styler.ColourTo(i - 1, state);
state = SCE_MAKE_DEFAULT;
}
break;
case SCE_MAKE_VARIABLE2:
if (ch == '$' && chNext == '(') {
varCount++;
} else if (ch == ')') {
varCount--;
if (varCount <= 0) {
styler.ColourTo(i, state);
state = SCE_MAKE_DEFAULT;
continue;
}
}
break;
case SCE_MAKE_VARIABLE3:
if (chPrev == '}') {
styler.ColourTo( i - 1, state);
state = SCE_MAKE_DEFAULT;
} break;
case SCE_MAKE_PREPROCESSOR:
if (!iswordchar(ch)) {
styler.ColourTo(i - 1, state);
state = SCE_MAKE_DEFAULT;
}
break;
case SCE_MAKE_COMMENT:
if (atLineStart) {
styler.ColourTo(i - 1, state);
state = SCE_MAKE_DEFAULT;
}
break;
}
if (state != SCE_MAKE_COMMENT && ch == '\\' && (chNext == '\n' || chNext == '\r')) {
i++;
lineCurrent++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if (ch == '\r' && chNext == '\n') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
continue;
}
if (state == SCE_MAKE_DEFAULT) {
if (ch == '#') {
styler.ColourTo(i - 1, state);
state = SCE_MAKE_COMMENT;
} else if ((ch == '$' && chNext == '(') || (ch == '$' && chNext == '$' && styler.SafeGetCharAt(i + 2) == '(')) {
styler.ColourTo(i - 1, state);
Sci_Position pos = i + 1;
if (chNext == '$') ++pos;
ch = chNext;
while (ch != ')') {
chNext = styler.SafeGetCharAt(pos + 1);
if (ch == '$' && chNext == '(')
break;
if (IsASpace(ch) || ch == ',')
break;
++pos;
ch = chNext;
}
if (ch == ')' || ch == '$') {
styler.ColourTo(pos, SCE_MAKE_VARIABLE2);
if (ch == '$') {
state = SCE_MAKE_VARIABLE2;
varCount = 2;
} else if (atLineStart) {
state = SCE_MAKE_TARGET;
}
} else {
styler.ColourTo(i + 1, SCE_MAKE_OPERATOR);
styler.ColourTo(pos - 1, SCE_MAKE_FUNCTION);
if (ch == ',')
styler.ColourTo(pos, SCE_MAKE_OPERATOR);
}
i = pos;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else if (ch == '$' && chNext == '{') { // bmake
styler.ColourTo(i - 1, state);
state = SCE_MAKE_VARIABLE3;
} else if (ch == '$' && (chNext == '$' || iswordstart(chNext))) {
styler.ColourTo(i - 1, state);
state = SCE_MAKE_VARIABLE;
} else if (visibleChars == 0 && ch == '!' && iswordstart(chNext)) {
styler.ColourTo(i - 1, state);
state = SCE_MAKE_PREPROCESSOR;
makeType = MAKE_TYPE_NMAKE;
} else if (IsMakeOp(ch, chNext) || (visibleChars == 0 && ch == '-')) {
styler.ColourTo(i - 1, state);
state = SCE_MAKE_OPERATOR;
} else if (isgraph(ch)) {
styler.ColourTo(i - 1, state);
buf[wordLen++] = (char)ch;
state = (visibleChars == 0)? SCE_MAKE_TARGET : SCE_MAKE_IDENTIFIER;
}
}
if (atEOL || i == endPos-1) {
lineCurrent++;
visibleChars = 0;
}
if (!isspacechar(ch) && !(visibleChars == 0 && ch == '-')) {
visibleChars++;
}
}
// Colourise remaining document
styler.ColourTo(endPos - 1, state);
}
#define IsCommentLine(line) IsLexCommentLine(line, styler, SCE_MAKE_COMMENT)
static void FoldMakeDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList, Accessor &styler) {
if (styler.GetPropertyInt("fold") == 0)
return;
const bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
const bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
Sci_PositionU endPos = startPos + length;
int visibleChars = 0;
Sci_Position lineCurrent = styler.GetLine(startPos);
int levelCurrent = SC_FOLDLEVELBASE;
if (lineCurrent > 0)
levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
int levelNext = levelCurrent;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (Sci_PositionU i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && atEOL && IsCommentLine(lineCurrent)) {
if (!IsCommentLine(lineCurrent - 1) && IsCommentLine(lineCurrent + 1))
levelNext++;
else if (IsCommentLine(lineCurrent - 1) && !IsCommentLine(lineCurrent+1))
levelNext--;
}
if (atEOL && IsBackslashLine(lineCurrent, styler) && !IsBackslashLine(lineCurrent-1, styler)) {
levelNext++;
}
if (atEOL && !IsBackslashLine(lineCurrent, styler) && IsBackslashLine(lineCurrent-1, styler)) {
levelNext--;
}
if (visibleChars == 0 && (ch == '!' || ch == 'i' || ch == 'e' || ch == 'd' || ch == '.')
&& style == SCE_MAKE_PREPROCESSOR && stylePrev != SCE_MAKE_PREPROCESSOR) {
char buf[MAX_WORD_LENGTH + 1];
Sci_Position j = i;
if (ch == '!' || ch == '.')
j++;
LexGetRangeLowered(j, styler, iswordchar, buf, MAX_WORD_LENGTH);
if ((buf[0] == 'i' && buf[1] == 'f') || strcmp(buf, "define") == 0 || strcmp(buf, "for") == 0)
levelNext++;
else if (strcmp(buf, "endif") == 0 || strcmp(buf, "endef") == 0 || strcmp(buf, "endfor") == 0)
levelNext--;
}
if (style == SCE_MAKE_OPERATOR) { // qmake
if (/*ch == '(' || */ch == '{')
levelNext++;
else if (/*ch == ')' || */ch == '}')
levelNext--;
}
if (!isspacechar(ch))
visibleChars++;
if (atEOL || (i == endPos-1)) {
int levelUse = levelCurrent;
int lev = levelUse | levelNext << 16;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if (levelUse < levelNext)
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelCurrent = levelNext;
visibleChars = 0;
}
}
}
LexerModule lmMake(SCLEX_MAKEFILE, ColouriseMakeDoc, "makefile", FoldMakeDoc);
|
#include "Persona.h"
#include "Poder.h"
#ifndef MAESTRO_H
#define MAESTRO_H
class Maestro:public Persona{
public:
Poder* poder;
Maestro();
Maestro(string,string,int,string,Elemento*, Poder*);
Poder* getPoder();
virtual string toString();
~Maestro();
};
#endif
|
#include "face.h"
Face::Face() : QListWidgetItem(0)
{
}
void Face::assignID(int id)
{
this->id = id;
}
void Face::assignHalfEdge(HalfEdge *halfEdge)
{
this->halfEdge = halfEdge;
}
void Face::assignColor(glm::vec4 color)
{
this->color = color;
}
HalfEdge* Face::getHalfEdge()
{
return halfEdge;
}
glm::vec4 Face::getColor()
{
return color;
}
int Face::getID()
{
return id;
}
|
#include "RecognizerListener.hh"
//#include "str.hh"
RecognizerListener::RecognizerListener(msg::InQueue *in_queue,
RecognizerStatus *recognition)
{
this->m_in_queue = in_queue;
this->m_recognition = recognition;
this->m_stop = false;
this->m_enabled = true;
this->m_thread_created = false;
this->m_wait_ready = false;
pthread_mutex_init(&this->m_disable_lock, NULL);
}
RecognizerListener::~RecognizerListener()
{
pthread_mutex_destroy(&this->m_disable_lock);
}
bool
RecognizerListener::start()
{
this->m_broken_pipe = false;
this->m_wait_ready = 0;
if (this->m_thread_created) {
fprintf(stderr, "Can't create thread for queue: thread already created.");
return false;
}
this->m_stop = false;
if (pthread_create(&this->m_thread, NULL, RecognizerListener::callback, this) != 0) {
fprintf(stderr, "Couldn't create thread for queue.");
return false;
}
this->m_thread_created = true;
return true;
}
void
RecognizerListener::stop()
{
if (this->m_thread_created) {
this->m_stop = true;
pthread_join(this->m_thread, NULL);
this->m_thread_created = false;
}
else {
fprintf(stderr, "Warning: Trying to join thread that is not created "
"in QC::stop.\n");
}
//*/
}
void
RecognizerListener::enable()
{
this->m_enabled = true;
}
void
RecognizerListener::disable()
{
pthread_mutex_lock(&this->m_disable_lock);
this->m_enabled = false;
pthread_mutex_unlock(&this->m_disable_lock);
}
void*
RecognizerListener::callback(void *user_data)
{
RecognizerListener *object = (RecognizerListener*)user_data;
try {
object->run();
}
catch (msg::ExceptionBrokenPipe exception) {
fprintf(stderr,
"Exception received from pipe (fd=%d): %s\n",
exception.get_fd(),
exception.what());
// Just raise a flag, because we want to do proper exception handling in
// the main thread.
object->m_broken_pipe = true;
}
return NULL;
}
void
RecognizerListener::run() throw(msg::ExceptionBrokenPipe)
{
msg::Message message;
bool yield = false;
if (!this->m_in_queue)
return;
while (!this->m_stop) {
pthread_mutex_lock(&this->m_disable_lock);
if (this->m_enabled) {
// Check for broken pipe.
if (this->m_in_queue->get_eof()) {
fprintf(stderr, "Warning: QueueController got eof from input!\n");
pthread_mutex_unlock(&this->m_disable_lock);
throw msg::ExceptionBrokenPipe(this->m_in_queue->get_fd());
}
// Read input from recognizer.
this->m_in_queue->flush();
if (!this->m_in_queue->empty()) {
message = this->m_in_queue->queue.front();
// Check ready message.
if (message.type() == msg::M_READY) {
if (this->m_wait_ready)
this->m_wait_ready = false;
this->m_recognition->set_ready();
}
// This has to be read because it might mean adaptation finished.
if (message.type() == msg::M_RECOG_END) {
this->m_recognition->recognition_end();
}
if (message.type() == msg::M_ADAPT_CANCELLED) {
// FIXME: Show information that adaptation failed
this->m_recognition->cancel_adaptation();
}
if (!this->m_wait_ready) {
// Read recognition message if not waiting for ready.
if (message.type() == msg::M_RECOG) {
// Pass recognition message forward.
// fprintf(stderr, "RECOG: %s\n", message.data_str().c_str());
this->m_recognition->lock();
this->m_recognition->parse(message.buf.substr(msg::header_size));
this->m_recognition->unlock();
this->m_recognition->received_recognition();
}
}
this->m_in_queue->queue.pop_front();
}
else {
// No messages, we can yield.
yield = true;
}
}
else {
// Disabled, we can yield.
yield = true;
}
pthread_mutex_unlock(&this->m_disable_lock);
if (yield) {
pthread_yield();
yield = false;
}
}
}
|
void DisplayModeMain()
{
if (ReadValues.newValues == 1 && ReadValues.ButtonPressed == FuncStop)
{
#if defined(DEBUGMODE)
Serial.print("DisplayMode | Changed to: ");
#endif
switch (Settings.LedEffects[Settings.EffectNumber].DisplayMode)
{
case Left:
Settings.LedEffects[Settings.EffectNumber].DisplayMode = Right;
#if defined(DEBUGMODE)
Serial.println("Right");
#endif
break;
case Right :
Settings.LedEffects[Settings.EffectNumber].DisplayMode = Night;
#if defined(DEBUGMODE)
Serial.println("Night");
#endif
break;
case Night:
Settings.LedEffects[Settings.EffectNumber].DisplayMode = All;
#if defined(DEBUGMODE)
Serial.println("All");
#endif
break;
case All:
Settings.LedEffects[Settings.EffectNumber].DisplayMode = Left;
#if defined(DEBUGMODE)
Serial.println("Left");
#endif
break;
default:
Settings.LedEffects[Settings.EffectNumber].DisplayMode = Left;
#if defined(DEBUGMODE)
Serial.println("Left (default)");
#endif
break;
}
ReadValues.newValues = 0;
SettingsNow.ChangesToEffectMade = true;
//show status update
SettingsNow.ShowACK = 1;
SettingsNow.ShowPercentage = 0;
}
}
|
// 问题的描述:旋转词
// 给定两个字符串,判断它们是否互为旋转词,即A字符串前面一部分字符移到后面形成的新字符串与B字符串相同
// 如 A = "1234", B = "2341"就是其中的一个旋转词
// 关键点在于(A + A)形成的新字符串,包含了A所有的旋转词
// 测试用例有3组:
// 1、空字符串
// 输入:
// string sequence1 = "";
// string sequence2 = "";
// 输出:false
// 2、A、B互为旋转词
// 输入:
// string sequence1 = "abcd";
// string sequence2 = "cdab";
// 输出:true
// 3、A、B互不为旋转词
// 输入:
// string sequence1 = "abcd";
// string sequence2 = "dcab";
// 输出:false
#include <iostream>
#include <string>
using namespace std;
bool CheckRotateWord(const string &sequence1, const string &sequence2) {
if (sequence1.empty() || sequence2.empty() || (sequence1.size() != sequence2.size()))
return false;
string synthesis_word = sequence1 + sequence1;
if (synthesis_word.find(sequence2) != string::npos)
return true;
else
return false;
}
int main() {
// 空字符串
// string sequence1 = "";
// string sequence2 = "";
// A、B互为旋转词
// string sequence1 = "abcd";
// string sequence2 = "cdab";
// A、B互不为旋转词
string sequence1 = "abcd";
string sequence2 = "dcab";
if (CheckRotateWord(sequence1, sequence2))
cout << "true" << endl;
else
cout << "false" << endl;
system("pause");
return 0;
}
|
#include "General.h"
#include "Log.h"
#include "Figure.h"
using namespace RsaToolbox;
#include <QDebug>
#include <QString>
#include <QtTest>
#include <QSignalSpy>
#include <QScopedPointer>
#include <QWidget>
#include <QDialog>
ComplexRowVector makeComplex(QRowVector mag, QRowVector phase_rad);
class test_smoothSqrt : public QObject
{
Q_OBJECT
public:
test_smoothSqrt();
private:
QScopedPointer<Log> log;
int cycle;
QString appName;
QString appVersion;
QString plotFilename;
QString logFilename;
QString logPath;
private Q_SLOTS:
void init();
void cleanup();
void unwrap_data();
void unwrap();
void wrap_data();
void wrap();
void smoothSqrt_data();
void smoothSqrt();
void phaseAtDc_data();
void phaseAtDc();
void fixPhaseAtDc_data();
void fixPhaseAtDc();
};
test_smoothSqrt::test_smoothSqrt() {
cycle = 0;
appName = "test_smoothSqrt";
appVersion = "0";
plotFilename = "%1 %2.png";
logFilename = "%1 %2 Log.txt";
logPath = "../RsaToolboxTest/Results/smoothSqrt Logs";
// Initialize object here
}
void test_smoothSqrt::init() {
// log.reset(new Log(logPath, logFilename.arg(cycle++).arg("init()"), appName, appVersion));
// log.reset();
}
void test_smoothSqrt::cleanup() {
// log.reset(new Log(logPath, logFilename.arg(cycle++).arg("cleanup()"), appName, appVersion));
// log.reset();
}
void test_smoothSqrt::unwrap_data() {
QTest::addColumn<QString>("testCase");
QTest::addColumn<QRowVector>("data");
uint points = 201;
QRowVector mag, phase;
mag = linearSpacing(.99, 1, points);
phase = linearSpacing(0, 0, points);
QTest::newRow("Zero phase") << QString("Zero phase") << RsaToolbox::arg(makeComplex(mag, phase));
points = 401;
mag = linearSpacing(.9, 1, points);
phase = linearSpacing(0, PI, points);
QTest::newRow("Small phase") << QString("Small phase") << RsaToolbox::arg(makeComplex(mag, phase));
points = 501;
mag = linearSpacing(0.9, 1, points);
phase = linearSpacing(PI/2.0, 10.0*PI, points);
QTest::newRow("Medium phase") << QString("Medium phase") << RsaToolbox::arg(makeComplex(mag, phase));
points = 12*2+2;
mag = linearSpacing(.9, 1, points);
phase = linearSpacing(3.0*PI, 15.0*PI, points);
QTest::newRow("Large phase") << QString("Large phase") << RsaToolbox::arg(makeComplex(mag, phase));
}
void test_smoothSqrt::unwrap() {
log.reset(new Log(logPath, logFilename.arg(cycle++).arg("unwrap()"), appName, appVersion));
QFETCH(QString, testCase);
QFETCH(QRowVector, data);
QRowVector result = RsaToolbox::unwrap(data);
log->printLine(testCase + ":");
log->printLine(toString(data, ", "));
log->printLine("Result:");
log->printLine(toString(result, ", "));
QString filename = logPath + "/" + plotFilename;
Figure figure("unwrap", 2, 1);
figure.select(0, 0);
figure.addTrace(data, Qt::red);
figure.select(1, 0);
figure.addTrace(result, Qt::red);
figure.savePng(filename.arg(cycle-1).arg(testCase));
QVERIFY(true);
log.reset();
}
void test_smoothSqrt::wrap_data() {
QTest::addColumn<QString>("testCase");
QTest::addColumn<QRowVector>("data");
QTest::newRow("Zero phase") << QString("Zero Phase") << linearSpacing(0, 0, 201);
QTest::newRow("Small phase") << QString("Small phase") << linearSpacing(0, PI, 401);
QTest::newRow("Medium phase") << QString("Medium phase") << linearSpacing(PI/2.0, 10.0*PI, 501);
QTest::newRow("Large phase") << QString("Large phase") << linearSpacing(3*PI, 15*PI, 12*2+2);
}
void test_smoothSqrt::wrap() {
log.reset(new Log(logPath, logFilename.arg(cycle++).arg("wrap()"), appName, appVersion));
QFETCH(QString, testCase);
QFETCH(QRowVector, data);
QRowVector result = RsaToolbox::wrap(data);
log->printLine(testCase + ":");
log->printLine(toString(data, ", "));
log->printLine("Result:");
log->printLine(toString(result, ", "));
QString filename = logPath + "/" + plotFilename;
Figure figure("wrap", 2, 1);
figure.select(0, 0);
figure.addTrace(data);
figure.select(1, 0);
figure.addTrace(result);
figure.savePng(filename.arg(cycle-1).arg(testCase));
QVERIFY(true);
log.reset();
}
void test_smoothSqrt::smoothSqrt_data() {
QTest::addColumn<QString>("testCase");
QTest::addColumn<ComplexRowVector>("data");
uint points = 201;
QRowVector mag, phase;
mag = linearSpacing(.99, 1, points);
phase = linearSpacing(0, 0, points);
QTest::newRow("Zero phase") << QString("Zero phase") << makeComplex(mag, phase);
points = 401;
mag = linearSpacing(.9, 1, points);
phase = linearSpacing(0, PI, points);
QTest::newRow("Small phase") << QString("Small phase") << makeComplex(mag, phase);
points = 501;
mag = linearSpacing(0.9, 1, points);
phase = linearSpacing(PI/2.0, 10.0*PI, points);
QTest::newRow("Medium phase") << QString("Medium phase") << makeComplex(mag, phase);
points = 12*2+2;
mag = linearSpacing(.9, 1, points);
phase = linearSpacing(3.0*PI, 15.0*PI, points);
QTest::newRow("Large phase") << QString("Large phase") << makeComplex(mag, phase);
}
void test_smoothSqrt::smoothSqrt() {
log.reset(new Log(logPath, logFilename.arg(cycle++).arg("smoothSqrt()"), appName, appVersion));
QFETCH(QString, testCase);
QFETCH(ComplexRowVector, data);
ComplexRowVector result = RsaToolbox::smoothSqrt(data);
log->printLine(testCase + ":");
log->printLine(toString(arg(data), ", "));
log->printLine("Result:");
log->printLine(toString(arg(result), ", "));
QString filename = logPath + "/" + plotFilename;
Figure figure("wrap", 2, 1);
figure.select(0, 0);
figure.addTrace(RsaToolbox::unwrap(arg(data)));
figure.select(1, 0);
figure.addTrace(RsaToolbox::unwrap(arg(result)));
figure.savePng(filename.arg(cycle-1).arg(testCase));
log.reset();
QVERIFY(true);
}
void test_smoothSqrt::phaseAtDc_data() {
QTest::addColumn<QString>("testCase");
QTest::addColumn<QRowVector>("x");
QTest::addColumn<ComplexRowVector>("y");
uint points = 201;
QRowVector mag, phase;
mag = linearSpacing(.99, 1, points);
phase = linearSpacing(0, 0, points);
QRowVector x = linearSpacing(1, 2, points);
QTest::newRow("Zero phase") << QString("Zero phase") << x << makeComplex(mag, phase);
points = 401;
mag = linearSpacing(.9, 1, points);
phase = linearSpacing(0, PI, points);
x = linearSpacing(1, 2, points);
QTest::newRow("Small phase") << QString("Small phase") << x << makeComplex(mag, phase);
points = 501;
mag = linearSpacing(0.9, 1, points);
phase = linearSpacing(PI/2.0, 10.0*PI, points);
x = linearSpacing(1, 2, points);
QTest::newRow("Medium phase") << QString("Medium phase") << x << makeComplex(mag, phase);
points = 12*2+2;
mag = linearSpacing(.9, 1, points);
phase = linearSpacing(3.0*PI, 15.0*PI, points);
x = linearSpacing(1, 2, points);
QTest::newRow("Large phase") << QString("Large phase") << x << makeComplex(mag, phase);
}
void test_smoothSqrt::phaseAtDc() {
log.reset(new Log(logPath, logFilename.arg(cycle++).arg("phaseAtDc()"), appName, appVersion));
QFETCH(QString, testCase);
QFETCH(QRowVector, x);
QFETCH(ComplexRowVector, y);
double result = RsaToolbox::phaseAtDc_rad(x, y);
log->printLine(testCase + " x:");
log->printLine(toString(x, ", "));
log->printLine(testCase + " y:");
log->printLine(toString(y, " "));
log->printLine("Result:");
log->printLine(formatValue(result, 2, RADIANS_UNITS));
QString filename = logPath + "/" + plotFilename;
Figure figure("wrap");
figure.select(0, 0);
figure.addTrace(x, RsaToolbox::unwrap(arg(y)));
figure.addTrace(QRowVector(1, 0), QRowVector(1, result));
figure.plot(0,0)->graph(1)->setScatterStyle(QCP::ssCircle);
figure.savePng(filename.arg(cycle-1).arg(testCase));
log.reset();
QVERIFY(true);
}
void test_smoothSqrt::fixPhaseAtDc_data() {
QTest::addColumn<QString>("testCase");
QTest::addColumn<QRowVector>("x");
QTest::addColumn<ComplexRowVector>("y");
uint points = 201;
QRowVector mag, phase;
mag = linearSpacing(.99, 1, points);
phase = linearSpacing(0, 0, points);
QRowVector x = linearSpacing(1, 2, points);
QTest::newRow("Zero phase") << QString("Zero phase") << x << makeComplex(mag, phase);
points = 401;
mag = linearSpacing(.9, 1, points);
phase = linearSpacing(0, PI, points);
x = linearSpacing(1, 2, points);
QTest::newRow("Small phase") << QString("Small phase") << x << makeComplex(mag, phase);
points = 501;
mag = linearSpacing(0.9, 1, points);
phase = linearSpacing(PI/2.0, 10.0*PI, points);
x = linearSpacing(1, 2, points);
QTest::newRow("Medium phase") << QString("Medium phase") << x << makeComplex(mag, phase);
points = 12*2+2;
mag = linearSpacing(.9, 1, points);
phase = linearSpacing(3.0*PI, 15.0*PI, points);
x = linearSpacing(1, 2, points);
QTest::newRow("Large phase") << QString("Large phase") << x << makeComplex(mag, phase);
}
void test_smoothSqrt::fixPhaseAtDc() {
log.reset(new Log(logPath, logFilename.arg(cycle++).arg("fixPhaseAtDc()"), appName, appVersion));
QFETCH(QString, testCase);
QFETCH(QRowVector, x);
QFETCH(ComplexRowVector, y);
ComplexRowVector result = RsaToolbox::fixPhaseAtDc(x, y);
log->printLine(testCase + " x:");
log->printLine(toString(x, ", "));
log->printLine(testCase + " y:");
log->printLine(toString(y, " "));
log->printLine("Result:");
log->printLine(toString(result, " "));
QString filename = logPath + "/" + plotFilename;
Figure figure("wrap");
figure.select(0, 0);
figure.addTrace(x, RsaToolbox::unwrap(arg(y)));
figure.addTrace(QRowVector(1, 0), QRowVector(1, RsaToolbox::phaseAtDc_rad(x, y)));
figure.plot(0,0)->graph(1)->setScatterStyle(QCP::ssCircle);
figure.addTrace(x, RsaToolbox::unwrap(arg(result)), Qt::red);
figure.addTrace(QRowVector(1, 0), QRowVector(1, RsaToolbox::phaseAtDc_rad(x, result)), Qt::red);
figure.plot(0,0)->graph(3)->setScatterStyle(QCP::ssCircle);
figure.savePng(filename.arg(cycle-1).arg(testCase));
log.reset();
QVERIFY(true);
}
ComplexRowVector makeComplex(QRowVector mag, QRowVector phase_rad) {
uint size = mag.size();
ComplexRowVector result(size);
ComplexDouble j(0, 1);
for (uint i = 0; i < size; i++) {
ComplexDouble c;
c = mag[i]*exp(j*phase_rad[i]);
result[i] = c;
}
return(result);
}
QTEST_MAIN(test_smoothSqrt)
#include "test_smoothSqrt.moc"
|
#include "SceneBase.h"
#include "GL\glew.h"
#include "shader.hpp"
#include "MeshBuilder.h"
#include "Application.h"
#include "Utility.h"
#include "LoadTGA.h"
#include <sstream>
SceneBase::SceneBase()
{
}
SceneBase::~SceneBase()
{
}
void SceneBase::Init()
{
// Blue background
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
// Enable depth test
//glEnable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glGenVertexArrays(1, &m_vertexArrayID);
glBindVertexArray(m_vertexArrayID);
m_programID = LoadShaders("Shader//Texture.vertexshader", "Shader//Text.fragmentshader");
// Get a handle for our uniform
m_parameters[U_MVP] = glGetUniformLocation(m_programID, "MVP");
//m_parameters[U_MODEL] = glGetUniformLocation(m_programID, "M");
//m_parameters[U_VIEW] = glGetUniformLocation(m_programID, "V");
m_parameters[U_MODELVIEW] = glGetUniformLocation(m_programID, "MV");
m_parameters[U_MODELVIEW_INVERSE_TRANSPOSE] = glGetUniformLocation(m_programID, "MV_inverse_transpose");
m_parameters[U_MATERIAL_AMBIENT] = glGetUniformLocation(m_programID, "material.kAmbient");
m_parameters[U_MATERIAL_DIFFUSE] = glGetUniformLocation(m_programID, "material.kDiffuse");
m_parameters[U_MATERIAL_SPECULAR] = glGetUniformLocation(m_programID, "material.kSpecular");
m_parameters[U_MATERIAL_SHININESS] = glGetUniformLocation(m_programID, "material.kShininess");
m_parameters[U_LIGHTENABLED] = glGetUniformLocation(m_programID, "lightEnabled");
m_parameters[U_NUMLIGHTS] = glGetUniformLocation(m_programID, "numLights");
m_parameters[U_LIGHT0_TYPE] = glGetUniformLocation(m_programID, "lights[0].type");
m_parameters[U_LIGHT0_POSITION] = glGetUniformLocation(m_programID, "lights[0].position_cameraspace");
m_parameters[U_LIGHT0_COLOR] = glGetUniformLocation(m_programID, "lights[0].color");
m_parameters[U_LIGHT0_POWER] = glGetUniformLocation(m_programID, "lights[0].power");
m_parameters[U_LIGHT0_KC] = glGetUniformLocation(m_programID, "lights[0].kC");
m_parameters[U_LIGHT0_KL] = glGetUniformLocation(m_programID, "lights[0].kL");
m_parameters[U_LIGHT0_KQ] = glGetUniformLocation(m_programID, "lights[0].kQ");
m_parameters[U_LIGHT0_SPOTDIRECTION] = glGetUniformLocation(m_programID, "lights[0].spotDirection");
m_parameters[U_LIGHT0_COSCUTOFF] = glGetUniformLocation(m_programID, "lights[0].cosCutoff");
m_parameters[U_LIGHT0_COSINNER] = glGetUniformLocation(m_programID, "lights[0].cosInner");
m_parameters[U_LIGHT0_EXPONENT] = glGetUniformLocation(m_programID, "lights[0].exponent");
m_parameters[U_LIGHT1_TYPE] = glGetUniformLocation(m_programID, "lights[1].type");
m_parameters[U_LIGHT1_POSITION] = glGetUniformLocation(m_programID, "lights[1].position_cameraspace");
m_parameters[U_LIGHT1_COLOR] = glGetUniformLocation(m_programID, "lights[1].color");
m_parameters[U_LIGHT1_POWER] = glGetUniformLocation(m_programID, "lights[1].power");
m_parameters[U_LIGHT1_KC] = glGetUniformLocation(m_programID, "lights[1].kC");
m_parameters[U_LIGHT1_KL] = glGetUniformLocation(m_programID, "lights[1].kL");
m_parameters[U_LIGHT1_KQ] = glGetUniformLocation(m_programID, "lights[1].kQ");
m_parameters[U_LIGHT1_SPOTDIRECTION] = glGetUniformLocation(m_programID, "lights[1].spotDirection");
m_parameters[U_LIGHT1_COSCUTOFF] = glGetUniformLocation(m_programID, "lights[1].cosCutoff");
m_parameters[U_LIGHT1_COSINNER] = glGetUniformLocation(m_programID, "lights[1].cosInner");
m_parameters[U_LIGHT1_EXPONENT] = glGetUniformLocation(m_programID, "lights[1].exponent");
// Get a handle for our "colorTexture" uniform
m_parameters[U_COLOR_TEXTURE_ENABLED] = glGetUniformLocation(m_programID, "colorTextureEnabled");
m_parameters[U_COLOR_TEXTURE] = glGetUniformLocation(m_programID, "colorTexture");
// Get a handle for our "textColor" uniform
m_parameters[U_TEXT_ENABLED] = glGetUniformLocation(m_programID, "textEnabled");
m_parameters[U_TEXT_COLOR] = glGetUniformLocation(m_programID, "textColor");
// Use our shader
glUseProgram(m_programID);
lights[0].type = Light::LIGHT_DIRECTIONAL;
lights[0].position.Set(0, 20, 0);
lights[0].color.Set(1, 1, 1);
lights[0].power = 1;
lights[0].kC = 1.f;
lights[0].kL = 0.01f;
lights[0].kQ = 0.001f;
lights[0].cosCutoff = cos(Math::DegreeToRadian(45));
lights[0].cosInner = cos(Math::DegreeToRadian(30));
lights[0].exponent = 3.f;
lights[0].spotDirection.Set(0.f, 1.f, 0.f);
lights[1].type = Light::LIGHT_DIRECTIONAL;
lights[1].position.Set(1, 1, 0);
lights[1].color.Set(1, 1, 0.5f);
lights[1].power = 0.4f;
//lights[1].kC = 1.f;
//lights[1].kL = 0.01f;
//lights[1].kQ = 0.001f;
//lights[1].cosCutoff = cos(Math::DegreeToRadian(45));
//lights[1].cosInner = cos(Math::DegreeToRadian(30));
//lights[1].exponent = 3.f;
//lights[1].spotDirection.Set(0.f, 1.f, 0.f);
glUniform1i(m_parameters[U_NUMLIGHTS], 1);
glUniform1i(m_parameters[U_TEXT_ENABLED], 0);
glUniform1i(m_parameters[U_LIGHT0_TYPE], lights[0].type);
glUniform3fv(m_parameters[U_LIGHT0_COLOR], 1, &lights[0].color.r);
glUniform1f(m_parameters[U_LIGHT0_POWER], lights[0].power);
glUniform1f(m_parameters[U_LIGHT0_KC], lights[0].kC);
glUniform1f(m_parameters[U_LIGHT0_KL], lights[0].kL);
glUniform1f(m_parameters[U_LIGHT0_KQ], lights[0].kQ);
glUniform1f(m_parameters[U_LIGHT0_COSCUTOFF], lights[0].cosCutoff);
glUniform1f(m_parameters[U_LIGHT0_COSINNER], lights[0].cosInner);
glUniform1f(m_parameters[U_LIGHT0_EXPONENT], lights[0].exponent);
glUniform1i(m_parameters[U_LIGHT1_TYPE], lights[1].type);
glUniform3fv(m_parameters[U_LIGHT1_COLOR], 1, &lights[1].color.r);
glUniform1f(m_parameters[U_LIGHT1_POWER], lights[1].power);
glUniform1f(m_parameters[U_LIGHT1_KC], lights[1].kC);
glUniform1f(m_parameters[U_LIGHT1_KL], lights[1].kL);
glUniform1f(m_parameters[U_LIGHT1_KQ], lights[1].kQ);
glUniform1f(m_parameters[U_LIGHT1_COSCUTOFF], lights[1].cosCutoff);
glUniform1f(m_parameters[U_LIGHT1_COSINNER], lights[1].cosInner);
glUniform1f(m_parameters[U_LIGHT1_EXPONENT], lights[1].exponent);
for (int i = 0; i < NUM_GEOMETRY; ++i)
{
meshList[i] = NULL;
}
meshList[GEO_AXES] = MeshBuilder::GenerateAxes("reference");//, 1000, 1000, 1000);
meshList[GEO_CROSSHAIR] = MeshBuilder::GenerateCrossHair("crosshair");
meshList[GEO_TEXT] = MeshBuilder::GenerateText("text", 16, 16);
meshList[GEO_TEXT]->textureID = LoadTGA("Image//calibri.tga");
meshList[GEO_TEXT]->material.kAmbient.Set(1, 0, 0);
// meshList[GEO_TILESET1] = MeshBuilder::GenerateTileSet("GEO_TILESET", 80, 8);
//meshList[GEO_TILESET1]->textureID = LoadTGA("Image//moderntileset.tga");
meshList[GEO_TILESET1] = MeshBuilder::GenerateTileSet("GEO_TILESET3", 30, 30);
meshList[GEO_TILESET1]->textureID = LoadTGA("Image//tileSet3.tga");
meshList[GEO_FIREBALL] = MeshBuilder::Generate2DMesh("GEO_FIREBALL", Color(1, 1, 1), 100, 100, 1, 1);
meshList[GEO_FIREBALL]->textureID = LoadTGA("Image//Fireball.tga");
meshList[GEO_CASTLE] = MeshBuilder::GenerateSpriteAnimation("sprite", 1, 2);
meshList[GEO_CASTLE]->textureID = LoadTGA("Image//Castle.tga");
meshList[GEO_DOOR] = MeshBuilder::Generate2DMesh("sprite", Color(1, 1, 1), 100, 100, 1, 1);
meshList[GEO_DOOR]->textureID = LoadTGA("Image//Door.tga");
meshList[GEO_VILLAGER] = MeshBuilder::GenerateSpriteAnimation("sprite", 1, 3);
meshList[GEO_VILLAGER]->textureID = LoadTGA("Image//Villager.tga");
meshList[GEO_GUARDS] = MeshBuilder::GenerateSpriteAnimation("sprite", 1, 3);
meshList[GEO_GUARDS]->textureID = LoadTGA("Image//Guards.tga");
meshList[GEO_GUARDSL] = MeshBuilder::GenerateSpriteAnimation("sprite", 1, 3);
meshList[GEO_GUARDSL ]->textureID = LoadTGA("Image//GuardsL.tga");
meshList[GEO_GUARDSR] = MeshBuilder::GenerateSpriteAnimation("sprite", 1, 3);
meshList[GEO_GUARDSR]->textureID = LoadTGA("Image//GuardsR.tga");
meshList[GEO_GUARDSUP] = MeshBuilder::GenerateSpriteAnimation("sprite", 1, 3);
meshList[GEO_GUARDSUP]->textureID = LoadTGA("Image//GuardsUP.tga");
meshList[GEO_TREE] = MeshBuilder::Generate2DMesh("sprite", Color(1, 1, 1), 100, 100, 1, 1);
meshList[GEO_TREE]->textureID = LoadTGA("Image//AppleTree.tga");
meshList[GEO_APPLES] = MeshBuilder::Generate2DMesh("sprite", Color(1, 1, 1), 100, 100, 1, 1);
meshList[GEO_APPLES]->textureID = LoadTGA("Image//Apple.tga");
meshList[GEO_ROTTENAPPLE] = MeshBuilder::Generate2DMesh("sprite", Color(1, 1, 1), 100, 100, 1, 1);
meshList[GEO_ROTTENAPPLE]->textureID = LoadTGA("Image//AppleRot.tga");
meshList[GEO_DECAYAPPLE] = MeshBuilder::Generate2DMesh("sprite", Color(1, 1, 1), 100, 100, 1, 1);
meshList[GEO_DECAYAPPLE]->textureID = LoadTGA("Image//AppleDecay.tga");
meshList[GEO_ARCHERR] = MeshBuilder::GenerateSpriteAnimation("sprite", 1, 3);
meshList[GEO_ARCHERR]->textureID = LoadTGA("Image//ArcherR.tga");
meshList[GEO_ARCHERL] = MeshBuilder::GenerateSpriteAnimation("sprite", 1, 3);
meshList[GEO_ARCHERL]->textureID = LoadTGA("Image//ArcherL.tga");
meshList[GEO_ARCHERATT] = MeshBuilder::Generate2DMesh("sprite", Color(1, 1, 1), 100, 100, 1, 1);
meshList[GEO_ARCHERATT]->textureID = LoadTGA("Image//ArcherAttack.tga");
SpriteAnimation *castle = dynamic_cast<SpriteAnimation*>(meshList[GEO_CASTLE]);
if (castle)
{
castle->m_anim = new Animation();
castle->m_anim->Set(0, 1, 1, 1, true);
}
SpriteAnimation *guards = dynamic_cast<SpriteAnimation*>(meshList[GEO_GUARDS]);
if (guards)
{
guards->m_anim = new Animation();
guards->m_anim->Set(0, 2, 1, 1, true);
}
SpriteAnimation *guardsL = dynamic_cast<SpriteAnimation*>(meshList[GEO_GUARDSL]);
if (guardsL)
{
guardsL->m_anim = new Animation();
guardsL->m_anim->Set(0, 2, 1, 1, true);
}
SpriteAnimation *guardsR = dynamic_cast<SpriteAnimation*>(meshList[GEO_GUARDSR]);
if (guardsR)
{
guardsR->m_anim = new Animation();
guardsR->m_anim->Set(0, 2, 1, 1, true);
}
SpriteAnimation *guardsUP = dynamic_cast<SpriteAnimation*>(meshList[GEO_GUARDSUP]);
if (guardsUP)
{
guardsUP->m_anim = new Animation();
guardsUP->m_anim->Set(0, 2, 1, 1, true);
}
SpriteAnimation *archerR = dynamic_cast<SpriteAnimation*>(meshList[GEO_ARCHERR]);
if (archerR)
{
archerR->m_anim = new Animation();
archerR->m_anim->Set(0, 2, 1, 1, true);
}
SpriteAnimation *archerL = dynamic_cast<SpriteAnimation*>(meshList[GEO_ARCHERL]);
if (archerL)
{
archerL->m_anim = new Animation();
archerL->m_anim->Set(0, 2, 1, 1, true);
}
SpriteAnimation *villager = dynamic_cast<SpriteAnimation*>(meshList[GEO_VILLAGER]);
if (villager)
{
villager->m_anim = new Animation();
villager->m_anim->Set(0, 2, 1, 1, true);
}
meshList[GEO_HEAL_IDLE] = MeshBuilder::GenerateSpriteAnimation("Healing Fountain", 1, 4);
meshList[GEO_HEAL_IDLE]->textureID = LoadTGA("Image//Fountain.tga");
meshList[GEO_HEAL_REST] = MeshBuilder::GenerateSpriteAnimation("Empty Fountain", 1, 1);
meshList[GEO_HEAL_REST]->textureID = LoadTGA("Image//EmptyFountain.tga");
meshList[GEO_HEAL_HEAL] = MeshBuilder::GenerateSpriteAnimation("Healing Fountain", 1, 4);
meshList[GEO_HEAL_HEAL]->textureID = LoadTGA("Image//Fountain.tga");
meshList[GEO_HEAL_EFFECT] = MeshBuilder::GenerateSpriteAnimation("Healing Effect", 1, 9);
meshList[GEO_HEAL_EFFECT]->textureID = LoadTGA("Image//HealEffect.tga");
meshList[GEO_KSIDLE] = MeshBuilder::GenerateSpriteAnimation("Idle Slime", 1, 2);
meshList[GEO_KSIDLE]->textureID = LoadTGA("Image//KingSlimeIdle.tga");
meshList[GEO_KSMOVEL] = MeshBuilder::GenerateSpriteAnimation("Move Slime", 1, 7);
meshList[GEO_KSMOVEL]->textureID = LoadTGA("Image//KingSlimeMove.tga");
meshList[GEO_KSMOVER] = MeshBuilder::GenerateSpriteAnimation("Move Slime", 1, 7);
meshList[GEO_KSMOVER]->textureID = LoadTGA("Image//KingSlimeMoveR.tga");
meshList[GEO_KSATTACKFORCE] = MeshBuilder::GenerateSpriteAnimation("KingSlimeAttack", 2, 5);
meshList[GEO_KSATTACKFORCE]->textureID = LoadTGA("Image//KSAttack.tga");
meshList[GEO_KSATTACK] = MeshBuilder::GenerateSpriteAnimation("Move Slime", 1, 7);
meshList[GEO_KSATTACK]->textureID = LoadTGA("Image//KingSlimeMove.tga");
SpriteAnimation *ksIDLE = dynamic_cast<SpriteAnimation*>(meshList[GEO_KSIDLE]);
if (ksIDLE)
{
ksIDLE->m_anim = new Animation();
ksIDLE->m_anim->Set(0, 1, 1, 1, true);
}
SpriteAnimation *ksMOVEL = dynamic_cast<SpriteAnimation*>(meshList[GEO_KSMOVEL]);
if (ksMOVEL)
{
ksMOVEL->m_anim = new Animation();
ksMOVEL->m_anim->Set(0, 6, 1, 1, true);
}
SpriteAnimation *ksMOVER = dynamic_cast<SpriteAnimation*>(meshList[GEO_KSMOVER]);
if (ksMOVER)
{
ksMOVER->m_anim = new Animation();
ksMOVER->m_anim->Set(0, 6, 1, 1, true);
}
SpriteAnimation *HealIDLE = dynamic_cast<SpriteAnimation*>(meshList[GEO_HEAL_IDLE]);
if (HealIDLE)
{
HealIDLE->m_anim = new Animation();
HealIDLE->m_anim->Set(0, 3, 1, 1, true);
}
SpriteAnimation *HealHEAL = dynamic_cast<SpriteAnimation*>(meshList[GEO_HEAL_HEAL]);
if (HealHEAL)
{
HealHEAL->m_anim = new Animation();
HealHEAL->m_anim->Set(0, 3, 1, 1, true);
}
SpriteAnimation *HealEFFECT = dynamic_cast<SpriteAnimation*>(meshList[GEO_HEAL_EFFECT]);
if (HealEFFECT)
{
HealEFFECT->m_anim = new Animation();
HealEFFECT->m_anim->Set(0, 8, 1, 1, true);
}
SpriteAnimation *ksATTACK = dynamic_cast<SpriteAnimation*>(meshList[GEO_KSATTACK]);
if (ksATTACK)
{
ksATTACK->m_anim = new Animation();
ksATTACK->m_anim->Set(0, 6, 1, 1, true);
}
SpriteAnimation *KSAttackDust = dynamic_cast<SpriteAnimation*>(meshList[GEO_KSATTACKFORCE]);
if (KSAttackDust)
{
KSAttackDust->m_anim = new Animation();
KSAttackDust->m_anim->Set(0, 9, 1, 1, true);
}
Math::InitRNG();
camera.Init(Vector3(0, 0, 10), Vector3(0, 0, 0), Vector3(0, 1, 0));
}
void SceneBase::RenderTile(Mesh* mesh, unsigned tileID, float size, float x, float y)
{
if (!mesh || mesh->textureID <= 0)
return;
Mtx44 ortho;
ortho.SetToOrtho(0, 800, 0, 600, -10, 10);
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity();
modelStack.PushMatrix();
modelStack.LoadIdentity();
modelStack.Translate(x, y, 0);
modelStack.Scale(size, size, 1);
glUniform1i(m_parameters[U_LIGHTENABLED], 0);
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
Mtx44 MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
mesh->Render(tileID * 6, 6);
glBindTexture(GL_TEXTURE_2D, 0);
glUniform1i(m_parameters[U_TEXT_ENABLED], 0);
modelStack.PopMatrix();
viewStack.PopMatrix();
projectionStack.PopMatrix();
}
void SceneBase::RenderTileMap(Mesh* mesh, CMap* map)
{
for (int y = 0; y < map->theNumOfTiles_Height; ++y)
{
for (int x = 0; x < map->theNumOfTiles_Width; ++x)
{
//if (map->theMap[y][x].BlockID != 0)
{
RenderTile(mesh, map->theMap[y][x].BlockID, 32, x * map->GetTileSize() - MapOffset.x, y * map->GetTileSize() - MapOffset.y);
}
}
}
}
void SceneBase::RenderTextOnScreen(Mesh* mesh, std::string text, Color color, float size, float x, float y)
{
if (!mesh || mesh->textureID <= 0)
return;
glDisable(GL_DEPTH_TEST);
Mtx44 ortho;
ortho.SetToOrtho(0, 800, 0, 600, -10, 10);
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity();
modelStack.PushMatrix();
modelStack.LoadIdentity();
modelStack.Translate(x, y, 0);
modelStack.Scale(size, size, size);
glUniform1i(m_parameters[U_TEXT_ENABLED], 1);
glUniform3fv(m_parameters[U_TEXT_COLOR], 1, &color.r);
glUniform1i(m_parameters[U_LIGHTENABLED], 0);
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
for (unsigned i = 0; i < text.length(); ++i)
{
Mtx44 characterSpacing;
characterSpacing.SetToTranslation(i * 0.5f + 0.5f, 0.5f, 0); //1.0f is the spacing of each character, you may change this value
Mtx44 MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top() * characterSpacing;
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
mesh->Render((unsigned)text[i] * 6, 6);
}
glBindTexture(GL_TEXTURE_2D, 0);
glUniform1i(m_parameters[U_TEXT_ENABLED], 0);
modelStack.PopMatrix();
viewStack.PopMatrix();
projectionStack.PopMatrix();
//glEnable(GL_DEPTH_TEST);
}
void SceneBase::Render2DMeshWScale(Mesh *mesh, const bool enableLight, const float sizeX, const float sizeY, const float x, const float y, const bool flip, const float offset)
{
glDisable(GL_CULL_FACE);
Mtx44 ortho;
ortho.SetToOrtho(0, 800, 0, 600, -10, 10);
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity();
modelStack.PushMatrix();
modelStack.LoadIdentity();
if (flip)
{
modelStack.Translate(x + offset, y, 0);
}
else
{
modelStack.Translate(x, y, 0);
}
modelStack.Scale(sizeX, sizeY, 1);
if (flip)
modelStack.Rotate(180, 0, 1, 0);
Mtx44 MVP, modelView, modelView_inverse_transpose;
MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
if (mesh->textureID > 0)
{
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
}
else
{
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 0);
}
mesh->Render();
if (mesh->textureID > 0)
{
glBindTexture(GL_TEXTURE_2D, 0);
}
modelStack.PopMatrix();
viewStack.PopMatrix();
projectionStack.PopMatrix();
glEnable(GL_CULL_FACE);
}
void SceneBase::Render2DMesh(Mesh *mesh, bool enableLight, float size, float x, float y, bool flip)
{
Mtx44 ortho;
ortho.SetToOrtho(0, 800, 0, 600, -10, 10);
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity();
modelStack.PushMatrix();
modelStack.LoadIdentity();
if (flip)
modelStack.Translate(x + 32, y, 0);
else
modelStack.Translate(x, y, 0);
modelStack.Scale(size, size, size);
if (flip)
modelStack.Rotate(180, 0, 1, 0);
Mtx44 MVP, modelView, modelView_inverse_transpose;
MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
if (mesh->textureID > 0)
{
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
}
else
{
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 0);
}
mesh->Render();
if (mesh->textureID > 0)
{
glBindTexture(GL_TEXTURE_2D, 0);
}
modelStack.PopMatrix();
viewStack.PopMatrix();
projectionStack.PopMatrix();
}
void SceneBase::RenderBackground(Mesh* mesh)
{
Render2DMesh(mesh, false, 1.0f,0,0,false); // World Overlay Background
}
void SceneBase::Render()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
Mtx44 perspective;
perspective.SetToPerspective(45.0f, 4.0f / 3.0f, 0.1f, 10000.0f);
//perspective.SetToOrtho(-80, 80, -60, 60, -1000, 1000);
projectionStack.LoadMatrix(perspective);
//// Camera matrix
viewStack.LoadIdentity();
viewStack.LookAt(
camera.position.x, camera.position.y, camera.position.z,
camera.target.x, camera.target.y, camera.target.z,
camera.up.x, camera.up.y, camera.up.z
);
//// Model matrix : an identity matrix (model will be at the origin)
modelStack.LoadIdentity();
}
void SceneBase::Update(double dt)
{
if (Application::IsKeyPressed('1'))
glEnable(GL_CULL_FACE);
if (Application::IsKeyPressed('2'))
glDisable(GL_CULL_FACE);
if (Application::IsKeyPressed('3'))
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
if (Application::IsKeyPressed('4'))
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
if (Application::IsKeyPressed('I'))
lights[0].position.z -= (float)(10.f * dt);
if (Application::IsKeyPressed('K'))
lights[0].position.z += (float)(10.f * dt);
if (Application::IsKeyPressed('J'))
lights[0].position.x -= (float)(10.f * dt);
if (Application::IsKeyPressed('L'))
lights[0].position.x += (float)(10.f * dt);
if (Application::IsKeyPressed('O'))
lights[0].position.y -= (float)(10.f * dt);
if (Application::IsKeyPressed('P'))
lights[0].position.y += (float)(10.f * dt);
camera.Update(dt);
}
void SceneBase::Exit()
{
//// Cleanup VBO
//for (int i = 0; i < NUM_GEOMETRY; ++i)
//{
// if (meshList[i])
// delete meshList[i];
//}
//glDeleteProgram(m_programID);
//glDeleteVertexArrays(1, &m_vertexArrayID);
}
|
#include <iostream>
using std::string;
class Container{
public:
class NumberBook{
public:
string name, lastName;
int number;
string birthDay;
NumberBook(string name, string lastName, int number, string birthDay){
setName(name);
setLastName(lastName);
setNumber(number);
setBirthDay(birthDay);
}
NumberBook(){}
void setName(string name){
this->name = name;
}
void setLastName(string lastName){
this->lastName = lastName;
}
void setNumber(int number) {
this->number = number;
}
void setBirthDay(string birthDay){
this->birthDay = birthDay;
}
string getName(){
return name;
}
string getLastName(){
return lastName;
}
int getNumber() {
return number;
}
string getBirthDay(){
return birthDay;
}
};
private:
NumberBook nb[100000];
public:
NumberBook* getNB(){
return nb;
}
void sort(int realSize, int s){
for (int startIndex = 0; startIndex < realSize - 1; ++startIndex){
int smallestIndex = startIndex;
for (int currentIndex = startIndex + 1; currentIndex < realSize; ++currentIndex){
if(s == 1)
if (nb[currentIndex].getName() < nb[smallestIndex].getName())
smallestIndex = currentIndex;
if(s == 2)
if (nb[currentIndex].getLastName() < nb[smallestIndex].getLastName())
smallestIndex = currentIndex;
if(s == 3)
if (nb[currentIndex].getNumber() < nb[smallestIndex].getNumber())
smallestIndex = currentIndex;
if(s == 4)
if (nb[currentIndex].getBirthDay() < nb[smallestIndex].getBirthDay())
smallestIndex = currentIndex;
}
std::swap(nb[startIndex], nb[smallestIndex]);
}
}
void search(int realSize, int s){
int i = 0;
if(s == 1){
string name;
std::cout << "Введите имя" << std::endl;
std::cin >> name;
for(i = 0; i < realSize; i++){
if(nb[i].getName() == name)
break;
}
}
if(s == 2){
string lastName;
std::cout << "Введите фамилию" << std::endl;
std::cin >> lastName;
for(i = 0; i < realSize; i++){
if(nb[i].getLastName() == lastName)
break;
}
}
if(s == 3){
int number;
std::cout << "Введите номер" << std::endl;
std::cin >> number;
for(i = 0; i < realSize; i++){
if(nb[i].getNumber() == number)
break;
}
}
if(s == 4){
string birthDay;
std::cout << "Введите дату рождения (дд.мм.гггг)" << std::endl;
std::cin >> birthDay;
for(i = 0; i < realSize; i++){
if(nb[i].getBirthDay() == birthDay)
break;
}
}
if(i == realSize)
std::cout << "В записной книжке нет такой записи!" << std::endl;
else{
std::cout << "Имя: Фамилия: Номер телефона: Дата рождения:" << std::endl;
std::cout << nb[i].getName() << " " << nb[i].getLastName() << " " << nb[i].getNumber() << " " << nb[i].getBirthDay() << std::endl;
}
}
};
int main() {
Container cont;
Container::NumberBook* nb = cont.getNB();
int realSize = 0;
int k = 10;
while(k != 0){
std::cout<< "Меню:\n"
"0. Закрыть программу\n"
"1. Добавить значение\n"
"2. Отобразить записную книжку\n"
"3. Удалить значение\n"
"4. Отсортировать по полю\n"
"5. Поиск\n";
std::cin>>k;
switch(k){
case 0:
exit(0);
case 2:
std::cout << "Имя: Фамилия: Номер телефона: Дата рождения:" << std::endl;
for(int i = 0; i < realSize; i++){
std::cout << nb[i].getName() << " " << nb[i].getLastName() << " " << nb[i].getNumber() << " " << nb[i].getBirthDay() << std::endl;
}
break;
case 3:
int num;
std::cout << "Введите номер телефона:" << std::endl;
std::cin >> num;
for(int i = 0; i < realSize; i++){
if(nb[i].getNumber() == num){
for(int j = i; j < realSize; j++){
if(j != realSize)
nb[j] = nb[j + 1];
}
realSize--;
}
}
break;
case 4:
std::cout << "Выберите поле сортировки: 1-имя 2-фамилия 3-номер телефона 4-дата рождения" << std::endl;
int s;
std::cin >> s;
cont.sort(realSize, s);
std::cout << "Сортировка завершена" << std::endl;
break;
case 5:
std::cout << "Выберите поле для поиска: 1-имя 2-фамилия 3-номер телефона 4-дата рождения" << std::endl;
int b;
std::cin >> b;
cont.search(realSize, b);
std::cout << "Поиск завершен!" << std::endl;
break;
case 1:
string name, lastName;
int number;
string birthDay;
std::cout<<"Введите: Имя Фамилию Номер Дату рождения(ДД.ММ.ГГГГ)"<<std::endl;
std::cin>>name>>lastName>>number>>birthDay;
std::cout<<std::endl;
nb[realSize++] = Container::NumberBook(name,lastName,number,birthDay);
break;
}
}
}
|
#include "SettingsDialog.h"
SettingsDialog::SettingsDialog(wxWindow* parent, wxFont& font): SettingsDialog1(parent)
{
SetTitle(_("Settings"));
if(font.IsOk()){
setFont(font);
this->settingsFont = font;
}
}
void SettingsDialog::setFont(wxFont& font)
{
fontPicker->SetSelectedFont(font);
}
wxFont SettingsDialog::getFont()
{
return this->settingsFont;
}
void SettingsDialog::FontChanged(wxFontPickerEvent& WXUNUSED(event))
{
this->settingsFont = fontPicker->GetSelectedFont();
}
|
/****************************************************************************
** Meta object code from reading C++ file 'accountcreation.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.13.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../../newProject/accountcreation.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'accountcreation.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.13.2. 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_AccountCreation_t {
QByteArrayData data[5];
char stringdata0[90];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_AccountCreation_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_AccountCreation_t qt_meta_stringdata_AccountCreation = {
{
QT_MOC_LITERAL(0, 0, 15), // "AccountCreation"
QT_MOC_LITERAL(1, 16, 20), // "closeAccountCreation"
QT_MOC_LITERAL(2, 37, 0), // ""
QT_MOC_LITERAL(3, 38, 24), // "on_pushButton_ok_clicked"
QT_MOC_LITERAL(4, 63, 26) // "on_pushButton_back_clicked"
},
"AccountCreation\0closeAccountCreation\0"
"\0on_pushButton_ok_clicked\0"
"on_pushButton_back_clicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_AccountCreation[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 29, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
3, 0, 30, 2, 0x08 /* Private */,
4, 0, 31, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void AccountCreation::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<AccountCreation *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->closeAccountCreation(); break;
case 1: _t->on_pushButton_ok_clicked(); break;
case 2: _t->on_pushButton_back_clicked(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (AccountCreation::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&AccountCreation::closeAccountCreation)) {
*result = 0;
return;
}
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject AccountCreation::staticMetaObject = { {
&QDialog::staticMetaObject,
qt_meta_stringdata_AccountCreation.data,
qt_meta_data_AccountCreation,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *AccountCreation::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *AccountCreation::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_AccountCreation.stringdata0))
return static_cast<void*>(this);
return QDialog::qt_metacast(_clname);
}
int AccountCreation::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 < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 3;
}
return _id;
}
// SIGNAL 0
void AccountCreation::closeAccountCreation()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
#ifndef _SYSLOG_WIN32_INCLUDED
#define _SYSLOG_WIN32_INCLUDED 1
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
/*
http://www.codeproject.com/system/mctutorial.asp?df=100&forumid=15526&exp=0&select=1238561
*/
#include <tchar.h>
#include "messages.h"
class CSyslog
{
private:
TCHAR *ident;
HANDLE hEventLog;
static unsigned short category[16];
int where;
public:
enum { TOTTY, TOLOG };
enum PHRASEA_LOG_LEVEL {
LOGL_PARSE = 0
, LOGL_ERR = 1
, LOGL_SQLOK = 2
, LOGL_ALLOC = 3
, LOGL_RECORD = 4
, LOGL_THESAURUS = 5
, LOGL_INFO = 6
};
static char *libLevel[7];
enum PHRASEA_LOG_CATEGORY {
LOGC_PROG_START = 0
, LOGC_PROG_END = 1
, LOGC_THREAD_START = 2
, LOGC_THREAD_END = 3
, LOGC_PRELOAD = 4
, LOGC_SQLERR = 5
, LOGC_XMLERR = 6
, LOGC_FLUSH = 7
, LOGC_INDEXING = 8
, LOGC_SIGNAL = 9
, LOGC_THESAURUS = 10
, LOGC_STRUCTURE = 11
, LOGC_ACNX_OK = 12
, LOGC_HASVALUE = 13
, LOGC_SQLOK = 14
, LOGC_ALLOC = 15
};
static char *libCategory[16];
CSyslog();
~CSyslog();
void install(const TCHAR *appname);
void open(const TCHAR *appname, int where);
void _log(PHRASEA_LOG_LEVEL level, PHRASEA_LOG_CATEGORY category, TCHAR *fmt, ...);
// void _log(PHRASEA_LOG_LEVEL level, PHRASEA_LOG_CATEGORY category, const char *fmt, ...);
void close();
// log(TCHAR *fmt, ...);
};
#endif
|
//
// Created by 史浩 on 2020-01-12.
//
#ifndef NDK_OPENGLES_GLRENDER_H
#define NDK_OPENGLES_GLRENDER_H
#include <android/native_window.h>
#include "egl/IGLRender.h"
#include "egl/EGLCore.h"
#include "egl/WindowSurface.h"
#include "ScreenFilter.h"
#include "Triangle.h"
#include <android/native_window.h>
#include <android/native_window_jni.h>
class GLRender : public IGLRender {
public:
GLRender();
virtual ~GLRender();
virtual void surfaceCreated(ANativeWindow *window);
virtual void surfaceChanged(int width, int height);
virtual void surfaceDestroyed(void);
void updateTexImage(void* bytes,int width,int height);
private:
EGLCore *mEGLCore;
WindowSurface *mWindowSurface;
ScreenFilter *mScreenFilter;
GLuint mTextureId;
Triangle* mTriangle;
};
#endif //NDK_OPENGLES_GLRENDER_H
|
#pragma once
#include "Forms/KeyForm/KeyForm.h"
class QWidget;
namespace Ui {
class ScaleForm;
}
class UniqueAnswerOptionsKeyForm : public KeyForm {
Q_OBJECT
signals:
void scaleDeleted(const QString &scaleName);
public:
explicit UniqueAnswerOptionsKeyForm(Scale *scale,
Questions *questions,
QWidget *parent = 0);
~UniqueAnswerOptionsKeyForm() {}
protected:
void addPartOfKeyOnForm(const PartOfKey &partOfKey) override;
private:
QTableWidgetItem *makeQuestionNumber(const PartOfKey &partOfKey);
QTableWidgetItem *makeAnswerOptions(const PartOfKey &partOfKey);
enum ColumnName {
QUESTION_NUMBER,
ANSWER_OPTIONS,
POINTS
};
};
|
#include <QTimer>
#include <QtConcurrentRun>
#include <QFile>
#include "hashchecker.h"
#include "../VFS/IFile.h"
#include "../Md5Utils/Md5Utils.h"
#include <assert.h>
HashChecker::HashChecker(QObject *parent)
: QObject(parent)
{
connect(&watcher, SIGNAL(finished()), this, SLOT(OnCheckFinish()));
assert(!working.isRunning());
}
HashChecker::~HashChecker()
{
}
void HashChecker::append(const QList<QString> &names)
{
if (checkQueue.isEmpty() && !working.isRunning())
QTimer::singleShot(0, this, SLOT(checkNext()));
foreach (QString entry, names)
{
checkQueue.enqueue(entry);
}
}
void HashChecker::checkNext()
{
if (checkQueue.isEmpty()) {
emit finished();
return;
}
QString entry = checkQueue.dequeue();
working = QtConcurrent::run(this, &HashChecker::check, entry);
watcher.setFuture(working);
}
CheckedEntry HashChecker::check( QString name )
{
unsigned char hash[16];
std::vector<Md5Digest> hash_set;
offset_type length_remote;
bool needdownload = false;
QList<QPair<qint64, qint64> > chunks;
std::string stdname = name.toStdString();
if(QFile::exists(name + ".hs"))
{
//compare hash set generate partial download
offset_type length;
std::vector<Md5Digest>hash_set_remote;
LoadHashSet((name + ".hs").toStdString(), hash_set_remote, length_remote);
GenerateHash(stdname, hash, hash_set, length);
size_t i = 0;
for(i = 0; i<hash_set.size() && i<hash_set_remote.size(); ++i)
{
if(hash_set[i] != hash_set_remote[i])
{
if(!chunks.empty())
{
QPair<qint64, qint64>& p = chunks.last();
if(p.first + p.second == i*block_size.offset)
p.second+=block_size.offset;
else
chunks.append(QPair<qint64, qint64>(i*block_size.offset, block_size.offset));
}
else
chunks.append(QPair<qint64, qint64>(i*block_size.offset, block_size.offset));
}
}
if(i<hash_set_remote.size())
{
if(!chunks.empty())
{
QPair<qint64, qint64>& p = chunks.last();
if(p.first + p.second == i*block_size.offset)
p.second = length_remote.offset - p.first;
else
chunks.append(QPair<qint64, qint64>(i*block_size.offset,
length_remote.offset - i*block_size.offset));
}
else
chunks.append(QPair<qint64, qint64>(i*block_size.offset,
length_remote.offset - i*block_size.offset));
}
needdownload = chunks.size()>0;
}
else
{
length_remote.offset = -1;
needdownload = true;
}
return CheckedEntry(name, needdownload, length_remote.offset, chunks);
}
void HashChecker::OnCheckFinish()
{
CheckedEntry entry = working.result();
if(entry.needdownload)
{
printf("pendding download %s\n", entry.name.toStdString().c_str());
emit finishcheck(entry);
}
else
{
printf("skipped download %s\n", entry.name.toStdString().c_str());
}
checkNext();
}
|
// AutoGetAwsFileDlg.h : 头文件
//
#pragma once
// CAutoGetAwsFileDlg 对话框
class CAutoGetAwsFileDlg : public CDialog
{
// 构造
public:
CAutoGetAwsFileDlg(CWnd* pParent = NULL); // 标准构造函数
// 对话框数据
enum { IDD = IDD_AUTOGETAWSFILE_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
HICON m_hIcon;
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CTime last_time, current_time;
CString savepath;
public:
// 程序运行的状态
CString ProgramState;
//任务栏图标信息
NOTIFYICONDATA nid;
// 隐藏到任务栏
void HideToTray(void);
//下载最新时次文件
bool GetFtpFile();
afx_msg void OnDestroy();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg LRESULT OnShowTask(WPARAM wParam,LPARAM lParam);
afx_msg void OnTimer(UINT_PTR nIDEvent);
// 设置程序状态并刷新
void SetProgramState(CString state);
// 从配置文件读取上次读取文件时间
void GetLastReadTime(void);
// 设置读取时间
void SetLastReadTime(CTime last_time);
// 开机自动运行
void AutoRunAfterStart(void);
};
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Определение старшей цифры числа n, если его разрядность неизвестна
// Determination of the most significant digit of the number n, if its capacity is unknown
// Функция log10 вычисляет десятичный логарифм
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include <iostream>
#include <cmath> // Библиотека простых математических операций
int main() {
using namespace std;
auto n = 91546;
double k = log10(n);
k = k - floor(k);
int result = pow(10, k);
cout << "Result: " << result << endl;
return 0;
}
// Output:
/*
Result: 9
0
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
#ifndef CAPP_MISC_H
#define CAPP_MISC_H
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <limits.h>
#include <sstream>
#include <memory>
using namespace std;
struct Node{
int value;
int min;
Node* next;
Node* rand;
Node(int val,int mn=INT_MAX):value(val),min(mn),next(nullptr){}
};
struct TreeNode{
TreeNode* right;
TreeNode* left;
TreeNode* next;//nextPtrRight
vector<TreeNode*> subNodes;
int value;
char sym;//treeToExpression
unsigned count;//for count smaller node than cur
TreeNode(int val,char c=' '):value(val),sym(c){}
};
struct GraphNode{
string value;
vector<GraphNode*> directs;
GraphNode(string val):value(val){}
};
struct Interval {
int start,end;
Interval(){};
Interval(int s,int e):start(s),end(e){}
};
struct Job{
int Id;
int superId;
};
struct Point{
int x;
int y;
Point(){}//Point p;
Point(int a,int b):x(a),y(b){}
};
struct Rect{
Point l;//lowerleft corner
Point r;//upper right corner
Rect(int lx,int ly,int rx,int ry){
l=Point(lx,ly);
r=Point(rx,ry);
}
};
struct compNode {
bool operator()(Node *p, Node *q) const {
return p->value>q->value;
}
};
//many repeated num by Node.count, push{if(v==top()) head->count++ pop{if (--head->count == 0) head=head->next;
class MinStack{
private:
Node* head=nullptr;//seg fault if not set to nullptr
public:
void push(int v){
if (head==nullptr)
head=new Node(0,v);//min=v, v-v=0
else{
int m=min(head->min,v);
Node* t=new Node(v-m,m);//store val-min to save mem
t->next=head;
head=t;
}
}
void pop(){
if (head==nullptr)
return;
head=head->next;
}
int top(){
if (head==nullptr)
return INT_MAX;
return head->value+head->min;//retore orig
}
int getMin(){
if(head==nullptr)
return INT_MAX;
return head->min;
}
};
template <class T>
class QueueByStack{
private:
stack<T> in;
stack<T> out;
public:
void enqueue(T it){
in.push(it);
}
T dequeue(){
if(out.empty()){
while(!in.empty()){
T t=in.top();
out.push(t);
in.pop();
}
}
T r=out.top();
out.pop();
return r;
}
};
template<unsigned row, unsigned col>
class Matrix{
private:
int m[row*col]{0};//int *m;
public:
//Matrix(){m = new int[row*col]{0}; }
//~Matrix(){ delete []m; }
Matrix(const Matrix<row,col>& src){
for (unsigned i=0;i<row;++i){
for (unsigned j=0;j<col;++j) {
//m[i*row+j]=src[i][j];
}
}
}
Matrix& operator=(const Matrix& src){
if(this==&src)
return *this;
delete[] m;
for (unsigned i=0;i<row;++i){
for (unsigned j=0;j<col;++j) {
//m[i*row+j]=src[i][j];
}
}
return *this;
}
//Matrix<2,3> mx; mx[1][2]; = Proxy(1)[2]
struct Proxy {
int* arr;
unsigned irow;
Proxy(int a[],unsigned r) : arr(a),irow(r) { }
int& operator[](const unsigned iCol) {
return arr[irow*col+iCol];
}
};
Proxy operator[](const unsigned iRow) {
return Proxy(m,iRow);
}
Matrix operator+(const Matrix& src){
for (unsigned i=0;i<row;++i){
for (unsigned j=0;j<col;++j) {
//m[i*row+j]+=src[i][j];
}
}
return Matrix(*this);
}
};
class Misc {
public:
//similar O(n) find max a-b from int[]A int[]B: go thru A B find max|minA|B, return max(maxA-minB,maxB-minA),
// if index a b can not be same, then need 2nd max|minA|B as well
void maxProd(int a[],size_t size)
{
int max1=INT_MIN;
int max2=INT_MIN;
int max3=INT_MIN;
int min1=INT_MAX;
int min2=INT_MAX;
for(unsigned i=0;i<size;i++)
{
if (a[i]>max1)
{
max3=max2;
max2=max1;
max1=a[i];
}
else if(a[i]>max2)
{
max3=max2;
max2=a[i];
}
else if(a[i]>max3)
{
max3=a[i];
}
if(a[i]<min1)
{
min2=min1;
min1=a[i];
}
else if(a[i]<min2)
{
min2=a[i];
}
}
if(min1*min2>max2*max3)
{
cout<<min1*min2*max1<<endl;
}
else
{
cout<<max1*max2*max3<<endl;
}
}
int maxSubArray(int a[],size_t size,int k)//O(n) REF JAVA vector<int>|* subSumZero
{
//vector<int>* res=new vector<int>();|vector<int> res;
unordered_map<int,int> mp;
mp[0]=-1;//case like {2 -2} [-1+1=0,1] with k=0
int sum=0,mx=0;//mn=INT_MAX;
for(int i=0;i<size;++i)
{
sum+=a[i];
if(mp.count(sum-k)>0)//sum of a[mp[sum-k] to i] = k
{
mx=max(mx,i-mp[sum-k]);//mn=min(mn,i-mp[sum-k]);
//res->push_back(mp[sum-k]+1);
//res->push_back(i);
}
if(mp.count(sum)==0)//keep the earlist pos to ger max len, need not for min len
mp[sum]=i;
}
return mx;//res
}
//increment n-1 of item each time, how many steps ti make all same
//[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
int minMoves(int num[],size_t sz){
int mn=num[0];
int sum=0;
for(int i=0;i<sz;++i){
mn=min(mn,num[i]);
sum+=num[i];
}
return sum-mn*sz;//diff btw all min to num
}
int maxSub(int a[], size_t size)
{
int newSum=a[0];
int max=a[0];
size_t start=0, end=0;
for(unsigned i=1;i<size;++i)
{
if(a[i]>newSum+a[i])
{
newSum=a[i];
start=i;
}
else
{
newSum+=a[i];
}
if(newSum>max)
{
max=newSum;
end=i;
}
}
return max;
}
//sorted array is rotated at 7 0 pivot (0 1 2 4 5 6 7 > 4 5 6 7 0 1 2)
int rotatePivot(int num[], size_t sz){
int l=0, r=sz-1;
while(l<r-1){
int m=(l+r)/2;
if(num[l]<num[m])//only need compare num[l], pivot right to m
l=m;
else//pivot left to m
r=m;
}//l=7 r=0
return l;//or r
}
int findPeak(int a[], size_t size)
{
int s=0,e=size-1;
while(s<e-1)
{
int m=(s+e)/2;
if(a[m]<a[m-1])
{
e=m-1;
}
else if(a[m]<a[m+1])
{
s=m+1;
}
else
{
return a[m];
}
}
return max(a[s],a[e]);
}
int sigNumBySet(int a[], size_t size)
{
unordered_set<int> num;
for(unsigned i=0;i<size;++i)
{
if (num.count(a[i])>0)
{
num.erase(a[i]);
}
else
{
num.insert(a[i]);
}
}
auto it=num.begin();
return *it;
}
void printRepeating(int a[], size_t size)
{
int count[size-2];
for(unsigned i=0;i<size;++i)
{
if(count[a[i]]==1)
{
cout<<a[i]<<endl;
}
count[a[i]]=1;
}
}
void mergeSortedArray(int A[], int m, int B[], int n) {
int i = m-1, j = n-1, index = m + n - 1;
while (i >= 0 && j >= 0) {
if (A[i] > B[j]) {
A[index--] = A[i--];//from end avoid overwrite
} else if (A[i] < B[j]) {
A[index--] = B[j--];
} else {//A[i] == B[j]
A[index--] = A[i--];
A[index--] = B[j--];
}
}
while (i >= 0) {//only A has items left
A[index--] = A[i--];
}
while (j >= 0) {
A[index--] = B[j--];
}
}
unsigned longestConsecutive(int a[], size_t size)
{
unordered_set<int> hs;
unsigned mx=0;
for(unsigned i=0;i<size;++i)
{
hs.insert(a[i]);
}
for(unsigned i=0;i<size;++i)
{
int left=a[i]-1;
int right=a[i]+1;
unsigned count=1;
while(hs.count(left))
{
count++;
hs.erase(left);
left--;
}
while(hs.count(right))
{
count++;
hs.erase(right);
right++;
}
mx=max(count,mx);
hs.erase(a[i]);
}
return mx;
}
int largestRectangle(int a[],size_t size)
{
stack<int> st;
int mx=0;
for(unsigned i=0;i<=size;++i)
{
int cur=(i==size)?-1:a[i];
while(!st.empty() && cur<=a[st.top()])
{
int h=st.top();
st.pop();
int w=st.empty()?i:(i-st.top()-1);//or int w=i-h;
cout<<a[h]<<"|"<<w<<endl;
mx=max(a[h]*w,mx);
}
st.push(i);
}
return mx;
}
int trapWater(int a[],size_t size)
{
int lmax[size]={0};
int rmax[size]={0};
int wtr=0;
//side bars do not trap water
for(unsigned i=1;i<size;++i)
{
lmax[i]=max(lmax[i-1],a[i-1]);
cout<<lmax[i]<<endl;
}
for(unsigned i=size-2;i>=0;--i)
{
rmax[i]=max(rmax[i+1],a[i+1]);
cout<<rmax[i]<<endl;
int mn=min(lmax[i],rmax[i]);
if(mn>a[i])
{
wtr+=mn-a[i];
}
}
return wtr;
}
int triangleCount(int a[],size_t size)
{
sort(a,a+size);
int ct=0;
for(unsigned i=size-1;i>2;--i)
{
int l=0,r=i-1;
while(l<r)
{
if(a[l]+a[r]>a[i])
{
ct+=r-l;
r--;
}
else
{
l++;
}
}
}
return ct;
}
void pascalTriangle(){
int pt[5][5];
for(unsigned i=0;i<5;++i){
for(unsigned j=0;j<=i;++j){
if(j==0||j==i)
pt[i][j]=1;
else
pt[i][j]=pt[i-1][j-1]+pt[i-1][j];
cout<<pt[i][j];
}
cout<<endl;
}
}
int pascalNumber(unsigned i,unsigned j){
if(j==0||i==j)
return 1;
if(j==1||j==i-1)
return i;
return pascalNumber(i-1,j-1)+pascalNumber(i-1,j);
}
int maxSumTriangle(vector<vector<int>>& data){
//vector<int> dp(data.back());
for(unsigned row=data.size()-2;row>=0;--row){
for(unsigned col=0;col<=row;++col){
data[row][col]=data[row][col]+max(data[row+1][col],data[row+1][col+1]);
//dp[col] = min(dp[col], dp[col + 1]) + data[row][col];
}
}
return data[0][0];//dp[0]
}
int maxPointsOnLine(vector<Point>& points){
if(points.empty())
return 0;
unordered_map<float, int> stat;
int mx=1;
for(int i=0;i<points.size();++i){
int dup=0;
stat.clear();//per base point
for(int j=i+1;j<points.size();++j){//thru rest points
if(points[i].x==points[j].x && points[i].y==points[j].y){
++dup;
}
else{
//slope of vertical as INT_MAX
float slope= (points[j].x - points[i].x) == 0 ? INT_MAX : (float) (points[j].y - points[i].y) / (points[j].x - points[i].x);
if(stat.count(slope)>0)
stat[slope]++;
else
stat[slope]=2;//2nd point from start
}
}
for(auto it=stat.begin();it!=stat.end();++it){
if (it->second+dup>mx)
mx=it->second+dup;
}
}
return mx;
}
bool isRectOverLap(Rect r1,Rect r2){
if(r1.r.x<r2.l.x || r1.l.x>r2.r.x)//r1 left|right aside r2
return false;
if(r1.l.y>r2.r.y || r1.r.y<r2.l.y)//r1 above|below aside r2
return false;
return true;
}
//first index of substring b in string a
int strStr(string a,string b){
for(int i=0;i<a.size();++i){
if(a[i]==b[0]){
bool c=true;
for(int j=1;j<b.size();++j){
if(a[i+j]!=b[j]){
c=false;
break;
}
}
if(c)
return i;
}
}
return 0;
}
bool isPalindrome(string s){
stack<char> st;
int len=s.size();
int idx=0;
while(idx<len/2){
st.push(s[idx]);
idx++;
}
if (len%2==1)
idx++;
while(idx<len){
if (st.empty())
return false;
if(s[idx]!=st.top())
return false;
idx++;
st.pop();
}
return true;
}
string helper(string s, int l, int r){
while(l>=0 && r<=s.size()-1 && s[l]==s[r]){
l--;
//count++; to find num of Palindrome include overlap
r++;
}
//previous pl=l+1 and pr=r-1 length of pr-pl+1=r-l-1
return s.substr(l+1,r-l-1);
}
string longestPalindrome(string s){
if(s.size()==1)
return s;
string lp=s.substr(0,1);
for (unsigned i=0;i<s.size();++i){
string tmp=helper(s,i,i);
if(tmp.size()>lp.size())
lp=tmp;
if(i<s.size()-1){
tmp=helper(s,i,i+1);
if(tmp.size()>lp.size())
lp=tmp;
}
}
return lp;
}
bool isAnagram(string sa, string sb){
if(sa.size()!=sb.size())
return false;
unsigned char ltr[128]={0};
for (unsigned i=0;i<sa.size();++i){
ltr[sa[i]]++;
ltr[sb[i]]--;
}
for(unsigned i=0;i<128;++i){
if (ltr[i]!=0)
return false;
}
return true;
}
vector<vector<string>> groupAnagrams(string sa[], size_t size){
vector<vector<string>> ret;
unordered_map<string,vector<string>> mp;
for (unsigned i=0;i<size;++i){
string s=sa[i];
sort(s.begin(),s.end());
if(mp.count(s))
mp[s].push_back(sa[i]);
else{
vector<string> vs;
vs.push_back(sa[i]);
mp.insert(make_pair(s,vs));
}
}
for(auto m : mp)
ret.push_back(m.second);
return ret;
}
void swap(int num[], size_t bgn,size_t end){
if(bgn==end)
return;
int t=num[bgn];
num[bgn]=num[end];
num[end]=t;
}
void permute(int num[],size_t sz,size_t bgn){
if(bgn>=sz){
for(unsigned i=0; i<sz;++i)
cout<<num[i];
cout<<endl;
}
for(unsigned i=bgn; i<sz;++i){
swap(num,bgn,i);
permute(num,sz,bgn+1);
swap(num,i,bgn);
}
}
static string key[]={"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void dailNumToStr(string dgt,vector<char>& lst,vector<string>& res){
if(dgt.size()==0){
string str{ lst.begin(), lst.end() };
res.push_back(str);
return;
}
int cur=dgt[0]-'0';
string ltr=key[cur];
for(char c : ltr){
lst.push_back(c);
dailNumToStr(dgt.substr(1),lst,res);
lst.pop_back();
}
}
void combNum(int num[],size_t sz,int bgn,int sum,vector<int>& lst, vector<vector<int>>& res){
if(sum==0){
res.push_back(lst);
cout<<endl;
return;
}
for(int i=bgn; i<sz;++i){
if(num[i]>sum)
continue;
lst.push_back(num[i]);
combNum(num,sz,i+1,sum-num[i],lst,res);
lst.pop_back();
}
}
int woodCut(unsigned l[], size_t sz, int k){
if (sz==1)
return l[0]/k;
unsigned bgn=0,mid=0,mx=0;
for(unsigned i=0;i<sz;++i){
mx=max(mx,l[i]);//cant compare unsigned & int
}
unsigned end=mx-1;
while(bgn+1<end){//bgn3,end5=mid4
mid=(bgn+end)/2;
unsigned ct=0;
for(unsigned i=0;i<sz;++i)
ct+=l[i]/mid;
if(ct>=k){
bgn=mid;
mx=mid;
}
else{
end=mid;
}
}
return mx;
}
void subJobs(vector<Job> jbs,int id){
unordered_map<int,vector<Job>*> rel;
for(Job j:jbs){
if(rel.count(j.superId)){
vector<Job>* r=rel[j.superId];
r->push_back(j);
}
else{
vector<Job>* r=new vector<Job>();
r->push_back(j);//or vector<int> store j.Id less mem
rel[j.superId]=r;
}
}
}
void listSubJobs(unordered_map<int,vector<Job>*>& rel,int id){//(unordered_map<int,unique_ptr<vector<Job>>> rel,int id)
vector<Job>* jbs=rel[id];
for(Job j:*jbs){//jbs is pointer
cout<<j.Id<<endl;
listSubJobs(rel,j.Id);
}
}
void listSubJobsBFS(unordered_map<int,unique_ptr<vector<Job>>> rel,int id){
queue<int> q;
q.push(id);
while(!q.empty()){
int cId=q.front();
q.pop();
unique_ptr<vector<Job>> jp=move(rel[cId]);//unique_ptr<vector<Job>> jp(new vector<Job>()); shared_ptr need not move
for(Job& j:*jp){
cout<<j.Id<<endl;
q.push(j.Id);
}
}
}
int getKthSmallest(int n[],size_t sz,unsigned k,unsigned bgn,unsigned end){
int pvt=n[end];//init call with bgn=0 end=size-1
int l=bgn;
int r=end-1;
while(l<r){
while(n[l]<pvt&&l<r){
l++;
}
while(n[r]>pvt&&l<r){
r--;
}
swap(n,l,r);
}
swap(n,l,end);
if(k==l+1)
return pvt;
else if(k<l+1){
return getKthSmallest(n,sz,k,bgn,l-1);
}
else{
return getKthSmallest(n,sz,k-l-1,l+1,end);
}
}
vector<int> streamMedian(int n[],size_t sz){
priority_queue<int,vector<int>,greater<int>> maxq;
priority_queue<int> minq;
vector<int> ret;
ret.push_back(n[0]);
maxq.push(n[0]);
for(int i=1;i<sz;++i){
int pre=maxq.top();
if(n[i]>pre)
minq.push(n[i]);
else
maxq.push(n[i]);
if(maxq.size()>minq.size()+1){
minq.push(maxq.top());
maxq.pop();
}
else if(maxq.size()<minq.size()){
maxq.push(minq.top());
minq.pop();
}
ret.push_back(maxq.top());
}
return ret;
}
//return P if A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1] with O(n)
int equilibriumIndex(vector<int> &A){
int sum = 0;
for(int i =0;i<A.size();i++){
sum = sum + A[i];
}
int for_sum = 0;
int result = 0;
for(int i =0;i<A.size();i++){
sum = sum-A[i];
if(sum == for_sum){
result = i;
break;
}
for_sum = for_sum + A[i];
}
return result;
}
//find index h in desc array where c[i<h]>=h and c[i>h]<=h by O(logn)
int hIndex(vector<int>& citations) {//[6,5,2|3,1,0] 2|3
sort(citations.begin(), citations.end(), greater<int>());
int len = citations.size(), left = 0, right = len - 1;
while (left < right) {
int mid = (left + right)/2;
if (citations[mid] == mid) return mid;
else if (citations[mid] > mid) left = mid + 1;
else right = mid - 1;//c[mid]<mid, to get bigger c[i] smaller i
}
return left;
}
//similiar put each item from unsorted array to array count[item]++ per occurrence
//output thru its index (sorted), 0 no output, dup output -- till 0
vector<int> countSortSimp(int in[], size_t sz, unsigned k){
int ca[k+1];
fill_n(ca,k+1,0);//cant ={0] for var size array
for(int i=0;i<sz;++i)
ca[in[i]]++;
vector<int> out(sz);
for(int j=0;j<=k;++j){
while(ca[j]>0){//sorted index as value if exists
out.push_back(j);
--ca[j];
}
}
return out;
}
vector<int> maxSlidingWindow(int num[], size_t sz, unsigned k){
vector<int> rst;
deque<int> dq;
for(int i=0;i<sz;++i){
if(i>=k){
rst.push_back(num[dq.front()]);
if(!dq.empty()&&dq.front()<=i-k)
dq.pop_front();
}
while(!dq.empty()&&num[dq.front()]<num[i])
dq.pop_back();
dq.push_back(i);
}
rst.push_back(num[dq.front()]);
return rst;
}
vector<GraphNode*> topSort(vector<GraphNode*> graph){
vector<GraphNode*> rst;
unordered_map<string,unsigned> mp;
for(GraphNode* gn : graph){
for(GraphNode* dn : gn->directs){
string key=dn->value;
if(mp.count(key))
mp[key]++;
else
mp[key]=1;
}
}
queue<GraphNode*> gq;
for(GraphNode* gn : graph){
if(mp.count(gn->value)==0){
rst.push_back(gn);
gq.push(gn);
}
}
while(!gq.empty()){
GraphNode* gn=gq.front();
gq.pop();
for(GraphNode* dn : gn->directs){
string key=dn->value;
mp[key]--;
if(mp[key]==0){
rst.push_back(dn);
gq.push(dn);
}
}
}
return rst;
}
//{a c d} {b c e}={a b c d e} or {b a c e d} not {a e c b d}
//tks=ac cd bc ce sz=5
//similar {"caa", "aaa", "aab"} > c a b
//compare each adjacent words find the first different letters load to pairs ca ab
vector<char> topOrder(vector<pair<char,char>> tks, int sz) {
int ct[sz]{0};
queue<int> tq;
vector<char> rs;
for (auto& t : tks)
ct[t.second-'a']++;//map char to int
for(int i=0;i<sz;++i){
if(ct[i]==0){
tq.push(i);
rs.push_back(i+'a');
}
}
while(!tq.empty()){
int f=tq.front();
tq.pop();
for (auto& t : tks){
if (f==t.first-'a'){
int s=t.second-'a';
if(--ct[s] == 0){
tq.push(s);
rs.push_back(s+'a');//t.second
}
}
}
}
return rs;
}
//1->2->3->4 as 2->1->4->3
Node* swapPairs(Node* hd){
Node* h=new Node(0);
h->next=hd;//extra node to track because orig head will be swapped
Node* p=h;
while(p->next!=nullptr && p->next->next!=nullptr){//0-1-2-3
Node* t1=p;//t1(0) p(0)
p=p->next;//p(1)
t1->next=p->next;//0->2
Node* t2=p->next->next;//t2(3) remember before reset next next
p->next->next=p;//2->1
p->next=t2;//1->3
p=t2;//p(3)
}//0-2-1-3
return h->next;
}
//O(1) space
Node* copyRandomList(Node* hd){
Node* i=hd;
Node* n;
while(i!=nullptr){
n=i->next;
Node* c=new Node(i->value);
i->next=c;
c->next=n;
i=n;
}
i=hd;
while(i!=nullptr){
if(i->rand!=nullptr){
i->next->rand=i->rand->next;
}
i=i->next->next;
}
i=hd;
n=i->next;
Node* nhd=n;
while(i!=nullptr){
i->next=n->next;
i=i->next;
n->next=i==nullptr?nullptr:i->next;
n=n->next;
}
return nhd;
}
//Merge Interval 2D similarly merge on X & Y
int mergeInterval(vector<Interval> av){
int maxLen=0;
stack<int> st;
for(Interval i : av){
if(st.empty()){
st.push(i.start);
st.push(i.end);
}
else{
if(st.top()>=i.start && st.top()<i.end){//=start|end push|not new end
st.pop();
st.push(i.end);
}
else if(st.top()<i.start){
int e=st.top();
st.pop();
maxLen=max(maxLen,e-st.top());
st.pop();
st.push(i.start);
st.push(i.end);
}
}
}
if(!st.empty()){
int e=st.top();
st.pop();
maxLen=max(maxLen,e-st.top());
st.pop();
}
return maxLen;
}
bool isValidBST(TreeNode* root,double min,double max){//isValidBST(root,INT_MIN,INT_MAX)
if(root==nullptr)
return true;
if(root->value<=min||root->value>=max)
return false;
return isValidBST(root->left,min,root->value) && isValidBST(root->right,root->value,max);
}
int maxDepth(TreeNode* root){
if(root==nullptr)
return 0;
int l=maxDepth(root->left);
int r=maxDepth(root->right);
return max(l,r)+1;//min for minDepth
}
int maxDepths(TreeNode* root){
if(root==nullptr)
return 0;
int curMax=0;
for(TreeNode* n:root->subNodes){
int curDepth=maxDepths(n);
curMax=max(curMax,curDepth);
}
return curMax+1;
}
int DistanceFromRoot(TreeNode* root, TreeNode* node){
int dist = 0;
//stack node with its distance to the source
std::stack<std::pair<std::shared_ptr<TreeNode>,int>> appStack;
appStack.push(std::make_pair(root,1));
//Depth First Search on each topic to the application
while(!appStack.empty()){
std::pair<std::shared_ptr<TreeNode>,int> nodeDist = appStack.top();
std::shared_ptr<TreeNode> tn = nodeDist.first;
dist = nodeDist.second;
appStack.pop();
/*
if(tn == node){
return dist;
}
*/
for (auto ta : tn->subNodes){
if(ta == node){
//return as soon as the appId found by publisher, earlier than above commented out
return dist+1;
}
dist += 1;
appStack.push(std::make_pair(ta, dist));
}
}
return dist;
}
int maxSum (TreeNode* root){
if(root==nullptr)
return 0;
int lmx=maxSum(root->left);
int rmx=maxSum(root->right);
return root->value+max(lmx,rmx);
}
//max distance btw nodes
int diameter(TreeNode * tree)
{
if (tree == NULL)
return 0;
int lheight = maxDepth(tree->left);
int rheight = maxDepth(tree->right);
int ldiameter = diameter(tree->left);
int rdiameter = diameter(tree->right);
//longest path between leaves via root vs diameter of root’s left|right subtree
return max(lheight + rheight + 1, max(ldiameter, rdiameter));
}
bool isBalanced(TreeNode* root){
int lh=0,rh=0;
if(root==nullptr)
return 0;
lh=maxDepth(root->left);
rh=maxDepth(root->right);
if(abs(lh-rh)<=1 && isBalanced(root->left) && isBalanced(root->right))
return true;
return false;
}
bool isFull(TreeNode* root){
if(root==nullptr)
return true;
if(root->left==nullptr&&root->right==nullptr)
return true;
if(root->left==nullptr||root->right==nullptr)//same as compareTree
return false;
return isFull(root->left)&&isFull(root->right);
}
bool hasPathSum(TreeNode* root, int sum){
if (root==nullptr)
return false;
if (root->value>sum)//only applicable if all node->value>0
return false;
if (root->value==sum && root->left==nullptr && root->right==nullptr)
return true;
return hasPathSum(root->left,sum-root->value)||hasPathSum(root->right,sum-root->value);
}
//REV#
void pathSum(TreeNode* root,int sum,vector<vector<int>>& result,vector<int>& list){
//void pathMinSum(TreeNode* root,int curSum,int minSum,vector<vector<int>>& result,vector<int>& list){
if(root->value>sum)//if use sum==0 then 1 more recursion and cant tell if leaf
//if(curSum+root->value>minSum)
return;
if(root->value==sum && root->left==nullptr && root->right==nullptr){
//if(curSum+root->value<minSum && root->left==nullptr && root->right==nullptr){
list.push_back(root->value);//list from previous recursion does not include current node
result.push_back(list);
list.pop_back();
}
if(root->left!=nullptr){
list.push_back(root->value);
pathSum(root->left,sum-root->value,result,list);
//pathMinSum(root->left,curSum+root->value,minSum,result,list);
list.pop_back();
}
if(root->right!=nullptr){
list.push_back(root->value);
pathSum(root->right,sum-root->value,result,list);
//pathMinSum(root->left,curSum+root->value,minSum,result,list);
list.pop_back();
}
}
int maxPathSum (TreeNode* root,int sum){
if(root==nullptr)
return sum;
int mx=max(maxPathSum(root->left,root->value+sum),maxPathSum(root->right,root->value+sum));
return max(sum,mx);//root->value < 0
}
//depth of path with most distinct nodes
int maxPathDistinct (TreeNode* root,unordered_set<int>& prev){
if(root==nullptr)
return 0;
char add=1;
if(prev.count(root->value)>0)
add=0;//not to increment if duplicate
prev.insert(root->value);
int mx=max(maxPathDistinct(root->left,prev)+add,maxPathDistinct(root->right,prev)+add);
prev.erase(root->value);
return mx;
}
//dfs to sum int at each node, x10 per layer
int sumNum(TreeNode* root,int sum){
if(root==nullptr)
return 0;
if(root->left==nullptr&&root->right==nullptr)
return sum*10+root->value;
return sumNum(root->left,sum*10+root->value)+sumNum(root->right,sum*10+root->value);
}
int sumNumBFS(TreeNode* root){
int sum;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
for(int i=0;i<q.size();++i){
TreeNode* c=q.front();
q.pop();
sum+=10*sum+c->value;
if(c->left!=nullptr)
q.push(c->left);
if(c->right!=nullptr)
q.push(c->right);
}
}
return sum;
}
unsigned insertNode(TreeNode* root,int val){
if(root==nullptr){//only 1st node
root=new TreeNode(val);
return 0;
}
while(root!=nullptr){
if(root->value>val){
if(root->left==nullptr){
root->left=new TreeNode(val);
int ct=root->count;
root->count++;//root has additional left
return ct;
}
else{
root=root->left;
}
}else{
if(root->right==nullptr){
root->right=new TreeNode(val);
root->right->count=root->count+1;// >root and all its smaller
return root->right->count;
}
else{
root=root->right;
}
}
}
}
//Count of Smaller Numbers After Self [5, 2, 6, 1], after 5|2 there are 2|1 smaller (2,1)|(1), output [2, 1, 1, 0].
vector<int> smallerNumsCount(int num[],size_t sz){
vector<int> ret;
TreeNode* root=new TreeNode(num[sz-1]);
for(unsigned i=sz-2;i>=0;--i){
int ct=insertNode(root,num[i]);
ret.push_back(ct);
}
return ret;
}
void removeleaf(TreeNode* p) {
if (p == NULL) {
return;
}
else {
if (p->left || p->right) {
removeleaf(p->left);
removeleaf(p->right);
}
else {
delete p;
return;
}
}
}
//REV#
TreeNode* lowestCommonAncestor(TreeNode* root,TreeNode* l,TreeNode* r){//l<r
while(root!=nullptr){
if(root->value<l->value)
root=root->right;//return lowestCommonAncestor(root->right,l,r);
else if(root->value>r->value)
root=root->left;//return lowestCommonAncestor(root->left,l,r);
else
return root;
}
return nullptr;
}
//revised
void findPrevNextTree(TreeNode* root,int val){
int prev=INT_MIN,next=INT_MAX;
while(root!=nullptr){
if(root->value>val){
next=root->value;
if(root->left->value<val){
prev=root->left->value;
return;
}
else
root=root->left; //findPrevNextRecursive(root->left,prev,next,val);
}
else if(root->value<val){
prev=root->value;
if(root->right->value>val){
next=root->right->value;
return;
}
else
root=root->right;//findPrevNextRecursive(root->right,prev,next,val);
}
else{
prev=root->left->value;
next=root->right->value;
return;
}
}
}
void findPrevNextArray(int num[],size_t sz,int val){
int bgn=0,mid=0,end=sz-1;
int prev=INT_MIN,next=INT_MAX;
while(bgn<end-1){//beg(prev) always < end(next)
mid=(bgn+end)/2;
if(num[mid]<val)
bgn=mid;
else if(num[mid]>val)
end=mid;
else{
prev=num[mid-1];
next=num[mid+1];
return;
}
}
prev=num[bgn];
next=num[end];
}
//UNI#finding right|left most occurrences of key in sort array with duplicate
int getRightMost(int num[], size_t sz,int val)//Left
{ int m, r=sz-1, l=0;
while( r - l > 1 )
{ m = l + (r - l)/2;
if( num[m] < val )
l = m;
else if(num[m] > val)
r = m;
else
l=m;//r=m; when num[m] == val keep move toward right|left till not
}
return l;//return r;
}
TreeNode* sortedArrayToBST(int num[],int bgn,int end){//end=size-1
if(bgn>end)
return nullptr;
int mid=(bgn+end)/2;
TreeNode* root=new TreeNode(num[mid]);
root->left=sortedArrayToBST(num,bgn,mid-1);
root->right=sortedArrayToBST(num,mid+1,end);
return root;
}
Node* findMid(Node* head){
Node* slow=head;
Node* fast=head;
while(fast->next!=nullptr && fast->next->next!=nullptr){
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
TreeNode* sortedListToBST(Node* head){
if(head==nullptr)
return nullptr;
else if(head->next==nullptr)
return new TreeNode(head->value);
Node* mid= findMid(head);
TreeNode* root=new TreeNode(mid->next->value);
root->right=sortedListToBST(mid->next->next);
mid->next=nullptr;//can only break by mid-next
root->left=sortedListToBST(head);
return root;
}
Node* IterateMergeList(Node* ln,Node* rn){//ref recursiveMergeList
Node* tn=new Node(0);
Node* hd=tn;
while(ln!=nullptr&&rn!=nullptr){
if(ln->value<rn->value){
hd->next=ln;
ln=ln->next;
}
if(ln->value<rn->value){
hd->next=rn;
rn=rn->next;
}
hd=hd->next;
}
if(ln!=nullptr)
hd->next=ln;
else if(rn!=nullptr)
hd->next=rn;
return tn->next;
}
//O(n log n) time using constant space complexity
Node* sortList(Node* head){
if(head==nullptr || head->next==nullptr)
return head;//recurse till single node
Node* mid=findMid(head);
Node* r=sortList(mid->next);
mid->next=nullptr;
Node* l=sortList(head);
return IterateMergeList(r,l);
}
//log(k) * n
Node* mergeKLists(Node* heads[],size_t sz){
priority_queue<Node*, vector<Node*>, compNode> pq;
Node* hd=new Node(0);
Node* cur=hd;
for(unsigned i=0;i<sz-1;++i){
if(heads[i]!=nullptr)
pq.push(heads[i]);
}
while(!pq.empty()){
Node* tn=pq.top();
pq.pop();
cur->next=tn;
cur=cur->next;
if(tn->next!=nullptr)//if input vector<queue<int>>, use pair{i,val} to track vector[i] for next val
pq.push(tn->next);
}
return hd->next;
}
vector<int> preorderTraversal(TreeNode* root){
vector<int> rv;
if(root==nullptr)
return rv;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* cur=stk.top();
stk.pop();
rv.push_back(cur->value);
if(cur->right!=nullptr)
stk.push(cur->right);//push right before left and left pop before right
if(cur->left!=nullptr)
stk.push(cur->left);
}
return rv;
}
//in-order: 4 2 5 (1) 6 7 3 8 left-root-right
//pre-order: (1) 2 4 5 3 7 6 8 root-left-right
TreeNode* buildHelper(vector<int> preOrder,int preBgn,int preEnd,vector<int> inorder,int inBgn,int inEnd){
TreeNode* root=new TreeNode(preOrder[preBgn]);
int pos=0;
for(unsigned i=0;i<inorder.size()-1;++i){
if(inorder[i]==preOrder[preBgn]){
pos=i;
break;
}
}
int len=pos-inBgn;
root->left=buildHelper(preOrder,preBgn+1,preBgn+len,inorder,inBgn,pos-1);
root->right=buildHelper(preOrder,preBgn+len+1,preEnd,inorder,pos+1,inEnd);
return root;
}
bool twoSumTree(TreeNode* root,int sum){
stack<TreeNode*> stk1;
stack<TreeNode*> stk2;
TreeNode* cur1=root;
TreeNode* cur2=root;
while(!stk1.empty()||!stk2.empty()||cur1!=nullptr||cur2!=nullptr){
if(cur1!=nullptr||cur2!=nullptr){
if(cur1!=nullptr){
cur1=cur1->left;
stk1.push(cur1);
}
if(cur2!=nullptr){
cur2=cur2->right;
stk2.push(cur2);
}
}
else{//till reach the end of left and right
int val1=stk1.top()->value;
int val2=stk2.top()->value;
if(val1==val2)
break;//left=right
if(val1+val2==sum)
return true;
else if(val1+val2<sum){//increase by val1
cur1=stk1.top()->right;
stk1.pop();
}
else{//val1+val2>sum, reduce by val2
cur2=stk2.top()->left;
stk2.pop();
}
}
}
return false;
}
bool compareTree(TreeNode* t1,TreeNode* t2){
if(t1==nullptr&&t2==nullptr)
return true;
else if(t1==nullptr||t2==nullptr)
return false;
return compareTree(t1->left,t2->right) && compareTree(t1->right,t2->left);//symmetric
}
//REV#
vector<int> rightSideView(TreeNode* root){//int nodeLayer(TreeNode* root,int layer,int order)
vector<int> res;
if(root==nullptr)
return res;
queue<TreeNode*> tq;
//int level=0
while(!tq.empty()){
size_t sz=tq.size();
//level++;
for(unsigned i=0;i<sz;++i){
TreeNode* cur=tq.front();
tq.pop();
//if(level==layer && i=order-1)
//return cur->value;
if(i==0)
res.push_back(cur->value);
if(cur->right!=nullptr)
tq.push(cur->right);
if(cur->left!=nullptr)
tq.push(cur->left);
}//nodes pudhed by whole layer
}
return res;
}
//Next Pointers to Right Node or null, recursive for space O(1)
void nextPtrRight(TreeNode* root){
if(root==nullptr)
return;
TreeNode* ln=root->left;
TreeNode* rn=root->right;
if(ln!=nullptr){
ln->next=rn;
if(ln->right!=nullptr)
ln->right->next=rn->left;
}
nextPtrRight(ln);
nextPtrRight(rn);
}
int getWeight(unsigned base,char c){
if(c=='+'||c=='-')
return base+1;
if(c=='*'||c=='/')
return base+2;
return INT_MAX;
}
TreeNode* expressionToTree(string exp){
stack<TreeNode*> stk;
unsigned base=0;
int val=0;
for(char c : exp){
if(c=='('){
base+=10;
continue;
}
if(c==')'){
base-=base;
continue;
}
val=getWeight(base,c);
TreeNode* cur=new TreeNode(val,c);
while(!stk.empty() && val<=stk.top()->value){//min tree
TreeNode* prev=stk.top();
stk.pop();
cur->left=prev;
}
if(!stk.empty()){
stk.top()->right=cur;
}
stk.push(cur);
}
TreeNode* res=stk.top();
while(!stk.empty()){
res=stk.top();
stk.pop();
}
return res;
}
string treeToExpression(TreeNode* root){
string cur="";
string l="";
string r="";
if(root!=nullptr){
cur=root->sym;
if(root->sym=='*' || root->sym=='/'){
if(root->left->sym=='+'||root->left->sym=='-')////(a+b)*...
l=l;//l="("+treeToExpression(root->left)+")";
else
l=treeToExpression(root->left);
if(root->right->sym=='+'||root->left->sym=='-')//...*(a+b)
r=r;//r="("+treeToExpression(root->right)+")";
else
r=treeToExpression(root->right);
}
else{//a+b+c+d a*b+c*d
l=treeToExpression(root->left);
r=treeToExpression(root->right);
}
}
return l.append(cur.append(r));//l+cur+r
}
int calulate(int a, int b, const string &op) {
if (op == "+") return a + b;
else if (op == "-") return a - b;
else if (op == "*") return a * b;
else return a / b;
}
bool isOK(const string &op1, const string &op2) {//op1 is higher than op2
if (op1 == "*" || op1 == "/" || op2 == ")") return true;
else return op2 == "+" || op2 == "-";
}
//UNI# assume the expression is valid, 1 stack store variables, 1 stack store operators
//if var push to stack,
//if op higher than prevop, push to stack
//if op lower than prevop,calc all prevops higher than op before push op
//if op is ( push to stack
//if op is ) calc all prevopFs before prev (
int evaluateExpression(vector<string> &expression) {
if (expression.empty()) return 0;
stack<int> stk_val;
stack<string> stk_op;
for (int i = 0; i <= expression.size(); ++i) {
if (i < expression.size() && isdigit(expression[i])) {
stk_val.push(atoi(expression[i].c_str()));//keep push if variable
} else if (i == expression.size() || expression[i] != "(") {
while (!stk_op.empty() && stk_op.top() != "(" && (i == expression.size() || isOK(stk_op.top(), expression[i]))) {
int tmp = stk_val.top();//if prev op is not ( or cur op is lower keep calc till
stk_val.pop();
stk_val.top() = calulate(stk_val.top(), tmp, stk_op.top());
stk_op.pop();
}
if (i == expression.size()) break;
else if (expression[i] == ")") stk_op.pop();
else stk_op.push(expression[i]);
} else {
stk_op.push(expression[i]);//push (
}
}
return stk_val.top();
}
bool wordBreak(string s,unordered_set<string> dict){
if(s.empty() || dict.count(s))
return true;
string ss=string("#").append(s);
int len = ss.size();
bool dp[len];
dp[0]=true;//treat # as in dict
for(int i=1;i<len;++i){
for(int k=0;k<i;++k){
//valid if dp[k] == true and s[k+1,i] in dictionary 0<k<i
dp[i]=dp[k]&&dict.count(ss.substr(k+1,i-k));
if(dp[i])//as long as one comb valid
break;
}
}
return dp[len-1];
}
//"13 DUP 4 POP 5 DUP + DUP + -" rerutn 7
int solution2(string &S) {
stringstream ss(S);
vector<string> sv;
string buf;
while (ss >> buf)
sv.push_back(buf);
stack<int> st;
for (auto c : sv){
if(int ci=atoi(c.c_str())>0)
st.push(ci);
else {
if (c == "+" && st.size()>=2) {
int s1=st.top();
st.pop();
int s2=st.top();
st.pop();
int x = s1+s2;
st.push(x);
}
else if (c == "-" && st.size()>=2) {
int s1=st.top();
st.pop();
int s2=st.top();
st.pop();
int x = s1-s2;
st.push(x);
}
else if (c == "DUP") {
int s1=st.top();
st.push(s1);
}
else if (c == "POP") {
st.pop();
}
else
return -1;
}
}
return st.top();
}
const int m=10,n=10;
static int matrix[m][n];
//end = m * n - 1; while(start<end){ mid = (end + start)/2;
//int num = matrix[mid/n][mid%n];//[row][col] if (num <|> target) { start|end =mid;}...O(logN+M)
bool searchSortMatrix(int** matrix,int val){
int r=5,c=0;//start from first item in last row
while(r>=0 && c<=10){
if(val<matrix[r][c])
--r;
else if(val>matrix[r][c])
++c;
else
return true;
}
return false;
}
//max gain sell 8 by any way 3:7+5:15=22
//{ 1, 4, 7, 9,15, 17,18,20,0} append 0 to actual array before call
int maxGain(int gain[],size_t sz){
int dp[sz]={0};//dp[0]=0
for(int i=1;i<sz;++i){
for(int j=1;j<=i;++j)//j=0 same as i
//for all j btw [0,i] gain by sell j + max gain of sell(i - j)
dp[i]=max(dp[i],dp[i-j]+gain[j-1]);//j-1: sell 2 map to gain[1]
}
return dp[sz-1];
}
int robMax(int gain[],size_t sz){
int dp[sz+1]={0};
dp[1]=gain[0];//dp[0]=0;
for(int i=2;i<sz+1;++i){
dp[i]=max(dp[i-1],dp[i-2]+gain[i-1]); //gain[i-1] for i
}
return dp[sz];
}
//BFS need queue to store all next nodes from current nodes
int traverse(int row,int col,int way,vector<int>&path,vector<vector<int>>& result){
if(row<0||row>=m||col<0||col>=n)
return 0;
else{
int pos=matrix[row][col];
if(pos==1||pos==-1)
return 0;
else if(row==m-1&&col==n-1){
path.push_back(way);
result.push_back(path);
path.pop_back();
return 1;
}
matrix[row][col]=-1;
path.push_back(way);//previous step
int ret=traverse(++row,col,1,path,result)+
traverse(row,++col,2,path,result)+
traverse(--row,col,3,path,result)+
traverse(row,--col,4,path,result);
path.pop_back();
matrix[row][col]=pos;
return ret;//return after restore
}
}
int minPathSum(int** matrix){//err matrix[][] must have const size
//int uniqPathSum(int** matrix){
int dp[m][n];//O(MN)time
dp[0][0]=matrix[0][0];
for(unsigned r=1;r<n;++r){
dp[r][0]=dp[r-1][0]+matrix[r][0];
//dp[r][0]=1;
}
for(unsigned c=1;c<m;++c){
dp[0][c]=dp[0][c-1]+matrix[0][c];
//dp[0][c]=1;
}
for(unsigned r=1;r<n;++r){
for(unsigned c=1;c<m;++c)
dp[r][c]=min(dp[r-1][c],dp[r][c-1])+matrix[r][c];
//dp[r][c]=dp[r-1][c]+dp[r][c-1];
}
}
//loop thru all pos to call with vector<vector<int> > dp(m, vector<int>(n, 0)); and return max
int longestIncreasePath(vector<vector<int>> &matrix, vector<vector<int>> &dp, int i, int j) {
if (dp[i][j])
return dp[i][j];//if alreay calc
vector<vector<int> > dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
int mx = 1, m = matrix.size(), n = matrix[0].size();
for (auto a : dirs) {
int x = i + a[0], y = j + a[1];
if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] <= matrix[i][j])
continue;
int len = 1 + longestIncreasePath(matrix, dp, x, y);
mx = max(mx, len);
}
dp[i][j] = mx;
return mx;
}
const int R=10,C=10;
void findWordsInMatrix(char matrix[R][C], int i, int j, string &str)
{
char preval=matrix[i][j];
matrix[i][j] = '#';//mark visited
str.push_back(preval);
//if (dict.count(str)>0) cout << str << endl;// print str is present in dictionary unordered_set
vector<vector<int> > dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0},{-1, -1}, {-1, 1}, {-1, 1}, {1, 1}};//8 ways
for (auto a : dirs) {
int row = i + a[0], col = j + a[1];
if (row>=0 && row<R && col>=0 && col<C && matrix[row][col] != '#')
findWordsInMatrix(matrix,row, col, str);
}
str.pop_back();// Erase current character from string
matrix[i][j] = preval;
}
//total number of ways to decode a digits message based on map 'A'=1 'B'=2 . 'J'=10.. 'Z'=26
int numDecodings(char *digits, int n)//121
{
if (n == 0 || n == 1)
return 1;
int count = 0;
if (digits[n-1] > '0') // If the last digit > 0
count = numDecodings(digits, n-1); //return as 1 way if each digit >0 : 1 2 1 = A B A
if (digits[n-2] < '2' || (digits[n-2] == '2' && digits[n-1] < '7') )// If the last two digits is from 10 to 26
count += numDecodings(digits, n-2); //21 = U, count 1 from above step+recur(1)
return count;
}
//#REV O(n)
int numDecodingsDP(char *digits, int n)
{
int count[n+1]{}; //count[n]:digits[n-1]
count[0] = 1;
count[1] = 1; //digits[0] can only 1 way
for (int i = 2; i <= n; i++)
{
if (digits[i-1] > '0')
count[i] = count[i-1];//count[i-1] X pass as 1 way
if (digits[i-2] < '2' || (digits[i-2] == '2' && digits[i-1] < '7') )
count[i] += count[i-2];//count[i-2] XX add as extra way
}
return count[n];
}
int minPathSumDFS(int row,int col){
//int uniqPathSumDFS(int row,int col){
//int minPathSumDFS(int row,int col, step k){ similar after k steps
if(row==m-1&&col==n-1)// || k=0
return matrix[row][col];
//return 1;
if(row<m-1&&col<n-1){
int d=minPathSumDFS(++row,col)+matrix[row][col];//(++row,col,k-1)
int r=minPathSumDFS(row,++col)+matrix[row][col];
return min(d,r);
//return uniqPathSumDFS(++row,col)+uniqPathSumDFS(++row,col);
}
if(row<m-1)
return minPathSumDFS(++row,col)+matrix[row][col];
//return uniqPathSumDFS(++row,col);
if(col<n-1)
return minPathSumDFS(row,++col)+matrix[row][col];
//return uniqPathSumDFS(row,++col);
return 0;//out of boundary
}
int calculateMinimumHP(int** matrix){
int hp[m][n];
hp[m-1][n-1]=max(1-matrix[m-1][n-1],1);
for(unsigned r=m-2;r>=0;--r)
hp[r][n-1]=max(hp[r+1][n-1]-matrix[r][n-1],1);
for(unsigned c=n-2;c>=0;--c)
hp[m-1][c]=max(hp[m-1][c+1]-matrix[m-1][c],1);
for(unsigned r=m-2;r>=0;--r){
for(unsigned c=n-2;c>=0;--c){
int down=max(hp[r+1][c]-matrix[r][c],1);
int right=max(hp[r][c+1]-matrix[r][c],1);
hp[r][c]=min(down,right);
}
}
return hp[0][0];
}
int sideIslands(int r,int c,int land){
if(r<0||c<0||r>m-1||c>n-1)//side to boundary
return 1;
if(matrix[r][c]==-land)//revisit
return 0;
if(matrix[r][c]!=land)//side to water or other land
return 1;
matrix[r][c]=-land;
return sideIslands(++r,c,land)+
sideIslands(r,++c,land)+
sideIslands(--r,c,land)+
sideIslands(r--,c,land);
}
int numIslands(int** matrix){
int sum=0;
for(int r=0;r<m-1;++r){
for(int c=0;c<n-1;++c){
if(matrix[r][c]!=0)//land
sum+=sideIslands(r,c,matrix[r][c]);
}
}
return sum;
}
int maxSquare(int** matrix){
int dp[m][n];
int maxLen=0;
for(int r=0;r<m-1;++r){
dp[r][m-1]=matrix[r][m-1];
maxLen=max(maxLen,dp[r][m-1]);
}
for(int c=0;c<n-1;++c){
dp[n-1][c]=matrix[n-1][c];
maxLen=max(maxLen,dp[n-1][c]);
}
for(int r=m-2;r>=0;--r){
for(int c=n-2;c>=0;--c){
if(matrix[r][c]==1){
//if adjacent 3 cells are at least 1, then cur cell (1) form 2x2 1s
dp[r][c]=min(min(dp[r+1][c],dp[r][c+1]),dp[r+1][c+1])+1;
maxLen=max(maxLen,dp[r][c]);
}
}
}
return maxLen*maxLen;
}
};
#endif //CAPP_MISC_H
|
#include <QDebug>
// RsaToolbox includes
#include "General.h"
#include "VnaSegmentedSweep.h"
#include "VnaChannel.h"
#include "Vna.h"
using namespace RsaToolbox;
// Qt includes
// #include <Qt>
/*!
* \class RsaToolbox::VnaSegmentedSweep
* \ingroup VnaGroup
* \brief The \c %VnaSegmentedSweep class
* configures and controls a frequency sweep
* with arbitrarily-defined measurement
* points.
*/
VnaSegmentedSweep::VnaSegmentedSweep(QObject *parent) :
QObject(parent)
{
placeholder.reset(new Vna());
_vna = placeholder.data();
_channel.reset(new VnaChannel());
_channelIndex = 0;
}
VnaSegmentedSweep::VnaSegmentedSweep(VnaSegmentedSweep &other)
{
if (other.isFullyInitialized()) {
_vna = other._vna;
_channel.reset(new VnaChannel(*other._channel.data()));
_channelIndex = other._channelIndex;
}
else {
placeholder.reset(new Vna());
_vna = placeholder.data();
_channel.reset(new VnaChannel());
_channelIndex = 0;
}
}
VnaSegmentedSweep::VnaSegmentedSweep(Vna *vna, VnaChannel *channel, QObject *parent) :
QObject(parent)
{
_vna = vna;
_channel.reset(new VnaChannel(*channel));
_channelIndex = channel->index();
}
VnaSegmentedSweep::VnaSegmentedSweep(Vna *vna, uint index, QObject *parent) :
QObject(parent)
{
_vna = vna;
_channel.reset(new VnaChannel(vna, index));
_channelIndex = index;
}
VnaSegmentedSweep::~VnaSegmentedSweep() {
}
uint VnaSegmentedSweep::points() {
uint numberOfSegments = segments();
uint points = 0;
for (uint i = 1; i <= numberOfSegments; i++) {
points += segment(i).points();
}
return points;
}
double VnaSegmentedSweep::start_Hz() {
return min(frequencies_Hz());
}
double VnaSegmentedSweep::stop_Hz() {
return max(frequencies_Hz());
}
QRowVector VnaSegmentedSweep::frequencies_Hz() {
QString scpi = ":CALC%1:DATA:STIM?\n";
scpi = scpi.arg(_channelIndex);
uint bufferSize = frequencyBufferSize(points());
return _vna->queryVector(scpi, bufferSize);
}
double VnaSegmentedSweep::power_dBm() {
QString scpi = ":SOUR%1:POW?\n";
scpi = scpi.arg(_channelIndex);
return _vna->query(scpi).trimmed().toDouble();
}
void VnaSegmentedSweep::setPower(double power_dBm) {
QString scpi = ":SOUR%1:POW %2\n";
scpi = scpi.arg(_channelIndex).arg(power_dBm);
_vna->write(scpi);
}
double VnaSegmentedSweep::ifBandwidth_Hz() {
QString scpi = QString("SENS%1:BAND?\n").arg(_channelIndex);
return _vna->query(scpi).trimmed().toDouble();
}
void VnaSegmentedSweep::setIfbandwidth(double bandwidth, SiPrefix prefix) {
QString scpi = "SENS%1:BAND %2%3\n";
scpi = scpi.arg(_channelIndex);
scpi = scpi.arg(bandwidth);
scpi = scpi.arg(toString(prefix, Units::Hertz));
_vna->write(scpi);
}
uint VnaSegmentedSweep::segments() {
QString scpi = ":SENS%1:SEGM:COUN?\n";
scpi = scpi.arg(_channelIndex);
return _vna->query(scpi).trimmed().toUInt();
}
void VnaSegmentedSweep::addSegment(uint index) {
QString scpi = ":SENS%1:SEGM%2:ADD\n";
scpi = scpi.arg(_channelIndex);
scpi = scpi.arg(index);
_vna->write(scpi);
}
uint VnaSegmentedSweep::addSegment() {
uint index = segments() + 1;
QString scpi = ":SENS%1:SEGM%2:ADD\n";
scpi = scpi.arg(_channelIndex);
scpi = scpi.arg(index);
_vna->write(scpi);
return index;
}
void VnaSegmentedSweep::deleteSegment(uint index) {
QString scpi = ":SENS%1:SEGM%2:DEL\n";
scpi = scpi.arg(_channelIndex);
scpi = scpi.arg(index);
_vna->write(scpi);
}
void VnaSegmentedSweep::deleteSegments() {
QString scpi = ":SENS%1:SEGM:DEL:ALL\n";
scpi = scpi.arg(_channelIndex);
_vna->write(scpi);
}
VnaSweepSegment &VnaSegmentedSweep::segment(uint index) {
_segment.reset(new VnaSweepSegment(_vna, _channel.data(), index));
return *_segment.data();
}
QVector<uint> VnaSegmentedSweep::sParameterGroup() {
return _channel->linearSweep().sParameterGroup();
}
void VnaSegmentedSweep::setSParameterGroup(QVector<uint> ports) {
_channel->linearSweep().setSParameterGroup(ports);
}
void VnaSegmentedSweep::clearSParameterGroup() {
_channel->linearSweep().clearSParameterGroup();
}
ComplexMatrix3D VnaSegmentedSweep::readSParameterGroup() {
// data size
const uint ports = sParameterGroup().size();
const uint points = this->points();
if (ports == 0 || points == 0) {
return ComplexMatrix3D();
}
// sweep
bool isContinuousSweep = _channel->isContinuousSweep();
_channel->manualSweepOn();
const uint timeout_ms = sweepTime_ms() * _channel->sweepCount();
_channel->startSweep();
_vna->pause(timeout_ms);
// query, return data
QString scpi = ":CALC%1:DATA:SGR? SDAT\n";
scpi = scpi.arg(_channelIndex);
const uint bufferSize = dataBufferSize(ports, points);
ComplexRowVector data = _vna->queryComplexVector(scpi, bufferSize);
_channel->continuousSweepOn(isContinuousSweep);
return toComplexMatrix3D(data, points, ports, ports);
}
uint VnaSegmentedSweep::sweepTime_ms() {
// Is this fixed as of ZNB firmware v2.60 beta,
// ZVA firmware v3.50?
// It appears to be working now...
QString scpi = ":SENS%1:SEGM:SWE:TIME:SUM?\n";
scpi = scpi.arg(_channelIndex);
return ceil(_vna->query(scpi).trimmed().toDouble() * 1000);
// return 600000; // 10 minutes!
}
NetworkData VnaSegmentedSweep::measure(uint port1) {
QVector<uint> ports;
ports << port1;
return measure(ports);
}
NetworkData VnaSegmentedSweep::measure(uint port1, uint port2) {
QVector<uint> ports;
ports << port1 << port2;
return measure(ports);
}
NetworkData VnaSegmentedSweep::measure(uint port1, uint port2, uint port3) {
QVector<uint> ports;
ports << port1 << port2 << port3;
return measure(ports);
}
NetworkData VnaSegmentedSweep::measure(uint port1, uint port2, uint port3, uint port4) {
QVector<uint> ports;
ports << port1 << port2 << port3 << port4;
return measure(ports);
}
NetworkData VnaSegmentedSweep::measure(QVector<uint> ports) {
NetworkData network;
if (ports.size() <= 0)
return network;
if (_channel->isCwSweep() || _channel->isTimeSweep())
return network;
const QRowVector freq_Hz = frequencies_Hz();
if (freq_Hz.isEmpty()) {
return network;
}
setSParameterGroup(ports);
const ComplexMatrix3D s = readSParameterGroup(); // sweeps
if (s.empty()) {
return network;
}
network.setParameter(NetworkParameter::S);
network.setReferenceImpedance(50);
network.setXUnits(Units::Hertz);
network.setData(freq_Hz, s);
return network;
}
void VnaSegmentedSweep::operator=(VnaSegmentedSweep const &other) {
if (other.isFullyInitialized()) {
_vna = other._vna;
_channel.reset(new VnaChannel(*other._channel.data()));
_channelIndex = _channel->index();
}
else {
_vna = placeholder.data();
_channel.reset(new VnaChannel());
_channelIndex = 0;
}
}
//void VnaSegmentedSweep::moveToThread(QThread *thread) {
// QObject::moveToThread(thread);
// if (_channel.isNull() == false)
// _channel->moveToThread(thread);
// if (_segment.isNull() == false)
// _segment->moveToThread(thread);
//}
// Private
bool VnaSegmentedSweep::isFullyInitialized() const {
if (_vna == NULL)
return false;
if (_vna == placeholder.data())
return false;
//else
return true;
}
uint VnaSegmentedSweep::frequencyBufferSize(uint points) {
const uint SIZE_PER_POINT = 20;
return SIZE_PER_POINT * points;
}
uint VnaSegmentedSweep::dataBufferSize(uint ports, uint points) {
const uint HEADER_MAX_SIZE = 11;
const uint SIZE_PER_POINT = 16;
const uint INSURANCE = 20;
return HEADER_MAX_SIZE + SIZE_PER_POINT*points*pow(double(ports), 2.0) + INSURANCE;
}
|
#include<iostream>
#include<queue>
#include<stack>
#include<vector>
#include<stdio.h>
#include<algorithm>
#include<string>
#include<string.h>
#include<sstream>
#include<set>
#include<map>
#include<iomanip>
#define N 505
using namespace std;
int root[N];
int key[N];
int cost[N];
struct edge{
int from, to,len;
edge(){}
edge(int a, int b,int c){from = a; to = b; len =c;}
bool operator <(const edge& e) const{return len<e.len;}
} edges[N*N];
int find (int a) {
if (root[a] < 0)
return a;
else
return root[a] = find(root[a]);
}
void UnionSet (int set1, int set2, int c) {
root[set1] += root[set2];
cost[set1] += cost[set2] + c;
root[set2] = set1;
}
void Union (int a, int b, int c) {
int root1=find(a);
int root2=find(b);
if (root[root1] < root[root2])
UnionSet(root1, root2, c);
else
UnionSet(root2, root1, c);
}
int getRolls(int a, int b){
return min(a-b,10+b-a);
}
int getTotalRolls(int a, int b){
int x,y;
int total = 0;
for(int i=0; i<4; i++){
x = a%10;
y = b%10;
if(x > y)
total += getRolls(x,y);
else
total += getRolls(y,x);
a = a/10;
b = b/10;
}
return total;
}
int main(){
int t,n;
scanf("%d", &t);
for(int i=0; i<t; i++){
scanf("%d", &n);
memset(root, -1, sizeof(root));
memset(cost, 0, sizeof(cost));
memset(key, 0, sizeof(key));
for(int j=0; j<n; j++){
cin>>key[j];
}
int e = 0;
int min = 40;
for(int j=0; j<n; j++){
int temp = getTotalRolls(key[j],0);
if(min>temp)
min = temp;
}
for(int j=0; j<n; j++){
for(int k=j+1; k<n; k++){
int len = getTotalRolls(key[j], key[k]);
edges[e++] = edge(j,k,len);
}
}
if(!e){
printf("%d\n", min);
continue;
}
sort(edges, edges+e);
int from,to,r;
for(int j=0; j<e; j++){
from = edges[j].from;
to = edges[j].to;
if(find(from) != find(to)){
Union(from,to,edges[j].len);
r = find(from);
if(root[r] == -n){
printf("%d\n",cost[r] + min);
break;
}
}
}
}
return 0;
}
|
#ifndef VECTOR_H
#define VECTOR_H
#include <algorithm>
#include <iostream>
#include <memory>
template<typename T, typename A>struct vector_base
{
A allocator;
T* elements;
int length;
int space;
vector_base(){};
vector_base(A& a, int n):
allocator{a}, elements{a.allocate(n)}, length{n}, space{n}{}
~vector_base() {allocator.deallocate(elements,space);}
};
template<typename T, typename A=std::allocator<T>> class vector_:private vector_base<T,A>
{
A allocator;
int length;
T* elements;
int space;
public:
vector_():length{0}, elements{nullptr}, space{0} {}
explicit vector_(int s): length{s}, elements{new T[s]}, space{s}
{
for (int i=0; i<length; i++)
elements[i]=0;
}
vector_(const vector_& a);
vector_& operator=(const vector_& a);
vector_(vector_&& a);
vector_& operator=(vector_&&);
~vector_() {delete[] elements;}
T& at(int n);
const T& at(int n) const;
T &operator[](int n);
const T& operator[](int n) const { return elements[n]; }
vector_(const std::initializer_list<T>& lst);
int size() const { return length; }
int capacity() const;
void reserve(int newalloc);
void resize(int newsize, T val=T());
void push_back(const T& val);
T get(int n) const { return elements[n]; }
void set(int n, T v) { elements[n] = v; }
};
#endif // VECTOR_H
|
#include <vector>
template<typename T, std::size_t N>
class matrix {
public:
static constexpr std::size_t order = N;
using value_type = T;
using iterator = typename std::vector<T>::iterator;
using const_iterator = typename std::vector<T>::const_iterator;
matrix() = default;
matrix(matrix&&) = default;
matrix& operator=(matrix&&) = default;
matrix(matrix const&) = default;
matrix& operator=(matrix const&) = default;
~matrix() = default;
template<typename U>
matrix(matrix_ref<U, N> const&);
template<typename U>
matrix& operator=(matrix_ref<U, N> const&);
template<typename... Exts>
explicit matrix(Exts... etxs);
matrix(matrix_initializer<T, N>);
matrix& operator=(matrix_initialzier<T, N>);
template<typename U>
matrix(std::initializer_list<U>) = delete;
template<typename U>
matrix& operator=(std::initializer_list<U>) = delete;
static constexpr std::size_t order() { return N; }
std::size_t extent(std::size_t n) const { return desc.extents[n]; }
std::size_t size() const { return elems.size(); }
matrix_slice<N> const& descriptor() const { return desc; }
T* data() { return elems.data(); }
T const* data() const { return elems.data(); }
// subscripting
template<typename... Args>
Enable_if<matrix_impl::requesting_element<Args...>(), T&>
operator()(Args... args);
template<typename... Args>
Enable_if<matrix_impl::requesting_element<Args...>(), T const&>
operator()(Args... args) const;
template<typename... Args>
Enable_if<matrix_impl::requesting_slice<Args...>(), matrix_ref<T, N>>
operator()(Args const&... args);
template<typename... Args>
Enable_if<matrix_impl::requesting_slice<Args...>(), matrix_ref<T const, N>>
operator()(Args const&... args) const;
matrix_ref<T, N-1> operator[](std::size_t i) { return row(i); }
matrix_ref<T const, N-1> operator[](std::size_t i) const { return row(i); }
matrix_ref<T, N-1> row(std::size_t n);
matrix_ref<T const, N-1> row(std::size_t n) const;
matrix_ref<T, N-1> col(std::size_t n);
matrix_ref<T const, N-1> col(std::size_t n) const;
// scalar arithmetic operations
template<typename F>
matrix& apply(F f);
template<typename M, typename F>
matrix& apply(M const&, F f);
matrix& operator=(T const& value);
matrix& operator+=(T const& value) {
return apply([&](T& a){ a+=val; });
}
matrix& operator-=(T const& value);
matrix& operator*=(T const& value);
matrix& operator/=(T const& value);
matrix& operator%=(T const& value);
// matrix arithmetic operations
template<typename M>
matrix& operator+=(M const& x);
template<typename M>
matrix& operator-=(M const& x);
private:
matrix_slice<N> desc;
std::vector<T> elems;
};
struct slice {
slice() : start{-1}, length{-1}, stride{1} {}
explicit slice(std::size_t s) : start{s}, length{-1}, stride{1} {}
slice(std::size_t s, std::size_t l, std::size_t n=1)
: start{s} length{l}, stride{n}
{}
std::size_t operator()(std::size_t i) const { return start + i*stride; }
static slice all;
std::size_t start, length, stride;
};
template<std::size_t N>
struct matrix_slice {
matrix_slice() = default;
matrix_slice(std::size_t s, std::initializer_list<std::size_t> exts);
matrix_slice(std::size_t s, std::initializer_list<std::size_t> exts,
std::initializer_List<std::size_t> strs);
template<typename... Dims>
matirx_slice(Dims... dims);
template<typename... Dims,
typename = typename std::enable_if<All(Convertible<Dims, std::size_t>()...)>>
std::size_t operator()(Dims... dims) const;
std::size_t size, start;
std::array<std::size_t, N> extents;
std::array<std::size_t, N> strides;
};
template<typename T, std::size_t N>
class matrix_ref : public matrix_base<T, N> {
public:
matrix_ref(matrix_slice<N> const& s, T *p) : desc{s}, ptr{p} {}
private:
matrix_slice<N> desc;
T* ptr;
};
template<typename T, std::size_t N>
class matrix : public matrix_base<T, N> {
private:
matrix_slice<N> desc;
std::vector<T> elements;
};
template<std::size_t N>
template<typename... Dims>
std::size_t matrix_slice<N>::operator()(Dims... dims) const {
static_assert(sizeof...(Dims) == N, "");
std::size_t args[N] { std::size_t(dims)... };
return inner_product(args, args+N, strides.begin(), std::size_t{0});
}
tempplate<typename T, std::size_t N>
template<typename M, typename F>
Enable_if<matrix_type<M>(), matrix<T, N>&> matrix<T, N>::apply(M& m, F f) {
assert(same_extents(desc, m.descriptor()));
for (auto i=begin(), j=m.begin(); i!=end(); ++i, ++j) {
f(*j, *j);
}
return *this;
}
template<typename T, std::size_t N>
matrix<T, N> operator+(matrix<T, N> const& a, matrix<T, N> const& b) {
matrix<T, N> res = a;
res += b;
return res;
}
template<typename T, typename T2, std::size_t N,
typename RT = matrix<Common_type<Value_type<T>, Value_type<T2>>, N>>
matrix<Rt, N> operator+(matrix<T, N> const& a, matrix<T2, N> const& b) {
matrix<RT, N> res = a;
res += b;
return res;
}
template<typename T, std::size_t N>
matrix<T, N> operator+(matrix_ref<T, N> const& x, T const& n) {
matrix<T, N> res = x;
res += n;
return res;
}
template<typename T, std::size_t N>
template<typename M>
Enable_if<matrix_type<M>(), matrix<T, N>&> matrix<T, N>::operator+=(M const& m) {
static_assert(m.order() == N, "+=: mismatched matrix dimensions");
assert(same_extents(desc, m.descriptor()));
return apply(m, [](T& a, Value_type<M>& b) { a+=b; });
}
template<typename T, std::size_t N>
matrix<T, N> operator+(matrix<T, N> const& m, T const& val) {
matrix<T, N> res = m;
res += val;
return res;
}
template<typename T, std::size_t N>
template<typename F>
matrix<T, N>& matrix<T, N>::apply(F f) {
for (auto& x : elems) f(x);
return *this;
}
template<typename T, std::size_t N>
template<typename... Exts>
matrix<T, N>::matrix(Exts... exts)
: desc{exts},
elems(desc.size())
{}
template<typename T, std::size_t N>
matrix<T, N>::matrix(matrix_initializer<T, N> init) {
matrix_impl::derive_extents(init, desc.extents);
elems.reserve(desc.size);
matrix_impl::insert_flat(init, elems);
//
assert(elems.size() == desc.size());
}
template<typename T, std::size_t N>
template<typename U>
matrix<T, N>::matrix(matrix_ref<U, N> const& x)
: desc{x.desc}, elems{x.begin(), x.end()}
{
static_assert(Convertible<U, T>(), "matrix constructor: incompatible element types");
}
template<typename T, std::size_t N>
template<typename U>
matrix<T, N>& matrix<T, N>::operator=(matrix_ref<U, N> const& x) {
static_assert(Convertible<T, U>(), "matrix =: incompatible element types");
desc = x.desc;
elems.assign(x.begin(), x.end());
return *this;
}
template<typename T, std::size_t N>
using matrix_initializer = typename matrix_impl::matrix_init<T, N>::type;
template<typename T, std::size_t N>
struct matrix_init {
using type = std::initializer_list<typename matrix_init<T, N-1>::type>;
};
template<typename T>
struct matrix_init<T, 1> {
using type = std::initializer_list<T>;
};
template<typename T>
struct matrix_init<T, 0>;
template<std::size_t N, typename List>
std::array<std::size_t, N> derive_extents(List const& list) {
std::array<std::size_t, N> a;
auto f = a.begin();
add_extents<N>(f, list);
return a;
}
template<typename T, std::size_t N>
matrix<T, N>::matrix(matrix_initializer<T, N> init) {
matrix_impl::derive_extents(init, desc, extents);
elems.reserve(desc.size);
matrix_impl::insert_flat(init, elems);
assert(elems.size() == desc.size());
}
template<std::size_t N, typename I, typename List>
Enable_if<(N>1), void> add_extents(I& first, List const& lis) {
assert(check_non_jagged(lis));
*first = lis.size();
add_extents<N-1>(++first, *lis.begin());
}
template<std::size_t N, typename I, typename List>
Enable_if<(N==1), void> add_extents(I& first, List const& lis) {
*first++ = lis.size();
}
template<typename List>
bool check_non_jagged(List const& lis) {
auto i = lis.begin();
for (auto j=i+1; j!=lis.end(); ++j)
if (i->size() != j->size())
return false;
return true;
}
template<typename T, typename Vec>
void insert_flat(std::initializer_list<T> lst, Vec& vec) {
add_list(lst.begin(), lst.end(), vec);
}
template<typename T, typename Vec>
void add_list(std::initializer_list<T> const* first,
std::initializer_list<T> const* last, Vec& vec) {
for (; first!= last; ++first)
add_list(first->begin(), first->end(), vec);
}
template<typename T, typename Vec>
void add_list(T const* first, T const* last, Vec& vec) {
vec.insert(vec.end(), first, last);
}
int main() {
return 0;
}
|
// Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "UnrealAI/UnrealAICharacter.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeUnrealAICharacter() {}
// Cross Module References
UNREALAI_API UClass* Z_Construct_UClass_AUnrealAICharacter_NoRegister();
UNREALAI_API UClass* Z_Construct_UClass_AUnrealAICharacter();
ENGINE_API UClass* Z_Construct_UClass_ACharacter();
UPackage* Z_Construct_UPackage__Script_UnrealAI();
ENGINE_API UClass* Z_Construct_UClass_USphereComponent_NoRegister();
ENGINE_API UClass* Z_Construct_UClass_UCameraComponent_NoRegister();
ENGINE_API UClass* Z_Construct_UClass_USpringArmComponent_NoRegister();
// End Cross Module References
static FName NAME_AUnrealAICharacter_Sprint = FName(TEXT("Sprint"));
void AUnrealAICharacter::Sprint()
{
ProcessEvent(FindFunctionChecked(NAME_AUnrealAICharacter_Sprint),NULL);
}
static FName NAME_AUnrealAICharacter_StopSprinting = FName(TEXT("StopSprinting"));
void AUnrealAICharacter::StopSprinting()
{
ProcessEvent(FindFunctionChecked(NAME_AUnrealAICharacter_StopSprinting),NULL);
}
static FName NAME_AUnrealAICharacter_StopWalking = FName(TEXT("StopWalking"));
void AUnrealAICharacter::StopWalking()
{
ProcessEvent(FindFunctionChecked(NAME_AUnrealAICharacter_StopWalking),NULL);
}
static FName NAME_AUnrealAICharacter_Walk = FName(TEXT("Walk"));
void AUnrealAICharacter::Walk()
{
ProcessEvent(FindFunctionChecked(NAME_AUnrealAICharacter_Walk),NULL);
}
void AUnrealAICharacter::StaticRegisterNativesAUnrealAICharacter()
{
}
struct Z_Construct_UFunction_AUnrealAICharacter_Sprint_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AUnrealAICharacter_Sprint_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "UnrealAICharacter.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AUnrealAICharacter_Sprint_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AUnrealAICharacter, nullptr, "Sprint", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08020800, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AUnrealAICharacter_Sprint_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AUnrealAICharacter_Sprint_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AUnrealAICharacter_Sprint()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AUnrealAICharacter_Sprint_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_AUnrealAICharacter_StopSprinting_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AUnrealAICharacter_StopSprinting_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "UnrealAICharacter.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AUnrealAICharacter_StopSprinting_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AUnrealAICharacter, nullptr, "StopSprinting", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08020800, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AUnrealAICharacter_StopSprinting_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AUnrealAICharacter_StopSprinting_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AUnrealAICharacter_StopSprinting()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AUnrealAICharacter_StopSprinting_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_AUnrealAICharacter_StopWalking_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AUnrealAICharacter_StopWalking_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "UnrealAICharacter.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AUnrealAICharacter_StopWalking_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AUnrealAICharacter, nullptr, "StopWalking", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08020800, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AUnrealAICharacter_StopWalking_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AUnrealAICharacter_StopWalking_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AUnrealAICharacter_StopWalking()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AUnrealAICharacter_StopWalking_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_AUnrealAICharacter_Walk_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AUnrealAICharacter_Walk_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "UnrealAICharacter.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AUnrealAICharacter_Walk_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AUnrealAICharacter, nullptr, "Walk", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08020800, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AUnrealAICharacter_Walk_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AUnrealAICharacter_Walk_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AUnrealAICharacter_Walk()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AUnrealAICharacter_Walk_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_AUnrealAICharacter_NoRegister()
{
return AUnrealAICharacter::StaticClass();
}
struct Z_Construct_UClass_AUnrealAICharacter_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_SphereRadius_MetaData[];
#endif
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_SphereRadius;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BaseLookUpRate_MetaData[];
#endif
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_BaseLookUpRate;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BaseTurnRate_MetaData[];
#endif
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_BaseTurnRate;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_SphereCollider_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_SphereCollider;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_FollowCamera_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_FollowCamera;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_CameraBoom_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_CameraBoom;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_AUnrealAICharacter_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_ACharacter,
(UObject* (*)())Z_Construct_UPackage__Script_UnrealAI,
};
const FClassFunctionLinkInfo Z_Construct_UClass_AUnrealAICharacter_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_AUnrealAICharacter_Sprint, "Sprint" }, // 3004099417
{ &Z_Construct_UFunction_AUnrealAICharacter_StopSprinting, "StopSprinting" }, // 3564643242
{ &Z_Construct_UFunction_AUnrealAICharacter_StopWalking, "StopWalking" }, // 3744168422
{ &Z_Construct_UFunction_AUnrealAICharacter_Walk, "Walk" }, // 3314681149
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AUnrealAICharacter_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Navigation" },
{ "IncludePath", "UnrealAICharacter.h" },
{ "ModuleRelativePath", "UnrealAICharacter.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_SphereRadius_MetaData[] = {
{ "Category", "QueryCollision" },
{ "ModuleRelativePath", "UnrealAICharacter.h" },
};
#endif
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_SphereRadius = { "SphereRadius", nullptr, (EPropertyFlags)0x0010000000000005, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AUnrealAICharacter, SphereRadius), METADATA_PARAMS(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_SphereRadius_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_SphereRadius_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_BaseLookUpRate_MetaData[] = {
{ "Category", "Camera" },
{ "Comment", "/** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */" },
{ "ModuleRelativePath", "UnrealAICharacter.h" },
{ "ToolTip", "Base look up/down rate, in deg/sec. Other scaling may affect final rate." },
};
#endif
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_BaseLookUpRate = { "BaseLookUpRate", nullptr, (EPropertyFlags)0x0010000000020015, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AUnrealAICharacter, BaseLookUpRate), METADATA_PARAMS(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_BaseLookUpRate_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_BaseLookUpRate_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_BaseTurnRate_MetaData[] = {
{ "Category", "Camera" },
{ "Comment", "/** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */" },
{ "ModuleRelativePath", "UnrealAICharacter.h" },
{ "ToolTip", "Base turn rate, in deg/sec. Other scaling may affect final turn rate." },
};
#endif
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_BaseTurnRate = { "BaseTurnRate", nullptr, (EPropertyFlags)0x0010000000020015, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AUnrealAICharacter, BaseTurnRate), METADATA_PARAMS(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_BaseTurnRate_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_BaseTurnRate_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_SphereCollider_MetaData[] = {
{ "AllowPrivateAccess", "true" },
{ "Category", "QueryCollison" },
{ "Comment", "/** Sphere Collision Component */" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "UnrealAICharacter.h" },
{ "ToolTip", "Sphere Collision Component" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_SphereCollider = { "SphereCollider", nullptr, (EPropertyFlags)0x00400000000a001d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AUnrealAICharacter, SphereCollider), Z_Construct_UClass_USphereComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_SphereCollider_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_SphereCollider_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_FollowCamera_MetaData[] = {
{ "AllowPrivateAccess", "true" },
{ "Category", "Camera" },
{ "Comment", "/** Follow camera */" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "UnrealAICharacter.h" },
{ "ToolTip", "Follow camera" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_FollowCamera = { "FollowCamera", nullptr, (EPropertyFlags)0x00400000000a001d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AUnrealAICharacter, FollowCamera), Z_Construct_UClass_UCameraComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_FollowCamera_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_FollowCamera_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_CameraBoom_MetaData[] = {
{ "AllowPrivateAccess", "true" },
{ "Category", "Camera" },
{ "Comment", "/** Camera boom positioning the camera behind the character */" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "UnrealAICharacter.h" },
{ "ToolTip", "Camera boom positioning the camera behind the character" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_CameraBoom = { "CameraBoom", nullptr, (EPropertyFlags)0x00400000000a001d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AUnrealAICharacter, CameraBoom), Z_Construct_UClass_USpringArmComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_CameraBoom_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_CameraBoom_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AUnrealAICharacter_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_SphereRadius,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_BaseLookUpRate,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_BaseTurnRate,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_SphereCollider,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_FollowCamera,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AUnrealAICharacter_Statics::NewProp_CameraBoom,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_AUnrealAICharacter_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<AUnrealAICharacter>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AUnrealAICharacter_Statics::ClassParams = {
&AUnrealAICharacter::StaticClass,
"Game",
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_AUnrealAICharacter_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
UE_ARRAY_COUNT(Z_Construct_UClass_AUnrealAICharacter_Statics::PropPointers),
0,
0x008000A4u,
METADATA_PARAMS(Z_Construct_UClass_AUnrealAICharacter_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_AUnrealAICharacter_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_AUnrealAICharacter()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AUnrealAICharacter_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(AUnrealAICharacter, 43885769);
template<> UNREALAI_API UClass* StaticClass<AUnrealAICharacter>()
{
return AUnrealAICharacter::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_AUnrealAICharacter(Z_Construct_UClass_AUnrealAICharacter, &AUnrealAICharacter::StaticClass, TEXT("/Script/UnrealAI"), TEXT("AUnrealAICharacter"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(AUnrealAICharacter);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
|
#ifndef _CONTROLLER_MANAGER
#define _CONTROLLER_MANAGER
#include <sdl2/SDL.h>
#include <map>
#include <iostream>
#include <glm/glm.hpp>
#define controller_manager controller_manager_t::instance()
struct controller_manager_t {
static controller_manager_t *instance();
void set_keydown(const SDL_Keycode keycode);
void set_keyup(const SDL_Keycode keycode);
bool get_keydown(const SDL_Keycode keycode);
void set_mousedown(const unsigned int);
void set_mouseup(const unsigned int);
bool get_mousedown(const unsigned int);
static controller_manager_t *singleton_instance;
controller_manager_t();
std::map<SDL_Keycode const, bool> keystates;
std::map<int const, bool> mousestates;
glm::vec2 last_cursor;
glm::vec2 cursor;
void set_cursor_position(const int x, const int y);
};
#endif
|
#include"stdio.h"
#include"conio.h"
void main(){
clrscr();
int i, end=10;
printf("*\n");
for(i=0; i<=end; i++){
printf("*");
for(int j=1; j<=i; j++){
if(i==end)
printf("*");
else printf(" ");
}
printf("*\n");
}
getch();
}
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class GreatFairyWar
{
public:
int getSumDps(int pos,int size,vector <int> dps)
{
int sumDps = 0;
for (int i=pos; i<size; ++i) {
sumDps += dps.at(i);
}
return sumDps;
}
int minHP(vector <int> dps, vector <int> hp)
{
int sumHP = 0;
int size = (int)dps.size();
for (int i=0; i<size; ++i) {
sumHP += hp.at(i) * getSumDps(i,size,dps);
}
return sumHP;
}
};
|
#include <iostream>
using namespace std;
int dp[501][501];
int sp[501][501];
int nums[501];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int tc;
cin >> tc;
while (tc--)
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> sp[i][i];
}
for (int gap = 1; gap <= n - 1; gap++)
{
for (int i = 1; i <= n - gap; i++)
{
int j = i + gap;
int _min = 987654321;
sp[i][j] = sp[i][j - 1] + sp[j][j];
for (int k = i; k < j; k++)
{
int num = dp[i][k] + dp[k + 1][j] + sp[i][j];
if (num < _min)
{
_min = num;
}
}
dp[i][j] = _min;
}
}
cout << dp[1][n] << '\n';
}
return 0;
}
|
/****************************************************************************
** Copyright (C) 2017 Olaf Japp
**
** This file is part of FlatSiteBuilder.
**
** FlatSiteBuilder is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** FlatSiteBuilder is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/
#include "elementeditor.h"
#include "widgetmimedata.h"
#include "flatbutton.h"
#include "moduldialog.h"
#include "mainwindow.h"
#include "roweditor.h"
#include "sectioneditor.h"
#include "plugins.h"
#include "pageeditor.h"
#include "contenteditor.h"
#include <QMimeData>
#include <QDrag>
#include <QMouseEvent>
#include <QHBoxLayout>
#include <QLabel>
#include <QTest>
#include <QParallelAnimationGroup>
#include <QPropertyAnimation>
#include <QXmlStreamWriter>
ElementEditor::ElementEditor()
{
setAutoFillBackground(true);
setMinimumWidth(120);
setMinimumHeight(50);
setMaximumHeight(50);
m_zoom = false;
m_mode = Mode::Empty;
m_normalColor = QColor(palette().base().color().name()).lighter().name();
m_enabledColor = palette().base().color().name();
m_dropColor = QColor(palette().base().color().name()).lighter().lighter().name();
setColor(m_normalColor);
m_link = new Hyperlink("(+) Insert Module");
m_editButton = new FlatButton(":/images/edit_normal.png", ":/images/edit_hover.png");
m_copyButton = new FlatButton(":/images/copy_normal.png", ":/images/copy_hover.png");
m_closeButton = new FlatButton(":/images/trash_normal.png", ":/images/trash_hover.png");
m_editButton->setVisible(false);
m_copyButton->setVisible(false);
m_closeButton->setVisible(false);
m_editButton->setToolTip("Edit Element");
m_closeButton->setToolTip("Delete Element");
m_copyButton->setToolTip("Copy Element");
m_text = new QLabel("Text");
m_text->setVisible(false);
QHBoxLayout *layout= new QHBoxLayout();
layout->addWidget(m_link, 0, Qt::AlignCenter);
layout->addWidget(m_editButton);
layout->addWidget(m_copyButton);
layout->addWidget(m_text, 1, Qt::AlignCenter);
layout->addWidget(m_closeButton);
setLayout(layout);
connect(m_link, SIGNAL(clicked()), this, SLOT(enable()));
connect(m_editButton, SIGNAL(clicked()), this, SLOT(edit()));
connect(m_copyButton, SIGNAL(clicked()), this, SLOT(copy()));
connect(m_closeButton, SIGNAL(clicked()), this, SLOT(close()));
}
void ElementEditor::load(QXmlStreamReader *stream)
{
m_type = stream->name() + "Editor";
QString label = stream->attributes().value("adminlabel").toString();
if(label.isEmpty())
m_text->setText(stream->name().toString());
else
m_text->setText(label);
ElementEditorInterface * editor = Plugins::getElementPlugin(m_type);
if(editor)
m_content = editor->load(stream);
}
void ElementEditor::setContent(QString content)
{
m_content = content;
QXmlStreamReader stream(content);
stream.readNextStartElement();
m_type = stream.name() + "Editor";
QString label = stream.attributes().value("adminlabel").toString();
if(label.isEmpty())
m_text->setText(stream.name().toString());
else
m_text->setText(label);
}
void ElementEditor::save(QXmlStreamWriter *stream)
{
if(m_mode == Mode::Enabled)
{
stream->device()->write(m_content.toUtf8());
}
}
ElementEditor *ElementEditor::clone()
{
ElementEditor *nee = new ElementEditor();
nee->setMode(m_mode);
nee->setText(m_text->text());
nee->setContent(m_content);
return nee;
}
void ElementEditor::setColor(QString name)
{
QPalette pal = palette();
pal.setColor(QPalette::Background, QColor(name));
setPalette(pal);
}
void ElementEditor::mousePressEvent(QMouseEvent *event)
{
if(m_mode != Mode::Enabled || event->button() != Qt::LeftButton)
return;
if(parentWidget()->layout()->count() == 1)
{
emit elementDragged();
}
WidgetMimeData *mimeData = new WidgetMimeData();
mimeData->setData(this);
QPixmap pixmap(this->size());
render(&pixmap);
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setHotSpot(event->pos());
drag->setPixmap(pixmap);
this->hide();
if(drag->exec(Qt::MoveAction) == Qt::IgnoreAction)
this->show();
}
void ElementEditor::dropped()
{
//seems to be a bug that after dropping the item the bgcolor changes
setColor(m_enabledColor);
}
void ElementEditor::setMode(Mode mode)
{
m_mode = mode;
if(mode == Mode::Empty)
{
m_link->setVisible(true);
m_editButton->setVisible(false);
m_copyButton->setVisible(false);
m_closeButton->setVisible(false);
m_text->setVisible(false);
setColor(m_normalColor);
}
else if(mode == Mode::Enabled)
{
m_link->setVisible(false);
m_editButton->setVisible(true);
m_copyButton->setVisible(true);
m_closeButton->setVisible(true);
m_text->setVisible(true);
setColor(m_enabledColor);
}
else if(mode == Mode::Dropzone)
{
m_link->setVisible(false);
m_editButton->setVisible(false);
m_copyButton->setVisible(false);
m_closeButton->setVisible(false);
m_text->setVisible(true);
m_text->setText("Drop Here");
setColor(m_dropColor);
}
}
void ElementEditor::enable()
{
ModulDialog *dlg = new ModulDialog();
dlg->exec();
if(dlg->result().isEmpty())
return;
ElementEditorInterface *editor = Plugins::getElementPlugin(dlg->result());
m_text->setText(editor->displayName());
m_content = "<" + editor->tagName() + "/>";
m_type = editor->className();
setMode(Mode::Enabled);
emit elementEnabled();
edit();
}
void ElementEditor::close()
{
parentWidget()->layout()->removeWidget(this);
this->deleteLater();
ContentEditor *ce = getContentEditor();
if(ce)
ce->editChanged("Delete Element");
}
void ElementEditor::edit()
{
ContentEditor *ce = getContentEditor();
if(ce)
ce->elementEdit(this);;
}
SectionEditor *ElementEditor::getSectionEditor()
{
SectionEditor *se = dynamic_cast<SectionEditor*>(parentWidget());
if(se)
return se;
ColumnEditor *ce = dynamic_cast<ColumnEditor*>(parentWidget());
if(ce)
{
RowEditor *re = dynamic_cast<RowEditor*>(ce->parentWidget());
if(re)
{
SectionEditor *se = dynamic_cast<SectionEditor*>(re->parentWidget());
if(se)
{
return se;
}
}
}
return NULL;
}
ContentEditor *ElementEditor::getContentEditor()
{
SectionEditor *se = getSectionEditor();
if(se)
{
PageEditor *pe = dynamic_cast<PageEditor*>(se->parentWidget());
if(pe)
{
QWidget *sa = dynamic_cast<QWidget*>(pe->parentWidget());
if(sa)
{
QWidget *vp = dynamic_cast<QWidget*>(sa->parentWidget());
if(vp)
{
ContentEditor *cee = dynamic_cast<ContentEditor*>(vp->parentWidget());
if(cee)
return cee;
}
}
}
}
return NULL;
}
void ElementEditor::copy()
{
emit elementCopied(this);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2012 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 CANVAS3D_SUPPORT
#include "modules/dom/src/canvas/webglconstants.h"
#include "modules/libvega/src/canvas/canvaswebglprogram.h"
#include "modules/libvega/src/canvas/canvaswebglshader.h"
#include "modules/webgl/src/wgl_validator.h"
CanvasWebGLProgram::CanvasWebGLProgram() : m_program(NULL), m_shaderVariables(NULL), m_linked(FALSE), m_linkId(0)
{
}
CanvasWebGLProgram::~CanvasWebGLProgram()
{
VEGARefCount::DecRef(m_program);
while (m_attachedShaders.GetCount() > 0)
{
CanvasWebGLShader* shader = m_attachedShaders.Remove(0);
shader->removeRef();
}
OP_DELETE(m_shaderVariables);
}
OP_STATUS CanvasWebGLProgram::Construct()
{
return g_vegaGlobals.vega3dDevice->createShaderProgram(&m_program, VEGA3dShaderProgram::SHADER_CUSTOM, VEGA3dShaderProgram::WRAP_CLAMP_CLAMP);
}
BOOL CanvasWebGLProgram::hasShader(CanvasWebGLShader* shader)
{
return m_attachedShaders.Find(shader) >= 0;
}
OP_STATUS CanvasWebGLProgram::addShader(CanvasWebGLShader* shader)
{
RETURN_IF_ERROR(m_attachedShaders.Add(shader));
shader->addRef();
return OpStatus::OK;
}
OP_STATUS CanvasWebGLProgram::removeShader(CanvasWebGLShader* shader)
{
RETURN_IF_ERROR(m_attachedShaders.RemoveByItem(shader));
shader->removeRef();
return OpStatus::OK;
}
unsigned int CanvasWebGLProgram::getNumAttachedShaders()
{
return m_attachedShaders.GetCount();
}
ES_Object* CanvasWebGLProgram::getAttachedShaderESObject(unsigned int i)
{
return m_attachedShaders.Get(i)->getESObject();
}
OP_STATUS CanvasWebGLProgram::link(unsigned int extensions_enabled, unsigned int max_vertex_attribs)
{
OP_NEW_DBG("CanvasWebGLProgram::link()", "webgl.shaders");
m_linked = FALSE;
++m_linkId;
int shader_index;
RETURN_IF_ERROR(validateLink(extensions_enabled));
RETURN_IF_ERROR(setUpActiveAttribBindings(max_vertex_attribs));
OP_STATUS status = OpStatus::OK;
for (shader_index = 0;
shader_index < (int)m_attachedShaders.GetCount();
++shader_index)
{
VEGA3dShader *shader = m_attachedShaders.Get(shader_index)->getShader();
status = shader ? m_program->addShader(shader) : OpStatus::ERR;
if (OpStatus::IsError(status))
break;
}
if (OpStatus::IsSuccess(status))
{
status = m_program->link(&m_info_log);
#ifdef _DEBUG
if (!m_info_log.IsEmpty())
OP_DBG((UNI_L("\nMessages from shader linking\n============================\n%s\n"),
m_info_log.CStr()));
#endif // _DEBUG
}
// Only try to remove the shaders that were actually added above
while (shader_index-- > 0)
{
VEGA3dShader *shader = m_attachedShaders.Get(shader_index)->getShader();
OP_ASSERT(shader);
m_program->removeShader(shader);
}
RETURN_IF_ERROR(status);
RETURN_IF_ERROR(setUpSamplerBindings());
m_linked = TRUE;
return status;
}
OP_STATUS CanvasWebGLProgram::setUpActiveAttribBindings(unsigned int max_vertex_attribs)
{
OpINT32Set bound_locations;
m_active_attrib_bindings.clear();
OpString8 uni_conv;
if (!m_shaderVariables)
{
OP_ASSERT(!"Did a shader fail to compile? If so, we should have bailed out earlier.");
return OpStatus::ERR;
}
/* Pass 1: Assign locations to attributes that have been bound via
bindAttribLocation(). */
for (WGL_ShaderVariable *attrib = m_shaderVariables->attributes.First();
attrib;
attrib = attrib->Suc())
{
unsigned location;
uni_conv.Set(attrib->name);
if (m_next_attrib_bindings.get(uni_conv.CStr(), location))
{
OP_ASSERT(location < max_vertex_attribs);
// Keep track of used locations
bound_locations.Add(static_cast<INT32>(location));
RETURN_IF_ERROR(m_active_attrib_bindings.set(uni_conv.CStr(), location));
}
}
/* Pass 2: Assign unused locations to attributes with no specified binding. */
unsigned unbound_location = 0;
for (WGL_ShaderVariable *attrib = m_shaderVariables->attributes.First();
attrib;
attrib = attrib->Suc())
{
uni_conv.Set(attrib->name);
if (!m_next_attrib_bindings.contains(uni_conv.CStr()))
{
// Find free location
while (bound_locations.Contains(static_cast<INT32>(unbound_location)))
++unbound_location;
if (unbound_location >= max_vertex_attribs)
return OpStatus::ERR;
RETURN_IF_ERROR(m_active_attrib_bindings.set(uni_conv.CStr(), unbound_location));
++unbound_location;
}
}
/* In the GL attribute model, we need to go out to the backend and bind
attributes to their locations prior to linking (which is when attribute
bindings become effectual) */
if (g_vegaGlobals.vega3dDevice->getAttribModel() == VEGA3dDevice::GLAttribModel)
{
const char *name;
unsigned location;
StringHash<unsigned>::Iterator iter = m_active_attrib_bindings.get_iterator();
while (iter.get_next(name, location))
RETURN_IF_ERROR(getProgram()->setInputLocation(name, location));
}
#ifdef _DEBUG
{
OP_NEW_DBG("CanvasWebGLProgram::link()", "webgl.attributes");
const char *name;
unsigned binding;
OP_DBG(("Attribute bindings assigned via bindAttribLocation():"));
StringHash<unsigned>::Iterator bound_iter = m_next_attrib_bindings.get_iterator();
while (bound_iter.get_next(name, binding))
OP_DBG(("%s : %u", name, binding));
OP_DBG(("Attribute bindings put into effect:"));
StringHash<unsigned>::Iterator active_iter = m_active_attrib_bindings.get_iterator();
while (active_iter.get_next(name, binding))
OP_DBG(("%s : %u", name, binding));
}
#endif // _DEBUG
return OpStatus::OK;
}
OP_STATUS CanvasWebGLProgram::setUpSamplerBindings()
{
/* Populate the m_sampler_values hash table, which maps sampler
ID's to sampler values (WebGL texture unit indices). This is used to
postpone the setting of the actual back-end uniform samplers and/or
texture units until draw time, which makes the implementation
simpler for back-ends where samplers are hardwired to particular
texture units, such as D3D. */
/* Remove any mappings from a previous link.
TODO: Does this correctly handle all combinations of
successful/failed links and installed/not installed programs? */
m_sampler_values.RemoveAll();
for (WGL_ShaderVariable *uniform = m_shaderVariables->uniforms.First();
uniform;
uniform = uniform->Suc())
{
if (uniform->type->GetType() == WGL_Type::Sampler)
{
// TODO: Failing below means we might leave the instance in a
// "half-initialized" state w.r.t. m_sampler_values. Might be
// able to clean up this method a bit later.
OpString8 name_8;
RETURN_IF_ERROR(name_8.Set(uniform->name));
// All samplers are initially bound to texture unit 0
UINT32 loc = getProgram()->getConstantLocation(name_8);
if (static_cast<WGL_SamplerType*>(uniform->type)->type == WGL_SamplerType::SamplerCube)
loc |= IS_SAMPLER_CUBE_BIT;
RETURN_IF_ERROR(m_sampler_values.Add(loc, 0));
}
}
return OpStatus::OK;
}
void CanvasWebGLProgram::destroyInternal()
{
VEGARefCount::DecRef(m_program);
m_program = NULL;
while (m_attachedShaders.GetCount() > 0)
{
CanvasWebGLShader* shader = m_attachedShaders.Remove(0);
shader->removeRef();
}
}
BOOL CanvasWebGLProgram::hasVertexShader() const
{
for (unsigned int i = 0; i < m_attachedShaders.GetCount(); ++i)
if (!m_attachedShaders.Get(i)->isFragmentShader())
return TRUE;
return FALSE;
}
BOOL CanvasWebGLProgram::hasFragmentShader() const
{
for (unsigned int i = 0; i < m_attachedShaders.GetCount(); ++i)
if (m_attachedShaders.Get(i)->isFragmentShader())
return TRUE;
return FALSE;
}
OP_STATUS CanvasWebGLProgram::validateLink(unsigned int extensions_enabled)
{
OP_ASSERT(!m_linked);
OP_DELETE(m_shaderVariables);
m_shaderVariables = NULL;
unsigned count = m_attachedShaders.GetCount();
if (count == 0)
return OpStatus::OK;
WGL_Validator::Configuration config;
config.console_logging = TRUE;
/* The info log is cleared regardless. */
m_info_log.Set("");
config.output_log = &m_info_log;
config.support_oes_derivatives = (extensions_enabled & WEBGL_EXT_OES_STANDARD_DERIVATIVES) != 0;
BOOL succeeded = TRUE;
for (unsigned i = 0; i < count; i++)
{
CanvasWebGLShader* shader = m_attachedShaders.Get(i);
if (!shader->isCompiled())
return OpStatus::ERR;
WGL_ShaderVariables *shader_variables = shader->getShaderVariables();
if (!shader_variables)
{
OP_ASSERT(!"Successfully compiled shaders should always have a set of shader variables");
continue;
}
if (!m_shaderVariables)
RETURN_IF_LEAVE(m_shaderVariables = WGL_ShaderVariables::MakeL(shader_variables));
else
{
WGL_ShaderVariables *extra_vars = shader_variables;
OP_BOOLEAN result = OpBoolean::IS_TRUE;
#if 0
/* Disabled until local tests verify that it is ready. */
RETURN_IF_LEAVE(result = WGL_Validator::ValidateLinkageL(config, m_shaderVariables, extra_vars));
#endif
succeeded = succeeded && (result == OpBoolean::IS_TRUE);
RETURN_IF_LEAVE(m_shaderVariables->MergeWithL(extra_vars));
}
}
return (succeeded ? OpStatus::OK : OpStatus::ERR);
}
OP_BOOLEAN CanvasWebGLProgram::lookupShaderAttribute(const char* name, VEGA3dShaderProgram::ConstantType &type, unsigned int &length, const uni_char** original_name)
{
if (m_shaderVariables)
return m_shaderVariables->LookupAttribute(name, type, length, original_name);
else
return OpStatus::ERR;
}
OP_BOOLEAN CanvasWebGLProgram::lookupShaderUniform(const char* name, VEGA3dShaderProgram::ConstantType &type, unsigned int &length, BOOL &is_array, const uni_char** original_name)
{
if (!m_shaderVariables)
return OpStatus::ERR;
return m_shaderVariables->LookupUniform(name, type, length, is_array, original_name);
}
#endif // CANVAS3D_SUPPORT
|
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define cn(x) cout << #x << " = " << x << endl;
void print(unordered_set<int> & set){
cout << set.size() << " ";
for(auto x : set){
cout << x+1 << " ";
}
cout << endl;
}
void print(vector<bool> & v){
for(bool x : v) cout << x << " ";
cout << endl;
}
void print(unordered_map<int, int> & m){
cout << "print map:" << endl;
for(auto p : m){
cout << p.first << " " << p.second << endl;
}
}
int main(){
int n;
cin >> n;
vector<int> v(n);
for(int i = 0; i < n; i++)
cin >> v[i];
vector<int> w(v);
sort(w.begin(), w.end());
unordered_map<int, int> map;
for(int i = 0; i < n; i++){
map[w[i]] = i;
}
vector<bool> used(n,false);
unordered_set<int> set;
vector<unordered_set<int> > ans;
int count = 0;
for(int i = 0; i < n; i++){
if(used[i]) continue;
set.clear();
set.insert(i);
used[i] = true;
int next = map[v[i]];
while(true){
used[next] = true;
if(set.find(next)!=set.end()){
ans.push_back(set);
break;
}else{
set.insert(next);
}
int vi = v[next];
next = map[vi];
}
}
cout << ans.size() << endl;
for(auto x : ans){
print(x);
}
return 0;
}
|
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <algorithm>
#include <memory.h>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <string>
#include <string.h>
#include <vector>
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const ld PI = acos(-1.);
using namespace std;
int main() {
int t;
int n;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
if (n & 1) {
puts("NIE");
continue;
}
int turn = 0;
int last = -1;
while (!(n & 1)) {
n >>= 1;
last = n;
turn ^= 1;
}
if (n == last) {
puts(turn == 0 ? "NIE" : "TAK");
} else {
puts(turn == 1 ? "NIE" : "TAK");
}
}
return 0;
}
|
// To find the lowest common ancestor of a binary serach tree
node * lca(node * root, int v1, int v2) {
if (root == NULL || root->data == v1 || root->data == v2)
return root;
node * left = lca(root->left, v1, v2);
node * right = lca(root->right, v1, v2);
if (left != NULL && right != NULL)
return root;
if (left != NULL)
return left;
return right;
}
|
#include <iostream>
#include <stdexcept>
#include "am_pm_clock.h"
/*
* Default constructor - initial time should be midnight
*/
am_pm_clock::am_pm_clock():
hours(12),minutes(0),seconds(0),am(true){}
/*
* Constructor - sets fields to the given argument values
*/
am_pm_clock::am_pm_clock(unsigned int hrs, unsigned int mins,
unsigned int secs, bool am_val):
hours(hrs),minutes(mins),seconds(secs),am(am_val){}
/*
* Copy constructor
*/
am_pm_clock::am_pm_clock(const am_pm_clock &clock){
hours=clock.hours;
minutes=clock.minutes;
seconds=clock.seconds;
am=clock.am;
}
/*
* Assignment operator
*/
am_pm_clock& am_pm_clock::operator=(const am_pm_clock& clock){
if(this!=&clock){
hours=clock.hours;
minutes=clock.minutes;
seconds=clock.seconds;
am=clock.am;
}return *this;
}
/*
* Toggles the am/pm value for the clock
*/
void am_pm_clock::toggle_am_pm(){
if(am)
am=false;
else
am=true;
}
/*
* Resets the time to midnight
*/
void am_pm_clock::reset(){
am=true;hours=12;minutes=0;seconds=0;
}
/*
* Advances the time of the clock by one second
*/
void am_pm_clock::advance_one_sec(){
if(seconds<59){
seconds++;
}else if(seconds==59){
if(minutes<59){
seconds=0;
minutes++;
}else if(minutes==59){
minutes=0;
seconds=0;
if(hours==11){
toggle_am_pm();
hours++;
}else if(hours==12){
hours=1;
}else{
hours++;
}
}
}
}
/*
* Advances the time of the clock by n seconds
*/
void am_pm_clock::advance_n_secs(unsigned int n){
for(unsigned int i=0;i<n;i++){
advance_one_sec();
}
}
/*
* Getter for hours field
*/
unsigned int am_pm_clock::get_hours() const{
return hours;
}
/*
* Setter for hours field; throws an invalid_argument exception
* if hrs is not a legal hours value
*/
void am_pm_clock::set_hours(unsigned int hrs){
if(1<=hrs && hrs<=12){
hours=hrs;
}else{
throw std::invalid_argument("not a legal hours value");
}
}
/*
* Getter for minutes field
*/
unsigned int am_pm_clock::get_minutes() const{
return minutes;
}
/*
* Setter for minutes field; throws an invalid_argument exception
* if mins is not a legal minutes value
*/
void am_pm_clock::set_minutes(unsigned int mins){
if(0<=mins && mins<=59){
minutes=mins;
}else{
throw std::invalid_argument("not a legal minutes value");
}
}
/*
* Getter for seconds field
*/
unsigned int am_pm_clock::get_seconds() const{
return seconds;
}
/*
* Setter for seconds field; throws an invalid_argument exception
* if secs is not a legal seconds value
*/
void am_pm_clock::set_seconds(unsigned int secs){
if(0<=secs && secs<=59){
seconds=secs;
}else{
throw std::invalid_argument("not a legal seconds value");
}
}
/*
* Getter for am field
*/
bool am_pm_clock::is_am() const{
return am;
}
/*
* Setter for am field
*/
void am_pm_clock::set_am(bool am_val){
am=am_val;
}
/*
* Print function - helper for output operator
*/
/*void print(std::ostream& out) const { ----i put it in the comments----
char buff[11];
std::sprintf(buff, "%02d:%02d:%02d%cm", hours, minutes, seconds,
( am ? 'a' : 'p' ));
out << buff;
}
*/
/*this function works if it's in the main cpp file, to display time
*
* void display(const am_pm_clock& mine){
std::cout<<mine.get_hours()<<":"<<mine.get_minutes()<<":"<<mine.get_seconds()<<" "<<
(mine.is_am() ? "am" : "pm")<<"\n";
}
*/
/*
* Destructor
*/
am_pm_clock::~am_pm_clock(){}
|
namespace wrapper {
struct Base {};
struct Derived : public Base {};
void Fun(Base* pObj) {
// compare the two type_info objects corresponding
// to the type of *pObj and Derived
if (typeid(*pObj) == typeid(Derived)) {
// ... aha, pObj actually points to a Derived object
}
}
class TypeInfo {
public:
// ctors/dtors
TypeInfo();
TypeInfo(const std::type_info&);
TypeInfo(const TypeInfo&);
TypeInfo& operator=(const TypeInfo&);
// compatibility functions
bool before(const TypeInfo&) const;
const char* name() const;
private:
const std::type_info* pInfo_;
};
// comparison operators
bool operator==(const TypeInfo&, const TypeInfo&);
bool operator!=(const TypeInfo&, const TypeInfo&);
bool operator<(const TypeInfo&, const TypeInfo&);
bool operator<=(const TypeInfo&, const TypeInfo&);
bool operator>(const TypeInfo&, const TypeInfo&);
bool operator>=(const TypeInfo&, const TypeInfo&);
void FunWithWrapper(Base* pObj) {
TypeInfo info = typeid(Derived);
if (typeid(*pObj) == info) {
// ... pBase actually points to a Derived object
}
}
}
|
#ifdef _DEBUG
#pragma comment(lib, "opencv_world440d.lib")
#pragma comment(lib, "jsoncppd.lib")
#else
#pragma comment(lib, "opencv_world440.lib")
#pragma comment(lib, "jsoncpp.lib")
#endif
#include <direct.h>
#include <io.h>
#include <json/json.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
#define MAX_SIDES_OF_POLY (30)
#define MAX_SHIELDED_AREA_NUM (10)
Mat srcImg;
Mat tmpImg;
std::string winName;
int caliNum = 0;
typedef struct myPoint_tag {
int x;
int y;
} myPoint_t;
typedef struct myLine_tag {
myPoint_t start;
myPoint_t end;
} myLine_t;
typedef struct myPoly_tag {
int ptNum;
myPoint_t point[MAX_SIDES_OF_POLY];
} myPoly_t;
typedef struct cali_param_tag {
myLine_t verticalLine[3];
myLine_t horizontalLine;
int verLine;
int horLine;
myPoly_t detectArea;
int extAreaNum;
myPoly_t shieldedArea[MAX_SHIELDED_AREA_NUM];
} cali_param_t;
int listFiles(std::string &dir, std::string &file) {
using namespace std;
dir.append("\\*");
intptr_t handle;
struct _finddata_t findData;
memset(&findData, 0, sizeof(struct _finddata_t));
handle = _findfirst(dir.c_str(), &findData); // 查找目录中的第一个文件
if (handle == -1) {
cout << "Failed to find first file!\n";
return -1;
}
int ret = 0;
do {
if (strcmp(findData.name, ".") == 0 ||
strcmp(findData.name, "..") == 0) { // 是否是子目录并且不为"."或".."
continue;
} else if (findData.attrib & _A_SUBDIR) {
string newDir = dir;
newDir = newDir + "\\" + findData.name;
listFiles(newDir, file);
} else {
if (findData.name == file) {
return 0;
}
}
} while (_findnext(handle, &findData) == 0); // 查找目录中的下一个文件
_findclose(handle); // 关闭搜索句柄
return -1;
}
int getLabelFile(std::string &vPath, std::string &labelFile) {
size_t pos = vPath.rfind("\\");
std::string path;
if (pos != std::string::npos) {
path = vPath.substr(0, pos);
}
labelFile = vPath.substr(pos + 1) + ".label.json";
if (0 != listFiles(path, labelFile)) {
return -1;
}
return 0;
}
void onMouse4Line(int event, int x, int y, int flags, void *privData) {
cali_param_t *cali = (cali_param_t *)privData;
static Point prePt = {-1, -1};
static Point curPt = {-1, -1};
char coordinate[12] = {0};
if (EVENT_LBUTTONDOWN == event) {
srcImg.copyTo(tmpImg);
prePt = Point(x, y);
snprintf(coordinate, 12, "(%d, %d)", x, y);
circle(tmpImg, prePt, 3, Scalar(255, 0, 0), FILLED, LINE_AA, 0);
std::string strCoordinate = coordinate;
putText(tmpImg, strCoordinate, prePt, FONT_HERSHEY_SIMPLEX, 0.5,
Scalar(0, 0, 255), 2);
imshow(winName, tmpImg);
tmpImg.copyTo(srcImg);
} else if (EVENT_MOUSEMOVE == event && (flags & EVENT_FLAG_LBUTTON)) {
srcImg.copyTo(tmpImg);
curPt = Point(x, y);
line(tmpImg, prePt, curPt, Scalar(255, 0, 0), 3, LINE_AA, 0);
imshow(winName, tmpImg);
} else if (EVENT_LBUTTONUP == event) {
srcImg.copyTo(tmpImg);
curPt = Point(x, y);
snprintf(coordinate, 12, "(%d, %d)", x, y);
circle(tmpImg, curPt, 3, Scalar(255, 0, 0), FILLED, LINE_AA, 0);
std::string strCoordinate = coordinate;
putText(tmpImg, strCoordinate, curPt, FONT_HERSHEY_SIMPLEX, 0.5,
Scalar(0, 0, 255), 2);
line(tmpImg, prePt, curPt, Scalar(255, 0, 0), 3, LINE_AA, 0);
imshow(winName, tmpImg);
tmpImg.copyTo(srcImg);
switch (caliNum) {
case 0:
cali->verticalLine[0].start.x = prePt.x;
cali->verticalLine[0].start.y = prePt.y;
cali->verticalLine[0].end.x = curPt.x;
cali->verticalLine[0].end.y = curPt.y;
break;
case 1:
cali->verticalLine[1].start.x = prePt.x;
cali->verticalLine[1].start.y = prePt.y;
cali->verticalLine[1].end.x = curPt.x;
cali->verticalLine[1].end.y = curPt.y;
break;
case 2:
cali->verticalLine[2].start.x = prePt.x;
cali->verticalLine[2].start.y = prePt.y;
cali->verticalLine[2].end.x = curPt.x;
cali->verticalLine[2].end.y = curPt.y;
break;
case 3:
cali->horizontalLine.start.x = prePt.x;
cali->horizontalLine.start.y = prePt.y;
cali->horizontalLine.end.x = curPt.x;
cali->horizontalLine.end.y = curPt.y;
break;
default:
break;
}
caliNum++;
}
}
void onMouseDetectArea(int event, int x, int y, int flags, void *privData) {
cali_param_t *cali = (cali_param_t *)privData;
static Point firstPt = {-1, -1};
static bool flag = false;
static Point prePt = {-1, -1};
static Point curPt = {-1, -1};
char coordinate[12] = {0};
if (EVENT_LBUTTONDOWN == event) {
srcImg.copyTo(tmpImg);
if (false == flag) {
firstPt = Point(x, y);
prePt = Point(x, y);
circle(tmpImg, prePt, 3, Scalar(255, 0, 0), FILLED, LINE_AA, 0);
flag = true;
} else {
curPt = Point(x, y);
circle(tmpImg, curPt, 3, Scalar(255, 0, 0), FILLED, LINE_AA, 0);
line(tmpImg, prePt, curPt, Scalar(255, 0, 0), 3, LINE_AA, 0);
prePt = Point(x, y);
}
snprintf(coordinate, 12, "(%d, %d)", x, y);
std::string strCoordinate = coordinate;
putText(tmpImg, strCoordinate, prePt, FONT_HERSHEY_SIMPLEX, 0.5,
Scalar(0, 0, 255), 2);
imshow(winName, tmpImg);
tmpImg.copyTo(srcImg);
// 填充标定结构体
cali->detectArea.point[cali->detectArea.ptNum].x = x;
cali->detectArea.point[cali->detectArea.ptNum].y = y;
cali->detectArea.ptNum++;
} else if (EVENT_RBUTTONDOWN == event) {
srcImg.copyTo(tmpImg);
line(tmpImg, prePt, firstPt, Scalar(255, 0, 0), 3, LINE_AA, 0);
imshow(winName, tmpImg);
tmpImg.copyTo(srcImg);
}
}
void onMouseExtArea(int event, int x, int y, int flags, void *privData) {
cali_param_t *cali = (cali_param_t *)privData;
static Point firstPt = {-1, -1};
static bool flag = false;
static Point prePt = {-1, -1};
static Point curPt = {-1, -1};
char coordinate[12] = {0};
if (EVENT_LBUTTONDOWN == event) {
srcImg.copyTo(tmpImg);
if (false == flag) {
firstPt = Point(x, y);
prePt = Point(x, y);
circle(tmpImg, prePt, 3, Scalar(255, 0, 0), FILLED, LINE_AA, 0);
flag = true;
} else {
curPt = Point(x, y);
circle(tmpImg, curPt, 3, Scalar(255, 0, 0), FILLED, LINE_AA, 0);
line(tmpImg, prePt, curPt, Scalar(255, 0, 0), 3, LINE_AA, 0);
prePt = Point(x, y);
}
snprintf(coordinate, 12, "(%d, %d)", x, y);
std::string strCoordinate = coordinate;
putText(tmpImg, strCoordinate, prePt, FONT_HERSHEY_SIMPLEX, 0.5,
Scalar(0, 0, 255), 2);
imshow(winName, tmpImg);
tmpImg.copyTo(srcImg);
// 填充标定结构体
cali->shieldedArea[cali->extAreaNum]
.point[cali->shieldedArea[cali->extAreaNum].ptNum]
.x = x;
cali->shieldedArea[cali->extAreaNum]
.point[cali->shieldedArea[cali->extAreaNum].ptNum]
.y = y;
cali->shieldedArea[cali->extAreaNum].ptNum++;
} else if (EVENT_RBUTTONDOWN == event) {
srcImg.copyTo(tmpImg);
line(tmpImg, prePt, firstPt, Scalar(255, 0, 0), 3, LINE_AA, 0);
imshow(winName, tmpImg);
tmpImg.copyTo(srcImg);
cali->extAreaNum++;
flag = false;
}
}
int videoLabelFunc(VideoCapture &v, Mat &frame, int w, int h, std::string path,
cali_param_t *cali) {
std::cout << "开始标定!" << std::endl;
// 三竖一横标定
std::cout << "开始三竖一横标定!" << std::endl;
std::cout << "按空格开始标定!" << std::endl;
winName = "caliWin";
namedWindow(winName);
Mat tmpFrame;
while (true) {
v >> frame;
imshow(winName, frame);
int key = waitKey(1);
if (' ' == key) break;
}
frame.copyTo(srcImg);
setMouseCallback(winName, onMouse4Line, (void *)cali);
waitKey(0);
if (caliNum < 4) {
std::cout << "三竖一横标定失败,请重新尝试!" << std::endl;
}
std::cout << "三竖一横标定成功!" << std::endl;
printf("v1: (%d, %d), (%d, %d)\n", cali->verticalLine[0].start.x,
cali->verticalLine[0].start.y, cali->verticalLine[0].end.x,
cali->verticalLine[0].end.y);
printf("v2: (%d, %d), (%d, %d)\n", cali->verticalLine[1].start.x,
cali->verticalLine[1].start.y, cali->verticalLine[1].end.x,
cali->verticalLine[1].end.y);
printf("v3: (%d, %d), (%d, %d)\n", cali->verticalLine[2].start.x,
cali->verticalLine[2].start.y, cali->verticalLine[2].end.x,
cali->verticalLine[2].end.y);
printf("h : (%d, %d), (%d, %d)\n", cali->horizontalLine.start.x,
cali->horizontalLine.start.y, cali->horizontalLine.end.x,
cali->horizontalLine.end.y);
std::cout << "输入竖线实际高度:";
std::cin >> cali->verLine;
std::cout << "输入横线实际长度:";
std::cin >> cali->horLine;
// 绘制检测区
std::cout << "开始绘制检测区!" << std::endl;
frame.copyTo(srcImg);
imshow(winName, srcImg);
setMouseCallback(winName, onMouseDetectArea, (void *)cali);
waitKey(0);
std::cout << "检测区绘制成功!" << std::endl;
std::cout << "detect area coordinate:" << std::endl;
for (int i = 0; i < cali->detectArea.ptNum; i++) {
std::cout << cali->detectArea.point[i].x << " "
<< cali->detectArea.point[i].y << std::endl;
}
// 绘制屏蔽区
int extFlag = 0;
std::cout << "是否配置屏蔽区(是:“1”,否:“0”):";
std::cin >> extFlag;
if (1 == extFlag) {
/*frame.copyTo(srcImg);*/
setMouseCallback(winName, onMouseExtArea, (void *)cali);
waitKey(0);
std::cout << "sheilded area num is [" << cali->extAreaNum
<< "]:" << std::endl;
for (int aIdx = 0; aIdx < cali->extAreaNum; aIdx++) {
std::cout << "sheilded area [" << aIdx << "]" << std::endl;
for (int pIdx = 0; pIdx < cali->shieldedArea[aIdx].ptNum; pIdx++) {
std::cout << cali->shieldedArea[aIdx].point[pIdx].x << ' '
<< cali->shieldedArea[aIdx].point[pIdx].y << std::endl;
}
}
}
std::cout << "标定结束!" << std::endl;
// 以json格式写入标定文件
Json::Value jv;
return 0;
}
int main(int argc, char *argv[]) {
std::string vPath;
std::cout << "input video path:";
std::cin >> vPath;
VideoCapture v;
v.open(vPath);
if (!v.isOpened()) {
std::cout << "error! \t" << vPath << " can't open!" << std::endl;
} else {
std::cout << vPath << " open Success!" << std::endl;
}
int w = v.get(CAP_PROP_FRAME_WIDTH);
int h = v.get(CAP_PROP_FRAME_HEIGHT);
int fNum = v.get(CAP_PROP_FRAME_COUNT);
printf("video's width [%d], height [%d], frameNum [%d]\n", w, h, fNum);
Mat frame;
// 跳过前10帧
for (int fIdx = 0; fIdx < 10; fIdx++) {
v >> frame;
}
cali_param_t cali = {0};
// 标定函数
std::string labelFile;
if (0 != getLabelFile(vPath, labelFile)) {
videoLabelFunc(v, frame, w, h, vPath, &cali);
} else {
std::cout << "标定文件已存在!" << std::endl;
}
return 0;
}
|
#include <iostream>
#include <cmath>
using namespace std;
int main(){
long long int mid, c, d, n, i, cn;
double root;
cin >> cn;
for (i=0; i<cn; i++){
cin >> n;
cout << "Case " << i+1 << ": ";
root = sqrt (n);
if (root - floor (root) == 0){
if (n%2==0)
cout << root << " " << 1 << endl;
else
cout << 1 << " " << root << endl;
}
else {
c = ceil(root);
mid = (c*c) - (c-1);
if ((c%2==0 && n<mid) || (c%2!=0 && n>mid)){
d = abs (n-mid);
cout << c-d << " " << c << endl;
}
else{
d=abs(n-mid);
cout << c << " " << c-d << endl;
}
}
}
return 0;
}
|
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <commdlg.h>
#include <basetsd.h>
#include <objbase.h>
#include <string.h>
#include <math.h>
#define StrSize 8
typedef struct {
int value;
char passedValue[StrSize];
int packetSize;
} ControllerInput;
typedef struct {
float value;
char passedValue[StrSize];
int packetSize;
} LeapInput;
//-----------------------------------------------------------------------------
// Function-prototypes
//-----------------------------------------------------------------------------
HRESULT UpdateControllerState();
int AnalogToDigital(int);
void FillByteSize();
void CheckDeadZone();
void CheckLeapDeadZone();
void SendData(HANDLE hserial);
void RecieveData(HANDLE hSerial);
|
#include "static_lib2/sublib2.h"
// #include "interface_lib2/sublib2.h"
int main(int argc, char *argv[])
{
sublib2 hi;
hi.print();
// sublib2 howdy;
// howdy.print();
return 0;
}
|
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
using namespace std;
int func(int a)
{
return (a++);
}
int i;
int main()
{
/* int i;
for(i=1;i<4;i++)
switch(i)
case 1: printf("%d",i);break;
{
case 2: printf("%d",i);break;
case 3: printf("%d",i);break;
}
switch(i) case 4: printf("%d",i);break;
*/
/* char *s = "\12345s\n";
printf("%d",sizeof(s));*/
/*
static int i=3;
printf("%d",i--);
return i>0?main():0;*/
/*char *s[]= {"dharma","hp","hi","fuck"};
char **p;
p=s;
printf("%s\n",++*p);
printf("%s\n",*p++);
printf("%s\n",++*p);
printf("%s\n",*++p);
char *t= "dharma";
char *q;
q=t;
printf("%s\n",++q); //harma
printf("%s\n",q++);//harma
printf("%s\n",++q); //rma*/
/* char a[] = "string";
char *p = "hieeder";
char *temp;
temp=a;
printf("%d",strlen(a));*/
/* char *a = "Alice";
int n=strlen(a);
*a = a[n];
for(int i=0;i<=n;i++)
{printf("%s",a);
a++;}
printf("\n",a);*/
/*
int x=20,y=15,z;
z = y+++x++;
printf("%d %d %d\n",x,y,z);
y = y+++x;
printf("%d %d %d",x,y,z);*/
/* int i=4,j=8;
printf("%d %d %d",i|j & j|i, i|j&j|i,i^j);*/
/* struct node
{
int a;
float b;
struct node *link;
};
struct node *p = (struct node *)malloc(sizeof(struct node));
struct node *q = (struct node *)malloc(sizeof(struct node));
printf("%d %d %d",sizeof(p),sizeof(q),sizeof(struct node));
*/
/* int a=0,b=4;char x=1,y=10;
if(a,b,x,y)
printf("hello");*/
/* int a=10;
int x= func(a);
printf("%d",--x);
*/
/*
int i=-1;
+i;
printf("%d %d",i,+i);*/
/* char not;
not = 2;
printf("%d",not);
*/
/* FILE *ptr;
char i;
ptr = fopen("x.txt","r");
while((i=fgetch(ptr))!=EOF)
printf("%c",i);
*/
int t;
for(t=4;scanf("%d",&i)-t;printf("%d\n",i))
printf("%d--",t--);
getch();
}
|
#ifndef PSEUDOGENOMEGENERATORBASE_H_INCLUDED
#define PSEUDOGENOMEGENERATORBASE_H_INCLUDED
#include "../../pseudogenome/DefaultPseudoGenome.h"
#include "../../pseudogenome/PseudoGenomeInterface.h"
#include "../../readsset/DefaultReadsSet.h"
#include "../SeparatedPseudoGenome.h"
using namespace PgSAHelpers;
using namespace PgSAReadsSet;
using namespace PgTools;
namespace PgSAIndex {
class PseudoGenomeGeneratorBase
{
public:
virtual SeparatedPseudoGenome* generateSeparatedPseudoGenome() = 0;
virtual PseudoGenomeBase* generatePseudoGenomeBase() = 0;
virtual const vector<bool> getBothSidesOverlappedReads(double overlappedReadsCountStopCoef) = 0;
virtual ~PseudoGenomeGeneratorBase() {} ;
};
class PseudoGenomeGeneratorFactory
{
public:
virtual ~PseudoGenomeGeneratorFactory() {};
virtual PseudoGenomeGeneratorBase* getGenerator(ReadsSourceIteratorTemplate<uint_read_len_max> *readsIterator) = 0;
};
}
#endif // PSEUDOGENOMEGENERATORBASE_H_INCLUDED
|
#include "../src/Logger.hpp"
int main()
{
Logger log( "test", "./logs" );
log.writeInfo( "testinfo" );
log.writeWarn( "testwarn" );
log.writeDebug( "testdebug" );
log.writeError( "testerror" );
return 0;
}
|
#include "GnSystemPCH.h"
#include "GnPath.h"
#ifdef WIN32
bool GnGetCurrentDirectory(gchar* pcStr, gtuint uiMaxSize)
{
if( GetCurrentDirectoryA( uiMaxSize, pcStr ) == 0 )
return false;
return true;
}
#else
#endif
gsize GnPath::ConvertToAbsolute(char* pcAbsolutePath, size_t stAbsBytes, const char* pcRelativePath, const char* pcRelativeToHere)
{
//// This function takes pcRelativePath and converts it to an absolute path
//// by concatenating it with pcRelativeToHere and removing dotdots.
//// The resulting absolute path is stored in pcAbsolutePath, which is
//// assumed to have been allocated with size stAbsBytes.
//// The function returns the number of bytes written.
//GnAssert(pcAbsolutePath && pcRelativePath);
//GnAssert(IsRelative(pcRelativePath));
//GnAssert(pcAbsolutePath != pcRelativePath); // destination cannot be source
//
//// If pcRelativeToHere is null or an empty string, use the current working
//// directory.
//if (!pcRelativeToHere)
//{
// pcRelativeToHere = "";
//}
//size_t stLenRelativeToHere = strlen(pcRelativeToHere);
//if (stLenRelativeToHere == 0)
//{
// char acCWD[NI_MAX_PATH];
// if (!GnGetCurrentDirectory(acCWD, NI_MAX_PATH))
// {
// if (stAbsBytes > 0)
// pcAbsolutePath[0] = NULL;
// return 0;
// }
// GnAssert(strlen(acCWD) != 0);
// return ConvertToAbsolute(pcAbsolutePath, stAbsBytes, pcRelativePath, acCWD);
//}
//size_t stLenRelativePath = strlen(pcRelativePath);
//// Concatenate a delimiter if necessary
//bool bInsertDelimiter =
// (pcRelativeToHere[stLenRelativeToHere-1] != NI_PATH_DELIMITER_CHAR);
//size_t stRequiredSize = 1 // null termination
// + stLenRelativeToHere
// + stLenRelativePath
// + ((bInsertDelimiter) ? 1 : 0);
//// Fail if not enough storage
//if (stAbsBytes < stRequiredSize)
//{
// if (stAbsBytes > 0)
// pcAbsolutePath[0] = NULL;
// return 0;
//}
//// Store pcRelativeToHere into pcAbsolutePath
//GnStrcpy(pcAbsolutePath, pcRelativeToHere, stAbsBytes);
//// Concatenate a delimiter if necessary
//if (bInsertDelimiter)
// GnStrcat(pcAbsolutePath, NI_PATH_DELIMITER_STR, stAbsBytes);
//// Concatenate pcRelativePath
//GnStrcat(pcAbsolutePath, pcRelativePath);
//RemoveDotDots(pcAbsolutePath);
return strlen(pcAbsolutePath);
}
bool GnPath::GetFileName(const gwchar* pcFilePath, gwchar* pcOutName, gsize maxPathLength, bool hasExtension)
{
#ifdef WIN32
gwchar strFullPath[GN_MAX_PATH];
if( GetFullPath( pcFilePath, strFullPath, GN_MAX_PATH ) == false )
return false;
gwchar strExtension[16];
errno_t err = _wsplitpath_s( strFullPath, NULL, 0, NULL, 0, pcOutName, maxPathLength, strExtension, 16 );
//_splitpath_s(strFullPath, drive, dir, NULL, NULL);
if( err != 0 )
return false;
if( hasExtension )
GnWStrcat( pcOutName, strExtension, maxPathLength );
#endif // WIN32
return true;
}
bool GnPath::GetFullPath(const gwchar* pcFilePath, gwchar* pcOutPath, gsize maxPathLength)
{
#ifdef WIN32
if( _wfullpath( pcOutPath, pcFilePath, maxPathLength ) == NULL )
return false;
#endif // WIN32
return true;
}
bool GnPath::GetFileNameA(const gchar* pcFilePath, gchar* pcOutName, gsize maxPathLength, bool hasExtension)
{
#ifdef WIN32
gchar strFullPath[GN_MAX_PATH];
if( GetFullPathA( pcFilePath, strFullPath, GN_MAX_PATH ) == false )
return false;
gchar strExtension[16];
errno_t err = _splitpath_s( strFullPath, NULL, 0, NULL, 0, pcOutName, maxPathLength, strExtension, 16 );
if( err != 0 )
return false;
if( hasExtension )
GnStrcat( pcOutName, strExtension, maxPathLength );
#endif // WIN32
return true;
}
bool GnPath::GetFullPathA(const gchar* pcFilePath, gchar* pcOutPath, gsize maxPathLength)
{
#ifdef WIN32
if( _fullpath( pcOutPath, pcFilePath, maxPathLength ) == NULL )
return false;
#endif // WIN32
return true;
}
bool GnPath::CheckSamePathA(const gchar* pcPath1, const gchar* pcPath2)
{
gchar strFullPath1[GN_MAX_PATH] = {0,};
gchar strFullPath2[GN_MAX_PATH] = {0,};
GetFullPathA( pcPath1, strFullPath1, GN_MAX_PATH );
GetFullPathA( pcPath2, strFullPath2, GN_MAX_PATH );
if( GnStricmp( strFullPath1, strFullPath2 ) != 0 )
return false;
return true;
}
|
#pragma once
#include "..\Common\Pch.h"
#include "..\Graphic\Direct3D.h"
#include "..\RenderResource\InputLayout.h"
class Sphere : public InputLayout
{
public:
Sphere();
~Sphere();
void Initialize();
void SetBuffer();
private:
vector<IL_PosTexNor> mVertexData;
vector<UINT> mIndexData;
virtual void InitializeData();
virtual void InitializeBuffer();
};
|
#ifndef CoinConf_H
#define CoinConf_H
#include "BaseCoinConf.h"
#include "Table.h"
class CoinConf : public BaseCoinConf
{
public:
public:
static CoinConf* getInstance();
virtual ~CoinConf();
virtual bool GetCoinConfigData();
Cfg* getCoinCfg() { return &coinCfg; }
int getWinCount(int64_t &bankerwin, int64_t &playerwin, int64_t &userbanker);
int setWinCount(int64_t bankerwin, int64_t playerwin, int64_t userbanker);
int delRobotWinInfo();
int setTableBanker(int id);
int setTableStatus(short status);
int setPlayerBet(short type, int64_t betcoin);
int clearPlayerUidBet();
int setPlayerUidBet(short type, int uid, int64_t betcoin);
int getSwtichTypeResult();
int64_t getJackPot();
int setJackPot(int64_t money);
int getjackpotResult(short &jackpotindex, short &jackcardtype);
int getBlackList(vector<int> &blacklist);
private:
Cfg coinCfg;
CoinConf();
};
#endif
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <vector>
#include <algorithm>
#include <math.h>
#define pb push_back
using namespace std;
int n;
void input() {
scanf("%d", &n);
}
// use for loop
/*int calcFactorial(int n) {
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
return factorial;
}*/
// use recusive
int calcFactorial(int n) {
if (n == 2)
return n;
return n * calcFactorial(n - 1);
}
void solve() {
printf("%d! = %d\n", n, calcFactorial(n));
}
int main()
{
int ntest;
freopen("labiec16.inp", "r", stdin);
scanf("%d", &ntest);
for (int itest = 0; itest < ntest; itest++) {
input();
solve();
}
return 0;
}
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_SF_LAYER_STATE_H
#define ANDROID_SF_LAYER_STATE_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <ui/Region.h>
#include <surfaceflinger/ISurface.h>
namespace android {
class Parcel;
class ISurfaceComposerClient;
struct layer_state_t {
layer_state_t()
: surface(0), what(0),
x(0), y(0), z(0), w(0), h(0),
alpha(0), tint(0), flags(0), mask(0),
reserved(0)
{
matrix.dsdx = matrix.dtdy = 1.0f;
matrix.dsdy = matrix.dtdx = 0.0f;
}
status_t write(Parcel& output) const;
status_t read(const Parcel& input);
struct matrix22_t {
float dsdx;
float dtdx;
float dsdy;
float dtdy;
};
SurfaceID surface;
uint32_t what;
float x;
float y;
uint32_t z;
uint32_t w;
uint32_t h;
float alpha;
uint32_t tint;
uint8_t flags;
uint8_t mask;
uint8_t reserved;
matrix22_t matrix;
// non POD must be last. see write/read
Region transparentRegion;
};
struct ComposerState {
sp<ISurfaceComposerClient> client;
layer_state_t state;
status_t write(Parcel& output) const;
status_t read(const Parcel& input);
};
}; // namespace android
#endif // ANDROID_SF_LAYER_STATE_H
|
/*
TouchKeys: multi-touch musical keyboard control software
Copyright (c) 2013 Andrew McPherson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=====================================================================
TouchkeyMultiFingerTriggerMappingFactory.h: factory for the multiple-
finger trigger mapping, which performs actions when two or more fingers
are added or removed from the key.
*/
#ifndef __TouchKeys__TouchkeyMultiFingerTriggerMappingFactory__
#define __TouchKeys__TouchkeyMultiFingerTriggerMappingFactory__
#include "../TouchkeyBaseMappingFactory.h"
#include "TouchkeyMultiFingerTriggerMapping.h"
class TouchkeyMultiFingerTriggerMappingFactory : public TouchkeyBaseMappingFactory<TouchkeyMultiFingerTriggerMapping> {
private:
public:
// ***** Constructor *****
// Default constructor, containing a reference to the PianoKeyboard class.
TouchkeyMultiFingerTriggerMappingFactory(PianoKeyboard &keyboard, MidiKeyboardSegment& segment);
// ***** Destructor *****
~TouchkeyMultiFingerTriggerMappingFactory() {}
// ***** Accessors / Modifiers *****
virtual const std::string factoryTypeName() { return "Multi-Finger\nTrigger"; }
// ***** Class-Specific Methods *****
// Parameters for multi-finger trigger
int getTouchesForTrigger() { return numTouchesForTrigger_; }
int getFramesForTrigger() { return numFramesForTrigger_; }
int getConsecutiveTapsForTrigger() { return numConsecutiveTapsForTrigger_; }
timestamp_diff_type getMaxTimeBetweenTapsForTrigger() { return maxTapSpacing_; }
bool getNeedsMidiNoteOn() { return needsMidiNoteOn_; }
int getTriggerOnAction() { return triggerOnAction_; }
int getTriggerOffAction() { return triggerOffAction_; }
int getTriggerOnNoteNumber() { return triggerOnNoteNum_; }
int getTriggerOffNoteNumber() { return triggerOffNoteNum_; }
int getTriggerOnNoteVelocity() { return triggerOnNoteVel_; }
int getTriggerOffNoteVelocity() { return triggerOffNoteVel_; }
void setTouchesForTrigger(int touches);
void setFramesForTrigger(int frames);
void setConsecutiveTapsForTrigger(int taps);
void setMaxTimeBetweenTapsForTrigger(timestamp_diff_type timeDiff);
void setNeedsMidiNoteOn(bool needsMidi);
void setTriggerOnAction(int action);
void setTriggerOffAction(int action);
void setTriggerOnNoteNumber(int note);
void setTriggerOffNoteNumber(int note);
void setTriggerOnNoteVelocity(int velocity);
void setTriggerOffNoteVelocity(int velocity);
#ifndef TOUCHKEYS_NO_GUI
// ***** GUI Support *****
bool hasBasicEditor() { return true; }
MappingEditorComponent* createBasicEditor();
bool hasExtendedEditor() { return false; }
MappingEditorComponent* createExtendedEditor() { return nullptr; }
#endif
// ****** OSC Control Support ******
OscMessage* oscControlMethod(const char *path, const char *types,
int numValues, lo_arg **values, void *data);
// TODO: ****** Preset Save/Load ******
XmlElement* getPreset();
bool loadPreset(XmlElement const* preset);
private:
// ***** Private Methods *****
void initializeMappingParameters(int noteNumber, TouchkeyMultiFingerTriggerMapping *mapping);
// Parameters
int numTouchesForTrigger_; // How many touches are needed for a trigger
int numFramesForTrigger_; // How many consecutive frames with these touches are needed to trigger
int numConsecutiveTapsForTrigger_; // How many taps with this number of touches are needed to trigger
timestamp_diff_type maxTapSpacing_; // How far apart the taps can come and be considered a multi-tap gesture
bool needsMidiNoteOn_; // Whether the MIDI note has to be on for this gesture to trigger
int triggerOnAction_, triggerOffAction_; // Actions to take on trigger on/off
int triggerOnNoteNum_, triggerOffNoteNum_; // Which notes to send if a note is being sent
int triggerOnNoteVel_, triggerOffNoteVel_; // Velocity to send if a note is being sent
};
#endif /* defined(__TouchKeys__TouchkeyMultiFingerTriggerMappingFactory__) */
|
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <queue>
#include <unordered_map>
#include <map>
using namespace std;
// A binary tree node has data, pointer to left child and a pointer to right child
struct Node{
int data;
struct Node *left, *right;
Node (int data){
this->data = data;
left = right = nullptr;
}
};
// Function to build the tree
Node* buildTree(string str){
//Corner case
if (str.length()==0 || str[0]=='N'){
return nullptr;
}
// Creating vector of strings from input
// string after splitting by space
vector<string> ip;
istringstream iss(str);
for (string str; iss>>str; ){
ip.push_back(str);
}
// Create the root of the tree
Node *root = new Node(stoi(ip[0]));
// Push the root to the queue
queue<Node *> queue;
queue.push(root);
// Starting for second element
int i=1;
while (!queue.empty() && i<ip.size()){
//Get and remove the front of the queue
Node* currNode = queue.front();
queue.pop();
// Get the current node's value from the string
string currVal = ip[i];
// If the left child is not null
if (currVal != "N"){
// Create the left child for the current node
currNode->left = new Node(stoi(currVal));
// Push it to the queue
queue.push(currNode->left);
}
// For the right child
i++;
if (i>=ip.size()){
break;
}
currVal = ip[i];
// If the right child is not null
if (currVal != "N"){
// Create the right child for the current node
currNode->right = new Node(stoi(currVal));
// Push it to the queue
queue.push(currNode->right);
}
i++;
}
return root;
}
// Given a binary tree, print its nodes in preorder
void preorderTraversal (Node *root){
if (!root){
return;
}
cout<<root->data<<" ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// Given a binary tree, print its node in inorder
void inorderTraversal (Node *root){
if (!root){
return;
}
inorderTraversal(root->left);
cout<<root->data<<" ";
inorderTraversal(root->right);
}
// Given a binary tree, print its node in postorder
void postorderTraversal (Node *root){
if (!root){
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
cout<<root->data<<" ";
}
// Given a binary tree, print its BFS traversal
void bfsTraversal (Node *root){
queue<Node *> bfs_nodes;
// vector to store visited is not required in case of trees
bfs_nodes.push(root);
while (!bfs_nodes.empty()){
Node *ptr = bfs_nodes.front();
bfs_nodes.pop();
if (!ptr){
continue;
}
cout<<ptr->data<<" ";
bfs_nodes.push(ptr->left);
bfs_nodes.push(ptr->right);
}
}
// Given a binary tree, print its left view
void leftViewUtil (Node *root, int cur_level, int *max_level){
if (!root){
return;
}
if (*max_level<cur_level){
cout<<root->data<<" ";
*max_level = cur_level;
}
// For right view, first call the leftViewUtil() for right child then for left child.
leftViewUtil(root->left, cur_level+1, max_level);
leftViewUtil(root->right, cur_level+1, max_level);
}
void leftView (Node *root){
int max_level=0;
leftViewUtil(root, 1, &max_level);
}
// Given a binary tree, print its vertical order traversal
void verticalTraversalUtil (Node *root, int hori_dist, map<int, vector<int>> &hori_dist_map){
if (!root){
return;
}
hori_dist_map[hori_dist].push_back(root->data);
verticalTraversalUtil(root->left, hori_dist-1, hori_dist_map);
verticalTraversalUtil(root->right, hori_dist+1, hori_dist_map);
}
void verticalTraversal (Node *root){
map<int, vector<int>> hori_dist_map;
verticalTraversalUtil(root, 0, hori_dist_map);
for (auto ele: hori_dist_map){
for (auto i: ele.second){
cout<<i<<" ";
}
}
}
/*
* Input1.txt
* 1
* / \
* 2 3
* / \
* 4 6
* \
* 5
* /
* 7
*/
int main() {
string s;
getline(cin, s);
cout<<"Input Binary Tree: "<<s<<endl;
Node* root = buildTree(s);
cout<<"\nDifferent types of Tree Traversal";
cout<<"\nPreorder Traversal: ";
preorderTraversal(root);
cout<<"\nInorder Traversal: ";
inorderTraversal(root);
cout<<"\nPostorder Traversal: ";
postorderTraversal(root);
cout<<"\nBFS Traversal: ";
bfsTraversal(root);
cout<<"\nLeft View: ";
leftView(root);
cout<<"\nVertical Traversal: ";
verticalTraversal(root);
return 0;
}
|
#include "stdafx.h"
#include "MainGame.h"
#include "TestScene.h"
#include "ToolMain.h"
#include "ToolSub.h"
MainGame::MainGame()
{
//SUBWIN->Init();
}
MainGame::~MainGame()
{
}
HRESULT MainGame::Init()
{
GameNode::Init();
SOUND->Init();
SUBWIN->Init();
isDebug = false;
IMAGE->AddImage("tile_main", "images/tile.bmp", 0, 0,
21 * 25, 16 * 25, 21, 16, true, RGB(255, 0, 255));
IMAGE->AddImage("tile_sub", "images/tile.bmp", 0, 0,
21 * 20, 16 * 20, 21, 16, true, RGB(255, 0, 255));
IMAGE->AddImage("tile_mini", "images/tile.bmp", 0, 0,
21 * 5, 16 * 5, 21, 16, true, RGB(255, 0, 255));
IMAGE->AddImage("toolbar", "images/toolbar_3x1.bmp", 0, 0,
3 * 50, 50, 3, 1, true, RGB(255, 0, 255));
IMAGE->AddImage("miniMap", "images/miniMap.bmp", 0, 0,
35, 35, true, RGB(255, 0, 255));
IMAGE->AddImage("camera", "images/camera.bmp", 0, 0,
200, 150, true, RGB(255, 0, 255));
IMAGE->AddImage("restore", "images/restore.bmp", 0, 0,
50, 50, true, RGB(255, 0, 255));
IMAGE->AddImage("test", "images/miniMap.bmp", 0, 0,
WINSIZEX, WINSIZEY, true, RGB(255, 0, 255));
//TestScene * test = new TestScene;
//SCENE->AddScene("Test", test);
//SOUND->AddSound("Test", "sounds/¿µÀü3.wav", true, true);
//SUBWIN->SetScene(test);
//SCENE->ChangeScene("Test");
ToolMain * main = (ToolMain*)SCENE->AddScene("MapTool_Main", new ToolMain);
ToolSub * sub = (ToolSub*)SCENE->AddScene("MapTool_Sub", new ToolSub);
SUBWIN->SetScene(sub);
sub->SetToolMain(main);
SCENE->ChangeScene("MapTool_Main");
return S_OK;
}
void MainGame::Release()
{
GameNode::Release();
}
void MainGame::Update()
{
GameNode::Update();
SUBWIN->Update();
SCENE->Update();
//====================== Debug =====================//
if (INPUT->GetKeyDown(VK_F11)) {
isDebug = !isDebug;
}
//==================================================//
}
void MainGame::Render()
{
PatBlt(GetMemDC(), 0, 0, WINSIZEX, WINSIZEY, WHITENESS);
//=================================================
{
//IMAGE->Render("test", GetMemDC(), 0, 0);
SCENE->Render();
SUBWIN->Render();
}
//================== Debug ====================
if (isDebug)
{
}
//=================================================
FRAME->Render(GetMemDC());
this->SetBackBuffer()->Render(GetHDC());
}
|
#include "storage/sstable/sstable_builder.h"
#include <iostream>
#include "absl/strings/str_cat.h"
#include "utils/file/filewriter.h"
#include "utils/file/filereader.h"
#include "utils/sort/qsort.h"
namespace storage {
namespace sstable {
const std::string DEFAULT_FILEPATH = "default";
using utils::file::filewriter::FileWriter;
using utils::file::filereader::FileReader;
SSTableBuilder::SSTableBuilder()
: filepath_(DEFAULT_FILEPATH), options_({}), index_count_(0) {}
SSTableBuilder::SSTableBuilder(std::string& filepath, SSTableOptions options)
: filepath_(std::move(filepath)),
options_(std::move(options)),
index_count_(0) {
// FileWriter::OpenOrDie(filepath_);
}
SSTableBuilder::~SSTableBuilder() {
QuickSortAndWrite();
MergeFiles();
// FileWriter::Close(filepath_);
}
// DEBUG
void SSTableBuilder::Test() {}
Status SSTableBuilder::Add(std::string key, std::string value) {
KeyValue kv{key, value};
if (++index_count_ > BUF_SIZE) {
QuickSortAndWrite();
}
buffer_.push_back(std::move(kv));
return utils::error_handling::Status::kOk;
}
Status SSTableBuilder::QuickSortAndWrite() {
// O(N*LOGN): Sort buffer_ by {key, value},
// TODO: Make sure this isn't copying?
auto q = utils::sort::MakeQuickSort(buffer_); // factory function with type deduction
q.Sort();
// TODO: Implement an ASSERT to check filename
std::string writeto_filename = absl::StrCat(filepath_, index_count_++);
tmp_files_.push_back(writeto_filename);
q.WriteToFile(writeto_filename); // Empties buffer as well
buffer_.clear();
// TODO
// O(N) : Write directly into a temporary file on disk (.sstable); keep
// track of these files.
return utils::error_handling::Status::kOk;
}
Status SSTableBuilder::MergeFiles() {
// TODO: Merge sort all the temporary files into a single one, then clean up.
// This will require splitting up the files into concurrent pairs, then
// tracking the temporary files each pair is merged into, and repeating this
// process again until we only have a single file.
// 1) Concurrency.
// 2) Concurrency with merge sorting an array.
// 3) Concurrency with opening and closing files.
// 4) This task.
for (const auto& filename : tmp_files_) {
std::cout << "filename: " << filename << std::endl;
FileReader::Open(filename);
}
return utils::error_handling::Status::kOk;
}
} // namespace sstable
} // namespace chunkblob
|
#ifndef _MA_COROUTINES_H
#define _MA_COROUTINES_H
#include "type_manipulation.h"
#include "allocators.h"
namespace ma
{
template <typename T>
struct identity
{
typedef T type;
};
template <class T>
inline T &&forward(typename remove_reference<T>::type &t) noexcept
{
return static_cast<T &&>(t);
}
template <class T>
inline T &&forward(typename remove_reference<T>::type &&t) noexcept
{
return static_cast<T &&>(t);
}
class cocontinuation
{
public:
cocontinuation(bool c) : result(c) {}
bool result;
};
template <typename T>
class costate
{
public:
costate(int id, const T &args) : _id(id), _state(0), state(args)
{
}
template <typename... TArgs>
costate(int id, TArgs &&... args) : _id(id), _state(0), state({forward<TArgs>(args)...})
{
}
int _id;
int _state;
T state;
inline int id() const { return _id; }
bool isFinished(int i)
{
return _state == -1;
}
};
template <typename T, typename... TArgs>
costate<T> &make_costate(int id, void *ptr, TArgs &&... args)
{
return *(new (ptr) costate<T>(id, forward<TArgs>(args)...));
}
#define START_COROUTINE \
switch (args._state) \
{ \
case 0:
#define END_COROUTINE \
} \
args._state = -1; \
return {false};
#define YIELD \
args._state = __LINE__; \
return {true}; \
case __LINE__:
#define ARGS args.state
#define AWAIT_IMPL(N, x) \
args._state = __LINE__; \
return {true}; \
case __LINE__: \
if (!(x)) \
return { true }
#define AWAIT(x) AWAIT_IMPL(__LINE__, x)
typedef cocontinuation (*FUNCPTR)(void *);
struct coroutine
{
FUNCPTR function;
ma::Block state;
int id() const { return *((int *)state.Pointer); }
cocontinuation step()
{
return function(state.Pointer);
}
};
template <typename T>
struct comakeresult
{
coroutine coroutine;
int id() const { return coroutine.id(); }
T &args() const
{
auto &cos = *((costate<T> *)coroutine.state.Pointer);
return cos.state;
}
bool isOk() const { return coroutine.id() >= 0; }
};
void *memset(void *ptr, int value, size_t num)
{
auto ptr2 = (char *)ptr;
while (num > 0)
{
(*ptr2) = value;
++ptr2;
num--;
}
return ptr;
}
template <typename TBuffer, unsigned int SIZE = 1024>
class CoManager
{
int pos;
bool CoroutinesBusy[SIZE];
coroutine Coroutines[SIZE];
TBuffer *Buffer;
public:
CoManager() : pos(0), Buffer(nullptr), CoroutinesBusy{0}
{
}
CoManager(TBuffer *buffer) : pos(0), Buffer(buffer), CoroutinesBusy{0}
{
}
void setBuffer(TBuffer *buffer) { Buffer = buffer; }
template <typename F>
using TFArg0 = unqualified_first_argument_of<F>;
template <typename F>
using TFArgs0Template = first_template_parameter_of<TFArg0<F>>;
template <typename F, typename... TArgs>
comakeresult<TFArgs0Template<F>>
make(F f, TArgs &&... args)
{
//find free slot - bitmap would be faster?
int stopAt = (pos - 1) % SIZE;
while (CoroutinesBusy[pos] && pos != stopAt)
pos = (pos + 1) % SIZE;
if (CoroutinesBusy[pos])
return {coroutine{nullptr, Block::Null}};
auto sizeargs = sizeof(TFArg0<F>);
auto blk = Buffer->allocate(sizeargs);
auto &costate = make_costate<
TFArgs0Template<F>,
TArgs...>(pos, blk.Pointer, forward<TArgs>(args)...);
auto oldpos = pos;
auto &coroutine = Coroutines[oldpos];
coroutine.function = (FUNCPTR)f;
coroutine.state = blk;
CoroutinesBusy[oldpos] = true;
++pos;
return {coroutine};
}
void free(int id)
{
if (id < 0)
return;
if (id >= SIZE)
return;
auto &coroutine = Coroutines[id];
Buffer->deallocate(coroutine.state);
coroutine.function = nullptr;
coroutine.state = ma::Block::Null;
CoroutinesBusy[id] = false;
pos = id;
}
cocontinuation step(int id)
{
if (id < 0)
return {false};
if (id >= 1024)
return {false};
auto &coroutine = Coroutines[id];
return coroutine.step();
}
};
} // namespace ma
#endif
|
#ifndef GRID_H
#define GRID_H
// Qt
#include <QObject>
#include <QRunnable>
#include <QList>
// PCL
#include "../DataTypes.h"
// Grid data
#include "GridCell.h"
class Grid : public QObject, public QRunnable
{
Q_OBJECT
public:
explicit Grid(QObject *parent = 0);
protected:
double minX;
double maxX;
double minY;
double maxY;
PointCloudT *cloud;
Grid *grid;
public slots:
void setInputCloud(PointCloudT *cloud);
void setInputGrid(Grid *grid);
signals:
void gridError(QString);
void gridStarted();
void gridProgress(int);
void gridFinished(Grid*);
};
#endif // GRID_H
|
#include <iostream>
#include <string>
#include <windows.h>
#include "CircularContainer.h"
HANDLE hCon;
enum Color { DARKBLUE = 1, DARKGREEN, DARKTEAL, DARKRED, DARKPINK, DARKYELLOW, GRAY, DARKGRAY, BLUE, GREEN, TEAL, RED, PINK, YELLOW, WHITE };
void SetColor(Color c){
if (hCon == NULL)
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hCon, c);
}
void ClearColor(){
SetColor(WHITE);
}
void __PASS_UNPASS_TEXT(std::string test_name, bool is_passed){
if (is_passed){
SetColor(GREEN);
std::cout << "[PASS] :" << test_name << std::endl;
}
else{
SetColor(RED);
std::cout << "[UNPASS] :" << test_name << std::endl;
}
}
void EXPECT_TRUE(std::string test_name, bool condition){
__PASS_UNPASS_TEXT(test_name, condition == true);
ClearColor();
}
void EXPECT_FALSE(std::string test_name, bool condition){
__PASS_UNPASS_TEXT(test_name, condition == false);
ClearColor();
}
template <typename T>
void EXPECT(std::string test_name, T expected, T actual){
__PASS_UNPASS_TEXT(test_name, expected == actual);
ClearColor();
if (expected != actual){
std::cout << "\t\t" << "Expected : " << expected << std::endl;
std::cout << "\t\t" << "Actual : " << actual << std::endl;
}
}
int main()
{
CircularContainer<int, 5> container;
/////////////////////////////////////////////////////
EXPECT_TRUE("empty() test" ,container.empty());
/////////////////////////////////////////////////////
container.push_back(1);
EXPECT_FALSE("not empty() test", container.empty());
/////////////////////////////////////////////////////
container.push_back(2);
container.clear();
EXPECT_TRUE("clear() test", container.empty());
/////////////////////////////////////////////////////
size_t cap = container.capacity();
for (size_t i = 0; i < cap; i++){
EXPECT<size_t>("size() test", container.size(), i);
container.push_back(static_cast<int>(i));
}
/////////////////////////////////////////////////////
for (size_t i = 0; i < container.size(); i++){
EXPECT<int>("at() test", static_cast<int>(i), container.at(i));
}
/////////////////////////////////////////////////////
container.resize(3);
EXPECT<size_t>("resize(3) test", 3, container.size());
for (size_t i = 0; i < container.size(); i++){
EXPECT<int>("at() test", static_cast<int>(i), container.at(i));
}
container.resize(5);
EXPECT<size_t>("resize(5) test", 5, container.size());
for (size_t i = 0; i < 3; i++){
EXPECT<int>("at() test", static_cast<int>(i), container.at(i));
}
container.resize(0);
EXPECT_TRUE("resize(0) test", container.empty());
/////////////////////////////////////////////////////
container.resize(4);
EXPECT_TRUE("front() text", container.front() == container.at(0));
EXPECT_TRUE("back() text", container.back() == container.at(container.size()-1));
/////////////////////////////////////////////////////
container.clear();
for (size_t i = 1; i <= 3; i++){
container.push_back(10*i);
EXPECT<int>("push_back() test", 10 * i, container.back());
}
for (size_t i = 1; i <= 2; i++){
container.push_front(100 * i);
EXPECT<int>("push_front() test", 100 * i, container.front());
}
/////////////////////////////////////////////////////
container.clear();
cap = container.capacity();
for (size_t i = 0; i < cap; i++){
container.push_back(i);
}
container.erase(2);
EXPECT<size_t>("erase(size_t) test", 4, container.size());
EXPECT<int>("erase(size_t) test", 0, container.at(0));
EXPECT<int>("erase(size_t) test", 1, container.at(1));
EXPECT<int>("erase(size_t) test", 3, container.at(2));
EXPECT<int>("erase(size_t) test", 4, container.at(3));
container.erase(0);
EXPECT<size_t>("erase(size_t) test", 3, container.size());
EXPECT<int>("erase(size_t) test", 1, container.at(0));
EXPECT<int>("erase(size_t) test", 3, container.at(1));
EXPECT<int>("erase(size_t) test", 4, container.at(2));
container.erase(2);
EXPECT<size_t>("erase(size_t) test", 2, container.size());
EXPECT<int>("erase(size_t) test", 1, container.at(0));
EXPECT<int>("erase(size_t) test", 3, container.at(1));
/////////////////////////////////////////////////////
container.clear();
cap = container.capacity();
for (size_t i = 0; i < cap; i++){
container.push_back(i);
}
container.erase(1, 3);
EXPECT<size_t>("erase(size_t,size_t) test", 2, container.size());
EXPECT<int>("erase(size_t,size_t) test", 0, container.at(0));
EXPECT<int>("erase(size_t,size_t) test", 4, container.at(1));
container.erase(0, 1);
EXPECT_TRUE("erase(size_t,size_t) test", container.empty());
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef UNIX_PROCESS_MANAGER_H
#define UNIX_PROCESS_MANAGER_H
#include "modules/util/adt/opvector.h"
#include "platforms/posix/posix_selector.h"
#include "platforms/posix_ipc/posix_ipc_event_handler.h"
class PosixIpcProcess;
class ProcessConnection;
class IpcServer;
/** @brief Manage components in sub-processes.
*/
class PosixIpcProcessManager : public PosixSelectListener, public PosixIpcEventHandlerListener
{
public:
PosixIpcProcessManager() : m_timeout(-1), m_nextid(1) {}
/** Create a new component in a sub-process
* @param [out] peer ID given to the component manager in the sub-process
* @param requester Address of the requesting component
* @param type Type of component to create
*/
OP_STATUS CreateComponent(int& peer, OpMessageAddress requester, OpComponentType type);
/** Send a message to one of the components maintained by this process manager
* @param message Message to send
*/
OP_STATUS SendMessage(OpTypedMessage* message);
/** Process events from the components managed by this manager
* @param next_timeout Time limit on events in ms, or UINT_MAX for no limit
*/
OP_STATUS ProcessEvents(unsigned int next_timeout);
/** Request a new timeout for ProcessEvents
* @param limit new timeout in ms
*/
void RequestRunSlice(unsigned int limit);
// Utilities for PosixIpcProcess
/** Register a pipe that should be watched for reading data
* Sub-processes will be instructed to read data when available
* @param fd File descriptor of pipe to watch
*/
OP_STATUS RegisterReadPipe(int fd) { return RegisterPipe(fd, false); }
/** Register a pipe that should be watched for writing data
* Sub-processes will be instructed to write data when possible
* @param fd File descriptor of pipe to watch
*/
OP_STATUS RegisterWritePipe(int fd) { return RegisterPipe(fd, true); }
/** Notify the process manager we have received word back from a component
* that was created
* @param address Address of the component that was created
*/
void OnComponentCreated(OpMessageAddress address);
// Implementing PosixSelectListener
virtual void OnReadReady(int fd);
virtual void OnWriteReady(int fd);
virtual void OnError(int fd, int err);
virtual void OnDetach(int fd);
// Implementing PosixIpcEventHandlerListener
virtual void OnSourceError(IpcHandle* source);
private:
class PipeHolder;
PosixIpcProcess* GetProcess(int cm_id);
OP_STATUS GetLogPath(OpString8& log_path);
OP_STATUS RegisterPipe(int fd, bool write);
OP_STATUS SetNonBlocking(int fd);
void KillProcess(PosixIpcProcess* process, bool detach = true);
AutoDeleteList<PosixIpcProcess> m_processes;
double m_timeout;
int m_nextid;
};
#endif // UNIX_PROCESS_MANAGER_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#include "modules/logdoc/logdoc_module.h"
#include "modules/logdoc/link.h"
#include "modules/logdoc/htm_lex.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/logdoc/namespace.h"
#include "modules/logdoc/src/html5/html5entities.h"
#include "modules/logdoc/html5namemapper.h"
#include "modules/layout/cssprops.h"
#include "modules/prefs/prefsmanager/collections/pc_fontcolor.h"
#include "modules/prefs/prefsmanager/collections/pc_display.h"
#if LOGDOC_MIN_ANIM_UPDATE_INTERVAL_DURING_LOADING > 0 || LOGDOC_MIN_ANIM_UPDATE_INTERVAL_LOW > 0
#include "modules/prefs/prefsmanager/collections/pc_core.h"
#endif // LOGDOC_MIN_ANIM_UPDATE_INTERVAL_DURING_LOADING > 0 || LOGDOC_MIN_ANIM_UPDATE_INTERVAL_LOW > 0
#ifdef OPERA_CONSOLE
# include "modules/locale/oplanguagemanager.h"
#endif // OPERA_CONSOLE
#include "modules/encodings/tablemanager/optablemanager.h"
#ifdef DNS_PREFETCHING
#include "modules/logdoc/dnsprefetcher.h"
#endif // DNS_PREFETCHING
#ifndef HAS_COMPLEX_GLOBALS
extern void init_AMP_ESC();
extern void init_ATTR_value_name();
extern void init_ClearNameMap();
extern void init_ScrollNameMap();
extern void init_ShapeNameMap();
extern void init_FrameValueNameMap();
extern void init_RulesNameMap();
extern void init_DirNameMap();
extern void init_MethodNameMap();
extern void init_BehaviorNameMap();
extern void init_XML_tag_name();
extern void init_g_html5_tag_names_upper();
extern void init_g_html5_attr_names_upper();
extern void init_g_html5_error_descs();
extern void HTML5TransitionsInitL();
#ifdef ACCESS_KEYS_SUPPORT
extern void init_g_AK2OK_names();
#endif // ACCESS_KEYS_SUPPORT
extern void init_LinkTypeMapL();
extern void init_gDTDStrings();
extern void init_g_handheld_html_doctypes();
extern void init_g_handheld_wml_doctypes();
# ifdef WML_WBXML_SUPPORT
extern void init_WML_WBXML_tag_tokens();
extern void init_WML_WBXML_attr_start_tokens();
extern void init_WML_WBXML_attr_value_tokens();
# endif // WML_WBXML_SUPPORT
# ifdef SI_WBXML_SUPPORT
extern void init_ServiceInd_WBXML_tag_tokens();
extern void init_ServiceInd_WBXML_attr_start_tokens();
extern void init_ServiceInd_WBXML_attr_value_tokens();
# endif // SI_WBXML_SUPPORT
# ifdef SL_WBXML_SUPPORT
extern void init_ServiceLoad_WBXML_attr_start_tokens();
extern void init_ServiceLoad_WBXML_attr_value_tokens();
# endif // SL_WBXML_SUPPORT
# ifdef PROV_WBXML_SUPPORT
extern void init_Provisioning_WBXML_tag_tokens();
extern void init_Provisioning_WBXML_attr_start_tokens();
extern void init_Provisioning_WBXML_attr_start_tokens_cp1();
extern void init_Provisioning_WBXML_attr_value_tokens();
extern void init_Provisioning_WBXML_attr_value_tokens_cp1();
# endif // PROV_WBXML_SUPPORT
# ifdef DRMREL_WBXML_SUPPORT
extern void init_RightsExpressionLanguage_WBXML_tag_tokens();
extern void init_RightsExpressionLanguage_WBXML_attr_start_tokens();
extern void init_RightsExpressionLanguage_WBXML_attr_value_tokens();
# endif // DRMREL_WBXML_SUPPORT
# ifdef CO_WBXML_SUPPORT
extern void init_CacheOperation_WBXML_tag_tokens();
extern void init_CacheOperation_WBXML_attr_start_tokens();
extern void init_CacheOperation_WBXML_attr_value_tokens();
# endif // CO_WBXML_SUPPORT
# ifdef EMN_WBXML_SUPPORT
extern void init_EmailNotification_WBXML_tag_tokens();
extern void init_EmailNotification_WBXML_attr_start_tokens();
extern void init_EmailNotification_WBXML_attr_value_tokens();
# endif // EMN_WBXML_SUPPORT
#endif // HAS_COMPLEX_GLOBALS
LogdocModule::LogdocModule() :
m_htm_lex(NULL)
, m_ns_manager(NULL)
, m_image_animation_handlers(NULL)
, m_url_image_content_providers(NULL)
, m_url_image_content_provider_mh(NULL)
#if defined ENCODINGS_HAVE_TABLE_DRIVEN && !defined ENCODINGS_OPPOSITE_ENDIAN
, m_win1252(NULL)
, m_win1252present(FALSE)
#endif // ENCODINGS_HAVE_TABLE_DRIVEN && !ENCODINGS_OPPOSITE_ENDIAN
, m_html5_entity_states(NULL)
, m_html5_name_mapper(NULL)
#ifdef DNS_PREFETCHING
, m_dns_prefetcher(NULL)
#endif // DNS_PREFETCHING
, m_tmp_buffers_used(0)
#if LOGDOC_MIN_ANIM_UPDATE_INTERVAL_DURING_LOADING > 0 || LOGDOC_MIN_ANIM_UPDATE_INTERVAL_LOW > 0
, m_cached_throttling_needed(FALSE)
, m_last_throttling_check_timestamp(0.0)
#endif // LOGDOC_MIN_ANIM_UPDATE_INTERVAL_DURING_LOADING > 0 || LOGDOC_MIN_ANIM_UPDATE_INTERVAL_LOW > 0
{
#ifndef HAS_COMPLEX_GLOBALS
for (unsigned j = 0; j < HTML5TreeState::kNumberOfTransitionStates; j++)
m_html5_transitions[j] = NULL;
#endif // !HAS_COMPLEX_GLOBALS
// set to NULL to avoid problems if allocation fails
for (int i = 0; i < 3; i++)
m_tmp_buffers[i] = NULL;
}
void
LogdocModule::InitL(const OperaInitInfo& info)
{
CONST_ARRAY_INIT(AMP_ESC);
CONST_ARRAY_INIT(ATTR_value_name);
CONST_ARRAY_INIT(ClearNameMap);
CONST_ARRAY_INIT(ScrollNameMap);
CONST_ARRAY_INIT(ShapeNameMap);
CONST_ARRAY_INIT(FrameValueNameMap);
CONST_ARRAY_INIT(RulesNameMap);
CONST_ARRAY_INIT(DirNameMap);
CONST_ARRAY_INIT(MethodNameMap);
CONST_ARRAY_INIT(BehaviorNameMap);
CONST_ARRAY_INIT(XML_tag_name);
CONST_ARRAY_INIT(g_html5_tag_names_upper);
CONST_ARRAY_INIT(g_html5_attr_names_upper);
CONST_ARRAY_INIT(g_html5_error_descs);
#ifdef ACCESS_KEYS_SUPPORT
CONST_ARRAY_INIT(g_AK2OK_names);
#endif // ACCESS_KEYS_SUPPORT
CONST_ARRAY_INIT(LinkTypeMapL);
CONST_ARRAY_INIT(gDTDStrings);
CONST_ARRAY_INIT(g_handheld_html_doctypes);
CONST_ARRAY_INIT(g_handheld_wml_doctypes);
#ifndef HAS_COMPLEX_GLOBALS
# ifdef WML_WBXML_SUPPORT
CONST_ARRAY_INIT(WML_WBXML_tag_tokens);
CONST_ARRAY_INIT(WML_WBXML_attr_start_tokens);
CONST_ARRAY_INIT(WML_WBXML_attr_value_tokens);
# endif // WML_WBXML_SUPPORT
# ifdef SI_WBXML_SUPPORT
CONST_ARRAY_INIT(ServiceInd_WBXML_tag_tokens);
CONST_ARRAY_INIT(ServiceInd_WBXML_attr_start_tokens);
CONST_ARRAY_INIT(ServiceInd_WBXML_attr_value_tokens);
# endif // SI_WBXML_SUPPORT
# ifdef SL_WBXML_SUPPORT
CONST_ARRAY_INIT(ServiceLoad_WBXML_attr_start_tokens);
CONST_ARRAY_INIT(ServiceLoad_WBXML_attr_value_tokens);
# endif // SL_WBXML_SUPPORT
# ifdef PROV_WBXML_SUPPORT
CONST_ARRAY_INIT(Provisioning_WBXML_tag_tokens);
CONST_ARRAY_INIT(Provisioning_WBXML_attr_start_tokens);
CONST_ARRAY_INIT(Provisioning_WBXML_attr_start_tokens_cp1);
CONST_ARRAY_INIT(Provisioning_WBXML_attr_value_tokens);
CONST_ARRAY_INIT(Provisioning_WBXML_attr_value_tokens_cp1);
# endif // PROV_WBXML_SUPPORT
# ifdef DRMREL_WBXML_SUPPORT
CONST_ARRAY_INIT(RightsExpressionLanguage_WBXML_tag_tokens);
CONST_ARRAY_INIT(RightsExpressionLanguage_WBXML_attr_start_tokens);
CONST_ARRAY_INIT(RightsExpressionLanguage_WBXML_attr_value_tokens);
# endif // DRMREL_WBXML_SUPPORT
# ifdef CO_WBXML_SUPPORT
CONST_ARRAY_INIT(CacheOperation_WBXML_tag_tokens);
CONST_ARRAY_INIT(CacheOperation_WBXML_attr_start_tokens);
CONST_ARRAY_INIT(CacheOperation_WBXML_attr_value_tokens);
# endif // CO_WBXML_SUPPORT
# ifdef EMN_WBXML_SUPPORT
CONST_ARRAY_INIT(EmailNotification_WBXML_tag_tokens);
CONST_ARRAY_INIT(EmailNotification_WBXML_attr_start_tokens);
CONST_ARRAY_INIT(EmailNotification_WBXML_attr_value_tokens);
# endif // EMN_WBXML_SUPPORT
for (unsigned j = 0; j < HTML5TreeState::kNumberOfTransitionStates; j++)
m_html5_transitions[j] = OP_NEWA_L(HTML5TreeState::State, HTML5TreeState::kNumberOfTransitionSubStates);
HTML5TransitionsInitL();
#endif // HAS_COMPLEX_GLOBALS
m_htm_lex = OP_NEW_L(HTM_Lex, ());
m_htm_lex->InitL();
m_ns_manager = OP_NEW_L(NamespaceManager, ());
m_ns_manager->InitL(256);
m_image_animation_handlers = OP_NEW_L(Head, ());
m_url_image_content_providers = OP_NEWA_L(Head, ImageCPHashCount);
m_url_image_content_provider_mh = OP_NEW_L(MessageHandler, (NULL));
for (int i = 0; i < 3; i++)
{
m_tmp_buffers[i] = OP_NEW_L(TempBuffer, ());
m_tmp_buffers[i]->SetCachedLengthPolicy(TempBuffer::TRUSTED);
}
m_tmp_buffers[0]->Expand(PREALLOC_BUFFER_SIZE);
m_tmp_buffers[1]->Expand(PREALLOC_BUFFER_SIZE);
m_tmp_buffers[2]->Expand(PREALLOC_BUFFER_SIZE);
HTML5EntityStates::InitL();
m_html5_name_mapper = OP_NEW_L(HTML5NameMapper, ());
m_html5_name_mapper->InitL();
#ifdef DNS_PREFETCHING
m_dns_prefetcher = OP_NEW_L(DNSPrefetcher, ());
#endif // DNS_PREFETCHING
}
void
LogdocModule::Destroy()
{
#ifndef HAS_COMPLEX_GLOBALS
for (unsigned j = 0; j < HTML5TreeState::kNumberOfTransitionStates; j++)
OP_DELETEA(m_html5_transitions[j]);
#endif // !HAS_COMPLEX_GLOBALS
OP_DELETEA(m_url_image_content_providers);
m_url_image_content_providers = NULL;
OP_DELETE(m_url_image_content_provider_mh);
m_url_image_content_provider_mh = NULL;
OP_DELETE(m_image_animation_handlers);
m_image_animation_handlers = NULL;
OP_DELETE(m_ns_manager);
m_ns_manager = NULL;
OP_DELETE(m_htm_lex);
m_htm_lex = NULL;
for (int i = 0; i < 3; i++)
OP_DELETE(m_tmp_buffers[i]);
#if defined ENCODINGS_HAVE_TABLE_DRIVEN && !defined ENCODINGS_OPPOSITE_ENDIAN
if (m_win1252)
{
g_table_manager->Release(m_win1252);
m_win1252 = NULL;
}
#endif // ENCODINGS_HAVE_TABLE_DRIVEN && !ENCODINGS_OPPOSITE_ENDIAN
HTML5EntityStates::Destroy();
OP_DELETE(m_html5_name_mapper);
m_html5_name_mapper = NULL;
#ifdef DNS_PREFETCHING
OP_DELETE(m_dns_prefetcher);
m_dns_prefetcher = NULL;
#endif // DNS_PREFETCHING
}
const unsigned short*
LogdocModule::GetWin1252Table()
{
#if defined ENCODINGS_HAVE_TABLE_DRIVEN && !defined ENCODINGS_OPPOSITE_ENDIAN
// Fetch the windows-1252 table from the table manager. We will keep
// this in memory until we exit Opera, since it is referenced every
// time we call ReplaceEscapes() to resolve numerical character
// references.
if (!m_win1252 && !m_win1252present)
{
long tablesize;
m_win1252 = (unsigned short *) g_table_manager->Get("windows-1252", tablesize);
// Make sure we got the right table, so that we can't index outside
// allocated memory.
if (tablesize != 256)
{
// This was no good, ignore the table, and set a flag so that we
// won't try loading it again later on.
if (m_win1252)
{
g_table_manager->Release(m_win1252);
}
m_win1252 = NULL;
m_win1252present = TRUE;
}
}
return m_win1252;
#else
// This is the part of the windows-1252 table we actually need for the
// ReplaceEscapes() function.
static const unsigned short win1252_table[160 - 128] =
{
8364, NOT_A_CHARACTER, 8218, 402, 8222, 8230, 8224, 8225,
710, 8240, 352, 8249, 338, NOT_A_CHARACTER, 381, NOT_A_CHARACTER,
NOT_A_CHARACTER, 8216, 8217, 8220, 8221, 8226, 8211, 8212,
732, 8482, 353, 8250, 339, NOT_A_CHARACTER, 382, 376
};
return win1252_table;
#endif // ENCODINGS_HAVE_TABLE_DRIVEN && !ENCODINGS_OPPOSITE_ENDIAN
}
TempBuffer*
LogdocModule::GetTempBuffer()
{
for (int i = 0; i < 3; i++)
if ((m_tmp_buffers_used & (1 << i)) == 0)
{
m_tmp_buffers_used |= (1 << i);
m_tmp_buffers[i]->Clear();
return m_tmp_buffers[i];
}
OP_ASSERT(!"We need to restructure the code that uses this or add more buffers.");
// returning the first instead of NULL to avoid crash, but things will fail.
m_tmp_buffers[0]->Clear();
return m_tmp_buffers[0];
}
void
LogdocModule::ReleaseTempBuffer(TempBuffer *buf)
{
for (int i = 0; i < 3; i++)
if (m_tmp_buffers[i] == buf)
{
m_tmp_buffers_used &= ~(1 << i);
if (buf->GetCapacity() > 4 * PREALLOC_BUFFER_SIZE)
{
// Something made the buffer quite big so make it return to default size to avoid wasting memory.
buf->FreeStorage();
OpStatus::Ignore(buf->Expand(PREALLOC_BUFFER_SIZE)); // If it fails we'll grow it when needed instead.
}
break;
}
}
#if LOGDOC_MIN_ANIM_UPDATE_INTERVAL_DURING_LOADING > 0 || LOGDOC_MIN_ANIM_UPDATE_INTERVAL_LOW > 0
BOOL
LogdocModule::IsThrottlingNeeded(BOOL force)
{
double curr_time = g_op_time_info->GetRuntimeMS();
if (curr_time > m_last_throttling_check_timestamp + g_pccore->GetIntegerPref(PrefsCollectionCore::SwitchAnimationThrottlingInterval))
{
m_cached_throttling_needed = force || (g_message_dispatcher->GetAverageLag() >= g_pccore->GetIntegerPref(PrefsCollectionCore::LagThresholdForAnimationThrottling));
m_last_throttling_check_timestamp = curr_time;
}
return m_cached_throttling_needed;
}
#endif // LOGDOC_MIN_ANIM_UPDATE_INTERVAL_DURING_LOADING > 0 || LOGDOC_MIN_ANIM_UPDATE_INTERVAL_LOW > 0
|
//
// Ball.cpp
// header_redo
//
// Created by Tyler Henry on 11/18/14.
//
//
#include "Ball.h"
//constructor for a ball
Ball::Ball() {
pos.x = ofGetWindowWidth() * 0.5;
pos.y = 0;
//gold(-ish)
r = 218;
g = 183;
b = 74;
}
void Ball::setup() {
//ball radius
radius = 50;
//position
pos.x = ofRandom(radius,(ofGetWindowWidth()-radius)); //between the window edges
pos.y = 0-radius; //start above top of screen
//velocity
vel.x = ofRandom(-5,5); //random X velocity
vel.y = 15; //speed of gravity
//gold(-ish)
r = 218;
g = 183;
b = 74;
}
void Ball::move() {
pos.x += vel.x;
pos.y += vel.y;
}
void Ball::display() {
ofPushStyle();
ofPushMatrix();
//move coordinate system to center of Ball
ofTranslate(pos.x,pos.y);
//set color
ofSetColor(r,g,b);
ofFill();
//draw Ball at translated position
ofCircle(0, 0, radius);
ofPopMatrix();
ofPopStyle();
}
|
//
// Created by 周华 on 2021/5/5.
//
#include "RendererComponent.h"
|
// @author sadmb
// @date 10th,Feb,2014.
// modified from utils/DepthRemapToRange.h of ofxNI2 by @satoruhiga
#pragma once
#include "ofMain.h"
namespace ofxKinect2
{
template <typename PixelType>
struct DoubleBuffer;
} // namespace ofxKinect2
template <typename PixelType>
struct ofxKinect2::DoubleBuffer
{
public:
DoubleBuffer() : front_buffer_index(0), back_buffer_index(1), allocated(false) {}
void allocate(int w, int h, int channels)
{
if (allocated) return;
allocated = true;
pix[0].allocate(w, h, channels);
pix[1].allocate(w, h, channels);
}
bool isAllocated()
{
return pix[0].isAllocated() && pix[1].isAllocated();
}
int getWidth()
{
return pix[0].getWidth();
}
int getHeight()
{
return pix[0].getHeight();
}
void clear()
{
pix[0].clear();
pix[1].clear();
}
PixelType& getFrontBuffer() { return pix[front_buffer_index]; }
const PixelType& getFrontBuffer() const { return pix[front_buffer_index]; }
PixelType& getBackBuffer() { return pix[back_buffer_index]; }
const PixelType& getBackBuffer() const { return pix[back_buffer_index]; }
void swap()
{
std::swap(front_buffer_index, back_buffer_index);
}
private:
PixelType pix[2];
int front_buffer_index, back_buffer_index;
bool allocated;
};
|
class Category_687 {
duplicate = 629;
};
class Category_579 {
duplicate = 629;
};
class Category_635 {
duplicate = 629;
};
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef XSLT_SUPPORT
# include "modules/xslt/src/xslt_textoutputhandler.h"
# include "modules/xslt/src/xslt_outputbuffer.h"
XSLT_TextOutputHandler::XSLT_TextOutputHandler (XSLT_OutputBuffer *buffer)
: buffer (buffer)
{
}
/* virtual */ void
XSLT_TextOutputHandler::StartElementL (const XMLCompleteName &name)
{
}
/* virtual */ void
XSLT_TextOutputHandler::AddAttributeL (const XMLCompleteName &name, const uni_char *value, BOOL id, BOOL specified)
{
}
/* virtual */ void
XSLT_TextOutputHandler::AddTextL (const uni_char *data, BOOL disable_output_escaping)
{
buffer->WriteL (data);
}
/* virtual */ void
XSLT_TextOutputHandler::AddCommentL (const uni_char *data)
{
}
/* virtual */ void
XSLT_TextOutputHandler::AddProcessingInstructionL (const uni_char *target, const uni_char *data)
{
}
/* virtual */ void
XSLT_TextOutputHandler::EndElementL (const XMLCompleteName &name)
{
}
/* virtual */ void
XSLT_TextOutputHandler::EndOutputL ()
{
buffer->EndL ();
}
#endif // XSLT_SUPPORT
|
#ifndef BBPLUS_HPP_INCLUDED
#define BBPLUS_HPP_INCLUDED
#include <regex>
#include "./marks.hpp"
namespace bbplus {
std::string parse(std::string input) {
std::string output = input;
for (int_fast8_t i = 0; i < MARKS_NB; ++i) {
while (std::regex_search(output, MARKS[i].input_regex) == true) {
output = std::regex_replace(
output, MARKS[i].input_regex, MARKS[i].replace_pattern
);
}
}
return output;
}
bool validate(std::string input, std::string mark_name = "") {
for (int_fast8_t i = 0; i < MARKS_NB; ++i) {
if (mark_name == "" || mark_name == MARKS[i].name) {
if (std::regex_match(input, MARKS[i].input_regex) == true) {
return true;
}
}
}
return false;
}
}
#endif
|
#include "arena.h"
#include "globals.h"
#include "doublely_linked_list.h"
#include "goal.h"
#include "wall.h"
#include "pothole.h"
#include "windmill.h"
#include "token.h"
#include "game.h"
#include "sandtrap.h"
//add more elements later
//the order of an arena is walls,potholes,element1,element2,element3,goal,ball
DLinkedList* createLevel1()
{
//394 bytes
DLinkedList* arena = create_dlinkedlist();
//make walls
Wall* walls[6];//186 bytes
walls[0] = create_wall(HORIZONTAL, 0, 0, 127, bounce); // top
walls[1] = create_wall(HORIZONTAL, 0, 127, 127, bounce);// bottom
walls[2] = create_wall(VERTICAL, 0, 0, 127, bounce); // left
walls[3] = create_wall(VERTICAL, 127, 0, 127, bounce); // right
walls[4] = create_wall(VERTICAL, 32,0, 80,bounce);
walls[5] = create_wall(VERTICAL, 80, 32, 95,bounce);
//add walls
for (int i = 0; i < 6; i++)
insertTail(arena, (void*)walls[i]);
//make windmills
Windmill* windmills[3];//84 bytes
windmills[0] = create_windmill(COUNTERCW,57,40,3.14*.13);
windmills[1] = create_windmill(COUNTERCW,13,80,3.14*.06);
windmills[2] = create_windmill(CLOCKWISE,100,15,3.14*.7);
//add windmills
for (int i = 0; i < 3; i++){
insertTail(arena, (void*)windmills[i]);
}
//add 5 tokens
Token* tokens[5];//80 bytes
tokens[0] = create_token(100,114);
tokens[1] = create_token(10,104);
tokens[2] = create_token(64,85);
tokens[3] = create_token(78,29);
tokens[4] = create_token(50,10);
for (int i = 0; i < 5; i++){
insertTail(arena, (void*)tokens[i]);
}
//make potholes
Pothole* potholes[1];//20 bytes
potholes[0] = create_pothole(20,118,8);
//add potholes
insertTail(arena, (void*)potholes[0]);
//make/add goal
insertTail(arena, (void*)create_goal(110,40)); //16 bytes
// Initialize the ball
Ball* ball = (Ball*) malloc(sizeof(Ball)); // 12 bytes
ball->type = BALL;
ball->x = 20;
ball->y = 20;
// Add ball to the arena
// NOTE: The ball should always be last in the arena list, so that the other
// ArenaElements have a chance to compute the Physics updates before the
// ball applies forward euler method.
insertTail(arena, (void*)ball);
return arena;
}
DLinkedList* createLevel2()
{
//384 bytes
DLinkedList* arena = create_dlinkedlist();
//make walls
Wall* walls[5];// 140 bytes
walls[0] = create_wall(HORIZONTAL, 0, 0, 127, bounce); // top
walls[1] = create_wall(HORIZONTAL, 0, 127, 127, bounce);// bottom
walls[2] = create_wall(VERTICAL, 0, 0, 127, bounce); // left
walls[3] = create_wall(VERTICAL, 127, 0, 127, bounce); // right
walls[4] = create_wall(HORIZONTAL,0,96,112,bounce);
//add walls
for (int i = 0; i < 5; i++)
insertTail(arena, (void*)walls[i]);
//add windmills
Windmill* windmills[4]; //112 bytes
windmills[0] = create_windmill(COUNTERCW,17,40,3.14*.13);
windmills[1] = create_windmill(COUNTERCW,17,80,3.14*.06);
windmills[2] = create_windmill(COUNTERCW,47,64,3.14*.7);
windmills[3] = create_windmill(CLOCKWISE,89,72,3.14*.32);
//add windmills
for (int i = 0; i < 4; i++)
insertTail(arena, (void*)windmills[i]);
//add 5 tokens
Token* tokens[5]; //80 bytes
tokens[0] = create_token(10,114);
tokens[1] = create_token(120,104);
tokens[2] = create_token(68,71);
tokens[3] = create_token(78,77);
tokens[4] = create_token(50,120);
for (int i = 0; i < 5; i++)
insertTail(arena, (void*)tokens[i]);
insertTail(arena, (void*)create_sandtrap(64,104,10,30));//24 bytes
//make/add goal
insertTail(arena, (void*)create_goal(10,110));//16 bytes
// Initialize the ball
Ball* ball = (Ball*) malloc(sizeof(Ball));//12 bytes
ball->type = BALL;
ball->x = 20;
ball->y = 20;
insertTail(arena, (void*)ball);
return arena;
}
DLinkedList* createLevel3()
{
//572 bytes
DLinkedList* arena = create_dlinkedlist();
//make walls
Wall* walls[9];//364 bytes
walls[0] = create_wall(HORIZONTAL, 0, 0, 127, bounce); // top
walls[1] = create_wall(HORIZONTAL, 0, 127, 127, bounce);// bottom
walls[2] = create_wall(VERTICAL, 0, 0, 127, bounce); // left
walls[3] = create_wall(VERTICAL, 127, 0, 127, bounce); // right
walls[4] = create_wall(VERTICAL, 32, 0, 64, bounce);
walls[5] = create_wall(VERTICAL, 64, 16, 64,bounce);
walls[6] = create_wall(VERTICAL, 80, 16, 16, bounce);
walls[7] = create_wall(HORIZONTAL, 64,16, 16,bounce);
walls[8] = create_wall(HORIZONTAL,0,96,112,bounce);
//add walls
for (int i = 0; i < 9; i++)
insertTail(arena, (void*)walls[i]);
//add windmills
Windmill* windmills[2];//112 bytes
windmills[0] = create_windmill(COUNTERCW,45,16,3.14*.06);
windmills[1] = create_windmill(COUNTERCW,47,64,3.14*.7);
//add windmills
for (int i = 0; i < 3; i++)
insertTail(arena, (void*)windmills[i]);
//add 5 tokens
Token* tokens[5];//80 bytes
tokens[0] = create_token(10,114);
tokens[1] = create_token(10,104);
tokens[2] = create_token(64,85);
tokens[3] = create_token(78,29);
tokens[4] = create_token(50,10);
for (int i = 0; i < 5; i++)
insertTail(arena, (void*)tokens[i]);
//make potholes
Pothole* potholes[2];//40 bytes
potholes[0] = create_pothole(89,110,4);
potholes[1] = create_pothole(30,110,2);
//add potholes
insertTail(arena, (void*)potholes[0]);
insertTail(arena, (void*)potholes[1]);
//make/add goal
insertTail(arena, (void*)create_goal(110,40));//16 bytes
// Initialize the ball
Ball* ball = (Ball*) malloc(sizeof(Ball));
ball->type = BALL;
ball->x = 20;
ball->y = 20;
insertTail(arena, (void*)ball);
return arena;
}
DLinkedList* copy_arena(DLinkedList* arena1)
{
DLinkedList* newArena = create_dlinkedlist();
ArenaElement* elem = (ArenaElement*)getHead(arena1);
do {
switch(elem->type) {
case WALL:
Wall* wall = create_wall(((Wall*)elem)->direction,((Wall*)elem)->x,((Wall*)elem)->y,
((Wall*)elem)->length,((Wall*)elem)->bounce);
insertTail(newArena,(void*)wall);
break;
case POTHOLE:
Pothole* pothole = create_pothole(((Pothole*)elem)->x,((Pothole*)elem)->y,
((Pothole*)elem)->radius);
insertTail(newArena,(void*)pothole);
break;
case WINDMILL:
Windmill* wm = create_windmill(((Windmill*)elem)->direction,((Windmill*)elem)->x,
((Windmill*)elem)->y, ((Windmill*)elem)->angle);
insertTail(newArena,(void*)wm);
break;
case TOKEN:
Token* token = create_token(((Token*)elem)->x,((Token*)elem)->y);
token->should_erase = ((Token*)elem)->should_erase;
insertTail(newArena,(void*)token);
break;
case SANDTRAP:
Sandtrap* st = create_sandtrap(((Sandtrap*)elem)->x1,((Sandtrap*)elem)->x2,
((Sandtrap*)elem)->y1,((Sandtrap*)elem)->y2);
insertTail(newArena,(void*)st);
break;
case GOAL:
Goal* goal = create_goal(((Goal*)elem)->x,((Goal*)elem)->y);
insertTail(newArena,(void*)goal);
break;
case BALL:
Ball* ball = (Ball*)malloc(sizeof(Ball));
ball->type = BALL;
ball->x = ((Ball*)elem)->x;
ball->y = ((Ball*)elem)->y;
insertTail(newArena,(void*)ball);
break;
default:
break;
}
} while(elem = (ArenaElement*)getNext(arena1));
return newArena;
}
|
#include <stdio.h>
#include <math.h>
#include <vector>
#include <stdlib.h>
using namespace std;
#define EPS 10e-9
#define CASAS_DECIMAIS 2
typedef struct {
double first, second;
int amount;
bool interval;
} number_t;
typedef vector<number_t> vN;
void f_changeMode(vN &numbers, int &mode);
void f_clear();
void f_insertData(vN &numbers, int mode);
int f_menu(int mode);
void f_ShowData(vN &numbers, int mode);
int main () {
int menu, mode = 1;
vN numbers;
while (menu = f_menu(mode), menu) {
switch(menu) {
case 1:
f_changeMode(numbers, mode);
break;
case 2:
f_insertData(numbers, mode);
break;
case 3:
f_ShowData(numbers, mode);
}
}
return 0;
}
void f_changeMode(vN &numbers, int &mode) {
int AuxMode = -1;
while (AuxMode < 0 || AuxMode > 3) {
printf("______________________________\n");
printf("Modos disponíveis:");
printf("0. Distribuição de frequência com intervalo de classe\n");
printf("1. Distribuição de frequência sem intervalo de classe\n");
printf("2. Dados isolados\n\n");
printf("Digite o modo desejado:\n(Lembre-se que ao mudar o modo, todos os dados inseridos anteriormente serão perdidos. Caso queira cancelar, digite 3)\n");
scanf("%d", &AuxMode);
}
if (AuxMode != 3) {
printf("Você trocou do modo (%s) para o modo (%s)", !mode ? "Distribuição de frequências com intervalos de classe":(mode == 1 ? "Distribuição de frequência sem intervalos de classe":"Dados Isolados"), !AuxMode ? "Distribuição de frequências com intervalos de classe":(mode == 1 ? "Distribuição de frequência sem intervalos de classe":"Dados Isolados"));
mode = AuxMode;
numbers.clear();
}
else {
f_clear();
printf("Operação cancelada.\n");
}
}
void f_clear() {
char str[] = {"clear || cls"};
system(str);
}
int f_ComparaNumber(const void
void f_insertData(vN &numbers, int mode) {
int quantidade;
number_t Input;
f_clear();
printf("Digite quantos %s serão inseridos.\n", !mode ? "intervalos de classes": mode == 1? "dados de frequencia":"dados isolados");
scanf("%d", &quantidade);
f_clear();
for (int i = 1; i <= quantidade; i++) {
f_clear();
printf("Digite %s numero %d:\n", !mode ? "o limite inferior e o superior do intervalo e a frequência do intervalo": mode == 1? "o dado e sua frequência":"o dado", i);
scanf("%lf", &Input.first);
if (!mode) scanf("%lf", &Input.second);
if (!mode || mode == 1) scanf("%d", &Input.amount);
Input.interval = !mode;
}
return;
}
int f_menu(int mode) {
int op = -1;
int QUANTIDADE_DE_OPCOES = 3;
while (!(op >= 0 && op <= QUANTIDADE_DE_OPCOES)) {
printf("_____________________________\n");
printf("Modo: %s\n\n", !mode ? "Distribuição de frequências com intervalos de classe":(mode == 1 ? "Distribuição de frequência sem intervalos de classe":"Dados Isolados"));
printf("1. Inserir dados\n");
printf("2. Mostrar dados inseridos\n");
printf("3. Mostrar Média, Desvio Padrão e Quoeficiente de variação dos dados inseridos\n");
printf("0. Sair\n");
printf("______________________________\n\n");
printf("Digite o numero da operação desejada");
scanf("%d", &op);
if (op < 0 && op > QUANTIDADE_DE_OPCOES) {
f_clear();
printf("Opção inválida. Tente novamente.\n");
}
}
return op;
}
void f_ShowData(vN &numbers, int &mode) {
int digits = 0, aux;
sort (numbers.begin(), number.end(), &f_ComparaNumber);
aux = numbers.back();
f_clear();
while (aux) { aux /= 10; digits++; }
if (!mode) printf("Intervalo\t\tFrequência\n");
else if (mode == 1) printf("Dado\t\tFrequência\n");
else printf("Rol de dados");
for (int i = 0; i < (int)numbers.size(); i++) {
if (!mode) {
printf("%.CASAS_DECIMAISlf - %.CASAS_DECIMAISlf\t\t%d\n", numbers[i].first, numbers[i].second, numbers[i].amount);
}
else if (mode == 1) {
printf("%CASAS_DECIMAISlf\t\t%d\n", numbers[i].first, numbers[i].amount);
}
else {
if (!(i%5)) printf("\n");
printf("%CASAS_DECIMAISlf", vetor[i].first);
}
}
printf("\n\n");
}
|
#include <Python.h>
#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <boost/python.hpp>
#include "conversion.h"
#include "brisk/brisk.h"
#include <sys/time.h>
namespace py = boost::python;
static cv::Mat get_gray_img(PyObject *p_img);
static std::vector<cv::KeyPoint> detect(cv::Mat img, PyObject *p_thresh, PyObject *p_octaves);
static PyObject* keypoints_ctopy(std::vector<cv::KeyPoint> keypoints);
static cv::Mat get_gray_img(PyObject *p_img) {
// get image and convert if necessary
NDArrayConverter cvt;
cv::Mat img_temp = cvt.toMat(p_img);
cv::Mat img;
if (img_temp.channels() == 1) {
img = img_temp;
} else {
cv::cvtColor(img_temp, img, CV_BGR2GRAY);
}
return img;
}
static std::vector<cv::KeyPoint> detect(cv::Mat img, PyObject *p_thresh, PyObject *p_octaves) {
// parse python arguments
int thresh;
int octaves;
PyArg_Parse(p_thresh, "i", &thresh);
PyArg_Parse(p_octaves, "i", &octaves);
// detect keypoints
cv::Ptr<cv::FeatureDetector> detector;
detector = new brisk::BriskFeatureDetector(thresh, octaves);
std::vector<cv::KeyPoint> keypoints;
detector->detect(img, keypoints);
return keypoints;
}
static PyObject* keypoints_ctopy(std::vector<cv::KeyPoint> keypoints) {
size_t num_keypoints = keypoints.size();
PyObject* ret_keypoints = PyList_New(num_keypoints);
// import cv2
PyObject* cv2_mod = PyImport_ImportModule("cv2");
for(size_t i = 0; i < num_keypoints; ++i) {
// cv2_keypoint = cv2.KeyPoint()
// TODO: PyInstance_New is maybe better
// cv2_keypoint has maybe a memory leak
PyObject* cv2_keypoint = PyObject_CallMethod(cv2_mod, "KeyPoint", "");
// build values
PyObject* cv2_keypoint_size = Py_BuildValue("f", keypoints[i].size);
PyObject* cv2_keypoint_angle = Py_BuildValue("f", keypoints[i].angle);
PyObject* cv2_keypoint_response = Py_BuildValue("f", keypoints[i].response);
PyObject* cv2_keypoint_pt_x = Py_BuildValue("f", keypoints[i].pt.x);
PyObject* cv2_keypoint_pt_y = Py_BuildValue("f", keypoints[i].pt.y);
// pack into tuple
PyObject* cv2_keypoint_pt = PyTuple_New(2);
PyTuple_SetItem(cv2_keypoint_pt, 0, cv2_keypoint_pt_x);
PyTuple_SetItem(cv2_keypoint_pt, 1, cv2_keypoint_pt_y);
// set attributes
PyObject_SetAttrString(cv2_keypoint, "size", cv2_keypoint_size);
PyObject_SetAttrString(cv2_keypoint, "angle", cv2_keypoint_angle);
PyObject_SetAttrString(cv2_keypoint, "response", cv2_keypoint_response);
PyObject_SetAttrString(cv2_keypoint, "pt", cv2_keypoint_pt);
// add keypoint to list
PyList_SetItem(ret_keypoints, i, cv2_keypoint);
Py_DECREF(cv2_keypoint_size);
Py_DECREF(cv2_keypoint_angle);
Py_DECREF(cv2_keypoint_response);
Py_DECREF(cv2_keypoint_pt_x);
Py_DECREF(cv2_keypoint_pt_y);
Py_DECREF(cv2_keypoint_pt);
}
Py_DECREF(cv2_mod);
return ret_keypoints;
}
PyObject* create() {
brisk::BriskDescriptorExtractor* descriptor_extractor = new brisk::BriskDescriptorExtractor();
return PyCObject_FromVoidPtr(static_cast<void*>(descriptor_extractor), NULL);
}
void destroy(PyObject* p_descriptor_extractor) {
brisk::BriskDescriptorExtractor* descriptor_extractor =
static_cast<brisk::BriskDescriptorExtractor*>(PyCObject_AsVoidPtr(p_descriptor_extractor));
delete descriptor_extractor;
}
PyObject* detect_keypoints(PyObject* p_descriptor_extractor, PyObject *p_img,
PyObject *p_thresh, PyObject *p_octaves) {
cv::Mat img = get_gray_img(p_img);
std::vector<cv::KeyPoint> keypoints = detect(img, p_thresh, p_octaves);
brisk::BriskDescriptorExtractor* descriptor_extractor =
static_cast<brisk::BriskDescriptorExtractor*>(PyCObject_AsVoidPtr(p_descriptor_extractor));
descriptor_extractor->computeAngles(img, keypoints);
PyObject* ret_keypoints = keypoints_ctopy(keypoints);
return ret_keypoints;
}
PyObject* detect_keypoints_no_angles(PyObject *p_img, PyObject *p_thresh, PyObject *p_octaves) {
cv::Mat img = get_gray_img(p_img);
std::vector<cv::KeyPoint> keypoints = detect(img, p_thresh, p_octaves);
PyObject* ret_keypoints = keypoints_ctopy(keypoints);
return ret_keypoints;
}
PyObject* extract_features(PyObject* p_descriptor_extractor,
PyObject *p_img, PyObject *p_keypoints) {
cv::Mat img = get_gray_img(p_img);
Py_ssize_t num_keypoints = PyList_Size(p_keypoints);
std::vector<cv::KeyPoint> keypoints;
for(Py_ssize_t i = 0; i < num_keypoints; ++i) {
keypoints.push_back(cv::KeyPoint());
PyObject* cv2_keypoint = PyList_GetItem(p_keypoints, i);
// get attributes
PyObject* cv2_keypoint_size = PyObject_GetAttrString(cv2_keypoint, "size");
PyObject* cv2_keypoint_angle = PyObject_GetAttrString(cv2_keypoint, "angle");
PyObject* cv2_keypoint_response = PyObject_GetAttrString(cv2_keypoint, "response");
PyObject* cv2_keypoint_pt = PyObject_GetAttrString(cv2_keypoint, "pt");
PyObject* cv2_keypoint_pt_x = PyTuple_GetItem(cv2_keypoint_pt, 0);
PyObject* cv2_keypoint_pt_y = PyTuple_GetItem(cv2_keypoint_pt, 1);
// set data
PyArg_Parse(cv2_keypoint_size, "f", &keypoints[i].size);
PyArg_Parse(cv2_keypoint_angle, "f", &keypoints[i].angle);
PyArg_Parse(cv2_keypoint_response, "f", &keypoints[i].response);
PyArg_Parse(cv2_keypoint_pt_x, "f", &keypoints[i].pt.x);
PyArg_Parse(cv2_keypoint_pt_y, "f", &keypoints[i].pt.y);
Py_DECREF(cv2_keypoint_size);
Py_DECREF(cv2_keypoint_angle);
Py_DECREF(cv2_keypoint_response);
Py_DECREF(cv2_keypoint_pt_x);
Py_DECREF(cv2_keypoint_pt_y);
Py_DECREF(cv2_keypoint_pt);
// TODO: decrement reference doesn't work
// Py_DECREF(cv2_keypoint);
}
cv::Mat descriptors;
brisk::BriskDescriptorExtractor* descriptor_extractor =
static_cast<brisk::BriskDescriptorExtractor*>(PyCObject_AsVoidPtr(p_descriptor_extractor));
descriptor_extractor->compute(img, keypoints, descriptors);
NDArrayConverter cvt;
PyObject* ret = PyList_New(2);
PyObject* ret_keypoints = keypoints_ctopy(keypoints);
PyList_SetItem(ret, 0, ret_keypoints);
PyList_SetItem(ret, 1, cvt.toNDArray(descriptors));
// TODO: decrement reference doesn't work
// Py_DECREF(ret_keypoints);
return ret;
}
PyObject* detect_and_extract(PyObject* p_descriptor_extractor, PyObject *p_img,
PyObject *p_thresh, PyObject *p_octaves) {
cv::Mat img = get_gray_img(p_img);
std::vector<cv::KeyPoint> keypoints = detect(img, p_thresh, p_octaves);
cv::Mat descriptors;
brisk::BriskDescriptorExtractor* descriptor_extractor =
static_cast<brisk::BriskDescriptorExtractor*>(PyCObject_AsVoidPtr(p_descriptor_extractor));
descriptor_extractor->compute(img, keypoints, descriptors);
NDArrayConverter cvt;
PyObject* ret = PyList_New(2);
PyObject* ret_keypoints = keypoints_ctopy(keypoints);
PyList_SetItem(ret, 0, ret_keypoints);
PyList_SetItem(ret, 1, cvt.toNDArray(descriptors));
// TODO: decrement reference doesn't work
// Py_DECREF(ret_keypoints);
return ret;
}
static void init() {
Py_Initialize();
import_array();
}
BOOST_PYTHON_MODULE(pybrisk) {
init();
py::def("create", create);
py::def("destroy", destroy);
py::def("detect_keypoints", detect_keypoints);
py::def("detect_keypoints_no_angles", detect_keypoints_no_angles);
py::def("extract_features", extract_features);
py::def("detect_and_extract", detect_and_extract);
}
|
/*
* Assignment 1 Part 1 Main Function for CS 1337
* Programmer: Medha Aiyah
* Description: This main function is used to make the drink machine and allow the user to by a specific drink.
*4
*/
//These are the appropriate headers used for this function
#include "drinkmachine.h"
using namespace std;
int main()
{
//These are the variables that I am using in this function
//I initialized some of the variables that are being used
DrinkMachine drinkMachine;
bool worked;
double totalSales;
double paid;
double change;
bool endingProgram = false;
worked = create(drinkMachine);
totalSales = 0;
//This is what will happen if the file was opened and it was able to retrieve the information
if(worked)
{
//This is the function used to display the chart of drinks along with their costs, quantity, and sold
dumpDrinkMachine(drinkMachine);
//This is what will happen when the program does not end
while (endingProgram == false)
{
//Asks the user to enter a certain number for the drink they want to get
cout << "Please enter the number of the drink being purchased" << endl;
cout << fixed << setprecision(2);
cout << '\t' << "0 Stop processing drink orders" << endl;
unsigned int typesOfDrinks;
typesOfDrinks = size(drinkMachine);
//Used to display the drinks and their costs
for (unsigned int i = 1; i <= typesOfDrinks; i++)
{
//Alter the widths to make it more like the example
DrinkItem menu = drink(drinkMachine, i);
cout << '\t' << menu.id << setw(16) << menu.name << setw(4) << '$' << menu.price << endl;
}
unsigned int userNum;
//Where the user can put in the number of the drinks they want
cin >> userNum;
//This is what will happen if the user types in 0
if (userNum == 0)
{
endingProgram = true;
}
//This is what will happen if a user types in an invalid number
else if ((userNum < 0) || (userNum > typesOfDrinks))
{
cout << "The drink you requested is not valid" << endl;
endingProgram = false;
}
//This is what will happen if the user types in a number between 1-7
else if(0 < userNum <= typesOfDrinks)
{
//This is what will happen if the drink is available
if (available(drinkMachine, userNum))
{
do
{
//The prompt that is used for the user to pay for the item
cout << "The " << name(drinkMachine, userNum) << " you are requesting costs $" << price(drinkMachine, userNum) << endl;
cout << "Enter the payment amount for the drink: " << endl;
cin >> paid;
endingProgram = false;
}while(!purchase(drinkMachine, userNum, paid, change));
//This is what will happen if the user types in a bigger price amount
if (paid > price(drinkMachine, userNum))
{
change = paid - price(drinkMachine, userNum);
cout << "Your change is $" << change << endl;
cout << "Thank you for your purchase" << endl;
endingProgram = false;
}
//This is what will happen if the user pays the exact price of the drink
if (paid == price(drinkMachine, userNum))
{
cout << "Thank you for your purchase" << endl;
endingProgram = false;
}
}
//This is what will happen if the drink is not available
else
{
cout << "Sorry we are out of " << name(drinkMachine, userNum) << "." << endl;
endingProgram = false;
}
totalSales += price(drinkMachine, userNum);
}
}
//It will print out the drink machine sales at the very end.
cout << "The drink machine sales were $" << totalSales << endl;
destroy(drinkMachine);
}
//This is what will happen if the file is unable to be read
else
{
cout << "The drink machine could not be created" << endl;
}
return 0;
}
|
#ifndef MESH_H
#define MESH_H
#include <vector>
#include <unordered_map>
#include <string>
#include <iostream>
#include <array>
#include <glm/glm.hpp>
#include "commun.h"
#include "resource.h"
struct vertex
{
glm::vec3 position;
glm::vec3 normal;
glm::vec2 texcoord;
};
class mesh
{
uint _vao;
enum
{
INDICES,
VERTEX,
N
};
std::array<uint,N> _vbo;
std::vector<vertex> _vertex;
std::vector<uint16> _indices;
bool _generated;
bool _placeholder[3];
void load_file(std::string path);
void load_obj(std::string path);
public:
mesh(std::string path);
mesh(std::string path, std::vector<vertex> v,std::vector<uint16> i);
~mesh();
void gen();
void degen();
void draw();
};
extern library<mesh> mesh_library;
#endif MESH_H
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Proto.h"
#include "GameFramework/Character.h"
#include "Dragon.generated.h"
DECLARE_MULTICAST_DELEGATE(FOnAttackEndDelegate);
DECLARE_MULTICAST_DELEGATE(FonAlertEndDelegate);
enum AttackPatten
{
Noting,
GrAttack1,
GrAttack2,
GrAttack3
};
UCLASS()
class PROTO_API ADragon : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
ADragon();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
virtual void PostInitializeComponents() override;
float GetHp() { return Hp; }
void SetHp(float NewHp) { Hp = NewHp; }
bool GetAlert() { return IsAlert; }
void SetAlert(bool NewAlert) { IsAlert = NewAlert; }
void Attack();
void AttackCheck();
FOnAttackEndDelegate OnAttackEnd;
FonAlertEndDelegate OnAlertEnd;
void Alert();
bool SelectPattern();
UFUNCTION()
void OnAttackMontageEnded(UAnimMontage * Montage, bool bInterrupted);
private:
UPROPERTY(EditInStanceOnly,Category = Stat,Meta = (AllowPrivateAccess = true))
float Hp;
UPROPERTY()
bool IsAlert; //경계중인지 아닌지
UPROPERTY(VisibleAnywhere,Category = body)
UCapsuleComponent * Head;
UPROPERTY(VisibleAnywhere, Category = body)
UCapsuleComponent * Tail;
UPROPERTY(VisibleAnywhere, Category = Effect)
UParticleSystemComponent * Effect;
UPROPERTY()
class UDRAnimInstance * DRAni;
UPROPERTY(VisibleInstanceOnly,BlueprintReadOnly,Category = Attack,Meta = (AllowPrivateAccess = true))
bool IsAttacking;
AttackPatten Pattern;
FTimerHandle TimerHandle;
void Dash();
void FIreBall();
UFUNCTION()
void OnEffectFinished(class UParticleSystemComponent* PSystem);
};
|
/* -*- Mode: c++; tab-width: 2; indent-tabs-mode: s; c-basic-offset: 2 -*-
**
** Copyright (C) 2012 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "adaptation_layer/system_utils.h"
#include "platforms/windows/includes/platform.h"
namespace opera_update_checker { namespace system_utils {
/* static */ void SystemUtils::Sleep(OAUCTime time)
{
::Sleep(time);
}
/* static */ int SystemUtils::strnicmp(const char* str1, const char* str2, size_t num_chars)
{
return _strnicmp(str1, str2, num_chars);
}
} }
|
/*
* Copyright (C) 2013 Tom Wong. All rights reserved.
*/
#include "gtdoccommand.h"
#include "gtbookmark.h"
#include "gtbookmarks.h"
#include "gtdocmodel.h"
#include "gtdocnote.h"
#include "gtdocnotes.h"
#include <QtCore/QDebug>
GT_BEGIN_NAMESPACE
GtDocCommand::GtDocCommand(GtDocModel *model,
QUndoCommand *parent)
: QUndoCommand(parent)
, m_model(model)
, m_done(false)
{
}
GtDocCommand::~GtDocCommand()
{
}
void GtDocCommand::undo()
{
QUndoCommand::undo();
m_done = false;
}
void GtDocCommand::redo()
{
m_done = true;
QUndoCommand::redo();
}
GtAddNoteCommand::GtAddNoteCommand(GtDocModel *model,
GtDocNote *note,
QUndoCommand *parent)
: GtDocCommand(model, parent)
, m_note(note)
{
setText(QObject::tr("\"Add Bookmark\""));
}
GtAddNoteCommand::~GtAddNoteCommand()
{
if (!m_done)
delete m_note;
}
void GtAddNoteCommand::undo()
{
GtDocCommand::undo();
m_model->notes()->removeNote(m_note);
}
void GtAddNoteCommand::redo()
{
m_model->notes()->addNote(m_note);
GtDocCommand::redo();
}
GtAddBookmarkCommand::GtAddBookmarkCommand(GtDocModel *model,
GtBookmark *parent,
GtBookmark *before,
GtBookmark *bookmark,
QUndoCommand *parentc)
: GtDocCommand(model, parentc)
, m_parent(parent)
, m_before(before)
, m_bookmark(bookmark)
{
if (!m_parent)
m_parent = m_model->bookmarks()->root();
}
GtAddBookmarkCommand::~GtAddBookmarkCommand()
{
if (!m_done)
delete m_bookmark;
}
void GtAddBookmarkCommand::undo()
{
GtDocCommand::undo();
GtBookmarks *bookmarks = m_model->bookmarks();
m_parent->remove(m_bookmark);
emit bookmarks->removed(m_bookmark);
}
void GtAddBookmarkCommand::redo()
{
GtBookmarks *bookmarks = m_model->bookmarks();
m_parent->insert(m_before, m_bookmark);
emit bookmarks->added(m_bookmark);
GtDocCommand::redo();
}
GtRenameBookmarkCommand::GtRenameBookmarkCommand(GtDocModel *model,
GtBookmark *bookmark,
const QString &name,
QUndoCommand *parent)
: GtDocCommand(model, parent)
, m_bookmark(bookmark)
, m_name(name)
{
setText(QObject::tr("\"Rename Bookmark\""));
}
GtRenameBookmarkCommand::~GtRenameBookmarkCommand()
{
}
void GtRenameBookmarkCommand::undo()
{
GtDocCommand::undo();
rename();
}
void GtRenameBookmarkCommand::redo()
{
rename();
GtDocCommand::redo();
}
void GtRenameBookmarkCommand::rename()
{
GtBookmarks *bookmarks = m_model->bookmarks();
QString temp = m_bookmark->title();
m_bookmark->setTitle(m_name);
m_name = temp;
emit bookmarks->updated(m_bookmark, GtBookmark::UpdateTitle);
}
GtDelBookmarkCommand::GtDelBookmarkCommand(GtDocModel *model,
GtBookmark *bookmark,
QUndoCommand *parent)
: GtDocCommand(model, parent)
, m_bookmark(bookmark)
{
setText(QObject::tr("\"Delete Bookmark\""));
m_parent = bookmark->parent();
m_before = bookmark->next();
}
GtDelBookmarkCommand::~GtDelBookmarkCommand()
{
if (m_done)
delete m_bookmark;
}
void GtDelBookmarkCommand::undo()
{
GtDocCommand::undo();
GtBookmarks *bookmarks = m_model->bookmarks();
m_parent->insert(m_before, m_bookmark);
emit bookmarks->removed(m_bookmark);
}
void GtDelBookmarkCommand::redo()
{
GtBookmarks *bookmarks = m_model->bookmarks();
m_parent->remove(m_bookmark);
emit bookmarks->removed(m_bookmark);
GtDocCommand::redo();
}
GT_END_NAMESPACE
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef PI_SHARED_MEMORY
#include "modules/pi/system/OpSharedMemory.h"
#include "platforms/windows_common/utils/OpAutoHandle.h"
#include <climits> // for CHAR_BIT
/** An implementation of OpSharedMemory.
*/
class WindowsOpSharedMemory : public OpSharedMemory
{
private:
/** Internal: Reference counter for the shared memory block.
*/
class RefCounter
{
public:
/// After construction, counter value is 1.
RefCounter();
/// @return true if count equals zero after decrementing, false otherwise.
bool DecrementAndCheck();
void Increment();
private:
LONG m_ref_count;
};
/** Internal: Header to facilitate offset computation. */
struct SharedMemoryHeader
{
SharedMemoryHeader(size_t size) :
size(size)
{}
RefCounter ref_counter;
size_t size;
};
/** Internal: Locker to provide atomic operations. */
class AutoLocker
{
public:
AutoLocker();
OP_STATUS Lock(const Identifier& key);
/// Destructor releases
~AutoLocker();
private:
HANDLE m_semaphore;
};
/** @return Number of bits required to store a pointer on this platform.
*/
static INTPTR GetPlatformBitness();
static bool PlatformBitnessMatches(const Identifier& identifier);
static OP_STATUS CreateSharedMemory(HANDLE& mem, Identifier &identifier_out, size_t size);
static OP_STATUS OpenSharedMemory(HANDLE& mem, const Identifier& identifier);
static OP_STATUS CreateMapping(void*& mapped_pointer_out, HANDLE mem);
/// Creates a SharedMemoryHeader at the begin of mapped_pointer
static void CreateSharedMemoryHeader(void* mapped_pointer, size_t size);
static SharedMemoryHeader& GetHeader(void* mapped_pointer)
{
return *reinterpret_cast<SharedMemoryHeader*>(mapped_pointer);
}
/** Constructor.
*
* Private, use Create() or Open() to get instance.
*
* @param memory Handle to valid, open shared memory obtained through
* CreateFileMapping.
* @param mapped_pointer Pointer mapped to the shared memory, obtained
* through MapViewOfFile.
* @param id Identifier of the memory block. id.key is the number used to
* name the shared memory block during a call to CreateFileMapping. If the
* name was "Local\Opera_sm_1234" it should be equal to 1234. id.platformType
* is the value returned by GetPlatformType().
*/
WindowsOpSharedMemory(HANDLE memory, void* mapped_pointer, Identifier id);
OpAutoHANDLE m_memory_handle;
OpAutoUnmapViewOfFile m_mapped_pointer;
Identifier m_identifier;
OpAutoPtr<CleanupFunctor> m_cleanup_callback;
static LONG m_counter;
static const size_t SHMEM_OBJ_ALIGN = sizeof(double) > sizeof(void*) ?
sizeof(double) : sizeof(void*);
static const size_t SHMEM_OVERHEAD = sizeof(SharedMemoryHeader);
static const size_t SHMEM_START = SHMEM_OVERHEAD +
((SHMEM_OBJ_ALIGN*SHMEM_OVERHEAD - SHMEM_OVERHEAD) % SHMEM_OBJ_ALIGN);
public:
typedef OpSharedMemory::Identifier Identifier;
typedef OpSharedMemory::CleanupFunctor CleanupFunctor;
~WindowsOpSharedMemory();
virtual size_t Size()
{
return GetHeader(m_mapped_pointer).size;
}
// Usable memory is behind the Header.
virtual void* Ptr()
{
return reinterpret_cast<char*>(m_mapped_pointer.get()) + SHMEM_START;
}
virtual const Identifier& GetIdentifier()
{
return m_identifier;
}
virtual void SetCleanupFunctor(OpAutoPtr<CleanupFunctor> cleanupFunctor)
{
m_cleanup_callback = cleanupFunctor;
}
static OP_STATUS Create(size_t size, OpSharedMemory **out);
static OP_STATUS Open(const Identifier& identifier, OpSharedMemory **out);
};
LONG WindowsOpSharedMemory::m_counter = 0;
// Implementation
// AutoLocker
WindowsOpSharedMemory::AutoLocker::AutoLocker() :
m_semaphore(NULL)
{
}
OP_STATUS WindowsOpSharedMemory::AutoLocker::Lock(const Identifier &key)
{
const size_t name_len = 64 + 10 /* "_semaphore" */;
char name[name_len] = { 0 }; // ARRAY OK 2012-08-24 mpawlowski
int result = _snprintf_s(name,
name_len,
"%s_semaphore",
key.Data());
if(result <= 0)
return OpStatus::ERR;
m_semaphore = CreateSemaphoreA(
NULL,
1,
1,
name);
if(!m_semaphore)
return OpStatus::ERR;
DWORD wait_result = WaitForSingleObject(
m_semaphore,
INFINITE);
return wait_result == WAIT_OBJECT_0 ? OpStatus::OK : OpStatus::ERR;
}
WindowsOpSharedMemory::AutoLocker::~AutoLocker()
{
if(m_semaphore)
{
ReleaseSemaphore(m_semaphore, 1, NULL);
CloseHandle(m_semaphore);
}
}
// RefCounter
WindowsOpSharedMemory::RefCounter::RefCounter() : m_ref_count(1)
{
}
bool WindowsOpSharedMemory::RefCounter::DecrementAndCheck()
{
OP_ASSERT(m_ref_count > 0);
return --m_ref_count == 0;
}
void WindowsOpSharedMemory::RefCounter::Increment()
{
++m_ref_count;
}
// SharedMemoryHeader
void WindowsOpSharedMemory::CreateSharedMemoryHeader(
void* mapped_pointer, size_t size)
{
OP_ASSERT(size >= sizeof(SharedMemoryHeader));
new (&(GetHeader(mapped_pointer))) SharedMemoryHeader(size);
}
// WindowsOpSharedMemory
OP_STATUS WindowsOpSharedMemory::OpenSharedMemory(HANDLE& mem, const Identifier &identifier)
{
mem = OpenFileMappingA(
FILE_MAP_ALL_ACCESS, // access rights
false, // child process can inherit handle
identifier.Data()); // name of the file mapping
return mem ? OpStatus::OK : OpStatus::ERR;
}
OP_STATUS WindowsOpSharedMemory::CreateSharedMemory(
HANDLE &mem, Identifier& identifier_out, size_t size)
{
const size_t key_len = 64;
char key[key_len] = { 0 }; // ARRAY OK 2012-08-22 mpawlowski
int result = _snprintf_s(key,
key_len,
"Local\\Opera%d_sm_%X_%X",
GetPlatformBitness(),
GetCurrentProcessId(),
InterlockedIncrement(&m_counter));
// An example name: Local\Opera32_sm_1DC_5
if(result <= 0)
return OpStatus::ERR;
HANDLE handle = CreateFileMappingA(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
size, // maximum object size (low-order DWORD)
key); // name of mapping object
if (!handle)
{
switch(GetLastError())
{
case ERROR_DISK_FULL: return OpStatus::ERR_NO_MEMORY;
default: return OpStatus::ERR;
}
}
RETURN_IF_ERROR(identifier_out.SetCopyData(key, key_len));
mem = handle;
return OpStatus::OK;
}
OP_STATUS WindowsOpSharedMemory::CreateMapping(void*& mapped_pointer_out, HANDLE mem)
{
mapped_pointer_out = MapViewOfFile(
mem, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0, // offset (high-order DWORD)
0, // offset (low-order DWORD)
0 // number of bytes to map, 0 means all
);
return mapped_pointer_out ? OpStatus::OK : OpStatus::ERR;
}
INTPTR WindowsOpSharedMemory::GetPlatformBitness()
{
/* We're assuming all Opera components with same bitness were built with
* the same compilation configuration and are binary-compatible platforms.
*/
return sizeof(char*) * CHAR_BIT;
}
bool WindowsOpSharedMemory::PlatformBitnessMatches(const Identifier& identifier)
{
char bitness_string[16] = { 0 }; // ARRAY OK 24-08-2012 mpawlowski
int result = _snprintf(bitness_string, 16, "Opera%d", GetPlatformBitness());
if(result < 0)
return false;
/* The identifier looks like Local\Opera32_sm_1DC_5, where Opera32 or Opera64
* signifies platform bitness. We search for that substring.*/
return identifier.FindFirst(bitness_string) != OpDataNotFound;
}
OP_STATUS WindowsOpSharedMemory::Create(size_t size,
OpSharedMemory **out)
{
HANDLE mem = 0;
void* mapped_pointer = NULL;
size_t totalSize = size + SHMEM_START;
Identifier id;
RETURN_IF_ERROR(CreateSharedMemory(mem, id, totalSize));
OpAutoHANDLE auto_mem(mem);
RETURN_IF_ERROR(CreateMapping(mapped_pointer, mem));
OpAutoUnmapViewOfFile auto_mapped_pointer(mapped_pointer);
CreateSharedMemoryHeader(mapped_pointer, size);
WindowsOpSharedMemory* windows_shmem = OP_NEW(WindowsOpSharedMemory,
(mem, mapped_pointer, id));
RETURN_OOM_IF_NULL(windows_shmem);
*out = windows_shmem;
auto_mem.release();
auto_mapped_pointer.release();
return OpStatus::OK;
}
OP_STATUS WindowsOpSharedMemory::Open(const Identifier& identifier,
OpSharedMemory **out)
{
if(!PlatformBitnessMatches(identifier))
return OpStatus::ERR_NO_ACCESS;
AutoLocker locker;
RETURN_IF_ERROR(locker.Lock(identifier));
HANDLE mem = 0;
void* mapped_pointer = NULL;
RETURN_IF_ERROR(OpenSharedMemory(mem, identifier));
OpAutoHANDLE auto_mem(mem);
RETURN_IF_ERROR(CreateMapping(mapped_pointer, mem));
OpAutoUnmapViewOfFile auto_mapped_pointer(mapped_pointer);
// Increment RefCounter
GetHeader(mapped_pointer).ref_counter.Increment();
WindowsOpSharedMemory* windows_shmem = OP_NEW(WindowsOpSharedMemory,
(mem, mapped_pointer, identifier));
RETURN_OOM_IF_NULL(windows_shmem);
*out = windows_shmem;
auto_mem.release();
auto_mapped_pointer.release();
return OpStatus::OK;
}
WindowsOpSharedMemory::WindowsOpSharedMemory(
HANDLE memory, void *mapped_pointer, Identifier id) :
m_memory_handle(memory),
m_mapped_pointer(mapped_pointer),
m_identifier(id)
{
}
WindowsOpSharedMemory::~WindowsOpSharedMemory()
{
AutoLocker locker;
OP_CHECK_STATUS(locker.Lock(GetIdentifier()));
// Decrement ref counter and conditional cleanup.
RefCounter& rc = GetHeader(m_mapped_pointer).ref_counter;
if(rc.DecrementAndCheck())
{
// We're the last owner of this shared memory.
// Clean up if there's a callback for that registered:
if(m_cleanup_callback.get())
m_cleanup_callback->Cleanup(Ptr());
}
}
OP_STATUS OpSharedMemory::Create(size_t size, OpSharedMemory **out)
{
return WindowsOpSharedMemory::Create(size, out);
}
OP_STATUS OpSharedMemory::Open(const Identifier& identifier, OpSharedMemory **out)
{
return WindowsOpSharedMemory::Open(identifier, out);
}
#endif // PI_SHARED_MEMORY
|
#include "pch.h"
#include "ppl.h"
#include <iostream>
#include <iostream>
#include"amp.h"
#include<array>
#include<iostream>
using namespace concurrency;
std::vector<accelerator> findAccelerators() {
std::vector<accelerator> accels;
accels = accelerator::get_all();
for (int i = 0; i < accels.size(); i++) {
std::wcout << i + 1 << "th device = " << accels[i].get_description() << ", " << (accels[i].get_is_emulated() ? "enum" : "normal") << std::endl;
}
accels.erase(std::remove_if(accels.begin(), accels.end(), [](accelerator& accel) {return accel.get_is_emulated(); }), accels.end());
return accels;
}
int main()
{
constexpr int dim = 1;
const int size = 100'000'000;
int* arr = new int[size];
#if 0
parallel_for
Concurrency::parallel_for(0, count, 1, [&](int i)
{
});
#else
std::vector<accelerator> accels = findAccelerators();
auto it = std::max_element(accels.begin(), accels.end(), [](const concurrency::accelerator& rhs, const concurrency::accelerator& lhs)
{
return rhs.get_dedicated_memory() < lhs.get_dedicated_memory();
});
concurrency::accelerator accel = *it;
concurrency::extent<dim> ex;
ex[0] = size;
concurrency::array_view<int, dim> view(size, &arr[0]);
parallel_for_each(accel.get_default_view(),
ex,
[=](concurrency::index<dim> gindex) restrict(amp) {
view[gindex] = 333;
}
);
view.synchronize();
#endif
for (int i = 0; i < size; i++) {
std::cout << arr[i] << ",";
}
std::cout << std::endl;
return 0;
}
|
#include "ShapesBlocks.h"
void rectBlocks:: addItem(int a,int b ,int c){
w.push_back(a);
h.push_back(b);
l.push_back(c);
}
|
#include "stdafx.h"
#include "DBUtil.h"
#include <stdexcept>
DBUtil * DBUtil::instance = nullptr;
DBUtil::DBUtil()
{
}
DBUtil::~DBUtil()
{
}
void DBUtil::open(std::string _filename) {
if (sqlite3_open(_filename.c_str(), &conn))
throw std::runtime_error(std::string("Couldn't open database: ") + sqlite3_errmsg(conn));
}
void DBUtil::close() {
if (conn) {
sqlite3_close(conn);
conn = nullptr;
}
}
std::vector<std::vector<std::string>> DBUtil::queryDB(std::string _query) {
if (!conn)
throw std::runtime_error("There's no open database");
sqlite3_stmt * stmt;
std::vector<std::vector<std::string>> rs;
sqlite3_prepare(conn, _query.c_str(), -1, &stmt, NULL);
sqlite3_step(stmt);
while (sqlite3_column_text(stmt, 0))
{
std::vector<std::string> row;
sqlite3_value
for (int i = 0; sqlite3_column_text(stmt, i); ++i)
row.emplace_back(std::string((char *)sqlite3_column_text(stmt, i)));
rs.emplace_back(row);
sqlite3_step(stmt);
}
return rs;
}
|
#include "renderingConfig.h"
//===========================================================================
//! @file renderigConfig.cpp
//! @brief 描画設定管理
//===========================================================================
//---------------------------------------------------------------------------
//! インスタンス取得
//---------------------------------------------------------------------------
RenderingConfig& RenderingConfig::getInstance()
{
static RenderingConfig instance;
return instance;
}
//---------------------------------------------------------------------------
//! 初期化
//---------------------------------------------------------------------------
bool RenderingConfig::initialize()
{
textureType_ = IBLTextureType::Forest;
tmpTextureType_ = IBLTextureType::Forest;
isSkyBox_ = true;
isIBL_ = true;
isTonemapping_ = true;
isShadowmapping_ = true;
isGlare_ = false;
isReflection_ = false;
isToonmapping_ = false;
isFog_ = false;
isWireFrame_ = false;
return true;
}
//---------------------------------------------------------------------------
//! 更新
//---------------------------------------------------------------------------
void RenderingConfig::update()
{
// Tonemap
(isTonemapping_) ? setFilter(FilterType::ToneMapping) : removeFilter(FilterType::ToneMapping);
// Glare
(isGlare_) ? setFilter(FilterType::GaussianBlur) : removeFilter(FilterType::GaussianBlur);
if(!isFog_)
textureType_ = tmpTextureType_;
}
//---------------------------------------------------------------------------
//! 解放
//---------------------------------------------------------------------------
void RenderingConfig::cleanup()
{
}
//---------------------------------------------------------------------------
//! ImGui描画
//---------------------------------------------------------------------------
void RenderingConfig::showImGuiWindow(DemoSceneType sceneType)
{
switch(sceneType) {
case DemoSceneType::Light:
this->showImGuiLight();
break;
case DemoSceneType::Sea:
this->showImGuiSea();
break;
case DemoSceneType::Water:
this->showImGuiWater();
break;
}
}
//---------------------------------------------------------------------------
//! ImGui描画(ライト)
//---------------------------------------------------------------------------
void RenderingConfig::showImGuiLight()
{
ImGui::Begin("RenderingConfig");
{
//
if(ImGui::TreeNode("RenderingConfig")) {
// Tonemap
ImGui::Checkbox("Tonemap", &isTonemapping_);
// Shadowmap
ImGui::Checkbox("Shadowmap", &isShadowmapping_);
// Glare
if(ImGui::Checkbox("Glare", &isGlare_)) {
if(isGlare_) {
isWireFrame_ = false;
isFog_ = false;
}
}
// Reflection
if(ImGui::Checkbox("Reflection", &isReflection_)) {
isToonmapping_ = false;
isFog_ = false;
}
// Toon
if(ImGui::Checkbox("ToonShader", &isToonmapping_)) {
isReflection_ = false;
isFog_ = false;
isWireFrame_ = false;
}
// Fog
if(ImGui::Checkbox("Fog", &isFog_)) {
isToonmapping_ = false;
isReflection_ = false;
if(isFog_) {
tmpTextureType_ = textureType_;
}
textureType_ = IBLTextureType::NullBlack;
}
// WireFrame
if(ImGui::Checkbox("WireFrame", &isWireFrame_)) {
if(isWireFrame_) {
isToonmapping_ = false;
isGlare_ = false;
}
}
ImGuiAbridgeIBL();
ImGui::TreePop();
}
} // END
if(!isIBL_)
textureType_ = IBLTextureType::NullBlack;
else
textureType_ = tmpTextureType_;
ImGui::End();
}
//---------------------------------------------------------------------------
//! ImGui描画(海)
//---------------------------------------------------------------------------
void RenderingConfig::showImGuiSea()
{
ImGui::Begin("RenderingConfig");
{
//
if(ImGui::TreeNode("RenderingConfig")) {
// Tonemap
ImGui::Checkbox("Tonemap", &isTonemapping_);
// WireFrame
if(ImGui::Checkbox("WireFrame", &isWireFrame_)) {
if(isWireFrame_) {
isToonmapping_ = false;
}
}
ImGuiAbridgeIBL();
ImGui::TreePop();
}
} // END
if(!isIBL_)
textureType_ = IBLTextureType::NullBlack;
else
textureType_ = tmpTextureType_;
ImGui::End();
}
//---------------------------------------------------------------------------
//! ImGui描画(水)
//---------------------------------------------------------------------------
void RenderingConfig::showImGuiWater()
{
ImGui::Begin("RenderingConfig");
{
//
if(ImGui::TreeNode("RenderingConfig")) {
// Tone
ImGui::Checkbox("Tonemap", &isTonemapping_);
// Glare
if(ImGui::Checkbox("Glare", &isGlare_)) {
if(isGlare_) {
isWireFrame_ = false;
}
}
// WireFrame
if(ImGui::Checkbox("WireFrame", &isWireFrame_)) {
if(isWireFrame_) {
isToonmapping_ = false;
isGlare_ = false;
}
}
ImGuiAbridgeIBL();
ImGui::TreePop();
}
} // END
if(!isIBL_)
textureType_ = IBLTextureType::NullBlack;
else
textureType_ = tmpTextureType_;
ImGui::End();
}
//---------------------------------------------------------------------------
//! ImGuiの同じ処理まとめてるだけ abridge=短縮
//---------------------------------------------------------------------------
void RenderingConfig::ImGuiAbridgeIBL()
{
// IBL
if(ImGui::TreeNode("IBL")) {
ImGui::Checkbox("IBL", &isIBL_);
if(ImGui::Button("Wilderness")) {
textureType_ = IBLTextureType::Wilderness;
tmpTextureType_ = textureType_;
isFog_ = false;
isIBL_ = true;
}
if(ImGui::Button("Forest")) {
textureType_ = IBLTextureType::Forest;
tmpTextureType_ = textureType_;
isFog_ = false;
isIBL_ = true;
}
if(ImGui::Button("RuinCastle")) {
textureType_ = IBLTextureType::RuinCastle;
tmpTextureType_ = textureType_;
isFog_ = false;
isIBL_ = true;
}
if(ImGui::Button("BlueSky")) {
textureType_ = IBLTextureType::BlueSky;
tmpTextureType_ = textureType_;
isFog_ = false;
isIBL_ = true;
}
ImGui::TreePop();
}
}
//---------------------------------------------------------------------------
//! 使用したいIBLテクスチャタイプ設定
//---------------------------------------------------------------------------
void RenderingConfig::setIBLTextureType(IBLTextureType type)
{
textureType_ = type;
tmpTextureType_ = type;
}
//---------------------------------------------------------------------------
//! スカイボックス有効,無効
//---------------------------------------------------------------------------
void RenderingConfig::isSkyBox(bool flag)
{
isSkyBox_ = flag;
}
//---------------------------------------------------------------------------
//! IBL有効,無効
//---------------------------------------------------------------------------
void RenderingConfig::isIBL(bool flag)
{
isIBL_ = flag;
}
//---------------------------------------------------------------------------
//! シャドウマップ有効,無効
//---------------------------------------------------------------------------
void RenderingConfig::isShadowmapping(bool flag)
{
isShadowmapping_ = flag;
}
//---------------------------------------------------------------------------
//! 環境反射有効,無効
//---------------------------------------------------------------------------
void RenderingConfig::isReflection(bool flag)
{
isReflection_ = flag;
}
//---------------------------------------------------------------------------
//! トーンマップ有効,無効
//---------------------------------------------------------------------------
void RenderingConfig::isTonemapping(bool flag)
{
isTonemapping_ = flag;
}
//---------------------------------------------------------------------------
//! 霧有効,無効
//---------------------------------------------------------------------------
void RenderingConfig::isFog(bool flag)
{
isFog_ = flag;
}
//---------------------------------------------------------------------------
//! ワイヤーフレーム有効,無効
//---------------------------------------------------------------------------
void RenderingConfig::isWireFrame(bool flag)
{
isWireFrame_ = flag;
}
//---------------------------------------------------------------------------
//! グレアフィルター有効,無効
//---------------------------------------------------------------------------
void RenderingConfig::isGlare(bool flag)
{
isGlare_ = flag;
}
//---------------------------------------------------------------------------
//! IBLテクスチャタイプ取得
//---------------------------------------------------------------------------
IBLTextureType RenderingConfig::getIBLTextureType() const
{
return textureType_;
}
//---------------------------------------------------------------------------
//! スカイボックス
//---------------------------------------------------------------------------
bool RenderingConfig::isSkyBox() const
{
return isSkyBox_;
}
//---------------------------------------------------------------------------
//!< IBL
//---------------------------------------------------------------------------
bool RenderingConfig::isIBL() const
{
return isIBL_;
}
//---------------------------------------------------------------------------
//! シャドウマップ
//---------------------------------------------------------------------------
bool RenderingConfig::isShadowmapping() const
{
return isShadowmapping_;
}
//---------------------------------------------------------------------------
//! 環境反射
//---------------------------------------------------------------------------
bool RenderingConfig::isReflection() const
{
return isReflection_;
}
//---------------------------------------------------------------------------
//! トーンマップ
//---------------------------------------------------------------------------
bool RenderingConfig::isToonmapping() const
{
return isToonmapping_;
}
//---------------------------------------------------------------------------
//! 霧
//---------------------------------------------------------------------------
bool RenderingConfig::isFog() const
{
return isFog_;
}
//---------------------------------------------------------------------------
//! ワイヤーフレーム
//---------------------------------------------------------------------------
bool RenderingConfig::isWireFrame() const
{
return isWireFrame_;
}
//---------------------------------------------------------------------------
//! グレアフィルター
//---------------------------------------------------------------------------
bool RenderingConfig::isGlare() const
{
return isGlare_;
}
|
/*
Copyright (c) 2014 Mircea Daniel Ispas
This file is part of "Push Game Engine" released under zlib license
For conditions of distribution and use, see copyright notice in Push.hpp
*/
#pragma once
#include <cstdint>
namespace Push
{
enum class LogType : uint32_t
{
Info,
Warning,
Error,
Count
};
void Log(LogType type, const char* module, const char* format, ...);
void Log(bool condition, LogType type, const char* module, const char* format, ...);
}
|
#include <unistd.h>
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
#include "process.h"
#include "linux_parser.h"
using std::string;
using std::to_string;
using std::vector;
Process::Process(int ID) : PassID(ID) {
}
// TODO: Return this process's ID
int Process::Pid(){
return PassID;
}
// TODO: Return this process's CPU utilization
float Process::CpuUtilization() {
// Idea from https://stackoverflow.com/questions/16726779/how-do-i-get-the-total-cpu-usage-of-an-application-from-proc-pid-stat/16736599#16736599
long seconds = Process::UpTime();
long total_time = LinuxParser::ActiveJiffies(Process::Pid())/sysconf(_SC_CLK_TCK);
cpu_usage = total_time/(float)seconds;
return cpu_usage;
}
// TODO: Return the command that generated this process
string Process::Command() { return LinuxParser::Command(Process::Pid()); }
// TODO: Return this process's memory utilization
string Process::Ram() { return LinuxParser::Ram(Process::Pid()); }
// TODO: Return the user (name) that generated this process
string Process::User() { return LinuxParser::User(Process::Pid()); }
// TODO: Return the age of this process (in seconds)
long int Process::UpTime() { return LinuxParser::UpTime(Process::Pid()); }
// TODO: Overload the "less than" comparison operator for Process objects
// REMOVE: [[maybe_unused]] once you define the function
bool Process::operator<(Process const& a) const {
return cpu_usage < a.cpu_usage;
}
|
#include "scoreform.h"
#include "ui_scoreform.h"
#include <QStringListModel>
#include <QDebug>
bool moreThan( const QString& v1, const QString& v2 )
{
return v1.toInt() > v2.toInt();
}
ScoreForm::ScoreForm(QWidget *parent)
: QDialog(parent)
, ui(new Ui::ScoreForm)
, m_settings("Trainer", "Multiplication")
{
ui->setupUi(this);
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addScore()));
connect(ui->nameLineEdit, SIGNAL(textChanged(QString)),
this, SLOT(updateName()));
connect(ui->closeButton, SIGNAL(clicked()),
this, SLOT(close()));
updateScoreList();
}
ScoreForm::~ScoreForm()
{
delete ui;
}
void ScoreForm::setScore(int score)
{
ui->score->setText(QString::number(score));
ui->nameLineEdit->setText(m_settings.value("LastName").toString());
ui->nameLineEdit->setEnabled(true);
}
void ScoreForm::addScore()
{
m_settings.setValue(ui->score->text(), ui->nameLineEdit->text());
m_settings.setValue("LastName", ui->nameLineEdit->text());
m_settings.sync();
updateScoreList();
ui->nameLineEdit->setEnabled(false);
ui->addButton->setEnabled(false);
}
void ScoreForm::updateName()
{
ui->addButton->setEnabled(ui->nameLineEdit->text().count() != 0);
}
void ScoreForm::updateScoreList()
{
QStringList scores = m_settings.allKeys();
scores.removeAll("LastName");
qSort(scores.begin(), scores.end(), moreThan);
QStringList nameWithScoreList;
foreach (const QString &score, scores) {
nameWithScoreList.append(QString("%1 - %2 Punkte").arg(m_settings.value(score).toString(), score));
}
ui->listView->setModel(new QStringListModel(nameWithScoreList));
}
|
#ifndef STATS_H
#define STATS_H
#include <cmath>
#include <iostream>
#include <QDialog>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlTableModel>
#include <QTableView>
#include <QMessageBox>
#include <QSqlQuery>
#include <QtSql/QSqlDriver>
namespace Ui {
class Stats;
}
class Stats : public QDialog
{
Q_OBJECT
public:
explicit Stats(QWidget *parent = nullptr);
~Stats();
void setData(QString username);
float standard_deviation(int size, QList<float> values);
float variance(int size, QList<float> values);
float calc_median(int size, QList<float> values);
float sample_mean(int size, QList<float> values);
bool Lv1Clear=false;
bool Lv2Clear=false;
bool Lv3Clear=false;
bool Lv4Clear=false;
bool Lv5Clear=false;
bool Lv6Clear=false;
bool Lv7Clear=false;
bool Lv8Clear=false;
bool Lv9Clear=false;
private slots:
void on_pushButton_back_clicked();
private:
Ui::Stats *ui;
signals:
void closeStatsWindow();
};
#endif // STATS_H
|
#include <iostream>
int calc_fib(int n) {
int fib_arr[n + 1];
fib_arr[0] = 0;
fib_arr[1] = 1;
for(int i = 2; i < n + 1; i++) {
fib_arr[i] = fib_arr[i - 1] + fib_arr[i - 2];
}
return fib_arr[n];
}
int main() {
int n = 0;
std::cin >> n;
std::cout << calc_fib(n) << '\n';
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.