text
stringlengths 8
6.88M
|
|---|
#include "unknown_pong.h"
//Initializes SDL and handles all errors
bool Unknown_pong::initSDL(std::string title, int width, int height) {
bool success = true;
if (SDL_Init(SDL_INIT_VIDEO) < 0) { //TODO: Probably will be replaced by SDL_INIT_EVERYTHING
Logger::logErrorSDL("Failed to initialize SDL!");
success = false;
} else {
Global::window = SDL_CreateWindow(title.c_str(),
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
width,
height,
0); //TODO: Add SDL_WINDOW_FULLSCREEN
if (Global::window == 0) {
Logger::logErrorSDL("SDL error while creating a window!");
success = false;
} else {
Global::renderer = SDL_CreateRenderer(Global::window,
-1,
SDL_RENDERER_ACCELERATED);
if (Global::renderer == 0) {
Logger::logErrorSDL("Failed to create renderer!");
success = false;
} else {
//TODO: IMG_Init in case the program will use textures as well
}
}
}
return success;
}
//Safely handles the closing of the whole program
void Unknown_pong::close() {
SDL_DestroyWindow(Global::window);
SDL_Quit();
}
//The event that's called by SDL's timers. It sends an SDL_USEREVENT to the message queue with a parameter attached
uint32 Unknown_pong::timerCallbackSDL(uint32 interval, void *param) {
SDL_Event event;
SDL_UserEvent userEvent = {};
userEvent.type = SDL_USEREVENT;
userEvent.code = (int32)param;
event.type = SDL_USEREVENT;
event.user = userEvent;
SDL_PushEvent(&event);
return interval;
}
//Initializes SDL timers
void Unknown_pong::initTimers(int fpsLimit) {
int fpsDelay = MILLISECONDS_IN_A_SECOND / fpsLimit; //The amount of milliseconds that should pass between each frame
if (SDL_AddTimer(fpsDelay, timerCallbackSDL, (int32 *)TIMER_FPS) == 0) {
Logger::logErrorSDL("Error while creating the FPS timer!");
}
}
int Unknown_pong::start() {
bool isGameRunning = true;
//TODO: Read in these values from a file
int windowWidth = 800;
int windowHeight = 600;
int fpsLimit = 144;
initSDL(Global::gameName, windowWidth, windowHeight);
FsHandler::initFolders();
Logger::clearLogFile();
initTimers(fpsLimit);
const uint8* keyboardState = SDL_GetKeyboardState(0); //Updates every time SDL_PollEvent() is called
//This is the main game loop
while (isGameRunning) {
SDL_Event sdlEvent;
while (SDL_PollEvent(&sdlEvent)) {
switch (sdlEvent.type) {
case SDL_USEREVENT:
if (sdlEvent.user.code == TIMER_FPS) {
InputHandler::handleKeyboardInput(keyboardState);
} else if (sdlEvent.user.code == TIMER_TICKS) {
//TODO: Implement ticks
}
break;
case SDL_QUIT:
isGameRunning = false;
break;
}
}
}
close();
return 0;
}
|
#include <stdio.h>
// DirectX 12 specific headers.
#include <d3d12.h>
#include <dxgi1_6.h>
#include <d3dcompiler.h>
#include <DirectXMath.h>
#if !defined(NDEBUG) && !defined(_DEBUG)
#error "Define at least one."
#elif defined(NDEBUG) && defined(_DEBUG)
#error "Define at most one."
#endif
#if defined(_WIN64)
#if defined(_DEBUG)
#pragma comment (lib, "lib/64/SDL2-staticd")
#else
#pragma comment (lib, "lib/64/SDL2-static")
#endif
#else
#if defined(_DEBUG)
#pragma comment (lib, "lib/32/SDL2-staticd")
#else
#pragma comment (lib, "lib/32/SDL2-static")
#endif
#endif
#pragma comment (lib, "Imm32")
#pragma comment (lib, "Setupapi")
#pragma comment (lib, "Version")
#pragma comment (lib, "Winmm")
#pragma comment (lib, "d3d12")
#pragma comment (lib, "dxgi")
#pragma comment (lib, "dxguid")
#pragma comment (lib, "uuid")
#pragma comment (lib, "gdi32")
#define _CRT_SECURE_NO_WARNINGS 1
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#define SDL_MAIN_HANDLED
#include "SDL2/SDL.h"
#include <cstdio>
#include <algorithm>
//// Windows Runtime Library. Needed for Microsoft::WRL::ComPtr<> template class.
//#include <wrl.h>
//using namespace Microsoft::WRL;
/*
d3d12.lib
dxgi.lib
dxguid.lib
uuid.lib
kernel32.lib
user32.lib
gdi32.lib
winspool.lib
comdlg32.lib
advapi32.lib
shell32.lib
ole32.lib
oleaut32.lib
odbc32.lib
odbccp32.lib
runtimeobject.lib
*/
#define SUCCEEDED(hr) (((HRESULT)(hr)) >= 0)
#define FAILED(hr) (((HRESULT)(hr)) < 0)
#define CHECK_AND_FAIL(hr) \
if (FAILED(hr)) { \
::printf("[ERROR] " #hr "() failed. \n"); \
::abort(); \
} \
/**/
#if defined(_DEBUG)
#define ENABLE_DEBUG_LAYER 1
#else
#define ENABLE_DEBUG_LAYER 0
#endif
int main ()
{
// SDL_Init
SDL_Init(SDL_INIT_VIDEO);
// Enable Debug Layer
#if ENABLE_DEBUG_LAYER > 0
ID3D12Debug * debug_interface_dx = nullptr;
if(SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug_interface_dx)))) {
debug_interface_dx->EnableDebugLayer();
}
#endif
// Create a Window
SDL_Window * wnd = SDL_CreateWindow("LearningD3D12", 0, 0, 1280, 720, 0);
if(nullptr == wnd) {
::abort();
}
// Query Adapter (PhysicalDevice)
IDXGIFactory * dxgi_factory = nullptr;
CHECK_AND_FAIL(CreateDXGIFactory(IID_PPV_ARGS(&dxgi_factory)));
constexpr uint32_t MaxAdapters = 8;
IDXGIAdapter * adapters[MaxAdapters] = {};
IDXGIAdapter * pAdapter;
for (UINT i = 0; dxgi_factory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND; ++i)
{
adapters[i] = pAdapter;
DXGI_ADAPTER_DESC adapter_desc = {};
::printf("GPU Info [%d] :\n", i);
if(SUCCEEDED(pAdapter->GetDesc(&adapter_desc))) {
::printf("\tDescription: %ls\n", adapter_desc.Description);
::printf("\tDedicatedVideoMemory: %zu\n", adapter_desc.DedicatedVideoMemory);
}
} // WARP -> Windows Advanced Rasterization ...
// Create Logical Device
ID3D12Device * d3d_device = nullptr;
auto res = D3D12CreateDevice(adapters[0], D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&d3d_device));
CHECK_AND_FAIL(res);
// Create Command Queues
// Create Swapchain
dxgi_factory->Release();
debug_interface_dx->Release();
// Loop
/*
*
// Wait for fences
CHECK(YRB::WaitForFences(&fences_framedone[frame_index], 1));
- SwapChain -> Give me the next image to render to.
- Render to Image
- Present SwapChain Image
*/
// Other stuff -> Shaders, DescriptorManagement (DescriptorHeap, RootSignature), PSO, Sync Objects, Buffers, Textures, ...
return 0;
}
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef XSLT_SUPPORT
#include "modules/xslt/src/xslt_outputhandler.h"
#include "modules/xmlutils/xmlparser.h"
#include "modules/xmlutils/xmltokenhandler.h"
/* virtual */
XSLT_OutputHandler::~XSLT_OutputHandler()
{
}
/* virtual */ void
XSLT_OutputHandler::SuggestNamespaceDeclarationL (XSLT_Element *element, XMLNamespaceDeclaration *nsdeclaration, BOOL skip_excluded_namespaces)
{
}
void
XSLT_OutputHandler::CopyOfL (XSLT_Element *copy_of, XMLTreeAccessor *tree, XMLTreeAccessor::Node *node)
{
TempBuffer buffer; ANCHOR (TempBuffer, buffer);
XMLCompleteName name; ANCHOR (XMLCompleteName, name);
XMLTreeAccessor::Node *stop = tree->GetNextNonDescendant (node);
XMLTreeAccessor::Node *root = node;
XMLTreeAccessor::Attributes *attributes;
const uni_char *data;
while (node != stop)
{
switch (tree->GetNodeType (node))
{
case XMLTreeAccessor::TYPE_ELEMENT:
{
tree->GetName (name, node);
StartElementL (name);
XMLTreeAccessor::Namespaces *namespaces;
LEAVE_IF_ERROR (tree->GetNamespaces (namespaces, node));
XMLNamespaceDeclaration::Reference nsdeclaration; ANCHOR (XMLNamespaceDeclaration::Reference, nsdeclaration);
for (unsigned nsindex = 0, nscount = namespaces->GetCount (); nsindex < nscount; ++nsindex)
{
const uni_char *uri, *prefix;
namespaces->GetNamespace (nsindex, uri, prefix);
if (prefix && uni_strcmp (prefix, "xml") != 0)
XMLNamespaceDeclaration::PushL (nsdeclaration, uri, ~0u, prefix, ~0u, 1);
}
SuggestNamespaceDeclarationL (copy_of, nsdeclaration, FALSE);
tree->GetAttributes (attributes, node, FALSE, TRUE);
for (unsigned index = 0, count = attributes->GetCount (); index < count; ++index)
{
const uni_char *value;
BOOL id, specified;
LEAVE_IF_ERROR (attributes->GetAttribute (index, name, value, id, specified, &buffer));
AddAttributeL (name, value, id, specified);
buffer.Clear ();
}
}
break;
case XMLTreeAccessor::TYPE_TEXT:
case XMLTreeAccessor::TYPE_CDATA_SECTION:
LEAVE_IF_ERROR (tree->GetData (data, node, &buffer));
AddTextL (data, FALSE);
buffer.Clear ();
break;
case XMLTreeAccessor::TYPE_COMMENT:
LEAVE_IF_ERROR (tree->GetData (data, node, &buffer));
AddCommentL (data);
buffer.Clear ();
break;
case XMLTreeAccessor::TYPE_PROCESSING_INSTRUCTION:
LEAVE_IF_ERROR (tree->GetData (data, node, &buffer));
AddProcessingInstructionL (tree->GetPITarget (node), data);
buffer.Clear ();
break;
default:
break;
}
XMLTreeAccessor::Node *old_node = node;
node = tree->GetNext (node);
// Close elements needing closing
// <one><two></two></one><three/>
if (node != stop)
{
OP_ASSERT(node);
OP_ASSERT(tree->IsAncestorOf(root, node));
while(!tree->IsAncestorOf(old_node, node))
{
if (tree->GetNodeType(old_node) == XMLTreeAccessor::TYPE_ELEMENT)
{
tree->GetName (name, old_node);
EndElementL (name);
}
old_node = tree->GetParent(old_node);
}
}
else
{
// Close everything
for (;;old_node = tree->GetParent(old_node))
{
if (tree->GetNodeType(old_node) == XMLTreeAccessor::TYPE_ELEMENT)
{
tree->GetName (name, old_node);
EndElementL (name);
}
if (old_node == root)
break;
}
}
}
}
void
XSLT_OutputHandler::CopyOfL (XSLT_Element *copy_of, XMLTreeAccessor *tree, XMLTreeAccessor::Node *node, const XMLCompleteName &attribute_name)
{
const uni_char *value;
BOOL id, specified;
TempBuffer buffer; ANCHOR (TempBuffer, buffer);
LEAVE_IF_ERROR (tree->GetAttribute(node, attribute_name, value, id, specified, &buffer));
AddAttributeL (attribute_name, value, id, specified);
}
#endif // XSLT_SUPPORT
|
/* XMRig
* Copyright 2010 Jeff Garzik <jgarzik@pobox.com>
* Copyright 2012-2014 pooler <pooler@litecoinpool.org>
* Copyright 2014 Lucas Jones <https://github.com/lucasjones>
* Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet>
* Copyright 2016 Jay D Dee <jayddee246@gmail.com>
* Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt>
* Copyright 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef XMRIG_CUDALIB_H
#define XMRIG_CUDALIB_H
using nvid_ctx = struct nvid_ctx;
#include "backend/cuda/wrappers/CudaDevice.h"
#include "base/tools/String.h"
#include <vector>
#include <string>
namespace xmrig {
class CudaLib
{
public:
enum DeviceProperty : uint32_t
{
DeviceId,
DeviceAlgorithm,
DeviceArchMajor,
DeviceArchMinor,
DeviceSmx,
DeviceBlocks,
DeviceThreads,
DeviceBFactor,
DeviceBSleep,
DeviceClockRate,
DeviceMemoryClockRate,
DeviceMemoryTotal,
DeviceMemoryFree,
DevicePciBusID,
DevicePciDeviceID,
DevicePciDomainID,
DeviceDatasetHost,
DeviceAstroBWTProcessedHashes,
};
static bool init(const char *fileName = nullptr);
static const char *lastError() noexcept;
static void close();
static inline bool isInitialized() { return m_initialized; }
static inline bool isReady() noexcept { return m_ready; }
static inline const String &loader() { return m_loader; }
static bool astroBWTHash(nvid_ctx *ctx, uint32_t startNonce, uint64_t target, uint32_t *rescount, uint32_t *resnonce) noexcept;
static bool astroBWTPrepare(nvid_ctx *ctx, uint32_t batchSize) noexcept;
static bool cnHash(nvid_ctx *ctx, uint32_t startNonce, uint64_t height, uint64_t target, uint32_t *rescount, uint32_t *resnonce);
static bool deviceInfo(nvid_ctx *ctx, int32_t blocks, int32_t threads, const Algorithm &algorithm, int32_t dataset_host = -1) noexcept;
static bool deviceInit(nvid_ctx *ctx) noexcept;
static bool rxHash(nvid_ctx *ctx, uint32_t startNonce, uint64_t target, uint32_t *rescount, uint32_t *resnonce) noexcept;
static bool rxPrepare(nvid_ctx *ctx, const void *dataset, size_t datasetSize, bool dataset_host, uint32_t batchSize) noexcept;
static bool kawPowHash(nvid_ctx *ctx, uint8_t* job_blob, uint64_t target, uint32_t *rescount, uint32_t *resnonce, uint32_t *skipped_hashes) noexcept;
static bool kawPowPrepare(nvid_ctx *ctx, const void* cache, size_t cache_size, const void* dag_precalc, size_t dag_size, uint32_t height, const uint64_t* dag_sizes) noexcept;
static bool kawPowStopHash(nvid_ctx *ctx) noexcept;
static bool setJob(nvid_ctx *ctx, const void *data, size_t size, const Algorithm &algorithm) noexcept;
static const char *deviceName(nvid_ctx *ctx) noexcept;
static const char *lastError(nvid_ctx *ctx) noexcept;
static const char *pluginVersion() noexcept;
static int32_t deviceInt(nvid_ctx *ctx, DeviceProperty property) noexcept;
static nvid_ctx *alloc(uint32_t id, int32_t bfactor, int32_t bsleep) noexcept;
static std::string version(uint32_t version);
static std::vector<CudaDevice> devices(int32_t bfactor, int32_t bsleep, const std::vector<uint32_t> &hints) noexcept;
static uint32_t deviceCount() noexcept;
static uint32_t deviceUint(nvid_ctx *ctx, DeviceProperty property) noexcept;
static uint32_t driverVersion() noexcept;
static uint32_t runtimeVersion() noexcept;
static uint64_t deviceUlong(nvid_ctx *ctx, DeviceProperty property) noexcept;
static void release(nvid_ctx *ctx) noexcept;
private:
static bool open();
static void load();
static bool m_initialized;
static bool m_ready;
static String m_error;
static String m_loader;
};
} // namespace xmrig
#endif /* XMRIG_CUDALIB_H */
|
#ifndef Core_GActionFollows_h
#define Core_GActionFollows_h
class GnIProgressBar;
class GActionFollows : public GAction
{
public:
enum eFollowType
{
eShadow,
};
private:
GLayer* mpActorLayer;
Gn2DMeshObjectPtr mpsFollowMesh;
GExtraData::eExtraType mFollowExtraType;
public:
GActionFollows(GActorController* pController);
virtual ~GActionFollows();
bool CreateFollow(eFollowType uiFollowsType);
public:
void Update(float fTime);
void AttachActionToController();
void DetachActionToController();
inline gtint GetActionType() {
return ACTION_FOLLOWS;
}
public:
inline void SetActorLayer(GLayer* pActorLayer) {
mpActorLayer = pActorLayer;
}
protected:
GnIProgressBar* CreateGageBar();
void SetFollowPosition();
protected:
inline GLayer* GetActorLayer() {
return mpActorLayer;
}
};
#endif
|
/*
* libcurl class
*
* @author fl@lekutech
* @date 2020-07-21
* @copuleft GPL 2.0
*/
#include "libcurl.h"
std::stringstream jsonout;
error* libcurl::err = 0;
bool libcurl::init(CURL*& conn, std::string url)
{
CURLcode code;
conn = curl_easy_init();
if(NULL == conn)
{
std::cout << stderr << " Failed to create CURL connection" << std::endl;
exit(EXIT_FAILURE);
}
code = curl_easy_setopt(conn, CURLOPT_URL, url.data());
code = curl_easy_setopt(conn, CURLOPT_WRITEFUNCTION, writer);
code = curl_easy_setopt(conn, CURLOPT_WRITEDATA, &jsonout);
code = curl_easy_setopt(conn, CURLOPT_SSL_VERIFYPEER, false); //设定为不验证证书和HOST
return true;
}
int libcurl::writer(void* ptr, size_t size, size_t nmemb, void* stream)
{
std::string data((const char*)ptr, (size_t)size * nmemb);
*((std::stringstream*)stream) << data << std::endl;
return size * nmemb;
}
std::string libcurl::libcurl_get(std::string& url)
{
CURL* conn = NULL;
CURLcode code;
err = new error;
if(!init(conn, url))
{
err->show();
exit(1);
}
code = curl_easy_perform(conn);
if (code != 0)
{
err->show();
exit(1);
}
std::string str_json = jsonout.str();
curl_easy_cleanup(conn);
jsonout.str("");
return str_json;
}
int libcurl::libcurl_post(const char* url, const char* data)
{
CURL* conn = NULL;
CURLcode code;
curl_global_init(CURL_GLOBAL_DEFAULT);
if(!init(conn, url))
{
std::cout << stderr << " Connection initializion failed" << std::endl;
return -1;
}
code = curl_easy_setopt(conn, CURLOPT_POST, true);
code = curl_easy_setopt(conn, CURLOPT_POSTFIELDS, data);
code = curl_easy_perform(conn);
curl_easy_cleanup(conn);
return 1;
}
int libcurl::libcurl_HttpDownload(std::string & url)
{
CURL* curl;
CURLcode res;
if(!init(curl, url))
{
std::cout << stderr << " Connection initializion failed" << std::endl;
return -1;
}
res = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); //设定为不验证证书和HOST
res = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
res = curl_easy_setopt(curl, CURLOPT_NOPROGRESS, FALSE);
res = curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, NULL);
res = curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, NULL);
//curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
//curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
//curl_easy_setopt(curl, CURLOPT_SSLENGINE_DEFAULT);
//curl_easy_setopt(curl, CURLOPT_CAINFO, "cacert.pem");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return 0;
}
|
#include<iostream>
#include<vector>
#include<fstream>
#include "omp.h"
#include<cmath>
#include<sys/time.h>
#include <algorithm>
using namespace std;
struct timeval start, end;
int vCount, nEdges, sourceNode;
struct Edge
{
public:
int source;
int destination;
int weight;
};
void print_shortest_path(long int dist[]){
for(int i=0; i< vCount ; i++){
cout << i << " " << dist[i] << endl;
}
}
int main(int argc, char **argv){
if(argc < 3){
cout << "Usage: ./a.out <filename(string)> <source(int)>" << endl;
exit(0);
}
int src, dst, wght;
sourceNode = atoi(argv[2]);
char *filename = argv[1];
cout << "reading file" << endl;
ifstream read(filename);
read >> vCount >> nEdges;
vector<Edge> edges;
int degree[vCount];
long int dist[vCount];
for(int i=0;i<vCount;i++){
dist[i]=9999999999;
degree[i]=0;
}
dist[sourceNode] = 0;
vector< vector<int> > schedule;
while(read >> src >> dst >> wght){
Edge e;
e.source = src;
e.destination = dst;
e.weight = wght;
edges.push_back(e);
}
gettimeofday(&start, NULL); //start time of the actual page rank algorithm
omp_set_num_threads(atoi(argv[2]));
int destination;
vector<bool> visited_edge(nEdges, false);
int k =0;
unsigned long int edges_visited = 0;
while(edges_visited!=edges.size()) {
vector<bool> visited_node;
visited_node.assign(vCount, false);
for(int i=0;i<edges.size();i++){
if(visited_edge[i]==0 && visited_node[edges[i].source]==0 && visited_node[edges[i].destination]==0) {
schedule.resize(k+1);
schedule[k].push_back(i);
visited_node[edges[i].source] = true;
visited_node[edges[i].destination] = true;
visited_edge[i] = true;
edges_visited++;
}
}
k++;
}
bool relaxed = true;
while(relaxed) {
relaxed = false;
for (int i = 0; i < schedule.size(); i++) {
#pragma omp parallel for reduction(|:relaxed)
for (int k = 0; k < schedule[i].size(); k++) {
if(dist[edges[schedule[i][k]].source] + edges[schedule[i][k]].weight < dist[edges[schedule[i][k]].destination]){
dist[edges[schedule[i][k]].destination] = dist[edges[schedule[i][k]].source] + edges[schedule[i][k]].weight;
relaxed = true;
}
}
}
}
gettimeofday(&end, NULL); //page rank ends here
cout << "Time taken by sequential execution bellman ford on " << argv[2] << " threads and " << vCount << " nodes is " << (((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6) << endl;
print_shortest_path(dist);
return 0;
}
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#ifndef INSTRUCTIONS1CONTROLLER_H_
#define INSTRUCTIONS1CONTROLLER_H_
#include "../controller/EmptyController.h"
namespace Demo {
/**
* Customowy kontroler do pierwszej planszy instrukcji.
*/
class Instructions1Controller : public Controller::EmptyController {
public:
C__ (void)
b_ ("EmptyController")
Instructions1Controller () :
player (NULL),
buttonLeft (NULL),
buttonRight (NULL),
envelope1 (NULL),
envelope2 (NULL),
envelope3 (NULL),
envelope4 (NULL),
envelope5 (NULL) {}
virtual ~Instructions1Controller () {}
bool onManagerLoad (Event::ManagerEvent *e, Model::IModel *m, View::IView *v);
bool onManagerUnload (Event::ManagerEvent *e, Model::IModel *m, View::IView *v);
S_ (setPlayer) void setPlayer (Model::IModel *m) { player = m; }
S_ (setButtonLeft) void setButtonLeft (Model::IModel *m) { buttonLeft = m; }
S_ (setButtonRight) void setButtonRight (Model::IModel *m) { buttonRight = m; }
S_ (setEnvelope1) void setEnvelope1 (Model::IModel *m) { envelope1 = m; }
S_ (setEnvelope2) void setEnvelope2 (Model::IModel *m) { envelope2 = m; }
S_ (setEnvelope3) void setEnvelope3 (Model::IModel *m) { envelope3 = m; }
S_ (setEnvelope4) void setEnvelope4 (Model::IModel *m) { envelope4 = m; }
S_ (setEnvelope5) void setEnvelope5 (Model::IModel *m) { envelope5 = m; }
private:
Model::IModel *player;
Model::IModel *buttonLeft;
Model::IModel *buttonRight;
Model::IModel *envelope1;
Model::IModel *envelope2;
Model::IModel *envelope3;
Model::IModel *envelope4;
Model::IModel *envelope5;
E_ (Instructions1Controller)
};
} /* namespace Demo */
# endif /* INSTRUCTIONS1CONTROLLER_H_ */
|
#if defined(_WIN32)
#include "winsock2.h"
#endif
#include <thread>
#include <mutex>
#include <algorithm>
#include "udp_manager.h"
#include "main_thread.h"
#include "protocol.h"
#include "interface.h"
#include "path.h"
bool on_checkip(const char* remote_ip, const int &remote_port)
{
file_server_thread::get_instance()->add_log(LOG_TYPE_INFO, "on_checkip---->>>>");
if (file_server_thread::get_instance()->udp_manager_ != nullptr)
{
return file_server_thread::get_instance()->udp_manager_->handle_checkip(remote_ip, remote_port);
}
return true;
}
bool on_recv(const char* data, const int &size, const int &linker_handle, const char* remote_ip, const int &remote_port, const int &consume_timer)
{
header *header_ptr = (header *)(data);
if (nullptr == header_ptr)
{
file_server_thread::get_instance()->add_log(LOG_TYPE_ERROR, "rudp_on_recv Failed linker_handle=%d size=%d", linker_handle, size);
return false;
}
file_server_thread::get_instance()->add_queue(*header_ptr, (char*)data, size, linker_handle, remote_ip, remote_port);
if (file_server_thread::get_instance()->udp_manager_ != nullptr)
{
file_server_thread::get_instance()->udp_manager_->handle_recv(data, size, linker_handle, remote_ip, remote_port, consume_timer);
}
return true;
}
void on_disconnect(const int &linker_handle, const char* remote_ip, const int &remote_port)
{
file_server_thread::get_instance()->add_log(LOG_TYPE_INFO, "on_disconnect---->>>> %d", linker_handle);
header header_ptr;
memset(&header_ptr, 0, sizeof(header_ptr));
header_ptr.protocol_id_ = HARQ_DISCONNECT;
file_server_thread::get_instance()->add_queue(header_ptr, nullptr, 0, linker_handle, remote_ip, remote_port);
if (file_server_thread::get_instance()->udp_manager_ != nullptr)
{
file_server_thread::get_instance()->udp_manager_->handle_disconnect(linker_handle, remote_ip, remote_port);
}
}
void on_error(const int &error, const int &linker_handle, const char* remote_ip, const int &remote_port)
{
file_server_thread::get_instance()->add_log(LOG_TYPE_INFO, "on_error---->>>> %d", error);
header header_ptr;
memset(&header_ptr, 0, sizeof(header_ptr));
header_ptr.protocol_id_ = HARQ_DISCONNECT;
file_server_thread::get_instance()->add_queue(header_ptr, nullptr, 0, linker_handle, remote_ip, remote_port);
if (file_server_thread::get_instance()->udp_manager_ != nullptr)
{
file_server_thread::get_instance()->udp_manager_->handle_error(error, linker_handle, remote_ip, remote_port);
}
}
void on_rto(const char* remote_ip, const int &remote_port, const int &local_rto, const int &remote_rto)
{
if (file_server_thread::get_instance()->udp_manager_ != nullptr)
{
file_server_thread::get_instance()->udp_manager_->handle_rto(remote_ip, remote_port, local_rto, remote_rto);
}
}
void on_rate(const char* remote_ip, const int &remote_port, const unsigned int &send_rate, const unsigned int &recv_rate)
{
if (file_server_thread::get_instance()->udp_manager_ != nullptr)
{
file_server_thread::get_instance()->udp_manager_->handle_rto(remote_ip, remote_port, send_rate, recv_rate);
}
}
udp_manager::udp_manager(void *parent)
{
parent_ = parent;
load_so();
}
udp_manager::~udp_manager(void)
{
}
void udp_manager::set_option(const std::string &attribute, const std::string &value)
{
std::string tmp_attribute = attribute;
transform(tmp_attribute.begin(), tmp_attribute.end(), tmp_attribute.begin(), ::tolower);
if("bind_ip" == tmp_attribute)
{
bind_ip_ = value;
}
else if("log" == tmp_attribute)
{
log_ = value;
}
else if("harq_so_path" == tmp_attribute)
{
harq_so_path_ = value;
}
}
void udp_manager::set_option(const std::string &attribute, const int &value)
{
std::string tmp_attribute = attribute;
transform(tmp_attribute.begin(), tmp_attribute.end(), tmp_attribute.begin(), ::tolower);
if("listen_port" == tmp_attribute)
{
listen_port_ = value;
}
else if("delay_interval" == tmp_attribute)
{
delay_interval_ = value;
}
}
void udp_manager::set_option(const std::string &attribute, const bool &value)
{
std::string tmp_attribute = attribute;
transform(tmp_attribute.begin(), tmp_attribute.end(), tmp_attribute.begin(), ::tolower);
if("delay" == tmp_attribute)
{
delay_ = value;
}
}
bool udp_manager::load_so()
{
if(!ustd::path::is_file_exist(((file_server_thread*)parent_)->libso_path_))
{
((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "Load so Falied Not Found libso_path=%s error=%s", ((file_server_thread*)parent_)->libso_path_.c_str(), lib_error());
return false;
}
lib_handle_ = lib_load(((file_server_thread*)parent_)->libso_path_.c_str());
if(nullptr == lib_handle_)
{
((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "Load so Falied libso_path=%s error=%s", ((file_server_thread*)parent_)->libso_path_.c_str(), lib_error());
return false;
}
//加载so透出的函数;
harq_start_server_ptr_ = (HARQ_START_SERVER)lib_function(lib_handle_, "harq_start_server");
harq_send_buffer_handle_ptr_ = (HARQ_SEND_BUFFER_HANDLE)lib_function(lib_handle_, "harq_send_buffer_handle");
harq_close_handle_ptr_ = (HARQ_CLOSE_HANDLE)lib_function(lib_handle_, "harq_close_handle");
harq_version_ptr_ = (HARQ_VERSION)lib_function(lib_handle_, "harq_version");
harq_end_server_ptr_ = (HARQ_END_SERVER)lib_function(lib_handle_, "harq_end_server");
if(nullptr == harq_start_server_ptr_)
{
((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "dlsym harq_start_server_ptr_ error\n");
lib_close(lib_handle_);
return false;
}
if(nullptr == harq_send_buffer_handle_ptr_)
{
((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "dlsym harq_send_buffer_handle error\n");
lib_close(lib_handle_);
return false;
}
if(nullptr == harq_close_handle_ptr_)
{
((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "dlsym harq_close_handle_ptr_ error\n");
lib_close(lib_handle_);
return false;
}
if(nullptr == harq_version_ptr_)
{
((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "dlsym harq_version_ptr_ error\n");
lib_close(lib_handle_);
return false;
}
if(nullptr == harq_end_server_ptr_)
{
((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "dlsym harq_end_server_ptr_ error\n");
lib_close(lib_handle_);
return false;
}
return true;
}
bool udp_manager::start_server()
{
if(harq_start_server_ptr_ != nullptr)
{
express_handle_ = harq_start_server_ptr_((char*)log_.c_str(), (char*)bind_ip_.c_str(), listen_port_, delay_, delay_interval_, 512 * KB, 10 * MB, &on_checkip, &on_recv, &on_disconnect, &on_error, &on_rto, &on_rate);
if (express_handle_ > 0)
return true;
else
return false;
}
return false;
}
bool udp_manager::init()
{
bool ret = start_server();
return ret;
}
int udp_manager::send_buffer(char* data, int size, int linker_handle)
{
if(-1 == linker_handle)
{
return -1;
}
return harq_send_buffer_handle_ptr_(express_handle_, data, size, linker_handle);
}
int udp_manager::send_login_response(const int &linker_handle)
{
if (-1 == linker_handle)
return -1;
reponse_login login;
login.header_.protocol_id_ = EXPRESS_RESPONSE_ONLINE;
login.result_ = 0;
return harq_send_buffer_handle_ptr_(express_handle_, (char*)&login, sizeof(login), linker_handle);
}
bool udp_manager::handle_checkip(const char* remote_ip, const int &remote_port)
{
return true;
}
bool udp_manager::handle_recv(const char* data, const int &size, const int &linker_handle, const char* remote_ip, const int &remote_port, const int &consume_timer)
{
return true;
}
void udp_manager::handle_disconnect(const int &linker_handle, const char* remote_ip, const int &remote_port)
{
}
void udp_manager::handle_error(const int &error, const int &linker_handle, const char* remote_ip, const int &remote_port)
{
}
void udp_manager::handle_rto(const char* remote_ip, const int &remote_port, const int &local_rto, const int &remote_rto)
{
}
void udp_manager::handle_rate(const char* remote_ip, const int &remote_port, const unsigned int &send_rate, const unsigned int &recv_rate)
{
}
void udp_manager::add_handle_ipport(const int &linker_handle, const char* remote_ip, const int &remote_port)
{
std::lock_guard<std::recursive_mutex> gurad(handle_ipport_lock_);
std::shared_ptr<handle_ipport> handle_ipport_ptr(new handle_ipport);
handle_ipport_ptr->linker_handle_ = linker_handle;
std::string tmp_remote_ip(remote_ip);
handle_ipport_ptr->remote_ip_ = tmp_remote_ip;
handle_ipport_ptr->remote_port_ = remote_port;
handle_ipport_list_.push_back(handle_ipport_ptr);
}
std::shared_ptr<handle_ipport> udp_manager::find_handle_ipport(const char* remote_ip, const int &remote_port)
{
std::lock_guard<std::recursive_mutex> gurad(handle_ipport_lock_);
std::string tmp_remote_ip(remote_ip);
for (auto iter = handle_ipport_list_.begin(); iter != handle_ipport_list_.end(); iter++)
{
std::shared_ptr<handle_ipport> handle_ipport_ptr = *iter;
if (tmp_remote_ip == handle_ipport_ptr->remote_ip_ && remote_port == handle_ipport_ptr->remote_port_)
{
return *iter;
}
}
return nullptr;
}
void udp_manager::delete_handle_ipport(const int &linker_handle)
{
std::lock_guard<std::recursive_mutex> gurad(handle_ipport_lock_);
for (auto iter = handle_ipport_list_.begin(); iter != handle_ipport_list_.end();)
{
std::shared_ptr<handle_ipport> handle_ipport_ptr = *iter;
if (linker_handle == handle_ipport_ptr->linker_handle_)
{
handle_ipport_list_.erase(iter++);
}
else
iter++;
}
}
void udp_manager::free_handle_ipport()
{
std::lock_guard<std::recursive_mutex> gurad(handle_ipport_lock_);
handle_ipport_list_.clear();
}
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
const LL M = 1000000007;
long long ans = 0;
int out[111111], in[111111];
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d%d", &out[i], &in[i]);
}
int killed = 0;
ans = 1;
sort(in, in + n);
sort(out, out + n);
for (int i = n - 1, j = n; i >= 0;) {
while (j > 0 && in[j - 1] > out[i]) --j;
int k = i;
while (k > 0 && out[k - 1] == out[i]) --k;
int vars = n - j - killed;
if (vars == 0) {
// Z - z - z
} else {
int rv = i - k + 1;
if (vars >= rv) {
while (rv > 0) {
ans = (ans * vars) % M;
++killed;
--rv;
--vars;
}
} else {
while (vars > 0) {
ans = (ans * rv) % M;
++killed;
--vars;
--rv;
}
}
}
i = k - 1;
}
cout << ans << endl;
return 0;
}
|
#ifndef CORE_IR_H
#define CORE_IR_H
#include "AbstractHandler.h"
#include "../lib/IRremote/IRremote.h"
namespace IR {
class Handler : public AbstractHandler {
IRrecv *irrecv;
decode_results results;
public:
Handler();
virtual void handle(uint16_t dataSize, uint8_t *data) override;
virtual void loop() override;
};
class IRReceivePacket : public AbstractPacket {
public:
IRReceivePacket(uint32_t value);
};
}
#endif //CORE_IR_H
|
#include <cstdlib>
#include <iostream>
#include <cmath>
#include "TFile.h"
#include "TTree.h"
#include "TH1D.h"
#include "TGraphAsymmErrors.h"
#include "TRandom3.h"
#include "AccMap.h"
#include "fiducials.h"
#include "Nuclear_Info.h"
#include "Cross_Sections.h"
using namespace std;
double sq(double x)
{
return x*x;
}
int main(int argc, char ** argv)
{
if (argc != 3)
{
cerr << "Wrong number of arguments. Instead use:\n"
<< "\tpp_np_cut /path/to/gen/file /path/to/file\n";
return -1;
}
// Read arguments, create files
TFile * infile = new TFile(argv[1]);
TFile * outfile = new TFile(argv[2],"RECREATE");
// Input Tree
TTree * inTree = (TTree*)infile->Get("genT");
Double_t gen_pe[3], gen_pLead[3], gen_pRec[3], gen_weight;
Int_t lead_type, rec_type;
inTree->SetBranchAddress("lead_type",&lead_type);
inTree->SetBranchAddress("rec_type",&rec_type);
inTree->SetBranchAddress("weight",&gen_weight);
inTree->SetBranchAddress("pe",gen_pe);
inTree->SetBranchAddress("pLead",gen_pLead);
inTree->SetBranchAddress("pRec",gen_pRec);
// Output Tree
TTree * T = new TTree("T","Cut Tree");
Float_t Q2, Xb, Pe[3], Pe_size, theta_e, phi_e, Pp[2][3], Pp_size[2], pq_angle[2], Ep[2], theta_p[2], phi_p[2], nu, q[3];
Float_t Pmiss_q_angle[2], Pmiss_size[2], Pmiss[2][3];
Float_t z = 0.;
Float_t Rp[2][3]={{0.,0.,-22.25},{0.,0.,-22.25}};
Double_t weight;
Double_t pRec_Mag;
Double_t pLead_Mag;
Int_t nmb = 2;
Int_t nump;
T->Branch("Q2",&Q2,"Q2/F");
T->Branch("Xb",&Xb,"Xb/F");
T->Branch("nu",&nu,"nu/F");
T->Branch("q",q,"q[3]/F");
T->Branch("Pe",Pe,"Pe[3]/F");
T->Branch("Pe_size",&Pe_size,"Pe_size/F");
T->Branch("theta_e",&theta_e,"theta_e/F");
T->Branch("phi_e",&phi_e,"phi_e/F");
T->Branch("Pp",Pp,"Pp[2][3]/F");
T->Branch("Pp_size",Pp_size,"Pp_size[2]/F");
T->Branch("pq_angle",pq_angle,"pq_angle[2]/F");
T->Branch("Ep",Ep,"Ep[2]/F");
T->Branch("theta_p",theta_p,"theta_p[2]/F");
T->Branch("phi_p",phi_p,"phi_p[2]/F");
T->Branch("Pmiss_q_angle",Pmiss_q_angle,"Pmiss_q_angle[2]/F");
T->Branch("Pmiss_size",Pmiss_size,"Pmiss_size[2]/F");
T->Branch("Pmiss",Pmiss,"Pmiss[2][3]/F");
T->Branch("Rp",Rp,"Rp[2][3]/F");
T->Branch("weight",&weight,"weight/D");
T->Branch("pRec",&pRec_Mag,"pRec/D");
T->Branch("pLead",&pLead_Mag,"pLead/D");
T->Branch("nump",&nump,"nump/I");
TRandom3 myRand(0);
double a = 0.03;
double b = 0.06;
Cross_Sections myCS;
// Loop over all events
const int nEvents = inTree->GetEntries(); // this is a key number for the weight
for (int event=0 ; event < nEvents ; event++)
{
if (event %100000==0)
cerr << "Working on event " << event << " out of " << nEvents <<"\n";
inTree->GetEvent(event);
// Require a recoil proton
if (rec_type != pCode)
continue;
if (lead_type == pCode)
{
nump = 2;
}
else
{
nump = 1;
}
// Create vectors for the particles
TVector3 vrec(gen_pRec[0],gen_pRec[1],gen_pRec[2]);
TVector3 ve(gen_pe[0],gen_pe[1],gen_pe[2]);
TVector3 vq = TVector3(0.,0.,eg2beam) - ve;
TVector3 vlead(gen_pLead[0],gen_pLead[1],gen_pLead[2]);
// Fiducial cuts
if (lead_type == nCode)
vlead += vlead*myRand.Gaus(0,a+b*vlead.Mag());
if (!accept_electron(ve))
continue;
if (!accept_proton_simple(vlead))
continue;
if (!accept_proton_simple(vrec))
continue;
if (!accept_neutron(vlead))
continue;
if (lead_type == pCode)
vlead += vlead*myRand.Gaus(0,a+b*vlead.Mag());
if (gen_weight <= 0.)
continue;
TVector3 vmiss=vlead-vq;
TVector3 vcm=vmiss+vrec;
TVector3 vrel=0.5*(vmiss-vrec);
double gen_pMiss_Mag = vmiss.Mag();
double gen_pe_Mag = ve.Mag();
double gen_nu = eg2beam - ve.Mag();
double gen_QSq = 2. * eg2beam * gen_pe_Mag * (1. - ve.CosTheta());
double gen_xB = gen_QSq/(2.*mN*gen_nu);
double gen_q_Mag = vq.Mag();
double gen_pLead_Mag = vlead.Mag();
double gen_pRec_Mag = vrec.Mag();
double gen_ELead = sqrt(gen_pLead_Mag*gen_pLead_Mag+mN*mN);
double m_miss = sqrt((gen_nu+2*mN-gen_ELead)*(gen_nu+2*mN-gen_ELead)-gen_pMiss_Mag*gen_pMiss_Mag);
// Meytal's cuts
if (gen_xB < 1.1)
continue;
if (0.62 > gen_pLead_Mag/gen_q_Mag)
continue;
if (gen_pLead_Mag/gen_q_Mag > 1.1)
continue;
if (vlead.Angle(vq) > 25.*M_PI/180.)
continue;
if (m_miss > 1.175)
continue;
if (0.4 > gen_pMiss_Mag)
continue;
if (gen_pMiss_Mag > 1)
continue;
if (gen_pRec_Mag < 0.35)
continue;
// Apply weight for cross sections
double gen_theta = ve.Theta();
double tau = gen_QSq/(4*mN*mN);
double epsilon = 1/(1.0+2.0*(1.+tau)*sq(tan(gen_theta/2)));
if (lead_type == pCode)
weight = gen_weight/(2*(epsilon/tau*sq(myCS.GEp(gen_QSq))+sq(myCS.GMp(gen_QSq))));
else
weight = gen_weight/(epsilon/tau*sq(myCS.GEn(gen_QSq))+sq(myCS.GMn(gen_QSq)));
// Load up tree
pRec_Mag = gen_pRec_Mag;
pLead_Mag = gen_pLead_Mag;
// Load up tree
Q2 = gen_QSq;
Xb = gen_xB;
nu = gen_nu;
Pe_size = gen_pe_Mag;
theta_e = ve.Theta() * 180./M_PI;
phi_e = ve.Phi()*180./M_PI;
if (phi_e < -30.) phi_e += 360;
Pp_size[0] = gen_pLead_Mag;
Pp_size[1] = gen_pRec_Mag;
pq_angle[0] = vq.Angle(vlead)*180./M_PI;
pq_angle[1] = vq.Angle(vrec)*180./M_PI;
Ep[0] = sqrt(gen_pLead_Mag*gen_pLead_Mag + mN*mN);
Ep[1] = sqrt(gen_pRec_Mag*gen_pRec_Mag + mN*mN);
theta_p[0] = vlead.Theta()*180./M_PI;
theta_p[0] = vrec.Theta()*180./M_PI;
phi_p[0] = vlead.Phi()*180./M_PI;
if (phi_p[0] < -30.) phi_p[0] += 360;
phi_p[1] = vrec.Phi()*180./M_PI;
if (phi_p[1] < -30.) phi_p[1] += 360;
for (int i=0 ; i<3 ; i++)
{
q[i] = vq[i];
Pe[i] = gen_pe[i];
Pp[0][i] = vlead[i];
Pp[1][i] = vrec[i];
Pmiss[0][i] = vlead[i] - vq[i];
Pmiss[1][i] = vrec[i] - vq[i];
}
Pmiss_q_angle[0] = (vlead - vq).Angle(vq) * 180./M_PI;
Pmiss_q_angle[1] = (vrec - vq).Angle(vq) * 180./M_PI;
Pmiss_size[0] = (vlead-vq).Mag();
Pmiss_size[1] = (vrec - vq).Mag();
T->Fill();
}
infile->Close();
outfile->cd();
T->Write();
outfile->Close();
return 0;
}
|
/*************************************************************************/
/* Copyright (C) Network Accessing Control -USTC, 2013 */
/* */
/* File Name : common/KWhiteList.h */
/* Pricipal Author : qinpeixi */
/* Subsystem Name : */
/* Module Name : */
/* Language : */
/* Target Environment : */
/* Created Time : Sun 10 Mar 2013 07:58:35 PM CST */
/* Description : */
/*************************************************************************/
#ifndef KWHITELIST_H
#define KWHITELIST_H
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include "constants.h"
#include "KMac.hpp"
#include "./widget.h"
using namespace std;
class KWhiteList
{
public:
KWhiteList();
//KWhiteList(const KWhiteList &wl);
KWhiteList& operator=(const KWhiteList &wl);
bool Search(const KMac &cMac);
bool Add(const KMac &cMac);
bool Delete(const KMac &cMac);
int Count() const { return m_cWhitelist.size(); }
void deleteAll() { this->m_cWhitelist.clear();} //Clear the whitelist
void PrintAll() const {
for (unsigned i=0; i<m_cWhitelist.size(); i++)
{
m_cWhitelist[i].Print();
}
}
void Serialize(char const *pcBuf) const {
copy(m_cWhitelist.begin(), m_cWhitelist.end(), (KMac*)pcBuf);
}
void Deserialize(const char *pccBuf, const int ciCnt) {
copy((KMac*)pccBuf, (KMac*)(pccBuf + ciCnt * sizeof(KMac)),
back_inserter(m_cWhitelist));
}
private:
vector<KMac> m_cWhitelist;
};
#endif
|
#ifndef APPLICATIONCLASS_H
#define APPLICATIONCLASS_H
// MY INCLUDES //
#include "WindowClass.h"
#include "InputClass.h"
#include "DirectXClass.h"
#include "CameraClass.h"
#include "SphereModelClass.h"
#include "SunClass.h"
#include "PlanetClass.h"
#include "EarthClass.h"
#include "LightClass.h"
#include "EarthShaderClass.h"
#include "TextureShaderClass.h"
#include "BumpMapShaderClass.h"
// GLOBALS //
static bool FULL_SCREEN = true;
static bool SHOW_CURSOR = false;
const bool VSYNC_ENABLED = true;
const float SCREEN_DEPTH = 1000.0f;
const float SCREEN_NEAR = 0.1f;
class ApplicationClass
{
public:
ApplicationClass();
ApplicationClass(const ApplicationClass&);
~ApplicationClass();
bool Initialize();
void Run();
void Shutdown();
private:
// Methods
bool InitializeFramework();
bool InitializeObjects();
bool InitializeShaders();
void Update(MSG&);
void Render();
void RenderSun();
void RenderEarth();
// Members
float m_scaleFactor;
WindowClass *m_Window;
InputClass *m_Input;
DirectXClass *m_Device;
CameraClass *m_Camera;
LightClass *m_Light;
SphereModelClass *m_Sphere;
SunClass *m_Sun;
EarthClass *m_Earth;
PlanetClass *m_Moon;
EarthShaderClass *m_EarthShader;
BumpMapShaderClass *m_BumpMapShader;
TextureShaderClass *m_TextureShader;
};
#endif
|
#pragma once
#include <chrono>
#include <iostream>
class Timer{
private:
std::chrono::time_point<std::chrono::high_resolution_clock> startTimePoint;
public:
Timer();
~Timer();
void Stop();
};
|
#include <iostream>
#include <cstdlib>
using namespace std;
struct c {
int value;
c * next;
};
int main() {
c * head = NULL;
c * p2 = NULL;
int i = 0;
cout << "输入几个数以空格键分开,以任意字母结尾即可"<<endl;
//构造链表
while (true) {
int temp;
cin >> temp;
if (!cin) break;
if (head == NULL) {
head = new c;
p2 = head;
}
else {
p2->next = new c;
p2 = p2->next;
}
i++;
p2->value = temp;
p2->next = NULL;
}
//排序
c * first = head;
c * second =NULL;
if (head != NULL) {
second = head->next;
}
c * temp = second;
for (int j = 1; j <= (i + 1 )/ 2-1; j++) {
first->next = second->next;
second->next = first->next->next;
first->next->next = temp;
first = first->next;
second = second->next;
}
//输出
c * p = head;
while (true) {
if (p == NULL) break;
cout << p->value << "->";
p = p->next;
}
cout << "NULL" << endl;
system("pause");
}
|
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define MaxNode 10
typedef struct
{
int value[MaxNode][MaxNode];
int n;
int m;
}Graph;
void DFS(vector<int> &flag, Graph &G, int node)
{
flag[node] = 1;
cout << " " << node;
for (int i=0; i<G.n; ++i) {
if (G.value[node][i] == 1 && flag[i] == 0)
DFS(flag, G, i);
}
}
void BFS(vector<int> &flag, queue<int> &Q, Graph &G, int node)
{
flag[node] = 1;
Q.push(node);
int temp = 0;
while (!Q.empty()) {
temp = Q.front();
cout << " " << temp;
Q.pop();
for (int i=0; i<G.n; ++i) {
if (G.value[temp][i] == 1 && flag[i] == 0) {
Q.push(i);
flag[i] = 1;
}
}
}
}
int main()
{
int N = 0,
M = 0;
cin >> N >> M;
Graph G;
G.m = M;
G.n = N;
int x = 0,
y = 0;
for (int i=0; i<N; ++i)
for (int j=0; j<N; ++j) {
G.value[i][j] = 0;
}
for (int i=0; i<M; ++i) {
cin >> x >> y;
G.value[x][y] = 1;
G.value[y][x] = 1;
}
vector<int> flag(N, 0);
for (int i=0; i<N; ++i)
if (flag[i] == 0) {
cout << "{";
DFS(flag, G, i);
cout << " }" << endl;
}
vector<int> flag1(N, 0);
queue<int> Q;
for (int i=0; i<N; ++i)
if (flag1[i] == 0) {
cout << "{";
BFS(flag1, Q, G, i);
cout << " }" << endl;
}
return 0;
}
|
#include "bigint.hpp"
#include <cstring>
#include <sstream>
#include <iostream>
//*** Input & output *****************************************
std::ostream& operator<<(std::ostream &out, const BigInt &right){
out << right.asString();
return out;
}
std::istream& operator>>(std::istream &in, BigInt &right){
std::string s;
in >> s;
right = BigInt(s);
return in;
}
//*** Constructors & destructor ******************************
BigInt::BigInt(long value){
std::stringstream ss;
ss << value;
createFromString(ss.str());
}
BigInt::BigInt(const BigInt &model) : length(model.length), sign(model.sign){
allocateDigits(length);
memcpy(data, model.data, sizeof(Digit)*length);
}
BigInt::BigInt(const std::string &value){
createFromString(value);
trimZeroes();
}
BigInt::~BigInt(){
free();
}
//*** Operators **********************************************
BigInt& BigInt::operator=(const BigInt &model){
if(data)
free();
length = model.length;
sign = model.sign;
allocateDigits(length);
memcpy(data, model.data, sizeof(Digit)*length);
return *this;
}
bool BigInt::operator==(const BigInt &right) const{
if(sign != right.sign || length != right.length)
return false;
for(std::size_t i = 0; i != length; ++i){
if(data[i] != right.data[i])
return false;
}
return true;
}
bool BigInt::operator<(const BigInt &right) const{
if(sign > right.sign)
return true;
else if(sign < right.sign)
return false;
if(length > right.length)
return sign ? true : false;
else if(length < right.length)
return sign ? false : true;
// What is known:
// a,b > 0 || a,b < 0
// length(a) == length(b)
for(std::size_t i = 0; i != length; ++i){
auto d1 = data[length-i-1];
auto d2 = right.data[length-i-1];
if(sign){
if(d1 < d2)
return false;
else if(d1 > d2)
return true;
}
else{
if(d1 > d2)
return false;
else if(d1 < d2)
return true;
}
}
return false; //they're equal
}
//************************************************************
BigInt BigInt::operator+(const BigInt &right) const{
if(sign ^ right.sign)
return sign ? (right - (-*this)) : (*this - (-right));
// Compute a + b, where a*b > 0.
const BigInt *max_n, *min_n;
if(this->abs() >= right.abs()){
max_n = this;
min_n = &right;
}
else{
max_n = &right;
min_n = this;
}
// max_n >= min_n => max_length >= min_length
Digit *tab = new Digit[max_n->length+1];
int8_t sh = 0;
std::size_t i = 0;
while(i < max_n->length){
tab[i] = sh + max_n->data[i];
if(i < min_n->length)
tab[i] += min_n->data[i];
if(tab[i] > 9){
tab[i] -= 10;
sh = 1;
}
else
sh = 0;
++i;
}
if(sh)
tab[i++] = 1;
BigInt result(tab, sign, i);
return result;
}
//************************************************************
BigInt BigInt::operator-(const BigInt &right) const{
if(sign ^ right.sign)
return sign ? (*this + (-right)) : (*this + (-right));
// Compute a - b, where a*b > 0.
const BigInt *max_n, *min_n;
if(this->abs() >= right.abs()){
max_n = this;
min_n = &right;
}
else{
max_n = &right;
min_n = this;
}
// max_n >= min_n => max_length >= min_length
Digit *tab = new Digit[max_n->length];
std::size_t i = 0;
int8_t *above = new int8_t[max_n->length];
for(std::size_t k = 0; k != max_n->length; ++k)
above[k] = max_n->data[k];
while(i < min_n->length){
if(above[i] >= min_n->data[i])
tab[i] = above[i] - min_n->data[i];
else{
above[i] += 10;
std::size_t k = i+1;
while(!above[k])
above[k++] += 9;
--above[k];
tab[i] = above[i] - min_n->data[i];
}
++i;
}
while(i < max_n->length){
tab[i] = above[i];
++i;
}
delete[] above;
bool s;
if(sign)
s = (*this <= right) ? true : false;
else
s = (*this >= right) ? false : true;
BigInt result(tab, s, i);
return result;
}
//************************************************************
BigInt BigInt::operator*(const BigInt &right) const{
if(*this == 0 || right == 0)
return BigInt(0);
const BigInt *greater = (abs() > right.abs() ? this : &right);
const BigInt *less = (abs() <= right.abs() ? this : &right);
std::size_t len = length + right.length;
char *result_data = new char[len]();
char *mid_data = new char[len * less->length]();
char sh = 0;
for(std::size_t i = 0; i != less->length; ++i){
for(std::size_t j = 0; j != greater->length; ++j){
std::size_t idx = j+i + i*len;
mid_data[idx] = greater->data[j] * less->data[i] + sh;
if(mid_data[idx] > 9){
char v = mid_data[idx] % 10;
sh = (mid_data[idx] - v) / 10;
mid_data[idx] = v;
}
else //if(j+1 != greater->length)
sh = 0;
}
mid_data[greater->length+i + i*len] = sh;
sh = 0;
}
for(std::size_t i = 0; i != len; ++i){
result_data[i] = sh;
sh = 0;
for(std::size_t j = 0; j != less->length; ++j)
result_data[i] += mid_data[i + j*len];
if(result_data[i] > 9){
char v = result_data[i] % 10;
sh = (result_data[i] - v) / 10;
result_data[i] = v;
}
}
BigInt result(result_data, sign ^ right.sign, length + right.length);
result.trimZeroes();
delete[] mid_data;
return result;
}
//************************************************************
BigInt BigInt::operator/(const BigInt &right) const{
BigInt result = *this;
BigInt x = 0;
for(std::size_t i = this->length; i > 0; --i){
x = 10*x + this->data[i-1];
Digit d = divint(x, right);
result[i-1] = d;
x -= right.abs()*d;
}
result.trimZeroes();
result.sign = (sign ^ right.sign);
result.ensurePositiveZero();
return result;
}
//************************************************************
BigInt BigInt::operator%(const BigInt &right) const{
// Note: a % b == -[(-a) % (-b)]
if(right == 0)
throw ZeroDivisionException();
BigInt a = *this;
BigInt b = right.abs();
bool flag = false;
if(right.sign){
// a % (-b) == -[(-a) % b]
a.sign = !a.sign;
b.sign = false;
flag = true;
}
if(a.sign){
while(a < 0)
a += b;
}
else{
while(a >= b)
a -= b;
}
a.sign = flag;
return a;
}
//************************************************************
BigInt BigInt::operator-() const{
BigInt result(*this);
if(result != 0)
result.sign = !sign;
return result;
}
//************************************************************
BigInt operator*(long left, const BigInt &right){
return right * left;
}
//*** Public methods *****************************************
std::string BigInt::asString() const{
const char OFFSET = '0' - 0;
std::stringstream result;
if(sign)
result << '-';
for(std::size_t i = length; i > 0; --i)
result << (char)(data[i-1] + OFFSET);
return result.str();
}
BigInt BigInt::abs() const{
BigInt result(*this);
result.sign = 0;
return result;
}
//*** Private methods ****************************************
void BigInt::createFromString(const std::string &s){
// Set length, sign and allocate memory.
if(s[0] == '-'){
length = s.length() - 1;
sign = true;
}
else{
length = s.length();
sign = false;
}
allocateDigits(length);
// Copy digits IN REVERSED ORDER.
Digit *p = data + length - 1;
for(auto i : ((s[0] == '-') ? s.substr(1) : s)){
Digit d = i - 48;
if(d >= 0 && d <= 9)
*(p--) = d;
else
throw ConstructionException();
}
ensurePositiveZero();
}
void BigInt::allocateDigits(std::size_t digits){
try{
data = new Digit[digits];
length = digits;
}catch(std::bad_alloc){
throw AllocationException();
}
}
void BigInt::trimZeroes(){
Digit *p = data + length - 1;
while(*p == 0 && p != data){
--length;
--p;
}
}
void BigInt::free(){
delete[] data;
length = 0;
}
void BigInt::ensurePositiveZero(){
if(length == 1 && sign && data[0] == 0)
sign = false;
}
BigInt::Digit BigInt::divint(BigInt a, BigInt b){
if(b == 0)
throw ZeroDivisionException();
a = a.abs();
b = b.abs();
if(a < b)
return 0;
else if(a == b)
return 1;
Digit result = 0;
do{
a -= b;
++result;
}while(a >= b);
return result;
}
//************************************************************
int main(){
std::cout << "Interactive calculator\n"
<< "Usage: 'NUMBER [+-*/%] NUMBER'\n\n";
while(true){
BigInt a(0), b(0);
char operation;
std::cout << ">>> ";
// Read in format "a op b". Spaces are required.
std::cin >> a >> operation >> b;
BigInt p(0);
switch(operation){
case '+':
p = a+b;
break;
case '-':
p = a-b;
break;
case '*':
p = a*b;
break;
case '/':
try{ p = a/b; }
catch(BigInt::BigIntException&){
std::cerr << "[Failed]\n";
continue;
}
break;
case '%':
try{ p = a%b; }
catch(BigInt::BigIntException&){
std::cerr << "[Failed]\n";
continue;
}
break;
default:
std::cerr << "[Unknown operation]\n";
}
std::cout << a << ' ' << operation << ' ' << b << " = " << p << '\n';
}
}
|
// Created on: 1992-09-28
// Created by: Remi GILET
// Copyright (c) 1992-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GC_MakeMirror_HeaderFile
#define _GC_MakeMirror_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
class Geom_Transformation;
class gp_Pnt;
class gp_Ax1;
class gp_Lin;
class gp_Dir;
class gp_Pln;
class gp_Ax2;
//! This class implements elementary construction algorithms for a
//! symmetrical transformation in 3D space about a point,
//! axis or plane. The result is a Geom_Transformation transformation.
//! A MakeMirror object provides a framework for:
//! - defining the construction of the transformation,
//! - implementing the construction algorithm, and
//! - consulting the result.
class GC_MakeMirror
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT GC_MakeMirror(const gp_Pnt& Point);
Standard_EXPORT GC_MakeMirror(const gp_Ax1& Axis);
Standard_EXPORT GC_MakeMirror(const gp_Lin& Line);
//! Make a symmetry transformation af axis defined by
//! <Point> and <Direc>.
Standard_EXPORT GC_MakeMirror(const gp_Pnt& Point, const gp_Dir& Direc);
//! Make a symmetry transformation of plane <Plane>.
Standard_EXPORT GC_MakeMirror(const gp_Pln& Plane);
//! Make a symmetry transformation of plane <Plane>.
Standard_EXPORT GC_MakeMirror(const gp_Ax2& Plane);
//! Returns the constructed transformation.
Standard_EXPORT const Handle(Geom_Transformation)& Value() const;
operator const Handle(Geom_Transformation)& () const { return Value(); }
protected:
private:
Handle(Geom_Transformation) TheMirror;
};
#endif // _GC_MakeMirror_HeaderFile
|
//===========================================================================
//! @file scene_sea2.h
//! @brief デモシーン 海2
//===========================================================================
//---------------------------------------------------------------------------
//! 初期化
//---------------------------------------------------------------------------
bool SceneSea2::initialize()
{
//=============================================================
// カメラ初期化
//=============================================================
auto cameraPosition = Vector3(+0.0f, +10.0f, +50.0f);
auto cameraLookAt = Vector3(+0.0f, +1.0f, +0.0f);
if(!DemoSceneBase::initializeCameraFps(cameraPosition, cameraLookAt))
return false;
//=============================================================
// ライト初期化
//=============================================================
if(!initializeLight())
return false;
//=============================================================
// モデル初期化
//=============================================================
if(!initializeModel())
return false;
redTexture_.reset(gpu::createTexture("texture/red.png"));
greenTexture_.reset(gpu::createTexture("texture/green.png"));
//sea_->setTexture(3, waveTexture_.get());
auto buffer = gpu::createRenderTarget(128, 128, DXGI_FORMAT_R32G32B32A32_FLOAT);
textureBuffer_.reset(buffer);
buffer = gpu::createRenderTarget(128, 128, DXGI_FORMAT_R32G32B32A32_FLOAT);
normalBuffer_.reset(buffer);
for(auto& buffer : buffers_) {
buffer.reset(gpu::createRenderTarget(128, 128, DXGI_FORMAT_R32G32B32A32_FLOAT));
}
// スカイボックス有効化
RenderConfig()().isSkyBox(false);
return true;
}
//---------------------------------------------------------------------------
//! ライト初期化
//---------------------------------------------------------------------------
bool SceneSea2::initializeLight()
{
//=============================================================
// 平行光源初期化
//=============================================================
{
auto position = Vector3(0.0f, 30.0f, -100.0f);
auto lookAt = Vector3(0.0f, 0.0f, 0.0f);
auto color = Vector4(1.0f, 1.0f, 1.0f, 1.0f);
if(!lightManager_->addLight(position, lookAt, color, 1.0f))
return false;
}
return true;
}
//---------------------------------------------------------------------------
//! モデル初期化
//---------------------------------------------------------------------------
bool SceneSea2::initializeModel()
{
//=============================================================
// 海用モデル
//=============================================================
sea_.reset(new Object());
if(!sea_)
return false;
if(!sea_->initialize("Subdivision_Plane.fbx", 100))
return false;
sea_->setShader("vsSea2", "psSea2");
// タスクに追加
taskManager_->addObject(sea_);
return true;
}
//---------------------------------------------------------------------------
//! 波の数値初期化
//---------------------------------------------------------------------------
bool SceneSea2::initializeWave()
{
wave_ = Wave();
return true;
}
//---------------------------------------------------------------------------
//! 更新
//---------------------------------------------------------------------------
void SceneSea2::update(f32 deleteTime)
{
// カメラ更新
cameraManager_->update();
// ライト更新
lightManager_->update();
taskManager_->update();
{
wave_.moveDistance_ += wave_.speed_;
auto cbWave = cbWave_.begin();
{
cbWave->moveDistance_ = wave_.moveDistance_;
cbWave->fineness_ = wave_.fineness_;
cbWave->sharp_ = wave_.sharp_;
cbWave->height_ = wave_.height_;
}
cbWave_.end();
gpu::setConstantBuffer(gpuSlot_, &cbWave_);
}
}
//---------------------------------------------------------------------------
//! 描画
//---------------------------------------------------------------------------
void SceneSea2::render()
{
// ライト描画
gpu::setShader("vsStandard", "psStandard");
lightManager_->render();
static bool f = false;
if(!f) {
f = true;
// 赤と緑のテクスチャを合成
{
// 赤テクスチャをバッファにコピー
for(auto& b : buffers_) {
gpu::setTexture(0, redTexture_.get());
gpu::setTexture(4, greenTexture_.get());
gpu::setShader("vsPrim2D", "ps2TextureAdd");
{
gpu::setRenderTarget(b.get());
GmRender()->put();
}
device::D3DContext()->OMSetRenderTargets(0, nullptr, nullptr);
gpu::setTexture(0, nullptr);
gpu::setTexture(4, nullptr);
}
}
}
s32 prevIndex = (bufferIndex_ == 0) ? (2) : (bufferIndex_ - 1);
s32 currentIndex = bufferIndex_;
s32 nextIndex = (bufferIndex_ + 1) % 3;
gpu::setTexture(0, buffers_[prevIndex].get());
gpu::setTexture(4, buffers_[currentIndex].get());
gpu::setShader("vsPrim2D", "psSeaWave");
f32 clearColor[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
device::D3DContext()->ClearRenderTargetView(buffers_[nextIndex]->getD3DRtv(), clearColor);
gpu::setRenderTarget(buffers_[nextIndex].get());
// 描画
GmRender()->put();
device::D3DContext()->OMSetRenderTargets(0, nullptr, nullptr);
gpu::setTexture(0, nullptr);
bufferIndex_ = nextIndex;
// 法線マップ作製
{
gpu::setTexture(3, buffers_[nextIndex].get());
gpu::setShader("vsPrim2D", "psSeaNormal");
gpu::setRenderTarget(normalBuffer_.get());
GmRender()->put();
device::D3DContext()->OMSetRenderTargets(0, nullptr, nullptr);
gpu::setTexture(3, normalBuffer_.get());
}
// 波描画
{
sea_->setShader("vsSea3", "psSea3");
gpu::setRenderTarget(GmRender()->getRenderBuffer(), GmRender()->getDepthStencil());
taskManager_->render();
}
}
//---------------------------------------------------------------------------
//! 描画
//---------------------------------------------------------------------------
void SceneSea2::render(RenderMode renderMode)
{
if(renderMode == RenderMode::Shadow)
return;
DemoSceneBase::render(renderMode);
ImGui::Begin(u8"シャドウマップ");
{
auto a = 128;
ImGui::InputInt(u8"解像度", &a, 1, 50, ImGuiInputTextFlags_ReadOnly);
ImGui::Image(normalBuffer_->getD3DSrv(), ImVec2(256, 256));
ImGui::InputInt(u8"解像度", &a, 1, 50, ImGuiInputTextFlags_ReadOnly);
ImGui::Image(buffers_[0]->getD3DSrv(), ImVec2(256, 256));
ImGui::InputInt(u8"解像度", &a, 1, 50, ImGuiInputTextFlags_ReadOnly);
ImGui::Image(buffers_[1]->getD3DSrv(), ImVec2(256, 256));
ImGui::InputInt(u8"解像度", &a, 1, 50, ImGuiInputTextFlags_ReadOnly);
ImGui::Image(buffers_[2]->getD3DSrv(), ImVec2(256, 256));
}
ImGui::End();
this->render();
}
//---------------------------------------------------------------------------
//! 解放
//---------------------------------------------------------------------------
void SceneSea2::cleanup()
{
}
|
#pragma once
#ifndef BINARYTREE_HPP_INCLUDE
#define BINARYTREE_HPP_INCLUDE
namespace bt {
#include "common.hpp"
typedef int Key;
typedef void* type;
typedef struct _Node {
Key key;
type value;
struct _Node *parent;
struct _Node *leftChild;
struct _Node *rightChild;
}Node, *pNode;
typedef struct _BinaryTree {
int height;
Node *root;
}BinaryTree;
typedef struct _bst BST, *pBST;
struct _bst {
pNode proot;
int(*keycmp)(void *key1, void *key2);
};
int btUI();
BinaryTree *initTree(Key key, type value);
Node *createNode(Key key, type value, Node *parent, Node *left, Node *right);
Node *initNode(Key key, type value);
void insertChild(Key key, type value, Node *root, BinaryTree *tree);
void insert(Key key, type value, BinaryTree *tree);
void preorder(Node *root);
void inorder(Node *root);
void postorder(Node *root);
int getNumber(char ch);
int isNumber(char ch);
int isEmpty(Node* node);
}
#endif
|
///****************************************************************************
// * *
// * Author : lukasz.iwaszkiewicz@gmail.com *
// * ~~~~~~~~ *
// * Date : Nov 19, 2009 *
// * ~~~~~~ *
// * License : see COPYING file for details. *
// * ~~~~~~~~~ *
// ****************************************************************************/
//
//#ifdef USE_SDL
//#include <iostream>
//#include <algorithm>
//#include <SDL.h>
//
//#include "TimerDispatcher.h"
//
//namespace Event {
//
//void TimerDispatcher::run (Model::IModel *m, EventIndex const &modeliIndex, PointerInsideIndex *pointerInsideIndex)
//{
// unsigned int now = SDL_GetTicks ();
//
// if (now - prevTime < tickInterval) {
// return;
// }
//
// prevTime = now;
// timerEvent.setTicks (now);
//
//// if (observer) {
//// observer->onEvent (&timerEvent);
//// }
//
//// for (Event::ObserverVector::iterator i = observers.begin (); i != observers.end (); ++i) {
//// (*i)->onEvent (&timerEvent);
//// }
//}
//
//}
//
//#endif
|
/***************************************************
* Mir Ali Talpur
* Vector4.cpp
* 4/1/2015
***************************************************/
#include "Vector4.h"
#include "Vector3.h"
#include <math.h>
#include <iostream>
#include <cstring>
/***************************************************
* Vector4()
* Constructor for the Vector4 class
***************************************************/
Vector4::Vector4()
{
std::memset(m, 0, sizeof(m));
}
/***************************************************
* Vector4(float, float, float)
* Constructor for the Vector4 class with 3 values
***************************************************/
Vector4::Vector4(float m0, float m1, float m2)
{
m[0] = m0;
m[1] = m1;
m[2] = m2;
m[3] = 1;
}
/***************************************************
* Vector4(float, float, float,float)
* Constructor for the Vector4 class with 4 values
***************************************************/
Vector4::Vector4(float m0, float m1, float m2, float m3)
{
m[0] = m0;
m[1] = m1;
m[2] = m2;
m[3] = m3;
}
/***************************************************
* ptr()
* returns ptr of the vector4 values
***************************************************/
float* Vector4::ptr()
{
return &m[0];
}
/***************************************************
* set(float,float,float,float)
* sets the vector4 array to x y and z w value
* passed in
***************************************************/
void Vector4::set(float x, float y, float z, float w)
{
m[0] = x;
m[1] = y;
m[2] = z;
m[3] = w;
}
/***************************************************
* overload [] operator
* returns the location of the particular
* Vector4 component
***************************************************/
float& Vector4::operator [] (int loc)
{
return m[loc];
}
/***************************************************
* add(Vector4)
* add all the vector4 components with the given
* vector4
* Basically add two Vector4's together
***************************************************/
Vector4 Vector4::add(Vector4& a)
{
Vector4 b;
b.m[0] = a.m[0] + m[0];
b.m[1] = a.m[1] + m[1];
b.m[2] = a.m[2] + m[2];
b.m[3] = a.m[3] + m[3];
return b;
}
/***************************************************
* Operator +
* Adds two Vector4s together using overloading
* function
***************************************************/
Vector4 Vector4::operator + (Vector4 a)
{
return add(a);
}
/***************************************************
* Operator -
* Subtract two Vector4s together using overloading
* function
***************************************************/
Vector4 Vector4::subtract(Vector4& a)
{
Vector4 b;
b.m[0] = m[0] - a.m[0];
b.m[1] = m[1] - a.m[1];
b.m[2] = m[2] - a.m[2];
b.m[3] = m[3] - a.m[3];
return b;
}
/***************************************************
* Operator -
* Subtract two Vector4s together using overloading
* function
***************************************************/
Vector4 Vector4::operator - (Vector4 a)
{
return subtract(a);
}
/***************************************************
* Dehomogenize()
* Scale the vector so that the fourth component is
* zero
***************************************************/
Vector4 Vector4::dehomogenize()
{
Vector4 b;
if(m[3] == 0){
m[3] = 1;
}
b.m[0] = m[0] / m[3];
b.m[1] = m[1] / m[3];
b.m[2] = m[2] / m[3];
b.m[3] = m[3] / m[3];
return b;
}
/***************************************************
* toVector3(float)
* Convert the vector4 to Vector3
***************************************************/
Vector3 Vector4::toVector3()
{
Vector3 b(m[0], m[1], m[2]);
return b;
}
/***************************************************
* dot(Vector4)
* dot product of two vector4s
***************************************************/
float Vector4::dot(Vector4 a)
{
return (m[0] * a.m[0]) + (m[1] * a.m[1]) + (m[2] * a.m[2]) + (m[3] * a.m[3]);
}
void Vector4::print(std::string comment)
{
std::cout << comment << std::endl;
std::cout << "<x:" << m[0] << ", y:" << m[1] << ", z:" << m[2] << ", w:" << m[3] << ">" << std::endl;
}
|
#ifndef LOGINWIDGET_H
#define LOGINWIDGET_H
#include <QWidget>
#include <QMainWindow>
#include <QStackedWidget>
#include <QLineEdit>
#include <QStyle>
#include <QDebug>
#include <QMovie>
#include <iostream>
#include <memory>
#include <ChatObjects/UserInfo.h>
#include <Controller/Controller.h>
#include <CallbacksHolder/Callback/BaseCallback.h>
namespace Ui {
class LoginWidget;
}
class LoginWidget : public QStackedWidget, public std::enable_shared_from_this<LoginWidget> {
Q_OBJECT
public:
explicit LoginWidget(QWidget *parent = nullptr);
~LoginWidget() override;
void login(const QString &login,const QString &password);
private slots:
void on_loginButton_clicked();
void showMainWidget();
signals:
void openMainWidget();
public:
friend class LoginCallback;
private:
Ui::LoginWidget *ui;
};
#endif // LOGINWIDGET_H
|
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
vector<int> A{3,3,4};
vector<int> B{3,3,4};
vector<int> C{3,3,4,3};
int i =0, j=0, k=0;
vector<int> v;
int n1 = A.size();
int n2 = B.size();
int n3 = C.size();
unordered_set <int> s;
vector<int> ans;
while(i < n1 && j < n2 && k < n3) {
if(A[i] == B[j] && B[j] == C[k]) {
if(s.find(A[i]) == s.end()) {
s.insert(A[i]);
ans.push_back(A[i]);
}
i++;
j++;
k++;
}
else if(A[i] < B[j]) {
i++;
}
else if(B[j] < C[k]) {
j++;
}
else {
k++;
}
}
cout << s.size() << endl;
for(auto x: ans) cout << x << " ";
return 0;
}
|
//==================QUESTIONS=======来源于 LeetCode 565=========================================
/*
A zero-indexed array A of length N contains all integers from 0 to N-1.
Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below.
Suppose the first element in S starts with the selection of element A[i] of index = i,
the next element in S should be A[A[i]], and then A[A[A[i]]]…
By that analogy, we stop adding right before a duplicate element occurs in S.
*/
/*
Example 1:
Input: A = [5,4,0,3,1,6,2]
Output: 6
Explanation:
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
One of the longest S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
*/
/*
Note:
N is an integer within the range [1, 20,000].
The elements of A are all distinct.
Each element of A is an integer within the range [0, N-1].
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int ret = 0;
int j;
vector<int> a;
vector<int> b;
for(int i = 0; i < nums.size(); i++){
int longest = 0;
j = i;
a.clear();
while(nums[j] >= 0){
int t = nums[j];
a.push_back(nums[j]);
nums[j] = -1;
j = t;
longest ++;
}
if(ret < longest){
ret = longest;
b.clear();
b=a;
}
}
for(int k : b){
cout<<k<<" ";
}
cout<<endl;
return ret;
}
};
int main(){
int i,p;
vector<int> gyh;
cin>>i;
while(i != 200001 ){
gyh.push_back(i);
cin>>i;
}
Solution a;
p = a.arrayNesting(gyh);
cout<<p<<endl;
return 0;
}
|
#include "elog/appenders/console_appender.hpp"
#include <iostream>
namespace elog
{
ConsoleAppender::ConsoleAppender(Formatter& formatter): RawAppender(formatter)
{
}
void ConsoleAppender::write(const std::string& line)
{
std::cout << line << std::endl;
std::cout.flush();
}
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int INF = 1e9;
int x[100100],h[100100],f[100100][3];
int main()
{
int n;
scanf("%d",&n);
for (int i = 1;i <= n; i++)
scanf("%d%d",&x[i],&h[i]);
f[1][0] = f[1][1] = f[1][2] = 1;
for (int i = 2;i <= n; i++) {
int k = x[i] - x[i-1];
f[i][0] = max(max(f[i-1][0],f[i-1][1]),(k > h[i-1])?f[i-1][2]:0);
f[i][1] = max((k > h[i])?(max(f[i-1][0],f[i-1][1])+1):0,(k > h[i]+h[i-1])?(f[i-1][2]+1):0);
f[i][2] = max(max(f[i-1][0],f[i-1][1])+1,(k > h[i-1])?(f[i-1][2]+1):0);
}
printf("%d\n",f[n][2]);
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef OP_SPEEDDIAL_SEARCH_WIDGET_H
#define OP_SPEEDDIAL_SEARCH_WIDGET_H
#include "adjunct/quick_toolkit/widgets/OpBar.h"
class OpWindowCommander;
class OpSearchDropDownSpecial;
class OpButton;
class OpLabel;
/***********************************************************************************
**
** OpSpeedDialSearchWidget
**
***********************************************************************************/
class OpSpeedDialSearchWidget : public OpWidget
{
public:
static OP_STATUS Construct(OpSpeedDialSearchWidget** obj);
OpSpeedDialSearchWidget();
virtual ~OpSpeedDialSearchWidget();
public:
// == OpInputContext ======================
virtual const char* GetInputContextName() {return "Speed Dial Search Widget";}
// Implementing the OpTreeModelItem interface
virtual Type GetType() {return WIDGET_TYPE_SPEEDDIAL_SEARCH;}
virtual void OnLayout();
void GetRequiredSize(INT32& width, INT32& height);
OP_STATUS Init();
// Implementing the OpWidgetListener interface
virtual void OnDragStart(OpWidget* widget, INT32 pos, INT32 x, INT32 y) {}
virtual void OnDragDrop(OpWidget* widget, OpDragObject* drag_object, INT32 pos, INT32 x, INT32 y) {}
virtual void OnDragLeave(OpWidget* widget, OpDragObject* drag_object) { }
void OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks);
virtual BOOL OnContextMenu(OpWidget* widget, INT32 child_index, const OpPoint& menu_point, const OpRect* avoid_rect, BOOL keyboard_invoked);
private:
void DoLayout();
private:
OpSearchDropDownSpecial* m_search_field;
};
#endif // OP_SPEEDDIAL_SEARCH_WIDGET_H
|
#include "MxGPUQueryManager.h"
|
// Meteorologist Report.cpp : This file contains the 'main' function. Program execution begins and ends there.
// Valeria Benetti 2183227
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Adding const ints for month and days
const int month = 3,
day = 30;
// Creating a 3x30 Array...slide 62??
char weather[month][day];
//Creating name placements for S, R, and C
int Sun, Rain, Cloudy;
// Creating value placers for the totals of Sun, Rain, Cloudy and the largest rain in the 3 months
int totalSun = 0,
totalRain = 0,
totalCloudy = 0,
largestRain = 0;
// Note to self....put file in second folder with the projects name on it...not the debug or main file
ifstream inFile("RainOrShine.txt"); //Open file
if(!inFile)
{
// If there is an error with opening the file
cout << "Error opening up the file";
}
else
{
// Read weather file to start gathering the data
for (int row = 0; row < month; row++)
{
for (int col = 0; col < day; col++)
{
inFile >> weather[row][col];
}
}
}
// Closing the file
inFile.close();
// Creating a report to print out
cout << "3 Month Weather Report" << endl;
for (int row = 0; row < month; row++)
{
Sun = 0;
Rain = 0;
Cloudy = 0;
//Creating the columns for the months
for (int col = 0; col < day; col++)
{
//Calculating the numbers for each month
switch(weather[row][col])
{
case 'S': Sun++;
break;
case 'R': Rain++;
break;
case 'C': Cloudy++;
break;
}
}
// Displaying the numbers for the months
cout << " For the month of ";
if (row == 0)
{
cout << "June \n";
}
else if (row == 1)
{
cout << "July \n";
}
else if (row == 2)
{
cout << "August \n";
}
// Print out the result of the months
cout << "Rainy: " << Rain << endl << "Sunny: " << Sun << endl << "Cloudy: " << Cloudy << endl;
// Total for 3-months
totalSun += Sun;
totalRain += Rain;
totalCloudy += Cloudy;
// Calculate the month that has the most rain
if (largestRain > Rain)
{
largestRain = row;
}
}
// Display the totals of the months
cout << "For the whole three-month period\n" << "Rainy: " << totalRain << endl << "Sunny: " << totalSun << endl << "Cloudy: " << totalCloudy << endl;
// Display the month with the largest period of rain
cout << "The month with the largest number of days that it rained is: ";
if (largestRain == 0)
{
cout << "June" << endl;
}
else if (largestRain == 1)
{
cout << "July" << endl;
}
else
{
cout << "August" << endl;
}
return 0;
}
/*
An amateur meteorologist wants to keep track of weather conditions during the past year's three-month summer season, and has designated each day as either rainy ('R'), cloudy ('C'), or sunny ('S').
Write a program that stores this information in a 3 x 30 array of characters, where the row indicates the month (0 = June, 1 = July, 2 = August) and the column indicates the day of the month.
Note data are not being collected for the 31st of any month.
The program should begin by reading the weather data in from a file.
Then it should create a report that displays, for each month and for the whole three-month period, how many days were rainy, how many were cloudy, and how many were sunny.
It should report which of the three months had the largest number of rainy days.
*/
|
# Copyright (C) 2012-2016 O.S. Systems Software LTDA.
# Copyright (C) 2013-2022 Martin Jansa <martin.jansa@gmail.com>
QT_MODULE ?= "${BPN}"
QT_MODULE_BRANCH ?= "5.15"
QT_MODULE_BRANCH_PARAM ?= "branch=${QT_MODULE_BRANCH}"
# each module needs to define valid SRCREV
SRC_URI = " \
${QT_GIT}/${QT_MODULE}.git;name=${QT_MODULE};${QT_MODULE_BRANCH_PARAM};protocol=${QT_GIT_PROTOCOL} \
"
CVE_PRODUCT:append = " qt"
S = "${WORKDIR}/git"
PV = "5.15.9+git${SRCPV}"
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@tiliae.eu *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#ifndef T_ABSTRACTMODEL_H_
#define T_ABSTRACTMODEL_H_
#include "../../model/Box.h"
/**
*
*/
class T_AbstractModel : public Model::Box {
public:
T_AbstractModel (std::string const &s) : name (s) {}
virtual ~T_AbstractModel () {}
std::string const &getName () const { return name; }
private:
std::string name;
};
# endif /* ABSTRACTMODEL_H_ */
|
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _gp_Sphere_HeaderFile
#define _gp_Sphere_HeaderFile
#include <gp_Ax1.hxx>
#include <gp_Ax3.hxx>
#include <Standard_ConstructionError.hxx>
//! Describes a sphere.
//! A sphere is defined by its radius and positioned in space
//! with a coordinate system (a gp_Ax3 object). The origin of
//! the coordinate system is the center of the sphere. This
//! coordinate system is the "local coordinate system" of the sphere.
//! Note: when a gp_Sphere sphere is converted into a
//! Geom_SphericalSurface sphere, some implicit
//! properties of its local coordinate system are used explicitly:
//! - its origin, "X Direction", "Y Direction" and "main
//! Direction" are used directly to define the parametric
//! directions on the sphere and the origin of the parameters,
//! - its implicit orientation (right-handed or left-handed)
//! gives the orientation (direct, indirect) to the
//! Geom_SphericalSurface sphere.
//! See Also
//! gce_MakeSphere which provides functions for more
//! complex sphere constructions
//! Geom_SphericalSurface which provides additional
//! functions for constructing spheres and works, in
//! particular, with the parametric equations of spheres.
class gp_Sphere
{
public:
DEFINE_STANDARD_ALLOC
//! Creates an indefinite sphere.
gp_Sphere()
: radius (RealLast())
{}
//! Constructs a sphere with radius theRadius, centered on the origin
//! of theA3. theA3 is the local coordinate system of the sphere.
//! Warnings :
//! It is not forbidden to create a sphere with null radius.
//! Raises ConstructionError if theRadius < 0.0
gp_Sphere (const gp_Ax3& theA3, const Standard_Real theRadius)
: pos (theA3),
radius (theRadius)
{
Standard_ConstructionError_Raise_if (theRadius < 0.0, "gp_Sphere() - radius should be >= 0");
}
//! Changes the center of the sphere.
void SetLocation (const gp_Pnt& theLoc) { pos.SetLocation (theLoc); }
//! Changes the local coordinate system of the sphere.
void SetPosition (const gp_Ax3& theA3) { pos = theA3; }
//! Assigns theR the radius of the Sphere.
//! Warnings :
//! It is not forbidden to create a sphere with null radius.
//! Raises ConstructionError if theR < 0.0
void SetRadius (const Standard_Real theR)
{
Standard_ConstructionError_Raise_if (theR < 0.0, "gp_Sphere::SetRadius() - radius should be >= 0");
radius = theR;
}
//! Computes the area of the sphere.
Standard_Real Area() const
{
return 4.0 * M_PI * radius * radius;
}
//! Computes the coefficients of the implicit equation of the quadric
//! in the absolute cartesian coordinates system :
//! @code
//! theA1.X**2 + theA2.Y**2 + theA3.Z**2 + 2.(theB1.X.Y + theB2.X.Z + theB3.Y.Z) +
//! 2.(theC1.X + theC2.Y + theC3.Z) + theD = 0.0
//! @endcode
Standard_EXPORT void Coefficients (Standard_Real& theA1, Standard_Real& theA2, Standard_Real& theA3,
Standard_Real& theB1, Standard_Real& theB2, Standard_Real& theB3,
Standard_Real& theC1, Standard_Real& theC2, Standard_Real& theC3, Standard_Real& theD) const;
//! Reverses the U parametrization of the sphere
//! reversing the YAxis.
void UReverse() { pos.YReverse(); }
//! Reverses the V parametrization of the sphere
//! reversing the ZAxis.
void VReverse() { pos.ZReverse(); }
//! Returns true if the local coordinate system of this sphere
//! is right-handed.
Standard_Boolean Direct() const { return pos.Direct(); }
//! --- Purpose ;
//! Returns the center of the sphere.
const gp_Pnt& Location() const { return pos.Location(); }
//! Returns the local coordinates system of the sphere.
const gp_Ax3& Position() const { return pos; }
//! Returns the radius of the sphere.
Standard_Real Radius() const { return radius; }
//! Computes the volume of the sphere
Standard_Real Volume() const
{
return (4.0 * M_PI * radius * radius * radius) / 3.0;
}
//! Returns the axis X of the sphere.
gp_Ax1 XAxis() const
{
return gp_Ax1 (pos.Location(), pos.XDirection());
}
//! Returns the axis Y of the sphere.
gp_Ax1 YAxis() const
{
return gp_Ax1 (pos.Location(), pos.YDirection());
}
Standard_EXPORT void Mirror (const gp_Pnt& theP);
//! Performs the symmetrical transformation of a sphere
//! with respect to the point theP which is the center of the
//! symmetry.
Standard_NODISCARD Standard_EXPORT gp_Sphere Mirrored (const gp_Pnt& theP) const;
Standard_EXPORT void Mirror (const gp_Ax1& theA1);
//! Performs the symmetrical transformation of a sphere with
//! respect to an axis placement which is the axis of the
//! symmetry.
Standard_NODISCARD Standard_EXPORT gp_Sphere Mirrored (const gp_Ax1& theA1) const;
Standard_EXPORT void Mirror (const gp_Ax2& theA2);
//! Performs the symmetrical transformation of a sphere with respect
//! to a plane. The axis placement theA2 locates the plane of the
//! of the symmetry : (Location, XDirection, YDirection).
Standard_NODISCARD Standard_EXPORT gp_Sphere Mirrored (const gp_Ax2& theA2) const;
void Rotate (const gp_Ax1& theA1, const Standard_Real theAng) { pos.Rotate (theA1, theAng); }
//! Rotates a sphere. theA1 is the axis of the rotation.
//! theAng is the angular value of the rotation in radians.
Standard_NODISCARD gp_Sphere Rotated (const gp_Ax1& theA1, const Standard_Real theAng) const
{
gp_Sphere aC = *this;
aC.pos.Rotate (theA1, theAng);
return aC;
}
void Scale (const gp_Pnt& theP, const Standard_Real theS);
//! Scales a sphere. theS is the scaling value.
//! The absolute value of S is used to scale the sphere
Standard_NODISCARD gp_Sphere Scaled (const gp_Pnt& theP, const Standard_Real theS) const;
void Transform (const gp_Trsf& theT);
//! Transforms a sphere with the transformation theT from class Trsf.
Standard_NODISCARD gp_Sphere Transformed (const gp_Trsf& theT) const;
void Translate (const gp_Vec& theV) { pos.Translate (theV); }
//! Translates a sphere in the direction of the vector theV.
//! The magnitude of the translation is the vector's magnitude.
Standard_NODISCARD gp_Sphere Translated (const gp_Vec& theV) const
{
gp_Sphere aC = *this;
aC.pos.Translate (theV);
return aC;
}
void Translate (const gp_Pnt& theP1, const gp_Pnt& theP2) { pos.Translate (theP1, theP2); }
//! Translates a sphere from the point theP1 to the point theP2.
Standard_NODISCARD gp_Sphere Translated (const gp_Pnt& theP1, const gp_Pnt& theP2) const
{
gp_Sphere aC = *this;
aC.pos.Translate (theP1, theP2);
return aC;
}
private:
gp_Ax3 pos;
Standard_Real radius;
};
//=======================================================================
//function : Scale
// purpose :
//=======================================================================
inline void gp_Sphere::Scale (const gp_Pnt& theP, const Standard_Real theS)
{
pos.Scale (theP, theS);
radius *= theS;
if (radius < 0)
{
radius = -radius;
}
}
//=======================================================================
//function : Scaled
// purpose :
//=======================================================================
inline gp_Sphere gp_Sphere::Scaled (const gp_Pnt& theP, const Standard_Real theS) const
{
gp_Sphere aC = *this;
aC.pos.Scale (theP, theS);
aC.radius *= theS;
if (aC.radius < 0)
{
aC.radius = -aC.radius;
}
return aC;
}
//=======================================================================
//function : Transform
// purpose :
//=======================================================================
inline void gp_Sphere::Transform (const gp_Trsf& theT)
{
pos.Transform(theT);
radius *= theT.ScaleFactor();
if (radius < 0)
{
radius = -radius;
}
}
//=======================================================================
//function : Transformed
// purpose :
//=======================================================================
inline gp_Sphere gp_Sphere::Transformed (const gp_Trsf& theT) const
{
gp_Sphere aC = *this;
aC.pos.Transform (theT);
aC.radius *= theT.ScaleFactor();
if (aC.radius < 0)
{
aC.radius = -aC.radius;
}
return aC;
}
#endif // _gp_Sphere_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#include "modules/unicode/unicode.h"
#include "modules/util/handy.h"
#ifndef _NO_GLOBALS_
// Do not call this directly, always call GetCharacterClass()
CharacterClass Unicode::GetCharacterClassInternalWithCache(UnicodePoint c)
{
// Simple 2 entry cache.
// It's common for this method to be called multiple times for the same 2 unicode points
// Typically prev and next character during layout
UnicodeModule::CC_CACHE_ENTRY *cache = g_opera->unicode_module.m_cc_cache;
int &cache_old = g_opera->unicode_module.m_cc_cache_old;
if (cache[!cache_old].c == c)
return cache[!cache_old].cls;
else if (cache[cache_old].c == c)
{
cache_old = !cache_old;
return cache[!cache_old].cls;
}
CharacterClass cls = GetCharacterClassInternal(c);
cache[cache_old].c = c;
cache[cache_old].cls = cls;
cache_old = !cache_old;
return cls;
}
#endif // !_NO_GLOBALS_
// Do not call this directly, always call GetCharacterClass()
CharacterClass Unicode::GetCharacterClassInternal(UnicodePoint c)
{
int plane = GetUnicodePlane(c);
// Illegal/empty plane
if (plane > 0xE || cls_planes[plane][0] == -1)
return CC_Unknown;
uni_char cp = static_cast<uni_char>(c);
// Sentinel
if (cp == 0xffff)
return CC_Unknown;
// Binary search the run-length compressed table.
size_t high = cls_planes[plane][1], low = cls_planes[plane][0], middle;
while (1)
{
middle = (high + low) >> 1;
if (cls_chars[middle] <= cp)
{
if (cls_chars[middle + 1] > cp)
{
// Codepoint range found, return the data.
return static_cast<CharacterClass>(cls_data[middle]);
}
else
{
low = middle;
}
}
else
{
high = middle;
}
}
/* NOT REACHED */
#ifdef _DEBUG
OP_ASSERT(!"Quite impossible\n");
return CC_Unknown;
#endif
}
BOOL Unicode::CheckPropertyValue(UnicodePoint c, UnicodeProperties prop)
{
const UnicodePoint *table;
int size;
if (FindTableForProperty(prop, &table, &size))
{
size_t low = 0;
size_t high = size - 1;
size_t middle;
do
{
middle = (high + low) >> 1;
if (table[middle] <= c)
{
if (table[middle + 1] > c)
{
// The property tables are constructed in this way that each element with even index is the begin of codepoints' range
// for which the value is TRUE and each odd element defines codepoint that starts the range with FALSE value.
return (middle % 2) ? FALSE : TRUE;
}
low = middle;
}
else
{
if (!high)
return FALSE;
high = middle;
}
}
while (1);
}
else
return FALSE;
}
BOOL Unicode::CheckDerivedPropertyValue(UnicodePoint c, UnicodeDerivedProperties prop)
{
switch (prop)
{
case DERPROP_Default_Ignorable_Code_Point:
return (CheckPropertyValue(c, PROP_Other_Default_Ignorable_Code_Point)
|| CheckPropertyValue(c, PROP_Variation_Selector)
|| GetCharacterClass(c) == CC_Cf)
&& !CheckPropertyValue(c, PROP_White_Space)
&& (c < 0xFFF9 || c > 0xFFFB)
&& (c < 0x0600 || c > 0x0603)
&& c != 0x06DD
&& c != 0x070F;
default:
return FALSE;
}
}
UnicodeBlockType Unicode::GetUnicodeBlockType(UnicodePoint c)
{
size_t low = 0;
size_t high = ARRAY_SIZE(table_blocks_ranges) - 1;
size_t middle;
do
{
middle = (high + low) >> 1;
if (table_blocks_ranges[middle] <= c)
{
if (table_blocks_ranges[middle + 1] > c)
return UnicodeBlockType(table_blocks_values[middle]);
low = middle;
}
else
high = middle;
}
while (1);
}
UnicodeJoiningType Unicode::GetUnicodeJoiningType(UnicodePoint c)
{
int low = 0;
int high = ARRAY_SIZE(table_joiningtype_codepoints) - 1;
int middle;
while (low<=high)
{
middle = (high + low) >> 1;
if (table_joiningtype_codepoints[middle] == c)
return table_joiningtype_values[middle];
if (table_joiningtype_codepoints[middle] < c)
low = middle + 1;
else
high = middle - 1;
}
CharacterClass cc = GetCharacterClass(c);
return (cc==CC_Mn || cc==CC_Me || cc==CC_Cf) ? JT_T : JT_U;
}
#ifdef USE_UNICODE_LINEBREAK
#ifndef _NO_GLOBALS_
// Do not call this directly, always call GetLineBreakClass()
LinebreakClass Unicode::GetLineBreakClassInternalWithCache(UnicodePoint c)
{
// Simple 2 entry cache.
// It's common for this method to be called multiple times for the same 2 unicode points
// Typically prev and next character during layout
UnicodeModule::LBC_CACHE_ENTRY *cache = g_opera->unicode_module.m_lbc_cache;
int &cache_old = g_opera->unicode_module.m_lbc_cache_old;
if (cache[!cache_old].c == c)
return cache[!cache_old].lbc;
else if (cache[cache_old].c == c)
{
cache_old = !cache_old;
return cache[!cache_old].lbc;
}
LinebreakClass lbc = GetLineBreakClassInternal(c);
cache[cache_old].c = c;
cache[cache_old].lbc = lbc;
cache_old = !cache_old;
return lbc;
}
#endif // !_NO_GLOBALS_
// Do not call this directly, always call GetLineBreakClass()
LinebreakClass Unicode::GetLineBreakClassInternal(UnicodePoint c)
{
// OP_ASSERT(!IsSurrogate(c));
int plane = GetUnicodePlane(c);
// Only handle BMP, SMP and SIP
if (plane > 2)
{
return LB_XX;
}
uni_char cp = static_cast<uni_char>(c);
// Sentinels
if (cp == 0xFFFF)
{
return LB_XX;
}
// Binary search the run-length compressed table.
size_t high = line_break_planes_new[plane][1], low = line_break_planes_new[plane][0];
size_t middle;
while (1)
{
middle = (high + low) >> 1;
if (line_break_chars_new[middle] <= cp)
{
if (line_break_chars_new[middle + 1] > cp)
{
// Codepoint range found, return the data.
LinebreakClass retval = static_cast<LinebreakClass>(line_break_data_new[middle]);
if (retval == LB_H2)
{
// Table compaction for Hangul
if (GetHangulSyllableType(cp) == Hangul_LVT)
retval = LB_H3;
}
return retval;
}
else
{
low = middle;
}
}
else
{
high = middle;
}
}
/* NOT REACHED */
#ifdef _DEBUG
OP_ASSERT(!"Quite impossible\n");
return LB_XX;
#endif
}
#endif
#ifdef USE_UNICODE_HANGUL_SYLLABLE
HangulSyllableType Unicode::GetHangulSyllableType(UnicodePoint c)
{
// OP_ASSERT(!IsSurrogate(c) || !"Invalid call to Unicode::GetHangulSyllableType()");
if (c >= 0x1100 && c <= 0x11FF)
{
// Hangul Jamo
if (c >= 0x11A8)
{
// Hangul_Syllable_Type=Trailing_Jamo
return Hangul_T;
}
else if (c >= 0x1160)
{
// Hangul_Syllable_Type=Vowel_Jamo
return Hangul_V;
}
else
{
// Hangul_Syllable_Type=Leading_Jamo
return Hangul_L;
}
}
else if (c >= 0xA960 && c <= 0xA97C)
{
return Hangul_L;
}
else if (c >= 0xAC00 && c <= 0xD7A3)
{
// Hangul Syllables
if (((c - 0xAC00) % 0x1C) == 0)
{
// Hangul_Syllable_Type=LV_Syllable
return Hangul_LV;
}
else
{
// Hangul_Syllable_Type=LVT_Syllable
return Hangul_LVT;
}
}
else if (c >= 0xD7B0 && c <= 0xD7FB)
{
if (c >= 0xD7CB)
{
// Hangul_Syllable_Type=Trailing_Jamo
return Hangul_T;
}
else if (c <= 0xD7C6)
{
// Hangul_Syllable_Type=Vowel_Jamo
return Hangul_V;
}
}
// ..U+10FF, U+1120..U+A95F, U+A980..U+ABFF, U+D7A4..U+D7CF,
// U+D7C7..U+D7CA, U+D7FC..
return Hangul_NA;
}
#endif
#ifdef USE_UNICODE_SEGMENTATION
#include "modules/unicode/tables/wordbreak.inl"
WordBreakType Unicode::GetWordBreakType(UnicodePoint c)
{
// OP_ASSERT(!IsSurrogate(c) || !"Unicode::GetWordBreakType()");
if (c >= 65532)
{
// Treat SMB as ALetter.
if (GetUnicodePlane(c) == 1)
return WB_ALetter;
// The upper parts of BMP and plane 2+ is unknown.
return WB_Other;
}
else
{
// Binary search the run-length compressed table.
size_t high = ARRAY_SIZE(word_break_chars), low = 0, middle;
while (1)
{
middle = (high + low) >> 1;
if (word_break_chars[middle] <= c)
{
if (word_break_chars[middle + 1] > c)
{
// Codepoint range found, return the data.
return static_cast<WordBreakType>(word_break_data[middle]);
}
else
{
low = middle;
}
}
else
{
high = middle;
}
}
/* NOT REACHED */
}
#ifdef _DEBUG
OP_ASSERT(!"Quite impossible\n");
return WB_Other;
#endif
}
#include "modules/unicode/tables/sentencebreak.inl"
SentenceBreakType Unicode::GetSentenceBreakType(UnicodePoint c)
{
if (c >= 65532)
{
// Treat SMB as OLetter.
if (GetUnicodePlane(c) == 1)
return SB_OLetter;
// Only handle BMP
return SB_Other;
}
else
{
// Binary search the run-length compressed table.
size_t high = ARRAY_SIZE(sentence_break_chars), low = 0, middle;
while (1)
{
middle = (high + low) >> 1;
if (sentence_break_chars[middle] <= c)
{
if (sentence_break_chars[middle + 1] > c)
{
// Codepoint range found, return the data.
return static_cast<SentenceBreakType>(sentence_break_data[middle]);
}
else
{
low = middle;
}
}
else
{
high = middle;
}
}
/* NOT REACHED */
}
#ifdef _DEBUG
OP_ASSERT(!"Quite impossible\n");
return SB_Other;
#endif
}
#endif
#ifdef USE_UNICODE_SCRIPT
#include "modules/unicode/tables/scripts.inl"
ScriptType Unicode::GetScriptType(UnicodePoint c)
{
if (c >= 65501)
{
// Only handle BMP
return SC_Unknown;
}
else
{
// Binary search the run-length compressed table.
size_t high = ARRAY_SIZE(script_chars), low = 0, middle;
while (1)
{
middle = (high + low) >> 1;
if (script_chars[middle] <= c)
{
if (script_chars[middle + 1] > c)
{
// Codepoint range found, return the data.
return static_cast<ScriptType>(script_data[middle]);
}
else
{
low = middle;
}
}
else
{
high = middle;
}
}
/* NOT REACHED */
}
#ifdef _DEBUG
OP_ASSERT(!"Quite impossible\n");
return SC_Unknown;
#endif
}
#endif // USE_UNICODE_SCRIPT
|
//
// Created by msagebaum on 3/31/18.
//
#include <util.h>
#include <iostream>
#include <cmath>
#include <settings.h>
#include <Statistics.h>
#include "../include/Track.h"
void Track::read(rapidxml::xml_node<>* trackSeg) {
DataPoint point;
for(rapidxml::xml_node<>* curPnt = trackSeg->first_node("trkpt"); curPnt; curPnt = curPnt->next_sibling("trkpt")) {
point.lat = parseDouble(curPnt->first_attribute("lat"), -100.0);
point.lon = parseDouble(curPnt->first_attribute("lon"), -100.0);
point.height = parseDouble(curPnt->first_node("ele"), 0.0);
point.time = parseDateTime(curPnt->first_node("time"), 0);
points.push_back(point);
}
}
void Track::write(rapidxml::xml_node<>* trackSeg, rapidxml::xml_document<>& doc) const {
for(auto&& point : points) {
rapidxml::xml_node<>* node = doc.allocate_node(rapidxml::node_element, "trkpt");
rapidxml::xml_node<>* eleNode = doc.allocate_node(rapidxml::node_element, "ele", toString(doc, point.height));
rapidxml::xml_node<>* timeNode = doc.allocate_node(rapidxml::node_element, "time", toString(doc, point.time));
rapidxml::xml_attribute<>* latAttr = doc.allocate_attribute("lat", toString(doc, point.lat));
rapidxml::xml_attribute<>* lonAttr = doc.allocate_attribute("lon", toString(doc, point.lon));
node->append_node(eleNode);
node->append_node(timeNode);
node->append_attribute(lonAttr);
node->append_attribute(latAttr);
trackSeg->append_node(node);
}
}
void Track::removeInvalid(const double maxSpeed_km_h) {
double maxSpeed_m_ms = maxSpeed_km_h / 3600.0;
// make a sanity check if the first node is valid
while(points.size() > 0) {
DataPoint& point = points[0];
DataPoint& next = points[1];
bool remove = false;
if(!isValidHeight(point)) {
remove = true;
if(Settings::verbose >= 1) {std::cerr << "Removing initial point due to height: " << point.height << std::endl;}
} else if(std::abs(next.height - point.height) > 10.0) {
remove = true;
if(Settings::verbose >= 1) {std::cerr << "Removing initial point due to large height jump: " << next.height - point.height << std::endl;}
} else if(std::abs(next.time - point.time) > 10000) {
remove = true;
if(Settings::verbose >= 1) {std::cerr << "Removing initial point due to large time: " << next.time - point.time << std::endl;}
}
if(remove) {
points.erase(points.begin());
} else {
break;
}
}
for(int pos = 1; pos < points.size(); /* increased inside the loop */) {
DataPoint& point = points[pos];
bool remove = !isValidHeight(point);
if(remove) {
if(Settings::verbose >= 1) {std::cerr << "Removing point due to height: " << point.height << std::endl;}
}
if(!remove) {
DataPoint& prev = points[pos - 1];
double dist = computePlainDist(point, prev);
long milliseconds = point.time - prev.time;
if(dist > maxSpeed_m_ms * milliseconds) {
remove = true;
if(Settings::verbose >= 1) {std::cerr << "Removing point due to speed limit: " << dist << " " << maxSpeed_m_ms * milliseconds << " " << 3600.0 * dist / milliseconds << std::endl;}
}
}
if(remove) {
points.erase(points.begin() + pos);
} else {
pos += 1;
}
}
}
void Track::linearizeWrongHeight(const double maxClimbSpeed_m_s, const double trendAdapt) {
double maxSpeed_m_ms = maxClimbSpeed_m_s / 1000.0;
size_t invalidStart = 0;
bool isInvalid = false;
double trend = (points[1].height - points[0].height) / (points[1].time - points[0].time);
for(size_t pos = 1; pos < points.size(); ++pos) {
DataPoint& startPoint = points[invalidStart];
DataPoint& prevPoint = points[pos - 1];
DataPoint& point = points[pos];
double trendStart = (point.height - startPoint.height) / (point.time - startPoint.time);
double trendCur = (point.height - prevPoint.height) / (point.time - prevPoint.time);
if(Settings::verbose >= 2) {std::cerr << "pos: " << pos << " trend:" << trend << " trendCur:" << trendCur << " invalid: " << isInvalid << "trendStartInv: " << trendStart << " maxSpeed_m_ms: " << maxSpeed_m_ms << std::endl;}
if(isInvalid) {
// invalid region try to find a position where the trend continues
if(trend - 0.003 <= trendStart && trendStart <= trend + 0.003) {
// found a continuing region
if(Settings::verbose >= 1) {std::cerr << "Interpolating due to climb speed limit from " << invalidStart << " to " << pos << "." << std::endl;}
// make a linear interpolation
double heightDiff = point.height - startPoint.height;
double timeDiff = point.time - startPoint.time;
for(size_t interpolatePos = invalidStart + 1; interpolatePos < pos; ++interpolatePos) {
DataPoint& curPoint = points[interpolatePos];
curPoint.height = startPoint.height + heightDiff * (curPoint.time - startPoint.time) / timeDiff;
}
isInvalid = false;
} else if(pos - invalidStart > 100) {
if(Settings::verbose >= 1) {std::cerr << "Could not determine end of invalid region " << invalidStart << " to " << pos << "." << std::endl;}
isInvalid = false;
}
} else {
if(std::abs(trendCur) > maxSpeed_m_ms) {
isInvalid = true;
invalidStart = pos - 1;
} else {
trend = trend * (1.0 - trendAdapt) + trendAdapt * trendCur;
}
}
}
}
bool Track::isValidHeight(const DataPoint& point) const {
return !(point.height <= 0.0 || point.height >= 3000.0);
}
double Track::computeDist(const DataPoint& p1, const DataPoint& p2) const {
double distPlain = computePlainDist(p1, p2);
double h = p2.height - p1.height;
return std::sqrt(h * h + distPlain * distPlain);
}
double Track::computePlainDist(const DataPoint& p1, const DataPoint& p2) const {
// very simple distance
// see: https://www.movable-type.co.uk/scripts/latlong.html
double x = deg2Rad(p2.lon - p1.lon) * std::cos(deg2Rad(p2.lat + p1.lat) * 0.5);
double y = deg2Rad(p2.lat - p1.lat);
return std::sqrt(x * x + y * y) * R;
}
void Track::extractBreaks(double minSeconds, double maxDistance, std::vector<Track>& breaks) {
size_t breakStart = 0;
long breakTime = 0;
for(size_t pos = 1; pos < points.size(); ++pos) {
DataPoint& startPoint = points[breakStart];
DataPoint& point = points[pos];
double dist = computeDist(point, startPoint);
long milliseconds = point.time - startPoint.time;
if(dist > maxDistance) {
// leaving the radius of the break point
if(breakTime > minSeconds * 1000.0) {
// break was long enough, extract it
if(Settings::verbose >= 1) {std::cerr << "Extracting break from " << breakStart << " to " << pos << "." << std::endl;}
extractTrack(breaks, breakStart, pos);
points.erase(points.begin() + breakStart + 1, points.begin() + pos); // leave the start of the break in the track
pos = breakStart; // reset the iteration back to the point where the break started
}
// reset the values for the break start
breakStart = pos;
breakTime = 0;
} else {
// break is still valid
breakTime = milliseconds; // store the duration of the break;
}
}
}
void Track::splitUpDown(double changeTolerance, std::vector<Track>& up, std::vector<Track>& down) {
if(points.size() == 0) {
return;
}
size_t sectionStart = 0;
size_t sectionMinPos = 0;
double sectionMin = points[0].height;
size_t sectionMaxPos = 0;
double sectionMax = points[0].height;
for(size_t pos = 1; pos < points.size(); ++pos) {
DataPoint& point = points[pos];
if(point.height < sectionMin) {
// new minimum
sectionMin = point.height;
sectionMinPos = pos;
} else if(point.height > sectionMax) {
// new maximum
sectionMax = point.height;
sectionMaxPos = pos;
} else {
// no update check if we have a change in direction
if(sectionMinPos < sectionMaxPos) {
// maximum is last so check for a decrease
double diff = sectionMax - point.height;
if(diff > changeTolerance) {
// we have a change of direction add the old section and update the values
extractTrack(up, sectionStart, sectionMaxPos + 1);
if(Settings::verbose >= 1) {std::cerr << "Extracting raise from " << sectionStart << " to " << sectionMaxPos << "." << std::endl;}
sectionStart = sectionMaxPos;
sectionMinPos = pos;
sectionMin = point.height;
}
} else {
// minimum is last so check for a increase
double diff = point.height - sectionMin;
if(diff > changeTolerance) {
// we have a change of direction add the old section and update the values
extractTrack(down, sectionStart, sectionMinPos + 1);
if(Settings::verbose >= 1) {std::cerr << "Extracting fall from " << sectionStart << " to " << sectionMinPos << "." << std::endl;}
sectionStart = sectionMinPos;
sectionMaxPos = pos;
sectionMax = point.height;
}
}
}
}
// add the last section
DataPoint& startPoint = points[sectionStart];
if(sectionMax - startPoint.height > startPoint.height - sectionMin) {
// maximum has a bigger raise
extractTrack(up, sectionStart, points.size());
} else {
// minimum has a bigger fall
extractTrack(down, sectionStart, points.size());
}
}
Statistics Track::computeStatistics(bool combineHeight) const {
Statistics s;
s.init();
for(size_t pos = 1; pos < points.size(); pos += 1) {
const DataPoint& prevPoint = points[pos - 1];
const DataPoint& curPoint = points[pos];
long time = curPoint.time - prevPoint.time;
double height = curPoint.height - prevPoint.height;
double distancePlain = computePlainDist(curPoint, prevPoint);
s.update(time, distancePlain, height);
}
s.finalize(combineHeight);
return s;
}
void Track::extractTrack(std::vector<Track>& tracks, size_t start, size_t end) const {
tracks.resize(tracks.size() + 1);
Track& track = tracks.back();
track.points.insert(track.points.end(), points.begin() + start, points.begin() + end);
}
|
#ifndef BEAT_THE_BEAT_GAME_H
#define BEAT_THE_BEAT_GAME_H
#include "Utils.h"
#include "Inputs.h"
#include "Stave.h"
class Game {
public:
static Game* getInstance();
~Game();
void init();
private:
static Game* _instance;
Game();
Game(const Game&);
Game& operator=(const Game&);
enum GameState {
Uninitialized,
ShowingMenu,
Exiting
};
GameState _gameState;
sf::RenderWindow _window;
sf::Clock _clock;
Stave _stave;
sf::Font _font;
sf::Text _fpsText;
float _fpsTimer;
int _fpsCount;
int _fpsCount2;
void gameLoop();
/***/
void update();
void draw();
void event();
bool isExiting();
void exitGame();
void loadAssets();
void initFpsText();
void updateFpsText(const sf::Time& deltatime);
void end();
};
#endif //BEAT_THE_BEAT_GAME_H
|
//Declaración de constantes
const int led = 13; //Da el nombre “led” para el pin 13
const int tiempoEncendido = 50; //En milisegundos
const int tiempoApagado = 50; //En milisegundos
//La estructura “setup()” se ejecuta una sola vez cada que la tarjeta Arduino es
//energizada o después de que el botón de reinicio es presionado.
void setup()
{
pinMode(led, OUTPUT); //Configura el pin "led" como salida digital
}
//La estructura “loop()” se repite indefinidamente mientras la tarjeta se
//mantenga energizada.
void loop()
{
digitalWrite(led, HIGH); //Establece el estado del pin "led" en alto (5V)
delay(tiempoEncendido); //Espera el Tiempo de encendido
digitalWrite(led, LOW); //Establece el estado del pin "led" en bajo (0V)
delay(tiempoApagado); //Espera el Tiempo de apagado
}
|
/******************************************************************************
* $Id$
*
* Project: libLAS - http://liblas.org - A BSD library for LAS format data.
* Purpose: LAS header writer implementation for C++ libLAS
* Author: Howard Butler, hobu.inc@gmail.com
*
******************************************************************************
* Copyright (c) 2010, Howard Butler
*
* 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 Martin Isenburg or Iowa Department
* of Natural Resources 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <liblas/header.hpp>
#include <liblas/point.hpp>
#include <liblas/spatialreference.hpp>
#include <liblas/detail/writer/header.hpp>
#include <liblas/detail/private_utility.hpp>
#include <liblas/detail/zippoint.hpp>
// boost
#include <boost/cstdint.hpp>
// std
#include <cassert>
#include <cstdlib> // std::size_t
#include <algorithm>
#include <fstream>
#include <iosfwd>
#include <ostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace boost;
using namespace std;
namespace liblas { namespace detail { namespace writer {
Header::Header(std::ostream& ofs, boost::uint32_t& count, liblas::Header const& header)
: m_ofs(ofs)
, m_header(header)
, m_pointCount(count)
{
}
void Header::write()
{
uint8_t n1 = 0;
uint16_t n2 = 0;
uint32_t n4 = 0;
// Figure out how many points we already have.
// Figure out if we're in append mode. If we are, we can't rewrite
// any of the VLRs including the Schema and SpatialReference ones.
bool bAppendMode = false;
// This test should only be true if we were opened in both
// std::ios::in *and* std::ios::out
// Seek to the beginning
m_ofs.seekp(0, ios::beg);
ios::pos_type begin = m_ofs.tellp();
// Seek to the end
m_ofs.seekp(0, ios::end);
ios::pos_type end = m_ofs.tellp();
if ((begin != end) && (end != static_cast<ios::pos_type>(0))) {
bAppendMode = true;
}
// If we are in append mode, we are not touching *any* VLRs.
if (bAppendMode)
{
// Believe the header
m_pointCount = m_header.GetPointRecordsCount();
// Position to the beginning of the file to start writing the header
m_ofs.seekp(0, ios::beg);
}
else
{
// Rewrite the georeference VLR entries if they exist
m_header.DeleteVLRs("liblas", 2112);
m_header.SetGeoreference();
// If we have a custom schema, add the VLR and write it into the
// file.
if (m_header.GetSchema().IsCustom()) {
// Wipe any schema-related VLRs we might have, as this is now out of date.
m_header.DeleteVLRs("liblas", 7);
VariableRecord v = m_header.GetSchema().GetVLR();
std::cout << m_header.GetSchema()<< std::endl;
m_header.AddVLR(v);
}
// add the laszip VLR, if needed
if (m_header.Compressed())
{
#ifdef HAVE_LASZIP
m_header.DeleteVLRs("laszip encoded", 22204);
ZipPoint zpd(m_header.GetDataFormatId(), m_header.GetVLRs());
VariableRecord v;
zpd.ConstructVLR(v);
m_header.AddVLR(v);
#else
throw configuration_error("LASzip compression support not enabled in this libLAS configuration.");
#endif
}
else
{
m_header.DeleteVLRs("laszip encoded", 22204);
}
int32_t existing_padding = m_header.GetDataOffset() -
(m_header.GetVLRBlockSize() +
m_header.GetHeaderSize());
if (existing_padding < 0)
{
int32_t d = abs(existing_padding);
// If our required VLR space is larger than we have
// room for, we have no padding. AddVLRs will take care
// of incrementing up the space it needs.
if (static_cast<boost::int32_t>(m_header.GetVLRBlockSize()) > d)
{
m_header.SetHeaderPadding(0);
} else {
m_header.SetHeaderPadding(d - m_header.GetVLRBlockSize());
}
} else {
// cast is safe, we've already checked for < 0
if (static_cast<uint32_t>(existing_padding) >= m_header.GetHeaderPadding())
{
m_header.SetHeaderPadding(existing_padding);
}
else {
m_header.SetHeaderPadding(m_header.GetHeaderPadding() + existing_padding);
}
}
m_header.SetDataOffset( m_header.GetHeaderSize() +
m_header.GetVLRBlockSize() +
m_header.GetHeaderPadding());
}
// 1. File Signature
std::string const filesig(m_header.GetFileSignature());
assert(filesig.size() == 4);
detail::write_n(m_ofs, filesig, 4);
// 2. File SourceId / Reserved
if (m_header.GetVersionMinor() == 0) {
n4 = m_header.GetReserved();
detail::write_n(m_ofs, n4, sizeof(n4));
} else if (m_header.GetVersionMinor() > 0) {
n2 = m_header.GetFileSourceId();
detail::write_n(m_ofs, n2, sizeof(n2));
n2 = m_header.GetReserved();
detail::write_n(m_ofs, n2, sizeof(n2));
}
// 3-6. GUID data
boost::uint8_t d[16];
boost::uuids::uuid u = m_header.GetProjectId();
d[0] = u.data[3];
d[1] = u.data[2];
d[2] = u.data[1];
d[3] = u.data[0];
d[4] = u.data[5];
d[5] = u.data[4];
d[6] = u.data[7];
d[7] = u.data[6];
for (int i=8; i<16; i++)
d[i] = u.data[i];
detail::write_n(m_ofs, d, 16);
// 7. Version major
n1 = m_header.GetVersionMajor();
assert(1 == n1);
detail::write_n(m_ofs, n1, sizeof(n1));
// 8. Version minor
n1 = m_header.GetVersionMinor();
detail::write_n(m_ofs, n1, sizeof(n1));
// 9. System ID
std::string sysid(m_header.GetSystemId(true));
assert(sysid.size() == 32);
detail::write_n(m_ofs, sysid, 32);
// 10. Generating Software ID
std::string softid(m_header.GetSoftwareId(true));
assert(softid.size() == 32);
detail::write_n(m_ofs, softid, 32);
// 11. Flight Date Julian
n2 = m_header.GetCreationDOY();
detail::write_n(m_ofs, n2, sizeof(n2));
// 12. Year
n2 = m_header.GetCreationYear();
detail::write_n(m_ofs, n2, sizeof(n2));
// 13. Header Size
n2 = m_header.GetHeaderSize();
assert(227 <= n2);
detail::write_n(m_ofs, n2, sizeof(n2));
// 14. Offset to data
n4 = m_header.GetDataOffset();
detail::write_n(m_ofs, n4, sizeof(n4));
// 15. Number of variable length records
n4 = m_header.GetRecordsCount();
detail::write_n(m_ofs, n4, sizeof(n4));
// 16. Point Data Format ID
n1 = static_cast<uint8_t>(m_header.GetDataFormatId());
uint8_t n1tmp = n1;
if (m_header.Compressed()) // high bit set indicates laszip compression
n1tmp |= 0x80;
detail::write_n(m_ofs, n1tmp, sizeof(n1tmp));
// 17. Point Data Record Length
n2 = m_header.GetDataRecordLength();
detail::write_n(m_ofs, n2, sizeof(n2));
// 18. Number of point records
// This value is updated if necessary, see UpdateHeader function.
n4 = m_header.GetPointRecordsCount();
detail::write_n(m_ofs, n4, sizeof(n4));
// 19. Number of points by return
std::vector<uint32_t>::size_type const srbyr = 5;
std::vector<uint32_t> const& vpbr = m_header.GetPointRecordsByReturnCount();
// TODO: fix this for 1.3, which has srbyr = 7; See detail/reader/header.cpp for more details
// assert(vpbr.size() <= srbyr);
uint32_t pbr[srbyr] = { 0 };
std::copy(vpbr.begin(), vpbr.begin() + srbyr, pbr); // FIXME: currently, copies only 5 records, to be improved
detail::write_n(m_ofs, pbr, sizeof(pbr));
// 20-22. Scale factors
detail::write_n(m_ofs, m_header.GetScaleX(), sizeof(double));
detail::write_n(m_ofs, m_header.GetScaleY(), sizeof(double));
detail::write_n(m_ofs, m_header.GetScaleZ(), sizeof(double));
// 23-25. Offsets
detail::write_n(m_ofs, m_header.GetOffsetX(), sizeof(double));
detail::write_n(m_ofs, m_header.GetOffsetY(), sizeof(double));
detail::write_n(m_ofs, m_header.GetOffsetZ(), sizeof(double));
// 26-27. Max/Min X
detail::write_n(m_ofs, m_header.GetMaxX(), sizeof(double));
detail::write_n(m_ofs, m_header.GetMinX(), sizeof(double));
// 28-29. Max/Min Y
detail::write_n(m_ofs, m_header.GetMaxY(), sizeof(double));
detail::write_n(m_ofs, m_header.GetMinY(), sizeof(double));
// 30-31. Max/Min Z
detail::write_n(m_ofs, m_header.GetMaxZ(), sizeof(double));
detail::write_n(m_ofs, m_header.GetMinZ(), sizeof(double));
if (!bAppendMode)
{
WriteVLRs();
// if we have padding, we should write it
if (m_header.GetHeaderPadding() > 0) {
m_ofs.seekp(m_header.GetHeaderSize() + m_header.GetVLRBlockSize(), std::ios::end);
detail::write_n(m_ofs, "\0", m_header.GetHeaderPadding());
}
// Write the 1.0 pad signature if we need to.
WriteLAS10PadSignature();
}
// If we already have points, we're going to put it at the end of the file.
// If we don't have any points, we're going to leave it where it is.
if (m_pointCount != 0)
{
m_ofs.seekp(0, std::ios::end);
}
else
{
m_ofs.seekp(m_header.GetDataOffset(), std::ios::beg);
}
}
void Header::WriteVLRs()
{
// Seek to the end of the public header block (beginning of the VLRs)
// to start writing
m_ofs.seekp(m_header.GetHeaderSize(), std::ios::beg);
int32_t diff = m_header.GetDataOffset() - GetRequiredHeaderSize();
if (diff < 0) {
m_header.SetDataOffset(GetRequiredHeaderSize());
// Seek to the location of the data offset in the header and write a new one.
m_ofs.seekp(96, std::ios::beg);
detail::write_n(m_ofs, m_header.GetDataOffset(), sizeof(m_header.GetDataOffset()));
m_ofs.seekp(m_header.GetHeaderSize(), std::ios::beg);
// std::ostringstream oss;
// oss << "Header is not large enough to contain VLRs. Data offset is ";
// oss << m_header.GetDataOffset() << " while the required total size ";
// oss << "for the VLRs is " << GetRequiredHeaderSize();
// throw std::runtime_error(oss.str());
}
for (uint32_t i = 0; i < m_header.GetRecordsCount(); ++i)
{
VariableRecord const &vlr = m_header.GetVLR(i);
detail::write_n(m_ofs, vlr.GetReserved(), sizeof(uint16_t));
detail::write_n(m_ofs, vlr.GetUserId(true).c_str(), 16);
detail::write_n(m_ofs, vlr.GetRecordId(), sizeof(uint16_t));
detail::write_n(m_ofs, vlr.GetRecordLength(), sizeof(uint16_t));
detail::write_n(m_ofs, vlr.GetDescription(true).c_str(), 32);
std::vector<uint8_t> const& data = vlr.GetData();
std::streamsize const size = static_cast<std::streamsize>(data.size());
if(size > 0)
{
detail::write_n(m_ofs, data.front(), size);
}
}
}
boost::int32_t Header::GetRequiredHeaderSize() const
{
return m_header.GetVLRBlockSize() + m_header.GetHeaderSize();
}
void Header::WriteLAS10PadSignature()
{
// Only write pad signature bytes for LAS 1.0 files. Any other files
// will not get the pad bytes and we are *not* allowing anyone to
// override this either - hobu
if (m_header.GetVersionMinor() > 0) {
return;
}
int32_t diff = m_header.GetDataOffset() - GetRequiredHeaderSize();
if (diff < 2) {
m_header.SetDataOffset(m_header.GetDataOffset() + 2);
// Seek to the location of the data offset in the header and write a new one.
m_ofs.seekp(96, std::ios::beg);
detail::write_n(m_ofs, m_header.GetDataOffset(), sizeof(m_header.GetDataOffset()));
}
// step back two bytes to write the pad bytes. We should have already
// determined by this point if a) they will fit b) they won't overwrite
// exiting real data
m_ofs.seekp(m_header.GetDataOffset() - 2, std::ios::beg);
// Write the pad bytes.
uint8_t const sgn1 = 0xCC;
uint8_t const sgn2 = 0xDD;
detail::write_n(m_ofs, sgn1, sizeof(uint8_t));
detail::write_n(m_ofs, sgn2, sizeof(uint8_t));
}
}}} // namespace liblas::detail::writer
|
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<queue>
using namespace std;
class point{
public:
int x;
int y;
point(int a=0,int b=0){
x=a;
y=b;
}
bool friend operator == (point a, point b){return (a.x == b.x) && (a.y == b.y);}
};
int board[8][8]={0};
int dx[8]={1,-1,2,2,1,-1,-2,-2};
int dy[8]={2,2,1,-1,-2,-2,1,-1};
int main(){
char x1,y1,x2,y2;
while(scanf("%c%c",&x1,&y1)!=EOF){
for(int i=0;i<8;i++)
for(int j=0;j<8;j++){
board[i][j]=-1;
}
point a,b;
a.y=x1-'a';
a.x=y1-'1';
board[a.x][a.y]=0;
getchar();
scanf("%c%c",&x2,&y2);
getchar();
b.y=x2-'a';
b.x=y2-'1';
board[b.x][b.y]=0;
queue<point> q;
q.push(a);
point s,ns;
while(!q.empty()){
s=q.front();
q.pop();
if(s==b){
break;
}else{
for(int i=0;i<8;i++){
ns=point(s.x+dx[i],s.y+dy[i]);
if((0<=ns.x)&&(ns.x<8)&&(0<=ns.y)&&(ns.y<8)){
if(board[ns.x][ns.y]<=0){
board[ns.x][ns.y]=board[s.x][s.y]+1;
q.push(ns);
}
}
}
}
}
printf("%d %d %d %d\n",x1,y1,x2,y2);
printf("To get from %c%c to %c%c takes %d knight moves.\n",x1,y1,x2,y2,board[b.x][b.y]);
}
return 0;
}
|
#include "utils.hpp"
namespace serpent {
std::bitset<32> cshr(std::bitset<32> const& val, size_t shift) {
assert(shift < 32);
std::bitset<32> res;
size_t cur = 0;
for (size_t i = shift; i < 32; i++) {
res[cur++] = val[i];
}
for (size_t i = 0; i < shift; i++) {
res[cur++] = val[i];
}
return res;
}
std::bitset<32> shr(std::bitset<32> const& val, size_t shift) {
assert(shift < 32);
std::bitset<32> res;
size_t cur = 0;
for (size_t i = shift; i < 32; i++) {
res[cur++] = val[i];
}
return res;
}
std::bitset<32> cshl(std::bitset<32> const& val, size_t shift) {
assert(shift < 32);
std::bitset<32> res;
size_t cur = 0;
for (size_t i = 32 - shift; i < 32; i++) {
res[cur++] = val[i];
}
for (size_t i = 0; i < 32 - shift; i++) {
res[cur++] = val[i];
}
return res;
}
std::bitset<32> shl(std::bitset<32> const& val, size_t shift) {
assert(shift < 32);
std::bitset<32> res;
size_t cur = shift;
for (size_t i = 0; i < 32 - shift; i++) {
res[cur++] = val[i];
}
return res;
}
std::array<std::bitset<32>, 4> S(std::array<std::bitset<32>, 4> const& words, size_t round, bool inverse) {
auto current_s = (inverse) ? table::INV_S[round % 8] : table::S[round % 8];
std::array<std::bitset<32>, 4> result;
for (size_t i = 0; i < 4; i++) {
uint32_t cur = words[i].to_ulong();
uint32_t res = 0;
for (size_t j = 0; j < 4; j++) {
unsigned char byte = (cur >> (8 * j)) & 0xff;
unsigned char lower = byte >> 4;
unsigned char upper = byte & 0x0f;
res |= ((current_s[lower] << 4) | (current_s[upper])) << ((3 - j) * 8);
}
result[i] = std::bitset<32>(res);
}
return result;
}
std::array<std::bitset<32>, 4> S1(std::bitset<128> const& message, size_t round, bool inverse) {
auto splited = split<4>(message);
return S(splited, round, inverse);
}
std::bitset<128> S(std::bitset<128> const& message, size_t round, bool inverse) {
auto res = S1(message, round, inverse);
return res[0] + res[1] + res[2] + res[3];
}
void generate_keys(std::bitset<256> const& real, std::array<std::bitset<128>, 33>& keys) {
std::vector<std::bitset<32>> words(140);
for (size_t i = 0; i < 256; i++) {
words[i / 32][i % 32] = real[i];
}
for (size_t i = 8; i < 140; i++) {
std::bitset<32> ibit(i - 8);
words[i] = cshr(words[i - 8] ^ words[i - 5] ^ words[i - 3] ^ words[i - 1] ^ table::phi ^ ibit, 11);
}
words.erase(words.begin(), words.begin() + 8);
assert(words.size() == 132);
std::vector<std::bitset<32>> almost_keys(132);
for (size_t i = 0, j = 3, cnt = 0; i < 33; i++, (j == 0) ? j = 7 : j--) {
auto pack = S({words[i * 4], words[i * 4 + 1], words[i * 4 + 2], words[i * 4 + 3]}, j);
for (size_t i = 0; i < 4; i++) {
almost_keys[cnt++] = pack[i];
}
}
for (size_t i = 0; i < 33; i++) {
keys[i] = almost_keys[4 * i] + almost_keys[4 * i + 1] + almost_keys[4 * i + 2] + almost_keys[4 * i + 3];
keys[i] = permute(keys[i], table::IP);
}
}
std::string from_block(std::bitset<128> const& b) {
std::vector<unsigned char> res(16);
size_t counter = 0;
for (size_t i = 0; i < 16; i++) {
for (size_t j = 0; j < 8; j++) {
if (b[counter++]) {
res[i] |= (1 << (7 - j));
}
}
}
return std::string(res.begin(), res.end());
}
std::bitset<128> linear(std::bitset<128> const& mes) {
std::bitset<128> result;
result = permute(mes, table::FP);
auto X = split<4>(result);
X[0] = cshl(X[0], 13);
X[2] = cshl(X[2], 3);
X[1] = X[1] ^ X[0] ^ X[2];
X[3] = X[3] ^ X[2] ^ shl(X[0], 3);
X[1] = cshl(X[1], 1);
X[3] = cshl(X[3], 7);
X[0] = X[0] ^ X[1] ^ X[3];
X[2] = X[2] ^ X[3] ^ shl(X[1], 7);
X[0] = cshl(X[0], 5);
X[2] = cshl(X[2], 22);
result = X[0] + X[1] + X[2] + X[3];
result = permute(result, table::IP);
return result;
}
std::bitset<128> inv_linear(std::bitset<128> const& mes) {
std::bitset<128> result;
result = permute(mes, table::FP);
auto X = split<4>(result);
X[2] = cshr(X[2], 22);
X[0] = cshr(X[0], 5);
X[2] = X[2] ^ X[3] ^ shl(X[1], 7);
X[0] = X[0] ^ X[1] ^ X[3];
X[3] = cshr(X[3], 7);
X[1] = cshr(X[1], 1);
X[3] = X[3] ^ X[2] ^ shl(X[0], 3);
X[1] = X[1] ^ X[0] ^ X[2];
X[2] = cshr(X[2], 3);
X[0] = cshr(X[0], 13);
result = X[0] + X[1] + X[2] + X[3];
result = permute(result, table::IP);
return result;
}
std::bitset<256> convert_key(const std::string& key) {
std::bitset<256> real;
if (key.size() == 16) {
auto block_key = to_block<16>(key);
copy_and_append(block_key, real);
} else if (key.size() == 24) {
auto block_key = to_block<24>(key);
copy_and_append(block_key, real);
} else if (key.size() == 32) {
real = to_block<32>(key);
} else {
throw std::runtime_error("Wrong key size: " + std::to_string(key.size()));
}
return real;
}
} // namespace serpent
|
/*
* Assignennt 2, COMP 5421, summer 2016
* Federico O'Reilly Regueiro 40012304
* Concordia University
*
* Line Editor implementation file
*/
#include "LineEditor.h"
LineEditor::LineEditor (const string& filename) {
this->filename = filename;
openHelper();
}
void LineEditor::run () {
displayEnteringCommand();
while (cin.good() && !quitLed) {
displayPrompt();
string commandBuffer;
getline(cin, commandBuffer);
bool valid = com.parse(commandBuffer, currentLine, buffer.size());
const Command::AddressRange ar = com.getAddressRange();
const Command::CommandType ct = com.getCommandType();
if (valid) {
routeCommand(ct, ar);
} else {
if (com.getCommandStatus() == Command::invalidRange) {
if (buffer.size() == 0) {
bool validInit = ((ct == Command::insert)
|| (ct == Command::append));
if (validInit) {
routeCommand(ct, Command::AddressRange(0,0));
} else {
string e1 = "error: file empty ";
string e2 = "- enter 'q' to quit, 'a' to append, ";
string e3 = "'i' to insert or 'h' for help";
cerr << e1 << e2 << e3 << endl;
}
} else {
cerr << "error: invalid range " << ar.start << " through "
<< ar.end << endl;
}
} else {
cerr << "error: invalid command." << endl;
}
}
}
}
void LineEditor::insert (const size_t& line) {
insertAppendHelper (line, true);
}
void LineEditor::append (const size_t& line) {
insertAppendHelper (line, false);
}
void LineEditor::remove (const Command::AddressRange& ar) {
auto it1 = buffer.begin();
auto it2 = buffer.begin();
advance(it1, ar.start-1);
advance(it2, ar.end);
buffer.erase(it1, it2);
currentLine = ar.start - 1;
dirty = true;
}
void LineEditor::print (const Command::AddressRange& ar
, const bool& numbered /*= false*/) {
auto it1 = buffer.begin();
auto it2 = buffer.begin();
advance(it1, ar.start-1);
advance(it2, ar.end);
currentLine = ar.start;
while (it1 != it2) {
string prepend = numbered ? "(" + to_string(currentLine) + ") " : "";
cout << prepend << *it1 << endl;
++it1;
++currentLine;
}
currentLine = ar.end;
}
void LineEditor::printCurrLine () {
cout << currentLine << endl;
}
void LineEditor::change (const Command::AddressRange& ar) {
size_t found;
string toBeReplaced;
string replacement;
cout << "change what? ";
getline (cin, toBeReplaced);
cout << "by what? ";
getline (cin, replacement);
// now make the required changes
auto start = buffer.begin();
advance(start, ar.start -1);
auto end = buffer.begin();
advance(end, ar.end);
while(start != end) {
found = start->find(toBeReplaced);
while (found != string::npos) {
start->replace(found, toBeReplaced.length(), replacement);
++found;
found = start->find(toBeReplaced, found);
}
++start;
}
currentLine = ar.end;
dirty = true;
}
void LineEditor::move (const size_t& lines, const bool& isUp /* = false*/) {
if (buffer.size() == 0) {
currentLine = 0;
}
else if (isUp) {
if (lines < currentLine) {
currentLine -= lines;
} else {
currentLine = 1;
cerr << "BOF reached" << endl;
}
} else {
if (lines <= (buffer.size() - currentLine)) {
currentLine += lines;
} else {
currentLine = buffer.size();
cerr << "EOF reached" << endl;
}
}
}
void LineEditor::write () {
if (filename.empty()) {
cout << "Name of the file to be saved? ";
// TODO some form of input validation for this
cin >> filename;
// TODO check if it exists and prompt to verwrite
}
ofstream ofs;
ofs.open(filename, ofstream::out | ofstream::trunc);
if (ofs.is_open()) {
auto it = buffer.begin();
while (it != buffer.end()) {
ofs << *it << endl;
++it;
}
ofs.close();
cout << "\"" << filename << "\" " << to_string(buffer.size())
<< " lines" << endl;
dirty = false;
} else {
cerr << "error: couldn't open " << filename << " for writing" << endl;
}
}
void LineEditor::quit () {
if (dirty) {
saveChanges();
}
quitLed = true;
}
void LineEditor::open () {
string newFilename;
if (dirty) {
saveChanges();
}
cout << "open file, filename? ";
if (cin.good()) {
getline(cin, newFilename);
} // TODO some form of validation
filename = newFilename;
buffer.clear(); // clear will call destructors on each string, nice!
currentLine = 0;
openHelper();
dirty = false;
}
void LineEditor::help () {
cout << "Line editor works on a text buffer one line at a time." << endl;
cout << "Valid commands are of the form [m][,[n]][c], where [] denote ";
cout << "optional parameters, m and n denote a start-end line number pair ";
cout << "that represents a range of lines to be affected by the command ";
cout << "c. Defaults for m and n are the current line and c ";
cout << "defaults to print."<< endl;
cout << "There are two address special characters: '.' and '$' which ";
cout << "represent the current line and the last line respectively." << endl;
cout << "If only a comma is input the whole buffer is ";
cout << "printed. The commands are: " << endl;
cout << (char) Command::insert << " - insert" << endl;
cout << (char) Command::append << " - append" << endl;
cout << (char) Command::print << " - print" << endl;
cout << (char) Command::numberPrint << " - numbered print" << endl;
cout << (char) Command::change << " - change" << endl;
cout << (char) Command::up << " - move up"<< endl;
cout << (char) Command::down << " - move down" << endl;
cout << (char) Command::write << " - write buffer to file" << endl;
cout << (char) Command::printCurrLine << " - print current line number" << endl;
cout << (char) Command::quit << " - quit led" << endl;
cout << (char) Command::open << " - open another file" << endl;
cout << (char) Command::help << " - print this help message" << endl;
cout << "The " << (char) Command::insert << " and ";
cout << (char) Command::append << " commands ";
cout << "take lines to be input from stdin, in order to exit back ";
cout << "into command mode, the user must enter a single '.',. " << endl;
cout << "When a buffer contains unmodified data, the prompt will display ";
cout << "a star. The user will be prompted to save when quitting or ";
cout << "opening another file.";
cout << endl;
}
void LineEditor::openHelper () {
if (!filename.empty()) {
ifstream file(filename);
string fileLine;
if (file.is_open()) {
while (getline(file, fileLine)) {
buffer.push_back(fileLine);
++currentLine;
}
file.close();
cout << "\"" << filename << "\" " << to_string(buffer.size())
<< " lines" << endl;
} else {
cerr << "Unable to open file " << filename << endl;
cout << "\"" << filename << "\" [New File]" << endl;
}
} else {
cout << "\"?\" [New File]" << endl;
}
}
void LineEditor::insertAppendHelper (const size_t& line, const bool& isInsert) {
string inputLine;
auto it = buffer.begin();
getline (cin , inputLine);
if (!buffer.empty()) {
size_t linesToAdvance = (isInsert) ? line-1 : line;
advance(it, linesToAdvance);
currentLine = linesToAdvance;
}
while (cin.good () && inputLine != ".")
{
buffer.insert(it, inputLine);
currentLine++;
dirty = true;
getline (cin , inputLine);
}
displayEnteringCommand();
}
void LineEditor::saveChanges () {
string name = (filename.empty()) ? "[New File]" : filename;
cout << "Save changes to " << name << " (y/n)?" << endl;
char yn;
cin >> yn;
while (cin.good() && yn != 'y' && yn != 'n' && yn != 'Y' && yn != 'N') {
cin >> yn;
}
// clear the input buffer
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (yn == 'Y' || yn == 'y') {
write();
}
}
void LineEditor::displayEnteringCommand() {
cout << "Entering command mode." << endl;
}
void LineEditor::displayPrompt() {
cout << ((dirty) ? "*:" : " :");
}
void LineEditor::routeCommand (const Command::CommandType& ct,
const Command::AddressRange& ar) {
switch (ct) {
case Command::insert:
insert(ar.start);
break;
case Command::append:
append(ar.end);
break;
case Command::remove:
remove(ar);
break;
case Command::print:
print(ar);
break;
case Command::numberPrint:
print(ar, true);
break;
case Command::change:
change(ar);
break;
case Command::up:
move(ar.start, true);
break;
case Command::down:
move(ar.end);
break;
case Command::write:
write();
break;
case Command::printCurrLine:
printCurrLine();
break;
case Command::quit:
quit();
break;
case Command::open:
open();
break;
case Command::help:
help();
break;
case Command::notRecognized:
cerr << "error: command not recognized by the parser" << endl;
break;
default:
cerr << "error: being here defies all logic..." << endl;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#ifndef __SMC_MAN_H__
#define __SMC_MAN_H__
#if defined _NATIVE_SSL_SUPPORT_ && defined _SSL_USE_EXTERNAL_KEYMANAGERS_
#include "modules/util/smartptr.h"
#include "modules/hardcore/base/periodic_task.h"
#include "modules/libssl/handshake/hand_types.h"
class OpKeyManStatus : public OpStatus
{
public:
enum
{
UNSUPPORTED_VERSION = USER_ERROR + 1,
DISABLED_MODULE = USER_ERROR + 2,
};
};
/** Client Key Manager Base Class
* This Base class is used to administrate external public key
* systems, like smart cards
*/
class SSL_KeyManager : public ListElement<SSL_KeyManager>, public OpReferenceCounter
{
public:
SSL_KeyManager();
~SSL_KeyManager();
/** Retrieve a list of the Public Keys and certificates available from this provider, items are added to cipherlist
* Optionally, the provider can select certificates based on a list of DER-encoded CA issuer names provided by the server,
* or based on the the server's name and port.
*
* Implementations should use SetupCertificateEntry() to add the certificate and key to the list, and to
* use AllowedCertificate() to check if a certificate issuer is permitted.
*
* @param cipherlist Pointer to list in which to add the combined certificate and key handlers
* @param ca_names List of DER encoded certificate issuer names, as provided by the server. Empty list means no restrictions.
* @param sn Servername object for the server being accessed.
* @param port The port number on the server we are connecting to.
*/
virtual OP_STATUS GetAvailableKeys(SSL_CertificateHandler_ListHead *cipherlist, SSL_DistinguishedName_list &ca_names, ServerName *sn, uint16 port) = 0;
#ifdef _SSL_USE_SMARTCARD_
/** Checks that all keys are present in their locations, and takes necessary actions for
* those keys that are no longer present, such as removing content authorized by the key
*
* This operation MUST NOT block, and MUST return immediately after checking the status.
*/
virtual void ConfirmKeysPresent() = 0;
#endif
/** Returns TRUE if this interface is not presently in use */
//BOOL Idle();
/** Returns last time used */
//time_t LastUsed();
/** Updates the last used timestamp */
//void WasUsedNow();
/** Register this manager in the main manager */
void Register(){g_ssl_api->RegisterExternalKeyManager((SSL_KeyManager *) this);};
/** Unregister this manager from the main manager */
void Unregister(){if(InList()) Out();};
protected:
/** Easy to use function to add a new cert and key item to the list, along with the required information
*
* @param cipherlist Pointer to list in which to add the combined certificate and key handlers
* @param lbl String with a label for the certificate
* @param shortname A short name for the key, used in list of available certificates
* @param certlist List of certificates, the first is the key's certificate, the others are issuer
* certificates, where the second signed the immediately preceding certificate
* @param pkey The handler of the private key to be used to sign the authentication. This key may or may not be login protected.
*/
OP_STATUS SetupCertificateEntry(SSL_CertificateHandler_ListHead *cipherlist, const OpStringC &lbl, const OpStringC &shortname, SSL_ASN1Cert_list &cert, SSL_PublicKeyCipher *pkey);
/** Checks if the issuer_candidate is in the list of issusers listed by the server
*
* @param ca_names List of DER encoded certificate issuer names, as provided by the server. Empty list means no restrictions.
* @param issuer_candidate DER encoded issuer name to be checked against ca_names list
* @return BOOL TRUE if allowed by the list.
*/
BOOL AllowedCertificate(SSL_DistinguishedName_list &ca_names, SSL_DistinguishedName &issuer_candidate);
};
typedef AutoDeleteList<SSL_KeyManager> SSL_Keymanager_Head;
/** The central manager of the key provider managers */
class SSL_ExternalKeyManager
#ifdef _SSL_USE_SMARTCARD_
: public PeriodicTask
#endif
{
private:
/** List of providers */
SSL_Keymanager_Head key_masters;
public:
SSL_ExternalKeyManager();
~SSL_ExternalKeyManager();
/** Intialize the Object */
OP_STATUS InitL();
private:
/** Retrieve a list of the Public Keys and certificates available from this provider, items are added to cipherlist
* Optionally, the provider can select certificates based on a list of DER-encoded CA issuer names provided by the server,
* or based on the the server's name and port.
*
* Implementations should use the SetupCertificateEntry to add the certificate and key to the list.
*
* @param cipherlist Pointer to list in which to add the combined certificate and key handlers
* @param ca_names List of DER encoded certificate issuer names, as provided by the server. Empty list means no restrictions.
* @param sn Servername object for the server being accessed.
* @param port The port number on the server we are connecting to.
*/
OP_STATUS GetAvailableKeys(SSL_CertificateHandler_ListHead *cipherlist, SSL_DistinguishedName_list &ca_names, ServerName *sn, uint16 port);
public:
#ifdef _SSL_USE_SMARTCARD_
/** Checks that all keys are present in their locations, and takes necessary actions for
* those keys that are no longer present, such as removing content authorized by the key
*
* This operation MUST NOT block, and MUST return immediately after checking the status.
*/
void ConfirmKeysPresent();
/** Action for the periodic task of checking if there are some keys removed from the system */
virtual void Run ();
#endif
/** Remove any masters that have been idle for more than 5 minutes */
//void RemoveIdle();
/** Are there any key providers? */
BOOL ActiveKeys(){return !key_masters.Empty();}
/** Add a new provider to the list of providers */
void RegisterKeyManager(SSL_KeyManager *provider){provider->Into(&key_masters);}
/** Retrieve a list of the Public Keys and certificates available from this provider, items are added to cipherlist
* Optionally, the provider can select certificates based on a list of DER-encoded CA issuer names provided by the server,
* or based on the the server's name and port.
*
* Implementations should use the SetupCertificateEntry to add the certificate and key to the list.
*
* @param cipherlist Pointer to list in which to add the combined certificate and key handlers
* @param ca_names List of DER encoded certificate issuer names, as provided by the server. Empty list means no restrictions.
* @param sn Servername object for the server being accessed.
* @param port The port number on the server we are connecting to.
*/
OP_STATUS GetAvailableKeysAndCertificates(SSL_CertificateHandler_ListHead *certs, SSL_DistinguishedName_list &ca_names, ServerName *sn, uint16 port);
};
#endif
#endif
|
#include "stdafx.h"
#include "cam.h"
#include <math.h>
#include "specmath.h"
#include <cassert>
cam::cam(vec3 look_from, vec3 look_to, float aspectRatio, float fov, float aperture, float focus_dist)
{
orig = look_from;
float theta = fov / 180.0f * specmath::PI;
float half_width_over_dist = tan(theta * 0.5);
float half_height = half_width_over_dist / aspectRatio;
vec3 world_up = vec3(0, 1, 0);
w = (orig - look_to).normalized();
u = world_up.cross(w).normalized();
v = w.cross(u);
llc = orig - half_width_over_dist * focus_dist * u - half_height * focus_dist * v - focus_dist * w;
horiz = 2.0f * u * half_width_over_dist * focus_dist;
vert = 2.0f * v * half_width_over_dist * focus_dist;
lens_radius = aperture / 2;
}
vec3 cam::origin() const
{
return orig;
}
vec3 cam::horizontal() const
{
return horiz;
}
vec3 cam::vertical() const
{
return vert;
}
ray cam::getRay(float s, float t) const
{
vec3 rd = specmath::random_inside_unit_disk() * lens_radius;
vec3 offset = rd.x() * u + rd.y() * v;
/*std::cout << offset;
assert(false);*/
return ray(orig + offset, llc + s * horiz + t * vert - orig - offset);
}
cam::~cam()
{
}
|
#include <cstdlib>
#include <iostream>
#include "uuidpp.h"
int main(int argc, char *argv[]) {
uuid u;
while (std::cin >> u)
if (u)
std::cout << u << std::endl;
return EXIT_SUCCESS;
};
//
|
#ifndef CBT_NODES_SEQUENCE_HPP
#define CBT_NODES_SEQUENCE_HPP
/* Models AND over return status,
* returns first failure, or abort, otherwise success.
*
* however, abort is not contagious in this case due to short circuiting.
* that is, we dont continue processing just to check if any abort.
*/
#include "cbt/behavior.hpp"
#include <array>
namespace cbt
{
auto sequence_impl(behavior *, std::uint8_t) -> behavior;
template<typename ...T>
auto sequence(T&&... xs) -> behavior
{
static_assert(sizeof...(T) < 256, "Too many nodes in sequence");
std::array<behavior, sizeof...(T)> a = { std::forward<T>(xs)... };
return sequence_impl(a.data(), static_cast<std::uint8_t>(a.size()));
}
} // namespace cbt
#endif // CBT_NODES_SEQUENCE_HPP
|
//
// Ellipse.h
// closedFrameworks
//
// Created by Charles Ringer on 27/03/2016.
// Copyright © 2016 WillMeaton.uk. All rights reserved.
//
#ifndef Ellipse_h
#define Ellipse_h
#include "Vector2D.h"
namespace Graphics{
class Ellipse{
private:
//Center point
Math::Vector2D cp;
//x radius and y radius
float xR, yR;
public:
Ellipse(const Math::Vector2D &cp, float xR, float yR)
{
this->cp=cp;
this->xR=xR;
this->yR=yR;
}
//Circle
Ellipse(const Math::Vector2D &cp, float r)
{
this->cp=cp;
xR=r;
yR=r;
}
Ellipse(float x, float y, float xR, float yR)
{
cp = Math::Vector2D(x, y);
xR = xR;
yR = yR;
}
//Circle
Ellipse(float x, float y, float r)
{
this->cp = Math::Vector2D(x, y);
xR = r;
yR = r;
}
void set(const Math::Vector2D &cp, float xR, float yR)
{
this->cp=cp;
this->xR=xR;
this->yR=yR;
}
void set(const Math::Vector2D &cp, float r)
{
this->cp=cp;
xR=r;
yR=r;
}
void set(float x, float y, float xR, float yR)
{
cp = Math::Vector2D(x, y);
xR = xR;
yR = yR;
}
void set(float x, float y, float r)
{
cp = Math::Vector2D(x, y);
xR = r;
yR = r;
}
//Getters
Math::Vector2D getVec() const { return cp;};
float getCX() const { return cp.x;};
float getCY() const { return cp.y;};
float getXR() const { return xR;};
float getYR() const { return yR;};
};
}
#endif /* Ellipse_h */
|
#include <sgfx/color.hpp>
#include <sgfx/primitives.hpp>
#include <sgfx/window.hpp>
#include <algorithm>
#include <numeric>
#include <random>
#include <utility>
#include <vector>
template <typename Container, typename Dest, typename F>
void transform(Container const& container, Dest dest, F f)
{
std::transform(begin(container), end(container), std::move(dest), std::move(f));
}
template <typename Container, typename Init, typename F>
auto accumulate(Container const& container, Init init, F f)
{
return std::accumulate(cbegin(container), cend(container), std::move(init), std::move(f));
}
int random_uniform_int(int max)
{
static std::mt19937 random_gen{std::random_device{}()};
std::uniform_int_distribution<int> dist(0, max - 1);
return dist(random_gen);
}
std::vector<sgfx::point> convex_hull(std::vector<sgfx::point> points)
{
// Graham scan, see: https://en.wikipedia.org/wiki/Graham_scan
std::vector<sgfx::point> ret_val;
enum class direction { clockwise, counterclockwise };
const auto compute_turn = [](sgfx::point first, sgfx::point second, sgfx::point third) {
if (((second.x - first.x) * (third.y - first.y) - (second.y - first.y) * (third.x - first.x)) <= 0)
return direction::clockwise;
return direction::counterclockwise;
};
const auto min_it =
std::min_element(std::begin(points), std::end(points), [](const auto& lhs, const auto& rhs) {
return lhs.y < rhs.y || (lhs.y == rhs.y && lhs.x < rhs.x);
});
std::swap(*min_it, points.front());
std::sort(std::begin(points) + 1, std::end(points), [&](const auto& lhs, const auto& rhs) {
return lhs != rhs && compute_turn(points.front(), lhs, rhs) == direction::counterclockwise;
});
for (const auto& p : points)
{
while (ret_val.size() > 2
&& compute_turn(ret_val[ret_val.size() - 2], ret_val[ret_val.size() - 1], p)
== direction::clockwise)
ret_val.pop_back();
ret_val.push_back(p);
}
return ret_val;
}
std::vector<sgfx::point> random_polygon(sgfx::dimension max_size, std::size_t vertices)
{
std::vector<sgfx::point> points;
std::generate_n(std::back_inserter(points), vertices, [&]() {
return sgfx::point{random_uniform_int(max_size.w), random_uniform_int(max_size.h)};
});
return points;
}
struct offset_polygon {
std::vector<sgfx::point> points;
sgfx::vec offset;
};
std::vector<sgfx::vec> edges(offset_polygon const& poly)
{
auto result = std::vector<sgfx::vec>{};
for (size_t i = 0; i < poly.points.size() - 1; ++i)
result.emplace_back(poly.points[i + 1] - poly.points[i]);
result.emplace_back(poly.points.back() - poly.points.front());
return result;
}
std::vector<sgfx::vec> axes(offset_polygon const& poly)
{
auto axes = std::vector<sgfx::vec>{};
transform(edges(poly), back_inserter(axes), [](auto& edge) { return perpendicular(edge); });
return axes;
}
sgfx::vec project(offset_polygon const& poly, sgfx::vec const& axis)
{
auto const edges = ::edges(poly);
// auto minimum = edges[0] * axis;
// auto maximum = minimum;
// for (size_t i = 1; i < edges.size(); ++i)
//{
// auto p = axis * edges[i];
// minimum = std::min(minimum, p);
// maximum = std::max(maximum, p);
//}
// return {minimum, maximum};
auto const minimum =
accumulate(edges, edges[0] * axis, [&](auto a, auto e) { return std::min(a, e * axis); });
auto const maximum =
accumulate(edges, edges[0] * axis, [&](auto a, auto e) { return std::max(a, e * axis); });
return {minimum, maximum};
}
void draw_outline(sgfx::canvas_view target, const offset_polygon& poly, sgfx::color::rgb_color col)
{
for (std::size_t i = 0; i < poly.points.size() - 1; ++i)
sgfx::line(target, poly.points[i] + poly.offset, poly.points[i + 1] + poly.offset, col);
sgfx::line(target, poly.points.front() + poly.offset, poly.points.back() + poly.offset, col);
}
constexpr bool overlap(sgfx::vec v, sgfx::vec w)
{
auto d = sgfx::vec{w.x - v.x, w.y - v.y};
return d * d != 0;
//return false; // TODO return (w - v) < 0;
}
bool sat_collide(const offset_polygon& poly0, const offset_polygon& poly1)
{
auto const axes0 = axes(poly0);
auto const axes1 = axes(poly1);
for (auto const axes : {axes0, axes1})
{
for (auto const axis : axes)
{
auto const p1 = project(poly0, axis);
auto const p2 = project(poly1, axis);
if (!overlap(p1, p2))
return false;
}
}
return true;
}
int main(int argc, char* argv[])
{
using namespace sgfx;
window main_window{1024, 768, "SAT-Test"};
offset_polygon poly0{convex_hull(random_polygon({300, 300}, 10)), {0, 0}};
offset_polygon poly1{convex_hull(random_polygon({300, 300}, 10)), {400, 0}};
while (main_window.handle_events() && !main_window.should_close())
{
if (main_window.is_pressed(key_id{'w'}))
poly0.offset.y -= 1;
if (main_window.is_pressed(key_id{'s'}))
poly0.offset.y += 1;
if (main_window.is_pressed(key_id{'a'}))
poly0.offset.x -= 1;
if (main_window.is_pressed(key_id{'d'}))
poly0.offset.x += 1;
if (main_window.is_pressed(key::up))
poly1.offset.y -= 1;
if (main_window.is_pressed(key::down))
poly1.offset.y += 1;
if (main_window.is_pressed(key::left))
poly1.offset.x -= 1;
if (main_window.is_pressed(key::right))
poly1.offset.x += 1;
clear(main_window, color::black);
const auto col = sat_collide(poly0, poly1) ? color::red : color::white;
draw_outline(main_window, poly0, col);
draw_outline(main_window, poly1, col);
main_window.show();
}
return 0;
}
|
/*First enter RGC irrespective of the order,then enter L,the dependent sources and then dependent sources */
#include<complex>
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
#include<cctype>
#include"stdio.h"
#include"stdlib.h"
#include<fstream>
#include<cmath>
#include<cstring>
#include<ctime>
using namespace std;
#include"print.h"
#include"stamping.h"
#include"functions.h"
#define pi 3.14
#define frequency_max 10e9
#define frequency_min 1e3
#define points 1000
int main(int argc, char *argv[])
{
double f_max=frequency_max;
double f_min=frequency_min;
double pts=points;
int count_s=0;
vector<vector<double> > X_big;
for(int num=1;num<argc;++num)
// char cont_1='y';
// while(cont_1=='y')
{
//if(cont_1=='y')
++count_s;
string input_file=argv[num];
cout<<" Entering the file : "<<input_file<<endl;
original_plus_MOR_giving_X_big(X_big,f_max,f_min,points,input_file);
// cout<<" DO YOU WANT TO ENTER THE FILES FOR OTHER CIRCUIT (Y/N)----: ";
// cin>> cont_1;
}// main while loop for different cicuits
file_write("SERIAL_X_BIG.txt",X_big);
cout<<"X_big written in SERIAL_X_BIG.txt"<<endl;
cout<<" number of circuits ran are : "<<count_s<<endl;
cout<<"the number of rows in X_big are : "<<X_big.size()<<" the number of columns in X_big are : "<<(X_big.at(0)).size()<<endl;
vector<vector<double> > X_svd;
vector<double> sigma;
cout<<"performing SVD................"<<endl;
double t1=clock();
SVD(X_svd,sigma,X_big);
file_write("SERIAL_X_SVD.txt",X_svd);
double t2=clock();
cout<<" TIME taken to compute SVD is : "<<(t2-t1)/double(CLOCKS_PER_SEC) << " seconds" <<endl;
cout<<"the number of rows in X_svd are : "<<X_svd.size()<<" the number of columns in X_svd are : "<<(X_svd.at(0)).size()<<endl;
cout<<"the number of elements in SIGMA are : "<<sigma.size()<<endl;
//writing the ratio in a file
fstream write("sigma.txt",fstream::out);
if(write.is_open())
{
for(int i=0;i<sigma.size();++i)
{
write<<i<<" "<<sigma[i]<<" "<<sigma[i]/sigma[0]<<endl;
}
write.close();
}
else cout<<"enable to open file"<<endl;
char answer='y';
while(answer=='y')
{
double thr;
int count_a=0;
cout<<"Enter the threshold for sigma matrix :";
cin>>thr;
for(int i=1;i<sigma.size();++i)
{
if(sigma[i]/sigma[0]>thr || sigma[i]/sigma[0]==thr)
{
++count_a;
}
}
cout<<" the no of columns are : "<<count_a<<endl;
vector<vector<double> > X_MATRIX;
retrun_X_MATRIX(X_MATRIX,X_svd,count_a);
cout<<"the number of rows in X_MATRIX are : "<<X_MATRIX.size()<<" the number of columns in X_MATRIX are : "<<(X_MATRIX.at(0)).size()<<endl;
original_plus_MOR_sending_X_MATRIX(X_MATRIX,f_max,f_min,points);
X_MATRIX.clear();
cout<<"do you want to continue for other vlaue of threshold (y/n) :";
cin>>answer;
}
cout<<"end of program"<<endl;
return 0;
}
|
#include "produceregz.h"
#include <thread>
#include "bnlogif.h"
#include "algo/aes_algo.h"
//begin cipher by liulijin add
#include "config.h"
#include <vector>
#include <algorithm>
//end cipher by liulijin add
static const size_t NDN_MAX_PACKET_SIZE = 7000;
static const size_t DATA_EMPTY_ITEM_SIZE = 300;
static const int CONNECTION_RETRY_TIMER = 1;
ProducerEgz::ProducerEgz(const string& macaddr, const string& bsdrmarket, int thrnum) :
m_macaddr(macaddr),
m_bsdrmarket(bsdrmarket),
m_thrnum(thrnum),
m_pegzface(nullptr),
pEgzListenThr(NULL),
m_egzseq(0),
m_pEgzSending(NULL),
m_pEgzSendingTail(NULL),
m_pEgzCathe(NULL)
{
}
ProducerEgz::~ProducerEgz()
{
stop();
}
string ProducerEgz::getBsdrMarket()
{
return m_bsdrmarket;
}
int ProducerEgz::getThrNum()
{
return m_thrnum;
}
bool ProducerEgz::run()
{
pEgzListenThr = new std::thread(&ProducerEgz::doRunEgz, this);
if(NULL == pEgzListenThr)
{
return false;
}
return true;
}
void ProducerEgz::doRunEgz()
{
std::ostringstream s;
s << m_thrnum;
string strName = "/yl/broadcast/egz/baar/producer/" + m_macaddr + "/"
+ m_bsdrmarket + "/" + s.str();
do
{
try
{
m_pegzface = std::unique_ptr<Face>(new Face);
if(nullptr == m_pegzface)
{
continue;
}
BN_LOG_INTERFACE("run egz producer:%s", strName.c_str());
// std::cout << "run egz producer:" << strName << std::endl << std::endl ;
m_listenId = m_pegzface->setInterestFilter(
strName,
bind(&ProducerEgz::onEgzInterest, this, _1, _2),
RegisterPrefixSuccessCallback(),
bind(&ProducerEgz::onEgzRegisterFailed, this, _1, _2)
);
m_pegzface->processEvents();
}
catch (std::runtime_error& e)
{
BN_LOG_ERROR("egz producer catch nfd error:%s", e.what());
}
catch(...)
{
BN_LOG_ERROR("egz producer process events catch unknow error.");
}
m_pegzface = nullptr;
if(m_shouldresume)
{
sleep(CONNECTION_RETRY_TIMER);
}
} while(m_shouldresume);
BN_LOG_INTERFACE("end egz service[bsdr market:%s][producer number:%d]",
m_bsdrmarket.c_str(), m_thrnum);
}
void ProducerEgz::stop()
{
// std::lock_guard<std::mutex> lock(m_resumeMutex);
BN_LOG_INTERFACE("producer[bsdr market:%s][producer number:%d]", m_bsdrmarket.c_str(), m_thrnum);
m_shouldresume = false;
if(m_pegzface != nullptr)
{
BN_LOG_INTERFACE("m_pegzface != nullptr]");
m_pegzface->shutdown();
}
if(pEgzListenThr != NULL)
{
pEgzListenThr->join();
pEgzListenThr = NULL;
}
m_pegzface = nullptr;
// BrCache::Instance()->InsertBNLinkData(m_bsdrmarket, m_pSending);
// BrCache::Instance()->InsertBNLinkData(m_bsdrmarket, m_pCache);
}
void ProducerEgz::onEgzInterest(const InterestFilter& filter, const Interest& interest)
{
// _LOG_INFO("onEgzInterest [market:" << m_bsdrmarket << "][producer number:" << m_thrnum << "]""receive interest:" << interest);
// std::cout << "onEgzInterest [market:" << m_bsdrmarket << "][producer number:" << m_thrnum << "]""receive interest:" << interest<< std::endl << std::endl ;
Name dataName(interest.getName());
Name::Component comConfirm = dataName.get(-1);
std::string strConfirm = comConfirm.toUri();
long lSeqnum;
std::istringstream is(strConfirm);
is >> lSeqnum;
if(m_egzseq == lSeqnum)
{
EGZDataNode * ptmp = NULL;
while(m_pEgzSending != NULL)
{
ptmp = m_pEgzSending;
m_pEgzSending = m_pEgzSending->next;
delete ptmp->pdata;
delete ptmp;
}
}
++m_egzseq;
m_egzseq = m_egzseq % 100;
m_egzseq = (m_egzseq <= 0) ? 1 : m_egzseq;
std::ostringstream s;
s << m_egzseq;
string content("<BrData><Seq>");
content += s.str();
content += "</Seq>";
if(m_pEgzSending != NULL)
{
EGZDataNode * ptmp = m_pEgzSending;
while(ptmp != NULL)
{
content = content + ptmp->pdata->toItemString();
ptmp = ptmp->next;
}
}
else
{
if(NULL == m_pEgzCathe)
{
BrCache::Instance()->GetEgzData(m_bsdrmarket, &m_pEgzCathe);
}
EGZDataNode * pTmpDataNode = NULL;
size_t packetsize = 0;
while(m_pEgzCathe != NULL)
{
EGZData * pEgzData = m_pEgzCathe->pdata;
size_t memsize = pEgzData->getMemSize();
if(NDN_MAX_PACKET_SIZE < packetsize + memsize + DATA_EMPTY_ITEM_SIZE)
{
break;
}
packetsize += memsize + DATA_EMPTY_ITEM_SIZE;
content = content + pEgzData->toItemString();
pTmpDataNode = m_pEgzCathe;
m_pEgzCathe = m_pEgzCathe->next;
pTmpDataNode->next = NULL;
if(NULL == m_pEgzSending)
{
m_pEgzSending = m_pEgzSendingTail = pTmpDataNode;
}
else
{
m_pEgzSendingTail->next = pTmpDataNode;
m_pEgzSendingTail = m_pEgzSendingTail->next;
}
}
}
content += "</BrData>";
// _LOG_INFO(content);
//begin encrypt the content by mali 20170606 add
/* Encrypt the plaintext */
//128bits key.
unsigned char key[KEY_BYTE_NUMBERS];
//Init vector.
unsigned char iv[KEY_BYTE_NUMBERS];
/* A 128 bit IV */
memcpy(key, KEY, KEY_BYTE_NUMBERS);
memcpy(iv, INITIAL_VECTOR, KEY_BYTE_NUMBERS);
int ciphertext_len;
int plaintext_len;
unsigned char *plaintextbuf = (unsigned char *)content.c_str();
unsigned char *ciphertextbuf=NULL;
if (Config::Instance()->m_sCipherSwitch == 1)
{
plaintext_len = strlen((const char*)plaintextbuf);
ciphertextbuf=(unsigned char *)malloc(MAX_TEXT_SIZE*sizeof(char));
if(NULL==ciphertextbuf)
{
BN_LOG_ERROR("ciphertextbuf malloc failed");
return;
}
try{
ciphertext_len = encrypt(plaintextbuf, strlen((const char *)plaintextbuf), key, iv,
ciphertextbuf);
}
catch (std::runtime_error& e)
{
BN_LOG_ERROR("producer catch nfd error:%s", e.what());
}
catch(...)
{
BN_LOG_ERROR("producer process events catch unknow error.");
}
}
//end encrypt the content by mali 20170606 add
// Create Data packet
shared_ptr<Data> data = make_shared<Data>();
data->setName(dataName);
data->setFreshnessPeriod(time::seconds(0));
//begin encrypt the content by mali 20170606 modify
if (Config::Instance()->m_sCipherSwitch == 1)
{
data->setContent(reinterpret_cast<const uint8_t*>(ciphertextbuf), ciphertext_len);
free(ciphertextbuf);
}
else
{
data->setContent(reinterpret_cast<const uint8_t*>(content.c_str()), content.size());
}
//end encrypt the content by mali 20170606 modify
// Sign Data packet with default identity
m_egzkeyChain.sign(*data);
// Return Data packet to the requester
// std::cout << ">> D: " << *data << std::endl;
if(m_pegzface != nullptr)
{
m_pegzface->put(*data);
}
}
void ProducerEgz::onEgzRegisterFailed(const Name& profix, const std::string& reason)
{
BN_LOG_ERROR("onEgzRegisterFailed");
if(m_pegzface != nullptr)
{
m_pegzface->shutdown();
}
}
|
#include "PwmRelay.h"
#include <iostream>
#include <sstream>
#include <Arduino.h>
using namespace Codingfield::Brew::Actuators;
PwmRelay::PwmRelay(Relays::Relay* relay, Relays::States idleState, Relays::States activateState) : actualRelay{relay},
idleState{idleState},
activateState{activateState} {
}
void PwmRelay::Update() {
if(!activated) return;
Relays::States targetState;
Relays::States currentState = actualRelay->State();
if(value < period) {
if(currentState == activateState || value == 0) {
consign = newConsign;
}
value++;
}
else {
value = 0;
consign = newConsign;
}
if(value < consign)
targetState = activateState;
else {
targetState = idleState;
}
if(currentState == activateState) {
activatedTime++;
totalActivatedTime++;
if(targetState == idleState && activatedTime >= minActivatedTime) {
actualRelay->State(idleState);
activatedTime = 0;
}
}
if(currentState == idleState) {
idleTime++;
if(targetState == activateState && idleTime >= minIdleTime) {
actualRelay->State(activateState);
idleTime = 0;
}
}
}
void PwmRelay::Reset() {
value = 0;
activatedTime = 0;
actualRelay->State(idleState);
idleTime = minActivatedTime+1;
}
void PwmRelay::Activate() {
activated = true;
Reset();
Update();
}
void PwmRelay::Deactivate() {
activated = false;
actualRelay->State(idleState);
}
void PwmRelay::Period(uint32_t p) {
period = p;
}
uint32_t PwmRelay::Period() const {
return period;
}
void PwmRelay::Consign(uint32_t c) {
newConsign = c;
}
uint32_t PwmRelay::Consign() const {
return consign;
}
void PwmRelay::MinimumActivatedTime(uint32_t m) {
minActivatedTime = m;
}
uint32_t PwmRelay::MinimumActivatedTime() const {
return minActivatedTime;
}
void PwmRelay::MinimumIdleTime(uint32_t m) {
minIdleTime = m;
}
uint32_t PwmRelay::MinimumIdleTime() const {
return minIdleTime;
}
bool PwmRelay::IsActivated() const {
return activated;
}
uint32_t PwmRelay::TotalActivatedTime() const {
return totalActivatedTime;
}
|
#ifndef BMI_H
#define BMI_H
#include<string>
using namespace std;
class BMI{
public:
void setmass(double num);
void sethigh(double num);
double getmass();
double gethigh();
double bmivalue();
string category(double bmi);
private:
double mass;
double high;
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
struct tree{
int l,r,mi;
};
struct que{
int l,r;
};
tree tr[500000];
que q[200000];
int a[200000],ans[200000],m,n;
void readit(){
scanf("%d%d",&m,&n);
for (int i=1;i<=m;i++)
scanf("%d",a+i);
for (int i=1;i<=n;i++)
scanf("%d%d",&q[i].l,&q[i].r);
}
void writeit(){
for (int i=1;i<n;i++)
printf("%d ",ans[i]);
printf("%d\n",ans[n]);
}
void build(int k,int s,int t){
tr[k].l=s;
tr[k].r=t;
if (s==t){
tr[k].mi=a[s];
return;
}
int mid=(s+t)>>1;
build(k<<1,s,mid);
build(k<<1|1,mid+1,t);
tr[k].mi=min(tr[k<<1].mi,tr[k<<1|1].mi);
}
int query(int k,int s,int t){
int l=tr[k].l,r=tr[k].r;
if (s==l&&t==r) return tr[k].mi;
int mid=(l+r)>>1;
if (t<=mid) return query(k<<1,s,t);
if (s>mid) return query(k<<1|1,s,t);
return min(query(k<<1,s,mid),query(k<<1|1,mid+1,t));
}
void work(){
build(1,1,m);
for (int i=1;i<=n;i++)
ans[i]=query(1,q[i].l,q[i].r);
}
int main(){
readit();
work();
writeit();
return 0;
}
|
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define FOR(i,n) for(ll i=0;i<n;i++)
#define FOR1(i,n) for(ll i=1;i<n;i++)
#define FORn1(i,n) for(ll i=1;i<=n;i++)
#define FORmap(i,mp) for(auto i=mp.begin();i!=mp.end();i++)
#define vll vector<ll>
#define vs vector<string>
#define pb(x) push_back(x)
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define mod 1000000007
using namespace std;
int main() {
// your code goes here
fast;
ll t;
cin>>t;
while(t--)
{
ll n,m,q;
cin>>n>>m>>q;
ll r[n]={0},c[m]={0};
FOR(i,q)
{
ll x,y;
cin>>x>>y;
r[x-1]++;
c[y-1]++;
}
ll reven=0,rodd=0,ceven=0,codd=0;
FOR(i,n)
{
if(!(r[i]&1))
reven++;
else
rodd++;
}
FOR(i,m)
{
if(c[i]&1)
codd++;
else
ceven++;
}
ll res=(rodd*ceven)+(reven*codd);
cout<<res<<endl;
}
return 0;
}
|
// monomer.h
#ifndef MONOMER_H
#define MONOMER_H
#include <memory>
#include <vector>
#include "BlobCrystallinOligomer/ifile.h"
#include "BlobCrystallinOligomer/particle.h"
#include "BlobCrystallinOligomer/shared_types.h"
#include "BlobCrystallinOligomer/space.h"
namespace monomer {
using ifile::MonomerData;
using ifile::ParticleData;
using particle::Particle;
using shared_types::CoorSet;
using shared_types::distT;
using shared_types::rotMatT;
using shared_types::vecT;
using space::CuboidPBC;
using std::vector;
using std::reference_wrapper;
using std::unique_ptr;
typedef vector<reference_wrapper<Particle>> particleArrayT;
// Consider making multiple classes for different versions of the alphaB
// monomer model, or in the distant future, alphaA monomers
/** alphB cyrstallin coarse grained monomer
*
* Contains the particles that make it up and an interface for manipulating
* the configuration.
*/
class Monomer {
public:
Monomer(MonomerData m_data, CuboidPBC& pbc_space);
/** Unique index */
int get_index();
/** Conformer (two NTD configs) */
int get_conformer(CoorSet coorset);
/** Get specified particle */
Particle& get_particle(int particle_i);
/** Get all particles */
particleArrayT get_particles();
int get_num_particles();
/** Get geometric center of all particles */
vecT get_center(CoorSet coorset);
/** Get maximum length from monomer center to particle center */
distT get_radius();
/** Translate monomer by given vector */
void translate(vecT disv);
/** Rotate monomer by given ? around given origin */
void rotate(vecT rot_c, rotMatT rot_mat);
/** Unwrap monomer relative to reference position */
void unwrap(vecT ref_pos);
/** Flip conformation */
void flip_conformation();
/** Make trial configuration current configuration */
void trial_to_current();
/** Reset trial to current */
void current_to_trial();
private:
int m_index; // Unique monomer index
int m_trial_conformer;
int m_conformer;
CuboidPBC& m_space;
vector<unique_ptr<Particle>> m_particles;
particleArrayT m_particle_refs;
int m_num_particles;
distT m_r;
void create_particles(vector<ParticleData> p_datas,
CuboidPBC& pbc_space);
void calc_monomer_radius();
};
}
#endif // MONOMER_H
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Player/MMOCharacter.h"
#include "MMOMob.generated.h"
UCLASS()
class MMOPROJECT_API AMMOMob : public AMMOCharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
AMMOMob(const FObjectInitializer& ObjectInitializer);
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
virtual void OnTargeted_Implementation(APlayerController* EventInstigator, AActor* TargetedBy) override;
virtual void OnStoppedTargeting_Implementation(APlayerController* EventInstigator, AActor* TargetedBy) override;
virtual float TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) override;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "AI")
float AggroRadius = 500.0f;
UPROPERTY(BlueprintReadWrite, Category = "AI")
bool bAggroReset = false;
UPROPERTY(Replicated, BlueprintReadWrite, Transient, Category = "Status")
bool bIsEvading = false;
};
|
#ifndef FIT_MANAGER_H
#define FIT_MANAGER_H
#include "TH1.h"
class FitManager
{
public:
FitManager();
~FitManager();
std::vector<TH1D *> GenerateProjections(TList *histList, float low_proj, float high_proj, float low_fit, float high_fit);
std::vector<TH1D *> CloneProjections(std::vector<TH1D *> histVec, float lowFit, float highFit);
TRWPeak *FitPeak(TH1D *inputHist, float peakPos, float lowFit, float highFit);
private:
};
#endif
|
// Created on: 2013-04-06
// Created by: Kirill Gavrilov
// Copyright (c) 2013-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef Xw_Window_HeaderFile
#define Xw_Window_HeaderFile
#include <Aspect_Window.hxx>
#include <Aspect_VKey.hxx>
class Aspect_DisplayConnection;
class Aspect_WindowInputListener;
typedef union _XEvent XEvent;
//! This class defines XLib window intended for creation of OpenGL context.
class Xw_Window : public Aspect_Window
{
DEFINE_STANDARD_RTTIEXT(Xw_Window, Aspect_Window)
public:
//! Convert X11 virtual key (KeySym) into Aspect_VKey.
Standard_EXPORT static Aspect_VKey VirtualKeyFromNative (unsigned long theKey);
public:
//! Creates a XLib window defined by his position and size in pixels.
//! Throws exception if window can not be created or Display do not support GLX extension.
Standard_EXPORT Xw_Window (const Handle(Aspect_DisplayConnection)& theXDisplay,
const Standard_CString theTitle,
const Standard_Integer thePxLeft,
const Standard_Integer thePxTop,
const Standard_Integer thePxWidth,
const Standard_Integer thePxHeight);
//! Creates a wrapper over existing Window handle
Standard_EXPORT Xw_Window (const Handle(Aspect_DisplayConnection)& theXDisplay,
const Aspect_Drawable theXWin,
const Aspect_FBConfig theFBConfig = NULL);
//! Destroys the Window and all resources attached to it
Standard_EXPORT ~Xw_Window();
//! Opens the window <me>
Standard_EXPORT virtual void Map() const Standard_OVERRIDE;
//! Closes the window <me>
Standard_EXPORT virtual void Unmap() const Standard_OVERRIDE;
//! Applies the resizing to the window <me>
Standard_EXPORT virtual Aspect_TypeOfResize DoResize() Standard_OVERRIDE;
//! Apply the mapping change to the window <me>
virtual Standard_Boolean DoMapping() const Standard_OVERRIDE
{
return Standard_True; // IsMapped()
}
//! Returns True if the window <me> is opened
Standard_EXPORT virtual Standard_Boolean IsMapped() const Standard_OVERRIDE;
//! Returns The Window RATIO equal to the physical WIDTH/HEIGHT dimensions
Standard_EXPORT virtual Standard_Real Ratio() const Standard_OVERRIDE;
//! Returns The Window POSITION in PIXEL
Standard_EXPORT virtual void Position (Standard_Integer& X1,
Standard_Integer& Y1,
Standard_Integer& X2,
Standard_Integer& Y2) const Standard_OVERRIDE;
//! Returns The Window SIZE in PIXEL
Standard_EXPORT virtual void Size (Standard_Integer& theWidth,
Standard_Integer& theHeight) const Standard_OVERRIDE;
//! @return native Window handle
Aspect_Drawable XWindow() const { return myXWindow; }
//! @return native Window handle
virtual Aspect_Drawable NativeHandle() const Standard_OVERRIDE
{
return myXWindow;
}
//! @return parent of native Window handle
virtual Aspect_Drawable NativeParentHandle() const Standard_OVERRIDE
{
return 0;
}
//! @return native Window FB config (GLXFBConfig on Xlib)
virtual Aspect_FBConfig NativeFBConfig() const Standard_OVERRIDE
{
return myFBConfig;
}
//! Sets window title.
Standard_EXPORT virtual void SetTitle (const TCollection_AsciiString& theTitle) Standard_OVERRIDE;
//! Invalidate entire window content through generation of Expose event.
//! This method does not aggregate multiple calls into single event - dedicated event will be sent on each call.
//! When NULL display connection is specified, the connection specified on window creation will be used.
//! Sending exposure messages from non-window thread would require dedicated display connection opened specifically
//! for this working thread to avoid race conditions, since Xlib display connection is not thread-safe by default.
Standard_EXPORT virtual void InvalidateContent (const Handle(Aspect_DisplayConnection)& theDisp) Standard_OVERRIDE;
//! Process a single window message.
//! @param theListener [in][out] listener to redirect message
//! @param theMsg [in][out] message to process
//! @return TRUE if message has been processed
Standard_EXPORT virtual bool ProcessMessage (Aspect_WindowInputListener& theListener,
XEvent& theMsg);
protected:
Aspect_Drawable myXWindow; //!< XLib window handle
Aspect_FBConfig myFBConfig; //!< GLXFBConfig
Standard_Integer myXLeft; //!< left position in pixels
Standard_Integer myYTop; //!< top position in pixels
Standard_Integer myXRight; //!< right position in pixels
Standard_Integer myYBottom; //!< bottom position in pixels
Standard_Boolean myIsOwnWin; //!< flag to indicate own window handle (to be deallocated on destruction)
};
DEFINE_STANDARD_HANDLE(Xw_Window, Aspect_Window)
#endif // _Xw_Window_H__
|
#pragma once
#include <bits/stdc++.h>
class AbstractDispatcher;
class Literal {
public:
Literal();
virtual void Accept(AbstractDispatcher& dispatcher) = 0;
virtual ~Literal();
};
class CharacterLiteral : public Literal {
public:
char val;
CharacterLiteral(char _val);
void Accept(AbstractDispatcher& dispatcher) override;
~CharacterLiteral();
};
class IntegerLiteral : public Literal {
public:
int val;
IntegerLiteral(int _val);
void Accept(AbstractDispatcher& dispatcher) override;
~IntegerLiteral();
};
class UnsignedLiteral : public Literal {
public:
unsigned val;
UnsignedLiteral(unsigned _val);
void Accept(AbstractDispatcher& dispatcher) override;
~UnsignedLiteral();
};
class BooleanLiteral : public Literal {
public:
bool val;
BooleanLiteral(bool _val);
void Accept(AbstractDispatcher& dispatcher) override;
~BooleanLiteral();
};
class StringLiteral : public Literal {
public:
std::string val;
StringLiteral(std::string _val);
void Accept(AbstractDispatcher& dispatcher) override;
~StringLiteral();
};
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "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 Qt Company Ltd 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
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef CODEEDITOR_H
#define CODEEDITOR_H
#include <QObject>
#include <QPlainTextEdit>
#include <QSyntaxHighlighter>
#include <QTextCharFormat>
#include <memory>
#include "../OrbitCore/RingBuffer.h"
#include "CodeReport.h"
QT_BEGIN_NAMESPACE
class QPaintEvent;
class QResizeEvent;
class QSize;
class QWidget;
class QTextDocument;
QT_END_NAMESPACE
class LineNumberArea;
//![codeeditordefinition]
class OrbitCodeEditor : public QPlainTextEdit {
Q_OBJECT
public:
explicit OrbitCodeEditor(QWidget* parent = nullptr);
void lineNumberAreaPaintEvent(QPaintEvent* event);
int lineNumberAreaWidth();
void HeatMapAreaPaintEvent(QPaintEvent* event);
int HeatMapAreaWidth();
bool loadCode(std::string a_Msg);
void loadFileMap();
void saveFileMap();
void gotoLine(int a_Line);
void SetText(std::string a_Text);
void SetReport(std::unique_ptr<CodeReport> report) { report_ = std::move(report); }
void HighlightWord(const std::string& a_Text, const QColor& a_Color,
QList<QTextEdit::ExtraSelection>& extraSelections);
static void setFileMappingWidget(QWidget* a_Widget) { GFileMapWidget = a_Widget; }
enum EditorType { CODE_VIEW, FILE_MAPPING };
void SetEditorType(EditorType a_Type);
void SetFindLineEdit(class QLineEdit* a_Find);
void SetSaveButton(class QPushButton* a_Button);
protected:
void resizeEvent(QResizeEvent* event) Q_DECL_OVERRIDE;
void keyPressEvent(QKeyEvent* e) override;
bool eventFilter(QObject* object, QEvent* event) override;
void Find(const QString& a_String, bool a_BackWards = false);
private slots:
void updateLineNumberAreaWidth(int newBlockCount);
void highlightCurrentLine();
void updateLineNumberArea(const QRect&, int);
void UpdateHeatMapArea(const QRect&, int);
void OnFindTextEntered(const QString&);
void OnSaveMapFile();
private:
QWidget* heatMapArea;
QWidget* lineNumberArea;
class Highlighter* highlighter;
class QLineEdit* m_FindLineEdit;
class QPushButton* m_SaveButton;
EditorType m_Type;
std::unique_ptr<CodeReport> report_;
static OrbitCodeEditor* GFileMapEditor;
static QWidget* GFileMapWidget;
static const int HISTORY_SIZE = 2;
RingBuffer<std::string, HISTORY_SIZE> m_SelectedText;
QColor m_SelectedColors[HISTORY_SIZE];
};
//![codeeditordefinition]
//![extraarea]
class LineNumberArea : public QWidget {
public:
explicit LineNumberArea(OrbitCodeEditor* editor) : QWidget(editor) { codeEditor = editor; }
[[nodiscard]] QSize sizeHint() const Q_DECL_OVERRIDE {
return QSize(codeEditor->lineNumberAreaWidth(), 0);
}
protected:
void paintEvent(QPaintEvent* event) Q_DECL_OVERRIDE {
codeEditor->lineNumberAreaPaintEvent(event);
}
private:
OrbitCodeEditor* codeEditor;
};
class HeatMapArea : public QWidget {
public:
explicit HeatMapArea(OrbitCodeEditor* editor) : QWidget(editor) { codeEditor = editor; }
[[nodiscard]] QSize sizeHint() const Q_DECL_OVERRIDE {
return QSize(codeEditor->lineNumberAreaWidth(), 0);
}
protected:
void paintEvent(QPaintEvent* event) Q_DECL_OVERRIDE { codeEditor->HeatMapAreaPaintEvent(event); }
private:
OrbitCodeEditor* codeEditor;
};
//! [0]
class Highlighter : public QSyntaxHighlighter {
Q_OBJECT
public:
explicit Highlighter(QTextDocument* parent = nullptr);
protected:
void highlightBlock(const QString& text) Q_DECL_OVERRIDE;
private:
struct HighlightingRule {
QRegExp pattern;
QTextCharFormat format;
};
QVector<HighlightingRule> highlightingRules;
QRegExp commentStartExpression;
QRegExp commentEndExpression;
QTextCharFormat keywordFormat;
QTextCharFormat classFormat;
QTextCharFormat singleLineCommentFormat;
QTextCharFormat multiLineCommentFormat;
QTextCharFormat quotationFormat;
QTextCharFormat functionFormat;
QTextCharFormat hexFormat;
};
#endif
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e17 // 4倍しても(4回足しても)long longを溢れない
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
int main() {
int h,w;
cin >> h >> w;
int a,b;
cin >> a >> b;
int ans = 0;
ans = w * a;
if (a < h) {
ans += abs(h-a) * b;
}
cout << h * w - ans << endl;
}
|
//算法:DP
//本题为简单的有向无环图,注意是单向图
//状态转移方程式:
//f[i]=max(f[i],f[j]+w[i]),其中j为可以到达i的点。
//即:i点能挖到的最大地雷数=能到达i点的点能挖到的最大地雷数+i点地雷
//注意用pre存路径
#include<cstdio>
using namespace std;
int n,ans,ans1;
int w[25],f[25],pre[25];
bool map[25][25];
void pr(int k)//递归输出路径
{
if(pre[k]==k)
{
printf("%d ",k);
return ;
}
pr(pre[k]);
printf("%d ",k);
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&w[i]);
pre[i]=i;//输入,顺便初始化
}
for(int i=1;i<=n;i++)//输入是否有路
for(int j=i+1;j<=n;j++)
{
int x;
scanf("%d",&x);
map[i][j]=x;
}
for(int i=1;i<=n;i++)//DP
{
f[i]=w[i];
for(int j=1;j<i;j++)
if(map[j][i] && f[j]+w[i]>f[i])//替换过程
{
f[i]=f[j]+w[i];
pre[i]=j;
}
if(ans<f[i])//记录答案
{
ans=f[i];
ans1=i;
}
}
pr(ans1);
printf("\n%d",ans);//输出
}
|
#include <imageprocessing/ConnectedComponent.h>
#include <util/rect.hpp>
#include <sopnet/slices/Slice.h>
#include "SetDifference.h"
double
SetDifference::operator()(const Slice& slice1, const Slice& slice2, bool normalized, bool align) {
const util::rect<double>& bb = slice1.getComponent()->getBoundingBox();
util::point<int> offset(static_cast<int>(bb.minX), static_cast<int>(bb.minY));
util::point<int> size(static_cast<int>(bb.width() + 2), static_cast<int>(bb.height() + 2));
std::vector<bool> pixels(size.x*size.y, false);
foreach (const util::point<unsigned int>& pixel, slice1.getComponent()->getPixels()) {
int x = (int)pixel.x - offset.x;
int y = (int)pixel.y - offset.y;
pixels[x + y*size.x] = true;
}
util::point<double> centerOffset(0, 0);
if (align)
centerOffset = slice1.getComponent()->getCenter() - slice2.getComponent()->getCenter();
unsigned int different = numDifferent(
slice1.getComponent()->getSize(),
pixels,
size,
centerOffset,
offset,
slice2);
if (normalized)
return static_cast<double>(different)/(slice1.getComponent()->getSize() + slice2.getComponent()->getSize());
else
return different;
}
double
SetDifference::operator()(const Slice& slice1a, const Slice& slice1b, const Slice& slice2, bool normalized, bool align) {
const util::rect<double>& bba = slice1a.getComponent()->getBoundingBox();
const util::rect<double>& bbb = slice1b.getComponent()->getBoundingBox();
util::rect<double> bb(std::min(bba.minX, bbb.minX), std::min(bba.minY, bbb.minY), std::max(bba.maxX, bbb.maxX), std::max(bba.maxY, bbb.maxY));
util::point<int> offset(static_cast<int>(bb.minX), static_cast<int>(bb.minY));
util::point<int> size(static_cast<int>(bb.width() + 2), static_cast<int>(bb.height() + 2));
std::vector<bool> pixels(size.x*size.y, false);
foreach (const util::point<unsigned int>& pixel, slice1a.getComponent()->getPixels()) {
int x = (int)pixel.x - offset.x;
int y = (int)pixel.y - offset.y;
pixels[x + y*size.x] = true;
}
foreach (const util::point<unsigned int>& pixel, slice1b.getComponent()->getPixels()) {
int x = (int)pixel.x - offset.x;
int y = (int)pixel.y - offset.y;
pixels[x + y*size.x] = true;
}
util::point<double> centerOffset(0, 0);
if (align)
centerOffset =
(slice1a.getComponent()->getCenter()*slice1a.getComponent()->getSize()
+
slice1b.getComponent()->getCenter()*slice1b.getComponent()->getSize())
/
(double)(slice1a.getComponent()->getSize() + slice1b.getComponent()->getSize())
-
slice2.getComponent()->getCenter();
unsigned int different = numDifferent(
slice1a.getComponent()->getSize() + slice1b.getComponent()->getSize(),
pixels,
size,
centerOffset,
offset,
slice2);
if (normalized)
return static_cast<double>(different)/(slice1a.getComponent()->getSize() + slice1b.getComponent()->getSize() + slice2.getComponent()->getSize());
else
return different;
}
unsigned int
SetDifference::numDifferent(
unsigned int size1,
const std::vector<bool>& pixels,
const util::point<int>& size,
const util::point<double>& centerOffset,
const util::point<double>& offset,
const Slice& slice2) {
// number of pixels in 2 but not 1
unsigned int in2not1 = 0;
// number of pixels that are both in 1 and 2
unsigned int shared = 0;
foreach (const util::point<unsigned int>& pixel, slice2.getComponent()->getPixels()) {
int x = (int)pixel.x - centerOffset.x - offset.x;
int y = (int)pixel.y - centerOffset.x - offset.y;
// not even close
if (x < 0 || x >= size.x || y < 0 || y >= size.y) {
in2not1++;
continue;
}
// within bounding box
if (pixels[x + y*size.x] == false)
// not in 1, but in 2
in2not1++;
else
// both in 1 and 2
shared++;
}
unsigned int in1not2 = size1 - shared;
assert(in2not1 + shared == slice2.getComponent()->getSize());
return in2not1 + in1not2;
}
|
//
// Created by Michael on 6/21/2015.
//
#include <math.h>
#include <stdio.h>
#include "orthotropic_lamina.h"
void OrthotropicLamina::calculate_elastic_constants(void) {
this->material.calculate_elastic_constants();
double to_radians = 0.01745329251994329576923690768489;
double c = cos(this->orientation*to_radians), s = sin(this->orientation*to_radians);
double c2 = c*c, c3 = c*c*c, c4 = c*c*c*c;
double s2 = s*s, s3 = s*s*s, s4 = s*s*s*s;
double C11 = this->material.C11, C12 = this->material.C12, C22 = this->material.C22, C66 = this->material.C66;
this->Q11 = C11*c4 + 2.*(C12 + 2.*C66)*s2*c2 + C22*s4;
this->Q22 = C11*s4 + 2.*(C12 + 2.*C66)*s2*c2 + C22*c4;
this->Q12 = (C11 + C22 - 4.*C66)*s2*c2 + C12*(s4 + c4);
this->Q66 = (C11 + C22 - 2.*C12 - 2.*C66)*s2*c2 + C66*(s4 + c4);
this->Q16 = (C11 - C12 - 2.*C66)*s*c3 + (C12 - C22 + 2.*C66)*s3*c;
this->Q26 = (C11 - C12 - 2.*C66)*s3*c + (C12 - C22 + 2.*C66)*s*c3;
}
|
#include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <numeric>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define ll long long
using namespace std;
int n, m, mod = 998244353;
vector<int> a, b;
struct Solution {
int solve() {
ll res = 1;
int x, y = n - 1;
for (int i = m - 1; i; --i) {
x = find_good(y, b[i]);
y = find_bad(x - 1, b[i]);
// cout << x << "," << y << endl;
if (x == -1) return 0;
res = (res * (x - y)) % mod;
}
if (*min_element(a.begin(), a.begin() + y + 1) != b[0]) return 0;
return res;
}
int find_good(int start, int v) { // first one <= start whose value == v
for (int i = start, low = INT_MAX; i > -1; --i) {
low = min(low, a[i]);
if (low == v) return i;
if (low < v) return -1;
}
return -1;
}
int find_bad(int start, int v) { // first one <= start whose value < v
for (int i = start, low = INT_MAX; i > -1; --i) {
low = min(low, a[i]);
if (low < v) return i;
}
return -1;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
a.resize(n);
b.resize(m);
for (int i = 0; i != n; ++i) cin >> a[i];
for (int i = 0; i != m; ++i) cin >> b[i];
Solution test;
cout << test.solve() << endl;
}
|
#include<iostream>
using namespace std;
class linklist
{
private:
struct node
{
int data;
node * link;
}*p;
public:
linklist();
void addatend(int item);
void addatbeg(int item);
void addafter(int loc, int item);
void display();
int count();
void del(int num);
void delat(int loc);
void reverse();
~linklist();
};
linklist::linklist()
{
p = NULL;
}
void linklist::addatend(int item)
{
node *temp, *r;
if(p==NULL)
{
temp = new node;
temp->data = item;
temp->link = NULL;
}
else
{
temp = p;
while(temp->link!=NULL)
{
temp = temp->link;
}
r = new node;
r->data = item;
r->link = NULL;
temp->link = r;
}
}
void linklist::addatbeg(int item)
{
node *temp;
temp = new node;
temp->data = item;
temp->link = p;
p = temp;
}
void linklist::addafter(int loc, int item)
{
node *temp, *r;
temp =p;
for(int i=0; i<loc; i++)
{
if(temp!=NULL)
temp = temp->link;
else
{
cout<<"The number of nodes are less than the location"<<loc<<" provided.";
return;
}
}
r = new node;
r->data = item;
r->link = temp->link;
temp->link = r;
}
void linklist::reverse()
{
node *q, *r, *s;
q = p;
r = NULL;
while(q!=NULL)
{
s = r;
r = q;
q = q->link;
r->link = s;
}
p = r;
}
void linklist::display()
{
node *temp;
temp = p;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp->link;
}
}
int linklist::count()
{
int counter=0;
node *temp;
while(temp!=NULL)
{
temp = temp->link;
counter++;
}
return counter;
}
void linklist::del(int num)
{
node *temp, *old;
temp=p;
while(temp!=NULL)
{
if(temp->data==num)
{
if(temp==p)
p = temp->link;
else
old->link = temp->link;
delete temp;
return;
}
else
{
old = temp;
temp = temp->link;
}
}
}
void linklist::delat(int loc)
{
node *temp, *old;
temp = p;
int counter=1;
while(temp!=NULL)
{
if(counter<loc)
{
counter++;
old = temp;
temp = temp->link;
}
else
{
if(temp == p)
p = temp->link;
else
old->link = temp->link;
delete temp;
return;
}
}
}
linklist::~linklist()
{
node *q;
while(p!=NULL)
{
q = p->link;
delete p;
p = q;
}
}
int main()
{
linklist l;
for(int i = 0; i<20; i++)
{
l.addatbeg(i+1);
}
l.reverse();
l.display();
cout<<endl;
for(int i = 1; i<=10; i=i++)
{
l.delat(i+1);
}
cout<<endl;
l.display();
}
|
//
// Created by xpl on 2021/6/24.
//
#include "AudioChannel.h"
#include "Log.h"
extern "C" {
#include <libavutil/time.h>
}
AudioChannel::AudioChannel(int channelId, JavaCallHelper *helper, AVCodecContext *avCodecContext,
const AVRational &base) : BaseChannel(channelId, helper, avCodecContext,
base) {
LOGI("AudioChannel::AudioChannel p = %p,_p=%p,thread_count = %d", &(this->avCodecContext),
&avCodecContext,
avCodecContext->thread_count);
out_channels = av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO); //2
// 采样位
out_sampleSize = av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);
// 采样率
out_sampleRate = 44100;
bufferCount = out_sampleRate * out_sampleSize * out_channels;
// 计算转换后数据的最大字节数
buffer = static_cast<uint8_t *>(malloc(bufferCount));
pthread_mutex_init(&delay_mutex, 0);
}
AudioChannel::~AudioChannel() {
free(buffer);
buffer = 0;
pthread_mutex_destroy(&delay_mutex);
LOGI("~AudioChannel");
}
void *audio_Decode_t(void *args) {
AudioChannel *audioChannel = static_cast<AudioChannel *>(args);
audioChannel->realDecode();
return 0;
}
void *audio_Play_t(void *args) {
AudioChannel *audioChannel = static_cast<AudioChannel *>(args);
audioChannel->realPlay();
return 0;
}
void AudioChannel::play() {
// 转换器
swrContext = swr_alloc_set_opts(0,
/*双声道*/
AV_CH_LAYOUT_STEREO,
/*采样位*/
AV_SAMPLE_FMT_S16,
/*采样率*/
44100,
avCodecContext->channel_layout,
avCodecContext->sample_fmt,
avCodecContext->sample_rate, 0, 0
);
swr_init(swrContext);
isPlaying = 1;
setEnable(1);
// 解码
pthread_create(&audioDecodeTask, 0, audio_Decode_t, this);
// 播放
pthread_create(&audioPlayTask, 0, audio_Play_t, this);
}
void AudioChannel::stop() {
isPlaying = 0;
helper = 0;
setEnable(0);
pthread_join(audioDecodeTask, 0);
pthread_join(audioPlayTask, 0);
releaseOpenSL();
if (swrContext) {
swr_free(&swrContext);
swrContext = 0;
}
}
void AudioChannel::decode() {
LOGI("AudioChannel::decode p = %p,thread_count = %d", &avCodecContext,
avCodecContext->thread_count);
AVPacket *avPacket = 0;
int ret = 0;
while (isPlaying) {
// av_usleep(delay);
ret = pkt_queue.deQueue(avPacket);
if (!isPlaying) {
break;
}
if (!ret) {
releaseAvPacket(avPacket);
continue;
}
ret = avcodec_send_packet(avCodecContext, avPacket);
if (ret < 0) {
break;
}
AVFrame *avFrame = av_frame_alloc();
ret = avcodec_receive_frame(avCodecContext, avFrame);
if (ret == AVERROR(EAGAIN)) {
releaseAvFrame(avFrame);
continue;
} else if (ret < 0) {
releaseAvFrame(avFrame);
break;
}
// while (frame_queue.size() > 100 && isPlaying) {
// av_usleep(1000 * 20);
// // faster
// }
frame_queue.enQueue(avFrame);
}
releaseAvPacket(avPacket);
}
void AudioChannel::realDecode() {
decode();
}
/**
* 播放回调
*/
void bqPlayerCallback(SLAndroidSimpleBufferQueueItf caller,
void *pContext) {
AudioChannel *audioChannel = static_cast<AudioChannel *>(pContext);
//pthread_mutex_lock(&(audioChannel->delay_mutex));
int dataSize = audioChannel->getData();
if (dataSize > 0) {
(*caller)->Enqueue(caller, audioChannel->buffer, dataSize);
}
//pthread_mutex_lock(&(audioChannel->delay_mutex));
}
int AudioChannel::getData() {
int dataSize = 0;
AVFrame *avFrame = 0;
while (isPlaying) {
av_usleep(this->delay);
int ret = frame_queue.deQueue(avFrame);
if (!isPlaying) {
releaseAvFrame(avFrame);
//this->delay = 0;
break;
}
if (!ret) {
releaseAvFrame(avFrame);
//this->delay = 0;
continue;
}
// 转换
int nb = swr_convert(swrContext, /*out*/&buffer, bufferCount,
/*in*/(const uint8_t **) (avFrame->data),/*样本数*/avFrame->nb_samples);
dataSize = nb * out_channels * out_sampleSize;
// 音频的时钟
clock = avFrame->pts * av_q2d(time_base);
LOGI("AudioChannel::getData %d clock=%lf", nb, clock);
//this->delay = 0;
break;
}
releaseAvFrame(avFrame);
return dataSize;
}
void AudioChannel::realPlay() {
LOGI("AudioChannel::realPlay");
/**
* 创建引擎
*/
// 1.创建引擎对象
// SLObjectItf slObjectItf = NULL;
SLresult result;
result = slCreateEngine(&slObjectItf, 0, NULL, 0, NULL, NULL);
if (SL_RESULT_SUCCESS != result) {
return;
}
// 2. 初始化
result = (*slObjectItf)->Realize(slObjectItf,/*同步*/SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != result) {
return;
}
// 3. 获取引擎接口
//SLEngineItf engineItf = NULL;
result = (*slObjectItf)->GetInterface(slObjectItf, SL_IID_ENGINE, &engineItf);
if (SL_RESULT_SUCCESS != result) {
return;
}
/**
* 创建混音器
*/
// 1.通过引擎接口创建混音器
// SLObjectItf outputMixObject = NULL;
result = (*engineItf)->CreateOutputMix(engineItf, &outputMixObject, 0, 0, 0);
if (SL_RESULT_SUCCESS != result) {
return;
}
// 2.初始化混音器
result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != result) {
return;
}
/**
* 创建播放器
*/
//数据源 (数据获取器+格式) avFrame
// PCM
// 声道 单声道/双声道
// 采样率 44k
// 采样位 16位 32位
// 重采样 pcm格式
//创建buffer缓冲类型的队列作为数据定位器(获取播放数据) 2个缓冲区
SLDataLocator_AndroidSimpleBufferQueue android_queue = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,
2};
//pcm数据格式: pcm、声道数、采样率、采样位、容器大小、通道掩码(双声道)、字节序(小端)
SLDataFormat_PCM pcm = {SL_DATAFORMAT_PCM, 2, SL_SAMPLINGRATE_44_1, SL_PCMSAMPLEFORMAT_FIXED_16,
SL_PCMSAMPLEFORMAT_FIXED_16,
SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT,
SL_BYTEORDER_LITTLEENDIAN};
SLDataSource slDataSource = {&android_queue, &pcm};
// 设置混音器,真正播放的
SLDataLocator_OutputMix outputMix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject};
SLDataSink audioSnk = {&outputMix, NULL};
// 需要的接口
const SLInterfaceID ids[1] = {SL_IID_BUFFERQUEUE}; // 队列操作接口
const SLboolean req[1] = {SL_BOOLEAN_TRUE}; // 是否必须
// SLObjectItf bqPlayerObject = NULL;
// 创建播放器,对混音器的包装,比如开始停止等
(*engineItf)->CreateAudioPlayer(engineItf, &bqPlayerObject, &slDataSource, &audioSnk, 1, ids,
req);
//初始化播放器
(*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE);
//获得播放数据队列操作接口
// SLAndroidSimpleBufferQueueItf bqPlayerBufferQueue = NULL;
(*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue);
//设置回调(启动播放器后执行回调来获取数据并播放)
(*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, this);
//获取播放状态接口
//SLPlayItf bqPlayerInterface = NULL;
(*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerInterface);
// 设置播放状态
(*bqPlayerInterface)->SetPlayState(bqPlayerInterface, SL_PLAYSTATE_PLAYING);
// 手动调用一次,才能播放
bqPlayerCallback(bqPlayerBufferQueue, this);
}
void AudioChannel::releaseOpenSL() {
LOGE("停止播放");
//设置停止状态
if (bqPlayerInterface) {
(*bqPlayerInterface)->SetPlayState(bqPlayerInterface, SL_PLAYSTATE_STOPPED);
bqPlayerInterface = 0;
}
//销毁播放器
if (bqPlayerObject) {
(*bqPlayerObject)->Destroy(bqPlayerObject);
bqPlayerObject = 0;
bqPlayerBufferQueue = 0;
}
//销毁混音器
if (outputMixObject) {
(*outputMixObject)->Destroy(outputMixObject);
outputMixObject = 0;
}
//销毁引擎
if (slObjectItf) {
(*slObjectItf)->Destroy(slObjectItf);
slObjectItf = 0;
engineItf = 0;
}
}
void AudioChannel::updateDelay(double delay) {
pthread_mutex_lock(&delay_mutex);
this->delay = delay;
pthread_mutex_unlock(&delay_mutex);
}
|
#include <string>
#include "caffe/data_transformer.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc.hpp>
#include "caffe/blob.hpp"
namespace caffe {
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const int batch_item_id,
const Datum& datum,
const vector<Dtype>& mean,
const vector<Dtype>& scale,
Dtype* transformed_data) {
const string& data = datum.data();
const int channels = datum.channels();
const int height = datum.height();
const int width = datum.width();
const int size = datum.channels() * datum.height() * datum.width();
const int size_one_channel = datum.height() * datum.width();
const int crop_size = param_.crop_size();
const bool mirror = param_.mirror();
const bool rotate = param_.rotate();
CHECK_EQ(mean.size(), scale.size());
Blob<Dtype> buffer;
buffer.Reshape(1, channels, height, width);
Dtype* buffer_data = buffer.mutable_cpu_data();
if (mirror && crop_size == 0) {
LOG(FATAL) << "Current implementation requires mirror and crop_size to be "
<< "set at the same time.";
}
if (rotate && phase_ == Caffe::TRAIN) {
cv::Mat src, dst;
src = cv::Mat::zeros(datum.height(), datum.width(), CV_8UC1);
cv::Point2f pt(src.cols/2., src.rows/2.);
int angle = Rand() % 360;
cv::Mat r = cv::getRotationMatrix2D(pt, angle, 1.0);
for (int c = 0; c != channels; ++c) {
for (int data_index = 0; data_index != datum.height() * datum.width() ; ++data_index ) {
Dtype datum_element =
static_cast<Dtype>(static_cast<uint8_t>(data[data_index + c * height * width]));
src.data[data_index] = datum_element;
}
cv::warpAffine(src, dst, r, cv::Size(src.cols, src.rows));
for (int data_index = 0; data_index != datum.height() * datum.width() ; ++data_index ) {
buffer_data[data_index + c * height * width] = dst.data[data_index];
}
//cv::imwrite("before.png", src);
//cv::imwrite("after.png", dst);
//cv::Mat out = cv::Mat::zeros(height, width, CV_8UC1);
//for (int data_index = 0; data_index != size_one_channel; ++data_index) {
// out.at<unsigned char>(data_index / width, data_index % width) = buffer_data[data_index + c * height * width];
//}
//cv::imwrite("out.tif",out);
}
} else {
for (int data_index = 0; data_index != size ; ++data_index ) {
unsigned char datum_element =
static_cast<uint8_t>(data[data_index]);
buffer_data[data_index] = datum_element;
if (datum_element < 0 || datum_element > 255) {
LOG(FATAL) << "asdasd";
}
}
}
if (crop_size) {
CHECK(data.size()) << "Image cropping only support uint8 data";
int h_off, w_off;
// We only do random crop when we do training.
if (phase_ == Caffe::TRAIN) {
h_off = Rand() % (height - crop_size);
w_off = Rand() % (width - crop_size);
} else {
h_off = (height - crop_size) / 2;
w_off = (width - crop_size) / 2;
}
if (mirror && Rand() % 2) {
// Copy mirrored version
for (int c = 0; c < channels; ++c) {
for (int h = 0; h < crop_size; ++h) {
for (int w = 0; w < crop_size; ++w) {
int data_index = (c * height + h + h_off) * width + w + w_off;
int top_index = ((batch_item_id * channels + c) * crop_size + h)
* crop_size + (crop_size - 1 - w);
Dtype datum_element = buffer_data[data_index];
transformed_data[top_index] =
(datum_element - mean[c]) * scale[c];
}
}
}
} else {
// Normal copy
for (int c = 0; c < channels; ++c) {
for (int h = 0; h < crop_size; ++h) {
for (int w = 0; w < crop_size; ++w) {
int top_index = ((batch_item_id * channels + c) * crop_size + h)
* crop_size + w;
int data_index = (c * height + h + h_off) * width + w + w_off;
Dtype datum_element =
buffer_data[data_index];
transformed_data[top_index] =
(datum_element - mean[c]) * scale[c];
}
}
}
}
} else {
// we will prefer to use data() first, and then try float_data()
if (data.size()) {
for (int c = 0; c < channels; ++c) {
int offset = c * size_one_channel + batch_item_id * size;
for (int j = 0; j <width * height ; ++j) {
Dtype datum_element =
buffer_data[c * size_one_channel + j ];
transformed_data[j + offset] =
(datum_element - mean[c]) * scale[c];
}
}
} else {
LOG(ERROR) << "This is not tested. The input data type is not correct";
for (int c = 0; c < channels; ++c) {
int offset = c * size_one_channel + batch_item_id * size;
for (int j = 0; j < width * height; ++j) {
transformed_data[j + offset] =
(datum.float_data(j + c * size_one_channel) - mean[c]) * scale[c];
}
}
}
}
}
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const int batch_item_id,
const Datum& datum,
const Dtype* mean,
Dtype* transformed_data) {
const string& data = datum.data();
const int channels = datum.channels();
const int height = datum.height();
const int width = datum.width();
const int size = datum.channels() * datum.height() * datum.width();
const int crop_size = param_.crop_size();
const bool mirror = param_.mirror();
const Dtype scale = param_.scale();
if (mirror && crop_size == 0) {
LOG(FATAL) << "Current implementation requires mirror and crop_size to be "
<< "set at the same time.";
}
if (crop_size) {
CHECK(data.size()) << "Image cropping only support uint8 data";
int h_off, w_off;
// We only do random crop when we do training.
if (phase_ == Caffe::TRAIN) {
h_off = Rand() % (height - crop_size);
w_off = Rand() % (width - crop_size);
} else {
h_off = (height - crop_size) / 2;
w_off = (width - crop_size) / 2;
}
if (mirror && Rand() % 2) {
// Copy mirrored version
for (int c = 0; c < channels; ++c) {
for (int h = 0; h < crop_size; ++h) {
for (int w = 0; w < crop_size; ++w) {
int data_index = (c * height + h + h_off) * width + w + w_off;
int top_index = ((batch_item_id * channels + c) * crop_size + h)
* crop_size + (crop_size - 1 - w);
Dtype datum_element =
static_cast<Dtype>(static_cast<uint8_t>(data[data_index]));
transformed_data[top_index] =
(datum_element - mean[data_index]) * scale;
}
}
}
} else {
// Normal copy
for (int c = 0; c < channels; ++c) {
for (int h = 0; h < crop_size; ++h) {
for (int w = 0; w < crop_size; ++w) {
int top_index = ((batch_item_id * channels + c) * crop_size + h)
* crop_size + w;
int data_index = (c * height + h + h_off) * width + w + w_off;
Dtype datum_element =
static_cast<Dtype>(static_cast<uint8_t>(data[data_index]));
transformed_data[top_index] =
(datum_element - mean[data_index]) * scale;
}
}
}
}
} else {
// we will prefer to use data() first, and then try float_data()
if (data.size()) {
for (int j = 0; j < size; ++j) {
Dtype datum_element =
static_cast<Dtype>(static_cast<uint8_t>(data[j]));
transformed_data[j + batch_item_id * size] =
(datum_element - mean[j]) * scale;
}
} else {
for (int j = 0; j < size; ++j) {
transformed_data[j + batch_item_id * size] =
(datum.float_data(j) - mean[j]) * scale;
}
}
}
}
template <typename Dtype>
void DataTransformer<Dtype>::InitRand() {
const bool needs_rand = (phase_ == Caffe::TRAIN) &&
(param_.mirror() || param_.crop_size() || param_.rotate());
if (needs_rand) {
const unsigned int rng_seed = caffe_rng_rand();
rng_.reset(new Caffe::RNG(rng_seed));
} else {
rng_.reset();
}
}
template <typename Dtype>
unsigned int DataTransformer<Dtype>::Rand() {
CHECK(rng_);
caffe::rng_t* rng =
static_cast<caffe::rng_t*>(rng_->generator());
return (*rng)();
}
INSTANTIATE_CLASS(DataTransformer);
} // namespace caffe
|
//
// Text.h
// Odin.MacOSX
//
// Created by Daniel on 08/10/15.
// Copyright (c) 2015 DG. All rights reserved.
//
#ifndef __Odin_MacOSX__Text__
#define __Odin_MacOSX__Text__
#include "Drawable.h"
#include "Font.h"
#include "Vector4.h"
#include "RenderStates.h"
#include <string>
namespace odin
{
namespace render
{
class Text : Drawable
{
public:
enum Style
{
Regular = 0, // Regular characters, no style
Bold = 1 << 0, // Bold characters
Italic = 1 << 1, // Italic characters
Underlined = 1 << 2, // Underlined characters
StrikeThrough = 1 << 3 // Strike through characters
};
Text();
Text(const std::string& text, const resource::Font& font, UI32 characterSize = 25);
~Text();
virtual void draw(const RenderStates& states);
void draw();
const std::string& getString() const;
void setString(const std::string& text);
const resource::Font& getFont() const;
void setFont(const resource::Font& font);
UI32 getSize() const;
void setSize(UI32 characterSize);
Style getStyle() const;
void setStyle(Style style);
const math::vec4& getColor() const;
void setColor(const math::vec4& color);
private:
void updateGeometry();
void load();
std::string m_text;
const resource::Font* m_font;
RenderStates m_renderStates;
UI32 m_characterSize;
Style m_style;
math::vec4 m_color;
UI32 m_numVertices;
UI32 m_vao;
UI32 m_vbo;
bool m_needUpdate;
static bool s_loaded;
};
}
}
#endif /* defined(__Odin_MacOSX__Text__) */
|
#include "Data/Database.h"
using namespace m2::server;
Database::Database(const std::string& rootDir)
: Users(rootDir)
, Dialogs(rootDir + "Dialogs/")
{}
bool
Database::CreateUser(uuids::uuid Uid, const std::string &PublicKey)
{ return Users.CreateUser(Uid, PublicKey) ? true : false; }
bool
Database::CreateUser(uuids::uuid Uid, std::string &&PublicKey)
{ return Users.CreateUser(Uid, std::move(PublicKey)); }
bool
Database::IsClienExists(uuids::uuid Uid)
{ return Users[Uid]; }
std::string
Database::getUserPublicKey(uuids::uuid Uid)
{ return Users(Uid).PublicKey(); }
std::string
Database::getPublicServerKey()
{ return "-----BEGIN PUBLIC KEY-----"
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7hXrrlg3N9Uelmd8X3uT"
"YyrunZwnBqb/RJ0srNxPd+PMe5Dasw39W6TMDcS7WYgeFIsdlIAfPzWeONKvdCnG"
"INRIJClOHKQOPejAjfISKaCRrdiCBCQ9hvfqhd7yi9kbWTlkOYtddMceJjwWfEuO"
"IBkaF1F03bOGKNQgXhEbCFTo8ow+F/lhz7MZXq+pWEpArXwSWFpigVHkAN+5acEY"
"jX/4Pzg9jwrh3NJMffoeFTch3UGFxY5oQShSGeqFqP4uCb2DvZjNu/aBJxNQHSPz"
"tf5A7KJHy+3smoy+zGUgmQyScnK4eqjgEipdv0x2I+9zlsl8oPa3Jis5RoQQWxMr"
"pwIDAQAB"
"-----END PUBLIC KEY-----"; }
std::string Database::getPrivateServerKey()
{ return "-----BEGIN RSA PRIVATE KEY-----"
"MIIEowIBAAKCAQEA7hXrrlg3N9Uelmd8X3uTYyrunZwnBqb/RJ0srNxPd+PMe5Da"
"sw39W6TMDcS7WYgeFIsdlIAfPzWeONKvdCnGINRIJClOHKQOPejAjfISKaCRrdiC"
"BCQ9hvfqhd7yi9kbWTlkOYtddMceJjwWfEuOIBkaF1F03bOGKNQgXhEbCFTo8ow+"
"F/lhz7MZXq+pWEpArXwSWFpigVHkAN+5acEYjX/4Pzg9jwrh3NJMffoeFTch3UGF"
"xY5oQShSGeqFqP4uCb2DvZjNu/aBJxNQHSPztf5A7KJHy+3smoy+zGUgmQyScnK4"
"eqjgEipdv0x2I+9zlsl8oPa3Jis5RoQQWxMrpwIDAQABAoIBAHVlM6fs8ZVDLejl"
"sCr4qQ0d7zih9ZBPKdFwWsYFf93S4lIPc/cUL9hPYxpq5iJYftSMYBKINmAZlSHZ"
"qQ/zRTGM2uGRyGVQ84DNUpzrPs9t0EdTWZCnOftiJS7LZvdUHysYpHXHZVaelBww"
"RroVG0hyeC4FSUXELqPVLPyVHKo3GICz2FUHR/lj2aKWTSrEJnzEUF+Eg24iVotE"
"zSGLvLoIGuMer98EX5uhaV5AlfHOfwjZZn//R0eopneJJkil7JnbFNXdznoMIYsd"
"iVboFSPOPhae7cef++Di2oTnWL3GHefURoAufMvcm1KCYwscCQ3YP2V4+6XnyeEq"
"vcD3o/ECgYEA+0FjGE8ohhbtHMevM18+aqRfnAG4mVod5QClN2WhwfDlo80l6zyj"
"HCD0IX9NU8ERDc2OOU6XTWVrwYAWzjZO2hv3VFby8ar0PYD3+pEN1xe3wqfEJCTR"
"uHs4pGoAAir0/S0jXJZu8o60Y2bYXFWy0iDfJFqtA5QvOBjdaEe/rJkCgYEA8pTe"
"UujEtryJqQpxIzwYflLb22qxAR33xoUgJe2FngnZS3HEF3rAEPYYMl1uOoZvKQUv"
"Nk29pvm+6KUMMa+y198rIUS8j7kd/ptE0XO0/MvhH7qOnWjoikZ9OyDDG8Z0lxHI"
"pHYkWzcAlH/H3SSN9POirCOmWz2agIp79R6Sgj8CgYBc7Gvn267TGLuM/1UOnNUK"
"v8wUeJZ7MNcJkNmJyW6vuZZUpFS30W9Jwe5ITTqeFTNndXR6QVS37SCTKfpFPdSf"
"2eP5L0celelKrd4Ir4j82eq+dSmXbH6bygbC1+k05ApDcGQ5o/FYh+qzMKAoVhGS"
"oVGlslt2jWGBT8DjBlYfUQKBgDJybQ225HnQGZyy1DZsn/ddSeWGeYru7YE2XCon"
"DBuCltLOtOXhHCIq23tV3L+FB4bzUg8r+Z3I4D/HWxLWJA4qlfCUN9Z3u9of9h7M"
"vj24NHgBtvjbQUjIQfDS7mBPVB26kAxLmWHyvUckj67YlED1jcXYoBbnZ8MFiaO/"
"GN7HAoGBAKsMXh7Zw+gntestvbYbye8x9IC7UPjjHObQEzRlYapOtgoX5tavOUu7"
"xP/7f7OE6j9kqHpB/rsJCSb5GIqyXdPaTjAyZQuJavbiFwUEZ9z9pl0Iii63swPi"
"/BEVBHlcyCajRYqioVIIPz7yx4SyNoyiPe5BUcvBR0m6ZzuAtMsz"
"-----END RSA PRIVATE KEY-----"; }
|
/**************************************************************************************
* File Name : Object.cpp
* Project Name : Keyboard Warriors
* Primary Author : Doyeong Yi
* Secondary Author : Jookyung Lee
* Copyright Information :
* "All content 2019 DigiPen (USA) Corporation, all rights reserved."
**************************************************************************************/
#include <iostream>
#include "Object.h"
#include "GameManager.h"
#include "ObjectFactory.h"
#include "ComponentTest.h"
#include "ObjectMaterial.h"
#include "FileLoadAndSave.hpp"
#include "UnitStateComponent.hpp"
#include "DataReader.hpp"
Object::Object()
: objectID(0), position(0) {}
Object::Object(const Object& rhs) : transform(rhs.transform), material(rhs.material), animation(rhs.animation)
, min(rhs.min), max(rhs.max), speed(rhs.speed), objectName(rhs.objectName), position(rhs.position), size(rhs.size), componentList(rhs.componentList)
{
AddComponent<MaterialComponent>();
GetComponent<MaterialComponent>()->material.shader = material.shader;
GetComponent<MaterialComponent>()->material.vertices = material.vertices;
AddComponent<UnitState>();
GetComponent<UnitState>()->SetUnit(this);
GetComponent<UnitState>()->SetType(GetComponent<BaseUnitState>()->GetType());
GetComponent<UnitState>()->SetState(GetComponent<BaseUnitState>()->GetState());
GetComponent<UnitState>()->SetAttackRange(GetComponent<BaseUnitState>()->GetAttackRange());
GetComponent<UnitState>()->SetAttackState(GetComponent<BaseUnitState>()->GetAttackState());
GetComponent<UnitState>()->SetSpriteChangeState(GetComponent<BaseUnitState>()->GetSpriteChangeState());
GetComponent<UnitState>()->SetHealth(GetComponent<BaseUnitState>()->GetHealth());
GetComponent<UnitState>()->SetDamage(GetComponent<BaseUnitState>()->GetDamage());
GetComponent<UnitState>()->SetInvincibilityState(GetComponent<BaseUnitState>()->GetInvincibilityState());
GetComponent<UnitState>()->healthBar.material = GetComponent<BaseUnitState>()->healthBar.material;
GetComponent<UnitState>()->healthBar.mesh = GetComponent<BaseUnitState>()->healthBar.mesh;
GetComponent<UnitState>()->healthBar.transform = GetComponent<BaseUnitState>()->healthBar.transform;
GetComponent<UnitState>()->healthBar.Initialize(transform.GetTranslation(), GetComponent<UnitState>()->GetHealth());
if (GetName() != "lair" && GetName() != "tower")
{
if (GetComponent<UnitState>()->GetType() != UnitType::ProjectilesPlayer && GetComponent<UnitState>()->GetType() != UnitType::ProjectilesEnemy)
{
AddComponent<ObjectAttackComponent>();
GetComponent<ObjectAttackComponent>()->SetUnit(this);
GetComponent<ObjectAttackComponent>()->projectile = GetComponent<BaseObjectAttackComponent>()->projectile;
GetComponent<ObjectAttackComponent>()->delayTime = GetComponent<BaseObjectAttackComponent>()->delayTime;
GetComponent<ObjectAttackComponent>()->soundID = GetComponent<BaseObjectAttackComponent>()->soundID;
GetComponent<ObjectAttackComponent>()->startPosition.x = GetComponent<BaseObjectAttackComponent>()->startPosition.x;
GetComponent<ObjectAttackComponent>()->startPosition.y = GetComponent<BaseObjectAttackComponent>()->startPosition.y;
}
}
}
void Object::Initialize(const char* name) noexcept
{
DataReader::ReadData(name, this);
GetComponent<BaseUnitState>()->healthBar.Initialize(transform.GetTranslation(), GetComponent<BaseUnitState>()->GetHealth());
AddComponent<BaseObjectAttackComponent>();
}
void Object::Update(float dt) noexcept
{
if (GetComponent<UnitState>()->GetState() == State::WALK) {
const vec2<float> changedPosition = transform.GetTranslation() + speed * dt;
transform.SetTranslation(changedPosition);
position = changedPosition;
const float halfWidth = size.x / 2.f;
const float halfHeight = size.y / 2.f;
min = { position.x - halfWidth, position.y - halfHeight };
max = { position.x + halfWidth, position.y + halfHeight };
}
}
Object* Object::Clone() const
{
return new Object(*this);
}
void Object::ChangeUnitAnimation()
{
if (GetName() == "knight")
{
if (GetComponent<UnitState>()->GetState() == State::WALK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::knight_move);
animation.ChangeAnimation(8, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
else if (GetComponent<UnitState>()->GetState() == State::ATTACK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::knight_attack);
animation.ChangeAnimation(8, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
}
else if (GetName() == "archer")
{
if (GetComponent<UnitState>()->GetState() == State::WALK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::archer_move);
animation.ChangeAnimation(8, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
else if (GetComponent<UnitState>()->GetState() == State::ATTACK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::archer_attack);
animation.ChangeAnimation(8, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
}
else if (GetName() == "Magician")
{
if (GetComponent<UnitState>()->GetState() == State::WALK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::magician_move);
animation.ChangeAnimation(8, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
else if (GetComponent<UnitState>()->GetState() == State::ATTACK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::magician_attack);
animation.ChangeAnimation(5, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
}
else if (GetName() == "skeleton")
{
if (GetComponent<UnitState>()->GetState() == State::WALK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::skeleton_move);
animation.ChangeAnimation(4, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
else if (GetComponent<UnitState>()->GetState() == State::ATTACK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::skeleton_attack);
animation.ChangeAnimation(7, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
}
else if (GetName() == "lich")
{
if (GetComponent<UnitState>()->GetState() == State::WALK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::lich_move);
animation.ChangeAnimation(8, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
else if (GetComponent<UnitState>()->GetState() == State::ATTACK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::lich_attack);
animation.ChangeAnimation(1, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
}
else if (GetName() == "Golem")
{
if (GetComponent<UnitState>()->GetState() == State::WALK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::golem_move);
animation.ChangeAnimation(4, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
else if (GetComponent<UnitState>()->GetState() == State::ATTACK && GetComponent<UnitState>()->GetSpriteChangeState() == true)
{
GetComponent<MaterialComponent>()->material.texture.LoadTextureFrom(PATH::golem_attack);
animation.ChangeAnimation(18, 1);
GetComponent<UnitState>()->SetSpriteChangeState(false);
}
}
else
{
GetComponent<MaterialComponent>()->material.texture = material.texture;
}
}
bool Object::isCollideWith(Object& object) noexcept
{
return !(max.x < object.min.x || object.max.x < min.x || max.y < object.min.y || object.max.y < min.y);
}
bool Object::isObjectInAttackRange(Object& object) noexcept
{
return !(max.x + GetComponent<UnitState>()->GetAttackRange().x < object.min.x || object.max.x < min.x - GetComponent<UnitState>()->GetAttackRange().x || max.y + GetComponent<UnitState>()->GetAttackRange().y < object.min.y || object.max.y < min.y - GetComponent<UnitState>()->GetAttackRange().y);
}
bool Object::isCollideWithMouse(vec2<float>& mouse_position, int width, int height) noexcept
{
return !(max.x + (width / 2.0f) < mouse_position.x || mouse_position.x < min.x + (width / 2.0f) || max.y + (height / 2.0f) < mouse_position.y || mouse_position.y < min.y + (height / 2.0f));
}
|
#include "client.h"
#include "contracts.h"
#include <ctime>
#include <thread>
#include <chrono>
#include <iostream>
#include <memory>
// constructor
CClient::CClient()
: m_pClientSocket(new EClientSocket(this, &m_readerOSSignal))
{}
bool CClient::connect(std::string addr, int port)
{
printf("Connecting to %s:%d... ", addr.empty() ? "127.0.0.1" : addr.c_str(), port);
bool res = m_pClientSocket->eConnect(addr.c_str(), port); //, clientId, m_extraAuth)
if (res) {
printf("SUCCESS\nConnected to %s:%d\n", m_pClientSocket->host().c_str(), m_pClientSocket->port());
m_pReader = std::make_unique<EReader>(m_pClientSocket.get(), &m_readerOSSignal);
m_pReader->start();
}
else
printf("FAILURE\nCannot connect to %s:%d\n", m_pClientSocket->host().c_str(), m_pClientSocket->port());
return res;
}
void CClient::processMessages(void)
{
switch (m_state) {
case state::contractDetails:
printf("--> contractDetails:\n");
m_pClientSocket->reqContractDetails(101, CContracts::simpleFuture());
m_pClientSocket->reqContractDetails(102, CContracts::crudeOil());
m_state = state::idle;
break;
case state::continuoseFuture: { // Error. Id: 202, Code: 162, Msg: Historical Market Data Service error message:No market data permissions for NYMEX FUT
printf("--> continuoseFuture:\n");
m_pClientSocket->reqContractDetails(201, CContracts::continuoseFuture());
char queryTime[80];
std::time_t now = std::time(nullptr);
std::strftime(queryTime, 80, "%Y%m%d %H:%M:%S", std::localtime(&now));
m_pClientSocket->reqHistoricalData(202, CContracts::continuoseFuture(), queryTime, "1 M", "1 day", "TRADES", 1, 1, false, TagValueListSPtr());
std::this_thread::sleep_for(std::chrono::seconds(10));
m_pClientSocket->cancelHistoricalData(202);
m_state = state::idle;
break; }
case state::headTimespamp:
printf("--> headTimespamp:\n");
m_pClientSocket->reqHeadTimestamp(301, CContracts::crudeOil(), "TRADES", 1, 1);
std::this_thread::sleep_for(std::chrono::seconds(1));
m_pClientSocket->cancelHeadTimestamp(301);
m_state = state::idle;
break;
case state::historicalData: {
printf("--> historicalData:\n");
char queryTime[80];
std::time_t now = std::time(nullptr);
std::strftime(queryTime, 80, "%Y%m%d %H:%M:%S", std::localtime(&now));
m_pClientSocket->reqHistoricalData(401, CContracts::eurGbpFx(), queryTime, "1 M", "1 day", "MIDPOINT", 1, 1, false, TagValueListSPtr());
// Error.Id: 402, Code : 162, Msg : Historical Market Data Service error message : No market data permissions for HEX STK
m_pClientSocket->reqHistoricalData(402, CContracts::europeanStock(), queryTime, "10 D", "1 min", "TRADES", 1, 1, false, TagValueListSPtr());
std::this_thread::sleep_for(std::chrono::seconds(2));
m_pClientSocket->cancelHistoricalData(401);
// m_pClientSocket->cancelHistoricalData(402);
m_state = state::idle;
break; }
case state::delayedTickData:
printf("--> delayedTickData:\n");
m_pClientSocket->reqMarketDataType(4); // send delayed-frozen (4) market data type
m_pClientSocket->reqMktData(501, CContracts::gold(), "", false, false, TagValueListSPtr());
std::this_thread::sleep_for(std::chrono::seconds(10));
m_pClientSocket->cancelMktData(501);
m_state = state::idle;
break;
case state::idle: break;
case state::connect: break;
}
m_readerOSSignal.waitForSignal();
errno = 0;
m_pReader->processMsgs();
}
|
//=============================================================================
// DxUtil.h by Frank Luna (C) 2005 All Rights Reserved.
// Edited by Kenji Shimojima
//
// Contains various utility code for DirectX applications, such as, clean up
// and debugging code.
//=============================================================================
#ifndef _DXDUTIL_H
#define _DXDUTIL_H
// Enable extra D3D debugging in debug builds if using the debug DirectX runtime.
// This makes D3D objects work well in the debugger watch window, but slows down
// performance slightly.
#if defined(DEBUG) | defined(_DEBUG)
#ifndef D3D_DEBUG_INFO
#define D3D_DEBUG_INFO
#endif
#endif
#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9d.lib")
#pragma comment(lib, "dxerr.lib")
#pragma comment(lib, "dxguid.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "dxguid.lib")
#include <d3d9.h>
#include <d3dx9.h>
#include <dxerr.h>
#include <string>
#include <sstream>
//===============================================================
// Clean up
#define ReleaseCOM(x) { if(x){ x->Release();x = 0; } }
//===============================================================
// Debug
#if defined(DEBUG) | defined(_DEBUG)
#ifndef HR
#define HR(x) \
{ \
HRESULT hr = x; \
if( FAILED(hr) ) \
{ \
DXTrace(__FILE__, __LINE__, hr, #x, TRUE); \
} \
}
#endif
#else
#ifndef HR
#define HR(x) x;
#endif
#endif
#endif // D3DUTIL_H
|
// Test driver
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <cstring>
#include <cstdlib>
#include "unsorted.h"
#include "tools.hpp"
using namespace std;
void PrintList(ofstream& outFile, UnsortedType& list);
bool IsThere2(ItemType& item, bool& found, UnsortedType& list);
int main()
{
ifstream inFile; // file containing operations
ofstream outFile; // file containing output
string inFileName; // input file external name
string outFileName; // output file external name
string outputLabel;
string command; // operation to be executed
int number;
ItemType item;
UnsortedType list;
bool found;
int numCommands;
UnsortedType list1, list2;
banner();
// Prompt for file names, read file names, and prepare files
cout << "Enter name of input command file; press return." << endl;
cin >> inFileName;
inFile.open(inFileName.c_str());
cout << "Enter name of output file; press return." << endl;
cin >> outFileName;
outFile.open(outFileName.c_str(), ios::out | ios::app);
cout << "Enter name of test run; press return." << endl;
cin >> outputLabel;
outFile << "[" << outputLabel << "]" << endl << endl;
if (!inFile)
{
cout << "file not found" << endl;
exit(2);
}
inFile >> command;
numCommands = 0;
while (command != "Quit")
{
if (command == "PutItem")
{
inFile >> number;
item.Initialize(number);
list.PutItem(item);
item.Print(outFile);
outFile << " is in list" << endl;
}
else if (command == "DeleteItem")
{
inFile >> number;
item.Initialize(number);
list.DeleteItem(item);
item.Print(outFile);
outFile << " is deleted" << endl;
}
else if (command == "GetItem")
{
inFile >> number;
item.Initialize(number);
item = list.GetItem(item, found);
item.Print(outFile);
if (found)
outFile << " found in list." << endl;
else outFile << " not in list." << endl;
}
else if (command == "GetLength")
outFile << "Length is " << list.GetLength() << endl;
else if (command == "IsFull")
if (list.IsFull())
outFile << "List is full." << endl;
else outFile << "List is not full." << endl;
else if (command == "MakeEmpty")
list.MakeEmpty();
else if (command == "PrintList")
PrintList(outFile, list);
else if (command == "IsThere") // NewStuff
{
inFile >> number;
item.Initialize(number);
list.IsThere(item, found);
item.Print(outFile);
if (found)
outFile << " is there in the list." << endl;
else outFile << " is not there in the list." << endl;
}
else if (command == "IsThere2") // NewStuff
{
inFile >> number;
item.Initialize(number);
IsThere2(item, found, list);
item.Print(outFile);
if (found)
outFile << " is there in the list." << endl;
else outFile << " is not there in the list." << endl;
}
else if (command == "SplitLists") // NewStuff
{
inFile >> number;
item.Initialize(number);
list.SplitLists(list, item, list1, list2);
item.Print(outFile);
outFile << " - This is the value for the split" << endl;
PrintList(outFile, list1);
PrintList(outFile, list2);
}
else
cout << command << " is not a valid command." << endl;
numCommands++;
cout << " Command number " << numCommands << " completed."
<< endl;
inFile >> command;
};
cout << "Testing completed." << endl;
inFile.close();
outFile.close();
bye();
return 0;
}
void PrintList(ofstream& dataFile, UnsortedType& list)
// Pre: list has been initialized.
// dataFile is open for writing.
// Post: Each component in list has been written to dataFile.
// dataFile is still open.
{
int length;
ItemType item;
list.ResetList();
length = list.GetLength();
for (int counter = 1; counter <= length; counter++)
{
item = list.GetNextItem();
item.Print(dataFile);
}
dataFile << endl;
}
bool IsThere2(ItemType& item, bool& found, UnsortedType& list) // NewStuff
//Preconditions: List has been initialized.
// Key member of item is initialized.
//Postconditions: If there is an element someItem whose key matches itemís key, then found = true;
// otherwise found = false.
// List is unchanged.
{
found = false;
list.GetItem(item, found);
return found;
}
|
//
// Created by cirkul on 27.11.2020.
//
#include "Animal.h"
Animal *Animal::spawn(Playground &pg, int i, int j) { return nullptr; }
void Animal::move() {
std::vector<Playground::Cell *> cells;
for (int i = this->i - 1; i <= this->i + 1; ++i) {
for (int j = this->j - 1; j <= this->j + 1; ++j) {
if (i < 0 || j < 0 || i >= this->pg->rows || j >= this->pg->cols)
continue;
if (this->pg->pg[i][j].creatureCount == MAX_COUNT)
continue;
if (i == this->i && j == this->j)
continue;
cells.push_back(&this->pg->pg[i][j]);
}
}
if (!cells.empty()) {
int randCell = rand() % cells.size();
--this->home->creatureCount;
++cells[randCell]->creatureCount;
auto it = this->home->animals.begin();
while (*it != this) ++it;
this->home->animals.erase(it);
cells[randCell]->animals.push_back(this);
this->i = cells[randCell]->i;
this->j = cells[randCell]->j;
this->home = cells[randCell];
}
}
bool Animal::starving() const {
if (this->satietyInd < 0.7* this->maxSatisfaction)
return false;
else
return true;
}
bool Animal::escape() { return false; }
void Animal::checkIfStarve() {
this->hp = this->defaultHp * ((double)this->satietyInd / (double)this->maxSatisfaction);
if (this->hp < 1)
this->isAlive = false;
this->satietyInd -= this->energyConsumption;
}
void Animal::aging() {
--this->lifeDuration;
if (!this->lifeDuration)
this->isAlive = false;
}
|
#include <iostream>
#include <ModuleLoader.h>
#include <ModuleFile.h>
#include <Module.h>
int main() {
std::cout << "Hello World from APP1!" << std::endl;
void(*say_hello)();
try {
ModuleLoader loader;
auto module1 = loader.load(ModuleFile::from("libmodule1.dylib"));
auto module2 = loader.load(ModuleFile::from("libmodule2.dylib"));
auto iface1 = module1.getInterface();
auto iface2 = module2.getInterface();
say_hello = (void(*)())(*iface1)("d6017c06-855b-4749-958a-4fbc32e61ed3");
auto say_goodbye = (void(*)())(*iface2)("a8ae62a2-8192-4852-9895-91e3bfbc6eaa");
say_hello();
say_goodbye();
}
catch(const char* ex) {
std::cerr << ex << std::endl;
}
return 0;
}
|
/*
* Created by Peng Qixiang on 2018/4/23.
*/
/*
* 大家都知道斐波那契数列,
* 现在要求输入一个整数n,请你输出斐波那契数列的第n项。
* n <= 39
*
*/
# include <iostream>
# include <vector>
using namespace std;
int FibonacciRecursion(int n) { //效率太低
if(n < 0){
return -1;
}
else if(n <= 1){
return n;
}
else{
return FibonacciRecursion(n-1) + FibonacciRecursion(n-2);
}
}
int Fibonacci(int n){
int f = 0;
int g = 1;
while(n--){
g += f;
f = g - f;
}
return f;
}
int main(){
cout << Fibonacci(5) << endl;
return 0;
}
|
//
// nehe24.cpp
// NeheGL
//
// Created by Andong Li on 10/5/13.
// Copyright (c) 2013 Andong Li. All rights reserved.
//
#include "nehe24.h"
const char* NEHE24::TITLE = "NEHE24";
GLfloat NEHE24::sleepTime = 0.0f;
int NEHE24::frameCounter = 0;
int NEHE24::currentTime = 0;
int NEHE24::lastTime = 0;
char NEHE24::FPSstr[15] = "Calculating...";
int NEHE24::scroll = 0;
int NEHE24::maxtokens = 0;
int NEHE24::swidth = 0;
int NEHE24::sheight = 0;
TextureImage NEHE24::textures[1]; // just for declaration
GLuint NEHE24::base = 0;
bool NEHE24::keys[256] = {}; //all set to false
bool NEHE24::specialKeys[256] = {}; //all set to false
GLvoid NEHE24::ReSizeGLScene(GLsizei width, GLsizei height){
swidth=width; // Set Scissor Width To Window Width
sheight=height; // Set Scissor Height To Window Height
if (height==0) // Prevent A Divide By Zero By
{
height=1;
}
glViewport(0,0,width,height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
glOrtho(0.0f,640,480,0.0f,-1.0f,1.0f); // Create Ortho 640x480 View (0,0 At Top Left)
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity();
}
bool NEHE24::LoadTGA(TextureImage *texture, const char *filename) {
GLubyte TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0}; // Uncompressed TGA Header
GLubyte TGAcompare[12]; // Used To Compare TGA Header
GLubyte header[6]; // First 6 Useful Bytes From The Header
GLuint bytesPerPixel; // Holds Number Of Bytes Per Pixel Used In The TGA File
GLuint imageSize; // Used To Store The Image Size When Setting Aside Ram
GLuint temp; // Temporary Variable
GLuint type=GL_RGBA; // Set The Default GL Mode To RBGA (32 BPP)
FILE *file = fopen(Utils::getAbsoluteDir(filename), "rb"); // Open The TGA File
if( file==NULL || // Does File Even Exist?
fread(TGAcompare,1,sizeof(TGAcompare),file)!=sizeof(TGAcompare) || // Are There 12 Bytes To Read?
memcmp(TGAheader,TGAcompare,sizeof(TGAheader))!=0 || // Does The Header Match What We Want?
fread(header,1,sizeof(header),file)!=sizeof(header)) // If So Read Next 6 Header Bytes
{
if (file == NULL) // Did The File Even Exist? *Added Jim Strong*
return false; // Return False
else
{
fclose(file); // If Anything Failed, Close The File
return false; // Return False
}
}
texture->width = header[1] * 256 + header[0]; // Determine The TGA Width (highbyte*256+lowbyte)
texture->height = header[3] * 256 + header[2]; // Determine The TGA Height (highbyte*256+lowbyte)
if( texture->width <=0 || // Is The Width Less Than Or Equal To Zero
texture->height <=0 || // Is The Height Less Than Or Equal To Zero
(header[4]!=24 && header[4]!=32)) // Is The TGA 24 or 32 Bit?
{
fclose(file); // If Anything Failed, Close The File
return false; // Return False
}
texture->bpp = header[4]; // Grab The TGA's Bits Per Pixel (24 or 32)
bytesPerPixel = texture->bpp/8; // Divide By 8 To Get The Bytes Per Pixel
imageSize = texture->width*texture->height*bytesPerPixel; // Calculate The Memory Required For The TGA Data
texture->imageData=(GLubyte *)malloc(imageSize); // Reserve Memory To Hold The TGA Data
if( texture->imageData==NULL || // Does The Storage Memory Exist?
fread(texture->imageData, 1, imageSize, file)!=imageSize) // Does The Image Size Match The Memory Reserved?
{
if(texture->imageData!=NULL) // Was Image Data Loaded
free(texture->imageData); // If So, Release The Image Data
fclose(file); // Close The File
return false; // Return False
}
for(GLuint i=0; i<int(imageSize); i+=bytesPerPixel) // Loop Through The Image Data
{ // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
temp=texture->imageData[i]; // Temporarily Store The Value At Image Data 'i'
texture->imageData[i] = texture->imageData[i + 2]; // Set The 1st Byte To The Value Of The 3rd Byte
texture->imageData[i + 2] = temp; // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
}
fclose (file); // Close The File
// Build A Texture From The Data
glGenTextures(1, &texture[0].texID); // Generate OpenGL texture IDs
glBindTexture(GL_TEXTURE_2D, texture[0].texID); // Bind Our Texture
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Linear Filtered
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtered
if (texture[0].bpp==24) // Was The TGA 24 Bits
{
type=GL_RGB; // If So Set The 'type' To GL_RGB
}
glTexImage2D(GL_TEXTURE_2D, 0, type, texture[0].width, texture[0].height, 0, type, GL_UNSIGNED_BYTE, texture[0].imageData);
return true;
}
// Build Our Font Display List
GLvoid NEHE24::buildFont(){
base=glGenLists(256); // Creating 256 Display Lists
glBindTexture(GL_TEXTURE_2D, textures[0].texID); // Select Our Font Texture
for (int loop1=0; loop1<256; loop1++) // Loop Through All 256 Lists
{
float cx=float(loop1%16)/16.0f; // X Position Of Current Character
float cy=float(loop1/16)/16.0f; // Y Position Of Current Character
glNewList(base+loop1,GL_COMPILE); // Start Building A List
glBegin(GL_QUADS); // Use A Quad For Each Character
glTexCoord2f(cx,1.0f-cy-0.0625f); // Texture Coord (Bottom Left)
glVertex2d(0,16); // Vertex Coord (Bottom Left)
glTexCoord2f(cx+0.0625f,1.0f-cy-0.0625f); // Texture Coord (Bottom Right)
glVertex2i(16,16); // Vertex Coord (Bottom Right)
glTexCoord2f(cx+0.0625f,1.0f-cy-0.001f); // Texture Coord (Top Right)
glVertex2i(16,0); // Vertex Coord (Top Right)
glTexCoord2f(cx,1.0f-cy-0.001f); // Texture Coord (Top Left)
glVertex2i(0,0); // Vertex Coord (Top Left)
glEnd(); // Done Building Our Quad (Character)
glTranslated(14,0,0); // Move To The Right Of The Character
glEndList(); // Done Building The Display List
} // Loop Until All 256 Are Built
}
// Delete The Font From Memory
GLvoid NEHE24::KillFont(){
glDeleteLists(base,256); // Delete All 256 Display Lists
}
GLvoid NEHE24::glPrint(GLint x, GLint y, int set, const char *fmt, ...){
char text[1024]; // Holds Our String
va_list ap; // Pointer To List Of Arguments
if (fmt == NULL) // If There's No Text
return; // Do Nothing
va_start(ap, fmt); // Parses The String For Variables
vsprintf(text, fmt, ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
if (set>1) // Did User Choose An Invalid Character Set?
{
set=1; // If So, Select Set 1 (Italic)
}
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
glLoadIdentity(); // Reset The Modelview Matrix
glTranslated(x,y,0); // Position The Text (0,0 - Top Left)
glListBase(base-32+(128*set)); // Choose The Font Set (0 or 1)
glScalef(1.0f,2.0f,1.0f); // Make The Text 2X Taller
glCallLists((int)(strlen(text)),GL_UNSIGNED_BYTE, text); // Write The Text To The Screen
glDisable(GL_TEXTURE_2D); // Disable Texture Mapping
}
GLvoid NEHE24::InitGL(){
// Load The Font Texture
if (!LoadTGA(&textures[0],"NeheGL/img/Font.tga")){
cout<<"Fail to load texture"<<endl;
}
buildFont(); // Build The Font
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glBindTexture(GL_TEXTURE_2D, textures[0].texID); // Select Our Font Texture
}
GLvoid NEHE24::DrawGLScene(){
char* token; // Storage For Our Token
int cnt=0; // Local Counter Variable
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0f,0.5f,0.5f); // Set Color To Bright Red
glPrint(10,16,1,"Renderer"); // Display Renderer
glPrint(40,48,1,"Vendor"); // Display Vendor Name
glPrint(26,80,1,"Version"); // Display Version
glColor3f(1.0f,0.7f,0.4f); // Set Color To Orange
glPrint(130,16,1,(char *)glGetString(GL_RENDERER)); // Display Renderer
glPrint(130,48,1,(char *)glGetString(GL_VENDOR)); // Display Vendor Name
glPrint(130,80,1,(char *)glGetString(GL_VERSION)); // Display Version
glColor3f(0.5f,0.5f,1.0f); // Set Color To Bright Blue
glPrint(192,432,1,"NeHe Productions"); // Write NeHe Productions At The Bottom Of The Screen
glLoadIdentity(); // Reset The ModelView Matrix
glColor3f(1.0f,1.0f,1.0f); // Set The Color To White
glBegin(GL_LINE_STRIP); // Start Drawing Line Strips (Something New)
glVertex2d(639,417); // Top Right Of Bottom Box
glVertex2d( 0,417); // Top Left Of Bottom Box
glVertex2d( 0,480); // Lower Left Of Bottom Box
glVertex2d(639,480); // Lower Right Of Bottom Box
glVertex2d(639,128); // Up To Bottom Right Of Top Box
glEnd(); // Done First Line Strip
glBegin(GL_LINE_STRIP); // Start Drawing Another Line Strip
glVertex2d( 0,128); // Bottom Left Of Top Box
glVertex2d(639,128); // Bottom Right Of Top Box
glVertex2d(639, 1); // Top Right Of Top Box
glVertex2d( 0, 1); // Top Left Of Top Box
glVertex2d( 0,417); // Down To Top Left Of Bottom Box
glEnd(); // Done Second Line Strip
glScissor(1 ,int(0.135416f*sheight),swidth-2,int(0.597916f*sheight)); // Define Scissor Region
glEnable(GL_SCISSOR_TEST); // Enable Scissor Testing
char* text=(char*)malloc(strlen((char *)glGetString(GL_EXTENSIONS))+1); // Allocate Memory For Our Extension String
strcpy (text,(char *)glGetString(GL_EXTENSIONS)); // Grab The Extension List, Store In Text
token = strtok(text, " "); // Parse 'text' For Words, Seperated By " " (spaces)
while(token != NULL) // While The Token Isn't NULL
{
cnt++; // Increase The Counter
if(cnt > maxtokens) // Is 'maxtokens' Less Than 'cnt'
maxtokens=cnt; // If So, Set 'maxtokens' Equal To 'cnt'
glColor3f(0.5f, 1.0f, 0.5f); // Set Color To Bright Green
glPrint(0, 96 + (cnt*32) - scroll, 0, "%i", cnt); // Print Current Extension Number
glColor3f(1.0f, 1.0f, 0.5f); // Set Color To Yellow
glPrint(50, 96 + (cnt*32) - scroll, 0, token); // Print The Current Token (Parsed Extension Name)
token = strtok(NULL, " "); // Search For The Next Token
}
glDisable(GL_SCISSOR_TEST); // Disable Scissor Testing
free(text);
//draw FPS text
GLint matrixMode;
glGetIntegerv(GL_MATRIX_MODE, &matrixMode); /* matrix mode? */
glDisable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glPushAttrib(GL_COLOR_BUFFER_BIT); /* save current colour */
glTranslatef(0.0f,0.0f,-1.0f);
glColor3f(0.8f,0.8f,0.8f);//set text color
computeFPS();
Utils::drawText(-0.98f,-0.98f, GLUT_BITMAP_HELVETICA_12, FPSstr);
glPopAttrib();
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(matrixMode);
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glutSwapBuffers();
// handle keyboard input
if (specialKeys[GLUT_KEY_UP] && (scroll>0)){
scroll-=2; // Decrease 'scroll' Moving Screen Down
}
if (specialKeys[GLUT_KEY_DOWN] && (scroll<32*(maxtokens-9)))
{
scroll+=2; // Increase 'scroll' Moving Screen Up
}
}
/*
This function is used to limit FPS for smooth animation
*/
GLvoid NEHE24::UpdateScene(int flag){
clock_t startTime = clock();
glutPostRedisplay();
clock_t endTime = clock();
//compute sleep time in millesecond
float sleepTime = ((CLOCKS_PER_SEC/EXPECT_FPS)-(endTime-startTime))/1000.0;
//sleepTime = floor(sleepTime+0.5);
sleepTime < 0 ? sleepTime = 0 : NULL;
glutTimerFunc(sleepTime, UpdateScene, flag);
}
GLvoid NEHE24::KeyboardFuction(unsigned char key, int x, int y){
keys[key] = true;
}
GLvoid NEHE24::KeyboardUpFuction(unsigned char key, int x, int y){
keys[key] = false;
}
GLvoid NEHE24::KeySpecialFuction(int key, int x, int y){
specialKeys[key] = true;
}
GLvoid NEHE24::KeySpecialUpFuction(int key, int x, int y){
specialKeys[key] = false;
}
void NEHE24::computeFPS(){
frameCounter++;
currentTime=glutGet(GLUT_ELAPSED_TIME);
if (currentTime - lastTime > FPS_UPDATE_CAP) {
sprintf(FPSstr,"FPS: %4.2f",frameCounter*1000.0/(currentTime-lastTime));
lastTime = currentTime;
frameCounter = 0;
}
}
|
#include "StdAfx.h"
#include "StopWatch.h"
StopWatch::StopWatch(void)
{
LARGE_INTEGER performanceFrequency;
QueryPerformanceFrequency(&performanceFrequency);
ticsPerMilliSec = performanceFrequency.QuadPart / 1000;
}
StopWatch::~StopWatch(void)
{
}
void StopWatch::startCounting(void)
{
QueryPerformanceCounter(&startTime);
}
LARGE_INTEGER StopWatch::checkCount(void)
{
QueryPerformanceCounter(¤tTime);
LARGE_INTEGER temp;
temp.QuadPart = (currentTime.QuadPart - startTime.QuadPart)/ticsPerMilliSec;
return temp;
}
|
/*
* cDiInfo - An application to get information via the Windows SetupDi... APIs
* Charles Machalow - MIT License - (C) 2016
* Registry.h - Windows Registry interfacing header file
*/
#pragma once
// Local includes
#include "Strings.h"
// STL includes
#include <string>
// WinApi includes
#include <Windows.h>
// Services folder
#define REGISTRY_SERVICES "SYSTEM\\CurrentControlSet\\Services\\"
namespace cdi
{
namespace registry
{
// Gets a string from a given place in the registry
bool getStringFromRegistry(HKEY hkey, std::string subKey, std::string value, std::string &output);
// Gets a numeric from a given place in the registry
bool getUIntFromRegistry(HKEY hkey, std::string subKey, std::string value, UINT64 &output);
}
}
|
#include "stdafx.h"
#include "CSoftUploadMessage.h"
#include "Markup.h"
#include "CMessageEventMediator.h"
#include "CMessageFactory.h"
#include "databasemanager.h"
CSoftUploadMessage::CSoftUploadMessage(CMessageEventMediator* pMessageEventMediator, QObject *parent)
: CMessage(pMessageEventMediator, parent)
{
m_bAddSuccess = false;
m_strClientInstalledResult = "";
}
CSoftUploadMessage::~CSoftUploadMessage()
{
}
void CSoftUploadMessage::packedSendMessage(NetMessage& netMessage)
{
CMarkup xml;
xml.SetDoc("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
xml.AddElem("Message");
xml.AddChildElem("Header");
xml.IntoElem();
xml.AddAttrib("MsgType", "EMSG_SOFTUPLOAD_RSP");
xml.OutOfElem();
xml.AddChildElem("Result");
xml.IntoElem();
xml.AddAttrib("ErrorCode", 0);
xml.AddAttrib("Value", QString::fromLocal8Bit(m_bAddSuccess ? "添加成功" : "添加失败,XML无法解析").toStdString().c_str());
xml.AddAttrib("CorrsLinkRunState", m_strClientInstalledResult.toStdString().c_str());
xml.OutOfElem();
netMessage.msgBuffer = packXml(&xml);;
netMessage.msgLen = xml.GetDoc().length();
}
bool CSoftUploadMessage::treatMessage(const NetMessage& netMessage, CMessageFactory* pFactory, SocketContext* clientSocket)
{
m_bAddSuccess = false;
m_strClientInstalledResult = "";
CMarkup xml;
if(xml.SetDoc(netMessage.msgBuffer))
{
if(xml.FindChildElem("InfoList"))
{
xml.IntoElem();
QString strId = QString::fromStdString(xml.GetAttrib("Id"));
if(!DataManagerThread->IsSoftInfoExist(strId) && DatabaseManager::Instance()->IsClientExist(strId))
{
DataMotion dataMotion;
dataMotion.msg = netMessage.msgHead;
dataMotion.clientInfo.id = strId;
while(xml.FindChildElem("Software"))
{
xml.IntoElem();
SoftwareInfo softwareInfo;
softwareInfo.name = QString::fromStdString(xml.GetAttrib("Name"));
softwareInfo.version = QString::fromStdString(xml.GetAttrib("Version"));
softwareInfo.category = QString::fromStdString(xml.GetAttrib("Category"));
dataMotion.softwareInfoVector.push_back(softwareInfo);
xml.OutOfElem();
}
xml.OutOfElem();
if(dataMotion.softwareInfoVector.count() > 0)
{
DataManagerThread->AddDataMotion(dataMotion);
}
if(xml.FindChildElem("ExtInfo"))
{
xml.IntoElem();
QString strShopId = QString::fromStdString(xml.GetAttrib("UnitNum"));
QString strClientInstalledResult = QString::fromStdString(xml.GetAttrib("CrosslinkRunInstalledState"));
if(!strShopId.isEmpty())
{
int nMotion = 0; //默认应该是插入2,但是不做插入,只更新
if(DatabaseManager::Instance()->GetCrosslinkRunInstalledResult(strShopId, m_strClientInstalledResult))
{
if(strClientInstalledResult == m_strClientInstalledResult)
{//服务器数据和上报数据一致,不更新
nMotion = 0; //不更新
}
else
{//服务器数据和上报数据不一致,更新
nMotion = 1; //更新
}
}
if(0 != nMotion)
{
DataMotion dataMotion;
dataMotion.msg = EMSG_CROSSRUNINFO;
dataMotion.userInfoMap.insert("UnitNum", QString::fromStdString(xml.GetAttrib("UnitNum")));
dataMotion.userInfoMap.insert("UnitName", QString::fromStdString(xml.GetAttrib("UnitName")));
dataMotion.userInfoMap.insert("CrosslinkRunInstalledState", strClientInstalledResult);
dataMotion.userInfoMap.insert("Motion", QString::fromLocal8Bit("%1").arg(nMotion));
DataManagerThread->AddDataMotion(dataMotion);
}
}
xml.OutOfElem();
}
}
m_bAddSuccess = true;
}
}
if(NULL != pFactory)
{
return pFactory->sendMessage(clientSocket, netMessage.msgHead);
}
return true;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2003 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Morten Stenshorne
*/
#ifndef SELECT_FONT_DIALOG_H
#define SELECT_FONT_DIALOG_H
#include "adjunct/desktop_pi/DesktopColorChooser.h"
#include "adjunct/quick_toolkit/widgets/Dialog.h"
class DesktopWindow;
class FontAtt;
class OpButton;
class OpDropDown;
class OpFontChooserListener;
class OpEdit;
class OpListBox;
class SelectFontDialog : public Dialog, public OpColorChooserListener
{
public:
SelectFontDialog(FontAtt &initial_font, COLORREF initial_color,
BOOL fontname_only, INT32 font_id, OpFontChooserListener *listener);
~SelectFontDialog();
virtual BOOL GetIsBlocking() { return TRUE; }
Type GetType() { return DIALOG_TYPE_SELECT_FONT; }
const char *GetWindowName() { return "Select Font Dialog"; }
const char *GetHelpAnchor() { return "fonts.html"; }
void OnInit();
UINT32 OnOk();
void OnClick(OpWidget *widget, UINT32 id=0);
void OnChange(OpWidget *widget, BOOL changed_by_mouse=FALSE);
BOOL OnInputAction(OpInputAction *action);
void OnColorSelected(COLORREF color);
virtual void UpdateSizes();
void UpdateSample();
private:
int FindNearestSizeIndex(int pixelsize);
int FindFontIndex(const uni_char *fontname);
const uni_char *GetCurrentFont();
BOOL CanChangeColor();
BOOL HasDefaultFont();
BOOL IsDefaultFontSelected();
BOOL GetDefaultFont(FontAtt &font);
protected:
virtual int GetCurrentPixelSize();
OpListBox *mSizeListBox;
struct SizeUserData
{
int pixelsize;
};
private:
struct FontUserData
{
OpString name;
bool default_entry;
};
FontAtt &mInitialFont;
OpFontChooserListener *mFcListener;
OpListBox *mFontListBox;
OpDropDown *mWeightDropDown;
OpButton *mColorButton;
OpCheckBox *mItalicCheckBox;
OpCheckBox *mUnderlineCheckBox;
OpCheckBox *mOverlineCheckBox;
OpCheckBox *mStrikeoutCheckBox;
OpEdit *mSampleEdit;
COLORREF mInitialColor;
BOOL mFontNameOnly;
int mCurFontIx;
int mCurWeightIx;
int mCurSizeIx;
int mLastPixelSizeSelected;
int mWeight;
int mFontId;
};
class SelectCSSFontDialog : public SelectFontDialog
{
public:
SelectCSSFontDialog(FontAtt &initial_font, OpFontChooserListener *listener)
:SelectFontDialog(initial_font,0,TRUE,-1,listener) {}
Type GetType() { return DIALOG_TYPE_SELECT_FONT; }
const char *GetWindowName() { return "Select CSS Font Dialog"; }
};
/** Tweaked Font Dialog to show font sizes from 1-7 (Smallest - Biggest), since that is what DocumentEditable wants
*/
class SelectMailComposeFontDialog : public SelectFontDialog
{
public:
SelectMailComposeFontDialog(FontAtt &initial_font, OpFontChooserListener *listener)
:SelectFontDialog(initial_font,0,FALSE,-1,listener) {}
virtual void UpdateSizes();
virtual int GetCurrentPixelSize();
virtual BOOL GetIsBlocking() { return FALSE; }
};
#endif // SELECT_FONT_DIALOG_H
|
#include<iostream>
using namespace std;
class base{
public:
virtual void fun1(){
cout<<endl<<"In BASE::fun1\n";
}
};
class derived1:public base{
public:
void fun1(){
cout<<endl<<"In DERIVED 1::fun1\n";
}
virtual void fun2(){
cout<<endl<<"In DERIVED 1::fun2\n";
}
};
class derived2:public derived1{
public:
void fun1(){
cout<<endl<<"In DERIVED 222::fun1\n";
}
void fun2(){
cout<<endl<<"In DERIVED 222::fun2\n";
}
};
int main(){
base *ptr1;
derived1 *ptr2;
base b;
derived2 d;
ptr1=&b;
ptr2=&d;
ptr1->fun1();
ptr2->fun1();
((derived1*) ptr2)->fun2();
return 0;
}
|
#ifndef STRAT_GAME_GRAPHICS_HH
#define STRAT_GAME_GRAPHICS_HH
#include "Config.hh"
#include "util/Math.hh"
#include "Sim.hh"
#include "Map.hh"
#include "Input.hh"
#include "opengl/OBJ.hh"
#include "opengl/TextureManager.hh"
#include "opengl/ProgramManager.hh"
#include "opengl/Framebuffer.hh"
#include <entityx/entityx.h>
#include <GL/glew.h>
struct Map;
struct InterpState;
struct RenderShipSystem {
RenderShipSystem(const Input &input,
opengl::TextureManager &textures)
: input(input), textures(textures) {
}
void load();
void render(entityx::EntityManager &entities, const InterpState &);
private:
const Input &input;
opengl::TextureManager &textures;
std::unique_ptr<opengl::OBJ> shipObj;
};
struct DebugRenderPhysicsStateSystem {
DebugRenderPhysicsStateSystem() {
}
void load();
void render(entityx::EntityManager &entities, const InterpState &);
};
struct Graphics {
Graphics(const Config &,
const Input &,
opengl::TextureManager &,
opengl::ProgramManager &);
void load();
void initTerrain(const Map &, const Water &);
void renderShadowMap(entityx::EntityManager &entities, const InterpState &interp);
void setup(const Input::View &);
void render(entityx::EntityManager &entities, const InterpState &);
void debugRender();
void update();
private:
Config config;
const Input &input;
opengl::TextureManager &textures;
opengl::ProgramManager &programs;
RenderShipSystem renderShipSystem;
DebugRenderPhysicsStateSystem debugRenderPhysicsStateSystem;
std::unique_ptr<TerrainMesh> terrain;
opengl::Program *shadowMapProgram;
std::unique_ptr<opengl::Framebuffer> shadowMap;
};
#endif
|
// Tries to place N Queens on an NxN Chessboard without each of them
// being attacked
// ITERATIVE (BRUTE FORCE) METHOD
// Note: no chessboard array is used! N^2 increase in space is not good lol
// Compile with: gcc 8queens.cpp -o queens -lm -O
#include <iostream>
#include <fstream>
#include <cmath>
#include <limits>
using namespace std;
class Queen
{
public:
Queen(){ rowNumber = 0; columnNumber = -1;}
virtual ~Queen(){}
bool MoveQueenRight(){ if(++columnNumber < chessBoardSize) return(true); else {columnNumber = -1; return(false);} }
void ResetQueenToLeft(){ columnNumber = 0; }
int GetRow(){ return(rowNumber); }
int GetColumn(){ return(columnNumber); }
int GetChessBoardSize() { return(chessBoardSize); }
void SetRow(int a){ rowNumber = a; }
void SetColumn(int a){ columnNumber = a; }
void SetChessBoardSize( int a ){ chessBoardSize = a; }
private:
int rowNumber;
int columnNumber;
static int chessBoardSize;
};
int Queen::chessBoardSize = 0;
bool IsQueenAttacked(int row, Queen * &Q);
bool PrintQueenPositionsASCI( Queen * &Q, int solutions );
bool PrintQueenPositionsHTML( Queen * &Q, int solutions, bool TorF );
int main( void )
{
int row = 0, solutions = 0;
Queen *pQ = NULL;
while( true )
{
cout << "\nEnter number of Queens (N):";
cin >> row;
if(!isnan(row) && row > 1){
cout << "\nPositions of " << row << "-Queens on an\n" << row <<"-by-" << row << " chessboard will now be found\n";
break;}
cout << "\nInput error!\nNumber of Queens should be greater than 1\n .. try again!\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
if( (pQ = new Queen[row]) == NULL ){
cout<< "\nCouldnt allocate space for Queens ... exiting programz\n";
exit(0);}
//Initialise Queen positions
pQ[0].SetChessBoardSize( row );
for( row = pQ[0].GetChessBoardSize() ; row > -1; row--)
pQ[row].SetRow(row);
cout << "Chessboard size is " << pQ[0].GetChessBoardSize() <<endl;
cin.ignore();
row = 0; /*Start Queen/row*/
do
{
if( pQ[row].MoveQueenRight() )
{
if( !IsQueenAttacked(row, pQ) )
{
if(row + 1 == pQ[0].GetChessBoardSize())
{
cout << "\nSolution " << ++solutions << " found! ... Writing solution";
PrintQueenPositionsASCI(pQ, solutions);
PrintQueenPositionsHTML( pQ, solutions, true);
cout << " .. continuing search ..";
}
else
row++;
}
continue;
}
else
row--;
} while( pQ[0].GetColumn() > -1 );
if( solutions > 0)
PrintQueenPositionsHTML( pQ, solutions, false);
cout << "\nTotal of " << solutions << " solutions found.\n";
delete[] pQ;
return(0);
}
// Every Queen is positioned off the board initially
// Results to be printed in HTML file
bool IsQueenAttacked(int row, Queen * &Q)
{
//Check if Queen Q[row] is in the same column or diagonal as previous queens
if( Q != NULL )
for( int i = row - 1; i > -1; --i )
if( Q[row].GetColumn() == Q[i].GetColumn() || ( abs(Q[row].GetColumn() - Q[i].GetColumn()) == abs(Q[row].GetRow() - Q[i].GetRow())) )
return(true); //Queen is attacked
return(false);
}
bool PrintQueenPositionsASCI( Queen * &Q, int solutions )
{
int row = 0, column = 0, n = 0, colPosition = 0;
ofstream fileQueens;
if( Q != NULL)
{
if( solutions == 1)
fileQueens.open("queen_positions.txt", ios::out);
else
fileQueens.open("queen_positions.txt", ios::app);
if( fileQueens.is_open() )
{
if( solutions == 1)
fileQueens << Q[0].GetChessBoardSize() << " Queens on an " << Q[0].GetChessBoardSize() <<" by " << Q[0].GetChessBoardSize() << " chessboard.\n" <<
"Reflected and rotationally-symmetric solutions are included below.\n";
fileQueens << "\nSolution " << solutions << "\n";
for( n = Q[0].GetChessBoardSize(), row = 0; row < n ; row++ )
fileQueens << " _";
fileQueens << "\n";
for( row = 0; row < n; row++)
{
colPosition = Q[row].GetColumn();
for(column = 0; column < n; column++)
{
if( colPosition == column )
fileQueens << "|Q";
else
fileQueens << "|_";
}
fileQueens << "|\n";
}
fileQueens << "\n\n";
fileQueens.close();
}
return(true);
}
return(false);
}
bool PrintQueenPositionsHTML( Queen * &Q, int solutions, bool TorF )
{
int row = 0, column = 0, n = 0, colPosition = 0;
ofstream fileQueens;
if( Q != NULL && TorF == true)
{
if( solutions == 1)
fileQueens.open("queen_positions.html", ios::out);
else
fileQueens.open("queen_positions.html", ios::app);
if( fileQueens.is_open() )
{
if( solutions == 1)
{
fileQueens << "<html>\n<head>\n<style type =\"text/css\">";
fileQueens << "\ntable {bordercolor=\"#111111\"; padding: 3; spacing: 1; font: 16 Georgia; color: #FF0000; font-weight: bold; }";
fileQueens << "\nBODY {text-align: left; font-size: 20}";
fileQueens << "\ntd {width: 17; text-align: center; vertical-align:middle}";
fileQueens << "\nh3{color: blue}";
fileQueens << "\np{font-size:15; color: #CC0066}";
fileQueens << "\n.bk{background-color: #C0C0C0; text-align: center}";
fileQueens << "\n</style>\n</head>\n<body>\n";
fileQueens << "<p>" << Q[0].GetChessBoardSize() << " Queens on an " << Q[0].GetChessBoardSize() <<" by " << Q[0].GetChessBoardSize() << " chessboard.<br>\n" <<
"Reflected and rotationally-symmetric solutions are included below.</p>\n";
}
fileQueens << "\n<h3>Solution "<< solutions << "</h3>\n<table border = \"4\">\n";
n = Q[0].GetChessBoardSize();
for( row = 0; row < n; row++)
{
colPosition = Q[row].GetColumn();
fileQueens << "<tr>\n";
for(column = 0; column < n; column++)
{
fileQueens << "<td";
if( (row + column)%2 == 0 ) //Colour the chessbaord
fileQueens << " class=\"bk\">";
else
fileQueens << ">";
if( colPosition == column )
fileQueens << "Q";
else
fileQueens << " ";
fileQueens << "</td>\n";
}
fileQueens << "</tr>\n";
}
fileQueens << "</table>\n<br>\n";
fileQueens.close();
}
return(true);
}
else
if( !TorF )
{
fileQueens.open("queen_positions.html", ios::app);
if( fileQueens.is_open() )
{
fileQueens << "\n</body>\n</html>\n\n";
fileQueens.close();
return(true);
}
}
return(false);
}
|
//====================================================================================
// @Title: CURSOR
//------------------------------------------------------------------------------------
// @Location: /prolix/interface/include/cCursor.cpp
// @Author: Kevin Chen
// @Rights: Copyright(c) 2011 Visionary Games
//====================================================================================
#include "../include/cCursor.h"
#include "../../engine/include/PrlxEngine.h"
#include "../../engine/include/PrlxGraphics.h"
#include "../../framework/include/cAssetMgr.h"
//====================================================================================
// cCursor
//====================================================================================
cCursor::cCursor()
{
// hide default system Cursor
SDL_ShowCursor(SDL_DISABLE);
mImage = AssetMgr->Load<Texture>("cursor.png");
// set initial position
pos = Point(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
// set pointer size
size = 1;
// set pointer bounding box
coll_rect.dim.w = size;
coll_rect.dim.h = size;
}
void cCursor::Move()
{
pos = Engine->Input->Mouse->pos;
coll_rect.pos = pos;
}
void cCursor::Update()
{
Move();
Draw();
}
void cCursor::Draw()
{
mImage->Draw(pos);
}
cCursor::~cCursor()
{
SDL_ShowCursor(SDL_ENABLE);
}
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/NavBarLogo.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IResize.h>
#include <Fuse.Binding.h>
#include <Fuse.Controls.Image.h>
#include <Fuse.IActualPlacement.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.ITemplateSource.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.Actions.ICollapse.h>
#include <Fuse.Triggers.Actions.IHide.h>
#include <Fuse.Triggers.Actions.IShow.h>
#include <Fuse.Visual.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.UX.IPropertyListener.h>
namespace g{struct NavBarLogo;}
namespace g{
// public partial sealed class NavBarLogo :2
// {
::g::Fuse::Controls::Control_type* NavBarLogo_typeof();
void NavBarLogo__ctor_7_fn(NavBarLogo* __this);
void NavBarLogo__InitializeUX_fn(NavBarLogo* __this);
void NavBarLogo__New4_fn(NavBarLogo** __retval);
struct NavBarLogo : ::g::Fuse::Controls::Image
{
void ctor_7();
void InitializeUX();
static NavBarLogo* New4();
};
// }
} // ::g
|
// List of script functions allowed to be sent from client via remoteExec
class Functions
{
// RemoteExec modes:
// 0- turned off
// 1- turned on, taking whitelist into account
// 2- turned on, ignoring whitelist (default, because of backward compatibility)
mode = 2;
// Ability to send jip messages: 0-disabled, 1-enabled (default)
jip = 1;
// your functions here
class AIDC_fnc_init
{
allowedTargets = 0; // can target anyone (default)
jip = 0; // sending JIP messages is disabled for this function (overrides settings in the Functions class)
};
};
|
#include "Matrix.h"
#include <string>
const string CANNOT_OPEN = "Не удалось открыть";
const string FOR_READING = "для чтения";
optional<vector<double>> ReadNumbers(const string& fileName)
{
// переделал на copy
vector<double> numbers;
ifstream file(fileName);
if (!file.is_open())
{
cout << CANNOT_OPEN << " " << fileName << " " << FOR_READING << endl;;
return nullopt;
}
copy(istream_iterator<double>(file), istream_iterator<double>(), back_inserter(numbers));
return numbers;
}
void CalculateNumbers(vector<double>& numbers)
{
// переделал на transform
if (numbers.empty()) return;
auto minElRef = min_element(numbers.begin(), numbers.end());
double min = *minElRef;
transform(numbers.begin(), numbers.end(), numbers.begin(), [&](double n) {return n * min; });
}
string ShowNumbers(vector<double>& numbers)
{
sort(numbers.begin(), numbers.end());
ostringstream streamObj;
streamObj << fixed << setprecision(3);
for (unsigned i = 0; i < numbers.size(); i++)
{
if (i != 0)
{
streamObj << " ";
}
streamObj << numbers[i];
}
return streamObj.str();
}
string MakeCalculation(const string& fileName)
{
auto numbers = ReadNumbers(fileName);
if (!numbers || numbers && numbers.value().empty())
{
return "";
}
CalculateNumbers(numbers.value());
string result = ShowNumbers(numbers.value());
return result;
}
|
class FirstCommonNode {
public:
ListNode* walkNStep(ListNode* p, int k) {
ListNode* cur = p;
while (cur != nullptr && k--) {
cur = cur->next;
}
return cur;
}
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == nullptr || pHead2 == nullptr) {
return nullptr;
}
ListNode* p1 = pHead1;
ListNode* p2 = pHead2;
int l1 = 0;
int l2 = 0;
while (p1 != nullptr && ++l1) p1 = p1->next;
while (p2 != nullptr && ++l2) p2 = p2->next;
p1 = pHead1, p2 = pHead2;
if (l1 > l2) {
p1 = walkNStep(p1, l1 - l2);
}
else { // l2 > l1
p2 = walkNStep(p2, l2 - l1);
}
while (p1 != nullptr) {
if (p1 == p2) return p1;
p1 = p1->next;
p2 = p2->next;
}
return nullptr;
}
void test() {
ListNode* h1 = getList({ 1, 2, 3 });
ListNode* h2 = getList({ 2, 12, 3, 4 });
cout << FindFirstCommonNode(h1, h2) << endl;
h1 = getList({ 1 });
h2 = getList({ 1 });
cout << FindFirstCommonNode(h1, h2) << endl;
h1 = getList({ });
h2 = getList({ });
cout << FindFirstCommonNode(h1, h2) << endl;
h1 = getList({ 1, 34, 2, 7, 8 });
h2 = getList({ 12, 5, 6, 3, 8 });
cout << FindFirstCommonNode(h1, h2) << endl;
h1 = getList({ 12, 4, 2, 7 });
h2 = getList({ 3, 9, 14, 22 });
cout << FindFirstCommonNode(h1, h2) << endl;
}
};
|
#include <vector>
#include <string>
namespace gb_util {
std::vector<std::string> split(const std::string& s, char delim);
std::string get_console_line(void);
unsigned short stous(std::string const &str, size_t *idx = 0, int base = 10);
}
|
// Файл util.h с реализацией вспомогатеьлных утилит
#include "util.h"
// Запись строки символов в указанный файл
void str2file(std::string &str, std::string fileName) {
std::ofstream out; // поток для записи
out.open(fileName); // окрываем файл для записи
if (out.is_open()) {
out << str;
}
}
// Чтение из файла в вектор строк
void file2vector(std::string fileName, std::vector<std::string> &text) {
std::ifstream in; // поток для xntybz
in.open(fileName); // окрываем файл для записи
std::string line;
if (in.is_open()) {
while (getline(in, line)) {
text.push_back(line);
}
}
}
// Формирование строк для файла с глобальными объектами
// Пока формируется только для одной единицы компиляции
// В дальнейшем нужно будет собирать множество разных файлов с одинаковыми расширениями.
void createGlobal(std::vector<std::string> &text) {
// Создается заголовок, определяющий глобальный объект
text.push_back(
"+package c2eo\n\n"
"+alias varint c2eo.varInt\n"
"+alias varfloat c2eo.varFloat\n\n"
"+alias sprintf org.eolang.txt.sprintf\n"
"+alias stdout org.eolang.io.stdout\n\n"
"[arg] > global\n"
);
// Читаются сформированные глобальные объекты
file2vector("glob.global", text);
#ifdef _DEBUG
file2vector("glob.debug", text);
#endif
// Формируется начало последовательности инициализаций
text.push_back(" seq > @");
// Читаются инициализации объектов
file2vector("glob.seq", text);
}
// Запись сформированного файла с глобальными объектами
void text2file(std::vector<std::string> &text, std::string fileName) {
std::ofstream out; // поток для записи
out.open(fileName); // окрываем файл для записи
if (out.is_open()) {
for(auto line: text) {
if (!line.empty())
out << line << "\n";
}
}
}
|
/*******************
첫번째 시도 : 시간 초과
두번째 시도 : 통과
********************/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> v_b, v_t, vResult;
int main(void)
{
int N, H;
int tempA, tempB;
cin >> N >> H;
for (int i = 0; i < N / 2; i++)
{
cin >> tempA >> tempB;
v_b.push_back(H - tempA);
v_t.push_back(tempB);
}
sort(v_b.begin(), v_b.end());
sort(v_t.begin(), v_t.end());
for (int i = 1; i <= H; i++)
{
int nCnt = 0;
vector<int>::iterator low = lower_bound(v_b.begin(), v_b.end(), i);
nCnt = low - v_b.begin();
vector<int>::iterator high = lower_bound(v_t.begin(), v_t.end(), i);
nCnt += v_t.size() - (high - v_t.begin());
vResult.push_back(nCnt);
}
sort(vResult.begin(), vResult.end());
int nResult = 1;
for (int i = 1; i < vResult.size(); i++)
{
if (vResult[0] == vResult[i])
{
nResult++;
}
}
printf("%d %d\n", vResult[0], nResult);
return 0;
}
|
//
// Created by Yujing Shen on 29/05/2017.
//
#include "../../include/nodes/ReluNode.h"
namespace sjtu{
ReluNode::ReluNode(Session *sess, const Shape &shape) :
SessionNode(sess, shape)
{
}
ReluNode::~ReluNode()
{
}
Node ReluNode::forward()
{
const Tensor X = _port_in[0]->get_data();
Tensor Y = _data;
if(!X->check_shape(Y))
throw ShapeNotMatchException();
int count = X->get_count();
for (int i = 0; i < count; ++i){
(*Y)(i) = (*X)(i) > 0 ? (*X)(i) : 0;
}
return this;
}
Node ReluNode::backward()
{
Tensor dX = _port_in[0]->get_diff();
const Tensor X = _port_in[0]->get_data();
const Tensor dY = _diff;
int counts = dX->get_count();
for(int i = 0; i < counts; ++i)
{
(*dX)(i) += (*X)(i) > 0 ? (*dY)(i) : 0;
}
return this;
}
Node ReluNode::optimize()
{
return this;
}
}
|
// ---------------------------------------------------------------------------
#ifndef ReaderH
#define ReaderH
// ---------------------------------------------------------------------------
class Reader {
public:
char readerName[20];
int readerID;
char addres[20];
char phone[20];
};
#endif
|
/************************************************************************/
/* 两个字符串A、B。从A中剔除存在于B中的字符。比如A=“hello world”,B="er",
* 那么剔除之后A变为"hllowold"。空间复杂度要求是O(1),时间复杂度越优越好。*/
/************************************************************************/
#include <string>
#include <bitset>
using namespace std;
class Solution{
public:
void DelCommanChar(string &str1, const string &str2){
bitset<128> record;
for(int i = 0; i < str1.size(); ++i){
record.set(int(str1[i]));
}
for(int i = 0; i < str2.size(); ++i){
record.reset(int(str2[i]));
}
for(int i = 0; i < str1.size();){
if(!record.test( int(str1[i]) )){
str1.erase(i, 1);
}
else{
++i;
}
}
}
};
//int main(){
// string str1("nihaolintong");
// string str2("nidaetada");
// Solution solution;
// solution.DelCommanChar(str1, str2);
// return 0;
//}
|
#include "helpers.h"
double sq(double x)
{
return x*x;
}
int clas_sector(double phi_deg)
{
while (phi_deg < -30.)
phi_deg+=360.;
while (phi_deg > 330.)
phi_deg-=360.;
int sec = (phi_deg+30.)/60.;
return sec;
}
|
// Copyright 2011 Yandex
#ifndef LTR_SCORERS_SCORER_H_
#define LTR_SCORERS_SCORER_H_
#include <boost/lexical_cast.hpp>
#include <vector>
#include <string>
#include "ltr/interfaces/aliaser.h"
#include "ltr/data/object.h"
#include "ltr/feature_converters/feature_converter.h"
#include "ltr/interfaces/serializable_functor.h"
#include "ltr/interfaces/printable.h"
#include "ltr/utility/shared_ptr.h"
using std::string;
namespace ltr {
/*
* Scorer is a class that can for every object evaluate
* a value - its rank, or score
*/
class Scorer : public SerializableFunctor<double>,
public Printable,
public Aliaser {
public:
typedef ltr::utility::shared_ptr<Scorer> Ptr;
typedef ltr::utility::shared_ptr<Scorer> BasePtr;
Scorer(const FeatureConverterArray&
feature_converters = FeatureConverterArray()):
feature_converters_(feature_converters) {}
double value(const Object& object) const {
return score(object);
}
double score(const Object& object) const;
const FeatureConverterArray& feature_converters() const {
return feature_converters_;
}
void set_feature_converters(const FeatureConverterArray& feature_converters) {
this->feature_converters_ = feature_converters;
}
void addFeatureConverter(
FeatureConverter::Ptr p_feature_converter) {
this->feature_converters_.push_back(p_feature_converter);
}
using SerializableFunctor<double>::generateCppCode;
string generateCppCode(const string& function_name) const {
if (feature_converters_.size() == 0)
return generateCppCodeImpl(function_name);
string code;
string implFunctionName(function_name);
implFunctionName.append("Impl");
code.append(generateCppCodeImpl(implFunctionName));
for (size_t featureConverterIdx = 0;
featureConverterIdx < feature_converters_.size();
++featureConverterIdx) {
code.append(feature_converters_.at(
featureConverterIdx)->generateCppCode());
}
code.append("double ");
code.append(function_name);
code.append("(const std::vector<double>& feature) {\n");
string prevVectorName("feature");
for (size_t featureConverterIdx = 0;
featureConverterIdx < feature_converters_.size();
++featureConverterIdx) {
string curVectorName = "feature" +
boost::lexical_cast<string>(featureConverterIdx);
string featureConverterFunctionName(feature_converters_.at(
featureConverterIdx)->getDefaultSerializableObjectName());
code.append(" std::vector<double> ");
code.append(curVectorName);
code.append(";\n ");
code.append(featureConverterFunctionName);
code.append("(");
code.append(prevVectorName);
code.append(", &");
code.append(curVectorName);
code.append(");\n");
prevVectorName = curVectorName;
}
code.append(" return ");
code.append(implFunctionName);
code.append("(");
code.append(prevVectorName);
code.append(");\n");
code.append("}\n");
return code;
}
template <class TElement>
void predict(const DataSet<TElement>& elements) const;
template <class TElement>
void predict(const TElement& element) const;
string generateLocalClassName(size_t index) const;
virtual ~Scorer() {}
private:
virtual double scoreImpl(const Object& obj) const = 0;
virtual string generateCppCodeImpl(const string& function_name) const = 0;
FeatureConverterArray feature_converters_;
};
}
#endif // LTR_SCORERS_SCORER_H_
|
#ifndef TREEFACE_SCENE_H
#define TREEFACE_SCENE_H
#include "treeface/base/Common.h"
#include "treeface/math/Vec4.h"
#include <treecore/RefCountObject.h>
#include <treecore/RefCountHolder.h>
namespace treecore {
class Result;
class var;
} // namespace treecore
namespace treeface {
class GeometryManager;
class MaterialManager;
class SceneNode;
class SceneNodeManager;
class SceneRenderer;
class Scene: public treecore::RefCountObject
{
friend class SceneRenderer;
public:
Scene( GeometryManager* geo_mgr = nullptr, MaterialManager* mat_mgr = nullptr );
Scene( const treecore::var& root, GeometryManager* geo_mgr = nullptr, MaterialManager* mat_mgr = nullptr );
Scene( const treecore::String& data_name, GeometryManager* geo_mgr = nullptr, MaterialManager* mat_mgr = nullptr );
TREECORE_DECLARE_NON_COPYABLE( Scene )
TREECORE_DECLARE_NON_MOVABLE( Scene )
virtual ~Scene();
/**
* @brief get the root of the scene hierarchy
*
* All nodes in the scene are added to this node. Do not modify the
* transform matrix of this node.
*
* @return root node object.
*/
SceneNode* get_root_node() noexcept;
/**
* @brief get node by name
* @param name: node name.
* @return If has node object with name, return node object; otherwise
* return nullptr.
*/
SceneNode* get_node( const treecore::String& name ) noexcept;
GeometryManager* get_geometry_manager() noexcept;
MaterialManager* get_material_manager() noexcept;
const Vec4f& get_global_light_color() const noexcept;
void set_global_light_color( float r, float g, float b, float a ) noexcept;
void set_global_light_color( const Vec4f& value ) noexcept;
const Vec4f& get_global_light_direction() const noexcept;
void set_global_light_direction( float x, float y, float z ) noexcept;
void set_global_light_direction( const Vec4f& value ) noexcept;
const Vec4f& get_global_light_ambient() const noexcept;
void set_global_light_ambient( float r, float g, float b, float a ) noexcept;
void set_global_light_ambient( const Vec4f& value ) noexcept;
private:
void build( const treecore::var& root );
struct Guts;
Guts* m_guts = nullptr;
};
} // namespace treeface
#endif // TREEFACE_SCENE_H
|
/*
* Copyright (c) 2016, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Author: Erik Nelson ( eanelson@eecs.berkeley.edu )
*/
#include <lens/lens_collision.h>
#include <raytracing/path.h>
#include <raytracing/ray.h>
#include <iostream>
#include <limits>
Ray::Ray() {}
Ray::Ray(const glm::vec3& origin, const glm::vec3& direction)
: origin_(origin), direction_(direction) {
NormalizeDirection();
}
Ray::Ray(double ox, double oy, double oz, double dx, double dy, double dz) {
origin_ = glm::vec3(ox, oy, oz);
direction_ = glm::vec3(dx, dy, dz);
NormalizeDirection();
}
Ray::~Ray() {}
Path Ray::Trace(const std::vector<Lens>& lenses) const {
Path path;
Ray ray = *this;
// Get collisions between this ray and all lenses in the scene.
bool collisions_remain = true;
while (collisions_remain) {
// Check for collisions with all lenses.
LensCollision nearest_collision;
double min_distance = std::numeric_limits<double>::infinity();
bool collision_found = false;
for (size_t ii = 0; ii < lenses.size(); ++ii) {
LensCollision collision;
if (collision.Compute(ray, lenses[ii])) {
collision_found = true;
// Check if this collision was the minimum distance collision.
if (collision.GetIncomingDistance() < min_distance) {
min_distance = collision.GetIncomingDistance();
nearest_collision = collision;
}
}
}
if (collision_found) {
// If we found a collision, add both the incoming and internal rays to the
// path, then update the outgoing ray so we can check for more collisions.
path.AddRay(nearest_collision.GetIncomingRay());
path.AddRay(nearest_collision.GetInternalRay());
ray = nearest_collision.GetOutgoingRay();
} else {
// If no more collisions exist, store the final ray and exit the loop
path.AddRay(ray);
collisions_remain = false;
}
}
return path;
}
const glm::vec3& Ray::GetOrigin() const {
return origin_;
}
const glm::vec3& Ray::GetDirection() const {
return direction_;
}
double Ray::GetOriginX() const {
return origin_.x;
}
double Ray::GetOriginY() const {
return origin_.y;
}
double Ray::GetOriginZ() const {
return origin_.z;
}
double Ray::GetDirectionX() const {
return direction_.x;
}
double Ray::GetDirectionY() const {
return direction_.y;
}
double Ray::GetDirectionZ() const {
return direction_.z;
}
void Ray::SetOrigin(const glm::vec3& origin) {
origin_ = origin;
}
void Ray::SetDirection(const glm::vec3& direction) {
direction_ = direction;
NormalizeDirection();
}
void Ray::SetOriginX(double x) {
origin_.x = x;
}
void Ray::SetOriginY(double y) {
origin_.y = y;
}
void Ray::SetOriginZ(double z) {
origin_.z = z;
}
void Ray::SetDirectionX(double x) {
direction_.x = x;
}
void Ray::SetDirectionY(double y) {
direction_.y = y;
}
void Ray::SetDirectionZ(double z) {
direction_.z = z;
}
void Ray::NormalizeDirection() {
direction_ = glm::normalize(direction_);
}
void Ray::Print(const std::string& prefix) const {
if (!prefix.empty())
std::cout << prefix << std::endl;
std::cout << "origin: ("
<< origin_.x << ", "
<< origin_.y << ", "
<< origin_.z << ")" << std::endl
<< "direction: ("
<< direction_.x << ", "
<< direction_.y << ", "
<< direction_.z << ")" << std::endl << std::endl;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.