blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17f689543d54245d384a62a5de9fb3450645baa5 | d8ed2de0acfbc8af08aa5accb4d727b632696f10 | /source/schemas/ws/EventsWebSocketServer.hpp | f47c2c69fb615a2561cfae52ba423ac5af350412 | [] | no_license | JegernOUTT/CameraManagerCore | ff6cdcc30396200b2ee15857337a9afed07dd89a | 060934b9ccc510ea7ef89082faf538ca40b38306 | refs/heads/master | 2020-06-25T22:35:45.395213 | 2017-07-12T11:45:47 | 2017-07-12T11:45:47 | 96,995,431 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,237 | hpp | EventsWebSocketServer.hpp | //
// Created by svakhreev on 27.03.17.
//
#ifndef CAMERAMANAGERCORE_EVENTSWEBSOCKETSERVER_HPP
#define CAMERAMANAGERCORE_EVENTSWEBSOCKETSERVER_HPP
#include "boost/cerrno.hpp"
#include <memory>
#include <functional>
#include <nlohmann/json.hpp>
#include <simple-websocket-server/server_ws.hpp>
#include "../../model/Event.hpp"
#include "../../signals/SignalContext.hpp"
#include "../model/SignalStatus.hpp"
namespace cameramanagercore::schemas::ws
{
using cameramanagercore::model::Event;
template <typename Contexts>
struct EventWebSocketServer
{
EventWebSocketServer(Contexts contexts, int port, int thread_count)
: _server(std::make_shared<WsServer>(port, thread_count)),
_contexts(contexts),
_signals_context(contexts.template Get<SignalsContext>())
{
_signals_context->AddSubscriber<Event>(EventsDataProcess);
_server->endpoint["^/events/?$"];
}
~EventWebSocketServer()
{
_signals_context->RemoveSubscriber(EventsDataProcess);
}
const std::function<void(SignalData<Event>)> EventsDataProcess =
[this] (SignalData<Event> signal)
{
switch (signal.status)
{
case DataStatus::Added:
{
for (auto& s: _server->endpoint["^/events/?$"].get_connections())
{
auto send_stream = std::make_shared<WsServer::SendStream>();
nlohmann::json answer;
answer["status"] = "OnAdd";
answer["data"] = *signal.data;
*send_stream << answer;
_server->send(s, send_stream, [](const boost::system::error_code& ec) { });
}
}
break;
case DataStatus::Changed:
{
for (auto& s: _server->endpoint["^/events/?$"].get_connections())
{
auto send_stream = std::make_shared<WsServer::SendStream>();
nlohmann::json answer;
answer["status"] = "OnChange";
answer["data"] = *signal.data;
*send_stream << answer;
_server->send(s, send_stream, [](const boost::system::error_code& ec) { });
}
}
break;
case DataStatus::Removed:
{
for (auto& s: _server->endpoint["^/events/?$"].get_connections())
{
auto send_stream = std::make_shared<WsServer::SendStream>();
nlohmann::json answer;
answer["status"] = "OnRemove";
answer["data"] = *signal.data;
*send_stream << answer;
_server->send(s, send_stream, [](const boost::system::error_code& ec) { });
}
}
break;
default: break;
}
};
void Start()
{
_server->start();
}
void Stop()
{
_server->stop();
}
private:
std::shared_ptr<WsServer> _server;
Contexts _contexts;
std::shared_ptr<SignalsContext> _signals_context;
};
}
#endif //CAMERAMANAGERCORE_EVENTSWEBSOCKETSERVER_HPP
|
fb2609f4f7ccea60a6efbacd6e53b28e8e783729 | 4a54dd5a93bbb3f603a2875d5e6dcb3020fb52f2 | /official/zone-2009-09-21-china/src/NetLib/AsyncStream.cpp | 59e4346ca644de84c10ee5f7ae4966b5844ecfcc | [] | no_license | Torashi1069/xenophase | 400ebed356cff6bfb735f9c03f10994aaad79f5e | c7bf89281c95a3c5cf909a14d0568eb940ad7449 | refs/heads/master | 2023-02-02T19:15:08.013577 | 2020-08-17T00:41:43 | 2020-08-17T00:41:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,974 | cpp | AsyncStream.cpp | #include "NetLib/AsyncStream.h"
#include "globals.hpp"
hook_val<unsigned long> CAsyncStream::m_newCompletionKey(SERVER, "CAsyncStream::m_newCompletionKey"); // = ?
hook_func<unsigned int (__stdcall *)(void* CP)> _CompletionProactor(SERVER, "CompletionProactor");
unsigned int __stdcall CompletionProactor(void* CP) // line 11
{
return (_CompletionProactor)(CP);
while( 1 )
{
DWORD transferSize;
ULONG_PTR compKey;
CAsyncOperation* op;
BOOL result = ::GetQueuedCompletionStatus((HANDLE)CP, &transferSize, &compKey, (LPOVERLAPPED*)&op, INFINITE);
if( op == NULL )
continue;
if( op->m_stream == NULL )
continue;
if( op->m_stream->m_completionKey != compKey )
continue;
op->m_stream->CAsyncStream::OnComplete(result, transferSize, op);
}
return 0;
}
hook_func<int (__cdecl *)(void)> _StartCompletionProactor(SERVER, "StartCompletionProactor");
int __cdecl StartCompletionProactor(void) // line 27
{
return (_StartCompletionProactor)();
g_completionPort = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0);
if( g_completionPort == NULL )
return 0;
CAsyncStream::m_newCompletionKey = 0;
SYSTEM_INFO sysInfo;
::GetSystemInfo(&sysInfo);
for( int v1 = 0; v1 < 32; ++v1 )
{
unsigned int threadID;
HANDLE v2 = (HANDLE)::_beginthreadex(0, 0, &CompletionProactor, g_completionPort, 0, &threadID);
if( v2 == 0 )
return 0;
::CloseHandle(v2);
}
return 1;
}
CAsyncStream::CAsyncStream(void) // line 54
{
InitializeCriticalSection(&m_csLock);
m_socket = INVALID_SOCKET;
m_packetHandler = NULL;
m_lastError = CAsyncStream::ERR_NONE;
m_recvQueue.CPacketQueue::Init(20480);
m_sendQueue.CPacketQueue::Init(102400);
memset(&m_recvOperation, 0, sizeof(OVERLAPPED));
memset(&m_recvOperation.m_dataBuf, 0, sizeof(m_recvOperation.m_dataBuf));
memset(&m_recvOperation.m_buffer, 0, sizeof(m_recvOperation.m_buffer));
m_recvOperation.m_dataBuf.len = sizeof(m_recvOperation.m_buffer);
m_recvOperation.m_dataBuf.buf = m_recvOperation.m_buffer;
m_recvOperation.m_type = CAsyncOperation::RECV;
m_recvOperation.m_stream = this;
memset(&m_sendOperation, 0, sizeof(OVERLAPPED));
memset(&m_sendOperation.m_dataBuf, 0, sizeof(m_sendOperation.m_dataBuf));
memset(&m_sendOperation.m_buffer, 0, sizeof(m_sendOperation.m_buffer));
m_sendOperation.m_dataBuf.buf = m_sendOperation.m_buffer;
m_sendOperation.m_type = CAsyncOperation::SEND;
m_sendOperation.m_stream = this;
}
CAsyncStream::CAsyncStream(int recvSize, int sendSize) // line 76
{
InitializeCriticalSection(&m_csLock);
m_socket = INVALID_SOCKET;
m_packetHandler = NULL;
m_lastError = CAsyncStream::ERR_NONE;
m_recvQueue.CPacketQueue::Init(recvSize);
m_sendQueue.CPacketQueue::Init(sendSize);
memset(&m_recvOperation, 0, sizeof(OVERLAPPED));
memset(&m_recvOperation.m_dataBuf, 0, sizeof(m_recvOperation.m_dataBuf));
memset(&m_recvOperation.m_buffer, 0, sizeof(m_recvOperation.m_buffer));
m_recvOperation.m_dataBuf.len = sizeof(m_recvOperation.m_buffer);
m_recvOperation.m_dataBuf.buf = m_recvOperation.m_buffer;
m_recvOperation.m_type = CAsyncOperation::RECV;
m_recvOperation.m_stream = this;
memset(&m_sendOperation, 0, sizeof(OVERLAPPED));
memset(&m_sendOperation.m_dataBuf, 0, sizeof(m_sendOperation.m_dataBuf));
memset(&m_sendOperation.m_buffer, 0, sizeof(m_sendOperation.m_buffer));
m_sendOperation.m_dataBuf.buf = m_sendOperation.m_buffer;
m_sendOperation.m_type = CAsyncOperation::SEND;
m_sendOperation.m_stream = this;
}
CAsyncStream::~CAsyncStream(void) // line 98
{
DeleteCriticalSection(&m_csLock);
}
hook_method<void (CAsyncStream::*)(CPacketHandler* handler)> CAsyncStream::_Init(SERVER, "CAsyncStream::Init");
void CAsyncStream::Init(CPacketHandler* handler) // line 107
{
return (this->*_Init)(handler);
m_socket = INVALID_SOCKET;
m_lastError = CAsyncStream::ERR_NONE;
m_recvQueue.CPacketQueue::Reset();
m_sendQueue.CPacketQueue::Reset();
m_packetHandler = handler;
handler->SetQueue(&m_recvQueue);
}
hook_method<bool (CAsyncStream::*)(SOCKET socket)> CAsyncStream::_Open(SERVER, "CAsyncStream::Open");
bool CAsyncStream::Open(SOCKET socket) // line 135
{
return (this->*_Open)(socket);
m_completionKey = CAsyncStream::m_newCompletionKey++;
m_socket = socket;
if( !CreateIoCompletionPort((HANDLE)socket, g_completionPort, m_completionKey, 0) )
return false;
m_lastError = CAsyncStream::ERR_NONE;
DWORD read = 0;
DWORD flags = 0;
if( WSARecv((SOCKET)m_socket, &m_recvOperation.m_dataBuf, 1, (LPDWORD)&read, &flags, &m_recvOperation, NULL) == SOCKET_ERROR
&& WSAGetLastError() != ERROR_IO_PENDING )
{
m_lastError = WSAGetLastError();
return false;
}
return true;
}
hook_method<void (CAsyncStream::*)(int len, const char* buf)> CAsyncStream::_Send(SERVER, "CAsyncStream::Send");
void CAsyncStream::Send(int len, const char* buf) // line 177
{
return (this->*_Send)(len, buf);
if( len <= 0 )
return;
int v4 = m_sendQueue.CPacketQueue::InsertData(len, buf);
if( v4 < 0 )
{
m_lastError = CAsyncStream::ERR_SENDQUEUEOVERFLOW;
this->CAsyncStream::Close();
return;
}
if( v4 <= len )
{
if( !this->CAsyncStream::SendDataInQueue(len) )
this->CAsyncStream::Close();
}
}
//hook_method<bool (CAsyncStream::*)(const unsigned char* in_pData, const int in_DataBytes)> CAsyncStream::_Send2(SERVER, "CAsyncStream::Send2");
bool CAsyncStream::Send2(const unsigned char* in_pData, const int in_DataBytes) // line ???
{
// return (this->*_Send2)(in_pData, in_DataBytes);
if( in_DataBytes <= 0 )
return false;
int v4 = m_sendQueue.CPacketQueue::InsertData(in_DataBytes, (const char*)in_pData);
if( v4 < 0 )
{
m_lastError = CAsyncStream::ERR_SENDQUEUEOVERFLOW;
this->CAsyncStream::Close();
return false;
}
if( v4 <= in_DataBytes )
{
if( !this->CAsyncStream::SendDataInQueue(in_DataBytes) )
this->CAsyncStream::Close();
}
return true;
}
//hook_method<bool (CAsyncStream::*)(const int in_DataBytes)> CAsyncStream::_IsSendable2(SERVER, "CAsyncStream::IsSendable2");
bool CAsyncStream::IsSendable2(const int in_DataBytes) // line ???
{
// return (this->*_IsSendable2)(in_DataBytes);
return( m_sendQueue.CPacketQueue::GetFreeSize() >= in_DataBytes );
}
hook_method<int (CAsyncStream::*)(void)> CAsyncStream::_Close(SERVER, "CAsyncStream::Close");
int CAsyncStream::Close(void) // line 198
{
return (this->*_Close)();
int result = 1;
if( m_socket == INVALID_SOCKET )
return 0;
::EnterCriticalSection(&m_csLock);
struct linger linger = {1, 0};
::setsockopt(m_socket, SOL_SOCKET, SO_LINGER, (const char *)&linger, sizeof(linger));
if( ::closesocket(m_socket) == SOCKET_ERROR )
result = 0;
m_socket = INVALID_SOCKET;
m_packetHandler->OnClose();
::LeaveCriticalSection(&m_csLock);
return result;
}
//hook_method<SOCKET (CAsyncStream::*)(void)> CAsyncStream::_GetSocket(SERVER, "CAsyncStream::GetSocket");
SOCKET CAsyncStream::GetSocket(void) // line ???
{
// return (this->*_GetSocket)();
return m_socket;
}
hook_method<void (CAsyncStream::*)(int size)> CAsyncStream::_SetRecvQueueSize(SERVER, "CAsyncStream::SetRecvQueueSize");
void CAsyncStream::SetRecvQueueSize(int size) // line 125
{
return (this->*_SetRecvQueueSize)(size);
m_recvQueue.CPacketQueue::Init(size);
}
//hook_method<void (CAsyncStream::*)(int size)> CAsyncStream::_SetSendQueueSize(SERVER, "CAsyncStream::SetSendQueueSize");
void CAsyncStream::SetSendQueueSize(int size) // line ???
{
// return (this->*_SetSendQueueSize)(size);
m_sendQueue.CPacketQueue::Init(size);
}
//hook_method<unsigned long (CAsyncStream::*)(void)> CAsyncStream::_GetIP(SERVER, "CAsyncStream::GetIP");
unsigned long CAsyncStream::GetIP(void) // line ???
{
// return (this->*_GetIP)();
sockaddr name = {};
int addrLen = sizeof(name);
getpeername(m_socket, &name, &addrLen);
return reinterpret_cast<sockaddr_in*>(&name)->sin_addr.s_addr;
}
hook_method<void (CAsyncStream::*)(int result, unsigned long transferSize, CAsyncOperation* op)> CAsyncStream::_OnComplete(SERVER, "CAsyncStream::OnComplete");
void CAsyncStream::OnComplete(int result, unsigned long transferSize, CAsyncOperation* op) // line 311
{
return (this->*_OnComplete)(result, transferSize, op);
if( this->m_socket == INVALID_SOCKET )
return;
if( result == 0 || transferSize <= 0 )
{
this->CAsyncStream::Close();
return;
}
int v5 = ( op->m_type != CAsyncOperation::SEND ) ? this->CAsyncStream::OnRecvCompletion(transferSize) : this->CAsyncStream::OnSendCompletion(transferSize);
if( v5 == 0 )
{
this->CAsyncStream::Close();
return;
}
}
//hook_method<unsigned long (CAsyncStream::*)(void)> CAsyncStream::_GetLastError(SERVER, "CAsyncStream::GetLastError");
unsigned long CAsyncStream::GetLastError(void) // line ???
{
// return (this->*_GetLastError)();
return m_lastError;
}
//hook_method<CPacketQueue* (CAsyncStream::*)(void)> CAsyncStream::_GetRecvQueuePtr(SERVER, "CAsyncStream::GetRecvQueuePtr");
CPacketQueue* CAsyncStream::GetRecvQueuePtr(void) // line ???
{
// return (this->*_GetRecvQueuePtr)();
return &m_recvQueue;
}
hook_method<int (CAsyncStream::*)(int size)> CAsyncStream::_SendDataInQueue(SERVER, "CAsyncStream::SendDataInQueue");
int CAsyncStream::SendDataInQueue(int size) // line 240
{
return (this->*_SendDataInQueue)(size);
if( size >= sizeof(m_sendOperation.m_buffer) )
size = sizeof(m_sendOperation.m_buffer);
m_sendQueue.CPacketQueue::PeekData(size, m_sendOperation.m_buffer);
m_sendOperation.m_dataBuf.len = size;
if( WSASend(m_socket, &m_sendOperation.m_dataBuf, 1, (LPDWORD)&size, 0, &m_sendOperation, NULL) == SOCKET_ERROR
&& WSAGetLastError() != ERROR_IO_PENDING )
{
m_lastError = WSAGetLastError();
return 0;
}
return 1;
}
hook_method<int (CAsyncStream::*)(long len)> CAsyncStream::_OnRecvCompletion(SERVER, "CAsyncStream::OnRecvCompletion");
int CAsyncStream::OnRecvCompletion(long len) // line 291
{
return (this->*_OnRecvCompletion)(len);
if( m_recvQueue.CPacketQueue::InsertData(len, m_recvOperation.m_buffer) == SOCKET_ERROR )
{
m_lastError = CAsyncStream::ERR_RECVQUEUEOVERFLOW;
return 0;
}
DWORD read = 0;
DWORD flags = 0;
if( WSARecv(m_socket, &m_recvOperation.m_dataBuf, 1, &read, &flags, &m_recvOperation, NULL) == SOCKET_ERROR
|| WSAGetLastError() == ERROR_IO_PENDING )
{
m_lastError = WSAGetLastError();
return 0;
}
return 1;
}
hook_method<int (CAsyncStream::*)(long len)> CAsyncStream::_OnSendCompletion(SERVER, "CAsyncStream::OnSendCompletion");
int CAsyncStream::OnSendCompletion(long len) // line 279
{
return (this->*_OnSendCompletion)(len);
int v2 = m_sendQueue.CPacketQueue::RemoveData(len);
if( v2 <= 0 )
return 1;
return this->CAsyncStream::SendDataInQueue(v2);
}
//hook_method<unsigned long (CAsyncStream::*)(void)> CAsyncStream::_GenerateCompletionKey(SERVER, "CAsyncStream::GenerateCompletionKey");
unsigned long CAsyncStream::GenerateCompletionKey(void) // line ???
{
// return (this->*_GenerateCompletionKey)();
return CAsyncStream::m_newCompletionKey++;
}
|
1a072647e0de2fb9dfbf9628375a48ddf0696120 | 8d510f05053edc39bf71238ed94fb3db0c361e10 | /Engine/Include/DlHelper.hpp | 0e5a4e2c7b4abe847ab392554542ed0df86c1f00 | [] | no_license | ReimuA/Raytracer | 944b203869cdf296126c0726216951c6a78edfad | 8cfb7b86fda4f2a2c4c9864254eab79bc71b76b6 | refs/heads/master | 2020-03-22T00:41:15.562352 | 2018-07-05T15:26:30 | 2018-07-05T15:26:30 | 139,259,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | hpp | DlHelper.hpp | /*
** EPITECH PROJECT, 2018
** <------------>
** File description:
** <------->
*/
#pragma once
#include <string>
namespace DlHelper {
void dlClose(void *handle);
void *dlSym(void *handle, const std::string &str);
void *dlOpen(const std::string &str);
};
|
6c04b9674ba6a61ae82a91304a4c3ab61d321096 | 91783283c6f7eb087afbaae5a49cc13e2fe74954 | /smart_parking_slots_cvsr.ino | b5307145929316f1957e5959c3130ff478bdbc8a | [] | no_license | umrsraj/Nano_Arduino | 12553883a7947b21dc9e48f68f4b2bef49a732cf | 93c56ae948c7c0692a7bfb205a84843aa2eaaf7f | refs/heads/master | 2020-05-27T14:37:30.523883 | 2019-07-01T13:53:36 | 2019-07-01T13:53:36 | 188,664,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,426 | ino | smart_parking_slots_cvsr.ino | /*
WiFiEsp example: WebClient
This sketch connects to google website using an ESP8266 module to
perform a simple web search.
For more details see: http://yaab-arduino.blogspot.com/p/wifiesp-example-client.html
*/
// http://projectsiot.xyz/IoTProjects/TollBooth/tollbooth.php?a=A&b=5&c=6&d=3
#include "WiFiEsp.h"
#include<String.h>
#include <LiquidCrystal.h>
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(12, 13); // RX, TX
#endif
LiquidCrystal lcd (2,3,4,5,6,7);
#define slot1Pin A0
#define slot2Pin A1
#define slot3Pin A2
#define slot4Pin A3
#define m11 8
#define m12 9
#define buzzer 10
#define gled A4
#define rled A5
String S1 = "N";
String S2 = "N";
String S3 = "N";
String S4 = "N";
void lcdstring (int a, int b, String w);
int s1 = 0;
int s2 = 0;
int s3 = 0;
int s4 = 0;
unsigned int P1 = 0;
unsigned int P2 = 0;
unsigned int P3 = 0;
unsigned int P4 = 0;
String slot1 = "0";
String slot2 = "0";
String slot3 = "0";
String slot4 = "0";
int count1 = 0; // count = 0
char input[12];
void beep ()
{
digitalWrite(buzzer,HIGH);
delay(1000);
digitalWrite(buzzer,LOW);
delay(100);
}
void forward ()
{
digitalWrite(m11,HIGH);
digitalWrite(m12,LOW);
}
void backward ()
{
digitalWrite(m12,HIGH);
digitalWrite(m11,LOW);
}
void stopp ()
{
digitalWrite(m11,LOW);
digitalWrite(m12,LOW);
}
char ssid[] = "project12"; // your network SSID (name)
char pass[] = "project123456"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
char server[] = "projectsiot.xyz";
String A = "GET /IoTProjects/CarParking/upload.php?a=";
String Z = " HTTP/1.1";
String str;
// Initialize the Ethernet client object
WiFiEspClient client;
void setup()
{
// initialize serial for debugging
Serial.begin(9600);
lcd.begin(16,2);
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" RFID BASED CAR ");
lcd.setCursor(0,1);
lcd.print(" PARKING SLOTS ");
delay(2000);
pinMode(buzzer,OUTPUT);
pinMode(m11,OUTPUT);
pinMode(m12,OUTPUT);
pinMode(gled,OUTPUT);
pinMode(rled,OUTPUT);
pinMode(slot1Pin,INPUT);
pinMode(slot2Pin,INPUT);
pinMode(slot3Pin,INPUT);
pinMode(slot4Pin,INPUT);
digitalWrite(rled,LOW);
digitalWrite(gled,LOW);
// initialize serial for ESP module
Serial1.begin(9600);
// initialize ESP module
WiFi.init(&Serial1);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (true);
}
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
status = WiFi.begin(ssid, pass);
}
// you're connected now, so print out the data
Serial.println("You're connected to the network");
Serial.println("sending data ---1 ");
Serial.println();
Serial.println("Starting connection to server...");
// if you get a connection, report back via serial
if (client.connect(server, 80)) {
Serial.println("Connected to server");
// Make a HTTP request
client.println("GET /IoTProjects/CarParking/upload.php?a=U&b=0&c=0&d=0 HTTP/1.1");
client.println("Host: projectsiot.xyz");
client.println("Connection: close");
client.println();
}
}
void loop()
{
s1 = analogRead(slot1Pin);
s2 = analogRead(slot2Pin);
s3 = analogRead(slot3Pin);
s4 = analogRead(slot4Pin);
Serial.print("ldr1 = "); Serial.println(s1);
Serial.print("ldr2 = "); Serial.println(s2);
Serial.print("ldr3 = "); Serial.println(s3);
Serial.print("ldr4 = "); Serial.println(s4);
lcd.setCursor(0,1);
lcd.print(" ");
if (s1>970)
{
P1 = 1;
S1 = "Y";
}
else
{
P1 = 0;
S1 = "N";
}
if (s2>970)
{
P2 = 1;
S2 = "Y";
}
else
{
P2 = 0;
S2 = "N";
}
if (s3>970)
{
P3 = 1;
S3 = "Y";
}
else
{
P3 = 0;
S3 = "N";
}
if (s4>900)
{
P4 = 1;
S4 = "Y";
}
else
{
P4 = 0;
S4 = "N";
}
lcd.setCursor(0,0);
lcd.print("plz show card ");
lcdstring(0,1,"S1:"+String(P1)+"S2:"+String(P2)+"S3:"+String(P3)+"S4:"+String(P4));
if(Serial.available())
{
count1 = 0;
while(Serial.available() && count1 < 12) // Read 12 characters and store them in input array
{
input[count1] = Serial.read();
count1++;
delay(5);
}//WHILE
//
Serial.println(input); // Print RFID tag number
Serial.print("input[10] is "); Serial.println(input[10]);
if (input[10]=='1')
{
Serial.println("1st vehicle detected");
if((P1==0)||(P2==0)||(P3==0)||(P4==0))
{
Serial.println("gate opening...........");
lcdstring(0,0,"GATE OPENING............");
forward ();
delay(2000);
lcdstring(0,0,"GATE - OPEN ");
stopp ();
delay(5000);
lcdstring(0,0,"GATE CLOSING............");
backward ();
delay(2000);
stopp ();
lcdstring(0,0,"GATE - CLOSE ");
delay(300);
}
else
{
lcdstring(0,0,"ALL SLOTS FULL ");
}
}
else if (input[10]=='9')
{
Serial.println("2nd vehicle detected");
if((P1==0)||(P2==0)||(P3==0)||(P4==0))
{
Serial.println("gate opening...........");
lcdstring(0,0,"GATE OPENING............");
forward ();
delay(2000);
lcdstring(0,0,"GATE - OPEN ");
stopp ();
delay(5000);
lcdstring(0,0,"GATE CLOSING............");
backward ();
delay(2000);
stopp ();
lcdstring(0,0,"GATE - CLOSE ");
delay(300);
}
else
{
lcdstring(0,0,"ALL SLOTS FULL ");
delay(2000);
lcdstring(0,0," ");
}
}
else
{
lcdstring(0,0,"INVALID CARD............... ");
beep ();
delay(2000);
lcdstring(0,0," ");
}
}
str = A +S1 + "&b=" + S2 +"&c=" + S3 + "&d=" + S4 + Z;
sndit ();
}
void sndit ()
{
Serial.print("str = "); Serial.println(A +S1 + "&b=" + S2 +"&c=" + S3 + "&d=" + S4 + Z);
Serial.println();
// if the server's disconnected, stop the client
if (!client.connected()) {
Serial.println();
Serial.println("Disconnecting from server...");
client.stop();
// do nothing forevermore
//while (true);
}
client.flush();
client.stop();
for(int x = 0; x<2; x++)
{
delay(1000);
Serial.println(x);
}
Serial.println();
Serial.println("Starting connection to server...");
// if you get a connection, report back via serial
if (client.connect(server, 80)) {
Serial.println("Connected to server");
// Make a HTTP request
//client.println("GET /IoTProjects/TollBooth/tollbooth.php?a=A&b=5&c=6&d=3 HTTP/1.1");
client.println(A + S1 + "&b=" + S2 +"&c=" + S3 + "&d=" + S4 + Z);
client.println("Host: projectsiot.xyz");
client.println("Connection: close");
client.println();
}
}
void lcdstring (int a, int b, String w)
{
lcd.setCursor(a,b);
lcd.print(w);
}
|
a5684f283562062063e72f384cd1eba1bb1ce47f | ad9f0e8b1b5ffae0685027b897032272a4b55acd | /hex grid node crafter/hex grid node crafter/battleCalc.h | 8e8d420525f934d015b7e11e9031c92c09a59a58 | [] | no_license | robertmcconnell2007/chickamauga | 33c36f61f9a467f0cca56c0ea9914ab57da98556 | 1883d055482973ba421e303661ce0acd529ca886 | refs/heads/master | 2021-01-23T00:14:57.431579 | 2010-08-31T19:36:15 | 2010-08-31T19:36:15 | 32,115,025 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,387 | h | battleCalc.h | #pragma once
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
enum battleResults
{
attackRetreat,//0
attackElim,//1
defendRetreat,//2
defendElim,//3
exchange//4
};
class battleCalculator
{
private:
int oddsArray[6][10];
public:
battleCalculator();
battleCalculator(char*);
int doBattle(int,int);
};
battleCalculator::battleCalculator()
{
ifstream file;
file.open("odds.txt");
for(int i=0; i<6; i++)
{
for(int k=0; k<10; k++)
{
file>>oddsArray[i][k];
}
}
file.close();
}
battleCalculator::battleCalculator(char* fileName)
{
ifstream file;
file.open(fileName);
for(int i=0; i<6; i++)
{
for(int k=0; k<10; k++)
{
file>>oddsArray[i][k];
}
}
file.close();
}
int battleCalculator::doBattle(int attackerPower,int defenderPower)
{
srand(time(0));
bool attackerAdvantage;
int odds;
int roll;
if(attackerPower==defenderPower)
{
odds=1;
attackerAdvantage=true;
}
else if(attackerPower>defenderPower)
{
attackerAdvantage=true;
odds=attackerPower/defenderPower;
}
else if(attackerPower<defenderPower)
{
attackerAdvantage=false;
odds=defenderPower/attackerPower;
}
roll=rand()%6+1;
if(attackerAdvantage)
{
return oddsArray[roll][odds+3];//odds is offset
}
else
{
return oddsArray[roll][5-odds];
}
}
|
4c81289231854269b10155e76fd108b8e6e7fd53 | 26ec2dbf36dbdbcd0697939d1b95f4f67f5ed027 | /Stop_VJets/StopSearches_VJetsBckgdEst.cc | 03ab8e43d09fcc1a39a4f840b7f4a416caf77353 | [] | no_license | caebergs/UserCode | 78d0fd17428c9ece70f9dffc546a841b614ef7ca | 88a7f7a67d18f579c2683aa01fb91341177fb574 | refs/heads/master | 2020-06-05T05:18:48.756206 | 2013-06-12T07:14:10 | 2013-06-12T07:14:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,839 | cc | StopSearches_VJetsBckgdEst.cc | #include "TStyle.h"
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <sys/stat.h>
// Root headers
#include "TArrow.h"
#include "TAxis.h"
#include "TCanvas.h"
#include "TChain.h"
#include "TCut.h"
#include "TEntryList.h"
#include "TFile.h"
#include "TGraphAsymmErrors.h"
#include "TH1.h"
#include "TH2.h"
#include "TH2I.h"
#include "TMath.h"
#include "TMarker.h"
#include "TPaveStats.h"
#include "TFitter.h"
// RooFit headers
#include "RooAddition.h"
#include "RooConstVar.h"
#include "RooCategory.h"
#include "RooDataSet.h"
#include "RooFormula.h"
#include "RooFormulaVar.h"
#include "RooRealVar.h"
#include "RooAddPdf.h"
#include "RooExtendPdf.h"
#include "RooGaussian.h"
#include "RooGenericPdf.h"
#include "RooProdPdf.h"
#include "RooMCStudy.h"
#include "RooMinuit.h"
#include "RooMinimizer.h"
#include "RooNLLVar.h"
#include "RooFitResult.h"
#include "RooPlot.h"
#include "RooTable.h"
#include "Roo1DTable.h"
using namespace RooFit;
using namespace std;
/**
Results from BTV-11-003, https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagPOG link to https://twiki.cern.ch/twiki/pub/CMS/BtagPOG/eff_b_c-ttbar_payload.txt
In Range : 0<=|eta|<=2.4 , 30<=p_T<=200 (approximately)
*/
/** TCHE */
Float_t eff_b_ttbar_FtCM(Float_t /*b-disc*/ x) {
return -3.67153247396e-07*x*x*x*x + -2.81599797034e-05*x*x*x + 0.00293190163243*x*x + -0.0849600849778*x + 0.928524440715 ;
};
Float_t eff_b_ttbar_FtCM_pluserr(Float_t /*b-disc*/ x) {
return 3.03337430722e-06*x*x*x*x + -0.000171604835897*x*x*x + 0.00474711667943*x*x + -0.0929933040514*x + 0.978347619293 ;
};
Float_t eff_b_ttbar_MC(Float_t /*b-disc*/ x) {
return 3.90732786802e-06*x*x*x*x + -0.000239934437355*x*x*x + 0.00664986827287*x*x + -0.112578996016*x + 1.00775721404 ;
};
Float_t eff_c_ttbar_MC(Float_t /*b-disc*/ x) {
return 0.343760640168*exp(-0.00315525164823*x*x*x + 0.0805427315196*x*x + -0.867625139194*x + 1.44815935164 ) ;
};
int StopSearches_VJetsBckgdEst()
{
clock_t start = clock();
cout << "***************************************************************" << endl;
cout << " Beginning of the program for the V+Jets background estimation " << endl;
cout << "***************************************************************" << endl;
bool verbose = true;
bool runOnPNFS = false;
bool Wbb_from_WJets = true;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////Configuration ////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string WbbShapeRootfile = "StopBckg_Outputtttttt.root";
/** TO BE ADAPTED **/
TChain *ttjets = new TChain("AnaTree");
if (runOnPNFS) {
ttjets->Add("dcap:///pnfs/iihe/cms/store/user/nstrobbe/Stop_443/muon/4J_0B/skims/big_TTbar_skim.root");
} else {
ttjets->Add("/user/nstrobbe/DATA/stop/skims_443/TTbar_skim.root");
}
TEntryList *entrylist_ttjets;
vector<double> *vjtDiscri_pf_ttjets = 0;
TChain *wjets = new TChain("AnaTree");
if (runOnPNFS) {
wjets->Add("dcap:///pnfs/iihe/cms/store/user/nstrobbe/Stop_443/muon/4J_0B/skims/WJets_skim.root");
} else {
wjets->Add("/user/nstrobbe/DATA/stop/skims_443/WJets_skim.root");
}
TEntryList *entrylist_wjets = 0;
vector<double> *vjtDiscri_pf_wjets = 0;
vector<double> *vjtFlav_pf_wjets = 0;
TChain *zjets = new TChain("AnaTree");
if (runOnPNFS) {
zjets->Add("dcap:///pnfs/iihe/cms/store/user/nstrobbe/Stop_443/muon/4J_0B/skims/ZJets_skim.root");
} else {
zjets->Add("/user/nstrobbe/DATA/stop/skims_443/ZJets_skim.root");
}
TEntryList *entrylist_zjets = 0;
vector<double> *vjtDiscri_pf_zjets = 0;
TChain *stjets = new TChain("AnaTree");
if (runOnPNFS) {
stjets->Add("dcap:///pnfs/iihe/cms/store/user/nstrobbe/Stop_443/muon/4J_0B/skims/T_tW_skim.root");
stjets->Add("dcap:///pnfs/iihe/cms/store/user/nstrobbe/Stop_443/muon/4J_0B/skims/Tbar_tW_skim.root");
} else {
stjets->Add("/user/nstrobbe/DATA/stop/skims_443/T_tW_skim.root");
stjets->Add("/user/nstrobbe/DATA/stop/skims_443/Tbar_tW_skim.root");
}
TEntryList *entrylist_stjets = 0;
vector<double> *vjtDiscri_pf_stjets = 0;
// TChain *vbjets = new TChain("AnaTree");
// vbjets->Add("dcap:///pnfs/iihe/cms/store/user/nstrobbe/Stop_443/muon/4J_0B/skims/XXX_skim.root");
// TEntryList *entrylist_vbjets = 0;
// vector<double> *vjtDiscri_pf_vbjets = 0;
// TBranch *b_vjtDiscri_pf = 0;
if(verbose){
cout<<"Number of events for :"<<endl;
cout<<" - ttjets = "<<ttjets->GetEntries()<<endl;
cout<<" - wjets = "<< wjets->GetEntries()<<endl;
cout<<" - zjets = "<< zjets->GetEntries()<<endl;
cout<<" - stjets = "<<stjets->GetEntries()<<endl;
// cout<<" - vbjets ="<<vbjets->GetEntries()<<endl;
}
// Processes XS (pb) taken from https://twiki.cern.ch/twiki/bin/viewauth/CMS/StandardModelCrossSections
/*** TO BE UPDATED TO THE MEASURED XS WHENEVER POSSIBLE ***/
float XS_ttjets = 165.;
float XS_wjets = 31314.;
float XS_zjets = 3048.;
float XS_stjets = 10.6;
float XS_vbjets = 35.5;
// Retrieve int. lumi from InputTree (?)
const double IntLumi = 5000;
// Normalization factors for a given int. lumi.
/** TO BE ADAPTED **/
bool skimmedTree = true;
double NormFact_ttjets = 0;
double NormFact_wjets = 0;
double NormFact_zjets = 0;
double NormFact_stjets = 0;
// double NormFact_vbjets = 0;
if(skimmedTree) {
ttjets->SetBranchAddress("eventWeight",&NormFact_ttjets);
wjets->SetBranchAddress("eventWeight",&NormFact_wjets);
zjets->SetBranchAddress("eventWeight",&NormFact_zjets);
stjets->SetBranchAddress("eventWeight",&NormFact_stjets);
//vbjets->SetBranchAddress("eventWeight",&NormFact_vbjets);
}
else{
NormFact_ttjets = XS_ttjets/ttjets->GetEntries();
NormFact_wjets = XS_wjets/wjets->GetEntries();
NormFact_zjets = XS_zjets/zjets->GetEntries();
NormFact_stjets = XS_stjets/stjets->GetEntries();
// NormFact_vbjets = XS_vbjets/vbjets->GetEntries();
}
//Output ROOT file
string postfix = "_VJetsBckgdEst";
string channelpostfix = "_SemiMuon";
string comment = "_Constants_euds";
string rootFileName ("StopSearches"+postfix+channelpostfix+comment+".root");
TFile *fout = new TFile (rootFileName.c_str(), "RECREATE");
TDirectory *myDir = 0;
// E v e n t s e l e c t i o n c u t s
// ---------------------------------------
const int NbOfPE = 1000;
const int NbOfJetBins = 4;
const int MinNbOfJets = 3;
int JetIdx = 1;
/** B-tagging working points ; https://twiki.cern.ch/twiki/bin/viewauth/CMS/BTagPerformanceOP#B_tagging_Operating_Points_for_3
TrackCountingHighEff TCHEL 1.7
TrackCountingHighEff TCHEM 3.3
TrackCountingHighEff TCHET 10.2 (not supported)
CombinedSecondaryVertex CSVL 0.244
CombinedSecondaryVertex CSVM 0.679
CombinedSecondaryVertex CSVT 0.898
**/
float btagCut = 1.7;
// Muon channel
TCut muon = "(muPt[0]>20.)&&(TMath::Abs(muEta[0])<=2.1)";
// Electron channel
//TCut electron = "(elPt[0]>0.)&&(elSCenergy[0]>=17.0)";
// Lepton selection
TCut lveto = "NmuIdIso==1";
// Channel selection
TCut singlep = muon+lveto;
// Jet selection
TCut pfnjet[NbOfJetBins];
pfnjet[0] = "Njt_pf==3";
pfnjet[1] = "Njt_pf==4";
pfnjet[2] = "Njt_pf==5";
pfnjet[3] = "Njt_pf>=6";
//TCut pf4jet = "Njt_pf>3";
//TCut btag = "Njtbtag_pf>0";
// Selection cuts
TCut cuts = (skimmedTree ? pfnjet[JetIdx] : singlep+pfnjet[JetIdx]);
// S e t t i n g s f o r m a x i m u m l i k e l i h o o d e s t i m a t i o n
// ------------------------------------------------------------------------------------
// Probabilities to have X b-quarks in the tt-like final state **DERIVED FROM MC SIMULATIONS**
const float e0bq_[NbOfJetBins] = {0.0247448,0.00873498,0.00638495,0.00734619};
const float e1bq_[NbOfJetBins] = {0.379931,0.179928,0.145577,0.134986};
const float e2bq_[NbOfJetBins] = {0.594488,0.808598,0.83759,0.836547};
// Initial values for minimization
float init_Nttlike[NbOfJetBins] = {0.,24500.,9850.,4015.};
float init_Nvlike[NbOfJetBins] = {0.,23400.,3900., 750.};
float init_Eb = 0.8; /** TO BE ADAPTED IF USED AS FIXED VARIABLE **/
float init_Eudsc = 0.2; /** TO BE ADAPTED IF USED AS FIXED VARIABLE **/
float init_Euds = 0.179; /** TO BE ADAPTED IF USED AS FIXED VARIABLE **/
// Mean and error values for constraints
float Eb_const_mean = 0.795; /** TO BE CALCULATED BY FUNCT FROM BTV-11-003 **/
float Eb_const_error = 0.795*0.1; /** TO BE CALCULATED BY FUNCT FROM BTV-11-003 **/
float Eudsc_const_mean = 0.000; /** TO BE DERIVED FROM MC **/
float Eudsc_const_error = 0.000; /** TO BE DERIVED FROM MC **/
float Euds_const_mean = 0.179; /** TO BE CALCULATED BY FUNCT FROM BTV-11-003 **/
float Euds_const_error = 0.179*0.1; /** TO BE CALCULATED BY FUNCT FROM BTV-11-003 **/
// Counters for the b-tagged jet multiplicity
int NbtaggedJets = 0;
int nB_Flavoured_Jets = 0;
int nC_Flavoured_Jets = 0;
int nLightAndGluon_Flavoured_Jets = 0;
// Histograms for the b-tagged jet multiplicity
TH1F* hNbtaggedJets_ttjets = new TH1F("hNbtaggedJets_ttjets",";B-tagged jet multiplicity",10,0,10);
TH1F* hNbtaggedJets_wjets = new TH1F("hNbtaggedJets_wjets", ";B-tagged jet multiplicity",10,0,10);
TH1F* hNbtaggedJets_zjets = new TH1F("hNbtaggedJets_zjets", ";B-tagged jet multiplicity",10,0,10);
TH1F* hNbtaggedJets_stjets = new TH1F("hNbtaggedJets_stjets",";B-tagged jet multiplicity",10,0,10);
TH1F* hNbtaggedJets_vbjets = new TH1F("hNbtaggedJets_vbjets",";B-tagged jet multiplicity",10,0,10);
TH1F* hNbtaggedJets_ttlike = new TH1F("hNbtaggedJets_ttlike",";B-tagged jet multiplicity",10,0,10);
TH1F* hNbtaggedJets_vlike = new TH1F("hNbtaggedJets_vlike" ,";B-tagged jet multiplicity",10,0,10);
TH1F* hNbtaggedJets = new TH1F("hNbtaggedJets" ,";B-tagged jet multiplicity",10,0,10);
TH1F* hWbb_In_WJets = new TH1F("hNbtaggedJets_wjets_Wbb",";B-tagged jet multiplicity",10,0,10);
TH1F* hWcx_In_WJets = new TH1F("hNbtaggedJets_wjets_Wcx",";B-tagged jet multiplicity",10,0,10);
TH1F* hWLFg_In_WJets = new TH1F("hNbtaggedJets_wjets_WLFg",";B-tagged jet multiplicity",10,0,10);
vector<int>::iterator Idx;
vector<int> FixedVarIdx;
//FixedVarIdx.push_back(0); // Fix eb, b-tagging efficiency
//FixedVarIdx.push_back(1); // Fix eudsc, mis-tagging efficiency for tt-like events
//FixedVarIdx.push_back(2); // Fix euds, mis-tagging efficiency for v-like events
string wp[3] = {"loose","medium","tight"};
bool doPE = false;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////// Analysis ////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// E v e n t s e l e c t i o n
// -----------------------------
ttjets->SetBranchAddress("vjtDiscri_pf", &vjtDiscri_pf_ttjets);//, &b_vjtDiscri_pf);
wjets->SetBranchAddress("vjtDiscri_pf", &vjtDiscri_pf_wjets);//, &b_vjtDiscri_pf);
zjets->SetBranchAddress("vjtDiscri_pf", &vjtDiscri_pf_zjets);//, &b_vjtDiscri_pf);
stjets->SetBranchAddress("vjtDiscri_pf", &vjtDiscri_pf_stjets);//, &b_vjtDiscri_pf);
// vbjets->SetBranchAddress("vjtDiscri_pf", &vjtDiscri_pf_vbjets);//, &b_vjtDiscri_pf);
wjets->SetBranchAddress("vjtFlav_pf", &vjtFlav_pf_wjets);//, &vjtFlav_pf);
ttjets->Draw(">>entrylist_ttjets", cuts, "entrylist");
wjets->Draw(">>entrylist_wjets", cuts, "entrylist");
zjets->Draw(">>entrylist_zjets", cuts, "entrylist");
stjets->Draw(">>entrylist_stjets", cuts, "entrylist");
// vbjets->Draw(">>entrylist_vbjets", cuts, "entrylist");
entrylist_ttjets = (TEntryList*)gDirectory->Get("entrylist_ttjets");
entrylist_wjets = (TEntryList*)gDirectory->Get("entrylist_wjets");
entrylist_zjets = (TEntryList*)gDirectory->Get("entrylist_zjets");
entrylist_stjets = (TEntryList*)gDirectory->Get("entrylist_stjets");
// entrylist_vbjets = (TEntryList*)gDirectory->Get("entrylist_vbjets");
//BBB
ttjets->SetEntryList(entrylist_ttjets);
wjets->SetEntryList(entrylist_wjets);
zjets->SetEntryList(entrylist_zjets);
stjets->SetEntryList(entrylist_stjets);
// vbjets->SetEntryList(entrylist_vbjets);
Long64_t NbOfEvtsToProcess = 0;
// For tt+jets events
NbOfEvtsToProcess = entrylist_ttjets->GetN();
if(verbose) cout<<"Processing tt+jets Tree (Nb of events = "<<NbOfEvtsToProcess<<")"<<endl;
for (Long64_t el = 0; el<NbOfEvtsToProcess; el++) {
if(el%100 == 0) cout<<"-- Processing the "<<el<<"th event ("<<100*(el)/(NbOfEvtsToProcess)<<"%)"<<flush<<"\r";
ttjets->GetEntry(entrylist_ttjets->GetEntry(el));
NbtaggedJets = 0;
for(UInt_t i = 0; i<vjtDiscri_pf_ttjets->size(); ++i)
{
if((*vjtDiscri_pf_ttjets)[i]>btagCut) NbtaggedJets++;
}
hNbtaggedJets_ttjets->Fill(NbtaggedJets);
}
hNbtaggedJets_ttjets->Scale(NormFact_ttjets*IntLumi);
// For w+jets events
NbOfEvtsToProcess = entrylist_wjets->GetN();
if(verbose) cout<<"Processing W+jets Tree (Nb of events = "<<NbOfEvtsToProcess<<")"<<endl;
for (Long64_t el = 0; el<entrylist_wjets->GetN();el++) {
if(el%100 == 0) cout<<"-- Processing the "<<el<<"th event ("<<100*(el)/(NbOfEvtsToProcess)<<"%)"<<flush<<"\r";
wjets->GetEntry(entrylist_wjets->GetEntry(el));
NbtaggedJets = 0;
nB_Flavoured_Jets = 0;
nC_Flavoured_Jets = 0;
nLightAndGluon_Flavoured_Jets = 0;
for(UInt_t i = 0; i<vjtDiscri_pf_wjets->size(); ++i)
{
if((*vjtDiscri_pf_wjets)[i]>btagCut) NbtaggedJets++;
if (std::fabs((*vjtFlav_pf_wjets)[i])==5.) {
nB_Flavoured_Jets++;
} else if (std::fabs((*vjtFlav_pf_wjets)[i])==4.) {
nC_Flavoured_Jets++;
} else {
nLightAndGluon_Flavoured_Jets++;
}
}
hNbtaggedJets_wjets->Fill(NbtaggedJets);
if (nB_Flavoured_Jets>0) {
hWbb_In_WJets->Fill(NbtaggedJets);
} else if (nC_Flavoured_Jets>0) {
hWcx_In_WJets->Fill(NbtaggedJets);
} else {
hWLFg_In_WJets->Fill(NbtaggedJets);
}
}
hNbtaggedJets_wjets->Scale(NormFact_wjets*IntLumi);
// For z+jets events
NbOfEvtsToProcess = entrylist_zjets->GetN();
if(verbose) cout<<"Processing Z+jets Tree (Nb of events = "<<NbOfEvtsToProcess<<")"<<endl;
for (Long64_t el = 0; el<entrylist_zjets->GetN();el++) {
if(el%100 == 0) cout<<"-- Processing the "<<el<<"th event ("<<100*(el)/(NbOfEvtsToProcess)<<"%)"<<flush<<"\r";
zjets->GetEntry(entrylist_zjets->GetEntry(el));
NbtaggedJets = 0;
for(UInt_t i = 0; i<vjtDiscri_pf_zjets->size(); ++i)
{
if((*vjtDiscri_pf_zjets)[i]>btagCut) NbtaggedJets++;
}
hNbtaggedJets_zjets->Fill(NbtaggedJets);
}
hNbtaggedJets_zjets->Scale(NormFact_zjets*IntLumi);
// For st+jets events
NbOfEvtsToProcess = entrylist_stjets->GetN();
if(verbose) cout<<"Processing st+jets Tree (Nb of events = "<<NbOfEvtsToProcess<<")"<<endl;
for (Long64_t el = 0; el<entrylist_stjets->GetN();el++) {
if(el%100 == 0) cout<<"-- Processing the "<<el<<"th event ("<<100*(el)/(NbOfEvtsToProcess)<<"%)"<<flush<<"\r";
stjets->GetEntry(entrylist_stjets->GetEntry(el));
NbtaggedJets = 0;
for(UInt_t i = 0; i<vjtDiscri_pf_stjets->size(); ++i)
{
if((*vjtDiscri_pf_stjets)[i]>btagCut) NbtaggedJets++;
}
hNbtaggedJets_stjets->Fill(NbtaggedJets);
}
hNbtaggedJets_stjets->Scale(NormFact_stjets*IntLumi);
/** Njtbtag CANNOT BE USED AS IT INCLUDES NON-SELECTED JETS !!!!
// Fill 2D histograms Nb b-tagged jets vs Nb jets
ttjets->Draw("Njtbtag_pf>>hNbtaggedJets_ttjets(10,0,10)",cuts);
wjets->Draw("Njtbtag_pf>>hNbtaggedJets_wjets(10,0,10)",cuts);
zjets->Draw("Njtbtag_pf>>hNbtaggedJets_zjets(10,0,10)",cuts);
stjets->Draw("Njtbtag_pf>>hNbtaggedJets_stjets(10,0,10)",cuts);
// vbjets->Draw("Njtbtag_pf>>hNbtaggedJets_vbjets(10,0,10)",cuts);
// Retrieve the b-tagged jet multiplicity histograms
hNbtaggedJets_ttjets = (TH1F*)gDirectory->Get("hNbtaggedJets_ttjets");
hNbtaggedJets_wjets = (TH1F*)gDirectory->Get("hNbtaggedJets_wjets");
hNbtaggedJets_zjets = (TH1F*)gDirectory->Get("hNbtaggedJets_zjets");
hNbtaggedJets_stjets = (TH1F*)gDirectory->Get("hNbtaggedJets_stjets");
// hNbtaggedJets_vbjets = (TH1F*)gDirectory->Get("hNbtaggedJets_vbjets");
// Set title axis for histograms
hNbtaggedJets_ttjets->SetTitle(";B-tagged jet multiplicity");
hNbtaggedJets_wjets->SetTitle(";B-tagged jet multiplicity");
hNbtaggedJets_zjets->SetTitle(";B-tagged jet multiplicity");
hNbtaggedJets_stjets->SetTitle(";B-tagged jet multiplicity");
// hNbtaggedJets_vbjets->SetTitle(";B-tagged jet multiplicity");
*/
// Select processes to be considered in the estimation
// - tt-like processes
hNbtaggedJets_ttlike->Add(hNbtaggedJets_ttjets);
// - v-like processes
hNbtaggedJets_vlike->Add(hNbtaggedJets_wjets);
hNbtaggedJets_vlike->Add(hNbtaggedJets_zjets);
// Set true numbers of tt-like and v-like events
float Nttlike = hNbtaggedJets_ttlike->Integral();
float Nvlike = hNbtaggedJets_vlike->Integral();
if (Wbb_from_WJets) {
for (int k =0; k<10; k++) {
hNbtaggedJets_vbjets->SetBinContent(k+1, hWbb_In_WJets->GetBinContent(hWbb_In_WJets->FindBin(k)));
}
} else {
int Nbins = 10 ;
Int_t Min = 0 ;
Int_t Max = 10 ;
TFile *f = new TFile(WbbShapeRootfile.c_str(), "READ");
if (!f->IsZombie()) {
char name[100];
for (UInt_t j=0; j<12; j++) {
if ((j!=1)&&(j!=2)&&(j!=5)) {
continue;
}
if (JetIdx==MinNbOfJets+NbOfJetBins-1) {
sprintf(name, "HistoryFlavor--AtLeast_%d_jets--FlavorHistoryPath_%d", JetIdx+MinNbOfJets, j);
} else {
sprintf(name, "HistoryFlavor--%d_jets--FlavorHistoryPath_%d", JetIdx+MinNbOfJets, j);
}
TH1I *h = (TH1I*) f->Get(name);
for (UInt_t k=1; k<=Nbins; k++) {
hNbtaggedJets_vbjets->Fill(k-1,h->GetBinContent(k));
}
}
f->Close();
}
}
// Set numbers of background events and associated uncertainties
float Nstjets = hNbtaggedJets_stjets->Integral();
float Nstjets_uncert = 0.3; // 30% uncertainty on the st+jets XS ** TO BE ADAPTED **
float Nvbjets = hNbtaggedJets_vbjets->Integral();
float Nvbjets_uncert = 0.3; // 30% uncertainty on the vb+jets XS ** TO BE ADAPTED **
// Sum over all datasets
hNbtaggedJets->Add(hNbtaggedJets_ttlike);
hNbtaggedJets->Add(hNbtaggedJets_vlike);
hNbtaggedJets->Add(hNbtaggedJets_stjets);
// hNbtaggedJets->Add(hNbtaggedJets_vbjets);
// Total nb of events (rescaled to the required int. lumi.)
int nExpected = (int)hNbtaggedJets->Integral();
if(verbose){
cout<<"***************************************"<<endl;
cout<<"- Number of entries / NormFactors "<<endl;
cout<<"-- for tt-like processes : "<<endl;
cout<<"--- tt+jets = "<<hNbtaggedJets_ttjets->GetEntries()<<"/ "<<NormFact_ttjets<<endl;
cout<<"--- total nb of events (for "<<IntLumi<<" /pb) = "<<Nttlike<<endl;
cout<<"---------------------------------"<<endl;
cout<<"-- for v-like processes : "<<endl;
cout<<"--- w+jets = "<<hNbtaggedJets_wjets->GetEntries()<<"/ "<<NormFact_wjets<<endl;
cout<<"--- z+jets = "<<hNbtaggedJets_zjets->GetEntries()<<"/ "<<NormFact_zjets<<endl;
cout<<"--- total nb of events (for "<<IntLumi<<" /pb) = "<<Nvlike<<endl;
cout<<"---------------------------------"<<endl;
cout<<"-- for background processes : "<<endl;
cout<<"--- st+jets = "<<hNbtaggedJets_stjets->GetEntries()<<"/ "<<NormFact_stjets<<endl;
cout<<"--- total nb of events (for "<<IntLumi<<" /pb) = "<<Nstjets<<endl;
// cout<<"--- vb+jets = "<<hNbtaggedJets_vbjets->GetEntries()<<"/ "<<NormFact_vbjets<<endl;
// cout<<"--- total nb of events (for "<<IntLumi<<" /pb) = "<<Nvbjets<<endl;
cout<<"---------------------------------"<<endl;
cout<<"-- for all processes : "<<endl;
cout<<"--- total = "<<hNbtaggedJets->GetEntries()<<endl;
cout<<"--- total nb of events (for "<<IntLumi<<" /pb) = "<<nExpected<<endl;
cout<<"***************************************"<<endl;
}
// C r e a t e o b s e r v a b l e
// ---------------------------------
// Estimation parameters
RooRealVar Ntt("Ntt","N_{t#bar{t}-like}",init_Nttlike[JetIdx],0.0,init_Nttlike[JetIdx]*3);
RooRealVar Nv("Nv","N_{V-like}",init_Nvlike[JetIdx],0.0,init_Nvlike[JetIdx]*4);
// Background normalization factors
RooRealVar Nst("Nst","N_{single top}",Nstjets,0.0,Nstjets*4);
RooRealVar Nvb("Nvb","N_{V+b-jets}",Nvbjets,0.0,Nvbjets*4);
RooRealVar eb( "eb", "#epsilon_{b-tag}", init_Eb,0.0,1.0);
Idx = find( FixedVarIdx.begin(), FixedVarIdx.end(), 0 );
if(Idx != FixedVarIdx.end()) eb.setConstant(kTRUE) ;
RooRealVar eudsc("eudsc","#epsilon_{mis-tag}", init_Eudsc,0.0,1.0);
Idx = find( FixedVarIdx.begin(), FixedVarIdx.end(), 1 );
if(Idx != FixedVarIdx.end()) eudsc.setConstant(kTRUE) ;
RooRealVar euds( "euds", "#epsilon^{,}_{mis-tag}",init_Euds,0.0,1.0);
Idx = find( FixedVarIdx.begin(), FixedVarIdx.end(), 2 );
if(Idx != FixedVarIdx.end()) euds.setConstant(kTRUE) ;
// Declare constants
RooConstVar n("n","number of selected jets",MinNbOfJets+JetIdx) ;
RooConstVar e0bq("e0bq","e0bq",e0bq_[JetIdx]);
RooConstVar e1bq("e1bq","e1bq",e1bq_[JetIdx]);
RooConstVar e2bq("e2bq","e2bq",e2bq_[JetIdx]);
//RooConstVar e3bq("e3bq","e3bq",e3bq_[njets]);
RooConstVar n0bjets_st("n0bjets_st","n^{0 b-jet}", hNbtaggedJets_stjets->GetBinContent(hNbtaggedJets_stjets->FindBin(0.)));
RooConstVar n1bjets_st("n1bjets_st","n^{1 b-jet}", hNbtaggedJets_stjets->GetBinContent(hNbtaggedJets_stjets->FindBin(1.)));
RooConstVar n2bjets_st("n2bjets_st","n^{2 b-jets}",hNbtaggedJets_stjets->GetBinContent(hNbtaggedJets_stjets->FindBin(2.)));
RooConstVar n3bjets_st("n3bjets_st","n^{3 b-jets}",hNbtaggedJets_stjets->GetBinContent(hNbtaggedJets_stjets->FindBin(3.)));
RooConstVar n0bjets_vb("n0bjets_vb","n^{0 b-jet}", hNbtaggedJets_vbjets->GetBinContent(hNbtaggedJets_vbjets->FindBin(0.)));
RooConstVar n1bjets_vb("n1bjets_vb","n^{1 b-jet}", hNbtaggedJets_vbjets->GetBinContent(hNbtaggedJets_vbjets->FindBin(1.)));
RooConstVar n2bjets_vb("n2bjets_vb","n^{2 b-jets}",hNbtaggedJets_vbjets->GetBinContent(hNbtaggedJets_vbjets->FindBin(2.)));
RooConstVar n3bjets_vb("n3bjets_vb","n^{3 b-jets}",hNbtaggedJets_vbjets->GetBinContent(hNbtaggedJets_vbjets->FindBin(3.)));
// C o n s t r u c t a c a t e g o r y w i t h l a b e l s a n d i n d e c e s
// -----------------------------------------------------------------------------------------
RooCategory nbjets("nbjets","Number of b-jets");
nbjets.defineType("N0bjet", 0);
nbjets.defineType("N1bjet", 1);
nbjets.defineType("N2bjets",2);
nbjets.defineType("N3bjets",3);
// C o n s t r u c t f o r m u l a s
// -------------------------------------------------------------------------------
RooFormulaVar p0bjets_tt("p0bjets_tt","p0bjets_tt","(1-eb)*(1-eb)*pow((1-eudsc),n-2)*e2bq+(1-eb)*pow((1-eudsc),n-1)*e1bq+pow((1-eudsc),n)*e0bq",RooArgList(eb,eudsc,n,e0bq,e1bq,e2bq));
RooFormulaVar p1bjets_tt("p1bjets_tt","p1bjets_tt","(2*eb*(1-eb)*pow(1-eudsc,n-2)+(1-eb)*(1-eb)*(n-2)*eudsc*pow(1-eudsc,n-3))*e2bq+(eb*pow(1-eudsc,n-1)+(1-eb)*(n-1)*eudsc*pow(1-eudsc,n-2))*e1bq+(n*eudsc*pow(1-eudsc,n-1))*e0bq",RooArgList(eb,eudsc,n,e0bq,e1bq,e2bq));
RooFormulaVar p2bjets_tt("p2bjets_tt","p2bjets_tt","(eb*eb*pow(1-eudsc,n-2)+2*eb*(1-eb)*(n-2)*eudsc*pow(1-eudsc,n-3)+(1-eb)*(1-eb)*((n-2)*(n-3)/2)*eudsc*eudsc*pow(1-eudsc,n-4))*e2bq+(eb*(n-1)*eudsc*pow(1-eudsc,n-2)+(1-eb)*((n-1)*(n-2)/2)*eudsc*eudsc*pow(1-eudsc,n-3))*e1bq+((n*(n-1)/2)*eudsc*eudsc*pow(1-eudsc,n-2))*e0bq",RooArgList(eb,eudsc,n,e0bq,e1bq,e2bq));
RooFormulaVar p3bjets_tt("p3bjets_tt","p3bjets_tt","(eb*eb*(n-2)*eudsc*pow(1-eudsc,n-3)+2*eb*(1-eb)*((n-2)*(n-3)/2)*eudsc*eudsc*pow(1-eudsc,n-4)+(n>4 ? pow((1-eb),2)*((n-2)*(n-3)*(n-4)/6)*pow(eudsc,3)*pow((1-eudsc),n-5) : 0 ))*e2bq+(eb*((n-1)*(n-2)/2)*eudsc*eudsc*pow(1-eudsc,n-3)+(1-eb)*((n-1)*(n-2)*(n-3)/6)*pow(eudsc,3)*pow(1-eudsc,n-4))*e1bq+((n*(n-1)*(n-2)/6)*pow(eudsc,3)*pow(1-eudsc,n-3))*e0bq",RooArgList(eb,eudsc,n,e0bq,e1bq,e2bq));
RooFormulaVar p0bjets_v ("p0bjets_v", "p0bjets_v" ,"pow(1-euds,n)",RooArgList(euds,n));
RooFormulaVar p1bjets_v ("p1bjets_v", "p1bjets_v" ,"n*euds*pow(1-euds,n-1)",RooArgList(euds,n));
RooFormulaVar p2bjets_v ("p2bjets_v", "p2bjets_v" ,"(n*(n-1)/2)*euds*euds*pow(1-euds,n-2)",RooArgList(euds,n));
RooFormulaVar p3bjets_v ("p3bjets_v", "p3bjets_v" ,"((n)*(n-1)*(n-2)/6)*pow(euds,3)*pow(1-euds,n-3)",RooArgList(euds,n));
// C o n s t r u c t p . d . f 's
// -------------------------------------------------------------------------------
RooGenericPdf pbjets_tt("pbjets_tt","pbjets_tt","(nbjets==0)*p0bjets_tt+(nbjets==1)*p1bjets_tt+(nbjets==2)*p2bjets_tt+(nbjets==3)*p3bjets_tt",RooArgList(nbjets,p0bjets_tt,p1bjets_tt,p2bjets_tt,p3bjets_tt));
RooExtendPdf pbjets_tt_ext("pbjets_tt_ext","pbjets_tt_ext",pbjets_tt,Ntt);
RooGenericPdf pbjets_v("pbjets_v","pbjets_v","(nbjets==0)*p0bjets_v+(nbjets==1)*p1bjets_v+(nbjets==2)*p2bjets_v+(nbjets==3)*p3bjets_v",RooArgList(nbjets,p0bjets_v,p1bjets_v,p2bjets_v,p3bjets_v));
RooExtendPdf pbjets_v_ext("pbjets_v_ext","pbjets_v_ext",pbjets_v,Nv);
RooGenericPdf pbjets_st("pbjets_st","pbjets_st","(nbjets==0)*n0bjets_st+(nbjets==1)*n1bjets_st+(nbjets==2)*n2bjets_st+(nbjets==3)*n3bjets_st",RooArgList(nbjets,n0bjets_st,n1bjets_st,n2bjets_st,n3bjets_st));
RooGenericPdf pbjets_vb("pbjets_vb","pbjets_vb","(nbjets==0)*n0bjets_vb+(nbjets==1)*n1bjets_vb+(nbjets==2)*n2bjets_vb+(nbjets==3)*n3bjets_vb",RooArgList(nbjets,n0bjets_vb,n1bjets_vb,n2bjets_vb,n3bjets_vb));
//RooAddPdf model("model","model",RooArgList(pbjets_tt,pbjets_v),RooArgList(Ntt,Nv));
RooAddPdf model("model","model",RooArgList(pbjets_tt,pbjets_v,pbjets_st,pbjets_vb),RooArgList(Ntt,Nv,Nst,Nvb));
// Contrainsts on free parameters
//RooGaussian Eb_constraint("Eb_constraint","Eb_constraint",eb,RooConst(Eb_const_mean),RooConst(Eb_const_error));
//RooGaussian Eudsc_constraint("Eudsc_constraint","Eudsc_constraint",eudsc,RooConst(XXX),RooConst(XXX));
RooGaussian Euds_constraint("Euds_constraint","Euds_constraint",euds,RooConst(Euds_const_mean),RooConst(Euds_const_error));
RooGaussian Nst_constraint("Nst_constraint","Nst_constraint",Nst,RooConst(Nstjets),RooConst(Nstjets*Nstjets_uncert));
RooGaussian Nvb_constraint("Nvbb_constraint","Nvbb_constraint",Nvb,RooConst(Nvbjets),RooConst(Nvbjets*Nvbjets_uncert));
//RooProdPdf model_constraint("model_constraint","model with constraint",RooArgSet(model,Eb_constraint)) ;
//RooProdPdf model_constraint("model_constraint","model with constraint",RooArgSet(model,Eudsc_constraint)) ;
//RooProdPdf model_constraint("model_constraint","model with constraint",RooArgSet(model,Euds_constraint)) ;
RooProdPdf model_constraint("model_constraint","model with constraint",RooArgSet(model,Euds_constraint,Nst_constraint,Nvb_constraint)) ;
// C r e a t e d a t a s e t
// -------------------------------------------------------------------------------
RooDataSet data("data","data",RooArgSet(nbjets)) ;
for (Int_t i=0 ; i<hNbtaggedJets->GetBinContent(hNbtaggedJets->FindBin(0.)) ; i++) { nbjets.setLabel("N0bjet") ; data.add(RooArgSet(nbjets));}
for (Int_t i=0 ; i<hNbtaggedJets->GetBinContent(hNbtaggedJets->FindBin(1.)) ; i++) { nbjets.setLabel("N1bjet") ; data.add(RooArgSet(nbjets));}
for (Int_t i=0 ; i<hNbtaggedJets->GetBinContent(hNbtaggedJets->FindBin(2.)) ; i++) { nbjets.setLabel("N2bjets") ; data.add(RooArgSet(nbjets));}
for (Int_t i=0 ; i<hNbtaggedJets->GetBinContent(hNbtaggedJets->FindBin(3.)) ; i++) { nbjets.setLabel("N3bjets") ; data.add(RooArgSet(nbjets));}
//data.Print("v");
Roo1DTable* table = data.table(nbjets);
table->Print("v");
// F i t t h e d a t a a n d c o n s t r u c t t h e l i k e l i h o o d f u n c t i o n
// ----------------------------------------------------------------------------------------------
//RooAbsReal* nll = model.createNLL(data);//,Optimize(0));
RooAbsReal* nll = model_constraint.createNLL(data,NumCPU(4));//,Optimize(0));
RooMinimizer minimizer(*nll);
//minimizer.optimizeConst(0) ; DO NOT SET IT TO TRUE, WILL NOT CONVERGE OTHERWISE
minimizer.setPrintLevel(-1);
//minimizer.setNoWarn();
// Set algorithm
minimizer.minimize("Minuit2", "Combined");
//minimizer.minimize("GSLMultiMin", "ConjugateFR");
//minimizer.minimize("GSLMultiMin", "BFGS2");
minimizer.minos();
if(doPE) RooFitResult* fit_result = model_constraint.fitTo(data,Constrain(RooArgSet(Euds_constraint,Nst_constraint)),Save(1),Extended(1),Minos(1),Strategy(2));//,Constrain(RooArgSet(Euds_constraint,Nst_constraint)));
//,ExternalConstraints(RooArgSet(Eb_constraint,Eudsc_constraint,Euds_constraint)));
RooFitResult* fit_result = minimizer.save();
fit_result->Print("v");
RooMCStudy* mcstudy = new RooMCStudy(model,nbjets,Constrain(RooArgSet(Euds_constraint,Nst_constraint)),Binned(kTRUE),Silence(),Extended(kTRUE),FitOptions(Optimize(0),Save(0),Minos(1),Extended(1),Strategy(2),PrintEvalErrors(-1)));
// Generate and fit NbOfPE samples of Poisson(nExpected) events
if(doPE){
mcstudy->generateAndFit(NbOfPE,nExpected) ;
}
// C o n s t r u c t p r o f i l e l i k e l i h o o d i n f r a c
// -----------------------------------------------------------------------
// The profile likelihood estimator on nll for Ntt will minimize nll w.r.t
// all floating parameters except frac for each evaluation
/*
RooAbsReal* pll_Ntt = nll->createProfile(Ntt) ;
// Plot the profile likelihood in frac
RooPlot* frame1 = Ntt.frame(Title("ProfileLL in Ntt")) ;
pll_Ntt->plotOn(frame1,LineColor(kRed)) ;
*/
// P l o t f i t r e s u l t s
// ---------------------------------------------------------------------
fout->cd();
//frame1->Write();
//hNbtaggedJets_ttjets->Draw("COLZ");
hNbtaggedJets_ttjets->Write();
//hNbtaggedJets_wjets->Draw("COLZ");
hNbtaggedJets_wjets->Write();
//hNbtaggedJets_zjets->Draw("COLZ");
hNbtaggedJets_zjets->Write();
//hNbtaggedJets_stjets->Draw("COLZ");
hNbtaggedJets_stjets->Write();
//hNbtaggedJets_vbjets->Draw("COLZ");
//hNbtaggedJets_vbjets->Write();
hNbtaggedJets->Write();
hWbb_In_WJets->Write();
hWcx_In_WJets->Write();
hWLFg_In_WJets->Write();
if(doPE){
RooPlot* frame_Nttpull = mcstudy->plotPull(Ntt,-4,4,100) ;
frame_Nttpull->SetName("myRooPlot_Nttpull");
frame_Nttpull->Write();
RooPlot* frame_Ntt = mcstudy->plotParam(Ntt);//,Binning(100,NbOfTTlike[NbOfJets-3]*(1-0.2),NbOfTTlike[NbOfJets-3]*(1+0.2))) ;
frame_Ntt->SetName("myRooPlot_Ntt");
frame_Ntt->Write();
RooPlot* frame_Nvpull = mcstudy->plotPull(Nv,-4,4,100) ;
frame_Nvpull->SetName("myRooPlot_Nvpull");
frame_Nvpull->Write();
RooPlot* frame_Nv = mcstudy->plotParam(Nv);//,Binning(100,NbOfVlike[NbOfJets-3]*(1-0.2),NbOfVlike[NbOfJets-3]*(1+0.2))) ;
frame_Nv->SetName("myRooPlot_Nv");
frame_Nv->Write();
if(!eb.isConstant()){
RooPlot* frame_ebpull = mcstudy->plotPull(eb,-4,4,100) ;
frame_ebpull->SetName("myRooPlot_Ebpull");
frame_ebpull->Write();
RooPlot* frame_eb = mcstudy->plotParam(eb,Binning(100)) ;
frame_eb->SetName("myRooPlot_eb");
frame_eb->Write();
}
if(!eudsc.isConstant()){
RooPlot* frame_eudscpull = mcstudy->plotPull(eudsc,-4,4,100) ;
frame_eudscpull->SetName("myRooPlot_Eudscpull");
frame_eudscpull->Write();
RooPlot* frame_eudsc = mcstudy->plotParam(eudsc,Binning(100)) ;
frame_eudsc->SetName("myRooPlot_eudsc");
frame_eudsc->Write();
}
if(!euds.isConstant()){
RooPlot* frame_eudspull = mcstudy->plotPull(euds,-4,4,100) ;
frame_eudspull->SetName("myRooPlot_Eudspull");
frame_eudspull->Write();
RooPlot* frame_euds = mcstudy->plotParam(euds,Binning(100)) ;
frame_euds->SetName("myRooPlot_euds");
frame_euds->Write();
}
}
// Closing files
fout->Close();
// Free memory (if needed)
cout << "It took us " << ((double)clock() - start) / CLOCKS_PER_SEC << " to run the program" << endl;
cout << "********************************************" << endl;
cout << " End of the program !! " << endl;
cout << "********************************************" << endl;
return 0;
}
/*
gcc -O $(root-config --cflags) $(root-config --libs) -lMathMore -lFoam -lMinuit -lRooFitCore -lRooFit -L/sandbox/cmss/slc5_amd64_gcc434/cms/cmssw/CMSSW_4_2_8/external/slc5_amd64_gcc434/lib -ldcap -o StopSearches_VJetsBckgdEst.exe StopSearches_VJetsBckgdEst.cc
*/
int main (int argc, char *argv[])
{
return StopSearches_VJetsBckgdEst();
}
|
737ef1b289ff79176fd5d8f2ab22ebfe2b03be4c | 9c3a452da21455f64e1e86c1385d3d85c46070ee | /IfcPlusPlus/src/ifcpp/IFC4/lib/IfcObjectTypeEnum.cpp | 86ce1744f8c5c57927bef5bab825ede346a7cdd3 | [
"MIT"
] | permissive | tao00720/ifcplusplus | a0e813757d79b505e36908894b031928389122c2 | 3d2e9aab5f74809a09832d041c20dec7323fd41d | refs/heads/master | 2021-07-02T04:51:25.421124 | 2017-04-11T15:53:48 | 2017-04-11T15:53:48 | 103,811,406 | 0 | 0 | null | 2017-09-17T07:35:36 | 2017-09-17T07:35:36 | null | UTF-8 | C++ | false | false | 2,850 | cpp | IfcObjectTypeEnum.cpp | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/IfcPPBasicTypes.h"
#include "ifcpp/model/IfcPPException.h"
#include "ifcpp/IFC4/include/IfcObjectTypeEnum.h"
// TYPE IfcObjectTypeEnum = ENUMERATION OF (PRODUCT ,PROCESS ,CONTROL ,RESOURCE ,ACTOR ,GROUP ,PROJECT ,NOTDEFINED);
IfcObjectTypeEnum::IfcObjectTypeEnum() {}
IfcObjectTypeEnum::~IfcObjectTypeEnum() {}
shared_ptr<IfcPPObject> IfcObjectTypeEnum::getDeepCopy( IfcPPCopyOptions& options )
{
shared_ptr<IfcObjectTypeEnum> copy_self( new IfcObjectTypeEnum() );
copy_self->m_enum = m_enum;
return copy_self;
}
void IfcObjectTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
if( is_select_type ) { stream << "IFCOBJECTTYPEENUM("; }
if( m_enum == ENUM_PRODUCT )
{
stream << ".PRODUCT.";
}
else if( m_enum == ENUM_PROCESS )
{
stream << ".PROCESS.";
}
else if( m_enum == ENUM_CONTROL )
{
stream << ".CONTROL.";
}
else if( m_enum == ENUM_RESOURCE )
{
stream << ".RESOURCE.";
}
else if( m_enum == ENUM_ACTOR )
{
stream << ".ACTOR.";
}
else if( m_enum == ENUM_GROUP )
{
stream << ".GROUP.";
}
else if( m_enum == ENUM_PROJECT )
{
stream << ".PROJECT.";
}
else if( m_enum == ENUM_NOTDEFINED )
{
stream << ".NOTDEFINED.";
}
if( is_select_type ) { stream << ")"; }
}
shared_ptr<IfcObjectTypeEnum> IfcObjectTypeEnum::createObjectFromSTEP( const std::wstring& arg, const map_t<int,shared_ptr<IfcPPEntity> >& map )
{
// read TYPE
if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcObjectTypeEnum>(); }
else if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcObjectTypeEnum>(); }
shared_ptr<IfcObjectTypeEnum> type_object( new IfcObjectTypeEnum() );
if( boost::iequals( arg, L".PRODUCT." ) )
{
type_object->m_enum = IfcObjectTypeEnum::ENUM_PRODUCT;
}
else if( boost::iequals( arg, L".PROCESS." ) )
{
type_object->m_enum = IfcObjectTypeEnum::ENUM_PROCESS;
}
else if( boost::iequals( arg, L".CONTROL." ) )
{
type_object->m_enum = IfcObjectTypeEnum::ENUM_CONTROL;
}
else if( boost::iequals( arg, L".RESOURCE." ) )
{
type_object->m_enum = IfcObjectTypeEnum::ENUM_RESOURCE;
}
else if( boost::iequals( arg, L".ACTOR." ) )
{
type_object->m_enum = IfcObjectTypeEnum::ENUM_ACTOR;
}
else if( boost::iequals( arg, L".GROUP." ) )
{
type_object->m_enum = IfcObjectTypeEnum::ENUM_GROUP;
}
else if( boost::iequals( arg, L".PROJECT." ) )
{
type_object->m_enum = IfcObjectTypeEnum::ENUM_PROJECT;
}
else if( boost::iequals( arg, L".NOTDEFINED." ) )
{
type_object->m_enum = IfcObjectTypeEnum::ENUM_NOTDEFINED;
}
return type_object;
}
|
b725735edb196876783fa2dd32a6fb4fb5181b92 | 0b27ca622610261415b56fd7d53e87cc66042fd5 | /exegesis/util/bits.h | 790ea9af6e7ccc6a725aa17fdb4509a648b6097c | [
"Apache-2.0"
] | permissive | google/EXEgesis | 1483dfd35b996bdad2dc1509ba7cdf91991d0c1b | ef5b019969a6aa4c5e26680a3728bb783661db48 | refs/heads/master | 2023-09-02T02:40:40.663198 | 2023-01-13T16:18:58 | 2023-01-13T16:18:58 | 76,657,412 | 214 | 40 | Apache-2.0 | 2023-04-10T00:27:11 | 2016-12-16T13:52:42 | C++ | UTF-8 | C++ | false | false | 2,645 | h | bits.h | // Copyright 2017 Google Inc.
//
// 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.
// Helper functions for reading bits of unsigned integers.
#ifndef EXEGESIS_UTIL_BITS_H_
#define EXEGESIS_UTIL_BITS_H_
#include <cstdint>
#include "glog/logging.h"
namespace exegesis {
// Returns true if the bit at 'bit_position' of 'value' is set to one.
// Otherwise, returns false. The position of the bit is zero-based.
inline bool IsNthBitSet(uint32_t value, int bit_position) {
DCHECK_LE(0, bit_position);
DCHECK_LT(bit_position, 32);
return value & (uint32_t{1} << bit_position);
}
// Clears the bits between the specified bit positions in 'value';
// 'start_bit_position' is the zero-based position of the first bit included in
// the range, and 'end_bit_position' is the zero-based position of the first bit
// not included in the range.
// The function returns the value with the bits cleared.
inline uint32_t ClearBitRange(uint32_t value, int start_bit_position,
int end_bit_position) {
DCHECK_LE(0, start_bit_position);
DCHECK_LT(start_bit_position, end_bit_position);
DCHECK_LE(end_bit_position, 32);
constexpr uint32_t kAllBits32 = 0xffffffffUL;
const int num_mask_bits = 32 - end_bit_position + start_bit_position;
const uint32_t inverse_mask = (kAllBits32 >> num_mask_bits)
<< start_bit_position;
return value & (~inverse_mask);
}
// Extracts the integer stored between the specified bits in 'value';
// 'start_bit_position' is the zero-based position of the first bit included in
// the range, and 'end_bit_position' is the zero-based position of the first bit
// not included in the range.
inline uint32_t GetBitRange(uint32_t value, int start_bit_position,
int end_bit_position) {
DCHECK_LE(0, start_bit_position);
DCHECK_LT(start_bit_position, end_bit_position);
DCHECK_LE(end_bit_position, 32);
constexpr uint32_t kAllBits32 = 0xffffffff;
const uint32_t mask = kAllBits32 >> (32 - end_bit_position);
return (value & mask) >> start_bit_position;
}
} // namespace exegesis
#endif // EXEGESIS_UTIL_BITS_H_
|
746b3a7a44022f4365cc4b6518c389ebadcbc6d6 | dfb64b62db1c725b65bc3ad36d16ebc016363afc | /src/fungame/graphic/VBO.cpp | 89b284ef28a75a228f9698d311a06feefdc78ec3 | [] | no_license | zhengweifu2018/fungame | 1afeb7a98a2f0bd473d5af27f37c1c4b826aedf5 | 699c61ab7abfc23a01afd63fc34da896906fb6c2 | refs/heads/master | 2023-05-26T07:39:02.805570 | 2020-01-13T12:20:24 | 2020-01-13T12:20:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90 | cpp | VBO.cpp | #include "fungame/graphic/VBO.h"
namespace fungrame { namespace graphic {
}}
|
f59351d86a272b56c5014810c63dbff8a3082961 | aeb57b2d79638213f80d563a4eb6371785869761 | /Hoowan-Editor/src/game/Player/Player.h | 24a3d928aebd9a32d3fcd299a39ba88291c777f1 | [
"Apache-2.0"
] | permissive | juanbecerra0/Hoowan | 9278cdebb09b83be703bf352d50aef9f977627e2 | 27d535a8f700537fe7158b40a7cbfa9c54c46e71 | refs/heads/master | 2023-01-14T09:35:21.081982 | 2020-11-10T16:37:41 | 2020-11-10T16:37:41 | 270,831,533 | 0 | 0 | Apache-2.0 | 2020-06-19T21:42:56 | 2020-06-08T21:16:48 | C++ | UTF-8 | C++ | false | false | 884 | h | Player.h | #pragma once
#include "Hoowan.h"
#include "../Scene/SpriteSheet.h"
class Player
{
public:
Player(Hoowan::Ref<Hoowan::Scene> scene, glm::vec2& startingPosition);
~Player();
void OnUpdate(Hoowan::Timestep ts);
glm::mat4& GetTransform() { return m_PlayerEntity.GetComponent<Hoowan::TransformComponent>().GetTransform(); }
glm::vec2 GetPosition() { return m_PlayerEntity.GetComponent<Hoowan::TransformComponent>().GetTransform()[3]; }
private:
void Move(bool holdingLeft, bool holdingRight, Hoowan::Timestep ts);
void Jump(bool holdingJump, Hoowan::Timestep ts);
void ApplyGravity(Hoowan::Timestep ts);
void FlipPlayerOrientation(bool flip);
private:
Hoowan::Entity m_PlayerEntity;
PlayerSprites m_PlayerSprites;
glm::vec2 m_DesiredVelocity = { 0.0f, 0.0f };
const glm::vec2 MAX_VELOCITY = { 8.0f, 9.8f };
private:
float m_Mass = 1.5f;
bool m_HasJumped = false;
}; |
65a567ab5b871b77e88d023ec82a4278480aa670 | f4b873e035d4f8ecebaed6305f976804796b2adc | /heroes2/variant.cpp | af5de1f5dd6777114caff20a9caba36ab72a228d | [] | no_license | Pavelius/heroes2 | 1066b6e242767364394c592b0a3f1a6b5880f413 | 00140380b737438367ff8f234cdc7a0a403c5502 | refs/heads/master | 2021-08-10T15:34:01.588053 | 2020-07-20T11:48:02 | 2020-07-20T11:48:02 | 204,486,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,214 | cpp | variant.cpp | #include "main.h"
const char* variant::getname() const {
switch(type) {
case Ability: return bsmeta<abilityi>::elements[value].name;
case Artifact: return bsmeta<artifacti>::elements[value].name;
case Castle: return bsmeta<castlei>::elements[value].getname();
case Hero: return bsmeta<heroi>::elements[value].getname();
case Landscape: return bsmeta<landscapei>::elements[value].name;
//case Moveable: return getmoveable()->getname();
case Skill: return bsmeta<skilli>::elements[value].name;
case Spell: return bsmeta<spelli>::elements[value].name;
case Monster: return bsmeta<monsteri>::elements[value].name;
default: return "";
}
}
variant::variant(const moveablei* v) : type(Moveable), value(v - bsmeta<moveablei>::elements) {}
variant::variant(const castlei* v) : type(CastleVar), value(v - bsmeta<castlei>::elements) {}
variant::variant(const heroi* v) : type(Hero), value(v ? v->getid() : RandomHero) {}
castlei* variant::getcastle() const {
return bsmeta<castlei>::elements + value;
}
heroi* variant::gethero() const {
if(value == RandomHero)
return 0;
return bsmeta<heroi>::elements + value;
}
moveablei* variant::getmoveable() const {
return bsmeta<moveablei>::elements + value;
} |
fecceab5e41028ca41b3f8538f15f817fb1c7d4f | 313a869d89a914a8d562379dbefb76f826e1e491 | /Source/Seraph/Public/Gloom/Interfaces/TargetsHexNode.h | 7ccb6be5628b14845445bc2993e9fabe9f5a51e4 | [] | no_license | shanemcdermott/TurnBasedHex | ced88a0ce55b205d0bf32bcb5a3594952d265f29 | b6a3659072eafefb571e92bcae3813c38294bbba | refs/heads/master | 2021-03-27T09:47:40.096537 | 2018-01-08T21:36:57 | 2018-01-08T21:36:57 | 116,730,958 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | h | TargetsHexNode.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "TargetsHexNode.generated.h"
class AActor;
// This class does not need to be modified.
UINTERFACE()
class UTargetsHexNode : public UInterface
{
GENERATED_UINTERFACE_BODY()
};
/**
*
*/
class ITargetsHexNode
{
GENERATED_IINTERFACE_BODY()
// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
virtual AActor* GetTarget();
virtual void SetTarget(AActor* NewTarget);
};
|
727aa61e1a44bf8d9df1de637d63ec3102f361cd | 9aee1fa1607a7eca8b1c820ef87beb6bc4341f6f | /server/plugin/src/process.cpp | b3a8437adfba3be494f7bc62f231b9fa427a60a2 | [
"Apache-2.0"
] | permissive | liuxiaozhen/nuts | d9e6bdaeb23d242d71bba2e37f0c270f80f53dbe | 5f0f56a38393be1d6a945f941890067d852b6ddc | refs/heads/master | 2020-05-29T11:43:28.875563 | 2013-12-16T16:20:35 | 2013-12-16T16:20:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 851 | cpp | process.cpp | /*
* process.cpp
*
* Created on: 2013-12-15
*/
#include "plugin.h"
/*
Bet 下注
Call 跟注
Fold 弃牌
Check 让牌 / 观让
raise 加注
Re-raise 再加注
All-in 全押 / 全进
这里分客户端命令和服务器命令
*/
static enum{
register=1,
further_register=2,
fast_login=3,
pwd_login=4,
imei_pwd_login=5,
enter_section=6,
start_game=7,//准备好
leave_game=8,
follow=9,
};
extern redisContext *g_redis_context;
int cmd_process(plugin_task *tsp)
{
uint8_t *data_start = eservice_buf_start(tsp->input_ebp);
plugin_header_t *plugin_head = tsp->plugin_head;
switch(plugin_head->Cmd)
{
case register: //login
break;
case 2://enter
break;
case 3:
break;
default:
g_err("cmd error ,cmd:%d,uin:%lu",plugin_head->Cmd,plugin_head->Uin);
return -1;
}
}
|
591cc297372a192f2e440b9ae1e47aa854bcb4da | 78cc7bc0c72838893cf59b1c8683fa82386b55dd | /interface/RecoObjects/SelectionOutputInfo.h | 9d5b1990d23e8c6b5d7af04f2b0e220da1532a88 | [
"Apache-2.0"
] | permissive | kreczko/AnalysisSoftware | 2751431e146a7945ce6b093d822ab70c3a45dc19 | fa83a3775a8d644e6098d28dbc6f3d7f1a11b400 | refs/heads/master | 2021-01-18T07:19:27.617774 | 2015-09-14T10:31:06 | 2015-09-14T10:31:06 | 7,689,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | h | SelectionOutputInfo.h | /*
* SelectionOutputInfo.h
*
* Created on: Dec 10, 2014
* Author: Emyr Clement
*/
#ifndef SELECTIONOUTPUTINFO_H_
#define SELECTIONOUTPUTINFO_H_
#include <vector>
#include <string>
#include <boost/array.hpp>
#include "Jet.h"
namespace BAT {
class SelectionOutputInfo {
public:
SelectionOutputInfo();
virtual ~SelectionOutputInfo();
//getters
unsigned int getNumberOfJets() const;
unsigned int getNumberOfBJets() const;
unsigned int getSignalLeptonIndex() const;
std::vector<unsigned int> getCleanedJetIndex() const;
std::vector<unsigned int> getCleanedBJetIndex() const;
//setters
void setNumberOfJets( unsigned int nJets );
void setNumberOfBJets( unsigned int nBJets );
void setSignalLeptonIndex( unsigned int signalLeptonIndices );
void setCleanedJetIndex( std::vector<unsigned int> cleanedJetsIndices );
void setCleanedBJetIndex( std::vector<unsigned int> cleanedBJetsIndices );
private:
unsigned int nJets_, nBJets_;
unsigned int signalLeptonIndex_;
std::vector<unsigned int> cleanedJetsIndices_;
std::vector<unsigned int> cleanedBJetsIndices_;
};
}
#endif /* SELECTIONOUTPUTINFO_H_ */
|
fdc108c8139b39a1fa3a28d215a595a5e1aef9ee | fc50c001c108cdeff73571beacc852ec73fcd05e | /microunit.h | b972ce78bf3a091541802c9916c518d7d75e1483 | [
"BSD-3-Clause"
] | permissive | smiranda/microunit | cbb04d428f85f4353073babde6ff8d6266d35af7 | 871a581a71408fc746b1c7f90730c34638baf8df | refs/heads/master | 2021-01-10T03:34:03.000300 | 2018-07-18T11:05:00 | 2018-07-18T11:05:00 | 54,343,039 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,375 | h | microunit.h | /**
* @file microunit.h
* @version 0.2
* @author Sebastiao Salvador de Miranda (ssm)
* @brief Tiny library for cpp unit testing. Should work on any c++11 compiler.
*
* Simply include this header in your test implementation file (e.g., main.cpp)
* and call microunit::UnitTester::Run() in the function main(). To register
* a new unit test case, use the macro UNIT (See the example below). Inside the
* test case body, you can use the following macros to control the result
* of the test.
*
* @li PASS() : Pass the test and return.
* @li FAIL() : Fail the test and return.
* @li ASSERT_TRUE(condition) : If the condition does not hold, fail and return.
* @li ASSERT_FALSE(condition) : If the condition holds, fail and return.
*
* @code{.cpp}
* UNIT(Test_Two_Plus_Two) {
* ASSERT_TRUE(2 + 2 == 4);
* };
* // ...
* int main(){
* return microunit::UnitTester::Run() ? 0 : -1;
* }
* @endcode
*
* @copyright Copyright (c) 2016-2017, Sebastiao Salvador de Miranda.
* All rights reserved. See licence below.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* (1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* (3) The name of the author may not be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#ifndef _MICROUNIT_MICROUNIT_H_
#define _MICROUNIT_MICROUNIT_H_
#include <string.h>
#include <map>
#include <string>
#include <vector>
#include <iostream>
/**
* @brief Helper macros to get current logging filename
*/
#if defined(_WIN32)
#define __FILENAME__ (strrchr(__FILE__, '\\') ? \
strrchr(__FILE__, '\\') + 1 : __FILE__)
#else
#define __FILENAME__ (strrchr(__FILE__, '/') ? \
strrchr(__FILE__, '/') + 1 : __FILE__)
#endif
#define MICROUNIT_SEPARATOR "----------------------------------------" \
"----------------------------------------"
#if defined(_WIN32)
#include "windows.h"
#endif
namespace microunit {
const static int COLORCODE_GREY{ 7 };
const static int COLORCODE_GREEN{ 10 };
const static int COLORCODE_RED{ 12 };
const static int COLORCODE_YELLOW{ 14 };
/**
* @brief Helper class to convert from color codes to ansi escape codes
* Used to print color in non-win32 systems.
*/
inline std::string ColorCodeToANSI(const int color_code) {
switch (color_code) {
case COLORCODE_GREY: return "\033[22;37m";
case COLORCODE_GREEN: return "\033[01;32m";
case COLORCODE_RED: return "\033[01;31m";
case COLORCODE_YELLOW: return "\033[01;33m";
default: return "";
}
}
/**
* @brief Helper function to change the current terminal color.
* @param [in] color_code Input color code.
*/
inline void SetTerminalColor(int color_code) {
#if defined(_WIN32)
HANDLE handler = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(handler, &buffer_info);
SetConsoleTextAttribute(handler, ((buffer_info.wAttributes & 0xFFF0) |
(WORD)color_code));
#else
std::cout << ColorCodeToANSI(color_code);
#endif
}
/**
* @brief Helper class to be used as a iostream manipulator and change the
* terminal color.
*/
class Color {
public:
Color(int code) : code_(code) {}
void Set() const {
SetTerminalColor(code_);
}
int code() const { return code_; }
private:
int code_;
};
const static Color Grey{ COLORCODE_GREY };
const static Color Green{ COLORCODE_GREEN };
const static Color Red{ COLORCODE_RED };
const static Color Yellow{ COLORCODE_YELLOW };
/**
* @brief Helper class to be used in a cout streaming statement. Resets to
* the default terminal color upon statement completion.
*/
class SaveColor {
public:
~SaveColor() {
SetTerminalColor(Grey.code());
};
};
/**
* @brief Helper class to be used in a cout streaming statement. Puts a line
* break upon statement completion.
*/
class EndingLineBreak {
public:
~EndingLineBreak() {
std::cout << std::endl;
};
};
}
/** @brief Operator to allow using SaveColor class with an ostream */
inline std::ostream& operator<<(std::ostream& os,
const microunit::SaveColor& obj) {
return os;
}
/** @brief Operator to allow using EndingLineBreak class with an ostream */
inline std::ostream& operator<<(std::ostream& os,
const microunit::EndingLineBreak& obj) {
return os;
}
/** @brief Operator to allow using Color class with an ostream */
inline std::ostream& operator<<(std::ostream& os,
const microunit::Color& color) {
color.Set();
return os;
}
/**
* @brief Macro for writing to the terminal an INFO-level log
*/
#define TERMINAL_INFO std::cout << microunit::SaveColor{} << \
microunit::EndingLineBreak{} << microunit::Yellow << "[ ] "
#define LOG_INFO TERMINAL_INFO << __FILENAME__ << ":" << __LINE__ << ": "
/**
* @brief Macro for writing to the terminal a BAD-level log
*/
#define TERMINAL_BAD std::cout << microunit::SaveColor{} << \
microunit::EndingLineBreak{} << microunit::Red << "[ ] "
#define LOG_BAD TERMINAL_BAD << __FILENAME__ << ":" << __LINE__ << ": "
/**
* @brief Macro for writing to the terminal a GOOD-level log
*/
#define TERMINAL_GOOD std::cout << microunit::SaveColor{} << \
microunit::EndingLineBreak{} << microunit::Green << "[ ] "
#define LOG_GOOD TERMINAL_GOOD << __FILENAME__ << ":" << __LINE__ << ": "
namespace microunit {
/**
* @brief Result of a unit test.
*/
struct UnitFunctionResult {
bool success{ true };
};
/**
* @brief Unit test function type.
*/
typedef void(*UnitFunction)(UnitFunctionResult*);
/**
* @brief Main class for unit test management. This class is a singleton
* and maintains a list of all registered unit test cases.
*/
class UnitTester {
public:
/**
* @brief Run all the registered unit test cases.
* @returns True if all tests pass, false otherwise.
*/
static bool Run() {
std::vector<std::string> failures, sucesses;
TERMINAL_INFO
<< "Will run " << Instance().unitfunction_map_.size()
<< " test cases";
// Iterate all registered unit tests
for (auto& unit : Instance().unitfunction_map_) {
std::cout << MICROUNIT_SEPARATOR << std::endl;
TERMINAL_GOOD << "Test case '" << unit.first << "'";
// Run the unit test
UnitFunctionResult result;
unit.second(&result);
if (!result.success) {
TERMINAL_BAD << "Failed test";
failures.push_back(unit.first);
} else {
TERMINAL_GOOD << "Passed test";
sucesses.push_back(unit.first);
}
}
std::cout
<< MICROUNIT_SEPARATOR << std::endl
<< MICROUNIT_SEPARATOR << std::endl;
TERMINAL_GOOD << "Passed " << sucesses.size()
<< " test cases:";
for (const auto& success_t : sucesses) {
TERMINAL_GOOD << success_t;
}
std::cout << MICROUNIT_SEPARATOR << std::endl;
// Output result summary
if (failures.empty()) {
TERMINAL_GOOD << "All tests passed";
std::cout << MICROUNIT_SEPARATOR << std::endl;
return true;
} else {
TERMINAL_BAD << "Failed " << failures.size()
<< " test cases:";
for (const auto& failure : failures) {
TERMINAL_BAD << failure;
}
std::cout << MICROUNIT_SEPARATOR << std::endl;
return false;
}
}
/**
* @brief Register a unit test case function. In regular library client usage,
* this doesn't need to be called, and the macro UNIT should be used
* instead.
* @param [in] name Name of the unit test case.
* @param [in] function Pointer to unit test case function.
* @returns True if all tests pass, false otherwise.
*/
static void RegisterFunction(const std::string &name,
UnitFunction function) {
Instance().unitfunction_map_.emplace(name, function);
}
/**
* @brief Helper class to register a unit test in construction time. This is
* used to call RegisterFunction in the construction of a static
* helper object. Used by the REGISTER_UNIT macro, which in turn is
* used by the UNIT macro.
* @returns True if all tests pass, false otherwise.
*/
class Registrator {
public:
Registrator(const std::string &name,
UnitFunction function) {
UnitTester::RegisterFunction(name, function);
};
Registrator(const Registrator&) = delete;
Registrator(Registrator&&) = delete;
~Registrator() {};
};
~UnitTester() {};
UnitTester(const UnitTester&) = delete;
UnitTester(UnitTester&&) = delete;
private:
UnitTester() {};
static UnitTester& Instance() {
static UnitTester instance;
return instance;
}
std::map<std::string, UnitFunction> unitfunction_map_;
};
}
#define MACROCAT_NEXP(A, B) A ## B
#define MACROCAT(A, B) MACROCAT_NEXP(A, B)
/**
* @brief Register a unit function using a helper static Registrator object.
*/
#define REGISTER_UNIT(FUNCTION) \
static microunit::UnitTester::Registrator \
MACROCAT(MICROUNIT_REGISTRATION, __COUNTER__)(#FUNCTION, FUNCTION);
/**
* @brief Define a unit function body. This macro is the one which should be used
* by client code to define unit test cases.
* @code{.cpp}
* UNIT(Test_Two_Plus_Two) {
* ASSERT_TRUE(2 + 2 == 4);
* };
* @endcode
*/
#define UNIT(FUNCTION) \
void FUNCTION(microunit::UnitFunctionResult*); \
REGISTER_UNIT(FUNCTION); \
void FUNCTION(microunit::UnitFunctionResult *__microunit_testresult)
/**
* @brief Pass the test and return from the test case.
*/
#define PASS() { \
LOG_GOOD << "Test stopped: Pass"; \
__microunit_testresult->success = true; \
return; \
}
/**
* @brief Fail the test and return from the test case.
*/
#define FAIL() { \
LOG_BAD << "Test stopped: Fail"; \
__microunit_testresult->success = false; \
return; \
}
/**
* @brief Check a particular test condition. If the condition does not hold,
* fail the test and return.
*/
#define ASSERT_TRUE(condition) if(!(condition)) { \
LOG_BAD << "Assert-true failed: " #condition; \
FAIL(); \
}
/**
* @brief Check a particular test condition. If the condition holds, fail the
* test and return.
*/
#define ASSERT_FALSE(condition) if((condition)) { \
LOG_BAD << "Assert-false failed: " #condition << std::endl; \
FAIL(); \
}
#endif
|
1a55b5d84d9cb2e96700db63ec1a817bc4c3dd54 | 12d3eed45e4ab921ffedd67e077dab0415b0c7d7 | /src/engine/main.cpp | 3d65f171f8966505b0469f1e89d8574563b150ed | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause"
] | permissive | ACBob/Bube | b2db4f36d9b9e4303bbe13e1f8c4676622a25d5d | 282bee7fd8a628f00550c65d719cd02e2afc6420 | refs/heads/master | 2023-04-23T20:09:35.885465 | 2021-05-05T20:03:27 | 2021-05-05T20:03:27 | 330,546,207 | 6 | 1 | null | 2021-03-25T10:52:09 | 2021-01-18T03:39:25 | C++ | UTF-8 | C++ | false | false | 39,286 | cpp | main.cpp | // main.cpp: initialisation & main loop
#include "engine.h"
#ifdef SDL_VIDEO_DRIVER_X11
#include "SDL_syswm.h"
#endif
extern void cleargamma();
void cleanup()
{
recorder::stop();
cleanupserver();
SDL_ShowCursor(SDL_TRUE);
SDL_SetRelativeMouseMode(SDL_FALSE);
if (screen)
SDL_SetWindowGrab(screen, SDL_FALSE);
cleargamma();
freeocta(worldroot);
extern void clear_command();
clear_command();
extern void clear_console();
clear_console();
extern void clear_mdls();
clear_mdls();
extern void clear_sound();
clear_sound();
closelogfile();
#ifdef __APPLE__
if (screen)
SDL_SetWindowFullscreen(screen, 0);
#endif
SDL_Quit();
}
extern void writeinitcfg();
void quit() // normal exit
{
writeinitcfg();
writeservercfg();
abortconnect();
disconnect();
localdisconnect();
writecfg();
cleanup();
exit(EXIT_SUCCESS);
}
void fatal(const char *s, ...) // failure exit
{
static int errors = 0;
errors++;
if (errors <= 2) // print up to one extra recursive error
{
defvformatstring(msg, s, s);
logoutf("%s", msg);
if (errors <= 1) // avoid recursion
{
if (SDL_WasInit(SDL_INIT_VIDEO))
{
SDL_ShowCursor(SDL_TRUE);
SDL_SetRelativeMouseMode(SDL_FALSE);
if (screen)
SDL_SetWindowGrab(screen, SDL_FALSE);
cleargamma();
#ifdef __APPLE__
if (screen)
SDL_SetWindowFullscreen(screen, 0);
#endif
}
SDL_Quit();
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "BubeEngine fatal error", msg, NULL);
}
}
exit(EXIT_FAILURE);
}
int curtime = 0, lastmillis = 1, elapsedtime = 0, totalmillis = 1;
dynent *player = NULL;
int initing = NOT_INITING;
bool initwarning(const char *desc, int level, int type)
{
if (initing < level)
{
addchange(desc, type);
return true;
}
return false;
}
VAR(desktopw, 1, 0, 0);
VAR(desktoph, 1, 0, 0);
int screenw = 0, screenh = 0;
SDL_Window *screen = NULL;
SDL_GLContext glcontext = NULL;
#define SCR_MINW 320
#define SCR_MINH 200
#define SCR_MAXW 10000
#define SCR_MAXH 10000
#define SCR_DEFAULTW 1024
#define SCR_DEFAULTH 768
VARF(scr_w, SCR_MINW, -1, SCR_MAXW, initwarning("screen resolution"));
VARF(scr_h, SCR_MINH, -1, SCR_MAXH, initwarning("screen resolution"));
VARF(depthbits, 0, 0, 32, initwarning("depth-buffer precision"));
VARF(fsaa, -1, -1, 16, initwarning("anti-aliasing"));
void writeinitcfg()
{
stream *f = openutf8file("init.cfg", "w");
if (!f)
return;
f->printf("// automatically written on exit, DO NOT MODIFY\n// modify settings in game\n");
extern int fullscreen, fullscreendesktop;
f->printf("fullscreen %d\n", fullscreen);
f->printf("fullscreendesktop %d\n", fullscreendesktop);
f->printf("scr_w %d\n", scr_w);
f->printf("scr_h %d\n", scr_h);
f->printf("depthbits %d\n", depthbits);
f->printf("fsaa %d\n", fsaa);
extern int usesound, soundchans, soundfreq, soundbufferlen;
extern char *audiodriver;
f->printf("usesound %d\n", usesound);
f->printf("soundchans %d\n", soundchans);
f->printf("soundfreq %d\n", soundfreq);
f->printf("soundbufferlen %d\n", soundbufferlen);
if (audiodriver[0])
f->printf("audiodriver %s\n", escapestring(audiodriver));
delete f;
}
COMMAND(quit, "");
static void getbackgroundres(int &w, int &h)
{
float wk = 1, hk = 1;
if (w < 1024)
wk = 1024.0f / w;
if (h < 768)
hk = 768.0f / h;
wk = hk = max(wk, hk);
w = int(ceil(w * wk));
h = int(ceil(h * hk));
}
string backgroundcaption = "";
Texture *backgroundmapshot = NULL;
string backgroundmapname = "";
char *backgroundmapinfo = NULL;
void setbackgroundinfo(const char *caption = NULL, Texture *mapshot = NULL, const char *mapname = NULL,
const char *mapinfo = NULL)
{
renderedframe = false;
copystring(backgroundcaption, caption ? caption : "");
backgroundmapshot = mapshot;
copystring(backgroundmapname, mapname ? mapname : "");
if (mapinfo != backgroundmapinfo)
{
DELETEA(backgroundmapinfo);
if (mapinfo)
backgroundmapinfo = newstring(mapinfo);
}
}
void restorebackground(bool force = false)
{
if (renderedframe)
{
if (!force)
return;
setbackgroundinfo();
}
renderbackground(backgroundcaption[0] ? backgroundcaption : NULL, backgroundmapshot,
backgroundmapname[0] ? backgroundmapname : NULL, backgroundmapinfo, true);
}
void bgquad(float x, float y, float w, float h, float tx = 0, float ty = 0, float tw = 1, float th = 1)
{
gle::begin(GL_TRIANGLE_STRIP);
gle::attribf(x, y);
gle::attribf(tx, ty);
gle::attribf(x + w, y);
gle::attribf(tx + tw, ty);
gle::attribf(x, y + h);
gle::attribf(tx, ty + th);
gle::attribf(x + w, y + h);
gle::attribf(tx + tw, ty + th);
gle::end();
}
void renderbackground(const char *caption, Texture *mapshot, const char *mapname, const char *mapinfo, bool restore,
bool force)
{
if (!inbetweenframes && !force)
return;
if (!restore || force)
stopsounds(); // stop sounds while loading
int w = screenw, h = screenh;
if (forceaspect)
w = int(ceil(h * forceaspect));
getbackgroundres(w, h);
gettextres(w, h);
static int lastupdate = -1, lastw = -1, lasth = -1;
static float backgroundu = 0, backgroundv = 0, detailu = 0, detailv = 0;
static int numdecals = 0;
static struct decal
{
float x, y, size;
int side;
} decals[12];
if ((renderedframe && !mainmenu && lastupdate != lastmillis) || lastw != w || lasth != h)
{
lastupdate = lastmillis;
lastw = w;
lasth = h;
backgroundu = rndscale(1);
backgroundv = rndscale(1);
detailu = rndscale(1);
detailv = rndscale(1);
numdecals = sizeof(decals) / sizeof(decals[0]);
numdecals = numdecals / 3 + rnd((numdecals * 2) / 3 + 1);
float maxsize = min(w, h) / 16.0f;
loopi(numdecals)
{
decal d = {rndscale(w), rndscale(h), maxsize / 2 + rndscale(maxsize / 2), rnd(2)};
decals[i] = d;
}
}
else if (lastupdate != lastmillis)
lastupdate = lastmillis;
loopi(restore ? 1 : 3)
{
hudmatrix.ortho(0, w, h, 0, -1, 1);
resethudmatrix();
hudshader->set();
gle::colorf(1, 1, 1);
gle::defvertex(2);
gle::deftexcoord0();
settexture("data/background.png", 0);
float bu = w * 0.67f / 256.0f + backgroundu, bv = h * 0.67f / 256.0f + backgroundv;
bgquad(0, 0, w, h, 0, 0, bu, bv);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
settexture("data/background_detail.png", 0);
float du = w * 0.8f / 512.0f + detailu, dv = h * 0.8f / 512.0f + detailv;
bgquad(0, 0, w, h, 0, 0, du, dv);
settexture("data/background_decal.png", 3);
gle::begin(GL_QUADS);
loopj(numdecals)
{
float hsz = decals[j].size, hx = clamp(decals[j].x, hsz, w - hsz), hy = clamp(decals[j].y, hsz, h - hsz),
side = decals[j].side;
gle::attribf(hx - hsz, hy - hsz);
gle::attribf(side, 0);
gle::attribf(hx + hsz, hy - hsz);
gle::attribf(1 - side, 0);
gle::attribf(hx + hsz, hy + hsz);
gle::attribf(1 - side, 1);
gle::attribf(hx - hsz, hy + hsz);
gle::attribf(side, 1);
}
gle::end();
float lh = 0.5f * min(w, h), lw = lh * 2, lx = 0.5f * (w - lw), ly = 0.5f * (h * 0.5f - lh);
settexture((maxtexsize ? min(maxtexsize, hwtexsize) : hwtexsize) >= 1024 && (screenw > 1280 || screenh > 800)
? "data/logo_1024.png"
: "data/logo.png",
3);
bgquad(lx, ly, lw, lh);
if (caption)
{
int tw = text_width(caption);
float tsz = 0.04f * min(w, h) / FONTH, tx = 0.5f * (w - tw * tsz),
ty = h - 0.075f * 1.5f * min(w, h) - 1.25f * FONTH * tsz;
pushhudmatrix();
hudmatrix.translate(tx, ty, 0);
hudmatrix.scale(tsz, tsz, 1);
flushhudmatrix();
draw_text(caption, 0, 0);
pophudmatrix();
}
if (mapshot || mapname)
{
int infowidth = 12 * FONTH;
float sz = 0.35f * min(w, h), msz = (0.75f * min(w, h) - sz) / (infowidth + FONTH), x = 0.5f * (w - sz),
y = ly + lh - sz / 15;
if (mapinfo)
{
int mw, mh;
text_bounds(mapinfo, mw, mh, infowidth);
x -= 0.5f * (mw * msz + FONTH * msz);
}
if (mapshot && mapshot != notexture)
{
glBindTexture(GL_TEXTURE_2D, mapshot->id);
bgquad(x, y, sz, sz);
}
else
{
int qw, qh;
text_bounds("?", qw, qh);
float qsz = sz * 0.5f / max(qw, qh);
pushhudmatrix();
hudmatrix.translate(x + 0.5f * (sz - qw * qsz), y + 0.5f * (sz - qh * qsz), 0);
hudmatrix.scale(qsz, qsz, 1);
flushhudmatrix();
draw_text("?", 0, 0);
pophudmatrix();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
settexture("data/mapshot_frame.png", 3);
bgquad(x, y, sz, sz);
if (mapname)
{
int tw = text_width(mapname);
float tsz = sz / (8 * FONTH), tx = 0.9f * sz - tw * tsz, ty = 0.9f * sz - FONTH * tsz;
if (tx < 0.1f * sz)
{
tsz = 0.1f * sz / tw;
tx = 0.1f;
}
pushhudmatrix();
hudmatrix.translate(x + tx, y + ty, 0);
hudmatrix.scale(tsz, tsz, 1);
flushhudmatrix();
draw_text(mapname, 0, 0);
pophudmatrix();
}
if (mapinfo)
{
pushhudmatrix();
hudmatrix.translate(x + sz + FONTH * msz, y, 0);
hudmatrix.scale(msz, msz, 1);
flushhudmatrix();
draw_text(mapinfo, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, -1, infowidth);
pophudmatrix();
}
}
glDisable(GL_BLEND);
if (!restore)
swapbuffers(false);
}
if (!restore)
setbackgroundinfo(caption, mapshot, mapname, mapinfo);
}
VAR(progressbackground, 0, 0, 1);
float loadprogress = 0;
void renderprogress(float bar, const char *text, GLuint tex, bool background) // also used during loading
{
if (!inbetweenframes || drawtex)
return;
extern int menufps, maxfps;
int fps = menufps ? (maxfps ? min(maxfps, menufps) : menufps) : maxfps;
if (fps)
{
static int lastprogress = 0;
int ticks = SDL_GetTicks(), diff = ticks - lastprogress;
if (bar > 0 && diff >= 0 && diff < (1000 + fps - 1) / fps)
return;
lastprogress = ticks;
}
clientkeepalive(); // make sure our connection doesn't time out while loading maps etc.
SDL_PumpEvents(); // keep the event queue awake to avoid 'beachball' cursor
extern int mesa_swap_bug, curvsync;
bool forcebackground = progressbackground || (mesa_swap_bug && (curvsync || totalmillis == 1));
if (background || forcebackground)
restorebackground(forcebackground);
int w = screenw, h = screenh;
if (forceaspect)
w = int(ceil(h * forceaspect));
getbackgroundres(w, h);
gettextres(w, h);
hudmatrix.ortho(0, w, h, 0, -1, 1);
resethudmatrix();
hudshader->set();
gle::colorf(1, 1, 1);
gle::defvertex(2);
gle::deftexcoord0();
float fh = 0.075f * min(w, h), fw = fh * 10, fx = renderedframe ? w - fw - fh / 4 : 0.5f * (w - fw),
fy = renderedframe ? fh / 4 : h - fh * 1.5f, fu1 = 0 / 512.0f, fu2 = 511 / 512.0f, fv1 = 0 / 64.0f,
fv2 = 52 / 64.0f;
settexture("data/loading_frame.png", 3);
bgquad(fx, fy, fw, fh, fu1, fv1, fu2 - fu1, fv2 - fv1);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
float bw = fw * (511 - 2 * 17) / 511.0f, bh = fh * 20 / 52.0f, bx = fx + fw * 17 / 511.0f,
by = fy + fh * 16 / 52.0f, bv1 = 0 / 32.0f, bv2 = 20 / 32.0f, su1 = 0 / 32.0f, su2 = 7 / 32.0f,
sw = fw * 7 / 511.0f, eu1 = 23 / 32.0f, eu2 = 30 / 32.0f, ew = fw * 7 / 511.0f, mw = bw - sw - ew,
ex = bx + sw + max(mw * bar, fw * 7 / 511.0f);
if (bar > 0)
{
settexture("data/loading_bar.png", 3);
gle::begin(GL_QUADS);
gle::attribf(bx, by);
gle::attribf(su1, bv1);
gle::attribf(bx + sw, by);
gle::attribf(su2, bv1);
gle::attribf(bx + sw, by + bh);
gle::attribf(su2, bv2);
gle::attribf(bx, by + bh);
gle::attribf(su1, bv2);
gle::attribf(bx + sw, by);
gle::attribf(su2, bv1);
gle::attribf(ex, by);
gle::attribf(eu1, bv1);
gle::attribf(ex, by + bh);
gle::attribf(eu1, bv2);
gle::attribf(bx + sw, by + bh);
gle::attribf(su2, bv2);
gle::attribf(ex, by);
gle::attribf(eu1, bv1);
gle::attribf(ex + ew, by);
gle::attribf(eu2, bv1);
gle::attribf(ex + ew, by + bh);
gle::attribf(eu2, bv2);
gle::attribf(ex, by + bh);
gle::attribf(eu1, bv2);
gle::end();
}
if (text)
{
int tw = text_width(text);
float tsz = bh * 0.8f / FONTH;
if (tw * tsz > mw)
tsz = mw / tw;
pushhudmatrix();
hudmatrix.translate(bx + sw, by + (bh - FONTH * tsz) / 2, 0);
hudmatrix.scale(tsz, tsz, 1);
flushhudmatrix();
draw_text(text, 0, 0);
pophudmatrix();
}
glDisable(GL_BLEND);
if (tex)
{
glBindTexture(GL_TEXTURE_2D, tex);
float sz = 0.35f * min(w, h), x = 0.5f * (w - sz), y = 0.5f * min(w, h) - sz / 15;
bgquad(x, y, sz, sz);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
settexture("data/mapshot_frame.png", 3);
bgquad(x, y, sz, sz);
glDisable(GL_BLEND);
}
swapbuffers(false);
}
int keyrepeatmask = 0, textinputmask = 0;
Uint32 textinputtime = 0;
VAR(textinputfilter, 0, 5, 1000);
void keyrepeat(bool on, int mask)
{
if (on)
keyrepeatmask |= mask;
else
keyrepeatmask &= ~mask;
}
void textinput(bool on, int mask)
{
if (on)
{
if (!textinputmask)
{
SDL_StartTextInput();
textinputtime = SDL_GetTicks();
}
textinputmask |= mask;
}
else if (textinputmask)
{
textinputmask &= ~mask;
if (!textinputmask)
SDL_StopTextInput();
}
}
#ifdef WIN32
// SDL_WarpMouseInWindow behaves erratically on Windows, so force relative mouse instead.
VARN(relativemouse, userelativemouse, 1, 1, 0);
#else
VARNP(relativemouse, userelativemouse, 0, 1, 1);
#endif
bool shouldgrab = false, grabinput = false, minimized = false, canrelativemouse = true, relativemouse = false;
#ifdef SDL_VIDEO_DRIVER_X11
VAR(sdl_xgrab_bug, 0, 0, 1);
#endif
void inputgrab(bool on, bool delay = false)
{
#ifdef SDL_VIDEO_DRIVER_X11
bool wasrelativemouse = relativemouse;
#endif
if (on)
{
SDL_ShowCursor(SDL_FALSE);
if (canrelativemouse && userelativemouse)
{
if (SDL_SetRelativeMouseMode(SDL_TRUE) >= 0)
{
SDL_SetWindowGrab(screen, SDL_TRUE);
relativemouse = true;
}
else
{
SDL_SetWindowGrab(screen, SDL_FALSE);
canrelativemouse = false;
relativemouse = false;
}
}
}
else
{
SDL_ShowCursor(SDL_TRUE);
if (relativemouse)
{
SDL_SetWindowGrab(screen, SDL_FALSE);
SDL_SetRelativeMouseMode(SDL_FALSE);
relativemouse = false;
}
}
shouldgrab = delay;
#ifdef SDL_VIDEO_DRIVER_X11
if ((relativemouse || wasrelativemouse) && sdl_xgrab_bug)
{
// Workaround for buggy SDL X11 pointer grabbing
union {
SDL_SysWMinfo info;
uchar buf[sizeof(SDL_SysWMinfo) + 128];
};
SDL_GetVersion(&info.version);
if (SDL_GetWindowWMInfo(screen, &info) && info.subsystem == SDL_SYSWM_X11)
{
if (relativemouse)
{
uint mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask;
XGrabPointer(info.info.x11.display, info.info.x11.window, True, mask, GrabModeAsync, GrabModeAsync,
info.info.x11.window, None, CurrentTime);
}
else
XUngrabPointer(info.info.x11.display, CurrentTime);
}
}
#endif
}
bool initwindowpos = false;
void setfullscreen(bool enable)
{
if (!screen)
return;
// initwarning(enable ? "fullscreen" : "windowed");
extern int fullscreendesktop;
SDL_SetWindowFullscreen(screen,
enable ? (fullscreendesktop ? SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_FULLSCREEN) : 0);
if (!enable)
{
SDL_SetWindowSize(screen, scr_w, scr_h);
if (initwindowpos)
{
int winx = SDL_WINDOWPOS_CENTERED, winy = SDL_WINDOWPOS_CENTERED;
SDL_SetWindowPosition(screen, winx, winy);
initwindowpos = false;
}
}
}
#ifdef _DEBUG
VARF(fullscreen, 0, 0, 1, setfullscreen(fullscreen != 0));
#else
VARF(fullscreen, 0, 1, 1, setfullscreen(fullscreen != 0));
#endif
void resetfullscreen()
{
setfullscreen(false);
setfullscreen(true);
}
VARF(fullscreendesktop, 0, 0, 1, if (fullscreen) resetfullscreen());
void screenres(int w, int h)
{
scr_w = clamp(w, SCR_MINW, SCR_MAXW);
scr_h = clamp(h, SCR_MINH, SCR_MAXH);
if (screen)
{
if (fullscreendesktop)
{
scr_w = min(scr_w, desktopw);
scr_h = min(scr_h, desktoph);
}
if (SDL_GetWindowFlags(screen) & SDL_WINDOW_FULLSCREEN)
{
if (fullscreendesktop)
gl_resize();
else
resetfullscreen();
initwindowpos = true;
}
else
{
SDL_SetWindowSize(screen, scr_w, scr_h);
SDL_SetWindowPosition(screen, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
initwindowpos = false;
}
}
else
{
initwarning("screen resolution");
}
}
ICOMMAND(screenres, "ii", (int *w, int *h), screenres(*w, *h));
static void setgamma(int val)
{
if (screen && SDL_SetWindowBrightness(screen, val / 100.0f) < 0)
conoutf(CON_ERROR, "Could not set gamma: %s", SDL_GetError());
}
static int curgamma = 100;
VARFNP(gamma, reqgamma, 30, 100, 300, {
if (initing || reqgamma == curgamma)
return;
curgamma = reqgamma;
setgamma(curgamma);
});
void restoregamma()
{
if (initing || reqgamma == 100)
return;
curgamma = reqgamma;
setgamma(curgamma);
}
void cleargamma()
{
if (curgamma != 100 && screen)
SDL_SetWindowBrightness(screen, 1.0f);
}
int curvsync = -1;
void restorevsync()
{
if (initing || !glcontext)
return;
extern int vsync, vsynctear;
if (!SDL_GL_SetSwapInterval(vsync ? (vsynctear ? -1 : 1) : 0))
curvsync = vsync;
}
VARFP(vsync, 0, 0, 1, restorevsync());
VARFP(vsynctear, 0, 0, 1, {
if (vsync)
restorevsync();
});
void setupscreen()
{
if (glcontext)
{
SDL_GL_DeleteContext(glcontext);
glcontext = NULL;
}
if (screen)
{
SDL_DestroyWindow(screen);
screen = NULL;
}
curvsync = -1;
SDL_Rect desktop;
if (SDL_GetDisplayBounds(0, &desktop) < 0)
fatal("failed querying desktop bounds: %s", SDL_GetError());
desktopw = desktop.w;
desktoph = desktop.h;
if (scr_h < 0)
scr_h = fullscreen ? desktoph : SCR_DEFAULTH;
if (scr_w < 0)
scr_w = (scr_h * desktopw) / desktoph;
scr_w = clamp(scr_w, SCR_MINW, SCR_MAXW);
scr_h = clamp(scr_h, SCR_MINH, SCR_MAXH);
if (fullscreendesktop)
{
scr_w = min(scr_w, desktopw);
scr_h = min(scr_h, desktoph);
}
int winx = SDL_WINDOWPOS_UNDEFINED, winy = SDL_WINDOWPOS_UNDEFINED, winw = scr_w, winh = scr_h,
flags = SDL_WINDOW_RESIZABLE;
if (fullscreen)
{
if (fullscreendesktop)
{
winw = desktopw;
winh = desktoph;
flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
}
else
flags |= SDL_WINDOW_FULLSCREEN;
initwindowpos = true;
}
SDL_GL_ResetAttributes();
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
#if !defined(WIN32) && !defined(__APPLE__)
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
#endif
static const int configs[] = {
0x3, /* try everything */
0x2, 0x1, /* try disabling one at a time */
0 /* try disabling everything */
};
int config = 0;
if (!depthbits)
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
if (!fsaa)
{
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
}
loopi(sizeof(configs) / sizeof(configs[0]))
{
config = configs[i];
if (!depthbits && config & 1)
continue;
if (fsaa <= 0 && config & 2)
continue;
if (depthbits)
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, config & 1 ? depthbits : 24);
if (fsaa > 0)
{
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, config & 2 ? 1 : 0);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, config & 2 ? fsaa : 0);
}
screen = SDL_CreateWindow("BubeEngine", winx, winy, winw, winh,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_INPUT_FOCUS |
SDL_WINDOW_MOUSE_FOCUS | flags);
if (!screen)
continue;
#ifdef __APPLE__
static const int glversions[] = {32, 20};
#else
static const int glversions[] = {33, 32, 31, 30, 20};
#endif
loopj(sizeof(glversions) / sizeof(glversions[0]))
{
glcompat = glversions[j] <= 30 ? 1 : 0;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, glversions[j] / 10);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, glversions[j] % 10);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, glversions[j] >= 32 ? SDL_GL_CONTEXT_PROFILE_CORE : 0);
glcontext = SDL_GL_CreateContext(screen);
if (glcontext)
break;
}
if (glcontext)
break;
}
if (!screen)
fatal("failed to create OpenGL window: %s", SDL_GetError());
else if (!glcontext)
fatal("failed to create OpenGL context: %s", SDL_GetError());
else
{
if (depthbits && (config & 1) == 0)
conoutf(CON_WARN, "%d bit z-buffer not supported - disabling", depthbits);
if (fsaa > 0 && (config & 2) == 0)
conoutf(CON_WARN, "%dx anti-aliasing not supported - disabling", fsaa);
}
SDL_SetWindowMinimumSize(screen, SCR_MINW, SCR_MINH);
SDL_SetWindowMaximumSize(screen, SCR_MAXW, SCR_MAXH);
SDL_GetWindowSize(screen, &screenw, &screenh);
}
void resetgl()
{
clearchanges(CHANGE_GFX);
renderbackground("resetting OpenGL");
extern void cleanupva();
extern void cleanupparticles();
extern void cleanupdecals();
extern void cleanupblobs();
extern void cleanupsky();
extern void cleanupmodels();
extern void cleanupprefabs();
extern void cleanuplightmaps();
extern void cleanupblendmap();
extern void cleanshadowmap();
extern void cleanreflections();
extern void cleanupglare();
extern void cleanupdepthfx();
recorder::cleanup();
cleanupva();
cleanupparticles();
cleanupdecals();
cleanupblobs();
cleanupsky();
cleanupmodels();
cleanupprefabs();
cleanuptextures();
cleanuplightmaps();
cleanupblendmap();
cleanshadowmap();
cleanreflections();
cleanupglare();
cleanupdepthfx();
cleanupshaders();
cleanupgl();
setupscreen();
inputgrab(grabinput);
gl_init();
inbetweenframes = false;
if (!reloadtexture(*notexture) || !reloadtexture("data/logo.png") || !reloadtexture("data/logo_1024.png") ||
!reloadtexture("data/background.png") || !reloadtexture("data/background_detail.png") ||
!reloadtexture("data/background_decal.png") || !reloadtexture("data/mapshot_frame.png") ||
!reloadtexture("data/loading_frame.png") || !reloadtexture("data/loading_bar.png"))
fatal("failed to reload core texture");
reloadfonts();
inbetweenframes = true;
renderbackground("initializing...");
restoregamma();
restorevsync();
reloadshaders();
reloadtextures();
initlights();
allchanged(true);
}
COMMAND(resetgl, "");
static queue<SDL_Event, 32> events;
static inline bool filterevent(const SDL_Event &event)
{
switch (event.type)
{
case SDL_MOUSEMOTION:
if (grabinput && !relativemouse && !(SDL_GetWindowFlags(screen) & SDL_WINDOW_FULLSCREEN))
{
if (event.motion.x == screenw / 2 && event.motion.y == screenh / 2)
return false; // ignore any motion events generated by SDL_WarpMouse
#ifdef __APPLE__
if (event.motion.y == 0)
return false; // let mac users drag windows via the title bar
#endif
}
break;
}
return true;
}
template <int SIZE> static inline bool pumpevents(queue<SDL_Event, SIZE> &events)
{
while (events.empty())
{
SDL_PumpEvents();
databuf<SDL_Event> buf = events.reserve(events.capacity());
int n = SDL_PeepEvents(buf.getbuf(), buf.remaining(), SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT);
if (n <= 0)
return false;
loopi(n) if (filterevent(buf.buf[i])) buf.put(buf.buf[i]);
events.addbuf(buf);
}
return true;
}
static int interceptkeysym = 0;
static int interceptevents(void *data, SDL_Event *event)
{
switch (event->type)
{
case SDL_MOUSEMOTION:
return 0;
case SDL_KEYDOWN:
if (event->key.keysym.sym == interceptkeysym)
{
interceptkeysym = -interceptkeysym;
return 0;
}
break;
}
return 1;
}
static void clearinterceptkey()
{
SDL_DelEventWatch(interceptevents, NULL);
interceptkeysym = 0;
}
bool interceptkey(int sym)
{
if (!interceptkeysym)
{
interceptkeysym = sym;
SDL_FilterEvents(interceptevents, NULL);
if (interceptkeysym < 0)
{
interceptkeysym = 0;
return true;
}
SDL_AddEventWatch(interceptevents, NULL);
}
else if (abs(interceptkeysym) != sym)
interceptkeysym = sym;
SDL_PumpEvents();
if (interceptkeysym < 0)
{
clearinterceptkey();
interceptkeysym = sym;
SDL_FilterEvents(interceptevents, NULL);
interceptkeysym = 0;
return true;
}
return false;
}
static void ignoremousemotion()
{
SDL_PumpEvents();
SDL_FlushEvent(SDL_MOUSEMOTION);
}
static void resetmousemotion()
{
if (grabinput && !relativemouse && !(SDL_GetWindowFlags(screen) & SDL_WINDOW_FULLSCREEN))
{
SDL_WarpMouseInWindow(screen, screenw / 2, screenh / 2);
}
}
static void checkmousemotion(int &dx, int &dy)
{
while (pumpevents(events))
{
SDL_Event &event = events.removing();
if (event.type != SDL_MOUSEMOTION)
return;
dx += event.motion.xrel;
dy += event.motion.yrel;
events.remove();
}
}
void checkinput()
{
if (interceptkeysym)
clearinterceptkey();
// int lasttype = 0, lastbut = 0;
bool mousemoved = false;
int focused = 0;
while (pumpevents(events))
{
SDL_Event &event = events.remove();
if (focused && event.type != SDL_WINDOWEVENT)
{
if (grabinput != (focused > 0))
inputgrab(grabinput = focused > 0, shouldgrab);
focused = 0;
}
switch (event.type)
{
case SDL_QUIT:
quit();
return;
case SDL_TEXTINPUT:
if (textinputmask && int(event.text.timestamp - textinputtime) >= textinputfilter)
{
uchar buf[SDL_TEXTINPUTEVENT_TEXT_SIZE + 1];
size_t len =
decodeutf8(buf, sizeof(buf) - 1, (const uchar *)event.text.text, strlen(event.text.text));
if (len > 0)
{
buf[len] = '\0';
processtextinput((const char *)buf, len);
}
}
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
if (keyrepeatmask || !event.key.repeat)
processkey(event.key.keysym.sym, event.key.state == SDL_PRESSED,
event.key.keysym.mod | SDL_GetModState());
break;
case SDL_WINDOWEVENT:
switch (event.window.event)
{
case SDL_WINDOWEVENT_CLOSE:
quit();
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
shouldgrab = true;
break;
case SDL_WINDOWEVENT_ENTER:
shouldgrab = false;
focused = 1;
break;
case SDL_WINDOWEVENT_LEAVE:
case SDL_WINDOWEVENT_FOCUS_LOST:
shouldgrab = false;
focused = -1;
break;
case SDL_WINDOWEVENT_MINIMIZED:
minimized = true;
break;
case SDL_WINDOWEVENT_MAXIMIZED:
case SDL_WINDOWEVENT_RESTORED:
minimized = false;
break;
case SDL_WINDOWEVENT_RESIZED:
break;
case SDL_WINDOWEVENT_SIZE_CHANGED: {
SDL_GetWindowSize(screen, &screenw, &screenh);
if (!fullscreendesktop || !(SDL_GetWindowFlags(screen) & SDL_WINDOW_FULLSCREEN))
{
scr_w = clamp(screenw, SCR_MINW, SCR_MAXW);
scr_h = clamp(screenh, SCR_MINH, SCR_MAXH);
}
gl_resize();
break;
}
}
break;
case SDL_MOUSEMOTION:
if (grabinput)
{
int dx = event.motion.xrel, dy = event.motion.yrel;
checkmousemotion(dx, dy);
if (!g3d_movecursor(dx, dy))
mousemove(dx, dy);
mousemoved = true;
}
else if (shouldgrab)
inputgrab(grabinput = true);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
// if(lasttype==event.type && lastbut==event.button.button) break; // why?? get event twice without it
switch (event.button.button)
{
case SDL_BUTTON_LEFT:
processkey(-1, event.button.state == SDL_PRESSED);
break;
case SDL_BUTTON_MIDDLE:
processkey(-2, event.button.state == SDL_PRESSED);
break;
case SDL_BUTTON_RIGHT:
processkey(-3, event.button.state == SDL_PRESSED);
break;
case SDL_BUTTON_X1:
processkey(-6, event.button.state == SDL_PRESSED);
break;
case SDL_BUTTON_X2:
processkey(-7, event.button.state == SDL_PRESSED);
break;
}
// lasttype = event.type;
// lastbut = event.button.button;
break;
case SDL_MOUSEWHEEL:
if (event.wheel.y > 0)
{
processkey(-4, true);
processkey(-4, false);
}
else if (event.wheel.y < 0)
{
processkey(-5, true);
processkey(-5, false);
}
break;
}
}
if (focused)
{
if (grabinput != (focused > 0))
inputgrab(grabinput = focused > 0, shouldgrab);
focused = 0;
}
if (mousemoved)
resetmousemotion();
}
void swapbuffers(bool overlay)
{
recorder::capture(overlay);
gle::disable();
SDL_GL_SwapWindow(screen);
}
VAR(menufps, 0, 60, 1000);
VARP(maxfps, 0, 200, 1000);
void limitfps(int &millis, int curmillis)
{
int limit = (mainmenu || minimized) && menufps ? (maxfps ? min(maxfps, menufps) : menufps) : maxfps;
if (!limit)
return;
static int fpserror = 0;
int delay = 1000 / limit - (millis - curmillis);
if (delay < 0)
fpserror = 0;
else
{
fpserror += 1000 % limit;
if (fpserror >= limit)
{
++delay;
fpserror -= limit;
}
if (delay > 0)
{
SDL_Delay(delay);
millis += delay;
}
}
}
#if defined(WIN32) && !defined(_DEBUG) && !defined(__GNUC__)
void stackdumper(unsigned int type, EXCEPTION_POINTERS *ep)
{
if (!ep)
fatal("unknown type");
EXCEPTION_RECORD *er = ep->ExceptionRecord;
CONTEXT *context = ep->ContextRecord;
char out[512];
formatstring(out, "BubeEngine Win32 Exception: 0x%x [0x%x]\n\n", er->ExceptionCode,
er->ExceptionCode == EXCEPTION_ACCESS_VIOLATION ? er->ExceptionInformation[1] : -1);
SymInitialize(GetCurrentProcess(), NULL, TRUE);
#ifdef _AMD64_
STACKFRAME64 sf = {
{context->Rip, 0, AddrModeFlat}, {}, {context->Rbp, 0, AddrModeFlat}, {context->Rsp, 0, AddrModeFlat}, 0};
while (::StackWalk64(IMAGE_FILE_MACHINE_AMD64, GetCurrentProcess(), GetCurrentThread(), &sf, context, NULL,
::SymFunctionTableAccess, ::SymGetModuleBase, NULL))
{
union {
IMAGEHLP_SYMBOL64 sym;
char symext[sizeof(IMAGEHLP_SYMBOL64) + sizeof(string)];
};
sym.SizeOfStruct = sizeof(sym);
sym.MaxNameLength = sizeof(symext) - sizeof(sym);
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(line);
DWORD64 symoff;
DWORD lineoff;
if (SymGetSymFromAddr64(GetCurrentProcess(), sf.AddrPC.Offset, &symoff, &sym) &&
SymGetLineFromAddr64(GetCurrentProcess(), sf.AddrPC.Offset, &lineoff, &line))
#else
STACKFRAME sf = {
{context->Eip, 0, AddrModeFlat}, {}, {context->Ebp, 0, AddrModeFlat}, {context->Esp, 0, AddrModeFlat}, 0};
while (::StackWalk(IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), GetCurrentThread(), &sf, context, NULL,
::SymFunctionTableAccess, ::SymGetModuleBase, NULL))
{
union {
IMAGEHLP_SYMBOL sym;
char symext[sizeof(IMAGEHLP_SYMBOL) + sizeof(string)];
};
sym.SizeOfStruct = sizeof(sym);
sym.MaxNameLength = sizeof(symext) - sizeof(sym);
IMAGEHLP_LINE line;
line.SizeOfStruct = sizeof(line);
DWORD symoff, lineoff;
if (SymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset, &symoff, &sym) &&
SymGetLineFromAddr(GetCurrentProcess(), sf.AddrPC.Offset, &lineoff, &line))
#endif
{
char *del = strrchr(line.FileName, '\\');
concformatstring(out, "%s - %s [%d]\n", sym.Name, del ? del + 1 : line.FileName, line.LineNumber);
}
}
fatal(out);
}
#endif
#define MAXFPSHISTORY 60
int fpspos = 0, fpshistory[MAXFPSHISTORY];
void resetfpshistory()
{
loopi(MAXFPSHISTORY) fpshistory[i] = 1;
fpspos = 0;
}
void updatefpshistory(int millis)
{
fpshistory[fpspos++] = max(1, min(1000, millis));
if (fpspos >= MAXFPSHISTORY)
fpspos = 0;
}
void getfps(int &fps, int &bestdiff, int &worstdiff)
{
int total = fpshistory[MAXFPSHISTORY - 1], best = total, worst = total;
loopi(MAXFPSHISTORY - 1)
{
int millis = fpshistory[i];
total += millis;
if (millis < best)
best = millis;
if (millis > worst)
worst = millis;
}
fps = (1000 * MAXFPSHISTORY) / total;
bestdiff = 1000 / best - fps;
worstdiff = fps - 1000 / worst;
}
void getfps_(int *raw)
{
int fps, bestdiff, worstdiff;
if (*raw)
fps = 1000 / fpshistory[(fpspos + MAXFPSHISTORY - 1) % MAXFPSHISTORY];
else
getfps(fps, bestdiff, worstdiff);
intret(fps);
}
COMMANDN(getfps, getfps_, "i");
bool inbetweenframes = false, renderedframe = true;
static bool findarg(int argc, char **argv, const char *str)
{
for (int i = 1; i < argc; i++)
if (strstr(argv[i], str) == argv[i])
return true;
return false;
}
static int clockrealbase = 0, clockvirtbase = 0;
static void clockreset()
{
clockrealbase = SDL_GetTicks();
clockvirtbase = totalmillis;
}
VARFP(clockerror, 990000, 1000000, 1010000, clockreset());
VARFP(clockfix, 0, 0, 1, clockreset());
int getclockmillis()
{
int millis = SDL_GetTicks() - clockrealbase;
if (clockfix)
millis = int(millis * (double(clockerror) / 1000000));
millis += clockvirtbase;
return max(millis, totalmillis);
}
VAR(numcpus, 1, 1, 16);
int main(int argc, char **argv)
{
#ifdef WIN32
// atexit((void (__cdecl *)(void))_CrtDumpMemoryLeaks);
#ifndef _DEBUG
#ifndef __GNUC__
__try
{
#endif
#endif
#endif
setlogfile(NULL);
int dedicated = 0;
char *load = NULL, *initscript = NULL;
initing = INIT_RESET;
// set home dir first
for (int i = 1; i < argc; i++)
if (argv[i][0] == '-' && argv[i][1] == 'q')
{
sethomedir(&argv[i][2]);
break;
}
// set log after home dir, but before anything else
for (int i = 1; i < argc; i++)
if (argv[i][0] == '-' && argv[i][1] == 'g')
{
const char *file = argv[i][2] ? &argv[i][2] : "log.txt";
setlogfile(file);
logoutf("Setting log file: %s", file);
break;
}
execfile("init.cfg", false);
for (int i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
switch (argv[i][1])
{
case 'q':
if (homedir[0])
logoutf("Using home directory: %s", homedir);
break;
case 'r': /* compat, ignore */
break;
case 'k': {
const char *dir = addpackagedir(&argv[i][2]);
if (dir)
logoutf("Adding package directory: %s", dir);
break;
}
case 'g':
break;
case 'd':
dedicated = atoi(&argv[i][2]);
if (dedicated <= 0)
dedicated = 2;
break;
case 'w':
scr_w = clamp(atoi(&argv[i][2]), SCR_MINW, SCR_MAXW);
if (!findarg(argc, argv, "-h"))
scr_h = -1;
break;
case 'h':
scr_h = clamp(atoi(&argv[i][2]), SCR_MINH, SCR_MAXH);
if (!findarg(argc, argv, "-w"))
scr_w = -1;
break;
case 'z':
depthbits = atoi(&argv[i][2]);
break;
case 'b': /* compat, ignore */
break;
case 'a':
fsaa = atoi(&argv[i][2]);
break;
case 'v': /* compat, ignore */
break;
case 't':
fullscreen = atoi(&argv[i][2]);
break;
case 's': /* compat, ignore */
break;
case 'f': /* compat, ignore */
break;
case 'l': {
char pkgdir[] = "packages/";
load = strstr(path(&argv[i][2]), path(pkgdir));
if (load)
load += sizeof(pkgdir) - 1;
else
load = &argv[i][2];
break;
}
case 'x':
initscript = &argv[i][2];
break;
default:
if (!serveroption(argv[i]))
gameargs.add(argv[i]);
break;
}
else
gameargs.add(argv[i]);
}
initing = NOT_INITING;
numcpus = clamp(SDL_GetCPUCount(), 1, 16);
if (dedicated <= 1)
{
logoutf("init: sdl");
if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0)
fatal("Unable to initialize SDL: %s", SDL_GetError());
#ifdef SDL_VIDEO_DRIVER_X11
SDL_version version;
SDL_GetVersion(&version);
if (SDL_VERSIONNUM(version.major, version.minor, version.patch) <= SDL_VERSIONNUM(2, 0, 12))
sdl_xgrab_bug = 1;
#endif
}
logoutf("init: net");
if (enet_initialize() < 0)
fatal("Unable to initialise network module");
atexit(enet_deinitialize);
enet_time_set(0);
logoutf("init: game");
game::parseoptions(gameargs);
initserver(dedicated > 0, dedicated > 1); // never returns if dedicated
ASSERT(dedicated <= 1);
game::initclient();
logoutf("init: video");
SDL_SetHint(SDL_HINT_GRAB_KEYBOARD, "0");
#if !defined(WIN32) && !defined(__APPLE__)
SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
#endif
setupscreen();
SDL_ShowCursor(SDL_FALSE);
SDL_StopTextInput(); // workaround for spurious text-input events getting sent on first text input toggle?
logoutf("init: gl");
gl_checkextensions();
gl_init();
notexture = textureload("packages/textures/notexture.png");
// if(!notexture) fatal("could not find core textures");
if (!notexture)
{
notexture = texturemissing();
conoutf(CON_WARN, "could not load missing texture, generated instead.");
}
logoutf("init: freetype");
if (!init_fonts())
fatal("cannot init freetype");
logoutf("init: console");
if (!execfile("data/stdlib.cfg", false))
fatal("cannot find data files"); // this is the first file we load.
if (!execfile("data/font.cfg", false))
fatal("cannot find font definitions");
if (!setfont("default"))
fatal("no default font specified");
logoutf("init: angelscript");
if (!initscriptengine())
fatal("cannot initialize scripting");
atexit(destructscriptengine);
inbetweenframes = true;
renderbackground("initializing...");
logoutf("init: world");
camera1 = player = game::iterdynents(0);
emptymap(0, true, NULL, false);
logoutf("init: sound");
initsound();
logoutf("init: cfg");
initing = INIT_LOAD;
execfile("data/keymap.cfg");
execfile("data/stdedit.cfg");
execfile("data/sounds.cfg");
execfile("data/menus.cfg");
execfile("data/heightmap.cfg");
execfile("data/blendbrush.cfg");
defformatstring(gamecfgname, "data/game_%s.cfg", game::gameident());
execfile(gamecfgname);
if (game::savedservers())
execfile(game::savedservers(), false);
identflags |= IDF_PERSIST;
if (!execfile(game::savedconfig(), false))
{
execfile(game::defaultconfig());
writecfg(game::restoreconfig());
}
execfile(game::autoexec(), false);
identflags &= ~IDF_PERSIST;
initing = INIT_GAME;
game::loadconfigs();
initing = NOT_INITING;
logoutf("init: render");
restoregamma();
restorevsync();
loadshaders();
initparticles();
initdecals();
identflags |= IDF_PERSIST;
logoutf("init: mainloop");
if (execfile("once.cfg", false))
remove(findfile("once.cfg", "rb"));
if (load)
{
logoutf("init: localconnect");
// localconnect();
game::changemap(load);
}
if (initscript)
execute(initscript);
initmumble();
resetfpshistory();
inputgrab(grabinput = true);
ignoremousemotion();
for (;;)
{
static int frames = 0;
int millis = getclockmillis();
limitfps(millis, totalmillis);
elapsedtime = millis - totalmillis;
static int timeerr = 0;
int scaledtime = game::scaletime(elapsedtime) + timeerr;
curtime = scaledtime / 100;
timeerr = scaledtime % 100;
if (!multiplayer(false) && curtime > 200)
curtime = 200;
if (game::ispaused())
curtime = 0;
lastmillis += curtime;
totalmillis = millis;
updatetime();
checkinput();
menuprocess();
tryedit();
if (lastmillis)
game::updateworld();
checksleep(lastmillis);
serverslice(false, 0);
if (frames)
updatefpshistory(elapsedtime);
frames++;
// miscellaneous general game effects
recomputecamera();
updateparticles();
updatesounds();
if (minimized)
continue;
inbetweenframes = false;
if (mainmenu)
gl_drawmainmenu();
else
gl_drawframe();
swapbuffers();
renderedframe = inbetweenframes = true;
}
ASSERT(0);
return EXIT_FAILURE;
#if defined(WIN32) && !defined(_DEBUG) && !defined(__GNUC__)
}
__except (stackdumper(0, GetExceptionInformation()), EXCEPTION_CONTINUE_SEARCH)
{
return 0;
}
#endif
}
|
5655594d7c110059ec676de93c69aa93cdbed418 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5695413893988352_0/C++/trunghai95/close_match.cpp | 3aa6361c40a2dce8fde4b72a739208bc17b1258f | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 909 | cpp | close_match.cpp | //brute-force 1000^2
#include <bits/stdc++.h>
using namespace std;
int test;
char C[20], J[20], len;
bool valid(int c, int j)
{
for (int i = len - 1; i >= 0; --i)
{
if (C[i] != '?' && C[i] - '0' != (c % 10))
return false;
if (J[i] != '?' && J[i] - '0' != (j % 10))
return false;
j /= 10;
c /= 10;
}
return true;
}
int main()
{
ios_base::sync_with_stdio(0);
cin >> test;
for (int tt = 1; tt <= test; ++tt)
{
cin >> C >> J;
len = strlen(C);
int mx = 1;
for (int i = 0; i < len; ++i)
mx *= 10;
mx -= 1;
int res = 1e9, resc = 0, resj = 0;
for (int c = 0; c <= mx; ++c)
for (int j = 0; j <= mx; ++j)
if (valid(c, j) && abs(c-j) < res)
{
res = abs(c-j);
resc = c, resj = j;
}
cout << "Case #" << tt << ": ";
cout << setfill('0') << setw(len) << resc << ' ' << setw(len) << resj << '\n';
}
return 0;
} |
5e850b3436bbb5c6cb0034b9a54bfeb0483206c5 | ffbf1cbd20eb7939e125fedf892810e86e21bc20 | /Controle_acc_s.lnk.ino | b12285662a0f0e06f8b8549e248bc6af1c104e1c | [] | no_license | bosstkd/arduino-AccessControlSystem | ea967b2c3c0fecf56e7af5007789c693e0689d7e | aaae174bb1ecf2ac0169aecb219451bd52b29bc4 | refs/heads/master | 2020-12-04T14:02:56.072962 | 2020-01-04T16:32:06 | 2020-01-04T16:32:06 | 231,793,780 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,839 | ino | Controle_acc_s.lnk.ino | #include <SoftwareSerial.h>
#include <SPI.h>
#include <MFRC522.h>
#include <EEPROM.h>
#define SSerialRX 0 //Serial Receive pin
#define SSerialTX 1 //Serial Transmit pin
#define SSerialTxControl 2 //RS485 Direction control
#define RS485Transmit HIGH
#define RS485Receive LOW
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);
/*-----( Declare objects )-----*/
SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
String str = "";
int openToSend = 2;
int gache = 5;
int ledAccept = 6;
int ledErreur = 7;
int lunchProg = 8;
int tTab = 130;
String userTab[130];
int index = 0;
void setup() {
pinMode(lunchProg, INPUT);
pinMode(ledAccept, OUTPUT);
pinMode(gache , OUTPUT);
pinMode(ledErreur, OUTPUT);
// Serial.begin(9600);
// Start the software serial port, to another device
RS485Serial.begin(115200); // set the data rate
pinMode(SSerialTxControl, OUTPUT);
digitalWrite(SSerialTxControl, RS485Receive); // Init Transceiver
SPI.begin();
mfrc522.PCD_Init();
int i = 0;
for(i = 0; i < tTab; i++){
userTab[i]="";
}
}
void loop() {
if(digitalRead(lunchProg) == 1){
digitalWrite(ledAccept, HIGH);
digitalWrite(ledErreur, LOW);
delay(200);
digitalWrite(ledAccept, LOW);
digitalWrite(ledErreur, HIGH);
delay(200);
if (RS485Serial.available() > 0) {
String mot = RS485Serial.readString();
prog(mot);
}
}else{
if (RS485Serial.available() > 0) {
// digitalWrite(SSerialTxControl, RS485Receive);
String mot = RS485Serial.readString();
String adrr= readEepromStr(0,2);
// ---------------- identification de porte par ADRR-------------//
if(mot.substring(0,3).equals(adrr)){
// ---------------- (Acceptation / refus) d'accès ----------
//String id = mot.substring(3, 11);
//String action = mot.substring(11, mot.length());
if(mot.substring(11, mot.length()).equals("ouvre")){
// **************** Accés accepter ************
openDoor();
if(!mot.substring(3, 11).equals("________")){
saveIdentifier(mot.substring(3, 11));
}
}else if(mot.substring(3, 11).equals("programe")){
prog(mot.substring(11, mot.length()));
}else if(mot.substring(3, 11).equals("supprime")){
// procedure de suppression des droits d'accès.
supp(mot.substring(11, mot.length()));
}else{
// **************** Accés refuser ************
int i = 0;
if(isIdExist(mot.substring(11, mot.length()))){
supp(mot.substring(11, mot.length()));
}
for(i = 0; i < 2; i++ ){
digitalWrite(ledErreur, HIGH); delay(400);
digitalWrite(ledErreur, LOW);
if(i < 1){
delay(300);
}
}
}
}
}else{
digitalWrite(ledAccept, LOW);
digitalWrite(ledErreur, LOW);
}
}
//------lecture sauf si une nouvelle carte RFID est présente sinon retour----------------------------------//
if(! mfrc522.PICC_IsNewCardPresent()){
return;
}
//-----Si pas de carte alors retour sinon lecture est envoi de code vers sur Serial port-------------------//
if(! mfrc522.PICC_ReadCardSerial()){
return;
}
//------lecture contenu complet de la carte et transfere vers le serial port mfrc522.PICC_DumpToSerial(&(mfrc522.uid));-----
str = "";
// Serial.println("Code de carte : ");
for(byte i = 0; i < mfrc522.uid.size; i++){
str = str + String(mfrc522.uid.uidByte[i], HEX);
}
str.toUpperCase();
if(isIdExist(str)){
// ------- Demande de sauvegarde du temps c tout ----------
str = readEepromStr(0,2)+str+"T";
openDoor();
}else{
// ------- Demande de confirmation + sauvegarde si ok -----
str = readEepromStr(0,2)+str+"C";
digitalWrite(ledErreur, HIGH);
}
digitalWrite(SSerialTxControl, RS485Transmit); // Enable RS485 Transmit
RS485Serial.print(str);
digitalWrite(SSerialTxControl, RS485Receive);
digitalWrite(ledAccept, HIGH);
delay(200);
digitalWrite(ledAccept, LOW);
digitalWrite(ledErreur, LOW);
}
//------------------- ecriture du str dans la position x de l'eeprom----------------------------
void StrToEeprom(String str, int x){
int str_len = str.length();
int i = x;
int j = 0;
char c = "";
int s = 0;
for( i = x; i < x + str_len; i++){
c = str.charAt(j);
j++;
s = c;
EEPROM.write(i, s);
}
}
// ----------------- Lecture depuis l'eeprom de la position x jusqu'a la position y-------------
String readEepromStr(int x, int y){
String str = "";
int i = 0;
char c = "";
for(i = x; i<=y; i++){
c = char(EEPROM.read(i));
str = String(str + c);
}
return str;
}
//------------------ Existing identifier--------------------------------------------------------
boolean isIdExist(String id){
boolean ok = false;
int i = 0;
for(i = 0; i < tTab; i++){
if(userTab[i].equals(id)){
ok = true;
break;
}
}
return ok;
}
//------------------- save identifier-----------------------------------------------------------
void saveIdentifier(String id){
boolean ok = false;
if(index < 0 || index >=tTab) {
int cherche = 0;
for(cherche = 0; cherche < tTab; cherche++){
if(userTab[cherche].equals("_")){
ok = true;
userTab[cherche] = id;
cherche = tTab;
break;
}
}
if(!ok){
index = 0;
}
}else{
index++;
}
if(!ok){
userTab[index] = id;
}
}
//------------------ Programmation ADRR---------------------------------------------------------
void prog(String adrr){
StrToEeprom(adrr, 0);
int i = 0;
digitalWrite(ledErreur, HIGH);
for(i = 3; i < EEPROM.length(); i++){
EEPROM.write(i,255);
}
for(i = 0; i<8; i++){
digitalWrite(ledAccept, HIGH); delay(100);
digitalWrite(ledAccept, LOW); delay(100);
}
}
//------------------ Suppression IDs ---------------------------------------------------------
void supp(String ids){
int i = 0;
int j = 0;
for(j = 0; j < ids.length(); j=j+8){
String id = ids.substring(j, j+8);
for(i = 0; i < tTab ; i++){
if(userTab[i].equals(id)){
userTab[i]="_";
}
}
}
}
//------------------ ouvrire la porte-----------------------------------------------------------
void openDoor(){
digitalWrite(gache, HIGH);
int i = 0;
for(i = 0; i < 3; i++ ){
digitalWrite(ledAccept, HIGH); delay(500);
digitalWrite(ledAccept, LOW);
if(i < 2)delay(300);
}
digitalWrite(gache, LOW);
}
|
0225b03340418a816e238ea93e0e62543514e56c | 7514c339481aba7c175b3517d8eb16fce693059b | /CPP/PrimalityTesting/utils/InputGenerator.cpp | 79185deed9803e26d9d7d36ef9ee1f32b533c903 | [] | no_license | AlinGeorgescu/Problem-Solving | 4ec4f4d52e659cf9da4ce43db256ec8f434291f4 | 8a9d715703a1eec6d7a8d2e0faa9bf78f6b053de | refs/heads/master | 2022-08-15T11:04:36.657000 | 2022-07-24T19:29:24 | 2022-07-24T19:29:24 | 165,862,493 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | cpp | InputGenerator.cpp | /**
* Copyright 2018 Alin-Andrei Georgescu (alinandrei2007@yahoo.com)
* Grupa: 325 CA
* Tema AA - Identificarea Numerelor Prime
*/
#include <iostream>
#include <set>
#include <random>
#include <limits>
#define NUM 1000000 // Numarul de numere de generat.
using std::set;
using std::random_device;
using std::mt19937;
using std::uniform_int_distribution;
using std::numeric_limits;
using std::cout;
// Genereaza NUM numere prime distincte si intregi (reprezentare pe 32 biti).
int main() {
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int>
dist(1, numeric_limits<int>::max());
set<int> numbers;
while(numbers.size() < NUM) {
numbers.insert(dist(mt));
}
cout << NUM << "\n";
for (int i : numbers)
cout << i << " ";
return 0;
}
|
080cda0af8398ff4cd9eb6f06ea47a274c7f775d | 1ac04ddeae434c64fc10e2194a65c249d02129de | /src/cses.fi/dp/Two_Sets_II.cpp | 028c6a8f5a8f0db95de6600342c5414e66f3ff96 | [] | no_license | VIPUL1306/cp_practice | f68de30c9d0af343d77ceda1397d14f22077b5d9 | a439e8cdec79962be6a168cdd70bad848138d757 | refs/heads/master | 2023-09-03T01:49:54.492499 | 2020-10-01T05:03:22 | 2020-10-01T05:03:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,698 | cpp | Two_Sets_II.cpp | // https://cses.fi/problemset/task/1093
#include<bits/stdc++.h>
#define MOD 1000000007
#define ll long long int
using namespace std;
ll bottomup_solution(ll n){
ll sum = (n*(n+1))/2;
vector<ll> dp(125255,0);
dp[0] = 1;
for(int i = 1;i<=n;i++){
for(int j = sum/2;j>=i;j--){
dp[j] = (dp[j] + dp[j-i])%MOD;
}
}
return ((dp[sum/2])*500000004)%MOD;
}
// vector<vector<ll>> memo(501,vector<ll>(100000,-1));
// ll topdown_solution_1(ll n, ll index, ll sum){
// if(sum*2>(n*(n+1))/2)
// return 0;
// if(index == n){
// if(sum*2 == (n*(n+1))/2){
// return 1;
// }else{
// return 0;
// }
// }
// if(memo[index][sum]!=-1)
// return memo[index][sum];
// if(sum*2 == (n*(n+1))/2){
// return 1;
// }
// ll cnt = 0;
// for(int i = index+1;i<=n;i++){
// if((sum+i)*2<=((n*(n+1))/2))
// cnt = (cnt + topdown_solution_1(n,i,sum+i))%MOD;
// }
// memo[index][sum] = cnt;
// return cnt;
// }
// ll topdown_solution(ll n, ll index, ll sum){
// if(index==n){
// return ((2*sum)==(n*(n+1)/2));
// }
// if(memo[index][sum]!=-1)
// return memo[index][sum];
// ll cnt=0;
// cnt=(topdown_solution(n,index+1,sum)%MOD+(topdown_solution(n,index+1,sum+index))%MOD)%MOD;
// memo[index][sum] = cnt;
// return cnt;
// }
int main(){
// freopen("ouput.txt","w",stdout);
ll n;
cin>>n;
if((n*(n+1))%4!=0){
cout<<"0\n";
return 0;
}
cout<<bottomup_solution(n)<<"\n";
// memo.clear();
// memo.resize(501,vector<ll>(100000,-1));
// cout<<topdown_solution_1(n,1,1)<<"\n";
// memo.clear();
// memo.resize(501,vector<ll>(100000,-1));
// cout<<topdown_solution(n,01,01)%MOD<<"\n";
return 0;
}
|
fd4852c6ec181838bf90a3bb990356858184eadb | dcc3bdd903b6c5ed2f6d9f43ff2d196bf6b88f16 | /NuklearGl/Scene.h | f619195b5cc2b92e25431f3b84f3410bae00d228 | [
"LicenseRef-scancode-public-domain"
] | permissive | Chrisso/gl-studies | a9dacd369c44686f77cc75c87cd7ca2fb315c9ea | 916cd4851df09d1c959afe8cb4ec0985f881fb7e | refs/heads/master | 2021-06-25T11:17:56.626472 | 2020-10-23T15:47:50 | 2020-10-23T15:47:50 | 135,674,916 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,644 | h | Scene.h | #pragma once
#include <glm/glm.hpp>
#include <ShaderProgram.h>
class CScene
{
private:
nk_context m_nkContext;
nk_font_atlas m_nkFontAtlas;
nk_draw_null_texture m_nkNull;
nk_convert_config m_nkConvertConfig;
nk_buffer m_nkCommands;
CShaderProgram *m_pNuklearShader = nullptr;
glm::mat4 m_matNuklear;
glm::vec2 m_vecSize;
GLuint m_nFontTexture = 0;
GLuint m_nVertexArray = 0;
GLuint m_nVertexBuffer = 0;
GLuint m_nElementBuffer = 0;
public:
CScene();
~CScene();
bool Create();
void Render(float time);
void Resize(int width, int height);
void MouseMove(unsigned int flags, int x, int y)
{
nk_input_motion(&m_nkContext, x, y);
}
void MouseButton(unsigned int button, bool pressed, int x, int y)
{
nk_buttons btn = NK_BUTTON_LEFT;
switch (btn)
{
case MK_LBUTTON: btn = NK_BUTTON_LEFT; break;
case MK_RBUTTON: btn = NK_BUTTON_RIGHT; break;
case MK_MBUTTON: btn = NK_BUTTON_MIDDLE; break;
}
nk_input_button(&m_nkContext, btn, x, y, pressed ? 1 : 0);
}
void Char(char c, unsigned int flags)
{
if (c >= 32)
nk_input_char(&m_nkContext, c);
}
void Key(char key, unsigned int flags, bool pressed)
{
nk_keys keys = NK_KEY_NONE;
switch (key)
{
case VK_SHIFT: keys = NK_KEY_SHIFT; break;
case VK_DELETE: keys = NK_KEY_DEL; break;
case VK_BACK: keys = NK_KEY_BACKSPACE; break;
case VK_UP: keys = NK_KEY_UP; break;
case VK_DOWN: keys = NK_KEY_DOWN; break;
case VK_LEFT: keys = NK_KEY_LEFT; break;
case VK_RIGHT: keys = NK_KEY_RIGHT; break;
}
if (keys != NK_KEY_NONE)
nk_input_key(&m_nkContext, keys, pressed ? 1 : 0);
}
};
|
7d9ae8207bba96bdfb4a66b2c2ddde722105968d | 7df11251e9e52a68b14d65222a20934670fe5a9e | /Dissimilarity matrix construction/header.cpp | 1233e2b3690d1b0e3cdf1176aaf11d1c49eb25bd | [] | no_license | nunonene/Multi-scale-analysis-and-clustering-of-stress-induced-co-expression-networks | 9a56403c43d8cb4582c57d4039397498eeb294fb | 785889a0e53d899810392c33f489f9b1f69878d8 | refs/heads/master | 2021-01-19T12:19:14.196941 | 2017-12-01T23:49:54 | 2017-12-01T23:49:54 | 82,304,720 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | header.cpp |
/* ----------------------------------------------------------------------
C++ files provided with:
http://www.bioconductor.org/packages/release/bioc/html/BHC.html
------------------------------------------------------------------------- */
#include "header.h"
extern "C" {
#include <math.h>
#include "mex.h"
}
bool fast_switch=false;
|
27c84c17a7d2d5c83e7ac3323c6eb864c29c6536 | a8117918f26beb4613236366e77072fb33f14ede | /vision/algorithms.cpp | d27694680d858c535febb2398dec32db1c1c4f9f | [] | no_license | yash101/FRC-Eye-2015 | 071e646d45bc54b96cb0c6507e4643cb700986a2 | 3e446212c47999a012b6e0607f46f1e2e14ed21b | refs/heads/master | 2021-01-19T06:39:47.468692 | 2015-02-08T17:21:11 | 2015-02-08T17:21:11 | 29,171,882 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 56 | cpp | algorithms.cpp | #include "algorithms.hpp"
algorithms::algorithms()
{
}
|
adfde54295fd5ac867a3d47c67191b3755560a19 | 26df8a922aea89557071dc919d6d21fb7241488a | /firmware/ArduinoPixel/src/external/esp_ws2812/esp_ws2812_rmt.cpp | 8ac8217d2c314a09d855911f667849da1c0e2d5d | [
"MIT"
] | permissive | nlamprian/ArduinoPixel | 813335abc7a495b4e604db37f737cb30f770f974 | eb28d9fed6deede2ca67b485b6fd834321a825b6 | refs/heads/master | 2023-02-05T22:32:49.543840 | 2020-12-27T18:41:07 | 2020-12-27T19:07:14 | 17,894,345 | 21 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 5,561 | cpp | esp_ws2812_rmt.cpp | /*! \file esp_ws2812_rmt.cpp
* \brief Definitions of functions for interfacing with the RMT peripheral on
* ESP32.
* \note Based on public domain code created on 19 Nov 2016 by Chris Osborn
* <fozztexx@fozztexx.com> http://insentricity.com
* \author Martin F. Falatic
* \date 2017
* \copyright The MIT License (MIT)
* \par
* Copyright (c) 2017 Martin F. Falatic
* \par
* 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:
* \par
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \par
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifdef ESP32
#include "external/esp_ws2812/esp_ws2812_rmt.h"
#ifdef DEBUG_WS2812_DRIVER
char *debug_buffer = NULL;
const int debug_buffer_size = 1024;
#endif
#define RMTCHANNEL 0 // There are 8 possible channels
#define DIVIDER 4 // 8 stil seems to work, but timings become marginal
#define MAX_PULSES 32 // A channel has a 64 pulse buffer - we use half per pass
#define RMT_DURATION_NS \
12.5 // Minimum time of a single RMT duration based on clock ns
RmtPulsePair ws2812_bitval_to_rmt_map[2];
uint16_t ws2812_pos, ws2812_len, ws2812_half;
extern TimingParams params;
extern xSemaphoreHandle ws2812_sem;
extern uint8_t *ws2812_buffer;
static uint16_t ws2812_buf_is_dirty;
void initRMTChannel(int rmtChannel) {
RMT.apb_conf.fifo_mask = 1; // Enable memory access, instead of FIFO mode
RMT.apb_conf.mem_tx_wrap_en = 1; // Wrap around when hitting end of buffer
RMT.conf_ch[rmtChannel].conf0.div_cnt = DIVIDER;
RMT.conf_ch[rmtChannel].conf0.mem_size = 1;
RMT.conf_ch[rmtChannel].conf0.carrier_en = 0;
RMT.conf_ch[rmtChannel].conf0.carrier_out_lv = 1;
RMT.conf_ch[rmtChannel].conf0.mem_pd = 0;
RMT.conf_ch[rmtChannel].conf1.rx_en = 0;
RMT.conf_ch[rmtChannel].conf1.mem_owner = 0;
RMT.conf_ch[rmtChannel].conf1.tx_conti_mode = 0; // Loop back mode
RMT.conf_ch[rmtChannel].conf1.ref_always_on = 1; // Use apb clock ( 80M)
RMT.conf_ch[rmtChannel].conf1.idle_out_en = 1;
RMT.conf_ch[rmtChannel].conf1.idle_out_lv = 0;
}
void copyToRmtBlock_half() {
// This fills half an RMT block
// When wraparound happens, we want to keep
// the inactive half of the RMT block filled
uint16_t offset = ws2812_half * MAX_PULSES;
ws2812_half = !ws2812_half;
uint16_t len = ws2812_len - ws2812_pos;
if (len > (MAX_PULSES / 8)) len = (MAX_PULSES / 8);
if (!len) {
if (!ws2812_buf_is_dirty) return;
// Clear the channel's data block and return
for (uint16_t i = 0; i < MAX_PULSES; ++i)
RMTMEM.chan[RMTCHANNEL].data32[i + offset].val = 0;
ws2812_buf_is_dirty = 0;
return;
}
ws2812_buf_is_dirty = 1;
uint16_t i;
for (i = 0; i < len; ++i) {
uint16_t byteval = ws2812_buffer[i + ws2812_pos];
#ifdef DEBUG_WS2812_DRIVER
snprintf(debug_buffer, debug_buffer_size, "%s%d(", debug_buffer, byteval);
#endif
// Shift bits out, MSB first, setting RMTMEM.chan[n].data32[x] to the
// RmtPulsePair value corresponding to the buffered bit value
for (uint16_t j = 0; j < 8; ++j, byteval <<= 1) {
int bitval = (byteval >> 7) & 0x01;
int data32_idx = i * 8 + offset + j;
RMTMEM.chan[RMTCHANNEL].data32[data32_idx].val =
ws2812_bitval_to_rmt_map[bitval].val;
#ifdef DEBUG_WS2812_DRIVER
snprintf(debug_buffer, debug_buffer_size, "%s%d", debug_buffer, bitval);
#endif
}
#ifdef DEBUG_WS2812_DRIVER
snprintf(debug_buffer, debug_buffer_size, "%s) ", debug_buffer);
#endif
// Handle the reset bit by stretching duration1 for the final bit in the
// stream
if (i + ws2812_pos == ws2812_len - 1) {
RMTMEM.chan[RMTCHANNEL].data32[i * 8 + offset + 7].duration1 =
params.TRS / (RMT_DURATION_NS * DIVIDER);
#ifdef DEBUG_WS2812_DRIVER
snprintf(debug_buffer, debug_buffer_size, "%sRESET ", debug_buffer);
#endif
}
}
// Clear the remainder of the channel's data not set above
for (i *= 8; i < MAX_PULSES; ++i)
RMTMEM.chan[RMTCHANNEL].data32[i + offset].val = 0;
ws2812_pos += len;
#ifdef DEBUG_WS2812_DRIVER
snprintf(debug_buffer, debug_buffer_size, "%s ", debug_buffer);
#endif
}
void handleInterrupt(void *arg) {
portBASE_TYPE task_awoken = 0;
if (RMT.int_st.ch0_tx_thr_event) {
copyToRmtBlock_half();
RMT.int_clr.ch0_tx_thr_event = 1;
} else if (RMT.int_st.ch0_tx_end && ws2812_sem) {
xSemaphoreGiveFromISR(ws2812_sem, &task_awoken);
RMT.int_clr.ch0_tx_end = 1;
}
}
void dumpDebugBuffer(int id) {
#ifdef DEBUG_WS2812_DRIVER
Serial.print("DEBUG: (");
Serial.print(id);
Serial.print(") ");
Serial.println(debug_buffer);
debug_buffer[0] = 0;
#endif
}
#endif // ESP32
|
079b14c6d13a637832028ea359b29fa84a99db33 | 338bfe4b504d2175f24a405d836fa34566d78b02 | /02-SGI_STL源码/SGI_STL/bits/stl_iterator.h | 68a5d24a7dd5259595a9c841f2feded8520b0bad | [] | no_license | irplay/code_repository | a74628d8940b6f5cc874307cd549fc5d61f18a6b | 34064b82ba9159111ceea7c58513f3c483c4384e | refs/heads/master | 2021-01-18T06:25:07.178124 | 2015-05-12T09:00:35 | 2015-05-12T09:00:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,378 | h | stl_iterator.h |
#ifndef __GLIBCPP_INTERNAL_ITERATOR_H
#define __GLIBCPP_INTERNAL_ITERATOR_H
namespace std
{
template<typename _Iterator>
class reverse_iterator
: public iterator<typename iterator_traits<_Iterator>::iterator_category,
typename iterator_traits<_Iterator>::value_type,
typename iterator_traits<_Iterator>::difference_type,
typename iterator_traits<_Iterator>::pointer,
typename iterator_traits<_Iterator>::reference>
{
protected:
_Iterator current;
public:
typedef _Iterator iterator_type;
typedef typename iterator_traits<_Iterator>::difference_type
difference_type;
typedef typename iterator_traits<_Iterator>::reference reference;
typedef typename iterator_traits<_Iterator>::pointer pointer;
public:
/**
* The default constructor gives an undefined state to this %iterator.
*/
reverse_iterator() { }
/**
* This %iterator will move in the opposite direction that @p x does.
*/
explicit
reverse_iterator(iterator_type __x) : current(__x) { }
/**
* The copy constructor is normal.
*/
reverse_iterator(const reverse_iterator& __x)
: current(__x.current) { }
/**
* A reverse_iterator across other types can be copied in the normal
* fashion.
*/
template<typename _Iter>
reverse_iterator(const reverse_iterator<_Iter>& __x)
: current(__x.base()) { }
/**
* @return @c current, the %iterator used for underlying work.
*/
iterator_type
base() const { return current; }
/**
* @return TODO
*
* @doctodo
*/
reference
operator*() const
{
_Iterator __tmp = current;
return *--__tmp;
}
/**
* @return TODO
*
* @doctodo
*/
pointer
operator->() const { return &(operator*()); }
/**
* @return TODO
*
* @doctodo
*/
reverse_iterator&
operator++()
{
--current;
return *this;
}
/**
* @return TODO
*
* @doctodo
*/
reverse_iterator
operator++(int)
{
reverse_iterator __tmp = *this;
--current;
return __tmp;
}
/**
* @return TODO
*
* @doctodo
*/
reverse_iterator&
operator--()
{
++current;
return *this;
}
/**
* @return TODO
*
* @doctodo
*/
reverse_iterator operator--(int)
{
reverse_iterator __tmp = *this;
++current;
return __tmp;
}
/**
* @return TODO
*
* @doctodo
*/
reverse_iterator
operator+(difference_type __n) const
{ return reverse_iterator(current - __n); }
/**
* @return TODO
*
* @doctodo
*/
reverse_iterator&
operator+=(difference_type __n)
{
current -= __n;
return *this;
}
/**
* @return TODO
*
* @doctodo
*/
reverse_iterator
operator-(difference_type __n) const
{ return reverse_iterator(current + __n); }
/**
* @return TODO
*
* @doctodo
*/
reverse_iterator&
operator-=(difference_type __n)
{
current += __n;
return *this;
}
/**
* @return TODO
*
* @doctodo
*/
reference
operator[](difference_type __n) const { return *(*this + __n); }
};
//@{
/**
* @param x A %reverse_iterator.
* @param y A %reverse_iterator.
* @return A simple bool.
*
* Reverse iterators forward many operations to their underlying base()
* iterators. Others are implemented in terms of one another.
*
*/
template<typename _Iterator>
inline bool
operator==(const reverse_iterator<_Iterator>& __x,
const reverse_iterator<_Iterator>& __y)
{ return __x.base() == __y.base(); }
template<typename _Iterator>
inline bool
operator<(const reverse_iterator<_Iterator>& __x,
const reverse_iterator<_Iterator>& __y)
{ return __y.base() < __x.base(); }
template<typename _Iterator>
inline bool
operator!=(const reverse_iterator<_Iterator>& __x,
const reverse_iterator<_Iterator>& __y)
{ return !(__x == __y); }
template<typename _Iterator>
inline bool
operator>(const reverse_iterator<_Iterator>& __x,
const reverse_iterator<_Iterator>& __y)
{ return __y < __x; }
template<typename _Iterator>
inline bool
operator<=(const reverse_iterator<_Iterator>& __x,
const reverse_iterator<_Iterator>& __y)
{ return !(__y < __x); }
template<typename _Iterator>
inline bool
operator>=(const reverse_iterator<_Iterator>& __x,
const reverse_iterator<_Iterator>& __y)
{ return !(__x < __y); }
template<typename _Iterator>
inline typename reverse_iterator<_Iterator>::difference_type
operator-(const reverse_iterator<_Iterator>& __x,
const reverse_iterator<_Iterator>& __y)
{ return __y.base() - __x.base(); }
template<typename _Iterator>
inline reverse_iterator<_Iterator>
operator+(typename reverse_iterator<_Iterator>::difference_type __n,
const reverse_iterator<_Iterator>& __x)
{ return reverse_iterator<_Iterator>(__x.base() - __n); }
//@}
// 24.4.2.2.1 back_insert_iterator
/**
* These are output iterators, constructed from a container-of-T.
* Assigning a T to the iterator appends it to the container using
* push_back.
*
* Tip: Using the back_inserter function to create these iterators can
* save typing.
*/
template<typename _Container>
class back_insert_iterator
: public iterator<output_iterator_tag, void, void, void, void>
{
protected:
_Container* container;
public:
/// A nested typedef for the type of whatever container you used.
typedef _Container container_type;
/// The only way to create this %iterator is with a container.
explicit
back_insert_iterator(_Container& __x) : container(&__x) { }
/**
* @param value An instance of whatever type
* container_type::const_reference is; presumably a
* reference-to-const T for container<T>.
* @return This %iterator, for chained operations.
*
* This kind of %iterator doesn't really have a "position" in the
* container (you can think of the position as being permanently at
* the end, if you like). Assigning a value to the %iterator will
* always append the value to the end of the container.
*/
back_insert_iterator&
operator=(typename _Container::const_reference __value)
{
container->push_back(__value);
return *this;
}
/// Simply returns *this.
back_insert_iterator&
operator*() { return *this; }
/// Simply returns *this. (This %iterator does not "move".)
back_insert_iterator&
operator++() { return *this; }
/// Simply returns *this. (This %iterator does not "move".)
back_insert_iterator
operator++(int) { return *this; }
};
/**
* @param x A container of arbitrary type.
* @return An instance of back_insert_iterator working on @p x.
*
* This wrapper function helps in creating back_insert_iterator instances.
* Typing the name of the %iterator requires knowing the precise full
* type of the container, which can be tedious and impedes generic
* programming. Using this function lets you take advantage of automatic
* template parameter deduction, making the compiler match the correct
* types for you.
*/
template<typename _Container>
inline back_insert_iterator<_Container>
back_inserter(_Container& __x)
{ return back_insert_iterator<_Container>(__x); }
/**
* These are output iterators, constructed from a container-of-T.
* Assigning a T to the iterator prepends it to the container using
* push_front.
*
* Tip: Using the front_inserter function to create these iterators can
* save typing.
*/
template<typename _Container>
class front_insert_iterator
: public iterator<output_iterator_tag, void, void, void, void>
{
protected:
_Container* container;
public:
/// A nested typedef for the type of whatever container you used.
typedef _Container container_type;
/// The only way to create this %iterator is with a container.
explicit front_insert_iterator(_Container& __x) : container(&__x) { }
/**
* @param value An instance of whatever type
* container_type::const_reference is; presumably a
* reference-to-const T for container<T>.
* @return This %iterator, for chained operations.
*
* This kind of %iterator doesn't really have a "position" in the
* container (you can think of the position as being permanently at
* the front, if you like). Assigning a value to the %iterator will
* always prepend the value to the front of the container.
*/
front_insert_iterator&
operator=(typename _Container::const_reference __value)
{
container->push_front(__value);
return *this;
}
/// Simply returns *this.
front_insert_iterator&
operator*() { return *this; }
/// Simply returns *this. (This %iterator does not "move".)
front_insert_iterator&
operator++() { return *this; }
/// Simply returns *this. (This %iterator does not "move".)
front_insert_iterator
operator++(int) { return *this; }
};
/**
* @param x A container of arbitrary type.
* @return An instance of front_insert_iterator working on @p x.
*
* This wrapper function helps in creating front_insert_iterator instances.
* Typing the name of the %iterator requires knowing the precise full
* type of the container, which can be tedious and impedes generic
* programming. Using this function lets you take advantage of automatic
* template parameter deduction, making the compiler match the correct
* types for you.
*/
template<typename _Container>
inline front_insert_iterator<_Container>
front_inserter(_Container& __x)
{ return front_insert_iterator<_Container>(__x); }
/**
* These are output iterators, constructed from a container-of-T.
* Assigning a T to the iterator inserts it in the container at the
* %iterator's position, rather than overwriting the value at that
* position.
*
* (Sequences will actually insert a @e copy of the value before the
* %iterator's position.)
*
* Tip: Using the inserter function to create these iterators can
* save typing.
*/
template<typename _Container>
class insert_iterator
: public iterator<output_iterator_tag, void, void, void, void>
{
protected:
_Container* container;
typename _Container::iterator iter;
public:
/// A nested typedef for the type of whatever container you used.
typedef _Container container_type;
/**
* The only way to create this %iterator is with a container and an
* initial position (a normal %iterator into the container).
*/
insert_iterator(_Container& __x, typename _Container::iterator __i)
: container(&__x), iter(__i) {}
/**
* @param value An instance of whatever type
* container_type::const_reference is; presumably a
* reference-to-const T for container<T>.
* @return This %iterator, for chained operations.
*
* This kind of %iterator maintains its own position in the
* container. Assigning a value to the %iterator will insert the
* value into the container at the place before the %iterator.
*
* The position is maintained such that subsequent assignments will
* insert values immediately after one another. For example,
* @code
* // vector v contains A and Z
*
* insert_iterator i (v, ++v.begin());
* i = 1;
* i = 2;
* i = 3;
*
* // vector v contains A, 1, 2, 3, and Z
* @endcode
*/
insert_iterator&
operator=(const typename _Container::const_reference __value)
{
iter = container->insert(iter, __value);
++iter;
return *this;
}
/// Simply returns *this.
insert_iterator&
operator*() { return *this; }
/// Simply returns *this. (This %iterator does not "move".)
insert_iterator&
operator++() { return *this; }
/// Simply returns *this. (This %iterator does not "move".)
insert_iterator&
operator++(int) { return *this; }
};
/**
* @param x A container of arbitrary type.
* @return An instance of insert_iterator working on @p x.
*
* This wrapper function helps in creating insert_iterator instances.
* Typing the name of the %iterator requires knowing the precise full
* type of the container, which can be tedious and impedes generic
* programming. Using this function lets you take advantage of automatic
* template parameter deduction, making the compiler match the correct
* types for you.
*/
template<typename _Container, typename _Iterator>
inline insert_iterator<_Container>
inserter(_Container& __x, _Iterator __i)
{
return insert_iterator<_Container>(__x,
typename _Container::iterator(__i));
}
} // namespace std
namespace __gnu_cxx
{
// This iterator adapter is 'normal' in the sense that it does not
// change the semantics of any of the operators of its iterator
// parameter. Its primary purpose is to convert an iterator that is
// not a class, e.g. a pointer, into an iterator that is a class.
// The _Container parameter exists solely so that different containers
// using this template can instantiate different types, even if the
// _Iterator parameter is the same.
using std::iterator_traits;
using std::iterator;
template<typename _Iterator, typename _Container>
class __normal_iterator
: public iterator<typename iterator_traits<_Iterator>::iterator_category,
typename iterator_traits<_Iterator>::value_type,
typename iterator_traits<_Iterator>::difference_type,
typename iterator_traits<_Iterator>::pointer,
typename iterator_traits<_Iterator>::reference>
{
protected:
_Iterator _M_current;
public:
typedef typename iterator_traits<_Iterator>::difference_type
difference_type;
typedef typename iterator_traits<_Iterator>::reference reference;
typedef typename iterator_traits<_Iterator>::pointer pointer;
__normal_iterator() : _M_current(_Iterator()) { }
explicit
__normal_iterator(const _Iterator& __i) : _M_current(__i) { }
// Allow iterator to const_iterator conversion
template<typename _Iter>
inline __normal_iterator(const __normal_iterator<_Iter, _Container>& __i)
: _M_current(__i.base()) { }
// Forward iterator requirements
reference
operator*() const { return *_M_current; }
pointer
operator->() const { return _M_current; }
__normal_iterator&
operator++() { ++_M_current; return *this; }
__normal_iterator
operator++(int) { return __normal_iterator(_M_current++); }
// Bidirectional iterator requirements
__normal_iterator&
operator--() { --_M_current; return *this; }
__normal_iterator
operator--(int) { return __normal_iterator(_M_current--); }
// Random access iterator requirements
reference
operator[](const difference_type& __n) const
{ return _M_current[__n]; }
__normal_iterator&
operator+=(const difference_type& __n)
{ _M_current += __n; return *this; }
__normal_iterator
operator+(const difference_type& __n) const
{ return __normal_iterator(_M_current + __n); }
__normal_iterator&
operator-=(const difference_type& __n)
{ _M_current -= __n; return *this; }
__normal_iterator
operator-(const difference_type& __n) const
{ return __normal_iterator(_M_current - __n); }
const _Iterator&
base() const { return _M_current; }
};
// Note: In what follows, the left- and right-hand-side iterators are
// allowed to vary in types (conceptually in cv-qualification) so that
// comparaison between cv-qualified and non-cv-qualified iterators be
// valid. However, the greedy and unfriendly operators in std::rel_ops
// will make overload resolution ambiguous (when in scope) if we don't
// provide overloads whose operands are of the same type. Can someone
// remind me what generic programming is about? -- Gaby
// Forward iterator requirements
template<typename _IteratorL, typename _IteratorR, typename _Container>
inline bool
operator==(const __normal_iterator<_IteratorL, _Container>& __lhs,
const __normal_iterator<_IteratorR, _Container>& __rhs)
{ return __lhs.base() == __rhs.base(); }
template<typename _Iterator, typename _Container>
inline bool
operator==(const __normal_iterator<_Iterator, _Container>& __lhs,
const __normal_iterator<_Iterator, _Container>& __rhs)
{ return __lhs.base() == __rhs.base(); }
template<typename _IteratorL, typename _IteratorR, typename _Container>
inline bool
operator!=(const __normal_iterator<_IteratorL, _Container>& __lhs,
const __normal_iterator<_IteratorR, _Container>& __rhs)
{ return __lhs.base() != __rhs.base(); }
template<typename _Iterator, typename _Container>
inline bool
operator!=(const __normal_iterator<_Iterator, _Container>& __lhs,
const __normal_iterator<_Iterator, _Container>& __rhs)
{ return __lhs.base() != __rhs.base(); }
// Random access iterator requirements
template<typename _IteratorL, typename _IteratorR, typename _Container>
inline bool
operator<(const __normal_iterator<_IteratorL, _Container>& __lhs,
const __normal_iterator<_IteratorR, _Container>& __rhs)
{ return __lhs.base() < __rhs.base(); }
template<typename _Iterator, typename _Container>
inline bool
operator<(const __normal_iterator<_Iterator, _Container>& __lhs,
const __normal_iterator<_Iterator, _Container>& __rhs)
{ return __lhs.base() < __rhs.base(); }
template<typename _IteratorL, typename _IteratorR, typename _Container>
inline bool
operator>(const __normal_iterator<_IteratorL, _Container>& __lhs,
const __normal_iterator<_IteratorR, _Container>& __rhs)
{ return __lhs.base() > __rhs.base(); }
template<typename _Iterator, typename _Container>
inline bool
operator>(const __normal_iterator<_Iterator, _Container>& __lhs,
const __normal_iterator<_Iterator, _Container>& __rhs)
{ return __lhs.base() > __rhs.base(); }
template<typename _IteratorL, typename _IteratorR, typename _Container>
inline bool
operator<=(const __normal_iterator<_IteratorL, _Container>& __lhs,
const __normal_iterator<_IteratorR, _Container>& __rhs)
{ return __lhs.base() <= __rhs.base(); }
template<typename _Iterator, typename _Container>
inline bool
operator<=(const __normal_iterator<_Iterator, _Container>& __lhs,
const __normal_iterator<_Iterator, _Container>& __rhs)
{ return __lhs.base() <= __rhs.base(); }
template<typename _IteratorL, typename _IteratorR, typename _Container>
inline bool
operator>=(const __normal_iterator<_IteratorL, _Container>& __lhs,
const __normal_iterator<_IteratorR, _Container>& __rhs)
{ return __lhs.base() >= __rhs.base(); }
template<typename _Iterator, typename _Container>
inline bool
operator>=(const __normal_iterator<_Iterator, _Container>& __lhs,
const __normal_iterator<_Iterator, _Container>& __rhs)
{ return __lhs.base() >= __rhs.base(); }
// _GLIBCPP_RESOLVE_LIB_DEFECTS
// According to the resolution of DR179 not only the various comparison
// operators but also operator- must accept mixed iterator/const_iterator
// parameters.
template<typename _IteratorL, typename _IteratorR, typename _Container>
inline typename __normal_iterator<_IteratorL, _Container>::difference_type
operator-(const __normal_iterator<_IteratorL, _Container>& __lhs,
const __normal_iterator<_IteratorR, _Container>& __rhs)
{ return __lhs.base() - __rhs.base(); }
template<typename _Iterator, typename _Container>
inline __normal_iterator<_Iterator, _Container>
operator+(typename __normal_iterator<_Iterator, _Container>::difference_type __n,
const __normal_iterator<_Iterator, _Container>& __i)
{ return __normal_iterator<_Iterator, _Container>(__i.base() + __n); }
} // namespace __gnu_cxx
#endif
// Local Variables:
// mode:C++
// End:
|
9c4869adf32c63c874e793d5d0d8dfd470df4c42 | a61cde1abdf6d984625752e3bb4b6a22d4d4d35d | /MS3/Product.h | e889037de56189e0c0e4a5da6a5d3227afe9a9ea | [] | no_license | fzhang13/OOP244 | e661ad94e1494d0f25228aac366e6fd0647b1146 | ecf7079baa5d62a23d42836a8fe4fdffc2bdf60f | refs/heads/master | 2020-03-26T22:30:43.924071 | 2018-11-05T18:25:25 | 2018-11-05T18:25:25 | 135,484,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,287 | h | Product.h | /**********************************************************
* Name: Xin Song Zhang
* Student ID: 111976171
* Seneca email: xszhang3@myseneca.ca
* Date of Completion: July 23rd, 2018
**********************************************************/
#ifndef PRODUCT_H
#define PRODUCT_H
#include <iostream>
#include "ErrorState.h"
namespace AMA {
const int maxCharSku = 7;
const int maxCharUnit = 10;
const int maxCharName = 75;
const double taxRate = 0.13;
const int max_sku_length = maxCharSku;
const int max_name_length = maxCharName;
const int max_unit_length = maxCharUnit;
class Product{
private:
char m_proType;
char m_proSku[maxCharSku + 1];
char m_proUnit[maxCharUnit + 1];
char* m_proName;
int m_quantityOnHand;
int m_quantityNeeded;
double m_priceOfEach;
bool m_taxable;
ErrorState m_err;
protected:
void name(const char*);
const char* name() const;
const char* sku() const;
const char* unit() const;
bool taxed() const;
double price() const;
double cost() const;
void message(const char*);
bool isClear() const;
public:
Product(char type = 'N');
Product(const char* sku, const char* pName, const char * unit, int onHand = 0, bool taxable = true, double beforeTax = 0.0, int needed = 0);
Product(const Product& other);
Product& operator=(const Product& other);
~Product();
std::fstream& store(std::fstream& file, bool newLine=true) const;
std::fstream& load(std::fstream& file);
std::ostream& write(std::ostream& os, bool linear) const;
std::istream& read(std::istream& is);
bool operator==(const char*) const;
double total_cost() const;
void quantity(int);
bool isEmpty() const;
int qtyNeeded() const;
int quantity() const;
bool operator>(const char*) const;
bool operator>(const Product&) const;
int operator+=(int);
};
std::ostream& operator<<(std::ostream&, const Product&);
std::istream& operator>>(std::istream& is, Product& other);
double operator+=(double& total, const Product& other);
}
#endif /* Product_hpp */
|
affa0c91db131dee1a2a01ac2d24d4c32a1c8eb5 | 75a574cc626abb6106d749cc55c7acd28e672594 | /Test/PostOrderBinaryIteratorWithOutStack.h | 79951f40427ded3eabbe194b7ebe93e0e9c85eb4 | [] | no_license | PeterGH/temp | 6b247e0f95ac3984d61459e0648421253d11bdc3 | 0427b6614880e8c596cca0350a02fda08fb28176 | refs/heads/master | 2020-03-31T16:10:30.114748 | 2018-11-19T03:48:53 | 2018-11-19T03:48:53 | 152,365,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,745 | h | PostOrderBinaryIteratorWithOutStack.h | #pragma once
#include "BinaryIterator.h"
#include "BinaryNodeWithParent.h"
using namespace std;
namespace Test {
template<class T> class PostOrderBinaryIteratorWithOutStack : public BinaryIterator<T, BinaryNodeWithParent> {
private:
BinaryNodeWithParent<T> * current;
BinaryNodeWithParent<T> * prev;
public:
PostOrderBinaryIteratorWithOutStack(BinaryNodeWithParent<T> * p) : BinaryIterator(p), current(p), prev(p)
{
this->operator++();
}
PostOrderBinaryIteratorWithOutStack(const PostOrderBinaryIteratorWithOutStack & it) : BinaryIterator(it), current(it.pointer), prev(it.pointer)
{
this->operator++();
}
PostOrderBinaryIteratorWithOutStack(void) : BinaryIterator(), current(nullptr), prev(nullptr) {}
// Prefix increment
// ++ it
bool operator++() {
if (this->current == nullptr) {
this->pointer = nullptr;
}
while (this->current != nullptr) {
if (this->prev == this->current->Right()) {
this->pointer = this->current;
this->prev = this->current;
this->current = this->current->Parent();
break;
} else if (this->current->Left() != nullptr && this->prev != this->current->Left()) {
this->prev = this->current;
this->current = (BinaryNodeWithParent<T> *)this->current->Left();
} else {
this->prev = this->current;
if (this->current->Right() != nullptr) {
this->current = (BinaryNodeWithParent<T> *)this->current->Right();
} else {
this->pointer = this->current;
this->current = this->current->Parent();
break;
}
}
}
return this->pointer != nullptr;
}
// Postfix increment
// it ++
bool operator++(int) { return operator++(); }
};
} |
09e70073c188c436c3d1725399453cbaa18bd638 | 6ea50d800eaf5690de87eea3f99839f07c662c8b | /ver.0.15.0.1/EmptyMapItem.h | 0da309b58ed803b6c917bbbb4454795a8d260a6f | [] | no_license | Toku555/MCPE-Headers | 73eefeab8754a9ce9db2545fb0ea437328cade9e | b0806aebd8c3f4638a1972199623d1bf686e6497 | refs/heads/master | 2021-01-15T20:53:23.115576 | 2016-09-01T15:38:27 | 2016-09-01T15:38:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 431 | h | EmptyMapItem.h | #pragma once
class EmptyMapItem{
public:
EmptyMapItem(void);
EmptyMapItem(void);
void addPlayerMarker(ItemInstance &);
void addPlayerMarker(ItemInstance &);
void getInteractText(Player const&);
void getInteractText(Player const&);
void requiresInteract(void);
void requiresInteract(void);
void use(ItemInstance &,Player &);
void use(ItemInstance &,Player &);
void ~EmptyMapItem();
void ~EmptyMapItem();
};
|
55e09555ca86a7a4f3befb5e35b6ab529d2fd482 | 6926361d32b07133eee7b84f7a2049f925b39199 | /src/SignalR/clients/cpp/src/signalrclient/negotiate.cpp | a38d1e31e3a9faf2da3afd4a8199ee96a4adc662 | [
"Apache-2.0"
] | permissive | lyqcoder/AspNetCore | d0ed82460adfaf94dd9d656443cdf45ad7fe6fa2 | 6a6a870f0847d347e72443eda843969d0b46da94 | refs/heads/master | 2020-05-04T06:17:27.579794 | 2019-04-01T23:01:26 | 2019-04-02T04:43:30 | 179,002,699 | 1 | 1 | Apache-2.0 | 2019-04-02T05:06:27 | 2019-04-02T05:06:25 | null | UTF-8 | C++ | false | false | 4,511 | cpp | negotiate.cpp | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#include "stdafx.h"
#include "negotiate.h"
#include "url_builder.h"
#include "signalrclient/signalr_exception.h"
namespace signalr
{
namespace negotiate
{
pplx::task<negotiation_response> negotiate(http_client& client, const std::string& base_url,
const signalr_client_config& config)
{
auto negotiate_url = url_builder::build_negotiate(base_url);
pplx::task_completion_event<negotiation_response> tce;
// TODO: signalr_client_config
http_request request;
request.method = http_method::POST;
for (auto& header : config.get_http_headers())
{
request.headers.insert(std::make_pair(utility::conversions::to_utf8string(header.first), utility::conversions::to_utf8string(header.second)));
}
client.send(negotiate_url, request, [tce](http_response http_response, std::exception_ptr exception)
{
if (exception != nullptr)
{
tce.set_exception(exception);
return;
}
if (http_response.status_code != 200)
{
tce.set_exception(signalr_exception("negotiate failed with status code " + std::to_string(http_response.status_code)));
return;
}
try
{
auto negotiation_response_json = web::json::value::parse(utility::conversions::to_string_t(http_response.content));
negotiation_response response;
if (negotiation_response_json.has_field(_XPLATSTR("error")))
{
response.error = utility::conversions::to_utf8string(negotiation_response_json[_XPLATSTR("error")].as_string());
tce.set(std::move(response));
return;
}
if (negotiation_response_json.has_field(_XPLATSTR("connectionId")))
{
response.connectionId = utility::conversions::to_utf8string(negotiation_response_json[_XPLATSTR("connectionId")].as_string());
}
if (negotiation_response_json.has_field(_XPLATSTR("availableTransports")))
{
for (auto transportData : negotiation_response_json[_XPLATSTR("availableTransports")].as_array())
{
available_transport transport;
transport.transport = utility::conversions::to_utf8string(transportData[_XPLATSTR("transport")].as_string());
for (auto format : transportData[_XPLATSTR("transferFormats")].as_array())
{
transport.transfer_formats.push_back(utility::conversions::to_utf8string(format.as_string()));
}
response.availableTransports.push_back(transport);
}
}
if (negotiation_response_json.has_field(_XPLATSTR("url")))
{
response.url = utility::conversions::to_utf8string(negotiation_response_json[_XPLATSTR("url")].as_string());
if (negotiation_response_json.has_field(_XPLATSTR("accessToken")))
{
response.accessToken = utility::conversions::to_utf8string(negotiation_response_json[_XPLATSTR("accessToken")].as_string());
}
}
if (negotiation_response_json.has_field(_XPLATSTR("ProtocolVersion")))
{
tce.set_exception(signalr_exception("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details."));
}
tce.set(std::move(response));
}
catch (...)
{
tce.set_exception(std::current_exception());
}
});
return pplx::create_task(tce);
}
}
}
|
f8c8ce0af086e8266cb2f867427cc4f9d6e49fa0 | a9e525c3db9f22caf20dcca2788c81c6bb8b6449 | /include/Thor/Math/ExpressionNodes.h | fb4b7baa0a554699b3f101fe49e6dabf692b25fc | [] | no_license | Soth1985/Thor2 | 6056c5b64ed7127d322189916edf9d44ec239145 | 9c7f18a5c795ecc7c0d78456ee5c9d30ea8aa696 | refs/heads/master | 2023-04-27T07:42:19.427364 | 2023-04-17T07:16:17 | 2023-04-17T07:16:17 | 57,103,735 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,868 | h | ExpressionNodes.h | #pragma once
#include <Thor/Framework/Common.h>
namespace Thor{
///////////////////////////////////////////////////////////////////
/**
* nil_t represents no type template parameter.
*/
struct nil_t
{};
template < class OpT >
struct Traverser;
///////////////////////////////////////////////////////////////////
/**
* This class represents binary operations in the expression parse tree.
* The temporary type TempT for a given expression is considered the same for all parts of expression,
* and is equal to the type of Block of the object the expression is assigned to.
* OpT should have a "static apply( const LhsT& l, const RhsT& r, TempT& tmp, const IterT& i )" method.
* This expression template expects a single temporary Block as input per expression.
*/
template < class OpT, class LhsT, class RhsT >
struct BinaryNode
{
//in debug mode we should store values instead of references to avoid crushes
//#ifdef _DEBUG
// const LhsT& lhs;
// const RhsT& rhs;
//#else
const LhsT lhs;
const RhsT rhs;
//#endif
typedef OpT op_t;
typedef LhsT lhs_t;
typedef RhsT rhs_t;
typedef BinaryNode< OpT, LhsT, RhsT > self_t;
//typedef TempT temp_t;
/*unsigned int block_size()
{
return block_sz;
};*/
template < class TempT, class IterT >
THOR_INLINE void traverse( TempT& tmp, const IterT& i ) const
{
//#pragma inline_depth(2048)
Traverser<OpT>::visit_node( lhs, rhs, tmp, i );
};
template < class ReturnT, class IterT >
THOR_INLINE ReturnT at( const IterT& i ) const
{
//return OpT::apply< ReturnT >( lhs.at<ReturnT>(i), rhs.at<ReturnT>(i) );
return OpT::apply< ReturnT >( lhs, rhs, i );
};
template < class ReturnT, class IterT >
THOR_INLINE ReturnT at( const IterT& i, const IterT& j ) const
{
//return OpT::apply< ReturnT >( lhs.at<ReturnT>(i), rhs.at<ReturnT>(i) );
return OpT::apply< ReturnT >( lhs, rhs, i, j );
};
THOR_INLINE BinaryNode( const LhsT& l, const RhsT& r ): lhs(l), rhs(r) {};
THOR_INLINE BinaryNode( const BinaryNode& copy ): lhs(copy.lhs), rhs(copy.rhs) {};
BinaryNode& operator=( const BinaryNode& ){};
};
///////////////////////////////////////////////////////////////////
/**
* This class represents unary operations in the expression parse tree.
* The temporary type TempT for a given expression is considered the same for all parts of expression,
* and is equal to the type of Block of the object the expression is assigned to.
* OpT should have a "static apply( const ArgT& a, TempT& tmp, const IterT& i )" method.
* This expression template expects a single temporary Block as input per expression.
*/
template < class OpT, class ArgT >
struct UnaryNode
{
//in debug mode we should store values instead of references to avoid crushes
//#ifdef _DEBUG
// const ArgT arg;
//#else
const ArgT arg;
//#endif
typedef OpT op_t;
typedef ArgT arg_t;
typedef UnaryNode< OpT, ArgT > self_t;
template < class TempT, class IterT >
THOR_INLINE void traverse( TempT& tmp, const IterT& i ) const
{
Traverser<OpT>::visit_node( arg, tmp, i );
};
//template < class IterT >
/*THOR_INLINE const float operator[]( int& i ) const
{
OpT::apply( arg, tmp, i );
}; */
template < class ReturnT, class IterT >
THOR_INLINE ReturnT at( const IterT& i ) const
{
//return OpT::apply<ReturnT>( arg.at<ReturnT>(i) );
return OpT::apply< ReturnT >( arg, i );
};
template < class ReturnT, class IterT >
THOR_INLINE ReturnT at( const IterT& i, const IterT& j ) const
{
//return OpT::apply<ReturnT>( arg.at<ReturnT>(i) );
return OpT::apply< ReturnT >( arg, i, j );
};
THOR_INLINE UnaryNode( const ArgT& a ): arg(a){};
THOR_INLINE UnaryNode( const UnaryNode& copy ): arg( copy.arg ){};
UnaryNode& operator=( const UnaryNode& ){};
};
template < class DataT >
class Leaf;
///////////////////////////////////////////////////////////////////
/**
* Expression stores the parse tree.
*/
template < class ExprT, class ResultT >
struct Expression
{
typedef ExprT node_t;
typedef ResultT result_t;
const ExprT tree;
template < class TempT, class IterT >
THOR_INLINE void traverse( TempT& tmp, const IterT& i ) const
{
tree.traverse( tmp, i );
};
THOR_INLINE Expression( const ExprT& node ):tree(node){};
THOR_INLINE Expression( const Expression& copy ):tree(copy.tree){};
Expression& operator=( const Expression& ){};
};
template <class OpT, class T>
struct unary_result;
template <class OpT, class L, class R>
struct binary_result;
///////////////////////////////////////////////////////////////////
/**
* MakeNode creates a parse tree node and plugs it into the tree.
* node_t is the type of a new node,
* expr_t is a resulting tree after a new node insertion.
* OpT is operator tag,
* T1 and T2 are node children,
* T3 is dummy parameter.
*/
//Generic case
template < class OpT = nil_t, class T1 = nil_t, class T2 = nil_t, class T3 = nil_t >
struct MakeNode
{
typedef nil_t node_t;
typedef Expression< nil_t, nil_t > expr_t;
};
//Leaf unary node
template < class OpT, class T1 >
struct MakeNode< OpT, T1 >
{
typedef UnaryNode< OpT, Leaf<T1> > node_t;
typedef typename unary_result<OpT,T1>::result_t result_t;
typedef Expression< node_t, result_t > expr_t;
};
//Unary node
template < class OpT, class T1, class R >
struct MakeNode< OpT, Expression<T1,R> >
{
typedef UnaryNode< OpT, T1 > node_t;
typedef typename Expression<T1,R>::result_t prev_result_t;
typedef typename unary_result<OpT,prev_result_t>::result_t result_t;
typedef Expression< node_t, result_t > expr_t;
};
//Leaf binary node
template < class OpT, class T1, class T2 >
struct MakeNode< OpT, T1, T2 >
{
typedef BinaryNode< OpT, Leaf<T1>, Leaf<T2> > node_t;
typedef typename binary_result<OpT,T1, T2>::result_t result_t;
typedef Expression< node_t, result_t > expr_t;
};
//Binary node with left leaf
template < class OpT, class T1, class T2, class R1 >
struct MakeNode< OpT, Expression<T1,R1>, T2 >
{
typedef BinaryNode< OpT, T1, Leaf<T2> > node_t;
typedef typename Expression<T1,R1>::result_t left_result_t;
typedef typename binary_result<OpT,left_result_t,T2>::result_t result_t;
typedef Expression< node_t, result_t > expr_t;
};
//Binary node with right leaf
template < class OpT, class T1, class T2, class R2 >
struct MakeNode< OpT, T1, Expression<T2,R2> >
{
typedef BinaryNode< OpT, Leaf<T1>, T2 > node_t;
typedef typename Expression<T2,R2>::result_t right_result_t;
typedef typename binary_result<OpT,T1,right_result_t>::result_t result_t;
typedef Expression< node_t, result_t > expr_t;
};
//Binary node
template < class OpT, class T1, class T2, class R1, class R2 >
struct MakeNode< OpT, Expression<T1,R1>, Expression<T2,R2> >
{
typedef BinaryNode< OpT, T1, T2 > node_t;
typedef typename Expression<T1,R1>::result_t left_result_t;
typedef typename Expression<T2,R2>::result_t right_result_t;
typedef typename binary_result<OpT,left_result_t,right_result_t>::result_t result_t;
typedef Expression< node_t, result_t > expr_t;
};
template < class DataT >
class Leaf
{
const DataT& data;
public:
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT& i ) const
{
return data(i);
};
template < class ReturnT, class IterT1, class IterT2 >
THOR_INLINE const ReturnT& at( const IterT1& i, const IterT2& j ) const
{
return data(i,j);
};
//reference accessor
THOR_INLINE const DataT& ref() const
{
return data;
};
THOR_INLINE Leaf( const DataT& data_ ): data(data_){};
THOR_INLINE Leaf( const Leaf& copy ): data(copy.data){};
Leaf& operator=( const Leaf& copy ){};
};
//
template <>
class Leaf<float>
{
const float data;
public:
//vector accessor
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT& i ) const
{
return data;
};
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT& i, const IterT& j ) const
{
return data;
};
//reference accessor
THOR_INLINE const float& ref(void) const
{
return data;
};
THOR_INLINE Leaf( const float& data_ ): data(data_){};
THOR_INLINE Leaf( const Leaf& copy ): data(copy.data){};
Leaf& operator=( const Leaf& ){};
};
//
template <>
class Leaf<double>
{
const double data;
public:
//vector accessor
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT& i ) const
{
return data;
};
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT& i, const IterT& j ) const
{
return data;
};
//reference accessor
THOR_INLINE const double& ref() const
{
return data;
};
THOR_INLINE Leaf( const double& data_ ): data(data_){};
THOR_INLINE Leaf( const Leaf& copy ): data(copy.data){};
Leaf& operator=( const Leaf& ){};
};
//
template <>
class Leaf<int>
{
const int data;
public:
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT& i ) const
{
return data;
};
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT& i, const IterT& j ) const
{
return data;
};
//reference accessor
THOR_INLINE const int& ref() const
{
return data;
};
THOR_INLINE Leaf( const int& data_ ): data(data_){};
THOR_INLINE Leaf( const Leaf& copy ): data(copy.data){};
Leaf& operator=( const Leaf& ){};
};
//
template <>
class Leaf<unsigned int>
{
const unsigned int data;
public:
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT &i ) const
{
return data;
};
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT& i, const IterT& j ) const
{
return data;
};
//reference accessor
THOR_INLINE const unsigned int& ref() const
{
return data;
};
THOR_INLINE Leaf( const unsigned int& data_ ): data(data_){};
THOR_INLINE Leaf( const Leaf& copy ): data(copy.data){};
Leaf& operator=( const Leaf& ){};
};
//
template <>
class Leaf<char>
{
const char data;
public:
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT& i ) const
{
return data;
};
template < class ReturnT, class IterT >
THOR_INLINE const ReturnT& at( const IterT& i, const IterT& j ) const
{
return data;
};
//reference accessor
THOR_INLINE const char& ref() const
{
return data;
};
THOR_INLINE Leaf( const char& data_ ): data(data_){};
THOR_INLINE Leaf( const Leaf& copy ): data(copy.data){};
Leaf& operator=( const Leaf& ){};
};
}//Thor |
5b84245423ecd27622c5226a757e57092edd27e8 | 5b53cd96e4cc12ddb18b738acd091941f2b69d64 | /URI/uri2582.cpp | b64cb01c27c1317b604d50c8bb150b30801b22c9 | [] | no_license | mtdecarvalho/POO-21.01 | 5457ea90c99564b0f5415a7139105a1bd24966e0 | 4fa78dc2ff7d87d2e4da9aa7b2d413dede6e3cbc | refs/heads/main | 2023-06-23T17:31:57.259442 | 2021-07-19T16:50:14 | 2021-07-19T16:50:14 | 354,854,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 832 | cpp | uri2582.cpp | #include <iostream>
using namespace std;
void musica( int X )
{
switch ( X )
{
case 0: cout << "PROXYCITY" << endl; break;
case 1: cout << "P.Y.N.G." << endl; break;
case 2: cout << "DNSUEY!" << endl; break;
case 3: cout << "SERVERS" << endl; break;
case 4: cout << "HOST!" << endl; break;
case 5: cout << "CRIPTONIZE" << endl; break;
case 6: cout << "OFFLINE DAY" << endl; break;
case 7: cout << "SALT" << endl; break;
case 8: cout << "ANSWER!" << endl; break;
case 9: cout << "RAR?" << endl; break;
case 10: cout << "WIFI ANTENNAS" << endl; break;
default: break;
}
}
int main ()
{
int C, X, Y, i;
cin >> C;
for ( i = 0 ; i < C ; i++ )
{
cin >> X >> Y;
musica(X+Y);
}
return 0;
} |
da632217b4473b20c4babdacaa1e77e1cda8c4bb | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /hackathon/brl/s2/targetList.h | f798f03ebf4a027b660f86fa41b37f3cf5ae9fca | [
"BSD-2-Clause",
"MIT"
] | permissive | Vaa3D/vaa3d_tools | edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9 | e6974d5223ae70474efaa85e1253f5df1814fae8 | refs/heads/master | 2023-08-03T06:12:01.013752 | 2023-08-02T07:26:01 | 2023-08-02T07:26:01 | 50,527,925 | 107 | 86 | MIT | 2023-05-22T23:43:48 | 2016-01-27T18:19:17 | C++ | UTF-8 | C++ | false | false | 752 | h | targetList.h | #ifndef TARGETLIST_H
#define TARGETLIST_H
#include <QWidget>
#include <QTableWidget>
#include "v3d_message.h"
#include <v3d_interface.h>
#include "tileInfo.h"
class TargetList : public QWidget
{
Q_OBJECT
public:
explicit TargetList(QWidget *parent = 0);
signals:
public slots:
void updateTargetTable(QList<TileInfo> inputTargetList, QList<LandmarkList> inputScanLocations);
void addTarget(const LocationSimple &newTarget);
void addScanLoc(int row, LocationSimple newScanLoc, float xWidth, float yWidth);
void updateScanTable(int newIndex, int ignore);
private:
QTableWidget* targetTable;
QTableWidget* scanLocTable;
QGridLayout* mainLayout;
QList<LandmarkList> scanLocations;
};
#endif // TARGETLIST_H
|
a4c1b7e003cbc732ab4fd791806dd8f6f1ac31ac | 35a8885c932fb958de277e91d9c0f17085655965 | /MapEditor/layer/GridLayerStratgey.h | f7ceb23121dd09102a0acf95823bd05be269e6af | [] | no_license | Kuiderlix/Map-Editor | 72470e4ffd1ca05eb873d698b2487871521b5800 | 5f4fc20d6e4121f71cbfd865c2efe4b8f5deec6f | refs/heads/master | 2021-05-27T08:40:03.341949 | 2014-06-24T11:29:11 | 2014-06-24T11:29:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | h | GridLayerStratgey.h | #ifndef GRIDLAYERSTRATGEY_H
#define GRIDLAYERSTRATGEY_H
#include "MapView.h"
class GridLayerStratgey : public IStrategy
{
public:
GridLayerStratgey(MapView * mapView);
virtual void execute();
private:
MapView * mapView;
};
#endif // GRIDLAYERSTRATGEY_H
|
3d33bbdb936d2a3e044c5c8e1df068452a0f19a5 | 30dded54c00844dfe5febbb977759c5c9643ea47 | /test/Base.h | 343ae0f8ba63aa79ca59d17813cd1ed3a8be4ac2 | [] | no_license | IamLupo/base-problem | 436839e4ae589cc991dcd124b2c88aef86acabac | b230373b8addc6a41ce23c49e2ec5a639c09a309 | refs/heads/master | 2020-03-24T00:06:14.065459 | 2018-07-27T17:51:41 | 2018-07-27T17:51:41 | 142,273,463 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 356 | h | Base.h | #ifndef H_BASE
#define H_BASE
#include <iostream>
#include <vector>
using namespace std;
class Base {
private:
int base;
long long value;
vector<int> digits;
void updateDigits();
public:
Base();
~Base();
void set(int base, int value);
bool isValid();
int collisions();
void draw();
};
#endif |
43a0c6f9345cde9b30448981c15e40d88537e523 | c423ab2463e0f9560fbc27de94262111fe45071c | /c-c++/diamond.cpp | 1a68daede24862d3dcdcdb19ab2d53328fd6133a | [] | no_license | cutecprog/playcode | 61ae5ccc7bfd7592f54036d818e42e589e5a3cde | 431e97ba3a6b27c14311968e6336e127449b6c4c | refs/heads/master | 2021-01-23T17:19:53.327367 | 2014-10-27T14:49:17 | 2014-10-27T14:49:17 | 3,365,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | cpp | diamond.cpp | #include <iostream>
#include <time.h>
using namespace std;
void makeDiamond (int, int);
int main()
{
int startTime;
int size, numOfTimes;
cin >> size >> numOfTimes;
startTime = time(0);
makeDiamond(size, numOfTimes);
cout << "Time to complete task: " <<(time(0) - startTime) << " Seconds" << endl;
system("pause");
}
void makeDiamond (int size, int numOfTimes)
{
int spaces = size;
int stars = 0;
int m = 1;
int c = 0;
while (c <= ((size*2)*numOfTimes))
{
for (int i =0; i < spaces; i++)
cout << ' ';
for (int i=0; i < stars*2+1; i++)
cout << '*';
c+= (m + 1);
m = (spaces==size || spaces==0 ? -m : m);
spaces += m;
stars -= m;
cout << endl;
}
}
|
adb2d4fa195c3ac98bf6f0834e205d142669a836 | d7170c2a8234c947432ee1cbffe2eb22db31b221 | /transmission_model/src/Stats.h | 16be415cf59d6c88f352add27075090b1f5bcf03 | [] | no_license | khanna7/BARS | c3ab28354f4bb711c7d8307486194769454c86ff | 6829f0da638c0c839c40dd6f6b84a645c62f4446 | refs/heads/master | 2023-07-06T06:33:57.160645 | 2023-06-28T23:17:24 | 2023-06-28T23:17:24 | 40,013,171 | 6 | 2 | null | 2016-05-17T17:08:43 | 2015-07-31T16:01:07 | C | UTF-8 | C++ | false | false | 5,913 | h | Stats.h | /*
* Stats.h
*
* Created on: Nov 6, 2015
* Author: nick
*/
#ifndef SRC_STATS_H_
#define SRC_STATS_H_
#include <vector>
#include <fstream>
#include "FileOutput.h"
#include "StatsWriter.h"
#include "common.h"
#include "PersonDataRecorder.h"
#include "Range.h"
namespace TransModel {
struct ARTEvent {
static const std::string header;
double tick;
int p_id;
// false is off art, true is on art
bool type;
void writeTo(FileOutput& out);
};
struct PREPEvent {
static const std::string header;
double tick;
int p_id;
// 0 is off prep, 1 is off because infected, 2 is on
int type;
void writeTo(FileOutput& out);
};
struct TestingEvent {
static const std::string header;
double tick;
int p_id;
bool result;
void writeTo(FileOutput& out);
};
struct Biomarker {
static const std::string header;
double tick;
int p_id;
float viral_load, cd4;
bool on_art;
void writeTo(FileOutput& out);
};
struct DeathEvent {
static const std::string header;
static const std::string AGE, INFECTION, ASM, ASM_CD4;
double tick;
int p_id;
float age;
bool art_status;
std::string cause;
void writeTo(FileOutput& out);
};
struct InfectionEvent {
static const std::string header;
double tick;
int p1_id, p2_id;
float p1_age, p2_age;
float p1_viral_load, p2_viral_load, p1_infectivity, p1_cd4, p2_cd4;
bool p1_art, p1_on_prep, p2_on_prep, condom_used;
int network_type;
void writeTo(FileOutput& out);
};
struct PartnershipEvent {
static const std::string header;
enum PEventType {ENDED_DISSOLUTION, STARTED, ENDED_DEATH_INFECTION, ENDED_DEATH_ASM, ENDED_AGING_OUT, ENDED_DEATH_ASM_CD4};
double tick_;
unsigned int edge_id_;
int p1_id, p2_id;
PEventType type_;
int network_type;
PartnershipEvent(double tick, unsigned int edge_id, int p1, int p2, PEventType type, int net_type);
void writeTo(FileOutput& out);
};
struct Counts {
static const std::string header;
double tick;
unsigned int main_edge_count, casual_edge_count,
//size, internal_infected, external_infected, infected_at_entry, uninfected,
entries, age_deaths, infection_deaths, asm_deaths;
int overlaps;
unsigned int sex_acts, casual_sex_acts, steady_sex_acts;
unsigned int sd_casual_sex_with_condom, sd_casual_sex_without_condom;
unsigned int sd_steady_sex_with_condom, sd_steady_sex_without_condom;
unsigned int sc_casual_sex_with_condom, sc_casual_sex_without_condom;
unsigned int sc_steady_sex_with_condom, sc_steady_sex_without_condom;
unsigned int on_art, on_prep;
//unsigned int uninfected_u26, uninfected_gte26, infected_via_transmission_u26, infected_via_transmission_gte26,
// vertex_count_u26, vertex_count_gte26;
//unsigned int external_infected_u26, external_infected_gte26, infected_at_entry_u26, infected_at_entry_gte26;
// internal_infected is infected by transmission
std::vector<unsigned int> uninfected, internal_infected, external_infected, infected_at_entry, vertex_count;
int min_age_;
double vl_supp_per_positives, vl_supp_per_diagnosis, cd4m_deaths;
Counts(int min_age, int max_age);
void reset();
void writeTo(FileOutput& out);
void incrementInfected(PersonPtr& p);
void incrementInfectedAtEntry(PersonPtr& p);
void incrementInfectedExternal(PersonPtr& p);
void incrementUninfected(PersonPtr& p);
void incrementVertexCount(PersonPtr p);
};
class Stats {
private:
std::shared_ptr<StatsWriterI<Counts>> counts_writer;
Counts current_counts;
std::shared_ptr<StatsWriterI<PartnershipEvent>> pevent_writer;
std::shared_ptr<StatsWriterI<InfectionEvent>> ievent_writer;
std::shared_ptr<StatsWriterI<Biomarker>> biomarker_writer;
std::shared_ptr<StatsWriterI<DeathEvent>> death_writer;
std::shared_ptr<StatsWriterI<TestingEvent>> tevent_writer;
std::shared_ptr<StatsWriterI<ARTEvent>> art_event_writer;
std::shared_ptr<StatsWriterI<PREPEvent>> prep_event_writer;
std::shared_ptr<PersonDataRecorderI> pd_recorder;
friend class StatsBuilder;
static Stats* instance_;
Stats(std::shared_ptr<StatsWriterI<Counts>> counts, std::shared_ptr<StatsWriterI<PartnershipEvent>> pevents,
std::shared_ptr<StatsWriterI<InfectionEvent>> infection_event_writer, std::shared_ptr<StatsWriterI<Biomarker>> bio_writer,
std::shared_ptr<StatsWriterI<DeathEvent>> death_event_writer, const std::string& person_data_fname,
std::shared_ptr<StatsWriterI<TestingEvent>> testing_event_writer, std::shared_ptr<StatsWriterI<ARTEvent>> art_event_writer,
std::shared_ptr<StatsWriterI<PREPEvent>> prep_event_writer, int min_age, int max_age);
public:
virtual ~Stats();
void resetForNextTimeStep();
Counts& currentCounts() {
return current_counts;
}
std::shared_ptr<PersonDataRecorderI> personDataRecorder() {
return pd_recorder;
}
static Stats* instance() {
return instance_;
}
void recordPartnershipEvent(double time, unsigned int edge_id, int p1, int p2, PartnershipEvent::PEventType event_type, int net_type);
void recordInfectionEvent(double time, const PersonPtr& p1, const PersonPtr& p2, bool condom, int net_type);
/**
* Records an infection event for persons entering the model as infected.
*/
void recordInfectionEvent(double time, const PersonPtr& p);
void recordBiomarker(double time, const PersonPtr& person);
void recordDeathEvent(double time, const PersonPtr& person, const std::string& cause);
void recordTestingEvent(double time, int p_id, bool result);
void recordARTEvent(double time, int p_id, bool onART);
void recordPREPEvent(double time, int p_id, int type);
};
} /* namespace TransModel */
#endif /* SRC_STATS_H_ */
|
d18a61519745137cd89f8d3c44d165b8956d4317 | 197381ad9ce2e3b224d9c40882da6e56b301f180 | /b.cpp | cf93ac9d1ab843cd79e4e49faef8c07d32d2d584 | [] | no_license | dalalsunil1986/OnlineJudge-Solution | c68ec45acf276478d1fa56dc7bede987bdc224a4 | fb2309c9c90b27dab02bec9d87e0de0a3359c128 | refs/heads/master | 2023-07-16T04:20:55.255485 | 2021-08-28T17:58:22 | 2021-08-28T17:58:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 657 | cpp | b.cpp | #include<bits/stdc++.h>
using namespace std;
double f(double v)
{
return pow(v,3)-3*v-5;
}
int main()
{
long long int i;
stepa: double a,b,c;
cout<<"Enter two guessing number: ";
cin>>a>>b;
if(f(a)*f(b)>0){
goto stepa;
}
double x1,x2,Er;
cout<<"iteration\ta\tb\tc\tf(c)\n";
for(i=1;i<=10;i++)
{
c=(a+b)/(2*1.0);
cout<<" "<<i<<"\t\t";
printf("%.4lf\t%.4lf\t%.4lf",a,b,c);
x2=c;
printf("\t%.4lf\n",f(c));
if(f(a)*f(c)<0)
{
b=c;
}
else
{
a=c;
}
}
cout<<"root is : "<<c<<endl;
}
|
47233b93492d8d483856ad50daa429d7f285dc18 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /ash/ash_element_identifiers.h | 24a96bbcfd1d36cf9ee64ea465ac16079e9ac55f | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 3,411 | h | ash_element_identifiers.h | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_ASH_ELEMENT_IDENTIFIERS_H_
#define ASH_ASH_ELEMENT_IDENTIFIERS_H_
#include "ash/ash_export.h"
#include "ui/base/interaction/element_identifier.h"
namespace ash {
// Element IDs -----------------------------------------------------------------
// Please keep this list alphabetized.
// Uniquely identifies the app list bubble view (the clamshell mode launcher).
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT,
kAppListBubbleViewElementId);
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT,
kBluetoothFeatureTileToggleElementId);
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT, kEnterpriseManagedView);
// Uniquely identifies an element corresponding to the Explore app. Note that
// this may be used in multiple contexts (e.g. app window, launcher, shelf,
// etc.), so care must be taken to use the desired context when looking up the
// associated element.
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT, kExploreAppElementId);
// Uniquely identifies the `HoldingSpaceTray`.
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT,
kHoldingSpaceTrayElementId);
// Uniquely identifies the home (launcher) button.
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT, kHomeButtonElementId);
// Uniquely identifies the `LoginUserView`.
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT, kLoginUserViewElementId);
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(
ASH_EXPORT,
kQuickSettingsSettingsButtonElementId);
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT,
kQuickSettingsViewElementId);
// Uniquely identifies the `SearchBoxView`.
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT, kSearchBoxViewElementId);
// Uniquely identifies an element corresponding to the Settings app. Note that
// this may be used in multiple contexts (e.g. app window, launcher, shelf,
// etc.), so care must be taken to use the desired context when looking up the
// associated element.
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT, kSettingsAppElementId);
// Uniquely identifies the `ShelfView`.
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT, kShelfViewElementId);
// Uniquely identifies the `UnifiedSystemTray`.
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT,
kUnifiedSystemTrayElementId);
// Uniquely identifies the `WelcomeTourDialog` for user education.
DECLARE_EXPORTED_ELEMENT_IDENTIFIER_VALUE(ASH_EXPORT,
kWelcomeTourDialogElementId);
// Element Names ---------------------------------------------------------------
// Please keep this list alphabetized.
// Name which may be set for the `HomeButton` during an interaction sequence to
// uniquely identify a particular instance.
inline constexpr char kHomeButtonElementName[] = "kHomeButtonElementName";
// Name which may be set for the `UnifiedSystemTray` during an interaction
// sequence to uniquely identify a particular instance.
inline constexpr char kUnifiedSystemTrayElementName[] =
"kUnifiedSystemTrayElementName";
} // namespace ash
#endif // ASH_ASH_ELEMENT_IDENTIFIERS_H_
|
33fe159e0d77d69947db5820b5ee146b83b15412 | 28871bf036c6081bae6f582e9606e1a0027ecc87 | /uartsetting.h | 5136bc99b468d2f0039af3c96fe89c263fb80731 | [] | no_license | Zhangfan94/PLCMonitor | 6f5fa641de353c3abeff6649afe4083e7b14f469 | e28062991b925cdd4f3ec2162cc564943eacc021 | refs/heads/master | 2021-04-06T02:07:02.712017 | 2018-05-13T05:18:26 | 2018-05-13T05:20:15 | 124,897,463 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | h | uartsetting.h | #ifndef UARTSETTING_H
#define UARTSETTING_H
#include "datamenu.h"
#include <QShowEvent>
#include <QWidget>
#include "settingmenu.h"
namespace Ui {
class UartSetting;
}
class UartSetting : public QWidget
{
Q_OBJECT
public:
explicit UartSetting(QWidget *parent = 0);
~UartSetting();
private:
bool initPlcSerialService();
bool initMcuSerialService();
protected:
void showEvent(QShowEvent *event);
private slots:
void on_loginBtn_clicked();
void on_retBtn_clicked();
private:
Ui::UartSetting *ui;
DataMenu* dataMenu;
};
#endif // UARTSETTING_H
|
d96bdc62121e219f9ad47a00c0f09f67c80ad169 | 7ea1866667a22f99f110503a7177d12f45e7cca1 | /CollatzAVL/DLL.h | 74ad4170f9f00fdfe5be501e4c8fd417efc4bf05 | [] | no_license | Diamond-Dust/CollatzAVL | c2cbecee7fc0d445ec976e6d6df4a7734487d747 | f98eb8b9a0ed82c1bc8a4d2ed1d9494c65788cfa | refs/heads/master | 2020-03-17T11:55:31.169453 | 2018-05-16T10:21:47 | 2018-05-16T10:21:47 | 133,569,168 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,421 | h | DLL.h | #pragma once
typedef struct Module {
char value;
Module* next;
Module* prev;
}Node;
class DLL {
private:
int size;
Module *head, *tail;
public:
DLL() {
head = nullptr;
tail = nullptr;
size = 0;
}
int GetSize() {
return size;
}
void AddFront(const char& newM) {
Module* NewM = new Module;
NewM->value = newM;
if (size == 0)
tail = NewM;
else
{
head->next = NewM;
NewM->prev = head;
}
head = NewM;
size++;
}
void AddBack(const char& newM) {
Module* NewM = new Module;
NewM->value = newM;
if (size == 0)
head = NewM;
else
{
tail->prev = NewM;
NewM->next = tail;
}
tail = NewM;
size++;
}
char PopFront() {
if (size == 0)
return 0;
char popped = head->value;
if (size > 1)
{
head = head->prev;
delete head->next;
}
else
{
head = nullptr;
tail = nullptr;
}
size--;
return popped;
}
char PopBack() {
if (size == 0)
return 0;
char popped = tail->value;
if (size > 1)
{
tail = tail->next;
delete tail->prev;
}
else
{
tail = nullptr;
head = nullptr;
}
size--;
return popped;
}
void Dissolve() {
char popped = this->PopFront();
if (popped == 0)
putchar('#');
while (popped)
{
putchar(popped);
popped = this->PopFront();
}
}
~DLL() {
delete head;
delete tail;
}
}; |
93d68abae877f7bf0adee329e95f30f4374404c7 | ffb70f65171441ff865e357738b77a80e57b555e | /lesson11part1.cpp | 3448be95887794ae1212d7d564483212dd7440e7 | [] | no_license | matthewsvu/School-Labs | 8a0da59a1e02bf6a44e7a3b8425c8fdb452fc1c2 | 65e9295b4826712b94e410493e9c220531c5ea43 | refs/heads/master | 2021-07-14T22:40:45.681631 | 2020-11-04T21:03:36 | 2020-11-04T21:03:36 | 221,845,010 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,818 | cpp | lesson11part1.cpp | /*
Make a program that will validate a loshu magic square with sizes between
3x3 and 21x21. There must be every number from 1 to n times in the square
and the program must open and close all files.
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <vector>
using namespace std;
const int MAX_SIZE = 21;
int readSquare(int square[MAX_SIZE][MAX_SIZE], string inputFileName) // reads in file name
{
int realSize; // calculates real size
ifstream finput; // initialize input stream
finput.open(inputFileName.c_str());
if(!finput) { // if file does not open return 0
return 0;
}
finput >> realSize; // read in the length of one side
for(int i = 0; i < realSize; i++) // loops through the matrix and reads in the value for all of possible values
{
for(int j = 0; j < realSize; j++)
{
finput >> square[i][j];
}
}
finput.close(); //close file
realSize = realSize * realSize; // finds the total size of the array 3*3 = 9 total values
return realSize;
}
bool validateSquare(const int square[MAX_SIZE][MAX_SIZE], int size)
{
int length = sqrt(size); // the length of one side of the matrix
int sum = (length * (length * length + 1)) / 2; // what the sum should be of the row/column/diagonal
int rowSum = 0, columnSum = 0, leftDiagonalSum = 0, rightDiagonalSum = 0;
for(int j = 0; j < length; j++) { // checks the row sum
columnSum += square[j][length-1];
}
for(int i = 0; i < length; i++) { // checks the column sum.
rowSum += square[length-1][i];
}
for(int i = 0; i < length; i++) {
for(int j = 0; j < length; j++) {
if(square[i][j] == square[i+1][j+1] || square[i][j] == square[i+2][j+2]) { // checks to see if there is any values that are duplicates of each other diagonally
return false;
}
leftDiagonalSum += square[(length-1)-i][(length-1)-j]; // adds diagonal sum for the left
rightDiagonalSum += square[i][(length-1)-j]; // for the right
}
}
leftDiagonalSum /= length;
rightDiagonalSum /= length; // divides the sum by length
if(leftDiagonalSum == sum && rightDiagonalSum == sum && columnSum == sum && rowSum == sum) { // return true when all of these vals equal the sum
return true;
}
if(sum == length && columnSum == sum && rowSum == sum) { // return true if sum is length meaning that the arrau is just 1 value
return true;
}
return false;
}
void displaySquare(int square[MAX_SIZE][MAX_SIZE], int size) // loops through the values in square and display them in order.
{
cout << "Magic square\n";
int sideLength = sqrt(size);
for(int i = 0; i < sideLength; i++) { // the loop
for(int j = 0; j < sideLength; j++) {
cout << square[i][j]; // display
if(j == sideLength - 1) { // adds new line right before loop ends
cout << endl;
}
}
}
cout << endl;
}
int main()
{
int loshuSquare[MAX_SIZE][MAX_SIZE]; // initialize the loshu square
string inputFileName;
cout << "Enter input file name\n"; // ask for file name
cin >> inputFileName;
int filledSquare = readSquare(loshuSquare, inputFileName); // reads the square into the 2d array
if(filledSquare == 0)
{
cout << "File \"" << inputFileName << "\" could not be opened\n"; // checks if file opened
}
else
{
displaySquare(loshuSquare, filledSquare); // displays square
if(validateSquare(loshuSquare, filledSquare) == true) // checks if it valid square
{
cout << "Valid magic square\n";
}
else
{
cout << "Invalid magic square\n";
}
}
}
|
737aabe8d4376656c6db38f873782c2b1dec3aaa | 95887af3ebd6b68c8f9c30c33ae5ca4a0393512f | /Library-Management-System/librarianaddbook.cpp | 8736692b30dea15849917bff3b4fe9d1e75a3bb6 | [
"MIT"
] | permissive | xukaixout/Library-Management-System | 318ce2240dde930750bff3a7d983408c6751550e | 77eed5c411b47873580d2fe010835d8748697b09 | refs/heads/main | 2023-02-07T22:49:49.400159 | 2020-11-12T06:51:32 | 2020-11-12T06:51:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,827 | cpp | librarianaddbook.cpp | #include "librarianaddbook.h"
#include "ui_librarianaddbook.h"
#include "QMessageBox"
#include "windows.h"
#include "testh.h"
#include "QComboBox"
#include "QString"
#include "vector"
#include "QDebug"
librarianAddBook::librarianAddBook(QWidget* parent) :
QDialog(parent),
ui(new Ui::librarianAddBook)
{
ui->setupUi(this);
ui->tableWidget->setFocusPolicy(Qt::NoFocus);
ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
ui->tableWidget_2->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->tableWidget_2->horizontalHeader()->setStretchLastSection(true);
//ui->tableWidget->item(1,1)->setText(QString("%1").arg(2));
/*
ui->lineEdit->setMaxLength(20);
ui->lineEdit_4->setMaxLength(20);
ui->lineEdit_5->setMaxLength(20);
ui->lineEdit_6->setMaxLength(20);
ui->lineEdit_7->setMaxLength(20);
ui->lineEdit_8->setMaxLength(20);
*/
//connect(ui->pushButton_3,SIGNAL(clicked(bool)),this,SLOT(on_pushButton_3_clicked()));
}
librarianAddBook::~librarianAddBook()
{
delete ui;
}
void librarianAddBook::on_pushButton_clicked()
{
/*
std::string _name,_author,_type,_ISBN;
int _pageNum,_wordNum,_price;
if(ui->lineEdit_2->text().isEmpty())
{
QMessageBox::information(this,"提示","请输入isbn");
return;
}
if(ui->lineEdit->text().isEmpty() || ui->lineEdit_4->text().isEmpty() || ui->lineEdit_5->text().isEmpty()||ui->lineEdit_6->text().isEmpty()||ui->lineEdit_7->text().isEmpty()||ui->lineEdit_8->text().isEmpty())
{
QMessageBox::information(this,"提示","书籍信息未填写完整");
return;
}
_name = ui->lineEdit->text().toStdString();
_author = ui->lineEdit_4->text().toStdString();
_price = ui->lineEdit_5->text().toInt();
_type = ui->lineEdit_6->text().toStdString();
_wordNum = ui->lineEdit_7->text().toInt();
_pageNum = ui->lineEdit_8->text().toInt();
int ifisbn_exist = exist_ISBN( _ISBN);
if (ifisbn_exist == 1)
{
QMessageBox::information(this,"提示","该isbn已经存在");
return ;
}
else
{
int ifsuccessful = addBook(_ISBN, _name, _price, _type, _author, _pageNum, _wordNum);
if(ifsuccessful == 1){
QMessageBox::information(this,"提示","add successfully");
Sleep(5000);
}
else QMessageBox::information(this,"提示","添加新书异常");
}
*/
int rowIndex = ui->tableWidget->rowCount();
ui->tableWidget->setRowCount(rowIndex + 1);//总行数增加1
QComboBox* combox_1 = new QComboBox(); // 下拉选择框控件
combox_1->addItem("A");
combox_1->addItem("B");
ui->tableWidget->setCellWidget(rowIndex, 0, (QWidget*)combox_1);
}
void librarianAddBook::on_pushButton_2_clicked()
{
/*
int rowIndex = ui->tableWidget->currentRow();
if (rowIndex != -1)
ui->tableWidget->removeRow(rowIndex);
*/
int i = ui->tableWidget->currentRow();
if (i == -1) QMessageBox::information(this, "提示", "你还没选中任何一行!");
ui->tableWidget->removeRow(i);
/*
std::string _ISBN;
if(ui->lineEdit_2->text().isEmpty())
{
QMessageBox::information(this,"提示","请输入isbn");
return;
}
_ISBN = ui->lineEdit_2->text().toStdString();
int ifisbn_exist = exist_ISBN( _ISBN);
if (ifisbn_exist == 0)
{
QMessageBox::information(this,"提示","该isbn不存在,请检查");
return ;
}
else if(ifisbn_exist == 1)
{
int ifsuccessful = addByISBN(_ISBN);
if(ifsuccessful == 1){
QMessageBox::information(this,"提示","add successfully");
Sleep(5000);
}
else QMessageBox::information(this,"提示","添加新书异常");
}
*/
}
void librarianAddBook::on_pushButton_3_clicked()
{
//std::string _name,_author,_type,_ISBN;
//int _pageNum,_wordNum,_price;
if (ui->tableWidget->rowCount() == 0)
{
QMessageBox::information(this, "提示", "你还没有添加内容");
return;
}
int _rowCount = ui->tableWidget->rowCount();
//判断
int _judge = 0;
for (int i = 0; i < _rowCount && !_judge; i++)
{
QWidget* widgetSex = ui->tableWidget->cellWidget(i, 0);
QComboBox* sex = (QComboBox*)widgetSex;
bool judge = false;
if (sex->currentText() == "B")
{
if (ui->tableWidget->item(i, 1) == NULL || (ui->tableWidget->item(i, 1) && ui->tableWidget->item(i, 1)->text() == tr("")))
{
_judge = 1;
}
if (ui->tableWidget->item(i, 2) == NULL || (ui->tableWidget->item(i, 2) && ui->tableWidget->item(i, 2)->text() == tr("")))
{
_judge = 1;
}
else {
if (!ui->tableWidget->item(i, 2)->text().toInt(&judge) || !judge) _judge = 2;
}
if (ui->tableWidget->item(i, 3) == NULL || (ui->tableWidget->item(i, 3) && ui->tableWidget->item(i, 3)->text() == tr("")))
{
_judge = 1;
}
if (ui->tableWidget->item(i, 4) == NULL || (ui->tableWidget->item(i, 4) && ui->tableWidget->item(i, 4)->text() == tr("")))
{
_judge = 1;
}
else {
if (!ui->tableWidget->item(i, 4)->text().toInt(&judge) || !judge) _judge = 2;
}
if (ui->tableWidget->item(i, 5) == NULL || (ui->tableWidget->item(i, 5) && ui->tableWidget->item(i, 5)->text() == tr("")))
{
_judge = 1;
}
if (ui->tableWidget->item(i, 6) == NULL || (ui->tableWidget->item(i, 6) && ui->tableWidget->item(i, 6)->text() == tr("")))
{
_judge = 1;
}
if (ui->tableWidget->item(i, 7) == NULL || (ui->tableWidget->item(i, 7) && ui->tableWidget->item(i, 7)->text() == tr("")))
{
_judge = 1;
}
else {
if (!ui->tableWidget->item(i, 7)->text().toInt(&judge) || !judge) _judge = 2;
}
if (ui->tableWidget->item(i, 8) == NULL || (ui->tableWidget->item(i, 8) && ui->tableWidget->item(i, 8)->text() == tr("")))
{
_judge = 1;
}
else {
if (!ui->tableWidget->item(i, 8)->text().toInt(&judge) || !judge) _judge = 2;
}
}
else
{
if (ui->tableWidget->item(i, 1) == NULL || (ui->tableWidget->item(i, 1) && ui->tableWidget->item(i, 1)->text() == tr("")))
{
_judge = 1;
}
if (ui->tableWidget->item(i, 2) == NULL || (ui->tableWidget->item(i, 2) && ui->tableWidget->item(i, 2)->text() == tr("")))
{
_judge = 1;
}
else {
if (!ui->tableWidget->item(i, 2)->text().toInt(&judge) || !judge) _judge = 2;
}
}
/*if ((ui->tableWidget->item(i, 2) && ui->tableWidget->item(i, 2)->text().toInt() > 50)) {
QMessageBox::information(this, "提示", "单种图书的最大添加数量为50本!");
return;
}*/
}
if (_judge == 1)
{
QMessageBox::information(this, "提示", "存在未填充的值!");
return;
}
else if (_judge == 2) {
QMessageBox::information(this, "提示", "存在非法的输入!");
return;
}
else {
//存储
int countnums = 0;
for (int i = 0; i < ui->tableWidget->rowCount(); i++)
{
int n = ui->tableWidget->item(i, 2)->text().toInt();
countnums = countnums + n;
if (n > 50) {
QMessageBox::information(this, "提示", "单种图书的最大添加数量为50本!");
return;
}
}
qDebug() << countnums;
ui->tableWidget_2->setRowCount(countnums);
int allnums = 0;
for (int i = 0; i < _rowCount; i++)
{
std::string _ISBN, _startBorrowTime, _shouldReturnTime, _name, _type, _author;
int _hasBorrowedNum, _isBorrowed, _price, _pageNum, _wordNum, _num;
std::vector<std::string> idNums;
QWidget* widgetSex = ui->tableWidget->cellWidget(i, 0);
QComboBox* sex = (QComboBox*)widgetSex;
//qDebug() << "testAloop1";
if (sex->currentText() == "B")
{
_ISBN = ui->tableWidget->item(i, 1)->text().toStdString();
_num = ui->tableWidget->item(i, 2)->text().toInt();
_name = ui->tableWidget->item(i, 3)->text().toStdString();
_price = ui->tableWidget->item(i, 4)->text().toInt();
_author = ui->tableWidget->item(i, 5)->text().toStdString();
_type = ui->tableWidget->item(i, 6)->text().toStdString();
_wordNum = ui->tableWidget->item(i, 7)->text().toInt();
_pageNum = ui->tableWidget->item(i, 8)->text().toInt();
if (exist_ISBN(_ISBN)) {
QMessageBox::information(this, "提示", "存在已录入信息的书籍,将直接添加数量!");
}
else addBook(_ISBN, _name, _price, _type, _author, _pageNum, _wordNum);
qDebug() << "testAloop2";
addByISBN(_ISBN, _num, idNums);
for (int i = 0; i <= idNums.size() - 1; i++)
{
qDebug() << "testAloop3";
searchBookById(idNums[i], _ISBN, _hasBorrowedNum, _isBorrowed, _startBorrowTime, _shouldReturnTime, _name, _price, _type, _author, _pageNum, _wordNum);
qDebug() << "testAloop4";
QString s4 = QString::fromStdString(idNums[i]);
QString s5 = QString::fromStdString(_name);
//qDebug() << "testAloop5";
ui->tableWidget_2->setItem(i + allnums, 0, new QTableWidgetItem(s4));
ui->tableWidget_2->setItem(i + allnums, 1, new QTableWidgetItem(s5));
//qDebug() << "testAloop6";
}
allnums = allnums + _num;
}
else
{
_ISBN = ui->tableWidget->item(i, 1)->text().toStdString();
_num = ui->tableWidget->item(i, 2)->text().toInt();
if (!exist_ISBN(_ISBN)) {
QMessageBox::information(this, "提示", ("ISBN: " + _ISBN + "未录入信息,将不被创建!").c_str());
continue;
}
addByISBN(_ISBN, _num, idNums);
for (int i = 0; i < idNums.size(); i++)
{
searchBookById(idNums[i], _ISBN, _hasBorrowedNum, _isBorrowed, _startBorrowTime, _shouldReturnTime, _name, _price, _type, _author, _pageNum, _wordNum);
QString s4 = QString::fromStdString(idNums[i]);
QString s5 = QString::fromStdString(_name);
ui->tableWidget_2->setItem(i + allnums, 0, new QTableWidgetItem(s4));
ui->tableWidget_2->setItem(i + allnums, 1, new QTableWidgetItem(s5));
}
allnums = allnums + _num;
}
}
QMessageBox::information(this, "提示", "处理完毕,请根据右侧表格为书籍贴好");
ui->tableWidget->clearContents();
ui->tableWidget->setRowCount(0);
//Sleep(3000);
}
}
|
f2b0b91cbd36951d8fc18bab35c533d0effae5a9 | f420ad28c7a8836a6afff7d083b37d6ede4f427d | /MyCameraApp/app/src/main/cpp/include/mylog.h | e618d97c4fcfff7d14237e3ab0ae533fe744be50 | [] | no_license | wuRDmemory/Android_test | 381b02a541db97eff71d755037d99e0d7a6ee127 | f86f6964cbc1a8aedd7977b9aa5d97d28b6b8321 | refs/heads/master | 2020-04-02T15:46:08.960750 | 2018-10-24T23:32:34 | 2018-10-24T23:32:34 | 154,582,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 987 | h | mylog.h | //
// Created by ubuntu on 18-9-21.
//
#ifndef MYCAMERAAPP_MYLOG_H
#define MYCAMERAAPP_MYLOG_H
#include <jni.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <android/log.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/bitmap.h>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdint.h>
#define TAG "Native" // 这个是自定义的LOG的标识
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__)
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__)
typedef unsigned char uint8;
typedef unsigned int uint32;
using namespace std;
using namespace cv;
#endif //MYCAMERAAPP_MYLOG_H
|
16efa91b8c76d5b8f17bcd8693fdfbd956b64366 | 0b7fd0e1314d442780395068305b511cf3f6d7ca | /src/vertical3d/image/ImageReader.h | e27bbf8a818aa9480e3ae87f871eba28ae421a5b | [] | no_license | sigsegv42/v3dlibs | b1baa4b07df46d5168ed169b5ae95a5c4c693085 | 2fad4d38b1700442f0b15a6b8db200f1925dd1e9 | refs/heads/master | 2020-06-02T10:54:47.188214 | 2014-12-24T21:40:07 | 2014-12-24T21:40:07 | 1,419,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 401 | h | ImageReader.h | #ifndef INCLUDED_V3D_IMAGEREADER
#define INCLUDED_V3D_IMAGEREADER
#include "Image.h"
#include <boost/shared_ptr.hpp>
#include <string>
namespace v3D
{
/**
*
**/
class ImageReader
{
public:
ImageReader();
virtual ~ImageReader();
virtual boost::shared_ptr<Image> read(const std::string & filename);
private:
};
}; // end namespace v3D
#endif // INCLUDED_V3D_IMAGEREADER
|
224a120a4a83ecf67da885c46b58e2f92b71dcd0 | 337ce318df64cf38c6c8caa265e7280748f992a2 | /override/derived.hpp | b0f2d5d45a299a117d83e3058796059790b839e1 | [] | no_license | cristobalmedinalopez/boost-python-examples | f724ba459ae9959287ce661248fb8e1ae6f743d6 | d9beed420ebac32bc6b6d327dbc6b4b972f35037 | refs/heads/master | 2021-01-10T12:41:36.339808 | 2016-04-13T08:24:26 | 2016-04-13T08:24:26 | 55,055,523 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 204 | hpp | derived.hpp | #include "base.hpp"
class Derived : public Base {
public:
Derived(){}
virtual char const* hello()
{
return "hello from Derived";
}
char const* sayhello()
{
return hello();
}
};
|
59b1ad8738de37598e5afefdb6ba81a99c0ba822 | a2853c5a618ae4eb9590a1ed4d71e8c10ffc3ae5 | /Media/Scripts/Buffs/BurningDamageOverTime.hpp | cdc26c9f5aa4c39ed84b1fabed20ae119b92f28a | [] | no_license | mengzhouli/deepdeepsite | e27a2b195d143f710f51037b4a346c9c80404d4c | 912c5e0aacd5ba5e222df56d0c5359bfb3126ac4 | refs/heads/master | 2021-01-20T17:29:38.712374 | 2017-05-16T17:10:37 | 2017-05-16T17:10:37 | 90,877,709 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,006 | hpp | BurningDamageOverTime.hpp | #pragma once
#include "Buffs/DamageOverTime.hpp"
#include "Drawables/Flame.hpp"
namespace Dwarf
{
namespace Character
{
class BurningDamageOverTime : public DamageOverTime
{
public:
BurningDamageOverTime(const BuffComponentParameters& parameters, CharacterID source, float dps, float tickRate);
protected:
void OnLoadContent(Content::ContentManager* contentManager) override;
void OnUnloadContent() override;
void OnApply() override;
void OnFinish() override;
bool CanTerminate() const override;
void OnUpdate(double totalTime, float dt) override;
void OnDraw(Graphics::LevelRenderer* levelRenderer) const override;
private:
void updateFlamePositions();
Graphics::Flame _flame;
};
}
template <>
void EnumeratePreloads<Character::BurningDamageOverTime>(PreloadSet& preloads);
} |
19b8137ad6bc4b2021f213f9b3baeb90c6818f8a | d7f5938376fc232b3066a8a51005b9c7c6ab3dc5 | /Online Judge/UVa/1585 - Score.cpp | da53dcce073b4a7424afe582766a812de37952dd | [] | no_license | NurenDurdanaAbha/Nuren | a0384e167256a051c224298444f6f75d58a709b6 | a2680693c8ccfc32268c05f816030098d16865c6 | refs/heads/master | 2021-01-09T16:19:45.805936 | 2020-02-22T15:55:19 | 2020-02-22T15:55:19 | 242,368,663 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | cpp | 1585 - Score.cpp | #include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
char s[100];
int i,l,test,t,count,sum;
cin>>test;
getchar();
for(t=1; t<=test; t++)
{
cin.getline(s,100);
l=strlen(s);
sum=0;
count=0;
for(i=0; i<l; i++)
{
if(s[i]=='O')
{
count++;
sum+=count;
}
else
count=0;
}
cout<<sum<<endl;
}
return 0;
}
|
90ed4eeba7889e8e0ad2c2bb7d64a4732ba99515 | 479a94f5ff583bbd7255e3996814e8fea6dd9a86 | /core/include/rendersystem/Material.h | b186d0e64c5837419cfab8ff4f448641e68e85a9 | [] | no_license | bitores/qt-3d | 5b590ac39c6f6f500b4cdef376933a36002d9fa1 | 53b40c9b87e217787c757de818e749eb672e8613 | refs/heads/master | 2021-01-01T17:30:56.087936 | 2017-07-23T12:00:53 | 2017-07-23T12:00:53 | 98,093,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,469 | h | Material.h | #ifndef _Material_H__
#define _Material_H__
#include "utils/include/prerequisites.h"
#include "utils/include/IteratorWrappers.h"
#include "utils/include/Common.h"
#include "utils/include/ColourValue.h"
#include "utils/include/BlendMode.h"
#include "utils/include/SharedPtr.h"
#include "asset/Resource.h"
// Forward declaration
class LodStrategy;
/** \addtogroup Core
* @{
*/
/** \addtogroup Materials
* @{
*/
/** Class encapsulates rendering properties of an object.
@remarks
Ogre's material class encapsulates ALL aspects of the visual appearance,
of an object. It also includes other flags which
might not be traditionally thought of as material properties such as
culling modes and depth buffer settings, but these affect the
appearance of the rendered object and are convenient to attach to the
material since it keeps all the settings in one place. This is
different to Direct3D which treats a material as just the colour
components (diffuse, specular) and not texture maps etc. An Ogre
Material can be thought of as equivalent to a 'Shader'.
@par
A Material can be rendered in multiple different ways depending on the
hardware available. You may configure a Material to use high-complexity
fragment shaders, but these won't work on every card; therefore a Technique
is an approach to creating the visual effect you are looking for. You are advised
to create fallback techniques with lower hardware requirements if you decide to
use advanced features. In addition, you also might want lower-detail techniques
for distant geometry.
@par
Each technique can be made up of multiple passes. A fixed-function pass
may combine multiple texture layers using multitexrtuing, but Ogre can
break that into multiple passes automatically if the active card cannot
handle that many simultaneous textures. Programmable passes, however, cannot
be split down automatically, so if the active graphics card cannot handle the
technique which contains these passes, OGRE will try to find another technique
which the card can do. If, at the end of the day, the card cannot handle any of the
techniques which are listed for the material, the engine will render the
geometry plain white, which should alert you to the problem.
@par
Ogre comes configured with a number of default settings for a newly
created material. These can be changed if you wish by retrieving the
default material settings through
SceneManager::getDefaultMaterialSettings. Any changes you make to the
Material returned from this method will apply to any materials created
from this point onward.
*/
class Material : public Resource
{
friend class SceneManager;
friend class MaterialManager;
public:
// /// distance list used to specify LOD
// typedef vector<Real>::type LodValueList;
// typedef ConstVectorIterator<LodValueList> LodValueIterator;
protected:
/** Internal method which sets the material up from the default settings.
*/
void applyDefaults(void);
typedef vector<Pass*> Passes;
/// All techniques, supported and unsupported
Passes mPasses;
// LodValueList mUserLodValues;
// LodValueList mLodValues;
// const LodStrategy *mLodStrategy;
bool mReceiveShadows;
bool mTransparencyCastsShadows;
/// Does this material require compilation?
bool mCompilationRequired;
/// Text description of why any techniques are not supported
String mUnsupportedReasons;
/** Overridden from Resource.
*/
void prepareImpl(void);
/** Overridden from Resource.
*/
void unprepareImpl(void);
/** Overridden from Resource.
*/
void loadImpl(void);
/** Unloads the material, frees resources etc.
@see
Resource
*/
void unloadImpl(void);
/// @copydoc Resource::calculateSize
size_t calculateSize(void) const { return 0; } // TODO
public:
// Root* mRoot;
/** Constructor - use resource manager's create method rather than this.
*/
Material(ResourceManager* creator, const String& name, ResourceHandle handle,
const String& group, bool isManual = false, ManualResourceLoader* loader = 0);
~Material();
/** Assignment operator to allow easy copying between materials.
*/
Material& operator=( const Material& rhs );
/** Determines if the material has any transparency with the rest of the scene (derived from
whether any Techniques say they involve transparency).
*/
bool isTransparent(void) const;
/** Sets whether objects using this material will receive shadows.
@remarks
This method allows a material to opt out of receiving shadows, if
it would otherwise do so. Shadows will not be cast on any objects
unless the scene is set up to support shadows
(@see SceneManager::setShadowTechnique), and not all techniques cast
shadows on all objects. In any case, if you have a need to prevent
shadows being received by material, this is the method you call to
do it.
@note
Transparent materials never receive shadows despite this setting.
The default is to receive shadows.
*/
void setReceiveShadows(bool enabled) { mReceiveShadows = enabled; }
/** Returns whether or not objects using this material will receive shadows. */
bool getReceiveShadows(void) const { return mReceiveShadows; }
/** Sets whether objects using this material be classified as opaque to the shadow caster system.
@remarks
This method allows a material to cast a shadow, even if it is transparent.
By default, transparent materials neither cast nor receive shadows. Shadows
will not be cast on any objects unless the scene is set up to support shadows
(@see SceneManager::setShadowTechnique), and not all techniques cast
shadows on all objects.
*/
void setTransparencyCastsShadows(bool enabled) { mTransparencyCastsShadows = enabled; }
/** Returns whether or not objects using this material be classified as opaque to the shadow caster system. */
bool getTransparencyCastsShadows(void) const { return mTransparencyCastsShadows; }
/** Creates a new Pass for this Technique.
@remarks
A Pass is a single rendering pass, i.e. a single draw of the given material.
Note that if you create a pass without a fragment program, during compilation of the
material the pass may be split into multiple passes if the graphics card cannot
handle the number of texture units requested. For passes with fragment programs, however,
the number of passes you create will never be altered, so you have to make sure
that you create an alternative fallback Technique for if a card does not have
enough facilities for what you're asking for.
*/
Pass* createPass(void);
/** Retrieves the Pass with the given index. */
Pass* getPass(unsigned short index);
/** Retrieves the Pass matching name.
Returns 0 if name match is not found.
*/
Pass* getPass(const String& name);
/** Retrieves the number of passes. */
unsigned short getNumPasses(void) const;
/** Removes the Pass with the given index. */
void removePass(unsigned short index);
/** Removes all Passes from this Technique. */
void removeAllPasses(void);
/** Move a pass from source index to destination index.
If successful then returns true.
*/
bool movePass(const unsigned short sourceIndex, const unsigned short destinationIndex);
typedef VectorIterator<Passes> PassIterator;
/** Gets an iterator over the passes in this Technique. */
const PassIterator getPassIterator(void);
// typedef VectorIterator<IlluminationPassList> IlluminationPassIterator;
// /** Gets an iterator over the illumination-stage categorised passes. */
// const IlluminationPassIterator getIlluminationPassIterator(void);
// /** Gets the number of levels-of-detail this material has in the
// given scheme, based on Technique::setLodIndex.
// @remarks
// Note that this will not be up to date until the material has been compiled.
// */
// unsigned short getNumLodLevels(unsigned short schemeIndex) const;
// /** Gets the number of levels-of-detail this material has in the
// given scheme, based on Technique::setLodIndex.
// @remarks
// Note that this will not be up to date until the material has been compiled.
// */
// unsigned short getNumLodLevels(const String& schemeName) const;
/** Creates a new copy of this material with the same settings but a new name.
@param newName The name for the cloned material
@param changeGroup If true, the resource group of the clone is changed
@param newGroup Only required if changeGroup is true; the new group to assign
*/
MaterialPtr clone(const String& newName, bool changeGroup = false,
const String& newGroup = StringUtil::BLANK) const;
/** Copies the details of this material into another, preserving the target's handle and name
(unlike operator=) but copying everything else.
@param mat Weak reference to material which will receive this material's settings.
*/
void copyDetailsTo(MaterialPtr& mat) const;
/** 'Compiles' this Material.
@remarks
Compiling a material involves determining which Techniques are supported on the
card on which OGRE is currently running, and for fixed-function Passes within those
Techniques, splitting the passes down where they contain more TextureUnitState
instances than the current card has texture units.
@par
This process is automatically done when the Material is loaded, but may be
repeated if you make some procedural changes.
@param
autoManageTextureUnits If true, when a fixed function pass has too many TextureUnitState
entries than the card has texture units, the Pass in question will be split into
more than one Pass in order to emulate the Pass. If you set this to false and
this situation arises, an Exception will be thrown.
*/
void compile(bool autoManageTextureUnits = true);
// -------------------------------------------------------------------------------
// The following methods are to make migration from previous versions simpler
// and to make code easier to write when dealing with simple materials
// They set the properties which have been moved to Pass for all Techniques and all Passes
/** Sets the point size properties for every Pass in every Technique.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setPointSize
*/
void setPointSize(Real ps);
/** Sets the ambient colour reflectance properties for every Pass in every Technique.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setAmbient
*/
void setAmbient(Real red, Real green, Real blue);
/** Sets the ambient colour reflectance properties for every Pass in every Technique.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setAmbient
*/
void setAmbient(const ColourValue& ambient);
/** Sets the diffuse colour reflectance properties of every Pass in every Technique.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setDiffuse
*/
void setDiffuse(Real red, Real green, Real blue, Real alpha);
/** Sets the diffuse colour reflectance properties of every Pass in every Technique.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setDiffuse
*/
void setDiffuse(const ColourValue& diffuse);
/** Sets the specular colour reflectance properties of every Pass in every Technique.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setSpecular
*/
void setSpecular(Real red, Real green, Real blue, Real alpha);
/** Sets the specular colour reflectance properties of every Pass in every Technique.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setSpecular
*/
void setSpecular(const ColourValue& specular);
/** Sets the shininess properties of every Pass in every Technique.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setShininess
*/
void setShininess(Real val);
/** Sets the amount of self-illumination of every Pass in every Technique.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setSelfIllumination
*/
void setSelfIllumination(Real red, Real green, Real blue);
/** Sets the amount of self-illumination of every Pass in every Technique.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setSelfIllumination
*/
void setSelfIllumination(const ColourValue& selfIllum);
/** Sets whether or not each Pass renders with depth-buffer checking on or not.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setDepthCheckEnabled
*/
void setDepthCheckEnabled(bool enabled);
/** Sets whether or not each Pass renders with depth-buffer writing on or not.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setDepthWriteEnabled
*/
void setDepthWriteEnabled(bool enabled);
/** Sets the function used to compare depth values when depth checking is on.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setDepthFunction
*/
void setDepthFunction( CompareFunction func );
/** Sets whether or not colour buffer writing is enabled for each Pass.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setColourWriteEnabled
*/
void setColourWriteEnabled(bool enabled);
/** Sets the culling mode for each pass based on the 'vertex winding'.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setCullingMode
*/
void setCullingMode( CullingMode mode );
/** Sets the manual culling mode, performed by CPU rather than hardware.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setManualCullingMode
*/
void setManualCullingMode( ManualCullingMode mode );
/** Sets whether or not dynamic lighting is enabled for every Pass.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setLightingEnabled
*/
void setLightingEnabled(bool enabled);
/** Sets the type of light shading required
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setShadingMode
*/
void setShadingMode( ShadeOptions mode );
/** Sets the fogging mode applied to each pass.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setFog
*/
void setFog(
bool overrideScene,
FogMode mode = FOG_NONE,
const ColourValue& colour = ColourValue::White,
Real expDensity = 0.001, Real linearStart = 0.0, Real linearEnd = 1.0 );
/** Sets the depth bias to be used for each Pass.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setDepthBias
*/
void setDepthBias(float constantBias, float slopeScaleBias);
/** Set texture filtering for every texture unit in every Technique and Pass
@note
This property has been moved to the TextureUnitState class, which is accessible via the
Technique and Pass. For simplicity, this method allows you to set these properties for
every current TeextureUnitState, If you need more precision, retrieve the Technique,
Pass and TextureUnitState instances and set the property there.
@see TextureUnitState::setTextureFiltering
*/
void setTextureFiltering(TextureFilterOptions filterType);
/** Sets the anisotropy level to be used for all textures.
@note
This property has been moved to the TextureUnitState class, which is accessible via the
Technique and Pass. For simplicity, this method allows you to set these properties for
every current TeextureUnitState, If you need more precision, retrieve the Technique,
Pass and TextureUnitState instances and set the property there.
@see TextureUnitState::setTextureAnisotropy
*/
void setTextureAnisotropy(int maxAniso);
/** Sets the kind of blending every pass has with the existing contents of the scene.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setSceneBlending
*/
void setSceneBlending( const SceneBlendType sbt );
/** Sets the kind of blending every pass has with the existing contents of the scene, using individual factors for color and alpha channels
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setSeparateSceneBlending
*/
void setSeparateSceneBlending( const SceneBlendType sbt, const SceneBlendType sbta );
/** Allows very fine control of blending every Pass with the existing contents of the scene.
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setSceneBlending
*/
void setSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor);
/** Allows very fine control of blending every Pass with the existing contents of the scene, using individual factors for color and alpha channels
@note
This property has been moved to the Pass class, which is accessible via the
Technique. For simplicity, this method allows you to set these properties for
every current Technique, and for every current Pass within those Techniques. If
you need more precision, retrieve the Technique and Pass instances and set the
property there.
@see Pass::setSeparateSceneBlending
*/
void setSeparateSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor, const SceneBlendFactor sourceFactorAlpha, const SceneBlendFactor destFactorAlpha);
/** Tells the material that it needs recompilation. */
void _notifyNeedsRecompile(void);
/** Sets the distance at which level-of-detail (LOD) levels come into effect.
@remarks
You should only use this if you have assigned LOD indexes to the Technique
instances attached to this Material. If you have done so, you should call this
method to determine the distance at which the lowe levels of detail kick in.
The decision about what distance is actually used is a combination of this
and the LOD bias applied to both the current Camera and the current Entity.
@param lodValues A vector of Reals which indicate the lod value at which to
switch to lower details. They are listed in LOD index order, starting at index
1 (ie the first level down from the highest level 0, which automatically applies
from a value of 0). These are 'user values', before being potentially
transformed by the strategy, so for the distance strategy this is an
unsquared distance for example.
*/
// void setLodLevels(const LodValueList& lodValues);
// /** Gets an iterator over the list of values at which each LOD comes into effect.
// @remarks
// Note that the iterator returned from this method is not totally analogous to
// the one passed in by calling setLodLevels - the list includes a zero
// entry at the start (since the highest LOD starts at value 0). Also, the
// values returned are after being transformed by LodStrategy::transformUserValue.
// */
// LodValueIterator getLodValueIterator(void) const;
//
// /** Gets the LOD index to use at the given value.
// @note The value passed in is the 'transformed' value. If you are dealing with
// an original source value (e.g. distance), use LodStrategy::transformUserValue
// to turn this into a lookup value.
// */
// ushort getLodIndex(Real value) const;
//
// /** Get lod strategy used by this material. */
// const LodStrategy *getLodStrategy() const;
// /** Set the lod strategy used by this material. */
// void setLodStrategy(LodStrategy *lodStrategy);
/** @copydoc Resource::touch
*/
void touch(void)
{
if (mCompilationRequired)
compile();
// call superclass
// Resource::touch();
}
/** Applies texture names to Texture Unit State with matching texture name aliases.
All techniques, passes, and Texture Unit States within the material are checked.
If matching texture aliases are found then true is returned.
@param
aliasList is a map container of texture alias, texture name pairs
@param
apply set true to apply the texture aliases else just test to see if texture alias matches are found.
@return
True if matching texture aliases were found in the material.
*/
// bool applyTextureAliases(const AliasTextureNamePairList& aliasList, const bool apply = true) const;
/** Gets the compilation status of the material.
@return True if the material needs recompilation.
*/
bool getCompilationRequired() const
{
return mCompilationRequired;
}
};
/** @} */
/** @} */
#endif
|
0d8d86cded7c8f5b648546e696c2e3a73bc9f3d6 | ff8bbfa7e9a33593a483176fc304a9701ffc65ab | /solver/FBEsolver.hpp | 40ee8e83e09bc9e5e0b7296c4cc59d4b1b0f3267 | [] | no_license | narutse/phasefield | 15d4a94757ed59f4b970c8d42528bd42a67fafd1 | b6bf8a43d85cd613f3c897ff7238f9f3205159ca | refs/heads/master | 2021-09-07T19:34:07.407779 | 2018-02-28T00:11:09 | 2018-02-28T00:11:09 | 122,397,670 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,883 | hpp | FBEsolver.hpp | #ifndef __FBESOLVER_HPP__
#define __FBESOLVER_HPP__
#include <iostream>
#include <Eigen/Sparse>
#include "MMSfunc.hpp"
#include "matrix.hpp"
// #define PRINT_ITER
namespace Solver
{
using namespace MMSfunc;
class FBESolver
{
template <class T> using vector = std::vector<T>;
using SpMat = Eigen::SparseMatrix<double>;
using Vec = Eigen::VectorXd;
using Map = Eigen::Map<Vec>;
// Boundary locations. These never change:
static constexpr double XL = 0.0;
static constexpr double XR = 1.0;
static constexpr double YB = 0.0;
static constexpr double YT = 0.5;
static constexpr double default_tf = 8.0;
// member variables:
const Param ¶m;
int M;
int N;
double dt;
double dx;
double dy;
vector<double> x;
vector<double> y;
Vec sol;
Vec rhs;
SpMat mat;
void ConstructMatrix();
void FillRHS(double t);
void Integrate(double t_final);
int sub2ind(int i, int j) { return i*N+j; };
public:
FBESolver(const Param ¶m, int M, int N, double dt)
: param(param), M(M), N(N), dt(dt),
dx(1.0 * (XR - XL) / (M - 1)), dy(1.0 * (YT - YB) / (N - 1)),
x(M), y(N),
sol((M-1)*N), rhs((M-1)*N), mat((M-1)*N,(M-1)*N)
{
for (int i = 0; i < M; ++i) {
x[i] = XL + (XR-XL)*1.0*i/(M-1);
}
for (int j = 0; j < N; ++j) {
y[j] = YB + (YT-YB)*1.0*j/(N-1);
}
}
Matrix<double> Solve(double t_final = default_tf)
{
Integrate(t_final);
// put output in a more readable form:
Matrix<double> result(M, N);
for (int i = 0; i < M-1; ++i) {
for (int j = 0; j < N; ++j) {
result(i, j) = sol[sub2ind(i, j)];
}
}
// copy grid point not used because of periodic BCs
for (int j = 0; j < N; ++j) result(M-1, j) = result(0, j);
return result;
}
Matrix<double> GetAnalytic(double t);
double GetDx() { return dx; }
double GetDy() { return dy; }
};
// implementations of non-trivial functions here:
void FBESolver::ConstructMatrix()
{
int n = (M-1)*N;
double diag = 1 + 4*dt*param.kappa/dx/dy;
double offdiag = -dt*param.kappa/dx/dy;
mat.reserve(Vec::Constant(n, 5));
// These can be reordered for spatial cache locality
// But I will edit this later since this function
// is only called once.
// Set up Diriclet BC:
for (int i = 0; i < M-1; ++i) {
int top = sub2ind(i, 0);
int bottom = sub2ind(i, N-1);
mat.insert(top, top) = 1.0;
mat.insert(bottom, bottom) = 1.0;
}
// interior diagonal:
for (int i = 0; i < M-1; ++i) {
for (int j = 1; j < N-1; ++j) {
int index = sub2ind(i, j);
mat.insert(index, index) = diag;
}
}
// interior off-diagonal:
for (int i = 0; i < M-1; ++i) {
for (int j = 1; j < N-1; ++j) {
int index = sub2ind(i, j);
int im = sub2ind((i==0) ? (M-2) : (i-1), j);
int ip = sub2ind((i==M-2) ? 0 : (i+1), j);
int jm = sub2ind(i, j-1);
int jp = sub2ind(i, j+1);
mat.insert(index, im) = offdiag;
mat.insert(index, ip) = offdiag;
mat.insert(index, jm) = offdiag;
mat.insert(index, jp) = offdiag;
}
}
mat.makeCompressed();
}
void FBESolver::FillRHS(double t)
{
// Dirichlet BC:
for (int i = 0; i < M-1; ++i) {
int top = sub2ind(i, 0);
int bottom = sub2ind(i, N-1);
rhs[top] = 1.0;
rhs[bottom] = 0.0;
}
// interior:
for (int i = 0; i < M-1; ++i) {
for (int j = 1; j < N-1; ++j) {
int index = sub2ind(i, j);
double S = source(param, x[i], y[j], t);
rhs[index] = sol[index] +
dt*(-4*pow(sol[index], 3) + 6*sol[index]*sol[index]
- 2*sol[index] + S);
}
}
}
void FBESolver::Integrate(double t_final)
{
// Initial values:
for (int i = 0; i < M-1; ++i) {
for (int j = 0; j < N; ++j) {
sol[sub2ind(i, j)] = eta(param, x[i], y[j], 0.0);
}
}
// Setting up solver:
ConstructMatrix();
Eigen::SparseLU<SpMat> solver;
// solver.analyzePattern(mat);
// solver.factorize(mat);
// if (solver.info() != Eigen::Success)
// std::cerr << "factorize failed!!!" << std::endl;
solver.compute(mat);
double t = 0.0;
double t_check = t_final - dt/2;
#ifdef PRINT_ITER
printf("t = %.6f", t);
#endif
while (t < t_check) {
FillRHS(t);
sol = solver.solve(rhs);
t += dt;
#ifdef PRINT_ITER
printf("\rt = %.6f", t);
#endif
}
}
Matrix<double> FBESolver::GetAnalytic(double t = default_tf)
{
Matrix<double> sol(M, N);
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
sol(i, j) = eta(param, x[i], y[j], t);
}
}
return sol;
}
}
#endif |
23f5117d3f26e710a91e2a8478edd22d99c1fdf2 | 17c694001063e7ec76a48278f87f3894d4744a88 | /TESTAudioObject.h | 860b58086d4500aa4be61f63900f4a07f5985619 | [] | no_license | tpower/Nori-Engine | f94bc24e50c8da6fd3e48979cb2c36de7cb10758 | 1b146047772b950cded36b0bc45575491c51cdb5 | refs/heads/master | 2016-09-03T06:27:03.382783 | 2012-10-07T19:32:29 | 2012-10-07T19:32:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | h | TESTAudioObject.h | #ifndef TESTAUDIOOBJECT_H
#define TESTAUDIOOBJECT_H
#include "AudibleObject.h"
class TESTAudioObject : public AudibleObject
{
private:
Mix_Chunk *testSound;
public:
void processSound();
void toggleActive(bool);
};
#endif // TESTAUDIOOBJECT_H
|
9d54f02f7fab79d7378b5c33af572a83055f5712 | c6ae6d23823615013c77d34cef3044c6758039a0 | /include/ticker.h | 1b2cb3e1a39f7992dcc1e81934528e2295c5b1de | [
"MIT"
] | permissive | DennieBee/WordClock | 94b64626147cb3fdb72626ca1c2ba4bf40161f00 | f76a59a5b2a58576bc77bd41ff4dbab29ba20c04 | refs/heads/master | 2021-03-31T02:58:51.947785 | 2020-03-22T22:48:56 | 2020-03-22T22:48:56 | 248,070,095 | 0 | 0 | null | 2020-03-17T20:48:05 | 2020-03-17T20:48:04 | null | UTF-8 | C++ | false | false | 252 | h | ticker.h | #ifndef TICKER_H
#define TICKER_H
#include <display.h>
#include <ihandler.h>
class Ticker : public IHandler
{
public:
static void Initialize(String text, CRGB textColor, uint8_t delay);
static void Handle(HandlerInfo info);
private:
};
#endif |
34db2c1aa75fff1cb55620dfc215e98bccd336bf | dc4b96c2d3dda03cc058d303a1ae0fc55233159b | /Codegen/CType/CTypeRef.cpp | 143e0005531735e21f7200bb8b7ff7e210c56641 | [
"MIT"
] | permissive | belyaev-mikhail/borealis | 43783b48883cc48620db28482f31c2cdb2cd244a | 82de619ad4c462f419c55ba375404516c291a7a2 | refs/heads/master | 2020-07-11T06:52:51.661898 | 2019-05-14T09:15:42 | 2019-05-14T09:15:42 | 204,470,584 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 77 | cpp | CTypeRef.cpp | //
// Created by belyaev on 5/12/15.
//
#include "Codegen/CType/CTypeRef.h"
|
73d96ac4d5bcdd18fde760aafb26238c2ce2e7d7 | 54767226ff842669c4c0726fb025431e584325c9 | /test/unit_test.hpp | 80f52fb44628eb52afbcac75df1f1d22e590c78e | [
"MIT"
] | permissive | mmpatil/NCD | 89d39159025b44f082a22d1a03c1073ed43f52cb | 3e0eea39aaa209e470c036e324509697d80aebc9 | refs/heads/master | 2020-07-16T14:27:01.750877 | 2019-09-29T23:44:29 | 2019-09-29T23:44:29 | 205,805,508 | 0 | 0 | MIT | 2019-09-02T07:56:45 | 2019-09-02T07:56:45 | null | UTF-8 | C++ | false | false | 1,039 | hpp | unit_test.hpp | /*
* unit_test.h
*
* Created on: Dec 23, 2014
* Author: atlas
*/
#ifndef UNIT_TEST_H_
#define UNIT_TEST_H_
extern "C" {
#include "ncd.h"
}
class DetectionInitTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
char const* args[6] = {"ncd_main", "127.0.0.1", "-n3000", "-t64", "-w5", "-c3"};
size_t sz = sizeof(args) / sizeof(args[0]);
check_args(sz, (char**)args);
}
};
class MeasureUdpTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
char const* args[6] = {"fake program!!!", "127.0.0.1", "-n4786", "-t33", "-w9", "-c7"};
size_t sz = sizeof(args) / sizeof(args[0]);
check_args(sz, (char**)args);
}
};
class DetectUdpTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
char const* args[6] = {"fake program!!!", "127.0.0.1", "-n2200", "-t64", "-w4", "-c2"};
size_t sz = sizeof(args) / sizeof(args[0]);
check_args(sz, (char**)args);
}
};
#endif /* UNIT_TEST_H_ */
|
a87ea828504007f6deb5701bbb0295a2aaa7bd24 | 695ec34399b8b89da00f9dd71a99ed80c9b35e2c | /Invitation_of_Crimson_Moon/move_hero.cpp | 90e917b67e749888cb4b4d7105f1a0268e69b7ca | [] | no_license | Alicepro/Invitation_of_Crimson_Moon | f814a91fe46c0ae33fa960608cccc6e5e9894167 | 5d559cd4562efde75dfafdea99a2d2546d16004f | refs/heads/master | 2020-12-31T01:47:22.217865 | 2014-11-19T13:14:09 | 2014-11-19T13:14:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24 | cpp | move_hero.cpp | #include "move_hero.h"
|
2e8590076eec52f4c86979d5c4e937921d7e9ff5 | 464d6cb42fb8981595cbf7260069cd1e6a67fe2f | /Combitorics/CDC YTU Count possible ways to construct buildings.cpp | d34b4db6add7be303aa4e714d69bd9c299623239 | [] | no_license | rahul799/leetcode_problems | fd42276f85dc881b869072b74654f5811c6618ea | cc7f086eb9ac9bbd20ea004c46d89aa84df10d36 | refs/heads/main | 2023-04-14T05:09:31.016878 | 2021-04-20T19:46:52 | 2021-04-20T19:46:52 | 359,933,382 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,084 | cpp | CDC YTU Count possible ways to construct buildings.cpp | Count possible ways to construct buildings
Difficulty Level : Medium
Last Updated : 12 Nov, 2018
Given an input number of sections and each section has 2 plots on either sides of the road. Find all possible ways to construct buildings in the plots such that there is a space between any 2 buildings.
Example :
N = 1
Output = 4
Place a building on one side.
Place a building on other side
Do not place any building.
Place a building on both sides.
N = 3
Output = 25
3 sections, which means possible ways for one side are
BSS, BSB, SSS, SBS, SSB where B represents a building
and S represents an empty space
Total possible ways are 25, because a way to place on
one side can correspond to any of 5 ways on other side.
N = 4
Output = 64
We strongly recommend to minimize your browser and try this yourself first
We can simplify the problem to first calculate for one side only. If we know the result for one side, we can always do square of the result and get result for two sides.
A new building can be placed on a section if section just before it has space. A space can be placed anywhere (it doesn’t matter whether the previous section has a building or not).
Let countB(i) be count of possible ways with i sections
ending with a building.
countS(i) be count of possible ways with i sections
ending with a space.
// A space can be added after a building or after a space.
countS(N) = countB(N-1) + countS(N-1)
// A building can only be added after a space.
countB[N] = countS(N-1)
// Result for one side is sum of the above two counts.
result1(N) = countS(N) + countB(N)
// Result for two sides is square of result1(N)
result2(N) = result1(N) * result1(N)
Below is the implementation of above idea.
C++
filter_none
edit
play_arrow
brightness_4
// C++ program to count all possible way to construct buildings
#include<iostream>
using namespace std;
// Returns count of possible ways for N sections
int countWays(int N)
{
// Base case
if (N == 1)
return 4; // 2 for one side and 4 for two sides
// countB is count of ways with a building at the end
// countS is count of ways with a space at the end
// prev_countB and prev_countS are previous values of
// countB and countS respectively.
// Initialize countB and countS for one side
int countB=1, countS=1, prev_countB, prev_countS;
// Use the above recursive formula for calculating
// countB and countS using previous values
for (int i=2; i<=N; i++)
{
prev_countB = countB;
prev_countS = countS;
countS = prev_countB + prev_countS;
countB = prev_countS;
}
// Result for one side is sum of ways ending with building
// and ending with space
int result = countS + countB;
// Result for 2 sides is square of result for one side
return (result*result);
}
// Driver program
int main()
{
int N = 3;
cout << "Count of ways for " << N
<< " sections is " << countWays(N);
return 0;
}
|
166d57f2b25f24daba0b12a422949d5dc1947e13 | 6bc31640a0aa00b0f62be75fd8e62864ae6c7e84 | /latortugaDump/latortugaDump.cpp | 32356612460a1cc28aed8ce2a92e503fa797c321 | [] | no_license | latortuga71/latortugaDump | 3ed377b3968eb2985573f22f04fa21c25ee53b75 | 2fe9c71831217d8c71519c5dac48aa2702d5b0f4 | refs/heads/main | 2023-03-03T23:16:35.540391 | 2021-02-14T23:46:45 | 2021-02-14T23:46:45 | 338,925,188 | 7 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,593 | cpp | latortugaDump.cpp | // latortugaDump.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <Windows.h>
#include <winternl.h>
#include <ntstatus.h>
#include <stdio.h>
#include <string>
#include <map>
#include <processsnapshot.h>
#include <intrin.h>
#include <Dbghelp.h>
#pragma comment(lib,"ntdll.lib")
#pragma comment(lib,"dbghelp.lib")
using std::map;
using std::string;
//zw query information
typedef unsigned long(__stdcall* pfnZwQueryInformationProcess)(IN HANDLE, IN unsigned int, OUT PVOID, IN ULONG, OUT PULONG);
pfnZwQueryInformationProcess ZwQueryInfoProcess = (pfnZwQueryInformationProcess)GetProcAddress(GetModuleHandleA("ntdll.dll"), "ZwQueryInformationProcess");
// use ntQuerySystemInformation to get parent process info
typedef DWORD(WINAPI* PNTQUERYSYSYTEMINFORMATION)(DWORD info_class, void* out, DWORD size, DWORD* out_size);
PNTQUERYSYSYTEMINFORMATION pNtQuerySystemInformation = (PNTQUERYSYSYTEMINFORMATION)GetProcAddress(GetModuleHandleA("NTDLL.DLL"), "NtQuerySystemInformation");
wchar_t parentImageName[MAX_PATH + 1];
string fullPath;
typedef struct _SYSTEM_PROCESS_INFO
{
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER Reserved[3];
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
ULONG BasePriority;
HANDLE ProcessId;
HANDLE InheritedFromProcessId;
}SYSTEM_PROCESS_INFO, * PSYSTEM_PROCESS_INFO;
int Error(const char* msg) {
printf("%s (%u)\n", msg, GetLastError());
return 1;
}
int EnableSeDebugPriv() {
HANDLE token;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token) == FALSE)
return Error("Failed to open process token");
LUID Luid;
if (LookupPrivilegeValueW(NULL, SE_DEBUG_NAME, &Luid) == FALSE)
return Error("Failed to get SE Debug LUID");
TOKEN_PRIVILEGES newTokenPriv;
newTokenPriv.PrivilegeCount = 1;
newTokenPriv.Privileges[0].Luid = Luid;
newTokenPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (AdjustTokenPrivileges(token, FALSE, &newTokenPriv, sizeof(newTokenPriv), NULL, NULL) == 0 || GetLastError() == ERROR_NOT_ALL_ASSIGNED)
return Error("Failed to change privs");
return 0;
}
int GetLsassyPid() {
size_t bufferSize = 102400;
ULONG ulReturnLength;
NTSTATUS status;
map <int, wchar_t*> pidMap;
int myPid = GetCurrentProcessId();
int parentPid = -1;
int parentPidImageSize;
PVOID buffer = VirtualAlloc(NULL, 1024 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
PSYSTEM_PROCESS_INFO procInfo;
procInfo = (PSYSTEM_PROCESS_INFO)buffer;
status = pNtQuerySystemInformation(SystemProcessInformation, procInfo, 1024 * 1024, NULL);
if (status != STATUS_SUCCESS)
return Error("Failed to query proc list");
// save into dictionary
while (procInfo->NextEntryOffset) {
printf(": Image Name: %ws :\n", procInfo->ImageName.Buffer);
procInfo = (PSYSTEM_PROCESS_INFO)((LPBYTE)procInfo + procInfo->NextEntryOffset);
pidMap[(int)procInfo->ProcessId] = procInfo->ImageName.Buffer;
if (wcscmp(L"lsass.exe", procInfo->ImageName.Buffer) == 0){ //, procInfo->ImageName.Length);
//if (procInfo->ImageName.Buffer == L"lsass.exe") {
int lsassPid = (int)procInfo->ProcessId;
printf(":: found lsass pid -> %d ::\n",lsassPid);
VirtualFree(buffer, 0, MEM_RELEASE);
return lsassPid;
}
}
VirtualFree(buffer, 0, MEM_RELEASE);
return 1;
}
BOOL CALLBACK ATPMiniDumpWriteCallBack(
__in PVOID CallbackParam,
__in const PMINIDUMP_CALLBACK_INPUT CallbackInput,
__inout PMINIDUMP_CALLBACK_OUTPUT CallbackOutput
){
switch (CallbackInput->CallbackType) {
case 16:
CallbackOutput->Status = S_FALSE;
break;
}
return TRUE;
}
int main()
{
if (EnableSeDebugPriv() != 0)
return 1;
int LsassPid;
HANDLE hLsass;
HANDLE hDmpFile;
// get lsass pid
LsassPid = GetLsassyPid();
if (LsassPid == 1)
return Error("Failed to get pid of lsass");
// get handle to lsass
//hLsass = OpenProcess(PROCESS_ALL_ACCESS, FALSE, LsassPid);
hLsass = OpenProcess(PROCESS_CREATE_PROCESS | PROCESS_CREATE_THREAD | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION, FALSE, LsassPid);
if (hLsass == NULL)
return Error("Failed to get handle to lsass");
// get handle to dump file
char dmpPath[] = "C:\\users\\public\\takeADump.DMP";
hDmpFile = CreateFileA(dmpPath, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDmpFile == INVALID_HANDLE_VALUE)
return Error("failed to get handle to dmp file");
printf("::: Ready to attempt dump! :::\n");
// below is classic way
//if (MiniDumpWriteDump(hLsass, LsassPid, hDmpFile, MiniDumpWithFullMemory, NULL, NULL, NULL) == FALSE)
// return Error("Failed to dump lasss");
// printf("::: Successfully dumped! ::::\n");
// return success
HPSS hSnapshot;
PSS_CAPTURE_FLAGS snapFlags = PSS_CAPTURE_VA_CLONE
| PSS_CAPTURE_HANDLES
| PSS_CAPTURE_HANDLE_NAME_INFORMATION
| PSS_CAPTURE_HANDLE_BASIC_INFORMATION
| PSS_CAPTURE_HANDLE_TYPE_SPECIFIC_INFORMATION
| PSS_CAPTURE_HANDLE_TRACE
| PSS_CAPTURE_THREADS
| PSS_CAPTURE_THREAD_CONTEXT
| PSS_CAPTURE_THREAD_CONTEXT_EXTENDED
| PSS_CREATE_BREAKAWAY_OPTIONAL
| PSS_CREATE_BREAKAWAY
| PSS_CREATE_RELEASE_SECTION
| PSS_CREATE_USE_VM_ALLOCATIONS;
DWORD hr = PssCaptureSnapshot(hLsass, snapFlags, CONTEXT_ALL, &hSnapshot);
MINIDUMP_CALLBACK_INFORMATION CallbackInfo;
ZeroMemory(&CallbackInfo, sizeof(MINIDUMP_CALLBACK_INFORMATION));
CallbackInfo.CallbackRoutine = ATPMiniDumpWriteCallBack;
CallbackInfo.CallbackParam = NULL;
BOOL yes = MiniDumpWriteDump(hSnapshot, LsassPid, hDmpFile, MiniDumpWithFullMemory, NULL, NULL, &CallbackInfo);
if (!yes)
return Error("failed to dump lsass");
printf(":::: Successfully dumped lsass ::::");
//CloseHandle(hSnapshot);
//CloseHandle(hLsass);
//CloseHandle(hDmpFile);
return 0;
}
|
e7089d66aa8361a0857f0bc255f0b06166a5eeba | 3273c7087ba6f3a805a4dfc6ba66bfea801012a3 | /src/libcore/handlerqueue.cpp | 446fb081e63dc72f599d5ecd32a452ed59e32a34 | [] | no_license | zhouxingtuan/gammaServer | e4d38cfaf8a05b0229048af7a1b4010839b2017e | 868d5c2d2cc9b65181489d42971e4a52efc1b800 | refs/heads/master | 2021-01-22T21:45:55.588529 | 2019-03-25T09:06:59 | 2019-03-25T09:06:59 | 85,474,498 | 12 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,918 | cpp | handlerqueue.cpp | //
// Created by IntelliJ IDEA.
// User: AppleTree
// Date: 16/5/30
// Time: 下午9:16
// To change this template use File | Settings | File Templates.
//
#include "handlerqueue.h"
NS_HIVE_BEGIN
static HandlerQueue* g_pHandlerQueue = NULL;
HandlerQueue::HandlerQueue() : RefObject(), Sync() {
}
HandlerQueue::~HandlerQueue(){
releaseWorker();
releaseHandler();
pthread_cond_destroy(&m_cond);
}
HandlerQueue* HandlerQueue::getInstance(void){
return g_pHandlerQueue;
}
HandlerQueue* HandlerQueue::createInstance(void){
if(g_pHandlerQueue == NULL){
g_pHandlerQueue = new HandlerQueue();
SAFE_RETAIN(g_pHandlerQueue)
}
return g_pHandlerQueue;
}
void HandlerQueue::destroyInstance(void){
if(NULL != g_pHandlerQueue){
g_pHandlerQueue->releaseWorker();
g_pHandlerQueue->releaseHandler();
}
SAFE_RELEASE(g_pHandlerQueue)
}
void HandlerQueue::releaseHandler(void){
for( auto pHandler : m_queue ){
pHandler->release();
}
m_queue.clear();
}
void HandlerQueue::releaseWorker(void){
for( auto pWorker : m_workers ){
pWorker->cancelThread();
pWorker->release();
}
m_workers.clear();
this->broadcast(); // wake up workers
}
void HandlerQueue::createWorker(int workerNumber){
if( m_workers.size() > 0 ){
return;
}
LOG_INFO("number=%d", workerNumber);
pthread_cond_init(&m_cond, NULL);
for(int i=0; i<workerNumber; ++i){
Worker* pWorker = new Worker(this);
m_workers.push_back(pWorker);
if( !pWorker->startThread() ){
LOG_ERROR("failed index=%d", i);
}else{
LOG_INFO("success index=%d", i);
}
}
}
void HandlerQueue::acceptHandler(Handler* pHandler){
pHandler->retain();
this->lock();
m_queue.push_back(pHandler);
this->signal(); // wake up workers
this->unlock();
}
Handler* HandlerQueue::nextHandler(void){
Handler* pHandler;
if( m_queue.empty() ){
return NULL;
}else{
pHandler = m_queue.front();
m_queue.pop_front();
}
return pHandler;
}
NS_HIVE_END
|
5f20376e613950b7207121b1f0e786cd81afba28 | 884ab831d68e79e7abefd50d23c0d6fa755f4ad0 | /MyLibrary/MyLibrary.h | a7b505337312c25f6617d41585c448d6306e03e0 | [] | no_license | kulikov050686/Homework_05 | af73c9fa0b17b91c1cc5b25a9daf5628c0628e21 | 0adca88c762eafb3bf22e057d6645a2a6054c942 | refs/heads/master | 2021-05-19T06:19:08.149893 | 2020-03-31T09:55:12 | 2020-03-31T09:55:12 | 251,563,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 595 | h | MyLibrary.h | #pragma once
namespace MyLibrary
{
class VinohradStrassen
{
public:
void mult_standart(double* c, double* a, double* b, int n);
void mult(double* c, double* a, double* b, int n);
private:
void copy(double* a, double* b, int ib, int jb, int n);
void copyback(double* a, int ia, int ja, double* b, int n);
void add(double* c, double* a, double* b, int n);
void sub(double* c, double* a, double* b, int n);
};
}
#ifdef __cplusplus
extern "C"
{
#endif
__declspec(dllexport) void VinohradStrassenAlgorithm(double* c, double* a, double* b, int n);
#ifdef __cplusplus
}
#endif |
caec3e92ddfd267b2732da5edc1b6e645abf2d0c | ad3e2a87c0f2c1f409edb1a6e3c06f0bc1826064 | /jjanow7Lab5/jjanow7Lab5.ino | 89a711eb3172216cca12042cd6c817517bec944c | [] | no_license | jacjanowski/Computer_Design | 4d643a139658b443fe8a5a76abe08e63b2cb0edd | 0a1be3f6e09e3016d2e636568fd2ac9c80eb1513 | refs/heads/main | 2023-01-19T19:56:48.073485 | 2020-10-27T15:54:02 | 2020-10-27T15:54:02 | 307,750,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,727 | ino | jjanow7Lab5.ino | //********************************************************************************
//Jacob Janowski - 672941241
//Lab 5 - Multiple Inputs and Outputs
//
//Description: In this lab, we are asked to produce a noise
// output utilizing our buzzer at the same time
// creating another output with 4 LEDs. Our input
// will use a photoresistor that will read in values
// and display a specific amount of lights to illuminate.
//
//Assumption: I assumed that we would somehow relate this lab with lab 1
// in that we will flash certain LEDs at a certain time. I thought
// that I would have to somehow grab my values from the light and make
// an 'if else' statement that checks how much light is being produced.
//
//References: https://www.arduino.cc/en/Reference/AnalogWrite
// https://www.arduino.cc/en/Reference/AnalogRead
//
//Youtube video link: https://youtu.be/tyrbZSo6egM
//
//**********************************************************************************
const int ledPin13 = 13;
const int ledPin11 = 11;
const int ledPin10 = 10;
const int ledPin5 = 5;
int value = 0;
const int buzzer = 12;
const int photoResistor = A0;
void setup () {
pinMode(ledPin13, OUTPUT);
pinMode(ledPin11, OUTPUT);
pinMode(ledPin10, OUTPUT);
pinMode(ledPin5, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(photoResistor, INPUT);
}
void loop() {
value = analogRead(photoResistor);
LEDsensorValues(value);
}
void LEDsensorValues(int value) {
if (value <= 205) {
digitalWrite(ledPin13, LOW);
digitalWrite(ledPin11, LOW);
digitalWrite(ledPin10, LOW);
digitalWrite(ledPin5, LOW);
}
else if (value <= 410) {
tone(buzzer, 100);
digitalWrite(ledPin13, HIGH);
digitalWrite(ledPin11, LOW);
digitalWrite(ledPin10, LOW);
digitalWrite(ledPin5, LOW);
delay(100);
noTone(buzzer);
}
else if (value <= 550) {
tone(buzzer, 200);
digitalWrite(ledPin13, HIGH);
digitalWrite(ledPin11, HIGH);
digitalWrite(ledPin10, LOW);
digitalWrite(ledPin5, LOW);
delay(100);
noTone(buzzer);
}
else if (value <= 690) {
tone(buzzer, 300);
digitalWrite(ledPin13, HIGH);
digitalWrite(ledPin11, HIGH);
digitalWrite(ledPin10, HIGH);
digitalWrite(ledPin5, LOW);
delay(100);
noTone(buzzer);
}
else if (value <= 800) {
tone(buzzer, 400);
digitalWrite(ledPin13, HIGH);
digitalWrite(ledPin11, HIGH);
digitalWrite(ledPin10, HIGH);
digitalWrite(ledPin5, HIGH);
delay(100);
noTone(buzzer);
}
}
|
316b1808dd394cf7b993363154e479e1118ba623 | 1aecc1834337ebbb69c7c97e4e12ac4f9c1f2c43 | /Cor_Engine/Sprite2DRenderer.h | 9bf502d26bca98f94ee26562930fdff565471510 | [] | no_license | EunwooSong/GP_Is_this_a_country | 374ccfb68e8b77d5d3bf7a5da22d370398914099 | 5c2c37b24e226c8749ecf37885b4a1bcb1052d81 | refs/heads/main | 2023-07-31T18:05:22.610465 | 2021-09-12T13:27:34 | 2021-09-12T13:27:34 | 348,374,590 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 979 | h | Sprite2DRenderer.h | #pragma once
#include "Component.h"
class Sprite2DRenderer
: public Component {
public:
Sprite2DRenderer() :
texture(nullptr),
color(1,1,1,1),
visibleRect(0,0,0,0),
width(0),
height(0),
isVisible(true){}
Sprite2DRenderer(const char* path);
Sprite2DRenderer(std::string path);
~Sprite2DRenderer() {}
void SetTexture(const char* path);
void Render() override;
int GetWidth() { return width; }
int GetHeight() { return height; }
Vec2 GetTextureSize() { return Vec2(width, height); }
D3DXCOLOR GetColor() { return color; }
void SetVisibleRect(Rect rect) { visibleRect = rect; }
Rect GetVisibleRect() { return visibleRect; }
void SetColor(D3DXCOLOR color) { this->color = color; }
void SetTexture(LPDIRECT3DTEXTURE9* texture);
protected:
LPDIRECT3DTEXTURE9* texture;
D3DXCOLOR color;
Rect visibleRect;
int width;
int height;
bool isVisible;
};
|
27b2f2da7284760ba1da0b49cb699db2b6a562f0 | 0a0087b9d2a1d1413f8be3f3390c288ee3018656 | /Identity/Engine/src/Physics/ICollider.cpp | 0ec5b7c28cbc94f2eb572bf1040007915027dfed | [] | no_license | GabMeloche/Identity-Engine | fcda4bbf737da7db887d166dec32778c06315a3d | b959e60ade02d94d5205c3526d6ae927a86ded74 | refs/heads/master | 2021-04-02T21:57:16.597937 | 2020-09-28T17:15:19 | 2020-09-28T17:16:46 | 248,327,267 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,654 | cpp | ICollider.cpp | #include <stdafx.h>
#include <Components/SphereCollider.h>
#include <Objects/GameObject.h>
#include <Components/Sound.h>
#include <Components/BoxCollider.h>
#include <Managers/SceneManager.h>
#include <Scene/Scene.h>
void Engine::Physics::ICollider::OnCollisionEnter()
{
if (m_gameObject->FindComponentOfType<Components::Sound>())
{
m_gameObject->FindComponentOfType<Components::Sound>()->Stop();
m_gameObject->FindComponentOfType<Components::Sound>()->PlaySound();
}
if (m_gameObject->GetName() == "Ball")
{
auto support = Managers::SceneManager::GetActiveScene()->GetGameObject("Steep1SupportRight");
if (support && m_collisionInfo->GetCollision()->GetName() == "Steep1")
support->FindComponentOfType<Components::BoxCollider>()->SetMass(10);
}
if (m_gameObject->GetName() == "Ball" && m_collisionInfo->GetCollision()->GetName() == "Steep2")
{
auto support = Managers::SceneManager::GetActiveScene()->GetGameObject("Steep2SupportLeft");
if (support)
support->FindComponentOfType<Components::BoxCollider>()->SetMass(10);
}
if (m_gameObject->GetName() == "Ball" && m_collisionInfo->GetCollision()->GetName() == "Steep3")
{
auto support = Managers::SceneManager::GetActiveScene()->GetGameObject("Steep3SupportRight");
if (support)
support->FindComponentOfType<Components::BoxCollider>()->SetMass(10);
}
if (m_gameObject->GetName() == "FlyingLink" && m_collisionInfo->GetCollision()->GetName() == "Stoper")
{
m_collisionInfo->GetCollision()->FindComponentOfType<Components::BoxCollider>()->SetMass(1);
}
std::string str(m_gameObject->GetName() + " On collision enter with " + m_collisionInfo->GetCollision()->GetName() + "\n");
//OutputDebugString(str.c_str());
}
void Engine::Physics::ICollider::OnCollisionStay()
{
std::string str(m_gameObject->GetName() + " On collision stay with " + m_collisionInfo->GetCollision()->GetName() + "\n");
//OutputDebugString(str.c_str());
}
void Engine::Physics::ICollider::OnCollisionExit()
{
if (m_gameObject->GetName() == "Ball (1)" && m_collisionInfo->GetCollision()->GetName() == "Steep (1)")
{
std::string str();
//OutputDebugString(str.c_str());
}
}
void Engine::Physics::ICollider::ActOnCollisionInfo()
{
if (m_hasCollidedThisFrame && m_hasCollidedLastFrame)
OnCollisionStay();
else if (m_hasCollidedThisFrame && !m_hasCollidedLastFrame)
OnCollisionEnter();
else if (!m_hasCollidedThisFrame && m_hasCollidedLastFrame)
{
OnCollisionExit();
m_collisionInfo = nullptr;
m_hasCollidedLastFrame = false;
m_hasCollidedThisFrame = false;
}
}
Matrix4F Engine::Physics::ICollider::GetWorldMatrix() const
{
btScalar m[16];
btTransform trans;
m_motionState->getWorldTransform(trans);
trans.getOpenGLMatrix(m);
Matrix4F mat
{
m[0], m[1], m[2], m[3],
m[4], m[5], m[6], m[7],
m[8], m[9], m[10], m[11],
m[12], m[13], m[14], m[15]
};
return mat.Transpose();
}
GPM::Vector3F Engine::Physics::ICollider::GetVelocity()
{
if (!m_rigidbody)
return GPM::Vector3F::zero;
const btVector3& vel = m_rigidbody->getLinearVelocity();
return std::move(GPM::Vector3F(vel.getX(), vel.getY(), vel.getZ()));
}
bool Engine::Physics::ICollider::IsColliding()
{
if (m_hasCollidedThisFrame && m_hasCollidedLastFrame)
return true;
return false;
}
|
1f36494d8286b9e9b9885cd19cc2af3e244594f9 | ca1303a5de37d1a1a2be1ff063362b926479ec46 | /RayTracer/Texture.cpp | 1aeeb0b222584a3005371d53a0b988e11c3e5215 | [] | no_license | AndreaCampagner/RayTracer | 556d798d08d634f683b5f298ba3b0fba363d44ba | c0add95b9be946d20dcdaa9b7e61292678aa7b92 | refs/heads/master | 2021-07-17T06:37:26.600335 | 2017-10-20T20:40:51 | 2017-10-20T20:40:51 | 105,381,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | cpp | Texture.cpp | #include "Texture.h"
#include <iostream>
const glm::dvec3 Texture::operator()(double u, double v) const
{
double w = (u * (double) width);
double h = v * (double) height;
int index = (int)h*width + w;
return image[index]*glm::dvec3(1.0/255,1.0/255,1.0/255);
}
|
1b07c9ecfd3f706661ce5b16ce36b00124b8f467 | 1fd71e5ff9a287538b73950c996cf6b3a056de62 | /yarp/src/libraries/os_services/common/YARPSyncComm.cpp | 650766592e3ffcf93e1b950e171f47eb1197260f | [] | no_license | paulfitz/poker | c34557ed163cb8242ca553e76b250dda3c65f0fb | 3e8f89c102a39b5475f1b550b1620f566ef63dba | refs/heads/master | 2020-04-19T08:48:50.388866 | 2011-09-02T16:25:32 | 2011-09-02T16:25:32 | 2,311,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,352 | cpp | YARPSyncComm.cpp | #include <stdio.h>
#include "YARPSyncComm.h"
#include "YARPNativeSyncComm.h"
#include "YARPSocketSyncComm.h"
#include "YARPNameID_defs.h"
#include "YARPNameService.h"
#include "YARPNativeNameService.h"
static void Complete(YARPNameID& dest)
{
if (dest.GetMode()==YARP_NAME_MODE_NULL)
{
dest = YARPNameService::GetRegistration();
}
if (dest.GetMode()==YARP_NAME_MODE_NULL)
{
if (YARPNativeNameService::IsNonTrivial())
{
dest = YARPNameID(YARP_NAME_MODE_NATIVE,0);
}
else
{
dest = YARPNameID(YARP_NAME_MODE_SOCKET,0);
}
}
}
int YARPSyncComm::Send(YARPNameID dest, char *buffer, int buffer_length,
char *return_buffer, int return_buffer_length)
{
Complete(dest);
if (dest.GetMode()==YARP_NAME_MODE_NATIVE)
{
return YARPNativeSyncComm::Send(dest,buffer,buffer_length,
return_buffer, return_buffer_length);
}
return YARPSocketSyncComm::Send(dest,buffer,buffer_length,
return_buffer, return_buffer_length);
}
YARPNameID YARPSyncComm::BlockingReceive(YARPNameID src, char *buffer,
int buffer_length)
{
Complete(src);
if (src.GetMode()==YARP_NAME_MODE_NATIVE)
{
return YARPNativeSyncComm::BlockingReceive(src,buffer,buffer_length);
}
return YARPSocketSyncComm::BlockingReceive(src,buffer,buffer_length);
}
YARPNameID YARPSyncComm::PollingReceive(YARPNameID src, char *buffer,
int buffer_length)
{
Complete(src);
if (src.GetMode()==YARP_NAME_MODE_NATIVE)
{
return YARPNativeSyncComm::PollingReceive(src,buffer,buffer_length);
}
return YARPSocketSyncComm::PollingReceive(src,buffer,buffer_length);
}
int YARPSyncComm::ContinuedReceive(YARPNameID src, char *buffer,
int buffer_length)
{
Complete(src);
if (src.GetMode()==YARP_NAME_MODE_NATIVE)
{
return YARPNativeSyncComm::ContinuedReceive(src,buffer,buffer_length);
}
return YARPSocketSyncComm::ContinuedReceive(src,buffer,buffer_length);
}
int YARPSyncComm::Reply(YARPNameID src, char *buffer, int buffer_length)
{
Complete(src);
if (src.GetMode()==YARP_NAME_MODE_NATIVE)
{
return YARPNativeSyncComm::Reply(src,buffer,buffer_length);
}
return YARPSocketSyncComm::Reply(src,buffer,buffer_length);
}
int YARPSyncComm::Send(YARPNameID dest, YARPMultipartMessage& msg,
YARPMultipartMessage& return_msg)
{
Complete(dest);
if (dest.GetMode()==YARP_NAME_MODE_NATIVE)
{
return YARPNativeSyncComm::Send(dest,msg,return_msg);
}
return YARPSocketSyncComm::Send(dest,msg,return_msg);
}
YARPNameID YARPSyncComm::BlockingReceive(YARPNameID src,
YARPMultipartMessage& msg)
{
Complete(src);
if (src.GetMode()==YARP_NAME_MODE_NATIVE)
{
return YARPNativeSyncComm::BlockingReceive(src,msg);
}
return YARPSocketSyncComm::BlockingReceive(src,msg);
}
YARPNameID YARPSyncComm::PollingReceive(YARPNameID src,
YARPMultipartMessage& msg)
{
Complete(src);
if (src.GetMode()==YARP_NAME_MODE_NATIVE)
{
return YARPNativeSyncComm::PollingReceive(src,msg);
}
return YARPSocketSyncComm::PollingReceive(src,msg);
}
int YARPSyncComm::Reply(YARPNameID src, YARPMultipartMessage& msg)
{
Complete(src);
if (src.GetMode()==YARP_NAME_MODE_NATIVE)
{
return YARPNativeSyncComm::Reply(src,msg);
}
return YARPSocketSyncComm::Reply(src,msg);
}
|
b40bfad544dcd8af6aa8df3aa8b791cc5e431d1d | e542300fc780b15fabeabdb5167eb828d251a05b | /10DX3D00/cSkinnedMesh.h | 9af4e6f59e0e789ba7fa9707186597e2e36a011f | [] | no_license | HongJunYeong/Orc_Must_Die | d1f6ec955e0ba15f9bf895ff2e41c1134b2b65a3 | d8b014c1e795412eab75d5264c71b9c926d41a90 | refs/heads/master | 2021-01-23T06:09:55.789360 | 2017-06-01T03:11:42 | 2017-06-01T03:11:42 | 93,011,009 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 754 | h | cSkinnedMesh.h | #pragma once
class cSkinnedMesh
{
public:
cSkinnedMesh();
~cSkinnedMesh();
protected:
LPD3DXFRAME m_pRoot;
LPD3DXANIMATIONCONTROLLER m_pAnimController;
// >>:
float m_fBlendTime;
float m_fPassedBlendTime;
bool m_isAnimBlend;
// <<:
public:
void Setup(char* szFolder, char* szFile);
void Update();
void Update(LPD3DXFRAME pFrame, LPD3DXFRAME pParent);
void Render(LPD3DXFRAME pFrame);
void SetupBoneMatrixPtrs(LPD3DXFRAME pFrame);
void UpdateSkinnedMesh(LPD3DXFRAME pFrame);
void SetAnimationIndex(int nIndex);
void SetAnimationIndexBlend(int nIndex);
/*
m_pAnimController->GetNumAnimationSets();
LPD3DXANIMATIONSET ...
m_pAnimController->GetAnimationSet(index,.....);
m_pAnimController->SetTrackAnimationSet(0,....);
*/
};
|
a80b256958d26561816304e601be6e8c549dbaf6 | ee695fb0c945f434b5dc1d409ee47ca134d3b6bc | /SCL/SCLMovableObject.h | 0bc890ab78f35be23c9dbdd00ba9322380d93173 | [] | no_license | ShenChangLing/VsSln | 1a1b4d897a6388a81daeb779945e55d82a1a391e | cf2f2bb2f07e8a0c495aca0f69e2964501f54ac5 | refs/heads/master | 2020-05-09T14:07:17.750904 | 2019-05-28T06:13:41 | 2019-05-28T06:13:41 | 181,182,163 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | h | SCLMovableObject.h | #pragma once
#include "SCLPrerequisites.h"
namespace SCL
{
//场景可移动对象
class SCL_DLL MovableObject
{
public:
MovableObject();
virtual ~MovableObject();
};
}
|
fdfc948c5d6087f4fc77225219a80abda6ee1fe0 | 0e8d57f10639b0bdcab2c89b307029697c909863 | /atcoder/agc023/A/main.cpp | e2d0aa0ec93e775cf48f37206fc52478e1f49547 | [
"Apache-2.0"
] | permissive | xirc/cp-algorithm | 07a6faf5228e07037920f5011326c16091a9157d | e83ea891e9f8994fdd6f704819c0c69f5edd699a | refs/heads/main | 2021-12-25T16:19:57.617683 | 2021-12-22T12:06:49 | 2021-12-22T12:06:49 | 226,591,291 | 15 | 1 | Apache-2.0 | 2021-12-22T12:06:50 | 2019-12-07T23:53:18 | C++ | UTF-8 | C++ | false | false | 629 | cpp | main.cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int N;
vector<int> A;
ll solve() {
vector<ll> T(N + 1, 0);
for (int i = 0; i < N; ++i) {
T[i+1] = T[i] + A[i];
}
map<ll,ll> M;
for (int i = 0; i < N + 1; ++i) {
++M[T[i]];
}
ll ans = 0;
for (auto e : M) {
auto c = e.second;
ans += c * (c - 1) / 2;
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> N;
A.assign(N, 0);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
cout << solve() << endl;
return 0;
} |
cd388da3bbe8967cfd6cf0e432dc729f0e4eec42 | 04b70278f383ff1693f49bca68164a6532110761 | /game.h | 9149503f9ffd6ea59f5bb20e37ce4e3219132f2b | [] | no_license | AlexWillisson/h4ck4th0n | 9474599241e1e165733dd874adef5796602964ef | 71233b0bda7976173be1cb98ac08d5d63beb4d3d | refs/heads/master | 2021-01-17T06:15:59.304267 | 2012-03-29T23:11:16 | 2012-03-29T23:11:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | h | game.h | #ifndef GAME_H
#define GAME_H
#include "socket.h"
#include "server.h"
#include "hack.h"
class Player {
public:
Client cl;
int object_id;
char key_pressed;
float angle;
double time_until_spawn;
int team;
};
class Game {
private:
World world;
int team_count[2];
std::map<int, Player> players;
std::vector<std::pair<char, Vector2D> > sounds;
SocketConnection *sc;
public:
Game();
bool add_player(Client cl);
void remove_player(int id);
void send_world();
void send_sounds_to(SocketConnection* c);
void process_packet(int id, ReadPacket *rp);
void update(float dt);
};
#endif
|
4d426355e7dd9b03c90833edcacf43b19a36a5cd | ed1b1e2f35e18569aa19b63568431c65493b4fbe | /archsim/src/abi/devices/virtio/VirtIO.cpp | 14dbed86afa03ae8d85f311d553dc1ea7227215c | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | yczheng-hit/gensim | cd215c6efc6357f1e375a90d7bda003e8288ed55 | 1c2c608d97ef8a90253b6f0567b43724ba553c6b | refs/heads/master | 2022-12-31T21:00:50.851259 | 2020-10-16T11:52:19 | 2020-10-16T11:52:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,497 | cpp | VirtIO.cpp | /* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */
#include "abi/devices/virtio/VirtIO.h"
#include "abi/devices/virtio/VirtQueue.h"
#include "abi/devices/IRQController.h"
#include "abi/EmulationModel.h"
#include "abi/memory/MemoryModel.h"
#include "util/LogContext.h"
#include <string.h>
UseLogContext(LogDevice);
DeclareChildLogContext(LogVirtIO, LogDevice, "VirtIO");
using namespace archsim::abi::devices::virtio;
using archsim::Address;
#define VIRTIO_CHAR_SHIFT(c, s) (((uint32_t)((uint8_t)c)) << (s))
#define VIRTIO_MAGIC (VIRTIO_CHAR_SHIFT('v', 0) | VIRTIO_CHAR_SHIFT('i', 8) | VIRTIO_CHAR_SHIFT('r', 16) | VIRTIO_CHAR_SHIFT('t', 24))
VirtIO::VirtIO(EmulationModel& parent_model, IRQLine& irq, Address base_address, uint32_t size, std::string name, uint32_t version, uint32_t device_id, uint8_t nr_queues)
: RegisterBackedMemoryComponent(parent_model, base_address, size, name),
irq(irq),
MagicValue("magic", 0x00, 32, VIRTIO_MAGIC),
Version("version", 0x04, 32, version),
DeviceID("device-id", 0x08, 32, device_id),
VendorID("vendor-id", 0x0c, 32, 0x554d4551),
HostFeatures("host-features", 0x10, 32, 0, true, false),
HostFeaturesSel("host-features-sel", 0x14, 32, 0, false, true),
GuestFeatures("guest-features", 0x20, 32, 0, false, true),
GuestFeaturesSel("guest-features-sel", 0x24, 32, 0, false, true),
GuestPageSize("guest-page-size", 0x28, 32, 0, false, true),
QueueSel("queue-sel", 0x30, 32, 0, false, true),
QueueNumMax("queue-num-max", 0x34, 32, 0, true, false),
QueueNum("queue-num", 0x38, 32, 0, false, true),
QueueAlign("queue-align", 0x3c, 32, 0, false, true),
QueuePFN("queue-pfn", 0x40, 32, 0),
QueueNotify("queue-notify", 0x50, 32, 0, false, true),
InterruptStatus("interrupt-status", 0x60, 32, 0, true, false),
InterruptACK("interrupt-ack", 0x64, 32, 0, false, true),
Status("status", 0x70, 32, 0)
{
AddRegister(MagicValue);
AddRegister(Version);
AddRegister(DeviceID);
AddRegister(VendorID);
AddRegister(HostFeatures);
AddRegister(HostFeaturesSel);
AddRegister(GuestFeatures);
AddRegister(GuestFeaturesSel);
AddRegister(GuestPageSize);
AddRegister(QueueSel);
AddRegister(QueueNumMax);
AddRegister(QueueNum);
AddRegister(QueueAlign);
AddRegister(QueuePFN);
AddRegister(QueueNotify);
AddRegister(InterruptStatus);
AddRegister(InterruptACK);
AddRegister(Status);
for (uint8_t i = 0; i < nr_queues; i++)
queues.push_back(new VirtQueue(i));
}
bool VirtIO::Initialise()
{
return true;
}
VirtIO::~VirtIO()
{
for (auto queue : queues) {
delete queue;
}
}
bool VirtIO::Read(uint32_t offset, uint8_t size, uint64_t& data)
{
LC_DEBUG3(LogVirtIO) << "[" << GetName() << "] Register Read offset=" << std::hex << offset << ", size=" << std::dec << (uint32_t)size;
if (offset >= 0x100 && offset <= (0x100 + GetConfigAreaSize())) {
uint32_t config_area_offset = offset - 0x100;
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Device Configuration Space Read offset=" << std::hex << config_area_offset << ", size=" << std::dec << (uint32_t)size;
if (size > (GetConfigAreaSize() - config_area_offset))
return false;
uint8_t *ca = GetConfigArea();
data = 0;
memcpy((void *)&data, ca + config_area_offset, size);
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Config Data: " << std::hex << data;
return true;
} else {
return RegisterBackedMemoryComponent::Read(offset, size, data);
}
}
uint32_t VirtIO::ReadRegister(MemoryRegister& reg)
{
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Read Register: " << reg.GetName() << " = " << std::hex << reg.Get();
if (reg == InterruptStatus) {
return irq.IsAsserted() ? 1 : 0;
} else if (reg == QueueNumMax) {
if (GetCurrentQueue()->GetPhysAddr().Get() == 0) {
return 0x400;
} else {
return 0;
}
} else if (reg == QueuePFN) {
return GetCurrentQueue()->GetPhysAddr().Get() >> guest_page_shift;
}
return RegisterBackedMemoryComponent::ReadRegister(reg);
}
void VirtIO::WriteRegister(MemoryRegister& reg, uint32_t value)
{
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Write Register: " << reg.GetName() << " = " << std::hex << value;
if (reg == Status) {
if (value == 0) {
HostFeaturesSel.Set(0);
GuestFeaturesSel.Set(0);
GuestPageSize.Set(0);
ResetDevice();
}
} else if (reg == QueuePFN) {
if (value == 0) {
HostFeaturesSel.Set(0);
GuestFeaturesSel.Set(0);
GuestPageSize.Set(0);
ResetDevice();
} else {
Address queue_phys_addr = Address(value << guest_page_shift);
VirtQueue *cq = GetCurrentQueue();
host_addr_t queue_host_addr;
if (!GetParentModel().GetMemoryModel().LockRegion(Address(queue_phys_addr), 0x2000, queue_host_addr))
assert(false);
cq->SetBaseAddress(queue_phys_addr, queue_host_addr);
}
} else if (reg == QueueAlign) {
GetCurrentQueue()->SetAlign(value);
} else if (reg == QueueNum) {
GetCurrentQueue()->SetSize(value);
} else if (reg == GuestPageSize) {
guest_page_shift = __builtin_ctz(value);
if(guest_page_shift > 31) guest_page_shift = 0;
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Setting guest page size=" << std::hex << value << ", shift=" << std::dec << (uint32_t)guest_page_shift;
} else if (reg == QueueNotify) {
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Queue Notify " << std::dec << QueueSel.Get();
ProcessQueue(GetQueue(value));
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Queue Notification Complete, ISR=" << std::hex << InterruptStatus.Get();
} else if (reg == InterruptACK) {
InterruptStatus.Set(InterruptStatus.Get() & ~value);
if (value != 0 && irq.IsAsserted()) {
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Rescinding Interrupt";
irq.Rescind();
}
}
if (InterruptStatus.Get() != 0) {
if (!irq.IsAsserted()) {
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Asserting Interrupt";
irq.Assert();
}
}
RegisterBackedMemoryComponent::WriteRegister(reg, value);
}
void VirtIO::ProcessQueue(VirtQueue *queue)
{
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Processing Queue";
uint16_t head_idx;
const VirtRing::VirtRingDesc *descr;
while ((descr = queue->PopDescriptorChainHead(head_idx)) != NULL) {
VirtIOQueueEvent *evt = new VirtIOQueueEvent (*queue, head_idx);
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Popped a descriptor chain head " << std::dec << head_idx << " " << std::hex << descr->flags;
bool have_next = false;
do {
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Processing descriptor " << descr->flags << std::hex << " " << descr->paddr << " " << descr->len;
host_addr_t descr_host_addr;
if (!GetParentModel().GetMemoryModel().LockRegion(Address(descr->paddr), descr->len, descr_host_addr))
assert(false);
if (descr->flags & 2) {
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Adding WRITE buffer @ " << descr_host_addr << ", size = " << descr->len;
evt->AddWriteBuffer(descr_host_addr, descr->len);
} else {
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Adding READ buffer @ " << descr_host_addr << ", size = " << descr->len;
evt->AddReadBuffer(descr_host_addr, descr->len);
}
have_next = (descr->flags & 1) == 1;
if (have_next) {
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Following descriptor chain to " << (uint32_t)descr->next;
descr = queue->GetDescriptor(descr->next);
}
} while (have_next);
LC_DEBUG1(LogVirtIO) << "[" << GetName() << "] Processing event";
ProcessEvent(evt);
}
}
|
3cb7714da67a89dd4f5f35df1023dbeeb2491a29 | c6efa1e74918806942f893fbcfb8a73a7dee0bf7 | /src/common/meta/Common.h | d2bf6d25a2b466c6f7e807be03c0790cba36be85 | [
"Apache-2.0"
] | permissive | panda-sheep/nebula-common | 1d9ec1e1591d52b796bc4badcaebc7e45f990ac9 | ca65cbdd7c04fa047f7a3897a3585795a74e27ae | refs/heads/master | 2023-07-11T05:33:41.739690 | 2020-09-15T14:00:20 | 2020-09-15T14:00:20 | 288,140,909 | 0 | 0 | null | 2020-08-17T09:42:06 | 2020-08-17T09:42:06 | null | UTF-8 | C++ | false | false | 1,198 | h | Common.h | /* Copyright (c) 2018 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#ifndef COMMON_META_METACOMMON_H_
#define COMMON_META_METACOMMON_H_
#include "common/base/Base.h"
#include "common/thrift/ThriftTypes.h"
#include "common/datatypes/HostAddr.h"
namespace nebula {
namespace meta {
struct PartHosts {
GraphSpaceID spaceId_;
PartitionID partId_;
std::vector<HostAddr> hosts_;
bool operator==(const PartHosts& rhs) const {
return this->spaceId_ == rhs.spaceId_ && this->partId_ == rhs.partId_ &&
this->hosts_ == rhs.hosts_;
}
bool operator!=(const PartHosts& rhs) const {
return !(*this == rhs);
}
};
using PartsMap = std::unordered_map<GraphSpaceID, std::unordered_map<PartitionID, PartHosts>>;
inline bool checkSegment(const std::string& segment) {
static const std::regex pattern("^[0-9a-zA-Z]+$");
if (!segment.empty() && std::regex_match(segment, pattern)) {
return true;
}
return false;
}
} // namespace meta
} // namespace nebula
#endif // COMMON_META_METACOMMON_H_
|
b6872b63eb83a1febd8fe76d1761126513ef711b | c264552726166f0eda755e7df921623ce2741ba4 | /tictactoe/ttt.cpp | 4b058e4580fd93ef6dac1dfd3b63eaa616bd0dc5 | [] | no_license | rithvik-yerramsetty/Tic-Tac-Toe | 20bd321e7f83df7d3e9278ffc482f573189a710c | 9714a24767907a25f4d6c2778d8319769e8eae94 | refs/heads/master | 2022-11-08T19:49:25.036125 | 2020-06-22T10:05:42 | 2020-06-22T10:05:42 | 273,833,132 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,379 | cpp | ttt.cpp | #include <stdio.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <string>
#include <algorithm>
const int SCREEN_WIDTH = 600;
const int SCREEN_HEIGHT = 600;
const int NO_RC = 3; //No of rows/columns
const int BUTTON_WIDTH = SCREEN_WIDTH / 3;
const int BUTTON_HEIGHT = SCREEN_HEIGHT / 3;
const int TOTAL_BUTTONS = 9;
enum GWinLine
{
ROW_ONE,
ROW_TWO,
ROW_THREE,
COL_ONE,
COL_TWO,
COL_THREE,
DIAG,
ANTI_DIAG,
NO_WIN
};
enum LButtonState
{
BUTTON_STATE_MOUSE_OUT = 0,
BUTTON_STATE_MOUSE_OVER_MOTION = 1,
BUTTON_STATE_MOUSE_DOWN = 2,
BUTTON_STATE_MOUSE_UP = 3,
//BUTTON_STATE_AI_SET = 4,
BUTTON_STATE_TOTAL = 4
};
class LTexture
{
public:
//Initializes variables
LTexture();
//Deallocates memory
~LTexture();
// LTexture operator=(LTexture &Texture );
//Loads image at specified path
bool loadFromFile( std::string path );
//Set blending
void setBlendMode( SDL_BlendMode blending );
//Set alpha modulation
void setAlpha( Uint8 alpha );
//Deallocates texture
void free();
//Renders texture at given point
void render( int x, int y, SDL_Rect* clip = NULL );
void render( int x1, int y1, int x2, int y2);
//Gets image dimensions
int getWidth();
int getHeight();
private:
//The actual hardware texture
SDL_Texture* mTexture;
//Image dimensions
int mWidth;
int mHeight;
};
class LButton
{
public:
static int turn;
//constructor
LButton();
//Destructor
// ~LButton();
//Set topleftposition for the button
void setPosition(int x, int y);
//Handle mouse movement
void handleEvent(SDL_Event* e);
//rendering
void render();
static void changeTurn();
bool isbuttonset();
void setbutton( LButtonState state);
void reset();
private:
//Top left position
SDL_Point mPosition;
LButtonState mCurrentState;
LTexture* mTextures[2];
int mButtonValue;
bool mButtonState;
// //Currently used global sprite
// LButtonSprite mCurrentSprite;
};
class LBoard
{
private:
int turn;
int board[NO_RC][NO_RC];
GWinLine mWinLine;
int moves;
public:
LBoard();
GWinLine checkgame(int x, int y, int turn);
int getturn();
void changeturn();
void handleEvent( SDL_Event* e);
bool isnotposs();
void render();
void playgame();
int minimax( int row, int col, bool player );
void reset();
};
int LButton::turn = 0;
bool init();
bool loadMedia();
void close();
SDL_Texture* loadTexture( std::string path);
SDL_Window* gWindow = NULL;
SDL_Renderer* gRenderer = NULL;
LTexture gGrid;
LTexture gX;
LTexture gO;
LBoard gBoard;
LButton gButtons[ TOTAL_BUTTONS ];
LTexture::LTexture()
{
//Initialize
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
LTexture::~LTexture()
{
//Deallocate
free();
}
bool LTexture::loadFromFile( std::string path )
{
//Get rid of preexisting texture
free();
//The final texture
SDL_Texture* newTexture = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
if( loadedSurface == NULL ){
printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
}
else{
//Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface );
if( newTexture == NULL )
{
printf( "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
}
else
{
//Get image dimensions
mWidth = loadedSurface->w;
mHeight = loadedSurface->h;
}
//Get rid of old loaded surface
SDL_FreeSurface( loadedSurface );
}
//Return success
mTexture = newTexture;
return mTexture != NULL;
}
void LTexture::setBlendMode( SDL_BlendMode blending )
{
//Set blending function
SDL_SetTextureBlendMode( mTexture, blending );
}
void LTexture::setAlpha( Uint8 alpha )
{
//Modulate texture alpha
SDL_SetTextureAlphaMod( mTexture, alpha );
}
void LTexture::free()
{
//Free texture if it exists
if( mTexture != NULL )
{
SDL_DestroyTexture( mTexture );
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
}
void LTexture::render( int x, int y, SDL_Rect* clip )
{
//Set rendering space and render to screen
SDL_Rect renderQuad = { x, y, mWidth, mHeight };
//Set clip rendering dimensions
if( clip != NULL )
{
renderQuad.w = clip->w;
renderQuad.h = clip->h;
SDL_SetRenderDrawColor( gRenderer, 0x00, 0xFF, 0x00, 0xFF );
SDL_RenderDrawRect( gRenderer, &renderQuad );
}
else{
//Render to screen
SDL_RenderCopy( gRenderer, mTexture, clip, &renderQuad );
}
}
void LTexture::render( int x1, int y1, int x2, int y2 )
{
SDL_SetRenderDrawColor( gRenderer, 0x00, 0xFF, 0xFF, 0xFF);
SDL_RenderDrawLine( gRenderer, x1, y1, x2, y2);
}
int LTexture::getWidth()
{
return mWidth;
}
int LTexture::getHeight()
{
return mHeight;
}
LButton::LButton()
{
mPosition.x = 0;
mPosition.y = 0;
mCurrentState = BUTTON_STATE_MOUSE_OUT;
mTextures[ 0 ] = &gX;
mTextures[ 1 ] = &gO;
mButtonState = false;
}
void LButton::reset()
{
mCurrentState = BUTTON_STATE_MOUSE_OUT;
mButtonState = false;
}
void LButton::setPosition(int x, int y){
mPosition.x = x;
mPosition.y = y;
}
void LButton::handleEvent(SDL_Event* e){
if( e->type == SDL_MOUSEMOTION || e->type == SDL_MOUSEBUTTONDOWN || e->type == SDL_MOUSEBUTTONUP )
{
//Get mouse position
int x, y;
SDL_GetMouseState( &x, &y );
//Check if mouse is in button
bool inside = true;
// printf("Pos- x- %f, y- %f", x, y);
//Mouse is left of the button
if( x < mPosition.x )
{
inside = false;
}
//Mouse is right of the button
else if( x > mPosition.x + BUTTON_WIDTH )
{
inside = false;
}
//Mouse above the button
else if( y < mPosition.y )
{
inside = false;
}
//Mouse below the button
else if( y > mPosition.y + BUTTON_HEIGHT )
{
inside = false;
}
if( !inside && mCurrentState != BUTTON_STATE_MOUSE_UP ){
mCurrentState = BUTTON_STATE_MOUSE_OUT;
}
else if( mCurrentState != BUTTON_STATE_MOUSE_UP ){
switch(e->type){
case SDL_MOUSEMOTION:
mCurrentState = BUTTON_STATE_MOUSE_OVER_MOTION;
break;
case SDL_MOUSEBUTTONDOWN:
mCurrentState = BUTTON_STATE_MOUSE_DOWN;
mButtonValue = turn;
break;
case SDL_MOUSEBUTTONUP:
// mCurrentState = BUTTON_STATE_MOUSE_UP;
// mButtonValue = turn;
// printf("ButtonPosition- x- %d, y- %d", mPosition.x, mPosition.y );
// mButtonState = true;
// LButton::changeTurn();
setbutton( BUTTON_STATE_MOUSE_UP );
break;
}
}
}
}
void LButton::setbutton( LButtonState state )
{
mCurrentState = state;
mButtonValue = turn;
mButtonState = true;
LButton::changeTurn();
}
void LButton::render()
{
//Show current button sprite
SDL_Rect outlineRect = { mPosition.x, mPosition.y, SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3 };
//Uint8 a = 255;
switch( mCurrentState ){
case BUTTON_STATE_MOUSE_OVER_MOTION:
gGrid.render( mPosition.x, mPosition.y, &outlineRect );
break;
case BUTTON_STATE_MOUSE_DOWN:
//a -= 64;
//gX.setAlpha(a);
mTextures[ mButtonValue ]->render(mPosition.x, mPosition.y );
// gX.render( mPosition.x, mPosition.y, &outlineRect );
break;
case BUTTON_STATE_MOUSE_UP:
mTextures[ mButtonValue ]->render(mPosition.x, mPosition.y );
mTextures[ mButtonValue ]->render( mPosition.x, mPosition.y, &outlineRect );
break;
// case BUTTON_STATE_AI_SET:
// mTextures[ mButtonValue ]->render(mPosition.x, mPosition.y );
// mTextures[ mButtonValue ]->render( mPosition.x, mPosition.y, &outlineRect );
// break;
default:
break;
}
}
void LButton::changeTurn()
{
LButton::turn = (LButton::turn == 0) ? 1 : 0;
}
bool LButton::isbuttonset()
{
return (mButtonState);
}
LBoard::LBoard()
{
moves = 0;
turn = 0;
mWinLine = NO_WIN;
for (int i = 0; i < NO_RC; i++)
{
for (int j = 0; j < NO_RC; j++)
{
/* code */
board[i][j] = -1;
}
}
}
void LBoard::reset()
{
moves = 0;
turn = 0;
mWinLine = NO_WIN;
for (int i = 0; i < NO_RC; i++)
{
for (int j = 0; j < NO_RC; j++)
{
/* code */
board[i][j] = -1;
}
}
}
GWinLine LBoard::checkgame(int x, int y, int turn)
{
board[ x ][ y ] = turn;
//check row
for (int i = 0; i < NO_RC; i++)
{
/* code */
if(board[x][i] != turn)
break;
if(i == NO_RC - 1)
{
if( x == 0)
return COL_ONE;
else if( x == 1)
return COL_TWO;
else
return COL_THREE;
}
}
//check column
for (int i = 0; i < NO_RC; i++)
{
/* code */
if(board[i][y] != turn)
break;
if(i == NO_RC - 1)
{
if( y == 0)
return ROW_ONE;
else if( y == 1)
return ROW_TWO;
else
return ROW_THREE;
}
}
if(x == y)
{
for (int i = 0; i < NO_RC; i++)
{
/* code */
if(board[i][i] != turn)
break;
if(i == NO_RC - 1)
return DIAG;
}
}
if( x+y == NO_RC - 1 )
{
for (int i = 0; i < NO_RC; i++)
{
/* code */
if(board[ NO_RC - i - 1 ][ i ] != turn)
break;
if(i == NO_RC - 1)
return ANTI_DIAG;
}
}
return NO_WIN;
}
int LBoard::getturn()
{
return turn;
}
void LBoard::changeturn()
{
turn = (turn==0) ? 1 : 0;
}
bool LBoard::isnotposs()
{
if( mWinLine != NO_WIN || moves == 9 )
return true;
return false;
}
void LBoard::render(){
int x1, y1, x2, y2;
switch (mWinLine)
{
case ROW_ONE:
x1 = 0;
y1 = 0 + SCREEN_WIDTH / 6;
x2 = SCREEN_HEIGHT;
y2 = 0 + SCREEN_WIDTH / 6;
break;
case ROW_TWO:
x1 = 0;
y1 = SCREEN_WIDTH / 3 + SCREEN_WIDTH / 6;
x2 = SCREEN_HEIGHT;
y2 = SCREEN_WIDTH / 3 + SCREEN_WIDTH / 6;
break;
case ROW_THREE:
x1 = 0;
y1 = SCREEN_WIDTH * 2 / 3 + SCREEN_WIDTH / 6;
x2 = SCREEN_HEIGHT;
y2 = SCREEN_WIDTH * 2 / 3 + SCREEN_WIDTH / 6;
break;
case COL_ONE:
x1 = 0 + SCREEN_HEIGHT / 6;
y1 = 0;
x2 = 0 + SCREEN_HEIGHT / 6;
y2 = SCREEN_WIDTH;
break;
case COL_TWO:
x1 = SCREEN_HEIGHT / 3 + SCREEN_HEIGHT / 6;
y1 = 0;
x2 = SCREEN_HEIGHT / 3 + SCREEN_HEIGHT / 6;
y2 = SCREEN_WIDTH;
break;
case COL_THREE:
x1 = SCREEN_HEIGHT * 2 / 3 + SCREEN_HEIGHT / 6;
y1 = 0;
x2 = SCREEN_HEIGHT * 2 / 3 + SCREEN_HEIGHT / 6;
y2 = SCREEN_WIDTH;
break;
case DIAG:
x1 = 0;
y1 = 0;
x2 = SCREEN_HEIGHT;
y2 = SCREEN_WIDTH;
break;
case ANTI_DIAG:
x1 = 0;
y1 = SCREEN_WIDTH;
x2 = SCREEN_HEIGHT;
y2 = 0;
break;
default:
return;
break;
}
gGrid.render( x1, y1, x2, y2);
}
void LBoard::handleEvent( SDL_Event* e)
{
if( e->type == SDL_MOUSEBUTTONUP )
{
//Get mouse position
int x, y;
SDL_GetMouseState( &x, &y );
if(x < SCREEN_HEIGHT / 3)
x = 0;
else if ( x < SCREEN_HEIGHT * 2 / 3 )
x = 1;
else
x = 2;
if(y < SCREEN_WIDTH / 3)
y = 0;
else if(y < SCREEN_WIDTH *2 / 3)
y = 1;
else
y = 2;
if( !gButtons[ (y * 3) + x ].isbuttonset() )
{
// printf("x- %d, y- %d \n", x, y);
moves++;
mWinLine = checkgame( x, y, turn);
// printf("mWinLine- %d \n", mWinLine);
changeturn();
}
}
}
int LBoard::minimax( int row, int col, bool player )
{
if( checkgame( row, col, player ) != NO_WIN )
{
board[ row ][ col ] = -1;
if( !player )
return -1;
else
return 1;
}
int ret = 0;
int flag = 1;
// printf(" board- %d\n", board[row][col]);
for( int curr_row = 0; curr_row < NO_RC; curr_row++)
{
for( int curr_col = 0; curr_col < NO_RC; curr_col++)
{
if( board[ curr_row ][ curr_col ] == -1 )
{
int minimaxval = minimax( curr_row, curr_col, !player );
if( !player )
{
if(flag)
{
ret = minimaxval;
flag = 0;
}
else
ret = std::max( ret, minimaxval );
}
else
{
if(flag)
{
ret = minimaxval;
flag = 0;
}
else
ret = std::min( ret, minimaxval );
}
// if(row == 0 && col == 0 )
// printf("ret- %d\n", ret);
}
}
}
board[ row ][ col ] = -1;
return ret;
}
void LBoard::playgame()
{
bool player = true;
int mvalue = -2 ;
int row = -1, col = -1;
for( int curr_row = 0; curr_row < NO_RC; curr_row++)
{
for( int curr_col = 0; curr_col < NO_RC; curr_col++)
{
if( board[ curr_row ][ curr_col ] == -1 )
{
int curr_val = minimax( curr_row, curr_col, player );
// printf("i- %d j- %d, curr_val- %d\n", curr_row, curr_col, curr_val);
if( curr_val > mvalue )
{
mvalue = curr_val;
row = curr_row;
col = curr_col;
}
}
}
}
if( row != -1)
{
moves++;
mWinLine = checkgame( row, col, player );
gButtons[ col*3 + row ].setbutton( BUTTON_STATE_MOUSE_UP );
changeturn();
}
}
bool init()
{
bool success = true;
if(SDL_Init(SDL_INIT_VIDEO) < 0){
printf("Unable to initialize SDL, Error- %s\n", SDL_GetError());
success = false;
}
else{
gWindow = SDL_CreateWindow("Tic-Tac-Toe", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (gWindow == NULL){
printf("Unable to create window. Error- %s\n", SDL_GetError());
success = false;
}
else{
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
if( gRenderer == NULL ){
printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else{
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) ){
printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
success = false;
}
}
}
}
return success;
}
bool loadMedia()
{
bool success = true;
if( !gGrid.loadFromFile( "grid.png" ) ){
printf( "Failed to load sprite sheet texture!\n" );
success = false;
}
if( !gX.loadFromFile( "x.png" ) ){
printf( "Failed to load sprite sheet texture!\n" );
success = false;
}
if( !gO.loadFromFile( "o.png" ) ){
printf( "Failed to load sprite sheet texture!\n" );
success = false;
}
if( success ){
gButtons[ 0 ].setPosition( 0, 0 );
gButtons[ 1 ].setPosition( SCREEN_WIDTH / 3 , 0);
gButtons[ 2 ].setPosition( SCREEN_WIDTH * 2 / 3, 0 );
gButtons[ 3 ].setPosition( 0, SCREEN_HEIGHT / 3);
gButtons[ 4 ].setPosition( SCREEN_HEIGHT / 3, SCREEN_WIDTH / 3 );
gButtons[ 5 ].setPosition( SCREEN_WIDTH * 2 / 3, SCREEN_HEIGHT / 3 );
gButtons[ 6 ].setPosition( 0, SCREEN_HEIGHT * 2 / 3 );
gButtons[ 7 ].setPosition( SCREEN_WIDTH / 3, SCREEN_HEIGHT * 2 / 3 );
gButtons[ 8 ].setPosition( SCREEN_HEIGHT * 2 / 3, SCREEN_WIDTH * 2 / 3 );
}
return success;
}
void close()
{
//Destroy window
SDL_DestroyRenderer( gRenderer );
SDL_DestroyWindow( gWindow );
gWindow = NULL;
gRenderer = NULL;
//Quit SDL subsystems
IMG_Quit();
SDL_Quit();
}
void reset()
{
gBoard.reset();
for( int i = 0; i < TOTAL_BUTTONS; ++i )
{
gButtons[ i ].reset();
}
LButton::turn = 0;
}
int main(int argc, char* args[])
{
if(!init()){
printf("Failed to initialize SDL!\n");
}
else{
if(!loadMedia()){
printf("Failed to load media!\n");
}
else{
bool quit = false;
SDL_Event e;
while(!quit){
if( gBoard.getturn() )
{
gBoard.playgame();
}
else
{
while(SDL_PollEvent(&e) != 0)
{
if(e.type == SDL_QUIT )
{
quit = true;
}
const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL );
if( ( currentKeyStates[ SDL_SCANCODE_RCTRL ] || currentKeyStates[ SDL_SCANCODE_LCTRL ] ) && currentKeyStates[ SDL_SCANCODE_R ] )
{
reset();
}
//Handle button events
gBoard.handleEvent( &e );
for( int i = 0; i < TOTAL_BUTTONS; ++i )
{
gButtons[ i ].handleEvent( &e );
}
}
}
//SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
SDL_RenderClear( gRenderer );
gGrid.render(0, 0);
//Render buttons
for( int i = 0; i < TOTAL_BUTTONS; ++i )
{
gButtons[ i ].render();
}
gBoard.render();
SDL_RenderPresent( gRenderer );
// while(gBoard.iswin());
if(gBoard.isnotposs())
{
// printf("Enter\n");
while( !quit )
{
while(SDL_PollEvent(&e) != 0)
{
if(e.type == SDL_QUIT )
quit = true;
const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL );
if( ( currentKeyStates[ SDL_SCANCODE_RCTRL ] || currentKeyStates[ SDL_SCANCODE_LCTRL ] ) && currentKeyStates[ SDL_SCANCODE_R ] )
{
reset();
break;
}
}
quit = true;
}
quit = false;
}
}
}
}
close();
return 0;
} |
f92265232c7d8902915154390445373e0c09b5ef | 1c5616c56c92d54388431b0894ea02458e564774 | /general/main.cpp | 6111245c02732469b8cb1d185661204ac849df96 | [] | no_license | bolt25/Codding | 93e021d4efe4e3a2bee056f8de9799845395168c | f32c9358bd02add1fc5f3bd1cf6abcac4cddd93d | refs/heads/master | 2020-08-23T12:21:13.074450 | 2019-10-21T16:33:29 | 2019-10-21T16:33:29 | 216,615,386 | 0 | 0 | null | 2019-10-21T16:32:08 | 2019-10-21T16:32:07 | null | UTF-8 | C++ | false | false | 111 | cpp | main.cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
cout<<-617613447 -25;
cout<<"\n"<<INT_MIN;
}
|
4670fa2d43b0ba6a62986686e5f8dfd0ff375460 | 2af239d2aa1c1ac854751ca5a132a53831cfac5d | /a_star_algorithm.cpp | 490b1cbd87024ef6084dd7e2485c9c33fa7d43dd | [] | no_license | NataliyaBlagonravova/a-star-algorithm | f0f9e6a74b93aa97d09d470b91930ca63fa2d24d | f4895d569e51ae799bc4db8b17100485b012d16b | refs/heads/master | 2021-01-20T21:12:17.636938 | 2016-07-26T14:04:05 | 2016-07-26T14:04:05 | 64,227,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,067 | cpp | a_star_algorithm.cpp | #include "a_star_algorithm.h"
TAStarAlgorithm::TAStarAlgorithm(TGraph *graph, uint64_t startNodeId, uint64_t finishNodeId, bool needFullOutput)
{
Graph = graph;
OpenNodes = new TOpenedNodesContainer();
ClosedNodes = new TClosedNodesContainer();
Path = new TPathContainer(Graph->GetNodeCount(), startNodeId, finishNodeId);
StartNodeId = startNodeId;
FinishNodeId = finishNodeId;
NeedFullOutput = needFullOutput;
SeenNodesCount = 0;
Calculate();
}
double TAStarAlgorithm::HeuristicCostEstimate(const TNode start, const TNode finish)
{
return CalculateDistance(start.Coordinates, finish.Coordinates);
}
void TAStarAlgorithm::Calculate()
{
OpenNodes->AddNode(StartNodeId, 0, HeuristicCostEstimate(
Graph->GetNode(StartNodeId),
Graph->GetNode(FinishNodeId)));
while (!OpenNodes->IsEmpty()) {
OpenNodes->FindNextBestNode();
uint64_t nodeId = OpenNodes->GetBestNodeId();
double pathLengthFromStart = OpenNodes->GetBestNodePathLengthFromStart();
++SeenNodesCount;
if (nodeId == FinishNodeId) {
Path->PathWasFound(pathLengthFromStart);
if (NeedFullOutput) {
Path->ReconstructPath();
}
return;
}
ClosedNodes->AddNode(nodeId);
for (TNeighbor neighbor : Graph->GetNode(nodeId).Neighbors) {
if (ClosedNodes->Contains(neighbor.Id)) {
continue;
}
double pathLengthFromStartThroughNode =
pathLengthFromStart +
neighbor.Distance;
if (!OpenNodes->Contains(neighbor.Id)) {
OpenNodes->AddNode(neighbor.Id, pathLengthFromStartThroughNode,
HeuristicCostEstimate(
Graph->GetNode(neighbor.Id),
Graph->GetNode(FinishNodeId)));
Path->SetNodeParent(neighbor.Id, nodeId);
} else {
if (pathLengthFromStartThroughNode < OpenNodes->GetPathLengthFromStart(neighbor.Id)) {
OpenNodes->AddNode(neighbor.Id, pathLengthFromStartThroughNode,
HeuristicCostEstimate(
Graph->GetNode(neighbor.Id),
Graph->GetNode(FinishNodeId)));
Path->SetNodeParent(neighbor.Id, nodeId);
}
}
}
}
}
double TAStarAlgorithm::GetPathLength()
{
return Path->GetLength();
}
bool TAStarAlgorithm::HasPath()
{
return Path->HasPathFromStartToFinish();
}
vector<uint64_t> &TAStarAlgorithm::GetPath()
{
return Path->GetPath();
}
uint64_t TAStarAlgorithm::GetPathNodeCount()
{
return Path->GetNodeCount();
}
TAStarAlgorithm::~TAStarAlgorithm()
{
delete OpenNodes;
delete ClosedNodes;
delete Path;
}
uint64_t TAStarAlgorithm::GetSeenNodesCount()
{
return SeenNodesCount;
}
|
4325af2b23b9c418585473a2fd929631f9291b53 | 30ccce5d98cef812062f91edb43701a614258ca6 | /Program/GprsController.ino | c2a7b0d6b539192eefc3dc1d98c1f39812e5c8a8 | [] | no_license | manunapo/security-system | 29c04656017834fb0e2feee115195bd1a695547a | 8c27e29802c25634dd04a4475cdcb58a1fe320a6 | refs/heads/master | 2021-01-21T13:44:04.758682 | 2016-05-29T15:41:57 | 2016-05-29T15:41:57 | 55,920,042 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,856 | ino | GprsController.ino | #include <SoftwareSerial.h>
//TX,RX
SoftwareSerial SIM900(7, 8);
int pinLedSignal_1 = 11;
int pinLedSignal_2 = 12;
String outMessage = "Se activo la alarma";
String destinationNumber = "298315550485";
void setUpGprs(){
SIM900.begin(19200);
pinMode(pinLedSignal_1, OUTPUT);
pinMode(pinLedSignal_2, OUTPUT);
SIM900.print("AT+CMGF=1\r");
delay(1000);
SIM900.print("AT+CNMI=1,2,0,0,0\r");
delay(1000);
}
void sendMessage(){
SIM900.print("AT+CMGF=1\r");
delay(1000);
SIM900.println("AT + CMGS = \"" + destinationNumber +"\"");
delay(1000);
SIM900.print(outMessage);
delay(1000);
SIM900.write((char)26); //ctrl+z
delay(1000);
}
void makeCall(){
SIM900.println("ATD" + destinationNumber + ";");
delay(1000);
}
void hangUp(){
SIM900.println("ATH");
delay(1000);
}
void checkSMS(){
char incomingChars;
int counter = 0;
String msgBody = "";
if(SIM900.available() >0){
while(SIM900.available() >0){
incomingChars = SIM900.read(); //Get the character from the cellular serial port.
if(counter == 6){
if(incomingChars != '\n' && incomingChars != '\r'){
msgBody += incomingChars;
}
}
if( incomingChars == '"'){
counter++;
}
Serial.print(incomingChars); //Print the incoming character to the terminal.
}
msgBody.toLowerCase();
boolean activate = msgBody.equals("activar");
boolean desactivate = msgBody.equals("desactivar");
if(activate){
stateActivate();
Serial.print("Llego activacion: ");Serial.println(msgBody);
}
if(desactivate){
stateDesactivate();
Serial.print("Llego desactivacion: ");Serial.println(msgBody);
}
}
}
void checkSignal(){
SIM900.print("AT+CSQ\r");
delay(100);
char incomingChars;
boolean found = false;
int signalInt = 0;
while(SIM900.available() > 0){
incomingChars = SIM900.read();
//Serial.print(incomingChars);
if(incomingChars == ','){
found = false;
}
if(found){
if(incomingChars == '0' ||
incomingChars == '1' ||
incomingChars == '2' ||
incomingChars == '3' ||
incomingChars == '4' ||
incomingChars == '5' ||
incomingChars == '6' ||
incomingChars == '7' ||
incomingChars == '8' ||
incomingChars == '9')
signalInt = signalInt * 10 + (incomingChars - '0');
}
if(incomingChars == ':'){
found = true;
}
}
Serial.print("Signal: ");Serial.println(signalInt);
if( signalInt > 2 && signalInt < 10){
digitalWrite(pinLedSignal_1, HIGH);
digitalWrite(pinLedSignal_2, LOW);
}else if(signalInt >= 10){
digitalWrite(pinLedSignal_1, HIGH);
digitalWrite(pinLedSignal_2, HIGH);
}else{
digitalWrite(pinLedSignal_1, LOW);
digitalWrite(pinLedSignal_2, LOW);
}
}
|
8d182070b0bcb2c21bc057cffa77c33b0b0a54e2 | ca4bfcaa8aafaacc33444d0e293fc68d1a025e04 | /src/dnnl_ops/Transpose.cpp | b43c03b98eea20138ea8ea754f1ffecacb3b8326 | [
"Apache-2.0"
] | permissive | codecaution/TSplit | 232d41b92dcb885ae140ce556a0123932af639c6 | 8f86f987163aa06521bfeeb174616eb4a0a81b47 | refs/heads/main | 2023-05-03T09:53:10.605881 | 2021-05-01T17:02:16 | 2021-05-01T17:02:16 | 363,457,345 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 618 | cpp | Transpose.cpp | #include <cctype>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <random>
#include <stdexcept>
#include <vector>
#include <type_traits>
#include <omp.h>
#include "dnnl.hpp"
#include "../common/c_runtime_api.h"
#include "dnnl_runtime.h"
extern "C" int cpu_Transpose(const DLArrayHandle in_arr, DLArrayHandle out_arr) {
float* input = (float*)(in_arr->data);
float* output = (float*)(out_arr->data);
int row = in_arr->shape[0];
int col = in_arr->shape[1];
int ind = 0;
#pragma omp parallel for
for (int i = 0; i < col * row; i++)
output[i] = input[ (i/row) + col * (i%row) ];
return 0;
} |
822976c1d37f36b1119bf986992092a36423a018 | d0276045ff88c6ad4969aa4deb929d1e2ed9efb7 | /Important DS Algo/Graph/Dijkstra.cpp | 8918d889ac15a527fe05316dc5242c98da1eaf3b | [] | no_license | rishabhtyagi2306/Competitive-Programming | 2f4d6e34701d3012832e908341606fa0501173a4 | 269d42a89940eefa73c922b6f275596fe68add6a | refs/heads/master | 2023-07-12T18:05:17.366652 | 2021-08-29T18:30:09 | 2021-08-29T18:30:09 | 256,992,147 | 3 | 3 | null | 2020-10-02T05:43:31 | 2020-04-19T12:20:46 | C++ | UTF-8 | C++ | false | false | 2,334 | cpp | Dijkstra.cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define vii vector<int>
#define vll vector<ll>
#define mii map<int, int>
#define mll map<ll, ll>
#define sii set<int>
#define sll set<ll>
#define umi unordered_map<int, int>
#define uml unordered_map<ll, ll>
#define usi unordered_set<int>
#define usl unordered_set<ll>
#define pii pair<int, int>
#define pll pair<ll, ll>
#define pb push_back
#define pf push_front
#define mk make_pair
#define endl "\n"
#define desc greater<int>()
#define F first
#define S second
#define mod 1000000007
#define pi 3.141592653589793238
#define lcm(a,b) (a/(__gcd(a,b)))*b
#define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout<<fixed;cout.precision(10);
using namespace std;
using namespace __gnu_pbds;
/*------------------------------------------Code Starts From Here------------------------------------------*/
int main() {
FASTIO
int T = 1;
// cin>>T;
while(T--)
{
int n, m, i, j;
cin>>n>>m;
vector<pii> adj[n+1];
int inf = INT_MAX;
for(i = 0; i < m; i++)
{
int u, v, w;
cin>>u>>v>>w;
adj[u].pb(mk(v, w));
adj[v].pb(mk(u, w));
}
int dist[n+1];
for(i = 0; i <= n; i++)
{
dist[i] = inf;
}
bool vis[n+1] = {false};
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push({0, 1});
dist[1] = 0;
int path[n+1];
memset(path, -1, sizeof(path));
while(!pq.empty())
{
int u = pq.top().S;
pq.pop();
vis[u] = true;
if(u == n)
break;
for(auto &j : adj[u])
{
int v = j.F;
int w = j.S;
if(!vis[v] && dist[v] > dist[u] + w)
{
dist[v] = dist[u] + w;
path[v] = u;
pq.push({dist[v], v});
}
}
}
if(vis[n])
{
int start = n;
vii ans;
ans.pb(start);
while(start != -1)
{
ans.pb(path[start]);
start = path[start];
}
reverse(ans.begin(), ans.end());
for(i = 1; i < ans.size(); i++)
{
cout<<ans[i]<<" ";
}
cout<<endl;
}
else
{
cout<<-1<<endl;
}
}
return 0;
} |
82c82dc7787369fa06ebde518b5e2822139116b0 | cc13bdb0f445b8acf6bec24946fcfb5e854989b6 | /Pods/Realm/include/core/realm/util/platform_info.hpp | 16ae43a4b71650e37f8a5cefde6f80b3f0ed7bd5 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-generic-export-compliance",
"LicenseRef-scancode-realm-platform-extension-2017"
] | permissive | devMEremenko/XcodeBenchmark | 59eaf0f7d6cdaead6338511431489d9d2bf0bbb5 | 3aaaa6aa4400a20513dd4b6fdb372c48b8c9e772 | refs/heads/master | 2023-09-04T08:37:51.014081 | 2023-07-25T23:37:37 | 2023-07-25T23:37:37 | 288,524,849 | 2,335 | 346 | MIT | 2023-09-08T16:52:16 | 2020-08-18T17:47:47 | Swift | UTF-8 | C++ | false | false | 1,933 | hpp | platform_info.hpp | /*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_UTIL_PLATFORM_INFO_HPP
#define REALM_UTIL_PLATFORM_INFO_HPP
#include <string>
namespace realm {
namespace util {
/// Get a description of the current system platform.
///
/// Returns a space-separated concatenation of `osname`, `sysname`, `release`,
/// `version`, and `machine` as returned by get_platform_info(PlatformInfo&).
std::string get_platform_info();
struct PlatformInfo {
std::string osname; ///< Equivalent to `uname -o` (Linux).
std::string sysname; ///< Equivalent to `uname -s`.
std::string release; ///< Equivalent to `uname -r`.
std::string version; ///< Equivalent to `uname -v`.
std::string machine; ///< Equivalent to `uname -m`.
};
/// Get a description of the current system platform.
void get_platform_info(PlatformInfo&);
// Implementation
inline std::string get_platform_info()
{
PlatformInfo info;
get_platform_info(info); // Throws
return (info.osname + " " + info.sysname + " " + info.release + " " + info.version + " " +
info.machine); // Throws
}
} // namespace util
} // namespace realm
#endif // REALM_UTIL_PLATFORM_INFO_HPP
|
df796716b42d543f656548c349ec3a92808550a1 | e6311cd105b74e0d3bfd67ed2a4ca0364dc238e0 | /logarea.cpp | 43391d524339fa7605c334dd80131fcc5a2db62f | [] | no_license | printesoi/IPTool | 22d33fad8c3c9cb3e5580f8616021212c5b7523f | f8122c0de1fdab560cec00d0849c07f8f2875796 | refs/heads/master | 2020-12-24T14:09:24.261328 | 2012-11-16T09:01:01 | 2012-11-16T09:01:01 | 6,413,194 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 256 | cpp | logarea.cpp | #include "logarea.h"
LogArea::LogArea(QWidget *parent) :
QTextEdit(parent)
{
setFixedHeight(60);
setReadOnly(true);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
}
void LogArea::appendMessage(const QString &msg)
{
append(msg);
}
|
5e6cef0a97de333e55b9a41f7a2a5d217a656ddd | 5664bdbfb287ef2bbb5b5c31a9d93e31acf7d5b9 | /sumaDeEnteros/sumaDeEnteros/Source.cpp | 49ef04a04d2e550c4d34b1f77fab0820a962b3f2 | [] | no_license | Paruck/programacionOrientadaAObjetos1 | b13d79b0f153e2e6c211a2f0df15141858cce34b | 6e0d042f015af003453c10ad745ae585e1e106d7 | refs/heads/master | 2021-01-19T04:24:34.593214 | 2017-12-13T22:35:40 | 2017-12-13T22:35:40 | 87,368,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | cpp | Source.cpp | #include <iostream>
#include <vector>
#include "Insert.h"
void main()
{
Insert i;
std::cout << "Escriba todos los numeros que desees que sume. \n";
std::cout << "Escribe cualquier numero negativo para mostrar el resultado. \n";
i.insertNum1();
//i.insertNum2();
std::cout << "\n";
system("PAUSE");
}
|
b3c4f4c5800bf0235535d74eb60725394afdae06 | 972662266cb2087a11e18f80523d4aea87a740e3 | /modules/VTK/include/vtkStandardImageRepresenter.hxx | 73e301308c192a3c3a5caab07edd514f91105198 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | tsuholic/statismo | 3f4cb455b4c82612e3835aeb4d200bcc4177d3ab | e9cea2877ed58752e97711caf98324c564325f98 | refs/heads/master | 2020-07-24T08:25:13.745852 | 2016-04-30T18:59:35 | 2016-04-30T18:59:35 | 73,791,891 | 1 | 0 | null | 2016-11-15T08:19:28 | 2016-11-15T08:19:28 | null | UTF-8 | C++ | false | false | 18,679 | hxx | vtkStandardImageRepresenter.hxx | /*
* This file is part of the statismo library.
*
* Author: Marcel Luethi (marcel.luethi@unibas.ch)
*
* Copyright (c) 2011 University of Basel
* 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 the project's author nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "vtkStandardImageRepresenter.h"
#include <vtkStructuredPointsReader.h>
#include <vtkStructuredPointsWriter.h>
#include <vtkPointData.h>
#include <vtkDataArray.h>
#include <vtkVersion.h>
#include <boost/filesystem.hpp>
#include "CommonTypes.h"
#include "HDF5Utils.h"
#include "StatismoUtils.h"
namespace statismo {
template<class TScalar, unsigned PixelDimensions>
vtkStandardImageRepresenter<TScalar, PixelDimensions>::vtkStandardImageRepresenter(
DatasetConstPointerType reference) :
m_reference(vtkStructuredPoints::New()) {
this->SetReference(reference);
}
template<class TScalar, unsigned PixelDimensions>
vtkStandardImageRepresenter<TScalar, PixelDimensions>::~vtkStandardImageRepresenter() {
if (m_reference != 0) {
m_reference->Delete();
m_reference = 0;
}
}
template<class TScalar, unsigned PixelDimensions>
vtkStandardImageRepresenter<TScalar, PixelDimensions>*
vtkStandardImageRepresenter<TScalar, PixelDimensions>::Clone() const {
// this works since Create deep copies the reference
return Create(m_reference);
}
template<class TScalar, unsigned PixelDimensions>
void vtkStandardImageRepresenter<TScalar, PixelDimensions>::Load(const H5::Group& fg) {
vtkStructuredPoints* ref = 0;
std::string repName = HDF5Utils::readStringAttribute(fg, "name");
if (repName == "vtkStructuredPointsRepresenter" || repName == "itkImageRepresenter" || repName == "itkVectorImageRepresenter") {
ref = LoadRefLegacy(fg);
} else {
ref = LoadRef(fg);
}
this->SetReference(ref);
}
template<class TScalar, unsigned PixelDimensions>
vtkStructuredPoints* vtkStandardImageRepresenter<TScalar, PixelDimensions>::LoadRef(const H5::Group& fg) const {
std::string type = HDF5Utils::readStringAttribute(fg, "datasetType");
if (type != "IMAGE") {
throw StatisticalModelException(
(std::string("Cannot load representer data: The ")
+ "representer specified in the given hdf5 file is of the wrong type: ("
+ type + ", expected IMAGE)").c_str());
}
statismo::VectorType originVec;
HDF5Utils::readVector(fg, "origin", originVec);
unsigned imageDimension = static_cast<unsigned>(HDF5Utils::readInt(fg,
"imageDimension"));
if (imageDimension > 3) {
throw StatisticalModelException(
"this representer does not support images of dimensionality > 3");
}
double origin[3] = { 0, 0, 0 };
for (unsigned i = 0; i < imageDimension; i++) {
origin[i] = originVec[i];
}
statismo::VectorType spacingVec;
HDF5Utils::readVector(fg, "spacing", spacingVec);
float spacing[3] = { 0, 0, 0 };
for (unsigned i = 0; i < imageDimension; i++) {
spacing[i] = spacingVec[i];
}
typename statismo::GenericEigenType<int>::VectorType sizeVec;
HDF5Utils::readVectorOfType<int>(fg, "size", sizeVec);
int size[3] = { 1, 1, 1 };
for (unsigned i = 0; i < imageDimension; i++) {
size[i] = sizeVec[i];
}
H5::Group pdGroup = fg.openGroup("./pointData");
typename statismo::GenericEigenType<double>::MatrixType pixelMat;
HDF5Utils::readMatrixOfType<double>(pdGroup, "pixelValues", pixelMat);
H5::DataSet ds = pdGroup.openDataSet("pixelValues");
unsigned int datatype = static_cast<unsigned>(HDF5Utils::readIntAttribute(
ds, "datatype"));
if (statismo::GetDataTypeId<TScalar>() != datatype) {
std::cout
<< "Warning: The datatype specified for the scalars does not match the TPixel template argument used in this representer."
<< std::endl;
}
pdGroup.close();
vtkStructuredPoints* newImage = vtkStructuredPoints::New();
newImage->SetDimensions(size[0], size[1], size[2]);
newImage->SetExtent(0, size[0] - 1, 0, size[1] - 1, 0, size[2] - 1);
newImage->SetOrigin(origin[0], origin[1], origin[2]);
newImage->SetSpacing(spacing[0], spacing[1], spacing[2]);
switch (datatype) {
case statismo::SIGNED_CHAR:
#if (VTK_MAJOR_VERSION == 5 )
newImage->SetScalarTypeToSignedChar();
newImage->SetNumberOfScalarComponents( PixelDimensions );
newImage->AllocateScalars();
#else
newImage->AllocateScalars(VTK_SIGNED_CHAR, PixelDimensions);
#endif
break;
case statismo::UNSIGNED_CHAR:
#if (VTK_MAJOR_VERSION == 5 )
newImage->SetScalarTypeToUnsignedChar();
newImage->SetNumberOfScalarComponents( PixelDimensions );
newImage->AllocateScalars();
#else
newImage->AllocateScalars(VTK_UNSIGNED_CHAR, PixelDimensions);
#endif
break;
case statismo::SIGNED_SHORT:
#if (VTK_MAJOR_VERSION == 5 )
newImage->SetScalarTypeToShort();
newImage->SetNumberOfScalarComponents( PixelDimensions );
newImage->AllocateScalars();
#else
newImage->AllocateScalars(VTK_SHORT, PixelDimensions);
#endif
break;
case statismo::UNSIGNED_SHORT:
#if (VTK_MAJOR_VERSION == 5 )
newImage->SetScalarTypeToUnsignedChar();
newImage->SetNumberOfScalarComponents( PixelDimensions );
newImage->AllocateScalars();
#else
newImage->AllocateScalars(VTK_UNSIGNED_SHORT, PixelDimensions);
#endif
break;
case statismo::SIGNED_INT:
#if (VTK_MAJOR_VERSION == 5 )
newImage->SetScalarTypeToInt();
newImage->SetNumberOfScalarComponents( PixelDimensions );
newImage->AllocateScalars();
#else
newImage->AllocateScalars(VTK_INT, PixelDimensions);
#endif
break;
case statismo::UNSIGNED_INT:
#if (VTK_MAJOR_VERSION == 5 )
newImage->SetScalarTypeToUnsignedInt();
newImage->SetNumberOfScalarComponents( PixelDimensions );
newImage->AllocateScalars();
#else
newImage->AllocateScalars(VTK_UNSIGNED_INT, PixelDimensions);
#endif
break;
case statismo::FLOAT:
#if (VTK_MAJOR_VERSION == 5 )
newImage->SetScalarTypeToFloat();
newImage->SetNumberOfScalarComponents( PixelDimensions );
newImage->AllocateScalars();
#else
newImage->AllocateScalars(VTK_FLOAT, PixelDimensions);
#endif
break;
case statismo::DOUBLE:
#if (VTK_MAJOR_VERSION == 5 )
newImage->SetScalarTypeToDouble();
newImage->SetNumberOfScalarComponents( PixelDimensions );
newImage->AllocateScalars();
#else
newImage->AllocateScalars(VTK_DOUBLE, PixelDimensions);
#endif
break;
default:
throw statismo::StatisticalModelException(
"the datatype found in the statismo model cannot be used for the vtkStandardImageRepresenter");
}
for (int i = 0; i < size[2]; i++) {
for (int j = 0; j < size[1]; j++) {
for (int k = 0; k < size[0]; k++) {
unsigned index = size[1] * size[0] * i + size[0] * j + k;
TScalar* scalarPtr =
static_cast<TScalar*>(newImage->GetScalarPointer(k, j,
i));
for (unsigned d = 0; d < PixelDimensions; d++) {
scalarPtr[d] = pixelMat(d, index);
}
}
}
}
return newImage;
}
template<class TScalar, unsigned PixelDimensions>
vtkStructuredPoints* vtkStandardImageRepresenter<TScalar, PixelDimensions>::LoadRefLegacy(const H5::Group& fg) const {
vtkStructuredPoints* ref = vtkStructuredPoints::New();
std::string tmpfilename = statismo::Utils::CreateTmpName(".vtk");
statismo::HDF5Utils::getFileFromHDF5(fg, "./reference", tmpfilename.c_str());
std::remove(tmpfilename.c_str());
vtkStructuredPointsReader* reader = vtkStructuredPointsReader::New();
reader->SetFileName(tmpfilename.c_str());
reader->Update();
boost::filesystem::remove(tmpfilename);
if (reader->GetErrorCode() != 0) {
throw StatisticalModelException((std::string("Could not read file ") + tmpfilename).c_str());
}
ref->DeepCopy(reader->GetOutput());
reader->Delete();
return ref;
}
template<class TScalar, unsigned PixelDimensions>
statismo::VectorType vtkStandardImageRepresenter<TScalar, PixelDimensions>::PointToVector(
const PointType& pt) const {
// a vtk point is always 3 dimensional
VectorType v(3);
for (unsigned i = 0; i < 3; i++) {
v(i) = pt[i];
}
return v;
}
template<class TScalar, unsigned PixelDimensions>
typename vtkStandardImageRepresenter<TScalar, PixelDimensions>::DatasetPointerType vtkStandardImageRepresenter<
TScalar, PixelDimensions>::DatasetToSample(
DatasetConstPointerType dataset) const {
// for this representer, a dataset is always the same as a sample
vtkStructuredPoints* clone = vtkStructuredPoints::New();
clone->DeepCopy(const_cast<vtkStructuredPoints*>(dataset));
if (const_cast<vtkStructuredPoints*>(m_reference)->GetNumberOfPoints()
!= const_cast<vtkStructuredPoints*>(dataset)->GetNumberOfPoints()) {
throw StatisticalModelException(
"The dataset need to have the same number of points as the reference");
}
return clone;
}
template<class TScalar, unsigned PixelDimensions>
VectorType vtkStandardImageRepresenter<TScalar, PixelDimensions>::SampleToSampleVector(
DatasetConstPointerType _sp) const {
vtkStructuredPoints* reference =
const_cast<vtkStructuredPoints*>(this->m_reference);
vtkStructuredPoints* sp = const_cast<vtkStructuredPoints*>(_sp);
if (reference->GetNumberOfPoints() != sp->GetNumberOfPoints()) {
throw StatisticalModelException(
"The sample does not have the correct number of points");
}
VectorType sample = VectorType::Zero(
m_reference->GetNumberOfPoints() * PixelDimensions);
vtkDataArray* dataArray = sp->GetPointData()->GetArray(0);
// TODO: Make this more efficient using SetVoidArray of vtk
// HOWEVER: This is only possible, if we enforce VectorType and
// vtkStructuredPoints to have the same data type, e.g. float or int.
for (unsigned i = 0; i < m_reference->GetNumberOfPoints(); i++) {
double val[PixelDimensions];
dataArray->GetTuple(i, val);
for (unsigned d = 0; d < PixelDimensions; d++) {
unsigned idx = MapPointIdToInternalIdx(i, d);
sample(idx) = val[d];
}
}
return sample;
}
template<class TScalar, unsigned PixelDimensions>
typename vtkStandardImageRepresenter<TScalar, PixelDimensions>::DatasetPointerType vtkStandardImageRepresenter<
TScalar, PixelDimensions>::SampleVectorToSample(
const VectorType& sample) const {
vtkStructuredPoints* sp = vtkStructuredPoints::New();
vtkStructuredPoints* reference =
const_cast<vtkStructuredPoints*>(m_reference);
sp->DeepCopy(reference);
vtkDataArray* dataArray = sp->GetPointData()->GetArray(0);
for (unsigned i = 0; i < GetNumberOfPoints(); i++) {
double val[PixelDimensions];
for (unsigned d = 0; d < PixelDimensions; d++) {
unsigned idx = MapPointIdToInternalIdx(i, d);
val[d] = sample(idx);
}
dataArray->SetTuple(i, val);
}
//sp->GetPointData()->SetScalars(scalars);
return sp;
}
template<class TScalar, unsigned PixelDimensions>
typename vtkStandardImageRepresenter<TScalar, PixelDimensions>::ValueType vtkStandardImageRepresenter<
TScalar, PixelDimensions>::PointSampleFromSample(
DatasetConstPointerType sample_, unsigned ptid) const {
DatasetPointerType sample = const_cast<DatasetPointerType>(sample_);
if (ptid >= sample->GetNumberOfPoints()) {
throw StatisticalModelException(
"invalid ptid provided to PointSampleFromSample");
}
double doubleVal[PixelDimensions];
sample->GetPointData()->GetScalars()->GetTuple(ptid, doubleVal);
ValueType val(PixelDimensions);
// vtk returns double. We need to convert it to whatever precision we are using in NDPixel
for (unsigned i = 0; i < PixelDimensions; i++) {
val[i] = static_cast<TScalar>(doubleVal[i]);
}
return val;
}
template<class TScalar, unsigned PixelDimensions>
statismo::VectorType vtkStandardImageRepresenter<TScalar, PixelDimensions>::PointSampleToPointSampleVector(
const ValueType& v) const {
VectorType vec(PixelDimensions);
for (unsigned i = 0; i < PixelDimensions; i++) {
vec[i] = const_cast<ValueType&>(v)[i];
vec[i] = v[i];
}
return vec;
}
template<class TScalar, unsigned PixelDimensions>
typename vtkStandardImageRepresenter<TScalar, PixelDimensions>::ValueType vtkStandardImageRepresenter<
TScalar, PixelDimensions>::PointSampleVectorToPointSample(
const VectorType& pointSample) const {
ValueType value(PixelDimensions);
for (unsigned i = 0; i < PixelDimensions; i++)
value[i] = pointSample[i];
return value;
}
template<class TScalar, unsigned Dimensions>
void vtkStandardImageRepresenter<TScalar, Dimensions>::Save(
const H5::Group& fg) const {
using namespace H5;
// get the effective image dimension, by check the size
int* size = m_reference->GetDimensions();
unsigned imageDimension = 0;
if (size[2] == 1 && size[1] == 1)
imageDimension = 1;
else if (size[2] == 1)
imageDimension = 2;
else
imageDimension = 3;
HDF5Utils::writeInt(fg, "imageDimension", imageDimension);
double* origin = m_reference->GetOrigin();
statismo::VectorType originVec = statismo::VectorType::Zero(imageDimension);
for (unsigned i = 0; i < imageDimension; i++) {
originVec(i) = origin[i];
}
HDF5Utils::writeVector(fg, "origin", originVec);
double* spacing = m_reference->GetSpacing();
statismo::VectorType spacingVec = statismo::VectorType::Zero(
imageDimension);
for (unsigned i = 0; i < imageDimension; i++) {
spacingVec(i) = spacing[i];
}
HDF5Utils::writeVector(fg, "spacing", spacingVec);
statismo::GenericEigenType<int>::VectorType sizeVec =
statismo::GenericEigenType<int>::VectorType::Zero(imageDimension);
for (unsigned i = 0; i < imageDimension; i++) {
sizeVec(i) = size[i];
}
HDF5Utils::writeVectorOfType<int>(fg, "size", sizeVec);
// VTK does not support image direction. We write the identity matrix
statismo::MatrixType directionMat = statismo::MatrixType::Identity(
imageDimension, imageDimension);
HDF5Utils::writeMatrix(fg, "direction", directionMat);
typedef statismo::GenericEigenType<double>::MatrixType DoubleMatrixType;
DoubleMatrixType pixelMat(GetDimensions(), GetNumberOfPoints());
for (unsigned i = 0; i < static_cast<unsigned>(size[2]); i++) {
for (unsigned j = 0; j < static_cast<unsigned>(size[1]); j++) {
for (unsigned k = 0; k < static_cast<unsigned>(size[0]); k++) {
unsigned ind = i * size[1] * size[0] + j * size[0] + k;
TScalar * pixel =
static_cast<TScalar*>(m_reference->GetScalarPointer(k,
j, i));
for (unsigned d = 0; d < GetDimensions(); d++) {
pixelMat(d, ind) = pixel[d];
}
}
}
}
H5::Group pdGroup = fg.createGroup("pointData");
statismo::HDF5Utils::writeInt(pdGroup, "pixelDimension", GetDimensions());
H5::DataSet ds = HDF5Utils::writeMatrixOfType<double>(pdGroup,
"pixelValues", pixelMat);
HDF5Utils::writeIntAttribute(ds, "datatype",
statismo::GetDataTypeId<TScalar>());
pdGroup.close();
}
template<class TScalar, unsigned Dimensions>
unsigned vtkStandardImageRepresenter<TScalar, Dimensions>::GetNumberOfPoints() const {
return GetNumberOfPoints(this->m_reference);
}
template<class TScalar, unsigned Dimensions>
void vtkStandardImageRepresenter<TScalar, Dimensions>::SetReference(
const vtkStructuredPoints* reference) {
if (m_reference == 0) {
m_reference = vtkStructuredPoints::New();
}
m_reference->DeepCopy(const_cast<vtkStructuredPoints*>(reference));
// set the domain
DomainType::DomainPointsListType ptList;
for (unsigned i = 0; i < m_reference->GetNumberOfPoints(); i++) {
double* d = m_reference->GetPoint(i);
ptList.push_back(vtkPoint(d));
}
m_domain = DomainType(ptList);
}
template<class TScalar, unsigned Dimensions>
unsigned vtkStandardImageRepresenter<TScalar, Dimensions>::GetPointIdForPoint(
const PointType& pt) const {
assert(m_reference != 0);
return this->m_reference->FindPoint(const_cast<double*>(pt.data()));
}
template<class TScalar, unsigned Dimensions>
unsigned vtkStandardImageRepresenter<TScalar, Dimensions>::GetNumberOfPoints(
vtkStructuredPoints* reference) {
return reference->GetNumberOfPoints();
}
} // namespace statismo
|
d0ea26e872f22d5b4a73de2fc8551d846dfc9717 | 54028afa9bde4eec77ddd463ce56f85d0d86973b | /src/Client.h | a36c075459bb15c6f41c5d63c9693d78693e37ca | [] | no_license | Kolbjoern/Pacman | 549875b88080a4d3064d5af5ef078f6749587e42 | 1b6b23d9d2ee8bc48b1757d83670cd1448586569 | refs/heads/master | 2022-08-05T09:56:23.167911 | 2020-05-27T19:42:39 | 2020-05-27T19:42:39 | 257,278,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | h | Client.h | #pragma once
#include <string>
#include <functional>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include "net/Network.h"
class Client
{
public:
void run();
void serverCall(std::function<void(void)> callback);
private:
void init();
void connect(std::string& address, unsigned short port);
void disconnect();
std::function<void(void)> m_startServer;
sf::RenderWindow m_window;
sf::UdpSocket m_socket;
sf::Packet m_packet;
Peer m_server;
}; |
d8ebbb0a8cff8e6ea056cb067800811ab40f713c | bc26fbd57d4aee1ab2f68fbb134baee187660393 | /Locker.h | c6797823ab18739b17d8a65943e0428836e19528 | [] | no_license | camilaserra5/75.42-taller-tp2 | 707c3ac6f7ce18ffc1ad127ad07045b04e205b76 | c7f11ca9f9e1ced690b9dc3ba965131ce9b320a9 | refs/heads/main | 2023-01-12T12:34:59.389323 | 2020-11-17T20:31:31 | 2020-11-17T20:31:31 | 309,196,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | h | Locker.h | #ifndef LOCKER_H
#define LOCKER_H
#include "FileProcessor.h"
#include "ExtendedBPF.h"
#include "ResultsProcessor.h"
class Locker {
public:
Locker(FileProcessor &&fileProcessor, ResultsProcessor &&resultsProcessor);
void operator()();
private:
FileProcessor &fileProcessor;
ResultsProcessor &resultsProcessor;
};
#endif //LOCKER_H
|
5e45ae8645157599e231f9dc9b5f4b7b0818ecdb | b9b300e189110a8effdea48fb26956fdabc534ea | /GameProject3D_01/state_player_damage.h | de256f25b8e6924491b9efbb09c833fcf9ee2878 | [] | no_license | iyotaA/GameProject3D_01 | f1f7032a984e81c51d8c0b6fe869564423a4be0e | 9d352f82cd887b996d4a19cabf39a6f02aff8cb5 | refs/heads/master | 2021-07-09T15:49:20.890128 | 2020-09-26T23:58:06 | 2020-09-26T23:58:06 | 221,925,517 | 0 | 0 | null | 2020-09-26T23:58:07 | 2019-11-15T13:04:35 | C++ | SHIFT_JIS | C++ | false | false | 879 | h | state_player_damage.h | #ifndef STATE_PLAYER_DAMAGE_H_
#define STATE_PLAYER_DAMAGE_H_
#include "state_player.h"
class CStatePlayerDamage : public CStatePlayer
{
public:
CStatePlayerDamage(CPlayer* pPlayer, int damage);
virtual ~CStatePlayerDamage();
virtual void Update(CPlayer* pPlayer) override;
virtual void UpdateDamageState(CStatePlayerDamage* pStateDamage, CPlayer* pPlayer) {};
void ChangeState(CStatePlayerDamage* pStateDamage);
protected:
CStatePlayerDamage() {} // デフォルトコンストラクタ封印
private:
CStatePlayerDamage* m_pStateDamage;
};
class CStatePlayerDamageNone : public CStatePlayerDamage
{
public:
CStatePlayerDamageNone(CPlayer* pPlayer) {}
virtual ~CStatePlayerDamageNone() {}
virtual void Update(CPlayer* pPlayer) override {}
virtual void UpdateMoveState(CStatePlayerDamage* pStateDamage, CPlayer* pPlayer) {}
};
#endif // !STATE_PLAYER_DAMAGE_H_
|
2044df4da21385a24cff7ceb64f79a1efbff01d5 | c28cd20b70d02048be55ae1b513ef9e1d2090798 | /applications/clawpack/burgers/2d/pwconst/pwconst_user.cpp | 681a9edacf147179b9f02019e4897eb758b976a5 | [
"BSD-3-Clause",
"GPL-2.0-or-later",
"GPL-1.0-or-later",
"BSD-2-Clause"
] | permissive | mjberger/forestclaw | 172798495b9a190b97889937c8f0248728a9400f | 26038e637b9c5c5224b2cab18fbae0b286106e0c | refs/heads/master | 2020-06-13T19:22:44.109062 | 2019-03-05T11:49:14 | 2019-03-05T11:49:14 | 194,764,399 | 0 | 0 | BSD-2-Clause | 2019-07-02T01:12:38 | 2019-07-02T01:12:37 | null | UTF-8 | C++ | false | false | 3,425 | cpp | pwconst_user.cpp | /*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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 "pwconst_user.h"
#include <fclaw2d_clawpatch.h>
#include <fc2d_clawpack46.h>
#include <clawpack46_user_fort.h> /* Headers for user defined fortran files */
#include <fc2d_clawpack5.h>
#include <clawpack5_user_fort.h>
void pwconst_link_solvers(fclaw2d_global_t *glob)
{
const user_options_t* user = pwconst_get_options(glob);
if (user->claw_version == 4)
{
fc2d_clawpack46_vtable_t *claw46_vt = fc2d_clawpack46_vt();
claw46_vt->fort_qinit = &CLAWPACK46_QINIT;
claw46_vt->fort_rpn2 = &CLAWPACK46_RPN2;
claw46_vt->fort_rpt2 = &CLAWPACK46_RPT2;
}
else if (user->claw_version == 5)
{
fc2d_clawpack5_vtable_t *claw5_vt = fc2d_clawpack5_vt();
claw5_vt->fort_qinit = &CLAWPACK5_QINIT;
claw5_vt->fort_rpn2 = &CLAWPACK5_RPN2;
claw5_vt->fort_rpt2 = &CLAWPACK5_RPT2;
}
}
#if 0
void pwconst_link_solvers(fclaw2d_domain_t *domain)
{
const user_options_t* user = pwconst_user_get_options(domain);
fclaw2d_init_vtable(&fclaw2d_vt);
if (user->claw_version == 4)
{
fc2d_clawpack46_set_vtable_defaults(&fclaw2d_vt,&classic_claw46);
classic_claw46.qinit = &CLAWPACK46_QINIT;
classic_claw46.rpn2 = &CLAWPACK46_RPN2;
classic_claw46.rpt2 = &CLAWPACK46_RPT2;
fc2d_clawpack46_set_vtable(classic_claw46);
}
else if (user->claw_version == 5)
{
fc2d_clawpack5_set_vtable_defaults(&fclaw2d_vt,&classic_claw5);
classic_claw5.qinit = &CLAWPACK5_QINIT;
classic_claw5.rpn2 = &CLAWPACK5_RPN2;
classic_claw5.rpt2 = &CLAWPACK5_RPT2;
fc2d_clawpack5_set_vtable(classic_claw5);
}
fclaw2d_set_vtable(domain,&fclaw2d_vt);
#if 0
fclaw2d_init_vtable(&fclaw2d_vt);
fc2d_clawpack46_init_vtable(&classic_claw);
vt.patch_initialize = &fc2d_clawpack46_qinit;
classic_claw.qinit = &QINIT;
classic_claw.rpn2 = &RPN2;
classic_claw.rpt2 = &RPT2;
fclaw2d_set_vtable(domain,&vt);
fc2d_clawpack46_set_vtable(&classic_claw);
#endif
}
#endif
|
7c5bff62f9b7a57f5de55f906cd7142f11d55399 | 9dfca22ce65a7009879fc096b8db64ae76e776be | /CF/D- 665 Div2 .cpp | e4d43f23acc4896b9bf36d5e598aa5942ce0f3f4 | [] | no_license | viranch044/Cpp_Codes | 9c76cf4aeee456b6e3205550e5a852016e2d3fae | 2dbf2f2505675b151ace3a448da472b13005fe9c | refs/heads/master | 2022-12-06T13:36:34.071940 | 2020-08-26T19:29:48 | 2020-08-26T19:29:48 | 277,124,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,853 | cpp | D- 665 Div2 .cpp | #include<bits/stdc++.h>
using namespace std;
int power(int x,int y){
if(y==0) return 1;
int temp = power(x,y/2);
int curr = (temp*temp)%mod;
if(y%2) return (curr*x)%mod;
else return curr;
}
void dfs(int x,vector<vector<int>>& edge, vector<int>& vec, vector<bool>& vis, int n, vector<int>& c){
vis[x] = true;
for(auto j:edge[x]){
if(!vis[j]){
dfs(j,edge,vec,vis,n,c);
vec[x-1]+= vec[j-1] ;
c.pb(vec[j-1]*(n-vec[j-1]));
}
}
vec[x-1]++;
}
signed main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
fast;
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<vector<int>> edge(n+1);
vi vec(n);
f(n-1){
int x,y;
cin>>x>>y;
edge[x].pb(y);
edge[y].pb(x);
}
vector<bool> vis(n+1);
vi c;
dfs(1,edge,vec,vis,n,c);
// for(auto i:c) cout<<i<<nl;
sort(all(c),greater<int>());
int m;
cin>>m;
vi val(m);
f(m) cin>>val[i];
sort(all(val), greater<int>());
int ans = 0;
if(m>n-1){
int temp = 1;
for(int i=0;i<=(m-n+1);i++) {
temp = (temp*val[i])%mod;
}
ans+=(temp*c[0]);
ans = ans%mod;
for(int i=1;i<n-1;i++){
ans+=(c[i]*val[(m-n+1+i)]);
ans = (ans)%mod;
}
}
else{
for(int i=0;i<m;i++){
ans+=(c[i]*val[i]);
ans = (ans)%mod;
}
for(int i=m;i<n-1;i++) {
ans+=(c[i]);
ans = ans%mod;
}
}
cout<<ans<<nl;
}
} |
85f132f0f0fab8601928c4f22aaa65b5817247f5 | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/Game Programming Gems 5/Section1-Gen_Programming/1.03-ComponentBasedObjectMgmt-Rene/Components/ICmpActor.h | adcec4a74a9a6777adbdd9147ed9941cd814dc51 | [] | no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 273 | h | ICmpActor.h | #ifndef __ICMPActor_H
#define __ICMPActor_H
#include "IComponent.h"
class CVector;
class ICmpActor : public IComponent
{
public:
ICmpActor() {}
virtual ~ICmpActor() {}
protected:
static void RegisterInterface(EComponentTypeId);
};
#endif //__ICMPActor_H |
7fbf6835a6b30b7843a826c92893ccb5a2c6a6e0 | fee783abde5891cb3936d68b0fc51e5bca720304 | /Projectfile/Intermediate/Build/Win64/UE4Editor/Inc/BasicStudy/Selectable.generated.h | 91da6fb22bb939142a08521de2c2fee2aae2af17 | [] | no_license | JJIKKYU/UnrealEngine_Study | a4d8eec27d668ed0288a31179d40f9925b4070ed | dcf4db94316f2317bdecc26387059ab8b5f78116 | refs/heads/master | 2022-02-13T07:56:41.844138 | 2019-08-21T14:35:48 | 2019-08-21T14:35:48 | 200,591,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,520 | h | Selectable.generated.h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef BASICSTUDY_Selectable_generated_h
#error "Selectable.generated.h already included, missing '#pragma once' in Selectable.h"
#endif
#define BASICSTUDY_Selectable_generated_h
#define Projectfile_Source_BasicStudy_Selectable_h_8_RPC_WRAPPERS
#define Projectfile_Source_BasicStudy_Selectable_h_8_RPC_WRAPPERS_NO_PURE_DECLS
#define Projectfile_Source_BasicStudy_Selectable_h_8_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API USelectable(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(USelectable) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, USelectable); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(USelectable); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API USelectable(USelectable&&); \
NO_API USelectable(const USelectable&); \
public:
#define Projectfile_Source_BasicStudy_Selectable_h_8_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API USelectable(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API USelectable(USelectable&&); \
NO_API USelectable(const USelectable&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, USelectable); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(USelectable); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(USelectable)
#define Projectfile_Source_BasicStudy_Selectable_h_8_GENERATED_UINTERFACE_BODY() \
private: \
static void StaticRegisterNativesUSelectable(); \
friend struct Z_Construct_UClass_USelectable_Statics; \
public: \
DECLARE_CLASS(USelectable, UInterface, COMPILED_IN_FLAGS(CLASS_Abstract | CLASS_Interface), CASTCLASS_None, TEXT("/Script/BasicStudy"), NO_API) \
DECLARE_SERIALIZER(USelectable)
#define Projectfile_Source_BasicStudy_Selectable_h_8_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
Projectfile_Source_BasicStudy_Selectable_h_8_GENERATED_UINTERFACE_BODY() \
Projectfile_Source_BasicStudy_Selectable_h_8_STANDARD_CONSTRUCTORS \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Projectfile_Source_BasicStudy_Selectable_h_8_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
Projectfile_Source_BasicStudy_Selectable_h_8_GENERATED_UINTERFACE_BODY() \
Projectfile_Source_BasicStudy_Selectable_h_8_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Projectfile_Source_BasicStudy_Selectable_h_8_INCLASS_IINTERFACE_NO_PURE_DECLS \
protected: \
virtual ~ISelectable() {} \
public: \
typedef USelectable UClassType; \
typedef ISelectable ThisClass; \
virtual UObject* _getUObject() const { check(0 && "Missing required implementation."); return nullptr; }
#define Projectfile_Source_BasicStudy_Selectable_h_8_INCLASS_IINTERFACE \
protected: \
virtual ~ISelectable() {} \
public: \
typedef USelectable UClassType; \
typedef ISelectable ThisClass; \
virtual UObject* _getUObject() const { check(0 && "Missing required implementation."); return nullptr; }
#define Projectfile_Source_BasicStudy_Selectable_h_5_PROLOG
#define Projectfile_Source_BasicStudy_Selectable_h_13_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Projectfile_Source_BasicStudy_Selectable_h_8_RPC_WRAPPERS \
Projectfile_Source_BasicStudy_Selectable_h_8_INCLASS_IINTERFACE \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Projectfile_Source_BasicStudy_Selectable_h_13_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Projectfile_Source_BasicStudy_Selectable_h_8_RPC_WRAPPERS_NO_PURE_DECLS \
Projectfile_Source_BasicStudy_Selectable_h_8_INCLASS_IINTERFACE_NO_PURE_DECLS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> BASICSTUDY_API UClass* StaticClass<class USelectable>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Projectfile_Source_BasicStudy_Selectable_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
|
07b9ba7a38fc48fe32ddd4f35cb8d12b2b356d3c | 4f0d30830302f0cff9f1e5d8ae4fe8576ef29149 | /myRPG/Abilities.h | e9ea52cbd72292290c4685eeaef0492cf5ea9813 | [] | no_license | zxczzx/myRPG | c18915707ce6da41f055119038253671f6d966b3 | e83dd1813646814d1a0439dfdfc94f8d8e75f126 | refs/heads/master | 2021-01-15T10:06:13.575781 | 2016-02-25T17:39:08 | 2016-02-25T17:39:08 | 48,168,228 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | h | Abilities.h | #pragma once
#include "libraries.h"
#include "Requirements.h"
class Character;
class Abilities
{
protected:
std::string name;
std::string description;
std::string useString;
int damage;
int manaConsumprion;
int quantity;
std::shared_ptr<Requirements> requirements;
std::shared_ptr<Abilities> thisObj;
bool usable; // needed so I can use it with Backpack container
public:
Abilities();
~Abilities();
bool execute(std::shared_ptr<Character> self, std::shared_ptr<Character> target);
template<class T>
static std::shared_ptr<Abilities> createAbility();
//getters
std::string getName();
int getQuantity();
bool isUsable();
std::string getDescription();
int getDamage();
int getManaConsumption();
std::shared_ptr<Requirements> getRequireents();
//setters
void setQuantity(int count);
void setDescription(std::string value);
void setName(std::string value);
void setUseString(std::string value);
void setDamage(int value);
void setManaConsumption(int value);
void setRequirements(std::shared_ptr<Requirements> obj);
void setThisObj(std::shared_ptr<Abilities> me);
};
template<class T>
std::shared_ptr<Abilities> Abilities::createAbility(){
std::shared_ptr<Abilities> ability = std::make_shared<T>();
ability->thisObj = ability;
return ability;
} |
d52ba9c0aaeec4854e88d3639f403a2369193462 | 31f21bd5b0112796ced3de1a9e890f8d2ec2fd1c | /Block.h | fb7bc9418f78c2ac55615aa11649220794f1042a | [
"MIT"
] | permissive | Frans-Lukas/Breakout | e27f32676ff27c40aa1d2fb026c2eee743eb4ef9 | 0b85807f20e11a8448e5fb8b0555fb0e0b8a2656 | refs/heads/master | 2021-05-03T17:58:54.908104 | 2018-03-05T19:46:12 | 2018-03-05T19:46:12 | 120,455,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | h | Block.h | #pragma once
#include"Entity.h"
class Block: public Entity{
private:
int lifeLeft;
sf::Color color = sf::Color::Red;
public:
Block(int newX, int newY, int newWidth,
int newHeight, int newLifeLeft);
int getLifeLeft();
sf::Color getColor();
void setColor(sf::Color color);
void decrementLifeLeft();
void callCollide(Entity collidingEntity) override;
}; |
337a87d3cbd4470cf6c7493c44d0097f5ad9053f | 1a19d4493fa96bc0d5d598ce39352cabacd498c9 | /include/sparse-int-array.hpp | 9421f915b8caa034f548352e1221a12e1827ccd8 | [
"MIT",
"BSD-3-Clause"
] | permissive | praveenmunagapati/succinct | 8dbc6ad40fd541ccd1147ecf585d99ca7f6428e4 | e8f56bc9b6273d8f30897b93e32aa1ace4dc26ef | refs/heads/master | 2021-05-28T06:43:58.331757 | 2014-09-18T15:07:40 | 2014-09-18T15:07:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,378 | hpp | sparse-int-array.hpp | #pragma once
#include <vector>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include "bit-utils.hpp"
template<typename T>
class SparseIntArray {
public:
SparseIntArray(size_t n) : size_(n) {
groups.resize(1 + n/64);
zero = 0;
}
size_t size() const {
return size_;
}
~SparseIntArray() {
for (Group& g : groups) {
if (WordPopCount(g.exist) > 1) {
delete[] g.u.values;
}
}
}
const T& operator[](size_t i) const {
int o = i % 64;
const Group& g = groups[i / 64];
if ((g.exist & (1ull << o)) == 0) return zero;
if (g.exist == (1ull << o)) return g.u.single;
int r = WordPopCount(g.exist & ((1ull << o) - 1));
return g.u.values[r];
}
const T& get(size_t i) const {
return (*this)[i];
}
T& operator[](size_t i) {
int o = i % 64;
Group& g = groups[i / 64];
if ((g.exist & (1ull << o)) == 0) {
if (g.exist == 0) {
g.exist = 1ull << o;
g.u.single = 0;
return g.u.single;
}
if (__builtin_popcountll(g.exist) == 1) {
T old = g.u.single;
g.u.values = new T[2];
assert (g.exist != (1ull << o));
if ((1ull << o) < g.exist) {
g.exist |= 1ull << o;
g.u.values[1] = old;
g.u.values[0] = 0;
return g.u.values[0];
} else {
g.exist |= 1ull << o;
g.u.values[0] = old;
g.u.values[1] = 0;
return g.u.values[1];
}
}
int k = __builtin_popcountll(g.exist);
assert(k > 1);
T* nv = new T[k + 1];
g.exist |= 1ull << o;
uint64_t v = g.exist;
int r = -1;
int p = 0;
int op = 0;
while (v) {
int j = ffsll(v) - 1;
v ^= 1ull << j;
if (j == o) {
r = p;
nv[p] = 0;
p++;
} else {
nv[p] = g.u.values[op];
p++;
op++;
}
}
delete[] g.u.values;
g.u.values = nv;
return g.u.values[r];
}
if (g.exist == (1ull << o)) return g.u.single;
int r = __builtin_popcountll(g.exist & ((1ull << o) - 1));
return g.u.values[r];
}
private:
struct Group {
Group() : exist(0) {
u.single = 0;
}
uint64_t exist;
union {
T *values;
T single;
} u;
};
std::vector<Group> groups;
size_t size_;
T zero;
};
|
64a7a379eda56caac4f2806697ab081e83f8b405 | 20613d831aca9a42d46e3c49a23cc565bed028f9 | /adagucserverEC/CDataPostProcessor.cpp | ff5e32a41720c240f9fd516e847e07547d90fd9c | [
"Apache-2.0"
] | permissive | KNMI/adaguc-server | 56dcfb61415c3c4e87b8dd9fdc695500d93aefa1 | 973c9d441aba918592b881fef419a6590659cd07 | refs/heads/master | 2023-08-17T04:36:10.133071 | 2023-08-14T15:40:19 | 2023-08-14T15:40:19 | 77,039,523 | 23 | 30 | Apache-2.0 | 2023-09-06T14:21:09 | 2016-12-21T09:54:04 | C++ | UTF-8 | C++ | false | false | 60,129 | cpp | CDataPostProcessor.cpp | #include "CDataPostProcessor.h"
#include "CRequest.h"
#include "CDataPostProcessor_ClipMinMax.h"
void writeLogFileLocal(const char *msg) {
char *logfile = getenv("ADAGUC_LOGFILE");
if (logfile != NULL) {
FILE *pFile = NULL;
pFile = fopen(logfile, "a");
if (pFile != NULL) {
// setvbuf(pFile, NULL, _IONBF, 0);
fputs(msg, pFile);
if (strncmp(msg, "[D:", 3) == 0 || strncmp(msg, "[W:", 3) == 0 || strncmp(msg, "[E:", 3) == 0) {
time_t myTime = time(NULL);
tm *myUsableTime = localtime(&myTime);
char szTemp[128];
snprintf(szTemp, 127, "%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ ", myUsableTime->tm_year + 1900, myUsableTime->tm_mon + 1, myUsableTime->tm_mday, myUsableTime->tm_hour, myUsableTime->tm_min,
myUsableTime->tm_sec);
fputs(szTemp, pFile);
}
fclose(pFile);
} else
fprintf(stderr, "Unable to write logfile %s\n", logfile);
}
}
extern CDPPExecutor cdppExecutorInstance;
CDPPExecutor cdppExecutorInstance;
CDPPExecutor *CDataPostProcessor::getCDPPExecutor() { return &cdppExecutorInstance; }
/************************/
/* CDPPAXplusB */
/************************/
const char *CDPPAXplusB::className = "CDPPAXplusB";
const char *CDPPAXplusB::getId() { return "AX+B"; }
int CDPPAXplusB::isApplicable(CServerConfig::XMLE_DataPostProc *proc, CDataSource *) {
if (proc->attr.algorithm.equals("ax+b")) {
return CDATAPOSTPROCESSOR_RUNBEFOREREADING;
}
return CDATAPOSTPROCESSOR_NOTAPPLICABLE;
}
int CDPPAXplusB::execute(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, int) {
if (isApplicable(proc, dataSource) != CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
return -1;
}
if (dataSource->formatConverterActive) {
/**
* See issue https://github.com/KNMI/adaguc-server/issues/155
*
* Data post processor is meant for grids, not for other types of data like point times series.
*/
CDBError("CDPPAXplusB not possible when a format converter is active.");
return -1;
}
// CDBDebug("Applying ax+b");
for (size_t varNr = 0; varNr < dataSource->getNumDataObjects(); varNr++) {
dataSource->getDataObject(varNr)->hasScaleOffset = true;
dataSource->getDataObject(varNr)->cdfVariable->setType(CDF_DOUBLE);
// Apply offset
if (proc->attr.b.empty() == false) {
CDF::Attribute *add_offset = dataSource->getDataObject(varNr)->cdfVariable->getAttributeNE("add_offset");
if (add_offset == NULL) {
dataSource->getDataObject(varNr)->dfadd_offset = proc->attr.b.toDouble();
} else {
dataSource->getDataObject(varNr)->dfadd_offset += proc->attr.b.toDouble();
}
}
// Apply scale
if (proc->attr.a.empty() == false) {
CDF::Attribute *scale_factor = dataSource->getDataObject(varNr)->cdfVariable->getAttributeNE("scale_factor");
if (scale_factor == NULL) {
dataSource->getDataObject(varNr)->dfscale_factor = proc->attr.a.toDouble();
} else {
dataSource->getDataObject(varNr)->dfscale_factor *= proc->attr.a.toDouble();
}
}
if (proc->attr.units.empty() == false) {
dataSource->getDataObject(varNr)->setUnits(proc->attr.units.c_str());
}
}
return 0;
}
/************************/
/*CDPPIncludeLayer */
/************************/
const char *CDPPIncludeLayer::className = "CDPPIncludeLayer";
const char *CDPPIncludeLayer::getId() { return "include_layer"; }
int CDPPIncludeLayer::isApplicable(CServerConfig::XMLE_DataPostProc *proc, CDataSource *) {
if (proc->attr.algorithm.equals("include_layer")) {
return CDATAPOSTPROCESSOR_RUNAFTERREADING | CDATAPOSTPROCESSOR_RUNBEFOREREADING;
}
return CDATAPOSTPROCESSOR_NOTAPPLICABLE;
}
CDataSource *CDPPIncludeLayer::getDataSource(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource) {
CDataSource *dataSourceToInclude = new CDataSource();
CT::string additionalLayerName = proc->attr.name.c_str();
size_t additionalLayerNo = 0;
for (size_t j = 0; j < dataSource->srvParams->cfg->Layer.size(); j++) {
CT::string layerName;
dataSource->srvParams->makeUniqueLayerName(&layerName, dataSource->srvParams->cfg->Layer[j]);
// CDBDebug("comparing for additionallayer %s==%s", additionalLayerName.c_str(), layerName.c_str());
if (additionalLayerName.equals(layerName)) {
additionalLayerNo = j;
break;
}
}
dataSourceToInclude->setCFGLayer(dataSource->srvParams, dataSource->srvParams->configObj->Configuration[0], dataSource->srvParams->cfg->Layer[additionalLayerNo], additionalLayerName.c_str(), 0);
return dataSourceToInclude;
}
int CDPPIncludeLayer::setDimsForNewDataSource(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, CDataSource *dataSourceToInclude) {
CT::string additionalLayerName = proc->attr.name.c_str();
bool dataIsFound = false;
try {
if (CRequest::setDimValuesForDataSource(dataSourceToInclude, dataSource->srvParams) == 0) {
dataIsFound = true;
}
} catch (ServiceExceptionCode e) {
}
if (dataIsFound == false) {
CDBDebug("No data available for layer %s", additionalLayerName.c_str());
return 1;
}
return 0;
}
int CDPPIncludeLayer::execute(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, int mode) {
if ((isApplicable(proc, dataSource) & mode) == false) {
return -1;
}
if (mode == CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
CDBDebug("CDATAPOSTPROCESSOR_RUNBEFOREREADING::Applying include_layer");
// Load the other datasource.
CDataSource *dataSourceToInclude = getDataSource(proc, dataSource);
if (dataSourceToInclude == NULL) {
CDBDebug("dataSourceToInclude has no data");
return 0;
}
/*
CDirReader dirReader;
if(CDBFileScanner::searchFileNames(&dirReader,dataSourceToInclude->cfgLayer->FilePath[0]->value.c_str(),dataSourceToInclude->cfgLayer->FilePath[0]->attr.filter,NULL)!=0){
CDBError("Could not find any filename");
return 1;
}
if(dirReader.fileList.size()==0){
CDBError("dirReader.fileList.size()==0");return 1;
}
dataSourceToInclude->addStep(dirReader.fileList[0]->fullName.c_str(),NULL);
*/
int status = setDimsForNewDataSource(proc, dataSource, dataSourceToInclude);
if (status != 0) {
CDBError("Trying to include datasource, but it has no values for given dimensions");
delete dataSourceToInclude;
;
return 1;
}
CDataReader reader;
status = reader.open(dataSourceToInclude, CNETCDFREADER_MODE_OPEN_HEADER); // Only read metadata
if (status != 0) {
CDBDebug("Can't open file %s for layer %s", dataSourceToInclude->getFileName(), proc->attr.name.c_str());
return 1;
}
for (size_t dataObjectNr = 0; dataObjectNr < dataSource->getNumDataObjects(); dataObjectNr++) {
if (dataSource->getDataObject(dataObjectNr)->cdfVariable->name.equals(dataSourceToInclude->getDataObject(0)->cdfVariable->name)) {
// CDBDebug("Probably already done");
delete dataSourceToInclude;
return 0;
}
}
for (size_t dataObjectNr = 0; dataObjectNr < dataSourceToInclude->getNumDataObjects(); dataObjectNr++) {
CDataSource::DataObject *currentDataObject = dataSource->getDataObject(0);
CDF::Variable *varToClone = NULL;
try {
varToClone = dataSourceToInclude->getDataObject(dataObjectNr)->cdfVariable;
} catch (int e) {
}
if (varToClone == NULL) {
CDBError("Variable not found");
return 1;
}
int mode = 0; // 0:append, 1:prepend
if (proc->attr.mode.empty() == false) {
if (proc->attr.mode.equals("append")) mode = 0;
if (proc->attr.mode.equals("prepend")) mode = 1;
}
CDataSource::DataObject *newDataObject = new CDataSource::DataObject();
if (mode == 0) dataSource->getDataObjectsVector()->push_back(newDataObject);
if (mode == 1) dataSource->getDataObjectsVector()->insert(dataSource->getDataObjectsVector()->begin(), newDataObject);
CDBDebug("--------> newDataObject %d ", dataSource->getDataObjectsVector()->size());
newDataObject->variableName.copy(varToClone->name.c_str());
newDataObject->cdfVariable = new CDF::Variable();
CT::string text;
text.print("{\"variable\":\"%s\",\"datapostproc\":\"%s\"}", varToClone->name.c_str(), this->getId());
newDataObject->cdfObject = currentDataObject->cdfObject; //(CDFObject*)varToClone->getParentCDFObject();
CDBDebug("--------> Adding variable %s ", varToClone->name.c_str());
newDataObject->cdfObject->addVariable(newDataObject->cdfVariable);
newDataObject->cdfVariable->setName(varToClone->name.c_str());
newDataObject->cdfVariable->setType(varToClone->getType());
newDataObject->cdfVariable->setSize(dataSource->dWidth * dataSource->dHeight);
for (size_t j = 0; j < currentDataObject->cdfVariable->dimensionlinks.size(); j++) {
newDataObject->cdfVariable->dimensionlinks.push_back(currentDataObject->cdfVariable->dimensionlinks[j]);
}
for (size_t j = 0; j < varToClone->attributes.size(); j++) {
newDataObject->cdfVariable->attributes.push_back(new CDF::Attribute(varToClone->attributes[j]));
}
newDataObject->cdfVariable->removeAttribute("ADAGUC_DATAOBJECTID");
newDataObject->cdfVariable->setAttributeText("ADAGUC_DATAOBJECTID", text.c_str());
newDataObject->cdfVariable->removeAttribute("scale_factor");
newDataObject->cdfVariable->removeAttribute("add_offset");
newDataObject->cdfVariable->setCustomReader(CDF::Variable::CustomMemoryReaderInstance);
}
reader.close();
delete dataSourceToInclude;
return 0;
}
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
CDBDebug("CDATAPOSTPROCESSOR_RUNAFTERREADING::Applying include_layer");
// Load the other datasource.
CDataSource *dataSourceToInclude = getDataSource(proc, dataSource);
if (dataSourceToInclude == NULL) {
CDBDebug("dataSourceToInclude has no data");
return 0;
}
int status = setDimsForNewDataSource(proc, dataSource, dataSourceToInclude);
if (status != 0) {
CDBError("Trying to include datasource, but it has no values for given dimensions");
delete dataSourceToInclude;
;
return 1;
}
dataSourceToInclude->setTimeStep(dataSource->getCurrentTimeStep());
// dataSourceToInclude->getDataObject(0)->cdfVariable->data=NULL;
CDataReader reader;
// CDBDebug("Opening %s",dataSourceToInclude->getFileName());
status = reader.open(dataSourceToInclude, CNETCDFREADER_MODE_OPEN_ALL); // Now open the data as well.
if (status != 0) {
CDBDebug("Can't open file %s for layer %s", dataSourceToInclude->getFileName(), proc->attr.name.c_str());
return 1;
}
/* size_t l=(size_t)dataSource->dHeight*(size_t)dataSource->dWidth;
CDF::allocateData( dataSourceToInclude->getDataObject(0)->cdfVariable->getType(),&dataSourceToInclude->getDataObject(0)->cdfVariable->data,l);
CDF::fill(dataSourceToInclude->getDataObject(0)->cdfVariable->data, dataSourceToInclude->getDataObject(0)->cdfVariable->getType(),100,(size_t)dataSource->dHeight*(size_t)dataSource->dWidth);
*/
for (size_t dataObjectNr = 0; dataObjectNr < dataSourceToInclude->getNumDataObjects(); dataObjectNr++) {
// This is the variable to read from
CDF::Variable *varToClone = dataSourceToInclude->getDataObject(dataObjectNr)->cdfVariable;
// This is the variable to write To
// CDBDebug("Filling %s",varToClone->name.c_str());
CDF::Variable *varToWriteTo = dataSource->getDataObject(varToClone->name.c_str())->cdfVariable;
CDF::fill(varToWriteTo->data, varToWriteTo->getType(), 0, (size_t)dataSource->dHeight * (size_t)dataSource->dWidth);
Settings settings;
settings.width = dataSource->dWidth;
settings.height = dataSource->dHeight;
settings.data = (void *)varToWriteTo->data; // To write TO
void *sourceData = (void *)varToClone->data; // To read FROM
CGeoParams sourceGeo;
sourceGeo.dWidth = dataSourceToInclude->dWidth;
sourceGeo.dHeight = dataSourceToInclude->dHeight;
sourceGeo.dfBBOX[0] = dataSourceToInclude->dfBBOX[0];
sourceGeo.dfBBOX[1] = dataSourceToInclude->dfBBOX[1];
sourceGeo.dfBBOX[2] = dataSourceToInclude->dfBBOX[2];
sourceGeo.dfBBOX[3] = dataSourceToInclude->dfBBOX[3];
sourceGeo.dfCellSizeX = dataSourceToInclude->dfCellSizeX;
sourceGeo.dfCellSizeY = dataSourceToInclude->dfCellSizeY;
sourceGeo.CRS = dataSourceToInclude->nativeProj4;
CGeoParams destGeo;
destGeo.dWidth = dataSource->dWidth;
destGeo.dHeight = dataSource->dHeight;
destGeo.dfBBOX[0] = dataSource->dfBBOX[0];
destGeo.dfBBOX[1] = dataSource->dfBBOX[1];
destGeo.dfBBOX[2] = dataSource->dfBBOX[2];
destGeo.dfBBOX[3] = dataSource->dfBBOX[3];
destGeo.dfCellSizeX = dataSource->dfCellSizeX;
destGeo.dfCellSizeY = dataSource->dfCellSizeY;
destGeo.CRS = dataSource->nativeProj4;
CImageWarper warper;
status = warper.initreproj(dataSourceToInclude, &destGeo, &dataSource->srvParams->cfg->Projection);
if (status != 0) {
CDBError("Unable to initialize projection");
return 1;
}
GenericDataWarper genericDataWarper;
switch (varToWriteTo->getType()) {
case CDF_CHAR:
genericDataWarper.render<char>(&warper, sourceData, &sourceGeo, &destGeo, &settings, &drawFunction);
break;
case CDF_BYTE:
genericDataWarper.render<char>(&warper, sourceData, &sourceGeo, &destGeo, &settings, &drawFunction);
break;
case CDF_UBYTE:
genericDataWarper.render<unsigned char>(&warper, sourceData, &sourceGeo, &destGeo, &settings, &drawFunction);
break;
case CDF_SHORT:
genericDataWarper.render<short>(&warper, sourceData, &sourceGeo, &destGeo, &settings, &drawFunction);
break;
case CDF_USHORT:
genericDataWarper.render<ushort>(&warper, sourceData, &sourceGeo, &destGeo, &settings, &drawFunction);
break;
case CDF_INT:
genericDataWarper.render<int>(&warper, sourceData, &sourceGeo, &destGeo, &settings, &drawFunction);
break;
case CDF_UINT:
genericDataWarper.render<uint>(&warper, sourceData, &sourceGeo, &destGeo, &settings, &drawFunction);
break;
case CDF_FLOAT:
genericDataWarper.render<float>(&warper, sourceData, &sourceGeo, &destGeo, &settings, &drawFunction);
break;
case CDF_DOUBLE:
genericDataWarper.render<double>(&warper, sourceData, &sourceGeo, &destGeo, &settings, &drawFunction);
break;
}
}
reader.close();
delete dataSourceToInclude;
}
return 0;
}
/************************/
/*CDPPDATAMASK */
/************************/
const char *CDPPDATAMASK::className = "CDPPDATAMASK";
const char *CDPPDATAMASK::getId() { return "datamask"; }
int CDPPDATAMASK::isApplicable(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource) {
if (proc->attr.algorithm.equals("datamask")) {
if (dataSource->getNumDataObjects() != 2 && dataSource->getNumDataObjects() != 3) {
CDBError("2 variables are needed for datamask, found %d", dataSource->getNumDataObjects());
return CDATAPOSTPROCESSOR_CONSTRAINTSNOTMET;
}
return CDATAPOSTPROCESSOR_RUNAFTERREADING | CDATAPOSTPROCESSOR_RUNBEFOREREADING;
}
return CDATAPOSTPROCESSOR_NOTAPPLICABLE;
}
template <typename TT, typename SS>
void CDPPDATAMASK::DOIT<TT, SS>::doIt(void *newData, void *orginalData, void *maskData, double newDataNoDataValue, CDFType maskType, double a, double b, double c, int mode, size_t l) {
switch (maskType) {
case CDF_CHAR:
DOIT<TT, char>::reallyDoIt(newData, orginalData, maskData, newDataNoDataValue, maskType, a, b, c, mode, l);
break;
case CDF_BYTE:
DOIT<TT, char>::reallyDoIt(newData, orginalData, maskData, newDataNoDataValue, maskType, a, b, c, mode, l);
break;
case CDF_UBYTE:
DOIT<TT, unsigned char>::reallyDoIt(newData, orginalData, maskData, newDataNoDataValue, maskType, a, b, c, mode, l);
break;
case CDF_SHORT:
DOIT<TT, short>::reallyDoIt(newData, orginalData, maskData, newDataNoDataValue, maskType, a, b, c, mode, l);
break;
case CDF_USHORT:
DOIT<TT, ushort>::reallyDoIt(newData, orginalData, maskData, newDataNoDataValue, maskType, a, b, c, mode, l);
break;
case CDF_INT:
DOIT<TT, int>::reallyDoIt(newData, orginalData, maskData, newDataNoDataValue, maskType, a, b, c, mode, l);
break;
case CDF_UINT:
DOIT<TT, uint>::reallyDoIt(newData, orginalData, maskData, newDataNoDataValue, maskType, a, b, c, mode, l);
break;
case CDF_FLOAT:
DOIT<TT, float>::reallyDoIt(newData, orginalData, maskData, newDataNoDataValue, maskType, a, b, c, mode, l);
break;
case CDF_DOUBLE:
DOIT<TT, double>::reallyDoIt(newData, orginalData, maskData, newDataNoDataValue, maskType, a, b, c, mode, l);
break;
}
}
template <typename TT, typename SS>
void CDPPDATAMASK::DOIT<TT, SS>::reallyDoIt(void *newData, void *orginalData, void *maskData, double newDataNoDataValue, CDFType, double a, double b, double c, int mode, size_t l) {
// if_mask_includes_then_nodata_else_data
if (mode == 0) {
for (size_t j = 0; j < l; j++) {
if (((SS *)maskData)[j] >= a && ((SS *)maskData)[j] <= b)
((TT *)newData)[j] = newDataNoDataValue;
else
((TT *)newData)[j] = ((TT *)orginalData)[j];
}
}
// if_mask_excludes_then_nodata_else_data
if (mode == 1) {
for (size_t j = 0; j < l; j++) {
if (((SS *)maskData)[j] >= a && ((SS *)maskData)[j] <= b)
((TT *)newData)[j] = ((TT *)orginalData)[j];
else
((TT *)newData)[j] = newDataNoDataValue;
}
}
// if_mask_includes_then_valuec_else_data
if (mode == 2) {
for (size_t j = 0; j < l; j++) {
if (((SS *)maskData)[j] >= a && ((SS *)maskData)[j] <= b)
((TT *)newData)[j] = c;
else
((TT *)newData)[j] = ((TT *)orginalData)[j];
}
}
// if_mask_excludes_then_valuec_else_data
if (mode == 3) {
for (size_t j = 0; j < l; j++) {
if (((SS *)maskData)[j] >= a && ((SS *)maskData)[j] <= b)
((TT *)newData)[j] = ((TT *)orginalData)[j];
else
((TT *)newData)[j] = c;
}
}
// if_mask_includes_then_mask_else_data
if (mode == 4) {
for (size_t j = 0; j < l; j++) {
if (((SS *)maskData)[j] >= a && ((SS *)maskData)[j] <= b)
((TT *)newData)[j] = ((SS *)maskData)[j];
else
((TT *)newData)[j] = ((TT *)orginalData)[j];
}
}
// if_mask_excludes_then_mask_else_data
if (mode == 5) {
for (size_t j = 0; j < l; j++) {
if (((SS *)maskData)[j] >= a && ((SS *)maskData)[j] <= b)
((TT *)newData)[j] = ((TT *)orginalData)[j];
else
((TT *)newData)[j] = ((SS *)maskData)[j];
}
}
}
int CDPPDATAMASK::execute(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, int mode) {
if ((isApplicable(proc, dataSource) & mode) == false) {
return -1;
}
if (mode == CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
if (dataSource->getDataObject(0)->cdfVariable->name.equals("masked")) return 0;
CDBDebug("CDATAPOSTPROCESSOR_RUNBEFOREREADING::Applying datamask");
CDF::Variable *varToClone = dataSource->getDataObject(0)->cdfVariable;
CDataSource::DataObject *newDataObject = new CDataSource::DataObject();
newDataObject->variableName.copy("masked");
dataSource->getDataObjectsVector()->insert(dataSource->getDataObjectsVector()->begin(), newDataObject);
newDataObject->cdfVariable = new CDF::Variable();
newDataObject->cdfObject = (CDFObject *)varToClone->getParentCDFObject();
newDataObject->cdfObject->addVariable(newDataObject->cdfVariable);
newDataObject->cdfVariable->setName("masked");
CT::string text;
text.print("{\"variable\":\"%s\",\"datapostproc\":\"%s\"}", "masked", this->getId());
newDataObject->cdfVariable->removeAttribute("ADAGUC_DATAOBJECTID");
newDataObject->cdfVariable->setAttributeText("ADAGUC_DATAOBJECTID", text.c_str());
newDataObject->cdfVariable->setType(dataSource->getDataObject(1)->cdfVariable->getType());
newDataObject->cdfVariable->setSize(dataSource->dWidth * dataSource->dHeight);
for (size_t j = 0; j < varToClone->dimensionlinks.size(); j++) {
newDataObject->cdfVariable->dimensionlinks.push_back(varToClone->dimensionlinks[j]);
}
for (size_t j = 0; j < varToClone->attributes.size(); j++) {
newDataObject->cdfVariable->attributes.push_back(new CDF::Attribute(varToClone->attributes[j]));
}
newDataObject->cdfVariable->removeAttribute("scale_factor");
newDataObject->cdfVariable->removeAttribute("add_offset");
if (proc->attr.units.empty() == false) {
newDataObject->cdfVariable->removeAttribute("units");
newDataObject->setUnits(proc->attr.units.c_str());
newDataObject->cdfVariable->setAttributeText("units", proc->attr.units.c_str());
}
if (proc->attr.name.empty() == false) {
newDataObject->cdfVariable->removeAttribute("long_name");
newDataObject->cdfVariable->setAttributeText("long_name", proc->attr.name.c_str());
}
newDataObject->cdfVariable->setCustomReader(CDF::Variable::CustomMemoryReaderInstance);
// return 0;
}
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
CDBDebug("Applying datamask");
double fa = 0, fb = 1; // More or equal to a and less than b
double fc = 0;
if (proc->attr.a.empty() == false) {
CT::string a;
a.copy(proc->attr.a.c_str());
fa = a.toDouble();
}
if (proc->attr.b.empty() == false) {
CT::string b;
b.copy(proc->attr.b.c_str());
fb = b.toDouble();
}
if (proc->attr.c.empty() == false) {
CT::string c;
c.copy(proc->attr.c.c_str());
fc = c.toDouble();
}
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
int mode = 0; // replace with noDataValue
if (proc->attr.mode.empty() == false) {
if (proc->attr.mode.equals("if_mask_includes_then_nodata_else_data")) mode = 0;
if (proc->attr.mode.equals("if_mask_excludes_then_nodata_else_data")) mode = 1;
if (proc->attr.mode.equals("if_mask_includes_then_valuec_else_data")) mode = 2;
if (proc->attr.mode.equals("if_mask_excludes_then_valuec_else_data")) mode = 3;
if (proc->attr.mode.equals("if_mask_includes_then_mask_else_data")) mode = 4;
if (proc->attr.mode.equals("if_mask_excludes_then_mask_else_data")) mode = 5;
}
void *newData = dataSource->getDataObject(0)->cdfVariable->data;
void *orginalData = dataSource->getDataObject(1)->cdfVariable->data; // sunz
void *maskData = dataSource->getDataObject(2)->cdfVariable->data;
double newDataNoDataValue = (double)dataSource->getDataObject(1)->dfNodataValue;
CDFType maskType = dataSource->getDataObject(2)->cdfVariable->getType();
switch (dataSource->getDataObject(0)->cdfVariable->getType()) {
case CDF_CHAR:
DOIT<char, void>::doIt(newData, orginalData, maskData, newDataNoDataValue, maskType, fa, fb, fc, mode, l);
break;
case CDF_BYTE:
DOIT<char, void>::doIt(newData, orginalData, maskData, newDataNoDataValue, maskType, fa, fb, fc, mode, l);
break;
case CDF_UBYTE:
DOIT<unsigned char, void>::doIt(newData, orginalData, maskData, newDataNoDataValue, maskType, fa, fb, fc, mode, l);
break;
case CDF_SHORT:
DOIT<short, void>::doIt(newData, orginalData, maskData, newDataNoDataValue, maskType, fa, fb, fc, mode, l);
break;
case CDF_USHORT:
DOIT<ushort, void>::doIt(newData, orginalData, maskData, newDataNoDataValue, maskType, fa, fb, fc, mode, l);
break;
case CDF_INT:
DOIT<int, void>::doIt(newData, orginalData, maskData, newDataNoDataValue, maskType, fa, fb, fc, mode, l);
break;
case CDF_UINT:
DOIT<uint, void>::doIt(newData, orginalData, maskData, newDataNoDataValue, maskType, fa, fb, fc, mode, l);
break;
case CDF_FLOAT:
DOIT<float, void>::doIt(newData, orginalData, maskData, newDataNoDataValue, maskType, fa, fb, fc, mode, l);
break;
case CDF_DOUBLE:
DOIT<double, void>::doIt(newData, orginalData, maskData, newDataNoDataValue, maskType, fa, fb, fc, mode, l);
break;
}
}
return 0;
}
/************************/
/*CDPPMSGCPPVisibleMask */
/************************/
const char *CDPPMSGCPPVisibleMask::className = "CDPPMSGCPPVisibleMask";
const char *CDPPMSGCPPVisibleMask::getId() { return "MSGCPP_VISIBLEMASK"; }
int CDPPMSGCPPVisibleMask::isApplicable(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource) {
if (proc->attr.algorithm.equals("msgcppvisiblemask")) {
if (dataSource->getNumDataObjects() != 2 && dataSource->getNumDataObjects() != 3) {
CDBError("2 variables are needed for msgcppvisiblemask, found %d", dataSource->getNumDataObjects());
return CDATAPOSTPROCESSOR_CONSTRAINTSNOTMET;
}
return CDATAPOSTPROCESSOR_RUNAFTERREADING | CDATAPOSTPROCESSOR_RUNBEFOREREADING;
}
return CDATAPOSTPROCESSOR_NOTAPPLICABLE;
}
int CDPPMSGCPPVisibleMask::execute(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, int mode) {
if ((isApplicable(proc, dataSource) & mode) == false) {
return -1;
}
if (mode == CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
if (dataSource->getDataObject(0)->cdfVariable->name.equals("mask")) return 0;
CDBDebug("CDATAPOSTPROCESSOR_RUNBEFOREREADING::Applying msgcpp VISIBLE mask");
CDF::Variable *varToClone = dataSource->getDataObject(0)->cdfVariable;
CDataSource::DataObject *newDataObject = new CDataSource::DataObject();
newDataObject->variableName.copy("mask");
dataSource->getDataObjectsVector()->insert(dataSource->getDataObjectsVector()->begin(), newDataObject);
newDataObject->cdfVariable = new CDF::Variable();
newDataObject->cdfObject = (CDFObject *)varToClone->getParentCDFObject();
newDataObject->cdfObject->addVariable(newDataObject->cdfVariable);
newDataObject->cdfVariable->setName("mask");
newDataObject->cdfVariable->setType(CDF_SHORT);
newDataObject->cdfVariable->setSize(dataSource->dWidth * dataSource->dHeight);
for (size_t j = 0; j < varToClone->dimensionlinks.size(); j++) {
newDataObject->cdfVariable->dimensionlinks.push_back(varToClone->dimensionlinks[j]);
}
for (size_t j = 0; j < varToClone->attributes.size(); j++) {
newDataObject->cdfVariable->attributes.push_back(new CDF::Attribute(varToClone->attributes[j]));
}
newDataObject->cdfVariable->removeAttribute("scale_factor");
newDataObject->cdfVariable->removeAttribute("add_offset");
newDataObject->cdfVariable->setAttributeText("standard_name", "visible_mask status_flag");
newDataObject->cdfVariable->setAttributeText("long_name", "Visible mask");
newDataObject->cdfVariable->setAttributeText("units", "1");
newDataObject->cdfVariable->removeAttribute("valid_range");
newDataObject->cdfVariable->removeAttribute("flag_values");
newDataObject->cdfVariable->removeAttribute("flag_meanings");
short attrData[3];
attrData[0] = -1;
newDataObject->cdfVariable->setAttribute("_FillValue", newDataObject->cdfVariable->getType(), attrData, 1);
attrData[0] = 0;
attrData[1] = 1;
newDataObject->cdfVariable->setAttribute("valid_range", newDataObject->cdfVariable->getType(), attrData, 2);
newDataObject->cdfVariable->setAttribute("flag_values", newDataObject->cdfVariable->getType(), attrData, 2);
newDataObject->cdfVariable->setAttributeText("flag_meanings", "no yes");
newDataObject->cdfVariable->setCustomReader(CDF::Variable::CustomMemoryReaderInstance);
// return 0;
}
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
CDBDebug("Applying msgcppvisiblemask");
short *mask = (short *)dataSource->getDataObject(0)->cdfVariable->data;
float *sunz = (float *)dataSource->getDataObject(1)->cdfVariable->data; // sunz
float *satz = (float *)dataSource->getDataObject(2)->cdfVariable->data;
short fNosunz = (short)dataSource->getDataObject(0)->dfNodataValue;
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
float fa = 72, fb = 75;
if (proc->attr.b.empty() == false) {
CT::string b;
b.copy(proc->attr.b.c_str());
fb = b.toDouble();
}
if (proc->attr.a.empty() == false) {
CT::string a;
a.copy(proc->attr.a.c_str());
fa = a.toDouble();
}
for (size_t j = 0; j < l; j++) {
if ((satz[j] < fa && sunz[j] < fa) || (satz[j] > fb))
mask[j] = fNosunz;
else
mask[j] = 1;
}
}
return 0;
}
/************************/
/*CDPPMSGCPPHIWCMask */
/************************/
const char *CDPPMSGCPPHIWCMask::className = "CDPPMSGCPPHIWCMask";
const char *CDPPMSGCPPHIWCMask::getId() { return "MSGCPP_HIWCMASK"; }
int CDPPMSGCPPHIWCMask::isApplicable(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource) {
if (proc->attr.algorithm.equals("msgcpphiwcmask")) {
if (dataSource->getNumDataObjects() != 4 && dataSource->getNumDataObjects() != 5) {
CDBError("4 variables are needed for msgcpphiwcmask, found %d", dataSource->getNumDataObjects());
return CDATAPOSTPROCESSOR_CONSTRAINTSNOTMET;
}
return CDATAPOSTPROCESSOR_RUNAFTERREADING | CDATAPOSTPROCESSOR_RUNBEFOREREADING;
}
return CDATAPOSTPROCESSOR_NOTAPPLICABLE;
}
int CDPPMSGCPPHIWCMask::execute(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, int mode) {
if ((isApplicable(proc, dataSource) & mode) == false) {
return -1;
}
if (mode == CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
if (dataSource->getDataObject(0)->cdfVariable->name.equals("hiwc")) return 0;
CDBDebug("CDATAPOSTPROCESSOR_RUNBEFOREREADING::Applying msgcpp HIWC mask");
CDF::Variable *varToClone = dataSource->getDataObject(0)->cdfVariable;
CDataSource::DataObject *newDataObject = new CDataSource::DataObject();
newDataObject->variableName.copy("hiwc");
dataSource->getDataObjectsVector()->insert(dataSource->getDataObjectsVector()->begin(), newDataObject);
newDataObject->cdfVariable = new CDF::Variable();
newDataObject->cdfObject = (CDFObject *)varToClone->getParentCDFObject();
newDataObject->cdfObject->addVariable(newDataObject->cdfVariable);
newDataObject->cdfVariable->setName("hiwc");
newDataObject->cdfVariable->setType(CDF_SHORT);
newDataObject->cdfVariable->setSize(dataSource->dWidth * dataSource->dHeight);
for (size_t j = 0; j < varToClone->dimensionlinks.size(); j++) {
newDataObject->cdfVariable->dimensionlinks.push_back(varToClone->dimensionlinks[j]);
}
for (size_t j = 0; j < varToClone->attributes.size(); j++) {
newDataObject->cdfVariable->attributes.push_back(new CDF::Attribute(varToClone->attributes[j]));
}
newDataObject->cdfVariable->removeAttribute("scale_factor");
newDataObject->cdfVariable->removeAttribute("add_offset");
newDataObject->cdfVariable->setAttributeText("standard_name", "high_ice_water_content status_flag");
newDataObject->cdfVariable->setAttributeText("long_name", "High ice water content");
newDataObject->cdfVariable->setAttributeText("units", "1");
newDataObject->cdfVariable->removeAttribute("valid_range");
newDataObject->cdfVariable->removeAttribute("flag_values");
newDataObject->cdfVariable->removeAttribute("flag_meanings");
short attrData[3];
attrData[0] = -1;
newDataObject->cdfVariable->setAttribute("_FillValue", newDataObject->cdfVariable->getType(), attrData, 1);
attrData[0] = 0;
attrData[1] = 1;
newDataObject->cdfVariable->setAttribute("valid_range", newDataObject->cdfVariable->getType(), attrData, 2);
newDataObject->cdfVariable->setAttribute("flag_values", newDataObject->cdfVariable->getType(), attrData, 2);
newDataObject->cdfVariable->setAttributeText("flag_meanings", "no yes");
newDataObject->cdfVariable->setCustomReader(CDF::Variable::CustomMemoryReaderInstance);
// return 0;
}
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
CDBDebug("CDATAPOSTPROCESSOR_RUNAFTERREADING::Applying msgcpp HIWC mask");
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
// CDF::allocateData(dataSource->getDataObject(0)->cdfVariable->getType(),&dataSource->getDataObject(0)->cdfVariable->data,l);
short *hiwc = (short *)dataSource->getDataObject(0)->cdfVariable->data;
float *cph = (float *)dataSource->getDataObject(1)->cdfVariable->data;
float *cwp = (float *)dataSource->getDataObject(2)->cdfVariable->data;
float *ctt = (float *)dataSource->getDataObject(3)->cdfVariable->data;
float *cot = (float *)dataSource->getDataObject(4)->cdfVariable->data;
for (size_t j = 0; j < l; j++) {
hiwc[j] = 0;
if (cph[j] == 2) {
if (cwp[j] > 0.1) {
if (ctt[j] < 270) {
if (cot[j] > 20) {
hiwc[j] = 1;
}
}
}
}
}
}
// dataSource->eraseDataObject(1);
return 0;
}
/*CPDPPExecutor*/
const char *CDPPExecutor::className = "CDPPExecutor";
CDPPExecutor::CDPPExecutor() {
// CDBDebug("CDPPExecutor");
dataPostProcessorList = new CT::PointerList<CDPPInterface *>();
dataPostProcessorList->push_back(new CDPPIncludeLayer());
dataPostProcessorList->push_back(new CDPPAXplusB());
dataPostProcessorList->push_back(new CDPPDATAMASK);
dataPostProcessorList->push_back(new CDPPMSGCPPVisibleMask());
dataPostProcessorList->push_back(new CDPPMSGCPPHIWCMask());
dataPostProcessorList->push_back(new CDPPBeaufort());
dataPostProcessorList->push_back(new CDPPToKnots());
dataPostProcessorList->push_back(new CDPDBZtoRR());
dataPostProcessorList->push_back(new CDPPAddFeatures());
dataPostProcessorList->push_back(new CDPPGoes16Metadata());
dataPostProcessorList->push_back(new CDPPClipMinMax());
}
CDPPExecutor::~CDPPExecutor() {
// CDBDebug("~CDPPExecutor");
delete dataPostProcessorList;
}
const CT::PointerList<CDPPInterface *> *CDPPExecutor::getPossibleProcessors() { return dataPostProcessorList; }
int CDPPExecutor::executeProcessors(CDataSource *dataSource, int mode) {
for (size_t dpi = 0; dpi < dataSource->cfgLayer->DataPostProc.size(); dpi++) {
CServerConfig::XMLE_DataPostProc *proc = dataSource->cfgLayer->DataPostProc[dpi];
for (size_t procId = 0; procId < dataPostProcessorList->size(); procId++) {
int code = dataPostProcessorList->get(procId)->isApplicable(proc, dataSource);
if (code == CDATAPOSTPROCESSOR_CONSTRAINTSNOTMET) {
CDBError("Constraints for DPP %s are not met", dataPostProcessorList->get(procId)->getId());
}
/*Will be runned when datasource metadata been loaded */
if (mode == CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
if (code & CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
try {
int status = dataPostProcessorList->get(procId)->execute(proc, dataSource, CDATAPOSTPROCESSOR_RUNBEFOREREADING);
if (status != 0) {
CDBError("Processor %s failed RUNBEFOREREADING, statuscode %d", dataPostProcessorList->get(procId)->getId(), status);
}
} catch (int e) {
CDBError("Exception in Processor %s failed RUNBEFOREREADING, exceptioncode %d", dataPostProcessorList->get(procId)->getId(), e);
}
}
}
/*Will be runned when datasource data been loaded */
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
if (code & CDATAPOSTPROCESSOR_RUNAFTERREADING) {
try {
int status = dataPostProcessorList->get(procId)->execute(proc, dataSource, CDATAPOSTPROCESSOR_RUNAFTERREADING);
if (status != 0) {
CDBError("Processor %s failed RUNAFTERREADING, statuscode %d", dataPostProcessorList->get(procId)->getId(), status);
}
} catch (int e) {
CDBError("Exception in Processor %s failed RUNAFTERREADING, exceptioncode %d", dataPostProcessorList->get(procId)->getId(), e);
}
}
}
}
}
return 0;
}
int CDPPExecutor::executeProcessors(CDataSource *dataSource, int mode, double *data, size_t numItems) {
// const CT::PointerList<CDPPInterface*> *availableProcs = getPossibleProcessors();
// CDBDebug("executeProcessors, found %d",dataSource->cfgLayer->DataPostProc.size());
for (size_t dpi = 0; dpi < dataSource->cfgLayer->DataPostProc.size(); dpi++) {
CServerConfig::XMLE_DataPostProc *proc = dataSource->cfgLayer->DataPostProc[dpi];
for (size_t procId = 0; procId < dataPostProcessorList->size(); procId++) {
int code = dataPostProcessorList->get(procId)->isApplicable(proc, dataSource);
if (code == CDATAPOSTPROCESSOR_CONSTRAINTSNOTMET) {
CDBError("Constraints for DPP %s are not met", dataPostProcessorList->get(procId)->getId());
}
/*Will be runned when datasource metadata been loaded */
if (mode == CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
if (code & CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
try {
int status = dataPostProcessorList->get(procId)->execute(proc, dataSource, CDATAPOSTPROCESSOR_RUNBEFOREREADING, NULL, 0);
if (status != 0) {
CDBError("Processor %s failed RUNBEFOREREADING, statuscode %d", dataPostProcessorList->get(procId)->getId(), status);
}
} catch (int e) {
CDBError("Exception in Processor %s failed RUNBEFOREREADING, exceptioncode %d", dataPostProcessorList->get(procId)->getId(), e);
}
}
}
/*Will be runned when datasource data been loaded */
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
if (code & CDATAPOSTPROCESSOR_RUNAFTERREADING) {
try {
int status = dataPostProcessorList->get(procId)->execute(proc, dataSource, CDATAPOSTPROCESSOR_RUNAFTERREADING, data, numItems);
if (status != 0) {
CDBError("Processor %s failed RUNAFTERREADING, statuscode %d", dataPostProcessorList->get(procId)->getId(), status);
}
} catch (int e) {
CDBError("Exception in Processor %s failed RUNAFTERREADING, exceptioncode %d", dataPostProcessorList->get(procId)->getId(), e);
}
}
}
}
}
return 0;
}
/************************/
/* CDPPBeaufort */
/************************/
const char *CDPPBeaufort::className = "CDPPBeaufort";
const char *CDPPBeaufort::getId() { return "beaufort"; }
int CDPPBeaufort::isApplicable(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource) {
if (proc->attr.algorithm.equals("beaufort")) {
if (dataSource->getNumDataObjects() != 1 && dataSource->getNumDataObjects() != 2) {
CDBError("1 or 2 variables are needed for beaufort, found %d", dataSource->getNumDataObjects());
return CDATAPOSTPROCESSOR_CONSTRAINTSNOTMET;
}
return CDATAPOSTPROCESSOR_RUNAFTERREADING;
}
return CDATAPOSTPROCESSOR_NOTAPPLICABLE;
}
float CDPPBeaufort::getBeaufort(float speed) {
int bft;
if (speed < 0.3) {
bft = 0;
} else if (speed < 1.6) {
bft = 1;
} else if (speed < 3.4) {
bft = 2;
} else if (speed < 5.5) {
bft = 3;
} else if (speed < 8.0) {
bft = 4;
} else if (speed < 10.8) {
bft = 5;
} else if (speed < 13.9) {
bft = 6;
} else if (speed < 17.2) {
bft = 7;
} else if (speed < 20.8) {
bft = 8;
} else if (speed < 24.5) {
bft = 9;
} else if (speed < 28.5) {
bft = 10;
} else if (speed < 32.6) {
bft = 11;
} else {
bft = 12;
}
// CDBDebug("bft(%f)=%d", speed, bft);
return bft;
}
int CDPPBeaufort::execute(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, int mode) {
if ((isApplicable(proc, dataSource) & mode) == false) {
return -1;
}
CDBDebug("Applying beaufort %d", mode == CDATAPOSTPROCESSOR_RUNAFTERREADING);
float factor = 1;
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
if (dataSource->getNumDataObjects() == 1) {
CDBDebug("Applying beaufort for 1 element");
if (dataSource->getDataObject(0)->getUnits().equals("knot") || dataSource->getDataObject(0)->getUnits().equals("kt")) {
factor = 1852. / 3600;
}
CDBDebug("Applying beaufort for 1 element with factor %f", factor);
dataSource->getDataObject(0)->setUnits("bft");
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
float *src = (float *)dataSource->getDataObject(0)->cdfVariable->data;
float noDataValue = dataSource->getDataObject(0)->dfNodataValue;
for (size_t cnt = 0; cnt < l; cnt++) {
float speed = *src;
if (speed == speed) {
if (speed != noDataValue) {
*src = getBeaufort(factor * speed);
}
}
src++;
}
// Convert point data if needed
size_t nrPoints = dataSource->getDataObject(0)->points.size();
CDBDebug("(1): %d points", nrPoints);
for (size_t pointNo = 0; pointNo < nrPoints; pointNo++) {
float speed = (float)dataSource->getDataObject(0)->points[pointNo].v;
if (speed == speed) {
if (speed != noDataValue) {
dataSource->getDataObject(0)->points[pointNo].v = getBeaufort(factor * speed);
}
}
}
}
if (dataSource->getNumDataObjects() == 2) {
CDBDebug("Applying beaufort for 2 elements %s %s", dataSource->getDataObject(0)->getUnits().c_str(), dataSource->getDataObject(1)->getUnits().c_str());
if ((dataSource->getDataObject(0)->getUnits().equals("m/s") || dataSource->getDataObject(0)->getUnits().equals("m s-1")) && dataSource->getDataObject(1)->getUnits().equals("degree")) {
// This is a (wind speed,direction) pair
dataSource->getDataObject(0)->setUnits("bft");
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
float *src = (float *)dataSource->getDataObject(0)->cdfVariable->data;
float noDataValue = dataSource->getDataObject(0)->dfNodataValue;
for (size_t cnt = 0; cnt < l; cnt++) {
float speed = *src;
if (speed == speed) {
if (speed != noDataValue) {
*src = getBeaufort(factor * speed);
}
}
src++;
}
// Convert point data if needed
size_t nrPoints = dataSource->getDataObject(0)->points.size();
CDBDebug("(2): %d points", nrPoints);
for (size_t pointNo = 0; pointNo < nrPoints; pointNo++) {
float speed = dataSource->getDataObject(0)->points[pointNo].v;
if (speed == speed) {
if (speed != noDataValue) {
dataSource->getDataObject(0)->points[pointNo].v = getBeaufort(factor * speed);
}
}
}
}
if ((dataSource->getDataObject(0)->getUnits().equals("m/s") || dataSource->getDataObject(0)->getUnits().equals("m s-1")) &&
(dataSource->getDataObject(1)->getUnits().equals("m/s") || dataSource->getDataObject(1)->getUnits().equals("m s-1"))) {
// This is a (u,v) pair
dataSource->getDataObject(0)->setUnits("bft");
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
float *srcu = (float *)dataSource->getDataObject(0)->cdfVariable->data;
float *srcv = (float *)dataSource->getDataObject(1)->cdfVariable->data;
float noDataValue = dataSource->getDataObject(0)->dfNodataValue;
float speed;
float speedu;
float speedv;
for (size_t cnt = 0; cnt < l; cnt++) {
speedu = *srcu;
speedv = *srcv;
if ((speedu == speedu) && (speedv == speedv)) {
if ((speedu != noDataValue) && (speedv != noDataValue)) {
speed = factor * hypot(speedu, speedv);
*srcu = getBeaufort(speed);
} else {
*srcu = noDataValue;
}
}
srcu++;
srcv++;
}
// Convert point data if needed
size_t nrPoints = dataSource->getDataObject(0)->points.size();
CDBDebug("(2): %d points", nrPoints);
for (size_t pointNo = 0; pointNo < nrPoints; pointNo++) {
speedu = dataSource->getDataObject(0)->points[pointNo].v;
speedv = dataSource->getDataObject(1)->points[pointNo].v;
if ((speedu == speedu) && (speedv == speedv)) {
if ((speedu != noDataValue) && (speedv != noDataValue)) {
speed = factor * hypot(speedu, speedv);
dataSource->getDataObject(0)->points[pointNo].v = getBeaufort(speed);
} else {
dataSource->getDataObject(0)->points[pointNo].v = noDataValue;
}
}
}
CDBDebug("Deleting dataObject(1))");
delete (dataSource->getDataObject(1));
dataSource->getDataObjectsVector()->erase(dataSource->getDataObjectsVector()->begin() + 1); // Remove second element
}
}
}
return 0;
}
/************************/
/* CDPPToKnots */
/************************/
const char *CDPPToKnots::className = "CDPPToToKnots";
const char *CDPPToKnots::getId() { return "toknots"; }
int CDPPToKnots::isApplicable(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource) {
if (proc->attr.algorithm.equals("toknots")) {
if (dataSource->getNumDataObjects() != 1 && dataSource->getNumDataObjects() != 2) {
CDBError("1 or 2 variables are needed for toknots, found %d", dataSource->getNumDataObjects());
return CDATAPOSTPROCESSOR_CONSTRAINTSNOTMET;
}
return CDATAPOSTPROCESSOR_RUNAFTERREADING;
}
return CDATAPOSTPROCESSOR_NOTAPPLICABLE;
}
int CDPPToKnots::execute(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, int mode) {
if ((isApplicable(proc, dataSource) & mode) == false) {
return -1;
}
CDBDebug("Applying toknots %d", mode == CDATAPOSTPROCESSOR_RUNAFTERREADING);
float factor = 1;
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
if (dataSource->getNumDataObjects() == 1) {
CDBDebug("Applying toknots for 1 element");
if (dataSource->getDataObject(0)->getUnits().equals("m/s") || dataSource->getDataObject(0)->getUnits().equals("m s-1")) {
factor = 3600 / 1852.;
CDBDebug("Applying toknots for 1 element with factor %f to grid", factor);
dataSource->getDataObject(0)->setUnits("kts");
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
float *src = (float *)dataSource->getDataObject(0)->cdfVariable->data;
float noDataValue = dataSource->getDataObject(0)->dfNodataValue;
for (size_t cnt = 0; cnt < l; cnt++) {
float speed = *src;
if (speed == speed) {
if (speed != noDataValue) {
*src = factor * speed;
}
}
src++;
}
// Convert point data if needed
size_t nrPoints = dataSource->getDataObject(0)->points.size();
CDBDebug("(1): %d points", nrPoints);
for (size_t pointNo = 0; pointNo < nrPoints; pointNo++) {
float speed = (float)dataSource->getDataObject(0)->points[pointNo].v;
if (speed == speed) {
if (speed != noDataValue) {
dataSource->getDataObject(0)->points[pointNo].v = factor * speed;
}
}
}
}
}
if (dataSource->getNumDataObjects() == 2) {
CDBDebug("Applying toknots for 2 elements %s %s", dataSource->getDataObject(0)->getUnits().c_str(), dataSource->getDataObject(1)->getUnits().c_str());
if ((dataSource->getDataObject(0)->getUnits().equals("m/s") || dataSource->getDataObject(0)->getUnits().equals("m s-1")) && dataSource->getDataObject(1)->getUnits().equals("degree")) {
factor = 3600 / 1852.;
// This is a (wind speed,direction) pair
dataSource->getDataObject(0)->setUnits("kts");
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
float *src = (float *)dataSource->getDataObject(0)->cdfVariable->data;
float noDataValue = dataSource->getDataObject(0)->dfNodataValue;
for (size_t cnt = 0; cnt < l; cnt++) {
float speed = *src;
if (speed == speed) {
if (speed != noDataValue) {
*src = factor * speed;
}
}
src++;
}
// Convert point data if needed
size_t nrPoints = dataSource->getDataObject(0)->points.size();
CDBDebug("(2): %d points", nrPoints);
for (size_t pointNo = 0; pointNo < nrPoints; pointNo++) {
float speed = dataSource->getDataObject(0)->points[pointNo].v;
if (speed == speed) {
if (speed != noDataValue) {
dataSource->getDataObject(0)->points[pointNo].v = factor * speed;
}
}
}
}
if ((dataSource->getDataObject(0)->getUnits().equals("m/s") || dataSource->getDataObject(0)->getUnits().equals("m s-1")) &&
(dataSource->getDataObject(1)->getUnits().equals("m/s") || dataSource->getDataObject(1)->getUnits().equals("m s-1"))) {
// This is a (u,v) pair
dataSource->getDataObject(0)->setUnits("kts");
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
float *srcu = (float *)dataSource->getDataObject(0)->cdfVariable->data;
float *srcv = (float *)dataSource->getDataObject(1)->cdfVariable->data;
float noDataValue = dataSource->getDataObject(0)->dfNodataValue;
float speed;
float speedu;
float speedv;
for (size_t cnt = 0; cnt < l; cnt++) {
speedu = *srcu;
speedv = *srcv;
if ((speedu == speedu) && (speedv == speedv)) {
if ((speedu != noDataValue) && (speedv != noDataValue)) {
speed = factor * hypot(speedu, speedv);
*srcu = speed;
} else {
*srcu = noDataValue;
}
}
srcu++;
srcv++;
}
// Convert point data if needed
size_t nrPoints = dataSource->getDataObject(0)->points.size();
CDBDebug("(2): %d points", nrPoints);
for (size_t pointNo = 0; pointNo < nrPoints; pointNo++) {
speedu = dataSource->getDataObject(0)->points[pointNo].v;
speedv = dataSource->getDataObject(1)->points[pointNo].v;
if ((speedu == speedu) && (speedv == speedv)) {
if ((speedu != noDataValue) && (speedv != noDataValue)) {
speed = factor * hypot(speedu, speedv);
dataSource->getDataObject(0)->points[pointNo].v = speed;
} else {
dataSource->getDataObject(0)->points[pointNo].v = noDataValue;
}
}
}
CDBDebug("Deleting dataObject(1))");
delete (dataSource->getDataObject(1));
dataSource->getDataObjectsVector()->erase(dataSource->getDataObjectsVector()->begin() + 1); // Remove second element
}
}
}
return 0;
}
/************************/
/* CDPDBZtoRR */
/************************/
const char *CDPDBZtoRR::className = "CDPDBZtoRR";
const char *CDPDBZtoRR::getId() { return "dbztorr"; }
int CDPDBZtoRR::isApplicable(CServerConfig::XMLE_DataPostProc *proc, CDataSource *) {
if (proc->attr.algorithm.equals("dbztorr")) {
return CDATAPOSTPROCESSOR_RUNAFTERREADING | CDATAPOSTPROCESSOR_RUNBEFOREREADING;
}
return CDATAPOSTPROCESSOR_NOTAPPLICABLE;
}
float CDPDBZtoRR::getRR(float dbZ) {
// TODO: Check why -32 as input does not return 0
return pow((pow(10, dbZ / 10.) / 200), 1 / 1.6);
}
int CDPDBZtoRR::execute(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, int mode, double *data, size_t numItems) {
CDBDebug("CDPDBZtoRR");
if ((isApplicable(proc, dataSource) & mode) == false) {
return -1;
}
if (mode == CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
dataSource->getDataObject(0)->setUnits("mm/hr");
}
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
float noDataValue = dataSource->getDataObject(0)->dfNodataValue;
for (size_t j = 0; j < numItems; j++) {
if (data[j] == data[j]) { // Check if NaN
if (data[j] != noDataValue) { // Check if equal to nodatavalue of the datasource
data[j] = getRR(data[j]);
}
}
}
}
return 0;
}
int CDPDBZtoRR::execute(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, int mode) {
if ((isApplicable(proc, dataSource) & mode) == false) {
return -1;
}
if (mode == CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
dataSource->getDataObject(0)->setUnits("mm/hr");
}
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
float *src = (float *)dataSource->getDataObject(0)->cdfVariable->data;
float noDataValue = dataSource->getDataObject(0)->dfNodataValue;
for (size_t cnt = 0; cnt < l; cnt++) {
float dbZ = *src;
if (dbZ == dbZ) {
if (dbZ != noDataValue) {
*src = getRR(dbZ);
}
}
src++;
}
}
return 0;
}
/************************/
/* CDPPAddFeatures */
/************************/
const char *CDPPAddFeatures::className = "CDPPAddFeatures";
const char *CDPPAddFeatures::getId() { return "addfeatures"; }
int CDPPAddFeatures::isApplicable(CServerConfig::XMLE_DataPostProc *proc, CDataSource *) {
if (proc->attr.algorithm.equals("addfeatures")) {
return CDATAPOSTPROCESSOR_RUNAFTERREADING | CDATAPOSTPROCESSOR_RUNBEFOREREADING;
}
return CDATAPOSTPROCESSOR_NOTAPPLICABLE;
}
int CDPPAddFeatures::execute(CServerConfig::XMLE_DataPostProc *proc, CDataSource *dataSource, int mode) {
if ((isApplicable(proc, dataSource) & mode) == false) {
return -1;
}
if (mode == CDATAPOSTPROCESSOR_RUNBEFOREREADING) {
// dataSource->getDataObject(0)->cdfVariable->setAttributeText("units","mm/hr");
// dataSource->getDataObject(0)->setUnits("mm/hr");
try {
if (dataSource->getDataObject(0)->cdfVariable->getAttribute("ADAGUC_GEOJSONPOINT")) return 0;
} catch (int a) {
}
CDBDebug("CDATAPOSTPROCESSOR_RUNBEFOREREADING::Adding features from GEOJson");
CDF::Variable *varToClone = dataSource->getDataObject(0)->cdfVariable;
CDataSource::DataObject *newDataObject = new CDataSource::DataObject();
newDataObject->variableName.copy("indexes");
dataSource->getDataObjectsVector()->insert(dataSource->getDataObjectsVector()->begin() + 1, newDataObject);
newDataObject->cdfVariable = new CDF::Variable();
newDataObject->cdfObject = (CDFObject *)varToClone->getParentCDFObject();
newDataObject->cdfObject->addVariable(newDataObject->cdfVariable);
newDataObject->cdfVariable->setName("indexes");
newDataObject->cdfVariable->setType(CDF_USHORT);
newDataObject->cdfVariable->setSize(dataSource->dWidth * dataSource->dHeight);
for (size_t j = 0; j < varToClone->dimensionlinks.size(); j++) {
newDataObject->cdfVariable->dimensionlinks.push_back(varToClone->dimensionlinks[j]);
}
newDataObject->cdfVariable->removeAttribute("standard_name");
newDataObject->cdfVariable->removeAttribute("_FillValue");
newDataObject->cdfVariable->setAttributeText("standard_name", "indexes");
newDataObject->cdfVariable->setAttributeText("long_name", "indexes");
newDataObject->cdfVariable->setAttributeText("units", "1");
newDataObject->cdfVariable->setAttributeText("ADAGUC_GEOJSONPOINT", "1");
dataSource->getDataObject(0)->cdfVariable->setAttributeText("ADAGUC_GEOJSONPOINT", "1");
unsigned short sf = 65535u;
newDataObject->cdfVariable->setAttribute("_FillValue", newDataObject->cdfVariable->getType(), &sf, 1);
}
if (mode == CDATAPOSTPROCESSOR_RUNAFTERREADING) {
CDataSource featureDataSource;
if (featureDataSource.setCFGLayer(dataSource->srvParams, dataSource->srvParams->configObj->Configuration[0], dataSource->srvParams->cfg->Layer[0], NULL, 0) != 0) {
return 1;
}
featureDataSource.addStep(proc->attr.a.c_str(), NULL); // Set filename
CDataReader reader;
CDBDebug("Opening %s", featureDataSource.getFileName());
int status = reader.open(&featureDataSource, CNETCDFREADER_MODE_OPEN_ALL);
// CDBDebug("fds: %s", CDF::dump(featureDataSource.getDataObject(0)->cdfObject).c_str());
if (status != 0) {
CDBDebug("Can't open file %s", proc->attr.a.c_str());
return 1;
} else {
CDF::Variable *fvar = featureDataSource.getDataObject(0)->cdfObject->getVariableNE("featureids");
size_t nrFeatures = 0;
if (fvar == NULL) {
CDBDebug("featureids not found");
} else {
// CDBDebug("featureids found %d %d", fvar->getType(), fvar->dimensionlinks[0]->getSize());
size_t start = 0;
nrFeatures = fvar->dimensionlinks[0]->getSize();
ptrdiff_t stride = 1;
fvar->readData(CDF_STRING, &start, &nrFeatures, &stride, false);
// for (size_t i=0; i<nrFeatures; i++) {
// CDBDebug(">> %s", ((char **)fvar->data)[i]);
// }
}
char **names = (char **)fvar->data;
float destNoDataValue = dataSource->getDataObject(0)->dfNodataValue;
std::vector<std::string> valueMap;
size_t nrPoints = dataSource->getDataObject(0)->points.size();
float valueForFeatureNr[nrFeatures];
for (size_t f = 0; f < nrFeatures; f++) {
valueForFeatureNr[f] = destNoDataValue;
const char *name = names[f];
bool found = false;
for (size_t p = 0; p < nrPoints && !found; p++) {
for (size_t c = 0; c < dataSource->getDataObject(0)->points[p].paramList.size() && !found; c++) {
CKeyValue ckv = dataSource->getDataObject(0)->points[p].paramList[c];
// CDBDebug("ckv: %s %s", ckv.key.c_str(), ckv.value.c_str());
if (ckv.key.equals("station")) {
CT::string station = ckv.value;
// CDBDebug(" comparing %s %s", station.c_str(), name);
if (strcmp(station.c_str(), name) == 0) {
valueForFeatureNr[f] = dataSource->getDataObject(0)->points[p].v;
// CDBDebug("Found %s as %d (%f)", name, f, valueForFeatureNr[f]);
found = true;
}
}
}
}
}
CDF::allocateData(dataSource->getDataObject(1)->cdfVariable->getType(), &dataSource->getDataObject(1)->cdfVariable->data, dataSource->dWidth * dataSource->dHeight); // For a 2D field
// Copy the gridded values from the geojson grid to the point data's grid
size_t l = (size_t)dataSource->dHeight * (size_t)dataSource->dWidth;
unsigned short *src = (unsigned short *)featureDataSource.getDataObject(0)->cdfVariable->data;
float *dest = (float *)dataSource->getDataObject(0)->cdfVariable->data;
unsigned short noDataValue = featureDataSource.getDataObject(0)->dfNodataValue;
unsigned short *indexDest = (unsigned short *)dataSource->getDataObject(1)->cdfVariable->data;
// size_t nrFeatures=valueMap.size();
for (size_t cnt = 0; cnt < l; cnt++) {
unsigned short featureNr = *src; // index of station in GeoJSON file
*dest = destNoDataValue;
*indexDest = 65535u;
// if (cnt<30) {
// CDBDebug("cnt=%d %d %f", cnt, featureNr, (featureNr!=noDataValue)?featureNr:-9999999);
// }
if (featureNr != noDataValue) {
*dest = valueForFeatureNr[featureNr];
*indexDest = featureNr;
}
src++;
dest++;
indexDest++;
}
CDBDebug("Setting ADAGUC_SKIP_POINTS");
dataSource->getDataObject(0)->cdfVariable->setAttributeText("ADAGUC_SKIP_POINTS", "1");
dataSource->getDataObject(1)->cdfVariable->setAttributeText("ADAGUC_SKIP_POINTS", "1");
}
}
return 0;
}
|
a68b01ea6e68c8ae81ab5096324de20aa85414f9 | 01de5d9591c26cc615708fc269aca678baf2aaec | /matlab/mex/vargplvm.cpp | 0052e788d29921b4d07c9653b9bae1c81671c557 | [] | no_license | shaohua0720/vargplvm | 0ba8c7566be0438d40137eefdac69680770253d0 | 80cc7f5977caa3be5f75cf564f046bf6f7506d59 | refs/heads/master | 2023-03-17T05:56:12.098117 | 2015-05-26T22:04:52 | 2015-05-26T22:04:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,343 | cpp | vargplvm.cpp | /* INSTRUCTIONS:
* Compiling to handle exceptions (that's for typedef): for the watcom compiler
* windows: mex COMPFLAGS="$COMPFLAGS -xs" vargplvm.cpp
*/
#include "vargplvmheader.h"
#include "mex.h"
/*
* #include <R.h>
* #include <Rdefines.h>
* #include <Rinternals.h>
* #include <Rmath.h>
*/
int DEBUGno =0; ////// DEBUG (init)
//row-wise
/*
mxArray* serializeMatrix(matrix mat) {
std::vector<double> v;
for (int i=0; i < mat.size(); i++) {
for (int j=0; j < mat[0].size(); j++) {
v.push_back(mat[i][j]);
}
}
mxArray * mx = mxCreateDoubleMatrix(1,v.size(), mxREAL);
std::copy(v.begin(), v.end(), mxGetPr(mx));
return mx;
}
*/
//column-wise
mxArray* serializeMatrix(matrix mat) {
std::vector<double> v;
for (unsigned int j=0; j < mat[0].size(); j++) {
for (unsigned int i=0; i < mat.size(); i++) {
v.push_back(mat[i][j]);
}
}
mxArray * mx = mxCreateDoubleMatrix(1,v.size(), mxREAL);
// memory copy so that matlab doesnt free the memory after this point
std::copy(v.begin(), v.end(), mxGetPr(mx));
return mx;
}
mxArray* copyRow(row r) {
std::vector<double> v;
for (unsigned int i=0; i < r.size(); i++) {
v.push_back(r[i]);
}
mxArray * mx = mxCreateDoubleMatrix(1,v.size(), mxREAL);
std::copy(v.begin(), v.end(), mxGetPr(mx));
return mx;
}
// Keep in mind that MATLAB is column major, C++ is row major
matrix reshapeMatrix(double* A, int N, int Q) {
int glob =0;
row vecZero(Q,0.0);
matrix mat(N,vecZero);
for (unsigned int i=0; i<N; i++){
for (unsigned int j=0; j<Q; j++) {
mat[i][j] = A[glob++];
}
}
return mat;
}
array3d reshapeMatrix(double* A, int N, int Q, int M) {
int glob =0;
row vecZero(Q,0.0);
matrix matZero(N,vecZero);
array3d arr3d(M,matZero);
for (unsigned int i=0; i<M ; i++) {
for (unsigned int j=0; j<N; j++){
for (unsigned int k=0; k<Q; k++) {
arr3d[i][j][k] = A[glob++];
}
}
}
return arr3d;
}
void printMatrix(matrix mat) {
for (unsigned int i=0; i < mat.size(); i++) {
for (unsigned int j=0; j < mat[0].size(); j++) {
printf("%f ",mat[i][j]);
}
printf("\n");
}
}
void printMatrix(array3d ar3d) {
for (unsigned int i=0; i<ar3d.size(); i++){
for (unsigned int j=0; j<ar3d[0].size(); j++) {
for (unsigned int k=0; k<ar3d[0][0].size(); k++) {
printf("%f ",ar3d[i][j][k]);
}
printf("\n");
}
printf("\n");
}
}
void DEBUGwrite()
{
FILE *out;
out = fopen("DEBUG.txt","w");
fprintf(out, "DEBUG%d\n",DEBUGno );
DEBUGno++;
fclose(out);
}
/**********************/
void read_txtf(matrix *data, char filename[])
{
char buffer[1000000];
char *p; // p is the pointer point to the first character of buffer
int j=0;// i and j are row and column indeces of c, which are start from 0 to 2503 and 99, respectively
int count=0; // count for the number of ' '
int col = 0;
FILE *fp=fopen(filename,"r");
if( !fp)
{
cout<<"Can't open file "<< filename<< ", exiting ...\n";
cin.get();
exit(1);
}
fgets(buffer, 1000000,fp);
p = buffer;
while (*p!='\n')
{
p++;
if (*p == '\t')
col++;
}
(*data).resize(col+1);
//cout<<"data size "<<(*data).size() << " ";
while( 1 )
{
char buffer[1000000] = {'\0'};
char buffer1[1000] = {'\0'};
fgets(buffer, 1000000, fp);
p = buffer; // the pointer 'p' point to the address of the first character of buffer
if(feof(fp))
break;
while (*p != '\n')
{
if(*p == '\t')// space or not?
{
buffer1[j]='\0';
(*data)[count].push_back(atof(buffer1)); // convert string to float
count++;
j = 0;
p++;
}
else
{
buffer1[j]= *p; // to be stored in column 1
j++;
p++;
}
}
if(*p == '\n')
{
buffer1[j] = '\0';
(*data)[count].push_back(atof(buffer1));
j = 0;
}
count = 0;
j=0;
}
fclose(fp);
}
//Matrix to array
void MtoA (matrix *M, array3d *A, int d2)
{
int d3 = (*M).size()/d2;
row vec(d2, 0.0);
matrix tmp((*M)[0].size(), vec);
for (int i = 0; i < d3; i++)
{
for (int j = 0; j < d2; j++)
{
for (unsigned int x = 0; x < (*M)[0].size(); x++)
tmp[x][j] = (*M)[j+i*d2][x];
}
(*A)[i] = tmp;
}
}
// Transpose matrix
void tM (matrix *Min, matrix *Mout)
{
row A((*Min).size(), 0.0);
(*Mout).resize((*Min)[0].size(), A);
for (int i = 0; i < (*Min).size() ; i++)
{
for (int j = 0; j < (*Min)[0].size(); j++)
{
(*Mout)[j][i] = (*Min)[i][j];
}
}
}
void write_txtf(vector<double> * V, char opfile[])
{
FILE *out;
out = fopen(opfile,"w");
for (unsigned int t = 0; t<(*V).size(); t++)
{
fprintf(out, "%.17g", (*V)[t]);
if (t<=(*V).size()-1)
fprintf(out, "\n");
}
fclose(out);
}
void write_txtf_M(matrix *V, char opfile[])
{
FILE *out;
out = fopen(opfile,"w");
if ((*V).size()>0)
{
for (unsigned int t = 0; t<(*V)[0].size(); t++)
{
for(unsigned int i = 0; i<(*V).size(); i++)
{
fprintf(out, "%.17g", (*V)[i][t]);
if (i < (*V).size()-1)
fprintf(out, "\t");
}
if (t <=(*V)[0].size()-1)
fprintf(out, "\n");
}
}
fclose(out);
}
void repmatRow(row * vec, int x, int y, int z, array3d *arr)
{
matrix mat(x, (*vec));
if (y == 1)
{
for (int i = 0; i < x; i++)
{
mat[i] = (*vec);
}
}
(*arr).resize(z, mat);
for (int i = 0; i < z; i++)
{
(*arr)[i] = mat;
}
}
void repmatArr(array3d * arr, int x, int y, int z, array3d *tmp)
{
int n, m;
n = (*arr).size();
m = (*arr)[0].size();
row vec(y);
matrix mat(m,vec);
(*tmp).resize(n, mat);
if (x == 1 && z == 1)
{
for (int ii = 0; ii < n; ii++)
{
for (int j = 0; j < m; j++)
{
for (int i = 0; i < y; i++)
{
(*tmp)[ii][j][i] = (*arr)[ii][j][0];
}
}
}
}
}
void AAminus(array3d * arr1, array3d * arr2, array3d *result)
{
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0][0].size(); k++)
{
(*result)[i][j][k] = (*arr1)[i][j][k] - (*arr2)[i][j][k];
}
}
}
}
void AAdiv(array3d * arr1, array3d * arr2, array3d *result)
{
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0][0].size(); k++)
(*result)[i][j][k] = (*arr1)[i][j][k] / (*arr2)[i][j][k];
}
}
}
void AAprod(array3d * arr1, array3d * arr2, array3d *result)
{
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0][0].size(); k++)
(*result)[i][j][k] = (*arr1)[i][j][k] * (*arr2)[i][j][k];
}
}
}
void AAsum(array3d * arr1, array3d * arr2, array3d *result)
{
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0][0].size(); k++)
(*result)[i][j][k] = (*arr1)[i][j][k] + (*arr2)[i][j][k];
}
}
}
void AApow(array3d * arr1, double M, array3d *result)
{
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0][0].size(); k++)
(*result)[i][j][k] = pow((*arr1)[i][j][k], M);
}
}
}
void Asum2(array3d * arr1, array3d *result)
{
row vec(1, 0.0);
matrix mat((*arr1)[0].size(), vec);
(*result).resize((*arr1).size(), mat);
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0][0].size(); k++)
{
if (k == 0)
(*result)[i][j][0] = (*arr1)[i][j][k];
else
(*result)[i][j][0] = (*result)[i][j][0] + (*arr1)[i][j][k];
}
}
}
}
void Asum3(array3d * arr1, matrix *result)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0][0].size(); k++)
{
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
if (i == 0)
(*result)[j][k] = (*arr1)[i][j][k];
else
(*result)[j][k] = (*result)[j][k] + (*arr1)[i][j][k];
}
}
}
}
void Msum1(matrix * arr1, row *result)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1).size(); k++)
{
if (k == 0)
(*result)[j] = (*arr1)[k][j];
else
(*result)[j] = (*result)[j] + (*arr1)[k][j];
}
}
}
void MMproddot(matrix * arr1, matrix * arr2, double M, matrix *result)
{
for(unsigned int j = 0; j <(*arr1).size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0].size(); k++)
{
(*result)[j][k] = (*arr1)[j][k] * (*arr2)[j][k] * M;
}
}
}
void MMsum(matrix * arr1, matrix * arr2, matrix *result)
{
for(unsigned int j = 0; j <(*arr1).size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0].size(); k++)
{
(*result)[j][k] = (*arr1)[j][k] +(*arr2)[j][k];
}
}
}
void AAprodscalar(array3d * arr1, double M, array3d *result)
{
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0][0].size(); k++)
(*result)[i][j][k] = (*arr1)[i][j][k]*M;
}
}
}
void AAexpminus(array3d * arr1, array3d *result)
{
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0][0].size(); k++)
(*result)[i][j][k] = exp(-(*arr1)[i][j][k]);
}
}
}
double Vprodsqrt( row* arr1)
{
double result = 1.0;
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
result = result * sqrt((*arr1)[i]);
}
return result;
}
void VVsum(row * arr1, row * arr2, row *result)
{
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
(*result)[i] = (*arr1)[i] + (*arr2)[i];
}
}
void ASprodminus( array3d* arr1, double s, double m, array3d *result)
{
for(unsigned int i = 0; i < (*arr1).size(); i++)
{
for(unsigned int j = 0; j <(*arr1)[0].size(); j++)
{
for(unsigned int k = 0; k <(*arr1)[0][0].size(); k++)
(*result)[i][j][k] = 2*((*arr1)[i][j][k]) - 1;
}
}
}
void VVproddot(row * arr1, row* arr2, double M, row *result)
{
for(unsigned int j = 0; j <(*arr1).size(); j++)
{
(*result)[j] = (*arr1)[j] * (*arr2)[j] * M;
}
}
/****************************************/
//void mexFunction(int nlhs, mxArray* plhs[], int nrhs, mxArray *prhs[]){
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
double *MNQ, *A_vec, *covGrad_dim2, *means_arr, *covars_arr, *asPlus1_arr, *aDasPlus1_arr, *ZmZm_arr, *covGrad_arr;
int M,N,Q, le, Zd2, cd2;
/* Check for proper number of arguments */
if (nrhs != 9) {
mexErrMsgIdAndTxt( "MATLAB:vargplvm:invalidNumInputs",
"Nine input arguments required (double* [M, N, Q], double* A_vec, double* covGrad_dim2, double* meansTransp_arr, double* covarsTransp_arr, double* asPlus1Transp_arr, double* aDasPlus1Transp_arr, double* ZmZm_arr, double* covGrad_arr).");
} else if (nlhs > 4) {
mexErrMsgIdAndTxt( "MATLAB:yprime:maxlhs",
"Too many output arguments.");
}
//mwSize i, n;
MNQ = mxGetPr(prhs[0]);
A_vec = mxGetPr(prhs[1]);
covGrad_dim2 = mxGetPr(prhs[2]);
means_arr = mxGetPr(prhs[3]);
covars_arr = mxGetPr(prhs[4]);
asPlus1_arr = mxGetPr(prhs[5]);
aDasPlus1_arr = mxGetPr(prhs[6]);
ZmZm_arr = mxGetPr(prhs[7]);
covGrad_arr = mxGetPr(prhs[8]);
M = (int) MNQ[0];
N = (int) MNQ[1];
Q = (int) MNQ[2];
//ZmZm_arr = mxGetPr(prhs[2]);
Zd2 = Q; //(int) ZmZm_arr[0];
cd2 = (int) covGrad_dim2[0];
//mexPrintf("%f\n",A_vec[0]);///
//mexPrintf("M=%d, N=%d, Q=%d\n",M,N,Q);///////
//mexPrintf("Zd2=%d, cd2=%d\n",Zd2, cd2); ///////
//mexPrintf("%d\n",nrhs);//////
double *pA;
pA = A_vec; // !!!!! pA = real(A_vec);
//le = Q;
//int M, N, Q, le, Zd2, cd2;
////bool isarray;
//M = INTEGER_VALUE(M_int);
//N = INTEGER_VALUE(N_int);
//Q = INTEGER_VALUE(Q_int);
//Zd2 = INTEGER_VALUE(ZmZm_arr);
//cd2 = INTEGER_VALUE(covGrad_arr);
//double *pA;
//pA = REAL(A_vec);
//le = length(A_vec);
row A(Q, 0.0);
for (int i = 0; i < Q; i++)
A[i] = pA[i];
row ve(Q);
matrix means;
means = reshapeMatrix(means_arr, N,Q);
matrix covars;
covars = reshapeMatrix(covars_arr, N,Q);
matrix asPlus1;
asPlus1=reshapeMatrix(asPlus1_arr, N,Q);
matrix aDasPlus1;
aDasPlus1=reshapeMatrix(aDasPlus1_arr, N,Q);
//row vecZeroM(M*Q,0.0);
matrix dataA;//(M,vecZeroM);
// char Zm1[] = "ZmZm.txt";
//read_txtf(&dataA, Zm1);
dataA = reshapeMatrix(ZmZm_arr, M*Q,M);
//printMatrix(dataA);////
matrix data2(M,ve);
array3d ZmZm(M,data2);
MtoA (&dataA, &ZmZm, Zd2);
// printf("ZmZm in cpp %u, %u, %u, %f\n", ZmZm.size(), ZmZm[0].size(), ZmZm[0][0].size(), ZmZm[0][0][0]);////////////
int n1 = 0, m1 = 0,x1 = 0;
matrix dataB;
//char cov1[] = "covGrad.txt";
//read_txtf(&dataB, cov1);
dataB = reshapeMatrix(covGrad_arr, M*cd2, M);
m1 = cd2;
n1 = dataB.size();
x1 = dataB[0].size()/m1;
row ve3(m1,0);
matrix data3(n1,ve3);
array3d covGrad(x1,data3);
MtoA (&dataB, &covGrad, cd2);
// printf("covGrad in cpp %u, %u, %u, %.16f\n", covGrad.size(), covGrad[0].size(), covGrad[0][0].size(), covGrad[0][0][0]);//////////
//getArray(covGrad_arr, &covGrad);
row mu_n(Q);
row s2_n(Q);
row AS_n(Q);
array3d MunZmZm(ZmZm);
array3d MunZmZmA(ZmZm);
array3d k2Kern_n(covGrad);
array3d tmpA(ZmZm);
array3d k2ncovG(ZmZm);
array3d *pMunZmZm = &MunZmZm;
array3d *pMunZmZmA = &MunZmZmA;
array3d *pk2Kern_n = &k2Kern_n;
array3d *ptmpA = &tmpA;
array3d *pk2ncovG = &k2ncovG;
array3d ar2k(covGrad);
array3d *par2k = &ar2k;
matrix tmpM(M,A);
matrix *tmp = &tmpM;
matrix gVarcovars(N,mu_n);
matrix gVarmeans(gVarcovars);
matrix partInd2(M,mu_n);
row partA2(Q);
matrix Amq(M, A);
array3d ar(ZmZm);
array3d *par = &ar;
// printf("par in cpp %u, %u, %u, %f\n", (*par).size(), (*par)[0].size(), (*par)[0][0].size(), (*par)[0][0][0]);
array3d ar2(ZmZm);
array3d *par2 = &ar2;
array3d ar3(ZmZm);
array3d *par3 = &ar3;
array3d ar4(ZmZm);
array3d *par4 = &ar4;
array3d ar5(ZmZm);
array3d *par5 = &ar5;
row arV(Q);
row *parV =&arV;
row arV2(Q);
row *parV2 = &arV2;
matrix arM(M,A);
matrix *parM = &arM;
matrix arM2(M,A);
matrix *parM2 = &arM2;
//printf("here \n");
for (int n = 0; n < N; ++n)
{
mu_n = means[n];
s2_n = covars[n];
AS_n = asPlus1[n];
//printf("here 20\n");
repmatRow(&mu_n, M, 1, M, par);
//printf("par in cpp %u, %u, %u, %.16f\n", (*par).size(), (*par)[0].size(), (*par)[0][0].size(), (*par)[0][0][0]);
AAminus(par, &ZmZm, pMunZmZm);
//printf("here 21\n");
repmatRow(&AS_n, M, 1, M, par);
AAdiv(pMunZmZm, par, pMunZmZmA);
//printf("here 22\n");
AApow(pMunZmZm, double(2), par2);
repmatRow(&(aDasPlus1[n]), M, 1, M, par);
AAprod(par2, par , par3);
Asum2(par3,pk2Kern_n);
//printf("here 23\n");
AAexpminus(pk2Kern_n, par2k);
AAprodscalar(par2k, 1/Vprodsqrt(&AS_n), pk2Kern_n);
// derivatives wrt to variational means
AAprod(pk2Kern_n,&covGrad, par2k);
repmatArr(par2k, 1, Q, 1, pk2ncovG);
AAprod(pMunZmZmA,pk2ncovG,ptmpA);
Asum3(ptmpA, tmp);
//printf("here 24\n");
Msum1(tmp, parV2);
VVproddot(&A, parV2, double(-2), parV);
//printf("here 25\n");
gVarmeans[n] = *parV;
// derivatives wrt inducing inputs
MMproddot(&Amq, tmp, double(1), parM);
MMsum(&partInd2, parM, parM2);
partInd2 = *parM2;
// Derivative wrt input scales
AAprod(pMunZmZmA, pMunZmZm, pMunZmZmA);
//printf("here 26\n");
repmatRow(&s2_n, M, 1, M, par);
AAsum(pMunZmZmA, par, par2);
repmatRow(&AS_n, M, 1, M, par3);
AAprod(par2, pk2ncovG, par4);
AAdiv(par4,par3 , par5);
Asum3(par5, parM);
Msum1(parM,parV);
VVsum(&partA2, parV, parV2);
partA2 = *parV2;
// printf("here 27\n");
// derivatives wrt variational diagonal covariances
repmatRow(&A, M, 1, M, par);
AAprod(pMunZmZmA, par,pMunZmZmA);
repmatRow(&(aDasPlus1[n]), M, 1, M, par);
ASprodminus(pMunZmZmA, double (2), double(1), par4);
AAprod(par4, pk2ncovG,par3);
AAprod(par, par3 ,par2);
Asum3(par2,parM);
Msum1(parM,parV);
gVarcovars[n] = *parV;
//printf("here 2\n");
}
//printf("here 3\n");
// write to text
/*
char pI2[] = "partInd2.txt";
write_txtf_M(&partInd2, pI2);
char pA2[] = "partA2.txt";
write_txtf(&partA2, pA2);
char gVm[] = "gVarmeans.txt";
write_txtf_M(&gVarmeans, gVm);
char gVc[] = "gVarcovars.txt";
write_txtf_M(&gVarcovars, gVc);
*/
///////////
plhs[0] = serializeMatrix(partInd2);
plhs[1] = copyRow(partA2);
plhs[2] = serializeMatrix(gVarmeans);
plhs[3] = serializeMatrix(gVarcovars);
//return 1;
}
|
cda39f6eceec7024b977986d5590a3c7a28b354e | ad99308660fdc88a292fb4366956f801e4a94c9c | /lab1/cpp/matrix.h | c440a5aef50ef1f6f5214036a966b872d29483de | [] | no_license | dxahtepb/itmo-multithread | 0062b4c260ecaffdd2d8785b6817ac072d82690b | dc6dc45853c03975d05c021f41acbe746cdb8bba | refs/heads/master | 2021-02-11T11:17:21.553466 | 2020-06-15T12:12:25 | 2020-06-15T12:12:25 | 244,486,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,047 | h | matrix.h | #pragma once
#include <cstddef>
#include <type_traits>
#include <vector>
#include <stdexcept>
#include <experimental/iterator>
template<typename T = long>
class Matrix {
static_assert(std::is_arithmetic_v<T>, "Matrix should be numeric");
public:
Matrix(size_t n, size_t m) : n_{n}, m_{m}, data_(n*m) {
//empty
}
Matrix(size_t n, size_t m, bool is_orc) : n_{n}, m_{m}, data_(n * m), is_orc(is_orc) {
//empty
}
Matrix(std::initializer_list<std::initializer_list<T>> list)
: n_(list.size()), m_(list.begin()->size()), data_() {
for (auto it_row = list.begin(); it_row != list.end(); ++it_row) {
if (it_row->size() != m_) {
throw std::runtime_error("Matrix is not rectangular");
}
std::move(it_row->begin(), it_row->end(), std::back_inserter(data_));
}
}
Matrix() = delete;
Matrix(const Matrix<T>& other) = delete;
Matrix(Matrix<T>&& other) noexcept = default;
Matrix<T>& operator=(const Matrix<T> &other) = delete;
Matrix<T>& operator=(Matrix<T> &&other) noexcept = default;
~Matrix() = default;
inline decltype(auto) at(size_t row, size_t column) {
return data_[is_orc ? (column * n_ + row) : (row * m_ + column)];
}
inline decltype(auto) at(size_t row, size_t column) const {
return data_[is_orc ? (column * n_ + row) : (row * m_ + column)];
}
size_t width() const {
return m_;
}
size_t height() const {
return n_;
}
private:
size_t n_;
size_t m_;
std::vector<T> data_;
bool is_orc = false;
};
template <typename T>
std::ostream& operator<<(std::ostream& output_stream, const Matrix<T>& matrix) {
output_stream << matrix.height() << " " << matrix.width() << std::endl;
for (size_t i = 0; i < matrix.height(); ++i) {
for (size_t j = 0; j < matrix.width(); ++j) {
output_stream << matrix.at(i, j);
}
output_stream << std::endl;
}
return output_stream;
}
|
e2d4e83ee6ae4f1e5df88753e4f052c285b444ea | ed342d4782a5ea67485ce8c47f789ec3965b7df1 | /Cpp/MFCSock/ClientSocket.h | 9fa152d1f8544a3ee14dec407abfda2c7af16611 | [] | no_license | cdecl/GlassLib | 5124f3b1211d2df1f759319fae7153109e096bca | 4b94bcb5bbd12ff87665a7a597f7a83c6c90e74f | refs/heads/master | 2021-01-10T13:28:43.161268 | 2016-02-16T06:22:54 | 2016-02-16T06:22:54 | 51,808,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,989 | h | ClientSocket.h | // Socket Library
// Version : 1.0
//////////////////////////////////////////////////////////////////////
// Copyright (c) 2003 by cdecl (byung-kyu kim)
// EMail : cdecl@interpark.com
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CLIENTSOCKET_H__768A9063_6021_4DE7_B088_16C74E689CF1__INCLUDED_)
#define AFX_CLIENTSOCKET_H__768A9063_6021_4DE7_B088_16C74E689CF1__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// ClientSocket.h : header file
//
#include <algorithm>
#include <queue>
using namespace std;
#include <afxmt.h>
class CClient;
/////////////////////////////////////////////////////////////////////////////
// CClientSocket command target
class CClientSocket : public CSocket
{
public:
// Attributes
public:
CClient *m_pClient;
// Operations
public:
CClientSocket(CClient *pClient);
virtual ~CClientSocket();
// Overrides
public:
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CClientSocket)
public:
virtual void OnClose(int nErrorCode);
virtual void OnReceive(int nErrorCode);
//}}AFX_VIRTUAL
// Generated message map functions
//{{AFX_MSG(CClientSocket)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
// Implementation
protected:
public:
BOOL IsValidSocket();
void Release();
private:
CSocketFile *m_pSocketFile;
public:
void CreateArchive();
CArchive *m_pArchiveLoad;
CArchive *m_pArchiveStore;
private:
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CLIENTSOCKET_H__768A9063_6021_4DE7_B088_16C74E689CF1__INCLUDED_)
//////////////////////////////////////////////////////////////////////
// Copyright (c) 2003 by cdecl (byung-kyu kim)
// EMail : cdecl@interpark.com
////////////////////////////////////////////////////////////////////// |
bc5b528d3af54ae37992d3667e3beb6df4e9265b | 87a2896f868dc13f89ecbb629d897f0ffe8a57e6 | /Code/792a.cpp | 719291d5677e25720077cbde4b3f94d6c5fef299 | [] | no_license | sahashoo/Daily | a20a4bce60b0903fde23bea9d5244c65a9ea3928 | c209cf800cbae850e2233a149d3cc8181b49fb5e | refs/heads/master | 2020-04-23T04:31:13.770829 | 2019-02-15T20:00:34 | 2019-02-15T20:00:34 | 170,910,172 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 432 | cpp | 792a.cpp | #include<bits/stdc++.h>
#define int long long
#define F first
#define S second
using namespace std;
const int maxn=5e5+100,MOD=1e9+7,INF=1e18+7;
int n,a[maxn],mn=INF,cnt;
int32_t main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
for(int i=0;i<n;i++)cin>>a[i];
sort(a,a+n);
for(int i=0;i<n-1;i++){
int d=abs(a[i]-a[i+1]);
if(mn>d)mn=d,cnt=0;
if(mn==d)cnt++;
}
cout<<mn<<" "<<cnt;
} |
cf440ae9dba06335c937e77a07d28361de8031be | 9241d6ca884b63e0abae80f13d6bbf7eeb818c1e | /FastCat/Dependencies/maya/maya/MFnToolContext.h | b23af9ebea1c8c55ca3f96b249a1dbaed8c1f72b | [] | no_license | AlexMiller12/FastCatVS2013 | 100022c6ed5206903bc10c65e05cebf3a79c4f45 | b93df56cc10e109e9f9b62ccd0cad5fc8be983ae | refs/heads/master | 2021-01-13T00:48:59.076862 | 2016-05-06T20:17:48 | 2016-05-06T20:17:48 | 52,799,609 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,847 | h | MFnToolContext.h |
#ifndef _MFnToolContext
#define _MFnToolContext
//
//-
// ===========================================================================
// Copyright 2013 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
// ===========================================================================
//+
//
// CLASS: MFnToolContext
//
// *****************************************************************************
#if defined __cplusplus
// *****************************************************************************
// INCLUDED HEADER FILES
#include <maya/MFnBase.h>
#include <maya/MString.h>
#include <maya/MObject.h>
// *****************************************************************************
// DECLARATIONS
#ifdef _WIN32
#pragma warning(disable: 4522)
#endif // _WIN32
// *****************************************************************************
// CLASS DECLARATION (MFnToolContext)
//! \ingroup OpenMaya MFn
//! \brief Tool context function set.
/*!
MFnToolContext is the function set that is used for querying tool contexts.
Typically this could be used in conjunction with MGlobal::currentToolContext().
*/
class OPENMAYAUI_EXPORT MFnToolContext : public MFnBase
{
declareMFn(MFnToolContext, MFnBase);
public:
MString name( MStatus* = NULL ) const;
MString title( MStatus* = NULL ) const;
BEGIN_NO_SCRIPT_SUPPORT:
declareMFnConstConstructor( MFnToolContext, MFnBase );
END_NO_SCRIPT_SUPPORT:
private:
};
#ifdef _WIN32
#pragma warning(default: 4522)
#endif // _WIN32
// *****************************************************************************
#endif /* __cplusplus */
#endif /* _MFnToolContext */
|
392866576a388a782b88d02991843875c8260346 | 2e60ec3492a3ba55704bf35fe4f57711b2d8ae8d | /Mixer/Zaher/audiomidiconverter/z_audiomidiconverter.cpp | 6351c87e02fa64390dd076042ce161019f78ddea | [] | no_license | NZBinome/Notefy | c89d544cb786377a87d848ad13f93f2584029ca6 | 9f9a06d79fc3933c52ebb65e53a670a0636a701b | refs/heads/master | 2021-01-15T14:28:36.533511 | 2015-05-18T16:40:55 | 2015-05-18T16:41:06 | 31,070,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,828 | cpp | z_audiomidiconverter.cpp | #include <fstream>
#include "../freq/freqtable.h"
#include "../libaiff/libaiff/libaiff.h"
#include "../audioread/aiffread.h"
#include "../wavFormat/diviseur.h"
#include "../signal/complex.h"
#include "../signal/signal.h"
#include "../signal/mixer.h"
#include "../midi/note.h"
#include "../signal/melody.h"
#include "../audioread/wavread.h"
#include "../libmel/melfile.h"
#include "../audiowrite/aiffwrite.h"
#include "z_audiomidiconverter.h"
#include <string.h>
enum FileType{
MID,
AIF,
WAV,
INV
};
inline FileType _z_amc_getFileTye(char *f)
{
int n=strlen(f);
char end[4];
for(int i=0;i<4;++i)
{
end[i]=f[n+i-4];
}
if(end[0]=='.')
{
if(end[1]=='m'&&end[2]=='i'&&end[3]=='d')
return MID;
else if(end[1]=='a'&&end[2]=='i'&&end[3]=='f')
return AIF;
else if(end[1]=='w'&&end[3]=='a'&&end[3]=='v')
return WAV;
}
return INV;
}
Z_audioMidiConverter::Z_audioMidiConverter()
{
}
void Z_audioMidiConverter::melToMid(Melody &m, char* filename)
{
MidiCreator c(m.fs());
Note n;
for(int i=0;i<m.n();++i)
{
double v[2];
m.valueAt(i,v);
n.findNote(v[0],m.scale());
n.findVolume(v[1]);
n.set_d(m.l());
c.addNote(n);
}
c.creerMidiFile(filename);
}
int Z_audioMidiConverter::convert(char *audioFile, char *midiFile)
{
const int gw=4; //gauss window
int n=strlen(audioFile);
AudioRead *f;
if(_z_amc_getFileTye(audioFile)==WAV)
{
f=new Wavread();
if(!f->open(audioFile))
return 0;
}
else if(_z_amc_getFileTye(audioFile)==AIF)
{
f=new AiffRead();
if(!f->open(audioFile))
return 0;
}
else
return 0;
Diviseur d(f->buffer(),f->l(),f->fs(),f->ba(),f->nc());
Signal s;
Melody m(d.d(),f->fs());
for(int i=0;i<d.d();++i)
{
s.set(d[i],f->fs(),d.ld(),f->ba(),f->nc());
m.append(s.fc(),s.p());
}
delete f;
m.set_l(s.l());
m.filtreBilateral(gw);
strcpy(midiFile,audioFile);
midiFile[n-3]='m';
midiFile[n-2]='e';
midiFile[n-1]='l';
midiFile[n]=0;
m.setScales();
MelFile mf;
mf.getFrom(m);
mf.create(midiFile);
midiFile[n-3]='m';
midiFile[n-2]='i';
midiFile[n-1]='d';
midiFile[n]=0;
melToMid(m,midiFile);
return 1;
}
unsigned short Z_audioMidiConverter::getInstrument(char * filename)
{
std::fstream f;
f.open(filename,std::ios::in|std::ios::binary);
f.seekg(22,std::ios::beg);
char c[3];
f.read(c,3*sizeof(char));
f.close();
return c[2];
}
void Z_audioMidiConverter::chooseInstrument(unsigned char inst, char * filename)
{
std::fstream f;
f.open(filename,std::ios::in|std::ios::out|std::ios::binary);
f.seekp(22,std::ios::beg);
char c[3];
c[0]=0;
c[1]=192;
c[2]=inst;
f.write(c,3*sizeof(char));
f.close();
}
void Z_audioMidiConverter::fix(char *filename, bool deFix)
{
char melfile[256];
int n=strlen(filename);
strcpy(melfile,filename);
short inst=getInstrument(filename);
melfile[n-3]='m';
melfile[n-2]='e';
melfile[n-1]='l';
melfile[n]=0;
Melody m;
MelFile mf;
mf.manipulate(melfile);
mf.getInfo();
mf.getFreq();
mf.getScal();
mf.getCoqa();
mf.writeTo(m);
if(deFix)
m.deFix();
else
{
if(!mf.isCorrected())
{
m.decompose();
mf.set_dft_dnp_dnpqt(m.correct(),m.distPlace(),0,m.distNum());
}
else
{
m.incScale();
mf.choose_cs(m.scaleN());
}
}
melToMid(m,filename);
mf.flush();
chooseInstrument(inst,filename);
}
void Z_audioMidiConverter::mix(const char **f, int n, const char *df)
{
AudioRead **af=new AudioRead*[n];
for(int i=0;i<n;++i)
{
switch(_z_amc_getFileTye(f[i]))
{
case AIF:
af[i]=new AiffRead();
break;
case WAV:
af[i]=new Wavread();
break;
case MID:
throw("not suported yet");
default:
throw("not supported files");
}
}
Signal *s=new Signal[n];
for(int i=0;i<n;++i)
{
af[i]->open(f[i]);
s[i].set(af[i]->buffer(),af[i]->fs(),af[i]->l(),af[i]->ba(),af[i]->nc());
}
Mixer m;
m.addSignals(s,n);
Signal *mix=m.mix();
AiffWrite aw;
int ba=2;
aw.set_l(mix->l()*ba);
aw.set_fs(mix->fs());
aw.set_ba(ba);
aw.set_buffer(mix->rawData(ba));
aw.write(df);
delete [] s;
for(int i=0;i<n;++i)
{
delete af[i];
}
delete [] af;
}
Z_audioMidiConverter::~Z_audioMidiConverter()
{
}
|
1831329bfccadcf278a799373bed67972c4832f3 | b7fa1e7bc65e5259393635a1aa71105ac573b8f2 | /include/pgmlink/features/tracking_feature_extractor.h | 36c72cef539121c8a48d20f03d98e7ff998033c9 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | ilastik/pgmlink | 8de5e4665f4e38ab1bce623e57668a3c71fab5fa | cf4d3da9c72312a3c2076b7af4b95d8e8344b1f2 | refs/heads/master | 2021-01-14T11:43:50.052996 | 2016-09-19T12:29:30 | 2016-09-19T12:29:30 | 48,373,377 | 0 | 0 | null | 2016-09-19T12:29:31 | 2015-12-21T13:32:39 | C++ | UTF-8 | C++ | false | false | 8,905 | h | tracking_feature_extractor.h | #ifndef TRACKING_FEATURE_EXTRACTOR_H
#define TRACKING_FEATURE_EXTRACTOR_H
#include "pgmlink/hypotheses.h"
#include "pgmlink/features/higher_order_features.h"
namespace pgmlink
{
namespace features
{
class MinMaxMeanVarCalculator
{
public:
MinMaxMeanVarCalculator();
void reset();
void add_value(const double& value);
void add_values(const FeatureMatrix& v);
size_t get_count() const;
double get_mean() const;
double get_var() const;
double get_min() const;
double get_max() const;
private:
std::vector<double> values;
};
class TrackingFeatureExtractorBase
{
public:
typedef std::vector<double> JointFeatureVector;
typedef std::vector<std::string> FeatureDescriptionVector;
public:
PGMLINK_EXPORT TrackingFeatureExtractorBase() {};
virtual PGMLINK_EXPORT size_t get_feature_vector_length() const = 0;
virtual PGMLINK_EXPORT void get_feature_descriptions(
FeatureDescriptionVector& feature_descriptions) const;
protected:
virtual PGMLINK_EXPORT void init_compute(FeatureVectorView return_vector);
virtual PGMLINK_EXPORT void push_back_feature(
std::string feature_name,
double feature_value);
virtual PGMLINK_EXPORT void push_back_feature(
std::string feature_name,
const MinMaxMeanVarCalculator& mmmv_calculator);
FeatureVectorView::iterator feature_vector_it_;
FeatureDescriptionVector::iterator feature_descriptions_it_;
FeatureDescriptionVector feature_descriptions_;
};
class TrackFeatureExtractor : public TrackingFeatureExtractorBase
/* TODO:
- add track length as a feature as well?
*/
{
public:
PGMLINK_EXPORT TrackFeatureExtractor();
PGMLINK_EXPORT void compute_features(
ConstTraxelRefVector& traxelref_vec,
FeatureVectorView return_vector);
PGMLINK_EXPORT void compute_features(
ConstTraxelRefVectors& traxelref_vecs,
FeatureMatrix& return_matrix);
PGMLINK_EXPORT virtual size_t get_feature_vector_length() const;
private:
void compute_sq_id_features(ConstTraxelRefVector&, std::string);
void compute_sq_diff_features(ConstTraxelRefVector&, std::string);
void compute_sq_curve_features(ConstTraxelRefVector&, std::string);
void compute_angle_features(ConstTraxelRefVector&, std::string);
};
class DivisionFeatureExtractor : public TrackingFeatureExtractorBase
{
public:
PGMLINK_EXPORT DivisionFeatureExtractor();
PGMLINK_EXPORT void compute_features(
ConstTraxelRefVector& traxelref_vec,
FeatureVectorView return_vector);
PGMLINK_EXPORT void compute_features(
ConstTraxelRefVectors& traxelref_vecs,
FeatureMatrix& return_matrix);
virtual PGMLINK_EXPORT size_t get_feature_vector_length() const;
private:
void compute_id_features(ConstTraxelRefVector&, std::string);
void compute_sq_diff_features(ConstTraxelRefVector&, std::string);
void compute_angle_features(ConstTraxelRefVector&, std::string);
};
/**
* @brief Takes a set of events from a tracking solution and computes a bunch of features for struct learning.
* @author Carsten Haubold
*/
class TrackingFeatureExtractor
{
public:
typedef std::vector<double> JointFeatureVector;
typedef std::vector<std::string> FeatureDescription;
private:
/// Forbid usage of default constructor
PGMLINK_EXPORT TrackingFeatureExtractor();
public:
/// Create the extractor given a hypotheses graph
PGMLINK_EXPORT TrackingFeatureExtractor(boost::shared_ptr<HypothesesGraph> graph,
const FieldOfView &fov);
/// Create the extractor given a hypotheses graph with filter function
PGMLINK_EXPORT TrackingFeatureExtractor(boost::shared_ptr<HypothesesGraph> graph,
const FieldOfView &fov,
boost::function<bool (const Traxel&)> margin_filter_function);
/// Train the svms with the given hypotheses graph assuming that the arc and
/// node active map contain a correct labeling
PGMLINK_EXPORT void train_track_svm();
PGMLINK_EXPORT void train_division_svm();
#ifdef WITH_DLIB
/// set and get for the outlier svms
PGMLINK_EXPORT boost::shared_ptr<SVMOutlierCalculator> get_track_svm() const;
PGMLINK_EXPORT boost::shared_ptr<SVMOutlierCalculator> get_division_svm() const;
PGMLINK_EXPORT void set_track_svm(boost::shared_ptr<SVMOutlierCalculator> track_svm);
PGMLINK_EXPORT void set_division_svm(boost::shared_ptr<SVMOutlierCalculator> division_svm);
#endif
/// Get the complete vector of features computed for the currently set solution
PGMLINK_EXPORT void get_feature_vector(JointFeatureVector& feature_vector) const;
/// Return a short description of the feature at the given index in the feature vector
PGMLINK_EXPORT const std::string get_feature_description(size_t feature_index) const;
/// Dispatch computation of features here
PGMLINK_EXPORT void compute_features();
/// Set HDF5 filename to which the features of all tracks will be written
PGMLINK_EXPORT void set_track_feature_output_file(const std::string& filename);
/// Append features for this solution to the given file.
/// If file does not exist, create it.
/// Comments are ignored, and will not be copied to the edited file
PGMLINK_EXPORT void append_feature_vector_to_file(const std::string &filename);
private:
void push_back_feature(std::string feature_name, double feature_value);
void push_back_feature(
std::string feature_name,
const MinMaxMeanVarCalculator& mmmv_calculator);
void save_features_to_h5(size_t track_id, const std::string& feature_name, FeatureMatrix &matrix, bool tracks = true);
void save_traxel_ids_to_h5(ConstTraxelRefVectors& track_traxels);
void save_division_traxels_to_h5(ConstTraxelRefVectors &division_traxels);
/**
* methods that compute each feature
*/
void compute_sq_diff_features(ConstTraxelRefVectors&, std::string);
void compute_sq_accel_features(ConstTraxelRefVectors&, std::string);
void compute_angle_features(ConstTraxelRefVectors&, std::string);
void compute_track_length_features(ConstTraxelRefVectors&);
void compute_id_features(ConstTraxelRefVectors&, const std::string&, bool is_track = true);
void compute_track_id_outlier(ConstTraxelRefVectors&, std::string);
void compute_track_diff_outlier(ConstTraxelRefVectors&, std::string);
void compute_svm_track_feature_outlier(ConstTraxelRefVectors&tracks);
void compute_division_sq_diff_features(ConstTraxelRefVectors&, std::string);
void compute_division_sq_diff_outlier(ConstTraxelRefVectors&, std::string);
void compute_child_deceleration_features(ConstTraxelRefVectors&, std::string);
void compute_child_deceleration_outlier(ConstTraxelRefVectors&, std::string);
void compute_division_angle_features(ConstTraxelRefVectors&, std::string);
void compute_division_angle_outlier(ConstTraxelRefVectors&, std::string);
void compute_svm_division_feature_outlier(ConstTraxelRefVectors&);
void compute_border_distances(ConstTraxelRefVectors&, std::string);
// TODO: add many more
/**
* methods that compute all features
*/
void compute_all_division_features();
void compute_all_app_dis_features();
void compute_all_track_features();
private:
boost::shared_ptr<SquaredDiffCalculator> sq_diff_calc_ptr_;
boost::shared_ptr<DiffCalculator> diff_calc_ptr_;
boost::shared_ptr<SquaredCurveCalculator> sq_curve_calc_ptr_;
boost::shared_ptr<MinCalculator<0> > row_min_calc_ptr_;
boost::shared_ptr<MaxCalculator<0> > row_max_calc_ptr_;
#ifdef WITH_DLIB
boost::shared_ptr<SVMOutlierCalculator> svm_track_outlier_calc_ptr_;
boost::shared_ptr<SVMOutlierCalculator> svm_div_outlier_calc_ptr_;
#endif
boost::shared_ptr<SquaredMahalanobisCalculator> sq_mahal_calc_ptr_;
boost::shared_ptr<AngleCosineCalculator> angle_cos_calc_ptr_;
boost::shared_ptr<ChildParentDiffCalculator> child_parent_diff_calc_ptr_;
boost::shared_ptr<SquaredNormCalculator<0> > sq_norm_calc_ptr_;
boost::shared_ptr<ChildDeceleration> child_decel_calc_ptr_;
boost::shared_ptr<DivAngleCosineCalculator> div_angle_calc_ptr_;
FieldOfView fov_;
boost::function<bool (const Traxel&)> margin_filter_function_;
JointFeatureVector joint_feature_vector_;
FeatureDescription feature_descriptions_;
boost::shared_ptr<HypothesesGraph> graph_;
std::string track_feature_output_file_;
};
class BorderDistanceFilter
{
public:
PGMLINK_EXPORT BorderDistanceFilter(
const FieldOfView& field_of_view,
double t_margin,
double spatial_margin);
PGMLINK_EXPORT bool is_out_of_margin(const Traxel& traxel) const;
private:
FieldOfView fov_;
};
} // end namespace features
} // end namespace pgmlink
#endif // TRACKING_FEATURE_EXTRACTOR_H
|
4e3284d3584279e6528979ead0abba0939cf084a | 6f6e378ea2a3e23d3ecefb1f8ff4e847a7dcda68 | /tinyember/TinyEmberPlus/main.cpp | 1ab9bbfc656f5f3af8a919475bf32abbc938983c | [
"BSL-1.0",
"LicenseRef-scancode-dco-1.1"
] | permissive | Lawo/ember-plus | 878b772f2dff07821019690ba91a72095bf68081 | b42f3143c89f093e01362da69fb39686d0f1bd9e | refs/heads/master | 2023-04-02T17:03:47.304757 | 2023-03-30T12:38:39 | 2023-03-30T12:38:39 | 40,001,159 | 99 | 54 | BSL-1.0 | 2023-03-06T08:30:53 | 2015-07-31T10:55:18 | C++ | UTF-8 | C++ | false | false | 3,245 | cpp | main.cpp | /*
Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.com).
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include "TinyEmberPlus.h"
#include <memory>
#include <QtGui>
#include "gadget/Subscriber.h"
#include "glow/ConsumerProxy.h"
#include "glow/ProviderInterface.h"
/**
* The LocalScheduler class marshalls asynchronous consumer request to the ui thread,
* where the requests are being handled.
*/
class LocalScheduler : public glow::ProviderInterface
{
public:
/** Constructor */
LocalScheduler()
: m_provider(nullptr)
{
}
/** Destructor */
virtual ~LocalScheduler()
{
}
/**
* Forwards the request to the attached provider implementation.
* @param node The gadget tree sent by a consumer.
* @param subscriber The subscriber object representing the consumer.
*/
virtual void notifyAsync(libember::dom::Node* node, gadget::Subscriber* subscriber)
{
auto provider = m_provider;
if (provider != nullptr)
provider->notifyAsync(node, subscriber);
}
/**
* Forwards the register request to the attached provider implementation.
* @param subscriber The subscriber object representing the consumer.
*/
virtual void registerSubscriberAsync(gadget::Subscriber* subscriber)
{
auto provider = m_provider;
if (provider != nullptr)
provider->registerSubscriberAsync(subscriber);
}
/**
* Forwards the unregister request to the attached provider implementation.
* @param subscriber The subscriber object representing the consumer.
*/
virtual void unregisterSubscriberAsync(gadget::Subscriber* subscriber)
{
auto provider = m_provider;
if (provider != nullptr)
provider->unregisterSubscriberAsync(subscriber);
}
/**
* Updates the provider where consumer requests are forwarded to.
* @param provider The provider to forward consumer requests to.
*/
void setSynchronizationObject(glow::ProviderInterface* provider)
{
m_provider = provider;
}
private:
glow::ProviderInterface* m_provider;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
auto first = argv;
auto const last = argv + argc;
auto port = short(9000);
for (; first != last; first++)
{
auto const item = QString(*first);
if (item.contains("port", Qt::CaseInsensitive) && (std::next(first) != last))
{
std::advance(first, 1);
port = QString(*first).toShort();
break;
}
}
auto result = -1;
{
LocalScheduler scheduler;
glow::ConsumerProxy proxy(&app, &scheduler, port);
TinyEmberPlus window(&proxy);
window.show();
scheduler.setSynchronizationObject(&window);
result = app.exec();
proxy.close();
}
return result;
}
|
1fe5aaf1b32d8bee464e65af991cefa88778cc0b | ead2601236ed17193f28cce5912a93d71fc2e90f | /codeforces/.vscode/384Div2/tempCodeRunnerFile.cpp | 8db7a9d5b4a612e3ab71dfa952b4c2fb0fa46754 | [] | no_license | AdityaKarn/cp-cpp | bcbb6f6be7fa0d657506d56fa248dd22ff8a3b41 | 1f885d5eae32fdaf45d943feeccbaf94fddcdf53 | refs/heads/master | 2023-02-15T03:53:57.917215 | 2021-01-11T12:47:34 | 2021-01-11T12:47:34 | 255,907,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31 | cpp | tempCodeRunnerFile.cpp | cout << i << " " << mx << "\n"; |
c40204765db7d6af2bc28e33f81ec811019ead84 | 3af87498fd11b1f3c72411e987552fb5062ee335 | /test/ber_types/IdentifierTest.cpp | d5978bb68450b8c68d010ea4554f3dd0d11b7c29 | [
"BSL-1.0"
] | permissive | ibiscum/fast_ber | 9443c0736a371dd471bea0a6ce9bfbabb2c72fa6 | d3e790f86ff91df8b6d6a0f308803606f59452af | refs/heads/master | 2023-07-07T06:09:15.684227 | 2021-08-08T11:27:49 | 2021-08-08T11:27:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,382 | cpp | IdentifierTest.cpp | #include "fast_ber/ber_types/Identifier.hpp"
#include "fast_ber/ber_types/Integer.hpp"
#include "fast_ber/util/DecodeHelpers.hpp"
#include "fast_ber/util/EncodeHelpers.hpp"
#include <catch2/catch.hpp>
TEST_CASE("Identifier: Encode ExplicitIdentifier")
{
fast_ber::Integer<> i(4);
std::array<uint8_t, 100> buffer = {};
std::array<uint8_t, 3> expected = {0x02, 0x01, 0x04};
size_t enc_size = fast_ber::encoded_length(i);
size_t size = fast_ber::encode(absl::Span<uint8_t>(buffer.data(), buffer.size()), i).length;
REQUIRE(size == 3);
REQUIRE(enc_size == 3);
REQUIRE(absl::MakeSpan(buffer.data(), 3) == absl::MakeSpan(expected));
}
TEST_CASE("Identifier: Encode TaggedExplicitIdentifier")
{
fast_ber::Integer<fast_ber::DoubleId<fast_ber::Id<fast_ber::Class::context_specific, 20>,
fast_ber::ExplicitId<fast_ber::UniversalTag::integer>>>
i(4);
std::array<uint8_t, 100> buffer = {};
std::array<uint8_t, 5> expected = {0xB4, 0x03, 0x02, 0x01, 0x04};
size_t enc_size = fast_ber::encoded_length(i);
size_t size = fast_ber::encode(absl::Span<uint8_t>(buffer.data(), buffer.size()), i).length;
REQUIRE(size == 5);
REQUIRE(enc_size == 5);
REQUIRE(absl::MakeSpan(buffer.data(), 5) == absl::MakeSpan(expected));
}
TEST_CASE("Identifier: Encode Id")
{
fast_ber::Integer<fast_ber::Id<fast_ber::Class::context_specific, 20>> i(4);
std::array<uint8_t, 100> buffer = {};
std::array<uint8_t, 3> expected = {0x94, 0x01, 0x04};
size_t enc_size = fast_ber::encoded_length(i);
size_t size = fast_ber::encode(absl::Span<uint8_t>(buffer.data(), buffer.size()), i).length;
REQUIRE(size == 3);
REQUIRE(enc_size == 3);
REQUIRE(absl::MakeSpan(buffer.data(), 3) == absl::MakeSpan(expected));
}
TEST_CASE("Identifier: Decode ExplicitIdentifier")
{
std::array<uint8_t, 3> data = {0x02, 0x01, 0x04};
auto iterator = fast_ber::BerViewIterator(absl::Span<uint8_t>(data.data(), data.size()));
fast_ber::Integer<> i = 500;
bool success = fast_ber::decode(iterator, i).success;
REQUIRE(success);
REQUIRE(i == 4);
}
TEST_CASE("Identifier: Decode TaggedExplicitIdentifier")
{
std::array<uint8_t, 5> data = {0xB4, 0x03, 0x02, 0x01, 0x04};
auto iterator = fast_ber::BerViewIterator(absl::Span<uint8_t>(data.data(), data.size()));
fast_ber::Integer<fast_ber::DoubleId<fast_ber::Id<fast_ber::Class::context_specific, 20>,
fast_ber::ExplicitId<fast_ber::UniversalTag::integer>>>
i = 500;
bool success = fast_ber::decode(iterator, i).success;
REQUIRE(success);
REQUIRE(i == 4);
}
TEST_CASE("Identifier: Decode Id")
{
std::array<uint8_t, 3> data = {0x94, 0x01, 0x04};
auto iterator = fast_ber::BerViewIterator(absl::Span<uint8_t>(data.data(), data.size()));
fast_ber::Integer<fast_ber::Id<fast_ber::Class::context_specific, 20>> i = 500;
bool success = fast_ber::decode(iterator, i).success;
REQUIRE(success);
REQUIRE(i == 4);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.