text
stringlengths 8
6.88M
|
|---|
#include "Bag.h"
#include "BagIterator.h"
#include "ShortTest.h"
#include "ExtendedTest.h"
#include <iostream>
#include<vector>
#include <assert.h>
using namespace std;
int main() {
testAll();
cout << "Short tests over" << endl;
testAllExtended();
return 0;
}
|
/***************************************************************************
* Filename : OpenGLContext.cpp
* Name : Ori Lazar
* Date : 29/10/2019
* Description : Implements the OpenGL Context handling interface.
.---.
.'_:___".
|__ --==|
[ ] :[|
|__| I=[|
/ / ____|
|-/.____.'
/___\ /___\
***************************************************************************/
#include "expch.h"
#include "OpenGLContext.h"
#include <GLFW/glfw3.h>
#include <glad/glad.h>
namespace Exalted
{
OpenGLContext::OpenGLContext(GLFWwindow* windowHandle)
: m_WindowHandle(windowHandle)
{
EX_CORE_ASSERT(m_WindowHandle, "Window handle is null!");
}
void OpenGLContext::Init()
{
glfwMakeContextCurrent(m_WindowHandle);
const int status = gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress));
EX_CORE_ASSERT(status, "Failed to initialize Glad!");
OpenGLContext::GetInfo();
}
void OpenGLContext::SwapBuffers()
{
glfwSwapBuffers(m_WindowHandle);
}
void OpenGLContext::GetInfo()
{
EX_CORE_INFO("\n-----------------------------------------\nRendering Information:\n GPU Vendor : {0}\n GPU Renderer : {1}\n GPU Driver : Version {2}\n-----------------------------------------", glGetString(GL_VENDOR), glGetString(GL_RENDERER), glGetString(GL_VERSION));
}
}
|
// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "MeshBuffer.h"
#include "MeshBufferResource.h"
#include "Buffer.h"
#include "Renderer.h"
#include "core/Engine.h"
namespace ouzel
{
namespace graphics
{
MeshBuffer::MeshBuffer()
{
resource = sharedEngine->getRenderer()->createMeshBuffer();
}
MeshBuffer::~MeshBuffer()
{
if (sharedEngine && resource) sharedEngine->getRenderer()->deleteResource(resource);
}
bool MeshBuffer::init(uint32_t newIndexSize, const std::shared_ptr<Buffer>& newIndexBuffer,
const std::vector<VertexAttribute>& newVertexAttributes, const std::shared_ptr<Buffer>& newVertexBuffer)
{
indexBuffer = newIndexBuffer;
vertexBuffer = newVertexBuffer;
if (!resource->init(newIndexSize, newIndexBuffer ? newIndexBuffer->getResource() : nullptr,
newVertexAttributes, newVertexBuffer ? newVertexBuffer->getResource() : nullptr))
{
return false;
}
sharedEngine->getRenderer()->uploadResource(resource);
return true;
}
uint32_t MeshBuffer::getIndexSize() const
{
return resource->getIndexSize();
}
bool MeshBuffer::setIndexSize(uint32_t newIndexSize)
{
if (!resource->setIndexSize(newIndexSize))
{
return false;
}
sharedEngine->getRenderer()->uploadResource(resource);
return true;
}
bool MeshBuffer::setIndexBuffer(const std::shared_ptr<Buffer>& newIndexBuffer)
{
indexBuffer = newIndexBuffer;
if (!resource->setIndexBuffer(newIndexBuffer ? newIndexBuffer->getResource() : nullptr))
{
return false;
}
sharedEngine->getRenderer()->uploadResource(resource);
return true;
}
uint32_t MeshBuffer::getVertexSize() const
{
return resource->getVertexSize();
}
const std::vector<VertexAttribute>& MeshBuffer::getVertexAttributes() const
{
return resource->getVertexAttributes();
}
bool MeshBuffer::setVertexAttributes(const std::vector<VertexAttribute>& newVertexAttributes)
{
if (!resource->setVertexAttributes(newVertexAttributes))
{
return false;
}
sharedEngine->getRenderer()->uploadResource(resource);
return true;
}
bool MeshBuffer::setVertexBuffer(const std::shared_ptr<Buffer>& newVertexBuffer)
{
vertexBuffer = newVertexBuffer;
if (!resource->setVertexBuffer(newVertexBuffer ? newVertexBuffer->getResource() : nullptr))
{
return false;
}
sharedEngine->getRenderer()->uploadResource(resource);
return true;
}
} // namespace graphics
} // namespace ouzel
|
#include "../../Dependencies/glew/glew.h"
#include "../../Dependencies/freeglut/freeglut.h"
#include "Shader_Loader/Shader_Loader.hpp"
#include "Game_Models/Game_Models.hpp"
#include <iostream>
using namespace Core;
GLuint program;
Models::GameModels* gameModels;
void renderScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.1, 0.3, 0.5, 1.0);
glBindVertexArray(gameModels->getModel("triangle1"));
// Use the created program
glUseProgram(program);
// Draw 3 vertices as triangle
glDrawArrays(GL_TRIANGLES, 0, 3);
glutSwapBuffers();
}
void closeCallback()
{
std::cout << "GLUT:\ Finished" << std::endl;
glutLeaveMainLoop();
}
void Init()
{
glEnable(GL_DEPTH_TEST);
gameModels = new Models::GameModels();
gameModels->createTriangleModel("triangle1");
// Load and compile shaders
Core::ShaderLoader shaderLoader;
program = shaderLoader.createProgram("Source\\Shaders\\Vertex_Shader.glsl", "Source\\Shaders\\Fragment_Shader.glsl");
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(500, 500);
glutInitWindowSize(800, 600);
glutCreateWindow("First Triangle");
glewInit();
Init();
if (glewIsSupported("GL_VERSION_4_4"))
std::cout << "GLEW version is 4.4" << std::endl;
else
std::cout << "GLEW 4.4 not supported" << std::endl;
glutDisplayFunc(renderScene);
glutCloseFunc(closeCallback);
glutMainLoop();
glDeleteProgram(program);
delete gameModels;
return 0;
}
|
#include<iostream>
using namespace std;
int sumOfN(int n){
if (n==0)
{
return 0;
}
else
{
return sumOfN(n-1)+n;
}
}
int main(int argc, char const *argv[])
{
cout<<sumOfN(5);
return 0;
}
|
#ifndef MESA_H
#define MESA_H
#include <graphics.h>
#include <sstream>
#include <string>
#include <iostream>
#include <graphics.h>
#include "Pieza.h"
using namespace std;
class Mesa
{
private:
int x1, x2, y1, y2; //Coordenadas necesarias para graficar un bar3d.
Pieza * ficha; //Si se encuentra la ficha dentro de las coordenadas la graficara.
public:
Mesa();
Mesa(Pieza *, int, int, int, int); //Recibe las coordenadas para dibujar el cuadro y una pieza o NULL.
bool getPos(int, int); //Metodo de verificacion de coordenadas que recibe un X y Y.
int getX1(); //Este y el siguiente metodo retorna las coordenadas para la esquina superior izquierda.
int getY1();
int getX2(); //Y este retorna las coordenadas para la esquina inferior izquierda.
int getY2();
void setFicha(Pieza *);
void DibujarTablero(); //Dibujar un cuadro segun las coordenadas y dibuja la ficha si es diferente de NULL.
Pieza * getFicha(); //Retorna la ficha segun las coordenadas.
void DibujarFicha(); //Toma los dos X y los Y para crear un tercer auxiliar para tener el centro del cuadro necesario para dibujar la pieza.
void imprimirFicha(); //Configura el centro del cuadro para dibujar la ficha.
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"
int32_t main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int t , arr[t];
cin>>t;
for(int i = 0; i<t ; i++)
{
cin>>arr[i];
}
vector<int> v;
stack<int> s;
for(int i = t - 1; i>=0; i--)
{
if(s.size() == 0)
{
v.push_back(-1);
}
}
return 0;
}
|
//---------------------------------------------------------------------------
#include <vcl.h>
#include "MainForm.h"
#pragma hdrstop
#include "OverallSettingsForm.h"
#include "S9Utils.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TFormOverallSettings *FormOverallSettings;
using namespace S9Utils;
//---------------------------------------------------------------------------
__fastcall TFormOverallSettings::TFormOverallSettings(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TFormOverallSettings::FormClose(TObject *Sender, TCloseAction &Action)
{
Release();
}
//---------------------------------------------------------------------------
void __fastcall TFormOverallSettings::FormDestroy(TObject *Sender)
{
if (ProgramData) delete ProgramData;
}
//---------------------------------------------------------------------------
void __fastcall TFormOverallSettings::FormCreate(TObject *Sender)
{
ButtonSend->Enabled = false;
ProgramData = NULL;
int iError = RefreshAll();
if (iError < 0)
{
if (iError != -1)
ShowMessage("Unable to refresh settings! (code=" + String(iError) + ")");
if (LoadDefaults() < 0)
return;
iError = ToGui(); // Display OverallSettings struct
if (iError < 0)
{
if (iError != -1)
ShowMessage("Unable to load from machine (ToGui())! (code=" + String(iError) + ")");
return;
}
ComboBoxBaudRate->Hint = "Sets a new baud-rate at both the machine and in this program\n"
"when you click \"Send\". If you change this and communication\n"
"stops working, you must reset the baud rate manually at both the\n"
"machine and in the main window of this program!";
ShowMessage("Defaults loaded. You need to press \"Refresh\" once the machine is connected...");
}
}
//---------------------------------------------------------------------------
void __fastcall TFormOverallSettings::FormShow(TObject *Sender)
{
// Drop the program-name list down
if (ComboBoxProgNames->Items->Count && !ComboBoxProgNames->DroppedDown)
ComboBoxProgNames->DroppedDown = true;
}
//---------------------------------------------------------------------------
// return 0 if success
int __fastcall TFormOverallSettings::RefreshCatalog(void)
{
try
{
int iError = FormMain->GetCatalog();
if (iError < 0)
{
if (iError == -2)
ShowMessage("Transmit timeout requesting catalog!");
else if (iError == -3)
ShowMessage("Timeout receiving catalog!");
else if (iError == -4)
ShowMessage("Incorrect catalog received!");
else
ShowMessage("Not able to get catalog, check power and cables... (code=" + String(iError) + ")");
return -1;
}
// Invoke property getters in FormMain that create string-lists.
// (MUST delete on destroy or prior to reinvoking!)
if (ProgramData)
delete ProgramData;
ProgramData = FormMain->CatalogProgramData;
if (!ProgramData)
return -2;
return 0;
}
catch(...)
{
return -100;
}
}
//---------------------------------------------------------------------------
void __fastcall TFormOverallSettings::ButtonCloseClick(TObject *Sender)
{
Close();
}
//---------------------------------------------------------------------------
void __fastcall TFormOverallSettings::ButtonRefreshClick(TObject *Sender)
{
if (IsBusy())
return;
try
{
FormMain->BusyCount++;
int iError = RefreshAll();
if (iError < 0)
{
if (iError != -1)
ShowMessage("Unable to refresh settings! (code=" + String(iError) + ")");
}
}
__finally
{
FormMain->BusyCount--;
}
}
//---------------------------------------------------------------------------
// return 0 if success, negative if fail
int __fastcall TFormOverallSettings::RefreshAll(void)
{
ButtonSend->Enabled = false;
// load catalog into ProgramData
int iError = RefreshCatalog();
if (iError < 0)
{
if (iError != -1)
ShowMessage("Unable to load catalog! (code=" + String(iError) + ")");
return -1;
}
// add programs to combo box with index in the objects list
ComboBoxProgNames->Items->Assign(ProgramData);
// load overall settings
iError = LoadFromMachine();
if (iError < 0)
{
if (iError != -1)
ShowMessage("Unable to load overall settings! (code=" + String(iError) + ")");
return -1;
}
ButtonSend->Enabled = true;
return 0;
}
//---------------------------------------------------------------------------
void __fastcall TFormOverallSettings::ButtonSendClick(TObject *Sender)
{
int iError = SendToMachine();
if (iError < 0)
{
if (iError != -1)
ShowMessage("Unable to send overall settings! (code=" + String(iError) + ")");
return;
}
}
//---------------------------------------------------------------------------
int __fastcall TFormOverallSettings::SendToMachine(void)
{
// don't allow multiple button presses
if (IsBusy())
return -1;
try
{
FormMain->BusyCount++;
try
{
// Save the machine's baud-rate that's working right now...
UInt32 OldBaudRate = OverallSettings.BaudRate;
int iError = FromGui(); // Load OverallSettings struct from GUI
if (iError < 0)
{
if (iError != -1)
ShowMessage("Unable to send to machine (FromGui())! (code=" + String(iError) + ")");
return -1;
}
// convert OverallSettings struct to os[]
iError = ToArray();
if (iError < 0)
{
if (iError != -1)
ShowMessage("Unable to send to machine (ToArray())! (code=" + String(iError) + ")");
return -1;
}
// send overall settings to Akai S950/S900, with delay
if (!FormMain->comws(OSSIZ, os, true))
{
ShowMessage("Unable to send... try again or close...");
return -1;
}
// trigger baud rate change in FormMain if user just changed baud-rate on machine!
if (OverallSettings.BaudRate != OldBaudRate)
{
// add timeout seconds for slower baud-rate...
int iTimeoutTime = OldBaudRate < 19200 ? TXTIMEOUT+2 : TXTIMEOUT;
// wait for comws() above to complete...
if (FormMain->WaitTxCom(iTimeoutTime) < 0)
{
ShowMessage("Unable to verify empty transmit buffer...");
return -1;
}
FormMain->BaudRate = OverallSettings.BaudRate;
}
}
catch(...)
{
return -100;
}
}
__finally
{
FormMain->BusyCount--;
}
return 0;
}
//---------------------------------------------------------------------------
int __fastcall TFormOverallSettings::LoadFromMachine(void)
{
try
{
// receive overall settings from Akai S950/S900
int iError = FormMain->LoadOverallSettingsToTempArray(); // get the overall settings into TempArray
if (iError < 0)
{
switch(iError)
{
case -2:
ShowMessage("transmit timeout!");
break;
case -3:
ShowMessage("timeout receiving sample parameters!");
break;
case -4:
ShowMessage("received wrong bytecount for overall settings!");
break;
case -5:
ShowMessage("bad checksum for overall settings!");
break;
case -6:
ShowMessage("exception in LoadOverallSettingsToTempArray()!");
break;
default:
break;
};
return -1; // could not get sample parms
}
// copy TempArray to os[]
memcpy(os, FormMain->TempArray, OSSIZ);
// convert os[] to OverallSettings struct
iError = FromArray();
if (iError < 0)
{
if (iError != -1)
ShowMessage("Unable to load from machine (FromArray())! (code=" + String(iError) + ")");
return -1;
}
iError = ToGui(); // Display OverallSettings struct
if (iError < 0)
{
if (iError != -1)
ShowMessage("Unable to load from machine (ToGui())! (code=" + String(iError) + ")");
return -1;
}
return 0;
}
catch(...)
{
return -100;
}
}
//---------------------------------------------------------------------------
// encodes Program Header into the os[7+80+2] (akai-formatted) array
int __fastcall TFormOverallSettings::ToArray(void)
{
try
{
// Clear array to all 0
// in this case - we don't clear because we need to retain the reserved
// data that we loaded from the machine when the form was created...
//memset(os, 0, OSSIZ);
os[0] = BEX;
os[1] = AKAI_ID;
os[2] = 0;
os[3] = OVS; // overall settings
os[4] = S900_ID;
os[5] = 0; // undefined
os[6] = 0;
// copy ASCII sample name, pad with blanks and terminate
AsciiStrEncode(&os[PRONAME], OverallSettings.ProgName);
encodeDB(OverallSettings.MidiTxEx , &os[MDXTCH]);
encodeDW(OverallSettings.RxSimChan, &os[RSCHNL]);
encodeDW(OverallSettings.RxSimKey, &os[RSKEY]);
encodeDW(OverallSettings.RxSimVel, &os[RSVEL]);
Byte temp = OverallSettings.MidiChan | (OverallSettings.bOmniOn ? 128 : 0);
encodeDB(temp, &os[BASMCH]);
temp = OverallSettings.bRxLoudCtrl7 ? 1 : 0;
encodeDB(temp, &os[MLEN]);
temp = OverallSettings.bCtrlByRs232 ? 2 : 1;
encodeDB(temp, &os[M1RS2]);
// here, at least for the S900, we have two reserved constants
// Don't need to set these if not clearing os (above)
// encodeDW(20727, &os[OSCONST1]);
// encodeDW(7238, &os[OSCONST2]);
encodeDB(OverallSettings.PitchWheelRange, &os[PWRANGE]);
encodeDW(OverallSettings.BaudRate/10, &os[RSBAUD]);
// checksum is exclusive or of 7-86 (80 bytes)
// and the value is put in index 87
compute_checksum(7, 87, os);
os[88] = EEX;
return 0;
}
catch(...)
{
return -100;
}
}
//---------------------------------------------------------------------------
// decodes ProgHeader (the working-set ProgramHeader.ProgName struct) from the
// pg[76+7] (akai-formatted) array
int __fastcall TFormOverallSettings::FromArray(void)
{
try
{
// ASCII sample name
AsciiStrDecode(OverallSettings.ProgName, &os[PRONAME]);
OverallSettings.MidiTxEx = decodeDB(&os[MDXTCH]);
OverallSettings.RxSimChan = decodeDW(&os[RSCHNL]);
OverallSettings.RxSimKey = decodeDW(&os[RSKEY]);
OverallSettings.RxSimVel = decodeDW(&os[RSVEL]);
Byte temp = decodeDB(&os[BASMCH]);
OverallSettings.MidiChan = (temp & 0x7f); // mask msb (flag)
OverallSettings.bOmniOn = (temp & 0x80);
temp = decodeDB(&os[MLEN]);
OverallSettings.bRxLoudCtrl7 = (temp == 0 ? false : true);
temp = decodeDB(&os[M1RS2]);
OverallSettings.bCtrlByRs232 = (temp == 2 ? true : false);
OverallSettings.PitchWheelRange = decodeDB(&os[PWRANGE]);
OverallSettings.BaudRate = decodeDW(&os[RSBAUD])*10;
return 0;
}
catch(...)
{
return -100;
}
}
//---------------------------------------------------------------------------
// Put ProgramHeader info to GUI
int __fastcall TFormOverallSettings::FromGui(void)
{
try
{
// Selected program name
AnsiString sTemp = ComboBoxProgNames->Text.TrimRight();
if (!NameOk(sTemp))
{
ShowMessage("Name must be 1-10 ASCII characters!");
ComboBoxProgNames->SetFocus();
return -1;
}
memset(OverallSettings.ProgName, 0, MAX_NAME_S900+1);
strcpy(OverallSettings.ProgName, sTemp.c_str());
// (0) Midi transmit channel for midi exclusive
int iTemp = ComboBoxMidiExTx->Text.ToIntDef(-1);
if (iTemp < 1 || iTemp > 16)
{
ShowMessage("Invalid entry. Midi number is 1-16!");
ComboBoxMidiExTx->SetFocus();
return -1;
}
OverallSettings.MidiTxEx = iTemp-1; // 0-15 so subtract 1
// (1) Reception simulator channel
// (spec says this is 1-16, not 0-15 like the basic channel)
iTemp = ComboBoxRxSimChan->Text.ToIntDef(-1);
if (iTemp < 1 || iTemp > 16)
{
ShowMessage("Invalid entry. Midi number is 1-16!");
ComboBoxRxSimChan->SetFocus();
return -1;
}
OverallSettings.RxSimChan = iTemp; // 1-16
// (60) Reception simulator key
iTemp = EditRxSimKey->Text.ToIntDef(-1);
if (iTemp < 0 || iTemp > 127)
{
ShowMessage("Invalid entry. Reception simulator key is 0-127!");
EditRxSimKey->SetFocus();
return -1;
}
OverallSettings.RxSimKey = iTemp;
// (64) Reception simulator velocity
iTemp = EditRxSimVel->Text.ToIntDef(-1);
if (iTemp < 1 || iTemp > 127)
{
ShowMessage("Invalid entry. Reception simulator velocity is 1-127!");
EditRxSimVel->SetFocus();
return -1;
}
OverallSettings.RxSimVel = iTemp;
// Basic (base) midi channel
iTemp = ComboBoxBaseMidiChan->Text.ToIntDef(-1);
if (iTemp < 1 || iTemp > 16)
{
ShowMessage("Invalid entry. Midi number is 1-16!");
ComboBoxBaseMidiChan->SetFocus();
return -1;
}
OverallSettings.MidiChan = iTemp-1; // 0-15 so subtract 1
// Omni midi-mode (respond on any channel)
OverallSettings.bOmniOn = CheckBoxOmni->Checked;
OverallSettings.bRxLoudCtrl7 = CheckBoxLoudnessOnMidi7->Checked;
OverallSettings.bCtrlByRs232 = (RadioGroupMidiRs232->ItemIndex == 1) ? true : false;
iTemp = EditPitchWheelRange->Text.ToIntDef(-1);
if (iTemp < 0 || iTemp > 12)
{
ShowMessage("Invalid entry. Pitch wheel range is 0-12!");
EditPitchWheelRange->SetFocus();
return -1;
}
OverallSettings.PitchWheelRange = iTemp;
// Baud rate
iTemp = ComboBoxBaudRate->Text.ToIntDef(-1);
if (iTemp < 300 || iTemp > 115200)
{
ShowMessage("Invalid entry. Baud rate is 300-115200!");
ComboBoxBaudRate->SetFocus();
return -1;
}
OverallSettings.BaudRate = iTemp;
return 0;
}
catch(...)
{
return -100;
}
}
//---------------------------------------------------------------------------
// Put ProgramHeader info to GUI
int __fastcall TFormOverallSettings::ToGui(void)
{
try
{
int iTemp;
// Selected program
ComboBoxProgNames->Text = String(OverallSettings.ProgName);
// (0) Midi transmit channel for midi exclusive
// (have to add 1 because MidiTxEx is 0-based)
ComboBoxMidiExTx->Text = String(OverallSettings.MidiTxEx+1);
// (1) Reception simulator channel
// 1-16, not 0-15 like the basic channel!
ComboBoxRxSimChan->Text = String(OverallSettings.RxSimChan);
// (60) Reception simulator key
EditRxSimKey->Text = String(OverallSettings.RxSimKey);
// (64) Reception simulator velocity
EditRxSimVel->Text = String(OverallSettings.RxSimVel);
// Basic (base) midi channel
// (have to add 1 because MidiChan is 0-based)
ComboBoxBaseMidiChan->Text = String(OverallSettings.MidiChan+1);
// Omni midi-mode (respond on any channel)
CheckBoxOmni->Checked = OverallSettings.bOmniOn;
CheckBoxLoudnessOnMidi7->Checked = OverallSettings.bRxLoudCtrl7;
RadioGroupMidiRs232->ItemIndex = OverallSettings.bCtrlByRs232 ? 1 : 0;
EditPitchWheelRange->Text = String(OverallSettings.PitchWheelRange);
// Baud rate
ComboBoxBaudRate->Text = String(OverallSettings.BaudRate);
return 0;
}
catch(...)
{
return -100;
}
}
//---------------------------------------------------------------------------
// Loads OverallSettings struct with default values
int __fastcall TFormOverallSettings::LoadDefaults(void)
{
try
{
strcpy(OverallSettings.ProgName, "DEFAULT PR");
OverallSettings.MidiTxEx = 0; // (0) Midi transmit channel for midi exclusive
OverallSettings.RxSimChan = 1; // (1) Reception simulator channel
OverallSettings.RxSimKey = 60; // (60) " Midi Key
OverallSettings.RxSimVel = 64; // (64) " Velocity
OverallSettings.MidiChan = 0; // 0
OverallSettings.bOmniOn = true; // (128) (this flag is from the MSB of BSAMCH)
OverallSettings.bRxLoudCtrl7 = false; // (0)
OverallSettings.bCtrlByRs232 = true; // (0) Midi/Rs232 select
OverallSettings.PitchWheelRange = 7; // (7) semitones up or down +/- 7 is default (0-127)
OverallSettings.BaudRate = FormMain->BaudRate; // get main form's rate
return 0;
}
catch(...)
{
return -100;
}
}
//---------------------------------------------------------------------------
|
#include <iostream>
using namespace std;
int f(int);
int g(int);
int main()
{
while(true)
{
int n;
cin>>n;
if(n==-1) return 0;
cout<<f(n)<<endl;
}
return 0;
}
int f(int n)
{
if(n==0) return 0;
else if(n==1) return 0;
else if(n==2) return 3;
return f(n-2) + (g(n-1) * 2);
}
int g(int n)
{
if(n==1) return 1;
else if(n==2) return 0;
return f(n-1) + g(n-2);
}
|
#include "file.h"
namespace File
{
String readEntireFile(String filename, Error* error) {
zeroMemory(error, sizeof(File::Error));
FILE* f = fopen(filename.data, "rb");
if (f == 0)
{
print("readEntireFile:: Invalid file. File = %s\n", &filename);
if (error) {
error->errorCode = FILE_CANT_OPEN;
}
String sNull = {};
return sNull;
}
fseek(f, 0, SEEK_END);
u32 fsize = ftell(f);
fseek(f, 0, SEEK_SET);
if (fsize == 0) {
String sNull = {};
return sNull;
}
String sfileData = {};
sfileData.data = (char*)malloc(fsize + 1);
if (sfileData.data == 0)
{
print("readEntireFile:: Memory allocation error. Size = %d\n", fsize + 1);
if (error) {
error->errorCode = FILE_NO_MEMORY;
}
String sNull = {};
return sNull;
}
sfileData.length = fsize;
fread(sfileData.data, fsize, 1, f);
sfileData.data[fsize] = 0; // Null terminate file contents
fclose(f);
return sfileData;
}
void writeEntireFile(String filename, Buffer* buffer, Error* error) {
assert(buffer != NULL);
assert(buffer->data != NULL);
assert(buffer->used >= 0);
char cFilename[260];
filename.toCString(cFilename, ArrayCount(cFilename));
FILE* f = fopen(cFilename, "wb");
if (f == 0)
{
print("writeEntireFile:: Unable to open file for writing. File = %s\n", &filename);
if (error) {
error->errorCode = FILE_CANT_OPEN;
}
return;
}
s32 bytesWritten = fwrite(buffer->data, sizeof(char), buffer->used, f);
if (bytesWritten != buffer->used)
{
print("writeEntireFile:: Failed to write. File = %s\n", &filename);
if (error) {
error->errorCode = FILE_NO_WRITE;
}
return;
}
fclose(f);
}
}
|
#include "base/pch.hpp"
#include "base/zenlang.hpp"
#include "gui/Mainframe.hpp"
#include "WindowImpl.hpp"
z::MainFrame::Create::_Out z::MainFrame::Create::run(const z::MainFrame::Definition& def) {
#if defined(WIN32)
z::widget::impl& impl = WindowImpl::createMainFrame(def, WS_OVERLAPPEDWINDOW, WS_EX_WINDOWEDGE);
::PostMessage(impl._val, WM_SIZE, 0, 0);
if(def.iconres.length() > 0) {
z::string resname = "IDI_" + def.iconres;
HICON hIcon = ::LoadIcon(::GetModuleHandle(NULL), z::s2e(resname).c_str());
if(hIcon == 0) {
z::elog("MainFrame", "Error loading icon: " + resname);
}
::SendMessage(impl._val, WM_SETICON, ICON_BIG, (LPARAM)(hIcon));
::SendMessage(impl._val, WM_SETICON, ICON_SMALL, (LPARAM)(hIcon));
}
#elif defined(GTK)
z::widget::impl& impl = WindowImpl::createWindow(def, 0);
if((def.position.w != -1) && (def.position.h != -1))
gtk_widget_set_size_request (impl._val, def.position.w, def.position.h);
impl._fixed = gtk_fixed_new();
gtk_container_add(GTK_CONTAINER(impl._val), impl._fixed);
gtk_widget_show(impl._fixed);
#elif defined(OSX)
z::widget::impl& impl = WindowImpl::createMainFrame(def);
#elif defined(QT)
UNIMPL();
z::widget::impl& impl = *((z::widget::impl*)(0));
#elif defined(IOS)
UNIMPL();
z::widget::impl& impl = WindowImpl::createMainFrame(def);
#else
#error "Unimplemented GUI mode"
#endif
z::widget win(impl);
#if !defined(OSX)
if(def.visible) {
z::Window::Show().run(win);
}
#endif
return _Out(win);
}
|
/*
Longest Common Subsequence (LCS). The following are some instances£º
a) X: xzyzzyx Y: zxyyzxz
b) X: ALLAAQANKESSSESFISRLLAIVAD
Y: KLQKKLAETEKRCTLLAAQANKENSNESFISRLLAIVAG
*/
#include<stdio.h>
#include<stdlib.h>
#define RESULTLEN 100
int getLCS(char[],int,char[],int ,char[][RESULTLEN]);
int getLen(char[]);
void showLCS(char[][RESULTLEN],int,int,int len);
int main(){
char x[]="yxxxyyyjjj";
int xlen=getLen(x);
char y[]="yxxyjjsdsj";
int ylen=getLen(y);
char result[xlen][100];// 'c' mean the common char in both x and y,'x' mean the longest common substring in x,'y' mean the similar
int len=getLCS(x,xlen,y,ylen,result);
printf("len = %d\n",len);
showLCS(result,xlen,ylen,len);
system("PAUSE");
return 0;
}
int getLen(char a[]){
int i=0;
while(a[i++]!='\0');
return i-1;
}
int getLCS(char x[],int xlen,char y[],int ylen,char result[][RESULTLEN]){
if(xlen==0||ylen==0)
return 0;
int len[xlen+1][ylen+1];
int i=0,j=0;
for(i=0;i<xlen+1;++i)
len[i][0]=0;
for(j=0;j<ylen;++j)
len[0][j]=0;
for(i=0;i<xlen;++i){
for(j=0;j<ylen;++j){
if(x[i]==y[j]){
len[i+1][j+1]=len[i][j]+1;
result[i][j]=x[i];
}else if(len[i][j+1]>len[i+1][j]){
len[i+1][j+1]=len[i][j+1];
result[i][j]='u';
}else{
len[i+1][j+1]=len[i+1][j];
result[i][j]='l';
}
}
}
return len[xlen][ylen];
}
void showLCS(char result[][RESULTLEN],int xlen,int ylen,int len){
char temp[len+1];
temp[len]='\0';
while(xlen>0 && ylen>0){
if(result[xlen-1][ylen-1]=='u')
--xlen;
else if(result[xlen-1][ylen-1]=='l')
--ylen;
else{
temp[--len]=result[xlen-1][ylen-1];
--xlen;
--ylen;
}
}
printf("%s\n",temp);
return;
}
|
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "vectors.h"
TEST_CASE("Verify Test Configuration", "verification") {
REQUIRE(true == true);
}
TEST_CASE("Test function is_prime") {
REQUIRE(is_prime(2) == true);
REQUIRE(is_prime(4) == false);
REQUIRE(is_prime(43) == true);
REQUIRE(is_prime(44) == false);
REQUIRE(is_prime(8) == false);
}
TEST_CASE("Test function get_max_from_vector") {
vector <int> nums1{ 3,8,1,99,1000 };
REQUIRE(get_max_from_vector(nums1) == 1000);
vector <int> nums2{ 15,12,11,99,88 };
REQUIRE(get_max_from_vector(nums2) == 99);
vector <int> nums3{ 150,120,11,990,88888 };
REQUIRE(get_max_from_vector(nums3) == 88888);
}
TEST_CASE("Test function vector_of_primes") {
vector <int> nums1{ 2, 3, 5, 7 };
REQUIRE(vector_of_primes(10) == nums1);
vector <int> nums2{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 };
REQUIRE(vector_of_primes(50) == nums2);
}
/*
This function isn't used in main, but I tested it and it works
as expected
*/
TEST_CASE("Test function get_primes_from_vector") {
vector <int> nums1{ 2, 3, 8, 10, 15, 16, 12, 18, 20 };
vector <int> expected1{ 2, 3};
REQUIRE(get_primes_from_vector(nums1) == expected1);
vector <int> nums2{ 6, 2, 3, 5 };
vector <int> expected2{ 2, 3, 5};
REQUIRE(get_primes_from_vector(nums2) == expected2);
vector <int> nums3{ 6, 8, 10 };
vector <int> expected3{ };
REQUIRE(get_primes_from_vector(nums3) == expected3);
}
|
/***************************************************************************
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**************************************************************************/
#include "PositionNormalFwidth.h"
namespace
{
const char kDesc[] = "Position and normal fwidth";
// shader file
const char kPositionNormalFwidthFile[] = "RenderPasses/PositionNormalFwidth/PositionNormalFwidth.ps.slang";
// Input buffer names
const char kPositon[] = "PosW";
const char kNormal[] = "NormW";
// Output buffer names
const char kPositionNormalFwidth[] = "PositionNormalFwidth";
}
// Don't remove this. it's required for hot-reload to function properly
extern "C" __declspec(dllexport) const char* getProjDir()
{
return PROJECT_DIR;
}
extern "C" __declspec(dllexport) void getPasses(Falcor::RenderPassLibrary& lib)
{
lib.registerClass("PositionNormalFwidth", kDesc, PositionNormalFwidth::create);
}
PositionNormalFwidth::PositionNormalFwidth()
{
mpPositionNomralFwidth = FullScreenPass::create(kPositionNormalFwidthFile, Program::DefineList(), 0);
}
PositionNormalFwidth::SharedPtr PositionNormalFwidth::create(RenderContext* pRenderContext, const Dictionary& dict)
{
SharedPtr pPass = SharedPtr(new PositionNormalFwidth());
return pPass;
}
std::string PositionNormalFwidth::getDesc() { return kDesc; }
Dictionary PositionNormalFwidth::getScriptingDictionary()
{
return Dictionary();
}
RenderPassReflection PositionNormalFwidth::reflect(const CompileData& compileData)
{
// Define the required resources here
RenderPassReflection reflector;
reflector.addInput(kPositon, "World Position");
reflector.addInput(kNormal, "World Normal");
reflector.addOutput(kPositionNormalFwidth, "PositonNormalFwidth").format(ResourceFormat::RG32Float).
bindFlags(ResourceBindFlags::UnorderedAccess);
return reflector;
}
void PositionNormalFwidth::compile(RenderContext* pContext, const CompileData& compileData)
{
Fbo::Desc desc;
desc.setColorTarget(0, Falcor::ResourceFormat::RG32Float);
mpFbo = Fbo::create2D(compileData.defaultTexDims.x, compileData.defaultTexDims.y, desc);
}
void PositionNormalFwidth::execute(RenderContext* pRenderContext, const RenderData& renderData)
{
// renderData holds the requested resources
// auto& pTexture = renderData["src"]->asTexture();
Texture::SharedPtr pPosition = renderData[kPositon]->asTexture();
Texture::SharedPtr pNormal = renderData[kNormal]->asTexture();
Texture::SharedPtr pPositionNormalFwidth = renderData[kPositionNormalFwidth]->asTexture();
mpPositionNomralFwidth["gPosW"] = pPosition;
mpPositionNomralFwidth["gNormW"] = pNormal;
//mpPositionNomralFwidth["gPositionNormalFwidth"] = pPositionNormalFwidth;
mpPositionNomralFwidth->execute(pRenderContext, mpFbo);
pRenderContext->blit(mpFbo->getColorTexture(0)->getSRV(), pPositionNormalFwidth->getRTV());
}
void PositionNormalFwidth::renderUI(Gui::Widgets& widget)
{
}
|
/*
* Metric.h
*
* Created on: May 25, 2011
* Author: marchi
*/
#ifndef METRIC_H_
#define METRIC_H_
#include <cmath>
#include "Ftypedefs.h"
#include "MyVec.h"
#include <vector>
using std::vector;
class Metric {
matrix co, oc;
static const matrix Idtity;
void invertCO();
int count;
double AA(){return norm(co[XX]);}
double BB(){return norm(co[YY]);}
double CC(){return norm(co[ZZ]);}
double Alpha(){
double alpha;
if (norm2(co[YY])*norm2(co[ZZ])!=0)
alpha = acos(cos_angle(co[YY],co[ZZ]));
else
alpha = 0.5*M_PI;
return alpha;
}
double Beta(){
double beta;
if (norm2(co[XX])*norm2(co[ZZ])!=0)
beta = acos(cos_angle(co[XX],co[ZZ]));
else
beta = 0.5*M_PI;
return beta;
}
double Gamma(){
double gamma;
if (norm2(co[XX])*norm2(co[YY])!=0)
gamma = acos(cos_angle(co[XX],co[YY]));
else
gamma = 0.5*M_PI;
return gamma;
}
public:
Metric();
Metric(const matrix &);
Metric(const Metric &);
virtual ~Metric();
Metric & operator()(const matrix &);
Metric & operator()(const Metric &);
Metric & operator=(const Metric & );
Metric & operator+=(const Metric &);
Metric operator/(const double);
const matrix & getCO() const {return co;};
const matrix & getOC() const {return oc;};
double getVol(){ return (double) (co[XX][XX]*(co[YY][YY]*co[ZZ][ZZ]-co[ZZ][YY]*co[YY][ZZ])
-co[YY][XX]*(co[XX][YY]*co[ZZ][ZZ]-co[ZZ][YY]*co[XX][ZZ])
+co[ZZ][XX]*(co[XX][YY]*co[YY][ZZ]-co[YY][YY]*co[XX][ZZ]));};
vector<double> getParas(){
vector<double> d=vector<double>(DIM*2);
d[0]=AA();
d[1]=BB();
d[2]=CC();
d[3]=RAD2DEG*Alpha();
d[4]=RAD2DEG*Beta();
d[5]=RAD2DEG*Gamma();
return d;}
};
#endif /* METRIC_H_ */
|
#include <bits/stdc++.h>
#define ull unsigned long long
#define ll long long
#define il inline
#define db double
#define ls rt << 1
#define rs rt << 1 | 1
#define pb push_back
#define mp make_pair
#define pii pair<int, int>
#define X first
#define Y second
#define pcc pair<char, char>
#define vi vector<int>
#define vl vector<ll>
#define rep(i, x, y) for(int i = x; i <= y; i ++)
#define rrep(i, x, y) for(int i = x; i >= y; i --)
#define rep0(i, n) for(int i = 0; i < (n); i ++)
#define per0(i, n) for(int i = (n) - 1; i >= 0; i --)
#define ept 1e-9
#define INF 0x3f3f3f3f
#define sz(x) (x).size()
#define ALL(x) (x).begin(), (x).end()
using namespace std;
inline int read()
{
int x = 0, f = 1; char ch = getchar();
while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
return x * f;
}
const int N = 110;
int n, a[N][N], b[N][N];
vector<pii> f[N][N];
int main()
{
int T = read();
while(T --)
{
n = read();
rep(i, 1, n) rep(j, 1, n) a[i][j] = read();
rep(i, 1, n) rep(j, 1, n) b[i][j] = read();
rep(i, 1, n) rep(j, 1, n)
{
if (i > 1 && j > 1)
{
f[i][j].clear();
int p = 0, q = 0;
for (; p < f[i - 1][j].size() || q < f[i][j - 1].size(); )
{
pii t;
if (p < f[i - 1][j].size() && q < f[i][j - 1].size())
{
if (f[i - 1][j][p] > f[i][j - 1][q]) t = f[i][j - 1][q++];
else t = f[i - 1][j][p++];
}
else
{
if (p == f[i - 1][j].size()) t = f[i][j - 1][q++];
else t = f[i - 1][j][p++];
}
while (!f[i][j].empty() && f[i][j].back().Y <= t.Y) f[i][j].pop_back();
f[i][j].push_back(t);
}
}
else if (i > 1) f[i][j] = f[i - 1][j];
else if (j > 1) f[i][j] = f[i][j - 1];
else { f[i][j].clear(); f[i][j].push_back(mp(0, 0)); }
for (auto &t : f[i][j]) t.X += a[i][j], t.Y += b[i][j];
}
ll ans = 0;
for (auto t : f[n][n]) ans = max(ans, 1ll * t.X * t.Y);
printf("%lld\n", ans);
}
return 0;
}
|
#include <cstdint>
#include <iostream>
#include "packet.h"
namespace comms {
std::ostream& operator<<(std::ostream &o, Packet &p) {
o << "ID: " << (int) p.ID << " Index: " << p.index << " Data: ";
if (p.ID == ID_MSG1) {
for (int i = 0; i < 16; i++)
o << (char) p.data[i];
} else {
for (int i = 0; i < 16; i++)
o << (int) p.data[i] << ',';
}
o << p.checksum;
return o;
}
/**
Determine the length of actual data in a packet with id
@params
id: packet ID
@return
Length of actual data in bytes. Return 0 if id invalid.
*/
size_t lengthByID(byte1_t id) {
//Status or message
switch (id) {
case ID_MSG1:
case ID_MSG2:
case ID_STATUS1:
case ID_STATUS2:
return 16;
case ID_DATA1:
case ID_DATA3:
return 12;
case ID_DATA4:
return 14;
case ID_DATA2:
return 10;
default:
return 0;
}
}
}
|
#include <bits/stdc++.h>
#include <string>
#include <cmath>
#include <sstream>
#define FOR(i, a, b) for (long long int i = (a); i < (b); i++)
#define FORR(i, a, b) for(long long int i = (a); i >=(b); i--)
#define pb(a) push_back(a)
#define mp(a,b) make_pair(a,b)
typedef long long int ll;
using namespace std;
ll mod1=1000000007;
ll mod2=67280421310721;
ll mod3=998244353;
ll INF=1e18;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll t;
cin>>t;
while(t--)
{
int n;
cin >> n;
int count = 0;
while(true){
if(n==1){
cout << count << "\n";
break;
}
else if(n%6 == 2 || n%6 == 4){
cout << "-1\n";
break;
}
else if(n%6==0){
n /= 6;
count++;
}
else{
n *= 2;
count++;
}
}
}
return 0;
}
|
/***********************************************************************
created: Sun Jan 11 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/OpenGLES/FBOTextureTarget.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/PropertyHelper.h"
#include "CEGUI/RendererModules/OpenGLES/Renderer.h"
#include "CEGUI/RendererModules/OpenGLES/Texture.h"
#ifndef __APPLE__
#include "EGL/egl.h"
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
// Where should it be?
typedef GLboolean (GL_APIENTRY *PFNGLISRENDERBUFFEROES)(GLuint);
typedef void (GL_APIENTRY *PFNGLBINDRENDERBUFFEROES)(GLenum, GLuint);
typedef void (GL_APIENTRY *PFNGLDELETERENDERBUFFERSOES)(GLsizei, const GLuint*);
typedef void (GL_APIENTRY *PFNGLGENRENDERBUFFERSOES)(GLsizei, GLuint*);
typedef void (GL_APIENTRY *PFNGLRENDERBUFFERSTORAGEOES)(GLenum, GLenum, GLsizei, GLsizei);
typedef void (GL_APIENTRY *PFNGLGETRENDERBUFFERPARAMETERIVOES)(GLenum, GLenum, GLint*);
typedef GLboolean (GL_APIENTRY *PFNGLISFRAMEBUFFEROES)(GLuint);
typedef void (GL_APIENTRY *PFNGLBINDFRAMEBUFFEROES)(GLenum, GLuint);
typedef void (GL_APIENTRY *PFNGLDELETEFRAMEBUFFERSOES)(GLsizei, const GLuint*);
typedef void (GL_APIENTRY *PFNGLGENFRAMEBUFFERSOES)(GLsizei, GLuint*);
typedef GLenum (GL_APIENTRY *PFNGLCHECKFRAMEBUFFERSTATUSOES)(GLenum);
typedef void (GL_APIENTRY *PFNGLFRAMEBUFFERTEXTURE2DOES)(GLenum, GLenum, GLenum, GLuint, GLint);
typedef void (GL_APIENTRY *PFNGLFRAMEBUFFERRENDERBUFFEROES)(GLenum, GLenum, GLenum, GLuint);
typedef void (GL_APIENTRY *PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOES)(GLenum, GLenum, GLenum, GLint*);
typedef void (GL_APIENTRY *PFNGLGENERATEMIPMAPOES)(GLenum);
PFNGLISRENDERBUFFEROES glIsRenderbufferEXT = 0;
PFNGLBINDRENDERBUFFEROES glBindRenderbufferEXT = 0;
PFNGLDELETERENDERBUFFERSOES glDeleteRenderbuffersEXT = 0;
PFNGLGENRENDERBUFFERSOES glGenRenderbuffersEXT = 0;
PFNGLRENDERBUFFERSTORAGEOES glRenderbufferStorageEXT = 0;
PFNGLGETRENDERBUFFERPARAMETERIVOES glGetRenderbufferParameterivEXT = 0;
PFNGLISFRAMEBUFFEROES glIsFramebufferEXT = 0;
PFNGLBINDFRAMEBUFFEROES glBindFramebufferEXT = 0;
PFNGLDELETEFRAMEBUFFERSOES glDeleteFramebuffersEXT = 0;
PFNGLGENFRAMEBUFFERSOES glGenFramebuffersEXT = 0;
PFNGLCHECKFRAMEBUFFERSTATUSOES glCheckFramebufferStatusEXT = 0;
PFNGLFRAMEBUFFERTEXTURE2DOES glFramebufferTexture2DEXT = 0;
PFNGLFRAMEBUFFERRENDERBUFFEROES glFramebufferRenderbufferEXT = 0;
PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOES glGetFramebufferAttachmentParameterivEXT = 0;
PFNGLGENERATEMIPMAPOES glGenerateMipmapEXT = 0;
//----------------------------------------------------------------------------//
const float OpenGLESFBOTextureTarget::DEFAULT_SIZE = 128.0f;
//----------------------------------------------------------------------------//
std::uint32_t OpenGLESFBOTextureTarget::s_textureNumber = 0;
//----------------------------------------------------------------------------//
OpenGLESFBOTextureTarget::OpenGLESFBOTextureTarget(OpenGLESRenderer& owner, bool addStencilBuffer) :
OpenGLESRenderTarget(owner, addStencilBuffer),
d_texture(0)
{
// this essentially creates a 'null' CEGUI::Texture
d_CEGUITexture = &static_cast<OpenGLESTexture&>(
d_owner.createTexture(generateTextureName(), d_texture, d_area.getSize()));
initialiseRenderTexture();
// setup area and cause the initial texture to be generated.
declareRenderSize(Sizef(DEFAULT_SIZE, DEFAULT_SIZE));
}
//----------------------------------------------------------------------------//
String OpenGLESFBOTextureTarget::generateTextureName()
{
String tmp("_gles_tt_tex_");
tmp.append(PropertyHelper<std::uint32_t>::toString(s_textureNumber++));
return tmp;
}
//----------------------------------------------------------------------------//
OpenGLESFBOTextureTarget::~OpenGLESFBOTextureTarget()
{
glDeleteFramebuffersEXT(1, &d_frameBuffer);
d_owner.destroyTexture(*d_CEGUITexture);
}
//----------------------------------------------------------------------------//
void OpenGLESFBOTextureTarget::declareRenderSize(const Sizef& sz)
{
// exit if current size is enough
if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >=sz.d_height))
return;
setArea(Rectf(d_area.getPosition(), d_owner.getAdjustedTextureSize(sz)));
resizeRenderTexture();
}
//----------------------------------------------------------------------------//
bool OpenGLESFBOTextureTarget::isImageryCache() const
{
return true;
}
//----------------------------------------------------------------------------//
void OpenGLESFBOTextureTarget::activate()
{
// switch to rendering to the texture
glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES, &d_oldFbo);
glBindFramebufferEXT(GL_FRAMEBUFFER_OES, d_frameBuffer);
OpenGLESRenderTarget::activate();
}
//----------------------------------------------------------------------------//
void OpenGLESFBOTextureTarget::deactivate()
{
OpenGLESRenderTarget::deactivate();
// switch back to rendering to default buffer
glBindFramebufferEXT(GL_FRAMEBUFFER_OES, d_oldFbo);
}
//----------------------------------------------------------------------------//
void OpenGLESFBOTextureTarget::clear()
{
// save old clear colour
GLfloat old_col[4];
glGetFloatv(GL_COLOR_CLEAR_VALUE, old_col);
GLint old_fbo;
glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES, &old_fbo);
// switch to our FBO
glBindFramebufferEXT(GL_FRAMEBUFFER_OES, d_frameBuffer);
// Clear it.
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT);
// switch back to rendering to view port
glBindFramebufferEXT(GL_FRAMEBUFFER_OES, old_fbo);
// restore previous clear colour
glClearColor(old_col[0], old_col[1], old_col[2], old_col[3]);
}
//----------------------------------------------------------------------------//
Texture& OpenGLESFBOTextureTarget::getTexture() const
{
return *d_CEGUITexture;
}
//----------------------------------------------------------------------------//
void OpenGLESFBOTextureTarget::initialiseRenderTexture()
{
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
GLint old_fbo;
glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES, &old_fbo);
// create FBO
glGenFramebuffersEXT(1, &d_frameBuffer);
glBindFramebufferEXT(GL_FRAMEBUFFER_OES, d_frameBuffer);
// set up the texture the FBO will draw to
glGenTextures(1, &d_texture);
glBindTexture(GL_TEXTURE_2D, d_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
static_cast<GLsizei>(DEFAULT_SIZE),
static_cast<GLsizei>(DEFAULT_SIZE),
0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES,
GL_TEXTURE_2D, d_texture, 0);
// TODO: Check for completeness and then maybe try some alternative stuff?
// switch from our frame buffer back to using default buffer.
glBindFramebufferEXT(GL_FRAMEBUFFER_OES, old_fbo);
// ensure the CEGUI::Texture is wrapping the gl texture and has correct size
d_CEGUITexture->setOpenGLESTexture(d_texture, d_area.getSize());
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLESFBOTextureTarget::resizeRenderTexture()
{
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
const Sizef sz(d_area.getSize());
// set the texture to the required size
glBindTexture(GL_TEXTURE_2D, d_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
static_cast<GLsizei>(sz.d_width),
static_cast<GLsizei>(sz.d_height),
0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
clear();
// ensure the CEGUI::Texture is wrapping the gl texture and has correct size
d_CEGUITexture->setOpenGLESTexture(d_texture, sz);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLESFBOTextureTarget::initializedFBOExtension()
{
if (!OpenGLESRenderer::isGLExtensionSupported("GL_OES_framebuffer_object"))
throw InvalidRequestException("This platform does not support FBO");
#ifndef __APPLE__
glIsRenderbufferEXT =
(PFNGLISRENDERBUFFEROES)eglGetProcAddress("glIsRenderbufferOES") ;
glBindRenderbufferEXT =
(PFNGLBINDRENDERBUFFEROES)eglGetProcAddress("glBindRenderbufferOES");
glDeleteRenderbuffersEXT =
(PFNGLDELETERENDERBUFFERSOES)eglGetProcAddress("glDeleteRenderbuffersOES");
glGenRenderbuffersEXT =
(PFNGLGENRENDERBUFFERSOES)eglGetProcAddress("glGenRenderbuffersOES");
glRenderbufferStorageEXT =
(PFNGLRENDERBUFFERSTORAGEOES)eglGetProcAddress("glRenderbufferStorageOES");
glGetRenderbufferParameterivEXT =
(PFNGLGETRENDERBUFFERPARAMETERIVOES)eglGetProcAddress("glGetRenderbufferParameterivOES");
glIsFramebufferEXT =
(PFNGLISFRAMEBUFFEROES)eglGetProcAddress("glIsFramebufferOES");
glBindFramebufferEXT =
(PFNGLBINDFRAMEBUFFEROES)eglGetProcAddress("glBindFramebufferOES");
glDeleteFramebuffersEXT =
(PFNGLDELETEFRAMEBUFFERSOES)eglGetProcAddress("glDeleteFramebuffersOES");
glGenFramebuffersEXT =
(PFNGLGENFRAMEBUFFERSOES)eglGetProcAddress("glGenFramebuffersOES");
glCheckFramebufferStatusEXT =
(PFNGLCHECKFRAMEBUFFERSTATUSOES)eglGetProcAddress("glCheckFramebufferStatusOES");
glFramebufferTexture2DEXT =
(PFNGLFRAMEBUFFERTEXTURE2DOES)eglGetProcAddress("glFramebufferTexture2DOES");
glFramebufferRenderbufferEXT =
(PFNGLFRAMEBUFFERRENDERBUFFEROES)eglGetProcAddress("glFramebufferRenderbufferOES");
glGetFramebufferAttachmentParameterivEXT =
(PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOES)eglGetProcAddress("glGetFramebufferAttachmentParameterivOES");
glGenerateMipmapEXT =
(PFNGLGENERATEMIPMAPOES)eglGetProcAddress("glGenerateMipmapOES");
#else
glIsRenderbufferEXT = ::glIsRenderbufferOES;
glBindRenderbufferEXT = ::glBindRenderbufferOES;
glDeleteRenderbuffersEXT = ::glDeleteRenderbuffersOES;
glGenRenderbuffersEXT = ::glGenRenderbuffersOES;
glRenderbufferStorageEXT = ::glRenderbufferStorageOES;
glGetRenderbufferParameterivEXT = ::glGetRenderbufferParameterivOES;
glIsFramebufferEXT = ::glIsFramebufferOES;
glBindFramebufferEXT = ::glBindFramebufferOES;
glDeleteFramebuffersEXT = ::glDeleteFramebuffersOES;
glGenFramebuffersEXT = ::glGenFramebuffersOES;
glCheckFramebufferStatusEXT = ::glCheckFramebufferStatusOES;
glFramebufferTexture2DEXT = ::glFramebufferTexture2DOES;
glFramebufferRenderbufferEXT = ::glFramebufferRenderbufferOES;
glGetFramebufferAttachmentParameterivEXT = ::glGetFramebufferAttachmentParameterivOES;
glGenerateMipmapEXT = ::glGenerateMipmapOES;
#endif
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
|
// This question is special, instead of using DP solution, we kind of use the markov chain.
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.empty()) return 0;
int n = prices.size();
vector<int> s0(n), s1(n), s2(n);
s0[0] = 0;
s1[0] = -prices[0];
s2[0] = INT_MIN;
for(int i = 1; i < n; i++)
{
s0[i] = max(s0[i - 1], s2[i - 1]);
s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]);
s2[i] = s1[i - 1] + prices[i];
}
return max(s0[n - 1], s2[n - 1]);
}
};
|
#include "../common/tcp_socket.h"
#include "protocol6.hpp"
#include <iostream>
using namespace std;
/*定义MAX_SEQ 保证为 2^n-1*/
const seq_nr MAX_SEQ = 7;
const seq_nr NR_BUFS = ((MAX_SEQ + 1) / 2);
bool no_nak = true;
//static const char* NetworkProcName = "./protocol6_network_s";
//static const char* DatalinkProcName = "./protocol6_datalink_s";
//static const char* PhysicalProcName = "./protocol6_physical_s";
// 网络层文件命名前缀
const char* ShareFilePrefix = "../data/network-datalink.share.";
static char IpAddr[32] = "0.0.0.0";
static int Port = 4000;
// 选择重传 sender
void physicalProcess(int dpshmid, int pdshmid)
{
// 映射网络层与链路层之间的共享内存 (shmid已继承
shmAddrDP = (char*)attachShm(dpshmid, nullptr, 0);
if (shmAddrDP == (void*)-1)
exit(EXIT_FAILURE);
shmAddrPD = (char*)attachShm(pdshmid, nullptr, 0);
if (shmAddrPD == (void*)-1)
exit(EXIT_FAILURE);
// 这里不能用signal 会重启被中断的系统调用而导致死锁
// 目的仅是为了在帧超时时中断recv操作 否则recv会持续阻塞 无法重传
setSigAction(timeout, handler, 0);
setSigAction(ack_timeout, handler, 0);
// 监控 SigDatalinkLayerReady 信号
sigset_t waitDatalink;
sigemptyset(&waitDatalink);
sigaddset(&waitDatalink, SigDatalinkLayerReady);
sigaddset(&waitDatalink, SigTransmitClose);
sigprocmask(SIG_BLOCK, &waitDatalink, nullptr);
int sockfd, connfd, sendLen, recvLen = 0, signum;
siginfo_t siginfo;
struct sockaddr_in clientAddr;
socklen_t clientLen = sizeof(clientAddr);
sockfd = getSocket(AF_INET, SOCK_STREAM, 0, true);
if (sockfd < 0)
exit(EXIT_FAILURE);
if (bindAddr(sockfd, IpAddr, Port, AF_INET) < 0)
exit(EXIT_FAILURE);
if (listen(sockfd, 5) < 0)
exit(EXIT_FAILURE);
while (true) {
connfd = accept(sockfd, (sockaddr*)&clientAddr, &clientLen);
if (connfd < 0) {
if (errno == EINTR)
continue;
printf("exit");
exit(EXIT_FAILURE);
}
break;
}
sendSignal(datalinkPid, SigPhysicalConnectSuccess);
srand((unsigned)(time(NULL)));
while (true) {
// 信号可能带有参数
while ((signum = sigwaitinfo(&waitDatalink, &siginfo)) == -1 && errno == EINTR)
;
if (signum == SigTransmitClose)
break;
if (signum != SigDatalinkLayerReady)
continue;
// 等到链路层数据准备完成的信号 发送数据
sendLen = send(connfd, shmAddrDP, siginfo.si_int, MSG_NOSIGNAL);
if (sendLen < 0) {
// 被中断继续等待事件
if (errno != EPIPE)
continue;
perror("send");
break;
}
/*static int count = 0;
printf("%d -- send -- %d\n", ++count, sendLen);*/
while (true) {
recvLen += recv(connfd, shmAddrPD + recvLen, sizeof(frame) - recvLen, 0);
if (recvLen <= 0)
break;
// 保证读到一个完整帧(数据帧或ack/nak帧)
if (recvLen != sizeof(frame) && (recvLen != (sizeof(frame) - sizeof(frame::info))))
continue;
break;
}
if (recvLen <= 0) {
// 如果不是被中断而停止读取 则退出 否则继续等待事件
//if (recvLen == 0 || errno != EINTR) {
if (recvLen == 0) {
perror("recv");
break;
}
recvLen = 0;
continue;
}
//printf("%d -- recv -- %d\n", count, recvLen);
// 重置 用于下次计数
recvLen = 0;
// 3%概率发送校验和错误
//if (errorWithPercent(3)) {
// sendSignal(datalinkPid, cksum_err);
// continue;
//}
//// 3%概率丢包
//if (errorWithPercent(3))
// continue;
// 正常通知
sendSignal(datalinkPid, frame_arrival);
}
printf("close\n");
close(connfd);
close(sockfd);
exit(EXIT_SUCCESS);
}
int main(int argc, char** argv)
{
/*if (daemon(1, 1) < 0) {
perror("daemon");
return -1;
}*/
char datafile[64], recvfile[64], logfile[64];
if (argc == 6) {
strcpy(IpAddr, argv[1]);
Port = atoi(argv[2]);
strcpy(datafile, argv[3]);
strcpy(recvfile, argv[4]);
strcpy(logfile, argv[5]);
}
else {
fprintf(stderr, "参数错误!!!\n"
"用法 : ./protocol6_s <bind-ip> <bind-port> <datafile> <recvfile> <logfile>\n"
"注 : 请自行在当前目录下创建data目录,用于存放发送方网络层拆分的共享数据文件\n"
"(mkdir ./data/)\n * 文件名长度请勿超过63。\n");
exit(EXIT_FAILURE);
}
networkProcess(datafile, recvfile, logfile);
exit(EXIT_SUCCESS);
}
|
//TODO: this class actually ignores overflows of long's.
class Tone
{
private:
unsigned long frequency;
unsigned long delayTime;
unsigned long lastTime;
bool isHigh;
int pin;
public:
Tone(int p);
void setTone(unsigned int freq);
void play();
void stop();
enum note{c1=131, d1=147, e1=165, f1=175, g1=196, a1=220, h1=247, c2=262, d2=294, e2=330, f2=350, g2=392, a2=440, h2=494,
c3=523, d3=587, e3=659, f3=699, g3=784, a3=880, h3=988, c4=1047, d4=1175, e4=1319, f4=1397, g4=1568, a4=1760, h4=1976};
};
|
#ifndef CONSULTOR_H
#define CONSULTOR_H
#include "Funcionario.h"
#include <iostream>
class Consultor: public Funcionario{
private:
float percentual;
public:
void setPercentual(float p);
float getPercentual();
float getSalario(float percentual);
virtual float getSalario();
};
#endif // CONSULTOR_H
|
//*******************************************************************************
// VMA209 - Pot meter + PWM example
// The VMA209 contains a blue potmeter (trimmer) which is connected to Analog 0
// In this example we show You how to measure the voltage between 0 and 5V,how to visualise it by the serial monitor, and how to adjust the intensity of 2 LED's by using PWM
// Programmed :Arduino IDE
// Board :Arduino Leonardo, UNO,
//*******************************************************************************/
int potpin=A0; //Initialize integer potpin as Analog 0
int ledpin1=11;//Define digital interface 11 (PWM output)
int ledpin2=10;//Define digital interface 10 (PWM output)
int val=0;// initialize val as a integer with value 0
void setup()
{
Serial.begin(9600);//Set the communications baudrate to 9600 Baud
}
void loop()
{
val=analogRead(potpin);// Read the sensor's analog value and assign it to val
Serial.println(val);// Print this value to the serial monitor
analogWrite(ledpin1,val/4);// write this value to the LED and set its brightness by PWM (value between 0 and 255, that's why devide by 4)
analogWrite(ledpin2,val/4);// write this value to the LED and set its brightness by PWM (value between 0 and 255, that's why devide by 4)
delay(100);//wait for 0,1 second for the next measurement
}
|
/* 3DMeshMetric is a visualization tool used to measures and display
* surface-to-surface distance between two triangle meshes.
*
* 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/>.
*
* Authors : Juliette Pera, Francois Budin, Beatriz Paniagua
* Web site : http://www.nitrc.org/projects/meshmetric3d/
*
* Reference : MeshValmet, Validation Metric for Meshes
* http://www.nitrc.org/projects/meshvalmet/
*
* This program also uses Qt libraries
* http://www.qt-project.org/
*/
#include "meshMetricGui.h"
meshMetricGui::meshMetricGui( QWidget *Parent , Qt::WFlags f , QString path )
{
setupUi(this);
m_WidgetMesh = new QVTKWidget( this -> scrollAreaMesh );
m_WidgetMesh->resize( scrollAreaMesh->size() );
m_MyWindowMesh.setSizeH( m_WidgetMesh->height() );
m_MyWindowMesh.setSizeW( m_WidgetMesh->width() );
m_MyWindowMesh.setMeshWidget( m_WidgetMesh );
scrollAreaMesh->setEnabled( true );
QObject::connect( pushButton , SIGNAL( clicked() ) , this , SLOT( DisplayInit() ) );
QObject::connect( pushButton2 , SIGNAL( clicked() ) , this , SLOT( Error() ) );
}
//*************************************************************************************************
void meshMetricGui::DisplayInit()
{
// add data
std::string Data ="/NIRAL/work/jpera/Project/Data/vtk_result_Datas/signed_distance_new.vtk";
m_DataList.push_back( Data );
m_DataList[0].initialization();
// add data to window
m_MyWindowMesh.addData( m_DataList[0].getActor() );
//update window
m_MyWindowMesh.initWindow();
m_MyWindowMesh.updateWindow();
}
void meshMetricGui::Error()
{
m_DataList[0].setDisplayError( true );
m_DataList[0].setColorBar( true );
m_DataList[0].setTypeDistance(1);
vtkSmartPointer <vtkColorTransferFunction> Lut = vtkSmartPointer <vtkColorTransferFunction>::New();
Lut -> AddRGBSegment( -10 , 0 , 0 , 1 , -0.5 , 0 , 1 , 1 );
Lut -> AddRGBSegment( -0.5 , 0 , 1 , 1 , 0 , 0 , 1 , 0 );
Lut -> AddRGBSegment( 0 , 0 , 1 , 0 , 0.5 , 1 , 1 , 0 );
Lut -> AddRGBSegment( 0.5 , 1 , 1 , 0 , 10 , 1 , 0 , 0 );
m_DataList[0].setLut( Lut );
m_DataList[0].changeMapperInput();
m_MyWindowMesh.setLut( m_DataList[0].getMapper()->GetLookupTable() );
m_MyWindowMesh.updateLut( 1 );
m_MyWindowMesh.updateWindow();
}
|
#ifndef _BALL
#define _BALL
#include "ofMain.h"
class Ball
{
public:
Ball();
~Ball();
void setup();
void update();
void draw();
// variables
float x;
float y;
float speedX;
float speedY;
int dim;
ofColor color;
private:
};
#endif
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
#ifndef POOMA_DOMAIN_NEWDOMAIN_H
#define POOMA_DOMAIN_NEWDOMAIN_H
//-----------------------------------------------------------------------------
// Class:
// NewDomain structs
//-----------------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////
/** @file
* @ingroup Domain
* @brief
* A set of simple structs which tell how to combine different Domain
* objects together.
*
* They are named NewDomain1 ... NewDomain7, are
* templated on from 1 ... 7 different domain types, and provide the
* following interface:
* - NewDomain2<T1,T2>::Type_t newdom; // resulting type when Domains combined
* - NewDomain2<T1,T2>::SliceType_t slicedom; // type for 'sliced' Dom's
* - newdom = NewDomain2<T1,T2>::combine(a,b); // combine a & b, return combo
* - NewDomain2<T1,T2>::fill(newdom, a, b); // combine a & b into newdom
* - slicedom = NewDomain2<T1,T2>::combineSlice(a,b); // 'slice' a & b
* - NewDomain2<T1,T2>::fillSlice(slicedom, a, b); // 'slice' into slicedom
*
* similarly for NewDomain1, and NewDomain3 ... NewDomain7
*/
//-----------------------------------------------------------------------------
// Typedefs:
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Includes:
//-----------------------------------------------------------------------------
#include "Domain/DomainTraits.h"
#include "Utilities/PAssert.h"
//-----------------------------------------------------------------------------
// Forward Declarations:
//-----------------------------------------------------------------------------
template<int Dim> class Loc;
template<int Dim> class Interval;
template<int Dim> class Range;
template<int Dim> class Grid;
template<int Dim> class AllDomain;
template<int Dim> class LeftDomain;
template<int Dim> class RightDomain;
template<int Dim, int SliceDim> class SliceInterval;
template<int Dim, int SliceDim> class SliceRange;
template<int Dim, class T> class Region;
template<class T> class IndirectionList;
/**
* CombineDomain is a utility class used only by the 'fill*' methods
* of NewDomain2 ... NewDomain7. It is templated on the following params:
* - RT : the return domain type, which is the domain we are constructing
* - CT : the domain type being combined with RT
* - DS : the domain index at which we should start adding CT into RT
* CombineDomain takes a domain object of type CT, and combines it into
* an existing domain object RT. The domain RT is then changed. DS provides
* the 'beginning' index at which CT should be added, for example if RT
* is a dim-5 domain, CT a dim-2 domain, and DS is 1, then RT[1] is
* set to be CT[0], and RT[2] is set to be CT[1].
*
* For "slice" rules (used by fillSlice methods), a separate CombineSliceDomain
* class is available. The complication here is that SliceDomain's store two
* pieces of information (the "total" domain, and the "slice" domain), instead
* of just one (the domain). To store these values, CombineSliceDomain takes
* a slightly different set of parameters:
* - RT: the return domain type, which is the domain we are constructing
* - CT: the domain type being combined with RT
* - DS: the "total" domain index at which we should start adding CT into RT
* - SliceDS: the "slice" domain index at which we should start adding CT into RT
* - incl: if this is false, then either RT is not a SliceDomain, or the
* type CT is a "singleValued" domain which should not be included in
* the slice domain.
* If this is true, then RT is a SliceDomain, and CT is a
* domain such as Interval or Range that should be included in both
* the total domain and the slice domain. To do this, the class
* is partially specialized to the case where incl=true.
* Those specializations fill in CT into both the total
* domain of RT and the slice domain of RT.
* - wildcard: if this is true, the domain being combined, of type CT, is a
* wildcard domain, so the user must provide a "reference" domain
* with which to combine. The wildcard takes the reference domain
* and copies or modifies it based on the type of wildcard.
* if this is false, the CT domain is not a wildcard, and the user-
* supplied reference domain is ignored.
*/
//
// the general version of CombineDomain. By using DomainTraits::getDomain
// on rt, this will work for even if rt is a 1D domain.
//
template<class RT, class CT, int DS>
struct CombineDomain {
enum { DRT = DomainTraits<RT>::dimensions };
enum { DCT = DomainTraits<CT>::dimensions };
static void combine(RT &rt, const CT& ct) {
CTAssert(DS >= 0);
CTAssert(DRT > (DS + DCT - 1));
for (int i=0; i < DCT; ++i)
DomainTraits<RT>::getDomain(rt, DS + i).setDomain(
DomainTraits<CT>::getDomain(ct, i));
}
};
/**
* the general version of CombineSliceDomainWC ... this class is used
* by CombineSliceDomain to set up slice domain objects. It is similar
* to CombineDomain except that it will on occasion fill in a separate
* 'slice domain'. It can also use wildcard domains, if it is given a
* reference domain which is used by the wildcard to determine the correct
* domain. If no slicing is being done, and no wildcard is used, this
* just fills in the reduced 'slice domain'.
*/
template<class RT, class UT, class CT, int DS, int SliceDS,
bool incl, bool wc>
struct CombineSliceDomainWC {
enum { DRT = DomainTraits<RT>::dimensions };
enum { DCT = DomainTraits<CT>::dimensions };
static void combine(RT &rt, const UT &, const CT& ct) {
CTAssert(DS >= 0);
CTAssert(DRT > (DS + DCT - 1));
for (int i=0; i < DCT; ++i)
DomainTraits<RT>::getDomain(rt, DS + i).setDomain(
DomainTraits<CT>::getPointDomain(ct, i));
}
};
/**
* specialization of CombineSliceDomainWC in which we fill in slice
* domain values and full domain values, but without using wildcards
*/
template<class RT, class UT, class CT, int DS, int SliceDS>
struct CombineSliceDomainWC<RT,UT,CT,DS,SliceDS,true,false> {
enum { DRT = DomainTraits<RT>::dimensions };
enum { DCT = DomainTraits<CT>::dimensions };
static void combine(RT &rt, const UT &, const CT& ct) {
CTAssert(DS >= 0 && SliceDS >= 0);
CTAssert(DRT > (DS + DCT - 1));
for (int i=0; i < DCT; ++i) {
DomainTraits<RT>::getDomain(rt, DS + i).setDomain(
DomainTraits<CT>::getPointDomain(ct, i));
DomainTraits<RT>::setIgnorable(rt, DS + i,
DomainTraits<CT>::getIgnorable(ct, i));
}
rt.setSliceFromTotal();
}
};
/**
* specialization of CombineSliceDomainWC in which we only fill in total
* domain values, using wildcards
*/
template<class RT, class UT, class CT, int DS, int SliceDS>
struct CombineSliceDomainWC<RT,UT,CT,DS,SliceDS,false,true> {
enum { DRT = DomainTraits<RT>::dimensions };
enum { DUT = DomainTraits<UT>::dimensions };
enum { DCT = DomainTraits<CT>::dimensions };
static void combine(RT &rt, const UT &u, const CT& ct) {
CTAssert(DS >= 0);
CTAssert(DRT > (DS + DCT - 1));
CTAssert(DUT == DRT);
for (int i=0; i < DCT; ++i)
DomainTraits<RT>::getDomain(rt, DS + i).setWildcardDomain(
DomainTraits<UT>::getPointDomain(u, DS + i),
DomainTraits<CT>::getPointDomain(ct, i));
}
};
/**
* specialization of CombineSliceDomainWC in which we fill in slice
* domain values and full domain values, using wildcards
*/
template<class RT, class UT, class CT, int DS, int SliceDS>
struct CombineSliceDomainWC<RT,UT,CT,DS,SliceDS,true,true> {
enum { DRT = DomainTraits<RT>::dimensions };
enum { DUT = DomainTraits<UT>::dimensions };
enum { DCT = DomainTraits<CT>::dimensions };
static void combine(RT &rt, const UT &u, const CT& ct) {
CTAssert(DS >= 0 && SliceDS >= 0);
CTAssert(DRT > (DS + DCT - 1));
CTAssert((int)DUT == DRT);
for (int i=0; i < DCT; ++i) {
DomainTraits<RT>::getDomain(rt, DS + i).setWildcardDomain(
DomainTraits<UT>::getPointDomain(u, DS + i),
DomainTraits<CT>::getPointDomain(ct, i));
DomainTraits<RT>::getSliceDomain(rt, SliceDS + i).setWildcardDomain(
DomainTraits<UT>::getPointDomain(u, DS + i),
DomainTraits<CT>::getPointDomain(ct, i));
DomainTraits<RT>::cantIgnoreDomain(rt, DS + i);
}
}
};
/**
* the general version of CombineSliceDomain ... by default, it just
* does the same thing as CombineDomain, except, for domains which store
* a slice, it will fill in a second 'total' domain with the extra info
* about the domains that are sliced out. If the boolean type 'incl'
* is true, there is a specialization here to also fill in
* these slice dimensions. If the combining domain is a wildcard, then
* we use a separate method to fill in the domain using the user-supplied
* reference domain. To get all this done, CombineSliceDomain defers to
* a separate CombineSliceDomainWC struct which has an extra boolean
* template param 'wildcard' indicating whether to use wildcard set routines.
*/
template<class RT, class UT, class CT, int DS, int SliceDS, bool incl>
struct CombineSliceDomain {
static void combine(RT &rt, const UT &u, const CT& ct) {
CombineSliceDomainWC<RT,UT,CT,DS,SliceDS,incl,
DomainTraits<CT>::wildcard>::combine(rt, u, ct);
}
};
/** @defgroup NewDomain
* @ingroup Domain
* NewDomain2 ... NewDomain7 are simple helper structs which are used to
* combine Domain objects of different types together (when possible).
* They are basically traits classes used to tell what the type is when
* you combine several domains together, and what the combined object
* looks like.
*
* If you have N Domain objects to combine (where N is from 1 to 7),
* the type of the Domain object which results when you combine the
* Domain objects together is (for, say, combining 4 Domains of types
* T1, T2, T3, and T4 together)
* NewDomain4<T1,T2,T3,T4>::Type_t
*
* The new Domain will be one of the Domain types listed in the include and
* forward ref sections above. Generally, combining a more specific
* type of domain with a more general type of domain (say, a Loc with a
* Range) results in return domain type of the more general category. E.g.,
* in the case of combining a Loc with Range, the result would be a Range.
*
* The dimension of the new Domain will be the sum of the dimensions of
* the input objects. The dimensions will be filled in from left to right
* from the arguments, going from 1 ... Dim for the dimensions. For example,
* if you combine three domains, the first of Dim 2, the next of Dim 1,
* the third of Dim 2, the result will be of Dim=5, and will have Dim 1&2
* taken from the first argument, Dim 3 from the second, and Dim 4&5 from
* the third.
*
* To combine domains together, there are two possibilities:
* -# combine them into a separate object, returned by the 'combine' method
* This takes N domain objects, and puts them into a new domain object
* of type NewDomainN<T1,T2,...,TN>::Type_t. The method
* Type_t NewDomainN<...>::combine(a,b,c,d,...)
* will combine the elements a, b, c, ... and return a new domain object
* -# fill them into a provided domain object, using the 'fill' method
* This does a similar thing as 'combine', but is more efficient since
* the user provides (in the first argument to 'fill') the domain object
* into which the elements should be combined. The syntax is
* void NewDomainN<...>::fill(retval,a,b,c,d,...)
* where a,b,c,d,... are the domain object to combine together, and
* retval is the domain object which should hold the result. Note that
* retval is a templated item, it does not have to be the same type as
* NewDomainN<...>::Type_t. fill returns a reference to the retval
* item.
*
* Both of these methods will perform 1D assigments of pieces of the domains
* to the resulting domain object, using the setDomain method of a 1D
* domain object.
*
* Determining the type of the combined domain is done pair-wise, starting
* with the first two types, then combining the result of that with the
* third type, etc. So, most of the work here is in NewDomain2, which
* must be specialized for the different possible pairwise combinations.
* The other NewDomainN's then use NewDomain2 and NewDomain(N-1)'s.
*
* There is actually more than one way to combine Domain objects together.
* Each method has an associated set of typedef and combine/fill methods.
* The above discussion was just for one of these methods; the different
* combining methods are:
* -# "Domain/Array constructor" rules:
* this combining method is applicable to
* the situation that exists when combining domain objects together
* in the constructors/operator='s of domain objects. In this case,
* the total dimension of the resulting object is the sum of the
* dimensions of the arguments. Loc<1> objects are treated like
* single points, but int's are treated like Interval<1> objects of
* size 0 ... int value - 1. For this case,
* the typedefs and combine/fill methods are:
* - NewDomainN::Type_t; // typedef
* - NewDomainN::Type_t NewDomainN::combine(a,b,...); // combine
* - void NewDomainN::fill(retval, a, b, ...); // fill
* -# "Slice" rules:
* this combining method is applicable to the situation
* that exists when combining domain objects together in the operator()'s
* of Array objects. In this case, the resulting domain may represent
* a "slice" of the full domain which would have been created if
* "domain constructor" rules had been applied. The slice is actually
* a lower-dimensional subdomain of the complete domain. Specifying
* a Loc or int for one or more of the dimensions in the operator() will
* result in that dimension being "sliced out", so that the total dim
* of the slice = sum of dimensions of Interval, Range objects
* - sum dimensions of Loc and int objects. If slice rules are used,
* and any Loc or int objects are being combined in, the resulting
* domain object will be a SliceDomain subclass (e.g., SliceInterval,
* SliceRange, whatever is the most general based on the other combined
* domain types). This SliceDomain subclass is templated on the total
* dimension, and the slice dimension, where slicedim < totaldim. If
* slice rules are used, but no singleValue'd domains are used, then
* regular "domain constructor" rules apply. The pairwise combination
* mechanism only allows you to combine a SliceDomain subclass with
* a non-SliceDomain, which means that you cannot combine, say,
* a SliceInterval with a SliceRange. Since slice domain objects are
* only meant for internal use when constructing a subdimensional
* Array from a larger dimensional Array, this is all that is needed.
* For this case, the typedefs and methods are:
* - NewDomainN::SliceType_t; // typedef
* - NewDomainN::SliceType_t NewDomainN::combineSlice(a,b,..); // combine
* - void NewDomainN::fillSlice(retval, a, b, ...); // fill
*
* So, to use NewDomainN objects, first determine what kind of combining
* rules you need in your particular context, and then use the relevant
* set of typedef and combine/fill methods from the list above.
*/
/** @addtogroup NewDomain
* A simple base class for all specialized NewDomain2 objects, defining
* the functions which all have in common. This is most easily done through
* a base class, since we need to define several different specializations
* of NewDomain2.
*/
template<class T1, class T2, class TCombine, class TSCombine>
struct NewDomain2Base
{
// the Type_t typedef is provided by the derived class as the TCombine param,
// the SliceType_t typedef is provided via the TSCombine param.
typedef TCombine Type_t;
typedef TSCombine SliceType_t;
// static data
enum { S2 = DomainTraits<T1>::dimensions };
enum { DX1 = DomainTraits<T1>::sliceDimensions };
enum { DX2 = DomainTraits<T2>::sliceDimensions };
// combine is used to combine two items together
inline static Type_t combine(const T1 &a, const T2 &b)
{
Type_t retval = Pooma::NoInit();
return fill(retval, a, b);
}
// fill does the same as combine, but fills info into an arbitrary type
// RT instead of into a newly-created instance of type Type_t
template<class RT>
inline static RT &fill(RT &retval, const T1 &a, const T2 &b)
{
CombineDomain<RT,T1,0>::combine(retval,a);
CombineDomain<RT,T2,S2>::combine(retval,b);
return retval;
}
// combineSlice is used to combine items together using the 'slice' domain.
// It uses a given 'user' domain which, if wildcards are being combined
// here, is used to fill in the resulting domain. It should have the
// same number of dimensions as the SliceType_t domain.
template<class UT>
inline static SliceType_t combineSlice(const UT &u,
const T1 &a, const T2 &b)
{
SliceType_t retval = Pooma::NoInit();
return fillSlice(retval, u, a, b);
}
// fillSlice does the same as combineSlice, but fills info into an arbitrary
// type RT instead of into a newly-created instance of type SliceType_t.
template<class RT, class UT>
inline static RT &fillSlice(RT &retval, const UT &u,
const T1 &a, const T2 &b)
{
enum { RDX =
DomainTraits<RT>::dimensions > DomainTraits<RT>::sliceDimensions };
CombineSliceDomain<RT,UT,T1,0,0,(DX1>0 && RDX)>::
combine(retval,u,a);
CombineSliceDomain<RT,UT,T2,S2,DX1,(DX2>0 && RDX)>::
combine(retval,u,b);
return retval;
}
};
/** @class NewDomain2
* @addtogroup NewDomain
* The general version of NewDomain2. The allowed versions of NewDomain2
* are given as partial specializations of this general case. The general
* case assumes T1 and T2 are single-valued domains for which DomainTraits
* exist, that combine together to form Interval's (or Loc's for slice
* combine rules).
*/
// first, create a simple struct used to add two dimensions together at
// compile time
template<class T1, class T2>
struct AddNewDomain2Dimensions
{
enum { dimensions =
DomainTraits<T1>::dimensions + DomainTraits<T2>::dimensions };
};
template<class T1, class T2>
struct NewDomain2
: public NewDomain2Base<T1, T2,
Interval<AddNewDomain2Dimensions<T1,T2>::dimensions>,
Loc<AddNewDomain2Dimensions<T1,T2>::dimensions> >
{ };
//-----------------------------------------------------------------------------
// Specific versions of NewDomain2, for all the allowed combinations.
//-----------------------------------------------------------------------------
// macros for use in defining NewDomain2. The first sets up the
// combination of a domain with itself and with an int or Loc. The second
// sets up the combination of a domain with another domain of a different
// type. The third sets up the combination of a SliceDomain with another
// domain type.
//
// The rules for combining domains using "domain/array constructor" rules are:
// 1. int's, char's, shorts's, long's are treated as Interval<1>(int val),
// e.g., 7 ==> Interval<1>(7)
// 2. The resulting domain is the most general which can store all the
// combined objects.
// 3. The final number of dimensions = sum of dimension of combined domains
//
// The rules for combining slice domains deserve special attention. They are:
// 1. Slice domains can only be combined with non-slice domains
// 2. Combining a slice domain with an int or Loc (or any single-valued
// domain) increases the total dimension of the domain, but not the
// slice dimension
// 3. Combining a slice domain with any other non-slice domain increases
// both the total dimension and the slice dimension
#define POOMA_NEWDOMAIN_SAME_SCALAR(DOM,SLICEDOM,S) \
template <int D> \
struct NewDomain2< DOM<D>, S > \
: public NewDomain2Base< DOM<D>, S, DOM<D+1>, SLICEDOM<D+1,D> > { }; \
template <int D> \
struct NewDomain2< S, DOM<D> > \
: public NewDomain2Base< S, DOM<D>, DOM<D+1>, SLICEDOM<D+1,D> > { }; \
template <int D> \
struct NewDomain2< DOM<D>, unsigned S > \
: public NewDomain2Base< DOM<D>, unsigned S, DOM<D+1>, SLICEDOM<D+1,D> > \
{ }; \
template <int D> \
struct NewDomain2< unsigned S, DOM<D> > \
: public NewDomain2Base< unsigned S, DOM<D>, DOM<D+1>, SLICEDOM<D+1,D> > \
{ };
#define POOMA_NEWDOMAIN_SAME(DOM,SLICEDOM) \
template <int D1, int D2> \
struct NewDomain2< DOM<D1>, DOM<D2> > \
: public NewDomain2Base< DOM<D1>, DOM<D2>, DOM<D1+D2>, DOM<D1+D2> > { }; \
template <int D1, int D2> \
struct NewDomain2< DOM<D1>, Loc<D2> > \
: public NewDomain2Base< DOM<D1>, Loc<D2>, DOM<D1+D2>, \
SLICEDOM<D1+D2,D1> > { }; \
template <int D1, int D2> \
struct NewDomain2< Loc<D2>, DOM<D1> > \
: public NewDomain2Base< Loc<D2>, DOM<D1>, DOM<D1+D2>, \
SLICEDOM<D1+D2,D1> > { }; \
POOMA_NEWDOMAIN_SAME_SCALAR(DOM,SLICEDOM,char) \
POOMA_NEWDOMAIN_SAME_SCALAR(DOM,SLICEDOM,short) \
POOMA_NEWDOMAIN_SAME_SCALAR(DOM,SLICEDOM,int) \
POOMA_NEWDOMAIN_SAME_SCALAR(DOM,SLICEDOM,long)
#define POOMA_NEWDOMAIN_OTHER(DOM1,DOM2) \
template <int D1, int D2> \
struct NewDomain2< DOM1<D1>, DOM2<D2> > \
: public NewDomain2Base< DOM1<D1>, DOM2<D2>, DOM1<D1+D2>, DOM1<D1+D2> > \
{ }; \
template <int D1, int D2> \
struct NewDomain2< DOM2<D1>, DOM1<D2> > \
: public NewDomain2Base< DOM2<D1>, DOM1<D2>, DOM1<D1+D2>, DOM1<D1+D2> > \
{ };
#define POOMA_NEWDOMAIN_SLICE_SAME_SCALAR(SLICEDOM,S) \
template <int D1, int DS1> \
struct NewDomain2< SLICEDOM<D1,DS1>, S > \
: public NewDomain2Base< SLICEDOM<D1,DS1>, S ,SLICEDOM<D1+1,DS1>, \
SLICEDOM<D1+1,DS1> > { }; \
template <int D1, int DS1> \
struct NewDomain2< SLICEDOM<D1,DS1>, unsigned S > \
: public NewDomain2Base< SLICEDOM<D1,DS1>, unsigned S, \
SLICEDOM<D1+1,DS1>, SLICEDOM<D1+1,DS1> > { }; \
template <int D1, int DS1> \
struct NewDomain2< S, SLICEDOM<D1,DS1> > \
: public NewDomain2Base< S, SLICEDOM<D1,DS1>, SLICEDOM<D1+1,DS1>, \
SLICEDOM<D1+1,DS1> > { }; \
template <int D1, int DS1> \
struct NewDomain2< unsigned S, SLICEDOM<D1,DS1> > \
: public NewDomain2Base< unsigned S, SLICEDOM<D1,DS1>, \
SLICEDOM<D1+1,DS1>, SLICEDOM<D1+1,DS1> > { };
#define POOMA_NEWDOMAIN_SLICE_SAME(SLICEDOM) \
template <int D1, int DS1, int D2> \
struct NewDomain2< SLICEDOM<D1,DS1>, Loc<D2> > \
: public NewDomain2Base< SLICEDOM<D1,DS1>, Loc<D2>, SLICEDOM<D1+D2,DS1>, \
SLICEDOM<D1+D2,DS1> > { }; \
template <int D1, int DS1, int D2> \
struct NewDomain2< Loc<D2>, SLICEDOM<D1,DS1> > \
: public NewDomain2Base< Loc<D2>, SLICEDOM<D1,DS1>, SLICEDOM<D1+D2,DS1>, \
SLICEDOM<D1+D2,DS1> > { }; \
POOMA_NEWDOMAIN_SLICE_SAME_SCALAR(SLICEDOM,char) \
POOMA_NEWDOMAIN_SLICE_SAME_SCALAR(SLICEDOM,short) \
POOMA_NEWDOMAIN_SLICE_SAME_SCALAR(SLICEDOM,int) \
POOMA_NEWDOMAIN_SLICE_SAME_SCALAR(SLICEDOM,long)
#define POOMA_NEWDOMAIN_SLICE_OTHER(DOM1,DOM2,SLICEDOM) \
template <int D1, int DS1, int D2> \
struct NewDomain2< DOM1<D1,DS1>, DOM2<D2> > \
: public NewDomain2Base< DOM1<D1,DS1>, DOM2<D2>, SLICEDOM<D1+D2,DS1+D2>, \
SLICEDOM<D1+D2,DS1+D2> > { }; \
template <int D1, int DS1, int D2> \
struct NewDomain2< DOM2<D2>, DOM1<D1,DS1> > \
: public NewDomain2Base< DOM2<D2>, DOM1<D1,DS1>, SLICEDOM<D1+D2,DS1+D2>, \
SLICEDOM<D1+D2,DS1+D2> > { };
//
// Range with others
//
POOMA_NEWDOMAIN_SAME(Range,SliceRange)
POOMA_NEWDOMAIN_OTHER(Range,Interval)
POOMA_NEWDOMAIN_OTHER(Range,AllDomain)
POOMA_NEWDOMAIN_OTHER(Range,LeftDomain)
POOMA_NEWDOMAIN_OTHER(Range,RightDomain)
POOMA_NEWDOMAIN_SLICE_SAME(SliceRange)
POOMA_NEWDOMAIN_SLICE_OTHER(SliceRange,Range,SliceRange)
POOMA_NEWDOMAIN_SLICE_OTHER(SliceRange,Interval,SliceRange)
POOMA_NEWDOMAIN_SLICE_OTHER(SliceRange,AllDomain,SliceRange)
POOMA_NEWDOMAIN_SLICE_OTHER(SliceRange,LeftDomain,SliceRange)
POOMA_NEWDOMAIN_SLICE_OTHER(SliceRange,RightDomain,SliceRange)
//
// Interval with others
//
POOMA_NEWDOMAIN_SAME(Interval,SliceInterval)
POOMA_NEWDOMAIN_OTHER(Interval,AllDomain)
POOMA_NEWDOMAIN_OTHER(Interval,LeftDomain)
POOMA_NEWDOMAIN_OTHER(Interval,RightDomain)
POOMA_NEWDOMAIN_SLICE_SAME(SliceInterval)
POOMA_NEWDOMAIN_SLICE_OTHER(SliceInterval,Interval,SliceInterval)
POOMA_NEWDOMAIN_SLICE_OTHER(SliceInterval,Range,SliceRange)
POOMA_NEWDOMAIN_SLICE_OTHER(SliceInterval,AllDomain,SliceInterval)
POOMA_NEWDOMAIN_SLICE_OTHER(SliceInterval,LeftDomain,SliceInterval)
POOMA_NEWDOMAIN_SLICE_OTHER(SliceInterval,RightDomain,SliceInterval)
//
// Wildcards with themselves
//
POOMA_NEWDOMAIN_SAME(AllDomain,SliceInterval)
POOMA_NEWDOMAIN_SAME(LeftDomain,SliceInterval)
POOMA_NEWDOMAIN_SAME(RightDomain,SliceInterval)
POOMA_NEWDOMAIN_OTHER(AllDomain,LeftDomain)
POOMA_NEWDOMAIN_OTHER(AllDomain,RightDomain)
POOMA_NEWDOMAIN_OTHER(LeftDomain,RightDomain)
//
// Grid with others
//
POOMA_NEWDOMAIN_SAME(Grid,SliceRange)
POOMA_NEWDOMAIN_OTHER(Grid,Range)
POOMA_NEWDOMAIN_OTHER(Grid,Interval)
POOMA_NEWDOMAIN_OTHER(Grid,AllDomain)
POOMA_NEWDOMAIN_OTHER(Grid,LeftDomain)
POOMA_NEWDOMAIN_OTHER(Grid,RightDomain)
//
// Grid with IndirectionList
//
template<int D>
struct NewDomain2< Grid<D>, IndirectionList<int> >
: public NewDomain2Base<Grid<D>,IndirectionList<int>,Grid<D+1>,Grid<D+1> >{};
template<int D>
struct NewDomain2< IndirectionList<int>, Grid<D> >
: public NewDomain2Base<IndirectionList<int>,Grid<D>,Grid<D+1>,Grid<D+1> >{};
//
// complete specializations for Loc with Loc. Other combinations of Loc
// with a scalar are covered by the default case.
//
template<int D1, int D2>
struct NewDomain2< Loc<D1>, Loc<D2> >
: public NewDomain2Base<Loc<D1>, Loc<D2>, Loc<D1+D2>, Loc<D1+D2> > { };
//
// macros for use in defining combinations of continuous domains
//
#define POOMA_NEWDOMAIN_CONTINUOUS_SAME(DOM) \
template <int D1, class T1, int D2, class T2> \
struct NewDomain2< DOM<D1,T1>, DOM<D2,T2> > \
: public NewDomain2Base< DOM<D1,T1>, DOM<D2,T2>, DOM<D1+D2,T1>, \
DOM<D1+D2,T1> > { };
#define POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(DOM,S) \
template <int D1, class T1> \
struct NewDomain2< DOM<D1,T1>, S > \
: public NewDomain2Base< DOM<D1,T1>, S, DOM<D1+1,T1>, DOM<D1+1,T1> > \
{ }; \
template <int D1, class T1> \
struct NewDomain2< S, DOM<D1,T1> > \
: public NewDomain2Base< S, DOM<D1,T1>, DOM<D1+1,T1>, DOM<D1+1,T1> > \
{ };
#define POOMA_NEWDOMAIN_CONTINUOUS_OTHER(DOM1,DOM2) \
template <int D1, class T1, int D2> \
struct NewDomain2< DOM1<D1,T1>, DOM2<D2> > \
: public NewDomain2Base< DOM1<D1,T1>, DOM2<D2>, DOM1<D1+D2,T1>, \
DOM1<D1+D2,T1> > { }; \
template <int D1, class T1, int D2> \
struct NewDomain2< DOM2<D2>, DOM1<D1,T1> > \
: public NewDomain2Base< DOM2<D2>, DOM1<D1,T1>, DOM1<D1+D2,T1>, \
DOM1<D1+D2,T1> > { };
#define POOMA_NEWDOMAIN_JUST_SCALAR_SAME(S,DOM) \
template <> \
struct NewDomain2<S, S> \
: public NewDomain2Base< S, S, DOM<2,S>, DOM<2,S> > { };
#define POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(S1,S2,DOM,S3) \
template <> \
struct NewDomain2<S1, S2> \
: public NewDomain2Base< S1, S2, DOM<2,S3>, DOM<2,S3> > { }; \
template <> \
struct NewDomain2<S2, S1> \
: public NewDomain2Base< S2, S1, DOM<2,S3>, DOM<2,S3> > { };
#define POOMA_NEWDOMAIN_JUST_SCALAR_DOMAIN(S,DOM1,DOM2) \
template <int D1> \
struct NewDomain2< S, DOM1<D1> > \
: public NewDomain2Base< S, DOM1<D1>, DOM2<D1+1,S>, DOM2<D1+1,S> > { }; \
template <int D1> \
struct NewDomain2< DOM1<D1>, S > \
: public NewDomain2Base< DOM1<D1>, S, DOM2<D1+1,S>, DOM2<D1+1,S> > { };
//
// combinations involving Region
//
POOMA_NEWDOMAIN_CONTINUOUS_SAME(Region)
POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(Region,char)
POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(Region,unsigned char)
POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(Region,short)
POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(Region,unsigned short)
POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(Region,int)
POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(Region,unsigned int)
POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(Region,long)
POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(Region,unsigned long)
POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(Region,float)
POOMA_NEWDOMAIN_CONTINUOUS_SCALAR(Region,double)
POOMA_NEWDOMAIN_CONTINUOUS_OTHER(Region,Range)
POOMA_NEWDOMAIN_CONTINUOUS_OTHER(Region,Interval)
POOMA_NEWDOMAIN_CONTINUOUS_OTHER(Region,Loc)
POOMA_NEWDOMAIN_CONTINUOUS_OTHER(Region,AllDomain)
POOMA_NEWDOMAIN_CONTINUOUS_OTHER(Region,LeftDomain)
POOMA_NEWDOMAIN_CONTINUOUS_OTHER(Region,RightDomain)
//
// combinations involving scalars other than int
//
POOMA_NEWDOMAIN_JUST_SCALAR_SAME(double,Region)
POOMA_NEWDOMAIN_JUST_SCALAR_SAME(float,Region)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(double,char,Region,double)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(double,unsigned char,Region,double)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(double,short,Region,double)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(double,unsigned short,Region,double)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(double,int,Region,double)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(double,unsigned int,Region,double)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(double,long,Region,double)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(double,unsigned long,Region,double)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(double,float,Region,double)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(float,char,Region,float)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(float,unsigned char,Region,float)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(float,short,Region,float)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(float,unsigned short,Region,float)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(float,int,Region,float)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(float,unsigned int,Region,float)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(float,long,Region,float)
POOMA_NEWDOMAIN_JUST_SCALAR_OTHER(float,unsigned long,Region,float)
POOMA_NEWDOMAIN_JUST_SCALAR_DOMAIN(double,Loc,Region)
POOMA_NEWDOMAIN_JUST_SCALAR_DOMAIN(double,Interval,Region)
POOMA_NEWDOMAIN_JUST_SCALAR_DOMAIN(double,Range,Region)
POOMA_NEWDOMAIN_JUST_SCALAR_DOMAIN(float,Loc,Region)
POOMA_NEWDOMAIN_JUST_SCALAR_DOMAIN(float,Interval,Region)
POOMA_NEWDOMAIN_JUST_SCALAR_DOMAIN(float,Range,Region)
/** @addtogroup NewDomain
* NewDomainNBase: a base class for all NewDomainN classes for N >= 3.
* This just simplifies the work of specifying all the typedefs for the
* combination results. The implementations of the combine and fill
* routines are left to the NewDomainN classes which are derived from
* NewDomainNBase.
* T = final type in list of types for NewDomainN. Each NewDomainN is
* templated on N types T1 ... TN. T should be the same as TN.
* ND = type of lower-dimensional NewDomainN class which the subclass will
* build on. For example, NewDomain4<T1,..T4> should be derived from
* NewDomainNBase<NewDomain3<T1,T2,T3>, T4>. Thus, in this case, we have
* ND ==> NewDomain3<T1,T2,T3>, and T ==> T4.
*/
template<class ND, class T>
struct NewDomainNBase
{
typedef typename ND::Type_t PrevType_t;
typedef typename ND::SliceType_t PrevSliceType_t;
typedef typename NewDomain2<PrevType_t,T>::Type_t Type_t;
typedef typename NewDomain2<PrevSliceType_t,T>::SliceType_t SliceType_t;
};
/** @addtogroup NewDomain
* NewDomain1 ... NewDomain7: these build on each other pairwise, eventually
* returning back to NewDomain2 for the final determination. NewDomain1
* does no actual combining, just a conversion; and NewDomain2 is defined
* already above.
*/
template<class T1>
struct NewDomain1
{
// typedefs
typedef typename DomainTraits<T1>::Domain_t Type_t;
typedef typename DomainTraits<T1>::NewDomain1_t SliceType_t;
// static data
enum { DX1 = DomainTraits<T1>::sliceDimensions };
inline static Type_t combine(const T1 &a)
{
Type_t retval = Pooma::NoInit();
return fill(retval, a);
}
template<class RT>
inline static RT &fill(RT &retval, const T1 &a)
{
CombineDomain<RT,T1,0>::combine(retval,a);
return retval;
}
template<class UT>
inline static SliceType_t combineSlice(const UT &u, const T1 &a)
{
SliceType_t retval = Pooma::NoInit();
return fillSlice(retval, u, a);
}
template<class RT, class UT>
inline static RT &fillSlice(RT &retval, const UT &u,
const T1 &a)
{
enum { RDX =
DomainTraits<RT>::dimensions > DomainTraits<RT>::sliceDimensions };
CombineSliceDomain<RT,UT,T1,0,0,(DX1>0 && RDX)>::combine(retval,u,a);
return retval;
}
};
template<class T1, class T2, class T3>
struct NewDomain3 : public NewDomainNBase<NewDomain2<T1,T2>, T3>
{
// typedefs
typedef typename NewDomainNBase<NewDomain2<T1,T2>, T3>::Type_t Type_t;
typedef typename NewDomainNBase<NewDomain2<T1,T2>, T3>::SliceType_t SliceType_t;
// static data
enum { S2 = DomainTraits<T1>::dimensions };
enum { S3 = S2 + DomainTraits<T2>::dimensions };
enum { DX1 = DomainTraits<T1>::sliceDimensions };
enum { DX2 = DomainTraits<T2>::sliceDimensions };
enum { DX3 = DomainTraits<T3>::sliceDimensions };
inline static Type_t combine(const T1 &a, const T2 &b, const T3 &c)
{
Type_t retval = Pooma::NoInit();
return fill(retval, a, b, c);
}
template<class RT>
inline static RT &fill(RT &retval,
const T1 &a, const T2 &b, const T3 &c)
{
CombineDomain<RT,T1,0>::combine(retval,a);
CombineDomain<RT,T2,S2>::combine(retval,b);
CombineDomain<RT,T3,S3>::combine(retval,c);
return retval;
}
template<class UT>
inline static SliceType_t combineSlice(const UT &u,
const T1 &a, const T2 &b, const T3 &c)
{
SliceType_t retval = Pooma::NoInit();
return fillSlice(retval, u, a, b, c);
}
template<class RT, class UT>
inline static RT &fillSlice(RT &retval, const UT &u,
const T1 &a, const T2 &b, const T3 &c)
{
enum { RDX =
DomainTraits<RT>::dimensions > DomainTraits<RT>::sliceDimensions };
CombineSliceDomain<RT,UT,T1,0,0,(DX1>0 && RDX)>::combine(retval,u,a);
CombineSliceDomain<RT,UT,T2,S2,DX1,(DX2>0 && RDX)>::combine(retval,u,b);
CombineSliceDomain<RT,UT,T3,S3,DX1+DX2,(DX3>0 && RDX)>::
combine(retval,u,c);
return retval;
}
};
template<class T1, class T2, class T3, class T4>
struct NewDomain4 : public NewDomainNBase<NewDomain3<T1,T2,T3>, T4>
{
// typedefs
typedef typename NewDomainNBase<NewDomain3<T1,T2,T3>, T4>::Type_t Type_t;
typedef typename NewDomainNBase<NewDomain3<T1,T2,T3>, T4>::SliceType_t
SliceType_t;
// static data
enum { S2 = DomainTraits<T1>::dimensions };
enum { S3 = S2 + DomainTraits<T2>::dimensions };
enum { S4 = S3 + DomainTraits<T3>::dimensions };
enum { DX1 = DomainTraits<T1>::sliceDimensions };
enum { DX2 = DomainTraits<T2>::sliceDimensions };
enum { DX3 = DomainTraits<T3>::sliceDimensions };
enum { DX4 = DomainTraits<T4>::sliceDimensions };
inline static Type_t combine(const T1 &a, const T2 &b, const T3 &c,
const T4 &d)
{
Type_t retval = Pooma::NoInit();
return fill(retval, a, b, c, d);
}
template<class RT>
inline static RT &fill(RT &retval,
const T1 &a, const T2 &b, const T3 &c,
const T4 &d)
{
CombineDomain<RT,T1,0>::combine(retval,a);
CombineDomain<RT,T2,S2>::combine(retval,b);
CombineDomain<RT,T3,S3>::combine(retval,c);
CombineDomain<RT,T4,S4>::combine(retval,d);
return retval;
}
template<class UT>
inline static SliceType_t combineSlice(const UT &u,
const T1 &a, const T2 &b, const T3 &c,
const T4 &d)
{
SliceType_t retval = Pooma::NoInit();
return fillSlice(retval, u, a, b, c, d);
}
template<class RT, class UT>
inline static RT &fillSlice(RT &retval, const UT &u,
const T1 &a, const T2 &b, const T3 &c,
const T4 &d)
{
enum { RDX =
DomainTraits<RT>::dimensions > DomainTraits<RT>::sliceDimensions };
CombineSliceDomain<RT,UT,T1,0,0,(DX1>0 && RDX)>::combine(retval,u,a);
CombineSliceDomain<RT,UT,T2,S2,DX1,(DX2>0 && RDX)>::combine(retval,u,b);
CombineSliceDomain<RT,UT,T3,S3,DX1+DX2,(DX3>0 && RDX)>::
combine(retval,u,c);
CombineSliceDomain<RT,UT,T4,S4,DX1+DX2+DX3,(DX4>0 && RDX)>::
combine(retval,u,d);
return retval;
}
};
template<class T1, class T2, class T3, class T4, class T5>
struct NewDomain5 : public NewDomainNBase<NewDomain4<T1,T2,T3,T4>, T5>
{
// typedefs
typedef typename NewDomainNBase<NewDomain4<T1,T2,T3,T4>, T5>::Type_t Type_t;
typedef typename NewDomainNBase<NewDomain4<T1,T2,T3,T4>, T5>::SliceType_t
SliceType_t;
// static data
enum { S2 = DomainTraits<T1>::dimensions };
enum { S3 = S2 + DomainTraits<T2>::dimensions };
enum { S4 = S3 + DomainTraits<T3>::dimensions };
enum { S5 = S4 + DomainTraits<T4>::dimensions };
enum { DX1 = DomainTraits<T1>::sliceDimensions };
enum { DX2 = DomainTraits<T2>::sliceDimensions };
enum { DX3 = DomainTraits<T3>::sliceDimensions };
enum { DX4 = DomainTraits<T4>::sliceDimensions };
enum { DX5 = DomainTraits<T5>::sliceDimensions };
inline static Type_t combine(const T1 &a, const T2 &b, const T3 &c,
const T4 &d, const T5 &e)
{
Type_t retval = Pooma::NoInit();
return fill(retval, a, b, c, d, e);
}
template<class RT>
inline static RT &fill(RT &retval,
const T1 &a, const T2 &b, const T3 &c,
const T4 &d, const T5 &e)
{
CombineDomain<RT,T1,0>::combine(retval,a);
CombineDomain<RT,T2,S2>::combine(retval,b);
CombineDomain<RT,T3,S3>::combine(retval,c);
CombineDomain<RT,T4,S4>::combine(retval,d);
CombineDomain<RT,T5,S5>::combine(retval,e);
return retval;
}
template<class UT>
inline static SliceType_t combineSlice(const UT &u,
const T1 &a, const T2 &b, const T3 &c,
const T4 &d, const T5 &e)
{
SliceType_t retval = Pooma::NoInit();
return fillSlice(retval, u, a, b, c, d, e);
}
template<class RT, class UT>
inline static RT &fillSlice(RT &retval, const UT &u,
const T1 &a, const T2 &b, const T3 &c,
const T4 &d, const T5 &e)
{
enum { RDX =
DomainTraits<RT>::dimensions > DomainTraits<RT>::sliceDimensions };
CombineSliceDomain<RT,UT,T1,0,0,(DX1>0 && RDX)>::combine(retval,u,a);
CombineSliceDomain<RT,UT,T2,S2,DX1,(DX2>0 && RDX)>::combine(retval,u,b);
CombineSliceDomain<RT,UT,T3,S3,DX1+DX2,(DX3>0 && RDX)>::
combine(retval,u,c);
CombineSliceDomain<RT,UT,T4,S4,DX1+DX2+DX3,(DX4>0 && RDX)>::
combine(retval,u,d);
CombineSliceDomain<RT,UT,T5,S5,DX1+DX2+DX3+DX4,(DX5>0 && RDX)>::
combine(retval,u,e);
return retval;
}
};
template<class T1, class T2, class T3, class T4, class T5, class T6>
struct NewDomain6 : public NewDomainNBase<NewDomain5<T1,T2,T3,T4,T5>, T6>
{
// typedefs
typedef typename
NewDomainNBase<NewDomain5<T1,T2,T3,T4,T5>, T6>::Type_t Type_t;
typedef typename
NewDomainNBase<NewDomain5<T1,T2,T3,T4,T5>, T6>::SliceType_t SliceType_t;
// static data
enum { S2 = DomainTraits<T1>::dimensions };
enum { S3 = S2 + DomainTraits<T2>::dimensions };
enum { S4 = S3 + DomainTraits<T3>::dimensions };
enum { S5 = S4 + DomainTraits<T4>::dimensions };
enum { S6 = S5 + DomainTraits<T5>::dimensions };
enum { DX1 = DomainTraits<T1>::sliceDimensions };
enum { DX2 = DomainTraits<T2>::sliceDimensions };
enum { DX3 = DomainTraits<T3>::sliceDimensions };
enum { DX4 = DomainTraits<T4>::sliceDimensions };
enum { DX5 = DomainTraits<T5>::sliceDimensions };
enum { DX6 = DomainTraits<T6>::sliceDimensions };
inline static Type_t combine(const T1 &a, const T2 &b,
const T3 &c, const T4 &d,
const T5 &e, const T6 &f)
{
Type_t retval = Pooma::NoInit();
return fill(retval, a, b, c, d, e, f);
}
template<class RT>
inline static RT &fill(RT &retval,
const T1 &a, const T2 &b,
const T3 &c, const T4 &d,
const T5 &e, const T6 &f)
{
CombineDomain<RT,T1,0>::combine(retval,a);
CombineDomain<RT,T2,S2>::combine(retval,b);
CombineDomain<RT,T3,S3>::combine(retval,c);
CombineDomain<RT,T4,S4>::combine(retval,d);
CombineDomain<RT,T5,S5>::combine(retval,e);
CombineDomain<RT,T6,S6>::combine(retval,f);
return retval;
}
template<class UT>
inline static SliceType_t combineSlice(const UT &u,
const T1 &a, const T2 &b,
const T3 &c, const T4 &d,
const T5 &e, const T6 &f)
{
SliceType_t retval = Pooma::NoInit();
return fillSlice(retval, u, a, b, c, d, e, f);
}
template<class RT, class UT>
inline static RT &fillSlice(RT &retval, const UT &u,
const T1 &a, const T2 &b, const T3 &c,
const T4 &d, const T5 &e, const T6 &f)
{
enum { RDX =
DomainTraits<RT>::dimensions > DomainTraits<RT>::sliceDimensions };
CombineSliceDomain<RT,UT,T1,0,0,(DX1>0 && RDX)>::combine(retval,u,a);
CombineSliceDomain<RT,UT,T2,S2,DX1,(DX2>0 && RDX)>::combine(retval,u,b);
CombineSliceDomain<RT,UT,T3,S3,DX1+DX2,(DX3>0 && RDX)>::
combine(retval,u,c);
CombineSliceDomain<RT,UT,T4,S4,DX1+DX2+DX3,(DX4>0 && RDX)>::
combine(retval,u,d);
CombineSliceDomain<RT,UT,T5,S5,DX1+DX2+DX3+DX4,(DX5>0 && RDX)>::
combine(retval,u,e);
CombineSliceDomain<RT,UT,T6,S6,DX1+DX2+DX3+DX4+DX5,(DX6>0 && RDX)>::
combine(retval,u,f);
return retval;
}
};
template<class T1, class T2, class T3, class T4, class T5, class T6, class T7>
struct NewDomain7 : public NewDomainNBase<NewDomain6<T1,T2,T3,T4,T5,T6>, T7>
{
// typedefs
typedef typename
NewDomainNBase<NewDomain6<T1,T2,T3,T4,T5,T6>, T7>::Type_t Type_t;
typedef typename
NewDomainNBase<NewDomain6<T1,T2,T3,T4,T5,T6>, T7>::SliceType_t SliceType_t;
// static data
enum { S2 = DomainTraits<T1>::dimensions };
enum { S3 = S2 + DomainTraits<T2>::dimensions };
enum { S4 = S3 + DomainTraits<T3>::dimensions };
enum { S5 = S4 + DomainTraits<T4>::dimensions };
enum { S6 = S5 + DomainTraits<T5>::dimensions };
enum { S7 = S6 + DomainTraits<T6>::dimensions };
enum { DX1 = DomainTraits<T1>::sliceDimensions };
enum { DX2 = DomainTraits<T2>::sliceDimensions };
enum { DX3 = DomainTraits<T3>::sliceDimensions };
enum { DX4 = DomainTraits<T4>::sliceDimensions };
enum { DX5 = DomainTraits<T5>::sliceDimensions };
enum { DX6 = DomainTraits<T6>::sliceDimensions };
enum { DX7 = DomainTraits<T7>::sliceDimensions };
inline static Type_t combine(const T1 &a, const T2 &b,
const T3 &c, const T4 &d,
const T5 &e, const T6 &f,
const T7 &g)
{
Type_t retval = Pooma::NoInit();
NewDomain7<T1,T2,T3,T4,T5,T6,T7>::fill(retval, a, b, c, d, e, f, g);
return fill(retval, a, b, c, d, e, f,g);
}
template<class RT>
inline static RT &fill(RT &retval,
const T1 &a, const T2 &b,
const T3 &c, const T4 &d,
const T5 &e, const T6 &f,
const T7 &g)
{
CombineDomain<RT,T1,0>::combine(retval,a);
CombineDomain<RT,T2,S2>::combine(retval,b);
CombineDomain<RT,T3,S3>::combine(retval,c);
CombineDomain<RT,T4,S4>::combine(retval,d);
CombineDomain<RT,T5,S5>::combine(retval,e);
CombineDomain<RT,T6,S6>::combine(retval,f);
CombineDomain<RT,T7,S7>::combine(retval,g);
return retval;
}
template<class UT>
inline static SliceType_t combineSlice(const UT &u,
const T1 &a, const T2 &b,
const T3 &c, const T4 &d,
const T5 &e, const T6 &f,
const T7 &g)
{
SliceType_t retval = Pooma::NoInit();
return fillSlice(retval, u, a, b, c, d, e, f, g);
}
template<class RT, class UT>
inline static RT &fillSlice(RT &retval, const UT &u,
const T1 &a, const T2 &b,
const T3 &c, const T4 &d,
const T5 &e, const T6 &f,
const T7 &g)
{
enum { RDX =
DomainTraits<RT>::dimensions > DomainTraits<RT>::sliceDimensions };
CombineSliceDomain<RT,UT,T1,0,0,(DX1>0 && RDX)>::combine(retval,u,a);
CombineSliceDomain<RT,UT,T2,S2,DX1,(DX2>0 && RDX)>::combine(retval,u,b);
CombineSliceDomain<RT,UT,T3,S3,DX1+DX2,(DX3>0 && RDX)>::
combine(retval,u,c);
CombineSliceDomain<RT,UT,T4,S4,DX1+DX2+DX3,(DX4>0 && RDX)>::
combine(retval,u,d);
CombineSliceDomain<RT,UT,T5,S5,DX1+DX2+DX3+DX4,(DX5>0 && RDX)>::
combine(retval,u,e);
CombineSliceDomain<RT,UT,T6,S6,DX1+DX2+DX3+DX4+DX5,(DX6>0 && RDX)>::
combine(retval,u,f);
CombineSliceDomain<RT,UT,T7,S7,DX1+DX2+DX3+DX4+DX5+DX6,(DX7>0 && RDX)>::
combine(retval,u,g);
return retval;
}
};
/** @addtogroup NewDomain
* TemporaryNewDomain1 is a fix for a deficiency in NewDomain1, which
* synthesizes SliceType_t from a single parameter, which is incorrect. We
* need the array's domain type in order to get the right answer when the
* user specifies a single AllDomain<Dim>.
*/
template<class Domain, class Sub>
struct TemporaryNewDomain1
{
typedef typename NewDomain1<Sub>::SliceType_t SliceType_t;
static inline
SliceType_t combineSlice(const Domain &d, const Sub &s)
{
return NewDomain1<Sub>::combineSlice(d, s);
}
};
template<class Domain, int N>
struct TemporaryNewDomain1<Domain, AllDomain<N> >
{
typedef Domain SliceType_t;
static inline
const SliceType_t &combineSlice(const Domain &d, const AllDomain<N> &)
{
return d;
}
};
#endif // POOMA_DOMAIN_NEWDOMAIN_H
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: NewDomain.h,v $ $Author: richard $
// $Revision: 1.36 $ $Date: 2004/11/01 18:16:32 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "core/CompileConfig.h"
#if OUZEL_SUPPORTS_DIRECT3D11
#include "BufferResourceD3D11.h"
#include "RendererD3D11.h"
#include "core/Engine.h"
#include "utils/Log.h"
namespace ouzel
{
namespace graphics
{
BufferResourceD3D11::BufferResourceD3D11()
{
}
BufferResourceD3D11::~BufferResourceD3D11()
{
if (buffer)
{
buffer->Release();
}
}
bool BufferResourceD3D11::upload()
{
std::lock_guard<std::mutex> lock(uploadMutex);
if (dirty)
{
RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());
if (!data.empty())
{
if (!buffer || data.size() > bufferSize)
{
if (buffer) buffer->Release();
bufferSize = static_cast<UINT>(data.size());
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = bufferSize;
bufferDesc.Usage = dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_IMMUTABLE;
switch (usage)
{
case Buffer::Usage::INDEX:
bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
break;
case Buffer::Usage::VERTEX:
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
break;
default:
Log(Log::Level::ERR) << "Unsupported buffer type";
return false;
}
bufferDesc.CPUAccessFlags = dynamic ? D3D11_CPU_ACCESS_WRITE : 0;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA bufferResourceData;
bufferResourceData.pSysMem = data.data();
bufferResourceData.SysMemPitch = 0;
bufferResourceData.SysMemSlicePitch = 0;
HRESULT hr = rendererD3D11->getDevice()->CreateBuffer(&bufferDesc, &bufferResourceData, &buffer);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 buffer, error: " << hr;
return false;
}
}
else
{
D3D11_MAPPED_SUBRESOURCE mappedSubresource;
mappedSubresource.pData = nullptr;
mappedSubresource.RowPitch = 0;
mappedSubresource.DepthPitch = 0;
HRESULT hr = rendererD3D11->getContext()->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedSubresource);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to lock Direct3D 11 buffer, error: " << hr;
return false;
}
std::copy(data.begin(), data.end(), static_cast<uint8_t*>(mappedSubresource.pData));
rendererD3D11->getContext()->Unmap(buffer, 0);
}
}
dirty = 0;
}
return true;
}
} // namespace graphics
} // namespace ouzel
#endif
|
#include <list>
#include <unordered_map>
using namespace std;
class LRUCache{
public:
LRUCache(int capacity):capa(capacity) {
}
int get(int key) {
unordered_map<int, __Val>::iterator wh = cache.find(key);
if(wh != cache.end()){
lru.splice(lru.begin(), lru, wh->second);
return wh->second->second;
}
return -1;
}
void set(int key, int value) {
unordered_map<int, __Val>::iterator wh = cache.find(key);
if(wh != cache.end()){
wh->second->second = value;
lru.splice(lru.begin(), lru, wh->second);
}else{
lru.push_front(make_pair(key, value));
cache.insert(make_pair(key, lru.begin()));
while(cache.size() > capa){
cache.erase(lru.back().first);
lru.pop_back();
}
}
}
private:
list<pair<int, int> > lru; //key + value
typedef list<pair<int, int> >::iterator __Val;
unordered_map<int, __Val> cache;
int capa;
};
int main()
{
}
|
#include "AStar.h"
//当前游戏的状态 0表示路,1表示起点,2表示障碍,3表示终点
AStar::AStar(int **newmap,int x1,int y1,int x2,int y2) {
for (int i = 0; i < 28; i++) {
for (int j = 0; j < 38; j++) {
map[i][j] = newmap[i][j];
}
}
//for (int i = 0; i < 28; i++) {
// for (int j = 0; j < 38; j++) {
// log("%d",map[i][j]);
// }
//}
AStarNode *m_pNode = new AStarNode(x1, y1, x2, y2);
OpenList.push_back(m_pNode);
isEnd = false;
}
bool AStar::FindPath() {
AStarNode *current, *temp; int i = 0;
while (isEnd!=true&&!OpenList.empty())
{
//log("%d %d",i++,OpenList.size());
current = this->minNode();
OpenList.pop_front();
map[current->y][current->x] = 4;//访问过
//current->isVisit = true;
//ClosedList.push_back(current);
if (current->x > 0) {//左边
if (map[current->y][current->x - 1] ==0|| map[current->y][current->x - 1] == 3) {
temp = isContain(current->x - 1, current->y);
if (temp) {
if (current->g + 1 < temp->g) {
temp->g = current->g + 1; temp->f = temp->g + temp->h; temp->parent = current;
}
}
else
{
AStarNode *newNode = new AStarNode(current->x - 1, current->y, current->xend, current->yend, current);
if (newNode->h == 0)this->isEnd = true;
OpenList.push_back(newNode);
}
}
}
if (current->x < 37) {//右边
if (map[current->y][current->x + 1] == 0 || map[current->y][current->x + 1] == 3) {
temp = isContain(current->x + 1, current->y);
if (temp) {
if (current->g + 1 < temp->g) {
temp->g = current->g + 1; temp->f = temp->g + temp->h; temp->parent = current;
}
}
else
{
AStarNode *newNode = new AStarNode(current->x + 1, current->y, current->xend, current->yend, current);
if (newNode->h == 0)this->isEnd = true;
OpenList.push_back(newNode);
}
}
}
if (current->y < 27) {//上边
if (map[current->y+1][current->x] == 0 || map[current->y + 1][current->x] == 3) {
temp = isContain(current->x , current->y+1);
if (temp) {
if (current->g + 1 < temp->g) {
temp->g = current->g + 1; temp->f = temp->g + temp->h; temp->parent = current;
}
}
else
{
AStarNode *newNode = new AStarNode(current->x, current->y + 1, current->xend, current->yend, current);
if (newNode->h == 0)this->isEnd = true;
OpenList.push_back(newNode);
}
}
}
if (current->y > 0) {//下边
if (map[current->y - 1][current->x] == 0 || map[current->y - 1][current->x] == 3) {
temp = isContain(current->x, current->y - 1);
if (temp) {
if (current->g + 1 < temp->g) {
temp->g = current->g + 1; temp->f = temp->g + temp->h; temp->parent = current;
}
}
else
{
AStarNode *newNode = new AStarNode(current->x, current->y - 1, current->xend, current->yend, current);
if (newNode->h == 0)this->isEnd = true;
OpenList.push_back(newNode);
}
}
}
}
return true;
}
AStarNode* AStar::minNode() {
AStarNode *current = OpenList.front();
for (auto node:OpenList)
{
if (current->f > node->f) {
current = node;
}
}
return current;
}
AStarNode* AStar::isContain(int x, int y) {
for (auto node : OpenList) {
if (node->x == x && node->y == y) {
return node;
}
}
return NULL;
}
std::stack<Point*> AStar::getPath() {
if(!OpenList.empty()){
AStarNode *current = OpenList.back();
Point *newPoint;
while (current != NULL)
{
newPoint = new Point(current->x, current->y);
this->Path.push(newPoint);
current = current->parent;
}
return Path;
}
Director::getInstance()->replaceScene(MyResult::createScene());
}
AStar::~AStar()
{
for (auto node : OpenList) {
delete node;
}
while (!Path.empty())
{
Path.pop();
}
}
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word, sentence;
while (cin >> word)
sentence = sentence + word;
cout << sentence << endl;
return 0;
}
|
#include<iostream>
#include<climits>
#define ll long long int
using namespace std;
int main()
{
ll n;
cin>>n;
ll b[n];
ll max=0,n_max=0,min=LONG_MAX,n_min=0;
for(int i=0; i < n; i++)
{
cin>>b[i];
if(b[i]>max)
{
max = b[i];
n_max = 1;
}
else if(b[i]==max)
n_max++;
if(b[i]<min)
{
min = b[i];
n_min = 1;
}
else if(b[i]==min)
n_min++;
}
(max!=min)?(cout<<max-min<<"\t"<<n_min*n_max):(cout<<"0\t"<<n_max*(n_max -1)/2);
return 0;
}
|
/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013-2015, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* 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 Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#include <iostream>
#include <vector>
#include <algorithm> // std::generate
#include <ctime> // std::time
#include <cstdlib> // std::rand, std::srand
#include <cmath> // pow
#include "CmdLineParse.hpp"
#include "BufferSummary.hpp"
#include "NoiseSource.hpp"
#include "SpParamFile.hpp"
#include "Paragon.hpp"
#include "nupic/algorithms/SpatialPooler.hpp"
#include "nupic/algorithms/Cells4.hpp"
#include "nupic/os/Timer.hpp"
using namespace std;
using namespace nupic;
using nupic::algorithms::spatial_pooler::SpatialPooler;
using nupic::algorithms::Cells4::Cells4;
// function generator:
// Genreates about 200 ones in a 10k buffer returning random (binary) numbers from {0,1}
UInt RandState = 0;
int RandomNumber01 ()
{
int ret = rand();
if(ret < 85899346)
return (rand() & 1);
else
return(0);
}
int main(int argc, const char * argv[])
{
const UInt DIM = 2048; // number of columns in SP, TP
const UInt DIM_INPUT = 10000;
const UInt EPOCHS = pow(10, 4); // number of iterations (calls to SP/TP compute() )
const UInt RNGSEQUENCECOUNT = 100; //number of buffers in the rng sequence
UInt Epochs = EPOCHS;
UInt EpochsTwo = EPOCHS;
UInt RngSequenceCount = RNGSEQUENCECOUNT;
CmdLineParse *CmdLine = new CmdLineParse(argc, argv);
RandState = CmdLine->Vars("RngSeed");
srand(RandState);
if(CmdLine->Vars("Epochs"))
Epochs = CmdLine->Vars("Epochs");
if(CmdLine->Vars("RngSequenceCount"))
RngSequenceCount = CmdLine->Vars("RngSequenceCount");
vector<UInt> inputDim = {DIM_INPUT};
vector<UInt> colDim = {DIM};
// generate random input
vector<UInt> input(DIM_INPUT);
vector<UInt> outSP(DIM); // active array, output of SP/TP
Paragon Classifier(RngSequenceCount, DIM);
NoiseSource ns = NoiseSource(DIM_INPUT);
BufferSummary SpSummary = BufferSummary();
SpatialPoolerParams Params = SpatialPoolerParams(CmdLine->Names("SpParams"));
// Params.EchoParams();
SpatialPooler sp(
inputDim,
colDim,
Params.ParamUInt("potentialRadius"),
Params.ParamReal("potentialPct"),
Params.ParamBool("globalInhibition"),
Params.ParamReal("localAreaDensity"),
Params.ParamUInt("numActiveColumnsPerInhArea"),
Params.ParamUInt("stimulusThreshold"),
Params.ParamReal("synPermInactiveDec"),
Params.ParamReal("synPermActiveInc"),
Params.ParamReal("synPermConnected"),
Params.ParamReal("minPctOverlapDutyCycles"),
Params.ParamReal("minPctActiveDutyCycles"),
Params.ParamUInt("dutyCyclePeriod"),
Params.ParamReal("maxBoost"),
Params.ParamInt("seed"),
Params.ParamUInt("spVerbosity"),
Params.ParamBool("wrapAround"));
// Start a stopwatch timer
Timer stopwatch(true);
// ***** Run the learning sequence *****
for (UInt e = 0; e < Epochs; e++) {
if((e % RngSequenceCount) == 0)
srand(RandState);
generate(input.begin(), input.end(), RandomNumber01);
fill(outSP.begin(), outSP.end(), 0);
unsigned int *crap = outSP.data();
sp.compute(input.data(), true, outSP.data());
sp.stripUnlearnedColumns(outSP.data());
// Stroustrup says the .data() call makes a copy of the data, and that shouldn't be relied on
// after a non-constant call has been made on the class. (Section 20.3.7, p589)
if(CmdLine->Flags("--display_while_learning"))
if((e % (10*RngSequenceCount)) < RngSequenceCount)
{
cout << "----------------- ========= ------------------ Epoch " << e << endl;
// SP
SpSummary.SetupBuffer(outSP);
cout << "Pattern sequence number = " << (e%RngSequenceCount) << endl;
cout << "Non-zero elements of final SP output (location : length) " << endl;
while(SpSummary.PrepareNextRunMsg())
cout << SpSummary.Msg << endl;
}
}
// ***** separate the sequences *****
cout << endl;
cout << "======================..................=======================............" << endl;
cout << "======================..................=======================............" << endl;
cout << endl;
// ***** Initialize the classifier *****
srand(RandState);
for (UInt e = 0; e < RngSequenceCount; e++) {
generate(input.begin(), input.end(), RandomNumber01);
fill(outSP.begin(), outSP.end(), 0);
sp.compute(input.data(), false, outSP.data()); // no learning in sp
sp.stripUnlearnedColumns(outSP.data());
Classifier.PatternSet[e] = new SparsePlutoVector(outSP);
}
// ***** Run the classifier sequence *****
srand(RandState);
for (UInt e = 0; e < RngSequenceCount; e++) {
generate(input.begin(), input.end(), RandomNumber01);
ns.InsertNoise(input, CmdLine->Vars("NoiseLevel"));
//.............
#if 0
SpSummary.SetupBuffer(input);
cout << "Non-zero elements of input (location : length) " << endl;
while(SpSummary.PrepareNextRunMsg())
cout << SpSummary.Msg << endl;
#endif
//..............
fill(outSP.begin(), outSP.end(), 0);
sp.compute(input.data(), false, outSP.data()); // no learning in sp
sp.stripUnlearnedColumns(outSP.data());
// print classification result
if(CmdLine->Flags("--classify"))
{
//for(int i=0; i < Classifier.PatternSet[e]->Ndx.size(); i++)
// cout << i << " loc= " << Classifier.PatternSet[e]->Ndx[i] << endl;
Classifier.Classify(outSP);
cout << "Pattern sequence number = " << e << endl;
for(int i=0; i < Classifier.MatchProbability.size(); i++)
cout << i << ": " << Classifier.MatchProbability[i] << endl;
cout << "Match " << Classifier.MaxNdx << " with probability "
<< Classifier.MaxProbability << endl;
}
// print entire final arrays
if(CmdLine->Flags("--dump_final"))
{
cout << "Pattern sequence number = " << e << endl;
cout << "SP=" << outSP << endl;
}
// print a list of non-zero runs
if(CmdLine->Flags("--sp_summary"))
{
SpSummary.SetupBuffer(outSP);
cout << "Pattern sequence number = " << e << endl;
cout << "Non-zero elements of final SP output (location : length) " << endl;
while(SpSummary.PrepareNextRunMsg())
cout << SpSummary.Msg << endl;
}
}
stopwatch.stop();
cout << "Total elapsed time = " << stopwatch.getElapsed() << " seconds" << endl;
return 0;
}
|
#include <iostream>
using namespace std;
int main()
{
int a[3], b[3], s = 0, l = 0;
for (int i = 0; i < 3; i++) cin >> a[i];
for (int i = 0; i < 3; i++) cin >> b[i];
for (int i = 0; i < 3; i++)
if (a[i] == b[i])
s += 1;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (a[i] == b[j]) l += 1;
cout << s << "S" << l - s << "B";
}
|
#include<iostream>
using namespace std;
int dp[30001];
int missile[20];
int n;
int main()
{
for(int i=0;i<=30001;i++)
{
dp[i]=0;
}
n=0;
while(!cin.eof())
{
cin >>missile[n];
dp[missile[n++]]=1;
}
for(int i=0;i<20;i++)
{
for(int j=
{
}
}
}
|
//
// main.cpp
// BFBDetectGraph
//
// Created by Tidesun on 21/3/2019.
// Copyright © 2019 Oliver. All rights reserved.
//
#include <iostream>
#include <chrono>
#include <ctime>
#include "file_reader.hpp"
#include "bfb_calculator.hpp"
using namespace std;
int main(int argc, char *argv[]) {
double costThreshold = 0.0;
if (argc>1) {
costThreshold = atof(argv[1]);
}
FileReader fileReader = FileReader("../static/vcf.csv",FileReader::SVCN);
//FileReader fileReader = FileReader("../static/sim.lh",FileReader::GRAPH);
Graph g = Graph();
fileReader.readGraph(&g);
BFBCalculator cal = BFBCalculator(g,costThreshold,'+','r');
cal.setAlgorithm(BFBCalculator::foldbackAlgo);
cal.runAlgorithm();
// cal.setAlgorithm(BFBCalculator::traverseAlgo);
// cal.runAlgorithm();
return 0;
}
|
#include<iostream>
#include<cmath>
using namespace std;
int dfs(int n,char a,char b,char c)
{
if(n==1)
{
cout<<a<<"-->"<<c<<endl;
}
else
{
dfs(n-1,a,c,b);
cout<<a<<"-->"<<c<<endl;
dfs(n-1,b,a,c);
}
}
int main()
{
int n;
cin >>n;
dfs(n,'A','B','C');
return 0;
}
|
#include "CUFLU.h"
#ifdef __CUDACC__
#include "CUAPI.h"
#include "CUFLU_Shared_FluUtility.cu"
#endif
#if ( MODEL == HYDRO && defined SRHD )
/********************************************************
1. Approximately relativistic ideal gas EoS (Taub-Mathews EoS)
2. This file is shared by both CPU and GPU
GPU_EoS_TaubMathews.cu -> CPU_EoS_TaubMathews.cpp
3. Three steps are required to implement an EoS
I. Set an EoS auxiliary array
II. Implement EoS conversion functions
III. Set EoS initialization functions
********************************************************/
// =============================================
// I. Set an EoS auxiliary array
// =============================================
//-------------------------------------------------------------------------------------------------------
// Function : EoS_SetAuxArray_TaubMathews
// Description : Set the auxiliary array AuxArray[]
// Note : 1. Invoked by EoS_Init_TaubMathews()
// 2. AuxArray[] has the size of EOS_NAUX_MAX defined in Macro.h (default = 10)
// 3. Add "#ifndef __CUDACC__" since this routine is only useful on CPU
// 4. Do not change the order of AuxArray[]
// --> For example, the dual-energy routines assume AuxArray[0]=GAMMA
//
// Parameter : AuxArray : Array to be filled up
//
// Return : AuxArray[]
//-------------------------------------------------------------------------------------------------------
#ifndef __CUDACC__
void EoS_SetAuxArray_TaubMathews( double AuxArray_Flt[], int AuxArray_Int[] )
{
AuxArray_Flt[0] = ( OPT__UNIT ) ? MOLECULAR_WEIGHT * Const_amu / Const_kB * (UNIT_E/UNIT_M)
: MOLECULAR_WEIGHT;
AuxArray_Flt[1] = 1.0 / AuxArray_Flt[0];
} // FUNCTION : EoS_SetAuxArray_TaubMathews
#endif // #ifndef __CUDACC__
// =============================================
// II. Implement EoS conversion functions
// (1) EoS_HTilde2Temp_*
// (2) EoS_Temp2HTilde_*
// (3) EoS_Temper2CSqr_*
// =============================================
//-------------------------------------------------------------------------------------------------------
// Function : EoS_GuessHTilde_TaubMathews
// Description : Guess a reduced enthalpy for Newton-Raphson iteration
// Note :
// Parameter : Con : Conservative variables
// Constant : The constant on the left side of Eq. A3 in "Tseng et al. 2021, MNRAS, 504, 3298"
// AuxArray_* : Auxiliary arrays (see the Note above)
// Table : EoS tables
// Return : GuessHTilde : guessed reduced enthalpy
//-------------------------------------------------------------------------------------------------------
GPU_DEVICE_NOINLINE
static real EoS_GuessHTilde_TaubMathews( const real Con[], real* const Constant, const double AuxArray_Flt[],
const int AuxArray_Int[], const real *const Table[EOS_NTABLE_MAX] )
{
real GuessHTilde, Discrimination;
real Msqr = SQR(Con[1]) + SQR(Con[2]) + SQR(Con[3]);
real Dsqr = SQR(Con[0]);
real abc = (real)1.0 / Dsqr;
real E_D = Con[4] / Con[0];
real M_Dsqr = abc * Msqr;
real M_D = SQRT( M_Dsqr );
real X = SQRT( E_D*E_D + (real)2.0*E_D );
real Y = X + M_D;
real Z = X - M_D;
*Constant = Y * Z;
real A = (real)437.0 * M_Dsqr + (real)117.0;
real B = (real)1.0 + M_Dsqr;
real C = (real)43.0*M_Dsqr + (real)63.0;
// Eq. A7 in "Tseng et al. 2021, MNRAS, 504, 3298"
Discrimination = (real)3240000.0 * SQR( B );
Discrimination /= SQR( A );
if ( *Constant >= Discrimination )
{
// Eq. A6 in "Tseng et al. 2021, MNRAS, 504, 3298"
GuessHTilde = (real)1.3333333 * SQRT( *Constant );
}
else
{
// Eq. A4 in "Tseng et al. 2021, MNRAS, 504, 3298"
GuessHTilde = (real)11.18 * SQRT( B*C* (*Constant) + (real)45.0*B*B );
GuessHTilde -= (real)75.0 * B;
GuessHTilde /= C;
}
return GuessHTilde;
}
//-------------------------------------------------------------------------------------------------------
// Function : EoS_HTilde2Temp_TaubMathews
// Description : Convert reduced enthalpy to temperature
//
// Note : Eq. 16 in "Tseng et al. 2021, MNRAS, 504, 3298"
//
// Parameter : HTilde : Reduced enthalpy
// Temp : Temperature (kT/mc**)
// DiffTemp : The derivitive of a reduced enthalpy with respect to temperature
// Passive : Passive scalars (must not used here)
// AuxArray_* : Auxiliary arrays (see the Note above)
// Table : EoS tables
//
// Return : Temp, DiffTemp
//-------------------------------------------------------------------------------------------------------
GPU_DEVICE_NOINLINE
static void EoS_HTilde2Temp_TaubMathews( const real HTilde, real* const Temp, real* const DiffTemp,
const real Passive[], const double AuxArray_Flt[],
const int AuxArray_Int[], const real *const Table[EOS_NTABLE_MAX] )
{
real HTildeSqr = SQR(HTilde);
real Factor0 = (real)2.0*HTildeSqr + (real)4.0*HTilde;
real Factor1 = SQRT( (real)9.0*HTildeSqr + (real)18.0*HTilde + (real)25.0 );
real Factor2 = (real)5.0*HTilde + (real)5.0 + Factor1;
if ( Temp != NULL )
*Temp = Factor0 / Factor2;
if ( DiffTemp != NULL )
*DiffTemp = ( (real)4.0*HTilde + (real)4.0 ) / Factor2
- Factor0 * ( ( (real)9.0*HTilde + (real)9.0 ) / Factor1 + (real)5.0 ) / SQR(Factor2);
} // FUNCTION : EoS_HTilde2Temp_TaubMathews
//-------------------------------------------------------------------------------------------------------
// Function : EoS_Temp2HTilde_TaubMathews
// Description :
// Note : Eq. 10 in "Tseng et al. 2021, MNRAS, 504, 3298"
// Parameter : Temp : Dimensionless temperature (kT/mc**2)
// Passive : Passive scalars (must not used here)
// AuxArray_* : Auxiliary arrays (see the Note above)
// Table : EoS tables
//
// Return : Reduced energy density
//-------------------------------------------------------------------------------------------------------
GPU_DEVICE_NOINLINE
static real EoS_Temp2HTilde_TaubMathews( const real Temp, const real Passive[], const double AuxArray_Flt[],
const int AuxArray_Int[], const real *const Table[EOS_NTABLE_MAX] )
{
real HTilde; // Reduced enthalpy
real TempSqr = Temp*Temp;
real Factor = (real)2.25*TempSqr;
HTilde = Factor;
HTilde /= (real)1.0 + SQRT( Factor + (real)1.0 );
HTilde += (real)2.5*Temp;
return HTilde;
} // FUNCTION : EoS_Temp2HTilde_TaubMathews
//-------------------------------------------------------------------------------------------------------
// Function : EoS_Temper2CSqr_TaubMathews
// Description : Convert gas temperature to sound speed squared
//
// Note : Eq. 14 in "Tseng et al. 2021, MNRAS, 504, 3298"
//
// Parameter : Rho : Gas proper mass density
// Pres : Gas pressure
// Passive : Passive scalars (must not used here)
// AuxArray_* : Auxiliary arrays (see the Note above)
// Table : EoS tables
//
// Return : Sound speed square
//-------------------------------------------------------------------------------------------------------
GPU_DEVICE_NOINLINE
static real EoS_Temper2CSqr_TaubMathews( const real Rho, const real Pres, const real Passive[], const double AuxArray_Flt[],
const int AuxArray_Int[], const real *const Table[EOS_NTABLE_MAX] )
{
real Cs2, Temp;
Temp = Pres/Rho;
real factor = SQRT( (real)2.25*Temp*Temp + (real)1.0 );
Cs2 = (real) 4.5*SQR(Temp) + (real) 5.0 * Temp * factor;
Cs2 /= (real)18.0*SQR(Temp) + (real)12.0 * Temp * factor + (real)3.0;
return Cs2;
} // FUNCTION : EoS_Temper2CSqr_TaubMathews
// =============================================
// III. Set EoS initialization functions
// =============================================
#ifdef __CUDACC__
# define FUNC_SPACE __device__ static
#else
# define FUNC_SPACE static
#endif
FUNC_SPACE EoS_GUESS_t EoS_GuessHTilde_Ptr = EoS_GuessHTilde_TaubMathews;
FUNC_SPACE EoS_H2TEM_t EoS_HTilde2Temp_Ptr = EoS_HTilde2Temp_TaubMathews;
FUNC_SPACE EoS_TEM2H_t EoS_Temp2HTilde_Ptr = EoS_Temp2HTilde_TaubMathews;
FUNC_SPACE EoS_TEM2C_t EoS_Temper2CSqr_Ptr = EoS_Temper2CSqr_TaubMathews;
//-----------------------------------------------------------------------------------------
// Function : EoS_InitCPU/GPUFunc_TaubMathews
// Description : Return the function pointers of the CPU/GPU EoS routines
//
// Note : 1. Invoked by EoS_Init_TaubMathews()
// 2. Must obtain the CPU and GPU function pointers by **separate** routines
// since CPU and GPU functions are compiled completely separately in GAMER
// --> In other words, a unified routine like the following won't work
//
// EoS_InitFunc_TaubMathews( CPU_FuncPtr, GPU_FuncPtr );
//
// 3. Call-by-reference
//
// Parameter : EoS_HTilde2Temp_CPU/GPUPtr : CPU/GPU function pointers to be set
// EoS_Temp2HTilde_CPU/GPUPtr : ...
// EoS_Temper2CSqr_CPU/GPUPtr : ...
//
// Return : EoS_HTilde2Temp_CPU, EoS_Temp2HTilde_CPU/GPUPtr, EoS_Temper2CSqr_CPU/GPUPtr
//-----------------------------------------------------------------------------------------
#ifdef __CUDACC__
__host__
void EoS_SetGPUFunc_TaubMathews( EoS_GUESS_t &EoS_GuessHTilde_GPUPtr,
EoS_H2TEM_t &EoS_HTilde2Temp_GPUPtr,
EoS_TEM2H_t &EoS_Temp2HTilde_GPUPtr,
EoS_TEM2C_t &EoS_Temper2CSqr_GPUPtr )
{
CUDA_CHECK_ERROR( cudaMemcpyFromSymbol( &EoS_GuessHTilde_GPUPtr, EoS_GuessHTilde_Ptr, sizeof(EoS_GUESS_t) ) );
CUDA_CHECK_ERROR( cudaMemcpyFromSymbol( &EoS_HTilde2Temp_GPUPtr, EoS_HTilde2Temp_Ptr, sizeof(EoS_H2TEM_t) ) );
CUDA_CHECK_ERROR( cudaMemcpyFromSymbol( &EoS_Temp2HTilde_GPUPtr, EoS_Temp2HTilde_Ptr, sizeof(EoS_TEM2H_t) ) );
CUDA_CHECK_ERROR( cudaMemcpyFromSymbol( &EoS_Temper2CSqr_GPUPtr, EoS_Temper2CSqr_Ptr, sizeof(EoS_TEM2C_t) ) );
}
#else // #ifdef __CUDACC__
void EoS_SetCPUFunc_TaubMathews( EoS_GUESS_t &EoS_GuessHTilde_CPUPtr,
EoS_H2TEM_t &EoS_HTilde2Temp_CPUPtr,
EoS_TEM2H_t &EoS_Temp2HTilde_CPUPtr,
EoS_TEM2C_t &EoS_Temper2CSqr_CPUPtr )
{
EoS_GuessHTilde_CPUPtr = EoS_GuessHTilde_Ptr;
EoS_HTilde2Temp_CPUPtr = EoS_HTilde2Temp_Ptr;
EoS_Temp2HTilde_CPUPtr = EoS_Temp2HTilde_Ptr;
EoS_Temper2CSqr_CPUPtr = EoS_Temper2CSqr_Ptr;
}
#endif // #ifdef __CUDACC__ ... else ...
#ifndef __CUDACC__
// local function prototypes
void EoS_SetAuxArray_TaubMathews( double [] );
void EoS_SetCPUFunc_TaubMathews(EoS_GUESS_t &, EoS_H2TEM_t &, EoS_TEM2H_t &, EoS_TEM2C_t & );
#ifdef GPU
void EoS_SetGPUFunc_TaubMathews(EoS_GUESS_t &, EoS_H2TEM_t &, EoS_TEM2H_t &, EoS_TEM2C_t & );
#endif
//-----------------------------------------------------------------------------------------
// Function : EoS_Init_TaubMathews
// Description : Initialize EoS
//
// Note : 1. Set an auxiliary array by invoking EoS_SetAuxArray_*()
// --> It will be copied to GPU automatically in CUAPI_SetConstMemory()
// 2. Set the CPU/GPU EoS routines by invoking EoS_SetCPU/GPUFunc_*()
// 3. Invoked by EoS_Init()
// --> Enable it by linking to the function pointer "EoS_Init_Ptr"
// 4. Add "#ifndef __CUDACC__" since this routine is only useful on CPU
//
// Parameter : None
//
// Return : None
//-----------------------------------------------------------------------------------------
void EoS_Init_TaubMathews()
{
EoS_SetAuxArray_TaubMathews( EoS_AuxArray_Flt, EoS_AuxArray_Int );
EoS_SetCPUFunc_TaubMathews( EoS_GuessHTilde_CPUPtr, EoS_HTilde2Temp_CPUPtr, EoS_Temp2HTilde_CPUPtr, EoS_Temper2CSqr_CPUPtr );
# ifdef GPU
EoS_SetGPUFunc_TaubMathews( EoS_GuessHTilde_GPUPtr, EoS_HTilde2Temp_GPUPtr, EoS_Temp2HTilde_GPUPtr, EoS_Temper2CSqr_GPUPtr );
# endif
} // FUNCTION : EoS_Init_TaubMathews
#endif // #ifndef __CUDACC__
#endif // #if ( MODEL == HYDRO && defined SRHD )
|
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void calc_Histo(const Mat& image, Mat& hist, Vec3i bins, Vec3f range_max, int _dims);
vector<Mat> load_histo(Vec3i bins, Vec3f ranges, int nImages);
Mat draw_histo(Mat hist);
Mat query_img();
Mat make_img(Mat img1, Mat img2);
Mat calc_similarity(Mat query_hist, vector<Mat>& DB_hists);
void select_view(double sinc, Mat DB_similaritys);
int main() {
Vec3i bins(30, 42, 0); // 계급 개수 : 색상(30개), 채도(42개)
Vec3f ranges(180, 256, 0); // 범위 : 색상(0~179), 채도(0~255)
Mat hsv, query_hist;
vector<Mat> DB_hists = load_histo(bins, ranges, 100);
Mat query = query_img(); // 입력영상 읽기
cvtColor(query, hsv, COLOR_BGR2HSV); // HSV 컬러 변환
// 2차원 히스토그램 계산
calc_Histo(hsv, query_hist, bins, ranges, 2);
// 출력용 히스토그램 영상
Mat hist_img = draw_histo(query_hist);
// 컬러 히스토그램을 이용한 유사도 계산
Mat DB_similaritys = calc_similarity(query_hist, DB_hists);
double sinc;
cout << "기준 유사도 입력 : ";
cin >> sinc;
// 유사도 기준 이상 영상 출력
select_view(sinc, DB_similaritys);
imshow("image", query);
imshow("hist_img", hist_img);
char c;
cin >> c;
}
// 계급수, 화소값 범위, 입력 이미지 개수 입력
vector<Mat> load_histo(Vec3i bins, Vec3f ranges, int nImages) {
vector<Mat> DB_hists;
for (int i = 0; i < nImages; i++) {
String fname = format("DB/img_%02d.jpg", i);
Mat hsv, hist, img = imread(fname, IMREAD_COLOR);
if (img.empty()) continue;
cvtColor(img, hsv, COLOR_BGR2HSV);
calc_Histo(hsv, hist, bins, ranges, 2);
DB_hists.push_back(hist);
}
cout << format("%d개 파일 로드 및 히스토그램 계산 완료\n\n", DB_hists.size());
return DB_hists; // 3차원 영상
}
Mat draw_histo(Mat hist) {
if (hist.dims != 2) {
cout << "히스토그램이 2차원 데이터가 아닙니다." << endl;
exit(1);
}
float ratio_value = 512.f;
float ratio_hue = 180.f / hist.rows;
float ratio_sat = 256.f / hist.cols;
Mat graph(hist.size(), CV_32FC3);
for (int i = 0; i < hist.rows; i++) {
for (int j = 0; j < hist.cols; j++) {
float vlaue = hist.at<float>(i, j) * ratio_value; // 빈도값
float hue = i * ratio_hue; // 색상값
float sat = j * ratio_sat; // 채도값
// 3채널의 한 값 저장
graph.at<Vec3f>(i, j) = Vec3f(hue, sat, vlaue);
}
}
graph.convertTo(graph, CV_8U);
cvtColor(graph, graph, COLOR_BGR2HSV);
resize(graph, graph, Size(0,0), 10, 10, INTER_NEAREST);
return graph;
}
// 매개변수 : 계산할 영상, 빈도수를 담을 영상, 구간수, 값의 최대 허용값
void calc_Histo(const Mat& image, Mat& hist, Vec3i bins, Vec3f range_max, int _dims) {
// 구간값 저장
int histSize[] = { bins[0], bins[1], bins[2] };
// 값의 범위 저장
float range1[] = { 0, (float)range_max[0] };
float range2[] = { 0, (float)range_max[1] };
float range3[] = { 0, (float)range_max[2] };
// 채널 수 만큼 저장
int channels[] = { 0, 1, 2 };
// 영상의 차원 수 저장
int dims = (_dims <= 0) ? image.channels() : _dims;
// 구간값들을 모아 2차원 배열로 변환
const float* ranges[] = { range1, range2, range3 };
/*
&image : 계산할 영상
1 : 영상의 수
channels : 채널의 수
Mat() : 마스크(Mat()이므로 전체 영상지정 효과x)
hist : 결과를 저장할 영상
dims : 결과 영상의 차원수
histSize : 구간수
ranges : 값의 범위값
=> image의 화소값 빈도수를 계산하여 hist에 담아준다.
*/
calcHist(&image, 1, channels, Mat(), hist, dims, histSize, ranges);
normalize(hist, hist, 0, 1, NORM_MINMAX);
}
Mat query_img() {
do {
int q_no = 74;
cout << "질의영상 번호를 입력하세요 : ";
cin >> q_no; // 콘솔창 통한 입력
String fname = format("DB/img_%02d.jpg", q_no);
// 질의영상 읽기
Mat query = imread(fname, IMREAD_COLOR);
if (query.empty()) cout << "질의영상 번호가 잘못되었습니다." << endl;
else return query; // 질의영상 반환
} while (1); // 질의영상 없으면 계속반복
}
Mat calc_similarity(Mat query_hist, vector<Mat>& DB_hists) {
Mat DB_similaritys;
for (int i = 0; i < (int)DB_hists.size(); i++) {
double compare = compareHist(query_hist, DB_hists[i], HISTCMP_CORREL);
DB_similaritys.push_back(compare);
}
return DB_similaritys;
}
void select_view(double sinc, Mat DB_similaritys) {
Mat m_idx, sorted_sim;
// 행단위 + 내림차순
int flag = SORT_EVERY_COLUMN + SORT_DESCENDING;
cv::sort(DB_similaritys, sorted_sim, flag);
sortIdx(DB_similaritys, m_idx, flag);
for (int i = 0; i < sorted_sim.total(); i++) {
double sim = sorted_sim.at<double>(i);
if (sim > sinc) {
int idx = m_idx.at<int>(i);
String fname = format("DB/img_%02d.jpg", idx);
Mat img = imread(fname, IMREAD_COLOR);
String title = format("img_%03d - %5.2f", idx, sim);
cout << title << endl;
//imshow(title, img);
}
}
}
|
#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
bool compare(pair<int,int> &a,pair<int,int> &b){
return a.second>b.second;
}
int main(){
int n;
while(scanf("%d",&n)){
vector< pair<int,int> > buffer,result;
pair<int,int> temp;
for(int i=0;i<n;i++){
scanf("%d %d",&temp.first,&temp.second);
buffer.push_back(temp);
}
sort(&buffer[0],&buffer[buffer.size()],compare);
int max_x=-1;
for(int i=0;i<buffer.size();i++)
if(max_x<buffer[i].first){
max_x = buffer[i].first;
printf("%d %d\n",buffer[i].first,buffer[i].second);
}
}
return 0;
}
|
#include <vector>
#include <string>
class Deck {
vector<Card*> base;
public:
// shuffle deck, randomize order of cards
vector<Card*> shuffle(vector<Card*> cards);
// drawCard from deck, return pointer to card drawn
Card* drawCard();
// whether deck contains any cards or not
bool isEmpty();
Deck();
~Deck();
};
std::ostream &operator<<(std::ostream &out, const Deck &d);
|
#include <opencv2/opencv.hpp>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include<math.h>
#define PI 3.1415926535
#define E 2.718281828
using namespace cv;
using namespace std;
struct feature
{
int sigma;
int x;
int y;
int octave;
double m;
double ori;
double theta;
double desc[4][4][8];
};
feature feat[10000];
void Dog(Mat &srcImage, Mat dog[3][5]);
void getmax_min(Mat dog[3][5], Mat dstmat[3][3]);
void downsize(Mat &srcImage, Mat &dstImage);
int compare_ptr(uchar *ptr1, uchar *ptr2, uchar *ptr3, uchar *ptr4, uchar *ptr5, uchar *ptr6, uchar *ptr7, uchar *ptr8, uchar *ptr9, int n);
void init_feat(feature a[10000])
{
for (int i = 0; i < 10000; i++)
{
a[i].m = 0;
a[i].x = 0;
a[i].y = 0;
a[i].ori = 0;
a[i].sigma = 0;
a[i].octave = 0;
}
}
void downsize(Mat &srcImage, Mat &dstImage)
{
int i, j;
uchar *ptr1, *ptr2;
int col, row;
col = srcImage.cols;
row = srcImage.rows;
if (row % 2 != 0) row--;
if (col % 2 != 0) col--;
for (i = 0; i < row; i+=2)
{
ptr1 = srcImage.ptr(i);
ptr2 = dstImage.ptr(i / 2);
for (j = 0; j < col; j+=2)
{
ptr2[j / 2] = ptr1[j];
}
}
}
void Dog(Mat &srcImage, Mat dog[3][5],Mat Gaussian[3][6])
{
int i, j,col,row;
uchar *ptr1, *ptr2,*ptr3,*ptr4;
double sigma = 1.6;
double k = pow(2.0, 1.0 / 3);
// double k = 1.259921;
//构建第0组第0层
col = srcImage.cols;
row = srcImage.rows;
for (i = 0; i < 6; i++) Gaussian[0][i].create(Size(2 * col, 2 * row), CV_8UC1);
for (i = 0; i < 6; i++) Gaussian[1][i].create(Size(col,row), CV_8UC1);
for (i = 0; i < 6; i++) Gaussian[2][i].create(Size(col/2,row/2), CV_8UC1);
for (i = 0; i < row-1; i++)
{
ptr1 = srcImage.ptr(i);
ptr4 = srcImage.ptr(i+1);
ptr2 = Gaussian[0][0].ptr(i * 2);
ptr3 = Gaussian[0][0].ptr(i * 2 + 1);
for (j = 0; j < col-1; j++)
{
ptr2[j * 2] = ptr1[j];
ptr2[j * 2 + 1] = (ptr1[j] + ptr1[j + 1])/2;
ptr3[j * 2] = (ptr1[j]+ptr4[j])/2;
ptr3[j * 2 + 1] = (ptr1[j] + ptr4[j] + ptr1[j+1] + ptr4[j+1]) / 4;
}
}
//高斯滤波构建DOG部分
for (i = 0; i < 3; i++)
{
if (i) downsize(Gaussian[i - 1][2], Gaussian[i][0]);
for (j = 1; j < 6; j++) GaussianBlur(Gaussian[i][0], Gaussian[i][j], Size(0, 0), pow(k, j)*sigma, pow(k, j)*sigma);
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 5; j++) dog[i][j] = Gaussian[i][j+1] - Gaussian[i][j];
}
// cout << dog[0][1] << endl;
}
/*
int compare_ptr(uchar *ptr1, uchar *ptr2, uchar *ptr3, uchar *ptr4, uchar *ptr5, uchar *ptr6, uchar *ptr7, uchar *ptr8, uchar *ptr9,int n)
{
int i,j,a,b,c;
uchar *ptr[9] = { ptr1, ptr2, ptr3, ptr4, ptr5, ptr6, ptr7, ptr8, ptr9 };
a = ptr5[n];
b = ptr1[n];
c = ptr1[n];
for (i = 0; i < 9; i++)
for (j = -1; j < 2; j++)
{
if (ptr[i][n + j] > b) b = ptr[i][n + j];
if (ptr[i][n + j] < c) c = ptr[i][n + j];
}
if ((a == b)) return 1;
else if ((a == c)) return 2; //这里可能要改
else return 0;
}
*/
int compare_ptr(uchar *ptr1, uchar *ptr2, uchar *ptr3, uchar *ptr4, uchar *ptr5, uchar *ptr6, uchar *ptr7, uchar *ptr8, uchar *ptr9, int n)
{
int i, j, a, b1, c1, b2, c2;
uchar *ptr[9] = { ptr1, ptr2, ptr3, ptr4, ptr5, ptr6, ptr7, ptr8, ptr9 };
a = ptr5[n];
b1 = ptr1[n];
c1 = ptr1[n];
b2 = 0;
c2 = 255;
int tempi1, tempj1, tempi2, tempj2;
for (i = 0; i < 9; i++)
for (j = -1; j < 2; j++)
{
if (ptr[i][n + j] > b1)
{
b1 = ptr[i][n + j];
tempi1 = i;
tempj1 = j;
}
if (ptr[i][n + j] < c1)
{
c1 = ptr[i][n + j];
tempi2 = i;
tempj2 = j;
}
}
for (i = 0; i < 9; i++)
for (j = -1; j < 2; j++)
{
if (((i != tempi1) || (j != tempj1)) && (ptr[i][n + j] > b2)) b2 = ptr[i][n + j];
if (((i != tempi2) || (j != tempj2)) && (ptr[i][n + j] < c2)) c2 = ptr[i][n + j];
}
if ((a == b1) && (b1>b2)) return 1;
if ((a == c1) && (c1<c2)) return 2; //这里可能要改
else return 0;
}
void drawcircle(Mat &srcImage, Mat &dstImage)
{
int col, row, i, j;
col = srcImage.cols;
row = srcImage.rows;
for (i = 1; i < row - 1; i++)
{
uchar *ptr1 = srcImage.ptr(i);
uchar *ptr2 = dstImage.ptr(i);
uchar *ptr3 = dstImage.ptr(i - 1);
uchar *ptr4 = dstImage.ptr(i + 1);
for (j = 5; j < col - 5; j++)
{
if (ptr2[j]>250) circle(srcImage, Point(j, i), 3, Scalar(0), 2, 8);
}
}
}
void getmax_min(Mat dog[3][5],Mat dstmat[3][3])
{
int i, j,m=0,n=0;
uchar *ptr1, *ptr2, *ptr3, *ptr4, *ptr5, *ptr6, *ptr7, *ptr8, *ptr9,*ptr_src;
int row, col;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++) dstmat[i][j].create(Size(dog[i][0].cols, dog[i][0].rows), CV_8UC1);
//给dstmat刷100
for (i = 0; i < 3; i++)
{
row = dstmat[i][0].rows;
col = dstmat[i][0].cols;
for (j = 0; j < 3; j++)
{
for (m = 0; m < row; m++)
{
ptr1 = dstmat[i][j].ptr(m);
for (n = 0; n < col; n++)
{
ptr1[n] = 100;
}
}
}
}
//给特征点刷255和0
for (i = 0; i < 3; i++)
{
row = dstmat[i][0].rows;
col = dstmat[i][0].cols;
for (j = 1; j < 4; j++)
{
for (m = 1; m < row - 1; m++)
{
ptr1 = dog[i][j - 1].ptr(m - 1);
ptr2 = dog[i][j - 1].ptr(m);
ptr3 = dog[i][j - 1].ptr(m + 1);
ptr4 = dog[i][j].ptr(m - 1);
ptr5 = dog[i][j].ptr(m);
ptr6 = dog[i][j].ptr(m + 1);
ptr7 = dog[i][j + 1].ptr(m - 1);
ptr8 = dog[i][j + 1].ptr(m);
ptr9 = dog[i][j + 1].ptr(m + 1);
ptr_src = dstmat[i][j-1].ptr(m);
for (n = 1; n < col - 1; n++)
{
if (compare_ptr(ptr1, ptr2, ptr3, ptr4, ptr5, ptr6, ptr7, ptr8, ptr9, n)==1) ptr_src[n]=255;
if (compare_ptr(ptr1, ptr2, ptr3, ptr4, ptr5, ptr6, ptr7, ptr8, ptr9, n) == 2) ptr_src[n] = 0;
}
}
}
}
}
void mat_to_array(Mat srcImageROI, double dstarray[3][3]) //把图像转化为数组
{
int i, j;
for (i = 0; i < 3; i++)
{
uchar *ptr = srcImageROI.ptr(i);
for (j = 0; j < 3; j++)
{
dstarray[i][j] = ptr[j];
}
}
}
int mat_invert(double srcarray[3][3], double dstarray[3][3]) //行列式为0返回0
{
double det;
double *ptr0, *ptr1, *ptr2;
ptr0 = srcarray[0];
ptr1 = srcarray[1];
ptr2 = srcarray[2];
det = ptr0[0] * ptr1[1] * ptr2[2]
+ ptr0[1] * ptr1[2] * ptr2[0]
+ ptr0[2] * ptr1[0] * ptr2[1]
- ptr0[0] * ptr1[2] * ptr2[1]
- ptr0[1] * ptr1[0] * ptr2[2]
- ptr0[2] * ptr1[1] * ptr2[0];
if (abs(det) < 1e-6)
{
return 0;
}
dstarray[0][0] = (ptr1[1] * ptr2[2] - ptr2[1] * ptr1[2]) / det;
dstarray[0][1] = (ptr2[1] * ptr0[2] - ptr0[1] * ptr2[2]) / det;
dstarray[0][2] = (ptr0[1] * ptr1[2] - ptr0[2] * ptr1[1]) / det;
dstarray[1][0] = (ptr1[2] * ptr2[0] - ptr2[2] * ptr1[0]) / det;
dstarray[1][1] = (ptr2[2] * ptr0[0] - ptr0[2] * ptr2[0]) / det;
dstarray[1][2] = (ptr0[2] * ptr1[0] - ptr0[0] * ptr1[2]) / det;
dstarray[2][0] = (ptr1[0] * ptr2[1] - ptr2[0] * ptr1[1]) / det;
dstarray[2][1] = (ptr2[0] * ptr0[1] - ptr0[0] * ptr2[1]) / det;
dstarray[2][2] = (ptr0[0] * ptr1[1] - ptr0[1] * ptr1[0]) / det;
return 1;
}
void mat_mul(double src1[3],double src2[3][3],double dst[3])
{
dst[0] = src2[0][0] * src1[0] + src2[0][1] * src1[1] + src2[0][2] * src1[2];
dst[1] = src2[1][0] * src1[0] + src2[1][1] * src1[1] + src2[1][2] * src1[2];
dst[2] = src2[2][0] * src1[0] + src2[2][1] * src1[1] + src2[2][2] * src1[2];
}
double **fir_der(Mat srcImage,Mat srcImageup,Mat srcImagedown) //一阶微分
{
int col, row, i, j,k;
uchar *ptr1,*ptr2,*ptr3;
double **res,*ptr;
col = srcImage.cols;
row = srcImage.rows;
res = (double**)malloc(sizeof(double *) * 3);
for (i = 0; i < 3; i++)
{
res[i] = (double*)malloc(sizeof(double)*row*col);
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < row*col; j++) res[i][j] = 0;
}
//求x方向的导数
for (i = 0; i < row; i++)
{
ptr1 = srcImage.ptr(i);
ptr = res[0]+i*col;
for (j = 1; j < col - 1; j++)
{
*(ptr+j) = ((double)ptr1[j + 1] - (double)ptr1[j - 1])/2.0;
}
}
//求y方向的导数
for (i = 1; i < row-1; i++)
{
ptr2 = srcImage.ptr(i - 1);
ptr3 = srcImage.ptr(i + 1);
ptr = res[1] + i*col;
for (j = 0; j < col; j++)
{
*(ptr + j) = ((double)ptr3[j] - (double)ptr2[j]) / 2.0;
}
}
//求sigma方向的导数
for (i = 0; i < row; i++)
{
ptr2 = srcImageup.ptr(i);
ptr3 = srcImagedown.ptr(i);
ptr = res[2] + i*col;
for (j = 0; j < col; j++)
{
*(ptr + j) = ((double)ptr2[j] - (double)ptr3[j]) / 2.0;
}
}
return res;
}
int get_int(double a)
{
int b=a;
if ((a-b)>0.5) return b+1;
else return b;
}
double **sec_der(Mat srcImage,Mat srcImageup,Mat srcImagedown) //二阶微分
{
int col, row, i, j, k;
uchar *ptr1, *ptr2, *ptr3,*ptr4;
double **res, *ptr;
col = srcImage.cols;
row = srcImage.rows;
res = (double**)malloc(sizeof(double *) * 6);
for (i = 0; i < 6; i++)
{
res[i] = (double*)malloc(sizeof(double)*row*col);
}
for (i = 0; i < 6; i++)
{
for (j = 0; j < row*col; j++) res[i][j] = 0;
}
//求x方向的二阶导数
for (i = 0; i < row; i++)
{
ptr1 = srcImage.ptr(i);
ptr = res[0] + i*col;
for (j = 1; j < col - 1; j++)
{
*(ptr + j) = (double)ptr1[j + 1] + (double)ptr1[j - 1]-2.0*(double)ptr1[j];
}
}
//求y方向的二阶导数
for (i = 1; i < row - 1; i++)
{
ptr1 = srcImage.ptr(i);
ptr2 = srcImage.ptr(i - 1);
ptr3 = srcImage.ptr(i + 1);
ptr = res[1] + i*col;
for (j = 0; j < col; j++)
{
*(ptr + j) = (double)ptr3[j] + (double)ptr2[j]-2.0*(double)ptr1[j];
}
}
//求sigma方向的二阶导数
for (i = 0; i < row; i++)
{
ptr1 = srcImage.ptr(i);
ptr2 = srcImageup.ptr(i);
ptr3 = srcImagedown.ptr(i);
ptr = res[2] + i*col;
for (j = 0; j < col; j++)
{
*(ptr + j) = (double)ptr3[j] + (double)ptr2[j] - 2.0*(double)ptr1[j];
}
}
//求xy方向的二阶导数
for (i = 1; i < row - 1; i++)
{
ptr1 = srcImage.ptr(i);
ptr2 = srcImage.ptr(i - 1);
ptr3 = srcImage.ptr(i + 1);
ptr = res[1] + i*col;
for (j = 1; j < col-1; j++)
{
*(ptr + j) = ((double)ptr3[j + 1] + (double)ptr2[j - 1] - ((double)ptr3[j - 1] + (double)ptr2[j + 1]))/4;
}
}
//求y,sigma方向的二阶导数
for (i = 1; i < row - 1; i++)
{
ptr1 = srcImageup.ptr(i + 1);
ptr2 = srcImageup.ptr(i - 1);
ptr3 = srcImagedown.ptr(i + 1);
ptr4 = srcImagedown.ptr(i - 1);
ptr = res[1] + i*col;
for (j = 0; j < col; j++)
{
*(ptr + j) = ((double)ptr4[j] + (double)ptr1[j] - ((double)ptr3[j] + (double)ptr2[j])) / 4;
}
}
//求x,sigma方向的二阶导数
for (i = 0; i < row; i++)
{
ptr2 = srcImageup.ptr(i);
ptr3 = srcImagedown.ptr(i);
ptr = res[1] + i*col;
for (j = 1; j < col - 1; j++)
{
*(ptr + j) = ((double)ptr2[j-1] + (double)ptr3[j+1] - ((double)ptr3[j-1] + (double)ptr2[j+1])) / 4;
}
}
return res;
}
void eliminate_point(Mat dog[3][5],Mat dstmat[3][3]) //这一部分先不要添加到main()里面。没有关键性影响。
{
double Hessian[3][3];
double Hessian_inv[3][3];
double Dx[3];
double dev_x[3];
double **fir, **sec;
double det, trace;
int col, row, i, j, k, m,n;
int x, y, sigma;
uchar *ptr1,*ptr2,*ptr3,*ptr4,*ptr5,*ptr6,*ptr7,*ptr8,*ptr9,*ptr10,*temp;
for (k = 0; k < 6; k++)
{
for (m = 0; m < 3; m++)
{
col = dog[m][0].cols;
row = dog[m][0].rows;
for (n = 1; n < 4; n++)
{
fir = fir_der(dog[m][n], dog[m][n + 1], dog[m][n - 1]);
sec = sec_der(dog[m][n], dog[m][n + 1], dog[m][n - 1]);
for (i = 0; i < row; i++)
{
ptr1 = dog[m][n].ptr(i);
ptr2 = dstmat[m][n - 1].ptr(i);
if (i == 0)
{
ptr9 = NULL;
ptr10 = dstmat[m][n - 1].ptr(i + 1);
}
else if (i == (row - 1))
{
ptr9 = dstmat[m][n - 1].ptr(i - 1);
ptr10 = NULL;
}
else
{
ptr9 = dstmat[m][n - 1].ptr(i - 1);
ptr10 = dstmat[m][n - 1].ptr(i + 1);
}
if (n > 1)
{
ptr3 = dstmat[m][n - 2].ptr(i);
//
if (i == 0)
{
ptr5 = NULL;
ptr6 = dstmat[m][n - 2].ptr(i + 1);
}
else if (i == (row - 1))
{
ptr5 = dstmat[m][n - 2].ptr(i - 1);
ptr6 = NULL;
}
else
{
ptr5 = dstmat[m][n - 2].ptr(i - 1);
ptr6 = dstmat[m][n - 2].ptr(i + 1);
}
//
}
else
{
ptr3 = NULL;
ptr5 = NULL;
ptr6 = NULL;
}
if (n < 3)
{
ptr4 = dstmat[m][n].ptr(i);
if (i == 0)
{
ptr7 = NULL;
ptr8 = dstmat[m][n].ptr(i + 1);
}
else if (i == (row - 1))
{
ptr7 = dstmat[m][n].ptr(i - 1);
ptr8 = NULL;
}
else
{
ptr7 = dstmat[m][n].ptr(i - 1);
ptr8 = dstmat[m][n].ptr(i + 1);
}
}
else
{
ptr4 = NULL;
ptr7 = NULL;
ptr8 = NULL;
}
for (j = 0; j < col; j++)
{
if ((ptr2[j] == 255) || (ptr2[j] == 0))
{
Dx[0] = fir[0][i*col + j];
Dx[1] = fir[1][i*col + j];
Dx[2] = fir[2][i*col + j];
Hessian[0][0] = sec[0][i*col + j];
Hessian[0][1] = sec[3][i*col + j];
Hessian[0][2] = sec[5][i*col + j];
Hessian[1][0] = sec[3][i*col + j];
Hessian[1][1] = sec[1][i*col + j];
Hessian[1][2] = sec[4][i*col + j];
Hessian[2][0] = sec[5][i*col + j];
Hessian[2][1] = sec[4][i*col + j];
Hessian[2][2] = sec[2][i*col + j];
if (mat_invert(Hessian, Hessian_inv))
{
mat_mul(Dx, Hessian_inv, dev_x);
trace = Hessian[0][0] + Hessian[1][1];
det = Hessian[0][0] * Hessian[1][1] - Hessian[0][1] * Hessian[0][1];
//去除D(x)与二维HESSIAN矩阵不符合的点
if (abs((double)ptr2[j] + 0.5*(Dx[0] * dev_x[0] + Dx[1] * dev_x[1] + Dx[2] * dev_x[2]) > 0.04) || (abs(trace*trace / det) >= 1.21))
{
ptr2[j] = 100;
continue;
}
else
{
if ((abs(dev_x[0]) <= 0.5) && (abs(dev_x[1]) <= 0.5) && (abs(dev_x[2]) <= 0.5)) continue;
else
{
if (dev_x[0] > 0.5) x = 1;
else if (dev_x[0] < -0.5) x = -1;
else x = 0;
if (dev_x[1] > 0.5) y = 1;
else if (dev_x[1] < -0.5) y = -1;
else y = 0;
if (dev_x[2] > 0.5) sigma = 1;
else if (dev_x[2] < -0.5) sigma = -1;
else sigma = 0;
if ((sigma == 1) && (y == 0)) temp = ptr4;
else if ((sigma == -1) && (y == 0)) temp = ptr3;
else if ((sigma == 0) && (y == 0)) temp = ptr2;
else if ((sigma == 1) && (y == 1)) temp = ptr8;
else if ((sigma == -1) && (y == 1)) temp = ptr6;
else if ((sigma == 0) && (y == 1)) temp = ptr10;
else if ((sigma == 1) && (y == -1)) temp = ptr7;
else if ((sigma == -1) && (y == -1)) temp = ptr5;
else if ((sigma == 0) && (y == -1)) temp = ptr9;
if ((temp != NULL) && ((j + x) >= 0) && ((j + x) <= col) && (k != 5))
{
temp[j + x] = ptr2[j];
ptr2[j] = 100;
}
else
{
ptr2[j] = 100;
break;
}
}
}
}
else ptr2[j] = 100;
}
else continue;
}
}
}
}
}
}//第四部就是用第二个公式调整特征点的位置,如果越界或者迭代了多次都不收敛就舍弃特征点,有可能在这部要对应回原图
int add_point(Mat dstmat[3][3], feature feat[10000],Mat Gaussian[3][6]) //返回值是结构体数组长度
{
int i = 0,j = 0,k=0,m=0,n=0;
int col, row;
uchar *ptr1,*ptr2,*ptr3,*ptr4;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
{
col = dstmat[i][j].cols;
row = dstmat[i][j].rows;
for (m = 1; m < row-1; m++)
{
ptr1 = dstmat[i][j].ptr(m);
ptr2 = Gaussian[i][j+1].ptr(m);
ptr3 = Gaussian[i][j + 1].ptr(m-1);
ptr4 = Gaussian[i][j + 1].ptr(m+1);
for (n = 0; n < col; n++)
{
if (ptr1[n] == 255 || ptr1[n] == 0)
{
feat[k].x=m;
feat[k].y = n;
feat[k].sigma = j + 1;
feat[k].octave = i;
feat[k].m = sqrt((ptr4[n] - ptr3[n])*(ptr4[n] - ptr3[n]) + (ptr2[n + 1] - ptr2[n - 1])*(ptr2[n + 1] - ptr2[n - 1]));
feat[k].ori = atan2((ptr2[n + 1] - ptr2[n - 1]) , (ptr4[n] - ptr3[n]));
feat[k].theta = 0;
k++;
}
}
}
}
return k;
} //
void gethist(double bin[36],feature feat[10000],Mat Gaussian[3][6],int length,int radious,double sig)
{
uchar *ptr1, *ptr2, *ptr3,*ptr4;
double ori,m,temp1;
int i,j,k;
int n;
for (i = 0; i < length; i++)
{
// ptr2 = Gaussian[feat[i].octave][feat[i].sigma].ptr(feat[i].x);
if ((feat[i].x - radious > 0) && (feat[i].x + radious) < (Gaussian[feat[i].octave][feat[i].sigma].rows-1) && (feat[i].y - radious > 0) && (feat[i].y + radious < (Gaussian[feat[i].octave][feat[i].sigma].cols)-1))
{
for (j = 0; j < 2 * radious; j++)
{
ptr2 = (uchar *)Gaussian[feat[i].octave][feat[i].sigma].ptr(feat[i].x + j - radious);
ptr3 = (uchar *)Gaussian[feat[i].octave][feat[i].sigma].ptr(feat[i].x + j - radious-1);
ptr4 = (uchar *)Gaussian[feat[i].octave][feat[i].sigma].ptr(feat[i].x + j - radious+1);
for (k = 0; k < 2 * radious; k++)
{
n = feat[i].y + k - radious;
ori = atan2((ptr2[n + 1] - ptr2[n - 1]) , (ptr4[n] - ptr3[n]));
m=sqrt((ptr4[n] - ptr3[n])*(ptr4[n] - ptr3[n]) + (ptr2[n + 1] - ptr2[n - 1])*(ptr2[n + 1] - ptr2[n - 1]));
if (ori >= -PI && ori < -17*PI / 18) bin[0] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -16 * PI / 18) bin[1] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -15 * PI / 18) bin[2] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -14 * PI / 18) bin[3] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -13 * PI / 18) bin[4] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -12 * PI / 18) bin[5] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -11 * PI / 18) bin[6] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -10 * PI / 18) bin[7] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -9 * PI / 18) bin[8] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -8 * PI / 18) bin[9] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -7 * PI / 18) bin[10] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -6 * PI / 18) bin[11] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -5 * PI / 18) bin[12] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -4 * PI / 18) bin[13] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -3 * PI / 18) bin[14] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -2 * PI / 18) bin[15] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < -1 * PI / 18) bin[16] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 0) bin[17] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < PI / 18) bin[18] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 2 * PI / 18) bin[19] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 3 * PI / 18) bin[20] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 4 * PI / 18) bin[21] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 5 * PI / 18) bin[22] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 6 * PI / 18) bin[23] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 7 * PI / 18) bin[24] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 8 * PI / 18) bin[25] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 9 * PI / 18) bin[26] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 10 * PI / 18) bin[27] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 11 * PI / 18) bin[28] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 12 * PI / 18) bin[29] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 13 * PI / 18) bin[30] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 14 * PI / 18) bin[31] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 15 * PI / 18) bin[32] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 16 * PI / 18) bin[33] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < 17 * PI / 18) bin[34] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else if (ori < PI) bin[35] += m*pow(E, -((k - radious)*(k - radious) + (j - radious)*(j - radious)) / (2 * sig*sig));
else printf("ori error1!\n");
temp1 = bin[0];
for (i = 0; i < 36; i++) if (bin[i]>temp1) temp1 = bin[i];
feat[i].theta = temp1;
}
}
}
}
}
void smoothhist(double bin[36])
{
int i;
for (i = 1; i < 35; i++)
{
bin[i] = 0.25*bin[i - 1] + 0.5*bin[i] + 0.25*bin[i + 1];
}
}
void reproduce(double bin[36], feature feat[10000], int &length,feature temp)
{
int i;
double temp1=0,temp2=0,tempi=0;
for (i = 0; i < 36; i++) if (bin[i]>temp1) temp1 = bin[i];
for (i = 0; i < 36; i++)
if ((abs(bin[i] - temp1)>1e-5) && (bin[i]>temp2))
{
temp2 = bin[i];
tempi = i;
}
if (temp2 > temp1*0.8)
{
length++;
feat[length]= temp;
feat[length].m = temp2;
feat[length].ori = (i-18+0.5)*PI/18;
feat[length].theta = (i - 18 + 0.5)*PI / 18;
}
}
void get_desc(feature feat[10000],int length,Mat Gaussian[3][6],int radious)
{
int i, j,k,n;
int tx, ty, tt;
double x1 = 0, y1 = 0;
double w,ori,m;
double dx, dy, dt;
uchar *ptr2, *ptr3, *ptr4;
double x2 = 0, y2 = 0;
for (k = 0; k < length; k++)
{
for (i = -radious; i <= radious; i++)
{
if ((feat[k].x - radious > 0) && (feat[k].x + radious) < (Gaussian[feat[k].octave][feat[k].sigma].rows - 1) && (feat[k].y - radious > 0) && (feat[k].y + radious < (Gaussian[feat[k].octave][feat[k].sigma].cols) - 1))
{
ptr2 = (uchar *)Gaussian[feat[k].octave][feat[k].sigma].ptr(feat[k].x + i);
ptr3 = (uchar *)Gaussian[feat[k].octave][feat[k].sigma].ptr(feat[k].x + i - 1);
ptr4 = (uchar *)Gaussian[feat[k].octave][feat[k].sigma].ptr(feat[k].x + i + 1);
for (j = -radious; j <= radious; j++)
{
//x1 = Gaussian[feat[k].octave][feat[k].sigma].ptr(feat[k].x + (int)x1)[feat[k].y + (int)y1]
x1 = i*cos(feat[k].theta) - j*sin(feat[k].theta);
y1 = i*sin(feat[k].theta) + j*cos(feat[k].theta);
n = feat[k].y + j;
ori = atan2((ptr2[n + 1] - ptr2[n - 1]), (ptr4[n] - ptr3[n]));
ori -= feat[k].theta;
if (ori < -PI) ori += 2 * PI;
if (ori > PI) ori -= 2 * PI;
m = sqrt((ptr4[n] - ptr3[n])*(ptr4[n] - ptr3[n]) + (ptr2[n + 1] - ptr2[n - 1])*(ptr2[n + 1] - ptr2[n - 1]));
x2 = (x1 / (3 * (feat[k].octave + 1)) + 2);
y2 = (y1 / (3 * (feat[k].octave + 1)) + 2);
tx = (int)x2;
ty = (int)y2;
dx = x2 - tx;
dy = y2 - ty;
if (-PI <= ori&&ori > -3 * PI / 4) dt = ori + PI;
else if (-3 * PI / 4 <= ori&&ori > -PI / 2) dt = ori + PI * 3 / 4;
else if (-PI / 2 <= ori&&ori > -PI / 4) dt = ori + PI/2;
else if (-PI / 4 <= ori&&ori >0) dt = ori + PI/ 4;
else if (0<= ori&&ori > PI / 4) dt = ori;
else if (PI / 4 <= ori&&ori >PI/2) dt = ori - PI / 4;
else if (PI / 2 <= ori&&ori > 3*PI / 4) dt = ori - PI / 2;
else if (3 * PI / 4 <= ori&&ori > PI) dt = ori - PI * 3 / 4;
else printf("error2!");
w = pow(E, -(x1*x1 + y1*y1) / 8);
if (-PI <= ori&&ori > -3 * PI / 4)
{
feat[k].desc[tx][ty][0] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][1] += w*m*dx*dy*(1-dt);
feat[k].desc[tx][ty+1][0] += w*m*dx*(1-dy)*dt;
feat[k].desc[tx][ty+1][1] += w*m*dx*(1-dy)*(1 - dt);
feat[k].desc[tx][ty][0] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][1] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx+1][ty + 1][0] += w*m*(1-dx)*(1 - dy)*dt;
feat[k].desc[tx+1][ty + 1][1] += w*m*(1-dx)*(1 - dy)*(1 - dt);
}
else if (-3 * PI / 4 <= ori&&ori > -PI / 2) {
feat[k].desc[tx][ty][1] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][2] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx][ty + 1][1] += w*m*dx*(1 - dy)*dt;
feat[k].desc[tx][ty + 1][2] += w*m*dx*(1 - dy)*(1 - dt);
feat[k].desc[tx][ty][1] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][2] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx + 1][ty + 1][1] += w*m*(1 - dx)*(1 - dy)*dt;
feat[k].desc[tx + 1][ty + 1][2] += w*m*(1 - dx)*(1 - dy)*(1 - dt);
}
else if (-PI / 2 <= ori&&ori > -PI / 4) {
feat[k].desc[tx][ty][2] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][3] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx][ty + 1][2] += w*m*dx*(1 - dy)*dt;
feat[k].desc[tx][ty + 1][3] += w*m*dx*(1 - dy)*(1 - dt);
feat[k].desc[tx][ty][2] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][3] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx + 1][ty + 1][2] += w*m*(1 - dx)*(1 - dy)*dt;
feat[k].desc[tx + 1][ty + 1][3] += w*m*(1 - dx)*(1 - dy)*(1 - dt);
}
else if (-PI / 4 <= ori&&ori >0) {
feat[k].desc[tx][ty][3] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][4] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx][ty + 1][3] += w*m*dx*(1 - dy)*dt;
feat[k].desc[tx][ty + 1][4] += w*m*dx*(1 - dy)*(1 - dt);
feat[k].desc[tx][ty][3] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][4] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx + 1][ty + 1][3] += w*m*(1 - dx)*(1 - dy)*dt;
feat[k].desc[tx + 1][ty + 1][4] += w*m*(1 - dx)*(1 - dy)*(1 - dt);
}
else if (0 <= ori&&ori > PI / 4) {
feat[k].desc[tx][ty][4] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][5] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx][ty + 1][4] += w*m*dx*(1 - dy)*dt;
feat[k].desc[tx][ty + 1][5] += w*m*dx*(1 - dy)*(1 - dt);
feat[k].desc[tx][ty][4] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][5] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx + 1][ty + 1][4] += w*m*(1 - dx)*(1 - dy)*dt;
feat[k].desc[tx + 1][ty + 1][5] += w*m*(1 - dx)*(1 - dy)*(1 - dt);
}
else if (PI / 4 <= ori&&ori >PI / 2) {
feat[k].desc[tx][ty][5] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][6] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx][ty + 1][5] += w*m*dx*(1 - dy)*dt;
feat[k].desc[tx][ty + 1][6] += w*m*dx*(1 - dy)*(1 - dt);
feat[k].desc[tx][ty][5] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][6] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx + 1][ty + 1][5] += w*m*(1 - dx)*(1 - dy)*dt;
feat[k].desc[tx + 1][ty + 1][6] += w*m*(1 - dx)*(1 - dy)*(1 - dt);
}
else if (PI / 2 <= ori&&ori > 3 * PI / 4) {
feat[k].desc[tx][ty][6] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][7] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx][ty + 1][6] += w*m*dx*(1 - dy)*dt;
feat[k].desc[tx][ty + 1][7] += w*m*dx*(1 - dy)*(1 - dt);
feat[k].desc[tx][ty][6] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][7] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx + 1][ty + 1][6] += w*m*(1 - dx)*(1 - dy)*dt;
feat[k].desc[tx + 1][ty + 1][7] += w*m*(1 - dx)*(1 - dy)*(1 - dt);
}
else if (3 * PI / 4 <= ori&&ori > PI) {
feat[k].desc[tx][ty][7] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][0] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx][ty + 1][7] += w*m*dx*(1 - dy)*dt;
feat[k].desc[tx][ty + 1][0] += w*m*dx*(1 - dy)*(1 - dt);
feat[k].desc[tx][ty][7] += w*m*dx*dy*dt;
feat[k].desc[tx][ty][0] += w*m*dx*dy*(1 - dt);
feat[k].desc[tx + 1][ty + 1][7] += w*m*(1 - dx)*(1 - dy)*dt;
feat[k].desc[tx + 1][ty + 1][0] += w*m*(1 - dx)*(1 - dy)*(1 - dt);
}
else printf("error3!");
//线性插值
}
}
}
}
}
void standardize(feature feat[10000], int length)
{
int i, j,k,m,n;
double sum;
for (i = 0; i < length; i++)
{
sum = 0;
for (m = 0; m < 4; m++)
{
for (n = 0; n < 4; n++)
{
for (k = 0; k < 8; k++) sum += feat[i].desc[m][n][k];
}
}
sum = sqrt(sum);
for (m = 0; m < 4; m++)
{
for (n = 0; n < 4; n++)
{
for (k = 0; k < 8; k++) feat[i].desc[m][n][k] = feat[i].desc[m][n][k]/sum;
}
}
for (m = 0; m < 4; m++)
{
for (n = 0; n < 4; n++)
{
for (k = 0; k < 8; k++) if (feat[i].desc[m][n][k]>0.2) feat[i].desc[m][n][k]=0.2;
}
}
sum = 0;
for (m = 0; m < 4; m++)
{
for (n = 0; n < 4; n++)
{
for (k = 0; k < 8; k++) sum += feat[i].desc[m][n][k];
}
}
sum = sqrt(sum);
for (m = 0; m < 4; m++)
{
for (n = 0; n < 4; n++)
{
for (k = 0; k < 8; k++) feat[i].desc[m][n][k] = feat[i].desc[m][n][k] / sum;
}
}
}
}
void match(feature feat[10000],int length,Mat Gaussian[3][6])
{
int i,j,k,l,m,n;
double temp[10000][10000] = { 65535 };
double temp1,temp2;
int tempi, tempj;
for (i = 0; i < length; i++)
{
for (j = i; j < length; j++)
{
for (m = 0; m < 4; m++)
for (n = 0; n < 4; n++)
for (l = 0; l < 8; l++)
{
temp[i][j]+= (feat[i].desc[m][n][l] - feat[j].desc[m][n][l])*(feat[i].desc[m][n][l] - feat[j].desc[m][n][l]);
}
}
}
for (i = 0; i < length; i++)
{
temp1 = 65535;
temp2 = 65535;
for (j = i; j < length; j++)
{
if (temp1>temp[i][j])
{
temp1 = temp[i][j];
tempi = i;
tempj = j;
}
}
for (j = i; j < length; j++)
{
if ((j!=tempj)&&temp2>temp[i][j]) temp2 = temp[i][j];
}
}
if ((temp1 / temp2) < 0.5&&feat[tempi].octave == feat[tempj].octave) line(Gaussian[feat[tempi].octave][0], Point(feat[tempj].y, feat[tempj].x), Point(feat[tempi].y, feat[tempi].x), Scalar(0), 2, 8);
}
void main()
{
Mat srcImage = imread("D:\\51.jpg",0);
Mat Gaussian[3][6];
int length;
int radious;
double bin[36] = { 0 };
feature feat[10000];
GaussianBlur(srcImage, srcImage, Size(0, 0), 0.5, 0.5);
Mat dog[3][5],dstmat[3][3];
Dog(srcImage, dog,Gaussian);
imshow("第一尺度第一层", Gaussian[0][1]);
imshow("第一尺度第二层", Gaussian[0][0]);
imshow("第一尺度第三层", Gaussian[0][2]);
imshow("第二尺度第一层", Gaussian[1][1]);
imshow("第二尺度第二层", Gaussian[1][0]);
imshow("第二尺度第三层", Gaussian[1][2]);
imshow("第三尺度第一层", Gaussian[2][1]);
imshow("第三尺度第二层", Gaussian[2][0]);
imshow("第三尺度第三层", Gaussian[2][2]);
// imshow("1", dog[1][0]);
/// getmax_min(dog, dstmat);
// eliminate_point(dog, dstmat);
// length=add_point(dstmat, feat, Gaussian);
// gethist(bin,feat,Gaussian,length,)
// imshow("1", dstmat[0][2]);
// imshow("2", dstmat[1][2]);
// imshow("3", dstmat[2][2]);
waitKey(0);
}
|
// lisp-aqtplotter.h -- Declarations for AquaTerm Graphics under Lisp
//
// DM/MCFA 02/99
// AquaTerm mods 06/04 DM
// ---------------------------------------------------------
#ifndef __GRAPHICS_H__
#define __GRAPHICS_H__
#define DEFAULT_WIN_ID 0
#define DEFAULT_X_POS 50
#define DEFAULT_Y_POS 50
#define DEFAULT_X_SIZE 400
#define DEFAULT_Y_SIZE 300
#define DEFAULT_BG 0x0FFFFFF // white
class TImage
{
public:
int m_width;
int m_height;
// int m_xlen;
// unsigned char *m_bits;
float m_xmag;
float m_ymag;
int m_xpos;
int m_ypos;
float m_sf;
float m_offset;
bool m_flipv;
bool m_fliph;
float m_xorg;
float m_xsf;
float m_yorg;
float m_ysf;
bool m_xlog;
bool m_ylog;
float m_xmin; // same as m_xorg
float m_xmax;
float m_ymin; // same as m_yorg
float m_ymax;
TImage(int xsiz, int ysiz,
int xpos, int ypos,
float xmag, float ymag,
float off, float sf,
bool flipv, bool fliph,
float xmin, float xmax,
float ymin, float ymax,
bool xlog, bool ylog);
virtual ~TImage();
int get_xpos()
{ return m_xpos; }
int get_ypos()
{ return m_ypos; }
int get_width()
{ return m_width; }
int get_height()
{ return m_height; }
float get_xmag()
{ return m_xmag; }
float get_ymag()
{ return m_ymag; }
bool needs_hflip()
{ return m_fliph; }
bool needs_vflip()
{ return m_flipv; }
// bool get_pixel(int wx, int wy, float &fx, float &fy, float &val);
};
struct PlotInfo
{
float m_xmin;
float m_xmax;
float m_ymin;
float m_ymax;
bool m_xlog;
bool m_ylog;
char *m_xtitle;
char *m_ytitle;
char *m_title;
float m_aspect;
int m_bg;
int m_fg;
bool m_fullgrid;
bool m_ticks_inside;
int get_bg()
{ return m_bg; }
int get_fg()
{ return m_fg; }
float get_xmin()
{ return m_xmin; }
float get_xmax()
{ return m_xmax; }
float get_ymin()
{ return m_ymin; }
float get_ymax()
{ return m_ymax; }
char* get_xtitle()
{ return m_xtitle; }
char* get_ytitle()
{ return m_ytitle; }
char* get_title()
{ return m_title; }
bool has_log_xaxis()
{ return m_xlog; }
bool has_log_yaxis()
{ return m_ylog; }
bool has_ticks_inside()
{ return m_ticks_inside; }
bool has_fullgrid()
{ return m_fullgrid; }
};
struct TPoint
{
int x;
int y;
};
struct TVertInfo
{
int m_color;
int m_nverts;
TPoint *m_pts;
};
struct TPolysParms
{
int m_npolys;
TVertInfo *m_polys;
};
struct WSizeInfo
{
int m_xsize;
int m_ysize;
int m_left;
int m_top;
};
struct DataInfo
{
int m_npts;
float *m_xvals;
float *m_yvals;
int m_psym;
int m_color;
int m_thick;
bool m_clip;
int m_penpat;
int m_alpha;
int get_plotting_symbol()
{ return m_psym; }
int get_color()
{ return m_color; }
int get_npts()
{ return m_npts; }
int get_line_thickness()
{ return m_thick; }
float* get_xvalues()
{ return m_xvals; }
float* get_yvalues()
{ return m_yvals; }
};
struct RECT
{
float m_left;
float m_top;
float m_right;
float m_bottom;
void set_tlbr(float top, float left, float bottom, float right)
{ m_top = top; m_left = left; m_bottom = bottom; m_right = right; }
float get_left()
{ return m_left; }
float get_right()
{ return m_right; }
float get_top()
{ return m_top; }
float get_bottom()
{ return m_bottom; }
float get_width()
{ return (m_right - m_left); }
float get_height()
{ return (m_top - m_bottom); }
};
struct WindowInfo;
struct PlotRec
{
float m_xmin;
float m_xsf;
float m_ymin;
float m_ysf;
RECT m_plotrect;
float m_ygap;
float m_xgap;
bool m_xlog;
bool m_ylog;
float m_xmax;
float m_ymax;
PlotRec(TImage *p);
PlotRec(WindowInfo *wp, PlotInfo *p);
PlotRec(WindowInfo *wp);
virtual ~PlotRec();
void set_plotrect(float top, float left, float bottom, float right)
{ m_plotrect.set_tlbr(top, left, bottom, right); }
float get_xmin()
{ return m_xmin; }
float get_xmax()
{ return m_xmax; }
float get_ymin()
{ return m_ymin; }
float get_ymax()
{ return m_ymax; }
void set_xgap(float gap)
{ m_xgap = gap; }
void set_ygap(float gap)
{ m_ygap = gap; }
void set_xaxis_sf(float sf)
{ m_xsf = sf; }
float get_xaxis_sf()
{ return m_xsf; }
float get_yaxis_sf()
{ return m_ysf; }
void set_yaxis_sf(float sf)
{ m_ysf = sf; }
RECT& get_plotrect()
{ return m_plotrect; }
float get_plotrect_left()
{ return m_plotrect.get_left(); }
float get_plotrect_right()
{ return m_plotrect.get_right(); }
float get_plotrect_top()
{ return m_plotrect.get_top(); }
float get_plotrect_bottom()
{ return m_plotrect.get_bottom(); }
float get_xgap()
{ return m_xgap; }
float get_ygap()
{ return m_ygap; }
bool has_log_xaxis()
{ return m_xlog; }
bool has_log_yaxis()
{ return m_ylog; }
};
struct WindowInfo
{
WindowInfo *m_next;
int m_id;
TImage *m_image;
int m_bg;
PlotRec *m_plot;
int m_delay;
int m_xsize;
int m_ysize;
WindowInfo(int winid);
virtual ~WindowInfo();
void init(int xsize, int ysize, int bg);
void reset();
void set_image(TImage *img, bool discard_plot_if_present = true);
void set_plot(PlotRec *p);
void discard_plot();
void discard_image();
void set_bg(int bg)
{ m_bg = bg; }
WindowInfo* get_next()
{ return m_next; }
void set_next(WindowInfo *p)
{ m_next = p; }
int get_id()
{ return m_id; }
// -------------------------------
void reset_delay()
{ m_delay = 0; }
void increment_delay()
{ ++m_delay; }
void decrement_delay()
{ --m_delay; }
bool not_delayed()
{ return (m_delay <= 0); }
bool is_delayed()
{ return (m_delay > 0); }
// -------------------------------
int get_width()
{ return m_xsize; }
int get_height()
{ return m_ysize; }
};
// -----------------------------------------------------
// Primitive graphics operations
enum { DATA_UNITS = 1,
FRACTION_UNITS = 2,
PIXEL_UNITS = 3 };
union drawable_point
{
float f[2];
int i[2];
};
struct drawable_line
{
drawable_point* origin;
drawable_point* extent;
};
struct drawable_rectangle
{
drawable_point* origin;
drawable_point* extent;
};
struct drawable_rounded_rectangle
{
drawable_point* origin;
drawable_point* extent;
};
struct drawable_ellipse
{
drawable_point* origin;
drawable_point* extent;
};
struct drawable_arc
{
drawable_point* origin;
drawable_point* extent;
float* start_angle;
float* stop_angle;
};
enum { FACE_BOLD,
FACE_ITALIC,
FACE_UNDERLINE };
struct text_face
{
char* face_name;
int face_size;
// face_styles list
};
struct drawable_text
{
drawable_point* origin;
text_face* face;
char* str;
};
union drawable_element
{
drawable_point point;
drawable_line line;
drawable_rectangle rectangle;
drawable_rounded_rectangle rounded_rectangle;
drawable_ellipse ellipse;
drawable_arc arc;
drawable_text text;
};
enum { GROP_SRC_COPY = 0,
GROP_SRC_OR = 1,
GROP_SRC_AND = 2,
GROP_SRC_XOR = 3,
GROP_SRC_CLEAR = 4 };
enum { ANCHOR_CTR,
ANCHOR_N,
ANCHOR_NE,
ANCHOR_E,
ANCHOR_SE,
ANCHOR_S,
ANCHOR_SW,
ANCHOR_W,
ANCHOR_NW };
enum { PENPAT_SOLID,
PENPAT_DASH,
PENPAT_DOT,
PENPAT_DASHDOT,
PENPAT_DASHDOTDOT,
PENPAT_NULL,
PENPAT_INSIDE_FRAME };
enum { DR_POINT,
DR_LINE,
DR_RECTANGLE,
DR_ROUNDED_RECTANGLE,
DR_ELLIPSE,
DR_ARC,
DR_CHORD,
DR_PIE,
DR_TEXT };
struct drawable
{
drawable_element* elt;
int grop; // int
int pen_pat; // int
int thick; // int
int border_color; // int
int is_filled; // bool
int fill_color; // int
int anchor; // int
};
#endif // __GRAPHICS_H__
|
#include<iostream>
#include<vector>
#include<stdio.h>
#include<string.h>
#include<strings.h>
#include<stdio.h>
#include<string>
using namespace std;
int main()
{
string h,k;
cin>>h>>k;
if(h.equal(k))
cout<<"r";
/* vector<string>l1;
int i,n,t;
char s[100];
cin>>t;
while(t--)
{
cin>>n;
for(i = 0;i <= n;++i)
{
gets(s);
l1.push_back(s);
}
// for(i = 0;i <= n;++i)
cout<<l1[0]<<endl;
}*/
}
|
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM9DS1.h>
#include <Adafruit_Simple_AHRS.h>
// Create LSM9DS0 board instance.
Adafruit_LSM9DS1 lsm = Adafruit_LSM9DS1();
// Create simple AHRS algorithm using the LSM9DS0 instance's accelerometer and magnetometer.
Adafruit_Simple_AHRS ahrs(&lsm.getAccel(), &lsm.getMag(), &lsm.getGyro());
void setupSensor()
{
// Set data rate for G and XL. Set G low-pass cut off. (Section 7.12)
lsm.write8(XGTYPE, Adafruit_LSM9DS1::LSM9DS1_REGISTER_CTRL_REG1_G, ODR_952 | G_BW_G_10 ); //952hz ODR + 63Hz cuttof
// Enable the XL (Section 7.23)
lsm.write8(XGTYPE, Adafruit_LSM9DS1::LSM9DS1_REGISTER_CTRL_REG5_XL, XL_ENABLE_X | XL_ENABLE_Y | XL_ENABLE_Z);
// Set low-pass XL filter frequency divider (Section 7.25)
lsm.write8(XGTYPE, Adafruit_LSM9DS1::LSM9DS1_REGISTER_CTRL_REG7_XL, HR_MODE | XL_LP_ODR_RATIO_9);
// enable mag continuous (Section 8.7)
lsm.write8(MAGTYPE, Adafruit_LSM9DS1::LSM9DS1_REGISTER_CTRL_REG3_M, B00000000); // continuous mode
// This only sets range of measurable values for each sensor. Setting these manually (I.e., without using these functions) will cause incorrect output from the library.
lsm.setupAccel(Adafruit_LSM9DS1::LSM9DS1_ACCELRANGE_2G);
lsm.setupMag(Adafruit_LSM9DS1::LSM9DS1_MAGGAIN_4GAUSS);
lsm.setupGyro(Adafruit_LSM9DS1::LSM9DS1_GYROSCALE_245DPS);
}
void setup(void)
{
Serial.begin(115200);
Serial.println(F("Adafruit LSM9DS1 9 DOF Board AHRS Example")); Serial.println("");
// Initialise the LSM9DS0 board.
if(!lsm.begin())
{
// There was a problem detecting the LSM9DS0 ... check your connections
Serial.print(F("Ooops, no LSM9DS1 detected ... Check your wiring or I2C ADDR!"));
while(1);
}
// Setup the sensor gain and integration time.
setupSensor();
}
unsigned int last = millis();
void loop(void)
{
quad_data_t orientation;
int now = millis();
// Use the simple AHRS function to get the current orientation.
if (ahrs.getQuadOrientation(&orientation))
{
/* 'orientation' should have valid .roll and .pitch fields */
Serial.print(now - last);
Serial.print(F(" "));
Serial.print(orientation.roll);
Serial.print(F(" "));
Serial.print(orientation.pitch);
Serial.print(F(" "));
Serial.print(orientation.roll_rate);
Serial.print(F(" "));
Serial.print(orientation.pitch_rate);
Serial.print(F(" "));
Serial.print(orientation.yaw_rate);
Serial.println(F(""));
}
last = now;
}
|
#include "FrameBuffer.h"
#include "Globals.h"
#include "glad.h"
namespace
{
constexpr std::array<glm::vec2, 6> QUAD
{
glm::vec2(-1.0f, -1.0f),
glm::vec2(1.0f, -1.0f),
glm::vec2(1.0f, 1.0f),
glm::vec2(1.0f, 1.0f),
glm::vec2(-1.0f, 1.0f),
glm::vec2(-1.0f, -1.0f)
};
constexpr std::array<glm::vec2, 6> TEXT_COORDS
{
glm::vec2(0.0f, 0.0f),
glm::vec2(1.0f, 0.0f),
glm::vec2(1.0f, 1.0f),
glm::vec2(1.0f, 1.0f),
glm::vec2(0.0f, 1.0f),
glm::vec2(0.0f, 0.0f)
};
}
FrameBuffer::FrameBuffer(const glm::uvec2& windowSize)
: m_ID(Globals::INVALID_OPENGL_ID),
m_vaoID(Globals::INVALID_OPENGL_ID),
m_positionsVBO(Globals::INVALID_OPENGL_ID),
m_textCoordsVBO(Globals::INVALID_OPENGL_ID),
m_textureID(Globals::INVALID_OPENGL_ID),
m_renderBufferID(Globals::INVALID_OPENGL_ID)
{
glGenFramebuffers(1, &m_ID);
glBindFramebuffer(GL_FRAMEBUFFER, m_ID);
glGenTextures(1, &m_textureID);
glBindTexture(GL_TEXTURE_2D, m_textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, windowSize.x, windowSize.y, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_textureID, 0);
glGenRenderbuffers(1, &m_renderBufferID);
glBindRenderbuffer(GL_RENDERBUFFER, m_renderBufferID);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, windowSize.x, windowSize.y); // use a single renderbuffer object for both a depth AND stencil buffer.
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_renderBufferID); // now actually attach it
// now that we actually created the framebuffer and added all attachments we want to check if it is actually complete now
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glGenVertexArrays(1, &m_vaoID);
glBindVertexArray(m_vaoID);
glGenBuffers(1, &m_positionsVBO);
glBindBuffer(GL_ARRAY_BUFFER, m_positionsVBO);
glBufferData(GL_ARRAY_BUFFER, QUAD.size() * sizeof(glm::vec2), QUAD.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (const void*)0);
glGenBuffers(1, &m_textCoordsVBO);
glBindBuffer(GL_ARRAY_BUFFER, m_textCoordsVBO);
glBufferData(GL_ARRAY_BUFFER, TEXT_COORDS.size() * sizeof(glm::vec2), TEXT_COORDS.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (const void*)0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
FrameBuffer::~FrameBuffer()
{
assert(m_ID != Globals::INVALID_OPENGL_ID);
glDeleteFramebuffers(1, &m_ID);
assert(m_vaoID != Globals::INVALID_OPENGL_ID);
glDeleteVertexArrays(1, &m_vaoID);
assert(m_textureID != Globals::INVALID_OPENGL_ID);
glDeleteTextures(1, &m_textureID);
assert(m_renderBufferID != Globals::INVALID_OPENGL_ID);
glDeleteRenderbuffers(1, &m_renderBufferID);
assert(m_positionsVBO != Globals::INVALID_OPENGL_ID);
glDeleteBuffers(1, &m_positionsVBO);
assert(m_textCoordsVBO != Globals::INVALID_OPENGL_ID);
glDeleteBuffers(1, &m_textCoordsVBO);
}
unsigned int FrameBuffer::getID() const
{
return m_ID;
}
unsigned int FrameBuffer::getVAOID() const
{
return m_vaoID;
}
unsigned int FrameBuffer::getTextureID() const
{
return m_textureID;
}
unsigned int FrameBuffer::getRenderBufferID() const
{
return m_renderBufferID;
}
//
//void FrameBuffer::bind() const
//{
//
//}
//
//void FrameBuffer::unbind() const
//{
//}
//
//void FrameBuffer::render() const
//{
//}
|
//
// Created by 邓岩 on 2019/5/20.
//
/*
* 连号区间数
问题描述
小明这些天一直在思考这样一个奇怪而有趣的问题:
在1~N的某个全排列中有多少个连号区间呢?这里所说的连号区间的定义是:
如果区间[L, R] 里的所有元素(即此排列的第L个到第R个元素)递增排序后能得到一个长度为R-L+1的“连续”数列,则称这个区间连号区间。
当N很小的时候,小明可以很快地算出答案,但是当N变大的时候,问题就不是那么简单了,现在小明需要你的帮助。
输入格式
第一行是一个正整数N (1 <= N <= 50000), 表示全排列的规模。
第二行是N个不同的数字Pi(1 <= Pi <= N), 表示这N个数字的某一全排列。
输出格式
输出一个整数,表示不同连号区间的数目。
样例输入1
4
3 2 4 1
样例输出1
7
样例输入2
5
3 4 2 5 1
样例输出2
9
*/
# include <iostream>
# include <cstring>
using namespace std;
#define ll long long
ll v[50001];
ll n;
int main(void)
{
long long sum = 0;
cin >> n;
for (int i = 0; i < n; i++) {
int j;
cin >> j;
v[i] = j;
}
for (int i = 0; i < n; i++) {
ll l, r;
l = r = v[i];
for (int j = i; j < n; j++) {
if (v[j] < l)
l = v[j];
if (v[j] > r)
r = v[j];
if (r - l == j - i)
sum++;
}
}
cout << sum << endl;
return 0;
}
|
#include "TreeDecompositionPACE.h"
RawInstructiveTreeDecomposition::RawInstructiveTreeDecomposition() {
// constructor
}
void RawInstructiveTreeDecomposition::print(unsigned &k, unsigned parentno) {
k++;
std::cout << k << " " << type << "(" << parentno << ") ";
bag.print();
for (auto it = color_to_vertex_map.begin(); it != color_to_vertex_map.end();
it++) {
std::cout << it->first << "->" << it->second << " ";
}
std::cout << std::endl;
unsigned num = k;
for (size_t i = 0; i < children.size(); i++) {
children[i]->print(k, num);
}
}
void RawInstructiveTreeDecomposition::printNode() {
bag.print();
for (auto it = color_to_vertex_map.begin(); it != color_to_vertex_map.end();
it++) {
std::cout << it->first << "->" << it->second << " ";
}
}
TreeDecompositionPACE::TreeDecompositionPACE() {
num_vertices = 0;
num_graph_vertices = 0;
num_edges = 0;
width = 0;
}
void TreeDecompositionPACE::setNum_vertices(unsigned n) {
bags.resize(n);
num_vertices = n;
}
void TreeDecompositionPACE::setNum_graph_vertices(unsigned n) {
num_graph_vertices = n;
}
void TreeDecompositionPACE::setWidth(unsigned w) { width = w; }
bool TreeDecompositionPACE::addVertexToBag(unsigned vertex,
unsigned bagnumber) {
if (bagnumber > 0) {
bags[bagnumber - 1].insert(vertex);
} else {
return false;
}
return true;
}
bool TreeDecompositionPACE::setABag(vertex_t s, unsigned bagnumber) {
if (bagnumber > 0 and bagnumber <= bags.size()) {
bags[bagnumber - 1] = s;
return true;
} else {
return false;
}
}
bool TreeDecompositionPACE::addEdge(unsigned e1, unsigned e2) {
if (e1 <= bags.size() and e2 <= bags.size()) {
if (e1 > e2) {
edges.insert(std::make_pair(e2, e1));
return true;
} else if (e1 < e2) {
edges.insert(std::make_pair(e1, e2));
return true;
} else {
return false;
}
} else {
return false;
}
}
void TreeDecompositionPACE::printBags() {
for (size_t i = 0; i < bags.size(); i++) {
std::cout << "b " << i + 1 << " ";
for (auto it = bags[i].begin(); it != bags[i].end(); it++) {
std::cout << *it;
if (next(it) != bags[i].end()) {
std::cout << " ";
}
}
std::cout << "" << std::endl;
}
}
void TreeDecompositionPACE::printEdges() {
for (auto it = edges.begin(); it != edges.end(); it++) {
std::cout << it->first << " " << it->second << std::endl;
}
}
void TreeDecompositionPACE::print() {
std::cout << "s td " << num_vertices << " " << width + 1 << " "
<< num_graph_vertices << std::endl;
printBags();
printEdges();
}
void TreeDecompositionPACE::printTree() {
unsigned k = 0;
if (root == nullptr) {
std::cout << "\033[1;31mError in TreeDecompositionPACE::printTree : "
"the root is not set!\033[0m"
<< std::endl;
} else {
root->print(k, 0);
}
}
void TreeDecompositionPACE::constructInnerNodes(
std::set<unsigned> &visited_bags, unsigned current,
std::shared_ptr<RawInstructiveTreeDecomposition> parent) {
visited_bags.insert(current);
if (bags[current - 1] == parent->bag.get_elements()) {
// this node serves no purpose, and its children can be connected to
// this node's parent.
for (auto [u_, v_] : edges) {
for (auto [u, v] :
{std::make_pair(u_, v_), std::make_pair(v_, u_)}) {
if (u == current && !visited_bags.count(v)) {
constructInnerNodes(visited_bags, v, parent);
}
}
}
} else {
std::shared_ptr<RawInstructiveTreeDecomposition> node(
new RawInstructiveTreeDecomposition);
node->bag.set_elements(bags[current - 1]);
node->parent = parent;
parent->children.push_back(node);
visited_bags.insert(current);
for (auto [u_, v_] : edges) {
for (auto [u, v] :
{std::make_pair(u_, v_), std::make_pair(v_, u_)}) {
if (u == current && !visited_bags.count(v)) {
constructInnerNodes(visited_bags, v, node);
}
}
}
}
}
bool TreeDecompositionPACE::constructRaw() {
std::shared_ptr<RawInstructiveTreeDecomposition> root_node(
new RawInstructiveTreeDecomposition);
root = root_node;
std::cerr << "edges: ";
for (auto [u, v] : edges) std::cerr << '(' << u << ',' << v << ") ";
std::cerr << '\n';
std::cerr << "root:\n";
root->printNode();
if (bags.size() > 0) {
root->bag.set_elements(bags[0]);
std::set<unsigned> visited_bags;
visited_bags.insert(1);
// create nodes for neighbors
for (auto it = edges.begin(); it != edges.end(); it++) {
// The reason that always the first pair should have edge with
// number 1 is that the edge set is an ordered set.
if (it->first == 1) {
constructInnerNodes(visited_bags, it->second, root);
} else if (it->second == 1) {
constructInnerNodes(visited_bags, it->first, root);
}
}
return true;
} else {
std::cout
<< "ERROR in TreeDecompositionPACE::constructRaw bags size is zero"
<< std::endl;
return false;
}
}
bool TreeDecompositionPACE::convertToBinary(
std::shared_ptr<RawInstructiveTreeDecomposition> node) {
if (node->children.size() > 2) {
// If "node" has n>2 children, then the algorithm creates "new_node"
// and set "new_node" as a second child of "node", and set n-1 children
// of "node" as children of "new_node".
std::shared_ptr<RawInstructiveTreeDecomposition> new_node(
new RawInstructiveTreeDecomposition);
new_node->bag = node->bag;
for (size_t i = 1; i < node->children.size(); i++) {
new_node->children.push_back(node->children[i]);
node->children[i]->parent = new_node;
}
node->children.resize(1);
node->children.push_back(new_node);
new_node->parent = node;
convertToBinary(node->children[0]);
convertToBinary(node->children[1]);
} else {
for (size_t i = 0; i < node->children.size(); i++) {
if (!convertToBinary(node->children[i])) {
return false;
}
}
}
return true;
}
bool TreeDecompositionPACE::joinFormat(
std::shared_ptr<RawInstructiveTreeDecomposition> node) {
if (node->children.size() > 2) {
std::cout << "ERROR in TreeDecompositionPACE::joinFormat, the Raw "
"instructive tree decomposition is not in binary form"
<< std::endl;
exit(20);
} else if (node->children.size() == 2) {
node->type = "Join";
if (!(node->bag == node->children[0]->bag)) {
std::shared_ptr<RawInstructiveTreeDecomposition> new_node(
new RawInstructiveTreeDecomposition);
new_node->bag = node->bag;
new_node->children.push_back(node->children[0]);
node->children[0]->parent = new_node;
node->children[0] = new_node;
new_node->parent = node;
joinFormat(new_node->children[0]);
} else {
joinFormat(node->children[0]);
}
if (!(node->bag == node->children[1]->bag)) {
std::shared_ptr<RawInstructiveTreeDecomposition> new_node(
new RawInstructiveTreeDecomposition);
new_node->bag = node->bag;
new_node->children.push_back(node->children[1]);
node->children[1]->parent = new_node;
node->children[1] = new_node;
new_node->parent = node;
joinFormat(new_node->children[0]);
} else {
joinFormat(node->children[1]);
}
} else if (node->children.size() == 1) {
joinFormat(node->children[0]);
} else {
}
return true;
}
bool TreeDecompositionPACE::addEmptyNodes(
std::shared_ptr<RawInstructiveTreeDecomposition> node) {
if (node->children.size() == 0) {
if (node->bag.get_elements().size() > 0) {
std::shared_ptr<RawInstructiveTreeDecomposition> empty_node(
new RawInstructiveTreeDecomposition);
empty_node->type = "Leaf";
node->children.push_back(empty_node);
empty_node->parent = node;
} else {
node->type = "Leaf";
}
} else {
for (size_t i = 0; i < node->children.size(); i++) {
addEmptyNodes(node->children[i]);
}
}
return true;
}
bool TreeDecompositionPACE::addIntroVertex(
std::shared_ptr<RawInstructiveTreeDecomposition> node) {
if (node->children.size() == 1) {
std::set<unsigned> set_diff;
std::set<unsigned> elements_node = node->bag.get_elements();
std::set<unsigned> elements_node_child =
node->children[0]->bag.get_elements();
set_difference(elements_node.begin(), elements_node.end(),
elements_node_child.begin(), elements_node_child.end(),
inserter(set_diff, set_diff.begin()));
if (set_diff.size() > 1) {
std::shared_ptr<RawInstructiveTreeDecomposition> new_node(
new RawInstructiveTreeDecomposition);
new_node->children.push_back(node->children[0]);
new_node->children[0]->parent = new_node;
node->children[0] = new_node;
new_node->parent = node;
std::set<unsigned> elements_node_new = node->bag.get_elements();
elements_node_new.erase(*set_diff.begin());
new_node->bag.set_elements(elements_node_new);
node->type = "IntroVertex_" + std::to_string(*set_diff.begin());
addIntroVertex(new_node);
} else if (set_diff.size() == 1) {
node->type = "IntroVertex_" + std::to_string(*set_diff.begin());
addIntroVertex(node->children[0]);
} else if (elements_node == elements_node_child) {
std::cerr << "duplicated bags" << std::endl;
exit(20);
} else {
addIntroVertex(node->children[0]);
}
} else if (node->children.size() == 2) {
addIntroVertex(node->children[0]);
addIntroVertex(node->children[1]);
} else if (node->children.size() > 2) {
std::cout << "ERROR in TreeDecompositionPACE::addIntroVertex, node has "
"more that two children. Number of Children = "
<< node->children.size() << std::endl;
exit(20);
}
// for(auto it:node->children){
// if(node->type == it->type and node->type!="Join"){
// std::cout<<"ERROR in TreeDecompositionPACE::addIntroVertex,
// has same IntroVertex type"<<std::endl;
// std::cout<<node->type<<" "<<it->type<<std::endl;
//// node->bag.print();
//// std::cout<<std::endl;
//// it->bag.print();
//// std::cout<<"\n"<<it->children.size()<<std::endl;
//// printTree();
// exit(20);
// }
// }
return true;
}
bool TreeDecompositionPACE::addForgetVertex(
std::shared_ptr<RawInstructiveTreeDecomposition> node) {
if (node->children.size() == 1) {
std::set<unsigned> set_diff;
std::set<unsigned> elements_node = node->bag.get_elements();
std::set<unsigned> elements_node_child =
node->children[0]->bag.get_elements();
set_difference(elements_node_child.begin(), elements_node_child.end(),
elements_node.begin(), elements_node.end(),
inserter(set_diff, set_diff.begin()));
if (set_diff.size() > 1) {
if (node->type == "") {
std::shared_ptr<RawInstructiveTreeDecomposition> new_node(
new RawInstructiveTreeDecomposition);
new_node->children.push_back(node->children[0]);
new_node->children[0]->parent = new_node;
node->children[0] = new_node;
new_node->parent = node;
std::set<unsigned> elements_node_new = node->bag.get_elements();
elements_node_new.insert(*set_diff.rbegin());
// set<unsigned> elements_node_new =
// new_node->children[0]->bag.get_elements();
// elements_node_new.erase(*set_diff.rbegin());
new_node->bag.set_elements(elements_node_new);
node->type =
"ForgetVertex_" + std::to_string(*set_diff.rbegin());
addForgetVertex(new_node);
} else {
set_diff.clear();
set_difference(elements_node.begin(), elements_node.end(),
elements_node_child.begin(),
elements_node_child.end(),
inserter(set_diff, set_diff.begin()));
if (set_diff.size() != 1) {
std::cout
<< "Error in TreeDecompositionPACE::addForgetVertex, "
"set_diff size is not 1.";
exit(20);
} else {
std::shared_ptr<RawInstructiveTreeDecomposition> new_node(
new RawInstructiveTreeDecomposition);
new_node->children.push_back(node->children[0]);
new_node->children[0]->parent = new_node;
node->children[0] = new_node;
new_node->parent = node;
std::set<unsigned> elements_node_new =
node->bag.get_elements();
elements_node_new.erase(*set_diff.begin());
new_node->bag.set_elements(elements_node_new);
addForgetVertex(new_node);
}
}
} else if (set_diff.size() == 1) {
if (node->type == "") {
node->type =
"ForgetVertex_" + std::to_string(*set_diff.begin());
addForgetVertex(node->children[0]);
} else {
set_diff.clear();
set_difference(elements_node.begin(), elements_node.end(),
elements_node_child.begin(),
elements_node_child.end(),
inserter(set_diff, set_diff.begin()));
if (set_diff.size() != 1) {
std::cout
<< "Error in TreeDecompositionPACE::addForgetVertex, "
"set_diff size is not 1.";
exit(20);
}
std::shared_ptr<RawInstructiveTreeDecomposition> new_node(
new RawInstructiveTreeDecomposition);
new_node->children.push_back(node->children[0]);
new_node->children[0]->parent = new_node;
node->children[0] = new_node;
new_node->parent = node;
std::set<unsigned> elements_node_new = node->bag.get_elements();
// set<unsigned> elements_node_new =
// new_node->children[0]->bag.get_elements();
// elements_node_new.erase(*set_diff.begin());
elements_node_new.erase(*set_diff.begin());
new_node->bag.set_elements(elements_node_new);
addForgetVertex(new_node);
}
} else {
addForgetVertex(node->children[0]);
}
} else if (node->children.size() == 2) {
addForgetVertex(node->children[0]);
addForgetVertex(node->children[1]);
}
for (auto it : node->children) {
if (node->type == it->type and node->type != "Join") {
std::cout << "ERROR in TreeDecompositionPACE::addIntroVertex, has "
"same ForgetVertex type"
<< std::endl;
exit(20);
}
}
return true;
}
bool TreeDecompositionPACE::addIntroEdge(
std::shared_ptr<RawInstructiveTreeDecomposition> node,
std::set<unsigned> &visited_edges) {
if (strstr(node->type.c_str(), "IntroVertex")) {
std::set<unsigned> set_diff;
std::set<unsigned> elements_node = node->bag.get_elements();
std::set<unsigned> elements_node_child =
node->children[0]->bag.get_elements();
set_difference(elements_node.begin(), elements_node.end(),
elements_node_child.begin(), elements_node_child.end(),
inserter(set_diff, set_diff.begin()));
if (set_diff.size() != 1) {
std::cout
<< "ERROR in TreeDecompositionPACE::addIntroEdgeRecursion, "
"set_diff is not verified"
<< std::endl;
node->bag.print();
std::cout << "\n" << node->type << std::endl;
node->children[0]->bag.print();
std::cout << "\n" << node->children[0]->type << std::endl;
node->children[0]->children[0]->bag.print();
std::cout << "\n"
<< node->children[0]->children[0]->type << std::endl;
node->children[0]->children[0]->children[0]->bag.print();
std::cout << "\n"
<< node->children[0]->children[0]->children[0]->type
<< std::endl;
exit(20);
} else {
unsigned introducedVertex = (unsigned)*set_diff.begin();
std::multimap<unsigned, unsigned> incidence =
multigraph->getIncidenceMap();
std::vector<std::shared_ptr<RawInstructiveTreeDecomposition>>
generated_nodes;
for (auto it = incidence.begin(); it != incidence.end(); it++) {
if (it->second == introducedVertex) {
if (visited_edges.find(it->first) == visited_edges.end()) {
for (auto itr = incidence.begin();
itr != incidence.end(); itr++) {
if (itr->second != it->second and
itr->first == it->first and
(node->bag.get_elements().count(itr->second) >
0)) {
visited_edges.insert(it->first);
std::shared_ptr<RawInstructiveTreeDecomposition>
new_node(
new RawInstructiveTreeDecomposition);
new_node->bag = node->bag;
if (it->second < itr->second) {
new_node->type =
"IntroEdge_" +
std::to_string(it->second) + "_" +
std::to_string(itr->second);
new_node->bag.set_edge(it->second,
itr->second);
} else {
new_node->type =
"IntroEdge_" +
std::to_string(itr->second) + "_" +
std::to_string(it->second);
new_node->bag.set_edge(itr->second,
it->second);
}
generated_nodes.push_back(new_node);
break;
}
}
}
}
}
for (size_t i = 0; i < generated_nodes.size(); i++) {
if (i == 0) {
if (!node->parent) {
root = generated_nodes[0];
} else {
generated_nodes[0]->parent = node->parent;
for (size_t t = 0; t < node->parent->children.size();
t++) {
if (node->parent->children[t] == node) {
node->parent->children[t] = generated_nodes[0];
break;
}
}
}
} else {
generated_nodes[i]->parent = generated_nodes[i - 1];
generated_nodes[i - 1]->children.push_back(
generated_nodes[i]);
}
}
if (generated_nodes.size() > 0) {
generated_nodes[generated_nodes.size() - 1]->children.push_back(
node);
node->parent = generated_nodes[generated_nodes.size() - 1];
}
return addIntroEdge(node->children[0], visited_edges);
}
} else if (strstr(node->type.c_str(), "Join")) {
return addIntroEdge(node->children[0], visited_edges) and
addIntroEdge(node->children[1], visited_edges);
} else if (strstr(node->type.c_str(), "ForgetVertex")) {
return addIntroEdge(node->children[0], visited_edges);
} else if (strstr(node->type.c_str(), "Leaf")) {
return true;
} else {
std::cout << "ERROR in TreeDecompositionPACE::addIntroEdgeRecursion, "
"node type is not satisfied"
<< std::endl;
exit(20);
}
}
bool TreeDecompositionPACE::colorNode(
std::shared_ptr<RawInstructiveTreeDecomposition> node,
std::vector<unsigned> &color_vertex, std::vector<unsigned> &vertex_color) {
if (!node->parent) {
// here is for root coloring
unsigned color = 1;
std::set<unsigned> elements = node->bag.get_elements();
for (auto it = elements.begin(); it != elements.end(); it++) {
vertex_color[*it - 1] = color;
color_vertex[color - 1] = *it;
node->color_to_vertex_map.insert(std::make_pair(color, *it));
color++;
}
} else {
std::set<unsigned> set_diff;
std::set<unsigned> elements_node = node->bag.get_elements();
std::set<unsigned> elements_node_parent =
node->parent->bag.get_elements();
set_difference(elements_node_parent.begin(), elements_node_parent.end(),
elements_node.begin(), elements_node.end(),
inserter(set_diff, set_diff.begin()));
node->color_to_vertex_map = node->parent->color_to_vertex_map;
for (auto it = set_diff.begin(); it != set_diff.end(); it++) {
color_vertex[vertex_color[*it - 1] - 1] = 0;
node->color_to_vertex_map.erase(vertex_color[*it - 1]);
}
set_diff.clear();
set_difference(elements_node.begin(), elements_node.end(),
elements_node_parent.begin(), elements_node_parent.end(),
inserter(set_diff, set_diff.begin()));
for (auto it = set_diff.begin(); it != set_diff.end(); it++) {
auto itr = find(color_vertex.begin(), color_vertex.end(), 0);
if (itr != color_vertex.end()) {
color_vertex[itr - color_vertex.begin()] = *it;
vertex_color[*it - 1] = itr - color_vertex.begin() + 1;
node->color_to_vertex_map.insert(
std::make_pair(itr - color_vertex.begin() + 1, *it));
} else {
std::cout << "ERROR in TreeDecompositionPACE::colorNode there "
"is no an available color!"
<< std::endl;
exit(20);
}
}
}
if (node->children.size() == 2) {
// Because tree decomposition is divided to two subtrees, we have to
// pass color vectors
std::vector<unsigned> color_vertex1 = color_vertex;
std::vector<unsigned> color_vertex2 = color_vertex;
std::vector<unsigned> vertex_color1 = vertex_color;
std::vector<unsigned> vertex_color2 = vertex_color;
colorNode(node->children[0], color_vertex1, vertex_color1);
colorNode(node->children[1], color_vertex2, vertex_color2);
} else if (node->children.size() == 1) {
colorNode(node->children[0], color_vertex, vertex_color);
}
return true;
}
bool TreeDecompositionPACE::colorTree() {
std::vector<unsigned> color_vertex;
std::vector<unsigned> vertex_color;
color_vertex.resize(width + 1, 0);
vertex_color.resize(multigraph->getVertices().size(), 0);
return colorNode(root, color_vertex, vertex_color);
}
bool TreeDecompositionPACE::updateInnerNodeTD(
std::shared_ptr<RawInstructiveTreeDecomposition> node, unsigned &number,
unsigned parentno) {
number++;
parentno = number;
bags.push_back(node->bag.get_elements());
num_vertices++;
num_edges = num_edges + node->children.size();
for (size_t i = 0; i < node->children.size(); i++) {
edges.insert(std::make_pair(parentno, number + 1));
updateInnerNodeTD(node->children[i], number, parentno);
}
return true;
}
bool TreeDecompositionPACE::updateTD() {
bags.clear();
edges.clear();
num_edges = 0;
num_vertices = 0;
unsigned number = 0;
unsigned parentno = 0;
updateInnerNodeTD(root, number, parentno);
return true;
}
void TreeDecompositionPACE::construct() {
constructRaw();
convertToBinary(root);
joinFormat(root);
addEmptyNodes(root);
addIntroVertex(root);
addForgetVertex(root);
std::set<unsigned> visited_edges;
addIntroEdge(root, visited_edges);
// for(auto item:visited_edges){std::cout<<item<<",";}std::cout<<std::endl;
colorTree();
updateTD();
validateTree(root);
std::cout << "Construction finished" << std::endl;
}
void TreeDecompositionPACE::createCTDNode(
std::shared_ptr<TermNode<ConcreteNode>> cnode,
std::shared_ptr<RawInstructiveTreeDecomposition> rnode) {
ConcreteNode concrete;
concrete.setSymbol(rnode->type);
Bag bag;
std::set<unsigned> bag_elements;
std::pair<unsigned, unsigned> e_new = std::make_pair(0, 0);
std::pair<unsigned, unsigned> e = rnode->bag.get_edge();
for (auto it = rnode->color_to_vertex_map.begin();
it != rnode->color_to_vertex_map.end(); it++) {
bag_elements.insert(it->first);
if (e.first == it->second) {
e_new.first = it->first;
} else if (e.second == it->second) {
e_new.second = it->first;
}
}
if (e_new.first > e_new.second) {
std::swap(e_new.first, e_new.second);
}
bag.set_elements(bag_elements);
bag.set_edge(e_new.first, e_new.second);
concrete.setBag(bag);
std::vector<std::shared_ptr<TermNode<ConcreteNode>>> children;
for (size_t i = 0; i < rnode->children.size(); i++) {
std::shared_ptr<TermNode<ConcreteNode>> ctdnode(
new TermNode<ConcreteNode>);
createCTDNode(ctdnode, rnode->children[i]);
children.push_back(ctdnode);
ctdnode->setParent(cnode);
}
cnode->setChildren(children);
if (strstr(rnode->type.c_str(), "IntroEdge_")) {
std::string type = "IntroEdge_" + std::to_string(e_new.first) + "_" +
std::to_string(e_new.second);
concrete.setSymbol(type);
} else if (strstr(rnode->type.c_str(), "IntroVertex_")) {
std::set<unsigned> set_diff;
std::set<unsigned> elements_node = concrete.getBag().get_elements();
std::set<unsigned> elements_node_child =
cnode->getChildren()[0]->getNodeContent().getBag().get_elements();
set_difference(elements_node.begin(), elements_node.end(),
elements_node_child.begin(), elements_node_child.end(),
inserter(set_diff, set_diff.begin()));
if (set_diff.size() != 1) {
std::cout << "ERROR in "
"TreeDecompositionPACE::createCTDNode(IntroVertex), "
"set_diff is not valid"
<< std::endl;
exit(20);
}
concrete.setSymbol("IntroVertex_" + std::to_string(*set_diff.begin()));
} else if (strstr(rnode->type.c_str(), "ForgetVertex_")) {
std::set<unsigned> set_diff;
std::set<unsigned> elements_node = concrete.getBag().get_elements();
std::set<unsigned> elements_node_child =
cnode->getChildren()[0]->getNodeContent().getBag().get_elements();
set_difference(elements_node_child.begin(), elements_node_child.end(),
elements_node.begin(), elements_node.end(),
inserter(set_diff, set_diff.begin()));
if (set_diff.size() != 1) {
std::cout << "ERORR in "
"TreeDecompositionPACE::createCTDNode(ForgetVertex), "
"set_diff is not valid"
<< std::endl;
exit(20);
}
concrete.setSymbol("ForgetVertex_" + std::to_string(*set_diff.begin()));
}
cnode->setNodeContent(concrete);
}
std::shared_ptr<ConcreteTreeDecomposition>
TreeDecompositionPACE::convertToConcreteTreeDecomposition() {
std::shared_ptr<ConcreteTreeDecomposition> concreteTreeDecomposition(
new ConcreteTreeDecomposition);
std::shared_ptr<TermNode<ConcreteNode>> ctd_root(
new TermNode<ConcreteNode>);
concreteTreeDecomposition->setRoot(ctd_root);
createCTDNode(ctd_root, root);
return concreteTreeDecomposition;
}
void TreeDecompositionPACE::setWidthType(const std::string &widthType) {
width_type = widthType;
}
unsigned int TreeDecompositionPACE::getWidth() const { return width; }
const std::string &TreeDecompositionPACE::getWidthType() const {
return width_type;
}
bool TreeDecompositionPACE::validateTree(
std::shared_ptr<RawInstructiveTreeDecomposition> node) {
if (node->children.size() == 2) {
if (node->type != "Join") {
std::cout
<< "Error in TreeDecompositionPACE::validateTree, join type"
<< std::endl;
exit(20);
}
if (node->children[0]->bag.get_elements() !=
node->children[1]->bag.get_elements()) {
std::cout << " Error in TreeDecompositionPACE::validateTree, "
"children of a join node do not have a same bagSet"
<< std::endl;
exit(20);
}
return validateTree(node->children[0]) and
validateTree(node->children[1]);
} else if (node->children.size() == 1) {
if (strstr(node->type.c_str(), "IntroVertex")) {
std::set<unsigned> set_diff;
std::set<unsigned> elements = node->bag.get_elements();
std::set<unsigned> childElements =
node->children[0]->bag.get_elements();
set_difference(elements.begin(), elements.end(),
childElements.begin(), childElements.end(),
inserter(set_diff, set_diff.begin()));
if (set_diff.size() != 1) {
std::cout << "Error in TreeDecompositionPACE::validateTree, "
"IntroVertex, set_diff is invalid"
<< std::endl;
exit(20);
}
} else if (strstr(node->type.c_str(), "ForgetVertex")) {
std::set<unsigned> set_diff;
std::set<unsigned> elements = node->bag.get_elements();
std::set<unsigned> childElements =
node->children[0]->bag.get_elements();
set_difference(childElements.begin(), childElements.end(),
elements.begin(), elements.end(),
inserter(set_diff, set_diff.begin()));
if (set_diff.size() != 1) {
std::cout << "Error in TreeDecompositionPACE::validateTree, "
"ForgetVertex, set_diff is invalid"
<< std::endl;
exit(20);
}
} else if (strstr(node->type.c_str(), "IntroEdge")) {
std::pair<unsigned, unsigned> e = std::make_pair(0, 0);
std::pair nodeEdge = node->bag.get_edge();
if (nodeEdge == e) {
std::cout << "Error in TreeDecompositionPACE::validateTree, "
"IntroEdge, nodeEdge is invalid"
<< std::endl;
exit(20);
}
} else {
std::cout << "Error in TreeDecompositionPACE::validateTree, node "
"type is invalid ("
<< node->type << ")" << std::endl;
exit(20);
}
return validateTree(node->children[0]);
} else if (node->children.size() == 0) {
if (strstr(node->type.c_str(), "Leaf")) {
if (!node->bag.get_elements().empty()) {
std::cout << "Error in TreeDecompositionPACE::validateTree, "
"Leaf is invalid"
<< std::endl;
exit(20);
}
} else {
std::cout << "Error in TreeDecompositionPACE::validateTree, node "
"type is invalid ("
<< node->type << ")" << std::endl;
exit(20);
}
return true;
} else {
std::cout << "Error in TreeDecompositionPACE::validateTree, node "
"children is invalid"
<< std::endl;
exit(20);
}
}
|
#include "CDrawing.h"
CDrawing::CDrawing(const SDrawingInfo& s)
{
V_PSM = CShaderManager::getInstance();
V_Array = V_PSM->M_GetPolygon(s.PolygonName);
V_Color = s.Global_Color;
V_Program = s.Program;
V_DrawMode = s.DrawMode;
V_LineColor = s.Line_Color;
}
void CDrawing::M_Draw(const glm::mat4& mat, T4Double color)
{
if (V_Array.aindex == -1) return; //dummy draw
glBindVertexArray(V_Array.aindex);
GLuint p = glGetUniformLocation(V_PSM->M_GetProgram() , "trans");
GLuint q = glGetUniformLocation(V_PSM->M_GetProgram(), "vicolor");
glUniformMatrix4fv(p, 1, GL_FALSE, &mat[0][0]);
float col[4];
for (int i = 0; i< 4; i++) col[i] = V_Color[i] * color[i];
glUniform4fv(q, 1, col);
if (V_DrawMode == 2) glDrawArrays(GL_TRIANGLE_STRIP, 0, V_Array.num);
else if (V_DrawMode == 1) glDrawArrays(GL_LINE_STRIP, 0, V_Array.num); //wireframe
else if (V_DrawMode == 3) // wireframe + color
{
glDrawArrays(GL_TRIANGLE_STRIP, 0, V_Array.num);
for (int i = 0; i < 4; i++) col[i] = V_LineColor[i];// *color[i];
glUniform4fv(q, 1, col);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // no fill
glDrawArrays(GL_TRIANGLE_STRIP, 0, V_Array.num);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // back to default
}
else if (V_DrawMode == 0)glDrawArrays(GL_POINTS, 0, V_Array.num);
else if (V_DrawMode == 4)glDrawArrays(GL_TRIANGLES, 0, V_Array.num);
else if (V_DrawMode == 5)
{
glDrawArrays(GL_TRIANGLES, 0, V_Array.num);
for (int i = 0; i < 4; i++) col[i] = V_LineColor[i];// *color[i];
glUniform4fv(q, 1, col);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // no fill
glDrawArrays(GL_TRIANGLES, 0, V_Array.num);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // back to default
}
else if (V_DrawMode == 6)
{
glDrawArrays(GL_LINES, 0, V_Array.num);
}
}
|
//
// SpriteFilterInkwell.h
// iPet
//
// Created by KimSteve on 2017. 5. 25..
// Copyright © 2017년 KimSteve. All rights reserved.
//
#ifndef SpriteFilterInkwell_h
#define SpriteFilterInkwell_h
#include <2d/CCSprite.h>
class SpriteFilterInkwell : public cocos2d::Sprite
{
public:
static SpriteFilterInkwell * createWithTexture(cocos2d::Texture2D * texture);
protected:
SpriteFilterInkwell();
virtual ~SpriteFilterInkwell();
virtual bool initWithTexture(cocos2d::Texture2D * texture) override;
protected:
virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) override;
virtual void onDraw(const cocos2d::Mat4& transform, uint32_t flags);
protected:
cocos2d::Texture2D * _ext;
private:
GLint _uniformAddedTexture;
cocos2d::CustomCommand _customCommand;
};
#endif /* SpriteFilterInkwell_h */
|
#include "SplashScene.h"
#include "cocos2d.h"
#include "MenuScene.h"
#include "SoundControl.h"
USING_NS_CC;
Scene* SplashScene::createScene(){
auto scene = Scene::create();
auto layer = SplashScene::create();
scene->addChild(layer);
return scene;
}
bool SplashScene::init(){
if(!Layer::init()){
return false;
}
SoundControl::getInstance();
auto node = CSLoader::createNode("SplashScene.csb");
addChild(node);
auto delay = DelayTime::create(1);
auto callfunc = CallFunc::create([](){
auto scene = MenuScene::createScene();
Director::getInstance()->replaceScene(scene);
});
//auto seq = Sequence::create(delay, callfunc, nullptr);
auto remove = RemoveSelf::create();
auto seq = Sequence::create(delay, remove, callfunc, nullptr);
runAction(seq);
return true;
}
|
#include <VirtualWire.h>
#include <Timer.h>
//Alive timer: once per 700 ms, the program checks for connection
Timer t;
boolean isAlive = true;
int dyingTimer;
//Pins for motor shield
int motor11;
int motor12;
int motor21;
int motor22;
void setup()
{
//Pins for motor shield
pinMode(motor11,OUTPUT);
pinMode(motor21,OUTPUT);
pinMode(motor12,OUTPUT);
pinMode(motor22,OUTPUT);
//Setup RC connection
Serial.begin(9600); // Configure the serial connection to the computer
vw_set_ptt_inverted(true); // Required by the RF module
vw_setup(2000); // bps connection speed
vw_set_rx_pin(3); // Arduino pin to connect the receiver data pin
vw_rx_start(); // Start the receiver
}
void loop()
{
//Needed for timer
t.update();
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
//Receive messages
if (vw_get_message(buf, &buflen)) // We check if we have received data
{
int i;
// Message with proper check
for (i = 0; i < buflen; i++)
{
uint8_t data = buf[i];
if(data == 128)
{
t.stop(dyingTimer);
isAlive = true;
dyingTimer = t.after(700,SetDead);
Serial.println("Connection is alive!");
}
else if(bitRead(data,0) == 1)
{
DriveForward();
}
else if(bitRead(data,1) == 1)
{
DriveBackward();
}
else if(bitRead(data,2) == 1)
{
DriveLeft();
}
else if(bitRead(data,3) == 1)
{
DriveRight();
}
else
{
StandStill();
}
}
}
//No connection: motor stops
if(isAlive == false)
{
Serial.println("Connection is Dead");
StandStill();
}
}
void SetDead()
{
isAlive = false;
}
void DriveForward()
{
Serial.println("Forward!");
}
void DriveBackward()
{
Serial.println("Backward");
}
void DriveLeft()
{
Serial.println("Left");
}
void DriveRight()
{
Serial.println("Right");
}
void StandStill()
{
Serial.println("Stand Still");
}
void Drive(int motorValue11,int motorValue12,int motorValue21, int motorValue22)
{
}
|
#ifndef CONTAINER_H
#define CONTAINER_H
/**
* A common wrapper interface for container-like data structures.
*
* @tparam U is the type of element in this container
*/
template<class U>
class Container {
public:
/**
* @return the pre-allocated capacity of this data structure if relevant, otherwise 0
*/
virtual unsigned capacity() const {
return 0;
}
virtual bool contains(U) const = 0;
virtual bool insert(U) = 0;
virtual bool remove(U) = 0;
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
vector<int> v;
int main(){
int t;
cin >> t;
while(t--){
int n,x;
cin >> n;
v.clear();
for(int i=0;i<n;i++){
cin >> x;
v.push_back(x);
}
sort(v.begin(),v.end());
long long ans=0;
for(int i=0;i<(n/2);i++)
ans+=(v[n-i-1]-v[i]);
cout << ans << endl;
}
return 0;
}
|
#include<iostream>
using namespace std;
int main()
{
int i,j,k,l,m;
string n;
cin>>n;
l=n.length();
if(n[0]!='-')
{
cout<<n<<endl;
}
else
{
if(n[l-1]-'0' >= n[l-2]-'0') { n.erase(n.begin()+(l-1)); if(n=="-0") cout<<n[1]<<endl; else cout<<n<<endl;}
else {n.erase(n.begin()+(l-2) ); if(n=="-0") cout<<n[1]<<endl; else cout<<n<<endl;}
}
return 0;
}
|
class Solution {
public:
int findNumbers(vector<int>& nums) {
int res = 0;
for (auto elem : nums) {
if (ndigits(elem) % 2 == 0) ++res;
}
return res;
}
int ndigits(int ival) {
int res = 0;
while (ival) {
ival /= 10;
++res;
}
return res;
}
};
|
#include<iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
void func() {
int a, b;
while (cin >> a >> b) {
int max = gcd(a, b);
int res = a / max * b;
cout << res << endl;
}
}
int main() {
func();
return 0;
}
|
#ifndef LSEDES_H
#define LSEDES_H
#include <iostream>
#include "sede.h"
using namespace std;
class Lsedes
{
private:
string lista_sedes[50];
int lista_tiempo[50];
int tamanio;
public:
Lsedes(Sede *sede[], int lenght);
void getListaSedes();
~Lsedes();
};
#endif // LSEDES_H
|
/* Copyright 2017-2018 All Rights Reserved.
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* [Contact]
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* 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 __SC_API_H__
#define __SC_API_H__
#include "Core.h"
#include "ServerAdapter.h"
#include "NMPolicy.h"
namespace sc {
typedef void (*StartCallback)(bool is_success);
void start_sc(StartCallback startCallback);
void start_sc(StartCallback startCallback, bool is_monitor, bool is_logging, bool is_append);
typedef void (*StopCallback)(bool is_success);
void stop_sc(StopCallback stopCallback);
void stop_sc(StopCallback stopCallback, bool is_monitor, bool is_logging);
void stop_monitoring(void);
void stop_logging(void);
inline void register_adapter(ServerAdapter *adapter) {
Core::singleton()->register_adapter(adapter);
}
inline int send(const void *dataBuffer, uint32_t dataLength) {
Core::singleton()->send(dataBuffer, dataLength, false);
}
inline int receive(void **dataBuffer) {
Core::singleton()->receive(dataBuffer, false);
}
void set_nm_policy(NMPolicy* nm_policy);
NMPolicy* get_nm_policy(void);
} /* namespace sc */
#endif /* !defined(__SC_API_H__) */
|
//Switch statements
//Author: Dalton Hook
//Date:4/19/2018
#include <iostream>
#include <string>
int main()
{
int bookScanID = 0;
std::string bookOwner;
std::cout << "Book ID Number pleae enter here" <<
std::endl;
std::cin >> bookScanID;
switch (bookScanID)
{
case 1:
level1();
break;
bookOwner = "Dalton";
break;
case 277346:
bookOwner = "Brosuis";
break;
case 277343:
bookOwner = "Aaron";
break;
case 277362:
bookOwner = "Shawn";
break;
case 277357:
bookOwner = "KaNe";
break;
default:
bookOwner = "Ivalid";
break;
}
if (bookOwner == "Invalid")
{
std::cout << "Invalid";
}
else std::cout << bookOwner << std::endl;
std::cout << bookOwner;
system("pause");
return 0;
}
|
/*Tile Class
Contains data and logic for an individual tile*/
#ifndef TILE_H
#define TILE_H
#include "rectangle.h"
#include "globals.h"
struct SDL_Texture;
class Graphics;
class Tile {
public:
Tile();
Tile(SDL_Texture* tileset, Vector2 size, Vector2 tilesetPosition, Vector2 position);
void update(int elapsedTime);
void draw(Graphics &graphics);
void setX(float x) { _position.x = x; };
void setY(float y) { _position.y = y; };
float getX() { return _position.x; };
float getY() { return _position.y; };
protected:
/*Size - Dimensions of tile*/
Vector2 _size;
/*TilesetPosition - Position in tileset that the tile comes from*/
Vector2 _tilesetPosition;
/*Position - Position on the map that the tile is on*/
Vector2 _position;
/*Tileset - Texture/image that the tile is taken from*/
SDL_Texture* _tileset;
private:
};
#endif
|
// ControlDemo.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "windows.h"
#include "commdlg.h"
#include "DUILib.h"
#include "DUIPopupWindow.h"
#include "DUIDebug.h"
#include "DUIControls.h"
#include "DUIResLoader.h"
#include "DUISkinMgr.h"
#include "DUIDibProcess.h"
#include "Python.h"
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#include <stdlib.h>
#include <sstream>
#include<Shlobj.h>
#pragma comment(lib,"Shell32.lib")
using namespace std;
DUI_USING_NAMESPACE
#define BUFSIZE 4096
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hInputFile = NULL;
void CreateChildProcess(void);
void WriteToPipe(void);
void ReadFromPipe(void);
void ErrorExit(PTSTR);
static OPENFILENAME ofn, ofn2;
PROCESS_INFORMATION piProcInfo;
CRefPtr<CImageList> Image[15];
DWORD ID[15];
double rate[15];
int mode,times;
CDUIString choose, title, choose_path, save;
BOOL start = false, have = false, havepath = false;
void PopFileInitialize(HWND hwnd)
{
static TCHAR szFilter[] = TEXT("所有图片文件\0*.bmp;*.dib;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.tif;*.tiff;*.png;*.ico\0") \
TEXT("位图文件(*.bmp;*.dib)\0*.bmp;*.dib\0") \
TEXT("JPEG(*.jpg;*.jpeg;*jpe;*.jfif)\0*.jpg;*.jpeg;*.jpe;*.jfif\0") \
TEXT("GIF(*.gif)\0*.gif\0") \
TEXT("TIFF(*.tif;*.tiff)\0*.tif;*.tiff\0") \
TEXT("PNG(*.png)\0*.png\0") \
TEXT("ICO(*.ico)\0*.ico\0") \
TEXT("所有文件\0*.*\0");
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = hwnd;
ofn.hInstance = NULL;
ofn.lpstrFilter = szFilter;
ofn.lpstrCustomFilter = NULL;
ofn.nMaxCustFilter = 0;
ofn.nFilterIndex = 0;
ofn.lpstrFile = NULL; // Set in Open and Close functions
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFileTitle = NULL; // Set in Open and Close functions
ofn.nMaxFileTitle = MAX_PATH;
ofn.lpstrInitialDir = NULL;
ofn.lpstrTitle = NULL;
ofn.Flags = 0; // Set in Open and Close functions
ofn.nFileOffset = 0;
ofn.nFileExtension = 0;
ofn.lpstrDefExt = TEXT("*.bmp;*.dib;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.tif;*.tiff;*.png;*.ico");
ofn.lCustData = 0L;
ofn.lpfnHook = NULL;
ofn.lpTemplateName = NULL;
static TCHAR szFilter2[] = TEXT("XML文件(*.xml)\0*.xml\0") \
TEXT("所有文件\0*.*\0");
ofn2.lStructSize = sizeof(OPENFILENAME);
ofn2.hwndOwner = hwnd;
ofn2.hInstance = NULL;
ofn2.lpstrFilter = szFilter2;
ofn2.lpstrCustomFilter = NULL;
ofn2.nMaxCustFilter = 0;
ofn2.nFilterIndex = 0;
ofn2.lpstrFile = NULL; // Set in Open and Close functions
ofn2.nMaxFile = MAX_PATH;
ofn2.lpstrFileTitle = NULL; // Set in Open and Close functions
ofn2.nMaxFileTitle = MAX_PATH;
ofn2.lpstrInitialDir = NULL;
ofn2.lpstrTitle = NULL;
ofn2.Flags = 0; // Set in Open and Close functions
ofn2.nFileOffset = 0;
ofn2.nFileExtension = 0;
ofn2.lpstrDefExt = TEXT("*.bmp;*.dib;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.tif;*.tiff;*.png;*.ico");
ofn2.lCustData = 0L;
ofn2.lpfnHook = NULL;
ofn2.lpTemplateName = NULL;
}
BOOL PopFileOpenDlg(HWND hwnd, PTSTR pstrFileName, PTSTR pstrTitleName)
{
ofn.hwndOwner = hwnd;
ofn.lpstrFile = pstrFileName;
ofn.lpstrFileTitle = pstrTitleName;
ofn.Flags = OFN_HIDEREADONLY | OFN_CREATEPROMPT | OFN_EXPLORER | OFN_FILEMUSTEXIST;
return GetOpenFileName(&ofn);
}
BOOL PopFileSaveDlg(HWND hwnd, PTSTR pstrFileName, PTSTR pstrTitleName)
{
ofn2.hwndOwner = hwnd;
ofn2.lpstrFile = pstrFileName;
ofn2.lpstrFileTitle = pstrTitleName;
ofn2.Flags = OFN_HIDEREADONLY | OFN_CREATEPROMPT | OFN_EXPLORER;
return GetSaveFileName(&ofn2);
}
BOOL PopFolderOpenDlg(PTSTR pstrFolderName)
{
BROWSEINFO bi = { 0 };
bi.hwndOwner = NULL;//拥有着窗口句柄,为NULL表示对话框是非模态的,实际应用中一般都要有这个句柄
bi.pszDisplayName = pstrFolderName;//接收文件夹的缓冲区
bi.lpszTitle = TEXT("选择一个文件夹");//标题
bi.ulFlags = BIF_NEWDIALOGSTYLE;
LPITEMIDLIST idl = SHBrowseForFolder(&bi);
return SHGetPathFromIDList(idl, pstrFolderName);
}
void ErrorExit(PTSTR lpszFunction)
// Format a readable error message, display a message box,
// and exit from the application.
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
0, NULL);
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(1);
}
class CMainWnd : public CDUIPopupWindow
{
typedef CDUIPopupWindow theBase;
BEGIN_MSG_MAP(CMainWnd)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_TIMER, OnTimer)
CHAIN_MSG_MAP(theBase)
END_MSG_MAP()
CDUIPopupWindow m_winTest;
LRESULT OnDestroy(UINT, WPARAM, LPARAM, BOOL& bHandled)
{
bHandled = FALSE;
if (m_winTest.IsWindow())
{
m_winTest.UnregisterNotifyHandler(this);
m_winTest.DestroyWindow();
}
PostQuitMessage(0);
return S_OK;
}
LRESULT OnCreate(UINT, WPARAM, LPARAM, BOOL& bHandled)
{
bHandled = FALSE;
ResetSkin();
memset(Image, 0, sizeof(Image));
return S_OK;
}
LRESULT OnTimer(UINT, WPARAM, LPARAM, BOOL& bHandled)
{
DWORD ExitCode;
ReadFromPipe();
if (start) {
if (GetExitCodeProcess(piProcInfo.hProcess, &ExitCode))
{
DUI::CTrace::TraceInfo(_T("Exit code = %d/n"), ExitCode);
}
else
{
DUI::CTrace::TraceInfo(_T("GetExitCodeProcess() failed: %ld/n"), GetLastError());
}
times++;
if (ExitCode != STILL_ACTIVE) {
//OutputEvent("Consumed ");
if (mode == 1) {
CDUIString temp = _T("result_JPG\\");
temp.append(title.substr(0, title.find(_T("."))));
CResLoader mResLoad;
mResLoad.ToAbsolutePath(temp);
int nLen = temp.length();
char buf[1024];
memset(buf, 0, sizeof(buf));
WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)temp.c_str(), temp.length(), (LPSTR)buf, 1024, NULL, NULL);
string str(buf);
if (access(str.c_str(), 0) == 0) {
//清空列表
IDUIControl* pControl = GetControlByName(_T("tile_layouQQ"));
if (pControl != NULL)
{
IDUITileLayout* pTilteLayout = (IDUITileLayout*)pControl->GetInterface(ITileLayout);
pControl = GetControlByName(_T("choose_list"));
IDUIListBox* pListBox = (IDUIListBox*)pControl->GetInterface(IListBox);
if (pListBox->GetControlCount() > 1) {
for (int i = 0; i < 14; i++) {
pListBox->RemoveControlAt(1);
pTilteLayout->RemoveControlAt(1);
}
}
pListBox->SetCurSel(-1);
if (pTilteLayout != NULL && pTilteLayout->GetControlCount() > 0 && pListBox != NULL && pListBox->GetControlCount() > 0)
{
CResLoader mResLoad;
long hFile = 0;
struct _finddata_t fileinfo;
string p;//字符串,存放路径
string newpath = p.assign(str).append("\\*.*").c_str();
wstring resfile[15];
int now = 0;
BOOL first = true, first2 = true;
if ((hFile = _findfirst(p.assign(str).append("\\*.*").c_str(), &fileinfo)) != -1)//若查找成功,则进入
{
do
{
//如果是目录,迭代之(即文件夹内还有文件夹)
if ((fileinfo.attrib & _A_SUBDIR))
{
}
else {
newpath = p.assign(str).append("\\").append(fileinfo.name);
int nLen = (int)newpath.length();
wchar_t buf[1024];
memset(buf, 0, sizeof(buf));
int nResult = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)newpath.c_str(), nLen, (LPWSTR)buf, 1024);
wstring wstr(buf);
DUI::CTrace::TraceInfo(_T("the file is %s\n"), wstr.c_str());
char *ptr;
resfile[(int)strtod(fileinfo.name, &ptr) - 1] = wstr;
}
} while (_findnext(hFile, &fileinfo) == 0);
//_findclose函数结束查找
_findclose(hFile);
}
IDUIRichEdit* pEventEdit = NULL;
IDUIControl* pControl = GetControlByName(_T("control_event_edit"));
if (pControl != NULL) pEventEdit = (IDUIRichEdit*)pControl->GetInterface(IRichEdit);
wstring data = pEventEdit->GetText();
for (int i = 0; i < 15; i++)
{
Image[i] = mResLoad.LoadImageFromFile(resfile[i]);
CRefPtr<IDUIControl> pNewControl;
IDUIPictureBox* pPictureBox;
if (!first) {
pNewControl = pTilteLayout->GetControlByIndex(0)->Clone();
pPictureBox = (IDUIPictureBox*)pNewControl->GetInterface(IPictureBox);
pTilteLayout->AddControl(pNewControl);
}
else {
pNewControl = pTilteLayout->GetControlByIndex(0);
pPictureBox = (IDUIPictureBox*)pNewControl->GetInterface(IPictureBox);
first = false;
}
pPictureBox->SetImage(Image[i]);
pPictureBox->SetDrawMode(PICTURE_BOX_STRETCH_IMAGE);
pTilteLayout->SetColumnCount(15);
DeleteFile(resfile[i].c_str());
IDUIIconTextItem* pIconText;
if (!first2) {
pNewControl = pListBox->GetControlByIndex(0)->Clone();
pIconText = (IDUIIconTextItem*)pNewControl->GetInterface(IListIconTextItem);
pListBox->AddControl(pNewControl);
}
else {
pNewControl = pListBox->GetControlByIndex(0);
pIconText = (IDUIIconTextItem*)pNewControl->GetInterface(IListIconTextItem);
first2 = false;
}
pIconText->SetIcon(Image[i]);
wchar_t buf[5];
_itow(i + 1, buf, 10);
pIconText->SetText(wstring(_T("候选图片")).append(wstring(buf)).c_str());
wstring now = data.substr(data.find(wstring(_T("Top ")).append(buf)), 42);
wchar_t *end;
ID[i] = wcstod(now.substr(now.find(wstring(_T("# ID: "))) + 6, 6).c_str(), &end);
rate[i] = wcstof(now.substr(now.find(wstring(_T("matching rate: "))) + 15, 7).c_str(), &end);
}
int ret = RemoveDirectory(temp.c_str());
start = false;
}
}
}
}
else if (mode == 2) {
CDUIString temp = _T("result_XML\\");
CResLoader mResLoad;
mResLoad.ToAbsolutePath(temp);
int nLen = temp.length();
char buf[1024];
memset(buf, 0, sizeof(buf));
WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)temp.c_str(), temp.length(), (LPSTR)buf, 1024, NULL, NULL);
string str(buf);
if (access(str.c_str(), 0) == 0) {
//清空列表
CResLoader mResLoad;
long hFile = 0;
struct _finddata_t fileinfo;
string p;//字符串,存放路径
string newpath = p.assign(str).append("\\*.*").c_str();
wstring resfile[15];
int now = 0;
BOOL first = true, first2 = true;
if ((hFile = _findfirst(p.assign(str).append("\\*.*").c_str(), &fileinfo)) != -1)//若查找成功,则进入
{
do
{
//如果是目录,迭代之(即文件夹内还有文件夹)
if ((fileinfo.attrib & _A_SUBDIR))
{
}
else if (string(fileinfo.name).compare("result.xml") == 0) {
start = false;
newpath = p.assign(str).append("\\").append(fileinfo.name);
int nLen = (int)newpath.length();
wchar_t buf[1024];
memset(buf, 0, sizeof(buf));
int nResult = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)newpath.c_str(), nLen, (LPWSTR)buf, 1024);
wstring wstr(buf);
DUI::CTrace::TraceInfo(_T("the file is %s\n"), wstr.c_str());
HANDLE hInputFile = CreateFile(
wstr.c_str(),
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if (hInputFile == INVALID_HANDLE_VALUE)
ErrorExit(TEXT("CreateFile"));
DWORD dwRead, dwWritten, dwTotalBytesAvail;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
memset(chBuf, 0, sizeof(chBuf));
while (ReadFile(hInputFile, chBuf, BUFSIZE, &dwRead, NULL))
{
if (dwRead <= 0)
break;
wchar_t buf[BUFSIZE];
memset(buf, 0, sizeof(buf));
int nResult = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)chBuf, dwRead, (LPWSTR)buf, BUFSIZE);
wstring wstr(buf);
IDUIRichEdit* pEventEdit = NULL;
IDUIControl* pControl = GetControlByName(_T("export_edit"));
if (pControl != NULL) pEventEdit = (IDUIRichEdit*)pControl->GetInterface(IRichEdit);
pEventEdit->AppendText(wstr.c_str());
if (str.length() == 0) break;
memset(chBuf, 0, sizeof(chBuf));
}
CloseHandle(hInputFile);
DeleteFile(wstr.c_str());
}
} while (_findnext(hFile, &fileinfo) == 0);
//_findclose函数结束查找
_findclose(hFile);
}
}
}
}
}
return S_OK;
}
void CreateChildProcess(int choice)
// Create a child process that uses the previously created pipes for STDIN and STDOUT.
{
CDUIString szCmdline = _T("python ");
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE;
CResLoader mResLoad;
CDUIString path, Current;
CDUIString temp = _T("");
mResLoad.ToAbsolutePath(temp);
Current = temp;
if (choice == 1)
{
temp = _T("test_single.py");
//mResLoad.ToAbsolutePath(temp);
path = szCmdline.append(temp);
path = path.append(_T(" --pic_path \""));
path.append(choose);
path.append(_T("\""));
mode = 1;
}
else if (choice == 2)
{
temp = _T("test_multiple.py ");
//mResLoad.ToAbsolutePath(temp);
path = szCmdline.append(temp);
path = path.append(_T(" --query_dir \""));
path.append(choose_path);
path.append(_T("\""));
mode = 2;
}
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = g_hChildStd_OUT_Wr;
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.hStdInput = g_hChildStd_IN_Rd;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
// Create the child process.
bSuccess = CreateProcess(NULL,
(LPWSTR)path.c_str(), // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_NO_WINDOW, // creation flags
NULL, // use parent's environment
Current.c_str(), // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
// If an error occurs, exit the application.
if (!bSuccess)
ErrorExit(TEXT("CreateProcess"));
else
{
// Close handles to the child process and its primary thread.
// Some applications might keep these handles to monitor the status
// of the child process, for example.
//CloseHandle(piProcInfo.hProcess);
//CloseHandle(piProcInfo.hThread);
}
}
void WriteToPipe(void)
// Read from a file and write its contents to the pipe for the child's STDIN.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
for (;;)
{
bSuccess = ReadFile(g_hInputFile, chBuf, BUFSIZE, &dwRead, NULL);
if (!bSuccess || dwRead == 0) break;
bSuccess = WriteFile(g_hChildStd_IN_Wr, chBuf, dwRead, &dwWritten, NULL);
if (!bSuccess) break;
}
// Close the pipe handle so the child process stops reading.
if (!CloseHandle(g_hChildStd_IN_Wr))
ErrorExit(TEXT("StdInWr CloseHandle"));
}
void ReadFromPipe(void)
// Read output from the child process's pipe for STDOUT
// and write to the parent process's pipe for STDOUT.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten, dwTotalBytesAvail, dwRealRead;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
Sleep(200);
while (PeekNamedPipe(g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRealRead, &dwTotalBytesAvail, NULL))
{
if (dwRealRead <= 0)
break;
memset(chBuf, 0, sizeof(chBuf));
bSuccess = ReadFile(g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if (!bSuccess || dwRead == 0) break;
/*bSuccess = WriteFile(hParentStdOut, chBuf,
dwRead, &dwWritten, NULL);
if (!bSuccess) break;*/
string str(chBuf);
std::wstring wstr(str.length(), L' ');
std::copy(str.begin(), str.end(), wstr.begin());
OutputEvent(wstr);
if (str.length() == 0) break;
}
}
VOID OnDUINotify(const DUINotify& info, BOOL& bHandled)
{
CheckSystemNotification(info, bHandled);
//DebugEvent(info);
if (m_winTest.IsWindow()
&& info.hWndManager == m_winTest.m_hWnd)
{
if (info.dwMsgType == WM_NOTIFY_BUTTON_CLICKED)
{
CDUIString strName = info.pSender->GetName();
if (strName.compare(_T("change_skin")) == 0)
{
ResetSkin();
}
}
return;
}
if (info.dwMsgType == WM_NOTIFY_BUTTON_CLICKED)
{
CDUIString strName = info.pSender->GetName();
if (strName.compare(_T("open")) == 0)
{
wchar_t FileName[128], TitleName[50];
memset(FileName, 0, sizeof(FileName));
memset(TitleName, 0, sizeof(TitleName));
if (PopFileOpenDlg(0, FileName, TitleName)) {
choose = FileName;
title = TitleName;
CResLoader mResLoad;
CRefPtr<CImageList> Image = mResLoad.LoadImageFromFile(FileName);
CRefPtr<IDUIControl> pControl = GetControlByName(_T("select"));
IDUIPictureBox* pPictureBox = (IDUIPictureBox*)pControl->GetInterface(IPictureBox);
pPictureBox->SetImage(Image);
pPictureBox->SetDrawMode(PICTURE_BOX_STRETCH_IMAGE);
have = true;
}
}
else if (strName.compare(_T("search")) == 0) {
if (start) return;
if (!have) return;
IDUIRichEdit* pEventEdit = NULL;
IDUIControl* pControl = GetControlByName(_T("control_event_edit"));
if (pControl != NULL) pEventEdit = (IDUIRichEdit*)pControl->GetInterface(IRichEdit);
pEventEdit->SetText(_T(""));
SECURITY_ATTRIBUTES saAttr;
printf("\n->Start of parent execution.\n");
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0))
ErrorExit(TEXT("StdoutRd CreatePipe"));
if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0))
ErrorExit(TEXT("Stdout SetHandleInformation"));
if (!CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
ErrorExit(TEXT("Stdin CreatePipe"));
if (!SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0))
ErrorExit(TEXT("Stdin SetHandleInformation"));
CreateChildProcess(1);
CResLoader mResLoad;
CDUIString temp = _T("inout.txt");
mResLoad.ToAbsolutePath(temp);
g_hInputFile = CreateFile(
temp.c_str(),
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if (g_hInputFile == INVALID_HANDLE_VALUE)
ErrorExit(TEXT("CreateFile"));
WriteToPipe();
OutputEvent(_T("\n->Searching for the similiar picture...\n\n"));
ReadFromPipe();
CloseHandle(g_hInputFile);
start = true; times = 0;
}
else if (strName.compare(_T("open_path")) == 0)
{
wchar_t PathName[256];
memset(PathName, 0, sizeof(PathName));
if (PopFolderOpenDlg(PathName)) {
choose_path = PathName;
CResLoader mResLoad;
CRefPtr<IDUIControl> pControl = GetControlByName(_T("path"));
IDUILabel* pLabel = (IDUILabel*)pControl->GetInterface(ILabel);
pLabel->SetText(wstring(_T("路径:")).append(choose_path));
havepath = true;
}
}
else if (strName.compare(_T("export")) == 0)
{
if (start) return;
if (!havepath) return;
SECURITY_ATTRIBUTES saAttr;
printf("\n->Start of parent execution.\n");
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0))
ErrorExit(TEXT("StdoutRd CreatePipe"));
if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0))
ErrorExit(TEXT("Stdout SetHandleInformation"));
if (!CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
ErrorExit(TEXT("Stdin CreatePipe"));
if (!SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0))
ErrorExit(TEXT("Stdin SetHandleInformation"));
CreateChildProcess(2);
CResLoader mResLoad;
CDUIString temp = _T("inout.txt");
mResLoad.ToAbsolutePath(temp);
g_hInputFile = CreateFile(
temp.c_str(),
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if (g_hInputFile == INVALID_HANDLE_VALUE)
ErrorExit(TEXT("CreateFile"));
WriteToPipe();
OutputEvent(_T("\n->Searching for the similiar picture...\n\n"));
ReadFromPipe();
CloseHandle(g_hInputFile);
start = true; times = 0;
}
else if (strName.compare(_T("save")) == 0)
{
wchar_t FileName[128], TitleName[50];
memset(FileName, 0, sizeof(FileName));
memset(TitleName, 0, sizeof(TitleName));
if (PopFileSaveDlg(0, FileName, TitleName)) {
save = FileName;
have = true;
HANDLE hOutputFile = CreateFile(
save.c_str(),
GENERIC_WRITE,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hOutputFile == INVALID_HANDLE_VALUE)
ErrorExit(TEXT("CreateFile"));
IDUIRichEdit* pEventEdit = NULL;
IDUIControl* pControl = GetControlByName(_T("export_edit"));
DWORD dwWritten;
BOOL bSuccess;
if (pControl != NULL) pEventEdit = (IDUIRichEdit*)pControl->GetInterface(IRichEdit);
wstring data = pEventEdit->GetText();
bSuccess = WriteFile(hOutputFile, data.c_str(), data.length(), &dwWritten, NULL);
CloseHandle(hOutputFile);
}
}
else if (strName.compare(_T("start")) == 0)
{
StartProgress();
}
else if (strName.compare(_T("add_listitem")) == 0)
{
AddListItem();
}
else if (strName.compare(_T("file_button")) == 0)
{
ShowMenu(info.pSender, _T("menu_file"));
}
else if (strName.compare(_T("click_me_button")) == 0)
{
ShowMenu(info.pSender, _T("menu_click_me"));
}
else if (strName.compare(_T("radio1")) == 0
|| strName.compare(_T("radio2")) == 0)
{
ClickRadioButton(info.pSender);
}
else if (strName.compare(_T("test_popup")) == 0)
{
ShowTestWindow();
}
else if (strName.compare(_T("add_treeitem")) == 0)
{
}
}
else if (info.dwMsgType == WM_NOTIFY_TRACK_POS_CHANGED)
{
SetTrackBarTooltip(info);
}
else if (info.dwMsgType == WM_NOTIFY_LISTBOX_NOTIFY)
{
IDUIControl* pControl = GetControlByName(_T("selected"));
if (pControl == NULL) return;
IDUIControl* pControl2 = GetControlByName(_T("choose_list"));
if (pControl2 == NULL) return;
IDUIControl* pControl3 = GetControlByName(_T("rate"));
if (pControl3 == NULL) return;
IDUIControl* pControl4 = GetControlByName(_T("number"));
if (pControl4 == NULL) return;
IDUIPictureBox* pPicBox = (IDUIPictureBox*)pControl->GetInterface(IPictureBox);
if (pPicBox == NULL) return;
IDUIListBox* pListBox = (IDUIListBox*)pControl2->GetInterface(IListBox);
if (pListBox == NULL) return;
IDUILabel* pLabel = (IDUILabel*)pControl3->GetInterface(ILabel);
if (pLabel == NULL) return;
IDUILabel* pLabel2 = (IDUILabel*)pControl4->GetInterface(ILabel);
if (pLabel2 == NULL) return;
INT i = pListBox->GetCurSel();
if (i >= 0 && !Image[i].IsNull()) {
pPicBox->SetImage(Image[i]);
pPicBox->SetDrawMode(PICTURE_BOX_STRETCH_IMAGE);
pPicBox->UpdateLayout();
wchar_t buf[25];
swprintf(buf, _T("%.2f%%"), rate[i]);
pLabel->SetText(wstring(buf));
swprintf(buf, _T("编号:%d"), ID[i]);
pLabel2->SetText(wstring(buf));
}
}
if (!bHandled)
{
theBase::OnDUINotify(info, bHandled);
}
}
VOID CheckSystemNotification(const DUINotify& info, BOOL& bHandled)
{
IDUIControl* pControl = info.pSender;
switch (info.dwMsgType)
{
case WM_NOTIFY_BUTTON_CLICKED:
if (pControl != NULL)
{
const CDUIString& strName = pControl->GetName();
if (strName.compare(DUI_SYS_MIN_BTN) == 0)
{
if (GetStyle()&WS_SYSMENU)
{
PostMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0);
}
else
{
ShowWindow(SW_MINIMIZE);
}
bHandled = TRUE;
}
else if (strName.compare(DUI_SYS_MAX_BTN) == 0)
{
if (GetStyle()&WS_SYSMENU)
PostMessage(WM_SYSCOMMAND, SC_MAXIMIZE, 0);
else
ShowWindow(SW_MAXIMIZE);
bHandled = TRUE;
}
else if (strName.compare(DUI_SYS_RESTORE_BTN) == 0)
{
if (GetStyle()&WS_SYSMENU)
PostMessage(WM_SYSCOMMAND, SC_RESTORE, 0);
else
ShowWindow(SW_RESTORE);
bHandled = TRUE;
}
else if (strName.compare(DUI_SYS_CLOSE_BTN) == 0)
{
if (GetStyle()&WS_SYSMENU)
PostMessage(WM_SYSCOMMAND, SC_CLOSE, 0);
else
PostMessage(WM_CLOSE, 0, 0);
bHandled = TRUE;
}
}
break;
default:
break;
}
}
VOID OutputEvent(const CDUIString& strText)
{
IDUIRichEdit* pEventEdit = NULL;
IDUIControl* pControl = GetControlByName(_T("control_event_edit"));
if (pControl != NULL) pEventEdit = (IDUIRichEdit*)pControl->GetInterface(IRichEdit);
if (pEventEdit == NULL) return;
pEventEdit->AppendText(strText.c_str());
}
VOID ResetSkin()
{
IDUIApp* pDUIApp = DUIGetAppInstance();
IDUISkinMgr* pSkinMgr = pDUIApp->GetSkinMgr();
static BOOL bRet = TRUE;
CRefPtr<CDUIFrameBK> pFrameBK = NULL;
if (bRet)
{
pFrameBK = pSkinMgr->GetFrameBK(_T("skin2_bk"));
}
else
{
pFrameBK = pSkinMgr->GetFrameBK(_T("skin1_bk"));
}
bRet = !bRet;
pSkinMgr->SetSkinUIData(pFrameBK);
}
virtual VOID OnBeforeFlipDIB(CDibSection* pDIB)
{
if (!IsNcActivate())
{
CGrayScaleImageFilter::Process(pDIB);
}
}
VOID StartProgress()
{
IDUIControl* pControl1 = GetControlByName(_T("progressbar1"));
IDUIControl* pControl2 = GetControlByName(_T("progressbar2"));
if (pControl1 == NULL || pControl2 == NULL) return;
IDUIProgressBar* pProgressbar1 = (IDUIProgressBar*)pControl1->GetInterface(IProgressBar);
if (pProgressbar1 == NULL) return;
IDUIProgressBar* pProgressbar2 = (IDUIProgressBar*)pControl2->GetInterface(IProgressBar);
if (pProgressbar2 == NULL) return;
INT nMin1, nMax1;
pProgressbar1->GetRange(nMin1, nMax1);
pProgressbar1->SetPos(nMin1);
INT nMin2, nMax2;
pProgressbar2->GetRange(nMin2, nMax2);
pProgressbar2->SetPos(nMin2);
while (pProgressbar1->GetPos() < nMax1
|| pProgressbar2->GetPos() < nMax2)
{
pProgressbar1->OffsetPos(50);
pProgressbar2->OffsetPos(100);
UpdateWindow();
Sleep(200);
}
}
VOID ClickRadioButton(IDUIControl* pControl)
{
IDUIControl* pRadio1 = GetControlByName(_T("radio1"));
IDUIControl* pRadio2 = GetControlByName(_T("radio2"));
IDUIControl* pUnCheck = NULL;
if (pControl == pRadio1)
{
pUnCheck = pRadio2;
}
else if (pControl == pRadio2)
{
pUnCheck = pRadio1;
}
//only one radio button can be checked at the same time
if (pUnCheck != NULL)
{
IDUIButton* pRadioUnCheck = (IDUIButton*)pUnCheck->GetInterface(IButton);
if (pRadioUnCheck != NULL)
{
pRadioUnCheck->SetCheck(FALSE);
}
}
}
VOID ShowMenu(IDUIControl* pControl, const CDUIString& strMenuName)
{
CRefPtr<IDUIMenu> pMemu = CDUIMenu::CreateFromResource(strMenuName);
if (!pMemu.IsNull())
{
RECT rtClient;
GetClientRect(&rtClient);
::ClientToScreen(m_hWnd, (LPPOINT)&rtClient);
::ClientToScreen(m_hWnd, ((LPPOINT)&rtClient + 1));
RECT rtControl = pControl->GetControlRect();
INT nX = rtClient.left + rtControl.left;
INT nY = rtClient.top + rtControl.bottom;
CRefPtr<IDUIMenuItem> pMenuItem = pMemu->TrackPopupMenu(pControl, nX, nY);
}
}
VOID SetTrackBarTooltip(const DUINotify& info)
{
IDUITrackBar* pTrackBar = (IDUITrackBar*)info.pSender->GetInterface(ITrackBar);
if (pTrackBar != NULL)
{
IDUIButton* pThumbBtn = pTrackBar->GetThumbButton();
if (pThumbBtn != NULL)
{
INT nPos = pTrackBar->GetPos();
wstringstream ws;
ws << L"current position:" << nPos;
pThumbBtn->SetTooltip(ws.str());
}
}
}
VOID ShowTestWindow()
{
if (!m_winTest.IsWindow())
{
m_winTest.SetUseSkinBK(TRUE);
RECT rtParent;
GetWindowRect(&rtParent);
RECT rtTest;
rtTest.left = rtParent.left + 100;
rtTest.top = rtParent.top + 100;
rtTest.right = rtTest.left + 400;
rtTest.bottom = rtTest.top + 400;
m_winTest.CreateFromResource(_T("popup_win"), NULL, rtTest, NULL
, WS_VISIBLE | WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,/* WS_EX_TOPMOST |*/ WS_EX_TOOLWINDOW);
m_winTest.RegisterNotifyHandler(this);
}
else
{
::SetActiveWindow(m_winTest.m_hWnd);
}
}
VOID AddListItem()
{
IDUIControl* pControl = GetControlByName(_T("test_list"));
if (pControl == NULL) return;
IDUIListBox* pList = (IDUIListBox*)pControl->GetInterface(IListBox);
if (pList == NULL) return;
INT nCount = pList->GetControlCount();
IDUIControl* pItemCopy = NULL;
INT nCopyIndex(0);
if (nCount > 0)
{
for (INT i = 0; i < nCount; ++i)
{
IDUIListItem* pItem = (IDUIListItem*)(pList->GetControlByIndex(i)->GetInterface(IListItem));
if (pItem != NULL
&& !pItem->GetGroup()
&& pItem->IsVisible()
&& !pItem->GetExpand())
{
pItemCopy = pItem;
nCopyIndex = i;
break;
}
}
}
if (pItemCopy != NULL)
{
LockLayout(TRUE);
const INT nCopyCount = 1000;
CDUIString strText = pItemCopy->GetText();
wstringstream ws;
for (INT i = 0; i < nCopyCount; ++i)
{
CRefPtr<IDUIControl> pControl = pItemCopy->Clone();
pList->AddControlAt(nCopyIndex, pControl);
ws.str(L"");
ws << strText << i;
pControl->SetText(ws.str());
}
LockLayout(FALSE);
LayoutRootControl();
Invalidate();
}
}
};
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
IDUIApp* pDUIApp = DUIGetAppInstance();
if (pDUIApp == NULL) return -1;
CResLoader loader;
CDUIString strXMLEntry;
loader.LoadXMLFromFile(_T(".\\res\\xml\\dui_control_demo.xml"), strXMLEntry);
//pDUIApp->Init(strXMLEntry);
BOOL bRet = pDUIApp->Init(strXMLEntry);//载入XML文件初始化皮肤部分
DUI_ASSERT(bRet);
if (!bRet) return -1;
PopFileInitialize(0);
IDUISkinMgr* pSkinMgr = pDUIApp->GetSkinMgr();
IDUIControlFactory* pControlFactory = pDUIApp->GetControlFactory();
CDUIString strTitle;
pSkinMgr->GetStringText(_T("ids_title"), strTitle);//查询XML文件中关键字为ids_title的部分获取窗口标题
CMainWnd main;
RECT rtMain = { 100, 100, 700, 700 };
main.CreateFromResource(_T("main_wnd"), NULL, rtMain, strTitle.c_str()
, WS_VISIBLE | WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
SetTimer(main, 1, 20, NULL);
//main.RegisterNotifyHandler(&main);
pDUIApp->GetMessageLoop()->Run();
pDUIApp->Term();
return 0;
}
|
class IProgess
{
public:
virtual void DoProgress(float value) = 0;
~IProgess();
};
class FileSplitter
{
public:
FileSplitter(const string& filePath,int fileNumber):m_filePath(filePath),m_fileNumber(fileNumber)
{
}
~FileSplitter();
void addIProgress(IProgess* iprogress) //订阅者自主决定是否订阅此通知
{
m_iprogressList.add(iprogress);
}
void removeIProgress(IProgess* iprogress)
{
m_iprogressList.remove(iprogress);
}
void split()
{
//1、读取大文件
//2、分批次向小文件写入
for(int i = 0; i < m_fileNumber; i++)
{
//...
float progessValue = m_fileNumber;
progessValue = (i+1)/progessValue
onProgress(progessValue);// 更新进度条
}
}
protected:
void onProgress(float value)
{
List<IProgess*>::Iterator itor = m_iprogressList.begin();//向list里的每一个订阅者进行通知
while(itor != m_iprogressList.end())
{
m_iprogress->DoProgress(value);
itor++;
}
}
private:
string m_filePath;
int m_fileNumber;
// ProgressBar *m_progessBar;//分割进度条 扮演了一个通知者的角色
//IProgess* m_iprogress; //抽象的通知机制
List<IProgess*> m_iprogressList;//抽象的通知机制,支持多个观察者
};
|
#pragma once
#include"Shader.hpp"
#include "texture_2d.hpp"
#include "sprite.hpp"
#include "../GameEngine/game.hpp"
#include "billboard.hpp"
#include "mouse_effect.hpp"
#include "text.hpp"
#include<vector>
#include<glm/gtc/matrix_transform.hpp>
#include<glm/gtc/type_ptr.hpp>
#include<SFML/System/Vector2.hpp>
#include"particle_emitter.hpp"
#include "post_processor.hpp"
#define NUM_LIGHTS 10 + 1 // pixie in back
struct lua_State;
class Shader;
class Texture2D;
class Sprite;
class Camera;
struct PointLights
{
//bool status; //On or off
glm::vec3 positions[NUM_LIGHTS];
glm::vec4 colors[NUM_LIGHTS];
};
class GraphicsSystem
{
private:
Camera* camera;
lua_State* luaState;
std::vector<int> tileMap;
std::vector<bool> visibleTiles; // For shadows
std::vector<Texture2D> tileTextures;
std::vector<Sprite> tiles;
std::vector<Sprite> backgrounds;
//Sprite background;
int numLights = 1;
ParticleEmitter* laserEffect;
Billboard* billboards;
MouseEffect* mouseEffect;
PostProcessor* postProcessor;
ShaderStruct& shaders;
std::vector<Texture2D> textures;
std::vector<Sprite> sprites;
PointLights lights;
bool drawLaser;
//Text stuff:
sf::Clock textClock;
Text* currentLevel;
Text* highscore;
public:
GraphicsSystem(ShaderStruct& shad);
~GraphicsSystem();
void draw(
float deltaTime, const glm::mat4& view,
const glm::mat4& projection, int level, float scores[], int numScores);
void drawLevelText(const glm::mat4& projection, int level);
void addCamera(Camera* cam);
void update(float deltaTime);
void addLuaFunctions(lua_State* luaState);
sf::Vector2f getPlayerPos() const;
sf::Vector2f getPixie() const;
void setHighscore(float* highscoreText, int index);
private:
void drawSprites(const glm::mat4& view, const glm::mat4& projection);
void drawTiles(const glm::mat4& view, const glm::mat4& projection);
void displayHighscore(const glm::mat4& projection, float scores[], int numScores);
void updateCamera();
static int loadTileMap(lua_State* luaState);
static int reloadTile(lua_State* luaState);
static int newtexture(lua_State* luaState);
static int settexture(lua_State* luaState);
static int newsprite(lua_State* luaState);
static int newLight(lua_State* luaState);
static int spritesize(lua_State* luaState);
static int spritepos(lua_State* luaState);
static int setspriterect(lua_State* luaState);
static int newtiletexture(lua_State* luaState);
static int clearTileMap(lua_State* luaState);
static int newbackground(lua_State* luaState);
static int backgroundpos(lua_State* luaState);
static int laseron(lua_State* luaState);
static int laseroff(lua_State* luaState);
static int flashon(lua_State* luaState);
static int flashoff(lua_State* luaState);
static int shakeon(lua_State* luaState);
static int shakeoff(lua_State* luaState);
static int lowhealthon(lua_State* luaState);
static int lowhealthoff(lua_State* luaState);
};
|
#include "music.h"
music::music(void)
{
Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096);
}
music::~music(void)
{
}
void music::Play()
{
melody = Mix_LoadMUS( "music.flac" ); //muzika
Mix_PlayMusic(melody, -1);
}
void music::SFX()
{
hit = Mix_LoadWAV("hit.flac"); //atsimusimo garsas
Mix_PlayChannel( -1, hit, 0 );
}
|
#pragma once
#include "app.h"
class misc_data {
public:
misc_data(u8* memory_pointer);
~misc_data();
private:
};
|
//
// GA-SDK-CPP
// Copyright 2018 GameAnalytics C++ SDK. All rights reserved.
//
#pragma once
#if !USE_UWP && !USE_TIZEN
#include <exception>
#include <string>
#include <signal.h>
namespace gameanalytics
{
namespace errorreporter
{
class GAUncaughtExceptionHandler
{
public:
static void setUncaughtExceptionHandlers();
private:
#if defined(_WIN32)
static void signalHandler(int sig);
#else
static void signalHandler(int sig, siginfo_t *info, void *context);
static const std::string format(const std::string& format, ...);
#endif
static void setupUncaughtSignals();
static void terminateHandler();
static std::terminate_handler previousTerminateHandler;
static int errorCount;
static int MAX_ERROR_TYPE_COUNT;
};
}
}
#endif
|
#include <iostream>
using namespace std;
int substr(char arr[],char str[]){
int si=0, ai=0;
bool found;
while(arr[ai] != '\0'){
//cout << "-------";
if(str[si] == arr[ai] && arr[ai-1]== ' '){
found=true;
int index=ai;
while(str[si] != '\0'){
if(str[si] != arr[ai]){found=false; ai++;break;}
else{si++;}
ai++;
}
if(found) return index;
//else{ai++;}
}
ai++;
}
return -1;
}
void removeDuplicateWords(char arr[]){
char duplicate[500]="\0";
int di=0;//dupliate index
int ai=0; // array index
char word[20];
int wi=0; // word index
while(arr[ai] != '\0'){
//------------------------pick a word
if(arr[ai] != ' ' && arr[ai] != '.') {word[wi]=arr[ai]; wi++;}
else{
//word has completed
word[wi]= '\0';
//------------------------ word pick end
wi=0;
// search word in duplicate array
// if not there, then insert
int exist=substr(duplicate,word);
if(exist == -1){
//insert word into duplicate array
while(word[wi] != '\0'){
duplicate[di]=word[wi];
di++;
wi++;
}
// insert space after
duplicate[di++]=' ';
}
wi=0;
}
ai++;
}
duplicate[di]='\0';
//copy into previous array
for(int i=0; i<=di; i++) arr[i]=duplicate[i];
}
int main(){
char str[50]="this is is is is str.";
removeDuplicateWords(str);
cout << str;
}
|
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
template <class T>
void quick_sort(T b, T e)
{
if (b == e)
return;
auto l = b, r = e - 1;
cout << "!:" << *l << " " << *r << endl;
while (l < r)
{
cout << *l << " " << *r << endl;
while (*r > *b)
r--;
while (*l <= *b && l < r)
l++;
std::swap(*l, *r);
}
std::swap(*b, *l);
quick_sort(b, l);
quick_sort(l + 1, e);
}
int main()
{
vector<int> v{10, 5, 8, 3, 1};
quick_sort(v.begin(), v.end());
for (auto x : v)
{
cout << x << endl;
}
}
|
#include <cstdio>
#include <iostream>
#include <math.h>
#include <algorithm>
using namespace std;
long long int status[1000000];
void siv()
{
long long int N=1000000,i,j;
long long int sq=sqrt(N);
for(i=4; i<=N; i+=2) status[i]=1;
for(i=3; i<=sq; i+=2)
{
if(status[i]==0)
{
for(j=i*i; j<=N; j+=i) status[j]=1;
}
}
status[1]=1;
status[0]=1;
}
int main()
{
long long int n,i,j,ck;
siv();
while(scanf("%lld",&n)!=EOF)
{
if(n==0)
break;
long long int m=n/2;
ck=0;
if(n<=3)
printf("%lld:\nNO WAY!\n",n);
else if(n%2!=0 && status[n-2]==0)
printf("%lld:\n2+%lld\n",n,n-2);
else if(n%2!=0 && status[n-2]!=0)
printf("%lld:\nNO WAY!\n",n);
else
{
for(i=2; i<=m; i++)
{
ck=1;
if(status[i]==0 && status[n-i]==0)
{
printf("%lld:\n%lld+%lld\n",n,i,n-i);
break;
}
}
if(ck==0)
printf("%lld:\nNO WAY!\n",n);
}
}
return 0;
}
|
// https://www.acwing.com/problem/content/102/
// acwing增减序列
#include <bits/stdc++.h>
using namespace std;
#define cin ios::sync_with_stdio(false); cin // cin 优化加速
#define N 110000
typedef long long ll;
ll n, m, i, j, p, q, a[N];
int main() {
freopen("note.txt", "r", stdin);
freopen("ans.txt", "w", stdout);
cin >> n;
for (i = 1; i <= n; ++ i) {
cin >> a[i];
}
for (i = 2; i <= n; ++ i) {
ll c = a[i] - a[i - 1];
if (c > 0) {
p += c;
} else {
q -= c;
}
}
// min(p, q) + abs(p - q) = max(p, q)
ll ans1 = max(p, q), ans2 = abs(p - q) + 1;
cout << ans1 << endl << ans2;
return 0;
}
|
// BRice & CHubbell
//=================================================================
// Declare Global Variables & Header Files
//=================================================================
// Including Arduino's I2C library, as well as the ultrasonic,
// motorshield, and LCD libraries.
#include <Wire.h>
#include <NewPing.h>
#include <Adafruit_MotorShield.h>
#include <LiquidCrystal.h>
// Constants are defined for the physical elements connecting to the Arduino
const int PUSH_BUTTONS = A0;
const int HEAT_SENSOR = A1;
const int LIGHT_SENSOR = A2;
const int LEFT_SENSOR = 8;
const int FRONT_SENSOR = 9;
const int RIGHT_SENSOR = 10;
const int SPEAKER = 11;
const int LEFT_LIMIT = 12;
const int RIGHT_LIMIT = 13;
// Constants used numerically in the algorithm
const int MAX_DISTANCE = 1000;
const int AMOUNT_OF_PULSES = 12;
// declare states
int INPUT_STATE = 1;
int MAZE_STATE = 2;
int ERROR_STATE = 3;
int HOUSE_STATE = 4;
int LIGHT_STATE = 5;
int RHOUSE_STATE = 6;
int RMAZE_STATE = 7;
int VICTORY_STATE = 8;
// declare variables
int _currentState;
int frontReading = 0;
int rightReading = 0;
int leftReading = 0;
int buttonVal = 0;
int heatVal = 0;
int lightVal = 0;
int Lsensor = 0;
int Tsensor = 0;
int LSpeed = 132;
int RSpeed = 120;
int location;
int currentDistance;
int left;
int right;
boolean button1;
boolean button2;
boolean button3;
boolean button4;
boolean Lwall;
boolean Fwall;
boolean Rwall;
boolean headedHome = false;
int movesSoFar = 0;
const int numOfMoves = 20;
int moves[numOfMoves];
unsigned long refreshTime = 0;
unsigned long stateTime = 0;
// Create the motor shield object with the default I2C address
Adafruit_MotorShield motorShield = Adafruit_MotorShield();
// Select which 'port' for each motor.
Adafruit_DCMotor *leftMotor = motorShield.getMotor(3);
Adafruit_DCMotor *rightMotor = motorShield.getMotor(4);
// Create an object for each ultrasonic sensor to be used
NewPing sonarFront = NewPing(FRONT_SENSOR, FRONT_SENSOR, MAX_DISTANCE);
NewPing sonarLeft = NewPing(LEFT_SENSOR, LEFT_SENSOR, MAX_DISTANCE);
NewPing sonarRight = NewPing(RIGHT_SENSOR, RIGHT_SENSOR, MAX_DISTANCE);
// Initialize the LCD with the numbers of the interface pins
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
void setup()
{
// Make noise
analogWrite(SPEAKER, 20);
// vary the light and temp parameters based on the sensor
while(millis() < 3000)
{
lightVal = analogRead(LIGHT_SENSOR);
heatVal = analogRead(HEAT_SENSOR);
// asigns relative to room light
if(lightVal > Lsensor)
{
Lsensor = lightVal;
}
// assigns relative to rooms temperature
if(heatVal > Tsensor)
Tsensor = heatVal;
}
// The motor shield and the serial monitor are initialized
motorShield.begin();
Serial.begin(9600);
// Motors started.
leftMotor->run(RELEASE);
rightMotor->run(RELEASE);
// set up the number of columns and rows on the LCD
lcd.begin(16, 2);
// fill the array
for (int i = 0; i <numOfMoves; i++)
{
moves[i] = 0;
}
// quits noise
analogWrite(SPEAKER, 0);
// go to first state
_currentState = INPUT_STATE;
}
// the loop routine runs over and over again forever:
void loop()
{
// Every quarter second clear the LCD and print to the serial monitor.
if ((millis() - refreshTime > 250))
{
refreshTime = millis();
// Prints the current state to the serial monitor. States are printed
// to the screen for troubleshooting.
//Serial.println(currentState);
// Clears the LCD screen.
lcd.clear();
}
while (_currentState == INPUT_STATE)
{
// show state
lcd.setCursor(0, 0);
lcd.print("Input:");
// read buttons
while(button4 == false && button3 == false && button2 == false && button1 == false)
{
// re read
buttonVal = analogRead(PUSH_BUTTONS);
Serial.println(buttonVal);
if (buttonVal >= 1020)
{
button4 = true;
}
else if (buttonVal >= 960 && buttonVal <= 1010)
{
button3 = true;
}
else if (buttonVal >= 500 && buttonVal <= 920)
{
button2 = true;
}
else if (buttonVal >= 9 && buttonVal <= 20)
{
button1 = true;
}
}
if(button1 == true)
{
moves[movesSoFar] = 1;
movesSoFar ++;
}
else if(button2 == true)
{
moves[movesSoFar] = 2;
movesSoFar ++;
}
else if(button3 == true)
{
moves[movesSoFar] = 3;
movesSoFar ++;
}
else if(button4 == true)
{
_currentState = MAZE_STATE;
}
// show moves
lcd.setCursor(0, 1);
lcd.print(moves[movesSoFar - 1]);
if (movesSoFar > 1)
{
lcd.setCursor(8, 1);
lcd.print(moves[movesSoFar - 2]);
}
while(button4 == true || button3 == true || button2 == true || button1 == true)
{
// re read
buttonVal = analogRead(PUSH_BUTTONS);
// debounce
if (buttonVal <= 0)
{
button4 = false;
button3 = false;
button2 = false;
button1 = false;
}
}
// error check
if (movesSoFar == numOfMoves)
{
// show error
lcd.setCursor(0, 1);
lcd.print("Out of room");
}
}
while (_currentState == MAZE_STATE)
{
// make variables
int i = 1;
boolean hot;
// show state
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Maze Time");
while(i < movesSoFar && Fwall == false)
{
// show moves
lcd.setCursor(0, 1);
lcd.print(moves[i]);
if (moves[i] == 3)
{
Serial.println("Went Left");
goLeft();
}
else if (moves[i] == 2)
{
Serial.println("Went Straight");
goStraight(24);
}
else if (moves[i] == 1)
{
Serial.println("Went Right");
goRight();
}
Fwall = senseFWall();
// incrament
i++;
}
lcd.clear();
lcd.setCursor(0, 1);
lcd.print("Searching...");
// see if its hot
hot = isHeat();
Fwall = senseFWall();
// hit a wall?
if (Fwall == true)
{
// Show error message
lcd.setCursor(0, 1);
lcd.print("Uh oh, WALL!");
//sound
analogWrite(SPEAKER, 160);
// jump out of exicution
_currentState = ERROR_STATE;
}
// if there is heat, you know you made it
if (Fwall == false && i <= movesSoFar + 1 && hot == true)
{
_currentState = HOUSE_STATE;
}
// maybe it just needs to move forward more?
else
{
// try going forward
while (Fwall == false && hot == false)
{
Fwall = senseFWall();
hot = isHeat();
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->run(FORWARD);
rightMotor->setSpeed(RSpeed);
delay(400);
leftMotor->run(FORWARD);
leftMotor->setSpeed(0);
rightMotor->run(FORWARD);
rightMotor->setSpeed(0);
delay(100);
}
// found it!
if (hot == true)
{
_currentState = HOUSE_STATE;
}
// default to wall following
if (Fwall == true)
{
// Show error message
lcd.setCursor(0, 1);
lcd.print("Uh oh, WALLS!");
Serial.println("Wall");
leftMotor->run(BACKWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->run(BACKWARD);
rightMotor->setSpeed(RSpeed);
delay(170);
leftMotor->run(FORWARD);
leftMotor->setSpeed(0);
rightMotor->run(FORWARD);
rightMotor->setSpeed(0);
//sound?
analogWrite(SPEAKER, 160);
// jump out of exicution
_currentState = ERROR_STATE;
}
}
}
while (_currentState == ERROR_STATE)
{
// default to wall following
// show state
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Following");
// create local variables
int left = 0;
int right = 0;
int x = 1;
// figure out where you are
for (int i = 1; i <= movesSoFar; i++)
{
if (moves[i] == 1)
{
while (moves[x] != 3 && x <= movesSoFar)
{
right ++;
Serial.println(right);
Serial.print("right");
x ++;
i ++;
}
i ++;
}
else if (moves[i] == 3)
{
while (moves[x] != 1 && x <= movesSoFar)
{
left ++;
Serial.println(left);
Serial.print("left");
x ++;
i ++;
}
i ++;
}
//incrament x
x ++;
}
analogWrite(SPEAKER, 0);
// am I left or right?
if (left > right)
{
followL();
}
else
{
followR();
}
}
while (_currentState == HOUSE_STATE)
{
// show state
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("In the house");
// now follow a wall?
if (moves[0] == 1)
{
followR();
}
else if (moves[0] == 3)
{
followL();
}
else
{
followR();
}
}
while (_currentState == LIGHT_STATE)
{
// show found
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Lego attached");
// make noise
foundItSound();
// make sure you get it attached
for (int i = 0; i <= 40; i++)
{
leftMotor->run(FORWARD);
leftMotor->setSpeed(160);
rightMotor->run(FORWARD);
rightMotor->setSpeed(160);
}
for (int i = 0; i <= 40; i++)
{
leftMotor->run(BACKWARD);
leftMotor->setSpeed(160);
rightMotor->run(BACKWARD);
rightMotor->setSpeed(160);
}
for (int i = 0; i <= 40; i++)
{
leftMotor->run(FORWARD);
leftMotor->setSpeed(160);
rightMotor->run(FORWARD);
rightMotor->setSpeed(160);
}
// stop noise
analogWrite(SPEAKER, 0);
_currentState = RHOUSE_STATE;
}
while (_currentState == RHOUSE_STATE)
{
// show state
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Leaving now");
// trigger memory
headedHome = true;
// now follow the wall back out
if (moves[0] == 1)
{
// Turn a 180
goRight();
goRight();
// leave
followL();
}
else if (moves[0] == 3)
{
// Turn a 180
goLeft();
goLeft();
// leave
followR();
}
}
while (_currentState == RMAZE_STATE)
{
// show state
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Maze...Again?!");
// make variable
int i = movesSoFar;
// go ahead and move back through it
while(i > 0 && Fwall == false)
{
// show moves
lcd.setCursor(0, 1);
lcd.print(moves[i]);
if (moves[i] == 1)
{
goLeft();
}
else if (moves[i] == 2)
{
goStraight(24);
}
else if (moves[i] == 3)
{
goRight();
}
Fwall = senseFWall();
// decrament
i--;
}
if (Fwall == true)
{
// Show error message
lcd.setCursor(0, 1);
lcd.print("Uh oh, WALLS!");
Serial.println("Wall");
//sound
analogWrite(SPEAKER, 160);
// jump out of exicution
_currentState = ERROR_STATE;
}
if (i <= 1)
{
_currentState = VICTORY_STATE;
}
}
if (_currentState == VICTORY_STATE)
{
// show state
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("YAY!!");
//sound
analogWrite(SPEAKER, 10);
// spin
goLeft();
goLeft();
goLeft();
goLeft();
//sound off
analogWrite(SPEAKER, 0);
}
}
///////////////////////////////////////////////////
// Functions!
///////////////////////////////////////////////////
void followR()
{
// variables
int fWallDistance;
int lWallDistance;
int rWallDistance;
int sides;
int error = 0;
boolean heat;
boolean light;
// show state
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Following R");
// check for heat and light
heat = isHeat();
light = isLight();
// spin so it actually sees the wall
goLeft();
//make decision
while (heat == false && light == false)
{
// recheck all
// ping and do conversion
// Values are returned in integer values of 1 inch increments.
fWallDistance = sonarFront.convert_in(sonarFront.ping_median(AMOUNT_OF_PULSES));
rWallDistance = sonarRight.convert_in(sonarRight.ping_median(AMOUNT_OF_PULSES));
lWallDistance = sonarLeft.convert_in(sonarLeft.ping_median(AMOUNT_OF_PULSES));
// error check
if(fWallDistance == 0)
{
lcd.setCursor(8, 1);
lcd.print("F = 0");
error ++;
}
else if(error >= 4)
{
// move the motors a bit
for (int i = 0; i <= 100; i++)
{
leftMotor->run(BACKWARD);
leftMotor->setSpeed(180);
rightMotor->run(BACKWARD);
rightMotor->setSpeed(180);
}
leftMotor->setSpeed(0);
rightMotor->setSpeed(0);
}
// do math
sides = rWallDistance + lWallDistance;
// check for heat and light
heat = isHeat();
light = isLight();
//if can go Right, do such
if(rWallDistance >= 12 && error < 4)
{
// show state
lcd.clear();
lcd.setCursor(0, 1);
lcd.print("Right ");
// reset error
error = 0;
// move
goRight();
goStraight(20);
// stay like that until you can do something different
while(rWallDistance <= 7 && rWallDistance >= 4 && fWallDistance >= 7)
{
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->run(FORWARD);
rightMotor->setSpeed(RSpeed);
delay(30);
leftMotor->run(FORWARD);
leftMotor->setSpeed(0);
rightMotor->run(FORWARD);
rightMotor->setSpeed(0);
delay(500);
rWallDistance = sonarRight.convert_in(sonarRight.ping_median(AMOUNT_OF_PULSES));
fWallDistance = sonarFront.convert_in(sonarFront.ping_median(AMOUNT_OF_PULSES));
lcd.setCursor(0, 1);
lcd.print("Straight");
}
}
// just need to veer right?
else if(rWallDistance < 12 && rWallDistance >= 5 && fWallDistance >= 6)
{
// show state
lcd.setCursor(0, 1);
lcd.print("Veer R");
// move the motors a bit
for (int i = 0; i <= 80; i++)
{
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->run(FORWARD);
rightMotor->setSpeed(RSpeed - 5); // 8);
}
leftMotor->setSpeed(0);
rightMotor->setSpeed(0);
}
// just need to veer left?
else if(rWallDistance <= 5 && rWallDistance >= 1 && fWallDistance >= 6)
{
// show state
lcd.setCursor(0, 1);
lcd.print("Veer L");
// move the motors a bit
for (int i = 0; i <= 80; i++)
{
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed - 15); // 60);
rightMotor->run(FORWARD);
rightMotor->setSpeed(RSpeed);
}
leftMotor->setSpeed(0);
rightMotor->setSpeed(0);
}
// are you out of the maze?
else if(sides >= 50)
{
// get me outa here
_currentState = VICTORY_STATE;
heat = true;
}
// last resort, go left
else
{
// show state
lcd.setCursor(0, 1);
lcd.print("Left ");
goLeft();
goStraight(20);
// stay like that until you can do something different
while(lWallDistance <= 6 && lWallDistance >= 2 && fWallDistance >= 6)
{
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->run(FORWARD);
rightMotor->setSpeed(RSpeed);
delay(30);
leftMotor->run(FORWARD);
leftMotor->setSpeed(0);
rightMotor->run(FORWARD);
rightMotor->setSpeed(0);
delay(500);
lWallDistance = sonarLeft.convert_in(sonarLeft.ping_median(AMOUNT_OF_PULSES));
fWallDistance = sonarFront.convert_in(sonarFront.ping_median(AMOUNT_OF_PULSES));
}
}
}
// if you find heat, your in the house
if (heat == true)
{
// figure out if coming or going
if (headedHome == false)
{
_currentState = HOUSE_STATE;
}
else if (_currentState = VICTORY_STATE)
{
_currentState = VICTORY_STATE;
}
else
{
_currentState = RMAZE_STATE;
}
}
// if you find light, your on the lego
if (light == true)
{
_currentState = LIGHT_STATE;
}
}
void followL()
{
// variables
int fWallDistance;
int lWallDistance;
int rWallDistance;
int sides;
int error = 0;
boolean heat;
boolean light;
// show state
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Following L");
// check for heat and light
heat = isHeat();
light = isLight();
// spin so it actually sees the wall
goRight();
//make decision
while (heat == false && light == false)
{
// recheck all
// ping and do conversion
// Values are returned in integer values of 1 inch increments.
fWallDistance = sonarFront.convert_in(sonarFront.ping_median(AMOUNT_OF_PULSES));
rWallDistance = sonarRight.convert_in(sonarRight.ping_median(AMOUNT_OF_PULSES));
lWallDistance = sonarLeft.convert_in(sonarLeft.ping_median(AMOUNT_OF_PULSES));
lcd.setCursor(8, 1);
lcd.print(" ");
// error check
if(fWallDistance == 0)
{
lcd.setCursor(8, 1);
lcd.print("F = 0");
error ++;
}
else if(error >= 4)
{
// move the motors a bit
for (int i = 0; i <= 100; i++)
{
leftMotor->run(BACKWARD);
leftMotor->setSpeed(180);
rightMotor->run(BACKWARD);
rightMotor->setSpeed(180);
}
leftMotor->setSpeed(0);
rightMotor->setSpeed(0);
}
// do math
sides = rWallDistance + lWallDistance;
// check for heat and light
heat = isHeat();
light = isLight();
//if can go Left, do such
if(lWallDistance >= 12 && error < 4)
{
// show state
lcd.setCursor(0, 1);
lcd.print("Left ");
// reset error
error = 0;
// move
goLeft();
goStraight(20);
// stay like that until you can do something different
while(lWallDistance <= 7 && lWallDistance >= 4 && fWallDistance >= 7)
{
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->run(FORWARD);
rightMotor->setSpeed(RSpeed);
delay(30);
leftMotor->run(FORWARD);
leftMotor->setSpeed(0);
rightMotor->run(FORWARD);
rightMotor->setSpeed(0);
delay(500);
lWallDistance = sonarLeft.convert_in(sonarLeft.ping_median(AMOUNT_OF_PULSES));
fWallDistance = sonarFront.convert_in(sonarFront.ping_median(AMOUNT_OF_PULSES));
lcd.setCursor(0, 1);
lcd.print("Straight");
}
}
// just need to veer left?
else if(lWallDistance < 12 && lWallDistance >= 5 && fWallDistance >= 6)
{
// show state
lcd.setCursor(0, 1);
lcd.print("Veer L");
// move the motors a bit
for (int i = 0; i <= 80; i++)
{
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed - 15);
rightMotor->run(FORWARD);
rightMotor->setSpeed(RSpeed);
}
leftMotor->setSpeed(0);
rightMotor->setSpeed(0);
}
// just need to veer right?
else if(lWallDistance <= 5 && lWallDistance >= 1 && fWallDistance >= 6)
{
// show state
lcd.setCursor(0, 1);
lcd.print("Veer R");
// move the motors a bit
for (int i = 0; i <= 80; i++)
{
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->run(FORWARD);
rightMotor->setSpeed(RSpeed - 5);
}
leftMotor->setSpeed(0);
rightMotor->setSpeed(0);
}
// are you out of the maze?
else if(sides >= 50)
{
// get me out of here
_currentState = VICTORY_STATE;
heat = true;
}
// last resort, go right
else
{
// show state
lcd.setCursor(0, 1);
lcd.print("Right ");
goRight();
goStraight(20);
// stay like that until you can do something different
while(lWallDistance <= 6 && lWallDistance >= 2 && fWallDistance >= 6)
{
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->run(FORWARD);
rightMotor->setSpeed(RSpeed);
delay(30);
leftMotor->run(FORWARD);
leftMotor->setSpeed(0);
rightMotor->run(FORWARD);
rightMotor->setSpeed(0);
delay(500);
rWallDistance = sonarRight.convert_in(sonarRight.ping_median(AMOUNT_OF_PULSES));
fWallDistance = sonarFront.convert_in(sonarFront.ping_median(AMOUNT_OF_PULSES));
}
}
}
// if you find heat, your in the house
if (heat == true)
{
// figure out if coming or going
if (headedHome == false)
{
_currentState = HOUSE_STATE;
}
else if (_currentState = VICTORY_STATE)
{
_currentState = VICTORY_STATE;
}
else
{
_currentState = RMAZE_STATE;
}
}
// if you find light, your on the lego
if (light == true)
{
_currentState = LIGHT_STATE;
}
}
// Drives straight the sent in distance
void goStraight(int distance)
{
// get the wall distance
int pings = 12;
int wallDistance = sonarFront.convert_in(sonarFront.ping_median(pings));
int rWallDistanceInitial = (sonarRight.convert_in(sonarRight.ping_median(AMOUNT_OF_PULSES)))/ 24;
int lWallDistanceInitial = (sonarLeft.convert_in(sonarLeft.ping_median(AMOUNT_OF_PULSES)) )/ 24;
int rWallDistance = (sonarRight.convert_in(sonarRight.ping_median(AMOUNT_OF_PULSES)))/ 24;
int lWallDistance = (sonarLeft.convert_in(sonarLeft.ping_median(AMOUNT_OF_PULSES)))/ 24;
Serial.print(wallDistance);
int finalDistance = wallDistance - distance;
// if it wont hit
// get them moving
rightMotor->run(FORWARD);
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->setSpeed(RSpeed);
currentDistance = wallDistance;
Fwall = senseFWall();
// while ((rWallDistance == rWallDistanceInitial) && (lWallDistance == lWallDistanceInitial) && rWallDistance != 0 && lWallDistance != 0) // runs until you are "distance" (input value) closer to the wall than you started
// {
while ((rWallDistance == rWallDistanceInitial) && (lWallDistance == lWallDistanceInitial) && Fwall == false) // runs until you are "distance" (input value) closer to the wall than you started
{
// currentDistance = sonarFront.convert_in(sonarFront.ping_median(pings));
Fwall = senseFWall();
rWallDistance = (sonarRight.convert_in(sonarRight.ping_median(AMOUNT_OF_PULSES))) / 24;
lWallDistance = (sonarLeft.convert_in(sonarLeft.ping_median(AMOUNT_OF_PULSES))) / 24;
lcd.setCursor(0, 0);
lcd.print("Go forward");
lcd.setCursor(8, 1);
lcd.print(currentDistance);
}
for(int i = 0; i <= 65; i++)
{
leftMotor->setSpeed(LSpeed);
rightMotor->setSpeed(RSpeed);
}
rightMotor->setSpeed(0);
leftMotor->setSpeed(0);
wallDistance = sonarFront.convert_in(sonarFront.ping_median(pings));
if ( wallDistance <= 2)
{
for(int i = 0; i <= 60; i++)
{
rightMotor->run(BACKWARD);
leftMotor->run(BACKWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->setSpeed(RSpeed);
}
rightMotor->setSpeed(0);
leftMotor->setSpeed(0);
rightMotor->run(FORWARD);
leftMotor->run(FORWARD);
}
// // otherwise it hit a wall
// else
// {
// lcd.setCursor(0, 1);
// lcd.print("Failure");
//// goStraight(distance/2);
// leftMotor->setSpeed(0);
// rightMotor->setSpeed(0);
// }
}
// turns 90 degrees right
void goRight()
{
// move
rightMotor->run(BACKWARD);
leftMotor->run(FORWARD);
leftMotor->setSpeed(LSpeed);
rightMotor->setSpeed(0);
// Run for a while
for (int i = 0; i <= 190; i++)
{
lcd.setCursor(0,1);
lcd.print ("Turn Right");
}
//
leftMotor->setSpeed(0);
rightMotor->setSpeed(0);
}
// Turns 90 degrees left
void goLeft()
{
// move
rightMotor->run(FORWARD);
leftMotor->run(BACKWARD);
leftMotor->setSpeed(0);
rightMotor->setSpeed(RSpeed);
// Run for a while
for (int i = 0; i <= 225; i++)
{
lcd.setCursor(0,1);
lcd.print ("Turn Left");
}
leftMotor->setSpeed(0);
rightMotor->setSpeed(0);
}
boolean senseLWall()
{
///////////////////////////////NOTE: When sonar reads 5, light sensor = 9 inches from wall.
// declare variables
int wallDistance;
int hit = 12;
boolean wall = false;
// ping and do conversion
// Values are returned in integer values of 1 inch increments.
wallDistance = sonarLeft.convert_in(sonarLeft.ping_median(AMOUNT_OF_PULSES));
Serial.println(wallDistance);
// too close
if(wallDistance <= hit)
{
wall = true;
}
// return it
return wall;
}
boolean senseRWall()
{
///////////////////////////////NOTE: When sonar reads 5, light sensor = 9 inches from wall.
// declare variables
int wallDistance;
int hit = 12;
boolean wall = false;
// ping and do conversion
// Values are returned in integer values of 1 inch increments.
wallDistance = sonarRight.convert_in(sonarRight.ping_median(AMOUNT_OF_PULSES));
Serial.println(wallDistance);
// too close
if(wallDistance <= hit)
{
wall = true;
}
// return it
return wall;
}
boolean senseFWall()
{
///////////////////////////////NOTE: When sonar reads 2, light sensor = 9 inches from wall.
// declare variables
int wallDistance = 0;
int hit = 6;
boolean wall = false;
// ping and do conversion
// Values are returned in integer values of 1 inch increments.
wallDistance = sonarFront.convert_in(sonarFront.ping_median(AMOUNT_OF_PULSES));
Serial.println(wallDistance);
// too close
if(wallDistance <= hit && wallDistance)
{
wall = true;
}
// return it
return wall;
}
boolean isHeat()
{
// declare variable
boolean hot = false;
// get data
heatVal = analogRead(HEAT_SENSOR);
Serial.print("HEAT: ");
Serial.println(heatVal);
// figure out what temp it should trigger
if (heatVal >= Tsensor + 5)
{
// hot = true;
}
// return it
return hot;
}
boolean isLight()
{
// declare variable
boolean light = false;
// get data
lightVal = analogRead(LIGHT_SENSOR);
Serial.print("LIGHT: ");
Serial.println(lightVal);
// figure out when it should trigger
if (lightVal >= Lsensor + 150)
{
// light = true;
}
// return it
return light;
}
// to make cool sounds
void foundItSound()
{
for (int i = 0; i <= 2000; i ++)
{
analogWrite(SPEAKER, 200);
}
for (int i = 0; i <= 2000; i ++)
{
analogWrite(SPEAKER, 100);
}
for (int i = 0; i <= 2000; i ++)
{
analogWrite(SPEAKER, 50);
}
for (int i = 0; i <= 2000; i ++)
{
analogWrite(SPEAKER, 100);
}
for (int i = 0; i <= 2000; i ++)
{
analogWrite(SPEAKER, 200);
}
}
|
// mips.cpp
#include "mips.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cmath>
using namespace std;
char res[100];
/*
* Return an initialized computer with the stack pointer set to the
* address of the end of data memory, the remaining registers initialized
* to zero, and the instructions read from the given file.
* The other arguments all govern how the program interacts with the user.
*/
//返回一个初始化的计算机,其堆栈指针设置为数据存储器末尾的地址,
//其余寄存器初始化为零,并且指令从给定文件读取。其他参数都控制程序如何与用户交互。
Computer* newComputer(FILE* filein, int printingRegisters, int printingMemory, int debugging, int interactive) {
int k;
unsigned int instr;
Computer* mips = (Computer*)malloc(sizeof(Computer));
for (k = 0; k < 32; k++) mips->registers[k] = 0;
/* stack pointer starts at end of data area and grows down */
// 29号寄存器是sp,sp指针开始时指向内存的最大地址位置,
// 向下移动表示申请内存栈的空间。
mips->registers[29] = 0x00400000 + (MAXNUMINSTRS + MAXNUMDATA) * 4;
k = 0;
while (1) {
instr = 0;
unsigned char temp = 0;
int i;
for (i = 0; i < 4; i++) {
if (!fread(&temp, 1, 1, filein)) {
i = -1;
break;
}
instr |= temp << (i << 3);
}
if (i == -1) break;
mips->memory[k] = instr;
k++;
if (k > MAXNUMINSTRS) {
fprintf(stderr, "Program is too big (%d instructions, only %d allowed).\n", k, MAXNUMINSTRS);
exit(1);
}
}
mips->printingRegisters = printingRegisters;
mips->printingMemory = printingMemory;
mips->interactive = interactive;
mips->debugging = debugging;
}
/*
* Run the simulation.运行模拟。
*/
void simulate(Computer* mips) {
char s[10]; /* used for handling interactive input *///用于处理交互式输入
unsigned int instr;
int changedReg, changedMem;
mips->pc = 0x00400000;
while (1) {
if (mips->interactive) {
printf("> ");
fgets(s, 10, stdin);
if (s[0] == 'q') return;
}
instr = contents(mips, mips->pc);
printf("Executing instruction at %8.8x: %8.8x\n", mips->pc, instr);
printf("\t%s\n", disassembled(instr, mips->pc));
//cout << '\t' << disassembled(instr, mips->pc) << endl;
simulateInstruction(mips, instr, &changedReg, &changedMem);
printInfo(mips, changedReg, changedMem);
}
}
/*
* Print relevant information about the state of the computer.
* changedReg is the index of the register changed by the instruction
* being simulated. If changedReg is -1, no register was updated by
* the simulated instruction, i.e. it was a branch, a jump, or a store).
* changedMem is the address of the memory location changed by the
* simulated instruction. For anything but a store, changedMem will be -1.
* Previously initialized flags indicate whether to print all the
* registers or just the one that changed, and whether to print
* all the nonzero memory or just the memory location that changed.
*/
/* 打印有关计算机状态的相关信息.changedReg是由正在模拟的指令更改的寄存器的索引。
* 如果changedReg为-1,则模拟指令没有更新寄存器,即它是分支,跳转或存储。
* changedMem是模拟指令更改的内存位置的地址。 对于除商店之外的任何东西,changedMem将为-1。
* 以前初始化的标志指示是打印所有寄存器还是仅打印更改的寄存器,以及是打印所有非零存储器还是仅打印更改的存储器位置。*/
void printInfo(Computer* mips, int changedReg, int changedMem) {
int k, addr;
printf("New pc = %8.8x\n", mips->pc);
if (!mips->printingRegisters && changedReg == -1) printf("No register was updated.\n");
else if (!mips->printingRegisters) printf("Updated r%d to %8.8x\n", changedReg, mips->registers[changedReg]);
else {
for (k = 0; k < 32; k++) {
printf("r%2d: %8.8x ", k, mips->registers[k]);
if ((k + 1) % 4 == 0) printf("\n");
}
}
if (!mips->printingMemory && changedMem == -1) printf("No memory location was updated.\n");
else if (!mips->printingMemory) printf("Updated memory at address %8.8x to %8.8x\n", changedMem, contents(mips, changedMem));
else {
printf("Nonzero memory\n");
printf("ADDR CONTENTS\n");
for (addr = 0x00400000 + (MAXNUMINSTRS << 2); addr < 0x00400000 + ((MAXNUMINSTRS + MAXNUMDATA) << 2); addr = addr + 4) {
if (contents(mips, addr) != 0) printf("%8.8x %8.8x\n", addr, contents(mips, addr));
}
}
printf("\n");
}
/*
* Return the contents of memory at the given address.
* 返回给定地址的内存内容。
*/
unsigned int contents(Computer* mips, int addr) {
int index = (addr - 0x00400000) / 4;
if (((addr & 0x3) != 0) || (index < 0) || (index >= (MAXNUMINSTRS + MAXNUMDATA))) {
printf("Invalid Address: %8.8x", addr);
exit(0);
}
return mips->memory[index];
}
/*
* Return a string containing the disassembled version of the given
* instruction. You absolutely MUST follow the formatting instructions
* given in the assignment. Note that the string your return should
* not include a tab at the beginning or a newline at the end since
* those are added in computer.c where this function is called.
*
* Finally you are responsible for managing the memory associated with
* any string you return. If you use malloc, you will somehow need to
* free the memory later (note that you cannot modify computer.c).
* Hint: static or global variables.
*/
/* 返回包含给定指令的反汇编版本的字符串。
* 你绝对必须遵循作业中给出的格式化说明。
* 请注意,返回的字符串不应包含开头的选项卡或结尾处的换行符,
* 因为这些字符串将添加到computer.c中,此处调用此函数。
* 最后,您负责管理与您返回的任何字符串相关联的内存。
* 如果你使用malloc,你将以某种方式需要释放内存(注意你不能修改computer.c)。
* 提示:静态或全局变量。*/
char *disassembled(unsigned int instr, unsigned int pc) {
/* You replace this code by the right stuff. */
//if (/*instruction isn't supported */) exit (0); // Your program must exit when an unsupported instruction is detected
int opcode, rs, rt, rd, shamt, func, immediate;
opcode = instr >> 26;
if (opcode == 0) {//R格式指令
rs = (instr << 6) >> 27;
rt = (instr << 11) >> 27;
rd = (instr << 16) >> 27;
shamt = (instr << 21) >> 27;
func = (instr << 26) >> 26;
if (func == 32 || func == 33 || func == 34 || func == 35 || func == 36 || func == 37 || func == 42) {
char str1[10], str2[10] = "\t$", str3[10] = ", $", str4[10] = ", $";
switch (func)
{
case 32:
strcpy_s(str1, "add"); strcpy_s(res, str1); break;
case 33:
strcpy_s(str1, "addu"); strcpy_s(res, str1); break;
case 34:
strcpy_s(str1, "sub"); strcpy_s(res, str1); break;
case 35:
strcpy_s(str1, "subu"); strcpy_s(res, str1); break;
case 36:
strcpy_s(str1, "and"); strcpy_s(res, str1); break;
case 37:
strcpy_s(str1, "or"); strcpy_s(res, str1); break;
case 42:
strcpy_s(str1, "slt"); strcpy_s(res, str1); break;
default:break;
}
strcat_s(str2, to_string(rd).c_str()); strcat_s(res, str2);
strcat_s(str3, to_string(rs).c_str()); strcat_s(res, str3);
strcat_s(str4, to_string(rt).c_str()); strcat_s(res, str4);
}
else if (func == 0 || func == 2) {
char str1[10], str2[10] = "\t$", str3[10] = ", $", str4[10] = ", ";
switch (func)
{
case 0:
strcpy_s(str1, "sll"); strcpy_s(res, str1); break;
case 2:
strcpy_s(str1, "srl"); strcpy_s(res, str1); break;
default:break;
}
strcat_s(str2, to_string(rd).c_str()); strcat_s(res, str2);
strcat_s(str3, to_string(rt).c_str()); strcat_s(res, str3);
strcat_s(str4, to_string(ImmediatelyConvertToDecimal(shamt)).c_str()); strcat_s(res, str4);
}
else if (func == 8)
{
char str1[10] = "jr\t$"; strcat_s(str1, to_string(rs).c_str());
strcpy_s(res, str1);
}
else
{
exit(0);
}
}
else if (opcode == 8 || opcode == 9 || opcode == 12 || opcode == 13 || opcode == 4 || opcode == 5)
{
rs = (instr << 6) >> 27;
rt = (instr << 11) >> 27;
immediate = (instr << 16) >> 16;
immediate = ImmediatelyConvertToDecimal(immediate);
char str1[10], str2[10] = "\t$", str3[10] = ", $", str4[30] = ", ";
switch (opcode)
{
case 8:
strcat_s(str2, to_string(rt).c_str()); strcat_s(str3, to_string(rs).c_str());
strcpy_s(str1, "addi"); strcat_s(str4, to_string(immediate).c_str()); break;
case 9:
strcat_s(str2, to_string(rt).c_str()); strcat_s(str3, to_string(rs).c_str());
strcpy_s(str1, "addiu"); strcat_s(str4, to_string(immediate).c_str()); break;
case 12:
strcat_s(str2, to_string(rt).c_str()); strcat_s(str3, to_string(rs).c_str());
strcpy_s(str1, "andi"); strcat_s(str4, "0x"); strcat_s(str4, tentohex(immediate).c_str()); break;
case 13:
strcat_s(str2, to_string(rt).c_str()); strcat_s(str3, to_string(rs).c_str());
strcpy_s(str1, "ori"); strcat_s(str4, "0x"); strcat_s(str4, tentohex(immediate).c_str()); break;
case 4:
strcat_s(str2, to_string(rs).c_str()); strcat_s(str3, to_string(rt).c_str());
strcpy_s(str1, "beq"); strcat_s(str4, "0x"); strcat_s(str4, tentohex(pc + immediate * 4 + 4).c_str()); break;
case 5:
strcat_s(str2, to_string(rs).c_str()); strcat_s(str3, to_string(rt).c_str());
strcpy_s(str1, "bne"); strcat_s(str4, "0x"); strcat_s(str4, tentohex(pc + immediate * 4 + 4).c_str()); break;
default:break;
}strcpy_s(res, str1);
strcat_s(res, str2);
strcat_s(res, str3);
strcat_s(res, str4);
}
else if (opcode == 15)
{
rt = (instr << 11) >> 27;
immediate = (instr << 16) >> 16;
immediate = ImmediatelyConvertToDecimal(immediate);
char str1[] = "lui", str2[10] = "\t$", str3[7] = ", 0x"; strcpy_s(res, str1);
strcat_s(str2, to_string(rt).c_str());
strcat_s(res, str2);
strcat_s(str3, tentohex(immediate).c_str());
strcat_s(res, str3);
}
else if (opcode == 35 || opcode == 43) {
rs = (instr << 6) >> 27;
rt = (instr << 11) >> 27;
immediate = (instr << 16) >> 16;
immediate = ImmediatelyConvertToDecimal(immediate);
char str1[10], str2[10] = "\t$", str3[10] = " ,", str4[10] = "($";
if (opcode == 35) { strcpy_s(str1, "lw"); }
else { strcpy_s(str1, "sw"); }
strcpy_s(res, str1); strcat_s(str2, to_string(rt).c_str()); strcat_s(res, str2);
strcat_s(str3, to_string(immediate).c_str()); strcat_s(res, str3);
strcat_s(str4, to_string(rs).c_str()); strcat_s(str4, ")"); strcat_s(res, str4); \
}
else if (opcode == 2 || opcode == 3) {
int address = (instr << 6) >> 6;
char str1[10], str2[30] = "\t0x";
if (opcode == 2) { strcpy_s(str1, "j"); }
else { strcpy_s(str1, "jal"); }
strcat_s(str2, tentohex(address).c_str());
strcpy_s(res, str1); strcat_s(res, str2);
}
else exit(0);
//cout << res;
//cout << res;
return (res);
}
/*
* Simulate the execution of the given instruction, updating the
* pc appropriately.
*
* If the instruction modified a register--i.e. if it was lw,
* addu, addiu, subu, sll, srl, and, andi, or, ori, lui, or slt
* to list a few examples-- return the index of the modified
* register in *changedReg, otherwise return -1 in *changedReg.
* Note that you should never return 0 in *changedReg, since
* $0 cannot be changed! Note that even if the instruction
* changes the register back to it's old value
* (e.g. addu $3, $3, $0) the destination register ($3 in the
* example) should be marked changed!
*
* If the instruction was sw, return the address of the
* updated memory location in *changedMem, otherwise return -1
* in *changedMem.
*/
/* 模拟给定指令的执行,适当更新pc。 如果指令修改了一个寄存器 - 即。
* 如果它是lw,addu,addiu,subu,sll,srl和,andi,or,ori,lui或slt
* 列出一些例子 - 在changedReg中返回修改后的寄存器的索引,否则在 *changedReg返回-1 。
* 请注意,您永远不应该在* changedReg中返回0,因为$ 0无法更改!
* 请注意,即使指令将寄存器更改回旧值(例如addu $ 3,$ 3,$ 0),
* 目标寄存器(示例中为$ 3)也应标记为已更改!如果指令为sw,则返回更新内存的地址
* 在* changedMem中的位置,否则在* changedMem中返回-1。*/
void simulateInstruction(Computer* mips, unsigned int instr, int *changedReg, int *changedMem) {
/* You replace this code by the right stuff. */
mips->pc = mips->pc + 4;
*changedReg = -1;
*changedMem = -1;
int opcode, rs, rt, rd, shamt, func, immediate; char res[100];
opcode = instr >> 26;
if (opcode == 0) {//R格式指令
rs = (instr << 6) >> 27;
rt = (instr << 11) >> 27;
rd = (instr << 16) >> 27;
shamt = (instr << 21) >> 27;
func = (instr << 26) >> 26;
if (func == 32 || func == 33 || func == 34 || func == 35 || func == 36 || func == 37 || func == 42) {
//char str1[5], str2[5] = "\t$", str3[5] = ", $", str4[5] = ", $";
switch (func)
{
case 32://add
*changedReg = rd;
mips->registers[rd] = mips->registers[rs] + mips->registers[rt]; break;
case 33://addu
*changedReg = rd;
mips->registers[rd] = mips->registers[rs] + mips->registers[rt]; break;
case 34://sub
*changedReg = rd;
mips->registers[rd] = mips->registers[rs] - mips->registers[rt]; break;
case 35://subu
*changedReg = rd;
mips->registers[rd] = mips->registers[rs] - mips->registers[rt]; break;
case 36://and
*changedReg = rd;
mips->registers[rd] = mips->registers[rs] & mips->registers[rt]; break;
case 37://or
*changedReg = rd;
mips->registers[rd] = mips->registers[rs] | mips->registers[rt]; break;
case 42://slt
*changedReg = rd;
mips->registers[rd] = (mips->registers[rs] < mips->registers[rt]); break;
default:break;
}
}
else if (func == 0 || func == 2) {
//char str1[5], str2[5] = "\t$", str3[5] = ", $", str4[5] = ", ";
switch (func)
{
case 0://sll
*changedReg = rd;
mips->registers[rd] = (mips->registers[rt] << ImmediatelyConvertToDecimal(shamt)); break;
case 2://srl
*changedReg = rd;
mips->registers[rd] = (mips->registers[rt] >> ImmediatelyConvertToDecimal(shamt)); break;
default:break;
}
}
else if (func == 8)
{
mips->pc = mips->registers[rs];
}
else
{
exit(0);
}
}
else if (opcode == 8 || opcode == 9 || opcode == 12 || opcode == 13 || opcode == 4 || opcode == 5)
{
rs = (instr << 6) >> 27;
rt = (instr << 11) >> 27;
immediate = (instr << 16) >> 16;
immediate = ImmediatelyConvertToDecimal(immediate);
char str1[10], str2[10] = "\t$", str3[10] = ", $", str4[10] = ", ";
strcat_s(str2, to_string(rs).c_str()); strcat_s(str3, to_string(rt).c_str());
switch (opcode)
{
case 8://addi
*changedReg = rt;
mips->registers[rt] = mips->registers[rs] + ImmediatelyConvertToDecimal(immediate); break;
case 9://addiu
*changedReg = rt;
mips->registers[rt] = mips->registers[rs] + ImmediatelyConvertToDecimal(immediate); break;
case 12://andi
*changedReg = rt;
mips->registers[rt] = mips->registers[rs] & ImmediatelyConvertToDecimal(immediate); break;
case 13://ori
*changedReg = rt;
mips->registers[rt] = mips->registers[rs] | ImmediatelyConvertToDecimal(immediate); break;
case 4://beq
if (mips->registers[rs] == mips->registers[rt]) { mips->pc = mips->pc + immediate * 4; }break;
case 5://bne
if (mips->registers[rs] != mips->registers[rt]) { mips->pc = mips->pc + immediate * 4; }break;
default:break;
}
}
else if (opcode == 15)//lui
{
rt = (instr << 11) >> 27;
immediate = (instr << 16) >> 16;
immediate = ImmediatelyConvertToDecimal(immediate);
*changedReg = rt;
mips->registers[rt] = immediate * 65536;
}
else if (opcode == 35 || opcode == 43) {
rs = (instr << 6) >> 27;
rt = (instr << 11) >> 27;
immediate = (instr << 16) >> 16;
immediate = ImmediatelyConvertToDecimal(immediate);
if (opcode == 35) {
*changedReg = rt;
mips->registers[rt] = contents(mips, mips->registers[rs] + immediate);
}
else {
*changedMem = mips->registers[rs] + immediate;
int index = (*changedMem - 0x00400000) / 4;
if (((*changedMem & 0x3) != 0) || (index < 0) || (index >= (MAXNUMINSTRS + MAXNUMDATA))) {
printf("Invalid Address: %8.8x", *changedMem);
exit(0);
}
mips->memory[index] = mips->registers[rt];
}
}
else if (opcode == 2 || opcode == 3) {
int address = (instr << 6) >> 6;
char str1[5], str2[27] = "\t";
if (opcode == 2) { mips->pc = address * 4; }
else {
*changedReg = 31;
mips->registers[31] = mips->pc + 4;
mips->pc = address * 4;
}
}
}
int main (int argc, char *argv[]) {
int argIndex;
int printingRegisters = FALSE;
int printingMemory = FALSE;
int debugging = FALSE;
int interactive = FALSE;
FILE *filein;
Computer* computer;
if (argc < 2) {
cerr << "Not enough arguments.\n";
return 1;
}
for (argIndex=1; argIndex<argc && argv[argIndex][0]=='-'; argIndex++) {
/* Argument is an option, we hope one of -r, -m, -i, -d. */
switch (argv[argIndex][1]) {
case 'r':
printingRegisters = TRUE;
break;
case 'm':
printingMemory = TRUE;
break;
case 'i':
interactive = TRUE;
break;
case 'd':
debugging = TRUE;
break;
default:
fprintf (stderr, "Invalid option \"%s\".\n", argv[argIndex]);
fprintf (stderr, "Correct options are -r, -m, -i, -d.\n");
return 1;
}
}
if (argIndex == argc) {
fprintf (stderr, "No file name given.\n");
return 1;
} else if (argIndex < argc-1) {
fprintf (stderr, "Too many arguments.\n");
return 1;
}
filein = fopen (argv[argIndex], "rb");
if (filein == NULL) {
fprintf (stderr, "Can't open file: %s\n", argv[argIndex]);
return 1;
}
computer = newComputer (filein, printingRegisters, printingMemory, debugging, interactive);
simulate (computer);
return 0;
}
|
C/C++获取本地日期时间常见方法
1.跨平台方法
1.1方法一:手动暴力法(snprintf)
snprintf()函数用于格式化输出字符串到指定大小的缓冲,可以获取我们想要的日期时间格式。
#include <iostream>
using namespace std;
#include <time.h>
time_t t = time(NULL);
struct tm* stime=localtime(&t);
char tmp[32]{0};
snprintf(tmp,sizeof(tmp),"%04d-%02d-%02d %02d:%02d:%02d",1900+stime->tm_year,1+stime->tm_mon,stime->tm_mday, stime->tm_hour,stime->tm_min,stime->tm_sec);
cout<<tmp<<endl;
输出结果:2015-04-02 23:12:56
1.2方法二:便捷快速法(strftime)
strftime()函数用于将时间(struct tm)格式化为字符串,可用于替代snprintf()函数。
#include <iostream>
#include <time.h>
using namespace std;
time_t t = time(0);
char tmp[32]={NULL};
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&t));
cout<<tmp<<endl;
输出结果:2015-04-02 23:12:56
1.3方法三:简获日历时间法
1.3.1通过ctime()+time_t
ctime()函数可用于将时间戳(time_t值)转换为可读的日历时间(calendar time)字符串,转换结果格式为:
Www Mmm dd hh:mm:ss yyyy
其中Www是weekday, Mmm 表示Month,dd表示每月的多少号,hh:mm:ss表示time,yyyy表示year。具体示例如下:
#include <time.h>
#include <iostream>
#include <string>
using namespace std;
time_t ts=time(NULL);
char tmp[32]{0};
strncpy(tmp,ctime(&ts),sizeof(tmp));
cout<<tmp<<endl;
输出结果:Fri Aug 14 23:19:42 2015
1.3.2通过asctime()+struct tm
asctime()函数功能与ctime()函数类似,用于将struct tm表示的日期时间转换为可读的日历时间字符串,结果格式同ctime()。asctime()与ctime()不同之处是asctime()传入的参数类型是struct tm指针型,ctime()的是time_t指针型。具体示例如下:
time_t ts=time(NULL);
struct tm stm=*localtime(&ts);
char tmp[32]{0};
strncpy(tmp,asctime(&stm),sizeof(tmp));
cout<<tmp<<endl;
输出结果:Fri Aug 14 23:19:42 2015
2.Windows平台获取日期时间
#include <iostream>
using namespace std;
#include <time.h>
#include <windows.h>
SYSTEMTIME sys;
GetLocalTime(&sys);
char tmp[64]={NULL};
sprintf(tmp,"%4d-%02d-%02d %02d:%02d:%02d ms:%03d",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute,sys.wSecond,sys.wMilliseconds);
cout<<tmp<<endl;
输出结果:2015-08-14 23:41:56 ms:354
3.Unix平台获取日期时间
#include <sys/time.h>
#include <unistd.h>
struct timeval now_time;
gettimeofday(&now_time, NULL);
time_t tt = now_time.tv_sec;
tm *temp = localtime(&tt);
char time_str[32]={NULL};
sprintf(time_str,"%04d-%02d-%02d%02d:%02d:%02d",temp->tm_year+ 1900,temp->tm_mon+1,temp->tm_mday,temp->tm_hour,temp->tm_min, temp->tm_sec);
cout<<tmp<<endl;
输出时间:2015-08-14 23:41:56
4.日期时间与时间戳的相互转换
4.1时间戳转日期时间
//@brief:时间戳转日期时间
static inline string getDateTimeFromTS(time_t ts)
{
if(ts<0)
{
return "";
}
struct tm tm = *localtime(&ts);
static char time_str[32]{0};
snprintf(time_str,sizeof(time_str),"%04d-%02d-%02d %02d:%02d:%02d",tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);
return string(time_str);
}
4.2日期时间转时间戳
(1)跨平台方法。
使用sscanf将日期时间字符串转为struct tm,再转为time_t。
//@brief:日期时间转时间戳
static inline time_t getTSFromDateTime(const string& dateTime,const char* fmt)
{
int dY, dM, dD, dH, dMin, dS;
sscanf(dateTime.c_str(),fmt, &dY, &dM, &dD, &dH, &dMin, &dS);
struct tm stm;
stm.tm_year = dY - 1900;
stm.tm_mon = dM - 1;
stm.tm_mday = dD;
stm.tm_hour = dH;
stm.tm_min = dMin;
stm.tm_sec = dS;
return mktime(&stm); //返回时间戳
}
(2)Linux平台方法。
使用glibc库函数strptime()将日期时间字符串转为struct tm,再转为time_t。strptime()函数的功能与strftime()函数功能相反,用于将日期时间字符串转换为struct tm。函数原型如下:
char *strptime(const char *s, const char *format, struct tm *tm)
参数说明:
s:struct tm格式化后的C字符串(以0结尾);
format:字符串格式,构建方式与strftime的format字符串完全一样;
struct tm *tm:转换后存储tm值的指针;
返回值:指向转换过程中第一个不能被处理的那个字符。
转换示例如下。
static inline time_t getTSFromDateTime(const string& dateTime, const char* fmt)
{
struct tm t;
memset(&t, 0, sizeof(t));
if(strptime(dateTime.c_str(),fmt,&t)!=NULL)
{
return mktime(&t);
}
return 0;
}
5.需知知识点
(5)clock tick,时钟计时单元,一个时钟计时单元的时间长短是由CPU控制的。一个clock tick不是CPU的一个时钟周期,而是C/C++的一个基本计时单位。在VC++的time.h文件中,我们可以找到相关的定义:
#ifndef _CLOCK_T_DEFINED
typedef long clock_t;
#define _CLOCK_T_DEFINED
#endif
#define CLOCKS_PER_SEC ((clock_t)1000)
clock_t clock( void );
这个函数返回从“进程启动”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)。
//获取逝去时间
clock_t start, finish;
start=clock();
…
finish=clock();
//逝去多少秒
long duration=(finish- start)/CLOCKS_PER_SEC;
(5)头文件<time.h>还提供了两种不同的函数将时间戳转换为年月日时分秒分开显示的日历时间格式struct tm。
struct tm* gmtime(const time_t* timer);
struct tm* localtime(const time_t* timer);
其中gmtime()函数是将时间戳转化为UTC+0的日历时间,即0时区的世界标准时间,并返回一个struct tm结构体来保存这个时间。而localtime()函数考虑时区,将时间戳转为本地日历时间。比如用gmtime()函数获得的时间是2018-07-30 00:00:00,那么用localtime()函数在中国地区获得的本地时间会比世界标准时间早8个小时,即2018-07-30 08:00:00。示例程序(VC++)如下:
#include <time.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
time_t ts = 0;
struct tm stm1;
gmtime_s(&stm1,&ts);
char tmp[32]{0};
asctime_s(tmp, &stm1);
cout<<tmp;
struct tm stm2;
localtime_s(&stm2, &ts);
asctime_s(tmp, &stm2);
cout <<tmp;
}
程序输出:
Thu Jan 1 00:00:00 1970
Thu Jan 1 08:00:00 1970
(6)分解时间就是以年月日时分秒等分量保存的时间结构,在C/C++中是struct tm结构。我们可以使用mktime()函数将用struct tm结构表示的日历时间转化为时间戳,其作用与gmtime()和localtime()函数具有相反。其函数原型如下:
time_t mktime(struct tm* timeptr);
|
#include <iostream>
using namespace std;
int main() {
int a, b, c;
cout << "가격 입력 : ";
cin >> a >> b >> c;
cout << "상품1 :";
cout.width(7);
cout << a << "원\n";
cout << "상품2 :";
cout.width(7);
cout << b << "원\n";
cout << "상품3 :";
cout.width(7);
cout << c << "원\n";
}
|
////////////////////////////////////////////////////////////////////////////////
#include <polysolve/FEMSolver.hpp>
#include <catch.hpp>
#include <iostream>
#include <unsupported/Eigen/SparseExtra>
////////////////////////////////////////////////////////////////////////////////
using namespace polysolve;
TEST_CASE("all", "[solver]")
{
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
const bool ok = loadMarket(A, path + "/A_2.mat");
REQUIRE(ok);
auto solvers = LinearSolver::availableSolvers();
for (const auto &s : solvers)
{
if (s == "Eigen::DGMRES")
continue;
#ifdef WIN32
if (s == "Eigen::ConjugateGradient" || s == "Eigen::BiCGSTAB" || s == "Eigen::GMRES" || s == "Eigen::MINRES")
continue;
#endif
auto solver = LinearSolver::create(s, "");
// solver->setParameters(params);
Eigen::VectorXd b(A.rows());
b.setRandom();
Eigen::VectorXd x(b.size());
x.setZero();
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
// solver->getInfo(solver_info);
// std::cout<<"Solver error: "<<x<<std::endl;
const double err = (A * x - b).norm();
INFO("solver: " + s);
REQUIRE(err < 1e-8);
}
}
#ifdef POLYSOLVE_WITH_HYPRE
TEST_CASE("hypre", "[solver]")
{
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
const bool ok = loadMarket(A, path + "/A_2.mat");
REQUIRE(ok);
auto solver = LinearSolver::create("Hypre", "");
// solver->setParameters(params);
Eigen::VectorXd b(A.rows());
b.setRandom();
Eigen::VectorXd x(b.size());
x.setZero();
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
// solver->getInfo(solver_info);
// std::cout<<"Solver error: "<<x<<std::endl;
const double err = (A * x - b).norm();
REQUIRE(err < 1e-8);
}
TEST_CASE("hypre_initial_guess", "[solver]")
{
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
const bool ok = loadMarket(A, path + "/A_2.mat");
REQUIRE(ok);
// solver->setParameters(params);
Eigen::VectorXd b(A.rows());
b.setRandom();
Eigen::VectorXd x(A.rows());
x.setZero();
{
json solver_info;
auto solver = LinearSolver::create("Hypre", "");
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 1);
}
{
json solver_info;
auto solver = LinearSolver::create("Hypre", "");
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] == 1);
}
// std::cout<<"Solver error: "<<x<<std::endl;
const double err = (A * x - b).norm();
REQUIRE(err < 1e-8);
}
#endif
#ifdef POLYSOLVE_WITH_AMGCL
TEST_CASE("amgcl_initial_guess", "[solver]")
{
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
const bool ok = loadMarket(A, path + "/A_2.mat");
REQUIRE(ok);
// solver->setParameters(params);
Eigen::VectorXd b(A.rows());
b.setRandom();
Eigen::VectorXd x(A.rows());
x.setZero();
{
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 0);
}
{
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] == 0);
}
// std::cout<<"Solver error: "<<x<<std::endl;
const double err = (A * x - b).norm();
REQUIRE(err < 1e-8);
}
#endif
|
#ifndef TREEWIDZARD_AUXILIARYCONTROLLER_HPP
#define TREEWIDZARD_AUXILIARYCONTROLLER_HPP
#include <fstream>
#include <iostream>
inline void show_manual() {
// random settings (not implemented in this version) [-random <seed> <intro
// vertex probability> <forget vertex probability> <ping number>]
//
/*
Random Search Parameters:
seed: The seed that initializes the random generator. This is an
unsigned int. intro vertex probability: The probability of
introducing a new vertex. This is a float between 0 and 1. forget vertex
probability: The probability of forgetting a vertex. This is a float between
0 and 1. ping number: At each "ping number" times the program prints the
number of iterations executed so far. This parameter only has an effect if
the -pl flag is on.
*/
std::cout << R"___( Searching for a Counterexample:
./treewidzard -atp [Width] [Flag Options] <search method> <property file>
[Width]: tw|pw = number
example: tw = 2 (The program will search graphs with tree-width at most 2)
example: pw = 2 (The program will search graphs with path-width at most 2)
Flag Options:
-pl print loop
-ps print states
-st print state tree decomposition if a counterexample is found
-pdbgn print directed bipartite graph in NAUTY format
-no-bfs-dag disable creation of the bfs dag, to speed up the search (NOT WORKING IN THIS VERSION)
-nthreads number of threads to use in parallel
-files write the counter example into files. Files: ITD and Augmented ITD,
Parsing a Tree Decomposition:
1- For PACE Format
./treewidzard -modelcheck PACE [Flag Options] <property file> <graph file> <tree decomposition file>
2- For ITD Decomposition Verify
./treewidzard -modelcheck ITD [Flag Options] <property file> <instructive tree decomposition file>
Flag Options:
-files write the counter example into files. Files: ITD and Augmented ITD, RunTree, Graph File, Graph in GML Format, Graph in PACE Format, Tree Decomposition
)___";
exit(20);
}
#endif // TREEWIDZARD_AUXILIARYCONTROLLER_HPP
|
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<int, int> m;
int res_length = 0;
int cur_length = 0;
for(int i = 0; i < s.length(); i++)
{
if(m.find(s[i] - 'a') == m.end())
{
m[s[i] - 'a'] = i;
cur_length++;
res_length = max(res_length, cur_length);
}
else // existing m[s[i] - 'a']
{
cur_length = min(i - m.find(s[i] - 'a')->second, ++cur_length);
res_length = max(res_length, cur_length);
m[s[i] - 'a'] = i;
}
}
return res_length;
}
};
// Note: min and max take linear complexity with the length of N, and constant if N == 1 || N == 2
|
/*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY
- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*====================================================================*/
/*
* writefile.c
*
* High-level procedures for writing images to file:
* l_int32 pixaWriteFiles()
* l_int32 pixWrite() [behavior depends on WRITE_AS_NAMED]
* l_int32 pixWriteStream()
* l_int32 pixWriteImpliedFormat()
* l_int32 pixWriteTempfile()
*
* Selection of output format if default is requested
* l_int32 pixChooseOutputFormat()
* l_int32 getImpliedFileFormat()
* const char *getFormatExtension()
*
* Write to memory
* l_int32 pixWriteMem()
*
* Image display for debugging
* l_int32 pixDisplay()
* l_int32 pixDisplayWithTitle()
* l_int32 pixDisplayMultiple()
* l_int32 pixDisplayWrite()
* l_int32 pixDisplayWriteFormat()
* l_int32 pixSaveTiled()
* l_int32 pixSaveTiledOutline()
* l_int32 pixSaveTiledWithText()
* void l_chooseDisplayProg()
*
* Supported file formats:
* (1) Writing is supported without any external libraries:
* bmp
* pnm (including pbm, pgm, etc)
* spix (raw serialized)
* (2) Writing is supported with installation of external libraries:
* png
* jpg (standard jfif version)
* tiff (including most varieties of compression)
* gif
* webp
* (3) Writing is supported through special interfaces:
* ps (PostScript, in psio1.c, psio2.c):
* level 1 (uncompressed)
* level 2 (g4 and dct encoding: requires tiff, jpg)
* level 3 (g4, dct and flate encoding: requires tiff, jpg, zlib)
* pdf (PDF, in pdfio.c):
* level 1 (g4 and dct encoding: requires tiff, jpg)
* level 2 (g4, dct and flate encoding: requires tiff, jpg, zlib)
* (4) No other output formats are supported, such as jp2 (jpeg2000)
*/
#include <string.h>
#include "allheaders.h"
/* Special flag for pixWrite(). The default for both unix and */
/* windows is to use whatever filename is given, as opposed to */
/* insuring the filename extension matches the image compression. */
#define WRITE_AS_NAMED 1
/* Display program (xv, xli, xzgv, open) to be invoked by pixDisplay() */
#ifdef _WIN32
static l_int32 var_DISPLAY_PROG = L_DISPLAY_WITH_IV; /* default */
#elif defined(__APPLE__)
static l_int32 var_DISPLAY_PROG = L_DISPLAY_WITH_OPEN; /* default */
#else
static l_int32 var_DISPLAY_PROG = L_DISPLAY_WITH_XZGV; /* default */
#endif /* _WIN32 */
/* MS VC++ can't handle array initialization with static consts ! */
#define L_BUF_SIZE 512
static const l_int32 MAX_DISPLAY_WIDTH = 1000;
static const l_int32 MAX_DISPLAY_HEIGHT = 800;
static const l_int32 MAX_SIZE_FOR_PNG = 200;
/* PostScript output for printing */
static const l_float32 DEFAULT_SCALING = 1.0;
/* Global array of image file format extension names. */
/* This is in 1-1 corrspondence with format enum in imageio.h. */
/* The empty string at the end represents the serialized format, */
/* which has no recognizable extension name, but the array must */
/* be padded to agree with the format enum. */
/* (Note on 'const': The size of the array can't be defined 'const' */
/* because that makes it static. The 'const' in the definition of */
/* the array refers to the strings in the array; the ptr to the */
/* array is not const and can be used 'extern' in other files.) */
LEPT_DLL l_int32 NumImageFileFormatExtensions = 19; /* array size */
LEPT_DLL const char *ImageFileFormatExtensions[] =
{
"unknown",
"bmp",
"jpg",
"png",
"tif",
"tif",
"tif",
"tif",
"tif",
"tif",
"tif",
"pnm",
"ps",
"gif",
"jp2",
"webp",
"pdf",
"default",
""
};
/* Local map of image file name extension to output format */
struct ExtensionMap
{
char extension[8];
l_int32 format;
};
static const struct ExtensionMap extension_map[] =
{
{ ".bmp", IFF_BMP },
{ ".jpg", IFF_JFIF_JPEG },
{ ".jpeg", IFF_JFIF_JPEG },
{ ".png", IFF_PNG },
{ ".tif", IFF_TIFF },
{ ".tiff", IFF_TIFF },
{ ".pnm", IFF_PNM },
{ ".gif", IFF_GIF },
{ ".jp2", IFF_JP2 },
{ ".ps", IFF_PS },
{ ".pdf", IFF_LPDF },
{ ".webp", IFF_WEBP }
};
/*---------------------------------------------------------------------*
* Top-level procedures for writing images to file *
*---------------------------------------------------------------------*/
/*!
* pixaWriteFiles()
*
* Input: rootname
* pixa
* format (defined in imageio.h; see notes for default)
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) Use @format = IFF_DEFAULT to decide the output format
* individually for each pix.
*/
l_int32
pixaWriteFiles(const char *rootname,
PIXA *pixa,
l_int32 format)
{
char bigbuf[L_BUF_SIZE];
l_int32 i, n, pixformat;
PIX *pix;
PROCNAME("pixaWriteFiles");
if (!rootname)
{
return ERROR_INT("rootname not defined", procName, 1);
}
if (!pixa)
{
return ERROR_INT("pixa not defined", procName, 1);
}
if (format < 0 || format == IFF_UNKNOWN ||
format >= NumImageFileFormatExtensions)
{
return ERROR_INT("invalid format", procName, 1);
}
n = pixaGetCount(pixa);
for (i = 0; i < n; i++)
{
pix = pixaGetPix(pixa, i, L_CLONE);
if (format == IFF_DEFAULT)
{
pixformat = pixChooseOutputFormat(pix);
}
else
{
pixformat = format;
}
snprintf(bigbuf, L_BUF_SIZE, "%s%03d.%s", rootname, i,
ImageFileFormatExtensions[pixformat]);
pixWrite(bigbuf, pix, pixformat);
pixDestroy(&pix);
}
return 0;
}
/*!
* pixWrite()
*
* Input: filename
* pix
* format (defined in imageio.h)
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) Open for write using binary mode (with the "b" flag)
* to avoid having Windows automatically translate the NL
* into CRLF, which corrupts image files. On non-windows
* systems this flag should be ignored, per ISO C90.
* Thanks to Dave Bryan for pointing this out.
* (2) If the default image format IFF_DEFAULT is requested:
* use the input format if known; otherwise, use a lossless format.
* (3) There are two modes with respect to file naming.
* (a) The default code writes to @filename.
* (b) If WRITE_AS_NAMED is defined to 0, it's a bit fancier.
* Then, if @filename does not have a file extension, one is
* automatically appended, depending on the requested format.
* The original intent for providing option (b) was to insure
* that filenames on Windows have an extension that matches
* the image compression. However, this is not the default.
*/
l_int32
pixWrite(const char *filename,
PIX *pix,
l_int32 format)
{
char *fname;
FILE *fp;
PROCNAME("pixWrite");
if (!pix)
{
return ERROR_INT("pix not defined", procName, 1);
}
if (!filename)
{
return ERROR_INT("filename not defined", procName, 1);
}
fname = genPathname(filename, NULL);
#if WRITE_AS_NAMED /* Default */
if ((fp = fopenWriteStream(fname, "wb+")) == NULL)
{
FREE(fname);
return ERROR_INT("stream not opened", procName, 1);
}
#else /* Add an extension to the output name if none exists */
{
l_int32 extlen;
char *extension, *filebuf;
splitPathAtExtension(fname, NULL, &extension);
extlen = strlen(extension);
FREE(extension);
if (extlen == 0)
{
if (format == IFF_DEFAULT || format == IFF_UNKNOWN)
{
format = pixChooseOutputFormat(pix);
}
filebuf = (char *)CALLOC(strlen(fname) + 10, sizeof(char));
if (!filebuf)
{
return ERROR_INT("filebuf not made", procName, 1);
FREE(fname);
}
strncpy(filebuf, fname, strlen(fname));
strcat(filebuf, ".");
strcat(filebuf, ImageFileFormatExtensions[format]);
}
else
{
filebuf = (char *)fname;
}
fp = fopenWriteStream(filebuf, "wb+");
if (filebuf != fname)
{
FREE(filebuf);
}
if (fp == NULL)
{
FREE(fname);
return ERROR_INT("stream not opened", procName, 1);
}
}
#endif /* WRITE_AS_NAMED */
FREE(fname);
if (pixWriteStream(fp, pix, format))
{
fclose(fp);
return ERROR_INT("pix not written to stream", procName, 1);
}
/* Close the stream except if GIF under windows, because
* EGifCloseFile() closes the windows file stream! */
if (format != IFF_GIF)
{
fclose(fp);
}
#ifndef _WIN32
else /* gif file */
{
fclose(fp);
}
#endif /* ! _WIN32 */
return 0;
}
/*!
* pixWriteStream()
*
* Input: stream
* pix
* format
* Return: 0 if OK; 1 on error.
*/
l_int32
pixWriteStream(FILE *fp,
PIX *pix,
l_int32 format)
{
PROCNAME("pixWriteStream");
if (!fp)
{
return ERROR_INT("stream not defined", procName, 1);
}
if (!pix)
{
return ERROR_INT("pix not defined", procName, 1);
}
if (format == IFF_DEFAULT)
{
format = pixChooseOutputFormat(pix);
}
switch(format)
{
case IFF_BMP:
pixWriteStreamBmp(fp, pix);
break;
case IFF_JFIF_JPEG: /* default quality; baseline sequential */
return pixWriteStreamJpeg(fp, pix, 75, 0);
break;
case IFF_PNG: /* no gamma value stored */
return pixWriteStreamPng(fp, pix, 0.0);
break;
case IFF_TIFF: /* uncompressed */
case IFF_TIFF_PACKBITS: /* compressed, binary only */
case IFF_TIFF_RLE: /* compressed, binary only */
case IFF_TIFF_G3: /* compressed, binary only */
case IFF_TIFF_G4: /* compressed, binary only */
case IFF_TIFF_LZW: /* compressed, all depths */
case IFF_TIFF_ZIP: /* compressed, all depths */
return pixWriteStreamTiff(fp, pix, format);
break;
case IFF_PNM:
return pixWriteStreamPnm(fp, pix);
break;
case IFF_PS:
return pixWriteStreamPS(fp, pix, NULL, 0, DEFAULT_SCALING);
break;
case IFF_GIF:
return pixWriteStreamGif(fp, pix);
break;
case IFF_JP2:
return pixWriteStreamJp2k(fp, pix, 34, 0, 0);
break;
case IFF_WEBP:
return pixWriteStreamWebP(fp, pix, 80, 0);
break;
case IFF_LPDF:
return pixWriteStreamPdf(fp, pix, 0, NULL);
break;
case IFF_SPIX:
return pixWriteStreamSpix(fp, pix);
break;
default:
return ERROR_INT("unknown format", procName, 1);
break;
}
return 0;
}
/*!
* pixWriteImpliedFormat()
*
* Input: filename
* pix
* quality (iff JPEG; 1 - 100, 0 for default)
* progressive (iff JPEG; 0 for baseline seq., 1 for progressive)
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) This determines the output format from the filename extension.
* (2) The last two args are ignored except for requests for jpeg files.
* (3) The jpeg default quality is 75.
*/
l_int32
pixWriteImpliedFormat(const char *filename,
PIX *pix,
l_int32 quality,
l_int32 progressive)
{
l_int32 format;
PROCNAME("pixWriteImpliedFormat");
if (!filename)
{
return ERROR_INT("filename not defined", procName, 1);
}
if (!pix)
{
return ERROR_INT("pix not defined", procName, 1);
}
/* Determine output format */
format = getImpliedFileFormat(filename);
if (format == IFF_UNKNOWN)
{
format = IFF_PNG;
}
else if (format == IFF_TIFF)
{
if (pixGetDepth(pix) == 1)
{
format = IFF_TIFF_G4;
}
else
#ifdef _WIN32
format = IFF_TIFF_LZW; /* poor compression */
#else
format = IFF_TIFF_ZIP; /* native windows tools can't handle this */
#endif /* _WIN32 */
}
if (format == IFF_JFIF_JPEG)
{
quality = L_MIN(quality, 100);
quality = L_MAX(quality, 0);
if (progressive != 0 && progressive != 1)
{
progressive = 0;
L_WARNING("invalid progressive; setting to baseline\n", procName);
}
if (quality == 0)
{
quality = 75;
}
pixWriteJpeg (filename, pix, quality, progressive);
}
else
{
pixWrite(filename, pix, format);
}
return 0;
}
/*!
* pixWriteTempfile()
*
* Input: dir (directory name; use '.' for local dir; no trailing '/')
* tail (<optional> tailname, including extension if any)
* pix
* format
* &filename (<optional> return actual filename used; use
* null to skip)
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) This generates a temp filename, writes the pix to it,
* and optionally returns the temp filename.
* (2) If the filename is returned to a windows program from a DLL,
* use lept_free() to free it.
* (3) See genTempFilename() for details. We omit the time and pid
* here.
*/
l_int32
pixWriteTempfile(const char *dir,
const char *tail,
PIX *pix,
l_int32 format,
char **pfilename)
{
char *filename;
l_int32 ret;
PROCNAME("pixWriteTempfile");
if (!dir)
{
return ERROR_INT("filename not defined", procName, 1);
}
if (!pix)
{
return ERROR_INT("pix not defined", procName, 1);
}
if ((filename = genTempFilename(dir, tail, 0, 0)) == NULL)
{
return ERROR_INT("temp filename not made", procName, 1);
}
ret = pixWrite(filename, pix, format);
if (pfilename)
{
*pfilename = filename;
}
else
{
FREE(filename);
}
return ret;
}
/*---------------------------------------------------------------------*
* Selection of output format if default is requested *
*---------------------------------------------------------------------*/
/*!
* pixChooseOutputFormat()
*
* Input: pix
* Return: output format, or 0 on error
*
* Notes:
* (1) This should only be called if the requested format is IFF_DEFAULT.
* (2) If the pix wasn't read from a file, its input format value
* will be IFF_UNKNOWN, and in that case it is written out
* in a compressed but lossless format.
*/
l_int32
pixChooseOutputFormat(PIX *pix)
{
l_int32 d, format;
PROCNAME("pixChooseOutputFormat");
if (!pix)
{
return ERROR_INT("pix not defined", procName, 0);
}
d = pixGetDepth(pix);
format = pixGetInputFormat(pix);
if (format == IFF_UNKNOWN) /* output lossless */
{
if (d == 1)
{
format = IFF_TIFF_G4;
}
else
{
format = IFF_PNG;
}
}
return format;
}
/*!
* getImpliedFileFormat()
*
* Input: filename
* Return: output format, or IFF_UNKNOWN on error or invalid extension.
*
* Notes:
* (1) This determines the output file format from the extension
* of the input filename.
*/
l_int32
getImpliedFileFormat(const char *filename)
{
char *extension;
int i, numext;
l_int32 format = IFF_UNKNOWN;
if (splitPathAtExtension (filename, NULL, &extension))
{
return IFF_UNKNOWN;
}
numext = sizeof(extension_map) / sizeof(extension_map[0]);
for (i = 0; i < numext; i++)
{
if (!strcmp(extension, extension_map[i].extension))
{
format = extension_map[i].format;
break;
}
}
FREE(extension);
return format;
}
/*!
* getFormatExtension()
*
* Input: format (integer)
* Return: extension (string), or null if format is out of range
*
* Notes:
* (1) This string is NOT owned by the caller; it is just a pointer
* to a global string. Do not free it.
*/
const char *
getFormatExtension(l_int32 format)
{
PROCNAME("getFormatExtension");
if (format < 0 || format >= NumImageFileFormatExtensions)
{
return (const char *)ERROR_PTR("invalid format", procName, NULL);
}
return ImageFileFormatExtensions[format];
}
/*---------------------------------------------------------------------*
* Write to memory *
*---------------------------------------------------------------------*/
/*!
* pixWriteMem()
*
* Input: &data (<return> data of tiff compressed image)
* &size (<return> size of returned data)
* pix
* format (defined in imageio.h)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) On windows, this will only write tiff and PostScript to memory.
* For other formats, it requires open_memstream(3).
* (2) PostScript output is uncompressed, in hex ascii.
* Most printers support level 2 compression (tiff_g4 for 1 bpp,
* jpeg for 8 and 32 bpp).
*/
l_int32
pixWriteMem(l_uint8 **pdata,
size_t *psize,
PIX *pix,
l_int32 format)
{
l_int32 ret;
PROCNAME("pixWriteMem");
if (!pdata)
{
return ERROR_INT("&data not defined", procName, 1 );
}
if (!psize)
{
return ERROR_INT("&size not defined", procName, 1 );
}
if (!pix)
{
return ERROR_INT("&pix not defined", procName, 1 );
}
if (format == IFF_DEFAULT)
{
format = pixChooseOutputFormat(pix);
}
switch(format)
{
case IFF_BMP:
ret = pixWriteMemBmp(pdata, psize, pix);
break;
case IFF_JFIF_JPEG: /* default quality; baseline sequential */
ret = pixWriteMemJpeg(pdata, psize, pix, 75, 0);
break;
case IFF_PNG: /* no gamma value stored */
ret = pixWriteMemPng(pdata, psize, pix, 0.0);
break;
case IFF_TIFF: /* uncompressed */
case IFF_TIFF_PACKBITS: /* compressed, binary only */
case IFF_TIFF_RLE: /* compressed, binary only */
case IFF_TIFF_G3: /* compressed, binary only */
case IFF_TIFF_G4: /* compressed, binary only */
case IFF_TIFF_LZW: /* compressed, all depths */
case IFF_TIFF_ZIP: /* compressed, all depths */
ret = pixWriteMemTiff(pdata, psize, pix, format);
break;
case IFF_PNM:
ret = pixWriteMemPnm(pdata, psize, pix);
break;
case IFF_PS:
ret = pixWriteMemPS(pdata, psize, pix, NULL, 0, DEFAULT_SCALING);
break;
case IFF_GIF:
ret = pixWriteMemGif(pdata, psize, pix);
break;
case IFF_JP2:
ret = pixWriteMemJp2k(pdata, psize, pix, 34, 0, 0);
break;
case IFF_WEBP:
ret = pixWriteMemWebP(pdata, psize, pix, 80, 0);
break;
case IFF_LPDF:
ret = pixWriteMemPdf(pdata, psize, pix, 0, NULL);
break;
case IFF_SPIX:
ret = pixWriteMemSpix(pdata, psize, pix);
break;
default:
return ERROR_INT("unknown format", procName, 1);
break;
}
return ret;
}
/*---------------------------------------------------------------------*
* Image display for debugging *
*---------------------------------------------------------------------*/
/*!
* pixDisplay()
*
* Input: pix (1, 2, 4, 8, 16, 32 bpp)
* x, y (location of display frame on the screen)
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) This displays the image using xzgv, xli or xv on Unix,
* or i_view on Windows. The display program must be on
* your $PATH variable. It is chosen by setting the global
* var_DISPLAY_PROG, using l_chooseDisplayProg().
* Default on Unix is xzgv.
* (2) Images with dimensions larger than MAX_DISPLAY_WIDTH or
* MAX_DISPLAY_HEIGHT are downscaled to fit those constraints.
* This is particulary important for displaying 1 bpp images
* with xv, because xv automatically downscales large images
* by subsampling, which looks poor. For 1 bpp, we use
* scale-to-gray to get decent-looking anti-aliased images.
* In all cases, we write a temporary file to /tmp, that is
* read by the display program.
* (3) For spp == 4, we call pixDisplayLayersRGBA() to show 3
* versions of the image: the image with a fully opaque
* alpha, the alpha, and the image as it would appear with
* a white background.
* (4) Note: this function uses a static internal variable to number
* output files written by a single process. Behavior with a
* shared library may be unpredictable.
*/
l_int32
pixDisplay(PIX *pixs,
l_int32 x,
l_int32 y)
{
return pixDisplayWithTitle(pixs, x, y, NULL, 1);
}
/*!
* pixDisplayWithTitle()
*
* Input: pix (1, 2, 4, 8, 16, 32 bpp)
* x, y (location of display frame)
* title (<optional> on frame; can be NULL);
* dispflag (1 to write, else disabled)
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) See notes for pixDisplay().
* (2) This displays the image if dispflag == 1.
*/
l_int32
pixDisplayWithTitle(PIX *pixs,
l_int32 x,
l_int32 y,
const char *title,
l_int32 dispflag)
{
char *tempname;
char buffer[L_BUF_SIZE];
static l_int32 index = 0; /* caution: not .so or thread safe */
l_int32 w, h, d, spp, maxheight, opaque, threeviews, ignore;
l_float32 ratw, rath, ratmin;
PIX *pix0, *pix1, *pix2;
PIXCMAP *cmap;
#ifndef _WIN32
l_int32 wt, ht;
#else
char *pathname;
char fullpath[_MAX_PATH];
#endif /* _WIN32 */
PROCNAME("pixDisplayWithTitle");
if (dispflag != 1)
{
return 0;
}
if (!pixs)
{
return ERROR_INT("pixs not defined", procName, 1);
}
if (var_DISPLAY_PROG != L_DISPLAY_WITH_XZGV &&
var_DISPLAY_PROG != L_DISPLAY_WITH_XLI &&
var_DISPLAY_PROG != L_DISPLAY_WITH_XV &&
var_DISPLAY_PROG != L_DISPLAY_WITH_IV &&
var_DISPLAY_PROG != L_DISPLAY_WITH_OPEN)
{
return ERROR_INT("no program chosen for display", procName, 1);
}
/* Display with three views if either spp = 4 or if colormapped
* and the alpha component is not fully opaque */
opaque = TRUE;
if ((cmap = pixGetColormap(pixs)) != NULL)
{
pixcmapIsOpaque(cmap, &opaque);
}
spp = pixGetSpp(pixs);
threeviews = (spp == 4 || !opaque) ? TRUE : FALSE;
/* If colormapped and not opaque, remove the colormap to RGBA */
if (!opaque)
{
pix0 = pixRemoveColormap(pixs, REMOVE_CMAP_WITH_ALPHA);
}
else
{
pix0 = pixClone(pixs);
}
/* Scale if necessary; this will also remove a colormap */
pixGetDimensions(pix0, &w, &h, &d);
maxheight = (threeviews) ? MAX_DISPLAY_HEIGHT / 3 : MAX_DISPLAY_HEIGHT;
if (w <= MAX_DISPLAY_WIDTH && h <= maxheight)
{
if (d == 16) /* take MSB */
{
pix1 = pixConvert16To8(pix0, 1);
}
else
{
pix1 = pixClone(pix0);
}
}
else
{
ratw = (l_float32)MAX_DISPLAY_WIDTH / (l_float32)w;
rath = (l_float32)maxheight / (l_float32)h;
ratmin = L_MIN(ratw, rath);
if (ratmin < 0.125 && d == 1)
{
pix1 = pixScaleToGray8(pix0);
}
else if (ratmin < 0.25 && d == 1)
{
pix1 = pixScaleToGray4(pix0);
}
else if (ratmin < 0.33 && d == 1)
{
pix1 = pixScaleToGray3(pix0);
}
else if (ratmin < 0.5 && d == 1)
{
pix1 = pixScaleToGray2(pix0);
}
else
{
pix1 = pixScale(pix0, ratmin, ratmin);
}
}
pixDestroy(&pix0);
if (!pix1)
{
return ERROR_INT("pix1 not made", procName, 1);
}
/* Generate the three views if required */
if (threeviews)
{
pix2 = pixDisplayLayersRGBA(pix1, 0xffffff00, 0);
}
else
{
pix2 = pixClone(pix1);
}
if (index == 0)
{
lept_rmdir("disp");
lept_mkdir("disp");
}
index++;
if (pixGetDepth(pix2) < 8 ||
(w < MAX_SIZE_FOR_PNG && h < MAX_SIZE_FOR_PNG))
{
snprintf(buffer, L_BUF_SIZE, "/tmp/disp/write.%03d.png", index);
pixWrite(buffer, pix2, IFF_PNG);
}
else
{
snprintf(buffer, L_BUF_SIZE, "/tmp/disp/write.%03d.jpg", index);
pixWrite(buffer, pix2, IFF_JFIF_JPEG);
}
tempname = genPathname(buffer, NULL);
#ifndef _WIN32
/* Unix */
if (var_DISPLAY_PROG == L_DISPLAY_WITH_XZGV)
{
/* no way to display title */
pixGetDimensions(pix2, &wt, &ht, NULL);
snprintf(buffer, L_BUF_SIZE,
"xzgv --geometry %dx%d+%d+%d %s &", wt + 10, ht + 10,
x, y, tempname);
}
else if (var_DISPLAY_PROG == L_DISPLAY_WITH_XLI)
{
if (title)
{
snprintf(buffer, L_BUF_SIZE,
"xli -dispgamma 1.0 -quiet -geometry +%d+%d -title \"%s\" %s &",
x, y, title, tempname);
}
else
{
snprintf(buffer, L_BUF_SIZE,
"xli -dispgamma 1.0 -quiet -geometry +%d+%d %s &",
x, y, tempname);
}
}
else if (var_DISPLAY_PROG == L_DISPLAY_WITH_XV)
{
if (title)
{
snprintf(buffer, L_BUF_SIZE,
"xv -quit -geometry +%d+%d -name \"%s\" %s &",
x, y, title, tempname);
}
else
{
snprintf(buffer, L_BUF_SIZE,
"xv -quit -geometry +%d+%d %s &", x, y, tempname);
}
}
else if (var_DISPLAY_PROG == L_DISPLAY_WITH_OPEN)
{
snprintf(buffer, L_BUF_SIZE, "open %s &", tempname);
}
ignore = system(buffer);
#else /* _WIN32 */
/* Windows: L_DISPLAY_WITH_IV */
pathname = genPathname(tempname, NULL);
_fullpath(fullpath, pathname, sizeof(fullpath));
if (title)
{
snprintf(buffer, L_BUF_SIZE,
"i_view32.exe \"%s\" /pos=(%d,%d) /title=\"%s\"",
fullpath, x, y, title);
}
else
{
snprintf(buffer, L_BUF_SIZE, "i_view32.exe \"%s\" /pos=(%d,%d)",
fullpath, x, y);
}
ignore = system(buffer);
FREE(pathname);
#endif /* _WIN32 */
pixDestroy(&pix1);
pixDestroy(&pix2);
FREE(tempname);
return 0;
}
/*!
* pixDisplayMultiple()
*
* Input: filepattern
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) This allows display of multiple images using gthumb on unix
* and i_view32 on windows. The @filepattern is a regular
* expression that is expanded by the shell.
* (2) _fullpath automatically changes '/' to '\' if necessary.
*/
l_int32
pixDisplayMultiple(const char *filepattern)
{
char buffer[L_BUF_SIZE];
l_int32 ignore;
#ifdef _WIN32
char *pathname;
char *dir, *tail;
char fullpath[_MAX_PATH];
#endif /* _WIN32 */
PROCNAME("pixDisplayMultiple");
if (!filepattern || strlen(filepattern) == 0)
{
return ERROR_INT("filepattern not defined", procName, 1);
}
#ifndef _WIN32
snprintf(buffer, L_BUF_SIZE, "gthumb %s &", filepattern);
#else
/* irFanView wants absolute path for directory */
pathname = genPathname(filepattern, NULL);
splitPathAtDirectory(pathname, &dir, &tail);
_fullpath(fullpath, dir, sizeof(fullpath));
snprintf(buffer, L_BUF_SIZE,
"i_view32.exe \"%s\" /filepattern=\"%s\" /thumbs", fullpath, tail);
FREE(pathname);
FREE(dir);
FREE(tail);
#endif /* _WIN32 */
ignore = system(buffer); /* gthumb || i_view32.exe */
return 0;
}
/*!
* pixDisplayWrite()
*
* Input: pix (1, 2, 4, 8, 16, 32 bpp)
* reduction (-1 to reset/erase; 0 to disable;
* otherwise this is a reduction factor)
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) This defaults to jpeg output for pix that are 32 bpp or
* 8 bpp without a colormap. If you want to write all images
* losslessly, use format == IFF_PNG in pixDisplayWriteFormat().
* (2) See pixDisplayWriteFormat() for usage details.
*/
l_int32
pixDisplayWrite(PIX *pixs,
l_int32 reduction)
{
return pixDisplayWriteFormat(pixs, reduction, IFF_JFIF_JPEG);
}
/*!
* pixDisplayWriteFormat()
*
* Input: pix (1, 2, 4, 8, 16, 32 bpp)
* reduction (-1 to reset/erase; 0 to disable;
* otherwise this is a reduction factor)
* format (IFF_PNG or IFF_JFIF_JPEG)
* Return: 0 if OK; 1 on error
*
* Notes:
* (1) This writes files if reduction > 0. These can be displayed using
* pixDisplayMultiple("/tmp/display/file*");
* (2) All previously written files can be erased by calling with
* reduction < 0; the value of pixs is ignored.
* (3) If reduction > 1 and depth == 1, this does a scale-to-gray
* reduction.
* (4) This function uses a static internal variable to number
* output files written by a single process. Behavior
* with a shared library may be unpredictable.
* (5) Output file format is as follows:
* format == IFF_JFIF_JPEG:
* png if d < 8 or d == 16 or if the output pix
* has a colormap. Otherwise, output is jpg.
* format == IFF_PNG:
* png (lossless) on all images.
* (6) For 16 bpp, the choice of full dynamic range with log scale
* is the best for displaying these images. Alternative outputs are
* pix8 = pixMaxDynamicRange(pixt, L_LINEAR_SCALE);
* pix8 = pixConvert16To8(pixt, 0); // low order byte
* pix8 = pixConvert16To8(pixt, 1); // high order byte
*/
l_int32
pixDisplayWriteFormat(PIX *pixs,
l_int32 reduction,
l_int32 format)
{
char buf[L_BUF_SIZE];
char *fname;
l_float32 scale;
PIX *pixt, *pix8;
static l_int32 index = 0; /* caution: not .so or thread safe */
PROCNAME("pixDisplayWriteFormat");
if (reduction == 0)
{
return 0;
}
if (reduction < 0)
{
index = 0; /* reset; this will cause erasure at next call to write */
return 0;
}
if (format != IFF_JFIF_JPEG && format != IFF_PNG)
{
return ERROR_INT("invalid format", procName, 1);
}
if (!pixs)
{
return ERROR_INT("pixs not defined", procName, 1);
}
if (index == 0)
{
lept_rmdir("display");
lept_mkdir("display");
}
index++;
if (reduction == 1)
{
pixt = pixClone(pixs);
}
else
{
scale = 1. / (l_float32)reduction;
if (pixGetDepth(pixs) == 1)
{
pixt = pixScaleToGray(pixs, scale);
}
else
{
pixt = pixScale(pixs, scale, scale);
}
}
if (pixGetDepth(pixt) == 16)
{
pix8 = pixMaxDynamicRange(pixt, L_LOG_SCALE);
snprintf(buf, L_BUF_SIZE, "file.%03d.png", index);
fname = genPathname("/tmp/display", buf);
pixWrite(fname, pix8, IFF_PNG);
pixDestroy(&pix8);
}
else if (pixGetDepth(pixt) < 8 || pixGetColormap(pixt) ||
format == IFF_PNG)
{
snprintf(buf, L_BUF_SIZE, "file.%03d.png", index);
fname = genPathname("/tmp/display", buf);
pixWrite(fname, pixt, IFF_PNG);
}
else
{
snprintf(buf, L_BUF_SIZE, "file.%03d.jpg", index);
fname = genPathname("/tmp/display", buf);
pixWrite(fname, pixt, format);
}
FREE(fname);
pixDestroy(&pixt);
return 0;
}
/*!
* pixSaveTiled()
*
* Input: pixs (1, 2, 4, 8, 32 bpp)
* pixa (the pix are accumulated here)
* scalefactor (0.0 to disable; otherwise this is a scale factor)
* newrow (0 if placed on the same row as previous; 1 otherwise)
* space (horizontal and vertical spacing, in pixels)
* dp (depth of pixa; 8 or 32 bpp; only used on first call)
* Return: 0 if OK, 1 on error.
*/
l_int32
pixSaveTiled(PIX *pixs,
PIXA *pixa,
l_float32 scalefactor,
l_int32 newrow,
l_int32 space,
l_int32 dp)
{
/* Save without an outline */
return pixSaveTiledOutline(pixs, pixa, scalefactor, newrow, space, 0, dp);
}
/*!
* pixSaveTiledOutline()
*
* Input: pixs (1, 2, 4, 8, 32 bpp)
* pixa (the pix are accumulated here)
* scalefactor (0.0 to disable; otherwise this is a scale factor)
* newrow (0 if placed on the same row as previous; 1 otherwise)
* space (horizontal and vertical spacing, in pixels)
* linewidth (width of added outline for image; 0 for no outline)
* dp (depth of pixa; 8 or 32 bpp; only used on first call)
* Return: 0 if OK, 1 on error.
*
* Notes:
* (1) Before calling this function for the first time, use
* pixaCreate() to make the @pixa that will accumulate the pix.
* This is passed in each time pixSaveTiled() is called.
* (2) @scalefactor scales the input image. After scaling and
* possible depth conversion, the image is saved in the input
* pixa, along with a box that specifies the location to
* place it when tiled later. Disable saving the pix by
* setting @scalefactor == 0.0.
* (3) @newrow and @space specify the location of the new pix
* with respect to the last one(s) that were entered.
* (4) @dp specifies the depth at which all pix are saved. It can
* be only 8 or 32 bpp. Any colormap is removed. This is only
* used at the first invocation.
* (5) This function uses two variables from call to call.
* If they were static, the function would not be .so or thread
* safe, and furthermore, there would be interference with two or
* more pixa accumulating images at a time. Consequently,
* we use the first pix in the pixa to store and obtain both
* the depth and the current position of the bottom (one pixel
* below the lowest image raster line when laid out using
* the boxa). The bottom variable is stored in the input format
* field, which is the only field available for storing an int.
*/
l_int32
pixSaveTiledOutline(PIX *pixs,
PIXA *pixa,
l_float32 scalefactor,
l_int32 newrow,
l_int32 space,
l_int32 linewidth,
l_int32 dp)
{
l_int32 n, top, left, bx, by, bw, w, h, depth, bottom;
BOX *box;
PIX *pix1, *pix2, *pix3, *pix4;
PROCNAME("pixSaveTiledOutline");
if (scalefactor == 0.0)
{
return 0;
}
if (!pixs)
{
return ERROR_INT("pixs not defined", procName, 1);
}
if (!pixa)
{
return ERROR_INT("pixa not defined", procName, 1);
}
n = pixaGetCount(pixa);
if (n == 0)
{
bottom = 0;
if (dp != 8 && dp != 32)
{
L_WARNING("dp not 8 or 32 bpp; using 32\n", procName);
depth = 32;
}
else
{
depth = dp;
}
}
else /* extract the depth and bottom params from the first pix */
{
pix1 = pixaGetPix(pixa, 0, L_CLONE);
depth = pixGetDepth(pix1);
bottom = pixGetInputFormat(pix1); /* not typical usage! */
pixDestroy(&pix1);
}
/* Remove colormap if it exists; otherwise a copy. This
* guarantees that pix4 is not a clone of pixs. */
pix1 = pixRemoveColormapGeneral(pixs, REMOVE_CMAP_BASED_ON_SRC, L_COPY);
/* Scale and convert to output depth */
if (scalefactor == 1.0)
{
pix2 = pixClone(pix1);
}
else if (scalefactor > 1.0)
{
pix2 = pixScale(pix1, scalefactor, scalefactor);
}
else if (scalefactor < 1.0)
{
if (pixGetDepth(pix1) == 1)
{
pix2 = pixScaleToGray(pix1, scalefactor);
}
else
{
pix2 = pixScale(pix1, scalefactor, scalefactor);
}
}
pixDestroy(&pix1);
if (depth == 8)
{
pix3 = pixConvertTo8(pix2, 0);
}
else
{
pix3 = pixConvertTo32(pix2);
}
pixDestroy(&pix2);
/* Add black outline */
if (linewidth > 0)
{
pix4 = pixAddBorder(pix3, linewidth, 0);
}
else
{
pix4 = pixClone(pix3);
}
pixDestroy(&pix3);
/* Find position of current pix (UL corner plus size) */
if (n == 0)
{
top = 0;
left = 0;
}
else if (newrow == 1)
{
top = bottom + space;
left = 0;
}
else if (n > 0)
{
pixaGetBoxGeometry(pixa, n - 1, &bx, &by, &bw, NULL);
top = by;
left = bx + bw + space;
}
pixGetDimensions(pix4, &w, &h, NULL);
bottom = L_MAX(bottom, top + h);
box = boxCreate(left, top, w, h);
pixaAddPix(pixa, pix4, L_INSERT);
pixaAddBox(pixa, box, L_INSERT);
/* Save the new bottom value */
pix1 = pixaGetPix(pixa, 0, L_CLONE);
pixSetInputFormat(pix1, bottom); /* not typical usage! */
pixDestroy(&pix1);
return 0;
}
/*!
* pixSaveTiledWithText()
*
* Input: pixs (1, 2, 4, 8, 32 bpp)
* pixa (the pix are accumulated here; as 32 bpp)
* outwidth (in pixels; use 0 to disable entirely)
* newrow (1 to start a new row; 0 to go on same row as previous)
* space (horizontal and vertical spacing, in pixels)
* linewidth (width of added outline for image; 0 for no outline)
* bmf (<optional> font struct)
* textstr (<optional> text string to be added)
* val (color to set the text)
* location (L_ADD_ABOVE, L_ADD_AT_TOP, L_ADD_AT_BOT, L_ADD_BELOW)
* Return: 0 if OK, 1 on error.
*
* Notes:
* (1) Before calling this function for the first time, use
* pixaCreate() to make the @pixa that will accumulate the pix.
* This is passed in each time pixSaveTiled() is called.
* (2) @outwidth is the scaled width. After scaling, the image is
* saved in the input pixa, along with a box that specifies
* the location to place it when tiled later. Disable saving
* the pix by setting @outwidth == 0.
* (3) @newrow and @space specify the location of the new pix
* with respect to the last one(s) that were entered.
* (4) All pix are saved as 32 bpp RGB.
* (5) If both @bmf and @textstr are defined, this generates a pix
* with the additional text; otherwise, no text is written.
* (6) The text is written before scaling, so it is properly
* antialiased in the scaled pix. However, if the pix on
* different calls have different widths, the size of the
* text will vary.
* (7) See pixSaveTiledOutline() for other implementation details.
*/
l_int32
pixSaveTiledWithText(PIX *pixs,
PIXA *pixa,
l_int32 outwidth,
l_int32 newrow,
l_int32 space,
l_int32 linewidth,
L_BMF *bmf,
const char *textstr,
l_uint32 val,
l_int32 location)
{
PIX *pix1, *pix2, *pix3, *pix4;
PROCNAME("pixSaveTiledWithText");
if (outwidth == 0)
{
return 0;
}
if (!pixs)
{
return ERROR_INT("pixs not defined", procName, 1);
}
if (!pixa)
{
return ERROR_INT("pixa not defined", procName, 1);
}
pix1 = pixConvertTo32(pixs);
if (linewidth > 0)
{
pix2 = pixAddBorder(pix1, linewidth, 0);
}
else
{
pix2 = pixClone(pix1);
}
if (bmf && textstr)
{
pix3 = pixAddSingleTextblock(pix2, bmf, textstr, val, location, NULL);
}
else
{
pix3 = pixClone(pix2);
}
pix4 = pixScaleToSize(pix3, outwidth, 0);
pixSaveTiled(pix4, pixa, 1.0, newrow, space, 32);
pixDestroy(&pix1);
pixDestroy(&pix2);
pixDestroy(&pix3);
pixDestroy(&pix4);
return 0;
}
void
l_chooseDisplayProg(l_int32 selection)
{
if (selection == L_DISPLAY_WITH_XLI ||
selection == L_DISPLAY_WITH_XZGV ||
selection == L_DISPLAY_WITH_XV ||
selection == L_DISPLAY_WITH_IV ||
selection == L_DISPLAY_WITH_OPEN)
{
var_DISPLAY_PROG = selection;
}
else
{
L_ERROR("invalid display program\n", "l_chooseDisplayProg");
}
return;
}
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "PuzzlePlatformers.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, PuzzlePlatformers, "PuzzlePlatformers" );
|
#ifndef BSCHEDULER_DAEMON_NETWORK_MASTER_HH
#define BSCHEDULER_DAEMON_NETWORK_MASTER_HH
#include <chrono>
#include <unordered_map>
#include <unordered_set>
#include <unistdx/net/interface_addresses>
#include <bscheduler/api.hh>
#include <bscheduler/daemon/master_discoverer.hh>
#include <bscheduler/ppl/socket_pipeline_event.hh>
namespace bsc {
class network_timer: public bsc::kernel {};
class network_master: public bsc::kernel {
private:
typedef sys::ipv4_address addr_type;
typedef addr_type::rep_type uint_type;
typedef sys::interface_address<addr_type> ifaddr_type;
typedef typename sys::ipaddr_traits<addr_type> traits_type;
typedef std::unordered_set<ifaddr_type> set_type;
typedef std::unordered_map<ifaddr_type,master_discoverer*> map_type;
typedef typename map_type::iterator map_iterator;
private:
map_type _ifaddrs;
set_type _allowedifaddrs;
uint_type _fanout = 10000;
network_timer* _timer = nullptr;
/// Interface address list update interval.
std::chrono::milliseconds _interval = std::chrono::seconds(1);
public:
void
act() override;
void
react(bsc::kernel* child) override;
inline void
fanout(uint_type rhs) noexcept {
this->_fanout = rhs;
}
inline void
allow(const ifaddr_type& rhs) {
if (rhs) {
this->_allowedifaddrs.emplace(rhs);
}
}
inline void
interval(std::chrono::milliseconds rhs) noexcept {
this->_interval = rhs;
}
private:
void
send_timer();
set_type
enumerate_ifaddrs();
void
update_ifaddrs();
void
add_ifaddr(const ifaddr_type& rhs);
void
remove_ifaddr(const ifaddr_type& rhs);
/// forward the probe to an appropriate discoverer
void
forward_probe(probe* p);
void
forward_hierarchy_kernel(hierarchy_kernel* p);
map_iterator
find_discoverer(const addr_type& a);
void
on_event(socket_pipeline_kernel* k);
inline bool
is_allowed(const ifaddr_type& rhs) const {
for (const ifaddr_type& ifa : this->_allowedifaddrs) {
if (ifa.contains(rhs.address())) {
return true;
}
}
return false;
}
};
}
#endif // vim:filetype=cpp
|
#ifndef __LINBOX_matrix_SlicedPolynomialMatrix_SlicedPolynomialMatrixMulKaratsuba_INL
#define __LINBOX_matrix_SlicedPolynomialMatrix_SlicedPolynomialMatrixMulKaratsuba_INL
#include <givaro/givpoly1dense.h>
#include <givaro/givpoly1denseops.inl>
#include "linbox/matrix/MatrixDomain/blas-matrix-domain.h"
#include "linbox/vector/vector-domain.h"
#include "fflas-ffpack/fflas/fflas.h"
#include <vector>
#include <stdlib.h>
#include <stdint.h>
namespace LinBox
{
template<class Field, class Vector3, class Vector1, class Vector2>
SlicedPolynomialMatrixMulKaratsuba<Field, Vector3, Vector1, Vector2 >::vec&
SlicedPolynomialMatrixMulKaratsuba<Field, Vector3, Vector1, Vector2 >::karatsuba(IntField& F, VectorDomain<Vector3::IntField>& VD,
vecV& C, vecM& A, vecV& B, size_t rd, size_t cd)
{
if (A.size() == 1)
{
for (int i = 0; i <B.size(); i++)
{
FFLAS::fgemv(F, FflasNoTrans, rd, cd, F.one, A[0].getPointer(), cd, B[i].getPointer(), 1, F.zero, C[i].getWritePointer(), 1);
}
return C;
}
if (B.size() == 1)
{
for (int i = 0; i < A.size(); i++)
{
FFLAS::fgemv(F, FflasNoTrans, rd, cd, F.one, A[i].getPointer(), cd, B[0].getPointer(), 1, F.zero, C[i].getWritePointer(), 1);
}
return C;
}
int m = (A.size() < B.size()) ? (B.size() / 2) : (A.size() / 2);
if ((m < A.size()) && (m < B.size()))
{
vecM A1(A.begin(), A.begin() + m);
vecM A2(A.begin() + m, A.end());
vecV B1(B.begin(), B.begin() + m);
vecV B2(B.begin() + m, B.end());
vecM A3;
int minlength_a = (A1.size() < A2.size()) ? A1.size() : A2.size();
int minlength_a = (A1.size() < A2.size()) ? A2.size() : A1.size();
for (int i = 0; i < minlength_a; i++)
{
Matrix AA(F, rd, cd);
A3.push_back(BlasMatrixDomainAdd<IntField, Matrix, Matrix, Matrix>()(F, AA, A1[i], A2[i]));
}
if (maxlength_a == A1.size())
{
for (int i = minlength_a; i < maxlength_a; i++)
{
A3.push_back(A1[i]);
}
}
else
{
for (int i = minlength_a; i < maxlength_a; i++)
{
A3.push_back(A2[i]);
}
}
vecV B3;
int minlength_b = (B1.size() < B2.size()) ? B1.size() : B2.size();
int maxlength_b = (B1.size() < B2.size()) ? B2.size() : B1.size();
for (int i = 0; i < minlength_b; i++)
{
Vector BB(F, cd);
B3.push_back(VD.add<Vector, Vector, Vector>(BB, B1[i], B2[i]));
}
if (maxlength_b == B1.size())
{
for (int i = minlength_b; i < maxlength_b; i++)
{
B3.push_back(B1[i]);
}
}
else
{
for (int i = minlength_b; i < maxlength_b; i++)
{
B3.push_back(B2[i]);
}
}
vecV C1;
vecV C2;
vecV C3;
Matrix CC(F, rd);
int xx;
xx = A1.size() + B1.size() - 1;
for (int i = 0; i < xx; i++)
{
C1.push_back(CC);
}
xx = A2.size() + B2.size() - 1;
for (int i = 0; i < xx; i++)
{
C2.push_back(CC);
}
xx = A3.size() + B3.size() - 1;
for (int i = 0; i < xx; i++)
{
C3.push_back(CC);
}
karatsuba(F, VD, C1, A1, B1);
karatsuba(F, VD, C2, A2, B2);
karatsuba(F, VD, C3, A3, B3);
for (int i = 0; i < C1.size(); i++)
{
VD.addin<Vector, Vector>(C[i], C1[i]);
}
int mm = 2 * m;
for (int i = 0; i < C2.size(); i++)
{
VD.addin<Vector, Vector>(C[mm + i], C2[i]);
}
for (int i = 0; i < C3.size(); i++)
{
VD.addin<Vector, Vector>(C[m + i], C3[i]);
}
for (int i = 0; i < C1.size(); i++)
{
VD.subin<Vector, Vector>(C[m + i], C1[i]);
}
for (int i = 0; i < C2.size(); i++)
{
VD.subin<Vector, Vector>(C[m + i], C2[i]);
}
return C;
}
if (A.size() <= m)
{
vecV B1(B.begin(), B.begin() + m);
vecV B2(B.begin() + m, B.end());
vecV C1;
vecV C2;
Vector CC(F, rd);
int xx;
xx = A.size() + B1.size() - 1;
for (int i = 0; i < xx; i++)
{
C1.push_back(CC);
}
xx = A.size() + B2.size() - 1;
for (int i = 0; i < xx; i++)
{
C2.push_back(CC);
}
karatsuba(F, VD, C1, A, B1);
karatsuba(F, VD, C2, A, B2);
for (int i = 0; i < C1.size(); i++)
{
VD.addin<Vector, Vector>(C[i], C1[i]);
}
for (int i = 0; i < C2.size(); i++)
{
VD.addin<Vector, Vector>(C[m + i], C2[i]);
}
return C;
}
if (B.size() <= m)
{
vecM A1(A.begin(), A.begin() + m);
vecM A2(A.begin() + m, A.end());
vecV C1;
vecV C2;
Matrix CC(F, rd);
int xx;
xx = A1.size() + B.size() - 1;
for (int i = 0; i < xx; i++)
{
C1.push_back(CC);
}
xx = A2.size() + B.size() - 1;
for (int i = 0; i < xx; i++)
{
C2.push_back(CC);
}
karatsuba(F, VD, C1, A1, B);
karatsuba(F, VD, C2, A2, B);
for (int i = 0; i < C1.size(); i++)
{
VD.addin<Vector, Vector>(C[i], C1[i]);
}
for (int i = 0; i < C2.size(); i++)
{
VD.addin<Vector, Vector>(C[m + i], C2[i]);
}
return C;
}
return C;
}
template<class Field, class Vector3, class Vector1, class Vector2>
Vector1& SlicedPolynomialMatrixMulKaratsuba<Field, Vector3, Vector1, Vector2 >::operator()(const Field& GF,
Vector3& C,
const Vector1& A,
const Vector2& B) const
{
//check dimensions
int xx;
vecV A1;
vecM B1;
xx = A.length();
for (int m = 0; m < xx; m++)
{
A1.push_back(A.getMatrixCoefficient(m));
}
xx = B.length();
for (int m = 0; m < xx; m++)
{
B1.push_back(B.getVectorCoefficient(m));
}
vecV C1;
xx = A1.size() + B1.size() - 1;
Vector CC(C.fieldF(), A.rowdim());
for (int i = 0; i < xx; i++)
{
C1.push_back(CC);
}
VectorDomain<IntField> VD(F);
karatsuba(C.fieldF(), VD, C1, A1, B1);
int mk = C1.size();
int mi = C1[0].rowdim();
int n = C.size();
Poly1Dom<IntField, Dense> PD(F);
for (int i = 0; i < mi; i++)
{
polynomial entry;
for (int k = 0; k < mk; k++)
{
entry.push_back(C1[k].getEntry(i));
}
PD.modin(entry, C.irreducible);
for (int k = 0; k < n; k++)
{
C[k].setEntry(i, w1[k]);
}
}
return C;
}
} // LinBox
#endif
|
#include <Arduino.h>
#include <ESP8266WebServer.h>
#include <PubSubClient.h>
#include <ESP_MQTTLogger.h>
#include "led_peripheral.h"
#define LED_PIN 2
LedPeripheral::LedPeripheral() {}
void LedPeripheral::begin(ESP_MQTTLogger& l) {
// set up the logger
_logger = l;
_updateable = true;
_publishable = false;
pinMode(LED_PIN, OUTPUT);
_state = false;
bool subbed = _logger.subscribe("ic/#");
if (! subbed) {
Serial.println("Couldn't subscribe to content messages");
_logger.publish("sys/error", "sub_fail");
} else {
_logger.publish("oc/status", "available");
}
}
void LedPeripheral::publish_data() {
// for an LED - this is a NOOP
}
void LedPeripheral::sub_handler(String topic, String payload) {
if ( topic.endsWith("led") ) {
// interpret the position.
// check explicitly for an "0" as str.toInt() returns 0 if type
// conversion isn't successful
if (payload == "1" || payload == "on") {
_state = true;
Serial.println("Turn on");
} else {
_state = false;
Serial.println("Turn off");
}
}
}
void LedPeripheral::update() {
// update the state of the LED
digitalWrite(LED_PIN, _state);
}
|
#include <iostream>
#include <cstdio>
using namespace std;
int x[100], y[100], z[100], i;
int KUCHKA1(int a1, int i)
{
}
int KUCHKA2(int a2, int i)
{
}
int KUCHKA3(int a3, int i)
{
}
void FUNKCIAPvP(int a)
{
int a1, a2, a3, k;
for (i = 0;i < a;i++)
{
x[i]++;
y[i]++;
z[i]++;
}
a1 = a;
a2 = a;
a3 = a;
cout << "Выберите одну из трех кучек: ";
cin >> k;
cout << "Ведите колчество спичек которые выхотите вытащить: ";
cin >> i;
if (k == 1)
{
KUCHKA1(a1, i);
}
else
{
if (k == 2)
{
KUCHKA2(a2, i);
}
else
{
if (k == 3)
{
KUCHKA3(a3, i);
}
else
{
cin >> "ERROR";
}
}
}
}
void FUNKCIAPvE(int a)
{
for (i = 0;i < a;i++)
{
x[i]++;
y[i]++;
z[i]++;
}
}
void FUNKCIAEvE(int a)
{
for (i = 0;i < a;i++)
{
x[i]++;
y[i]++;
z[i]++;
}
}
int main()
{
int j, a, PvP, PvE, EvE;
cout << "ВЫБЕРИТЕ РЕЖИМ: 1)PvP 2)PvE 3)EvE" << endl << "Напишите номер выбранного режима";
cin >> j;
if (j == 1)
{
cout << "Введите размер кучек" << endl;
cin >> a;
FUNKCIAPvP(a);
}
else
if (j == 2)
{
cout << "Введите размер кучек" << endl;
cin >> a;
FUNKCIAPvE(a);
}
else
if (j == 3)
{
cout << "Введите размер кучек" << endl;
cin >> a;
FUNKCIAEvE(a);
}
else
{
cin >> "ERROR";
}
return 0;
}
|
#include "Video.h"
namespace photon {
int num_initialized = 0;
};
void photon::Video::initialize() {
if(num_initialized == 0)
SDL_Init(SDL_INIT_VIDEO);
num_initialized++;
}
void photon::Video::destroy() {
num_initialized--;
if(num_initialized == 0)
SDL_Quit();
}
|
/**
* This is an example demonstrating the use of the LiFuelGauge library
* The example uses an LCD display to show battery status information
* When an Alert Threshold interrupt is generated, the lowPower ISR is
* called and the a sign appears on the LCD display
*
* Note:
* After exiting sleep mode or resetting, give the MAX17043/4
* half a second to perform the first measurements
*/
#include <LiquidCrystal.h>
#include <Wire.h>
#include <LiFuelGauge.h>
// Creates a LiquidCrystal instance with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);
// LiFuelGauge constructor parameters
// 1. IC type, MAX17043 or MAX17044
// 2. Number of interrupt to which the alert pin is associated (Optional)
// 3. ISR to call when an alert interrupt is generated (Optional)
//
// Creates a LiFuelGauge instance for the MAX17043 IC
// and attaches lowPower to INT0 (PIN2 on most boards, PIN3 on Leonardo)
LiFuelGauge gauge(MAX17043, 0, lowPower);
// A flag to indicate a generated alert interrupt
volatile boolean alert = false;
void setup()
{
lcd.begin(16, 2); // Sets up the LCD's number of columns and rows
gauge.reset(); // Resets MAX17043
delay(200); // Waits for the initial measurements to be made
setAThres();
setTemplate();
}
void loop()
{
lcd.setCursor(5,0);
lcd.print(gauge.getSOC()); // Gets the battery's state of charge
lcd.setCursor(7,1);
lcd.print(gauge.getVoltage()); // Gets the battery voltage
if ( alert )
{
lcd.clear();
lcd.print("Beware,");
lcd.setCursor(0,1);
lcd.print("Low Power!");
while ( true )
{
lcd.display();
delay(1000);
lcd.noDisplay();
delay(1000);
}
}
delay(2000);
}
void lowPower() { alert = true; }
// Sets the Alert Threshold to 10% of full capacity
// and informs on the LCD display
void setAThres()
{
gauge.setAlertThreshold(10);
lcd.print("Alert Threshold");
lcd.setCursor(0,1);
lcd.print("is set to ");
lcd.print(gauge.getAlertThreshold());
lcd.print('%');
delay(4000);
}
// Prints some labels on the LCD display
void setTemplate()
{
lcd.clear();
lcd.print("SOC: %");
lcd.setCursor(0,1);
lcd.print("VCELL: V");
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve(){
ll n,x;cin>>n;
vector<int>a(n+1);
for(int i=0;i<n;i++) {
cin>>x;
a[x]=i+1;
}
int l=1,ans=1;
for(int i=1;i<=n;i++){
if(l>a[i]) ans++;
l=a[i];
}
cout<<ans;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("op.txt","w",stdout);
#endif
int t=1;
//cin>>t;
while(t--){
solve();
}
}
|
#include "mpi.h"
// for local development
//#include "/usr/lib/openmpi/include/mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "mpi_openmp_barrier.h"
#include "../OpenMP/centralized/openmp_centralized_barrier.h"
#include <unistd.h>
#define ROUND 100
int main(int argc, char** argv){
if (argc != 2){
printf("wrong number of inputs\n");
exit(1);
}
int p_id, num_processes, thread_id, num_threads;
thread_id = -1;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_processes);
MPI_Comm_rank(MPI_COMM_WORLD, &p_id);
num_threads = *argv[1] - '0';
omp_set_num_threads(num_threads);
bool process_sense;
bool thread_sense = true;
OpenMP_Centralized_Barrier_Shared* s = new OpenMP_Centralized_Barrier_Shared;
Mpi_Openmp_Barrier mob(&process_sense, &thread_sense, &num_processes, &num_threads, s);
double time1, time2, total_sum, local_sum;
local_sum = 0;
for (int i=0; i<ROUND; i++){
time1 = MPI_Wtime();
#pragma omp parallel num_threads(num_threads) firstprivate(mob, thread_id) shared(s)
{
thread_id = omp_get_thread_num();
//printf("hello world from p%i:t%i of %i process and %i threads\n", p_id, thread_id, num_processes, num_threads);
//printf("p%i: t%i enters\n", p_id, thread_id);
mob.thread_sync(thread_id, s);
}
//threads are synced, now sync across processes
mob.process_sync(&process_sense, &p_id);
//printf("p%i exits with all threads synced\n", p_id);
time2 = MPI_Wtime();
local_sum += time2 - time1;
}
printf("rank %i spend %f seconds\n", p_id, local_sum);
MPI_Reduce(&local_sum, &total_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (p_id == 0){
double avg = total_sum/(1.0*ROUND*num_processes*num_threads);
printf("total time is %f seconds\n", total_sum);
printf("average time per process per thread per round: %f microseconds\n", avg*1000000);
}
MPI_Finalize();
return 0;
}
|
// Charlie Company Loadouts
// By SFC.Atherton.H version 0.1
// Squad
class Cav_B_C_AutomaticRifleman_F : Cav_B_Charlie_base_F { //General AR : 28kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_saw"};
primary[] = {"rhs_weap_m249_pip_S_para","rhsusf_acc_SFMB556","","rhsusf_acc_ELCAN"};
//secondary[] = {""};
//launcher[] = {""};
//binoculars[] = {""};
magazines[] = {
"rhsusf_200rnd_556x45_mixed_box",4,
"rhs_mag_m67",1,
"SmokeShell",3
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_Flashlight_XL50",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_RiflemanLAT_F : Cav_B_Charlie_base_F { //General Rifleman AT : 29kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
//primary[] = {};
//secondary[] = {""};
launcher[] = {"rhs_weap_M136_hp"};
//binoculars[] = {""};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_Rifleman_F : Cav_B_Charlie_base_F { //General Rifleman : ??kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_FireTeamLeader_F : Cav_B_Charlie_base_F { //General FTL : 27kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_grenadier"};
primary[] = {"rhs_weap_m4a1_m320","rhsusf_acc_SFMB556","rhsusf_acc_anpeq15_bk_light","rhsusf_acc_ACOG_RMR"};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red",8,
"rhs_mag_m67",2,
"SmokeShell",4,
"SmokeShellGreen",1,
"SmokeShellYellow",1,
"SmokeShellBlue",1,
"rhs_mag_M433_HEDP",7,
"1Rnd_Smoke_Grenade_shell",2,
"1Rnd_SmokeRed_Grenade_shell",2,
"ACE_HuntIR_M203",2
};
items[] = {
"ACRE_PRC152",
"ACE_microDAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
"ACE_HuntIR_monitor",
"ACE_SpraypaintBlack",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_Alpha_FireTeamLeader_F : Cav_B_C_FireTeamLeader_F {
items[] = {
"ACRE_PRC152",
"ACE_microDAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
"ACE_HuntIR_monitor",
"ACE_SpraypaintRed",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
};
class Cav_B_C_Bravo_FireTeamLeader_F : Cav_B_C_FireTeamLeader_F {
items[] = {
"ACRE_PRC152",
"ACE_microDAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
"ACE_HuntIR_monitor",
"ACE_SpraypaintBlue",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
};
class Cav_B_C_Grenadier_F : Cav_B_Charlie_base_F { //General GRN : 25kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_grenadier"};
primary[] = {"rhs_weap_m4a1_m320","rhsusf_acc_SFMB556","rhsusf_acc_anpeq15_bk_light","rhsusf_acc_compm4"};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",2,
"SmokeShell",4,
"rhs_mag_M433_HEDP",7,
"1Rnd_Smoke_Grenade_shell",2,
"ACE_HuntIR_M203",2
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_SquadLeader_F : Cav_B_Charlie_base_F { //General SL : 24kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_squadleader"};
primary[] = {"rhs_weap_m4a1_carryhandle","rhsusf_acc_SFMB556","rhsusf_acc_anpeq15_bk_light","rhsusf_acc_ACOG_RMR"};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red",7,
"rhs_mag_m67",3,
"SmokeShell",4,
"SmokeShellRed",2,
"SmokeShellGreen",2,
"SmokeShellBlue",2
};
items[] = {
"ACE_microDAGR",
"ACRE_PRC152",2,
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
"ACE_HuntIR_monitor",
"ACE_Chemlight_HiGreen",
"ACE_Chemlight_HiBlue",
"ACE_SpraypaintBlack",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_Marksman_Local : Cav_B_Charlie_base_F { //DMR : 24kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_sniper"};
primary[] = {"rhs_weap_sr25_ec","rhsusf_acc_anpeq15side_bk","rhsusf_acc_su230a","rhsusf_acc_harris_bipod"};
//secondary[] = {""};
//launcher[] = {""};
//binoculars[] = {""};
magazines[] = {
"rhsusf_20Rnd_762x51_SR25_m993_Mag",7,
"rhs_mag_m67",2,
"SmokeShell",4
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_Flashlight_XL50",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
// AT Team
class Cav_B_C_AAT_Local : Cav_B_Charlie_base_F { //MAAWS Assistant : 30kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
//primary[] = {};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6,
"tf47_m3maaws_HE",1,
"tf47_m3maaws_HEAT",1
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_AT_Local : Cav_B_Charlie_base_F { //MAAWS Gunner : 37kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
//primary[] = {};
//secondary[] = {""};
launcher[] = {"tf47_m3maaws","tf47_optic_m3maaws"};
//binoculars[] = {""};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",3,
"SmokeShell",4,
"tf47_m3maaws_HE",1,
"tf47_m3maaws_HEAT",1
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
// MK19 Team
class Cav_B_C_Support_MK19_TeamLeader_Local : Cav_B_Charlie_base_F { //Mk.19 FTL : 27kg
backpack[] = {"RHS_Mk19_Tripod_Bag"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_teamleader_alt"};
primary[] = {"rhs_weap_m4a1_carryhandle","rhsusf_acc_SFMB556","rhsusf_acc_anpeq15_bk_light","rhsusf_acc_ACOG_RMR"};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",2,
"SmokeShell",4,
"SmokeShellGreen",1,
"SmokeShellYellow",1,
"SmokeShellBlue",1
};
items[] = {
"ACE_microDAGR",
"ACRE_PRC152",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_Support_MK19_Gunner_Local : Cav_B_Charlie_base_F { //Mk.19 Gun : 35kg
backpack[] = {"RHS_Mk19_Gun_Bag"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
//primary[] = {};
//secondary[] = {""};
//launcher[] = {""};
//binoculars[] = {""};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_Support_MK19_Assistant_Local : Cav_B_Charlie_base_F { //Mk.19 Tri : 28kg
backpack[] = {"RHS_Mk19_Tripod_Bag"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
//primary[] = {};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
// MMG Team
class CAV_Charlie_Machinegunner_TeamLeader_Local : Cav_B_Charlie_base_F { //MMG FTL : 29kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_teamleader_alt"};
primary[] = {"rhs_weap_m4a1_carryhandle","rhsusf_acc_SFMB556","rhsusf_acc_anpeq15_bk_light","rhsusf_acc_ACOG_RMR"};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red",8,
"rhs_mag_m67",2,
"SmokeShell",4,
"SmokeShellRed",2,
"SmokeShellGreen",2,
"rhsusf_100Rnd_762x51_m62_tracer",3
};
items[] = {
"ACE_microDAGR",
"ACRE_PRC152",
"ACE_IR_Strobe_Item",
"ACE_SpareBarrel",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class CAV_Charlie_Machinegunner_Local : Cav_B_Charlie_base_F { //MMG Gunner : 33kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_machinegunner"};
primary[] = {"rhs_weap_m240B","rhsusf_acc_ARDEC_M240","rhsusf_acc_anpeq15side_bk","rhsusf_acc_ACOG_MDO"};
//secondary[] = {""};
//launcher[] = {""};
//binoculars[] = {""};
magazines[] = {
"rhs_mag_m67",1,
"SmokeShell",4,
"rhsusf_100Rnd_762x51_m62_tracer",4
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_Flashlight_XL50",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
// Mortar Team
class Cav_B_C_Support_Mortar_AutomaticRifleman_Local : Cav_B_Charlie_base_F { //Mortar AR : 35kg
backpack[] = {"B_Mortar_01_support_F"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_saw"};
primary[] = {"rhs_weap_m249_pip_S_para","rhsusf_acc_SFMB556","rhsusf_acc_ELCAN"};
//secondary[] = {""};
//launcher[] = {""};
//binoculars[] = {""};
magazines[] = {
"rhs_mag_m67",1,
"SmokeShell",3,
"rhsusf_200rnd_556x45_mixed_box",4
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_Flashlight_XL50",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_Support_Mortar_TeamLeader_Local : Cav_B_Charlie_base_F { //Mortar FTL : 30kg
backpack[] = {"B_Mortar_01_support_F"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_teamleader_alt"};
primary[] = {"rhs_weap_m4a1_carryhandle","rhsusf_acc_SFMB556","rhsusf_acc_anpeq15_bk_light","rhsusf_acc_ACOG_RMR"};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red",8,
"rhs_mag_m67",2,
"SmokeShell",4,
"SmokeShellRed",2,
"SmokeShellGreen",2
};
items[] = {
"ACE_microDAGR",
"ACRE_PRC152",
"ACE_IR_Strobe_Item",
"ACE_RangeTable_82mm",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_Support_Mortar_Gunner_Local : Cav_B_Charlie_base_F { //Mortar Gunner : 38kg
backpack[] = {"B_Mortar_01_weapon_F"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
//primary[] = {};
//secondary[] = {""};
//launcher[] = {""};
//binoculars[] = {""};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_RangeTable_82mm",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_Support_Mortar_SquadLeader_Local : Cav_B_Charlie_base_F { //Mortar SL : 24kg
backpack[] = {"B_Mortar_01_weapon_F"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_squadleader"};
primary[] = {"rhs_weap_m4a1_carryhandle","rhsusf_acc_SFMB556","rhsusf_acc_anpeq15_bk_light","rhsusf_acc_ACOG_RMR"};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red",8,
"rhs_mag_m67",3,
"SmokeShell",4,
"SmokeShellRed",2,
"SmokeShellGreen",2,
"SmokeShellBlue",2
};
items[] = {
"ACE_microDAGR",
"ACRE_PRC152",2,
"ACE_IR_Strobe_Item",
"ACE_RangeTable_82mm",
"ACE_EntrenchingTool",
"ACE_HuntIR_monitor",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
// AA Team
class Cav_B_C_AAA_Local : Cav_B_Charlie_base_F { //Stinger Assist : 28kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
//primary[] = {};
//secondary[] = {""};
//launcher[] = {""};
//binoculars[] = {""};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6,
"rhs_fim92_mag",1
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_AA_Local : Cav_B_Charlie_base_F { //Stinger Gunner : 37kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
//primary[] = {};
//secondary[] = {""};
launcher[] = {"rhs_weap_fim92"};
//binoculars[] = {""};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6,
"rhs_fim92_mag",2
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
// TOW Team
class CAV_Charlie_TOWSFTL : Cav_B_Charlie_base_F { //TOWS FTL : 27kg
backpack[] = {"rhs_TOW_Tripod_Bag"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_teamleader_alt"};
primary[] = {"rhs_weap_m4a1_carryhandle","rhsusf_acc_SFMB556","rhsusf_acc_anpeq15_bk_light","rhsusf_acc_ACOG_RMR"};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red",8,
"rhs_mag_m67",2,
"SmokeShell",4
};
items[] = {
"ACE_microDAGR",
"ACRE_PRC152",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class CAV_Charlie_TOWSGUN : Cav_B_Charlie_base_F { //TOWS Gunner : 35kg
backpack[] = {"rhs_Tow_Gun_Bag"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
//primary[] = {};
//secondary[] = {""};
//launcher[] = {""};
//binoculars[] = {""};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class CAV_Charlie_TOWSTRI : Cav_B_Charlie_base_F { //TOWS Tripod : 28kg
backpack[] = {"rhs_TOW_Tripod_Bag"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
//primary[] = {};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"Binocular"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
// Staff
class Cav_B_C_Officer_F : Cav_B_Charlie_base_F { //Platoon Staff : 27kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_squadleader"};
primary[] = {"rhs_weap_m4a1_carryhandle","rhsusf_acc_SFMB556","rhsusf_acc_anpeq15_bk_light","rhsusf_acc_ACOG_RMR"};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red",7,
"rhs_mag_m67",3,
"SmokeShell",4,
"SmokeShellRed",3,
"SmokeShellGreen",3,
"SmokeShellBlue",3,
"SmokeShellYellow",3,
"SmokeShellPurple",3
};
items[] = {
"ACE_microDAGR",
"ACRE_PRC152",2,
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
"ACE_HuntIR_monitor",
"ACE_Chemlight_HiGreen",
"ACE_Chemlight_HiBlue",
"ACE_SpraypaintGreen",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class Cav_B_C_PlatoonMedic_F : Cav_B_Charlie_base_F { //Platoon Medic : 34kg
backpack[] = {"B_Kitbag_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_medic"};
//primary[] = {};
//secondary[] = {""};
//launcher[] = {""};
//binoculars[] = {""};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",1,
"SmokeShell",3,
"SmokeShellGreen",2,
"SmokeShellBlue",2,
"SmokeShellPurple",2
};
items[] = {
"ACE_microDAGR",
"ACRE_PRC152",2,
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
"ACE_HuntIR_monitor",
"ACE_Chemlight_HiRed",6,
"ACE_surgicalKit",
"ACE_salineIV",10,
"ACE_morphine",15,
"ACE_elasticBandage",40,
"ACE_quikclot",40,
"ACE_epinephrine",8,
"ACE_tourniquet",10,
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
class CAV_Charlie_CompanyStaff_F : Cav_B_Charlie_base_F { //Company Staff : 27kg
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_squadleader"};
primary[] = {"rhs_weap_m4a1_carryhandle","rhsusf_acc_SFMB556","rhsusf_acc_anpeq15_bk_light","rhsusf_acc_ACOG_RMR"};
//secondary[] = {""};
//launcher[] = {""};
binoculars[] = {"ACE_Vector"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red",7,
"rhs_mag_m67",3,
"SmokeShell",4,
"SmokeShellRed",3,
"SmokeShellGreen",3,
"SmokeShellBlue",3,
"SmokeShellYellow",3,
"SmokeShellPurple",3
};
items[] = {
"ACE_microDAGR",
"ACRE_PRC152",2,
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
"ACE_HuntIR_monitor",
"ACE_Chemlight_HiGreen",
"ACE_Chemlight_HiBlue",
"ACE_SpraypaintGreen",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools"
};
//compass[] = {"ItemCompass"};
gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
// Other
class Cav_B_C_CombatLifeSaver_F : Cav_B_Charlie_base_F {
//backpack[] = {"B_AssaultPack_mcamo"};
//goggles[] = {"rhs_googles_clear"};
headgear[] = {"rhsusf_ach_helmet_ocp"};
uniform[] = {"LOP_U_ISTS_Fatigue_19"};
vest[] = {"rhsusf_spcs_ocp_rifleman_alt"};
magazines[] = {
"rhs_mag_30Rnd_556x45_M855A1_Stanag",8,
"rhs_mag_m67",4,
"SmokeShell",6
};
items[] = {
"ACE_DAGR",
"ACE_IR_Strobe_Item",
"ACE_EntrenchingTool",
// Personal Medical Equipment
"ACE_quikclot",10,
"ACE_tourniquet",4,
// Standard
"ACE_MapTools",
// Medical Equipment
"ACE_personalAidKit",
"ACE_quikclot",20,
"ACE_tourniquet",6,
"ACE_morphine",6
};
//compass[] = {"ItemCompass"};
//gps[] = {""};
//map[] = {"ItemMap"};
nvgs[] = {"rhsusf_ANPVS_14"};
//watch[] = {"ItemWatch"};
//insignia[] = {""};
preLoadout = "[(_this select 0), 'charlie', 0, 0] call cScripts_fnc_setPreInitPlayerSettings;";
postLoadout = "[(_this select 0),true,true] call cScripts_fnc_setPostInitPlayerSettings;";
};
|
/*
Copyright (c) 2014, Martin Björkström
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "framefilter.h"
#include "imagefilterparameter.h"
#include <QPainter>
class FrameFilterWorker : public AbstractImageFilterWorker
{
public:
FrameFilterWorker(int horizontal, int vertical)
{
m_horizontal = horizontal / 200.0;
m_vertical = vertical / 200.0;
}
void doWork(const QImage &origin) {
QImage newImage(origin);
QPainter painter;
QLinearGradient gradientLeft(0,0,(qreal)newImage.width(),0);
gradientLeft.setColorAt(0, Qt::black);
gradientLeft.setColorAt(m_vertical, Qt::transparent);
QLinearGradient gradientRight((qreal)newImage.width(),0,0,0);
gradientRight.setColorAt(0, Qt::black);
gradientRight.setColorAt(m_vertical, Qt::transparent);
QLinearGradient gradientTop(0,0,0,(qreal)newImage.height());
gradientTop.setColorAt(0, Qt::black);
gradientTop.setColorAt(m_horizontal, Qt::transparent);
QLinearGradient gradientBottom(0,(qreal)newImage.height(),0,0);
gradientBottom.setColorAt(0, Qt::black);
gradientBottom.setColorAt(m_horizontal, Qt::transparent);
painter.begin(&newImage);
painter.fillRect(0,0,newImage.width(),newImage.height(),gradientLeft);
painter.fillRect(0,0,newImage.width(),newImage.height(),gradientRight);
painter.fillRect(0,0,newImage.width(),newImage.height(),gradientTop);
painter.fillRect(0,0,newImage.width(),newImage.height(),gradientBottom);
painter.end();
emit resultReady(newImage);
}
private:
qreal m_horizontal;
qreal m_vertical;
};
FrameFilter::FrameFilter(QObject *parent) :
AbstractImageFilter(parent)
{
m_params << new ImageFilterParameter("Horizontal", 0, 100, this)
<< new ImageFilterParameter("Vertical", 0, 100, this);
resetParameters();
}
QString FrameFilter::name() const
{
return QLatin1String("Frame");
}
AbstractImageFilterWorker *FrameFilter::createWorker()
{
return new FrameFilterWorker(m_params[0]->value(), m_params[1]->value());
}
QList<ImageFilterParameter *> FrameFilter::parameterList()
{
return m_params;
}
void FrameFilter::resetParameters()
{
m_params[0]->setValue(0);
m_params[1]->setValue(0);
}
|
#include<iostream>
#include<cstring>
using namespace std;
int m,n;
int dp[51][51];
int x1,y1,x2,y2;
int mxy[4][2]=
{
1,2,
1,-2,
2,1,
2,-1
};
int main()
{
cin >>n>>m;
cin >>x1>>y1>>x2>>y2;
memset(dp,0,sizeof(dp));
dp[x1][y1]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
//if(dp[i][j]>0)
for(int r=0;r<4;r++)
{
int xx=i-mxy[r][0],yy=j-mxy[r][1];
if(xx>=1 && xx<=n && yy>=1 && yy<=m)
{
dp[i][j]+=dp[xx][yy];
}
}
}
}
cout <<dp[x2][y2]<<endl;
return 0;
}
|
#include <fstream>
#include <stdexcept>
#include "ppm.h"
namespace ppm {
void
write_ppm(const std::string& filename, const std::vector<unsigned char>& data,
unsigned int width, unsigned int height)
{
std::ofstream outfile {filename, std::ios_base::out};
if (!outfile.is_open()) {
throw std::runtime_error("[ppm]: The ppm file cannot be opened for writing.");
}
outfile << "P3" << '\n'
<< width << " " << height << '\n'
<< 255 << '\n';
std::size_t index = 0;
for (std::size_t i = 0; i < height; i++) {
for (std::size_t j = 0; j < width; j++, index += 4) {
outfile << static_cast<int>(data[index]) << ' '
<< static_cast<int>(data[index + 1]) << ' '
<< static_cast<int>(data[index + 2]);
if (j != width - 1) {
outfile << ' ';
}
}
outfile << '\n';
}
}
} // namespace ppm
|
/*
* Generating fibonnaci numbers
* with__Dynamic Programming__
*/
#include <iostream>
#define rep(i,n) for(i=0;i<n;i++)
#define x 94
using namespace std;
main()
{
unsigned long long int f[100];
int i;
f[0] = 0; f[1] = 1;
for(i=2;i<x;i++)
{
f[i] = f[i-1] + f[i-2];
}
rep(i,x)
{
if(0)cout<<f[i]<<endl;
else cout<<f[i]<<"\n";
}
}
|
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
#include <iostream>
template<typename T>
struct Not_starts_with{
public:
Not_starts_with(const T& val) : value_{val} { }
template<typename U>
bool operator()(const U& x) { return *(std::begin(x)) != value_;}
private:
T value_;
};
void f(const std::vector<std::string>& vs, const char c) {
std::vector<std::string> tmp(vs);
Not_starts_with<char> nsw(c);
tmp.erase(std::remove_if(tmp.begin(), tmp.end(), nsw),
tmp.end());
std::unique(tmp.begin(), tmp.end());
for(auto x : tmp)
std::cout << x << '\n';
}
void f_inv(const std::vector<std::string>& vs, const char c) {
std::vector<std::string> tmp;
std::copy(vs.crbegin(), vs.crend(),
std::back_inserter(tmp));
f(tmp, c);
}
int main()
{
std::vector<std::string> vs = {"ciao", "aaaaa", "bbbb", "wwww", "cccc"};
f(vs, 'c');
f_inv(vs, 'c');
return 0;
}
|
/****************************************
*
* INSERT-PROJECT-NAME-HERE - INSERT-GENERIC-NAME-HERE
* Copyright (C) 2019 Victor Tran
*
* 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/>.
*
* *************************************/
#ifndef SAVEDIALOG_H
#define SAVEDIALOG_H
#include <QWidget>
namespace Ui {
class SaveDialog;
}
struct SaveDialogPrivate;
struct SaveObject;
class SaveDialog : public QWidget
{
Q_OBJECT
public:
explicit SaveDialog(QWidget *parent = nullptr);
~SaveDialog();
SaveObject selectedSaveFile();
private slots:
void on_backButton_clicked();
void newSave();
void on_saveView_activated(const QModelIndex &index);
signals:
void rejected();
void accepted();
private:
Ui::SaveDialog *ui;
SaveDialogPrivate* d;
};
#endif // SAVEDIALOG_H
|
#include <iostream> // iostream
#include "Course.h"
#include <vector>
#include <string>
#include "HASH_NODE.h"
using namespace std;//Hello world
const int COURSE_SIZE = 83;
Course courseList[COURSE_SIZE];
const int HASH_SIZE = 111;
HASH_NODE* hashTable[HASH_SIZE];
struct RESULT{
Course result_course;
int show_times = 0;
RESULT* next = NULL;
};
string changeToLower(string source); // change a string to lower and return a new lower string
int Hash(string word); // input a word and return the hash number of the word
void iniHashTable(); // initiallize the HashTable
string* keyWordProcess(string keyword,int& wordNumber); // divided the key words into different word part and return the link of the Dynamic array
void loadResult(RESULT* resultHead, HASH_NODE* node); // input the head of result and load answer to the result
//change a string to lower and return a new lower string
string changeToLower(string source) {
string result = source;
for(int i = 0; i<source.length(); i++) {
result[i] = tolower(source[i]);
}
return result;
}
//Hash function
int Hash(string s){
const int p =31;
const int m =111;
long long hash_value = 0;
long long p_pow = 1;
for (char c : s){
hash_value = (hash_value + (c - 'a' + 1)*p_pow) % m;
p_pow = (p_pow * p)%m;
}
return hash_value;
}
// input keyword and wordNumber and return a wordlist. return null if there is no keyword input
string* keyWordProcess(string keyword, int& wordNumber) {
wordNumber++;
char next;
int i = 0;
//remove started blank and end blank
keyword.erase(0,keyword.find_first_not_of(" "));
keyword.erase(keyword.find_last_not_of(" ")+1);
// if their is no key word return null
if(i == keyword.length()) {
return NULL;
}
keyword = changeToLower(keyword);
// cout word number;
while(i < keyword.length()) {
if(keyword[i] == ' ') {
wordNumber++;
while(keyword[i+1] == ' ' && (i+1 < keyword.length())) {
i++;
} // skip blank space if necessary
}
i++;
}
string* wordList = new string[wordNumber];
// ini the word list
for(int i = 0; i < wordNumber; i++) {
wordList[i] = "";
}
int wordindex = 0;
int index = 0;
// add word to word list;
while(index < keyword.length()) {
if(keyword[index] == ' ') {
while(keyword[index+1] == ' ' && (index+1 < keyword.length())) {
index++;
} // skip blank space if necessary
index++;
wordindex++; // move to next word
}
else {
wordList[wordindex] = wordList[wordindex] + keyword[index];
index++;
}
}
return wordList;
}
void loadResult(RESULT* resultHead, HASH_NODE* node) {
COURSE_INDEX* currentCouresIndexPtr = node -> getCourseIDPtr();
if(resultHead -> show_times == 0) {
int courseID = currentCouresIndexPtr -> course_index;
resultHead -> result_course = courseList[courseID];
resultHead -> show_times = resultHead -> show_times + 1;
currentCouresIndexPtr = currentCouresIndexPtr -> next; //move to next ID
while(currentCouresIndexPtr != NULL) {
bool needNew = true;
RESULT* currentResult = resultHead;
while(currentResult != NULL) {
// judeg if there is the same coure in the result
if(currentResult -> result_course.getCourseName() == courseList[currentCouresIndexPtr -> course_index].getCourseName()) {
currentResult -> show_times = currentResult -> show_times + 1;
needNew = false;
break;
}
}
if(needNew){
currentResult = new RESULT();
// add information to new result
currentResult -> result_course = courseList[currentCouresIndexPtr -> course_index];
currentResult -> show_times = currentResult -> show_times + 1;
//add new result to the total result
RESULT* tempPtr = resultHead;
resultHead = currentResult;
resultHead -> next = tempPtr;
}
}
}
else {
// look up all the course ID;
while(currentCouresIndexPtr != NULL) {
bool needNew = true;
RESULT* currentResult = resultHead;
while(currentResult != NULL) {
// judeg if there is the same coure in the result
if(currentResult -> result_course.getCourseName() == courseList[currentCouresIndexPtr -> course_index].getCourseName()) {
currentResult -> show_times = currentResult -> show_times + 1;
needNew = false;
break;
}
}
if(needNew){
currentResult = new RESULT();
// add information to new result
currentResult -> result_course = courseList[currentCouresIndexPtr -> course_index];
currentResult -> show_times = currentResult -> show_times + 1;
//add new result to the total result
RESULT* tempPtr = resultHead;
resultHead = currentResult;
resultHead -> next = tempPtr;
}
}
}
}
//input the key words and return the Result link list
RESULT *hashSearch(string keyword){
int wordNumber = 0;
RESULT* resultHead = new RESULT();
string* wordList = keyWordProcess(keyword, wordNumber); // return dynamic string list with lower words
for(int i = 0; i < wordNumber; i++) {
int hashNumber = Hash(wordList[i]);
HASH_NODE* hashHead = hashTable[hashNumber];
while(hashHead != NULL) {
if(hashHead -> getWord() == wordList[i]) {
loadResult(resultHead, hashHead);
}
hashHead = hashHead -> next;
}
}
return resultHead;
}
bool compare(string a, string b){
if(a.length()!=b.length()) return false;
int len=a.length();
for(int i=0;i<len;i++){
if(a[i]!=b[i]) return false;
}
return true;
}
void insert(COURSE_INDEX* &courseIndex, COURSE_INDEX* index) {
index->next = courseIndex;
courseIndex = index;
}
void add(string word, int index){
int hashCode=Hash(word);
HASH_NODE* current=new HASH_NODE();
current->setHashNode(hashTable[hashCode]->getWord(),hashTable[hashCode]->getCourseIDPtr());
bool dup=false;
while(current!=NULL){
if(compare(word,current->getWord())){
dup=true;
COURSE_INDEX *newCourseIndex=new COURSE_INDEX;
newCourseIndex->course_index=index;
COURSE_INDEX *temp=current->getCourseIDPtr();
insert(temp,newCourseIndex);
current->setCourseIndex(temp);
}
current=current->next;
}
if(!dup){
current->next=new HASH_NODE;
COURSE_INDEX *newCourseIndex=new COURSE_INDEX;
newCourseIndex->course_index=index;
current->next->setHashNode(word,newCourseIndex);
}
}
vector<string> split(const string& str)
{
vector<string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(" ", prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos - prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + 1;
} while (pos < str.length() && prev < str.length());
return tokens;
}
void iniHashTable(){
for(int i=0;i<111;i++){
HASH_NODE *temp=new HASH_NODE();
hashTable[i]=temp;
}
for(int i=0;i<83;i++){
Course currentCourse=courseList[i];
string currentCourseName=courseList[i].getCourseName();
vector<string> elements=split(currentCourseName);
vector<string>::iterator it;
for(it=elements.begin();it!=elements.end();it++){
add(*it,i);
}
}
}
|
#ifndef HTTPENDPOINTJSONGET_H
#define HTTPENDPOINTJSONGET_H
#include "httpendpoint.h"
#include "jsonconverter.h"
#include <functional>
template <typename T> class HttpEndpointJsonGet : public HttpEndpoint {
public:
using callback_t = std::function<const T(void)>;
HttpEndpointJsonGet(const String &endpoint) : HttpEndpoint(endpoint) {}
virtual ~HttpEndpointJsonGet() {}
void setCallback(callback_t callback) { this->callback = callback; }
private:
callback_t callback;
protected:
virtual bool requestHead(HttpRequest &request,
HttpResponse &response) override {
debugf("requestHead");
if (!callback)
return false;
response.code = HTTP_STATUS_OK;
response.setContentType(ContentType::toString(MIME_JSON));
return true;
}
virtual bool requestGet(HttpRequest &request,
HttpResponse &response) override {
debugf("requestGet");
const T &value = callback();
auto *jsonStream = JsonConverter::toJson<T>(value);
return response.sendDataStream(jsonStream);
}
};
#endif // HTTPENDPOINTJSONGET_H
|
//
// Created by Peter Chen on 5/29/16.
//
#ifndef CUBEWORLD_ITEMDEFINITION_H
#define CUBEWORLD_ITEMDEFINITION_H
class ItemDefinition {
};
#endif //CUBEWORLD_ITEMDEFINITION_H
|
#include<iostream>
template <class T>
T function(T a, T b, T f)
{
return (a + b - f / a) + f * a * a - (a + b);
}
// (2 + 3 - 4 / 2) + 4 * 2 * 2 - (2 + 3)
//44
int main()
{
int a = 3;
int b = 2;
int f = 5;
std :: cout << function(a, b, f) << '\n';
std :: cout << function(3.1, 4.2, 2.7) << '\n';
std :: cout << function(3.0f, 7.1f, 6.2f) << '\n';
std :: cout << function(4l, 5l, 6l);
}
|
#include "BinaryTree.h"
template <class TKey, class TItem>
class IDictionary {
private:
//BinaryTree<TKey, TItem>* Tree;
int Capacity;
int Count;
public:
BinaryTree<TKey, TItem>* Tree;
IDictionary(int capacity = 100) {
this->Capacity = capacity;
this->Count = 0;
this->Tree = new BinaryTree<TKey, TItem>();
}
int GetCapacity() {
return this->Capacity;
}
int GetCount() {
return this->Count;
}
ListSequence<TItem>* Get(TKey key) {
ListSequence<auto>* List = this->Tree->findNode(key);
//BinaryTree<TKey, TItem>::Node * node = this->Tree->findNode(key);
ListSequence<auto>* ListItem = new ListSequence<auto>();
//BinaryTree<TKey, TItem>::Node* =
for (int i = 0; i < List->GetSize(); i++) {
if (List->Get(i) != nullptr) {
ListItem->Prepend(List->Get(i)->item);
}
else return NULL;
}
}
bool ContainsKey(TKey key) {
return this->Tree->toCheck(key);
}
void Add(TKey key, TItem item) {
this->Tree->toInsert(key, item);
++this->Count;
}
// Для типов, совместимых с std::cout
void Print(string maintag = "", string tag = "") {
auto list = this->Tree->Chain("LNR");
cout << " ";
cout.width(20);
cout.setf(ios::left);
cout << maintag;
cout << " | ";
cout.width(6);
cout << tag;
cout << " " << endl;
cout << "============================" << "|" << "==========================" << endl;
for (int i = 0; i < list->GetSize(); ++i) {
cout << " ";
cout.width(20);
cout.setf(ios::left);
cout << list->Get(i)->key << " | ";
cout << list->Get(i)->item << endl;
cout << "----------------------------" << "|" << "--------------------------" << endl;
}
/*
for (int i = 0; i < list->GetSize(); ++i) {
cout << " ";
cout.width(20);
cout.setf(ios::left);
cout << list->Get(i)->key << " | ";
auto List = Tree->findNode(list->Get(i)->key);
if (List->GetSize() > 1) {
for (int j = 0; j < List->GetSize() - 1; j++) {
cout << List->Get(j) << ", ";
}
cout << List->Get(List->GetSize() - 1) << endl;
}
else {
cout << list->Get(i)->item << endl;
}
i += List->GetSize()-1;
delete List;
cout << "----------------------------" << "|" << "--------------------------" << endl;
}
*/
delete list;
}
void Remove(TKey key) {
this->Tree->removeNode(key);
return;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.